@brandbrigade/ott-bb-player 1.0.69 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +126 -270
- package/dist/OTTPlayer.js +13 -13
- package/package.json +3 -4
package/dist/OTTPlayer.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
(function(ie,me){typeof exports=="object"&&typeof module<"u"?module.exports=me():typeof define=="function"&&define.amd?define(me):(ie=typeof globalThis<"u"?globalThis:ie||self,ie.OTTPlayer=me())})(this,function(){"use strict";const ie=t=>Math.abs(t-59.94005994005994)<20?59.94:Math.abs(t-29.97002997002997)<10?29.97:Math.abs(t-14.985014985014985)<8?14.98:0,me=t=>t>30&&t<70?59.94005994005994:t>15?29.97002997002997:t>7?14.985014985014985:0;class nt{constructor(e){this.frameDurations=[],this.frameDurationsCapacity=e,this.lastTimestamp=null}addFrameDuration(e){return this.frameDurations.push(e),this.frameDurations.length>this.frameDurationsCapacity&&this.frameDurations.shift(),this.calculateAverage()}addTimestamp(e){if(this.lastTimestamp===null)return this.lastTimestamp=e,null;const r=e-this.lastTimestamp;return this.lastTimestamp=e,this.addFrameDuration(r)}calculateAverage(){if(this.frameDurations.length===0)return 0;const r=this.frameDurations.reduce((o,a)=>o+a,0)/this.frameDurations.length,n=this.frameDurations.filter(o=>Math.abs(o-r)<=r*.2);return n.reduce((o,a)=>o+a,0)/n.length||r}getFPS(){const e=this.calculateAverage();if(e===0)return 0;const r=1/e;return me(r)}getPerciseFPS(){const e=this.calculateAverage();return e===0?0:1/e}}const U=class U{constructor(e,r,n,s,i){this.copy=()=>new U(this.h,this.m,this.s,this.f,this.field),this.print=()=>{const o=":";let a=("0"+this.h).slice(-2)+o+("0"+this.m).slice(-2)+o+("0"+this.s).slice(-2)+o+("0"+this.f).slice(-2);return a+="."+(this.field?"1":"2"),a},this.toZipTimeCodeString=()=>{const o=this.copy();return o.f=0,o.s=o.s%2===0?o.s:o.s-1,o.field=0,U.toStr(o)},this.toFrames=o=>{let a=60,c=0;Math.floor(o)==60?(a=60,c=0):Math.floor(o)==59?(a=60,c=4):Math.floor(o)==30?(a=30,c=0):Math.floor(o)==29&&(a=30,c=2);let d=this.h,l=this.m,u=this.s,f=this.f,p=this.field;const h=d*60+l,g=(h-Math.floor(h/10))*c;return d*(a*3600)+l*(a*60)+u*a+(f*2+p)-g},this.addSeconds=o=>{let a=this.copy();if(a.s+=o,a.s>=60){const c=Math.floor(a.s/60);if(a.s=a.s%60,a.m+=c,a.m>=60){const d=Math.floor(a.m/60);a.m=a.m%60,a.h+=d}}return a},this.addFrames=(o,a)=>{let c=this.toFrames(a);return c+=o,U.fromFrames(c,a)},this.subtractFrames=(o,a)=>this.addFrames(-o,a),this.h=e||0,this.m=r||0,this.s=n||0,this.f=s||0,this.field=i||0}static compare(e,r){return e.h!==r.h?e.h<r.h?-1:1:e.m!==r.m?e.m<r.m?-1:1:e.s!==r.s?e.s<r.s?-1:1:e.f!==r.f?e.f<r.f?-1:1:e.field!==r.field?e.field<r.field?-1:1:0}static generateTimecodeRange(e,r,n){const s=[];let i=e;for(;U.compare(i,r)<=0;)s.push(i),i=i.addSeconds(n);return s}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(e){return this.toFrames(e)*1e3/e}};U.calculateCurrentTimeCode=e=>{var u;if(!e.video||!e.clocker||!e.gameParams)throw new Error("OTTPlayer is not initialized");const r=e.video,n=e.clocker,s=n.videoFPScalculator.getFPS(),a=(r.currentTime-n.syncPoint.playerTime)%(60*60*24)*s+n.syncPoint.frame;if(a===0||s===0)throw new Error("Current frame is 0 or fps is 0");const c=U.calculateCurrentOffset(a,(u=e.gameParams)==null?void 0:u.offsets);if(c===void 0)throw new Error("Offset is undefined");let d=Math.floor(a-c);return d<0&&(d+=5178816),d>=5178816&&(d-=5178816),U.fromFrames(d,s)},U.calculateCurrentOffset=(e,r)=>{for(let n=1;n<r.length;n++)if(e<r[n].frame)return r[n-1].offset;return Math.abs(r[r.length-1].offset)},U.fromFrames=(e,r)=>{let n=60,s=0;Math.floor(r)==60?(n=60,s=0):Math.floor(r)==59?(n=60,s=4):Math.floor(r)==30?(n=30,s=0):Math.floor(r)==29&&(n=30,s=2);let i=Math.floor(r*60),o=Math.floor(r*60*10),a=o*6,c=e,d=Math.floor(c/a);c-=d*a;let l=Math.floor(c/o);c-=l*o,c>=n*60&&(c+=s*(Math.floor((c-n*60)/i)+1));let u=Math.floor(c/(n*60));c-=u*(n*60);let f=Math.floor(c/n);c-=f*n;let p=c;u+=l*10;let h=0;return h=p%2,p=Math.floor(p/2),new U(d,u,f,p,h)},U.toStr=e=>{const r="_";let n=("0"+e.h).slice(-2)+r+("0"+e.m).slice(-2)+r+("0"+e.s).slice(-2)+r+("0"+e.f).slice(-2);return e.field&&(n+="_1"),n},U.fromStr=e=>{const n=e.split("_").map(Number);if(n.length==4){const[s,i,o,a]=n;return new U(s,i,o,a,0)}else if(n.length==5){const[s,i,o,a,c]=n;return new U(s,i,o,a,c)}else throw new Error("Invalid timecode format: "+e)},U.fromMetadata=e=>{const r=/^(\d{2}):(\d{2}):(\d{2}):(\d{2})(?:\.(\d))?$/,n=e.timecode.match(r);if(!n)throw new Error("Invalid timecode format: "+e.timecode);const[,s,i,o,a,c]=n,d=Number(s),l=Number(i),u=Number(o),f=Number(a),p=c?Number(c):0;return new U(d,l,u,f,p)};let L=U;const tn=async(t,e)=>{e&&Object.assign(t,e);let r;typeof document>"u"?r=new URL(self.location.href):r=new URL(document.location.href);const n=r.searchParams.get("config");if(n){let s;if(rn(n))s=await(await fetch(n)).json();else try{s=JSON.parse(decodeURIComponent(n))}catch(i){console.error("Failed to parse config parameter as JSON:",i);return}Object.assign(t,s)}},rn=t=>{try{return new URL(t),!0}catch{return!1}},_=(t,e)=>e==="Errors"?!0:!t.debug||!t.debug.on?!1:t.debug[`log${e}`];class nn{constructor(e){this.last10=[],this.errorsInProgress=[],this.lastFrameTC=null,this.fps=e}setFPS(e){this.fps=e}timecodeRecieved(e){if(!e)return;const r=L.fromStr(e);if(this.last10.push(r),this.last10.length>10&&this.last10.shift(),this.lastFrameTC){const n=this.incrementInterlaced(this.lastFrameTC);L.compare(r,n)!==0&&(console.warn("Timecode sequence is invalid! Detected at:",e),this.errorsInProgress.push({preTCs:[...this.last10],postTCs:[],framesAfter:0,printed:!1}))}for(const n of this.errorsInProgress)n.printed||(n.postTCs.push(r),n.framesAfter++);for(const n of this.errorsInProgress)if(!n.printed&&n.framesAfter>=10){console.error("Full 20-frame sequence around error:");const s=[...n.preTCs,...n.postTCs];console.error(s.map(i=>L.toStr(i))),n.printed=!0}this.lastFrameTC=r}incrementInterlaced(e){const r=e.copy();return r.field===0?(r.field=1,r):(r.field=0,r.f++,r.f>=30&&(r.f=0,r.s++,r.s>=60&&(r.s=0,r.m++,r.m>=60&&(r.m=0,r.h++))),r)}}class sn{constructor(e,r){this.click=async n=>{const s=this.video.getBoundingClientRect(),i=(n.clientX-s.left)/s.width,o=(n.clientY-s.top)/s.height,a={x:i,y:o};this.renderer.postMessage({type:"VIDEO_CLICK",clickData:a})},this.video=e.video,this.logger=e.logger,this.renderer=r,this.renderer.onmessage=n=>{if(n.data.type==="OPEN_URL"){const s=n.data.url;s&&(window.open(s,"_blank"),this.logger.info("didClickAd",{url:s}))}}}}const Bt='(function(){"use strict";const w=(e,t)=>t==="Errors"?!0:!e.debug||!e.debug.on?!1:e.debug[`log${t}`],T={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},x=console,W={};Object.keys(T).forEach(e=>{W[e]=x[e]});const fe="Datadog Browser SDK:",_={debug:W.debug.bind(x,fe),log:W.log.bind(x,fe),info:W.info.bind(x,fe),warn:W.warn.bind(x,fe),error:W.error.bind(x,fe)},Xe="https://docs.datadoghq.com",vt=`${Xe}/real_user_monitoring/browser/troubleshooting`,Re="More details:";function Lt(e,t){return(...n)=>{try{return e(...n)}catch(r){_.error(t,r)}}}function Ce(e){return e!==0&&Math.random()*100<=e}function Fn(e){return Un(e)&&e>=0&&e<=100}function Un(e){return typeof e=="number"}const pe=1e3,K=60*pe,It=60*K,Bn=365*(24*It);function he(){return new Date().getTime()}function F(){return he()}function ve(){return performance.now()}function U(){return{relative:ve(),timeStamp:F()}}function Gn(){return{relative:0,timeStamp:At()}}function jn(e,t){return t-e}function Hn(e,t){return e+t}function zn(e){return e-At()}let Ve;function At(){return Ve===void 0&&(Ve=performance.timing.navigationStart),Ve}const D=1024,kt=1024*D,Wn=/[^\\u0000-\\u007F]/;function Qe(e){return Wn.test(e)?window.TextEncoder!==void 0?new TextEncoder().encode(e).length:new Blob([e]).size:e.length}function Kn(e){return{...e}}function xt(e,t){return Object.keys(e).some(n=>e[n]===t)}function me(e){return Object.keys(e).length===0}function B(){if(typeof globalThis=="object")return globalThis;Object.defineProperty(Object.prototype,"_dd_temp_",{get(){return this},configurable:!0});let e=_dd_temp_;return delete Object.prototype._dd_temp_,typeof e!="object"&&(typeof self=="object"?e=self:typeof window=="object"?e=window:e={}),e}function ne(e,t){const n=B();let r;return n.Zone&&typeof n.Zone.__symbol__=="function"&&(r=e[n.Zone.__symbol__(t)]),r||(r=e[t]),r}let Le,Dt=!1;function Jn(e){Le=e}function qn(e){Dt=e}function Yn(e,t,n){const r=n.value;n.value=function(...o){return(Le?y(r):r).apply(this,o)}}function y(e){return function(){return ge(e,this,arguments)}}function ge(e,t,n){try{return e.apply(t,n)}catch(r){Zn(r)}}function Zn(e){if(et(e),Le)try{Le(e)}catch(t){et(t)}}function et(...e){Dt&&_.error("[MONITOR]",...e)}function Se(e,t){return ne(B(),"setTimeout")(y(e),t)}function Mt(e){ne(B(),"clearTimeout")(e)}function tt(e,t){return ne(B(),"setInterval")(y(e),t)}function Nt(e){ne(B(),"clearInterval")(e)}class O{constructor(t){this.onFirstSubscribe=t,this.observers=[]}subscribe(t){return this.observers.push(t),this.observers.length===1&&this.onFirstSubscribe&&(this.onLastUnsubscribe=this.onFirstSubscribe(this)||void 0),{unsubscribe:()=>{this.observers=this.observers.filter(n=>t!==n),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}}notify(t){this.observers.forEach(n=>n(t))}}function $t(...e){return new O(t=>{const n=e.map(r=>r.subscribe(o=>t.notify(o)));return()=>n.forEach(r=>r.unsubscribe())})}function Pt(e,t,n){let r=!1,o,s;return{throttled:(...i)=>{if(r){o=i;return}e(...i),r=!0,s=Se(()=>{o&&e(...o),r=!1,o=void 0},t)},cancel:()=>{Mt(s),r=!1,o=void 0}}}function G(){}function j(e){return e?(parseInt(e,10)^Math.random()*16>>parseInt(e,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,j)}const Ie=/([\\w-]+)\\s*=\\s*([^;]+)/g;function Xn(e,t){for(Ie.lastIndex=0;;){const n=Ie.exec(e);if(n){if(n[1]===t)return n[2]}else break}}function Vn(e){const t=new Map;for(Ie.lastIndex=0;;){const n=Ie.exec(e);if(n)t.set(n[1],n[2]);else break}return t}function Qn(e,t,n=""){const r=e.charCodeAt(t-1),s=r>=55296&&r<=56319?t+1:t;return e.length<=s?e:`${e.slice(0,s)}${n}`}function er(){return tr()===0}let Ae;function tr(){return Ae??(Ae=nr())}function nr(e=window){var t;const n=e.navigator.userAgent;return e.chrome||/HeadlessChrome/.test(n)?0:((t=e.navigator.vendor)===null||t===void 0?void 0:t.indexOf("Apple"))===0||/safari/i.test(n)&&!/chrome|android/i.test(n)?1:2}function ye(e,t,n=0,r){const o=new Date;o.setTime(o.getTime()+n);const s=`expires=${o.toUTCString()}`,i=r&&r.crossSite?"none":"strict",a=r&&r.domain?`;domain=${r.domain}`:"",c=r&&r.secure?";secure":"",l=r&&r.partitioned?";partitioned":"";document.cookie=`${e}=${t};${s};path=/;samesite=${i}${a}${c}${l}`}function nt(e){return Xn(document.cookie,e)}let rt;function J(e){return rt||(rt=Vn(document.cookie)),rt.get(e)}function Ft(e,t){ye(e,"",0,t)}function rr(e){if(document.cookie===void 0||document.cookie===null)return!1;try{const t=`dd_cookie_test_${j()}`,n="test";ye(t,n,K,e);const r=nt(t)===n;return Ft(t,e),r}catch(t){return _.error(t),!1}}let ot;function or(){if(ot===void 0){const e=`dd_site_test_${j()}`,t="test",n=window.location.hostname.split(".");let r=n.pop();for(;n.length&&!nt(e);)r=`${n.pop()}.${r}`,ye(e,t,pe,{domain:r});Ft(e,{domain:r}),ot=r}return ot}const re="_dd_s";function ke(e){return Object.values(e)}function sr(e){return Object.entries(e)}const st=4*It,Ut=15*K,ir=Bn,be={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},Bt=/^([a-zA-Z]+)=([a-z0-9-]+)$/,it="&";function ar(e){return!!e&&(e.indexOf(it)!==-1||Bt.test(e))}const cr="1";function q(e,t){const n={isExpired:cr};return t.trackAnonymousUser&&(e!=null&&e.anonymousId?n.anonymousId=e==null?void 0:e.anonymousId:n.anonymousId=j()),n}function xe(e){return me(e)}function Gt(e){return!xe(e)}function De(e){return e.isExpired!==void 0||!ur(e)}function ur(e){return(e.created===void 0||he()-Number(e.created)<st)&&(e.expire===void 0||he()<Number(e.expire))}function jt(e){e.expire=String(he()+Ut)}function at(e){return sr(e).map(([t,n])=>t==="anonymousId"?`aid=${n}`:`${t}=${n}`).join(it)}function Ht(e){const t={};return ar(e)&&e.split(it).forEach(n=>{const r=Bt.exec(n);if(r!==null){const[,o,s]=r;o==="aid"?t.anonymousId=s:t[o]=s}}),t}const lr="_dd",dr="_dd_r",fr="_dd_l",pr="rum",hr="logs";function mr(e){if(!J(re)){const n=J(lr),r=J(dr),o=J(fr),s={};n&&(s.id=n),o&&/^[01]$/.test(o)&&(s[hr]=o),r&&/^[012]$/.test(r)&&(s[pr]=r),Gt(s)&&(jt(s),e.persistSession(s))}}function zt(e){const t=Er(e);return rr(t)?{type:be.COOKIE,cookieOptions:t}:void 0}function gr(e,t){const n={isLockEnabled:er(),persistSession:Sr(t),retrieveSession:br,expireSession:r=>yr(t,r,e)};return mr(n),n}function Sr(e){return t=>{ye(re,at(t),Ut,e)}}function yr(e,t,n){const r=q(t,n);ye(re,at(r),n.trackAnonymousUser?ir:st,e)}function br(){const e=nt(re);return Ht(e)}function Er(e){const t={};return t.secure=!!e.useSecureSessionCookie||!!e.usePartitionedCrossSiteSessionCookie,t.crossSite=!!e.usePartitionedCrossSiteSessionCookie,t.partitioned=!!e.usePartitionedCrossSiteSessionCookie,e.trackSessionAcrossSubdomains&&(t.domain=or()),t}const Tr="_dd_test_";function Wt(){try{const e=j(),t=`${Tr}${e}`;localStorage.setItem(t,e);const n=localStorage.getItem(t);return localStorage.removeItem(t),e===n?{type:be.LOCAL_STORAGE}:void 0}catch{return}}function _r(e){return{isLockEnabled:!1,persistSession:Kt,retrieveSession:wr,expireSession:t=>Or(t,e)}}function Kt(e){localStorage.setItem(re,at(e))}function wr(){const e=localStorage.getItem(re);return Ht(e)}function Or(e,t){Kt(q(e,t))}const Rr=10,Cr=100,Jt=[];let Me;function Y(e,t,n=0){var r;const{isLockEnabled:o,persistSession:s,expireSession:i}=t,a=f=>s({...f,lock:l}),c=()=>{const f=t.retrieveSession(),h=f.lock;return f.lock&&delete f.lock,{session:f,lock:h}};if(Me||(Me=e),e!==Me){Jt.push(e);return}if(o&&n>=Cr){qt(t);return}let l,u=c();if(o){if(u.lock){Ne(e,t,n);return}if(l=j(),a(u.session),u=c(),u.lock!==l){Ne(e,t,n);return}}let d=e.process(u.session);if(o&&(u=c(),u.lock!==l)){Ne(e,t,n);return}if(d&&(De(d)?i(d):(jt(d),o?a(d):s(d))),o&&!(d&&De(d))){if(u=c(),u.lock!==l){Ne(e,t,n);return}s(u.session),d=u.session}(r=e.after)===null||r===void 0||r.call(e,d||u.session),qt(t)}function Ne(e,t,n){Se(()=>{Y(e,t,n+1)},Rr)}function qt(e){Me=void 0;const t=Jt.shift();t&&Y(t,e)}const Yt=pe;function vr(e){switch(e.sessionPersistence){case be.COOKIE:return zt(e);case be.LOCAL_STORAGE:return Wt();case void 0:{let t=zt(e);return!t&&e.allowFallbackToLocalStorage&&(t=Wt()),t}default:_.error(`Invalid session persistence \'${String(e.sessionPersistence)}\'`)}}function Lr(e,t,n,r){const o=new O,s=new O,i=new O,a=e.type===be.COOKIE?gr(t,e.cookieOptions):_r(t),{expireSession:c}=a,l=tt(m,Yt);let u;E();const{throttled:d,cancel:f}=Pt(()=>{Y({process:S=>{if(xe(S))return;const de=b(S);return z(de),de},after:S=>{Gt(S)&&!v()&&Mi(S),u=S}},a)},Yt);function h(){Y({process:S=>v()?b(S):void 0},a)}function m(){Y({process:S=>De(S)?q(S,t):void 0,after:b},a)}function b(S){return De(S)&&(S=q(S,t)),v()&&(te(S)?Di():(i.notify({previousState:u,newState:S}),u=S)),S}function E(){Y({process:S=>{if(xe(S))return q(S,t)},after:S=>{u=S}},a)}function z(S){if(xe(S))return!1;const{trackingType:de,isTracked:$i}=r(S[n]);S[n]=de,delete S.isExpired,$i&&!S.id&&(S.id=j(),S.created=String(he()))}function v(){return u[n]!==void 0}function te(S){return u.id!==S.id||u[n]!==S[n]}function Di(){u=q(u,t),s.notify()}function Mi(S){u=S,o.notify()}function Ni(S){Y({process:de=>({...de,...S}),after:b},a)}return{expandOrRenewSession:d,expandSession:h,getSession:()=>u,renewObservable:o,expireObservable:s,sessionStateUpdateObservable:i,restartSession:E,expire:()=>{f(),c(u),b(q(u,t))},stop:()=>{Nt(l)},updateSessionState:Ni}}const ct={GRANTED:"granted",NOT_GRANTED:"not-granted"};function Ir(e){const t=new O;return{tryToInit(n){e||(e=n)},update(n){e=n,t.notify()},isGranted(){return e===ct.GRANTED},observable:t}}function Z(e,t,n){if(typeof e!="object"||e===null)return JSON.stringify(e);const r=oe(Object.prototype),o=oe(Array.prototype),s=oe(Object.getPrototypeOf(e)),i=oe(e);try{return JSON.stringify(e,t,n)}catch{return"<error: unable to serialize object>"}finally{r(),o(),s(),i()}}function oe(e){const t=e,n=t.toJSON;return n?(delete t.toJSON,()=>{t.toJSON=n}):G}function ut(e){return Ar(e,location.href).href}function Ar(e,t){const n=kr();if(n)try{return t!==void 0?new n(e,t):new n(e)}catch(s){throw new Error(`Failed to construct URL: ${String(s)} ${Z({url:e,base:t})}`)}if(t===void 0&&!/:/.test(e))throw new Error(`Invalid URL: \'${e}\'`);let r=document;const o=r.createElement("a");if(t!==void 0){r=document.implementation.createHTMLDocument("");const s=r.createElement("base");s.href=t,r.head.appendChild(s),r.body.appendChild(o)}return o.href=e,o}const Zt=URL;let $e;function kr(){if($e===void 0)try{$e=new Zt("http://test/path").href==="http://test/path"}catch{$e=!1}return $e?Zt:void 0}const xr="datad0g.com",Dr="dd0g-gov.com",se="datadoghq.com",Mr="ddog-gov.com",Nr="pci.browser-intake-datadoghq.com",$r=["ddsource","ddtags"];function Ee(e,t,n){const r=Pr(e,t);return{build(o,s){const i=Ur(e,t,n,o,s);return r(i)},urlPrefix:r(""),trackType:t}}function Pr(e,t){const n=`/api/v2/${t}`,r=e.proxy;if(typeof r=="string"){const s=ut(r);return i=>`${s}?ddforward=${encodeURIComponent(`${n}?${i}`)}`}if(typeof r=="function")return s=>r({path:n,parameters:s});const o=Fr(t,e);return s=>`https://${o}${n}?${s}`}function Fr(e,t){const{site:n=se,internalAnalyticsSubdomain:r}=t;if(e==="logs"&&t.usePciIntake&&n===se)return Nr;if(r&&n===se)return`${r}.${se}`;if(n===Dr)return`http-intake.logs.${n}`;const o=n.split("."),s=o.pop();return`browser-intake-${o.join("-")}.${s}`}function Ur({clientToken:e,internalAnalyticsSubdomain:t},n,r,o,{retry:s,encoding:i}){const a=["sdk_version:6.5.0",`api:${o}`].concat(r);s&&a.push(`retry_count:${s.count}`,`retry_after:${s.lastFailureStatus}`);const c=["ddsource=browser",`ddtags=${encodeURIComponent(a.join(","))}`,`dd-api-key=${e}`,`dd-evp-origin-version=${encodeURIComponent("6.5.0")}`,"dd-evp-origin=browser",`dd-request-id=${j()}`];return i&&c.push(`dd-evp-encoding=${i}`),n==="rum"&&c.push(`batch_time=${F()}`),t&&c.reverse(),c.join("&")}const Br=200;function Gr(e){const{env:t,service:n,version:r,datacenter:o}=e,s=[];return t&&s.push(Pe("env",t)),n&&s.push(Pe("service",n)),r&&s.push(Pe("version",r)),o&&s.push(Pe("datacenter",o)),s}function Pe(e,t){const n=Br-e.length-1;(t.length>n||jr(t))&&_.warn(`${e} value doesn\'t meet tag requirements and will be sanitized. ${Re} ${Xe}/getting_started/tagging/#defining-tags`);const r=t.replace(/,/g,"_");return`${e}:${r}`}function jr(e){return Hr()?new RegExp("[^\\\\p{Ll}\\\\p{Lo}0-9_:./-]","u").test(e):!1}function Hr(){try{return new RegExp("[\\\\p{Ll}]","u"),!0}catch{return!1}}function zr(e){const t=e.site||se,n=Gr(e),r=Wr(e,n);return{replica:Kr(e,n),site:t,...r}}function Wr(e,t){return{logsEndpointBuilder:Ee(e,"logs",t),rumEndpointBuilder:Ee(e,"rum",t),sessionReplayEndpointBuilder:Ee(e,"replay",t)}}function Kr(e,t){if(!e.replica)return;const n={...e,site:se,clientToken:e.replica.clientToken},r={logsEndpointBuilder:Ee(n,"logs",t),rumEndpointBuilder:Ee(n,"rum",t)};return{applicationId:e.replica.applicationId,...r}}function Jr(e){return $r.every(t=>e.includes(t))}function lt(e,t){return e!=null&&typeof e!="string"?(_.error(`${t} must be defined as a string`),!1):!0}function qr(e){return e&&typeof e=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(e)?(_.error(`Site should be a valid Datadog site. ${Re} ${Xe}/getting_started/site/.`),!1):!0}function Fe(e,t){return e!==void 0&&!Fn(e)?(_.error(`${t} Sample Rate should be a number between 0 and 100`),!1):!0}function Yr(e){var t,n,r,o,s,i;if(!e||!e.clientToken){_.error("Client Token is not configured, we will not send any data.");return}if(!(!qr(e.site)||!Fe(e.sessionSampleRate,"Session")||!Fe(e.telemetrySampleRate,"Telemetry")||!Fe(e.telemetryConfigurationSampleRate,"Telemetry Configuration")||!Fe(e.telemetryUsageSampleRate,"Telemetry Usage")||!lt(e.version,"Version")||!lt(e.env,"Env")||!lt(e.service,"Service"))){if(e.trackingConsent!==void 0&&!xt(ct,e.trackingConsent)){_.error(\'Tracking Consent should be either "granted" or "not-granted"\');return}return{beforeSend:e.beforeSend&&Lt(e.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:vr(e),sessionSampleRate:(t=e.sessionSampleRate)!==null&&t!==void 0?t:100,telemetrySampleRate:(n=e.telemetrySampleRate)!==null&&n!==void 0?n:20,telemetryConfigurationSampleRate:(r=e.telemetryConfigurationSampleRate)!==null&&r!==void 0?r:5,telemetryUsageSampleRate:(o=e.telemetryUsageSampleRate)!==null&&o!==void 0?o:5,service:e.service||void 0,silentMultipleInit:!!e.silentMultipleInit,allowUntrustedEvents:!!e.allowUntrustedEvents,trackingConsent:(s=e.trackingConsent)!==null&&s!==void 0?s:ct.GRANTED,trackAnonymousUser:(i=e.trackAnonymousUser)!==null&&i!==void 0?i:!0,storeContextsAcrossPages:!!e.storeContextsAcrossPages,batchBytesLimit:16*D,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*pe,batchMessagesLimit:50,messageBytesLimit:256*D,...zr(e)}}}function Zr(e){return{session_sample_rate:e.sessionSampleRate,telemetry_sample_rate:e.telemetrySampleRate,telemetry_configuration_sample_rate:e.telemetryConfigurationSampleRate,telemetry_usage_sample_rate:e.telemetryUsageSampleRate,use_before_send:!!e.beforeSend,use_partitioned_cross_site_session_cookie:e.usePartitionedCrossSiteSessionCookie,use_secure_session_cookie:e.useSecureSessionCookie,use_proxy:!!e.proxy,silent_multiple_init:e.silentMultipleInit,track_session_across_subdomains:e.trackSessionAcrossSubdomains,track_anonymous_user:e.trackAnonymousUser,session_persistence:e.sessionPersistence,allow_fallback_to_local_storage:!!e.allowFallbackToLocalStorage,store_contexts_across_pages:!!e.storeContextsAcrossPages,allow_untrusted_events:!!e.allowUntrustedEvents,tracking_consent:e.trackingConsent}}var dt;(function(e){e.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",e.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(dt||(dt={}));const Xt=new Set;function Xr(e){Array.isArray(e)&&Vr(e.filter(t=>xt(dt,t)))}function Vr(e){e.forEach(t=>{Xt.add(t)})}function Qr(){return Xt}const Te="?";function M(e){const t=[];let n=ft(e,"stack");const r=String(e);return n&&n.startsWith(r)&&(n=n.slice(r.length)),n&&n.split(`\n`).forEach(o=>{const s=no(o)||oo(o)||io(o)||uo(o);s&&(!s.func&&s.line&&(s.func=Te),t.push(s))}),{message:ft(e,"message"),name:ft(e,"name"),stack:t}}const Vt="((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\\\w+\\\\.|\\\\/).*?)",ie="(?::(\\\\d+))",eo=new RegExp(`^\\\\s*at (.*?) ?\\\\(${Vt}${ie}?${ie}?\\\\)?\\\\s*$`,"i"),to=new RegExp(`\\\\((\\\\S*)${ie}${ie}\\\\)`);function no(e){const t=eo.exec(e);if(!t)return;const n=t[2]&&t[2].indexOf("native")===0,r=t[2]&&t[2].indexOf("eval")===0,o=to.exec(t[2]);return r&&o&&(t[2]=o[1],t[3]=o[2],t[4]=o[3]),{args:n?[t[2]]:[],column:t[4]?+t[4]:void 0,func:t[1]||Te,line:t[3]?+t[3]:void 0,url:n?void 0:t[2]}}const ro=new RegExp(`^\\\\s*at ?${Vt}${ie}?${ie}??\\\\s*$`,"i");function oo(e){const t=ro.exec(e);if(t)return{args:[],column:t[3]?+t[3]:void 0,func:Te,line:t[2]?+t[2]:void 0,url:t[1]}}const so=/^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;function io(e){const t=so.exec(e);if(t)return{args:[],column:t[4]?+t[4]:void 0,func:t[1]||Te,line:+t[3],url:t[2]}}const ao=/^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i,co=/(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;function uo(e){const t=ao.exec(e);if(!t)return;const n=t[3]&&t[3].indexOf(" > eval")>-1,r=co.exec(t[3]);return n&&r&&(t[3]=r[1],t[4]=r[2],t[5]=void 0),{args:t[2]?t[2].split(","):[],column:t[5]?+t[5]:void 0,func:t[1]||Te,line:t[4]?+t[4]:void 0,url:t[3]}}function ft(e,t){if(typeof e!="object"||!e||!(t in e))return;const n=e[t];return typeof n=="string"?n:void 0}function lo(e,t,n,r){const o=[{url:t,column:r,line:n}],{name:s,message:i}=po(e);return{name:s,message:i,stack:o}}const fo=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\\s\\S]*)$/;function po(e){let t,n;return{}.toString.call(e)==="[object String]"&&([,t,n]=fo.exec(e)),{name:t,message:n}}function Ue(e){const n=new Error(e);n.name="HandlingStack";let r;return ge(()=>{const o=M(n);o.stack=o.stack.slice(2),r=X(o)}),r}function X(e){let t=Qt(e);return e.stack.forEach(n=>{const r=n.func==="?"?"<anonymous>":n.func,o=n.args&&n.args.length>0?`(${n.args.join(", ")})`:"",s=n.line?`:${n.line}`:"",i=n.line&&n.column?`:${n.column}`:"";t+=`\n at ${r}${o} @ ${n.url}${s}${i}`}),t}function Qt(e){return`${e.name||"Error"}: ${e.message}`}function V(e,t,n,{computeHandlingStack:r}={}){let o=e[t];if(typeof o!="function")if(t in e&&t.startsWith("on"))o=G;else return{stop:G};let s=!1;const i=function(){if(s)return o.apply(this,arguments);const a=Array.from(arguments);let c;ge(n,null,[{target:this,parameters:a,onPostCall:u=>{c=u},handlingStack:r?Ue("instrumented method"):void 0}]);const l=o.apply(this,a);return c&&ge(c,null,[l]),l};return e[t]=i,{stop:()=>{s=!0,e[t]===i&&(e[t]=o)}}}const ho=220*D,mo="$",go=3;function N(e,t=ho){const n=oe(Object.prototype),r=oe(Array.prototype),o=[],s=new WeakMap,i=pt(e,mo,void 0,o,s),a=JSON.stringify(i);let c=a?a.length:0;if(c>t){mt(t,"discarded",e);return}for(;o.length>0&&c<t;){const l=o.shift();let u=0;if(Array.isArray(l.source))for(let d=0;d<l.source.length;d++){const f=pt(l.source[d],l.path,d,o,s);if(f!==void 0?c+=JSON.stringify(f).length:c+=4,c+=u,u=1,c>t){mt(t,"truncated",e);break}l.target[d]=f}else for(const d in l.source)if(Object.prototype.hasOwnProperty.call(l.source,d)){const f=pt(l.source[d],l.path,d,o,s);if(f!==void 0&&(c+=JSON.stringify(f).length+u+d.length+go,u=1),c>t){mt(t,"truncated",e);break}l.target[d]=f}}return n(),r(),i}function pt(e,t,n,r,o){const s=bo(e);if(!s||typeof s!="object")return So(s);const i=ht(s);if(i!=="[Object]"&&i!=="[Array]"&&i!=="[Error]")return i;const a=e;if(o.has(a))return`[Reference seen at ${o.get(a)}]`;const c=n!==void 0?`${t}.${n}`:t,l=Array.isArray(s)?[]:{};return o.set(a,c),r.push({source:s,target:l,path:c}),l}function So(e){return typeof e=="bigint"?`[BigInt] ${e.toString()}`:typeof e=="function"?`[Function] ${e.name||"unknown"}`:typeof e=="symbol"?`[Symbol] ${e.description||e.toString()}`:e}function ht(e){try{if(e instanceof Event)return yo(e);if(e instanceof RegExp)return`[RegExp] ${e.toString()}`;const n=Object.prototype.toString.call(e).match(/\\[object (.*)\\]/);if(n&&n[1])return`[${n[1]}]`}catch{}return"[Unserializable]"}function yo(e){return{type:e.type,isTrusted:e.isTrusted,currentTarget:e.currentTarget?ht(e.currentTarget):null,target:e.target?ht(e.target):null}}function bo(e){const t=e;if(t&&typeof t.toJSON=="function")try{return t.toJSON()}catch{}return e}function mt(e,t,n){_.warn(`The data provided has been ${t} as it is over the limit of ${e} characters:`,n)}const en="No stack, consider using an instance of Error";function tn({stackTrace:e,originalError:t,handlingStack:n,componentStack:r,startClocks:o,nonErrorPrefix:s,source:i,handling:a}){const c=H(t),l=Eo(e,c,s,t),u=To(c,e)?X(e):en,d=c?on(t,i):void 0,f=e?e.name:void 0,h=nn(t),m=rn(t);return{startClocks:o,source:i,handling:a,handlingStack:n,componentStack:r,originalError:t,type:f,message:l,stack:u,causes:d,fingerprint:h,context:m}}function Eo(e,t,n,r){return e!=null&&e.message&&(e!=null&&e.name)?e.message:t?"Empty message":`${n} ${Z(N(r))}`}function To(e,t){return t===void 0?!1:e?!0:t.stack.length>0&&(t.stack.length>1||t.stack[0].url!==void 0)}function nn(e){return H(e)&&"dd_fingerprint"in e?String(e.dd_fingerprint):void 0}function rn(e){if(e!==null&&typeof e=="object"&&"dd_context"in e)return e.dd_context}function _o(e){var t;return(t=/@ (.+)/.exec(e))===null||t===void 0?void 0:t[1]}function H(e){return e instanceof Error||Object.prototype.toString.call(e)==="[object Error]"}function on(e,t){let n=e;const r=[];for(;H(n==null?void 0:n.cause)&&r.length<10;){const o=M(n.cause);r.push({message:n.cause.message,source:t,type:o==null?void 0:o.name,stack:X(o)}),n=n.cause}return r.length?r:void 0}const L={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function wo(e){const t=(o,s)=>{const i=tn({stackTrace:o,originalError:s,startClocks:U(),nonErrorPrefix:"Uncaught",source:L.SOURCE,handling:"unhandled"});e.notify(i)},{stop:n}=Oo(t),{stop:r}=Ro(t);return{stop:()=>{n(),r()}}}function Oo(e){return V(window,"onerror",({parameters:[t,n,r,o,s]})=>{let i;H(s)?i=M(s):i=lo(t,n,r,o),e(i,s??t)})}function Ro(e){return V(window,"onunhandledrejection",({parameters:[t]})=>{const n=t.reason||"Empty reason",r=M(n);e(r,n)})}function Co(e){const t={version:"6.5.0",onReady(n){n()},...e};return Object.defineProperty(t,"_setDebug",{get(){return qn},enumerable:!1}),t}function vo(e,t,n){const r=e[t];r&&!r.q&&r.version&&_.warn("SDK is loaded more than once. This is unsupported and might have unexpected behavior."),e[t]=n,r&&r.q&&r.q.forEach(o=>Lt(o,"onReady callback threw an error:")())}function sn(e,t){t.silentMultipleInit||_.error(`${e} is already initialized.`)}function Q(e,t,n,r,o){return gt(e,t,[n],r,o)}function gt(e,t,n,r,{once:o,capture:s,passive:i}={}){const a=y(f=>{!f.isTrusted&&!f.__ddIsTrusted&&!e.allowUntrustedEvents||(o&&d(),r(f))}),c=i?{capture:s,passive:i}:s,l=window.EventTarget&&t instanceof EventTarget?window.EventTarget.prototype:t,u=ne(l,"addEventListener");n.forEach(f=>u.call(t,f,a,c));function d(){const f=ne(l,"removeEventListener");n.forEach(h=>f.call(t,h,a,c))}return{stop:d}}const Be={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function Lo(e,t){const n=[];t.includes(Be.cspViolation)&&n.push(Ao(e));const r=t.filter(o=>o!==Be.cspViolation);return r.length&&n.push(Io(r)),$t(...n)}function Io(e){return new O(t=>{if(!window.ReportingObserver)return;const n=y((o,s)=>o.forEach(i=>t.notify(ko(i)))),r=new window.ReportingObserver(n,{types:e,buffered:!0});return r.observe(),()=>{r.disconnect()}})}function Ao(e){return new O(t=>{const{stop:n}=Q(e,document,"securitypolicyviolation",r=>{t.notify(xo(r))});return n})}function ko(e){const{type:t,body:n}=e;return an({type:n.id,message:`${t}: ${n.message}`,originalError:e,stack:cn(n.id,n.message,n.sourceFile,n.lineNumber,n.columnNumber)})}function xo(e){const t=`\'${e.blockedURI}\' blocked by \'${e.effectiveDirective}\' directive`;return an({type:e.effectiveDirective,message:`${Be.cspViolation}: ${t}`,originalError:e,csp:{disposition:e.disposition},stack:cn(e.effectiveDirective,e.originalPolicy?`${t} of the policy "${Qn(e.originalPolicy,100,"...")}"`:"no policy",e.sourceFile,e.lineNumber,e.columnNumber)})}function an(e){return{startClocks:U(),source:L.REPORT,handling:"unhandled",...e}}function cn(e,t,n,r,o){return n?X({name:e,message:t,stack:[{func:"?",url:n,line:r??void 0,column:o??void 0}]}):void 0}function un(e,t){const n=window.__ddBrowserSdkExtensionCallback;n&&n({type:e,payload:t})}function ln(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Ge(e,t,n=Do()){if(t===void 0)return e;if(typeof t!="object"||t===null)return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=t.flags||[t.global?"g":"",t.ignoreCase?"i":"",t.multiline?"m":"",t.sticky?"y":"",t.unicode?"u":""].join("");return new RegExp(t.source,o)}if(n.hasAlreadyBeenSeen(t))return;if(Array.isArray(t)){const o=Array.isArray(e)?e:[];for(let s=0;s<t.length;++s)o[s]=Ge(o[s],t[s],n);return o}const r=ln(e)==="object"?e:{};for(const o in t)Object.prototype.hasOwnProperty.call(t,o)&&(r[o]=Ge(r[o],t[o],n));return r}function dn(e){return Ge(void 0,e)}function ae(...e){let t;for(const n of e)n!=null&&(t=Ge(t,n));return t}function Do(){if(typeof WeakSet<"u"){const t=new WeakSet;return{hasAlreadyBeenSeen(n){const r=t.has(n);return r||t.add(n),r}}}const e=[];return{hasAlreadyBeenSeen(t){const n=e.indexOf(t)>=0;return n||e.push(t),n}}}function Mo(){var e;const t=window.navigator;return{status:t.onLine?"connected":"not_connected",interfaces:t.connection&&t.connection.type?[t.connection.type]:void 0,effective_type:(e=t.connection)===null||e===void 0?void 0:e.effectiveType}}function No(e){const t=new Set;return e.forEach(n=>t.add(n)),Array.from(t)}function fn(e,t){const n=e.indexOf(t);n>=0&&e.splice(n,1)}const $o=500;function pn(){const e=[];return{add:o=>{e.push(o)>$o&&e.splice(0,1)},remove:o=>{fn(e,o)},drain:o=>{e.forEach(s=>s(o)),e.length=0}}}const ee={log:"log",configuration:"configuration",usage:"usage"},Po=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],Fo=[Mr];let hn=pn(),ce=e=>{hn.add(()=>ce(e))};function Uo(e,t){let n;const r=new O,o=new Set,s=!Fo.includes(t.site)&&Ce(t.telemetrySampleRate),i={[ee.log]:s,[ee.configuration]:s&&Ce(t.telemetryConfigurationSampleRate),[ee.usage]:s&&Ce(t.telemetryUsageSampleRate)},a=Bo();ce=l=>{const u=Z(l);if(i[l.type]&&o.size<t.maxTelemetryEventsPerPage&&!o.has(u)){const d=c(e,l,a);r.notify(d),un("telemetry",d),o.add(u)}},Jn(gn);function c(l,u,d){return ae({type:"telemetry",date:F(),service:l,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:ae(u,{runtime_env:d,connectivity:Mo(),sdk_setup:"npm"}),experimental_features:Array.from(Qr())},n!==void 0?n():{})}return{setContextProvider:l=>{n=l},observable:r,enabled:s}}function Bo(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function Go(){hn.drain()}function jo(e){return e.site===xr}function mn(e,t){et(T.debug,e,t),ce({type:ee.log,message:e,status:"debug",...t})}function gn(e,t){ce({type:ee.log,status:"error",...Wo(e),...t})}function Ho(e){ce({type:ee.configuration,configuration:e})}function zo(e){ce({type:ee.usage,usage:e})}function Wo(e){if(H(e)){const t=M(e);return{error:{kind:t.name,stack:X(Ko(t))},message:t.message}}return{error:{stack:en},message:`Uncaught ${Z(e)}`}}function Ko(e){return e.stack=e.stack.filter(t=>!t.url||Po.some(n=>t.url.startsWith(n))),e}const _e=1/0,Jo=K;let we=null;const je=new Set;function qo(){je.forEach(e=>e())}function Yo({expireDelay:e,maxEntries:t}){let n=[];const r=[];we||(we=tt(()=>qo(),Jo));const o=()=>{const h=ve()-e;for(;n.length>0&&n[n.length-1].endTime<h;){const m=n.pop();m&&r.push(m.startTime)}};je.add(o);function s(h,m){const b={value:h,startTime:m,endTime:_e,remove:()=>{fn(n,b)},close:E=>{b.endTime=E}};return t&&n.length>=t&&n.pop(),n.unshift(b),b}function i(h=_e,m={returnInactive:!1}){for(const b of n)if(b.startTime<=h){if(m.returnInactive||h<=b.endTime)return b.value;break}}function a(h){const m=n[0];m&&m.endTime===_e&&m.close(h)}function c(h=_e,m=0){const b=Hn(h,m);return n.filter(E=>E.startTime<=b&&h<=E.endTime).map(E=>E.value)}function l(){return n.map(({startTime:h,endTime:m,value:b})=>({startTime:h,endTime:m===_e?"Infinity":m,value:b}))}function u(){return r}function d(){n=[]}function f(){je.delete(o),je.size===0&&we&&(Nt(we),we=null)}return{add:s,find:i,closeActive:a,findAll:c,reset:d,stop:f,getAllEntries:l,getDeletedEntries:u}}const Zo=K,Xo=st;function Vo(e,t,n,r){const o=new O,s=new O,i=Lr(e.sessionStoreStrategyType,e,t,n),a=Yo({expireDelay:Xo});i.renewObservable.subscribe(()=>{a.add(c(),ve()),o.notify()}),i.expireObservable.subscribe(()=>{s.notify(),a.closeActive(ve())}),i.expandOrRenewSession(),a.add(c(),Gn().relative),r.observable.subscribe(()=>{r.isGranted()?i.expandOrRenewSession():i.expire()}),Qo(e,()=>{r.isGranted()&&i.expandOrRenewSession()}),es(e,()=>i.expandSession()),ts(e,()=>i.restartSession());function c(){return{id:i.getSession().id,trackingType:i.getSession()[t],isReplayForced:!!i.getSession().forcedReplay,anonymousId:i.getSession().anonymousId}}return{findSession:(l,u)=>a.find(l,u),renewObservable:o,expireObservable:s,sessionStateUpdateObservable:i.sessionStateUpdateObservable,expire:i.expire,updateSessionState:i.updateSessionState}}function Qo(e,t){gt(e,window,["click","touchstart","keydown","scroll"],t,{capture:!0,passive:!0})}function es(e,t){const n=()=>{document.visibilityState==="visible"&&t()};Q(e,document,"visibilitychange",n),tt(n,Zo)}function ts(e,t){Q(e,window,"resume",t,{capture:!0})}function Sn(e){return e>=500}function ns(e){try{return e.clone()}catch{return}}const rs=80*D,os=32,yn=3*kt,ss=K,bn=pe;function En(e,t,n,r,o){t.transportStatus===0&&t.queuedPayloads.size()===0&&t.bandwidthMonitor.canHandle(e)?_n(e,t,n,{onSuccess:()=>wn(0,t,n,r,o),onFailure:()=>{t.queuedPayloads.enqueue(e),Tn(t,n,r,o)}}):t.queuedPayloads.enqueue(e)}function Tn(e,t,n,r){e.transportStatus===2&&Se(()=>{const o=e.queuedPayloads.first();_n(o,e,t,{onSuccess:()=>{e.queuedPayloads.dequeue(),e.currentBackoffTime=bn,wn(1,e,t,n,r)},onFailure:()=>{e.currentBackoffTime=Math.min(ss,e.currentBackoffTime*2),Tn(e,t,n,r)}})},e.currentBackoffTime)}function _n(e,t,n,{onSuccess:r,onFailure:o}){t.bandwidthMonitor.add(e),n(e,s=>{t.bandwidthMonitor.remove(e),is(s)?(t.transportStatus=t.bandwidthMonitor.ongoingRequestCount>0?1:2,e.retry={count:e.retry?e.retry.count+1:1,lastFailureStatus:s.status},o()):(t.transportStatus=0,r())})}function wn(e,t,n,r,o){e===0&&t.queuedPayloads.isFull()&&!t.queueFullReported&&(o({message:`Reached max ${r} events size queued for upload: ${yn/kt}MiB`,source:L.AGENT,startClocks:U()}),t.queueFullReported=!0);const s=t.queuedPayloads;for(t.queuedPayloads=On();s.size()>0;)En(s.dequeue(),t,n,r,o)}function is(e){return e.type!=="opaque"&&(e.status===0&&!navigator.onLine||e.status===408||e.status===429||Sn(e.status))}function as(){return{transportStatus:0,currentBackoffTime:bn,bandwidthMonitor:cs(),queuedPayloads:On(),queueFullReported:!1}}function On(){const e=[];return{bytesCount:0,enqueue(t){this.isFull()||(e.push(t),this.bytesCount+=t.bytesCount)},first(){return e[0]},dequeue(){const t=e.shift();return t&&(this.bytesCount-=t.bytesCount),t},size(){return e.length},isFull(){return this.bytesCount>=yn}}}function cs(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(e){return this.ongoingRequestCount===0||this.ongoingByteCount+e.bytesCount<=rs&&this.ongoingRequestCount<os},add(e){this.ongoingRequestCount+=1,this.ongoingByteCount+=e.bytesCount},remove(e){this.ongoingRequestCount-=1,this.ongoingByteCount-=e.bytesCount}}}function us(e,t,n){const r=as(),o=(s,i)=>fs(e,t,s,i);return{send:s=>{En(s,r,o,e.trackType,n)},sendOnExit:s=>{ls(e,t,s)}}}function ls(e,t,n){if(!!navigator.sendBeacon&&n.bytesCount<t)try{const s=e.build("beacon",n);if(navigator.sendBeacon(s,n.data))return}catch(s){ds(s)}const o=e.build("xhr",n);St(o,n.data)}let Rn=!1;function ds(e){Rn||(Rn=!0,gn(e))}function fs(e,t,n,r){if(ps()&&n.bytesCount<t){const s=e.build("fetch",n);fetch(s,{method:"POST",body:n.data,keepalive:!0,mode:"cors"}).then(y(i=>r==null?void 0:r({status:i.status,type:i.type})),y(()=>{const i=e.build("xhr",n);St(i,n.data,r)}))}else{const s=e.build("xhr",n);St(s,n.data,r)}}function ps(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function St(e,t,n){const r=new XMLHttpRequest;r.open("POST",e,!0),t instanceof Blob&&r.setRequestHeader("Content-Type",t.type),Q({allowUntrustedEvents:!0},r,"loadend",()=>{n==null||n({status:r.status})},{once:!0}),r.send(t)}function yt(){const e=hs();if(e)return{getCapabilities(){var t;return JSON.parse(((t=e.getCapabilities)===null||t===void 0?void 0:t.call(e))||"[]")},getPrivacyLevel(){var t;return(t=e.getPrivacyLevel)===null||t===void 0?void 0:t.call(e)},getAllowedWebViewHosts(){return JSON.parse(e.getAllowedWebViewHosts())},send(t,n,r){const o=r?{id:r}:void 0;e.send(JSON.stringify({eventType:t,event:n,view:o}))}}}function He(e){var t;e===void 0&&(e=(t=B().location)===null||t===void 0?void 0:t.hostname);const n=yt();return!!n&&n.getAllowedWebViewHosts().some(r=>e===r||e.endsWith(`.${r}`))}function hs(){return B().DatadogEventBridge}const ze={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function ms(e){return new O(t=>{const{stop:n}=gt(e,window,["visibilitychange","freeze"],o=>{o.type==="visibilitychange"&&document.visibilityState==="hidden"?t.notify({reason:ze.HIDDEN}):o.type==="freeze"&&t.notify({reason:ze.FROZEN})},{capture:!0}),r=Q(e,window,"beforeunload",()=>{t.notify({reason:ze.UNLOADING})}).stop;return()=>{n(),r()}})}function gs(e){return ke(ze).includes(e)}function Ss({encoder:e,request:t,flushController:n,messageBytesLimit:r}){let o={};const s=n.flushObservable.subscribe(d=>u(d));function i(d,f,h){n.notifyBeforeAddMessage(f),h!==void 0?(o[h]=d,n.notifyAfterAddMessage()):e.write(e.isEmpty?d:`\n${d}`,m=>{n.notifyAfterAddMessage(m-f)})}function a(d){return d!==void 0&&o[d]!==void 0}function c(d){const f=o[d];delete o[d];const h=e.estimateEncodedBytesCount(f);n.notifyAfterRemoveMessage(h)}function l(d,f){const h=Z(d),m=e.estimateEncodedBytesCount(h);if(m>=r){_.warn(`Discarded a message whose size was bigger than the maximum allowed size ${r}KB. ${Re} ${vt}/#technical-limitations`);return}a(f)&&c(f),i(h,m,f)}function u(d){const f=ke(o).join(`\n`);o={};const h=gs(d.reason),m=h?t.sendOnExit:t.send;if(h&&e.isAsync){const b=e.finishSync();b.outputBytesCount&&m(Cn(b));const E=[b.pendingData,f].filter(Boolean).join(`\n`);E&&m({data:E,bytesCount:Qe(E)})}else f&&e.write(e.isEmpty?f:`\n${f}`),e.finish(b=>{m(Cn(b))})}return{flushController:n,add:l,upsert:l,stop:s.unsubscribe}}function Cn(e){let t;return typeof e.output=="string"?t=e.output:t=new Blob([e.output],{type:"text/plain"}),{data:t,bytesCount:e.outputBytesCount,encoding:e.encoding}}function ys({messagesLimit:e,bytesLimit:t,durationLimit:n,pageExitObservable:r,sessionExpireObservable:o}){const s=r.subscribe(m=>u(m.reason)),i=o.subscribe(()=>u("session_expire")),a=new O(()=>()=>{s.unsubscribe(),i.unsubscribe()});let c=0,l=0;function u(m){if(l===0)return;const b=l,E=c;l=0,c=0,h(),a.notify({reason:m,messagesCount:b,bytesCount:E})}let d;function f(){d===void 0&&(d=Se(()=>{u("duration_limit")},n))}function h(){Mt(d),d=void 0}return{flushObservable:a,get messagesCount(){return l},notifyBeforeAddMessage(m){c+m>=t&&u("bytes_limit"),l+=1,c+=m,f()},notifyAfterAddMessage(m=0){c+=m,l>=e?u("messages_limit"):c>=t&&u("bytes_limit")},notifyAfterRemoveMessage(m){c-=m,l-=1,l===0&&h()}}}function vn(e,t,n,r,o,s,i=Ss){const a=l(e,t),c=n&&l(e,n);function l(u,{endpoint:d,encoder:f}){return i({encoder:f,request:us(d,u.batchBytesLimit,r),flushController:ys({messagesLimit:u.batchMessagesLimit,bytesLimit:u.batchBytesLimit,durationLimit:u.flushTimeout,pageExitObservable:o,sessionExpireObservable:s}),messageBytesLimit:u.messageBytesLimit})}return{flushObservable:a.flushController.flushObservable,add(u,d=!0){a.add(u),c&&d&&c.add(n.transformMessage?n.transformMessage(u):u)},upsert:(u,d)=>{a.upsert(u,d),c&&c.upsert(n.transformMessage?n.transformMessage(u):u,d)},stop:()=>{a.stop(),c&&c.stop()}}}function We(){let e="",t=0;return{isAsync:!1,get isEmpty(){return!e},write(n,r){const o=Qe(n);t+=o,e+=n,r&&r(o)},finish(n){n(this.finishSync())},finishSync(){const n={output:e,outputBytesCount:t,rawBytesCount:t,pendingData:""};return e="",t=0,n},estimateEncodedBytesCount(n){return n.length}}}class bs{constructor(){this.callbacks={}}notify(t,n){const r=this.callbacks[t];r&&r.forEach(o=>o(n))}subscribe(t,n){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(n),{unsubscribe:()=>{this.callbacks[t]=this.callbacks[t].filter(r=>n!==r)}}}}function Es(e,t,n){let r=0,o=!1;return{isLimitReached(){if(r===0&&Se(()=>{r=0},K),r+=1,r<=t||o)return o=!1,!1;if(r===t+1){o=!0;try{n({message:`Reached max number of ${e}s by minute: ${t}`,source:L.AGENT,startClocks:U()})}finally{o=!1}}return!0}}}let bt;const Et=new WeakMap;function Ts(e){return bt||(bt=_s(e)),bt}function _s(e){return new O(t=>{const{stop:n}=V(XMLHttpRequest.prototype,"open",ws),{stop:r}=V(XMLHttpRequest.prototype,"send",s=>{Os(s,e,t)},{computeHandlingStack:!0}),{stop:o}=V(XMLHttpRequest.prototype,"abort",Rs);return()=>{n(),r(),o()}})}function ws({target:e,parameters:[t,n]}){Et.set(e,{state:"open",method:String(t).toUpperCase(),url:ut(String(n))})}function Os({target:e,handlingStack:t},n,r){const o=Et.get(e);if(!o)return;const s=o;s.state="start",s.startClocks=U(),s.isAborted=!1,s.xhr=e,s.handlingStack=t;let i=!1;const{stop:a}=V(e,"onreadystatechange",()=>{e.readyState===XMLHttpRequest.DONE&&c()}),c=()=>{if(l(),a(),i)return;i=!0;const u=o;u.state="complete",u.duration=jn(s.startClocks.timeStamp,F()),u.status=e.status,r.notify(Kn(u))},{stop:l}=Q(n,e,"loadend",c);r.notify(s)}function Rs({target:e}){const t=Et.get(e);t&&(t.isAborted=!0)}let Tt;function Ln(){return Tt||(Tt=Cs()),Tt}function Cs(){return new O(e=>{if(!window.fetch)return;const{stop:t}=V(window,"fetch",n=>vs(n,e),{computeHandlingStack:!0});return t})}function vs({parameters:e,onPostCall:t,handlingStack:n},r){const[o,s]=e;let i=s&&s.method;i===void 0&&o instanceof Request&&(i=o.method);const a=i!==void 0?String(i).toUpperCase():"GET",c=o instanceof Request?o.url:ut(String(o)),l=U(),u={state:"start",init:s,input:o,method:a,startClocks:l,url:c,handlingStack:n};r.notify(u),e[0]=u.input,e[1]=u.init,t(d=>Ls(r,d,u))}function Ls(e,t,n){const r=n;function o(s){r.state="resolve",Object.assign(r,s),e.notify(r)}t.then(y(s=>{o({response:s,responseType:s.type,status:s.status,isAborted:!1})}),y(s=>{var i,a;o({status:0,isAborted:((a=(i=r.init)===null||i===void 0?void 0:i.signal)===null||a===void 0?void 0:a.aborted)||s instanceof DOMException&&s.code===DOMException.ABORT_ERR,error:s})}))}let _t={};function Is(e){const t=e.map(n=>(_t[n]||(_t[n]=As(n)),_t[n]));return $t(...t)}function As(e){return new O(t=>{const n=x[e];return x[e]=(...r)=>{n.apply(console,r);const o=Ue("console error");ge(()=>{t.notify(ks(r,e,o))})},()=>{x[e]=n}})}function ks(e,t,n){const r=e.map(s=>xs(s)).join(" ");let o;if(t===T.error){const s=e.find(H);o={stack:s?X(M(s)):void 0,fingerprint:nn(s),causes:s?on(s,"console"):void 0,startClocks:U(),message:r,source:L.CONSOLE,handling:"handled",handlingStack:n,context:rn(s)}}return{api:t,message:r,error:o,handlingStack:n}}function xs(e){return typeof e=="string"?N(e):H(e)?Qt(M(e)):Z(N(e),void 0,2)}function Ds(e){const t=ln(e)==="object";return t||_.error("Unsupported context:",e),t}function wt(e,t,n){const r={...e};for(const[o,{required:s,type:i}]of Object.entries(t))i==="string"&&o in r&&(r[o]=String(r[o])),s&&!(o in e)&&_.warn(`The property ${o} of ${n} is required; context will not be sent to the intake.`);return r}function Ke(e="",{customerDataTracker:t,propertiesConfig:n={}}={}){let r={};const o=new O,s={getContext:()=>dn(r),setContext:i=>{Ds(i)?(r=N(wt(i,n,e)),t==null||t.updateCustomerData(r)):s.clearContext(),o.notify()},setContextProperty:(i,a)=>{r=N(wt({...r,[i]:a},n,e)),t==null||t.updateCustomerData(r),o.notify()},removeContextProperty:i=>{delete r[i],t==null||t.updateCustomerData(r),wt(r,n,e),o.notify()},clearContext:()=>{r={},t==null||t.resetCustomerData(),o.notify()},changeObservable:o};return s}const Ms="_dd_c",Ns=[];function Ot(e,t,n,r){const o=$s(n,r);Ns.push(Q(e,window,"storage",({key:l})=>{o===l&&i()})),t.changeObservable.subscribe(a);const s=ae(c(),t.getContext());me(s)||t.setContext(s);function i(){t.setContext(c())}function a(){localStorage.setItem(o,JSON.stringify(t.getContext()))}function c(){const l=localStorage.getItem(o);return l?JSON.parse(l):{}}}function $s(e,t){return`${Ms}_${e}_${t}`}const Ps=3*D,Fs=16*D,Us=200;function Bs(e=2){const t=new Map;let n=!1;function r(o=0){if(n||e===0)return;const s=e===2?Ps:Fs;let i=o;t.forEach(a=>{i+=a.getBytesCount()}),i>s&&(Gs(s),n=!0)}return{createDetachedTracker:()=>{const o=In(()=>r(o.getBytesCount()));return o},getOrCreateTracker:o=>(t.has(o)||t.set(o,In(r)),t.get(o)),setCompressionStatus:o=>{e===0&&(e=o,r())},getCompressionStatus:()=>e,stop:()=>{t.forEach(o=>o.stop()),t.clear()}}}function In(e){let t=0;const{throttled:n,cancel:r}=Pt(s=>{t=Qe(Z(s)),e()},Us),o=()=>{r(),t=0};return{updateCustomerData:s=>{me(s)?o():n(s)},resetCustomerData:o,getBytesCount:()=>t,stop:()=>{r()}}}function Gs(e){_.warn(`Customer data exceeds the recommended ${e/D}KiB threshold. ${Re} ${vt}/#customer-data-exceeds-the-recommended-threshold-warning`)}function js(e,t,n){const r=e.getReader(),o=[];let s=0;i();function i(){r.read().then(y(c=>{if(c.done){a();return}o.push(c.value),s+=c.value.length,s>n.bytesLimit?a():i()}),y(c=>t(c)))}function a(){r.cancel().catch(G);let c,l;{let u;if(o.length===1)u=o[0];else{u=new Uint8Array(s);let d=0;o.forEach(f=>{u.set(f,d),d+=f.length})}c=u.slice(0,n.bytesLimit),l=u.length>n.bytesLimit}t(void 0,c,l)}}const Hs="datadog-synthetics-public-id",zs="datadog-synthetics-result-id",Ws="datadog-synthetics-injects-rum";function An(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||J(Ws))}function Ks(){const e=window._DATADOG_SYNTHETICS_PUBLIC_ID||J(Hs);return typeof e=="string"?e:void 0}function Js(){const e=window._DATADOG_SYNTHETICS_RESULT_ID||J(zs);return typeof e=="string"?e:void 0}function Je(e,t,n){const r=n.getHandler(),o=Array.isArray(r)?r:[r];return kn[e]>=kn[n.getLevel()]&&o.includes(t)}const g={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},kn={[g.ok]:0,[g.debug]:1,[g.info]:2,[g.notice]:4,[g.warn]:5,[g.error]:6,[g.critical]:7,[g.alert]:8,[g.emerg]:9};function qe(e,{includeMessage:t=!1}={}){return{stack:e.stack,kind:e.type,message:t?e.message:void 0,causes:e.causes,fingerprint:e.fingerprint,handling:e.handling}}var qs=function(e,t,n,r){var o=arguments.length,s=o<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s};const Oe={console:"console",http:"http",silent:"silent"},Ys=Object.keys(g);let A=class{constructor(t,n,r,o=Oe.http,s=g.debug,i={}){this.handleLogStrategy=t,this.handlerType=o,this.level=s,this.contextManager=Ke("logger",{customerDataTracker:n}),this.contextManager.setContext(i),r&&this.contextManager.setContextProperty("logger",{name:r})}logImplementation(t,n,r=g.info,o,s){const i=N(n);let a;if(o!=null){const c=tn({stackTrace:H(o)?M(o):void 0,originalError:o,nonErrorPrefix:"Provided",source:L.LOGGER,handling:"handled",startClocks:U()});a=ae({error:qe(c,{includeMessage:!0})},i)}else a=i;this.handleLogStrategy({message:N(t),context:a,status:r},this,s)}log(t,n,r=g.info,o){let s;Je(r,Oe.http,this)&&(s=Ue("log")),this.logImplementation(t,n,r,o,s)}setContext(t){this.contextManager.setContext(t)}getContext(){return this.contextManager.getContext()}setContextProperty(t,n){this.contextManager.setContextProperty(t,n)}removeContextProperty(t){this.contextManager.removeContextProperty(t)}clearContext(){this.contextManager.clearContext()}setHandler(t){this.handlerType=t}getHandler(){return this.handlerType}setLevel(t){this.level=t}getLevel(){return this.level}};qs([Yn],A.prototype,"logImplementation",null),A.prototype.ok=$(g.ok),A.prototype.debug=$(g.debug),A.prototype.info=$(g.info),A.prototype.notice=$(g.notice),A.prototype.warn=$(g.warn),A.prototype.error=$(g.error),A.prototype.critical=$(g.critical),A.prototype.alert=$(g.alert),A.prototype.emerg=$(g.emerg);function $(e){return function(t,n,r){let o;Je(e,Oe.http,this)&&(o=Ue("log")),this.logImplementation(t,n,e,r,o)}}function Zs(e,t,n){return{view:{referrer:document.referrer,url:window.location.href},context:e.getContext(),user:t.getContext(),account:n.getContext()}}const Xs=32*D;function Vs(e){e.usePciIntake===!0&&e.site&&e.site!=="datadoghq.com"&&_.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");const t=Yr(e),n=xn(e.forwardConsoleLogs,ke(T),"Forward Console Logs"),r=xn(e.forwardReports,ke(Be),"Forward Reports");if(!(!t||!n||!r))return e.forwardErrorsToLogs&&!n.includes(T.error)&&n.push(T.error),{forwardErrorsToLogs:e.forwardErrorsToLogs!==!1,forwardConsoleLogs:n,forwardReports:r,requestErrorResponseLengthLimit:Xs,...t}}function xn(e,t,n){if(e===void 0)return[];if(!(e==="all"||Array.isArray(e)&&e.every(r=>t.includes(r)))){_.error(`${n} should be "all" or an array with allowed values "${t.join(\'", "\')}"`);return}return e==="all"?t:No(e)}function Qs(e){const t=Zr(e);return{forward_errors_to_logs:e.forwardErrorsToLogs,forward_console_logs:e.forwardConsoleLogs,forward_reports:e.forwardReports,use_pci_intake:e.usePciIntake,...t}}function ei(e,t,n){const r=pn();let o,s;const i=t.observable.subscribe(a);function a(){if(!s||!o||!t.isGranted())return;i.unsubscribe();const c=n(o,s);r.drain(c)}return{init(c){if(!c){_.error("Missing configuration");return}if(Xr(c.enableExperimentalFeatures),He()&&(c=ti(c)),o=c,s){sn("DD_LOGS",c);return}const l=Vs(c);l&&(s=l,Ln().subscribe(G),t.tryToInit(l.trackingConsent),a())},get initConfiguration(){return o},getInternalContext:G,handleLog(c,l,u,d=e(),f=F()){r.add(h=>h.handleLog(c,l,u,d,f))}}}function ti(e){return{...e,clientToken:"empty"}}const Rt="logs";function ni(e){const t=Bs(),n=Ke("global context",{customerDataTracker:t.getOrCreateTracker(2)}),r=Ke("user",{customerDataTracker:t.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),o=Ke("account",{customerDataTracker:t.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),s=Ir();function i(){return Zs(n,r,o)}let a=ei(i,s,(u,d)=>{u.storeContextsAcrossPages&&(Ot(d,n,Rt,2),Ot(d,r,Rt,1),Ot(d,o,Rt,4));const f=e(u,d,i,s);return a=ri(u,f),f});const c={},l=new A((...u)=>a.handleLog(...u),t.createDetachedTracker());return Co({logger:l,init:y(u=>a.init(u)),setTrackingConsent:y(u=>{s.update(u),zo({feature:"set-tracking-consent",tracking_consent:u})}),getGlobalContext:y(()=>n.getContext()),setGlobalContext:y(u=>n.setContext(u)),setGlobalContextProperty:y((u,d)=>n.setContextProperty(u,d)),removeGlobalContextProperty:y(u=>n.removeContextProperty(u)),clearGlobalContext:y(()=>n.clearContext()),createLogger:y((u,d={})=>(c[u]=new A((...f)=>a.handleLog(...f),t.createDetachedTracker(),N(u),d.handler,d.level,N(d.context)),c[u])),getLogger:y(u=>c[u]),getInitConfiguration:y(()=>dn(a.initConfiguration)),getInternalContext:y(u=>a.getInternalContext(u)),setUser:y(r.setContext),getUser:y(r.getContext),setUserProperty:y(r.setContextProperty),removeUserProperty:y(r.removeContextProperty),clearUser:y(r.clearContext),setAccount:y(o.setContext),getAccount:y(o.getContext),setAccountProperty:y(o.setContextProperty),removeAccountProperty:y(o.removeContextProperty),clearAccount:y(o.clearContext)})}function ri(e,t){return{init:n=>{sn("DD_LOGS",n)},initConfiguration:e,...t}}const oi="logs";function si(e,t){const n=Vo(e,oi,r=>ai(e,r),t);return{findTrackedSession:(r,o={returnInactive:!1})=>{const s=n.findSession(r,o);return s&&s.trackingType==="1"?{id:s.id,anonymousId:s.anonymousId}:void 0},expireObservable:n.expireObservable}}function ii(e){const n=Dn(e)==="1"?{}:void 0;return{findTrackedSession:()=>n,expireObservable:new O}}function Dn(e){return Ce(e.sessionSampleRate)?"1":"0"}function ai(e,t){const n=ci(t)?t:Dn(e);return{trackingType:n,isTracked:n==="1"}}function ci(e){return e==="0"||e==="1"}let Mn=!1;function Ye(e){const t=window;if(An()){const r=n(t.DD_RUM_SYNTHETICS);return!r&&!Mn&&(Mn=!0,mn("Logs sent before RUM is injected by the synthetics worker",{testId:Ks(),resultId:Js()})),r}return n(t.DD_RUM);function n(r){if(r&&r.getInternalContext)return r.getInternalContext(e)}}function ui(e,t,n,r,o){const s=Ys.concat(["custom"]),i={};s.forEach(a=>{i[a]=Es(a,t.eventRateLimiterThreshold,o)}),n.subscribe(0,({rawLogsEvent:a,messageContext:c=void 0,savedCommonContext:l=void 0,domainContext:u})=>{var d,f;const h=zn(a.date),m=e.findTrackedSession(h);if(!e.findTrackedSession(h,{returnInactive:!0}))return;const E=l||r();let z;!me(E.account)&&E.account.id&&(z=E.account),m&&m.anonymousId&&!E.user.anonymous_id&&(E.user.anonymous_id=m.anonymousId);const v=ae({service:t.service,session_id:m?m.id:void 0,session:m?{id:m.id}:void 0,usr:me(E.user)?void 0:E.user,account:z,view:E.view},E.context,Ye(h),a,c);((d=t.beforeSend)===null||d===void 0?void 0:d.call(t,v,u))===!1||v.origin!==L.AGENT&&((f=i[v.status])!==null&&f!==void 0?f:i.custom).isLimitReached()||n.notify(1,v)})}const li={[T.log]:g.info,[T.debug]:g.debug,[T.info]:g.info,[T.warn]:g.warn,[T.error]:g.error};function di(e,t){const n=Is(e.forwardConsoleLogs).subscribe(r=>{var o;const s={rawLogsEvent:{date:F(),message:r.message,origin:L.CONSOLE,error:r.error&&qe(r.error),status:li[r.api]},messageContext:(o=r.error)===null||o===void 0?void 0:o.context,domainContext:{handlingStack:r.handlingStack}};t.notify(0,s)});return{stop:()=>{n.unsubscribe()}}}function fi(e,t){const n=Lo(e,e.forwardReports).subscribe(r=>{let o=r.message,s;const i=r.originalError.type==="deprecation"?g.warn:g.error;i===g.error?s=qe(r):r.stack&&(o+=` Found in ${_o(r.stack)}`),t.notify(0,{rawLogsEvent:{date:F(),message:o,origin:L.REPORT,error:s,status:i}})});return{stop:()=>{n.unsubscribe()}}}function pi(e,t){if(!e.forwardErrorsToLogs)return{stop:G};const n=Ts(e).subscribe(s=>{s.state==="complete"&&o("xhr",s)}),r=Ln().subscribe(s=>{s.state==="resolve"&&o("fetch",s)});function o(s,i){!Jr(i.url)&&(Si(i)||Sn(i.status))&&("xhr"in i?hi(i.xhr,e,a):i.response?gi(i.response,e,a):i.error&&mi(i.error,e,a));function a(c){const l={isAborted:i.isAborted,handlingStack:i.handlingStack};t.notify(0,{rawLogsEvent:{message:`${yi(s)} error ${i.method} ${i.url}`,date:i.startClocks.timeStamp,error:{stack:c||"Failed to load",handling:void 0},http:{method:i.method,status_code:i.status,url:i.url},status:g.error,origin:L.NETWORK},domainContext:l})}}return{stop:()=>{n.unsubscribe(),r.unsubscribe()}}}function hi(e,t,n){typeof e.response=="string"?n(Ct(e.response,t)):n(e.response)}function mi(e,t,n){n(Ct(X(M(e)),t))}function gi(e,t,n){const r=ns(e);!r||!r.body?n():window.TextDecoder?bi(r.body,t.requestErrorResponseLengthLimit,(o,s)=>{n(o?`Unable to retrieve response: ${o}`:s)}):r.text().then(y(o=>n(Ct(o,t))),y(o=>n(`Unable to retrieve response: ${o}`)))}function Si(e){return e.status===0&&e.responseType!=="opaque"}function Ct(e,t){return e.length>t.requestErrorResponseLengthLimit?`${e.substring(0,t.requestErrorResponseLengthLimit)}...`:e}function yi(e){return e==="xhr"?"XHR":"Fetch"}function bi(e,t,n){js(e,(r,o,s)=>{if(r)n(r);else{let i=new TextDecoder().decode(o);s&&(i+="..."),n(void 0,i)}},{bytesLimit:t,collectStreamBody:!0})}function Ei(e,t){if(!e.forwardErrorsToLogs)return{stop:G};const n=new O,{stop:r}=wo(n),o=n.subscribe(s=>{t.notify(0,{rawLogsEvent:{message:s.message,date:s.startClocks.timeStamp,error:qe(s),origin:L.SOURCE,status:g.error},messageContext:s.context})});return{stop:()=>{r(),o.unsubscribe()}}}const Ti=bs;function _i(e){function t(n,r,o,s,i){const a=ae(r.getContext(),n.context);if(Je(n.status,Oe.console,r)&&Oi(n,a),Je(n.status,Oe.http,r)){const c={rawLogsEvent:{date:i||F(),message:n.message,status:n.status,origin:L.LOGGER},messageContext:a,savedCommonContext:s};o&&(c.domainContext={handlingStack:o}),e.notify(0,c)}}return{handleLog:t}}const wi={[g.ok]:T.debug,[g.debug]:T.debug,[g.info]:T.info,[g.notice]:T.info,[g.warn]:T.warn,[g.error]:T.error,[g.critical]:T.error,[g.alert]:T.error,[g.emerg]:T.error};function Oi({status:e,message:t},n){W[wi[e]].call(x,t,n)}function Ri(e,t,n,r,o){const s=vn(e,{endpoint:e.logsEndpointBuilder,encoder:We()},e.replica&&{endpoint:e.replica.logsEndpointBuilder,encoder:We()},n,r,o.expireObservable);return t.subscribe(1,i=>{s.add(i)}),s}function Ci(e){const t=yt();e.subscribe(1,n=>{t.send("log",n)})}function vi(e){return{get:t=>{const n=e.findTrackedSession(t);if(n)return{session_id:n.id}}}}function Li(e){return t=>{e.notify(0,{rawLogsEvent:{message:t.message,date:t.startClocks.timeStamp,origin:L.AGENT,status:g.error}}),mn("Error reported to customer",{"error.message":t.message})}}function Ii(e,t,n,r,o){const s=Uo("browser-logs-sdk",t);s.setContextProvider(()=>{var a,c,l,u,d,f;return{application:{id:(a=Ye())===null||a===void 0?void 0:a.application_id},session:{id:(c=o.findTrackedSession())===null||c===void 0?void 0:c.id},view:{id:(u=(l=Ye())===null||l===void 0?void 0:l.view)===null||u===void 0?void 0:u.id},action:{id:(f=(d=Ye())===null||d===void 0?void 0:d.user_action)===null||f===void 0?void 0:f.id}}});const i=[];if(He()){const a=yt(),c=s.observable.subscribe(l=>a.send("internal_telemetry",l));i.push(()=>c.unsubscribe())}else{const a=vn(t,{endpoint:t.rumEndpointBuilder,encoder:We()},t.replica&&{endpoint:t.replica.rumEndpointBuilder,encoder:We()},n,r,o.expireObservable);i.push(()=>a.stop());const c=s.observable.subscribe(l=>a.add(l,jo(t)));i.push(()=>c.unsubscribe())}return Go(),Ho(Qs(e)),{telemetry:s,stop:()=>{i.forEach(a=>a())}}}function Ai(e,t,n,r){const o=new Ti,s=[];o.subscribe(1,f=>un("logs",f));const i=Li(o),a=ms(t),c=t.sessionStoreStrategyType&&!He()&&!An()?si(t,r):ii(t),{stop:l}=Ii(e,t,i,a,c);s.push(()=>l()),pi(t,o),Ei(t,o),di(t,o),fi(t,o);const{handleLog:u}=_i(o);if(ui(c,t,o,n,i),He())Ci(o);else{const{stop:f}=Ri(t,o,i,a,c);s.push(()=>f())}const d=vi(c);return{handleLog:u,getInternalContext:d.get,stop:()=>{s.forEach(f=>f())}}}const ue=ni(Ai);vo(B(),"DD_LOGS",ue);const R=class R{constructor(t,n,r,o,s){this.copy=()=>new R(this.h,this.m,this.s,this.f,this.field),this.print=()=>{const i=":";let a=("0"+this.h).slice(-2)+i+("0"+this.m).slice(-2)+i+("0"+this.s).slice(-2)+i+("0"+this.f).slice(-2);return a+="."+(this.field?"1":"2"),a},this.toZipTimeCodeString=()=>{const i=this.copy();return i.f=0,i.s=i.s%2===0?i.s:i.s-1,i.field=0,R.toStr(i)},this.toFrames=i=>{let a=60,c=0;Math.floor(i)==60?(a=60,c=0):Math.floor(i)==59?(a=60,c=4):Math.floor(i)==30?(a=30,c=0):Math.floor(i)==29&&(a=30,c=2);let l=this.h,u=this.m,d=this.s,f=this.f,h=this.field;const m=l*60+u,E=(m-Math.floor(m/10))*c;return l*(a*3600)+u*(a*60)+d*a+(f*2+h)-E},this.addSeconds=i=>{let a=this.copy();if(a.s+=i,a.s>=60){const c=Math.floor(a.s/60);if(a.s=a.s%60,a.m+=c,a.m>=60){const l=Math.floor(a.m/60);a.m=a.m%60,a.h+=l}}return a},this.addFrames=(i,a)=>{let c=this.toFrames(a);return c+=i,R.fromFrames(c,a)},this.subtractFrames=(i,a)=>this.addFrames(-i,a),this.h=t||0,this.m=n||0,this.s=r||0,this.f=o||0,this.field=s||0}static compare(t,n){return t.h!==n.h?t.h<n.h?-1:1:t.m!==n.m?t.m<n.m?-1:1:t.s!==n.s?t.s<n.s?-1:1:t.f!==n.f?t.f<n.f?-1:1:t.field!==n.field?t.field<n.field?-1:1:0}static generateTimecodeRange(t,n,r){const o=[];let s=t;for(;R.compare(s,n)<=0;)o.push(s),s=s.addSeconds(r);return o}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(t){return this.toFrames(t)*1e3/t}};R.calculateCurrentTimeCode=t=>{var d;if(!t.video||!t.clocker||!t.gameParams)throw new Error("OTTPlayer is not initialized");const n=t.video,r=t.clocker,o=r.videoFPScalculator.getFPS(),a=(n.currentTime-r.syncPoint.playerTime)%(60*60*24)*o+r.syncPoint.frame;if(a===0||o===0)throw new Error("Current frame is 0 or fps is 0");const c=R.calculateCurrentOffset(a,(d=t.gameParams)==null?void 0:d.offsets);if(c===void 0)throw new Error("Offset is undefined");let l=Math.floor(a-c);return l<0&&(l+=5178816),l>=5178816&&(l-=5178816),R.fromFrames(l,o)},R.calculateCurrentOffset=(t,n)=>{for(let r=1;r<n.length;r++)if(t<n[r].frame)return n[r-1].offset;return Math.abs(n[n.length-1].offset)},R.fromFrames=(t,n)=>{let r=60,o=0;Math.floor(n)==60?(r=60,o=0):Math.floor(n)==59?(r=60,o=4):Math.floor(n)==30?(r=30,o=0):Math.floor(n)==29&&(r=30,o=2);let s=Math.floor(n*60),i=Math.floor(n*60*10),a=i*6,c=t,l=Math.floor(c/a);c-=l*a;let u=Math.floor(c/i);c-=u*i,c>=r*60&&(c+=o*(Math.floor((c-r*60)/s)+1));let d=Math.floor(c/(r*60));c-=d*(r*60);let f=Math.floor(c/r);c-=f*r;let h=c;d+=u*10;let m=0;return m=h%2,h=Math.floor(h/2),new R(l,d,f,h,m)},R.toStr=t=>{const n="_";let r=("0"+t.h).slice(-2)+n+("0"+t.m).slice(-2)+n+("0"+t.s).slice(-2)+n+("0"+t.f).slice(-2);return t.field&&(r+="_1"),r},R.fromStr=t=>{const r=t.split("_").map(Number);if(r.length==4){const[o,s,i,a]=r;return new R(o,s,i,a,0)}else if(r.length==5){const[o,s,i,a,c]=r;return new R(o,s,i,a,c)}else throw new Error("Invalid timecode format: "+t)},R.fromMetadata=t=>{const n=/^(\\d{2}):(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d))?$/,r=t.timecode.match(n);if(!r)throw new Error("Invalid timecode format: "+t.timecode);const[,o,s,i,a,c]=r,l=Number(o),u=Number(s),d=Number(i),f=Number(a),h=c?Number(c):0;return new R(l,u,d,f,h)};let C=R;const p=class p{constructor(t){this.listenerMap=new Map,p.options=t,this.isLoggingOn=t.LOG_TO_DATADOG,this.eventTarget=new EventTarget,this.isLoggingOn&&ue.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!1,sessionSampleRate:100});const n="bb_logger_mac_uuid";let r=localStorage.getItem(n);r||(r=crypto.randomUUID(),localStorage.setItem(n,r)),p.tracking.mac=r,p.tracking.dev=`${t.platform}_${t.browserName}`,p.beatHandle||(p.options&&w(p.options,"Logger")&&console.log("[Logger] Starting tracking beat"),p.beatHandle=window.setInterval(p.flushTracking,15e3))}static setMessagePort(t){this.messagePort=t}static getMessagePort(){return this.messagePort}setLoggingOn(t){this.isLoggingOn=t}addEventListener(t,n){const r=o=>n(o);this.listenerMap.set(n,{eventName:t,wrappedListener:r}),this.eventTarget.addEventListener(t,r)}removeEventListener(t,n){const r=this.listenerMap.get(n);r&&r.eventName===t&&(this.eventTarget.removeEventListener(t,r.wrappedListener),this.listenerMap.delete(n))}removeAllEventListeners(){for(const[t,{eventName:n,wrappedListener:r}]of this.listenerMap)this.eventTarget.removeEventListener(n,r);this.listenerMap.clear()}setAttributes(t){p.processAttributes(t);for(const n in t)ue.logger.setContextProperty(n,t[n])}info(t,n){t==="didClickAd"&&this.emit("mediaSessionDidRegisterClick",{url:(n==null?void 0:n.url)||""}),t==="didToggleGlobalAugmentationDrawing"&&this.emit("mediaSessionDidUpdateGlobalAugmentationState",{isGlobalAugmentationEnabled:(n==null?void 0:n.isEnabled)||!0}),t==="didStartDrawingAugmentationMedia"&&this.emit("mediaSessionDidBeginShotRendering",n),t==="didEndDrawingAugmentationMedia"&&this.emit("mediaSessionDidEndShotRendering",n),t==="didRegisterShot"&&this.emit("mediaSessionDidRegisterShot",n),n&&p.processAttributes(n),this.isLoggingOn&&(ue.logger.info(t,n),p.options&&w(p.options,"Logger")&&console.log("[Logger] Sending info: ",t))}error(t,n){n&&p.processAttributes(n),this.isLoggingOn&&(ue.logger.error(t,n),p.tracking.err_time=Date.now().toFixed(0),p.tracking.err_desc=t+(n?` - ${JSON.stringify(n)}`:""),p.options&&w(p.options,"Logger")&&console.log("[Logger] Sending error: ",t))}warn(t,n){n&&p.processAttributes(n),this.isLoggingOn&&(ue.logger.warn(t,n),p.options&&w(p.options,"Logger")&&console.log("[Logger] Sending warn: ",t))}handleMessageFromWorker(t){t.actionType==="INFO"?this.info(t.message,t.attributes):t.actionType==="ERROR"?this.error(t.message,t.attributes):t.actionType==="WARN"?this.warn(t.message,t.attributes):t.actionType==="SET_ATTRIBUTES"&&t.attributes&&this.setAttributes(t.attributes)}static setAttributes(t){if(!p.messagePort){console.error("[Logger] messagePort is not set! Cannot send attributes.");return}try{p.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:t})}catch(n){console.error("[Logger] Error posting message:",n)}}static info(t,n){p.messagePort.postMessage({type:"LOG",actionType:"INFO",message:t,attributes:n})}static error(t,n){p.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:t,attributes:n})}static warn(t,n){p.messagePort.postMessage({type:"LOG",actionType:"WARN",message:t,attributes:n})}static processAttributes(t){if(t.player_version&&(p.tracking.sdk=t.player_version),t.media_id&&(p.tracking.gid=t.media_id),t.game_id&&(p.tracking.buc=t.game_id),t.bb_session_id&&(p.tracking.sid=t.bb_session_id,p.options&&w(p.options,"Logger")&&console.log("[Logger] Setting bb_session_id:",p.tracking.sid)),t.last_timecode){const r=C.fromStr(t.last_timecode);p.tracking.tc=r.print(),p.lastTimecodeMillis=r.totalMilliseconds(59.94),p.lastTimecodeMillis&&p.lastZipMillis&&(p.tracking.cache=(p.lastZipMillis-p.lastTimecodeMillis).toFixed(0))}t.last_offset&&(p.tracking.off=t.last_offset),t.last_loading_zip&&(p.tracking.zip=t.last_loading_zip+".zip",p.lastZipMillis=C.fromStr(t.last_loading_zip).totalMilliseconds(59.94),p.lastTimecodeMillis&&p.lastZipMillis&&(p.tracking.cache=(p.lastZipMillis-p.lastTimecodeMillis).toFixed(0))),t.last_rendered_frame&&(p.tracking.aug_time=Date.now().toFixed(0)),t.asset&&(p.tracking.asset=t.asset)}static objectToQuery(t){return Object.entries(t).filter(([n,r])=>r!==0&&r!=="").map(([n,r])=>`${encodeURIComponent(n)}=${encodeURIComponent(String(r))}`).join("&")}emit(t,n){const r=new CustomEvent(t,{detail:n});this.eventTarget.dispatchEvent(r)}};p.tracking={start:Date.now().toFixed(0),dev:"",sdk:"",mac:"",gid:"",sid:"",off:"",zip:"",aug_time:"",err_time:"",err_desc:"",tc:"",asset:"",cache:"",buc:""},p.lastTimecodeMillis=0,p.lastZipMillis=0,p.flushTracking=()=>{const t=Date.now().toFixed(0);p.tracking.now=t;const r=`https://dwu3k7rrxk5s3.cloudfront.net/metrics/1.gif?${p.objectToQuery(p.tracking)}`;p.options&&w(p.options,"Logger")&&console.log("[Logger] Flushing tracking data:",r),fetch(r,{method:"GET",mode:"no-cors",keepalive:!0,headers:{"X-Platform":"Web"}}).catch(()=>{}),p.tracking.err_desc="",p.tracking.err_time=""};let I=p;class Nn{constructor(t,n,r){this.jobsQueue=[],this.processedTimecodes=[],this.retryingTimecodes=new Set,this.permanentlyFailedTimecodes=new Set,this.activeDownloads=new Set,this.pendingRetryTimeouts=new Map,this.downloaderStopped=!1,this.firstDownload=!0,this.updateStreamData=o=>{this.downloaderStopped||(this.streamData=o,this.initiateJobs(this.options.DOWNLOADER_ZIP_START_OFFSET,this.options.DOWNLOADER_ZIP_END_OFFSET,this.options.DOWNLOADER_ZIP_LENGTH_SECONDS),this.clearOldJobs(1),this.notifyZipBufferStatus(),this.startNextJob())},this.initiateJobs=(o,s,i)=>{if(!this.streamData){I.error("[Downloader] Stream data is not available"),this.options&&w(this.options,"Errors")&&console.error("[Downloader] Stream data is not available");return}const a=C.fromStr(this.streamData.timeCode),c=a.addSeconds(o),l=a.addSeconds(s),u=C.generateTimecodeRange(c,l,i);for(const d of u){const f=d.toZipTimeCodeString();this.processedTimecodes.includes(f)||this.addJob(f)}},this.clearOldJobs=o=>{if(!this.streamData){I.error("[Downloader] Stream data is not available"),this.options&&w(this.options,"Errors")&&console.error("[Downloader] Stream data is not available");return}const i=C.fromStr(this.streamData.timeCode).totalSeconds()-o;this.processedTimecodes=this.processedTimecodes.filter(l=>C.fromStr(l).totalSeconds()>i),Array.from(this.retryingTimecodes).filter(l=>C.fromStr(l).totalSeconds()<=i).forEach(l=>this.retryingTimecodes.delete(l)),Array.from(this.permanentlyFailedTimecodes).filter(l=>C.fromStr(l).totalSeconds()<=i).forEach(l=>this.permanentlyFailedTimecodes.delete(l))},this.clearAllJobs=()=>{this.jobsQueue=[],this.processedTimecodes=[],this.retryingTimecodes.clear(),this.permanentlyFailedTimecodes.clear(),this.activeDownloads.clear(),this.pendingRetryTimeouts.forEach(o=>clearTimeout(o)),this.pendingRetryTimeouts.clear()},this.addJob=o=>{if(!this.downloaderStopped){if(this.jobsQueue.some(s=>s===o)){this.options&&w(this.options,"Downloader")&&console.log(`[Downloader] Job already in queue for timeCode=${o}`);return}if(this.activeDownloads.has(o)){this.options&&w(this.options,"Downloader")&&console.log(`[Downloader] Job already downloading for timeCode=${o}`);return}this.jobsQueue.push(o),this.startNextJob()}},this.startNextJob=()=>{if(!this.downloaderStopped&&this.jobsQueue.length>0){const o=this.jobsQueue.shift();this.options&&w(this.options,"Downloader")&&console.log(`[Downloader] Starting job timeCode=${o}`),this.downloadZip(o)}},this.downloadZip=async o=>{if(!this.streamData){I.error("[Downloader] Stream data is not available"),this.options&&w(this.options,"Errors")&&console.error("[Downloader] Stream data is not available");return}this.activeDownloads.add(o),this.firstDownload&&(this.firstDownload=!1,I.info("didStartAugmentationDownload",{timestamp:o}));const{fps:s,zipBaseURL:i,bucketName:a}=this.streamData,c=async(l=0)=>{const u=this.shouldBeFinalRetry(o,60);try{if(this.options&&w(this.options,"Downloader")){const h=l>0?` (retry ${l}${u?", final":""})`:"";console.log(`[Downloader] Fetching zip for timeCode=${o}${h}`)}const d=await this.fetchMetadata(i,a,s,o,u);if(this.downloaderStopped)return;this.retryingTimecodes.delete(o),this.activeDownloads.delete(o);const f=this.pendingRetryTimeouts.get(o);f!==void 0&&(clearTimeout(f),this.pendingRetryTimeouts.delete(o)),this.processedTimecodes.includes(o)||this.processedTimecodes.push(o),this.postArrayBufferToDecoder(o,d),I.setAttributes({last_loading_zip:o}),this.notifyZipBufferStatus(),this.startNextJob()}catch(d){if(l===0&&this.retryingTimecodes.add(o),this.downloaderStopped){this.options&&w(this.options,"Downloader")&&console.log("[Downloader] Stopping retry - downloader has been stopped"),this.startNextJob();return}if(u){I.error("[Downloader] Error fetching zip",{error:d.message||d}),this.options&&w(this.options,"Errors")&&console.error("[Downloader] Error fetching zip:",d),this.retryingTimecodes.delete(o),this.permanentlyFailedTimecodes.add(o),this.activeDownloads.delete(o);const h=this.pendingRetryTimeouts.get(o);h!==void 0&&(clearTimeout(h),this.pendingRetryTimeouts.delete(o)),this.notifyZipBufferStatus(),this.startNextJob();return}const f=setTimeout(()=>{this.pendingRetryTimeouts.delete(o),c(l+1)},1e3);this.pendingRetryTimeouts.set(o,f)}};await c()},this.shouldBeFinalRetry=(o,s)=>{var d;if(!((d=this.streamData)!=null&&d.timeCode))return!1;const i=C.fromStr(o),a=C.fromStr(this.streamData.timeCode),c=i.toFrames(s),l=a.toFrames(s);return c-l<=60},this.fetchMetadata=async(o,s,i,a,c=!1)=>{const u=`${`${o}/${s}`}/${this.options.BUCKET_SUBFOLDER_PATH}${a}.zip`,d=performance.now();let f;const h=this.options.SEND_METRICS?{"X-Platform":"Web"}:{},m=!!(this.options.authEmail&&this.options.authPassword);if(this.options.SEND_METRICS){let v="";if(this.streamData&&this.streamData.timeCode){const te=this.streamData.timeCode;te.match(/^\\d{2}_\\d{2}_\\d{2}_\\d{2}$/)?v=`?tc=${te}_1`:te.match(/^\\d{2}_\\d{2}_\\d{2}_\\d{2}_1$/)&&(v=`?tc=${te.replace(/_1$/,"_2")}`)}c&&(v+=`${v?"&":"?"}fr=true`),f=await fetch(u+v,{headers:h,cache:"no-store",credentials:m?"include":"omit"})}else f=await fetch(u,{headers:h,cache:"no-store",credentials:m?"include":"omit"});const b=await f.arrayBuffer(),z=(performance.now()-d)/1e3;if(!f.ok)throw new Error(`HTTP error! Status: ${f.status}`);return z>1&&I.warn("didFetchZip",{downloadTaskURL:u,downloadTime:z}),b},this.stop=()=>{this.downloaderStopped=!0,this.clearAllJobs()},this.postArrayBufferToDecoder=t,this.onZipBufferStatusChange=r,this.options=n}isStopped(){return this.downloaderStopped}roundToZipBoundary(t,n){const r=t.totalSeconds(),o=Math.floor(r/n)*n,s=Math.floor(o/3600),i=Math.floor(o%3600/60),a=o%60;return new C(s,i,a,0,0)}calculateContinuousZipBuffer(){if(!this.streamData)return 0;const t=C.fromStr(this.streamData.timeCode),n=this.options.DOWNLOADER_ZIP_LENGTH_SECONDS;let r=t.addSeconds(this.options.DOWNLOADER_ZIP_START_OFFSET);r=this.roundToZipBoundary(r,n);let o=0;const s=Math.ceil(this.options.DOWNLOADER_ZIP_END_OFFSET/n);for(let i=0;i<s;i++){const a=r.toZipTimeCodeString();if(this.permanentlyFailedTimecodes.has(a)||!this.processedTimecodes.includes(a))break;o+=n,r=r.addSeconds(n)}return o}notifyZipBufferStatus(){if(!this.onZipBufferStatusChange)return;const t=this.calculateContinuousZipBuffer();this.onZipBufferStatusChange({continuousSeconds:t,isReady:t>=this.options.ZIP_BUFFER_READY_THRESHOLD,needsFadeout:t<=this.options.ZIP_BUFFER_FADEOUT_THRESHOLD,retryingTimecodes:Array.from(this.retryingTimecodes),failedTimecodes:Array.from(this.permanentlyFailedTimecodes)})}}let Ze=null,le=null,P,k;function $n(e){Ze&&Ze.postMessage({type:"ZIP_BUFFER_STATUS",status:e})}self.onmessage=async e=>{const{data:t}=e;if(t.type==="SET_LOGGER_PORT"&&I.setMessagePort(t.port),t.type==="SET_RENDERER_PORT"&&(Ze=t.port,Ze.onmessage=ki),t.type==="SET_DECODER_PORT"&&(le=t.port,le.onmessage=xi),t.type==="SET_OPTIONS"&&(k=t.options,I.setMessagePort(self),P=new Nn(Pn,k,$n)),t.type==="STOP_WORKER"){P&&P.stop();return}if(t.type==="RESTART_WORKER"){if(!k)return;P&&P.stop(),P=new Nn(Pn,k,$n);return}};async function ki(e){const{data:t}=e;if(self.postMessage(t),t.type==="DOWNLOADER_INPUT"){if(!P||P.isStopped())return;P.updateStreamData(t.streamData)}}function Pn(e,t){if(!le)return;k&&w(k,"Downloader")&&console.log(`[DownloaderWorker] Posting an ArrayBuffer to Decoder, timeCode=${e}`);const n={type:"DECODER_INPUT",timeCode:e,arrayBuffer:t};le==null||le.postMessage(n,{transfer:[t]})}function xi(e){k&&w(k,"Downloader")&&console.log("[DownloaderWorker] Received message from Decoder:",e.data)}self.onunhandledrejection=e=>{I.error("[DownloaderWorker] Unhandled rejection",{error:e.reason}),k&&(w(k,"Errors")&&console.error("[DownloaderWorker] Unhandled rejection:",e.reason),e.preventDefault())},self.onerror=e=>{I.error("[DownloaderWorker] Unhandled error",{error:e}),k&&(w(k,"Errors")&&console.error("[DownloaderWorker] Unhandled error:",e),e instanceof Event&&e.preventDefault())}})();\n',Nt=typeof self<"u"&&self.Blob&&new Blob([Bt],{type:"text/javascript;charset=utf-8"});function on(t){let e;try{if(e=Nt&&(self.URL||self.webkitURL).createObjectURL(Nt),!e)throw"";const r=new Worker(e,{name:t==null?void 0:t.name});return r.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),r}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Bt),{name:t==null?void 0:t.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}const zt='(function(){"use strict";const k=(a,n)=>n==="Errors"?!0:!a.debug||!a.debug.on?!1:a.debug[`log${n}`];function Zt(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var mt={},Qt;function fn(){return Qt||(Qt=1,function(a){var n=function(){var e=new Date,t=4,r=3,l=2,h=1,m=t,y={setLogLevel:function(b){b==this.debug?m=h:b==this.info?m=l:b==this.warn?m=r:(b==this.error,m=t)},debug:function(b,x){console.debug===void 0&&(console.debug=console.log),h>=m&&console.debug("["+n.getDurationString(new Date-e,1e3)+"]","["+b+"]",x)},log:function(b,x){this.debug(b.msg)},info:function(b,x){l>=m&&console.info("["+n.getDurationString(new Date-e,1e3)+"]","["+b+"]",x)},warn:function(b,x){r>=m&&console.warn("["+n.getDurationString(new Date-e,1e3)+"]","["+b+"]",x)},error:function(b,x){t>=m&&console.error("["+n.getDurationString(new Date-e,1e3)+"]","["+b+"]",x)}};return y}();n.getDurationString=function(e,t){var r;function l(w,T){for(var C=""+w,F=C.split(".");F[0].length<T;)F[0]="0"+F[0];return F.join(".")}e<0?(r=!0,e=-e):r=!1;var h=t||1,m=e/h,y=Math.floor(m/3600);m-=y*3600;var b=Math.floor(m/60);m-=b*60;var x=m*1e3;return m=Math.floor(m),x-=m*1e3,x=Math.floor(x),(r?"-":"")+y+":"+l(b,2)+":"+l(m,2)+"."+l(x,3)},n.printRanges=function(e){var t=e.length;if(t>0){for(var r="",l=0;l<t;l++)l>0&&(r+=","),r+="["+n.getDurationString(e.start(l))+","+n.getDurationString(e.end(l))+"]";return r}else return"(empty)"},a.Log=n;var o=function(e){if(e instanceof ArrayBuffer)this.buffer=e,this.dataview=new DataView(e);else throw"Needs an array buffer";this.position=0};o.prototype.getPosition=function(){return this.position},o.prototype.getEndPosition=function(){return this.buffer.byteLength},o.prototype.getLength=function(){return this.buffer.byteLength},o.prototype.seek=function(e){var t=Math.max(0,Math.min(this.buffer.byteLength,e));return this.position=isNaN(t)||!isFinite(t)?0:t,!0},o.prototype.isEos=function(){return this.getPosition()>=this.getEndPosition()},o.prototype.readAnyInt=function(e,t){var r=0;if(this.position+e<=this.buffer.byteLength){switch(e){case 1:t?r=this.dataview.getInt8(this.position):r=this.dataview.getUint8(this.position);break;case 2:t?r=this.dataview.getInt16(this.position):r=this.dataview.getUint16(this.position);break;case 3:if(t)throw"No method for reading signed 24 bits values";r=this.dataview.getUint8(this.position)<<16,r|=this.dataview.getUint8(this.position+1)<<8,r|=this.dataview.getUint8(this.position+2);break;case 4:t?r=this.dataview.getInt32(this.position):r=this.dataview.getUint32(this.position);break;case 8:if(t)throw"No method for reading signed 64 bits values";r=this.dataview.getUint32(this.position)<<32,r|=this.dataview.getUint32(this.position+4);break;default:throw"readInt method not implemented for size: "+e}return this.position+=e,r}else throw"Not enough bytes in buffer"},o.prototype.readUint8=function(){return this.readAnyInt(1,!1)},o.prototype.readUint16=function(){return this.readAnyInt(2,!1)},o.prototype.readUint24=function(){return this.readAnyInt(3,!1)},o.prototype.readUint32=function(){return this.readAnyInt(4,!1)},o.prototype.readUint64=function(){return this.readAnyInt(8,!1)},o.prototype.readString=function(e){if(this.position+e<=this.buffer.byteLength){for(var t="",r=0;r<e;r++)t+=String.fromCharCode(this.readUint8());return t}else throw"Not enough bytes in buffer"},o.prototype.readCString=function(){for(var e=[];;){var t=this.readUint8();if(t!==0)e.push(t);else break}return String.fromCharCode.apply(null,e)},o.prototype.readInt8=function(){return this.readAnyInt(1,!0)},o.prototype.readInt16=function(){return this.readAnyInt(2,!0)},o.prototype.readInt32=function(){return this.readAnyInt(4,!0)},o.prototype.readInt64=function(){return this.readAnyInt(8,!1)},o.prototype.readUint8Array=function(e){for(var t=new Uint8Array(e),r=0;r<e;r++)t[r]=this.readUint8();return t},o.prototype.readInt16Array=function(e){for(var t=new Int16Array(e),r=0;r<e;r++)t[r]=this.readInt16();return t},o.prototype.readUint16Array=function(e){for(var t=new Int16Array(e),r=0;r<e;r++)t[r]=this.readUint16();return t},o.prototype.readUint32Array=function(e){for(var t=new Uint32Array(e),r=0;r<e;r++)t[r]=this.readUint32();return t},o.prototype.readInt32Array=function(e){for(var t=new Int32Array(e),r=0;r<e;r++)t[r]=this.readInt32();return t},a.MP4BoxStream=o;var d=function(e,t,r){this._byteOffset=t||0,e instanceof ArrayBuffer?this.buffer=e:typeof e=="object"?(this.dataView=e,t&&(this._byteOffset+=t)):this.buffer=new ArrayBuffer(e||0),this.position=0,this.endianness=r??d.LITTLE_ENDIAN};d.prototype={},d.prototype.getPosition=function(){return this.position},d.prototype._realloc=function(e){if(this._dynamicSize){var t=this._byteOffset+this.position+e,r=this._buffer.byteLength;if(t<=r){t>this._byteLength&&(this._byteLength=t);return}for(r<1&&(r=1);t>r;)r*=2;var l=new ArrayBuffer(r),h=new Uint8Array(this._buffer),m=new Uint8Array(l,0,h.length);m.set(h),this.buffer=l,this._byteLength=t}},d.prototype._trimAlloc=function(){if(this._byteLength!=this._buffer.byteLength){var e=new ArrayBuffer(this._byteLength),t=new Uint8Array(e),r=new Uint8Array(this._buffer,0,t.length);t.set(r),this.buffer=e}},d.BIG_ENDIAN=!1,d.LITTLE_ENDIAN=!0,d.prototype._byteLength=0,Object.defineProperty(d.prototype,"byteLength",{get:function(){return this._byteLength-this._byteOffset}}),Object.defineProperty(d.prototype,"buffer",{get:function(){return this._trimAlloc(),this._buffer},set:function(e){this._buffer=e,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(d.prototype,"byteOffset",{get:function(){return this._byteOffset},set:function(e){this._byteOffset=e,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(d.prototype,"dataView",{get:function(){return this._dataView},set:function(e){this._byteOffset=e.byteOffset,this._buffer=e.buffer,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+e.byteLength}}),d.prototype.seek=function(e){var t=Math.max(0,Math.min(this.byteLength,e));this.position=isNaN(t)||!isFinite(t)?0:t},d.prototype.isEof=function(){return this.position>=this._byteLength},d.prototype.mapUint8Array=function(e){this._realloc(e*1);var t=new Uint8Array(this._buffer,this.byteOffset+this.position,e);return this.position+=e*1,t},d.prototype.readInt32Array=function(e,t){e=e??this.byteLength-this.position/4;var r=new Int32Array(e);return d.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT),d.arrayToNative(r,t??this.endianness),this.position+=r.byteLength,r},d.prototype.readInt16Array=function(e,t){e=e??this.byteLength-this.position/2;var r=new Int16Array(e);return d.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT),d.arrayToNative(r,t??this.endianness),this.position+=r.byteLength,r},d.prototype.readInt8Array=function(e){e=e??this.byteLength-this.position;var t=new Int8Array(e);return d.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT),this.position+=t.byteLength,t},d.prototype.readUint32Array=function(e,t){e=e??this.byteLength-this.position/4;var r=new Uint32Array(e);return d.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT),d.arrayToNative(r,t??this.endianness),this.position+=r.byteLength,r},d.prototype.readUint16Array=function(e,t){e=e??this.byteLength-this.position/2;var r=new Uint16Array(e);return d.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT),d.arrayToNative(r,t??this.endianness),this.position+=r.byteLength,r},d.prototype.readUint8Array=function(e){e=e??this.byteLength-this.position;var t=new Uint8Array(e);return d.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT),this.position+=t.byteLength,t},d.prototype.readFloat64Array=function(e,t){e=e??this.byteLength-this.position/8;var r=new Float64Array(e);return d.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT),d.arrayToNative(r,t??this.endianness),this.position+=r.byteLength,r},d.prototype.readFloat32Array=function(e,t){e=e??this.byteLength-this.position/4;var r=new Float32Array(e);return d.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT),d.arrayToNative(r,t??this.endianness),this.position+=r.byteLength,r},d.prototype.readInt32=function(e){var t=this._dataView.getInt32(this.position,e??this.endianness);return this.position+=4,t},d.prototype.readInt16=function(e){var t=this._dataView.getInt16(this.position,e??this.endianness);return this.position+=2,t},d.prototype.readInt8=function(){var e=this._dataView.getInt8(this.position);return this.position+=1,e},d.prototype.readUint32=function(e){var t=this._dataView.getUint32(this.position,e??this.endianness);return this.position+=4,t},d.prototype.readUint16=function(e){var t=this._dataView.getUint16(this.position,e??this.endianness);return this.position+=2,t},d.prototype.readUint8=function(){var e=this._dataView.getUint8(this.position);return this.position+=1,e},d.prototype.readFloat32=function(e){var t=this._dataView.getFloat32(this.position,e??this.endianness);return this.position+=4,t},d.prototype.readFloat64=function(e){var t=this._dataView.getFloat64(this.position,e??this.endianness);return this.position+=8,t},d.endianness=new Int8Array(new Int16Array([1]).buffer)[0]>0,d.memcpy=function(e,t,r,l,h){var m=new Uint8Array(e,t,h),y=new Uint8Array(r,l,h);m.set(y)},d.arrayToNative=function(e,t){return t==this.endianness?e:this.flipArrayEndianness(e)},d.nativeToEndian=function(e,t){return this.endianness==t?e:this.flipArrayEndianness(e)},d.flipArrayEndianness=function(e){for(var t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=0;r<e.byteLength;r+=e.BYTES_PER_ELEMENT)for(var l=r+e.BYTES_PER_ELEMENT-1,h=r;l>h;l--,h++){var m=t[h];t[h]=t[l],t[l]=m}return e},d.prototype.failurePosition=0,String.fromCharCodeUint8=function(e){for(var t=[],r=0;r<e.length;r++)t[r]=e[r];return String.fromCharCode.apply(null,t)},d.prototype.readString=function(e,t){return t==null||t=="ASCII"?String.fromCharCodeUint8.apply(null,[this.mapUint8Array(e??this.byteLength-this.position)]):new TextDecoder(t).decode(this.mapUint8Array(e))},d.prototype.readCString=function(e){var t=this.byteLength-this.position,r=new Uint8Array(this._buffer,this._byteOffset+this.position),l=t;e!=null&&(l=Math.min(e,t));for(var h=0;h<l&&r[h]!==0;h++);var m=String.fromCharCodeUint8.apply(null,[this.mapUint8Array(h)]);return e!=null?this.position+=l-h:h!=t&&(this.position+=1),m};var f=Math.pow(2,32);d.prototype.readInt64=function(){return this.readInt32()*f+this.readUint32()},d.prototype.readUint64=function(){return this.readUint32()*f+this.readUint32()},d.prototype.readInt64=function(){return this.readUint32()*f+this.readUint32()},d.prototype.readUint24=function(){return(this.readUint8()<<16)+(this.readUint8()<<8)+this.readUint8()},a.DataStream=d,d.prototype.save=function(e){var t=new Blob([this.buffer]);if(window.URL&&URL.createObjectURL){var r=window.URL.createObjectURL(t),l=document.createElement("a");document.body.appendChild(l),l.setAttribute("href",r),l.setAttribute("download",e),l.setAttribute("target","_self"),l.click(),window.URL.revokeObjectURL(r)}else throw"DataStream.save: Can\'t create object URL."},d.prototype._dynamicSize=!0,Object.defineProperty(d.prototype,"dynamicSize",{get:function(){return this._dynamicSize},set:function(e){e||this._trimAlloc(),this._dynamicSize=e}}),d.prototype.shift=function(e){var t=new ArrayBuffer(this._byteLength-e),r=new Uint8Array(t),l=new Uint8Array(this._buffer,e,r.length);r.set(l),this.buffer=t,this.position-=e},d.prototype.writeInt32Array=function(e,t){if(this._realloc(e.length*4),e instanceof Int32Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapInt32Array(e.length,t);else for(var r=0;r<e.length;r++)this.writeInt32(e[r],t)},d.prototype.writeInt16Array=function(e,t){if(this._realloc(e.length*2),e instanceof Int16Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapInt16Array(e.length,t);else for(var r=0;r<e.length;r++)this.writeInt16(e[r],t)},d.prototype.writeInt8Array=function(e){if(this._realloc(e.length*1),e instanceof Int8Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapInt8Array(e.length);else for(var t=0;t<e.length;t++)this.writeInt8(e[t])},d.prototype.writeUint32Array=function(e,t){if(this._realloc(e.length*4),e instanceof Uint32Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapUint32Array(e.length,t);else for(var r=0;r<e.length;r++)this.writeUint32(e[r],t)},d.prototype.writeUint16Array=function(e,t){if(this._realloc(e.length*2),e instanceof Uint16Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapUint16Array(e.length,t);else for(var r=0;r<e.length;r++)this.writeUint16(e[r],t)},d.prototype.writeUint8Array=function(e){if(this._realloc(e.length*1),e instanceof Uint8Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapUint8Array(e.length);else for(var t=0;t<e.length;t++)this.writeUint8(e[t])},d.prototype.writeFloat64Array=function(e,t){if(this._realloc(e.length*8),e instanceof Float64Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapFloat64Array(e.length,t);else for(var r=0;r<e.length;r++)this.writeFloat64(e[r],t)},d.prototype.writeFloat32Array=function(e,t){if(this._realloc(e.length*4),e instanceof Float32Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapFloat32Array(e.length,t);else for(var r=0;r<e.length;r++)this.writeFloat32(e[r],t)},d.prototype.writeInt32=function(e,t){this._realloc(4),this._dataView.setInt32(this.position,e,t??this.endianness),this.position+=4},d.prototype.writeInt16=function(e,t){this._realloc(2),this._dataView.setInt16(this.position,e,t??this.endianness),this.position+=2},d.prototype.writeInt8=function(e){this._realloc(1),this._dataView.setInt8(this.position,e),this.position+=1},d.prototype.writeUint32=function(e,t){this._realloc(4),this._dataView.setUint32(this.position,e,t??this.endianness),this.position+=4},d.prototype.writeUint16=function(e,t){this._realloc(2),this._dataView.setUint16(this.position,e,t??this.endianness),this.position+=2},d.prototype.writeUint8=function(e){this._realloc(1),this._dataView.setUint8(this.position,e),this.position+=1},d.prototype.writeFloat32=function(e,t){this._realloc(4),this._dataView.setFloat32(this.position,e,t??this.endianness),this.position+=4},d.prototype.writeFloat64=function(e,t){this._realloc(8),this._dataView.setFloat64(this.position,e,t??this.endianness),this.position+=8},d.prototype.writeUCS2String=function(e,t,r){r==null&&(r=e.length);for(var l=0;l<e.length&&l<r;l++)this.writeUint16(e.charCodeAt(l),t);for(;l<r;l++)this.writeUint16(0)},d.prototype.writeString=function(e,t,r){var l=0;if(t==null||t=="ASCII")if(r!=null){var h=Math.min(e.length,r);for(l=0;l<h;l++)this.writeUint8(e.charCodeAt(l));for(;l<r;l++)this.writeUint8(0)}else for(l=0;l<e.length;l++)this.writeUint8(e.charCodeAt(l));else this.writeUint8Array(new TextEncoder(t).encode(e.substring(0,r)))},d.prototype.writeCString=function(e,t){var r=0;if(t!=null){var l=Math.min(e.length,t);for(r=0;r<l;r++)this.writeUint8(e.charCodeAt(r));for(;r<t;r++)this.writeUint8(0)}else{for(r=0;r<e.length;r++)this.writeUint8(e.charCodeAt(r));this.writeUint8(0)}},d.prototype.writeStruct=function(e,t){for(var r=0;r<e.length;r+=2){var l=e[r+1];this.writeType(l,t[e[r]],t)}},d.prototype.writeType=function(e,t,r){var l;if(typeof e=="function")return e(this,t);if(typeof e=="object"&&!(e instanceof Array))return e.set(this,t,r);var h=null,m="ASCII",y=this.position;switch(typeof e=="string"&&/:/.test(e)&&(l=e.split(":"),e=l[0],h=parseInt(l[1])),typeof e=="string"&&/,/.test(e)&&(l=e.split(","),e=l[0],m=parseInt(l[1])),e){case"uint8":this.writeUint8(t);break;case"int8":this.writeInt8(t);break;case"uint16":this.writeUint16(t,this.endianness);break;case"int16":this.writeInt16(t,this.endianness);break;case"uint32":this.writeUint32(t,this.endianness);break;case"int32":this.writeInt32(t,this.endianness);break;case"float32":this.writeFloat32(t,this.endianness);break;case"float64":this.writeFloat64(t,this.endianness);break;case"uint16be":this.writeUint16(t,d.BIG_ENDIAN);break;case"int16be":this.writeInt16(t,d.BIG_ENDIAN);break;case"uint32be":this.writeUint32(t,d.BIG_ENDIAN);break;case"int32be":this.writeInt32(t,d.BIG_ENDIAN);break;case"float32be":this.writeFloat32(t,d.BIG_ENDIAN);break;case"float64be":this.writeFloat64(t,d.BIG_ENDIAN);break;case"uint16le":this.writeUint16(t,d.LITTLE_ENDIAN);break;case"int16le":this.writeInt16(t,d.LITTLE_ENDIAN);break;case"uint32le":this.writeUint32(t,d.LITTLE_ENDIAN);break;case"int32le":this.writeInt32(t,d.LITTLE_ENDIAN);break;case"float32le":this.writeFloat32(t,d.LITTLE_ENDIAN);break;case"float64le":this.writeFloat64(t,d.LITTLE_ENDIAN);break;case"cstring":this.writeCString(t,h);break;case"string":this.writeString(t,m,h);break;case"u16string":this.writeUCS2String(t,this.endianness,h);break;case"u16stringle":this.writeUCS2String(t,d.LITTLE_ENDIAN,h);break;case"u16stringbe":this.writeUCS2String(t,d.BIG_ENDIAN,h);break;default:if(e.length==3){for(var b=e[1],x=0;x<t.length;x++)this.writeType(b,t[x]);break}else{this.writeStruct(e,t);break}}h!=null&&(this.position=y,this._realloc(h),this.position=y+h)},d.prototype.writeUint64=function(e){var t=Math.floor(e/f);this.writeUint32(t),this.writeUint32(e&4294967295)},d.prototype.writeUint24=function(e){this.writeUint8((e&16711680)>>16),this.writeUint8((e&65280)>>8),this.writeUint8(e&255)},d.prototype.adjustUint32=function(e,t){var r=this.position;this.seek(e),this.writeUint32(t),this.seek(r)},d.prototype.mapInt32Array=function(e,t){this._realloc(e*4);var r=new Int32Array(this._buffer,this.byteOffset+this.position,e);return d.arrayToNative(r,t??this.endianness),this.position+=e*4,r},d.prototype.mapInt16Array=function(e,t){this._realloc(e*2);var r=new Int16Array(this._buffer,this.byteOffset+this.position,e);return d.arrayToNative(r,t??this.endianness),this.position+=e*2,r},d.prototype.mapInt8Array=function(e){this._realloc(e*1);var t=new Int8Array(this._buffer,this.byteOffset+this.position,e);return this.position+=e*1,t},d.prototype.mapUint32Array=function(e,t){this._realloc(e*4);var r=new Uint32Array(this._buffer,this.byteOffset+this.position,e);return d.arrayToNative(r,t??this.endianness),this.position+=e*4,r},d.prototype.mapUint16Array=function(e,t){this._realloc(e*2);var r=new Uint16Array(this._buffer,this.byteOffset+this.position,e);return d.arrayToNative(r,t??this.endianness),this.position+=e*2,r},d.prototype.mapFloat64Array=function(e,t){this._realloc(e*8);var r=new Float64Array(this._buffer,this.byteOffset+this.position,e);return d.arrayToNative(r,t??this.endianness),this.position+=e*8,r},d.prototype.mapFloat32Array=function(e,t){this._realloc(e*4);var r=new Float32Array(this._buffer,this.byteOffset+this.position,e);return d.arrayToNative(r,t??this.endianness),this.position+=e*4,r};var c=function(e){this.buffers=[],this.bufferIndex=-1,e&&(this.insertBuffer(e),this.bufferIndex=0)};c.prototype=new d(new ArrayBuffer,0,d.BIG_ENDIAN),c.prototype.initialized=function(){var e;return this.bufferIndex>-1?!0:this.buffers.length>0?(e=this.buffers[0],e.fileStart===0?(this.buffer=e,this.bufferIndex=0,n.debug("MultiBufferStream","Stream ready for parsing"),!0):(n.warn("MultiBufferStream","The first buffer should have a fileStart of 0"),this.logBufferLevel(),!1)):(n.warn("MultiBufferStream","No buffer to start parsing from"),this.logBufferLevel(),!1)},ArrayBuffer.concat=function(e,t){n.debug("ArrayBuffer","Trying to create a new buffer of size: "+(e.byteLength+t.byteLength));var r=new Uint8Array(e.byteLength+t.byteLength);return r.set(new Uint8Array(e),0),r.set(new Uint8Array(t),e.byteLength),r.buffer},c.prototype.reduceBuffer=function(e,t,r){var l;return l=new Uint8Array(r),l.set(new Uint8Array(e,t,r)),l.buffer.fileStart=e.fileStart+t,l.buffer.usedBytes=0,l.buffer},c.prototype.insertBuffer=function(e){for(var t=!0,r=0;r<this.buffers.length;r++){var l=this.buffers[r];if(e.fileStart<=l.fileStart){if(e.fileStart===l.fileStart)if(e.byteLength>l.byteLength){this.buffers.splice(r,1),r--;continue}else n.warn("MultiBufferStream","Buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+") already appended, ignoring");else e.fileStart+e.byteLength<=l.fileStart||(e=this.reduceBuffer(e,0,l.fileStart-e.fileStart)),n.debug("MultiBufferStream","Appending new buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+")"),this.buffers.splice(r,0,e),r===0&&(this.buffer=e);t=!1;break}else if(e.fileStart<l.fileStart+l.byteLength){var h=l.fileStart+l.byteLength-e.fileStart,m=e.byteLength-h;if(m>0)e=this.reduceBuffer(e,h,m);else{t=!1;break}}}t&&(n.debug("MultiBufferStream","Appending new buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+")"),this.buffers.push(e),r===0&&(this.buffer=e))},c.prototype.logBufferLevel=function(e){var t,r,l,h,m=[],y,b="";for(l=0,h=0,t=0;t<this.buffers.length;t++)r=this.buffers[t],t===0?(y={},m.push(y),y.start=r.fileStart,y.end=r.fileStart+r.byteLength,b+="["+y.start+"-"):y.end===r.fileStart?y.end=r.fileStart+r.byteLength:(y={},y.start=r.fileStart,b+=m[m.length-1].end-1+"], ["+y.start+"-",y.end=r.fileStart+r.byteLength,m.push(y)),l+=r.usedBytes,h+=r.byteLength;m.length>0&&(b+=y.end-1+"]");var x=e?n.info:n.debug;this.buffers.length===0?x("MultiBufferStream","No more buffer in memory"):x("MultiBufferStream",""+this.buffers.length+" stored buffer(s) ("+l+"/"+h+" bytes), continuous ranges: "+b)},c.prototype.cleanBuffers=function(){var e,t;for(e=0;e<this.buffers.length;e++)t=this.buffers[e],t.usedBytes===t.byteLength&&(n.debug("MultiBufferStream","Removing buffer #"+e),this.buffers.splice(e,1),e--)},c.prototype.mergeNextBuffer=function(){var e;if(this.bufferIndex+1<this.buffers.length)if(e=this.buffers[this.bufferIndex+1],e.fileStart===this.buffer.fileStart+this.buffer.byteLength){var t=this.buffer.byteLength,r=this.buffer.usedBytes,l=this.buffer.fileStart;return this.buffers[this.bufferIndex]=ArrayBuffer.concat(this.buffer,e),this.buffer=this.buffers[this.bufferIndex],this.buffers.splice(this.bufferIndex+1,1),this.buffer.usedBytes=r,this.buffer.fileStart=l,n.debug("ISOFile","Concatenating buffer for box parsing (length: "+t+"->"+this.buffer.byteLength+")"),!0}else return!1;else return!1},c.prototype.findPosition=function(e,t,r){var l,h=null,m=-1;for(e===!0?l=0:l=this.bufferIndex;l<this.buffers.length&&(h=this.buffers[l],h.fileStart<=t);){m=l,r&&(h.fileStart+h.byteLength<=t?h.usedBytes=h.byteLength:h.usedBytes=t-h.fileStart,this.logBufferLevel());l++}return m!==-1?(h=this.buffers[m],h.fileStart+h.byteLength>=t?(n.debug("MultiBufferStream","Found position in existing buffer #"+m),m):-1):-1},c.prototype.findEndContiguousBuf=function(e){var t,r,l,h=e!==void 0?e:this.bufferIndex;if(r=this.buffers[h],this.buffers.length>h+1)for(t=h+1;t<this.buffers.length&&(l=this.buffers[t],l.fileStart===r.fileStart+r.byteLength);t++)r=l;return r.fileStart+r.byteLength},c.prototype.getEndFilePositionAfter=function(e){var t=this.findPosition(!0,e,!1);return t!==-1?this.findEndContiguousBuf(t):e},c.prototype.addUsedBytes=function(e){this.buffer.usedBytes+=e,this.logBufferLevel()},c.prototype.setAllUsedBytes=function(){this.buffer.usedBytes=this.buffer.byteLength,this.logBufferLevel()},c.prototype.seek=function(e,t,r){var l;return l=this.findPosition(t,e,r),l!==-1?(this.buffer=this.buffers[l],this.bufferIndex=l,this.position=e-this.buffer.fileStart,n.debug("MultiBufferStream","Repositioning parser at buffer position: "+this.position),!0):(n.debug("MultiBufferStream","Position "+e+" not found in buffered data"),!1)},c.prototype.getPosition=function(){if(this.bufferIndex===-1||this.buffers[this.bufferIndex]===null)throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.position},c.prototype.getLength=function(){return this.byteLength},c.prototype.getEndPosition=function(){if(this.bufferIndex===-1||this.buffers[this.bufferIndex]===null)throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.byteLength},a.MultiBufferStream=c;var u=function(){var e=3,t=4,r=5,l=6,h=[];h[e]="ES_Descriptor",h[t]="DecoderConfigDescriptor",h[r]="DecoderSpecificInfo",h[l]="SLConfigDescriptor",this.getDescriptorName=function(b){return h[b]};var m=this,y={};return this.parseOneDescriptor=function(b){var x=0,w,T,C;for(w=b.readUint8(),C=b.readUint8();C&128;)x=(x<<7)+(C&127),C=b.readUint8();return x=(x<<7)+(C&127),n.debug("MPEG4DescriptorParser","Found "+(h[w]||"Descriptor "+w)+", size "+x+" at position "+b.getPosition()),h[w]?T=new y[h[w]](x):T=new y.Descriptor(x),T.parse(b),T},y.Descriptor=function(b,x){this.tag=b,this.size=x,this.descs=[]},y.Descriptor.prototype.parse=function(b){this.data=b.readUint8Array(this.size)},y.Descriptor.prototype.findDescriptor=function(b){for(var x=0;x<this.descs.length;x++)if(this.descs[x].tag==b)return this.descs[x];return null},y.Descriptor.prototype.parseRemainingDescriptors=function(b){for(var x=b.position;b.position<x+this.size;){var w=m.parseOneDescriptor(b);this.descs.push(w)}},y.ES_Descriptor=function(b){y.Descriptor.call(this,e,b)},y.ES_Descriptor.prototype=new y.Descriptor,y.ES_Descriptor.prototype.parse=function(b){if(this.ES_ID=b.readUint16(),this.flags=b.readUint8(),this.size-=3,this.flags&128?(this.dependsOn_ES_ID=b.readUint16(),this.size-=2):this.dependsOn_ES_ID=0,this.flags&64){var x=b.readUint8();this.URL=b.readString(x),this.size-=x+1}else this.URL="";this.flags&32?(this.OCR_ES_ID=b.readUint16(),this.size-=2):this.OCR_ES_ID=0,this.parseRemainingDescriptors(b)},y.ES_Descriptor.prototype.getOTI=function(b){var x=this.findDescriptor(t);return x?x.oti:0},y.ES_Descriptor.prototype.getAudioConfig=function(b){var x=this.findDescriptor(t);if(!x)return null;var w=x.findDescriptor(r);if(w&&w.data){var T=(w.data[0]&248)>>3;return T===31&&w.data.length>=2&&(T=32+((w.data[0]&7)<<3)+((w.data[1]&224)>>5)),T}else return null},y.DecoderConfigDescriptor=function(b){y.Descriptor.call(this,t,b)},y.DecoderConfigDescriptor.prototype=new y.Descriptor,y.DecoderConfigDescriptor.prototype.parse=function(b){this.oti=b.readUint8(),this.streamType=b.readUint8(),this.upStream=(this.streamType>>1&1)!==0,this.streamType=this.streamType>>>2,this.bufferSize=b.readUint24(),this.maxBitrate=b.readUint32(),this.avgBitrate=b.readUint32(),this.size-=13,this.parseRemainingDescriptors(b)},y.DecoderSpecificInfo=function(b){y.Descriptor.call(this,r,b)},y.DecoderSpecificInfo.prototype=new y.Descriptor,y.SLConfigDescriptor=function(b){y.Descriptor.call(this,l,b)},y.SLConfigDescriptor.prototype=new y.Descriptor,this};a.MPEG4DescriptorParser=u;var s={ERR_INVALID_DATA:-1,ERR_NOT_ENOUGH_DATA:0,OK:1,BASIC_BOXES:["mdat","idat","free","skip","meco","strk"],FULL_BOXES:["hmhd","nmhd","iods","xml ","bxml","ipro","mere"],CONTAINER_BOXES:[["moov",["trak","pssh"]],["trak"],["edts"],["mdia"],["minf"],["dinf"],["stbl",["sgpd","sbgp"]],["mvex",["trex"]],["moof",["traf"]],["traf",["trun","sgpd","sbgp"]],["vttc"],["tref"],["iref"],["mfra",["tfra"]],["meco"],["hnti"],["hinf"],["strk"],["strd"],["sinf"],["rinf"],["schi"],["trgr"],["udta",["kind"]],["iprp",["ipma"]],["ipco"],["grpl"],["j2kH"],["etyp",["tyco"]]],boxCodes:[],fullBoxCodes:[],containerBoxCodes:[],sampleEntryCodes:{},sampleGroupEntryCodes:[],trackGroupTypes:[],UUIDBoxes:{},UUIDs:[],initialize:function(){s.FullBox.prototype=new s.Box,s.ContainerBox.prototype=new s.Box,s.SampleEntry.prototype=new s.Box,s.TrackGroupTypeBox.prototype=new s.FullBox,s.BASIC_BOXES.forEach(function(e){s.createBoxCtor(e)}),s.FULL_BOXES.forEach(function(e){s.createFullBoxCtor(e)}),s.CONTAINER_BOXES.forEach(function(e){s.createContainerBoxCtor(e[0],null,e[1])})},Box:function(e,t,r){this.type=e,this.size=t,this.uuid=r},FullBox:function(e,t,r){s.Box.call(this,e,t,r),this.flags=0,this.version=0},ContainerBox:function(e,t,r){s.Box.call(this,e,t,r),this.boxes=[]},SampleEntry:function(e,t,r,l){s.ContainerBox.call(this,e,t),this.hdr_size=r,this.start=l},SampleGroupEntry:function(e){this.grouping_type=e},TrackGroupTypeBox:function(e,t){s.FullBox.call(this,e,t)},createBoxCtor:function(e,t){s.boxCodes.push(e),s[e+"Box"]=function(r){s.Box.call(this,e,r)},s[e+"Box"].prototype=new s.Box,t&&(s[e+"Box"].prototype.parse=t)},createFullBoxCtor:function(e,t){s[e+"Box"]=function(r){s.FullBox.call(this,e,r)},s[e+"Box"].prototype=new s.FullBox,s[e+"Box"].prototype.parse=function(r){this.parseFullHeader(r),t&&t.call(this,r)}},addSubBoxArrays:function(e){if(e){this.subBoxNames=e;for(var t=e.length,r=0;r<t;r++)this[e[r]+"s"]=[]}},createContainerBoxCtor:function(e,t,r){s[e+"Box"]=function(l){s.ContainerBox.call(this,e,l),s.addSubBoxArrays.call(this,r)},s[e+"Box"].prototype=new s.ContainerBox,t&&(s[e+"Box"].prototype.parse=t)},createMediaSampleEntryCtor:function(e,t,r){s.sampleEntryCodes[e]=[],s[e+"SampleEntry"]=function(l,h){s.SampleEntry.call(this,l,h),s.addSubBoxArrays.call(this,r)},s[e+"SampleEntry"].prototype=new s.SampleEntry,t&&(s[e+"SampleEntry"].prototype.parse=t)},createSampleEntryCtor:function(e,t,r,l){s.sampleEntryCodes[e].push(t),s[t+"SampleEntry"]=function(h){s[e+"SampleEntry"].call(this,t,h),s.addSubBoxArrays.call(this,l)},s[t+"SampleEntry"].prototype=new s[e+"SampleEntry"],r&&(s[t+"SampleEntry"].prototype.parse=r)},createEncryptedSampleEntryCtor:function(e,t,r){s.createSampleEntryCtor.call(this,e,t,r,["sinf"])},createSampleGroupCtor:function(e,t){s[e+"SampleGroupEntry"]=function(r){s.SampleGroupEntry.call(this,e,r)},s[e+"SampleGroupEntry"].prototype=new s.SampleGroupEntry,t&&(s[e+"SampleGroupEntry"].prototype.parse=t)},createTrackGroupCtor:function(e,t){s[e+"TrackGroupTypeBox"]=function(r){s.TrackGroupTypeBox.call(this,e,r)},s[e+"TrackGroupTypeBox"].prototype=new s.TrackGroupTypeBox,t&&(s[e+"TrackGroupTypeBox"].prototype.parse=t)},createUUIDBox:function(e,t,r,l){s.UUIDs.push(e),s.UUIDBoxes[e]=function(h){t?s.FullBox.call(this,"uuid",h,e):r?s.ContainerBox.call(this,"uuid",h,e):s.Box.call(this,"uuid",h,e)},s.UUIDBoxes[e].prototype=t?new s.FullBox:r?new s.ContainerBox:new s.Box,l&&(t?s.UUIDBoxes[e].prototype.parse=function(h){this.parseFullHeader(h),l&&l.call(this,h)}:s.UUIDBoxes[e].prototype.parse=l)}};s.initialize(),s.TKHD_FLAG_ENABLED=1,s.TKHD_FLAG_IN_MOVIE=2,s.TKHD_FLAG_IN_PREVIEW=4,s.TFHD_FLAG_BASE_DATA_OFFSET=1,s.TFHD_FLAG_SAMPLE_DESC=2,s.TFHD_FLAG_SAMPLE_DUR=8,s.TFHD_FLAG_SAMPLE_SIZE=16,s.TFHD_FLAG_SAMPLE_FLAGS=32,s.TFHD_FLAG_DUR_EMPTY=65536,s.TFHD_FLAG_DEFAULT_BASE_IS_MOOF=131072,s.TRUN_FLAGS_DATA_OFFSET=1,s.TRUN_FLAGS_FIRST_FLAG=4,s.TRUN_FLAGS_DURATION=256,s.TRUN_FLAGS_SIZE=512,s.TRUN_FLAGS_FLAGS=1024,s.TRUN_FLAGS_CTS_OFFSET=2048,s.Box.prototype.add=function(e){return this.addBox(new s[e+"Box"])},s.Box.prototype.addBox=function(e){return this.boxes.push(e),this[e.type+"s"]?this[e.type+"s"].push(e):this[e.type]=e,e},s.Box.prototype.set=function(e,t){return this[e]=t,this},s.Box.prototype.addEntry=function(e,t){var r=t||"entries";return this[r]||(this[r]=[]),this[r].push(e),this},a.BoxParser=s,s.parseUUID=function(e){return s.parseHex16(e)},s.parseHex16=function(e){for(var t="",r=0;r<16;r++){var l=e.readUint8().toString(16);t+=l.length===1?"0"+l:l}return t},s.parseOneBox=function(e,t,r){var l,h=e.getPosition(),m=0,y,b;if(e.getEndPosition()-h<8)return n.debug("BoxParser","Not enough data in stream to parse the type and size of the box"),{code:s.ERR_NOT_ENOUGH_DATA};if(r&&r<8)return n.debug("BoxParser","Not enough bytes left in the parent box to parse a new box"),{code:s.ERR_NOT_ENOUGH_DATA};var x=e.readUint32(),w=e.readString(4),T=w;if(n.debug("BoxParser","Found box of type \'"+w+"\' and size "+x+" at position "+h),m=8,w=="uuid"){if(e.getEndPosition()-e.getPosition()<16||r-m<16)return e.seek(h),n.debug("BoxParser","Not enough bytes left in the parent box to parse a UUID box"),{code:s.ERR_NOT_ENOUGH_DATA};b=s.parseUUID(e),m+=16,T=b}if(x==1){if(e.getEndPosition()-e.getPosition()<8||r&&r-m<8)return e.seek(h),n.warn("BoxParser",\'Not enough data in stream to parse the extended size of the "\'+w+\'" box\'),{code:s.ERR_NOT_ENOUGH_DATA};x=e.readUint64(),m+=8}else if(x===0){if(r)x=r;else if(w!=="mdat")return n.error("BoxParser","Unlimited box size not supported for type: \'"+w+"\'"),l=new s.Box(w,x),{code:s.OK,box:l,size:l.size}}return x!==0&&x<m?(n.error("BoxParser","Box of type "+w+" has an invalid size "+x+" (too small to be a box)"),{code:s.ERR_NOT_ENOUGH_DATA,type:w,size:x,hdr_size:m,start:h}):x!==0&&r&&x>r?(n.error("BoxParser","Box of type \'"+w+"\' has a size "+x+" greater than its container size "+r),{code:s.ERR_NOT_ENOUGH_DATA,type:w,size:x,hdr_size:m,start:h}):x!==0&&h+x>e.getEndPosition()?(e.seek(h),n.info("BoxParser","Not enough data in stream to parse the entire \'"+w+"\' box"),{code:s.ERR_NOT_ENOUGH_DATA,type:w,size:x,hdr_size:m,start:h}):t?{code:s.OK,type:w,size:x,hdr_size:m,start:h}:(s[w+"Box"]?l=new s[w+"Box"](x):w!=="uuid"?(n.warn("BoxParser","Unknown box type: \'"+w+"\'"),l=new s.Box(w,x),l.has_unparsed_data=!0):s.UUIDBoxes[b]?l=new s.UUIDBoxes[b](x):(n.warn("BoxParser","Unknown uuid type: \'"+b+"\'"),l=new s.Box(w,x),l.uuid=b,l.has_unparsed_data=!0),l.hdr_size=m,l.start=h,l.write===s.Box.prototype.write&&l.type!=="mdat"&&(n.info("BoxParser","\'"+T+"\' box writing not yet implemented, keeping unparsed data in memory for later write"),l.parseDataAndRewind(e)),l.parse(e),y=e.getPosition()-(l.start+l.size),y<0?(n.warn("BoxParser","Parsing of box \'"+T+"\' did not read the entire indicated box data size (missing "+-y+" bytes), seeking forward"),e.seek(l.start+l.size)):y>0&&(n.error("BoxParser","Parsing of box \'"+T+"\' read "+y+" more bytes than the indicated box data size, seeking backwards"),l.size!==0&&e.seek(l.start+l.size)),{code:s.OK,box:l,size:l.size})},s.Box.prototype.parse=function(e){this.type!="mdat"?this.data=e.readUint8Array(this.size-this.hdr_size):this.size===0?e.seek(e.getEndPosition()):e.seek(this.start+this.size)},s.Box.prototype.parseDataAndRewind=function(e){this.data=e.readUint8Array(this.size-this.hdr_size),e.position-=this.size-this.hdr_size},s.FullBox.prototype.parseDataAndRewind=function(e){this.parseFullHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size),this.hdr_size-=4,e.position-=this.size-this.hdr_size},s.FullBox.prototype.parseFullHeader=function(e){this.version=e.readUint8(),this.flags=e.readUint24(),this.hdr_size+=4},s.FullBox.prototype.parse=function(e){this.parseFullHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size)},s.ContainerBox.prototype.parse=function(e){for(var t,r;e.getPosition()<this.start+this.size;)if(t=s.parseOneBox(e,!1,this.size-(e.getPosition()-this.start)),t.code===s.OK)if(r=t.box,this.boxes.push(r),this.subBoxNames&&this.subBoxNames.indexOf(r.type)!=-1)this[this.subBoxNames[this.subBoxNames.indexOf(r.type)]+"s"].push(r);else{var l=r.type!=="uuid"?r.type:r.uuid;this[l]?n.warn("Box of type "+l+" already stored in field of this type"):this[l]=r}else return},s.Box.prototype.parseLanguage=function(e){this.language=e.readUint16();var t=[];t[0]=this.language>>10&31,t[1]=this.language>>5&31,t[2]=this.language&31,this.languageString=String.fromCharCode(t[0]+96,t[1]+96,t[2]+96)},s.SAMPLE_ENTRY_TYPE_VISUAL="Visual",s.SAMPLE_ENTRY_TYPE_AUDIO="Audio",s.SAMPLE_ENTRY_TYPE_HINT="Hint",s.SAMPLE_ENTRY_TYPE_METADATA="Metadata",s.SAMPLE_ENTRY_TYPE_SUBTITLE="Subtitle",s.SAMPLE_ENTRY_TYPE_SYSTEM="System",s.SAMPLE_ENTRY_TYPE_TEXT="Text",s.SampleEntry.prototype.parseHeader=function(e){e.readUint8Array(6),this.data_reference_index=e.readUint16(),this.hdr_size+=8},s.SampleEntry.prototype.parse=function(e){this.parseHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size)},s.SampleEntry.prototype.parseDataAndRewind=function(e){this.parseHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size),this.hdr_size-=8,e.position-=this.size-this.hdr_size},s.SampleEntry.prototype.parseFooter=function(e){s.ContainerBox.prototype.parse.call(this,e)},s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_HINT),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_METADATA),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SYSTEM),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_TEXT),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,function(e){var t;this.parseHeader(e),e.readUint16(),e.readUint16(),e.readUint32Array(3),this.width=e.readUint16(),this.height=e.readUint16(),this.horizresolution=e.readUint32(),this.vertresolution=e.readUint32(),e.readUint32(),this.frame_count=e.readUint16(),t=Math.min(31,e.readUint8()),this.compressorname=e.readString(t),t<31&&e.readString(31-t),this.depth=e.readUint16(),e.readUint16(),this.parseFooter(e)}),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,function(e){this.parseHeader(e),e.readUint32Array(2),this.channel_count=e.readUint16(),this.samplesize=e.readUint16(),e.readUint16(),e.readUint16(),this.samplerate=e.readUint32()/65536,this.parseFooter(e)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"avc1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"avc2"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"avc3"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"avc4"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"av01"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"dav1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"hvc1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"hev1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"hvt1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"lhe1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"dvh1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"dvhe"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vvc1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vvi1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vvs1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vvcN"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vp08"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vp09"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"avs3"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"j2ki"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"mjp2"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"mjpg"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"uncv"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"mp4a"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"ac-3"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"ac-4"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"ec-3"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"Opus"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"mha1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"mha2"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"mhm1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"mhm2"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"fLaC"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"encv"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"enca"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE,"encu"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SYSTEM,"encs"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_TEXT,"enct"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_METADATA,"encm"),s.createBoxCtor("a1lx",function(e){var t=e.readUint8()&1,r=((t&1)+1)*16;this.layer_size=[];for(var l=0;l<3;l++)r==16?this.layer_size[l]=e.readUint16():this.layer_size[l]=e.readUint32()}),s.createBoxCtor("a1op",function(e){this.op_index=e.readUint8()}),s.createFullBoxCtor("auxC",function(e){this.aux_type=e.readCString();var t=this.size-this.hdr_size-(this.aux_type.length+1);this.aux_subtype=e.readUint8Array(t)}),s.createBoxCtor("av1C",function(e){var t=e.readUint8();if(t>>7&!1){n.error("av1C marker problem");return}if(this.version=t&127,this.version!==1){n.error("av1C version "+this.version+" not supported");return}if(t=e.readUint8(),this.seq_profile=t>>5&7,this.seq_level_idx_0=t&31,t=e.readUint8(),this.seq_tier_0=t>>7&1,this.high_bitdepth=t>>6&1,this.twelve_bit=t>>5&1,this.monochrome=t>>4&1,this.chroma_subsampling_x=t>>3&1,this.chroma_subsampling_y=t>>2&1,this.chroma_sample_position=t&3,t=e.readUint8(),this.reserved_1=t>>5&7,this.reserved_1!==0){n.error("av1C reserved_1 parsing problem");return}if(this.initial_presentation_delay_present=t>>4&1,this.initial_presentation_delay_present===1)this.initial_presentation_delay_minus_one=t&15;else if(this.reserved_2=t&15,this.reserved_2!==0){n.error("av1C reserved_2 parsing problem");return}var r=this.size-this.hdr_size-4;this.configOBUs=e.readUint8Array(r)}),s.createBoxCtor("avcC",function(e){var t,r;for(this.configurationVersion=e.readUint8(),this.AVCProfileIndication=e.readUint8(),this.profile_compatibility=e.readUint8(),this.AVCLevelIndication=e.readUint8(),this.lengthSizeMinusOne=e.readUint8()&3,this.nb_SPS_nalus=e.readUint8()&31,r=this.size-this.hdr_size-6,this.SPS=[],t=0;t<this.nb_SPS_nalus;t++)this.SPS[t]={},this.SPS[t].length=e.readUint16(),this.SPS[t].nalu=e.readUint8Array(this.SPS[t].length),r-=2+this.SPS[t].length;for(this.nb_PPS_nalus=e.readUint8(),r--,this.PPS=[],t=0;t<this.nb_PPS_nalus;t++)this.PPS[t]={},this.PPS[t].length=e.readUint16(),this.PPS[t].nalu=e.readUint8Array(this.PPS[t].length),r-=2+this.PPS[t].length;r>0&&(this.ext=e.readUint8Array(r))}),s.createBoxCtor("btrt",function(e){this.bufferSizeDB=e.readUint32(),this.maxBitrate=e.readUint32(),this.avgBitrate=e.readUint32()}),s.createFullBoxCtor("ccst",function(e){var t=e.readUint8();this.all_ref_pics_intra=(t&128)==128,this.intra_pred_used=(t&64)==64,this.max_ref_per_pic=(t&63)>>2,e.readUint24()}),s.createBoxCtor("cdef",function(e){var t;for(this.channel_count=e.readUint16(),this.channel_indexes=[],this.channel_types=[],this.channel_associations=[],t=0;t<this.channel_count;t++)this.channel_indexes.push(e.readUint16()),this.channel_types.push(e.readUint16()),this.channel_associations.push(e.readUint16())}),s.createBoxCtor("clap",function(e){this.cleanApertureWidthN=e.readUint32(),this.cleanApertureWidthD=e.readUint32(),this.cleanApertureHeightN=e.readUint32(),this.cleanApertureHeightD=e.readUint32(),this.horizOffN=e.readUint32(),this.horizOffD=e.readUint32(),this.vertOffN=e.readUint32(),this.vertOffD=e.readUint32()}),s.createBoxCtor("clli",function(e){this.max_content_light_level=e.readUint16(),this.max_pic_average_light_level=e.readUint16()}),s.createFullBoxCtor("cmex",function(e){this.flags&1&&(this.pos_x=e.readInt32()),this.flags&2&&(this.pos_y=e.readInt32()),this.flags&4&&(this.pos_z=e.readInt32()),this.flags&8&&(this.version==0?this.flags&16?(this.quat_x=e.readInt32(),this.quat_y=e.readInt32(),this.quat_z=e.readInt32()):(this.quat_x=e.readInt16(),this.quat_y=e.readInt16(),this.quat_z=e.readInt16()):this.version==1),this.flags&32&&(this.id=e.readUint32())}),s.createFullBoxCtor("cmin",function(e){this.focal_length_x=e.readInt32(),this.principal_point_x=e.readInt32(),this.principal_point_y=e.readInt32(),this.flags&1&&(this.focal_length_y=e.readInt32(),this.skew_factor=e.readInt32())}),s.createBoxCtor("cmpd",function(e){for(this.component_count=e.readUint32(),this.component_types=[],this.component_type_urls=[],i=0;i<this.component_count;i++){var t=e.readUint16();this.component_types.push(t),t>=32768&&this.component_type_urls.push(e.readCString())}}),s.createFullBoxCtor("co64",function(e){var t,r;if(t=e.readUint32(),this.chunk_offsets=[],this.version===0)for(r=0;r<t;r++)this.chunk_offsets.push(e.readUint64())}),s.createFullBoxCtor("CoLL",function(e){this.maxCLL=e.readUint16(),this.maxFALL=e.readUint16()}),s.createBoxCtor("colr",function(e){if(this.colour_type=e.readString(4),this.colour_type==="nclx"){this.colour_primaries=e.readUint16(),this.transfer_characteristics=e.readUint16(),this.matrix_coefficients=e.readUint16();var t=e.readUint8();this.full_range_flag=t>>7}else this.colour_type==="rICC"?this.ICC_profile=e.readUint8Array(this.size-4):this.colour_type==="prof"&&(this.ICC_profile=e.readUint8Array(this.size-4))}),s.createFullBoxCtor("cprt",function(e){this.parseLanguage(e),this.notice=e.readCString()}),s.createFullBoxCtor("cslg",function(e){this.version===0&&(this.compositionToDTSShift=e.readInt32(),this.leastDecodeToDisplayDelta=e.readInt32(),this.greatestDecodeToDisplayDelta=e.readInt32(),this.compositionStartTime=e.readInt32(),this.compositionEndTime=e.readInt32())}),s.createFullBoxCtor("ctts",function(e){var t,r;if(t=e.readUint32(),this.sample_counts=[],this.sample_offsets=[],this.version===0)for(r=0;r<t;r++){this.sample_counts.push(e.readUint32());var l=e.readInt32();l<0&&n.warn("BoxParser","ctts box uses negative values without using version 1"),this.sample_offsets.push(l)}else if(this.version==1)for(r=0;r<t;r++)this.sample_counts.push(e.readUint32()),this.sample_offsets.push(e.readInt32())}),s.createBoxCtor("dac3",function(e){var t=e.readUint8(),r=e.readUint8(),l=e.readUint8();this.fscod=t>>6,this.bsid=t>>1&31,this.bsmod=(t&1)<<2|r>>6&3,this.acmod=r>>3&7,this.lfeon=r>>2&1,this.bit_rate_code=r&3|l>>5&7}),s.createBoxCtor("dec3",function(e){var t=e.readUint16();this.data_rate=t>>3,this.num_ind_sub=t&7,this.ind_subs=[];for(var r=0;r<this.num_ind_sub+1;r++){var l={};this.ind_subs.push(l);var h=e.readUint8(),m=e.readUint8(),y=e.readUint8();l.fscod=h>>6,l.bsid=h>>1&31,l.bsmod=(h&1)<<4|m>>4&15,l.acmod=m>>1&7,l.lfeon=m&1,l.num_dep_sub=y>>1&15,l.num_dep_sub>0&&(l.chan_loc=(y&1)<<8|e.readUint8())}}),s.createFullBoxCtor("dfLa",function(e){var t=127,r=128,l=[],h=["STREAMINFO","PADDING","APPLICATION","SEEKTABLE","VORBIS_COMMENT","CUESHEET","PICTURE","RESERVED"];do{var m=e.readUint8(),y=Math.min(m&t,h.length-1);if(y?e.readUint8Array(e.readUint24()):(e.readUint8Array(13),this.samplerate=e.readUint32()>>12,e.readUint8Array(20)),l.push(h[y]),m&r)break}while(!0);this.numMetadataBlocks=l.length+" ("+l.join(", ")+")"}),s.createBoxCtor("dimm",function(e){this.bytessent=e.readUint64()}),s.createBoxCtor("dmax",function(e){this.time=e.readUint32()}),s.createBoxCtor("dmed",function(e){this.bytessent=e.readUint64()}),s.createBoxCtor("dOps",function(e){if(this.Version=e.readUint8(),this.OutputChannelCount=e.readUint8(),this.PreSkip=e.readUint16(),this.InputSampleRate=e.readUint32(),this.OutputGain=e.readInt16(),this.ChannelMappingFamily=e.readUint8(),this.ChannelMappingFamily!==0){this.StreamCount=e.readUint8(),this.CoupledCount=e.readUint8(),this.ChannelMapping=[];for(var t=0;t<this.OutputChannelCount;t++)this.ChannelMapping[t]=e.readUint8()}}),s.createFullBoxCtor("dref",function(e){var t,r;this.entries=[];for(var l=e.readUint32(),h=0;h<l;h++)if(t=s.parseOneBox(e,!1,this.size-(e.getPosition()-this.start)),t.code===s.OK)r=t.box,this.entries.push(r);else return}),s.createBoxCtor("drep",function(e){this.bytessent=e.readUint64()}),s.createFullBoxCtor("elng",function(e){this.extended_language=e.readString(this.size-this.hdr_size)}),s.createFullBoxCtor("elst",function(e){this.entries=[];for(var t=e.readUint32(),r=0;r<t;r++){var l={};this.entries.push(l),this.version===1?(l.segment_duration=e.readUint64(),l.media_time=e.readInt64()):(l.segment_duration=e.readUint32(),l.media_time=e.readInt32()),l.media_rate_integer=e.readInt16(),l.media_rate_fraction=e.readInt16()}}),s.createFullBoxCtor("emsg",function(e){this.version==1?(this.timescale=e.readUint32(),this.presentation_time=e.readUint64(),this.event_duration=e.readUint32(),this.id=e.readUint32(),this.scheme_id_uri=e.readCString(),this.value=e.readCString()):(this.scheme_id_uri=e.readCString(),this.value=e.readCString(),this.timescale=e.readUint32(),this.presentation_time_delta=e.readUint32(),this.event_duration=e.readUint32(),this.id=e.readUint32());var t=this.size-this.hdr_size-(4*4+(this.scheme_id_uri.length+1)+(this.value.length+1));this.version==1&&(t-=4),this.message_data=e.readUint8Array(t)}),s.createEntityToGroupCtor=function(e,t){s[e+"Box"]=function(r){s.FullBox.call(this,e,r)},s[e+"Box"].prototype=new s.FullBox,s[e+"Box"].prototype.parse=function(r){if(this.parseFullHeader(r),t)t.call(this,r);else for(this.group_id=r.readUint32(),this.num_entities_in_group=r.readUint32(),this.entity_ids=[],i=0;i<this.num_entities_in_group;i++){var l=r.readUint32();this.entity_ids.push(l)}}},s.createEntityToGroupCtor("aebr"),s.createEntityToGroupCtor("afbr"),s.createEntityToGroupCtor("albc"),s.createEntityToGroupCtor("altr"),s.createEntityToGroupCtor("brst"),s.createEntityToGroupCtor("dobr"),s.createEntityToGroupCtor("eqiv"),s.createEntityToGroupCtor("favc"),s.createEntityToGroupCtor("fobr"),s.createEntityToGroupCtor("iaug"),s.createEntityToGroupCtor("pano"),s.createEntityToGroupCtor("slid"),s.createEntityToGroupCtor("ster"),s.createEntityToGroupCtor("tsyn"),s.createEntityToGroupCtor("wbbr"),s.createEntityToGroupCtor("prgr"),s.createEntityToGroupCtor("pymd",function(e){this.group_id=e.readUint32(),this.num_entities_in_group=e.readUint32(),this.entity_ids=[];for(var t=0;t<this.num_entities_in_group;t++){var r=e.readUint32();this.entity_ids.push(r)}for(this.tile_size_x=e.readUint16(),this.tile_size_y=e.readUint16(),this.layer_binning=[],this.tiles_in_layer_column_minus1=[],this.tiles_in_layer_row_minus1=[],t=0;t<this.num_entities_in_group;t++)this.layer_binning[t]=e.readUint16(),this.tiles_in_layer_row_minus1[t]=e.readUint16(),this.tiles_in_layer_column_minus1[t]=e.readUint16()}),s.createFullBoxCtor("esds",function(e){var t=e.readUint8Array(this.size-this.hdr_size);if(typeof u<"u"){var r=new u;this.esd=r.parseOneDescriptor(new d(t.buffer,0,d.BIG_ENDIAN))}}),s.createBoxCtor("fiel",function(e){this.fieldCount=e.readUint8(),this.fieldOrdering=e.readUint8()}),s.createBoxCtor("frma",function(e){this.data_format=e.readString(4)}),s.createBoxCtor("ftyp",function(e){var t=this.size-this.hdr_size;this.major_brand=e.readString(4),this.minor_version=e.readUint32(),t-=8,this.compatible_brands=[];for(var r=0;t>=4;)this.compatible_brands[r]=e.readString(4),t-=4,r++}),s.createFullBoxCtor("hdlr",function(e){this.version===0&&(e.readUint32(),this.handler=e.readString(4),e.readUint32Array(3),this.name=e.readString(this.size-this.hdr_size-20),this.name[this.name.length-1]==="\\0"&&(this.name=this.name.slice(0,-1)))}),s.createBoxCtor("hvcC",function(e){var t,r,l,h;this.configurationVersion=e.readUint8(),h=e.readUint8(),this.general_profile_space=h>>6,this.general_tier_flag=(h&32)>>5,this.general_profile_idc=h&31,this.general_profile_compatibility=e.readUint32(),this.general_constraint_indicator=e.readUint8Array(6),this.general_level_idc=e.readUint8(),this.min_spatial_segmentation_idc=e.readUint16()&4095,this.parallelismType=e.readUint8()&3,this.chroma_format_idc=e.readUint8()&3,this.bit_depth_luma_minus8=e.readUint8()&7,this.bit_depth_chroma_minus8=e.readUint8()&7,this.avgFrameRate=e.readUint16(),h=e.readUint8(),this.constantFrameRate=h>>6,this.numTemporalLayers=(h&13)>>3,this.temporalIdNested=(h&4)>>2,this.lengthSizeMinusOne=h&3,this.nalu_arrays=[];var m=e.readUint8();for(t=0;t<m;t++){var y=[];this.nalu_arrays.push(y),h=e.readUint8(),y.completeness=(h&128)>>7,y.nalu_type=h&63;var b=e.readUint16();for(r=0;r<b;r++){var x={};y.push(x),l=e.readUint16(),x.data=e.readUint8Array(l)}}}),s.createFullBoxCtor("iinf",function(e){var t;this.version===0?this.entry_count=e.readUint16():this.entry_count=e.readUint32(),this.item_infos=[];for(var r=0;r<this.entry_count;r++)if(t=s.parseOneBox(e,!1,this.size-(e.getPosition()-this.start)),t.code===s.OK)t.box.type!=="infe"&&n.error("BoxParser","Expected \'infe\' box, got "+t.box.type),this.item_infos[r]=t.box;else return}),s.createFullBoxCtor("iloc",function(e){var t;t=e.readUint8(),this.offset_size=t>>4&15,this.length_size=t&15,t=e.readUint8(),this.base_offset_size=t>>4&15,this.version===1||this.version===2?this.index_size=t&15:this.index_size=0,this.items=[];var r=0;if(this.version<2)r=e.readUint16();else if(this.version===2)r=e.readUint32();else throw"version of iloc box not supported";for(var l=0;l<r;l++){var h={};if(this.items.push(h),this.version<2)h.item_ID=e.readUint16();else if(this.version===2)h.item_ID=e.readUint32();else throw"version of iloc box not supported";switch(this.version===1||this.version===2?h.construction_method=e.readUint16()&15:h.construction_method=0,h.data_reference_index=e.readUint16(),this.base_offset_size){case 0:h.base_offset=0;break;case 4:h.base_offset=e.readUint32();break;case 8:h.base_offset=e.readUint64();break;default:throw"Error reading base offset size"}var m=e.readUint16();h.extents=[];for(var y=0;y<m;y++){var b={};if(h.extents.push(b),this.version===1||this.version===2)switch(this.index_size){case 0:b.extent_index=0;break;case 4:b.extent_index=e.readUint32();break;case 8:b.extent_index=e.readUint64();break;default:throw"Error reading extent index"}switch(this.offset_size){case 0:b.extent_offset=0;break;case 4:b.extent_offset=e.readUint32();break;case 8:b.extent_offset=e.readUint64();break;default:throw"Error reading extent index"}switch(this.length_size){case 0:b.extent_length=0;break;case 4:b.extent_length=e.readUint32();break;case 8:b.extent_length=e.readUint64();break;default:throw"Error reading extent index"}}}}),s.createBoxCtor("imir",function(e){var t=e.readUint8();this.reserved=t>>7,this.axis=t&1}),s.createFullBoxCtor("infe",function(e){if((this.version===0||this.version===1)&&(this.item_ID=e.readUint16(),this.item_protection_index=e.readUint16(),this.item_name=e.readCString(),this.content_type=e.readCString(),this.content_encoding=e.readCString()),this.version===1){this.extension_type=e.readString(4),n.warn("BoxParser","Cannot parse extension type"),e.seek(this.start+this.size);return}this.version>=2&&(this.version===2?this.item_ID=e.readUint16():this.version===3&&(this.item_ID=e.readUint32()),this.item_protection_index=e.readUint16(),this.item_type=e.readString(4),this.item_name=e.readCString(),this.item_type==="mime"?(this.content_type=e.readCString(),this.content_encoding=e.readCString()):this.item_type==="uri "&&(this.item_uri_type=e.readCString()))}),s.createFullBoxCtor("ipma",function(e){var t,r;for(entry_count=e.readUint32(),this.associations=[],t=0;t<entry_count;t++){var l={};this.associations.push(l),this.version<1?l.id=e.readUint16():l.id=e.readUint32();var h=e.readUint8();for(l.props=[],r=0;r<h;r++){var m=e.readUint8(),y={};l.props.push(y),y.essential=(m&128)>>7===1,this.flags&1?y.property_index=(m&127)<<8|e.readUint8():y.property_index=m&127}}}),s.createFullBoxCtor("iref",function(e){var t,r;for(this.references=[];e.getPosition()<this.start+this.size;)if(t=s.parseOneBox(e,!0,this.size-(e.getPosition()-this.start)),t.code===s.OK)this.version===0?r=new s.SingleItemTypeReferenceBox(t.type,t.size,t.hdr_size,t.start):r=new s.SingleItemTypeReferenceBoxLarge(t.type,t.size,t.hdr_size,t.start),r.write===s.Box.prototype.write&&r.type!=="mdat"&&(n.warn("BoxParser",r.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),r.parseDataAndRewind(e)),r.parse(e),this.references.push(r);else return}),s.createBoxCtor("irot",function(e){this.angle=e.readUint8()&3}),s.createFullBoxCtor("ispe",function(e){this.image_width=e.readUint32(),this.image_height=e.readUint32()}),s.createFullBoxCtor("kind",function(e){this.schemeURI=e.readCString(),this.value=e.readCString()}),s.createFullBoxCtor("leva",function(e){var t=e.readUint8();this.levels=[];for(var r=0;r<t;r++){var l={};this.levels[r]=l,l.track_ID=e.readUint32();var h=e.readUint8();switch(l.padding_flag=h>>7,l.assignment_type=h&127,l.assignment_type){case 0:l.grouping_type=e.readString(4);break;case 1:l.grouping_type=e.readString(4),l.grouping_type_parameter=e.readUint32();break;case 2:break;case 3:break;case 4:l.sub_track_id=e.readUint32();break;default:n.warn("BoxParser","Unknown leva assignement type")}}}),s.createBoxCtor("lhvC",function(e){var t,r,l;this.configurationVersion=e.readUint8(),this.min_spatial_segmentation_idc=e.readUint16()&4095,this.parallelismType=e.readUint8()&3,l=e.readUint8(),this.numTemporalLayers=(l&13)>>3,this.temporalIdNested=(l&4)>>2,this.lengthSizeMinusOne=l&3,this.nalu_arrays=[];var h=e.readUint8();for(t=0;t<h;t++){var m=[];this.nalu_arrays.push(m),l=e.readUint8(),m.completeness=(l&128)>>7,m.nalu_type=l&63;var y=e.readUint16();for(r=0;r<y;r++){var b={};m.push(b);var x=e.readUint16();b.data=e.readUint8Array(x)}}}),s.createBoxCtor("lsel",function(e){this.layer_id=e.readUint16()}),s.createBoxCtor("maxr",function(e){this.period=e.readUint32(),this.bytes=e.readUint32()});function p(e,t){this.x=e,this.y=t}p.prototype.toString=function(){return"("+this.x+","+this.y+")"},s.createBoxCtor("mdcv",function(e){this.display_primaries=[],this.display_primaries[0]=new p(e.readUint16(),e.readUint16()),this.display_primaries[1]=new p(e.readUint16(),e.readUint16()),this.display_primaries[2]=new p(e.readUint16(),e.readUint16()),this.white_point=new p(e.readUint16(),e.readUint16()),this.max_display_mastering_luminance=e.readUint32(),this.min_display_mastering_luminance=e.readUint32()}),s.createFullBoxCtor("mdhd",function(e){this.version==1?(this.creation_time=e.readUint64(),this.modification_time=e.readUint64(),this.timescale=e.readUint32(),this.duration=e.readUint64()):(this.creation_time=e.readUint32(),this.modification_time=e.readUint32(),this.timescale=e.readUint32(),this.duration=e.readUint32()),this.parseLanguage(e),e.readUint16()}),s.createFullBoxCtor("mehd",function(e){this.flags&1&&(n.warn("BoxParser","mehd box incorrectly uses flags set to 1, converting version to 1"),this.version=1),this.version==1?this.fragment_duration=e.readUint64():this.fragment_duration=e.readUint32()}),s.createFullBoxCtor("meta",function(e){this.boxes=[],s.ContainerBox.prototype.parse.call(this,e)}),s.createFullBoxCtor("mfhd",function(e){this.sequence_number=e.readUint32()}),s.createFullBoxCtor("mfro",function(e){this._size=e.readUint32()}),s.createFullBoxCtor("mskC",function(e){this.bits_per_pixel=e.readUint8()}),s.createFullBoxCtor("mvhd",function(e){this.version==1?(this.creation_time=e.readUint64(),this.modification_time=e.readUint64(),this.timescale=e.readUint32(),this.duration=e.readUint64()):(this.creation_time=e.readUint32(),this.modification_time=e.readUint32(),this.timescale=e.readUint32(),this.duration=e.readUint32()),this.rate=e.readUint32(),this.volume=e.readUint16()>>8,e.readUint16(),e.readUint32Array(2),this.matrix=e.readUint32Array(9),e.readUint32Array(6),this.next_track_id=e.readUint32()}),s.createBoxCtor("npck",function(e){this.packetssent=e.readUint32()}),s.createBoxCtor("nump",function(e){this.packetssent=e.readUint64()}),s.createFullBoxCtor("padb",function(e){var t=e.readUint32();this.padbits=[];for(var r=0;r<Math.floor((t+1)/2);r++)this.padbits=e.readUint8()}),s.createBoxCtor("pasp",function(e){this.hSpacing=e.readUint32(),this.vSpacing=e.readUint32()}),s.createBoxCtor("payl",function(e){this.text=e.readString(this.size-this.hdr_size)}),s.createBoxCtor("payt",function(e){this.payloadID=e.readUint32();var t=e.readUint8();this.rtpmap_string=e.readString(t)}),s.createFullBoxCtor("pdin",function(e){var t=(this.size-this.hdr_size)/8;this.rate=[],this.initial_delay=[];for(var r=0;r<t;r++)this.rate[r]=e.readUint32(),this.initial_delay[r]=e.readUint32()}),s.createFullBoxCtor("pitm",function(e){this.version===0?this.item_id=e.readUint16():this.item_id=e.readUint32()}),s.createFullBoxCtor("pixi",function(e){var t;for(this.num_channels=e.readUint8(),this.bits_per_channels=[],t=0;t<this.num_channels;t++)this.bits_per_channels[t]=e.readUint8()}),s.createBoxCtor("pmax",function(e){this.bytes=e.readUint32()}),s.createFullBoxCtor("prdi",function(e){if(this.step_count=e.readUint16(),this.item_count=[],this.flags&2)for(var t=0;t<this.step_count;t++)this.item_count[t]=e.readUint16()}),s.createFullBoxCtor("prft",function(e){this.ref_track_id=e.readUint32(),this.ntp_timestamp=e.readUint64(),this.version===0?this.media_time=e.readUint32():this.media_time=e.readUint64()}),s.createFullBoxCtor("pssh",function(e){if(this.system_id=s.parseHex16(e),this.version>0){var t=e.readUint32();this.kid=[];for(var r=0;r<t;r++)this.kid[r]=s.parseHex16(e)}var l=e.readUint32();l>0&&(this.data=e.readUint8Array(l))}),s.createFullBoxCtor("clef",function(e){this.width=e.readUint32(),this.height=e.readUint32()}),s.createFullBoxCtor("enof",function(e){this.width=e.readUint32(),this.height=e.readUint32()}),s.createFullBoxCtor("prof",function(e){this.width=e.readUint32(),this.height=e.readUint32()}),s.createContainerBoxCtor("tapt",null,["clef","prof","enof"]),s.createBoxCtor("rtp ",function(e){this.descriptionformat=e.readString(4),this.sdptext=e.readString(this.size-this.hdr_size-4)}),s.createFullBoxCtor("saio",function(e){this.flags&1&&(this.aux_info_type=e.readString(4),this.aux_info_type_parameter=e.readUint32());var t=e.readUint32();this.offset=[];for(var r=0;r<t;r++)this.version===0?this.offset[r]=e.readUint32():this.offset[r]=e.readUint64()}),s.createFullBoxCtor("saiz",function(e){if(this.flags&1&&(this.aux_info_type=e.readString(4),this.aux_info_type_parameter=e.readUint32()),this.default_sample_info_size=e.readUint8(),this.sample_count=e.readUint32(),this.sample_info_size=[],this.default_sample_info_size===0)for(var t=0;t<this.sample_count;t++)this.sample_info_size[t]=e.readUint8()}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_METADATA,"mett",function(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.mime_format=e.readCString(),this.parseFooter(e)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_METADATA,"metx",function(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.namespace=e.readCString(),this.schema_location=e.readCString(),this.parseFooter(e)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE,"sbtt",function(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.mime_format=e.readCString(),this.parseFooter(e)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE,"stpp",function(e){this.parseHeader(e),this.namespace=e.readCString(),this.schema_location=e.readCString(),this.auxiliary_mime_types=e.readCString(),this.parseFooter(e)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE,"stxt",function(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.mime_format=e.readCString(),this.parseFooter(e)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE,"tx3g",function(e){this.parseHeader(e),this.displayFlags=e.readUint32(),this.horizontal_justification=e.readInt8(),this.vertical_justification=e.readInt8(),this.bg_color_rgba=e.readUint8Array(4),this.box_record=e.readInt16Array(4),this.style_record=e.readUint8Array(12),this.parseFooter(e)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_METADATA,"wvtt",function(e){this.parseHeader(e),this.parseFooter(e)}),s.createSampleGroupCtor("alst",function(e){var t,r=e.readUint16();for(this.first_output_sample=e.readUint16(),this.sample_offset=[],t=0;t<r;t++)this.sample_offset[t]=e.readUint32();var l=this.description_length-4-4*r;for(this.num_output_samples=[],this.num_total_samples=[],t=0;t<l/4;t++)this.num_output_samples[t]=e.readUint16(),this.num_total_samples[t]=e.readUint16()}),s.createSampleGroupCtor("avll",function(e){this.layerNumber=e.readUint8(),this.accurateStatisticsFlag=e.readUint8(),this.avgBitRate=e.readUint16(),this.avgFrameRate=e.readUint16()}),s.createSampleGroupCtor("avss",function(e){this.subSequenceIdentifier=e.readUint16(),this.layerNumber=e.readUint8();var t=e.readUint8();this.durationFlag=t>>7,this.avgRateFlag=t>>6&1,this.durationFlag&&(this.duration=e.readUint32()),this.avgRateFlag&&(this.accurateStatisticsFlag=e.readUint8(),this.avgBitRate=e.readUint16(),this.avgFrameRate=e.readUint16()),this.dependency=[];for(var r=e.readUint8(),l=0;l<r;l++){var h={};this.dependency.push(h),h.subSeqDirectionFlag=e.readUint8(),h.layerNumber=e.readUint8(),h.subSequenceIdentifier=e.readUint16()}}),s.createSampleGroupCtor("dtrt",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("mvif",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("prol",function(e){this.roll_distance=e.readInt16()}),s.createSampleGroupCtor("rap ",function(e){var t=e.readUint8();this.num_leading_samples_known=t>>7,this.num_leading_samples=t&127}),s.createSampleGroupCtor("rash",function(e){if(this.operation_point_count=e.readUint16(),this.description_length!==2+(this.operation_point_count===1?2:this.operation_point_count*6)+9)n.warn("BoxParser","Mismatch in "+this.grouping_type+" sample group length"),this.data=e.readUint8Array(this.description_length-2);else{if(this.operation_point_count===1)this.target_rate_share=e.readUint16();else{this.target_rate_share=[],this.available_bitrate=[];for(var t=0;t<this.operation_point_count;t++)this.available_bitrate[t]=e.readUint32(),this.target_rate_share[t]=e.readUint16()}this.maximum_bitrate=e.readUint32(),this.minimum_bitrate=e.readUint32(),this.discard_priority=e.readUint8()}}),s.createSampleGroupCtor("roll",function(e){this.roll_distance=e.readInt16()}),s.SampleGroupEntry.prototype.parse=function(e){n.warn("BoxParser","Unknown Sample Group type: "+this.grouping_type),this.data=e.readUint8Array(this.description_length)},s.createSampleGroupCtor("scif",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("scnm",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("seig",function(e){this.reserved=e.readUint8();var t=e.readUint8();this.crypt_byte_block=t>>4,this.skip_byte_block=t&15,this.isProtected=e.readUint8(),this.Per_Sample_IV_Size=e.readUint8(),this.KID=s.parseHex16(e),this.constant_IV_size=0,this.constant_IV=0,this.isProtected===1&&this.Per_Sample_IV_Size===0&&(this.constant_IV_size=e.readUint8(),this.constant_IV=e.readUint8Array(this.constant_IV_size))}),s.createSampleGroupCtor("stsa",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("sync",function(e){var t=e.readUint8();this.NAL_unit_type=t&63}),s.createSampleGroupCtor("tele",function(e){var t=e.readUint8();this.level_independently_decodable=t>>7}),s.createSampleGroupCtor("tsas",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("tscl",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("vipr",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createFullBoxCtor("sbgp",function(e){this.grouping_type=e.readString(4),this.version===1?this.grouping_type_parameter=e.readUint32():this.grouping_type_parameter=0,this.entries=[];for(var t=e.readUint32(),r=0;r<t;r++){var l={};this.entries.push(l),l.sample_count=e.readInt32(),l.group_description_index=e.readInt32()}});function _(e,t){this.bad_pixel_row=e,this.bad_pixel_column=t}_.prototype.toString=function(){return"[row: "+this.bad_pixel_row+", column: "+this.bad_pixel_column+"]"},s.createFullBoxCtor("sbpm",function(e){var t;for(this.component_count=e.readUint16(),this.component_index=[],t=0;t<this.component_count;t++)this.component_index.push(e.readUint16());var r=e.readUint8();for(this.correction_applied=(r&128)==128,this.num_bad_rows=e.readUint32(),this.num_bad_cols=e.readUint32(),this.num_bad_pixels=e.readUint32(),this.bad_rows=[],this.bad_columns=[],this.bad_pixels=[],t=0;t<this.num_bad_rows;t++)this.bad_rows.push(e.readUint32());for(t=0;t<this.num_bad_cols;t++)this.bad_columns.push(e.readUint32());for(t=0;t<this.num_bad_pixels;t++){var l=e.readUint32(),h=e.readUint32();this.bad_pixels.push(new _(l,h))}}),s.createFullBoxCtor("schm",function(e){this.scheme_type=e.readString(4),this.scheme_version=e.readUint32(),this.flags&1&&(this.scheme_uri=e.readString(this.size-this.hdr_size-8))}),s.createBoxCtor("sdp ",function(e){this.sdptext=e.readString(this.size-this.hdr_size)}),s.createFullBoxCtor("sdtp",function(e){var t,r=this.size-this.hdr_size;this.is_leading=[],this.sample_depends_on=[],this.sample_is_depended_on=[],this.sample_has_redundancy=[];for(var l=0;l<r;l++)t=e.readUint8(),this.is_leading[l]=t>>6,this.sample_depends_on[l]=t>>4&3,this.sample_is_depended_on[l]=t>>2&3,this.sample_has_redundancy[l]=t&3}),s.createFullBoxCtor("senc"),s.createFullBoxCtor("sgpd",function(e){this.grouping_type=e.readString(4),n.debug("BoxParser","Found Sample Groups of type "+this.grouping_type),this.version===1?this.default_length=e.readUint32():this.default_length=0,this.version>=2&&(this.default_group_description_index=e.readUint32()),this.entries=[];for(var t=e.readUint32(),r=0;r<t;r++){var l;s[this.grouping_type+"SampleGroupEntry"]?l=new s[this.grouping_type+"SampleGroupEntry"](this.grouping_type):l=new s.SampleGroupEntry(this.grouping_type),this.entries.push(l),this.version===1?this.default_length===0?l.description_length=e.readUint32():l.description_length=this.default_length:l.description_length=this.default_length,l.write===s.SampleGroupEntry.prototype.write&&(n.info("BoxParser","SampleGroup for type "+this.grouping_type+" writing not yet implemented, keeping unparsed data in memory for later write"),l.data=e.readUint8Array(l.description_length),e.position-=l.description_length),l.parse(e)}}),s.createFullBoxCtor("sidx",function(e){this.reference_ID=e.readUint32(),this.timescale=e.readUint32(),this.version===0?(this.earliest_presentation_time=e.readUint32(),this.first_offset=e.readUint32()):(this.earliest_presentation_time=e.readUint64(),this.first_offset=e.readUint64()),e.readUint16(),this.references=[];for(var t=e.readUint16(),r=0;r<t;r++){var l={};this.references.push(l);var h=e.readUint32();l.reference_type=h>>31&1,l.referenced_size=h&2147483647,l.subsegment_duration=e.readUint32(),h=e.readUint32(),l.starts_with_SAP=h>>31&1,l.SAP_type=h>>28&7,l.SAP_delta_time=h&268435455}}),s.SingleItemTypeReferenceBox=function(e,t,r,l){s.Box.call(this,e,t),this.hdr_size=r,this.start=l},s.SingleItemTypeReferenceBox.prototype=new s.Box,s.SingleItemTypeReferenceBox.prototype.parse=function(e){this.from_item_ID=e.readUint16();var t=e.readUint16();this.references=[];for(var r=0;r<t;r++)this.references[r]={},this.references[r].to_item_ID=e.readUint16()},s.SingleItemTypeReferenceBoxLarge=function(e,t,r,l){s.Box.call(this,e,t),this.hdr_size=r,this.start=l},s.SingleItemTypeReferenceBoxLarge.prototype=new s.Box,s.SingleItemTypeReferenceBoxLarge.prototype.parse=function(e){this.from_item_ID=e.readUint32();var t=e.readUint16();this.references=[];for(var r=0;r<t;r++)this.references[r]={},this.references[r].to_item_ID=e.readUint32()},s.createFullBoxCtor("SmDm",function(e){this.primaryRChromaticity_x=e.readUint16(),this.primaryRChromaticity_y=e.readUint16(),this.primaryGChromaticity_x=e.readUint16(),this.primaryGChromaticity_y=e.readUint16(),this.primaryBChromaticity_x=e.readUint16(),this.primaryBChromaticity_y=e.readUint16(),this.whitePointChromaticity_x=e.readUint16(),this.whitePointChromaticity_y=e.readUint16(),this.luminanceMax=e.readUint32(),this.luminanceMin=e.readUint32()}),s.createFullBoxCtor("smhd",function(e){this.balance=e.readUint16(),e.readUint16()}),s.createFullBoxCtor("ssix",function(e){this.subsegments=[];for(var t=e.readUint32(),r=0;r<t;r++){var l={};this.subsegments.push(l),l.ranges=[];for(var h=e.readUint32(),m=0;m<h;m++){var y={};l.ranges.push(y),y.level=e.readUint8(),y.range_size=e.readUint24()}}}),s.createFullBoxCtor("stco",function(e){var t;if(t=e.readUint32(),this.chunk_offsets=[],this.version===0)for(var r=0;r<t;r++)this.chunk_offsets.push(e.readUint32())}),s.createFullBoxCtor("stdp",function(e){var t=(this.size-this.hdr_size)/2;this.priority=[];for(var r=0;r<t;r++)this.priority[r]=e.readUint16()}),s.createFullBoxCtor("sthd"),s.createFullBoxCtor("stri",function(e){this.switch_group=e.readUint16(),this.alternate_group=e.readUint16(),this.sub_track_id=e.readUint32();var t=(this.size-this.hdr_size-8)/4;this.attribute_list=[];for(var r=0;r<t;r++)this.attribute_list[r]=e.readUint32()}),s.createFullBoxCtor("stsc",function(e){var t,r;if(t=e.readUint32(),this.first_chunk=[],this.samples_per_chunk=[],this.sample_description_index=[],this.version===0)for(r=0;r<t;r++)this.first_chunk.push(e.readUint32()),this.samples_per_chunk.push(e.readUint32()),this.sample_description_index.push(e.readUint32())}),s.createFullBoxCtor("stsd",function(e){var t,r,l,h;for(this.entries=[],l=e.readUint32(),t=1;t<=l;t++)if(r=s.parseOneBox(e,!0,this.size-(e.getPosition()-this.start)),r.code===s.OK)s[r.type+"SampleEntry"]?(h=new s[r.type+"SampleEntry"](r.size),h.hdr_size=r.hdr_size,h.start=r.start):(n.warn("BoxParser","Unknown sample entry type: "+r.type),h=new s.SampleEntry(r.type,r.size,r.hdr_size,r.start)),h.write===s.SampleEntry.prototype.write&&(n.info("BoxParser","SampleEntry "+h.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),h.parseDataAndRewind(e)),h.parse(e),this.entries.push(h);else return}),s.createFullBoxCtor("stsg",function(e){this.grouping_type=e.readUint32();var t=e.readUint16();this.group_description_index=[];for(var r=0;r<t;r++)this.group_description_index[r]=e.readUint32()}),s.createFullBoxCtor("stsh",function(e){var t,r;if(t=e.readUint32(),this.shadowed_sample_numbers=[],this.sync_sample_numbers=[],this.version===0)for(r=0;r<t;r++)this.shadowed_sample_numbers.push(e.readUint32()),this.sync_sample_numbers.push(e.readUint32())}),s.createFullBoxCtor("stss",function(e){var t,r;if(r=e.readUint32(),this.version===0)for(this.sample_numbers=[],t=0;t<r;t++)this.sample_numbers.push(e.readUint32())}),s.createFullBoxCtor("stsz",function(e){var t;if(this.sample_sizes=[],this.version===0)for(this.sample_size=e.readUint32(),this.sample_count=e.readUint32(),t=0;t<this.sample_count;t++)this.sample_size===0?this.sample_sizes.push(e.readUint32()):this.sample_sizes[t]=this.sample_size}),s.createFullBoxCtor("stts",function(e){var t,r,l;if(t=e.readUint32(),this.sample_counts=[],this.sample_deltas=[],this.version===0)for(r=0;r<t;r++)this.sample_counts.push(e.readUint32()),l=e.readInt32(),l<0&&(n.warn("BoxParser","File uses negative stts sample delta, using value 1 instead, sync may be lost!"),l=1),this.sample_deltas.push(l)}),s.createFullBoxCtor("stvi",function(e){var t=e.readUint32();this.single_view_allowed=t&3,this.stereo_scheme=e.readUint32();var r=e.readUint32();this.stereo_indication_type=e.readString(r);var l,h;for(this.boxes=[];e.getPosition()<this.start+this.size;)if(l=s.parseOneBox(e,!1,this.size-(e.getPosition()-this.start)),l.code===s.OK)h=l.box,this.boxes.push(h),this[h.type]=h;else return}),s.createBoxCtor("styp",function(e){s.ftypBox.prototype.parse.call(this,e)}),s.createFullBoxCtor("stz2",function(e){var t,r;if(this.sample_sizes=[],this.version===0)if(this.reserved=e.readUint24(),this.field_size=e.readUint8(),r=e.readUint32(),this.field_size===4)for(t=0;t<r;t+=2){var l=e.readUint8();this.sample_sizes[t]=l>>4&15,this.sample_sizes[t+1]=l&15}else if(this.field_size===8)for(t=0;t<r;t++)this.sample_sizes[t]=e.readUint8();else if(this.field_size===16)for(t=0;t<r;t++)this.sample_sizes[t]=e.readUint16();else n.error("BoxParser","Error in length field in stz2 box")}),s.createFullBoxCtor("subs",function(e){var t,r,l,h;for(l=e.readUint32(),this.entries=[],t=0;t<l;t++){var m={};if(this.entries[t]=m,m.sample_delta=e.readUint32(),m.subsamples=[],h=e.readUint16(),h>0)for(r=0;r<h;r++){var y={};m.subsamples.push(y),this.version==1?y.size=e.readUint32():y.size=e.readUint16(),y.priority=e.readUint8(),y.discardable=e.readUint8(),y.codec_specific_parameters=e.readUint32()}}}),s.createFullBoxCtor("tenc",function(e){if(e.readUint8(),this.version===0)e.readUint8();else{var t=e.readUint8();this.default_crypt_byte_block=t>>4&15,this.default_skip_byte_block=t&15}this.default_isProtected=e.readUint8(),this.default_Per_Sample_IV_Size=e.readUint8(),this.default_KID=s.parseHex16(e),this.default_isProtected===1&&this.default_Per_Sample_IV_Size===0&&(this.default_constant_IV_size=e.readUint8(),this.default_constant_IV=e.readUint8Array(this.default_constant_IV_size))}),s.createFullBoxCtor("tfdt",function(e){this.version==1?this.baseMediaDecodeTime=e.readUint64():this.baseMediaDecodeTime=e.readUint32()}),s.createFullBoxCtor("tfhd",function(e){var t=0;this.track_id=e.readUint32(),this.size-this.hdr_size>t&&this.flags&s.TFHD_FLAG_BASE_DATA_OFFSET?(this.base_data_offset=e.readUint64(),t+=8):this.base_data_offset=0,this.size-this.hdr_size>t&&this.flags&s.TFHD_FLAG_SAMPLE_DESC?(this.default_sample_description_index=e.readUint32(),t+=4):this.default_sample_description_index=0,this.size-this.hdr_size>t&&this.flags&s.TFHD_FLAG_SAMPLE_DUR?(this.default_sample_duration=e.readUint32(),t+=4):this.default_sample_duration=0,this.size-this.hdr_size>t&&this.flags&s.TFHD_FLAG_SAMPLE_SIZE?(this.default_sample_size=e.readUint32(),t+=4):this.default_sample_size=0,this.size-this.hdr_size>t&&this.flags&s.TFHD_FLAG_SAMPLE_FLAGS?(this.default_sample_flags=e.readUint32(),t+=4):this.default_sample_flags=0}),s.createFullBoxCtor("tfra",function(e){this.track_ID=e.readUint32(),e.readUint24();var t=e.readUint8();this.length_size_of_traf_num=t>>4&3,this.length_size_of_trun_num=t>>2&3,this.length_size_of_sample_num=t&3,this.entries=[];for(var r=e.readUint32(),l=0;l<r;l++)this.version===1?(this.time=e.readUint64(),this.moof_offset=e.readUint64()):(this.time=e.readUint32(),this.moof_offset=e.readUint32()),this.traf_number=e["readUint"+8*(this.length_size_of_traf_num+1)](),this.trun_number=e["readUint"+8*(this.length_size_of_trun_num+1)](),this.sample_number=e["readUint"+8*(this.length_size_of_sample_num+1)]()}),s.createFullBoxCtor("tkhd",function(e){this.version==1?(this.creation_time=e.readUint64(),this.modification_time=e.readUint64(),this.track_id=e.readUint32(),e.readUint32(),this.duration=e.readUint64()):(this.creation_time=e.readUint32(),this.modification_time=e.readUint32(),this.track_id=e.readUint32(),e.readUint32(),this.duration=e.readUint32()),e.readUint32Array(2),this.layer=e.readInt16(),this.alternate_group=e.readInt16(),this.volume=e.readInt16()>>8,e.readUint16(),this.matrix=e.readInt32Array(9),this.width=e.readUint32(),this.height=e.readUint32()}),s.createBoxCtor("tmax",function(e){this.time=e.readUint32()}),s.createBoxCtor("tmin",function(e){this.time=e.readUint32()}),s.createBoxCtor("totl",function(e){this.bytessent=e.readUint32()}),s.createBoxCtor("tpay",function(e){this.bytessent=e.readUint32()}),s.createBoxCtor("tpyl",function(e){this.bytessent=e.readUint64()}),s.TrackGroupTypeBox.prototype.parse=function(e){this.parseFullHeader(e),this.track_group_id=e.readUint32()},s.createTrackGroupCtor("msrc"),s.TrackReferenceTypeBox=function(e,t,r,l){s.Box.call(this,e,t),this.hdr_size=r,this.start=l},s.TrackReferenceTypeBox.prototype=new s.Box,s.TrackReferenceTypeBox.prototype.parse=function(e){this.track_ids=e.readUint32Array((this.size-this.hdr_size)/4)},s.trefBox.prototype.parse=function(e){for(var t,r;e.getPosition()<this.start+this.size;)if(t=s.parseOneBox(e,!0,this.size-(e.getPosition()-this.start)),t.code===s.OK)r=new s.TrackReferenceTypeBox(t.type,t.size,t.hdr_size,t.start),r.write===s.Box.prototype.write&&r.type!=="mdat"&&(n.info("BoxParser","TrackReference "+r.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),r.parseDataAndRewind(e)),r.parse(e),this.boxes.push(r);else return},s.createFullBoxCtor("trep",function(e){for(this.track_ID=e.readUint32(),this.boxes=[];e.getPosition()<this.start+this.size;)if(ret=s.parseOneBox(e,!1,this.size-(e.getPosition()-this.start)),ret.code===s.OK)box=ret.box,this.boxes.push(box);else return}),s.createFullBoxCtor("trex",function(e){this.track_id=e.readUint32(),this.default_sample_description_index=e.readUint32(),this.default_sample_duration=e.readUint32(),this.default_sample_size=e.readUint32(),this.default_sample_flags=e.readUint32()}),s.createBoxCtor("trpy",function(e){this.bytessent=e.readUint64()}),s.createFullBoxCtor("trun",function(e){var t=0;if(this.sample_count=e.readUint32(),t+=4,this.size-this.hdr_size>t&&this.flags&s.TRUN_FLAGS_DATA_OFFSET?(this.data_offset=e.readInt32(),t+=4):this.data_offset=0,this.size-this.hdr_size>t&&this.flags&s.TRUN_FLAGS_FIRST_FLAG?(this.first_sample_flags=e.readUint32(),t+=4):this.first_sample_flags=0,this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[],this.size-this.hdr_size>t)for(var r=0;r<this.sample_count;r++)this.flags&s.TRUN_FLAGS_DURATION&&(this.sample_duration[r]=e.readUint32()),this.flags&s.TRUN_FLAGS_SIZE&&(this.sample_size[r]=e.readUint32()),this.flags&s.TRUN_FLAGS_FLAGS&&(this.sample_flags[r]=e.readUint32()),this.flags&s.TRUN_FLAGS_CTS_OFFSET&&(this.version===0?this.sample_composition_time_offset[r]=e.readUint32():this.sample_composition_time_offset[r]=e.readInt32())}),s.createFullBoxCtor("tsel",function(e){this.switch_group=e.readUint32();var t=(this.size-this.hdr_size-4)/4;this.attribute_list=[];for(var r=0;r<t;r++)this.attribute_list[r]=e.readUint32()}),s.createFullBoxCtor("txtC",function(e){this.config=e.readCString()}),s.createBoxCtor("tyco",function(e){var t=(this.size-this.hdr_size)/4;this.compatible_brands=[];for(var r=0;r<t;r++)this.compatible_brands[r]=e.readString(4)}),s.createFullBoxCtor("udes",function(e){this.lang=e.readCString(),this.name=e.readCString(),this.description=e.readCString(),this.tags=e.readCString()}),s.createFullBoxCtor("uncC",function(e){var t;if(this.profile=e.readUint32(),this.version!=1){if(this.version==0){for(this.component_count=e.readUint32(),this.component_index=[],this.component_bit_depth_minus_one=[],this.component_format=[],this.component_align_size=[],t=0;t<this.component_count;t++)this.component_index.push(e.readUint16()),this.component_bit_depth_minus_one.push(e.readUint8()),this.component_format.push(e.readUint8()),this.component_align_size.push(e.readUint8());this.sampling_type=e.readUint8(),this.interleave_type=e.readUint8(),this.block_size=e.readUint8();var r=e.readUint8();this.component_little_endian=r>>7&1,this.block_pad_lsb=r>>6&1,this.block_little_endian=r>>5&1,this.block_reversed=r>>4&1,this.pad_unknown=r>>3&1,this.pixel_size=e.readUint32(),this.row_align_size=e.readUint32(),this.tile_align_size=e.readUint32(),this.num_tile_cols_minus_one=e.readUint32(),this.num_tile_rows_minus_one=e.readUint32()}}}),s.createFullBoxCtor("url ",function(e){this.flags!==1&&(this.location=e.readCString())}),s.createFullBoxCtor("urn ",function(e){this.name=e.readCString(),this.size-this.hdr_size-this.name.length-1>0&&(this.location=e.readCString())}),s.createUUIDBox("a5d40b30e81411ddba2f0800200c9a66",!0,!1,function(e){this.LiveServerManifest=e.readString(this.size-this.hdr_size).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/\'/g,"'")}),s.createUUIDBox("d08a4f1810f34a82b6c832d8aba183d3",!0,!1,function(e){this.system_id=s.parseHex16(e);var t=e.readUint32();t>0&&(this.data=e.readUint8Array(t))}),s.createUUIDBox("a2394f525a9b4f14a2446c427c648df4",!0,!1),s.createUUIDBox("8974dbce7be74c5184f97148f9882554",!0,!1,function(e){this.default_AlgorithmID=e.readUint24(),this.default_IV_size=e.readUint8(),this.default_KID=s.parseHex16(e)}),s.createUUIDBox("d4807ef2ca3946958e5426cb9e46a79f",!0,!1,function(e){this.fragment_count=e.readUint8(),this.entries=[];for(var t=0;t<this.fragment_count;t++){var r={},l=0,h=0;this.version===1?(l=e.readUint64(),h=e.readUint64()):(l=e.readUint32(),h=e.readUint32()),r.absolute_time=l,r.absolute_duration=h,this.entries.push(r)}}),s.createUUIDBox("6d1d9b0542d544e680e2141daff757b2",!0,!1,function(e){this.version===1?(this.absolute_time=e.readUint64(),this.duration=e.readUint64()):(this.absolute_time=e.readUint32(),this.duration=e.readUint32())}),s.createFullBoxCtor("vmhd",function(e){this.graphicsmode=e.readUint16(),this.opcolor=e.readUint16Array(3)}),s.createFullBoxCtor("vpcC",function(e){var t;this.version===1?(this.profile=e.readUint8(),this.level=e.readUint8(),t=e.readUint8(),this.bitDepth=t>>4,this.chromaSubsampling=t>>1&7,this.videoFullRangeFlag=t&1,this.colourPrimaries=e.readUint8(),this.transferCharacteristics=e.readUint8(),this.matrixCoefficients=e.readUint8(),this.codecIntializationDataSize=e.readUint16(),this.codecIntializationData=e.readUint8Array(this.codecIntializationDataSize)):(this.profile=e.readUint8(),this.level=e.readUint8(),t=e.readUint8(),this.bitDepth=t>>4&15,this.colorSpace=t&15,t=e.readUint8(),this.chromaSubsampling=t>>4&15,this.transferFunction=t>>1&7,this.videoFullRangeFlag=t&1,this.codecIntializationDataSize=e.readUint16(),this.codecIntializationData=e.readUint8Array(this.codecIntializationDataSize))}),s.createBoxCtor("vttC",function(e){this.text=e.readString(this.size-this.hdr_size)}),s.createFullBoxCtor("vvcC",function(e){var t,r,l={held_bits:void 0,num_held_bits:0,stream_read_1_bytes:function(A){this.held_bits=A.readUint8(),this.num_held_bits=8},stream_read_2_bytes:function(A){this.held_bits=A.readUint16(),this.num_held_bits=16},extract_bits:function(A){var R=this.held_bits>>this.num_held_bits-A&(1<<A)-1;return this.num_held_bits-=A,R}};if(l.stream_read_1_bytes(e),l.extract_bits(5),this.lengthSizeMinusOne=l.extract_bits(2),this.ptl_present_flag=l.extract_bits(1),this.ptl_present_flag){l.stream_read_2_bytes(e),this.ols_idx=l.extract_bits(9),this.num_sublayers=l.extract_bits(3),this.constant_frame_rate=l.extract_bits(2),this.chroma_format_idc=l.extract_bits(2),l.stream_read_1_bytes(e),this.bit_depth_minus8=l.extract_bits(3),l.extract_bits(5);{if(l.stream_read_2_bytes(e),l.extract_bits(2),this.num_bytes_constraint_info=l.extract_bits(6),this.general_profile_idc=l.extract_bits(7),this.general_tier_flag=l.extract_bits(1),this.general_level_idc=e.readUint8(),l.stream_read_1_bytes(e),this.ptl_frame_only_constraint_flag=l.extract_bits(1),this.ptl_multilayer_enabled_flag=l.extract_bits(1),this.general_constraint_info=new Uint8Array(this.num_bytes_constraint_info),this.num_bytes_constraint_info){for(t=0;t<this.num_bytes_constraint_info-1;t++){var h=l.extract_bits(6);l.stream_read_1_bytes(e);var m=l.extract_bits(2);this.general_constraint_info[t]=h<<2|m}this.general_constraint_info[this.num_bytes_constraint_info-1]=l.extract_bits(6)}else l.extract_bits(6);if(this.num_sublayers>1){for(l.stream_read_1_bytes(e),this.ptl_sublayer_present_mask=0,r=this.num_sublayers-2;r>=0;--r){var y=l.extract_bits(1);this.ptl_sublayer_present_mask|=y<<r}for(r=this.num_sublayers;r<=8&&this.num_sublayers>1;++r)l.extract_bits(1);for(this.sublayer_level_idc=[],r=this.num_sublayers-2;r>=0;--r)this.ptl_sublayer_present_mask&1<<r&&(this.sublayer_level_idc[r]=e.readUint8())}if(this.ptl_num_sub_profiles=e.readUint8(),this.general_sub_profile_idc=[],this.ptl_num_sub_profiles)for(t=0;t<this.ptl_num_sub_profiles;t++)this.general_sub_profile_idc.push(e.readUint32())}this.max_picture_width=e.readUint16(),this.max_picture_height=e.readUint16(),this.avg_frame_rate=e.readUint16()}var b=12,x=13;this.nalu_arrays=[];var w=e.readUint8();for(t=0;t<w;t++){var T=[];this.nalu_arrays.push(T),l.stream_read_1_bytes(e),T.completeness=l.extract_bits(1),l.extract_bits(2),T.nalu_type=l.extract_bits(5);var C=1;for(T.nalu_type!=x&&T.nalu_type!=b&&(C=e.readUint16()),r=0;r<C;r++){var F=e.readUint16();T.push({data:e.readUint8Array(F),length:F})}}}),s.createFullBoxCtor("vvnC",function(e){var t=strm.readUint8();this.lengthSizeMinusOne=t&3}),s.SampleEntry.prototype.isVideo=function(){return!1},s.SampleEntry.prototype.isAudio=function(){return!1},s.SampleEntry.prototype.isSubtitle=function(){return!1},s.SampleEntry.prototype.isMetadata=function(){return!1},s.SampleEntry.prototype.isHint=function(){return!1},s.SampleEntry.prototype.getCodec=function(){return this.type.replace(".","")},s.SampleEntry.prototype.getWidth=function(){return""},s.SampleEntry.prototype.getHeight=function(){return""},s.SampleEntry.prototype.getChannelCount=function(){return""},s.SampleEntry.prototype.getSampleRate=function(){return""},s.SampleEntry.prototype.getSampleSize=function(){return""},s.VisualSampleEntry.prototype.isVideo=function(){return!0},s.VisualSampleEntry.prototype.getWidth=function(){return this.width},s.VisualSampleEntry.prototype.getHeight=function(){return this.height},s.AudioSampleEntry.prototype.isAudio=function(){return!0},s.AudioSampleEntry.prototype.getChannelCount=function(){return this.channel_count},s.AudioSampleEntry.prototype.getSampleRate=function(){return this.samplerate},s.AudioSampleEntry.prototype.getSampleSize=function(){return this.samplesize},s.SubtitleSampleEntry.prototype.isSubtitle=function(){return!0},s.MetadataSampleEntry.prototype.isMetadata=function(){return!0},s.decimalToHex=function(e,t){var r=Number(e).toString(16);for(t=typeof t>"u"||t===null?t=2:t;r.length<t;)r="0"+r;return r},s.avc1SampleEntry.prototype.getCodec=s.avc2SampleEntry.prototype.getCodec=s.avc3SampleEntry.prototype.getCodec=s.avc4SampleEntry.prototype.getCodec=function(){var e=s.SampleEntry.prototype.getCodec.call(this);return this.avcC?e+"."+s.decimalToHex(this.avcC.AVCProfileIndication)+s.decimalToHex(this.avcC.profile_compatibility)+s.decimalToHex(this.avcC.AVCLevelIndication):e},s.hev1SampleEntry.prototype.getCodec=s.hvc1SampleEntry.prototype.getCodec=function(){var e,t=s.SampleEntry.prototype.getCodec.call(this);if(this.hvcC){switch(t+=".",this.hvcC.general_profile_space){case 0:t+="";break;case 1:t+="A";break;case 2:t+="B";break;case 3:t+="C";break}t+=this.hvcC.general_profile_idc,t+=".";var r=this.hvcC.general_profile_compatibility,l=0;for(e=0;e<32&&(l|=r&1,e!=31);e++)l<<=1,r>>=1;t+=s.decimalToHex(l,0),t+=".",this.hvcC.general_tier_flag===0?t+="L":t+="H",t+=this.hvcC.general_level_idc;var h=!1,m="";for(e=5;e>=0;e--)(this.hvcC.general_constraint_indicator[e]||h)&&(m="."+s.decimalToHex(this.hvcC.general_constraint_indicator[e],0)+m,h=!0);t+=m}return t},s.vvc1SampleEntry.prototype.getCodec=s.vvi1SampleEntry.prototype.getCodec=function(){var e,t=s.SampleEntry.prototype.getCodec.call(this);if(this.vvcC){t+="."+this.vvcC.general_profile_idc,this.vvcC.general_tier_flag?t+=".H":t+=".L",t+=this.vvcC.general_level_idc;var r="";if(this.vvcC.general_constraint_info){var l=[],h=0;h|=this.vvcC.ptl_frame_only_constraint<<7,h|=this.vvcC.ptl_multilayer_enabled<<6;var m;for(e=0;e<this.vvcC.general_constraint_info.length;++e)h|=this.vvcC.general_constraint_info[e]>>2&63,l.push(h),h&&(m=e),h=this.vvcC.general_constraint_info[e]>>2&3;if(m===void 0)r=".CA";else{r=".C";var y="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",b=0,x=0;for(e=0;e<=m;++e)for(b=b<<8|l[e],x+=8;x>=5;){var w=b>>x-5&31;r+=y[w],x-=5,b&=(1<<x)-1}x&&(b<<=5-x,r+=y[b&31])}}t+=r}return t},s.mp4aSampleEntry.prototype.getCodec=function(){var e=s.SampleEntry.prototype.getCodec.call(this);if(this.esds&&this.esds.esd){var t=this.esds.esd.getOTI(),r=this.esds.esd.getAudioConfig();return e+"."+s.decimalToHex(t)+(r?"."+r:"")}else return e},s.stxtSampleEntry.prototype.getCodec=function(){var e=s.SampleEntry.prototype.getCodec.call(this);return this.mime_format?e+"."+this.mime_format:e},s.vp08SampleEntry.prototype.getCodec=s.vp09SampleEntry.prototype.getCodec=function(){var e=s.SampleEntry.prototype.getCodec.call(this),t=this.vpcC.level;t==0&&(t="00");var r=this.vpcC.bitDepth;return r==8&&(r="08"),e+".0"+this.vpcC.profile+"."+t+"."+r},s.av01SampleEntry.prototype.getCodec=function(){var e=s.SampleEntry.prototype.getCodec.call(this),t=this.av1C.seq_level_idx_0;t<10&&(t="0"+t);var r;return this.av1C.seq_profile===2&&this.av1C.high_bitdepth===1?r=this.av1C.twelve_bit===1?"12":"10":this.av1C.seq_profile<=2&&(r=this.av1C.high_bitdepth===1?"10":"08"),e+"."+this.av1C.seq_profile+"."+t+(this.av1C.seq_tier_0?"H":"M")+"."+r},s.Box.prototype.writeHeader=function(e,t){this.size+=8,this.size>f&&(this.size+=8),this.type==="uuid"&&(this.size+=16),n.debug("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+e.getPosition()+(t||"")),this.size>f?e.writeUint32(1):(this.sizePosition=e.getPosition(),e.writeUint32(this.size)),e.writeString(this.type,null,4),this.type==="uuid"&&e.writeUint8Array(this.uuid),this.size>f&&e.writeUint64(this.size)},s.FullBox.prototype.writeHeader=function(e){this.size+=4,s.Box.prototype.writeHeader.call(this,e," v="+this.version+" f="+this.flags),e.writeUint8(this.version),e.writeUint24(this.flags)},s.Box.prototype.write=function(e){this.type==="mdat"?this.data&&(this.size=this.data.length,this.writeHeader(e),e.writeUint8Array(this.data)):(this.size=this.data?this.data.length:0,this.writeHeader(e),this.data&&e.writeUint8Array(this.data))},s.ContainerBox.prototype.write=function(e){this.size=0,this.writeHeader(e);for(var t=0;t<this.boxes.length;t++)this.boxes[t]&&(this.boxes[t].write(e),this.size+=this.boxes[t].size);n.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),e.adjustUint32(this.sizePosition,this.size)},s.TrackReferenceTypeBox.prototype.write=function(e){this.size=this.track_ids.length*4,this.writeHeader(e),e.writeUint32Array(this.track_ids)},s.avcCBox.prototype.write=function(e){var t;for(this.size=7,t=0;t<this.SPS.length;t++)this.size+=2+this.SPS[t].length;for(t=0;t<this.PPS.length;t++)this.size+=2+this.PPS[t].length;for(this.ext&&(this.size+=this.ext.length),this.writeHeader(e),e.writeUint8(this.configurationVersion),e.writeUint8(this.AVCProfileIndication),e.writeUint8(this.profile_compatibility),e.writeUint8(this.AVCLevelIndication),e.writeUint8(this.lengthSizeMinusOne+252),e.writeUint8(this.SPS.length+224),t=0;t<this.SPS.length;t++)e.writeUint16(this.SPS[t].length),e.writeUint8Array(this.SPS[t].nalu);for(e.writeUint8(this.PPS.length),t=0;t<this.PPS.length;t++)e.writeUint16(this.PPS[t].length),e.writeUint8Array(this.PPS[t].nalu);this.ext&&e.writeUint8Array(this.ext)},s.co64Box.prototype.write=function(e){var t;for(this.version=0,this.flags=0,this.size=4+8*this.chunk_offsets.length,this.writeHeader(e),e.writeUint32(this.chunk_offsets.length),t=0;t<this.chunk_offsets.length;t++)e.writeUint64(this.chunk_offsets[t])},s.cslgBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4*5,this.writeHeader(e),e.writeInt32(this.compositionToDTSShift),e.writeInt32(this.leastDecodeToDisplayDelta),e.writeInt32(this.greatestDecodeToDisplayDelta),e.writeInt32(this.compositionStartTime),e.writeInt32(this.compositionEndTime)},s.cttsBox.prototype.write=function(e){var t;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(e),e.writeUint32(this.sample_counts.length),t=0;t<this.sample_counts.length;t++)e.writeUint32(this.sample_counts[t]),this.version===1?e.writeInt32(this.sample_offsets[t]):e.writeUint32(this.sample_offsets[t])},s.drefBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4,this.writeHeader(e),e.writeUint32(this.entries.length);for(var t=0;t<this.entries.length;t++)this.entries[t].write(e),this.size+=this.entries[t].size;n.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),e.adjustUint32(this.sizePosition,this.size)},s.elngBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=this.extended_language.length,this.writeHeader(e),e.writeString(this.extended_language)},s.elstBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4+12*this.entries.length,this.writeHeader(e),e.writeUint32(this.entries.length);for(var t=0;t<this.entries.length;t++){var r=this.entries[t];e.writeUint32(r.segment_duration),e.writeInt32(r.media_time),e.writeInt16(r.media_rate_integer),e.writeInt16(r.media_rate_fraction)}},s.emsgBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4*4+this.message_data.length+(this.scheme_id_uri.length+1)+(this.value.length+1),this.writeHeader(e),e.writeCString(this.scheme_id_uri),e.writeCString(this.value),e.writeUint32(this.timescale),e.writeUint32(this.presentation_time_delta),e.writeUint32(this.event_duration),e.writeUint32(this.id),e.writeUint8Array(this.message_data)},s.ftypBox.prototype.write=function(e){this.size=8+4*this.compatible_brands.length,this.writeHeader(e),e.writeString(this.major_brand,null,4),e.writeUint32(this.minor_version);for(var t=0;t<this.compatible_brands.length;t++)e.writeString(this.compatible_brands[t],null,4)},s.hdlrBox.prototype.write=function(e){this.size=5*4+this.name.length+1,this.version=0,this.flags=0,this.writeHeader(e),e.writeUint32(0),e.writeString(this.handler,null,4),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeCString(this.name)},s.hvcCBox.prototype.write=function(e){var t,r;for(this.size=23,t=0;t<this.nalu_arrays.length;t++)for(this.size+=3,r=0;r<this.nalu_arrays[t].length;r++)this.size+=2+this.nalu_arrays[t][r].data.length;for(this.writeHeader(e),e.writeUint8(this.configurationVersion),e.writeUint8((this.general_profile_space<<6)+(this.general_tier_flag<<5)+this.general_profile_idc),e.writeUint32(this.general_profile_compatibility),e.writeUint8Array(this.general_constraint_indicator),e.writeUint8(this.general_level_idc),e.writeUint16(this.min_spatial_segmentation_idc+(15<<24)),e.writeUint8(this.parallelismType+252),e.writeUint8(this.chroma_format_idc+252),e.writeUint8(this.bit_depth_luma_minus8+248),e.writeUint8(this.bit_depth_chroma_minus8+248),e.writeUint16(this.avgFrameRate),e.writeUint8((this.constantFrameRate<<6)+(this.numTemporalLayers<<3)+(this.temporalIdNested<<2)+this.lengthSizeMinusOne),e.writeUint8(this.nalu_arrays.length),t=0;t<this.nalu_arrays.length;t++)for(e.writeUint8((this.nalu_arrays[t].completeness<<7)+this.nalu_arrays[t].nalu_type),e.writeUint16(this.nalu_arrays[t].length),r=0;r<this.nalu_arrays[t].length;r++)e.writeUint16(this.nalu_arrays[t][r].data.length),e.writeUint8Array(this.nalu_arrays[t][r].data)},s.kindBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=this.schemeURI.length+1+(this.value.length+1),this.writeHeader(e),e.writeCString(this.schemeURI),e.writeCString(this.value)},s.mdhdBox.prototype.write=function(e){this.size=4*4+2*2,this.flags=0,this.version=0,this.writeHeader(e),e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.timescale),e.writeUint32(this.duration),e.writeUint16(this.language),e.writeUint16(0)},s.mehdBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4,this.writeHeader(e),e.writeUint32(this.fragment_duration)},s.mfhdBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4,this.writeHeader(e),e.writeUint32(this.sequence_number)},s.mvhdBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=23*4+2*2,this.writeHeader(e),e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.timescale),e.writeUint32(this.duration),e.writeUint32(this.rate),e.writeUint16(this.volume<<8),e.writeUint16(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32Array(this.matrix),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(this.next_track_id)},s.SampleEntry.prototype.writeHeader=function(e){this.size=8,s.Box.prototype.writeHeader.call(this,e),e.writeUint8(0),e.writeUint8(0),e.writeUint8(0),e.writeUint8(0),e.writeUint8(0),e.writeUint8(0),e.writeUint16(this.data_reference_index)},s.SampleEntry.prototype.writeFooter=function(e){for(var t=0;t<this.boxes.length;t++)this.boxes[t].write(e),this.size+=this.boxes[t].size;n.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),e.adjustUint32(this.sizePosition,this.size)},s.SampleEntry.prototype.write=function(e){this.writeHeader(e),e.writeUint8Array(this.data),this.size+=this.data.length,n.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),e.adjustUint32(this.sizePosition,this.size)},s.VisualSampleEntry.prototype.write=function(e){this.writeHeader(e),this.size+=2*7+6*4+32,e.writeUint16(0),e.writeUint16(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint16(this.width),e.writeUint16(this.height),e.writeUint32(this.horizresolution),e.writeUint32(this.vertresolution),e.writeUint32(0),e.writeUint16(this.frame_count),e.writeUint8(Math.min(31,this.compressorname.length)),e.writeString(this.compressorname,null,31),e.writeUint16(this.depth),e.writeInt16(-1),this.writeFooter(e)},s.AudioSampleEntry.prototype.write=function(e){this.writeHeader(e),this.size+=2*4+3*4,e.writeUint32(0),e.writeUint32(0),e.writeUint16(this.channel_count),e.writeUint16(this.samplesize),e.writeUint16(0),e.writeUint16(0),e.writeUint32(this.samplerate<<16),this.writeFooter(e)},s.stppSampleEntry.prototype.write=function(e){this.writeHeader(e),this.size+=this.namespace.length+1+this.schema_location.length+1+this.auxiliary_mime_types.length+1,e.writeCString(this.namespace),e.writeCString(this.schema_location),e.writeCString(this.auxiliary_mime_types),this.writeFooter(e)},s.SampleGroupEntry.prototype.write=function(e){e.writeUint8Array(this.data)},s.sbgpBox.prototype.write=function(e){this.version=1,this.flags=0,this.size=12+8*this.entries.length,this.writeHeader(e),e.writeString(this.grouping_type,null,4),e.writeUint32(this.grouping_type_parameter),e.writeUint32(this.entries.length);for(var t=0;t<this.entries.length;t++){var r=this.entries[t];e.writeInt32(r.sample_count),e.writeInt32(r.group_description_index)}},s.sgpdBox.prototype.write=function(e){var t,r;for(this.flags=0,this.size=12,t=0;t<this.entries.length;t++)r=this.entries[t],this.version===1&&(this.default_length===0&&(this.size+=4),this.size+=r.data.length);for(this.writeHeader(e),e.writeString(this.grouping_type,null,4),this.version===1&&e.writeUint32(this.default_length),this.version>=2&&e.writeUint32(this.default_sample_description_index),e.writeUint32(this.entries.length),t=0;t<this.entries.length;t++)r=this.entries[t],this.version===1&&this.default_length===0&&e.writeUint32(r.description_length),r.write(e)},s.sidxBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4*4+2+2+12*this.references.length,this.writeHeader(e),e.writeUint32(this.reference_ID),e.writeUint32(this.timescale),e.writeUint32(this.earliest_presentation_time),e.writeUint32(this.first_offset),e.writeUint16(0),e.writeUint16(this.references.length);for(var t=0;t<this.references.length;t++){var r=this.references[t];e.writeUint32(r.reference_type<<31|r.referenced_size),e.writeUint32(r.subsegment_duration),e.writeUint32(r.starts_with_SAP<<31|r.SAP_type<<28|r.SAP_delta_time)}},s.smhdBox.prototype.write=function(e){this.version=0,this.flags=1,this.size=4,this.writeHeader(e),e.writeUint16(this.balance),e.writeUint16(0)},s.stcoBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4+4*this.chunk_offsets.length,this.writeHeader(e),e.writeUint32(this.chunk_offsets.length),e.writeUint32Array(this.chunk_offsets)},s.stscBox.prototype.write=function(e){var t;for(this.version=0,this.flags=0,this.size=4+12*this.first_chunk.length,this.writeHeader(e),e.writeUint32(this.first_chunk.length),t=0;t<this.first_chunk.length;t++)e.writeUint32(this.first_chunk[t]),e.writeUint32(this.samples_per_chunk[t]),e.writeUint32(this.sample_description_index[t])},s.stsdBox.prototype.write=function(e){var t;for(this.version=0,this.flags=0,this.size=0,this.writeHeader(e),e.writeUint32(this.entries.length),this.size+=4,t=0;t<this.entries.length;t++)this.entries[t].write(e),this.size+=this.entries[t].size;n.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),e.adjustUint32(this.sizePosition,this.size)},s.stshBox.prototype.write=function(e){var t;for(this.version=0,this.flags=0,this.size=4+8*this.shadowed_sample_numbers.length,this.writeHeader(e),e.writeUint32(this.shadowed_sample_numbers.length),t=0;t<this.shadowed_sample_numbers.length;t++)e.writeUint32(this.shadowed_sample_numbers[t]),e.writeUint32(this.sync_sample_numbers[t])},s.stssBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4+4*this.sample_numbers.length,this.writeHeader(e),e.writeUint32(this.sample_numbers.length),e.writeUint32Array(this.sample_numbers)},s.stszBox.prototype.write=function(e){var t,r=!0;if(this.version=0,this.flags=0,this.sample_sizes.length>0)for(t=0;t+1<this.sample_sizes.length;)if(this.sample_sizes[t+1]!==this.sample_sizes[0]){r=!1;break}else t++;else r=!1;this.size=8,r||(this.size+=4*this.sample_sizes.length),this.writeHeader(e),r?e.writeUint32(this.sample_sizes[0]):e.writeUint32(0),e.writeUint32(this.sample_sizes.length),r||e.writeUint32Array(this.sample_sizes)},s.sttsBox.prototype.write=function(e){var t;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(e),e.writeUint32(this.sample_counts.length),t=0;t<this.sample_counts.length;t++)e.writeUint32(this.sample_counts[t]),e.writeUint32(this.sample_deltas[t])},s.tfdtBox.prototype.write=function(e){var t=Math.pow(2,32)-1;this.version=this.baseMediaDecodeTime>t?1:0,this.flags=0,this.size=4,this.version===1&&(this.size+=4),this.writeHeader(e),this.version===1?e.writeUint64(this.baseMediaDecodeTime):e.writeUint32(this.baseMediaDecodeTime)},s.tfhdBox.prototype.write=function(e){this.version=0,this.size=4,this.flags&s.TFHD_FLAG_BASE_DATA_OFFSET&&(this.size+=8),this.flags&s.TFHD_FLAG_SAMPLE_DESC&&(this.size+=4),this.flags&s.TFHD_FLAG_SAMPLE_DUR&&(this.size+=4),this.flags&s.TFHD_FLAG_SAMPLE_SIZE&&(this.size+=4),this.flags&s.TFHD_FLAG_SAMPLE_FLAGS&&(this.size+=4),this.writeHeader(e),e.writeUint32(this.track_id),this.flags&s.TFHD_FLAG_BASE_DATA_OFFSET&&e.writeUint64(this.base_data_offset),this.flags&s.TFHD_FLAG_SAMPLE_DESC&&e.writeUint32(this.default_sample_description_index),this.flags&s.TFHD_FLAG_SAMPLE_DUR&&e.writeUint32(this.default_sample_duration),this.flags&s.TFHD_FLAG_SAMPLE_SIZE&&e.writeUint32(this.default_sample_size),this.flags&s.TFHD_FLAG_SAMPLE_FLAGS&&e.writeUint32(this.default_sample_flags)},s.tkhdBox.prototype.write=function(e){this.version=0,this.size=4*18+2*4,this.writeHeader(e),e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.track_id),e.writeUint32(0),e.writeUint32(this.duration),e.writeUint32(0),e.writeUint32(0),e.writeInt16(this.layer),e.writeInt16(this.alternate_group),e.writeInt16(this.volume<<8),e.writeUint16(0),e.writeInt32Array(this.matrix),e.writeUint32(this.width),e.writeUint32(this.height)},s.trexBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4*5,this.writeHeader(e),e.writeUint32(this.track_id),e.writeUint32(this.default_sample_description_index),e.writeUint32(this.default_sample_duration),e.writeUint32(this.default_sample_size),e.writeUint32(this.default_sample_flags)},s.trunBox.prototype.write=function(e){this.version=0,this.size=4,this.flags&s.TRUN_FLAGS_DATA_OFFSET&&(this.size+=4),this.flags&s.TRUN_FLAGS_FIRST_FLAG&&(this.size+=4),this.flags&s.TRUN_FLAGS_DURATION&&(this.size+=4*this.sample_duration.length),this.flags&s.TRUN_FLAGS_SIZE&&(this.size+=4*this.sample_size.length),this.flags&s.TRUN_FLAGS_FLAGS&&(this.size+=4*this.sample_flags.length),this.flags&s.TRUN_FLAGS_CTS_OFFSET&&(this.size+=4*this.sample_composition_time_offset.length),this.writeHeader(e),e.writeUint32(this.sample_count),this.flags&s.TRUN_FLAGS_DATA_OFFSET&&(this.data_offset_position=e.getPosition(),e.writeInt32(this.data_offset)),this.flags&s.TRUN_FLAGS_FIRST_FLAG&&e.writeUint32(this.first_sample_flags);for(var t=0;t<this.sample_count;t++)this.flags&s.TRUN_FLAGS_DURATION&&e.writeUint32(this.sample_duration[t]),this.flags&s.TRUN_FLAGS_SIZE&&e.writeUint32(this.sample_size[t]),this.flags&s.TRUN_FLAGS_FLAGS&&e.writeUint32(this.sample_flags[t]),this.flags&s.TRUN_FLAGS_CTS_OFFSET&&(this.version===0?e.writeUint32(this.sample_composition_time_offset[t]):e.writeInt32(this.sample_composition_time_offset[t]))},s["url Box"].prototype.write=function(e){this.version=0,this.location?(this.flags=0,this.size=this.location.length+1):(this.flags=1,this.size=0),this.writeHeader(e),this.location&&e.writeCString(this.location)},s["urn Box"].prototype.write=function(e){this.version=0,this.flags=0,this.size=this.name.length+1+(this.location?this.location.length+1:0),this.writeHeader(e),e.writeCString(this.name),this.location&&e.writeCString(this.location)},s.vmhdBox.prototype.write=function(e){this.version=0,this.flags=1,this.size=8,this.writeHeader(e),e.writeUint16(this.graphicsmode),e.writeUint16Array(this.opcolor)},s.cttsBox.prototype.unpack=function(e){var t,r,l;for(l=0,t=0;t<this.sample_counts.length;t++)for(r=0;r<this.sample_counts[t];r++)e[l].pts=e[l].dts+this.sample_offsets[t],l++},s.sttsBox.prototype.unpack=function(e){var t,r,l;for(l=0,t=0;t<this.sample_counts.length;t++)for(r=0;r<this.sample_counts[t];r++)l===0?e[l].dts=0:e[l].dts=e[l-1].dts+this.sample_deltas[t],l++},s.stcoBox.prototype.unpack=function(e){var t;for(t=0;t<this.chunk_offsets.length;t++)e[t].offset=this.chunk_offsets[t]},s.stscBox.prototype.unpack=function(e){var t,r,l,h,m;for(h=0,m=0,t=0;t<this.first_chunk.length;t++)for(r=0;r<(t+1<this.first_chunk.length?this.first_chunk[t+1]:1/0);r++)for(m++,l=0;l<this.samples_per_chunk[t];l++){if(e[h])e[h].description_index=this.sample_description_index[t],e[h].chunk_index=m;else return;h++}},s.stszBox.prototype.unpack=function(e){var t;for(t=0;t<this.sample_sizes.length;t++)e[t].size=this.sample_sizes[t]},s.DIFF_BOXES_PROP_NAMES=["boxes","entries","references","subsamples","items","item_infos","extents","associations","subsegments","ranges","seekLists","seekPoints","esd","levels"],s.DIFF_PRIMITIVE_ARRAY_PROP_NAMES=["compatible_brands","matrix","opcolor","sample_counts","sample_counts","sample_deltas","first_chunk","samples_per_chunk","sample_sizes","chunk_offsets","sample_offsets","sample_description_index","sample_duration"],s.boxEqualFields=function(e,t){if(e&&!t)return!1;var r;for(r in e)if(!(s.DIFF_BOXES_PROP_NAMES.indexOf(r)>-1)){if(e[r]instanceof s.Box||t[r]instanceof s.Box)continue;if(typeof e[r]>"u"||typeof t[r]>"u")continue;if(typeof e[r]=="function"||typeof t[r]=="function")continue;if(e.subBoxNames&&e.subBoxNames.indexOf(r.slice(0,4))>-1||t.subBoxNames&&t.subBoxNames.indexOf(r.slice(0,4))>-1)continue;if(r==="data"||r==="start"||r==="size"||r==="creation_time"||r==="modification_time")continue;if(s.DIFF_PRIMITIVE_ARRAY_PROP_NAMES.indexOf(r)>-1)continue;if(e[r]!==t[r])return!1}return!0},s.boxEqual=function(e,t){if(!s.boxEqualFields(e,t))return!1;for(var r=0;r<s.DIFF_BOXES_PROP_NAMES.length;r++){var l=s.DIFF_BOXES_PROP_NAMES[r];if(e[l]&&t[l]&&!s.boxEqual(e[l],t[l]))return!1}return!0};var g=function(){};g.prototype.parseSample=function(e){var t,r,l=new o(e.buffer);for(t=[];!l.isEos();)r=s.parseOneBox(l,!1),r.code===s.OK&&r.box.type==="vttc"&&t.push(r.box);return t},g.prototype.getText=function(e,t,r){function l(w,T,C){return C=C||"0",w=w+"",w.length>=T?w:new Array(T-w.length+1).join(C)+w}function h(w){var T=Math.floor(w/3600),C=Math.floor((w-T*3600)/60),F=Math.floor(w-T*3600-C*60),A=Math.floor((w-T*3600-C*60-F)*1e3);return""+l(T,2)+":"+l(C,2)+":"+l(F,2)+"."+l(A,3)}for(var m=this.parseSample(r),y="",b=0;b<m.length;b++){var x=m[b];y+=h(e)+" --> "+h(t)+`\\r\n`,y+=x.payl.text}return y};var v=function(){};v.prototype.parseSample=function(e){var t={},r;t.resources=[];var l=new o(e.data.buffer);if(!e.subsamples||e.subsamples.length===0)t.documentString=l.readString(e.data.length);else if(t.documentString=l.readString(e.subsamples[0].size),e.subsamples.length>1)for(r=1;r<e.subsamples.length;r++)t.resources[r]=l.readUint8Array(e.subsamples[r].size);return typeof DOMParser<"u"&&(t.document=new DOMParser().parseFromString(t.documentString,"application/xml")),t};var U=function(){};U.prototype.parseSample=function(e){var t,r=new o(e.data.buffer);return t=r.readString(e.data.length),t},U.prototype.parseConfig=function(e){var t,r=new o(e.buffer);return r.readUint32(),t=r.readCString(),t},a.VTTin4Parser=g,a.XMLSubtitlein4Parser=v,a.Textin4Parser=U;var S=function(e){this.stream=e||new c,this.boxes=[],this.mdats=[],this.moofs=[],this.isProgressive=!1,this.moovStartFound=!1,this.onMoovStart=null,this.moovStartSent=!1,this.onReady=null,this.readySent=!1,this.onSegment=null,this.onSamples=null,this.onError=null,this.sampleListBuilt=!1,this.fragmentedTracks=[],this.extractedTracks=[],this.isFragmentationInitialized=!1,this.sampleProcessingStarted=!1,this.nextMoofNumber=0,this.itemListBuilt=!1,this.items=[],this.entity_groups=[],this.onSidx=null,this.sidxSent=!1};S.prototype.setSegmentOptions=function(e,t,r){var l=this.getTrackById(e);if(l){var h={};this.fragmentedTracks.push(h),h.id=e,h.user=t,h.trak=l,l.nextSample=0,h.segmentStream=null,h.nb_samples=1e3,h.rapAlignement=!0,r&&(r.nbSamples&&(h.nb_samples=r.nbSamples),r.rapAlignement&&(h.rapAlignement=r.rapAlignement))}},S.prototype.unsetSegmentOptions=function(e){for(var t=-1,r=0;r<this.fragmentedTracks.length;r++){var l=this.fragmentedTracks[r];l.id==e&&(t=r)}t>-1&&this.fragmentedTracks.splice(t,1)},S.prototype.setExtractionOptions=function(e,t,r){var l=this.getTrackById(e);if(l){var h={};this.extractedTracks.push(h),h.id=e,h.user=t,h.trak=l,l.nextSample=0,h.nb_samples=1e3,h.samples=[],r&&r.nbSamples&&(h.nb_samples=r.nbSamples)}},S.prototype.unsetExtractionOptions=function(e){for(var t=-1,r=0;r<this.extractedTracks.length;r++){var l=this.extractedTracks[r];l.id==e&&(t=r)}t>-1&&this.extractedTracks.splice(t,1)},S.prototype.parse=function(){var e,t,r=!1;if(!(this.restoreParsePosition&&!this.restoreParsePosition()))for(;;)if(this.hasIncompleteMdat&&this.hasIncompleteMdat()){if(this.processIncompleteMdat())continue;return}else if(this.saveParsePosition&&this.saveParsePosition(),e=s.parseOneBox(this.stream,r),e.code===s.ERR_NOT_ENOUGH_DATA)if(this.processIncompleteBox){if(this.processIncompleteBox(e))continue;return}else return;else{var l;switch(t=e.box,l=t.type!=="uuid"?t.type:t.uuid,this.boxes.push(t),l){case"mdat":this.mdats.push(t);break;case"moof":this.moofs.push(t);break;case"moov":this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0);default:this[l]!==void 0&&n.warn("ISOFile","Duplicate Box of type: "+l+", overriding previous occurrence"),this[l]=t;break}this.updateUsedBytes&&this.updateUsedBytes(t,e)}},S.prototype.checkBuffer=function(e){if(e==null)throw"Buffer must be defined and non empty";if(e.fileStart===void 0)throw"Buffer must have a fileStart property";return e.byteLength===0?(n.warn("ISOFile","Ignoring empty buffer (fileStart: "+e.fileStart+")"),this.stream.logBufferLevel(),!1):(n.info("ISOFile","Processing buffer (fileStart: "+e.fileStart+")"),e.usedBytes=0,this.stream.insertBuffer(e),this.stream.logBufferLevel(),this.stream.initialized()?!0:(n.warn("ISOFile","Not ready to start parsing"),!1))},S.prototype.appendBuffer=function(e,t){var r;if(this.checkBuffer(e))return this.parse(),this.moovStartFound&&!this.moovStartSent&&(this.moovStartSent=!0,this.onMoovStart&&this.onMoovStart()),this.moov?(this.sampleListBuilt||(this.buildSampleLists(),this.sampleListBuilt=!0),this.updateSampleLists(),this.onReady&&!this.readySent&&(this.readySent=!0,this.onReady(this.getInfo())),this.processSamples(t),this.nextSeekPosition?(r=this.nextSeekPosition,this.nextSeekPosition=void 0):r=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(r=this.stream.getEndFilePositionAfter(r))):this.nextParsePosition?r=this.nextParsePosition:r=0,this.sidx&&this.onSidx&&!this.sidxSent&&(this.onSidx(this.sidx),this.sidxSent=!0),this.meta&&(this.flattenItemInfo&&!this.itemListBuilt&&(this.flattenItemInfo(),this.itemListBuilt=!0),this.processItems&&this.processItems(this.onItem)),this.stream.cleanBuffers&&(n.info("ISOFile","Done processing buffer (fileStart: "+e.fileStart+") - next buffer to fetch should have a fileStart position of "+r),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),n.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize())),r},S.prototype.getInfo=function(){var e,t,r={},l,h,m,y,b=new Date("1904-01-01T00:00:00Z").getTime();if(this.moov)for(r.hasMoov=!0,r.duration=this.moov.mvhd.duration,r.timescale=this.moov.mvhd.timescale,r.isFragmented=this.moov.mvex!=null,r.isFragmented&&this.moov.mvex.mehd&&(r.fragment_duration=this.moov.mvex.mehd.fragment_duration),r.isProgressive=this.isProgressive,r.hasIOD=this.moov.iods!=null,r.brands=[],r.brands.push(this.ftyp.major_brand),r.brands=r.brands.concat(this.ftyp.compatible_brands),r.created=new Date(b+this.moov.mvhd.creation_time*1e3),r.modified=new Date(b+this.moov.mvhd.modification_time*1e3),r.tracks=[],r.audioTracks=[],r.videoTracks=[],r.subtitleTracks=[],r.metadataTracks=[],r.hintTracks=[],r.otherTracks=[],e=0;e<this.moov.traks.length;e++){if(l=this.moov.traks[e],y=l.mdia.minf.stbl.stsd.entries[0],h={},r.tracks.push(h),h.id=l.tkhd.track_id,h.name=l.mdia.hdlr.name,h.references=[],l.tref)for(t=0;t<l.tref.boxes.length;t++)m={},h.references.push(m),m.type=l.tref.boxes[t].type,m.track_ids=l.tref.boxes[t].track_ids;l.edts&&(h.edits=l.edts.elst.entries),h.created=new Date(b+l.tkhd.creation_time*1e3),h.modified=new Date(b+l.tkhd.modification_time*1e3),h.movie_duration=l.tkhd.duration,h.movie_timescale=r.timescale,h.layer=l.tkhd.layer,h.alternate_group=l.tkhd.alternate_group,h.volume=l.tkhd.volume,h.matrix=l.tkhd.matrix,h.track_width=l.tkhd.width/65536,h.track_height=l.tkhd.height/65536,h.timescale=l.mdia.mdhd.timescale,h.cts_shift=l.mdia.minf.stbl.cslg,h.duration=l.mdia.mdhd.duration,h.samples_duration=l.samples_duration,h.codec=y.getCodec(),h.kind=l.udta&&l.udta.kinds.length?l.udta.kinds[0]:{schemeURI:"",value:""},h.language=l.mdia.elng?l.mdia.elng.extended_language:l.mdia.mdhd.languageString,h.nb_samples=l.samples.length,h.size=l.samples_size,h.bitrate=h.size*8*h.timescale/h.samples_duration,y.isAudio()?(h.type="audio",r.audioTracks.push(h),h.audio={},h.audio.sample_rate=y.getSampleRate(),h.audio.channel_count=y.getChannelCount(),h.audio.sample_size=y.getSampleSize()):y.isVideo()?(h.type="video",r.videoTracks.push(h),h.video={},h.video.width=y.getWidth(),h.video.height=y.getHeight()):y.isSubtitle()?(h.type="subtitles",r.subtitleTracks.push(h)):y.isHint()?(h.type="metadata",r.hintTracks.push(h)):y.isMetadata()?(h.type="metadata",r.metadataTracks.push(h)):(h.type="metadata",r.otherTracks.push(h))}else r.hasMoov=!1;if(r.mime="",r.hasMoov&&r.tracks){for(r.videoTracks&&r.videoTracks.length>0?r.mime+=\'video/mp4; codecs="\':r.audioTracks&&r.audioTracks.length>0?r.mime+=\'audio/mp4; codecs="\':r.mime+=\'application/mp4; codecs="\',e=0;e<r.tracks.length;e++)e!==0&&(r.mime+=","),r.mime+=r.tracks[e].codec;r.mime+=\'"; profiles="\',r.mime+=this.ftyp.compatible_brands.join(),r.mime+=\'"\'}return r},S.prototype.setNextSeekPositionFromSample=function(e){e&&(this.nextSeekPosition?this.nextSeekPosition=Math.min(e.offset+e.alreadyRead,this.nextSeekPosition):this.nextSeekPosition=e.offset+e.alreadyRead)},S.prototype.processSamples=function(e){var t,r;if(this.sampleProcessingStarted){if(this.isFragmentationInitialized&&this.onSegment!==null)for(t=0;t<this.fragmentedTracks.length;t++){var l=this.fragmentedTracks[t];for(r=l.trak;r.nextSample<r.samples.length&&this.sampleProcessingStarted;){n.debug("ISOFile","Creating media fragment on track #"+l.id+" for sample "+r.nextSample);var h=this.createFragment(l.id,r.nextSample,l.segmentStream);if(h)l.segmentStream=h,r.nextSample++;else break;if((r.nextSample%l.nb_samples===0||e||r.nextSample>=r.samples.length)&&(n.info("ISOFile","Sending fragmented data on track #"+l.id+" for samples ["+Math.max(0,r.nextSample-l.nb_samples)+","+(r.nextSample-1)+"]"),n.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(l.id,l.user,l.segmentStream.buffer,r.nextSample,e||r.nextSample>=r.samples.length),l.segmentStream=null,l!==this.fragmentedTracks[t]))break}}if(this.onSamples!==null)for(t=0;t<this.extractedTracks.length;t++){var m=this.extractedTracks[t];for(r=m.trak;r.nextSample<r.samples.length&&this.sampleProcessingStarted;){n.debug("ISOFile","Exporting on track #"+m.id+" sample #"+r.nextSample);var y=this.getSample(r,r.nextSample);if(y)r.nextSample++,m.samples.push(y);else{this.setNextSeekPositionFromSample(r.samples[r.nextSample]);break}if((r.nextSample%m.nb_samples===0||r.nextSample>=r.samples.length)&&(n.debug("ISOFile","Sending samples on track #"+m.id+" for sample "+r.nextSample),this.onSamples&&this.onSamples(m.id,m.user,m.samples),m.samples=[],m!==this.extractedTracks[t]))break}}}},S.prototype.getBox=function(e){var t=this.getBoxes(e,!0);return t.length?t[0]:null},S.prototype.getBoxes=function(e,t){var r=[];return S._sweep.call(this,e,r,t),r},S._sweep=function(e,t,r){this.type&&this.type==e&&t.push(this);for(var l in this.boxes){if(t.length&&r)return;S._sweep.call(this.boxes[l],e,t,r)}},S.prototype.getTrackSamplesInfo=function(e){var t=this.getTrackById(e);if(t)return t.samples},S.prototype.getTrackSample=function(e,t){var r=this.getTrackById(e),l=this.getSample(r,t);return l},S.prototype.releaseUsedSamples=function(e,t){var r=0,l=this.getTrackById(e);l.lastValidSample||(l.lastValidSample=0);for(var h=l.lastValidSample;h<t;h++)r+=this.releaseSample(l,h);n.info("ISOFile","Track #"+e+" released samples up to "+t+" (released size: "+r+", remaining: "+this.samplesDataSize+")"),l.lastValidSample=t},S.prototype.start=function(){this.sampleProcessingStarted=!0,this.processSamples(!1)},S.prototype.stop=function(){this.sampleProcessingStarted=!1},S.prototype.flush=function(){n.info("ISOFile","Flushing remaining samples"),this.updateSampleLists(),this.processSamples(!0),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0)},S.prototype.seekTrack=function(e,t,r){var l,h,m=1/0,y=0,b=0,x;if(r.samples.length===0)return n.info("ISOFile","No sample in track, cannot seek! Using time "+n.getDurationString(0,1)+" and offset: 0"),{offset:0,time:0};for(l=0;l<r.samples.length;l++){if(h=r.samples[l],l===0)b=0,x=h.timescale;else if(h.cts>e*h.timescale){b=l-1;break}t&&h.is_sync&&(y=l)}for(t&&(b=y),e=r.samples[b].cts,r.nextSample=b;r.samples[b].alreadyRead===r.samples[b].size&&r.samples[b+1];)b++;return m=r.samples[b].offset+r.samples[b].alreadyRead,n.info("ISOFile","Seeking to "+(t?"RAP":"")+" sample #"+r.nextSample+" on track "+r.tkhd.track_id+", time "+n.getDurationString(e,x)+" and offset: "+m),{offset:m,time:e/x}},S.prototype.getTrackDuration=function(e){var t;return e.samples?(t=e.samples[e.samples.length-1],(t.cts+t.duration)/t.timescale):1/0},S.prototype.seek=function(e,t){var r=this.moov,l,h,m,y={offset:1/0,time:1/0};if(this.moov){for(m=0;m<r.traks.length;m++)l=r.traks[m],!(e>this.getTrackDuration(l))&&(h=this.seekTrack(e,t,l),h.offset<y.offset&&(y.offset=h.offset),h.time<y.time&&(y.time=h.time));return n.info("ISOFile","Seeking at time "+n.getDurationString(y.time,1)+" needs a buffer with a fileStart position of "+y.offset),y.offset===1/0?y={offset:this.nextParsePosition,time:0}:y.offset=this.stream.getEndFilePositionAfter(y.offset),n.info("ISOFile","Adjusted seek position (after checking data already in buffer): "+y.offset),y}else throw"Cannot seek: moov not received!"},S.prototype.equal=function(e){for(var t=0;t<this.boxes.length&&t<e.boxes.length;){var r=this.boxes[t],l=e.boxes[t];if(!s.boxEqual(r,l))return!1;t++}return!0},a.ISOFile=S,S.prototype.lastBoxStartPosition=0,S.prototype.parsingMdat=null,S.prototype.nextParsePosition=0,S.prototype.discardMdatData=!1,S.prototype.processIncompleteBox=function(e){var t,r,l;return e.type==="mdat"?(t=new s[e.type+"Box"](e.size),this.parsingMdat=t,this.boxes.push(t),this.mdats.push(t),t.start=e.start,t.hdr_size=e.hdr_size,this.stream.addUsedBytes(t.hdr_size),this.lastBoxStartPosition=t.start+t.size,l=this.stream.seek(t.start+t.size,!1,this.discardMdatData),l?(this.parsingMdat=null,!0):(this.moovStartFound?this.nextParsePosition=this.stream.findEndContiguousBuf():this.nextParsePosition=t.start+t.size,!1)):(e.type==="moov"&&(this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0)),r=this.stream.mergeNextBuffer?this.stream.mergeNextBuffer():!1,r?(this.nextParsePosition=this.stream.getEndPosition(),!0):(e.type?this.moovStartFound?this.nextParsePosition=this.stream.getEndPosition():this.nextParsePosition=this.stream.getPosition()+e.size:this.nextParsePosition=this.stream.getEndPosition(),!1))},S.prototype.hasIncompleteMdat=function(){return this.parsingMdat!==null},S.prototype.processIncompleteMdat=function(){var e,t;return e=this.parsingMdat,t=this.stream.seek(e.start+e.size,!1,this.discardMdatData),t?(n.debug("ISOFile","Found \'mdat\' end in buffered data"),this.parsingMdat=null,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)},S.prototype.restoreParsePosition=function(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)},S.prototype.saveParsePosition=function(){this.lastBoxStartPosition=this.stream.getPosition()},S.prototype.updateUsedBytes=function(e,t){this.stream.addUsedBytes&&(e.type==="mdat"?(this.stream.addUsedBytes(e.hdr_size),this.discardMdatData&&this.stream.addUsedBytes(e.size-e.hdr_size)):this.stream.addUsedBytes(e.size))},S.prototype.add=s.Box.prototype.add,S.prototype.addBox=s.Box.prototype.addBox,S.prototype.init=function(e){var t=e||{};this.add("ftyp").set("major_brand",t.brands&&t.brands[0]||"iso4").set("minor_version",0).set("compatible_brands",t.brands||["iso4"]);var r=this.add("moov");return r.add("mvhd").set("timescale",t.timescale||600).set("rate",t.rate||65536).set("creation_time",0).set("modification_time",0).set("duration",t.duration||0).set("volume",t.width?0:256).set("matrix",[65536,0,0,0,65536,0,0,0,1073741824]).set("next_track_id",1),r.add("mvex"),this},S.prototype.addTrack=function(e){this.moov||this.init(e);var t=e||{};t.width=t.width||320,t.height=t.height||320,t.id=t.id||this.moov.mvhd.next_track_id,t.type=t.type||"avc1";var r=this.moov.add("trak");this.moov.mvhd.next_track_id=t.id+1,r.add("tkhd").set("flags",s.TKHD_FLAG_ENABLED|s.TKHD_FLAG_IN_MOVIE|s.TKHD_FLAG_IN_PREVIEW).set("creation_time",0).set("modification_time",0).set("track_id",t.id).set("duration",t.duration||0).set("layer",t.layer||0).set("alternate_group",0).set("volume",1).set("matrix",[0,0,0,0,0,0,0,0,0]).set("width",t.width<<16).set("height",t.height<<16);var l=r.add("mdia");l.add("mdhd").set("creation_time",0).set("modification_time",0).set("timescale",t.timescale||1).set("duration",t.media_duration||0).set("language",t.language||"und"),l.add("hdlr").set("handler",t.hdlr||"vide").set("name",t.name||"Track created with MP4Box.js"),l.add("elng").set("extended_language",t.language||"fr-FR");var h=l.add("minf");if(s[t.type+"SampleEntry"]!==void 0){var m=new s[t.type+"SampleEntry"];m.data_reference_index=1;var y="";for(var b in s.sampleEntryCodes)for(var x=s.sampleEntryCodes[b],w=0;w<x.length;w++)if(x.indexOf(t.type)>-1){y=b;break}switch(y){case"Visual":if(h.add("vmhd").set("graphicsmode",0).set("opcolor",[0,0,0]),m.set("width",t.width).set("height",t.height).set("horizresolution",72<<16).set("vertresolution",72<<16).set("frame_count",1).set("compressorname",t.type+" Compressor").set("depth",24),t.avcDecoderConfigRecord){var T=new s.avcCBox;T.parse(new o(t.avcDecoderConfigRecord)),m.addBox(T)}else if(t.hevcDecoderConfigRecord){var C=new s.hvcCBox;C.parse(new o(t.hevcDecoderConfigRecord)),m.addBox(C)}break;case"Audio":h.add("smhd").set("balance",t.balance||0),m.set("channel_count",t.channel_count||2).set("samplesize",t.samplesize||16).set("samplerate",t.samplerate||65536);break;case"Hint":h.add("hmhd");break;case"Subtitle":switch(h.add("sthd"),t.type){case"stpp":m.set("namespace",t.namespace||"nonamespace").set("schema_location",t.schema_location||"").set("auxiliary_mime_types",t.auxiliary_mime_types||"");break}break;case"Metadata":h.add("nmhd");break;case"System":h.add("nmhd");break;default:h.add("nmhd");break}t.description&&m.addBox(t.description),t.description_boxes&&t.description_boxes.forEach(function(A){m.addBox(A)}),h.add("dinf").add("dref").addEntry(new s["url Box"]().set("flags",1));var F=h.add("stbl");return F.add("stsd").addEntry(m),F.add("stts").set("sample_counts",[]).set("sample_deltas",[]),F.add("stsc").set("first_chunk",[]).set("samples_per_chunk",[]).set("sample_description_index",[]),F.add("stco").set("chunk_offsets",[]),F.add("stsz").set("sample_sizes",[]),this.moov.mvex.add("trex").set("track_id",t.id).set("default_sample_description_index",t.default_sample_description_index||1).set("default_sample_duration",t.default_sample_duration||0).set("default_sample_size",t.default_sample_size||0).set("default_sample_flags",t.default_sample_flags||0),this.buildTrakSampleLists(r),t.id}},s.Box.prototype.computeSize=function(e){var t=e||new d;t.endianness=d.BIG_ENDIAN,this.write(t)},S.prototype.addSample=function(e,t,r){var l=r||{},h={},m=this.getTrackById(e);if(m!==null){h.number=m.samples.length,h.track_id=m.tkhd.track_id,h.timescale=m.mdia.mdhd.timescale,h.description_index=l.sample_description_index?l.sample_description_index-1:0,h.description=m.mdia.minf.stbl.stsd.entries[h.description_index],h.data=t,h.size=t.byteLength,h.alreadyRead=h.size,h.duration=l.duration||1,h.cts=l.cts||0,h.dts=l.dts||0,h.is_sync=l.is_sync||!1,h.is_leading=l.is_leading||0,h.depends_on=l.depends_on||0,h.is_depended_on=l.is_depended_on||0,h.has_redundancy=l.has_redundancy||0,h.degradation_priority=l.degradation_priority||0,h.offset=0,h.subsamples=l.subsamples,m.samples.push(h),m.samples_size+=h.size,m.samples_duration+=h.duration,m.first_dts===void 0&&(m.first_dts=l.dts),this.processSamples();var y=this.createSingleSampleMoof(h);return this.addBox(y),y.computeSize(),y.trafs[0].truns[0].data_offset=y.size+8,this.add("mdat").data=new Uint8Array(t),h}},S.prototype.createSingleSampleMoof=function(e){var t=0;e.is_sync?t=1<<25:t=65536;var r=new s.moofBox;r.add("mfhd").set("sequence_number",this.nextMoofNumber),this.nextMoofNumber++;var l=r.add("traf"),h=this.getTrackById(e.track_id);return l.add("tfhd").set("track_id",e.track_id).set("flags",s.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),l.add("tfdt").set("baseMediaDecodeTime",e.dts-(h.first_dts||0)),l.add("trun").set("flags",s.TRUN_FLAGS_DATA_OFFSET|s.TRUN_FLAGS_DURATION|s.TRUN_FLAGS_SIZE|s.TRUN_FLAGS_FLAGS|s.TRUN_FLAGS_CTS_OFFSET).set("data_offset",0).set("first_sample_flags",0).set("sample_count",1).set("sample_duration",[e.duration]).set("sample_size",[e.size]).set("sample_flags",[t]).set("sample_composition_time_offset",[e.cts-e.dts]),r},S.prototype.lastMoofIndex=0,S.prototype.samplesDataSize=0,S.prototype.resetTables=function(){var e,t,r,l,h,m,y,b;for(this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=0,e=0;e<this.moov.traks.length;e++){t=this.moov.traks[e],t.tkhd.duration=0,t.mdia.mdhd.duration=0,r=t.mdia.minf.stbl.stco||t.mdia.minf.stbl.co64,r.chunk_offsets=[],l=t.mdia.minf.stbl.stsc,l.first_chunk=[],l.samples_per_chunk=[],l.sample_description_index=[],h=t.mdia.minf.stbl.stsz||t.mdia.minf.stbl.stz2,h.sample_sizes=[],m=t.mdia.minf.stbl.stts,m.sample_counts=[],m.sample_deltas=[],y=t.mdia.minf.stbl.ctts,y&&(y.sample_counts=[],y.sample_offsets=[]),b=t.mdia.minf.stbl.stss;var x=t.mdia.minf.stbl.boxes.indexOf(b);x!=-1&&(t.mdia.minf.stbl.boxes[x]=null)}},S.initSampleGroups=function(e,t,r,l,h){var m,y,b,x;function w(T,C,F){this.grouping_type=T,this.grouping_type_parameter=C,this.sbgp=F,this.last_sample_in_run=-1,this.entry_index=-1}for(t&&(t.sample_groups_info=[]),e.sample_groups_info||(e.sample_groups_info=[]),y=0;y<r.length;y++){for(x=r[y].grouping_type+"/"+r[y].grouping_type_parameter,b=new w(r[y].grouping_type,r[y].grouping_type_parameter,r[y]),t&&(t.sample_groups_info[x]=b),e.sample_groups_info[x]||(e.sample_groups_info[x]=b),m=0;m<l.length;m++)l[m].grouping_type===r[y].grouping_type&&(b.description=l[m],b.description.used=!0);if(h)for(m=0;m<h.length;m++)h[m].grouping_type===r[y].grouping_type&&(b.fragment_description=h[m],b.fragment_description.used=!0,b.is_fragment=!0)}if(t){if(h)for(y=0;y<h.length;y++)!h[y].used&&h[y].version>=2&&(x=h[y].grouping_type+"/0",b=new w(h[y].grouping_type,0),b.is_fragment=!0,t.sample_groups_info[x]||(t.sample_groups_info[x]=b))}else for(y=0;y<l.length;y++)!l[y].used&&l[y].version>=2&&(x=l[y].grouping_type+"/0",b=new w(l[y].grouping_type,0),e.sample_groups_info[x]||(e.sample_groups_info[x]=b))},S.setSampleGroupProperties=function(e,t,r,l){var h,m;t.sample_groups=[];for(h in l)if(t.sample_groups[h]={},t.sample_groups[h].grouping_type=l[h].grouping_type,t.sample_groups[h].grouping_type_parameter=l[h].grouping_type_parameter,r>=l[h].last_sample_in_run&&(l[h].last_sample_in_run<0&&(l[h].last_sample_in_run=0),l[h].entry_index++,l[h].entry_index<=l[h].sbgp.entries.length-1&&(l[h].last_sample_in_run+=l[h].sbgp.entries[l[h].entry_index].sample_count)),l[h].entry_index<=l[h].sbgp.entries.length-1?t.sample_groups[h].group_description_index=l[h].sbgp.entries[l[h].entry_index].group_description_index:t.sample_groups[h].group_description_index=-1,t.sample_groups[h].group_description_index!==0){var y;l[h].fragment_description?y=l[h].fragment_description:y=l[h].description,t.sample_groups[h].group_description_index>0?(t.sample_groups[h].group_description_index>65535?m=(t.sample_groups[h].group_description_index>>16)-1:m=t.sample_groups[h].group_description_index-1,y&&m>=0&&(t.sample_groups[h].description=y.entries[m])):y&&y.version>=2&&y.default_group_description_index>0&&(t.sample_groups[h].description=y.entries[y.default_group_description_index-1])}},S.process_sdtp=function(e,t,r){t&&(e?(t.is_leading=e.is_leading[r],t.depends_on=e.sample_depends_on[r],t.is_depended_on=e.sample_is_depended_on[r],t.has_redundancy=e.sample_has_redundancy[r]):(t.is_leading=0,t.depends_on=0,t.is_depended_on=0,t.has_redundancy=0))},S.prototype.buildSampleLists=function(){var e,t;for(e=0;e<this.moov.traks.length;e++)t=this.moov.traks[e],this.buildTrakSampleLists(t)},S.prototype.buildTrakSampleLists=function(e){var t,r,l,h,m,y,b,x,w,T,C,F,A,R,P,K,Z,V,N,q,ee,xe,j,W;if(e.samples=[],e.samples_duration=0,e.samples_size=0,r=e.mdia.minf.stbl.stco||e.mdia.minf.stbl.co64,l=e.mdia.minf.stbl.stsc,h=e.mdia.minf.stbl.stsz||e.mdia.minf.stbl.stz2,m=e.mdia.minf.stbl.stts,y=e.mdia.minf.stbl.ctts,b=e.mdia.minf.stbl.stss,x=e.mdia.minf.stbl.stsd,w=e.mdia.minf.stbl.subs,F=e.mdia.minf.stbl.stdp,T=e.mdia.minf.stbl.sbgps,C=e.mdia.minf.stbl.sgpds,V=-1,N=-1,q=-1,ee=-1,xe=0,j=0,W=0,S.initSampleGroups(e,null,T,C),!(typeof h>"u")){for(t=0;t<h.sample_sizes.length;t++){var L={};L.number=t,L.track_id=e.tkhd.track_id,L.timescale=e.mdia.mdhd.timescale,L.alreadyRead=0,e.samples[t]=L,L.size=h.sample_sizes[t],e.samples_size+=L.size,t===0?(R=1,A=0,L.chunk_index=R,L.chunk_run_index=A,Z=l.samples_per_chunk[A],K=0,A+1<l.first_chunk.length?P=l.first_chunk[A+1]-1:P=1/0):t<Z?(L.chunk_index=R,L.chunk_run_index=A):(R++,L.chunk_index=R,K=0,R<=P||(A++,A+1<l.first_chunk.length?P=l.first_chunk[A+1]-1:P=1/0),L.chunk_run_index=A,Z+=l.samples_per_chunk[A]),L.description_index=l.sample_description_index[L.chunk_run_index]-1,L.description=x.entries[L.description_index],L.offset=r.chunk_offsets[L.chunk_index-1]+K,K+=L.size,t>V&&(N++,V<0&&(V=0),V+=m.sample_counts[N]),t>0?(e.samples[t-1].duration=m.sample_deltas[N],e.samples_duration+=e.samples[t-1].duration,L.dts=e.samples[t-1].dts+e.samples[t-1].duration):L.dts=0,y?(t>=q&&(ee++,q<0&&(q=0),q+=y.sample_counts[ee]),L.cts=e.samples[t].dts+y.sample_offsets[ee]):L.cts=L.dts,b?(t==b.sample_numbers[xe]-1?(L.is_sync=!0,xe++):(L.is_sync=!1,L.degradation_priority=0),w&&w.entries[j].sample_delta+W==t+1&&(L.subsamples=w.entries[j].subsamples,W+=w.entries[j].sample_delta,j++)):L.is_sync=!0,S.process_sdtp(e.mdia.minf.stbl.sdtp,L,L.number),F?L.degradation_priority=F.priority[t]:L.degradation_priority=0,w&&w.entries[j].sample_delta+W==t&&(L.subsamples=w.entries[j].subsamples,W+=w.entries[j].sample_delta),(T.length>0||C.length>0)&&S.setSampleGroupProperties(e,L,t,e.sample_groups_info)}t>0&&(e.samples[t-1].duration=Math.max(e.mdia.mdhd.duration-e.samples[t-1].dts,0),e.samples_duration+=e.samples[t-1].duration)}},S.prototype.updateSampleLists=function(){var e,t,r,l,h,m,y,b,x,w,T,C,F,A,R;if(this.moov!==void 0){for(;this.lastMoofIndex<this.moofs.length;)if(x=this.moofs[this.lastMoofIndex],this.lastMoofIndex++,x.type=="moof")for(w=x,e=0;e<w.trafs.length;e++){for(T=w.trafs[e],C=this.getTrackById(T.tfhd.track_id),F=this.getTrexById(T.tfhd.track_id),T.tfhd.flags&s.TFHD_FLAG_SAMPLE_DESC?l=T.tfhd.default_sample_description_index:l=F?F.default_sample_description_index:1,T.tfhd.flags&s.TFHD_FLAG_SAMPLE_DUR?h=T.tfhd.default_sample_duration:h=F?F.default_sample_duration:0,T.tfhd.flags&s.TFHD_FLAG_SAMPLE_SIZE?m=T.tfhd.default_sample_size:m=F?F.default_sample_size:0,T.tfhd.flags&s.TFHD_FLAG_SAMPLE_FLAGS?y=T.tfhd.default_sample_flags:y=F?F.default_sample_flags:0,T.sample_number=0,T.sbgps.length>0&&S.initSampleGroups(C,T,T.sbgps,C.mdia.minf.stbl.sgpds,T.sgpds),t=0;t<T.truns.length;t++){var P=T.truns[t];for(r=0;r<P.sample_count;r++){A={},A.moof_number=this.lastMoofIndex,A.number_in_traf=T.sample_number,T.sample_number++,A.number=C.samples.length,T.first_sample_index=C.samples.length,C.samples.push(A),A.track_id=C.tkhd.track_id,A.timescale=C.mdia.mdhd.timescale,A.description_index=l-1,A.description=C.mdia.minf.stbl.stsd.entries[A.description_index],A.size=m,P.flags&s.TRUN_FLAGS_SIZE&&(A.size=P.sample_size[r]),C.samples_size+=A.size,A.duration=h,P.flags&s.TRUN_FLAGS_DURATION&&(A.duration=P.sample_duration[r]),C.samples_duration+=A.duration,C.first_traf_merged||r>0?A.dts=C.samples[C.samples.length-2].dts+C.samples[C.samples.length-2].duration:(T.tfdt?A.dts=T.tfdt.baseMediaDecodeTime:A.dts=0,C.first_traf_merged=!0),A.cts=A.dts,P.flags&s.TRUN_FLAGS_CTS_OFFSET&&(A.cts=A.dts+P.sample_composition_time_offset[r]),R=y,P.flags&s.TRUN_FLAGS_FLAGS?R=P.sample_flags[r]:r===0&&P.flags&s.TRUN_FLAGS_FIRST_FLAG&&(R=P.first_sample_flags),A.is_sync=!(R>>16&1),A.is_leading=R>>26&3,A.depends_on=R>>24&3,A.is_depended_on=R>>22&3,A.has_redundancy=R>>20&3,A.degradation_priority=R&65535;var K=!!(T.tfhd.flags&s.TFHD_FLAG_BASE_DATA_OFFSET),Z=!!(T.tfhd.flags&s.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),V=!!(P.flags&s.TRUN_FLAGS_DATA_OFFSET),N=0;K?N=T.tfhd.base_data_offset:Z||t===0?N=w.start:N=b,t===0&&r===0?V?A.offset=N+P.data_offset:A.offset=N:A.offset=b,b=A.offset+A.size,(T.sbgps.length>0||T.sgpds.length>0||C.mdia.minf.stbl.sbgps.length>0||C.mdia.minf.stbl.sgpds.length>0)&&S.setSampleGroupProperties(C,A,A.number_in_traf,T.sample_groups_info)}}if(T.subs){C.has_fragment_subsamples=!0;var q=T.first_sample_index;for(t=0;t<T.subs.entries.length;t++)q+=T.subs.entries[t].sample_delta,A=C.samples[q-1],A.subsamples=T.subs.entries[t].subsamples}}}},S.prototype.getSample=function(e,t){var r,l=e.samples[t];if(!this.moov)return null;if(!l.data)l.data=new Uint8Array(l.size),l.alreadyRead=0,this.samplesDataSize+=l.size,n.debug("ISOFile","Allocating sample #"+t+" on track #"+e.tkhd.track_id+" of size "+l.size+" (total: "+this.samplesDataSize+")");else if(l.alreadyRead==l.size)return l;for(;;){var h=this.stream.findPosition(!0,l.offset+l.alreadyRead,!1);if(h>-1){r=this.stream.buffers[h];var m=r.byteLength-(l.offset+l.alreadyRead-r.fileStart);if(l.size-l.alreadyRead<=m)return n.debug("ISOFile","Getting sample #"+t+" data (alreadyRead: "+l.alreadyRead+" offset: "+(l.offset+l.alreadyRead-r.fileStart)+" read size: "+(l.size-l.alreadyRead)+" full size: "+l.size+")"),d.memcpy(l.data.buffer,l.alreadyRead,r,l.offset+l.alreadyRead-r.fileStart,l.size-l.alreadyRead),r.usedBytes+=l.size-l.alreadyRead,this.stream.logBufferLevel(),l.alreadyRead=l.size,l;if(m===0)return null;n.debug("ISOFile","Getting sample #"+t+" partial data (alreadyRead: "+l.alreadyRead+" offset: "+(l.offset+l.alreadyRead-r.fileStart)+" read size: "+m+" full size: "+l.size+")"),d.memcpy(l.data.buffer,l.alreadyRead,r,l.offset+l.alreadyRead-r.fileStart,m),l.alreadyRead+=m,r.usedBytes+=m,this.stream.logBufferLevel()}else return null}},S.prototype.releaseSample=function(e,t){var r=e.samples[t];return r.data?(this.samplesDataSize-=r.size,r.data=null,r.alreadyRead=0,r.size):0},S.prototype.getAllocatedSampleDataSize=function(){return this.samplesDataSize},S.prototype.getCodecs=function(){var e,t="";for(e=0;e<this.moov.traks.length;e++){var r=this.moov.traks[e];e>0&&(t+=","),t+=r.mdia.minf.stbl.stsd.entries[0].getCodec()}return t},S.prototype.getTrexById=function(e){var t;if(!this.moov||!this.moov.mvex)return null;for(t=0;t<this.moov.mvex.trexs.length;t++){var r=this.moov.mvex.trexs[t];if(r.track_id==e)return r}return null},S.prototype.getTrackById=function(e){if(this.moov===void 0)return null;for(var t=0;t<this.moov.traks.length;t++){var r=this.moov.traks[t];if(r.tkhd.track_id==e)return r}return null},S.prototype.itemsDataSize=0,S.prototype.flattenItemInfo=function(){var e=this.items,t=this.entity_groups,r,l,h,m=this.meta;if(m!=null&&m.hdlr!==void 0&&m.iinf!==void 0){for(r=0;r<m.iinf.item_infos.length;r++)h={},h.id=m.iinf.item_infos[r].item_ID,e[h.id]=h,h.ref_to=[],h.name=m.iinf.item_infos[r].item_name,m.iinf.item_infos[r].protection_index>0&&(h.protection=m.ipro.protections[m.iinf.item_infos[r].protection_index-1]),m.iinf.item_infos[r].item_type?h.type=m.iinf.item_infos[r].item_type:h.type="mime",h.content_type=m.iinf.item_infos[r].content_type,h.content_encoding=m.iinf.item_infos[r].content_encoding;if(m.grpl)for(r=0;r<m.grpl.boxes.length;r++)entity_group={},entity_group.id=m.grpl.boxes[r].group_id,entity_group.entity_ids=m.grpl.boxes[r].entity_ids,entity_group.type=m.grpl.boxes[r].type,t[entity_group.id]=entity_group;if(m.iloc)for(r=0;r<m.iloc.items.length;r++){var y=m.iloc.items[r];switch(h=e[y.item_ID],y.data_reference_index!==0&&(n.warn("Item storage with reference to other files: not supported"),h.source=m.dinf.boxes[y.data_reference_index-1]),y.construction_method){case 0:break;case 1:break;case 2:n.warn("Item storage with construction_method : not supported");break}for(h.extents=[],h.size=0,l=0;l<y.extents.length;l++)h.extents[l]={},h.extents[l].offset=y.extents[l].extent_offset+y.base_offset,y.construction_method==1&&(h.extents[l].offset+=m.idat.start+m.idat.hdr_size),h.extents[l].length=y.extents[l].extent_length,h.extents[l].alreadyRead=0,h.size+=h.extents[l].length}if(m.pitm&&(e[m.pitm.item_id].primary=!0),m.iref)for(r=0;r<m.iref.references.length;r++){var b=m.iref.references[r];for(l=0;l<b.references.length;l++)e[b.from_item_ID].ref_to.push({type:b.type,id:b.references[l]})}if(m.iprp)for(var x=0;x<m.iprp.ipmas.length;x++){var w=m.iprp.ipmas[x];for(r=0;r<w.associations.length;r++){var T=w.associations[r];if(h=e[T.id],h||(h=t[T.id]),h)for(h.properties===void 0&&(h.properties={},h.properties.boxes=[]),l=0;l<T.props.length;l++){var C=T.props[l];if(C.property_index>0&&C.property_index-1<m.iprp.ipco.boxes.length){var F=m.iprp.ipco.boxes[C.property_index-1];h.properties[F.type]=F,h.properties.boxes.push(F)}}}}}},S.prototype.getItem=function(e){var t,r;if(!this.meta)return null;if(r=this.items[e],!r.data&&r.size)r.data=new Uint8Array(r.size),r.alreadyRead=0,this.itemsDataSize+=r.size,n.debug("ISOFile","Allocating item #"+e+" of size "+r.size+" (total: "+this.itemsDataSize+")");else if(r.alreadyRead===r.size)return r;for(var l=0;l<r.extents.length;l++){var h=r.extents[l];if(h.alreadyRead!==h.length){var m=this.stream.findPosition(!0,h.offset+h.alreadyRead,!1);if(m>-1){t=this.stream.buffers[m];var y=t.byteLength-(h.offset+h.alreadyRead-t.fileStart);if(h.length-h.alreadyRead<=y)n.debug("ISOFile","Getting item #"+e+" extent #"+l+" data (alreadyRead: "+h.alreadyRead+" offset: "+(h.offset+h.alreadyRead-t.fileStart)+" read size: "+(h.length-h.alreadyRead)+" full extent size: "+h.length+" full item size: "+r.size+")"),d.memcpy(r.data.buffer,r.alreadyRead,t,h.offset+h.alreadyRead-t.fileStart,h.length-h.alreadyRead),t.usedBytes+=h.length-h.alreadyRead,this.stream.logBufferLevel(),r.alreadyRead+=h.length-h.alreadyRead,h.alreadyRead=h.length;else return n.debug("ISOFile","Getting item #"+e+" extent #"+l+" partial data (alreadyRead: "+h.alreadyRead+" offset: "+(h.offset+h.alreadyRead-t.fileStart)+" read size: "+y+" full extent size: "+h.length+" full item size: "+r.size+")"),d.memcpy(r.data.buffer,r.alreadyRead,t,h.offset+h.alreadyRead-t.fileStart,y),h.alreadyRead+=y,r.alreadyRead+=y,t.usedBytes+=y,this.stream.logBufferLevel(),null}else return null}}return r.alreadyRead===r.size?r:null},S.prototype.releaseItem=function(e){var t=this.items[e];if(t.data){this.itemsDataSize-=t.size,t.data=null,t.alreadyRead=0;for(var r=0;r<t.extents.length;r++){var l=t.extents[r];l.alreadyRead=0}return t.size}else return 0},S.prototype.processItems=function(e){for(var t in this.items){var r=this.items[t];this.getItem(r.id),e&&!r.sent&&(e(r),r.sent=!0,r.data=null)}},S.prototype.hasItem=function(e){for(var t in this.items){var r=this.items[t];if(r.name===e)return r.id}return-1},S.prototype.getMetaHandler=function(){return this.meta?this.meta.hdlr.handler:null},S.prototype.getPrimaryItem=function(){return!this.meta||!this.meta.pitm?null:this.getItem(this.meta.pitm.item_id)},S.prototype.itemToFragmentedTrackFile=function(e){var t=e||{},r=null;if(t.itemId?r=this.getItem(t.itemId):r=this.getPrimaryItem(),r==null)return null;var l=new S;l.discardMdatData=!1;var h={type:r.type,description_boxes:r.properties.boxes};r.properties.ispe&&(h.width=r.properties.ispe.image_width,h.height=r.properties.ispe.image_height);var m=l.addTrack(h);return m?(l.addSample(m,r.data),l):null},S.prototype.write=function(e){for(var t=0;t<this.boxes.length;t++)this.boxes[t].write(e)},S.prototype.createFragment=function(e,t,r){var l=this.getTrackById(e),h=this.getSample(l,t);if(h==null)return this.setNextSeekPositionFromSample(l.samples[t]),null;var m=r||new d;m.endianness=d.BIG_ENDIAN;var y=this.createSingleSampleMoof(h);y.write(m),y.trafs[0].truns[0].data_offset=y.size+8,n.debug("MP4Box","Adjusting data_offset with new value "+y.trafs[0].truns[0].data_offset),m.adjustUint32(y.trafs[0].truns[0].data_offset_position,y.trafs[0].truns[0].data_offset);var b=new s.mdatBox;return b.data=h.data,b.write(m),m},S.writeInitializationSegment=function(e,t,r,l){var h;n.debug("ISOFile","Generating initialization segment");var m=new d;m.endianness=d.BIG_ENDIAN,e.write(m);var y=t.add("mvex");for(r&&y.add("mehd").set("fragment_duration",r),h=0;h<t.traks.length;h++)y.add("trex").set("track_id",t.traks[h].tkhd.track_id).set("default_sample_description_index",1).set("default_sample_duration",l).set("default_sample_size",0).set("default_sample_flags",65536);return t.write(m),m.buffer},S.prototype.save=function(e){var t=new d;t.endianness=d.BIG_ENDIAN,this.write(t),t.save(e)},S.prototype.getBuffer=function(){var e=new d;return e.endianness=d.BIG_ENDIAN,this.write(e),e.buffer},S.prototype.initializeSegmentation=function(){var e,t,r,l;for(this.onSegment===null&&n.warn("MP4Box","No segmentation callback set!"),this.isFragmentationInitialized||(this.isFragmentationInitialized=!0,this.nextMoofNumber=0,this.resetTables()),t=[],e=0;e<this.fragmentedTracks.length;e++){var h=new s.moovBox;h.mvhd=this.moov.mvhd,h.boxes.push(h.mvhd),r=this.getTrackById(this.fragmentedTracks[e].id),h.boxes.push(r),h.traks.push(r),l={},l.id=r.tkhd.track_id,l.user=this.fragmentedTracks[e].user,l.buffer=S.writeInitializationSegment(this.ftyp,h,this.moov.mvex&&this.moov.mvex.mehd?this.moov.mvex.mehd.fragment_duration:void 0,this.moov.traks[e].samples.length>0?this.moov.traks[e].samples[0].duration:0),t.push(l)}return t},s.Box.prototype.printHeader=function(e){this.size+=8,this.size>f&&(this.size+=8),this.type==="uuid"&&(this.size+=16),e.log(e.indent+"size:"+this.size),e.log(e.indent+"type:"+this.type)},s.FullBox.prototype.printHeader=function(e){this.size+=4,s.Box.prototype.printHeader.call(this,e),e.log(e.indent+"version:"+this.version),e.log(e.indent+"flags:"+this.flags)},s.Box.prototype.print=function(e){this.printHeader(e)},s.ContainerBox.prototype.print=function(e){this.printHeader(e);for(var t=0;t<this.boxes.length;t++)if(this.boxes[t]){var r=e.indent;e.indent+=" ",this.boxes[t].print(e),e.indent=r}},S.prototype.print=function(e){e.indent="";for(var t=0;t<this.boxes.length;t++)this.boxes[t]&&this.boxes[t].print(e)},s.mvhdBox.prototype.print=function(e){s.FullBox.prototype.printHeader.call(this,e),e.log(e.indent+"creation_time: "+this.creation_time),e.log(e.indent+"modification_time: "+this.modification_time),e.log(e.indent+"timescale: "+this.timescale),e.log(e.indent+"duration: "+this.duration),e.log(e.indent+"rate: "+this.rate),e.log(e.indent+"volume: "+(this.volume>>8)),e.log(e.indent+"matrix: "+this.matrix.join(", ")),e.log(e.indent+"next_track_id: "+this.next_track_id)},s.tkhdBox.prototype.print=function(e){s.FullBox.prototype.printHeader.call(this,e),e.log(e.indent+"creation_time: "+this.creation_time),e.log(e.indent+"modification_time: "+this.modification_time),e.log(e.indent+"track_id: "+this.track_id),e.log(e.indent+"duration: "+this.duration),e.log(e.indent+"volume: "+(this.volume>>8)),e.log(e.indent+"matrix: "+this.matrix.join(", ")),e.log(e.indent+"layer: "+this.layer),e.log(e.indent+"alternate_group: "+this.alternate_group),e.log(e.indent+"width: "+this.width),e.log(e.indent+"height: "+this.height)};var E={};E.createFile=function(e,t){var r=e!==void 0?e:!0,l=new S(t);return l.discardMdatData=!r,l},a.createFile=E.createFile}(mt)),mt}var yt=fn(),cn=Zt(yt),vt={exports:{}},ei;function hn(){return ei||(ei=1,function(a){var n={};a.exports=n,n.parse=function(o,d){for(var f=n.bin.readUshort,c=n.bin.readUint,_=0,u={},s=new Uint8Array(o),p=s.length-4;c(s,p)!=101010256;)p--;var _=p;_+=4,_+=4;var g=f(s,_);_+=2,f(s,_),_+=2;var v=c(s,_);_+=4;var U=c(s,_);_+=4,_=U;for(var S=0;S<g;S++){c(s,_),_+=4,_+=4,_+=4,_+=4,c(s,_),_+=4;var v=c(s,_);_+=4;var E=c(s,_);_+=4;var e=f(s,_),t=f(s,_+2),r=f(s,_+4);_+=6,_+=8;var l=c(s,_);_+=4,_+=e+t+r,n._readLocal(s,l,u,v,E,d)}return u},n._readLocal=function(o,d,f,c,u,s){var p=n.bin.readUshort,_=n.bin.readUint;_(o,d),d+=4,p(o,d),d+=2,p(o,d),d+=2;var g=p(o,d);d+=2,_(o,d),d+=4,_(o,d),d+=4,d+=8;var v=p(o,d);d+=2;var U=p(o,d);d+=2;var S=n.bin.readUTF8(o,d,v);if(d+=v,d+=U,s){f[S]={size:u,csize:c};return}var E=new Uint8Array(o.buffer,d);if(g==0)f[S]=new Uint8Array(E.buffer.slice(d,d+c));else if(g==8){var e=new Uint8Array(u);n.inflateRaw(E,e),f[S]=e}else throw"unknown compression method: "+g},n.inflateRaw=function(o,d){return n.F.inflate(o,d)},n.inflate=function(o,d){return o[0],o[1],n.inflateRaw(new Uint8Array(o.buffer,o.byteOffset+2,o.length-6),d)},n.deflate=function(o,d){d==null&&(d={level:6});var f=0,c=new Uint8Array(50+Math.floor(o.length*1.1));c[f]=120,c[f+1]=156,f+=2,f=n.F.deflateRaw(o,c,f,d.level);var u=n.adler(o,0,o.length);return c[f+0]=u>>>24&255,c[f+1]=u>>>16&255,c[f+2]=u>>>8&255,c[f+3]=u>>>0&255,new Uint8Array(c.buffer,0,f+4)},n.deflateRaw=function(o,d){d==null&&(d={level:6});var f=new Uint8Array(50+Math.floor(o.length*1.1)),c=n.F.deflateRaw(o,f,c,d.level);return new Uint8Array(f.buffer,0,c)},n.encode=function(o,d){d==null&&(d=!1);var f=0,c=n.bin.writeUint,u=n.bin.writeUshort,s={};for(var p in o){var _=!n._noNeed(p)&&!d,g=o[p],v=n.crc.crc(g,0,g.length);s[p]={cpr:_,usize:g.length,crc:v,file:_?n.deflateRaw(g):g}}for(var p in s)f+=s[p].file.length+30+46+2*n.bin.sizeUTF8(p);f+=22;var U=new Uint8Array(f),S=0,E=[];for(var p in s){var e=s[p];E.push(S),S=n._writeHeader(U,S,p,e,0)}var t=0,r=S;for(var p in s){var e=s[p];E.push(S),S=n._writeHeader(U,S,p,e,1,E[t++])}var l=S-r;return c(U,S,101010256),S+=4,S+=4,u(U,S,t),S+=2,u(U,S,t),S+=2,c(U,S,l),S+=4,c(U,S,r),S+=4,S+=2,U.buffer},n._noNeed=function(o){var d=o.split(".").pop().toLowerCase();return"png,jpg,jpeg,zip".indexOf(d)!=-1},n._writeHeader=function(o,d,f,c,u,s){var p=n.bin.writeUint,_=n.bin.writeUshort,g=c.file;p(o,d,u==0?67324752:33639248),d+=4,u==1&&(d+=2),_(o,d,20),d+=2,_(o,d,0),d+=2,_(o,d,c.cpr?8:0),d+=2,p(o,d,0),d+=4,p(o,d,c.crc),d+=4,p(o,d,g.length),d+=4,p(o,d,c.usize),d+=4,_(o,d,n.bin.sizeUTF8(f)),d+=2,_(o,d,0),d+=2,u==1&&(d+=2,d+=2,d+=6,p(o,d,s),d+=4);var v=n.bin.writeUTF8(o,d,f);return d+=v,u==0&&(o.set(g,d),d+=g.length),d},n.crc={table:function(){for(var o=new Uint32Array(256),d=0;d<256;d++){for(var f=d,c=0;c<8;c++)f&1?f=3988292384^f>>>1:f=f>>>1;o[d]=f}return o}(),update:function(o,d,f,c){for(var u=0;u<c;u++)o=n.crc.table[(o^d[f+u])&255]^o>>>8;return o},crc:function(o,d,f){return n.crc.update(4294967295,o,d,f)^4294967295}},n.adler=function(o,d,f){for(var c=1,u=0,s=d,p=d+f;s<p;){for(var _=Math.min(s+5552,p);s<_;)c+=o[s++],u+=c;c=c%65521,u=u%65521}return u<<16|c},n.bin={readUshort:function(o,d){return o[d]|o[d+1]<<8},writeUshort:function(o,d,f){o[d]=f&255,o[d+1]=f>>8&255},readUint:function(o,d){return o[d+3]*(256*256*256)+(o[d+2]<<16|o[d+1]<<8|o[d])},writeUint:function(o,d,f){o[d]=f&255,o[d+1]=f>>8&255,o[d+2]=f>>16&255,o[d+3]=f>>24&255},readASCII:function(o,d,f){for(var c="",u=0;u<f;u++)c+=String.fromCharCode(o[d+u]);return c},writeASCII:function(o,d,f){for(var c=0;c<f.length;c++)o[d+c]=f.charCodeAt(c)},pad:function(o){return o.length<2?"0"+o:o},readUTF8:function(o,d,f){for(var c="",u,s=0;s<f;s++)c+="%"+n.bin.pad(o[d+s].toString(16));try{u=decodeURIComponent(c)}catch{return n.bin.readASCII(o,d,f)}return u},writeUTF8:function(o,d,f){for(var c=f.length,u=0,s=0;s<c;s++){var p=f.charCodeAt(s);if(!(p&4294967168))o[d+u]=p,u++;else if(!(p&4294965248))o[d+u]=192|p>>6,o[d+u+1]=128|p>>0&63,u+=2;else if(!(p&4294901760))o[d+u]=224|p>>12,o[d+u+1]=128|p>>6&63,o[d+u+2]=128|p>>0&63,u+=3;else if(!(p&4294967295-(1<<21)+1))o[d+u]=240|p>>18,o[d+u+1]=128|p>>12&63,o[d+u+2]=128|p>>6&63,o[d+u+3]=128|p>>0&63,u+=4;else throw"e"}return u},sizeUTF8:function(o){for(var d=o.length,f=0,c=0;c<d;c++){var u=o.charCodeAt(c);if(!(u&4294967168))f++;else if(!(u&4294965248))f+=2;else if(!(u&4294901760))f+=3;else if(!(u&4294967295-(1<<21)+1))f+=4;else throw"e"}return f}},n.F={},n.F.deflateRaw=function(o,d,f,c){var u=[[0,0,0,0,0],[4,4,8,4,0],[4,5,16,8,0],[4,6,16,16,0],[4,10,16,32,0],[8,16,32,32,0],[8,16,128,128,0],[8,32,128,256,0],[32,128,258,1024,1],[32,258,258,4096,1]],s=u[c],p=n.F.U,_=n.F._goodIndex;n.F._hash;var g=n.F._putsE,v=0,U=f<<3,S=0,E=o.length;if(c==0){for(;v<E;){var e=Math.min(65535,E-v);g(d,U,v+e==E?1:0),U=n.F._copyExact(o,v,e,d,U+8),v+=e}return U>>>3}var t=p.lits,r=p.strt,l=p.prev,h=0,m=0,y=0,b=0,x=0,w=0;for(E>2&&(w=n.F._hash(o,0),r[w]=0),v=0;v<E;v++){if(x=w,v+1<E-2){w=n.F._hash(o,v+1);var T=v+1&32767;l[T]=r[w],r[w]=T}if(S<=v){(h>14e3||m>26697)&&E-v>100&&(S<v&&(t[h]=v-S,h+=2,S=v),U=n.F._writeBlock(v==E-1||S==E?1:0,t,h,b,o,y,v-y,d,U),h=m=b=0,y=v);var C=0;v<E-2&&(C=n.F._bestMatch(o,v,l,x,Math.min(s[2],E-v),s[3]));var e=C>>>16,F=C&65535;if(C!=0){var e=C>>>16,F=C&65535,A=_(e,p.of0);p.lhst[257+A]++;var R=_(F,p.df0);p.dhst[R]++,b+=p.exb[A]+p.dxb[R],t[h]=e<<23|v-S,t[h+1]=F<<16|A<<8|R,h+=2,S=v+e}else p.lhst[o[v]]++;m++}}for((y!=v||o.length==0)&&(S<v&&(t[h]=v-S,h+=2,S=v),U=n.F._writeBlock(1,t,h,b,o,y,v-y,d,U),h=0,m=0,h=m=b=0,y=v);U&7;)U++;return U>>>3},n.F._bestMatch=function(o,d,f,c,u,s){var p=d&32767,_=f[p],g=p-_+32768&32767;if(_==p||c!=n.F._hash(o,d-g))return 0;for(var v=0,U=0,S=Math.min(32767,d);g<=S&&--s!=0&&_!=p;){if(v==0||o[d+v]==o[d+v-g]){var E=n.F._howLong(o,d,g);if(E>v){if(v=E,U=g,v>=u)break;g+2<E&&(E=g+2);for(var e=0,t=0;t<E-2;t++){var r=d-g+t+32768&32767,l=f[r],h=r-l+32768&32767;h>e&&(e=h,_=r)}}}p=_,_=f[p],g+=p-_+32768&32767}return v<<16|U},n.F._howLong=function(o,d,f){if(o[d]!=o[d-f]||o[d+1]!=o[d+1-f]||o[d+2]!=o[d+2-f])return 0;var c=d,u=Math.min(o.length,d+258);for(d+=3;d<u&&o[d]==o[d-f];)d++;return d-c},n.F._hash=function(o,d){return(o[d]<<8|o[d+1])+(o[d+2]<<4)&65535},n.saved=0,n.F._writeBlock=function(o,d,f,c,u,s,p,_,g){var v=n.F.U,U=n.F._putsF,S=n.F._putsE,E,e,t,r,l,h,m,y,b;v.lhst[256]++,E=n.F.getTrees(),e=E[0],t=E[1],r=E[2],l=E[3],h=E[4],m=E[5],y=E[6],b=E[7];var x=(g+3&7?8-(g+3&7):0)+32+(p<<3),w=c+n.F.contSize(v.fltree,v.lhst)+n.F.contSize(v.fdtree,v.dhst),T=c+n.F.contSize(v.ltree,v.lhst)+n.F.contSize(v.dtree,v.dhst);T+=14+3*m+n.F.contSize(v.itree,v.ihst)+(v.ihst[16]*2+v.ihst[17]*3+v.ihst[18]*7);for(var C=0;C<286;C++)v.lhst[C]=0;for(var C=0;C<30;C++)v.dhst[C]=0;for(var C=0;C<19;C++)v.ihst[C]=0;var F=x<w&&x<T?0:w<T?1:2;if(U(_,g,o),U(_,g+1,F),g+=3,F==0){for(;g&7;)g++;g=n.F._copyExact(u,s,p,_,g)}else{var A,R;if(F==1&&(A=v.fltree,R=v.fdtree),F==2){n.F.makeCodes(v.ltree,e),n.F.revCodes(v.ltree,e),n.F.makeCodes(v.dtree,t),n.F.revCodes(v.dtree,t),n.F.makeCodes(v.itree,r),n.F.revCodes(v.itree,r),A=v.ltree,R=v.dtree,S(_,g,l-257),g+=5,S(_,g,h-1),g+=5,S(_,g,m-4),g+=4;for(var P=0;P<m;P++)S(_,g+P*3,v.itree[(v.ordr[P]<<1)+1]);g+=3*m,g=n.F._codeTiny(y,v.itree,_,g),g=n.F._codeTiny(b,v.itree,_,g)}for(var K=s,Z=0;Z<f;Z+=2){for(var V=d[Z],N=V>>>23,q=K+(V&(1<<23)-1);K<q;)g=n.F._writeLit(u[K++],A,_,g);if(N!=0){var ee=d[Z+1],xe=ee>>16,j=ee>>8&255,W=ee&255;g=n.F._writeLit(257+j,A,_,g),S(_,g,N-v.of0[j]),g+=v.exb[j],g=n.F._writeLit(W,R,_,g),U(_,g,xe-v.df0[W]),g+=v.dxb[W],K+=N}}g=n.F._writeLit(256,A,_,g)}return g},n.F._copyExact=function(o,d,f,c,u){var s=u>>>3;return c[s]=f,c[s+1]=f>>>8,c[s+2]=255-c[s],c[s+3]=255-c[s+1],s+=4,c.set(new Uint8Array(o.buffer,d,f),s),u+(f+4<<3)},n.F.getTrees=function(){for(var o=n.F.U,d=n.F._hufTree(o.lhst,o.ltree,15),f=n.F._hufTree(o.dhst,o.dtree,15),c=[],u=n.F._lenCodes(o.ltree,c),s=[],p=n.F._lenCodes(o.dtree,s),_=0;_<c.length;_+=2)o.ihst[c[_]]++;for(var _=0;_<s.length;_+=2)o.ihst[s[_]]++;for(var g=n.F._hufTree(o.ihst,o.itree,7),v=19;v>4&&o.itree[(o.ordr[v-1]<<1)+1]==0;)v--;return[d,f,g,u,p,v,c,s]},n.F.getSecond=function(o){for(var d=[],f=0;f<o.length;f+=2)d.push(o[f+1]);return d},n.F.nonZero=function(o){for(var d="",f=0;f<o.length;f+=2)o[f+1]!=0&&(d+=(f>>1)+",");return d},n.F.contSize=function(o,d){for(var f=0,c=0;c<d.length;c++)f+=d[c]*o[(c<<1)+1];return f},n.F._codeTiny=function(o,d,f,c){for(var u=0;u<o.length;u+=2){var s=o[u],p=o[u+1];c=n.F._writeLit(s,d,f,c);var _=s==16?2:s==17?3:7;s>15&&(n.F._putsE(f,c,p,_),c+=_)}return c},n.F._lenCodes=function(o,d){for(var f=o.length;f!=2&&o[f-1]==0;)f-=2;for(var c=0;c<f;c+=2){var u=o[c+1],s=c+3<f?o[c+3]:-1,p=c+5<f?o[c+5]:-1,_=c==0?-1:o[c-1];if(u==0&&s==u&&p==u){for(var g=c+5;g+2<f&&o[g+2]==u;)g+=2;var v=Math.min(g+1-c>>>1,138);v<11?d.push(17,v-3):d.push(18,v-11),c+=v*2-2}else if(u==_&&s==u&&p==u){for(var g=c+5;g+2<f&&o[g+2]==u;)g+=2;var v=Math.min(g+1-c>>>1,6);d.push(16,v-3),c+=v*2-2}else d.push(u,0)}return f>>>1},n.F._hufTree=function(o,d,f){var c=[],u=o.length,s=d.length,p=0;for(p=0;p<s;p+=2)d[p]=0,d[p+1]=0;for(p=0;p<u;p++)o[p]!=0&&c.push({lit:p,f:o[p]});var _=c.length,g=c.slice(0);if(_==0)return 0;if(_==1){var v=c[0].lit,g=v==0?1:0;return d[(v<<1)+1]=1,d[(g<<1)+1]=1,1}c.sort(function(l,h){return l.f-h.f});var U=c[0],S=c[1],E=0,e=1,t=2;for(c[0]={lit:-1,f:U.f+S.f,l:U,r:S,d:0};e!=_-1;)E!=e&&(t==_||c[E].f<c[t].f)?U=c[E++]:U=c[t++],E!=e&&(t==_||c[E].f<c[t].f)?S=c[E++]:S=c[t++],c[e++]={lit:-1,f:U.f+S.f,l:U,r:S};var r=n.F.setDepth(c[e-1],0);for(r>f&&(n.F.restrictDepth(g,f,r),r=f),p=0;p<_;p++)d[(g[p].lit<<1)+1]=g[p].d;return r},n.F.setDepth=function(o,d){return o.lit!=-1?(o.d=d,d):Math.max(n.F.setDepth(o.l,d+1),n.F.setDepth(o.r,d+1))},n.F.restrictDepth=function(o,d,f){var c=0,u=1<<f-d,s=0;for(o.sort(function(_,g){return g.d==_.d?_.f-g.f:g.d-_.d}),c=0;c<o.length&&o[c].d>d;c++){var p=o[c].d;o[c].d=d,s+=u-(1<<f-p)}for(s=s>>>f-d;s>0;){var p=o[c].d;p<d?(o[c].d++,s-=1<<d-p-1):c++}for(;c>=0;c--)o[c].d==d&&s<0&&(o[c].d--,s++);s!=0&&console.log("debt left")},n.F._goodIndex=function(o,d){var f=0;return d[f|16]<=o&&(f|=16),d[f|8]<=o&&(f|=8),d[f|4]<=o&&(f|=4),d[f|2]<=o&&(f|=2),d[f|1]<=o&&(f|=1),f},n.F._writeLit=function(o,d,f,c){return n.F._putsF(f,c,d[o<<1]),c+d[(o<<1)+1]},n.F.inflate=function(o,d){var f=Uint8Array;if(o[0]==3&&o[1]==0)return d||new f(0);var c=n.F,u=c._bitsF,s=c._bitsE,p=c._decodeTiny,_=c.makeCodes,g=c.codes2map,v=c._get17,U=c.U,S=d==null;S&&(d=new f(o.length>>>2<<3));for(var E=0,e=0,t=0,r=0,l=0,h=0,m=0,y=0,b=0,x,w;E==0;){if(E=u(o,b,1),e=u(o,b+1,2),b+=3,e==0){b&7&&(b+=8-(b&7));var T=(b>>>3)+4,C=o[T-4]|o[T-3]<<8;S&&(d=n.F._check(d,y+C)),d.set(new f(o.buffer,o.byteOffset+T,C),y),b=T+C<<3,y+=C;continue}if(S&&(d=n.F._check(d,y+(1<<17))),e==1&&(x=U.flmap,w=U.fdmap,h=511,m=31),e==2){t=s(o,b,5)+257,r=s(o,b+5,5)+1,l=s(o,b+10,4)+4,b+=14;for(var F=0;F<38;F+=2)U.itree[F]=0,U.itree[F+1]=0;for(var A=1,F=0;F<l;F++){var R=s(o,b+F*3,3);U.itree[(U.ordr[F]<<1)+1]=R,R>A&&(A=R)}b+=3*l,_(U.itree,A),g(U.itree,A,U.imap),x=U.lmap,w=U.dmap,b=p(U.imap,(1<<A)-1,t+r,o,b,U.ttree);var P=c._copyOut(U.ttree,0,t,U.ltree);h=(1<<P)-1;var K=c._copyOut(U.ttree,t,r,U.dtree);m=(1<<K)-1,_(U.ltree,P),g(U.ltree,P,x),_(U.dtree,K),g(U.dtree,K,w)}for(;;){var Z=x[v(o,b)&h];b+=Z&15;var V=Z>>>4;if(!(V>>>8))d[y++]=V;else{if(V==256)break;var N=y+V-254;if(V>264){var q=U.ldef[V-257];N=y+(q>>>3)+s(o,b,q&7),b+=q&7}var ee=w[v(o,b)&m];b+=ee&15;var xe=ee>>>4,j=U.ddef[xe],W=(j>>>4)+u(o,b,j&15);for(b+=j&15,S&&(d=n.F._check(d,y+(1<<17)));y<N;)d[y]=d[y++-W],d[y]=d[y++-W],d[y]=d[y++-W],d[y]=d[y++-W];y=N}}}return d.length==y?d:d.slice(0,y)},n.F._check=function(o,d){var f=o.length;if(d<=f)return o;var c=new Uint8Array(Math.max(f<<1,d));return c.set(o,0),c},n.F._decodeTiny=function(o,d,f,c,u,s){for(var p=n.F._bitsE,_=n.F._get17,g=0;g<f;){var v=o[_(c,u)&d];u+=v&15;var U=v>>>4;if(U<=15)s[g]=U,g++;else{var S=0,E=0;U==16?(E=3+p(c,u,2),u+=2,S=s[g-1]):U==17?(E=3+p(c,u,3),u+=3):U==18&&(E=11+p(c,u,7),u+=7);for(var e=g+E;g<e;)s[g]=S,g++}}return u},n.F._copyOut=function(o,d,f,c){for(var u=0,s=0,p=c.length>>>1;s<f;){var _=o[s+d];c[s<<1]=0,c[(s<<1)+1]=_,_>u&&(u=_),s++}for(;s<p;)c[s<<1]=0,c[(s<<1)+1]=0,s++;return u},n.F.makeCodes=function(o,d){for(var f=n.F.U,c=o.length,u,s,p,_,g,v=f.bl_count,_=0;_<=d;_++)v[_]=0;for(_=1;_<c;_+=2)v[o[_]]++;var U=f.next_code;for(u=0,v[0]=0,s=1;s<=d;s++)u=u+v[s-1]<<1,U[s]=u;for(p=0;p<c;p+=2)g=o[p+1],g!=0&&(o[p]=U[g],U[g]++)},n.F.codes2map=function(o,d,f){for(var c=o.length,u=n.F.U,s=u.rev15,p=0;p<c;p+=2)if(o[p+1]!=0)for(var _=p>>1,g=o[p+1],v=_<<4|g,U=d-g,S=o[p]<<U,E=S+(1<<U);S!=E;){var e=s[S]>>>15-d;f[e]=v,S++}},n.F.revCodes=function(o,d){for(var f=n.F.U.rev15,c=15-d,u=0;u<o.length;u+=2){var s=o[u]<<d-o[u+1];o[u]=f[s]>>>c}},n.F._putsE=function(o,d,f){f=f<<(d&7);var c=d>>>3;o[c]|=f,o[c+1]|=f>>>8},n.F._putsF=function(o,d,f){f=f<<(d&7);var c=d>>>3;o[c]|=f,o[c+1]|=f>>>8,o[c+2]|=f>>>16},n.F._bitsE=function(o,d,f){return(o[d>>>3]|o[(d>>>3)+1]<<8)>>>(d&7)&(1<<f)-1},n.F._bitsF=function(o,d,f){return(o[d>>>3]|o[(d>>>3)+1]<<8|o[(d>>>3)+2]<<16)>>>(d&7)&(1<<f)-1},n.F._get17=function(o,d){return(o[d>>>3]|o[(d>>>3)+1]<<8|o[(d>>>3)+2]<<16)>>>(d&7)},n.F._get25=function(o,d){return(o[d>>>3]|o[(d>>>3)+1]<<8|o[(d>>>3)+2]<<16|o[(d>>>3)+3]<<24)>>>(d&7)},n.F.U=function(){var o=Uint16Array,d=Uint32Array;return{next_code:new o(16),bl_count:new o(16),ordr:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],of0:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],exb:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],ldef:new o(32),df0:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],dxb:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],ddef:new d(32),flmap:new o(512),fltree:[],fdmap:new o(32),fdtree:[],lmap:new o(32768),ltree:[],ttree:[],dmap:new o(32768),dtree:[],imap:new o(512),itree:[],rev15:new o(32768),lhst:new d(286),dhst:new d(30),ihst:new d(19),lits:new d(15e3),strt:new o(65536),prev:new o(32768)}}(),function(){for(var o=n.F.U,d=32768,f=0;f<d;f++){var c=f;c=(c&2863311530)>>>1|(c&1431655765)<<1,c=(c&3435973836)>>>2|(c&858993459)<<2,c=(c&4042322160)>>>4|(c&252645135)<<4,c=(c&4278255360)>>>8|(c&16711935)<<8,o.rev15[f]=(c>>>16|c<<16)>>>17}function u(s,p,_){for(;p--!=0;)s.push(0,_)}for(var f=0;f<32;f++)o.ldef[f]=o.of0[f]<<3|o.exb[f],o.ddef[f]=o.df0[f]<<4|o.dxb[f];u(o.fltree,144,8),u(o.fltree,112,9),u(o.fltree,24,7),u(o.fltree,8,8),n.F.makeCodes(o.fltree,9),n.F.codes2map(o.fltree,9,o.flmap),n.F.revCodes(o.fltree,9),u(o.fdtree,32,5),n.F.makeCodes(o.fdtree,5),n.F.codes2map(o.fdtree,5,o.fdmap),n.F.revCodes(o.fdtree,5),u(o.itree,19,0),u(o.ltree,286,0),u(o.dtree,30,0),u(o.ttree,320,0)}()}(vt)),vt.exports}var un=hn(),pn=Zt(un);const Y=class Y{constructor(n,o,d,f,c){this.copy=()=>new Y(this.h,this.m,this.s,this.f,this.field),this.print=()=>{const u=":";let s=("0"+this.h).slice(-2)+u+("0"+this.m).slice(-2)+u+("0"+this.s).slice(-2)+u+("0"+this.f).slice(-2);return s+="."+(this.field?"1":"2"),s},this.toZipTimeCodeString=()=>{const u=this.copy();return u.f=0,u.s=u.s%2===0?u.s:u.s-1,u.field=0,Y.toStr(u)},this.toFrames=u=>{let s=60,p=0;Math.floor(u)==60?(s=60,p=0):Math.floor(u)==59?(s=60,p=4):Math.floor(u)==30?(s=30,p=0):Math.floor(u)==29&&(s=30,p=2);let _=this.h,g=this.m,v=this.s,U=this.f,S=this.field;const E=_*60+g,t=(E-Math.floor(E/10))*p;return _*(s*3600)+g*(s*60)+v*s+(U*2+S)-t},this.addSeconds=u=>{let s=this.copy();if(s.s+=u,s.s>=60){const p=Math.floor(s.s/60);if(s.s=s.s%60,s.m+=p,s.m>=60){const _=Math.floor(s.m/60);s.m=s.m%60,s.h+=_}}return s},this.addFrames=(u,s)=>{let p=this.toFrames(s);return p+=u,Y.fromFrames(p,s)},this.subtractFrames=(u,s)=>this.addFrames(-u,s),this.h=n||0,this.m=o||0,this.s=d||0,this.f=f||0,this.field=c||0}static compare(n,o){return n.h!==o.h?n.h<o.h?-1:1:n.m!==o.m?n.m<o.m?-1:1:n.s!==o.s?n.s<o.s?-1:1:n.f!==o.f?n.f<o.f?-1:1:n.field!==o.field?n.field<o.field?-1:1:0}static generateTimecodeRange(n,o,d){const f=[];let c=n;for(;Y.compare(c,o)<=0;)f.push(c),c=c.addSeconds(d);return f}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(n){return this.toFrames(n)*1e3/n}};Y.calculateCurrentTimeCode=n=>{var v;if(!n.video||!n.clocker||!n.gameParams)throw new Error("OTTPlayer is not initialized");const o=n.video,d=n.clocker,f=d.videoFPScalculator.getFPS(),s=(o.currentTime-d.syncPoint.playerTime)%(60*60*24)*f+d.syncPoint.frame;if(s===0||f===0)throw new Error("Current frame is 0 or fps is 0");const p=Y.calculateCurrentOffset(s,(v=n.gameParams)==null?void 0:v.offsets);if(p===void 0)throw new Error("Offset is undefined");let _=Math.floor(s-p);return _<0&&(_+=5178816),_>=5178816&&(_-=5178816),Y.fromFrames(_,f)},Y.calculateCurrentOffset=(n,o)=>{for(let d=1;d<o.length;d++)if(n<o[d].frame)return o[d-1].offset;return Math.abs(o[o.length-1].offset)},Y.fromFrames=(n,o)=>{let d=60,f=0;Math.floor(o)==60?(d=60,f=0):Math.floor(o)==59?(d=60,f=4):Math.floor(o)==30?(d=30,f=0):Math.floor(o)==29&&(d=30,f=2);let c=Math.floor(o*60),u=Math.floor(o*60*10),s=u*6,p=n,_=Math.floor(p/s);p-=_*s;let g=Math.floor(p/u);p-=g*u,p>=d*60&&(p+=f*(Math.floor((p-d*60)/c)+1));let v=Math.floor(p/(d*60));p-=v*(d*60);let U=Math.floor(p/d);p-=U*d;let S=p;v+=g*10;let E=0;return E=S%2,S=Math.floor(S/2),new Y(_,v,U,S,E)},Y.toStr=n=>{const o="_";let d=("0"+n.h).slice(-2)+o+("0"+n.m).slice(-2)+o+("0"+n.s).slice(-2)+o+("0"+n.f).slice(-2);return n.field&&(d+="_1"),d},Y.fromStr=n=>{const d=n.split("_").map(Number);if(d.length==4){const[f,c,u,s]=d;return new Y(f,c,u,s,0)}else if(d.length==5){const[f,c,u,s,p]=d;return new Y(f,c,u,s,p)}else throw new Error("Invalid timecode format: "+n)},Y.fromMetadata=n=>{const o=/^(\\d{2}):(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d))?$/,d=n.timecode.match(o);if(!d)throw new Error("Invalid timecode format: "+n.timecode);const[,f,c,u,s,p]=d,_=Number(f),g=Number(c),v=Number(u),U=Number(s),S=p?Number(p):0;return new Y(_,g,v,U,S)};let $=Y;const O={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},te=console,he={};Object.keys(O).forEach(a=>{he[a]=te[a]});const Be="Datadog Browser SDK:",M={debug:he.debug.bind(te,Be),log:he.log.bind(te,Be),info:he.info.bind(te,Be),warn:he.warn.bind(te,Be),error:he.error.bind(te,Be)},St="https://docs.datadoghq.com",ti=`${St}/real_user_monitoring/browser/troubleshooting`,Ve="More details:";function ii(a,n){return(...o)=>{try{return a(...o)}catch(d){M.error(n,d)}}}function $e(a){return a!==0&&Math.random()*100<=a}function _n(a){return gn(a)&&a>=0&&a<=100}function gn(a){return typeof a=="number"}const ke=1e3,ue=60*ke,ni=60*ue,mn=365*(24*ni);function Le(){return new Date().getTime()}function oe(){return Le()}function je(){return performance.now()}function ae(){return{relative:je(),timeStamp:oe()}}function yn(){return{relative:0,timeStamp:ri()}}function vn(a,n){return n-a}function Sn(a,n){return a+n}function bn(a){return a-ri()}let bt;function ri(){return bt===void 0&&(bt=performance.timing.navigationStart),bt}const ie=1024,si=1024*ie,xn=/[^\\u0000-\\u007F]/;function xt(a){return xn.test(a)?window.TextEncoder!==void 0?new TextEncoder().encode(a).length:new Blob([a]).size:a.length}function Un(a){return{...a}}function oi(a,n){return Object.keys(a).some(o=>a[o]===n)}function De(a){return Object.keys(a).length===0}function de(){if(typeof globalThis=="object")return globalThis;Object.defineProperty(Object.prototype,"_dd_temp_",{get(){return this},configurable:!0});let a=_dd_temp_;return delete Object.prototype._dd_temp_,typeof a!="object"&&(typeof self=="object"?a=self:typeof window=="object"?a=window:a={}),a}function Ue(a,n){const o=de();let d;return o.Zone&&typeof o.Zone.__symbol__=="function"&&(d=a[o.Zone.__symbol__(n)]),d||(d=a[n]),d}let Ke,ai=!1;function En(a){Ke=a}function wn(a){ai=a}function Tn(a,n,o){const d=o.value;o.value=function(...f){return(Ke?D(d):d).apply(this,f)}}function D(a){return function(){return Re(a,this,arguments)}}function Re(a,n,o){try{return a.apply(n,o)}catch(d){Cn(d)}}function Cn(a){if(Ut(a),Ke)try{Ke(a)}catch(n){Ut(n)}}function Ut(...a){ai&&M.error("[MONITOR]",...a)}function Pe(a,n){return Ue(de(),"setTimeout")(D(a),n)}function di(a){Ue(de(),"clearTimeout")(a)}function Et(a,n){return Ue(de(),"setInterval")(D(a),n)}function li(a){Ue(de(),"clearInterval")(a)}class G{constructor(n){this.onFirstSubscribe=n,this.observers=[]}subscribe(n){return this.observers.push(n),this.observers.length===1&&this.onFirstSubscribe&&(this.onLastUnsubscribe=this.onFirstSubscribe(this)||void 0),{unsubscribe:()=>{this.observers=this.observers.filter(o=>n!==o),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}}notify(n){this.observers.forEach(o=>o(n))}}function fi(...a){return new G(n=>{const o=a.map(d=>d.subscribe(f=>n.notify(f)));return()=>o.forEach(d=>d.unsubscribe())})}function ci(a,n,o){let d=!1,f,c;return{throttled:(...u)=>{if(d){f=u;return}a(...u),d=!0,c=Pe(()=>{f&&a(...f),d=!1,f=void 0},n)},cancel:()=>{di(c),d=!1,f=void 0}}}function le(){}function fe(a){return a?(parseInt(a,10)^Math.random()*16>>parseInt(a,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,fe)}const qe=/([\\w-]+)\\s*=\\s*([^;]+)/g;function An(a,n){for(qe.lastIndex=0;;){const o=qe.exec(a);if(o){if(o[1]===n)return o[2]}else break}}function In(a){const n=new Map;for(qe.lastIndex=0;;){const o=qe.exec(a);if(o)n.set(o[1],o[2]);else break}return n}function Fn(a,n,o=""){const d=a.charCodeAt(n-1),c=d>=55296&&d<=56319?n+1:n;return a.length<=c?a:`${a.slice(0,c)}${o}`}function Bn(){return kn()===0}let We;function kn(){return We??(We=Ln())}function Ln(a=window){var n;const o=a.navigator.userAgent;return a.chrome||/HeadlessChrome/.test(o)?0:((n=a.navigator.vendor)===null||n===void 0?void 0:n.indexOf("Apple"))===0||/safari/i.test(o)&&!/chrome|android/i.test(o)?1:2}function ze(a,n,o=0,d){const f=new Date;f.setTime(f.getTime()+o);const c=`expires=${f.toUTCString()}`,u=d&&d.crossSite?"none":"strict",s=d&&d.domain?`;domain=${d.domain}`:"",p=d&&d.secure?";secure":"",_=d&&d.partitioned?";partitioned":"";document.cookie=`${a}=${n};${c};path=/;samesite=${u}${s}${p}${_}`}function wt(a){return An(document.cookie,a)}let Tt;function pe(a){return Tt||(Tt=In(document.cookie)),Tt.get(a)}function hi(a,n){ze(a,"",0,n)}function Dn(a){if(document.cookie===void 0||document.cookie===null)return!1;try{const n=`dd_cookie_test_${fe()}`,o="test";ze(n,o,ue,a);const d=wt(n)===o;return hi(n,a),d}catch(n){return M.error(n),!1}}let Ct;function Rn(){if(Ct===void 0){const a=`dd_site_test_${fe()}`,n="test",o=window.location.hostname.split(".");let d=o.pop();for(;o.length&&!wt(a);)d=`${o.pop()}.${d}`,ze(a,n,ke,{domain:d});hi(a,{domain:d}),Ct=d}return Ct}const Ee="_dd_s";function Je(a){return Object.values(a)}function Pn(a){return Object.entries(a)}const At=4*ni,ui=15*ue,zn=mn,Oe={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},pi=/^([a-zA-Z]+)=([a-z0-9-]+)$/,It="&";function On(a){return!!a&&(a.indexOf(It)!==-1||pi.test(a))}const Mn="1";function _e(a,n){const o={isExpired:Mn};return n.trackAnonymousUser&&(a!=null&&a.anonymousId?o.anonymousId=a==null?void 0:a.anonymousId:o.anonymousId=fe()),o}function Xe(a){return De(a)}function _i(a){return!Xe(a)}function Ze(a){return a.isExpired!==void 0||!Nn(a)}function Nn(a){return(a.created===void 0||Le()-Number(a.created)<At)&&(a.expire===void 0||Le()<Number(a.expire))}function gi(a){a.expire=String(Le()+ui)}function Ft(a){return Pn(a).map(([n,o])=>n==="anonymousId"?`aid=${o}`:`${n}=${o}`).join(It)}function mi(a){const n={};return On(a)&&a.split(It).forEach(o=>{const d=pi.exec(o);if(d!==null){const[,f,c]=d;f==="aid"?n.anonymousId=c:n[f]=c}}),n}const Gn="_dd",Hn="_dd_r",Yn="_dd_l",Vn="rum",$n="logs";function jn(a){if(!pe(Ee)){const o=pe(Gn),d=pe(Hn),f=pe(Yn),c={};o&&(c.id=o),f&&/^[01]$/.test(f)&&(c[$n]=f),d&&/^[012]$/.test(d)&&(c[Vn]=d),_i(c)&&(gi(c),a.persistSession(c))}}function yi(a){const n=Xn(a);return Dn(n)?{type:Oe.COOKIE,cookieOptions:n}:void 0}function Kn(a,n){const o={isLockEnabled:Bn(),persistSession:qn(n),retrieveSession:Jn,expireSession:d=>Wn(n,d,a)};return jn(o),o}function qn(a){return n=>{ze(Ee,Ft(n),ui,a)}}function Wn(a,n,o){const d=_e(n,o);ze(Ee,Ft(d),o.trackAnonymousUser?zn:At,a)}function Jn(){const a=wt(Ee);return mi(a)}function Xn(a){const n={};return n.secure=!!a.useSecureSessionCookie||!!a.usePartitionedCrossSiteSessionCookie,n.crossSite=!!a.usePartitionedCrossSiteSessionCookie,n.partitioned=!!a.usePartitionedCrossSiteSessionCookie,a.trackSessionAcrossSubdomains&&(n.domain=Rn()),n}const Zn="_dd_test_";function vi(){try{const a=fe(),n=`${Zn}${a}`;localStorage.setItem(n,a);const o=localStorage.getItem(n);return localStorage.removeItem(n),a===o?{type:Oe.LOCAL_STORAGE}:void 0}catch{return}}function Qn(a){return{isLockEnabled:!1,persistSession:Si,retrieveSession:er,expireSession:n=>tr(n,a)}}function Si(a){localStorage.setItem(Ee,Ft(a))}function er(){const a=localStorage.getItem(Ee);return mi(a)}function tr(a,n){Si(_e(a,n))}const ir=10,nr=100,bi=[];let Qe;function ge(a,n,o=0){var d;const{isLockEnabled:f,persistSession:c,expireSession:u}=n,s=U=>c({...U,lock:_}),p=()=>{const U=n.retrieveSession(),S=U.lock;return U.lock&&delete U.lock,{session:U,lock:S}};if(Qe||(Qe=a),a!==Qe){bi.push(a);return}if(f&&o>=nr){xi(n);return}let _,g=p();if(f){if(g.lock){et(a,n,o);return}if(_=fe(),s(g.session),g=p(),g.lock!==_){et(a,n,o);return}}let v=a.process(g.session);if(f&&(g=p(),g.lock!==_)){et(a,n,o);return}if(v&&(Ze(v)?u(v):(gi(v),f?s(v):c(v))),f&&!(v&&Ze(v))){if(g=p(),g.lock!==_){et(a,n,o);return}c(g.session),v=g.session}(d=a.after)===null||d===void 0||d.call(a,v||g.session),xi(n)}function et(a,n,o){Pe(()=>{ge(a,n,o+1)},ir)}function xi(a){Qe=void 0;const n=bi.shift();n&&ge(n,a)}const Ui=ke;function rr(a){switch(a.sessionPersistence){case Oe.COOKIE:return yi(a);case Oe.LOCAL_STORAGE:return vi();case void 0:{let n=yi(a);return!n&&a.allowFallbackToLocalStorage&&(n=vi()),n}default:M.error(`Invalid session persistence \'${String(a.sessionPersistence)}\'`)}}function sr(a,n,o,d){const f=new G,c=new G,u=new G,s=a.type===Oe.COOKIE?Kn(n,a.cookieOptions):Qn(n),{expireSession:p}=s,_=Et(E,Ui);let g;t();const{throttled:v,cancel:U}=ci(()=>{ge({process:x=>{if(Xe(x))return;const w=e(x);return r(w),w},after:x=>{_i(x)&&!l()&&y(x),g=x}},s)},Ui);function S(){ge({process:x=>l()?e(x):void 0},s)}function E(){ge({process:x=>Ze(x)?_e(x,n):void 0,after:e},s)}function e(x){return Ze(x)&&(x=_e(x,n)),l()&&(h(x)?m():(u.notify({previousState:g,newState:x}),g=x)),x}function t(){ge({process:x=>{if(Xe(x))return _e(x,n)},after:x=>{g=x}},s)}function r(x){if(Xe(x))return!1;const{trackingType:w,isTracked:T}=d(x[o]);x[o]=w,delete x.isExpired,T&&!x.id&&(x.id=fe(),x.created=String(Le()))}function l(){return g[o]!==void 0}function h(x){return g.id!==x.id||g[o]!==x[o]}function m(){g=_e(g,n),c.notify()}function y(x){g=x,f.notify()}function b(x){ge({process:w=>({...w,...x}),after:e},s)}return{expandOrRenewSession:v,expandSession:S,getSession:()=>g,renewObservable:f,expireObservable:c,sessionStateUpdateObservable:u,restartSession:t,expire:()=>{U(),p(g),e(_e(g,n))},stop:()=>{li(_)},updateSessionState:b}}const Bt={GRANTED:"granted",NOT_GRANTED:"not-granted"};function or(a){const n=new G;return{tryToInit(o){a||(a=o)},update(o){a=o,n.notify()},isGranted(){return a===Bt.GRANTED},observable:n}}function me(a,n,o){if(typeof a!="object"||a===null)return JSON.stringify(a);const d=we(Object.prototype),f=we(Array.prototype),c=we(Object.getPrototypeOf(a)),u=we(a);try{return JSON.stringify(a,n,o)}catch{return"<error: unable to serialize object>"}finally{d(),f(),c(),u()}}function we(a){const n=a,o=n.toJSON;return o?(delete n.toJSON,()=>{n.toJSON=o}):le}function kt(a){return ar(a,location.href).href}function ar(a,n){const o=dr();if(o)try{return n!==void 0?new o(a,n):new o(a)}catch(c){throw new Error(`Failed to construct URL: ${String(c)} ${me({url:a,base:n})}`)}if(n===void 0&&!/:/.test(a))throw new Error(`Invalid URL: \'${a}\'`);let d=document;const f=d.createElement("a");if(n!==void 0){d=document.implementation.createHTMLDocument("");const c=d.createElement("base");c.href=n,d.head.appendChild(c),d.body.appendChild(f)}return f.href=a,f}const Ei=URL;let tt;function dr(){if(tt===void 0)try{tt=new Ei("http://test/path").href==="http://test/path"}catch{tt=!1}return tt?Ei:void 0}const lr="datad0g.com",fr="dd0g-gov.com",Te="datadoghq.com",cr="ddog-gov.com",hr="pci.browser-intake-datadoghq.com",ur=["ddsource","ddtags"];function Me(a,n,o){const d=pr(a,n);return{build(f,c){const u=gr(a,n,o,f,c);return d(u)},urlPrefix:d(""),trackType:n}}function pr(a,n){const o=`/api/v2/${n}`,d=a.proxy;if(typeof d=="string"){const c=kt(d);return u=>`${c}?ddforward=${encodeURIComponent(`${o}?${u}`)}`}if(typeof d=="function")return c=>d({path:o,parameters:c});const f=_r(n,a);return c=>`https://${f}${o}?${c}`}function _r(a,n){const{site:o=Te,internalAnalyticsSubdomain:d}=n;if(a==="logs"&&n.usePciIntake&&o===Te)return hr;if(d&&o===Te)return`${d}.${Te}`;if(o===fr)return`http-intake.logs.${o}`;const f=o.split("."),c=f.pop();return`browser-intake-${f.join("-")}.${c}`}function gr({clientToken:a,internalAnalyticsSubdomain:n},o,d,f,{retry:c,encoding:u}){const s=["sdk_version:6.5.0",`api:${f}`].concat(d);c&&s.push(`retry_count:${c.count}`,`retry_after:${c.lastFailureStatus}`);const p=["ddsource=browser",`ddtags=${encodeURIComponent(s.join(","))}`,`dd-api-key=${a}`,`dd-evp-origin-version=${encodeURIComponent("6.5.0")}`,"dd-evp-origin=browser",`dd-request-id=${fe()}`];return u&&p.push(`dd-evp-encoding=${u}`),o==="rum"&&p.push(`batch_time=${oe()}`),n&&p.reverse(),p.join("&")}const mr=200;function yr(a){const{env:n,service:o,version:d,datacenter:f}=a,c=[];return n&&c.push(it("env",n)),o&&c.push(it("service",o)),d&&c.push(it("version",d)),f&&c.push(it("datacenter",f)),c}function it(a,n){const o=mr-a.length-1;(n.length>o||vr(n))&&M.warn(`${a} value doesn\'t meet tag requirements and will be sanitized. ${Ve} ${St}/getting_started/tagging/#defining-tags`);const d=n.replace(/,/g,"_");return`${a}:${d}`}function vr(a){return Sr()?new RegExp("[^\\\\p{Ll}\\\\p{Lo}0-9_:./-]","u").test(a):!1}function Sr(){try{return new RegExp("[\\\\p{Ll}]","u"),!0}catch{return!1}}function br(a){const n=a.site||Te,o=yr(a),d=xr(a,o);return{replica:Ur(a,o),site:n,...d}}function xr(a,n){return{logsEndpointBuilder:Me(a,"logs",n),rumEndpointBuilder:Me(a,"rum",n),sessionReplayEndpointBuilder:Me(a,"replay",n)}}function Ur(a,n){if(!a.replica)return;const o={...a,site:Te,clientToken:a.replica.clientToken},d={logsEndpointBuilder:Me(o,"logs",n),rumEndpointBuilder:Me(o,"rum",n)};return{applicationId:a.replica.applicationId,...d}}function Er(a){return ur.every(n=>a.includes(n))}function Lt(a,n){return a!=null&&typeof a!="string"?(M.error(`${n} must be defined as a string`),!1):!0}function wr(a){return a&&typeof a=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(a)?(M.error(`Site should be a valid Datadog site. ${Ve} ${St}/getting_started/site/.`),!1):!0}function nt(a,n){return a!==void 0&&!_n(a)?(M.error(`${n} Sample Rate should be a number between 0 and 100`),!1):!0}function Tr(a){var n,o,d,f,c,u;if(!a||!a.clientToken){M.error("Client Token is not configured, we will not send any data.");return}if(!(!wr(a.site)||!nt(a.sessionSampleRate,"Session")||!nt(a.telemetrySampleRate,"Telemetry")||!nt(a.telemetryConfigurationSampleRate,"Telemetry Configuration")||!nt(a.telemetryUsageSampleRate,"Telemetry Usage")||!Lt(a.version,"Version")||!Lt(a.env,"Env")||!Lt(a.service,"Service"))){if(a.trackingConsent!==void 0&&!oi(Bt,a.trackingConsent)){M.error(\'Tracking Consent should be either "granted" or "not-granted"\');return}return{beforeSend:a.beforeSend&&ii(a.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:rr(a),sessionSampleRate:(n=a.sessionSampleRate)!==null&&n!==void 0?n:100,telemetrySampleRate:(o=a.telemetrySampleRate)!==null&&o!==void 0?o:20,telemetryConfigurationSampleRate:(d=a.telemetryConfigurationSampleRate)!==null&&d!==void 0?d:5,telemetryUsageSampleRate:(f=a.telemetryUsageSampleRate)!==null&&f!==void 0?f:5,service:a.service||void 0,silentMultipleInit:!!a.silentMultipleInit,allowUntrustedEvents:!!a.allowUntrustedEvents,trackingConsent:(c=a.trackingConsent)!==null&&c!==void 0?c:Bt.GRANTED,trackAnonymousUser:(u=a.trackAnonymousUser)!==null&&u!==void 0?u:!0,storeContextsAcrossPages:!!a.storeContextsAcrossPages,batchBytesLimit:16*ie,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*ke,batchMessagesLimit:50,messageBytesLimit:256*ie,...br(a)}}}function Cr(a){return{session_sample_rate:a.sessionSampleRate,telemetry_sample_rate:a.telemetrySampleRate,telemetry_configuration_sample_rate:a.telemetryConfigurationSampleRate,telemetry_usage_sample_rate:a.telemetryUsageSampleRate,use_before_send:!!a.beforeSend,use_partitioned_cross_site_session_cookie:a.usePartitionedCrossSiteSessionCookie,use_secure_session_cookie:a.useSecureSessionCookie,use_proxy:!!a.proxy,silent_multiple_init:a.silentMultipleInit,track_session_across_subdomains:a.trackSessionAcrossSubdomains,track_anonymous_user:a.trackAnonymousUser,session_persistence:a.sessionPersistence,allow_fallback_to_local_storage:!!a.allowFallbackToLocalStorage,store_contexts_across_pages:!!a.storeContextsAcrossPages,allow_untrusted_events:!!a.allowUntrustedEvents,tracking_consent:a.trackingConsent}}var Dt;(function(a){a.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",a.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(Dt||(Dt={}));const wi=new Set;function Ar(a){Array.isArray(a)&&Ir(a.filter(n=>oi(Dt,n)))}function Ir(a){a.forEach(n=>{wi.add(n)})}function Fr(){return wi}const Ne="?";function ne(a){const n=[];let o=Rt(a,"stack");const d=String(a);return o&&o.startsWith(d)&&(o=o.slice(d.length)),o&&o.split(`\n`).forEach(f=>{const c=Lr(f)||Rr(f)||zr(f)||Nr(f);c&&(!c.func&&c.line&&(c.func=Ne),n.push(c))}),{message:Rt(a,"message"),name:Rt(a,"name"),stack:n}}const Ti="((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\\\w+\\\\.|\\\\/).*?)",Ce="(?::(\\\\d+))",Br=new RegExp(`^\\\\s*at (.*?) ?\\\\(${Ti}${Ce}?${Ce}?\\\\)?\\\\s*$`,"i"),kr=new RegExp(`\\\\((\\\\S*)${Ce}${Ce}\\\\)`);function Lr(a){const n=Br.exec(a);if(!n)return;const o=n[2]&&n[2].indexOf("native")===0,d=n[2]&&n[2].indexOf("eval")===0,f=kr.exec(n[2]);return d&&f&&(n[2]=f[1],n[3]=f[2],n[4]=f[3]),{args:o?[n[2]]:[],column:n[4]?+n[4]:void 0,func:n[1]||Ne,line:n[3]?+n[3]:void 0,url:o?void 0:n[2]}}const Dr=new RegExp(`^\\\\s*at ?${Ti}${Ce}?${Ce}??\\\\s*$`,"i");function Rr(a){const n=Dr.exec(a);if(n)return{args:[],column:n[3]?+n[3]:void 0,func:Ne,line:n[2]?+n[2]:void 0,url:n[1]}}const Pr=/^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;function zr(a){const n=Pr.exec(a);if(n)return{args:[],column:n[4]?+n[4]:void 0,func:n[1]||Ne,line:+n[3],url:n[2]}}const Or=/^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i,Mr=/(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;function Nr(a){const n=Or.exec(a);if(!n)return;const o=n[3]&&n[3].indexOf(" > eval")>-1,d=Mr.exec(n[3]);return o&&d&&(n[3]=d[1],n[4]=d[2],n[5]=void 0),{args:n[2]?n[2].split(","):[],column:n[5]?+n[5]:void 0,func:n[1]||Ne,line:n[4]?+n[4]:void 0,url:n[3]}}function Rt(a,n){if(typeof a!="object"||!a||!(n in a))return;const o=a[n];return typeof o=="string"?o:void 0}function Gr(a,n,o,d){const f=[{url:n,column:d,line:o}],{name:c,message:u}=Yr(a);return{name:c,message:u,stack:f}}const Hr=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\\s\\S]*)$/;function Yr(a){let n,o;return{}.toString.call(a)==="[object String]"&&([,n,o]=Hr.exec(a)),{name:n,message:o}}function rt(a){const o=new Error(a);o.name="HandlingStack";let d;return Re(()=>{const f=ne(o);f.stack=f.stack.slice(2),d=ye(f)}),d}function ye(a){let n=Ci(a);return a.stack.forEach(o=>{const d=o.func==="?"?"<anonymous>":o.func,f=o.args&&o.args.length>0?`(${o.args.join(", ")})`:"",c=o.line?`:${o.line}`:"",u=o.line&&o.column?`:${o.column}`:"";n+=`\n at ${d}${f} @ ${o.url}${c}${u}`}),n}function Ci(a){return`${a.name||"Error"}: ${a.message}`}function ve(a,n,o,{computeHandlingStack:d}={}){let f=a[n];if(typeof f!="function")if(n in a&&n.startsWith("on"))f=le;else return{stop:le};let c=!1;const u=function(){if(c)return f.apply(this,arguments);const s=Array.from(arguments);let p;Re(o,null,[{target:this,parameters:s,onPostCall:g=>{p=g},handlingStack:d?rt("instrumented method"):void 0}]);const _=f.apply(this,s);return p&&Re(p,null,[_]),_};return a[n]=u,{stop:()=>{c=!0,a[n]===u&&(a[n]=f)}}}const Vr=220*ie,$r="$",jr=3;function re(a,n=Vr){const o=we(Object.prototype),d=we(Array.prototype),f=[],c=new WeakMap,u=Pt(a,$r,void 0,f,c),s=JSON.stringify(u);let p=s?s.length:0;if(p>n){Ot(n,"discarded",a);return}for(;f.length>0&&p<n;){const _=f.shift();let g=0;if(Array.isArray(_.source))for(let v=0;v<_.source.length;v++){const U=Pt(_.source[v],_.path,v,f,c);if(U!==void 0?p+=JSON.stringify(U).length:p+=4,p+=g,g=1,p>n){Ot(n,"truncated",a);break}_.target[v]=U}else for(const v in _.source)if(Object.prototype.hasOwnProperty.call(_.source,v)){const U=Pt(_.source[v],_.path,v,f,c);if(U!==void 0&&(p+=JSON.stringify(U).length+g+v.length+jr,g=1),p>n){Ot(n,"truncated",a);break}_.target[v]=U}}return o(),d(),u}function Pt(a,n,o,d,f){const c=Wr(a);if(!c||typeof c!="object")return Kr(c);const u=zt(c);if(u!=="[Object]"&&u!=="[Array]"&&u!=="[Error]")return u;const s=a;if(f.has(s))return`[Reference seen at ${f.get(s)}]`;const p=o!==void 0?`${n}.${o}`:n,_=Array.isArray(c)?[]:{};return f.set(s,p),d.push({source:c,target:_,path:p}),_}function Kr(a){return typeof a=="bigint"?`[BigInt] ${a.toString()}`:typeof a=="function"?`[Function] ${a.name||"unknown"}`:typeof a=="symbol"?`[Symbol] ${a.description||a.toString()}`:a}function zt(a){try{if(a instanceof Event)return qr(a);if(a instanceof RegExp)return`[RegExp] ${a.toString()}`;const o=Object.prototype.toString.call(a).match(/\\[object (.*)\\]/);if(o&&o[1])return`[${o[1]}]`}catch{}return"[Unserializable]"}function qr(a){return{type:a.type,isTrusted:a.isTrusted,currentTarget:a.currentTarget?zt(a.currentTarget):null,target:a.target?zt(a.target):null}}function Wr(a){const n=a;if(n&&typeof n.toJSON=="function")try{return n.toJSON()}catch{}return a}function Ot(a,n,o){M.warn(`The data provided has been ${n} as it is over the limit of ${a} characters:`,o)}const Ai="No stack, consider using an instance of Error";function Ii({stackTrace:a,originalError:n,handlingStack:o,componentStack:d,startClocks:f,nonErrorPrefix:c,source:u,handling:s}){const p=ce(n),_=Jr(a,p,c,n),g=Xr(p,a)?ye(a):Ai,v=p?ki(n,u):void 0,U=a?a.name:void 0,S=Fi(n),E=Bi(n);return{startClocks:f,source:u,handling:s,handlingStack:o,componentStack:d,originalError:n,type:U,message:_,stack:g,causes:v,fingerprint:S,context:E}}function Jr(a,n,o,d){return a!=null&&a.message&&(a!=null&&a.name)?a.message:n?"Empty message":`${o} ${me(re(d))}`}function Xr(a,n){return n===void 0?!1:a?!0:n.stack.length>0&&(n.stack.length>1||n.stack[0].url!==void 0)}function Fi(a){return ce(a)&&"dd_fingerprint"in a?String(a.dd_fingerprint):void 0}function Bi(a){if(a!==null&&typeof a=="object"&&"dd_context"in a)return a.dd_context}function Zr(a){var n;return(n=/@ (.+)/.exec(a))===null||n===void 0?void 0:n[1]}function ce(a){return a instanceof Error||Object.prototype.toString.call(a)==="[object Error]"}function ki(a,n){let o=a;const d=[];for(;ce(o==null?void 0:o.cause)&&d.length<10;){const f=ne(o.cause);d.push({message:o.cause.message,source:n,type:f==null?void 0:f.name,stack:ye(f)}),o=o.cause}return d.length?d:void 0}const J={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function Qr(a){const n=(f,c)=>{const u=Ii({stackTrace:f,originalError:c,startClocks:ae(),nonErrorPrefix:"Uncaught",source:J.SOURCE,handling:"unhandled"});a.notify(u)},{stop:o}=es(n),{stop:d}=ts(n);return{stop:()=>{o(),d()}}}function es(a){return ve(window,"onerror",({parameters:[n,o,d,f,c]})=>{let u;ce(c)?u=ne(c):u=Gr(n,o,d,f),a(u,c??n)})}function ts(a){return ve(window,"onunhandledrejection",({parameters:[n]})=>{const o=n.reason||"Empty reason",d=ne(o);a(d,o)})}function is(a){const n={version:"6.5.0",onReady(o){o()},...a};return Object.defineProperty(n,"_setDebug",{get(){return wn},enumerable:!1}),n}function ns(a,n,o){const d=a[n];d&&!d.q&&d.version&&M.warn("SDK is loaded more than once. This is unsupported and might have unexpected behavior."),a[n]=o,d&&d.q&&d.q.forEach(f=>ii(f,"onReady callback threw an error:")())}function Li(a,n){n.silentMultipleInit||M.error(`${a} is already initialized.`)}function Se(a,n,o,d,f){return Mt(a,n,[o],d,f)}function Mt(a,n,o,d,{once:f,capture:c,passive:u}={}){const s=D(U=>{!U.isTrusted&&!U.__ddIsTrusted&&!a.allowUntrustedEvents||(f&&v(),d(U))}),p=u?{capture:c,passive:u}:c,_=window.EventTarget&&n instanceof EventTarget?window.EventTarget.prototype:n,g=Ue(_,"addEventListener");o.forEach(U=>g.call(n,U,s,p));function v(){const U=Ue(_,"removeEventListener");o.forEach(S=>U.call(n,S,s,p))}return{stop:v}}const st={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function rs(a,n){const o=[];n.includes(st.cspViolation)&&o.push(os(a));const d=n.filter(f=>f!==st.cspViolation);return d.length&&o.push(ss(d)),fi(...o)}function ss(a){return new G(n=>{if(!window.ReportingObserver)return;const o=D((f,c)=>f.forEach(u=>n.notify(as(u)))),d=new window.ReportingObserver(o,{types:a,buffered:!0});return d.observe(),()=>{d.disconnect()}})}function os(a){return new G(n=>{const{stop:o}=Se(a,document,"securitypolicyviolation",d=>{n.notify(ds(d))});return o})}function as(a){const{type:n,body:o}=a;return Di({type:o.id,message:`${n}: ${o.message}`,originalError:a,stack:Ri(o.id,o.message,o.sourceFile,o.lineNumber,o.columnNumber)})}function ds(a){const n=`\'${a.blockedURI}\' blocked by \'${a.effectiveDirective}\' directive`;return Di({type:a.effectiveDirective,message:`${st.cspViolation}: ${n}`,originalError:a,csp:{disposition:a.disposition},stack:Ri(a.effectiveDirective,a.originalPolicy?`${n} of the policy "${Fn(a.originalPolicy,100,"...")}"`:"no policy",a.sourceFile,a.lineNumber,a.columnNumber)})}function Di(a){return{startClocks:ae(),source:J.REPORT,handling:"unhandled",...a}}function Ri(a,n,o,d,f){return o?ye({name:a,message:n,stack:[{func:"?",url:o,line:d??void 0,column:f??void 0}]}):void 0}function Pi(a,n){const o=window.__ddBrowserSdkExtensionCallback;o&&o({type:a,payload:n})}function zi(a){return a===null?"null":Array.isArray(a)?"array":typeof a}function ot(a,n,o=ls()){if(n===void 0)return a;if(typeof n!="object"||n===null)return n;if(n instanceof Date)return new Date(n.getTime());if(n instanceof RegExp){const f=n.flags||[n.global?"g":"",n.ignoreCase?"i":"",n.multiline?"m":"",n.sticky?"y":"",n.unicode?"u":""].join("");return new RegExp(n.source,f)}if(o.hasAlreadyBeenSeen(n))return;if(Array.isArray(n)){const f=Array.isArray(a)?a:[];for(let c=0;c<n.length;++c)f[c]=ot(f[c],n[c],o);return f}const d=zi(a)==="object"?a:{};for(const f in n)Object.prototype.hasOwnProperty.call(n,f)&&(d[f]=ot(d[f],n[f],o));return d}function Oi(a){return ot(void 0,a)}function Ae(...a){let n;for(const o of a)o!=null&&(n=ot(n,o));return n}function ls(){if(typeof WeakSet<"u"){const n=new WeakSet;return{hasAlreadyBeenSeen(o){const d=n.has(o);return d||n.add(o),d}}}const a=[];return{hasAlreadyBeenSeen(n){const o=a.indexOf(n)>=0;return o||a.push(n),o}}}function fs(){var a;const n=window.navigator;return{status:n.onLine?"connected":"not_connected",interfaces:n.connection&&n.connection.type?[n.connection.type]:void 0,effective_type:(a=n.connection)===null||a===void 0?void 0:a.effectiveType}}function cs(a){const n=new Set;return a.forEach(o=>n.add(o)),Array.from(n)}function Mi(a,n){const o=a.indexOf(n);o>=0&&a.splice(o,1)}const hs=500;function Ni(){const a=[];return{add:f=>{a.push(f)>hs&&a.splice(0,1)},remove:f=>{Mi(a,f)},drain:f=>{a.forEach(c=>c(f)),a.length=0}}}const be={log:"log",configuration:"configuration",usage:"usage"},us=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],ps=[cr];let Gi=Ni(),Ie=a=>{Gi.add(()=>Ie(a))};function _s(a,n){let o;const d=new G,f=new Set,c=!ps.includes(n.site)&&$e(n.telemetrySampleRate),u={[be.log]:c,[be.configuration]:c&&$e(n.telemetryConfigurationSampleRate),[be.usage]:c&&$e(n.telemetryUsageSampleRate)},s=gs();Ie=_=>{const g=me(_);if(u[_.type]&&f.size<n.maxTelemetryEventsPerPage&&!f.has(g)){const v=p(a,_,s);d.notify(v),Pi("telemetry",v),f.add(g)}},En(Yi);function p(_,g,v){return Ae({type:"telemetry",date:oe(),service:_,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:Ae(g,{runtime_env:v,connectivity:fs(),sdk_setup:"npm"}),experimental_features:Array.from(Fr())},o!==void 0?o():{})}return{setContextProvider:_=>{o=_},observable:d,enabled:c}}function gs(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function ms(){Gi.drain()}function ys(a){return a.site===lr}function Hi(a,n){Ut(O.debug,a,n),Ie({type:be.log,message:a,status:"debug",...n})}function Yi(a,n){Ie({type:be.log,status:"error",...bs(a),...n})}function vs(a){Ie({type:be.configuration,configuration:a})}function Ss(a){Ie({type:be.usage,usage:a})}function bs(a){if(ce(a)){const n=ne(a);return{error:{kind:n.name,stack:ye(xs(n))},message:n.message}}return{error:{stack:Ai},message:`Uncaught ${me(a)}`}}function xs(a){return a.stack=a.stack.filter(n=>!n.url||us.some(o=>n.url.startsWith(o))),a}const Ge=1/0,Us=ue;let He=null;const at=new Set;function Es(){at.forEach(a=>a())}function ws({expireDelay:a,maxEntries:n}){let o=[];const d=[];He||(He=Et(()=>Es(),Us));const f=()=>{const S=je()-a;for(;o.length>0&&o[o.length-1].endTime<S;){const E=o.pop();E&&d.push(E.startTime)}};at.add(f);function c(S,E){const e={value:S,startTime:E,endTime:Ge,remove:()=>{Mi(o,e)},close:t=>{e.endTime=t}};return n&&o.length>=n&&o.pop(),o.unshift(e),e}function u(S=Ge,E={returnInactive:!1}){for(const e of o)if(e.startTime<=S){if(E.returnInactive||S<=e.endTime)return e.value;break}}function s(S){const E=o[0];E&&E.endTime===Ge&&E.close(S)}function p(S=Ge,E=0){const e=Sn(S,E);return o.filter(t=>t.startTime<=e&&S<=t.endTime).map(t=>t.value)}function _(){return o.map(({startTime:S,endTime:E,value:e})=>({startTime:S,endTime:E===Ge?"Infinity":E,value:e}))}function g(){return d}function v(){o=[]}function U(){at.delete(f),at.size===0&&He&&(li(He),He=null)}return{add:c,find:u,closeActive:s,findAll:p,reset:v,stop:U,getAllEntries:_,getDeletedEntries:g}}const Ts=ue,Cs=At;function As(a,n,o,d){const f=new G,c=new G,u=sr(a.sessionStoreStrategyType,a,n,o),s=ws({expireDelay:Cs});u.renewObservable.subscribe(()=>{s.add(p(),je()),f.notify()}),u.expireObservable.subscribe(()=>{c.notify(),s.closeActive(je())}),u.expandOrRenewSession(),s.add(p(),yn().relative),d.observable.subscribe(()=>{d.isGranted()?u.expandOrRenewSession():u.expire()}),Is(a,()=>{d.isGranted()&&u.expandOrRenewSession()}),Fs(a,()=>u.expandSession()),Bs(a,()=>u.restartSession());function p(){return{id:u.getSession().id,trackingType:u.getSession()[n],isReplayForced:!!u.getSession().forcedReplay,anonymousId:u.getSession().anonymousId}}return{findSession:(_,g)=>s.find(_,g),renewObservable:f,expireObservable:c,sessionStateUpdateObservable:u.sessionStateUpdateObservable,expire:u.expire,updateSessionState:u.updateSessionState}}function Is(a,n){Mt(a,window,["click","touchstart","keydown","scroll"],n,{capture:!0,passive:!0})}function Fs(a,n){const o=()=>{document.visibilityState==="visible"&&n()};Se(a,document,"visibilitychange",o),Et(o,Ts)}function Bs(a,n){Se(a,window,"resume",n,{capture:!0})}function Vi(a){return a>=500}function ks(a){try{return a.clone()}catch{return}}const Ls=80*ie,Ds=32,$i=3*si,Rs=ue,ji=ke;function Ki(a,n,o,d,f){n.transportStatus===0&&n.queuedPayloads.size()===0&&n.bandwidthMonitor.canHandle(a)?Wi(a,n,o,{onSuccess:()=>Ji(0,n,o,d,f),onFailure:()=>{n.queuedPayloads.enqueue(a),qi(n,o,d,f)}}):n.queuedPayloads.enqueue(a)}function qi(a,n,o,d){a.transportStatus===2&&Pe(()=>{const f=a.queuedPayloads.first();Wi(f,a,n,{onSuccess:()=>{a.queuedPayloads.dequeue(),a.currentBackoffTime=ji,Ji(1,a,n,o,d)},onFailure:()=>{a.currentBackoffTime=Math.min(Rs,a.currentBackoffTime*2),qi(a,n,o,d)}})},a.currentBackoffTime)}function Wi(a,n,o,{onSuccess:d,onFailure:f}){n.bandwidthMonitor.add(a),o(a,c=>{n.bandwidthMonitor.remove(a),Ps(c)?(n.transportStatus=n.bandwidthMonitor.ongoingRequestCount>0?1:2,a.retry={count:a.retry?a.retry.count+1:1,lastFailureStatus:c.status},f()):(n.transportStatus=0,d())})}function Ji(a,n,o,d,f){a===0&&n.queuedPayloads.isFull()&&!n.queueFullReported&&(f({message:`Reached max ${d} events size queued for upload: ${$i/si}MiB`,source:J.AGENT,startClocks:ae()}),n.queueFullReported=!0);const c=n.queuedPayloads;for(n.queuedPayloads=Xi();c.size()>0;)Ki(c.dequeue(),n,o,d,f)}function Ps(a){return a.type!=="opaque"&&(a.status===0&&!navigator.onLine||a.status===408||a.status===429||Vi(a.status))}function zs(){return{transportStatus:0,currentBackoffTime:ji,bandwidthMonitor:Os(),queuedPayloads:Xi(),queueFullReported:!1}}function Xi(){const a=[];return{bytesCount:0,enqueue(n){this.isFull()||(a.push(n),this.bytesCount+=n.bytesCount)},first(){return a[0]},dequeue(){const n=a.shift();return n&&(this.bytesCount-=n.bytesCount),n},size(){return a.length},isFull(){return this.bytesCount>=$i}}}function Os(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(a){return this.ongoingRequestCount===0||this.ongoingByteCount+a.bytesCount<=Ls&&this.ongoingRequestCount<Ds},add(a){this.ongoingRequestCount+=1,this.ongoingByteCount+=a.bytesCount},remove(a){this.ongoingRequestCount-=1,this.ongoingByteCount-=a.bytesCount}}}function Ms(a,n,o){const d=zs(),f=(c,u)=>Hs(a,n,c,u);return{send:c=>{Ki(c,d,f,a.trackType,o)},sendOnExit:c=>{Ns(a,n,c)}}}function Ns(a,n,o){if(!!navigator.sendBeacon&&o.bytesCount<n)try{const c=a.build("beacon",o);if(navigator.sendBeacon(c,o.data))return}catch(c){Gs(c)}const f=a.build("xhr",o);Nt(f,o.data)}let Zi=!1;function Gs(a){Zi||(Zi=!0,Yi(a))}function Hs(a,n,o,d){if(Ys()&&o.bytesCount<n){const c=a.build("fetch",o);fetch(c,{method:"POST",body:o.data,keepalive:!0,mode:"cors"}).then(D(u=>d==null?void 0:d({status:u.status,type:u.type})),D(()=>{const u=a.build("xhr",o);Nt(u,o.data,d)}))}else{const c=a.build("xhr",o);Nt(c,o.data,d)}}function Ys(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function Nt(a,n,o){const d=new XMLHttpRequest;d.open("POST",a,!0),n instanceof Blob&&d.setRequestHeader("Content-Type",n.type),Se({allowUntrustedEvents:!0},d,"loadend",()=>{o==null||o({status:d.status})},{once:!0}),d.send(n)}function Gt(){const a=Vs();if(a)return{getCapabilities(){var n;return JSON.parse(((n=a.getCapabilities)===null||n===void 0?void 0:n.call(a))||"[]")},getPrivacyLevel(){var n;return(n=a.getPrivacyLevel)===null||n===void 0?void 0:n.call(a)},getAllowedWebViewHosts(){return JSON.parse(a.getAllowedWebViewHosts())},send(n,o,d){const f=d?{id:d}:void 0;a.send(JSON.stringify({eventType:n,event:o,view:f}))}}}function dt(a){var n;a===void 0&&(a=(n=de().location)===null||n===void 0?void 0:n.hostname);const o=Gt();return!!o&&o.getAllowedWebViewHosts().some(d=>a===d||a.endsWith(`.${d}`))}function Vs(){return de().DatadogEventBridge}const lt={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function $s(a){return new G(n=>{const{stop:o}=Mt(a,window,["visibilitychange","freeze"],f=>{f.type==="visibilitychange"&&document.visibilityState==="hidden"?n.notify({reason:lt.HIDDEN}):f.type==="freeze"&&n.notify({reason:lt.FROZEN})},{capture:!0}),d=Se(a,window,"beforeunload",()=>{n.notify({reason:lt.UNLOADING})}).stop;return()=>{o(),d()}})}function js(a){return Je(lt).includes(a)}function Ks({encoder:a,request:n,flushController:o,messageBytesLimit:d}){let f={};const c=o.flushObservable.subscribe(v=>g(v));function u(v,U,S){o.notifyBeforeAddMessage(U),S!==void 0?(f[S]=v,o.notifyAfterAddMessage()):a.write(a.isEmpty?v:`\n${v}`,E=>{o.notifyAfterAddMessage(E-U)})}function s(v){return v!==void 0&&f[v]!==void 0}function p(v){const U=f[v];delete f[v];const S=a.estimateEncodedBytesCount(U);o.notifyAfterRemoveMessage(S)}function _(v,U){const S=me(v),E=a.estimateEncodedBytesCount(S);if(E>=d){M.warn(`Discarded a message whose size was bigger than the maximum allowed size ${d}KB. ${Ve} ${ti}/#technical-limitations`);return}s(U)&&p(U),u(S,E,U)}function g(v){const U=Je(f).join(`\n`);f={};const S=js(v.reason),E=S?n.sendOnExit:n.send;if(S&&a.isAsync){const e=a.finishSync();e.outputBytesCount&&E(Qi(e));const t=[e.pendingData,U].filter(Boolean).join(`\n`);t&&E({data:t,bytesCount:xt(t)})}else U&&a.write(a.isEmpty?U:`\n${U}`),a.finish(e=>{E(Qi(e))})}return{flushController:o,add:_,upsert:_,stop:c.unsubscribe}}function Qi(a){let n;return typeof a.output=="string"?n=a.output:n=new Blob([a.output],{type:"text/plain"}),{data:n,bytesCount:a.outputBytesCount,encoding:a.encoding}}function qs({messagesLimit:a,bytesLimit:n,durationLimit:o,pageExitObservable:d,sessionExpireObservable:f}){const c=d.subscribe(E=>g(E.reason)),u=f.subscribe(()=>g("session_expire")),s=new G(()=>()=>{c.unsubscribe(),u.unsubscribe()});let p=0,_=0;function g(E){if(_===0)return;const e=_,t=p;_=0,p=0,S(),s.notify({reason:E,messagesCount:e,bytesCount:t})}let v;function U(){v===void 0&&(v=Pe(()=>{g("duration_limit")},o))}function S(){di(v),v=void 0}return{flushObservable:s,get messagesCount(){return _},notifyBeforeAddMessage(E){p+E>=n&&g("bytes_limit"),_+=1,p+=E,U()},notifyAfterAddMessage(E=0){p+=E,_>=a?g("messages_limit"):p>=n&&g("bytes_limit")},notifyAfterRemoveMessage(E){p-=E,_-=1,_===0&&S()}}}function en(a,n,o,d,f,c,u=Ks){const s=_(a,n),p=o&&_(a,o);function _(g,{endpoint:v,encoder:U}){return u({encoder:U,request:Ms(v,g.batchBytesLimit,d),flushController:qs({messagesLimit:g.batchMessagesLimit,bytesLimit:g.batchBytesLimit,durationLimit:g.flushTimeout,pageExitObservable:f,sessionExpireObservable:c}),messageBytesLimit:g.messageBytesLimit})}return{flushObservable:s.flushController.flushObservable,add(g,v=!0){s.add(g),p&&v&&p.add(o.transformMessage?o.transformMessage(g):g)},upsert:(g,v)=>{s.upsert(g,v),p&&p.upsert(o.transformMessage?o.transformMessage(g):g,v)},stop:()=>{s.stop(),p&&p.stop()}}}function ft(){let a="",n=0;return{isAsync:!1,get isEmpty(){return!a},write(o,d){const f=xt(o);n+=f,a+=o,d&&d(f)},finish(o){o(this.finishSync())},finishSync(){const o={output:a,outputBytesCount:n,rawBytesCount:n,pendingData:""};return a="",n=0,o},estimateEncodedBytesCount(o){return o.length}}}class Ws{constructor(){this.callbacks={}}notify(n,o){const d=this.callbacks[n];d&&d.forEach(f=>f(o))}subscribe(n,o){return this.callbacks[n]||(this.callbacks[n]=[]),this.callbacks[n].push(o),{unsubscribe:()=>{this.callbacks[n]=this.callbacks[n].filter(d=>o!==d)}}}}function Js(a,n,o){let d=0,f=!1;return{isLimitReached(){if(d===0&&Pe(()=>{d=0},ue),d+=1,d<=n||f)return f=!1,!1;if(d===n+1){f=!0;try{o({message:`Reached max number of ${a}s by minute: ${n}`,source:J.AGENT,startClocks:ae()})}finally{f=!1}}return!0}}}let Ht;const Yt=new WeakMap;function Xs(a){return Ht||(Ht=Zs(a)),Ht}function Zs(a){return new G(n=>{const{stop:o}=ve(XMLHttpRequest.prototype,"open",Qs),{stop:d}=ve(XMLHttpRequest.prototype,"send",c=>{eo(c,a,n)},{computeHandlingStack:!0}),{stop:f}=ve(XMLHttpRequest.prototype,"abort",to);return()=>{o(),d(),f()}})}function Qs({target:a,parameters:[n,o]}){Yt.set(a,{state:"open",method:String(n).toUpperCase(),url:kt(String(o))})}function eo({target:a,handlingStack:n},o,d){const f=Yt.get(a);if(!f)return;const c=f;c.state="start",c.startClocks=ae(),c.isAborted=!1,c.xhr=a,c.handlingStack=n;let u=!1;const{stop:s}=ve(a,"onreadystatechange",()=>{a.readyState===XMLHttpRequest.DONE&&p()}),p=()=>{if(_(),s(),u)return;u=!0;const g=f;g.state="complete",g.duration=vn(c.startClocks.timeStamp,oe()),g.status=a.status,d.notify(Un(g))},{stop:_}=Se(o,a,"loadend",p);d.notify(c)}function to({target:a}){const n=Yt.get(a);n&&(n.isAborted=!0)}let Vt;function tn(){return Vt||(Vt=io()),Vt}function io(){return new G(a=>{if(!window.fetch)return;const{stop:n}=ve(window,"fetch",o=>no(o,a),{computeHandlingStack:!0});return n})}function no({parameters:a,onPostCall:n,handlingStack:o},d){const[f,c]=a;let u=c&&c.method;u===void 0&&f instanceof Request&&(u=f.method);const s=u!==void 0?String(u).toUpperCase():"GET",p=f instanceof Request?f.url:kt(String(f)),_=ae(),g={state:"start",init:c,input:f,method:s,startClocks:_,url:p,handlingStack:o};d.notify(g),a[0]=g.input,a[1]=g.init,n(v=>ro(d,v,g))}function ro(a,n,o){const d=o;function f(c){d.state="resolve",Object.assign(d,c),a.notify(d)}n.then(D(c=>{f({response:c,responseType:c.type,status:c.status,isAborted:!1})}),D(c=>{var u,s;f({status:0,isAborted:((s=(u=d.init)===null||u===void 0?void 0:u.signal)===null||s===void 0?void 0:s.aborted)||c instanceof DOMException&&c.code===DOMException.ABORT_ERR,error:c})}))}let $t={};function so(a){const n=a.map(o=>($t[o]||($t[o]=oo(o)),$t[o]));return fi(...n)}function oo(a){return new G(n=>{const o=te[a];return te[a]=(...d)=>{o.apply(console,d);const f=rt("console error");Re(()=>{n.notify(ao(d,a,f))})},()=>{te[a]=o}})}function ao(a,n,o){const d=a.map(c=>lo(c)).join(" ");let f;if(n===O.error){const c=a.find(ce);f={stack:c?ye(ne(c)):void 0,fingerprint:Fi(c),causes:c?ki(c,"console"):void 0,startClocks:ae(),message:d,source:J.CONSOLE,handling:"handled",handlingStack:o,context:Bi(c)}}return{api:n,message:d,error:f,handlingStack:o}}function lo(a){return typeof a=="string"?re(a):ce(a)?Ci(ne(a)):me(re(a),void 0,2)}function fo(a){const n=zi(a)==="object";return n||M.error("Unsupported context:",a),n}function jt(a,n,o){const d={...a};for(const[f,{required:c,type:u}]of Object.entries(n))u==="string"&&f in d&&(d[f]=String(d[f])),c&&!(f in a)&&M.warn(`The property ${f} of ${o} is required; context will not be sent to the intake.`);return d}function ct(a="",{customerDataTracker:n,propertiesConfig:o={}}={}){let d={};const f=new G,c={getContext:()=>Oi(d),setContext:u=>{fo(u)?(d=re(jt(u,o,a)),n==null||n.updateCustomerData(d)):c.clearContext(),f.notify()},setContextProperty:(u,s)=>{d=re(jt({...d,[u]:s},o,a)),n==null||n.updateCustomerData(d),f.notify()},removeContextProperty:u=>{delete d[u],n==null||n.updateCustomerData(d),jt(d,o,a),f.notify()},clearContext:()=>{d={},n==null||n.resetCustomerData(),f.notify()},changeObservable:f};return c}const co="_dd_c",ho=[];function Kt(a,n,o,d){const f=uo(o,d);ho.push(Se(a,window,"storage",({key:_})=>{f===_&&u()})),n.changeObservable.subscribe(s);const c=Ae(p(),n.getContext());De(c)||n.setContext(c);function u(){n.setContext(p())}function s(){localStorage.setItem(f,JSON.stringify(n.getContext()))}function p(){const _=localStorage.getItem(f);return _?JSON.parse(_):{}}}function uo(a,n){return`${co}_${a}_${n}`}const po=3*ie,_o=16*ie,go=200;function mo(a=2){const n=new Map;let o=!1;function d(f=0){if(o||a===0)return;const c=a===2?po:_o;let u=f;n.forEach(s=>{u+=s.getBytesCount()}),u>c&&(yo(c),o=!0)}return{createDetachedTracker:()=>{const f=nn(()=>d(f.getBytesCount()));return f},getOrCreateTracker:f=>(n.has(f)||n.set(f,nn(d)),n.get(f)),setCompressionStatus:f=>{a===0&&(a=f,d())},getCompressionStatus:()=>a,stop:()=>{n.forEach(f=>f.stop()),n.clear()}}}function nn(a){let n=0;const{throttled:o,cancel:d}=ci(c=>{n=xt(me(c)),a()},go),f=()=>{d(),n=0};return{updateCustomerData:c=>{De(c)?f():o(c)},resetCustomerData:f,getBytesCount:()=>n,stop:()=>{d()}}}function yo(a){M.warn(`Customer data exceeds the recommended ${a/ie}KiB threshold. ${Ve} ${ti}/#customer-data-exceeds-the-recommended-threshold-warning`)}function vo(a,n,o){const d=a.getReader(),f=[];let c=0;u();function u(){d.read().then(D(p=>{if(p.done){s();return}f.push(p.value),c+=p.value.length,c>o.bytesLimit?s():u()}),D(p=>n(p)))}function s(){d.cancel().catch(le);let p,_;{let g;if(f.length===1)g=f[0];else{g=new Uint8Array(c);let v=0;f.forEach(U=>{g.set(U,v),v+=U.length})}p=g.slice(0,o.bytesLimit),_=g.length>o.bytesLimit}n(void 0,p,_)}}const So="datadog-synthetics-public-id",bo="datadog-synthetics-result-id",xo="datadog-synthetics-injects-rum";function rn(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||pe(xo))}function Uo(){const a=window._DATADOG_SYNTHETICS_PUBLIC_ID||pe(So);return typeof a=="string"?a:void 0}function Eo(){const a=window._DATADOG_SYNTHETICS_RESULT_ID||pe(bo);return typeof a=="string"?a:void 0}function ht(a,n,o){const d=o.getHandler(),f=Array.isArray(d)?d:[d];return sn[a]>=sn[o.getLevel()]&&f.includes(n)}const B={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},sn={[B.ok]:0,[B.debug]:1,[B.info]:2,[B.notice]:4,[B.warn]:5,[B.error]:6,[B.critical]:7,[B.alert]:8,[B.emerg]:9};function ut(a,{includeMessage:n=!1}={}){return{stack:a.stack,kind:a.type,message:n?a.message:void 0,causes:a.causes,fingerprint:a.fingerprint,handling:a.handling}}var wo=function(a,n,o,d){var f=arguments.length,c=f<3?n:d===null?d=Object.getOwnPropertyDescriptor(n,o):d,u;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")c=Reflect.decorate(a,n,o,d);else for(var s=a.length-1;s>=0;s--)(u=a[s])&&(c=(f<3?u(c):f>3?u(n,o,c):u(n,o))||c);return f>3&&c&&Object.defineProperty(n,o,c),c};const Ye={console:"console",http:"http",silent:"silent"},To=Object.keys(B);let Q=class{constructor(n,o,d,f=Ye.http,c=B.debug,u={}){this.handleLogStrategy=n,this.handlerType=f,this.level=c,this.contextManager=ct("logger",{customerDataTracker:o}),this.contextManager.setContext(u),d&&this.contextManager.setContextProperty("logger",{name:d})}logImplementation(n,o,d=B.info,f,c){const u=re(o);let s;if(f!=null){const p=Ii({stackTrace:ce(f)?ne(f):void 0,originalError:f,nonErrorPrefix:"Provided",source:J.LOGGER,handling:"handled",startClocks:ae()});s=Ae({error:ut(p,{includeMessage:!0})},u)}else s=u;this.handleLogStrategy({message:re(n),context:s,status:d},this,c)}log(n,o,d=B.info,f){let c;ht(d,Ye.http,this)&&(c=rt("log")),this.logImplementation(n,o,d,f,c)}setContext(n){this.contextManager.setContext(n)}getContext(){return this.contextManager.getContext()}setContextProperty(n,o){this.contextManager.setContextProperty(n,o)}removeContextProperty(n){this.contextManager.removeContextProperty(n)}clearContext(){this.contextManager.clearContext()}setHandler(n){this.handlerType=n}getHandler(){return this.handlerType}setLevel(n){this.level=n}getLevel(){return this.level}};wo([Tn],Q.prototype,"logImplementation",null),Q.prototype.ok=se(B.ok),Q.prototype.debug=se(B.debug),Q.prototype.info=se(B.info),Q.prototype.notice=se(B.notice),Q.prototype.warn=se(B.warn),Q.prototype.error=se(B.error),Q.prototype.critical=se(B.critical),Q.prototype.alert=se(B.alert),Q.prototype.emerg=se(B.emerg);function se(a){return function(n,o,d){let f;ht(a,Ye.http,this)&&(f=rt("log")),this.logImplementation(n,o,a,d,f)}}function Co(a,n,o){return{view:{referrer:document.referrer,url:window.location.href},context:a.getContext(),user:n.getContext(),account:o.getContext()}}const Ao=32*ie;function Io(a){a.usePciIntake===!0&&a.site&&a.site!=="datadoghq.com"&&M.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");const n=Tr(a),o=on(a.forwardConsoleLogs,Je(O),"Forward Console Logs"),d=on(a.forwardReports,Je(st),"Forward Reports");if(!(!n||!o||!d))return a.forwardErrorsToLogs&&!o.includes(O.error)&&o.push(O.error),{forwardErrorsToLogs:a.forwardErrorsToLogs!==!1,forwardConsoleLogs:o,forwardReports:d,requestErrorResponseLengthLimit:Ao,...n}}function on(a,n,o){if(a===void 0)return[];if(!(a==="all"||Array.isArray(a)&&a.every(d=>n.includes(d)))){M.error(`${o} should be "all" or an array with allowed values "${n.join(\'", "\')}"`);return}return a==="all"?n:cs(a)}function Fo(a){const n=Cr(a);return{forward_errors_to_logs:a.forwardErrorsToLogs,forward_console_logs:a.forwardConsoleLogs,forward_reports:a.forwardReports,use_pci_intake:a.usePciIntake,...n}}function Bo(a,n,o){const d=Ni();let f,c;const u=n.observable.subscribe(s);function s(){if(!c||!f||!n.isGranted())return;u.unsubscribe();const p=o(f,c);d.drain(p)}return{init(p){if(!p){M.error("Missing configuration");return}if(Ar(p.enableExperimentalFeatures),dt()&&(p=ko(p)),f=p,c){Li("DD_LOGS",p);return}const _=Io(p);_&&(c=_,tn().subscribe(le),n.tryToInit(_.trackingConsent),s())},get initConfiguration(){return f},getInternalContext:le,handleLog(p,_,g,v=a(),U=oe()){d.add(S=>S.handleLog(p,_,g,v,U))}}}function ko(a){return{...a,clientToken:"empty"}}const qt="logs";function Lo(a){const n=mo(),o=ct("global context",{customerDataTracker:n.getOrCreateTracker(2)}),d=ct("user",{customerDataTracker:n.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),f=ct("account",{customerDataTracker:n.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),c=or();function u(){return Co(o,d,f)}let s=Bo(u,c,(g,v)=>{g.storeContextsAcrossPages&&(Kt(v,o,qt,2),Kt(v,d,qt,1),Kt(v,f,qt,4));const U=a(g,v,u,c);return s=Do(g,U),U});const p={},_=new Q((...g)=>s.handleLog(...g),n.createDetachedTracker());return is({logger:_,init:D(g=>s.init(g)),setTrackingConsent:D(g=>{c.update(g),Ss({feature:"set-tracking-consent",tracking_consent:g})}),getGlobalContext:D(()=>o.getContext()),setGlobalContext:D(g=>o.setContext(g)),setGlobalContextProperty:D((g,v)=>o.setContextProperty(g,v)),removeGlobalContextProperty:D(g=>o.removeContextProperty(g)),clearGlobalContext:D(()=>o.clearContext()),createLogger:D((g,v={})=>(p[g]=new Q((...U)=>s.handleLog(...U),n.createDetachedTracker(),re(g),v.handler,v.level,re(v.context)),p[g])),getLogger:D(g=>p[g]),getInitConfiguration:D(()=>Oi(s.initConfiguration)),getInternalContext:D(g=>s.getInternalContext(g)),setUser:D(d.setContext),getUser:D(d.getContext),setUserProperty:D(d.setContextProperty),removeUserProperty:D(d.removeContextProperty),clearUser:D(d.clearContext),setAccount:D(f.setContext),getAccount:D(f.getContext),setAccountProperty:D(f.setContextProperty),removeAccountProperty:D(f.removeContextProperty),clearAccount:D(f.clearContext)})}function Do(a,n){return{init:o=>{Li("DD_LOGS",o)},initConfiguration:a,...n}}const Ro="logs";function Po(a,n){const o=As(a,Ro,d=>Oo(a,d),n);return{findTrackedSession:(d,f={returnInactive:!1})=>{const c=o.findSession(d,f);return c&&c.trackingType==="1"?{id:c.id,anonymousId:c.anonymousId}:void 0},expireObservable:o.expireObservable}}function zo(a){const o=an(a)==="1"?{}:void 0;return{findTrackedSession:()=>o,expireObservable:new G}}function an(a){return $e(a.sessionSampleRate)?"1":"0"}function Oo(a,n){const o=Mo(n)?n:an(a);return{trackingType:o,isTracked:o==="1"}}function Mo(a){return a==="0"||a==="1"}let dn=!1;function pt(a){const n=window;if(rn()){const d=o(n.DD_RUM_SYNTHETICS);return!d&&!dn&&(dn=!0,Hi("Logs sent before RUM is injected by the synthetics worker",{testId:Uo(),resultId:Eo()})),d}return o(n.DD_RUM);function o(d){if(d&&d.getInternalContext)return d.getInternalContext(a)}}function No(a,n,o,d,f){const c=To.concat(["custom"]),u={};c.forEach(s=>{u[s]=Js(s,n.eventRateLimiterThreshold,f)}),o.subscribe(0,({rawLogsEvent:s,messageContext:p=void 0,savedCommonContext:_=void 0,domainContext:g})=>{var v,U;const S=bn(s.date),E=a.findTrackedSession(S);if(!a.findTrackedSession(S,{returnInactive:!0}))return;const t=_||d();let r;!De(t.account)&&t.account.id&&(r=t.account),E&&E.anonymousId&&!t.user.anonymous_id&&(t.user.anonymous_id=E.anonymousId);const l=Ae({service:n.service,session_id:E?E.id:void 0,session:E?{id:E.id}:void 0,usr:De(t.user)?void 0:t.user,account:r,view:t.view},t.context,pt(S),s,p);((v=n.beforeSend)===null||v===void 0?void 0:v.call(n,l,g))===!1||l.origin!==J.AGENT&&((U=u[l.status])!==null&&U!==void 0?U:u.custom).isLimitReached()||o.notify(1,l)})}const Go={[O.log]:B.info,[O.debug]:B.debug,[O.info]:B.info,[O.warn]:B.warn,[O.error]:B.error};function Ho(a,n){const o=so(a.forwardConsoleLogs).subscribe(d=>{var f;const c={rawLogsEvent:{date:oe(),message:d.message,origin:J.CONSOLE,error:d.error&&ut(d.error),status:Go[d.api]},messageContext:(f=d.error)===null||f===void 0?void 0:f.context,domainContext:{handlingStack:d.handlingStack}};n.notify(0,c)});return{stop:()=>{o.unsubscribe()}}}function Yo(a,n){const o=rs(a,a.forwardReports).subscribe(d=>{let f=d.message,c;const u=d.originalError.type==="deprecation"?B.warn:B.error;u===B.error?c=ut(d):d.stack&&(f+=` Found in ${Zr(d.stack)}`),n.notify(0,{rawLogsEvent:{date:oe(),message:f,origin:J.REPORT,error:c,status:u}})});return{stop:()=>{o.unsubscribe()}}}function Vo(a,n){if(!a.forwardErrorsToLogs)return{stop:le};const o=Xs(a).subscribe(c=>{c.state==="complete"&&f("xhr",c)}),d=tn().subscribe(c=>{c.state==="resolve"&&f("fetch",c)});function f(c,u){!Er(u.url)&&(qo(u)||Vi(u.status))&&("xhr"in u?$o(u.xhr,a,s):u.response?Ko(u.response,a,s):u.error&&jo(u.error,a,s));function s(p){const _={isAborted:u.isAborted,handlingStack:u.handlingStack};n.notify(0,{rawLogsEvent:{message:`${Wo(c)} error ${u.method} ${u.url}`,date:u.startClocks.timeStamp,error:{stack:p||"Failed to load",handling:void 0},http:{method:u.method,status_code:u.status,url:u.url},status:B.error,origin:J.NETWORK},domainContext:_})}}return{stop:()=>{o.unsubscribe(),d.unsubscribe()}}}function $o(a,n,o){typeof a.response=="string"?o(Wt(a.response,n)):o(a.response)}function jo(a,n,o){o(Wt(ye(ne(a)),n))}function Ko(a,n,o){const d=ks(a);!d||!d.body?o():window.TextDecoder?Jo(d.body,n.requestErrorResponseLengthLimit,(f,c)=>{o(f?`Unable to retrieve response: ${f}`:c)}):d.text().then(D(f=>o(Wt(f,n))),D(f=>o(`Unable to retrieve response: ${f}`)))}function qo(a){return a.status===0&&a.responseType!=="opaque"}function Wt(a,n){return a.length>n.requestErrorResponseLengthLimit?`${a.substring(0,n.requestErrorResponseLengthLimit)}...`:a}function Wo(a){return a==="xhr"?"XHR":"Fetch"}function Jo(a,n,o){vo(a,(d,f,c)=>{if(d)o(d);else{let u=new TextDecoder().decode(f);c&&(u+="..."),o(void 0,u)}},{bytesLimit:n,collectStreamBody:!0})}function Xo(a,n){if(!a.forwardErrorsToLogs)return{stop:le};const o=new G,{stop:d}=Qr(o),f=o.subscribe(c=>{n.notify(0,{rawLogsEvent:{message:c.message,date:c.startClocks.timeStamp,error:ut(c),origin:J.SOURCE,status:B.error},messageContext:c.context})});return{stop:()=>{d(),f.unsubscribe()}}}const Zo=Ws;function Qo(a){function n(o,d,f,c,u){const s=Ae(d.getContext(),o.context);if(ht(o.status,Ye.console,d)&&ta(o,s),ht(o.status,Ye.http,d)){const p={rawLogsEvent:{date:u||oe(),message:o.message,status:o.status,origin:J.LOGGER},messageContext:s,savedCommonContext:c};f&&(p.domainContext={handlingStack:f}),a.notify(0,p)}}return{handleLog:n}}const ea={[B.ok]:O.debug,[B.debug]:O.debug,[B.info]:O.info,[B.notice]:O.info,[B.warn]:O.warn,[B.error]:O.error,[B.critical]:O.error,[B.alert]:O.error,[B.emerg]:O.error};function ta({status:a,message:n},o){he[ea[a]].call(te,n,o)}function ia(a,n,o,d,f){const c=en(a,{endpoint:a.logsEndpointBuilder,encoder:ft()},a.replica&&{endpoint:a.replica.logsEndpointBuilder,encoder:ft()},o,d,f.expireObservable);return n.subscribe(1,u=>{c.add(u)}),c}function na(a){const n=Gt();a.subscribe(1,o=>{n.send("log",o)})}function ra(a){return{get:n=>{const o=a.findTrackedSession(n);if(o)return{session_id:o.id}}}}function sa(a){return n=>{a.notify(0,{rawLogsEvent:{message:n.message,date:n.startClocks.timeStamp,origin:J.AGENT,status:B.error}}),Hi("Error reported to customer",{"error.message":n.message})}}function oa(a,n,o,d,f){const c=_s("browser-logs-sdk",n);c.setContextProvider(()=>{var s,p,_,g,v,U;return{application:{id:(s=pt())===null||s===void 0?void 0:s.application_id},session:{id:(p=f.findTrackedSession())===null||p===void 0?void 0:p.id},view:{id:(g=(_=pt())===null||_===void 0?void 0:_.view)===null||g===void 0?void 0:g.id},action:{id:(U=(v=pt())===null||v===void 0?void 0:v.user_action)===null||U===void 0?void 0:U.id}}});const u=[];if(dt()){const s=Gt(),p=c.observable.subscribe(_=>s.send("internal_telemetry",_));u.push(()=>p.unsubscribe())}else{const s=en(n,{endpoint:n.rumEndpointBuilder,encoder:ft()},n.replica&&{endpoint:n.replica.rumEndpointBuilder,encoder:ft()},o,d,f.expireObservable);u.push(()=>s.stop());const p=c.observable.subscribe(_=>s.add(_,ys(n)));u.push(()=>p.unsubscribe())}return ms(),vs(Fo(a)),{telemetry:c,stop:()=>{u.forEach(s=>s())}}}function aa(a,n,o,d){const f=new Zo,c=[];f.subscribe(1,U=>Pi("logs",U));const u=sa(f),s=$s(n),p=n.sessionStoreStrategyType&&!dt()&&!rn()?Po(n,d):zo(n),{stop:_}=oa(a,n,u,s,p);c.push(()=>_()),Vo(n,f),Xo(n,f),Ho(n,f),Yo(n,f);const{handleLog:g}=Qo(f);if(No(p,n,f,o,u),dt())na(f);else{const{stop:U}=ia(n,f,u,s,p);c.push(()=>U())}const v=ra(p);return{handleLog:g,getInternalContext:v.get,stop:()=>{c.forEach(U=>U())}}}const Fe=Lo(aa);ns(de(),"DD_LOGS",Fe);const I=class I{constructor(n){this.listenerMap=new Map,I.options=n,this.isLoggingOn=n.LOG_TO_DATADOG,this.eventTarget=new EventTarget,this.isLoggingOn&&Fe.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!1,sessionSampleRate:100});const o="bb_logger_mac_uuid";let d=localStorage.getItem(o);d||(d=crypto.randomUUID(),localStorage.setItem(o,d)),I.tracking.mac=d,I.tracking.dev=`${n.platform}_${n.browserName}`,I.beatHandle||(I.options&&k(I.options,"Logger")&&console.log("[Logger] Starting tracking beat"),I.beatHandle=window.setInterval(I.flushTracking,15e3))}static setMessagePort(n){this.messagePort=n}static getMessagePort(){return this.messagePort}setLoggingOn(n){this.isLoggingOn=n}addEventListener(n,o){const d=f=>o(f);this.listenerMap.set(o,{eventName:n,wrappedListener:d}),this.eventTarget.addEventListener(n,d)}removeEventListener(n,o){const d=this.listenerMap.get(o);d&&d.eventName===n&&(this.eventTarget.removeEventListener(n,d.wrappedListener),this.listenerMap.delete(o))}removeAllEventListeners(){for(const[n,{eventName:o,wrappedListener:d}]of this.listenerMap)this.eventTarget.removeEventListener(o,d);this.listenerMap.clear()}setAttributes(n){I.processAttributes(n);for(const o in n)Fe.logger.setContextProperty(o,n[o])}info(n,o){n==="didClickAd"&&this.emit("mediaSessionDidRegisterClick",{url:(o==null?void 0:o.url)||""}),n==="didToggleGlobalAugmentationDrawing"&&this.emit("mediaSessionDidUpdateGlobalAugmentationState",{isGlobalAugmentationEnabled:(o==null?void 0:o.isEnabled)||!0}),n==="didStartDrawingAugmentationMedia"&&this.emit("mediaSessionDidBeginShotRendering",o),n==="didEndDrawingAugmentationMedia"&&this.emit("mediaSessionDidEndShotRendering",o),n==="didRegisterShot"&&this.emit("mediaSessionDidRegisterShot",o),o&&I.processAttributes(o),this.isLoggingOn&&(Fe.logger.info(n,o),I.options&&k(I.options,"Logger")&&console.log("[Logger] Sending info: ",n))}error(n,o){o&&I.processAttributes(o),this.isLoggingOn&&(Fe.logger.error(n,o),I.tracking.err_time=Date.now().toFixed(0),I.tracking.err_desc=n+(o?` - ${JSON.stringify(o)}`:""),I.options&&k(I.options,"Logger")&&console.log("[Logger] Sending error: ",n))}warn(n,o){o&&I.processAttributes(o),this.isLoggingOn&&(Fe.logger.warn(n,o),I.options&&k(I.options,"Logger")&&console.log("[Logger] Sending warn: ",n))}handleMessageFromWorker(n){n.actionType==="INFO"?this.info(n.message,n.attributes):n.actionType==="ERROR"?this.error(n.message,n.attributes):n.actionType==="WARN"?this.warn(n.message,n.attributes):n.actionType==="SET_ATTRIBUTES"&&n.attributes&&this.setAttributes(n.attributes)}static setAttributes(n){if(!I.messagePort){console.error("[Logger] messagePort is not set! Cannot send attributes.");return}try{I.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:n})}catch(o){console.error("[Logger] Error posting message:",o)}}static info(n,o){I.messagePort.postMessage({type:"LOG",actionType:"INFO",message:n,attributes:o})}static error(n,o){I.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:n,attributes:o})}static warn(n,o){I.messagePort.postMessage({type:"LOG",actionType:"WARN",message:n,attributes:o})}static processAttributes(n){if(n.player_version&&(I.tracking.sdk=n.player_version),n.media_id&&(I.tracking.gid=n.media_id),n.game_id&&(I.tracking.buc=n.game_id),n.bb_session_id&&(I.tracking.sid=n.bb_session_id,I.options&&k(I.options,"Logger")&&console.log("[Logger] Setting bb_session_id:",I.tracking.sid)),n.last_timecode){const d=$.fromStr(n.last_timecode);I.tracking.tc=d.print(),I.lastTimecodeMillis=d.totalMilliseconds(59.94),I.lastTimecodeMillis&&I.lastZipMillis&&(I.tracking.cache=(I.lastZipMillis-I.lastTimecodeMillis).toFixed(0))}n.last_offset&&(I.tracking.off=n.last_offset),n.last_loading_zip&&(I.tracking.zip=n.last_loading_zip+".zip",I.lastZipMillis=$.fromStr(n.last_loading_zip).totalMilliseconds(59.94),I.lastTimecodeMillis&&I.lastZipMillis&&(I.tracking.cache=(I.lastZipMillis-I.lastTimecodeMillis).toFixed(0))),n.last_rendered_frame&&(I.tracking.aug_time=Date.now().toFixed(0)),n.asset&&(I.tracking.asset=n.asset)}static objectToQuery(n){return Object.entries(n).filter(([o,d])=>d!==0&&d!=="").map(([o,d])=>`${encodeURIComponent(o)}=${encodeURIComponent(String(d))}`).join("&")}emit(n,o){const d=new CustomEvent(n,{detail:o});this.eventTarget.dispatchEvent(d)}};I.tracking={start:Date.now().toFixed(0),dev:"",sdk:"",mac:"",gid:"",sid:"",off:"",zip:"",aug_time:"",err_time:"",err_desc:"",tc:"",asset:"",cache:"",buc:""},I.lastTimecodeMillis=0,I.lastZipMillis=0,I.flushTracking=()=>{const n=Date.now().toFixed(0);I.tracking.now=n;const d=`https://dwu3k7rrxk5s3.cloudfront.net/metrics/1.gif?${I.objectToQuery(I.tracking)}`;I.options&&k(I.options,"Logger")&&console.log("[Logger] Flushing tracking data:",d),fetch(d,{method:"GET",mode:"no-cors",keepalive:!0,headers:{"X-Platform":"Web"}}).catch(()=>{}),I.tracking.err_desc="",I.tracking.err_time=""};let z=I;class Jt{constructor(n,o,d){this.videoDecoder=null,this.reservedVideoDecoder=null,this.videoDecoderNeedsKeyFrame=!1,this.reservedVideoDecoderNeedsKeyFrame=!1,this.currentTimecode="",this.fps=0,this.unchunkedJobs=[],this.jobChunking=null,this.jobsQueue=[],this.chunksQueue=[],this.chunksForDecodingFrames=[],this.processedMetadata=[],this.lastJobEndTimecode=0,this.lastProcessedFrameTimecode=0,this.storedFrames=[],this.videoDecoderConfigured=!1,this.reservedVideoDecoderConfigured=!1,this.timecodeErrorCount=0,this.decoderStopped=!1,this.chunkCount=0,this.chunkingTimeSum=0,this.avgChunkingTime=0,this.decodingFrameCount=0,this.decodingTimeSum=0,this.avgDecodingTime=0,this.lastPerformanceCheck=performance.now(),this.loggerTimeoutStart=0,this.loggerTimeout=1e4,this.lastStatusUpdate=0,this.STATUS_UPDATE_INTERVAL=200,this.lastDecoderStatus={healthy:!0,issue:""},this.lastTimecodeStatus={consistent:!0,errorCount:0},this.addJob=(f,c)=>{if(this.decoderStopped)return;const{alphaMp4:u,metadataList:s}=this.parseZipAndMetadata(c,f);if(!u){this.options&&k(this.options,"Decoder")&&console.log("[Decoder] No alpha.mp4 found, no decoding needed.");return}const p={timeCode:f,alphaMp4:u,metadata:s,chunks:[],totalFrameCount:s.length,framesProcessed:0,framesSentToDecoder:0,useReserveDecoder:s.length<3,chunkingTime:0};this.jobChunking?this.unchunkedJobs.push(p):(this.jobChunking=p,this.chunkJob(p)),this.options&&k(this.options,"Decoder")&&console.log("[Decoder] Added job:",p)},this.clearOldJobsAndChunks=f=>{const u=$.fromStr(this.currentTimecode).totalMilliseconds(this.fps)-f;this.unchunkedJobs=this.unchunkedJobs.filter(s=>$.fromStr(s.timeCode).totalMilliseconds(this.fps)>u),this.jobsQueue=this.jobsQueue.filter(s=>$.fromStr(s.timeCode).totalMilliseconds(this.fps)>u),this.chunksQueue=this.chunksQueue.filter(s=>$.fromStr(s.timeCode).totalMilliseconds(this.fps)>u)},this.clearAllJobsAndChunks=()=>{this.unchunkedJobs=[],this.jobsQueue=[],this.chunksQueue=[]},this.updateCurrentTimecode=(f,c)=>{if(!this.decoderStopped&&this.options){if(this.fps=59.94,this.currentTimecode){const u=$.fromStr(f).totalMilliseconds(this.fps),s=$.fromStr(this.currentTimecode).totalMilliseconds(this.fps);if(u<s||u>s+this.options.DECODER_LEAD_TIME_MILLIS){this.timecodeErrorCount++,this.updateStatus();const p=performance.now();if(u<s&&(p-this.loggerTimeoutStart>this.loggerTimeout&&(this.loggerTimeoutStart=p,z.error("[Decoder] Timecode is going backwards")),this.options&&k(this.options,"Errors")&&console.error("[Decoder] Timecode is going backwards")),u>s+this.options.DECODER_LEAD_TIME_MILLIS&&(p-this.loggerTimeoutStart>this.loggerTimeout&&(this.loggerTimeoutStart=p,z.error("[Decoder] Timecode is too far ahead")),this.options&&k(this.options,"Errors")&&console.error("[Decoder] Timecode is too far ahead")),this.timecodeErrorCount>5&&!this.options.BURNED_TIMECODES_MODE&&this.restartDecoder(),!this.options.BURNED_TIMECODES_MODE)return}}this.timecodeErrorCount=0,this.currentTimecode=f,this.clearOldJobsAndChunks(2100),this.decodeUpcomingChunks(),this.updateStatus()}},this.setupMP4Box=(f=!1)=>{const c=cn.createFile();return c.onError=u=>{z.error("[Decoder] MP4 parsing error",u),this.options&&k(this.options,"Errors")&&console.error("[Decoder] MP4 parsing error:",u)},c.onReady=u=>{const s=u.tracks.find(p=>p.type==="video");if(s){if(!(f?this.reservedVideoDecoderConfigured:this.videoDecoderConfigured)){this.options&&k(this.options,"Decoder")&&console.error("[Decoder] Starting a new VideoDecoder");let _;f?(this.reservedVideoDecoder=new VideoDecoder({output:this.onFrameDecoded,error:this.onDecoderError}),_=this.reservedVideoDecoder):(this.videoDecoder=new VideoDecoder({output:this.onFrameDecoded,error:this.onDecoderError}),_=this.videoDecoder),_.configure({codec:s.codec,codedWidth:s.video.width,codedHeight:s.video.height,description:this.getDescription(c.getTrackById(s.id)),hardwareAcceleration:"prefer-hardware",optimizeForLatency:!0}),f?(this.reservedVideoDecoderConfigured=!0,this.reservedVideoDecoderNeedsKeyFrame=!0):(this.videoDecoderConfigured=!0,this.videoDecoderNeedsKeyFrame=!0,this.updateStatus())}c.setExtractionOptions(s.id),c.start()}},c.onSamples=async(u,s,p)=>{var U;const _=[];let g=0,v=0;if(this.options&&k(this.options,"Decoder")&&console.log("[Decoder] onSamples for job",(U=this.jobChunking)==null?void 0:U.timeCode,"samples=",p.length),this.options.browserName==="Firefox"){const S=p.map(e=>e.cts).sort((e,t)=>e-t);g=200-S[0],v=S[S.length-1]+g}for(const S of p){const E=this.options.browserName==="Firefox"?S.cts+this.lastJobEndTimecode+g:S.cts,e=new EncodedVideoChunk({type:S.is_sync?"key":"delta",timestamp:E,data:new Uint8Array(S.data)});_.push(e)}this.storeChunks(_),this.options.browserName==="Firefox"&&(this.lastJobEndTimecode+=v)},c},this.chunkJob=async f=>{f.chunkingTime=performance.now(),this.mp4boxfile=this.setupMP4Box(f.useReserveDecoder);const u=await new Blob([f.alphaMp4],{type:"video/mp4"}).arrayBuffer();u.fileStart=0,this.mp4boxfile.appendBuffer(u)},this.storeChunks=f=>{var s;this.options&&k(this.options,"Decoder")&&console.log("[Decoder] Storing chunks:",f);const c=this.jobChunking;if(f.length!==c.metadata.length){const p=c.metadata.filter(_=>_.placeholders||_.LED&&_.LED.cubePlaceholders);p.length==f.length&&(c.metadata=p)}if(this.options&&k(this.options,"Errors")&&f.length!==c.metadata.length){const p=c.metadata.findIndex((_,g)=>!f[g]);console.error("[Decoder] MISMATCH: first undefined chunk at index",p)}if((s=this.options.debug)!=null&&s.trackPerformance&&(c.chunkingTime=performance.now()-c.chunkingTime,this.chunkCount++,this.chunkingTimeSum+=c.chunkingTime,this.avgChunkingTime=this.chunkingTimeSum/this.chunkCount),this.unchunkedJobs.length>0){const p=this.unchunkedJobs.shift();this.jobChunking=p,this.chunkJob(p)}else this.jobChunking=null;const u=c==null?void 0:c.metadata.map((p,_)=>({timeCode:p.timecode,chunk:f[_],metadata:p,job:c,cancelled:!1,decodingTime:0}));c.chunks=u,this.chunksQueue.push(...u),this.jobsQueue.push(c),this.options&&k(this.options,"Decoder")&&console.log("[Decoder] Jobs Queue:",this.jobsQueue),this.options&&k(this.options,"Decoder")&&console.log("[Decoder] Chunks Queue:",this.chunksQueue)},this.onFrameDecoded=f=>{var p;let c=0;if(this.options.browserName==="Firefox"){c=this.lastProcessedFrameTimecode+200;const _=f.timestamp;if(_!==c){if(this.options&&k(this.options,"Decoder")&&console.log("[Decoder] Frame out of order, storing frame:",_),this.storedFrames.push(f),this.storedFrames.sort((g,v)=>g.timestamp-v.timestamp),this.storedFrames[0].timestamp===c){const g=this.storedFrames.shift();g&&this.onFrameDecoded(g)}this.storedFrames.sort((g,v)=>g.timestamp-v.timestamp);return}this.lastProcessedFrameTimecode=_}this.options&&k(this.options,"Decoder")&&console.log("[Decoder] Frame decoded:",f);const u=this.chunksForDecodingFrames.shift();if(!u){z.error("[Decoder] No current chunk for a processed frame"),this.options&&k(this.options,"Errors")&&console.error("[Decoder] No current chunk for a processed frame");return}if(u.cancelled||this.decoderStopped){this.options&&k(this.options,"Decoder")&&console.log("[Decoder] Skipping cancelled chunk:",u.timeCode),f.close();return}const s=u.metadata;if((p=this.options.debug)!=null&&p.trackPerformance){const _=performance.now();u.decodingTime=_-u.decodingTime,this.decodingFrameCount++,this.decodingTimeSum+=u.decodingTime,this.avgDecodingTime=this.decodingTimeSum/this.decodingFrameCount,_-this.lastPerformanceCheck>=this.options.PERFORMANCE_TRACKING_INTERVAL&&(this.trackPerformance(),this.lastPerformanceCheck=_)}if(u.job.framesProcessed++,s.alphaMask=f,this.processedMetadata.push(s),z.setAttributes({last_decoded_frame:s.timecode}),(this.processedMetadata.length>=this.options.DECODER_FRAME_BATCH_SIZE||u.job.framesProcessed>=u.job.totalFrameCount)&&(this.postBatchToRenderer(this.processedMetadata),this.processedMetadata.forEach(_=>_.alphaMask.close()),this.processedMetadata=[]),this.options.browserName==="Firefox"&&this.storedFrames.length>0){const _=(c+200)%24200||400;if(this.storedFrames[0].timestamp===_){const g=this.storedFrames.shift();g&&this.onFrameDecoded(g)}}},this.onDecoderError=f=>{var s,p;z.error("[Decoder] VideoDecoder error",f),this.options&&k(this.options,"Errors")&&console.error("[Decoder] VideoDecoder error:",f),this.videoDecoderConfigured=!1,this.reservedVideoDecoderConfigured=!1,this.videoDecoderNeedsKeyFrame=!0,this.reservedVideoDecoderNeedsKeyFrame=!0,this.updateStatus();const c=this.chunksForDecodingFrames.shift();if(!c){z.error("[Decoder] No broken chunk for an error"),this.options&&k(this.options,"Errors")&&console.error("[Decoder] No broken chunk for an error");return}const u=c.job;u&&u.chunks.forEach(_=>_.cancelled=!0),(s=this.reservedVideoDecoder)==null||s.close(),(p=this.videoDecoder)==null||p.close()},this.parseZipAndMetadata=(f,c)=>{var e;const u=pn.parse(f),s=((e=u["alpha.mp4"])==null?void 0:e.buffer)||null,p=Object.keys(u).filter(t=>t.endsWith(".json")).sort(this.numericFileComparator).map(t=>{const r=JSON.parse(new TextDecoder().decode(u[t]));return r.timecode=$.toStr($.fromMetadata(r)),r}),_=p.length;let g=120;const[v,U,S]=c.split("_").map(Number);U%10===0&&S===0?g=120:S===0&&(g=116),_!==g&&(z.error("[Decoder] Metadata count mismatch",{expected:g,actual:_,timecode:c}),this.options&&k(this.options,"Errors")&&console.error("[Decoder] Metadata count mismatch:",{expected:g,actual:_,timecode:c}));const E=p;return this.options&&k(this.options,"Decoder")&&console.log("[Decoder] ZIP",c,"metadataFull=",p.length,"metadataFiltered=",E.length),{alphaMp4:s,metadataList:E}},this.numericFileComparator=(f,c)=>{const u=/^(\\d{2})_(\\d{2})_(\\d{2})_(\\d{2})(?:\\.(\\d+))?\\.(.+)$/,s=f.match(u),p=c.match(u);if(!s||!p)return 0;const[,_,g,v,U,S="0",E]=s,[,e,t,r,l,h="0",m]=p;return parseInt(_,10)-parseInt(e,10)||parseInt(g,10)-parseInt(t,10)||parseInt(v,10)-parseInt(r,10)||parseInt(U,10)-parseInt(l,10)||parseInt(S,10)-parseInt(h,10)||E.localeCompare(m)},this.getDescription=f=>{for(const c of f.mdia.minf.stbl.stsd.entries){const u=c.avcC||c.hvcC||c.vpcC||c.av1C;if(u){const s=new yt.DataStream(void 0,0,yt.DataStream.BIG_ENDIAN);return u.write(s),new Uint8Array(s.buffer,8)}}return null},this.trackPerformance=()=>{const f=this.getAvgChunkingTime(),c=this.getAvgDecodingTime();fa([{metric:"Chunking time",value:f},{metric:"Decoding time",value:c}])},this.postBatchToRenderer=n,this.restartDecoder=o,this.options=d,this.mp4boxfile=this.setupMP4Box()}isStopped(){return this.decoderStopped}updateStatus(){const n=performance.now();if(n-this.lastStatusUpdate<this.STATUS_UPDATE_INTERVAL)return;const o={healthy:this.videoDecoderConfigured&&!this.decoderStopped,issue:this.videoDecoderConfigured?this.decoderStopped?"Stopped":"":"Not configured"},d={consistent:this.timecodeErrorCount<=3,errorCount:this.timecodeErrorCount};(JSON.stringify(o)!==JSON.stringify(this.lastDecoderStatus)||JSON.stringify(d)!==JSON.stringify(this.lastTimecodeStatus))&&(z.setAttributes({decoder_status:o,timecode_status:d}),this.lastDecoderStatus=o,this.lastTimecodeStatus=d,this.lastStatusUpdate=n)}decodeUpcomingChunks(){const n=$.fromStr(this.currentTimecode).totalMilliseconds(this.fps),o=n+this.options.DECODER_LEAD_TIME_MILLIS,d=this.chunksQueue.filter(c=>{const u=$.fromStr(c.timeCode).totalMilliseconds(this.fps);return u>=n&&u<=o&&!c.decoded});d.sort((c,u)=>{const s=$.fromStr(c.timeCode).totalMilliseconds(this.fps),p=$.fromStr(u.timeCode).totalMilliseconds(this.fps);return s-p});const f=d.slice(0,this.options.DECODER_FRAME_BATCH_SIZE);for(const c of f){if(c.cancelled){this.options&&k(this.options,"Decoder")&&console.log("[Decoder] Skipping cancelled chunk:",c.timeCode);continue}const u=c.job.useReserveDecoder?this.reservedVideoDecoder:this.videoDecoder;if(!u||u.state==="closed"){z.error("[Decoder] No VideoDecoder available"),this.options&&k(this.options,"Errors")&&console.error("[Decoder] No VideoDecoder available");continue}if((c.job.useReserveDecoder?this.reservedVideoDecoderNeedsKeyFrame:this.videoDecoderNeedsKeyFrame)&&c.chunk.type==="delta"){z.error("[Decoder] Decoder needs a key frame, skipping delta chunk",{chunkTimeCode:c.timeCode}),this.options&&k(this.options,"Errors")&&console.error("[Decoder] Decoder needs a key frame, skipping delta chunk:",c.timeCode),c.decoded=!0;continue}try{this.chunksForDecodingFrames.push(c),c.chunk.type==="key"&&(c.job.useReserveDecoder?this.reservedVideoDecoderNeedsKeyFrame=!1:this.videoDecoderNeedsKeyFrame=!1),c.decodingTime=performance.now(),u.decode(c.chunk)}catch(p){z.error("[Decoder] Error decoding chunk",p),this.options&&k(this.options,"Errors")&&console.error("[Decoder] Error decoding chunk:",p),this.videoDecoderConfigured=!1,this.reservedVideoDecoderConfigured=!1,this.videoDecoderNeedsKeyFrame=!0,this.updateStatus(),this.reservedVideoDecoderNeedsKeyFrame=!0,c.job.chunks.forEach(g=>g.cancelled=!0),u.close()}finally{if(c.decoded=!0,c.job.framesSentToDecoder++,c.job.framesSentToDecoder>=c.job.totalFrameCount){u.flush(),c.job.useReserveDecoder;continue}}}}getAvgChunkingTime(){var n;if((n=this.options.debug)!=null&&n.trackPerformance){const o=this.avgChunkingTime;return this.chunkCount=0,this.chunkingTimeSum=0,this.avgChunkingTime=0,o}return 0}getAvgDecodingTime(){var n;if((n=this.options.debug)!=null&&n.trackPerformance){const o=this.avgDecodingTime;return this.decodingFrameCount=0,this.decodingTimeSum=0,this.avgDecodingTime=0,o}return 0}stop(){var n,o;this.decoderStopped=!0,this.updateStatus(),this.clearAllJobsAndChunks();try{(n=this.videoDecoder)==null||n.close()}catch(d){z.error("[Decoder] Error closing main VideoDecoder",d),this.options&&k(this.options,"Errors")&&console.error("[Decoder] Error closing main VideoDecoder:",d)}try{(o=this.reservedVideoDecoder)==null||o.close()}catch(d){z.error("[Decoder] Error closing reserved VideoDecoder",d),this.options&&k(this.options,"Errors")&&console.error("[Decoder] Error closing reserved VideoDecoder:",d)}}}let ln=null,_t=null,X,H;self.onmessage=async a=>{const{data:n}=a;if(n.type==="SET_LOGGER_PORT"&&z.setMessagePort(n.port),n.type==="SET_DOWNLOADER_PORT"&&(ln=n.port,ln.onmessage=da),n.type==="SET_RENDERER_PORT"&&(_t=n.port,_t.onmessage=la),n.type==="SET_OPTIONS"&&(H=n.options,z.setMessagePort(self),X=new Jt(Xt,gt,H)),n.type==="STOP_WORKER"){X&&X.stop();return}if(n.type==="RESTART_WORKER"){if(!H)return;gt();return}};function da(a){const{data:n}=a;if(n.type==="DECODER_INPUT"){if(!X||X.isStopped())return;const{timeCode:o,arrayBuffer:d}=n;H&&k(H,"Decoder")&&console.log("[DecoderWorker] Received ArrayBuffer from Downloader, timeCode =",o),X.addJob(o,d)}}function la(a){const{data:n}=a;if(n.type==="DECODER_REQUEST"){if(!X||X.isStopped())return;const{timeCode:o,fps:d}=n;H&&k(H,"Decoder")&&console.log("[DecoderWorker] Received TimeCode request from Renderer, timeCode =",o),X.updateCurrentTimecode(o,d)}}function gt(){H&&(X.stop(),X=new Jt(Xt,gt,H))}function Xt(a){if(!_t)return;H&&k(H,"Decoder")&&console.log(`[DecoderWorker] Posting a batch of ${a.length} frames to Renderer`);const n=a.map(o=>o.alphaMask).filter(o=>o!==void 0);try{const o=new Set(n);_t.postMessage({type:"RENDERER_INPUT",batch:a},[...o]),n.forEach(d=>d.close())}catch(o){z.error("[DecoderWorker] Error posting batch to Renderer",{error:o}),H&&k(H,"Errors")&&console.error("[DecoderWorker] Error posting batch to Renderer:",o),n.forEach(d=>d.close());return}}function fa(a){const n={type:"TRACK_PERFORMANCE",data:a};self.postMessage(n)}self.onunhandledrejection=a=>{z.error("[DecoderWorker] Unhandled rejection",{error:a.reason}),H&&(k(H,"Errors")&&console.error("[DecoderWorker] Unhandled rejection:",a.reason),X.stop(),X=new Jt(Xt,gt,H),a.preventDefault())},self.onerror=a=>{z.error("[DecoderWorker] Unhandled error",{error:a}),H&&(k(H,"Errors")&&console.error("[DecoderWorker] Unhandled error:",a),a instanceof Event&&a.preventDefault())}})();\n',$t=typeof self<"u"&&self.Blob&&new Blob([zt],{type:"text/javascript;charset=utf-8"});function an(t){let e;try{if(e=$t&&(self.URL||self.webkitURL).createObjectURL($t),!e)throw"";const r=new Worker(e,{name:t==null?void 0:t.name});return r.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),r}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(zt),{name:t==null?void 0:t.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}const Gt=`(function(){"use strict";const g=(t,e)=>e==="Errors"?!0:!t.debug||!t.debug.on?!1:t.debug[\`log\${e}\`],P={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},H=console,ie={};Object.keys(P).forEach(t=>{ie[t]=H[t]});const ye="Datadog Browser SDK:",O={debug:ie.debug.bind(H,ye),log:ie.log.bind(H,ye),info:ie.info.bind(H,ye),warn:ie.warn.bind(H,ye),error:ie.error.bind(H,ye)},Tt="https://docs.datadoghq.com",Zt=\`\${Tt}/real_user_monitoring/browser/troubleshooting\`,Ne="More details:";function Jt(t,e){return(...s)=>{try{return t(...s)}catch(r){O.error(e,r)}}}function ke(t){return t!==0&&Math.random()*100<=t}function ms(t){return ps(t)&&t>=0&&t<=100}function ps(t){return typeof t=="number"}const xe=1e3,oe=60*xe,Qt=60*oe,gs=365*(24*Qt);function Se(){return new Date().getTime()}function J(){return Se()}function Ge(){return performance.now()}function Q(){return{relative:Ge(),timeStamp:J()}}function Es(){return{relative:0,timeStamp:er()}}function Ts(t,e){return e-t}function As(t,e){return t+e}function _s(t){return t-er()}let At;function er(){return At===void 0&&(At=performance.timing.navigationStart),At}const z=1024,tr=1024*z,bs=/[^\\u0000-\\u007F]/;function _t(t){return bs.test(t)?window.TextEncoder!==void 0?new TextEncoder().encode(t).length:new Blob([t]).size:t.length}function Rs(t){return{...t}}function rr(t,e){return Object.keys(t).some(s=>t[s]===e)}function Le(t){return Object.keys(t).length===0}function ee(){if(typeof globalThis=="object")return globalThis;Object.defineProperty(Object.prototype,"_dd_temp_",{get(){return this},configurable:!0});let t=_dd_temp_;return delete Object.prototype._dd_temp_,typeof t!="object"&&(typeof self=="object"?t=self:typeof window=="object"?t=window:t={}),t}function pe(t,e){const s=ee();let r;return s.Zone&&typeof s.Zone.__symbol__=="function"&&(r=t[s.Zone.__symbol__(e)]),r||(r=t[e]),r}let Xe,sr=!1;function vs(t){Xe=t}function ys(t){sr=t}function xs(t,e,s){const r=s.value;s.value=function(...n){return(Xe?y(r):r).apply(this,n)}}function y(t){return function(){return De(t,this,arguments)}}function De(t,e,s){try{return t.apply(e,s)}catch(r){Ss(r)}}function Ss(t){if(bt(t),Xe)try{Xe(t)}catch(e){bt(e)}}function bt(...t){sr&&O.error("[MONITOR]",...t)}function we(t,e){return pe(ee(),"setTimeout")(y(t),e)}function nr(t){pe(ee(),"clearTimeout")(t)}function Rt(t,e){return pe(ee(),"setInterval")(y(t),e)}function ir(t){pe(ee(),"clearInterval")(t)}class B{constructor(e){this.onFirstSubscribe=e,this.observers=[]}subscribe(e){return this.observers.push(e),this.observers.length===1&&this.onFirstSubscribe&&(this.onLastUnsubscribe=this.onFirstSubscribe(this)||void 0),{unsubscribe:()=>{this.observers=this.observers.filter(s=>e!==s),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}}notify(e){this.observers.forEach(s=>s(e))}}function or(...t){return new B(e=>{const s=t.map(r=>r.subscribe(n=>e.notify(n)));return()=>s.forEach(r=>r.unsubscribe())})}function ar(t,e,s){let r=!1,n,o;return{throttled:(...i)=>{if(r){n=i;return}t(...i),r=!0,o=we(()=>{n&&t(...n),r=!1,n=void 0},e)},cancel:()=>{nr(o),r=!1,n=void 0}}}function te(){}function re(t){return t?(parseInt(t,10)^Math.random()*16>>parseInt(t,10)/4).toString(16):\`10000000-1000-4000-8000-\${1e11}\`.replace(/[018]/g,re)}const We=/([\\w-]+)\\s*=\\s*([^;]+)/g;function Ls(t,e){for(We.lastIndex=0;;){const s=We.exec(t);if(s){if(s[1]===e)return s[2]}else break}}function Ds(t){const e=new Map;for(We.lastIndex=0;;){const s=We.exec(t);if(s)e.set(s[1],s[2]);else break}return e}function ws(t,e,s=""){const r=t.charCodeAt(e-1),o=r>=55296&&r<=56319?e+1:e;return t.length<=o?t:\`\${t.slice(0,o)}\${s}\`}function Us(){return Ps()===0}let Ye;function Ps(){return Ye??(Ye=Os())}function Os(t=window){var e;const s=t.navigator.userAgent;return t.chrome||/HeadlessChrome/.test(s)?0:((e=t.navigator.vendor)===null||e===void 0?void 0:e.indexOf("Apple"))===0||/safari/i.test(s)&&!/chrome|android/i.test(s)?1:2}function Ue(t,e,s=0,r){const n=new Date;n.setTime(n.getTime()+s);const o=\`expires=\${n.toUTCString()}\`,i=r&&r.crossSite?"none":"strict",a=r&&r.domain?\`;domain=\${r.domain}\`:"",c=r&&r.secure?";secure":"",u=r&&r.partitioned?";partitioned":"";document.cookie=\`\${t}=\${e};\${o};path=/;samesite=\${i}\${a}\${c}\${u}\`}function vt(t){return Ls(document.cookie,t)}let yt;function ae(t){return yt||(yt=Ds(document.cookie)),yt.get(t)}function cr(t,e){Ue(t,"",0,e)}function Cs(t){if(document.cookie===void 0||document.cookie===null)return!1;try{const e=\`dd_cookie_test_\${re()}\`,s="test";Ue(e,s,oe,t);const r=vt(e)===s;return cr(e,t),r}catch(e){return O.error(e),!1}}let xt;function Fs(){if(xt===void 0){const t=\`dd_site_test_\${re()}\`,e="test",s=window.location.hostname.split(".");let r=s.pop();for(;s.length&&!vt(t);)r=\`\${s.pop()}.\${r}\`,Ue(t,e,xe,{domain:r});cr(t,{domain:r}),xt=r}return xt}const ge="_dd_s";function He(t){return Object.values(t)}function Is(t){return Object.entries(t)}const St=4*Qt,lr=15*oe,Ms=gs,Pe={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},ur=/^([a-zA-Z]+)=([a-z0-9-]+)$/,Lt="&";function Bs(t){return!!t&&(t.indexOf(Lt)!==-1||ur.test(t))}const Ns="1";function ce(t,e){const s={isExpired:Ns};return e.trackAnonymousUser&&(t!=null&&t.anonymousId?s.anonymousId=t==null?void 0:t.anonymousId:s.anonymousId=re()),s}function $e(t){return Le(t)}function dr(t){return!$e(t)}function Ve(t){return t.isExpired!==void 0||!ks(t)}function ks(t){return(t.created===void 0||Se()-Number(t.created)<St)&&(t.expire===void 0||Se()<Number(t.expire))}function fr(t){t.expire=String(Se()+lr)}function Dt(t){return Is(t).map(([e,s])=>e==="anonymousId"?\`aid=\${s}\`:\`\${e}=\${s}\`).join(Lt)}function hr(t){const e={};return Bs(t)&&t.split(Lt).forEach(s=>{const r=ur.exec(s);if(r!==null){const[,n,o]=r;n==="aid"?e.anonymousId=o:e[n]=o}}),e}const Gs="_dd",Xs="_dd_r",Ws="_dd_l",Ys="rum",Hs="logs";function $s(t){if(!ae(ge)){const s=ae(Gs),r=ae(Xs),n=ae(Ws),o={};s&&(o.id=s),n&&/^[01]$/.test(n)&&(o[Hs]=n),r&&/^[012]$/.test(r)&&(o[Ys]=r),dr(o)&&(fr(o),t.persistSession(o))}}function mr(t){const e=Ks(t);return Cs(e)?{type:Pe.COOKIE,cookieOptions:e}:void 0}function Vs(t,e){const s={isLockEnabled:Us(),persistSession:zs(e),retrieveSession:qs,expireSession:r=>js(e,r,t)};return $s(s),s}function zs(t){return e=>{Ue(ge,Dt(e),lr,t)}}function js(t,e,s){const r=ce(e,s);Ue(ge,Dt(r),s.trackAnonymousUser?Ms:St,t)}function qs(){const t=vt(ge);return hr(t)}function Ks(t){const e={};return e.secure=!!t.useSecureSessionCookie||!!t.usePartitionedCrossSiteSessionCookie,e.crossSite=!!t.usePartitionedCrossSiteSessionCookie,e.partitioned=!!t.usePartitionedCrossSiteSessionCookie,t.trackSessionAcrossSubdomains&&(e.domain=Fs()),e}const Zs="_dd_test_";function pr(){try{const t=re(),e=\`\${Zs}\${t}\`;localStorage.setItem(e,t);const s=localStorage.getItem(e);return localStorage.removeItem(e),t===s?{type:Pe.LOCAL_STORAGE}:void 0}catch{return}}function Js(t){return{isLockEnabled:!1,persistSession:gr,retrieveSession:Qs,expireSession:e=>en(e,t)}}function gr(t){localStorage.setItem(ge,Dt(t))}function Qs(){const t=localStorage.getItem(ge);return hr(t)}function en(t,e){gr(ce(t,e))}const tn=10,rn=100,Er=[];let ze;function le(t,e,s=0){var r;const{isLockEnabled:n,persistSession:o,expireSession:i}=e,a=f=>o({...f,lock:u}),c=()=>{const f=e.retrieveSession(),m=f.lock;return f.lock&&delete f.lock,{session:f,lock:m}};if(ze||(ze=t),t!==ze){Er.push(t);return}if(n&&s>=rn){Tr(e);return}let u,l=c();if(n){if(l.lock){je(t,e,s);return}if(u=re(),a(l.session),l=c(),l.lock!==u){je(t,e,s);return}}let d=t.process(l.session);if(n&&(l=c(),l.lock!==u)){je(t,e,s);return}if(d&&(Ve(d)?i(d):(fr(d),n?a(d):o(d))),n&&!(d&&Ve(d))){if(l=c(),l.lock!==u){je(t,e,s);return}o(l.session),d=l.session}(r=t.after)===null||r===void 0||r.call(t,d||l.session),Tr(e)}function je(t,e,s){we(()=>{le(t,e,s+1)},tn)}function Tr(t){ze=void 0;const e=Er.shift();e&&le(e,t)}const Ar=xe;function sn(t){switch(t.sessionPersistence){case Pe.COOKIE:return mr(t);case Pe.LOCAL_STORAGE:return pr();case void 0:{let e=mr(t);return!e&&t.allowFallbackToLocalStorage&&(e=pr()),e}default:O.error(\`Invalid session persistence '\${String(t.sessionPersistence)}'\`)}}function nn(t,e,s,r){const n=new B,o=new B,i=new B,a=t.type===Pe.COOKIE?Vs(e,t.cookieOptions):Js(e),{expireSession:c}=a,u=Rt(p,Ar);let l;h();const{throttled:d,cancel:f}=ar(()=>{le({process:A=>{if($e(A))return;const L=T(A);return R(L),L},after:A=>{dr(A)&&!S()&&M(A),l=A}},a)},Ar);function m(){le({process:A=>S()?T(A):void 0},a)}function p(){le({process:A=>Ve(A)?ce(A,e):void 0,after:T},a)}function T(A){return Ve(A)&&(A=ce(A,e)),S()&&(F(A)?I():(i.notify({previousState:l,newState:A}),l=A)),A}function h(){le({process:A=>{if($e(A))return ce(A,e)},after:A=>{l=A}},a)}function R(A){if($e(A))return!1;const{trackingType:L,isTracked:W}=r(A[s]);A[s]=L,delete A.isExpired,W&&!A.id&&(A.id=re(),A.created=String(Se()))}function S(){return l[s]!==void 0}function F(A){return l.id!==A.id||l[s]!==A[s]}function I(){l=ce(l,e),o.notify()}function M(A){l=A,n.notify()}function k(A){le({process:L=>({...L,...A}),after:T},a)}return{expandOrRenewSession:d,expandSession:m,getSession:()=>l,renewObservable:n,expireObservable:o,sessionStateUpdateObservable:i,restartSession:h,expire:()=>{f(),c(l),T(ce(l,e))},stop:()=>{ir(u)},updateSessionState:k}}const wt={GRANTED:"granted",NOT_GRANTED:"not-granted"};function on(t){const e=new B;return{tryToInit(s){t||(t=s)},update(s){t=s,e.notify()},isGranted(){return t===wt.GRANTED},observable:e}}function ue(t,e,s){if(typeof t!="object"||t===null)return JSON.stringify(t);const r=Ee(Object.prototype),n=Ee(Array.prototype),o=Ee(Object.getPrototypeOf(t)),i=Ee(t);try{return JSON.stringify(t,e,s)}catch{return"<error: unable to serialize object>"}finally{r(),n(),o(),i()}}function Ee(t){const e=t,s=e.toJSON;return s?(delete e.toJSON,()=>{e.toJSON=s}):te}function Ut(t){return an(t,location.href).href}function an(t,e){const s=cn();if(s)try{return e!==void 0?new s(t,e):new s(t)}catch(o){throw new Error(\`Failed to construct URL: \${String(o)} \${ue({url:t,base:e})}\`)}if(e===void 0&&!/:/.test(t))throw new Error(\`Invalid URL: '\${t}'\`);let r=document;const n=r.createElement("a");if(e!==void 0){r=document.implementation.createHTMLDocument("");const o=r.createElement("base");o.href=e,r.head.appendChild(o),r.body.appendChild(n)}return n.href=t,n}const _r=URL;let qe;function cn(){if(qe===void 0)try{qe=new _r("http://test/path").href==="http://test/path"}catch{qe=!1}return qe?_r:void 0}const ln="datad0g.com",un="dd0g-gov.com",Te="datadoghq.com",dn="ddog-gov.com",fn="pci.browser-intake-datadoghq.com",hn=["ddsource","ddtags"];function Oe(t,e,s){const r=mn(t,e);return{build(n,o){const i=gn(t,e,s,n,o);return r(i)},urlPrefix:r(""),trackType:e}}function mn(t,e){const s=\`/api/v2/\${e}\`,r=t.proxy;if(typeof r=="string"){const o=Ut(r);return i=>\`\${o}?ddforward=\${encodeURIComponent(\`\${s}?\${i}\`)}\`}if(typeof r=="function")return o=>r({path:s,parameters:o});const n=pn(e,t);return o=>\`https://\${n}\${s}?\${o}\`}function pn(t,e){const{site:s=Te,internalAnalyticsSubdomain:r}=e;if(t==="logs"&&e.usePciIntake&&s===Te)return fn;if(r&&s===Te)return\`\${r}.\${Te}\`;if(s===un)return\`http-intake.logs.\${s}\`;const n=s.split("."),o=n.pop();return\`browser-intake-\${n.join("-")}.\${o}\`}function gn({clientToken:t,internalAnalyticsSubdomain:e},s,r,n,{retry:o,encoding:i}){const a=["sdk_version:6.5.0",\`api:\${n}\`].concat(r);o&&a.push(\`retry_count:\${o.count}\`,\`retry_after:\${o.lastFailureStatus}\`);const c=["ddsource=browser",\`ddtags=\${encodeURIComponent(a.join(","))}\`,\`dd-api-key=\${t}\`,\`dd-evp-origin-version=\${encodeURIComponent("6.5.0")}\`,"dd-evp-origin=browser",\`dd-request-id=\${re()}\`];return i&&c.push(\`dd-evp-encoding=\${i}\`),s==="rum"&&c.push(\`batch_time=\${J()}\`),e&&c.reverse(),c.join("&")}const En=200;function Tn(t){const{env:e,service:s,version:r,datacenter:n}=t,o=[];return e&&o.push(Ke("env",e)),s&&o.push(Ke("service",s)),r&&o.push(Ke("version",r)),n&&o.push(Ke("datacenter",n)),o}function Ke(t,e){const s=En-t.length-1;(e.length>s||An(e))&&O.warn(\`\${t} value doesn't meet tag requirements and will be sanitized. \${Ne} \${Tt}/getting_started/tagging/#defining-tags\`);const r=e.replace(/,/g,"_");return\`\${t}:\${r}\`}function An(t){return _n()?new RegExp("[^\\\\p{Ll}\\\\p{Lo}0-9_:./-]","u").test(t):!1}function _n(){try{return new RegExp("[\\\\p{Ll}]","u"),!0}catch{return!1}}function bn(t){const e=t.site||Te,s=Tn(t),r=Rn(t,s);return{replica:vn(t,s),site:e,...r}}function Rn(t,e){return{logsEndpointBuilder:Oe(t,"logs",e),rumEndpointBuilder:Oe(t,"rum",e),sessionReplayEndpointBuilder:Oe(t,"replay",e)}}function vn(t,e){if(!t.replica)return;const s={...t,site:Te,clientToken:t.replica.clientToken},r={logsEndpointBuilder:Oe(s,"logs",e),rumEndpointBuilder:Oe(s,"rum",e)};return{applicationId:t.replica.applicationId,...r}}function yn(t){return hn.every(e=>t.includes(e))}function Pt(t,e){return t!=null&&typeof t!="string"?(O.error(\`\${e} must be defined as a string\`),!1):!0}function xn(t){return t&&typeof t=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(t)?(O.error(\`Site should be a valid Datadog site. \${Ne} \${Tt}/getting_started/site/.\`),!1):!0}function Ze(t,e){return t!==void 0&&!ms(t)?(O.error(\`\${e} Sample Rate should be a number between 0 and 100\`),!1):!0}function Sn(t){var e,s,r,n,o,i;if(!t||!t.clientToken){O.error("Client Token is not configured, we will not send any data.");return}if(!(!xn(t.site)||!Ze(t.sessionSampleRate,"Session")||!Ze(t.telemetrySampleRate,"Telemetry")||!Ze(t.telemetryConfigurationSampleRate,"Telemetry Configuration")||!Ze(t.telemetryUsageSampleRate,"Telemetry Usage")||!Pt(t.version,"Version")||!Pt(t.env,"Env")||!Pt(t.service,"Service"))){if(t.trackingConsent!==void 0&&!rr(wt,t.trackingConsent)){O.error('Tracking Consent should be either "granted" or "not-granted"');return}return{beforeSend:t.beforeSend&&Jt(t.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:sn(t),sessionSampleRate:(e=t.sessionSampleRate)!==null&&e!==void 0?e:100,telemetrySampleRate:(s=t.telemetrySampleRate)!==null&&s!==void 0?s:20,telemetryConfigurationSampleRate:(r=t.telemetryConfigurationSampleRate)!==null&&r!==void 0?r:5,telemetryUsageSampleRate:(n=t.telemetryUsageSampleRate)!==null&&n!==void 0?n:5,service:t.service||void 0,silentMultipleInit:!!t.silentMultipleInit,allowUntrustedEvents:!!t.allowUntrustedEvents,trackingConsent:(o=t.trackingConsent)!==null&&o!==void 0?o:wt.GRANTED,trackAnonymousUser:(i=t.trackAnonymousUser)!==null&&i!==void 0?i:!0,storeContextsAcrossPages:!!t.storeContextsAcrossPages,batchBytesLimit:16*z,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*xe,batchMessagesLimit:50,messageBytesLimit:256*z,...bn(t)}}}function Ln(t){return{session_sample_rate:t.sessionSampleRate,telemetry_sample_rate:t.telemetrySampleRate,telemetry_configuration_sample_rate:t.telemetryConfigurationSampleRate,telemetry_usage_sample_rate:t.telemetryUsageSampleRate,use_before_send:!!t.beforeSend,use_partitioned_cross_site_session_cookie:t.usePartitionedCrossSiteSessionCookie,use_secure_session_cookie:t.useSecureSessionCookie,use_proxy:!!t.proxy,silent_multiple_init:t.silentMultipleInit,track_session_across_subdomains:t.trackSessionAcrossSubdomains,track_anonymous_user:t.trackAnonymousUser,session_persistence:t.sessionPersistence,allow_fallback_to_local_storage:!!t.allowFallbackToLocalStorage,store_contexts_across_pages:!!t.storeContextsAcrossPages,allow_untrusted_events:!!t.allowUntrustedEvents,tracking_consent:t.trackingConsent}}var Ot;(function(t){t.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",t.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(Ot||(Ot={}));const br=new Set;function Dn(t){Array.isArray(t)&&wn(t.filter(e=>rr(Ot,e)))}function wn(t){t.forEach(e=>{br.add(e)})}function Un(){return br}const Ce="?";function j(t){const e=[];let s=Ct(t,"stack");const r=String(t);return s&&s.startsWith(r)&&(s=s.slice(r.length)),s&&s.split(\`
|
|
2
|
-
\`).forEach(n=>{const o=Cn(n)||In(n)||Bn(n)||Gn(n);o&&(!o.func&&o.line&&(o.func=
|
|
3
|
-
at \${r}\${n} @ \${s.url}\${o}\${i}\`}),e}function vr(t){return\`\${t.name||"Error"}: \${t.message}\`}function fe(t,e,s,{computeHandlingStack:r}={}){let n=t[e];if(typeof n!="function")if(e in t&&e.startsWith("on"))n=te;else return{stop:te};let o=!1;const i=function(){if(o)return n.apply(this,arguments);const a=Array.from(arguments);let c;De(s,null,[{target:this,parameters:a,onPostCall:l=>{c=l},handlingStack:r?Je("instrumented method"):void 0}]);const u=n.apply(this,a);return c&&De(c,null,[u]),u};return t[e]=i,{stop:()=>{o=!0,t[e]===i&&(t[e]=n)}}}const Hn=220*z,$n="$",Vn=3;function q(t,e=Hn){const s=Ee(Object.prototype),r=Ee(Array.prototype),n=[],o=new WeakMap,i=Ft(t,$n,void 0,n,o),a=JSON.stringify(i);let c=a?a.length:0;if(c>e){Mt(e,"discarded",t);return}for(;n.length>0&&c<e;){const u=n.shift();let l=0;if(Array.isArray(u.source))for(let d=0;d<u.source.length;d++){const f=Ft(u.source[d],u.path,d,n,o);if(f!==void 0?c+=JSON.stringify(f).length:c+=4,c+=l,l=1,c>e){Mt(e,"truncated",t);break}u.target[d]=f}else for(const d in u.source)if(Object.prototype.hasOwnProperty.call(u.source,d)){const f=Ft(u.source[d],u.path,d,n,o);if(f!==void 0&&(c+=JSON.stringify(f).length+l+d.length+Vn,l=1),c>e){Mt(e,"truncated",t);break}u.target[d]=f}}return s(),r(),i}function Ft(t,e,s,r,n){const o=qn(t);if(!o||typeof o!="object")return zn(o);const i=It(o);if(i!=="[Object]"&&i!=="[Array]"&&i!=="[Error]")return i;const a=t;if(n.has(a))return\`[Reference seen at \${n.get(a)}]\`;const c=s!==void 0?\`\${e}.\${s}\`:e,u=Array.isArray(o)?[]:{};return n.set(a,c),r.push({source:o,target:u,path:c}),u}function zn(t){return typeof t=="bigint"?\`[BigInt] \${t.toString()}\`:typeof t=="function"?\`[Function] \${t.name||"unknown"}\`:typeof t=="symbol"?\`[Symbol] \${t.description||t.toString()}\`:t}function It(t){try{if(t instanceof Event)return jn(t);if(t instanceof RegExp)return\`[RegExp] \${t.toString()}\`;const s=Object.prototype.toString.call(t).match(/\\[object (.*)\\]/);if(s&&s[1])return\`[\${s[1]}]\`}catch{}return"[Unserializable]"}function jn(t){return{type:t.type,isTrusted:t.isTrusted,currentTarget:t.currentTarget?It(t.currentTarget):null,target:t.target?It(t.target):null}}function qn(t){const e=t;if(e&&typeof e.toJSON=="function")try{return e.toJSON()}catch{}return t}function Mt(t,e,s){O.warn(\`The data provided has been \${e} as it is over the limit of \${t} characters:\`,s)}const yr="No stack, consider using an instance of Error";function xr({stackTrace:t,originalError:e,handlingStack:s,componentStack:r,startClocks:n,nonErrorPrefix:o,source:i,handling:a}){const c=se(e),u=Kn(t,c,o,e),l=Zn(c,t)?de(t):yr,d=c?Dr(e,i):void 0,f=t?t.name:void 0,m=Sr(e),p=Lr(e);return{startClocks:n,source:i,handling:a,handlingStack:s,componentStack:r,originalError:e,type:f,message:u,stack:l,causes:d,fingerprint:m,context:p}}function Kn(t,e,s,r){return t!=null&&t.message&&(t!=null&&t.name)?t.message:e?"Empty message":\`\${s} \${ue(q(r))}\`}function Zn(t,e){return e===void 0?!1:t?!0:e.stack.length>0&&(e.stack.length>1||e.stack[0].url!==void 0)}function Sr(t){return se(t)&&"dd_fingerprint"in t?String(t.dd_fingerprint):void 0}function Lr(t){if(t!==null&&typeof t=="object"&&"dd_context"in t)return t.dd_context}function Jn(t){var e;return(e=/@ (.+)/.exec(t))===null||e===void 0?void 0:e[1]}function se(t){return t instanceof Error||Object.prototype.toString.call(t)==="[object Error]"}function Dr(t,e){let s=t;const r=[];for(;se(s==null?void 0:s.cause)&&r.length<10;){const n=j(s.cause);r.push({message:s.cause.message,source:e,type:n==null?void 0:n.name,stack:de(n)}),s=s.cause}return r.length?r:void 0}const X={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function Qn(t){const e=(n,o)=>{const i=xr({stackTrace:n,originalError:o,startClocks:Q(),nonErrorPrefix:"Uncaught",source:X.SOURCE,handling:"unhandled"});t.notify(i)},{stop:s}=ei(e),{stop:r}=ti(e);return{stop:()=>{s(),r()}}}function ei(t){return fe(window,"onerror",({parameters:[e,s,r,n,o]})=>{let i;se(o)?i=j(o):i=Xn(e,s,r,n),t(i,o??e)})}function ti(t){return fe(window,"onunhandledrejection",({parameters:[e]})=>{const s=e.reason||"Empty reason",r=j(s);t(r,s)})}function ri(t){const e={version:"6.5.0",onReady(s){s()},...t};return Object.defineProperty(e,"_setDebug",{get(){return ys},enumerable:!1}),e}function si(t,e,s){const r=t[e];r&&!r.q&&r.version&&O.warn("SDK is loaded more than once. This is unsupported and might have unexpected behavior."),t[e]=s,r&&r.q&&r.q.forEach(n=>Jt(n,"onReady callback threw an error:")())}function wr(t,e){e.silentMultipleInit||O.error(\`\${t} is already initialized.\`)}function he(t,e,s,r,n){return Bt(t,e,[s],r,n)}function Bt(t,e,s,r,{once:n,capture:o,passive:i}={}){const a=y(f=>{!f.isTrusted&&!f.__ddIsTrusted&&!t.allowUntrustedEvents||(n&&d(),r(f))}),c=i?{capture:o,passive:i}:o,u=window.EventTarget&&e instanceof EventTarget?window.EventTarget.prototype:e,l=pe(u,"addEventListener");s.forEach(f=>l.call(e,f,a,c));function d(){const f=pe(u,"removeEventListener");s.forEach(m=>f.call(e,m,a,c))}return{stop:d}}const Qe={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function ni(t,e){const s=[];e.includes(Qe.cspViolation)&&s.push(oi(t));const r=e.filter(n=>n!==Qe.cspViolation);return r.length&&s.push(ii(r)),or(...s)}function ii(t){return new B(e=>{if(!window.ReportingObserver)return;const s=y((n,o)=>n.forEach(i=>e.notify(ai(i)))),r=new window.ReportingObserver(s,{types:t,buffered:!0});return r.observe(),()=>{r.disconnect()}})}function oi(t){return new B(e=>{const{stop:s}=he(t,document,"securitypolicyviolation",r=>{e.notify(ci(r))});return s})}function ai(t){const{type:e,body:s}=t;return Ur({type:s.id,message:\`\${e}: \${s.message}\`,originalError:t,stack:Pr(s.id,s.message,s.sourceFile,s.lineNumber,s.columnNumber)})}function ci(t){const e=\`'\${t.blockedURI}' blocked by '\${t.effectiveDirective}' directive\`;return Ur({type:t.effectiveDirective,message:\`\${Qe.cspViolation}: \${e}\`,originalError:t,csp:{disposition:t.disposition},stack:Pr(t.effectiveDirective,t.originalPolicy?\`\${e} of the policy "\${ws(t.originalPolicy,100,"...")}"\`:"no policy",t.sourceFile,t.lineNumber,t.columnNumber)})}function Ur(t){return{startClocks:Q(),source:X.REPORT,handling:"unhandled",...t}}function Pr(t,e,s,r,n){return s?de({name:t,message:e,stack:[{func:"?",url:s,line:r??void 0,column:n??void 0}]}):void 0}function Or(t,e){const s=window.__ddBrowserSdkExtensionCallback;s&&s({type:t,payload:e})}function Cr(t){return t===null?"null":Array.isArray(t)?"array":typeof t}function et(t,e,s=li()){if(e===void 0)return t;if(typeof e!="object"||e===null)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){const n=e.flags||[e.global?"g":"",e.ignoreCase?"i":"",e.multiline?"m":"",e.sticky?"y":"",e.unicode?"u":""].join("");return new RegExp(e.source,n)}if(s.hasAlreadyBeenSeen(e))return;if(Array.isArray(e)){const n=Array.isArray(t)?t:[];for(let o=0;o<e.length;++o)n[o]=et(n[o],e[o],s);return n}const r=Cr(t)==="object"?t:{};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=et(r[n],e[n],s));return r}function Fr(t){return et(void 0,t)}function _e(...t){let e;for(const s of t)s!=null&&(e=et(e,s));return e}function li(){if(typeof WeakSet<"u"){const e=new WeakSet;return{hasAlreadyBeenSeen(s){const r=e.has(s);return r||e.add(s),r}}}const t=[];return{hasAlreadyBeenSeen(e){const s=t.indexOf(e)>=0;return s||t.push(e),s}}}function ui(){var t;const e=window.navigator;return{status:e.onLine?"connected":"not_connected",interfaces:e.connection&&e.connection.type?[e.connection.type]:void 0,effective_type:(t=e.connection)===null||t===void 0?void 0:t.effectiveType}}function di(t){const e=new Set;return t.forEach(s=>e.add(s)),Array.from(e)}function Ir(t,e){const s=t.indexOf(e);s>=0&&t.splice(s,1)}const fi=500;function Mr(){const t=[];return{add:n=>{t.push(n)>fi&&t.splice(0,1)},remove:n=>{Ir(t,n)},drain:n=>{t.forEach(o=>o(n)),t.length=0}}}const me={log:"log",configuration:"configuration",usage:"usage"},hi=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],mi=[dn];let Br=Mr(),be=t=>{Br.add(()=>be(t))};function pi(t,e){let s;const r=new B,n=new Set,o=!mi.includes(e.site)&&ke(e.telemetrySampleRate),i={[me.log]:o,[me.configuration]:o&&ke(e.telemetryConfigurationSampleRate),[me.usage]:o&&ke(e.telemetryUsageSampleRate)},a=gi();be=u=>{const l=ue(u);if(i[u.type]&&n.size<e.maxTelemetryEventsPerPage&&!n.has(l)){const d=c(t,u,a);r.notify(d),Or("telemetry",d),n.add(l)}},vs(kr);function c(u,l,d){return _e({type:"telemetry",date:J(),service:u,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:_e(l,{runtime_env:d,connectivity:ui(),sdk_setup:"npm"}),experimental_features:Array.from(Un())},s!==void 0?s():{})}return{setContextProvider:u=>{s=u},observable:r,enabled:o}}function gi(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function Ei(){Br.drain()}function Ti(t){return t.site===ln}function Nr(t,e){bt(P.debug,t,e),be({type:me.log,message:t,status:"debug",...e})}function kr(t,e){be({type:me.log,status:"error",...bi(t),...e})}function Ai(t){be({type:me.configuration,configuration:t})}function _i(t){be({type:me.usage,usage:t})}function bi(t){if(se(t)){const e=j(t);return{error:{kind:e.name,stack:de(Ri(e))},message:e.message}}return{error:{stack:yr},message:\`Uncaught \${ue(t)}\`}}function Ri(t){return t.stack=t.stack.filter(e=>!e.url||hi.some(s=>e.url.startsWith(s))),t}const Fe=1/0,vi=oe;let Ie=null;const tt=new Set;function yi(){tt.forEach(t=>t())}function xi({expireDelay:t,maxEntries:e}){let s=[];const r=[];Ie||(Ie=Rt(()=>yi(),vi));const n=()=>{const m=Ge()-t;for(;s.length>0&&s[s.length-1].endTime<m;){const p=s.pop();p&&r.push(p.startTime)}};tt.add(n);function o(m,p){const T={value:m,startTime:p,endTime:Fe,remove:()=>{Ir(s,T)},close:h=>{T.endTime=h}};return e&&s.length>=e&&s.pop(),s.unshift(T),T}function i(m=Fe,p={returnInactive:!1}){for(const T of s)if(T.startTime<=m){if(p.returnInactive||m<=T.endTime)return T.value;break}}function a(m){const p=s[0];p&&p.endTime===Fe&&p.close(m)}function c(m=Fe,p=0){const T=As(m,p);return s.filter(h=>h.startTime<=T&&m<=h.endTime).map(h=>h.value)}function u(){return s.map(({startTime:m,endTime:p,value:T})=>({startTime:m,endTime:p===Fe?"Infinity":p,value:T}))}function l(){return r}function d(){s=[]}function f(){tt.delete(n),tt.size===0&&Ie&&(ir(Ie),Ie=null)}return{add:o,find:i,closeActive:a,findAll:c,reset:d,stop:f,getAllEntries:u,getDeletedEntries:l}}const Si=oe,Li=St;function Di(t,e,s,r){const n=new B,o=new B,i=nn(t.sessionStoreStrategyType,t,e,s),a=xi({expireDelay:Li});i.renewObservable.subscribe(()=>{a.add(c(),Ge()),n.notify()}),i.expireObservable.subscribe(()=>{o.notify(),a.closeActive(Ge())}),i.expandOrRenewSession(),a.add(c(),Es().relative),r.observable.subscribe(()=>{r.isGranted()?i.expandOrRenewSession():i.expire()}),wi(t,()=>{r.isGranted()&&i.expandOrRenewSession()}),Ui(t,()=>i.expandSession()),Pi(t,()=>i.restartSession());function c(){return{id:i.getSession().id,trackingType:i.getSession()[e],isReplayForced:!!i.getSession().forcedReplay,anonymousId:i.getSession().anonymousId}}return{findSession:(u,l)=>a.find(u,l),renewObservable:n,expireObservable:o,sessionStateUpdateObservable:i.sessionStateUpdateObservable,expire:i.expire,updateSessionState:i.updateSessionState}}function wi(t,e){Bt(t,window,["click","touchstart","keydown","scroll"],e,{capture:!0,passive:!0})}function Ui(t,e){const s=()=>{document.visibilityState==="visible"&&e()};he(t,document,"visibilitychange",s),Rt(s,Si)}function Pi(t,e){he(t,window,"resume",e,{capture:!0})}function Gr(t){return t>=500}function Oi(t){try{return t.clone()}catch{return}}const Ci=80*z,Fi=32,Xr=3*tr,Ii=oe,Wr=xe;function Yr(t,e,s,r,n){e.transportStatus===0&&e.queuedPayloads.size()===0&&e.bandwidthMonitor.canHandle(t)?$r(t,e,s,{onSuccess:()=>Vr(0,e,s,r,n),onFailure:()=>{e.queuedPayloads.enqueue(t),Hr(e,s,r,n)}}):e.queuedPayloads.enqueue(t)}function Hr(t,e,s,r){t.transportStatus===2&&we(()=>{const n=t.queuedPayloads.first();$r(n,t,e,{onSuccess:()=>{t.queuedPayloads.dequeue(),t.currentBackoffTime=Wr,Vr(1,t,e,s,r)},onFailure:()=>{t.currentBackoffTime=Math.min(Ii,t.currentBackoffTime*2),Hr(t,e,s,r)}})},t.currentBackoffTime)}function $r(t,e,s,{onSuccess:r,onFailure:n}){e.bandwidthMonitor.add(t),s(t,o=>{e.bandwidthMonitor.remove(t),Mi(o)?(e.transportStatus=e.bandwidthMonitor.ongoingRequestCount>0?1:2,t.retry={count:t.retry?t.retry.count+1:1,lastFailureStatus:o.status},n()):(e.transportStatus=0,r())})}function Vr(t,e,s,r,n){t===0&&e.queuedPayloads.isFull()&&!e.queueFullReported&&(n({message:\`Reached max \${r} events size queued for upload: \${Xr/tr}MiB\`,source:X.AGENT,startClocks:Q()}),e.queueFullReported=!0);const o=e.queuedPayloads;for(e.queuedPayloads=zr();o.size()>0;)Yr(o.dequeue(),e,s,r,n)}function Mi(t){return t.type!=="opaque"&&(t.status===0&&!navigator.onLine||t.status===408||t.status===429||Gr(t.status))}function Bi(){return{transportStatus:0,currentBackoffTime:Wr,bandwidthMonitor:Ni(),queuedPayloads:zr(),queueFullReported:!1}}function zr(){const t=[];return{bytesCount:0,enqueue(e){this.isFull()||(t.push(e),this.bytesCount+=e.bytesCount)},first(){return t[0]},dequeue(){const e=t.shift();return e&&(this.bytesCount-=e.bytesCount),e},size(){return t.length},isFull(){return this.bytesCount>=Xr}}}function Ni(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(t){return this.ongoingRequestCount===0||this.ongoingByteCount+t.bytesCount<=Ci&&this.ongoingRequestCount<Fi},add(t){this.ongoingRequestCount+=1,this.ongoingByteCount+=t.bytesCount},remove(t){this.ongoingRequestCount-=1,this.ongoingByteCount-=t.bytesCount}}}function ki(t,e,s){const r=Bi(),n=(o,i)=>Wi(t,e,o,i);return{send:o=>{Yr(o,r,n,t.trackType,s)},sendOnExit:o=>{Gi(t,e,o)}}}function Gi(t,e,s){if(!!navigator.sendBeacon&&s.bytesCount<e)try{const o=t.build("beacon",s);if(navigator.sendBeacon(o,s.data))return}catch(o){Xi(o)}const n=t.build("xhr",s);Nt(n,s.data)}let jr=!1;function Xi(t){jr||(jr=!0,kr(t))}function Wi(t,e,s,r){if(Yi()&&s.bytesCount<e){const o=t.build("fetch",s);fetch(o,{method:"POST",body:s.data,keepalive:!0,mode:"cors"}).then(y(i=>r==null?void 0:r({status:i.status,type:i.type})),y(()=>{const i=t.build("xhr",s);Nt(i,s.data,r)}))}else{const o=t.build("xhr",s);Nt(o,s.data,r)}}function Yi(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function Nt(t,e,s){const r=new XMLHttpRequest;r.open("POST",t,!0),e instanceof Blob&&r.setRequestHeader("Content-Type",e.type),he({allowUntrustedEvents:!0},r,"loadend",()=>{s==null||s({status:r.status})},{once:!0}),r.send(e)}function kt(){const t=Hi();if(t)return{getCapabilities(){var e;return JSON.parse(((e=t.getCapabilities)===null||e===void 0?void 0:e.call(t))||"[]")},getPrivacyLevel(){var e;return(e=t.getPrivacyLevel)===null||e===void 0?void 0:e.call(t)},getAllowedWebViewHosts(){return JSON.parse(t.getAllowedWebViewHosts())},send(e,s,r){const n=r?{id:r}:void 0;t.send(JSON.stringify({eventType:e,event:s,view:n}))}}}function rt(t){var e;t===void 0&&(t=(e=ee().location)===null||e===void 0?void 0:e.hostname);const s=kt();return!!s&&s.getAllowedWebViewHosts().some(r=>t===r||t.endsWith(\`.\${r}\`))}function Hi(){return ee().DatadogEventBridge}const st={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function $i(t){return new B(e=>{const{stop:s}=Bt(t,window,["visibilitychange","freeze"],n=>{n.type==="visibilitychange"&&document.visibilityState==="hidden"?e.notify({reason:st.HIDDEN}):n.type==="freeze"&&e.notify({reason:st.FROZEN})},{capture:!0}),r=he(t,window,"beforeunload",()=>{e.notify({reason:st.UNLOADING})}).stop;return()=>{s(),r()}})}function Vi(t){return He(st).includes(t)}function zi({encoder:t,request:e,flushController:s,messageBytesLimit:r}){let n={};const o=s.flushObservable.subscribe(d=>l(d));function i(d,f,m){s.notifyBeforeAddMessage(f),m!==void 0?(n[m]=d,s.notifyAfterAddMessage()):t.write(t.isEmpty?d:\`
|
|
4
|
-
\${
|
|
5
|
-
\`);n={};const m=Vi(
|
|
6
|
-
\`);h&&p({data:h,bytesCount:
|
|
7
|
-
\${f}\`),t.finish(T=>{p(qr(T))})}return{flushController:s,add:u,upsert:u,stop:o.unsubscribe}}function qr(t){let e;return typeof t.output=="string"?e=t.output:e=new Blob([t.output],{type:"text/plain"}),{data:e,bytesCount:t.outputBytesCount,encoding:t.encoding}}function ji({messagesLimit:t,bytesLimit:e,durationLimit:s,pageExitObservable:r,sessionExpireObservable:n}){const o=r.subscribe(p=>l(p.reason)),i=n.subscribe(()=>l("session_expire")),a=new B(()=>()=>{o.unsubscribe(),i.unsubscribe()});let c=0,u=0;function l(p){if(u===0)return;const T=u,h=c;u=0,c=0,m(),a.notify({reason:p,messagesCount:T,bytesCount:h})}let d;function f(){d===void 0&&(d=we(()=>{l("duration_limit")},s))}function m(){nr(d),d=void 0}return{flushObservable:a,get messagesCount(){return u},notifyBeforeAddMessage(p){c+p>=e&&l("bytes_limit"),u+=1,c+=p,f()},notifyAfterAddMessage(p=0){c+=p,u>=t?l("messages_limit"):c>=e&&l("bytes_limit")},notifyAfterRemoveMessage(p){c-=p,u-=1,u===0&&m()}}}function Kr(t,e,s,r,n,o,i=zi){const a=u(t,e),c=s&&u(t,s);function u(l,{endpoint:d,encoder:f}){return i({encoder:f,request:ki(d,l.batchBytesLimit,r),flushController:ji({messagesLimit:l.batchMessagesLimit,bytesLimit:l.batchBytesLimit,durationLimit:l.flushTimeout,pageExitObservable:n,sessionExpireObservable:o}),messageBytesLimit:l.messageBytesLimit})}return{flushObservable:a.flushController.flushObservable,add(l,d=!0){a.add(l),c&&d&&c.add(s.transformMessage?s.transformMessage(l):l)},upsert:(l,d)=>{a.upsert(l,d),c&&c.upsert(s.transformMessage?s.transformMessage(l):l,d)},stop:()=>{a.stop(),c&&c.stop()}}}function nt(){let t="",e=0;return{isAsync:!1,get isEmpty(){return!t},write(s,r){const n=_t(s);e+=n,t+=s,r&&r(n)},finish(s){s(this.finishSync())},finishSync(){const s={output:t,outputBytesCount:e,rawBytesCount:e,pendingData:""};return t="",e=0,s},estimateEncodedBytesCount(s){return s.length}}}class qi{constructor(){this.callbacks={}}notify(e,s){const r=this.callbacks[e];r&&r.forEach(n=>n(s))}subscribe(e,s){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(s),{unsubscribe:()=>{this.callbacks[e]=this.callbacks[e].filter(r=>s!==r)}}}}function Ki(t,e,s){let r=0,n=!1;return{isLimitReached(){if(r===0&&we(()=>{r=0},oe),r+=1,r<=e||n)return n=!1,!1;if(r===e+1){n=!0;try{s({message:\`Reached max number of \${t}s by minute: \${e}\`,source:X.AGENT,startClocks:Q()})}finally{n=!1}}return!0}}}let Gt;const Xt=new WeakMap;function Zi(t){return Gt||(Gt=Ji(t)),Gt}function Ji(t){return new B(e=>{const{stop:s}=fe(XMLHttpRequest.prototype,"open",Qi),{stop:r}=fe(XMLHttpRequest.prototype,"send",o=>{eo(o,t,e)},{computeHandlingStack:!0}),{stop:n}=fe(XMLHttpRequest.prototype,"abort",to);return()=>{s(),r(),n()}})}function Qi({target:t,parameters:[e,s]}){Xt.set(t,{state:"open",method:String(e).toUpperCase(),url:Ut(String(s))})}function eo({target:t,handlingStack:e},s,r){const n=Xt.get(t);if(!n)return;const o=n;o.state="start",o.startClocks=Q(),o.isAborted=!1,o.xhr=t,o.handlingStack=e;let i=!1;const{stop:a}=fe(t,"onreadystatechange",()=>{t.readyState===XMLHttpRequest.DONE&&c()}),c=()=>{if(u(),a(),i)return;i=!0;const l=n;l.state="complete",l.duration=Ts(o.startClocks.timeStamp,J()),l.status=t.status,r.notify(Rs(l))},{stop:u}=he(s,t,"loadend",c);r.notify(o)}function to({target:t}){const e=Xt.get(t);e&&(e.isAborted=!0)}let Wt;function Zr(){return Wt||(Wt=ro()),Wt}function ro(){return new B(t=>{if(!window.fetch)return;const{stop:e}=fe(window,"fetch",s=>so(s,t),{computeHandlingStack:!0});return e})}function so({parameters:t,onPostCall:e,handlingStack:s},r){const[n,o]=t;let i=o&&o.method;i===void 0&&n instanceof Request&&(i=n.method);const a=i!==void 0?String(i).toUpperCase():"GET",c=n instanceof Request?n.url:Ut(String(n)),u=Q(),l={state:"start",init:o,input:n,method:a,startClocks:u,url:c,handlingStack:s};r.notify(l),t[0]=l.input,t[1]=l.init,e(d=>no(r,d,l))}function no(t,e,s){const r=s;function n(o){r.state="resolve",Object.assign(r,o),t.notify(r)}e.then(y(o=>{n({response:o,responseType:o.type,status:o.status,isAborted:!1})}),y(o=>{var i,a;n({status:0,isAborted:((a=(i=r.init)===null||i===void 0?void 0:i.signal)===null||a===void 0?void 0:a.aborted)||o instanceof DOMException&&o.code===DOMException.ABORT_ERR,error:o})}))}let Yt={};function io(t){const e=t.map(s=>(Yt[s]||(Yt[s]=oo(s)),Yt[s]));return or(...e)}function oo(t){return new B(e=>{const s=H[t];return H[t]=(...r)=>{s.apply(console,r);const n=Je("console error");De(()=>{e.notify(ao(r,t,n))})},()=>{H[t]=s}})}function ao(t,e,s){const r=t.map(o=>co(o)).join(" ");let n;if(e===P.error){const o=t.find(se);n={stack:o?de(j(o)):void 0,fingerprint:Sr(o),causes:o?Dr(o,"console"):void 0,startClocks:Q(),message:r,source:X.CONSOLE,handling:"handled",handlingStack:s,context:Lr(o)}}return{api:e,message:r,error:n,handlingStack:s}}function co(t){return typeof t=="string"?q(t):se(t)?vr(j(t)):ue(q(t),void 0,2)}function lo(t){const e=Cr(t)==="object";return e||O.error("Unsupported context:",t),e}function Ht(t,e,s){const r={...t};for(const[n,{required:o,type:i}]of Object.entries(e))i==="string"&&n in r&&(r[n]=String(r[n])),o&&!(n in t)&&O.warn(\`The property \${n} of \${s} is required; context will not be sent to the intake.\`);return r}function it(t="",{customerDataTracker:e,propertiesConfig:s={}}={}){let r={};const n=new B,o={getContext:()=>Fr(r),setContext:i=>{lo(i)?(r=q(Ht(i,s,t)),e==null||e.updateCustomerData(r)):o.clearContext(),n.notify()},setContextProperty:(i,a)=>{r=q(Ht({...r,[i]:a},s,t)),e==null||e.updateCustomerData(r),n.notify()},removeContextProperty:i=>{delete r[i],e==null||e.updateCustomerData(r),Ht(r,s,t),n.notify()},clearContext:()=>{r={},e==null||e.resetCustomerData(),n.notify()},changeObservable:n};return o}const uo="_dd_c",fo=[];function $t(t,e,s,r){const n=ho(s,r);fo.push(he(t,window,"storage",({key:u})=>{n===u&&i()})),e.changeObservable.subscribe(a);const o=_e(c(),e.getContext());Le(o)||e.setContext(o);function i(){e.setContext(c())}function a(){localStorage.setItem(n,JSON.stringify(e.getContext()))}function c(){const u=localStorage.getItem(n);return u?JSON.parse(u):{}}}function ho(t,e){return\`\${uo}_\${t}_\${e}\`}const mo=3*z,po=16*z,go=200;function Eo(t=2){const e=new Map;let s=!1;function r(n=0){if(s||t===0)return;const o=t===2?mo:po;let i=n;e.forEach(a=>{i+=a.getBytesCount()}),i>o&&(To(o),s=!0)}return{createDetachedTracker:()=>{const n=Jr(()=>r(n.getBytesCount()));return n},getOrCreateTracker:n=>(e.has(n)||e.set(n,Jr(r)),e.get(n)),setCompressionStatus:n=>{t===0&&(t=n,r())},getCompressionStatus:()=>t,stop:()=>{e.forEach(n=>n.stop()),e.clear()}}}function Jr(t){let e=0;const{throttled:s,cancel:r}=ar(o=>{e=_t(ue(o)),t()},go),n=()=>{r(),e=0};return{updateCustomerData:o=>{Le(o)?n():s(o)},resetCustomerData:n,getBytesCount:()=>e,stop:()=>{r()}}}function To(t){O.warn(\`Customer data exceeds the recommended \${t/z}KiB threshold. \${Ne} \${Zt}/#customer-data-exceeds-the-recommended-threshold-warning\`)}function Ao(t,e,s){const r=t.getReader(),n=[];let o=0;i();function i(){r.read().then(y(c=>{if(c.done){a();return}n.push(c.value),o+=c.value.length,o>s.bytesLimit?a():i()}),y(c=>e(c)))}function a(){r.cancel().catch(te);let c,u;{let l;if(n.length===1)l=n[0];else{l=new Uint8Array(o);let d=0;n.forEach(f=>{l.set(f,d),d+=f.length})}c=l.slice(0,s.bytesLimit),u=l.length>s.bytesLimit}e(void 0,c,u)}}const _o="datadog-synthetics-public-id",bo="datadog-synthetics-result-id",Ro="datadog-synthetics-injects-rum";function Qr(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||ae(Ro))}function vo(){const t=window._DATADOG_SYNTHETICS_PUBLIC_ID||ae(_o);return typeof t=="string"?t:void 0}function yo(){const t=window._DATADOG_SYNTHETICS_RESULT_ID||ae(bo);return typeof t=="string"?t:void 0}function ot(t,e,s){const r=s.getHandler(),n=Array.isArray(r)?r:[r];return es[t]>=es[s.getLevel()]&&n.includes(e)}const _={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},es={[_.ok]:0,[_.debug]:1,[_.info]:2,[_.notice]:4,[_.warn]:5,[_.error]:6,[_.critical]:7,[_.alert]:8,[_.emerg]:9};function at(t,{includeMessage:e=!1}={}){return{stack:t.stack,kind:t.type,message:e?t.message:void 0,causes:t.causes,fingerprint:t.fingerprint,handling:t.handling}}var xo=function(t,e,s,r){var n=arguments.length,o=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,s):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(t,e,s,r);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(o=(n<3?i(o):n>3?i(e,s,o):i(e,s))||o);return n>3&&o&&Object.defineProperty(e,s,o),o};const Me={console:"console",http:"http",silent:"silent"},So=Object.keys(_);let Y=class{constructor(e,s,r,n=Me.http,o=_.debug,i={}){this.handleLogStrategy=e,this.handlerType=n,this.level=o,this.contextManager=it("logger",{customerDataTracker:s}),this.contextManager.setContext(i),r&&this.contextManager.setContextProperty("logger",{name:r})}logImplementation(e,s,r=_.info,n,o){const i=q(s);let a;if(n!=null){const c=xr({stackTrace:se(n)?j(n):void 0,originalError:n,nonErrorPrefix:"Provided",source:X.LOGGER,handling:"handled",startClocks:Q()});a=_e({error:at(c,{includeMessage:!0})},i)}else a=i;this.handleLogStrategy({message:q(e),context:a,status:r},this,o)}log(e,s,r=_.info,n){let o;ot(r,Me.http,this)&&(o=Je("log")),this.logImplementation(e,s,r,n,o)}setContext(e){this.contextManager.setContext(e)}getContext(){return this.contextManager.getContext()}setContextProperty(e,s){this.contextManager.setContextProperty(e,s)}removeContextProperty(e){this.contextManager.removeContextProperty(e)}clearContext(){this.contextManager.clearContext()}setHandler(e){this.handlerType=e}getHandler(){return this.handlerType}setLevel(e){this.level=e}getLevel(){return this.level}};xo([xs],Y.prototype,"logImplementation",null),Y.prototype.ok=K(_.ok),Y.prototype.debug=K(_.debug),Y.prototype.info=K(_.info),Y.prototype.notice=K(_.notice),Y.prototype.warn=K(_.warn),Y.prototype.error=K(_.error),Y.prototype.critical=K(_.critical),Y.prototype.alert=K(_.alert),Y.prototype.emerg=K(_.emerg);function K(t){return function(e,s,r){let n;ot(t,Me.http,this)&&(n=Je("log")),this.logImplementation(e,s,t,r,n)}}function Lo(t,e,s){return{view:{referrer:document.referrer,url:window.location.href},context:t.getContext(),user:e.getContext(),account:s.getContext()}}const Do=32*z;function wo(t){t.usePciIntake===!0&&t.site&&t.site!=="datadoghq.com"&&O.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");const e=Sn(t),s=ts(t.forwardConsoleLogs,He(P),"Forward Console Logs"),r=ts(t.forwardReports,He(Qe),"Forward Reports");if(!(!e||!s||!r))return t.forwardErrorsToLogs&&!s.includes(P.error)&&s.push(P.error),{forwardErrorsToLogs:t.forwardErrorsToLogs!==!1,forwardConsoleLogs:s,forwardReports:r,requestErrorResponseLengthLimit:Do,...e}}function ts(t,e,s){if(t===void 0)return[];if(!(t==="all"||Array.isArray(t)&&t.every(r=>e.includes(r)))){O.error(\`\${s} should be "all" or an array with allowed values "\${e.join('", "')}"\`);return}return t==="all"?e:di(t)}function Uo(t){const e=Ln(t);return{forward_errors_to_logs:t.forwardErrorsToLogs,forward_console_logs:t.forwardConsoleLogs,forward_reports:t.forwardReports,use_pci_intake:t.usePciIntake,...e}}function Po(t,e,s){const r=Mr();let n,o;const i=e.observable.subscribe(a);function a(){if(!o||!n||!e.isGranted())return;i.unsubscribe();const c=s(n,o);r.drain(c)}return{init(c){if(!c){O.error("Missing configuration");return}if(Dn(c.enableExperimentalFeatures),rt()&&(c=Oo(c)),n=c,o){wr("DD_LOGS",c);return}const u=wo(c);u&&(o=u,Zr().subscribe(te),e.tryToInit(u.trackingConsent),a())},get initConfiguration(){return n},getInternalContext:te,handleLog(c,u,l,d=t(),f=J()){r.add(m=>m.handleLog(c,u,l,d,f))}}}function Oo(t){return{...t,clientToken:"empty"}}const Vt="logs";function Co(t){const e=Eo(),s=it("global context",{customerDataTracker:e.getOrCreateTracker(2)}),r=it("user",{customerDataTracker:e.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),n=it("account",{customerDataTracker:e.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),o=on();function i(){return Lo(s,r,n)}let a=Po(i,o,(l,d)=>{l.storeContextsAcrossPages&&($t(d,s,Vt,2),$t(d,r,Vt,1),$t(d,n,Vt,4));const f=t(l,d,i,o);return a=Fo(l,f),f});const c={},u=new Y((...l)=>a.handleLog(...l),e.createDetachedTracker());return ri({logger:u,init:y(l=>a.init(l)),setTrackingConsent:y(l=>{o.update(l),_i({feature:"set-tracking-consent",tracking_consent:l})}),getGlobalContext:y(()=>s.getContext()),setGlobalContext:y(l=>s.setContext(l)),setGlobalContextProperty:y((l,d)=>s.setContextProperty(l,d)),removeGlobalContextProperty:y(l=>s.removeContextProperty(l)),clearGlobalContext:y(()=>s.clearContext()),createLogger:y((l,d={})=>(c[l]=new Y((...f)=>a.handleLog(...f),e.createDetachedTracker(),q(l),d.handler,d.level,q(d.context)),c[l])),getLogger:y(l=>c[l]),getInitConfiguration:y(()=>Fr(a.initConfiguration)),getInternalContext:y(l=>a.getInternalContext(l)),setUser:y(r.setContext),getUser:y(r.getContext),setUserProperty:y(r.setContextProperty),removeUserProperty:y(r.removeContextProperty),clearUser:y(r.clearContext),setAccount:y(n.setContext),getAccount:y(n.getContext),setAccountProperty:y(n.setContextProperty),removeAccountProperty:y(n.removeContextProperty),clearAccount:y(n.clearContext)})}function Fo(t,e){return{init:s=>{wr("DD_LOGS",s)},initConfiguration:t,...e}}const Io="logs";function Mo(t,e){const s=Di(t,Io,r=>No(t,r),e);return{findTrackedSession:(r,n={returnInactive:!1})=>{const o=s.findSession(r,n);return o&&o.trackingType==="1"?{id:o.id,anonymousId:o.anonymousId}:void 0},expireObservable:s.expireObservable}}function Bo(t){const s=rs(t)==="1"?{}:void 0;return{findTrackedSession:()=>s,expireObservable:new B}}function rs(t){return ke(t.sessionSampleRate)?"1":"0"}function No(t,e){const s=ko(e)?e:rs(t);return{trackingType:s,isTracked:s==="1"}}function ko(t){return t==="0"||t==="1"}let ss=!1;function ct(t){const e=window;if(Qr()){const r=s(e.DD_RUM_SYNTHETICS);return!r&&!ss&&(ss=!0,Nr("Logs sent before RUM is injected by the synthetics worker",{testId:vo(),resultId:yo()})),r}return s(e.DD_RUM);function s(r){if(r&&r.getInternalContext)return r.getInternalContext(t)}}function Go(t,e,s,r,n){const o=So.concat(["custom"]),i={};o.forEach(a=>{i[a]=Ki(a,e.eventRateLimiterThreshold,n)}),s.subscribe(0,({rawLogsEvent:a,messageContext:c=void 0,savedCommonContext:u=void 0,domainContext:l})=>{var d,f;const m=_s(a.date),p=t.findTrackedSession(m);if(!t.findTrackedSession(m,{returnInactive:!0}))return;const h=u||r();let R;!Le(h.account)&&h.account.id&&(R=h.account),p&&p.anonymousId&&!h.user.anonymous_id&&(h.user.anonymous_id=p.anonymousId);const S=_e({service:e.service,session_id:p?p.id:void 0,session:p?{id:p.id}:void 0,usr:Le(h.user)?void 0:h.user,account:R,view:h.view},h.context,ct(m),a,c);((d=e.beforeSend)===null||d===void 0?void 0:d.call(e,S,l))===!1||S.origin!==X.AGENT&&((f=i[S.status])!==null&&f!==void 0?f:i.custom).isLimitReached()||s.notify(1,S)})}const Xo={[P.log]:_.info,[P.debug]:_.debug,[P.info]:_.info,[P.warn]:_.warn,[P.error]:_.error};function Wo(t,e){const s=io(t.forwardConsoleLogs).subscribe(r=>{var n;const o={rawLogsEvent:{date:J(),message:r.message,origin:X.CONSOLE,error:r.error&&at(r.error),status:Xo[r.api]},messageContext:(n=r.error)===null||n===void 0?void 0:n.context,domainContext:{handlingStack:r.handlingStack}};e.notify(0,o)});return{stop:()=>{s.unsubscribe()}}}function Yo(t,e){const s=ni(t,t.forwardReports).subscribe(r=>{let n=r.message,o;const i=r.originalError.type==="deprecation"?_.warn:_.error;i===_.error?o=at(r):r.stack&&(n+=\` Found in \${Jn(r.stack)}\`),e.notify(0,{rawLogsEvent:{date:J(),message:n,origin:X.REPORT,error:o,status:i}})});return{stop:()=>{s.unsubscribe()}}}function Ho(t,e){if(!t.forwardErrorsToLogs)return{stop:te};const s=Zi(t).subscribe(o=>{o.state==="complete"&&n("xhr",o)}),r=Zr().subscribe(o=>{o.state==="resolve"&&n("fetch",o)});function n(o,i){!yn(i.url)&&(jo(i)||Gr(i.status))&&("xhr"in i?$o(i.xhr,t,a):i.response?zo(i.response,t,a):i.error&&Vo(i.error,t,a));function a(c){const u={isAborted:i.isAborted,handlingStack:i.handlingStack};e.notify(0,{rawLogsEvent:{message:\`\${qo(o)} error \${i.method} \${i.url}\`,date:i.startClocks.timeStamp,error:{stack:c||"Failed to load",handling:void 0},http:{method:i.method,status_code:i.status,url:i.url},status:_.error,origin:X.NETWORK},domainContext:u})}}return{stop:()=>{s.unsubscribe(),r.unsubscribe()}}}function $o(t,e,s){typeof t.response=="string"?s(zt(t.response,e)):s(t.response)}function Vo(t,e,s){s(zt(de(j(t)),e))}function zo(t,e,s){const r=Oi(t);!r||!r.body?s():window.TextDecoder?Ko(r.body,e.requestErrorResponseLengthLimit,(n,o)=>{s(n?\`Unable to retrieve response: \${n}\`:o)}):r.text().then(y(n=>s(zt(n,e))),y(n=>s(\`Unable to retrieve response: \${n}\`)))}function jo(t){return t.status===0&&t.responseType!=="opaque"}function zt(t,e){return t.length>e.requestErrorResponseLengthLimit?\`\${t.substring(0,e.requestErrorResponseLengthLimit)}...\`:t}function qo(t){return t==="xhr"?"XHR":"Fetch"}function Ko(t,e,s){Ao(t,(r,n,o)=>{if(r)s(r);else{let i=new TextDecoder().decode(n);o&&(i+="..."),s(void 0,i)}},{bytesLimit:e,collectStreamBody:!0})}function Zo(t,e){if(!t.forwardErrorsToLogs)return{stop:te};const s=new B,{stop:r}=Qn(s),n=s.subscribe(o=>{e.notify(0,{rawLogsEvent:{message:o.message,date:o.startClocks.timeStamp,error:at(o),origin:X.SOURCE,status:_.error},messageContext:o.context})});return{stop:()=>{r(),n.unsubscribe()}}}const Jo=qi;function Qo(t){function e(s,r,n,o,i){const a=_e(r.getContext(),s.context);if(ot(s.status,Me.console,r)&&ta(s,a),ot(s.status,Me.http,r)){const c={rawLogsEvent:{date:i||J(),message:s.message,status:s.status,origin:X.LOGGER},messageContext:a,savedCommonContext:o};n&&(c.domainContext={handlingStack:n}),t.notify(0,c)}}return{handleLog:e}}const ea={[_.ok]:P.debug,[_.debug]:P.debug,[_.info]:P.info,[_.notice]:P.info,[_.warn]:P.warn,[_.error]:P.error,[_.critical]:P.error,[_.alert]:P.error,[_.emerg]:P.error};function ta({status:t,message:e},s){ie[ea[t]].call(H,e,s)}function ra(t,e,s,r,n){const o=Kr(t,{endpoint:t.logsEndpointBuilder,encoder:nt()},t.replica&&{endpoint:t.replica.logsEndpointBuilder,encoder:nt()},s,r,n.expireObservable);return e.subscribe(1,i=>{o.add(i)}),o}function sa(t){const e=kt();t.subscribe(1,s=>{e.send("log",s)})}function na(t){return{get:e=>{const s=t.findTrackedSession(e);if(s)return{session_id:s.id}}}}function ia(t){return e=>{t.notify(0,{rawLogsEvent:{message:e.message,date:e.startClocks.timeStamp,origin:X.AGENT,status:_.error}}),Nr("Error reported to customer",{"error.message":e.message})}}function oa(t,e,s,r,n){const o=pi("browser-logs-sdk",e);o.setContextProvider(()=>{var a,c,u,l,d,f;return{application:{id:(a=ct())===null||a===void 0?void 0:a.application_id},session:{id:(c=n.findTrackedSession())===null||c===void 0?void 0:c.id},view:{id:(l=(u=ct())===null||u===void 0?void 0:u.view)===null||l===void 0?void 0:l.id},action:{id:(f=(d=ct())===null||d===void 0?void 0:d.user_action)===null||f===void 0?void 0:f.id}}});const i=[];if(rt()){const a=kt(),c=o.observable.subscribe(u=>a.send("internal_telemetry",u));i.push(()=>c.unsubscribe())}else{const a=Kr(e,{endpoint:e.rumEndpointBuilder,encoder:nt()},e.replica&&{endpoint:e.replica.rumEndpointBuilder,encoder:nt()},s,r,n.expireObservable);i.push(()=>a.stop());const c=o.observable.subscribe(u=>a.add(u,Ti(e)));i.push(()=>c.unsubscribe())}return Ei(),Ai(Uo(t)),{telemetry:o,stop:()=>{i.forEach(a=>a())}}}function aa(t,e,s,r){const n=new Jo,o=[];n.subscribe(1,f=>Or("logs",f));const i=ia(n),a=$i(e),c=e.sessionStoreStrategyType&&!rt()&&!Qr()?Mo(e,r):Bo(e),{stop:u}=oa(t,e,i,a,c);o.push(()=>u()),Ho(e,n),Zo(e,n),Wo(e,n),Yo(e,n);const{handleLog:l}=Qo(n);if(Go(c,e,n,s,i),rt())sa(n);else{const{stop:f}=ra(e,n,i,a,c);o.push(()=>f())}const d=na(c);return{handleLog:l,getInternalContext:d.get,stop:()=>{o.forEach(f=>f())}}}const Re=Co(aa);si(ee(),"DD_LOGS",Re);const N=class N{constructor(e,s,r,n,o){this.copy=()=>new N(this.h,this.m,this.s,this.f,this.field),this.print=()=>{const i=":";let a=("0"+this.h).slice(-2)+i+("0"+this.m).slice(-2)+i+("0"+this.s).slice(-2)+i+("0"+this.f).slice(-2);return a+="."+(this.field?"1":"2"),a},this.toZipTimeCodeString=()=>{const i=this.copy();return i.f=0,i.s=i.s%2===0?i.s:i.s-1,i.field=0,N.toStr(i)},this.toFrames=i=>{let a=60,c=0;Math.floor(i)==60?(a=60,c=0):Math.floor(i)==59?(a=60,c=4):Math.floor(i)==30?(a=30,c=0):Math.floor(i)==29&&(a=30,c=2);let u=this.h,l=this.m,d=this.s,f=this.f,m=this.field;const p=u*60+l,h=(p-Math.floor(p/10))*c;return u*(a*3600)+l*(a*60)+d*a+(f*2+m)-h},this.addSeconds=i=>{let a=this.copy();if(a.s+=i,a.s>=60){const c=Math.floor(a.s/60);if(a.s=a.s%60,a.m+=c,a.m>=60){const u=Math.floor(a.m/60);a.m=a.m%60,a.h+=u}}return a},this.addFrames=(i,a)=>{let c=this.toFrames(a);return c+=i,N.fromFrames(c,a)},this.subtractFrames=(i,a)=>this.addFrames(-i,a),this.h=e||0,this.m=s||0,this.s=r||0,this.f=n||0,this.field=o||0}static compare(e,s){return e.h!==s.h?e.h<s.h?-1:1:e.m!==s.m?e.m<s.m?-1:1:e.s!==s.s?e.s<s.s?-1:1:e.f!==s.f?e.f<s.f?-1:1:e.field!==s.field?e.field<s.field?-1:1:0}static generateTimecodeRange(e,s,r){const n=[];let o=e;for(;N.compare(o,s)<=0;)n.push(o),o=o.addSeconds(r);return n}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(e){return this.toFrames(e)*1e3/e}};N.calculateCurrentTimeCode=e=>{var d;if(!e.video||!e.clocker||!e.gameParams)throw new Error("OTTPlayer is not initialized");const s=e.video,r=e.clocker,n=r.videoFPScalculator.getFPS(),a=(s.currentTime-r.syncPoint.playerTime)%(60*60*24)*n+r.syncPoint.frame;if(a===0||n===0)throw new Error("Current frame is 0 or fps is 0");const c=N.calculateCurrentOffset(a,(d=e.gameParams)==null?void 0:d.offsets);if(c===void 0)throw new Error("Offset is undefined");let u=Math.floor(a-c);return u<0&&(u+=5178816),u>=5178816&&(u-=5178816),N.fromFrames(u,n)},N.calculateCurrentOffset=(e,s)=>{for(let r=1;r<s.length;r++)if(e<s[r].frame)return s[r-1].offset;return Math.abs(s[s.length-1].offset)},N.fromFrames=(e,s)=>{let r=60,n=0;Math.floor(s)==60?(r=60,n=0):Math.floor(s)==59?(r=60,n=4):Math.floor(s)==30?(r=30,n=0):Math.floor(s)==29&&(r=30,n=2);let o=Math.floor(s*60),i=Math.floor(s*60*10),a=i*6,c=e,u=Math.floor(c/a);c-=u*a;let l=Math.floor(c/i);c-=l*i,c>=r*60&&(c+=n*(Math.floor((c-r*60)/o)+1));let d=Math.floor(c/(r*60));c-=d*(r*60);let f=Math.floor(c/r);c-=f*r;let m=c;d+=l*10;let p=0;return p=m%2,m=Math.floor(m/2),new N(u,d,f,m,p)},N.toStr=e=>{const s="_";let r=("0"+e.h).slice(-2)+s+("0"+e.m).slice(-2)+s+("0"+e.s).slice(-2)+s+("0"+e.f).slice(-2);return e.field&&(r+="_1"),r},N.fromStr=e=>{const r=e.split("_").map(Number);if(r.length==4){const[n,o,i,a]=r;return new N(n,o,i,a,0)}else if(r.length==5){const[n,o,i,a,c]=r;return new N(n,o,i,a,c)}else throw new Error("Invalid timecode format: "+e)},N.fromMetadata=e=>{const s=/^(\\d{2}):(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d))?$/,r=e.timecode.match(s);if(!r)throw new Error("Invalid timecode format: "+e.timecode);const[,n,o,i,a,c]=r,u=Number(n),l=Number(o),d=Number(i),f=Number(a),m=c?Number(c):0;return new N(u,l,d,f,m)};let $=N;const E=class E{constructor(e){this.listenerMap=new Map,E.options=e,this.isLoggingOn=e.LOG_TO_DATADOG,this.eventTarget=new EventTarget,this.isLoggingOn&&Re.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!1,sessionSampleRate:100});const s="bb_logger_mac_uuid";let r=localStorage.getItem(s);r||(r=crypto.randomUUID(),localStorage.setItem(s,r)),E.tracking.mac=r,E.tracking.dev=\`\${e.platform}_\${e.browserName}\`,E.beatHandle||(E.options&&g(E.options,"Logger")&&console.log("[Logger] Starting tracking beat"),E.beatHandle=window.setInterval(E.flushTracking,15e3))}static setMessagePort(e){this.messagePort=e}static getMessagePort(){return this.messagePort}setLoggingOn(e){this.isLoggingOn=e}addEventListener(e,s){const r=n=>s(n);this.listenerMap.set(s,{eventName:e,wrappedListener:r}),this.eventTarget.addEventListener(e,r)}removeEventListener(e,s){const r=this.listenerMap.get(s);r&&r.eventName===e&&(this.eventTarget.removeEventListener(e,r.wrappedListener),this.listenerMap.delete(s))}removeAllEventListeners(){for(const[e,{eventName:s,wrappedListener:r}]of this.listenerMap)this.eventTarget.removeEventListener(s,r);this.listenerMap.clear()}setAttributes(e){E.processAttributes(e);for(const s in e)Re.logger.setContextProperty(s,e[s])}info(e,s){e==="didClickAd"&&this.emit("mediaSessionDidRegisterClick",{url:(s==null?void 0:s.url)||""}),e==="didToggleGlobalAugmentationDrawing"&&this.emit("mediaSessionDidUpdateGlobalAugmentationState",{isGlobalAugmentationEnabled:(s==null?void 0:s.isEnabled)||!0}),e==="didStartDrawingAugmentationMedia"&&this.emit("mediaSessionDidBeginShotRendering",s),e==="didEndDrawingAugmentationMedia"&&this.emit("mediaSessionDidEndShotRendering",s),e==="didRegisterShot"&&this.emit("mediaSessionDidRegisterShot",s),s&&E.processAttributes(s),this.isLoggingOn&&(Re.logger.info(e,s),E.options&&g(E.options,"Logger")&&console.log("[Logger] Sending info: ",e))}error(e,s){s&&E.processAttributes(s),this.isLoggingOn&&(Re.logger.error(e,s),E.tracking.err_time=Date.now().toFixed(0),E.tracking.err_desc=e+(s?\` - \${JSON.stringify(s)}\`:""),E.options&&g(E.options,"Logger")&&console.log("[Logger] Sending error: ",e))}warn(e,s){s&&E.processAttributes(s),this.isLoggingOn&&(Re.logger.warn(e,s),E.options&&g(E.options,"Logger")&&console.log("[Logger] Sending warn: ",e))}handleMessageFromWorker(e){e.actionType==="INFO"?this.info(e.message,e.attributes):e.actionType==="ERROR"?this.error(e.message,e.attributes):e.actionType==="WARN"?this.warn(e.message,e.attributes):e.actionType==="SET_ATTRIBUTES"&&e.attributes&&this.setAttributes(e.attributes)}static setAttributes(e){if(!E.messagePort){console.error("[Logger] messagePort is not set! Cannot send attributes.");return}try{E.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:e})}catch(s){console.error("[Logger] Error posting message:",s)}}static info(e,s){E.messagePort.postMessage({type:"LOG",actionType:"INFO",message:e,attributes:s})}static error(e,s){E.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:e,attributes:s})}static warn(e,s){E.messagePort.postMessage({type:"LOG",actionType:"WARN",message:e,attributes:s})}static processAttributes(e){if(e.player_version&&(E.tracking.sdk=e.player_version),e.media_id&&(E.tracking.gid=e.media_id),e.game_id&&(E.tracking.buc=e.game_id),e.bb_session_id&&(E.tracking.sid=e.bb_session_id,E.options&&g(E.options,"Logger")&&console.log("[Logger] Setting bb_session_id:",E.tracking.sid)),e.last_timecode){const r=$.fromStr(e.last_timecode);E.tracking.tc=r.print(),E.lastTimecodeMillis=r.totalMilliseconds(59.94),E.lastTimecodeMillis&&E.lastZipMillis&&(E.tracking.cache=(E.lastZipMillis-E.lastTimecodeMillis).toFixed(0))}e.last_offset&&(E.tracking.off=e.last_offset),e.last_loading_zip&&(E.tracking.zip=e.last_loading_zip+".zip",E.lastZipMillis=$.fromStr(e.last_loading_zip).totalMilliseconds(59.94),E.lastTimecodeMillis&&E.lastZipMillis&&(E.tracking.cache=(E.lastZipMillis-E.lastTimecodeMillis).toFixed(0))),e.last_rendered_frame&&(E.tracking.aug_time=Date.now().toFixed(0)),e.asset&&(E.tracking.asset=e.asset)}static objectToQuery(e){return Object.entries(e).filter(([s,r])=>r!==0&&r!=="").map(([s,r])=>\`\${encodeURIComponent(s)}=\${encodeURIComponent(String(r))}\`).join("&")}emit(e,s){const r=new CustomEvent(e,{detail:s});this.eventTarget.dispatchEvent(r)}};E.tracking={start:Date.now().toFixed(0),dev:"",sdk:"",mac:"",gid:"",sid:"",off:"",zip:"",aug_time:"",err_time:"",err_desc:"",tc:"",asset:"",cache:"",buc:""},E.lastTimecodeMillis=0,E.lastZipMillis=0,E.flushTracking=()=>{const e=Date.now().toFixed(0);E.tracking.now=e;const r=\`https://dwu3k7rrxk5s3.cloudfront.net/metrics/1.gif?\${E.objectToQuery(E.tracking)}\`;E.options&&g(E.options,"Logger")&&console.log("[Logger] Flushing tracking data:",r),fetch(r,{method:"GET",mode:"no-cors",keepalive:!0,headers:{"X-Platform":"Web"}}).catch(()=>{}),E.tracking.err_desc="",E.tracking.err_time=""};let D=E;const ca=\`
|
|
1
|
+
(function(ie,me){typeof exports=="object"&&typeof module<"u"?module.exports=me():typeof define=="function"&&define.amd?define(me):(ie=typeof globalThis<"u"?globalThis:ie||self,ie.OTTPlayer=me())})(this,function(){"use strict";const ie=t=>Math.abs(t-59.94005994005994)<20?59.94:Math.abs(t-29.97002997002997)<10?29.97:Math.abs(t-14.985014985014985)<8?14.98:0,me=t=>t>30&&t<70?59.94005994005994:t>15?29.97002997002997:t>7?14.985014985014985:0;class nt{constructor(e){this.frameDurations=[],this.frameDurationsCapacity=e,this.lastTimestamp=null}addFrameDuration(e){return this.frameDurations.push(e),this.frameDurations.length>this.frameDurationsCapacity&&this.frameDurations.shift(),this.calculateAverage()}addTimestamp(e){if(this.lastTimestamp===null)return this.lastTimestamp=e,null;const r=e-this.lastTimestamp;return this.lastTimestamp=e,this.addFrameDuration(r)}calculateAverage(){if(this.frameDurations.length===0)return 0;const r=this.frameDurations.reduce((o,a)=>o+a,0)/this.frameDurations.length,n=this.frameDurations.filter(o=>Math.abs(o-r)<=r*.2);return n.reduce((o,a)=>o+a,0)/n.length||r}getFPS(){const e=this.calculateAverage();if(e===0)return 0;const r=1/e;return me(r)}getPerciseFPS(){const e=this.calculateAverage();return e===0?0:1/e}}const U=class U{constructor(e,r,n,s,i){this.copy=()=>new U(this.h,this.m,this.s,this.f,this.field),this.print=()=>{const o=":";let a=("0"+this.h).slice(-2)+o+("0"+this.m).slice(-2)+o+("0"+this.s).slice(-2)+o+("0"+this.f).slice(-2);return a+="."+(this.field?"1":"2"),a},this.toZipTimeCodeString=()=>{const o=this.copy();return o.f=0,o.s=o.s%2===0?o.s:o.s-1,o.field=0,U.toStr(o)},this.toFrames=o=>{let a=60,c=0;Math.floor(o)==60?(a=60,c=0):Math.floor(o)==59?(a=60,c=4):Math.floor(o)==30?(a=30,c=0):Math.floor(o)==29&&(a=30,c=2);let d=this.h,l=this.m,u=this.s,f=this.f,p=this.field;const h=d*60+l,g=(h-Math.floor(h/10))*c;return d*(a*3600)+l*(a*60)+u*a+(f*2+p)-g},this.addSeconds=o=>{let a=this.copy();if(a.s+=o,a.s>=60){const c=Math.floor(a.s/60);if(a.s=a.s%60,a.m+=c,a.m>=60){const d=Math.floor(a.m/60);a.m=a.m%60,a.h+=d}}return a},this.addFrames=(o,a)=>{let c=this.toFrames(a);return c+=o,U.fromFrames(c,a)},this.subtractFrames=(o,a)=>this.addFrames(-o,a),this.h=e||0,this.m=r||0,this.s=n||0,this.f=s||0,this.field=i||0}static compare(e,r){return e.h!==r.h?e.h<r.h?-1:1:e.m!==r.m?e.m<r.m?-1:1:e.s!==r.s?e.s<r.s?-1:1:e.f!==r.f?e.f<r.f?-1:1:e.field!==r.field?e.field<r.field?-1:1:0}static generateTimecodeRange(e,r,n){const s=[];let i=e;for(;U.compare(i,r)<=0;)s.push(i),i=i.addSeconds(n);return s}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(e){return this.toFrames(e)*1e3/e}};U.calculateCurrentTimeCode=e=>{var u;if(!e.video||!e.clocker||!e.gameParams)throw new Error("OTTPlayer is not initialized");const r=e.video,n=e.clocker,s=n.videoFPScalculator.getFPS(),a=(r.currentTime-n.syncPoint.playerTime)%(60*60*24)*s+n.syncPoint.frame;if(a===0||s===0)throw new Error("Current frame is 0 or fps is 0");const c=U.calculateCurrentOffset(a,(u=e.gameParams)==null?void 0:u.offsets);if(c===void 0)throw new Error("Offset is undefined");let d=Math.floor(a-c);return d<0&&(d+=5178816),d>=5178816&&(d-=5178816),U.fromFrames(d,s)},U.calculateCurrentOffset=(e,r)=>{for(let n=1;n<r.length;n++)if(e<r[n].frame)return r[n-1].offset;return Math.abs(r[r.length-1].offset)},U.fromFrames=(e,r)=>{let n=60,s=0;Math.floor(r)==60?(n=60,s=0):Math.floor(r)==59?(n=60,s=4):Math.floor(r)==30?(n=30,s=0):Math.floor(r)==29&&(n=30,s=2);let i=Math.floor(r*60),o=Math.floor(r*60*10),a=o*6,c=e,d=Math.floor(c/a);c-=d*a;let l=Math.floor(c/o);c-=l*o,c>=n*60&&(c+=s*(Math.floor((c-n*60)/i)+1));let u=Math.floor(c/(n*60));c-=u*(n*60);let f=Math.floor(c/n);c-=f*n;let p=c;u+=l*10;let h=0;return h=p%2,p=Math.floor(p/2),new U(d,u,f,p,h)},U.toStr=e=>{const r="_";let n=("0"+e.h).slice(-2)+r+("0"+e.m).slice(-2)+r+("0"+e.s).slice(-2)+r+("0"+e.f).slice(-2);return e.field&&(n+="_1"),n},U.fromStr=e=>{const n=e.split("_").map(Number);if(n.length==4){const[s,i,o,a]=n;return new U(s,i,o,a,0)}else if(n.length==5){const[s,i,o,a,c]=n;return new U(s,i,o,a,c)}else throw new Error("Invalid timecode format: "+e)},U.fromMetadata=e=>{const r=/^(\d{2}):(\d{2}):(\d{2}):(\d{2})(?:\.(\d))?$/,n=e.timecode.match(r);if(!n)throw new Error("Invalid timecode format: "+e.timecode);const[,s,i,o,a,c]=n,d=Number(s),l=Number(i),u=Number(o),f=Number(a),p=c?Number(c):0;return new U(d,l,u,f,p)};let L=U;const tn=async(t,e)=>{e&&Object.assign(t,e);let r;typeof document>"u"?r=new URL(self.location.href):r=new URL(document.location.href);const n=r.searchParams.get("config");if(n){let s;if(rn(n))s=await(await fetch(n)).json();else try{s=JSON.parse(decodeURIComponent(n))}catch(i){console.error("Failed to parse config parameter as JSON:",i);return}Object.assign(t,s)}},rn=t=>{try{return new URL(t),!0}catch{return!1}},_=(t,e)=>e==="Errors"?!0:!t.debug||!t.debug.on?!1:t.debug[`log${e}`];class nn{constructor(e){this.last10=[],this.errorsInProgress=[],this.lastFrameTC=null,this.fps=e}setFPS(e){this.fps=e}timecodeRecieved(e){if(!e)return;const r=L.fromStr(e);if(this.last10.push(r),this.last10.length>10&&this.last10.shift(),this.lastFrameTC){const n=this.incrementInterlaced(this.lastFrameTC);L.compare(r,n)!==0&&(console.warn("Timecode sequence is invalid! Detected at:",e),this.errorsInProgress.push({preTCs:[...this.last10],postTCs:[],framesAfter:0,printed:!1}))}for(const n of this.errorsInProgress)n.printed||(n.postTCs.push(r),n.framesAfter++);for(const n of this.errorsInProgress)if(!n.printed&&n.framesAfter>=10){console.error("Full 20-frame sequence around error:");const s=[...n.preTCs,...n.postTCs];console.error(s.map(i=>L.toStr(i))),n.printed=!0}this.lastFrameTC=r}incrementInterlaced(e){const r=e.copy();return r.field===0?(r.field=1,r):(r.field=0,r.f++,r.f>=30&&(r.f=0,r.s++,r.s>=60&&(r.s=0,r.m++,r.m>=60&&(r.m=0,r.h++))),r)}}class sn{constructor(e,r){this.click=async n=>{const s=this.video.getBoundingClientRect(),i=(n.clientX-s.left)/s.width,o=(n.clientY-s.top)/s.height,a={x:i,y:o};this.renderer.postMessage({type:"VIDEO_CLICK",clickData:a})},this.video=e.video,this.logger=e.logger,this.renderer=r,this.renderer.onmessage=n=>{if(n.data.type==="OPEN_URL"){const s=n.data.url;s&&(window.open(s,"_blank"),this.logger.info("didClickAd",{url:s}))}}}}const Bt='(function(){"use strict";const w=(e,t)=>t==="Errors"?!0:!e.debug||!e.debug.on?!1:e.debug[`log${t}`],T={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},x=console,W={};Object.keys(T).forEach(e=>{W[e]=x[e]});const fe="Datadog Browser SDK:",_={debug:W.debug.bind(x,fe),log:W.log.bind(x,fe),info:W.info.bind(x,fe),warn:W.warn.bind(x,fe),error:W.error.bind(x,fe)},Xe="https://docs.datadoghq.com",vt=`${Xe}/real_user_monitoring/browser/troubleshooting`,Re="More details:";function Lt(e,t){return(...n)=>{try{return e(...n)}catch(r){_.error(t,r)}}}function Ce(e){return e!==0&&Math.random()*100<=e}function Fn(e){return Un(e)&&e>=0&&e<=100}function Un(e){return typeof e=="number"}const pe=1e3,K=60*pe,It=60*K,Bn=365*(24*It);function he(){return new Date().getTime()}function F(){return he()}function ve(){return performance.now()}function U(){return{relative:ve(),timeStamp:F()}}function Gn(){return{relative:0,timeStamp:At()}}function jn(e,t){return t-e}function Hn(e,t){return e+t}function zn(e){return e-At()}let Ve;function At(){return Ve===void 0&&(Ve=performance.timing.navigationStart),Ve}const D=1024,kt=1024*D,Wn=/[^\\u0000-\\u007F]/;function Qe(e){return Wn.test(e)?window.TextEncoder!==void 0?new TextEncoder().encode(e).length:new Blob([e]).size:e.length}function Kn(e){return{...e}}function xt(e,t){return Object.keys(e).some(n=>e[n]===t)}function me(e){return Object.keys(e).length===0}function B(){if(typeof globalThis=="object")return globalThis;Object.defineProperty(Object.prototype,"_dd_temp_",{get(){return this},configurable:!0});let e=_dd_temp_;return delete Object.prototype._dd_temp_,typeof e!="object"&&(typeof self=="object"?e=self:typeof window=="object"?e=window:e={}),e}function ne(e,t){const n=B();let r;return n.Zone&&typeof n.Zone.__symbol__=="function"&&(r=e[n.Zone.__symbol__(t)]),r||(r=e[t]),r}let Le,Dt=!1;function Jn(e){Le=e}function qn(e){Dt=e}function Yn(e,t,n){const r=n.value;n.value=function(...o){return(Le?y(r):r).apply(this,o)}}function y(e){return function(){return ge(e,this,arguments)}}function ge(e,t,n){try{return e.apply(t,n)}catch(r){Zn(r)}}function Zn(e){if(et(e),Le)try{Le(e)}catch(t){et(t)}}function et(...e){Dt&&_.error("[MONITOR]",...e)}function Se(e,t){return ne(B(),"setTimeout")(y(e),t)}function Mt(e){ne(B(),"clearTimeout")(e)}function tt(e,t){return ne(B(),"setInterval")(y(e),t)}function Nt(e){ne(B(),"clearInterval")(e)}class O{constructor(t){this.onFirstSubscribe=t,this.observers=[]}subscribe(t){return this.observers.push(t),this.observers.length===1&&this.onFirstSubscribe&&(this.onLastUnsubscribe=this.onFirstSubscribe(this)||void 0),{unsubscribe:()=>{this.observers=this.observers.filter(n=>t!==n),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}}notify(t){this.observers.forEach(n=>n(t))}}function $t(...e){return new O(t=>{const n=e.map(r=>r.subscribe(o=>t.notify(o)));return()=>n.forEach(r=>r.unsubscribe())})}function Pt(e,t,n){let r=!1,o,s;return{throttled:(...i)=>{if(r){o=i;return}e(...i),r=!0,s=Se(()=>{o&&e(...o),r=!1,o=void 0},t)},cancel:()=>{Mt(s),r=!1,o=void 0}}}function G(){}function j(e){return e?(parseInt(e,10)^Math.random()*16>>parseInt(e,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,j)}const Ie=/([\\w-]+)\\s*=\\s*([^;]+)/g;function Xn(e,t){for(Ie.lastIndex=0;;){const n=Ie.exec(e);if(n){if(n[1]===t)return n[2]}else break}}function Vn(e){const t=new Map;for(Ie.lastIndex=0;;){const n=Ie.exec(e);if(n)t.set(n[1],n[2]);else break}return t}function Qn(e,t,n=""){const r=e.charCodeAt(t-1),s=r>=55296&&r<=56319?t+1:t;return e.length<=s?e:`${e.slice(0,s)}${n}`}function er(){return tr()===0}let Ae;function tr(){return Ae??(Ae=nr())}function nr(e=window){var t;const n=e.navigator.userAgent;return e.chrome||/HeadlessChrome/.test(n)?0:((t=e.navigator.vendor)===null||t===void 0?void 0:t.indexOf("Apple"))===0||/safari/i.test(n)&&!/chrome|android/i.test(n)?1:2}function ye(e,t,n=0,r){const o=new Date;o.setTime(o.getTime()+n);const s=`expires=${o.toUTCString()}`,i=r&&r.crossSite?"none":"strict",a=r&&r.domain?`;domain=${r.domain}`:"",c=r&&r.secure?";secure":"",l=r&&r.partitioned?";partitioned":"";document.cookie=`${e}=${t};${s};path=/;samesite=${i}${a}${c}${l}`}function nt(e){return Xn(document.cookie,e)}let rt;function J(e){return rt||(rt=Vn(document.cookie)),rt.get(e)}function Ft(e,t){ye(e,"",0,t)}function rr(e){if(document.cookie===void 0||document.cookie===null)return!1;try{const t=`dd_cookie_test_${j()}`,n="test";ye(t,n,K,e);const r=nt(t)===n;return Ft(t,e),r}catch(t){return _.error(t),!1}}let ot;function or(){if(ot===void 0){const e=`dd_site_test_${j()}`,t="test",n=window.location.hostname.split(".");let r=n.pop();for(;n.length&&!nt(e);)r=`${n.pop()}.${r}`,ye(e,t,pe,{domain:r});Ft(e,{domain:r}),ot=r}return ot}const re="_dd_s";function ke(e){return Object.values(e)}function sr(e){return Object.entries(e)}const st=4*It,Ut=15*K,ir=Bn,be={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},Bt=/^([a-zA-Z]+)=([a-z0-9-]+)$/,it="&";function ar(e){return!!e&&(e.indexOf(it)!==-1||Bt.test(e))}const cr="1";function q(e,t){const n={isExpired:cr};return t.trackAnonymousUser&&(e!=null&&e.anonymousId?n.anonymousId=e==null?void 0:e.anonymousId:n.anonymousId=j()),n}function xe(e){return me(e)}function Gt(e){return!xe(e)}function De(e){return e.isExpired!==void 0||!ur(e)}function ur(e){return(e.created===void 0||he()-Number(e.created)<st)&&(e.expire===void 0||he()<Number(e.expire))}function jt(e){e.expire=String(he()+Ut)}function at(e){return sr(e).map(([t,n])=>t==="anonymousId"?`aid=${n}`:`${t}=${n}`).join(it)}function Ht(e){const t={};return ar(e)&&e.split(it).forEach(n=>{const r=Bt.exec(n);if(r!==null){const[,o,s]=r;o==="aid"?t.anonymousId=s:t[o]=s}}),t}const lr="_dd",dr="_dd_r",fr="_dd_l",pr="rum",hr="logs";function mr(e){if(!J(re)){const n=J(lr),r=J(dr),o=J(fr),s={};n&&(s.id=n),o&&/^[01]$/.test(o)&&(s[hr]=o),r&&/^[012]$/.test(r)&&(s[pr]=r),Gt(s)&&(jt(s),e.persistSession(s))}}function zt(e){const t=Er(e);return rr(t)?{type:be.COOKIE,cookieOptions:t}:void 0}function gr(e,t){const n={isLockEnabled:er(),persistSession:Sr(t),retrieveSession:br,expireSession:r=>yr(t,r,e)};return mr(n),n}function Sr(e){return t=>{ye(re,at(t),Ut,e)}}function yr(e,t,n){const r=q(t,n);ye(re,at(r),n.trackAnonymousUser?ir:st,e)}function br(){const e=nt(re);return Ht(e)}function Er(e){const t={};return t.secure=!!e.useSecureSessionCookie||!!e.usePartitionedCrossSiteSessionCookie,t.crossSite=!!e.usePartitionedCrossSiteSessionCookie,t.partitioned=!!e.usePartitionedCrossSiteSessionCookie,e.trackSessionAcrossSubdomains&&(t.domain=or()),t}const Tr="_dd_test_";function Wt(){try{const e=j(),t=`${Tr}${e}`;localStorage.setItem(t,e);const n=localStorage.getItem(t);return localStorage.removeItem(t),e===n?{type:be.LOCAL_STORAGE}:void 0}catch{return}}function _r(e){return{isLockEnabled:!1,persistSession:Kt,retrieveSession:wr,expireSession:t=>Or(t,e)}}function Kt(e){localStorage.setItem(re,at(e))}function wr(){const e=localStorage.getItem(re);return Ht(e)}function Or(e,t){Kt(q(e,t))}const Rr=10,Cr=100,Jt=[];let Me;function Y(e,t,n=0){var r;const{isLockEnabled:o,persistSession:s,expireSession:i}=t,a=f=>s({...f,lock:l}),c=()=>{const f=t.retrieveSession(),h=f.lock;return f.lock&&delete f.lock,{session:f,lock:h}};if(Me||(Me=e),e!==Me){Jt.push(e);return}if(o&&n>=Cr){qt(t);return}let l,u=c();if(o){if(u.lock){Ne(e,t,n);return}if(l=j(),a(u.session),u=c(),u.lock!==l){Ne(e,t,n);return}}let d=e.process(u.session);if(o&&(u=c(),u.lock!==l)){Ne(e,t,n);return}if(d&&(De(d)?i(d):(jt(d),o?a(d):s(d))),o&&!(d&&De(d))){if(u=c(),u.lock!==l){Ne(e,t,n);return}s(u.session),d=u.session}(r=e.after)===null||r===void 0||r.call(e,d||u.session),qt(t)}function Ne(e,t,n){Se(()=>{Y(e,t,n+1)},Rr)}function qt(e){Me=void 0;const t=Jt.shift();t&&Y(t,e)}const Yt=pe;function vr(e){switch(e.sessionPersistence){case be.COOKIE:return zt(e);case be.LOCAL_STORAGE:return Wt();case void 0:{let t=zt(e);return!t&&e.allowFallbackToLocalStorage&&(t=Wt()),t}default:_.error(`Invalid session persistence \'${String(e.sessionPersistence)}\'`)}}function Lr(e,t,n,r){const o=new O,s=new O,i=new O,a=e.type===be.COOKIE?gr(t,e.cookieOptions):_r(t),{expireSession:c}=a,l=tt(m,Yt);let u;E();const{throttled:d,cancel:f}=Pt(()=>{Y({process:S=>{if(xe(S))return;const de=b(S);return z(de),de},after:S=>{Gt(S)&&!v()&&Mi(S),u=S}},a)},Yt);function h(){Y({process:S=>v()?b(S):void 0},a)}function m(){Y({process:S=>De(S)?q(S,t):void 0,after:b},a)}function b(S){return De(S)&&(S=q(S,t)),v()&&(te(S)?Di():(i.notify({previousState:u,newState:S}),u=S)),S}function E(){Y({process:S=>{if(xe(S))return q(S,t)},after:S=>{u=S}},a)}function z(S){if(xe(S))return!1;const{trackingType:de,isTracked:$i}=r(S[n]);S[n]=de,delete S.isExpired,$i&&!S.id&&(S.id=j(),S.created=String(he()))}function v(){return u[n]!==void 0}function te(S){return u.id!==S.id||u[n]!==S[n]}function Di(){u=q(u,t),s.notify()}function Mi(S){u=S,o.notify()}function Ni(S){Y({process:de=>({...de,...S}),after:b},a)}return{expandOrRenewSession:d,expandSession:h,getSession:()=>u,renewObservable:o,expireObservable:s,sessionStateUpdateObservable:i,restartSession:E,expire:()=>{f(),c(u),b(q(u,t))},stop:()=>{Nt(l)},updateSessionState:Ni}}const ct={GRANTED:"granted",NOT_GRANTED:"not-granted"};function Ir(e){const t=new O;return{tryToInit(n){e||(e=n)},update(n){e=n,t.notify()},isGranted(){return e===ct.GRANTED},observable:t}}function Z(e,t,n){if(typeof e!="object"||e===null)return JSON.stringify(e);const r=oe(Object.prototype),o=oe(Array.prototype),s=oe(Object.getPrototypeOf(e)),i=oe(e);try{return JSON.stringify(e,t,n)}catch{return"<error: unable to serialize object>"}finally{r(),o(),s(),i()}}function oe(e){const t=e,n=t.toJSON;return n?(delete t.toJSON,()=>{t.toJSON=n}):G}function ut(e){return Ar(e,location.href).href}function Ar(e,t){const n=kr();if(n)try{return t!==void 0?new n(e,t):new n(e)}catch(s){throw new Error(`Failed to construct URL: ${String(s)} ${Z({url:e,base:t})}`)}if(t===void 0&&!/:/.test(e))throw new Error(`Invalid URL: \'${e}\'`);let r=document;const o=r.createElement("a");if(t!==void 0){r=document.implementation.createHTMLDocument("");const s=r.createElement("base");s.href=t,r.head.appendChild(s),r.body.appendChild(o)}return o.href=e,o}const Zt=URL;let $e;function kr(){if($e===void 0)try{$e=new Zt("http://test/path").href==="http://test/path"}catch{$e=!1}return $e?Zt:void 0}const xr="datad0g.com",Dr="dd0g-gov.com",se="datadoghq.com",Mr="ddog-gov.com",Nr="pci.browser-intake-datadoghq.com",$r=["ddsource","ddtags"];function Ee(e,t,n){const r=Pr(e,t);return{build(o,s){const i=Ur(e,t,n,o,s);return r(i)},urlPrefix:r(""),trackType:t}}function Pr(e,t){const n=`/api/v2/${t}`,r=e.proxy;if(typeof r=="string"){const s=ut(r);return i=>`${s}?ddforward=${encodeURIComponent(`${n}?${i}`)}`}if(typeof r=="function")return s=>r({path:n,parameters:s});const o=Fr(t,e);return s=>`https://${o}${n}?${s}`}function Fr(e,t){const{site:n=se,internalAnalyticsSubdomain:r}=t;if(e==="logs"&&t.usePciIntake&&n===se)return Nr;if(r&&n===se)return`${r}.${se}`;if(n===Dr)return`http-intake.logs.${n}`;const o=n.split("."),s=o.pop();return`browser-intake-${o.join("-")}.${s}`}function Ur({clientToken:e,internalAnalyticsSubdomain:t},n,r,o,{retry:s,encoding:i}){const a=["sdk_version:6.5.0",`api:${o}`].concat(r);s&&a.push(`retry_count:${s.count}`,`retry_after:${s.lastFailureStatus}`);const c=["ddsource=browser",`ddtags=${encodeURIComponent(a.join(","))}`,`dd-api-key=${e}`,`dd-evp-origin-version=${encodeURIComponent("6.5.0")}`,"dd-evp-origin=browser",`dd-request-id=${j()}`];return i&&c.push(`dd-evp-encoding=${i}`),n==="rum"&&c.push(`batch_time=${F()}`),t&&c.reverse(),c.join("&")}const Br=200;function Gr(e){const{env:t,service:n,version:r,datacenter:o}=e,s=[];return t&&s.push(Pe("env",t)),n&&s.push(Pe("service",n)),r&&s.push(Pe("version",r)),o&&s.push(Pe("datacenter",o)),s}function Pe(e,t){const n=Br-e.length-1;(t.length>n||jr(t))&&_.warn(`${e} value doesn\'t meet tag requirements and will be sanitized. ${Re} ${Xe}/getting_started/tagging/#defining-tags`);const r=t.replace(/,/g,"_");return`${e}:${r}`}function jr(e){return Hr()?new RegExp("[^\\\\p{Ll}\\\\p{Lo}0-9_:./-]","u").test(e):!1}function Hr(){try{return new RegExp("[\\\\p{Ll}]","u"),!0}catch{return!1}}function zr(e){const t=e.site||se,n=Gr(e),r=Wr(e,n);return{replica:Kr(e,n),site:t,...r}}function Wr(e,t){return{logsEndpointBuilder:Ee(e,"logs",t),rumEndpointBuilder:Ee(e,"rum",t),sessionReplayEndpointBuilder:Ee(e,"replay",t)}}function Kr(e,t){if(!e.replica)return;const n={...e,site:se,clientToken:e.replica.clientToken},r={logsEndpointBuilder:Ee(n,"logs",t),rumEndpointBuilder:Ee(n,"rum",t)};return{applicationId:e.replica.applicationId,...r}}function Jr(e){return $r.every(t=>e.includes(t))}function lt(e,t){return e!=null&&typeof e!="string"?(_.error(`${t} must be defined as a string`),!1):!0}function qr(e){return e&&typeof e=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(e)?(_.error(`Site should be a valid Datadog site. ${Re} ${Xe}/getting_started/site/.`),!1):!0}function Fe(e,t){return e!==void 0&&!Fn(e)?(_.error(`${t} Sample Rate should be a number between 0 and 100`),!1):!0}function Yr(e){var t,n,r,o,s,i;if(!e||!e.clientToken){_.error("Client Token is not configured, we will not send any data.");return}if(!(!qr(e.site)||!Fe(e.sessionSampleRate,"Session")||!Fe(e.telemetrySampleRate,"Telemetry")||!Fe(e.telemetryConfigurationSampleRate,"Telemetry Configuration")||!Fe(e.telemetryUsageSampleRate,"Telemetry Usage")||!lt(e.version,"Version")||!lt(e.env,"Env")||!lt(e.service,"Service"))){if(e.trackingConsent!==void 0&&!xt(ct,e.trackingConsent)){_.error(\'Tracking Consent should be either "granted" or "not-granted"\');return}return{beforeSend:e.beforeSend&&Lt(e.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:vr(e),sessionSampleRate:(t=e.sessionSampleRate)!==null&&t!==void 0?t:100,telemetrySampleRate:(n=e.telemetrySampleRate)!==null&&n!==void 0?n:20,telemetryConfigurationSampleRate:(r=e.telemetryConfigurationSampleRate)!==null&&r!==void 0?r:5,telemetryUsageSampleRate:(o=e.telemetryUsageSampleRate)!==null&&o!==void 0?o:5,service:e.service||void 0,silentMultipleInit:!!e.silentMultipleInit,allowUntrustedEvents:!!e.allowUntrustedEvents,trackingConsent:(s=e.trackingConsent)!==null&&s!==void 0?s:ct.GRANTED,trackAnonymousUser:(i=e.trackAnonymousUser)!==null&&i!==void 0?i:!0,storeContextsAcrossPages:!!e.storeContextsAcrossPages,batchBytesLimit:16*D,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*pe,batchMessagesLimit:50,messageBytesLimit:256*D,...zr(e)}}}function Zr(e){return{session_sample_rate:e.sessionSampleRate,telemetry_sample_rate:e.telemetrySampleRate,telemetry_configuration_sample_rate:e.telemetryConfigurationSampleRate,telemetry_usage_sample_rate:e.telemetryUsageSampleRate,use_before_send:!!e.beforeSend,use_partitioned_cross_site_session_cookie:e.usePartitionedCrossSiteSessionCookie,use_secure_session_cookie:e.useSecureSessionCookie,use_proxy:!!e.proxy,silent_multiple_init:e.silentMultipleInit,track_session_across_subdomains:e.trackSessionAcrossSubdomains,track_anonymous_user:e.trackAnonymousUser,session_persistence:e.sessionPersistence,allow_fallback_to_local_storage:!!e.allowFallbackToLocalStorage,store_contexts_across_pages:!!e.storeContextsAcrossPages,allow_untrusted_events:!!e.allowUntrustedEvents,tracking_consent:e.trackingConsent}}var dt;(function(e){e.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",e.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(dt||(dt={}));const Xt=new Set;function Xr(e){Array.isArray(e)&&Vr(e.filter(t=>xt(dt,t)))}function Vr(e){e.forEach(t=>{Xt.add(t)})}function Qr(){return Xt}const Te="?";function M(e){const t=[];let n=ft(e,"stack");const r=String(e);return n&&n.startsWith(r)&&(n=n.slice(r.length)),n&&n.split(`\n`).forEach(o=>{const s=no(o)||oo(o)||io(o)||uo(o);s&&(!s.func&&s.line&&(s.func=Te),t.push(s))}),{message:ft(e,"message"),name:ft(e,"name"),stack:t}}const Vt="((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\\\w+\\\\.|\\\\/).*?)",ie="(?::(\\\\d+))",eo=new RegExp(`^\\\\s*at (.*?) ?\\\\(${Vt}${ie}?${ie}?\\\\)?\\\\s*$`,"i"),to=new RegExp(`\\\\((\\\\S*)${ie}${ie}\\\\)`);function no(e){const t=eo.exec(e);if(!t)return;const n=t[2]&&t[2].indexOf("native")===0,r=t[2]&&t[2].indexOf("eval")===0,o=to.exec(t[2]);return r&&o&&(t[2]=o[1],t[3]=o[2],t[4]=o[3]),{args:n?[t[2]]:[],column:t[4]?+t[4]:void 0,func:t[1]||Te,line:t[3]?+t[3]:void 0,url:n?void 0:t[2]}}const ro=new RegExp(`^\\\\s*at ?${Vt}${ie}?${ie}??\\\\s*$`,"i");function oo(e){const t=ro.exec(e);if(t)return{args:[],column:t[3]?+t[3]:void 0,func:Te,line:t[2]?+t[2]:void 0,url:t[1]}}const so=/^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;function io(e){const t=so.exec(e);if(t)return{args:[],column:t[4]?+t[4]:void 0,func:t[1]||Te,line:+t[3],url:t[2]}}const ao=/^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i,co=/(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;function uo(e){const t=ao.exec(e);if(!t)return;const n=t[3]&&t[3].indexOf(" > eval")>-1,r=co.exec(t[3]);return n&&r&&(t[3]=r[1],t[4]=r[2],t[5]=void 0),{args:t[2]?t[2].split(","):[],column:t[5]?+t[5]:void 0,func:t[1]||Te,line:t[4]?+t[4]:void 0,url:t[3]}}function ft(e,t){if(typeof e!="object"||!e||!(t in e))return;const n=e[t];return typeof n=="string"?n:void 0}function lo(e,t,n,r){const o=[{url:t,column:r,line:n}],{name:s,message:i}=po(e);return{name:s,message:i,stack:o}}const fo=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\\s\\S]*)$/;function po(e){let t,n;return{}.toString.call(e)==="[object String]"&&([,t,n]=fo.exec(e)),{name:t,message:n}}function Ue(e){const n=new Error(e);n.name="HandlingStack";let r;return ge(()=>{const o=M(n);o.stack=o.stack.slice(2),r=X(o)}),r}function X(e){let t=Qt(e);return e.stack.forEach(n=>{const r=n.func==="?"?"<anonymous>":n.func,o=n.args&&n.args.length>0?`(${n.args.join(", ")})`:"",s=n.line?`:${n.line}`:"",i=n.line&&n.column?`:${n.column}`:"";t+=`\n at ${r}${o} @ ${n.url}${s}${i}`}),t}function Qt(e){return`${e.name||"Error"}: ${e.message}`}function V(e,t,n,{computeHandlingStack:r}={}){let o=e[t];if(typeof o!="function")if(t in e&&t.startsWith("on"))o=G;else return{stop:G};let s=!1;const i=function(){if(s)return o.apply(this,arguments);const a=Array.from(arguments);let c;ge(n,null,[{target:this,parameters:a,onPostCall:u=>{c=u},handlingStack:r?Ue("instrumented method"):void 0}]);const l=o.apply(this,a);return c&&ge(c,null,[l]),l};return e[t]=i,{stop:()=>{s=!0,e[t]===i&&(e[t]=o)}}}const ho=220*D,mo="$",go=3;function N(e,t=ho){const n=oe(Object.prototype),r=oe(Array.prototype),o=[],s=new WeakMap,i=pt(e,mo,void 0,o,s),a=JSON.stringify(i);let c=a?a.length:0;if(c>t){mt(t,"discarded",e);return}for(;o.length>0&&c<t;){const l=o.shift();let u=0;if(Array.isArray(l.source))for(let d=0;d<l.source.length;d++){const f=pt(l.source[d],l.path,d,o,s);if(f!==void 0?c+=JSON.stringify(f).length:c+=4,c+=u,u=1,c>t){mt(t,"truncated",e);break}l.target[d]=f}else for(const d in l.source)if(Object.prototype.hasOwnProperty.call(l.source,d)){const f=pt(l.source[d],l.path,d,o,s);if(f!==void 0&&(c+=JSON.stringify(f).length+u+d.length+go,u=1),c>t){mt(t,"truncated",e);break}l.target[d]=f}}return n(),r(),i}function pt(e,t,n,r,o){const s=bo(e);if(!s||typeof s!="object")return So(s);const i=ht(s);if(i!=="[Object]"&&i!=="[Array]"&&i!=="[Error]")return i;const a=e;if(o.has(a))return`[Reference seen at ${o.get(a)}]`;const c=n!==void 0?`${t}.${n}`:t,l=Array.isArray(s)?[]:{};return o.set(a,c),r.push({source:s,target:l,path:c}),l}function So(e){return typeof e=="bigint"?`[BigInt] ${e.toString()}`:typeof e=="function"?`[Function] ${e.name||"unknown"}`:typeof e=="symbol"?`[Symbol] ${e.description||e.toString()}`:e}function ht(e){try{if(e instanceof Event)return yo(e);if(e instanceof RegExp)return`[RegExp] ${e.toString()}`;const n=Object.prototype.toString.call(e).match(/\\[object (.*)\\]/);if(n&&n[1])return`[${n[1]}]`}catch{}return"[Unserializable]"}function yo(e){return{type:e.type,isTrusted:e.isTrusted,currentTarget:e.currentTarget?ht(e.currentTarget):null,target:e.target?ht(e.target):null}}function bo(e){const t=e;if(t&&typeof t.toJSON=="function")try{return t.toJSON()}catch{}return e}function mt(e,t,n){_.warn(`The data provided has been ${t} as it is over the limit of ${e} characters:`,n)}const en="No stack, consider using an instance of Error";function tn({stackTrace:e,originalError:t,handlingStack:n,componentStack:r,startClocks:o,nonErrorPrefix:s,source:i,handling:a}){const c=H(t),l=Eo(e,c,s,t),u=To(c,e)?X(e):en,d=c?on(t,i):void 0,f=e?e.name:void 0,h=nn(t),m=rn(t);return{startClocks:o,source:i,handling:a,handlingStack:n,componentStack:r,originalError:t,type:f,message:l,stack:u,causes:d,fingerprint:h,context:m}}function Eo(e,t,n,r){return e!=null&&e.message&&(e!=null&&e.name)?e.message:t?"Empty message":`${n} ${Z(N(r))}`}function To(e,t){return t===void 0?!1:e?!0:t.stack.length>0&&(t.stack.length>1||t.stack[0].url!==void 0)}function nn(e){return H(e)&&"dd_fingerprint"in e?String(e.dd_fingerprint):void 0}function rn(e){if(e!==null&&typeof e=="object"&&"dd_context"in e)return e.dd_context}function _o(e){var t;return(t=/@ (.+)/.exec(e))===null||t===void 0?void 0:t[1]}function H(e){return e instanceof Error||Object.prototype.toString.call(e)==="[object Error]"}function on(e,t){let n=e;const r=[];for(;H(n==null?void 0:n.cause)&&r.length<10;){const o=M(n.cause);r.push({message:n.cause.message,source:t,type:o==null?void 0:o.name,stack:X(o)}),n=n.cause}return r.length?r:void 0}const L={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function wo(e){const t=(o,s)=>{const i=tn({stackTrace:o,originalError:s,startClocks:U(),nonErrorPrefix:"Uncaught",source:L.SOURCE,handling:"unhandled"});e.notify(i)},{stop:n}=Oo(t),{stop:r}=Ro(t);return{stop:()=>{n(),r()}}}function Oo(e){return V(window,"onerror",({parameters:[t,n,r,o,s]})=>{let i;H(s)?i=M(s):i=lo(t,n,r,o),e(i,s??t)})}function Ro(e){return V(window,"onunhandledrejection",({parameters:[t]})=>{const n=t.reason||"Empty reason",r=M(n);e(r,n)})}function Co(e){const t={version:"6.5.0",onReady(n){n()},...e};return Object.defineProperty(t,"_setDebug",{get(){return qn},enumerable:!1}),t}function vo(e,t,n){const r=e[t];r&&!r.q&&r.version&&_.warn("SDK is loaded more than once. This is unsupported and might have unexpected behavior."),e[t]=n,r&&r.q&&r.q.forEach(o=>Lt(o,"onReady callback threw an error:")())}function sn(e,t){t.silentMultipleInit||_.error(`${e} is already initialized.`)}function Q(e,t,n,r,o){return gt(e,t,[n],r,o)}function gt(e,t,n,r,{once:o,capture:s,passive:i}={}){const a=y(f=>{!f.isTrusted&&!f.__ddIsTrusted&&!e.allowUntrustedEvents||(o&&d(),r(f))}),c=i?{capture:s,passive:i}:s,l=window.EventTarget&&t instanceof EventTarget?window.EventTarget.prototype:t,u=ne(l,"addEventListener");n.forEach(f=>u.call(t,f,a,c));function d(){const f=ne(l,"removeEventListener");n.forEach(h=>f.call(t,h,a,c))}return{stop:d}}const Be={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function Lo(e,t){const n=[];t.includes(Be.cspViolation)&&n.push(Ao(e));const r=t.filter(o=>o!==Be.cspViolation);return r.length&&n.push(Io(r)),$t(...n)}function Io(e){return new O(t=>{if(!window.ReportingObserver)return;const n=y((o,s)=>o.forEach(i=>t.notify(ko(i)))),r=new window.ReportingObserver(n,{types:e,buffered:!0});return r.observe(),()=>{r.disconnect()}})}function Ao(e){return new O(t=>{const{stop:n}=Q(e,document,"securitypolicyviolation",r=>{t.notify(xo(r))});return n})}function ko(e){const{type:t,body:n}=e;return an({type:n.id,message:`${t}: ${n.message}`,originalError:e,stack:cn(n.id,n.message,n.sourceFile,n.lineNumber,n.columnNumber)})}function xo(e){const t=`\'${e.blockedURI}\' blocked by \'${e.effectiveDirective}\' directive`;return an({type:e.effectiveDirective,message:`${Be.cspViolation}: ${t}`,originalError:e,csp:{disposition:e.disposition},stack:cn(e.effectiveDirective,e.originalPolicy?`${t} of the policy "${Qn(e.originalPolicy,100,"...")}"`:"no policy",e.sourceFile,e.lineNumber,e.columnNumber)})}function an(e){return{startClocks:U(),source:L.REPORT,handling:"unhandled",...e}}function cn(e,t,n,r,o){return n?X({name:e,message:t,stack:[{func:"?",url:n,line:r??void 0,column:o??void 0}]}):void 0}function un(e,t){const n=window.__ddBrowserSdkExtensionCallback;n&&n({type:e,payload:t})}function ln(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Ge(e,t,n=Do()){if(t===void 0)return e;if(typeof t!="object"||t===null)return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=t.flags||[t.global?"g":"",t.ignoreCase?"i":"",t.multiline?"m":"",t.sticky?"y":"",t.unicode?"u":""].join("");return new RegExp(t.source,o)}if(n.hasAlreadyBeenSeen(t))return;if(Array.isArray(t)){const o=Array.isArray(e)?e:[];for(let s=0;s<t.length;++s)o[s]=Ge(o[s],t[s],n);return o}const r=ln(e)==="object"?e:{};for(const o in t)Object.prototype.hasOwnProperty.call(t,o)&&(r[o]=Ge(r[o],t[o],n));return r}function dn(e){return Ge(void 0,e)}function ae(...e){let t;for(const n of e)n!=null&&(t=Ge(t,n));return t}function Do(){if(typeof WeakSet<"u"){const t=new WeakSet;return{hasAlreadyBeenSeen(n){const r=t.has(n);return r||t.add(n),r}}}const e=[];return{hasAlreadyBeenSeen(t){const n=e.indexOf(t)>=0;return n||e.push(t),n}}}function Mo(){var e;const t=window.navigator;return{status:t.onLine?"connected":"not_connected",interfaces:t.connection&&t.connection.type?[t.connection.type]:void 0,effective_type:(e=t.connection)===null||e===void 0?void 0:e.effectiveType}}function No(e){const t=new Set;return e.forEach(n=>t.add(n)),Array.from(t)}function fn(e,t){const n=e.indexOf(t);n>=0&&e.splice(n,1)}const $o=500;function pn(){const e=[];return{add:o=>{e.push(o)>$o&&e.splice(0,1)},remove:o=>{fn(e,o)},drain:o=>{e.forEach(s=>s(o)),e.length=0}}}const ee={log:"log",configuration:"configuration",usage:"usage"},Po=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],Fo=[Mr];let hn=pn(),ce=e=>{hn.add(()=>ce(e))};function Uo(e,t){let n;const r=new O,o=new Set,s=!Fo.includes(t.site)&&Ce(t.telemetrySampleRate),i={[ee.log]:s,[ee.configuration]:s&&Ce(t.telemetryConfigurationSampleRate),[ee.usage]:s&&Ce(t.telemetryUsageSampleRate)},a=Bo();ce=l=>{const u=Z(l);if(i[l.type]&&o.size<t.maxTelemetryEventsPerPage&&!o.has(u)){const d=c(e,l,a);r.notify(d),un("telemetry",d),o.add(u)}},Jn(gn);function c(l,u,d){return ae({type:"telemetry",date:F(),service:l,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:ae(u,{runtime_env:d,connectivity:Mo(),sdk_setup:"npm"}),experimental_features:Array.from(Qr())},n!==void 0?n():{})}return{setContextProvider:l=>{n=l},observable:r,enabled:s}}function Bo(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function Go(){hn.drain()}function jo(e){return e.site===xr}function mn(e,t){et(T.debug,e,t),ce({type:ee.log,message:e,status:"debug",...t})}function gn(e,t){ce({type:ee.log,status:"error",...Wo(e),...t})}function Ho(e){ce({type:ee.configuration,configuration:e})}function zo(e){ce({type:ee.usage,usage:e})}function Wo(e){if(H(e)){const t=M(e);return{error:{kind:t.name,stack:X(Ko(t))},message:t.message}}return{error:{stack:en},message:`Uncaught ${Z(e)}`}}function Ko(e){return e.stack=e.stack.filter(t=>!t.url||Po.some(n=>t.url.startsWith(n))),e}const _e=1/0,Jo=K;let we=null;const je=new Set;function qo(){je.forEach(e=>e())}function Yo({expireDelay:e,maxEntries:t}){let n=[];const r=[];we||(we=tt(()=>qo(),Jo));const o=()=>{const h=ve()-e;for(;n.length>0&&n[n.length-1].endTime<h;){const m=n.pop();m&&r.push(m.startTime)}};je.add(o);function s(h,m){const b={value:h,startTime:m,endTime:_e,remove:()=>{fn(n,b)},close:E=>{b.endTime=E}};return t&&n.length>=t&&n.pop(),n.unshift(b),b}function i(h=_e,m={returnInactive:!1}){for(const b of n)if(b.startTime<=h){if(m.returnInactive||h<=b.endTime)return b.value;break}}function a(h){const m=n[0];m&&m.endTime===_e&&m.close(h)}function c(h=_e,m=0){const b=Hn(h,m);return n.filter(E=>E.startTime<=b&&h<=E.endTime).map(E=>E.value)}function l(){return n.map(({startTime:h,endTime:m,value:b})=>({startTime:h,endTime:m===_e?"Infinity":m,value:b}))}function u(){return r}function d(){n=[]}function f(){je.delete(o),je.size===0&&we&&(Nt(we),we=null)}return{add:s,find:i,closeActive:a,findAll:c,reset:d,stop:f,getAllEntries:l,getDeletedEntries:u}}const Zo=K,Xo=st;function Vo(e,t,n,r){const o=new O,s=new O,i=Lr(e.sessionStoreStrategyType,e,t,n),a=Yo({expireDelay:Xo});i.renewObservable.subscribe(()=>{a.add(c(),ve()),o.notify()}),i.expireObservable.subscribe(()=>{s.notify(),a.closeActive(ve())}),i.expandOrRenewSession(),a.add(c(),Gn().relative),r.observable.subscribe(()=>{r.isGranted()?i.expandOrRenewSession():i.expire()}),Qo(e,()=>{r.isGranted()&&i.expandOrRenewSession()}),es(e,()=>i.expandSession()),ts(e,()=>i.restartSession());function c(){return{id:i.getSession().id,trackingType:i.getSession()[t],isReplayForced:!!i.getSession().forcedReplay,anonymousId:i.getSession().anonymousId}}return{findSession:(l,u)=>a.find(l,u),renewObservable:o,expireObservable:s,sessionStateUpdateObservable:i.sessionStateUpdateObservable,expire:i.expire,updateSessionState:i.updateSessionState}}function Qo(e,t){gt(e,window,["click","touchstart","keydown","scroll"],t,{capture:!0,passive:!0})}function es(e,t){const n=()=>{document.visibilityState==="visible"&&t()};Q(e,document,"visibilitychange",n),tt(n,Zo)}function ts(e,t){Q(e,window,"resume",t,{capture:!0})}function Sn(e){return e>=500}function ns(e){try{return e.clone()}catch{return}}const rs=80*D,os=32,yn=3*kt,ss=K,bn=pe;function En(e,t,n,r,o){t.transportStatus===0&&t.queuedPayloads.size()===0&&t.bandwidthMonitor.canHandle(e)?_n(e,t,n,{onSuccess:()=>wn(0,t,n,r,o),onFailure:()=>{t.queuedPayloads.enqueue(e),Tn(t,n,r,o)}}):t.queuedPayloads.enqueue(e)}function Tn(e,t,n,r){e.transportStatus===2&&Se(()=>{const o=e.queuedPayloads.first();_n(o,e,t,{onSuccess:()=>{e.queuedPayloads.dequeue(),e.currentBackoffTime=bn,wn(1,e,t,n,r)},onFailure:()=>{e.currentBackoffTime=Math.min(ss,e.currentBackoffTime*2),Tn(e,t,n,r)}})},e.currentBackoffTime)}function _n(e,t,n,{onSuccess:r,onFailure:o}){t.bandwidthMonitor.add(e),n(e,s=>{t.bandwidthMonitor.remove(e),is(s)?(t.transportStatus=t.bandwidthMonitor.ongoingRequestCount>0?1:2,e.retry={count:e.retry?e.retry.count+1:1,lastFailureStatus:s.status},o()):(t.transportStatus=0,r())})}function wn(e,t,n,r,o){e===0&&t.queuedPayloads.isFull()&&!t.queueFullReported&&(o({message:`Reached max ${r} events size queued for upload: ${yn/kt}MiB`,source:L.AGENT,startClocks:U()}),t.queueFullReported=!0);const s=t.queuedPayloads;for(t.queuedPayloads=On();s.size()>0;)En(s.dequeue(),t,n,r,o)}function is(e){return e.type!=="opaque"&&(e.status===0&&!navigator.onLine||e.status===408||e.status===429||Sn(e.status))}function as(){return{transportStatus:0,currentBackoffTime:bn,bandwidthMonitor:cs(),queuedPayloads:On(),queueFullReported:!1}}function On(){const e=[];return{bytesCount:0,enqueue(t){this.isFull()||(e.push(t),this.bytesCount+=t.bytesCount)},first(){return e[0]},dequeue(){const t=e.shift();return t&&(this.bytesCount-=t.bytesCount),t},size(){return e.length},isFull(){return this.bytesCount>=yn}}}function cs(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(e){return this.ongoingRequestCount===0||this.ongoingByteCount+e.bytesCount<=rs&&this.ongoingRequestCount<os},add(e){this.ongoingRequestCount+=1,this.ongoingByteCount+=e.bytesCount},remove(e){this.ongoingRequestCount-=1,this.ongoingByteCount-=e.bytesCount}}}function us(e,t,n){const r=as(),o=(s,i)=>fs(e,t,s,i);return{send:s=>{En(s,r,o,e.trackType,n)},sendOnExit:s=>{ls(e,t,s)}}}function ls(e,t,n){if(!!navigator.sendBeacon&&n.bytesCount<t)try{const s=e.build("beacon",n);if(navigator.sendBeacon(s,n.data))return}catch(s){ds(s)}const o=e.build("xhr",n);St(o,n.data)}let Rn=!1;function ds(e){Rn||(Rn=!0,gn(e))}function fs(e,t,n,r){if(ps()&&n.bytesCount<t){const s=e.build("fetch",n);fetch(s,{method:"POST",body:n.data,keepalive:!0,mode:"cors"}).then(y(i=>r==null?void 0:r({status:i.status,type:i.type})),y(()=>{const i=e.build("xhr",n);St(i,n.data,r)}))}else{const s=e.build("xhr",n);St(s,n.data,r)}}function ps(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function St(e,t,n){const r=new XMLHttpRequest;r.open("POST",e,!0),t instanceof Blob&&r.setRequestHeader("Content-Type",t.type),Q({allowUntrustedEvents:!0},r,"loadend",()=>{n==null||n({status:r.status})},{once:!0}),r.send(t)}function yt(){const e=hs();if(e)return{getCapabilities(){var t;return JSON.parse(((t=e.getCapabilities)===null||t===void 0?void 0:t.call(e))||"[]")},getPrivacyLevel(){var t;return(t=e.getPrivacyLevel)===null||t===void 0?void 0:t.call(e)},getAllowedWebViewHosts(){return JSON.parse(e.getAllowedWebViewHosts())},send(t,n,r){const o=r?{id:r}:void 0;e.send(JSON.stringify({eventType:t,event:n,view:o}))}}}function He(e){var t;e===void 0&&(e=(t=B().location)===null||t===void 0?void 0:t.hostname);const n=yt();return!!n&&n.getAllowedWebViewHosts().some(r=>e===r||e.endsWith(`.${r}`))}function hs(){return B().DatadogEventBridge}const ze={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function ms(e){return new O(t=>{const{stop:n}=gt(e,window,["visibilitychange","freeze"],o=>{o.type==="visibilitychange"&&document.visibilityState==="hidden"?t.notify({reason:ze.HIDDEN}):o.type==="freeze"&&t.notify({reason:ze.FROZEN})},{capture:!0}),r=Q(e,window,"beforeunload",()=>{t.notify({reason:ze.UNLOADING})}).stop;return()=>{n(),r()}})}function gs(e){return ke(ze).includes(e)}function Ss({encoder:e,request:t,flushController:n,messageBytesLimit:r}){let o={};const s=n.flushObservable.subscribe(d=>u(d));function i(d,f,h){n.notifyBeforeAddMessage(f),h!==void 0?(o[h]=d,n.notifyAfterAddMessage()):e.write(e.isEmpty?d:`\n${d}`,m=>{n.notifyAfterAddMessage(m-f)})}function a(d){return d!==void 0&&o[d]!==void 0}function c(d){const f=o[d];delete o[d];const h=e.estimateEncodedBytesCount(f);n.notifyAfterRemoveMessage(h)}function l(d,f){const h=Z(d),m=e.estimateEncodedBytesCount(h);if(m>=r){_.warn(`Discarded a message whose size was bigger than the maximum allowed size ${r}KB. ${Re} ${vt}/#technical-limitations`);return}a(f)&&c(f),i(h,m,f)}function u(d){const f=ke(o).join(`\n`);o={};const h=gs(d.reason),m=h?t.sendOnExit:t.send;if(h&&e.isAsync){const b=e.finishSync();b.outputBytesCount&&m(Cn(b));const E=[b.pendingData,f].filter(Boolean).join(`\n`);E&&m({data:E,bytesCount:Qe(E)})}else f&&e.write(e.isEmpty?f:`\n${f}`),e.finish(b=>{m(Cn(b))})}return{flushController:n,add:l,upsert:l,stop:s.unsubscribe}}function Cn(e){let t;return typeof e.output=="string"?t=e.output:t=new Blob([e.output],{type:"text/plain"}),{data:t,bytesCount:e.outputBytesCount,encoding:e.encoding}}function ys({messagesLimit:e,bytesLimit:t,durationLimit:n,pageExitObservable:r,sessionExpireObservable:o}){const s=r.subscribe(m=>u(m.reason)),i=o.subscribe(()=>u("session_expire")),a=new O(()=>()=>{s.unsubscribe(),i.unsubscribe()});let c=0,l=0;function u(m){if(l===0)return;const b=l,E=c;l=0,c=0,h(),a.notify({reason:m,messagesCount:b,bytesCount:E})}let d;function f(){d===void 0&&(d=Se(()=>{u("duration_limit")},n))}function h(){Mt(d),d=void 0}return{flushObservable:a,get messagesCount(){return l},notifyBeforeAddMessage(m){c+m>=t&&u("bytes_limit"),l+=1,c+=m,f()},notifyAfterAddMessage(m=0){c+=m,l>=e?u("messages_limit"):c>=t&&u("bytes_limit")},notifyAfterRemoveMessage(m){c-=m,l-=1,l===0&&h()}}}function vn(e,t,n,r,o,s,i=Ss){const a=l(e,t),c=n&&l(e,n);function l(u,{endpoint:d,encoder:f}){return i({encoder:f,request:us(d,u.batchBytesLimit,r),flushController:ys({messagesLimit:u.batchMessagesLimit,bytesLimit:u.batchBytesLimit,durationLimit:u.flushTimeout,pageExitObservable:o,sessionExpireObservable:s}),messageBytesLimit:u.messageBytesLimit})}return{flushObservable:a.flushController.flushObservable,add(u,d=!0){a.add(u),c&&d&&c.add(n.transformMessage?n.transformMessage(u):u)},upsert:(u,d)=>{a.upsert(u,d),c&&c.upsert(n.transformMessage?n.transformMessage(u):u,d)},stop:()=>{a.stop(),c&&c.stop()}}}function We(){let e="",t=0;return{isAsync:!1,get isEmpty(){return!e},write(n,r){const o=Qe(n);t+=o,e+=n,r&&r(o)},finish(n){n(this.finishSync())},finishSync(){const n={output:e,outputBytesCount:t,rawBytesCount:t,pendingData:""};return e="",t=0,n},estimateEncodedBytesCount(n){return n.length}}}class bs{constructor(){this.callbacks={}}notify(t,n){const r=this.callbacks[t];r&&r.forEach(o=>o(n))}subscribe(t,n){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(n),{unsubscribe:()=>{this.callbacks[t]=this.callbacks[t].filter(r=>n!==r)}}}}function Es(e,t,n){let r=0,o=!1;return{isLimitReached(){if(r===0&&Se(()=>{r=0},K),r+=1,r<=t||o)return o=!1,!1;if(r===t+1){o=!0;try{n({message:`Reached max number of ${e}s by minute: ${t}`,source:L.AGENT,startClocks:U()})}finally{o=!1}}return!0}}}let bt;const Et=new WeakMap;function Ts(e){return bt||(bt=_s(e)),bt}function _s(e){return new O(t=>{const{stop:n}=V(XMLHttpRequest.prototype,"open",ws),{stop:r}=V(XMLHttpRequest.prototype,"send",s=>{Os(s,e,t)},{computeHandlingStack:!0}),{stop:o}=V(XMLHttpRequest.prototype,"abort",Rs);return()=>{n(),r(),o()}})}function ws({target:e,parameters:[t,n]}){Et.set(e,{state:"open",method:String(t).toUpperCase(),url:ut(String(n))})}function Os({target:e,handlingStack:t},n,r){const o=Et.get(e);if(!o)return;const s=o;s.state="start",s.startClocks=U(),s.isAborted=!1,s.xhr=e,s.handlingStack=t;let i=!1;const{stop:a}=V(e,"onreadystatechange",()=>{e.readyState===XMLHttpRequest.DONE&&c()}),c=()=>{if(l(),a(),i)return;i=!0;const u=o;u.state="complete",u.duration=jn(s.startClocks.timeStamp,F()),u.status=e.status,r.notify(Kn(u))},{stop:l}=Q(n,e,"loadend",c);r.notify(s)}function Rs({target:e}){const t=Et.get(e);t&&(t.isAborted=!0)}let Tt;function Ln(){return Tt||(Tt=Cs()),Tt}function Cs(){return new O(e=>{if(!window.fetch)return;const{stop:t}=V(window,"fetch",n=>vs(n,e),{computeHandlingStack:!0});return t})}function vs({parameters:e,onPostCall:t,handlingStack:n},r){const[o,s]=e;let i=s&&s.method;i===void 0&&o instanceof Request&&(i=o.method);const a=i!==void 0?String(i).toUpperCase():"GET",c=o instanceof Request?o.url:ut(String(o)),l=U(),u={state:"start",init:s,input:o,method:a,startClocks:l,url:c,handlingStack:n};r.notify(u),e[0]=u.input,e[1]=u.init,t(d=>Ls(r,d,u))}function Ls(e,t,n){const r=n;function o(s){r.state="resolve",Object.assign(r,s),e.notify(r)}t.then(y(s=>{o({response:s,responseType:s.type,status:s.status,isAborted:!1})}),y(s=>{var i,a;o({status:0,isAborted:((a=(i=r.init)===null||i===void 0?void 0:i.signal)===null||a===void 0?void 0:a.aborted)||s instanceof DOMException&&s.code===DOMException.ABORT_ERR,error:s})}))}let _t={};function Is(e){const t=e.map(n=>(_t[n]||(_t[n]=As(n)),_t[n]));return $t(...t)}function As(e){return new O(t=>{const n=x[e];return x[e]=(...r)=>{n.apply(console,r);const o=Ue("console error");ge(()=>{t.notify(ks(r,e,o))})},()=>{x[e]=n}})}function ks(e,t,n){const r=e.map(s=>xs(s)).join(" ");let o;if(t===T.error){const s=e.find(H);o={stack:s?X(M(s)):void 0,fingerprint:nn(s),causes:s?on(s,"console"):void 0,startClocks:U(),message:r,source:L.CONSOLE,handling:"handled",handlingStack:n,context:rn(s)}}return{api:t,message:r,error:o,handlingStack:n}}function xs(e){return typeof e=="string"?N(e):H(e)?Qt(M(e)):Z(N(e),void 0,2)}function Ds(e){const t=ln(e)==="object";return t||_.error("Unsupported context:",e),t}function wt(e,t,n){const r={...e};for(const[o,{required:s,type:i}]of Object.entries(t))i==="string"&&o in r&&(r[o]=String(r[o])),s&&!(o in e)&&_.warn(`The property ${o} of ${n} is required; context will not be sent to the intake.`);return r}function Ke(e="",{customerDataTracker:t,propertiesConfig:n={}}={}){let r={};const o=new O,s={getContext:()=>dn(r),setContext:i=>{Ds(i)?(r=N(wt(i,n,e)),t==null||t.updateCustomerData(r)):s.clearContext(),o.notify()},setContextProperty:(i,a)=>{r=N(wt({...r,[i]:a},n,e)),t==null||t.updateCustomerData(r),o.notify()},removeContextProperty:i=>{delete r[i],t==null||t.updateCustomerData(r),wt(r,n,e),o.notify()},clearContext:()=>{r={},t==null||t.resetCustomerData(),o.notify()},changeObservable:o};return s}const Ms="_dd_c",Ns=[];function Ot(e,t,n,r){const o=$s(n,r);Ns.push(Q(e,window,"storage",({key:l})=>{o===l&&i()})),t.changeObservable.subscribe(a);const s=ae(c(),t.getContext());me(s)||t.setContext(s);function i(){t.setContext(c())}function a(){localStorage.setItem(o,JSON.stringify(t.getContext()))}function c(){const l=localStorage.getItem(o);return l?JSON.parse(l):{}}}function $s(e,t){return`${Ms}_${e}_${t}`}const Ps=3*D,Fs=16*D,Us=200;function Bs(e=2){const t=new Map;let n=!1;function r(o=0){if(n||e===0)return;const s=e===2?Ps:Fs;let i=o;t.forEach(a=>{i+=a.getBytesCount()}),i>s&&(Gs(s),n=!0)}return{createDetachedTracker:()=>{const o=In(()=>r(o.getBytesCount()));return o},getOrCreateTracker:o=>(t.has(o)||t.set(o,In(r)),t.get(o)),setCompressionStatus:o=>{e===0&&(e=o,r())},getCompressionStatus:()=>e,stop:()=>{t.forEach(o=>o.stop()),t.clear()}}}function In(e){let t=0;const{throttled:n,cancel:r}=Pt(s=>{t=Qe(Z(s)),e()},Us),o=()=>{r(),t=0};return{updateCustomerData:s=>{me(s)?o():n(s)},resetCustomerData:o,getBytesCount:()=>t,stop:()=>{r()}}}function Gs(e){_.warn(`Customer data exceeds the recommended ${e/D}KiB threshold. ${Re} ${vt}/#customer-data-exceeds-the-recommended-threshold-warning`)}function js(e,t,n){const r=e.getReader(),o=[];let s=0;i();function i(){r.read().then(y(c=>{if(c.done){a();return}o.push(c.value),s+=c.value.length,s>n.bytesLimit?a():i()}),y(c=>t(c)))}function a(){r.cancel().catch(G);let c,l;{let u;if(o.length===1)u=o[0];else{u=new Uint8Array(s);let d=0;o.forEach(f=>{u.set(f,d),d+=f.length})}c=u.slice(0,n.bytesLimit),l=u.length>n.bytesLimit}t(void 0,c,l)}}const Hs="datadog-synthetics-public-id",zs="datadog-synthetics-result-id",Ws="datadog-synthetics-injects-rum";function An(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||J(Ws))}function Ks(){const e=window._DATADOG_SYNTHETICS_PUBLIC_ID||J(Hs);return typeof e=="string"?e:void 0}function Js(){const e=window._DATADOG_SYNTHETICS_RESULT_ID||J(zs);return typeof e=="string"?e:void 0}function Je(e,t,n){const r=n.getHandler(),o=Array.isArray(r)?r:[r];return kn[e]>=kn[n.getLevel()]&&o.includes(t)}const g={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},kn={[g.ok]:0,[g.debug]:1,[g.info]:2,[g.notice]:4,[g.warn]:5,[g.error]:6,[g.critical]:7,[g.alert]:8,[g.emerg]:9};function qe(e,{includeMessage:t=!1}={}){return{stack:e.stack,kind:e.type,message:t?e.message:void 0,causes:e.causes,fingerprint:e.fingerprint,handling:e.handling}}var qs=function(e,t,n,r){var o=arguments.length,s=o<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s};const Oe={console:"console",http:"http",silent:"silent"},Ys=Object.keys(g);let A=class{constructor(t,n,r,o=Oe.http,s=g.debug,i={}){this.handleLogStrategy=t,this.handlerType=o,this.level=s,this.contextManager=Ke("logger",{customerDataTracker:n}),this.contextManager.setContext(i),r&&this.contextManager.setContextProperty("logger",{name:r})}logImplementation(t,n,r=g.info,o,s){const i=N(n);let a;if(o!=null){const c=tn({stackTrace:H(o)?M(o):void 0,originalError:o,nonErrorPrefix:"Provided",source:L.LOGGER,handling:"handled",startClocks:U()});a=ae({error:qe(c,{includeMessage:!0})},i)}else a=i;this.handleLogStrategy({message:N(t),context:a,status:r},this,s)}log(t,n,r=g.info,o){let s;Je(r,Oe.http,this)&&(s=Ue("log")),this.logImplementation(t,n,r,o,s)}setContext(t){this.contextManager.setContext(t)}getContext(){return this.contextManager.getContext()}setContextProperty(t,n){this.contextManager.setContextProperty(t,n)}removeContextProperty(t){this.contextManager.removeContextProperty(t)}clearContext(){this.contextManager.clearContext()}setHandler(t){this.handlerType=t}getHandler(){return this.handlerType}setLevel(t){this.level=t}getLevel(){return this.level}};qs([Yn],A.prototype,"logImplementation",null),A.prototype.ok=$(g.ok),A.prototype.debug=$(g.debug),A.prototype.info=$(g.info),A.prototype.notice=$(g.notice),A.prototype.warn=$(g.warn),A.prototype.error=$(g.error),A.prototype.critical=$(g.critical),A.prototype.alert=$(g.alert),A.prototype.emerg=$(g.emerg);function $(e){return function(t,n,r){let o;Je(e,Oe.http,this)&&(o=Ue("log")),this.logImplementation(t,n,e,r,o)}}function Zs(e,t,n){return{view:{referrer:document.referrer,url:window.location.href},context:e.getContext(),user:t.getContext(),account:n.getContext()}}const Xs=32*D;function Vs(e){e.usePciIntake===!0&&e.site&&e.site!=="datadoghq.com"&&_.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");const t=Yr(e),n=xn(e.forwardConsoleLogs,ke(T),"Forward Console Logs"),r=xn(e.forwardReports,ke(Be),"Forward Reports");if(!(!t||!n||!r))return e.forwardErrorsToLogs&&!n.includes(T.error)&&n.push(T.error),{forwardErrorsToLogs:e.forwardErrorsToLogs!==!1,forwardConsoleLogs:n,forwardReports:r,requestErrorResponseLengthLimit:Xs,...t}}function xn(e,t,n){if(e===void 0)return[];if(!(e==="all"||Array.isArray(e)&&e.every(r=>t.includes(r)))){_.error(`${n} should be "all" or an array with allowed values "${t.join(\'", "\')}"`);return}return e==="all"?t:No(e)}function Qs(e){const t=Zr(e);return{forward_errors_to_logs:e.forwardErrorsToLogs,forward_console_logs:e.forwardConsoleLogs,forward_reports:e.forwardReports,use_pci_intake:e.usePciIntake,...t}}function ei(e,t,n){const r=pn();let o,s;const i=t.observable.subscribe(a);function a(){if(!s||!o||!t.isGranted())return;i.unsubscribe();const c=n(o,s);r.drain(c)}return{init(c){if(!c){_.error("Missing configuration");return}if(Xr(c.enableExperimentalFeatures),He()&&(c=ti(c)),o=c,s){sn("DD_LOGS",c);return}const l=Vs(c);l&&(s=l,Ln().subscribe(G),t.tryToInit(l.trackingConsent),a())},get initConfiguration(){return o},getInternalContext:G,handleLog(c,l,u,d=e(),f=F()){r.add(h=>h.handleLog(c,l,u,d,f))}}}function ti(e){return{...e,clientToken:"empty"}}const Rt="logs";function ni(e){const t=Bs(),n=Ke("global context",{customerDataTracker:t.getOrCreateTracker(2)}),r=Ke("user",{customerDataTracker:t.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),o=Ke("account",{customerDataTracker:t.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),s=Ir();function i(){return Zs(n,r,o)}let a=ei(i,s,(u,d)=>{u.storeContextsAcrossPages&&(Ot(d,n,Rt,2),Ot(d,r,Rt,1),Ot(d,o,Rt,4));const f=e(u,d,i,s);return a=ri(u,f),f});const c={},l=new A((...u)=>a.handleLog(...u),t.createDetachedTracker());return Co({logger:l,init:y(u=>a.init(u)),setTrackingConsent:y(u=>{s.update(u),zo({feature:"set-tracking-consent",tracking_consent:u})}),getGlobalContext:y(()=>n.getContext()),setGlobalContext:y(u=>n.setContext(u)),setGlobalContextProperty:y((u,d)=>n.setContextProperty(u,d)),removeGlobalContextProperty:y(u=>n.removeContextProperty(u)),clearGlobalContext:y(()=>n.clearContext()),createLogger:y((u,d={})=>(c[u]=new A((...f)=>a.handleLog(...f),t.createDetachedTracker(),N(u),d.handler,d.level,N(d.context)),c[u])),getLogger:y(u=>c[u]),getInitConfiguration:y(()=>dn(a.initConfiguration)),getInternalContext:y(u=>a.getInternalContext(u)),setUser:y(r.setContext),getUser:y(r.getContext),setUserProperty:y(r.setContextProperty),removeUserProperty:y(r.removeContextProperty),clearUser:y(r.clearContext),setAccount:y(o.setContext),getAccount:y(o.getContext),setAccountProperty:y(o.setContextProperty),removeAccountProperty:y(o.removeContextProperty),clearAccount:y(o.clearContext)})}function ri(e,t){return{init:n=>{sn("DD_LOGS",n)},initConfiguration:e,...t}}const oi="logs";function si(e,t){const n=Vo(e,oi,r=>ai(e,r),t);return{findTrackedSession:(r,o={returnInactive:!1})=>{const s=n.findSession(r,o);return s&&s.trackingType==="1"?{id:s.id,anonymousId:s.anonymousId}:void 0},expireObservable:n.expireObservable}}function ii(e){const n=Dn(e)==="1"?{}:void 0;return{findTrackedSession:()=>n,expireObservable:new O}}function Dn(e){return Ce(e.sessionSampleRate)?"1":"0"}function ai(e,t){const n=ci(t)?t:Dn(e);return{trackingType:n,isTracked:n==="1"}}function ci(e){return e==="0"||e==="1"}let Mn=!1;function Ye(e){const t=window;if(An()){const r=n(t.DD_RUM_SYNTHETICS);return!r&&!Mn&&(Mn=!0,mn("Logs sent before RUM is injected by the synthetics worker",{testId:Ks(),resultId:Js()})),r}return n(t.DD_RUM);function n(r){if(r&&r.getInternalContext)return r.getInternalContext(e)}}function ui(e,t,n,r,o){const s=Ys.concat(["custom"]),i={};s.forEach(a=>{i[a]=Es(a,t.eventRateLimiterThreshold,o)}),n.subscribe(0,({rawLogsEvent:a,messageContext:c=void 0,savedCommonContext:l=void 0,domainContext:u})=>{var d,f;const h=zn(a.date),m=e.findTrackedSession(h);if(!e.findTrackedSession(h,{returnInactive:!0}))return;const E=l||r();let z;!me(E.account)&&E.account.id&&(z=E.account),m&&m.anonymousId&&!E.user.anonymous_id&&(E.user.anonymous_id=m.anonymousId);const v=ae({service:t.service,session_id:m?m.id:void 0,session:m?{id:m.id}:void 0,usr:me(E.user)?void 0:E.user,account:z,view:E.view},E.context,Ye(h),a,c);((d=t.beforeSend)===null||d===void 0?void 0:d.call(t,v,u))===!1||v.origin!==L.AGENT&&((f=i[v.status])!==null&&f!==void 0?f:i.custom).isLimitReached()||n.notify(1,v)})}const li={[T.log]:g.info,[T.debug]:g.debug,[T.info]:g.info,[T.warn]:g.warn,[T.error]:g.error};function di(e,t){const n=Is(e.forwardConsoleLogs).subscribe(r=>{var o;const s={rawLogsEvent:{date:F(),message:r.message,origin:L.CONSOLE,error:r.error&&qe(r.error),status:li[r.api]},messageContext:(o=r.error)===null||o===void 0?void 0:o.context,domainContext:{handlingStack:r.handlingStack}};t.notify(0,s)});return{stop:()=>{n.unsubscribe()}}}function fi(e,t){const n=Lo(e,e.forwardReports).subscribe(r=>{let o=r.message,s;const i=r.originalError.type==="deprecation"?g.warn:g.error;i===g.error?s=qe(r):r.stack&&(o+=` Found in ${_o(r.stack)}`),t.notify(0,{rawLogsEvent:{date:F(),message:o,origin:L.REPORT,error:s,status:i}})});return{stop:()=>{n.unsubscribe()}}}function pi(e,t){if(!e.forwardErrorsToLogs)return{stop:G};const n=Ts(e).subscribe(s=>{s.state==="complete"&&o("xhr",s)}),r=Ln().subscribe(s=>{s.state==="resolve"&&o("fetch",s)});function o(s,i){!Jr(i.url)&&(Si(i)||Sn(i.status))&&("xhr"in i?hi(i.xhr,e,a):i.response?gi(i.response,e,a):i.error&&mi(i.error,e,a));function a(c){const l={isAborted:i.isAborted,handlingStack:i.handlingStack};t.notify(0,{rawLogsEvent:{message:`${yi(s)} error ${i.method} ${i.url}`,date:i.startClocks.timeStamp,error:{stack:c||"Failed to load",handling:void 0},http:{method:i.method,status_code:i.status,url:i.url},status:g.error,origin:L.NETWORK},domainContext:l})}}return{stop:()=>{n.unsubscribe(),r.unsubscribe()}}}function hi(e,t,n){typeof e.response=="string"?n(Ct(e.response,t)):n(e.response)}function mi(e,t,n){n(Ct(X(M(e)),t))}function gi(e,t,n){const r=ns(e);!r||!r.body?n():window.TextDecoder?bi(r.body,t.requestErrorResponseLengthLimit,(o,s)=>{n(o?`Unable to retrieve response: ${o}`:s)}):r.text().then(y(o=>n(Ct(o,t))),y(o=>n(`Unable to retrieve response: ${o}`)))}function Si(e){return e.status===0&&e.responseType!=="opaque"}function Ct(e,t){return e.length>t.requestErrorResponseLengthLimit?`${e.substring(0,t.requestErrorResponseLengthLimit)}...`:e}function yi(e){return e==="xhr"?"XHR":"Fetch"}function bi(e,t,n){js(e,(r,o,s)=>{if(r)n(r);else{let i=new TextDecoder().decode(o);s&&(i+="..."),n(void 0,i)}},{bytesLimit:t,collectStreamBody:!0})}function Ei(e,t){if(!e.forwardErrorsToLogs)return{stop:G};const n=new O,{stop:r}=wo(n),o=n.subscribe(s=>{t.notify(0,{rawLogsEvent:{message:s.message,date:s.startClocks.timeStamp,error:qe(s),origin:L.SOURCE,status:g.error},messageContext:s.context})});return{stop:()=>{r(),o.unsubscribe()}}}const Ti=bs;function _i(e){function t(n,r,o,s,i){const a=ae(r.getContext(),n.context);if(Je(n.status,Oe.console,r)&&Oi(n,a),Je(n.status,Oe.http,r)){const c={rawLogsEvent:{date:i||F(),message:n.message,status:n.status,origin:L.LOGGER},messageContext:a,savedCommonContext:s};o&&(c.domainContext={handlingStack:o}),e.notify(0,c)}}return{handleLog:t}}const wi={[g.ok]:T.debug,[g.debug]:T.debug,[g.info]:T.info,[g.notice]:T.info,[g.warn]:T.warn,[g.error]:T.error,[g.critical]:T.error,[g.alert]:T.error,[g.emerg]:T.error};function Oi({status:e,message:t},n){W[wi[e]].call(x,t,n)}function Ri(e,t,n,r,o){const s=vn(e,{endpoint:e.logsEndpointBuilder,encoder:We()},e.replica&&{endpoint:e.replica.logsEndpointBuilder,encoder:We()},n,r,o.expireObservable);return t.subscribe(1,i=>{s.add(i)}),s}function Ci(e){const t=yt();e.subscribe(1,n=>{t.send("log",n)})}function vi(e){return{get:t=>{const n=e.findTrackedSession(t);if(n)return{session_id:n.id}}}}function Li(e){return t=>{e.notify(0,{rawLogsEvent:{message:t.message,date:t.startClocks.timeStamp,origin:L.AGENT,status:g.error}}),mn("Error reported to customer",{"error.message":t.message})}}function Ii(e,t,n,r,o){const s=Uo("browser-logs-sdk",t);s.setContextProvider(()=>{var a,c,l,u,d,f;return{application:{id:(a=Ye())===null||a===void 0?void 0:a.application_id},session:{id:(c=o.findTrackedSession())===null||c===void 0?void 0:c.id},view:{id:(u=(l=Ye())===null||l===void 0?void 0:l.view)===null||u===void 0?void 0:u.id},action:{id:(f=(d=Ye())===null||d===void 0?void 0:d.user_action)===null||f===void 0?void 0:f.id}}});const i=[];if(He()){const a=yt(),c=s.observable.subscribe(l=>a.send("internal_telemetry",l));i.push(()=>c.unsubscribe())}else{const a=vn(t,{endpoint:t.rumEndpointBuilder,encoder:We()},t.replica&&{endpoint:t.replica.rumEndpointBuilder,encoder:We()},n,r,o.expireObservable);i.push(()=>a.stop());const c=s.observable.subscribe(l=>a.add(l,jo(t)));i.push(()=>c.unsubscribe())}return Go(),Ho(Qs(e)),{telemetry:s,stop:()=>{i.forEach(a=>a())}}}function Ai(e,t,n,r){const o=new Ti,s=[];o.subscribe(1,f=>un("logs",f));const i=Li(o),a=ms(t),c=t.sessionStoreStrategyType&&!He()&&!An()?si(t,r):ii(t),{stop:l}=Ii(e,t,i,a,c);s.push(()=>l()),pi(t,o),Ei(t,o),di(t,o),fi(t,o);const{handleLog:u}=_i(o);if(ui(c,t,o,n,i),He())Ci(o);else{const{stop:f}=Ri(t,o,i,a,c);s.push(()=>f())}const d=vi(c);return{handleLog:u,getInternalContext:d.get,stop:()=>{s.forEach(f=>f())}}}const ue=ni(Ai);vo(B(),"DD_LOGS",ue);const R=class R{constructor(t,n,r,o,s){this.copy=()=>new R(this.h,this.m,this.s,this.f,this.field),this.print=()=>{const i=":";let a=("0"+this.h).slice(-2)+i+("0"+this.m).slice(-2)+i+("0"+this.s).slice(-2)+i+("0"+this.f).slice(-2);return a+="."+(this.field?"1":"2"),a},this.toZipTimeCodeString=()=>{const i=this.copy();return i.f=0,i.s=i.s%2===0?i.s:i.s-1,i.field=0,R.toStr(i)},this.toFrames=i=>{let a=60,c=0;Math.floor(i)==60?(a=60,c=0):Math.floor(i)==59?(a=60,c=4):Math.floor(i)==30?(a=30,c=0):Math.floor(i)==29&&(a=30,c=2);let l=this.h,u=this.m,d=this.s,f=this.f,h=this.field;const m=l*60+u,E=(m-Math.floor(m/10))*c;return l*(a*3600)+u*(a*60)+d*a+(f*2+h)-E},this.addSeconds=i=>{let a=this.copy();if(a.s+=i,a.s>=60){const c=Math.floor(a.s/60);if(a.s=a.s%60,a.m+=c,a.m>=60){const l=Math.floor(a.m/60);a.m=a.m%60,a.h+=l}}return a},this.addFrames=(i,a)=>{let c=this.toFrames(a);return c+=i,R.fromFrames(c,a)},this.subtractFrames=(i,a)=>this.addFrames(-i,a),this.h=t||0,this.m=n||0,this.s=r||0,this.f=o||0,this.field=s||0}static compare(t,n){return t.h!==n.h?t.h<n.h?-1:1:t.m!==n.m?t.m<n.m?-1:1:t.s!==n.s?t.s<n.s?-1:1:t.f!==n.f?t.f<n.f?-1:1:t.field!==n.field?t.field<n.field?-1:1:0}static generateTimecodeRange(t,n,r){const o=[];let s=t;for(;R.compare(s,n)<=0;)o.push(s),s=s.addSeconds(r);return o}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(t){return this.toFrames(t)*1e3/t}};R.calculateCurrentTimeCode=t=>{var d;if(!t.video||!t.clocker||!t.gameParams)throw new Error("OTTPlayer is not initialized");const n=t.video,r=t.clocker,o=r.videoFPScalculator.getFPS(),a=(n.currentTime-r.syncPoint.playerTime)%(60*60*24)*o+r.syncPoint.frame;if(a===0||o===0)throw new Error("Current frame is 0 or fps is 0");const c=R.calculateCurrentOffset(a,(d=t.gameParams)==null?void 0:d.offsets);if(c===void 0)throw new Error("Offset is undefined");let l=Math.floor(a-c);return l<0&&(l+=5178816),l>=5178816&&(l-=5178816),R.fromFrames(l,o)},R.calculateCurrentOffset=(t,n)=>{for(let r=1;r<n.length;r++)if(t<n[r].frame)return n[r-1].offset;return Math.abs(n[n.length-1].offset)},R.fromFrames=(t,n)=>{let r=60,o=0;Math.floor(n)==60?(r=60,o=0):Math.floor(n)==59?(r=60,o=4):Math.floor(n)==30?(r=30,o=0):Math.floor(n)==29&&(r=30,o=2);let s=Math.floor(n*60),i=Math.floor(n*60*10),a=i*6,c=t,l=Math.floor(c/a);c-=l*a;let u=Math.floor(c/i);c-=u*i,c>=r*60&&(c+=o*(Math.floor((c-r*60)/s)+1));let d=Math.floor(c/(r*60));c-=d*(r*60);let f=Math.floor(c/r);c-=f*r;let h=c;d+=u*10;let m=0;return m=h%2,h=Math.floor(h/2),new R(l,d,f,h,m)},R.toStr=t=>{const n="_";let r=("0"+t.h).slice(-2)+n+("0"+t.m).slice(-2)+n+("0"+t.s).slice(-2)+n+("0"+t.f).slice(-2);return t.field&&(r+="_1"),r},R.fromStr=t=>{const r=t.split("_").map(Number);if(r.length==4){const[o,s,i,a]=r;return new R(o,s,i,a,0)}else if(r.length==5){const[o,s,i,a,c]=r;return new R(o,s,i,a,c)}else throw new Error("Invalid timecode format: "+t)},R.fromMetadata=t=>{const n=/^(\\d{2}):(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d))?$/,r=t.timecode.match(n);if(!r)throw new Error("Invalid timecode format: "+t.timecode);const[,o,s,i,a,c]=r,l=Number(o),u=Number(s),d=Number(i),f=Number(a),h=c?Number(c):0;return new R(l,u,d,f,h)};let C=R;const p=class p{constructor(t){this.listenerMap=new Map,p.options=t,this.isLoggingOn=t.LOG_TO_DATADOG,this.eventTarget=new EventTarget,this.isLoggingOn&&ue.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!1,sessionSampleRate:100});const n="bb_logger_mac_uuid";let r=localStorage.getItem(n);r||(r=crypto.randomUUID(),localStorage.setItem(n,r)),p.tracking.mac=r,p.tracking.dev=`${t.platform}_${t.browserName}`,p.beatHandle||(p.options&&w(p.options,"Logger")&&console.log("[Logger] Starting tracking beat"),p.beatHandle=window.setInterval(p.flushTracking,15e3))}static setMessagePort(t){this.messagePort=t}static getMessagePort(){return this.messagePort}setLoggingOn(t){this.isLoggingOn=t}addEventListener(t,n){const r=o=>n(o);this.listenerMap.set(n,{eventName:t,wrappedListener:r}),this.eventTarget.addEventListener(t,r)}removeEventListener(t,n){const r=this.listenerMap.get(n);r&&r.eventName===t&&(this.eventTarget.removeEventListener(t,r.wrappedListener),this.listenerMap.delete(n))}removeAllEventListeners(){for(const[t,{eventName:n,wrappedListener:r}]of this.listenerMap)this.eventTarget.removeEventListener(n,r);this.listenerMap.clear()}setAttributes(t){p.processAttributes(t);for(const n in t)ue.logger.setContextProperty(n,t[n])}info(t,n){t==="didClickAd"&&this.emit("mediaSessionDidRegisterClick",{url:(n==null?void 0:n.url)||""}),t==="didToggleGlobalAugmentationDrawing"&&this.emit("mediaSessionDidUpdateGlobalAugmentationState",{isGlobalAugmentationEnabled:(n==null?void 0:n.isEnabled)||!0}),t==="didStartDrawingAugmentationMedia"&&this.emit("mediaSessionDidBeginShotRendering",n),t==="didEndDrawingAugmentationMedia"&&this.emit("mediaSessionDidEndShotRendering",n),t==="didRegisterShot"&&this.emit("mediaSessionDidRegisterShot",n),n&&p.processAttributes(n),this.isLoggingOn&&(ue.logger.info(t,n),p.options&&w(p.options,"Logger")&&console.log("[Logger] Sending info: ",t))}error(t,n){n&&p.processAttributes(n),this.isLoggingOn&&(ue.logger.error(t,n),p.tracking.err_time=Date.now().toFixed(0),p.tracking.err_desc=t+(n?` - ${JSON.stringify(n)}`:""),p.options&&w(p.options,"Logger")&&console.log("[Logger] Sending error: ",t))}warn(t,n){n&&p.processAttributes(n),this.isLoggingOn&&(ue.logger.warn(t,n),p.options&&w(p.options,"Logger")&&console.log("[Logger] Sending warn: ",t))}handleMessageFromWorker(t){t.actionType==="INFO"?this.info(t.message,t.attributes):t.actionType==="ERROR"?this.error(t.message,t.attributes):t.actionType==="WARN"?this.warn(t.message,t.attributes):t.actionType==="SET_ATTRIBUTES"&&t.attributes&&this.setAttributes(t.attributes)}static setAttributes(t){if(!p.messagePort){console.error("[Logger] messagePort is not set! Cannot send attributes.");return}try{p.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:t})}catch(n){console.error("[Logger] Error posting message:",n)}}static info(t,n){p.messagePort.postMessage({type:"LOG",actionType:"INFO",message:t,attributes:n})}static error(t,n){p.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:t,attributes:n})}static warn(t,n){p.messagePort.postMessage({type:"LOG",actionType:"WARN",message:t,attributes:n})}static processAttributes(t){if(t.player_version&&(p.tracking.sdk=t.player_version),t.media_id&&(p.tracking.gid=t.media_id),t.game_id&&(p.tracking.buc=t.game_id),t.bb_session_id&&(p.tracking.sid=t.bb_session_id,p.options&&w(p.options,"Logger")&&console.log("[Logger] Setting bb_session_id:",p.tracking.sid)),t.last_timecode){const r=C.fromStr(t.last_timecode);p.tracking.tc=r.print(),p.lastTimecodeMillis=r.totalMilliseconds(59.94),p.lastTimecodeMillis&&p.lastZipMillis&&(p.tracking.cache=(p.lastZipMillis-p.lastTimecodeMillis).toFixed(0))}t.last_offset&&(p.tracking.off=t.last_offset),t.last_loading_zip&&(p.tracking.zip=t.last_loading_zip+".zip",p.lastZipMillis=C.fromStr(t.last_loading_zip).totalMilliseconds(59.94),p.lastTimecodeMillis&&p.lastZipMillis&&(p.tracking.cache=(p.lastZipMillis-p.lastTimecodeMillis).toFixed(0))),t.last_rendered_frame&&(p.tracking.aug_time=Date.now().toFixed(0)),t.asset&&(p.tracking.asset=t.asset)}static objectToQuery(t){return Object.entries(t).filter(([n,r])=>r!==0&&r!=="").map(([n,r])=>`${encodeURIComponent(n)}=${encodeURIComponent(String(r))}`).join("&")}emit(t,n){const r=new CustomEvent(t,{detail:n});this.eventTarget.dispatchEvent(r)}};p.tracking={start:Date.now().toFixed(0),dev:"",sdk:"",mac:"",gid:"",sid:"",off:"",zip:"",aug_time:"",err_time:"",err_desc:"",tc:"",asset:"",cache:"",buc:""},p.lastTimecodeMillis=0,p.lastZipMillis=0,p.flushTracking=()=>{const t=Date.now().toFixed(0);p.tracking.now=t;const r=`https://dwu3k7rrxk5s3.cloudfront.net/metrics/1.gif?${p.objectToQuery(p.tracking)}`;p.options&&w(p.options,"Logger")&&console.log("[Logger] Flushing tracking data:",r),fetch(r,{method:"GET",mode:"no-cors",keepalive:!0,headers:{"X-Platform":"Web"}}).catch(()=>{}),p.tracking.err_desc="",p.tracking.err_time=""};let I=p;class Nn{constructor(t,n,r){this.jobsQueue=[],this.processedTimecodes=[],this.retryingTimecodes=new Set,this.permanentlyFailedTimecodes=new Set,this.activeDownloads=new Set,this.pendingRetryTimeouts=new Map,this.downloaderStopped=!1,this.firstDownload=!0,this.updateStreamData=o=>{this.downloaderStopped||(this.streamData=o,this.initiateJobs(this.options.DOWNLOADER_ZIP_START_OFFSET,this.options.DOWNLOADER_ZIP_END_OFFSET,this.options.DOWNLOADER_ZIP_LENGTH_SECONDS),this.clearOldJobs(1),this.notifyZipBufferStatus(),this.startNextJob())},this.initiateJobs=(o,s,i)=>{if(!this.streamData){I.error("[Downloader] Stream data is not available"),this.options&&w(this.options,"Errors")&&console.error("[Downloader] Stream data is not available");return}const a=C.fromStr(this.streamData.timeCode),c=a.addSeconds(o),l=a.addSeconds(s),u=C.generateTimecodeRange(c,l,i);for(const d of u){const f=d.toZipTimeCodeString();this.processedTimecodes.includes(f)||this.addJob(f)}},this.clearOldJobs=o=>{if(!this.streamData){I.error("[Downloader] Stream data is not available"),this.options&&w(this.options,"Errors")&&console.error("[Downloader] Stream data is not available");return}const i=C.fromStr(this.streamData.timeCode).totalSeconds()-o;this.processedTimecodes=this.processedTimecodes.filter(l=>C.fromStr(l).totalSeconds()>i),Array.from(this.retryingTimecodes).filter(l=>C.fromStr(l).totalSeconds()<=i).forEach(l=>this.retryingTimecodes.delete(l)),Array.from(this.permanentlyFailedTimecodes).filter(l=>C.fromStr(l).totalSeconds()<=i).forEach(l=>this.permanentlyFailedTimecodes.delete(l))},this.clearAllJobs=()=>{this.jobsQueue=[],this.processedTimecodes=[],this.retryingTimecodes.clear(),this.permanentlyFailedTimecodes.clear(),this.activeDownloads.clear(),this.pendingRetryTimeouts.forEach(o=>clearTimeout(o)),this.pendingRetryTimeouts.clear()},this.addJob=o=>{if(!this.downloaderStopped){if(this.jobsQueue.some(s=>s===o)){this.options&&w(this.options,"Downloader")&&console.log(`[Downloader] Job already in queue for timeCode=${o}`);return}if(this.activeDownloads.has(o)){this.options&&w(this.options,"Downloader")&&console.log(`[Downloader] Job already downloading for timeCode=${o}`);return}this.jobsQueue.push(o),this.startNextJob()}},this.startNextJob=()=>{if(!this.downloaderStopped&&this.jobsQueue.length>0){const o=this.jobsQueue.shift();this.options&&w(this.options,"Downloader")&&console.log(`[Downloader] Starting job timeCode=${o}`),this.downloadZip(o)}},this.downloadZip=async o=>{if(!this.streamData){I.error("[Downloader] Stream data is not available"),this.options&&w(this.options,"Errors")&&console.error("[Downloader] Stream data is not available");return}this.activeDownloads.add(o),this.firstDownload&&(this.firstDownload=!1,I.info("didStartAugmentationDownload",{timestamp:o}));const{fps:s,zipBaseURL:i,bucketName:a}=this.streamData,c=async(l=0)=>{const u=this.shouldBeFinalRetry(o,60);try{if(this.options&&w(this.options,"Downloader")){const h=l>0?` (retry ${l}${u?", final":""})`:"";console.log(`[Downloader] Fetching zip for timeCode=${o}${h}`)}const d=await this.fetchMetadata(i,a,s,o,u);if(this.downloaderStopped)return;this.retryingTimecodes.delete(o),this.activeDownloads.delete(o);const f=this.pendingRetryTimeouts.get(o);f!==void 0&&(clearTimeout(f),this.pendingRetryTimeouts.delete(o)),this.processedTimecodes.includes(o)||this.processedTimecodes.push(o),this.postArrayBufferToDecoder(o,d),I.setAttributes({last_loading_zip:o}),this.notifyZipBufferStatus(),this.startNextJob()}catch(d){if(l===0&&this.retryingTimecodes.add(o),this.downloaderStopped){this.options&&w(this.options,"Downloader")&&console.log("[Downloader] Stopping retry - downloader has been stopped"),this.startNextJob();return}if(u){I.error("[Downloader] Error fetching zip",{error:d.message||d}),this.options&&w(this.options,"Errors")&&console.error("[Downloader] Error fetching zip:",d),this.retryingTimecodes.delete(o),this.permanentlyFailedTimecodes.add(o),this.activeDownloads.delete(o);const h=this.pendingRetryTimeouts.get(o);h!==void 0&&(clearTimeout(h),this.pendingRetryTimeouts.delete(o)),this.notifyZipBufferStatus(),this.startNextJob();return}const f=setTimeout(()=>{this.pendingRetryTimeouts.delete(o),c(l+1)},1e3);this.pendingRetryTimeouts.set(o,f)}};await c()},this.shouldBeFinalRetry=(o,s)=>{var d;if(!((d=this.streamData)!=null&&d.timeCode))return!1;const i=C.fromStr(o),a=C.fromStr(this.streamData.timeCode),c=i.toFrames(s),l=a.toFrames(s);return c-l<=60},this.fetchMetadata=async(o,s,i,a,c=!1)=>{const u=`${`${o}/${s}`}/${this.options.BUCKET_SUBFOLDER_PATH}${a}.zip`,d=performance.now();let f;const h=this.options.SEND_METRICS?{"X-Platform":"Web"}:{},m=!!(this.options.authNbaToken||this.options.authEmail&&this.options.authPassword);if(this.options.SEND_METRICS){let v="";if(this.streamData&&this.streamData.timeCode){const te=this.streamData.timeCode;te.match(/^\\d{2}_\\d{2}_\\d{2}_\\d{2}$/)?v=`?tc=${te}_1`:te.match(/^\\d{2}_\\d{2}_\\d{2}_\\d{2}_1$/)&&(v=`?tc=${te.replace(/_1$/,"_2")}`)}c&&(v+=`${v?"&":"?"}fr=true`),f=await fetch(u+v,{headers:h,cache:"no-store",credentials:m?"include":"omit"})}else f=await fetch(u,{headers:h,cache:"no-store",credentials:m?"include":"omit"});const b=await f.arrayBuffer(),z=(performance.now()-d)/1e3;if(!f.ok)throw new Error(`HTTP error! Status: ${f.status}`);return z>1&&I.warn("didFetchZip",{downloadTaskURL:u,downloadTime:z}),b},this.stop=()=>{this.downloaderStopped=!0,this.clearAllJobs()},this.postArrayBufferToDecoder=t,this.onZipBufferStatusChange=r,this.options=n}isStopped(){return this.downloaderStopped}roundToZipBoundary(t,n){const r=t.totalSeconds(),o=Math.floor(r/n)*n,s=Math.floor(o/3600),i=Math.floor(o%3600/60),a=o%60;return new C(s,i,a,0,0)}calculateContinuousZipBuffer(){if(!this.streamData)return 0;const t=C.fromStr(this.streamData.timeCode),n=this.options.DOWNLOADER_ZIP_LENGTH_SECONDS;let r=t.addSeconds(this.options.DOWNLOADER_ZIP_START_OFFSET);r=this.roundToZipBoundary(r,n);let o=0;const s=Math.ceil(this.options.DOWNLOADER_ZIP_END_OFFSET/n);for(let i=0;i<s;i++){const a=r.toZipTimeCodeString();if(this.permanentlyFailedTimecodes.has(a)||!this.processedTimecodes.includes(a))break;o+=n,r=r.addSeconds(n)}return o}notifyZipBufferStatus(){if(!this.onZipBufferStatusChange)return;const t=this.calculateContinuousZipBuffer();this.onZipBufferStatusChange({continuousSeconds:t,isReady:t>=this.options.ZIP_BUFFER_READY_THRESHOLD,needsFadeout:t<=this.options.ZIP_BUFFER_FADEOUT_THRESHOLD,retryingTimecodes:Array.from(this.retryingTimecodes),failedTimecodes:Array.from(this.permanentlyFailedTimecodes)})}}let Ze=null,le=null,P,k;function $n(e){Ze&&Ze.postMessage({type:"ZIP_BUFFER_STATUS",status:e})}self.onmessage=async e=>{const{data:t}=e;if(t.type==="SET_LOGGER_PORT"&&I.setMessagePort(t.port),t.type==="SET_RENDERER_PORT"&&(Ze=t.port,Ze.onmessage=ki),t.type==="SET_DECODER_PORT"&&(le=t.port,le.onmessage=xi),t.type==="SET_OPTIONS"&&(k=t.options,I.setMessagePort(self),P=new Nn(Pn,k,$n)),t.type==="STOP_WORKER"){P&&P.stop();return}if(t.type==="RESTART_WORKER"){if(!k)return;P&&P.stop(),P=new Nn(Pn,k,$n);return}};async function ki(e){const{data:t}=e;if(self.postMessage(t),t.type==="DOWNLOADER_INPUT"){if(!P||P.isStopped())return;P.updateStreamData(t.streamData)}}function Pn(e,t){if(!le)return;k&&w(k,"Downloader")&&console.log(`[DownloaderWorker] Posting an ArrayBuffer to Decoder, timeCode=${e}`);const n={type:"DECODER_INPUT",timeCode:e,arrayBuffer:t};le==null||le.postMessage(n,{transfer:[t]})}function xi(e){k&&w(k,"Downloader")&&console.log("[DownloaderWorker] Received message from Decoder:",e.data)}self.onunhandledrejection=e=>{I.error("[DownloaderWorker] Unhandled rejection",{error:e.reason}),k&&(w(k,"Errors")&&console.error("[DownloaderWorker] Unhandled rejection:",e.reason),e.preventDefault())},self.onerror=e=>{I.error("[DownloaderWorker] Unhandled error",{error:e}),k&&(w(k,"Errors")&&console.error("[DownloaderWorker] Unhandled error:",e),e instanceof Event&&e.preventDefault())}})();\n',Nt=typeof self<"u"&&self.Blob&&new Blob([Bt],{type:"text/javascript;charset=utf-8"});function on(t){let e;try{if(e=Nt&&(self.URL||self.webkitURL).createObjectURL(Nt),!e)throw"";const r=new Worker(e,{name:t==null?void 0:t.name});return r.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),r}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Bt),{name:t==null?void 0:t.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}const zt='(function(){"use strict";const k=(a,n)=>n==="Errors"?!0:!a.debug||!a.debug.on?!1:a.debug[`log${n}`];function Zt(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var mt={},Qt;function fn(){return Qt||(Qt=1,function(a){var n=function(){var e=new Date,t=4,r=3,l=2,h=1,m=t,y={setLogLevel:function(b){b==this.debug?m=h:b==this.info?m=l:b==this.warn?m=r:(b==this.error,m=t)},debug:function(b,x){console.debug===void 0&&(console.debug=console.log),h>=m&&console.debug("["+n.getDurationString(new Date-e,1e3)+"]","["+b+"]",x)},log:function(b,x){this.debug(b.msg)},info:function(b,x){l>=m&&console.info("["+n.getDurationString(new Date-e,1e3)+"]","["+b+"]",x)},warn:function(b,x){r>=m&&console.warn("["+n.getDurationString(new Date-e,1e3)+"]","["+b+"]",x)},error:function(b,x){t>=m&&console.error("["+n.getDurationString(new Date-e,1e3)+"]","["+b+"]",x)}};return y}();n.getDurationString=function(e,t){var r;function l(w,T){for(var C=""+w,F=C.split(".");F[0].length<T;)F[0]="0"+F[0];return F.join(".")}e<0?(r=!0,e=-e):r=!1;var h=t||1,m=e/h,y=Math.floor(m/3600);m-=y*3600;var b=Math.floor(m/60);m-=b*60;var x=m*1e3;return m=Math.floor(m),x-=m*1e3,x=Math.floor(x),(r?"-":"")+y+":"+l(b,2)+":"+l(m,2)+"."+l(x,3)},n.printRanges=function(e){var t=e.length;if(t>0){for(var r="",l=0;l<t;l++)l>0&&(r+=","),r+="["+n.getDurationString(e.start(l))+","+n.getDurationString(e.end(l))+"]";return r}else return"(empty)"},a.Log=n;var o=function(e){if(e instanceof ArrayBuffer)this.buffer=e,this.dataview=new DataView(e);else throw"Needs an array buffer";this.position=0};o.prototype.getPosition=function(){return this.position},o.prototype.getEndPosition=function(){return this.buffer.byteLength},o.prototype.getLength=function(){return this.buffer.byteLength},o.prototype.seek=function(e){var t=Math.max(0,Math.min(this.buffer.byteLength,e));return this.position=isNaN(t)||!isFinite(t)?0:t,!0},o.prototype.isEos=function(){return this.getPosition()>=this.getEndPosition()},o.prototype.readAnyInt=function(e,t){var r=0;if(this.position+e<=this.buffer.byteLength){switch(e){case 1:t?r=this.dataview.getInt8(this.position):r=this.dataview.getUint8(this.position);break;case 2:t?r=this.dataview.getInt16(this.position):r=this.dataview.getUint16(this.position);break;case 3:if(t)throw"No method for reading signed 24 bits values";r=this.dataview.getUint8(this.position)<<16,r|=this.dataview.getUint8(this.position+1)<<8,r|=this.dataview.getUint8(this.position+2);break;case 4:t?r=this.dataview.getInt32(this.position):r=this.dataview.getUint32(this.position);break;case 8:if(t)throw"No method for reading signed 64 bits values";r=this.dataview.getUint32(this.position)<<32,r|=this.dataview.getUint32(this.position+4);break;default:throw"readInt method not implemented for size: "+e}return this.position+=e,r}else throw"Not enough bytes in buffer"},o.prototype.readUint8=function(){return this.readAnyInt(1,!1)},o.prototype.readUint16=function(){return this.readAnyInt(2,!1)},o.prototype.readUint24=function(){return this.readAnyInt(3,!1)},o.prototype.readUint32=function(){return this.readAnyInt(4,!1)},o.prototype.readUint64=function(){return this.readAnyInt(8,!1)},o.prototype.readString=function(e){if(this.position+e<=this.buffer.byteLength){for(var t="",r=0;r<e;r++)t+=String.fromCharCode(this.readUint8());return t}else throw"Not enough bytes in buffer"},o.prototype.readCString=function(){for(var e=[];;){var t=this.readUint8();if(t!==0)e.push(t);else break}return String.fromCharCode.apply(null,e)},o.prototype.readInt8=function(){return this.readAnyInt(1,!0)},o.prototype.readInt16=function(){return this.readAnyInt(2,!0)},o.prototype.readInt32=function(){return this.readAnyInt(4,!0)},o.prototype.readInt64=function(){return this.readAnyInt(8,!1)},o.prototype.readUint8Array=function(e){for(var t=new Uint8Array(e),r=0;r<e;r++)t[r]=this.readUint8();return t},o.prototype.readInt16Array=function(e){for(var t=new Int16Array(e),r=0;r<e;r++)t[r]=this.readInt16();return t},o.prototype.readUint16Array=function(e){for(var t=new Int16Array(e),r=0;r<e;r++)t[r]=this.readUint16();return t},o.prototype.readUint32Array=function(e){for(var t=new Uint32Array(e),r=0;r<e;r++)t[r]=this.readUint32();return t},o.prototype.readInt32Array=function(e){for(var t=new Int32Array(e),r=0;r<e;r++)t[r]=this.readInt32();return t},a.MP4BoxStream=o;var d=function(e,t,r){this._byteOffset=t||0,e instanceof ArrayBuffer?this.buffer=e:typeof e=="object"?(this.dataView=e,t&&(this._byteOffset+=t)):this.buffer=new ArrayBuffer(e||0),this.position=0,this.endianness=r??d.LITTLE_ENDIAN};d.prototype={},d.prototype.getPosition=function(){return this.position},d.prototype._realloc=function(e){if(this._dynamicSize){var t=this._byteOffset+this.position+e,r=this._buffer.byteLength;if(t<=r){t>this._byteLength&&(this._byteLength=t);return}for(r<1&&(r=1);t>r;)r*=2;var l=new ArrayBuffer(r),h=new Uint8Array(this._buffer),m=new Uint8Array(l,0,h.length);m.set(h),this.buffer=l,this._byteLength=t}},d.prototype._trimAlloc=function(){if(this._byteLength!=this._buffer.byteLength){var e=new ArrayBuffer(this._byteLength),t=new Uint8Array(e),r=new Uint8Array(this._buffer,0,t.length);t.set(r),this.buffer=e}},d.BIG_ENDIAN=!1,d.LITTLE_ENDIAN=!0,d.prototype._byteLength=0,Object.defineProperty(d.prototype,"byteLength",{get:function(){return this._byteLength-this._byteOffset}}),Object.defineProperty(d.prototype,"buffer",{get:function(){return this._trimAlloc(),this._buffer},set:function(e){this._buffer=e,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(d.prototype,"byteOffset",{get:function(){return this._byteOffset},set:function(e){this._byteOffset=e,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(d.prototype,"dataView",{get:function(){return this._dataView},set:function(e){this._byteOffset=e.byteOffset,this._buffer=e.buffer,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+e.byteLength}}),d.prototype.seek=function(e){var t=Math.max(0,Math.min(this.byteLength,e));this.position=isNaN(t)||!isFinite(t)?0:t},d.prototype.isEof=function(){return this.position>=this._byteLength},d.prototype.mapUint8Array=function(e){this._realloc(e*1);var t=new Uint8Array(this._buffer,this.byteOffset+this.position,e);return this.position+=e*1,t},d.prototype.readInt32Array=function(e,t){e=e??this.byteLength-this.position/4;var r=new Int32Array(e);return d.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT),d.arrayToNative(r,t??this.endianness),this.position+=r.byteLength,r},d.prototype.readInt16Array=function(e,t){e=e??this.byteLength-this.position/2;var r=new Int16Array(e);return d.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT),d.arrayToNative(r,t??this.endianness),this.position+=r.byteLength,r},d.prototype.readInt8Array=function(e){e=e??this.byteLength-this.position;var t=new Int8Array(e);return d.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT),this.position+=t.byteLength,t},d.prototype.readUint32Array=function(e,t){e=e??this.byteLength-this.position/4;var r=new Uint32Array(e);return d.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT),d.arrayToNative(r,t??this.endianness),this.position+=r.byteLength,r},d.prototype.readUint16Array=function(e,t){e=e??this.byteLength-this.position/2;var r=new Uint16Array(e);return d.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT),d.arrayToNative(r,t??this.endianness),this.position+=r.byteLength,r},d.prototype.readUint8Array=function(e){e=e??this.byteLength-this.position;var t=new Uint8Array(e);return d.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT),this.position+=t.byteLength,t},d.prototype.readFloat64Array=function(e,t){e=e??this.byteLength-this.position/8;var r=new Float64Array(e);return d.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT),d.arrayToNative(r,t??this.endianness),this.position+=r.byteLength,r},d.prototype.readFloat32Array=function(e,t){e=e??this.byteLength-this.position/4;var r=new Float32Array(e);return d.memcpy(r.buffer,0,this.buffer,this.byteOffset+this.position,e*r.BYTES_PER_ELEMENT),d.arrayToNative(r,t??this.endianness),this.position+=r.byteLength,r},d.prototype.readInt32=function(e){var t=this._dataView.getInt32(this.position,e??this.endianness);return this.position+=4,t},d.prototype.readInt16=function(e){var t=this._dataView.getInt16(this.position,e??this.endianness);return this.position+=2,t},d.prototype.readInt8=function(){var e=this._dataView.getInt8(this.position);return this.position+=1,e},d.prototype.readUint32=function(e){var t=this._dataView.getUint32(this.position,e??this.endianness);return this.position+=4,t},d.prototype.readUint16=function(e){var t=this._dataView.getUint16(this.position,e??this.endianness);return this.position+=2,t},d.prototype.readUint8=function(){var e=this._dataView.getUint8(this.position);return this.position+=1,e},d.prototype.readFloat32=function(e){var t=this._dataView.getFloat32(this.position,e??this.endianness);return this.position+=4,t},d.prototype.readFloat64=function(e){var t=this._dataView.getFloat64(this.position,e??this.endianness);return this.position+=8,t},d.endianness=new Int8Array(new Int16Array([1]).buffer)[0]>0,d.memcpy=function(e,t,r,l,h){var m=new Uint8Array(e,t,h),y=new Uint8Array(r,l,h);m.set(y)},d.arrayToNative=function(e,t){return t==this.endianness?e:this.flipArrayEndianness(e)},d.nativeToEndian=function(e,t){return this.endianness==t?e:this.flipArrayEndianness(e)},d.flipArrayEndianness=function(e){for(var t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=0;r<e.byteLength;r+=e.BYTES_PER_ELEMENT)for(var l=r+e.BYTES_PER_ELEMENT-1,h=r;l>h;l--,h++){var m=t[h];t[h]=t[l],t[l]=m}return e},d.prototype.failurePosition=0,String.fromCharCodeUint8=function(e){for(var t=[],r=0;r<e.length;r++)t[r]=e[r];return String.fromCharCode.apply(null,t)},d.prototype.readString=function(e,t){return t==null||t=="ASCII"?String.fromCharCodeUint8.apply(null,[this.mapUint8Array(e??this.byteLength-this.position)]):new TextDecoder(t).decode(this.mapUint8Array(e))},d.prototype.readCString=function(e){var t=this.byteLength-this.position,r=new Uint8Array(this._buffer,this._byteOffset+this.position),l=t;e!=null&&(l=Math.min(e,t));for(var h=0;h<l&&r[h]!==0;h++);var m=String.fromCharCodeUint8.apply(null,[this.mapUint8Array(h)]);return e!=null?this.position+=l-h:h!=t&&(this.position+=1),m};var f=Math.pow(2,32);d.prototype.readInt64=function(){return this.readInt32()*f+this.readUint32()},d.prototype.readUint64=function(){return this.readUint32()*f+this.readUint32()},d.prototype.readInt64=function(){return this.readUint32()*f+this.readUint32()},d.prototype.readUint24=function(){return(this.readUint8()<<16)+(this.readUint8()<<8)+this.readUint8()},a.DataStream=d,d.prototype.save=function(e){var t=new Blob([this.buffer]);if(window.URL&&URL.createObjectURL){var r=window.URL.createObjectURL(t),l=document.createElement("a");document.body.appendChild(l),l.setAttribute("href",r),l.setAttribute("download",e),l.setAttribute("target","_self"),l.click(),window.URL.revokeObjectURL(r)}else throw"DataStream.save: Can\'t create object URL."},d.prototype._dynamicSize=!0,Object.defineProperty(d.prototype,"dynamicSize",{get:function(){return this._dynamicSize},set:function(e){e||this._trimAlloc(),this._dynamicSize=e}}),d.prototype.shift=function(e){var t=new ArrayBuffer(this._byteLength-e),r=new Uint8Array(t),l=new Uint8Array(this._buffer,e,r.length);r.set(l),this.buffer=t,this.position-=e},d.prototype.writeInt32Array=function(e,t){if(this._realloc(e.length*4),e instanceof Int32Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapInt32Array(e.length,t);else for(var r=0;r<e.length;r++)this.writeInt32(e[r],t)},d.prototype.writeInt16Array=function(e,t){if(this._realloc(e.length*2),e instanceof Int16Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapInt16Array(e.length,t);else for(var r=0;r<e.length;r++)this.writeInt16(e[r],t)},d.prototype.writeInt8Array=function(e){if(this._realloc(e.length*1),e instanceof Int8Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapInt8Array(e.length);else for(var t=0;t<e.length;t++)this.writeInt8(e[t])},d.prototype.writeUint32Array=function(e,t){if(this._realloc(e.length*4),e instanceof Uint32Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapUint32Array(e.length,t);else for(var r=0;r<e.length;r++)this.writeUint32(e[r],t)},d.prototype.writeUint16Array=function(e,t){if(this._realloc(e.length*2),e instanceof Uint16Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapUint16Array(e.length,t);else for(var r=0;r<e.length;r++)this.writeUint16(e[r],t)},d.prototype.writeUint8Array=function(e){if(this._realloc(e.length*1),e instanceof Uint8Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapUint8Array(e.length);else for(var t=0;t<e.length;t++)this.writeUint8(e[t])},d.prototype.writeFloat64Array=function(e,t){if(this._realloc(e.length*8),e instanceof Float64Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapFloat64Array(e.length,t);else for(var r=0;r<e.length;r++)this.writeFloat64(e[r],t)},d.prototype.writeFloat32Array=function(e,t){if(this._realloc(e.length*4),e instanceof Float32Array&&this.byteOffset+this.position%e.BYTES_PER_ELEMENT===0)d.memcpy(this._buffer,this.byteOffset+this.position,e.buffer,0,e.byteLength),this.mapFloat32Array(e.length,t);else for(var r=0;r<e.length;r++)this.writeFloat32(e[r],t)},d.prototype.writeInt32=function(e,t){this._realloc(4),this._dataView.setInt32(this.position,e,t??this.endianness),this.position+=4},d.prototype.writeInt16=function(e,t){this._realloc(2),this._dataView.setInt16(this.position,e,t??this.endianness),this.position+=2},d.prototype.writeInt8=function(e){this._realloc(1),this._dataView.setInt8(this.position,e),this.position+=1},d.prototype.writeUint32=function(e,t){this._realloc(4),this._dataView.setUint32(this.position,e,t??this.endianness),this.position+=4},d.prototype.writeUint16=function(e,t){this._realloc(2),this._dataView.setUint16(this.position,e,t??this.endianness),this.position+=2},d.prototype.writeUint8=function(e){this._realloc(1),this._dataView.setUint8(this.position,e),this.position+=1},d.prototype.writeFloat32=function(e,t){this._realloc(4),this._dataView.setFloat32(this.position,e,t??this.endianness),this.position+=4},d.prototype.writeFloat64=function(e,t){this._realloc(8),this._dataView.setFloat64(this.position,e,t??this.endianness),this.position+=8},d.prototype.writeUCS2String=function(e,t,r){r==null&&(r=e.length);for(var l=0;l<e.length&&l<r;l++)this.writeUint16(e.charCodeAt(l),t);for(;l<r;l++)this.writeUint16(0)},d.prototype.writeString=function(e,t,r){var l=0;if(t==null||t=="ASCII")if(r!=null){var h=Math.min(e.length,r);for(l=0;l<h;l++)this.writeUint8(e.charCodeAt(l));for(;l<r;l++)this.writeUint8(0)}else for(l=0;l<e.length;l++)this.writeUint8(e.charCodeAt(l));else this.writeUint8Array(new TextEncoder(t).encode(e.substring(0,r)))},d.prototype.writeCString=function(e,t){var r=0;if(t!=null){var l=Math.min(e.length,t);for(r=0;r<l;r++)this.writeUint8(e.charCodeAt(r));for(;r<t;r++)this.writeUint8(0)}else{for(r=0;r<e.length;r++)this.writeUint8(e.charCodeAt(r));this.writeUint8(0)}},d.prototype.writeStruct=function(e,t){for(var r=0;r<e.length;r+=2){var l=e[r+1];this.writeType(l,t[e[r]],t)}},d.prototype.writeType=function(e,t,r){var l;if(typeof e=="function")return e(this,t);if(typeof e=="object"&&!(e instanceof Array))return e.set(this,t,r);var h=null,m="ASCII",y=this.position;switch(typeof e=="string"&&/:/.test(e)&&(l=e.split(":"),e=l[0],h=parseInt(l[1])),typeof e=="string"&&/,/.test(e)&&(l=e.split(","),e=l[0],m=parseInt(l[1])),e){case"uint8":this.writeUint8(t);break;case"int8":this.writeInt8(t);break;case"uint16":this.writeUint16(t,this.endianness);break;case"int16":this.writeInt16(t,this.endianness);break;case"uint32":this.writeUint32(t,this.endianness);break;case"int32":this.writeInt32(t,this.endianness);break;case"float32":this.writeFloat32(t,this.endianness);break;case"float64":this.writeFloat64(t,this.endianness);break;case"uint16be":this.writeUint16(t,d.BIG_ENDIAN);break;case"int16be":this.writeInt16(t,d.BIG_ENDIAN);break;case"uint32be":this.writeUint32(t,d.BIG_ENDIAN);break;case"int32be":this.writeInt32(t,d.BIG_ENDIAN);break;case"float32be":this.writeFloat32(t,d.BIG_ENDIAN);break;case"float64be":this.writeFloat64(t,d.BIG_ENDIAN);break;case"uint16le":this.writeUint16(t,d.LITTLE_ENDIAN);break;case"int16le":this.writeInt16(t,d.LITTLE_ENDIAN);break;case"uint32le":this.writeUint32(t,d.LITTLE_ENDIAN);break;case"int32le":this.writeInt32(t,d.LITTLE_ENDIAN);break;case"float32le":this.writeFloat32(t,d.LITTLE_ENDIAN);break;case"float64le":this.writeFloat64(t,d.LITTLE_ENDIAN);break;case"cstring":this.writeCString(t,h);break;case"string":this.writeString(t,m,h);break;case"u16string":this.writeUCS2String(t,this.endianness,h);break;case"u16stringle":this.writeUCS2String(t,d.LITTLE_ENDIAN,h);break;case"u16stringbe":this.writeUCS2String(t,d.BIG_ENDIAN,h);break;default:if(e.length==3){for(var b=e[1],x=0;x<t.length;x++)this.writeType(b,t[x]);break}else{this.writeStruct(e,t);break}}h!=null&&(this.position=y,this._realloc(h),this.position=y+h)},d.prototype.writeUint64=function(e){var t=Math.floor(e/f);this.writeUint32(t),this.writeUint32(e&4294967295)},d.prototype.writeUint24=function(e){this.writeUint8((e&16711680)>>16),this.writeUint8((e&65280)>>8),this.writeUint8(e&255)},d.prototype.adjustUint32=function(e,t){var r=this.position;this.seek(e),this.writeUint32(t),this.seek(r)},d.prototype.mapInt32Array=function(e,t){this._realloc(e*4);var r=new Int32Array(this._buffer,this.byteOffset+this.position,e);return d.arrayToNative(r,t??this.endianness),this.position+=e*4,r},d.prototype.mapInt16Array=function(e,t){this._realloc(e*2);var r=new Int16Array(this._buffer,this.byteOffset+this.position,e);return d.arrayToNative(r,t??this.endianness),this.position+=e*2,r},d.prototype.mapInt8Array=function(e){this._realloc(e*1);var t=new Int8Array(this._buffer,this.byteOffset+this.position,e);return this.position+=e*1,t},d.prototype.mapUint32Array=function(e,t){this._realloc(e*4);var r=new Uint32Array(this._buffer,this.byteOffset+this.position,e);return d.arrayToNative(r,t??this.endianness),this.position+=e*4,r},d.prototype.mapUint16Array=function(e,t){this._realloc(e*2);var r=new Uint16Array(this._buffer,this.byteOffset+this.position,e);return d.arrayToNative(r,t??this.endianness),this.position+=e*2,r},d.prototype.mapFloat64Array=function(e,t){this._realloc(e*8);var r=new Float64Array(this._buffer,this.byteOffset+this.position,e);return d.arrayToNative(r,t??this.endianness),this.position+=e*8,r},d.prototype.mapFloat32Array=function(e,t){this._realloc(e*4);var r=new Float32Array(this._buffer,this.byteOffset+this.position,e);return d.arrayToNative(r,t??this.endianness),this.position+=e*4,r};var c=function(e){this.buffers=[],this.bufferIndex=-1,e&&(this.insertBuffer(e),this.bufferIndex=0)};c.prototype=new d(new ArrayBuffer,0,d.BIG_ENDIAN),c.prototype.initialized=function(){var e;return this.bufferIndex>-1?!0:this.buffers.length>0?(e=this.buffers[0],e.fileStart===0?(this.buffer=e,this.bufferIndex=0,n.debug("MultiBufferStream","Stream ready for parsing"),!0):(n.warn("MultiBufferStream","The first buffer should have a fileStart of 0"),this.logBufferLevel(),!1)):(n.warn("MultiBufferStream","No buffer to start parsing from"),this.logBufferLevel(),!1)},ArrayBuffer.concat=function(e,t){n.debug("ArrayBuffer","Trying to create a new buffer of size: "+(e.byteLength+t.byteLength));var r=new Uint8Array(e.byteLength+t.byteLength);return r.set(new Uint8Array(e),0),r.set(new Uint8Array(t),e.byteLength),r.buffer},c.prototype.reduceBuffer=function(e,t,r){var l;return l=new Uint8Array(r),l.set(new Uint8Array(e,t,r)),l.buffer.fileStart=e.fileStart+t,l.buffer.usedBytes=0,l.buffer},c.prototype.insertBuffer=function(e){for(var t=!0,r=0;r<this.buffers.length;r++){var l=this.buffers[r];if(e.fileStart<=l.fileStart){if(e.fileStart===l.fileStart)if(e.byteLength>l.byteLength){this.buffers.splice(r,1),r--;continue}else n.warn("MultiBufferStream","Buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+") already appended, ignoring");else e.fileStart+e.byteLength<=l.fileStart||(e=this.reduceBuffer(e,0,l.fileStart-e.fileStart)),n.debug("MultiBufferStream","Appending new buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+")"),this.buffers.splice(r,0,e),r===0&&(this.buffer=e);t=!1;break}else if(e.fileStart<l.fileStart+l.byteLength){var h=l.fileStart+l.byteLength-e.fileStart,m=e.byteLength-h;if(m>0)e=this.reduceBuffer(e,h,m);else{t=!1;break}}}t&&(n.debug("MultiBufferStream","Appending new buffer (fileStart: "+e.fileStart+" - Length: "+e.byteLength+")"),this.buffers.push(e),r===0&&(this.buffer=e))},c.prototype.logBufferLevel=function(e){var t,r,l,h,m=[],y,b="";for(l=0,h=0,t=0;t<this.buffers.length;t++)r=this.buffers[t],t===0?(y={},m.push(y),y.start=r.fileStart,y.end=r.fileStart+r.byteLength,b+="["+y.start+"-"):y.end===r.fileStart?y.end=r.fileStart+r.byteLength:(y={},y.start=r.fileStart,b+=m[m.length-1].end-1+"], ["+y.start+"-",y.end=r.fileStart+r.byteLength,m.push(y)),l+=r.usedBytes,h+=r.byteLength;m.length>0&&(b+=y.end-1+"]");var x=e?n.info:n.debug;this.buffers.length===0?x("MultiBufferStream","No more buffer in memory"):x("MultiBufferStream",""+this.buffers.length+" stored buffer(s) ("+l+"/"+h+" bytes), continuous ranges: "+b)},c.prototype.cleanBuffers=function(){var e,t;for(e=0;e<this.buffers.length;e++)t=this.buffers[e],t.usedBytes===t.byteLength&&(n.debug("MultiBufferStream","Removing buffer #"+e),this.buffers.splice(e,1),e--)},c.prototype.mergeNextBuffer=function(){var e;if(this.bufferIndex+1<this.buffers.length)if(e=this.buffers[this.bufferIndex+1],e.fileStart===this.buffer.fileStart+this.buffer.byteLength){var t=this.buffer.byteLength,r=this.buffer.usedBytes,l=this.buffer.fileStart;return this.buffers[this.bufferIndex]=ArrayBuffer.concat(this.buffer,e),this.buffer=this.buffers[this.bufferIndex],this.buffers.splice(this.bufferIndex+1,1),this.buffer.usedBytes=r,this.buffer.fileStart=l,n.debug("ISOFile","Concatenating buffer for box parsing (length: "+t+"->"+this.buffer.byteLength+")"),!0}else return!1;else return!1},c.prototype.findPosition=function(e,t,r){var l,h=null,m=-1;for(e===!0?l=0:l=this.bufferIndex;l<this.buffers.length&&(h=this.buffers[l],h.fileStart<=t);){m=l,r&&(h.fileStart+h.byteLength<=t?h.usedBytes=h.byteLength:h.usedBytes=t-h.fileStart,this.logBufferLevel());l++}return m!==-1?(h=this.buffers[m],h.fileStart+h.byteLength>=t?(n.debug("MultiBufferStream","Found position in existing buffer #"+m),m):-1):-1},c.prototype.findEndContiguousBuf=function(e){var t,r,l,h=e!==void 0?e:this.bufferIndex;if(r=this.buffers[h],this.buffers.length>h+1)for(t=h+1;t<this.buffers.length&&(l=this.buffers[t],l.fileStart===r.fileStart+r.byteLength);t++)r=l;return r.fileStart+r.byteLength},c.prototype.getEndFilePositionAfter=function(e){var t=this.findPosition(!0,e,!1);return t!==-1?this.findEndContiguousBuf(t):e},c.prototype.addUsedBytes=function(e){this.buffer.usedBytes+=e,this.logBufferLevel()},c.prototype.setAllUsedBytes=function(){this.buffer.usedBytes=this.buffer.byteLength,this.logBufferLevel()},c.prototype.seek=function(e,t,r){var l;return l=this.findPosition(t,e,r),l!==-1?(this.buffer=this.buffers[l],this.bufferIndex=l,this.position=e-this.buffer.fileStart,n.debug("MultiBufferStream","Repositioning parser at buffer position: "+this.position),!0):(n.debug("MultiBufferStream","Position "+e+" not found in buffered data"),!1)},c.prototype.getPosition=function(){if(this.bufferIndex===-1||this.buffers[this.bufferIndex]===null)throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.position},c.prototype.getLength=function(){return this.byteLength},c.prototype.getEndPosition=function(){if(this.bufferIndex===-1||this.buffers[this.bufferIndex]===null)throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.byteLength},a.MultiBufferStream=c;var u=function(){var e=3,t=4,r=5,l=6,h=[];h[e]="ES_Descriptor",h[t]="DecoderConfigDescriptor",h[r]="DecoderSpecificInfo",h[l]="SLConfigDescriptor",this.getDescriptorName=function(b){return h[b]};var m=this,y={};return this.parseOneDescriptor=function(b){var x=0,w,T,C;for(w=b.readUint8(),C=b.readUint8();C&128;)x=(x<<7)+(C&127),C=b.readUint8();return x=(x<<7)+(C&127),n.debug("MPEG4DescriptorParser","Found "+(h[w]||"Descriptor "+w)+", size "+x+" at position "+b.getPosition()),h[w]?T=new y[h[w]](x):T=new y.Descriptor(x),T.parse(b),T},y.Descriptor=function(b,x){this.tag=b,this.size=x,this.descs=[]},y.Descriptor.prototype.parse=function(b){this.data=b.readUint8Array(this.size)},y.Descriptor.prototype.findDescriptor=function(b){for(var x=0;x<this.descs.length;x++)if(this.descs[x].tag==b)return this.descs[x];return null},y.Descriptor.prototype.parseRemainingDescriptors=function(b){for(var x=b.position;b.position<x+this.size;){var w=m.parseOneDescriptor(b);this.descs.push(w)}},y.ES_Descriptor=function(b){y.Descriptor.call(this,e,b)},y.ES_Descriptor.prototype=new y.Descriptor,y.ES_Descriptor.prototype.parse=function(b){if(this.ES_ID=b.readUint16(),this.flags=b.readUint8(),this.size-=3,this.flags&128?(this.dependsOn_ES_ID=b.readUint16(),this.size-=2):this.dependsOn_ES_ID=0,this.flags&64){var x=b.readUint8();this.URL=b.readString(x),this.size-=x+1}else this.URL="";this.flags&32?(this.OCR_ES_ID=b.readUint16(),this.size-=2):this.OCR_ES_ID=0,this.parseRemainingDescriptors(b)},y.ES_Descriptor.prototype.getOTI=function(b){var x=this.findDescriptor(t);return x?x.oti:0},y.ES_Descriptor.prototype.getAudioConfig=function(b){var x=this.findDescriptor(t);if(!x)return null;var w=x.findDescriptor(r);if(w&&w.data){var T=(w.data[0]&248)>>3;return T===31&&w.data.length>=2&&(T=32+((w.data[0]&7)<<3)+((w.data[1]&224)>>5)),T}else return null},y.DecoderConfigDescriptor=function(b){y.Descriptor.call(this,t,b)},y.DecoderConfigDescriptor.prototype=new y.Descriptor,y.DecoderConfigDescriptor.prototype.parse=function(b){this.oti=b.readUint8(),this.streamType=b.readUint8(),this.upStream=(this.streamType>>1&1)!==0,this.streamType=this.streamType>>>2,this.bufferSize=b.readUint24(),this.maxBitrate=b.readUint32(),this.avgBitrate=b.readUint32(),this.size-=13,this.parseRemainingDescriptors(b)},y.DecoderSpecificInfo=function(b){y.Descriptor.call(this,r,b)},y.DecoderSpecificInfo.prototype=new y.Descriptor,y.SLConfigDescriptor=function(b){y.Descriptor.call(this,l,b)},y.SLConfigDescriptor.prototype=new y.Descriptor,this};a.MPEG4DescriptorParser=u;var s={ERR_INVALID_DATA:-1,ERR_NOT_ENOUGH_DATA:0,OK:1,BASIC_BOXES:["mdat","idat","free","skip","meco","strk"],FULL_BOXES:["hmhd","nmhd","iods","xml ","bxml","ipro","mere"],CONTAINER_BOXES:[["moov",["trak","pssh"]],["trak"],["edts"],["mdia"],["minf"],["dinf"],["stbl",["sgpd","sbgp"]],["mvex",["trex"]],["moof",["traf"]],["traf",["trun","sgpd","sbgp"]],["vttc"],["tref"],["iref"],["mfra",["tfra"]],["meco"],["hnti"],["hinf"],["strk"],["strd"],["sinf"],["rinf"],["schi"],["trgr"],["udta",["kind"]],["iprp",["ipma"]],["ipco"],["grpl"],["j2kH"],["etyp",["tyco"]]],boxCodes:[],fullBoxCodes:[],containerBoxCodes:[],sampleEntryCodes:{},sampleGroupEntryCodes:[],trackGroupTypes:[],UUIDBoxes:{},UUIDs:[],initialize:function(){s.FullBox.prototype=new s.Box,s.ContainerBox.prototype=new s.Box,s.SampleEntry.prototype=new s.Box,s.TrackGroupTypeBox.prototype=new s.FullBox,s.BASIC_BOXES.forEach(function(e){s.createBoxCtor(e)}),s.FULL_BOXES.forEach(function(e){s.createFullBoxCtor(e)}),s.CONTAINER_BOXES.forEach(function(e){s.createContainerBoxCtor(e[0],null,e[1])})},Box:function(e,t,r){this.type=e,this.size=t,this.uuid=r},FullBox:function(e,t,r){s.Box.call(this,e,t,r),this.flags=0,this.version=0},ContainerBox:function(e,t,r){s.Box.call(this,e,t,r),this.boxes=[]},SampleEntry:function(e,t,r,l){s.ContainerBox.call(this,e,t),this.hdr_size=r,this.start=l},SampleGroupEntry:function(e){this.grouping_type=e},TrackGroupTypeBox:function(e,t){s.FullBox.call(this,e,t)},createBoxCtor:function(e,t){s.boxCodes.push(e),s[e+"Box"]=function(r){s.Box.call(this,e,r)},s[e+"Box"].prototype=new s.Box,t&&(s[e+"Box"].prototype.parse=t)},createFullBoxCtor:function(e,t){s[e+"Box"]=function(r){s.FullBox.call(this,e,r)},s[e+"Box"].prototype=new s.FullBox,s[e+"Box"].prototype.parse=function(r){this.parseFullHeader(r),t&&t.call(this,r)}},addSubBoxArrays:function(e){if(e){this.subBoxNames=e;for(var t=e.length,r=0;r<t;r++)this[e[r]+"s"]=[]}},createContainerBoxCtor:function(e,t,r){s[e+"Box"]=function(l){s.ContainerBox.call(this,e,l),s.addSubBoxArrays.call(this,r)},s[e+"Box"].prototype=new s.ContainerBox,t&&(s[e+"Box"].prototype.parse=t)},createMediaSampleEntryCtor:function(e,t,r){s.sampleEntryCodes[e]=[],s[e+"SampleEntry"]=function(l,h){s.SampleEntry.call(this,l,h),s.addSubBoxArrays.call(this,r)},s[e+"SampleEntry"].prototype=new s.SampleEntry,t&&(s[e+"SampleEntry"].prototype.parse=t)},createSampleEntryCtor:function(e,t,r,l){s.sampleEntryCodes[e].push(t),s[t+"SampleEntry"]=function(h){s[e+"SampleEntry"].call(this,t,h),s.addSubBoxArrays.call(this,l)},s[t+"SampleEntry"].prototype=new s[e+"SampleEntry"],r&&(s[t+"SampleEntry"].prototype.parse=r)},createEncryptedSampleEntryCtor:function(e,t,r){s.createSampleEntryCtor.call(this,e,t,r,["sinf"])},createSampleGroupCtor:function(e,t){s[e+"SampleGroupEntry"]=function(r){s.SampleGroupEntry.call(this,e,r)},s[e+"SampleGroupEntry"].prototype=new s.SampleGroupEntry,t&&(s[e+"SampleGroupEntry"].prototype.parse=t)},createTrackGroupCtor:function(e,t){s[e+"TrackGroupTypeBox"]=function(r){s.TrackGroupTypeBox.call(this,e,r)},s[e+"TrackGroupTypeBox"].prototype=new s.TrackGroupTypeBox,t&&(s[e+"TrackGroupTypeBox"].prototype.parse=t)},createUUIDBox:function(e,t,r,l){s.UUIDs.push(e),s.UUIDBoxes[e]=function(h){t?s.FullBox.call(this,"uuid",h,e):r?s.ContainerBox.call(this,"uuid",h,e):s.Box.call(this,"uuid",h,e)},s.UUIDBoxes[e].prototype=t?new s.FullBox:r?new s.ContainerBox:new s.Box,l&&(t?s.UUIDBoxes[e].prototype.parse=function(h){this.parseFullHeader(h),l&&l.call(this,h)}:s.UUIDBoxes[e].prototype.parse=l)}};s.initialize(),s.TKHD_FLAG_ENABLED=1,s.TKHD_FLAG_IN_MOVIE=2,s.TKHD_FLAG_IN_PREVIEW=4,s.TFHD_FLAG_BASE_DATA_OFFSET=1,s.TFHD_FLAG_SAMPLE_DESC=2,s.TFHD_FLAG_SAMPLE_DUR=8,s.TFHD_FLAG_SAMPLE_SIZE=16,s.TFHD_FLAG_SAMPLE_FLAGS=32,s.TFHD_FLAG_DUR_EMPTY=65536,s.TFHD_FLAG_DEFAULT_BASE_IS_MOOF=131072,s.TRUN_FLAGS_DATA_OFFSET=1,s.TRUN_FLAGS_FIRST_FLAG=4,s.TRUN_FLAGS_DURATION=256,s.TRUN_FLAGS_SIZE=512,s.TRUN_FLAGS_FLAGS=1024,s.TRUN_FLAGS_CTS_OFFSET=2048,s.Box.prototype.add=function(e){return this.addBox(new s[e+"Box"])},s.Box.prototype.addBox=function(e){return this.boxes.push(e),this[e.type+"s"]?this[e.type+"s"].push(e):this[e.type]=e,e},s.Box.prototype.set=function(e,t){return this[e]=t,this},s.Box.prototype.addEntry=function(e,t){var r=t||"entries";return this[r]||(this[r]=[]),this[r].push(e),this},a.BoxParser=s,s.parseUUID=function(e){return s.parseHex16(e)},s.parseHex16=function(e){for(var t="",r=0;r<16;r++){var l=e.readUint8().toString(16);t+=l.length===1?"0"+l:l}return t},s.parseOneBox=function(e,t,r){var l,h=e.getPosition(),m=0,y,b;if(e.getEndPosition()-h<8)return n.debug("BoxParser","Not enough data in stream to parse the type and size of the box"),{code:s.ERR_NOT_ENOUGH_DATA};if(r&&r<8)return n.debug("BoxParser","Not enough bytes left in the parent box to parse a new box"),{code:s.ERR_NOT_ENOUGH_DATA};var x=e.readUint32(),w=e.readString(4),T=w;if(n.debug("BoxParser","Found box of type \'"+w+"\' and size "+x+" at position "+h),m=8,w=="uuid"){if(e.getEndPosition()-e.getPosition()<16||r-m<16)return e.seek(h),n.debug("BoxParser","Not enough bytes left in the parent box to parse a UUID box"),{code:s.ERR_NOT_ENOUGH_DATA};b=s.parseUUID(e),m+=16,T=b}if(x==1){if(e.getEndPosition()-e.getPosition()<8||r&&r-m<8)return e.seek(h),n.warn("BoxParser",\'Not enough data in stream to parse the extended size of the "\'+w+\'" box\'),{code:s.ERR_NOT_ENOUGH_DATA};x=e.readUint64(),m+=8}else if(x===0){if(r)x=r;else if(w!=="mdat")return n.error("BoxParser","Unlimited box size not supported for type: \'"+w+"\'"),l=new s.Box(w,x),{code:s.OK,box:l,size:l.size}}return x!==0&&x<m?(n.error("BoxParser","Box of type "+w+" has an invalid size "+x+" (too small to be a box)"),{code:s.ERR_NOT_ENOUGH_DATA,type:w,size:x,hdr_size:m,start:h}):x!==0&&r&&x>r?(n.error("BoxParser","Box of type \'"+w+"\' has a size "+x+" greater than its container size "+r),{code:s.ERR_NOT_ENOUGH_DATA,type:w,size:x,hdr_size:m,start:h}):x!==0&&h+x>e.getEndPosition()?(e.seek(h),n.info("BoxParser","Not enough data in stream to parse the entire \'"+w+"\' box"),{code:s.ERR_NOT_ENOUGH_DATA,type:w,size:x,hdr_size:m,start:h}):t?{code:s.OK,type:w,size:x,hdr_size:m,start:h}:(s[w+"Box"]?l=new s[w+"Box"](x):w!=="uuid"?(n.warn("BoxParser","Unknown box type: \'"+w+"\'"),l=new s.Box(w,x),l.has_unparsed_data=!0):s.UUIDBoxes[b]?l=new s.UUIDBoxes[b](x):(n.warn("BoxParser","Unknown uuid type: \'"+b+"\'"),l=new s.Box(w,x),l.uuid=b,l.has_unparsed_data=!0),l.hdr_size=m,l.start=h,l.write===s.Box.prototype.write&&l.type!=="mdat"&&(n.info("BoxParser","\'"+T+"\' box writing not yet implemented, keeping unparsed data in memory for later write"),l.parseDataAndRewind(e)),l.parse(e),y=e.getPosition()-(l.start+l.size),y<0?(n.warn("BoxParser","Parsing of box \'"+T+"\' did not read the entire indicated box data size (missing "+-y+" bytes), seeking forward"),e.seek(l.start+l.size)):y>0&&(n.error("BoxParser","Parsing of box \'"+T+"\' read "+y+" more bytes than the indicated box data size, seeking backwards"),l.size!==0&&e.seek(l.start+l.size)),{code:s.OK,box:l,size:l.size})},s.Box.prototype.parse=function(e){this.type!="mdat"?this.data=e.readUint8Array(this.size-this.hdr_size):this.size===0?e.seek(e.getEndPosition()):e.seek(this.start+this.size)},s.Box.prototype.parseDataAndRewind=function(e){this.data=e.readUint8Array(this.size-this.hdr_size),e.position-=this.size-this.hdr_size},s.FullBox.prototype.parseDataAndRewind=function(e){this.parseFullHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size),this.hdr_size-=4,e.position-=this.size-this.hdr_size},s.FullBox.prototype.parseFullHeader=function(e){this.version=e.readUint8(),this.flags=e.readUint24(),this.hdr_size+=4},s.FullBox.prototype.parse=function(e){this.parseFullHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size)},s.ContainerBox.prototype.parse=function(e){for(var t,r;e.getPosition()<this.start+this.size;)if(t=s.parseOneBox(e,!1,this.size-(e.getPosition()-this.start)),t.code===s.OK)if(r=t.box,this.boxes.push(r),this.subBoxNames&&this.subBoxNames.indexOf(r.type)!=-1)this[this.subBoxNames[this.subBoxNames.indexOf(r.type)]+"s"].push(r);else{var l=r.type!=="uuid"?r.type:r.uuid;this[l]?n.warn("Box of type "+l+" already stored in field of this type"):this[l]=r}else return},s.Box.prototype.parseLanguage=function(e){this.language=e.readUint16();var t=[];t[0]=this.language>>10&31,t[1]=this.language>>5&31,t[2]=this.language&31,this.languageString=String.fromCharCode(t[0]+96,t[1]+96,t[2]+96)},s.SAMPLE_ENTRY_TYPE_VISUAL="Visual",s.SAMPLE_ENTRY_TYPE_AUDIO="Audio",s.SAMPLE_ENTRY_TYPE_HINT="Hint",s.SAMPLE_ENTRY_TYPE_METADATA="Metadata",s.SAMPLE_ENTRY_TYPE_SUBTITLE="Subtitle",s.SAMPLE_ENTRY_TYPE_SYSTEM="System",s.SAMPLE_ENTRY_TYPE_TEXT="Text",s.SampleEntry.prototype.parseHeader=function(e){e.readUint8Array(6),this.data_reference_index=e.readUint16(),this.hdr_size+=8},s.SampleEntry.prototype.parse=function(e){this.parseHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size)},s.SampleEntry.prototype.parseDataAndRewind=function(e){this.parseHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size),this.hdr_size-=8,e.position-=this.size-this.hdr_size},s.SampleEntry.prototype.parseFooter=function(e){s.ContainerBox.prototype.parse.call(this,e)},s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_HINT),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_METADATA),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SYSTEM),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_TEXT),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,function(e){var t;this.parseHeader(e),e.readUint16(),e.readUint16(),e.readUint32Array(3),this.width=e.readUint16(),this.height=e.readUint16(),this.horizresolution=e.readUint32(),this.vertresolution=e.readUint32(),e.readUint32(),this.frame_count=e.readUint16(),t=Math.min(31,e.readUint8()),this.compressorname=e.readString(t),t<31&&e.readString(31-t),this.depth=e.readUint16(),e.readUint16(),this.parseFooter(e)}),s.createMediaSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,function(e){this.parseHeader(e),e.readUint32Array(2),this.channel_count=e.readUint16(),this.samplesize=e.readUint16(),e.readUint16(),e.readUint16(),this.samplerate=e.readUint32()/65536,this.parseFooter(e)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"avc1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"avc2"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"avc3"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"avc4"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"av01"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"dav1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"hvc1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"hev1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"hvt1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"lhe1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"dvh1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"dvhe"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vvc1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vvi1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vvs1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vvcN"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vp08"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"vp09"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"avs3"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"j2ki"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"mjp2"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"mjpg"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"uncv"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"mp4a"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"ac-3"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"ac-4"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"ec-3"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"Opus"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"mha1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"mha2"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"mhm1"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"mhm2"),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"fLaC"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_VISUAL,"encv"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_AUDIO,"enca"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE,"encu"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SYSTEM,"encs"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_TEXT,"enct"),s.createEncryptedSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_METADATA,"encm"),s.createBoxCtor("a1lx",function(e){var t=e.readUint8()&1,r=((t&1)+1)*16;this.layer_size=[];for(var l=0;l<3;l++)r==16?this.layer_size[l]=e.readUint16():this.layer_size[l]=e.readUint32()}),s.createBoxCtor("a1op",function(e){this.op_index=e.readUint8()}),s.createFullBoxCtor("auxC",function(e){this.aux_type=e.readCString();var t=this.size-this.hdr_size-(this.aux_type.length+1);this.aux_subtype=e.readUint8Array(t)}),s.createBoxCtor("av1C",function(e){var t=e.readUint8();if(t>>7&!1){n.error("av1C marker problem");return}if(this.version=t&127,this.version!==1){n.error("av1C version "+this.version+" not supported");return}if(t=e.readUint8(),this.seq_profile=t>>5&7,this.seq_level_idx_0=t&31,t=e.readUint8(),this.seq_tier_0=t>>7&1,this.high_bitdepth=t>>6&1,this.twelve_bit=t>>5&1,this.monochrome=t>>4&1,this.chroma_subsampling_x=t>>3&1,this.chroma_subsampling_y=t>>2&1,this.chroma_sample_position=t&3,t=e.readUint8(),this.reserved_1=t>>5&7,this.reserved_1!==0){n.error("av1C reserved_1 parsing problem");return}if(this.initial_presentation_delay_present=t>>4&1,this.initial_presentation_delay_present===1)this.initial_presentation_delay_minus_one=t&15;else if(this.reserved_2=t&15,this.reserved_2!==0){n.error("av1C reserved_2 parsing problem");return}var r=this.size-this.hdr_size-4;this.configOBUs=e.readUint8Array(r)}),s.createBoxCtor("avcC",function(e){var t,r;for(this.configurationVersion=e.readUint8(),this.AVCProfileIndication=e.readUint8(),this.profile_compatibility=e.readUint8(),this.AVCLevelIndication=e.readUint8(),this.lengthSizeMinusOne=e.readUint8()&3,this.nb_SPS_nalus=e.readUint8()&31,r=this.size-this.hdr_size-6,this.SPS=[],t=0;t<this.nb_SPS_nalus;t++)this.SPS[t]={},this.SPS[t].length=e.readUint16(),this.SPS[t].nalu=e.readUint8Array(this.SPS[t].length),r-=2+this.SPS[t].length;for(this.nb_PPS_nalus=e.readUint8(),r--,this.PPS=[],t=0;t<this.nb_PPS_nalus;t++)this.PPS[t]={},this.PPS[t].length=e.readUint16(),this.PPS[t].nalu=e.readUint8Array(this.PPS[t].length),r-=2+this.PPS[t].length;r>0&&(this.ext=e.readUint8Array(r))}),s.createBoxCtor("btrt",function(e){this.bufferSizeDB=e.readUint32(),this.maxBitrate=e.readUint32(),this.avgBitrate=e.readUint32()}),s.createFullBoxCtor("ccst",function(e){var t=e.readUint8();this.all_ref_pics_intra=(t&128)==128,this.intra_pred_used=(t&64)==64,this.max_ref_per_pic=(t&63)>>2,e.readUint24()}),s.createBoxCtor("cdef",function(e){var t;for(this.channel_count=e.readUint16(),this.channel_indexes=[],this.channel_types=[],this.channel_associations=[],t=0;t<this.channel_count;t++)this.channel_indexes.push(e.readUint16()),this.channel_types.push(e.readUint16()),this.channel_associations.push(e.readUint16())}),s.createBoxCtor("clap",function(e){this.cleanApertureWidthN=e.readUint32(),this.cleanApertureWidthD=e.readUint32(),this.cleanApertureHeightN=e.readUint32(),this.cleanApertureHeightD=e.readUint32(),this.horizOffN=e.readUint32(),this.horizOffD=e.readUint32(),this.vertOffN=e.readUint32(),this.vertOffD=e.readUint32()}),s.createBoxCtor("clli",function(e){this.max_content_light_level=e.readUint16(),this.max_pic_average_light_level=e.readUint16()}),s.createFullBoxCtor("cmex",function(e){this.flags&1&&(this.pos_x=e.readInt32()),this.flags&2&&(this.pos_y=e.readInt32()),this.flags&4&&(this.pos_z=e.readInt32()),this.flags&8&&(this.version==0?this.flags&16?(this.quat_x=e.readInt32(),this.quat_y=e.readInt32(),this.quat_z=e.readInt32()):(this.quat_x=e.readInt16(),this.quat_y=e.readInt16(),this.quat_z=e.readInt16()):this.version==1),this.flags&32&&(this.id=e.readUint32())}),s.createFullBoxCtor("cmin",function(e){this.focal_length_x=e.readInt32(),this.principal_point_x=e.readInt32(),this.principal_point_y=e.readInt32(),this.flags&1&&(this.focal_length_y=e.readInt32(),this.skew_factor=e.readInt32())}),s.createBoxCtor("cmpd",function(e){for(this.component_count=e.readUint32(),this.component_types=[],this.component_type_urls=[],i=0;i<this.component_count;i++){var t=e.readUint16();this.component_types.push(t),t>=32768&&this.component_type_urls.push(e.readCString())}}),s.createFullBoxCtor("co64",function(e){var t,r;if(t=e.readUint32(),this.chunk_offsets=[],this.version===0)for(r=0;r<t;r++)this.chunk_offsets.push(e.readUint64())}),s.createFullBoxCtor("CoLL",function(e){this.maxCLL=e.readUint16(),this.maxFALL=e.readUint16()}),s.createBoxCtor("colr",function(e){if(this.colour_type=e.readString(4),this.colour_type==="nclx"){this.colour_primaries=e.readUint16(),this.transfer_characteristics=e.readUint16(),this.matrix_coefficients=e.readUint16();var t=e.readUint8();this.full_range_flag=t>>7}else this.colour_type==="rICC"?this.ICC_profile=e.readUint8Array(this.size-4):this.colour_type==="prof"&&(this.ICC_profile=e.readUint8Array(this.size-4))}),s.createFullBoxCtor("cprt",function(e){this.parseLanguage(e),this.notice=e.readCString()}),s.createFullBoxCtor("cslg",function(e){this.version===0&&(this.compositionToDTSShift=e.readInt32(),this.leastDecodeToDisplayDelta=e.readInt32(),this.greatestDecodeToDisplayDelta=e.readInt32(),this.compositionStartTime=e.readInt32(),this.compositionEndTime=e.readInt32())}),s.createFullBoxCtor("ctts",function(e){var t,r;if(t=e.readUint32(),this.sample_counts=[],this.sample_offsets=[],this.version===0)for(r=0;r<t;r++){this.sample_counts.push(e.readUint32());var l=e.readInt32();l<0&&n.warn("BoxParser","ctts box uses negative values without using version 1"),this.sample_offsets.push(l)}else if(this.version==1)for(r=0;r<t;r++)this.sample_counts.push(e.readUint32()),this.sample_offsets.push(e.readInt32())}),s.createBoxCtor("dac3",function(e){var t=e.readUint8(),r=e.readUint8(),l=e.readUint8();this.fscod=t>>6,this.bsid=t>>1&31,this.bsmod=(t&1)<<2|r>>6&3,this.acmod=r>>3&7,this.lfeon=r>>2&1,this.bit_rate_code=r&3|l>>5&7}),s.createBoxCtor("dec3",function(e){var t=e.readUint16();this.data_rate=t>>3,this.num_ind_sub=t&7,this.ind_subs=[];for(var r=0;r<this.num_ind_sub+1;r++){var l={};this.ind_subs.push(l);var h=e.readUint8(),m=e.readUint8(),y=e.readUint8();l.fscod=h>>6,l.bsid=h>>1&31,l.bsmod=(h&1)<<4|m>>4&15,l.acmod=m>>1&7,l.lfeon=m&1,l.num_dep_sub=y>>1&15,l.num_dep_sub>0&&(l.chan_loc=(y&1)<<8|e.readUint8())}}),s.createFullBoxCtor("dfLa",function(e){var t=127,r=128,l=[],h=["STREAMINFO","PADDING","APPLICATION","SEEKTABLE","VORBIS_COMMENT","CUESHEET","PICTURE","RESERVED"];do{var m=e.readUint8(),y=Math.min(m&t,h.length-1);if(y?e.readUint8Array(e.readUint24()):(e.readUint8Array(13),this.samplerate=e.readUint32()>>12,e.readUint8Array(20)),l.push(h[y]),m&r)break}while(!0);this.numMetadataBlocks=l.length+" ("+l.join(", ")+")"}),s.createBoxCtor("dimm",function(e){this.bytessent=e.readUint64()}),s.createBoxCtor("dmax",function(e){this.time=e.readUint32()}),s.createBoxCtor("dmed",function(e){this.bytessent=e.readUint64()}),s.createBoxCtor("dOps",function(e){if(this.Version=e.readUint8(),this.OutputChannelCount=e.readUint8(),this.PreSkip=e.readUint16(),this.InputSampleRate=e.readUint32(),this.OutputGain=e.readInt16(),this.ChannelMappingFamily=e.readUint8(),this.ChannelMappingFamily!==0){this.StreamCount=e.readUint8(),this.CoupledCount=e.readUint8(),this.ChannelMapping=[];for(var t=0;t<this.OutputChannelCount;t++)this.ChannelMapping[t]=e.readUint8()}}),s.createFullBoxCtor("dref",function(e){var t,r;this.entries=[];for(var l=e.readUint32(),h=0;h<l;h++)if(t=s.parseOneBox(e,!1,this.size-(e.getPosition()-this.start)),t.code===s.OK)r=t.box,this.entries.push(r);else return}),s.createBoxCtor("drep",function(e){this.bytessent=e.readUint64()}),s.createFullBoxCtor("elng",function(e){this.extended_language=e.readString(this.size-this.hdr_size)}),s.createFullBoxCtor("elst",function(e){this.entries=[];for(var t=e.readUint32(),r=0;r<t;r++){var l={};this.entries.push(l),this.version===1?(l.segment_duration=e.readUint64(),l.media_time=e.readInt64()):(l.segment_duration=e.readUint32(),l.media_time=e.readInt32()),l.media_rate_integer=e.readInt16(),l.media_rate_fraction=e.readInt16()}}),s.createFullBoxCtor("emsg",function(e){this.version==1?(this.timescale=e.readUint32(),this.presentation_time=e.readUint64(),this.event_duration=e.readUint32(),this.id=e.readUint32(),this.scheme_id_uri=e.readCString(),this.value=e.readCString()):(this.scheme_id_uri=e.readCString(),this.value=e.readCString(),this.timescale=e.readUint32(),this.presentation_time_delta=e.readUint32(),this.event_duration=e.readUint32(),this.id=e.readUint32());var t=this.size-this.hdr_size-(4*4+(this.scheme_id_uri.length+1)+(this.value.length+1));this.version==1&&(t-=4),this.message_data=e.readUint8Array(t)}),s.createEntityToGroupCtor=function(e,t){s[e+"Box"]=function(r){s.FullBox.call(this,e,r)},s[e+"Box"].prototype=new s.FullBox,s[e+"Box"].prototype.parse=function(r){if(this.parseFullHeader(r),t)t.call(this,r);else for(this.group_id=r.readUint32(),this.num_entities_in_group=r.readUint32(),this.entity_ids=[],i=0;i<this.num_entities_in_group;i++){var l=r.readUint32();this.entity_ids.push(l)}}},s.createEntityToGroupCtor("aebr"),s.createEntityToGroupCtor("afbr"),s.createEntityToGroupCtor("albc"),s.createEntityToGroupCtor("altr"),s.createEntityToGroupCtor("brst"),s.createEntityToGroupCtor("dobr"),s.createEntityToGroupCtor("eqiv"),s.createEntityToGroupCtor("favc"),s.createEntityToGroupCtor("fobr"),s.createEntityToGroupCtor("iaug"),s.createEntityToGroupCtor("pano"),s.createEntityToGroupCtor("slid"),s.createEntityToGroupCtor("ster"),s.createEntityToGroupCtor("tsyn"),s.createEntityToGroupCtor("wbbr"),s.createEntityToGroupCtor("prgr"),s.createEntityToGroupCtor("pymd",function(e){this.group_id=e.readUint32(),this.num_entities_in_group=e.readUint32(),this.entity_ids=[];for(var t=0;t<this.num_entities_in_group;t++){var r=e.readUint32();this.entity_ids.push(r)}for(this.tile_size_x=e.readUint16(),this.tile_size_y=e.readUint16(),this.layer_binning=[],this.tiles_in_layer_column_minus1=[],this.tiles_in_layer_row_minus1=[],t=0;t<this.num_entities_in_group;t++)this.layer_binning[t]=e.readUint16(),this.tiles_in_layer_row_minus1[t]=e.readUint16(),this.tiles_in_layer_column_minus1[t]=e.readUint16()}),s.createFullBoxCtor("esds",function(e){var t=e.readUint8Array(this.size-this.hdr_size);if(typeof u<"u"){var r=new u;this.esd=r.parseOneDescriptor(new d(t.buffer,0,d.BIG_ENDIAN))}}),s.createBoxCtor("fiel",function(e){this.fieldCount=e.readUint8(),this.fieldOrdering=e.readUint8()}),s.createBoxCtor("frma",function(e){this.data_format=e.readString(4)}),s.createBoxCtor("ftyp",function(e){var t=this.size-this.hdr_size;this.major_brand=e.readString(4),this.minor_version=e.readUint32(),t-=8,this.compatible_brands=[];for(var r=0;t>=4;)this.compatible_brands[r]=e.readString(4),t-=4,r++}),s.createFullBoxCtor("hdlr",function(e){this.version===0&&(e.readUint32(),this.handler=e.readString(4),e.readUint32Array(3),this.name=e.readString(this.size-this.hdr_size-20),this.name[this.name.length-1]==="\\0"&&(this.name=this.name.slice(0,-1)))}),s.createBoxCtor("hvcC",function(e){var t,r,l,h;this.configurationVersion=e.readUint8(),h=e.readUint8(),this.general_profile_space=h>>6,this.general_tier_flag=(h&32)>>5,this.general_profile_idc=h&31,this.general_profile_compatibility=e.readUint32(),this.general_constraint_indicator=e.readUint8Array(6),this.general_level_idc=e.readUint8(),this.min_spatial_segmentation_idc=e.readUint16()&4095,this.parallelismType=e.readUint8()&3,this.chroma_format_idc=e.readUint8()&3,this.bit_depth_luma_minus8=e.readUint8()&7,this.bit_depth_chroma_minus8=e.readUint8()&7,this.avgFrameRate=e.readUint16(),h=e.readUint8(),this.constantFrameRate=h>>6,this.numTemporalLayers=(h&13)>>3,this.temporalIdNested=(h&4)>>2,this.lengthSizeMinusOne=h&3,this.nalu_arrays=[];var m=e.readUint8();for(t=0;t<m;t++){var y=[];this.nalu_arrays.push(y),h=e.readUint8(),y.completeness=(h&128)>>7,y.nalu_type=h&63;var b=e.readUint16();for(r=0;r<b;r++){var x={};y.push(x),l=e.readUint16(),x.data=e.readUint8Array(l)}}}),s.createFullBoxCtor("iinf",function(e){var t;this.version===0?this.entry_count=e.readUint16():this.entry_count=e.readUint32(),this.item_infos=[];for(var r=0;r<this.entry_count;r++)if(t=s.parseOneBox(e,!1,this.size-(e.getPosition()-this.start)),t.code===s.OK)t.box.type!=="infe"&&n.error("BoxParser","Expected \'infe\' box, got "+t.box.type),this.item_infos[r]=t.box;else return}),s.createFullBoxCtor("iloc",function(e){var t;t=e.readUint8(),this.offset_size=t>>4&15,this.length_size=t&15,t=e.readUint8(),this.base_offset_size=t>>4&15,this.version===1||this.version===2?this.index_size=t&15:this.index_size=0,this.items=[];var r=0;if(this.version<2)r=e.readUint16();else if(this.version===2)r=e.readUint32();else throw"version of iloc box not supported";for(var l=0;l<r;l++){var h={};if(this.items.push(h),this.version<2)h.item_ID=e.readUint16();else if(this.version===2)h.item_ID=e.readUint32();else throw"version of iloc box not supported";switch(this.version===1||this.version===2?h.construction_method=e.readUint16()&15:h.construction_method=0,h.data_reference_index=e.readUint16(),this.base_offset_size){case 0:h.base_offset=0;break;case 4:h.base_offset=e.readUint32();break;case 8:h.base_offset=e.readUint64();break;default:throw"Error reading base offset size"}var m=e.readUint16();h.extents=[];for(var y=0;y<m;y++){var b={};if(h.extents.push(b),this.version===1||this.version===2)switch(this.index_size){case 0:b.extent_index=0;break;case 4:b.extent_index=e.readUint32();break;case 8:b.extent_index=e.readUint64();break;default:throw"Error reading extent index"}switch(this.offset_size){case 0:b.extent_offset=0;break;case 4:b.extent_offset=e.readUint32();break;case 8:b.extent_offset=e.readUint64();break;default:throw"Error reading extent index"}switch(this.length_size){case 0:b.extent_length=0;break;case 4:b.extent_length=e.readUint32();break;case 8:b.extent_length=e.readUint64();break;default:throw"Error reading extent index"}}}}),s.createBoxCtor("imir",function(e){var t=e.readUint8();this.reserved=t>>7,this.axis=t&1}),s.createFullBoxCtor("infe",function(e){if((this.version===0||this.version===1)&&(this.item_ID=e.readUint16(),this.item_protection_index=e.readUint16(),this.item_name=e.readCString(),this.content_type=e.readCString(),this.content_encoding=e.readCString()),this.version===1){this.extension_type=e.readString(4),n.warn("BoxParser","Cannot parse extension type"),e.seek(this.start+this.size);return}this.version>=2&&(this.version===2?this.item_ID=e.readUint16():this.version===3&&(this.item_ID=e.readUint32()),this.item_protection_index=e.readUint16(),this.item_type=e.readString(4),this.item_name=e.readCString(),this.item_type==="mime"?(this.content_type=e.readCString(),this.content_encoding=e.readCString()):this.item_type==="uri "&&(this.item_uri_type=e.readCString()))}),s.createFullBoxCtor("ipma",function(e){var t,r;for(entry_count=e.readUint32(),this.associations=[],t=0;t<entry_count;t++){var l={};this.associations.push(l),this.version<1?l.id=e.readUint16():l.id=e.readUint32();var h=e.readUint8();for(l.props=[],r=0;r<h;r++){var m=e.readUint8(),y={};l.props.push(y),y.essential=(m&128)>>7===1,this.flags&1?y.property_index=(m&127)<<8|e.readUint8():y.property_index=m&127}}}),s.createFullBoxCtor("iref",function(e){var t,r;for(this.references=[];e.getPosition()<this.start+this.size;)if(t=s.parseOneBox(e,!0,this.size-(e.getPosition()-this.start)),t.code===s.OK)this.version===0?r=new s.SingleItemTypeReferenceBox(t.type,t.size,t.hdr_size,t.start):r=new s.SingleItemTypeReferenceBoxLarge(t.type,t.size,t.hdr_size,t.start),r.write===s.Box.prototype.write&&r.type!=="mdat"&&(n.warn("BoxParser",r.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),r.parseDataAndRewind(e)),r.parse(e),this.references.push(r);else return}),s.createBoxCtor("irot",function(e){this.angle=e.readUint8()&3}),s.createFullBoxCtor("ispe",function(e){this.image_width=e.readUint32(),this.image_height=e.readUint32()}),s.createFullBoxCtor("kind",function(e){this.schemeURI=e.readCString(),this.value=e.readCString()}),s.createFullBoxCtor("leva",function(e){var t=e.readUint8();this.levels=[];for(var r=0;r<t;r++){var l={};this.levels[r]=l,l.track_ID=e.readUint32();var h=e.readUint8();switch(l.padding_flag=h>>7,l.assignment_type=h&127,l.assignment_type){case 0:l.grouping_type=e.readString(4);break;case 1:l.grouping_type=e.readString(4),l.grouping_type_parameter=e.readUint32();break;case 2:break;case 3:break;case 4:l.sub_track_id=e.readUint32();break;default:n.warn("BoxParser","Unknown leva assignement type")}}}),s.createBoxCtor("lhvC",function(e){var t,r,l;this.configurationVersion=e.readUint8(),this.min_spatial_segmentation_idc=e.readUint16()&4095,this.parallelismType=e.readUint8()&3,l=e.readUint8(),this.numTemporalLayers=(l&13)>>3,this.temporalIdNested=(l&4)>>2,this.lengthSizeMinusOne=l&3,this.nalu_arrays=[];var h=e.readUint8();for(t=0;t<h;t++){var m=[];this.nalu_arrays.push(m),l=e.readUint8(),m.completeness=(l&128)>>7,m.nalu_type=l&63;var y=e.readUint16();for(r=0;r<y;r++){var b={};m.push(b);var x=e.readUint16();b.data=e.readUint8Array(x)}}}),s.createBoxCtor("lsel",function(e){this.layer_id=e.readUint16()}),s.createBoxCtor("maxr",function(e){this.period=e.readUint32(),this.bytes=e.readUint32()});function p(e,t){this.x=e,this.y=t}p.prototype.toString=function(){return"("+this.x+","+this.y+")"},s.createBoxCtor("mdcv",function(e){this.display_primaries=[],this.display_primaries[0]=new p(e.readUint16(),e.readUint16()),this.display_primaries[1]=new p(e.readUint16(),e.readUint16()),this.display_primaries[2]=new p(e.readUint16(),e.readUint16()),this.white_point=new p(e.readUint16(),e.readUint16()),this.max_display_mastering_luminance=e.readUint32(),this.min_display_mastering_luminance=e.readUint32()}),s.createFullBoxCtor("mdhd",function(e){this.version==1?(this.creation_time=e.readUint64(),this.modification_time=e.readUint64(),this.timescale=e.readUint32(),this.duration=e.readUint64()):(this.creation_time=e.readUint32(),this.modification_time=e.readUint32(),this.timescale=e.readUint32(),this.duration=e.readUint32()),this.parseLanguage(e),e.readUint16()}),s.createFullBoxCtor("mehd",function(e){this.flags&1&&(n.warn("BoxParser","mehd box incorrectly uses flags set to 1, converting version to 1"),this.version=1),this.version==1?this.fragment_duration=e.readUint64():this.fragment_duration=e.readUint32()}),s.createFullBoxCtor("meta",function(e){this.boxes=[],s.ContainerBox.prototype.parse.call(this,e)}),s.createFullBoxCtor("mfhd",function(e){this.sequence_number=e.readUint32()}),s.createFullBoxCtor("mfro",function(e){this._size=e.readUint32()}),s.createFullBoxCtor("mskC",function(e){this.bits_per_pixel=e.readUint8()}),s.createFullBoxCtor("mvhd",function(e){this.version==1?(this.creation_time=e.readUint64(),this.modification_time=e.readUint64(),this.timescale=e.readUint32(),this.duration=e.readUint64()):(this.creation_time=e.readUint32(),this.modification_time=e.readUint32(),this.timescale=e.readUint32(),this.duration=e.readUint32()),this.rate=e.readUint32(),this.volume=e.readUint16()>>8,e.readUint16(),e.readUint32Array(2),this.matrix=e.readUint32Array(9),e.readUint32Array(6),this.next_track_id=e.readUint32()}),s.createBoxCtor("npck",function(e){this.packetssent=e.readUint32()}),s.createBoxCtor("nump",function(e){this.packetssent=e.readUint64()}),s.createFullBoxCtor("padb",function(e){var t=e.readUint32();this.padbits=[];for(var r=0;r<Math.floor((t+1)/2);r++)this.padbits=e.readUint8()}),s.createBoxCtor("pasp",function(e){this.hSpacing=e.readUint32(),this.vSpacing=e.readUint32()}),s.createBoxCtor("payl",function(e){this.text=e.readString(this.size-this.hdr_size)}),s.createBoxCtor("payt",function(e){this.payloadID=e.readUint32();var t=e.readUint8();this.rtpmap_string=e.readString(t)}),s.createFullBoxCtor("pdin",function(e){var t=(this.size-this.hdr_size)/8;this.rate=[],this.initial_delay=[];for(var r=0;r<t;r++)this.rate[r]=e.readUint32(),this.initial_delay[r]=e.readUint32()}),s.createFullBoxCtor("pitm",function(e){this.version===0?this.item_id=e.readUint16():this.item_id=e.readUint32()}),s.createFullBoxCtor("pixi",function(e){var t;for(this.num_channels=e.readUint8(),this.bits_per_channels=[],t=0;t<this.num_channels;t++)this.bits_per_channels[t]=e.readUint8()}),s.createBoxCtor("pmax",function(e){this.bytes=e.readUint32()}),s.createFullBoxCtor("prdi",function(e){if(this.step_count=e.readUint16(),this.item_count=[],this.flags&2)for(var t=0;t<this.step_count;t++)this.item_count[t]=e.readUint16()}),s.createFullBoxCtor("prft",function(e){this.ref_track_id=e.readUint32(),this.ntp_timestamp=e.readUint64(),this.version===0?this.media_time=e.readUint32():this.media_time=e.readUint64()}),s.createFullBoxCtor("pssh",function(e){if(this.system_id=s.parseHex16(e),this.version>0){var t=e.readUint32();this.kid=[];for(var r=0;r<t;r++)this.kid[r]=s.parseHex16(e)}var l=e.readUint32();l>0&&(this.data=e.readUint8Array(l))}),s.createFullBoxCtor("clef",function(e){this.width=e.readUint32(),this.height=e.readUint32()}),s.createFullBoxCtor("enof",function(e){this.width=e.readUint32(),this.height=e.readUint32()}),s.createFullBoxCtor("prof",function(e){this.width=e.readUint32(),this.height=e.readUint32()}),s.createContainerBoxCtor("tapt",null,["clef","prof","enof"]),s.createBoxCtor("rtp ",function(e){this.descriptionformat=e.readString(4),this.sdptext=e.readString(this.size-this.hdr_size-4)}),s.createFullBoxCtor("saio",function(e){this.flags&1&&(this.aux_info_type=e.readString(4),this.aux_info_type_parameter=e.readUint32());var t=e.readUint32();this.offset=[];for(var r=0;r<t;r++)this.version===0?this.offset[r]=e.readUint32():this.offset[r]=e.readUint64()}),s.createFullBoxCtor("saiz",function(e){if(this.flags&1&&(this.aux_info_type=e.readString(4),this.aux_info_type_parameter=e.readUint32()),this.default_sample_info_size=e.readUint8(),this.sample_count=e.readUint32(),this.sample_info_size=[],this.default_sample_info_size===0)for(var t=0;t<this.sample_count;t++)this.sample_info_size[t]=e.readUint8()}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_METADATA,"mett",function(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.mime_format=e.readCString(),this.parseFooter(e)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_METADATA,"metx",function(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.namespace=e.readCString(),this.schema_location=e.readCString(),this.parseFooter(e)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE,"sbtt",function(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.mime_format=e.readCString(),this.parseFooter(e)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE,"stpp",function(e){this.parseHeader(e),this.namespace=e.readCString(),this.schema_location=e.readCString(),this.auxiliary_mime_types=e.readCString(),this.parseFooter(e)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE,"stxt",function(e){this.parseHeader(e),this.content_encoding=e.readCString(),this.mime_format=e.readCString(),this.parseFooter(e)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_SUBTITLE,"tx3g",function(e){this.parseHeader(e),this.displayFlags=e.readUint32(),this.horizontal_justification=e.readInt8(),this.vertical_justification=e.readInt8(),this.bg_color_rgba=e.readUint8Array(4),this.box_record=e.readInt16Array(4),this.style_record=e.readUint8Array(12),this.parseFooter(e)}),s.createSampleEntryCtor(s.SAMPLE_ENTRY_TYPE_METADATA,"wvtt",function(e){this.parseHeader(e),this.parseFooter(e)}),s.createSampleGroupCtor("alst",function(e){var t,r=e.readUint16();for(this.first_output_sample=e.readUint16(),this.sample_offset=[],t=0;t<r;t++)this.sample_offset[t]=e.readUint32();var l=this.description_length-4-4*r;for(this.num_output_samples=[],this.num_total_samples=[],t=0;t<l/4;t++)this.num_output_samples[t]=e.readUint16(),this.num_total_samples[t]=e.readUint16()}),s.createSampleGroupCtor("avll",function(e){this.layerNumber=e.readUint8(),this.accurateStatisticsFlag=e.readUint8(),this.avgBitRate=e.readUint16(),this.avgFrameRate=e.readUint16()}),s.createSampleGroupCtor("avss",function(e){this.subSequenceIdentifier=e.readUint16(),this.layerNumber=e.readUint8();var t=e.readUint8();this.durationFlag=t>>7,this.avgRateFlag=t>>6&1,this.durationFlag&&(this.duration=e.readUint32()),this.avgRateFlag&&(this.accurateStatisticsFlag=e.readUint8(),this.avgBitRate=e.readUint16(),this.avgFrameRate=e.readUint16()),this.dependency=[];for(var r=e.readUint8(),l=0;l<r;l++){var h={};this.dependency.push(h),h.subSeqDirectionFlag=e.readUint8(),h.layerNumber=e.readUint8(),h.subSequenceIdentifier=e.readUint16()}}),s.createSampleGroupCtor("dtrt",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("mvif",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("prol",function(e){this.roll_distance=e.readInt16()}),s.createSampleGroupCtor("rap ",function(e){var t=e.readUint8();this.num_leading_samples_known=t>>7,this.num_leading_samples=t&127}),s.createSampleGroupCtor("rash",function(e){if(this.operation_point_count=e.readUint16(),this.description_length!==2+(this.operation_point_count===1?2:this.operation_point_count*6)+9)n.warn("BoxParser","Mismatch in "+this.grouping_type+" sample group length"),this.data=e.readUint8Array(this.description_length-2);else{if(this.operation_point_count===1)this.target_rate_share=e.readUint16();else{this.target_rate_share=[],this.available_bitrate=[];for(var t=0;t<this.operation_point_count;t++)this.available_bitrate[t]=e.readUint32(),this.target_rate_share[t]=e.readUint16()}this.maximum_bitrate=e.readUint32(),this.minimum_bitrate=e.readUint32(),this.discard_priority=e.readUint8()}}),s.createSampleGroupCtor("roll",function(e){this.roll_distance=e.readInt16()}),s.SampleGroupEntry.prototype.parse=function(e){n.warn("BoxParser","Unknown Sample Group type: "+this.grouping_type),this.data=e.readUint8Array(this.description_length)},s.createSampleGroupCtor("scif",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("scnm",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("seig",function(e){this.reserved=e.readUint8();var t=e.readUint8();this.crypt_byte_block=t>>4,this.skip_byte_block=t&15,this.isProtected=e.readUint8(),this.Per_Sample_IV_Size=e.readUint8(),this.KID=s.parseHex16(e),this.constant_IV_size=0,this.constant_IV=0,this.isProtected===1&&this.Per_Sample_IV_Size===0&&(this.constant_IV_size=e.readUint8(),this.constant_IV=e.readUint8Array(this.constant_IV_size))}),s.createSampleGroupCtor("stsa",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("sync",function(e){var t=e.readUint8();this.NAL_unit_type=t&63}),s.createSampleGroupCtor("tele",function(e){var t=e.readUint8();this.level_independently_decodable=t>>7}),s.createSampleGroupCtor("tsas",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("tscl",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createSampleGroupCtor("vipr",function(e){n.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),s.createFullBoxCtor("sbgp",function(e){this.grouping_type=e.readString(4),this.version===1?this.grouping_type_parameter=e.readUint32():this.grouping_type_parameter=0,this.entries=[];for(var t=e.readUint32(),r=0;r<t;r++){var l={};this.entries.push(l),l.sample_count=e.readInt32(),l.group_description_index=e.readInt32()}});function _(e,t){this.bad_pixel_row=e,this.bad_pixel_column=t}_.prototype.toString=function(){return"[row: "+this.bad_pixel_row+", column: "+this.bad_pixel_column+"]"},s.createFullBoxCtor("sbpm",function(e){var t;for(this.component_count=e.readUint16(),this.component_index=[],t=0;t<this.component_count;t++)this.component_index.push(e.readUint16());var r=e.readUint8();for(this.correction_applied=(r&128)==128,this.num_bad_rows=e.readUint32(),this.num_bad_cols=e.readUint32(),this.num_bad_pixels=e.readUint32(),this.bad_rows=[],this.bad_columns=[],this.bad_pixels=[],t=0;t<this.num_bad_rows;t++)this.bad_rows.push(e.readUint32());for(t=0;t<this.num_bad_cols;t++)this.bad_columns.push(e.readUint32());for(t=0;t<this.num_bad_pixels;t++){var l=e.readUint32(),h=e.readUint32();this.bad_pixels.push(new _(l,h))}}),s.createFullBoxCtor("schm",function(e){this.scheme_type=e.readString(4),this.scheme_version=e.readUint32(),this.flags&1&&(this.scheme_uri=e.readString(this.size-this.hdr_size-8))}),s.createBoxCtor("sdp ",function(e){this.sdptext=e.readString(this.size-this.hdr_size)}),s.createFullBoxCtor("sdtp",function(e){var t,r=this.size-this.hdr_size;this.is_leading=[],this.sample_depends_on=[],this.sample_is_depended_on=[],this.sample_has_redundancy=[];for(var l=0;l<r;l++)t=e.readUint8(),this.is_leading[l]=t>>6,this.sample_depends_on[l]=t>>4&3,this.sample_is_depended_on[l]=t>>2&3,this.sample_has_redundancy[l]=t&3}),s.createFullBoxCtor("senc"),s.createFullBoxCtor("sgpd",function(e){this.grouping_type=e.readString(4),n.debug("BoxParser","Found Sample Groups of type "+this.grouping_type),this.version===1?this.default_length=e.readUint32():this.default_length=0,this.version>=2&&(this.default_group_description_index=e.readUint32()),this.entries=[];for(var t=e.readUint32(),r=0;r<t;r++){var l;s[this.grouping_type+"SampleGroupEntry"]?l=new s[this.grouping_type+"SampleGroupEntry"](this.grouping_type):l=new s.SampleGroupEntry(this.grouping_type),this.entries.push(l),this.version===1?this.default_length===0?l.description_length=e.readUint32():l.description_length=this.default_length:l.description_length=this.default_length,l.write===s.SampleGroupEntry.prototype.write&&(n.info("BoxParser","SampleGroup for type "+this.grouping_type+" writing not yet implemented, keeping unparsed data in memory for later write"),l.data=e.readUint8Array(l.description_length),e.position-=l.description_length),l.parse(e)}}),s.createFullBoxCtor("sidx",function(e){this.reference_ID=e.readUint32(),this.timescale=e.readUint32(),this.version===0?(this.earliest_presentation_time=e.readUint32(),this.first_offset=e.readUint32()):(this.earliest_presentation_time=e.readUint64(),this.first_offset=e.readUint64()),e.readUint16(),this.references=[];for(var t=e.readUint16(),r=0;r<t;r++){var l={};this.references.push(l);var h=e.readUint32();l.reference_type=h>>31&1,l.referenced_size=h&2147483647,l.subsegment_duration=e.readUint32(),h=e.readUint32(),l.starts_with_SAP=h>>31&1,l.SAP_type=h>>28&7,l.SAP_delta_time=h&268435455}}),s.SingleItemTypeReferenceBox=function(e,t,r,l){s.Box.call(this,e,t),this.hdr_size=r,this.start=l},s.SingleItemTypeReferenceBox.prototype=new s.Box,s.SingleItemTypeReferenceBox.prototype.parse=function(e){this.from_item_ID=e.readUint16();var t=e.readUint16();this.references=[];for(var r=0;r<t;r++)this.references[r]={},this.references[r].to_item_ID=e.readUint16()},s.SingleItemTypeReferenceBoxLarge=function(e,t,r,l){s.Box.call(this,e,t),this.hdr_size=r,this.start=l},s.SingleItemTypeReferenceBoxLarge.prototype=new s.Box,s.SingleItemTypeReferenceBoxLarge.prototype.parse=function(e){this.from_item_ID=e.readUint32();var t=e.readUint16();this.references=[];for(var r=0;r<t;r++)this.references[r]={},this.references[r].to_item_ID=e.readUint32()},s.createFullBoxCtor("SmDm",function(e){this.primaryRChromaticity_x=e.readUint16(),this.primaryRChromaticity_y=e.readUint16(),this.primaryGChromaticity_x=e.readUint16(),this.primaryGChromaticity_y=e.readUint16(),this.primaryBChromaticity_x=e.readUint16(),this.primaryBChromaticity_y=e.readUint16(),this.whitePointChromaticity_x=e.readUint16(),this.whitePointChromaticity_y=e.readUint16(),this.luminanceMax=e.readUint32(),this.luminanceMin=e.readUint32()}),s.createFullBoxCtor("smhd",function(e){this.balance=e.readUint16(),e.readUint16()}),s.createFullBoxCtor("ssix",function(e){this.subsegments=[];for(var t=e.readUint32(),r=0;r<t;r++){var l={};this.subsegments.push(l),l.ranges=[];for(var h=e.readUint32(),m=0;m<h;m++){var y={};l.ranges.push(y),y.level=e.readUint8(),y.range_size=e.readUint24()}}}),s.createFullBoxCtor("stco",function(e){var t;if(t=e.readUint32(),this.chunk_offsets=[],this.version===0)for(var r=0;r<t;r++)this.chunk_offsets.push(e.readUint32())}),s.createFullBoxCtor("stdp",function(e){var t=(this.size-this.hdr_size)/2;this.priority=[];for(var r=0;r<t;r++)this.priority[r]=e.readUint16()}),s.createFullBoxCtor("sthd"),s.createFullBoxCtor("stri",function(e){this.switch_group=e.readUint16(),this.alternate_group=e.readUint16(),this.sub_track_id=e.readUint32();var t=(this.size-this.hdr_size-8)/4;this.attribute_list=[];for(var r=0;r<t;r++)this.attribute_list[r]=e.readUint32()}),s.createFullBoxCtor("stsc",function(e){var t,r;if(t=e.readUint32(),this.first_chunk=[],this.samples_per_chunk=[],this.sample_description_index=[],this.version===0)for(r=0;r<t;r++)this.first_chunk.push(e.readUint32()),this.samples_per_chunk.push(e.readUint32()),this.sample_description_index.push(e.readUint32())}),s.createFullBoxCtor("stsd",function(e){var t,r,l,h;for(this.entries=[],l=e.readUint32(),t=1;t<=l;t++)if(r=s.parseOneBox(e,!0,this.size-(e.getPosition()-this.start)),r.code===s.OK)s[r.type+"SampleEntry"]?(h=new s[r.type+"SampleEntry"](r.size),h.hdr_size=r.hdr_size,h.start=r.start):(n.warn("BoxParser","Unknown sample entry type: "+r.type),h=new s.SampleEntry(r.type,r.size,r.hdr_size,r.start)),h.write===s.SampleEntry.prototype.write&&(n.info("BoxParser","SampleEntry "+h.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),h.parseDataAndRewind(e)),h.parse(e),this.entries.push(h);else return}),s.createFullBoxCtor("stsg",function(e){this.grouping_type=e.readUint32();var t=e.readUint16();this.group_description_index=[];for(var r=0;r<t;r++)this.group_description_index[r]=e.readUint32()}),s.createFullBoxCtor("stsh",function(e){var t,r;if(t=e.readUint32(),this.shadowed_sample_numbers=[],this.sync_sample_numbers=[],this.version===0)for(r=0;r<t;r++)this.shadowed_sample_numbers.push(e.readUint32()),this.sync_sample_numbers.push(e.readUint32())}),s.createFullBoxCtor("stss",function(e){var t,r;if(r=e.readUint32(),this.version===0)for(this.sample_numbers=[],t=0;t<r;t++)this.sample_numbers.push(e.readUint32())}),s.createFullBoxCtor("stsz",function(e){var t;if(this.sample_sizes=[],this.version===0)for(this.sample_size=e.readUint32(),this.sample_count=e.readUint32(),t=0;t<this.sample_count;t++)this.sample_size===0?this.sample_sizes.push(e.readUint32()):this.sample_sizes[t]=this.sample_size}),s.createFullBoxCtor("stts",function(e){var t,r,l;if(t=e.readUint32(),this.sample_counts=[],this.sample_deltas=[],this.version===0)for(r=0;r<t;r++)this.sample_counts.push(e.readUint32()),l=e.readInt32(),l<0&&(n.warn("BoxParser","File uses negative stts sample delta, using value 1 instead, sync may be lost!"),l=1),this.sample_deltas.push(l)}),s.createFullBoxCtor("stvi",function(e){var t=e.readUint32();this.single_view_allowed=t&3,this.stereo_scheme=e.readUint32();var r=e.readUint32();this.stereo_indication_type=e.readString(r);var l,h;for(this.boxes=[];e.getPosition()<this.start+this.size;)if(l=s.parseOneBox(e,!1,this.size-(e.getPosition()-this.start)),l.code===s.OK)h=l.box,this.boxes.push(h),this[h.type]=h;else return}),s.createBoxCtor("styp",function(e){s.ftypBox.prototype.parse.call(this,e)}),s.createFullBoxCtor("stz2",function(e){var t,r;if(this.sample_sizes=[],this.version===0)if(this.reserved=e.readUint24(),this.field_size=e.readUint8(),r=e.readUint32(),this.field_size===4)for(t=0;t<r;t+=2){var l=e.readUint8();this.sample_sizes[t]=l>>4&15,this.sample_sizes[t+1]=l&15}else if(this.field_size===8)for(t=0;t<r;t++)this.sample_sizes[t]=e.readUint8();else if(this.field_size===16)for(t=0;t<r;t++)this.sample_sizes[t]=e.readUint16();else n.error("BoxParser","Error in length field in stz2 box")}),s.createFullBoxCtor("subs",function(e){var t,r,l,h;for(l=e.readUint32(),this.entries=[],t=0;t<l;t++){var m={};if(this.entries[t]=m,m.sample_delta=e.readUint32(),m.subsamples=[],h=e.readUint16(),h>0)for(r=0;r<h;r++){var y={};m.subsamples.push(y),this.version==1?y.size=e.readUint32():y.size=e.readUint16(),y.priority=e.readUint8(),y.discardable=e.readUint8(),y.codec_specific_parameters=e.readUint32()}}}),s.createFullBoxCtor("tenc",function(e){if(e.readUint8(),this.version===0)e.readUint8();else{var t=e.readUint8();this.default_crypt_byte_block=t>>4&15,this.default_skip_byte_block=t&15}this.default_isProtected=e.readUint8(),this.default_Per_Sample_IV_Size=e.readUint8(),this.default_KID=s.parseHex16(e),this.default_isProtected===1&&this.default_Per_Sample_IV_Size===0&&(this.default_constant_IV_size=e.readUint8(),this.default_constant_IV=e.readUint8Array(this.default_constant_IV_size))}),s.createFullBoxCtor("tfdt",function(e){this.version==1?this.baseMediaDecodeTime=e.readUint64():this.baseMediaDecodeTime=e.readUint32()}),s.createFullBoxCtor("tfhd",function(e){var t=0;this.track_id=e.readUint32(),this.size-this.hdr_size>t&&this.flags&s.TFHD_FLAG_BASE_DATA_OFFSET?(this.base_data_offset=e.readUint64(),t+=8):this.base_data_offset=0,this.size-this.hdr_size>t&&this.flags&s.TFHD_FLAG_SAMPLE_DESC?(this.default_sample_description_index=e.readUint32(),t+=4):this.default_sample_description_index=0,this.size-this.hdr_size>t&&this.flags&s.TFHD_FLAG_SAMPLE_DUR?(this.default_sample_duration=e.readUint32(),t+=4):this.default_sample_duration=0,this.size-this.hdr_size>t&&this.flags&s.TFHD_FLAG_SAMPLE_SIZE?(this.default_sample_size=e.readUint32(),t+=4):this.default_sample_size=0,this.size-this.hdr_size>t&&this.flags&s.TFHD_FLAG_SAMPLE_FLAGS?(this.default_sample_flags=e.readUint32(),t+=4):this.default_sample_flags=0}),s.createFullBoxCtor("tfra",function(e){this.track_ID=e.readUint32(),e.readUint24();var t=e.readUint8();this.length_size_of_traf_num=t>>4&3,this.length_size_of_trun_num=t>>2&3,this.length_size_of_sample_num=t&3,this.entries=[];for(var r=e.readUint32(),l=0;l<r;l++)this.version===1?(this.time=e.readUint64(),this.moof_offset=e.readUint64()):(this.time=e.readUint32(),this.moof_offset=e.readUint32()),this.traf_number=e["readUint"+8*(this.length_size_of_traf_num+1)](),this.trun_number=e["readUint"+8*(this.length_size_of_trun_num+1)](),this.sample_number=e["readUint"+8*(this.length_size_of_sample_num+1)]()}),s.createFullBoxCtor("tkhd",function(e){this.version==1?(this.creation_time=e.readUint64(),this.modification_time=e.readUint64(),this.track_id=e.readUint32(),e.readUint32(),this.duration=e.readUint64()):(this.creation_time=e.readUint32(),this.modification_time=e.readUint32(),this.track_id=e.readUint32(),e.readUint32(),this.duration=e.readUint32()),e.readUint32Array(2),this.layer=e.readInt16(),this.alternate_group=e.readInt16(),this.volume=e.readInt16()>>8,e.readUint16(),this.matrix=e.readInt32Array(9),this.width=e.readUint32(),this.height=e.readUint32()}),s.createBoxCtor("tmax",function(e){this.time=e.readUint32()}),s.createBoxCtor("tmin",function(e){this.time=e.readUint32()}),s.createBoxCtor("totl",function(e){this.bytessent=e.readUint32()}),s.createBoxCtor("tpay",function(e){this.bytessent=e.readUint32()}),s.createBoxCtor("tpyl",function(e){this.bytessent=e.readUint64()}),s.TrackGroupTypeBox.prototype.parse=function(e){this.parseFullHeader(e),this.track_group_id=e.readUint32()},s.createTrackGroupCtor("msrc"),s.TrackReferenceTypeBox=function(e,t,r,l){s.Box.call(this,e,t),this.hdr_size=r,this.start=l},s.TrackReferenceTypeBox.prototype=new s.Box,s.TrackReferenceTypeBox.prototype.parse=function(e){this.track_ids=e.readUint32Array((this.size-this.hdr_size)/4)},s.trefBox.prototype.parse=function(e){for(var t,r;e.getPosition()<this.start+this.size;)if(t=s.parseOneBox(e,!0,this.size-(e.getPosition()-this.start)),t.code===s.OK)r=new s.TrackReferenceTypeBox(t.type,t.size,t.hdr_size,t.start),r.write===s.Box.prototype.write&&r.type!=="mdat"&&(n.info("BoxParser","TrackReference "+r.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),r.parseDataAndRewind(e)),r.parse(e),this.boxes.push(r);else return},s.createFullBoxCtor("trep",function(e){for(this.track_ID=e.readUint32(),this.boxes=[];e.getPosition()<this.start+this.size;)if(ret=s.parseOneBox(e,!1,this.size-(e.getPosition()-this.start)),ret.code===s.OK)box=ret.box,this.boxes.push(box);else return}),s.createFullBoxCtor("trex",function(e){this.track_id=e.readUint32(),this.default_sample_description_index=e.readUint32(),this.default_sample_duration=e.readUint32(),this.default_sample_size=e.readUint32(),this.default_sample_flags=e.readUint32()}),s.createBoxCtor("trpy",function(e){this.bytessent=e.readUint64()}),s.createFullBoxCtor("trun",function(e){var t=0;if(this.sample_count=e.readUint32(),t+=4,this.size-this.hdr_size>t&&this.flags&s.TRUN_FLAGS_DATA_OFFSET?(this.data_offset=e.readInt32(),t+=4):this.data_offset=0,this.size-this.hdr_size>t&&this.flags&s.TRUN_FLAGS_FIRST_FLAG?(this.first_sample_flags=e.readUint32(),t+=4):this.first_sample_flags=0,this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[],this.size-this.hdr_size>t)for(var r=0;r<this.sample_count;r++)this.flags&s.TRUN_FLAGS_DURATION&&(this.sample_duration[r]=e.readUint32()),this.flags&s.TRUN_FLAGS_SIZE&&(this.sample_size[r]=e.readUint32()),this.flags&s.TRUN_FLAGS_FLAGS&&(this.sample_flags[r]=e.readUint32()),this.flags&s.TRUN_FLAGS_CTS_OFFSET&&(this.version===0?this.sample_composition_time_offset[r]=e.readUint32():this.sample_composition_time_offset[r]=e.readInt32())}),s.createFullBoxCtor("tsel",function(e){this.switch_group=e.readUint32();var t=(this.size-this.hdr_size-4)/4;this.attribute_list=[];for(var r=0;r<t;r++)this.attribute_list[r]=e.readUint32()}),s.createFullBoxCtor("txtC",function(e){this.config=e.readCString()}),s.createBoxCtor("tyco",function(e){var t=(this.size-this.hdr_size)/4;this.compatible_brands=[];for(var r=0;r<t;r++)this.compatible_brands[r]=e.readString(4)}),s.createFullBoxCtor("udes",function(e){this.lang=e.readCString(),this.name=e.readCString(),this.description=e.readCString(),this.tags=e.readCString()}),s.createFullBoxCtor("uncC",function(e){var t;if(this.profile=e.readUint32(),this.version!=1){if(this.version==0){for(this.component_count=e.readUint32(),this.component_index=[],this.component_bit_depth_minus_one=[],this.component_format=[],this.component_align_size=[],t=0;t<this.component_count;t++)this.component_index.push(e.readUint16()),this.component_bit_depth_minus_one.push(e.readUint8()),this.component_format.push(e.readUint8()),this.component_align_size.push(e.readUint8());this.sampling_type=e.readUint8(),this.interleave_type=e.readUint8(),this.block_size=e.readUint8();var r=e.readUint8();this.component_little_endian=r>>7&1,this.block_pad_lsb=r>>6&1,this.block_little_endian=r>>5&1,this.block_reversed=r>>4&1,this.pad_unknown=r>>3&1,this.pixel_size=e.readUint32(),this.row_align_size=e.readUint32(),this.tile_align_size=e.readUint32(),this.num_tile_cols_minus_one=e.readUint32(),this.num_tile_rows_minus_one=e.readUint32()}}}),s.createFullBoxCtor("url ",function(e){this.flags!==1&&(this.location=e.readCString())}),s.createFullBoxCtor("urn ",function(e){this.name=e.readCString(),this.size-this.hdr_size-this.name.length-1>0&&(this.location=e.readCString())}),s.createUUIDBox("a5d40b30e81411ddba2f0800200c9a66",!0,!1,function(e){this.LiveServerManifest=e.readString(this.size-this.hdr_size).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/\'/g,"'")}),s.createUUIDBox("d08a4f1810f34a82b6c832d8aba183d3",!0,!1,function(e){this.system_id=s.parseHex16(e);var t=e.readUint32();t>0&&(this.data=e.readUint8Array(t))}),s.createUUIDBox("a2394f525a9b4f14a2446c427c648df4",!0,!1),s.createUUIDBox("8974dbce7be74c5184f97148f9882554",!0,!1,function(e){this.default_AlgorithmID=e.readUint24(),this.default_IV_size=e.readUint8(),this.default_KID=s.parseHex16(e)}),s.createUUIDBox("d4807ef2ca3946958e5426cb9e46a79f",!0,!1,function(e){this.fragment_count=e.readUint8(),this.entries=[];for(var t=0;t<this.fragment_count;t++){var r={},l=0,h=0;this.version===1?(l=e.readUint64(),h=e.readUint64()):(l=e.readUint32(),h=e.readUint32()),r.absolute_time=l,r.absolute_duration=h,this.entries.push(r)}}),s.createUUIDBox("6d1d9b0542d544e680e2141daff757b2",!0,!1,function(e){this.version===1?(this.absolute_time=e.readUint64(),this.duration=e.readUint64()):(this.absolute_time=e.readUint32(),this.duration=e.readUint32())}),s.createFullBoxCtor("vmhd",function(e){this.graphicsmode=e.readUint16(),this.opcolor=e.readUint16Array(3)}),s.createFullBoxCtor("vpcC",function(e){var t;this.version===1?(this.profile=e.readUint8(),this.level=e.readUint8(),t=e.readUint8(),this.bitDepth=t>>4,this.chromaSubsampling=t>>1&7,this.videoFullRangeFlag=t&1,this.colourPrimaries=e.readUint8(),this.transferCharacteristics=e.readUint8(),this.matrixCoefficients=e.readUint8(),this.codecIntializationDataSize=e.readUint16(),this.codecIntializationData=e.readUint8Array(this.codecIntializationDataSize)):(this.profile=e.readUint8(),this.level=e.readUint8(),t=e.readUint8(),this.bitDepth=t>>4&15,this.colorSpace=t&15,t=e.readUint8(),this.chromaSubsampling=t>>4&15,this.transferFunction=t>>1&7,this.videoFullRangeFlag=t&1,this.codecIntializationDataSize=e.readUint16(),this.codecIntializationData=e.readUint8Array(this.codecIntializationDataSize))}),s.createBoxCtor("vttC",function(e){this.text=e.readString(this.size-this.hdr_size)}),s.createFullBoxCtor("vvcC",function(e){var t,r,l={held_bits:void 0,num_held_bits:0,stream_read_1_bytes:function(A){this.held_bits=A.readUint8(),this.num_held_bits=8},stream_read_2_bytes:function(A){this.held_bits=A.readUint16(),this.num_held_bits=16},extract_bits:function(A){var R=this.held_bits>>this.num_held_bits-A&(1<<A)-1;return this.num_held_bits-=A,R}};if(l.stream_read_1_bytes(e),l.extract_bits(5),this.lengthSizeMinusOne=l.extract_bits(2),this.ptl_present_flag=l.extract_bits(1),this.ptl_present_flag){l.stream_read_2_bytes(e),this.ols_idx=l.extract_bits(9),this.num_sublayers=l.extract_bits(3),this.constant_frame_rate=l.extract_bits(2),this.chroma_format_idc=l.extract_bits(2),l.stream_read_1_bytes(e),this.bit_depth_minus8=l.extract_bits(3),l.extract_bits(5);{if(l.stream_read_2_bytes(e),l.extract_bits(2),this.num_bytes_constraint_info=l.extract_bits(6),this.general_profile_idc=l.extract_bits(7),this.general_tier_flag=l.extract_bits(1),this.general_level_idc=e.readUint8(),l.stream_read_1_bytes(e),this.ptl_frame_only_constraint_flag=l.extract_bits(1),this.ptl_multilayer_enabled_flag=l.extract_bits(1),this.general_constraint_info=new Uint8Array(this.num_bytes_constraint_info),this.num_bytes_constraint_info){for(t=0;t<this.num_bytes_constraint_info-1;t++){var h=l.extract_bits(6);l.stream_read_1_bytes(e);var m=l.extract_bits(2);this.general_constraint_info[t]=h<<2|m}this.general_constraint_info[this.num_bytes_constraint_info-1]=l.extract_bits(6)}else l.extract_bits(6);if(this.num_sublayers>1){for(l.stream_read_1_bytes(e),this.ptl_sublayer_present_mask=0,r=this.num_sublayers-2;r>=0;--r){var y=l.extract_bits(1);this.ptl_sublayer_present_mask|=y<<r}for(r=this.num_sublayers;r<=8&&this.num_sublayers>1;++r)l.extract_bits(1);for(this.sublayer_level_idc=[],r=this.num_sublayers-2;r>=0;--r)this.ptl_sublayer_present_mask&1<<r&&(this.sublayer_level_idc[r]=e.readUint8())}if(this.ptl_num_sub_profiles=e.readUint8(),this.general_sub_profile_idc=[],this.ptl_num_sub_profiles)for(t=0;t<this.ptl_num_sub_profiles;t++)this.general_sub_profile_idc.push(e.readUint32())}this.max_picture_width=e.readUint16(),this.max_picture_height=e.readUint16(),this.avg_frame_rate=e.readUint16()}var b=12,x=13;this.nalu_arrays=[];var w=e.readUint8();for(t=0;t<w;t++){var T=[];this.nalu_arrays.push(T),l.stream_read_1_bytes(e),T.completeness=l.extract_bits(1),l.extract_bits(2),T.nalu_type=l.extract_bits(5);var C=1;for(T.nalu_type!=x&&T.nalu_type!=b&&(C=e.readUint16()),r=0;r<C;r++){var F=e.readUint16();T.push({data:e.readUint8Array(F),length:F})}}}),s.createFullBoxCtor("vvnC",function(e){var t=strm.readUint8();this.lengthSizeMinusOne=t&3}),s.SampleEntry.prototype.isVideo=function(){return!1},s.SampleEntry.prototype.isAudio=function(){return!1},s.SampleEntry.prototype.isSubtitle=function(){return!1},s.SampleEntry.prototype.isMetadata=function(){return!1},s.SampleEntry.prototype.isHint=function(){return!1},s.SampleEntry.prototype.getCodec=function(){return this.type.replace(".","")},s.SampleEntry.prototype.getWidth=function(){return""},s.SampleEntry.prototype.getHeight=function(){return""},s.SampleEntry.prototype.getChannelCount=function(){return""},s.SampleEntry.prototype.getSampleRate=function(){return""},s.SampleEntry.prototype.getSampleSize=function(){return""},s.VisualSampleEntry.prototype.isVideo=function(){return!0},s.VisualSampleEntry.prototype.getWidth=function(){return this.width},s.VisualSampleEntry.prototype.getHeight=function(){return this.height},s.AudioSampleEntry.prototype.isAudio=function(){return!0},s.AudioSampleEntry.prototype.getChannelCount=function(){return this.channel_count},s.AudioSampleEntry.prototype.getSampleRate=function(){return this.samplerate},s.AudioSampleEntry.prototype.getSampleSize=function(){return this.samplesize},s.SubtitleSampleEntry.prototype.isSubtitle=function(){return!0},s.MetadataSampleEntry.prototype.isMetadata=function(){return!0},s.decimalToHex=function(e,t){var r=Number(e).toString(16);for(t=typeof t>"u"||t===null?t=2:t;r.length<t;)r="0"+r;return r},s.avc1SampleEntry.prototype.getCodec=s.avc2SampleEntry.prototype.getCodec=s.avc3SampleEntry.prototype.getCodec=s.avc4SampleEntry.prototype.getCodec=function(){var e=s.SampleEntry.prototype.getCodec.call(this);return this.avcC?e+"."+s.decimalToHex(this.avcC.AVCProfileIndication)+s.decimalToHex(this.avcC.profile_compatibility)+s.decimalToHex(this.avcC.AVCLevelIndication):e},s.hev1SampleEntry.prototype.getCodec=s.hvc1SampleEntry.prototype.getCodec=function(){var e,t=s.SampleEntry.prototype.getCodec.call(this);if(this.hvcC){switch(t+=".",this.hvcC.general_profile_space){case 0:t+="";break;case 1:t+="A";break;case 2:t+="B";break;case 3:t+="C";break}t+=this.hvcC.general_profile_idc,t+=".";var r=this.hvcC.general_profile_compatibility,l=0;for(e=0;e<32&&(l|=r&1,e!=31);e++)l<<=1,r>>=1;t+=s.decimalToHex(l,0),t+=".",this.hvcC.general_tier_flag===0?t+="L":t+="H",t+=this.hvcC.general_level_idc;var h=!1,m="";for(e=5;e>=0;e--)(this.hvcC.general_constraint_indicator[e]||h)&&(m="."+s.decimalToHex(this.hvcC.general_constraint_indicator[e],0)+m,h=!0);t+=m}return t},s.vvc1SampleEntry.prototype.getCodec=s.vvi1SampleEntry.prototype.getCodec=function(){var e,t=s.SampleEntry.prototype.getCodec.call(this);if(this.vvcC){t+="."+this.vvcC.general_profile_idc,this.vvcC.general_tier_flag?t+=".H":t+=".L",t+=this.vvcC.general_level_idc;var r="";if(this.vvcC.general_constraint_info){var l=[],h=0;h|=this.vvcC.ptl_frame_only_constraint<<7,h|=this.vvcC.ptl_multilayer_enabled<<6;var m;for(e=0;e<this.vvcC.general_constraint_info.length;++e)h|=this.vvcC.general_constraint_info[e]>>2&63,l.push(h),h&&(m=e),h=this.vvcC.general_constraint_info[e]>>2&3;if(m===void 0)r=".CA";else{r=".C";var y="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",b=0,x=0;for(e=0;e<=m;++e)for(b=b<<8|l[e],x+=8;x>=5;){var w=b>>x-5&31;r+=y[w],x-=5,b&=(1<<x)-1}x&&(b<<=5-x,r+=y[b&31])}}t+=r}return t},s.mp4aSampleEntry.prototype.getCodec=function(){var e=s.SampleEntry.prototype.getCodec.call(this);if(this.esds&&this.esds.esd){var t=this.esds.esd.getOTI(),r=this.esds.esd.getAudioConfig();return e+"."+s.decimalToHex(t)+(r?"."+r:"")}else return e},s.stxtSampleEntry.prototype.getCodec=function(){var e=s.SampleEntry.prototype.getCodec.call(this);return this.mime_format?e+"."+this.mime_format:e},s.vp08SampleEntry.prototype.getCodec=s.vp09SampleEntry.prototype.getCodec=function(){var e=s.SampleEntry.prototype.getCodec.call(this),t=this.vpcC.level;t==0&&(t="00");var r=this.vpcC.bitDepth;return r==8&&(r="08"),e+".0"+this.vpcC.profile+"."+t+"."+r},s.av01SampleEntry.prototype.getCodec=function(){var e=s.SampleEntry.prototype.getCodec.call(this),t=this.av1C.seq_level_idx_0;t<10&&(t="0"+t);var r;return this.av1C.seq_profile===2&&this.av1C.high_bitdepth===1?r=this.av1C.twelve_bit===1?"12":"10":this.av1C.seq_profile<=2&&(r=this.av1C.high_bitdepth===1?"10":"08"),e+"."+this.av1C.seq_profile+"."+t+(this.av1C.seq_tier_0?"H":"M")+"."+r},s.Box.prototype.writeHeader=function(e,t){this.size+=8,this.size>f&&(this.size+=8),this.type==="uuid"&&(this.size+=16),n.debug("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+e.getPosition()+(t||"")),this.size>f?e.writeUint32(1):(this.sizePosition=e.getPosition(),e.writeUint32(this.size)),e.writeString(this.type,null,4),this.type==="uuid"&&e.writeUint8Array(this.uuid),this.size>f&&e.writeUint64(this.size)},s.FullBox.prototype.writeHeader=function(e){this.size+=4,s.Box.prototype.writeHeader.call(this,e," v="+this.version+" f="+this.flags),e.writeUint8(this.version),e.writeUint24(this.flags)},s.Box.prototype.write=function(e){this.type==="mdat"?this.data&&(this.size=this.data.length,this.writeHeader(e),e.writeUint8Array(this.data)):(this.size=this.data?this.data.length:0,this.writeHeader(e),this.data&&e.writeUint8Array(this.data))},s.ContainerBox.prototype.write=function(e){this.size=0,this.writeHeader(e);for(var t=0;t<this.boxes.length;t++)this.boxes[t]&&(this.boxes[t].write(e),this.size+=this.boxes[t].size);n.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),e.adjustUint32(this.sizePosition,this.size)},s.TrackReferenceTypeBox.prototype.write=function(e){this.size=this.track_ids.length*4,this.writeHeader(e),e.writeUint32Array(this.track_ids)},s.avcCBox.prototype.write=function(e){var t;for(this.size=7,t=0;t<this.SPS.length;t++)this.size+=2+this.SPS[t].length;for(t=0;t<this.PPS.length;t++)this.size+=2+this.PPS[t].length;for(this.ext&&(this.size+=this.ext.length),this.writeHeader(e),e.writeUint8(this.configurationVersion),e.writeUint8(this.AVCProfileIndication),e.writeUint8(this.profile_compatibility),e.writeUint8(this.AVCLevelIndication),e.writeUint8(this.lengthSizeMinusOne+252),e.writeUint8(this.SPS.length+224),t=0;t<this.SPS.length;t++)e.writeUint16(this.SPS[t].length),e.writeUint8Array(this.SPS[t].nalu);for(e.writeUint8(this.PPS.length),t=0;t<this.PPS.length;t++)e.writeUint16(this.PPS[t].length),e.writeUint8Array(this.PPS[t].nalu);this.ext&&e.writeUint8Array(this.ext)},s.co64Box.prototype.write=function(e){var t;for(this.version=0,this.flags=0,this.size=4+8*this.chunk_offsets.length,this.writeHeader(e),e.writeUint32(this.chunk_offsets.length),t=0;t<this.chunk_offsets.length;t++)e.writeUint64(this.chunk_offsets[t])},s.cslgBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4*5,this.writeHeader(e),e.writeInt32(this.compositionToDTSShift),e.writeInt32(this.leastDecodeToDisplayDelta),e.writeInt32(this.greatestDecodeToDisplayDelta),e.writeInt32(this.compositionStartTime),e.writeInt32(this.compositionEndTime)},s.cttsBox.prototype.write=function(e){var t;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(e),e.writeUint32(this.sample_counts.length),t=0;t<this.sample_counts.length;t++)e.writeUint32(this.sample_counts[t]),this.version===1?e.writeInt32(this.sample_offsets[t]):e.writeUint32(this.sample_offsets[t])},s.drefBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4,this.writeHeader(e),e.writeUint32(this.entries.length);for(var t=0;t<this.entries.length;t++)this.entries[t].write(e),this.size+=this.entries[t].size;n.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),e.adjustUint32(this.sizePosition,this.size)},s.elngBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=this.extended_language.length,this.writeHeader(e),e.writeString(this.extended_language)},s.elstBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4+12*this.entries.length,this.writeHeader(e),e.writeUint32(this.entries.length);for(var t=0;t<this.entries.length;t++){var r=this.entries[t];e.writeUint32(r.segment_duration),e.writeInt32(r.media_time),e.writeInt16(r.media_rate_integer),e.writeInt16(r.media_rate_fraction)}},s.emsgBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4*4+this.message_data.length+(this.scheme_id_uri.length+1)+(this.value.length+1),this.writeHeader(e),e.writeCString(this.scheme_id_uri),e.writeCString(this.value),e.writeUint32(this.timescale),e.writeUint32(this.presentation_time_delta),e.writeUint32(this.event_duration),e.writeUint32(this.id),e.writeUint8Array(this.message_data)},s.ftypBox.prototype.write=function(e){this.size=8+4*this.compatible_brands.length,this.writeHeader(e),e.writeString(this.major_brand,null,4),e.writeUint32(this.minor_version);for(var t=0;t<this.compatible_brands.length;t++)e.writeString(this.compatible_brands[t],null,4)},s.hdlrBox.prototype.write=function(e){this.size=5*4+this.name.length+1,this.version=0,this.flags=0,this.writeHeader(e),e.writeUint32(0),e.writeString(this.handler,null,4),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeCString(this.name)},s.hvcCBox.prototype.write=function(e){var t,r;for(this.size=23,t=0;t<this.nalu_arrays.length;t++)for(this.size+=3,r=0;r<this.nalu_arrays[t].length;r++)this.size+=2+this.nalu_arrays[t][r].data.length;for(this.writeHeader(e),e.writeUint8(this.configurationVersion),e.writeUint8((this.general_profile_space<<6)+(this.general_tier_flag<<5)+this.general_profile_idc),e.writeUint32(this.general_profile_compatibility),e.writeUint8Array(this.general_constraint_indicator),e.writeUint8(this.general_level_idc),e.writeUint16(this.min_spatial_segmentation_idc+(15<<24)),e.writeUint8(this.parallelismType+252),e.writeUint8(this.chroma_format_idc+252),e.writeUint8(this.bit_depth_luma_minus8+248),e.writeUint8(this.bit_depth_chroma_minus8+248),e.writeUint16(this.avgFrameRate),e.writeUint8((this.constantFrameRate<<6)+(this.numTemporalLayers<<3)+(this.temporalIdNested<<2)+this.lengthSizeMinusOne),e.writeUint8(this.nalu_arrays.length),t=0;t<this.nalu_arrays.length;t++)for(e.writeUint8((this.nalu_arrays[t].completeness<<7)+this.nalu_arrays[t].nalu_type),e.writeUint16(this.nalu_arrays[t].length),r=0;r<this.nalu_arrays[t].length;r++)e.writeUint16(this.nalu_arrays[t][r].data.length),e.writeUint8Array(this.nalu_arrays[t][r].data)},s.kindBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=this.schemeURI.length+1+(this.value.length+1),this.writeHeader(e),e.writeCString(this.schemeURI),e.writeCString(this.value)},s.mdhdBox.prototype.write=function(e){this.size=4*4+2*2,this.flags=0,this.version=0,this.writeHeader(e),e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.timescale),e.writeUint32(this.duration),e.writeUint16(this.language),e.writeUint16(0)},s.mehdBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4,this.writeHeader(e),e.writeUint32(this.fragment_duration)},s.mfhdBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4,this.writeHeader(e),e.writeUint32(this.sequence_number)},s.mvhdBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=23*4+2*2,this.writeHeader(e),e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.timescale),e.writeUint32(this.duration),e.writeUint32(this.rate),e.writeUint16(this.volume<<8),e.writeUint16(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32Array(this.matrix),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(this.next_track_id)},s.SampleEntry.prototype.writeHeader=function(e){this.size=8,s.Box.prototype.writeHeader.call(this,e),e.writeUint8(0),e.writeUint8(0),e.writeUint8(0),e.writeUint8(0),e.writeUint8(0),e.writeUint8(0),e.writeUint16(this.data_reference_index)},s.SampleEntry.prototype.writeFooter=function(e){for(var t=0;t<this.boxes.length;t++)this.boxes[t].write(e),this.size+=this.boxes[t].size;n.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),e.adjustUint32(this.sizePosition,this.size)},s.SampleEntry.prototype.write=function(e){this.writeHeader(e),e.writeUint8Array(this.data),this.size+=this.data.length,n.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),e.adjustUint32(this.sizePosition,this.size)},s.VisualSampleEntry.prototype.write=function(e){this.writeHeader(e),this.size+=2*7+6*4+32,e.writeUint16(0),e.writeUint16(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint16(this.width),e.writeUint16(this.height),e.writeUint32(this.horizresolution),e.writeUint32(this.vertresolution),e.writeUint32(0),e.writeUint16(this.frame_count),e.writeUint8(Math.min(31,this.compressorname.length)),e.writeString(this.compressorname,null,31),e.writeUint16(this.depth),e.writeInt16(-1),this.writeFooter(e)},s.AudioSampleEntry.prototype.write=function(e){this.writeHeader(e),this.size+=2*4+3*4,e.writeUint32(0),e.writeUint32(0),e.writeUint16(this.channel_count),e.writeUint16(this.samplesize),e.writeUint16(0),e.writeUint16(0),e.writeUint32(this.samplerate<<16),this.writeFooter(e)},s.stppSampleEntry.prototype.write=function(e){this.writeHeader(e),this.size+=this.namespace.length+1+this.schema_location.length+1+this.auxiliary_mime_types.length+1,e.writeCString(this.namespace),e.writeCString(this.schema_location),e.writeCString(this.auxiliary_mime_types),this.writeFooter(e)},s.SampleGroupEntry.prototype.write=function(e){e.writeUint8Array(this.data)},s.sbgpBox.prototype.write=function(e){this.version=1,this.flags=0,this.size=12+8*this.entries.length,this.writeHeader(e),e.writeString(this.grouping_type,null,4),e.writeUint32(this.grouping_type_parameter),e.writeUint32(this.entries.length);for(var t=0;t<this.entries.length;t++){var r=this.entries[t];e.writeInt32(r.sample_count),e.writeInt32(r.group_description_index)}},s.sgpdBox.prototype.write=function(e){var t,r;for(this.flags=0,this.size=12,t=0;t<this.entries.length;t++)r=this.entries[t],this.version===1&&(this.default_length===0&&(this.size+=4),this.size+=r.data.length);for(this.writeHeader(e),e.writeString(this.grouping_type,null,4),this.version===1&&e.writeUint32(this.default_length),this.version>=2&&e.writeUint32(this.default_sample_description_index),e.writeUint32(this.entries.length),t=0;t<this.entries.length;t++)r=this.entries[t],this.version===1&&this.default_length===0&&e.writeUint32(r.description_length),r.write(e)},s.sidxBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4*4+2+2+12*this.references.length,this.writeHeader(e),e.writeUint32(this.reference_ID),e.writeUint32(this.timescale),e.writeUint32(this.earliest_presentation_time),e.writeUint32(this.first_offset),e.writeUint16(0),e.writeUint16(this.references.length);for(var t=0;t<this.references.length;t++){var r=this.references[t];e.writeUint32(r.reference_type<<31|r.referenced_size),e.writeUint32(r.subsegment_duration),e.writeUint32(r.starts_with_SAP<<31|r.SAP_type<<28|r.SAP_delta_time)}},s.smhdBox.prototype.write=function(e){this.version=0,this.flags=1,this.size=4,this.writeHeader(e),e.writeUint16(this.balance),e.writeUint16(0)},s.stcoBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4+4*this.chunk_offsets.length,this.writeHeader(e),e.writeUint32(this.chunk_offsets.length),e.writeUint32Array(this.chunk_offsets)},s.stscBox.prototype.write=function(e){var t;for(this.version=0,this.flags=0,this.size=4+12*this.first_chunk.length,this.writeHeader(e),e.writeUint32(this.first_chunk.length),t=0;t<this.first_chunk.length;t++)e.writeUint32(this.first_chunk[t]),e.writeUint32(this.samples_per_chunk[t]),e.writeUint32(this.sample_description_index[t])},s.stsdBox.prototype.write=function(e){var t;for(this.version=0,this.flags=0,this.size=0,this.writeHeader(e),e.writeUint32(this.entries.length),this.size+=4,t=0;t<this.entries.length;t++)this.entries[t].write(e),this.size+=this.entries[t].size;n.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),e.adjustUint32(this.sizePosition,this.size)},s.stshBox.prototype.write=function(e){var t;for(this.version=0,this.flags=0,this.size=4+8*this.shadowed_sample_numbers.length,this.writeHeader(e),e.writeUint32(this.shadowed_sample_numbers.length),t=0;t<this.shadowed_sample_numbers.length;t++)e.writeUint32(this.shadowed_sample_numbers[t]),e.writeUint32(this.sync_sample_numbers[t])},s.stssBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4+4*this.sample_numbers.length,this.writeHeader(e),e.writeUint32(this.sample_numbers.length),e.writeUint32Array(this.sample_numbers)},s.stszBox.prototype.write=function(e){var t,r=!0;if(this.version=0,this.flags=0,this.sample_sizes.length>0)for(t=0;t+1<this.sample_sizes.length;)if(this.sample_sizes[t+1]!==this.sample_sizes[0]){r=!1;break}else t++;else r=!1;this.size=8,r||(this.size+=4*this.sample_sizes.length),this.writeHeader(e),r?e.writeUint32(this.sample_sizes[0]):e.writeUint32(0),e.writeUint32(this.sample_sizes.length),r||e.writeUint32Array(this.sample_sizes)},s.sttsBox.prototype.write=function(e){var t;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(e),e.writeUint32(this.sample_counts.length),t=0;t<this.sample_counts.length;t++)e.writeUint32(this.sample_counts[t]),e.writeUint32(this.sample_deltas[t])},s.tfdtBox.prototype.write=function(e){var t=Math.pow(2,32)-1;this.version=this.baseMediaDecodeTime>t?1:0,this.flags=0,this.size=4,this.version===1&&(this.size+=4),this.writeHeader(e),this.version===1?e.writeUint64(this.baseMediaDecodeTime):e.writeUint32(this.baseMediaDecodeTime)},s.tfhdBox.prototype.write=function(e){this.version=0,this.size=4,this.flags&s.TFHD_FLAG_BASE_DATA_OFFSET&&(this.size+=8),this.flags&s.TFHD_FLAG_SAMPLE_DESC&&(this.size+=4),this.flags&s.TFHD_FLAG_SAMPLE_DUR&&(this.size+=4),this.flags&s.TFHD_FLAG_SAMPLE_SIZE&&(this.size+=4),this.flags&s.TFHD_FLAG_SAMPLE_FLAGS&&(this.size+=4),this.writeHeader(e),e.writeUint32(this.track_id),this.flags&s.TFHD_FLAG_BASE_DATA_OFFSET&&e.writeUint64(this.base_data_offset),this.flags&s.TFHD_FLAG_SAMPLE_DESC&&e.writeUint32(this.default_sample_description_index),this.flags&s.TFHD_FLAG_SAMPLE_DUR&&e.writeUint32(this.default_sample_duration),this.flags&s.TFHD_FLAG_SAMPLE_SIZE&&e.writeUint32(this.default_sample_size),this.flags&s.TFHD_FLAG_SAMPLE_FLAGS&&e.writeUint32(this.default_sample_flags)},s.tkhdBox.prototype.write=function(e){this.version=0,this.size=4*18+2*4,this.writeHeader(e),e.writeUint32(this.creation_time),e.writeUint32(this.modification_time),e.writeUint32(this.track_id),e.writeUint32(0),e.writeUint32(this.duration),e.writeUint32(0),e.writeUint32(0),e.writeInt16(this.layer),e.writeInt16(this.alternate_group),e.writeInt16(this.volume<<8),e.writeUint16(0),e.writeInt32Array(this.matrix),e.writeUint32(this.width),e.writeUint32(this.height)},s.trexBox.prototype.write=function(e){this.version=0,this.flags=0,this.size=4*5,this.writeHeader(e),e.writeUint32(this.track_id),e.writeUint32(this.default_sample_description_index),e.writeUint32(this.default_sample_duration),e.writeUint32(this.default_sample_size),e.writeUint32(this.default_sample_flags)},s.trunBox.prototype.write=function(e){this.version=0,this.size=4,this.flags&s.TRUN_FLAGS_DATA_OFFSET&&(this.size+=4),this.flags&s.TRUN_FLAGS_FIRST_FLAG&&(this.size+=4),this.flags&s.TRUN_FLAGS_DURATION&&(this.size+=4*this.sample_duration.length),this.flags&s.TRUN_FLAGS_SIZE&&(this.size+=4*this.sample_size.length),this.flags&s.TRUN_FLAGS_FLAGS&&(this.size+=4*this.sample_flags.length),this.flags&s.TRUN_FLAGS_CTS_OFFSET&&(this.size+=4*this.sample_composition_time_offset.length),this.writeHeader(e),e.writeUint32(this.sample_count),this.flags&s.TRUN_FLAGS_DATA_OFFSET&&(this.data_offset_position=e.getPosition(),e.writeInt32(this.data_offset)),this.flags&s.TRUN_FLAGS_FIRST_FLAG&&e.writeUint32(this.first_sample_flags);for(var t=0;t<this.sample_count;t++)this.flags&s.TRUN_FLAGS_DURATION&&e.writeUint32(this.sample_duration[t]),this.flags&s.TRUN_FLAGS_SIZE&&e.writeUint32(this.sample_size[t]),this.flags&s.TRUN_FLAGS_FLAGS&&e.writeUint32(this.sample_flags[t]),this.flags&s.TRUN_FLAGS_CTS_OFFSET&&(this.version===0?e.writeUint32(this.sample_composition_time_offset[t]):e.writeInt32(this.sample_composition_time_offset[t]))},s["url Box"].prototype.write=function(e){this.version=0,this.location?(this.flags=0,this.size=this.location.length+1):(this.flags=1,this.size=0),this.writeHeader(e),this.location&&e.writeCString(this.location)},s["urn Box"].prototype.write=function(e){this.version=0,this.flags=0,this.size=this.name.length+1+(this.location?this.location.length+1:0),this.writeHeader(e),e.writeCString(this.name),this.location&&e.writeCString(this.location)},s.vmhdBox.prototype.write=function(e){this.version=0,this.flags=1,this.size=8,this.writeHeader(e),e.writeUint16(this.graphicsmode),e.writeUint16Array(this.opcolor)},s.cttsBox.prototype.unpack=function(e){var t,r,l;for(l=0,t=0;t<this.sample_counts.length;t++)for(r=0;r<this.sample_counts[t];r++)e[l].pts=e[l].dts+this.sample_offsets[t],l++},s.sttsBox.prototype.unpack=function(e){var t,r,l;for(l=0,t=0;t<this.sample_counts.length;t++)for(r=0;r<this.sample_counts[t];r++)l===0?e[l].dts=0:e[l].dts=e[l-1].dts+this.sample_deltas[t],l++},s.stcoBox.prototype.unpack=function(e){var t;for(t=0;t<this.chunk_offsets.length;t++)e[t].offset=this.chunk_offsets[t]},s.stscBox.prototype.unpack=function(e){var t,r,l,h,m;for(h=0,m=0,t=0;t<this.first_chunk.length;t++)for(r=0;r<(t+1<this.first_chunk.length?this.first_chunk[t+1]:1/0);r++)for(m++,l=0;l<this.samples_per_chunk[t];l++){if(e[h])e[h].description_index=this.sample_description_index[t],e[h].chunk_index=m;else return;h++}},s.stszBox.prototype.unpack=function(e){var t;for(t=0;t<this.sample_sizes.length;t++)e[t].size=this.sample_sizes[t]},s.DIFF_BOXES_PROP_NAMES=["boxes","entries","references","subsamples","items","item_infos","extents","associations","subsegments","ranges","seekLists","seekPoints","esd","levels"],s.DIFF_PRIMITIVE_ARRAY_PROP_NAMES=["compatible_brands","matrix","opcolor","sample_counts","sample_counts","sample_deltas","first_chunk","samples_per_chunk","sample_sizes","chunk_offsets","sample_offsets","sample_description_index","sample_duration"],s.boxEqualFields=function(e,t){if(e&&!t)return!1;var r;for(r in e)if(!(s.DIFF_BOXES_PROP_NAMES.indexOf(r)>-1)){if(e[r]instanceof s.Box||t[r]instanceof s.Box)continue;if(typeof e[r]>"u"||typeof t[r]>"u")continue;if(typeof e[r]=="function"||typeof t[r]=="function")continue;if(e.subBoxNames&&e.subBoxNames.indexOf(r.slice(0,4))>-1||t.subBoxNames&&t.subBoxNames.indexOf(r.slice(0,4))>-1)continue;if(r==="data"||r==="start"||r==="size"||r==="creation_time"||r==="modification_time")continue;if(s.DIFF_PRIMITIVE_ARRAY_PROP_NAMES.indexOf(r)>-1)continue;if(e[r]!==t[r])return!1}return!0},s.boxEqual=function(e,t){if(!s.boxEqualFields(e,t))return!1;for(var r=0;r<s.DIFF_BOXES_PROP_NAMES.length;r++){var l=s.DIFF_BOXES_PROP_NAMES[r];if(e[l]&&t[l]&&!s.boxEqual(e[l],t[l]))return!1}return!0};var g=function(){};g.prototype.parseSample=function(e){var t,r,l=new o(e.buffer);for(t=[];!l.isEos();)r=s.parseOneBox(l,!1),r.code===s.OK&&r.box.type==="vttc"&&t.push(r.box);return t},g.prototype.getText=function(e,t,r){function l(w,T,C){return C=C||"0",w=w+"",w.length>=T?w:new Array(T-w.length+1).join(C)+w}function h(w){var T=Math.floor(w/3600),C=Math.floor((w-T*3600)/60),F=Math.floor(w-T*3600-C*60),A=Math.floor((w-T*3600-C*60-F)*1e3);return""+l(T,2)+":"+l(C,2)+":"+l(F,2)+"."+l(A,3)}for(var m=this.parseSample(r),y="",b=0;b<m.length;b++){var x=m[b];y+=h(e)+" --> "+h(t)+`\\r\n`,y+=x.payl.text}return y};var v=function(){};v.prototype.parseSample=function(e){var t={},r;t.resources=[];var l=new o(e.data.buffer);if(!e.subsamples||e.subsamples.length===0)t.documentString=l.readString(e.data.length);else if(t.documentString=l.readString(e.subsamples[0].size),e.subsamples.length>1)for(r=1;r<e.subsamples.length;r++)t.resources[r]=l.readUint8Array(e.subsamples[r].size);return typeof DOMParser<"u"&&(t.document=new DOMParser().parseFromString(t.documentString,"application/xml")),t};var U=function(){};U.prototype.parseSample=function(e){var t,r=new o(e.data.buffer);return t=r.readString(e.data.length),t},U.prototype.parseConfig=function(e){var t,r=new o(e.buffer);return r.readUint32(),t=r.readCString(),t},a.VTTin4Parser=g,a.XMLSubtitlein4Parser=v,a.Textin4Parser=U;var S=function(e){this.stream=e||new c,this.boxes=[],this.mdats=[],this.moofs=[],this.isProgressive=!1,this.moovStartFound=!1,this.onMoovStart=null,this.moovStartSent=!1,this.onReady=null,this.readySent=!1,this.onSegment=null,this.onSamples=null,this.onError=null,this.sampleListBuilt=!1,this.fragmentedTracks=[],this.extractedTracks=[],this.isFragmentationInitialized=!1,this.sampleProcessingStarted=!1,this.nextMoofNumber=0,this.itemListBuilt=!1,this.items=[],this.entity_groups=[],this.onSidx=null,this.sidxSent=!1};S.prototype.setSegmentOptions=function(e,t,r){var l=this.getTrackById(e);if(l){var h={};this.fragmentedTracks.push(h),h.id=e,h.user=t,h.trak=l,l.nextSample=0,h.segmentStream=null,h.nb_samples=1e3,h.rapAlignement=!0,r&&(r.nbSamples&&(h.nb_samples=r.nbSamples),r.rapAlignement&&(h.rapAlignement=r.rapAlignement))}},S.prototype.unsetSegmentOptions=function(e){for(var t=-1,r=0;r<this.fragmentedTracks.length;r++){var l=this.fragmentedTracks[r];l.id==e&&(t=r)}t>-1&&this.fragmentedTracks.splice(t,1)},S.prototype.setExtractionOptions=function(e,t,r){var l=this.getTrackById(e);if(l){var h={};this.extractedTracks.push(h),h.id=e,h.user=t,h.trak=l,l.nextSample=0,h.nb_samples=1e3,h.samples=[],r&&r.nbSamples&&(h.nb_samples=r.nbSamples)}},S.prototype.unsetExtractionOptions=function(e){for(var t=-1,r=0;r<this.extractedTracks.length;r++){var l=this.extractedTracks[r];l.id==e&&(t=r)}t>-1&&this.extractedTracks.splice(t,1)},S.prototype.parse=function(){var e,t,r=!1;if(!(this.restoreParsePosition&&!this.restoreParsePosition()))for(;;)if(this.hasIncompleteMdat&&this.hasIncompleteMdat()){if(this.processIncompleteMdat())continue;return}else if(this.saveParsePosition&&this.saveParsePosition(),e=s.parseOneBox(this.stream,r),e.code===s.ERR_NOT_ENOUGH_DATA)if(this.processIncompleteBox){if(this.processIncompleteBox(e))continue;return}else return;else{var l;switch(t=e.box,l=t.type!=="uuid"?t.type:t.uuid,this.boxes.push(t),l){case"mdat":this.mdats.push(t);break;case"moof":this.moofs.push(t);break;case"moov":this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0);default:this[l]!==void 0&&n.warn("ISOFile","Duplicate Box of type: "+l+", overriding previous occurrence"),this[l]=t;break}this.updateUsedBytes&&this.updateUsedBytes(t,e)}},S.prototype.checkBuffer=function(e){if(e==null)throw"Buffer must be defined and non empty";if(e.fileStart===void 0)throw"Buffer must have a fileStart property";return e.byteLength===0?(n.warn("ISOFile","Ignoring empty buffer (fileStart: "+e.fileStart+")"),this.stream.logBufferLevel(),!1):(n.info("ISOFile","Processing buffer (fileStart: "+e.fileStart+")"),e.usedBytes=0,this.stream.insertBuffer(e),this.stream.logBufferLevel(),this.stream.initialized()?!0:(n.warn("ISOFile","Not ready to start parsing"),!1))},S.prototype.appendBuffer=function(e,t){var r;if(this.checkBuffer(e))return this.parse(),this.moovStartFound&&!this.moovStartSent&&(this.moovStartSent=!0,this.onMoovStart&&this.onMoovStart()),this.moov?(this.sampleListBuilt||(this.buildSampleLists(),this.sampleListBuilt=!0),this.updateSampleLists(),this.onReady&&!this.readySent&&(this.readySent=!0,this.onReady(this.getInfo())),this.processSamples(t),this.nextSeekPosition?(r=this.nextSeekPosition,this.nextSeekPosition=void 0):r=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(r=this.stream.getEndFilePositionAfter(r))):this.nextParsePosition?r=this.nextParsePosition:r=0,this.sidx&&this.onSidx&&!this.sidxSent&&(this.onSidx(this.sidx),this.sidxSent=!0),this.meta&&(this.flattenItemInfo&&!this.itemListBuilt&&(this.flattenItemInfo(),this.itemListBuilt=!0),this.processItems&&this.processItems(this.onItem)),this.stream.cleanBuffers&&(n.info("ISOFile","Done processing buffer (fileStart: "+e.fileStart+") - next buffer to fetch should have a fileStart position of "+r),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),n.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize())),r},S.prototype.getInfo=function(){var e,t,r={},l,h,m,y,b=new Date("1904-01-01T00:00:00Z").getTime();if(this.moov)for(r.hasMoov=!0,r.duration=this.moov.mvhd.duration,r.timescale=this.moov.mvhd.timescale,r.isFragmented=this.moov.mvex!=null,r.isFragmented&&this.moov.mvex.mehd&&(r.fragment_duration=this.moov.mvex.mehd.fragment_duration),r.isProgressive=this.isProgressive,r.hasIOD=this.moov.iods!=null,r.brands=[],r.brands.push(this.ftyp.major_brand),r.brands=r.brands.concat(this.ftyp.compatible_brands),r.created=new Date(b+this.moov.mvhd.creation_time*1e3),r.modified=new Date(b+this.moov.mvhd.modification_time*1e3),r.tracks=[],r.audioTracks=[],r.videoTracks=[],r.subtitleTracks=[],r.metadataTracks=[],r.hintTracks=[],r.otherTracks=[],e=0;e<this.moov.traks.length;e++){if(l=this.moov.traks[e],y=l.mdia.minf.stbl.stsd.entries[0],h={},r.tracks.push(h),h.id=l.tkhd.track_id,h.name=l.mdia.hdlr.name,h.references=[],l.tref)for(t=0;t<l.tref.boxes.length;t++)m={},h.references.push(m),m.type=l.tref.boxes[t].type,m.track_ids=l.tref.boxes[t].track_ids;l.edts&&(h.edits=l.edts.elst.entries),h.created=new Date(b+l.tkhd.creation_time*1e3),h.modified=new Date(b+l.tkhd.modification_time*1e3),h.movie_duration=l.tkhd.duration,h.movie_timescale=r.timescale,h.layer=l.tkhd.layer,h.alternate_group=l.tkhd.alternate_group,h.volume=l.tkhd.volume,h.matrix=l.tkhd.matrix,h.track_width=l.tkhd.width/65536,h.track_height=l.tkhd.height/65536,h.timescale=l.mdia.mdhd.timescale,h.cts_shift=l.mdia.minf.stbl.cslg,h.duration=l.mdia.mdhd.duration,h.samples_duration=l.samples_duration,h.codec=y.getCodec(),h.kind=l.udta&&l.udta.kinds.length?l.udta.kinds[0]:{schemeURI:"",value:""},h.language=l.mdia.elng?l.mdia.elng.extended_language:l.mdia.mdhd.languageString,h.nb_samples=l.samples.length,h.size=l.samples_size,h.bitrate=h.size*8*h.timescale/h.samples_duration,y.isAudio()?(h.type="audio",r.audioTracks.push(h),h.audio={},h.audio.sample_rate=y.getSampleRate(),h.audio.channel_count=y.getChannelCount(),h.audio.sample_size=y.getSampleSize()):y.isVideo()?(h.type="video",r.videoTracks.push(h),h.video={},h.video.width=y.getWidth(),h.video.height=y.getHeight()):y.isSubtitle()?(h.type="subtitles",r.subtitleTracks.push(h)):y.isHint()?(h.type="metadata",r.hintTracks.push(h)):y.isMetadata()?(h.type="metadata",r.metadataTracks.push(h)):(h.type="metadata",r.otherTracks.push(h))}else r.hasMoov=!1;if(r.mime="",r.hasMoov&&r.tracks){for(r.videoTracks&&r.videoTracks.length>0?r.mime+=\'video/mp4; codecs="\':r.audioTracks&&r.audioTracks.length>0?r.mime+=\'audio/mp4; codecs="\':r.mime+=\'application/mp4; codecs="\',e=0;e<r.tracks.length;e++)e!==0&&(r.mime+=","),r.mime+=r.tracks[e].codec;r.mime+=\'"; profiles="\',r.mime+=this.ftyp.compatible_brands.join(),r.mime+=\'"\'}return r},S.prototype.setNextSeekPositionFromSample=function(e){e&&(this.nextSeekPosition?this.nextSeekPosition=Math.min(e.offset+e.alreadyRead,this.nextSeekPosition):this.nextSeekPosition=e.offset+e.alreadyRead)},S.prototype.processSamples=function(e){var t,r;if(this.sampleProcessingStarted){if(this.isFragmentationInitialized&&this.onSegment!==null)for(t=0;t<this.fragmentedTracks.length;t++){var l=this.fragmentedTracks[t];for(r=l.trak;r.nextSample<r.samples.length&&this.sampleProcessingStarted;){n.debug("ISOFile","Creating media fragment on track #"+l.id+" for sample "+r.nextSample);var h=this.createFragment(l.id,r.nextSample,l.segmentStream);if(h)l.segmentStream=h,r.nextSample++;else break;if((r.nextSample%l.nb_samples===0||e||r.nextSample>=r.samples.length)&&(n.info("ISOFile","Sending fragmented data on track #"+l.id+" for samples ["+Math.max(0,r.nextSample-l.nb_samples)+","+(r.nextSample-1)+"]"),n.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(l.id,l.user,l.segmentStream.buffer,r.nextSample,e||r.nextSample>=r.samples.length),l.segmentStream=null,l!==this.fragmentedTracks[t]))break}}if(this.onSamples!==null)for(t=0;t<this.extractedTracks.length;t++){var m=this.extractedTracks[t];for(r=m.trak;r.nextSample<r.samples.length&&this.sampleProcessingStarted;){n.debug("ISOFile","Exporting on track #"+m.id+" sample #"+r.nextSample);var y=this.getSample(r,r.nextSample);if(y)r.nextSample++,m.samples.push(y);else{this.setNextSeekPositionFromSample(r.samples[r.nextSample]);break}if((r.nextSample%m.nb_samples===0||r.nextSample>=r.samples.length)&&(n.debug("ISOFile","Sending samples on track #"+m.id+" for sample "+r.nextSample),this.onSamples&&this.onSamples(m.id,m.user,m.samples),m.samples=[],m!==this.extractedTracks[t]))break}}}},S.prototype.getBox=function(e){var t=this.getBoxes(e,!0);return t.length?t[0]:null},S.prototype.getBoxes=function(e,t){var r=[];return S._sweep.call(this,e,r,t),r},S._sweep=function(e,t,r){this.type&&this.type==e&&t.push(this);for(var l in this.boxes){if(t.length&&r)return;S._sweep.call(this.boxes[l],e,t,r)}},S.prototype.getTrackSamplesInfo=function(e){var t=this.getTrackById(e);if(t)return t.samples},S.prototype.getTrackSample=function(e,t){var r=this.getTrackById(e),l=this.getSample(r,t);return l},S.prototype.releaseUsedSamples=function(e,t){var r=0,l=this.getTrackById(e);l.lastValidSample||(l.lastValidSample=0);for(var h=l.lastValidSample;h<t;h++)r+=this.releaseSample(l,h);n.info("ISOFile","Track #"+e+" released samples up to "+t+" (released size: "+r+", remaining: "+this.samplesDataSize+")"),l.lastValidSample=t},S.prototype.start=function(){this.sampleProcessingStarted=!0,this.processSamples(!1)},S.prototype.stop=function(){this.sampleProcessingStarted=!1},S.prototype.flush=function(){n.info("ISOFile","Flushing remaining samples"),this.updateSampleLists(),this.processSamples(!0),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0)},S.prototype.seekTrack=function(e,t,r){var l,h,m=1/0,y=0,b=0,x;if(r.samples.length===0)return n.info("ISOFile","No sample in track, cannot seek! Using time "+n.getDurationString(0,1)+" and offset: 0"),{offset:0,time:0};for(l=0;l<r.samples.length;l++){if(h=r.samples[l],l===0)b=0,x=h.timescale;else if(h.cts>e*h.timescale){b=l-1;break}t&&h.is_sync&&(y=l)}for(t&&(b=y),e=r.samples[b].cts,r.nextSample=b;r.samples[b].alreadyRead===r.samples[b].size&&r.samples[b+1];)b++;return m=r.samples[b].offset+r.samples[b].alreadyRead,n.info("ISOFile","Seeking to "+(t?"RAP":"")+" sample #"+r.nextSample+" on track "+r.tkhd.track_id+", time "+n.getDurationString(e,x)+" and offset: "+m),{offset:m,time:e/x}},S.prototype.getTrackDuration=function(e){var t;return e.samples?(t=e.samples[e.samples.length-1],(t.cts+t.duration)/t.timescale):1/0},S.prototype.seek=function(e,t){var r=this.moov,l,h,m,y={offset:1/0,time:1/0};if(this.moov){for(m=0;m<r.traks.length;m++)l=r.traks[m],!(e>this.getTrackDuration(l))&&(h=this.seekTrack(e,t,l),h.offset<y.offset&&(y.offset=h.offset),h.time<y.time&&(y.time=h.time));return n.info("ISOFile","Seeking at time "+n.getDurationString(y.time,1)+" needs a buffer with a fileStart position of "+y.offset),y.offset===1/0?y={offset:this.nextParsePosition,time:0}:y.offset=this.stream.getEndFilePositionAfter(y.offset),n.info("ISOFile","Adjusted seek position (after checking data already in buffer): "+y.offset),y}else throw"Cannot seek: moov not received!"},S.prototype.equal=function(e){for(var t=0;t<this.boxes.length&&t<e.boxes.length;){var r=this.boxes[t],l=e.boxes[t];if(!s.boxEqual(r,l))return!1;t++}return!0},a.ISOFile=S,S.prototype.lastBoxStartPosition=0,S.prototype.parsingMdat=null,S.prototype.nextParsePosition=0,S.prototype.discardMdatData=!1,S.prototype.processIncompleteBox=function(e){var t,r,l;return e.type==="mdat"?(t=new s[e.type+"Box"](e.size),this.parsingMdat=t,this.boxes.push(t),this.mdats.push(t),t.start=e.start,t.hdr_size=e.hdr_size,this.stream.addUsedBytes(t.hdr_size),this.lastBoxStartPosition=t.start+t.size,l=this.stream.seek(t.start+t.size,!1,this.discardMdatData),l?(this.parsingMdat=null,!0):(this.moovStartFound?this.nextParsePosition=this.stream.findEndContiguousBuf():this.nextParsePosition=t.start+t.size,!1)):(e.type==="moov"&&(this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0)),r=this.stream.mergeNextBuffer?this.stream.mergeNextBuffer():!1,r?(this.nextParsePosition=this.stream.getEndPosition(),!0):(e.type?this.moovStartFound?this.nextParsePosition=this.stream.getEndPosition():this.nextParsePosition=this.stream.getPosition()+e.size:this.nextParsePosition=this.stream.getEndPosition(),!1))},S.prototype.hasIncompleteMdat=function(){return this.parsingMdat!==null},S.prototype.processIncompleteMdat=function(){var e,t;return e=this.parsingMdat,t=this.stream.seek(e.start+e.size,!1,this.discardMdatData),t?(n.debug("ISOFile","Found \'mdat\' end in buffered data"),this.parsingMdat=null,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)},S.prototype.restoreParsePosition=function(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)},S.prototype.saveParsePosition=function(){this.lastBoxStartPosition=this.stream.getPosition()},S.prototype.updateUsedBytes=function(e,t){this.stream.addUsedBytes&&(e.type==="mdat"?(this.stream.addUsedBytes(e.hdr_size),this.discardMdatData&&this.stream.addUsedBytes(e.size-e.hdr_size)):this.stream.addUsedBytes(e.size))},S.prototype.add=s.Box.prototype.add,S.prototype.addBox=s.Box.prototype.addBox,S.prototype.init=function(e){var t=e||{};this.add("ftyp").set("major_brand",t.brands&&t.brands[0]||"iso4").set("minor_version",0).set("compatible_brands",t.brands||["iso4"]);var r=this.add("moov");return r.add("mvhd").set("timescale",t.timescale||600).set("rate",t.rate||65536).set("creation_time",0).set("modification_time",0).set("duration",t.duration||0).set("volume",t.width?0:256).set("matrix",[65536,0,0,0,65536,0,0,0,1073741824]).set("next_track_id",1),r.add("mvex"),this},S.prototype.addTrack=function(e){this.moov||this.init(e);var t=e||{};t.width=t.width||320,t.height=t.height||320,t.id=t.id||this.moov.mvhd.next_track_id,t.type=t.type||"avc1";var r=this.moov.add("trak");this.moov.mvhd.next_track_id=t.id+1,r.add("tkhd").set("flags",s.TKHD_FLAG_ENABLED|s.TKHD_FLAG_IN_MOVIE|s.TKHD_FLAG_IN_PREVIEW).set("creation_time",0).set("modification_time",0).set("track_id",t.id).set("duration",t.duration||0).set("layer",t.layer||0).set("alternate_group",0).set("volume",1).set("matrix",[0,0,0,0,0,0,0,0,0]).set("width",t.width<<16).set("height",t.height<<16);var l=r.add("mdia");l.add("mdhd").set("creation_time",0).set("modification_time",0).set("timescale",t.timescale||1).set("duration",t.media_duration||0).set("language",t.language||"und"),l.add("hdlr").set("handler",t.hdlr||"vide").set("name",t.name||"Track created with MP4Box.js"),l.add("elng").set("extended_language",t.language||"fr-FR");var h=l.add("minf");if(s[t.type+"SampleEntry"]!==void 0){var m=new s[t.type+"SampleEntry"];m.data_reference_index=1;var y="";for(var b in s.sampleEntryCodes)for(var x=s.sampleEntryCodes[b],w=0;w<x.length;w++)if(x.indexOf(t.type)>-1){y=b;break}switch(y){case"Visual":if(h.add("vmhd").set("graphicsmode",0).set("opcolor",[0,0,0]),m.set("width",t.width).set("height",t.height).set("horizresolution",72<<16).set("vertresolution",72<<16).set("frame_count",1).set("compressorname",t.type+" Compressor").set("depth",24),t.avcDecoderConfigRecord){var T=new s.avcCBox;T.parse(new o(t.avcDecoderConfigRecord)),m.addBox(T)}else if(t.hevcDecoderConfigRecord){var C=new s.hvcCBox;C.parse(new o(t.hevcDecoderConfigRecord)),m.addBox(C)}break;case"Audio":h.add("smhd").set("balance",t.balance||0),m.set("channel_count",t.channel_count||2).set("samplesize",t.samplesize||16).set("samplerate",t.samplerate||65536);break;case"Hint":h.add("hmhd");break;case"Subtitle":switch(h.add("sthd"),t.type){case"stpp":m.set("namespace",t.namespace||"nonamespace").set("schema_location",t.schema_location||"").set("auxiliary_mime_types",t.auxiliary_mime_types||"");break}break;case"Metadata":h.add("nmhd");break;case"System":h.add("nmhd");break;default:h.add("nmhd");break}t.description&&m.addBox(t.description),t.description_boxes&&t.description_boxes.forEach(function(A){m.addBox(A)}),h.add("dinf").add("dref").addEntry(new s["url Box"]().set("flags",1));var F=h.add("stbl");return F.add("stsd").addEntry(m),F.add("stts").set("sample_counts",[]).set("sample_deltas",[]),F.add("stsc").set("first_chunk",[]).set("samples_per_chunk",[]).set("sample_description_index",[]),F.add("stco").set("chunk_offsets",[]),F.add("stsz").set("sample_sizes",[]),this.moov.mvex.add("trex").set("track_id",t.id).set("default_sample_description_index",t.default_sample_description_index||1).set("default_sample_duration",t.default_sample_duration||0).set("default_sample_size",t.default_sample_size||0).set("default_sample_flags",t.default_sample_flags||0),this.buildTrakSampleLists(r),t.id}},s.Box.prototype.computeSize=function(e){var t=e||new d;t.endianness=d.BIG_ENDIAN,this.write(t)},S.prototype.addSample=function(e,t,r){var l=r||{},h={},m=this.getTrackById(e);if(m!==null){h.number=m.samples.length,h.track_id=m.tkhd.track_id,h.timescale=m.mdia.mdhd.timescale,h.description_index=l.sample_description_index?l.sample_description_index-1:0,h.description=m.mdia.minf.stbl.stsd.entries[h.description_index],h.data=t,h.size=t.byteLength,h.alreadyRead=h.size,h.duration=l.duration||1,h.cts=l.cts||0,h.dts=l.dts||0,h.is_sync=l.is_sync||!1,h.is_leading=l.is_leading||0,h.depends_on=l.depends_on||0,h.is_depended_on=l.is_depended_on||0,h.has_redundancy=l.has_redundancy||0,h.degradation_priority=l.degradation_priority||0,h.offset=0,h.subsamples=l.subsamples,m.samples.push(h),m.samples_size+=h.size,m.samples_duration+=h.duration,m.first_dts===void 0&&(m.first_dts=l.dts),this.processSamples();var y=this.createSingleSampleMoof(h);return this.addBox(y),y.computeSize(),y.trafs[0].truns[0].data_offset=y.size+8,this.add("mdat").data=new Uint8Array(t),h}},S.prototype.createSingleSampleMoof=function(e){var t=0;e.is_sync?t=1<<25:t=65536;var r=new s.moofBox;r.add("mfhd").set("sequence_number",this.nextMoofNumber),this.nextMoofNumber++;var l=r.add("traf"),h=this.getTrackById(e.track_id);return l.add("tfhd").set("track_id",e.track_id).set("flags",s.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),l.add("tfdt").set("baseMediaDecodeTime",e.dts-(h.first_dts||0)),l.add("trun").set("flags",s.TRUN_FLAGS_DATA_OFFSET|s.TRUN_FLAGS_DURATION|s.TRUN_FLAGS_SIZE|s.TRUN_FLAGS_FLAGS|s.TRUN_FLAGS_CTS_OFFSET).set("data_offset",0).set("first_sample_flags",0).set("sample_count",1).set("sample_duration",[e.duration]).set("sample_size",[e.size]).set("sample_flags",[t]).set("sample_composition_time_offset",[e.cts-e.dts]),r},S.prototype.lastMoofIndex=0,S.prototype.samplesDataSize=0,S.prototype.resetTables=function(){var e,t,r,l,h,m,y,b;for(this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=0,e=0;e<this.moov.traks.length;e++){t=this.moov.traks[e],t.tkhd.duration=0,t.mdia.mdhd.duration=0,r=t.mdia.minf.stbl.stco||t.mdia.minf.stbl.co64,r.chunk_offsets=[],l=t.mdia.minf.stbl.stsc,l.first_chunk=[],l.samples_per_chunk=[],l.sample_description_index=[],h=t.mdia.minf.stbl.stsz||t.mdia.minf.stbl.stz2,h.sample_sizes=[],m=t.mdia.minf.stbl.stts,m.sample_counts=[],m.sample_deltas=[],y=t.mdia.minf.stbl.ctts,y&&(y.sample_counts=[],y.sample_offsets=[]),b=t.mdia.minf.stbl.stss;var x=t.mdia.minf.stbl.boxes.indexOf(b);x!=-1&&(t.mdia.minf.stbl.boxes[x]=null)}},S.initSampleGroups=function(e,t,r,l,h){var m,y,b,x;function w(T,C,F){this.grouping_type=T,this.grouping_type_parameter=C,this.sbgp=F,this.last_sample_in_run=-1,this.entry_index=-1}for(t&&(t.sample_groups_info=[]),e.sample_groups_info||(e.sample_groups_info=[]),y=0;y<r.length;y++){for(x=r[y].grouping_type+"/"+r[y].grouping_type_parameter,b=new w(r[y].grouping_type,r[y].grouping_type_parameter,r[y]),t&&(t.sample_groups_info[x]=b),e.sample_groups_info[x]||(e.sample_groups_info[x]=b),m=0;m<l.length;m++)l[m].grouping_type===r[y].grouping_type&&(b.description=l[m],b.description.used=!0);if(h)for(m=0;m<h.length;m++)h[m].grouping_type===r[y].grouping_type&&(b.fragment_description=h[m],b.fragment_description.used=!0,b.is_fragment=!0)}if(t){if(h)for(y=0;y<h.length;y++)!h[y].used&&h[y].version>=2&&(x=h[y].grouping_type+"/0",b=new w(h[y].grouping_type,0),b.is_fragment=!0,t.sample_groups_info[x]||(t.sample_groups_info[x]=b))}else for(y=0;y<l.length;y++)!l[y].used&&l[y].version>=2&&(x=l[y].grouping_type+"/0",b=new w(l[y].grouping_type,0),e.sample_groups_info[x]||(e.sample_groups_info[x]=b))},S.setSampleGroupProperties=function(e,t,r,l){var h,m;t.sample_groups=[];for(h in l)if(t.sample_groups[h]={},t.sample_groups[h].grouping_type=l[h].grouping_type,t.sample_groups[h].grouping_type_parameter=l[h].grouping_type_parameter,r>=l[h].last_sample_in_run&&(l[h].last_sample_in_run<0&&(l[h].last_sample_in_run=0),l[h].entry_index++,l[h].entry_index<=l[h].sbgp.entries.length-1&&(l[h].last_sample_in_run+=l[h].sbgp.entries[l[h].entry_index].sample_count)),l[h].entry_index<=l[h].sbgp.entries.length-1?t.sample_groups[h].group_description_index=l[h].sbgp.entries[l[h].entry_index].group_description_index:t.sample_groups[h].group_description_index=-1,t.sample_groups[h].group_description_index!==0){var y;l[h].fragment_description?y=l[h].fragment_description:y=l[h].description,t.sample_groups[h].group_description_index>0?(t.sample_groups[h].group_description_index>65535?m=(t.sample_groups[h].group_description_index>>16)-1:m=t.sample_groups[h].group_description_index-1,y&&m>=0&&(t.sample_groups[h].description=y.entries[m])):y&&y.version>=2&&y.default_group_description_index>0&&(t.sample_groups[h].description=y.entries[y.default_group_description_index-1])}},S.process_sdtp=function(e,t,r){t&&(e?(t.is_leading=e.is_leading[r],t.depends_on=e.sample_depends_on[r],t.is_depended_on=e.sample_is_depended_on[r],t.has_redundancy=e.sample_has_redundancy[r]):(t.is_leading=0,t.depends_on=0,t.is_depended_on=0,t.has_redundancy=0))},S.prototype.buildSampleLists=function(){var e,t;for(e=0;e<this.moov.traks.length;e++)t=this.moov.traks[e],this.buildTrakSampleLists(t)},S.prototype.buildTrakSampleLists=function(e){var t,r,l,h,m,y,b,x,w,T,C,F,A,R,P,K,Z,V,N,q,ee,xe,j,W;if(e.samples=[],e.samples_duration=0,e.samples_size=0,r=e.mdia.minf.stbl.stco||e.mdia.minf.stbl.co64,l=e.mdia.minf.stbl.stsc,h=e.mdia.minf.stbl.stsz||e.mdia.minf.stbl.stz2,m=e.mdia.minf.stbl.stts,y=e.mdia.minf.stbl.ctts,b=e.mdia.minf.stbl.stss,x=e.mdia.minf.stbl.stsd,w=e.mdia.minf.stbl.subs,F=e.mdia.minf.stbl.stdp,T=e.mdia.minf.stbl.sbgps,C=e.mdia.minf.stbl.sgpds,V=-1,N=-1,q=-1,ee=-1,xe=0,j=0,W=0,S.initSampleGroups(e,null,T,C),!(typeof h>"u")){for(t=0;t<h.sample_sizes.length;t++){var L={};L.number=t,L.track_id=e.tkhd.track_id,L.timescale=e.mdia.mdhd.timescale,L.alreadyRead=0,e.samples[t]=L,L.size=h.sample_sizes[t],e.samples_size+=L.size,t===0?(R=1,A=0,L.chunk_index=R,L.chunk_run_index=A,Z=l.samples_per_chunk[A],K=0,A+1<l.first_chunk.length?P=l.first_chunk[A+1]-1:P=1/0):t<Z?(L.chunk_index=R,L.chunk_run_index=A):(R++,L.chunk_index=R,K=0,R<=P||(A++,A+1<l.first_chunk.length?P=l.first_chunk[A+1]-1:P=1/0),L.chunk_run_index=A,Z+=l.samples_per_chunk[A]),L.description_index=l.sample_description_index[L.chunk_run_index]-1,L.description=x.entries[L.description_index],L.offset=r.chunk_offsets[L.chunk_index-1]+K,K+=L.size,t>V&&(N++,V<0&&(V=0),V+=m.sample_counts[N]),t>0?(e.samples[t-1].duration=m.sample_deltas[N],e.samples_duration+=e.samples[t-1].duration,L.dts=e.samples[t-1].dts+e.samples[t-1].duration):L.dts=0,y?(t>=q&&(ee++,q<0&&(q=0),q+=y.sample_counts[ee]),L.cts=e.samples[t].dts+y.sample_offsets[ee]):L.cts=L.dts,b?(t==b.sample_numbers[xe]-1?(L.is_sync=!0,xe++):(L.is_sync=!1,L.degradation_priority=0),w&&w.entries[j].sample_delta+W==t+1&&(L.subsamples=w.entries[j].subsamples,W+=w.entries[j].sample_delta,j++)):L.is_sync=!0,S.process_sdtp(e.mdia.minf.stbl.sdtp,L,L.number),F?L.degradation_priority=F.priority[t]:L.degradation_priority=0,w&&w.entries[j].sample_delta+W==t&&(L.subsamples=w.entries[j].subsamples,W+=w.entries[j].sample_delta),(T.length>0||C.length>0)&&S.setSampleGroupProperties(e,L,t,e.sample_groups_info)}t>0&&(e.samples[t-1].duration=Math.max(e.mdia.mdhd.duration-e.samples[t-1].dts,0),e.samples_duration+=e.samples[t-1].duration)}},S.prototype.updateSampleLists=function(){var e,t,r,l,h,m,y,b,x,w,T,C,F,A,R;if(this.moov!==void 0){for(;this.lastMoofIndex<this.moofs.length;)if(x=this.moofs[this.lastMoofIndex],this.lastMoofIndex++,x.type=="moof")for(w=x,e=0;e<w.trafs.length;e++){for(T=w.trafs[e],C=this.getTrackById(T.tfhd.track_id),F=this.getTrexById(T.tfhd.track_id),T.tfhd.flags&s.TFHD_FLAG_SAMPLE_DESC?l=T.tfhd.default_sample_description_index:l=F?F.default_sample_description_index:1,T.tfhd.flags&s.TFHD_FLAG_SAMPLE_DUR?h=T.tfhd.default_sample_duration:h=F?F.default_sample_duration:0,T.tfhd.flags&s.TFHD_FLAG_SAMPLE_SIZE?m=T.tfhd.default_sample_size:m=F?F.default_sample_size:0,T.tfhd.flags&s.TFHD_FLAG_SAMPLE_FLAGS?y=T.tfhd.default_sample_flags:y=F?F.default_sample_flags:0,T.sample_number=0,T.sbgps.length>0&&S.initSampleGroups(C,T,T.sbgps,C.mdia.minf.stbl.sgpds,T.sgpds),t=0;t<T.truns.length;t++){var P=T.truns[t];for(r=0;r<P.sample_count;r++){A={},A.moof_number=this.lastMoofIndex,A.number_in_traf=T.sample_number,T.sample_number++,A.number=C.samples.length,T.first_sample_index=C.samples.length,C.samples.push(A),A.track_id=C.tkhd.track_id,A.timescale=C.mdia.mdhd.timescale,A.description_index=l-1,A.description=C.mdia.minf.stbl.stsd.entries[A.description_index],A.size=m,P.flags&s.TRUN_FLAGS_SIZE&&(A.size=P.sample_size[r]),C.samples_size+=A.size,A.duration=h,P.flags&s.TRUN_FLAGS_DURATION&&(A.duration=P.sample_duration[r]),C.samples_duration+=A.duration,C.first_traf_merged||r>0?A.dts=C.samples[C.samples.length-2].dts+C.samples[C.samples.length-2].duration:(T.tfdt?A.dts=T.tfdt.baseMediaDecodeTime:A.dts=0,C.first_traf_merged=!0),A.cts=A.dts,P.flags&s.TRUN_FLAGS_CTS_OFFSET&&(A.cts=A.dts+P.sample_composition_time_offset[r]),R=y,P.flags&s.TRUN_FLAGS_FLAGS?R=P.sample_flags[r]:r===0&&P.flags&s.TRUN_FLAGS_FIRST_FLAG&&(R=P.first_sample_flags),A.is_sync=!(R>>16&1),A.is_leading=R>>26&3,A.depends_on=R>>24&3,A.is_depended_on=R>>22&3,A.has_redundancy=R>>20&3,A.degradation_priority=R&65535;var K=!!(T.tfhd.flags&s.TFHD_FLAG_BASE_DATA_OFFSET),Z=!!(T.tfhd.flags&s.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),V=!!(P.flags&s.TRUN_FLAGS_DATA_OFFSET),N=0;K?N=T.tfhd.base_data_offset:Z||t===0?N=w.start:N=b,t===0&&r===0?V?A.offset=N+P.data_offset:A.offset=N:A.offset=b,b=A.offset+A.size,(T.sbgps.length>0||T.sgpds.length>0||C.mdia.minf.stbl.sbgps.length>0||C.mdia.minf.stbl.sgpds.length>0)&&S.setSampleGroupProperties(C,A,A.number_in_traf,T.sample_groups_info)}}if(T.subs){C.has_fragment_subsamples=!0;var q=T.first_sample_index;for(t=0;t<T.subs.entries.length;t++)q+=T.subs.entries[t].sample_delta,A=C.samples[q-1],A.subsamples=T.subs.entries[t].subsamples}}}},S.prototype.getSample=function(e,t){var r,l=e.samples[t];if(!this.moov)return null;if(!l.data)l.data=new Uint8Array(l.size),l.alreadyRead=0,this.samplesDataSize+=l.size,n.debug("ISOFile","Allocating sample #"+t+" on track #"+e.tkhd.track_id+" of size "+l.size+" (total: "+this.samplesDataSize+")");else if(l.alreadyRead==l.size)return l;for(;;){var h=this.stream.findPosition(!0,l.offset+l.alreadyRead,!1);if(h>-1){r=this.stream.buffers[h];var m=r.byteLength-(l.offset+l.alreadyRead-r.fileStart);if(l.size-l.alreadyRead<=m)return n.debug("ISOFile","Getting sample #"+t+" data (alreadyRead: "+l.alreadyRead+" offset: "+(l.offset+l.alreadyRead-r.fileStart)+" read size: "+(l.size-l.alreadyRead)+" full size: "+l.size+")"),d.memcpy(l.data.buffer,l.alreadyRead,r,l.offset+l.alreadyRead-r.fileStart,l.size-l.alreadyRead),r.usedBytes+=l.size-l.alreadyRead,this.stream.logBufferLevel(),l.alreadyRead=l.size,l;if(m===0)return null;n.debug("ISOFile","Getting sample #"+t+" partial data (alreadyRead: "+l.alreadyRead+" offset: "+(l.offset+l.alreadyRead-r.fileStart)+" read size: "+m+" full size: "+l.size+")"),d.memcpy(l.data.buffer,l.alreadyRead,r,l.offset+l.alreadyRead-r.fileStart,m),l.alreadyRead+=m,r.usedBytes+=m,this.stream.logBufferLevel()}else return null}},S.prototype.releaseSample=function(e,t){var r=e.samples[t];return r.data?(this.samplesDataSize-=r.size,r.data=null,r.alreadyRead=0,r.size):0},S.prototype.getAllocatedSampleDataSize=function(){return this.samplesDataSize},S.prototype.getCodecs=function(){var e,t="";for(e=0;e<this.moov.traks.length;e++){var r=this.moov.traks[e];e>0&&(t+=","),t+=r.mdia.minf.stbl.stsd.entries[0].getCodec()}return t},S.prototype.getTrexById=function(e){var t;if(!this.moov||!this.moov.mvex)return null;for(t=0;t<this.moov.mvex.trexs.length;t++){var r=this.moov.mvex.trexs[t];if(r.track_id==e)return r}return null},S.prototype.getTrackById=function(e){if(this.moov===void 0)return null;for(var t=0;t<this.moov.traks.length;t++){var r=this.moov.traks[t];if(r.tkhd.track_id==e)return r}return null},S.prototype.itemsDataSize=0,S.prototype.flattenItemInfo=function(){var e=this.items,t=this.entity_groups,r,l,h,m=this.meta;if(m!=null&&m.hdlr!==void 0&&m.iinf!==void 0){for(r=0;r<m.iinf.item_infos.length;r++)h={},h.id=m.iinf.item_infos[r].item_ID,e[h.id]=h,h.ref_to=[],h.name=m.iinf.item_infos[r].item_name,m.iinf.item_infos[r].protection_index>0&&(h.protection=m.ipro.protections[m.iinf.item_infos[r].protection_index-1]),m.iinf.item_infos[r].item_type?h.type=m.iinf.item_infos[r].item_type:h.type="mime",h.content_type=m.iinf.item_infos[r].content_type,h.content_encoding=m.iinf.item_infos[r].content_encoding;if(m.grpl)for(r=0;r<m.grpl.boxes.length;r++)entity_group={},entity_group.id=m.grpl.boxes[r].group_id,entity_group.entity_ids=m.grpl.boxes[r].entity_ids,entity_group.type=m.grpl.boxes[r].type,t[entity_group.id]=entity_group;if(m.iloc)for(r=0;r<m.iloc.items.length;r++){var y=m.iloc.items[r];switch(h=e[y.item_ID],y.data_reference_index!==0&&(n.warn("Item storage with reference to other files: not supported"),h.source=m.dinf.boxes[y.data_reference_index-1]),y.construction_method){case 0:break;case 1:break;case 2:n.warn("Item storage with construction_method : not supported");break}for(h.extents=[],h.size=0,l=0;l<y.extents.length;l++)h.extents[l]={},h.extents[l].offset=y.extents[l].extent_offset+y.base_offset,y.construction_method==1&&(h.extents[l].offset+=m.idat.start+m.idat.hdr_size),h.extents[l].length=y.extents[l].extent_length,h.extents[l].alreadyRead=0,h.size+=h.extents[l].length}if(m.pitm&&(e[m.pitm.item_id].primary=!0),m.iref)for(r=0;r<m.iref.references.length;r++){var b=m.iref.references[r];for(l=0;l<b.references.length;l++)e[b.from_item_ID].ref_to.push({type:b.type,id:b.references[l]})}if(m.iprp)for(var x=0;x<m.iprp.ipmas.length;x++){var w=m.iprp.ipmas[x];for(r=0;r<w.associations.length;r++){var T=w.associations[r];if(h=e[T.id],h||(h=t[T.id]),h)for(h.properties===void 0&&(h.properties={},h.properties.boxes=[]),l=0;l<T.props.length;l++){var C=T.props[l];if(C.property_index>0&&C.property_index-1<m.iprp.ipco.boxes.length){var F=m.iprp.ipco.boxes[C.property_index-1];h.properties[F.type]=F,h.properties.boxes.push(F)}}}}}},S.prototype.getItem=function(e){var t,r;if(!this.meta)return null;if(r=this.items[e],!r.data&&r.size)r.data=new Uint8Array(r.size),r.alreadyRead=0,this.itemsDataSize+=r.size,n.debug("ISOFile","Allocating item #"+e+" of size "+r.size+" (total: "+this.itemsDataSize+")");else if(r.alreadyRead===r.size)return r;for(var l=0;l<r.extents.length;l++){var h=r.extents[l];if(h.alreadyRead!==h.length){var m=this.stream.findPosition(!0,h.offset+h.alreadyRead,!1);if(m>-1){t=this.stream.buffers[m];var y=t.byteLength-(h.offset+h.alreadyRead-t.fileStart);if(h.length-h.alreadyRead<=y)n.debug("ISOFile","Getting item #"+e+" extent #"+l+" data (alreadyRead: "+h.alreadyRead+" offset: "+(h.offset+h.alreadyRead-t.fileStart)+" read size: "+(h.length-h.alreadyRead)+" full extent size: "+h.length+" full item size: "+r.size+")"),d.memcpy(r.data.buffer,r.alreadyRead,t,h.offset+h.alreadyRead-t.fileStart,h.length-h.alreadyRead),t.usedBytes+=h.length-h.alreadyRead,this.stream.logBufferLevel(),r.alreadyRead+=h.length-h.alreadyRead,h.alreadyRead=h.length;else return n.debug("ISOFile","Getting item #"+e+" extent #"+l+" partial data (alreadyRead: "+h.alreadyRead+" offset: "+(h.offset+h.alreadyRead-t.fileStart)+" read size: "+y+" full extent size: "+h.length+" full item size: "+r.size+")"),d.memcpy(r.data.buffer,r.alreadyRead,t,h.offset+h.alreadyRead-t.fileStart,y),h.alreadyRead+=y,r.alreadyRead+=y,t.usedBytes+=y,this.stream.logBufferLevel(),null}else return null}}return r.alreadyRead===r.size?r:null},S.prototype.releaseItem=function(e){var t=this.items[e];if(t.data){this.itemsDataSize-=t.size,t.data=null,t.alreadyRead=0;for(var r=0;r<t.extents.length;r++){var l=t.extents[r];l.alreadyRead=0}return t.size}else return 0},S.prototype.processItems=function(e){for(var t in this.items){var r=this.items[t];this.getItem(r.id),e&&!r.sent&&(e(r),r.sent=!0,r.data=null)}},S.prototype.hasItem=function(e){for(var t in this.items){var r=this.items[t];if(r.name===e)return r.id}return-1},S.prototype.getMetaHandler=function(){return this.meta?this.meta.hdlr.handler:null},S.prototype.getPrimaryItem=function(){return!this.meta||!this.meta.pitm?null:this.getItem(this.meta.pitm.item_id)},S.prototype.itemToFragmentedTrackFile=function(e){var t=e||{},r=null;if(t.itemId?r=this.getItem(t.itemId):r=this.getPrimaryItem(),r==null)return null;var l=new S;l.discardMdatData=!1;var h={type:r.type,description_boxes:r.properties.boxes};r.properties.ispe&&(h.width=r.properties.ispe.image_width,h.height=r.properties.ispe.image_height);var m=l.addTrack(h);return m?(l.addSample(m,r.data),l):null},S.prototype.write=function(e){for(var t=0;t<this.boxes.length;t++)this.boxes[t].write(e)},S.prototype.createFragment=function(e,t,r){var l=this.getTrackById(e),h=this.getSample(l,t);if(h==null)return this.setNextSeekPositionFromSample(l.samples[t]),null;var m=r||new d;m.endianness=d.BIG_ENDIAN;var y=this.createSingleSampleMoof(h);y.write(m),y.trafs[0].truns[0].data_offset=y.size+8,n.debug("MP4Box","Adjusting data_offset with new value "+y.trafs[0].truns[0].data_offset),m.adjustUint32(y.trafs[0].truns[0].data_offset_position,y.trafs[0].truns[0].data_offset);var b=new s.mdatBox;return b.data=h.data,b.write(m),m},S.writeInitializationSegment=function(e,t,r,l){var h;n.debug("ISOFile","Generating initialization segment");var m=new d;m.endianness=d.BIG_ENDIAN,e.write(m);var y=t.add("mvex");for(r&&y.add("mehd").set("fragment_duration",r),h=0;h<t.traks.length;h++)y.add("trex").set("track_id",t.traks[h].tkhd.track_id).set("default_sample_description_index",1).set("default_sample_duration",l).set("default_sample_size",0).set("default_sample_flags",65536);return t.write(m),m.buffer},S.prototype.save=function(e){var t=new d;t.endianness=d.BIG_ENDIAN,this.write(t),t.save(e)},S.prototype.getBuffer=function(){var e=new d;return e.endianness=d.BIG_ENDIAN,this.write(e),e.buffer},S.prototype.initializeSegmentation=function(){var e,t,r,l;for(this.onSegment===null&&n.warn("MP4Box","No segmentation callback set!"),this.isFragmentationInitialized||(this.isFragmentationInitialized=!0,this.nextMoofNumber=0,this.resetTables()),t=[],e=0;e<this.fragmentedTracks.length;e++){var h=new s.moovBox;h.mvhd=this.moov.mvhd,h.boxes.push(h.mvhd),r=this.getTrackById(this.fragmentedTracks[e].id),h.boxes.push(r),h.traks.push(r),l={},l.id=r.tkhd.track_id,l.user=this.fragmentedTracks[e].user,l.buffer=S.writeInitializationSegment(this.ftyp,h,this.moov.mvex&&this.moov.mvex.mehd?this.moov.mvex.mehd.fragment_duration:void 0,this.moov.traks[e].samples.length>0?this.moov.traks[e].samples[0].duration:0),t.push(l)}return t},s.Box.prototype.printHeader=function(e){this.size+=8,this.size>f&&(this.size+=8),this.type==="uuid"&&(this.size+=16),e.log(e.indent+"size:"+this.size),e.log(e.indent+"type:"+this.type)},s.FullBox.prototype.printHeader=function(e){this.size+=4,s.Box.prototype.printHeader.call(this,e),e.log(e.indent+"version:"+this.version),e.log(e.indent+"flags:"+this.flags)},s.Box.prototype.print=function(e){this.printHeader(e)},s.ContainerBox.prototype.print=function(e){this.printHeader(e);for(var t=0;t<this.boxes.length;t++)if(this.boxes[t]){var r=e.indent;e.indent+=" ",this.boxes[t].print(e),e.indent=r}},S.prototype.print=function(e){e.indent="";for(var t=0;t<this.boxes.length;t++)this.boxes[t]&&this.boxes[t].print(e)},s.mvhdBox.prototype.print=function(e){s.FullBox.prototype.printHeader.call(this,e),e.log(e.indent+"creation_time: "+this.creation_time),e.log(e.indent+"modification_time: "+this.modification_time),e.log(e.indent+"timescale: "+this.timescale),e.log(e.indent+"duration: "+this.duration),e.log(e.indent+"rate: "+this.rate),e.log(e.indent+"volume: "+(this.volume>>8)),e.log(e.indent+"matrix: "+this.matrix.join(", ")),e.log(e.indent+"next_track_id: "+this.next_track_id)},s.tkhdBox.prototype.print=function(e){s.FullBox.prototype.printHeader.call(this,e),e.log(e.indent+"creation_time: "+this.creation_time),e.log(e.indent+"modification_time: "+this.modification_time),e.log(e.indent+"track_id: "+this.track_id),e.log(e.indent+"duration: "+this.duration),e.log(e.indent+"volume: "+(this.volume>>8)),e.log(e.indent+"matrix: "+this.matrix.join(", ")),e.log(e.indent+"layer: "+this.layer),e.log(e.indent+"alternate_group: "+this.alternate_group),e.log(e.indent+"width: "+this.width),e.log(e.indent+"height: "+this.height)};var E={};E.createFile=function(e,t){var r=e!==void 0?e:!0,l=new S(t);return l.discardMdatData=!r,l},a.createFile=E.createFile}(mt)),mt}var yt=fn(),cn=Zt(yt),vt={exports:{}},ei;function hn(){return ei||(ei=1,function(a){var n={};a.exports=n,n.parse=function(o,d){for(var f=n.bin.readUshort,c=n.bin.readUint,_=0,u={},s=new Uint8Array(o),p=s.length-4;c(s,p)!=101010256;)p--;var _=p;_+=4,_+=4;var g=f(s,_);_+=2,f(s,_),_+=2;var v=c(s,_);_+=4;var U=c(s,_);_+=4,_=U;for(var S=0;S<g;S++){c(s,_),_+=4,_+=4,_+=4,_+=4,c(s,_),_+=4;var v=c(s,_);_+=4;var E=c(s,_);_+=4;var e=f(s,_),t=f(s,_+2),r=f(s,_+4);_+=6,_+=8;var l=c(s,_);_+=4,_+=e+t+r,n._readLocal(s,l,u,v,E,d)}return u},n._readLocal=function(o,d,f,c,u,s){var p=n.bin.readUshort,_=n.bin.readUint;_(o,d),d+=4,p(o,d),d+=2,p(o,d),d+=2;var g=p(o,d);d+=2,_(o,d),d+=4,_(o,d),d+=4,d+=8;var v=p(o,d);d+=2;var U=p(o,d);d+=2;var S=n.bin.readUTF8(o,d,v);if(d+=v,d+=U,s){f[S]={size:u,csize:c};return}var E=new Uint8Array(o.buffer,d);if(g==0)f[S]=new Uint8Array(E.buffer.slice(d,d+c));else if(g==8){var e=new Uint8Array(u);n.inflateRaw(E,e),f[S]=e}else throw"unknown compression method: "+g},n.inflateRaw=function(o,d){return n.F.inflate(o,d)},n.inflate=function(o,d){return o[0],o[1],n.inflateRaw(new Uint8Array(o.buffer,o.byteOffset+2,o.length-6),d)},n.deflate=function(o,d){d==null&&(d={level:6});var f=0,c=new Uint8Array(50+Math.floor(o.length*1.1));c[f]=120,c[f+1]=156,f+=2,f=n.F.deflateRaw(o,c,f,d.level);var u=n.adler(o,0,o.length);return c[f+0]=u>>>24&255,c[f+1]=u>>>16&255,c[f+2]=u>>>8&255,c[f+3]=u>>>0&255,new Uint8Array(c.buffer,0,f+4)},n.deflateRaw=function(o,d){d==null&&(d={level:6});var f=new Uint8Array(50+Math.floor(o.length*1.1)),c=n.F.deflateRaw(o,f,c,d.level);return new Uint8Array(f.buffer,0,c)},n.encode=function(o,d){d==null&&(d=!1);var f=0,c=n.bin.writeUint,u=n.bin.writeUshort,s={};for(var p in o){var _=!n._noNeed(p)&&!d,g=o[p],v=n.crc.crc(g,0,g.length);s[p]={cpr:_,usize:g.length,crc:v,file:_?n.deflateRaw(g):g}}for(var p in s)f+=s[p].file.length+30+46+2*n.bin.sizeUTF8(p);f+=22;var U=new Uint8Array(f),S=0,E=[];for(var p in s){var e=s[p];E.push(S),S=n._writeHeader(U,S,p,e,0)}var t=0,r=S;for(var p in s){var e=s[p];E.push(S),S=n._writeHeader(U,S,p,e,1,E[t++])}var l=S-r;return c(U,S,101010256),S+=4,S+=4,u(U,S,t),S+=2,u(U,S,t),S+=2,c(U,S,l),S+=4,c(U,S,r),S+=4,S+=2,U.buffer},n._noNeed=function(o){var d=o.split(".").pop().toLowerCase();return"png,jpg,jpeg,zip".indexOf(d)!=-1},n._writeHeader=function(o,d,f,c,u,s){var p=n.bin.writeUint,_=n.bin.writeUshort,g=c.file;p(o,d,u==0?67324752:33639248),d+=4,u==1&&(d+=2),_(o,d,20),d+=2,_(o,d,0),d+=2,_(o,d,c.cpr?8:0),d+=2,p(o,d,0),d+=4,p(o,d,c.crc),d+=4,p(o,d,g.length),d+=4,p(o,d,c.usize),d+=4,_(o,d,n.bin.sizeUTF8(f)),d+=2,_(o,d,0),d+=2,u==1&&(d+=2,d+=2,d+=6,p(o,d,s),d+=4);var v=n.bin.writeUTF8(o,d,f);return d+=v,u==0&&(o.set(g,d),d+=g.length),d},n.crc={table:function(){for(var o=new Uint32Array(256),d=0;d<256;d++){for(var f=d,c=0;c<8;c++)f&1?f=3988292384^f>>>1:f=f>>>1;o[d]=f}return o}(),update:function(o,d,f,c){for(var u=0;u<c;u++)o=n.crc.table[(o^d[f+u])&255]^o>>>8;return o},crc:function(o,d,f){return n.crc.update(4294967295,o,d,f)^4294967295}},n.adler=function(o,d,f){for(var c=1,u=0,s=d,p=d+f;s<p;){for(var _=Math.min(s+5552,p);s<_;)c+=o[s++],u+=c;c=c%65521,u=u%65521}return u<<16|c},n.bin={readUshort:function(o,d){return o[d]|o[d+1]<<8},writeUshort:function(o,d,f){o[d]=f&255,o[d+1]=f>>8&255},readUint:function(o,d){return o[d+3]*(256*256*256)+(o[d+2]<<16|o[d+1]<<8|o[d])},writeUint:function(o,d,f){o[d]=f&255,o[d+1]=f>>8&255,o[d+2]=f>>16&255,o[d+3]=f>>24&255},readASCII:function(o,d,f){for(var c="",u=0;u<f;u++)c+=String.fromCharCode(o[d+u]);return c},writeASCII:function(o,d,f){for(var c=0;c<f.length;c++)o[d+c]=f.charCodeAt(c)},pad:function(o){return o.length<2?"0"+o:o},readUTF8:function(o,d,f){for(var c="",u,s=0;s<f;s++)c+="%"+n.bin.pad(o[d+s].toString(16));try{u=decodeURIComponent(c)}catch{return n.bin.readASCII(o,d,f)}return u},writeUTF8:function(o,d,f){for(var c=f.length,u=0,s=0;s<c;s++){var p=f.charCodeAt(s);if(!(p&4294967168))o[d+u]=p,u++;else if(!(p&4294965248))o[d+u]=192|p>>6,o[d+u+1]=128|p>>0&63,u+=2;else if(!(p&4294901760))o[d+u]=224|p>>12,o[d+u+1]=128|p>>6&63,o[d+u+2]=128|p>>0&63,u+=3;else if(!(p&4294967295-(1<<21)+1))o[d+u]=240|p>>18,o[d+u+1]=128|p>>12&63,o[d+u+2]=128|p>>6&63,o[d+u+3]=128|p>>0&63,u+=4;else throw"e"}return u},sizeUTF8:function(o){for(var d=o.length,f=0,c=0;c<d;c++){var u=o.charCodeAt(c);if(!(u&4294967168))f++;else if(!(u&4294965248))f+=2;else if(!(u&4294901760))f+=3;else if(!(u&4294967295-(1<<21)+1))f+=4;else throw"e"}return f}},n.F={},n.F.deflateRaw=function(o,d,f,c){var u=[[0,0,0,0,0],[4,4,8,4,0],[4,5,16,8,0],[4,6,16,16,0],[4,10,16,32,0],[8,16,32,32,0],[8,16,128,128,0],[8,32,128,256,0],[32,128,258,1024,1],[32,258,258,4096,1]],s=u[c],p=n.F.U,_=n.F._goodIndex;n.F._hash;var g=n.F._putsE,v=0,U=f<<3,S=0,E=o.length;if(c==0){for(;v<E;){var e=Math.min(65535,E-v);g(d,U,v+e==E?1:0),U=n.F._copyExact(o,v,e,d,U+8),v+=e}return U>>>3}var t=p.lits,r=p.strt,l=p.prev,h=0,m=0,y=0,b=0,x=0,w=0;for(E>2&&(w=n.F._hash(o,0),r[w]=0),v=0;v<E;v++){if(x=w,v+1<E-2){w=n.F._hash(o,v+1);var T=v+1&32767;l[T]=r[w],r[w]=T}if(S<=v){(h>14e3||m>26697)&&E-v>100&&(S<v&&(t[h]=v-S,h+=2,S=v),U=n.F._writeBlock(v==E-1||S==E?1:0,t,h,b,o,y,v-y,d,U),h=m=b=0,y=v);var C=0;v<E-2&&(C=n.F._bestMatch(o,v,l,x,Math.min(s[2],E-v),s[3]));var e=C>>>16,F=C&65535;if(C!=0){var e=C>>>16,F=C&65535,A=_(e,p.of0);p.lhst[257+A]++;var R=_(F,p.df0);p.dhst[R]++,b+=p.exb[A]+p.dxb[R],t[h]=e<<23|v-S,t[h+1]=F<<16|A<<8|R,h+=2,S=v+e}else p.lhst[o[v]]++;m++}}for((y!=v||o.length==0)&&(S<v&&(t[h]=v-S,h+=2,S=v),U=n.F._writeBlock(1,t,h,b,o,y,v-y,d,U),h=0,m=0,h=m=b=0,y=v);U&7;)U++;return U>>>3},n.F._bestMatch=function(o,d,f,c,u,s){var p=d&32767,_=f[p],g=p-_+32768&32767;if(_==p||c!=n.F._hash(o,d-g))return 0;for(var v=0,U=0,S=Math.min(32767,d);g<=S&&--s!=0&&_!=p;){if(v==0||o[d+v]==o[d+v-g]){var E=n.F._howLong(o,d,g);if(E>v){if(v=E,U=g,v>=u)break;g+2<E&&(E=g+2);for(var e=0,t=0;t<E-2;t++){var r=d-g+t+32768&32767,l=f[r],h=r-l+32768&32767;h>e&&(e=h,_=r)}}}p=_,_=f[p],g+=p-_+32768&32767}return v<<16|U},n.F._howLong=function(o,d,f){if(o[d]!=o[d-f]||o[d+1]!=o[d+1-f]||o[d+2]!=o[d+2-f])return 0;var c=d,u=Math.min(o.length,d+258);for(d+=3;d<u&&o[d]==o[d-f];)d++;return d-c},n.F._hash=function(o,d){return(o[d]<<8|o[d+1])+(o[d+2]<<4)&65535},n.saved=0,n.F._writeBlock=function(o,d,f,c,u,s,p,_,g){var v=n.F.U,U=n.F._putsF,S=n.F._putsE,E,e,t,r,l,h,m,y,b;v.lhst[256]++,E=n.F.getTrees(),e=E[0],t=E[1],r=E[2],l=E[3],h=E[4],m=E[5],y=E[6],b=E[7];var x=(g+3&7?8-(g+3&7):0)+32+(p<<3),w=c+n.F.contSize(v.fltree,v.lhst)+n.F.contSize(v.fdtree,v.dhst),T=c+n.F.contSize(v.ltree,v.lhst)+n.F.contSize(v.dtree,v.dhst);T+=14+3*m+n.F.contSize(v.itree,v.ihst)+(v.ihst[16]*2+v.ihst[17]*3+v.ihst[18]*7);for(var C=0;C<286;C++)v.lhst[C]=0;for(var C=0;C<30;C++)v.dhst[C]=0;for(var C=0;C<19;C++)v.ihst[C]=0;var F=x<w&&x<T?0:w<T?1:2;if(U(_,g,o),U(_,g+1,F),g+=3,F==0){for(;g&7;)g++;g=n.F._copyExact(u,s,p,_,g)}else{var A,R;if(F==1&&(A=v.fltree,R=v.fdtree),F==2){n.F.makeCodes(v.ltree,e),n.F.revCodes(v.ltree,e),n.F.makeCodes(v.dtree,t),n.F.revCodes(v.dtree,t),n.F.makeCodes(v.itree,r),n.F.revCodes(v.itree,r),A=v.ltree,R=v.dtree,S(_,g,l-257),g+=5,S(_,g,h-1),g+=5,S(_,g,m-4),g+=4;for(var P=0;P<m;P++)S(_,g+P*3,v.itree[(v.ordr[P]<<1)+1]);g+=3*m,g=n.F._codeTiny(y,v.itree,_,g),g=n.F._codeTiny(b,v.itree,_,g)}for(var K=s,Z=0;Z<f;Z+=2){for(var V=d[Z],N=V>>>23,q=K+(V&(1<<23)-1);K<q;)g=n.F._writeLit(u[K++],A,_,g);if(N!=0){var ee=d[Z+1],xe=ee>>16,j=ee>>8&255,W=ee&255;g=n.F._writeLit(257+j,A,_,g),S(_,g,N-v.of0[j]),g+=v.exb[j],g=n.F._writeLit(W,R,_,g),U(_,g,xe-v.df0[W]),g+=v.dxb[W],K+=N}}g=n.F._writeLit(256,A,_,g)}return g},n.F._copyExact=function(o,d,f,c,u){var s=u>>>3;return c[s]=f,c[s+1]=f>>>8,c[s+2]=255-c[s],c[s+3]=255-c[s+1],s+=4,c.set(new Uint8Array(o.buffer,d,f),s),u+(f+4<<3)},n.F.getTrees=function(){for(var o=n.F.U,d=n.F._hufTree(o.lhst,o.ltree,15),f=n.F._hufTree(o.dhst,o.dtree,15),c=[],u=n.F._lenCodes(o.ltree,c),s=[],p=n.F._lenCodes(o.dtree,s),_=0;_<c.length;_+=2)o.ihst[c[_]]++;for(var _=0;_<s.length;_+=2)o.ihst[s[_]]++;for(var g=n.F._hufTree(o.ihst,o.itree,7),v=19;v>4&&o.itree[(o.ordr[v-1]<<1)+1]==0;)v--;return[d,f,g,u,p,v,c,s]},n.F.getSecond=function(o){for(var d=[],f=0;f<o.length;f+=2)d.push(o[f+1]);return d},n.F.nonZero=function(o){for(var d="",f=0;f<o.length;f+=2)o[f+1]!=0&&(d+=(f>>1)+",");return d},n.F.contSize=function(o,d){for(var f=0,c=0;c<d.length;c++)f+=d[c]*o[(c<<1)+1];return f},n.F._codeTiny=function(o,d,f,c){for(var u=0;u<o.length;u+=2){var s=o[u],p=o[u+1];c=n.F._writeLit(s,d,f,c);var _=s==16?2:s==17?3:7;s>15&&(n.F._putsE(f,c,p,_),c+=_)}return c},n.F._lenCodes=function(o,d){for(var f=o.length;f!=2&&o[f-1]==0;)f-=2;for(var c=0;c<f;c+=2){var u=o[c+1],s=c+3<f?o[c+3]:-1,p=c+5<f?o[c+5]:-1,_=c==0?-1:o[c-1];if(u==0&&s==u&&p==u){for(var g=c+5;g+2<f&&o[g+2]==u;)g+=2;var v=Math.min(g+1-c>>>1,138);v<11?d.push(17,v-3):d.push(18,v-11),c+=v*2-2}else if(u==_&&s==u&&p==u){for(var g=c+5;g+2<f&&o[g+2]==u;)g+=2;var v=Math.min(g+1-c>>>1,6);d.push(16,v-3),c+=v*2-2}else d.push(u,0)}return f>>>1},n.F._hufTree=function(o,d,f){var c=[],u=o.length,s=d.length,p=0;for(p=0;p<s;p+=2)d[p]=0,d[p+1]=0;for(p=0;p<u;p++)o[p]!=0&&c.push({lit:p,f:o[p]});var _=c.length,g=c.slice(0);if(_==0)return 0;if(_==1){var v=c[0].lit,g=v==0?1:0;return d[(v<<1)+1]=1,d[(g<<1)+1]=1,1}c.sort(function(l,h){return l.f-h.f});var U=c[0],S=c[1],E=0,e=1,t=2;for(c[0]={lit:-1,f:U.f+S.f,l:U,r:S,d:0};e!=_-1;)E!=e&&(t==_||c[E].f<c[t].f)?U=c[E++]:U=c[t++],E!=e&&(t==_||c[E].f<c[t].f)?S=c[E++]:S=c[t++],c[e++]={lit:-1,f:U.f+S.f,l:U,r:S};var r=n.F.setDepth(c[e-1],0);for(r>f&&(n.F.restrictDepth(g,f,r),r=f),p=0;p<_;p++)d[(g[p].lit<<1)+1]=g[p].d;return r},n.F.setDepth=function(o,d){return o.lit!=-1?(o.d=d,d):Math.max(n.F.setDepth(o.l,d+1),n.F.setDepth(o.r,d+1))},n.F.restrictDepth=function(o,d,f){var c=0,u=1<<f-d,s=0;for(o.sort(function(_,g){return g.d==_.d?_.f-g.f:g.d-_.d}),c=0;c<o.length&&o[c].d>d;c++){var p=o[c].d;o[c].d=d,s+=u-(1<<f-p)}for(s=s>>>f-d;s>0;){var p=o[c].d;p<d?(o[c].d++,s-=1<<d-p-1):c++}for(;c>=0;c--)o[c].d==d&&s<0&&(o[c].d--,s++);s!=0&&console.log("debt left")},n.F._goodIndex=function(o,d){var f=0;return d[f|16]<=o&&(f|=16),d[f|8]<=o&&(f|=8),d[f|4]<=o&&(f|=4),d[f|2]<=o&&(f|=2),d[f|1]<=o&&(f|=1),f},n.F._writeLit=function(o,d,f,c){return n.F._putsF(f,c,d[o<<1]),c+d[(o<<1)+1]},n.F.inflate=function(o,d){var f=Uint8Array;if(o[0]==3&&o[1]==0)return d||new f(0);var c=n.F,u=c._bitsF,s=c._bitsE,p=c._decodeTiny,_=c.makeCodes,g=c.codes2map,v=c._get17,U=c.U,S=d==null;S&&(d=new f(o.length>>>2<<3));for(var E=0,e=0,t=0,r=0,l=0,h=0,m=0,y=0,b=0,x,w;E==0;){if(E=u(o,b,1),e=u(o,b+1,2),b+=3,e==0){b&7&&(b+=8-(b&7));var T=(b>>>3)+4,C=o[T-4]|o[T-3]<<8;S&&(d=n.F._check(d,y+C)),d.set(new f(o.buffer,o.byteOffset+T,C),y),b=T+C<<3,y+=C;continue}if(S&&(d=n.F._check(d,y+(1<<17))),e==1&&(x=U.flmap,w=U.fdmap,h=511,m=31),e==2){t=s(o,b,5)+257,r=s(o,b+5,5)+1,l=s(o,b+10,4)+4,b+=14;for(var F=0;F<38;F+=2)U.itree[F]=0,U.itree[F+1]=0;for(var A=1,F=0;F<l;F++){var R=s(o,b+F*3,3);U.itree[(U.ordr[F]<<1)+1]=R,R>A&&(A=R)}b+=3*l,_(U.itree,A),g(U.itree,A,U.imap),x=U.lmap,w=U.dmap,b=p(U.imap,(1<<A)-1,t+r,o,b,U.ttree);var P=c._copyOut(U.ttree,0,t,U.ltree);h=(1<<P)-1;var K=c._copyOut(U.ttree,t,r,U.dtree);m=(1<<K)-1,_(U.ltree,P),g(U.ltree,P,x),_(U.dtree,K),g(U.dtree,K,w)}for(;;){var Z=x[v(o,b)&h];b+=Z&15;var V=Z>>>4;if(!(V>>>8))d[y++]=V;else{if(V==256)break;var N=y+V-254;if(V>264){var q=U.ldef[V-257];N=y+(q>>>3)+s(o,b,q&7),b+=q&7}var ee=w[v(o,b)&m];b+=ee&15;var xe=ee>>>4,j=U.ddef[xe],W=(j>>>4)+u(o,b,j&15);for(b+=j&15,S&&(d=n.F._check(d,y+(1<<17)));y<N;)d[y]=d[y++-W],d[y]=d[y++-W],d[y]=d[y++-W],d[y]=d[y++-W];y=N}}}return d.length==y?d:d.slice(0,y)},n.F._check=function(o,d){var f=o.length;if(d<=f)return o;var c=new Uint8Array(Math.max(f<<1,d));return c.set(o,0),c},n.F._decodeTiny=function(o,d,f,c,u,s){for(var p=n.F._bitsE,_=n.F._get17,g=0;g<f;){var v=o[_(c,u)&d];u+=v&15;var U=v>>>4;if(U<=15)s[g]=U,g++;else{var S=0,E=0;U==16?(E=3+p(c,u,2),u+=2,S=s[g-1]):U==17?(E=3+p(c,u,3),u+=3):U==18&&(E=11+p(c,u,7),u+=7);for(var e=g+E;g<e;)s[g]=S,g++}}return u},n.F._copyOut=function(o,d,f,c){for(var u=0,s=0,p=c.length>>>1;s<f;){var _=o[s+d];c[s<<1]=0,c[(s<<1)+1]=_,_>u&&(u=_),s++}for(;s<p;)c[s<<1]=0,c[(s<<1)+1]=0,s++;return u},n.F.makeCodes=function(o,d){for(var f=n.F.U,c=o.length,u,s,p,_,g,v=f.bl_count,_=0;_<=d;_++)v[_]=0;for(_=1;_<c;_+=2)v[o[_]]++;var U=f.next_code;for(u=0,v[0]=0,s=1;s<=d;s++)u=u+v[s-1]<<1,U[s]=u;for(p=0;p<c;p+=2)g=o[p+1],g!=0&&(o[p]=U[g],U[g]++)},n.F.codes2map=function(o,d,f){for(var c=o.length,u=n.F.U,s=u.rev15,p=0;p<c;p+=2)if(o[p+1]!=0)for(var _=p>>1,g=o[p+1],v=_<<4|g,U=d-g,S=o[p]<<U,E=S+(1<<U);S!=E;){var e=s[S]>>>15-d;f[e]=v,S++}},n.F.revCodes=function(o,d){for(var f=n.F.U.rev15,c=15-d,u=0;u<o.length;u+=2){var s=o[u]<<d-o[u+1];o[u]=f[s]>>>c}},n.F._putsE=function(o,d,f){f=f<<(d&7);var c=d>>>3;o[c]|=f,o[c+1]|=f>>>8},n.F._putsF=function(o,d,f){f=f<<(d&7);var c=d>>>3;o[c]|=f,o[c+1]|=f>>>8,o[c+2]|=f>>>16},n.F._bitsE=function(o,d,f){return(o[d>>>3]|o[(d>>>3)+1]<<8)>>>(d&7)&(1<<f)-1},n.F._bitsF=function(o,d,f){return(o[d>>>3]|o[(d>>>3)+1]<<8|o[(d>>>3)+2]<<16)>>>(d&7)&(1<<f)-1},n.F._get17=function(o,d){return(o[d>>>3]|o[(d>>>3)+1]<<8|o[(d>>>3)+2]<<16)>>>(d&7)},n.F._get25=function(o,d){return(o[d>>>3]|o[(d>>>3)+1]<<8|o[(d>>>3)+2]<<16|o[(d>>>3)+3]<<24)>>>(d&7)},n.F.U=function(){var o=Uint16Array,d=Uint32Array;return{next_code:new o(16),bl_count:new o(16),ordr:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],of0:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],exb:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],ldef:new o(32),df0:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],dxb:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],ddef:new d(32),flmap:new o(512),fltree:[],fdmap:new o(32),fdtree:[],lmap:new o(32768),ltree:[],ttree:[],dmap:new o(32768),dtree:[],imap:new o(512),itree:[],rev15:new o(32768),lhst:new d(286),dhst:new d(30),ihst:new d(19),lits:new d(15e3),strt:new o(65536),prev:new o(32768)}}(),function(){for(var o=n.F.U,d=32768,f=0;f<d;f++){var c=f;c=(c&2863311530)>>>1|(c&1431655765)<<1,c=(c&3435973836)>>>2|(c&858993459)<<2,c=(c&4042322160)>>>4|(c&252645135)<<4,c=(c&4278255360)>>>8|(c&16711935)<<8,o.rev15[f]=(c>>>16|c<<16)>>>17}function u(s,p,_){for(;p--!=0;)s.push(0,_)}for(var f=0;f<32;f++)o.ldef[f]=o.of0[f]<<3|o.exb[f],o.ddef[f]=o.df0[f]<<4|o.dxb[f];u(o.fltree,144,8),u(o.fltree,112,9),u(o.fltree,24,7),u(o.fltree,8,8),n.F.makeCodes(o.fltree,9),n.F.codes2map(o.fltree,9,o.flmap),n.F.revCodes(o.fltree,9),u(o.fdtree,32,5),n.F.makeCodes(o.fdtree,5),n.F.codes2map(o.fdtree,5,o.fdmap),n.F.revCodes(o.fdtree,5),u(o.itree,19,0),u(o.ltree,286,0),u(o.dtree,30,0),u(o.ttree,320,0)}()}(vt)),vt.exports}var un=hn(),pn=Zt(un);const Y=class Y{constructor(n,o,d,f,c){this.copy=()=>new Y(this.h,this.m,this.s,this.f,this.field),this.print=()=>{const u=":";let s=("0"+this.h).slice(-2)+u+("0"+this.m).slice(-2)+u+("0"+this.s).slice(-2)+u+("0"+this.f).slice(-2);return s+="."+(this.field?"1":"2"),s},this.toZipTimeCodeString=()=>{const u=this.copy();return u.f=0,u.s=u.s%2===0?u.s:u.s-1,u.field=0,Y.toStr(u)},this.toFrames=u=>{let s=60,p=0;Math.floor(u)==60?(s=60,p=0):Math.floor(u)==59?(s=60,p=4):Math.floor(u)==30?(s=30,p=0):Math.floor(u)==29&&(s=30,p=2);let _=this.h,g=this.m,v=this.s,U=this.f,S=this.field;const E=_*60+g,t=(E-Math.floor(E/10))*p;return _*(s*3600)+g*(s*60)+v*s+(U*2+S)-t},this.addSeconds=u=>{let s=this.copy();if(s.s+=u,s.s>=60){const p=Math.floor(s.s/60);if(s.s=s.s%60,s.m+=p,s.m>=60){const _=Math.floor(s.m/60);s.m=s.m%60,s.h+=_}}return s},this.addFrames=(u,s)=>{let p=this.toFrames(s);return p+=u,Y.fromFrames(p,s)},this.subtractFrames=(u,s)=>this.addFrames(-u,s),this.h=n||0,this.m=o||0,this.s=d||0,this.f=f||0,this.field=c||0}static compare(n,o){return n.h!==o.h?n.h<o.h?-1:1:n.m!==o.m?n.m<o.m?-1:1:n.s!==o.s?n.s<o.s?-1:1:n.f!==o.f?n.f<o.f?-1:1:n.field!==o.field?n.field<o.field?-1:1:0}static generateTimecodeRange(n,o,d){const f=[];let c=n;for(;Y.compare(c,o)<=0;)f.push(c),c=c.addSeconds(d);return f}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(n){return this.toFrames(n)*1e3/n}};Y.calculateCurrentTimeCode=n=>{var v;if(!n.video||!n.clocker||!n.gameParams)throw new Error("OTTPlayer is not initialized");const o=n.video,d=n.clocker,f=d.videoFPScalculator.getFPS(),s=(o.currentTime-d.syncPoint.playerTime)%(60*60*24)*f+d.syncPoint.frame;if(s===0||f===0)throw new Error("Current frame is 0 or fps is 0");const p=Y.calculateCurrentOffset(s,(v=n.gameParams)==null?void 0:v.offsets);if(p===void 0)throw new Error("Offset is undefined");let _=Math.floor(s-p);return _<0&&(_+=5178816),_>=5178816&&(_-=5178816),Y.fromFrames(_,f)},Y.calculateCurrentOffset=(n,o)=>{for(let d=1;d<o.length;d++)if(n<o[d].frame)return o[d-1].offset;return Math.abs(o[o.length-1].offset)},Y.fromFrames=(n,o)=>{let d=60,f=0;Math.floor(o)==60?(d=60,f=0):Math.floor(o)==59?(d=60,f=4):Math.floor(o)==30?(d=30,f=0):Math.floor(o)==29&&(d=30,f=2);let c=Math.floor(o*60),u=Math.floor(o*60*10),s=u*6,p=n,_=Math.floor(p/s);p-=_*s;let g=Math.floor(p/u);p-=g*u,p>=d*60&&(p+=f*(Math.floor((p-d*60)/c)+1));let v=Math.floor(p/(d*60));p-=v*(d*60);let U=Math.floor(p/d);p-=U*d;let S=p;v+=g*10;let E=0;return E=S%2,S=Math.floor(S/2),new Y(_,v,U,S,E)},Y.toStr=n=>{const o="_";let d=("0"+n.h).slice(-2)+o+("0"+n.m).slice(-2)+o+("0"+n.s).slice(-2)+o+("0"+n.f).slice(-2);return n.field&&(d+="_1"),d},Y.fromStr=n=>{const d=n.split("_").map(Number);if(d.length==4){const[f,c,u,s]=d;return new Y(f,c,u,s,0)}else if(d.length==5){const[f,c,u,s,p]=d;return new Y(f,c,u,s,p)}else throw new Error("Invalid timecode format: "+n)},Y.fromMetadata=n=>{const o=/^(\\d{2}):(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d))?$/,d=n.timecode.match(o);if(!d)throw new Error("Invalid timecode format: "+n.timecode);const[,f,c,u,s,p]=d,_=Number(f),g=Number(c),v=Number(u),U=Number(s),S=p?Number(p):0;return new Y(_,g,v,U,S)};let $=Y;const O={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},te=console,he={};Object.keys(O).forEach(a=>{he[a]=te[a]});const Be="Datadog Browser SDK:",M={debug:he.debug.bind(te,Be),log:he.log.bind(te,Be),info:he.info.bind(te,Be),warn:he.warn.bind(te,Be),error:he.error.bind(te,Be)},St="https://docs.datadoghq.com",ti=`${St}/real_user_monitoring/browser/troubleshooting`,Ve="More details:";function ii(a,n){return(...o)=>{try{return a(...o)}catch(d){M.error(n,d)}}}function $e(a){return a!==0&&Math.random()*100<=a}function _n(a){return gn(a)&&a>=0&&a<=100}function gn(a){return typeof a=="number"}const ke=1e3,ue=60*ke,ni=60*ue,mn=365*(24*ni);function Le(){return new Date().getTime()}function oe(){return Le()}function je(){return performance.now()}function ae(){return{relative:je(),timeStamp:oe()}}function yn(){return{relative:0,timeStamp:ri()}}function vn(a,n){return n-a}function Sn(a,n){return a+n}function bn(a){return a-ri()}let bt;function ri(){return bt===void 0&&(bt=performance.timing.navigationStart),bt}const ie=1024,si=1024*ie,xn=/[^\\u0000-\\u007F]/;function xt(a){return xn.test(a)?window.TextEncoder!==void 0?new TextEncoder().encode(a).length:new Blob([a]).size:a.length}function Un(a){return{...a}}function oi(a,n){return Object.keys(a).some(o=>a[o]===n)}function De(a){return Object.keys(a).length===0}function de(){if(typeof globalThis=="object")return globalThis;Object.defineProperty(Object.prototype,"_dd_temp_",{get(){return this},configurable:!0});let a=_dd_temp_;return delete Object.prototype._dd_temp_,typeof a!="object"&&(typeof self=="object"?a=self:typeof window=="object"?a=window:a={}),a}function Ue(a,n){const o=de();let d;return o.Zone&&typeof o.Zone.__symbol__=="function"&&(d=a[o.Zone.__symbol__(n)]),d||(d=a[n]),d}let Ke,ai=!1;function En(a){Ke=a}function wn(a){ai=a}function Tn(a,n,o){const d=o.value;o.value=function(...f){return(Ke?D(d):d).apply(this,f)}}function D(a){return function(){return Re(a,this,arguments)}}function Re(a,n,o){try{return a.apply(n,o)}catch(d){Cn(d)}}function Cn(a){if(Ut(a),Ke)try{Ke(a)}catch(n){Ut(n)}}function Ut(...a){ai&&M.error("[MONITOR]",...a)}function Pe(a,n){return Ue(de(),"setTimeout")(D(a),n)}function di(a){Ue(de(),"clearTimeout")(a)}function Et(a,n){return Ue(de(),"setInterval")(D(a),n)}function li(a){Ue(de(),"clearInterval")(a)}class G{constructor(n){this.onFirstSubscribe=n,this.observers=[]}subscribe(n){return this.observers.push(n),this.observers.length===1&&this.onFirstSubscribe&&(this.onLastUnsubscribe=this.onFirstSubscribe(this)||void 0),{unsubscribe:()=>{this.observers=this.observers.filter(o=>n!==o),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}}notify(n){this.observers.forEach(o=>o(n))}}function fi(...a){return new G(n=>{const o=a.map(d=>d.subscribe(f=>n.notify(f)));return()=>o.forEach(d=>d.unsubscribe())})}function ci(a,n,o){let d=!1,f,c;return{throttled:(...u)=>{if(d){f=u;return}a(...u),d=!0,c=Pe(()=>{f&&a(...f),d=!1,f=void 0},n)},cancel:()=>{di(c),d=!1,f=void 0}}}function le(){}function fe(a){return a?(parseInt(a,10)^Math.random()*16>>parseInt(a,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,fe)}const qe=/([\\w-]+)\\s*=\\s*([^;]+)/g;function An(a,n){for(qe.lastIndex=0;;){const o=qe.exec(a);if(o){if(o[1]===n)return o[2]}else break}}function In(a){const n=new Map;for(qe.lastIndex=0;;){const o=qe.exec(a);if(o)n.set(o[1],o[2]);else break}return n}function Fn(a,n,o=""){const d=a.charCodeAt(n-1),c=d>=55296&&d<=56319?n+1:n;return a.length<=c?a:`${a.slice(0,c)}${o}`}function Bn(){return kn()===0}let We;function kn(){return We??(We=Ln())}function Ln(a=window){var n;const o=a.navigator.userAgent;return a.chrome||/HeadlessChrome/.test(o)?0:((n=a.navigator.vendor)===null||n===void 0?void 0:n.indexOf("Apple"))===0||/safari/i.test(o)&&!/chrome|android/i.test(o)?1:2}function ze(a,n,o=0,d){const f=new Date;f.setTime(f.getTime()+o);const c=`expires=${f.toUTCString()}`,u=d&&d.crossSite?"none":"strict",s=d&&d.domain?`;domain=${d.domain}`:"",p=d&&d.secure?";secure":"",_=d&&d.partitioned?";partitioned":"";document.cookie=`${a}=${n};${c};path=/;samesite=${u}${s}${p}${_}`}function wt(a){return An(document.cookie,a)}let Tt;function pe(a){return Tt||(Tt=In(document.cookie)),Tt.get(a)}function hi(a,n){ze(a,"",0,n)}function Dn(a){if(document.cookie===void 0||document.cookie===null)return!1;try{const n=`dd_cookie_test_${fe()}`,o="test";ze(n,o,ue,a);const d=wt(n)===o;return hi(n,a),d}catch(n){return M.error(n),!1}}let Ct;function Rn(){if(Ct===void 0){const a=`dd_site_test_${fe()}`,n="test",o=window.location.hostname.split(".");let d=o.pop();for(;o.length&&!wt(a);)d=`${o.pop()}.${d}`,ze(a,n,ke,{domain:d});hi(a,{domain:d}),Ct=d}return Ct}const Ee="_dd_s";function Je(a){return Object.values(a)}function Pn(a){return Object.entries(a)}const At=4*ni,ui=15*ue,zn=mn,Oe={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},pi=/^([a-zA-Z]+)=([a-z0-9-]+)$/,It="&";function On(a){return!!a&&(a.indexOf(It)!==-1||pi.test(a))}const Mn="1";function _e(a,n){const o={isExpired:Mn};return n.trackAnonymousUser&&(a!=null&&a.anonymousId?o.anonymousId=a==null?void 0:a.anonymousId:o.anonymousId=fe()),o}function Xe(a){return De(a)}function _i(a){return!Xe(a)}function Ze(a){return a.isExpired!==void 0||!Nn(a)}function Nn(a){return(a.created===void 0||Le()-Number(a.created)<At)&&(a.expire===void 0||Le()<Number(a.expire))}function gi(a){a.expire=String(Le()+ui)}function Ft(a){return Pn(a).map(([n,o])=>n==="anonymousId"?`aid=${o}`:`${n}=${o}`).join(It)}function mi(a){const n={};return On(a)&&a.split(It).forEach(o=>{const d=pi.exec(o);if(d!==null){const[,f,c]=d;f==="aid"?n.anonymousId=c:n[f]=c}}),n}const Gn="_dd",Hn="_dd_r",Yn="_dd_l",Vn="rum",$n="logs";function jn(a){if(!pe(Ee)){const o=pe(Gn),d=pe(Hn),f=pe(Yn),c={};o&&(c.id=o),f&&/^[01]$/.test(f)&&(c[$n]=f),d&&/^[012]$/.test(d)&&(c[Vn]=d),_i(c)&&(gi(c),a.persistSession(c))}}function yi(a){const n=Xn(a);return Dn(n)?{type:Oe.COOKIE,cookieOptions:n}:void 0}function Kn(a,n){const o={isLockEnabled:Bn(),persistSession:qn(n),retrieveSession:Jn,expireSession:d=>Wn(n,d,a)};return jn(o),o}function qn(a){return n=>{ze(Ee,Ft(n),ui,a)}}function Wn(a,n,o){const d=_e(n,o);ze(Ee,Ft(d),o.trackAnonymousUser?zn:At,a)}function Jn(){const a=wt(Ee);return mi(a)}function Xn(a){const n={};return n.secure=!!a.useSecureSessionCookie||!!a.usePartitionedCrossSiteSessionCookie,n.crossSite=!!a.usePartitionedCrossSiteSessionCookie,n.partitioned=!!a.usePartitionedCrossSiteSessionCookie,a.trackSessionAcrossSubdomains&&(n.domain=Rn()),n}const Zn="_dd_test_";function vi(){try{const a=fe(),n=`${Zn}${a}`;localStorage.setItem(n,a);const o=localStorage.getItem(n);return localStorage.removeItem(n),a===o?{type:Oe.LOCAL_STORAGE}:void 0}catch{return}}function Qn(a){return{isLockEnabled:!1,persistSession:Si,retrieveSession:er,expireSession:n=>tr(n,a)}}function Si(a){localStorage.setItem(Ee,Ft(a))}function er(){const a=localStorage.getItem(Ee);return mi(a)}function tr(a,n){Si(_e(a,n))}const ir=10,nr=100,bi=[];let Qe;function ge(a,n,o=0){var d;const{isLockEnabled:f,persistSession:c,expireSession:u}=n,s=U=>c({...U,lock:_}),p=()=>{const U=n.retrieveSession(),S=U.lock;return U.lock&&delete U.lock,{session:U,lock:S}};if(Qe||(Qe=a),a!==Qe){bi.push(a);return}if(f&&o>=nr){xi(n);return}let _,g=p();if(f){if(g.lock){et(a,n,o);return}if(_=fe(),s(g.session),g=p(),g.lock!==_){et(a,n,o);return}}let v=a.process(g.session);if(f&&(g=p(),g.lock!==_)){et(a,n,o);return}if(v&&(Ze(v)?u(v):(gi(v),f?s(v):c(v))),f&&!(v&&Ze(v))){if(g=p(),g.lock!==_){et(a,n,o);return}c(g.session),v=g.session}(d=a.after)===null||d===void 0||d.call(a,v||g.session),xi(n)}function et(a,n,o){Pe(()=>{ge(a,n,o+1)},ir)}function xi(a){Qe=void 0;const n=bi.shift();n&&ge(n,a)}const Ui=ke;function rr(a){switch(a.sessionPersistence){case Oe.COOKIE:return yi(a);case Oe.LOCAL_STORAGE:return vi();case void 0:{let n=yi(a);return!n&&a.allowFallbackToLocalStorage&&(n=vi()),n}default:M.error(`Invalid session persistence \'${String(a.sessionPersistence)}\'`)}}function sr(a,n,o,d){const f=new G,c=new G,u=new G,s=a.type===Oe.COOKIE?Kn(n,a.cookieOptions):Qn(n),{expireSession:p}=s,_=Et(E,Ui);let g;t();const{throttled:v,cancel:U}=ci(()=>{ge({process:x=>{if(Xe(x))return;const w=e(x);return r(w),w},after:x=>{_i(x)&&!l()&&y(x),g=x}},s)},Ui);function S(){ge({process:x=>l()?e(x):void 0},s)}function E(){ge({process:x=>Ze(x)?_e(x,n):void 0,after:e},s)}function e(x){return Ze(x)&&(x=_e(x,n)),l()&&(h(x)?m():(u.notify({previousState:g,newState:x}),g=x)),x}function t(){ge({process:x=>{if(Xe(x))return _e(x,n)},after:x=>{g=x}},s)}function r(x){if(Xe(x))return!1;const{trackingType:w,isTracked:T}=d(x[o]);x[o]=w,delete x.isExpired,T&&!x.id&&(x.id=fe(),x.created=String(Le()))}function l(){return g[o]!==void 0}function h(x){return g.id!==x.id||g[o]!==x[o]}function m(){g=_e(g,n),c.notify()}function y(x){g=x,f.notify()}function b(x){ge({process:w=>({...w,...x}),after:e},s)}return{expandOrRenewSession:v,expandSession:S,getSession:()=>g,renewObservable:f,expireObservable:c,sessionStateUpdateObservable:u,restartSession:t,expire:()=>{U(),p(g),e(_e(g,n))},stop:()=>{li(_)},updateSessionState:b}}const Bt={GRANTED:"granted",NOT_GRANTED:"not-granted"};function or(a){const n=new G;return{tryToInit(o){a||(a=o)},update(o){a=o,n.notify()},isGranted(){return a===Bt.GRANTED},observable:n}}function me(a,n,o){if(typeof a!="object"||a===null)return JSON.stringify(a);const d=we(Object.prototype),f=we(Array.prototype),c=we(Object.getPrototypeOf(a)),u=we(a);try{return JSON.stringify(a,n,o)}catch{return"<error: unable to serialize object>"}finally{d(),f(),c(),u()}}function we(a){const n=a,o=n.toJSON;return o?(delete n.toJSON,()=>{n.toJSON=o}):le}function kt(a){return ar(a,location.href).href}function ar(a,n){const o=dr();if(o)try{return n!==void 0?new o(a,n):new o(a)}catch(c){throw new Error(`Failed to construct URL: ${String(c)} ${me({url:a,base:n})}`)}if(n===void 0&&!/:/.test(a))throw new Error(`Invalid URL: \'${a}\'`);let d=document;const f=d.createElement("a");if(n!==void 0){d=document.implementation.createHTMLDocument("");const c=d.createElement("base");c.href=n,d.head.appendChild(c),d.body.appendChild(f)}return f.href=a,f}const Ei=URL;let tt;function dr(){if(tt===void 0)try{tt=new Ei("http://test/path").href==="http://test/path"}catch{tt=!1}return tt?Ei:void 0}const lr="datad0g.com",fr="dd0g-gov.com",Te="datadoghq.com",cr="ddog-gov.com",hr="pci.browser-intake-datadoghq.com",ur=["ddsource","ddtags"];function Me(a,n,o){const d=pr(a,n);return{build(f,c){const u=gr(a,n,o,f,c);return d(u)},urlPrefix:d(""),trackType:n}}function pr(a,n){const o=`/api/v2/${n}`,d=a.proxy;if(typeof d=="string"){const c=kt(d);return u=>`${c}?ddforward=${encodeURIComponent(`${o}?${u}`)}`}if(typeof d=="function")return c=>d({path:o,parameters:c});const f=_r(n,a);return c=>`https://${f}${o}?${c}`}function _r(a,n){const{site:o=Te,internalAnalyticsSubdomain:d}=n;if(a==="logs"&&n.usePciIntake&&o===Te)return hr;if(d&&o===Te)return`${d}.${Te}`;if(o===fr)return`http-intake.logs.${o}`;const f=o.split("."),c=f.pop();return`browser-intake-${f.join("-")}.${c}`}function gr({clientToken:a,internalAnalyticsSubdomain:n},o,d,f,{retry:c,encoding:u}){const s=["sdk_version:6.5.0",`api:${f}`].concat(d);c&&s.push(`retry_count:${c.count}`,`retry_after:${c.lastFailureStatus}`);const p=["ddsource=browser",`ddtags=${encodeURIComponent(s.join(","))}`,`dd-api-key=${a}`,`dd-evp-origin-version=${encodeURIComponent("6.5.0")}`,"dd-evp-origin=browser",`dd-request-id=${fe()}`];return u&&p.push(`dd-evp-encoding=${u}`),o==="rum"&&p.push(`batch_time=${oe()}`),n&&p.reverse(),p.join("&")}const mr=200;function yr(a){const{env:n,service:o,version:d,datacenter:f}=a,c=[];return n&&c.push(it("env",n)),o&&c.push(it("service",o)),d&&c.push(it("version",d)),f&&c.push(it("datacenter",f)),c}function it(a,n){const o=mr-a.length-1;(n.length>o||vr(n))&&M.warn(`${a} value doesn\'t meet tag requirements and will be sanitized. ${Ve} ${St}/getting_started/tagging/#defining-tags`);const d=n.replace(/,/g,"_");return`${a}:${d}`}function vr(a){return Sr()?new RegExp("[^\\\\p{Ll}\\\\p{Lo}0-9_:./-]","u").test(a):!1}function Sr(){try{return new RegExp("[\\\\p{Ll}]","u"),!0}catch{return!1}}function br(a){const n=a.site||Te,o=yr(a),d=xr(a,o);return{replica:Ur(a,o),site:n,...d}}function xr(a,n){return{logsEndpointBuilder:Me(a,"logs",n),rumEndpointBuilder:Me(a,"rum",n),sessionReplayEndpointBuilder:Me(a,"replay",n)}}function Ur(a,n){if(!a.replica)return;const o={...a,site:Te,clientToken:a.replica.clientToken},d={logsEndpointBuilder:Me(o,"logs",n),rumEndpointBuilder:Me(o,"rum",n)};return{applicationId:a.replica.applicationId,...d}}function Er(a){return ur.every(n=>a.includes(n))}function Lt(a,n){return a!=null&&typeof a!="string"?(M.error(`${n} must be defined as a string`),!1):!0}function wr(a){return a&&typeof a=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(a)?(M.error(`Site should be a valid Datadog site. ${Ve} ${St}/getting_started/site/.`),!1):!0}function nt(a,n){return a!==void 0&&!_n(a)?(M.error(`${n} Sample Rate should be a number between 0 and 100`),!1):!0}function Tr(a){var n,o,d,f,c,u;if(!a||!a.clientToken){M.error("Client Token is not configured, we will not send any data.");return}if(!(!wr(a.site)||!nt(a.sessionSampleRate,"Session")||!nt(a.telemetrySampleRate,"Telemetry")||!nt(a.telemetryConfigurationSampleRate,"Telemetry Configuration")||!nt(a.telemetryUsageSampleRate,"Telemetry Usage")||!Lt(a.version,"Version")||!Lt(a.env,"Env")||!Lt(a.service,"Service"))){if(a.trackingConsent!==void 0&&!oi(Bt,a.trackingConsent)){M.error(\'Tracking Consent should be either "granted" or "not-granted"\');return}return{beforeSend:a.beforeSend&&ii(a.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:rr(a),sessionSampleRate:(n=a.sessionSampleRate)!==null&&n!==void 0?n:100,telemetrySampleRate:(o=a.telemetrySampleRate)!==null&&o!==void 0?o:20,telemetryConfigurationSampleRate:(d=a.telemetryConfigurationSampleRate)!==null&&d!==void 0?d:5,telemetryUsageSampleRate:(f=a.telemetryUsageSampleRate)!==null&&f!==void 0?f:5,service:a.service||void 0,silentMultipleInit:!!a.silentMultipleInit,allowUntrustedEvents:!!a.allowUntrustedEvents,trackingConsent:(c=a.trackingConsent)!==null&&c!==void 0?c:Bt.GRANTED,trackAnonymousUser:(u=a.trackAnonymousUser)!==null&&u!==void 0?u:!0,storeContextsAcrossPages:!!a.storeContextsAcrossPages,batchBytesLimit:16*ie,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*ke,batchMessagesLimit:50,messageBytesLimit:256*ie,...br(a)}}}function Cr(a){return{session_sample_rate:a.sessionSampleRate,telemetry_sample_rate:a.telemetrySampleRate,telemetry_configuration_sample_rate:a.telemetryConfigurationSampleRate,telemetry_usage_sample_rate:a.telemetryUsageSampleRate,use_before_send:!!a.beforeSend,use_partitioned_cross_site_session_cookie:a.usePartitionedCrossSiteSessionCookie,use_secure_session_cookie:a.useSecureSessionCookie,use_proxy:!!a.proxy,silent_multiple_init:a.silentMultipleInit,track_session_across_subdomains:a.trackSessionAcrossSubdomains,track_anonymous_user:a.trackAnonymousUser,session_persistence:a.sessionPersistence,allow_fallback_to_local_storage:!!a.allowFallbackToLocalStorage,store_contexts_across_pages:!!a.storeContextsAcrossPages,allow_untrusted_events:!!a.allowUntrustedEvents,tracking_consent:a.trackingConsent}}var Dt;(function(a){a.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",a.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(Dt||(Dt={}));const wi=new Set;function Ar(a){Array.isArray(a)&&Ir(a.filter(n=>oi(Dt,n)))}function Ir(a){a.forEach(n=>{wi.add(n)})}function Fr(){return wi}const Ne="?";function ne(a){const n=[];let o=Rt(a,"stack");const d=String(a);return o&&o.startsWith(d)&&(o=o.slice(d.length)),o&&o.split(`\n`).forEach(f=>{const c=Lr(f)||Rr(f)||zr(f)||Nr(f);c&&(!c.func&&c.line&&(c.func=Ne),n.push(c))}),{message:Rt(a,"message"),name:Rt(a,"name"),stack:n}}const Ti="((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\\\w+\\\\.|\\\\/).*?)",Ce="(?::(\\\\d+))",Br=new RegExp(`^\\\\s*at (.*?) ?\\\\(${Ti}${Ce}?${Ce}?\\\\)?\\\\s*$`,"i"),kr=new RegExp(`\\\\((\\\\S*)${Ce}${Ce}\\\\)`);function Lr(a){const n=Br.exec(a);if(!n)return;const o=n[2]&&n[2].indexOf("native")===0,d=n[2]&&n[2].indexOf("eval")===0,f=kr.exec(n[2]);return d&&f&&(n[2]=f[1],n[3]=f[2],n[4]=f[3]),{args:o?[n[2]]:[],column:n[4]?+n[4]:void 0,func:n[1]||Ne,line:n[3]?+n[3]:void 0,url:o?void 0:n[2]}}const Dr=new RegExp(`^\\\\s*at ?${Ti}${Ce}?${Ce}??\\\\s*$`,"i");function Rr(a){const n=Dr.exec(a);if(n)return{args:[],column:n[3]?+n[3]:void 0,func:Ne,line:n[2]?+n[2]:void 0,url:n[1]}}const Pr=/^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;function zr(a){const n=Pr.exec(a);if(n)return{args:[],column:n[4]?+n[4]:void 0,func:n[1]||Ne,line:+n[3],url:n[2]}}const Or=/^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i,Mr=/(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;function Nr(a){const n=Or.exec(a);if(!n)return;const o=n[3]&&n[3].indexOf(" > eval")>-1,d=Mr.exec(n[3]);return o&&d&&(n[3]=d[1],n[4]=d[2],n[5]=void 0),{args:n[2]?n[2].split(","):[],column:n[5]?+n[5]:void 0,func:n[1]||Ne,line:n[4]?+n[4]:void 0,url:n[3]}}function Rt(a,n){if(typeof a!="object"||!a||!(n in a))return;const o=a[n];return typeof o=="string"?o:void 0}function Gr(a,n,o,d){const f=[{url:n,column:d,line:o}],{name:c,message:u}=Yr(a);return{name:c,message:u,stack:f}}const Hr=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\\s\\S]*)$/;function Yr(a){let n,o;return{}.toString.call(a)==="[object String]"&&([,n,o]=Hr.exec(a)),{name:n,message:o}}function rt(a){const o=new Error(a);o.name="HandlingStack";let d;return Re(()=>{const f=ne(o);f.stack=f.stack.slice(2),d=ye(f)}),d}function ye(a){let n=Ci(a);return a.stack.forEach(o=>{const d=o.func==="?"?"<anonymous>":o.func,f=o.args&&o.args.length>0?`(${o.args.join(", ")})`:"",c=o.line?`:${o.line}`:"",u=o.line&&o.column?`:${o.column}`:"";n+=`\n at ${d}${f} @ ${o.url}${c}${u}`}),n}function Ci(a){return`${a.name||"Error"}: ${a.message}`}function ve(a,n,o,{computeHandlingStack:d}={}){let f=a[n];if(typeof f!="function")if(n in a&&n.startsWith("on"))f=le;else return{stop:le};let c=!1;const u=function(){if(c)return f.apply(this,arguments);const s=Array.from(arguments);let p;Re(o,null,[{target:this,parameters:s,onPostCall:g=>{p=g},handlingStack:d?rt("instrumented method"):void 0}]);const _=f.apply(this,s);return p&&Re(p,null,[_]),_};return a[n]=u,{stop:()=>{c=!0,a[n]===u&&(a[n]=f)}}}const Vr=220*ie,$r="$",jr=3;function re(a,n=Vr){const o=we(Object.prototype),d=we(Array.prototype),f=[],c=new WeakMap,u=Pt(a,$r,void 0,f,c),s=JSON.stringify(u);let p=s?s.length:0;if(p>n){Ot(n,"discarded",a);return}for(;f.length>0&&p<n;){const _=f.shift();let g=0;if(Array.isArray(_.source))for(let v=0;v<_.source.length;v++){const U=Pt(_.source[v],_.path,v,f,c);if(U!==void 0?p+=JSON.stringify(U).length:p+=4,p+=g,g=1,p>n){Ot(n,"truncated",a);break}_.target[v]=U}else for(const v in _.source)if(Object.prototype.hasOwnProperty.call(_.source,v)){const U=Pt(_.source[v],_.path,v,f,c);if(U!==void 0&&(p+=JSON.stringify(U).length+g+v.length+jr,g=1),p>n){Ot(n,"truncated",a);break}_.target[v]=U}}return o(),d(),u}function Pt(a,n,o,d,f){const c=Wr(a);if(!c||typeof c!="object")return Kr(c);const u=zt(c);if(u!=="[Object]"&&u!=="[Array]"&&u!=="[Error]")return u;const s=a;if(f.has(s))return`[Reference seen at ${f.get(s)}]`;const p=o!==void 0?`${n}.${o}`:n,_=Array.isArray(c)?[]:{};return f.set(s,p),d.push({source:c,target:_,path:p}),_}function Kr(a){return typeof a=="bigint"?`[BigInt] ${a.toString()}`:typeof a=="function"?`[Function] ${a.name||"unknown"}`:typeof a=="symbol"?`[Symbol] ${a.description||a.toString()}`:a}function zt(a){try{if(a instanceof Event)return qr(a);if(a instanceof RegExp)return`[RegExp] ${a.toString()}`;const o=Object.prototype.toString.call(a).match(/\\[object (.*)\\]/);if(o&&o[1])return`[${o[1]}]`}catch{}return"[Unserializable]"}function qr(a){return{type:a.type,isTrusted:a.isTrusted,currentTarget:a.currentTarget?zt(a.currentTarget):null,target:a.target?zt(a.target):null}}function Wr(a){const n=a;if(n&&typeof n.toJSON=="function")try{return n.toJSON()}catch{}return a}function Ot(a,n,o){M.warn(`The data provided has been ${n} as it is over the limit of ${a} characters:`,o)}const Ai="No stack, consider using an instance of Error";function Ii({stackTrace:a,originalError:n,handlingStack:o,componentStack:d,startClocks:f,nonErrorPrefix:c,source:u,handling:s}){const p=ce(n),_=Jr(a,p,c,n),g=Xr(p,a)?ye(a):Ai,v=p?ki(n,u):void 0,U=a?a.name:void 0,S=Fi(n),E=Bi(n);return{startClocks:f,source:u,handling:s,handlingStack:o,componentStack:d,originalError:n,type:U,message:_,stack:g,causes:v,fingerprint:S,context:E}}function Jr(a,n,o,d){return a!=null&&a.message&&(a!=null&&a.name)?a.message:n?"Empty message":`${o} ${me(re(d))}`}function Xr(a,n){return n===void 0?!1:a?!0:n.stack.length>0&&(n.stack.length>1||n.stack[0].url!==void 0)}function Fi(a){return ce(a)&&"dd_fingerprint"in a?String(a.dd_fingerprint):void 0}function Bi(a){if(a!==null&&typeof a=="object"&&"dd_context"in a)return a.dd_context}function Zr(a){var n;return(n=/@ (.+)/.exec(a))===null||n===void 0?void 0:n[1]}function ce(a){return a instanceof Error||Object.prototype.toString.call(a)==="[object Error]"}function ki(a,n){let o=a;const d=[];for(;ce(o==null?void 0:o.cause)&&d.length<10;){const f=ne(o.cause);d.push({message:o.cause.message,source:n,type:f==null?void 0:f.name,stack:ye(f)}),o=o.cause}return d.length?d:void 0}const J={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function Qr(a){const n=(f,c)=>{const u=Ii({stackTrace:f,originalError:c,startClocks:ae(),nonErrorPrefix:"Uncaught",source:J.SOURCE,handling:"unhandled"});a.notify(u)},{stop:o}=es(n),{stop:d}=ts(n);return{stop:()=>{o(),d()}}}function es(a){return ve(window,"onerror",({parameters:[n,o,d,f,c]})=>{let u;ce(c)?u=ne(c):u=Gr(n,o,d,f),a(u,c??n)})}function ts(a){return ve(window,"onunhandledrejection",({parameters:[n]})=>{const o=n.reason||"Empty reason",d=ne(o);a(d,o)})}function is(a){const n={version:"6.5.0",onReady(o){o()},...a};return Object.defineProperty(n,"_setDebug",{get(){return wn},enumerable:!1}),n}function ns(a,n,o){const d=a[n];d&&!d.q&&d.version&&M.warn("SDK is loaded more than once. This is unsupported and might have unexpected behavior."),a[n]=o,d&&d.q&&d.q.forEach(f=>ii(f,"onReady callback threw an error:")())}function Li(a,n){n.silentMultipleInit||M.error(`${a} is already initialized.`)}function Se(a,n,o,d,f){return Mt(a,n,[o],d,f)}function Mt(a,n,o,d,{once:f,capture:c,passive:u}={}){const s=D(U=>{!U.isTrusted&&!U.__ddIsTrusted&&!a.allowUntrustedEvents||(f&&v(),d(U))}),p=u?{capture:c,passive:u}:c,_=window.EventTarget&&n instanceof EventTarget?window.EventTarget.prototype:n,g=Ue(_,"addEventListener");o.forEach(U=>g.call(n,U,s,p));function v(){const U=Ue(_,"removeEventListener");o.forEach(S=>U.call(n,S,s,p))}return{stop:v}}const st={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function rs(a,n){const o=[];n.includes(st.cspViolation)&&o.push(os(a));const d=n.filter(f=>f!==st.cspViolation);return d.length&&o.push(ss(d)),fi(...o)}function ss(a){return new G(n=>{if(!window.ReportingObserver)return;const o=D((f,c)=>f.forEach(u=>n.notify(as(u)))),d=new window.ReportingObserver(o,{types:a,buffered:!0});return d.observe(),()=>{d.disconnect()}})}function os(a){return new G(n=>{const{stop:o}=Se(a,document,"securitypolicyviolation",d=>{n.notify(ds(d))});return o})}function as(a){const{type:n,body:o}=a;return Di({type:o.id,message:`${n}: ${o.message}`,originalError:a,stack:Ri(o.id,o.message,o.sourceFile,o.lineNumber,o.columnNumber)})}function ds(a){const n=`\'${a.blockedURI}\' blocked by \'${a.effectiveDirective}\' directive`;return Di({type:a.effectiveDirective,message:`${st.cspViolation}: ${n}`,originalError:a,csp:{disposition:a.disposition},stack:Ri(a.effectiveDirective,a.originalPolicy?`${n} of the policy "${Fn(a.originalPolicy,100,"...")}"`:"no policy",a.sourceFile,a.lineNumber,a.columnNumber)})}function Di(a){return{startClocks:ae(),source:J.REPORT,handling:"unhandled",...a}}function Ri(a,n,o,d,f){return o?ye({name:a,message:n,stack:[{func:"?",url:o,line:d??void 0,column:f??void 0}]}):void 0}function Pi(a,n){const o=window.__ddBrowserSdkExtensionCallback;o&&o({type:a,payload:n})}function zi(a){return a===null?"null":Array.isArray(a)?"array":typeof a}function ot(a,n,o=ls()){if(n===void 0)return a;if(typeof n!="object"||n===null)return n;if(n instanceof Date)return new Date(n.getTime());if(n instanceof RegExp){const f=n.flags||[n.global?"g":"",n.ignoreCase?"i":"",n.multiline?"m":"",n.sticky?"y":"",n.unicode?"u":""].join("");return new RegExp(n.source,f)}if(o.hasAlreadyBeenSeen(n))return;if(Array.isArray(n)){const f=Array.isArray(a)?a:[];for(let c=0;c<n.length;++c)f[c]=ot(f[c],n[c],o);return f}const d=zi(a)==="object"?a:{};for(const f in n)Object.prototype.hasOwnProperty.call(n,f)&&(d[f]=ot(d[f],n[f],o));return d}function Oi(a){return ot(void 0,a)}function Ae(...a){let n;for(const o of a)o!=null&&(n=ot(n,o));return n}function ls(){if(typeof WeakSet<"u"){const n=new WeakSet;return{hasAlreadyBeenSeen(o){const d=n.has(o);return d||n.add(o),d}}}const a=[];return{hasAlreadyBeenSeen(n){const o=a.indexOf(n)>=0;return o||a.push(n),o}}}function fs(){var a;const n=window.navigator;return{status:n.onLine?"connected":"not_connected",interfaces:n.connection&&n.connection.type?[n.connection.type]:void 0,effective_type:(a=n.connection)===null||a===void 0?void 0:a.effectiveType}}function cs(a){const n=new Set;return a.forEach(o=>n.add(o)),Array.from(n)}function Mi(a,n){const o=a.indexOf(n);o>=0&&a.splice(o,1)}const hs=500;function Ni(){const a=[];return{add:f=>{a.push(f)>hs&&a.splice(0,1)},remove:f=>{Mi(a,f)},drain:f=>{a.forEach(c=>c(f)),a.length=0}}}const be={log:"log",configuration:"configuration",usage:"usage"},us=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],ps=[cr];let Gi=Ni(),Ie=a=>{Gi.add(()=>Ie(a))};function _s(a,n){let o;const d=new G,f=new Set,c=!ps.includes(n.site)&&$e(n.telemetrySampleRate),u={[be.log]:c,[be.configuration]:c&&$e(n.telemetryConfigurationSampleRate),[be.usage]:c&&$e(n.telemetryUsageSampleRate)},s=gs();Ie=_=>{const g=me(_);if(u[_.type]&&f.size<n.maxTelemetryEventsPerPage&&!f.has(g)){const v=p(a,_,s);d.notify(v),Pi("telemetry",v),f.add(g)}},En(Yi);function p(_,g,v){return Ae({type:"telemetry",date:oe(),service:_,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:Ae(g,{runtime_env:v,connectivity:fs(),sdk_setup:"npm"}),experimental_features:Array.from(Fr())},o!==void 0?o():{})}return{setContextProvider:_=>{o=_},observable:d,enabled:c}}function gs(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function ms(){Gi.drain()}function ys(a){return a.site===lr}function Hi(a,n){Ut(O.debug,a,n),Ie({type:be.log,message:a,status:"debug",...n})}function Yi(a,n){Ie({type:be.log,status:"error",...bs(a),...n})}function vs(a){Ie({type:be.configuration,configuration:a})}function Ss(a){Ie({type:be.usage,usage:a})}function bs(a){if(ce(a)){const n=ne(a);return{error:{kind:n.name,stack:ye(xs(n))},message:n.message}}return{error:{stack:Ai},message:`Uncaught ${me(a)}`}}function xs(a){return a.stack=a.stack.filter(n=>!n.url||us.some(o=>n.url.startsWith(o))),a}const Ge=1/0,Us=ue;let He=null;const at=new Set;function Es(){at.forEach(a=>a())}function ws({expireDelay:a,maxEntries:n}){let o=[];const d=[];He||(He=Et(()=>Es(),Us));const f=()=>{const S=je()-a;for(;o.length>0&&o[o.length-1].endTime<S;){const E=o.pop();E&&d.push(E.startTime)}};at.add(f);function c(S,E){const e={value:S,startTime:E,endTime:Ge,remove:()=>{Mi(o,e)},close:t=>{e.endTime=t}};return n&&o.length>=n&&o.pop(),o.unshift(e),e}function u(S=Ge,E={returnInactive:!1}){for(const e of o)if(e.startTime<=S){if(E.returnInactive||S<=e.endTime)return e.value;break}}function s(S){const E=o[0];E&&E.endTime===Ge&&E.close(S)}function p(S=Ge,E=0){const e=Sn(S,E);return o.filter(t=>t.startTime<=e&&S<=t.endTime).map(t=>t.value)}function _(){return o.map(({startTime:S,endTime:E,value:e})=>({startTime:S,endTime:E===Ge?"Infinity":E,value:e}))}function g(){return d}function v(){o=[]}function U(){at.delete(f),at.size===0&&He&&(li(He),He=null)}return{add:c,find:u,closeActive:s,findAll:p,reset:v,stop:U,getAllEntries:_,getDeletedEntries:g}}const Ts=ue,Cs=At;function As(a,n,o,d){const f=new G,c=new G,u=sr(a.sessionStoreStrategyType,a,n,o),s=ws({expireDelay:Cs});u.renewObservable.subscribe(()=>{s.add(p(),je()),f.notify()}),u.expireObservable.subscribe(()=>{c.notify(),s.closeActive(je())}),u.expandOrRenewSession(),s.add(p(),yn().relative),d.observable.subscribe(()=>{d.isGranted()?u.expandOrRenewSession():u.expire()}),Is(a,()=>{d.isGranted()&&u.expandOrRenewSession()}),Fs(a,()=>u.expandSession()),Bs(a,()=>u.restartSession());function p(){return{id:u.getSession().id,trackingType:u.getSession()[n],isReplayForced:!!u.getSession().forcedReplay,anonymousId:u.getSession().anonymousId}}return{findSession:(_,g)=>s.find(_,g),renewObservable:f,expireObservable:c,sessionStateUpdateObservable:u.sessionStateUpdateObservable,expire:u.expire,updateSessionState:u.updateSessionState}}function Is(a,n){Mt(a,window,["click","touchstart","keydown","scroll"],n,{capture:!0,passive:!0})}function Fs(a,n){const o=()=>{document.visibilityState==="visible"&&n()};Se(a,document,"visibilitychange",o),Et(o,Ts)}function Bs(a,n){Se(a,window,"resume",n,{capture:!0})}function Vi(a){return a>=500}function ks(a){try{return a.clone()}catch{return}}const Ls=80*ie,Ds=32,$i=3*si,Rs=ue,ji=ke;function Ki(a,n,o,d,f){n.transportStatus===0&&n.queuedPayloads.size()===0&&n.bandwidthMonitor.canHandle(a)?Wi(a,n,o,{onSuccess:()=>Ji(0,n,o,d,f),onFailure:()=>{n.queuedPayloads.enqueue(a),qi(n,o,d,f)}}):n.queuedPayloads.enqueue(a)}function qi(a,n,o,d){a.transportStatus===2&&Pe(()=>{const f=a.queuedPayloads.first();Wi(f,a,n,{onSuccess:()=>{a.queuedPayloads.dequeue(),a.currentBackoffTime=ji,Ji(1,a,n,o,d)},onFailure:()=>{a.currentBackoffTime=Math.min(Rs,a.currentBackoffTime*2),qi(a,n,o,d)}})},a.currentBackoffTime)}function Wi(a,n,o,{onSuccess:d,onFailure:f}){n.bandwidthMonitor.add(a),o(a,c=>{n.bandwidthMonitor.remove(a),Ps(c)?(n.transportStatus=n.bandwidthMonitor.ongoingRequestCount>0?1:2,a.retry={count:a.retry?a.retry.count+1:1,lastFailureStatus:c.status},f()):(n.transportStatus=0,d())})}function Ji(a,n,o,d,f){a===0&&n.queuedPayloads.isFull()&&!n.queueFullReported&&(f({message:`Reached max ${d} events size queued for upload: ${$i/si}MiB`,source:J.AGENT,startClocks:ae()}),n.queueFullReported=!0);const c=n.queuedPayloads;for(n.queuedPayloads=Xi();c.size()>0;)Ki(c.dequeue(),n,o,d,f)}function Ps(a){return a.type!=="opaque"&&(a.status===0&&!navigator.onLine||a.status===408||a.status===429||Vi(a.status))}function zs(){return{transportStatus:0,currentBackoffTime:ji,bandwidthMonitor:Os(),queuedPayloads:Xi(),queueFullReported:!1}}function Xi(){const a=[];return{bytesCount:0,enqueue(n){this.isFull()||(a.push(n),this.bytesCount+=n.bytesCount)},first(){return a[0]},dequeue(){const n=a.shift();return n&&(this.bytesCount-=n.bytesCount),n},size(){return a.length},isFull(){return this.bytesCount>=$i}}}function Os(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(a){return this.ongoingRequestCount===0||this.ongoingByteCount+a.bytesCount<=Ls&&this.ongoingRequestCount<Ds},add(a){this.ongoingRequestCount+=1,this.ongoingByteCount+=a.bytesCount},remove(a){this.ongoingRequestCount-=1,this.ongoingByteCount-=a.bytesCount}}}function Ms(a,n,o){const d=zs(),f=(c,u)=>Hs(a,n,c,u);return{send:c=>{Ki(c,d,f,a.trackType,o)},sendOnExit:c=>{Ns(a,n,c)}}}function Ns(a,n,o){if(!!navigator.sendBeacon&&o.bytesCount<n)try{const c=a.build("beacon",o);if(navigator.sendBeacon(c,o.data))return}catch(c){Gs(c)}const f=a.build("xhr",o);Nt(f,o.data)}let Zi=!1;function Gs(a){Zi||(Zi=!0,Yi(a))}function Hs(a,n,o,d){if(Ys()&&o.bytesCount<n){const c=a.build("fetch",o);fetch(c,{method:"POST",body:o.data,keepalive:!0,mode:"cors"}).then(D(u=>d==null?void 0:d({status:u.status,type:u.type})),D(()=>{const u=a.build("xhr",o);Nt(u,o.data,d)}))}else{const c=a.build("xhr",o);Nt(c,o.data,d)}}function Ys(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function Nt(a,n,o){const d=new XMLHttpRequest;d.open("POST",a,!0),n instanceof Blob&&d.setRequestHeader("Content-Type",n.type),Se({allowUntrustedEvents:!0},d,"loadend",()=>{o==null||o({status:d.status})},{once:!0}),d.send(n)}function Gt(){const a=Vs();if(a)return{getCapabilities(){var n;return JSON.parse(((n=a.getCapabilities)===null||n===void 0?void 0:n.call(a))||"[]")},getPrivacyLevel(){var n;return(n=a.getPrivacyLevel)===null||n===void 0?void 0:n.call(a)},getAllowedWebViewHosts(){return JSON.parse(a.getAllowedWebViewHosts())},send(n,o,d){const f=d?{id:d}:void 0;a.send(JSON.stringify({eventType:n,event:o,view:f}))}}}function dt(a){var n;a===void 0&&(a=(n=de().location)===null||n===void 0?void 0:n.hostname);const o=Gt();return!!o&&o.getAllowedWebViewHosts().some(d=>a===d||a.endsWith(`.${d}`))}function Vs(){return de().DatadogEventBridge}const lt={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function $s(a){return new G(n=>{const{stop:o}=Mt(a,window,["visibilitychange","freeze"],f=>{f.type==="visibilitychange"&&document.visibilityState==="hidden"?n.notify({reason:lt.HIDDEN}):f.type==="freeze"&&n.notify({reason:lt.FROZEN})},{capture:!0}),d=Se(a,window,"beforeunload",()=>{n.notify({reason:lt.UNLOADING})}).stop;return()=>{o(),d()}})}function js(a){return Je(lt).includes(a)}function Ks({encoder:a,request:n,flushController:o,messageBytesLimit:d}){let f={};const c=o.flushObservable.subscribe(v=>g(v));function u(v,U,S){o.notifyBeforeAddMessage(U),S!==void 0?(f[S]=v,o.notifyAfterAddMessage()):a.write(a.isEmpty?v:`\n${v}`,E=>{o.notifyAfterAddMessage(E-U)})}function s(v){return v!==void 0&&f[v]!==void 0}function p(v){const U=f[v];delete f[v];const S=a.estimateEncodedBytesCount(U);o.notifyAfterRemoveMessage(S)}function _(v,U){const S=me(v),E=a.estimateEncodedBytesCount(S);if(E>=d){M.warn(`Discarded a message whose size was bigger than the maximum allowed size ${d}KB. ${Ve} ${ti}/#technical-limitations`);return}s(U)&&p(U),u(S,E,U)}function g(v){const U=Je(f).join(`\n`);f={};const S=js(v.reason),E=S?n.sendOnExit:n.send;if(S&&a.isAsync){const e=a.finishSync();e.outputBytesCount&&E(Qi(e));const t=[e.pendingData,U].filter(Boolean).join(`\n`);t&&E({data:t,bytesCount:xt(t)})}else U&&a.write(a.isEmpty?U:`\n${U}`),a.finish(e=>{E(Qi(e))})}return{flushController:o,add:_,upsert:_,stop:c.unsubscribe}}function Qi(a){let n;return typeof a.output=="string"?n=a.output:n=new Blob([a.output],{type:"text/plain"}),{data:n,bytesCount:a.outputBytesCount,encoding:a.encoding}}function qs({messagesLimit:a,bytesLimit:n,durationLimit:o,pageExitObservable:d,sessionExpireObservable:f}){const c=d.subscribe(E=>g(E.reason)),u=f.subscribe(()=>g("session_expire")),s=new G(()=>()=>{c.unsubscribe(),u.unsubscribe()});let p=0,_=0;function g(E){if(_===0)return;const e=_,t=p;_=0,p=0,S(),s.notify({reason:E,messagesCount:e,bytesCount:t})}let v;function U(){v===void 0&&(v=Pe(()=>{g("duration_limit")},o))}function S(){di(v),v=void 0}return{flushObservable:s,get messagesCount(){return _},notifyBeforeAddMessage(E){p+E>=n&&g("bytes_limit"),_+=1,p+=E,U()},notifyAfterAddMessage(E=0){p+=E,_>=a?g("messages_limit"):p>=n&&g("bytes_limit")},notifyAfterRemoveMessage(E){p-=E,_-=1,_===0&&S()}}}function en(a,n,o,d,f,c,u=Ks){const s=_(a,n),p=o&&_(a,o);function _(g,{endpoint:v,encoder:U}){return u({encoder:U,request:Ms(v,g.batchBytesLimit,d),flushController:qs({messagesLimit:g.batchMessagesLimit,bytesLimit:g.batchBytesLimit,durationLimit:g.flushTimeout,pageExitObservable:f,sessionExpireObservable:c}),messageBytesLimit:g.messageBytesLimit})}return{flushObservable:s.flushController.flushObservable,add(g,v=!0){s.add(g),p&&v&&p.add(o.transformMessage?o.transformMessage(g):g)},upsert:(g,v)=>{s.upsert(g,v),p&&p.upsert(o.transformMessage?o.transformMessage(g):g,v)},stop:()=>{s.stop(),p&&p.stop()}}}function ft(){let a="",n=0;return{isAsync:!1,get isEmpty(){return!a},write(o,d){const f=xt(o);n+=f,a+=o,d&&d(f)},finish(o){o(this.finishSync())},finishSync(){const o={output:a,outputBytesCount:n,rawBytesCount:n,pendingData:""};return a="",n=0,o},estimateEncodedBytesCount(o){return o.length}}}class Ws{constructor(){this.callbacks={}}notify(n,o){const d=this.callbacks[n];d&&d.forEach(f=>f(o))}subscribe(n,o){return this.callbacks[n]||(this.callbacks[n]=[]),this.callbacks[n].push(o),{unsubscribe:()=>{this.callbacks[n]=this.callbacks[n].filter(d=>o!==d)}}}}function Js(a,n,o){let d=0,f=!1;return{isLimitReached(){if(d===0&&Pe(()=>{d=0},ue),d+=1,d<=n||f)return f=!1,!1;if(d===n+1){f=!0;try{o({message:`Reached max number of ${a}s by minute: ${n}`,source:J.AGENT,startClocks:ae()})}finally{f=!1}}return!0}}}let Ht;const Yt=new WeakMap;function Xs(a){return Ht||(Ht=Zs(a)),Ht}function Zs(a){return new G(n=>{const{stop:o}=ve(XMLHttpRequest.prototype,"open",Qs),{stop:d}=ve(XMLHttpRequest.prototype,"send",c=>{eo(c,a,n)},{computeHandlingStack:!0}),{stop:f}=ve(XMLHttpRequest.prototype,"abort",to);return()=>{o(),d(),f()}})}function Qs({target:a,parameters:[n,o]}){Yt.set(a,{state:"open",method:String(n).toUpperCase(),url:kt(String(o))})}function eo({target:a,handlingStack:n},o,d){const f=Yt.get(a);if(!f)return;const c=f;c.state="start",c.startClocks=ae(),c.isAborted=!1,c.xhr=a,c.handlingStack=n;let u=!1;const{stop:s}=ve(a,"onreadystatechange",()=>{a.readyState===XMLHttpRequest.DONE&&p()}),p=()=>{if(_(),s(),u)return;u=!0;const g=f;g.state="complete",g.duration=vn(c.startClocks.timeStamp,oe()),g.status=a.status,d.notify(Un(g))},{stop:_}=Se(o,a,"loadend",p);d.notify(c)}function to({target:a}){const n=Yt.get(a);n&&(n.isAborted=!0)}let Vt;function tn(){return Vt||(Vt=io()),Vt}function io(){return new G(a=>{if(!window.fetch)return;const{stop:n}=ve(window,"fetch",o=>no(o,a),{computeHandlingStack:!0});return n})}function no({parameters:a,onPostCall:n,handlingStack:o},d){const[f,c]=a;let u=c&&c.method;u===void 0&&f instanceof Request&&(u=f.method);const s=u!==void 0?String(u).toUpperCase():"GET",p=f instanceof Request?f.url:kt(String(f)),_=ae(),g={state:"start",init:c,input:f,method:s,startClocks:_,url:p,handlingStack:o};d.notify(g),a[0]=g.input,a[1]=g.init,n(v=>ro(d,v,g))}function ro(a,n,o){const d=o;function f(c){d.state="resolve",Object.assign(d,c),a.notify(d)}n.then(D(c=>{f({response:c,responseType:c.type,status:c.status,isAborted:!1})}),D(c=>{var u,s;f({status:0,isAborted:((s=(u=d.init)===null||u===void 0?void 0:u.signal)===null||s===void 0?void 0:s.aborted)||c instanceof DOMException&&c.code===DOMException.ABORT_ERR,error:c})}))}let $t={};function so(a){const n=a.map(o=>($t[o]||($t[o]=oo(o)),$t[o]));return fi(...n)}function oo(a){return new G(n=>{const o=te[a];return te[a]=(...d)=>{o.apply(console,d);const f=rt("console error");Re(()=>{n.notify(ao(d,a,f))})},()=>{te[a]=o}})}function ao(a,n,o){const d=a.map(c=>lo(c)).join(" ");let f;if(n===O.error){const c=a.find(ce);f={stack:c?ye(ne(c)):void 0,fingerprint:Fi(c),causes:c?ki(c,"console"):void 0,startClocks:ae(),message:d,source:J.CONSOLE,handling:"handled",handlingStack:o,context:Bi(c)}}return{api:n,message:d,error:f,handlingStack:o}}function lo(a){return typeof a=="string"?re(a):ce(a)?Ci(ne(a)):me(re(a),void 0,2)}function fo(a){const n=zi(a)==="object";return n||M.error("Unsupported context:",a),n}function jt(a,n,o){const d={...a};for(const[f,{required:c,type:u}]of Object.entries(n))u==="string"&&f in d&&(d[f]=String(d[f])),c&&!(f in a)&&M.warn(`The property ${f} of ${o} is required; context will not be sent to the intake.`);return d}function ct(a="",{customerDataTracker:n,propertiesConfig:o={}}={}){let d={};const f=new G,c={getContext:()=>Oi(d),setContext:u=>{fo(u)?(d=re(jt(u,o,a)),n==null||n.updateCustomerData(d)):c.clearContext(),f.notify()},setContextProperty:(u,s)=>{d=re(jt({...d,[u]:s},o,a)),n==null||n.updateCustomerData(d),f.notify()},removeContextProperty:u=>{delete d[u],n==null||n.updateCustomerData(d),jt(d,o,a),f.notify()},clearContext:()=>{d={},n==null||n.resetCustomerData(),f.notify()},changeObservable:f};return c}const co="_dd_c",ho=[];function Kt(a,n,o,d){const f=uo(o,d);ho.push(Se(a,window,"storage",({key:_})=>{f===_&&u()})),n.changeObservable.subscribe(s);const c=Ae(p(),n.getContext());De(c)||n.setContext(c);function u(){n.setContext(p())}function s(){localStorage.setItem(f,JSON.stringify(n.getContext()))}function p(){const _=localStorage.getItem(f);return _?JSON.parse(_):{}}}function uo(a,n){return`${co}_${a}_${n}`}const po=3*ie,_o=16*ie,go=200;function mo(a=2){const n=new Map;let o=!1;function d(f=0){if(o||a===0)return;const c=a===2?po:_o;let u=f;n.forEach(s=>{u+=s.getBytesCount()}),u>c&&(yo(c),o=!0)}return{createDetachedTracker:()=>{const f=nn(()=>d(f.getBytesCount()));return f},getOrCreateTracker:f=>(n.has(f)||n.set(f,nn(d)),n.get(f)),setCompressionStatus:f=>{a===0&&(a=f,d())},getCompressionStatus:()=>a,stop:()=>{n.forEach(f=>f.stop()),n.clear()}}}function nn(a){let n=0;const{throttled:o,cancel:d}=ci(c=>{n=xt(me(c)),a()},go),f=()=>{d(),n=0};return{updateCustomerData:c=>{De(c)?f():o(c)},resetCustomerData:f,getBytesCount:()=>n,stop:()=>{d()}}}function yo(a){M.warn(`Customer data exceeds the recommended ${a/ie}KiB threshold. ${Ve} ${ti}/#customer-data-exceeds-the-recommended-threshold-warning`)}function vo(a,n,o){const d=a.getReader(),f=[];let c=0;u();function u(){d.read().then(D(p=>{if(p.done){s();return}f.push(p.value),c+=p.value.length,c>o.bytesLimit?s():u()}),D(p=>n(p)))}function s(){d.cancel().catch(le);let p,_;{let g;if(f.length===1)g=f[0];else{g=new Uint8Array(c);let v=0;f.forEach(U=>{g.set(U,v),v+=U.length})}p=g.slice(0,o.bytesLimit),_=g.length>o.bytesLimit}n(void 0,p,_)}}const So="datadog-synthetics-public-id",bo="datadog-synthetics-result-id",xo="datadog-synthetics-injects-rum";function rn(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||pe(xo))}function Uo(){const a=window._DATADOG_SYNTHETICS_PUBLIC_ID||pe(So);return typeof a=="string"?a:void 0}function Eo(){const a=window._DATADOG_SYNTHETICS_RESULT_ID||pe(bo);return typeof a=="string"?a:void 0}function ht(a,n,o){const d=o.getHandler(),f=Array.isArray(d)?d:[d];return sn[a]>=sn[o.getLevel()]&&f.includes(n)}const B={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},sn={[B.ok]:0,[B.debug]:1,[B.info]:2,[B.notice]:4,[B.warn]:5,[B.error]:6,[B.critical]:7,[B.alert]:8,[B.emerg]:9};function ut(a,{includeMessage:n=!1}={}){return{stack:a.stack,kind:a.type,message:n?a.message:void 0,causes:a.causes,fingerprint:a.fingerprint,handling:a.handling}}var wo=function(a,n,o,d){var f=arguments.length,c=f<3?n:d===null?d=Object.getOwnPropertyDescriptor(n,o):d,u;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")c=Reflect.decorate(a,n,o,d);else for(var s=a.length-1;s>=0;s--)(u=a[s])&&(c=(f<3?u(c):f>3?u(n,o,c):u(n,o))||c);return f>3&&c&&Object.defineProperty(n,o,c),c};const Ye={console:"console",http:"http",silent:"silent"},To=Object.keys(B);let Q=class{constructor(n,o,d,f=Ye.http,c=B.debug,u={}){this.handleLogStrategy=n,this.handlerType=f,this.level=c,this.contextManager=ct("logger",{customerDataTracker:o}),this.contextManager.setContext(u),d&&this.contextManager.setContextProperty("logger",{name:d})}logImplementation(n,o,d=B.info,f,c){const u=re(o);let s;if(f!=null){const p=Ii({stackTrace:ce(f)?ne(f):void 0,originalError:f,nonErrorPrefix:"Provided",source:J.LOGGER,handling:"handled",startClocks:ae()});s=Ae({error:ut(p,{includeMessage:!0})},u)}else s=u;this.handleLogStrategy({message:re(n),context:s,status:d},this,c)}log(n,o,d=B.info,f){let c;ht(d,Ye.http,this)&&(c=rt("log")),this.logImplementation(n,o,d,f,c)}setContext(n){this.contextManager.setContext(n)}getContext(){return this.contextManager.getContext()}setContextProperty(n,o){this.contextManager.setContextProperty(n,o)}removeContextProperty(n){this.contextManager.removeContextProperty(n)}clearContext(){this.contextManager.clearContext()}setHandler(n){this.handlerType=n}getHandler(){return this.handlerType}setLevel(n){this.level=n}getLevel(){return this.level}};wo([Tn],Q.prototype,"logImplementation",null),Q.prototype.ok=se(B.ok),Q.prototype.debug=se(B.debug),Q.prototype.info=se(B.info),Q.prototype.notice=se(B.notice),Q.prototype.warn=se(B.warn),Q.prototype.error=se(B.error),Q.prototype.critical=se(B.critical),Q.prototype.alert=se(B.alert),Q.prototype.emerg=se(B.emerg);function se(a){return function(n,o,d){let f;ht(a,Ye.http,this)&&(f=rt("log")),this.logImplementation(n,o,a,d,f)}}function Co(a,n,o){return{view:{referrer:document.referrer,url:window.location.href},context:a.getContext(),user:n.getContext(),account:o.getContext()}}const Ao=32*ie;function Io(a){a.usePciIntake===!0&&a.site&&a.site!=="datadoghq.com"&&M.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");const n=Tr(a),o=on(a.forwardConsoleLogs,Je(O),"Forward Console Logs"),d=on(a.forwardReports,Je(st),"Forward Reports");if(!(!n||!o||!d))return a.forwardErrorsToLogs&&!o.includes(O.error)&&o.push(O.error),{forwardErrorsToLogs:a.forwardErrorsToLogs!==!1,forwardConsoleLogs:o,forwardReports:d,requestErrorResponseLengthLimit:Ao,...n}}function on(a,n,o){if(a===void 0)return[];if(!(a==="all"||Array.isArray(a)&&a.every(d=>n.includes(d)))){M.error(`${o} should be "all" or an array with allowed values "${n.join(\'", "\')}"`);return}return a==="all"?n:cs(a)}function Fo(a){const n=Cr(a);return{forward_errors_to_logs:a.forwardErrorsToLogs,forward_console_logs:a.forwardConsoleLogs,forward_reports:a.forwardReports,use_pci_intake:a.usePciIntake,...n}}function Bo(a,n,o){const d=Ni();let f,c;const u=n.observable.subscribe(s);function s(){if(!c||!f||!n.isGranted())return;u.unsubscribe();const p=o(f,c);d.drain(p)}return{init(p){if(!p){M.error("Missing configuration");return}if(Ar(p.enableExperimentalFeatures),dt()&&(p=ko(p)),f=p,c){Li("DD_LOGS",p);return}const _=Io(p);_&&(c=_,tn().subscribe(le),n.tryToInit(_.trackingConsent),s())},get initConfiguration(){return f},getInternalContext:le,handleLog(p,_,g,v=a(),U=oe()){d.add(S=>S.handleLog(p,_,g,v,U))}}}function ko(a){return{...a,clientToken:"empty"}}const qt="logs";function Lo(a){const n=mo(),o=ct("global context",{customerDataTracker:n.getOrCreateTracker(2)}),d=ct("user",{customerDataTracker:n.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),f=ct("account",{customerDataTracker:n.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),c=or();function u(){return Co(o,d,f)}let s=Bo(u,c,(g,v)=>{g.storeContextsAcrossPages&&(Kt(v,o,qt,2),Kt(v,d,qt,1),Kt(v,f,qt,4));const U=a(g,v,u,c);return s=Do(g,U),U});const p={},_=new Q((...g)=>s.handleLog(...g),n.createDetachedTracker());return is({logger:_,init:D(g=>s.init(g)),setTrackingConsent:D(g=>{c.update(g),Ss({feature:"set-tracking-consent",tracking_consent:g})}),getGlobalContext:D(()=>o.getContext()),setGlobalContext:D(g=>o.setContext(g)),setGlobalContextProperty:D((g,v)=>o.setContextProperty(g,v)),removeGlobalContextProperty:D(g=>o.removeContextProperty(g)),clearGlobalContext:D(()=>o.clearContext()),createLogger:D((g,v={})=>(p[g]=new Q((...U)=>s.handleLog(...U),n.createDetachedTracker(),re(g),v.handler,v.level,re(v.context)),p[g])),getLogger:D(g=>p[g]),getInitConfiguration:D(()=>Oi(s.initConfiguration)),getInternalContext:D(g=>s.getInternalContext(g)),setUser:D(d.setContext),getUser:D(d.getContext),setUserProperty:D(d.setContextProperty),removeUserProperty:D(d.removeContextProperty),clearUser:D(d.clearContext),setAccount:D(f.setContext),getAccount:D(f.getContext),setAccountProperty:D(f.setContextProperty),removeAccountProperty:D(f.removeContextProperty),clearAccount:D(f.clearContext)})}function Do(a,n){return{init:o=>{Li("DD_LOGS",o)},initConfiguration:a,...n}}const Ro="logs";function Po(a,n){const o=As(a,Ro,d=>Oo(a,d),n);return{findTrackedSession:(d,f={returnInactive:!1})=>{const c=o.findSession(d,f);return c&&c.trackingType==="1"?{id:c.id,anonymousId:c.anonymousId}:void 0},expireObservable:o.expireObservable}}function zo(a){const o=an(a)==="1"?{}:void 0;return{findTrackedSession:()=>o,expireObservable:new G}}function an(a){return $e(a.sessionSampleRate)?"1":"0"}function Oo(a,n){const o=Mo(n)?n:an(a);return{trackingType:o,isTracked:o==="1"}}function Mo(a){return a==="0"||a==="1"}let dn=!1;function pt(a){const n=window;if(rn()){const d=o(n.DD_RUM_SYNTHETICS);return!d&&!dn&&(dn=!0,Hi("Logs sent before RUM is injected by the synthetics worker",{testId:Uo(),resultId:Eo()})),d}return o(n.DD_RUM);function o(d){if(d&&d.getInternalContext)return d.getInternalContext(a)}}function No(a,n,o,d,f){const c=To.concat(["custom"]),u={};c.forEach(s=>{u[s]=Js(s,n.eventRateLimiterThreshold,f)}),o.subscribe(0,({rawLogsEvent:s,messageContext:p=void 0,savedCommonContext:_=void 0,domainContext:g})=>{var v,U;const S=bn(s.date),E=a.findTrackedSession(S);if(!a.findTrackedSession(S,{returnInactive:!0}))return;const t=_||d();let r;!De(t.account)&&t.account.id&&(r=t.account),E&&E.anonymousId&&!t.user.anonymous_id&&(t.user.anonymous_id=E.anonymousId);const l=Ae({service:n.service,session_id:E?E.id:void 0,session:E?{id:E.id}:void 0,usr:De(t.user)?void 0:t.user,account:r,view:t.view},t.context,pt(S),s,p);((v=n.beforeSend)===null||v===void 0?void 0:v.call(n,l,g))===!1||l.origin!==J.AGENT&&((U=u[l.status])!==null&&U!==void 0?U:u.custom).isLimitReached()||o.notify(1,l)})}const Go={[O.log]:B.info,[O.debug]:B.debug,[O.info]:B.info,[O.warn]:B.warn,[O.error]:B.error};function Ho(a,n){const o=so(a.forwardConsoleLogs).subscribe(d=>{var f;const c={rawLogsEvent:{date:oe(),message:d.message,origin:J.CONSOLE,error:d.error&&ut(d.error),status:Go[d.api]},messageContext:(f=d.error)===null||f===void 0?void 0:f.context,domainContext:{handlingStack:d.handlingStack}};n.notify(0,c)});return{stop:()=>{o.unsubscribe()}}}function Yo(a,n){const o=rs(a,a.forwardReports).subscribe(d=>{let f=d.message,c;const u=d.originalError.type==="deprecation"?B.warn:B.error;u===B.error?c=ut(d):d.stack&&(f+=` Found in ${Zr(d.stack)}`),n.notify(0,{rawLogsEvent:{date:oe(),message:f,origin:J.REPORT,error:c,status:u}})});return{stop:()=>{o.unsubscribe()}}}function Vo(a,n){if(!a.forwardErrorsToLogs)return{stop:le};const o=Xs(a).subscribe(c=>{c.state==="complete"&&f("xhr",c)}),d=tn().subscribe(c=>{c.state==="resolve"&&f("fetch",c)});function f(c,u){!Er(u.url)&&(qo(u)||Vi(u.status))&&("xhr"in u?$o(u.xhr,a,s):u.response?Ko(u.response,a,s):u.error&&jo(u.error,a,s));function s(p){const _={isAborted:u.isAborted,handlingStack:u.handlingStack};n.notify(0,{rawLogsEvent:{message:`${Wo(c)} error ${u.method} ${u.url}`,date:u.startClocks.timeStamp,error:{stack:p||"Failed to load",handling:void 0},http:{method:u.method,status_code:u.status,url:u.url},status:B.error,origin:J.NETWORK},domainContext:_})}}return{stop:()=>{o.unsubscribe(),d.unsubscribe()}}}function $o(a,n,o){typeof a.response=="string"?o(Wt(a.response,n)):o(a.response)}function jo(a,n,o){o(Wt(ye(ne(a)),n))}function Ko(a,n,o){const d=ks(a);!d||!d.body?o():window.TextDecoder?Jo(d.body,n.requestErrorResponseLengthLimit,(f,c)=>{o(f?`Unable to retrieve response: ${f}`:c)}):d.text().then(D(f=>o(Wt(f,n))),D(f=>o(`Unable to retrieve response: ${f}`)))}function qo(a){return a.status===0&&a.responseType!=="opaque"}function Wt(a,n){return a.length>n.requestErrorResponseLengthLimit?`${a.substring(0,n.requestErrorResponseLengthLimit)}...`:a}function Wo(a){return a==="xhr"?"XHR":"Fetch"}function Jo(a,n,o){vo(a,(d,f,c)=>{if(d)o(d);else{let u=new TextDecoder().decode(f);c&&(u+="..."),o(void 0,u)}},{bytesLimit:n,collectStreamBody:!0})}function Xo(a,n){if(!a.forwardErrorsToLogs)return{stop:le};const o=new G,{stop:d}=Qr(o),f=o.subscribe(c=>{n.notify(0,{rawLogsEvent:{message:c.message,date:c.startClocks.timeStamp,error:ut(c),origin:J.SOURCE,status:B.error},messageContext:c.context})});return{stop:()=>{d(),f.unsubscribe()}}}const Zo=Ws;function Qo(a){function n(o,d,f,c,u){const s=Ae(d.getContext(),o.context);if(ht(o.status,Ye.console,d)&&ta(o,s),ht(o.status,Ye.http,d)){const p={rawLogsEvent:{date:u||oe(),message:o.message,status:o.status,origin:J.LOGGER},messageContext:s,savedCommonContext:c};f&&(p.domainContext={handlingStack:f}),a.notify(0,p)}}return{handleLog:n}}const ea={[B.ok]:O.debug,[B.debug]:O.debug,[B.info]:O.info,[B.notice]:O.info,[B.warn]:O.warn,[B.error]:O.error,[B.critical]:O.error,[B.alert]:O.error,[B.emerg]:O.error};function ta({status:a,message:n},o){he[ea[a]].call(te,n,o)}function ia(a,n,o,d,f){const c=en(a,{endpoint:a.logsEndpointBuilder,encoder:ft()},a.replica&&{endpoint:a.replica.logsEndpointBuilder,encoder:ft()},o,d,f.expireObservable);return n.subscribe(1,u=>{c.add(u)}),c}function na(a){const n=Gt();a.subscribe(1,o=>{n.send("log",o)})}function ra(a){return{get:n=>{const o=a.findTrackedSession(n);if(o)return{session_id:o.id}}}}function sa(a){return n=>{a.notify(0,{rawLogsEvent:{message:n.message,date:n.startClocks.timeStamp,origin:J.AGENT,status:B.error}}),Hi("Error reported to customer",{"error.message":n.message})}}function oa(a,n,o,d,f){const c=_s("browser-logs-sdk",n);c.setContextProvider(()=>{var s,p,_,g,v,U;return{application:{id:(s=pt())===null||s===void 0?void 0:s.application_id},session:{id:(p=f.findTrackedSession())===null||p===void 0?void 0:p.id},view:{id:(g=(_=pt())===null||_===void 0?void 0:_.view)===null||g===void 0?void 0:g.id},action:{id:(U=(v=pt())===null||v===void 0?void 0:v.user_action)===null||U===void 0?void 0:U.id}}});const u=[];if(dt()){const s=Gt(),p=c.observable.subscribe(_=>s.send("internal_telemetry",_));u.push(()=>p.unsubscribe())}else{const s=en(n,{endpoint:n.rumEndpointBuilder,encoder:ft()},n.replica&&{endpoint:n.replica.rumEndpointBuilder,encoder:ft()},o,d,f.expireObservable);u.push(()=>s.stop());const p=c.observable.subscribe(_=>s.add(_,ys(n)));u.push(()=>p.unsubscribe())}return ms(),vs(Fo(a)),{telemetry:c,stop:()=>{u.forEach(s=>s())}}}function aa(a,n,o,d){const f=new Zo,c=[];f.subscribe(1,U=>Pi("logs",U));const u=sa(f),s=$s(n),p=n.sessionStoreStrategyType&&!dt()&&!rn()?Po(n,d):zo(n),{stop:_}=oa(a,n,u,s,p);c.push(()=>_()),Vo(n,f),Xo(n,f),Ho(n,f),Yo(n,f);const{handleLog:g}=Qo(f);if(No(p,n,f,o,u),dt())na(f);else{const{stop:U}=ia(n,f,u,s,p);c.push(()=>U())}const v=ra(p);return{handleLog:g,getInternalContext:v.get,stop:()=>{c.forEach(U=>U())}}}const Fe=Lo(aa);ns(de(),"DD_LOGS",Fe);const I=class I{constructor(n){this.listenerMap=new Map,I.options=n,this.isLoggingOn=n.LOG_TO_DATADOG,this.eventTarget=new EventTarget,this.isLoggingOn&&Fe.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!1,sessionSampleRate:100});const o="bb_logger_mac_uuid";let d=localStorage.getItem(o);d||(d=crypto.randomUUID(),localStorage.setItem(o,d)),I.tracking.mac=d,I.tracking.dev=`${n.platform}_${n.browserName}`,I.beatHandle||(I.options&&k(I.options,"Logger")&&console.log("[Logger] Starting tracking beat"),I.beatHandle=window.setInterval(I.flushTracking,15e3))}static setMessagePort(n){this.messagePort=n}static getMessagePort(){return this.messagePort}setLoggingOn(n){this.isLoggingOn=n}addEventListener(n,o){const d=f=>o(f);this.listenerMap.set(o,{eventName:n,wrappedListener:d}),this.eventTarget.addEventListener(n,d)}removeEventListener(n,o){const d=this.listenerMap.get(o);d&&d.eventName===n&&(this.eventTarget.removeEventListener(n,d.wrappedListener),this.listenerMap.delete(o))}removeAllEventListeners(){for(const[n,{eventName:o,wrappedListener:d}]of this.listenerMap)this.eventTarget.removeEventListener(o,d);this.listenerMap.clear()}setAttributes(n){I.processAttributes(n);for(const o in n)Fe.logger.setContextProperty(o,n[o])}info(n,o){n==="didClickAd"&&this.emit("mediaSessionDidRegisterClick",{url:(o==null?void 0:o.url)||""}),n==="didToggleGlobalAugmentationDrawing"&&this.emit("mediaSessionDidUpdateGlobalAugmentationState",{isGlobalAugmentationEnabled:(o==null?void 0:o.isEnabled)||!0}),n==="didStartDrawingAugmentationMedia"&&this.emit("mediaSessionDidBeginShotRendering",o),n==="didEndDrawingAugmentationMedia"&&this.emit("mediaSessionDidEndShotRendering",o),n==="didRegisterShot"&&this.emit("mediaSessionDidRegisterShot",o),o&&I.processAttributes(o),this.isLoggingOn&&(Fe.logger.info(n,o),I.options&&k(I.options,"Logger")&&console.log("[Logger] Sending info: ",n))}error(n,o){o&&I.processAttributes(o),this.isLoggingOn&&(Fe.logger.error(n,o),I.tracking.err_time=Date.now().toFixed(0),I.tracking.err_desc=n+(o?` - ${JSON.stringify(o)}`:""),I.options&&k(I.options,"Logger")&&console.log("[Logger] Sending error: ",n))}warn(n,o){o&&I.processAttributes(o),this.isLoggingOn&&(Fe.logger.warn(n,o),I.options&&k(I.options,"Logger")&&console.log("[Logger] Sending warn: ",n))}handleMessageFromWorker(n){n.actionType==="INFO"?this.info(n.message,n.attributes):n.actionType==="ERROR"?this.error(n.message,n.attributes):n.actionType==="WARN"?this.warn(n.message,n.attributes):n.actionType==="SET_ATTRIBUTES"&&n.attributes&&this.setAttributes(n.attributes)}static setAttributes(n){if(!I.messagePort){console.error("[Logger] messagePort is not set! Cannot send attributes.");return}try{I.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:n})}catch(o){console.error("[Logger] Error posting message:",o)}}static info(n,o){I.messagePort.postMessage({type:"LOG",actionType:"INFO",message:n,attributes:o})}static error(n,o){I.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:n,attributes:o})}static warn(n,o){I.messagePort.postMessage({type:"LOG",actionType:"WARN",message:n,attributes:o})}static processAttributes(n){if(n.player_version&&(I.tracking.sdk=n.player_version),n.media_id&&(I.tracking.gid=n.media_id),n.game_id&&(I.tracking.buc=n.game_id),n.bb_session_id&&(I.tracking.sid=n.bb_session_id,I.options&&k(I.options,"Logger")&&console.log("[Logger] Setting bb_session_id:",I.tracking.sid)),n.last_timecode){const d=$.fromStr(n.last_timecode);I.tracking.tc=d.print(),I.lastTimecodeMillis=d.totalMilliseconds(59.94),I.lastTimecodeMillis&&I.lastZipMillis&&(I.tracking.cache=(I.lastZipMillis-I.lastTimecodeMillis).toFixed(0))}n.last_offset&&(I.tracking.off=n.last_offset),n.last_loading_zip&&(I.tracking.zip=n.last_loading_zip+".zip",I.lastZipMillis=$.fromStr(n.last_loading_zip).totalMilliseconds(59.94),I.lastTimecodeMillis&&I.lastZipMillis&&(I.tracking.cache=(I.lastZipMillis-I.lastTimecodeMillis).toFixed(0))),n.last_rendered_frame&&(I.tracking.aug_time=Date.now().toFixed(0)),n.asset&&(I.tracking.asset=n.asset)}static objectToQuery(n){return Object.entries(n).filter(([o,d])=>d!==0&&d!=="").map(([o,d])=>`${encodeURIComponent(o)}=${encodeURIComponent(String(d))}`).join("&")}emit(n,o){const d=new CustomEvent(n,{detail:o});this.eventTarget.dispatchEvent(d)}};I.tracking={start:Date.now().toFixed(0),dev:"",sdk:"",mac:"",gid:"",sid:"",off:"",zip:"",aug_time:"",err_time:"",err_desc:"",tc:"",asset:"",cache:"",buc:""},I.lastTimecodeMillis=0,I.lastZipMillis=0,I.flushTracking=()=>{const n=Date.now().toFixed(0);I.tracking.now=n;const d=`https://dwu3k7rrxk5s3.cloudfront.net/metrics/1.gif?${I.objectToQuery(I.tracking)}`;I.options&&k(I.options,"Logger")&&console.log("[Logger] Flushing tracking data:",d),fetch(d,{method:"GET",mode:"no-cors",keepalive:!0,headers:{"X-Platform":"Web"}}).catch(()=>{}),I.tracking.err_desc="",I.tracking.err_time=""};let z=I;class Jt{constructor(n,o,d){this.videoDecoder=null,this.reservedVideoDecoder=null,this.videoDecoderNeedsKeyFrame=!1,this.reservedVideoDecoderNeedsKeyFrame=!1,this.currentTimecode="",this.fps=0,this.unchunkedJobs=[],this.jobChunking=null,this.jobsQueue=[],this.chunksQueue=[],this.chunksForDecodingFrames=[],this.processedMetadata=[],this.lastJobEndTimecode=0,this.lastProcessedFrameTimecode=0,this.storedFrames=[],this.videoDecoderConfigured=!1,this.reservedVideoDecoderConfigured=!1,this.timecodeErrorCount=0,this.decoderStopped=!1,this.chunkCount=0,this.chunkingTimeSum=0,this.avgChunkingTime=0,this.decodingFrameCount=0,this.decodingTimeSum=0,this.avgDecodingTime=0,this.lastPerformanceCheck=performance.now(),this.loggerTimeoutStart=0,this.loggerTimeout=1e4,this.lastStatusUpdate=0,this.STATUS_UPDATE_INTERVAL=200,this.lastDecoderStatus={healthy:!0,issue:""},this.lastTimecodeStatus={consistent:!0,errorCount:0},this.addJob=(f,c)=>{if(this.decoderStopped)return;const{alphaMp4:u,metadataList:s}=this.parseZipAndMetadata(c,f);if(!u){this.options&&k(this.options,"Decoder")&&console.log("[Decoder] No alpha.mp4 found, no decoding needed.");return}const p={timeCode:f,alphaMp4:u,metadata:s,chunks:[],totalFrameCount:s.length,framesProcessed:0,framesSentToDecoder:0,useReserveDecoder:s.length<3,chunkingTime:0};this.jobChunking?this.unchunkedJobs.push(p):(this.jobChunking=p,this.chunkJob(p)),this.options&&k(this.options,"Decoder")&&console.log("[Decoder] Added job:",p)},this.clearOldJobsAndChunks=f=>{const u=$.fromStr(this.currentTimecode).totalMilliseconds(this.fps)-f;this.unchunkedJobs=this.unchunkedJobs.filter(s=>$.fromStr(s.timeCode).totalMilliseconds(this.fps)>u),this.jobsQueue=this.jobsQueue.filter(s=>$.fromStr(s.timeCode).totalMilliseconds(this.fps)>u),this.chunksQueue=this.chunksQueue.filter(s=>$.fromStr(s.timeCode).totalMilliseconds(this.fps)>u)},this.clearAllJobsAndChunks=()=>{this.unchunkedJobs=[],this.jobsQueue=[],this.chunksQueue=[]},this.updateCurrentTimecode=(f,c)=>{if(!this.decoderStopped&&this.options){if(this.fps=59.94,this.currentTimecode){const u=$.fromStr(f).totalMilliseconds(this.fps),s=$.fromStr(this.currentTimecode).totalMilliseconds(this.fps);if(u<s||u>s+this.options.DECODER_LEAD_TIME_MILLIS){this.timecodeErrorCount++,this.updateStatus();const p=performance.now();if(u<s&&(p-this.loggerTimeoutStart>this.loggerTimeout&&(this.loggerTimeoutStart=p,z.error("[Decoder] Timecode is going backwards")),this.options&&k(this.options,"Errors")&&console.error("[Decoder] Timecode is going backwards")),u>s+this.options.DECODER_LEAD_TIME_MILLIS&&(p-this.loggerTimeoutStart>this.loggerTimeout&&(this.loggerTimeoutStart=p,z.error("[Decoder] Timecode is too far ahead")),this.options&&k(this.options,"Errors")&&console.error("[Decoder] Timecode is too far ahead")),this.timecodeErrorCount>5&&!this.options.BURNED_TIMECODES_MODE&&this.restartDecoder(),!this.options.BURNED_TIMECODES_MODE)return}}this.timecodeErrorCount=0,this.currentTimecode=f,this.clearOldJobsAndChunks(2100),this.decodeUpcomingChunks(),this.updateStatus()}},this.setupMP4Box=(f=!1)=>{const c=cn.createFile();return c.onError=u=>{z.error("[Decoder] MP4 parsing error",u),this.options&&k(this.options,"Errors")&&console.error("[Decoder] MP4 parsing error:",u)},c.onReady=u=>{const s=u.tracks.find(p=>p.type==="video");if(s){if(!(f?this.reservedVideoDecoderConfigured:this.videoDecoderConfigured)){this.options&&k(this.options,"Decoder")&&console.error("[Decoder] Starting a new VideoDecoder");let _;f?(this.reservedVideoDecoder=new VideoDecoder({output:this.onFrameDecoded,error:this.onDecoderError}),_=this.reservedVideoDecoder):(this.videoDecoder=new VideoDecoder({output:this.onFrameDecoded,error:this.onDecoderError}),_=this.videoDecoder),_.configure({codec:s.codec,codedWidth:s.video.width,codedHeight:s.video.height,description:this.getDescription(c.getTrackById(s.id)),hardwareAcceleration:"prefer-hardware",optimizeForLatency:!0}),f?(this.reservedVideoDecoderConfigured=!0,this.reservedVideoDecoderNeedsKeyFrame=!0):(this.videoDecoderConfigured=!0,this.videoDecoderNeedsKeyFrame=!0,this.updateStatus())}c.setExtractionOptions(s.id),c.start()}},c.onSamples=async(u,s,p)=>{var U;const _=[];let g=0,v=0;if(this.options&&k(this.options,"Decoder")&&console.log("[Decoder] onSamples for job",(U=this.jobChunking)==null?void 0:U.timeCode,"samples=",p.length),this.options.browserName==="Firefox"){const S=p.map(e=>e.cts).sort((e,t)=>e-t);g=200-S[0],v=S[S.length-1]+g}for(const S of p){const E=this.options.browserName==="Firefox"?S.cts+this.lastJobEndTimecode+g:S.cts,e=new EncodedVideoChunk({type:S.is_sync?"key":"delta",timestamp:E,data:new Uint8Array(S.data)});_.push(e)}this.storeChunks(_),this.options.browserName==="Firefox"&&(this.lastJobEndTimecode+=v)},c},this.chunkJob=async f=>{f.chunkingTime=performance.now(),this.mp4boxfile=this.setupMP4Box(f.useReserveDecoder);const u=await new Blob([f.alphaMp4],{type:"video/mp4"}).arrayBuffer();u.fileStart=0,this.mp4boxfile.appendBuffer(u)},this.storeChunks=f=>{var s;this.options&&k(this.options,"Decoder")&&console.log("[Decoder] Storing chunks:",f);const c=this.jobChunking;if(f.length!==c.metadata.length){const p=c.metadata.filter(_=>_.placeholders||_.LED&&_.LED.cubePlaceholders);p.length==f.length&&(c.metadata=p)}if(this.options&&k(this.options,"Errors")&&f.length!==c.metadata.length){const p=c.metadata.findIndex((_,g)=>!f[g]);console.error("[Decoder] MISMATCH: first undefined chunk at index",p)}if((s=this.options.debug)!=null&&s.trackPerformance&&(c.chunkingTime=performance.now()-c.chunkingTime,this.chunkCount++,this.chunkingTimeSum+=c.chunkingTime,this.avgChunkingTime=this.chunkingTimeSum/this.chunkCount),this.unchunkedJobs.length>0){const p=this.unchunkedJobs.shift();this.jobChunking=p,this.chunkJob(p)}else this.jobChunking=null;const u=c==null?void 0:c.metadata.map((p,_)=>({timeCode:p.timecode,chunk:f[_],metadata:p,job:c,cancelled:!1,decodingTime:0}));c.chunks=u,this.chunksQueue.push(...u),this.jobsQueue.push(c),this.options&&k(this.options,"Decoder")&&console.log("[Decoder] Jobs Queue:",this.jobsQueue),this.options&&k(this.options,"Decoder")&&console.log("[Decoder] Chunks Queue:",this.chunksQueue)},this.onFrameDecoded=f=>{var p;let c=0;if(this.options.browserName==="Firefox"){c=this.lastProcessedFrameTimecode+200;const _=f.timestamp;if(_!==c){if(this.options&&k(this.options,"Decoder")&&console.log("[Decoder] Frame out of order, storing frame:",_),this.storedFrames.push(f),this.storedFrames.sort((g,v)=>g.timestamp-v.timestamp),this.storedFrames[0].timestamp===c){const g=this.storedFrames.shift();g&&this.onFrameDecoded(g)}this.storedFrames.sort((g,v)=>g.timestamp-v.timestamp);return}this.lastProcessedFrameTimecode=_}this.options&&k(this.options,"Decoder")&&console.log("[Decoder] Frame decoded:",f);const u=this.chunksForDecodingFrames.shift();if(!u){z.error("[Decoder] No current chunk for a processed frame"),this.options&&k(this.options,"Errors")&&console.error("[Decoder] No current chunk for a processed frame");return}if(u.cancelled||this.decoderStopped){this.options&&k(this.options,"Decoder")&&console.log("[Decoder] Skipping cancelled chunk:",u.timeCode),f.close();return}const s=u.metadata;if((p=this.options.debug)!=null&&p.trackPerformance){const _=performance.now();u.decodingTime=_-u.decodingTime,this.decodingFrameCount++,this.decodingTimeSum+=u.decodingTime,this.avgDecodingTime=this.decodingTimeSum/this.decodingFrameCount,_-this.lastPerformanceCheck>=this.options.PERFORMANCE_TRACKING_INTERVAL&&(this.trackPerformance(),this.lastPerformanceCheck=_)}if(u.job.framesProcessed++,s.alphaMask=f,this.processedMetadata.push(s),z.setAttributes({last_decoded_frame:s.timecode}),(this.processedMetadata.length>=this.options.DECODER_FRAME_BATCH_SIZE||u.job.framesProcessed>=u.job.totalFrameCount)&&(this.postBatchToRenderer(this.processedMetadata),this.processedMetadata.forEach(_=>_.alphaMask.close()),this.processedMetadata=[]),this.options.browserName==="Firefox"&&this.storedFrames.length>0){const _=(c+200)%24200||400;if(this.storedFrames[0].timestamp===_){const g=this.storedFrames.shift();g&&this.onFrameDecoded(g)}}},this.onDecoderError=f=>{var s,p;z.error("[Decoder] VideoDecoder error",f),this.options&&k(this.options,"Errors")&&console.error("[Decoder] VideoDecoder error:",f),this.videoDecoderConfigured=!1,this.reservedVideoDecoderConfigured=!1,this.videoDecoderNeedsKeyFrame=!0,this.reservedVideoDecoderNeedsKeyFrame=!0,this.updateStatus();const c=this.chunksForDecodingFrames.shift();if(!c){z.error("[Decoder] No broken chunk for an error"),this.options&&k(this.options,"Errors")&&console.error("[Decoder] No broken chunk for an error");return}const u=c.job;u&&u.chunks.forEach(_=>_.cancelled=!0),(s=this.reservedVideoDecoder)==null||s.close(),(p=this.videoDecoder)==null||p.close()},this.parseZipAndMetadata=(f,c)=>{var e;const u=pn.parse(f),s=((e=u["alpha.mp4"])==null?void 0:e.buffer)||null,p=Object.keys(u).filter(t=>t.endsWith(".json")).sort(this.numericFileComparator).map(t=>{const r=JSON.parse(new TextDecoder().decode(u[t]));return r.timecode=$.toStr($.fromMetadata(r)),r}),_=p.length;let g=120;const[v,U,S]=c.split("_").map(Number);U%10===0&&S===0?g=120:S===0&&(g=116),_!==g&&(z.error("[Decoder] Metadata count mismatch",{expected:g,actual:_,timecode:c}),this.options&&k(this.options,"Errors")&&console.error("[Decoder] Metadata count mismatch:",{expected:g,actual:_,timecode:c}));const E=p;return this.options&&k(this.options,"Decoder")&&console.log("[Decoder] ZIP",c,"metadataFull=",p.length,"metadataFiltered=",E.length),{alphaMp4:s,metadataList:E}},this.numericFileComparator=(f,c)=>{const u=/^(\\d{2})_(\\d{2})_(\\d{2})_(\\d{2})(?:\\.(\\d+))?\\.(.+)$/,s=f.match(u),p=c.match(u);if(!s||!p)return 0;const[,_,g,v,U,S="0",E]=s,[,e,t,r,l,h="0",m]=p;return parseInt(_,10)-parseInt(e,10)||parseInt(g,10)-parseInt(t,10)||parseInt(v,10)-parseInt(r,10)||parseInt(U,10)-parseInt(l,10)||parseInt(S,10)-parseInt(h,10)||E.localeCompare(m)},this.getDescription=f=>{for(const c of f.mdia.minf.stbl.stsd.entries){const u=c.avcC||c.hvcC||c.vpcC||c.av1C;if(u){const s=new yt.DataStream(void 0,0,yt.DataStream.BIG_ENDIAN);return u.write(s),new Uint8Array(s.buffer,8)}}return null},this.trackPerformance=()=>{const f=this.getAvgChunkingTime(),c=this.getAvgDecodingTime();fa([{metric:"Chunking time",value:f},{metric:"Decoding time",value:c}])},this.postBatchToRenderer=n,this.restartDecoder=o,this.options=d,this.mp4boxfile=this.setupMP4Box()}isStopped(){return this.decoderStopped}updateStatus(){const n=performance.now();if(n-this.lastStatusUpdate<this.STATUS_UPDATE_INTERVAL)return;const o={healthy:this.videoDecoderConfigured&&!this.decoderStopped,issue:this.videoDecoderConfigured?this.decoderStopped?"Stopped":"":"Not configured"},d={consistent:this.timecodeErrorCount<=3,errorCount:this.timecodeErrorCount};(JSON.stringify(o)!==JSON.stringify(this.lastDecoderStatus)||JSON.stringify(d)!==JSON.stringify(this.lastTimecodeStatus))&&(z.setAttributes({decoder_status:o,timecode_status:d}),this.lastDecoderStatus=o,this.lastTimecodeStatus=d,this.lastStatusUpdate=n)}decodeUpcomingChunks(){const n=$.fromStr(this.currentTimecode).totalMilliseconds(this.fps),o=n+this.options.DECODER_LEAD_TIME_MILLIS,d=this.chunksQueue.filter(c=>{const u=$.fromStr(c.timeCode).totalMilliseconds(this.fps);return u>=n&&u<=o&&!c.decoded});d.sort((c,u)=>{const s=$.fromStr(c.timeCode).totalMilliseconds(this.fps),p=$.fromStr(u.timeCode).totalMilliseconds(this.fps);return s-p});const f=d.slice(0,this.options.DECODER_FRAME_BATCH_SIZE);for(const c of f){if(c.cancelled){this.options&&k(this.options,"Decoder")&&console.log("[Decoder] Skipping cancelled chunk:",c.timeCode);continue}const u=c.job.useReserveDecoder?this.reservedVideoDecoder:this.videoDecoder;if(!u||u.state==="closed"){z.error("[Decoder] No VideoDecoder available"),this.options&&k(this.options,"Errors")&&console.error("[Decoder] No VideoDecoder available");continue}if((c.job.useReserveDecoder?this.reservedVideoDecoderNeedsKeyFrame:this.videoDecoderNeedsKeyFrame)&&c.chunk.type==="delta"){z.error("[Decoder] Decoder needs a key frame, skipping delta chunk",{chunkTimeCode:c.timeCode}),this.options&&k(this.options,"Errors")&&console.error("[Decoder] Decoder needs a key frame, skipping delta chunk:",c.timeCode),c.decoded=!0;continue}try{this.chunksForDecodingFrames.push(c),c.chunk.type==="key"&&(c.job.useReserveDecoder?this.reservedVideoDecoderNeedsKeyFrame=!1:this.videoDecoderNeedsKeyFrame=!1),c.decodingTime=performance.now(),u.decode(c.chunk)}catch(p){z.error("[Decoder] Error decoding chunk",p),this.options&&k(this.options,"Errors")&&console.error("[Decoder] Error decoding chunk:",p),this.videoDecoderConfigured=!1,this.reservedVideoDecoderConfigured=!1,this.videoDecoderNeedsKeyFrame=!0,this.updateStatus(),this.reservedVideoDecoderNeedsKeyFrame=!0,c.job.chunks.forEach(g=>g.cancelled=!0),u.close()}finally{if(c.decoded=!0,c.job.framesSentToDecoder++,c.job.framesSentToDecoder>=c.job.totalFrameCount){u.flush(),c.job.useReserveDecoder;continue}}}}getAvgChunkingTime(){var n;if((n=this.options.debug)!=null&&n.trackPerformance){const o=this.avgChunkingTime;return this.chunkCount=0,this.chunkingTimeSum=0,this.avgChunkingTime=0,o}return 0}getAvgDecodingTime(){var n;if((n=this.options.debug)!=null&&n.trackPerformance){const o=this.avgDecodingTime;return this.decodingFrameCount=0,this.decodingTimeSum=0,this.avgDecodingTime=0,o}return 0}stop(){var n,o;this.decoderStopped=!0,this.updateStatus(),this.clearAllJobsAndChunks();try{(n=this.videoDecoder)==null||n.close()}catch(d){z.error("[Decoder] Error closing main VideoDecoder",d),this.options&&k(this.options,"Errors")&&console.error("[Decoder] Error closing main VideoDecoder:",d)}try{(o=this.reservedVideoDecoder)==null||o.close()}catch(d){z.error("[Decoder] Error closing reserved VideoDecoder",d),this.options&&k(this.options,"Errors")&&console.error("[Decoder] Error closing reserved VideoDecoder:",d)}}}let ln=null,_t=null,X,H;self.onmessage=async a=>{const{data:n}=a;if(n.type==="SET_LOGGER_PORT"&&z.setMessagePort(n.port),n.type==="SET_DOWNLOADER_PORT"&&(ln=n.port,ln.onmessage=da),n.type==="SET_RENDERER_PORT"&&(_t=n.port,_t.onmessage=la),n.type==="SET_OPTIONS"&&(H=n.options,z.setMessagePort(self),X=new Jt(Xt,gt,H)),n.type==="STOP_WORKER"){X&&X.stop();return}if(n.type==="RESTART_WORKER"){if(!H)return;gt();return}};function da(a){const{data:n}=a;if(n.type==="DECODER_INPUT"){if(!X||X.isStopped())return;const{timeCode:o,arrayBuffer:d}=n;H&&k(H,"Decoder")&&console.log("[DecoderWorker] Received ArrayBuffer from Downloader, timeCode =",o),X.addJob(o,d)}}function la(a){const{data:n}=a;if(n.type==="DECODER_REQUEST"){if(!X||X.isStopped())return;const{timeCode:o,fps:d}=n;H&&k(H,"Decoder")&&console.log("[DecoderWorker] Received TimeCode request from Renderer, timeCode =",o),X.updateCurrentTimecode(o,d)}}function gt(){H&&(X.stop(),X=new Jt(Xt,gt,H))}function Xt(a){if(!_t)return;H&&k(H,"Decoder")&&console.log(`[DecoderWorker] Posting a batch of ${a.length} frames to Renderer`);const n=a.map(o=>o.alphaMask).filter(o=>o!==void 0);try{const o=new Set(n);_t.postMessage({type:"RENDERER_INPUT",batch:a},[...o]),n.forEach(d=>d.close())}catch(o){z.error("[DecoderWorker] Error posting batch to Renderer",{error:o}),H&&k(H,"Errors")&&console.error("[DecoderWorker] Error posting batch to Renderer:",o),n.forEach(d=>d.close());return}}function fa(a){const n={type:"TRACK_PERFORMANCE",data:a};self.postMessage(n)}self.onunhandledrejection=a=>{z.error("[DecoderWorker] Unhandled rejection",{error:a.reason}),H&&(k(H,"Errors")&&console.error("[DecoderWorker] Unhandled rejection:",a.reason),X.stop(),X=new Jt(Xt,gt,H),a.preventDefault())},self.onerror=a=>{z.error("[DecoderWorker] Unhandled error",{error:a}),H&&(k(H,"Errors")&&console.error("[DecoderWorker] Unhandled error:",a),a instanceof Event&&a.preventDefault())}})();\n',$t=typeof self<"u"&&self.Blob&&new Blob([zt],{type:"text/javascript;charset=utf-8"});function an(t){let e;try{if(e=$t&&(self.URL||self.webkitURL).createObjectURL($t),!e)throw"";const r=new Worker(e,{name:t==null?void 0:t.name});return r.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),r}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(zt),{name:t==null?void 0:t.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}const Gt=`(function(){"use strict";const g=(t,e)=>e==="Errors"?!0:!t.debug||!t.debug.on?!1:t.debug[\`log\${e}\`],I={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},H=console,ie={};Object.keys(I).forEach(t=>{ie[t]=H[t]});const xe="Datadog Browser SDK:",M={debug:ie.debug.bind(H,xe),log:ie.log.bind(H,xe),info:ie.info.bind(H,xe),warn:ie.warn.bind(H,xe),error:ie.error.bind(H,xe)},At="https://docs.datadoghq.com",Zt=\`\${At}/real_user_monitoring/browser/troubleshooting\`,ke="More details:";function Jt(t,e){return(...s)=>{try{return t(...s)}catch(r){M.error(e,r)}}}function Ge(t){return t!==0&&Math.random()*100<=t}function ms(t){return ps(t)&&t>=0&&t<=100}function ps(t){return typeof t=="number"}const Se=1e3,oe=60*Se,Qt=60*oe,gs=365*(24*Qt);function Le(){return new Date().getTime()}function J(){return Le()}function Xe(){return performance.now()}function Q(){return{relative:Xe(),timeStamp:J()}}function Es(){return{relative:0,timeStamp:er()}}function Ts(t,e){return e-t}function As(t,e){return t+e}function _s(t){return t-er()}let _t;function er(){return _t===void 0&&(_t=performance.timing.navigationStart),_t}const z=1024,tr=1024*z,bs=/[^\\u0000-\\u007F]/;function bt(t){return bs.test(t)?window.TextEncoder!==void 0?new TextEncoder().encode(t).length:new Blob([t]).size:t.length}function Rs(t){return{...t}}function rr(t,e){return Object.keys(t).some(s=>t[s]===e)}function De(t){return Object.keys(t).length===0}function ee(){if(typeof globalThis=="object")return globalThis;Object.defineProperty(Object.prototype,"_dd_temp_",{get(){return this},configurable:!0});let t=_dd_temp_;return delete Object.prototype._dd_temp_,typeof t!="object"&&(typeof self=="object"?t=self:typeof window=="object"?t=window:t={}),t}function ge(t,e){const s=ee();let r;return s.Zone&&typeof s.Zone.__symbol__=="function"&&(r=t[s.Zone.__symbol__(e)]),r||(r=t[e]),r}let We,sr=!1;function vs(t){We=t}function ys(t){sr=t}function xs(t,e,s){const r=s.value;s.value=function(...n){return(We?x(r):r).apply(this,n)}}function x(t){return function(){return we(t,this,arguments)}}function we(t,e,s){try{return t.apply(e,s)}catch(r){Ss(r)}}function Ss(t){if(Rt(t),We)try{We(t)}catch(e){Rt(e)}}function Rt(...t){sr&&M.error("[MONITOR]",...t)}function Ue(t,e){return ge(ee(),"setTimeout")(x(t),e)}function nr(t){ge(ee(),"clearTimeout")(t)}function vt(t,e){return ge(ee(),"setInterval")(x(t),e)}function ir(t){ge(ee(),"clearInterval")(t)}class N{constructor(e){this.onFirstSubscribe=e,this.observers=[]}subscribe(e){return this.observers.push(e),this.observers.length===1&&this.onFirstSubscribe&&(this.onLastUnsubscribe=this.onFirstSubscribe(this)||void 0),{unsubscribe:()=>{this.observers=this.observers.filter(s=>e!==s),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}}notify(e){this.observers.forEach(s=>s(e))}}function or(...t){return new N(e=>{const s=t.map(r=>r.subscribe(n=>e.notify(n)));return()=>s.forEach(r=>r.unsubscribe())})}function ar(t,e,s){let r=!1,n,o;return{throttled:(...i)=>{if(r){n=i;return}t(...i),r=!0,o=Ue(()=>{n&&t(...n),r=!1,n=void 0},e)},cancel:()=>{nr(o),r=!1,n=void 0}}}function te(){}function re(t){return t?(parseInt(t,10)^Math.random()*16>>parseInt(t,10)/4).toString(16):\`10000000-1000-4000-8000-\${1e11}\`.replace(/[018]/g,re)}const Ye=/([\\w-]+)\\s*=\\s*([^;]+)/g;function Ls(t,e){for(Ye.lastIndex=0;;){const s=Ye.exec(t);if(s){if(s[1]===e)return s[2]}else break}}function Ds(t){const e=new Map;for(Ye.lastIndex=0;;){const s=Ye.exec(t);if(s)e.set(s[1],s[2]);else break}return e}function ws(t,e,s=""){const r=t.charCodeAt(e-1),o=r>=55296&&r<=56319?e+1:e;return t.length<=o?t:\`\${t.slice(0,o)}\${s}\`}function Us(){return Ps()===0}let He;function Ps(){return He??(He=Os())}function Os(t=window){var e;const s=t.navigator.userAgent;return t.chrome||/HeadlessChrome/.test(s)?0:((e=t.navigator.vendor)===null||e===void 0?void 0:e.indexOf("Apple"))===0||/safari/i.test(s)&&!/chrome|android/i.test(s)?1:2}function Pe(t,e,s=0,r){const n=new Date;n.setTime(n.getTime()+s);const o=\`expires=\${n.toUTCString()}\`,i=r&&r.crossSite?"none":"strict",a=r&&r.domain?\`;domain=\${r.domain}\`:"",c=r&&r.secure?";secure":"",d=r&&r.partitioned?";partitioned":"";document.cookie=\`\${t}=\${e};\${o};path=/;samesite=\${i}\${a}\${c}\${d}\`}function yt(t){return Ls(document.cookie,t)}let xt;function ae(t){return xt||(xt=Ds(document.cookie)),xt.get(t)}function cr(t,e){Pe(t,"",0,e)}function Cs(t){if(document.cookie===void 0||document.cookie===null)return!1;try{const e=\`dd_cookie_test_\${re()}\`,s="test";Pe(e,s,oe,t);const r=yt(e)===s;return cr(e,t),r}catch(e){return M.error(e),!1}}let St;function Fs(){if(St===void 0){const t=\`dd_site_test_\${re()}\`,e="test",s=window.location.hostname.split(".");let r=s.pop();for(;s.length&&!yt(t);)r=\`\${s.pop()}.\${r}\`,Pe(t,e,Se,{domain:r});cr(t,{domain:r}),St=r}return St}const Ee="_dd_s";function $e(t){return Object.values(t)}function Is(t){return Object.entries(t)}const Lt=4*Qt,lr=15*oe,Ms=gs,Oe={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},ur=/^([a-zA-Z]+)=([a-z0-9-]+)$/,Dt="&";function Bs(t){return!!t&&(t.indexOf(Dt)!==-1||ur.test(t))}const Ns="1";function ce(t,e){const s={isExpired:Ns};return e.trackAnonymousUser&&(t!=null&&t.anonymousId?s.anonymousId=t==null?void 0:t.anonymousId:s.anonymousId=re()),s}function Ve(t){return De(t)}function dr(t){return!Ve(t)}function ze(t){return t.isExpired!==void 0||!ks(t)}function ks(t){return(t.created===void 0||Le()-Number(t.created)<Lt)&&(t.expire===void 0||Le()<Number(t.expire))}function fr(t){t.expire=String(Le()+lr)}function wt(t){return Is(t).map(([e,s])=>e==="anonymousId"?\`aid=\${s}\`:\`\${e}=\${s}\`).join(Dt)}function hr(t){const e={};return Bs(t)&&t.split(Dt).forEach(s=>{const r=ur.exec(s);if(r!==null){const[,n,o]=r;n==="aid"?e.anonymousId=o:e[n]=o}}),e}const Gs="_dd",Xs="_dd_r",Ws="_dd_l",Ys="rum",Hs="logs";function $s(t){if(!ae(Ee)){const s=ae(Gs),r=ae(Xs),n=ae(Ws),o={};s&&(o.id=s),n&&/^[01]$/.test(n)&&(o[Hs]=n),r&&/^[012]$/.test(r)&&(o[Ys]=r),dr(o)&&(fr(o),t.persistSession(o))}}function mr(t){const e=Ks(t);return Cs(e)?{type:Oe.COOKIE,cookieOptions:e}:void 0}function Vs(t,e){const s={isLockEnabled:Us(),persistSession:zs(e),retrieveSession:qs,expireSession:r=>js(e,r,t)};return $s(s),s}function zs(t){return e=>{Pe(Ee,wt(e),lr,t)}}function js(t,e,s){const r=ce(e,s);Pe(Ee,wt(r),s.trackAnonymousUser?Ms:Lt,t)}function qs(){const t=yt(Ee);return hr(t)}function Ks(t){const e={};return e.secure=!!t.useSecureSessionCookie||!!t.usePartitionedCrossSiteSessionCookie,e.crossSite=!!t.usePartitionedCrossSiteSessionCookie,e.partitioned=!!t.usePartitionedCrossSiteSessionCookie,t.trackSessionAcrossSubdomains&&(e.domain=Fs()),e}const Zs="_dd_test_";function pr(){try{const t=re(),e=\`\${Zs}\${t}\`;localStorage.setItem(e,t);const s=localStorage.getItem(e);return localStorage.removeItem(e),t===s?{type:Oe.LOCAL_STORAGE}:void 0}catch{return}}function Js(t){return{isLockEnabled:!1,persistSession:gr,retrieveSession:Qs,expireSession:e=>en(e,t)}}function gr(t){localStorage.setItem(Ee,wt(t))}function Qs(){const t=localStorage.getItem(Ee);return hr(t)}function en(t,e){gr(ce(t,e))}const tn=10,rn=100,Er=[];let je;function le(t,e,s=0){var r;const{isLockEnabled:n,persistSession:o,expireSession:i}=e,a=u=>o({...u,lock:d}),c=()=>{const u=e.retrieveSession(),m=u.lock;return u.lock&&delete u.lock,{session:u,lock:m}};if(je||(je=t),t!==je){Er.push(t);return}if(n&&s>=rn){Tr(e);return}let d,l=c();if(n){if(l.lock){qe(t,e,s);return}if(d=re(),a(l.session),l=c(),l.lock!==d){qe(t,e,s);return}}let f=t.process(l.session);if(n&&(l=c(),l.lock!==d)){qe(t,e,s);return}if(f&&(ze(f)?i(f):(fr(f),n?a(f):o(f))),n&&!(f&&ze(f))){if(l=c(),l.lock!==d){qe(t,e,s);return}o(l.session),f=l.session}(r=t.after)===null||r===void 0||r.call(t,f||l.session),Tr(e)}function qe(t,e,s){Ue(()=>{le(t,e,s+1)},tn)}function Tr(t){je=void 0;const e=Er.shift();e&&le(e,t)}const Ar=Se;function sn(t){switch(t.sessionPersistence){case Oe.COOKIE:return mr(t);case Oe.LOCAL_STORAGE:return pr();case void 0:{let e=mr(t);return!e&&t.allowFallbackToLocalStorage&&(e=pr()),e}default:M.error(\`Invalid session persistence '\${String(t.sessionPersistence)}'\`)}}function nn(t,e,s,r){const n=new N,o=new N,i=new N,a=t.type===Oe.COOKIE?Vs(e,t.cookieOptions):Js(e),{expireSession:c}=a,d=vt(p,Ar);let l;h();const{throttled:f,cancel:u}=ar(()=>{le({process:A=>{if(Ve(A))return;const P=T(A);return _(P),P},after:A=>{dr(A)&&!y()&&U(A),l=A}},a)},Ar);function m(){le({process:A=>y()?T(A):void 0},a)}function p(){le({process:A=>ze(A)?ce(A,e):void 0,after:T},a)}function T(A){return ze(A)&&(A=ce(A,e)),y()&&(D(A)?w():(i.notify({previousState:l,newState:A}),l=A)),A}function h(){le({process:A=>{if(Ve(A))return ce(A,e)},after:A=>{l=A}},a)}function _(A){if(Ve(A))return!1;const{trackingType:P,isTracked:W}=r(A[s]);A[s]=P,delete A.isExpired,W&&!A.id&&(A.id=re(),A.created=String(Le()))}function y(){return l[s]!==void 0}function D(A){return l.id!==A.id||l[s]!==A[s]}function w(){l=ce(l,e),o.notify()}function U(A){l=A,n.notify()}function L(A){le({process:P=>({...P,...A}),after:T},a)}return{expandOrRenewSession:f,expandSession:m,getSession:()=>l,renewObservable:n,expireObservable:o,sessionStateUpdateObservable:i,restartSession:h,expire:()=>{u(),c(l),T(ce(l,e))},stop:()=>{ir(d)},updateSessionState:L}}const Ut={GRANTED:"granted",NOT_GRANTED:"not-granted"};function on(t){const e=new N;return{tryToInit(s){t||(t=s)},update(s){t=s,e.notify()},isGranted(){return t===Ut.GRANTED},observable:e}}function ue(t,e,s){if(typeof t!="object"||t===null)return JSON.stringify(t);const r=Te(Object.prototype),n=Te(Array.prototype),o=Te(Object.getPrototypeOf(t)),i=Te(t);try{return JSON.stringify(t,e,s)}catch{return"<error: unable to serialize object>"}finally{r(),n(),o(),i()}}function Te(t){const e=t,s=e.toJSON;return s?(delete e.toJSON,()=>{e.toJSON=s}):te}function Pt(t){return an(t,location.href).href}function an(t,e){const s=cn();if(s)try{return e!==void 0?new s(t,e):new s(t)}catch(o){throw new Error(\`Failed to construct URL: \${String(o)} \${ue({url:t,base:e})}\`)}if(e===void 0&&!/:/.test(t))throw new Error(\`Invalid URL: '\${t}'\`);let r=document;const n=r.createElement("a");if(e!==void 0){r=document.implementation.createHTMLDocument("");const o=r.createElement("base");o.href=e,r.head.appendChild(o),r.body.appendChild(n)}return n.href=t,n}const _r=URL;let Ke;function cn(){if(Ke===void 0)try{Ke=new _r("http://test/path").href==="http://test/path"}catch{Ke=!1}return Ke?_r:void 0}const ln="datad0g.com",un="dd0g-gov.com",Ae="datadoghq.com",dn="ddog-gov.com",fn="pci.browser-intake-datadoghq.com",hn=["ddsource","ddtags"];function Ce(t,e,s){const r=mn(t,e);return{build(n,o){const i=gn(t,e,s,n,o);return r(i)},urlPrefix:r(""),trackType:e}}function mn(t,e){const s=\`/api/v2/\${e}\`,r=t.proxy;if(typeof r=="string"){const o=Pt(r);return i=>\`\${o}?ddforward=\${encodeURIComponent(\`\${s}?\${i}\`)}\`}if(typeof r=="function")return o=>r({path:s,parameters:o});const n=pn(e,t);return o=>\`https://\${n}\${s}?\${o}\`}function pn(t,e){const{site:s=Ae,internalAnalyticsSubdomain:r}=e;if(t==="logs"&&e.usePciIntake&&s===Ae)return fn;if(r&&s===Ae)return\`\${r}.\${Ae}\`;if(s===un)return\`http-intake.logs.\${s}\`;const n=s.split("."),o=n.pop();return\`browser-intake-\${n.join("-")}.\${o}\`}function gn({clientToken:t,internalAnalyticsSubdomain:e},s,r,n,{retry:o,encoding:i}){const a=["sdk_version:6.5.0",\`api:\${n}\`].concat(r);o&&a.push(\`retry_count:\${o.count}\`,\`retry_after:\${o.lastFailureStatus}\`);const c=["ddsource=browser",\`ddtags=\${encodeURIComponent(a.join(","))}\`,\`dd-api-key=\${t}\`,\`dd-evp-origin-version=\${encodeURIComponent("6.5.0")}\`,"dd-evp-origin=browser",\`dd-request-id=\${re()}\`];return i&&c.push(\`dd-evp-encoding=\${i}\`),s==="rum"&&c.push(\`batch_time=\${J()}\`),e&&c.reverse(),c.join("&")}const En=200;function Tn(t){const{env:e,service:s,version:r,datacenter:n}=t,o=[];return e&&o.push(Ze("env",e)),s&&o.push(Ze("service",s)),r&&o.push(Ze("version",r)),n&&o.push(Ze("datacenter",n)),o}function Ze(t,e){const s=En-t.length-1;(e.length>s||An(e))&&M.warn(\`\${t} value doesn't meet tag requirements and will be sanitized. \${ke} \${At}/getting_started/tagging/#defining-tags\`);const r=e.replace(/,/g,"_");return\`\${t}:\${r}\`}function An(t){return _n()?new RegExp("[^\\\\p{Ll}\\\\p{Lo}0-9_:./-]","u").test(t):!1}function _n(){try{return new RegExp("[\\\\p{Ll}]","u"),!0}catch{return!1}}function bn(t){const e=t.site||Ae,s=Tn(t),r=Rn(t,s);return{replica:vn(t,s),site:e,...r}}function Rn(t,e){return{logsEndpointBuilder:Ce(t,"logs",e),rumEndpointBuilder:Ce(t,"rum",e),sessionReplayEndpointBuilder:Ce(t,"replay",e)}}function vn(t,e){if(!t.replica)return;const s={...t,site:Ae,clientToken:t.replica.clientToken},r={logsEndpointBuilder:Ce(s,"logs",e),rumEndpointBuilder:Ce(s,"rum",e)};return{applicationId:t.replica.applicationId,...r}}function yn(t){return hn.every(e=>t.includes(e))}function Ot(t,e){return t!=null&&typeof t!="string"?(M.error(\`\${e} must be defined as a string\`),!1):!0}function xn(t){return t&&typeof t=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(t)?(M.error(\`Site should be a valid Datadog site. \${ke} \${At}/getting_started/site/.\`),!1):!0}function Je(t,e){return t!==void 0&&!ms(t)?(M.error(\`\${e} Sample Rate should be a number between 0 and 100\`),!1):!0}function Sn(t){var e,s,r,n,o,i;if(!t||!t.clientToken){M.error("Client Token is not configured, we will not send any data.");return}if(!(!xn(t.site)||!Je(t.sessionSampleRate,"Session")||!Je(t.telemetrySampleRate,"Telemetry")||!Je(t.telemetryConfigurationSampleRate,"Telemetry Configuration")||!Je(t.telemetryUsageSampleRate,"Telemetry Usage")||!Ot(t.version,"Version")||!Ot(t.env,"Env")||!Ot(t.service,"Service"))){if(t.trackingConsent!==void 0&&!rr(Ut,t.trackingConsent)){M.error('Tracking Consent should be either "granted" or "not-granted"');return}return{beforeSend:t.beforeSend&&Jt(t.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:sn(t),sessionSampleRate:(e=t.sessionSampleRate)!==null&&e!==void 0?e:100,telemetrySampleRate:(s=t.telemetrySampleRate)!==null&&s!==void 0?s:20,telemetryConfigurationSampleRate:(r=t.telemetryConfigurationSampleRate)!==null&&r!==void 0?r:5,telemetryUsageSampleRate:(n=t.telemetryUsageSampleRate)!==null&&n!==void 0?n:5,service:t.service||void 0,silentMultipleInit:!!t.silentMultipleInit,allowUntrustedEvents:!!t.allowUntrustedEvents,trackingConsent:(o=t.trackingConsent)!==null&&o!==void 0?o:Ut.GRANTED,trackAnonymousUser:(i=t.trackAnonymousUser)!==null&&i!==void 0?i:!0,storeContextsAcrossPages:!!t.storeContextsAcrossPages,batchBytesLimit:16*z,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*Se,batchMessagesLimit:50,messageBytesLimit:256*z,...bn(t)}}}function Ln(t){return{session_sample_rate:t.sessionSampleRate,telemetry_sample_rate:t.telemetrySampleRate,telemetry_configuration_sample_rate:t.telemetryConfigurationSampleRate,telemetry_usage_sample_rate:t.telemetryUsageSampleRate,use_before_send:!!t.beforeSend,use_partitioned_cross_site_session_cookie:t.usePartitionedCrossSiteSessionCookie,use_secure_session_cookie:t.useSecureSessionCookie,use_proxy:!!t.proxy,silent_multiple_init:t.silentMultipleInit,track_session_across_subdomains:t.trackSessionAcrossSubdomains,track_anonymous_user:t.trackAnonymousUser,session_persistence:t.sessionPersistence,allow_fallback_to_local_storage:!!t.allowFallbackToLocalStorage,store_contexts_across_pages:!!t.storeContextsAcrossPages,allow_untrusted_events:!!t.allowUntrustedEvents,tracking_consent:t.trackingConsent}}var Ct;(function(t){t.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",t.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(Ct||(Ct={}));const br=new Set;function Dn(t){Array.isArray(t)&&wn(t.filter(e=>rr(Ct,e)))}function wn(t){t.forEach(e=>{br.add(e)})}function Un(){return br}const Fe="?";function j(t){const e=[];let s=Ft(t,"stack");const r=String(t);return s&&s.startsWith(r)&&(s=s.slice(r.length)),s&&s.split(\`
|
|
2
|
+
\`).forEach(n=>{const o=Cn(n)||In(n)||Bn(n)||Gn(n);o&&(!o.func&&o.line&&(o.func=Fe),e.push(o))}),{message:Ft(t,"message"),name:Ft(t,"name"),stack:e}}const Rr="((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\\\w+\\\\.|\\\\/).*?)",_e="(?::(\\\\d+))",Pn=new RegExp(\`^\\\\s*at (.*?) ?\\\\(\${Rr}\${_e}?\${_e}?\\\\)?\\\\s*$\`,"i"),On=new RegExp(\`\\\\((\\\\S*)\${_e}\${_e}\\\\)\`);function Cn(t){const e=Pn.exec(t);if(!e)return;const s=e[2]&&e[2].indexOf("native")===0,r=e[2]&&e[2].indexOf("eval")===0,n=On.exec(e[2]);return r&&n&&(e[2]=n[1],e[3]=n[2],e[4]=n[3]),{args:s?[e[2]]:[],column:e[4]?+e[4]:void 0,func:e[1]||Fe,line:e[3]?+e[3]:void 0,url:s?void 0:e[2]}}const Fn=new RegExp(\`^\\\\s*at ?\${Rr}\${_e}?\${_e}??\\\\s*$\`,"i");function In(t){const e=Fn.exec(t);if(e)return{args:[],column:e[3]?+e[3]:void 0,func:Fe,line:e[2]?+e[2]:void 0,url:e[1]}}const Mn=/^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;function Bn(t){const e=Mn.exec(t);if(e)return{args:[],column:e[4]?+e[4]:void 0,func:e[1]||Fe,line:+e[3],url:e[2]}}const Nn=/^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i,kn=/(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;function Gn(t){const e=Nn.exec(t);if(!e)return;const s=e[3]&&e[3].indexOf(" > eval")>-1,r=kn.exec(e[3]);return s&&r&&(e[3]=r[1],e[4]=r[2],e[5]=void 0),{args:e[2]?e[2].split(","):[],column:e[5]?+e[5]:void 0,func:e[1]||Fe,line:e[4]?+e[4]:void 0,url:e[3]}}function Ft(t,e){if(typeof t!="object"||!t||!(e in t))return;const s=t[e];return typeof s=="string"?s:void 0}function Xn(t,e,s,r){const n=[{url:e,column:r,line:s}],{name:o,message:i}=Yn(t);return{name:o,message:i,stack:n}}const Wn=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\\s\\S]*)$/;function Yn(t){let e,s;return{}.toString.call(t)==="[object String]"&&([,e,s]=Wn.exec(t)),{name:e,message:s}}function Qe(t){const s=new Error(t);s.name="HandlingStack";let r;return we(()=>{const n=j(s);n.stack=n.stack.slice(2),r=de(n)}),r}function de(t){let e=vr(t);return t.stack.forEach(s=>{const r=s.func==="?"?"<anonymous>":s.func,n=s.args&&s.args.length>0?\`(\${s.args.join(", ")})\`:"",o=s.line?\`:\${s.line}\`:"",i=s.line&&s.column?\`:\${s.column}\`:"";e+=\`
|
|
3
|
+
at \${r}\${n} @ \${s.url}\${o}\${i}\`}),e}function vr(t){return\`\${t.name||"Error"}: \${t.message}\`}function fe(t,e,s,{computeHandlingStack:r}={}){let n=t[e];if(typeof n!="function")if(e in t&&e.startsWith("on"))n=te;else return{stop:te};let o=!1;const i=function(){if(o)return n.apply(this,arguments);const a=Array.from(arguments);let c;we(s,null,[{target:this,parameters:a,onPostCall:l=>{c=l},handlingStack:r?Qe("instrumented method"):void 0}]);const d=n.apply(this,a);return c&&we(c,null,[d]),d};return t[e]=i,{stop:()=>{o=!0,t[e]===i&&(t[e]=n)}}}const Hn=220*z,$n="$",Vn=3;function q(t,e=Hn){const s=Te(Object.prototype),r=Te(Array.prototype),n=[],o=new WeakMap,i=It(t,$n,void 0,n,o),a=JSON.stringify(i);let c=a?a.length:0;if(c>e){Bt(e,"discarded",t);return}for(;n.length>0&&c<e;){const d=n.shift();let l=0;if(Array.isArray(d.source))for(let f=0;f<d.source.length;f++){const u=It(d.source[f],d.path,f,n,o);if(u!==void 0?c+=JSON.stringify(u).length:c+=4,c+=l,l=1,c>e){Bt(e,"truncated",t);break}d.target[f]=u}else for(const f in d.source)if(Object.prototype.hasOwnProperty.call(d.source,f)){const u=It(d.source[f],d.path,f,n,o);if(u!==void 0&&(c+=JSON.stringify(u).length+l+f.length+Vn,l=1),c>e){Bt(e,"truncated",t);break}d.target[f]=u}}return s(),r(),i}function It(t,e,s,r,n){const o=qn(t);if(!o||typeof o!="object")return zn(o);const i=Mt(o);if(i!=="[Object]"&&i!=="[Array]"&&i!=="[Error]")return i;const a=t;if(n.has(a))return\`[Reference seen at \${n.get(a)}]\`;const c=s!==void 0?\`\${e}.\${s}\`:e,d=Array.isArray(o)?[]:{};return n.set(a,c),r.push({source:o,target:d,path:c}),d}function zn(t){return typeof t=="bigint"?\`[BigInt] \${t.toString()}\`:typeof t=="function"?\`[Function] \${t.name||"unknown"}\`:typeof t=="symbol"?\`[Symbol] \${t.description||t.toString()}\`:t}function Mt(t){try{if(t instanceof Event)return jn(t);if(t instanceof RegExp)return\`[RegExp] \${t.toString()}\`;const s=Object.prototype.toString.call(t).match(/\\[object (.*)\\]/);if(s&&s[1])return\`[\${s[1]}]\`}catch{}return"[Unserializable]"}function jn(t){return{type:t.type,isTrusted:t.isTrusted,currentTarget:t.currentTarget?Mt(t.currentTarget):null,target:t.target?Mt(t.target):null}}function qn(t){const e=t;if(e&&typeof e.toJSON=="function")try{return e.toJSON()}catch{}return t}function Bt(t,e,s){M.warn(\`The data provided has been \${e} as it is over the limit of \${t} characters:\`,s)}const yr="No stack, consider using an instance of Error";function xr({stackTrace:t,originalError:e,handlingStack:s,componentStack:r,startClocks:n,nonErrorPrefix:o,source:i,handling:a}){const c=se(e),d=Kn(t,c,o,e),l=Zn(c,t)?de(t):yr,f=c?Dr(e,i):void 0,u=t?t.name:void 0,m=Sr(e),p=Lr(e);return{startClocks:n,source:i,handling:a,handlingStack:s,componentStack:r,originalError:e,type:u,message:d,stack:l,causes:f,fingerprint:m,context:p}}function Kn(t,e,s,r){return t!=null&&t.message&&(t!=null&&t.name)?t.message:e?"Empty message":\`\${s} \${ue(q(r))}\`}function Zn(t,e){return e===void 0?!1:t?!0:e.stack.length>0&&(e.stack.length>1||e.stack[0].url!==void 0)}function Sr(t){return se(t)&&"dd_fingerprint"in t?String(t.dd_fingerprint):void 0}function Lr(t){if(t!==null&&typeof t=="object"&&"dd_context"in t)return t.dd_context}function Jn(t){var e;return(e=/@ (.+)/.exec(t))===null||e===void 0?void 0:e[1]}function se(t){return t instanceof Error||Object.prototype.toString.call(t)==="[object Error]"}function Dr(t,e){let s=t;const r=[];for(;se(s==null?void 0:s.cause)&&r.length<10;){const n=j(s.cause);r.push({message:s.cause.message,source:e,type:n==null?void 0:n.name,stack:de(n)}),s=s.cause}return r.length?r:void 0}const X={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function Qn(t){const e=(n,o)=>{const i=xr({stackTrace:n,originalError:o,startClocks:Q(),nonErrorPrefix:"Uncaught",source:X.SOURCE,handling:"unhandled"});t.notify(i)},{stop:s}=ei(e),{stop:r}=ti(e);return{stop:()=>{s(),r()}}}function ei(t){return fe(window,"onerror",({parameters:[e,s,r,n,o]})=>{let i;se(o)?i=j(o):i=Xn(e,s,r,n),t(i,o??e)})}function ti(t){return fe(window,"onunhandledrejection",({parameters:[e]})=>{const s=e.reason||"Empty reason",r=j(s);t(r,s)})}function ri(t){const e={version:"6.5.0",onReady(s){s()},...t};return Object.defineProperty(e,"_setDebug",{get(){return ys},enumerable:!1}),e}function si(t,e,s){const r=t[e];r&&!r.q&&r.version&&M.warn("SDK is loaded more than once. This is unsupported and might have unexpected behavior."),t[e]=s,r&&r.q&&r.q.forEach(n=>Jt(n,"onReady callback threw an error:")())}function wr(t,e){e.silentMultipleInit||M.error(\`\${t} is already initialized.\`)}function he(t,e,s,r,n){return Nt(t,e,[s],r,n)}function Nt(t,e,s,r,{once:n,capture:o,passive:i}={}){const a=x(u=>{!u.isTrusted&&!u.__ddIsTrusted&&!t.allowUntrustedEvents||(n&&f(),r(u))}),c=i?{capture:o,passive:i}:o,d=window.EventTarget&&e instanceof EventTarget?window.EventTarget.prototype:e,l=ge(d,"addEventListener");s.forEach(u=>l.call(e,u,a,c));function f(){const u=ge(d,"removeEventListener");s.forEach(m=>u.call(e,m,a,c))}return{stop:f}}const et={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function ni(t,e){const s=[];e.includes(et.cspViolation)&&s.push(oi(t));const r=e.filter(n=>n!==et.cspViolation);return r.length&&s.push(ii(r)),or(...s)}function ii(t){return new N(e=>{if(!window.ReportingObserver)return;const s=x((n,o)=>n.forEach(i=>e.notify(ai(i)))),r=new window.ReportingObserver(s,{types:t,buffered:!0});return r.observe(),()=>{r.disconnect()}})}function oi(t){return new N(e=>{const{stop:s}=he(t,document,"securitypolicyviolation",r=>{e.notify(ci(r))});return s})}function ai(t){const{type:e,body:s}=t;return Ur({type:s.id,message:\`\${e}: \${s.message}\`,originalError:t,stack:Pr(s.id,s.message,s.sourceFile,s.lineNumber,s.columnNumber)})}function ci(t){const e=\`'\${t.blockedURI}' blocked by '\${t.effectiveDirective}' directive\`;return Ur({type:t.effectiveDirective,message:\`\${et.cspViolation}: \${e}\`,originalError:t,csp:{disposition:t.disposition},stack:Pr(t.effectiveDirective,t.originalPolicy?\`\${e} of the policy "\${ws(t.originalPolicy,100,"...")}"\`:"no policy",t.sourceFile,t.lineNumber,t.columnNumber)})}function Ur(t){return{startClocks:Q(),source:X.REPORT,handling:"unhandled",...t}}function Pr(t,e,s,r,n){return s?de({name:t,message:e,stack:[{func:"?",url:s,line:r??void 0,column:n??void 0}]}):void 0}function Or(t,e){const s=window.__ddBrowserSdkExtensionCallback;s&&s({type:t,payload:e})}function Cr(t){return t===null?"null":Array.isArray(t)?"array":typeof t}function tt(t,e,s=li()){if(e===void 0)return t;if(typeof e!="object"||e===null)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){const n=e.flags||[e.global?"g":"",e.ignoreCase?"i":"",e.multiline?"m":"",e.sticky?"y":"",e.unicode?"u":""].join("");return new RegExp(e.source,n)}if(s.hasAlreadyBeenSeen(e))return;if(Array.isArray(e)){const n=Array.isArray(t)?t:[];for(let o=0;o<e.length;++o)n[o]=tt(n[o],e[o],s);return n}const r=Cr(t)==="object"?t:{};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=tt(r[n],e[n],s));return r}function Fr(t){return tt(void 0,t)}function be(...t){let e;for(const s of t)s!=null&&(e=tt(e,s));return e}function li(){if(typeof WeakSet<"u"){const e=new WeakSet;return{hasAlreadyBeenSeen(s){const r=e.has(s);return r||e.add(s),r}}}const t=[];return{hasAlreadyBeenSeen(e){const s=t.indexOf(e)>=0;return s||t.push(e),s}}}function ui(){var t;const e=window.navigator;return{status:e.onLine?"connected":"not_connected",interfaces:e.connection&&e.connection.type?[e.connection.type]:void 0,effective_type:(t=e.connection)===null||t===void 0?void 0:t.effectiveType}}function di(t){const e=new Set;return t.forEach(s=>e.add(s)),Array.from(e)}function Ir(t,e){const s=t.indexOf(e);s>=0&&t.splice(s,1)}const fi=500;function Mr(){const t=[];return{add:n=>{t.push(n)>fi&&t.splice(0,1)},remove:n=>{Ir(t,n)},drain:n=>{t.forEach(o=>o(n)),t.length=0}}}const me={log:"log",configuration:"configuration",usage:"usage"},hi=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],mi=[dn];let Br=Mr(),Re=t=>{Br.add(()=>Re(t))};function pi(t,e){let s;const r=new N,n=new Set,o=!mi.includes(e.site)&&Ge(e.telemetrySampleRate),i={[me.log]:o,[me.configuration]:o&&Ge(e.telemetryConfigurationSampleRate),[me.usage]:o&&Ge(e.telemetryUsageSampleRate)},a=gi();Re=d=>{const l=ue(d);if(i[d.type]&&n.size<e.maxTelemetryEventsPerPage&&!n.has(l)){const f=c(t,d,a);r.notify(f),Or("telemetry",f),n.add(l)}},vs(kr);function c(d,l,f){return be({type:"telemetry",date:J(),service:d,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:be(l,{runtime_env:f,connectivity:ui(),sdk_setup:"npm"}),experimental_features:Array.from(Un())},s!==void 0?s():{})}return{setContextProvider:d=>{s=d},observable:r,enabled:o}}function gi(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function Ei(){Br.drain()}function Ti(t){return t.site===ln}function Nr(t,e){Rt(I.debug,t,e),Re({type:me.log,message:t,status:"debug",...e})}function kr(t,e){Re({type:me.log,status:"error",...bi(t),...e})}function Ai(t){Re({type:me.configuration,configuration:t})}function _i(t){Re({type:me.usage,usage:t})}function bi(t){if(se(t)){const e=j(t);return{error:{kind:e.name,stack:de(Ri(e))},message:e.message}}return{error:{stack:yr},message:\`Uncaught \${ue(t)}\`}}function Ri(t){return t.stack=t.stack.filter(e=>!e.url||hi.some(s=>e.url.startsWith(s))),t}const Ie=1/0,vi=oe;let Me=null;const rt=new Set;function yi(){rt.forEach(t=>t())}function xi({expireDelay:t,maxEntries:e}){let s=[];const r=[];Me||(Me=vt(()=>yi(),vi));const n=()=>{const m=Xe()-t;for(;s.length>0&&s[s.length-1].endTime<m;){const p=s.pop();p&&r.push(p.startTime)}};rt.add(n);function o(m,p){const T={value:m,startTime:p,endTime:Ie,remove:()=>{Ir(s,T)},close:h=>{T.endTime=h}};return e&&s.length>=e&&s.pop(),s.unshift(T),T}function i(m=Ie,p={returnInactive:!1}){for(const T of s)if(T.startTime<=m){if(p.returnInactive||m<=T.endTime)return T.value;break}}function a(m){const p=s[0];p&&p.endTime===Ie&&p.close(m)}function c(m=Ie,p=0){const T=As(m,p);return s.filter(h=>h.startTime<=T&&m<=h.endTime).map(h=>h.value)}function d(){return s.map(({startTime:m,endTime:p,value:T})=>({startTime:m,endTime:p===Ie?"Infinity":p,value:T}))}function l(){return r}function f(){s=[]}function u(){rt.delete(n),rt.size===0&&Me&&(ir(Me),Me=null)}return{add:o,find:i,closeActive:a,findAll:c,reset:f,stop:u,getAllEntries:d,getDeletedEntries:l}}const Si=oe,Li=Lt;function Di(t,e,s,r){const n=new N,o=new N,i=nn(t.sessionStoreStrategyType,t,e,s),a=xi({expireDelay:Li});i.renewObservable.subscribe(()=>{a.add(c(),Xe()),n.notify()}),i.expireObservable.subscribe(()=>{o.notify(),a.closeActive(Xe())}),i.expandOrRenewSession(),a.add(c(),Es().relative),r.observable.subscribe(()=>{r.isGranted()?i.expandOrRenewSession():i.expire()}),wi(t,()=>{r.isGranted()&&i.expandOrRenewSession()}),Ui(t,()=>i.expandSession()),Pi(t,()=>i.restartSession());function c(){return{id:i.getSession().id,trackingType:i.getSession()[e],isReplayForced:!!i.getSession().forcedReplay,anonymousId:i.getSession().anonymousId}}return{findSession:(d,l)=>a.find(d,l),renewObservable:n,expireObservable:o,sessionStateUpdateObservable:i.sessionStateUpdateObservable,expire:i.expire,updateSessionState:i.updateSessionState}}function wi(t,e){Nt(t,window,["click","touchstart","keydown","scroll"],e,{capture:!0,passive:!0})}function Ui(t,e){const s=()=>{document.visibilityState==="visible"&&e()};he(t,document,"visibilitychange",s),vt(s,Si)}function Pi(t,e){he(t,window,"resume",e,{capture:!0})}function Gr(t){return t>=500}function Oi(t){try{return t.clone()}catch{return}}const Ci=80*z,Fi=32,Xr=3*tr,Ii=oe,Wr=Se;function Yr(t,e,s,r,n){e.transportStatus===0&&e.queuedPayloads.size()===0&&e.bandwidthMonitor.canHandle(t)?$r(t,e,s,{onSuccess:()=>Vr(0,e,s,r,n),onFailure:()=>{e.queuedPayloads.enqueue(t),Hr(e,s,r,n)}}):e.queuedPayloads.enqueue(t)}function Hr(t,e,s,r){t.transportStatus===2&&Ue(()=>{const n=t.queuedPayloads.first();$r(n,t,e,{onSuccess:()=>{t.queuedPayloads.dequeue(),t.currentBackoffTime=Wr,Vr(1,t,e,s,r)},onFailure:()=>{t.currentBackoffTime=Math.min(Ii,t.currentBackoffTime*2),Hr(t,e,s,r)}})},t.currentBackoffTime)}function $r(t,e,s,{onSuccess:r,onFailure:n}){e.bandwidthMonitor.add(t),s(t,o=>{e.bandwidthMonitor.remove(t),Mi(o)?(e.transportStatus=e.bandwidthMonitor.ongoingRequestCount>0?1:2,t.retry={count:t.retry?t.retry.count+1:1,lastFailureStatus:o.status},n()):(e.transportStatus=0,r())})}function Vr(t,e,s,r,n){t===0&&e.queuedPayloads.isFull()&&!e.queueFullReported&&(n({message:\`Reached max \${r} events size queued for upload: \${Xr/tr}MiB\`,source:X.AGENT,startClocks:Q()}),e.queueFullReported=!0);const o=e.queuedPayloads;for(e.queuedPayloads=zr();o.size()>0;)Yr(o.dequeue(),e,s,r,n)}function Mi(t){return t.type!=="opaque"&&(t.status===0&&!navigator.onLine||t.status===408||t.status===429||Gr(t.status))}function Bi(){return{transportStatus:0,currentBackoffTime:Wr,bandwidthMonitor:Ni(),queuedPayloads:zr(),queueFullReported:!1}}function zr(){const t=[];return{bytesCount:0,enqueue(e){this.isFull()||(t.push(e),this.bytesCount+=e.bytesCount)},first(){return t[0]},dequeue(){const e=t.shift();return e&&(this.bytesCount-=e.bytesCount),e},size(){return t.length},isFull(){return this.bytesCount>=Xr}}}function Ni(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(t){return this.ongoingRequestCount===0||this.ongoingByteCount+t.bytesCount<=Ci&&this.ongoingRequestCount<Fi},add(t){this.ongoingRequestCount+=1,this.ongoingByteCount+=t.bytesCount},remove(t){this.ongoingRequestCount-=1,this.ongoingByteCount-=t.bytesCount}}}function ki(t,e,s){const r=Bi(),n=(o,i)=>Wi(t,e,o,i);return{send:o=>{Yr(o,r,n,t.trackType,s)},sendOnExit:o=>{Gi(t,e,o)}}}function Gi(t,e,s){if(!!navigator.sendBeacon&&s.bytesCount<e)try{const o=t.build("beacon",s);if(navigator.sendBeacon(o,s.data))return}catch(o){Xi(o)}const n=t.build("xhr",s);kt(n,s.data)}let jr=!1;function Xi(t){jr||(jr=!0,kr(t))}function Wi(t,e,s,r){if(Yi()&&s.bytesCount<e){const o=t.build("fetch",s);fetch(o,{method:"POST",body:s.data,keepalive:!0,mode:"cors"}).then(x(i=>r==null?void 0:r({status:i.status,type:i.type})),x(()=>{const i=t.build("xhr",s);kt(i,s.data,r)}))}else{const o=t.build("xhr",s);kt(o,s.data,r)}}function Yi(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function kt(t,e,s){const r=new XMLHttpRequest;r.open("POST",t,!0),e instanceof Blob&&r.setRequestHeader("Content-Type",e.type),he({allowUntrustedEvents:!0},r,"loadend",()=>{s==null||s({status:r.status})},{once:!0}),r.send(e)}function Gt(){const t=Hi();if(t)return{getCapabilities(){var e;return JSON.parse(((e=t.getCapabilities)===null||e===void 0?void 0:e.call(t))||"[]")},getPrivacyLevel(){var e;return(e=t.getPrivacyLevel)===null||e===void 0?void 0:e.call(t)},getAllowedWebViewHosts(){return JSON.parse(t.getAllowedWebViewHosts())},send(e,s,r){const n=r?{id:r}:void 0;t.send(JSON.stringify({eventType:e,event:s,view:n}))}}}function st(t){var e;t===void 0&&(t=(e=ee().location)===null||e===void 0?void 0:e.hostname);const s=Gt();return!!s&&s.getAllowedWebViewHosts().some(r=>t===r||t.endsWith(\`.\${r}\`))}function Hi(){return ee().DatadogEventBridge}const nt={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function $i(t){return new N(e=>{const{stop:s}=Nt(t,window,["visibilitychange","freeze"],n=>{n.type==="visibilitychange"&&document.visibilityState==="hidden"?e.notify({reason:nt.HIDDEN}):n.type==="freeze"&&e.notify({reason:nt.FROZEN})},{capture:!0}),r=he(t,window,"beforeunload",()=>{e.notify({reason:nt.UNLOADING})}).stop;return()=>{s(),r()}})}function Vi(t){return $e(nt).includes(t)}function zi({encoder:t,request:e,flushController:s,messageBytesLimit:r}){let n={};const o=s.flushObservable.subscribe(f=>l(f));function i(f,u,m){s.notifyBeforeAddMessage(u),m!==void 0?(n[m]=f,s.notifyAfterAddMessage()):t.write(t.isEmpty?f:\`
|
|
4
|
+
\${f}\`,p=>{s.notifyAfterAddMessage(p-u)})}function a(f){return f!==void 0&&n[f]!==void 0}function c(f){const u=n[f];delete n[f];const m=t.estimateEncodedBytesCount(u);s.notifyAfterRemoveMessage(m)}function d(f,u){const m=ue(f),p=t.estimateEncodedBytesCount(m);if(p>=r){M.warn(\`Discarded a message whose size was bigger than the maximum allowed size \${r}KB. \${ke} \${Zt}/#technical-limitations\`);return}a(u)&&c(u),i(m,p,u)}function l(f){const u=$e(n).join(\`
|
|
5
|
+
\`);n={};const m=Vi(f.reason),p=m?e.sendOnExit:e.send;if(m&&t.isAsync){const T=t.finishSync();T.outputBytesCount&&p(qr(T));const h=[T.pendingData,u].filter(Boolean).join(\`
|
|
6
|
+
\`);h&&p({data:h,bytesCount:bt(h)})}else u&&t.write(t.isEmpty?u:\`
|
|
7
|
+
\${u}\`),t.finish(T=>{p(qr(T))})}return{flushController:s,add:d,upsert:d,stop:o.unsubscribe}}function qr(t){let e;return typeof t.output=="string"?e=t.output:e=new Blob([t.output],{type:"text/plain"}),{data:e,bytesCount:t.outputBytesCount,encoding:t.encoding}}function ji({messagesLimit:t,bytesLimit:e,durationLimit:s,pageExitObservable:r,sessionExpireObservable:n}){const o=r.subscribe(p=>l(p.reason)),i=n.subscribe(()=>l("session_expire")),a=new N(()=>()=>{o.unsubscribe(),i.unsubscribe()});let c=0,d=0;function l(p){if(d===0)return;const T=d,h=c;d=0,c=0,m(),a.notify({reason:p,messagesCount:T,bytesCount:h})}let f;function u(){f===void 0&&(f=Ue(()=>{l("duration_limit")},s))}function m(){nr(f),f=void 0}return{flushObservable:a,get messagesCount(){return d},notifyBeforeAddMessage(p){c+p>=e&&l("bytes_limit"),d+=1,c+=p,u()},notifyAfterAddMessage(p=0){c+=p,d>=t?l("messages_limit"):c>=e&&l("bytes_limit")},notifyAfterRemoveMessage(p){c-=p,d-=1,d===0&&m()}}}function Kr(t,e,s,r,n,o,i=zi){const a=d(t,e),c=s&&d(t,s);function d(l,{endpoint:f,encoder:u}){return i({encoder:u,request:ki(f,l.batchBytesLimit,r),flushController:ji({messagesLimit:l.batchMessagesLimit,bytesLimit:l.batchBytesLimit,durationLimit:l.flushTimeout,pageExitObservable:n,sessionExpireObservable:o}),messageBytesLimit:l.messageBytesLimit})}return{flushObservable:a.flushController.flushObservable,add(l,f=!0){a.add(l),c&&f&&c.add(s.transformMessage?s.transformMessage(l):l)},upsert:(l,f)=>{a.upsert(l,f),c&&c.upsert(s.transformMessage?s.transformMessage(l):l,f)},stop:()=>{a.stop(),c&&c.stop()}}}function it(){let t="",e=0;return{isAsync:!1,get isEmpty(){return!t},write(s,r){const n=bt(s);e+=n,t+=s,r&&r(n)},finish(s){s(this.finishSync())},finishSync(){const s={output:t,outputBytesCount:e,rawBytesCount:e,pendingData:""};return t="",e=0,s},estimateEncodedBytesCount(s){return s.length}}}class qi{constructor(){this.callbacks={}}notify(e,s){const r=this.callbacks[e];r&&r.forEach(n=>n(s))}subscribe(e,s){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(s),{unsubscribe:()=>{this.callbacks[e]=this.callbacks[e].filter(r=>s!==r)}}}}function Ki(t,e,s){let r=0,n=!1;return{isLimitReached(){if(r===0&&Ue(()=>{r=0},oe),r+=1,r<=e||n)return n=!1,!1;if(r===e+1){n=!0;try{s({message:\`Reached max number of \${t}s by minute: \${e}\`,source:X.AGENT,startClocks:Q()})}finally{n=!1}}return!0}}}let Xt;const Wt=new WeakMap;function Zi(t){return Xt||(Xt=Ji(t)),Xt}function Ji(t){return new N(e=>{const{stop:s}=fe(XMLHttpRequest.prototype,"open",Qi),{stop:r}=fe(XMLHttpRequest.prototype,"send",o=>{eo(o,t,e)},{computeHandlingStack:!0}),{stop:n}=fe(XMLHttpRequest.prototype,"abort",to);return()=>{s(),r(),n()}})}function Qi({target:t,parameters:[e,s]}){Wt.set(t,{state:"open",method:String(e).toUpperCase(),url:Pt(String(s))})}function eo({target:t,handlingStack:e},s,r){const n=Wt.get(t);if(!n)return;const o=n;o.state="start",o.startClocks=Q(),o.isAborted=!1,o.xhr=t,o.handlingStack=e;let i=!1;const{stop:a}=fe(t,"onreadystatechange",()=>{t.readyState===XMLHttpRequest.DONE&&c()}),c=()=>{if(d(),a(),i)return;i=!0;const l=n;l.state="complete",l.duration=Ts(o.startClocks.timeStamp,J()),l.status=t.status,r.notify(Rs(l))},{stop:d}=he(s,t,"loadend",c);r.notify(o)}function to({target:t}){const e=Wt.get(t);e&&(e.isAborted=!0)}let Yt;function Zr(){return Yt||(Yt=ro()),Yt}function ro(){return new N(t=>{if(!window.fetch)return;const{stop:e}=fe(window,"fetch",s=>so(s,t),{computeHandlingStack:!0});return e})}function so({parameters:t,onPostCall:e,handlingStack:s},r){const[n,o]=t;let i=o&&o.method;i===void 0&&n instanceof Request&&(i=n.method);const a=i!==void 0?String(i).toUpperCase():"GET",c=n instanceof Request?n.url:Pt(String(n)),d=Q(),l={state:"start",init:o,input:n,method:a,startClocks:d,url:c,handlingStack:s};r.notify(l),t[0]=l.input,t[1]=l.init,e(f=>no(r,f,l))}function no(t,e,s){const r=s;function n(o){r.state="resolve",Object.assign(r,o),t.notify(r)}e.then(x(o=>{n({response:o,responseType:o.type,status:o.status,isAborted:!1})}),x(o=>{var i,a;n({status:0,isAborted:((a=(i=r.init)===null||i===void 0?void 0:i.signal)===null||a===void 0?void 0:a.aborted)||o instanceof DOMException&&o.code===DOMException.ABORT_ERR,error:o})}))}let Ht={};function io(t){const e=t.map(s=>(Ht[s]||(Ht[s]=oo(s)),Ht[s]));return or(...e)}function oo(t){return new N(e=>{const s=H[t];return H[t]=(...r)=>{s.apply(console,r);const n=Qe("console error");we(()=>{e.notify(ao(r,t,n))})},()=>{H[t]=s}})}function ao(t,e,s){const r=t.map(o=>co(o)).join(" ");let n;if(e===I.error){const o=t.find(se);n={stack:o?de(j(o)):void 0,fingerprint:Sr(o),causes:o?Dr(o,"console"):void 0,startClocks:Q(),message:r,source:X.CONSOLE,handling:"handled",handlingStack:s,context:Lr(o)}}return{api:e,message:r,error:n,handlingStack:s}}function co(t){return typeof t=="string"?q(t):se(t)?vr(j(t)):ue(q(t),void 0,2)}function lo(t){const e=Cr(t)==="object";return e||M.error("Unsupported context:",t),e}function $t(t,e,s){const r={...t};for(const[n,{required:o,type:i}]of Object.entries(e))i==="string"&&n in r&&(r[n]=String(r[n])),o&&!(n in t)&&M.warn(\`The property \${n} of \${s} is required; context will not be sent to the intake.\`);return r}function ot(t="",{customerDataTracker:e,propertiesConfig:s={}}={}){let r={};const n=new N,o={getContext:()=>Fr(r),setContext:i=>{lo(i)?(r=q($t(i,s,t)),e==null||e.updateCustomerData(r)):o.clearContext(),n.notify()},setContextProperty:(i,a)=>{r=q($t({...r,[i]:a},s,t)),e==null||e.updateCustomerData(r),n.notify()},removeContextProperty:i=>{delete r[i],e==null||e.updateCustomerData(r),$t(r,s,t),n.notify()},clearContext:()=>{r={},e==null||e.resetCustomerData(),n.notify()},changeObservable:n};return o}const uo="_dd_c",fo=[];function Vt(t,e,s,r){const n=ho(s,r);fo.push(he(t,window,"storage",({key:d})=>{n===d&&i()})),e.changeObservable.subscribe(a);const o=be(c(),e.getContext());De(o)||e.setContext(o);function i(){e.setContext(c())}function a(){localStorage.setItem(n,JSON.stringify(e.getContext()))}function c(){const d=localStorage.getItem(n);return d?JSON.parse(d):{}}}function ho(t,e){return\`\${uo}_\${t}_\${e}\`}const mo=3*z,po=16*z,go=200;function Eo(t=2){const e=new Map;let s=!1;function r(n=0){if(s||t===0)return;const o=t===2?mo:po;let i=n;e.forEach(a=>{i+=a.getBytesCount()}),i>o&&(To(o),s=!0)}return{createDetachedTracker:()=>{const n=Jr(()=>r(n.getBytesCount()));return n},getOrCreateTracker:n=>(e.has(n)||e.set(n,Jr(r)),e.get(n)),setCompressionStatus:n=>{t===0&&(t=n,r())},getCompressionStatus:()=>t,stop:()=>{e.forEach(n=>n.stop()),e.clear()}}}function Jr(t){let e=0;const{throttled:s,cancel:r}=ar(o=>{e=bt(ue(o)),t()},go),n=()=>{r(),e=0};return{updateCustomerData:o=>{De(o)?n():s(o)},resetCustomerData:n,getBytesCount:()=>e,stop:()=>{r()}}}function To(t){M.warn(\`Customer data exceeds the recommended \${t/z}KiB threshold. \${ke} \${Zt}/#customer-data-exceeds-the-recommended-threshold-warning\`)}function Ao(t,e,s){const r=t.getReader(),n=[];let o=0;i();function i(){r.read().then(x(c=>{if(c.done){a();return}n.push(c.value),o+=c.value.length,o>s.bytesLimit?a():i()}),x(c=>e(c)))}function a(){r.cancel().catch(te);let c,d;{let l;if(n.length===1)l=n[0];else{l=new Uint8Array(o);let f=0;n.forEach(u=>{l.set(u,f),f+=u.length})}c=l.slice(0,s.bytesLimit),d=l.length>s.bytesLimit}e(void 0,c,d)}}const _o="datadog-synthetics-public-id",bo="datadog-synthetics-result-id",Ro="datadog-synthetics-injects-rum";function Qr(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||ae(Ro))}function vo(){const t=window._DATADOG_SYNTHETICS_PUBLIC_ID||ae(_o);return typeof t=="string"?t:void 0}function yo(){const t=window._DATADOG_SYNTHETICS_RESULT_ID||ae(bo);return typeof t=="string"?t:void 0}function at(t,e,s){const r=s.getHandler(),n=Array.isArray(r)?r:[r];return es[t]>=es[s.getLevel()]&&n.includes(e)}const R={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},es={[R.ok]:0,[R.debug]:1,[R.info]:2,[R.notice]:4,[R.warn]:5,[R.error]:6,[R.critical]:7,[R.alert]:8,[R.emerg]:9};function ct(t,{includeMessage:e=!1}={}){return{stack:t.stack,kind:t.type,message:e?t.message:void 0,causes:t.causes,fingerprint:t.fingerprint,handling:t.handling}}var xo=function(t,e,s,r){var n=arguments.length,o=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,s):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(t,e,s,r);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(o=(n<3?i(o):n>3?i(e,s,o):i(e,s))||o);return n>3&&o&&Object.defineProperty(e,s,o),o};const Be={console:"console",http:"http",silent:"silent"},So=Object.keys(R);let Y=class{constructor(e,s,r,n=Be.http,o=R.debug,i={}){this.handleLogStrategy=e,this.handlerType=n,this.level=o,this.contextManager=ot("logger",{customerDataTracker:s}),this.contextManager.setContext(i),r&&this.contextManager.setContextProperty("logger",{name:r})}logImplementation(e,s,r=R.info,n,o){const i=q(s);let a;if(n!=null){const c=xr({stackTrace:se(n)?j(n):void 0,originalError:n,nonErrorPrefix:"Provided",source:X.LOGGER,handling:"handled",startClocks:Q()});a=be({error:ct(c,{includeMessage:!0})},i)}else a=i;this.handleLogStrategy({message:q(e),context:a,status:r},this,o)}log(e,s,r=R.info,n){let o;at(r,Be.http,this)&&(o=Qe("log")),this.logImplementation(e,s,r,n,o)}setContext(e){this.contextManager.setContext(e)}getContext(){return this.contextManager.getContext()}setContextProperty(e,s){this.contextManager.setContextProperty(e,s)}removeContextProperty(e){this.contextManager.removeContextProperty(e)}clearContext(){this.contextManager.clearContext()}setHandler(e){this.handlerType=e}getHandler(){return this.handlerType}setLevel(e){this.level=e}getLevel(){return this.level}};xo([xs],Y.prototype,"logImplementation",null),Y.prototype.ok=K(R.ok),Y.prototype.debug=K(R.debug),Y.prototype.info=K(R.info),Y.prototype.notice=K(R.notice),Y.prototype.warn=K(R.warn),Y.prototype.error=K(R.error),Y.prototype.critical=K(R.critical),Y.prototype.alert=K(R.alert),Y.prototype.emerg=K(R.emerg);function K(t){return function(e,s,r){let n;at(t,Be.http,this)&&(n=Qe("log")),this.logImplementation(e,s,t,r,n)}}function Lo(t,e,s){return{view:{referrer:document.referrer,url:window.location.href},context:t.getContext(),user:e.getContext(),account:s.getContext()}}const Do=32*z;function wo(t){t.usePciIntake===!0&&t.site&&t.site!=="datadoghq.com"&&M.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");const e=Sn(t),s=ts(t.forwardConsoleLogs,$e(I),"Forward Console Logs"),r=ts(t.forwardReports,$e(et),"Forward Reports");if(!(!e||!s||!r))return t.forwardErrorsToLogs&&!s.includes(I.error)&&s.push(I.error),{forwardErrorsToLogs:t.forwardErrorsToLogs!==!1,forwardConsoleLogs:s,forwardReports:r,requestErrorResponseLengthLimit:Do,...e}}function ts(t,e,s){if(t===void 0)return[];if(!(t==="all"||Array.isArray(t)&&t.every(r=>e.includes(r)))){M.error(\`\${s} should be "all" or an array with allowed values "\${e.join('", "')}"\`);return}return t==="all"?e:di(t)}function Uo(t){const e=Ln(t);return{forward_errors_to_logs:t.forwardErrorsToLogs,forward_console_logs:t.forwardConsoleLogs,forward_reports:t.forwardReports,use_pci_intake:t.usePciIntake,...e}}function Po(t,e,s){const r=Mr();let n,o;const i=e.observable.subscribe(a);function a(){if(!o||!n||!e.isGranted())return;i.unsubscribe();const c=s(n,o);r.drain(c)}return{init(c){if(!c){M.error("Missing configuration");return}if(Dn(c.enableExperimentalFeatures),st()&&(c=Oo(c)),n=c,o){wr("DD_LOGS",c);return}const d=wo(c);d&&(o=d,Zr().subscribe(te),e.tryToInit(d.trackingConsent),a())},get initConfiguration(){return n},getInternalContext:te,handleLog(c,d,l,f=t(),u=J()){r.add(m=>m.handleLog(c,d,l,f,u))}}}function Oo(t){return{...t,clientToken:"empty"}}const zt="logs";function Co(t){const e=Eo(),s=ot("global context",{customerDataTracker:e.getOrCreateTracker(2)}),r=ot("user",{customerDataTracker:e.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),n=ot("account",{customerDataTracker:e.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),o=on();function i(){return Lo(s,r,n)}let a=Po(i,o,(l,f)=>{l.storeContextsAcrossPages&&(Vt(f,s,zt,2),Vt(f,r,zt,1),Vt(f,n,zt,4));const u=t(l,f,i,o);return a=Fo(l,u),u});const c={},d=new Y((...l)=>a.handleLog(...l),e.createDetachedTracker());return ri({logger:d,init:x(l=>a.init(l)),setTrackingConsent:x(l=>{o.update(l),_i({feature:"set-tracking-consent",tracking_consent:l})}),getGlobalContext:x(()=>s.getContext()),setGlobalContext:x(l=>s.setContext(l)),setGlobalContextProperty:x((l,f)=>s.setContextProperty(l,f)),removeGlobalContextProperty:x(l=>s.removeContextProperty(l)),clearGlobalContext:x(()=>s.clearContext()),createLogger:x((l,f={})=>(c[l]=new Y((...u)=>a.handleLog(...u),e.createDetachedTracker(),q(l),f.handler,f.level,q(f.context)),c[l])),getLogger:x(l=>c[l]),getInitConfiguration:x(()=>Fr(a.initConfiguration)),getInternalContext:x(l=>a.getInternalContext(l)),setUser:x(r.setContext),getUser:x(r.getContext),setUserProperty:x(r.setContextProperty),removeUserProperty:x(r.removeContextProperty),clearUser:x(r.clearContext),setAccount:x(n.setContext),getAccount:x(n.getContext),setAccountProperty:x(n.setContextProperty),removeAccountProperty:x(n.removeContextProperty),clearAccount:x(n.clearContext)})}function Fo(t,e){return{init:s=>{wr("DD_LOGS",s)},initConfiguration:t,...e}}const Io="logs";function Mo(t,e){const s=Di(t,Io,r=>No(t,r),e);return{findTrackedSession:(r,n={returnInactive:!1})=>{const o=s.findSession(r,n);return o&&o.trackingType==="1"?{id:o.id,anonymousId:o.anonymousId}:void 0},expireObservable:s.expireObservable}}function Bo(t){const s=rs(t)==="1"?{}:void 0;return{findTrackedSession:()=>s,expireObservable:new N}}function rs(t){return Ge(t.sessionSampleRate)?"1":"0"}function No(t,e){const s=ko(e)?e:rs(t);return{trackingType:s,isTracked:s==="1"}}function ko(t){return t==="0"||t==="1"}let ss=!1;function lt(t){const e=window;if(Qr()){const r=s(e.DD_RUM_SYNTHETICS);return!r&&!ss&&(ss=!0,Nr("Logs sent before RUM is injected by the synthetics worker",{testId:vo(),resultId:yo()})),r}return s(e.DD_RUM);function s(r){if(r&&r.getInternalContext)return r.getInternalContext(t)}}function Go(t,e,s,r,n){const o=So.concat(["custom"]),i={};o.forEach(a=>{i[a]=Ki(a,e.eventRateLimiterThreshold,n)}),s.subscribe(0,({rawLogsEvent:a,messageContext:c=void 0,savedCommonContext:d=void 0,domainContext:l})=>{var f,u;const m=_s(a.date),p=t.findTrackedSession(m);if(!t.findTrackedSession(m,{returnInactive:!0}))return;const h=d||r();let _;!De(h.account)&&h.account.id&&(_=h.account),p&&p.anonymousId&&!h.user.anonymous_id&&(h.user.anonymous_id=p.anonymousId);const y=be({service:e.service,session_id:p?p.id:void 0,session:p?{id:p.id}:void 0,usr:De(h.user)?void 0:h.user,account:_,view:h.view},h.context,lt(m),a,c);((f=e.beforeSend)===null||f===void 0?void 0:f.call(e,y,l))===!1||y.origin!==X.AGENT&&((u=i[y.status])!==null&&u!==void 0?u:i.custom).isLimitReached()||s.notify(1,y)})}const Xo={[I.log]:R.info,[I.debug]:R.debug,[I.info]:R.info,[I.warn]:R.warn,[I.error]:R.error};function Wo(t,e){const s=io(t.forwardConsoleLogs).subscribe(r=>{var n;const o={rawLogsEvent:{date:J(),message:r.message,origin:X.CONSOLE,error:r.error&&ct(r.error),status:Xo[r.api]},messageContext:(n=r.error)===null||n===void 0?void 0:n.context,domainContext:{handlingStack:r.handlingStack}};e.notify(0,o)});return{stop:()=>{s.unsubscribe()}}}function Yo(t,e){const s=ni(t,t.forwardReports).subscribe(r=>{let n=r.message,o;const i=r.originalError.type==="deprecation"?R.warn:R.error;i===R.error?o=ct(r):r.stack&&(n+=\` Found in \${Jn(r.stack)}\`),e.notify(0,{rawLogsEvent:{date:J(),message:n,origin:X.REPORT,error:o,status:i}})});return{stop:()=>{s.unsubscribe()}}}function Ho(t,e){if(!t.forwardErrorsToLogs)return{stop:te};const s=Zi(t).subscribe(o=>{o.state==="complete"&&n("xhr",o)}),r=Zr().subscribe(o=>{o.state==="resolve"&&n("fetch",o)});function n(o,i){!yn(i.url)&&(jo(i)||Gr(i.status))&&("xhr"in i?$o(i.xhr,t,a):i.response?zo(i.response,t,a):i.error&&Vo(i.error,t,a));function a(c){const d={isAborted:i.isAborted,handlingStack:i.handlingStack};e.notify(0,{rawLogsEvent:{message:\`\${qo(o)} error \${i.method} \${i.url}\`,date:i.startClocks.timeStamp,error:{stack:c||"Failed to load",handling:void 0},http:{method:i.method,status_code:i.status,url:i.url},status:R.error,origin:X.NETWORK},domainContext:d})}}return{stop:()=>{s.unsubscribe(),r.unsubscribe()}}}function $o(t,e,s){typeof t.response=="string"?s(jt(t.response,e)):s(t.response)}function Vo(t,e,s){s(jt(de(j(t)),e))}function zo(t,e,s){const r=Oi(t);!r||!r.body?s():window.TextDecoder?Ko(r.body,e.requestErrorResponseLengthLimit,(n,o)=>{s(n?\`Unable to retrieve response: \${n}\`:o)}):r.text().then(x(n=>s(jt(n,e))),x(n=>s(\`Unable to retrieve response: \${n}\`)))}function jo(t){return t.status===0&&t.responseType!=="opaque"}function jt(t,e){return t.length>e.requestErrorResponseLengthLimit?\`\${t.substring(0,e.requestErrorResponseLengthLimit)}...\`:t}function qo(t){return t==="xhr"?"XHR":"Fetch"}function Ko(t,e,s){Ao(t,(r,n,o)=>{if(r)s(r);else{let i=new TextDecoder().decode(n);o&&(i+="..."),s(void 0,i)}},{bytesLimit:e,collectStreamBody:!0})}function Zo(t,e){if(!t.forwardErrorsToLogs)return{stop:te};const s=new N,{stop:r}=Qn(s),n=s.subscribe(o=>{e.notify(0,{rawLogsEvent:{message:o.message,date:o.startClocks.timeStamp,error:ct(o),origin:X.SOURCE,status:R.error},messageContext:o.context})});return{stop:()=>{r(),n.unsubscribe()}}}const Jo=qi;function Qo(t){function e(s,r,n,o,i){const a=be(r.getContext(),s.context);if(at(s.status,Be.console,r)&&ta(s,a),at(s.status,Be.http,r)){const c={rawLogsEvent:{date:i||J(),message:s.message,status:s.status,origin:X.LOGGER},messageContext:a,savedCommonContext:o};n&&(c.domainContext={handlingStack:n}),t.notify(0,c)}}return{handleLog:e}}const ea={[R.ok]:I.debug,[R.debug]:I.debug,[R.info]:I.info,[R.notice]:I.info,[R.warn]:I.warn,[R.error]:I.error,[R.critical]:I.error,[R.alert]:I.error,[R.emerg]:I.error};function ta({status:t,message:e},s){ie[ea[t]].call(H,e,s)}function ra(t,e,s,r,n){const o=Kr(t,{endpoint:t.logsEndpointBuilder,encoder:it()},t.replica&&{endpoint:t.replica.logsEndpointBuilder,encoder:it()},s,r,n.expireObservable);return e.subscribe(1,i=>{o.add(i)}),o}function sa(t){const e=Gt();t.subscribe(1,s=>{e.send("log",s)})}function na(t){return{get:e=>{const s=t.findTrackedSession(e);if(s)return{session_id:s.id}}}}function ia(t){return e=>{t.notify(0,{rawLogsEvent:{message:e.message,date:e.startClocks.timeStamp,origin:X.AGENT,status:R.error}}),Nr("Error reported to customer",{"error.message":e.message})}}function oa(t,e,s,r,n){const o=pi("browser-logs-sdk",e);o.setContextProvider(()=>{var a,c,d,l,f,u;return{application:{id:(a=lt())===null||a===void 0?void 0:a.application_id},session:{id:(c=n.findTrackedSession())===null||c===void 0?void 0:c.id},view:{id:(l=(d=lt())===null||d===void 0?void 0:d.view)===null||l===void 0?void 0:l.id},action:{id:(u=(f=lt())===null||f===void 0?void 0:f.user_action)===null||u===void 0?void 0:u.id}}});const i=[];if(st()){const a=Gt(),c=o.observable.subscribe(d=>a.send("internal_telemetry",d));i.push(()=>c.unsubscribe())}else{const a=Kr(e,{endpoint:e.rumEndpointBuilder,encoder:it()},e.replica&&{endpoint:e.replica.rumEndpointBuilder,encoder:it()},s,r,n.expireObservable);i.push(()=>a.stop());const c=o.observable.subscribe(d=>a.add(d,Ti(e)));i.push(()=>c.unsubscribe())}return Ei(),Ai(Uo(t)),{telemetry:o,stop:()=>{i.forEach(a=>a())}}}function aa(t,e,s,r){const n=new Jo,o=[];n.subscribe(1,u=>Or("logs",u));const i=ia(n),a=$i(e),c=e.sessionStoreStrategyType&&!st()&&!Qr()?Mo(e,r):Bo(e),{stop:d}=oa(t,e,i,a,c);o.push(()=>d()),Ho(e,n),Zo(e,n),Wo(e,n),Yo(e,n);const{handleLog:l}=Qo(n);if(Go(c,e,n,s,i),st())sa(n);else{const{stop:u}=ra(e,n,i,a,c);o.push(()=>u())}const f=na(c);return{handleLog:l,getInternalContext:f.get,stop:()=>{o.forEach(u=>u())}}}const ve=Co(aa);si(ee(),"DD_LOGS",ve);const k=class k{constructor(e,s,r,n,o){this.copy=()=>new k(this.h,this.m,this.s,this.f,this.field),this.print=()=>{const i=":";let a=("0"+this.h).slice(-2)+i+("0"+this.m).slice(-2)+i+("0"+this.s).slice(-2)+i+("0"+this.f).slice(-2);return a+="."+(this.field?"1":"2"),a},this.toZipTimeCodeString=()=>{const i=this.copy();return i.f=0,i.s=i.s%2===0?i.s:i.s-1,i.field=0,k.toStr(i)},this.toFrames=i=>{let a=60,c=0;Math.floor(i)==60?(a=60,c=0):Math.floor(i)==59?(a=60,c=4):Math.floor(i)==30?(a=30,c=0):Math.floor(i)==29&&(a=30,c=2);let d=this.h,l=this.m,f=this.s,u=this.f,m=this.field;const p=d*60+l,h=(p-Math.floor(p/10))*c;return d*(a*3600)+l*(a*60)+f*a+(u*2+m)-h},this.addSeconds=i=>{let a=this.copy();if(a.s+=i,a.s>=60){const c=Math.floor(a.s/60);if(a.s=a.s%60,a.m+=c,a.m>=60){const d=Math.floor(a.m/60);a.m=a.m%60,a.h+=d}}return a},this.addFrames=(i,a)=>{let c=this.toFrames(a);return c+=i,k.fromFrames(c,a)},this.subtractFrames=(i,a)=>this.addFrames(-i,a),this.h=e||0,this.m=s||0,this.s=r||0,this.f=n||0,this.field=o||0}static compare(e,s){return e.h!==s.h?e.h<s.h?-1:1:e.m!==s.m?e.m<s.m?-1:1:e.s!==s.s?e.s<s.s?-1:1:e.f!==s.f?e.f<s.f?-1:1:e.field!==s.field?e.field<s.field?-1:1:0}static generateTimecodeRange(e,s,r){const n=[];let o=e;for(;k.compare(o,s)<=0;)n.push(o),o=o.addSeconds(r);return n}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(e){return this.toFrames(e)*1e3/e}};k.calculateCurrentTimeCode=e=>{var f;if(!e.video||!e.clocker||!e.gameParams)throw new Error("OTTPlayer is not initialized");const s=e.video,r=e.clocker,n=r.videoFPScalculator.getFPS(),a=(s.currentTime-r.syncPoint.playerTime)%(60*60*24)*n+r.syncPoint.frame;if(a===0||n===0)throw new Error("Current frame is 0 or fps is 0");const c=k.calculateCurrentOffset(a,(f=e.gameParams)==null?void 0:f.offsets);if(c===void 0)throw new Error("Offset is undefined");let d=Math.floor(a-c);return d<0&&(d+=5178816),d>=5178816&&(d-=5178816),k.fromFrames(d,n)},k.calculateCurrentOffset=(e,s)=>{for(let r=1;r<s.length;r++)if(e<s[r].frame)return s[r-1].offset;return Math.abs(s[s.length-1].offset)},k.fromFrames=(e,s)=>{let r=60,n=0;Math.floor(s)==60?(r=60,n=0):Math.floor(s)==59?(r=60,n=4):Math.floor(s)==30?(r=30,n=0):Math.floor(s)==29&&(r=30,n=2);let o=Math.floor(s*60),i=Math.floor(s*60*10),a=i*6,c=e,d=Math.floor(c/a);c-=d*a;let l=Math.floor(c/i);c-=l*i,c>=r*60&&(c+=n*(Math.floor((c-r*60)/o)+1));let f=Math.floor(c/(r*60));c-=f*(r*60);let u=Math.floor(c/r);c-=u*r;let m=c;f+=l*10;let p=0;return p=m%2,m=Math.floor(m/2),new k(d,f,u,m,p)},k.toStr=e=>{const s="_";let r=("0"+e.h).slice(-2)+s+("0"+e.m).slice(-2)+s+("0"+e.s).slice(-2)+s+("0"+e.f).slice(-2);return e.field&&(r+="_1"),r},k.fromStr=e=>{const r=e.split("_").map(Number);if(r.length==4){const[n,o,i,a]=r;return new k(n,o,i,a,0)}else if(r.length==5){const[n,o,i,a,c]=r;return new k(n,o,i,a,c)}else throw new Error("Invalid timecode format: "+e)},k.fromMetadata=e=>{const s=/^(\\d{2}):(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d))?$/,r=e.timecode.match(s);if(!r)throw new Error("Invalid timecode format: "+e.timecode);const[,n,o,i,a,c]=r,d=Number(n),l=Number(o),f=Number(i),u=Number(a),m=c?Number(c):0;return new k(d,l,f,u,m)};let $=k;const E=class E{constructor(e){this.listenerMap=new Map,E.options=e,this.isLoggingOn=e.LOG_TO_DATADOG,this.eventTarget=new EventTarget,this.isLoggingOn&&ve.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!1,sessionSampleRate:100});const s="bb_logger_mac_uuid";let r=localStorage.getItem(s);r||(r=crypto.randomUUID(),localStorage.setItem(s,r)),E.tracking.mac=r,E.tracking.dev=\`\${e.platform}_\${e.browserName}\`,E.beatHandle||(E.options&&g(E.options,"Logger")&&console.log("[Logger] Starting tracking beat"),E.beatHandle=window.setInterval(E.flushTracking,15e3))}static setMessagePort(e){this.messagePort=e}static getMessagePort(){return this.messagePort}setLoggingOn(e){this.isLoggingOn=e}addEventListener(e,s){const r=n=>s(n);this.listenerMap.set(s,{eventName:e,wrappedListener:r}),this.eventTarget.addEventListener(e,r)}removeEventListener(e,s){const r=this.listenerMap.get(s);r&&r.eventName===e&&(this.eventTarget.removeEventListener(e,r.wrappedListener),this.listenerMap.delete(s))}removeAllEventListeners(){for(const[e,{eventName:s,wrappedListener:r}]of this.listenerMap)this.eventTarget.removeEventListener(s,r);this.listenerMap.clear()}setAttributes(e){E.processAttributes(e);for(const s in e)ve.logger.setContextProperty(s,e[s])}info(e,s){e==="didClickAd"&&this.emit("mediaSessionDidRegisterClick",{url:(s==null?void 0:s.url)||""}),e==="didToggleGlobalAugmentationDrawing"&&this.emit("mediaSessionDidUpdateGlobalAugmentationState",{isGlobalAugmentationEnabled:(s==null?void 0:s.isEnabled)||!0}),e==="didStartDrawingAugmentationMedia"&&this.emit("mediaSessionDidBeginShotRendering",s),e==="didEndDrawingAugmentationMedia"&&this.emit("mediaSessionDidEndShotRendering",s),e==="didRegisterShot"&&this.emit("mediaSessionDidRegisterShot",s),s&&E.processAttributes(s),this.isLoggingOn&&(ve.logger.info(e,s),E.options&&g(E.options,"Logger")&&console.log("[Logger] Sending info: ",e))}error(e,s){s&&E.processAttributes(s),this.isLoggingOn&&(ve.logger.error(e,s),E.tracking.err_time=Date.now().toFixed(0),E.tracking.err_desc=e+(s?\` - \${JSON.stringify(s)}\`:""),E.options&&g(E.options,"Logger")&&console.log("[Logger] Sending error: ",e))}warn(e,s){s&&E.processAttributes(s),this.isLoggingOn&&(ve.logger.warn(e,s),E.options&&g(E.options,"Logger")&&console.log("[Logger] Sending warn: ",e))}handleMessageFromWorker(e){e.actionType==="INFO"?this.info(e.message,e.attributes):e.actionType==="ERROR"?this.error(e.message,e.attributes):e.actionType==="WARN"?this.warn(e.message,e.attributes):e.actionType==="SET_ATTRIBUTES"&&e.attributes&&this.setAttributes(e.attributes)}static setAttributes(e){if(!E.messagePort){console.error("[Logger] messagePort is not set! Cannot send attributes.");return}try{E.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:e})}catch(s){console.error("[Logger] Error posting message:",s)}}static info(e,s){E.messagePort.postMessage({type:"LOG",actionType:"INFO",message:e,attributes:s})}static error(e,s){E.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:e,attributes:s})}static warn(e,s){E.messagePort.postMessage({type:"LOG",actionType:"WARN",message:e,attributes:s})}static processAttributes(e){if(e.player_version&&(E.tracking.sdk=e.player_version),e.media_id&&(E.tracking.gid=e.media_id),e.game_id&&(E.tracking.buc=e.game_id),e.bb_session_id&&(E.tracking.sid=e.bb_session_id,E.options&&g(E.options,"Logger")&&console.log("[Logger] Setting bb_session_id:",E.tracking.sid)),e.last_timecode){const r=$.fromStr(e.last_timecode);E.tracking.tc=r.print(),E.lastTimecodeMillis=r.totalMilliseconds(59.94),E.lastTimecodeMillis&&E.lastZipMillis&&(E.tracking.cache=(E.lastZipMillis-E.lastTimecodeMillis).toFixed(0))}e.last_offset&&(E.tracking.off=e.last_offset),e.last_loading_zip&&(E.tracking.zip=e.last_loading_zip+".zip",E.lastZipMillis=$.fromStr(e.last_loading_zip).totalMilliseconds(59.94),E.lastTimecodeMillis&&E.lastZipMillis&&(E.tracking.cache=(E.lastZipMillis-E.lastTimecodeMillis).toFixed(0))),e.last_rendered_frame&&(E.tracking.aug_time=Date.now().toFixed(0)),e.asset&&(E.tracking.asset=e.asset)}static objectToQuery(e){return Object.entries(e).filter(([s,r])=>r!==0&&r!=="").map(([s,r])=>\`\${encodeURIComponent(s)}=\${encodeURIComponent(String(r))}\`).join("&")}emit(e,s){const r=new CustomEvent(e,{detail:s});this.eventTarget.dispatchEvent(r)}};E.tracking={start:Date.now().toFixed(0),dev:"",sdk:"",mac:"",gid:"",sid:"",off:"",zip:"",aug_time:"",err_time:"",err_desc:"",tc:"",asset:"",cache:"",buc:""},E.lastTimecodeMillis=0,E.lastZipMillis=0,E.flushTracking=()=>{const e=Date.now().toFixed(0);E.tracking.now=e;const r=\`https://dwu3k7rrxk5s3.cloudfront.net/metrics/1.gif?\${E.objectToQuery(E.tracking)}\`;E.options&&g(E.options,"Logger")&&console.log("[Logger] Flushing tracking data:",r),fetch(r,{method:"GET",mode:"no-cors",keepalive:!0,headers:{"X-Platform":"Web"}}).catch(()=>{}),E.tracking.err_desc="",E.tracking.err_time=""};let O=E;const ca=\`
|
|
8
8
|
attribute vec2 a_position;
|
|
9
9
|
attribute vec2 a_uv;
|
|
10
10
|
|
|
@@ -380,20 +380,20 @@ void main(){
|
|
|
380
380
|
// keep your current vertical AA:
|
|
381
381
|
gl_FragColor = vec4(tex.rgb, tex.a * coverage);
|
|
382
382
|
|
|
383
|
-
}\`,
|
|
383
|
+
}\`,qt=\`
|
|
384
384
|
attribute vec2 aPos;
|
|
385
385
|
varying vec2 vUV;
|
|
386
386
|
void main(){
|
|
387
387
|
vUV = (aPos + 1.0) * 0.5; // Convert from [-1,1] to [0,1]
|
|
388
388
|
gl_Position = vec4(aPos, 0.0, 1.0);
|
|
389
|
-
}\`,
|
|
389
|
+
}\`,Kt=\`
|
|
390
390
|
precision mediump float;
|
|
391
391
|
uniform sampler2D uFBOTex;
|
|
392
392
|
varying vec2 vUV;
|
|
393
393
|
void main(){
|
|
394
394
|
gl_FragColor = texture2D(uFBOTex, vUV);
|
|
395
|
-
}\`;function Ta(t,e,s){let r=0,n=0;for(const o of Object.values(t)){const i=o.corners,a=Math.abs(ns(i));if(!a)continue;const c=Aa(i,e,s),u=c.length>=3?Math.abs(ns(c)):0;r+=u,n+=a}return{percentOfAd:n?r/n*100:0,percentOfScreen:r/(e*s)*100}}function ns(t){let e=0;for(let s=0,r=t.length-1;s<t.length;r=s++)e+=t[r].x*t[s].y-t[s].x*t[r].y;return e*.5}function Aa(t,e,s){const r=[{inside:o=>o.x>=0,inter:(o,i)=>({x:0,y:o.y+(i.y-o.y)*(0-o.x)/(i.x-o.x)})},{inside:o=>o.x<=e,inter:(o,i)=>({x:e,y:o.y+(i.y-o.y)*(e-o.x)/(i.x-o.x)})},{inside:o=>o.y>=0,inter:(o,i)=>({x:o.x+(i.x-o.x)*(0-o.y)/(i.y-o.y),y:0})},{inside:o=>o.y<=s,inter:(o,i)=>({x:o.x+(i.x-o.x)*(s-o.y)/(i.y-o.y),y:s})}];let n=t;for(const o of r){const i=n;if(n=[],!i.length)break;let a=i[i.length-1];for(const c of i){const u=o.inside(c),l=o.inside(a);u?(l||n.push(o.inter(a,c)),n.push(c)):l&&n.push(o.inter(a,c)),a=c}}return n}class is{constructor(e,s){this.logoToRegion=new Map,this.atlasDirty=!1,this.nextX=0,this.nextY=0,this.rowH=0,this.INITIAL_ATLAS_SIZE=256,this.ATLAS_SIZE=this.INITIAL_ATLAS_SIZE,this.ATLAS_PADDING=4,this.ledOverlayW=0,this.ledOverlayH=0,this.LED_PADDING=100,this.LED_AA_STRENGTH=1,this.LOGO_AA_STRENGTH=1,this.ledArtW=0,this.ledArtH=0,this.ledCubes=[],this.queryInFlight=!1,this.GPUFrameTimeCount=0,this.GPUFrameTimeSum=0,this.avgGPUFrameTime=0,this.CPUFrameTimeCount=0,this.CPUFrameTimeSum=0,this.avgCPUFrameTime=0,this.timestampW=0,this.timestampH=0,this.compileShader=(r,n)=>{const o=this.gl,i=o.createShader(r);return o.shaderSource(i,n),o.compileShader(i),o.getShaderParameter(i,o.COMPILE_STATUS)?i:(g(this.options,"Errors")&&console.error(\`Error compiling shader: \${o.getShaderInfoLog(i)}\`),o.deleteShader(i),null)},this.createTextureFromImageBitmap=r=>{const n=this.gl,o=n.createTexture();return n.bindTexture(n.TEXTURE_2D,o),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,r),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),o},this.drawVideoFrameBase=r=>{const n=this.gl;if(!this.videoProgram||this.videoAPos===void 0||this.videoAUv===void 0||!this.uVideoTexture){g(this.options,"Errors")&&console.error("[WebGL] Video program not initialized");return}n.useProgram(this.videoProgram),n.viewport(0,0,n.canvas.width,n.canvas.height),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,r),n.uniform1i(this.uVideoTexture,0),n.bindBuffer(n.ARRAY_BUFFER,this.fsPosBuf),n.enableVertexAttribArray(this.videoAPos),n.vertexAttribPointer(this.videoAPos,2,n.FLOAT,!1,0,0),n.bindBuffer(n.ARRAY_BUFFER,this.fsUvBuf),n.enableVertexAttribArray(this.videoAUv),n.vertexAttribPointer(this.videoAUv,2,n.FLOAT,!1,0,0),n.clearColor(0,0,0,1),n.clear(n.COLOR_BUFFER_BIT),n.drawArrays(n.TRIANGLES,0,6),this.program&&n.useProgram(this.program)},this.createTextureFromVideoFrame=r=>{const n=this.gl,o=n.createTexture();return n.bindTexture(n.TEXTURE_2D,o),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,r),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.bindTexture(n.TEXTURE_2D,null),o},this.deleteTexture=r=>{this.gl.deleteTexture(r)},this.options=s,this.renderer=e,this.gl=e.glContext,this.initTiming()}init(){this.initAtlas(),this.initBuffers(),this.initPrograms(),this.options.RENDER_LED&&(this.instancedExt=this.gl.getExtension("ANGLE_instanced_arrays"),this.instancedExt||g(this.options,"Errors")&&console.error("ANGLE_instanced_arrays extension not available"))}initPrograms(){const e=this.gl;if(this.program=this.linkProgram(ua,da),this.aPos=e.getAttribLocation(this.program,"a_position"),this.aUv=e.getAttribLocation(this.program,"a_uv"),this.aTransform=e.getAttribLocation(this.program,"a_transform"),this.uRes=e.getUniformLocation(this.program,"u_resolution"),this.uCanvasRes=e.getUniformLocation(this.program,"u_canvasResolution"),this.uOpacity=e.getUniformLocation(this.program,"u_opacity"),this.uAAStrength=e.getUniformLocation(this.program,"u_aaStrength"),this.uAtlas=e.getUniformLocation(this.program,"u_atlas"),this.uAlphaMask=e.getUniformLocation(this.program,"u_alphaMask"),this.options.BURNED_TIMECODES_MODE&&(this.videoProgram=this.linkProgram(ca,la),this.videoAPos=e.getAttribLocation(this.videoProgram,"a_position"),this.videoAUv=e.getAttribLocation(this.videoProgram,"a_uv"),this.uVideoTexture=e.getUniformLocation(this.videoProgram,"u_videoTexture")),this.options.RENDER_LED){if(this.blitProgram=this.linkProgram(ma,pa),!this.blitProgram){g(this.options,"Errors")&&console.error("[WebGL] Failed to create blit program");return}this.blit_aPos=e.getAttribLocation(this.blitProgram,"aPos"),this.cubesProgram=this.linkProgram(ga,Ea),this.cubes_uEdgeFeatherPx=e.getUniformLocation(this.cubesProgram,"uEdgeFeatherPx")||void 0,this.fboCompositeProgram=this.linkProgram(jt,qt),this.fboComposite_aPos=e.getAttribLocation(this.fboCompositeProgram,"aPos"),this.fboComposite_uFBOTex=e.getUniformLocation(this.fboCompositeProgram,"uFBOTex"),this.ledCompositeProgram=this.linkProgram(fa,ha),this.comp_aPos=e.getAttribLocation(this.ledCompositeProgram,"a_position"),this.comp_aUv=e.getAttribLocation(this.ledCompositeProgram,"a_uv"),this.comp_uOverlay=e.getUniformLocation(this.ledCompositeProgram,"u_overlay"),this.comp_uAlphaMask=e.getUniformLocation(this.ledCompositeProgram,"u_alphaMask"),this.comp_uUVRect=e.getUniformLocation(this.ledCompositeProgram,"u_uvRect"),this.comp_uRes=e.getUniformLocation(this.ledCompositeProgram,"u_resolution")}}linkProgram(e,s){const r=this.gl,n=this.compileShader(r.VERTEX_SHADER,e),o=this.compileShader(r.FRAGMENT_SHADER,s),i=r.createProgram();if(r.attachShader(i,n),r.attachShader(i,o),r.linkProgram(i),!r.getProgramParameter(i,r.LINK_STATUS)){const a=r.getProgramInfoLog(i);throw g(this.options,"Errors")&&console.error("WebGL link error: "+a),new Error("WebGL link error: "+a)}if(!r.getProgramParameter(i,r.LINK_STATUS)){const a=r.getProgramInfoLog(i);throw new Error("WebGL link error: "+a)}return i}drawAugmentation(e,s,r,n=1,o=!0,i){var p;const a=performance.now();this.syncAtlasGL();const{pos:c,uv:u,transforms:l,vertCount:d}=this.buildQuadData(s);if(!d)return;if(!this.program||this.aPos===void 0||this.aUv===void 0||this.aTransform===void 0||!this.uRes||!this.uOpacity||!this.uAtlas||!this.uAlphaMask){g(this.options,"Errors")&&console.error("[Renderer] Program or attributes not initialized");return}const f=this.gl;f.bindFramebuffer(f.FRAMEBUFFER,null),f.viewport(0,0,f.canvas.width,f.canvas.height),f.useProgram(this.program),f.uniform2f(this.uRes,r.width,r.height),this.uCanvasRes&&f.uniform2f(this.uCanvasRes,f.canvas.width,f.canvas.height),f.uniform1f(this.uOpacity,n),this.uAAStrength&&f.uniform1f(this.uAAStrength,this.LOGO_AA_STRENGTH),f.activeTexture(f.TEXTURE0),f.bindTexture(f.TEXTURE_2D,e),f.uniform1i(this.uAlphaMask,0),f.activeTexture(f.TEXTURE1),f.bindTexture(f.TEXTURE_2D,this.atlasTex),f.uniform1i(this.uAtlas,1),f.bindBuffer(f.ARRAY_BUFFER,this.posBuf),f.bufferData(f.ARRAY_BUFFER,c,f.DYNAMIC_DRAW),f.enableVertexAttribArray(this.aPos),f.vertexAttribPointer(this.aPos,2,f.FLOAT,!1,0,0),f.bindBuffer(f.ARRAY_BUFFER,this.uvBuf),f.bufferData(f.ARRAY_BUFFER,u,f.DYNAMIC_DRAW),f.enableVertexAttribArray(this.aUv),f.vertexAttribPointer(this.aUv,4,f.FLOAT,!1,0,0),f.bindBuffer(f.ARRAY_BUFFER,this.transformBuf),f.bufferData(f.ARRAY_BUFFER,l,f.DYNAMIC_DRAW);const m=9*4;for(let T=0;T<3;T++){const h=this.aTransform+T;f.enableVertexAttribArray(h),f.vertexAttribPointer(h,3,f.FLOAT,!1,m,T*3*4)}if(f.enable(f.BLEND),f.blendFunc(f.SRC_ALPHA,f.ONE_MINUS_SRC_ALPHA),o&&(f.clearColor(0,0,0,0),f.clear(f.COLOR_BUFFER_BIT)),this.beginTimer(),f.drawArrays(f.TRIANGLES,0,d),this.endTimer(),this.measureLogoVisibility(s),this.options.DRAW_TIMESTAMP_WEBGL&&i&&this.drawTimestampOnCanvas(i),(p=this.options.debug)!=null&&p.trackPerformance){const h=performance.now()-a;this.CPUFrameTimeCount++,this.CPUFrameTimeSum+=h,this.avgCPUFrameTime=this.CPUFrameTimeSum/this.CPUFrameTimeCount}}ensureTimestampTexture(e){try{const s=this.gl,r=18,n=8,o=6;if(!this.timestampCanvas||this.lastTimestampString!==e){const a=new OffscreenCanvas(1,1).getContext("2d");a.font=\`\${r}px monospace\`;const c=a.measureText(e),u=Math.ceil(c.width+n*2)|0,l=Math.ceil(r+o*2)|0;this.timestampCanvas=new OffscreenCanvas(u,l),this.timestampCtx=this.timestampCanvas.getContext("2d"),this.timestampW=u,this.timestampH=l;const d=this.timestampCtx;d.clearRect(0,0,u,l),d.fillStyle="rgba(0,0,0,0.55)",d.fillRect(0,0,u,l),d.font=\`\${r}px monospace\`,d.textBaseline="middle",d.fillStyle="#00FF88",d.fillText(e,n,l/2),this.timestampTex||(this.timestampTex=s.createTexture()),s.bindTexture(s.TEXTURE_2D,this.timestampTex),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,!0),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,this.timestampCanvas),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,!1),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),this.lastTimestampString=e}}catch(s){g(this.options,"Errors")&&console.error("[WebGL] ensureTimestampTexture failed",s)}}drawTimestampOnCanvas(e){const s=this.gl;try{if(this.ensureTimestampTexture(e),!this.timestampTex||!this.timestampCanvas)return;this.fboCompositeProgram||(this.fboCompositeProgram=this.linkProgram(jt,qt),this.fboComposite_aPos=s.getAttribLocation(this.fboCompositeProgram,"aPos"),this.fboComposite_uFBOTex=s.getUniformLocation(this.fboCompositeProgram,"uFBOTex")),this.timestampVBO||(this.timestampVBO=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,this.timestampVBO),s.bufferData(s.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),s.STATIC_DRAW));const r=s.canvas.width|0,n=s.canvas.height|0,o=10,i=10,a=Math.min(this.timestampW,r-o),c=Math.min(this.timestampH,n-i),u=Math.max(0,r-o-a),l=Math.max(0,n-i-c);s.viewport(u,l,a,c),s.useProgram(this.fboCompositeProgram),s.disable(s.DEPTH_TEST),s.disable(s.CULL_FACE),s.enable(s.BLEND),s.blendFunc(s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA);const d=this.fboComposite_aPos;s.bindBuffer(s.ARRAY_BUFFER,this.timestampVBO),s.enableVertexAttribArray(d),s.vertexAttribPointer(d,2,s.FLOAT,!1,0,0),d!==0&&(s.enableVertexAttribArray(0),s.vertexAttribPointer(0,2,s.FLOAT,!1,0,0)),s.activeTexture(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,this.timestampTex),this.fboComposite_uFBOTex&&s.uniform1i(this.fboComposite_uFBOTex,0),s.drawArrays(s.TRIANGLE_STRIP,0,4),s.viewport(0,0,r,n)}catch(r){g(this.options,"Errors")&&console.error("[WebGL] drawTimestampOnCanvas failed",r)}}buildCubes(e,s,r){var n;try{const o=[];let i=0;const a=e.LedModel;for(const c of a){const u=(n=c.panel)==null?void 0:n.height,l=c.bottomPoints||[];if(!(!u||l.length<2))for(let d=0;d<l.length-1;d++){const f=l[d],m=l[d+1],p=m.x-f.x,T=m.y-f.y,h=(m.z||0)-(f.z||0),R=Math.hypot(p,T,h),S=Math.max(1,Math.round(R/u*r));o.push({uOffsetPx:i,sliceWidthPx:S}),i=(i+S)%s}}this.ledCubes=o}catch{g(this.options,"Errors")&&console.error("[WebGL] Error building LED cubes from model")}}updateLEDCubesFromModel(e,s){if(!(s&&this.ledModelVersion===s)){if(!this.ensureLEDArtFromAds()){g(this.options,"Errors")&&console.error("[LED Debug] No LED art available from ads");return}this.buildCubes(e,this.ledArtW,this.ledArtH),s&&(this.ledModelVersion=s)}}renderCubes(e,s,r,n,o){const i=this.gl,a=this.instancedExt,c=this.cubesProgram,u=this.blitProgram,l=s,d=r,f=n,m=o,p=this.LED_PADDING,T=this.cornerVBO,h=this.quadVBO,R=this.bDstTL,S=this.bDstTR,F=this.bDstBR,I=this.bDstBL,M=this.bH0,k=this.bH1,A=this.bH2,L=this.bU0,W=this.bSW;if(!T||!h||!R||!S||!F||!I||!M||!k||!A||!L||!W){g(this.options,"Errors")&&console.error("[WebGL] Missing required vertex buffers for LED rendering");return}(!this.overlayTex||!this.overlayFBO)&&(this.overlayTex=i.createTexture(),i.bindTexture(i.TEXTURE_2D,this.overlayTex),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,n,o,0,i.RGBA,i.UNSIGNED_BYTE,null),this.overlayFBO=i.createFramebuffer(),i.bindFramebuffer(i.FRAMEBUFFER,this.overlayFBO),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,this.overlayTex,0),i.bindFramebuffer(i.FRAMEBUFFER,null),i.disable(i.DEPTH_TEST),i.enable(i.BLEND),i.blendFunc(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA));const Z=this.overlayFBO;if(this.overlayTex,!c||!u||!a){g(this.options,"Errors")&&console.error("[WebGL] Missing programs or buffers",{cubesProg:c,blitProg:u,instancedExt:a});return}if(this.blit_aPos===void 0||this.blit_aPos<0){g(this.options,"Errors")&&console.error("[WebGL] Invalid blit_aPos attribute location:",this.blit_aPos);return}i.bindFramebuffer(i.FRAMEBUFFER,Z),i.viewport(0,0,f,m),i.clearColor(0,0,0,0),i.clear(i.COLOR_BUFFER_BIT),i.useProgram(c),i.bindBuffer(i.ARRAY_BUFFER,T),i.enableVertexAttribArray(0),i.vertexAttribPointer(0,1,i.FLOAT,!1,0,0),i.bindBuffer(i.ARRAY_BUFFER,R),i.enableVertexAttribArray(1),i.vertexAttribPointer(1,2,i.FLOAT,!1,0,0),a.vertexAttribDivisorANGLE(1,1),i.bindBuffer(i.ARRAY_BUFFER,S),i.enableVertexAttribArray(2),i.vertexAttribPointer(2,2,i.FLOAT,!1,0,0),a.vertexAttribDivisorANGLE(2,1),i.bindBuffer(i.ARRAY_BUFFER,F),i.enableVertexAttribArray(3),i.vertexAttribPointer(3,2,i.FLOAT,!1,0,0),a.vertexAttribDivisorANGLE(3,1),i.bindBuffer(i.ARRAY_BUFFER,I),i.enableVertexAttribArray(4),i.vertexAttribPointer(4,2,i.FLOAT,!1,0,0),a.vertexAttribDivisorANGLE(4,1),i.bindBuffer(i.ARRAY_BUFFER,M),i.enableVertexAttribArray(5),i.vertexAttribPointer(5,3,i.FLOAT,!1,0,0),a.vertexAttribDivisorANGLE(5,1),i.bindBuffer(i.ARRAY_BUFFER,k),i.enableVertexAttribArray(6),i.vertexAttribPointer(6,3,i.FLOAT,!1,0,0),a.vertexAttribDivisorANGLE(6,1),i.bindBuffer(i.ARRAY_BUFFER,A),i.enableVertexAttribArray(7),i.vertexAttribPointer(7,3,i.FLOAT,!1,0,0),a.vertexAttribDivisorANGLE(7,1),i.bindBuffer(i.ARRAY_BUFFER,L),i.enableVertexAttribArray(8),i.vertexAttribPointer(8,1,i.FLOAT,!1,0,0),a.vertexAttribDivisorANGLE(8,1),i.bindBuffer(i.ARRAY_BUFFER,W),i.enableVertexAttribArray(9),i.vertexAttribPointer(9,1,i.FLOAT,!1,0,0),a.vertexAttribDivisorANGLE(9,1),i.uniform2f(i.getUniformLocation(c,"uResolution"),f,m),i.uniform1i(i.getUniformLocation(c,"uFlipY"),1),i.uniform2f(i.getUniformLocation(c,"uShift"),0,0),i.uniform2f(i.getUniformLocation(c,"uArtSize"),this.ledArtW,this.ledArtH),this.cubes_uEdgeFeatherPx&&i.uniform1f(this.cubes_uEdgeFeatherPx,this.LED_AA_STRENGTH),i.activeTexture(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,this.ledArtTex),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.uniform1i(i.getUniformLocation(c,"uArt"),0),i.getParameter(i.TEXTURE_BINDING_2D)!==this.ledArtTex&&g(this.options,"Errors")&&console.error("Warning: Texture binding mismatch!"),a.drawArraysInstancedANGLE(i.TRIANGLES,0,6,e),a.vertexAttribDivisorANGLE(0,0);for(let V=1;V<=9;V++)a.vertexAttribDivisorANGLE(V,0),i.disableVertexAttribArray(V);i.disableVertexAttribArray(0);const gt=p/f,w=p/m,x=(p+l)/f,G=(p+d)/m;this.ledOverlayUVRect=[gt,w,x,G]}drawAugmentationWithLED(e,s,r,n=1,o,i){this.gl;let a=!1;try{if(o&&o.cubePlaceholders&&o.intrinsics&&o.referenceSize&&this.ensureLEDArtFromAds()){const c=Math.max(1,o.referenceSize.width|0),u=Math.max(1,o.referenceSize.height|0),l=this.LED_PADDING|0,d=c+l*2,f=u+l*2;this.ensureLedOverlay(d,f);const m=this.getCubesTransformationsToLiveImage(o);m&&m>0&&(this.renderCubes(m,c,u,d,f),a=!0)}}catch(c){g(this.options,"Errors")&&console.error("[WebGL] LED prep error:",c)}this.drawAugmentation(e,s,r,n,!0,a?void 0:i),a&&this.compositeLEDOverlayDirectToCanvas(!1,e)}drawLEDOnly(e,s){try{if(!s||!s.cubePlaceholders||!s.intrinsics||!s.referenceSize){g(this.options,"Errors")&&console.error("[LED Debug] Missing LED data - led:",!!s,"cubePlaceholders:",!!(s!=null&&s.cubePlaceholders),"intrinsics:",!!(s!=null&&s.intrinsics),"referenceSize:",!!(s!=null&&s.referenceSize));return}if(!this.ensureLEDArtFromAds()){g(this.options,"Errors")&&console.error("[LED Debug] Failed to ensure LED art from ads");return}const r=s.referenceSize.width,n=s.referenceSize.height,o=r+this.LED_PADDING*2,i=n+this.LED_PADDING*2;this.ensureLedOverlay(o,i);const a=this.getCubesTransformationsToLiveImage(s);if(!a||a===0){g(this.options,"Errors")&&console.error("[LED Debug] No LED cubes to render - check LED model data");return}this.renderCubes(a,r,n,o,i),this.compositeLEDOverlayDirectToCanvas(!0,e)}catch(r){g(this.options,"Errors")&&console.error("[WebGL] LED-only path error",r)}}drawLEDOverlayOnTop(e,s){try{if(!s||!s.cubePlaceholders||!s.intrinsics||!s.referenceSize){g(this.options,"Errors")&&console.error("[LED Debug] Missing LED data for drawLEDOverlayOnTop");return}if(!this.ensureLEDArtFromAds()){g(this.options,"Errors")&&console.error("[LED Debug] Failed to ensure LED art for drawLEDOverlayOnTop");return}const r=s.referenceSize.width,n=s.referenceSize.height,o=r+this.LED_PADDING*2,i=n+this.LED_PADDING*2;this.ensureLedOverlay(o,i);const a=this.getCubesTransformationsToLiveImage(s);a&&a>0&&(this.renderCubes(a,r,n,o,i),this.compositeLEDOverlayDirectToCanvas(!1,e))}catch(r){g(this.options,"Errors")&&console.error("[WebGL] drawLEDOverlayOnTop error",r)}}compositeLEDOverlayDirectToCanvas(e,s){const r=this.gl;if(!this.ledCompositeProgram||!this.overlayTex||!this.fsPosBuf||!this.fsUvBuf||this.comp_aPos===void 0||this.comp_aUv===void 0||!this.comp_uOverlay||!this.comp_uAlphaMask||!this.comp_uUVRect||!this.comp_uRes||!this.ledOverlayUVRect){g(this.options,"Errors")&&console.error("[WebGL] Missing resources for direct LED composite");return}r.bindFramebuffer(r.FRAMEBUFFER,null);const n=r.canvas.width,o=r.canvas.height;r.viewport(0,0,n,o),e&&(r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT)),r.useProgram(this.ledCompositeProgram),r.disable(r.DEPTH_TEST),r.disable(r.CULL_FACE),r.enable(r.BLEND),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA);for(let l=0;l<16;l++)r.disableVertexAttribArray(l);r.bindBuffer(r.ARRAY_BUFFER,this.fsPosBuf),r.enableVertexAttribArray(this.comp_aPos),r.vertexAttribPointer(this.comp_aPos,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.fsUvBuf),r.enableVertexAttribArray(this.comp_aUv),r.vertexAttribPointer(this.comp_aUv,2,r.FLOAT,!1,0,0),r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.overlayTex),r.uniform1i(this.comp_uOverlay,0),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,s),r.uniform1i(this.comp_uAlphaMask,1);const[i,a,c,u]=this.ledOverlayUVRect;r.uniform4f(this.comp_uUVRect,i,a,c,u),r.uniform2f(this.comp_uRes,n,o),r.drawArrays(r.TRIANGLES,0,6)}compositeLEDFBOToCanvas(e,s){const r=this.gl,n=this.quadVBO;if(!this.compositeTex||!this.fboCompositeProgram||!n){g(this.options,"Errors")&&console.error("[WebGL] Missing resources for LED FBO compositing");return}for(;r.getError()!==r.NO_ERROR;);r.bindFramebuffer(r.FRAMEBUFFER,null);const o=r.canvas.width,i=r.canvas.height;if(r.viewport(0,0,o,i),e&&(r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT)),this.fboCompositeProgram||(this.fboCompositeProgram=this.linkProgram(jt,qt),this.fboComposite_aPos=r.getAttribLocation(this.fboCompositeProgram,"aPos"),this.fboComposite_uFBOTex=r.getUniformLocation(this.fboCompositeProgram,"uFBOTex")),s&&this.ledCompositeProgram&&this.fsPosBuf&&this.fsUvBuf&&this.comp_aPos!==void 0&&this.comp_aUv!==void 0&&this.comp_uOverlay&&this.comp_uAlphaMask&&this.comp_uUVRect&&this.comp_uRes){r.useProgram(this.ledCompositeProgram),r.disable(r.DEPTH_TEST),r.disable(r.CULL_FACE),r.enable(r.BLEND),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA);for(let d=0;d<16;d++)r.disableVertexAttribArray(d);r.bindBuffer(r.ARRAY_BUFFER,this.fsPosBuf),r.enableVertexAttribArray(this.comp_aPos),r.vertexAttribPointer(this.comp_aPos,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.fsUvBuf),r.enableVertexAttribArray(this.comp_aUv),r.vertexAttribPointer(this.comp_aUv,2,r.FLOAT,!1,0,0),r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.compositeTex),r.uniform1i(this.comp_uOverlay,0),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,s),r.uniform1i(this.comp_uAlphaMask,1),r.uniform4f(this.comp_uUVRect,0,0,1,1),r.uniform2f(this.comp_uRes,o,i),r.drawArrays(r.TRIANGLES,0,6);return}r.useProgram(this.fboCompositeProgram),r.disable(r.DEPTH_TEST),r.disable(r.CULL_FACE),r.enable(r.BLEND),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA);for(let d=0;d<16;d++)r.disableVertexAttribArray(d);r.bindBuffer(r.ARRAY_BUFFER,n);const a=this.fboComposite_aPos;if(a===void 0||a<0){g(this.options,"Errors")&&console.error("[WebGL] Invalid fboComposite aPos location:",a);return}r.enableVertexAttribArray(a),r.vertexAttribPointer(a,2,r.FLOAT,!1,0,0),a!==0&&(r.enableVertexAttribArray(0),r.vertexAttribPointer(0,2,r.FLOAT,!1,0,0));const c=r.getBufferParameter(r.ARRAY_BUFFER,r.BUFFER_SIZE);c!==32&&g(this.options,"Errors")&&console.error("[WebGL] Unexpected quadVBO size:",c,"expected 32 bytes"),r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.compositeTex),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),this.fboComposite_uFBOTex&&r.uniform1i(this.fboComposite_uFBOTex,0);const u=r.getError();u&&g(this.options,"Errors")&&console.error("[WebGL] Error before composite draw:",u),r.drawArrays(r.TRIANGLE_STRIP,0,4);const l=r.getError();l&&g(this.options,"Errors")&&console.error("[WebGL] Error in LED FBO composite:",l)}getDistortionCtx(e){if(!e.intrinsics||!e.distortion)return;const s=e.intrinsics,r=e.distortion,n=r[0],o=r[1],i=r[2],a=s.cx,c=s.cy,u=s.fx,l=s.fy;return{k1:n,k2:o,k3:i,cx:a,cy:c,fx:u,fy:l,undistortNormalized(d,f){let m=d,p=f;for(let T=0;T<5;T++){const h=m*m+p*p,R=h*h,S=R*h,F=1+n*h+o*R+i*S,I=F!==0?1/F:1;m=d*I,p=f*I}return{x:m,y:p}},undistortCanvasPoint(d,f){const m=d.x+f,p=d.y+f,T=(m-(a+f))/u,h=(p-(c+f))/l,R=this.undistortNormalized(T,h),S=a+f+u*R.x,F=c+f+l*R.y;return{x:S-f,y:F-f}}}}pickCorners(e){const s=e.tgtCorners||e.block&&e.block.fenceVertices2D;return!s||s.length!==4?null:[s[0],s[1],s[2],s[3]]}getHinv(e,s){const r=[],n=[];for(let x=0;x<4;x++){const G=e[x].x,V=e[x].y,ve=s[x].x,U=s[x].y;r.push([G,V,1,0,0,0,-G*ve,-V*ve]),n.push(ve),r.push([0,0,0,G,V,1,-G*U,-V*U]),n.push(U)}const o=8,i=r.map(x=>x.slice()),a=n.slice();for(let x=0;x<o;x++){let G=x;for(let U=x+1;U<o;U++)Math.abs(i[U][x])>Math.abs(i[G][x])&&(G=U);if(G!==x){const U=i[x];i[x]=i[G],i[G]=U;const Be=a[x];a[x]=a[G],a[G]=Be}const ve=1/(i[x][x]||1e-12);for(let U=x;U<o;U++)i[x][U]*=ve;a[x]*=ve;for(let U=0;U<o;U++){if(U===x)continue;const Be=i[U][x];if(Be!==0){for(let Et=x;Et<o;Et++)i[U][Et]-=Be*i[x][Et];a[U]-=Be*a[x]}}}const c=a,u=[c[0],c[1],c[2],c[3],c[4],c[5],c[6],c[7],1],[l,d,f,m,p,T,h,R,S]=[u[0],u[1],u[2],u[3],u[4],u[5],u[6],u[7],u[8]],F=p*S-T*R,I=-(m*S-T*h),M=m*R-p*h,k=-(d*S-f*R),A=l*S-f*h,L=-(l*R-d*h),W=d*T-f*p,Z=-(l*T-f*m),pt=l*p-d*m,w=1/(l*F+d*I+f*M||1e-12);return[F*w,k*w,W*w,I*w,A*w,Z*w,M*w,L*w,pt*w]}getCubesTransformationsToLiveImage(e){if(!e||!e.cubePlaceholders||!e.intrinsics||!e.referenceSize)return;const s=this.LED_PADDING,r=e.cubePlaceholders,n=r.length,o=new Float32Array(n*2),i=new Float32Array(n*2),a=new Float32Array(n*2),c=new Float32Array(n*2),u=new Float32Array(n*3),l=new Float32Array(n*3),d=new Float32Array(n*3),f=new Float32Array(n),m=new Float32Array(n);let p=0;const T=this.getDistortionCtx(e);if(!T)return;for(let R=0;R<n;R++){const S=r[R],F=S.index;if(F<0||F>=this.ledCubes.length)continue;const I=this.pickCorners(S);if(!I)continue;const M=T.undistortCanvasPoint(I[0],s),k=T.undistortCanvasPoint(I[1],s),A=T.undistortCanvasPoint(I[2],s),L=T.undistortCanvasPoint(I[3],s);o.set([M.x,M.y],R*2),i.set([k.x,k.y],R*2),a.set([A.x,A.y],R*2),c.set([L.x,L.y],R*2);const W=this.ledCubes[F],Z=Math.max(1,W.sliceWidthPx),pt=[{x:0,y:this.ledArtH},{x:0,y:0},{x:Z,y:0},{x:Z,y:this.ledArtH}],gt=[M,k,A,L],w=this.getHinv(pt,gt);u.set([w[0],w[1],w[2]],R*3),l.set([w[3],w[4],w[5]],R*3),d.set([w[6],w[7],w[8]],R*3),f[R]=W.uOffsetPx/this.ledArtW,m[R]=Z,p++}const h=this.gl;return h.bindBuffer(h.ARRAY_BUFFER,this.bDstTL),h.bufferData(h.ARRAY_BUFFER,o,h.DYNAMIC_DRAW),h.bindBuffer(h.ARRAY_BUFFER,this.bDstTR),h.bufferData(h.ARRAY_BUFFER,i,h.DYNAMIC_DRAW),h.bindBuffer(h.ARRAY_BUFFER,this.bDstBR),h.bufferData(h.ARRAY_BUFFER,a,h.DYNAMIC_DRAW),h.bindBuffer(h.ARRAY_BUFFER,this.bDstBL),h.bufferData(h.ARRAY_BUFFER,c,h.DYNAMIC_DRAW),h.bindBuffer(h.ARRAY_BUFFER,this.bH0),h.bufferData(h.ARRAY_BUFFER,u,h.DYNAMIC_DRAW),h.bindBuffer(h.ARRAY_BUFFER,this.bH1),h.bufferData(h.ARRAY_BUFFER,l,h.DYNAMIC_DRAW),h.bindBuffer(h.ARRAY_BUFFER,this.bH2),h.bufferData(h.ARRAY_BUFFER,d,h.DYNAMIC_DRAW),h.bindBuffer(h.ARRAY_BUFFER,this.bU0),h.bufferData(h.ARRAY_BUFFER,f,h.DYNAMIC_DRAW),h.bindBuffer(h.ARRAY_BUFFER,this.bSW),h.bufferData(h.ARRAY_BUFFER,m,h.DYNAMIC_DRAW),p}setLEDArtTexture(e){try{const s=this.gl;this.ledArtTex||(this.ledArtTex=s.createTexture()),s.bindTexture(s.TEXTURE_2D,this.ledArtTex),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,e);const r=this.getDims(e);this.ledArtW=r.w||1,this.ledArtH=r.h||1;const n=this.isPowerOf2(this.ledArtW)&&this.isPowerOf2(this.ledArtH);if(s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),n)s.generateMipmap(s.TEXTURE_2D),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR_MIPMAP_LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR);else{s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR);const o=s.getExtension("EXT_texture_filter_anisotropic")||s.getExtension("WEBKIT_EXT_texture_filter_anisotropic");if(o){const i=s.getParameter(o.MAX_TEXTURE_MAX_ANISOTROPY_EXT);s.texParameteri(s.TEXTURE_2D,o.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(16,i))}}}catch(s){g(this.options,"Errors")&&console.error("[WebGL] setLEDArtTexture failed",s)}}ensureLEDArtFromAds(){var e,s,r,n,o,i;try{if(this.ledArtTex)return!0;const a=((r=(s=(e=this.renderer.ads)==null?void 0:e.ledAds)==null?void 0:s[0])==null?void 0:r.image)||((i=(o=(n=this.renderer.ads)==null?void 0:n.ads)==null?void 0:o[0])==null?void 0:i.image);if(!a)return g(this.options,"Errors")&&console.error("[LED Debug] No ad image found in ads object"),!1;if(!this.ledArtTex){const c=this.gl,u=c.createTexture();c.bindTexture(c.TEXTURE_2D,u),c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,a),this.ledArtW=a.width||1,this.ledArtH=a.height||1;const l=this.isPowerOf2(this.ledArtW)&&this.isPowerOf2(this.ledArtH);if(c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),l)c.generateMipmap(c.TEXTURE_2D),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MIN_FILTER,c.LINEAR_MIPMAP_LINEAR),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MAG_FILTER,c.LINEAR);else{c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MIN_FILTER,c.LINEAR),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MAG_FILTER,c.LINEAR);const d=c.getExtension("EXT_texture_filter_anisotropic")||c.getExtension("WEBKIT_EXT_texture_filter_anisotropic");if(d){const f=c.getParameter(d.MAX_TEXTURE_MAX_ANISOTROPY_EXT);c.texParameteri(c.TEXTURE_2D,d.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(16,f))}}this.ledArtTex=u}return!0}catch(a){return g(this.options,"Errors")&&console.error("[LED Debug] Error in ensureLEDArtFromAds:",a),!1}}ensureLedOverlay(e,s){const r=this.gl;this.ledOverlayTex&&this.ledOverlayW===e&&this.ledOverlayH===s||(this.ledOverlayTex&&r.deleteTexture(this.ledOverlayTex),this.ledOverlayFBO&&r.deleteFramebuffer(this.ledOverlayFBO),this.ledOverlayTex=r.createTexture(),r.bindTexture(r.TEXTURE_2D,this.ledOverlayTex),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,s,0,r.RGBA,r.UNSIGNED_BYTE,null),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),this.ledOverlayFBO=r.createFramebuffer(),r.bindFramebuffer(r.FRAMEBUFFER,this.ledOverlayFBO),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.ledOverlayTex,0),r.bindFramebuffer(r.FRAMEBUFFER,null),this.ledOverlayW=e,this.ledOverlayH=s)}ensureCompositeFBO(e,s){const r=this.gl;this.compositeTex&&this.compositeFBO,this.compositeTex&&r.deleteTexture(this.compositeTex),this.compositeFBO&&r.deleteFramebuffer(this.compositeFBO),this.compositeTex=r.createTexture(),r.bindTexture(r.TEXTURE_2D,this.compositeTex),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,s,0,r.RGBA,r.UNSIGNED_BYTE,null),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),this.compositeFBO=r.createFramebuffer(),r.bindFramebuffer(r.FRAMEBUFFER,this.compositeFBO),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.compositeTex,0);const n=r.checkFramebufferStatus(r.FRAMEBUFFER);n!==r.FRAMEBUFFER_COMPLETE&&console.error("[WebGL] Composite FBO incomplete:",n),r.bindFramebuffer(r.FRAMEBUFFER,null)}initBuffers(){const e=this.gl;this.posBuf=e.createBuffer(),this.uvBuf=e.createBuffer(),this.transformBuf=e.createBuffer(),this.fsPosBuf=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.fsPosBuf),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,1,0,1,1,0,0,1,1,0,1]),e.STATIC_DRAW),this.fsUvBuf=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.fsUvBuf),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,1,0,1,1,0,0,1,1,0,1]),e.STATIC_DRAW),this.options.RENDER_LED&&(this.quadVBO=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.quadVBO),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),e.STATIC_DRAW),this.cornerVBO=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.cornerVBO),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,3,1,1,3,2]),e.STATIC_DRAW),this.bDstTL=e.createBuffer(),this.bDstTR=e.createBuffer(),this.bDstBR=e.createBuffer(),this.bDstBL=e.createBuffer(),this.bH0=e.createBuffer(),this.bH1=e.createBuffer(),this.bH2=e.createBuffer(),this.bU0=e.createBuffer(),this.bSW=e.createBuffer())}buildQuadData(e){const s=[],r=[],n=[];return Object.values(e).forEach(o=>{var u,l;const i=(l=(u=this.renderer.ads)==null?void 0:u.adMap.get(o.name))==null?void 0:l.name;if(!i)return;const a=this.logoToRegion.get(i);if(!a)return;const c=o.corners;s.push(c[0].x,c[0].y,c[1].x,c[1].y,c[2].x,c[2].y,c[0].x,c[0].y,c[2].x,c[2].y,c[3].x,c[3].y);for(let d=0;d<6;d++)r.push(a.u0,a.v0,a.u1,a.v1);for(let d=0;d<6;d++)n.push(...o.tranform)}),{pos:new Float32Array(s),uv:new Float32Array(r),transforms:new Float32Array(n),vertCount:s.length/2}}cleanGL(){this.gl.clearColor(0,0,0,0),this.gl.clear(this.gl.COLOR_BUFFER_BIT)}initAtlas(){this.atlasCanvas=new OffscreenCanvas(this.INITIAL_ATLAS_SIZE,this.INITIAL_ATLAS_SIZE),this.atlasCanvas.width=this.atlasCanvas.height=this.INITIAL_ATLAS_SIZE,this.atlasCtx=this.atlasCanvas.getContext("2d"),this.atlasTex=this.gl.createTexture(),this.atlasCtx.clearRect(0,0,this.INITIAL_ATLAS_SIZE,this.INITIAL_ATLAS_SIZE),this.syncAtlasGL()}getDims(e){if("width"in e&&"height"in e)return{w:e.width,h:e.height};const s=e;return{w:s.displayWidth??s.codedWidth,h:s.displayHeight??s.codedHeight}}isPowerOf2(e){return(e&e-1)===0}calculateRequiredAtlasSize(e,s){const r=this.ATLAS_PADDING*2;let n=(e+r)*(s+r);this.logoToRegion.forEach(i=>{const a=(i.u1-i.u0)*this.ATLAS_SIZE,c=(i.v1-i.v0)*this.ATLAS_SIZE;n+=(a+r)*(c+r)}),n*=1.3;let o=this.INITIAL_ATLAS_SIZE;for(;o*o<n;)o*=2;return o}resizeAtlas(e,s){const r=this.calculateRequiredAtlasSize(e,s);if(r<=this.ATLAS_SIZE)return;const n=new OffscreenCanvas(r,r),o=n.getContext("2d");o.clearRect(0,0,r,r),o.drawImage(this.atlasCanvas,0,0);const i=this.ATLAS_SIZE/r;this.ATLAS_SIZE=r,this.atlasCanvas=n,this.atlasCtx=o,this.logoToRegion.forEach((a,c)=>{const u={u0:a.u0*i,v0:a.v0*i,u1:a.u1*i,v1:a.v1*i};this.logoToRegion.set(c,u)}),this.syncAtlasGL()}addToAtlas(e,s){if(this.logoToRegion.has(e))return this.logoToRegion.get(e);const{w:r,h:n}=this.getDims(s),o=this.ATLAS_PADDING,i=r+o*2,a=n+o*2;this.nextX+i>this.ATLAS_SIZE&&(this.nextX=0,this.nextY+=this.rowH,this.rowH=0),(this.nextY+a>this.ATLAS_SIZE||this.nextX+i>this.ATLAS_SIZE)&&this.resizeAtlas(i,a);const c=this.nextX+o,u=this.nextY+o;this.atlasCtx.drawImage(s,c,u,r,n);const l={u0:c/this.ATLAS_SIZE,v0:u/this.ATLAS_SIZE,u1:(c+r)/this.ATLAS_SIZE,v1:(u+n)/this.ATLAS_SIZE};return this.logoToRegion.set(e,l),this.atlasDirty=!0,this.nextX+=i,this.rowH=Math.max(this.rowH,a),l}syncAtlasGL(){if(!this.atlasDirty)return;const e=this.gl;e.bindTexture(e.TEXTURE_2D,this.atlasTex),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.atlasCanvas),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),this.isPowerOf2(this.ATLAS_SIZE)?(e.generateMipmap(e.TEXTURE_2D),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR_MIPMAP_LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR)):(e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR));const r=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");if(r){const n=e.getParameter(r.MAX_TEXTURE_MAX_ANISOTROPY_EXT);e.texParameteri(e.TEXTURE_2D,r.TEXTURE_MAX_ANISOTROPY_EXT,n)}this.atlasDirty=!1}clearAtlas(){this.logoToRegion.clear(),this.nextX=this.nextY=this.rowH=0,this.atlasCtx.clearRect(0,0,this.ATLAS_SIZE,this.ATLAS_SIZE),this.atlasDirty=!0,this.syncAtlasGL()}generateAdTexture(e,s){D.setAttributes({asset:e}),this.addToAtlas(e,s)}measureLogoVisibility(e){const s=this.gl.canvas.width,r=this.gl.canvas.height,n=this.renderer.shot;if(!n)return;const{percentOfAd:o,percentOfScreen:i}=Ta(e,s,r);n.frameCount++,n.sumPercentOfAd+=o,n.sumPercentOfScreen+=i,n.lastProcessingTime=performance.now()}initTiming(){var e;(e=this.options.debug)!=null&&e.trackPerformance&&(this.timerExt=this.gl.getExtension("EXT_disjoint_timer_query"),this.timerExt||g(this.options,"Errors")&&console.error("EXT_disjoint_timer_query not supported"))}beginTimer(){!this.timerExt||this.queryInFlight||(this.query=this.timerExt.createQueryEXT(),this.timerExt.beginQueryEXT(this.timerExt.TIME_ELAPSED_EXT,this.query))}endTimer(){if(!this.timerExt||!this.query||this.queryInFlight)return;this.timerExt.endQueryEXT(this.timerExt.TIME_ELAPSED_EXT),this.queryInFlight=!0;const e=()=>{if(!this.queryInFlight)return;const s=this.timerExt.getQueryObjectEXT(this.query,this.timerExt.QUERY_RESULT_AVAILABLE_EXT),r=this.gl.getParameter(this.timerExt.GPU_DISJOINT_EXT);if(s&&!r){const o=this.timerExt.getQueryObjectEXT(this.query,this.timerExt.QUERY_RESULT_EXT)/1e6;this.GPUFrameTimeSum+=o,this.GPUFrameTimeCount++,this.avgGPUFrameTime=this.GPUFrameTimeSum/this.GPUFrameTimeCount,this.timerExt.deleteQueryEXT(this.query),this.query=null,this.queryInFlight=!1}else requestAnimationFrame(e)};requestAnimationFrame(e)}getAvgGPUFrameTime(){var e;if((e=this.options.debug)!=null&&e.trackPerformance){const s=this.avgGPUFrameTime;return this.GPUFrameTimeCount=0,this.GPUFrameTimeSum=0,this.avgGPUFrameTime=0,s}return 0}getAvgCPUFrameTime(){var e;if((e=this.options.debug)!=null&&e.trackPerformance){const s=this.avgCPUFrameTime;return this.CPUFrameTimeCount=0,this.CPUFrameTimeSum=0,this.avgCPUFrameTime=0,s}return 0}}const os=["LeftTop","MidTopLeft","MidTopRight","RightTop","LeftBottom","MidBottomLeft","MidBottomRight","RightBottom"];class as{constructor(e,s){this.ads=[],this.ledAds=[],this.isOverridden=!1,this.assetKeyToAdv=new Map,this.getAds=async()=>{var r;try{const n=this.options.adsBaseURL,o=await fetch(n+"/profiles/geo/",{method:"GET",redirect:"follow",cache:"no-store"});if(this.options&&g(this.options,"Ads")&&console.log("[ADS] adListResponse: ",o),!o.ok){D.error("[ADS] Failed to fetch ad list"),this.options&&g(this.options,"Errors")&&console.error("[ADS] Failed to fetch ad list");return}const i=await o.json();this.options&&g(this.options,"Ads")&&console.log("[ADS] Current JSON with ads: ",i.rootAdPath);const a=i.rootAdPath;if(!a){D.error("[ADS] rootAdPath is missing in the ads response"),this.options&&g(this.options,"Errors")&&console.error("[ADS] rootAdPath is missing in the response");return}if(this.lastJson===JSON.stringify(i))return;this.lastJson=JSON.stringify(i),this.ads=[],this.options&&g(this.options,"Ads")&&console.warn("[ADS] Fetching ad image from: ",a);const c=a,u=c.split("assets/")[1].split("?")[0],d=await(await fetch(c,{headers:{"X-Platform":"Web"}})).blob(),f=await createImageBitmap(d),m={name:c,imageUrl:c,image:f,adUrl:"https://www.BurgerKing.com/"};if(this.ads.push(m),this.ledAds=[m],this.isOverridden)this.options&&g(this.options,"Ads")&&console.log("[ADS] Skipping texture upload due to manual override");else{this.setAd("LeftTop",0),this.setAd("RightBottom",0),this.setAd("MidBottomLeft",0),this.setAd("MidTopRight",0),this.setAd("MidTopLeft",0),this.setAd("MidBottomRight",0),this.setAd("LeftBottom",0),this.setAd("RightTop",0),this.uploadAdTextures();try{(r=this.ledAds[0])!=null&&r.image&&this.webgl.setLEDArtTexture(this.ledAds[0].image)}catch{}}}catch{}finally{this.refreshTimeoutId&&(clearTimeout(this.refreshTimeoutId),this.refreshTimeoutId=void 0),this.isOverridden||(this.refreshTimeoutId=setTimeout(this.getAds,1e4))}},this.loadAdvImage=async r=>{const n=\`#\${r.name}\`,o=r.url;if(n.indexOf(".json")>-1)return;const a=await(await fetch(o)).blob();return await createImageBitmap(a)},this.setAd=(r,n)=>{this.adMap.set(r,this.ads[n])},this.uploadAdTextures=()=>{this.webgl.clearAtlas(),this.adMap.forEach((r,n)=>{!r||!r.image||this.webgl.generateAdTexture(r.name,r.image)})},this.overrideAdImage=async r=>{this.options&&g(this.options,"Ads")&&console.log("[ADS] overrideAdImage called"),this.stopAutoRefresh();const n=this.ads[0];let o;try{o=await this.computeImageBitmapHash(r)}catch{}const i={name:o?\`asset_\${o}\`:"override_ad",imageUrl:(n==null?void 0:n.imageUrl)||"",image:r,adUrl:(n==null?void 0:n.adUrl)||""};o&&this.assetKeyToAdv.set(o,i),this.ads=[i],this.adMap.forEach((a,c)=>this.adMap.set(c,i)),this.uploadAdTextures(),this.options&&g(this.options,"Ads")&&console.log("[ADS] overrideAdImage completed")},this.overrideLEDImage=r=>{this.options&&g(this.options,"Ads")&&console.log("[ADS] overrideLEDImage called"),this.stopAutoRefresh();const n=this.ledAds[0]||this.ads[0],o={name:"override_led",imageUrl:(n==null?void 0:n.imageUrl)||"",image:r,adUrl:(n==null?void 0:n.adUrl)||""};this.ledAds=[o];try{this.webgl.setLEDArtTexture(r),this.options&&g(this.options,"Ads")&&console.log("[ADS] overrideLEDImage completed")}catch{this.options&&g(this.options,"Errors")&&console.error("[ADS] Failed to set LED art texture")}},this.overrideAdImageForPlaceholder=async(r,n)=>{if(this.placeholderNames.indexOf(n)===-1){D.error(\`[ADS] Unknown placeholder: \${n}\`),this.options&&g(this.options,"Errors")&&console.error("[ADS] Unknown placeholder provided to overrideAdImageForPlaceholder:",n);try{r.close()}catch{}return}this.stopAutoRefresh();let o,i;try{i=await this.computeImageBitmapHash(r)}catch{}if(i&&(o=this.assetKeyToAdv.get(i)),o)try{r.close()}catch{}else{const a=this.ads[0];o={name:i?\`asset_\${i}\`:\`override_\${Date.now()}\`,imageUrl:(a==null?void 0:a.imageUrl)||"",image:r,adUrl:(a==null?void 0:a.adUrl)||""},i&&this.assetKeyToAdv.set(i,o);try{this.uploadAdTextures()}catch{}}this.adMap.set(n,o);try{this.uploadAdTextures()}catch{this.options&&g(this.options,"Errors")&&console.error("[ADS] Failed to set ad texture")}},this.getAdURLAtCoord=(r,n,o)=>{let i;return Object.keys(r).forEach(a=>{const c=r[a].corners.map(u=>({x:u.x/n.width,y:u.y/n.height}));if(this.isPointInPlaceholder(c,o)){const u=r[a].name,l=this.adMap.get(u);this.options&&g(this.options,"Ads")&&console.log("ad: ",l),l&&(this.options&&g(this.options,"Ads")&&console.log("ad.url: ",l.adUrl),i=l.adUrl)}}),i},this.isPointInPlaceholder=(r,n)=>{let o=!1;const{x:i,y:a}=n,c=r.length;for(let u=0,l=c-1;u<c;l=u++){const d=r[u].x,f=r[u].y,m=r[l].x,p=r[l].y;f>a!=p>a&&i<(m-d)*(a-f)/(p-f)+d&&(o=!o)}return o},this.placeholderNames=os,this.webgl=e,this.options=s,this.adMap=new Map,os.forEach(r=>{this.adMap.set(r,void 0)}),this.getAds()}stopAutoRefresh(){this.isOverridden=!0,this.refreshTimeoutId&&(clearTimeout(this.refreshTimeoutId),this.refreshTimeoutId=void 0)}resumeAutoRefresh(){this.isOverridden=!1,this.getAds()}pause(){this.refreshTimeoutId&&(clearTimeout(this.refreshTimeoutId),this.refreshTimeoutId=void 0),this.options&&g(this.options,"Ads")&&console.log("[ADS] Paused ad refresh")}resume(){this.options&&g(this.options,"Ads")&&console.log("[ADS] Resuming ad refresh"),this.isOverridden||this.getAds()}async computeImageBitmapHash(e){const s=Math.max(1,e.width||0),r=Math.max(1,e.height||0),n=new OffscreenCanvas(s,r),o=n.getContext("2d");if(!o)throw new Error("2D context not available");o.drawImage(e,0,0,s,r);const a=await(await n.convertToBlob({type:"image/png"})).arrayBuffer(),c=await crypto.subtle.digest("SHA-256",a),u=new Uint8Array(c);let l="";for(let d=0;d<u.length;d++)l+=u[d].toString(16).padStart(2,"0");return l}}class cs{constructor(e,s){this.renderDataMap=new Map,this.isRenderData=!1,this.videoFrameTexture=null,this.state="OFF",this.opacity=0,this.lastStateUpdate=0,this.stateUpdateInterval=500,this.lastPerformanceCheck=performance.now(),this.lastStatusUpdate=0,this.STATUS_UPDATE_INTERVAL=200,this.statusInitialized=!1,this.lastWebGLStatus={ready:!1,issue:""},this.lastRenderState="OFF",this.lastDataStatus={stream_data:!1,ads:!1,render_data:!1,alpha_mask:!1,placeholders:!1,processing_size:!1,isLive:!1},this.lastKillswitchStatus={web:!1,local:!1},this.lastZipBufferStatus=void 0,this.rendererStopped=!1,this.setWebGLEventListeners=()=>{const r=this.glContext.canvas;r.addEventListener("webglcontextlost",n=>{console.warn("Context lost:",n),n.preventDefault()}),r.addEventListener("webglcontextrestored",()=>{console.log("Context restored!"),this.webgl=new is(this,this.options),this.ads=new as(this.webgl,this.options),this.webgl.init(),this.updateStatusOverlay()})},this.addMetadataBatch=r=>{if(this.rendererStopped){r.forEach(n=>{if(n.alphaMask)try{n.alphaMask.close()}catch{}});return}r.forEach(n=>{var o;if(n.alphaMask){this.options&&g(this.options,"Renderer")&&console.log(\`[RendererWorker] Creating texture for timeCode=\${n.timecode}\`);try{const i=this.webgl.createTextureFromVideoFrame(n.alphaMask),a=n.timecode,c={width:n.processingWidth,height:n.processingHeight},u=n.placeholders??{},l={alphaMask:i,placeholders:u,processingSize:c,isLive:n.isLive},d=n.LED;if(d&&(l.led={cubePlaceholders:d.cubePlaceholders,intrinsics:d.intrinsics,distortion:d.distortion,referenceSize:d.referenceSize,modelVersion:d.modelVersion??((o=d.model)==null?void 0:o.version)},d.model&&d.model.LedModel))try{this.webgl.updateLEDCubesFromModel(d.model,l.led.modelVersion)}catch{}this.renderDataMap.set(a,l),D.setAttributes({last_webgl_uploaded_frame:a})}catch{this.options&&g(this.options,"Errors")&&console.error(\`[RendererWorker] Error creating texture for timeCode=\${n.timecode}\`)}finally{n.alphaMask.close()}}})},this.handleBurnedFrameRender=(r,n)=>{var o;if(!this.streamData||!((o=this.ads)!=null&&o.ads)){r.close();return}try{this.videoFrameTexture&&this.webgl.deleteTexture(this.videoFrameTexture),this.videoFrameTexture=this.webgl.createTextureFromImageBitmap(r);const i=this.renderDataMap.get(n);this.webgl.drawVideoFrameBase(this.videoFrameTexture),i&&(this.webgl.drawAugmentation(i.alphaMask,i.placeholders,i.processingSize,1,!1,this.options.DRAW_TIMESTAMP_WEBGL?n:void 0),this.shot&&(this.shot.frameCount++,this.shot.lastProcessingTime=performance.now())),this.deleteOldTextures(n),D.setAttributes({last_rendered_frame:n,renderer_state:this.state,has_augmentation:!!i,burned_timecode_mode:!0})}catch(i){D.error(\`[Renderer] Error rendering burned frame for timeCode=\${n}\`,{error:i}),this.options&&g(this.options,"Errors")&&console.error("[Renderer] Error rendering burned frame:",i)}finally{r.close()}},this.handleBurnedFrameRenderWithLED=(r,n)=>{var o;if(this.rendererStopped){try{r.close()}catch{}return}if(!this.streamData||!((o=this.ads)!=null&&o.ads)){r.close();return}try{this.videoFrameTexture&&this.webgl.deleteTexture(this.videoFrameTexture),this.videoFrameTexture=this.webgl.createTextureFromImageBitmap(r);const i=this.renderDataMap.get(n);this.webgl.drawVideoFrameBase(this.videoFrameTexture),i&&(i.placeholders&&Object.keys(i.placeholders).length>0&&this.webgl.drawAugmentation(i.alphaMask,i.placeholders,i.processingSize,1,!1,this.options.DRAW_TIMESTAMP_WEBGL?n:void 0),i.led&&this.webgl.drawLEDOverlayOnTop(i.alphaMask,i.led),this.shot&&(this.shot.frameCount++,this.shot.lastProcessingTime=performance.now())),this.deleteOldTextures(n),D.setAttributes({last_rendered_frame:n,renderer_state:this.state,has_augmentation:!!i,has_led:!!(i!=null&&i.led),burned_timecode_mode:!0})}catch(i){D.error(\`[Renderer] Error rendering burned frame with LED for timeCode=\${n}\`,{error:i}),this.options&&g(this.options,"Errors")&&console.error("[Renderer] Error rendering burned frame with LED:",i)}finally{r.close()}},this.handleRenderDraw=(r,n)=>{var p,T,h,R,S,F,I;if(this.rendererStopped||!this.streamData||!((p=this.ads)!=null&&p.ads))return;const o=this.renderDataMap.get(r);!!o!==this.isRenderData&&(o?(this.shot&&this.finalizeShot(this.shot,r),this.shot={shotId:crypto.randomUUID(),adURL:((T=this.ads.ads[0])==null?void 0:T.adUrl)||"",sumPercentOfScreen:0,sumPercentOfAd:0,frameCount:0,start:performance.now(),lastProcessingTime:performance.now()},D.info("didStartDrawingAugmentationMedia",{timecode:r,adID:this.shot.shotId,adURL:this.shot.adURL})):this.shot&&this.finalizeShot(this.shot,r),this.isRenderData=!!o);const i=o?o.isLive:!1,a=!this.zipBufferStatus||this.zipBufferStatus.isReady,c=((h=this.zipBufferStatus)==null?void 0:h.needsFadeout)||!1,u=i&&!c&&!!this.ottActions&&(this.ottActions.toggle[this.streamData.customerId]!==void 0?this.ottActions.toggle[this.streamData.customerId]&&this.ottActions.toggle.web:this.ottActions.toggle.web)&&(this.ottActions.toggle.local!==void 0?this.ottActions.toggle.local:!0),l=((R=this.ottActions)==null?void 0:R.benchmarkPassed)??!1;if(!u||c||!l?(this.state==="ON"||this.state==="FADE_IN")&&(this.state="FADE_OUT"):a&&l&&(this.state==="OFF"||this.state==="FADE_OUT")&&(this.state="FADE_IN"),this.state==="FADE_IN"?(this.opacity===0&&(this.lastStateUpdate=performance.now(),this.opacity=.001),this.opacity=Math.min(1,this.opacity+(performance.now()-this.lastStateUpdate)/this.stateUpdateInterval),this.lastStateUpdate=performance.now(),this.opacity===1&&(this.state="ON")):this.state==="FADE_OUT"&&(this.opacity===1&&(this.lastStateUpdate=performance.now(),this.opacity=.999),this.opacity=Math.max(0,this.opacity-(performance.now()-this.lastStateUpdate)/this.stateUpdateInterval),this.lastStateUpdate=performance.now(),this.opacity===0&&(this.state="OFF")),!o)return;const d=o.alphaMask,f=o.placeholders,m=o.processingSize;if(!(!d||!f||!m)){if((this.glContext.canvas.width!==m.width||this.glContext.canvas.height!==m.height)&&(this.glContext.canvas.width=m.width,this.glContext.canvas.height=m.height),n!=0)if(n>0){const M=$.fromStr(r).addFrames(1,this.streamData.fps),k=(S=this.renderDataMap.get($.toStr(M)))==null?void 0:S.placeholders;k&&Object.keys(k).forEach(A=>{A in f&&(f[A].tranform=f[A].tranform.map((L,W)=>L*(1-n)+k[A].tranform[W]*n))})}else{const M=Math.abs(n),k=$.fromStr(r).subtractFrames(1,this.streamData.fps),A=(F=this.renderDataMap.get($.toStr(k)))==null?void 0:F.placeholders;A&&Object.keys(A).forEach(L=>{L in f&&(f[L].tranform=f[L].tranform.map((W,Z)=>A[L].tranform[Z]*(1-M)+W*M))})}if(this.options&&g(this.options,"Renderer")&&console.log(\`[Renderer] Render logic: binding texture for \${r}\`),D.setAttributes({last_rendered_frame:r,renderer_state:this.state}),this.updateStatusOverlay(),this.webgl.drawAugmentationWithLED(d,f,m,this.opacity,o.led,this.options.DRAW_TIMESTAMP_WEBGL?r:void 0),this.options&&((I=this.options.debug)!=null&&I.trackPerformance)){const M=performance.now();M-this.lastPerformanceCheck>=this.options.PERFORMANCE_TRACKING_INTERVAL&&(this.trackPerformance(),this.lastPerformanceCheck=M)}}},this.handleRenderClear=()=>{this.rendererStopped||(console.log("handleRenderClear"),this.opacity=0,this.state="OFF")},this.getAdURLByCoord=r=>{var c,u;if(!this.ads||!this.streamData||!this.streamData.timeCode||!this.renderDataMap)return null;const n=this.streamData.timeCode,o=(c=this.renderDataMap.get(n))==null?void 0:c.placeholders,i=(u=this.renderDataMap.get(n))==null?void 0:u.processingSize;if(!o||!i)return null;console.log("placeholders: ",o);const a=this.ads.getAdURLAtCoord(o,i,r);return console.log("url: ",a),a},this.deleteTexture=r=>{var o;const n=(o=this.renderDataMap.get(r))==null?void 0:o.alphaMask;n&&(this.webgl.deleteTexture(n),this.renderDataMap.delete(r))},this.deleteOldTextures=r=>{if(!this.streamData)return;const n=59.94,o=$.fromStr(r).totalMilliseconds(n);this.renderDataMap.forEach((i,a)=>{$.fromStr(a).totalMilliseconds(n)<o-100&&(this.options&&g(this.options,"Renderer")&&console.log(\`[Renderer] Deleting old texture for timeCode=\${a}\`),this.webgl.deleteTexture(i.alphaMask),this.renderDataMap.delete(a))})},this.deleteAllTextures=()=>{this.renderDataMap.forEach((r,n)=>{this.webgl.deleteTexture(r.alphaMask),this.renderDataMap.delete(n)})},this.cleanGL=()=>{this.webgl.cleanGL()},this.updateStreamData=r=>{this.streamData=r,this.updateStatusOverlay()},this.finalizeShot=(r,n)=>{r.end=r.lastProcessingTime,r.duration=r.end-r.start,D.info("didEndDrawingAugmentationMedia",{timecode:n,adID:r.shotId,adURL:r.adURL}),r.avaragePercentOfAd=r.sumPercentOfAd/r.frameCount,r.avaragePercentOfScreen=r.sumPercentOfScreen/r.frameCount,D.info("didRegisterShot",{adID:r.shotId,adURL:r.adURL,avaragePercentOfScreen:r.avaragePercentOfScreen.toFixed(2),avaragePercentOfAd:r.avaragePercentOfAd.toFixed(2),frameCount:r.frameCount,duration:r.duration.toFixed(0)}),this.shot=void 0},this.trackPerformance=()=>{const r=this.webgl.getAvgGPUFrameTime(),n=this.webgl.getAvgCPUFrameTime();Ra([{metric:"Rendering GPU time",value:r},{metric:"Rendering CPU time",value:n}],D.getMessagePort())},this.glContext=e,this.webgl=new is(this,s),this.options=s,this.ads=new as(this.webgl,s),this.rendererStopped=!1,this.webgl.init(),this.updateStatusOverlay()}isStopped(){return this.rendererStopped}setZipBufferStatus(e){this.zipBufferStatus=e,this.updateStatusOverlay()}updateStatusOverlay(){var c,u,l,d,f;const e=performance.now(),s=!this.statusInitialized;if(!s&&e-this.lastStatusUpdate<this.STATUS_UPDATE_INTERVAL)return;const r={ready:!!this.glContext&&!this.glContext.isContextLost()&&!!this.webgl,issue:(c=this.glContext)!=null&&c.isContextLost()?"Context Lost":""},n=(u=this.streamData)==null?void 0:u.timeCode,o=n?this.renderDataMap.get(n):void 0,i={stream_data:!!this.streamData,timecode:n||"",ads:!!((l=this.ads)!=null&&l.ads&&this.ads.ads.length>0),render_data:!!o,alpha_mask:!!(o!=null&&o.alphaMask),placeholders:!!(o!=null&&o.placeholders),processing_size:!!(o!=null&&o.processingSize),isLive:(o==null?void 0:o.isLive)||!1},a={web:((d=this.ottActions)==null?void 0:d.toggle.web)!==!1,local:((f=this.ottActions)==null?void 0:f.toggle.local)!==!1};(s||JSON.stringify(r)!==JSON.stringify(this.lastWebGLStatus)||this.state!==this.lastRenderState||JSON.stringify(i)!==JSON.stringify(this.lastDataStatus)||JSON.stringify(a)!==JSON.stringify(this.lastKillswitchStatus)||JSON.stringify(this.zipBufferStatus)!==JSON.stringify(this.lastZipBufferStatus))&&(D.setAttributes({webgl_status:r,renderer_state:this.state,data_status:i,killswitch_status:a,zip_buffer_status:this.zipBufferStatus}),this.lastWebGLStatus=r,this.lastRenderState=this.state,this.lastDataStatus=i,this.lastKillswitchStatus=a,this.lastZipBufferStatus=this.zipBufferStatus,this.lastStatusUpdate=e,this.statusInitialized=!0)}stop(){this.rendererStopped=!0,this.ads&&this.ads.pause(),this.cleanGL(),this.deleteAllTextures(),this.videoFrameTexture&&(this.webgl.deleteTexture(this.videoFrameTexture),this.videoFrameTexture=null)}}let lt=null,ut=null,ls=null,Kt=null,ne=null,b=null,v,C,dt,us=0,ds=0,ft=null,ht,mt=null;self.onmessage=t=>{const{data:e}=t;if(e.type==="SET_LOGGER_PORT"&&(Kt=e.port,D.setMessagePort(e.port)),e.type==="INIT_OFFSCREEN"){const s=e.offscreen;if(v=e.options,ne=s.getContext("webgl"),v&&g(v,"Renderer")&&console.log("[RendererWorker] Initializing OffscreenCanvas"),!ne||ne!=null&&ne.isContextLost()){D.error("[RendererWorker] Failed to acquire WebGL context"),v&&g(v,"Errors")&&console.error("[RendererWorker] Failed to acquire WebGL context");return}b=new cs(ne,v),v&&g(v,"Renderer")&&console.log("[RendererWorker] OffscreenCanvas initialized, gl context acquired"),postMessage({type:"RENDERER_READY"}),(async()=>{var r,n,o,i;try{if(ft){const a=await createImageBitmap(ft);ht?(n=(r=b.ads)==null?void 0:r.overrideAdImageForPlaceholder)==null||n.call(r,a,ht):(o=b.ads)==null||o.overrideAdImage(a),ft=null,ht=void 0}if(mt){const a=await createImageBitmap(mt);(i=b.ads)==null||i.overrideLEDImage(a),mt=null}}catch(a){console.error("[RendererWorker] Failed to flush pending overrides",a)}})()}if(e.type==="SET_DOWNLOADER_PORT"&&(lt=e.port,lt.onmessage=xa),e.type==="SET_DECODER_PORT"&&(ut=e.port,ut.onmessage=ya),e.type==="SET_ADAPTER_PORT"&&(ls=e.port,ls.onmessage=Sa),(e.type==="RENDERER_DRAW"||e.type==="RENDERER_CLEAR")&&fs(e),e.type==="BURNED_FRAME_RENDER"&&va(e),e.type==="VIDEO_CLICK"&&b){const s=b.getAdURLByCoord(e.clickData);postMessage({type:"OPEN_URL",url:s})}if(e.type==="STOP_WORKER"){b&&b.stop();return}if(e.type==="RESTART_WORKER"){if(!ne||!v)return;b&&b.stop(),b=new cs(ne,v),postMessage({type:"RENDERER_READY"});return}};function _a(){!lt||!C||lt.postMessage({type:"DOWNLOADER_INPUT",streamData:C})}function ba(){!ut||!C||ut.postMessage({type:"DECODER_REQUEST",timeCode:C.timeCode,fps:C.fps})}function Ra(t,e){if(!Kt&&!e)return;const s=Kt||e,r={type:"TRACK_PERFORMANCE",data:t};s.postMessage(r)}function fs(t){!b||b.isStopped()||(C=t.streamData,b?(C&&(b.updateStreamData(C),C.ottActions&&(b.ottActions=C.ottActions)),b.cleanGL(),t.type==="RENDERER_CLEAR"&&b.handleRenderClear(),t.type==="RENDERER_DRAW"&&C&&(b.handleRenderDraw(C.timeCode,C.frameCorrection),b.deleteOldTextures(C.timeCode)),hs()):v&&g(v,"Errors")&&console.error("[RendererWorker] WebGL context is not initialized."))}function va(t){if(!b||b.isStopped()){t.imageBitmap.close();return}C=t.streamData,b?(b.updateStreamData(C),C.ottActions&&(b.ottActions=C.ottActions),b.cleanGL(),b.handleBurnedFrameRenderWithLED(t.imageBitmap,t.timecode),hs()):(t.imageBitmap.close(),v&&g(v,"Errors")&&console.error("[RendererWorker] WebGL context not initialized for burned frame"))}self.addEventListener("message",t=>{var s,r,n,o;const e=t.data;if(!b){((e==null?void 0:e.type)==="SET_AD_IMAGE"||(e==null?void 0:e.type)==="SET_LED_IMAGE")&&e.imageBitmap&&e.imageBitmap.close();return}if(e.type==="SET_AD_IMAGE")try{e.placeholder?(r=(s=b.ads)==null?void 0:s.overrideAdImageForPlaceholder)==null||r.call(s,e.imageBitmap,e.placeholder):(n=b.ads)==null||n.overrideAdImage(e.imageBitmap)}catch{try{e.imageBitmap.close()}catch{}}if(e.type==="SET_LED_IMAGE")try{(o=b.ads)==null||o.overrideLEDImage(e.imageBitmap)}catch{try{e.imageBitmap.close()}catch{}}}),self.addEventListener("message",async t=>{var s,r,n,o,i,a;const e=t.data;if(!b){e.type==="SET_AD_BLOB"&&(ft=e.blob,ht=e.placeholder),e.type==="SET_LED_BLOB"&&(mt=e.blob);return}if(e.type==="SET_AD_BLOB")try{v&&g(v,"Renderer")&&console.log("[RendererWorker] SET_AD_BLOB size",(s=e.blob)==null?void 0:s.size);const c=new Blob([await e.blob.arrayBuffer()],{type:e.blob.type||"image/png"}),u=await createImageBitmap(c);e.placeholder?(n=(r=b.ads)==null?void 0:r.overrideAdImageForPlaceholder)==null||n.call(r,u,e.placeholder):(o=b.ads)==null||o.overrideAdImage(u)}catch(c){v&&g(v,"Errors")&&console.error("[RendererWorker] SET_AD_BLOB failed",c)}if(e.type==="SET_LED_BLOB")try{v&&g(v,"Renderer")&&console.log("[RendererWorker] SET_LED_BLOB size",(i=e.blob)==null?void 0:i.size);const c=new Blob([await e.blob.arrayBuffer()],{type:e.blob.type||"image/png"}),u=await createImageBitmap(c);(a=b.ads)==null||a.overrideLEDImage(u)}catch(c){v&&g(v,"Errors")&&console.error("[RendererWorker] SET_LED_BLOB failed",c)}});function hs(){if(!v)return;const t=performance.now();t-us>v.DOWNLOADER_UPDATE_FREQUENCY&&(_a(),us=t),t-ds>v.DECODER_UPDATE_FREQUENCY&&(ba(),ds=t)}function ya(t){if(!b||b.isStopped())return;const{data:e}=t;if(e.type==="RENDERER_INPUT"){const s=e.batch;v&&g(v,"Renderer")&&console.log(\`[RendererWorker] Received a batch of \${s.length} frames\`),b&&b.addMetadataBatch(s)}}function xa(t){const{data:e}=t;if(e.type==="ZIP_BUFFER_STATUS"){dt=e.status,b&&dt&&b.setZipBufferStatus(dt),v&&g(v,"Renderer")&&console.log("[RendererWorker] Zip buffer status:",dt);return}C&&v&&g(v,"Renderer")&&console.log("[RendererWorker] Message from Downloader:",t.data)}function Sa(t){const{data:e}=t;(e.type==="RENDERER_DRAW"||e.type==="RENDERER_CLEAR")&&fs(e)}self.onunhandledrejection=t=>{D.error("[RendererWorker] Unhandled rejection",{error:t.reason}),v&&(g(v,"Errors")&&console.error("[RendererWorker] Unhandled rejection:",t.reason),t.preventDefault())},self.onerror=t=>{D.error("[RendererWorker] Unhandled error",{error:t}),v&&(g(v,"Errors")&&console.error("[RendererWorker] Unhandled error:",t),t instanceof Event&&t.preventDefault())}})();
|
|
396
|
-
`,Vt=typeof self<"u"&&self.Blob&&new Blob([Gt],{type:"text/javascript;charset=utf-8"});function cn(t){let e;try{if(e=Vt&&(self.URL||self.webkitURL).createObjectURL(Vt),!e)throw"";const r=new Worker(e,{name:t==null?void 0:t.name});return r.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),r}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Gt),{name:t==null?void 0:t.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}const Ht='(function(){"use strict";const A=(e,t)=>t==="Errors"?!0:!e.debug||!e.debug.on?!1:e.debug[`log${t}`],jn=e=>Math.abs(e-59.94005994005994)<20?59.94:Math.abs(e-29.97002997002997)<10?29.97:Math.abs(e-14.985014985014985)<8?14.98:0,w={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},I=console,z={};Object.keys(w).forEach(e=>{z[e]=I[e]});const fe="Datadog Browser SDK:",_={debug:z.debug.bind(I,fe),log:z.log.bind(I,fe),info:z.info.bind(I,fe),warn:z.warn.bind(I,fe),error:z.error.bind(I,fe)},Je="https://docs.datadoghq.com",Lt=`${Je}/real_user_monitoring/browser/troubleshooting`,Ce="More details:";function At(e,t){return(...n)=>{try{return e(...n)}catch(r){_.error(t,r)}}}function Oe(e){return e!==0&&Math.random()*100<=e}function Wn(e){return zn(e)&&e>=0&&e<=100}function zn(e){return typeof e=="number"}const pe=1e3,H=60*pe,kt=60*H,Hn=365*(24*kt);function me(){return new Date().getTime()}function $(){return me()}function Re(){return performance.now()}function U(){return{relative:Re(),timeStamp:$()}}function Kn(){return{relative:0,timeStamp:It()}}function Vn(e,t){return t-e}function qn(e,t){return e+t}function Yn(e){return e-It()}let Ze;function It(){return Ze===void 0&&(Ze=performance.timing.navigationStart),Ze}const M=1024,Mt=1024*M,Xn=/[^\\u0000-\\u007F]/;function Qe(e){return Xn.test(e)?window.TextEncoder!==void 0?new TextEncoder().encode(e).length:new Blob([e]).size:e.length}function Jn(e){return{...e}}function Pt(e,t){return Object.keys(e).some(n=>e[n]===t)}function ge(e){return Object.keys(e).length===0}function B(){if(typeof globalThis=="object")return globalThis;Object.defineProperty(Object.prototype,"_dd_temp_",{get(){return this},configurable:!0});let e=_dd_temp_;return delete Object.prototype._dd_temp_,typeof e!="object"&&(typeof self=="object"?e=self:typeof window=="object"?e=window:e={}),e}function te(e,t){const n=B();let r;return n.Zone&&typeof n.Zone.__symbol__=="function"&&(r=e[n.Zone.__symbol__(t)]),r||(r=e[t]),r}let xe,Dt=!1;function Zn(e){xe=e}function Qn(e){Dt=e}function er(e,t,n){const r=n.value;n.value=function(...o){return(xe?b(r):r).apply(this,o)}}function b(e){return function(){return he(e,this,arguments)}}function he(e,t,n){try{return e.apply(t,n)}catch(r){tr(r)}}function tr(e){if(et(e),xe)try{xe(e)}catch(t){et(t)}}function et(...e){Dt&&_.error("[MONITOR]",...e)}function Se(e,t){return te(B(),"setTimeout")(b(e),t)}function Nt(e){te(B(),"clearTimeout")(e)}function tt(e,t){return te(B(),"setInterval")(b(e),t)}function Ft(e){te(B(),"clearInterval")(e)}class v{constructor(t){this.onFirstSubscribe=t,this.observers=[]}subscribe(t){return this.observers.push(t),this.observers.length===1&&this.onFirstSubscribe&&(this.onLastUnsubscribe=this.onFirstSubscribe(this)||void 0),{unsubscribe:()=>{this.observers=this.observers.filter(n=>t!==n),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}}notify(t){this.observers.forEach(n=>n(t))}}function $t(...e){return new v(t=>{const n=e.map(r=>r.subscribe(o=>t.notify(o)));return()=>n.forEach(r=>r.unsubscribe())})}function Ut(e,t,n){let r=!1,o,s;return{throttled:(...i)=>{if(r){o=i;return}e(...i),r=!0,s=Se(()=>{o&&e(...o),r=!1,o=void 0},t)},cancel:()=>{Nt(s),r=!1,o=void 0}}}function G(){}function j(e){return e?(parseInt(e,10)^Math.random()*16>>parseInt(e,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,j)}const Le=/([\\w-]+)\\s*=\\s*([^;]+)/g;function nr(e,t){for(Le.lastIndex=0;;){const n=Le.exec(e);if(n){if(n[1]===t)return n[2]}else break}}function rr(e){const t=new Map;for(Le.lastIndex=0;;){const n=Le.exec(e);if(n)t.set(n[1],n[2]);else break}return t}function or(e,t,n=""){const r=e.charCodeAt(t-1),s=r>=55296&&r<=56319?t+1:t;return e.length<=s?e:`${e.slice(0,s)}${n}`}function sr(){return ir()===0}let Ae;function ir(){return Ae??(Ae=ar())}function ar(e=window){var t;const n=e.navigator.userAgent;return e.chrome||/HeadlessChrome/.test(n)?0:((t=e.navigator.vendor)===null||t===void 0?void 0:t.indexOf("Apple"))===0||/safari/i.test(n)&&!/chrome|android/i.test(n)?1:2}function ye(e,t,n=0,r){const o=new Date;o.setTime(o.getTime()+n);const s=`expires=${o.toUTCString()}`,i=r&&r.crossSite?"none":"strict",a=r&&r.domain?`;domain=${r.domain}`:"",c=r&&r.secure?";secure":"",l=r&&r.partitioned?";partitioned":"";document.cookie=`${e}=${t};${s};path=/;samesite=${i}${a}${c}${l}`}function nt(e){return nr(document.cookie,e)}let rt;function K(e){return rt||(rt=rr(document.cookie)),rt.get(e)}function Bt(e,t){ye(e,"",0,t)}function cr(e){if(document.cookie===void 0||document.cookie===null)return!1;try{const t=`dd_cookie_test_${j()}`,n="test";ye(t,n,H,e);const r=nt(t)===n;return Bt(t,e),r}catch(t){return _.error(t),!1}}let ot;function ur(){if(ot===void 0){const e=`dd_site_test_${j()}`,t="test",n=window.location.hostname.split(".");let r=n.pop();for(;n.length&&!nt(e);)r=`${n.pop()}.${r}`,ye(e,t,pe,{domain:r});Bt(e,{domain:r}),ot=r}return ot}const ne="_dd_s";function ke(e){return Object.values(e)}function lr(e){return Object.entries(e)}const st=4*kt,Gt=15*H,dr=Hn,be={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},jt=/^([a-zA-Z]+)=([a-z0-9-]+)$/,it="&";function fr(e){return!!e&&(e.indexOf(it)!==-1||jt.test(e))}const pr="1";function V(e,t){const n={isExpired:pr};return t.trackAnonymousUser&&(e!=null&&e.anonymousId?n.anonymousId=e==null?void 0:e.anonymousId:n.anonymousId=j()),n}function Ie(e){return ge(e)}function Wt(e){return!Ie(e)}function Me(e){return e.isExpired!==void 0||!mr(e)}function mr(e){return(e.created===void 0||me()-Number(e.created)<st)&&(e.expire===void 0||me()<Number(e.expire))}function zt(e){e.expire=String(me()+Gt)}function at(e){return lr(e).map(([t,n])=>t==="anonymousId"?`aid=${n}`:`${t}=${n}`).join(it)}function Ht(e){const t={};return fr(e)&&e.split(it).forEach(n=>{const r=jt.exec(n);if(r!==null){const[,o,s]=r;o==="aid"?t.anonymousId=s:t[o]=s}}),t}const gr="_dd",hr="_dd_r",Sr="_dd_l",yr="rum",br="logs";function Er(e){if(!K(ne)){const n=K(gr),r=K(hr),o=K(Sr),s={};n&&(s.id=n),o&&/^[01]$/.test(o)&&(s[br]=o),r&&/^[012]$/.test(r)&&(s[yr]=r),Wt(s)&&(zt(s),e.persistSession(s))}}function Kt(e){const t=Cr(e);return cr(t)?{type:be.COOKIE,cookieOptions:t}:void 0}function Tr(e,t){const n={isLockEnabled:sr(),persistSession:wr(t),retrieveSession:vr,expireSession:r=>_r(t,r,e)};return Er(n),n}function wr(e){return t=>{ye(ne,at(t),Gt,e)}}function _r(e,t,n){const r=V(t,n);ye(ne,at(r),n.trackAnonymousUser?dr:st,e)}function vr(){const e=nt(ne);return Ht(e)}function Cr(e){const t={};return t.secure=!!e.useSecureSessionCookie||!!e.usePartitionedCrossSiteSessionCookie,t.crossSite=!!e.usePartitionedCrossSiteSessionCookie,t.partitioned=!!e.usePartitionedCrossSiteSessionCookie,e.trackSessionAcrossSubdomains&&(t.domain=ur()),t}const Or="_dd_test_";function Vt(){try{const e=j(),t=`${Or}${e}`;localStorage.setItem(t,e);const n=localStorage.getItem(t);return localStorage.removeItem(t),e===n?{type:be.LOCAL_STORAGE}:void 0}catch{return}}function Rr(e){return{isLockEnabled:!1,persistSession:qt,retrieveSession:xr,expireSession:t=>Lr(t,e)}}function qt(e){localStorage.setItem(ne,at(e))}function xr(){const e=localStorage.getItem(ne);return Ht(e)}function Lr(e,t){qt(V(e,t))}const Ar=10,kr=100,Yt=[];let Pe;function q(e,t,n=0){var r;const{isLockEnabled:o,persistSession:s,expireSession:i}=t,a=f=>s({...f,lock:l}),c=()=>{const f=t.retrieveSession(),h=f.lock;return f.lock&&delete f.lock,{session:f,lock:h}};if(Pe||(Pe=e),e!==Pe){Yt.push(e);return}if(o&&n>=kr){Xt(t);return}let l,u=c();if(o){if(u.lock){De(e,t,n);return}if(l=j(),a(u.session),u=c(),u.lock!==l){De(e,t,n);return}}let d=e.process(u.session);if(o&&(u=c(),u.lock!==l)){De(e,t,n);return}if(d&&(Me(d)?i(d):(zt(d),o?a(d):s(d))),o&&!(d&&Me(d))){if(u=c(),u.lock!==l){De(e,t,n);return}s(u.session),d=u.session}(r=e.after)===null||r===void 0||r.call(e,d||u.session),Xt(t)}function De(e,t,n){Se(()=>{q(e,t,n+1)},Ar)}function Xt(e){Pe=void 0;const t=Yt.shift();t&&q(t,e)}const Jt=pe;function Ir(e){switch(e.sessionPersistence){case be.COOKIE:return Kt(e);case be.LOCAL_STORAGE:return Vt();case void 0:{let t=Kt(e);return!t&&e.allowFallbackToLocalStorage&&(t=Vt()),t}default:_.error(`Invalid session persistence \'${String(e.sessionPersistence)}\'`)}}function Mr(e,t,n,r){const o=new v,s=new v,i=new v,a=e.type===be.COOKIE?Tr(t,e.cookieOptions):Rr(t),{expireSession:c}=a,l=tt(g,Jt);let u;p();const{throttled:d,cancel:f}=Ut(()=>{q({process:y=>{if(Ie(y))return;const de=E(y);return O(de),de},after:y=>{Wt(y)&&!R()&&Bn(y),u=y}},a)},Jt);function h(){q({process:y=>R()?E(y):void 0},a)}function g(){q({process:y=>Me(y)?V(y,t):void 0,after:E},a)}function E(y){return Me(y)&&(y=V(y,t)),R()&&(F(y)?le():(i.notify({previousState:u,newState:y}),u=y)),y}function p(){q({process:y=>{if(Ie(y))return V(y,t)},after:y=>{u=y}},a)}function O(y){if(Ie(y))return!1;const{trackingType:de,isTracked:Gi}=r(y[n]);y[n]=de,delete y.isExpired,Gi&&!y.id&&(y.id=j(),y.created=String(me()))}function R(){return u[n]!==void 0}function F(y){return u.id!==y.id||u[n]!==y[n]}function le(){u=V(u,t),s.notify()}function Bn(y){u=y,o.notify()}function Gn(y){q({process:de=>({...de,...y}),after:E},a)}return{expandOrRenewSession:d,expandSession:h,getSession:()=>u,renewObservable:o,expireObservable:s,sessionStateUpdateObservable:i,restartSession:p,expire:()=>{f(),c(u),E(V(u,t))},stop:()=>{Ft(l)},updateSessionState:Gn}}const ct={GRANTED:"granted",NOT_GRANTED:"not-granted"};function Pr(e){const t=new v;return{tryToInit(n){e||(e=n)},update(n){e=n,t.notify()},isGranted(){return e===ct.GRANTED},observable:t}}function Y(e,t,n){if(typeof e!="object"||e===null)return JSON.stringify(e);const r=re(Object.prototype),o=re(Array.prototype),s=re(Object.getPrototypeOf(e)),i=re(e);try{return JSON.stringify(e,t,n)}catch{return"<error: unable to serialize object>"}finally{r(),o(),s(),i()}}function re(e){const t=e,n=t.toJSON;return n?(delete t.toJSON,()=>{t.toJSON=n}):G}function ut(e){return Dr(e,location.href).href}function Dr(e,t){const n=Nr();if(n)try{return t!==void 0?new n(e,t):new n(e)}catch(s){throw new Error(`Failed to construct URL: ${String(s)} ${Y({url:e,base:t})}`)}if(t===void 0&&!/:/.test(e))throw new Error(`Invalid URL: \'${e}\'`);let r=document;const o=r.createElement("a");if(t!==void 0){r=document.implementation.createHTMLDocument("");const s=r.createElement("base");s.href=t,r.head.appendChild(s),r.body.appendChild(o)}return o.href=e,o}const Zt=URL;let Ne;function Nr(){if(Ne===void 0)try{Ne=new Zt("http://test/path").href==="http://test/path"}catch{Ne=!1}return Ne?Zt:void 0}const Fr="datad0g.com",$r="dd0g-gov.com",oe="datadoghq.com",Ur="ddog-gov.com",Br="pci.browser-intake-datadoghq.com",Gr=["ddsource","ddtags"];function Ee(e,t,n){const r=jr(e,t);return{build(o,s){const i=zr(e,t,n,o,s);return r(i)},urlPrefix:r(""),trackType:t}}function jr(e,t){const n=`/api/v2/${t}`,r=e.proxy;if(typeof r=="string"){const s=ut(r);return i=>`${s}?ddforward=${encodeURIComponent(`${n}?${i}`)}`}if(typeof r=="function")return s=>r({path:n,parameters:s});const o=Wr(t,e);return s=>`https://${o}${n}?${s}`}function Wr(e,t){const{site:n=oe,internalAnalyticsSubdomain:r}=t;if(e==="logs"&&t.usePciIntake&&n===oe)return Br;if(r&&n===oe)return`${r}.${oe}`;if(n===$r)return`http-intake.logs.${n}`;const o=n.split("."),s=o.pop();return`browser-intake-${o.join("-")}.${s}`}function zr({clientToken:e,internalAnalyticsSubdomain:t},n,r,o,{retry:s,encoding:i}){const a=["sdk_version:6.5.0",`api:${o}`].concat(r);s&&a.push(`retry_count:${s.count}`,`retry_after:${s.lastFailureStatus}`);const c=["ddsource=browser",`ddtags=${encodeURIComponent(a.join(","))}`,`dd-api-key=${e}`,`dd-evp-origin-version=${encodeURIComponent("6.5.0")}`,"dd-evp-origin=browser",`dd-request-id=${j()}`];return i&&c.push(`dd-evp-encoding=${i}`),n==="rum"&&c.push(`batch_time=${$()}`),t&&c.reverse(),c.join("&")}const Hr=200;function Kr(e){const{env:t,service:n,version:r,datacenter:o}=e,s=[];return t&&s.push(Fe("env",t)),n&&s.push(Fe("service",n)),r&&s.push(Fe("version",r)),o&&s.push(Fe("datacenter",o)),s}function Fe(e,t){const n=Hr-e.length-1;(t.length>n||Vr(t))&&_.warn(`${e} value doesn\'t meet tag requirements and will be sanitized. ${Ce} ${Je}/getting_started/tagging/#defining-tags`);const r=t.replace(/,/g,"_");return`${e}:${r}`}function Vr(e){return qr()?new RegExp("[^\\\\p{Ll}\\\\p{Lo}0-9_:./-]","u").test(e):!1}function qr(){try{return new RegExp("[\\\\p{Ll}]","u"),!0}catch{return!1}}function Yr(e){const t=e.site||oe,n=Kr(e),r=Xr(e,n);return{replica:Jr(e,n),site:t,...r}}function Xr(e,t){return{logsEndpointBuilder:Ee(e,"logs",t),rumEndpointBuilder:Ee(e,"rum",t),sessionReplayEndpointBuilder:Ee(e,"replay",t)}}function Jr(e,t){if(!e.replica)return;const n={...e,site:oe,clientToken:e.replica.clientToken},r={logsEndpointBuilder:Ee(n,"logs",t),rumEndpointBuilder:Ee(n,"rum",t)};return{applicationId:e.replica.applicationId,...r}}function Zr(e){return Gr.every(t=>e.includes(t))}function lt(e,t){return e!=null&&typeof e!="string"?(_.error(`${t} must be defined as a string`),!1):!0}function Qr(e){return e&&typeof e=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(e)?(_.error(`Site should be a valid Datadog site. ${Ce} ${Je}/getting_started/site/.`),!1):!0}function $e(e,t){return e!==void 0&&!Wn(e)?(_.error(`${t} Sample Rate should be a number between 0 and 100`),!1):!0}function eo(e){var t,n,r,o,s,i;if(!e||!e.clientToken){_.error("Client Token is not configured, we will not send any data.");return}if(!(!Qr(e.site)||!$e(e.sessionSampleRate,"Session")||!$e(e.telemetrySampleRate,"Telemetry")||!$e(e.telemetryConfigurationSampleRate,"Telemetry Configuration")||!$e(e.telemetryUsageSampleRate,"Telemetry Usage")||!lt(e.version,"Version")||!lt(e.env,"Env")||!lt(e.service,"Service"))){if(e.trackingConsent!==void 0&&!Pt(ct,e.trackingConsent)){_.error(\'Tracking Consent should be either "granted" or "not-granted"\');return}return{beforeSend:e.beforeSend&&At(e.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:Ir(e),sessionSampleRate:(t=e.sessionSampleRate)!==null&&t!==void 0?t:100,telemetrySampleRate:(n=e.telemetrySampleRate)!==null&&n!==void 0?n:20,telemetryConfigurationSampleRate:(r=e.telemetryConfigurationSampleRate)!==null&&r!==void 0?r:5,telemetryUsageSampleRate:(o=e.telemetryUsageSampleRate)!==null&&o!==void 0?o:5,service:e.service||void 0,silentMultipleInit:!!e.silentMultipleInit,allowUntrustedEvents:!!e.allowUntrustedEvents,trackingConsent:(s=e.trackingConsent)!==null&&s!==void 0?s:ct.GRANTED,trackAnonymousUser:(i=e.trackAnonymousUser)!==null&&i!==void 0?i:!0,storeContextsAcrossPages:!!e.storeContextsAcrossPages,batchBytesLimit:16*M,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*pe,batchMessagesLimit:50,messageBytesLimit:256*M,...Yr(e)}}}function to(e){return{session_sample_rate:e.sessionSampleRate,telemetry_sample_rate:e.telemetrySampleRate,telemetry_configuration_sample_rate:e.telemetryConfigurationSampleRate,telemetry_usage_sample_rate:e.telemetryUsageSampleRate,use_before_send:!!e.beforeSend,use_partitioned_cross_site_session_cookie:e.usePartitionedCrossSiteSessionCookie,use_secure_session_cookie:e.useSecureSessionCookie,use_proxy:!!e.proxy,silent_multiple_init:e.silentMultipleInit,track_session_across_subdomains:e.trackSessionAcrossSubdomains,track_anonymous_user:e.trackAnonymousUser,session_persistence:e.sessionPersistence,allow_fallback_to_local_storage:!!e.allowFallbackToLocalStorage,store_contexts_across_pages:!!e.storeContextsAcrossPages,allow_untrusted_events:!!e.allowUntrustedEvents,tracking_consent:e.trackingConsent}}var dt;(function(e){e.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",e.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(dt||(dt={}));const Qt=new Set;function no(e){Array.isArray(e)&&ro(e.filter(t=>Pt(dt,t)))}function ro(e){e.forEach(t=>{Qt.add(t)})}function oo(){return Qt}const Te="?";function P(e){const t=[];let n=ft(e,"stack");const r=String(e);return n&&n.startsWith(r)&&(n=n.slice(r.length)),n&&n.split(`\n`).forEach(o=>{const s=ao(o)||uo(o)||fo(o)||go(o);s&&(!s.func&&s.line&&(s.func=Te),t.push(s))}),{message:ft(e,"message"),name:ft(e,"name"),stack:t}}const en="((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\\\w+\\\\.|\\\\/).*?)",se="(?::(\\\\d+))",so=new RegExp(`^\\\\s*at (.*?) ?\\\\(${en}${se}?${se}?\\\\)?\\\\s*$`,"i"),io=new RegExp(`\\\\((\\\\S*)${se}${se}\\\\)`);function ao(e){const t=so.exec(e);if(!t)return;const n=t[2]&&t[2].indexOf("native")===0,r=t[2]&&t[2].indexOf("eval")===0,o=io.exec(t[2]);return r&&o&&(t[2]=o[1],t[3]=o[2],t[4]=o[3]),{args:n?[t[2]]:[],column:t[4]?+t[4]:void 0,func:t[1]||Te,line:t[3]?+t[3]:void 0,url:n?void 0:t[2]}}const co=new RegExp(`^\\\\s*at ?${en}${se}?${se}??\\\\s*$`,"i");function uo(e){const t=co.exec(e);if(t)return{args:[],column:t[3]?+t[3]:void 0,func:Te,line:t[2]?+t[2]:void 0,url:t[1]}}const lo=/^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;function fo(e){const t=lo.exec(e);if(t)return{args:[],column:t[4]?+t[4]:void 0,func:t[1]||Te,line:+t[3],url:t[2]}}const po=/^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i,mo=/(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;function go(e){const t=po.exec(e);if(!t)return;const n=t[3]&&t[3].indexOf(" > eval")>-1,r=mo.exec(t[3]);return n&&r&&(t[3]=r[1],t[4]=r[2],t[5]=void 0),{args:t[2]?t[2].split(","):[],column:t[5]?+t[5]:void 0,func:t[1]||Te,line:t[4]?+t[4]:void 0,url:t[3]}}function ft(e,t){if(typeof e!="object"||!e||!(t in e))return;const n=e[t];return typeof n=="string"?n:void 0}function ho(e,t,n,r){const o=[{url:t,column:r,line:n}],{name:s,message:i}=yo(e);return{name:s,message:i,stack:o}}const So=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\\s\\S]*)$/;function yo(e){let t,n;return{}.toString.call(e)==="[object String]"&&([,t,n]=So.exec(e)),{name:t,message:n}}function Ue(e){const n=new Error(e);n.name="HandlingStack";let r;return he(()=>{const o=P(n);o.stack=o.stack.slice(2),r=X(o)}),r}function X(e){let t=tn(e);return e.stack.forEach(n=>{const r=n.func==="?"?"<anonymous>":n.func,o=n.args&&n.args.length>0?`(${n.args.join(", ")})`:"",s=n.line?`:${n.line}`:"",i=n.line&&n.column?`:${n.column}`:"";t+=`\n at ${r}${o} @ ${n.url}${s}${i}`}),t}function tn(e){return`${e.name||"Error"}: ${e.message}`}function J(e,t,n,{computeHandlingStack:r}={}){let o=e[t];if(typeof o!="function")if(t in e&&t.startsWith("on"))o=G;else return{stop:G};let s=!1;const i=function(){if(s)return o.apply(this,arguments);const a=Array.from(arguments);let c;he(n,null,[{target:this,parameters:a,onPostCall:u=>{c=u},handlingStack:r?Ue("instrumented method"):void 0}]);const l=o.apply(this,a);return c&&he(c,null,[l]),l};return e[t]=i,{stop:()=>{s=!0,e[t]===i&&(e[t]=o)}}}const bo=220*M,Eo="$",To=3;function D(e,t=bo){const n=re(Object.prototype),r=re(Array.prototype),o=[],s=new WeakMap,i=pt(e,Eo,void 0,o,s),a=JSON.stringify(i);let c=a?a.length:0;if(c>t){gt(t,"discarded",e);return}for(;o.length>0&&c<t;){const l=o.shift();let u=0;if(Array.isArray(l.source))for(let d=0;d<l.source.length;d++){const f=pt(l.source[d],l.path,d,o,s);if(f!==void 0?c+=JSON.stringify(f).length:c+=4,c+=u,u=1,c>t){gt(t,"truncated",e);break}l.target[d]=f}else for(const d in l.source)if(Object.prototype.hasOwnProperty.call(l.source,d)){const f=pt(l.source[d],l.path,d,o,s);if(f!==void 0&&(c+=JSON.stringify(f).length+u+d.length+To,u=1),c>t){gt(t,"truncated",e);break}l.target[d]=f}}return n(),r(),i}function pt(e,t,n,r,o){const s=vo(e);if(!s||typeof s!="object")return wo(s);const i=mt(s);if(i!=="[Object]"&&i!=="[Array]"&&i!=="[Error]")return i;const a=e;if(o.has(a))return`[Reference seen at ${o.get(a)}]`;const c=n!==void 0?`${t}.${n}`:t,l=Array.isArray(s)?[]:{};return o.set(a,c),r.push({source:s,target:l,path:c}),l}function wo(e){return typeof e=="bigint"?`[BigInt] ${e.toString()}`:typeof e=="function"?`[Function] ${e.name||"unknown"}`:typeof e=="symbol"?`[Symbol] ${e.description||e.toString()}`:e}function mt(e){try{if(e instanceof Event)return _o(e);if(e instanceof RegExp)return`[RegExp] ${e.toString()}`;const n=Object.prototype.toString.call(e).match(/\\[object (.*)\\]/);if(n&&n[1])return`[${n[1]}]`}catch{}return"[Unserializable]"}function _o(e){return{type:e.type,isTrusted:e.isTrusted,currentTarget:e.currentTarget?mt(e.currentTarget):null,target:e.target?mt(e.target):null}}function vo(e){const t=e;if(t&&typeof t.toJSON=="function")try{return t.toJSON()}catch{}return e}function gt(e,t,n){_.warn(`The data provided has been ${t} as it is over the limit of ${e} characters:`,n)}const nn="No stack, consider using an instance of Error";function rn({stackTrace:e,originalError:t,handlingStack:n,componentStack:r,startClocks:o,nonErrorPrefix:s,source:i,handling:a}){const c=W(t),l=Co(e,c,s,t),u=Oo(c,e)?X(e):nn,d=c?an(t,i):void 0,f=e?e.name:void 0,h=on(t),g=sn(t);return{startClocks:o,source:i,handling:a,handlingStack:n,componentStack:r,originalError:t,type:f,message:l,stack:u,causes:d,fingerprint:h,context:g}}function Co(e,t,n,r){return e!=null&&e.message&&(e!=null&&e.name)?e.message:t?"Empty message":`${n} ${Y(D(r))}`}function Oo(e,t){return t===void 0?!1:e?!0:t.stack.length>0&&(t.stack.length>1||t.stack[0].url!==void 0)}function on(e){return W(e)&&"dd_fingerprint"in e?String(e.dd_fingerprint):void 0}function sn(e){if(e!==null&&typeof e=="object"&&"dd_context"in e)return e.dd_context}function Ro(e){var t;return(t=/@ (.+)/.exec(e))===null||t===void 0?void 0:t[1]}function W(e){return e instanceof Error||Object.prototype.toString.call(e)==="[object Error]"}function an(e,t){let n=e;const r=[];for(;W(n==null?void 0:n.cause)&&r.length<10;){const o=P(n.cause);r.push({message:n.cause.message,source:t,type:o==null?void 0:o.name,stack:X(o)}),n=n.cause}return r.length?r:void 0}const x={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function xo(e){const t=(o,s)=>{const i=rn({stackTrace:o,originalError:s,startClocks:U(),nonErrorPrefix:"Uncaught",source:x.SOURCE,handling:"unhandled"});e.notify(i)},{stop:n}=Lo(t),{stop:r}=Ao(t);return{stop:()=>{n(),r()}}}function Lo(e){return J(window,"onerror",({parameters:[t,n,r,o,s]})=>{let i;W(s)?i=P(s):i=ho(t,n,r,o),e(i,s??t)})}function Ao(e){return J(window,"onunhandledrejection",({parameters:[t]})=>{const n=t.reason||"Empty reason",r=P(n);e(r,n)})}function ko(e){const t={version:"6.5.0",onReady(n){n()},...e};return Object.defineProperty(t,"_setDebug",{get(){return Qn},enumerable:!1}),t}function Io(e,t,n){const r=e[t];r&&!r.q&&r.version&&_.warn("SDK is loaded more than once. This is unsupported and might have unexpected behavior."),e[t]=n,r&&r.q&&r.q.forEach(o=>At(o,"onReady callback threw an error:")())}function cn(e,t){t.silentMultipleInit||_.error(`${e} is already initialized.`)}function Z(e,t,n,r,o){return ht(e,t,[n],r,o)}function ht(e,t,n,r,{once:o,capture:s,passive:i}={}){const a=b(f=>{!f.isTrusted&&!f.__ddIsTrusted&&!e.allowUntrustedEvents||(o&&d(),r(f))}),c=i?{capture:s,passive:i}:s,l=window.EventTarget&&t instanceof EventTarget?window.EventTarget.prototype:t,u=te(l,"addEventListener");n.forEach(f=>u.call(t,f,a,c));function d(){const f=te(l,"removeEventListener");n.forEach(h=>f.call(t,h,a,c))}return{stop:d}}const Be={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function Mo(e,t){const n=[];t.includes(Be.cspViolation)&&n.push(Do(e));const r=t.filter(o=>o!==Be.cspViolation);return r.length&&n.push(Po(r)),$t(...n)}function Po(e){return new v(t=>{if(!window.ReportingObserver)return;const n=b((o,s)=>o.forEach(i=>t.notify(No(i)))),r=new window.ReportingObserver(n,{types:e,buffered:!0});return r.observe(),()=>{r.disconnect()}})}function Do(e){return new v(t=>{const{stop:n}=Z(e,document,"securitypolicyviolation",r=>{t.notify(Fo(r))});return n})}function No(e){const{type:t,body:n}=e;return un({type:n.id,message:`${t}: ${n.message}`,originalError:e,stack:ln(n.id,n.message,n.sourceFile,n.lineNumber,n.columnNumber)})}function Fo(e){const t=`\'${e.blockedURI}\' blocked by \'${e.effectiveDirective}\' directive`;return un({type:e.effectiveDirective,message:`${Be.cspViolation}: ${t}`,originalError:e,csp:{disposition:e.disposition},stack:ln(e.effectiveDirective,e.originalPolicy?`${t} of the policy "${or(e.originalPolicy,100,"...")}"`:"no policy",e.sourceFile,e.lineNumber,e.columnNumber)})}function un(e){return{startClocks:U(),source:x.REPORT,handling:"unhandled",...e}}function ln(e,t,n,r,o){return n?X({name:e,message:t,stack:[{func:"?",url:n,line:r??void 0,column:o??void 0}]}):void 0}function dn(e,t){const n=window.__ddBrowserSdkExtensionCallback;n&&n({type:e,payload:t})}function fn(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Ge(e,t,n=$o()){if(t===void 0)return e;if(typeof t!="object"||t===null)return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=t.flags||[t.global?"g":"",t.ignoreCase?"i":"",t.multiline?"m":"",t.sticky?"y":"",t.unicode?"u":""].join("");return new RegExp(t.source,o)}if(n.hasAlreadyBeenSeen(t))return;if(Array.isArray(t)){const o=Array.isArray(e)?e:[];for(let s=0;s<t.length;++s)o[s]=Ge(o[s],t[s],n);return o}const r=fn(e)==="object"?e:{};for(const o in t)Object.prototype.hasOwnProperty.call(t,o)&&(r[o]=Ge(r[o],t[o],n));return r}function pn(e){return Ge(void 0,e)}function ie(...e){let t;for(const n of e)n!=null&&(t=Ge(t,n));return t}function $o(){if(typeof WeakSet<"u"){const t=new WeakSet;return{hasAlreadyBeenSeen(n){const r=t.has(n);return r||t.add(n),r}}}const e=[];return{hasAlreadyBeenSeen(t){const n=e.indexOf(t)>=0;return n||e.push(t),n}}}function Uo(){var e;const t=window.navigator;return{status:t.onLine?"connected":"not_connected",interfaces:t.connection&&t.connection.type?[t.connection.type]:void 0,effective_type:(e=t.connection)===null||e===void 0?void 0:e.effectiveType}}function Bo(e){const t=new Set;return e.forEach(n=>t.add(n)),Array.from(t)}function mn(e,t){const n=e.indexOf(t);n>=0&&e.splice(n,1)}const Go=500;function gn(){const e=[];return{add:o=>{e.push(o)>Go&&e.splice(0,1)},remove:o=>{mn(e,o)},drain:o=>{e.forEach(s=>s(o)),e.length=0}}}const Q={log:"log",configuration:"configuration",usage:"usage"},jo=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],Wo=[Ur];let hn=gn(),ae=e=>{hn.add(()=>ae(e))};function zo(e,t){let n;const r=new v,o=new Set,s=!Wo.includes(t.site)&&Oe(t.telemetrySampleRate),i={[Q.log]:s,[Q.configuration]:s&&Oe(t.telemetryConfigurationSampleRate),[Q.usage]:s&&Oe(t.telemetryUsageSampleRate)},a=Ho();ae=l=>{const u=Y(l);if(i[l.type]&&o.size<t.maxTelemetryEventsPerPage&&!o.has(u)){const d=c(e,l,a);r.notify(d),dn("telemetry",d),o.add(u)}},Zn(yn);function c(l,u,d){return ie({type:"telemetry",date:$(),service:l,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:ie(u,{runtime_env:d,connectivity:Uo(),sdk_setup:"npm"}),experimental_features:Array.from(oo())},n!==void 0?n():{})}return{setContextProvider:l=>{n=l},observable:r,enabled:s}}function Ho(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function Ko(){hn.drain()}function Vo(e){return e.site===Fr}function Sn(e,t){et(w.debug,e,t),ae({type:Q.log,message:e,status:"debug",...t})}function yn(e,t){ae({type:Q.log,status:"error",...Xo(e),...t})}function qo(e){ae({type:Q.configuration,configuration:e})}function Yo(e){ae({type:Q.usage,usage:e})}function Xo(e){if(W(e)){const t=P(e);return{error:{kind:t.name,stack:X(Jo(t))},message:t.message}}return{error:{stack:nn},message:`Uncaught ${Y(e)}`}}function Jo(e){return e.stack=e.stack.filter(t=>!t.url||jo.some(n=>t.url.startsWith(n))),e}const we=1/0,Zo=H;let _e=null;const je=new Set;function Qo(){je.forEach(e=>e())}function es({expireDelay:e,maxEntries:t}){let n=[];const r=[];_e||(_e=tt(()=>Qo(),Zo));const o=()=>{const h=Re()-e;for(;n.length>0&&n[n.length-1].endTime<h;){const g=n.pop();g&&r.push(g.startTime)}};je.add(o);function s(h,g){const E={value:h,startTime:g,endTime:we,remove:()=>{mn(n,E)},close:p=>{E.endTime=p}};return t&&n.length>=t&&n.pop(),n.unshift(E),E}function i(h=we,g={returnInactive:!1}){for(const E of n)if(E.startTime<=h){if(g.returnInactive||h<=E.endTime)return E.value;break}}function a(h){const g=n[0];g&&g.endTime===we&&g.close(h)}function c(h=we,g=0){const E=qn(h,g);return n.filter(p=>p.startTime<=E&&h<=p.endTime).map(p=>p.value)}function l(){return n.map(({startTime:h,endTime:g,value:E})=>({startTime:h,endTime:g===we?"Infinity":g,value:E}))}function u(){return r}function d(){n=[]}function f(){je.delete(o),je.size===0&&_e&&(Ft(_e),_e=null)}return{add:s,find:i,closeActive:a,findAll:c,reset:d,stop:f,getAllEntries:l,getDeletedEntries:u}}const ts=H,ns=st;function rs(e,t,n,r){const o=new v,s=new v,i=Mr(e.sessionStoreStrategyType,e,t,n),a=es({expireDelay:ns});i.renewObservable.subscribe(()=>{a.add(c(),Re()),o.notify()}),i.expireObservable.subscribe(()=>{s.notify(),a.closeActive(Re())}),i.expandOrRenewSession(),a.add(c(),Kn().relative),r.observable.subscribe(()=>{r.isGranted()?i.expandOrRenewSession():i.expire()}),os(e,()=>{r.isGranted()&&i.expandOrRenewSession()}),ss(e,()=>i.expandSession()),is(e,()=>i.restartSession());function c(){return{id:i.getSession().id,trackingType:i.getSession()[t],isReplayForced:!!i.getSession().forcedReplay,anonymousId:i.getSession().anonymousId}}return{findSession:(l,u)=>a.find(l,u),renewObservable:o,expireObservable:s,sessionStateUpdateObservable:i.sessionStateUpdateObservable,expire:i.expire,updateSessionState:i.updateSessionState}}function os(e,t){ht(e,window,["click","touchstart","keydown","scroll"],t,{capture:!0,passive:!0})}function ss(e,t){const n=()=>{document.visibilityState==="visible"&&t()};Z(e,document,"visibilitychange",n),tt(n,ts)}function is(e,t){Z(e,window,"resume",t,{capture:!0})}function bn(e){return e>=500}function as(e){try{return e.clone()}catch{return}}const cs=80*M,us=32,En=3*Mt,ls=H,Tn=pe;function wn(e,t,n,r,o){t.transportStatus===0&&t.queuedPayloads.size()===0&&t.bandwidthMonitor.canHandle(e)?vn(e,t,n,{onSuccess:()=>Cn(0,t,n,r,o),onFailure:()=>{t.queuedPayloads.enqueue(e),_n(t,n,r,o)}}):t.queuedPayloads.enqueue(e)}function _n(e,t,n,r){e.transportStatus===2&&Se(()=>{const o=e.queuedPayloads.first();vn(o,e,t,{onSuccess:()=>{e.queuedPayloads.dequeue(),e.currentBackoffTime=Tn,Cn(1,e,t,n,r)},onFailure:()=>{e.currentBackoffTime=Math.min(ls,e.currentBackoffTime*2),_n(e,t,n,r)}})},e.currentBackoffTime)}function vn(e,t,n,{onSuccess:r,onFailure:o}){t.bandwidthMonitor.add(e),n(e,s=>{t.bandwidthMonitor.remove(e),ds(s)?(t.transportStatus=t.bandwidthMonitor.ongoingRequestCount>0?1:2,e.retry={count:e.retry?e.retry.count+1:1,lastFailureStatus:s.status},o()):(t.transportStatus=0,r())})}function Cn(e,t,n,r,o){e===0&&t.queuedPayloads.isFull()&&!t.queueFullReported&&(o({message:`Reached max ${r} events size queued for upload: ${En/Mt}MiB`,source:x.AGENT,startClocks:U()}),t.queueFullReported=!0);const s=t.queuedPayloads;for(t.queuedPayloads=On();s.size()>0;)wn(s.dequeue(),t,n,r,o)}function ds(e){return e.type!=="opaque"&&(e.status===0&&!navigator.onLine||e.status===408||e.status===429||bn(e.status))}function fs(){return{transportStatus:0,currentBackoffTime:Tn,bandwidthMonitor:ps(),queuedPayloads:On(),queueFullReported:!1}}function On(){const e=[];return{bytesCount:0,enqueue(t){this.isFull()||(e.push(t),this.bytesCount+=t.bytesCount)},first(){return e[0]},dequeue(){const t=e.shift();return t&&(this.bytesCount-=t.bytesCount),t},size(){return e.length},isFull(){return this.bytesCount>=En}}}function ps(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(e){return this.ongoingRequestCount===0||this.ongoingByteCount+e.bytesCount<=cs&&this.ongoingRequestCount<us},add(e){this.ongoingRequestCount+=1,this.ongoingByteCount+=e.bytesCount},remove(e){this.ongoingRequestCount-=1,this.ongoingByteCount-=e.bytesCount}}}function ms(e,t,n){const r=fs(),o=(s,i)=>Ss(e,t,s,i);return{send:s=>{wn(s,r,o,e.trackType,n)},sendOnExit:s=>{gs(e,t,s)}}}function gs(e,t,n){if(!!navigator.sendBeacon&&n.bytesCount<t)try{const s=e.build("beacon",n);if(navigator.sendBeacon(s,n.data))return}catch(s){hs(s)}const o=e.build("xhr",n);St(o,n.data)}let Rn=!1;function hs(e){Rn||(Rn=!0,yn(e))}function Ss(e,t,n,r){if(ys()&&n.bytesCount<t){const s=e.build("fetch",n);fetch(s,{method:"POST",body:n.data,keepalive:!0,mode:"cors"}).then(b(i=>r==null?void 0:r({status:i.status,type:i.type})),b(()=>{const i=e.build("xhr",n);St(i,n.data,r)}))}else{const s=e.build("xhr",n);St(s,n.data,r)}}function ys(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function St(e,t,n){const r=new XMLHttpRequest;r.open("POST",e,!0),t instanceof Blob&&r.setRequestHeader("Content-Type",t.type),Z({allowUntrustedEvents:!0},r,"loadend",()=>{n==null||n({status:r.status})},{once:!0}),r.send(t)}function yt(){const e=bs();if(e)return{getCapabilities(){var t;return JSON.parse(((t=e.getCapabilities)===null||t===void 0?void 0:t.call(e))||"[]")},getPrivacyLevel(){var t;return(t=e.getPrivacyLevel)===null||t===void 0?void 0:t.call(e)},getAllowedWebViewHosts(){return JSON.parse(e.getAllowedWebViewHosts())},send(t,n,r){const o=r?{id:r}:void 0;e.send(JSON.stringify({eventType:t,event:n,view:o}))}}}function We(e){var t;e===void 0&&(e=(t=B().location)===null||t===void 0?void 0:t.hostname);const n=yt();return!!n&&n.getAllowedWebViewHosts().some(r=>e===r||e.endsWith(`.${r}`))}function bs(){return B().DatadogEventBridge}const ze={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function Es(e){return new v(t=>{const{stop:n}=ht(e,window,["visibilitychange","freeze"],o=>{o.type==="visibilitychange"&&document.visibilityState==="hidden"?t.notify({reason:ze.HIDDEN}):o.type==="freeze"&&t.notify({reason:ze.FROZEN})},{capture:!0}),r=Z(e,window,"beforeunload",()=>{t.notify({reason:ze.UNLOADING})}).stop;return()=>{n(),r()}})}function Ts(e){return ke(ze).includes(e)}function ws({encoder:e,request:t,flushController:n,messageBytesLimit:r}){let o={};const s=n.flushObservable.subscribe(d=>u(d));function i(d,f,h){n.notifyBeforeAddMessage(f),h!==void 0?(o[h]=d,n.notifyAfterAddMessage()):e.write(e.isEmpty?d:`\n${d}`,g=>{n.notifyAfterAddMessage(g-f)})}function a(d){return d!==void 0&&o[d]!==void 0}function c(d){const f=o[d];delete o[d];const h=e.estimateEncodedBytesCount(f);n.notifyAfterRemoveMessage(h)}function l(d,f){const h=Y(d),g=e.estimateEncodedBytesCount(h);if(g>=r){_.warn(`Discarded a message whose size was bigger than the maximum allowed size ${r}KB. ${Ce} ${Lt}/#technical-limitations`);return}a(f)&&c(f),i(h,g,f)}function u(d){const f=ke(o).join(`\n`);o={};const h=Ts(d.reason),g=h?t.sendOnExit:t.send;if(h&&e.isAsync){const E=e.finishSync();E.outputBytesCount&&g(xn(E));const p=[E.pendingData,f].filter(Boolean).join(`\n`);p&&g({data:p,bytesCount:Qe(p)})}else f&&e.write(e.isEmpty?f:`\n${f}`),e.finish(E=>{g(xn(E))})}return{flushController:n,add:l,upsert:l,stop:s.unsubscribe}}function xn(e){let t;return typeof e.output=="string"?t=e.output:t=new Blob([e.output],{type:"text/plain"}),{data:t,bytesCount:e.outputBytesCount,encoding:e.encoding}}function _s({messagesLimit:e,bytesLimit:t,durationLimit:n,pageExitObservable:r,sessionExpireObservable:o}){const s=r.subscribe(g=>u(g.reason)),i=o.subscribe(()=>u("session_expire")),a=new v(()=>()=>{s.unsubscribe(),i.unsubscribe()});let c=0,l=0;function u(g){if(l===0)return;const E=l,p=c;l=0,c=0,h(),a.notify({reason:g,messagesCount:E,bytesCount:p})}let d;function f(){d===void 0&&(d=Se(()=>{u("duration_limit")},n))}function h(){Nt(d),d=void 0}return{flushObservable:a,get messagesCount(){return l},notifyBeforeAddMessage(g){c+g>=t&&u("bytes_limit"),l+=1,c+=g,f()},notifyAfterAddMessage(g=0){c+=g,l>=e?u("messages_limit"):c>=t&&u("bytes_limit")},notifyAfterRemoveMessage(g){c-=g,l-=1,l===0&&h()}}}function Ln(e,t,n,r,o,s,i=ws){const a=l(e,t),c=n&&l(e,n);function l(u,{endpoint:d,encoder:f}){return i({encoder:f,request:ms(d,u.batchBytesLimit,r),flushController:_s({messagesLimit:u.batchMessagesLimit,bytesLimit:u.batchBytesLimit,durationLimit:u.flushTimeout,pageExitObservable:o,sessionExpireObservable:s}),messageBytesLimit:u.messageBytesLimit})}return{flushObservable:a.flushController.flushObservable,add(u,d=!0){a.add(u),c&&d&&c.add(n.transformMessage?n.transformMessage(u):u)},upsert:(u,d)=>{a.upsert(u,d),c&&c.upsert(n.transformMessage?n.transformMessage(u):u,d)},stop:()=>{a.stop(),c&&c.stop()}}}function He(){let e="",t=0;return{isAsync:!1,get isEmpty(){return!e},write(n,r){const o=Qe(n);t+=o,e+=n,r&&r(o)},finish(n){n(this.finishSync())},finishSync(){const n={output:e,outputBytesCount:t,rawBytesCount:t,pendingData:""};return e="",t=0,n},estimateEncodedBytesCount(n){return n.length}}}class vs{constructor(){this.callbacks={}}notify(t,n){const r=this.callbacks[t];r&&r.forEach(o=>o(n))}subscribe(t,n){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(n),{unsubscribe:()=>{this.callbacks[t]=this.callbacks[t].filter(r=>n!==r)}}}}function Cs(e,t,n){let r=0,o=!1;return{isLimitReached(){if(r===0&&Se(()=>{r=0},H),r+=1,r<=t||o)return o=!1,!1;if(r===t+1){o=!0;try{n({message:`Reached max number of ${e}s by minute: ${t}`,source:x.AGENT,startClocks:U()})}finally{o=!1}}return!0}}}let bt;const Et=new WeakMap;function Os(e){return bt||(bt=Rs(e)),bt}function Rs(e){return new v(t=>{const{stop:n}=J(XMLHttpRequest.prototype,"open",xs),{stop:r}=J(XMLHttpRequest.prototype,"send",s=>{Ls(s,e,t)},{computeHandlingStack:!0}),{stop:o}=J(XMLHttpRequest.prototype,"abort",As);return()=>{n(),r(),o()}})}function xs({target:e,parameters:[t,n]}){Et.set(e,{state:"open",method:String(t).toUpperCase(),url:ut(String(n))})}function Ls({target:e,handlingStack:t},n,r){const o=Et.get(e);if(!o)return;const s=o;s.state="start",s.startClocks=U(),s.isAborted=!1,s.xhr=e,s.handlingStack=t;let i=!1;const{stop:a}=J(e,"onreadystatechange",()=>{e.readyState===XMLHttpRequest.DONE&&c()}),c=()=>{if(l(),a(),i)return;i=!0;const u=o;u.state="complete",u.duration=Vn(s.startClocks.timeStamp,$()),u.status=e.status,r.notify(Jn(u))},{stop:l}=Z(n,e,"loadend",c);r.notify(s)}function As({target:e}){const t=Et.get(e);t&&(t.isAborted=!0)}let Tt;function An(){return Tt||(Tt=ks()),Tt}function ks(){return new v(e=>{if(!window.fetch)return;const{stop:t}=J(window,"fetch",n=>Is(n,e),{computeHandlingStack:!0});return t})}function Is({parameters:e,onPostCall:t,handlingStack:n},r){const[o,s]=e;let i=s&&s.method;i===void 0&&o instanceof Request&&(i=o.method);const a=i!==void 0?String(i).toUpperCase():"GET",c=o instanceof Request?o.url:ut(String(o)),l=U(),u={state:"start",init:s,input:o,method:a,startClocks:l,url:c,handlingStack:n};r.notify(u),e[0]=u.input,e[1]=u.init,t(d=>Ms(r,d,u))}function Ms(e,t,n){const r=n;function o(s){r.state="resolve",Object.assign(r,s),e.notify(r)}t.then(b(s=>{o({response:s,responseType:s.type,status:s.status,isAborted:!1})}),b(s=>{var i,a;o({status:0,isAborted:((a=(i=r.init)===null||i===void 0?void 0:i.signal)===null||a===void 0?void 0:a.aborted)||s instanceof DOMException&&s.code===DOMException.ABORT_ERR,error:s})}))}let wt={};function Ps(e){const t=e.map(n=>(wt[n]||(wt[n]=Ds(n)),wt[n]));return $t(...t)}function Ds(e){return new v(t=>{const n=I[e];return I[e]=(...r)=>{n.apply(console,r);const o=Ue("console error");he(()=>{t.notify(Ns(r,e,o))})},()=>{I[e]=n}})}function Ns(e,t,n){const r=e.map(s=>Fs(s)).join(" ");let o;if(t===w.error){const s=e.find(W);o={stack:s?X(P(s)):void 0,fingerprint:on(s),causes:s?an(s,"console"):void 0,startClocks:U(),message:r,source:x.CONSOLE,handling:"handled",handlingStack:n,context:sn(s)}}return{api:t,message:r,error:o,handlingStack:n}}function Fs(e){return typeof e=="string"?D(e):W(e)?tn(P(e)):Y(D(e),void 0,2)}function $s(e){const t=fn(e)==="object";return t||_.error("Unsupported context:",e),t}function _t(e,t,n){const r={...e};for(const[o,{required:s,type:i}]of Object.entries(t))i==="string"&&o in r&&(r[o]=String(r[o])),s&&!(o in e)&&_.warn(`The property ${o} of ${n} is required; context will not be sent to the intake.`);return r}function Ke(e="",{customerDataTracker:t,propertiesConfig:n={}}={}){let r={};const o=new v,s={getContext:()=>pn(r),setContext:i=>{$s(i)?(r=D(_t(i,n,e)),t==null||t.updateCustomerData(r)):s.clearContext(),o.notify()},setContextProperty:(i,a)=>{r=D(_t({...r,[i]:a},n,e)),t==null||t.updateCustomerData(r),o.notify()},removeContextProperty:i=>{delete r[i],t==null||t.updateCustomerData(r),_t(r,n,e),o.notify()},clearContext:()=>{r={},t==null||t.resetCustomerData(),o.notify()},changeObservable:o};return s}const Us="_dd_c",Bs=[];function vt(e,t,n,r){const o=Gs(n,r);Bs.push(Z(e,window,"storage",({key:l})=>{o===l&&i()})),t.changeObservable.subscribe(a);const s=ie(c(),t.getContext());ge(s)||t.setContext(s);function i(){t.setContext(c())}function a(){localStorage.setItem(o,JSON.stringify(t.getContext()))}function c(){const l=localStorage.getItem(o);return l?JSON.parse(l):{}}}function Gs(e,t){return`${Us}_${e}_${t}`}const js=3*M,Ws=16*M,zs=200;function Hs(e=2){const t=new Map;let n=!1;function r(o=0){if(n||e===0)return;const s=e===2?js:Ws;let i=o;t.forEach(a=>{i+=a.getBytesCount()}),i>s&&(Ks(s),n=!0)}return{createDetachedTracker:()=>{const o=kn(()=>r(o.getBytesCount()));return o},getOrCreateTracker:o=>(t.has(o)||t.set(o,kn(r)),t.get(o)),setCompressionStatus:o=>{e===0&&(e=o,r())},getCompressionStatus:()=>e,stop:()=>{t.forEach(o=>o.stop()),t.clear()}}}function kn(e){let t=0;const{throttled:n,cancel:r}=Ut(s=>{t=Qe(Y(s)),e()},zs),o=()=>{r(),t=0};return{updateCustomerData:s=>{ge(s)?o():n(s)},resetCustomerData:o,getBytesCount:()=>t,stop:()=>{r()}}}function Ks(e){_.warn(`Customer data exceeds the recommended ${e/M}KiB threshold. ${Ce} ${Lt}/#customer-data-exceeds-the-recommended-threshold-warning`)}function Vs(e,t,n){const r=e.getReader(),o=[];let s=0;i();function i(){r.read().then(b(c=>{if(c.done){a();return}o.push(c.value),s+=c.value.length,s>n.bytesLimit?a():i()}),b(c=>t(c)))}function a(){r.cancel().catch(G);let c,l;{let u;if(o.length===1)u=o[0];else{u=new Uint8Array(s);let d=0;o.forEach(f=>{u.set(f,d),d+=f.length})}c=u.slice(0,n.bytesLimit),l=u.length>n.bytesLimit}t(void 0,c,l)}}const qs="datadog-synthetics-public-id",Ys="datadog-synthetics-result-id",Xs="datadog-synthetics-injects-rum";function In(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||K(Xs))}function Js(){const e=window._DATADOG_SYNTHETICS_PUBLIC_ID||K(qs);return typeof e=="string"?e:void 0}function Zs(){const e=window._DATADOG_SYNTHETICS_RESULT_ID||K(Ys);return typeof e=="string"?e:void 0}function Ve(e,t,n){const r=n.getHandler(),o=Array.isArray(r)?r:[r];return Mn[e]>=Mn[n.getLevel()]&&o.includes(t)}const S={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},Mn={[S.ok]:0,[S.debug]:1,[S.info]:2,[S.notice]:4,[S.warn]:5,[S.error]:6,[S.critical]:7,[S.alert]:8,[S.emerg]:9};function qe(e,{includeMessage:t=!1}={}){return{stack:e.stack,kind:e.type,message:t?e.message:void 0,causes:e.causes,fingerprint:e.fingerprint,handling:e.handling}}var Qs=function(e,t,n,r){var o=arguments.length,s=o<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s};const ve={console:"console",http:"http",silent:"silent"},ei=Object.keys(S);let k=class{constructor(t,n,r,o=ve.http,s=S.debug,i={}){this.handleLogStrategy=t,this.handlerType=o,this.level=s,this.contextManager=Ke("logger",{customerDataTracker:n}),this.contextManager.setContext(i),r&&this.contextManager.setContextProperty("logger",{name:r})}logImplementation(t,n,r=S.info,o,s){const i=D(n);let a;if(o!=null){const c=rn({stackTrace:W(o)?P(o):void 0,originalError:o,nonErrorPrefix:"Provided",source:x.LOGGER,handling:"handled",startClocks:U()});a=ie({error:qe(c,{includeMessage:!0})},i)}else a=i;this.handleLogStrategy({message:D(t),context:a,status:r},this,s)}log(t,n,r=S.info,o){let s;Ve(r,ve.http,this)&&(s=Ue("log")),this.logImplementation(t,n,r,o,s)}setContext(t){this.contextManager.setContext(t)}getContext(){return this.contextManager.getContext()}setContextProperty(t,n){this.contextManager.setContextProperty(t,n)}removeContextProperty(t){this.contextManager.removeContextProperty(t)}clearContext(){this.contextManager.clearContext()}setHandler(t){this.handlerType=t}getHandler(){return this.handlerType}setLevel(t){this.level=t}getLevel(){return this.level}};Qs([er],k.prototype,"logImplementation",null),k.prototype.ok=N(S.ok),k.prototype.debug=N(S.debug),k.prototype.info=N(S.info),k.prototype.notice=N(S.notice),k.prototype.warn=N(S.warn),k.prototype.error=N(S.error),k.prototype.critical=N(S.critical),k.prototype.alert=N(S.alert),k.prototype.emerg=N(S.emerg);function N(e){return function(t,n,r){let o;Ve(e,ve.http,this)&&(o=Ue("log")),this.logImplementation(t,n,e,r,o)}}function ti(e,t,n){return{view:{referrer:document.referrer,url:window.location.href},context:e.getContext(),user:t.getContext(),account:n.getContext()}}const ni=32*M;function ri(e){e.usePciIntake===!0&&e.site&&e.site!=="datadoghq.com"&&_.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");const t=eo(e),n=Pn(e.forwardConsoleLogs,ke(w),"Forward Console Logs"),r=Pn(e.forwardReports,ke(Be),"Forward Reports");if(!(!t||!n||!r))return e.forwardErrorsToLogs&&!n.includes(w.error)&&n.push(w.error),{forwardErrorsToLogs:e.forwardErrorsToLogs!==!1,forwardConsoleLogs:n,forwardReports:r,requestErrorResponseLengthLimit:ni,...t}}function Pn(e,t,n){if(e===void 0)return[];if(!(e==="all"||Array.isArray(e)&&e.every(r=>t.includes(r)))){_.error(`${n} should be "all" or an array with allowed values "${t.join(\'", "\')}"`);return}return e==="all"?t:Bo(e)}function oi(e){const t=to(e);return{forward_errors_to_logs:e.forwardErrorsToLogs,forward_console_logs:e.forwardConsoleLogs,forward_reports:e.forwardReports,use_pci_intake:e.usePciIntake,...t}}function si(e,t,n){const r=gn();let o,s;const i=t.observable.subscribe(a);function a(){if(!s||!o||!t.isGranted())return;i.unsubscribe();const c=n(o,s);r.drain(c)}return{init(c){if(!c){_.error("Missing configuration");return}if(no(c.enableExperimentalFeatures),We()&&(c=ii(c)),o=c,s){cn("DD_LOGS",c);return}const l=ri(c);l&&(s=l,An().subscribe(G),t.tryToInit(l.trackingConsent),a())},get initConfiguration(){return o},getInternalContext:G,handleLog(c,l,u,d=e(),f=$()){r.add(h=>h.handleLog(c,l,u,d,f))}}}function ii(e){return{...e,clientToken:"empty"}}const Ct="logs";function ai(e){const t=Hs(),n=Ke("global context",{customerDataTracker:t.getOrCreateTracker(2)}),r=Ke("user",{customerDataTracker:t.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),o=Ke("account",{customerDataTracker:t.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),s=Pr();function i(){return ti(n,r,o)}let a=si(i,s,(u,d)=>{u.storeContextsAcrossPages&&(vt(d,n,Ct,2),vt(d,r,Ct,1),vt(d,o,Ct,4));const f=e(u,d,i,s);return a=ci(u,f),f});const c={},l=new k((...u)=>a.handleLog(...u),t.createDetachedTracker());return ko({logger:l,init:b(u=>a.init(u)),setTrackingConsent:b(u=>{s.update(u),Yo({feature:"set-tracking-consent",tracking_consent:u})}),getGlobalContext:b(()=>n.getContext()),setGlobalContext:b(u=>n.setContext(u)),setGlobalContextProperty:b((u,d)=>n.setContextProperty(u,d)),removeGlobalContextProperty:b(u=>n.removeContextProperty(u)),clearGlobalContext:b(()=>n.clearContext()),createLogger:b((u,d={})=>(c[u]=new k((...f)=>a.handleLog(...f),t.createDetachedTracker(),D(u),d.handler,d.level,D(d.context)),c[u])),getLogger:b(u=>c[u]),getInitConfiguration:b(()=>pn(a.initConfiguration)),getInternalContext:b(u=>a.getInternalContext(u)),setUser:b(r.setContext),getUser:b(r.getContext),setUserProperty:b(r.setContextProperty),removeUserProperty:b(r.removeContextProperty),clearUser:b(r.clearContext),setAccount:b(o.setContext),getAccount:b(o.getContext),setAccountProperty:b(o.setContextProperty),removeAccountProperty:b(o.removeContextProperty),clearAccount:b(o.clearContext)})}function ci(e,t){return{init:n=>{cn("DD_LOGS",n)},initConfiguration:e,...t}}const ui="logs";function li(e,t){const n=rs(e,ui,r=>fi(e,r),t);return{findTrackedSession:(r,o={returnInactive:!1})=>{const s=n.findSession(r,o);return s&&s.trackingType==="1"?{id:s.id,anonymousId:s.anonymousId}:void 0},expireObservable:n.expireObservable}}function di(e){const n=Dn(e)==="1"?{}:void 0;return{findTrackedSession:()=>n,expireObservable:new v}}function Dn(e){return Oe(e.sessionSampleRate)?"1":"0"}function fi(e,t){const n=pi(t)?t:Dn(e);return{trackingType:n,isTracked:n==="1"}}function pi(e){return e==="0"||e==="1"}let Nn=!1;function Ye(e){const t=window;if(In()){const r=n(t.DD_RUM_SYNTHETICS);return!r&&!Nn&&(Nn=!0,Sn("Logs sent before RUM is injected by the synthetics worker",{testId:Js(),resultId:Zs()})),r}return n(t.DD_RUM);function n(r){if(r&&r.getInternalContext)return r.getInternalContext(e)}}function mi(e,t,n,r,o){const s=ei.concat(["custom"]),i={};s.forEach(a=>{i[a]=Cs(a,t.eventRateLimiterThreshold,o)}),n.subscribe(0,({rawLogsEvent:a,messageContext:c=void 0,savedCommonContext:l=void 0,domainContext:u})=>{var d,f;const h=Yn(a.date),g=e.findTrackedSession(h);if(!e.findTrackedSession(h,{returnInactive:!0}))return;const p=l||r();let O;!ge(p.account)&&p.account.id&&(O=p.account),g&&g.anonymousId&&!p.user.anonymous_id&&(p.user.anonymous_id=g.anonymousId);const R=ie({service:t.service,session_id:g?g.id:void 0,session:g?{id:g.id}:void 0,usr:ge(p.user)?void 0:p.user,account:O,view:p.view},p.context,Ye(h),a,c);((d=t.beforeSend)===null||d===void 0?void 0:d.call(t,R,u))===!1||R.origin!==x.AGENT&&((f=i[R.status])!==null&&f!==void 0?f:i.custom).isLimitReached()||n.notify(1,R)})}const gi={[w.log]:S.info,[w.debug]:S.debug,[w.info]:S.info,[w.warn]:S.warn,[w.error]:S.error};function hi(e,t){const n=Ps(e.forwardConsoleLogs).subscribe(r=>{var o;const s={rawLogsEvent:{date:$(),message:r.message,origin:x.CONSOLE,error:r.error&&qe(r.error),status:gi[r.api]},messageContext:(o=r.error)===null||o===void 0?void 0:o.context,domainContext:{handlingStack:r.handlingStack}};t.notify(0,s)});return{stop:()=>{n.unsubscribe()}}}function Si(e,t){const n=Mo(e,e.forwardReports).subscribe(r=>{let o=r.message,s;const i=r.originalError.type==="deprecation"?S.warn:S.error;i===S.error?s=qe(r):r.stack&&(o+=` Found in ${Ro(r.stack)}`),t.notify(0,{rawLogsEvent:{date:$(),message:o,origin:x.REPORT,error:s,status:i}})});return{stop:()=>{n.unsubscribe()}}}function yi(e,t){if(!e.forwardErrorsToLogs)return{stop:G};const n=Os(e).subscribe(s=>{s.state==="complete"&&o("xhr",s)}),r=An().subscribe(s=>{s.state==="resolve"&&o("fetch",s)});function o(s,i){!Zr(i.url)&&(wi(i)||bn(i.status))&&("xhr"in i?bi(i.xhr,e,a):i.response?Ti(i.response,e,a):i.error&&Ei(i.error,e,a));function a(c){const l={isAborted:i.isAborted,handlingStack:i.handlingStack};t.notify(0,{rawLogsEvent:{message:`${_i(s)} error ${i.method} ${i.url}`,date:i.startClocks.timeStamp,error:{stack:c||"Failed to load",handling:void 0},http:{method:i.method,status_code:i.status,url:i.url},status:S.error,origin:x.NETWORK},domainContext:l})}}return{stop:()=>{n.unsubscribe(),r.unsubscribe()}}}function bi(e,t,n){typeof e.response=="string"?n(Ot(e.response,t)):n(e.response)}function Ei(e,t,n){n(Ot(X(P(e)),t))}function Ti(e,t,n){const r=as(e);!r||!r.body?n():window.TextDecoder?vi(r.body,t.requestErrorResponseLengthLimit,(o,s)=>{n(o?`Unable to retrieve response: ${o}`:s)}):r.text().then(b(o=>n(Ot(o,t))),b(o=>n(`Unable to retrieve response: ${o}`)))}function wi(e){return e.status===0&&e.responseType!=="opaque"}function Ot(e,t){return e.length>t.requestErrorResponseLengthLimit?`${e.substring(0,t.requestErrorResponseLengthLimit)}...`:e}function _i(e){return e==="xhr"?"XHR":"Fetch"}function vi(e,t,n){Vs(e,(r,o,s)=>{if(r)n(r);else{let i=new TextDecoder().decode(o);s&&(i+="..."),n(void 0,i)}},{bytesLimit:t,collectStreamBody:!0})}function Ci(e,t){if(!e.forwardErrorsToLogs)return{stop:G};const n=new v,{stop:r}=xo(n),o=n.subscribe(s=>{t.notify(0,{rawLogsEvent:{message:s.message,date:s.startClocks.timeStamp,error:qe(s),origin:x.SOURCE,status:S.error},messageContext:s.context})});return{stop:()=>{r(),o.unsubscribe()}}}const Oi=vs;function Ri(e){function t(n,r,o,s,i){const a=ie(r.getContext(),n.context);if(Ve(n.status,ve.console,r)&&Li(n,a),Ve(n.status,ve.http,r)){const c={rawLogsEvent:{date:i||$(),message:n.message,status:n.status,origin:x.LOGGER},messageContext:a,savedCommonContext:s};o&&(c.domainContext={handlingStack:o}),e.notify(0,c)}}return{handleLog:t}}const xi={[S.ok]:w.debug,[S.debug]:w.debug,[S.info]:w.info,[S.notice]:w.info,[S.warn]:w.warn,[S.error]:w.error,[S.critical]:w.error,[S.alert]:w.error,[S.emerg]:w.error};function Li({status:e,message:t},n){z[xi[e]].call(I,t,n)}function Ai(e,t,n,r,o){const s=Ln(e,{endpoint:e.logsEndpointBuilder,encoder:He()},e.replica&&{endpoint:e.replica.logsEndpointBuilder,encoder:He()},n,r,o.expireObservable);return t.subscribe(1,i=>{s.add(i)}),s}function ki(e){const t=yt();e.subscribe(1,n=>{t.send("log",n)})}function Ii(e){return{get:t=>{const n=e.findTrackedSession(t);if(n)return{session_id:n.id}}}}function Mi(e){return t=>{e.notify(0,{rawLogsEvent:{message:t.message,date:t.startClocks.timeStamp,origin:x.AGENT,status:S.error}}),Sn("Error reported to customer",{"error.message":t.message})}}function Pi(e,t,n,r,o){const s=zo("browser-logs-sdk",t);s.setContextProvider(()=>{var a,c,l,u,d,f;return{application:{id:(a=Ye())===null||a===void 0?void 0:a.application_id},session:{id:(c=o.findTrackedSession())===null||c===void 0?void 0:c.id},view:{id:(u=(l=Ye())===null||l===void 0?void 0:l.view)===null||u===void 0?void 0:u.id},action:{id:(f=(d=Ye())===null||d===void 0?void 0:d.user_action)===null||f===void 0?void 0:f.id}}});const i=[];if(We()){const a=yt(),c=s.observable.subscribe(l=>a.send("internal_telemetry",l));i.push(()=>c.unsubscribe())}else{const a=Ln(t,{endpoint:t.rumEndpointBuilder,encoder:He()},t.replica&&{endpoint:t.replica.rumEndpointBuilder,encoder:He()},n,r,o.expireObservable);i.push(()=>a.stop());const c=s.observable.subscribe(l=>a.add(l,Vo(t)));i.push(()=>c.unsubscribe())}return Ko(),qo(oi(e)),{telemetry:s,stop:()=>{i.forEach(a=>a())}}}function Di(e,t,n,r){const o=new Oi,s=[];o.subscribe(1,f=>dn("logs",f));const i=Mi(o),a=Es(t),c=t.sessionStoreStrategyType&&!We()&&!In()?li(t,r):di(t),{stop:l}=Pi(e,t,i,a,c);s.push(()=>l()),yi(t,o),Ci(t,o),hi(t,o),Si(t,o);const{handleLog:u}=Ri(o);if(mi(c,t,o,n,i),We())ki(o);else{const{stop:f}=Ai(t,o,i,a,c);s.push(()=>f())}const d=Ii(c);return{handleLog:u,getInternalContext:d.get,stop:()=>{s.forEach(f=>f())}}}const ce=ai(Di);Io(B(),"DD_LOGS",ce);const C=class C{constructor(t,n,r,o,s){this.copy=()=>new C(this.h,this.m,this.s,this.f,this.field),this.print=()=>{const i=":";let a=("0"+this.h).slice(-2)+i+("0"+this.m).slice(-2)+i+("0"+this.s).slice(-2)+i+("0"+this.f).slice(-2);return a+="."+(this.field?"1":"2"),a},this.toZipTimeCodeString=()=>{const i=this.copy();return i.f=0,i.s=i.s%2===0?i.s:i.s-1,i.field=0,C.toStr(i)},this.toFrames=i=>{let a=60,c=0;Math.floor(i)==60?(a=60,c=0):Math.floor(i)==59?(a=60,c=4):Math.floor(i)==30?(a=30,c=0):Math.floor(i)==29&&(a=30,c=2);let l=this.h,u=this.m,d=this.s,f=this.f,h=this.field;const g=l*60+u,p=(g-Math.floor(g/10))*c;return l*(a*3600)+u*(a*60)+d*a+(f*2+h)-p},this.addSeconds=i=>{let a=this.copy();if(a.s+=i,a.s>=60){const c=Math.floor(a.s/60);if(a.s=a.s%60,a.m+=c,a.m>=60){const l=Math.floor(a.m/60);a.m=a.m%60,a.h+=l}}return a},this.addFrames=(i,a)=>{let c=this.toFrames(a);return c+=i,C.fromFrames(c,a)},this.subtractFrames=(i,a)=>this.addFrames(-i,a),this.h=t||0,this.m=n||0,this.s=r||0,this.f=o||0,this.field=s||0}static compare(t,n){return t.h!==n.h?t.h<n.h?-1:1:t.m!==n.m?t.m<n.m?-1:1:t.s!==n.s?t.s<n.s?-1:1:t.f!==n.f?t.f<n.f?-1:1:t.field!==n.field?t.field<n.field?-1:1:0}static generateTimecodeRange(t,n,r){const o=[];let s=t;for(;C.compare(s,n)<=0;)o.push(s),s=s.addSeconds(r);return o}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(t){return this.toFrames(t)*1e3/t}};C.calculateCurrentTimeCode=t=>{var d;if(!t.video||!t.clocker||!t.gameParams)throw new Error("OTTPlayer is not initialized");const n=t.video,r=t.clocker,o=r.videoFPScalculator.getFPS(),a=(n.currentTime-r.syncPoint.playerTime)%(60*60*24)*o+r.syncPoint.frame;if(a===0||o===0)throw new Error("Current frame is 0 or fps is 0");const c=C.calculateCurrentOffset(a,(d=t.gameParams)==null?void 0:d.offsets);if(c===void 0)throw new Error("Offset is undefined");let l=Math.floor(a-c);return l<0&&(l+=5178816),l>=5178816&&(l-=5178816),C.fromFrames(l,o)},C.calculateCurrentOffset=(t,n)=>{for(let r=1;r<n.length;r++)if(t<n[r].frame)return n[r-1].offset;return Math.abs(n[n.length-1].offset)},C.fromFrames=(t,n)=>{let r=60,o=0;Math.floor(n)==60?(r=60,o=0):Math.floor(n)==59?(r=60,o=4):Math.floor(n)==30?(r=30,o=0):Math.floor(n)==29&&(r=30,o=2);let s=Math.floor(n*60),i=Math.floor(n*60*10),a=i*6,c=t,l=Math.floor(c/a);c-=l*a;let u=Math.floor(c/i);c-=u*i,c>=r*60&&(c+=o*(Math.floor((c-r*60)/s)+1));let d=Math.floor(c/(r*60));c-=d*(r*60);let f=Math.floor(c/r);c-=f*r;let h=c;d+=u*10;let g=0;return g=h%2,h=Math.floor(h/2),new C(l,d,f,h,g)},C.toStr=t=>{const n="_";let r=("0"+t.h).slice(-2)+n+("0"+t.m).slice(-2)+n+("0"+t.s).slice(-2)+n+("0"+t.f).slice(-2);return t.field&&(r+="_1"),r},C.fromStr=t=>{const r=t.split("_").map(Number);if(r.length==4){const[o,s,i,a]=r;return new C(o,s,i,a,0)}else if(r.length==5){const[o,s,i,a,c]=r;return new C(o,s,i,a,c)}else throw new Error("Invalid timecode format: "+t)},C.fromMetadata=t=>{const n=/^(\\d{2}):(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d))?$/,r=t.timecode.match(n);if(!r)throw new Error("Invalid timecode format: "+t.timecode);const[,o,s,i,a,c]=r,l=Number(o),u=Number(s),d=Number(i),f=Number(a),h=c?Number(c):0;return new C(l,u,d,f,h)};let ee=C;const m=class m{constructor(t){this.listenerMap=new Map,m.options=t,this.isLoggingOn=t.LOG_TO_DATADOG,this.eventTarget=new EventTarget,this.isLoggingOn&&ce.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!1,sessionSampleRate:100});const n="bb_logger_mac_uuid";let r=localStorage.getItem(n);r||(r=crypto.randomUUID(),localStorage.setItem(n,r)),m.tracking.mac=r,m.tracking.dev=`${t.platform}_${t.browserName}`,m.beatHandle||(m.options&&A(m.options,"Logger")&&console.log("[Logger] Starting tracking beat"),m.beatHandle=window.setInterval(m.flushTracking,15e3))}static setMessagePort(t){this.messagePort=t}static getMessagePort(){return this.messagePort}setLoggingOn(t){this.isLoggingOn=t}addEventListener(t,n){const r=o=>n(o);this.listenerMap.set(n,{eventName:t,wrappedListener:r}),this.eventTarget.addEventListener(t,r)}removeEventListener(t,n){const r=this.listenerMap.get(n);r&&r.eventName===t&&(this.eventTarget.removeEventListener(t,r.wrappedListener),this.listenerMap.delete(n))}removeAllEventListeners(){for(const[t,{eventName:n,wrappedListener:r}]of this.listenerMap)this.eventTarget.removeEventListener(n,r);this.listenerMap.clear()}setAttributes(t){m.processAttributes(t);for(const n in t)ce.logger.setContextProperty(n,t[n])}info(t,n){t==="didClickAd"&&this.emit("mediaSessionDidRegisterClick",{url:(n==null?void 0:n.url)||""}),t==="didToggleGlobalAugmentationDrawing"&&this.emit("mediaSessionDidUpdateGlobalAugmentationState",{isGlobalAugmentationEnabled:(n==null?void 0:n.isEnabled)||!0}),t==="didStartDrawingAugmentationMedia"&&this.emit("mediaSessionDidBeginShotRendering",n),t==="didEndDrawingAugmentationMedia"&&this.emit("mediaSessionDidEndShotRendering",n),t==="didRegisterShot"&&this.emit("mediaSessionDidRegisterShot",n),n&&m.processAttributes(n),this.isLoggingOn&&(ce.logger.info(t,n),m.options&&A(m.options,"Logger")&&console.log("[Logger] Sending info: ",t))}error(t,n){n&&m.processAttributes(n),this.isLoggingOn&&(ce.logger.error(t,n),m.tracking.err_time=Date.now().toFixed(0),m.tracking.err_desc=t+(n?` - ${JSON.stringify(n)}`:""),m.options&&A(m.options,"Logger")&&console.log("[Logger] Sending error: ",t))}warn(t,n){n&&m.processAttributes(n),this.isLoggingOn&&(ce.logger.warn(t,n),m.options&&A(m.options,"Logger")&&console.log("[Logger] Sending warn: ",t))}handleMessageFromWorker(t){t.actionType==="INFO"?this.info(t.message,t.attributes):t.actionType==="ERROR"?this.error(t.message,t.attributes):t.actionType==="WARN"?this.warn(t.message,t.attributes):t.actionType==="SET_ATTRIBUTES"&&t.attributes&&this.setAttributes(t.attributes)}static setAttributes(t){if(!m.messagePort){console.error("[Logger] messagePort is not set! Cannot send attributes.");return}try{m.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:t})}catch(n){console.error("[Logger] Error posting message:",n)}}static info(t,n){m.messagePort.postMessage({type:"LOG",actionType:"INFO",message:t,attributes:n})}static error(t,n){m.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:t,attributes:n})}static warn(t,n){m.messagePort.postMessage({type:"LOG",actionType:"WARN",message:t,attributes:n})}static processAttributes(t){if(t.player_version&&(m.tracking.sdk=t.player_version),t.media_id&&(m.tracking.gid=t.media_id),t.game_id&&(m.tracking.buc=t.game_id),t.bb_session_id&&(m.tracking.sid=t.bb_session_id,m.options&&A(m.options,"Logger")&&console.log("[Logger] Setting bb_session_id:",m.tracking.sid)),t.last_timecode){const r=ee.fromStr(t.last_timecode);m.tracking.tc=r.print(),m.lastTimecodeMillis=r.totalMilliseconds(59.94),m.lastTimecodeMillis&&m.lastZipMillis&&(m.tracking.cache=(m.lastZipMillis-m.lastTimecodeMillis).toFixed(0))}t.last_offset&&(m.tracking.off=t.last_offset),t.last_loading_zip&&(m.tracking.zip=t.last_loading_zip+".zip",m.lastZipMillis=ee.fromStr(t.last_loading_zip).totalMilliseconds(59.94),m.lastTimecodeMillis&&m.lastZipMillis&&(m.tracking.cache=(m.lastZipMillis-m.lastTimecodeMillis).toFixed(0))),t.last_rendered_frame&&(m.tracking.aug_time=Date.now().toFixed(0)),t.asset&&(m.tracking.asset=t.asset)}static objectToQuery(t){return Object.entries(t).filter(([n,r])=>r!==0&&r!=="").map(([n,r])=>`${encodeURIComponent(n)}=${encodeURIComponent(String(r))}`).join("&")}emit(t,n){const r=new CustomEvent(t,{detail:n});this.eventTarget.dispatchEvent(r)}};m.tracking={start:Date.now().toFixed(0),dev:"",sdk:"",mac:"",gid:"",sid:"",off:"",zip:"",aug_time:"",err_time:"",err_desc:"",tc:"",asset:"",cache:"",buc:""},m.lastTimecodeMillis=0,m.lastZipMillis=0,m.flushTracking=()=>{const t=Date.now().toFixed(0);m.tracking.now=t;const r=`https://dwu3k7rrxk5s3.cloudfront.net/metrics/1.gif?${m.objectToQuery(m.tracking)}`;m.options&&A(m.options,"Logger")&&console.log("[Logger] Flushing tracking data:",r),fetch(r,{method:"GET",mode:"no-cors",keepalive:!0,headers:{"X-Platform":"Web"}}).catch(()=>{}),m.tracking.err_desc="",m.tracking.err_time=""};let ue=m;const Fn=(()=>{const e=()=>{const p=navigator.userAgent;return/windows/i.test(p)?"Windows":/android/i.test(p)?"Android":/iphone|ipad|ipod/i.test(p)?"iOS":/mac/i.test(p)?"Mac":/ipad/i.test(p)?"iPad":"Something else"},t=()=>e()==="Mac",n=()=>e()==="iPad",r=()=>e()==="iOS",o=()=>{const p=e();return p==="iOS"||p==="Mac"||p==="iPad"},s=()=>e()==="Windows",i=()=>e()==="Android",a=()=>{switch(e()){case"Windows":return"a Windows PC";case"Android":return"an Android phone";case"iOS":return"an iPhone";case"Mac":return"a Mac";case"iPad":return"an iPad";default:return"an Unknown device"}},c=()=>({header:[navigator.platform,navigator.userAgent,navigator.appVersion,navigator.vendor,window.opera],dataos:[{name:"Windows Phone",value:"Windows Phone",version:"OS"},{name:"Windows",value:"Win",version:"NT"},{name:"iPhone",value:"iPhone",version:"OS"},{name:"iPad",value:"iPad",version:"OS"},{name:"Kindle",value:"Silk",version:"Silk"},{name:"Android",value:"Android",version:"Android"},{name:"PlayBook",value:"PlayBook",version:"OS"},{name:"BlackBerry",value:"BlackBerry",version:"/"},{name:"Macintosh",value:"Mac",version:"OS X"},{name:"Linux",value:"Linux",version:"rv"},{name:"Palm",value:"Palm",version:"PalmOS"}],databrowser:[{name:"Chrome",value:"Chrome",version:"Chrome"},{name:"Firefox",value:"Firefox",version:"Firefox"},{name:"Safari",value:"Safari",version:"Version"},{name:"Internet Explorer",value:"MSIE",version:"MSIE"},{name:"Opera",value:"Opera",version:"Opera"},{name:"BlackBerry",value:"CLDC",version:"CLDC"},{name:"Mozilla",value:"Mozilla",version:"Mozilla"}],init(){const R=this.header.join(" ");return this.matchItem(R,this.dataos)},matchItem(R,F){for(let le=0;le<F.length;le+=1)if(new RegExp(F[le].value,"i").test(R))return F[le].name;return"unknown"}}).init(),l=()=>{const p=navigator.userAgent;return p.indexOf("Chrome")>-1&&p.indexOf("Edge")===-1?"Chrome":p.indexOf("Safari")>-1&&p.indexOf("Chrome")===-1?"Safari":p.indexOf("Firefox")>-1?"Firefox":p.indexOf("MSIE")>-1||p.indexOf("Trident")>-1?"Internet Explorer":p.indexOf("Edge")>-1?"Edge":"Unknown"};return{getCurrentPlatform:e,isMac:t,isiPad:n,isiPhone:r,isApple:o,isWindows:s,isAndroid:i,getDeviceDescription:a,getDeviceName:c,getBrowserName:l,isSafariMac:()=>t()&&l()==="Safari",isChromeMac:()=>t()&&l()==="Chrome",isChromeWin:()=>s()&&l()==="Chrome",isFirefoxMac:()=>t()&&l()==="Firefox",isFirefoxWin:()=>s()&&l()==="Firefox"}})(),Rt={lastRendererFrameSent:0,isRAFSeen:!1,isRVFCSeen:!1,RVFCmissed:!1,RVFCframeExpected:0,compensationMode:!1,compensationCounter:0,frameCorrection:0,lastMessageSent:""};let Xe=null,L,T;self.onmessage=async e=>{const{data:t}=e;t.type==="SET_LOGGER_PORT"&&ue.setMessagePort(t.port),t.type==="SET_RENDERER_PORT"&&(Xe=t.port,Xe.onmessage=Ni),t.type==="ADAPTER_UPDATE_DATA"&&(T=t.data,$n()),t.type==="SET_OPTIONS"&&(L=t.options,ue.setMessagePort(self))};function Ni(e){L&&A(L,"Adapter")&&console.log("[AdapterWorker] Message from Renderer:",e.data)}const $n=()=>{!T||T.siData.isVideoPaused||(Fn.isChromeMac()?Fi():Fn.isSafariMac()&&$i())},Fi=()=>{if(!T||T.siData.isVideoPaused||!T.vfcData.lastFrameMetadata)return;const{siData:e,vfcData:t,afData:n,debugControls:r}=T;if(!e.isRAFSeen){let o=4,s=-11,i=1,a=5;if(r){const p=parseInt(r["Window Start (ms)"],10);isNaN(p)||(o=p);const O=parseInt(r["Window End (ms)"],10);isNaN(O)||(s=O);const R=parseInt(r["Frame Correction"],10);isNaN(R)||(i=R);const F=parseInt(r["Timeout time"],10);isNaN(F)||(a=F)}const c=1e3/t.videoFPS;1e3/n.animationFPS;const l=n.lastTimestamp,u=t.storedMetadata.reduce((p,O)=>Math.abs(O.expectedDisplayTime-l)<Math.abs(p.expectedDisplayTime-l)?O:p),d=u.expectedDisplayTime-o,f=[];for(let p=-10;p<10;p++)f.push(d+p*c);const h=u.expectedDisplayTime-s,g=[];for(let p=-10;p<10;p++)g.push(h+p*c);let E=null;f.forEach((p,O)=>{l>p&&l<g[O]&&(E=O-10)}),E!==null?setTimeout(p=>xt(t.lastCalculatedMediaTimeVideoFrame+p*Math.round(60/t.videoFPS)+i),a,E):xt(Rt.lastRendererFrameSent)}},$i=()=>{if(!T||T.siData.isVideoPaused||!T.vfcData.lastFrameMetadata)return;const{siData:e,vfcData:t,afData:n}=T;let r=n.lastCalculatedPlayerTimeFraction;const o=n.previousCalculatedPlayerTimeFraction;r<.3&&r>.1&&o<.3&&o>.1&&(r=Math.min(r,o));let s=0;r<.1?s=0:r>.1&&r<.3?s=(r-.1)/(.3-.1):s=1;let i=n.lastCalculatedPlayerTimeVideoFrame;s==1&&(i++,s=0),xt(i,s)},xt=(e,t)=>{if(!T)return;Rt.lastRendererFrameSent=e,T.siData.workingFps;const n=ee.fromFrames(e,6e4/1001),r=T.vfcData.videoFPS;if(r<=10||r>70){console.error("Video FPS is out of supported range: "+r),Bi(n);return}T.afData.animationFPS,Ui(n,t)},Ui=(e,t)=>{const n=ee.toStr(e);Rt.lastMessageSent=n,L&&A(L,"Adapter")&&console.log(`[AdapterWorker] Rendering augmentation for timecode: ${n} , ${e}`),Un(n,t)},Bi=e=>{const t=ee.toStr(e);L&&A(L,"Adapter")&&console.log("[AdapterWorker] Clearing augmentation"),Un(t,0,!0)},Un=(e,t,n)=>{if(!Xe||!T)return;const r=e;L&&A(L,"Adapter")&&console.log(`[AdapterWorker] Sending current time code to the Renderer: ${r}`);const o={timeCode:r,frameCorrection:t||0,fps:jn(T.siData.workingFps),zipBaseURL:T.zipBaseURL,adsBaseURL:T.adsBaseURL,bucketName:T.bucketName,customerId:T.customerId,offsets:T.offsets},i={type:n?"RENDERER_CLEAR":"RENDERER_DRAW",streamData:o};Xe.postMessage(i)};self.onunhandledrejection=e=>{ue.error("[AdapterWorker] Unhandled rejection",{error:e.reason}),L&&(A(L,"Errors")&&console.error("[AdapterWorker] Unhandled rejection:",e.reason),e.preventDefault())},self.onerror=e=>{ue.error("[AdapterWorker] Unhandled error",{error:e}),L&&(A(L,"Errors")&&console.error("[AdapterWorker] Unhandled error:",e),e instanceof Event&&e.preventDefault())},setInterval($n,2)})();\n',Wt=typeof self<"u"&&self.Blob&&new Blob([Ht],{type:"text/javascript;charset=utf-8"});function ln(t){let e;try{if(e=Wt&&(self.URL||self.webkitURL).createObjectURL(Wt),!e)throw"";const r=new Worker(e,{name:t==null?void 0:t.name});return r.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),r}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Ht),{name:t==null?void 0:t.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}class jt{constructor(){this.metrics=new Map,this.containers=[],this.createContainer=()=>{const e=document.createElement("div");e.style.display="flex",e.style.gap="30px",e.style.marginTop="2px",e.style.marginBottom="2px",e.style.fontSize="12px",e.style.fontFamily="monospace";const r={div:e,metrics:[]};return this.containers.push(r),document.body.appendChild(e),r},this.createMetric=(e,r)=>{const n=document.createElement("span");n.style.display="inline-flex",n.style.gap="4px",n.style.whiteSpace="nowrap",n.style.flexShrink="0";const s=document.createElement("span");s.textContent=`${e}:`,s.style.flexShrink="0",s.style.fontWeight="bold";const i=document.createElement("span");i.style.minWidth="0",i.style.textAlign="right",i.style.whiteSpace="nowrap",i.style.flexShrink="0",i.style.display="inline-block",i.textContent="",n.appendChild(s),n.appendChild(i);const o={name:e,value:"",span:n,valueSpan:i,maxWidth:0};return r.metrics.push(o),r.div.appendChild(n),this.metrics.set(e,o),o},this.updateMetric=(e,r)=>{const n=this.metrics.get(e);if(!n){console.error("Metric does not exist");return}typeof r=="boolean"?n.value=r?"true":"false":n.value=r,n.valueSpan.textContent=String(n.value);const s=n.valueSpan.offsetWidth;s>n.maxWidth&&(n.maxWidth=s,n.valueSpan.style.minWidth=`${s}px`)}}delete(){this.containers.forEach(e=>{e.div.remove()})}}class dn{constructor(e){if(this.canPlayListner=()=>this.setupCanvas(),this.clickListner=n=>{this.clicker.click(n)},this.mediaTime=0,this.timecodeChecker=new nn(0),this.rendererReady=!1,this.pendingAdBitmaps=[],this.lastAdBlobPerPlaceholder=new Map,this.logger=e.logger,this.OTTPlayer=e,this.options=e.options,this.debug=this.options.debug?this.options.debug.on:!1,this.options.debug&&this.debug){this.metrics=new jt;const n=this.metrics.createContainer();if(this.metrics.createMetric("Last Downloaded Zip",n),this.metrics.createMetric("Last Decoded Frame",n),this.metrics.createMetric("Last WebGL Uploaded Frame",n),this.metrics.createMetric("Last Rendered Frame",n),this.metrics.createMetric("Renderer State",n),this.options.debug.trackPerformance){const s=this.metrics.createContainer();this.metrics.createMetric("Rendering GPU time",s),this.metrics.createMetric("Rendering CPU time",s),this.metrics.createMetric("Chunking time",s),this.metrics.createMetric("Decoding time",s)}}this.downloaderWorker=new on,this.decoderWorker=new an,this.rendererWorker=new cn;const r=[this.downloaderWorker,this.decoderWorker,this.rendererWorker];this.options.ADAPTER_RUN_IN_WORKER&&(this.adapterWorker=new ln,r.push(this.adapterWorker)),window.BB.workerInstances.push(...r),this.rendererToDownloader=new MessageChannel,this.rendererToMain=new MessageChannel,this.downloaderToDecoder=new MessageChannel,this.decoderToRenderer=new MessageChannel,this.options.ADAPTER_RUN_IN_WORKER&&(this.adapterToRenderer=new MessageChannel),this.setupWorkers(),this.canvas=document.createElement("canvas"),this.OTTPlayer.video.readyState>=3?this.setupCanvas():this.OTTPlayer.video.addEventListener("canplay",this.canPlayListner,{once:!0}),this.processedTimecodes=[],this.clicker=new sn(this.OTTPlayer,this.rendererWorker),this.segmentFirstFrameTimecode=new L,this.syncPoint={frame:0,playerTime:0,stringTime:""},this.cacheStarted=!1,this.animationFPScalculator=new nt(20),this.videoFPScalculator=new nt(20),this.startAnimationFrameLoop(),this.startVideoFrameCallbackLoop()}startAnimationFrameLoop(){const e=()=>{this.animationFPScalculator.addTimestamp(performance.now()/1e3),this.OTTPlayer.RUN_PIXEL_TICKERS&&this.OTTPlayer.pixelTickers.forEach(r=>{r.update()}),this.animationFrameLoopId=requestAnimationFrame(e)};this.animationFrameLoopId=requestAnimationFrame(e)}startVideoFrameCallbackLoop(){const e=(r,n)=>{this.mediaTime=n.mediaTime,this.videoFPScalculator.addTimestamp(n.mediaTime),this.videoFrameCallbackLoopId=this.OTTPlayer.video.requestVideoFrameCallback(e)};this.videoFrameCallbackLoopId=this.OTTPlayer.video.requestVideoFrameCallback(e)}updateCanvasSize(){if(!this.canvasContainer)return;const e=this.canvasContainer,r=e.style.width,n=e.style.height;if(r&&n){this.canvas.style.width=r,this.canvas.style.height=n,this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=void 0);return}const s=window.getComputedStyle(e);this.canvas.style.width=s.width,this.canvas.style.height=s.height,!this.resizeObserver&&typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>{const i=window.getComputedStyle(e);this.canvas.style.width=i.width,this.canvas.style.height=i.height}),this.resizeObserver.observe(e))}setupCanvas(){const e=this.OTTPlayer.video,r=this.options.CANVAS_CONTAINER||e.parentElement;if(!r){console.error("[Clocker] No container found for canvas placement"),this.logger.error("setupCanvas failed: no container found");return}this.canvasContainer=r,console.log("video.videoWidth: ",e.videoWidth),console.log("video.videoHeight: ",e.videoHeight),this.canvas.width=e.videoWidth,this.canvas.height=e.videoHeight,this.canvas.style.zIndex="3000",this.canvas.style.position="absolute",this.canvas.style.top="0%",this.canvas.style.left="0",console.log("container: ",r),console.log("[OTTPlayer] container sizes:"),console.log("container.style.width: ",r.style.width),console.log("container.style.height: ",r.style.height),this.updateCanvasSize(),this.canvas.style.pointerEvents="none",r.addEventListener("click",this.clickListner),r.style.position="relative",r.appendChild(this.canvas);const n=this.canvas.transferControlToOffscreen(),{CANVAS_CONTAINER:s,...i}=this.options,o={type:"INIT_OFFSCREEN",offscreen:n,options:i};this.rendererWorker.postMessage(o,[n]),e.onseeked=()=>{this.onVideoSeeked()},e.onseeking=()=>{this.onVideoSeeked()}}setupWorkers(){const{CANVAS_CONTAINER:e,...r}=this.options;this.downloaderWorker.onmessage=n=>{n.data.type==="LOG"?(n.data.actionType==="SET_ATTRIBUTES"&&n.data.attributes.last_loading_zip&&this.metrics&&this.metrics.updateMetric("Last Downloaded Zip",n.data.attributes.last_loading_zip),this.logger.handleMessageFromWorker(n.data)):n.data.type==="TRACK_PERFORMANCE"&&this.trackPerformance(n.data)},this.decoderWorker.onmessage=n=>{if(n.data.type==="LOG"){if(n.data.actionType==="SET_ATTRIBUTES"&&(n.data.attributes.last_decoded_frame&&this.metrics&&this.metrics.updateMetric("Last Decoded Frame",n.data.attributes.last_decoded_frame),this.OTTPlayer.statusOverlay)){const s=n.data.attributes;s.decoder_status&&this.OTTPlayer.statusOverlay.updateMetric("health","decoder",s.decoder_status.healthy,s.decoder_status.issue),s.timecode_status&&this.OTTPlayer.statusOverlay.updateMetric("timecode","consistency",s.timecode_status.consistent,s.timecode_status.errorCount>0?`Errors: ${s.timecode_status.errorCount}`:void 0)}this.logger.handleMessageFromWorker(n.data)}else n.data.type==="TRACK_PERFORMANCE"&&this.trackPerformance(n.data)},this.rendererWorker.onmessage=n=>{n.data.type==="LOG"?(n.data.actionType==="SET_ATTRIBUTES"&&this.metrics&&(n.data.attributes.last_webgl_uploaded_frame&&this.metrics.updateMetric("Last WebGL Uploaded Frame",n.data.attributes.last_webgl_uploaded_frame),n.data.attributes.last_rendered_frame&&this.metrics.updateMetric("Last Rendered Frame",n.data.attributes.last_rendered_frame),n.data.attributes.renderer_state&&this.metrics.updateMetric("Renderer State",n.data.attributes.renderer_state)),this.logger.handleMessageFromWorker(n.data)):n.data.type==="TRACK_PERFORMANCE"?this.trackPerformance(n.data):n.data.type==="RENDERER_READY"&&(this.rendererReady=!0,this.flushOverrides(!0))},this.adapterWorker&&(this.adapterWorker.onmessage=n=>{n.data.type==="LOG"?this.logger.handleMessageFromWorker(n.data):n.data.type==="TRACK_PERFORMANCE"&&this.trackPerformance(n.data)}),this.rendererWorker.postMessage({type:"SET_DOWNLOADER_PORT",port:this.rendererToDownloader.port1},[this.rendererToDownloader.port1]),this.downloaderWorker.postMessage({type:"SET_RENDERER_PORT",port:this.rendererToDownloader.port2},[this.rendererToDownloader.port2]),this.downloaderWorker.postMessage({type:"SET_DECODER_PORT",port:this.downloaderToDecoder.port1},[this.downloaderToDecoder.port1]),this.decoderWorker.postMessage({type:"SET_DOWNLOADER_PORT",port:this.downloaderToDecoder.port2},[this.downloaderToDecoder.port2]),this.decoderWorker.postMessage({type:"SET_RENDERER_PORT",port:this.decoderToRenderer.port1},[this.decoderToRenderer.port1]),this.rendererWorker.postMessage({type:"SET_DECODER_PORT",port:this.decoderToRenderer.port2},[this.decoderToRenderer.port2]),this.adapterWorker&&this.adapterToRenderer&&(this.adapterWorker.postMessage({type:"SET_RENDERER_PORT",port:this.adapterToRenderer.port1},[this.adapterToRenderer.port1]),this.rendererWorker.postMessage({type:"SET_ADAPTER_PORT",port:this.adapterToRenderer.port2},[this.adapterToRenderer.port2])),this.rendererWorker.postMessage({type:"SET_LOGGER_PORT",port:this.rendererToMain.port1},[this.rendererToMain.port1]),this.rendererToMain.port2.onmessage=n=>{var s,i;if(n.data.type==="LOG"){if(n.data.actionType==="SET_ATTRIBUTES"&&(this.metrics&&(n.data.attributes.last_webgl_uploaded_frame&&this.metrics.updateMetric("Last WebGL Uploaded Frame",n.data.attributes.last_webgl_uploaded_frame),n.data.attributes.last_rendered_frame&&this.metrics.updateMetric("Last Rendered Frame",n.data.attributes.last_rendered_frame),n.data.attributes.renderer_state&&this.metrics.updateMetric("Renderer State",n.data.attributes.renderer_state)),this.OTTPlayer.statusOverlay)){const o=n.data.attributes;if(o.webgl_status&&this.OTTPlayer.statusOverlay.updateMetric("health","webgl",o.webgl_status.ready,o.webgl_status.issue),o.renderer_state&&this.OTTPlayer.statusOverlay.updateMetric("switches","render_state",o.renderer_state),o.data_status){const a=o.data_status;this.OTTPlayer.statusOverlay.updateMetric("data","stream_data",a.stream_data,a.timecode||void 0),this.OTTPlayer.statusOverlay.updateMetric("data","ads",a.ads),this.OTTPlayer.statusOverlay.updateMetric("data","render_data",a.render_data),this.OTTPlayer.statusOverlay.updateMetric("data","alpha_mask",a.alpha_mask),this.OTTPlayer.statusOverlay.updateMetric("data","placeholders",a.placeholders),this.OTTPlayer.statusOverlay.updateMetric("data","processing_size",a.processing_size),this.OTTPlayer.statusOverlay.updateMetric("switches","isLive",a.isLive)}if(o.killswitch_status){const a=o.killswitch_status;this.OTTPlayer.statusOverlay.updateMetric("switches","killswitch_web",a.web),this.OTTPlayer.statusOverlay.updateMetric("switches","killswitch_local",a.local)}if(o.zip_buffer_status){const a=o.zip_buffer_status,c=((s=a.retryingTimecodes)==null?void 0:s.length)||0,d=((i=a.failedTimecodes)==null?void 0:i.length)||0;let l=`${a.continuousSeconds.toFixed(1)}s`;(c>0||d>0)&&(l+=` | Retrying: ${c}, Failed: ${d}`),this.OTTPlayer.statusOverlay.updateMetric("data","zip_buffer",!a.needsFadeout,l)}}this.logger.handleMessageFromWorker(n.data)}else n.data.type==="TRACK_PERFORMANCE"&&this.trackPerformance(n.data)},this.downloaderWorker.postMessage({type:"SET_OPTIONS",options:r}),this.decoderWorker.postMessage({type:"SET_OPTIONS",options:r}),this.adapterWorker&&this.adapterWorker.postMessage({type:"SET_OPTIONS",options:r}),this.rendererWorker.postMessage({type:"SET_OPTIONS",options:r})}callAdapterWorker(e){this.adapterWorker&&this.adapterWorker.postMessage({type:"ADAPTER_UPDATE_DATA",data:e})}callRendererWorkerWithFrame(e,r){if(!this.OTTPlayer.gameParams||!this.OTTPlayer.gameParams.bucketName){e.close();return}const n={timeCode:r,frameCorrection:0,fps:ie(this.videoFPScalculator.getFPS()),zipBaseURL:this.OTTPlayer.options.zipBaseURL,adsBaseURL:this.OTTPlayer.options.adsBaseURL,bucketName:this.OTTPlayer.gameParams.bucketName,offsets:this.OTTPlayer.gameParams.offsets,customerId:this.OTTPlayer.gameParams.customerId,ottActions:this.OTTPlayer.ottActions},s={type:"BURNED_FRAME_RENDER",imageBitmap:e,timecode:r,streamData:n};this.rendererWorker.postMessage(s,[e]),this.logger.setAttributes({last_timecode:r})}setAdImage(e,r){if(!this.rendererReady){this.pendingAdBitmaps.push({imageBitmap:e,placeholder:r});return}const n={type:"SET_AD_IMAGE",imageBitmap:e,placeholder:r};this.rendererWorker.postMessage(n,[e])}setLEDImage(e){if(!this.rendererReady){if(this.pendingLEDBitmap)try{this.pendingLEDBitmap.close()}catch{}this.pendingLEDBitmap=e;return}const r={type:"SET_LED_IMAGE",imageBitmap:e};this.rendererWorker.postMessage(r,[e])}setAdBlob(e,r){r?this.lastAdBlobPerPlaceholder.set(r,e):this.lastGlobalAdBlob=e;const n={type:"SET_AD_BLOB",blob:e,placeholder:r};this.rendererWorker.postMessage(n)}setLEDBlob(e){this.lastLEDBlob=e;const r={type:"SET_LED_BLOB",blob:e};this.rendererWorker.postMessage(r)}callRendererWorker(e,r,n){var a,c;this.options&&_(this.options,"Clocker")&&console.log(`[Clocker] Sending current time code to the Renderer: ${e}`);const s=n?"RENDERER_CLEAR":"RENDERER_DRAW";if(!e||!this.OTTPlayer.gameParams||!this.OTTPlayer.gameParams.bucketName||!this.OTTPlayer.gameParams.offsets){const d={type:s};this.rendererWorker.postMessage(d);return}const i={timeCode:e,frameCorrection:r||0,fps:ie(this.videoFPScalculator.getFPS()),zipBaseURL:this.OTTPlayer.options.zipBaseURL,adsBaseURL:this.OTTPlayer.options.adsBaseURL,bucketName:this.OTTPlayer.gameParams.bucketName,offsets:this.OTTPlayer.gameParams.offsets,customerId:this.OTTPlayer.gameParams.customerId,ottActions:this.OTTPlayer.ottActions?{...this.OTTPlayer.ottActions,benchmarkPassed:((c=(a=this.OTTPlayer.adapter)==null?void 0:a.benchmark)==null?void 0:c.hasPassed())??!1}:void 0},o={type:s,streamData:i};this.rendererWorker.postMessage(o),n||this.logger.setAttributes({last_timecode:e})}onVideoSeeked(){this.restartWorkers(),this.OTTPlayer.adapter&&this.OTTPlayer.adapter.onVideoSeeked(),this.logger.info("didSeek")}stopWorkers(){const e={type:"STOP_WORKER"};this.downloaderWorker.postMessage(e),this.decoderWorker.postMessage(e),this.rendererWorker.postMessage(e)}restartWorkers(){this.rendererReady=!1;const e={type:"RESTART_WORKER"};this.downloaderWorker.postMessage(e),this.decoderWorker.postMessage(e),this.rendererWorker.postMessage(e)}pause(){this.stopWorkers(),this.animationFrameLoopId&&(cancelAnimationFrame(this.animationFrameLoopId),this.animationFrameLoopId=void 0),this.videoFrameCallbackLoopId&&(this.OTTPlayer.video.cancelVideoFrameCallback(this.videoFrameCallbackLoopId),this.videoFrameCallbackLoopId=void 0)}resume(){this.restartWorkers(),this.animationFrameLoopId||this.startAnimationFrameLoop(),this.videoFrameCallbackLoopId||this.startVideoFrameCallbackLoop()}trackPerformance(e){var r;if((r=this.options.debug)!=null&&r.trackPerformance&&this.metrics)for(let n of e.data)this.metrics.updateMetric(n.metric,n.value.toFixed(2))}flushOverrides(e=!1){if(e){if(this.lastGlobalAdBlob){const r={type:"SET_AD_BLOB",blob:this.lastGlobalAdBlob};this.rendererWorker.postMessage(r)}this.lastAdBlobPerPlaceholder.size>0&&this.lastAdBlobPerPlaceholder.forEach((r,n)=>{const s={type:"SET_AD_BLOB",blob:r,placeholder:n};this.rendererWorker.postMessage(s)})}if(this.pendingAdBitmaps.length>0){for(const r of this.pendingAdBitmaps){const n={type:"SET_AD_IMAGE",imageBitmap:r.imageBitmap,placeholder:r.placeholder};this.rendererWorker.postMessage(n,[r.imageBitmap])}this.pendingAdBitmaps=[]}if(this.pendingLEDBitmap){const r=this.pendingLEDBitmap;this.pendingLEDBitmap=void 0;const n={type:"SET_LED_IMAGE",imageBitmap:r};this.rendererWorker.postMessage(n,[r])}else if(e&&this.lastLEDBlob){const r={type:"SET_LED_BLOB",blob:this.lastLEDBlob};this.rendererWorker.postMessage(r)}}delete(){const e=this.OTTPlayer.video,r=this.canvasContainer||e.parentElement;if(this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=void 0),r&&this.canvas&&r.contains(this.canvas)&&r.removeChild(this.canvas),this.rendererWorker.terminate(),this.downloaderWorker.terminate(),this.decoderWorker.terminate(),this.adapterWorker&&this.adapterWorker.terminate(),this.metrics&&this.metrics.delete(),this.animationFrameLoopId&&cancelAnimationFrame(this.animationFrameLoopId),this.videoFrameCallbackLoopId&&e.cancelVideoFrameCallback(this.videoFrameCallbackLoopId),e.removeEventListener("canplay",this.canPlayListner),r&&r.removeEventListener("click",this.clickListner),this.pendingAdBitmaps&&this.pendingAdBitmaps.length>0){for(const n of this.pendingAdBitmaps)try{n.imageBitmap.close()}catch{}this.pendingAdBitmaps=[]}if(this.pendingLEDBitmap){try{this.pendingLEDBitmap.close()}catch{}this.pendingLEDBitmap=void 0}}}class un{constructor(){this.controls=new Map,this.containers=[]}createContainer(e){const r=document.createElement("div");r.style.display="flex",r.style.flexWrap="wrap",r.style.gap="10px",r.style.padding="10px",r.style.marginBottom="10px",r.style.border="1px solid #ccc",r.style.fontSize="14px",r.style.backgroundColor="#f9f9f9";const n=document.createElement("button");n.textContent="Apply",n.style.cursor="pointer";const s={div:r,controls:[],button:n};return n.addEventListener("click",()=>{const i={};s.controls.forEach(o=>{o.type==="input"||o.type==="select"?o.appliedValue=o.element.value:o.type==="checkbox"&&(o.appliedValue=String(o.element.checked)),i[o.name]=o.appliedValue}),e&&e(i)}),r.appendChild(n),document.body.appendChild(r),this.containers.push(s),s}createInput(e,r="",n){const s=document.createElement("label");s.style.display="flex",s.style.flexDirection="column",s.style.fontWeight="bold";const i=document.createElement("span");i.textContent=e,i.style.marginBottom="3px";const o=document.createElement("input");o.type="text",o.value=String(r),o.style.minWidth="60px";const a={name:e,type:"input",element:o,container:n,appliedValue:String(r)};this.controls.set(e,a),n.controls.push(a),s.appendChild(i),s.appendChild(o),n.div.insertBefore(s,n.button)}createSelect(e,r,n="",s){const i=document.createElement("label");i.style.display="flex",i.style.flexDirection="column",i.style.fontWeight="bold";const o=document.createElement("span");o.textContent=e,o.style.marginBottom="3px";const a=document.createElement("select");a.style.minWidth="80px",Object.entries(r).forEach(([d,l])=>{const u=document.createElement("option");u.textContent=d,u.value=String(l),a.appendChild(u)}),a.value=String(n);const c={name:e,type:"select",element:a,container:s,appliedValue:String(n)};this.controls.set(e,c),s.controls.push(c),i.appendChild(o),i.appendChild(a),s.div.insertBefore(i,s.button)}createCheckbox(e,r=!1,n){const s=document.createElement("label");s.style.display="flex",s.style.fontWeight="bold";const i=document.createElement("span");i.textContent=e,i.style.marginRight="5px";const o=document.createElement("input");o.type="checkbox",o.checked=r;const a={name:e,type:"checkbox",element:o,container:n,appliedValue:String(r)};this.controls.set(e,a),n.controls.push(a),s.appendChild(i),s.appendChild(o),n.div.insertBefore(s,n.button)}exportData(){const e={};return this.controls.forEach(r=>{e[r.name]=r.appliedValue}),e}getValue(e){const r=this.controls.get(e);return r?r.appliedValue:(console.error(`No control found with name: ${e}`),"")}delete(){this.containers.forEach(e=>{e.div.remove()}),this.containers=[],this.controls.clear()}}const Ue=t=>t.toString().padStart(2,"0"),st=":",hn=(t,e,r=!1)=>{let n="";return Array.isArray(t)?(n=[Ue(t[0]),Ue(t[1]),Ue(t[2]),Ue(t[3])].join(":"),r==!0?t[4]==1&&e?n+=".2":n+=".1":t[4]==1&&e&&(n+=".1")):(n=("0"+t.h).slice(-2)+st+("0"+t.m).slice(-2)+st+("0"+t.s).slice(-2)+st+("0"+t.f).slice(-2),n+="."+(t.field?"1":"2")),n},fn=(t,e,r)=>{let n=60,s=0;Math.floor(e)==60?(n=60,s=0):Math.floor(e)==59?(n=60,s=4):Math.floor(e)==30?(n=30,s=0):Math.floor(e)==29&&(n=30,s=2);let i=0,a=Math.floor(e*60*10)*6,c=t[0],d=t[1],l=t[2],u=t[3],f=t[4];return i+=c*a,i+=d*(n*60),i+=l*n,i+=u*2+f,i-=s*d,i+=s*Math.floor(d/10),i},I=(()=>{const t=()=>{const g=navigator.userAgent;return/windows/i.test(g)?"Windows":/android/i.test(g)?"Android":/iphone|ipad|ipod/i.test(g)?"iOS":/mac/i.test(g)?"Mac":/ipad/i.test(g)?"iPad":"Something else"},e=()=>t()==="Mac",r=()=>t()==="iPad",n=()=>t()==="iOS",s=()=>{const g=t();return g==="iOS"||g==="Mac"||g==="iPad"},i=()=>t()==="Windows",o=()=>t()==="Android",a=()=>{switch(t()){case"Windows":return"a Windows PC";case"Android":return"an Android phone";case"iOS":return"an iPhone";case"Mac":return"a Mac";case"iPad":return"an iPad";default:return"an Unknown device"}},c=()=>({header:[navigator.platform,navigator.userAgent,navigator.appVersion,navigator.vendor,window.opera],dataos:[{name:"Windows Phone",value:"Windows Phone",version:"OS"},{name:"Windows",value:"Win",version:"NT"},{name:"iPhone",value:"iPhone",version:"OS"},{name:"iPad",value:"iPad",version:"OS"},{name:"Kindle",value:"Silk",version:"Silk"},{name:"Android",value:"Android",version:"Android"},{name:"PlayBook",value:"PlayBook",version:"OS"},{name:"BlackBerry",value:"BlackBerry",version:"/"},{name:"Macintosh",value:"Mac",version:"OS X"},{name:"Linux",value:"Linux",version:"rv"},{name:"Palm",value:"Palm",version:"PalmOS"}],databrowser:[{name:"Chrome",value:"Chrome",version:"Chrome"},{name:"Firefox",value:"Firefox",version:"Firefox"},{name:"Safari",value:"Safari",version:"Version"},{name:"Internet Explorer",value:"MSIE",version:"MSIE"},{name:"Opera",value:"Opera",version:"Opera"},{name:"BlackBerry",value:"CLDC",version:"CLDC"},{name:"Mozilla",value:"Mozilla",version:"Mozilla"}],init(){const b=this.header.join(" ");return this.matchItem(b,this.dataos)},matchItem(b,E){for(let A=0;A<E.length;A+=1)if(new RegExp(E[A].value,"i").test(b))return E[A].name;return"unknown"}}).init(),d=()=>{const g=navigator.userAgent;return g.indexOf("Chrome")>-1&&g.indexOf("Edge")===-1?"Chrome":g.indexOf("Safari")>-1&&g.indexOf("Chrome")===-1?"Safari":g.indexOf("Firefox")>-1?"Firefox":g.indexOf("MSIE")>-1||g.indexOf("Trident")>-1?"Internet Explorer":g.indexOf("Edge")>-1?"Edge":"Unknown"};return{getCurrentPlatform:t,isMac:e,isiPad:r,isiPhone:n,isApple:s,isWindows:i,isAndroid:o,getDeviceDescription:a,getDeviceName:c,getBrowserName:d,isSafariMac:()=>e()&&d()==="Safari",isChromeMac:()=>e()&&d()==="Chrome",isChromeWin:()=>i()&&d()==="Chrome",isFirefoxMac:()=>e()&&d()==="Firefox",isFirefoxWin:()=>i()&&d()==="Firefox"}})();class pn{constructor(e=10){this.testStartTime=0,this.currentState="FAILED",this.previousState="FAILED",this.testDurationMs=e*1e3,this.lastConditions=this.getEmptyConditions()}test(e){const r=Object.values(e).every(s=>s===!0);if(this.previousState=this.currentState,!r){this.currentState="FAILED",this.testStartTime=0,this.lastConditions=e;const s=this.previousState==="PASSED"||this.previousState==="TESTING";return{state:"FAILED",failedConditions:this.getFailedConditions(e),shouldClear:s}}const n=performance.now();if(this.currentState==="FAILED"&&(this.currentState="TESTING",this.testStartTime=n),this.currentState==="TESTING"){const s=n-this.testStartTime,i=this.testDurationMs-s;return i<=0?(this.currentState="PASSED",{state:"PASSED"}):{state:"TESTING",remainingSeconds:Math.ceil(i/1e3)}}return this.lastConditions=e,{state:"PASSED"}}hasPassed(){return this.currentState==="PASSED"}getStatus(){if(this.currentState==="FAILED")return{state:"FAILED",failedConditions:this.getFailedConditions(this.lastConditions)};if(this.currentState==="TESTING"){const r=performance.now()-this.testStartTime,n=this.testDurationMs-r;return{state:"TESTING",remainingSeconds:Math.ceil(n/1e3)}}return{state:"PASSED"}}reset(){this.currentState="FAILED",this.testStartTime=0}setDuration(e){this.testDurationMs=e*1e3}getFailedConditions(e){const r=[];return e.gameParams||r.push("game_params"),e.browserSupported||r.push("browser"),e.patternDetected||r.push("pattern"),e.fpsSupported||r.push("fps"),e.noMKAdsPlaying||r.push("mk_ads"),e.syncPointSet||r.push("sync_point"),r}getEmptyConditions(){return{gameParams:!1,browserSupported:!1,patternDetected:!1,fpsSupported:!1,noMKAdsPlaying:!0,syncPointSet:!1}}}class mn{constructor(){this.OUT_WIDTH=4,this.OUT_HEIGHT=1,this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl2");if(!e)throw new Error("WebGL2 not supported");this.gl=e;const r=`#version 300 es
|
|
395
|
+
}\`;function Ta(t,e,s){let r=0,n=0;for(const o of Object.values(t)){const i=o.corners,a=Math.abs(ns(i));if(!a)continue;const c=Aa(i,e,s),d=c.length>=3?Math.abs(ns(c)):0;r+=d,n+=a}return{percentOfAd:n?r/n*100:0,percentOfScreen:r/(e*s)*100}}function ns(t){let e=0;for(let s=0,r=t.length-1;s<t.length;r=s++)e+=t[r].x*t[s].y-t[s].x*t[r].y;return e*.5}function Aa(t,e,s){const r=[{inside:o=>o.x>=0,inter:(o,i)=>({x:0,y:o.y+(i.y-o.y)*(0-o.x)/(i.x-o.x)})},{inside:o=>o.x<=e,inter:(o,i)=>({x:e,y:o.y+(i.y-o.y)*(e-o.x)/(i.x-o.x)})},{inside:o=>o.y>=0,inter:(o,i)=>({x:o.x+(i.x-o.x)*(0-o.y)/(i.y-o.y),y:0})},{inside:o=>o.y<=s,inter:(o,i)=>({x:o.x+(i.x-o.x)*(s-o.y)/(i.y-o.y),y:s})}];let n=t;for(const o of r){const i=n;if(n=[],!i.length)break;let a=i[i.length-1];for(const c of i){const d=o.inside(c),l=o.inside(a);d?(l||n.push(o.inter(a,c)),n.push(c)):l&&n.push(o.inter(a,c)),a=c}}return n}class is{constructor(e,s){this.logoToRegion=new Map,this.atlasDirty=!1,this.nextX=0,this.nextY=0,this.rowH=0,this.INITIAL_ATLAS_SIZE=256,this.ATLAS_SIZE=this.INITIAL_ATLAS_SIZE,this.ATLAS_PADDING=4,this.ledOverlayW=0,this.ledOverlayH=0,this.LED_PADDING=100,this.LED_AA_STRENGTH=1,this.LOGO_AA_STRENGTH=1,this.ledArtW=0,this.ledArtH=0,this.ledCubes=[],this.queryInFlight=!1,this.GPUFrameTimeCount=0,this.GPUFrameTimeSum=0,this.avgGPUFrameTime=0,this.CPUFrameTimeCount=0,this.CPUFrameTimeSum=0,this.avgCPUFrameTime=0,this.timestampW=0,this.timestampH=0,this.compileShader=(r,n)=>{const o=this.gl,i=o.createShader(r);return o.shaderSource(i,n),o.compileShader(i),o.getShaderParameter(i,o.COMPILE_STATUS)?i:(g(this.options,"Errors")&&console.error(\`Error compiling shader: \${o.getShaderInfoLog(i)}\`),o.deleteShader(i),null)},this.createTextureFromImageBitmap=r=>{const n=this.gl,o=n.createTexture();return n.bindTexture(n.TEXTURE_2D,o),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,r),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),o},this.drawVideoFrameBase=r=>{const n=this.gl;if(!this.videoProgram||this.videoAPos===void 0||this.videoAUv===void 0||!this.uVideoTexture){g(this.options,"Errors")&&console.error("[WebGL] Video program not initialized");return}n.useProgram(this.videoProgram),n.viewport(0,0,n.canvas.width,n.canvas.height),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,r),n.uniform1i(this.uVideoTexture,0),n.bindBuffer(n.ARRAY_BUFFER,this.fsPosBuf),n.enableVertexAttribArray(this.videoAPos),n.vertexAttribPointer(this.videoAPos,2,n.FLOAT,!1,0,0),n.bindBuffer(n.ARRAY_BUFFER,this.fsUvBuf),n.enableVertexAttribArray(this.videoAUv),n.vertexAttribPointer(this.videoAUv,2,n.FLOAT,!1,0,0),n.clearColor(0,0,0,1),n.clear(n.COLOR_BUFFER_BIT),n.drawArrays(n.TRIANGLES,0,6),this.program&&n.useProgram(this.program)},this.createTextureFromVideoFrame=r=>{const n=this.gl,o=n.createTexture();return n.bindTexture(n.TEXTURE_2D,o),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,r),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.bindTexture(n.TEXTURE_2D,null),o},this.deleteTexture=r=>{this.gl.deleteTexture(r)},this.options=s,this.renderer=e,this.gl=e.glContext,this.initTiming()}init(){this.initAtlas(),this.initBuffers(),this.initPrograms(),this.options.RENDER_LED&&(this.instancedExt=this.gl.getExtension("ANGLE_instanced_arrays"),this.instancedExt||g(this.options,"Errors")&&console.error("ANGLE_instanced_arrays extension not available"))}initPrograms(){const e=this.gl;if(this.program=this.linkProgram(ua,da),this.aPos=e.getAttribLocation(this.program,"a_position"),this.aUv=e.getAttribLocation(this.program,"a_uv"),this.aTransform=e.getAttribLocation(this.program,"a_transform"),this.uRes=e.getUniformLocation(this.program,"u_resolution"),this.uCanvasRes=e.getUniformLocation(this.program,"u_canvasResolution"),this.uOpacity=e.getUniformLocation(this.program,"u_opacity"),this.uAAStrength=e.getUniformLocation(this.program,"u_aaStrength"),this.uAtlas=e.getUniformLocation(this.program,"u_atlas"),this.uAlphaMask=e.getUniformLocation(this.program,"u_alphaMask"),this.options.BURNED_TIMECODES_MODE&&(this.videoProgram=this.linkProgram(ca,la),this.videoAPos=e.getAttribLocation(this.videoProgram,"a_position"),this.videoAUv=e.getAttribLocation(this.videoProgram,"a_uv"),this.uVideoTexture=e.getUniformLocation(this.videoProgram,"u_videoTexture")),this.options.RENDER_LED){if(this.blitProgram=this.linkProgram(ma,pa),!this.blitProgram){g(this.options,"Errors")&&console.error("[WebGL] Failed to create blit program");return}this.blit_aPos=e.getAttribLocation(this.blitProgram,"aPos"),this.cubesProgram=this.linkProgram(ga,Ea),this.cubes_uEdgeFeatherPx=e.getUniformLocation(this.cubesProgram,"uEdgeFeatherPx")||void 0,this.fboCompositeProgram=this.linkProgram(qt,Kt),this.fboComposite_aPos=e.getAttribLocation(this.fboCompositeProgram,"aPos"),this.fboComposite_uFBOTex=e.getUniformLocation(this.fboCompositeProgram,"uFBOTex"),this.ledCompositeProgram=this.linkProgram(fa,ha),this.comp_aPos=e.getAttribLocation(this.ledCompositeProgram,"a_position"),this.comp_aUv=e.getAttribLocation(this.ledCompositeProgram,"a_uv"),this.comp_uOverlay=e.getUniformLocation(this.ledCompositeProgram,"u_overlay"),this.comp_uAlphaMask=e.getUniformLocation(this.ledCompositeProgram,"u_alphaMask"),this.comp_uUVRect=e.getUniformLocation(this.ledCompositeProgram,"u_uvRect"),this.comp_uRes=e.getUniformLocation(this.ledCompositeProgram,"u_resolution")}}linkProgram(e,s){const r=this.gl,n=this.compileShader(r.VERTEX_SHADER,e),o=this.compileShader(r.FRAGMENT_SHADER,s),i=r.createProgram();if(r.attachShader(i,n),r.attachShader(i,o),r.linkProgram(i),!r.getProgramParameter(i,r.LINK_STATUS)){const a=r.getProgramInfoLog(i);throw g(this.options,"Errors")&&console.error("WebGL link error: "+a),new Error("WebGL link error: "+a)}if(!r.getProgramParameter(i,r.LINK_STATUS)){const a=r.getProgramInfoLog(i);throw new Error("WebGL link error: "+a)}return i}drawAugmentation(e,s,r,n=1,o=!0,i){var p;const a=performance.now();this.syncAtlasGL();const{pos:c,uv:d,transforms:l,vertCount:f}=this.buildQuadData(s);if(!f)return;if(!this.program||this.aPos===void 0||this.aUv===void 0||this.aTransform===void 0||!this.uRes||!this.uOpacity||!this.uAtlas||!this.uAlphaMask){g(this.options,"Errors")&&console.error("[Renderer] Program or attributes not initialized");return}const u=this.gl;u.bindFramebuffer(u.FRAMEBUFFER,null),u.viewport(0,0,u.canvas.width,u.canvas.height),u.useProgram(this.program),u.uniform2f(this.uRes,r.width,r.height),this.uCanvasRes&&u.uniform2f(this.uCanvasRes,u.canvas.width,u.canvas.height),u.uniform1f(this.uOpacity,n),this.uAAStrength&&u.uniform1f(this.uAAStrength,this.LOGO_AA_STRENGTH),u.activeTexture(u.TEXTURE0),u.bindTexture(u.TEXTURE_2D,e),u.uniform1i(this.uAlphaMask,0),u.activeTexture(u.TEXTURE1),u.bindTexture(u.TEXTURE_2D,this.atlasTex),u.uniform1i(this.uAtlas,1),u.bindBuffer(u.ARRAY_BUFFER,this.posBuf),u.bufferData(u.ARRAY_BUFFER,c,u.DYNAMIC_DRAW),u.enableVertexAttribArray(this.aPos),u.vertexAttribPointer(this.aPos,2,u.FLOAT,!1,0,0),u.bindBuffer(u.ARRAY_BUFFER,this.uvBuf),u.bufferData(u.ARRAY_BUFFER,d,u.DYNAMIC_DRAW),u.enableVertexAttribArray(this.aUv),u.vertexAttribPointer(this.aUv,4,u.FLOAT,!1,0,0),u.bindBuffer(u.ARRAY_BUFFER,this.transformBuf),u.bufferData(u.ARRAY_BUFFER,l,u.DYNAMIC_DRAW);const m=9*4;for(let T=0;T<3;T++){const h=this.aTransform+T;u.enableVertexAttribArray(h),u.vertexAttribPointer(h,3,u.FLOAT,!1,m,T*3*4)}if(u.enable(u.BLEND),u.blendFunc(u.SRC_ALPHA,u.ONE_MINUS_SRC_ALPHA),o&&(u.clearColor(0,0,0,0),u.clear(u.COLOR_BUFFER_BIT)),this.beginTimer(),u.drawArrays(u.TRIANGLES,0,f),this.endTimer(),this.measureLogoVisibility(s),this.options.DRAW_TIMESTAMP_WEBGL&&i&&this.drawTimestampOnCanvas(i),(p=this.options.debug)!=null&&p.trackPerformance){const h=performance.now()-a;this.CPUFrameTimeCount++,this.CPUFrameTimeSum+=h,this.avgCPUFrameTime=this.CPUFrameTimeSum/this.CPUFrameTimeCount}}ensureTimestampTexture(e){try{const s=this.gl,r=18,n=8,o=6;if(!this.timestampCanvas||this.lastTimestampString!==e){const a=new OffscreenCanvas(1,1).getContext("2d");a.font=\`\${r}px monospace\`;const c=a.measureText(e),d=Math.ceil(c.width+n*2)|0,l=Math.ceil(r+o*2)|0;this.timestampCanvas=new OffscreenCanvas(d,l),this.timestampCtx=this.timestampCanvas.getContext("2d"),this.timestampW=d,this.timestampH=l;const f=this.timestampCtx;f.clearRect(0,0,d,l),f.fillStyle="rgba(0,0,0,0.55)",f.fillRect(0,0,d,l),f.font=\`\${r}px monospace\`,f.textBaseline="middle",f.fillStyle="#00FF88",f.fillText(e,n,l/2),this.timestampTex||(this.timestampTex=s.createTexture()),s.bindTexture(s.TEXTURE_2D,this.timestampTex),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,!0),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,this.timestampCanvas),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,!1),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),this.lastTimestampString=e}}catch(s){g(this.options,"Errors")&&console.error("[WebGL] ensureTimestampTexture failed",s)}}drawTimestampOnCanvas(e){const s=this.gl;try{if(this.ensureTimestampTexture(e),!this.timestampTex||!this.timestampCanvas)return;this.fboCompositeProgram||(this.fboCompositeProgram=this.linkProgram(qt,Kt),this.fboComposite_aPos=s.getAttribLocation(this.fboCompositeProgram,"aPos"),this.fboComposite_uFBOTex=s.getUniformLocation(this.fboCompositeProgram,"uFBOTex")),this.timestampVBO||(this.timestampVBO=s.createBuffer(),s.bindBuffer(s.ARRAY_BUFFER,this.timestampVBO),s.bufferData(s.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),s.STATIC_DRAW));const r=s.canvas.width|0,n=s.canvas.height|0,o=10,i=10,a=Math.min(this.timestampW,r-o),c=Math.min(this.timestampH,n-i),d=Math.max(0,r-o-a),l=Math.max(0,n-i-c);s.viewport(d,l,a,c),s.useProgram(this.fboCompositeProgram),s.disable(s.DEPTH_TEST),s.disable(s.CULL_FACE),s.enable(s.BLEND),s.blendFunc(s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA);const f=this.fboComposite_aPos;s.bindBuffer(s.ARRAY_BUFFER,this.timestampVBO),s.enableVertexAttribArray(f),s.vertexAttribPointer(f,2,s.FLOAT,!1,0,0),f!==0&&(s.enableVertexAttribArray(0),s.vertexAttribPointer(0,2,s.FLOAT,!1,0,0)),s.activeTexture(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,this.timestampTex),this.fboComposite_uFBOTex&&s.uniform1i(this.fboComposite_uFBOTex,0),s.drawArrays(s.TRIANGLE_STRIP,0,4),s.viewport(0,0,r,n)}catch(r){g(this.options,"Errors")&&console.error("[WebGL] drawTimestampOnCanvas failed",r)}}buildCubes(e,s,r){var n;try{const o=[];let i=0;const a=e.LedModel;for(const c of a){const d=(n=c.panel)==null?void 0:n.height,l=c.bottomPoints||[];if(!(!d||l.length<2))for(let f=0;f<l.length-1;f++){const u=l[f],m=l[f+1],p=m.x-u.x,T=m.y-u.y,h=(m.z||0)-(u.z||0),_=Math.hypot(p,T,h),y=Math.max(1,Math.round(_/d*r));o.push({uOffsetPx:i,sliceWidthPx:y}),i=(i+y)%s}}this.ledCubes=o}catch{g(this.options,"Errors")&&console.error("[WebGL] Error building LED cubes from model")}}updateLEDCubesFromModel(e,s){if(!(s&&this.ledModelVersion===s)){if(!this.ensureLEDArtFromAds()){g(this.options,"Errors")&&console.error("[LED Debug] No LED art available from ads");return}this.buildCubes(e,this.ledArtW,this.ledArtH),s&&(this.ledModelVersion=s)}}renderCubes(e,s,r,n,o){const i=this.gl,a=this.instancedExt,c=this.cubesProgram,d=this.blitProgram,l=s,f=r,u=n,m=o,p=this.LED_PADDING,T=this.cornerVBO,h=this.quadVBO,_=this.bDstTL,y=this.bDstTR,D=this.bDstBR,w=this.bDstBL,U=this.bH0,L=this.bH1,A=this.bH2,P=this.bU0,W=this.bSW;if(!T||!h||!_||!y||!D||!w||!U||!L||!A||!P||!W){g(this.options,"Errors")&&console.error("[WebGL] Missing required vertex buffers for LED rendering");return}(!this.overlayTex||!this.overlayFBO)&&(this.overlayTex=i.createTexture(),i.bindTexture(i.TEXTURE_2D,this.overlayTex),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,n,o,0,i.RGBA,i.UNSIGNED_BYTE,null),this.overlayFBO=i.createFramebuffer(),i.bindFramebuffer(i.FRAMEBUFFER,this.overlayFBO),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,this.overlayTex,0),i.bindFramebuffer(i.FRAMEBUFFER,null),i.disable(i.DEPTH_TEST),i.enable(i.BLEND),i.blendFunc(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA));const Z=this.overlayFBO;if(this.overlayTex,!c||!d||!a){g(this.options,"Errors")&&console.error("[WebGL] Missing programs or buffers",{cubesProg:c,blitProg:d,instancedExt:a});return}if(this.blit_aPos===void 0||this.blit_aPos<0){g(this.options,"Errors")&&console.error("[WebGL] Invalid blit_aPos attribute location:",this.blit_aPos);return}i.bindFramebuffer(i.FRAMEBUFFER,Z),i.viewport(0,0,u,m),i.clearColor(0,0,0,0),i.clear(i.COLOR_BUFFER_BIT),i.useProgram(c),i.bindBuffer(i.ARRAY_BUFFER,T),i.enableVertexAttribArray(0),i.vertexAttribPointer(0,1,i.FLOAT,!1,0,0),i.bindBuffer(i.ARRAY_BUFFER,_),i.enableVertexAttribArray(1),i.vertexAttribPointer(1,2,i.FLOAT,!1,0,0),a.vertexAttribDivisorANGLE(1,1),i.bindBuffer(i.ARRAY_BUFFER,y),i.enableVertexAttribArray(2),i.vertexAttribPointer(2,2,i.FLOAT,!1,0,0),a.vertexAttribDivisorANGLE(2,1),i.bindBuffer(i.ARRAY_BUFFER,D),i.enableVertexAttribArray(3),i.vertexAttribPointer(3,2,i.FLOAT,!1,0,0),a.vertexAttribDivisorANGLE(3,1),i.bindBuffer(i.ARRAY_BUFFER,w),i.enableVertexAttribArray(4),i.vertexAttribPointer(4,2,i.FLOAT,!1,0,0),a.vertexAttribDivisorANGLE(4,1),i.bindBuffer(i.ARRAY_BUFFER,U),i.enableVertexAttribArray(5),i.vertexAttribPointer(5,3,i.FLOAT,!1,0,0),a.vertexAttribDivisorANGLE(5,1),i.bindBuffer(i.ARRAY_BUFFER,L),i.enableVertexAttribArray(6),i.vertexAttribPointer(6,3,i.FLOAT,!1,0,0),a.vertexAttribDivisorANGLE(6,1),i.bindBuffer(i.ARRAY_BUFFER,A),i.enableVertexAttribArray(7),i.vertexAttribPointer(7,3,i.FLOAT,!1,0,0),a.vertexAttribDivisorANGLE(7,1),i.bindBuffer(i.ARRAY_BUFFER,P),i.enableVertexAttribArray(8),i.vertexAttribPointer(8,1,i.FLOAT,!1,0,0),a.vertexAttribDivisorANGLE(8,1),i.bindBuffer(i.ARRAY_BUFFER,W),i.enableVertexAttribArray(9),i.vertexAttribPointer(9,1,i.FLOAT,!1,0,0),a.vertexAttribDivisorANGLE(9,1),i.uniform2f(i.getUniformLocation(c,"uResolution"),u,m),i.uniform1i(i.getUniformLocation(c,"uFlipY"),1),i.uniform2f(i.getUniformLocation(c,"uShift"),0,0),i.uniform2f(i.getUniformLocation(c,"uArtSize"),this.ledArtW,this.ledArtH),this.cubes_uEdgeFeatherPx&&i.uniform1f(this.cubes_uEdgeFeatherPx,this.LED_AA_STRENGTH),i.activeTexture(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,this.ledArtTex),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.uniform1i(i.getUniformLocation(c,"uArt"),0),i.getParameter(i.TEXTURE_BINDING_2D)!==this.ledArtTex&&g(this.options,"Errors")&&console.error("Warning: Texture binding mismatch!"),a.drawArraysInstancedANGLE(i.TRIANGLES,0,6,e),a.vertexAttribDivisorANGLE(0,0);for(let V=1;V<=9;V++)a.vertexAttribDivisorANGLE(V,0),i.disableVertexAttribArray(V);i.disableVertexAttribArray(0);const Et=p/u,C=p/m,S=(p+l)/u,G=(p+f)/m;this.ledOverlayUVRect=[Et,C,S,G]}drawAugmentationWithLED(e,s,r,n=1,o,i){this.gl;let a=!1;try{if(o&&o.cubePlaceholders&&o.intrinsics&&o.referenceSize&&this.ensureLEDArtFromAds()){const c=Math.max(1,o.referenceSize.width|0),d=Math.max(1,o.referenceSize.height|0),l=this.LED_PADDING|0,f=c+l*2,u=d+l*2;this.ensureLedOverlay(f,u);const m=this.getCubesTransformationsToLiveImage(o);m&&m>0&&(this.renderCubes(m,c,d,f,u),a=!0)}}catch(c){g(this.options,"Errors")&&console.error("[WebGL] LED prep error:",c)}this.drawAugmentation(e,s,r,n,!0,a?void 0:i),a&&this.compositeLEDOverlayDirectToCanvas(!1,e)}drawLEDOnly(e,s){try{if(!s||!s.cubePlaceholders||!s.intrinsics||!s.referenceSize){g(this.options,"Errors")&&console.error("[LED Debug] Missing LED data - led:",!!s,"cubePlaceholders:",!!(s!=null&&s.cubePlaceholders),"intrinsics:",!!(s!=null&&s.intrinsics),"referenceSize:",!!(s!=null&&s.referenceSize));return}if(!this.ensureLEDArtFromAds()){g(this.options,"Errors")&&console.error("[LED Debug] Failed to ensure LED art from ads");return}const r=s.referenceSize.width,n=s.referenceSize.height,o=r+this.LED_PADDING*2,i=n+this.LED_PADDING*2;this.ensureLedOverlay(o,i);const a=this.getCubesTransformationsToLiveImage(s);if(!a||a===0){g(this.options,"Errors")&&console.error("[LED Debug] No LED cubes to render - check LED model data");return}this.renderCubes(a,r,n,o,i),this.compositeLEDOverlayDirectToCanvas(!0,e)}catch(r){g(this.options,"Errors")&&console.error("[WebGL] LED-only path error",r)}}drawLEDOverlayOnTop(e,s){try{if(!s||!s.cubePlaceholders||!s.intrinsics||!s.referenceSize){g(this.options,"Errors")&&console.error("[LED Debug] Missing LED data for drawLEDOverlayOnTop");return}if(!this.ensureLEDArtFromAds()){g(this.options,"Errors")&&console.error("[LED Debug] Failed to ensure LED art for drawLEDOverlayOnTop");return}const r=s.referenceSize.width,n=s.referenceSize.height,o=r+this.LED_PADDING*2,i=n+this.LED_PADDING*2;this.ensureLedOverlay(o,i);const a=this.getCubesTransformationsToLiveImage(s);a&&a>0&&(this.renderCubes(a,r,n,o,i),this.compositeLEDOverlayDirectToCanvas(!1,e))}catch(r){g(this.options,"Errors")&&console.error("[WebGL] drawLEDOverlayOnTop error",r)}}compositeLEDOverlayDirectToCanvas(e,s){const r=this.gl;if(!this.ledCompositeProgram||!this.overlayTex||!this.fsPosBuf||!this.fsUvBuf||this.comp_aPos===void 0||this.comp_aUv===void 0||!this.comp_uOverlay||!this.comp_uAlphaMask||!this.comp_uUVRect||!this.comp_uRes||!this.ledOverlayUVRect){g(this.options,"Errors")&&console.error("[WebGL] Missing resources for direct LED composite");return}r.bindFramebuffer(r.FRAMEBUFFER,null);const n=r.canvas.width,o=r.canvas.height;r.viewport(0,0,n,o),e&&(r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT)),r.useProgram(this.ledCompositeProgram),r.disable(r.DEPTH_TEST),r.disable(r.CULL_FACE),r.enable(r.BLEND),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA);for(let l=0;l<16;l++)r.disableVertexAttribArray(l);r.bindBuffer(r.ARRAY_BUFFER,this.fsPosBuf),r.enableVertexAttribArray(this.comp_aPos),r.vertexAttribPointer(this.comp_aPos,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.fsUvBuf),r.enableVertexAttribArray(this.comp_aUv),r.vertexAttribPointer(this.comp_aUv,2,r.FLOAT,!1,0,0),r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.overlayTex),r.uniform1i(this.comp_uOverlay,0),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,s),r.uniform1i(this.comp_uAlphaMask,1);const[i,a,c,d]=this.ledOverlayUVRect;r.uniform4f(this.comp_uUVRect,i,a,c,d),r.uniform2f(this.comp_uRes,n,o),r.drawArrays(r.TRIANGLES,0,6)}compositeLEDFBOToCanvas(e,s){const r=this.gl,n=this.quadVBO;if(!this.compositeTex||!this.fboCompositeProgram||!n){g(this.options,"Errors")&&console.error("[WebGL] Missing resources for LED FBO compositing");return}for(;r.getError()!==r.NO_ERROR;);r.bindFramebuffer(r.FRAMEBUFFER,null);const o=r.canvas.width,i=r.canvas.height;if(r.viewport(0,0,o,i),e&&(r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT)),this.fboCompositeProgram||(this.fboCompositeProgram=this.linkProgram(qt,Kt),this.fboComposite_aPos=r.getAttribLocation(this.fboCompositeProgram,"aPos"),this.fboComposite_uFBOTex=r.getUniformLocation(this.fboCompositeProgram,"uFBOTex")),s&&this.ledCompositeProgram&&this.fsPosBuf&&this.fsUvBuf&&this.comp_aPos!==void 0&&this.comp_aUv!==void 0&&this.comp_uOverlay&&this.comp_uAlphaMask&&this.comp_uUVRect&&this.comp_uRes){r.useProgram(this.ledCompositeProgram),r.disable(r.DEPTH_TEST),r.disable(r.CULL_FACE),r.enable(r.BLEND),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA);for(let f=0;f<16;f++)r.disableVertexAttribArray(f);r.bindBuffer(r.ARRAY_BUFFER,this.fsPosBuf),r.enableVertexAttribArray(this.comp_aPos),r.vertexAttribPointer(this.comp_aPos,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.fsUvBuf),r.enableVertexAttribArray(this.comp_aUv),r.vertexAttribPointer(this.comp_aUv,2,r.FLOAT,!1,0,0),r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.compositeTex),r.uniform1i(this.comp_uOverlay,0),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,s),r.uniform1i(this.comp_uAlphaMask,1),r.uniform4f(this.comp_uUVRect,0,0,1,1),r.uniform2f(this.comp_uRes,o,i),r.drawArrays(r.TRIANGLES,0,6);return}r.useProgram(this.fboCompositeProgram),r.disable(r.DEPTH_TEST),r.disable(r.CULL_FACE),r.enable(r.BLEND),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA);for(let f=0;f<16;f++)r.disableVertexAttribArray(f);r.bindBuffer(r.ARRAY_BUFFER,n);const a=this.fboComposite_aPos;if(a===void 0||a<0){g(this.options,"Errors")&&console.error("[WebGL] Invalid fboComposite aPos location:",a);return}r.enableVertexAttribArray(a),r.vertexAttribPointer(a,2,r.FLOAT,!1,0,0),a!==0&&(r.enableVertexAttribArray(0),r.vertexAttribPointer(0,2,r.FLOAT,!1,0,0));const c=r.getBufferParameter(r.ARRAY_BUFFER,r.BUFFER_SIZE);c!==32&&g(this.options,"Errors")&&console.error("[WebGL] Unexpected quadVBO size:",c,"expected 32 bytes"),r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.compositeTex),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),this.fboComposite_uFBOTex&&r.uniform1i(this.fboComposite_uFBOTex,0);const d=r.getError();d&&g(this.options,"Errors")&&console.error("[WebGL] Error before composite draw:",d),r.drawArrays(r.TRIANGLE_STRIP,0,4);const l=r.getError();l&&g(this.options,"Errors")&&console.error("[WebGL] Error in LED FBO composite:",l)}getDistortionCtx(e){if(!e.intrinsics||!e.distortion)return;const s=e.intrinsics,r=e.distortion,n=r[0],o=r[1],i=r[2],a=s.cx,c=s.cy,d=s.fx,l=s.fy;return{k1:n,k2:o,k3:i,cx:a,cy:c,fx:d,fy:l,undistortNormalized(f,u){let m=f,p=u;for(let T=0;T<5;T++){const h=m*m+p*p,_=h*h,y=_*h,D=1+n*h+o*_+i*y,w=D!==0?1/D:1;m=f*w,p=u*w}return{x:m,y:p}},undistortCanvasPoint(f,u){const m=f.x+u,p=f.y+u,T=(m-(a+u))/d,h=(p-(c+u))/l,_=this.undistortNormalized(T,h),y=a+u+d*_.x,D=c+u+l*_.y;return{x:y-u,y:D-u}}}}pickCorners(e){const s=e.tgtCorners||e.block&&e.block.fenceVertices2D;return!s||s.length!==4?null:[s[0],s[1],s[2],s[3]]}getHinv(e,s){const r=[],n=[];for(let S=0;S<4;S++){const G=e[S].x,V=e[S].y,ye=s[S].x,F=s[S].y;r.push([G,V,1,0,0,0,-G*ye,-V*ye]),n.push(ye),r.push([0,0,0,G,V,1,-G*F,-V*F]),n.push(F)}const o=8,i=r.map(S=>S.slice()),a=n.slice();for(let S=0;S<o;S++){let G=S;for(let F=S+1;F<o;F++)Math.abs(i[F][S])>Math.abs(i[G][S])&&(G=F);if(G!==S){const F=i[S];i[S]=i[G],i[G]=F;const Ne=a[S];a[S]=a[G],a[G]=Ne}const ye=1/(i[S][S]||1e-12);for(let F=S;F<o;F++)i[S][F]*=ye;a[S]*=ye;for(let F=0;F<o;F++){if(F===S)continue;const Ne=i[F][S];if(Ne!==0){for(let Tt=S;Tt<o;Tt++)i[F][Tt]-=Ne*i[S][Tt];a[F]-=Ne*a[S]}}}const c=a,d=[c[0],c[1],c[2],c[3],c[4],c[5],c[6],c[7],1],[l,f,u,m,p,T,h,_,y]=[d[0],d[1],d[2],d[3],d[4],d[5],d[6],d[7],d[8]],D=p*y-T*_,w=-(m*y-T*h),U=m*_-p*h,L=-(f*y-u*_),A=l*y-u*h,P=-(l*_-f*h),W=f*T-u*p,Z=-(l*T-u*m),gt=l*p-f*m,C=1/(l*D+f*w+u*U||1e-12);return[D*C,L*C,W*C,w*C,A*C,Z*C,U*C,P*C,gt*C]}getCubesTransformationsToLiveImage(e){if(!e||!e.cubePlaceholders||!e.intrinsics||!e.referenceSize)return;const s=this.LED_PADDING,r=e.cubePlaceholders,n=r.length,o=new Float32Array(n*2),i=new Float32Array(n*2),a=new Float32Array(n*2),c=new Float32Array(n*2),d=new Float32Array(n*3),l=new Float32Array(n*3),f=new Float32Array(n*3),u=new Float32Array(n),m=new Float32Array(n);let p=0;const T=this.getDistortionCtx(e);if(!T)return;for(let _=0;_<n;_++){const y=r[_],D=y.index;if(D<0||D>=this.ledCubes.length)continue;const w=this.pickCorners(y);if(!w)continue;const U=T.undistortCanvasPoint(w[0],s),L=T.undistortCanvasPoint(w[1],s),A=T.undistortCanvasPoint(w[2],s),P=T.undistortCanvasPoint(w[3],s);o.set([U.x,U.y],_*2),i.set([L.x,L.y],_*2),a.set([A.x,A.y],_*2),c.set([P.x,P.y],_*2);const W=this.ledCubes[D],Z=Math.max(1,W.sliceWidthPx),gt=[{x:0,y:this.ledArtH},{x:0,y:0},{x:Z,y:0},{x:Z,y:this.ledArtH}],Et=[U,L,A,P],C=this.getHinv(gt,Et);d.set([C[0],C[1],C[2]],_*3),l.set([C[3],C[4],C[5]],_*3),f.set([C[6],C[7],C[8]],_*3),u[_]=W.uOffsetPx/this.ledArtW,m[_]=Z,p++}const h=this.gl;return h.bindBuffer(h.ARRAY_BUFFER,this.bDstTL),h.bufferData(h.ARRAY_BUFFER,o,h.DYNAMIC_DRAW),h.bindBuffer(h.ARRAY_BUFFER,this.bDstTR),h.bufferData(h.ARRAY_BUFFER,i,h.DYNAMIC_DRAW),h.bindBuffer(h.ARRAY_BUFFER,this.bDstBR),h.bufferData(h.ARRAY_BUFFER,a,h.DYNAMIC_DRAW),h.bindBuffer(h.ARRAY_BUFFER,this.bDstBL),h.bufferData(h.ARRAY_BUFFER,c,h.DYNAMIC_DRAW),h.bindBuffer(h.ARRAY_BUFFER,this.bH0),h.bufferData(h.ARRAY_BUFFER,d,h.DYNAMIC_DRAW),h.bindBuffer(h.ARRAY_BUFFER,this.bH1),h.bufferData(h.ARRAY_BUFFER,l,h.DYNAMIC_DRAW),h.bindBuffer(h.ARRAY_BUFFER,this.bH2),h.bufferData(h.ARRAY_BUFFER,f,h.DYNAMIC_DRAW),h.bindBuffer(h.ARRAY_BUFFER,this.bU0),h.bufferData(h.ARRAY_BUFFER,u,h.DYNAMIC_DRAW),h.bindBuffer(h.ARRAY_BUFFER,this.bSW),h.bufferData(h.ARRAY_BUFFER,m,h.DYNAMIC_DRAW),p}setLEDArtTexture(e){try{const s=this.gl;this.ledArtTex||(this.ledArtTex=s.createTexture()),s.bindTexture(s.TEXTURE_2D,this.ledArtTex),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,e);const r=this.getDims(e);this.ledArtW=r.w||1,this.ledArtH=r.h||1;const n=this.isPowerOf2(this.ledArtW)&&this.isPowerOf2(this.ledArtH);if(s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),n)s.generateMipmap(s.TEXTURE_2D),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR_MIPMAP_LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR);else{s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR);const o=s.getExtension("EXT_texture_filter_anisotropic")||s.getExtension("WEBKIT_EXT_texture_filter_anisotropic");if(o){const i=s.getParameter(o.MAX_TEXTURE_MAX_ANISOTROPY_EXT);s.texParameteri(s.TEXTURE_2D,o.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(16,i))}}}catch(s){g(this.options,"Errors")&&console.error("[WebGL] setLEDArtTexture failed",s)}}ensureLEDArtFromAds(){var e,s,r,n,o,i;try{if(this.ledArtTex)return!0;const a=((r=(s=(e=this.renderer.ads)==null?void 0:e.ledAds)==null?void 0:s[0])==null?void 0:r.image)||((i=(o=(n=this.renderer.ads)==null?void 0:n.ads)==null?void 0:o[0])==null?void 0:i.image);if(!a)return g(this.options,"Errors")&&console.error("[LED Debug] No ad image found in ads object"),!1;if(!this.ledArtTex){const c=this.gl,d=c.createTexture();c.bindTexture(c.TEXTURE_2D,d),c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,a),this.ledArtW=a.width||1,this.ledArtH=a.height||1;const l=this.isPowerOf2(this.ledArtW)&&this.isPowerOf2(this.ledArtH);if(c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),l)c.generateMipmap(c.TEXTURE_2D),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MIN_FILTER,c.LINEAR_MIPMAP_LINEAR),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MAG_FILTER,c.LINEAR);else{c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MIN_FILTER,c.LINEAR),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MAG_FILTER,c.LINEAR);const f=c.getExtension("EXT_texture_filter_anisotropic")||c.getExtension("WEBKIT_EXT_texture_filter_anisotropic");if(f){const u=c.getParameter(f.MAX_TEXTURE_MAX_ANISOTROPY_EXT);c.texParameteri(c.TEXTURE_2D,f.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(16,u))}}this.ledArtTex=d}return!0}catch(a){return g(this.options,"Errors")&&console.error("[LED Debug] Error in ensureLEDArtFromAds:",a),!1}}ensureLedOverlay(e,s){const r=this.gl;this.ledOverlayTex&&this.ledOverlayW===e&&this.ledOverlayH===s||(this.ledOverlayTex&&r.deleteTexture(this.ledOverlayTex),this.ledOverlayFBO&&r.deleteFramebuffer(this.ledOverlayFBO),this.ledOverlayTex=r.createTexture(),r.bindTexture(r.TEXTURE_2D,this.ledOverlayTex),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,s,0,r.RGBA,r.UNSIGNED_BYTE,null),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),this.ledOverlayFBO=r.createFramebuffer(),r.bindFramebuffer(r.FRAMEBUFFER,this.ledOverlayFBO),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.ledOverlayTex,0),r.bindFramebuffer(r.FRAMEBUFFER,null),this.ledOverlayW=e,this.ledOverlayH=s)}ensureCompositeFBO(e,s){const r=this.gl;this.compositeTex&&this.compositeFBO,this.compositeTex&&r.deleteTexture(this.compositeTex),this.compositeFBO&&r.deleteFramebuffer(this.compositeFBO),this.compositeTex=r.createTexture(),r.bindTexture(r.TEXTURE_2D,this.compositeTex),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,s,0,r.RGBA,r.UNSIGNED_BYTE,null),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),this.compositeFBO=r.createFramebuffer(),r.bindFramebuffer(r.FRAMEBUFFER,this.compositeFBO),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.compositeTex,0);const n=r.checkFramebufferStatus(r.FRAMEBUFFER);n!==r.FRAMEBUFFER_COMPLETE&&console.error("[WebGL] Composite FBO incomplete:",n),r.bindFramebuffer(r.FRAMEBUFFER,null)}initBuffers(){const e=this.gl;this.posBuf=e.createBuffer(),this.uvBuf=e.createBuffer(),this.transformBuf=e.createBuffer(),this.fsPosBuf=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.fsPosBuf),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,1,0,1,1,0,0,1,1,0,1]),e.STATIC_DRAW),this.fsUvBuf=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.fsUvBuf),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,0,1,0,1,1,0,0,1,1,0,1]),e.STATIC_DRAW),this.options.RENDER_LED&&(this.quadVBO=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.quadVBO),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),e.STATIC_DRAW),this.cornerVBO=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.cornerVBO),e.bufferData(e.ARRAY_BUFFER,new Float32Array([0,3,1,1,3,2]),e.STATIC_DRAW),this.bDstTL=e.createBuffer(),this.bDstTR=e.createBuffer(),this.bDstBR=e.createBuffer(),this.bDstBL=e.createBuffer(),this.bH0=e.createBuffer(),this.bH1=e.createBuffer(),this.bH2=e.createBuffer(),this.bU0=e.createBuffer(),this.bSW=e.createBuffer())}buildQuadData(e){const s=[],r=[],n=[];return Object.values(e).forEach(o=>{var d,l;const i=(l=(d=this.renderer.ads)==null?void 0:d.adMap.get(o.name))==null?void 0:l.name;if(!i)return;const a=this.logoToRegion.get(i);if(!a)return;const c=o.corners;s.push(c[0].x,c[0].y,c[1].x,c[1].y,c[2].x,c[2].y,c[0].x,c[0].y,c[2].x,c[2].y,c[3].x,c[3].y);for(let f=0;f<6;f++)r.push(a.u0,a.v0,a.u1,a.v1);for(let f=0;f<6;f++)n.push(...o.tranform)}),{pos:new Float32Array(s),uv:new Float32Array(r),transforms:new Float32Array(n),vertCount:s.length/2}}cleanGL(){this.gl.clearColor(0,0,0,0),this.gl.clear(this.gl.COLOR_BUFFER_BIT)}initAtlas(){this.atlasCanvas=new OffscreenCanvas(this.INITIAL_ATLAS_SIZE,this.INITIAL_ATLAS_SIZE),this.atlasCanvas.width=this.atlasCanvas.height=this.INITIAL_ATLAS_SIZE,this.atlasCtx=this.atlasCanvas.getContext("2d"),this.atlasTex=this.gl.createTexture(),this.atlasCtx.clearRect(0,0,this.INITIAL_ATLAS_SIZE,this.INITIAL_ATLAS_SIZE),this.syncAtlasGL()}getDims(e){if("width"in e&&"height"in e)return{w:e.width,h:e.height};const s=e;return{w:s.displayWidth??s.codedWidth,h:s.displayHeight??s.codedHeight}}isPowerOf2(e){return(e&e-1)===0}calculateRequiredAtlasSize(e,s){const r=this.ATLAS_PADDING*2;let n=(e+r)*(s+r);this.logoToRegion.forEach(i=>{const a=(i.u1-i.u0)*this.ATLAS_SIZE,c=(i.v1-i.v0)*this.ATLAS_SIZE;n+=(a+r)*(c+r)}),n*=1.3;let o=this.INITIAL_ATLAS_SIZE;for(;o*o<n;)o*=2;return o}resizeAtlas(e,s){const r=this.calculateRequiredAtlasSize(e,s);if(r<=this.ATLAS_SIZE)return;const n=new OffscreenCanvas(r,r),o=n.getContext("2d");o.clearRect(0,0,r,r),o.drawImage(this.atlasCanvas,0,0);const i=this.ATLAS_SIZE/r;this.ATLAS_SIZE=r,this.atlasCanvas=n,this.atlasCtx=o,this.logoToRegion.forEach((a,c)=>{const d={u0:a.u0*i,v0:a.v0*i,u1:a.u1*i,v1:a.v1*i};this.logoToRegion.set(c,d)}),this.syncAtlasGL()}addToAtlas(e,s){if(this.logoToRegion.has(e))return this.logoToRegion.get(e);const{w:r,h:n}=this.getDims(s),o=this.ATLAS_PADDING,i=r+o*2,a=n+o*2;this.nextX+i>this.ATLAS_SIZE&&(this.nextX=0,this.nextY+=this.rowH,this.rowH=0),(this.nextY+a>this.ATLAS_SIZE||this.nextX+i>this.ATLAS_SIZE)&&this.resizeAtlas(i,a);const c=this.nextX+o,d=this.nextY+o;this.atlasCtx.drawImage(s,c,d,r,n);const l={u0:c/this.ATLAS_SIZE,v0:d/this.ATLAS_SIZE,u1:(c+r)/this.ATLAS_SIZE,v1:(d+n)/this.ATLAS_SIZE};return this.logoToRegion.set(e,l),this.atlasDirty=!0,this.nextX+=i,this.rowH=Math.max(this.rowH,a),l}syncAtlasGL(){if(!this.atlasDirty)return;const e=this.gl;e.bindTexture(e.TEXTURE_2D,this.atlasTex),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.atlasCanvas),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),this.isPowerOf2(this.ATLAS_SIZE)?(e.generateMipmap(e.TEXTURE_2D),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR_MIPMAP_LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR)):(e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR));const r=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");if(r){const n=e.getParameter(r.MAX_TEXTURE_MAX_ANISOTROPY_EXT);e.texParameteri(e.TEXTURE_2D,r.TEXTURE_MAX_ANISOTROPY_EXT,n)}this.atlasDirty=!1}clearAtlas(){this.logoToRegion.clear(),this.nextX=this.nextY=this.rowH=0,this.atlasCtx.clearRect(0,0,this.ATLAS_SIZE,this.ATLAS_SIZE),this.atlasDirty=!0,this.syncAtlasGL()}generateAdTexture(e,s){O.setAttributes({asset:e}),this.addToAtlas(e,s)}measureLogoVisibility(e){const s=this.gl.canvas.width,r=this.gl.canvas.height,n=this.renderer.shot;if(!n)return;const{percentOfAd:o,percentOfScreen:i}=Ta(e,s,r);n.frameCount++,n.sumPercentOfAd+=o,n.sumPercentOfScreen+=i,n.lastProcessingTime=performance.now()}initTiming(){var e;(e=this.options.debug)!=null&&e.trackPerformance&&(this.timerExt=this.gl.getExtension("EXT_disjoint_timer_query"),this.timerExt||g(this.options,"Errors")&&console.error("EXT_disjoint_timer_query not supported"))}beginTimer(){!this.timerExt||this.queryInFlight||(this.query=this.timerExt.createQueryEXT(),this.timerExt.beginQueryEXT(this.timerExt.TIME_ELAPSED_EXT,this.query))}endTimer(){if(!this.timerExt||!this.query||this.queryInFlight)return;this.timerExt.endQueryEXT(this.timerExt.TIME_ELAPSED_EXT),this.queryInFlight=!0;const e=()=>{if(!this.queryInFlight)return;const s=this.timerExt.getQueryObjectEXT(this.query,this.timerExt.QUERY_RESULT_AVAILABLE_EXT),r=this.gl.getParameter(this.timerExt.GPU_DISJOINT_EXT);if(s&&!r){const o=this.timerExt.getQueryObjectEXT(this.query,this.timerExt.QUERY_RESULT_EXT)/1e6;this.GPUFrameTimeSum+=o,this.GPUFrameTimeCount++,this.avgGPUFrameTime=this.GPUFrameTimeSum/this.GPUFrameTimeCount,this.timerExt.deleteQueryEXT(this.query),this.query=null,this.queryInFlight=!1}else requestAnimationFrame(e)};requestAnimationFrame(e)}getAvgGPUFrameTime(){var e;if((e=this.options.debug)!=null&&e.trackPerformance){const s=this.avgGPUFrameTime;return this.GPUFrameTimeCount=0,this.GPUFrameTimeSum=0,this.avgGPUFrameTime=0,s}return 0}getAvgCPUFrameTime(){var e;if((e=this.options.debug)!=null&&e.trackPerformance){const s=this.avgCPUFrameTime;return this.CPUFrameTimeCount=0,this.CPUFrameTimeSum=0,this.avgCPUFrameTime=0,s}return 0}}const os=["LeftTop","MidTopLeft","MidTopRight","RightTop","LeftBottom","MidBottomLeft","MidBottomRight","RightBottom"];class as{constructor(e,s){this.ads=[],this.ledAds=[],this.isOverridden=!1,this.assetKeyToAdv=new Map,this.getAds=async()=>{var r;try{const n=this.options.adsBaseURL,o=await fetch(n+"/profiles/geo/",{method:"GET",redirect:"follow",cache:"no-store"});if(this.options&&g(this.options,"Ads")&&console.log("[ADS] adListResponse: ",o),!o.ok){O.error("[ADS] Failed to fetch ad list"),this.options&&g(this.options,"Errors")&&console.error("[ADS] Failed to fetch ad list");return}const i=await o.json();this.options&&g(this.options,"Ads")&&console.log("[ADS] Current JSON with ads: ",i.rootAdPath);const a=i.rootAdPath;if(!a){O.error("[ADS] rootAdPath is missing in the ads response"),this.options&&g(this.options,"Errors")&&console.error("[ADS] rootAdPath is missing in the response");return}if(this.lastJson===JSON.stringify(i))return;this.lastJson=JSON.stringify(i),this.ads=[],this.options&&g(this.options,"Ads")&&console.warn("[ADS] Fetching ad image from: ",a);const c=a,d=c.split("assets/")[1].split("?")[0],f=await(await fetch(c,{headers:{"X-Platform":"Web"}})).blob(),u=await createImageBitmap(f),m={name:c,imageUrl:c,image:u,adUrl:"https://www.BurgerKing.com/"};if(this.ads.push(m),this.ledAds=[m],this.isOverridden)this.options&&g(this.options,"Ads")&&console.log("[ADS] Skipping texture upload due to manual override");else{this.setAd("LeftTop",0),this.setAd("RightBottom",0),this.setAd("MidBottomLeft",0),this.setAd("MidTopRight",0),this.setAd("MidTopLeft",0),this.setAd("MidBottomRight",0),this.setAd("LeftBottom",0),this.setAd("RightTop",0),this.uploadAdTextures();try{(r=this.ledAds[0])!=null&&r.image&&this.webgl.setLEDArtTexture(this.ledAds[0].image)}catch{}}}catch{}finally{this.refreshTimeoutId&&(clearTimeout(this.refreshTimeoutId),this.refreshTimeoutId=void 0),this.isOverridden||(this.refreshTimeoutId=setTimeout(this.getAds,1e4))}},this.loadAdvImage=async r=>{const n=\`#\${r.name}\`,o=r.url;if(n.indexOf(".json")>-1)return;const a=await(await fetch(o)).blob();return await createImageBitmap(a)},this.setAd=(r,n)=>{this.adMap.set(r,this.ads[n])},this.uploadAdTextures=()=>{this.webgl.clearAtlas(),this.adMap.forEach((r,n)=>{!r||!r.image||this.webgl.generateAdTexture(r.name,r.image)})},this.overrideAdImage=async r=>{this.options&&g(this.options,"Ads")&&console.log("[ADS] overrideAdImage called"),this.stopAutoRefresh();const n=this.ads[0];let o;try{o=await this.computeImageBitmapHash(r)}catch{}const i={name:o?\`asset_\${o}\`:"override_ad",imageUrl:(n==null?void 0:n.imageUrl)||"",image:r,adUrl:(n==null?void 0:n.adUrl)||""};o&&this.assetKeyToAdv.set(o,i),this.ads=[i],this.adMap.forEach((a,c)=>this.adMap.set(c,i)),this.uploadAdTextures(),this.options&&g(this.options,"Ads")&&console.log("[ADS] overrideAdImage completed")},this.overrideLEDImage=r=>{this.options&&g(this.options,"Ads")&&console.log("[ADS] overrideLEDImage called"),this.stopAutoRefresh();const n=this.ledAds[0]||this.ads[0],o={name:"override_led",imageUrl:(n==null?void 0:n.imageUrl)||"",image:r,adUrl:(n==null?void 0:n.adUrl)||""};this.ledAds=[o];try{this.webgl.setLEDArtTexture(r),this.options&&g(this.options,"Ads")&&console.log("[ADS] overrideLEDImage completed")}catch{this.options&&g(this.options,"Errors")&&console.error("[ADS] Failed to set LED art texture")}},this.overrideAdImageForPlaceholder=async(r,n)=>{if(this.placeholderNames.indexOf(n)===-1){O.error(\`[ADS] Unknown placeholder: \${n}\`),this.options&&g(this.options,"Errors")&&console.error("[ADS] Unknown placeholder provided to overrideAdImageForPlaceholder:",n);try{r.close()}catch{}return}this.stopAutoRefresh();let o,i;try{i=await this.computeImageBitmapHash(r)}catch{}if(i&&(o=this.assetKeyToAdv.get(i)),o)try{r.close()}catch{}else{const a=this.ads[0];o={name:i?\`asset_\${i}\`:\`override_\${Date.now()}\`,imageUrl:(a==null?void 0:a.imageUrl)||"",image:r,adUrl:(a==null?void 0:a.adUrl)||""},i&&this.assetKeyToAdv.set(i,o);try{this.uploadAdTextures()}catch{}}this.adMap.set(n,o);try{this.uploadAdTextures()}catch{this.options&&g(this.options,"Errors")&&console.error("[ADS] Failed to set ad texture")}},this.getAdURLAtCoord=(r,n,o)=>{let i;return Object.keys(r).forEach(a=>{const c=r[a].corners.map(d=>({x:d.x/n.width,y:d.y/n.height}));if(this.isPointInPlaceholder(c,o)){const d=r[a].name,l=this.adMap.get(d);this.options&&g(this.options,"Ads")&&console.log("ad: ",l),l&&(this.options&&g(this.options,"Ads")&&console.log("ad.url: ",l.adUrl),i=l.adUrl)}}),i},this.isPointInPlaceholder=(r,n)=>{let o=!1;const{x:i,y:a}=n,c=r.length;for(let d=0,l=c-1;d<c;l=d++){const f=r[d].x,u=r[d].y,m=r[l].x,p=r[l].y;u>a!=p>a&&i<(m-f)*(a-u)/(p-u)+f&&(o=!o)}return o},this.placeholderNames=os,this.webgl=e,this.options=s,this.adMap=new Map,os.forEach(r=>{this.adMap.set(r,void 0)}),this.getAds()}stopAutoRefresh(){this.isOverridden=!0,this.refreshTimeoutId&&(clearTimeout(this.refreshTimeoutId),this.refreshTimeoutId=void 0)}resumeAutoRefresh(){this.isOverridden=!1,this.ads=[],this.ledAds=[],this.lastJson=void 0,this.getAds()}pause(){this.refreshTimeoutId&&(clearTimeout(this.refreshTimeoutId),this.refreshTimeoutId=void 0),this.options&&g(this.options,"Ads")&&console.log("[ADS] Paused ad refresh")}resume(){this.options&&g(this.options,"Ads")&&console.log("[ADS] Resuming ad refresh"),this.isOverridden||this.getAds()}async computeImageBitmapHash(e){const s=Math.max(1,e.width||0),r=Math.max(1,e.height||0),n=new OffscreenCanvas(s,r),o=n.getContext("2d");if(!o)throw new Error("2D context not available");o.drawImage(e,0,0,s,r);const a=await(await n.convertToBlob({type:"image/png"})).arrayBuffer(),c=await crypto.subtle.digest("SHA-256",a),d=new Uint8Array(c);let l="";for(let f=0;f<d.length;f++)l+=d[f].toString(16).padStart(2,"0");return l}}class cs{constructor(e,s){this.renderDataMap=new Map,this.isRenderData=!1,this.videoFrameTexture=null,this.state="OFF",this.opacity=0,this.lastStateUpdate=0,this.stateUpdateInterval=500,this.lastPerformanceCheck=performance.now(),this.lastStatusUpdate=0,this.STATUS_UPDATE_INTERVAL=200,this.statusInitialized=!1,this.lastWebGLStatus={ready:!1,issue:""},this.lastRenderState="OFF",this.lastDataStatus={stream_data:!1,ads:!1,render_data:!1,alpha_mask:!1,placeholders:!1,processing_size:!1,isLive:!1},this.lastKillswitchStatus={web:!1,local:!1},this.lastZipBufferStatus=void 0,this.rendererStopped=!1,this.setWebGLEventListeners=()=>{const r=this.glContext.canvas;r.addEventListener("webglcontextlost",n=>{console.warn("Context lost:",n),n.preventDefault()}),r.addEventListener("webglcontextrestored",()=>{console.log("Context restored!"),this.webgl=new is(this,this.options),this.ads=new as(this.webgl,this.options),this.webgl.init(),this.updateStatusOverlay()})},this.addMetadataBatch=r=>{if(this.rendererStopped){r.forEach(n=>{if(n.alphaMask)try{n.alphaMask.close()}catch{}});return}r.forEach(n=>{var o;if(n.alphaMask){this.options&&g(this.options,"Renderer")&&console.log(\`[RendererWorker] Creating texture for timeCode=\${n.timecode}\`);try{const i=this.webgl.createTextureFromVideoFrame(n.alphaMask),a=n.timecode,c={width:n.processingWidth,height:n.processingHeight},d=n.placeholders??{},l={alphaMask:i,placeholders:d,processingSize:c,isLive:n.isLive},f=n.LED;if(f&&(l.led={cubePlaceholders:f.cubePlaceholders,intrinsics:f.intrinsics,distortion:f.distortion,referenceSize:f.referenceSize,modelVersion:f.modelVersion??((o=f.model)==null?void 0:o.version)},f.model&&f.model.LedModel))try{this.webgl.updateLEDCubesFromModel(f.model,l.led.modelVersion)}catch{}this.renderDataMap.set(a,l),O.setAttributes({last_webgl_uploaded_frame:a})}catch{this.options&&g(this.options,"Errors")&&console.error(\`[RendererWorker] Error creating texture for timeCode=\${n.timecode}\`)}finally{n.alphaMask.close()}}})},this.handleBurnedFrameRender=(r,n)=>{var o;if(!this.streamData||!((o=this.ads)!=null&&o.ads)){r.close();return}try{this.videoFrameTexture&&this.webgl.deleteTexture(this.videoFrameTexture),this.videoFrameTexture=this.webgl.createTextureFromImageBitmap(r);const i=this.renderDataMap.get(n);this.webgl.drawVideoFrameBase(this.videoFrameTexture),i&&(this.webgl.drawAugmentation(i.alphaMask,i.placeholders,i.processingSize,1,!1,this.options.DRAW_TIMESTAMP_WEBGL?n:void 0),this.shot&&(this.shot.frameCount++,this.shot.lastProcessingTime=performance.now())),this.deleteOldTextures(n),O.setAttributes({last_rendered_frame:n,renderer_state:this.state,has_augmentation:!!i,burned_timecode_mode:!0})}catch(i){O.error(\`[Renderer] Error rendering burned frame for timeCode=\${n}\`,{error:i}),this.options&&g(this.options,"Errors")&&console.error("[Renderer] Error rendering burned frame:",i)}finally{r.close()}},this.handleBurnedFrameRenderWithLED=(r,n)=>{var o;if(this.rendererStopped){try{r.close()}catch{}return}if(!this.streamData||!((o=this.ads)!=null&&o.ads)){r.close();return}try{this.videoFrameTexture&&this.webgl.deleteTexture(this.videoFrameTexture),this.videoFrameTexture=this.webgl.createTextureFromImageBitmap(r);const i=this.renderDataMap.get(n);this.webgl.drawVideoFrameBase(this.videoFrameTexture),i&&(i.placeholders&&Object.keys(i.placeholders).length>0&&this.webgl.drawAugmentation(i.alphaMask,i.placeholders,i.processingSize,1,!1,this.options.DRAW_TIMESTAMP_WEBGL?n:void 0),i.led&&this.webgl.drawLEDOverlayOnTop(i.alphaMask,i.led),this.shot&&(this.shot.frameCount++,this.shot.lastProcessingTime=performance.now())),this.deleteOldTextures(n),O.setAttributes({last_rendered_frame:n,renderer_state:this.state,has_augmentation:!!i,has_led:!!(i!=null&&i.led),burned_timecode_mode:!0})}catch(i){O.error(\`[Renderer] Error rendering burned frame with LED for timeCode=\${n}\`,{error:i}),this.options&&g(this.options,"Errors")&&console.error("[Renderer] Error rendering burned frame with LED:",i)}finally{r.close()}},this.handleRenderDraw=(r,n)=>{var p,T,h,_,y,D,w;if(this.rendererStopped||!this.streamData||!((p=this.ads)!=null&&p.ads))return;const o=this.renderDataMap.get(r);!!o!==this.isRenderData&&(o?(this.shot&&this.finalizeShot(this.shot,r),this.shot={shotId:crypto.randomUUID(),adURL:((T=this.ads.ads[0])==null?void 0:T.adUrl)||"",sumPercentOfScreen:0,sumPercentOfAd:0,frameCount:0,start:performance.now(),lastProcessingTime:performance.now()},O.info("didStartDrawingAugmentationMedia",{timecode:r,adID:this.shot.shotId,adURL:this.shot.adURL})):this.shot&&this.finalizeShot(this.shot,r),this.isRenderData=!!o);const i=o?o.isLive:!1,a=!this.zipBufferStatus||this.zipBufferStatus.isReady,c=((h=this.zipBufferStatus)==null?void 0:h.needsFadeout)||!1,d=i&&!c&&!!this.ottActions&&(this.ottActions.toggle[this.streamData.customerId]!==void 0?this.ottActions.toggle[this.streamData.customerId]&&this.ottActions.toggle.web:this.ottActions.toggle.web)&&(this.ottActions.toggle.local!==void 0?this.ottActions.toggle.local:!0),l=((_=this.ottActions)==null?void 0:_.benchmarkPassed)??!1;if(!d||c||!l?(this.state==="ON"||this.state==="FADE_IN")&&(this.state="FADE_OUT"):a&&l&&(this.state==="OFF"||this.state==="FADE_OUT")&&(this.state="FADE_IN"),this.state==="FADE_IN"?(this.opacity===0&&(this.lastStateUpdate=performance.now(),this.opacity=.001),this.opacity=Math.min(1,this.opacity+(performance.now()-this.lastStateUpdate)/this.stateUpdateInterval),this.lastStateUpdate=performance.now(),this.opacity===1&&(this.state="ON")):this.state==="FADE_OUT"&&(this.opacity===1&&(this.lastStateUpdate=performance.now(),this.opacity=.999),this.opacity=Math.max(0,this.opacity-(performance.now()-this.lastStateUpdate)/this.stateUpdateInterval),this.lastStateUpdate=performance.now(),this.opacity===0&&(this.state="OFF")),!o)return;const f=o.alphaMask,u=o.placeholders,m=o.processingSize;if(!(!f||!u||!m)){if((this.glContext.canvas.width!==m.width||this.glContext.canvas.height!==m.height)&&(this.glContext.canvas.width=m.width,this.glContext.canvas.height=m.height),n!=0)if(n>0){const U=$.fromStr(r).addFrames(1,this.streamData.fps),L=(y=this.renderDataMap.get($.toStr(U)))==null?void 0:y.placeholders;L&&Object.keys(L).forEach(A=>{A in u&&(u[A].tranform=u[A].tranform.map((P,W)=>P*(1-n)+L[A].tranform[W]*n))})}else{const U=Math.abs(n),L=$.fromStr(r).subtractFrames(1,this.streamData.fps),A=(D=this.renderDataMap.get($.toStr(L)))==null?void 0:D.placeholders;A&&Object.keys(A).forEach(P=>{P in u&&(u[P].tranform=u[P].tranform.map((W,Z)=>A[P].tranform[Z]*(1-U)+W*U))})}if(this.options&&g(this.options,"Renderer")&&console.log(\`[Renderer] Render logic: binding texture for \${r}\`),O.setAttributes({last_rendered_frame:r,renderer_state:this.state}),this.updateStatusOverlay(),this.webgl.drawAugmentationWithLED(f,u,m,this.opacity,o.led,this.options.DRAW_TIMESTAMP_WEBGL?r:void 0),this.options&&((w=this.options.debug)!=null&&w.trackPerformance)){const U=performance.now();U-this.lastPerformanceCheck>=this.options.PERFORMANCE_TRACKING_INTERVAL&&(this.trackPerformance(),this.lastPerformanceCheck=U)}}},this.handleRenderClear=()=>{this.rendererStopped||(console.log("handleRenderClear"),this.opacity=0,this.state="OFF")},this.getAdURLByCoord=r=>{var c,d;if(!this.ads||!this.streamData||!this.streamData.timeCode||!this.renderDataMap)return null;const n=this.streamData.timeCode,o=(c=this.renderDataMap.get(n))==null?void 0:c.placeholders,i=(d=this.renderDataMap.get(n))==null?void 0:d.processingSize;if(!o||!i)return null;console.log("placeholders: ",o);const a=this.ads.getAdURLAtCoord(o,i,r);return console.log("url: ",a),a},this.deleteTexture=r=>{var o;const n=(o=this.renderDataMap.get(r))==null?void 0:o.alphaMask;n&&(this.webgl.deleteTexture(n),this.renderDataMap.delete(r))},this.deleteOldTextures=r=>{if(!this.streamData)return;const n=59.94,o=$.fromStr(r).totalMilliseconds(n);this.renderDataMap.forEach((i,a)=>{$.fromStr(a).totalMilliseconds(n)<o-100&&(this.options&&g(this.options,"Renderer")&&console.log(\`[Renderer] Deleting old texture for timeCode=\${a}\`),this.webgl.deleteTexture(i.alphaMask),this.renderDataMap.delete(a))})},this.deleteAllTextures=()=>{this.renderDataMap.forEach((r,n)=>{this.webgl.deleteTexture(r.alphaMask),this.renderDataMap.delete(n)})},this.cleanGL=()=>{this.webgl.cleanGL()},this.updateStreamData=r=>{this.streamData=r,this.updateStatusOverlay()},this.finalizeShot=(r,n)=>{r.end=r.lastProcessingTime,r.duration=r.end-r.start,O.info("didEndDrawingAugmentationMedia",{timecode:n,adID:r.shotId,adURL:r.adURL}),r.avaragePercentOfAd=r.sumPercentOfAd/r.frameCount,r.avaragePercentOfScreen=r.sumPercentOfScreen/r.frameCount,O.info("didRegisterShot",{adID:r.shotId,adURL:r.adURL,avaragePercentOfScreen:r.avaragePercentOfScreen.toFixed(2),avaragePercentOfAd:r.avaragePercentOfAd.toFixed(2),frameCount:r.frameCount,duration:r.duration.toFixed(0)}),this.shot=void 0},this.trackPerformance=()=>{const r=this.webgl.getAvgGPUFrameTime(),n=this.webgl.getAvgCPUFrameTime();Ra([{metric:"Rendering GPU time",value:r},{metric:"Rendering CPU time",value:n}],O.getMessagePort())},this.glContext=e,this.webgl=new is(this,s),this.options=s,this.ads=new as(this.webgl,s),this.rendererStopped=!1,this.webgl.init(),this.updateStatusOverlay()}isStopped(){return this.rendererStopped}setZipBufferStatus(e){this.zipBufferStatus=e,this.updateStatusOverlay()}updateStatusOverlay(){var c,d,l,f,u;const e=performance.now(),s=!this.statusInitialized;if(!s&&e-this.lastStatusUpdate<this.STATUS_UPDATE_INTERVAL)return;const r={ready:!!this.glContext&&!this.glContext.isContextLost()&&!!this.webgl,issue:(c=this.glContext)!=null&&c.isContextLost()?"Context Lost":""},n=(d=this.streamData)==null?void 0:d.timeCode,o=n?this.renderDataMap.get(n):void 0,i={stream_data:!!this.streamData,timecode:n||"",ads:!!((l=this.ads)!=null&&l.ads&&this.ads.ads.length>0),render_data:!!o,alpha_mask:!!(o!=null&&o.alphaMask),placeholders:!!(o!=null&&o.placeholders),processing_size:!!(o!=null&&o.processingSize),isLive:(o==null?void 0:o.isLive)||!1},a={web:((f=this.ottActions)==null?void 0:f.toggle.web)!==!1,local:((u=this.ottActions)==null?void 0:u.toggle.local)!==!1};(s||JSON.stringify(r)!==JSON.stringify(this.lastWebGLStatus)||this.state!==this.lastRenderState||JSON.stringify(i)!==JSON.stringify(this.lastDataStatus)||JSON.stringify(a)!==JSON.stringify(this.lastKillswitchStatus)||JSON.stringify(this.zipBufferStatus)!==JSON.stringify(this.lastZipBufferStatus))&&(O.setAttributes({webgl_status:r,renderer_state:this.state,data_status:i,killswitch_status:a,zip_buffer_status:this.zipBufferStatus}),this.lastWebGLStatus=r,this.lastRenderState=this.state,this.lastDataStatus=i,this.lastKillswitchStatus=a,this.lastZipBufferStatus=this.zipBufferStatus,this.lastStatusUpdate=e,this.statusInitialized=!0)}stop(){this.rendererStopped=!0,this.ads&&this.ads.pause(),this.cleanGL(),this.deleteAllTextures(),this.videoFrameTexture&&(this.webgl.deleteTexture(this.videoFrameTexture),this.videoFrameTexture=null)}}let ut=null,dt=null,ls=null,pe=null,ne=null,b=null,v,B,ft,us=0,ds=0,ht=null,mt,pt=null;self.onmessage=async t=>{var s,r,n,o,i,a,c,d,l,f,u,m,p,T,h;const{data:e}=t;if(e.type==="SET_LOGGER_PORT"&&(pe=e.port,O.setMessagePort(e.port)),e.type==="INIT_OFFSCREEN"){const _=e.offscreen;if(v=e.options,ne=_.getContext("webgl"),v&&g(v,"Renderer")&&console.log("[RendererWorker] Initializing OffscreenCanvas"),!ne||ne!=null&&ne.isContextLost()){O.error("[RendererWorker] Failed to acquire WebGL context"),v&&g(v,"Errors")&&console.error("[RendererWorker] Failed to acquire WebGL context");return}b=new cs(ne,v),v&&g(v,"Renderer")&&console.log("[RendererWorker] OffscreenCanvas initialized, gl context acquired"),pe?pe.postMessage({type:"RENDERER_READY"}):postMessage({type:"RENDERER_READY"}),(async()=>{var y,D,w,U;try{if(ht){const L=await createImageBitmap(ht);mt?(D=(y=b.ads)==null?void 0:y.overrideAdImageForPlaceholder)==null||D.call(y,L,mt):(w=b.ads)==null||w.overrideAdImage(L),ht=null,mt=void 0}if(pt){const L=await createImageBitmap(pt);(U=b.ads)==null||U.overrideLEDImage(L),pt=null}}catch(L){console.error("[RendererWorker] Failed to flush pending overrides",L)}})()}if(e.type==="SET_DOWNLOADER_PORT"&&(ut=e.port,ut.onmessage=xa),e.type==="SET_DECODER_PORT"&&(dt=e.port,dt.onmessage=ya),e.type==="SET_ADAPTER_PORT"&&(ls=e.port,ls.onmessage=Sa),(e.type==="RENDERER_DRAW"||e.type==="RENDERER_CLEAR")&&fs(e),e.type==="BURNED_FRAME_RENDER"&&va(e),e.type==="VIDEO_CLICK"&&b){const _=b.getAdURLByCoord(e.clickData);postMessage({type:"OPEN_URL",url:_})}if(e.type==="STOP_WORKER"){b&&b.stop();return}if(e.type==="RESTART_WORKER"){if(!ne||!v)return;b&&b.stop(),b=new cs(ne,v),pe?pe.postMessage({type:"RENDERER_READY"}):postMessage({type:"RENDERER_READY"});return}if(e.type==="RESET_ADS"){if(!b)return;try{v&&g(v,"Renderer")&&console.log("[RendererWorker] RESET_ADS - resuming auto-refresh"),(s=b.ads)==null||s.resumeAutoRefresh()}catch(_){v&&g(v,"Errors")&&console.error("[RendererWorker] RESET_ADS failed",_)}return}if(e.type==="SET_AD_IMAGE"){if(!b){try{(r=e.imageBitmap)==null||r.close()}catch{}return}try{e.placeholder?(o=(n=b.ads)==null?void 0:n.overrideAdImageForPlaceholder)==null||o.call(n,e.imageBitmap,e.placeholder):(i=b.ads)==null||i.overrideAdImage(e.imageBitmap)}catch{try{(a=e.imageBitmap)==null||a.close()}catch{}}return}if(e.type==="SET_LED_IMAGE"){if(!b){try{(c=e.imageBitmap)==null||c.close()}catch{}return}try{(d=b.ads)==null||d.overrideLEDImage(e.imageBitmap)}catch{try{(l=e.imageBitmap)==null||l.close()}catch{}}return}if(e.type==="SET_AD_BLOB"){if(!b){ht=e.blob,mt=e.placeholder;return}try{v&&g(v,"Renderer")&&console.log("[RendererWorker] SET_AD_BLOB size",(f=e.blob)==null?void 0:f.size);const _=new Blob([await e.blob.arrayBuffer()],{type:e.blob.type||"image/png"}),y=await createImageBitmap(_);e.placeholder?(m=(u=b.ads)==null?void 0:u.overrideAdImageForPlaceholder)==null||m.call(u,y,e.placeholder):(p=b.ads)==null||p.overrideAdImage(y)}catch(_){v&&g(v,"Errors")&&console.error("[RendererWorker] SET_AD_BLOB failed",_)}return}if(e.type==="SET_LED_BLOB"){if(!b){pt=e.blob;return}try{v&&g(v,"Renderer")&&console.log("[RendererWorker] SET_LED_BLOB size",(T=e.blob)==null?void 0:T.size);const _=new Blob([await e.blob.arrayBuffer()],{type:e.blob.type||"image/png"}),y=await createImageBitmap(_);(h=b.ads)==null||h.overrideLEDImage(y)}catch(_){v&&g(v,"Errors")&&console.error("[RendererWorker] SET_LED_BLOB failed",_)}return}};function _a(){!ut||!B||ut.postMessage({type:"DOWNLOADER_INPUT",streamData:B})}function ba(){!dt||!B||dt.postMessage({type:"DECODER_REQUEST",timeCode:B.timeCode,fps:B.fps})}function Ra(t,e){if(!pe&&!e)return;const s=pe||e,r={type:"TRACK_PERFORMANCE",data:t};s.postMessage(r)}function fs(t){!b||b.isStopped()||(B=t.streamData,b?(B&&(b.updateStreamData(B),B.ottActions&&(b.ottActions=B.ottActions)),b.cleanGL(),t.type==="RENDERER_CLEAR"&&b.handleRenderClear(),t.type==="RENDERER_DRAW"&&B&&(b.handleRenderDraw(B.timeCode,B.frameCorrection),b.deleteOldTextures(B.timeCode)),hs()):v&&g(v,"Errors")&&console.error("[RendererWorker] WebGL context is not initialized."))}function va(t){if(!b||b.isStopped()){t.imageBitmap.close();return}B=t.streamData,b?(b.updateStreamData(B),B.ottActions&&(b.ottActions=B.ottActions),b.cleanGL(),b.handleBurnedFrameRenderWithLED(t.imageBitmap,t.timecode),hs()):(t.imageBitmap.close(),v&&g(v,"Errors")&&console.error("[RendererWorker] WebGL context not initialized for burned frame"))}function hs(){if(!v)return;const t=performance.now();t-us>v.DOWNLOADER_UPDATE_FREQUENCY&&(_a(),us=t),t-ds>v.DECODER_UPDATE_FREQUENCY&&(ba(),ds=t)}function ya(t){if(!b||b.isStopped())return;const{data:e}=t;if(e.type==="RENDERER_INPUT"){const s=e.batch;v&&g(v,"Renderer")&&console.log(\`[RendererWorker] Received a batch of \${s.length} frames\`),b&&b.addMetadataBatch(s)}}function xa(t){const{data:e}=t;if(e.type==="ZIP_BUFFER_STATUS"){ft=e.status,b&&ft&&b.setZipBufferStatus(ft),v&&g(v,"Renderer")&&console.log("[RendererWorker] Zip buffer status:",ft);return}B&&v&&g(v,"Renderer")&&console.log("[RendererWorker] Message from Downloader:",t.data)}function Sa(t){const{data:e}=t;(e.type==="RENDERER_DRAW"||e.type==="RENDERER_CLEAR")&&fs(e)}self.onunhandledrejection=t=>{O.error("[RendererWorker] Unhandled rejection",{error:t.reason}),v&&(g(v,"Errors")&&console.error("[RendererWorker] Unhandled rejection:",t.reason),t.preventDefault())},self.onerror=t=>{O.error("[RendererWorker] Unhandled error",{error:t}),v&&(g(v,"Errors")&&console.error("[RendererWorker] Unhandled error:",t),t instanceof Event&&t.preventDefault())}})();
|
|
396
|
+
`,Vt=typeof self<"u"&&self.Blob&&new Blob([Gt],{type:"text/javascript;charset=utf-8"});function cn(t){let e;try{if(e=Vt&&(self.URL||self.webkitURL).createObjectURL(Vt),!e)throw"";const r=new Worker(e,{name:t==null?void 0:t.name});return r.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),r}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Gt),{name:t==null?void 0:t.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}const Ht='(function(){"use strict";const A=(e,t)=>t==="Errors"?!0:!e.debug||!e.debug.on?!1:e.debug[`log${t}`],jn=e=>Math.abs(e-59.94005994005994)<20?59.94:Math.abs(e-29.97002997002997)<10?29.97:Math.abs(e-14.985014985014985)<8?14.98:0,w={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},I=console,z={};Object.keys(w).forEach(e=>{z[e]=I[e]});const fe="Datadog Browser SDK:",_={debug:z.debug.bind(I,fe),log:z.log.bind(I,fe),info:z.info.bind(I,fe),warn:z.warn.bind(I,fe),error:z.error.bind(I,fe)},Je="https://docs.datadoghq.com",Lt=`${Je}/real_user_monitoring/browser/troubleshooting`,Ce="More details:";function At(e,t){return(...n)=>{try{return e(...n)}catch(r){_.error(t,r)}}}function Oe(e){return e!==0&&Math.random()*100<=e}function Wn(e){return zn(e)&&e>=0&&e<=100}function zn(e){return typeof e=="number"}const pe=1e3,H=60*pe,kt=60*H,Hn=365*(24*kt);function me(){return new Date().getTime()}function $(){return me()}function Re(){return performance.now()}function U(){return{relative:Re(),timeStamp:$()}}function Kn(){return{relative:0,timeStamp:It()}}function Vn(e,t){return t-e}function qn(e,t){return e+t}function Yn(e){return e-It()}let Ze;function It(){return Ze===void 0&&(Ze=performance.timing.navigationStart),Ze}const M=1024,Mt=1024*M,Xn=/[^\\u0000-\\u007F]/;function Qe(e){return Xn.test(e)?window.TextEncoder!==void 0?new TextEncoder().encode(e).length:new Blob([e]).size:e.length}function Jn(e){return{...e}}function Pt(e,t){return Object.keys(e).some(n=>e[n]===t)}function ge(e){return Object.keys(e).length===0}function B(){if(typeof globalThis=="object")return globalThis;Object.defineProperty(Object.prototype,"_dd_temp_",{get(){return this},configurable:!0});let e=_dd_temp_;return delete Object.prototype._dd_temp_,typeof e!="object"&&(typeof self=="object"?e=self:typeof window=="object"?e=window:e={}),e}function te(e,t){const n=B();let r;return n.Zone&&typeof n.Zone.__symbol__=="function"&&(r=e[n.Zone.__symbol__(t)]),r||(r=e[t]),r}let xe,Dt=!1;function Zn(e){xe=e}function Qn(e){Dt=e}function er(e,t,n){const r=n.value;n.value=function(...o){return(xe?b(r):r).apply(this,o)}}function b(e){return function(){return he(e,this,arguments)}}function he(e,t,n){try{return e.apply(t,n)}catch(r){tr(r)}}function tr(e){if(et(e),xe)try{xe(e)}catch(t){et(t)}}function et(...e){Dt&&_.error("[MONITOR]",...e)}function Se(e,t){return te(B(),"setTimeout")(b(e),t)}function Nt(e){te(B(),"clearTimeout")(e)}function tt(e,t){return te(B(),"setInterval")(b(e),t)}function Ft(e){te(B(),"clearInterval")(e)}class v{constructor(t){this.onFirstSubscribe=t,this.observers=[]}subscribe(t){return this.observers.push(t),this.observers.length===1&&this.onFirstSubscribe&&(this.onLastUnsubscribe=this.onFirstSubscribe(this)||void 0),{unsubscribe:()=>{this.observers=this.observers.filter(n=>t!==n),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}}notify(t){this.observers.forEach(n=>n(t))}}function $t(...e){return new v(t=>{const n=e.map(r=>r.subscribe(o=>t.notify(o)));return()=>n.forEach(r=>r.unsubscribe())})}function Ut(e,t,n){let r=!1,o,s;return{throttled:(...i)=>{if(r){o=i;return}e(...i),r=!0,s=Se(()=>{o&&e(...o),r=!1,o=void 0},t)},cancel:()=>{Nt(s),r=!1,o=void 0}}}function G(){}function j(e){return e?(parseInt(e,10)^Math.random()*16>>parseInt(e,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,j)}const Le=/([\\w-]+)\\s*=\\s*([^;]+)/g;function nr(e,t){for(Le.lastIndex=0;;){const n=Le.exec(e);if(n){if(n[1]===t)return n[2]}else break}}function rr(e){const t=new Map;for(Le.lastIndex=0;;){const n=Le.exec(e);if(n)t.set(n[1],n[2]);else break}return t}function or(e,t,n=""){const r=e.charCodeAt(t-1),s=r>=55296&&r<=56319?t+1:t;return e.length<=s?e:`${e.slice(0,s)}${n}`}function sr(){return ir()===0}let Ae;function ir(){return Ae??(Ae=ar())}function ar(e=window){var t;const n=e.navigator.userAgent;return e.chrome||/HeadlessChrome/.test(n)?0:((t=e.navigator.vendor)===null||t===void 0?void 0:t.indexOf("Apple"))===0||/safari/i.test(n)&&!/chrome|android/i.test(n)?1:2}function ye(e,t,n=0,r){const o=new Date;o.setTime(o.getTime()+n);const s=`expires=${o.toUTCString()}`,i=r&&r.crossSite?"none":"strict",a=r&&r.domain?`;domain=${r.domain}`:"",c=r&&r.secure?";secure":"",l=r&&r.partitioned?";partitioned":"";document.cookie=`${e}=${t};${s};path=/;samesite=${i}${a}${c}${l}`}function nt(e){return nr(document.cookie,e)}let rt;function K(e){return rt||(rt=rr(document.cookie)),rt.get(e)}function Bt(e,t){ye(e,"",0,t)}function cr(e){if(document.cookie===void 0||document.cookie===null)return!1;try{const t=`dd_cookie_test_${j()}`,n="test";ye(t,n,H,e);const r=nt(t)===n;return Bt(t,e),r}catch(t){return _.error(t),!1}}let ot;function ur(){if(ot===void 0){const e=`dd_site_test_${j()}`,t="test",n=window.location.hostname.split(".");let r=n.pop();for(;n.length&&!nt(e);)r=`${n.pop()}.${r}`,ye(e,t,pe,{domain:r});Bt(e,{domain:r}),ot=r}return ot}const ne="_dd_s";function ke(e){return Object.values(e)}function lr(e){return Object.entries(e)}const st=4*kt,Gt=15*H,dr=Hn,be={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},jt=/^([a-zA-Z]+)=([a-z0-9-]+)$/,it="&";function fr(e){return!!e&&(e.indexOf(it)!==-1||jt.test(e))}const pr="1";function V(e,t){const n={isExpired:pr};return t.trackAnonymousUser&&(e!=null&&e.anonymousId?n.anonymousId=e==null?void 0:e.anonymousId:n.anonymousId=j()),n}function Ie(e){return ge(e)}function Wt(e){return!Ie(e)}function Me(e){return e.isExpired!==void 0||!mr(e)}function mr(e){return(e.created===void 0||me()-Number(e.created)<st)&&(e.expire===void 0||me()<Number(e.expire))}function zt(e){e.expire=String(me()+Gt)}function at(e){return lr(e).map(([t,n])=>t==="anonymousId"?`aid=${n}`:`${t}=${n}`).join(it)}function Ht(e){const t={};return fr(e)&&e.split(it).forEach(n=>{const r=jt.exec(n);if(r!==null){const[,o,s]=r;o==="aid"?t.anonymousId=s:t[o]=s}}),t}const gr="_dd",hr="_dd_r",Sr="_dd_l",yr="rum",br="logs";function Er(e){if(!K(ne)){const n=K(gr),r=K(hr),o=K(Sr),s={};n&&(s.id=n),o&&/^[01]$/.test(o)&&(s[br]=o),r&&/^[012]$/.test(r)&&(s[yr]=r),Wt(s)&&(zt(s),e.persistSession(s))}}function Kt(e){const t=Cr(e);return cr(t)?{type:be.COOKIE,cookieOptions:t}:void 0}function Tr(e,t){const n={isLockEnabled:sr(),persistSession:wr(t),retrieveSession:vr,expireSession:r=>_r(t,r,e)};return Er(n),n}function wr(e){return t=>{ye(ne,at(t),Gt,e)}}function _r(e,t,n){const r=V(t,n);ye(ne,at(r),n.trackAnonymousUser?dr:st,e)}function vr(){const e=nt(ne);return Ht(e)}function Cr(e){const t={};return t.secure=!!e.useSecureSessionCookie||!!e.usePartitionedCrossSiteSessionCookie,t.crossSite=!!e.usePartitionedCrossSiteSessionCookie,t.partitioned=!!e.usePartitionedCrossSiteSessionCookie,e.trackSessionAcrossSubdomains&&(t.domain=ur()),t}const Or="_dd_test_";function Vt(){try{const e=j(),t=`${Or}${e}`;localStorage.setItem(t,e);const n=localStorage.getItem(t);return localStorage.removeItem(t),e===n?{type:be.LOCAL_STORAGE}:void 0}catch{return}}function Rr(e){return{isLockEnabled:!1,persistSession:qt,retrieveSession:xr,expireSession:t=>Lr(t,e)}}function qt(e){localStorage.setItem(ne,at(e))}function xr(){const e=localStorage.getItem(ne);return Ht(e)}function Lr(e,t){qt(V(e,t))}const Ar=10,kr=100,Yt=[];let Pe;function q(e,t,n=0){var r;const{isLockEnabled:o,persistSession:s,expireSession:i}=t,a=f=>s({...f,lock:l}),c=()=>{const f=t.retrieveSession(),h=f.lock;return f.lock&&delete f.lock,{session:f,lock:h}};if(Pe||(Pe=e),e!==Pe){Yt.push(e);return}if(o&&n>=kr){Xt(t);return}let l,u=c();if(o){if(u.lock){De(e,t,n);return}if(l=j(),a(u.session),u=c(),u.lock!==l){De(e,t,n);return}}let d=e.process(u.session);if(o&&(u=c(),u.lock!==l)){De(e,t,n);return}if(d&&(Me(d)?i(d):(zt(d),o?a(d):s(d))),o&&!(d&&Me(d))){if(u=c(),u.lock!==l){De(e,t,n);return}s(u.session),d=u.session}(r=e.after)===null||r===void 0||r.call(e,d||u.session),Xt(t)}function De(e,t,n){Se(()=>{q(e,t,n+1)},Ar)}function Xt(e){Pe=void 0;const t=Yt.shift();t&&q(t,e)}const Jt=pe;function Ir(e){switch(e.sessionPersistence){case be.COOKIE:return Kt(e);case be.LOCAL_STORAGE:return Vt();case void 0:{let t=Kt(e);return!t&&e.allowFallbackToLocalStorage&&(t=Vt()),t}default:_.error(`Invalid session persistence \'${String(e.sessionPersistence)}\'`)}}function Mr(e,t,n,r){const o=new v,s=new v,i=new v,a=e.type===be.COOKIE?Tr(t,e.cookieOptions):Rr(t),{expireSession:c}=a,l=tt(g,Jt);let u;p();const{throttled:d,cancel:f}=Ut(()=>{q({process:y=>{if(Ie(y))return;const de=E(y);return O(de),de},after:y=>{Wt(y)&&!R()&&Bn(y),u=y}},a)},Jt);function h(){q({process:y=>R()?E(y):void 0},a)}function g(){q({process:y=>Me(y)?V(y,t):void 0,after:E},a)}function E(y){return Me(y)&&(y=V(y,t)),R()&&(F(y)?le():(i.notify({previousState:u,newState:y}),u=y)),y}function p(){q({process:y=>{if(Ie(y))return V(y,t)},after:y=>{u=y}},a)}function O(y){if(Ie(y))return!1;const{trackingType:de,isTracked:Gi}=r(y[n]);y[n]=de,delete y.isExpired,Gi&&!y.id&&(y.id=j(),y.created=String(me()))}function R(){return u[n]!==void 0}function F(y){return u.id!==y.id||u[n]!==y[n]}function le(){u=V(u,t),s.notify()}function Bn(y){u=y,o.notify()}function Gn(y){q({process:de=>({...de,...y}),after:E},a)}return{expandOrRenewSession:d,expandSession:h,getSession:()=>u,renewObservable:o,expireObservable:s,sessionStateUpdateObservable:i,restartSession:p,expire:()=>{f(),c(u),E(V(u,t))},stop:()=>{Ft(l)},updateSessionState:Gn}}const ct={GRANTED:"granted",NOT_GRANTED:"not-granted"};function Pr(e){const t=new v;return{tryToInit(n){e||(e=n)},update(n){e=n,t.notify()},isGranted(){return e===ct.GRANTED},observable:t}}function Y(e,t,n){if(typeof e!="object"||e===null)return JSON.stringify(e);const r=re(Object.prototype),o=re(Array.prototype),s=re(Object.getPrototypeOf(e)),i=re(e);try{return JSON.stringify(e,t,n)}catch{return"<error: unable to serialize object>"}finally{r(),o(),s(),i()}}function re(e){const t=e,n=t.toJSON;return n?(delete t.toJSON,()=>{t.toJSON=n}):G}function ut(e){return Dr(e,location.href).href}function Dr(e,t){const n=Nr();if(n)try{return t!==void 0?new n(e,t):new n(e)}catch(s){throw new Error(`Failed to construct URL: ${String(s)} ${Y({url:e,base:t})}`)}if(t===void 0&&!/:/.test(e))throw new Error(`Invalid URL: \'${e}\'`);let r=document;const o=r.createElement("a");if(t!==void 0){r=document.implementation.createHTMLDocument("");const s=r.createElement("base");s.href=t,r.head.appendChild(s),r.body.appendChild(o)}return o.href=e,o}const Zt=URL;let Ne;function Nr(){if(Ne===void 0)try{Ne=new Zt("http://test/path").href==="http://test/path"}catch{Ne=!1}return Ne?Zt:void 0}const Fr="datad0g.com",$r="dd0g-gov.com",oe="datadoghq.com",Ur="ddog-gov.com",Br="pci.browser-intake-datadoghq.com",Gr=["ddsource","ddtags"];function Ee(e,t,n){const r=jr(e,t);return{build(o,s){const i=zr(e,t,n,o,s);return r(i)},urlPrefix:r(""),trackType:t}}function jr(e,t){const n=`/api/v2/${t}`,r=e.proxy;if(typeof r=="string"){const s=ut(r);return i=>`${s}?ddforward=${encodeURIComponent(`${n}?${i}`)}`}if(typeof r=="function")return s=>r({path:n,parameters:s});const o=Wr(t,e);return s=>`https://${o}${n}?${s}`}function Wr(e,t){const{site:n=oe,internalAnalyticsSubdomain:r}=t;if(e==="logs"&&t.usePciIntake&&n===oe)return Br;if(r&&n===oe)return`${r}.${oe}`;if(n===$r)return`http-intake.logs.${n}`;const o=n.split("."),s=o.pop();return`browser-intake-${o.join("-")}.${s}`}function zr({clientToken:e,internalAnalyticsSubdomain:t},n,r,o,{retry:s,encoding:i}){const a=["sdk_version:6.5.0",`api:${o}`].concat(r);s&&a.push(`retry_count:${s.count}`,`retry_after:${s.lastFailureStatus}`);const c=["ddsource=browser",`ddtags=${encodeURIComponent(a.join(","))}`,`dd-api-key=${e}`,`dd-evp-origin-version=${encodeURIComponent("6.5.0")}`,"dd-evp-origin=browser",`dd-request-id=${j()}`];return i&&c.push(`dd-evp-encoding=${i}`),n==="rum"&&c.push(`batch_time=${$()}`),t&&c.reverse(),c.join("&")}const Hr=200;function Kr(e){const{env:t,service:n,version:r,datacenter:o}=e,s=[];return t&&s.push(Fe("env",t)),n&&s.push(Fe("service",n)),r&&s.push(Fe("version",r)),o&&s.push(Fe("datacenter",o)),s}function Fe(e,t){const n=Hr-e.length-1;(t.length>n||Vr(t))&&_.warn(`${e} value doesn\'t meet tag requirements and will be sanitized. ${Ce} ${Je}/getting_started/tagging/#defining-tags`);const r=t.replace(/,/g,"_");return`${e}:${r}`}function Vr(e){return qr()?new RegExp("[^\\\\p{Ll}\\\\p{Lo}0-9_:./-]","u").test(e):!1}function qr(){try{return new RegExp("[\\\\p{Ll}]","u"),!0}catch{return!1}}function Yr(e){const t=e.site||oe,n=Kr(e),r=Xr(e,n);return{replica:Jr(e,n),site:t,...r}}function Xr(e,t){return{logsEndpointBuilder:Ee(e,"logs",t),rumEndpointBuilder:Ee(e,"rum",t),sessionReplayEndpointBuilder:Ee(e,"replay",t)}}function Jr(e,t){if(!e.replica)return;const n={...e,site:oe,clientToken:e.replica.clientToken},r={logsEndpointBuilder:Ee(n,"logs",t),rumEndpointBuilder:Ee(n,"rum",t)};return{applicationId:e.replica.applicationId,...r}}function Zr(e){return Gr.every(t=>e.includes(t))}function lt(e,t){return e!=null&&typeof e!="string"?(_.error(`${t} must be defined as a string`),!1):!0}function Qr(e){return e&&typeof e=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(e)?(_.error(`Site should be a valid Datadog site. ${Ce} ${Je}/getting_started/site/.`),!1):!0}function $e(e,t){return e!==void 0&&!Wn(e)?(_.error(`${t} Sample Rate should be a number between 0 and 100`),!1):!0}function eo(e){var t,n,r,o,s,i;if(!e||!e.clientToken){_.error("Client Token is not configured, we will not send any data.");return}if(!(!Qr(e.site)||!$e(e.sessionSampleRate,"Session")||!$e(e.telemetrySampleRate,"Telemetry")||!$e(e.telemetryConfigurationSampleRate,"Telemetry Configuration")||!$e(e.telemetryUsageSampleRate,"Telemetry Usage")||!lt(e.version,"Version")||!lt(e.env,"Env")||!lt(e.service,"Service"))){if(e.trackingConsent!==void 0&&!Pt(ct,e.trackingConsent)){_.error(\'Tracking Consent should be either "granted" or "not-granted"\');return}return{beforeSend:e.beforeSend&&At(e.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:Ir(e),sessionSampleRate:(t=e.sessionSampleRate)!==null&&t!==void 0?t:100,telemetrySampleRate:(n=e.telemetrySampleRate)!==null&&n!==void 0?n:20,telemetryConfigurationSampleRate:(r=e.telemetryConfigurationSampleRate)!==null&&r!==void 0?r:5,telemetryUsageSampleRate:(o=e.telemetryUsageSampleRate)!==null&&o!==void 0?o:5,service:e.service||void 0,silentMultipleInit:!!e.silentMultipleInit,allowUntrustedEvents:!!e.allowUntrustedEvents,trackingConsent:(s=e.trackingConsent)!==null&&s!==void 0?s:ct.GRANTED,trackAnonymousUser:(i=e.trackAnonymousUser)!==null&&i!==void 0?i:!0,storeContextsAcrossPages:!!e.storeContextsAcrossPages,batchBytesLimit:16*M,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*pe,batchMessagesLimit:50,messageBytesLimit:256*M,...Yr(e)}}}function to(e){return{session_sample_rate:e.sessionSampleRate,telemetry_sample_rate:e.telemetrySampleRate,telemetry_configuration_sample_rate:e.telemetryConfigurationSampleRate,telemetry_usage_sample_rate:e.telemetryUsageSampleRate,use_before_send:!!e.beforeSend,use_partitioned_cross_site_session_cookie:e.usePartitionedCrossSiteSessionCookie,use_secure_session_cookie:e.useSecureSessionCookie,use_proxy:!!e.proxy,silent_multiple_init:e.silentMultipleInit,track_session_across_subdomains:e.trackSessionAcrossSubdomains,track_anonymous_user:e.trackAnonymousUser,session_persistence:e.sessionPersistence,allow_fallback_to_local_storage:!!e.allowFallbackToLocalStorage,store_contexts_across_pages:!!e.storeContextsAcrossPages,allow_untrusted_events:!!e.allowUntrustedEvents,tracking_consent:e.trackingConsent}}var dt;(function(e){e.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",e.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(dt||(dt={}));const Qt=new Set;function no(e){Array.isArray(e)&&ro(e.filter(t=>Pt(dt,t)))}function ro(e){e.forEach(t=>{Qt.add(t)})}function oo(){return Qt}const Te="?";function P(e){const t=[];let n=ft(e,"stack");const r=String(e);return n&&n.startsWith(r)&&(n=n.slice(r.length)),n&&n.split(`\n`).forEach(o=>{const s=ao(o)||uo(o)||fo(o)||go(o);s&&(!s.func&&s.line&&(s.func=Te),t.push(s))}),{message:ft(e,"message"),name:ft(e,"name"),stack:t}}const en="((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\\\w+\\\\.|\\\\/).*?)",se="(?::(\\\\d+))",so=new RegExp(`^\\\\s*at (.*?) ?\\\\(${en}${se}?${se}?\\\\)?\\\\s*$`,"i"),io=new RegExp(`\\\\((\\\\S*)${se}${se}\\\\)`);function ao(e){const t=so.exec(e);if(!t)return;const n=t[2]&&t[2].indexOf("native")===0,r=t[2]&&t[2].indexOf("eval")===0,o=io.exec(t[2]);return r&&o&&(t[2]=o[1],t[3]=o[2],t[4]=o[3]),{args:n?[t[2]]:[],column:t[4]?+t[4]:void 0,func:t[1]||Te,line:t[3]?+t[3]:void 0,url:n?void 0:t[2]}}const co=new RegExp(`^\\\\s*at ?${en}${se}?${se}??\\\\s*$`,"i");function uo(e){const t=co.exec(e);if(t)return{args:[],column:t[3]?+t[3]:void 0,func:Te,line:t[2]?+t[2]:void 0,url:t[1]}}const lo=/^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;function fo(e){const t=lo.exec(e);if(t)return{args:[],column:t[4]?+t[4]:void 0,func:t[1]||Te,line:+t[3],url:t[2]}}const po=/^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i,mo=/(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;function go(e){const t=po.exec(e);if(!t)return;const n=t[3]&&t[3].indexOf(" > eval")>-1,r=mo.exec(t[3]);return n&&r&&(t[3]=r[1],t[4]=r[2],t[5]=void 0),{args:t[2]?t[2].split(","):[],column:t[5]?+t[5]:void 0,func:t[1]||Te,line:t[4]?+t[4]:void 0,url:t[3]}}function ft(e,t){if(typeof e!="object"||!e||!(t in e))return;const n=e[t];return typeof n=="string"?n:void 0}function ho(e,t,n,r){const o=[{url:t,column:r,line:n}],{name:s,message:i}=yo(e);return{name:s,message:i,stack:o}}const So=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\\s\\S]*)$/;function yo(e){let t,n;return{}.toString.call(e)==="[object String]"&&([,t,n]=So.exec(e)),{name:t,message:n}}function Ue(e){const n=new Error(e);n.name="HandlingStack";let r;return he(()=>{const o=P(n);o.stack=o.stack.slice(2),r=X(o)}),r}function X(e){let t=tn(e);return e.stack.forEach(n=>{const r=n.func==="?"?"<anonymous>":n.func,o=n.args&&n.args.length>0?`(${n.args.join(", ")})`:"",s=n.line?`:${n.line}`:"",i=n.line&&n.column?`:${n.column}`:"";t+=`\n at ${r}${o} @ ${n.url}${s}${i}`}),t}function tn(e){return`${e.name||"Error"}: ${e.message}`}function J(e,t,n,{computeHandlingStack:r}={}){let o=e[t];if(typeof o!="function")if(t in e&&t.startsWith("on"))o=G;else return{stop:G};let s=!1;const i=function(){if(s)return o.apply(this,arguments);const a=Array.from(arguments);let c;he(n,null,[{target:this,parameters:a,onPostCall:u=>{c=u},handlingStack:r?Ue("instrumented method"):void 0}]);const l=o.apply(this,a);return c&&he(c,null,[l]),l};return e[t]=i,{stop:()=>{s=!0,e[t]===i&&(e[t]=o)}}}const bo=220*M,Eo="$",To=3;function D(e,t=bo){const n=re(Object.prototype),r=re(Array.prototype),o=[],s=new WeakMap,i=pt(e,Eo,void 0,o,s),a=JSON.stringify(i);let c=a?a.length:0;if(c>t){gt(t,"discarded",e);return}for(;o.length>0&&c<t;){const l=o.shift();let u=0;if(Array.isArray(l.source))for(let d=0;d<l.source.length;d++){const f=pt(l.source[d],l.path,d,o,s);if(f!==void 0?c+=JSON.stringify(f).length:c+=4,c+=u,u=1,c>t){gt(t,"truncated",e);break}l.target[d]=f}else for(const d in l.source)if(Object.prototype.hasOwnProperty.call(l.source,d)){const f=pt(l.source[d],l.path,d,o,s);if(f!==void 0&&(c+=JSON.stringify(f).length+u+d.length+To,u=1),c>t){gt(t,"truncated",e);break}l.target[d]=f}}return n(),r(),i}function pt(e,t,n,r,o){const s=vo(e);if(!s||typeof s!="object")return wo(s);const i=mt(s);if(i!=="[Object]"&&i!=="[Array]"&&i!=="[Error]")return i;const a=e;if(o.has(a))return`[Reference seen at ${o.get(a)}]`;const c=n!==void 0?`${t}.${n}`:t,l=Array.isArray(s)?[]:{};return o.set(a,c),r.push({source:s,target:l,path:c}),l}function wo(e){return typeof e=="bigint"?`[BigInt] ${e.toString()}`:typeof e=="function"?`[Function] ${e.name||"unknown"}`:typeof e=="symbol"?`[Symbol] ${e.description||e.toString()}`:e}function mt(e){try{if(e instanceof Event)return _o(e);if(e instanceof RegExp)return`[RegExp] ${e.toString()}`;const n=Object.prototype.toString.call(e).match(/\\[object (.*)\\]/);if(n&&n[1])return`[${n[1]}]`}catch{}return"[Unserializable]"}function _o(e){return{type:e.type,isTrusted:e.isTrusted,currentTarget:e.currentTarget?mt(e.currentTarget):null,target:e.target?mt(e.target):null}}function vo(e){const t=e;if(t&&typeof t.toJSON=="function")try{return t.toJSON()}catch{}return e}function gt(e,t,n){_.warn(`The data provided has been ${t} as it is over the limit of ${e} characters:`,n)}const nn="No stack, consider using an instance of Error";function rn({stackTrace:e,originalError:t,handlingStack:n,componentStack:r,startClocks:o,nonErrorPrefix:s,source:i,handling:a}){const c=W(t),l=Co(e,c,s,t),u=Oo(c,e)?X(e):nn,d=c?an(t,i):void 0,f=e?e.name:void 0,h=on(t),g=sn(t);return{startClocks:o,source:i,handling:a,handlingStack:n,componentStack:r,originalError:t,type:f,message:l,stack:u,causes:d,fingerprint:h,context:g}}function Co(e,t,n,r){return e!=null&&e.message&&(e!=null&&e.name)?e.message:t?"Empty message":`${n} ${Y(D(r))}`}function Oo(e,t){return t===void 0?!1:e?!0:t.stack.length>0&&(t.stack.length>1||t.stack[0].url!==void 0)}function on(e){return W(e)&&"dd_fingerprint"in e?String(e.dd_fingerprint):void 0}function sn(e){if(e!==null&&typeof e=="object"&&"dd_context"in e)return e.dd_context}function Ro(e){var t;return(t=/@ (.+)/.exec(e))===null||t===void 0?void 0:t[1]}function W(e){return e instanceof Error||Object.prototype.toString.call(e)==="[object Error]"}function an(e,t){let n=e;const r=[];for(;W(n==null?void 0:n.cause)&&r.length<10;){const o=P(n.cause);r.push({message:n.cause.message,source:t,type:o==null?void 0:o.name,stack:X(o)}),n=n.cause}return r.length?r:void 0}const x={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function xo(e){const t=(o,s)=>{const i=rn({stackTrace:o,originalError:s,startClocks:U(),nonErrorPrefix:"Uncaught",source:x.SOURCE,handling:"unhandled"});e.notify(i)},{stop:n}=Lo(t),{stop:r}=Ao(t);return{stop:()=>{n(),r()}}}function Lo(e){return J(window,"onerror",({parameters:[t,n,r,o,s]})=>{let i;W(s)?i=P(s):i=ho(t,n,r,o),e(i,s??t)})}function Ao(e){return J(window,"onunhandledrejection",({parameters:[t]})=>{const n=t.reason||"Empty reason",r=P(n);e(r,n)})}function ko(e){const t={version:"6.5.0",onReady(n){n()},...e};return Object.defineProperty(t,"_setDebug",{get(){return Qn},enumerable:!1}),t}function Io(e,t,n){const r=e[t];r&&!r.q&&r.version&&_.warn("SDK is loaded more than once. This is unsupported and might have unexpected behavior."),e[t]=n,r&&r.q&&r.q.forEach(o=>At(o,"onReady callback threw an error:")())}function cn(e,t){t.silentMultipleInit||_.error(`${e} is already initialized.`)}function Z(e,t,n,r,o){return ht(e,t,[n],r,o)}function ht(e,t,n,r,{once:o,capture:s,passive:i}={}){const a=b(f=>{!f.isTrusted&&!f.__ddIsTrusted&&!e.allowUntrustedEvents||(o&&d(),r(f))}),c=i?{capture:s,passive:i}:s,l=window.EventTarget&&t instanceof EventTarget?window.EventTarget.prototype:t,u=te(l,"addEventListener");n.forEach(f=>u.call(t,f,a,c));function d(){const f=te(l,"removeEventListener");n.forEach(h=>f.call(t,h,a,c))}return{stop:d}}const Be={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function Mo(e,t){const n=[];t.includes(Be.cspViolation)&&n.push(Do(e));const r=t.filter(o=>o!==Be.cspViolation);return r.length&&n.push(Po(r)),$t(...n)}function Po(e){return new v(t=>{if(!window.ReportingObserver)return;const n=b((o,s)=>o.forEach(i=>t.notify(No(i)))),r=new window.ReportingObserver(n,{types:e,buffered:!0});return r.observe(),()=>{r.disconnect()}})}function Do(e){return new v(t=>{const{stop:n}=Z(e,document,"securitypolicyviolation",r=>{t.notify(Fo(r))});return n})}function No(e){const{type:t,body:n}=e;return un({type:n.id,message:`${t}: ${n.message}`,originalError:e,stack:ln(n.id,n.message,n.sourceFile,n.lineNumber,n.columnNumber)})}function Fo(e){const t=`\'${e.blockedURI}\' blocked by \'${e.effectiveDirective}\' directive`;return un({type:e.effectiveDirective,message:`${Be.cspViolation}: ${t}`,originalError:e,csp:{disposition:e.disposition},stack:ln(e.effectiveDirective,e.originalPolicy?`${t} of the policy "${or(e.originalPolicy,100,"...")}"`:"no policy",e.sourceFile,e.lineNumber,e.columnNumber)})}function un(e){return{startClocks:U(),source:x.REPORT,handling:"unhandled",...e}}function ln(e,t,n,r,o){return n?X({name:e,message:t,stack:[{func:"?",url:n,line:r??void 0,column:o??void 0}]}):void 0}function dn(e,t){const n=window.__ddBrowserSdkExtensionCallback;n&&n({type:e,payload:t})}function fn(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Ge(e,t,n=$o()){if(t===void 0)return e;if(typeof t!="object"||t===null)return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=t.flags||[t.global?"g":"",t.ignoreCase?"i":"",t.multiline?"m":"",t.sticky?"y":"",t.unicode?"u":""].join("");return new RegExp(t.source,o)}if(n.hasAlreadyBeenSeen(t))return;if(Array.isArray(t)){const o=Array.isArray(e)?e:[];for(let s=0;s<t.length;++s)o[s]=Ge(o[s],t[s],n);return o}const r=fn(e)==="object"?e:{};for(const o in t)Object.prototype.hasOwnProperty.call(t,o)&&(r[o]=Ge(r[o],t[o],n));return r}function pn(e){return Ge(void 0,e)}function ie(...e){let t;for(const n of e)n!=null&&(t=Ge(t,n));return t}function $o(){if(typeof WeakSet<"u"){const t=new WeakSet;return{hasAlreadyBeenSeen(n){const r=t.has(n);return r||t.add(n),r}}}const e=[];return{hasAlreadyBeenSeen(t){const n=e.indexOf(t)>=0;return n||e.push(t),n}}}function Uo(){var e;const t=window.navigator;return{status:t.onLine?"connected":"not_connected",interfaces:t.connection&&t.connection.type?[t.connection.type]:void 0,effective_type:(e=t.connection)===null||e===void 0?void 0:e.effectiveType}}function Bo(e){const t=new Set;return e.forEach(n=>t.add(n)),Array.from(t)}function mn(e,t){const n=e.indexOf(t);n>=0&&e.splice(n,1)}const Go=500;function gn(){const e=[];return{add:o=>{e.push(o)>Go&&e.splice(0,1)},remove:o=>{mn(e,o)},drain:o=>{e.forEach(s=>s(o)),e.length=0}}}const Q={log:"log",configuration:"configuration",usage:"usage"},jo=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],Wo=[Ur];let hn=gn(),ae=e=>{hn.add(()=>ae(e))};function zo(e,t){let n;const r=new v,o=new Set,s=!Wo.includes(t.site)&&Oe(t.telemetrySampleRate),i={[Q.log]:s,[Q.configuration]:s&&Oe(t.telemetryConfigurationSampleRate),[Q.usage]:s&&Oe(t.telemetryUsageSampleRate)},a=Ho();ae=l=>{const u=Y(l);if(i[l.type]&&o.size<t.maxTelemetryEventsPerPage&&!o.has(u)){const d=c(e,l,a);r.notify(d),dn("telemetry",d),o.add(u)}},Zn(yn);function c(l,u,d){return ie({type:"telemetry",date:$(),service:l,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:ie(u,{runtime_env:d,connectivity:Uo(),sdk_setup:"npm"}),experimental_features:Array.from(oo())},n!==void 0?n():{})}return{setContextProvider:l=>{n=l},observable:r,enabled:s}}function Ho(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function Ko(){hn.drain()}function Vo(e){return e.site===Fr}function Sn(e,t){et(w.debug,e,t),ae({type:Q.log,message:e,status:"debug",...t})}function yn(e,t){ae({type:Q.log,status:"error",...Xo(e),...t})}function qo(e){ae({type:Q.configuration,configuration:e})}function Yo(e){ae({type:Q.usage,usage:e})}function Xo(e){if(W(e)){const t=P(e);return{error:{kind:t.name,stack:X(Jo(t))},message:t.message}}return{error:{stack:nn},message:`Uncaught ${Y(e)}`}}function Jo(e){return e.stack=e.stack.filter(t=>!t.url||jo.some(n=>t.url.startsWith(n))),e}const we=1/0,Zo=H;let _e=null;const je=new Set;function Qo(){je.forEach(e=>e())}function es({expireDelay:e,maxEntries:t}){let n=[];const r=[];_e||(_e=tt(()=>Qo(),Zo));const o=()=>{const h=Re()-e;for(;n.length>0&&n[n.length-1].endTime<h;){const g=n.pop();g&&r.push(g.startTime)}};je.add(o);function s(h,g){const E={value:h,startTime:g,endTime:we,remove:()=>{mn(n,E)},close:p=>{E.endTime=p}};return t&&n.length>=t&&n.pop(),n.unshift(E),E}function i(h=we,g={returnInactive:!1}){for(const E of n)if(E.startTime<=h){if(g.returnInactive||h<=E.endTime)return E.value;break}}function a(h){const g=n[0];g&&g.endTime===we&&g.close(h)}function c(h=we,g=0){const E=qn(h,g);return n.filter(p=>p.startTime<=E&&h<=p.endTime).map(p=>p.value)}function l(){return n.map(({startTime:h,endTime:g,value:E})=>({startTime:h,endTime:g===we?"Infinity":g,value:E}))}function u(){return r}function d(){n=[]}function f(){je.delete(o),je.size===0&&_e&&(Ft(_e),_e=null)}return{add:s,find:i,closeActive:a,findAll:c,reset:d,stop:f,getAllEntries:l,getDeletedEntries:u}}const ts=H,ns=st;function rs(e,t,n,r){const o=new v,s=new v,i=Mr(e.sessionStoreStrategyType,e,t,n),a=es({expireDelay:ns});i.renewObservable.subscribe(()=>{a.add(c(),Re()),o.notify()}),i.expireObservable.subscribe(()=>{s.notify(),a.closeActive(Re())}),i.expandOrRenewSession(),a.add(c(),Kn().relative),r.observable.subscribe(()=>{r.isGranted()?i.expandOrRenewSession():i.expire()}),os(e,()=>{r.isGranted()&&i.expandOrRenewSession()}),ss(e,()=>i.expandSession()),is(e,()=>i.restartSession());function c(){return{id:i.getSession().id,trackingType:i.getSession()[t],isReplayForced:!!i.getSession().forcedReplay,anonymousId:i.getSession().anonymousId}}return{findSession:(l,u)=>a.find(l,u),renewObservable:o,expireObservable:s,sessionStateUpdateObservable:i.sessionStateUpdateObservable,expire:i.expire,updateSessionState:i.updateSessionState}}function os(e,t){ht(e,window,["click","touchstart","keydown","scroll"],t,{capture:!0,passive:!0})}function ss(e,t){const n=()=>{document.visibilityState==="visible"&&t()};Z(e,document,"visibilitychange",n),tt(n,ts)}function is(e,t){Z(e,window,"resume",t,{capture:!0})}function bn(e){return e>=500}function as(e){try{return e.clone()}catch{return}}const cs=80*M,us=32,En=3*Mt,ls=H,Tn=pe;function wn(e,t,n,r,o){t.transportStatus===0&&t.queuedPayloads.size()===0&&t.bandwidthMonitor.canHandle(e)?vn(e,t,n,{onSuccess:()=>Cn(0,t,n,r,o),onFailure:()=>{t.queuedPayloads.enqueue(e),_n(t,n,r,o)}}):t.queuedPayloads.enqueue(e)}function _n(e,t,n,r){e.transportStatus===2&&Se(()=>{const o=e.queuedPayloads.first();vn(o,e,t,{onSuccess:()=>{e.queuedPayloads.dequeue(),e.currentBackoffTime=Tn,Cn(1,e,t,n,r)},onFailure:()=>{e.currentBackoffTime=Math.min(ls,e.currentBackoffTime*2),_n(e,t,n,r)}})},e.currentBackoffTime)}function vn(e,t,n,{onSuccess:r,onFailure:o}){t.bandwidthMonitor.add(e),n(e,s=>{t.bandwidthMonitor.remove(e),ds(s)?(t.transportStatus=t.bandwidthMonitor.ongoingRequestCount>0?1:2,e.retry={count:e.retry?e.retry.count+1:1,lastFailureStatus:s.status},o()):(t.transportStatus=0,r())})}function Cn(e,t,n,r,o){e===0&&t.queuedPayloads.isFull()&&!t.queueFullReported&&(o({message:`Reached max ${r} events size queued for upload: ${En/Mt}MiB`,source:x.AGENT,startClocks:U()}),t.queueFullReported=!0);const s=t.queuedPayloads;for(t.queuedPayloads=On();s.size()>0;)wn(s.dequeue(),t,n,r,o)}function ds(e){return e.type!=="opaque"&&(e.status===0&&!navigator.onLine||e.status===408||e.status===429||bn(e.status))}function fs(){return{transportStatus:0,currentBackoffTime:Tn,bandwidthMonitor:ps(),queuedPayloads:On(),queueFullReported:!1}}function On(){const e=[];return{bytesCount:0,enqueue(t){this.isFull()||(e.push(t),this.bytesCount+=t.bytesCount)},first(){return e[0]},dequeue(){const t=e.shift();return t&&(this.bytesCount-=t.bytesCount),t},size(){return e.length},isFull(){return this.bytesCount>=En}}}function ps(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(e){return this.ongoingRequestCount===0||this.ongoingByteCount+e.bytesCount<=cs&&this.ongoingRequestCount<us},add(e){this.ongoingRequestCount+=1,this.ongoingByteCount+=e.bytesCount},remove(e){this.ongoingRequestCount-=1,this.ongoingByteCount-=e.bytesCount}}}function ms(e,t,n){const r=fs(),o=(s,i)=>Ss(e,t,s,i);return{send:s=>{wn(s,r,o,e.trackType,n)},sendOnExit:s=>{gs(e,t,s)}}}function gs(e,t,n){if(!!navigator.sendBeacon&&n.bytesCount<t)try{const s=e.build("beacon",n);if(navigator.sendBeacon(s,n.data))return}catch(s){hs(s)}const o=e.build("xhr",n);St(o,n.data)}let Rn=!1;function hs(e){Rn||(Rn=!0,yn(e))}function Ss(e,t,n,r){if(ys()&&n.bytesCount<t){const s=e.build("fetch",n);fetch(s,{method:"POST",body:n.data,keepalive:!0,mode:"cors"}).then(b(i=>r==null?void 0:r({status:i.status,type:i.type})),b(()=>{const i=e.build("xhr",n);St(i,n.data,r)}))}else{const s=e.build("xhr",n);St(s,n.data,r)}}function ys(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function St(e,t,n){const r=new XMLHttpRequest;r.open("POST",e,!0),t instanceof Blob&&r.setRequestHeader("Content-Type",t.type),Z({allowUntrustedEvents:!0},r,"loadend",()=>{n==null||n({status:r.status})},{once:!0}),r.send(t)}function yt(){const e=bs();if(e)return{getCapabilities(){var t;return JSON.parse(((t=e.getCapabilities)===null||t===void 0?void 0:t.call(e))||"[]")},getPrivacyLevel(){var t;return(t=e.getPrivacyLevel)===null||t===void 0?void 0:t.call(e)},getAllowedWebViewHosts(){return JSON.parse(e.getAllowedWebViewHosts())},send(t,n,r){const o=r?{id:r}:void 0;e.send(JSON.stringify({eventType:t,event:n,view:o}))}}}function We(e){var t;e===void 0&&(e=(t=B().location)===null||t===void 0?void 0:t.hostname);const n=yt();return!!n&&n.getAllowedWebViewHosts().some(r=>e===r||e.endsWith(`.${r}`))}function bs(){return B().DatadogEventBridge}const ze={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function Es(e){return new v(t=>{const{stop:n}=ht(e,window,["visibilitychange","freeze"],o=>{o.type==="visibilitychange"&&document.visibilityState==="hidden"?t.notify({reason:ze.HIDDEN}):o.type==="freeze"&&t.notify({reason:ze.FROZEN})},{capture:!0}),r=Z(e,window,"beforeunload",()=>{t.notify({reason:ze.UNLOADING})}).stop;return()=>{n(),r()}})}function Ts(e){return ke(ze).includes(e)}function ws({encoder:e,request:t,flushController:n,messageBytesLimit:r}){let o={};const s=n.flushObservable.subscribe(d=>u(d));function i(d,f,h){n.notifyBeforeAddMessage(f),h!==void 0?(o[h]=d,n.notifyAfterAddMessage()):e.write(e.isEmpty?d:`\n${d}`,g=>{n.notifyAfterAddMessage(g-f)})}function a(d){return d!==void 0&&o[d]!==void 0}function c(d){const f=o[d];delete o[d];const h=e.estimateEncodedBytesCount(f);n.notifyAfterRemoveMessage(h)}function l(d,f){const h=Y(d),g=e.estimateEncodedBytesCount(h);if(g>=r){_.warn(`Discarded a message whose size was bigger than the maximum allowed size ${r}KB. ${Ce} ${Lt}/#technical-limitations`);return}a(f)&&c(f),i(h,g,f)}function u(d){const f=ke(o).join(`\n`);o={};const h=Ts(d.reason),g=h?t.sendOnExit:t.send;if(h&&e.isAsync){const E=e.finishSync();E.outputBytesCount&&g(xn(E));const p=[E.pendingData,f].filter(Boolean).join(`\n`);p&&g({data:p,bytesCount:Qe(p)})}else f&&e.write(e.isEmpty?f:`\n${f}`),e.finish(E=>{g(xn(E))})}return{flushController:n,add:l,upsert:l,stop:s.unsubscribe}}function xn(e){let t;return typeof e.output=="string"?t=e.output:t=new Blob([e.output],{type:"text/plain"}),{data:t,bytesCount:e.outputBytesCount,encoding:e.encoding}}function _s({messagesLimit:e,bytesLimit:t,durationLimit:n,pageExitObservable:r,sessionExpireObservable:o}){const s=r.subscribe(g=>u(g.reason)),i=o.subscribe(()=>u("session_expire")),a=new v(()=>()=>{s.unsubscribe(),i.unsubscribe()});let c=0,l=0;function u(g){if(l===0)return;const E=l,p=c;l=0,c=0,h(),a.notify({reason:g,messagesCount:E,bytesCount:p})}let d;function f(){d===void 0&&(d=Se(()=>{u("duration_limit")},n))}function h(){Nt(d),d=void 0}return{flushObservable:a,get messagesCount(){return l},notifyBeforeAddMessage(g){c+g>=t&&u("bytes_limit"),l+=1,c+=g,f()},notifyAfterAddMessage(g=0){c+=g,l>=e?u("messages_limit"):c>=t&&u("bytes_limit")},notifyAfterRemoveMessage(g){c-=g,l-=1,l===0&&h()}}}function Ln(e,t,n,r,o,s,i=ws){const a=l(e,t),c=n&&l(e,n);function l(u,{endpoint:d,encoder:f}){return i({encoder:f,request:ms(d,u.batchBytesLimit,r),flushController:_s({messagesLimit:u.batchMessagesLimit,bytesLimit:u.batchBytesLimit,durationLimit:u.flushTimeout,pageExitObservable:o,sessionExpireObservable:s}),messageBytesLimit:u.messageBytesLimit})}return{flushObservable:a.flushController.flushObservable,add(u,d=!0){a.add(u),c&&d&&c.add(n.transformMessage?n.transformMessage(u):u)},upsert:(u,d)=>{a.upsert(u,d),c&&c.upsert(n.transformMessage?n.transformMessage(u):u,d)},stop:()=>{a.stop(),c&&c.stop()}}}function He(){let e="",t=0;return{isAsync:!1,get isEmpty(){return!e},write(n,r){const o=Qe(n);t+=o,e+=n,r&&r(o)},finish(n){n(this.finishSync())},finishSync(){const n={output:e,outputBytesCount:t,rawBytesCount:t,pendingData:""};return e="",t=0,n},estimateEncodedBytesCount(n){return n.length}}}class vs{constructor(){this.callbacks={}}notify(t,n){const r=this.callbacks[t];r&&r.forEach(o=>o(n))}subscribe(t,n){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(n),{unsubscribe:()=>{this.callbacks[t]=this.callbacks[t].filter(r=>n!==r)}}}}function Cs(e,t,n){let r=0,o=!1;return{isLimitReached(){if(r===0&&Se(()=>{r=0},H),r+=1,r<=t||o)return o=!1,!1;if(r===t+1){o=!0;try{n({message:`Reached max number of ${e}s by minute: ${t}`,source:x.AGENT,startClocks:U()})}finally{o=!1}}return!0}}}let bt;const Et=new WeakMap;function Os(e){return bt||(bt=Rs(e)),bt}function Rs(e){return new v(t=>{const{stop:n}=J(XMLHttpRequest.prototype,"open",xs),{stop:r}=J(XMLHttpRequest.prototype,"send",s=>{Ls(s,e,t)},{computeHandlingStack:!0}),{stop:o}=J(XMLHttpRequest.prototype,"abort",As);return()=>{n(),r(),o()}})}function xs({target:e,parameters:[t,n]}){Et.set(e,{state:"open",method:String(t).toUpperCase(),url:ut(String(n))})}function Ls({target:e,handlingStack:t},n,r){const o=Et.get(e);if(!o)return;const s=o;s.state="start",s.startClocks=U(),s.isAborted=!1,s.xhr=e,s.handlingStack=t;let i=!1;const{stop:a}=J(e,"onreadystatechange",()=>{e.readyState===XMLHttpRequest.DONE&&c()}),c=()=>{if(l(),a(),i)return;i=!0;const u=o;u.state="complete",u.duration=Vn(s.startClocks.timeStamp,$()),u.status=e.status,r.notify(Jn(u))},{stop:l}=Z(n,e,"loadend",c);r.notify(s)}function As({target:e}){const t=Et.get(e);t&&(t.isAborted=!0)}let Tt;function An(){return Tt||(Tt=ks()),Tt}function ks(){return new v(e=>{if(!window.fetch)return;const{stop:t}=J(window,"fetch",n=>Is(n,e),{computeHandlingStack:!0});return t})}function Is({parameters:e,onPostCall:t,handlingStack:n},r){const[o,s]=e;let i=s&&s.method;i===void 0&&o instanceof Request&&(i=o.method);const a=i!==void 0?String(i).toUpperCase():"GET",c=o instanceof Request?o.url:ut(String(o)),l=U(),u={state:"start",init:s,input:o,method:a,startClocks:l,url:c,handlingStack:n};r.notify(u),e[0]=u.input,e[1]=u.init,t(d=>Ms(r,d,u))}function Ms(e,t,n){const r=n;function o(s){r.state="resolve",Object.assign(r,s),e.notify(r)}t.then(b(s=>{o({response:s,responseType:s.type,status:s.status,isAborted:!1})}),b(s=>{var i,a;o({status:0,isAborted:((a=(i=r.init)===null||i===void 0?void 0:i.signal)===null||a===void 0?void 0:a.aborted)||s instanceof DOMException&&s.code===DOMException.ABORT_ERR,error:s})}))}let wt={};function Ps(e){const t=e.map(n=>(wt[n]||(wt[n]=Ds(n)),wt[n]));return $t(...t)}function Ds(e){return new v(t=>{const n=I[e];return I[e]=(...r)=>{n.apply(console,r);const o=Ue("console error");he(()=>{t.notify(Ns(r,e,o))})},()=>{I[e]=n}})}function Ns(e,t,n){const r=e.map(s=>Fs(s)).join(" ");let o;if(t===w.error){const s=e.find(W);o={stack:s?X(P(s)):void 0,fingerprint:on(s),causes:s?an(s,"console"):void 0,startClocks:U(),message:r,source:x.CONSOLE,handling:"handled",handlingStack:n,context:sn(s)}}return{api:t,message:r,error:o,handlingStack:n}}function Fs(e){return typeof e=="string"?D(e):W(e)?tn(P(e)):Y(D(e),void 0,2)}function $s(e){const t=fn(e)==="object";return t||_.error("Unsupported context:",e),t}function _t(e,t,n){const r={...e};for(const[o,{required:s,type:i}]of Object.entries(t))i==="string"&&o in r&&(r[o]=String(r[o])),s&&!(o in e)&&_.warn(`The property ${o} of ${n} is required; context will not be sent to the intake.`);return r}function Ke(e="",{customerDataTracker:t,propertiesConfig:n={}}={}){let r={};const o=new v,s={getContext:()=>pn(r),setContext:i=>{$s(i)?(r=D(_t(i,n,e)),t==null||t.updateCustomerData(r)):s.clearContext(),o.notify()},setContextProperty:(i,a)=>{r=D(_t({...r,[i]:a},n,e)),t==null||t.updateCustomerData(r),o.notify()},removeContextProperty:i=>{delete r[i],t==null||t.updateCustomerData(r),_t(r,n,e),o.notify()},clearContext:()=>{r={},t==null||t.resetCustomerData(),o.notify()},changeObservable:o};return s}const Us="_dd_c",Bs=[];function vt(e,t,n,r){const o=Gs(n,r);Bs.push(Z(e,window,"storage",({key:l})=>{o===l&&i()})),t.changeObservable.subscribe(a);const s=ie(c(),t.getContext());ge(s)||t.setContext(s);function i(){t.setContext(c())}function a(){localStorage.setItem(o,JSON.stringify(t.getContext()))}function c(){const l=localStorage.getItem(o);return l?JSON.parse(l):{}}}function Gs(e,t){return`${Us}_${e}_${t}`}const js=3*M,Ws=16*M,zs=200;function Hs(e=2){const t=new Map;let n=!1;function r(o=0){if(n||e===0)return;const s=e===2?js:Ws;let i=o;t.forEach(a=>{i+=a.getBytesCount()}),i>s&&(Ks(s),n=!0)}return{createDetachedTracker:()=>{const o=kn(()=>r(o.getBytesCount()));return o},getOrCreateTracker:o=>(t.has(o)||t.set(o,kn(r)),t.get(o)),setCompressionStatus:o=>{e===0&&(e=o,r())},getCompressionStatus:()=>e,stop:()=>{t.forEach(o=>o.stop()),t.clear()}}}function kn(e){let t=0;const{throttled:n,cancel:r}=Ut(s=>{t=Qe(Y(s)),e()},zs),o=()=>{r(),t=0};return{updateCustomerData:s=>{ge(s)?o():n(s)},resetCustomerData:o,getBytesCount:()=>t,stop:()=>{r()}}}function Ks(e){_.warn(`Customer data exceeds the recommended ${e/M}KiB threshold. ${Ce} ${Lt}/#customer-data-exceeds-the-recommended-threshold-warning`)}function Vs(e,t,n){const r=e.getReader(),o=[];let s=0;i();function i(){r.read().then(b(c=>{if(c.done){a();return}o.push(c.value),s+=c.value.length,s>n.bytesLimit?a():i()}),b(c=>t(c)))}function a(){r.cancel().catch(G);let c,l;{let u;if(o.length===1)u=o[0];else{u=new Uint8Array(s);let d=0;o.forEach(f=>{u.set(f,d),d+=f.length})}c=u.slice(0,n.bytesLimit),l=u.length>n.bytesLimit}t(void 0,c,l)}}const qs="datadog-synthetics-public-id",Ys="datadog-synthetics-result-id",Xs="datadog-synthetics-injects-rum";function In(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||K(Xs))}function Js(){const e=window._DATADOG_SYNTHETICS_PUBLIC_ID||K(qs);return typeof e=="string"?e:void 0}function Zs(){const e=window._DATADOG_SYNTHETICS_RESULT_ID||K(Ys);return typeof e=="string"?e:void 0}function Ve(e,t,n){const r=n.getHandler(),o=Array.isArray(r)?r:[r];return Mn[e]>=Mn[n.getLevel()]&&o.includes(t)}const S={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},Mn={[S.ok]:0,[S.debug]:1,[S.info]:2,[S.notice]:4,[S.warn]:5,[S.error]:6,[S.critical]:7,[S.alert]:8,[S.emerg]:9};function qe(e,{includeMessage:t=!1}={}){return{stack:e.stack,kind:e.type,message:t?e.message:void 0,causes:e.causes,fingerprint:e.fingerprint,handling:e.handling}}var Qs=function(e,t,n,r){var o=arguments.length,s=o<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);return o>3&&s&&Object.defineProperty(t,n,s),s};const ve={console:"console",http:"http",silent:"silent"},ei=Object.keys(S);let k=class{constructor(t,n,r,o=ve.http,s=S.debug,i={}){this.handleLogStrategy=t,this.handlerType=o,this.level=s,this.contextManager=Ke("logger",{customerDataTracker:n}),this.contextManager.setContext(i),r&&this.contextManager.setContextProperty("logger",{name:r})}logImplementation(t,n,r=S.info,o,s){const i=D(n);let a;if(o!=null){const c=rn({stackTrace:W(o)?P(o):void 0,originalError:o,nonErrorPrefix:"Provided",source:x.LOGGER,handling:"handled",startClocks:U()});a=ie({error:qe(c,{includeMessage:!0})},i)}else a=i;this.handleLogStrategy({message:D(t),context:a,status:r},this,s)}log(t,n,r=S.info,o){let s;Ve(r,ve.http,this)&&(s=Ue("log")),this.logImplementation(t,n,r,o,s)}setContext(t){this.contextManager.setContext(t)}getContext(){return this.contextManager.getContext()}setContextProperty(t,n){this.contextManager.setContextProperty(t,n)}removeContextProperty(t){this.contextManager.removeContextProperty(t)}clearContext(){this.contextManager.clearContext()}setHandler(t){this.handlerType=t}getHandler(){return this.handlerType}setLevel(t){this.level=t}getLevel(){return this.level}};Qs([er],k.prototype,"logImplementation",null),k.prototype.ok=N(S.ok),k.prototype.debug=N(S.debug),k.prototype.info=N(S.info),k.prototype.notice=N(S.notice),k.prototype.warn=N(S.warn),k.prototype.error=N(S.error),k.prototype.critical=N(S.critical),k.prototype.alert=N(S.alert),k.prototype.emerg=N(S.emerg);function N(e){return function(t,n,r){let o;Ve(e,ve.http,this)&&(o=Ue("log")),this.logImplementation(t,n,e,r,o)}}function ti(e,t,n){return{view:{referrer:document.referrer,url:window.location.href},context:e.getContext(),user:t.getContext(),account:n.getContext()}}const ni=32*M;function ri(e){e.usePciIntake===!0&&e.site&&e.site!=="datadoghq.com"&&_.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");const t=eo(e),n=Pn(e.forwardConsoleLogs,ke(w),"Forward Console Logs"),r=Pn(e.forwardReports,ke(Be),"Forward Reports");if(!(!t||!n||!r))return e.forwardErrorsToLogs&&!n.includes(w.error)&&n.push(w.error),{forwardErrorsToLogs:e.forwardErrorsToLogs!==!1,forwardConsoleLogs:n,forwardReports:r,requestErrorResponseLengthLimit:ni,...t}}function Pn(e,t,n){if(e===void 0)return[];if(!(e==="all"||Array.isArray(e)&&e.every(r=>t.includes(r)))){_.error(`${n} should be "all" or an array with allowed values "${t.join(\'", "\')}"`);return}return e==="all"?t:Bo(e)}function oi(e){const t=to(e);return{forward_errors_to_logs:e.forwardErrorsToLogs,forward_console_logs:e.forwardConsoleLogs,forward_reports:e.forwardReports,use_pci_intake:e.usePciIntake,...t}}function si(e,t,n){const r=gn();let o,s;const i=t.observable.subscribe(a);function a(){if(!s||!o||!t.isGranted())return;i.unsubscribe();const c=n(o,s);r.drain(c)}return{init(c){if(!c){_.error("Missing configuration");return}if(no(c.enableExperimentalFeatures),We()&&(c=ii(c)),o=c,s){cn("DD_LOGS",c);return}const l=ri(c);l&&(s=l,An().subscribe(G),t.tryToInit(l.trackingConsent),a())},get initConfiguration(){return o},getInternalContext:G,handleLog(c,l,u,d=e(),f=$()){r.add(h=>h.handleLog(c,l,u,d,f))}}}function ii(e){return{...e,clientToken:"empty"}}const Ct="logs";function ai(e){const t=Hs(),n=Ke("global context",{customerDataTracker:t.getOrCreateTracker(2)}),r=Ke("user",{customerDataTracker:t.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),o=Ke("account",{customerDataTracker:t.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),s=Pr();function i(){return ti(n,r,o)}let a=si(i,s,(u,d)=>{u.storeContextsAcrossPages&&(vt(d,n,Ct,2),vt(d,r,Ct,1),vt(d,o,Ct,4));const f=e(u,d,i,s);return a=ci(u,f),f});const c={},l=new k((...u)=>a.handleLog(...u),t.createDetachedTracker());return ko({logger:l,init:b(u=>a.init(u)),setTrackingConsent:b(u=>{s.update(u),Yo({feature:"set-tracking-consent",tracking_consent:u})}),getGlobalContext:b(()=>n.getContext()),setGlobalContext:b(u=>n.setContext(u)),setGlobalContextProperty:b((u,d)=>n.setContextProperty(u,d)),removeGlobalContextProperty:b(u=>n.removeContextProperty(u)),clearGlobalContext:b(()=>n.clearContext()),createLogger:b((u,d={})=>(c[u]=new k((...f)=>a.handleLog(...f),t.createDetachedTracker(),D(u),d.handler,d.level,D(d.context)),c[u])),getLogger:b(u=>c[u]),getInitConfiguration:b(()=>pn(a.initConfiguration)),getInternalContext:b(u=>a.getInternalContext(u)),setUser:b(r.setContext),getUser:b(r.getContext),setUserProperty:b(r.setContextProperty),removeUserProperty:b(r.removeContextProperty),clearUser:b(r.clearContext),setAccount:b(o.setContext),getAccount:b(o.getContext),setAccountProperty:b(o.setContextProperty),removeAccountProperty:b(o.removeContextProperty),clearAccount:b(o.clearContext)})}function ci(e,t){return{init:n=>{cn("DD_LOGS",n)},initConfiguration:e,...t}}const ui="logs";function li(e,t){const n=rs(e,ui,r=>fi(e,r),t);return{findTrackedSession:(r,o={returnInactive:!1})=>{const s=n.findSession(r,o);return s&&s.trackingType==="1"?{id:s.id,anonymousId:s.anonymousId}:void 0},expireObservable:n.expireObservable}}function di(e){const n=Dn(e)==="1"?{}:void 0;return{findTrackedSession:()=>n,expireObservable:new v}}function Dn(e){return Oe(e.sessionSampleRate)?"1":"0"}function fi(e,t){const n=pi(t)?t:Dn(e);return{trackingType:n,isTracked:n==="1"}}function pi(e){return e==="0"||e==="1"}let Nn=!1;function Ye(e){const t=window;if(In()){const r=n(t.DD_RUM_SYNTHETICS);return!r&&!Nn&&(Nn=!0,Sn("Logs sent before RUM is injected by the synthetics worker",{testId:Js(),resultId:Zs()})),r}return n(t.DD_RUM);function n(r){if(r&&r.getInternalContext)return r.getInternalContext(e)}}function mi(e,t,n,r,o){const s=ei.concat(["custom"]),i={};s.forEach(a=>{i[a]=Cs(a,t.eventRateLimiterThreshold,o)}),n.subscribe(0,({rawLogsEvent:a,messageContext:c=void 0,savedCommonContext:l=void 0,domainContext:u})=>{var d,f;const h=Yn(a.date),g=e.findTrackedSession(h);if(!e.findTrackedSession(h,{returnInactive:!0}))return;const p=l||r();let O;!ge(p.account)&&p.account.id&&(O=p.account),g&&g.anonymousId&&!p.user.anonymous_id&&(p.user.anonymous_id=g.anonymousId);const R=ie({service:t.service,session_id:g?g.id:void 0,session:g?{id:g.id}:void 0,usr:ge(p.user)?void 0:p.user,account:O,view:p.view},p.context,Ye(h),a,c);((d=t.beforeSend)===null||d===void 0?void 0:d.call(t,R,u))===!1||R.origin!==x.AGENT&&((f=i[R.status])!==null&&f!==void 0?f:i.custom).isLimitReached()||n.notify(1,R)})}const gi={[w.log]:S.info,[w.debug]:S.debug,[w.info]:S.info,[w.warn]:S.warn,[w.error]:S.error};function hi(e,t){const n=Ps(e.forwardConsoleLogs).subscribe(r=>{var o;const s={rawLogsEvent:{date:$(),message:r.message,origin:x.CONSOLE,error:r.error&&qe(r.error),status:gi[r.api]},messageContext:(o=r.error)===null||o===void 0?void 0:o.context,domainContext:{handlingStack:r.handlingStack}};t.notify(0,s)});return{stop:()=>{n.unsubscribe()}}}function Si(e,t){const n=Mo(e,e.forwardReports).subscribe(r=>{let o=r.message,s;const i=r.originalError.type==="deprecation"?S.warn:S.error;i===S.error?s=qe(r):r.stack&&(o+=` Found in ${Ro(r.stack)}`),t.notify(0,{rawLogsEvent:{date:$(),message:o,origin:x.REPORT,error:s,status:i}})});return{stop:()=>{n.unsubscribe()}}}function yi(e,t){if(!e.forwardErrorsToLogs)return{stop:G};const n=Os(e).subscribe(s=>{s.state==="complete"&&o("xhr",s)}),r=An().subscribe(s=>{s.state==="resolve"&&o("fetch",s)});function o(s,i){!Zr(i.url)&&(wi(i)||bn(i.status))&&("xhr"in i?bi(i.xhr,e,a):i.response?Ti(i.response,e,a):i.error&&Ei(i.error,e,a));function a(c){const l={isAborted:i.isAborted,handlingStack:i.handlingStack};t.notify(0,{rawLogsEvent:{message:`${_i(s)} error ${i.method} ${i.url}`,date:i.startClocks.timeStamp,error:{stack:c||"Failed to load",handling:void 0},http:{method:i.method,status_code:i.status,url:i.url},status:S.error,origin:x.NETWORK},domainContext:l})}}return{stop:()=>{n.unsubscribe(),r.unsubscribe()}}}function bi(e,t,n){typeof e.response=="string"?n(Ot(e.response,t)):n(e.response)}function Ei(e,t,n){n(Ot(X(P(e)),t))}function Ti(e,t,n){const r=as(e);!r||!r.body?n():window.TextDecoder?vi(r.body,t.requestErrorResponseLengthLimit,(o,s)=>{n(o?`Unable to retrieve response: ${o}`:s)}):r.text().then(b(o=>n(Ot(o,t))),b(o=>n(`Unable to retrieve response: ${o}`)))}function wi(e){return e.status===0&&e.responseType!=="opaque"}function Ot(e,t){return e.length>t.requestErrorResponseLengthLimit?`${e.substring(0,t.requestErrorResponseLengthLimit)}...`:e}function _i(e){return e==="xhr"?"XHR":"Fetch"}function vi(e,t,n){Vs(e,(r,o,s)=>{if(r)n(r);else{let i=new TextDecoder().decode(o);s&&(i+="..."),n(void 0,i)}},{bytesLimit:t,collectStreamBody:!0})}function Ci(e,t){if(!e.forwardErrorsToLogs)return{stop:G};const n=new v,{stop:r}=xo(n),o=n.subscribe(s=>{t.notify(0,{rawLogsEvent:{message:s.message,date:s.startClocks.timeStamp,error:qe(s),origin:x.SOURCE,status:S.error},messageContext:s.context})});return{stop:()=>{r(),o.unsubscribe()}}}const Oi=vs;function Ri(e){function t(n,r,o,s,i){const a=ie(r.getContext(),n.context);if(Ve(n.status,ve.console,r)&&Li(n,a),Ve(n.status,ve.http,r)){const c={rawLogsEvent:{date:i||$(),message:n.message,status:n.status,origin:x.LOGGER},messageContext:a,savedCommonContext:s};o&&(c.domainContext={handlingStack:o}),e.notify(0,c)}}return{handleLog:t}}const xi={[S.ok]:w.debug,[S.debug]:w.debug,[S.info]:w.info,[S.notice]:w.info,[S.warn]:w.warn,[S.error]:w.error,[S.critical]:w.error,[S.alert]:w.error,[S.emerg]:w.error};function Li({status:e,message:t},n){z[xi[e]].call(I,t,n)}function Ai(e,t,n,r,o){const s=Ln(e,{endpoint:e.logsEndpointBuilder,encoder:He()},e.replica&&{endpoint:e.replica.logsEndpointBuilder,encoder:He()},n,r,o.expireObservable);return t.subscribe(1,i=>{s.add(i)}),s}function ki(e){const t=yt();e.subscribe(1,n=>{t.send("log",n)})}function Ii(e){return{get:t=>{const n=e.findTrackedSession(t);if(n)return{session_id:n.id}}}}function Mi(e){return t=>{e.notify(0,{rawLogsEvent:{message:t.message,date:t.startClocks.timeStamp,origin:x.AGENT,status:S.error}}),Sn("Error reported to customer",{"error.message":t.message})}}function Pi(e,t,n,r,o){const s=zo("browser-logs-sdk",t);s.setContextProvider(()=>{var a,c,l,u,d,f;return{application:{id:(a=Ye())===null||a===void 0?void 0:a.application_id},session:{id:(c=o.findTrackedSession())===null||c===void 0?void 0:c.id},view:{id:(u=(l=Ye())===null||l===void 0?void 0:l.view)===null||u===void 0?void 0:u.id},action:{id:(f=(d=Ye())===null||d===void 0?void 0:d.user_action)===null||f===void 0?void 0:f.id}}});const i=[];if(We()){const a=yt(),c=s.observable.subscribe(l=>a.send("internal_telemetry",l));i.push(()=>c.unsubscribe())}else{const a=Ln(t,{endpoint:t.rumEndpointBuilder,encoder:He()},t.replica&&{endpoint:t.replica.rumEndpointBuilder,encoder:He()},n,r,o.expireObservable);i.push(()=>a.stop());const c=s.observable.subscribe(l=>a.add(l,Vo(t)));i.push(()=>c.unsubscribe())}return Ko(),qo(oi(e)),{telemetry:s,stop:()=>{i.forEach(a=>a())}}}function Di(e,t,n,r){const o=new Oi,s=[];o.subscribe(1,f=>dn("logs",f));const i=Mi(o),a=Es(t),c=t.sessionStoreStrategyType&&!We()&&!In()?li(t,r):di(t),{stop:l}=Pi(e,t,i,a,c);s.push(()=>l()),yi(t,o),Ci(t,o),hi(t,o),Si(t,o);const{handleLog:u}=Ri(o);if(mi(c,t,o,n,i),We())ki(o);else{const{stop:f}=Ai(t,o,i,a,c);s.push(()=>f())}const d=Ii(c);return{handleLog:u,getInternalContext:d.get,stop:()=>{s.forEach(f=>f())}}}const ce=ai(Di);Io(B(),"DD_LOGS",ce);const C=class C{constructor(t,n,r,o,s){this.copy=()=>new C(this.h,this.m,this.s,this.f,this.field),this.print=()=>{const i=":";let a=("0"+this.h).slice(-2)+i+("0"+this.m).slice(-2)+i+("0"+this.s).slice(-2)+i+("0"+this.f).slice(-2);return a+="."+(this.field?"1":"2"),a},this.toZipTimeCodeString=()=>{const i=this.copy();return i.f=0,i.s=i.s%2===0?i.s:i.s-1,i.field=0,C.toStr(i)},this.toFrames=i=>{let a=60,c=0;Math.floor(i)==60?(a=60,c=0):Math.floor(i)==59?(a=60,c=4):Math.floor(i)==30?(a=30,c=0):Math.floor(i)==29&&(a=30,c=2);let l=this.h,u=this.m,d=this.s,f=this.f,h=this.field;const g=l*60+u,p=(g-Math.floor(g/10))*c;return l*(a*3600)+u*(a*60)+d*a+(f*2+h)-p},this.addSeconds=i=>{let a=this.copy();if(a.s+=i,a.s>=60){const c=Math.floor(a.s/60);if(a.s=a.s%60,a.m+=c,a.m>=60){const l=Math.floor(a.m/60);a.m=a.m%60,a.h+=l}}return a},this.addFrames=(i,a)=>{let c=this.toFrames(a);return c+=i,C.fromFrames(c,a)},this.subtractFrames=(i,a)=>this.addFrames(-i,a),this.h=t||0,this.m=n||0,this.s=r||0,this.f=o||0,this.field=s||0}static compare(t,n){return t.h!==n.h?t.h<n.h?-1:1:t.m!==n.m?t.m<n.m?-1:1:t.s!==n.s?t.s<n.s?-1:1:t.f!==n.f?t.f<n.f?-1:1:t.field!==n.field?t.field<n.field?-1:1:0}static generateTimecodeRange(t,n,r){const o=[];let s=t;for(;C.compare(s,n)<=0;)o.push(s),s=s.addSeconds(r);return o}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(t){return this.toFrames(t)*1e3/t}};C.calculateCurrentTimeCode=t=>{var d;if(!t.video||!t.clocker||!t.gameParams)throw new Error("OTTPlayer is not initialized");const n=t.video,r=t.clocker,o=r.videoFPScalculator.getFPS(),a=(n.currentTime-r.syncPoint.playerTime)%(60*60*24)*o+r.syncPoint.frame;if(a===0||o===0)throw new Error("Current frame is 0 or fps is 0");const c=C.calculateCurrentOffset(a,(d=t.gameParams)==null?void 0:d.offsets);if(c===void 0)throw new Error("Offset is undefined");let l=Math.floor(a-c);return l<0&&(l+=5178816),l>=5178816&&(l-=5178816),C.fromFrames(l,o)},C.calculateCurrentOffset=(t,n)=>{for(let r=1;r<n.length;r++)if(t<n[r].frame)return n[r-1].offset;return Math.abs(n[n.length-1].offset)},C.fromFrames=(t,n)=>{let r=60,o=0;Math.floor(n)==60?(r=60,o=0):Math.floor(n)==59?(r=60,o=4):Math.floor(n)==30?(r=30,o=0):Math.floor(n)==29&&(r=30,o=2);let s=Math.floor(n*60),i=Math.floor(n*60*10),a=i*6,c=t,l=Math.floor(c/a);c-=l*a;let u=Math.floor(c/i);c-=u*i,c>=r*60&&(c+=o*(Math.floor((c-r*60)/s)+1));let d=Math.floor(c/(r*60));c-=d*(r*60);let f=Math.floor(c/r);c-=f*r;let h=c;d+=u*10;let g=0;return g=h%2,h=Math.floor(h/2),new C(l,d,f,h,g)},C.toStr=t=>{const n="_";let r=("0"+t.h).slice(-2)+n+("0"+t.m).slice(-2)+n+("0"+t.s).slice(-2)+n+("0"+t.f).slice(-2);return t.field&&(r+="_1"),r},C.fromStr=t=>{const r=t.split("_").map(Number);if(r.length==4){const[o,s,i,a]=r;return new C(o,s,i,a,0)}else if(r.length==5){const[o,s,i,a,c]=r;return new C(o,s,i,a,c)}else throw new Error("Invalid timecode format: "+t)},C.fromMetadata=t=>{const n=/^(\\d{2}):(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d))?$/,r=t.timecode.match(n);if(!r)throw new Error("Invalid timecode format: "+t.timecode);const[,o,s,i,a,c]=r,l=Number(o),u=Number(s),d=Number(i),f=Number(a),h=c?Number(c):0;return new C(l,u,d,f,h)};let ee=C;const m=class m{constructor(t){this.listenerMap=new Map,m.options=t,this.isLoggingOn=t.LOG_TO_DATADOG,this.eventTarget=new EventTarget,this.isLoggingOn&&ce.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!1,sessionSampleRate:100});const n="bb_logger_mac_uuid";let r=localStorage.getItem(n);r||(r=crypto.randomUUID(),localStorage.setItem(n,r)),m.tracking.mac=r,m.tracking.dev=`${t.platform}_${t.browserName}`,m.beatHandle||(m.options&&A(m.options,"Logger")&&console.log("[Logger] Starting tracking beat"),m.beatHandle=window.setInterval(m.flushTracking,15e3))}static setMessagePort(t){this.messagePort=t}static getMessagePort(){return this.messagePort}setLoggingOn(t){this.isLoggingOn=t}addEventListener(t,n){const r=o=>n(o);this.listenerMap.set(n,{eventName:t,wrappedListener:r}),this.eventTarget.addEventListener(t,r)}removeEventListener(t,n){const r=this.listenerMap.get(n);r&&r.eventName===t&&(this.eventTarget.removeEventListener(t,r.wrappedListener),this.listenerMap.delete(n))}removeAllEventListeners(){for(const[t,{eventName:n,wrappedListener:r}]of this.listenerMap)this.eventTarget.removeEventListener(n,r);this.listenerMap.clear()}setAttributes(t){m.processAttributes(t);for(const n in t)ce.logger.setContextProperty(n,t[n])}info(t,n){t==="didClickAd"&&this.emit("mediaSessionDidRegisterClick",{url:(n==null?void 0:n.url)||""}),t==="didToggleGlobalAugmentationDrawing"&&this.emit("mediaSessionDidUpdateGlobalAugmentationState",{isGlobalAugmentationEnabled:(n==null?void 0:n.isEnabled)||!0}),t==="didStartDrawingAugmentationMedia"&&this.emit("mediaSessionDidBeginShotRendering",n),t==="didEndDrawingAugmentationMedia"&&this.emit("mediaSessionDidEndShotRendering",n),t==="didRegisterShot"&&this.emit("mediaSessionDidRegisterShot",n),n&&m.processAttributes(n),this.isLoggingOn&&(ce.logger.info(t,n),m.options&&A(m.options,"Logger")&&console.log("[Logger] Sending info: ",t))}error(t,n){n&&m.processAttributes(n),this.isLoggingOn&&(ce.logger.error(t,n),m.tracking.err_time=Date.now().toFixed(0),m.tracking.err_desc=t+(n?` - ${JSON.stringify(n)}`:""),m.options&&A(m.options,"Logger")&&console.log("[Logger] Sending error: ",t))}warn(t,n){n&&m.processAttributes(n),this.isLoggingOn&&(ce.logger.warn(t,n),m.options&&A(m.options,"Logger")&&console.log("[Logger] Sending warn: ",t))}handleMessageFromWorker(t){t.actionType==="INFO"?this.info(t.message,t.attributes):t.actionType==="ERROR"?this.error(t.message,t.attributes):t.actionType==="WARN"?this.warn(t.message,t.attributes):t.actionType==="SET_ATTRIBUTES"&&t.attributes&&this.setAttributes(t.attributes)}static setAttributes(t){if(!m.messagePort){console.error("[Logger] messagePort is not set! Cannot send attributes.");return}try{m.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:t})}catch(n){console.error("[Logger] Error posting message:",n)}}static info(t,n){m.messagePort.postMessage({type:"LOG",actionType:"INFO",message:t,attributes:n})}static error(t,n){m.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:t,attributes:n})}static warn(t,n){m.messagePort.postMessage({type:"LOG",actionType:"WARN",message:t,attributes:n})}static processAttributes(t){if(t.player_version&&(m.tracking.sdk=t.player_version),t.media_id&&(m.tracking.gid=t.media_id),t.game_id&&(m.tracking.buc=t.game_id),t.bb_session_id&&(m.tracking.sid=t.bb_session_id,m.options&&A(m.options,"Logger")&&console.log("[Logger] Setting bb_session_id:",m.tracking.sid)),t.last_timecode){const r=ee.fromStr(t.last_timecode);m.tracking.tc=r.print(),m.lastTimecodeMillis=r.totalMilliseconds(59.94),m.lastTimecodeMillis&&m.lastZipMillis&&(m.tracking.cache=(m.lastZipMillis-m.lastTimecodeMillis).toFixed(0))}t.last_offset&&(m.tracking.off=t.last_offset),t.last_loading_zip&&(m.tracking.zip=t.last_loading_zip+".zip",m.lastZipMillis=ee.fromStr(t.last_loading_zip).totalMilliseconds(59.94),m.lastTimecodeMillis&&m.lastZipMillis&&(m.tracking.cache=(m.lastZipMillis-m.lastTimecodeMillis).toFixed(0))),t.last_rendered_frame&&(m.tracking.aug_time=Date.now().toFixed(0)),t.asset&&(m.tracking.asset=t.asset)}static objectToQuery(t){return Object.entries(t).filter(([n,r])=>r!==0&&r!=="").map(([n,r])=>`${encodeURIComponent(n)}=${encodeURIComponent(String(r))}`).join("&")}emit(t,n){const r=new CustomEvent(t,{detail:n});this.eventTarget.dispatchEvent(r)}};m.tracking={start:Date.now().toFixed(0),dev:"",sdk:"",mac:"",gid:"",sid:"",off:"",zip:"",aug_time:"",err_time:"",err_desc:"",tc:"",asset:"",cache:"",buc:""},m.lastTimecodeMillis=0,m.lastZipMillis=0,m.flushTracking=()=>{const t=Date.now().toFixed(0);m.tracking.now=t;const r=`https://dwu3k7rrxk5s3.cloudfront.net/metrics/1.gif?${m.objectToQuery(m.tracking)}`;m.options&&A(m.options,"Logger")&&console.log("[Logger] Flushing tracking data:",r),fetch(r,{method:"GET",mode:"no-cors",keepalive:!0,headers:{"X-Platform":"Web"}}).catch(()=>{}),m.tracking.err_desc="",m.tracking.err_time=""};let ue=m;const Fn=(()=>{const e=()=>{const p=navigator.userAgent;return/windows/i.test(p)?"Windows":/android/i.test(p)?"Android":/iphone|ipad|ipod/i.test(p)?"iOS":/mac/i.test(p)?"Mac":/ipad/i.test(p)?"iPad":"Something else"},t=()=>e()==="Mac",n=()=>e()==="iPad",r=()=>e()==="iOS",o=()=>{const p=e();return p==="iOS"||p==="Mac"||p==="iPad"},s=()=>e()==="Windows",i=()=>e()==="Android",a=()=>{switch(e()){case"Windows":return"a Windows PC";case"Android":return"an Android phone";case"iOS":return"an iPhone";case"Mac":return"a Mac";case"iPad":return"an iPad";default:return"an Unknown device"}},c=()=>({header:[navigator.platform,navigator.userAgent,navigator.appVersion,navigator.vendor,window.opera],dataos:[{name:"Windows Phone",value:"Windows Phone",version:"OS"},{name:"Windows",value:"Win",version:"NT"},{name:"iPhone",value:"iPhone",version:"OS"},{name:"iPad",value:"iPad",version:"OS"},{name:"Kindle",value:"Silk",version:"Silk"},{name:"Android",value:"Android",version:"Android"},{name:"PlayBook",value:"PlayBook",version:"OS"},{name:"BlackBerry",value:"BlackBerry",version:"/"},{name:"Macintosh",value:"Mac",version:"OS X"},{name:"Linux",value:"Linux",version:"rv"},{name:"Palm",value:"Palm",version:"PalmOS"}],databrowser:[{name:"Chrome",value:"Chrome",version:"Chrome"},{name:"Firefox",value:"Firefox",version:"Firefox"},{name:"Safari",value:"Safari",version:"Version"},{name:"Internet Explorer",value:"MSIE",version:"MSIE"},{name:"Opera",value:"Opera",version:"Opera"},{name:"BlackBerry",value:"CLDC",version:"CLDC"},{name:"Mozilla",value:"Mozilla",version:"Mozilla"}],init(){const R=this.header.join(" ");return this.matchItem(R,this.dataos)},matchItem(R,F){for(let le=0;le<F.length;le+=1)if(new RegExp(F[le].value,"i").test(R))return F[le].name;return"unknown"}}).init(),l=()=>{const p=navigator.userAgent;return p.indexOf("Chrome")>-1&&p.indexOf("Edge")===-1?"Chrome":p.indexOf("Safari")>-1&&p.indexOf("Chrome")===-1?"Safari":p.indexOf("Firefox")>-1?"Firefox":p.indexOf("MSIE")>-1||p.indexOf("Trident")>-1?"Internet Explorer":p.indexOf("Edge")>-1?"Edge":"Unknown"};return{getCurrentPlatform:e,isMac:t,isiPad:n,isiPhone:r,isApple:o,isWindows:s,isAndroid:i,getDeviceDescription:a,getDeviceName:c,getBrowserName:l,isSafariMac:()=>t()&&l()==="Safari",isChromeMac:()=>t()&&l()==="Chrome",isChromeWin:()=>s()&&l()==="Chrome",isFirefoxMac:()=>t()&&l()==="Firefox",isFirefoxWin:()=>s()&&l()==="Firefox"}})(),Rt={lastRendererFrameSent:0,isRAFSeen:!1,isRVFCSeen:!1,RVFCmissed:!1,RVFCframeExpected:0,compensationMode:!1,compensationCounter:0,frameCorrection:0,lastMessageSent:""};let Xe=null,L,T;self.onmessage=async e=>{const{data:t}=e;t.type==="SET_LOGGER_PORT"&&ue.setMessagePort(t.port),t.type==="SET_RENDERER_PORT"&&(Xe=t.port,Xe.onmessage=Ni),t.type==="ADAPTER_UPDATE_DATA"&&(T=t.data,$n()),t.type==="SET_OPTIONS"&&(L=t.options,ue.setMessagePort(self))};function Ni(e){L&&A(L,"Adapter")&&console.log("[AdapterWorker] Message from Renderer:",e.data)}const $n=()=>{!T||T.siData.isVideoPaused||(Fn.isChromeMac()?Fi():Fn.isSafariMac()&&$i())},Fi=()=>{if(!T||T.siData.isVideoPaused||!T.vfcData.lastFrameMetadata)return;const{siData:e,vfcData:t,afData:n,debugControls:r}=T;if(!e.isRAFSeen){let o=4,s=-11,i=1,a=5;if(r){const p=parseInt(r["Window Start (ms)"],10);isNaN(p)||(o=p);const O=parseInt(r["Window End (ms)"],10);isNaN(O)||(s=O);const R=parseInt(r["Frame Correction"],10);isNaN(R)||(i=R);const F=parseInt(r["Timeout time"],10);isNaN(F)||(a=F)}const c=1e3/t.videoFPS;1e3/n.animationFPS;const l=n.lastTimestamp,u=t.storedMetadata.reduce((p,O)=>Math.abs(O.expectedDisplayTime-l)<Math.abs(p.expectedDisplayTime-l)?O:p),d=u.expectedDisplayTime-o,f=[];for(let p=-10;p<10;p++)f.push(d+p*c);const h=u.expectedDisplayTime-s,g=[];for(let p=-10;p<10;p++)g.push(h+p*c);let E=null;f.forEach((p,O)=>{l>p&&l<g[O]&&(E=O-10)}),E!==null?setTimeout(p=>xt(t.lastCalculatedMediaTimeVideoFrame+p*Math.round(60/t.videoFPS)+i),a,E):xt(Rt.lastRendererFrameSent)}},$i=()=>{if(!T||T.siData.isVideoPaused||!T.vfcData.lastFrameMetadata)return;const{siData:e,vfcData:t,afData:n}=T;let r=n.lastCalculatedPlayerTimeFraction;const o=n.previousCalculatedPlayerTimeFraction;r<.3&&r>.1&&o<.3&&o>.1&&(r=Math.min(r,o));let s=0;r<.1?s=0:r>.1&&r<.3?s=(r-.1)/(.3-.1):s=1;let i=n.lastCalculatedPlayerTimeVideoFrame;s==1&&(i++,s=0),xt(i,s)},xt=(e,t)=>{if(!T)return;Rt.lastRendererFrameSent=e,T.siData.workingFps;const n=ee.fromFrames(e,6e4/1001),r=T.vfcData.videoFPS;if(r<=10||r>70){console.error("Video FPS is out of supported range: "+r),Bi(n);return}T.afData.animationFPS,Ui(n,t)},Ui=(e,t)=>{const n=ee.toStr(e);Rt.lastMessageSent=n,L&&A(L,"Adapter")&&console.log(`[AdapterWorker] Rendering augmentation for timecode: ${n} , ${e}`),Un(n,t)},Bi=e=>{const t=ee.toStr(e);L&&A(L,"Adapter")&&console.log("[AdapterWorker] Clearing augmentation"),Un(t,0,!0)},Un=(e,t,n)=>{if(!Xe||!T)return;const r=e;L&&A(L,"Adapter")&&console.log(`[AdapterWorker] Sending current time code to the Renderer: ${r}`);const o={timeCode:r,frameCorrection:t||0,fps:jn(T.siData.workingFps),zipBaseURL:T.zipBaseURL,adsBaseURL:T.adsBaseURL,bucketName:T.bucketName,customerId:T.customerId,offsets:T.offsets},i={type:n?"RENDERER_CLEAR":"RENDERER_DRAW",streamData:o};Xe.postMessage(i)};self.onunhandledrejection=e=>{ue.error("[AdapterWorker] Unhandled rejection",{error:e.reason}),L&&(A(L,"Errors")&&console.error("[AdapterWorker] Unhandled rejection:",e.reason),e.preventDefault())},self.onerror=e=>{ue.error("[AdapterWorker] Unhandled error",{error:e}),L&&(A(L,"Errors")&&console.error("[AdapterWorker] Unhandled error:",e),e instanceof Event&&e.preventDefault())},setInterval($n,2)})();\n',Wt=typeof self<"u"&&self.Blob&&new Blob([Ht],{type:"text/javascript;charset=utf-8"});function ln(t){let e;try{if(e=Wt&&(self.URL||self.webkitURL).createObjectURL(Wt),!e)throw"";const r=new Worker(e,{name:t==null?void 0:t.name});return r.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),r}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Ht),{name:t==null?void 0:t.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}class jt{constructor(){this.metrics=new Map,this.containers=[],this.createContainer=()=>{const e=document.createElement("div");e.style.display="flex",e.style.gap="30px",e.style.marginTop="2px",e.style.marginBottom="2px",e.style.fontSize="12px",e.style.fontFamily="monospace";const r={div:e,metrics:[]};return this.containers.push(r),document.body.appendChild(e),r},this.createMetric=(e,r)=>{const n=document.createElement("span");n.style.display="inline-flex",n.style.gap="4px",n.style.whiteSpace="nowrap",n.style.flexShrink="0";const s=document.createElement("span");s.textContent=`${e}:`,s.style.flexShrink="0",s.style.fontWeight="bold";const i=document.createElement("span");i.style.minWidth="0",i.style.textAlign="right",i.style.whiteSpace="nowrap",i.style.flexShrink="0",i.style.display="inline-block",i.textContent="",n.appendChild(s),n.appendChild(i);const o={name:e,value:"",span:n,valueSpan:i,maxWidth:0};return r.metrics.push(o),r.div.appendChild(n),this.metrics.set(e,o),o},this.updateMetric=(e,r)=>{const n=this.metrics.get(e);if(!n){console.error("Metric does not exist");return}typeof r=="boolean"?n.value=r?"true":"false":n.value=r,n.valueSpan.textContent=String(n.value);const s=n.valueSpan.offsetWidth;s>n.maxWidth&&(n.maxWidth=s,n.valueSpan.style.minWidth=`${s}px`)}}delete(){this.containers.forEach(e=>{e.div.remove()})}}class dn{constructor(e){if(this.canPlayListner=()=>this.setupCanvas(),this.clickListner=n=>{this.clicker.click(n)},this.mediaTime=0,this.timecodeChecker=new nn(0),this.rendererReady=!1,this.pendingAdBitmaps=[],this.lastAdBlobPerPlaceholder=new Map,this.logger=e.logger,this.OTTPlayer=e,this.options=e.options,this.debug=this.options.debug?this.options.debug.on:!1,this.options.debug&&this.debug){this.metrics=new jt;const n=this.metrics.createContainer();if(this.metrics.createMetric("Last Downloaded Zip",n),this.metrics.createMetric("Last Decoded Frame",n),this.metrics.createMetric("Last WebGL Uploaded Frame",n),this.metrics.createMetric("Last Rendered Frame",n),this.metrics.createMetric("Renderer State",n),this.options.debug.trackPerformance){const s=this.metrics.createContainer();this.metrics.createMetric("Rendering GPU time",s),this.metrics.createMetric("Rendering CPU time",s),this.metrics.createMetric("Chunking time",s),this.metrics.createMetric("Decoding time",s)}}this.downloaderWorker=new on,this.decoderWorker=new an,this.rendererWorker=new cn;const r=[this.downloaderWorker,this.decoderWorker,this.rendererWorker];this.options.ADAPTER_RUN_IN_WORKER&&(this.adapterWorker=new ln,r.push(this.adapterWorker)),window.BB.workerInstances.push(...r),this.rendererToDownloader=new MessageChannel,this.rendererToMain=new MessageChannel,this.downloaderToDecoder=new MessageChannel,this.decoderToRenderer=new MessageChannel,this.options.ADAPTER_RUN_IN_WORKER&&(this.adapterToRenderer=new MessageChannel),this.setupWorkers(),this.canvas=document.createElement("canvas"),this.OTTPlayer.video.readyState>=3?this.setupCanvas():this.OTTPlayer.video.addEventListener("canplay",this.canPlayListner,{once:!0}),this.processedTimecodes=[],this.clicker=new sn(this.OTTPlayer,this.rendererWorker),this.segmentFirstFrameTimecode=new L,this.syncPoint={frame:0,playerTime:0,stringTime:""},this.cacheStarted=!1,this.animationFPScalculator=new nt(20),this.videoFPScalculator=new nt(20),this.startAnimationFrameLoop(),this.startVideoFrameCallbackLoop()}startAnimationFrameLoop(){const e=()=>{this.animationFPScalculator.addTimestamp(performance.now()/1e3),this.OTTPlayer.RUN_PIXEL_TICKERS&&this.OTTPlayer.pixelTickers.forEach(r=>{r.update()}),this.animationFrameLoopId=requestAnimationFrame(e)};this.animationFrameLoopId=requestAnimationFrame(e)}startVideoFrameCallbackLoop(){const e=(r,n)=>{this.mediaTime=n.mediaTime,this.videoFPScalculator.addTimestamp(n.mediaTime),this.videoFrameCallbackLoopId=this.OTTPlayer.video.requestVideoFrameCallback(e)};this.videoFrameCallbackLoopId=this.OTTPlayer.video.requestVideoFrameCallback(e)}updateCanvasSize(){if(!this.canvasContainer)return;const e=this.canvasContainer,r=e.style.width,n=e.style.height;if(r&&n){this.canvas.style.width=r,this.canvas.style.height=n,this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=void 0);return}const s=window.getComputedStyle(e);this.canvas.style.width=s.width,this.canvas.style.height=s.height,!this.resizeObserver&&typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>{const i=window.getComputedStyle(e);this.canvas.style.width=i.width,this.canvas.style.height=i.height}),this.resizeObserver.observe(e))}setupCanvas(){const e=this.OTTPlayer.video,r=this.options.CANVAS_CONTAINER||e.parentElement;if(!r){console.error("[Clocker] No container found for canvas placement"),this.logger.error("setupCanvas failed: no container found");return}this.canvasContainer=r,console.log("video.videoWidth: ",e.videoWidth),console.log("video.videoHeight: ",e.videoHeight),this.canvas.width=e.videoWidth,this.canvas.height=e.videoHeight,this.canvas.style.zIndex="3000",this.canvas.style.position="absolute",this.canvas.style.top="0%",this.canvas.style.left="0",console.log("container: ",r),console.log("[OTTPlayer] container sizes:"),console.log("container.style.width: ",r.style.width),console.log("container.style.height: ",r.style.height),this.updateCanvasSize(),this.canvas.style.pointerEvents="none",r.addEventListener("click",this.clickListner),r.style.position="relative",r.appendChild(this.canvas);const n=this.canvas.transferControlToOffscreen(),{CANVAS_CONTAINER:s,...i}=this.options,o={type:"INIT_OFFSCREEN",offscreen:n,options:i};this.rendererWorker.postMessage(o,[n]),e.onseeked=()=>{this.onVideoSeeked()},e.onseeking=()=>{this.onVideoSeeked()}}setupWorkers(){const{CANVAS_CONTAINER:e,...r}=this.options;this.downloaderWorker.onmessage=n=>{n.data.type==="LOG"?(n.data.actionType==="SET_ATTRIBUTES"&&n.data.attributes.last_loading_zip&&this.metrics&&this.metrics.updateMetric("Last Downloaded Zip",n.data.attributes.last_loading_zip),this.logger.handleMessageFromWorker(n.data)):n.data.type==="TRACK_PERFORMANCE"&&this.trackPerformance(n.data)},this.decoderWorker.onmessage=n=>{if(n.data.type==="LOG"){if(n.data.actionType==="SET_ATTRIBUTES"&&(n.data.attributes.last_decoded_frame&&this.metrics&&this.metrics.updateMetric("Last Decoded Frame",n.data.attributes.last_decoded_frame),this.OTTPlayer.statusOverlay)){const s=n.data.attributes;s.decoder_status&&this.OTTPlayer.statusOverlay.updateMetric("health","decoder",s.decoder_status.healthy,s.decoder_status.issue),s.timecode_status&&this.OTTPlayer.statusOverlay.updateMetric("timecode","consistency",s.timecode_status.consistent,s.timecode_status.errorCount>0?`Errors: ${s.timecode_status.errorCount}`:void 0)}this.logger.handleMessageFromWorker(n.data)}else n.data.type==="TRACK_PERFORMANCE"&&this.trackPerformance(n.data)},this.rendererWorker.onmessage=n=>{n.data.type==="LOG"?(n.data.actionType==="SET_ATTRIBUTES"&&this.metrics&&(n.data.attributes.last_webgl_uploaded_frame&&this.metrics.updateMetric("Last WebGL Uploaded Frame",n.data.attributes.last_webgl_uploaded_frame),n.data.attributes.last_rendered_frame&&this.metrics.updateMetric("Last Rendered Frame",n.data.attributes.last_rendered_frame),n.data.attributes.renderer_state&&this.metrics.updateMetric("Renderer State",n.data.attributes.renderer_state)),this.logger.handleMessageFromWorker(n.data)):n.data.type==="TRACK_PERFORMANCE"?this.trackPerformance(n.data):n.data.type==="RENDERER_READY"&&(this.rendererReady=!0,this.flushOverrides(!0))},this.adapterWorker&&(this.adapterWorker.onmessage=n=>{n.data.type==="LOG"?this.logger.handleMessageFromWorker(n.data):n.data.type==="TRACK_PERFORMANCE"&&this.trackPerformance(n.data)}),this.rendererWorker.postMessage({type:"SET_DOWNLOADER_PORT",port:this.rendererToDownloader.port1},[this.rendererToDownloader.port1]),this.downloaderWorker.postMessage({type:"SET_RENDERER_PORT",port:this.rendererToDownloader.port2},[this.rendererToDownloader.port2]),this.downloaderWorker.postMessage({type:"SET_DECODER_PORT",port:this.downloaderToDecoder.port1},[this.downloaderToDecoder.port1]),this.decoderWorker.postMessage({type:"SET_DOWNLOADER_PORT",port:this.downloaderToDecoder.port2},[this.downloaderToDecoder.port2]),this.decoderWorker.postMessage({type:"SET_RENDERER_PORT",port:this.decoderToRenderer.port1},[this.decoderToRenderer.port1]),this.rendererWorker.postMessage({type:"SET_DECODER_PORT",port:this.decoderToRenderer.port2},[this.decoderToRenderer.port2]),this.adapterWorker&&this.adapterToRenderer&&(this.adapterWorker.postMessage({type:"SET_RENDERER_PORT",port:this.adapterToRenderer.port1},[this.adapterToRenderer.port1]),this.rendererWorker.postMessage({type:"SET_ADAPTER_PORT",port:this.adapterToRenderer.port2},[this.adapterToRenderer.port2])),this.rendererWorker.postMessage({type:"SET_LOGGER_PORT",port:this.rendererToMain.port1},[this.rendererToMain.port1]),this.rendererToMain.port2.onmessage=n=>{var s,i;if(n.data.type==="LOG"){if(n.data.actionType==="SET_ATTRIBUTES"&&(this.metrics&&(n.data.attributes.last_webgl_uploaded_frame&&this.metrics.updateMetric("Last WebGL Uploaded Frame",n.data.attributes.last_webgl_uploaded_frame),n.data.attributes.last_rendered_frame&&this.metrics.updateMetric("Last Rendered Frame",n.data.attributes.last_rendered_frame),n.data.attributes.renderer_state&&this.metrics.updateMetric("Renderer State",n.data.attributes.renderer_state)),this.OTTPlayer.statusOverlay)){const o=n.data.attributes;if(o.webgl_status&&this.OTTPlayer.statusOverlay.updateMetric("health","webgl",o.webgl_status.ready,o.webgl_status.issue),o.renderer_state&&this.OTTPlayer.statusOverlay.updateMetric("switches","render_state",o.renderer_state),o.data_status){const a=o.data_status;this.OTTPlayer.statusOverlay.updateMetric("data","stream_data",a.stream_data,a.timecode||void 0),this.OTTPlayer.statusOverlay.updateMetric("data","ads",a.ads),this.OTTPlayer.statusOverlay.updateMetric("data","render_data",a.render_data),this.OTTPlayer.statusOverlay.updateMetric("data","alpha_mask",a.alpha_mask),this.OTTPlayer.statusOverlay.updateMetric("data","placeholders",a.placeholders),this.OTTPlayer.statusOverlay.updateMetric("data","processing_size",a.processing_size),this.OTTPlayer.statusOverlay.updateMetric("switches","isLive",a.isLive)}if(o.killswitch_status){const a=o.killswitch_status;this.OTTPlayer.statusOverlay.updateMetric("switches","killswitch_web",a.web),this.OTTPlayer.statusOverlay.updateMetric("switches","killswitch_local",a.local)}if(o.zip_buffer_status){const a=o.zip_buffer_status,c=((s=a.retryingTimecodes)==null?void 0:s.length)||0,d=((i=a.failedTimecodes)==null?void 0:i.length)||0;let l=`${a.continuousSeconds.toFixed(1)}s`;(c>0||d>0)&&(l+=` | Retrying: ${c}, Failed: ${d}`),this.OTTPlayer.statusOverlay.updateMetric("data","zip_buffer",!a.needsFadeout,l)}}this.logger.handleMessageFromWorker(n.data)}else n.data.type==="TRACK_PERFORMANCE"?this.trackPerformance(n.data):n.data.type==="RENDERER_READY"&&(this.rendererReady=!0,this.flushOverrides(!0))},this.downloaderWorker.postMessage({type:"SET_OPTIONS",options:r}),this.decoderWorker.postMessage({type:"SET_OPTIONS",options:r}),this.adapterWorker&&this.adapterWorker.postMessage({type:"SET_OPTIONS",options:r}),this.rendererWorker.postMessage({type:"SET_OPTIONS",options:r})}callAdapterWorker(e){this.adapterWorker&&this.adapterWorker.postMessage({type:"ADAPTER_UPDATE_DATA",data:e})}callRendererWorkerWithFrame(e,r){if(!this.OTTPlayer.gameParams||!this.OTTPlayer.gameParams.bucketName){e.close();return}const n={timeCode:r,frameCorrection:0,fps:ie(this.videoFPScalculator.getFPS()),zipBaseURL:this.OTTPlayer.options.zipBaseURL,adsBaseURL:this.OTTPlayer.options.adsBaseURL,bucketName:this.OTTPlayer.gameParams.bucketName,offsets:this.OTTPlayer.gameParams.offsets,customerId:this.OTTPlayer.gameParams.customerId,ottActions:this.OTTPlayer.ottActions},s={type:"BURNED_FRAME_RENDER",imageBitmap:e,timecode:r,streamData:n};this.rendererWorker.postMessage(s,[e]),this.logger.setAttributes({last_timecode:r})}setAdImage(e,r){if(!this.rendererReady){this.pendingAdBitmaps.push({imageBitmap:e,placeholder:r});return}const n={type:"SET_AD_IMAGE",imageBitmap:e,placeholder:r};this.rendererWorker.postMessage(n,[e])}setLEDImage(e){if(!this.rendererReady){if(this.pendingLEDBitmap)try{this.pendingLEDBitmap.close()}catch{}this.pendingLEDBitmap=e;return}const r={type:"SET_LED_IMAGE",imageBitmap:e};this.rendererWorker.postMessage(r,[e])}setAdBlob(e,r){r?this.lastAdBlobPerPlaceholder.set(r,e):this.lastGlobalAdBlob=e;const n={type:"SET_AD_BLOB",blob:e,placeholder:r};this.rendererWorker.postMessage(n)}setLEDBlob(e){this.lastLEDBlob=e;const r={type:"SET_LED_BLOB",blob:e};this.rendererWorker.postMessage(r)}resetAds(){this.lastGlobalAdBlob=void 0,this.rendererWorker.postMessage({type:"RESET_ADS"})}callRendererWorker(e,r,n){var a,c;this.options&&_(this.options,"Clocker")&&console.log(`[Clocker] Sending current time code to the Renderer: ${e}`);const s=n?"RENDERER_CLEAR":"RENDERER_DRAW";if(!e||!this.OTTPlayer.gameParams||!this.OTTPlayer.gameParams.bucketName||!this.OTTPlayer.gameParams.offsets){const d={type:s};this.rendererWorker.postMessage(d);return}const i={timeCode:e,frameCorrection:r||0,fps:ie(this.videoFPScalculator.getFPS()),zipBaseURL:this.OTTPlayer.options.zipBaseURL,adsBaseURL:this.OTTPlayer.options.adsBaseURL,bucketName:this.OTTPlayer.gameParams.bucketName,offsets:this.OTTPlayer.gameParams.offsets,customerId:this.OTTPlayer.gameParams.customerId,ottActions:this.OTTPlayer.ottActions?{...this.OTTPlayer.ottActions,benchmarkPassed:((c=(a=this.OTTPlayer.adapter)==null?void 0:a.benchmark)==null?void 0:c.hasPassed())??!1}:void 0},o={type:s,streamData:i};this.rendererWorker.postMessage(o),n||this.logger.setAttributes({last_timecode:e})}onVideoSeeked(){this.restartWorkers(),this.OTTPlayer.adapter&&this.OTTPlayer.adapter.onVideoSeeked(),this.logger.info("didSeek")}stopWorkers(){const e={type:"STOP_WORKER"};this.downloaderWorker.postMessage(e),this.decoderWorker.postMessage(e),this.rendererWorker.postMessage(e)}restartWorkers(){this.rendererReady=!1;const e={type:"RESTART_WORKER"};this.downloaderWorker.postMessage(e),this.decoderWorker.postMessage(e),this.rendererWorker.postMessage(e)}pause(){this.stopWorkers(),this.animationFrameLoopId&&(cancelAnimationFrame(this.animationFrameLoopId),this.animationFrameLoopId=void 0),this.videoFrameCallbackLoopId&&(this.OTTPlayer.video.cancelVideoFrameCallback(this.videoFrameCallbackLoopId),this.videoFrameCallbackLoopId=void 0)}resume(){this.restartWorkers(),this.animationFrameLoopId||this.startAnimationFrameLoop(),this.videoFrameCallbackLoopId||this.startVideoFrameCallbackLoop()}trackPerformance(e){var r;if((r=this.options.debug)!=null&&r.trackPerformance&&this.metrics)for(let n of e.data)this.metrics.updateMetric(n.metric,n.value.toFixed(2))}flushOverrides(e=!1){if(e){if(this.lastGlobalAdBlob){const r={type:"SET_AD_BLOB",blob:this.lastGlobalAdBlob};this.rendererWorker.postMessage(r)}this.lastAdBlobPerPlaceholder.size>0&&this.lastAdBlobPerPlaceholder.forEach((r,n)=>{const s={type:"SET_AD_BLOB",blob:r,placeholder:n};this.rendererWorker.postMessage(s)})}if(this.pendingAdBitmaps.length>0){for(const r of this.pendingAdBitmaps){const n={type:"SET_AD_IMAGE",imageBitmap:r.imageBitmap,placeholder:r.placeholder};this.rendererWorker.postMessage(n,[r.imageBitmap])}this.pendingAdBitmaps=[]}if(this.pendingLEDBitmap){const r=this.pendingLEDBitmap;this.pendingLEDBitmap=void 0;const n={type:"SET_LED_IMAGE",imageBitmap:r};this.rendererWorker.postMessage(n,[r])}else if(e&&this.lastLEDBlob){const r={type:"SET_LED_BLOB",blob:this.lastLEDBlob};this.rendererWorker.postMessage(r)}}delete(){const e=this.OTTPlayer.video,r=this.canvasContainer||e.parentElement;if(this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=void 0),r&&this.canvas&&r.contains(this.canvas)&&r.removeChild(this.canvas),this.rendererWorker.terminate(),this.downloaderWorker.terminate(),this.decoderWorker.terminate(),this.adapterWorker&&this.adapterWorker.terminate(),this.metrics&&this.metrics.delete(),this.animationFrameLoopId&&cancelAnimationFrame(this.animationFrameLoopId),this.videoFrameCallbackLoopId&&e.cancelVideoFrameCallback(this.videoFrameCallbackLoopId),e.removeEventListener("canplay",this.canPlayListner),r&&r.removeEventListener("click",this.clickListner),this.pendingAdBitmaps&&this.pendingAdBitmaps.length>0){for(const n of this.pendingAdBitmaps)try{n.imageBitmap.close()}catch{}this.pendingAdBitmaps=[]}if(this.pendingLEDBitmap){try{this.pendingLEDBitmap.close()}catch{}this.pendingLEDBitmap=void 0}}}class un{constructor(){this.controls=new Map,this.containers=[]}createContainer(e){const r=document.createElement("div");r.style.display="flex",r.style.flexWrap="wrap",r.style.gap="10px",r.style.padding="10px",r.style.marginBottom="10px",r.style.border="1px solid #ccc",r.style.fontSize="14px",r.style.backgroundColor="#f9f9f9";const n=document.createElement("button");n.textContent="Apply",n.style.cursor="pointer";const s={div:r,controls:[],button:n};return n.addEventListener("click",()=>{const i={};s.controls.forEach(o=>{o.type==="input"||o.type==="select"?o.appliedValue=o.element.value:o.type==="checkbox"&&(o.appliedValue=String(o.element.checked)),i[o.name]=o.appliedValue}),e&&e(i)}),r.appendChild(n),document.body.appendChild(r),this.containers.push(s),s}createInput(e,r="",n){const s=document.createElement("label");s.style.display="flex",s.style.flexDirection="column",s.style.fontWeight="bold";const i=document.createElement("span");i.textContent=e,i.style.marginBottom="3px";const o=document.createElement("input");o.type="text",o.value=String(r),o.style.minWidth="60px";const a={name:e,type:"input",element:o,container:n,appliedValue:String(r)};this.controls.set(e,a),n.controls.push(a),s.appendChild(i),s.appendChild(o),n.div.insertBefore(s,n.button)}createSelect(e,r,n="",s){const i=document.createElement("label");i.style.display="flex",i.style.flexDirection="column",i.style.fontWeight="bold";const o=document.createElement("span");o.textContent=e,o.style.marginBottom="3px";const a=document.createElement("select");a.style.minWidth="80px",Object.entries(r).forEach(([d,l])=>{const u=document.createElement("option");u.textContent=d,u.value=String(l),a.appendChild(u)}),a.value=String(n);const c={name:e,type:"select",element:a,container:s,appliedValue:String(n)};this.controls.set(e,c),s.controls.push(c),i.appendChild(o),i.appendChild(a),s.div.insertBefore(i,s.button)}createCheckbox(e,r=!1,n){const s=document.createElement("label");s.style.display="flex",s.style.fontWeight="bold";const i=document.createElement("span");i.textContent=e,i.style.marginRight="5px";const o=document.createElement("input");o.type="checkbox",o.checked=r;const a={name:e,type:"checkbox",element:o,container:n,appliedValue:String(r)};this.controls.set(e,a),n.controls.push(a),s.appendChild(i),s.appendChild(o),n.div.insertBefore(s,n.button)}exportData(){const e={};return this.controls.forEach(r=>{e[r.name]=r.appliedValue}),e}getValue(e){const r=this.controls.get(e);return r?r.appliedValue:(console.error(`No control found with name: ${e}`),"")}delete(){this.containers.forEach(e=>{e.div.remove()}),this.containers=[],this.controls.clear()}}const Ue=t=>t.toString().padStart(2,"0"),st=":",hn=(t,e,r=!1)=>{let n="";return Array.isArray(t)?(n=[Ue(t[0]),Ue(t[1]),Ue(t[2]),Ue(t[3])].join(":"),r==!0?t[4]==1&&e?n+=".2":n+=".1":t[4]==1&&e&&(n+=".1")):(n=("0"+t.h).slice(-2)+st+("0"+t.m).slice(-2)+st+("0"+t.s).slice(-2)+st+("0"+t.f).slice(-2),n+="."+(t.field?"1":"2")),n},fn=(t,e,r)=>{let n=60,s=0;Math.floor(e)==60?(n=60,s=0):Math.floor(e)==59?(n=60,s=4):Math.floor(e)==30?(n=30,s=0):Math.floor(e)==29&&(n=30,s=2);let i=0,a=Math.floor(e*60*10)*6,c=t[0],d=t[1],l=t[2],u=t[3],f=t[4];return i+=c*a,i+=d*(n*60),i+=l*n,i+=u*2+f,i-=s*d,i+=s*Math.floor(d/10),i},I=(()=>{const t=()=>{const g=navigator.userAgent;return/windows/i.test(g)?"Windows":/android/i.test(g)?"Android":/iphone|ipad|ipod/i.test(g)?"iOS":/mac/i.test(g)?"Mac":/ipad/i.test(g)?"iPad":"Something else"},e=()=>t()==="Mac",r=()=>t()==="iPad",n=()=>t()==="iOS",s=()=>{const g=t();return g==="iOS"||g==="Mac"||g==="iPad"},i=()=>t()==="Windows",o=()=>t()==="Android",a=()=>{switch(t()){case"Windows":return"a Windows PC";case"Android":return"an Android phone";case"iOS":return"an iPhone";case"Mac":return"a Mac";case"iPad":return"an iPad";default:return"an Unknown device"}},c=()=>({header:[navigator.platform,navigator.userAgent,navigator.appVersion,navigator.vendor,window.opera],dataos:[{name:"Windows Phone",value:"Windows Phone",version:"OS"},{name:"Windows",value:"Win",version:"NT"},{name:"iPhone",value:"iPhone",version:"OS"},{name:"iPad",value:"iPad",version:"OS"},{name:"Kindle",value:"Silk",version:"Silk"},{name:"Android",value:"Android",version:"Android"},{name:"PlayBook",value:"PlayBook",version:"OS"},{name:"BlackBerry",value:"BlackBerry",version:"/"},{name:"Macintosh",value:"Mac",version:"OS X"},{name:"Linux",value:"Linux",version:"rv"},{name:"Palm",value:"Palm",version:"PalmOS"}],databrowser:[{name:"Chrome",value:"Chrome",version:"Chrome"},{name:"Firefox",value:"Firefox",version:"Firefox"},{name:"Safari",value:"Safari",version:"Version"},{name:"Internet Explorer",value:"MSIE",version:"MSIE"},{name:"Opera",value:"Opera",version:"Opera"},{name:"BlackBerry",value:"CLDC",version:"CLDC"},{name:"Mozilla",value:"Mozilla",version:"Mozilla"}],init(){const b=this.header.join(" ");return this.matchItem(b,this.dataos)},matchItem(b,E){for(let A=0;A<E.length;A+=1)if(new RegExp(E[A].value,"i").test(b))return E[A].name;return"unknown"}}).init(),d=()=>{const g=navigator.userAgent;return g.indexOf("Chrome")>-1&&g.indexOf("Edge")===-1?"Chrome":g.indexOf("Safari")>-1&&g.indexOf("Chrome")===-1?"Safari":g.indexOf("Firefox")>-1?"Firefox":g.indexOf("MSIE")>-1||g.indexOf("Trident")>-1?"Internet Explorer":g.indexOf("Edge")>-1?"Edge":"Unknown"};return{getCurrentPlatform:t,isMac:e,isiPad:r,isiPhone:n,isApple:s,isWindows:i,isAndroid:o,getDeviceDescription:a,getDeviceName:c,getBrowserName:d,isSafariMac:()=>e()&&d()==="Safari",isChromeMac:()=>e()&&d()==="Chrome",isChromeWin:()=>i()&&d()==="Chrome",isFirefoxMac:()=>e()&&d()==="Firefox",isFirefoxWin:()=>i()&&d()==="Firefox"}})();class pn{constructor(e=10){this.testStartTime=0,this.currentState="FAILED",this.previousState="FAILED",this.testDurationMs=e*1e3,this.lastConditions=this.getEmptyConditions()}test(e){const r=Object.values(e).every(s=>s===!0);if(this.previousState=this.currentState,!r){this.currentState="FAILED",this.testStartTime=0,this.lastConditions=e;const s=this.previousState==="PASSED"||this.previousState==="TESTING";return{state:"FAILED",failedConditions:this.getFailedConditions(e),shouldClear:s}}const n=performance.now();if(this.currentState==="FAILED"&&(this.currentState="TESTING",this.testStartTime=n),this.currentState==="TESTING"){const s=n-this.testStartTime,i=this.testDurationMs-s;return i<=0?(this.currentState="PASSED",{state:"PASSED"}):{state:"TESTING",remainingSeconds:Math.ceil(i/1e3)}}return this.lastConditions=e,{state:"PASSED"}}hasPassed(){return this.currentState==="PASSED"}getStatus(){if(this.currentState==="FAILED")return{state:"FAILED",failedConditions:this.getFailedConditions(this.lastConditions)};if(this.currentState==="TESTING"){const r=performance.now()-this.testStartTime,n=this.testDurationMs-r;return{state:"TESTING",remainingSeconds:Math.ceil(n/1e3)}}return{state:"PASSED"}}reset(){this.currentState="FAILED",this.testStartTime=0}setDuration(e){this.testDurationMs=e*1e3}getFailedConditions(e){const r=[];return e.gameParams||r.push("game_params"),e.browserSupported||r.push("browser"),e.patternDetected||r.push("pattern"),e.fpsSupported||r.push("fps"),e.noMKAdsPlaying||r.push("mk_ads"),e.syncPointSet||r.push("sync_point"),r}getEmptyConditions(){return{gameParams:!1,browserSupported:!1,patternDetected:!1,fpsSupported:!1,noMKAdsPlaying:!0,syncPointSet:!1}}}class mn{constructor(){this.OUT_WIDTH=4,this.OUT_HEIGHT=1,this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl2");if(!e)throw new Error("WebGL2 not supported");this.gl=e;const r=`#version 300 es
|
|
397
397
|
|
|
398
398
|
precision highp float;
|
|
399
399
|
|
|
@@ -491,10 +491,10 @@ void main(){
|
|
|
491
491
|
|
|
492
492
|
}
|
|
493
493
|
|
|
494
|
-
`,s=this.createShader(this.gl.VERTEX_SHADER,r),i=this.createShader(this.gl.FRAGMENT_SHADER,n);this.program=this.createProgram(s,i),this.gl.useProgram(this.program),this.positionLoc=this.gl.getAttribLocation(this.program,"a_position"),this.texCoordLoc=this.gl.getAttribLocation(this.program,"a_texCoord"),this.resolutionLoc=this.gl.getUniformLocation(this.program,"u_resolution"),this.videoSizeLoc=this.gl.getUniformLocation(this.program,"u_videoSize"),this.textureLoc=this.gl.getUniformLocation(this.program,"u_image"),this.positionBuffer=this.gl.createBuffer(),this.texCoordBuffer=this.gl.createBuffer(),this.videoTexture=this.gl.createTexture(),this.fbo=this.gl.createFramebuffer(),this.outTex=this.gl.createTexture(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,0,this.OUT_WIDTH,0,0,this.OUT_HEIGHT,0,this.OUT_HEIGHT,this.OUT_WIDTH,0,this.OUT_WIDTH,this.OUT_HEIGHT]),this.gl.STATIC_DRAW),this.gl.enableVertexAttribArray(this.positionLoc),this.gl.vertexAttribPointer(this.positionLoc,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.texCoordBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),this.gl.STATIC_DRAW),this.gl.enableVertexAttribArray(this.texCoordLoc),this.gl.vertexAttribPointer(this.texCoordLoc,2,this.gl.FLOAT,!1,0,0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.outTex),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.NEAREST),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.NEAREST),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.OUT_WIDTH,this.OUT_HEIGHT,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this.fbo),this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER,this.gl.COLOR_ATTACHMENT0,this.gl.TEXTURE_2D,this.outTex,0)}createShader(e,r){const n=this.gl.createShader(e);if(this.gl.shaderSource(n,r),this.gl.compileShader(n),!this.gl.getShaderParameter(n,this.gl.COMPILE_STATUS)){const s=this.gl.getShaderInfoLog(n);throw this.gl.deleteShader(n),new Error("Shader compile failed: "+s)}return n}createProgram(e,r){const n=this.gl.createProgram();if(this.gl.attachShader(n,e),this.gl.attachShader(n,r),this.gl.linkProgram(n),!this.gl.getProgramParameter(n,this.gl.LINK_STATUS)){const s=this.gl.getProgramInfoLog(n);throw this.gl.deleteProgram(n),new Error("Program link failed: "+s)}return this.gl.detachShader(n,e),this.gl.detachShader(n,r),this.gl.deleteShader(e),this.gl.deleteShader(r),n}decode(e){const r=e.videoWidth|0,n=e.videoHeight|0;if(r===0||n===0)return null;this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.NEAREST),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.NEAREST),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.canvas.width=this.OUT_WIDTH,this.canvas.height=this.OUT_HEIGHT,this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this.fbo),this.gl.viewport(0,0,this.OUT_WIDTH,this.OUT_HEIGHT),this.gl.useProgram(this.program),this.resolutionLoc&&this.gl.uniform2f(this.resolutionLoc,this.OUT_WIDTH,this.OUT_HEIGHT),this.videoSizeLoc&&this.gl.uniform2f(this.videoSizeLoc,r,n),this.textureLoc&&this.gl.uniform1i(this.textureLoc,0),this.gl.drawArrays(this.gl.TRIANGLES,0,6);const s=new Uint8Array(this.OUT_WIDTH*this.OUT_HEIGHT*4);this.gl.readPixels(0,0,this.OUT_WIDTH,this.OUT_HEIGHT,this.gl.RGBA,this.gl.UNSIGNED_BYTE,s);const i=s[0],o=s[4],a=s[8],c=s[12],d=Math.floor(c/2),l=c%2===1?"_1":"",u=("0"+i).slice(-2),f=("0"+o).slice(-2),p=("0"+a).slice(-2),h=("0"+d).slice(-2);return`${u}_${f}_${p}_${h}${l}`}decodeFromImageBitmap(e){const r=e.width|0,n=e.height|0;if(r===0||n===0)return null;this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.NEAREST),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.NEAREST),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.canvas.width=this.OUT_WIDTH,this.canvas.height=this.OUT_HEIGHT,this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this.fbo),this.gl.viewport(0,0,this.OUT_WIDTH,this.OUT_HEIGHT),this.gl.useProgram(this.program),this.resolutionLoc&&this.gl.uniform2f(this.resolutionLoc,this.OUT_WIDTH,this.OUT_HEIGHT),this.videoSizeLoc&&this.gl.uniform2f(this.videoSizeLoc,r,n),this.textureLoc&&this.gl.uniform1i(this.textureLoc,0),this.gl.drawArrays(this.gl.TRIANGLES,0,6);const s=new Uint8Array(this.OUT_WIDTH*this.OUT_HEIGHT*4);this.gl.readPixels(0,0,this.OUT_WIDTH,this.OUT_HEIGHT,this.gl.RGBA,this.gl.UNSIGNED_BYTE,s);const i=s[0],o=s[4],a=s[8],c=s[12],d=Math.floor(c/2),l=c%2===1?"_1":"",u=("0"+i).slice(-2),f=("0"+o).slice(-2),p=("0"+a).slice(-2),h=("0"+d).slice(-2);return`${u}_${f}_${p}_${h}${l}`}dispose(){this.videoTexture&&this.gl.deleteTexture(this.videoTexture),this.outTex&&this.gl.deleteTexture(this.outTex),this.fbo&&this.gl.deleteFramebuffer(this.fbo),this.positionBuffer&&this.gl.deleteBuffer(this.positionBuffer),this.texCoordBuffer&&this.gl.deleteBuffer(this.texCoordBuffer),this.program&&this.gl.deleteProgram(this.program)}}const pe=class pe{constructor(e){if(this.platformSupported=!0,this.firstFrameTimecodeSet=!1,this.firstFrameTimecode=[0,0,0,0,0],this.firstVideoFrameCallbackFired=!1,this.isMKAdPlaying=!1,this.loggerTimeoutStart=0,this.loggerTimeout=1e4,this.lastStatusUpdate=0,this.STATUS_UPDATE_INTERVAL=100,this.resumedAt=0,this.SKIP_PROCESSING_AFTER_RESUME_MS=1e3,this.afData={counter:0,lastTimestamp:0,previousTimestamp:0,lastMetadataNow:0,timeFromLastRVFC:0,animationFPS:0,playerTimeOffset:0,lastPlayerTimeFromSync:0,lastCalculatedPlayerTimeVideoFrame:0,lastCalculatedPlayerTimeFraction:0,previousCalculatedPlayerTimeFraction:2},this.vfcData={counter:0,lastTimestamp:0,previousTimestamp:0,timeFromLastRAF:0,videoFPS:0,lastFrameMetadata:null,lastFrameMetadataNow:0,storedMetadata:[],timePerformanceNowToExpectedDisplayTime:0,timeRVFCnowToExpectedDisplayTime:0,mediaTimeOffset:0,lastMediaTimeFromSync:0,lastCalculatedMediaTimeVideoFrame:0},this.siData={counter:0,lastTimestamp:0,lastOffset:0,timeFromLastRAF:0,timeFromLastRVFC:0,lastSeenRAFCount:0,lastSeenRVFCCount:0,isRAFSeen:!1,isRVFCSeen:!1,isVideoPaused:!0,workingFps:0,refreshRate:0,RVFCmissed:0,RVFCframeExpected:0,expectedRefreshRate:0,avgExpectedRefreshRate:0,newRefreshRateFrames:0,expectedFPS:0,newFPSFrames:0,RVFCpattern:[],isRVFCpatternDetected:!1,patternTracking:[],patternTrackingIndex:-1,patternNextValue:-1,possibilityTracking:[],previousPossibilityValue:-1,lastCallback:null,lastCalculatedFrame:0,lastRendererFrameSent:0,lastMessageSent:"",compensationMode:!1,compensationCounter:0,frameCorrection:0,determineFramesIntervals:[],determineAFIntervals:[],expectedDisplayTimeReminder:0,animationFramesToDisplayTime:0},this.tcTimeStamp=0,this.timecode_offset=0,this.burnedLastTcKey=-1,this.sampleBurnedFrame=async()=>{var r;if(!(!this.OTTPlayer||!this.video)&&!(this.video.videoWidth===0||this.video.videoHeight===0)&&this.gl2Decoder)try{let n=await createImageBitmap(this.video);const s=this.gl2Decoder.decodeFromImageBitmap(n);if(!s){try{n.close()}catch{}return}const i=this.parseTcKey(s);if(i<=this.burnedLastTcKey){try{n.close()}catch{}return}this.burnedLastTcKey=i,this.metrics&&this.metrics.updateMetric("Last sent timecode",s),(r=this.OTTPlayer.clocker)==null||r.callRendererWorkerWithFrame(n,s),n=void 0}catch(n){this.logger.error("[Adapter] sampleBurnedFrame error: "+n)}},this.onAnimationFrame=r=>{if(this.video.paused||!this.OTTPlayer.clocker||!this.OTTPlayer.gameParams||!this.syncPoint){this.animationFrameLoopId=window.requestAnimationFrame(this.onAnimationFrame);return}this.afData.counter++,this.afData.previousTimestamp=this.afData.lastTimestamp,this.afData.lastTimestamp=performance.now(),this.afData.lastMetadataNow=r,this.afData.timeFromLastRVFC=this.afData.lastTimestamp-this.vfcData.lastTimestamp,this.afData.animationFPS=this.OTTPlayer.clocker.animationFPScalculator.getPerciseFPS(),this.siData.lastCallback=="RAF"&&this.siData.RVFCmissed++,this.siData.lastCallback="RAF";const n=(this.video.currentTime-this.syncPoint.playerTime)*(6e4/1001);this.afData.lastPlayerTimeFromSync=n;const s=Math.floor(n)+this.syncPoint.frame;this.afData.playerTimeOffset=L.calculateCurrentOffset(s,this.OTTPlayer.gameParams.offsets);let i=s-this.afData.playerTimeOffset;if(i<0&&(i+=5178816),i++,this.afData.lastCalculatedPlayerTimeVideoFrame=i,this.afData.previousCalculatedPlayerTimeFraction=this.afData.lastCalculatedPlayerTimeFraction,this.afData.lastCalculatedPlayerTimeFraction=n-Math.floor(n),this.metrics)try{this.metrics.updateMetric("RAF calls",this.afData.counter),this.metrics.updateMetric("Last player time",this.video.currentTime.toFixed(4)),this.metrics.updateMetric("Last player time frame",this.afData.lastCalculatedPlayerTimeVideoFrame),this.metrics.updateMetric("Last player time fraction",this.afData.lastCalculatedPlayerTimeFraction.toFixed(4)),this.metrics.updateMetric("Last player time double frame",this.afData.lastPlayerTimeFromSync.toFixed(5)),this.metrics.updateMetric("AF metadata now - perf.now()",(this.afData.lastTimestamp-this.afData.lastMetadataNow).toFixed(3)),this.metrics.updateMetric("VF ExpDispTime - AF metadata now",(this.afData.lastTimestamp-this.vfcData.lastFrameMetadata.expectedDisplayTime).toFixed(3)),this.metrics.updateMetric("Last RAF call",this.afData.lastTimestamp.toFixed(2)),this.metrics.updateMetric("RAF - RVFC dif",this.afData.timeFromLastRVFC.toFixed(2))}catch(o){this.options&&_(this.options,"Adapter")&&console.error(o)}this.animationFrameLoopId=window.requestAnimationFrame(this.onAnimationFrame),this.determineFrameUpdate()},this.onVideoFrame=(r,n)=>{if(this.firstVideoFrameCallbackFired||(this.firstVideoFrameCallbackFired=!0,this.logger.info("[Adapter] First video frame callback fired"),console.log("[Adapter] First video frame callback fired")),this.video.paused||!this.OTTPlayer.clocker||!this.OTTPlayer.gameParams||!this.syncPoint){this.videoFrameCallbackLoopId=this.video.requestVideoFrameCallback(this.onVideoFrame);return}this.vfcData.counter++,this.vfcData.previousTimestamp=this.vfcData.lastTimestamp,this.vfcData.lastTimestamp=performance.now(),this.vfcData.timeFromLastRAF=this.vfcData.lastTimestamp-this.afData.lastTimestamp,this.siData.RVFCmissed=0,this.vfcData.videoFPS=this.OTTPlayer.clocker.videoFPScalculator.getPerciseFPS(),this.siData.lastCallback="RVFC";const s=(n.mediaTime-this.syncPoint.playerTime)*(6e4/1001);this.vfcData.lastMediaTimeFromSync=s;const i=Math.floor(s+.1)+this.syncPoint.frame;this.vfcData.mediaTimeOffset=L.calculateCurrentOffset(i,this.OTTPlayer.gameParams.offsets);let o=i-this.vfcData.mediaTimeOffset;o<0&&(o+=5178816),o++,this.vfcData.lastCalculatedMediaTimeVideoFrame=o,this.vfcData.lastFrameMetadata=n,this.vfcData.storedMetadata.push(n),this.vfcData.storedMetadata.length>10&&this.vfcData.storedMetadata.shift(),this.vfcData.timePerformanceNowToExpectedDisplayTime=n.expectedDisplayTime-this.vfcData.lastTimestamp,this.vfcData.timeRVFCnowToExpectedDisplayTime=n.expectedDisplayTime-r,this.vfcData.lastFrameMetadataNow=r,this.metrics&&(this.metrics.updateMetric("MediaTime",n.mediaTime),this.metrics.updateMetric("MediaTimeWithSync",i),this.metrics.updateMetric("RVFC calls",this.vfcData.counter),this.metrics.updateMetric("Last metadata media time",n.mediaTime.toFixed(4)),this.metrics.updateMetric("Last metadata media time frame",this.vfcData.lastCalculatedMediaTimeVideoFrame),this.metrics.updateMetric("Time to presentation time",(n.presentationTime-r).toFixed(4)),this.metrics.updateMetric("Metadata presented frames",n.presentedFrames),this.metrics.updateMetric("Metadata processing duration",n.processingDuration),this.metrics.updateMetric("Last media time double frame",this.vfcData.lastMediaTimeFromSync.toFixed(5)),this.metrics.updateMetric("VF metadata now - perf.now()",(this.afData.lastTimestamp-this.afData.lastMetadataNow).toFixed(3)),this.metrics.updateMetric("RVFC to expected display time",this.vfcData.timeRVFCnowToExpectedDisplayTime.toFixed(4)),this.metrics.updateMetric("Performance Now to expected display time",this.vfcData.timePerformanceNowToExpectedDisplayTime.toFixed(4)),this.metrics.updateMetric("Last RVFC call",this.vfcData.lastTimestamp.toFixed(2))),this.videoFrameCallbackLoopId=this.video.requestVideoFrameCallback(this.onVideoFrame),this.determineFrameUpdate()},this.determineFrameUpdate=()=>{var n,s,i,o;if(!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;this.siData.counter===0&&this.logger.info("didStartAugmentation"),this.siData.counter++,this.siData.isVideoPaused=this.video.paused,this.siData.isRAFSeen=this.siData.lastSeenRAFCount==this.afData.counter,this.siData.isRVFCSeen=this.siData.lastSeenRVFCCount==this.vfcData.counter,this.siData.lastTimestamp=performance.now(),this.siData.timeFromLastRAF=this.siData.lastTimestamp-this.afData.lastTimestamp,this.siData.timeFromLastRVFC=this.siData.lastTimestamp-this.vfcData.lastTimestamp,this.siData.lastSeenRAFCount=this.afData.counter,this.siData.lastSeenRVFCCount=this.vfcData.counter,this.siData.workingFps=this.OTTPlayer.clocker.videoFPScalculator.getFPS(),this.siData.refreshRate=this.OTTPlayer.clocker.animationFPScalculator.getPerciseFPS();const r=this.siData.lastTimestamp;if(this.OTTPlayer.statusOverlay&&r-this.lastStatusUpdate>this.STATUS_UPDATE_INTERVAL&&(this.updateStatusOverlay(),this.lastStatusUpdate=r),!this.OTTPlayer.options.ADAPTER_RUN_IN_WORKER)this.platformSpecificFrameUpdate();else{const a={siData:this.siData,vfcData:this.vfcData,afData:this.afData,debugControls:(n=this.debugControls)==null?void 0:n.exportData(),zipBaseURL:this.OTTPlayer.options.zipBaseURL,adsBaseURL:this.OTTPlayer.options.adsBaseURL,bucketName:((s=this.OTTPlayer.gameParams)==null?void 0:s.bucketName)||"",offsets:((i=this.OTTPlayer.gameParams)==null?void 0:i.offsets)||[],customerId:((o=this.OTTPlayer.gameParams)==null?void 0:o.customerId)||""};this.OTTPlayer.clocker.callAdapterWorker(a)}},this.determineFrameUpdateChromeMac=()=>{if(this.resumedAt>0&&performance.now()-this.resumedAt<this.SKIP_PROCESSING_AFTER_RESUME_MS)return;const r=Math.round(1e3/this.vfcData.timeRVFCnowToExpectedDisplayTime);r>0&&r<500&&(this.expectedRefreshRateCalculator.addFrameDuration(this.vfcData.timeRVFCnowToExpectedDisplayTime/1e3),Math.abs(this.siData.expectedRefreshRate-r)>4?this.siData.newRefreshRateFrames++:(this.siData.expectedRefreshRate=r,this.siData.avgExpectedRefreshRate=this.expectedRefreshRateCalculator.getPerciseFPS(),this.siData.newRefreshRateFrames=0),this.siData.newRefreshRateFrames>10&&(this.siData.newRefreshRateFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedRefreshRate=r,this.siData.isRVFCpatternDetected=!1));const n=this.OTTPlayer.clocker.videoFPScalculator.getPerciseFPS();if(n>0&&n<500&&(Math.abs(this.siData.expectedFPS-n)>4?this.siData.newFPSFrames++:(this.siData.expectedFPS=n,this.siData.newFPSFrames=0),this.siData.newFPSFrames>10&&(this.siData.newFPSFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedFPS=n,this.siData.isRVFCpatternDetected=!1)),this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;const s=20,i=1e3;if(!this.siData.isRVFCSeen){const o=Math.round(this.vfcData.timeRVFCnowToExpectedDisplayTime/(1e3/this.afData.animationFPS));if(o<=0&&this.siData.patternTracking.length<=1-o){this.siData.patternTracking=[!0];for(let a=0;a<1-o;a++)this.siData.patternTracking.push(!1)}else o<=1&&(this.siData.patternTracking[this.siData.patternTracking.length-2+o]=!0)}if(this.siData.isRAFSeen||this.siData.patternTracking.push(!1),this.siData.patternTracking.length>i&&this.siData.patternTracking.shift(),!this.siData.isRVFCpatternDetected){const o=this.siData.patternTracking;for(let a=1;a*s<=o.length;a++){for(let c=0;c+a*s<=o.length;c++){let d=!0;for(let l=0;l<s-1;l++){const u=o.slice(c+l*a,c+(l+1)*a),f=o.slice(c+(l+1)*a,c+(l+2)*a);if(!u.every((p,h)=>p===f[h])){d=!1;break}}if(d){const l=o.slice(c,c+a),u=l.every(h=>!h),f=l.every(h=>h),p=this.afData.animationFPS-this.vfcData.videoFPS;if(u||f&&p>5)continue;this.siData.RVFCpattern=l,this.siData.isRVFCpatternDetected=!0;break}}if(this.siData.isRVFCpatternDetected)break}}if(this.siData.RVFCpattern.length>0){const o=this.siData.RVFCpattern,a=this.siData.patternTracking;let c=-1;for(let d=a.length-o.length;d>=0;d--){let l=!0;for(let u=0;u<o.length;u++)if(o[u]!==a[d+u]){l=!1;break}if(l){c=d;break}}if(c>=0){const d=(a.length-c)%o.length,l=o[d];this.siData.patternTrackingIndex=d,this.siData.patternNextValue=l?1:0}if(a.length>=o.length*5){a.slice(a.length-o.length*5);let d=0,l=0;for(let u=0;u+o.length<=a.length;u++)a.slice(u,u+o.length).every((p,h)=>p===o[h])?(d++,l=Math.max(l,d),u+=o.length-1):d=0;l<6&&(this.siData.isRVFCpatternDetected=!1)}Math.abs(this.siData.avgExpectedRefreshRate-this.siData.refreshRate)>3&&(this.siData.isRVFCpatternDetected=!1)}if(this.metrics){performance.now();const o=[this.afData.lastTimestamp,this.vfcData.lastTimestamp,this.afData.previousTimestamp,this.vfcData.previousTimestamp].sort((l,u)=>u-l),a=o[0],c=o[1],d=a-c;this.siData.determineFramesIntervals||(this.siData.determineFramesIntervals=[]),this.siData.determineFramesIntervals.push(d.toFixed(2)),this.siData.determineFramesIntervals.length>10&&this.siData.determineFramesIntervals.shift(),this.metrics.updateMetric("Determine frames intervals",this.siData.determineFramesIntervals.join(", ")),this.metrics.updateMetric("RVFC missed",this.siData.RVFCmissed),this.metrics.updateMetric("Pattern found",this.siData.isRVFCpatternDetected),this.metrics.updateMetric("Pattern array",this.siData.RVFCpattern.map(l=>l?1:0).join("")),this.metrics.updateMetric("Pattern next index",this.siData.patternTrackingIndex),this.metrics.updateMetric("Pattern tracking",this.siData.patternTracking.slice(this.siData.patternTracking.length>100?this.siData.patternTracking.length-100:0).map(l=>l?1:0).join("")),this.metrics.updateMetric("Pattern next value",this.siData.patternNextValue),this.metrics.updateMetric("Refresh rate",this.siData.refreshRate.toFixed(2)),this.metrics.updateMetric("Expected Refresh Rate",this.siData.expectedRefreshRate),this.metrics.updateMetric("Avg Expected Refresh Rate",this.siData.avgExpectedRefreshRate.toFixed(2)),this.metrics.updateMetric("New Refresh Rate Frames",this.siData.newRefreshRateFrames)}if(!this.siData.isRAFSeen&&this.siData.isRVFCpatternDetected){let o=0,a=1,c=5;if(this.debugControls){const d=parseInt(this.debugControls.getValue("Pattern offset"),10);isNaN(d)||(o=d);const l=parseInt(this.debugControls.getValue("Frame Correction"),10);isNaN(l)||(a=l);const u=parseInt(this.debugControls.getValue("Timeout time"),10);isNaN(u)||(c=u)}this.siData.lastOffset!=this.vfcData.mediaTimeOffset&&(this.siData.lastOffset=this.vfcData.mediaTimeOffset,this.logger.info("didChangeOffset",{offset:this.vfcData.mediaTimeOffset}),this.logger.setAttributes({last_offset:this.vfcData.mediaTimeOffset})),this.siData.RVFCpattern[(this.siData.patternTrackingIndex+this.siData.RVFCpattern.length-1+o)%this.siData.RVFCpattern.length]?setTimeout(()=>this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+a),c):this.callRenderer(this.siData.lastRendererFrameSent)}},this.determineFrameUpdateChromeWin=()=>{if(this.resumedAt>0&&performance.now()-this.resumedAt<this.SKIP_PROCESSING_AFTER_RESUME_MS)return;const r=Math.round(1e3/this.vfcData.timeRVFCnowToExpectedDisplayTime);r>0&&r<500&&(this.expectedRefreshRateCalculator.addFrameDuration(this.vfcData.timeRVFCnowToExpectedDisplayTime/1e3),Math.abs(this.siData.expectedRefreshRate-r)>3?this.siData.newRefreshRateFrames++:(this.siData.expectedRefreshRate=r,this.siData.avgExpectedRefreshRate=this.expectedRefreshRateCalculator.getPerciseFPS()),this.siData.newRefreshRateFrames>10&&(this.siData.newRefreshRateFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedRefreshRate=r,this.siData.isRVFCpatternDetected=!1));const n=this.OTTPlayer.clocker.videoFPScalculator.getPerciseFPS();if(n>0&&n<500&&(Math.abs(this.siData.expectedFPS-n)>4?this.siData.newFPSFrames++:(this.siData.expectedFPS=n,this.siData.newFPSFrames=0),this.siData.newFPSFrames>10&&(this.siData.newFPSFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedFPS=n,this.siData.isRVFCpatternDetected=!1)),this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;const s=20,i=1e3;if(!this.siData.isRVFCSeen){const o=Math.round(this.vfcData.timeRVFCnowToExpectedDisplayTime/(1e3/this.afData.animationFPS));if(o<=0&&this.siData.patternTracking.length<=1-o){this.siData.patternTracking=[!0];for(let a=0;a<1-o;a++)this.siData.patternTracking.push(!1)}else o<=1&&(this.siData.patternTracking[this.siData.patternTracking.length-2+o]=!0)}if(this.siData.isRAFSeen||this.siData.patternTracking.push(!1),this.siData.patternTracking.length>i&&this.siData.patternTracking.shift(),!this.siData.isRVFCpatternDetected){const o=this.siData.patternTracking;for(let a=1;a*s<=o.length;a++){for(let c=0;c+a*s<=o.length;c++){let d=!0;for(let l=0;l<s-1;l++){const u=o.slice(c+l*a,c+(l+1)*a),f=o.slice(c+(l+1)*a,c+(l+2)*a);if(!u.every((p,h)=>p===f[h])){d=!1;break}}if(d){const l=o.slice(c,c+a),u=l.every(h=>!h),f=l.every(h=>h),p=this.afData.animationFPS-this.vfcData.videoFPS;if(u||f&&p>5)continue;this.siData.RVFCpattern=l,this.siData.isRVFCpatternDetected=!0;break}}if(this.siData.isRVFCpatternDetected)break}}if(this.siData.RVFCpattern.length>0){const o=this.siData.RVFCpattern,a=this.siData.patternTracking;let c=-1;for(let d=a.length-o.length;d>=0;d--){let l=!0;for(let u=0;u<o.length;u++)if(o[u]!==a[d+u]){l=!1;break}if(l){c=d;break}}if(c>=0){const d=(a.length-c)%o.length,l=o[d];this.siData.patternTrackingIndex=d,this.siData.patternNextValue=l?1:0}if(a.length>=o.length*5){a.slice(a.length-o.length*5);let d=0,l=0;for(let u=0;u+o.length<=a.length;u++)a.slice(u,u+o.length).every((p,h)=>p===o[h])?(d++,l=Math.max(l,d),u+=o.length-1):d=0;l<6&&(this.siData.isRVFCpatternDetected=!1)}Math.abs(this.siData.avgExpectedRefreshRate-this.siData.refreshRate)>3&&(this.siData.isRVFCpatternDetected=!1)}if(this.metrics){performance.now();const o=[this.afData.lastTimestamp,this.vfcData.lastTimestamp,this.afData.previousTimestamp,this.vfcData.previousTimestamp].sort((l,u)=>u-l),a=o[0],c=o[1],d=a-c;this.siData.determineFramesIntervals||(this.siData.determineFramesIntervals=[]),this.siData.determineFramesIntervals.push(d.toFixed(2)),this.siData.determineFramesIntervals.length>10&&this.siData.determineFramesIntervals.shift(),this.metrics.updateMetric("Determine frames intervals",this.siData.determineFramesIntervals.join(", ")),this.metrics.updateMetric("RVFC missed",this.siData.RVFCmissed),this.metrics.updateMetric("Pattern found",this.siData.isRVFCpatternDetected),this.metrics.updateMetric("Pattern array",this.siData.RVFCpattern.map(l=>l?1:0).join("")),this.metrics.updateMetric("Pattern next index",this.siData.patternTrackingIndex),this.metrics.updateMetric("Pattern tracking",this.siData.patternTracking.slice(this.siData.patternTracking.length>100?this.siData.patternTracking.length-100:0).map(l=>l?1:0).join("")),this.metrics.updateMetric("Pattern next value",this.siData.patternNextValue),this.metrics.updateMetric("Refresh rate",this.siData.refreshRate.toFixed(2)),this.metrics.updateMetric("Expected Refresh Rate",this.siData.expectedRefreshRate),this.metrics.updateMetric("Avg Expected Refresh Rate",this.siData.avgExpectedRefreshRate.toFixed(2)),this.metrics.updateMetric("New Refresh Rate Frames",this.siData.newRefreshRateFrames)}if(!this.siData.isRAFSeen&&this.siData.isRVFCpatternDetected){let o=0,a=2,c=!1;if(this.debugControls){const u=parseInt(this.debugControls.getValue("Pattern offset"),10);isNaN(u)||(o=u);const f=parseInt(this.debugControls.getValue("Frame Correction"),10);isNaN(f)||(a=f),parseInt(this.debugControls.getValue("Timeout time"),10),this.debugControls.getValue("Video Captur Card Mode")==="true"&&(c=!0)}this.siData.lastOffset!=this.vfcData.mediaTimeOffset&&(this.siData.lastOffset=this.vfcData.mediaTimeOffset,this.logger.info("didChangeOffset",{offset:this.vfcData.mediaTimeOffset}),this.logger.setAttributes({last_offset:this.vfcData.mediaTimeOffset})),c&&(o+=1);const d=(this.siData.patternTrackingIndex+this.siData.RVFCpattern.length-1+o)%this.siData.RVFCpattern.length,l=(d+this.siData.RVFCpattern.length-1)%this.siData.RVFCpattern.length;if(this.siData.RVFCpattern[d]){let u=0;c&&this.siData.lastRendererFrameSent==this.vfcData.lastCalculatedMediaTimeVideoFrame&&this.siData.RVFCpattern[l]&&(u=2),this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+u+a)}}},this.determineFrameUpdateSifariMac=()=>{if(this.resumedAt>0&&performance.now()-this.resumedAt<this.SKIP_PROCESSING_AFTER_RESUME_MS||(this.siData.expectedRefreshRate&&this.siData.expectedFPS&&(this.expectedRefreshRateCalculator.addFrameDuration(1/this.siData.refreshRate),this.siData.avgExpectedRefreshRate=this.expectedRefreshRateCalculator.getPerciseFPS(),Math.abs(this.siData.expectedRefreshRate-this.siData.avgExpectedRefreshRate)>3&&this.siData.newRefreshRateFrames++,Math.abs(this.siData.expectedFPS-this.siData.workingFps)>3&&this.siData.newFPSFrames++,(this.siData.newRefreshRateFrames>10||this.siData.newFPSFrames>10)&&(this.siData.newRefreshRateFrames=0,this.siData.expectedRefreshRate=0,this.siData.newFPSFrames=0,this.siData.expectedFPS=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.isRVFCpatternDetected=!1)),this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata))return;const r=Math.abs(this.siData.refreshRate-this.siData.workingFps)<2?8:20,n=1e3,s=[this.afData.lastTimestamp,this.vfcData.lastTimestamp,this.afData.previousTimestamp,this.vfcData.previousTimestamp].sort((h,m)=>m-h),i=2,o=s[0],a=s[1],c=o-a,d=1e3/this.afData.animationFPS,l=Math.round(d/4+.1),u=this.vfcData.timeRVFCnowToExpectedDisplayTime;if(this.siData.isRVFCSeen)this.metrics;else{const h=(-u-l)/d,m=Math.ceil(h),g=(Math.round(h)-h)*d,S=Math.abs(g)<=i,E=g<=0?m-1:m+1,A=Math.abs(-u-l)<=i;if(this.metrics&&(this.metrics.updateMetric("Is Smoothing Needed",S),this.metrics.updateMetric("Is More Than Border",m),this.metrics.updateMetric("Is Smoothed",E)),S&&!A){const w=Math.min(m,E),R=Math.max(m,E);this.metrics&&this.metrics.updateMetric("Pssblty next index",""+w+" "+R),this.siData.possibilityTracking[this.siData.possibilityTracking.length-w]=2,this.siData.possibilityTracking[this.siData.possibilityTracking.length-R]=1}else S&&A&&(this.metrics&&this.metrics.updateMetric("Pssblty next index","min"),this.siData.possibilityTracking[this.siData.possibilityTracking.length-1]=1,this.siData.possibilityTracking.push(2),this.siData.possibilityTracking.push(3));if(-u<l)this.siData.expectedDisplayTimeReminder=-u;else if(c>d&&-u-(c-d)<=l)this.siData.expectedDisplayTimeReminder=-u-(c-d);else{let w=-u-c,R=0,v=this.siData.determineFramesIntervals.length-1;for(let F=this.siData.determineAFIntervals.length-1;F>=0&&(v--,!(this.siData.determineAFIntervals[F]>d&&w-(this.siData.determineAFIntervals[F]-d)<=l||w<=l||this.siData.determineFramesIntervals[v].includes("vf")&&this.siData.workingFps<40));F--)w-=this.siData.determineAFIntervals[F],R+=1;if(this.siData.patternTracking.length<R+1){this.siData.patternTracking=[!0];for(let F=0;F<R;F++)this.siData.patternTracking.push(!1)}else this.siData.patternTracking[this.siData.patternTracking.length-1-R]=!0;this.siData.animationFramesToDisplayTime=R}}if(this.siData.isRAFSeen||(this.siData.expectedDisplayTimeReminder?(this.siData.expectedDisplayTimeReminder-l,this.siData.expectedDisplayTimeReminder+c<=l?(this.siData.patternTracking.push(!0),this.siData.animationFramesToDisplayTime=0):(this.siData.patternTracking[this.siData.patternTracking.length-1]=!0,this.siData.patternTracking.push(!1),this.siData.animationFramesToDisplayTime=1),this.siData.expectedDisplayTimeReminder=0):(this.siData.patternTracking.push(!1),this.siData.animationFramesToDisplayTime+=1),this.siData.possibilityTracking[this.siData.possibilityTracking.length-1]==3?this.siData.possibilityTracking.pop():this.siData.possibilityTracking.push(0)),this.siData.patternTracking.length>n&&this.siData.patternTracking.shift(),this.siData.possibilityTracking.length>n&&this.siData.possibilityTracking.shift(),!this.siData.isRVFCpatternDetected){const h=this.siData.patternTracking;for(let m=1;m*r<=h.length;m++){for(let g=0;g+m*r<=h.length;g++){let S=!0;for(let b=0;b<r-1;b++){const E=h.slice(g+b*m,g+(b+1)*m),A=h.slice(g+(b+1)*m,g+(b+2)*m);if(!E.every((w,R)=>w===A[R])){S=!1;break}}if(S){const b=h.slice(g,g+m),E=b.every(R=>!R),A=b.every(R=>R),w=this.afData.animationFPS-this.vfcData.videoFPS;if(E||A&&w>5)continue;this.siData.RVFCpattern=b,this.siData.isRVFCpatternDetected=!0;break}}if(this.siData.isRVFCpatternDetected){this.siData.expectedRefreshRate=this.siData.refreshRate,this.siData.expectedFPS=this.siData.workingFps;break}}}if(this.siData.RVFCpattern.length>0){const h=this.siData.RVFCpattern,m=this.siData.patternTracking;let g=-1;for(let S=m.length-h.length*5;S>=0;S--){let b=!0;for(let E=0;E<h.length*5;E++)if(h[E%h.length]!==m[S+E]){b=!1;break}if(b){g=S;break}}if(g>=0){const S=(m.length-g)%h.length,b=h[S];this.siData.patternTrackingIndex=S,this.siData.patternNextValue=b?1:0}if(m.length>=h.length*5){m.slice(m.length-h.length*5);let S=0,b=0;for(let E=0;E+h.length<=m.length;E++)m.slice(E,E+h.length).every((w,R)=>w===h[R])?(S++,b=Math.max(b,S),E+=h.length-1):S=0;b<6&&(this.siData.isRVFCpatternDetected=!1)}}const f=[];for(let h=1;h<=3;h++)f.push(this.siData.possibilityTracking[this.siData.possibilityTracking.length-this.siData.RVFCpattern.length*h]);const p=Math.max(...f);if(this.metrics){let h="";if(this.siData.isRAFSeen?h="vf: "+c.toFixed(0):h="af: "+c.toFixed(0),this.siData.determineFramesIntervals.push(h),this.siData.determineFramesIntervals.length>10&&this.siData.determineFramesIntervals.shift(),!this.siData.isRAFSeen){const m=this.afData.lastTimestamp-this.afData.previousTimestamp;this.siData.determineAFIntervals.push(m),this.siData.determineAFIntervals.length>10&&this.siData.determineAFIntervals.shift()}this.siData.isRVFCSeen||this.metrics.updateMetric("Last AF to VF time",(this.vfcData.lastTimestamp-this.afData.lastTimestamp).toFixed(0)),this.metrics.updateMetric("Determine frames intervals",this.siData.determineFramesIntervals.join(", ")),this.metrics.updateMetric("AF frames intervals",this.siData.determineAFIntervals.map(m=>m.toFixed(0)).join(", ")),this.metrics.updateMetric("RVFC missed",this.siData.RVFCmissed),this.metrics.updateMetric("Pattern found",this.siData.isRVFCpatternDetected),this.metrics.updateMetric("Pattern array",this.siData.RVFCpattern.map(m=>m?1:0).join("")),this.metrics.updateMetric("Pattern next index",this.siData.patternTrackingIndex),this.metrics.updateMetric("Pattern tracking",this.siData.patternTracking.map(m=>m?1:0).slice(this.siData.patternTracking.length>100?this.siData.patternTracking.length-100:0).join("")),this.metrics.updateMetric("Pattern next value",this.siData.patternNextValue),this.metrics.updateMetric("Pssblty found",this.siData.isRVFCpatternDetected),this.metrics.updateMetric("Pssblty array",this.siData.RVFCpattern.map(m=>m?1:0).join("")),this.metrics.updateMetric("Pssblty tracking",this.siData.possibilityTracking.slice(this.siData.possibilityTracking.length>100?this.siData.possibilityTracking.length-100:0).join("")),this.metrics.updateMetric("Pssblty next value",p),this.metrics.updateMetric("Refresh rate",this.siData.refreshRate.toFixed(2)),this.metrics.updateMetric("Expected Refresh Rate",this.siData.expectedRefreshRate.toFixed(5)),this.metrics.updateMetric("Avg Expected Refresh Rate",this.siData.avgExpectedRefreshRate.toFixed(5)),this.metrics.updateMetric("New Refresh Rate Frames",this.siData.newRefreshRateFrames),this.metrics.updateMetric("AF To Display Time",this.siData.animationFramesToDisplayTime),this.metrics.updateMetric("Call Renderer Reached",!1)}if(!this.siData.isRAFSeen&&this.siData.isRVFCpatternDetected){let h=0,m=0;if(this.debugControls){const S=parseInt(this.debugControls.getValue("Pattern offset"),10);isNaN(S)||(h=S);const b=parseInt(this.debugControls.getValue("Frame Correction"),10);isNaN(b)||(m=b),parseInt(this.debugControls.getValue("Timeout time"),10)}this.siData.lastOffset!=this.vfcData.mediaTimeOffset&&(this.siData.lastOffset=this.vfcData.mediaTimeOffset,this.logger.info("didChangeOffset",{offset:this.vfcData.mediaTimeOffset}),this.logger.setAttributes({last_offset:this.vfcData.mediaTimeOffset}));const g=(this.siData.patternTrackingIndex+this.siData.RVFCpattern.length+h)%this.siData.RVFCpattern.length;if(this.siData.RVFCpattern[g]||p){const S=Math.ceil(this.siData.animationFramesToDisplayTime/this.siData.RVFCpattern.length)+1,b=this.siData.RVFCpattern.map(ke=>ke?1:0).join("").repeat(S),E=(this.siData.RVFCpattern.length-this.siData.patternTrackingIndex)%this.siData.RVFCpattern.length,A=b.slice(0,E==0?-this.siData.RVFCpattern.length:-E);let w=0;const R=this.siData.possibilityTracking.length-1-this.siData.animationFramesToDisplayTime;A[A.length-1-this.siData.animationFramesToDisplayTime]=="0"&&this.siData.possibilityTracking[R]==1&&(w=-1);const v=this.siData.animationFramesToDisplayTime+w,F=v<=0?"":A.slice(-v);let De=F.split("").filter(ke=>ke==="1").length*Math.round(60/this.siData.workingFps);this.siData.workingFps<40&&(De+=1),this.siData.compensationMode&&!(p==2||this.siData.previousPossibilityValue==2)&&(this.siData.compensationCounter=1,this.siData.compensationMode=!1),this.siData.compensationCounter==1?this.siData.possibilityTracking.slice(-5).every(ke=>ke===0)&&(this.siData.compensationCounter-=.1):this.siData.compensationCounter>0&&this.siData.compensationCounter<1&&(this.siData.compensationCounter=Math.max(this.siData.compensationCounter-.1,0)),p==1?this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+De+m-1,this.siData.compensationCounter):p==2&&this.siData.previousPossibilityValue==1?this.callRenderer(this.siData.lastRendererFrameSent+1,this.siData.compensationCounter):this.siData.RVFCpattern[g]&&((p==2||this.siData.previousPossibilityValue==2)&&Math.abs(this.afData.animationFPS-this.siData.workingFps)<5&&this.siData.lastRendererFrameSent==this.vfcData.lastCalculatedMediaTimeVideoFrame+De+m?(this.callRenderer(this.siData.lastRendererFrameSent+1,this.siData.compensationCounter),this.siData.compensationMode=!0):this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+De+m,this.siData.compensationCounter)),this.metrics&&(this.metrics.updateMetric("Call Renderer Reached",!0),this.metrics.updateMetric("Is Smoothing Needed",this.siData.compensationMode),this.metrics.updateMetric("Correction",De),this.metrics.updateMetric("Compensation Counter",this.siData.compensationCounter),this.metrics.updateMetric("Repeated Pattern",b),this.metrics.updateMetric("Trimmed Pattern",A),this.metrics.updateMetric("Sliced Pattern",F),this.metrics.updateMetric("AF To Display Time Correction",w)),this.siData.previousPossibilityValue=p}else this.callRenderer(this.siData.lastRendererFrameSent)}},this.determineFrameUpdateFirefoxMac=()=>{if(this.resumedAt>0&&performance.now()-this.resumedAt<this.SKIP_PROCESSING_AFTER_RESUME_MS)return;const r=Math.round(1e3/this.vfcData.timeRVFCnowToExpectedDisplayTime);if(r>0&&r<500&&(this.expectedRefreshRateCalculator.addFrameDuration(this.vfcData.timeRVFCnowToExpectedDisplayTime/1e3),Math.abs(this.siData.expectedRefreshRate-r)>3?this.siData.newRefreshRateFrames++:(this.siData.expectedRefreshRate=r,this.siData.avgExpectedRefreshRate=this.expectedRefreshRateCalculator.getPerciseFPS()),this.siData.newRefreshRateFrames>10&&(this.siData.newRefreshRateFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedRefreshRate=r,this.siData.isRVFCpatternDetected=!1)),this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;const n=5,s=1e3;if(!this.siData.isRVFCSeen){const i=Math.round(this.vfcData.timeRVFCnowToExpectedDisplayTime/(1e3/this.afData.animationFPS));if(i<=0&&this.siData.patternTracking.length<=1-i){this.siData.patternTracking=[!0];for(let o=0;o<1-i;o++)this.siData.patternTracking.push(!1)}else i<=1&&(this.siData.patternTracking[this.siData.patternTracking.length-2+i]=!0)}if(this.siData.isRAFSeen||this.siData.patternTracking.push(!1),this.siData.patternTracking.length>s&&this.siData.patternTracking.shift(),!this.siData.isRVFCpatternDetected){const i=this.siData.patternTracking;for(let o=1;o*n<=i.length;o++){for(let a=0;a+o*n<=i.length;a++){let c=!0;for(let d=0;d<n-1;d++){const l=i.slice(a+d*o,a+(d+1)*o),u=i.slice(a+(d+1)*o,a+(d+2)*o);if(!l.every((f,p)=>f===u[p])){c=!1;break}}if(c){const d=i.slice(a,a+o),l=d.every(p=>!p),u=d.every(p=>p),f=this.afData.animationFPS-this.vfcData.videoFPS;if(l||u&&f>5)continue;this.siData.RVFCpattern=d,this.siData.isRVFCpatternDetected=!0;break}}if(this.siData.isRVFCpatternDetected)break}}if(this.siData.RVFCpattern.length>0){const i=this.siData.RVFCpattern,o=this.siData.patternTracking;let a=-1;for(let c=o.length-i.length;c>=0;c--){let d=!0;for(let l=0;l<i.length;l++)if(i[l]!==o[c+l]){d=!1;break}if(d){a=c;break}}if(a>=0){const c=(o.length-a)%i.length,d=i[c];this.siData.patternTrackingIndex=c,this.siData.patternNextValue=d?1:0}if(o.length>=i.length*5){o.slice(o.length-i.length*5);let c=0,d=0;for(let l=0;l+i.length<=o.length;l++)o.slice(l,l+i.length).every((f,p)=>f===i[p])?(c++,d=Math.max(d,c),l+=i.length-1):c=0;d<5&&(this.siData.isRVFCpatternDetected=!1)}Math.abs(this.siData.avgExpectedRefreshRate-this.siData.refreshRate)>3&&(this.siData.isRVFCpatternDetected=!1)}if(this.metrics){performance.now();const i=[this.afData.lastTimestamp,this.vfcData.lastTimestamp,this.afData.previousTimestamp,this.vfcData.previousTimestamp].sort((d,l)=>l-d),o=i[0],a=i[1],c=o-a;this.siData.determineFramesIntervals||(this.siData.determineFramesIntervals=[]),this.siData.determineFramesIntervals.push(c.toFixed(2)),this.siData.determineFramesIntervals.length>10&&this.siData.determineFramesIntervals.shift(),this.metrics.updateMetric("Determine frames intervals",this.siData.determineFramesIntervals.join(", ")),this.metrics.updateMetric("RVFC missed",this.siData.RVFCmissed),this.metrics.updateMetric("Pattern found",this.siData.isRVFCpatternDetected),this.metrics.updateMetric("Pattern array",this.siData.RVFCpattern.map(d=>d?1:0).join("")),this.metrics.updateMetric("Pattern next index",this.siData.patternTrackingIndex),this.metrics.updateMetric("Pattern tracking",this.siData.patternTracking.slice(this.siData.patternTracking.length>100?this.siData.patternTracking.length-100:0).map(d=>d?1:0).join("")),this.metrics.updateMetric("Pattern next value",this.siData.patternNextValue),this.metrics.updateMetric("Refresh rate",this.siData.refreshRate.toFixed(2)),this.metrics.updateMetric("Expected Refresh Rate",this.siData.expectedRefreshRate),this.metrics.updateMetric("Avg Expected Refresh Rate",this.siData.avgExpectedRefreshRate.toFixed(2)),this.metrics.updateMetric("New Refresh Rate Frames",this.siData.newRefreshRateFrames)}if(!this.siData.isRAFSeen&&this.siData.isRVFCpatternDetected){let i=0,o=1;if(this.debugControls){const a=parseInt(this.debugControls.getValue("Pattern offset"),10);isNaN(a)||(i=a);const c=parseInt(this.debugControls.getValue("Frame Correction"),10);isNaN(c)||(o=c),parseInt(this.debugControls.getValue("Timeout time"),10)}if(this.siData.lastOffset!=this.vfcData.mediaTimeOffset&&(this.siData.lastOffset=this.vfcData.mediaTimeOffset,this.logger.info("didChangeOffset",{offset:this.vfcData.mediaTimeOffset}),this.logger.setAttributes({last_offset:this.vfcData.mediaTimeOffset})),this.siData.RVFCpattern[(this.siData.patternTrackingIndex+this.siData.RVFCpattern.length-1+i)%this.siData.RVFCpattern.length]){let a=this.vfcData.lastCalculatedMediaTimeVideoFrame+o;a==this.siData.lastRendererFrameSent&&(a+=2),this.callRenderer(a)}else this.callRenderer(this.siData.lastRendererFrameSent)}},this.callRenderer=(r,n)=>{if(!this.OTTPlayer.clocker||!this.OTTPlayer)return;this.siData.lastRendererFrameSent=r,this.metrics&&this.metrics.updateMetric("Last sent frame",r);const s=this.OTTPlayer.clocker.videoFPScalculator.getFPS();this.metrics&&this.metrics.updateMetric("FPS",s.toFixed(2));const i=L.fromFrames(r,6e4/1001);this.renderAugmentation(i,n)},this.playbackTimeDelta=0,this.wallClockTimeDelta=0,this.dateTimeDelta=0,this.renderAugmentation=(r,n)=>{if(!this.OTTPlayer||!this.OTTPlayer.clocker)throw new Error("OTTPlayer is not initialized");const s=L.toStr(r);this.siData.lastMessageSent=s,this.options&&_(this.options,"Adapter")&&console.log(`Rendering augmentation for timecode: ${s} , ${r}`),this.metrics&&this.metrics.updateMetric("Last sent timecode",s),this.OTTPlayer.clocker.callRendererWorker(s,n)},this.onVideoSeeked=()=>{this.firstFrameTimecode=[0,0,0,0,0],this.firstFrameTimecodeSet=!1},this.clearAugmentation=r=>{if(!this.OTTPlayer||!this.OTTPlayer.clocker)throw new Error("OTTPlayer is not initialized");const n=r?L.toStr(r):void 0;this.options&&_(this.options,"Adapter")&&console.log("Clearing augmentation"),this.OTTPlayer.clocker.callRendererWorker(n,0,!0)},this.logger=e.logger,this.OTTPlayer=e,this.options=e.options,this.benchmark=new pn(e.options.BENCHMARK_DURATION_SECONDS),this.options&&_(this.options,"Adapter")&&console.log("Adapter is initialized",this.OTTPlayer),this.video=e.video,this.debug=this.options.debug?this.options.debug.on:!1,this.expectedRefreshRateCalculator=new nt(20),I.isChromeMac())this.platformSpecificFrameUpdate=this.determineFrameUpdateChromeMac;else if(I.isChromeWin())this.platformSpecificFrameUpdate=this.determineFrameUpdateChromeWin;else{I.isSafariMac(),I.isFirefoxMac(),this.platformSpecificFrameUpdate=()=>{},this.logger.error("Unsupported platform: "+this.options.platform+" "+this.options.browserName),console.error("Unsupported platform: "+this.options.platform+" "+this.options.browserName),this.platformSupported=!1;return}if(this.debug){this.metrics=new jt;const r=this.metrics.createContainer(),n=this.metrics.createContainer(),s=this.metrics.createContainer(),i=this.metrics.createContainer(),o=this.metrics.createContainer(),a=this.metrics.createContainer(),c=this.metrics.createContainer(),d=this.metrics.createContainer(),l=this.metrics.createContainer(),u=this.metrics.createContainer(),f=this.metrics.createContainer(),p=this.metrics.createContainer(),h=this.metrics.createContainer(),m=this.metrics.createContainer(),g=this.metrics.createContainer(),S=this.metrics.createContainer();this.metrics.createMetric("tcTimeStamp",r),this.metrics.createMetric("timecodeOffset",r),this.metrics.createMetric("firstFrameTimecode",r),this.metrics.createMetric("frame",n),this.metrics.createMetric("playerTime",n),this.metrics.createMetric("stringTime",n),this.metrics.createMetric("lastUpdate",n),this.metrics.createMetric("MediaTime",s),this.metrics.createMetric("MediaTimeWithSync",s),this.metrics.createMetric("RAF calls",i),this.metrics.createMetric("RVFC calls",i),this.metrics.createMetric("RVFC missed",i),this.metrics.createMetric("Last sent frame",i),this.metrics.createMetric("Last sent timecode",i),this.metrics.createMetric("Last metadata media time",o),this.metrics.createMetric("Last player time",o),this.metrics.createMetric("RVFC to expected display time",o),this.metrics.createMetric("Performance Now to expected display time",o),this.metrics.createMetric("Last metadata media time frame",a),this.metrics.createMetric("Last player time frame",a),this.metrics.createMetric("Last player time fraction",a),this.metrics.createMetric("Last media time double frame",c),this.metrics.createMetric("Last player time double frame",c),this.metrics.createMetric("Compensation Counter",c),this.metrics.createMetric("AF metadata now - perf.now()",d),this.metrics.createMetric("VF metadata now - perf.now()",d),this.metrics.createMetric("VF ExpDispTime - AF metadata now",d),this.metrics.createMetric("Time to presentation time",l),this.metrics.createMetric("Metadata presented frames",l),this.metrics.createMetric("Metadata processing duration",l),this.metrics.createMetric("FPS",u),this.metrics.createMetric("Refresh rate",u),this.metrics.createMetric("Last RAF call",u),this.metrics.createMetric("Last RVFC call",u),this.metrics.createMetric("RAF - RVFC dif",u),this.metrics.createMetric("Determine frames intervals",f),this.metrics.createMetric("Last AF to VF time",p),this.metrics.createMetric("AF frames intervals",p),this.metrics.createMetric("Expected Refresh Rate",h),this.metrics.createMetric("Avg Expected Refresh Rate",h),this.metrics.createMetric("New Refresh Rate Frames",h),this.metrics.createMetric("AF To Display Time",h),this.metrics.createMetric("AF To Display Time Correction",h),this.metrics.createMetric("Call Renderer Reached",h),this.metrics.createMetric("Is Smoothing Needed",m),this.metrics.createMetric("Is More Than Border",m),this.metrics.createMetric("Is Smoothed",m),this.metrics.createMetric("Correction",m),this.metrics.createMetric("Repeated Pattern",m),this.metrics.createMetric("Trimmed Pattern",m),this.metrics.createMetric("Sliced Pattern",m),this.metrics.createMetric("Pattern found",g),this.metrics.createMetric("Pattern array",g),this.metrics.createMetric("Pattern tracking",g),this.metrics.createMetric("Pattern next index",g),this.metrics.createMetric("Pattern next value",g),this.metrics.createMetric("Pssblty found",S),this.metrics.createMetric("Pssblty array",S),this.metrics.createMetric("Pssblty tracking",S),this.metrics.createMetric("Pssblty next index",S),this.metrics.createMetric("Pssblty next value",S),this.debugControls=new un;const b=this.debugControls.createContainer(),E=this.debugControls.createContainer();this.debugControls.createInput("Window Start (ms)",4,b),this.debugControls.createInput("Window End (ms)",-11,b),this.debugControls.createSelect("Pattern offset",{"-5":-5,"-4":-4,"-3":-3,"-2":-2,"-1":-1,0:0,1:1,2:2,3:3,4:4,5:5},"0",b),this.debugControls.createCheckbox("Video Captur Card Mode",!1,b),I.isChromeWin()?this.debugControls.createSelect("Frame Correction",{"-4":-4,"-3":-3,"-2":-2,"-1":-1,0:0,1:1,2:2,3:3,4:4},"2",E):I.isSafariMac()?this.debugControls.createSelect("Frame Correction",{"-4":-4,"-3":-3,"-2":-2,"-1":-1,0:0,1:1,2:2,3:3,4:4},"0",E):this.debugControls.createSelect("Frame Correction",{"-4":-4,"-3":-3,"-2":-2,"-1":-1,0:0,1:1,2:2,3:3,4:4},"1",E),this.debugControls.createSelect("Timeout time",{0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,10:10,11:11,12:12,13:13,14:14,15:15,16:16,17:17,18:18,19:19,20:20},"5",E)}this.platformSupported&&(this.OTTPlayer.video.readyState>=3?this.setupAdapter():this.OTTPlayer.video.addEventListener("canplay",()=>this.setupAdapter(),{once:!0}))}isVideoFpsSupported(e){return e>pe.MIN_SUPPORTED_FPS&&e<=pe.MAX_SUPPORTED_FPS}setupAdapter(){const e=this.video;if(this.options.BURNED_TIMECODES_MODE){this.startBurnedPipeline();return}if(this.debug){const r=typeof wmcsdk<"u"?wmcsdk:wmcPlayer;console.log(r);const n=r.getAvailableVideoQualities(),s={};n.forEach(a=>{s[a.label]=a.id});const i=a=>{r.doSetVideoQuality(a.videoQuality)},o=this.debugControls.createContainer(i);this.debugControls.createSelect("videoQuality",s,n[0].id,o)}this.animationFrameLoopId=window.requestAnimationFrame(this.onAnimationFrame),this.videoFrameCallbackLoopId=e.requestVideoFrameCallback(this.onVideoFrame)}startBurnedPipeline(){this.gl2Decoder=new mn,this.burnedIntervalId=window.setInterval(this.sampleBurnedFrame,33)}stopBurnedPipeline(){this.burnedIntervalId&&(window.clearInterval(this.burnedIntervalId),this.burnedIntervalId=void 0),this.gl2Decoder&&(this.gl2Decoder.dispose(),this.gl2Decoder=void 0),this.burnedLastTcKey=-1}parseTcKey(e){const r=e.split("_");if(r.length<4)return-1;const n=parseInt(r[0],10)||0,s=parseInt(r[1],10)||0,i=parseInt(r[2],10)||0,o=parseInt(r[3],10)||0,a=r.length>=5&&r[4]==="1"?1:0;return((n*3600+s*60+i)*60+o)*2+a}updateStatusOverlay(){var i,o,a;const e=this.OTTPlayer.statusOverlay;e.updateMetric("support","browser",this.platformSupported,`${this.options.browserName} on ${this.options.platform}`),e.updateMetric("support","pattern",this.siData.isRVFCpatternDetected,this.siData.isRVFCpatternDetected?this.siData.RVFCpattern.map(c=>c?"1":"0").join("").slice(0,20):"Detecting...");const r=((i=this.OTTPlayer.clocker)==null?void 0:i.videoFPScalculator.getPerciseFPS())||0,n=this.isVideoFpsSupported(r);e.updateMetric("support","fps",n,r>0?`${r.toFixed(2)} fps`:"Detecting..."),e.updateMetric("support","game_params",!!this.OTTPlayer.gameParams),e.updateMetric("support","mk_ads",!this.isMKAdPlaying,this.isMKAdPlaying?"Ad in progress":"No ads"),this.syncPoint?e.updateMetric("timecode","sync_point",!0,this.syncPoint.stringTime):e.updateMetric("timecode","sync_point",!1,"Not set");const s=this.benchmark.test({gameParams:!!this.OTTPlayer.gameParams,browserSupported:this.platformSupported,patternDetected:this.siData.isRVFCpatternDetected,fpsSupported:n,noMKAdsPlaying:!this.isMKAdPlaying,syncPointSet:!!this.syncPoint});s.shouldClear&&(this.options&&_(this.options,"Adapter")&&console.log("[Benchmark] Failed - clearing augmentation. Reasons:",(o=s.failedConditions)==null?void 0:o.join(", ")),this.clearAugmentation()),e.updateMetric("benchmark","status",s.state,s.state==="TESTING"?`Stability test: ${s.remainingSeconds}s`:s.state==="FAILED"?`Failed: ${(a=s.failedConditions)==null?void 0:a.join(", ")}`:"Stable")}onNewSegmentForMetadata(e){if(!this.firstFrameTimecodeSet){const a=performance.now();a-this.loggerTimeoutStart>this.loggerTimeout&&(this.loggerTimeoutStart=a,this.logger.error("[Adapter] First frame timecode of the recieved segment not set")),console.error("[Adapter] First frame timecode of the recieved segment not set");return}const r=fn(this.firstFrameTimecode,6e4/1001);if(!e.mimeType.includes("video"))return;const n=hn(this.firstFrameTimecode,!0,!0);this.options&&_(this.options,"Adapter")&&console.log("New segment ("+e.url+"): "+n+" ("+r+") playing at "+e.playbackTime);const s=e.playbackTime;s-this.playbackTimeDelta,this.playbackTimeDelta=s;const i=e.wallClockTime/1e3;if(i-this.wallClockTimeDelta,this.wallClockTimeDelta=i,e.dateTime instanceof Date){const a=e.dateTime.getTime()/1e3;a-this.dateTimeDelta,this.dateTimeDelta=a}const o={frame:r,playerTime:s,stringTime:n,lastUpdate:performance.now()};this.syncPoint=o,this.metrics&&(this.metrics.updateMetric("frame",o.frame),this.metrics.updateMetric("playerTime",o.playerTime),this.metrics.updateMetric("stringTime",o.stringTime),this.metrics.updateMetric("lastUpdate",o.lastUpdate)),this.options&&_(this.options,"Adapter")&&console.log("url: "+e.url)}onNewMetadata(e){if(e&&e.metadata&&e.metadata.id==0||I.isSafariMac()){console.log("onNewMetadata: ",e);let r=!1;if(e.metadata.messageData)r=this.processTimedMetadata(e.metadata.messageData,e.metadata.presentationTime);else if(e.metadata.frames&&e.metadata.frames.length&&e.metadata.frames[0].key&&e.metadata.frames[0].key.toLowerCase()==="priv"){const n=e.metadata.frames.filter(s=>s.info&&s.info.toLowerCase().includes("ntc"));if(n.length){const s=`${n[n.length-1].info}\0${String.fromCharCode(...n[n.length-1].data)}`;r=this.processTimedMetadata(s,e.metadata.presentationTime)}}if(r&&(e.metadata.id==0||I.isSafariMac()&&this.timecode_offset==0)){e.metadata.presentationTime*1e3,this.logger.setAttributes({id3_metadata:this.tcTimeStamp-this.timecode_offset});const n=new Date(this.tcTimeStamp-this.timecode_offset);let s=Math.round(n.getUTCMilliseconds()*30*2/1001)/2;const i=s%1;let o=1;i==.5&&(s=Math.floor(s),o=2),this.firstFrameTimecode=[n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),Math.floor(s),o==1?0:1],this.logger.setAttributes({segment_first_frame_timecode:this.firstFrameTimecode}),this.firstFrameTimecodeSet||this.logger.info(`[Adapter] Segment first frame timecode set: ${this.firstFrameTimecode}`),this.firstFrameTimecodeSet=!0,console.log("First frame timecode reciesved at: ",new Date().toISOString()),console.log("First frame timecode: ",this.firstFrameTimecode),console.log("video.currentTime: ",this.video.currentTime),console.log("video.currentTime to UTC: ",new Date(this.video.currentTime*1e3).toISOString()),this.metrics&&(this.metrics.updateMetric("tcTimeStamp",this.tcTimeStamp),this.metrics.updateMetric("timecodeOffset",this.timecode_offset),this.metrics.updateMetric("firstFrameTimecode",this.firstFrameTimecode.join(",")))}}}onAdEvent(e){this.options&&_(this.options,"Adapter")&&console.log(`MK Ad event: ${e}`),this.isMKAdPlaying=e==="start"}parseId3Tag(e,r){console.log("Parsing ID3 tag: ",r);const n=e.exec(r);return n&&n[1]?n[1]:null}processTimedMetadata(e,r){if(e&&e.includes("www.mediakind.com/NTC")){let n=!1;const s=/tc__[\s\S]{4}(\d+)/,i=this.parseId3Tag(s,e);i?(this.tcTimeStamp=new Date(parseInt(i)).getTime(),console.log(`NewTcTimeStamp: ${this.tcTimeStamp}`),n=!0):console.log("tcTimeStamp not found.");const o=/offs[\s\S]{4}(\d+)/,a=this.parseId3Tag(o,e);return a?(this.timecode_offset=parseInt(a)/90,console.log(`New Extracted offset: ${this.timecode_offset}`),n=!0):console.log("offset not found."),n}return!1}pause(){this.animationFrameLoopId&&(cancelAnimationFrame(this.animationFrameLoopId),this.animationFrameLoopId=void 0),this.videoFrameCallbackLoopId&&(this.video.cancelVideoFrameCallback(this.videoFrameCallbackLoopId),this.videoFrameCallbackLoopId=void 0),this.burnedIntervalId&&(clearInterval(this.burnedIntervalId),this.burnedIntervalId=void 0)}resume(){this.resumedAt=performance.now(),this.options&&_(this.options,"Adapter")&&console.log("[Adapter] Resumed - skipping expensive processing for",this.SKIP_PROCESSING_AFTER_RESUME_MS,"ms"),this.siData.patternTracking=[],this.siData.possibilityTracking=[],this.siData.determineFramesIntervals=[],this.siData.determineAFIntervals=[],this.siData.isRVFCpatternDetected=!1,this.siData.RVFCpattern=[],this.siData.expectedRefreshRate=0,this.siData.expectedFPS=0,this.siData.newRefreshRateFrames=0,this.siData.newFPSFrames=0,this.animationFrameLoopId||(this.animationFrameLoopId=window.requestAnimationFrame(this.onAnimationFrame)),this.videoFrameCallbackLoopId||(this.videoFrameCallbackLoopId=this.video.requestVideoFrameCallback(this.onVideoFrame)),this.options.BURNED_TIMECODES_MODE&&!this.burnedIntervalId&&(this.burnedIntervalId=window.setInterval(this.sampleBurnedFrame,33))}delete(){this.options.BURNED_TIMECODES_MODE&&this.stopBurnedPipeline(),this.animationFrameLoopId&&cancelAnimationFrame(this.animationFrameLoopId),this.videoFrameCallbackLoopId&&this.video.cancelVideoFrameCallback(this.videoFrameCallbackLoopId),this.intervalLoopId&&clearInterval(this.intervalLoopId),this.metrics&&this.metrics.delete(),this.debugControls&&this.debugControls.delete()}};pe.MIN_SUPPORTED_FPS=20,pe.MAX_SUPPORTED_FPS=40;let it=pe;class q{constructor(e,r){this.size=1,this.positionElement=()=>{let s=0,i=0;this.corner=="left-top"?(this.element.style.top=`${s}px`,this.element.style.left=`${i}px`):this.corner=="right-top"?(this.element.style.top=`${s}px`,this.element.style.left=`${i+this.video.offsetWidth-this.size}px`):this.corner=="right-bottom"?(this.element.style.top=`${s+this.video.offsetHeight-this.size}px`,this.element.style.left=`${i+this.video.offsetWidth-this.size}px`):this.corner=="left-bottom"&&(this.element.style.top=`${s+this.video.offsetHeight-this.size}px`,this.element.style.left=`${i}px`)},this.video=r,this.container=r.parentElement,this.corner=e;const n=document.createElement("div");n.style.position="absolute",n.style.width=`${this.size}px`,n.style.height=`${this.size}px`,n.style.transition="background-color 0s",n.style.zIndex="100000",this.element=n,this.container.appendChild(n),this.positionElement()}getRandomColor(){const n=Math.floor(Math.random()*11)+0;return`rgb(${n},${n},${n})`}update(){this.element.style.backgroundColor=this.getRandomColor(),this.positionElement()}delete(){this.container.removeChild(this.element)}static createInAllCorners(e){return[new q("left-top",e),new q("right-top",e),new q("right-bottom",e),new q("left-bottom",e)]}static updateAll(e){e.forEach(r=>r.update())}static deleteAll(e){e.forEach(r=>r.delete())}}const C={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},M=console,X={};Object.keys(C).forEach(t=>{X[t]=M[t]});const ge="Datadog Browser SDK:",D={debug:X.debug.bind(M,ge),log:X.log.bind(M,ge),info:X.info.bind(M,ge),warn:X.warn.bind(M,ge),error:X.error.bind(M,ge)},ot="https://docs.datadoghq.com",Yt=`${ot}/real_user_monitoring/browser/troubleshooting`,Fe="More details:";function qt(t,e){return(...r)=>{try{return t(...r)}catch(n){D.error(e,n)}}}function Le(t){return t!==0&&Math.random()*100<=t}function gn(t){return yn(t)&&t>=0&&t<=100}function yn(t){return typeof t=="number"}const ye=1e3,K=60*ye,Xt=60*K,_n=365*(24*Xt);function _e(){return new Date().getTime()}function G(){return _e()}function Pe(){return performance.now()}function V(){return{relative:Pe(),timeStamp:G()}}function bn(){return{relative:0,timeStamp:Kt()}}function vn(t,e){return e-t}function Tn(t,e){return t+e}function Sn(t){return t-Kt()}let at;function Kt(){return at===void 0&&(at=performance.timing.navigationStart),at}const B=1024,Jt=1024*B,En=/[^\u0000-\u007F]/;function ct(t){return En.test(t)?window.TextEncoder!==void 0?new TextEncoder().encode(t).length:new Blob([t]).size:t.length}function xn(t){return{...t}}function Zt(t,e){return Object.keys(t).some(r=>t[r]===e)}function be(t){return Object.keys(t).length===0}function H(){if(typeof globalThis=="object")return globalThis;Object.defineProperty(Object.prototype,"_dd_temp_",{get(){return this},configurable:!0});let t=_dd_temp_;return delete Object.prototype._dd_temp_,typeof t!="object"&&(typeof self=="object"?t=self:typeof window=="object"?t=window:t={}),t}function oe(t,e){const r=H();let n;return r.Zone&&typeof r.Zone.__symbol__=="function"&&(n=t[r.Zone.__symbol__(e)]),n||(n=t[e]),n}let Oe,Qt=!1;function wn(t){Oe=t}function An(t){Qt=t}function Rn(t,e,r){const n=r.value;r.value=function(...s){return(Oe?x(n):n).apply(this,s)}}function x(t){return function(){return ve(t,this,arguments)}}function ve(t,e,r){try{return t.apply(e,r)}catch(n){Cn(n)}}function Cn(t){if(lt(t),Oe)try{Oe(t)}catch(e){lt(e)}}function lt(...t){Qt&&D.error("[MONITOR]",...t)}function Te(t,e){return oe(H(),"setTimeout")(x(t),e)}function er(t){oe(H(),"clearTimeout")(t)}function dt(t,e){return oe(H(),"setInterval")(x(t),e)}function tr(t){oe(H(),"clearInterval")(t)}class k{constructor(e){this.onFirstSubscribe=e,this.observers=[]}subscribe(e){return this.observers.push(e),this.observers.length===1&&this.onFirstSubscribe&&(this.onLastUnsubscribe=this.onFirstSubscribe(this)||void 0),{unsubscribe:()=>{this.observers=this.observers.filter(r=>e!==r),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}}notify(e){this.observers.forEach(r=>r(e))}}function rr(...t){return new k(e=>{const r=t.map(n=>n.subscribe(s=>e.notify(s)));return()=>r.forEach(n=>n.unsubscribe())})}function nr(t,e,r){let n=!1,s,i;return{throttled:(...o)=>{if(n){s=o;return}t(...o),n=!0,i=Te(()=>{s&&t(...s),n=!1,s=void 0},e)},cancel:()=>{er(i),n=!1,s=void 0}}}function W(){}function j(t){return t?(parseInt(t,10)^Math.random()*16>>parseInt(t,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,j)}const Ie=/([\w-]+)\s*=\s*([^;]+)/g;function Dn(t,e){for(Ie.lastIndex=0;;){const r=Ie.exec(t);if(r){if(r[1]===e)return r[2]}else break}}function kn(t){const e=new Map;for(Ie.lastIndex=0;;){const r=Ie.exec(t);if(r)e.set(r[1],r[2]);else break}return e}function Un(t,e,r=""){const n=t.charCodeAt(e-1),i=n>=55296&&n<=56319?e+1:e;return t.length<=i?t:`${t.slice(0,i)}${r}`}function Fn(){return Ln()===0}let Me;function Ln(){return Me??(Me=Pn())}function Pn(t=window){var e;const r=t.navigator.userAgent;return t.chrome||/HeadlessChrome/.test(r)?0:((e=t.navigator.vendor)===null||e===void 0?void 0:e.indexOf("Apple"))===0||/safari/i.test(r)&&!/chrome|android/i.test(r)?1:2}function Se(t,e,r=0,n){const s=new Date;s.setTime(s.getTime()+r);const i=`expires=${s.toUTCString()}`,o=n&&n.crossSite?"none":"strict",a=n&&n.domain?`;domain=${n.domain}`:"",c=n&&n.secure?";secure":"",d=n&&n.partitioned?";partitioned":"";document.cookie=`${t}=${e};${i};path=/;samesite=${o}${a}${c}${d}`}function ut(t){return Dn(document.cookie,t)}let ht;function J(t){return ht||(ht=kn(document.cookie)),ht.get(t)}function sr(t,e){Se(t,"",0,e)}function On(t){if(document.cookie===void 0||document.cookie===null)return!1;try{const e=`dd_cookie_test_${j()}`,r="test";Se(e,r,K,t);const n=ut(e)===r;return sr(e,t),n}catch(e){return D.error(e),!1}}let ft;function In(){if(ft===void 0){const t=`dd_site_test_${j()}`,e="test",r=window.location.hostname.split(".");let n=r.pop();for(;r.length&&!ut(t);)n=`${r.pop()}.${n}`,Se(t,e,ye,{domain:n});sr(t,{domain:n}),ft=n}return ft}const ae="_dd_s";function Be(t){return Object.values(t)}function Mn(t){return Object.entries(t)}const pt=4*Xt,ir=15*K,Bn=_n,Ee={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},or=/^([a-zA-Z]+)=([a-z0-9-]+)$/,mt="&";function Nn(t){return!!t&&(t.indexOf(mt)!==-1||or.test(t))}const zn="1";function Z(t,e){const r={isExpired:zn};return e.trackAnonymousUser&&(t!=null&&t.anonymousId?r.anonymousId=t==null?void 0:t.anonymousId:r.anonymousId=j()),r}function Ne(t){return be(t)}function ar(t){return!Ne(t)}function ze(t){return t.isExpired!==void 0||!$n(t)}function $n(t){return(t.created===void 0||_e()-Number(t.created)<pt)&&(t.expire===void 0||_e()<Number(t.expire))}function cr(t){t.expire=String(_e()+ir)}function gt(t){return Mn(t).map(([e,r])=>e==="anonymousId"?`aid=${r}`:`${e}=${r}`).join(mt)}function lr(t){const e={};return Nn(t)&&t.split(mt).forEach(r=>{const n=or.exec(r);if(n!==null){const[,s,i]=n;s==="aid"?e.anonymousId=i:e[s]=i}}),e}const Gn="_dd",Vn="_dd_r",Hn="_dd_l",Wn="rum",jn="logs";function Yn(t){if(!J(ae)){const r=J(Gn),n=J(Vn),s=J(Hn),i={};r&&(i.id=r),s&&/^[01]$/.test(s)&&(i[jn]=s),n&&/^[012]$/.test(n)&&(i[Wn]=n),ar(i)&&(cr(i),t.persistSession(i))}}function dr(t){const e=Zn(t);return On(e)?{type:Ee.COOKIE,cookieOptions:e}:void 0}function qn(t,e){const r={isLockEnabled:Fn(),persistSession:Xn(e),retrieveSession:Jn,expireSession:n=>Kn(e,n,t)};return Yn(r),r}function Xn(t){return e=>{Se(ae,gt(e),ir,t)}}function Kn(t,e,r){const n=Z(e,r);Se(ae,gt(n),r.trackAnonymousUser?Bn:pt,t)}function Jn(){const t=ut(ae);return lr(t)}function Zn(t){const e={};return e.secure=!!t.useSecureSessionCookie||!!t.usePartitionedCrossSiteSessionCookie,e.crossSite=!!t.usePartitionedCrossSiteSessionCookie,e.partitioned=!!t.usePartitionedCrossSiteSessionCookie,t.trackSessionAcrossSubdomains&&(e.domain=In()),e}const Qn="_dd_test_";function ur(){try{const t=j(),e=`${Qn}${t}`;localStorage.setItem(e,t);const r=localStorage.getItem(e);return localStorage.removeItem(e),t===r?{type:Ee.LOCAL_STORAGE}:void 0}catch{return}}function es(t){return{isLockEnabled:!1,persistSession:hr,retrieveSession:ts,expireSession:e=>rs(e,t)}}function hr(t){localStorage.setItem(ae,gt(t))}function ts(){const t=localStorage.getItem(ae);return lr(t)}function rs(t,e){hr(Z(t,e))}const ns=10,ss=100,fr=[];let $e;function Q(t,e,r=0){var n;const{isLockEnabled:s,persistSession:i,expireSession:o}=e,a=f=>i({...f,lock:d}),c=()=>{const f=e.retrieveSession(),p=f.lock;return f.lock&&delete f.lock,{session:f,lock:p}};if($e||($e=t),t!==$e){fr.push(t);return}if(s&&r>=ss){pr(e);return}let d,l=c();if(s){if(l.lock){Ge(t,e,r);return}if(d=j(),a(l.session),l=c(),l.lock!==d){Ge(t,e,r);return}}let u=t.process(l.session);if(s&&(l=c(),l.lock!==d)){Ge(t,e,r);return}if(u&&(ze(u)?o(u):(cr(u),s?a(u):i(u))),s&&!(u&&ze(u))){if(l=c(),l.lock!==d){Ge(t,e,r);return}i(l.session),u=l.session}(n=t.after)===null||n===void 0||n.call(t,u||l.session),pr(e)}function Ge(t,e,r){Te(()=>{Q(t,e,r+1)},ns)}function pr(t){$e=void 0;const e=fr.shift();e&&Q(e,t)}const mr=ye;function is(t){switch(t.sessionPersistence){case Ee.COOKIE:return dr(t);case Ee.LOCAL_STORAGE:return ur();case void 0:{let e=dr(t);return!e&&t.allowFallbackToLocalStorage&&(e=ur()),e}default:D.error(`Invalid session persistence '${String(t.sessionPersistence)}'`)}}function os(t,e,r,n){const s=new k,i=new k,o=new k,a=t.type===Ee.COOKIE?qn(e,t.cookieOptions):es(e),{expireSession:c}=a,d=dt(h,mr);let l;g();const{throttled:u,cancel:f}=nr(()=>{Q({process:v=>{if(Ne(v))return;const F=m(v);return S(F),F},after:v=>{ar(v)&&!b()&&w(v),l=v}},a)},mr);function p(){Q({process:v=>b()?m(v):void 0},a)}function h(){Q({process:v=>ze(v)?Z(v,e):void 0,after:m},a)}function m(v){return ze(v)&&(v=Z(v,e)),b()&&(E(v)?A():(o.notify({previousState:l,newState:v}),l=v)),v}function g(){Q({process:v=>{if(Ne(v))return Z(v,e)},after:v=>{l=v}},a)}function S(v){if(Ne(v))return!1;const{trackingType:F,isTracked:Mt}=n(v[r]);v[r]=F,delete v.isExpired,Mt&&!v.id&&(v.id=j(),v.created=String(_e()))}function b(){return l[r]!==void 0}function E(v){return l.id!==v.id||l[r]!==v[r]}function A(){l=Z(l,e),i.notify()}function w(v){l=v,s.notify()}function R(v){Q({process:F=>({...F,...v}),after:m},a)}return{expandOrRenewSession:u,expandSession:p,getSession:()=>l,renewObservable:s,expireObservable:i,sessionStateUpdateObservable:o,restartSession:g,expire:()=>{f(),c(l),m(Z(l,e))},stop:()=>{tr(d)},updateSessionState:R}}const yt={GRANTED:"granted",NOT_GRANTED:"not-granted"};function as(t){const e=new k;return{tryToInit(r){t||(t=r)},update(r){t=r,e.notify()},isGranted(){return t===yt.GRANTED},observable:e}}function ee(t,e,r){if(typeof t!="object"||t===null)return JSON.stringify(t);const n=ce(Object.prototype),s=ce(Array.prototype),i=ce(Object.getPrototypeOf(t)),o=ce(t);try{return JSON.stringify(t,e,r)}catch{return"<error: unable to serialize object>"}finally{n(),s(),i(),o()}}function ce(t){const e=t,r=e.toJSON;return r?(delete e.toJSON,()=>{e.toJSON=r}):W}function _t(t){return cs(t,location.href).href}function cs(t,e){const r=ls();if(r)try{return e!==void 0?new r(t,e):new r(t)}catch(i){throw new Error(`Failed to construct URL: ${String(i)} ${ee({url:t,base:e})}`)}if(e===void 0&&!/:/.test(t))throw new Error(`Invalid URL: '${t}'`);let n=document;const s=n.createElement("a");if(e!==void 0){n=document.implementation.createHTMLDocument("");const i=n.createElement("base");i.href=e,n.head.appendChild(i),n.body.appendChild(s)}return s.href=t,s}const gr=URL;let Ve;function ls(){if(Ve===void 0)try{Ve=new gr("http://test/path").href==="http://test/path"}catch{Ve=!1}return Ve?gr:void 0}const ds="datad0g.com",us="dd0g-gov.com",le="datadoghq.com",hs="ddog-gov.com",fs="pci.browser-intake-datadoghq.com",ps=["ddsource","ddtags"];function xe(t,e,r){const n=ms(t,e);return{build(s,i){const o=ys(t,e,r,s,i);return n(o)},urlPrefix:n(""),trackType:e}}function ms(t,e){const r=`/api/v2/${e}`,n=t.proxy;if(typeof n=="string"){const i=_t(n);return o=>`${i}?ddforward=${encodeURIComponent(`${r}?${o}`)}`}if(typeof n=="function")return i=>n({path:r,parameters:i});const s=gs(e,t);return i=>`https://${s}${r}?${i}`}function gs(t,e){const{site:r=le,internalAnalyticsSubdomain:n}=e;if(t==="logs"&&e.usePciIntake&&r===le)return fs;if(n&&r===le)return`${n}.${le}`;if(r===us)return`http-intake.logs.${r}`;const s=r.split("."),i=s.pop();return`browser-intake-${s.join("-")}.${i}`}function ys({clientToken:t,internalAnalyticsSubdomain:e},r,n,s,{retry:i,encoding:o}){const a=["sdk_version:6.5.0",`api:${s}`].concat(n);i&&a.push(`retry_count:${i.count}`,`retry_after:${i.lastFailureStatus}`);const c=["ddsource=browser",`ddtags=${encodeURIComponent(a.join(","))}`,`dd-api-key=${t}`,`dd-evp-origin-version=${encodeURIComponent("6.5.0")}`,"dd-evp-origin=browser",`dd-request-id=${j()}`];return o&&c.push(`dd-evp-encoding=${o}`),r==="rum"&&c.push(`batch_time=${G()}`),e&&c.reverse(),c.join("&")}const _s=200;function bs(t){const{env:e,service:r,version:n,datacenter:s}=t,i=[];return e&&i.push(He("env",e)),r&&i.push(He("service",r)),n&&i.push(He("version",n)),s&&i.push(He("datacenter",s)),i}function He(t,e){const r=_s-t.length-1;(e.length>r||vs(e))&&D.warn(`${t} value doesn't meet tag requirements and will be sanitized. ${Fe} ${ot}/getting_started/tagging/#defining-tags`);const n=e.replace(/,/g,"_");return`${t}:${n}`}function vs(t){return Ts()?new RegExp("[^\\p{Ll}\\p{Lo}0-9_:./-]","u").test(t):!1}function Ts(){try{return new RegExp("[\\p{Ll}]","u"),!0}catch{return!1}}function Ss(t){const e=t.site||le,r=bs(t),n=Es(t,r);return{replica:xs(t,r),site:e,...n}}function Es(t,e){return{logsEndpointBuilder:xe(t,"logs",e),rumEndpointBuilder:xe(t,"rum",e),sessionReplayEndpointBuilder:xe(t,"replay",e)}}function xs(t,e){if(!t.replica)return;const r={...t,site:le,clientToken:t.replica.clientToken},n={logsEndpointBuilder:xe(r,"logs",e),rumEndpointBuilder:xe(r,"rum",e)};return{applicationId:t.replica.applicationId,...n}}function ws(t){return ps.every(e=>t.includes(e))}function bt(t,e){return t!=null&&typeof t!="string"?(D.error(`${e} must be defined as a string`),!1):!0}function As(t){return t&&typeof t=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(t)?(D.error(`Site should be a valid Datadog site. ${Fe} ${ot}/getting_started/site/.`),!1):!0}function We(t,e){return t!==void 0&&!gn(t)?(D.error(`${e} Sample Rate should be a number between 0 and 100`),!1):!0}function Rs(t){var e,r,n,s,i,o;if(!t||!t.clientToken){D.error("Client Token is not configured, we will not send any data.");return}if(!(!As(t.site)||!We(t.sessionSampleRate,"Session")||!We(t.telemetrySampleRate,"Telemetry")||!We(t.telemetryConfigurationSampleRate,"Telemetry Configuration")||!We(t.telemetryUsageSampleRate,"Telemetry Usage")||!bt(t.version,"Version")||!bt(t.env,"Env")||!bt(t.service,"Service"))){if(t.trackingConsent!==void 0&&!Zt(yt,t.trackingConsent)){D.error('Tracking Consent should be either "granted" or "not-granted"');return}return{beforeSend:t.beforeSend&&qt(t.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:is(t),sessionSampleRate:(e=t.sessionSampleRate)!==null&&e!==void 0?e:100,telemetrySampleRate:(r=t.telemetrySampleRate)!==null&&r!==void 0?r:20,telemetryConfigurationSampleRate:(n=t.telemetryConfigurationSampleRate)!==null&&n!==void 0?n:5,telemetryUsageSampleRate:(s=t.telemetryUsageSampleRate)!==null&&s!==void 0?s:5,service:t.service||void 0,silentMultipleInit:!!t.silentMultipleInit,allowUntrustedEvents:!!t.allowUntrustedEvents,trackingConsent:(i=t.trackingConsent)!==null&&i!==void 0?i:yt.GRANTED,trackAnonymousUser:(o=t.trackAnonymousUser)!==null&&o!==void 0?o:!0,storeContextsAcrossPages:!!t.storeContextsAcrossPages,batchBytesLimit:16*B,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*ye,batchMessagesLimit:50,messageBytesLimit:256*B,...Ss(t)}}}function Cs(t){return{session_sample_rate:t.sessionSampleRate,telemetry_sample_rate:t.telemetrySampleRate,telemetry_configuration_sample_rate:t.telemetryConfigurationSampleRate,telemetry_usage_sample_rate:t.telemetryUsageSampleRate,use_before_send:!!t.beforeSend,use_partitioned_cross_site_session_cookie:t.usePartitionedCrossSiteSessionCookie,use_secure_session_cookie:t.useSecureSessionCookie,use_proxy:!!t.proxy,silent_multiple_init:t.silentMultipleInit,track_session_across_subdomains:t.trackSessionAcrossSubdomains,track_anonymous_user:t.trackAnonymousUser,session_persistence:t.sessionPersistence,allow_fallback_to_local_storage:!!t.allowFallbackToLocalStorage,store_contexts_across_pages:!!t.storeContextsAcrossPages,allow_untrusted_events:!!t.allowUntrustedEvents,tracking_consent:t.trackingConsent}}var vt;(function(t){t.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",t.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(vt||(vt={}));const yr=new Set;function Ds(t){Array.isArray(t)&&ks(t.filter(e=>Zt(vt,e)))}function ks(t){t.forEach(e=>{yr.add(e)})}function Us(){return yr}const we="?";function N(t){const e=[];let r=Tt(t,"stack");const n=String(t);return r&&r.startsWith(n)&&(r=r.slice(n.length)),r&&r.split(`
|
|
494
|
+
`,s=this.createShader(this.gl.VERTEX_SHADER,r),i=this.createShader(this.gl.FRAGMENT_SHADER,n);this.program=this.createProgram(s,i),this.gl.useProgram(this.program),this.positionLoc=this.gl.getAttribLocation(this.program,"a_position"),this.texCoordLoc=this.gl.getAttribLocation(this.program,"a_texCoord"),this.resolutionLoc=this.gl.getUniformLocation(this.program,"u_resolution"),this.videoSizeLoc=this.gl.getUniformLocation(this.program,"u_videoSize"),this.textureLoc=this.gl.getUniformLocation(this.program,"u_image"),this.positionBuffer=this.gl.createBuffer(),this.texCoordBuffer=this.gl.createBuffer(),this.videoTexture=this.gl.createTexture(),this.fbo=this.gl.createFramebuffer(),this.outTex=this.gl.createTexture(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,0,this.OUT_WIDTH,0,0,this.OUT_HEIGHT,0,this.OUT_HEIGHT,this.OUT_WIDTH,0,this.OUT_WIDTH,this.OUT_HEIGHT]),this.gl.STATIC_DRAW),this.gl.enableVertexAttribArray(this.positionLoc),this.gl.vertexAttribPointer(this.positionLoc,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.texCoordBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),this.gl.STATIC_DRAW),this.gl.enableVertexAttribArray(this.texCoordLoc),this.gl.vertexAttribPointer(this.texCoordLoc,2,this.gl.FLOAT,!1,0,0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.outTex),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.NEAREST),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.NEAREST),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.OUT_WIDTH,this.OUT_HEIGHT,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this.fbo),this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER,this.gl.COLOR_ATTACHMENT0,this.gl.TEXTURE_2D,this.outTex,0)}createShader(e,r){const n=this.gl.createShader(e);if(this.gl.shaderSource(n,r),this.gl.compileShader(n),!this.gl.getShaderParameter(n,this.gl.COMPILE_STATUS)){const s=this.gl.getShaderInfoLog(n);throw this.gl.deleteShader(n),new Error("Shader compile failed: "+s)}return n}createProgram(e,r){const n=this.gl.createProgram();if(this.gl.attachShader(n,e),this.gl.attachShader(n,r),this.gl.linkProgram(n),!this.gl.getProgramParameter(n,this.gl.LINK_STATUS)){const s=this.gl.getProgramInfoLog(n);throw this.gl.deleteProgram(n),new Error("Program link failed: "+s)}return this.gl.detachShader(n,e),this.gl.detachShader(n,r),this.gl.deleteShader(e),this.gl.deleteShader(r),n}decode(e){const r=e.videoWidth|0,n=e.videoHeight|0;if(r===0||n===0)return null;this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.NEAREST),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.NEAREST),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.canvas.width=this.OUT_WIDTH,this.canvas.height=this.OUT_HEIGHT,this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this.fbo),this.gl.viewport(0,0,this.OUT_WIDTH,this.OUT_HEIGHT),this.gl.useProgram(this.program),this.resolutionLoc&&this.gl.uniform2f(this.resolutionLoc,this.OUT_WIDTH,this.OUT_HEIGHT),this.videoSizeLoc&&this.gl.uniform2f(this.videoSizeLoc,r,n),this.textureLoc&&this.gl.uniform1i(this.textureLoc,0),this.gl.drawArrays(this.gl.TRIANGLES,0,6);const s=new Uint8Array(this.OUT_WIDTH*this.OUT_HEIGHT*4);this.gl.readPixels(0,0,this.OUT_WIDTH,this.OUT_HEIGHT,this.gl.RGBA,this.gl.UNSIGNED_BYTE,s);const i=s[0],o=s[4],a=s[8],c=s[12],d=Math.floor(c/2),l=c%2===1?"_1":"",u=("0"+i).slice(-2),f=("0"+o).slice(-2),p=("0"+a).slice(-2),h=("0"+d).slice(-2);return`${u}_${f}_${p}_${h}${l}`}decodeFromImageBitmap(e){const r=e.width|0,n=e.height|0;if(r===0||n===0)return null;this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.NEAREST),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.NEAREST),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.canvas.width=this.OUT_WIDTH,this.canvas.height=this.OUT_HEIGHT,this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this.fbo),this.gl.viewport(0,0,this.OUT_WIDTH,this.OUT_HEIGHT),this.gl.useProgram(this.program),this.resolutionLoc&&this.gl.uniform2f(this.resolutionLoc,this.OUT_WIDTH,this.OUT_HEIGHT),this.videoSizeLoc&&this.gl.uniform2f(this.videoSizeLoc,r,n),this.textureLoc&&this.gl.uniform1i(this.textureLoc,0),this.gl.drawArrays(this.gl.TRIANGLES,0,6);const s=new Uint8Array(this.OUT_WIDTH*this.OUT_HEIGHT*4);this.gl.readPixels(0,0,this.OUT_WIDTH,this.OUT_HEIGHT,this.gl.RGBA,this.gl.UNSIGNED_BYTE,s);const i=s[0],o=s[4],a=s[8],c=s[12],d=Math.floor(c/2),l=c%2===1?"_1":"",u=("0"+i).slice(-2),f=("0"+o).slice(-2),p=("0"+a).slice(-2),h=("0"+d).slice(-2);return`${u}_${f}_${p}_${h}${l}`}dispose(){this.videoTexture&&this.gl.deleteTexture(this.videoTexture),this.outTex&&this.gl.deleteTexture(this.outTex),this.fbo&&this.gl.deleteFramebuffer(this.fbo),this.positionBuffer&&this.gl.deleteBuffer(this.positionBuffer),this.texCoordBuffer&&this.gl.deleteBuffer(this.texCoordBuffer),this.program&&this.gl.deleteProgram(this.program)}}const pe=class pe{constructor(e){if(this.platformSupported=!0,this.firstFrameTimecodeSet=!1,this.firstFrameTimecode=[0,0,0,0,0],this.firstVideoFrameCallbackFired=!1,this.isMKAdPlaying=!1,this.loggerTimeoutStart=0,this.loggerTimeout=1e4,this.lastStatusUpdate=0,this.STATUS_UPDATE_INTERVAL=100,this.lastBenchmarkUpdate=0,this.BENCHMARK_UPDATE_INTERVAL=100,this.resumedAt=0,this.SKIP_PROCESSING_AFTER_RESUME_MS=1e3,this.afData={counter:0,lastTimestamp:0,previousTimestamp:0,lastMetadataNow:0,timeFromLastRVFC:0,animationFPS:0,playerTimeOffset:0,lastPlayerTimeFromSync:0,lastCalculatedPlayerTimeVideoFrame:0,lastCalculatedPlayerTimeFraction:0,previousCalculatedPlayerTimeFraction:2},this.vfcData={counter:0,lastTimestamp:0,previousTimestamp:0,timeFromLastRAF:0,videoFPS:0,lastFrameMetadata:null,lastFrameMetadataNow:0,storedMetadata:[],timePerformanceNowToExpectedDisplayTime:0,timeRVFCnowToExpectedDisplayTime:0,mediaTimeOffset:0,lastMediaTimeFromSync:0,lastCalculatedMediaTimeVideoFrame:0},this.siData={counter:0,lastTimestamp:0,lastOffset:0,timeFromLastRAF:0,timeFromLastRVFC:0,lastSeenRAFCount:0,lastSeenRVFCCount:0,isRAFSeen:!1,isRVFCSeen:!1,isVideoPaused:!0,workingFps:0,refreshRate:0,RVFCmissed:0,RVFCframeExpected:0,expectedRefreshRate:0,avgExpectedRefreshRate:0,newRefreshRateFrames:0,expectedFPS:0,newFPSFrames:0,RVFCpattern:[],isRVFCpatternDetected:!1,patternTracking:[],patternTrackingIndex:-1,patternNextValue:-1,possibilityTracking:[],previousPossibilityValue:-1,lastCallback:null,lastCalculatedFrame:0,lastRendererFrameSent:0,lastMessageSent:"",compensationMode:!1,compensationCounter:0,frameCorrection:0,determineFramesIntervals:[],determineAFIntervals:[],expectedDisplayTimeReminder:0,animationFramesToDisplayTime:0},this.tcTimeStamp=0,this.timecode_offset=0,this.burnedLastTcKey=-1,this.sampleBurnedFrame=async()=>{var r;if(!(!this.OTTPlayer||!this.video)&&!(this.video.videoWidth===0||this.video.videoHeight===0)&&this.gl2Decoder)try{let n=await createImageBitmap(this.video);const s=this.gl2Decoder.decodeFromImageBitmap(n);if(!s){try{n.close()}catch{}return}const i=this.parseTcKey(s);if(i<=this.burnedLastTcKey){try{n.close()}catch{}return}this.burnedLastTcKey=i,this.metrics&&this.metrics.updateMetric("Last sent timecode",s),(r=this.OTTPlayer.clocker)==null||r.callRendererWorkerWithFrame(n,s),n=void 0}catch(n){this.logger.error("[Adapter] sampleBurnedFrame error: "+n)}},this.onAnimationFrame=r=>{if(this.video.paused||!this.OTTPlayer.clocker||!this.OTTPlayer.gameParams||!this.syncPoint){this.animationFrameLoopId=window.requestAnimationFrame(this.onAnimationFrame);return}this.afData.counter++,this.afData.previousTimestamp=this.afData.lastTimestamp,this.afData.lastTimestamp=performance.now(),this.afData.lastMetadataNow=r,this.afData.timeFromLastRVFC=this.afData.lastTimestamp-this.vfcData.lastTimestamp,this.afData.animationFPS=this.OTTPlayer.clocker.animationFPScalculator.getPerciseFPS(),this.siData.lastCallback=="RAF"&&this.siData.RVFCmissed++,this.siData.lastCallback="RAF";const n=(this.video.currentTime-this.syncPoint.playerTime)*(6e4/1001);this.afData.lastPlayerTimeFromSync=n;const s=Math.floor(n)+this.syncPoint.frame;this.afData.playerTimeOffset=L.calculateCurrentOffset(s,this.OTTPlayer.gameParams.offsets);let i=s-this.afData.playerTimeOffset;if(i<0&&(i+=5178816),i++,this.afData.lastCalculatedPlayerTimeVideoFrame=i,this.afData.previousCalculatedPlayerTimeFraction=this.afData.lastCalculatedPlayerTimeFraction,this.afData.lastCalculatedPlayerTimeFraction=n-Math.floor(n),this.metrics)try{this.metrics.updateMetric("RAF calls",this.afData.counter),this.metrics.updateMetric("Last player time",this.video.currentTime.toFixed(4)),this.metrics.updateMetric("Last player time frame",this.afData.lastCalculatedPlayerTimeVideoFrame),this.metrics.updateMetric("Last player time fraction",this.afData.lastCalculatedPlayerTimeFraction.toFixed(4)),this.metrics.updateMetric("Last player time double frame",this.afData.lastPlayerTimeFromSync.toFixed(5)),this.metrics.updateMetric("AF metadata now - perf.now()",(this.afData.lastTimestamp-this.afData.lastMetadataNow).toFixed(3)),this.metrics.updateMetric("VF ExpDispTime - AF metadata now",(this.afData.lastTimestamp-this.vfcData.lastFrameMetadata.expectedDisplayTime).toFixed(3)),this.metrics.updateMetric("Last RAF call",this.afData.lastTimestamp.toFixed(2)),this.metrics.updateMetric("RAF - RVFC dif",this.afData.timeFromLastRVFC.toFixed(2))}catch(o){this.options&&_(this.options,"Adapter")&&console.error(o)}this.animationFrameLoopId=window.requestAnimationFrame(this.onAnimationFrame),this.determineFrameUpdate()},this.onVideoFrame=(r,n)=>{if(this.firstVideoFrameCallbackFired||(this.firstVideoFrameCallbackFired=!0,this.logger.info("[Adapter] First video frame callback fired"),console.log("[Adapter] First video frame callback fired")),this.video.paused||!this.OTTPlayer.clocker||!this.OTTPlayer.gameParams||!this.syncPoint){this.videoFrameCallbackLoopId=this.video.requestVideoFrameCallback(this.onVideoFrame);return}this.vfcData.counter++,this.vfcData.previousTimestamp=this.vfcData.lastTimestamp,this.vfcData.lastTimestamp=performance.now(),this.vfcData.timeFromLastRAF=this.vfcData.lastTimestamp-this.afData.lastTimestamp,this.siData.RVFCmissed=0,this.vfcData.videoFPS=this.OTTPlayer.clocker.videoFPScalculator.getPerciseFPS(),this.siData.lastCallback="RVFC";const s=(n.mediaTime-this.syncPoint.playerTime)*(6e4/1001);this.vfcData.lastMediaTimeFromSync=s;const i=Math.floor(s+.1)+this.syncPoint.frame;this.vfcData.mediaTimeOffset=L.calculateCurrentOffset(i,this.OTTPlayer.gameParams.offsets);let o=i-this.vfcData.mediaTimeOffset;o<0&&(o+=5178816),o++,this.vfcData.lastCalculatedMediaTimeVideoFrame=o,this.vfcData.lastFrameMetadata=n,this.vfcData.storedMetadata.push(n),this.vfcData.storedMetadata.length>10&&this.vfcData.storedMetadata.shift(),this.vfcData.timePerformanceNowToExpectedDisplayTime=n.expectedDisplayTime-this.vfcData.lastTimestamp,this.vfcData.timeRVFCnowToExpectedDisplayTime=n.expectedDisplayTime-r,this.vfcData.lastFrameMetadataNow=r,this.metrics&&(this.metrics.updateMetric("MediaTime",n.mediaTime),this.metrics.updateMetric("MediaTimeWithSync",i),this.metrics.updateMetric("RVFC calls",this.vfcData.counter),this.metrics.updateMetric("Last metadata media time",n.mediaTime.toFixed(4)),this.metrics.updateMetric("Last metadata media time frame",this.vfcData.lastCalculatedMediaTimeVideoFrame),this.metrics.updateMetric("Time to presentation time",(n.presentationTime-r).toFixed(4)),this.metrics.updateMetric("Metadata presented frames",n.presentedFrames),this.metrics.updateMetric("Metadata processing duration",n.processingDuration),this.metrics.updateMetric("Last media time double frame",this.vfcData.lastMediaTimeFromSync.toFixed(5)),this.metrics.updateMetric("VF metadata now - perf.now()",(this.afData.lastTimestamp-this.afData.lastMetadataNow).toFixed(3)),this.metrics.updateMetric("RVFC to expected display time",this.vfcData.timeRVFCnowToExpectedDisplayTime.toFixed(4)),this.metrics.updateMetric("Performance Now to expected display time",this.vfcData.timePerformanceNowToExpectedDisplayTime.toFixed(4)),this.metrics.updateMetric("Last RVFC call",this.vfcData.lastTimestamp.toFixed(2))),this.videoFrameCallbackLoopId=this.video.requestVideoFrameCallback(this.onVideoFrame),this.determineFrameUpdate()},this.determineFrameUpdate=()=>{var n,s,i,o;if(!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;this.siData.counter===0&&this.logger.info("didStartAugmentation"),this.siData.counter++,this.siData.isVideoPaused=this.video.paused,this.siData.isRAFSeen=this.siData.lastSeenRAFCount==this.afData.counter,this.siData.isRVFCSeen=this.siData.lastSeenRVFCCount==this.vfcData.counter,this.siData.lastTimestamp=performance.now(),this.siData.timeFromLastRAF=this.siData.lastTimestamp-this.afData.lastTimestamp,this.siData.timeFromLastRVFC=this.siData.lastTimestamp-this.vfcData.lastTimestamp,this.siData.lastSeenRAFCount=this.afData.counter,this.siData.lastSeenRVFCCount=this.vfcData.counter,this.siData.workingFps=this.OTTPlayer.clocker.videoFPScalculator.getFPS(),this.siData.refreshRate=this.OTTPlayer.clocker.animationFPScalculator.getPerciseFPS();const r=this.siData.lastTimestamp;if(r-this.lastBenchmarkUpdate>this.BENCHMARK_UPDATE_INTERVAL&&(this.runBenchmarkTest(),this.lastBenchmarkUpdate=r),this.OTTPlayer.statusOverlay&&r-this.lastStatusUpdate>this.STATUS_UPDATE_INTERVAL&&(this.updateStatusOverlay(),this.lastStatusUpdate=r),!this.OTTPlayer.options.ADAPTER_RUN_IN_WORKER)this.platformSpecificFrameUpdate();else{const a={siData:this.siData,vfcData:this.vfcData,afData:this.afData,debugControls:(n=this.debugControls)==null?void 0:n.exportData(),zipBaseURL:this.OTTPlayer.options.zipBaseURL,adsBaseURL:this.OTTPlayer.options.adsBaseURL,bucketName:((s=this.OTTPlayer.gameParams)==null?void 0:s.bucketName)||"",offsets:((i=this.OTTPlayer.gameParams)==null?void 0:i.offsets)||[],customerId:((o=this.OTTPlayer.gameParams)==null?void 0:o.customerId)||""};this.OTTPlayer.clocker.callAdapterWorker(a)}},this.determineFrameUpdateChromeMac=()=>{if(this.resumedAt>0&&performance.now()-this.resumedAt<this.SKIP_PROCESSING_AFTER_RESUME_MS)return;const r=Math.round(1e3/this.vfcData.timeRVFCnowToExpectedDisplayTime);r>0&&r<500&&(this.expectedRefreshRateCalculator.addFrameDuration(this.vfcData.timeRVFCnowToExpectedDisplayTime/1e3),Math.abs(this.siData.expectedRefreshRate-r)>4?this.siData.newRefreshRateFrames++:(this.siData.expectedRefreshRate=r,this.siData.avgExpectedRefreshRate=this.expectedRefreshRateCalculator.getPerciseFPS(),this.siData.newRefreshRateFrames=0),this.siData.newRefreshRateFrames>10&&(this.siData.newRefreshRateFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedRefreshRate=r,this.siData.isRVFCpatternDetected=!1));const n=this.OTTPlayer.clocker.videoFPScalculator.getPerciseFPS();if(n>0&&n<500&&(Math.abs(this.siData.expectedFPS-n)>4?this.siData.newFPSFrames++:(this.siData.expectedFPS=n,this.siData.newFPSFrames=0),this.siData.newFPSFrames>10&&(this.siData.newFPSFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedFPS=n,this.siData.isRVFCpatternDetected=!1)),this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;const s=20,i=1e3;if(!this.siData.isRVFCSeen){const o=Math.round(this.vfcData.timeRVFCnowToExpectedDisplayTime/(1e3/this.afData.animationFPS));if(o<=0&&this.siData.patternTracking.length<=1-o){this.siData.patternTracking=[!0];for(let a=0;a<1-o;a++)this.siData.patternTracking.push(!1)}else o<=1&&(this.siData.patternTracking[this.siData.patternTracking.length-2+o]=!0)}if(this.siData.isRAFSeen||this.siData.patternTracking.push(!1),this.siData.patternTracking.length>i&&this.siData.patternTracking.shift(),!this.siData.isRVFCpatternDetected){const o=this.siData.patternTracking;for(let a=1;a*s<=o.length;a++){for(let c=0;c+a*s<=o.length;c++){let d=!0;for(let l=0;l<s-1;l++){const u=o.slice(c+l*a,c+(l+1)*a),f=o.slice(c+(l+1)*a,c+(l+2)*a);if(!u.every((p,h)=>p===f[h])){d=!1;break}}if(d){const l=o.slice(c,c+a),u=l.every(h=>!h),f=l.every(h=>h),p=this.afData.animationFPS-this.vfcData.videoFPS;if(u||f&&p>5)continue;this.siData.RVFCpattern=l,this.siData.isRVFCpatternDetected=!0;break}}if(this.siData.isRVFCpatternDetected)break}}if(this.siData.RVFCpattern.length>0){const o=this.siData.RVFCpattern,a=this.siData.patternTracking;let c=-1;for(let d=a.length-o.length;d>=0;d--){let l=!0;for(let u=0;u<o.length;u++)if(o[u]!==a[d+u]){l=!1;break}if(l){c=d;break}}if(c>=0){const d=(a.length-c)%o.length,l=o[d];this.siData.patternTrackingIndex=d,this.siData.patternNextValue=l?1:0}if(a.length>=o.length*5){a.slice(a.length-o.length*5);let d=0,l=0;for(let u=0;u+o.length<=a.length;u++)a.slice(u,u+o.length).every((p,h)=>p===o[h])?(d++,l=Math.max(l,d),u+=o.length-1):d=0;l<6&&(this.siData.isRVFCpatternDetected=!1)}Math.abs(this.siData.avgExpectedRefreshRate-this.siData.refreshRate)>3&&(this.siData.isRVFCpatternDetected=!1)}if(this.metrics){performance.now();const o=[this.afData.lastTimestamp,this.vfcData.lastTimestamp,this.afData.previousTimestamp,this.vfcData.previousTimestamp].sort((l,u)=>u-l),a=o[0],c=o[1],d=a-c;this.siData.determineFramesIntervals||(this.siData.determineFramesIntervals=[]),this.siData.determineFramesIntervals.push(d.toFixed(2)),this.siData.determineFramesIntervals.length>10&&this.siData.determineFramesIntervals.shift(),this.metrics.updateMetric("Determine frames intervals",this.siData.determineFramesIntervals.join(", ")),this.metrics.updateMetric("RVFC missed",this.siData.RVFCmissed),this.metrics.updateMetric("Pattern found",this.siData.isRVFCpatternDetected),this.metrics.updateMetric("Pattern array",this.siData.RVFCpattern.map(l=>l?1:0).join("")),this.metrics.updateMetric("Pattern next index",this.siData.patternTrackingIndex),this.metrics.updateMetric("Pattern tracking",this.siData.patternTracking.slice(this.siData.patternTracking.length>100?this.siData.patternTracking.length-100:0).map(l=>l?1:0).join("")),this.metrics.updateMetric("Pattern next value",this.siData.patternNextValue),this.metrics.updateMetric("Refresh rate",this.siData.refreshRate.toFixed(2)),this.metrics.updateMetric("Expected Refresh Rate",this.siData.expectedRefreshRate),this.metrics.updateMetric("Avg Expected Refresh Rate",this.siData.avgExpectedRefreshRate.toFixed(2)),this.metrics.updateMetric("New Refresh Rate Frames",this.siData.newRefreshRateFrames)}if(!this.siData.isRAFSeen&&this.siData.isRVFCpatternDetected){let o=0,a=1,c=5;if(this.debugControls){const d=parseInt(this.debugControls.getValue("Pattern offset"),10);isNaN(d)||(o=d);const l=parseInt(this.debugControls.getValue("Frame Correction"),10);isNaN(l)||(a=l);const u=parseInt(this.debugControls.getValue("Timeout time"),10);isNaN(u)||(c=u)}this.siData.lastOffset!=this.vfcData.mediaTimeOffset&&(this.siData.lastOffset=this.vfcData.mediaTimeOffset,this.logger.info("didChangeOffset",{offset:this.vfcData.mediaTimeOffset}),this.logger.setAttributes({last_offset:this.vfcData.mediaTimeOffset})),this.siData.RVFCpattern[(this.siData.patternTrackingIndex+this.siData.RVFCpattern.length-1+o)%this.siData.RVFCpattern.length]?setTimeout(()=>this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+a),c):this.callRenderer(this.siData.lastRendererFrameSent)}},this.determineFrameUpdateChromeWin=()=>{if(this.resumedAt>0&&performance.now()-this.resumedAt<this.SKIP_PROCESSING_AFTER_RESUME_MS)return;const r=Math.round(1e3/this.vfcData.timeRVFCnowToExpectedDisplayTime);r>0&&r<500&&(this.expectedRefreshRateCalculator.addFrameDuration(this.vfcData.timeRVFCnowToExpectedDisplayTime/1e3),Math.abs(this.siData.expectedRefreshRate-r)>3?this.siData.newRefreshRateFrames++:(this.siData.expectedRefreshRate=r,this.siData.avgExpectedRefreshRate=this.expectedRefreshRateCalculator.getPerciseFPS()),this.siData.newRefreshRateFrames>10&&(this.siData.newRefreshRateFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedRefreshRate=r,this.siData.isRVFCpatternDetected=!1));const n=this.OTTPlayer.clocker.videoFPScalculator.getPerciseFPS();if(n>0&&n<500&&(Math.abs(this.siData.expectedFPS-n)>4?this.siData.newFPSFrames++:(this.siData.expectedFPS=n,this.siData.newFPSFrames=0),this.siData.newFPSFrames>10&&(this.siData.newFPSFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedFPS=n,this.siData.isRVFCpatternDetected=!1)),this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;const s=20,i=1e3;if(!this.siData.isRVFCSeen){const o=Math.round(this.vfcData.timeRVFCnowToExpectedDisplayTime/(1e3/this.afData.animationFPS));if(o<=0&&this.siData.patternTracking.length<=1-o){this.siData.patternTracking=[!0];for(let a=0;a<1-o;a++)this.siData.patternTracking.push(!1)}else o<=1&&(this.siData.patternTracking[this.siData.patternTracking.length-2+o]=!0)}if(this.siData.isRAFSeen||this.siData.patternTracking.push(!1),this.siData.patternTracking.length>i&&this.siData.patternTracking.shift(),!this.siData.isRVFCpatternDetected){const o=this.siData.patternTracking;for(let a=1;a*s<=o.length;a++){for(let c=0;c+a*s<=o.length;c++){let d=!0;for(let l=0;l<s-1;l++){const u=o.slice(c+l*a,c+(l+1)*a),f=o.slice(c+(l+1)*a,c+(l+2)*a);if(!u.every((p,h)=>p===f[h])){d=!1;break}}if(d){const l=o.slice(c,c+a),u=l.every(h=>!h),f=l.every(h=>h),p=this.afData.animationFPS-this.vfcData.videoFPS;if(u||f&&p>5)continue;this.siData.RVFCpattern=l,this.siData.isRVFCpatternDetected=!0;break}}if(this.siData.isRVFCpatternDetected)break}}if(this.siData.RVFCpattern.length>0){const o=this.siData.RVFCpattern,a=this.siData.patternTracking;let c=-1;for(let d=a.length-o.length;d>=0;d--){let l=!0;for(let u=0;u<o.length;u++)if(o[u]!==a[d+u]){l=!1;break}if(l){c=d;break}}if(c>=0){const d=(a.length-c)%o.length,l=o[d];this.siData.patternTrackingIndex=d,this.siData.patternNextValue=l?1:0}if(a.length>=o.length*5){a.slice(a.length-o.length*5);let d=0,l=0;for(let u=0;u+o.length<=a.length;u++)a.slice(u,u+o.length).every((p,h)=>p===o[h])?(d++,l=Math.max(l,d),u+=o.length-1):d=0;l<6&&(this.siData.isRVFCpatternDetected=!1)}Math.abs(this.siData.avgExpectedRefreshRate-this.siData.refreshRate)>3&&(this.siData.isRVFCpatternDetected=!1)}if(this.metrics){performance.now();const o=[this.afData.lastTimestamp,this.vfcData.lastTimestamp,this.afData.previousTimestamp,this.vfcData.previousTimestamp].sort((l,u)=>u-l),a=o[0],c=o[1],d=a-c;this.siData.determineFramesIntervals||(this.siData.determineFramesIntervals=[]),this.siData.determineFramesIntervals.push(d.toFixed(2)),this.siData.determineFramesIntervals.length>10&&this.siData.determineFramesIntervals.shift(),this.metrics.updateMetric("Determine frames intervals",this.siData.determineFramesIntervals.join(", ")),this.metrics.updateMetric("RVFC missed",this.siData.RVFCmissed),this.metrics.updateMetric("Pattern found",this.siData.isRVFCpatternDetected),this.metrics.updateMetric("Pattern array",this.siData.RVFCpattern.map(l=>l?1:0).join("")),this.metrics.updateMetric("Pattern next index",this.siData.patternTrackingIndex),this.metrics.updateMetric("Pattern tracking",this.siData.patternTracking.slice(this.siData.patternTracking.length>100?this.siData.patternTracking.length-100:0).map(l=>l?1:0).join("")),this.metrics.updateMetric("Pattern next value",this.siData.patternNextValue),this.metrics.updateMetric("Refresh rate",this.siData.refreshRate.toFixed(2)),this.metrics.updateMetric("Expected Refresh Rate",this.siData.expectedRefreshRate),this.metrics.updateMetric("Avg Expected Refresh Rate",this.siData.avgExpectedRefreshRate.toFixed(2)),this.metrics.updateMetric("New Refresh Rate Frames",this.siData.newRefreshRateFrames)}if(!this.siData.isRAFSeen&&this.siData.isRVFCpatternDetected){let o=0,a=2,c=!1;if(this.debugControls){const u=parseInt(this.debugControls.getValue("Pattern offset"),10);isNaN(u)||(o=u);const f=parseInt(this.debugControls.getValue("Frame Correction"),10);isNaN(f)||(a=f),parseInt(this.debugControls.getValue("Timeout time"),10),this.debugControls.getValue("Video Captur Card Mode")==="true"&&(c=!0)}this.siData.lastOffset!=this.vfcData.mediaTimeOffset&&(this.siData.lastOffset=this.vfcData.mediaTimeOffset,this.logger.info("didChangeOffset",{offset:this.vfcData.mediaTimeOffset}),this.logger.setAttributes({last_offset:this.vfcData.mediaTimeOffset})),c&&(o+=1);const d=(this.siData.patternTrackingIndex+this.siData.RVFCpattern.length-1+o)%this.siData.RVFCpattern.length,l=(d+this.siData.RVFCpattern.length-1)%this.siData.RVFCpattern.length;if(this.siData.RVFCpattern[d]){let u=0;c&&this.siData.lastRendererFrameSent==this.vfcData.lastCalculatedMediaTimeVideoFrame&&this.siData.RVFCpattern[l]&&(u=2),this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+u+a)}}},this.determineFrameUpdateSifariMac=()=>{if(this.resumedAt>0&&performance.now()-this.resumedAt<this.SKIP_PROCESSING_AFTER_RESUME_MS||(this.siData.expectedRefreshRate&&this.siData.expectedFPS&&(this.expectedRefreshRateCalculator.addFrameDuration(1/this.siData.refreshRate),this.siData.avgExpectedRefreshRate=this.expectedRefreshRateCalculator.getPerciseFPS(),Math.abs(this.siData.expectedRefreshRate-this.siData.avgExpectedRefreshRate)>3&&this.siData.newRefreshRateFrames++,Math.abs(this.siData.expectedFPS-this.siData.workingFps)>3&&this.siData.newFPSFrames++,(this.siData.newRefreshRateFrames>10||this.siData.newFPSFrames>10)&&(this.siData.newRefreshRateFrames=0,this.siData.expectedRefreshRate=0,this.siData.newFPSFrames=0,this.siData.expectedFPS=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.isRVFCpatternDetected=!1)),this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata))return;const r=Math.abs(this.siData.refreshRate-this.siData.workingFps)<2?8:20,n=1e3,s=[this.afData.lastTimestamp,this.vfcData.lastTimestamp,this.afData.previousTimestamp,this.vfcData.previousTimestamp].sort((h,m)=>m-h),i=2,o=s[0],a=s[1],c=o-a,d=1e3/this.afData.animationFPS,l=Math.round(d/4+.1),u=this.vfcData.timeRVFCnowToExpectedDisplayTime;if(this.siData.isRVFCSeen)this.metrics;else{const h=(-u-l)/d,m=Math.ceil(h),g=(Math.round(h)-h)*d,S=Math.abs(g)<=i,E=g<=0?m-1:m+1,A=Math.abs(-u-l)<=i;if(this.metrics&&(this.metrics.updateMetric("Is Smoothing Needed",S),this.metrics.updateMetric("Is More Than Border",m),this.metrics.updateMetric("Is Smoothed",E)),S&&!A){const w=Math.min(m,E),R=Math.max(m,E);this.metrics&&this.metrics.updateMetric("Pssblty next index",""+w+" "+R),this.siData.possibilityTracking[this.siData.possibilityTracking.length-w]=2,this.siData.possibilityTracking[this.siData.possibilityTracking.length-R]=1}else S&&A&&(this.metrics&&this.metrics.updateMetric("Pssblty next index","min"),this.siData.possibilityTracking[this.siData.possibilityTracking.length-1]=1,this.siData.possibilityTracking.push(2),this.siData.possibilityTracking.push(3));if(-u<l)this.siData.expectedDisplayTimeReminder=-u;else if(c>d&&-u-(c-d)<=l)this.siData.expectedDisplayTimeReminder=-u-(c-d);else{let w=-u-c,R=0,v=this.siData.determineFramesIntervals.length-1;for(let F=this.siData.determineAFIntervals.length-1;F>=0&&(v--,!(this.siData.determineAFIntervals[F]>d&&w-(this.siData.determineAFIntervals[F]-d)<=l||w<=l||this.siData.determineFramesIntervals[v].includes("vf")&&this.siData.workingFps<40));F--)w-=this.siData.determineAFIntervals[F],R+=1;if(this.siData.patternTracking.length<R+1){this.siData.patternTracking=[!0];for(let F=0;F<R;F++)this.siData.patternTracking.push(!1)}else this.siData.patternTracking[this.siData.patternTracking.length-1-R]=!0;this.siData.animationFramesToDisplayTime=R}}if(this.siData.isRAFSeen||(this.siData.expectedDisplayTimeReminder?(this.siData.expectedDisplayTimeReminder-l,this.siData.expectedDisplayTimeReminder+c<=l?(this.siData.patternTracking.push(!0),this.siData.animationFramesToDisplayTime=0):(this.siData.patternTracking[this.siData.patternTracking.length-1]=!0,this.siData.patternTracking.push(!1),this.siData.animationFramesToDisplayTime=1),this.siData.expectedDisplayTimeReminder=0):(this.siData.patternTracking.push(!1),this.siData.animationFramesToDisplayTime+=1),this.siData.possibilityTracking[this.siData.possibilityTracking.length-1]==3?this.siData.possibilityTracking.pop():this.siData.possibilityTracking.push(0)),this.siData.patternTracking.length>n&&this.siData.patternTracking.shift(),this.siData.possibilityTracking.length>n&&this.siData.possibilityTracking.shift(),!this.siData.isRVFCpatternDetected){const h=this.siData.patternTracking;for(let m=1;m*r<=h.length;m++){for(let g=0;g+m*r<=h.length;g++){let S=!0;for(let b=0;b<r-1;b++){const E=h.slice(g+b*m,g+(b+1)*m),A=h.slice(g+(b+1)*m,g+(b+2)*m);if(!E.every((w,R)=>w===A[R])){S=!1;break}}if(S){const b=h.slice(g,g+m),E=b.every(R=>!R),A=b.every(R=>R),w=this.afData.animationFPS-this.vfcData.videoFPS;if(E||A&&w>5)continue;this.siData.RVFCpattern=b,this.siData.isRVFCpatternDetected=!0;break}}if(this.siData.isRVFCpatternDetected){this.siData.expectedRefreshRate=this.siData.refreshRate,this.siData.expectedFPS=this.siData.workingFps;break}}}if(this.siData.RVFCpattern.length>0){const h=this.siData.RVFCpattern,m=this.siData.patternTracking;let g=-1;for(let S=m.length-h.length*5;S>=0;S--){let b=!0;for(let E=0;E<h.length*5;E++)if(h[E%h.length]!==m[S+E]){b=!1;break}if(b){g=S;break}}if(g>=0){const S=(m.length-g)%h.length,b=h[S];this.siData.patternTrackingIndex=S,this.siData.patternNextValue=b?1:0}if(m.length>=h.length*5){m.slice(m.length-h.length*5);let S=0,b=0;for(let E=0;E+h.length<=m.length;E++)m.slice(E,E+h.length).every((w,R)=>w===h[R])?(S++,b=Math.max(b,S),E+=h.length-1):S=0;b<6&&(this.siData.isRVFCpatternDetected=!1)}}const f=[];for(let h=1;h<=3;h++)f.push(this.siData.possibilityTracking[this.siData.possibilityTracking.length-this.siData.RVFCpattern.length*h]);const p=Math.max(...f);if(this.metrics){let h="";if(this.siData.isRAFSeen?h="vf: "+c.toFixed(0):h="af: "+c.toFixed(0),this.siData.determineFramesIntervals.push(h),this.siData.determineFramesIntervals.length>10&&this.siData.determineFramesIntervals.shift(),!this.siData.isRAFSeen){const m=this.afData.lastTimestamp-this.afData.previousTimestamp;this.siData.determineAFIntervals.push(m),this.siData.determineAFIntervals.length>10&&this.siData.determineAFIntervals.shift()}this.siData.isRVFCSeen||this.metrics.updateMetric("Last AF to VF time",(this.vfcData.lastTimestamp-this.afData.lastTimestamp).toFixed(0)),this.metrics.updateMetric("Determine frames intervals",this.siData.determineFramesIntervals.join(", ")),this.metrics.updateMetric("AF frames intervals",this.siData.determineAFIntervals.map(m=>m.toFixed(0)).join(", ")),this.metrics.updateMetric("RVFC missed",this.siData.RVFCmissed),this.metrics.updateMetric("Pattern found",this.siData.isRVFCpatternDetected),this.metrics.updateMetric("Pattern array",this.siData.RVFCpattern.map(m=>m?1:0).join("")),this.metrics.updateMetric("Pattern next index",this.siData.patternTrackingIndex),this.metrics.updateMetric("Pattern tracking",this.siData.patternTracking.map(m=>m?1:0).slice(this.siData.patternTracking.length>100?this.siData.patternTracking.length-100:0).join("")),this.metrics.updateMetric("Pattern next value",this.siData.patternNextValue),this.metrics.updateMetric("Pssblty found",this.siData.isRVFCpatternDetected),this.metrics.updateMetric("Pssblty array",this.siData.RVFCpattern.map(m=>m?1:0).join("")),this.metrics.updateMetric("Pssblty tracking",this.siData.possibilityTracking.slice(this.siData.possibilityTracking.length>100?this.siData.possibilityTracking.length-100:0).join("")),this.metrics.updateMetric("Pssblty next value",p),this.metrics.updateMetric("Refresh rate",this.siData.refreshRate.toFixed(2)),this.metrics.updateMetric("Expected Refresh Rate",this.siData.expectedRefreshRate.toFixed(5)),this.metrics.updateMetric("Avg Expected Refresh Rate",this.siData.avgExpectedRefreshRate.toFixed(5)),this.metrics.updateMetric("New Refresh Rate Frames",this.siData.newRefreshRateFrames),this.metrics.updateMetric("AF To Display Time",this.siData.animationFramesToDisplayTime),this.metrics.updateMetric("Call Renderer Reached",!1)}if(!this.siData.isRAFSeen&&this.siData.isRVFCpatternDetected){let h=0,m=0;if(this.debugControls){const S=parseInt(this.debugControls.getValue("Pattern offset"),10);isNaN(S)||(h=S);const b=parseInt(this.debugControls.getValue("Frame Correction"),10);isNaN(b)||(m=b),parseInt(this.debugControls.getValue("Timeout time"),10)}this.siData.lastOffset!=this.vfcData.mediaTimeOffset&&(this.siData.lastOffset=this.vfcData.mediaTimeOffset,this.logger.info("didChangeOffset",{offset:this.vfcData.mediaTimeOffset}),this.logger.setAttributes({last_offset:this.vfcData.mediaTimeOffset}));const g=(this.siData.patternTrackingIndex+this.siData.RVFCpattern.length+h)%this.siData.RVFCpattern.length;if(this.siData.RVFCpattern[g]||p){const S=Math.ceil(this.siData.animationFramesToDisplayTime/this.siData.RVFCpattern.length)+1,b=this.siData.RVFCpattern.map(ke=>ke?1:0).join("").repeat(S),E=(this.siData.RVFCpattern.length-this.siData.patternTrackingIndex)%this.siData.RVFCpattern.length,A=b.slice(0,E==0?-this.siData.RVFCpattern.length:-E);let w=0;const R=this.siData.possibilityTracking.length-1-this.siData.animationFramesToDisplayTime;A[A.length-1-this.siData.animationFramesToDisplayTime]=="0"&&this.siData.possibilityTracking[R]==1&&(w=-1);const v=this.siData.animationFramesToDisplayTime+w,F=v<=0?"":A.slice(-v);let De=F.split("").filter(ke=>ke==="1").length*Math.round(60/this.siData.workingFps);this.siData.workingFps<40&&(De+=1),this.siData.compensationMode&&!(p==2||this.siData.previousPossibilityValue==2)&&(this.siData.compensationCounter=1,this.siData.compensationMode=!1),this.siData.compensationCounter==1?this.siData.possibilityTracking.slice(-5).every(ke=>ke===0)&&(this.siData.compensationCounter-=.1):this.siData.compensationCounter>0&&this.siData.compensationCounter<1&&(this.siData.compensationCounter=Math.max(this.siData.compensationCounter-.1,0)),p==1?this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+De+m-1,this.siData.compensationCounter):p==2&&this.siData.previousPossibilityValue==1?this.callRenderer(this.siData.lastRendererFrameSent+1,this.siData.compensationCounter):this.siData.RVFCpattern[g]&&((p==2||this.siData.previousPossibilityValue==2)&&Math.abs(this.afData.animationFPS-this.siData.workingFps)<5&&this.siData.lastRendererFrameSent==this.vfcData.lastCalculatedMediaTimeVideoFrame+De+m?(this.callRenderer(this.siData.lastRendererFrameSent+1,this.siData.compensationCounter),this.siData.compensationMode=!0):this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+De+m,this.siData.compensationCounter)),this.metrics&&(this.metrics.updateMetric("Call Renderer Reached",!0),this.metrics.updateMetric("Is Smoothing Needed",this.siData.compensationMode),this.metrics.updateMetric("Correction",De),this.metrics.updateMetric("Compensation Counter",this.siData.compensationCounter),this.metrics.updateMetric("Repeated Pattern",b),this.metrics.updateMetric("Trimmed Pattern",A),this.metrics.updateMetric("Sliced Pattern",F),this.metrics.updateMetric("AF To Display Time Correction",w)),this.siData.previousPossibilityValue=p}else this.callRenderer(this.siData.lastRendererFrameSent)}},this.determineFrameUpdateFirefoxMac=()=>{if(this.resumedAt>0&&performance.now()-this.resumedAt<this.SKIP_PROCESSING_AFTER_RESUME_MS)return;const r=Math.round(1e3/this.vfcData.timeRVFCnowToExpectedDisplayTime);if(r>0&&r<500&&(this.expectedRefreshRateCalculator.addFrameDuration(this.vfcData.timeRVFCnowToExpectedDisplayTime/1e3),Math.abs(this.siData.expectedRefreshRate-r)>3?this.siData.newRefreshRateFrames++:(this.siData.expectedRefreshRate=r,this.siData.avgExpectedRefreshRate=this.expectedRefreshRateCalculator.getPerciseFPS()),this.siData.newRefreshRateFrames>10&&(this.siData.newRefreshRateFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedRefreshRate=r,this.siData.isRVFCpatternDetected=!1)),this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;const n=5,s=1e3;if(!this.siData.isRVFCSeen){const i=Math.round(this.vfcData.timeRVFCnowToExpectedDisplayTime/(1e3/this.afData.animationFPS));if(i<=0&&this.siData.patternTracking.length<=1-i){this.siData.patternTracking=[!0];for(let o=0;o<1-i;o++)this.siData.patternTracking.push(!1)}else i<=1&&(this.siData.patternTracking[this.siData.patternTracking.length-2+i]=!0)}if(this.siData.isRAFSeen||this.siData.patternTracking.push(!1),this.siData.patternTracking.length>s&&this.siData.patternTracking.shift(),!this.siData.isRVFCpatternDetected){const i=this.siData.patternTracking;for(let o=1;o*n<=i.length;o++){for(let a=0;a+o*n<=i.length;a++){let c=!0;for(let d=0;d<n-1;d++){const l=i.slice(a+d*o,a+(d+1)*o),u=i.slice(a+(d+1)*o,a+(d+2)*o);if(!l.every((f,p)=>f===u[p])){c=!1;break}}if(c){const d=i.slice(a,a+o),l=d.every(p=>!p),u=d.every(p=>p),f=this.afData.animationFPS-this.vfcData.videoFPS;if(l||u&&f>5)continue;this.siData.RVFCpattern=d,this.siData.isRVFCpatternDetected=!0;break}}if(this.siData.isRVFCpatternDetected)break}}if(this.siData.RVFCpattern.length>0){const i=this.siData.RVFCpattern,o=this.siData.patternTracking;let a=-1;for(let c=o.length-i.length;c>=0;c--){let d=!0;for(let l=0;l<i.length;l++)if(i[l]!==o[c+l]){d=!1;break}if(d){a=c;break}}if(a>=0){const c=(o.length-a)%i.length,d=i[c];this.siData.patternTrackingIndex=c,this.siData.patternNextValue=d?1:0}if(o.length>=i.length*5){o.slice(o.length-i.length*5);let c=0,d=0;for(let l=0;l+i.length<=o.length;l++)o.slice(l,l+i.length).every((f,p)=>f===i[p])?(c++,d=Math.max(d,c),l+=i.length-1):c=0;d<5&&(this.siData.isRVFCpatternDetected=!1)}Math.abs(this.siData.avgExpectedRefreshRate-this.siData.refreshRate)>3&&(this.siData.isRVFCpatternDetected=!1)}if(this.metrics){performance.now();const i=[this.afData.lastTimestamp,this.vfcData.lastTimestamp,this.afData.previousTimestamp,this.vfcData.previousTimestamp].sort((d,l)=>l-d),o=i[0],a=i[1],c=o-a;this.siData.determineFramesIntervals||(this.siData.determineFramesIntervals=[]),this.siData.determineFramesIntervals.push(c.toFixed(2)),this.siData.determineFramesIntervals.length>10&&this.siData.determineFramesIntervals.shift(),this.metrics.updateMetric("Determine frames intervals",this.siData.determineFramesIntervals.join(", ")),this.metrics.updateMetric("RVFC missed",this.siData.RVFCmissed),this.metrics.updateMetric("Pattern found",this.siData.isRVFCpatternDetected),this.metrics.updateMetric("Pattern array",this.siData.RVFCpattern.map(d=>d?1:0).join("")),this.metrics.updateMetric("Pattern next index",this.siData.patternTrackingIndex),this.metrics.updateMetric("Pattern tracking",this.siData.patternTracking.slice(this.siData.patternTracking.length>100?this.siData.patternTracking.length-100:0).map(d=>d?1:0).join("")),this.metrics.updateMetric("Pattern next value",this.siData.patternNextValue),this.metrics.updateMetric("Refresh rate",this.siData.refreshRate.toFixed(2)),this.metrics.updateMetric("Expected Refresh Rate",this.siData.expectedRefreshRate),this.metrics.updateMetric("Avg Expected Refresh Rate",this.siData.avgExpectedRefreshRate.toFixed(2)),this.metrics.updateMetric("New Refresh Rate Frames",this.siData.newRefreshRateFrames)}if(!this.siData.isRAFSeen&&this.siData.isRVFCpatternDetected){let i=0,o=1;if(this.debugControls){const a=parseInt(this.debugControls.getValue("Pattern offset"),10);isNaN(a)||(i=a);const c=parseInt(this.debugControls.getValue("Frame Correction"),10);isNaN(c)||(o=c),parseInt(this.debugControls.getValue("Timeout time"),10)}if(this.siData.lastOffset!=this.vfcData.mediaTimeOffset&&(this.siData.lastOffset=this.vfcData.mediaTimeOffset,this.logger.info("didChangeOffset",{offset:this.vfcData.mediaTimeOffset}),this.logger.setAttributes({last_offset:this.vfcData.mediaTimeOffset})),this.siData.RVFCpattern[(this.siData.patternTrackingIndex+this.siData.RVFCpattern.length-1+i)%this.siData.RVFCpattern.length]){let a=this.vfcData.lastCalculatedMediaTimeVideoFrame+o;a==this.siData.lastRendererFrameSent&&(a+=2),this.callRenderer(a)}else this.callRenderer(this.siData.lastRendererFrameSent)}},this.callRenderer=(r,n)=>{if(!this.OTTPlayer.clocker||!this.OTTPlayer)return;this.siData.lastRendererFrameSent=r,this.metrics&&this.metrics.updateMetric("Last sent frame",r);const s=this.OTTPlayer.clocker.videoFPScalculator.getFPS();this.metrics&&this.metrics.updateMetric("FPS",s.toFixed(2));const i=L.fromFrames(r,6e4/1001);this.renderAugmentation(i,n)},this.playbackTimeDelta=0,this.wallClockTimeDelta=0,this.dateTimeDelta=0,this.renderAugmentation=(r,n)=>{if(!this.OTTPlayer||!this.OTTPlayer.clocker)throw new Error("OTTPlayer is not initialized");const s=L.toStr(r);this.siData.lastMessageSent=s,this.options&&_(this.options,"Adapter")&&console.log(`Rendering augmentation for timecode: ${s} , ${r}`),this.metrics&&this.metrics.updateMetric("Last sent timecode",s),this.OTTPlayer.clocker.callRendererWorker(s,n)},this.onVideoSeeked=()=>{this.firstFrameTimecode=[0,0,0,0,0],this.firstFrameTimecodeSet=!1,this.isMKAdPlaying&&(this.options&&_(this.options,"Adapter")&&console.log("[Adapter] Resetting MK ad state after seek/scrub"),this.isMKAdPlaying=!1)},this.clearAugmentation=r=>{if(!this.OTTPlayer||!this.OTTPlayer.clocker)throw new Error("OTTPlayer is not initialized");const n=r?L.toStr(r):void 0;this.options&&_(this.options,"Adapter")&&console.log("Clearing augmentation"),this.OTTPlayer.clocker.callRendererWorker(n,0,!0)},this.logger=e.logger,this.OTTPlayer=e,this.options=e.options,this.benchmark=new pn(e.options.BENCHMARK_DURATION_SECONDS),this.options&&_(this.options,"Adapter")&&console.log("Adapter is initialized",this.OTTPlayer),this.video=e.video,this.debug=this.options.debug?this.options.debug.on:!1,this.expectedRefreshRateCalculator=new nt(20),I.isChromeMac())this.platformSpecificFrameUpdate=this.determineFrameUpdateChromeMac;else if(I.isChromeWin())this.platformSpecificFrameUpdate=this.determineFrameUpdateChromeWin;else{I.isSafariMac(),I.isFirefoxMac(),this.platformSpecificFrameUpdate=()=>{},this.logger.error("Unsupported platform: "+this.options.platform+" "+this.options.browserName),console.error("Unsupported platform: "+this.options.platform+" "+this.options.browserName),this.platformSupported=!1;return}if(this.debug){this.metrics=new jt;const r=this.metrics.createContainer(),n=this.metrics.createContainer(),s=this.metrics.createContainer(),i=this.metrics.createContainer(),o=this.metrics.createContainer(),a=this.metrics.createContainer(),c=this.metrics.createContainer(),d=this.metrics.createContainer(),l=this.metrics.createContainer(),u=this.metrics.createContainer(),f=this.metrics.createContainer(),p=this.metrics.createContainer(),h=this.metrics.createContainer(),m=this.metrics.createContainer(),g=this.metrics.createContainer(),S=this.metrics.createContainer();this.metrics.createMetric("tcTimeStamp",r),this.metrics.createMetric("timecodeOffset",r),this.metrics.createMetric("firstFrameTimecode",r),this.metrics.createMetric("frame",n),this.metrics.createMetric("playerTime",n),this.metrics.createMetric("stringTime",n),this.metrics.createMetric("lastUpdate",n),this.metrics.createMetric("MediaTime",s),this.metrics.createMetric("MediaTimeWithSync",s),this.metrics.createMetric("RAF calls",i),this.metrics.createMetric("RVFC calls",i),this.metrics.createMetric("RVFC missed",i),this.metrics.createMetric("Last sent frame",i),this.metrics.createMetric("Last sent timecode",i),this.metrics.createMetric("Last metadata media time",o),this.metrics.createMetric("Last player time",o),this.metrics.createMetric("RVFC to expected display time",o),this.metrics.createMetric("Performance Now to expected display time",o),this.metrics.createMetric("Last metadata media time frame",a),this.metrics.createMetric("Last player time frame",a),this.metrics.createMetric("Last player time fraction",a),this.metrics.createMetric("Last media time double frame",c),this.metrics.createMetric("Last player time double frame",c),this.metrics.createMetric("Compensation Counter",c),this.metrics.createMetric("AF metadata now - perf.now()",d),this.metrics.createMetric("VF metadata now - perf.now()",d),this.metrics.createMetric("VF ExpDispTime - AF metadata now",d),this.metrics.createMetric("Time to presentation time",l),this.metrics.createMetric("Metadata presented frames",l),this.metrics.createMetric("Metadata processing duration",l),this.metrics.createMetric("FPS",u),this.metrics.createMetric("Refresh rate",u),this.metrics.createMetric("Last RAF call",u),this.metrics.createMetric("Last RVFC call",u),this.metrics.createMetric("RAF - RVFC dif",u),this.metrics.createMetric("Determine frames intervals",f),this.metrics.createMetric("Last AF to VF time",p),this.metrics.createMetric("AF frames intervals",p),this.metrics.createMetric("Expected Refresh Rate",h),this.metrics.createMetric("Avg Expected Refresh Rate",h),this.metrics.createMetric("New Refresh Rate Frames",h),this.metrics.createMetric("AF To Display Time",h),this.metrics.createMetric("AF To Display Time Correction",h),this.metrics.createMetric("Call Renderer Reached",h),this.metrics.createMetric("Is Smoothing Needed",m),this.metrics.createMetric("Is More Than Border",m),this.metrics.createMetric("Is Smoothed",m),this.metrics.createMetric("Correction",m),this.metrics.createMetric("Repeated Pattern",m),this.metrics.createMetric("Trimmed Pattern",m),this.metrics.createMetric("Sliced Pattern",m),this.metrics.createMetric("Pattern found",g),this.metrics.createMetric("Pattern array",g),this.metrics.createMetric("Pattern tracking",g),this.metrics.createMetric("Pattern next index",g),this.metrics.createMetric("Pattern next value",g),this.metrics.createMetric("Pssblty found",S),this.metrics.createMetric("Pssblty array",S),this.metrics.createMetric("Pssblty tracking",S),this.metrics.createMetric("Pssblty next index",S),this.metrics.createMetric("Pssblty next value",S),this.debugControls=new un;const b=this.debugControls.createContainer(),E=this.debugControls.createContainer();this.debugControls.createInput("Window Start (ms)",4,b),this.debugControls.createInput("Window End (ms)",-11,b),this.debugControls.createSelect("Pattern offset",{"-5":-5,"-4":-4,"-3":-3,"-2":-2,"-1":-1,0:0,1:1,2:2,3:3,4:4,5:5},"0",b),this.debugControls.createCheckbox("Video Captur Card Mode",!1,b),I.isChromeWin()?this.debugControls.createSelect("Frame Correction",{"-4":-4,"-3":-3,"-2":-2,"-1":-1,0:0,1:1,2:2,3:3,4:4},"2",E):I.isSafariMac()?this.debugControls.createSelect("Frame Correction",{"-4":-4,"-3":-3,"-2":-2,"-1":-1,0:0,1:1,2:2,3:3,4:4},"0",E):this.debugControls.createSelect("Frame Correction",{"-4":-4,"-3":-3,"-2":-2,"-1":-1,0:0,1:1,2:2,3:3,4:4},"1",E),this.debugControls.createSelect("Timeout time",{0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,10:10,11:11,12:12,13:13,14:14,15:15,16:16,17:17,18:18,19:19,20:20},"5",E)}this.platformSupported&&(this.OTTPlayer.video.readyState>=3?this.setupAdapter():this.OTTPlayer.video.addEventListener("canplay",()=>this.setupAdapter(),{once:!0}))}isVideoFpsSupported(e){return e>pe.MIN_SUPPORTED_FPS&&e<=pe.MAX_SUPPORTED_FPS}setupAdapter(){const e=this.video;if(this.options.BURNED_TIMECODES_MODE){this.startBurnedPipeline();return}if(this.debug){const r=typeof wmcsdk<"u"?wmcsdk:wmcPlayer;console.log(r);const n=r.getAvailableVideoQualities(),s={};n.forEach(a=>{s[a.label]=a.id});const i=a=>{r.doSetVideoQuality(a.videoQuality)},o=this.debugControls.createContainer(i);this.debugControls.createSelect("videoQuality",s,n[0].id,o)}this.animationFrameLoopId=window.requestAnimationFrame(this.onAnimationFrame),this.videoFrameCallbackLoopId=e.requestVideoFrameCallback(this.onVideoFrame)}startBurnedPipeline(){this.gl2Decoder=new mn,this.burnedIntervalId=window.setInterval(this.sampleBurnedFrame,33)}stopBurnedPipeline(){this.burnedIntervalId&&(window.clearInterval(this.burnedIntervalId),this.burnedIntervalId=void 0),this.gl2Decoder&&(this.gl2Decoder.dispose(),this.gl2Decoder=void 0),this.burnedLastTcKey=-1}parseTcKey(e){const r=e.split("_");if(r.length<4)return-1;const n=parseInt(r[0],10)||0,s=parseInt(r[1],10)||0,i=parseInt(r[2],10)||0,o=parseInt(r[3],10)||0,a=r.length>=5&&r[4]==="1"?1:0;return((n*3600+s*60+i)*60+o)*2+a}runBenchmarkTest(){var s,i;const e=((s=this.OTTPlayer.clocker)==null?void 0:s.videoFPScalculator.getPerciseFPS())||0,r=this.isVideoFpsSupported(e),n=this.benchmark.test({gameParams:!!this.OTTPlayer.gameParams,browserSupported:this.platformSupported,patternDetected:this.siData.isRVFCpatternDetected,fpsSupported:r,noMKAdsPlaying:!this.isMKAdPlaying,syncPointSet:!!this.syncPoint});n.shouldClear&&(this.options&&_(this.options,"Adapter")&&console.log("[Benchmark] Failed - clearing augmentation. Reasons:",(i=n.failedConditions)==null?void 0:i.join(", ")),this.clearAugmentation())}updateStatusOverlay(){var i,o;const e=this.OTTPlayer.statusOverlay;e.updateMetric("support","browser",this.platformSupported,`${this.options.browserName} on ${this.options.platform}`),e.updateMetric("support","pattern",this.siData.isRVFCpatternDetected,this.siData.isRVFCpatternDetected?this.siData.RVFCpattern.map(a=>a?"1":"0").join("").slice(0,20):"Detecting...");const r=((i=this.OTTPlayer.clocker)==null?void 0:i.videoFPScalculator.getPerciseFPS())||0,n=this.isVideoFpsSupported(r);e.updateMetric("support","fps",n,r>0?`${r.toFixed(2)} fps`:"Detecting..."),e.updateMetric("support","game_params",!!this.OTTPlayer.gameParams),e.updateMetric("support","mk_ads",!this.isMKAdPlaying,this.isMKAdPlaying?"Ad in progress":"No ads"),this.syncPoint?e.updateMetric("timecode","sync_point",!0,this.syncPoint.stringTime):e.updateMetric("timecode","sync_point",!1,"Not set");const s=this.benchmark.getStatus();e.updateMetric("benchmark","status",s.state,s.state==="TESTING"?`Stability test: ${s.remainingSeconds}s`:s.state==="FAILED"?`Failed: ${(o=s.failedConditions)==null?void 0:o.join(", ")}`:"Stable")}onNewSegmentForMetadata(e){if(!this.firstFrameTimecodeSet){const a=performance.now();a-this.loggerTimeoutStart>this.loggerTimeout&&(this.loggerTimeoutStart=a,this.logger.error("[Adapter] First frame timecode of the recieved segment not set")),console.error("[Adapter] First frame timecode of the recieved segment not set");return}const r=fn(this.firstFrameTimecode,6e4/1001);if(!e.mimeType.includes("video"))return;const n=hn(this.firstFrameTimecode,!0,!0);this.options&&_(this.options,"Adapter")&&console.log("New segment ("+e.url+"): "+n+" ("+r+") playing at "+e.playbackTime);const s=e.playbackTime;s-this.playbackTimeDelta,this.playbackTimeDelta=s;const i=e.wallClockTime/1e3;if(i-this.wallClockTimeDelta,this.wallClockTimeDelta=i,e.dateTime instanceof Date){const a=e.dateTime.getTime()/1e3;a-this.dateTimeDelta,this.dateTimeDelta=a}const o={frame:r,playerTime:s,stringTime:n,lastUpdate:performance.now()};this.syncPoint=o,this.metrics&&(this.metrics.updateMetric("frame",o.frame),this.metrics.updateMetric("playerTime",o.playerTime),this.metrics.updateMetric("stringTime",o.stringTime),this.metrics.updateMetric("lastUpdate",o.lastUpdate)),this.options&&_(this.options,"Adapter")&&console.log("url: "+e.url)}onNewMetadata(e){if(e&&e.metadata&&e.metadata.id==0||I.isSafariMac()){console.log("onNewMetadata: ",e);let r=!1;if(e.metadata.messageData)r=this.processTimedMetadata(e.metadata.messageData,e.metadata.presentationTime);else if(e.metadata.frames&&e.metadata.frames.length&&e.metadata.frames[0].key&&e.metadata.frames[0].key.toLowerCase()==="priv"){const n=e.metadata.frames.filter(s=>s.info&&s.info.toLowerCase().includes("ntc"));if(n.length){const s=`${n[n.length-1].info}\0${String.fromCharCode(...n[n.length-1].data)}`;r=this.processTimedMetadata(s,e.metadata.presentationTime)}}if(r&&(e.metadata.id==0||I.isSafariMac()&&this.timecode_offset==0)){e.metadata.presentationTime*1e3,this.logger.setAttributes({id3_metadata:this.tcTimeStamp-this.timecode_offset});const n=new Date(this.tcTimeStamp-this.timecode_offset);let s=Math.round(n.getUTCMilliseconds()*30*2/1001)/2;const i=s%1;let o=1;i==.5&&(s=Math.floor(s),o=2),this.firstFrameTimecode=[n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),Math.floor(s),o==1?0:1],this.logger.setAttributes({segment_first_frame_timecode:this.firstFrameTimecode}),this.firstFrameTimecodeSet||this.logger.info(`[Adapter] Segment first frame timecode set: ${this.firstFrameTimecode}`),this.firstFrameTimecodeSet=!0,console.log("First frame timecode reciesved at: ",new Date().toISOString()),console.log("First frame timecode: ",this.firstFrameTimecode),console.log("video.currentTime: ",this.video.currentTime),console.log("video.currentTime to UTC: ",new Date(this.video.currentTime*1e3).toISOString()),this.metrics&&(this.metrics.updateMetric("tcTimeStamp",this.tcTimeStamp),this.metrics.updateMetric("timecodeOffset",this.timecode_offset),this.metrics.updateMetric("firstFrameTimecode",this.firstFrameTimecode.join(",")))}}}onAdEvent(e){this.options&&_(this.options,"Adapter")&&console.log(`MK Ad event: ${e}`),this.isMKAdPlaying=e==="start"}parseId3Tag(e,r){console.log("Parsing ID3 tag: ",r);const n=e.exec(r);return n&&n[1]?n[1]:null}processTimedMetadata(e,r){if(e&&e.includes("www.mediakind.com/NTC")){let n=!1;const s=/tc__[\s\S]{4}(\d+)/,i=this.parseId3Tag(s,e);i?(this.tcTimeStamp=new Date(parseInt(i)).getTime(),console.log(`NewTcTimeStamp: ${this.tcTimeStamp}`),n=!0):console.log("tcTimeStamp not found.");const o=/offs[\s\S]{4}(\d+)/,a=this.parseId3Tag(o,e);return a?(this.timecode_offset=parseInt(a)/90,console.log(`New Extracted offset: ${this.timecode_offset}`),n=!0):console.log("offset not found."),n}return!1}pause(){this.animationFrameLoopId&&(cancelAnimationFrame(this.animationFrameLoopId),this.animationFrameLoopId=void 0),this.videoFrameCallbackLoopId&&(this.video.cancelVideoFrameCallback(this.videoFrameCallbackLoopId),this.videoFrameCallbackLoopId=void 0),this.burnedIntervalId&&(clearInterval(this.burnedIntervalId),this.burnedIntervalId=void 0)}resume(){this.resumedAt=performance.now(),this.options&&_(this.options,"Adapter")&&console.log("[Adapter] Resumed - skipping expensive processing for",this.SKIP_PROCESSING_AFTER_RESUME_MS,"ms"),this.siData.patternTracking=[],this.siData.possibilityTracking=[],this.siData.determineFramesIntervals=[],this.siData.determineAFIntervals=[],this.siData.isRVFCpatternDetected=!1,this.siData.RVFCpattern=[],this.siData.expectedRefreshRate=0,this.siData.expectedFPS=0,this.siData.newRefreshRateFrames=0,this.siData.newFPSFrames=0,this.animationFrameLoopId||(this.animationFrameLoopId=window.requestAnimationFrame(this.onAnimationFrame)),this.videoFrameCallbackLoopId||(this.videoFrameCallbackLoopId=this.video.requestVideoFrameCallback(this.onVideoFrame)),this.options.BURNED_TIMECODES_MODE&&!this.burnedIntervalId&&(this.burnedIntervalId=window.setInterval(this.sampleBurnedFrame,33))}delete(){this.options.BURNED_TIMECODES_MODE&&this.stopBurnedPipeline(),this.animationFrameLoopId&&cancelAnimationFrame(this.animationFrameLoopId),this.videoFrameCallbackLoopId&&this.video.cancelVideoFrameCallback(this.videoFrameCallbackLoopId),this.intervalLoopId&&clearInterval(this.intervalLoopId),this.metrics&&this.metrics.delete(),this.debugControls&&this.debugControls.delete()}};pe.MIN_SUPPORTED_FPS=20,pe.MAX_SUPPORTED_FPS=40;let it=pe;class q{constructor(e,r){this.size=1,this.positionElement=()=>{let s=0,i=0;this.corner=="left-top"?(this.element.style.top=`${s}px`,this.element.style.left=`${i}px`):this.corner=="right-top"?(this.element.style.top=`${s}px`,this.element.style.left=`${i+this.video.offsetWidth-this.size}px`):this.corner=="right-bottom"?(this.element.style.top=`${s+this.video.offsetHeight-this.size}px`,this.element.style.left=`${i+this.video.offsetWidth-this.size}px`):this.corner=="left-bottom"&&(this.element.style.top=`${s+this.video.offsetHeight-this.size}px`,this.element.style.left=`${i}px`)},this.video=r,this.container=r.parentElement,this.corner=e;const n=document.createElement("div");n.style.position="absolute",n.style.width=`${this.size}px`,n.style.height=`${this.size}px`,n.style.transition="background-color 0s",n.style.zIndex="100000",this.element=n,this.container.appendChild(n),this.positionElement()}getRandomColor(){const n=Math.floor(Math.random()*11)+0;return`rgb(${n},${n},${n})`}update(){this.element.style.backgroundColor=this.getRandomColor(),this.positionElement()}delete(){this.container.removeChild(this.element)}static createInAllCorners(e){return[new q("left-top",e),new q("right-top",e),new q("right-bottom",e),new q("left-bottom",e)]}static updateAll(e){e.forEach(r=>r.update())}static deleteAll(e){e.forEach(r=>r.delete())}}const C={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},M=console,X={};Object.keys(C).forEach(t=>{X[t]=M[t]});const ge="Datadog Browser SDK:",D={debug:X.debug.bind(M,ge),log:X.log.bind(M,ge),info:X.info.bind(M,ge),warn:X.warn.bind(M,ge),error:X.error.bind(M,ge)},ot="https://docs.datadoghq.com",Yt=`${ot}/real_user_monitoring/browser/troubleshooting`,Fe="More details:";function qt(t,e){return(...r)=>{try{return t(...r)}catch(n){D.error(e,n)}}}function Le(t){return t!==0&&Math.random()*100<=t}function gn(t){return yn(t)&&t>=0&&t<=100}function yn(t){return typeof t=="number"}const ye=1e3,K=60*ye,Xt=60*K,_n=365*(24*Xt);function _e(){return new Date().getTime()}function G(){return _e()}function Pe(){return performance.now()}function V(){return{relative:Pe(),timeStamp:G()}}function bn(){return{relative:0,timeStamp:Kt()}}function vn(t,e){return e-t}function Tn(t,e){return t+e}function Sn(t){return t-Kt()}let at;function Kt(){return at===void 0&&(at=performance.timing.navigationStart),at}const B=1024,Jt=1024*B,En=/[^\u0000-\u007F]/;function ct(t){return En.test(t)?window.TextEncoder!==void 0?new TextEncoder().encode(t).length:new Blob([t]).size:t.length}function xn(t){return{...t}}function Zt(t,e){return Object.keys(t).some(r=>t[r]===e)}function be(t){return Object.keys(t).length===0}function H(){if(typeof globalThis=="object")return globalThis;Object.defineProperty(Object.prototype,"_dd_temp_",{get(){return this},configurable:!0});let t=_dd_temp_;return delete Object.prototype._dd_temp_,typeof t!="object"&&(typeof self=="object"?t=self:typeof window=="object"?t=window:t={}),t}function oe(t,e){const r=H();let n;return r.Zone&&typeof r.Zone.__symbol__=="function"&&(n=t[r.Zone.__symbol__(e)]),n||(n=t[e]),n}let Oe,Qt=!1;function wn(t){Oe=t}function An(t){Qt=t}function Rn(t,e,r){const n=r.value;r.value=function(...s){return(Oe?x(n):n).apply(this,s)}}function x(t){return function(){return ve(t,this,arguments)}}function ve(t,e,r){try{return t.apply(e,r)}catch(n){Cn(n)}}function Cn(t){if(lt(t),Oe)try{Oe(t)}catch(e){lt(e)}}function lt(...t){Qt&&D.error("[MONITOR]",...t)}function Te(t,e){return oe(H(),"setTimeout")(x(t),e)}function er(t){oe(H(),"clearTimeout")(t)}function dt(t,e){return oe(H(),"setInterval")(x(t),e)}function tr(t){oe(H(),"clearInterval")(t)}class k{constructor(e){this.onFirstSubscribe=e,this.observers=[]}subscribe(e){return this.observers.push(e),this.observers.length===1&&this.onFirstSubscribe&&(this.onLastUnsubscribe=this.onFirstSubscribe(this)||void 0),{unsubscribe:()=>{this.observers=this.observers.filter(r=>e!==r),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}}notify(e){this.observers.forEach(r=>r(e))}}function rr(...t){return new k(e=>{const r=t.map(n=>n.subscribe(s=>e.notify(s)));return()=>r.forEach(n=>n.unsubscribe())})}function nr(t,e,r){let n=!1,s,i;return{throttled:(...o)=>{if(n){s=o;return}t(...o),n=!0,i=Te(()=>{s&&t(...s),n=!1,s=void 0},e)},cancel:()=>{er(i),n=!1,s=void 0}}}function W(){}function j(t){return t?(parseInt(t,10)^Math.random()*16>>parseInt(t,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,j)}const Ie=/([\w-]+)\s*=\s*([^;]+)/g;function Dn(t,e){for(Ie.lastIndex=0;;){const r=Ie.exec(t);if(r){if(r[1]===e)return r[2]}else break}}function kn(t){const e=new Map;for(Ie.lastIndex=0;;){const r=Ie.exec(t);if(r)e.set(r[1],r[2]);else break}return e}function Un(t,e,r=""){const n=t.charCodeAt(e-1),i=n>=55296&&n<=56319?e+1:e;return t.length<=i?t:`${t.slice(0,i)}${r}`}function Fn(){return Ln()===0}let Me;function Ln(){return Me??(Me=Pn())}function Pn(t=window){var e;const r=t.navigator.userAgent;return t.chrome||/HeadlessChrome/.test(r)?0:((e=t.navigator.vendor)===null||e===void 0?void 0:e.indexOf("Apple"))===0||/safari/i.test(r)&&!/chrome|android/i.test(r)?1:2}function Se(t,e,r=0,n){const s=new Date;s.setTime(s.getTime()+r);const i=`expires=${s.toUTCString()}`,o=n&&n.crossSite?"none":"strict",a=n&&n.domain?`;domain=${n.domain}`:"",c=n&&n.secure?";secure":"",d=n&&n.partitioned?";partitioned":"";document.cookie=`${t}=${e};${i};path=/;samesite=${o}${a}${c}${d}`}function ut(t){return Dn(document.cookie,t)}let ht;function J(t){return ht||(ht=kn(document.cookie)),ht.get(t)}function sr(t,e){Se(t,"",0,e)}function On(t){if(document.cookie===void 0||document.cookie===null)return!1;try{const e=`dd_cookie_test_${j()}`,r="test";Se(e,r,K,t);const n=ut(e)===r;return sr(e,t),n}catch(e){return D.error(e),!1}}let ft;function In(){if(ft===void 0){const t=`dd_site_test_${j()}`,e="test",r=window.location.hostname.split(".");let n=r.pop();for(;r.length&&!ut(t);)n=`${r.pop()}.${n}`,Se(t,e,ye,{domain:n});sr(t,{domain:n}),ft=n}return ft}const ae="_dd_s";function Be(t){return Object.values(t)}function Mn(t){return Object.entries(t)}const pt=4*Xt,ir=15*K,Bn=_n,Ee={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},or=/^([a-zA-Z]+)=([a-z0-9-]+)$/,mt="&";function Nn(t){return!!t&&(t.indexOf(mt)!==-1||or.test(t))}const zn="1";function Z(t,e){const r={isExpired:zn};return e.trackAnonymousUser&&(t!=null&&t.anonymousId?r.anonymousId=t==null?void 0:t.anonymousId:r.anonymousId=j()),r}function Ne(t){return be(t)}function ar(t){return!Ne(t)}function ze(t){return t.isExpired!==void 0||!$n(t)}function $n(t){return(t.created===void 0||_e()-Number(t.created)<pt)&&(t.expire===void 0||_e()<Number(t.expire))}function cr(t){t.expire=String(_e()+ir)}function gt(t){return Mn(t).map(([e,r])=>e==="anonymousId"?`aid=${r}`:`${e}=${r}`).join(mt)}function lr(t){const e={};return Nn(t)&&t.split(mt).forEach(r=>{const n=or.exec(r);if(n!==null){const[,s,i]=n;s==="aid"?e.anonymousId=i:e[s]=i}}),e}const Gn="_dd",Vn="_dd_r",Hn="_dd_l",Wn="rum",jn="logs";function Yn(t){if(!J(ae)){const r=J(Gn),n=J(Vn),s=J(Hn),i={};r&&(i.id=r),s&&/^[01]$/.test(s)&&(i[jn]=s),n&&/^[012]$/.test(n)&&(i[Wn]=n),ar(i)&&(cr(i),t.persistSession(i))}}function dr(t){const e=Zn(t);return On(e)?{type:Ee.COOKIE,cookieOptions:e}:void 0}function qn(t,e){const r={isLockEnabled:Fn(),persistSession:Xn(e),retrieveSession:Jn,expireSession:n=>Kn(e,n,t)};return Yn(r),r}function Xn(t){return e=>{Se(ae,gt(e),ir,t)}}function Kn(t,e,r){const n=Z(e,r);Se(ae,gt(n),r.trackAnonymousUser?Bn:pt,t)}function Jn(){const t=ut(ae);return lr(t)}function Zn(t){const e={};return e.secure=!!t.useSecureSessionCookie||!!t.usePartitionedCrossSiteSessionCookie,e.crossSite=!!t.usePartitionedCrossSiteSessionCookie,e.partitioned=!!t.usePartitionedCrossSiteSessionCookie,t.trackSessionAcrossSubdomains&&(e.domain=In()),e}const Qn="_dd_test_";function ur(){try{const t=j(),e=`${Qn}${t}`;localStorage.setItem(e,t);const r=localStorage.getItem(e);return localStorage.removeItem(e),t===r?{type:Ee.LOCAL_STORAGE}:void 0}catch{return}}function es(t){return{isLockEnabled:!1,persistSession:hr,retrieveSession:ts,expireSession:e=>rs(e,t)}}function hr(t){localStorage.setItem(ae,gt(t))}function ts(){const t=localStorage.getItem(ae);return lr(t)}function rs(t,e){hr(Z(t,e))}const ns=10,ss=100,fr=[];let $e;function Q(t,e,r=0){var n;const{isLockEnabled:s,persistSession:i,expireSession:o}=e,a=f=>i({...f,lock:d}),c=()=>{const f=e.retrieveSession(),p=f.lock;return f.lock&&delete f.lock,{session:f,lock:p}};if($e||($e=t),t!==$e){fr.push(t);return}if(s&&r>=ss){pr(e);return}let d,l=c();if(s){if(l.lock){Ge(t,e,r);return}if(d=j(),a(l.session),l=c(),l.lock!==d){Ge(t,e,r);return}}let u=t.process(l.session);if(s&&(l=c(),l.lock!==d)){Ge(t,e,r);return}if(u&&(ze(u)?o(u):(cr(u),s?a(u):i(u))),s&&!(u&&ze(u))){if(l=c(),l.lock!==d){Ge(t,e,r);return}i(l.session),u=l.session}(n=t.after)===null||n===void 0||n.call(t,u||l.session),pr(e)}function Ge(t,e,r){Te(()=>{Q(t,e,r+1)},ns)}function pr(t){$e=void 0;const e=fr.shift();e&&Q(e,t)}const mr=ye;function is(t){switch(t.sessionPersistence){case Ee.COOKIE:return dr(t);case Ee.LOCAL_STORAGE:return ur();case void 0:{let e=dr(t);return!e&&t.allowFallbackToLocalStorage&&(e=ur()),e}default:D.error(`Invalid session persistence '${String(t.sessionPersistence)}'`)}}function os(t,e,r,n){const s=new k,i=new k,o=new k,a=t.type===Ee.COOKIE?qn(e,t.cookieOptions):es(e),{expireSession:c}=a,d=dt(h,mr);let l;g();const{throttled:u,cancel:f}=nr(()=>{Q({process:v=>{if(Ne(v))return;const F=m(v);return S(F),F},after:v=>{ar(v)&&!b()&&w(v),l=v}},a)},mr);function p(){Q({process:v=>b()?m(v):void 0},a)}function h(){Q({process:v=>ze(v)?Z(v,e):void 0,after:m},a)}function m(v){return ze(v)&&(v=Z(v,e)),b()&&(E(v)?A():(o.notify({previousState:l,newState:v}),l=v)),v}function g(){Q({process:v=>{if(Ne(v))return Z(v,e)},after:v=>{l=v}},a)}function S(v){if(Ne(v))return!1;const{trackingType:F,isTracked:Mt}=n(v[r]);v[r]=F,delete v.isExpired,Mt&&!v.id&&(v.id=j(),v.created=String(_e()))}function b(){return l[r]!==void 0}function E(v){return l.id!==v.id||l[r]!==v[r]}function A(){l=Z(l,e),i.notify()}function w(v){l=v,s.notify()}function R(v){Q({process:F=>({...F,...v}),after:m},a)}return{expandOrRenewSession:u,expandSession:p,getSession:()=>l,renewObservable:s,expireObservable:i,sessionStateUpdateObservable:o,restartSession:g,expire:()=>{f(),c(l),m(Z(l,e))},stop:()=>{tr(d)},updateSessionState:R}}const yt={GRANTED:"granted",NOT_GRANTED:"not-granted"};function as(t){const e=new k;return{tryToInit(r){t||(t=r)},update(r){t=r,e.notify()},isGranted(){return t===yt.GRANTED},observable:e}}function ee(t,e,r){if(typeof t!="object"||t===null)return JSON.stringify(t);const n=ce(Object.prototype),s=ce(Array.prototype),i=ce(Object.getPrototypeOf(t)),o=ce(t);try{return JSON.stringify(t,e,r)}catch{return"<error: unable to serialize object>"}finally{n(),s(),i(),o()}}function ce(t){const e=t,r=e.toJSON;return r?(delete e.toJSON,()=>{e.toJSON=r}):W}function _t(t){return cs(t,location.href).href}function cs(t,e){const r=ls();if(r)try{return e!==void 0?new r(t,e):new r(t)}catch(i){throw new Error(`Failed to construct URL: ${String(i)} ${ee({url:t,base:e})}`)}if(e===void 0&&!/:/.test(t))throw new Error(`Invalid URL: '${t}'`);let n=document;const s=n.createElement("a");if(e!==void 0){n=document.implementation.createHTMLDocument("");const i=n.createElement("base");i.href=e,n.head.appendChild(i),n.body.appendChild(s)}return s.href=t,s}const gr=URL;let Ve;function ls(){if(Ve===void 0)try{Ve=new gr("http://test/path").href==="http://test/path"}catch{Ve=!1}return Ve?gr:void 0}const ds="datad0g.com",us="dd0g-gov.com",le="datadoghq.com",hs="ddog-gov.com",fs="pci.browser-intake-datadoghq.com",ps=["ddsource","ddtags"];function xe(t,e,r){const n=ms(t,e);return{build(s,i){const o=ys(t,e,r,s,i);return n(o)},urlPrefix:n(""),trackType:e}}function ms(t,e){const r=`/api/v2/${e}`,n=t.proxy;if(typeof n=="string"){const i=_t(n);return o=>`${i}?ddforward=${encodeURIComponent(`${r}?${o}`)}`}if(typeof n=="function")return i=>n({path:r,parameters:i});const s=gs(e,t);return i=>`https://${s}${r}?${i}`}function gs(t,e){const{site:r=le,internalAnalyticsSubdomain:n}=e;if(t==="logs"&&e.usePciIntake&&r===le)return fs;if(n&&r===le)return`${n}.${le}`;if(r===us)return`http-intake.logs.${r}`;const s=r.split("."),i=s.pop();return`browser-intake-${s.join("-")}.${i}`}function ys({clientToken:t,internalAnalyticsSubdomain:e},r,n,s,{retry:i,encoding:o}){const a=["sdk_version:6.5.0",`api:${s}`].concat(n);i&&a.push(`retry_count:${i.count}`,`retry_after:${i.lastFailureStatus}`);const c=["ddsource=browser",`ddtags=${encodeURIComponent(a.join(","))}`,`dd-api-key=${t}`,`dd-evp-origin-version=${encodeURIComponent("6.5.0")}`,"dd-evp-origin=browser",`dd-request-id=${j()}`];return o&&c.push(`dd-evp-encoding=${o}`),r==="rum"&&c.push(`batch_time=${G()}`),e&&c.reverse(),c.join("&")}const _s=200;function bs(t){const{env:e,service:r,version:n,datacenter:s}=t,i=[];return e&&i.push(He("env",e)),r&&i.push(He("service",r)),n&&i.push(He("version",n)),s&&i.push(He("datacenter",s)),i}function He(t,e){const r=_s-t.length-1;(e.length>r||vs(e))&&D.warn(`${t} value doesn't meet tag requirements and will be sanitized. ${Fe} ${ot}/getting_started/tagging/#defining-tags`);const n=e.replace(/,/g,"_");return`${t}:${n}`}function vs(t){return Ts()?new RegExp("[^\\p{Ll}\\p{Lo}0-9_:./-]","u").test(t):!1}function Ts(){try{return new RegExp("[\\p{Ll}]","u"),!0}catch{return!1}}function Ss(t){const e=t.site||le,r=bs(t),n=Es(t,r);return{replica:xs(t,r),site:e,...n}}function Es(t,e){return{logsEndpointBuilder:xe(t,"logs",e),rumEndpointBuilder:xe(t,"rum",e),sessionReplayEndpointBuilder:xe(t,"replay",e)}}function xs(t,e){if(!t.replica)return;const r={...t,site:le,clientToken:t.replica.clientToken},n={logsEndpointBuilder:xe(r,"logs",e),rumEndpointBuilder:xe(r,"rum",e)};return{applicationId:t.replica.applicationId,...n}}function ws(t){return ps.every(e=>t.includes(e))}function bt(t,e){return t!=null&&typeof t!="string"?(D.error(`${e} must be defined as a string`),!1):!0}function As(t){return t&&typeof t=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(t)?(D.error(`Site should be a valid Datadog site. ${Fe} ${ot}/getting_started/site/.`),!1):!0}function We(t,e){return t!==void 0&&!gn(t)?(D.error(`${e} Sample Rate should be a number between 0 and 100`),!1):!0}function Rs(t){var e,r,n,s,i,o;if(!t||!t.clientToken){D.error("Client Token is not configured, we will not send any data.");return}if(!(!As(t.site)||!We(t.sessionSampleRate,"Session")||!We(t.telemetrySampleRate,"Telemetry")||!We(t.telemetryConfigurationSampleRate,"Telemetry Configuration")||!We(t.telemetryUsageSampleRate,"Telemetry Usage")||!bt(t.version,"Version")||!bt(t.env,"Env")||!bt(t.service,"Service"))){if(t.trackingConsent!==void 0&&!Zt(yt,t.trackingConsent)){D.error('Tracking Consent should be either "granted" or "not-granted"');return}return{beforeSend:t.beforeSend&&qt(t.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:is(t),sessionSampleRate:(e=t.sessionSampleRate)!==null&&e!==void 0?e:100,telemetrySampleRate:(r=t.telemetrySampleRate)!==null&&r!==void 0?r:20,telemetryConfigurationSampleRate:(n=t.telemetryConfigurationSampleRate)!==null&&n!==void 0?n:5,telemetryUsageSampleRate:(s=t.telemetryUsageSampleRate)!==null&&s!==void 0?s:5,service:t.service||void 0,silentMultipleInit:!!t.silentMultipleInit,allowUntrustedEvents:!!t.allowUntrustedEvents,trackingConsent:(i=t.trackingConsent)!==null&&i!==void 0?i:yt.GRANTED,trackAnonymousUser:(o=t.trackAnonymousUser)!==null&&o!==void 0?o:!0,storeContextsAcrossPages:!!t.storeContextsAcrossPages,batchBytesLimit:16*B,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*ye,batchMessagesLimit:50,messageBytesLimit:256*B,...Ss(t)}}}function Cs(t){return{session_sample_rate:t.sessionSampleRate,telemetry_sample_rate:t.telemetrySampleRate,telemetry_configuration_sample_rate:t.telemetryConfigurationSampleRate,telemetry_usage_sample_rate:t.telemetryUsageSampleRate,use_before_send:!!t.beforeSend,use_partitioned_cross_site_session_cookie:t.usePartitionedCrossSiteSessionCookie,use_secure_session_cookie:t.useSecureSessionCookie,use_proxy:!!t.proxy,silent_multiple_init:t.silentMultipleInit,track_session_across_subdomains:t.trackSessionAcrossSubdomains,track_anonymous_user:t.trackAnonymousUser,session_persistence:t.sessionPersistence,allow_fallback_to_local_storage:!!t.allowFallbackToLocalStorage,store_contexts_across_pages:!!t.storeContextsAcrossPages,allow_untrusted_events:!!t.allowUntrustedEvents,tracking_consent:t.trackingConsent}}var vt;(function(t){t.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",t.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(vt||(vt={}));const yr=new Set;function Ds(t){Array.isArray(t)&&ks(t.filter(e=>Zt(vt,e)))}function ks(t){t.forEach(e=>{yr.add(e)})}function Us(){return yr}const we="?";function N(t){const e=[];let r=Tt(t,"stack");const n=String(t);return r&&r.startsWith(n)&&(r=r.slice(n.length)),r&&r.split(`
|
|
495
495
|
`).forEach(s=>{const i=Ps(s)||Is(s)||Bs(s)||$s(s);i&&(!i.func&&i.line&&(i.func=we),e.push(i))}),{message:Tt(t,"message"),name:Tt(t,"name"),stack:e}}const _r="((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\w+\\.|\\/).*?)",de="(?::(\\d+))",Fs=new RegExp(`^\\s*at (.*?) ?\\(${_r}${de}?${de}?\\)?\\s*$`,"i"),Ls=new RegExp(`\\((\\S*)${de}${de}\\)`);function Ps(t){const e=Fs.exec(t);if(!e)return;const r=e[2]&&e[2].indexOf("native")===0,n=e[2]&&e[2].indexOf("eval")===0,s=Ls.exec(e[2]);return n&&s&&(e[2]=s[1],e[3]=s[2],e[4]=s[3]),{args:r?[e[2]]:[],column:e[4]?+e[4]:void 0,func:e[1]||we,line:e[3]?+e[3]:void 0,url:r?void 0:e[2]}}const Os=new RegExp(`^\\s*at ?${_r}${de}?${de}??\\s*$`,"i");function Is(t){const e=Os.exec(t);if(e)return{args:[],column:e[3]?+e[3]:void 0,func:we,line:e[2]?+e[2]:void 0,url:e[1]}}const Ms=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;function Bs(t){const e=Ms.exec(t);if(e)return{args:[],column:e[4]?+e[4]:void 0,func:e[1]||we,line:+e[3],url:e[2]}}const Ns=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i,zs=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i;function $s(t){const e=Ns.exec(t);if(!e)return;const r=e[3]&&e[3].indexOf(" > eval")>-1,n=zs.exec(e[3]);return r&&n&&(e[3]=n[1],e[4]=n[2],e[5]=void 0),{args:e[2]?e[2].split(","):[],column:e[5]?+e[5]:void 0,func:e[1]||we,line:e[4]?+e[4]:void 0,url:e[3]}}function Tt(t,e){if(typeof t!="object"||!t||!(e in t))return;const r=t[e];return typeof r=="string"?r:void 0}function Gs(t,e,r,n){const s=[{url:e,column:n,line:r}],{name:i,message:o}=Hs(t);return{name:i,message:o,stack:s}}const Vs=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\s\S]*)$/;function Hs(t){let e,r;return{}.toString.call(t)==="[object String]"&&([,e,r]=Vs.exec(t)),{name:e,message:r}}function je(t){const r=new Error(t);r.name="HandlingStack";let n;return ve(()=>{const s=N(r);s.stack=s.stack.slice(2),n=te(s)}),n}function te(t){let e=br(t);return t.stack.forEach(r=>{const n=r.func==="?"?"<anonymous>":r.func,s=r.args&&r.args.length>0?`(${r.args.join(", ")})`:"",i=r.line?`:${r.line}`:"",o=r.line&&r.column?`:${r.column}`:"";e+=`
|
|
496
496
|
at ${n}${s} @ ${r.url}${i}${o}`}),e}function br(t){return`${t.name||"Error"}: ${t.message}`}function re(t,e,r,{computeHandlingStack:n}={}){let s=t[e];if(typeof s!="function")if(e in t&&e.startsWith("on"))s=W;else return{stop:W};let i=!1;const o=function(){if(i)return s.apply(this,arguments);const a=Array.from(arguments);let c;ve(r,null,[{target:this,parameters:a,onPostCall:l=>{c=l},handlingStack:n?je("instrumented method"):void 0}]);const d=s.apply(this,a);return c&&ve(c,null,[d]),d};return t[e]=o,{stop:()=>{i=!0,t[e]===o&&(t[e]=s)}}}const Ws=220*B,js="$",Ys=3;function z(t,e=Ws){const r=ce(Object.prototype),n=ce(Array.prototype),s=[],i=new WeakMap,o=St(t,js,void 0,s,i),a=JSON.stringify(o);let c=a?a.length:0;if(c>e){xt(e,"discarded",t);return}for(;s.length>0&&c<e;){const d=s.shift();let l=0;if(Array.isArray(d.source))for(let u=0;u<d.source.length;u++){const f=St(d.source[u],d.path,u,s,i);if(f!==void 0?c+=JSON.stringify(f).length:c+=4,c+=l,l=1,c>e){xt(e,"truncated",t);break}d.target[u]=f}else for(const u in d.source)if(Object.prototype.hasOwnProperty.call(d.source,u)){const f=St(d.source[u],d.path,u,s,i);if(f!==void 0&&(c+=JSON.stringify(f).length+l+u.length+Ys,l=1),c>e){xt(e,"truncated",t);break}d.target[u]=f}}return r(),n(),o}function St(t,e,r,n,s){const i=Ks(t);if(!i||typeof i!="object")return qs(i);const o=Et(i);if(o!=="[Object]"&&o!=="[Array]"&&o!=="[Error]")return o;const a=t;if(s.has(a))return`[Reference seen at ${s.get(a)}]`;const c=r!==void 0?`${e}.${r}`:e,d=Array.isArray(i)?[]:{};return s.set(a,c),n.push({source:i,target:d,path:c}),d}function qs(t){return typeof t=="bigint"?`[BigInt] ${t.toString()}`:typeof t=="function"?`[Function] ${t.name||"unknown"}`:typeof t=="symbol"?`[Symbol] ${t.description||t.toString()}`:t}function Et(t){try{if(t instanceof Event)return Xs(t);if(t instanceof RegExp)return`[RegExp] ${t.toString()}`;const r=Object.prototype.toString.call(t).match(/\[object (.*)\]/);if(r&&r[1])return`[${r[1]}]`}catch{}return"[Unserializable]"}function Xs(t){return{type:t.type,isTrusted:t.isTrusted,currentTarget:t.currentTarget?Et(t.currentTarget):null,target:t.target?Et(t.target):null}}function Ks(t){const e=t;if(e&&typeof e.toJSON=="function")try{return e.toJSON()}catch{}return t}function xt(t,e,r){D.warn(`The data provided has been ${e} as it is over the limit of ${t} characters:`,r)}const vr="No stack, consider using an instance of Error";function Tr({stackTrace:t,originalError:e,handlingStack:r,componentStack:n,startClocks:s,nonErrorPrefix:i,source:o,handling:a}){const c=Y(e),d=Js(t,c,i,e),l=Zs(c,t)?te(t):vr,u=c?xr(e,o):void 0,f=t?t.name:void 0,p=Sr(e),h=Er(e);return{startClocks:s,source:o,handling:a,handlingStack:r,componentStack:n,originalError:e,type:f,message:d,stack:l,causes:u,fingerprint:p,context:h}}function Js(t,e,r,n){return t!=null&&t.message&&(t!=null&&t.name)?t.message:e?"Empty message":`${r} ${ee(z(n))}`}function Zs(t,e){return e===void 0?!1:t?!0:e.stack.length>0&&(e.stack.length>1||e.stack[0].url!==void 0)}function Sr(t){return Y(t)&&"dd_fingerprint"in t?String(t.dd_fingerprint):void 0}function Er(t){if(t!==null&&typeof t=="object"&&"dd_context"in t)return t.dd_context}function Qs(t){var e;return(e=/@ (.+)/.exec(t))===null||e===void 0?void 0:e[1]}function Y(t){return t instanceof Error||Object.prototype.toString.call(t)==="[object Error]"}function xr(t,e){let r=t;const n=[];for(;Y(r==null?void 0:r.cause)&&n.length<10;){const s=N(r.cause);n.push({message:r.cause.message,source:e,type:s==null?void 0:s.name,stack:te(s)}),r=r.cause}return n.length?n:void 0}const P={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function ei(t){const e=(s,i)=>{const o=Tr({stackTrace:s,originalError:i,startClocks:V(),nonErrorPrefix:"Uncaught",source:P.SOURCE,handling:"unhandled"});t.notify(o)},{stop:r}=ti(e),{stop:n}=ri(e);return{stop:()=>{r(),n()}}}function ti(t){return re(window,"onerror",({parameters:[e,r,n,s,i]})=>{let o;Y(i)?o=N(i):o=Gs(e,r,n,s),t(o,i??e)})}function ri(t){return re(window,"onunhandledrejection",({parameters:[e]})=>{const r=e.reason||"Empty reason",n=N(r);t(n,r)})}function ni(t){const e={version:"6.5.0",onReady(r){r()},...t};return Object.defineProperty(e,"_setDebug",{get(){return An},enumerable:!1}),e}function si(t,e,r){const n=t[e];n&&!n.q&&n.version&&D.warn("SDK is loaded more than once. This is unsupported and might have unexpected behavior."),t[e]=r,n&&n.q&&n.q.forEach(s=>qt(s,"onReady callback threw an error:")())}function wr(t,e){e.silentMultipleInit||D.error(`${t} is already initialized.`)}function ne(t,e,r,n,s){return wt(t,e,[r],n,s)}function wt(t,e,r,n,{once:s,capture:i,passive:o}={}){const a=x(f=>{!f.isTrusted&&!f.__ddIsTrusted&&!t.allowUntrustedEvents||(s&&u(),n(f))}),c=o?{capture:i,passive:o}:i,d=window.EventTarget&&e instanceof EventTarget?window.EventTarget.prototype:e,l=oe(d,"addEventListener");r.forEach(f=>l.call(e,f,a,c));function u(){const f=oe(d,"removeEventListener");r.forEach(p=>f.call(e,p,a,c))}return{stop:u}}const Ye={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function ii(t,e){const r=[];e.includes(Ye.cspViolation)&&r.push(ai(t));const n=e.filter(s=>s!==Ye.cspViolation);return n.length&&r.push(oi(n)),rr(...r)}function oi(t){return new k(e=>{if(!window.ReportingObserver)return;const r=x((s,i)=>s.forEach(o=>e.notify(ci(o)))),n=new window.ReportingObserver(r,{types:t,buffered:!0});return n.observe(),()=>{n.disconnect()}})}function ai(t){return new k(e=>{const{stop:r}=ne(t,document,"securitypolicyviolation",n=>{e.notify(li(n))});return r})}function ci(t){const{type:e,body:r}=t;return Ar({type:r.id,message:`${e}: ${r.message}`,originalError:t,stack:Rr(r.id,r.message,r.sourceFile,r.lineNumber,r.columnNumber)})}function li(t){const e=`'${t.blockedURI}' blocked by '${t.effectiveDirective}' directive`;return Ar({type:t.effectiveDirective,message:`${Ye.cspViolation}: ${e}`,originalError:t,csp:{disposition:t.disposition},stack:Rr(t.effectiveDirective,t.originalPolicy?`${e} of the policy "${Un(t.originalPolicy,100,"...")}"`:"no policy",t.sourceFile,t.lineNumber,t.columnNumber)})}function Ar(t){return{startClocks:V(),source:P.REPORT,handling:"unhandled",...t}}function Rr(t,e,r,n,s){return r?te({name:t,message:e,stack:[{func:"?",url:r,line:n??void 0,column:s??void 0}]}):void 0}function Cr(t,e){const r=window.__ddBrowserSdkExtensionCallback;r&&r({type:t,payload:e})}function Dr(t){return t===null?"null":Array.isArray(t)?"array":typeof t}function qe(t,e,r=di()){if(e===void 0)return t;if(typeof e!="object"||e===null)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){const s=e.flags||[e.global?"g":"",e.ignoreCase?"i":"",e.multiline?"m":"",e.sticky?"y":"",e.unicode?"u":""].join("");return new RegExp(e.source,s)}if(r.hasAlreadyBeenSeen(e))return;if(Array.isArray(e)){const s=Array.isArray(t)?t:[];for(let i=0;i<e.length;++i)s[i]=qe(s[i],e[i],r);return s}const n=Dr(t)==="object"?t:{};for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(n[s]=qe(n[s],e[s],r));return n}function kr(t){return qe(void 0,t)}function ue(...t){let e;for(const r of t)r!=null&&(e=qe(e,r));return e}function di(){if(typeof WeakSet<"u"){const e=new WeakSet;return{hasAlreadyBeenSeen(r){const n=e.has(r);return n||e.add(r),n}}}const t=[];return{hasAlreadyBeenSeen(e){const r=t.indexOf(e)>=0;return r||t.push(e),r}}}function ui(){var t;const e=window.navigator;return{status:e.onLine?"connected":"not_connected",interfaces:e.connection&&e.connection.type?[e.connection.type]:void 0,effective_type:(t=e.connection)===null||t===void 0?void 0:t.effectiveType}}function hi(t){const e=new Set;return t.forEach(r=>e.add(r)),Array.from(e)}function Ur(t,e){const r=t.indexOf(e);r>=0&&t.splice(r,1)}const fi=500;function Fr(){const t=[];return{add:s=>{t.push(s)>fi&&t.splice(0,1)},remove:s=>{Ur(t,s)},drain:s=>{t.forEach(i=>i(s)),t.length=0}}}const se={log:"log",configuration:"configuration",usage:"usage"},pi=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],mi=[hs];let Lr=Fr(),he=t=>{Lr.add(()=>he(t))};function gi(t,e){let r;const n=new k,s=new Set,i=!mi.includes(e.site)&&Le(e.telemetrySampleRate),o={[se.log]:i,[se.configuration]:i&&Le(e.telemetryConfigurationSampleRate),[se.usage]:i&&Le(e.telemetryUsageSampleRate)},a=yi();he=d=>{const l=ee(d);if(o[d.type]&&s.size<e.maxTelemetryEventsPerPage&&!s.has(l)){const u=c(t,d,a);n.notify(u),Cr("telemetry",u),s.add(l)}},wn(Or);function c(d,l,u){return ue({type:"telemetry",date:G(),service:d,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:ue(l,{runtime_env:u,connectivity:ui(),sdk_setup:"npm"}),experimental_features:Array.from(Us())},r!==void 0?r():{})}return{setContextProvider:d=>{r=d},observable:n,enabled:i}}function yi(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function _i(){Lr.drain()}function bi(t){return t.site===ds}function Pr(t,e){lt(C.debug,t,e),he({type:se.log,message:t,status:"debug",...e})}function Or(t,e){he({type:se.log,status:"error",...Si(t),...e})}function vi(t){he({type:se.configuration,configuration:t})}function Ti(t){he({type:se.usage,usage:t})}function Si(t){if(Y(t)){const e=N(t);return{error:{kind:e.name,stack:te(Ei(e))},message:e.message}}return{error:{stack:vr},message:`Uncaught ${ee(t)}`}}function Ei(t){return t.stack=t.stack.filter(e=>!e.url||pi.some(r=>e.url.startsWith(r))),t}const Ae=1/0,xi=K;let Re=null;const Xe=new Set;function wi(){Xe.forEach(t=>t())}function Ai({expireDelay:t,maxEntries:e}){let r=[];const n=[];Re||(Re=dt(()=>wi(),xi));const s=()=>{const p=Pe()-t;for(;r.length>0&&r[r.length-1].endTime<p;){const h=r.pop();h&&n.push(h.startTime)}};Xe.add(s);function i(p,h){const m={value:p,startTime:h,endTime:Ae,remove:()=>{Ur(r,m)},close:g=>{m.endTime=g}};return e&&r.length>=e&&r.pop(),r.unshift(m),m}function o(p=Ae,h={returnInactive:!1}){for(const m of r)if(m.startTime<=p){if(h.returnInactive||p<=m.endTime)return m.value;break}}function a(p){const h=r[0];h&&h.endTime===Ae&&h.close(p)}function c(p=Ae,h=0){const m=Tn(p,h);return r.filter(g=>g.startTime<=m&&p<=g.endTime).map(g=>g.value)}function d(){return r.map(({startTime:p,endTime:h,value:m})=>({startTime:p,endTime:h===Ae?"Infinity":h,value:m}))}function l(){return n}function u(){r=[]}function f(){Xe.delete(s),Xe.size===0&&Re&&(tr(Re),Re=null)}return{add:i,find:o,closeActive:a,findAll:c,reset:u,stop:f,getAllEntries:d,getDeletedEntries:l}}const Ri=K,Ci=pt;function Di(t,e,r,n){const s=new k,i=new k,o=os(t.sessionStoreStrategyType,t,e,r),a=Ai({expireDelay:Ci});o.renewObservable.subscribe(()=>{a.add(c(),Pe()),s.notify()}),o.expireObservable.subscribe(()=>{i.notify(),a.closeActive(Pe())}),o.expandOrRenewSession(),a.add(c(),bn().relative),n.observable.subscribe(()=>{n.isGranted()?o.expandOrRenewSession():o.expire()}),ki(t,()=>{n.isGranted()&&o.expandOrRenewSession()}),Ui(t,()=>o.expandSession()),Fi(t,()=>o.restartSession());function c(){return{id:o.getSession().id,trackingType:o.getSession()[e],isReplayForced:!!o.getSession().forcedReplay,anonymousId:o.getSession().anonymousId}}return{findSession:(d,l)=>a.find(d,l),renewObservable:s,expireObservable:i,sessionStateUpdateObservable:o.sessionStateUpdateObservable,expire:o.expire,updateSessionState:o.updateSessionState}}function ki(t,e){wt(t,window,["click","touchstart","keydown","scroll"],e,{capture:!0,passive:!0})}function Ui(t,e){const r=()=>{document.visibilityState==="visible"&&e()};ne(t,document,"visibilitychange",r),dt(r,Ri)}function Fi(t,e){ne(t,window,"resume",e,{capture:!0})}function Ir(t){return t>=500}function Li(t){try{return t.clone()}catch{return}}const Pi=80*B,Oi=32,Mr=3*Jt,Ii=K,Br=ye;function Nr(t,e,r,n,s){e.transportStatus===0&&e.queuedPayloads.size()===0&&e.bandwidthMonitor.canHandle(t)?$r(t,e,r,{onSuccess:()=>Gr(0,e,r,n,s),onFailure:()=>{e.queuedPayloads.enqueue(t),zr(e,r,n,s)}}):e.queuedPayloads.enqueue(t)}function zr(t,e,r,n){t.transportStatus===2&&Te(()=>{const s=t.queuedPayloads.first();$r(s,t,e,{onSuccess:()=>{t.queuedPayloads.dequeue(),t.currentBackoffTime=Br,Gr(1,t,e,r,n)},onFailure:()=>{t.currentBackoffTime=Math.min(Ii,t.currentBackoffTime*2),zr(t,e,r,n)}})},t.currentBackoffTime)}function $r(t,e,r,{onSuccess:n,onFailure:s}){e.bandwidthMonitor.add(t),r(t,i=>{e.bandwidthMonitor.remove(t),Mi(i)?(e.transportStatus=e.bandwidthMonitor.ongoingRequestCount>0?1:2,t.retry={count:t.retry?t.retry.count+1:1,lastFailureStatus:i.status},s()):(e.transportStatus=0,n())})}function Gr(t,e,r,n,s){t===0&&e.queuedPayloads.isFull()&&!e.queueFullReported&&(s({message:`Reached max ${n} events size queued for upload: ${Mr/Jt}MiB`,source:P.AGENT,startClocks:V()}),e.queueFullReported=!0);const i=e.queuedPayloads;for(e.queuedPayloads=Vr();i.size()>0;)Nr(i.dequeue(),e,r,n,s)}function Mi(t){return t.type!=="opaque"&&(t.status===0&&!navigator.onLine||t.status===408||t.status===429||Ir(t.status))}function Bi(){return{transportStatus:0,currentBackoffTime:Br,bandwidthMonitor:Ni(),queuedPayloads:Vr(),queueFullReported:!1}}function Vr(){const t=[];return{bytesCount:0,enqueue(e){this.isFull()||(t.push(e),this.bytesCount+=e.bytesCount)},first(){return t[0]},dequeue(){const e=t.shift();return e&&(this.bytesCount-=e.bytesCount),e},size(){return t.length},isFull(){return this.bytesCount>=Mr}}}function Ni(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(t){return this.ongoingRequestCount===0||this.ongoingByteCount+t.bytesCount<=Pi&&this.ongoingRequestCount<Oi},add(t){this.ongoingRequestCount+=1,this.ongoingByteCount+=t.bytesCount},remove(t){this.ongoingRequestCount-=1,this.ongoingByteCount-=t.bytesCount}}}function zi(t,e,r){const n=Bi(),s=(i,o)=>Vi(t,e,i,o);return{send:i=>{Nr(i,n,s,t.trackType,r)},sendOnExit:i=>{$i(t,e,i)}}}function $i(t,e,r){if(!!navigator.sendBeacon&&r.bytesCount<e)try{const i=t.build("beacon",r);if(navigator.sendBeacon(i,r.data))return}catch(i){Gi(i)}const s=t.build("xhr",r);At(s,r.data)}let Hr=!1;function Gi(t){Hr||(Hr=!0,Or(t))}function Vi(t,e,r,n){if(Hi()&&r.bytesCount<e){const i=t.build("fetch",r);fetch(i,{method:"POST",body:r.data,keepalive:!0,mode:"cors"}).then(x(o=>n==null?void 0:n({status:o.status,type:o.type})),x(()=>{const o=t.build("xhr",r);At(o,r.data,n)}))}else{const i=t.build("xhr",r);At(i,r.data,n)}}function Hi(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function At(t,e,r){const n=new XMLHttpRequest;n.open("POST",t,!0),e instanceof Blob&&n.setRequestHeader("Content-Type",e.type),ne({allowUntrustedEvents:!0},n,"loadend",()=>{r==null||r({status:n.status})},{once:!0}),n.send(e)}function Rt(){const t=Wi();if(t)return{getCapabilities(){var e;return JSON.parse(((e=t.getCapabilities)===null||e===void 0?void 0:e.call(t))||"[]")},getPrivacyLevel(){var e;return(e=t.getPrivacyLevel)===null||e===void 0?void 0:e.call(t)},getAllowedWebViewHosts(){return JSON.parse(t.getAllowedWebViewHosts())},send(e,r,n){const s=n?{id:n}:void 0;t.send(JSON.stringify({eventType:e,event:r,view:s}))}}}function Ke(t){var e;t===void 0&&(t=(e=H().location)===null||e===void 0?void 0:e.hostname);const r=Rt();return!!r&&r.getAllowedWebViewHosts().some(n=>t===n||t.endsWith(`.${n}`))}function Wi(){return H().DatadogEventBridge}const Je={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function ji(t){return new k(e=>{const{stop:r}=wt(t,window,["visibilitychange","freeze"],s=>{s.type==="visibilitychange"&&document.visibilityState==="hidden"?e.notify({reason:Je.HIDDEN}):s.type==="freeze"&&e.notify({reason:Je.FROZEN})},{capture:!0}),n=ne(t,window,"beforeunload",()=>{e.notify({reason:Je.UNLOADING})}).stop;return()=>{r(),n()}})}function Yi(t){return Be(Je).includes(t)}function qi({encoder:t,request:e,flushController:r,messageBytesLimit:n}){let s={};const i=r.flushObservable.subscribe(u=>l(u));function o(u,f,p){r.notifyBeforeAddMessage(f),p!==void 0?(s[p]=u,r.notifyAfterAddMessage()):t.write(t.isEmpty?u:`
|
|
497
497
|
${u}`,h=>{r.notifyAfterAddMessage(h-f)})}function a(u){return u!==void 0&&s[u]!==void 0}function c(u){const f=s[u];delete s[u];const p=t.estimateEncodedBytesCount(f);r.notifyAfterRemoveMessage(p)}function d(u,f){const p=ee(u),h=t.estimateEncodedBytesCount(p);if(h>=n){D.warn(`Discarded a message whose size was bigger than the maximum allowed size ${n}KB. ${Fe} ${Yt}/#technical-limitations`);return}a(f)&&c(f),o(p,h,f)}function l(u){const f=Be(s).join(`
|
|
498
498
|
`);s={};const p=Yi(u.reason),h=p?e.sendOnExit:e.send;if(p&&t.isAsync){const m=t.finishSync();m.outputBytesCount&&h(Wr(m));const g=[m.pendingData,f].filter(Boolean).join(`
|
|
499
499
|
`);g&&h({data:g,bytesCount:ct(g)})}else f&&t.write(t.isEmpty?f:`
|
|
500
|
-
${f}`),t.finish(m=>{h(Wr(m))})}return{flushController:r,add:d,upsert:d,stop:i.unsubscribe}}function Wr(t){let e;return typeof t.output=="string"?e=t.output:e=new Blob([t.output],{type:"text/plain"}),{data:e,bytesCount:t.outputBytesCount,encoding:t.encoding}}function Xi({messagesLimit:t,bytesLimit:e,durationLimit:r,pageExitObservable:n,sessionExpireObservable:s}){const i=n.subscribe(h=>l(h.reason)),o=s.subscribe(()=>l("session_expire")),a=new k(()=>()=>{i.unsubscribe(),o.unsubscribe()});let c=0,d=0;function l(h){if(d===0)return;const m=d,g=c;d=0,c=0,p(),a.notify({reason:h,messagesCount:m,bytesCount:g})}let u;function f(){u===void 0&&(u=Te(()=>{l("duration_limit")},r))}function p(){er(u),u=void 0}return{flushObservable:a,get messagesCount(){return d},notifyBeforeAddMessage(h){c+h>=e&&l("bytes_limit"),d+=1,c+=h,f()},notifyAfterAddMessage(h=0){c+=h,d>=t?l("messages_limit"):c>=e&&l("bytes_limit")},notifyAfterRemoveMessage(h){c-=h,d-=1,d===0&&p()}}}function jr(t,e,r,n,s,i,o=qi){const a=d(t,e),c=r&&d(t,r);function d(l,{endpoint:u,encoder:f}){return o({encoder:f,request:zi(u,l.batchBytesLimit,n),flushController:Xi({messagesLimit:l.batchMessagesLimit,bytesLimit:l.batchBytesLimit,durationLimit:l.flushTimeout,pageExitObservable:s,sessionExpireObservable:i}),messageBytesLimit:l.messageBytesLimit})}return{flushObservable:a.flushController.flushObservable,add(l,u=!0){a.add(l),c&&u&&c.add(r.transformMessage?r.transformMessage(l):l)},upsert:(l,u)=>{a.upsert(l,u),c&&c.upsert(r.transformMessage?r.transformMessage(l):l,u)},stop:()=>{a.stop(),c&&c.stop()}}}function Ze(){let t="",e=0;return{isAsync:!1,get isEmpty(){return!t},write(r,n){const s=ct(r);e+=s,t+=r,n&&n(s)},finish(r){r(this.finishSync())},finishSync(){const r={output:t,outputBytesCount:e,rawBytesCount:e,pendingData:""};return t="",e=0,r},estimateEncodedBytesCount(r){return r.length}}}class Ki{constructor(){this.callbacks={}}notify(e,r){const n=this.callbacks[e];n&&n.forEach(s=>s(r))}subscribe(e,r){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(r),{unsubscribe:()=>{this.callbacks[e]=this.callbacks[e].filter(n=>r!==n)}}}}function Ji(t,e,r){let n=0,s=!1;return{isLimitReached(){if(n===0&&Te(()=>{n=0},K),n+=1,n<=e||s)return s=!1,!1;if(n===e+1){s=!0;try{r({message:`Reached max number of ${t}s by minute: ${e}`,source:P.AGENT,startClocks:V()})}finally{s=!1}}return!0}}}let Ct;const Dt=new WeakMap;function Zi(t){return Ct||(Ct=Qi(t)),Ct}function Qi(t){return new k(e=>{const{stop:r}=re(XMLHttpRequest.prototype,"open",eo),{stop:n}=re(XMLHttpRequest.prototype,"send",i=>{to(i,t,e)},{computeHandlingStack:!0}),{stop:s}=re(XMLHttpRequest.prototype,"abort",ro);return()=>{r(),n(),s()}})}function eo({target:t,parameters:[e,r]}){Dt.set(t,{state:"open",method:String(e).toUpperCase(),url:_t(String(r))})}function to({target:t,handlingStack:e},r,n){const s=Dt.get(t);if(!s)return;const i=s;i.state="start",i.startClocks=V(),i.isAborted=!1,i.xhr=t,i.handlingStack=e;let o=!1;const{stop:a}=re(t,"onreadystatechange",()=>{t.readyState===XMLHttpRequest.DONE&&c()}),c=()=>{if(d(),a(),o)return;o=!0;const l=s;l.state="complete",l.duration=vn(i.startClocks.timeStamp,G()),l.status=t.status,n.notify(xn(l))},{stop:d}=ne(r,t,"loadend",c);n.notify(i)}function ro({target:t}){const e=Dt.get(t);e&&(e.isAborted=!0)}let kt;function Yr(){return kt||(kt=no()),kt}function no(){return new k(t=>{if(!window.fetch)return;const{stop:e}=re(window,"fetch",r=>so(r,t),{computeHandlingStack:!0});return e})}function so({parameters:t,onPostCall:e,handlingStack:r},n){const[s,i]=t;let o=i&&i.method;o===void 0&&s instanceof Request&&(o=s.method);const a=o!==void 0?String(o).toUpperCase():"GET",c=s instanceof Request?s.url:_t(String(s)),d=V(),l={state:"start",init:i,input:s,method:a,startClocks:d,url:c,handlingStack:r};n.notify(l),t[0]=l.input,t[1]=l.init,e(u=>io(n,u,l))}function io(t,e,r){const n=r;function s(i){n.state="resolve",Object.assign(n,i),t.notify(n)}e.then(x(i=>{s({response:i,responseType:i.type,status:i.status,isAborted:!1})}),x(i=>{var o,a;s({status:0,isAborted:((a=(o=n.init)===null||o===void 0?void 0:o.signal)===null||a===void 0?void 0:a.aborted)||i instanceof DOMException&&i.code===DOMException.ABORT_ERR,error:i})}))}let Ut={};function oo(t){const e=t.map(r=>(Ut[r]||(Ut[r]=ao(r)),Ut[r]));return rr(...e)}function ao(t){return new k(e=>{const r=M[t];return M[t]=(...n)=>{r.apply(console,n);const s=je("console error");ve(()=>{e.notify(co(n,t,s))})},()=>{M[t]=r}})}function co(t,e,r){const n=t.map(i=>lo(i)).join(" ");let s;if(e===C.error){const i=t.find(Y);s={stack:i?te(N(i)):void 0,fingerprint:Sr(i),causes:i?xr(i,"console"):void 0,startClocks:V(),message:n,source:P.CONSOLE,handling:"handled",handlingStack:r,context:Er(i)}}return{api:e,message:n,error:s,handlingStack:r}}function lo(t){return typeof t=="string"?z(t):Y(t)?br(N(t)):ee(z(t),void 0,2)}function uo(t){const e=Dr(t)==="object";return e||D.error("Unsupported context:",t),e}function Ft(t,e,r){const n={...t};for(const[s,{required:i,type:o}]of Object.entries(e))o==="string"&&s in n&&(n[s]=String(n[s])),i&&!(s in t)&&D.warn(`The property ${s} of ${r} is required; context will not be sent to the intake.`);return n}function Qe(t="",{customerDataTracker:e,propertiesConfig:r={}}={}){let n={};const s=new k,i={getContext:()=>kr(n),setContext:o=>{uo(o)?(n=z(Ft(o,r,t)),e==null||e.updateCustomerData(n)):i.clearContext(),s.notify()},setContextProperty:(o,a)=>{n=z(Ft({...n,[o]:a},r,t)),e==null||e.updateCustomerData(n),s.notify()},removeContextProperty:o=>{delete n[o],e==null||e.updateCustomerData(n),Ft(n,r,t),s.notify()},clearContext:()=>{n={},e==null||e.resetCustomerData(),s.notify()},changeObservable:s};return i}const ho="_dd_c",fo=[];function Lt(t,e,r,n){const s=po(r,n);fo.push(ne(t,window,"storage",({key:d})=>{s===d&&o()})),e.changeObservable.subscribe(a);const i=ue(c(),e.getContext());be(i)||e.setContext(i);function o(){e.setContext(c())}function a(){localStorage.setItem(s,JSON.stringify(e.getContext()))}function c(){const d=localStorage.getItem(s);return d?JSON.parse(d):{}}}function po(t,e){return`${ho}_${t}_${e}`}const mo=3*B,go=16*B,yo=200;function _o(t=2){const e=new Map;let r=!1;function n(s=0){if(r||t===0)return;const i=t===2?mo:go;let o=s;e.forEach(a=>{o+=a.getBytesCount()}),o>i&&(bo(i),r=!0)}return{createDetachedTracker:()=>{const s=qr(()=>n(s.getBytesCount()));return s},getOrCreateTracker:s=>(e.has(s)||e.set(s,qr(n)),e.get(s)),setCompressionStatus:s=>{t===0&&(t=s,n())},getCompressionStatus:()=>t,stop:()=>{e.forEach(s=>s.stop()),e.clear()}}}function qr(t){let e=0;const{throttled:r,cancel:n}=nr(i=>{e=ct(ee(i)),t()},yo),s=()=>{n(),e=0};return{updateCustomerData:i=>{be(i)?s():r(i)},resetCustomerData:s,getBytesCount:()=>e,stop:()=>{n()}}}function bo(t){D.warn(`Customer data exceeds the recommended ${t/B}KiB threshold. ${Fe} ${Yt}/#customer-data-exceeds-the-recommended-threshold-warning`)}function vo(t,e,r){const n=t.getReader(),s=[];let i=0;o();function o(){n.read().then(x(c=>{if(c.done){a();return}s.push(c.value),i+=c.value.length,i>r.bytesLimit?a():o()}),x(c=>e(c)))}function a(){n.cancel().catch(W);let c,d;{let l;if(s.length===1)l=s[0];else{l=new Uint8Array(i);let u=0;s.forEach(f=>{l.set(f,u),u+=f.length})}c=l.slice(0,r.bytesLimit),d=l.length>r.bytesLimit}e(void 0,c,d)}}const To="datadog-synthetics-public-id",So="datadog-synthetics-result-id",Eo="datadog-synthetics-injects-rum";function Xr(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||J(Eo))}function xo(){const t=window._DATADOG_SYNTHETICS_PUBLIC_ID||J(To);return typeof t=="string"?t:void 0}function wo(){const t=window._DATADOG_SYNTHETICS_RESULT_ID||J(So);return typeof t=="string"?t:void 0}function et(t,e,r){const n=r.getHandler(),s=Array.isArray(n)?n:[n];return Kr[t]>=Kr[r.getLevel()]&&s.includes(e)}const T={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},Kr={[T.ok]:0,[T.debug]:1,[T.info]:2,[T.notice]:4,[T.warn]:5,[T.error]:6,[T.critical]:7,[T.alert]:8,[T.emerg]:9};function tt(t,{includeMessage:e=!1}={}){return{stack:t.stack,kind:t.type,message:e?t.message:void 0,causes:t.causes,fingerprint:t.fingerprint,handling:t.handling}}var Ao=function(t,e,r,n){var s=arguments.length,i=s<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,r,i):o(e,r))||i);return s>3&&i&&Object.defineProperty(e,r,i),i};const Ce={console:"console",http:"http",silent:"silent"},Ro=Object.keys(T);let O=class{constructor(e,r,n,s=Ce.http,i=T.debug,o={}){this.handleLogStrategy=e,this.handlerType=s,this.level=i,this.contextManager=Qe("logger",{customerDataTracker:r}),this.contextManager.setContext(o),n&&this.contextManager.setContextProperty("logger",{name:n})}logImplementation(e,r,n=T.info,s,i){const o=z(r);let a;if(s!=null){const c=Tr({stackTrace:Y(s)?N(s):void 0,originalError:s,nonErrorPrefix:"Provided",source:P.LOGGER,handling:"handled",startClocks:V()});a=ue({error:tt(c,{includeMessage:!0})},o)}else a=o;this.handleLogStrategy({message:z(e),context:a,status:n},this,i)}log(e,r,n=T.info,s){let i;et(n,Ce.http,this)&&(i=je("log")),this.logImplementation(e,r,n,s,i)}setContext(e){this.contextManager.setContext(e)}getContext(){return this.contextManager.getContext()}setContextProperty(e,r){this.contextManager.setContextProperty(e,r)}removeContextProperty(e){this.contextManager.removeContextProperty(e)}clearContext(){this.contextManager.clearContext()}setHandler(e){this.handlerType=e}getHandler(){return this.handlerType}setLevel(e){this.level=e}getLevel(){return this.level}};Ao([Rn],O.prototype,"logImplementation",null),O.prototype.ok=$(T.ok),O.prototype.debug=$(T.debug),O.prototype.info=$(T.info),O.prototype.notice=$(T.notice),O.prototype.warn=$(T.warn),O.prototype.error=$(T.error),O.prototype.critical=$(T.critical),O.prototype.alert=$(T.alert),O.prototype.emerg=$(T.emerg);function $(t){return function(e,r,n){let s;et(t,Ce.http,this)&&(s=je("log")),this.logImplementation(e,r,t,n,s)}}function Co(t,e,r){return{view:{referrer:document.referrer,url:window.location.href},context:t.getContext(),user:e.getContext(),account:r.getContext()}}const Do=32*B;function ko(t){t.usePciIntake===!0&&t.site&&t.site!=="datadoghq.com"&&D.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");const e=Rs(t),r=Jr(t.forwardConsoleLogs,Be(C),"Forward Console Logs"),n=Jr(t.forwardReports,Be(Ye),"Forward Reports");if(!(!e||!r||!n))return t.forwardErrorsToLogs&&!r.includes(C.error)&&r.push(C.error),{forwardErrorsToLogs:t.forwardErrorsToLogs!==!1,forwardConsoleLogs:r,forwardReports:n,requestErrorResponseLengthLimit:Do,...e}}function Jr(t,e,r){if(t===void 0)return[];if(!(t==="all"||Array.isArray(t)&&t.every(n=>e.includes(n)))){D.error(`${r} should be "all" or an array with allowed values "${e.join('", "')}"`);return}return t==="all"?e:hi(t)}function Uo(t){const e=Cs(t);return{forward_errors_to_logs:t.forwardErrorsToLogs,forward_console_logs:t.forwardConsoleLogs,forward_reports:t.forwardReports,use_pci_intake:t.usePciIntake,...e}}function Fo(t,e,r){const n=Fr();let s,i;const o=e.observable.subscribe(a);function a(){if(!i||!s||!e.isGranted())return;o.unsubscribe();const c=r(s,i);n.drain(c)}return{init(c){if(!c){D.error("Missing configuration");return}if(Ds(c.enableExperimentalFeatures),Ke()&&(c=Lo(c)),s=c,i){wr("DD_LOGS",c);return}const d=ko(c);d&&(i=d,Yr().subscribe(W),e.tryToInit(d.trackingConsent),a())},get initConfiguration(){return s},getInternalContext:W,handleLog(c,d,l,u=t(),f=G()){n.add(p=>p.handleLog(c,d,l,u,f))}}}function Lo(t){return{...t,clientToken:"empty"}}const Pt="logs";function Po(t){const e=_o(),r=Qe("global context",{customerDataTracker:e.getOrCreateTracker(2)}),n=Qe("user",{customerDataTracker:e.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),s=Qe("account",{customerDataTracker:e.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),i=as();function o(){return Co(r,n,s)}let a=Fo(o,i,(l,u)=>{l.storeContextsAcrossPages&&(Lt(u,r,Pt,2),Lt(u,n,Pt,1),Lt(u,s,Pt,4));const f=t(l,u,o,i);return a=Oo(l,f),f});const c={},d=new O((...l)=>a.handleLog(...l),e.createDetachedTracker());return ni({logger:d,init:x(l=>a.init(l)),setTrackingConsent:x(l=>{i.update(l),Ti({feature:"set-tracking-consent",tracking_consent:l})}),getGlobalContext:x(()=>r.getContext()),setGlobalContext:x(l=>r.setContext(l)),setGlobalContextProperty:x((l,u)=>r.setContextProperty(l,u)),removeGlobalContextProperty:x(l=>r.removeContextProperty(l)),clearGlobalContext:x(()=>r.clearContext()),createLogger:x((l,u={})=>(c[l]=new O((...f)=>a.handleLog(...f),e.createDetachedTracker(),z(l),u.handler,u.level,z(u.context)),c[l])),getLogger:x(l=>c[l]),getInitConfiguration:x(()=>kr(a.initConfiguration)),getInternalContext:x(l=>a.getInternalContext(l)),setUser:x(n.setContext),getUser:x(n.getContext),setUserProperty:x(n.setContextProperty),removeUserProperty:x(n.removeContextProperty),clearUser:x(n.clearContext),setAccount:x(s.setContext),getAccount:x(s.getContext),setAccountProperty:x(s.setContextProperty),removeAccountProperty:x(s.removeContextProperty),clearAccount:x(s.clearContext)})}function Oo(t,e){return{init:r=>{wr("DD_LOGS",r)},initConfiguration:t,...e}}const Io="logs";function Mo(t,e){const r=Di(t,Io,n=>No(t,n),e);return{findTrackedSession:(n,s={returnInactive:!1})=>{const i=r.findSession(n,s);return i&&i.trackingType==="1"?{id:i.id,anonymousId:i.anonymousId}:void 0},expireObservable:r.expireObservable}}function Bo(t){const r=Zr(t)==="1"?{}:void 0;return{findTrackedSession:()=>r,expireObservable:new k}}function Zr(t){return Le(t.sessionSampleRate)?"1":"0"}function No(t,e){const r=zo(e)?e:Zr(t);return{trackingType:r,isTracked:r==="1"}}function zo(t){return t==="0"||t==="1"}let Qr=!1;function rt(t){const e=window;if(Xr()){const n=r(e.DD_RUM_SYNTHETICS);return!n&&!Qr&&(Qr=!0,Pr("Logs sent before RUM is injected by the synthetics worker",{testId:xo(),resultId:wo()})),n}return r(e.DD_RUM);function r(n){if(n&&n.getInternalContext)return n.getInternalContext(t)}}function $o(t,e,r,n,s){const i=Ro.concat(["custom"]),o={};i.forEach(a=>{o[a]=Ji(a,e.eventRateLimiterThreshold,s)}),r.subscribe(0,({rawLogsEvent:a,messageContext:c=void 0,savedCommonContext:d=void 0,domainContext:l})=>{var u,f;const p=Sn(a.date),h=t.findTrackedSession(p);if(!t.findTrackedSession(p,{returnInactive:!0}))return;const g=d||n();let S;!be(g.account)&&g.account.id&&(S=g.account),h&&h.anonymousId&&!g.user.anonymous_id&&(g.user.anonymous_id=h.anonymousId);const b=ue({service:e.service,session_id:h?h.id:void 0,session:h?{id:h.id}:void 0,usr:be(g.user)?void 0:g.user,account:S,view:g.view},g.context,rt(p),a,c);((u=e.beforeSend)===null||u===void 0?void 0:u.call(e,b,l))===!1||b.origin!==P.AGENT&&((f=o[b.status])!==null&&f!==void 0?f:o.custom).isLimitReached()||r.notify(1,b)})}const Go={[C.log]:T.info,[C.debug]:T.debug,[C.info]:T.info,[C.warn]:T.warn,[C.error]:T.error};function Vo(t,e){const r=oo(t.forwardConsoleLogs).subscribe(n=>{var s;const i={rawLogsEvent:{date:G(),message:n.message,origin:P.CONSOLE,error:n.error&&tt(n.error),status:Go[n.api]},messageContext:(s=n.error)===null||s===void 0?void 0:s.context,domainContext:{handlingStack:n.handlingStack}};e.notify(0,i)});return{stop:()=>{r.unsubscribe()}}}function Ho(t,e){const r=ii(t,t.forwardReports).subscribe(n=>{let s=n.message,i;const o=n.originalError.type==="deprecation"?T.warn:T.error;o===T.error?i=tt(n):n.stack&&(s+=` Found in ${Qs(n.stack)}`),e.notify(0,{rawLogsEvent:{date:G(),message:s,origin:P.REPORT,error:i,status:o}})});return{stop:()=>{r.unsubscribe()}}}function Wo(t,e){if(!t.forwardErrorsToLogs)return{stop:W};const r=Zi(t).subscribe(i=>{i.state==="complete"&&s("xhr",i)}),n=Yr().subscribe(i=>{i.state==="resolve"&&s("fetch",i)});function s(i,o){!ws(o.url)&&(Xo(o)||Ir(o.status))&&("xhr"in o?jo(o.xhr,t,a):o.response?qo(o.response,t,a):o.error&&Yo(o.error,t,a));function a(c){const d={isAborted:o.isAborted,handlingStack:o.handlingStack};e.notify(0,{rawLogsEvent:{message:`${Ko(i)} error ${o.method} ${o.url}`,date:o.startClocks.timeStamp,error:{stack:c||"Failed to load",handling:void 0},http:{method:o.method,status_code:o.status,url:o.url},status:T.error,origin:P.NETWORK},domainContext:d})}}return{stop:()=>{r.unsubscribe(),n.unsubscribe()}}}function jo(t,e,r){typeof t.response=="string"?r(Ot(t.response,e)):r(t.response)}function Yo(t,e,r){r(Ot(te(N(t)),e))}function qo(t,e,r){const n=Li(t);!n||!n.body?r():window.TextDecoder?Jo(n.body,e.requestErrorResponseLengthLimit,(s,i)=>{r(s?`Unable to retrieve response: ${s}`:i)}):n.text().then(x(s=>r(Ot(s,e))),x(s=>r(`Unable to retrieve response: ${s}`)))}function Xo(t){return t.status===0&&t.responseType!=="opaque"}function Ot(t,e){return t.length>e.requestErrorResponseLengthLimit?`${t.substring(0,e.requestErrorResponseLengthLimit)}...`:t}function Ko(t){return t==="xhr"?"XHR":"Fetch"}function Jo(t,e,r){vo(t,(n,s,i)=>{if(n)r(n);else{let o=new TextDecoder().decode(s);i&&(o+="..."),r(void 0,o)}},{bytesLimit:e,collectStreamBody:!0})}function Zo(t,e){if(!t.forwardErrorsToLogs)return{stop:W};const r=new k,{stop:n}=ei(r),s=r.subscribe(i=>{e.notify(0,{rawLogsEvent:{message:i.message,date:i.startClocks.timeStamp,error:tt(i),origin:P.SOURCE,status:T.error},messageContext:i.context})});return{stop:()=>{n(),s.unsubscribe()}}}const Qo=Ki;function ea(t){function e(r,n,s,i,o){const a=ue(n.getContext(),r.context);if(et(r.status,Ce.console,n)&&ra(r,a),et(r.status,Ce.http,n)){const c={rawLogsEvent:{date:o||G(),message:r.message,status:r.status,origin:P.LOGGER},messageContext:a,savedCommonContext:i};s&&(c.domainContext={handlingStack:s}),t.notify(0,c)}}return{handleLog:e}}const ta={[T.ok]:C.debug,[T.debug]:C.debug,[T.info]:C.info,[T.notice]:C.info,[T.warn]:C.warn,[T.error]:C.error,[T.critical]:C.error,[T.alert]:C.error,[T.emerg]:C.error};function ra({status:t,message:e},r){X[ta[t]].call(M,e,r)}function na(t,e,r,n,s){const i=jr(t,{endpoint:t.logsEndpointBuilder,encoder:Ze()},t.replica&&{endpoint:t.replica.logsEndpointBuilder,encoder:Ze()},r,n,s.expireObservable);return e.subscribe(1,o=>{i.add(o)}),i}function sa(t){const e=Rt();t.subscribe(1,r=>{e.send("log",r)})}function ia(t){return{get:e=>{const r=t.findTrackedSession(e);if(r)return{session_id:r.id}}}}function oa(t){return e=>{t.notify(0,{rawLogsEvent:{message:e.message,date:e.startClocks.timeStamp,origin:P.AGENT,status:T.error}}),Pr("Error reported to customer",{"error.message":e.message})}}function aa(t,e,r,n,s){const i=gi("browser-logs-sdk",e);i.setContextProvider(()=>{var a,c,d,l,u,f;return{application:{id:(a=rt())===null||a===void 0?void 0:a.application_id},session:{id:(c=s.findTrackedSession())===null||c===void 0?void 0:c.id},view:{id:(l=(d=rt())===null||d===void 0?void 0:d.view)===null||l===void 0?void 0:l.id},action:{id:(f=(u=rt())===null||u===void 0?void 0:u.user_action)===null||f===void 0?void 0:f.id}}});const o=[];if(Ke()){const a=Rt(),c=i.observable.subscribe(d=>a.send("internal_telemetry",d));o.push(()=>c.unsubscribe())}else{const a=jr(e,{endpoint:e.rumEndpointBuilder,encoder:Ze()},e.replica&&{endpoint:e.replica.rumEndpointBuilder,encoder:Ze()},r,n,s.expireObservable);o.push(()=>a.stop());const c=i.observable.subscribe(d=>a.add(d,bi(e)));o.push(()=>c.unsubscribe())}return _i(),vi(Uo(t)),{telemetry:i,stop:()=>{o.forEach(a=>a())}}}function ca(t,e,r,n){const s=new Qo,i=[];s.subscribe(1,f=>Cr("logs",f));const o=oa(s),a=ji(e),c=e.sessionStoreStrategyType&&!Ke()&&!Xr()?Mo(e,n):Bo(e),{stop:d}=aa(t,e,o,a,c);i.push(()=>d()),Wo(e,s),Zo(e,s),Vo(e,s),Ho(e,s);const{handleLog:l}=ea(s);if($o(c,e,s,r,o),Ke())sa(s);else{const{stop:f}=na(e,s,o,a,c);i.push(()=>f())}const u=ia(c);return{handleLog:l,getInternalContext:u.get,stop:()=>{i.forEach(f=>f())}}}const fe=Po(ca);si(H(),"DD_LOGS",fe);const y=class y{constructor(e){this.listenerMap=new Map,y.options=e,this.isLoggingOn=e.LOG_TO_DATADOG,this.eventTarget=new EventTarget,this.isLoggingOn&&fe.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!1,sessionSampleRate:100});const r="bb_logger_mac_uuid";let n=localStorage.getItem(r);n||(n=crypto.randomUUID(),localStorage.setItem(r,n)),y.tracking.mac=n,y.tracking.dev=`${e.platform}_${e.browserName}`,y.beatHandle||(y.options&&_(y.options,"Logger")&&console.log("[Logger] Starting tracking beat"),y.beatHandle=window.setInterval(y.flushTracking,15e3))}static setMessagePort(e){this.messagePort=e}static getMessagePort(){return this.messagePort}setLoggingOn(e){this.isLoggingOn=e}addEventListener(e,r){const n=s=>r(s);this.listenerMap.set(r,{eventName:e,wrappedListener:n}),this.eventTarget.addEventListener(e,n)}removeEventListener(e,r){const n=this.listenerMap.get(r);n&&n.eventName===e&&(this.eventTarget.removeEventListener(e,n.wrappedListener),this.listenerMap.delete(r))}removeAllEventListeners(){for(const[e,{eventName:r,wrappedListener:n}]of this.listenerMap)this.eventTarget.removeEventListener(r,n);this.listenerMap.clear()}setAttributes(e){y.processAttributes(e);for(const r in e)fe.logger.setContextProperty(r,e[r])}info(e,r){e==="didClickAd"&&this.emit("mediaSessionDidRegisterClick",{url:(r==null?void 0:r.url)||""}),e==="didToggleGlobalAugmentationDrawing"&&this.emit("mediaSessionDidUpdateGlobalAugmentationState",{isGlobalAugmentationEnabled:(r==null?void 0:r.isEnabled)||!0}),e==="didStartDrawingAugmentationMedia"&&this.emit("mediaSessionDidBeginShotRendering",r),e==="didEndDrawingAugmentationMedia"&&this.emit("mediaSessionDidEndShotRendering",r),e==="didRegisterShot"&&this.emit("mediaSessionDidRegisterShot",r),r&&y.processAttributes(r),this.isLoggingOn&&(fe.logger.info(e,r),y.options&&_(y.options,"Logger")&&console.log("[Logger] Sending info: ",e))}error(e,r){r&&y.processAttributes(r),this.isLoggingOn&&(fe.logger.error(e,r),y.tracking.err_time=Date.now().toFixed(0),y.tracking.err_desc=e+(r?` - ${JSON.stringify(r)}`:""),y.options&&_(y.options,"Logger")&&console.log("[Logger] Sending error: ",e))}warn(e,r){r&&y.processAttributes(r),this.isLoggingOn&&(fe.logger.warn(e,r),y.options&&_(y.options,"Logger")&&console.log("[Logger] Sending warn: ",e))}handleMessageFromWorker(e){e.actionType==="INFO"?this.info(e.message,e.attributes):e.actionType==="ERROR"?this.error(e.message,e.attributes):e.actionType==="WARN"?this.warn(e.message,e.attributes):e.actionType==="SET_ATTRIBUTES"&&e.attributes&&this.setAttributes(e.attributes)}static setAttributes(e){if(!y.messagePort){console.error("[Logger] messagePort is not set! Cannot send attributes.");return}try{y.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:e})}catch(r){console.error("[Logger] Error posting message:",r)}}static info(e,r){y.messagePort.postMessage({type:"LOG",actionType:"INFO",message:e,attributes:r})}static error(e,r){y.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:e,attributes:r})}static warn(e,r){y.messagePort.postMessage({type:"LOG",actionType:"WARN",message:e,attributes:r})}static processAttributes(e){if(e.player_version&&(y.tracking.sdk=e.player_version),e.media_id&&(y.tracking.gid=e.media_id),e.game_id&&(y.tracking.buc=e.game_id),e.bb_session_id&&(y.tracking.sid=e.bb_session_id,y.options&&_(y.options,"Logger")&&console.log("[Logger] Setting bb_session_id:",y.tracking.sid)),e.last_timecode){const n=L.fromStr(e.last_timecode);y.tracking.tc=n.print(),y.lastTimecodeMillis=n.totalMilliseconds(59.94),y.lastTimecodeMillis&&y.lastZipMillis&&(y.tracking.cache=(y.lastZipMillis-y.lastTimecodeMillis).toFixed(0))}e.last_offset&&(y.tracking.off=e.last_offset),e.last_loading_zip&&(y.tracking.zip=e.last_loading_zip+".zip",y.lastZipMillis=L.fromStr(e.last_loading_zip).totalMilliseconds(59.94),y.lastTimecodeMillis&&y.lastZipMillis&&(y.tracking.cache=(y.lastZipMillis-y.lastTimecodeMillis).toFixed(0))),e.last_rendered_frame&&(y.tracking.aug_time=Date.now().toFixed(0)),e.asset&&(y.tracking.asset=e.asset)}static objectToQuery(e){return Object.entries(e).filter(([r,n])=>n!==0&&n!=="").map(([r,n])=>`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`).join("&")}emit(e,r){const n=new CustomEvent(e,{detail:r});this.eventTarget.dispatchEvent(n)}};y.tracking={start:Date.now().toFixed(0),dev:"",sdk:"",mac:"",gid:"",sid:"",off:"",zip:"",aug_time:"",err_time:"",err_desc:"",tc:"",asset:"",cache:"",buc:""},y.lastTimecodeMillis=0,y.lastZipMillis=0,y.flushTracking=()=>{const e=Date.now().toFixed(0);y.tracking.now=e;const n=`https://dwu3k7rrxk5s3.cloudfront.net/metrics/1.gif?${y.objectToQuery(y.tracking)}`;y.options&&_(y.options,"Logger")&&console.log("[Logger] Flushing tracking data:",n),fetch(n,{method:"GET",mode:"no-cors",keepalive:!0,headers:{"X-Platform":"Web"}}).catch(()=>{}),y.tracking.err_desc="",y.tracking.err_time=""};let It=y;const la={env:"prod",urlConfigURL:"https://db8igqxlbvayn.cloudfront.net/url_config.json",gameBaseURL:"https://db8igqxlbvayn.cloudfront.net",zipBaseURL:"https://db8igqxlbvayn.cloudfront.net",adsBaseURL:"https://dwu3k7rrxk5s3.cloudfront.net",LOG_TO_DATADOG:!0,SEND_METRICS:!0,BURNED_TIMECODES_MODE:!1,RENDER_LED:!0,DRAW_TIMESTAMP_WEBGL:!1,ADAPTER_RUN_IN_WORKER:!1,DOWNLOADER_UPDATE_FREQUENCY:1e3,DOWNLOADER_ZIP_START_OFFSET:2,DOWNLOADER_ZIP_END_OFFSET:10,DOWNLOADER_ZIP_LENGTH_SECONDS:2,ZIP_BUFFER_READY_THRESHOLD:5,ZIP_BUFFER_FADEOUT_THRESHOLD:1,BENCHMARK_DURATION_SECONDS:10,DECODER_UPDATE_FREQUENCY:30,DECODER_FRAME_BATCH_SIZE:3,DECODER_LEAD_TIME_MILLIS:180,PERFORMANCE_TRACKING_INTERVAL:1e3,BUCKET_SUBFOLDER_PATH:"manifests/59.94/",debug:{on:!1,showAugmentationStatus:!1,logOTTPlayer:!1,logClocker:!1,logDownloader:!1,logDecoder:!1,logRenderer:!1,logFetcher:!1,logAdapter:!1,logAds:!1,logLogger:!1,logErrors:!1,trackPerformance:!1}},da="https://identity-qa.nba.com/qa/auth";class ua{constructor(e){this.cookies=[],this.xToken=null,this.authInProgress=!1,this.OTTPlayer=e,this.options=e.options,this.logger=e.logger}async fetchNBAToken(e,r){const n=this.options.authIdentityUrl||da;_(this.options,"OTTPlayer")&&console.log(`[CloudFrontAuth] Fetching JWT from: ${n}`);const s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,password:r})});if(!s.ok){const o=await s.text().catch(()=>"");throw new Error(`NBA auth request failed: ${s.status} ${s.statusText} - ${o}`)}const i=await s.json().catch(()=>null);if(!i||!i.data||!i.data.jwt)throw new Error("NBA auth response was invalid or missing JWT token");return i.data.jwt}async loginAndGetCookies(e){try{const r=this.options.authNbaToken,n=this.options.authEmail,s=this.options.authPassword;if(!r&&(!n||!s))return _(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] No credentials or NBA token provided, skipping authentication"),[];const i=this.options.zipBaseURL;if(!i)return console.warn("[CloudFrontAuth] No zipBaseURL configured, cannot authenticate"),[];if(this.lastGameId===e&&this.cookies.length>0)return _(this.options,"OTTPlayer")&&console.log(`[CloudFrontAuth] ✓ Using cached cookies for gameId=${e}`),this.cookies;if(this.authInProgress)return _(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] ⏳ Auth already in progress, waiting..."),await this.waitForAuth(),this.cookies;this.authInProgress=!0,this.lastGameId=e,console.log(`[CloudFrontAuth] 🔐 Starting authentication for gameId=${e}`),console.log(`[CloudFrontAuth] CloudFront URL: ${i}`);let o;r?(o=r,_(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] ✓ Using provided NBA token")):this.xToken?(o=this.xToken,_(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] ✓ Using existing x-token")):(o=await this.fetchNBAToken(n,s),_(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] ✓ Got JWT token from NBA Identity"));const a=`${i}/auth/${encodeURIComponent(e)}`;console.log(`[CloudFrontAuth] Fetching cookies from: ${a}`);const c=await fetch(a,{method:"GET",credentials:"include",headers:{Authorization:`Bearer ${o}`}});if(!c.ok&&c.status!==204)throw new Error(`Failed to fetch cookies: ${c.status} ${c.statusText}`);_(this.options,"OTTPlayer")&&console.log(`[CloudFrontAuth] Auth endpoint status: ${c.status}`);const d=c.headers.get("x-token");d&&(this.xToken=d,_(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] ✓ Received fresh x-token"));const l=c.headers.get("set-cookie");return l?this.cookies=l.split(",").map(u=>u.trim()):this.cookies=["browser-managed-httponly-cookies"],console.log("[CloudFrontAuth] ✅ Successfully authenticated"),console.log("[CloudFrontAuth] Note: Cookies are HttpOnly and managed by browser automatically"),this.logger.info("didAuthenticateCloudFront",{gameId:e,cookieCount:this.cookies.length,hasXToken:!!this.xToken}),this.scheduleCookieRefresh(e),this.cookies}catch(r){return console.error("[CloudFrontAuth] ❌ Authentication failed:",r),this.logger.error("[CloudFrontAuth] Authentication failed",{error:r.message||r}),this.xToken=null,[]}finally{this.authInProgress=!1}}async waitForAuth(){return new Promise(e=>{const r=setInterval(()=>{this.authInProgress||(clearInterval(r),e())},100)})}scheduleCookieRefresh(e){this.cookieRefreshTimer&&window.clearTimeout(this.cookieRefreshTimer),this.cookieRefreshTimer=window.setTimeout(()=>{_(this.options,"OTTPlayer")&&console.log(`[CloudFrontAuth] Auto-refreshing cookies and x-token for gameId=${e}`),this.loginAndGetCookies(e)},7*60*60*1e3)}getCookies(){return this.cookies}getXToken(){return this.xToken}isAuthenticated(){return this.cookies.length>0}destroy(){this.cookies=[],this.xToken=null,this.lastGameId=void 0,this.cookieRefreshTimer&&(window.clearTimeout(this.cookieRefreshTimer),this.cookieRefreshTimer=void 0)}}class ha{constructor(e){this.groups=new Map,this.isVisible=!0,this.lastFrameTime=0,this.TARGET_FPS=60,this.FRAME_INTERVAL=1e3/this.TARGET_FPS,this.canvas=document.createElement("canvas"),this.canvas.style.position="absolute",this.canvas.style.top="0",this.canvas.style.left="0",this.canvas.style.pointerEvents="none",this.canvas.style.zIndex="3001",this.canvas.width=e.clientWidth,this.canvas.height=e.clientHeight,this.canvas.style.width="100%",this.canvas.style.height="100%",this.ctx=this.canvas.getContext("2d"),e.appendChild(this.canvas),this.initializeGroups(),this.startRenderLoop(),this.setupResizeObserver(e)}initializeGroups(){this.groups.set("support",{title:"Basic Augmentation Support",metrics:new Map([["game_params",{value:!1}],["browser",{value:!1,detail:""}],["pattern",{value:!1,detail:""}],["fps",{value:!1,detail:""}],["mk_ads",{value:!1,detail:""}]])}),this.groups.set("timecode",{title:"TimeCode Status",metrics:new Map([["sync_point",{value:!1,detail:""}],["consistency",{value:!1,detail:""}]])}),this.groups.set("benchmark",{title:"",metrics:new Map([["status",{value:"FAILED",detail:""}]])}),this.groups.set("switches",{title:"Augmentation Switches",metrics:new Map([["killswitch_web",{value:!1}],["killswitch_local",{value:!1}],["isLive",{value:!1}],["render_state",{value:"OFF"}]])}),this.groups.set("data",{title:"Augmentation Data Presence",metrics:new Map([["zip_buffer",{value:!1,detail:"0.0s"}],["stream_data",{value:!1}],["ads",{value:!1}],["render_data",{value:!1}],["alpha_mask",{value:!1}],["placeholders",{value:!1}],["processing_size",{value:!1}]])}),this.groups.set("health",{title:"Player Components Health",metrics:new Map([["decoder",{value:!1,detail:""}],["webgl",{value:!1,detail:""}]])})}updateMetric(e,r,n,s){const i=this.groups.get(e);i&&i.metrics.set(r,{value:n,detail:s})}startRenderLoop(){const e=r=>{r-this.lastFrameTime>=this.FRAME_INTERVAL&&(this.isVisible&&this.draw(),this.lastFrameTime=r),this.animationFrameId=requestAnimationFrame(e)};this.animationFrameId=requestAnimationFrame(e)}setupResizeObserver(e){typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>{this.canvas.width=e.clientWidth,this.canvas.height=e.clientHeight}),this.resizeObserver.observe(e))}draw(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);const e=12,r=e+3,n=10,s=15,i=10;this.ctx.font=`${e}px monospace`,this.ctx.textBaseline="top";let o=i;this.groups.forEach((c,d)=>{var l;if(d==="benchmark"){const u=c.metrics.get("status");if(u){const f=u.value;let p,h;f==="PASSED"?(p="rgba(0,255,136,0.8)",h="STABILITY TEST: PASSED"):f==="TESTING"?(p="rgba(255,170,0,0.8)",h=`STABILITY TEST: TESTING${u.detail?" ("+((l=u.detail.split(":")[1])==null?void 0:l.trim())+")":""}`):(p="rgba(255,51,51,0.8)",h="STABILITY TEST: FAILED"),this.ctx.fillStyle=p,this.ctx.fillRect(i,o,250,20),this.ctx.fillStyle="#000",this.ctx.font=`bold ${e}px monospace`,this.ctx.fillText(h,i+5,o+4),this.ctx.font=`${e}px monospace`,o+=25}return}this.ctx.fillStyle="rgba(0,0,0,0.7)",this.ctx.fillRect(i,o,300,r+2),this.ctx.fillStyle="#fff",this.ctx.font=`bold ${e}px monospace`,this.ctx.fillText(c.title,i+5,o+1),this.ctx.font=`${e}px monospace`,o+=r+4,c.metrics.forEach((u,f)=>{const p=this.getColorForValue(u.value),h=this.formatValue(u.value);this.ctx.fillStyle="rgba(0,0,0,0.5)",this.ctx.fillRect(i+s,o,285-s,r),this.ctx.fillStyle=p,this.ctx.beginPath(),this.ctx.arc(i+s+5,o+r/2,3,0,Math.PI*2),this.ctx.fill(),this.ctx.fillStyle="#fff";const m=f.replace(/_/g," ");this.ctx.fillText(`${m}: ${h}`,i+s+15,o+1),o+=r,u.detail&&(this.ctx.fillStyle="rgba(0,0,0,0.4)",this.ctx.fillRect(i+s,o,285-s,r),this.ctx.fillStyle="#aaa",this.ctx.fillText(` ${u.detail}`,i+s+15,o+1),o+=r)}),o+=n});const a=this.isAugmentationReady();this.ctx.fillStyle=a?"rgba(0,255,136,0.8)":"rgba(255,51,51,0.8)",this.ctx.fillRect(i,o,250,20),this.ctx.fillStyle="#000",this.ctx.font=`bold ${e}px monospace`,this.ctx.fillText(`AUGMENTATION: ${a?"READY":"NOT READY"}`,i+5,o+4),this.ctx.font=`${e}px monospace`}formatValue(e){return typeof e=="boolean"?e?"OK":"NO":e==="PASSED"?"PASSED":e==="TESTING"?"TESTING":e==="FAILED"?"FAILED":e}getColorForValue(e){return typeof e=="boolean"?e?"#00ff88":"#ff3333":e==="ON"||e==="FADE_IN"?"#00ff88":e==="FADE_OUT"?"#ffaa00":e==="PASSED"?"#00ff88":e==="TESTING"?"#ffaa00":"#ff3333"}isAugmentationReady(){var u,f,p,h,m,g,S,b,E,A;const e=this.groups.get("support"),r=this.groups.get("switches"),n=this.groups.get("data"),s=this.groups.get("health"),i=this.groups.get("benchmark");if(!e||!r||!n||!s||!i)return!1;const o=((u=e.metrics.get("game_params"))==null?void 0:u.value)===!0&&((f=e.metrics.get("browser"))==null?void 0:f.value)===!0&&((p=e.metrics.get("pattern"))==null?void 0:p.value)===!0&&((h=e.metrics.get("fps"))==null?void 0:h.value)===!0&&((m=e.metrics.get("mk_ads"))==null?void 0:m.value)===!0,a=((g=r.metrics.get("killswitch_web"))==null?void 0:g.value)===!0&&((S=r.metrics.get("killswitch_local"))==null?void 0:S.value)===!0&&(((b=r.metrics.get("render_state"))==null?void 0:b.value)==="ON"||((E=r.metrics.get("render_state"))==null?void 0:E.value)==="FADE_IN"),c=Array.from(n.metrics.values()).every(w=>w.value===!0),d=Array.from(s.metrics.values()).every(w=>w.value===!0),l=((A=i.metrics.get("status"))==null?void 0:A.value)==="PASSED";return o&&a&&c&&d&&l}toggle(){this.isVisible=!this.isVisible,this.isVisible||this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}pause(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}resume(){this.animationFrameId||this.startRenderLoop()}delete(){this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.resizeObserver&&this.resizeObserver.disconnect(),this.canvas.remove()}}class en{constructor(e,r,n,s){this.RUN_PIXEL_TICKERS=!0,this.pixelTickers=[],this.handleVisibilityChange=()=>{document.hidden?this.onTabHidden():this.onTabVisible()},this.fetchGameParams=async()=>{try{if(_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] GameId: ",this.options.gameId),this.options.OVERRIDE_GAME_PARAMS){_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Using OVERRIDE_GAME_PARAMS from configuration");const d=this.options.OVERRIDE_GAME_PARAMS;if(this.options.BURNED_TIMECODES_MODE){this.gameParams=d;return}if(d.hasOwnProperty("bucketName")&&d.hasOwnProperty("offsets")){if(this.logger.setAttributes({game_id:d.bucketName,customer_name:d.customerName,customer_id:d.customerId}),this.gameParams){const l=JSON.stringify(this.gameParams),u=JSON.stringify(d);l!==u&&this.logger.info("didChangeGameParams",{oldParams:this.gameParams,newParams:d})}else this.logger.info("didFetchGameInfo",d);this.gameParams=d,this.cloudFrontAuth&&d.bucketName&&this.cloudFrontAuth.loginAndGetCookies(d.bucketName).then(()=>{_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] CloudFront authentication completed for bucketName:",d.bucketName)}).catch(l=>{_(this.options,"Errors")&&console.error("[OTTPlayer] CloudFront authentication failed:",l)});return}else throw new Error(`OVERRIDE_GAME_PARAMS for ${this.options.gameId} is missing required properties (bucketName or offsets)`)}let o;const a=`${this.options.gameBaseURL}/${this.options.gameId}.json`;if(_(this.options,"OTTPlayer")&&console.log(`Fetching GameParams from ${a}`),this.options.SEND_METRICS?o=await fetch(a,{headers:{"X-Platform":"Web"},cache:"no-store"}):o=await fetch(a,{cache:"no-store"}),!o.ok){const d=`Unable to fetch game params for ${this.options.gameId}. HTTP error. Status: ${o.status}`;this.logger.error("[OTTPlayer] Failed to fetch game params",{status:o.status,gameId:this.options.gameId}),_(this.options,"Errors")&&console.error(`[OTTPlayer] ${d}`),this.destroy();return}const c=await o.json();if(this.options.BURNED_TIMECODES_MODE){this.gameParams=c;return}if(this.handleOttActions(o,c),c.hasOwnProperty("bucketName")&&c.hasOwnProperty("offsets"))o=c;else throw new Error(`Game params for ${this.options.gameId} not found in JSON`);if(this.logger.setAttributes({game_id:o.bucketName,customer_name:o.customerName,customer_id:o.customerId}),this.gameParams){const d=JSON.stringify(this.gameParams),l=JSON.stringify(o);d!==l&&this.logger.info("didChangeGameParams",{oldParams:this.gameParams,newParams:o})}else this.logger.info("didFetchGameInfo",this.gameParams);this.gameParams=o,this.cloudFrontAuth&&o.bucketName&&this.cloudFrontAuth.loginAndGetCookies(o.bucketName).then(()=>{_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] CloudFront authentication completed for bucketName:",o.bucketName)}).catch(d=>{_(this.options,"Errors")&&console.error("[OTTPlayer] CloudFront authentication failed:",d)})}catch(o){this.logger.error("[OTTPlayer] Error fetching game params",{error:o}),_(this.options,"Errors")&&console.error("[OTTPlayer] Error fetching game params:",o)}this.fetchGameParamsTimeoutId=window.setTimeout(()=>this.fetchGameParams(),1e4)},this.setGameParams=o=>{try{if(_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Overriding game params"),this.fetchGameParamsTimeoutId&&(window.clearTimeout(this.fetchGameParamsTimeoutId),this.fetchGameParamsTimeoutId=void 0),this.options.BURNED_TIMECODES_MODE){this.gameParams=o;return}if(o.hasOwnProperty("bucketName")&&o.hasOwnProperty("offsets")){if(this.logger.setAttributes({game_id:o.bucketName,customer_name:o.customerName,customer_id:o.customerId}),this.gameParams){const a=JSON.stringify(this.gameParams),c=JSON.stringify(o);a!==c&&this.logger.info("didChangeGameParams",{oldParams:this.gameParams,newParams:o})}else this.logger.info("didFetchGameInfo",o);this.gameParams=o,this.cloudFrontAuth&&o.bucketName&&this.cloudFrontAuth.loginAndGetCookies(o.bucketName).then(()=>{_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] CloudFront authentication completed for bucketName:",o.bucketName)}).catch(a=>{_(this.options,"Errors")&&console.error("[OTTPlayer] CloudFront authentication failed:",a)});return}else throw new Error(`Game params for ${this.options.gameId} is missing required properties (bucketName or offsets)`)}catch(a){this.logger.error("[OTTPlayer] Error overriding game params",{error:a}),_(this.options,"Errors")&&console.error("[OTTPlayer] Error overriding game params:",a)}};const i="OTTPlayer_v1.0.69";console.log(`%c${i}`,"font-size: 16px; font-weight: bold; color: blue;"),this.video=e,this.options={...n,...la,platform:I.getCurrentPlatform(),browserName:I.getBrowserName(),augmentation:{channelName:"nba"}},this.options.browserName==="Firefox"&&(this.options.DECODER_LEAD_TIME_MILLIS=300),_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Starting fetchUrlConfig"),this.fetchUrlConfig(s),this.logger=new It(this.options),this.logger.setAttributes({player_version:i,bb_session_id:crypto.randomUUID()}),this.logger.info("didGetConfiguration",{...n,fps:r}),tn(this.options,s).then(()=>{var o;if(this.logger.setAttributes({media_id:this.options.gameId}),window.BB.playerInstances.length>0&&window.BB.playerInstances.forEach(a=>{a.destroy()}),window.BB.workerInstances.length>0&&window.BB.workerInstances.forEach(a=>{a.terminate()}),this.cloudFrontAuth=new ua(this),this.clocker=new dn(this),this.adapter=new it(this),this.ottActions={toggle:{ios:!0,android:!0,web:!0,local:this.options.enabled}},(o=this.options.debug)!=null&&o.showAugmentationStatus){const a=this.options.CANVAS_CONTAINER||this.video.parentElement;a&&(this.statusOverlay=new ha(a))}this.RUN_PIXEL_TICKERS&&(this.pixelTickers=q.createInAllCorners(this.video)),this.applyImageOverridesFromOptions(),this.flushPendingOverrides(),this.fetchGameParams(),window.BB.playerInstances.push(this),document.addEventListener("visibilitychange",this.handleVisibilityChange)})}onNewMetadata(e){!this.adapter||this.options.BURNED_TIMECODES_MODE||this.adapter.onNewMetadata(e)}onNewSegment(e){!this.adapter||this.options.BURNED_TIMECODES_MODE||this.adapter.onNewSegmentForMetadata(e)}onAdEvent(e){console.log(`[OTTPlayer] onAdEvent: ${e}`),!(!this.adapter||this.options.BURNED_TIMECODES_MODE)&&this.adapter.onAdEvent(e)}async fetchUrlConfig(e){try{if(!this.options.urlConfigURL){_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] No urlConfigURL provided, skipping URL config fetch");return}_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Fetching URL config from:",this.options.urlConfigURL);const r=await fetch(this.options.urlConfigURL);if(!r.ok)throw new Error(`Failed to fetch URL config: ${r.status} ${r.statusText}`);const n=await r.json();if(!n||typeof n!="object")throw new Error("Invalid URL config structure: not an object");const s=this.options.env;if(!n[s])throw new Error(`Environment '${s}' not found in URL config`);const i=n[s];if(!i.gameBaseUrl||!i.zipBaseUrl||!i.adsBaseUrl)throw new Error(`Missing required URLs in environment '${s}' config`);e!=null&&e.gameBaseURL||(this.options.gameBaseURL=i.gameBaseUrl),e!=null&&e.zipBaseURL||(this.options.zipBaseURL=i.zipBaseUrl),e!=null&&e.adsBaseURL||(this.options.adsBaseURL=i.adsBaseUrl),_(this.options,"OTTPlayer")&&(console.log("[OTTPlayer] URL config loaded successfully for environment:",s),console.log("[OTTPlayer] Updated URLs:",{gameBaseURL:this.options.gameBaseURL,zipBaseURL:this.options.zipBaseURL,adsBaseURL:this.options.adsBaseURL}))}catch(r){_(this.options,"OTTPlayer")&&(console.warn("[OTTPlayer] Failed to fetch URL config:",r),console.log("[OTTPlayer] Using default URLs from options"))}}handleOttActions(e,r){if(!this.clocker||this.options.BURNED_TIMECODES_MODE)return;const n=e.headers.get("x-tgi-ott-actions");let s;if(n?s=JSON.parse(n):s={toggle:{ios:!0,android:!0,web:!0}},!this.ottActions||this.ottActions.toggle.web!==s.toggle.web||s.toggle[r.customerId]!==void 0&&(this.ottActions.toggle[r.customerId]===void 0||this.ottActions.toggle[r.customerId]!==s.toggle[r.customerId])||s.toggle[r.customerId]===void 0&&this.ottActions.toggle[r.customerId]!==void 0){const o=s.toggle[r.customerId]!==void 0?s.toggle[r.customerId]&&s.toggle.web:s.toggle.web;this.ottActions&&this.logger.info("didToggleGlobalAugmentationDrawing",{isEnabled:o}),s.toggle.local=this.options.enabled,this.ottActions=s,console.warn("[OTTPlayer] ottActions",s)}}toggle(e){this.options.enabled=e,this.ottActions&&(this.ottActions.toggle.local=e,this.logger.info("didToggleGlobalAugmentationDrawing",{isEnabled:e}))}setFps(e){this.fps=e}setMediaInfo(e){e.fps&&this.setFps(e.fps),e.bitrate&&(this.bitrate=e.bitrate)}setAd(e,r){if(typeof e=="string"){let n;try{n=new URL(e,document.baseURI).toString()}catch(s){_(this.options,"Errors")&&console.error("[OTTPlayer] Invalid ad URL passed to setAd",e,s);return}fetch(n,{cache:"no-store"}).then(s=>s.blob()).then(async s=>{if(!this.clocker){this.pendingAdBlob=s,this.pendingAdPlaceholder=r;return}this.clocker.setAdBlob(s,r)}).catch(s=>{_(this.options,"Errors")&&console.error("[OTTPlayer] Failed to fetch ad image from URL in setAd",n,s)});return}if(!this.clocker){if(e instanceof Blob)this.pendingAdBlob=e;else{if(this.pendingAdBitmap)try{this.pendingAdBitmap.close()}catch{}this.pendingAdBitmap=e}this.pendingAdPlaceholder=r;return}if(e instanceof Blob){this.clocker.setAdBlob(e,r);return}else this.clocker.setAdImage(e,r)}setLED(e){if(typeof e=="string"){let r;try{r=new URL(e,document.baseURI).toString()}catch(n){_(this.options,"Errors")&&console.error("[OTTPlayer] Invalid LED URL passed to setLED",e,n);return}fetch(r,{cache:"no-store"}).then(n=>n.blob()).then(n=>{if(!this.clocker){this.pendingLEDBlob=n;return}this.clocker.setLEDBlob(n)}).catch(n=>{_(this.options,"Errors")&&console.error("[OTTPlayer] Failed to fetch LED image from URL in setLED",r,n)});return}if(!this.clocker){if(e instanceof Blob)this.pendingLEDBlob=e;else{if(this.pendingLEDBitmap)try{this.pendingLEDBitmap.close()}catch{}this.pendingLEDBitmap=e}return}e instanceof Blob?this.clocker.setLEDBlob(e):this.clocker.setLEDImage(e)}async applyImageOverridesFromOptions(){try{const e=[];this.options.OVERRIDE_AD&&e.push(this.applySingleOverride(this.options.OVERRIDE_AD,"ad")),this.options.OVERRIDE_LED&&e.push(this.applySingleOverride(this.options.OVERRIDE_LED,"led")),await Promise.all(e)}catch(e){_(this.options,"Errors")&&console.error("[OTTPlayer] Failed to apply image overrides",e)}}async applySingleOverride(e,r){let n;if(typeof e=="string")try{const s=new URL(e,document.baseURI).toString();n=await(await fetch(s,{cache:"no-store"})).blob()}catch(s){_(this.options,"Errors")&&console.error(`[OTTPlayer] Failed to fetch override ${r} from URL`,e,s);return}else n=e;if(n){if(!this.clocker){r==="ad"?this.pendingAdBlob=n:this.pendingLEDBlob=n;return}r==="ad"?this.clocker.setAdBlob(n):this.clocker.setLEDBlob(n)}}flushPendingOverrides(){if(this.clocker){if(this.pendingAdBitmap){const e=this.pendingAdBitmap;this.pendingAdBitmap=void 0,this.clocker.setAdImage(e,this.pendingAdPlaceholder),this.pendingAdPlaceholder=void 0}else if(this.pendingAdBlob){const e=this.pendingAdBlob;this.pendingAdBlob=void 0,this.clocker.setAdBlob(e,this.pendingAdPlaceholder),this.pendingAdPlaceholder=void 0}if(this.pendingLEDBitmap){const e=this.pendingLEDBitmap;this.pendingLEDBitmap=void 0,this.clocker.setLEDImage(e)}else if(this.pendingLEDBlob){const e=this.pendingLEDBlob;this.pendingLEDBlob=void 0,this.clocker.setLEDBlob(e)}}}onTabHidden(){var e,r,n;_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Tab hidden - pausing all components"),this.fetchGameParamsTimeoutId&&(window.clearTimeout(this.fetchGameParamsTimeoutId),this.fetchGameParamsTimeoutId=void 0),(e=this.clocker)==null||e.pause(),(r=this.adapter)==null||r.pause(),(n=this.statusOverlay)==null||n.pause()}onTabVisible(){var e,r,n;_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Tab visible - resuming all components"),(e=this.clocker)==null||e.resume(),(r=this.adapter)==null||r.resume(),(n=this.statusOverlay)==null||n.resume(),this.fetchGameParams()}on(e,r){this.logger.addEventListener(e,r)}off(e,r){this.logger.removeEventListener(e,r)}destroy(){var r;document.removeEventListener("visibilitychange",this.handleVisibilityChange),this.fetchGameParamsTimeoutId&&(window.clearTimeout(this.fetchGameParamsTimeoutId),this.fetchGameParamsTimeoutId=void 0),(r=this.clocker)==null||r.delete(),this.clocker=void 0,this.adapter&&(this.adapter.delete(),this.adapter=void 0),this.cloudFrontAuth&&(this.cloudFrontAuth.destroy(),this.cloudFrontAuth=void 0),this.statusOverlay&&(this.statusOverlay.delete(),this.statusOverlay=void 0),q.deleteAll(this.pixelTickers),this.pixelTickers=[],this.logger.removeAllEventListeners();const e=window.BB.playerInstances.indexOf(this);e>=0&&window.BB.playerInstances.splice(e,1)}}return window.BB={OTTPlayer:en,playerInstances:[],workerInstances:[]},en});
|
|
500
|
+
${f}`),t.finish(m=>{h(Wr(m))})}return{flushController:r,add:d,upsert:d,stop:i.unsubscribe}}function Wr(t){let e;return typeof t.output=="string"?e=t.output:e=new Blob([t.output],{type:"text/plain"}),{data:e,bytesCount:t.outputBytesCount,encoding:t.encoding}}function Xi({messagesLimit:t,bytesLimit:e,durationLimit:r,pageExitObservable:n,sessionExpireObservable:s}){const i=n.subscribe(h=>l(h.reason)),o=s.subscribe(()=>l("session_expire")),a=new k(()=>()=>{i.unsubscribe(),o.unsubscribe()});let c=0,d=0;function l(h){if(d===0)return;const m=d,g=c;d=0,c=0,p(),a.notify({reason:h,messagesCount:m,bytesCount:g})}let u;function f(){u===void 0&&(u=Te(()=>{l("duration_limit")},r))}function p(){er(u),u=void 0}return{flushObservable:a,get messagesCount(){return d},notifyBeforeAddMessage(h){c+h>=e&&l("bytes_limit"),d+=1,c+=h,f()},notifyAfterAddMessage(h=0){c+=h,d>=t?l("messages_limit"):c>=e&&l("bytes_limit")},notifyAfterRemoveMessage(h){c-=h,d-=1,d===0&&p()}}}function jr(t,e,r,n,s,i,o=qi){const a=d(t,e),c=r&&d(t,r);function d(l,{endpoint:u,encoder:f}){return o({encoder:f,request:zi(u,l.batchBytesLimit,n),flushController:Xi({messagesLimit:l.batchMessagesLimit,bytesLimit:l.batchBytesLimit,durationLimit:l.flushTimeout,pageExitObservable:s,sessionExpireObservable:i}),messageBytesLimit:l.messageBytesLimit})}return{flushObservable:a.flushController.flushObservable,add(l,u=!0){a.add(l),c&&u&&c.add(r.transformMessage?r.transformMessage(l):l)},upsert:(l,u)=>{a.upsert(l,u),c&&c.upsert(r.transformMessage?r.transformMessage(l):l,u)},stop:()=>{a.stop(),c&&c.stop()}}}function Ze(){let t="",e=0;return{isAsync:!1,get isEmpty(){return!t},write(r,n){const s=ct(r);e+=s,t+=r,n&&n(s)},finish(r){r(this.finishSync())},finishSync(){const r={output:t,outputBytesCount:e,rawBytesCount:e,pendingData:""};return t="",e=0,r},estimateEncodedBytesCount(r){return r.length}}}class Ki{constructor(){this.callbacks={}}notify(e,r){const n=this.callbacks[e];n&&n.forEach(s=>s(r))}subscribe(e,r){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(r),{unsubscribe:()=>{this.callbacks[e]=this.callbacks[e].filter(n=>r!==n)}}}}function Ji(t,e,r){let n=0,s=!1;return{isLimitReached(){if(n===0&&Te(()=>{n=0},K),n+=1,n<=e||s)return s=!1,!1;if(n===e+1){s=!0;try{r({message:`Reached max number of ${t}s by minute: ${e}`,source:P.AGENT,startClocks:V()})}finally{s=!1}}return!0}}}let Ct;const Dt=new WeakMap;function Zi(t){return Ct||(Ct=Qi(t)),Ct}function Qi(t){return new k(e=>{const{stop:r}=re(XMLHttpRequest.prototype,"open",eo),{stop:n}=re(XMLHttpRequest.prototype,"send",i=>{to(i,t,e)},{computeHandlingStack:!0}),{stop:s}=re(XMLHttpRequest.prototype,"abort",ro);return()=>{r(),n(),s()}})}function eo({target:t,parameters:[e,r]}){Dt.set(t,{state:"open",method:String(e).toUpperCase(),url:_t(String(r))})}function to({target:t,handlingStack:e},r,n){const s=Dt.get(t);if(!s)return;const i=s;i.state="start",i.startClocks=V(),i.isAborted=!1,i.xhr=t,i.handlingStack=e;let o=!1;const{stop:a}=re(t,"onreadystatechange",()=>{t.readyState===XMLHttpRequest.DONE&&c()}),c=()=>{if(d(),a(),o)return;o=!0;const l=s;l.state="complete",l.duration=vn(i.startClocks.timeStamp,G()),l.status=t.status,n.notify(xn(l))},{stop:d}=ne(r,t,"loadend",c);n.notify(i)}function ro({target:t}){const e=Dt.get(t);e&&(e.isAborted=!0)}let kt;function Yr(){return kt||(kt=no()),kt}function no(){return new k(t=>{if(!window.fetch)return;const{stop:e}=re(window,"fetch",r=>so(r,t),{computeHandlingStack:!0});return e})}function so({parameters:t,onPostCall:e,handlingStack:r},n){const[s,i]=t;let o=i&&i.method;o===void 0&&s instanceof Request&&(o=s.method);const a=o!==void 0?String(o).toUpperCase():"GET",c=s instanceof Request?s.url:_t(String(s)),d=V(),l={state:"start",init:i,input:s,method:a,startClocks:d,url:c,handlingStack:r};n.notify(l),t[0]=l.input,t[1]=l.init,e(u=>io(n,u,l))}function io(t,e,r){const n=r;function s(i){n.state="resolve",Object.assign(n,i),t.notify(n)}e.then(x(i=>{s({response:i,responseType:i.type,status:i.status,isAborted:!1})}),x(i=>{var o,a;s({status:0,isAborted:((a=(o=n.init)===null||o===void 0?void 0:o.signal)===null||a===void 0?void 0:a.aborted)||i instanceof DOMException&&i.code===DOMException.ABORT_ERR,error:i})}))}let Ut={};function oo(t){const e=t.map(r=>(Ut[r]||(Ut[r]=ao(r)),Ut[r]));return rr(...e)}function ao(t){return new k(e=>{const r=M[t];return M[t]=(...n)=>{r.apply(console,n);const s=je("console error");ve(()=>{e.notify(co(n,t,s))})},()=>{M[t]=r}})}function co(t,e,r){const n=t.map(i=>lo(i)).join(" ");let s;if(e===C.error){const i=t.find(Y);s={stack:i?te(N(i)):void 0,fingerprint:Sr(i),causes:i?xr(i,"console"):void 0,startClocks:V(),message:n,source:P.CONSOLE,handling:"handled",handlingStack:r,context:Er(i)}}return{api:e,message:n,error:s,handlingStack:r}}function lo(t){return typeof t=="string"?z(t):Y(t)?br(N(t)):ee(z(t),void 0,2)}function uo(t){const e=Dr(t)==="object";return e||D.error("Unsupported context:",t),e}function Ft(t,e,r){const n={...t};for(const[s,{required:i,type:o}]of Object.entries(e))o==="string"&&s in n&&(n[s]=String(n[s])),i&&!(s in t)&&D.warn(`The property ${s} of ${r} is required; context will not be sent to the intake.`);return n}function Qe(t="",{customerDataTracker:e,propertiesConfig:r={}}={}){let n={};const s=new k,i={getContext:()=>kr(n),setContext:o=>{uo(o)?(n=z(Ft(o,r,t)),e==null||e.updateCustomerData(n)):i.clearContext(),s.notify()},setContextProperty:(o,a)=>{n=z(Ft({...n,[o]:a},r,t)),e==null||e.updateCustomerData(n),s.notify()},removeContextProperty:o=>{delete n[o],e==null||e.updateCustomerData(n),Ft(n,r,t),s.notify()},clearContext:()=>{n={},e==null||e.resetCustomerData(),s.notify()},changeObservable:s};return i}const ho="_dd_c",fo=[];function Lt(t,e,r,n){const s=po(r,n);fo.push(ne(t,window,"storage",({key:d})=>{s===d&&o()})),e.changeObservable.subscribe(a);const i=ue(c(),e.getContext());be(i)||e.setContext(i);function o(){e.setContext(c())}function a(){localStorage.setItem(s,JSON.stringify(e.getContext()))}function c(){const d=localStorage.getItem(s);return d?JSON.parse(d):{}}}function po(t,e){return`${ho}_${t}_${e}`}const mo=3*B,go=16*B,yo=200;function _o(t=2){const e=new Map;let r=!1;function n(s=0){if(r||t===0)return;const i=t===2?mo:go;let o=s;e.forEach(a=>{o+=a.getBytesCount()}),o>i&&(bo(i),r=!0)}return{createDetachedTracker:()=>{const s=qr(()=>n(s.getBytesCount()));return s},getOrCreateTracker:s=>(e.has(s)||e.set(s,qr(n)),e.get(s)),setCompressionStatus:s=>{t===0&&(t=s,n())},getCompressionStatus:()=>t,stop:()=>{e.forEach(s=>s.stop()),e.clear()}}}function qr(t){let e=0;const{throttled:r,cancel:n}=nr(i=>{e=ct(ee(i)),t()},yo),s=()=>{n(),e=0};return{updateCustomerData:i=>{be(i)?s():r(i)},resetCustomerData:s,getBytesCount:()=>e,stop:()=>{n()}}}function bo(t){D.warn(`Customer data exceeds the recommended ${t/B}KiB threshold. ${Fe} ${Yt}/#customer-data-exceeds-the-recommended-threshold-warning`)}function vo(t,e,r){const n=t.getReader(),s=[];let i=0;o();function o(){n.read().then(x(c=>{if(c.done){a();return}s.push(c.value),i+=c.value.length,i>r.bytesLimit?a():o()}),x(c=>e(c)))}function a(){n.cancel().catch(W);let c,d;{let l;if(s.length===1)l=s[0];else{l=new Uint8Array(i);let u=0;s.forEach(f=>{l.set(f,u),u+=f.length})}c=l.slice(0,r.bytesLimit),d=l.length>r.bytesLimit}e(void 0,c,d)}}const To="datadog-synthetics-public-id",So="datadog-synthetics-result-id",Eo="datadog-synthetics-injects-rum";function Xr(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||J(Eo))}function xo(){const t=window._DATADOG_SYNTHETICS_PUBLIC_ID||J(To);return typeof t=="string"?t:void 0}function wo(){const t=window._DATADOG_SYNTHETICS_RESULT_ID||J(So);return typeof t=="string"?t:void 0}function et(t,e,r){const n=r.getHandler(),s=Array.isArray(n)?n:[n];return Kr[t]>=Kr[r.getLevel()]&&s.includes(e)}const T={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},Kr={[T.ok]:0,[T.debug]:1,[T.info]:2,[T.notice]:4,[T.warn]:5,[T.error]:6,[T.critical]:7,[T.alert]:8,[T.emerg]:9};function tt(t,{includeMessage:e=!1}={}){return{stack:t.stack,kind:t.type,message:e?t.message:void 0,causes:t.causes,fingerprint:t.fingerprint,handling:t.handling}}var Ao=function(t,e,r,n){var s=arguments.length,i=s<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,r,i):o(e,r))||i);return s>3&&i&&Object.defineProperty(e,r,i),i};const Ce={console:"console",http:"http",silent:"silent"},Ro=Object.keys(T);let O=class{constructor(e,r,n,s=Ce.http,i=T.debug,o={}){this.handleLogStrategy=e,this.handlerType=s,this.level=i,this.contextManager=Qe("logger",{customerDataTracker:r}),this.contextManager.setContext(o),n&&this.contextManager.setContextProperty("logger",{name:n})}logImplementation(e,r,n=T.info,s,i){const o=z(r);let a;if(s!=null){const c=Tr({stackTrace:Y(s)?N(s):void 0,originalError:s,nonErrorPrefix:"Provided",source:P.LOGGER,handling:"handled",startClocks:V()});a=ue({error:tt(c,{includeMessage:!0})},o)}else a=o;this.handleLogStrategy({message:z(e),context:a,status:n},this,i)}log(e,r,n=T.info,s){let i;et(n,Ce.http,this)&&(i=je("log")),this.logImplementation(e,r,n,s,i)}setContext(e){this.contextManager.setContext(e)}getContext(){return this.contextManager.getContext()}setContextProperty(e,r){this.contextManager.setContextProperty(e,r)}removeContextProperty(e){this.contextManager.removeContextProperty(e)}clearContext(){this.contextManager.clearContext()}setHandler(e){this.handlerType=e}getHandler(){return this.handlerType}setLevel(e){this.level=e}getLevel(){return this.level}};Ao([Rn],O.prototype,"logImplementation",null),O.prototype.ok=$(T.ok),O.prototype.debug=$(T.debug),O.prototype.info=$(T.info),O.prototype.notice=$(T.notice),O.prototype.warn=$(T.warn),O.prototype.error=$(T.error),O.prototype.critical=$(T.critical),O.prototype.alert=$(T.alert),O.prototype.emerg=$(T.emerg);function $(t){return function(e,r,n){let s;et(t,Ce.http,this)&&(s=je("log")),this.logImplementation(e,r,t,n,s)}}function Co(t,e,r){return{view:{referrer:document.referrer,url:window.location.href},context:t.getContext(),user:e.getContext(),account:r.getContext()}}const Do=32*B;function ko(t){t.usePciIntake===!0&&t.site&&t.site!=="datadoghq.com"&&D.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");const e=Rs(t),r=Jr(t.forwardConsoleLogs,Be(C),"Forward Console Logs"),n=Jr(t.forwardReports,Be(Ye),"Forward Reports");if(!(!e||!r||!n))return t.forwardErrorsToLogs&&!r.includes(C.error)&&r.push(C.error),{forwardErrorsToLogs:t.forwardErrorsToLogs!==!1,forwardConsoleLogs:r,forwardReports:n,requestErrorResponseLengthLimit:Do,...e}}function Jr(t,e,r){if(t===void 0)return[];if(!(t==="all"||Array.isArray(t)&&t.every(n=>e.includes(n)))){D.error(`${r} should be "all" or an array with allowed values "${e.join('", "')}"`);return}return t==="all"?e:hi(t)}function Uo(t){const e=Cs(t);return{forward_errors_to_logs:t.forwardErrorsToLogs,forward_console_logs:t.forwardConsoleLogs,forward_reports:t.forwardReports,use_pci_intake:t.usePciIntake,...e}}function Fo(t,e,r){const n=Fr();let s,i;const o=e.observable.subscribe(a);function a(){if(!i||!s||!e.isGranted())return;o.unsubscribe();const c=r(s,i);n.drain(c)}return{init(c){if(!c){D.error("Missing configuration");return}if(Ds(c.enableExperimentalFeatures),Ke()&&(c=Lo(c)),s=c,i){wr("DD_LOGS",c);return}const d=ko(c);d&&(i=d,Yr().subscribe(W),e.tryToInit(d.trackingConsent),a())},get initConfiguration(){return s},getInternalContext:W,handleLog(c,d,l,u=t(),f=G()){n.add(p=>p.handleLog(c,d,l,u,f))}}}function Lo(t){return{...t,clientToken:"empty"}}const Pt="logs";function Po(t){const e=_o(),r=Qe("global context",{customerDataTracker:e.getOrCreateTracker(2)}),n=Qe("user",{customerDataTracker:e.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),s=Qe("account",{customerDataTracker:e.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),i=as();function o(){return Co(r,n,s)}let a=Fo(o,i,(l,u)=>{l.storeContextsAcrossPages&&(Lt(u,r,Pt,2),Lt(u,n,Pt,1),Lt(u,s,Pt,4));const f=t(l,u,o,i);return a=Oo(l,f),f});const c={},d=new O((...l)=>a.handleLog(...l),e.createDetachedTracker());return ni({logger:d,init:x(l=>a.init(l)),setTrackingConsent:x(l=>{i.update(l),Ti({feature:"set-tracking-consent",tracking_consent:l})}),getGlobalContext:x(()=>r.getContext()),setGlobalContext:x(l=>r.setContext(l)),setGlobalContextProperty:x((l,u)=>r.setContextProperty(l,u)),removeGlobalContextProperty:x(l=>r.removeContextProperty(l)),clearGlobalContext:x(()=>r.clearContext()),createLogger:x((l,u={})=>(c[l]=new O((...f)=>a.handleLog(...f),e.createDetachedTracker(),z(l),u.handler,u.level,z(u.context)),c[l])),getLogger:x(l=>c[l]),getInitConfiguration:x(()=>kr(a.initConfiguration)),getInternalContext:x(l=>a.getInternalContext(l)),setUser:x(n.setContext),getUser:x(n.getContext),setUserProperty:x(n.setContextProperty),removeUserProperty:x(n.removeContextProperty),clearUser:x(n.clearContext),setAccount:x(s.setContext),getAccount:x(s.getContext),setAccountProperty:x(s.setContextProperty),removeAccountProperty:x(s.removeContextProperty),clearAccount:x(s.clearContext)})}function Oo(t,e){return{init:r=>{wr("DD_LOGS",r)},initConfiguration:t,...e}}const Io="logs";function Mo(t,e){const r=Di(t,Io,n=>No(t,n),e);return{findTrackedSession:(n,s={returnInactive:!1})=>{const i=r.findSession(n,s);return i&&i.trackingType==="1"?{id:i.id,anonymousId:i.anonymousId}:void 0},expireObservable:r.expireObservable}}function Bo(t){const r=Zr(t)==="1"?{}:void 0;return{findTrackedSession:()=>r,expireObservable:new k}}function Zr(t){return Le(t.sessionSampleRate)?"1":"0"}function No(t,e){const r=zo(e)?e:Zr(t);return{trackingType:r,isTracked:r==="1"}}function zo(t){return t==="0"||t==="1"}let Qr=!1;function rt(t){const e=window;if(Xr()){const n=r(e.DD_RUM_SYNTHETICS);return!n&&!Qr&&(Qr=!0,Pr("Logs sent before RUM is injected by the synthetics worker",{testId:xo(),resultId:wo()})),n}return r(e.DD_RUM);function r(n){if(n&&n.getInternalContext)return n.getInternalContext(t)}}function $o(t,e,r,n,s){const i=Ro.concat(["custom"]),o={};i.forEach(a=>{o[a]=Ji(a,e.eventRateLimiterThreshold,s)}),r.subscribe(0,({rawLogsEvent:a,messageContext:c=void 0,savedCommonContext:d=void 0,domainContext:l})=>{var u,f;const p=Sn(a.date),h=t.findTrackedSession(p);if(!t.findTrackedSession(p,{returnInactive:!0}))return;const g=d||n();let S;!be(g.account)&&g.account.id&&(S=g.account),h&&h.anonymousId&&!g.user.anonymous_id&&(g.user.anonymous_id=h.anonymousId);const b=ue({service:e.service,session_id:h?h.id:void 0,session:h?{id:h.id}:void 0,usr:be(g.user)?void 0:g.user,account:S,view:g.view},g.context,rt(p),a,c);((u=e.beforeSend)===null||u===void 0?void 0:u.call(e,b,l))===!1||b.origin!==P.AGENT&&((f=o[b.status])!==null&&f!==void 0?f:o.custom).isLimitReached()||r.notify(1,b)})}const Go={[C.log]:T.info,[C.debug]:T.debug,[C.info]:T.info,[C.warn]:T.warn,[C.error]:T.error};function Vo(t,e){const r=oo(t.forwardConsoleLogs).subscribe(n=>{var s;const i={rawLogsEvent:{date:G(),message:n.message,origin:P.CONSOLE,error:n.error&&tt(n.error),status:Go[n.api]},messageContext:(s=n.error)===null||s===void 0?void 0:s.context,domainContext:{handlingStack:n.handlingStack}};e.notify(0,i)});return{stop:()=>{r.unsubscribe()}}}function Ho(t,e){const r=ii(t,t.forwardReports).subscribe(n=>{let s=n.message,i;const o=n.originalError.type==="deprecation"?T.warn:T.error;o===T.error?i=tt(n):n.stack&&(s+=` Found in ${Qs(n.stack)}`),e.notify(0,{rawLogsEvent:{date:G(),message:s,origin:P.REPORT,error:i,status:o}})});return{stop:()=>{r.unsubscribe()}}}function Wo(t,e){if(!t.forwardErrorsToLogs)return{stop:W};const r=Zi(t).subscribe(i=>{i.state==="complete"&&s("xhr",i)}),n=Yr().subscribe(i=>{i.state==="resolve"&&s("fetch",i)});function s(i,o){!ws(o.url)&&(Xo(o)||Ir(o.status))&&("xhr"in o?jo(o.xhr,t,a):o.response?qo(o.response,t,a):o.error&&Yo(o.error,t,a));function a(c){const d={isAborted:o.isAborted,handlingStack:o.handlingStack};e.notify(0,{rawLogsEvent:{message:`${Ko(i)} error ${o.method} ${o.url}`,date:o.startClocks.timeStamp,error:{stack:c||"Failed to load",handling:void 0},http:{method:o.method,status_code:o.status,url:o.url},status:T.error,origin:P.NETWORK},domainContext:d})}}return{stop:()=>{r.unsubscribe(),n.unsubscribe()}}}function jo(t,e,r){typeof t.response=="string"?r(Ot(t.response,e)):r(t.response)}function Yo(t,e,r){r(Ot(te(N(t)),e))}function qo(t,e,r){const n=Li(t);!n||!n.body?r():window.TextDecoder?Jo(n.body,e.requestErrorResponseLengthLimit,(s,i)=>{r(s?`Unable to retrieve response: ${s}`:i)}):n.text().then(x(s=>r(Ot(s,e))),x(s=>r(`Unable to retrieve response: ${s}`)))}function Xo(t){return t.status===0&&t.responseType!=="opaque"}function Ot(t,e){return t.length>e.requestErrorResponseLengthLimit?`${t.substring(0,e.requestErrorResponseLengthLimit)}...`:t}function Ko(t){return t==="xhr"?"XHR":"Fetch"}function Jo(t,e,r){vo(t,(n,s,i)=>{if(n)r(n);else{let o=new TextDecoder().decode(s);i&&(o+="..."),r(void 0,o)}},{bytesLimit:e,collectStreamBody:!0})}function Zo(t,e){if(!t.forwardErrorsToLogs)return{stop:W};const r=new k,{stop:n}=ei(r),s=r.subscribe(i=>{e.notify(0,{rawLogsEvent:{message:i.message,date:i.startClocks.timeStamp,error:tt(i),origin:P.SOURCE,status:T.error},messageContext:i.context})});return{stop:()=>{n(),s.unsubscribe()}}}const Qo=Ki;function ea(t){function e(r,n,s,i,o){const a=ue(n.getContext(),r.context);if(et(r.status,Ce.console,n)&&ra(r,a),et(r.status,Ce.http,n)){const c={rawLogsEvent:{date:o||G(),message:r.message,status:r.status,origin:P.LOGGER},messageContext:a,savedCommonContext:i};s&&(c.domainContext={handlingStack:s}),t.notify(0,c)}}return{handleLog:e}}const ta={[T.ok]:C.debug,[T.debug]:C.debug,[T.info]:C.info,[T.notice]:C.info,[T.warn]:C.warn,[T.error]:C.error,[T.critical]:C.error,[T.alert]:C.error,[T.emerg]:C.error};function ra({status:t,message:e},r){X[ta[t]].call(M,e,r)}function na(t,e,r,n,s){const i=jr(t,{endpoint:t.logsEndpointBuilder,encoder:Ze()},t.replica&&{endpoint:t.replica.logsEndpointBuilder,encoder:Ze()},r,n,s.expireObservable);return e.subscribe(1,o=>{i.add(o)}),i}function sa(t){const e=Rt();t.subscribe(1,r=>{e.send("log",r)})}function ia(t){return{get:e=>{const r=t.findTrackedSession(e);if(r)return{session_id:r.id}}}}function oa(t){return e=>{t.notify(0,{rawLogsEvent:{message:e.message,date:e.startClocks.timeStamp,origin:P.AGENT,status:T.error}}),Pr("Error reported to customer",{"error.message":e.message})}}function aa(t,e,r,n,s){const i=gi("browser-logs-sdk",e);i.setContextProvider(()=>{var a,c,d,l,u,f;return{application:{id:(a=rt())===null||a===void 0?void 0:a.application_id},session:{id:(c=s.findTrackedSession())===null||c===void 0?void 0:c.id},view:{id:(l=(d=rt())===null||d===void 0?void 0:d.view)===null||l===void 0?void 0:l.id},action:{id:(f=(u=rt())===null||u===void 0?void 0:u.user_action)===null||f===void 0?void 0:f.id}}});const o=[];if(Ke()){const a=Rt(),c=i.observable.subscribe(d=>a.send("internal_telemetry",d));o.push(()=>c.unsubscribe())}else{const a=jr(e,{endpoint:e.rumEndpointBuilder,encoder:Ze()},e.replica&&{endpoint:e.replica.rumEndpointBuilder,encoder:Ze()},r,n,s.expireObservable);o.push(()=>a.stop());const c=i.observable.subscribe(d=>a.add(d,bi(e)));o.push(()=>c.unsubscribe())}return _i(),vi(Uo(t)),{telemetry:i,stop:()=>{o.forEach(a=>a())}}}function ca(t,e,r,n){const s=new Qo,i=[];s.subscribe(1,f=>Cr("logs",f));const o=oa(s),a=ji(e),c=e.sessionStoreStrategyType&&!Ke()&&!Xr()?Mo(e,n):Bo(e),{stop:d}=aa(t,e,o,a,c);i.push(()=>d()),Wo(e,s),Zo(e,s),Vo(e,s),Ho(e,s);const{handleLog:l}=ea(s);if($o(c,e,s,r,o),Ke())sa(s);else{const{stop:f}=na(e,s,o,a,c);i.push(()=>f())}const u=ia(c);return{handleLog:l,getInternalContext:u.get,stop:()=>{i.forEach(f=>f())}}}const fe=Po(ca);si(H(),"DD_LOGS",fe);const y=class y{constructor(e){this.listenerMap=new Map,y.options=e,this.isLoggingOn=e.LOG_TO_DATADOG,this.eventTarget=new EventTarget,this.isLoggingOn&&fe.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!1,sessionSampleRate:100});const r="bb_logger_mac_uuid";let n=localStorage.getItem(r);n||(n=crypto.randomUUID(),localStorage.setItem(r,n)),y.tracking.mac=n,y.tracking.dev=`${e.platform}_${e.browserName}`,y.beatHandle||(y.options&&_(y.options,"Logger")&&console.log("[Logger] Starting tracking beat"),y.beatHandle=window.setInterval(y.flushTracking,15e3))}static setMessagePort(e){this.messagePort=e}static getMessagePort(){return this.messagePort}setLoggingOn(e){this.isLoggingOn=e}addEventListener(e,r){const n=s=>r(s);this.listenerMap.set(r,{eventName:e,wrappedListener:n}),this.eventTarget.addEventListener(e,n)}removeEventListener(e,r){const n=this.listenerMap.get(r);n&&n.eventName===e&&(this.eventTarget.removeEventListener(e,n.wrappedListener),this.listenerMap.delete(r))}removeAllEventListeners(){for(const[e,{eventName:r,wrappedListener:n}]of this.listenerMap)this.eventTarget.removeEventListener(r,n);this.listenerMap.clear()}setAttributes(e){y.processAttributes(e);for(const r in e)fe.logger.setContextProperty(r,e[r])}info(e,r){e==="didClickAd"&&this.emit("mediaSessionDidRegisterClick",{url:(r==null?void 0:r.url)||""}),e==="didToggleGlobalAugmentationDrawing"&&this.emit("mediaSessionDidUpdateGlobalAugmentationState",{isGlobalAugmentationEnabled:(r==null?void 0:r.isEnabled)||!0}),e==="didStartDrawingAugmentationMedia"&&this.emit("mediaSessionDidBeginShotRendering",r),e==="didEndDrawingAugmentationMedia"&&this.emit("mediaSessionDidEndShotRendering",r),e==="didRegisterShot"&&this.emit("mediaSessionDidRegisterShot",r),r&&y.processAttributes(r),this.isLoggingOn&&(fe.logger.info(e,r),y.options&&_(y.options,"Logger")&&console.log("[Logger] Sending info: ",e))}error(e,r){r&&y.processAttributes(r),this.isLoggingOn&&(fe.logger.error(e,r),y.tracking.err_time=Date.now().toFixed(0),y.tracking.err_desc=e+(r?` - ${JSON.stringify(r)}`:""),y.options&&_(y.options,"Logger")&&console.log("[Logger] Sending error: ",e))}warn(e,r){r&&y.processAttributes(r),this.isLoggingOn&&(fe.logger.warn(e,r),y.options&&_(y.options,"Logger")&&console.log("[Logger] Sending warn: ",e))}handleMessageFromWorker(e){e.actionType==="INFO"?this.info(e.message,e.attributes):e.actionType==="ERROR"?this.error(e.message,e.attributes):e.actionType==="WARN"?this.warn(e.message,e.attributes):e.actionType==="SET_ATTRIBUTES"&&e.attributes&&this.setAttributes(e.attributes)}static setAttributes(e){if(!y.messagePort){console.error("[Logger] messagePort is not set! Cannot send attributes.");return}try{y.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:e})}catch(r){console.error("[Logger] Error posting message:",r)}}static info(e,r){y.messagePort.postMessage({type:"LOG",actionType:"INFO",message:e,attributes:r})}static error(e,r){y.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:e,attributes:r})}static warn(e,r){y.messagePort.postMessage({type:"LOG",actionType:"WARN",message:e,attributes:r})}static processAttributes(e){if(e.player_version&&(y.tracking.sdk=e.player_version),e.media_id&&(y.tracking.gid=e.media_id),e.game_id&&(y.tracking.buc=e.game_id),e.bb_session_id&&(y.tracking.sid=e.bb_session_id,y.options&&_(y.options,"Logger")&&console.log("[Logger] Setting bb_session_id:",y.tracking.sid)),e.last_timecode){const n=L.fromStr(e.last_timecode);y.tracking.tc=n.print(),y.lastTimecodeMillis=n.totalMilliseconds(59.94),y.lastTimecodeMillis&&y.lastZipMillis&&(y.tracking.cache=(y.lastZipMillis-y.lastTimecodeMillis).toFixed(0))}e.last_offset&&(y.tracking.off=e.last_offset),e.last_loading_zip&&(y.tracking.zip=e.last_loading_zip+".zip",y.lastZipMillis=L.fromStr(e.last_loading_zip).totalMilliseconds(59.94),y.lastTimecodeMillis&&y.lastZipMillis&&(y.tracking.cache=(y.lastZipMillis-y.lastTimecodeMillis).toFixed(0))),e.last_rendered_frame&&(y.tracking.aug_time=Date.now().toFixed(0)),e.asset&&(y.tracking.asset=e.asset)}static objectToQuery(e){return Object.entries(e).filter(([r,n])=>n!==0&&n!=="").map(([r,n])=>`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`).join("&")}emit(e,r){const n=new CustomEvent(e,{detail:r});this.eventTarget.dispatchEvent(n)}};y.tracking={start:Date.now().toFixed(0),dev:"",sdk:"",mac:"",gid:"",sid:"",off:"",zip:"",aug_time:"",err_time:"",err_desc:"",tc:"",asset:"",cache:"",buc:""},y.lastTimecodeMillis=0,y.lastZipMillis=0,y.flushTracking=()=>{const e=Date.now().toFixed(0);y.tracking.now=e;const n=`https://dwu3k7rrxk5s3.cloudfront.net/metrics/1.gif?${y.objectToQuery(y.tracking)}`;y.options&&_(y.options,"Logger")&&console.log("[Logger] Flushing tracking data:",n),fetch(n,{method:"GET",mode:"no-cors",keepalive:!0,headers:{"X-Platform":"Web"}}).catch(()=>{}),y.tracking.err_desc="",y.tracking.err_time=""};let It=y;const la={env:"prod",urlConfigURL:"https://db8igqxlbvayn.cloudfront.net/url_config.json",gameBaseURL:"https://db8igqxlbvayn.cloudfront.net",zipBaseURL:"https://db8igqxlbvayn.cloudfront.net",adsBaseURL:"https://dwu3k7rrxk5s3.cloudfront.net",LOG_TO_DATADOG:!0,SEND_METRICS:!0,BURNED_TIMECODES_MODE:!1,RENDER_LED:!0,DRAW_TIMESTAMP_WEBGL:!1,ADAPTER_RUN_IN_WORKER:!1,DOWNLOADER_UPDATE_FREQUENCY:1e3,DOWNLOADER_ZIP_START_OFFSET:2,DOWNLOADER_ZIP_END_OFFSET:10,DOWNLOADER_ZIP_LENGTH_SECONDS:2,ZIP_BUFFER_READY_THRESHOLD:5,ZIP_BUFFER_FADEOUT_THRESHOLD:1,BENCHMARK_DURATION_SECONDS:10,DECODER_UPDATE_FREQUENCY:30,DECODER_FRAME_BATCH_SIZE:3,DECODER_LEAD_TIME_MILLIS:180,PERFORMANCE_TRACKING_INTERVAL:1e3,BUCKET_SUBFOLDER_PATH:"manifests/59.94/",debug:{on:!1,showAugmentationStatus:!1,logOTTPlayer:!1,logClocker:!1,logDownloader:!1,logDecoder:!1,logRenderer:!1,logFetcher:!1,logAdapter:!1,logAds:!1,logLogger:!1,logErrors:!1,trackPerformance:!1}},da="https://identity-qa.nba.com/qa/auth";class ua{constructor(e){this.cookies=[],this.xToken=null,this.authInProgress=!1,this.OTTPlayer=e,this.options=e.options,this.logger=e.logger}async fetchNBAToken(e,r){const n=this.options.authIdentityUrl||da;_(this.options,"OTTPlayer")&&console.log(`[CloudFrontAuth] Fetching JWT from: ${n}`);const s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,password:r})});if(!s.ok){const o=await s.text().catch(()=>"");throw new Error(`NBA auth request failed: ${s.status} ${s.statusText} - ${o}`)}const i=await s.json().catch(()=>null);if(!i||!i.data||!i.data.jwt)throw new Error("NBA auth response was invalid or missing JWT token");return i.data.jwt}async loginAndGetCookies(e){try{const r=this.options.authNbaToken,n=this.options.authEmail,s=this.options.authPassword;if(!r&&(!n||!s))return _(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] No credentials or NBA token provided, skipping authentication"),[];const i=this.options.zipBaseURL;if(!i)return console.warn("[CloudFrontAuth] No zipBaseURL configured, cannot authenticate"),[];if(this.lastGameId===e&&this.cookies.length>0)return _(this.options,"OTTPlayer")&&console.log(`[CloudFrontAuth] ✓ Using cached cookies for gameId=${e}`),this.cookies;if(this.authInProgress)return _(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] ⏳ Auth already in progress, waiting..."),await this.waitForAuth(),this.cookies;this.authInProgress=!0,this.lastGameId=e,console.log(`[CloudFrontAuth] 🔐 Starting authentication for gameId=${e}`),console.log(`[CloudFrontAuth] CloudFront URL: ${i}`);let o;r?(o=r,_(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] ✓ Using provided NBA token")):this.xToken?(o=this.xToken,_(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] ✓ Using existing x-token")):(o=await this.fetchNBAToken(n,s),_(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] ✓ Got JWT token from NBA Identity"));const a=`${i}/auth/${encodeURIComponent(e)}`;console.log(`[CloudFrontAuth] Fetching cookies from: ${a}`);const c=await fetch(a,{method:"GET",credentials:"include",headers:{Authorization:`Bearer ${o}`}});if(!c.ok&&c.status!==204)throw new Error(`Failed to fetch cookies: ${c.status} ${c.statusText}`);_(this.options,"OTTPlayer")&&console.log(`[CloudFrontAuth] Auth endpoint status: ${c.status}`);const d=c.headers.get("x-token");d&&(this.xToken=d,_(this.options,"OTTPlayer")&&console.log("[CloudFrontAuth] ✓ Received fresh x-token"));const l=c.headers.get("set-cookie");return l?this.cookies=l.split(",").map(u=>u.trim()):this.cookies=["browser-managed-httponly-cookies"],console.log("[CloudFrontAuth] ✅ Successfully authenticated"),console.log("[CloudFrontAuth] Note: Cookies are HttpOnly and managed by browser automatically"),this.logger.info("didAuthenticateCloudFront",{gameId:e,cookieCount:this.cookies.length,hasXToken:!!this.xToken}),this.scheduleCookieRefresh(e),this.cookies}catch(r){return console.error("[CloudFrontAuth] ❌ Authentication failed:",r),this.logger.error("[CloudFrontAuth] Authentication failed",{error:r.message||r}),this.xToken=null,[]}finally{this.authInProgress=!1}}async waitForAuth(){return new Promise(e=>{const r=setInterval(()=>{this.authInProgress||(clearInterval(r),e())},100)})}scheduleCookieRefresh(e){this.cookieRefreshTimer&&window.clearTimeout(this.cookieRefreshTimer),this.cookieRefreshTimer=window.setTimeout(()=>{_(this.options,"OTTPlayer")&&console.log(`[CloudFrontAuth] Auto-refreshing cookies and x-token for gameId=${e}`),this.loginAndGetCookies(e)},7*60*60*1e3)}getCookies(){return this.cookies}getXToken(){return this.xToken}isAuthenticated(){return this.cookies.length>0}destroy(){this.cookies=[],this.xToken=null,this.lastGameId=void 0,this.cookieRefreshTimer&&(window.clearTimeout(this.cookieRefreshTimer),this.cookieRefreshTimer=void 0)}}class ha{constructor(e){this.groups=new Map,this.isVisible=!0,this.lastFrameTime=0,this.TARGET_FPS=60,this.FRAME_INTERVAL=1e3/this.TARGET_FPS,this.canvas=document.createElement("canvas"),this.canvas.style.position="absolute",this.canvas.style.top="0",this.canvas.style.left="0",this.canvas.style.pointerEvents="none",this.canvas.style.zIndex="3001",this.canvas.width=e.clientWidth,this.canvas.height=e.clientHeight,this.canvas.style.width="100%",this.canvas.style.height="100%",this.ctx=this.canvas.getContext("2d"),e.appendChild(this.canvas),this.initializeGroups(),this.startRenderLoop(),this.setupResizeObserver(e)}initializeGroups(){this.groups.set("support",{title:"Basic Augmentation Support",metrics:new Map([["game_params",{value:!1}],["browser",{value:!1,detail:""}],["pattern",{value:!1,detail:""}],["fps",{value:!1,detail:""}],["mk_ads",{value:!1,detail:""}]])}),this.groups.set("timecode",{title:"TimeCode Status",metrics:new Map([["sync_point",{value:!1,detail:""}],["consistency",{value:!1,detail:""}]])}),this.groups.set("benchmark",{title:"",metrics:new Map([["status",{value:"FAILED",detail:""}]])}),this.groups.set("switches",{title:"Augmentation Switches",metrics:new Map([["killswitch_web",{value:!1}],["killswitch_local",{value:!1}],["isLive",{value:!1}],["render_state",{value:"OFF"}]])}),this.groups.set("data",{title:"Augmentation Data Presence",metrics:new Map([["zip_buffer",{value:!1,detail:"0.0s"}],["stream_data",{value:!1}],["ads",{value:!1}],["render_data",{value:!1}],["alpha_mask",{value:!1}],["placeholders",{value:!1}],["processing_size",{value:!1}]])}),this.groups.set("health",{title:"Player Components Health",metrics:new Map([["decoder",{value:!1,detail:""}],["webgl",{value:!1,detail:""}]])})}updateMetric(e,r,n,s){const i=this.groups.get(e);i&&i.metrics.set(r,{value:n,detail:s})}startRenderLoop(){const e=r=>{r-this.lastFrameTime>=this.FRAME_INTERVAL&&(this.isVisible&&this.draw(),this.lastFrameTime=r),this.animationFrameId=requestAnimationFrame(e)};this.animationFrameId=requestAnimationFrame(e)}setupResizeObserver(e){typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>{this.canvas.width=e.clientWidth,this.canvas.height=e.clientHeight}),this.resizeObserver.observe(e))}draw(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);const e=12,r=e+3,n=10,s=15,i=10;this.ctx.font=`${e}px monospace`,this.ctx.textBaseline="top";let o=i;this.groups.forEach((c,d)=>{var l;if(d==="benchmark"){const u=c.metrics.get("status");if(u){const f=u.value;let p,h;f==="PASSED"?(p="rgba(0,255,136,0.8)",h="STABILITY TEST: PASSED"):f==="TESTING"?(p="rgba(255,170,0,0.8)",h=`STABILITY TEST: TESTING${u.detail?" ("+((l=u.detail.split(":")[1])==null?void 0:l.trim())+")":""}`):(p="rgba(255,51,51,0.8)",h="STABILITY TEST: FAILED"),this.ctx.fillStyle=p,this.ctx.fillRect(i,o,250,20),this.ctx.fillStyle="#000",this.ctx.font=`bold ${e}px monospace`,this.ctx.fillText(h,i+5,o+4),this.ctx.font=`${e}px monospace`,o+=25}return}this.ctx.fillStyle="rgba(0,0,0,0.7)",this.ctx.fillRect(i,o,300,r+2),this.ctx.fillStyle="#fff",this.ctx.font=`bold ${e}px monospace`,this.ctx.fillText(c.title,i+5,o+1),this.ctx.font=`${e}px monospace`,o+=r+4,c.metrics.forEach((u,f)=>{const p=this.getColorForValue(u.value),h=this.formatValue(u.value);this.ctx.fillStyle="rgba(0,0,0,0.5)",this.ctx.fillRect(i+s,o,285-s,r),this.ctx.fillStyle=p,this.ctx.beginPath(),this.ctx.arc(i+s+5,o+r/2,3,0,Math.PI*2),this.ctx.fill(),this.ctx.fillStyle="#fff";const m=f.replace(/_/g," ");this.ctx.fillText(`${m}: ${h}`,i+s+15,o+1),o+=r,u.detail&&(this.ctx.fillStyle="rgba(0,0,0,0.4)",this.ctx.fillRect(i+s,o,285-s,r),this.ctx.fillStyle="#aaa",this.ctx.fillText(` ${u.detail}`,i+s+15,o+1),o+=r)}),o+=n});const a=this.isAugmentationReady();this.ctx.fillStyle=a?"rgba(0,255,136,0.8)":"rgba(255,51,51,0.8)",this.ctx.fillRect(i,o,250,20),this.ctx.fillStyle="#000",this.ctx.font=`bold ${e}px monospace`,this.ctx.fillText(`AUGMENTATION: ${a?"READY":"NOT READY"}`,i+5,o+4),this.ctx.font=`${e}px monospace`}formatValue(e){return typeof e=="boolean"?e?"OK":"NO":e==="PASSED"?"PASSED":e==="TESTING"?"TESTING":e==="FAILED"?"FAILED":e}getColorForValue(e){return typeof e=="boolean"?e?"#00ff88":"#ff3333":e==="ON"||e==="FADE_IN"?"#00ff88":e==="FADE_OUT"?"#ffaa00":e==="PASSED"?"#00ff88":e==="TESTING"?"#ffaa00":"#ff3333"}isAugmentationReady(){var u,f,p,h,m,g,S,b,E,A;const e=this.groups.get("support"),r=this.groups.get("switches"),n=this.groups.get("data"),s=this.groups.get("health"),i=this.groups.get("benchmark");if(!e||!r||!n||!s||!i)return!1;const o=((u=e.metrics.get("game_params"))==null?void 0:u.value)===!0&&((f=e.metrics.get("browser"))==null?void 0:f.value)===!0&&((p=e.metrics.get("pattern"))==null?void 0:p.value)===!0&&((h=e.metrics.get("fps"))==null?void 0:h.value)===!0&&((m=e.metrics.get("mk_ads"))==null?void 0:m.value)===!0,a=((g=r.metrics.get("killswitch_web"))==null?void 0:g.value)===!0&&((S=r.metrics.get("killswitch_local"))==null?void 0:S.value)===!0&&(((b=r.metrics.get("render_state"))==null?void 0:b.value)==="ON"||((E=r.metrics.get("render_state"))==null?void 0:E.value)==="FADE_IN"),c=Array.from(n.metrics.values()).every(w=>w.value===!0),d=Array.from(s.metrics.values()).every(w=>w.value===!0),l=((A=i.metrics.get("status"))==null?void 0:A.value)==="PASSED";return o&&a&&c&&d&&l}toggle(){this.isVisible=!this.isVisible,this.isVisible||this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}pause(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}resume(){this.animationFrameId||this.startRenderLoop()}delete(){this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.resizeObserver&&this.resizeObserver.disconnect(),this.canvas.remove()}}class en{constructor(e,r,n,s){this.RUN_PIXEL_TICKERS=!0,this.pixelTickers=[],this.handleVisibilityChange=()=>{document.hidden?this.onTabHidden():this.onTabVisible()},this.fetchGameParams=async()=>{try{if(_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] GameId: ",this.options.gameId),this.options.OVERRIDE_GAME_PARAMS){_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Using OVERRIDE_GAME_PARAMS from configuration");const d=this.options.OVERRIDE_GAME_PARAMS;if(this.options.BURNED_TIMECODES_MODE){this.gameParams=d;return}if(d.hasOwnProperty("bucketName")&&d.hasOwnProperty("offsets")){if(this.logger.setAttributes({game_id:d.bucketName,customer_name:d.customerName,customer_id:d.customerId}),this.gameParams){const l=JSON.stringify(this.gameParams),u=JSON.stringify(d);l!==u&&this.logger.info("didChangeGameParams",{oldParams:this.gameParams,newParams:d})}else this.logger.info("didFetchGameInfo",d);this.gameParams=d,this.cloudFrontAuth&&d.bucketName&&this.cloudFrontAuth.loginAndGetCookies(d.bucketName).then(()=>{_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] CloudFront authentication completed for bucketName:",d.bucketName)}).catch(l=>{_(this.options,"Errors")&&console.error("[OTTPlayer] CloudFront authentication failed:",l)});return}else throw new Error(`OVERRIDE_GAME_PARAMS for ${this.options.gameId} is missing required properties (bucketName or offsets)`)}let o;const a=`${this.options.gameBaseURL}/${this.options.gameId}.json`;if(_(this.options,"OTTPlayer")&&console.log(`Fetching GameParams from ${a}`),this.options.SEND_METRICS?o=await fetch(a,{headers:{"X-Platform":"Web"},cache:"no-store"}):o=await fetch(a,{cache:"no-store"}),!o.ok){const d=`Unable to fetch game params for ${this.options.gameId}. HTTP error. Status: ${o.status}`;this.logger.error("[OTTPlayer] Failed to fetch game params",{status:o.status,gameId:this.options.gameId}),_(this.options,"Errors")&&console.error(`[OTTPlayer] ${d}`),this.destroy();return}const c=await o.json();if(this.options.BURNED_TIMECODES_MODE){this.gameParams=c;return}if(this.handleOttActions(o,c),c.hasOwnProperty("bucketName")&&c.hasOwnProperty("offsets"))o=c;else throw new Error(`Game params for ${this.options.gameId} not found in JSON`);if(this.logger.setAttributes({game_id:o.bucketName,customer_name:o.customerName,customer_id:o.customerId}),this.gameParams){const d=JSON.stringify(this.gameParams),l=JSON.stringify(o);d!==l&&this.logger.info("didChangeGameParams",{oldParams:this.gameParams,newParams:o})}else this.logger.info("didFetchGameInfo",this.gameParams);this.gameParams=o,this.cloudFrontAuth&&o.bucketName&&this.cloudFrontAuth.loginAndGetCookies(o.bucketName).then(()=>{_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] CloudFront authentication completed for bucketName:",o.bucketName)}).catch(d=>{_(this.options,"Errors")&&console.error("[OTTPlayer] CloudFront authentication failed:",d)})}catch(o){this.logger.error("[OTTPlayer] Error fetching game params",{error:o}),_(this.options,"Errors")&&console.error("[OTTPlayer] Error fetching game params:",o)}this.fetchGameParamsTimeoutId=window.setTimeout(()=>this.fetchGameParams(),1e4)},this.setGameParams=o=>{try{if(_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Overriding game params"),this.fetchGameParamsTimeoutId&&(window.clearTimeout(this.fetchGameParamsTimeoutId),this.fetchGameParamsTimeoutId=void 0),this.options.BURNED_TIMECODES_MODE){this.gameParams=o;return}if(o.hasOwnProperty("bucketName")&&o.hasOwnProperty("offsets")){if(this.logger.setAttributes({game_id:o.bucketName,customer_name:o.customerName,customer_id:o.customerId}),this.gameParams){const a=JSON.stringify(this.gameParams),c=JSON.stringify(o);a!==c&&this.logger.info("didChangeGameParams",{oldParams:this.gameParams,newParams:o})}else this.logger.info("didFetchGameInfo",o);this.gameParams=o,this.cloudFrontAuth&&o.bucketName&&this.cloudFrontAuth.loginAndGetCookies(o.bucketName).then(()=>{_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] CloudFront authentication completed for bucketName:",o.bucketName)}).catch(a=>{_(this.options,"Errors")&&console.error("[OTTPlayer] CloudFront authentication failed:",a)});return}else throw new Error(`Game params for ${this.options.gameId} is missing required properties (bucketName or offsets)`)}catch(a){this.logger.error("[OTTPlayer] Error overriding game params",{error:a}),_(this.options,"Errors")&&console.error("[OTTPlayer] Error overriding game params:",a)}};const i="OTTPlayer_v1.1.1";console.log(`%c${i}`,"font-size: 16px; font-weight: bold; color: blue;"),this.video=e,this.options={...n,...la,platform:I.getCurrentPlatform(),browserName:I.getBrowserName(),augmentation:{channelName:"nba"}},this.options.browserName==="Firefox"&&(this.options.DECODER_LEAD_TIME_MILLIS=300),_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Starting fetchUrlConfig"),this.fetchUrlConfig(s),this.logger=new It(this.options),this.logger.setAttributes({player_version:i,bb_session_id:crypto.randomUUID()}),this.logger.info("didGetConfiguration",{...n,fps:r}),tn(this.options,s).then(()=>{var o;if(this.logger.setAttributes({media_id:this.options.gameId}),window.BB.playerInstances.length>0&&window.BB.playerInstances.forEach(a=>{a.destroy()}),window.BB.workerInstances.length>0&&window.BB.workerInstances.forEach(a=>{a.terminate()}),this.cloudFrontAuth=new ua(this),this.clocker=new dn(this),this.adapter=new it(this),this.ottActions={toggle:{ios:!0,android:!0,web:!0,local:this.options.enabled}},(o=this.options.debug)!=null&&o.showAugmentationStatus){const a=this.options.CANVAS_CONTAINER||this.video.parentElement;a&&(this.statusOverlay=new ha(a))}this.RUN_PIXEL_TICKERS&&(this.pixelTickers=q.createInAllCorners(this.video)),this.applyImageOverridesFromOptions(),this.flushPendingOverrides(),this.fetchGameParams(),window.BB.playerInstances.push(this),document.addEventListener("visibilitychange",this.handleVisibilityChange)})}onNewMetadata(e){!this.adapter||this.options.BURNED_TIMECODES_MODE||this.adapter.onNewMetadata(e)}onNewSegment(e){!this.adapter||this.options.BURNED_TIMECODES_MODE||this.adapter.onNewSegmentForMetadata(e)}onAdEvent(e){console.log(`[OTTPlayer] onAdEvent: ${e}`),!(!this.adapter||this.options.BURNED_TIMECODES_MODE)&&this.adapter.onAdEvent(e)}async fetchUrlConfig(e){try{if(!this.options.urlConfigURL){_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] No urlConfigURL provided, skipping URL config fetch");return}_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Fetching URL config from:",this.options.urlConfigURL);const r=await fetch(this.options.urlConfigURL);if(!r.ok)throw new Error(`Failed to fetch URL config: ${r.status} ${r.statusText}`);const n=await r.json();if(!n||typeof n!="object")throw new Error("Invalid URL config structure: not an object");const s=this.options.env;if(!n[s])throw new Error(`Environment '${s}' not found in URL config`);const i=n[s];if(!i.gameBaseUrl||!i.zipBaseUrl||!i.adsBaseUrl)throw new Error(`Missing required URLs in environment '${s}' config`);e!=null&&e.gameBaseURL||(this.options.gameBaseURL=i.gameBaseUrl),e!=null&&e.zipBaseURL||(this.options.zipBaseURL=i.zipBaseUrl),e!=null&&e.adsBaseURL||(this.options.adsBaseURL=i.adsBaseUrl),_(this.options,"OTTPlayer")&&(console.log("[OTTPlayer] URL config loaded successfully for environment:",s),console.log("[OTTPlayer] Updated URLs:",{gameBaseURL:this.options.gameBaseURL,zipBaseURL:this.options.zipBaseURL,adsBaseURL:this.options.adsBaseURL}))}catch(r){_(this.options,"OTTPlayer")&&(console.warn("[OTTPlayer] Failed to fetch URL config:",r),console.log("[OTTPlayer] Using default URLs from options"))}}handleOttActions(e,r){if(!this.clocker||this.options.BURNED_TIMECODES_MODE)return;const n=e.headers.get("x-tgi-ott-actions");let s;if(n?s=JSON.parse(n):s={toggle:{ios:!0,android:!0,web:!0}},!this.ottActions||this.ottActions.toggle.web!==s.toggle.web||s.toggle[r.customerId]!==void 0&&(this.ottActions.toggle[r.customerId]===void 0||this.ottActions.toggle[r.customerId]!==s.toggle[r.customerId])||s.toggle[r.customerId]===void 0&&this.ottActions.toggle[r.customerId]!==void 0){const o=s.toggle[r.customerId]!==void 0?s.toggle[r.customerId]&&s.toggle.web:s.toggle.web;this.ottActions&&this.logger.info("didToggleGlobalAugmentationDrawing",{isEnabled:o}),s.toggle.local=this.options.enabled,this.ottActions=s,console.warn("[OTTPlayer] ottActions",s)}}toggle(e){this.options.enabled=e,this.ottActions&&(this.ottActions.toggle.local=e,this.logger.info("didToggleGlobalAugmentationDrawing",{isEnabled:e}))}setFps(e){this.fps=e}setMediaInfo(e){e.fps&&this.setFps(e.fps),e.bitrate&&(this.bitrate=e.bitrate)}setAd(e,r){if(e===void 0){if(!this.clocker){this.pendingAdBlob=void 0,this.pendingAdBitmap=void 0,this.pendingAdPlaceholder=void 0;return}this.clocker.resetAds();return}if(typeof e=="string"){let n;try{n=new URL(e,document.baseURI).toString()}catch(s){_(this.options,"Errors")&&console.error("[OTTPlayer] Invalid ad URL passed to setAd",e,s);return}fetch(n,{cache:"no-store"}).then(s=>s.blob()).then(async s=>{if(!this.clocker){this.pendingAdBlob=s,this.pendingAdPlaceholder=r;return}this.clocker.setAdBlob(s,r)}).catch(s=>{_(this.options,"Errors")&&console.error("[OTTPlayer] Failed to fetch ad image from URL in setAd",n,s)});return}if(!this.clocker){if(e instanceof Blob)this.pendingAdBlob=e;else{if(this.pendingAdBitmap)try{this.pendingAdBitmap.close()}catch{}this.pendingAdBitmap=e}this.pendingAdPlaceholder=r;return}if(e instanceof Blob){this.clocker.setAdBlob(e,r);return}else this.clocker.setAdImage(e,r)}setLED(e){if(typeof e=="string"){let r;try{r=new URL(e,document.baseURI).toString()}catch(n){_(this.options,"Errors")&&console.error("[OTTPlayer] Invalid LED URL passed to setLED",e,n);return}fetch(r,{cache:"no-store"}).then(n=>n.blob()).then(n=>{if(!this.clocker){this.pendingLEDBlob=n;return}this.clocker.setLEDBlob(n)}).catch(n=>{_(this.options,"Errors")&&console.error("[OTTPlayer] Failed to fetch LED image from URL in setLED",r,n)});return}if(!this.clocker){if(e instanceof Blob)this.pendingLEDBlob=e;else{if(this.pendingLEDBitmap)try{this.pendingLEDBitmap.close()}catch{}this.pendingLEDBitmap=e}return}e instanceof Blob?this.clocker.setLEDBlob(e):this.clocker.setLEDImage(e)}async applyImageOverridesFromOptions(){try{const e=[];this.options.OVERRIDE_AD&&e.push(this.applySingleOverride(this.options.OVERRIDE_AD,"ad")),this.options.OVERRIDE_LED&&e.push(this.applySingleOverride(this.options.OVERRIDE_LED,"led")),await Promise.all(e)}catch(e){_(this.options,"Errors")&&console.error("[OTTPlayer] Failed to apply image overrides",e)}}async applySingleOverride(e,r){let n;if(typeof e=="string")try{const s=new URL(e,document.baseURI).toString();n=await(await fetch(s,{cache:"no-store"})).blob()}catch(s){_(this.options,"Errors")&&console.error(`[OTTPlayer] Failed to fetch override ${r} from URL`,e,s);return}else n=e;if(n){if(!this.clocker){r==="ad"?this.pendingAdBlob=n:this.pendingLEDBlob=n;return}r==="ad"?this.clocker.setAdBlob(n):this.clocker.setLEDBlob(n)}}flushPendingOverrides(){if(this.clocker){if(this.pendingAdBitmap){const e=this.pendingAdBitmap;this.pendingAdBitmap=void 0,this.clocker.setAdImage(e,this.pendingAdPlaceholder),this.pendingAdPlaceholder=void 0}else if(this.pendingAdBlob){const e=this.pendingAdBlob;this.pendingAdBlob=void 0,this.clocker.setAdBlob(e,this.pendingAdPlaceholder),this.pendingAdPlaceholder=void 0}if(this.pendingLEDBitmap){const e=this.pendingLEDBitmap;this.pendingLEDBitmap=void 0,this.clocker.setLEDImage(e)}else if(this.pendingLEDBlob){const e=this.pendingLEDBlob;this.pendingLEDBlob=void 0,this.clocker.setLEDBlob(e)}}}onTabHidden(){var e,r,n;_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Tab hidden - pausing all components"),this.fetchGameParamsTimeoutId&&(window.clearTimeout(this.fetchGameParamsTimeoutId),this.fetchGameParamsTimeoutId=void 0),(e=this.clocker)==null||e.pause(),(r=this.adapter)==null||r.pause(),(n=this.statusOverlay)==null||n.pause()}onTabVisible(){var e,r,n;_(this.options,"OTTPlayer")&&console.log("[OTTPlayer] Tab visible - resuming all components"),(e=this.clocker)==null||e.resume(),(r=this.adapter)==null||r.resume(),(n=this.statusOverlay)==null||n.resume(),this.fetchGameParams()}on(e,r){this.logger.addEventListener(e,r)}off(e,r){this.logger.removeEventListener(e,r)}destroy(){var r;document.removeEventListener("visibilitychange",this.handleVisibilityChange),this.fetchGameParamsTimeoutId&&(window.clearTimeout(this.fetchGameParamsTimeoutId),this.fetchGameParamsTimeoutId=void 0),(r=this.clocker)==null||r.delete(),this.clocker=void 0,this.adapter&&(this.adapter.delete(),this.adapter=void 0),this.cloudFrontAuth&&(this.cloudFrontAuth.destroy(),this.cloudFrontAuth=void 0),this.statusOverlay&&(this.statusOverlay.delete(),this.statusOverlay=void 0),q.deleteAll(this.pixelTickers),this.pixelTickers=[],this.logger.removeAllEventListeners();const e=window.BB.playerInstances.indexOf(this);e>=0&&window.BB.playerInstances.splice(e,1)}}return window.BB={OTTPlayer:en,playerInstances:[],workerInstances:[]},en});
|