@brandbrigade/ott-bb-player 1.0.61 → 1.0.63

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/OTTPlayer.js CHANGED
@@ -1,7 +1,7 @@
1
- (function(he,pe){typeof exports=="object"&&typeof module<"u"?module.exports=pe():typeof define=="function"&&define.amd?define(pe):(he=typeof globalThis<"u"?globalThis:he||self,he.OTTPlayer=pe())})(this,function(){"use strict";const he=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,pe=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 n=e-this.lastTimestamp;return this.lastTimestamp=e,this.addFrameDuration(n)}calculateAverage(){if(this.frameDurations.length===0)return 0;const n=this.frameDurations.reduce((o,a)=>o+a,0)/this.frameDurations.length,r=this.frameDurations.filter(o=>Math.abs(o-n)<=n*.2);return r.reduce((o,a)=>o+a,0)/r.length||n}getFPS(){const e=this.calculateAverage();if(e===0)return 0;const n=1/e;return pe(n)}getPerciseFPS(){const e=this.calculateAverage();return e===0?0:1/e}}const U=class U{constructor(e,n,r,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 l=this.h,u=this.m,d=this.s,f=this.f,p=this.field;const h=l*60+u,g=(h-Math.floor(h/10))*c;return l*(a*3600)+u*(a*60)+d*a+(f*2+p)-g},this.addSeconds=o=>{let a=this.copy();return a.s+=o,a.s>=60&&(a.s=0,a.m++,a.m>=60&&(a.m=0,a.h++)),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=n||0,this.s=r||0,this.f=s||0,this.field=i||0}static compare(e,n){return e.h!==n.h?e.h<n.h?-1:1:e.m!==n.m?e.m<n.m?-1:1:e.s!==n.s?e.s<n.s?-1:1:e.f!==n.f?e.f<n.f?-1:1:e.field!==n.field?e.field<n.field?-1:1:0}static generateTimecodeRange(e,n,r){const s=[];let i=e;for(;U.compare(i,n)<=0;)s.push(i),i=i.addSeconds(r);return s}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(e){return this.toFrames(e)*1e3/e}};U.calculateCurrentTimeCode=e=>{var d;if(!e.video||!e.clocker||!e.gameParams)throw new Error("OTTPlayer is not initialized");const n=e.video,r=e.clocker,s=r.videoFPScalculator.getFPS(),a=(n.currentTime-r.syncPoint.playerTime)%(60*60*24)*s+r.syncPoint.frame;if(a===0||s===0)throw new Error("Current frame is 0 or fps is 0");const c=U.calculateCurrentOffset(a,(d=e.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),U.fromFrames(l,s)},U.calculateCurrentOffset=(e,n)=>{for(let r=1;r<n.length;r++)if(e<n[r].frame)return n[r-1].offset;return n[n.length-1].offset},U.fromFrames=(e,n)=>{let r=60,s=0;Math.floor(n)==60?(r=60,s=0):Math.floor(n)==59?(r=60,s=4):Math.floor(n)==30?(r=30,s=0):Math.floor(n)==29&&(r=30,s=2);let i=Math.floor(n*60),o=Math.floor(n*60*10),a=o*6,c=e,l=Math.floor(c/a);c-=l*a;let u=Math.floor(c/o);c-=u*o,c>=r*60&&(c+=s*(Math.floor((c-r*60)/i)+1));let d=Math.floor(c/(r*60));c-=d*(r*60);let f=Math.floor(c/r);c-=f*r;let p=c;d+=u*10;let h=0;return h=p%2,p=Math.floor(p/2),new U(l,d,f,p,h)},U.toStr=e=>{const n="_";let r=("0"+e.h).slice(-2)+n+("0"+e.m).slice(-2)+n+("0"+e.s).slice(-2)+n+("0"+e.f).slice(-2);return e.field&&(r+="_1"),r},U.fromStr=e=>{const r=e.split("_").map(Number);if(r.length==4){const[s,i,o,a]=r;return new U(s,i,o,a,0)}else if(r.length==5){const[s,i,o,a,c]=r;return new U(s,i,o,a,c)}else throw new Error("Invalid timecode format: "+e)},U.fromMetadata=e=>{const n=/^(\d{2}):(\d{2}):(\d{2}):(\d{2})(?:\.(\d))?$/,r=e.timecode.match(n);if(!r)throw new Error("Invalid timecode format: "+e.timecode);const[,s,i,o,a,c]=r,l=Number(s),u=Number(i),d=Number(o),f=Number(a),p=c?Number(c):0;return new U(l,u,d,f,p)};let O=U;const Qn=async t=>{let e;typeof document>"u"?e=new URL(self.location.href):e=new URL(document.location.href);const n=e.searchParams.get("config");if(n){const s=await(await fetch(n)).json();Object.assign(t,s)}},L=(t,e)=>!t.debug||!t.debug.on?!1:t.debug[`log${e}`];class er{constructor(e){this.last10=[],this.errorsInProgress=[],this.lastFrameTC=null,this.fps=e}setFPS(e){this.fps=e}timecodeRecieved(e){if(!e)return;const n=O.fromStr(e);if(this.last10.push(n),this.last10.length>10&&this.last10.shift(),this.lastFrameTC){const r=this.incrementInterlaced(this.lastFrameTC);O.compare(n,r)!==0&&(console.warn("Timecode sequence is invalid! Detected at:",e),this.errorsInProgress.push({preTCs:[...this.last10],postTCs:[],framesAfter:0,printed:!1}))}for(const r of this.errorsInProgress)r.printed||(r.postTCs.push(n),r.framesAfter++);for(const r of this.errorsInProgress)if(!r.printed&&r.framesAfter>=10){console.error("Full 20-frame sequence around error:");const s=[...r.preTCs,...r.postTCs];console.error(s.map(i=>O.toStr(i))),r.printed=!0}this.lastFrameTC=n}incrementInterlaced(e){const n=e.copy();return n.field===0?(n.field=1,n):(n.field=0,n.f++,n.f>=30&&(n.f=0,n.s++,n.s>=60&&(n.s=0,n.m++,n.m>=60&&(n.m=0,n.h++))),n)}}class tr{constructor(e,n){this.click=async r=>{const s=this.video.getBoundingClientRect(),i=(r.clientX-s.left)/s.width,o=(r.clientY-s.top)/s.height,a={x:i,y:o};this.renderer.postMessage({type:"VIDEO_CLICK",clickData:a})},this.video=e,this.renderer=n,this.renderer.onmessage=r=>{if(r.data.type==="OPEN_URL"){const s=r.data.url;s&&window.open(s,"_blank")}}}}const It='(function(){"use strict";const C=(e,t)=>!e.debug||!e.debug.on?!1:e.debug[`log${t}`],E={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},L=console,G={};Object.keys(E).forEach(e=>{G[e]=L[e]});const ue="Datadog Browser SDK:",_={debug:G.debug.bind(L,ue),log:G.log.bind(L,ue),info:G.info.bind(L,ue),warn:G.warn.bind(L,ue),error:G.error.bind(L,ue)},Ye="https://docs.datadoghq.com",Rt=`${Ye}/real_user_monitoring/browser/troubleshooting`,we="More details:";function Ct(e,t){return(...n)=>{try{return e(...n)}catch(r){_.error(t,r)}}}function Oe(e){return e!==0&&Math.random()*100<=e}function Pn(e){return $n(e)&&e>=0&&e<=100}function $n(e){return typeof e=="number"}const le=1e3,j=60*le,vt=60*j,Un=365*(24*vt);function de(){return new Date().getTime()}function N(){return de()}function Re(){return performance.now()}function M(){return{relative:Re(),timeStamp:N()}}function Bn(){return{relative:0,timeStamp:It()}}function Fn(e,t){return t-e}function Gn(e,t){return e+t}function jn(e){return e-It()}let Ve;function It(){return Ve===void 0&&(Ve=performance.timing.navigationStart),Ve}const A=1024,Lt=1024*A,Hn=/[^\\u0000-\\u007F]/;function Xe(e){return Hn.test(e)?window.TextEncoder!==void 0?new TextEncoder().encode(e).length:new Blob([e]).size:e.length}function zn(e){return{...e}}function At(e,t){return Object.keys(e).some(n=>e[n]===t)}function fe(e){return Object.keys(e).length===0}function P(){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 X(e,t){const n=P();let r;return n.Zone&&typeof n.Zone.__symbol__=="function"&&(r=e[n.Zone.__symbol__(t)]),r||(r=e[t]),r}let Ce,xt=!1;function Jn(e){Ce=e}function Kn(e){xt=e}function Wn(e,t,n){const r=n.value;n.value=function(...o){return(Ce?b(r):r).apply(this,o)}}function b(e){return function(){return pe(e,this,arguments)}}function pe(e,t,n){try{return e.apply(t,n)}catch(r){qn(r)}}function qn(e){if(Ze(e),Ce)try{Ce(e)}catch(t){Ze(t)}}function Ze(...e){xt&&_.error("[MONITOR]",...e)}function he(e,t){return X(P(),"setTimeout")(b(e),t)}function kt(e){X(P(),"clearTimeout")(e)}function Qe(e,t){return X(P(),"setInterval")(b(e),t)}function Dt(e){X(P(),"clearInterval")(e)}class T{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 Nt(...e){return new T(t=>{const n=e.map(r=>r.subscribe(o=>t.notify(o)));return()=>n.forEach(r=>r.unsubscribe())})}function Mt(e,t,n){let r=!1,o,s;return{throttled:(...i)=>{if(r){o=i;return}e(...i),r=!0,s=he(()=>{o&&e(...o),r=!1,o=void 0},t)},cancel:()=>{kt(s),r=!1,o=void 0}}}function $(){}function U(e){return e?(parseInt(e,10)^Math.random()*16>>parseInt(e,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,U)}const ve=/([\\w-]+)\\s*=\\s*([^;]+)/g;function Yn(e,t){for(ve.lastIndex=0;;){const n=ve.exec(e);if(n){if(n[1]===t)return n[2]}else break}}function Vn(e){const t=new Map;for(ve.lastIndex=0;;){const n=ve.exec(e);if(n)t.set(n[1],n[2]);else break}return t}function Xn(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 Zn(){return Qn()===0}let Ie;function Qn(){return Ie??(Ie=er())}function er(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 ge(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",c=r&&r.domain?`;domain=${r.domain}`:"",a=r&&r.secure?";secure":"",l=r&&r.partitioned?";partitioned":"";document.cookie=`${e}=${t};${s};path=/;samesite=${i}${c}${a}${l}`}function et(e){return Yn(document.cookie,e)}let tt;function H(e){return tt||(tt=Vn(document.cookie)),tt.get(e)}function Pt(e,t){ge(e,"",0,t)}function tr(e){if(document.cookie===void 0||document.cookie===null)return!1;try{const t=`dd_cookie_test_${U()}`,n="test";ge(t,n,j,e);const r=et(t)===n;return Pt(t,e),r}catch(t){return _.error(t),!1}}let nt;function nr(){if(nt===void 0){const e=`dd_site_test_${U()}`,t="test",n=window.location.hostname.split(".");let r=n.pop();for(;n.length&&!et(e);)r=`${n.pop()}.${r}`,ge(e,t,le,{domain:r});Pt(e,{domain:r}),nt=r}return nt}const Z="_dd_s";function Le(e){return Object.values(e)}function rr(e){return Object.entries(e)}const rt=4*vt,$t=15*j,or=Un,me={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},Ut=/^([a-zA-Z]+)=([a-z0-9-]+)$/,ot="&";function sr(e){return!!e&&(e.indexOf(ot)!==-1||Ut.test(e))}const ir="1";function z(e,t){const n={isExpired:ir};return t.trackAnonymousUser&&(e!=null&&e.anonymousId?n.anonymousId=e==null?void 0:e.anonymousId:n.anonymousId=U()),n}function Ae(e){return fe(e)}function Bt(e){return!Ae(e)}function xe(e){return e.isExpired!==void 0||!cr(e)}function cr(e){return(e.created===void 0||de()-Number(e.created)<rt)&&(e.expire===void 0||de()<Number(e.expire))}function Ft(e){e.expire=String(de()+$t)}function st(e){return rr(e).map(([t,n])=>t==="anonymousId"?`aid=${n}`:`${t}=${n}`).join(ot)}function Gt(e){const t={};return sr(e)&&e.split(ot).forEach(n=>{const r=Ut.exec(n);if(r!==null){const[,o,s]=r;o==="aid"?t.anonymousId=s:t[o]=s}}),t}const ar="_dd",ur="_dd_r",lr="_dd_l",dr="rum",fr="logs";function pr(e){if(!H(Z)){const n=H(ar),r=H(ur),o=H(lr),s={};n&&(s.id=n),o&&/^[01]$/.test(o)&&(s[fr]=o),r&&/^[012]$/.test(r)&&(s[dr]=r),Bt(s)&&(Ft(s),e.persistSession(s))}}function jt(e){const t=Sr(e);return tr(t)?{type:me.COOKIE,cookieOptions:t}:void 0}function hr(e,t){const n={isLockEnabled:Zn(),persistSession:gr(t),retrieveSession:br,expireSession:r=>mr(t,r,e)};return pr(n),n}function gr(e){return t=>{ge(Z,st(t),$t,e)}}function mr(e,t,n){const r=z(t,n);ge(Z,st(r),n.trackAnonymousUser?or:rt,e)}function br(){const e=et(Z);return Gt(e)}function Sr(e){const t={};return t.secure=!!e.useSecureSessionCookie||!!e.usePartitionedCrossSiteSessionCookie,t.crossSite=!!e.usePartitionedCrossSiteSessionCookie,t.partitioned=!!e.usePartitionedCrossSiteSessionCookie,e.trackSessionAcrossSubdomains&&(t.domain=nr()),t}const yr="_dd_test_";function Ht(){try{const e=U(),t=`${yr}${e}`;localStorage.setItem(t,e);const n=localStorage.getItem(t);return localStorage.removeItem(t),e===n?{type:me.LOCAL_STORAGE}:void 0}catch{return}}function Er(e){return{isLockEnabled:!1,persistSession:zt,retrieveSession:_r,expireSession:t=>Tr(t,e)}}function zt(e){localStorage.setItem(Z,st(e))}function _r(){const e=localStorage.getItem(Z);return Gt(e)}function Tr(e,t){zt(z(e,t))}const wr=10,Or=100,Jt=[];let ke;function J(e,t,n=0){var r;const{isLockEnabled:o,persistSession:s,expireSession:i}=t,c=f=>s({...f,lock:l}),a=()=>{const f=t.retrieveSession(),h=f.lock;return f.lock&&delete f.lock,{session:f,lock:h}};if(ke||(ke=e),e!==ke){Jt.push(e);return}if(o&&n>=Or){Kt(t);return}let l,u=a();if(o){if(u.lock){De(e,t,n);return}if(l=U(),c(u.session),u=a(),u.lock!==l){De(e,t,n);return}}let d=e.process(u.session);if(o&&(u=a(),u.lock!==l)){De(e,t,n);return}if(d&&(xe(d)?i(d):(Ft(d),o?c(d):s(d))),o&&!(d&&xe(d))){if(u=a(),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),Kt(t)}function De(e,t,n){he(()=>{J(e,t,n+1)},wr)}function Kt(e){ke=void 0;const t=Jt.shift();t&&J(t,e)}const Wt=le;function Rr(e){switch(e.sessionPersistence){case me.COOKIE:return jt(e);case me.LOCAL_STORAGE:return Ht();case void 0:{let t=jt(e);return!t&&e.allowFallbackToLocalStorage&&(t=Ht()),t}default:_.error(`Invalid session persistence \'${String(e.sessionPersistence)}\'`)}}function Cr(e,t,n,r){const o=new T,s=new T,i=new T,c=e.type===me.COOKIE?hr(t,e.cookieOptions):Er(t),{expireSession:a}=c,l=Qe(p,Wt);let u;y();const{throttled:d,cancel:f}=Mt(()=>{J({process:m=>{if(Ae(m))return;const ae=S(m);return Te(ae),ae},after:m=>{Bt(m)&&!F()&&Di(m),u=m}},c)},Wt);function h(){J({process:m=>F()?S(m):void 0},c)}function p(){J({process:m=>xe(m)?z(m,t):void 0,after:S},c)}function S(m){return xe(m)&&(m=z(m,t)),F()&&(xi(m)?ki():(i.notify({previousState:u,newState:m}),u=m)),m}function y(){J({process:m=>{if(Ae(m))return z(m,t)},after:m=>{u=m}},c)}function Te(m){if(Ae(m))return!1;const{trackingType:ae,isTracked:Mi}=r(m[n]);m[n]=ae,delete m.isExpired,Mi&&!m.id&&(m.id=U(),m.created=String(de()))}function F(){return u[n]!==void 0}function xi(m){return u.id!==m.id||u[n]!==m[n]}function ki(){u=z(u,t),s.notify()}function Di(m){u=m,o.notify()}function Ni(m){J({process:ae=>({...ae,...m}),after:S},c)}return{expandOrRenewSession:d,expandSession:h,getSession:()=>u,renewObservable:o,expireObservable:s,sessionStateUpdateObservable:i,restartSession:y,expire:()=>{f(),a(u),S(z(u,t))},stop:()=>{Dt(l)},updateSessionState:Ni}}const it={GRANTED:"granted",NOT_GRANTED:"not-granted"};function vr(e){const t=new T;return{tryToInit(n){e||(e=n)},update(n){e=n,t.notify()},isGranted(){return e===it.GRANTED},observable:t}}function K(e,t,n){if(typeof e!="object"||e===null)return JSON.stringify(e);const r=Q(Object.prototype),o=Q(Array.prototype),s=Q(Object.getPrototypeOf(e)),i=Q(e);try{return JSON.stringify(e,t,n)}catch{return"<error: unable to serialize object>"}finally{r(),o(),s(),i()}}function Q(e){const t=e,n=t.toJSON;return n?(delete t.toJSON,()=>{t.toJSON=n}):$}function ct(e){return Ir(e,location.href).href}function Ir(e,t){const n=Lr();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)} ${K({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 qt=URL;let Ne;function Lr(){if(Ne===void 0)try{Ne=new qt("http://test/path").href==="http://test/path"}catch{Ne=!1}return Ne?qt:void 0}const Ar="datad0g.com",xr="dd0g-gov.com",ee="datadoghq.com",kr="ddog-gov.com",Dr="pci.browser-intake-datadoghq.com",Nr=["ddsource","ddtags"];function be(e,t,n){const r=Mr(e,t);return{build(o,s){const i=$r(e,t,n,o,s);return r(i)},urlPrefix:r(""),trackType:t}}function Mr(e,t){const n=`/api/v2/${t}`,r=e.proxy;if(typeof r=="string"){const s=ct(r);return i=>`${s}?ddforward=${encodeURIComponent(`${n}?${i}`)}`}if(typeof r=="function")return s=>r({path:n,parameters:s});const o=Pr(t,e);return s=>`https://${o}${n}?${s}`}function Pr(e,t){const{site:n=ee,internalAnalyticsSubdomain:r}=t;if(e==="logs"&&t.usePciIntake&&n===ee)return Dr;if(r&&n===ee)return`${r}.${ee}`;if(n===xr)return`http-intake.logs.${n}`;const o=n.split("."),s=o.pop();return`browser-intake-${o.join("-")}.${s}`}function $r({clientToken:e,internalAnalyticsSubdomain:t},n,r,o,{retry:s,encoding:i}){const c=["sdk_version:6.5.0",`api:${o}`].concat(r);s&&c.push(`retry_count:${s.count}`,`retry_after:${s.lastFailureStatus}`);const a=["ddsource=browser",`ddtags=${encodeURIComponent(c.join(","))}`,`dd-api-key=${e}`,`dd-evp-origin-version=${encodeURIComponent("6.5.0")}`,"dd-evp-origin=browser",`dd-request-id=${U()}`];return i&&a.push(`dd-evp-encoding=${i}`),n==="rum"&&a.push(`batch_time=${N()}`),t&&a.reverse(),a.join("&")}const Ur=200;function Br(e){const{env:t,service:n,version:r,datacenter:o}=e,s=[];return t&&s.push(Me("env",t)),n&&s.push(Me("service",n)),r&&s.push(Me("version",r)),o&&s.push(Me("datacenter",o)),s}function Me(e,t){const n=Ur-e.length-1;(t.length>n||Fr(t))&&_.warn(`${e} value doesn\'t meet tag requirements and will be sanitized. ${we} ${Ye}/getting_started/tagging/#defining-tags`);const r=t.replace(/,/g,"_");return`${e}:${r}`}function Fr(e){return Gr()?new RegExp("[^\\\\p{Ll}\\\\p{Lo}0-9_:./-]","u").test(e):!1}function Gr(){try{return new RegExp("[\\\\p{Ll}]","u"),!0}catch{return!1}}function jr(e){const t=e.site||ee,n=Br(e),r=Hr(e,n);return{replica:zr(e,n),site:t,...r}}function Hr(e,t){return{logsEndpointBuilder:be(e,"logs",t),rumEndpointBuilder:be(e,"rum",t),sessionReplayEndpointBuilder:be(e,"replay",t)}}function zr(e,t){if(!e.replica)return;const n={...e,site:ee,clientToken:e.replica.clientToken},r={logsEndpointBuilder:be(n,"logs",t),rumEndpointBuilder:be(n,"rum",t)};return{applicationId:e.replica.applicationId,...r}}function Jr(e){return Nr.every(t=>e.includes(t))}function at(e,t){return e!=null&&typeof e!="string"?(_.error(`${t} must be defined as a string`),!1):!0}function Kr(e){return e&&typeof e=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(e)?(_.error(`Site should be a valid Datadog site. ${we} ${Ye}/getting_started/site/.`),!1):!0}function Pe(e,t){return e!==void 0&&!Pn(e)?(_.error(`${t} Sample Rate should be a number between 0 and 100`),!1):!0}function Wr(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(!(!Kr(e.site)||!Pe(e.sessionSampleRate,"Session")||!Pe(e.telemetrySampleRate,"Telemetry")||!Pe(e.telemetryConfigurationSampleRate,"Telemetry Configuration")||!Pe(e.telemetryUsageSampleRate,"Telemetry Usage")||!at(e.version,"Version")||!at(e.env,"Env")||!at(e.service,"Service"))){if(e.trackingConsent!==void 0&&!At(it,e.trackingConsent)){_.error(\'Tracking Consent should be either "granted" or "not-granted"\');return}return{beforeSend:e.beforeSend&&Ct(e.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:Rr(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:it.GRANTED,trackAnonymousUser:(i=e.trackAnonymousUser)!==null&&i!==void 0?i:!0,storeContextsAcrossPages:!!e.storeContextsAcrossPages,batchBytesLimit:16*A,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*le,batchMessagesLimit:50,messageBytesLimit:256*A,...jr(e)}}}function qr(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 ut;(function(e){e.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",e.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(ut||(ut={}));const Yt=new Set;function Yr(e){Array.isArray(e)&&Vr(e.filter(t=>At(ut,t)))}function Vr(e){e.forEach(t=>{Yt.add(t)})}function Xr(){return Yt}const Se="?";function x(e){const t=[];let n=lt(e,"stack");const r=String(e);return n&&n.startsWith(r)&&(n=n.slice(r.length)),n&&n.split(`\n`).forEach(o=>{const s=eo(o)||no(o)||oo(o)||co(o);s&&(!s.func&&s.line&&(s.func=Se),t.push(s))}),{message:lt(e,"message"),name:lt(e,"name"),stack:t}}const Vt="((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\\\w+\\\\.|\\\\/).*?)",te="(?::(\\\\d+))",Zr=new RegExp(`^\\\\s*at (.*?) ?\\\\(${Vt}${te}?${te}?\\\\)?\\\\s*$`,"i"),Qr=new RegExp(`\\\\((\\\\S*)${te}${te}\\\\)`);function eo(e){const t=Zr.exec(e);if(!t)return;const n=t[2]&&t[2].indexOf("native")===0,r=t[2]&&t[2].indexOf("eval")===0,o=Qr.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]||Se,line:t[3]?+t[3]:void 0,url:n?void 0:t[2]}}const to=new RegExp(`^\\\\s*at ?${Vt}${te}?${te}??\\\\s*$`,"i");function no(e){const t=to.exec(e);if(t)return{args:[],column:t[3]?+t[3]:void 0,func:Se,line:t[2]?+t[2]:void 0,url:t[1]}}const ro=/^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;function oo(e){const t=ro.exec(e);if(t)return{args:[],column:t[4]?+t[4]:void 0,func:t[1]||Se,line:+t[3],url:t[2]}}const so=/^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i,io=/(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;function co(e){const t=so.exec(e);if(!t)return;const n=t[3]&&t[3].indexOf(" > eval")>-1,r=io.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]||Se,line:t[4]?+t[4]:void 0,url:t[3]}}function lt(e,t){if(typeof e!="object"||!e||!(t in e))return;const n=e[t];return typeof n=="string"?n:void 0}function ao(e,t,n,r){const o=[{url:t,column:r,line:n}],{name:s,message:i}=lo(e);return{name:s,message:i,stack:o}}const uo=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\\s\\S]*)$/;function lo(e){let t,n;return{}.toString.call(e)==="[object String]"&&([,t,n]=uo.exec(e)),{name:t,message:n}}function $e(e){const n=new Error(e);n.name="HandlingStack";let r;return pe(()=>{const o=x(n);o.stack=o.stack.slice(2),r=W(o)}),r}function W(e){let t=Xt(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 Xt(e){return`${e.name||"Error"}: ${e.message}`}function q(e,t,n,{computeHandlingStack:r}={}){let o=e[t];if(typeof o!="function")if(t in e&&t.startsWith("on"))o=$;else return{stop:$};let s=!1;const i=function(){if(s)return o.apply(this,arguments);const c=Array.from(arguments);let a;pe(n,null,[{target:this,parameters:c,onPostCall:u=>{a=u},handlingStack:r?$e("instrumented method"):void 0}]);const l=o.apply(this,c);return a&&pe(a,null,[l]),l};return e[t]=i,{stop:()=>{s=!0,e[t]===i&&(e[t]=o)}}}const fo=220*A,po="$",ho=3;function k(e,t=fo){const n=Q(Object.prototype),r=Q(Array.prototype),o=[],s=new WeakMap,i=dt(e,po,void 0,o,s),c=JSON.stringify(i);let a=c?c.length:0;if(a>t){pt(t,"discarded",e);return}for(;o.length>0&&a<t;){const l=o.shift();let u=0;if(Array.isArray(l.source))for(let d=0;d<l.source.length;d++){const f=dt(l.source[d],l.path,d,o,s);if(f!==void 0?a+=JSON.stringify(f).length:a+=4,a+=u,u=1,a>t){pt(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=dt(l.source[d],l.path,d,o,s);if(f!==void 0&&(a+=JSON.stringify(f).length+u+d.length+ho,u=1),a>t){pt(t,"truncated",e);break}l.target[d]=f}}return n(),r(),i}function dt(e,t,n,r,o){const s=bo(e);if(!s||typeof s!="object")return go(s);const i=ft(s);if(i!=="[Object]"&&i!=="[Array]"&&i!=="[Error]")return i;const c=e;if(o.has(c))return`[Reference seen at ${o.get(c)}]`;const a=n!==void 0?`${t}.${n}`:t,l=Array.isArray(s)?[]:{};return o.set(c,a),r.push({source:s,target:l,path:a}),l}function go(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 ft(e){try{if(e instanceof Event)return mo(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 mo(e){return{type:e.type,isTrusted:e.isTrusted,currentTarget:e.currentTarget?ft(e.currentTarget):null,target:e.target?ft(e.target):null}}function bo(e){const t=e;if(t&&typeof t.toJSON=="function")try{return t.toJSON()}catch{}return e}function pt(e,t,n){_.warn(`The data provided has been ${t} as it is over the limit of ${e} characters:`,n)}const Zt="No stack, consider using an instance of Error";function Qt({stackTrace:e,originalError:t,handlingStack:n,componentStack:r,startClocks:o,nonErrorPrefix:s,source:i,handling:c}){const a=B(t),l=So(e,a,s,t),u=yo(a,e)?W(e):Zt,d=a?nn(t,i):void 0,f=e?e.name:void 0,h=en(t),p=tn(t);return{startClocks:o,source:i,handling:c,handlingStack:n,componentStack:r,originalError:t,type:f,message:l,stack:u,causes:d,fingerprint:h,context:p}}function So(e,t,n,r){return e!=null&&e.message&&(e!=null&&e.name)?e.message:t?"Empty message":`${n} ${K(k(r))}`}function yo(e,t){return t===void 0?!1:e?!0:t.stack.length>0&&(t.stack.length>1||t.stack[0].url!==void 0)}function en(e){return B(e)&&"dd_fingerprint"in e?String(e.dd_fingerprint):void 0}function tn(e){if(e!==null&&typeof e=="object"&&"dd_context"in e)return e.dd_context}function Eo(e){var t;return(t=/@ (.+)/.exec(e))===null||t===void 0?void 0:t[1]}function B(e){return e instanceof Error||Object.prototype.toString.call(e)==="[object Error]"}function nn(e,t){let n=e;const r=[];for(;B(n==null?void 0:n.cause)&&r.length<10;){const o=x(n.cause);r.push({message:n.cause.message,source:t,type:o==null?void 0:o.name,stack:W(o)}),n=n.cause}return r.length?r:void 0}const v={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function _o(e){const t=(o,s)=>{const i=Qt({stackTrace:o,originalError:s,startClocks:M(),nonErrorPrefix:"Uncaught",source:v.SOURCE,handling:"unhandled"});e.notify(i)},{stop:n}=To(t),{stop:r}=wo(t);return{stop:()=>{n(),r()}}}function To(e){return q(window,"onerror",({parameters:[t,n,r,o,s]})=>{let i;B(s)?i=x(s):i=ao(t,n,r,o),e(i,s??t)})}function wo(e){return q(window,"onunhandledrejection",({parameters:[t]})=>{const n=t.reason||"Empty reason",r=x(n);e(r,n)})}function Oo(e){const t={version:"6.5.0",onReady(n){n()},...e};return Object.defineProperty(t,"_setDebug",{get(){return Kn},enumerable:!1}),t}function Ro(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=>Ct(o,"onReady callback threw an error:")())}function rn(e,t){t.silentMultipleInit||_.error(`${e} is already initialized.`)}function Y(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 c=b(f=>{!f.isTrusted&&!f.__ddIsTrusted&&!e.allowUntrustedEvents||(o&&d(),r(f))}),a=i?{capture:s,passive:i}:s,l=window.EventTarget&&t instanceof EventTarget?window.EventTarget.prototype:t,u=X(l,"addEventListener");n.forEach(f=>u.call(t,f,c,a));function d(){const f=X(l,"removeEventListener");n.forEach(h=>f.call(t,h,c,a))}return{stop:d}}const Ue={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function Co(e,t){const n=[];t.includes(Ue.cspViolation)&&n.push(Io(e));const r=t.filter(o=>o!==Ue.cspViolation);return r.length&&n.push(vo(r)),Nt(...n)}function vo(e){return new T(t=>{if(!window.ReportingObserver)return;const n=b((o,s)=>o.forEach(i=>t.notify(Lo(i)))),r=new window.ReportingObserver(n,{types:e,buffered:!0});return r.observe(),()=>{r.disconnect()}})}function Io(e){return new T(t=>{const{stop:n}=Y(e,document,"securitypolicyviolation",r=>{t.notify(Ao(r))});return n})}function Lo(e){const{type:t,body:n}=e;return on({type:n.id,message:`${t}: ${n.message}`,originalError:e,stack:sn(n.id,n.message,n.sourceFile,n.lineNumber,n.columnNumber)})}function Ao(e){const t=`\'${e.blockedURI}\' blocked by \'${e.effectiveDirective}\' directive`;return on({type:e.effectiveDirective,message:`${Ue.cspViolation}: ${t}`,originalError:e,csp:{disposition:e.disposition},stack:sn(e.effectiveDirective,e.originalPolicy?`${t} of the policy "${Xn(e.originalPolicy,100,"...")}"`:"no policy",e.sourceFile,e.lineNumber,e.columnNumber)})}function on(e){return{startClocks:M(),source:v.REPORT,handling:"unhandled",...e}}function sn(e,t,n,r,o){return n?W({name:e,message:t,stack:[{func:"?",url:n,line:r??void 0,column:o??void 0}]}):void 0}function cn(e,t){const n=window.__ddBrowserSdkExtensionCallback;n&&n({type:e,payload:t})}function an(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Be(e,t,n=xo()){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]=Be(o[s],t[s],n);return o}const r=an(e)==="object"?e:{};for(const o in t)Object.prototype.hasOwnProperty.call(t,o)&&(r[o]=Be(r[o],t[o],n));return r}function un(e){return Be(void 0,e)}function ne(...e){let t;for(const n of e)n!=null&&(t=Be(t,n));return t}function xo(){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 ko(){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 Do(e){const t=new Set;return e.forEach(n=>t.add(n)),Array.from(t)}function ln(e,t){const n=e.indexOf(t);n>=0&&e.splice(n,1)}const No=500;function dn(){const e=[];return{add:o=>{e.push(o)>No&&e.splice(0,1)},remove:o=>{ln(e,o)},drain:o=>{e.forEach(s=>s(o)),e.length=0}}}const V={log:"log",configuration:"configuration",usage:"usage"},Mo=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],Po=[kr];let fn=dn(),re=e=>{fn.add(()=>re(e))};function $o(e,t){let n;const r=new T,o=new Set,s=!Po.includes(t.site)&&Oe(t.telemetrySampleRate),i={[V.log]:s,[V.configuration]:s&&Oe(t.telemetryConfigurationSampleRate),[V.usage]:s&&Oe(t.telemetryUsageSampleRate)},c=Uo();re=l=>{const u=K(l);if(i[l.type]&&o.size<t.maxTelemetryEventsPerPage&&!o.has(u)){const d=a(e,l,c);r.notify(d),cn("telemetry",d),o.add(u)}},Jn(hn);function a(l,u,d){return ne({type:"telemetry",date:N(),service:l,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:ne(u,{runtime_env:d,connectivity:ko(),sdk_setup:"npm"}),experimental_features:Array.from(Xr())},n!==void 0?n():{})}return{setContextProvider:l=>{n=l},observable:r,enabled:s}}function Uo(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function Bo(){fn.drain()}function Fo(e){return e.site===Ar}function pn(e,t){Ze(E.debug,e,t),re({type:V.log,message:e,status:"debug",...t})}function hn(e,t){re({type:V.log,status:"error",...Ho(e),...t})}function Go(e){re({type:V.configuration,configuration:e})}function jo(e){re({type:V.usage,usage:e})}function Ho(e){if(B(e)){const t=x(e);return{error:{kind:t.name,stack:W(zo(t))},message:t.message}}return{error:{stack:Zt},message:`Uncaught ${K(e)}`}}function zo(e){return e.stack=e.stack.filter(t=>!t.url||Mo.some(n=>t.url.startsWith(n))),e}const ye=1/0,Jo=j;let Ee=null;const Fe=new Set;function Ko(){Fe.forEach(e=>e())}function Wo({expireDelay:e,maxEntries:t}){let n=[];const r=[];Ee||(Ee=Qe(()=>Ko(),Jo));const o=()=>{const h=Re()-e;for(;n.length>0&&n[n.length-1].endTime<h;){const p=n.pop();p&&r.push(p.startTime)}};Fe.add(o);function s(h,p){const S={value:h,startTime:p,endTime:ye,remove:()=>{ln(n,S)},close:y=>{S.endTime=y}};return t&&n.length>=t&&n.pop(),n.unshift(S),S}function i(h=ye,p={returnInactive:!1}){for(const S of n)if(S.startTime<=h){if(p.returnInactive||h<=S.endTime)return S.value;break}}function c(h){const p=n[0];p&&p.endTime===ye&&p.close(h)}function a(h=ye,p=0){const S=Gn(h,p);return n.filter(y=>y.startTime<=S&&h<=y.endTime).map(y=>y.value)}function l(){return n.map(({startTime:h,endTime:p,value:S})=>({startTime:h,endTime:p===ye?"Infinity":p,value:S}))}function u(){return r}function d(){n=[]}function f(){Fe.delete(o),Fe.size===0&&Ee&&(Dt(Ee),Ee=null)}return{add:s,find:i,closeActive:c,findAll:a,reset:d,stop:f,getAllEntries:l,getDeletedEntries:u}}const qo=j,Yo=rt;function Vo(e,t,n,r){const o=new T,s=new T,i=Cr(e.sessionStoreStrategyType,e,t,n),c=Wo({expireDelay:Yo});i.renewObservable.subscribe(()=>{c.add(a(),Re()),o.notify()}),i.expireObservable.subscribe(()=>{s.notify(),c.closeActive(Re())}),i.expandOrRenewSession(),c.add(a(),Bn().relative),r.observable.subscribe(()=>{r.isGranted()?i.expandOrRenewSession():i.expire()}),Xo(e,()=>{r.isGranted()&&i.expandOrRenewSession()}),Zo(e,()=>i.expandSession()),Qo(e,()=>i.restartSession());function a(){return{id:i.getSession().id,trackingType:i.getSession()[t],isReplayForced:!!i.getSession().forcedReplay,anonymousId:i.getSession().anonymousId}}return{findSession:(l,u)=>c.find(l,u),renewObservable:o,expireObservable:s,sessionStateUpdateObservable:i.sessionStateUpdateObservable,expire:i.expire,updateSessionState:i.updateSessionState}}function Xo(e,t){ht(e,window,["click","touchstart","keydown","scroll"],t,{capture:!0,passive:!0})}function Zo(e,t){const n=()=>{document.visibilityState==="visible"&&t()};Y(e,document,"visibilitychange",n),Qe(n,qo)}function Qo(e,t){Y(e,window,"resume",t,{capture:!0})}function gn(e){return e>=500}function es(e){try{return e.clone()}catch{return}}const ts=80*A,ns=32,mn=3*Lt,rs=j,bn=le;function Sn(e,t,n,r,o){t.transportStatus===0&&t.queuedPayloads.size()===0&&t.bandwidthMonitor.canHandle(e)?En(e,t,n,{onSuccess:()=>_n(0,t,n,r,o),onFailure:()=>{t.queuedPayloads.enqueue(e),yn(t,n,r,o)}}):t.queuedPayloads.enqueue(e)}function yn(e,t,n,r){e.transportStatus===2&&he(()=>{const o=e.queuedPayloads.first();En(o,e,t,{onSuccess:()=>{e.queuedPayloads.dequeue(),e.currentBackoffTime=bn,_n(1,e,t,n,r)},onFailure:()=>{e.currentBackoffTime=Math.min(rs,e.currentBackoffTime*2),yn(e,t,n,r)}})},e.currentBackoffTime)}function En(e,t,n,{onSuccess:r,onFailure:o}){t.bandwidthMonitor.add(e),n(e,s=>{t.bandwidthMonitor.remove(e),os(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 _n(e,t,n,r,o){e===0&&t.queuedPayloads.isFull()&&!t.queueFullReported&&(o({message:`Reached max ${r} events size queued for upload: ${mn/Lt}MiB`,source:v.AGENT,startClocks:M()}),t.queueFullReported=!0);const s=t.queuedPayloads;for(t.queuedPayloads=Tn();s.size()>0;)Sn(s.dequeue(),t,n,r,o)}function os(e){return e.type!=="opaque"&&(e.status===0&&!navigator.onLine||e.status===408||e.status===429||gn(e.status))}function ss(){return{transportStatus:0,currentBackoffTime:bn,bandwidthMonitor:is(),queuedPayloads:Tn(),queueFullReported:!1}}function Tn(){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>=mn}}}function is(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(e){return this.ongoingRequestCount===0||this.ongoingByteCount+e.bytesCount<=ts&&this.ongoingRequestCount<ns},add(e){this.ongoingRequestCount+=1,this.ongoingByteCount+=e.bytesCount},remove(e){this.ongoingRequestCount-=1,this.ongoingByteCount-=e.bytesCount}}}function cs(e,t,n){const r=ss(),o=(s,i)=>ls(e,t,s,i);return{send:s=>{Sn(s,r,o,e.trackType,n)},sendOnExit:s=>{as(e,t,s)}}}function as(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){us(s)}const o=e.build("xhr",n);gt(o,n.data)}let wn=!1;function us(e){wn||(wn=!0,hn(e))}function ls(e,t,n,r){if(ds()&&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);gt(i,n.data,r)}))}else{const s=e.build("xhr",n);gt(s,n.data,r)}}function ds(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function gt(e,t,n){const r=new XMLHttpRequest;r.open("POST",e,!0),t instanceof Blob&&r.setRequestHeader("Content-Type",t.type),Y({allowUntrustedEvents:!0},r,"loadend",()=>{n==null||n({status:r.status})},{once:!0}),r.send(t)}function mt(){const e=fs();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 Ge(e){var t;e===void 0&&(e=(t=P().location)===null||t===void 0?void 0:t.hostname);const n=mt();return!!n&&n.getAllowedWebViewHosts().some(r=>e===r||e.endsWith(`.${r}`))}function fs(){return P().DatadogEventBridge}const je={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function ps(e){return new T(t=>{const{stop:n}=ht(e,window,["visibilitychange","freeze"],o=>{o.type==="visibilitychange"&&document.visibilityState==="hidden"?t.notify({reason:je.HIDDEN}):o.type==="freeze"&&t.notify({reason:je.FROZEN})},{capture:!0}),r=Y(e,window,"beforeunload",()=>{t.notify({reason:je.UNLOADING})}).stop;return()=>{n(),r()}})}function hs(e){return Le(je).includes(e)}function gs({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}`,p=>{n.notifyAfterAddMessage(p-f)})}function c(d){return d!==void 0&&o[d]!==void 0}function a(d){const f=o[d];delete o[d];const h=e.estimateEncodedBytesCount(f);n.notifyAfterRemoveMessage(h)}function l(d,f){const h=K(d),p=e.estimateEncodedBytesCount(h);if(p>=r){_.warn(`Discarded a message whose size was bigger than the maximum allowed size ${r}KB. ${we} ${Rt}/#technical-limitations`);return}c(f)&&a(f),i(h,p,f)}function u(d){const f=Le(o).join(`\n`);o={};const h=hs(d.reason),p=h?t.sendOnExit:t.send;if(h&&e.isAsync){const S=e.finishSync();S.outputBytesCount&&p(On(S));const y=[S.pendingData,f].filter(Boolean).join(`\n`);y&&p({data:y,bytesCount:Xe(y)})}else f&&e.write(e.isEmpty?f:`\n${f}`),e.finish(S=>{p(On(S))})}return{flushController:n,add:l,upsert:l,stop:s.unsubscribe}}function On(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 ms({messagesLimit:e,bytesLimit:t,durationLimit:n,pageExitObservable:r,sessionExpireObservable:o}){const s=r.subscribe(p=>u(p.reason)),i=o.subscribe(()=>u("session_expire")),c=new T(()=>()=>{s.unsubscribe(),i.unsubscribe()});let a=0,l=0;function u(p){if(l===0)return;const S=l,y=a;l=0,a=0,h(),c.notify({reason:p,messagesCount:S,bytesCount:y})}let d;function f(){d===void 0&&(d=he(()=>{u("duration_limit")},n))}function h(){kt(d),d=void 0}return{flushObservable:c,get messagesCount(){return l},notifyBeforeAddMessage(p){a+p>=t&&u("bytes_limit"),l+=1,a+=p,f()},notifyAfterAddMessage(p=0){a+=p,l>=e?u("messages_limit"):a>=t&&u("bytes_limit")},notifyAfterRemoveMessage(p){a-=p,l-=1,l===0&&h()}}}function Rn(e,t,n,r,o,s,i=gs){const c=l(e,t),a=n&&l(e,n);function l(u,{endpoint:d,encoder:f}){return i({encoder:f,request:cs(d,u.batchBytesLimit,r),flushController:ms({messagesLimit:u.batchMessagesLimit,bytesLimit:u.batchBytesLimit,durationLimit:u.flushTimeout,pageExitObservable:o,sessionExpireObservable:s}),messageBytesLimit:u.messageBytesLimit})}return{flushObservable:c.flushController.flushObservable,add(u,d=!0){c.add(u),a&&d&&a.add(n.transformMessage?n.transformMessage(u):u)},upsert:(u,d)=>{c.upsert(u,d),a&&a.upsert(n.transformMessage?n.transformMessage(u):u,d)},stop:()=>{c.stop(),a&&a.stop()}}}function He(){let e="",t=0;return{isAsync:!1,get isEmpty(){return!e},write(n,r){const o=Xe(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 Ss(e,t,n){let r=0,o=!1;return{isLimitReached(){if(r===0&&he(()=>{r=0},j),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:v.AGENT,startClocks:M()})}finally{o=!1}}return!0}}}let bt;const St=new WeakMap;function ys(e){return bt||(bt=Es(e)),bt}function Es(e){return new T(t=>{const{stop:n}=q(XMLHttpRequest.prototype,"open",_s),{stop:r}=q(XMLHttpRequest.prototype,"send",s=>{Ts(s,e,t)},{computeHandlingStack:!0}),{stop:o}=q(XMLHttpRequest.prototype,"abort",ws);return()=>{n(),r(),o()}})}function _s({target:e,parameters:[t,n]}){St.set(e,{state:"open",method:String(t).toUpperCase(),url:ct(String(n))})}function Ts({target:e,handlingStack:t},n,r){const o=St.get(e);if(!o)return;const s=o;s.state="start",s.startClocks=M(),s.isAborted=!1,s.xhr=e,s.handlingStack=t;let i=!1;const{stop:c}=q(e,"onreadystatechange",()=>{e.readyState===XMLHttpRequest.DONE&&a()}),a=()=>{if(l(),c(),i)return;i=!0;const u=o;u.state="complete",u.duration=Fn(s.startClocks.timeStamp,N()),u.status=e.status,r.notify(zn(u))},{stop:l}=Y(n,e,"loadend",a);r.notify(s)}function ws({target:e}){const t=St.get(e);t&&(t.isAborted=!0)}let yt;function Cn(){return yt||(yt=Os()),yt}function Os(){return new T(e=>{if(!window.fetch)return;const{stop:t}=q(window,"fetch",n=>Rs(n,e),{computeHandlingStack:!0});return t})}function Rs({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 c=i!==void 0?String(i).toUpperCase():"GET",a=o instanceof Request?o.url:ct(String(o)),l=M(),u={state:"start",init:s,input:o,method:c,startClocks:l,url:a,handlingStack:n};r.notify(u),e[0]=u.input,e[1]=u.init,t(d=>Cs(r,d,u))}function Cs(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,c;o({status:0,isAborted:((c=(i=r.init)===null||i===void 0?void 0:i.signal)===null||c===void 0?void 0:c.aborted)||s instanceof DOMException&&s.code===DOMException.ABORT_ERR,error:s})}))}let Et={};function vs(e){const t=e.map(n=>(Et[n]||(Et[n]=Is(n)),Et[n]));return Nt(...t)}function Is(e){return new T(t=>{const n=L[e];return L[e]=(...r)=>{n.apply(console,r);const o=$e("console error");pe(()=>{t.notify(Ls(r,e,o))})},()=>{L[e]=n}})}function Ls(e,t,n){const r=e.map(s=>As(s)).join(" ");let o;if(t===E.error){const s=e.find(B);o={stack:s?W(x(s)):void 0,fingerprint:en(s),causes:s?nn(s,"console"):void 0,startClocks:M(),message:r,source:v.CONSOLE,handling:"handled",handlingStack:n,context:tn(s)}}return{api:t,message:r,error:o,handlingStack:n}}function As(e){return typeof e=="string"?k(e):B(e)?Xt(x(e)):K(k(e),void 0,2)}function xs(e){const t=an(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 ze(e="",{customerDataTracker:t,propertiesConfig:n={}}={}){let r={};const o=new T,s={getContext:()=>un(r),setContext:i=>{xs(i)?(r=k(_t(i,n,e)),t==null||t.updateCustomerData(r)):s.clearContext(),o.notify()},setContextProperty:(i,c)=>{r=k(_t({...r,[i]:c},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 ks="_dd_c",Ds=[];function Tt(e,t,n,r){const o=Ns(n,r);Ds.push(Y(e,window,"storage",({key:l})=>{o===l&&i()})),t.changeObservable.subscribe(c);const s=ne(a(),t.getContext());fe(s)||t.setContext(s);function i(){t.setContext(a())}function c(){localStorage.setItem(o,JSON.stringify(t.getContext()))}function a(){const l=localStorage.getItem(o);return l?JSON.parse(l):{}}}function Ns(e,t){return`${ks}_${e}_${t}`}const Ms=3*A,Ps=16*A,$s=200;function Us(e=2){const t=new Map;let n=!1;function r(o=0){if(n||e===0)return;const s=e===2?Ms:Ps;let i=o;t.forEach(c=>{i+=c.getBytesCount()}),i>s&&(Bs(s),n=!0)}return{createDetachedTracker:()=>{const o=vn(()=>r(o.getBytesCount()));return o},getOrCreateTracker:o=>(t.has(o)||t.set(o,vn(r)),t.get(o)),setCompressionStatus:o=>{e===0&&(e=o,r())},getCompressionStatus:()=>e,stop:()=>{t.forEach(o=>o.stop()),t.clear()}}}function vn(e){let t=0;const{throttled:n,cancel:r}=Mt(s=>{t=Xe(K(s)),e()},$s),o=()=>{r(),t=0};return{updateCustomerData:s=>{fe(s)?o():n(s)},resetCustomerData:o,getBytesCount:()=>t,stop:()=>{r()}}}function Bs(e){_.warn(`Customer data exceeds the recommended ${e/A}KiB threshold. ${we} ${Rt}/#customer-data-exceeds-the-recommended-threshold-warning`)}function Fs(e,t,n){const r=e.getReader(),o=[];let s=0;i();function i(){r.read().then(b(a=>{if(a.done){c();return}o.push(a.value),s+=a.value.length,s>n.bytesLimit?c():i()}),b(a=>t(a)))}function c(){r.cancel().catch($);let a,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})}a=u.slice(0,n.bytesLimit),l=u.length>n.bytesLimit}t(void 0,a,l)}}const Gs="datadog-synthetics-public-id",js="datadog-synthetics-result-id",Hs="datadog-synthetics-injects-rum";function In(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||H(Hs))}function zs(){const e=window._DATADOG_SYNTHETICS_PUBLIC_ID||H(Gs);return typeof e=="string"?e:void 0}function Js(){const e=window._DATADOG_SYNTHETICS_RESULT_ID||H(js);return typeof e=="string"?e:void 0}function Je(e,t,n){const r=n.getHandler(),o=Array.isArray(r)?r:[r];return Ln[e]>=Ln[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"},Ln={[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 Ke(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 Ks=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 c=e.length-1;c>=0;c--)(i=e[c])&&(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 _e={console:"console",http:"http",silent:"silent"},Ws=Object.keys(g);let I=class{constructor(t,n,r,o=_e.http,s=g.debug,i={}){this.handleLogStrategy=t,this.handlerType=o,this.level=s,this.contextManager=ze("logger",{customerDataTracker:n}),this.contextManager.setContext(i),r&&this.contextManager.setContextProperty("logger",{name:r})}logImplementation(t,n,r=g.info,o,s){const i=k(n);let c;if(o!=null){const a=Qt({stackTrace:B(o)?x(o):void 0,originalError:o,nonErrorPrefix:"Provided",source:v.LOGGER,handling:"handled",startClocks:M()});c=ne({error:Ke(a,{includeMessage:!0})},i)}else c=i;this.handleLogStrategy({message:k(t),context:c,status:r},this,s)}log(t,n,r=g.info,o){let s;Je(r,_e.http,this)&&(s=$e("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}};Ks([Wn],I.prototype,"logImplementation",null),I.prototype.ok=D(g.ok),I.prototype.debug=D(g.debug),I.prototype.info=D(g.info),I.prototype.notice=D(g.notice),I.prototype.warn=D(g.warn),I.prototype.error=D(g.error),I.prototype.critical=D(g.critical),I.prototype.alert=D(g.alert),I.prototype.emerg=D(g.emerg);function D(e){return function(t,n,r){let o;Je(e,_e.http,this)&&(o=$e("log")),this.logImplementation(t,n,e,r,o)}}function qs(e,t,n){return{view:{referrer:document.referrer,url:window.location.href},context:e.getContext(),user:t.getContext(),account:n.getContext()}}const Ys=32*A;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=Wr(e),n=An(e.forwardConsoleLogs,Le(E),"Forward Console Logs"),r=An(e.forwardReports,Le(Ue),"Forward Reports");if(!(!t||!n||!r))return e.forwardErrorsToLogs&&!n.includes(E.error)&&n.push(E.error),{forwardErrorsToLogs:e.forwardErrorsToLogs!==!1,forwardConsoleLogs:n,forwardReports:r,requestErrorResponseLengthLimit:Ys,...t}}function An(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:Do(e)}function Xs(e){const t=qr(e);return{forward_errors_to_logs:e.forwardErrorsToLogs,forward_console_logs:e.forwardConsoleLogs,forward_reports:e.forwardReports,use_pci_intake:e.usePciIntake,...t}}function Zs(e,t,n){const r=dn();let o,s;const i=t.observable.subscribe(c);function c(){if(!s||!o||!t.isGranted())return;i.unsubscribe();const a=n(o,s);r.drain(a)}return{init(a){if(!a){_.error("Missing configuration");return}if(Yr(a.enableExperimentalFeatures),Ge()&&(a=Qs(a)),o=a,s){rn("DD_LOGS",a);return}const l=Vs(a);l&&(s=l,Cn().subscribe($),t.tryToInit(l.trackingConsent),c())},get initConfiguration(){return o},getInternalContext:$,handleLog(a,l,u,d=e(),f=N()){r.add(h=>h.handleLog(a,l,u,d,f))}}}function Qs(e){return{...e,clientToken:"empty"}}const wt="logs";function ei(e){const t=Us(),n=ze("global context",{customerDataTracker:t.getOrCreateTracker(2)}),r=ze("user",{customerDataTracker:t.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),o=ze("account",{customerDataTracker:t.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),s=vr();function i(){return qs(n,r,o)}let c=Zs(i,s,(u,d)=>{u.storeContextsAcrossPages&&(Tt(d,n,wt,2),Tt(d,r,wt,1),Tt(d,o,wt,4));const f=e(u,d,i,s);return c=ti(u,f),f});const a={},l=new I((...u)=>c.handleLog(...u),t.createDetachedTracker());return Oo({logger:l,init:b(u=>c.init(u)),setTrackingConsent:b(u=>{s.update(u),jo({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={})=>(a[u]=new I((...f)=>c.handleLog(...f),t.createDetachedTracker(),k(u),d.handler,d.level,k(d.context)),a[u])),getLogger:b(u=>a[u]),getInitConfiguration:b(()=>un(c.initConfiguration)),getInternalContext:b(u=>c.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 ti(e,t){return{init:n=>{rn("DD_LOGS",n)},initConfiguration:e,...t}}const ni="logs";function ri(e,t){const n=Vo(e,ni,r=>si(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 oi(e){const n=xn(e)==="1"?{}:void 0;return{findTrackedSession:()=>n,expireObservable:new T}}function xn(e){return Oe(e.sessionSampleRate)?"1":"0"}function si(e,t){const n=ii(t)?t:xn(e);return{trackingType:n,isTracked:n==="1"}}function ii(e){return e==="0"||e==="1"}let kn=!1;function We(e){const t=window;if(In()){const r=n(t.DD_RUM_SYNTHETICS);return!r&&!kn&&(kn=!0,pn("Logs sent before RUM is injected by the synthetics worker",{testId:zs(),resultId:Js()})),r}return n(t.DD_RUM);function n(r){if(r&&r.getInternalContext)return r.getInternalContext(e)}}function ci(e,t,n,r,o){const s=Ws.concat(["custom"]),i={};s.forEach(c=>{i[c]=Ss(c,t.eventRateLimiterThreshold,o)}),n.subscribe(0,({rawLogsEvent:c,messageContext:a=void 0,savedCommonContext:l=void 0,domainContext:u})=>{var d,f;const h=jn(c.date),p=e.findTrackedSession(h);if(!e.findTrackedSession(h,{returnInactive:!0}))return;const y=l||r();let Te;!fe(y.account)&&y.account.id&&(Te=y.account),p&&p.anonymousId&&!y.user.anonymous_id&&(y.user.anonymous_id=p.anonymousId);const F=ne({service:t.service,session_id:p?p.id:void 0,session:p?{id:p.id}:void 0,usr:fe(y.user)?void 0:y.user,account:Te,view:y.view},y.context,We(h),c,a);((d=t.beforeSend)===null||d===void 0?void 0:d.call(t,F,u))===!1||F.origin!==v.AGENT&&((f=i[F.status])!==null&&f!==void 0?f:i.custom).isLimitReached()||n.notify(1,F)})}const ai={[E.log]:g.info,[E.debug]:g.debug,[E.info]:g.info,[E.warn]:g.warn,[E.error]:g.error};function ui(e,t){const n=vs(e.forwardConsoleLogs).subscribe(r=>{var o;const s={rawLogsEvent:{date:N(),message:r.message,origin:v.CONSOLE,error:r.error&&Ke(r.error),status:ai[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 li(e,t){const n=Co(e,e.forwardReports).subscribe(r=>{let o=r.message,s;const i=r.originalError.type==="deprecation"?g.warn:g.error;i===g.error?s=Ke(r):r.stack&&(o+=` Found in ${Eo(r.stack)}`),t.notify(0,{rawLogsEvent:{date:N(),message:o,origin:v.REPORT,error:s,status:i}})});return{stop:()=>{n.unsubscribe()}}}function di(e,t){if(!e.forwardErrorsToLogs)return{stop:$};const n=ys(e).subscribe(s=>{s.state==="complete"&&o("xhr",s)}),r=Cn().subscribe(s=>{s.state==="resolve"&&o("fetch",s)});function o(s,i){!Jr(i.url)&&(gi(i)||gn(i.status))&&("xhr"in i?fi(i.xhr,e,c):i.response?hi(i.response,e,c):i.error&&pi(i.error,e,c));function c(a){const l={isAborted:i.isAborted,handlingStack:i.handlingStack};t.notify(0,{rawLogsEvent:{message:`${mi(s)} error ${i.method} ${i.url}`,date:i.startClocks.timeStamp,error:{stack:a||"Failed to load",handling:void 0},http:{method:i.method,status_code:i.status,url:i.url},status:g.error,origin:v.NETWORK},domainContext:l})}}return{stop:()=>{n.unsubscribe(),r.unsubscribe()}}}function fi(e,t,n){typeof e.response=="string"?n(Ot(e.response,t)):n(e.response)}function pi(e,t,n){n(Ot(W(x(e)),t))}function hi(e,t,n){const r=es(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(b(o=>n(Ot(o,t))),b(o=>n(`Unable to retrieve response: ${o}`)))}function gi(e){return e.status===0&&e.responseType!=="opaque"}function Ot(e,t){return e.length>t.requestErrorResponseLengthLimit?`${e.substring(0,t.requestErrorResponseLengthLimit)}...`:e}function mi(e){return e==="xhr"?"XHR":"Fetch"}function bi(e,t,n){Fs(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 Si(e,t){if(!e.forwardErrorsToLogs)return{stop:$};const n=new T,{stop:r}=_o(n),o=n.subscribe(s=>{t.notify(0,{rawLogsEvent:{message:s.message,date:s.startClocks.timeStamp,error:Ke(s),origin:v.SOURCE,status:g.error},messageContext:s.context})});return{stop:()=>{r(),o.unsubscribe()}}}const yi=bs;function Ei(e){function t(n,r,o,s,i){const c=ne(r.getContext(),n.context);if(Je(n.status,_e.console,r)&&Ti(n,c),Je(n.status,_e.http,r)){const a={rawLogsEvent:{date:i||N(),message:n.message,status:n.status,origin:v.LOGGER},messageContext:c,savedCommonContext:s};o&&(a.domainContext={handlingStack:o}),e.notify(0,a)}}return{handleLog:t}}const _i={[g.ok]:E.debug,[g.debug]:E.debug,[g.info]:E.info,[g.notice]:E.info,[g.warn]:E.warn,[g.error]:E.error,[g.critical]:E.error,[g.alert]:E.error,[g.emerg]:E.error};function Ti({status:e,message:t},n){G[_i[e]].call(L,t,n)}function wi(e,t,n,r,o){const s=Rn(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 Oi(e){const t=mt();e.subscribe(1,n=>{t.send("log",n)})}function Ri(e){return{get:t=>{const n=e.findTrackedSession(t);if(n)return{session_id:n.id}}}}function Ci(e){return t=>{e.notify(0,{rawLogsEvent:{message:t.message,date:t.startClocks.timeStamp,origin:v.AGENT,status:g.error}}),pn("Error reported to customer",{"error.message":t.message})}}function vi(e,t,n,r,o){const s=$o("browser-logs-sdk",t);s.setContextProvider(()=>{var c,a,l,u,d,f;return{application:{id:(c=We())===null||c===void 0?void 0:c.application_id},session:{id:(a=o.findTrackedSession())===null||a===void 0?void 0:a.id},view:{id:(u=(l=We())===null||l===void 0?void 0:l.view)===null||u===void 0?void 0:u.id},action:{id:(f=(d=We())===null||d===void 0?void 0:d.user_action)===null||f===void 0?void 0:f.id}}});const i=[];if(Ge()){const c=mt(),a=s.observable.subscribe(l=>c.send("internal_telemetry",l));i.push(()=>a.unsubscribe())}else{const c=Rn(t,{endpoint:t.rumEndpointBuilder,encoder:He()},t.replica&&{endpoint:t.replica.rumEndpointBuilder,encoder:He()},n,r,o.expireObservable);i.push(()=>c.stop());const a=s.observable.subscribe(l=>c.add(l,Fo(t)));i.push(()=>a.unsubscribe())}return Bo(),Go(Xs(e)),{telemetry:s,stop:()=>{i.forEach(c=>c())}}}function Ii(e,t,n,r){const o=new yi,s=[];o.subscribe(1,f=>cn("logs",f));const i=Ci(o),c=ps(t),a=t.sessionStoreStrategyType&&!Ge()&&!In()?ri(t,r):oi(t),{stop:l}=vi(e,t,i,c,a);s.push(()=>l()),di(t,o),Si(t,o),ui(t,o),li(t,o);const{handleLog:u}=Ei(o);if(ci(a,t,o,n,i),Ge())Oi(o);else{const{stop:f}=wi(t,o,i,c,a);s.push(()=>f())}const d=Ri(a);return{handleLog:u,getInternalContext:d.get,stop:()=>{s.forEach(f=>f())}}}const oe=ei(Ii);Ro(P(),"DD_LOGS",oe);class O{constructor(t){this.isLoggingOn=t,t&&oe.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!1,sessionSampleRate:100})}static setMessagePort(t){this.messagePort=t}static getMessagePort(){return this.messagePort}setLoggingOn(t){this.isLoggingOn=t}setAttributes(t){for(const n in t)oe.logger.setContextProperty(n,t[n])}info(t,n){this.isLoggingOn&&(oe.logger.info(t,n),console.log("[Logger] Sending info: ",t))}error(t,n){this.isLoggingOn&&(oe.logger.error(t,n),console.log("[Logger] Sending error: ",t))}warn(t,n){this.isLoggingOn&&(oe.logger.warn(t,n),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){O.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:t})}static info(t,n){O.messagePort.postMessage({type:"LOG",actionType:"INFO",message:t,attributes:n})}static error(t,n){O.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:t,attributes:n})}static warn(t,n){O.messagePort.postMessage({type:"LOG",actionType:"WARN",message:t,attributes:n})}}const w=class w{constructor(t,n,r,o,s){this.copy=()=>new w(this.h,this.m,this.s,this.f,this.field),this.print=()=>{const i=":";let c=("0"+this.h).slice(-2)+i+("0"+this.m).slice(-2)+i+("0"+this.s).slice(-2)+i+("0"+this.f).slice(-2);return c+="."+(this.field?"1":"2"),c},this.toZipTimeCodeString=()=>{const i=this.copy();return i.f=0,i.s=i.s%2===0?i.s:i.s-1,i.field=0,w.toStr(i)},this.toFrames=i=>{let c=60,a=0;Math.floor(i)==60?(c=60,a=0):Math.floor(i)==59?(c=60,a=4):Math.floor(i)==30?(c=30,a=0):Math.floor(i)==29&&(c=30,a=2);let l=this.h,u=this.m,d=this.s,f=this.f,h=this.field;const p=l*60+u,y=(p-Math.floor(p/10))*a;return l*(c*3600)+u*(c*60)+d*c+(f*2+h)-y},this.addSeconds=i=>{let c=this.copy();return c.s+=i,c.s>=60&&(c.s=0,c.m++,c.m>=60&&(c.m=0,c.h++)),c},this.addFrames=(i,c)=>{let a=this.toFrames(c);return a+=i,w.fromFrames(a,c)},this.subtractFrames=(i,c)=>this.addFrames(-i,c),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(;w.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}};w.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(),c=(n.currentTime-r.syncPoint.playerTime)%(60*60*24)*o+r.syncPoint.frame;if(c===0||o===0)throw new Error("Current frame is 0 or fps is 0");const a=w.calculateCurrentOffset(c,(d=t.gameParams)==null?void 0:d.offsets);if(a===void 0)throw new Error("Offset is undefined");let l=Math.floor(c-a);return l<0&&(l+=5178816),l>=5178816&&(l-=5178816),w.fromFrames(l,o)},w.calculateCurrentOffset=(t,n)=>{for(let r=1;r<n.length;r++)if(t<n[r].frame)return n[r-1].offset;return n[n.length-1].offset},w.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),c=i*6,a=t,l=Math.floor(a/c);a-=l*c;let u=Math.floor(a/i);a-=u*i,a>=r*60&&(a+=o*(Math.floor((a-r*60)/s)+1));let d=Math.floor(a/(r*60));a-=d*(r*60);let f=Math.floor(a/r);a-=f*r;let h=a;d+=u*10;let p=0;return p=h%2,h=Math.floor(h/2),new w(l,d,f,h,p)},w.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},w.fromStr=t=>{const r=t.split("_").map(Number);if(r.length==4){const[o,s,i,c]=r;return new w(o,s,i,c,0)}else if(r.length==5){const[o,s,i,c,a]=r;return new w(o,s,i,c,a)}else throw new Error("Invalid timecode format: "+t)},w.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,c,a]=r,l=Number(o),u=Number(s),d=Number(i),f=Number(c),h=a?Number(a):0;return new w(l,u,d,f,h)};let se=w;class Dn{constructor(t,n,r){this.jobsQueue=[],this.processedTimecodes=[],this.downloaderStopped=!1,this.firstDownload=!0,this.updateStreamData=o=>{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.initiateJobs=(o,s,i)=>{if(!this.streamData){O.error("[Downloader] Stream data is not available"),this.options&&C(this.options,"Errors")&&console.error("[Downloader] Stream data is not available");return}const c=se.fromStr(this.streamData.timeCode),a=c.addSeconds(o),l=c.addSeconds(s),u=se.generateTimecodeRange(a,l,i);for(const d of u){const f=d.toZipTimeCodeString();this.processedTimecodes.includes(f)||(this.processedTimecodes.push(f),this.addJob(f))}},this.clearOldJobs=o=>{if(!this.streamData){O.error("[Downloader] Stream data is not available"),this.options&&C(this.options,"Errors")&&console.error("[Downloader] Stream data is not available");return}const i=se.fromStr(this.streamData.timeCode).totalSeconds()-o;this.processedTimecodes=this.processedTimecodes.filter(c=>se.fromStr(c).totalSeconds()>i)},this.clearAllJobs=()=>{this.jobsQueue=[],this.currentJob=void 0,this.processedTimecodes=[]},this.addJob=o=>{if(this.jobsQueue.some(s=>s===o)){this.options&&C(this.options,"Downloader")&&console.log(`[Downloader] Job already exists for timeCode=${o}`);return}this.jobsQueue.push(o),this.startNextJob()},this.startNextJob=()=>{!this.currentJob&&this.jobsQueue.length>0&&(this.currentJob=this.jobsQueue.shift(),this.options&&C(this.options,"Downloader")&&console.log(`[Downloader] Starting job timeCode=${this.currentJob}`),this.downloadZip(this.currentJob))},this.jobDone=()=>{this.currentJob=void 0,this.startNextJob()},this.downloadZip=async o=>{if(!this.streamData){O.error("[Downloader] Stream data is not available"),this.options&&C(this.options,"Errors")&&console.error("[Downloader] Stream data is not available");return}this.firstDownload&&(this.firstDownload=!1,O.info("didStartAugmentationDownload",{timestamp:o}));const{fps:s,cloudFrontURL:i,bucketName:c}=this.streamData;try{this.options&&C(this.options,"Downloader")&&console.log(`[Downloader] Fetching zip for timeCode=${o}`);const{arrayBuffer:a,ottActions:l}=await this.fetchMetadata(i,c,s,o);if(this.downloaderStopped)return;if(this.postArrayBufferToDecoder(o,a),O.setAttributes({last_loading_zip:o}),!this.ottActions||this.ottActions.toggle.web!==l.toggle.web||l.toggle[this.streamData.customerId]!==void 0&&(this.ottActions.toggle[this.streamData.customerId]===void 0||this.ottActions.toggle[this.streamData.customerId]!==l.toggle[this.streamData.customerId])||l.toggle[this.streamData.customerId]===void 0&&this.ottActions.toggle[this.streamData.customerId]!==void 0){const d=l.toggle[this.streamData.customerId]!==void 0?l.toggle[this.streamData.customerId]&&l.toggle.web:l.toggle.web;this.ottActions&&O.info("didToggleGlobalAugmentationDrawing",{isEnabled:d}),this.ottActions=l,this.postOTTActionsToRenderer(l)}}catch(a){O.error("[Downloader] Error fetching zip",a),this.options&&C(this.options,"Errors")&&console.error("[Downloader] Error fetching zip:",a)}this.jobDone()},this.fetchMetadata=async(o,s,i,c)=>{const l=`${`${o}/${s}`}/manifests/59.94/${c}.zip`;this.options&&C(this.options,"Fetcher")&&console.log(`[Fetcher] Fetching metadata from ${l}`);const u=performance.now(),d=await fetch(l),f=await d.arrayBuffer(),p=(performance.now()-u)/1e3,S=d.headers.get("x-tgi-ott-actions");let y;if(S?y=JSON.parse(S):y={toggle:{ios:!0,android:!0,web:!0}},!d.ok)throw new Error(`HTTP error! Status: ${d.status}`);return p>1&&O.warn("didFetchZip",{downloadTaskURL:l,downloadTime:p}),{arrayBuffer:f,ottActions:y}},this.stop=()=>{this.downloaderStopped=!0,this.clearAllJobs()},this.postArrayBufferToDecoder=t,this.postOTTActionsToRenderer=n,this.options=r}}let ie=null,ce=null,qe,R;self.onmessage=async e=>{const{data:t}=e;if(t.type==="SET_LOGGER_PORT"&&O.setMessagePort(t.port),t.type==="SET_RENDERER_PORT"&&(ie=t.port,ie.onmessage=Li),t.type==="SET_DECODER_PORT"&&(ce=t.port,ce.onmessage=Ai),t.type==="SET_OPTIONS"&&(R=t.options,O.setMessagePort(self),qe=new Dn(Nn,Mn,R)),t.type==="VIDEO_SEEKED"){if(!R)return;qe.stop(),qe=new Dn(Nn,Mn,R)}};async function Li(e){const{data:t}=e;self.postMessage(t),t.type==="DOWNLOADER_INPUT"&&qe.updateStreamData(t.streamData)}function Nn(e,t){if(!ce)return;R&&C(R,"Downloader")&&console.log(`[DownloaderWorker] Posting an ArrayBuffer to Decoder, timeCode=${e}`);const n={type:"DECODER_INPUT",timeCode:e,arrayBuffer:t};ce==null||ce.postMessage(n,{transfer:[t]})}function Mn(e){if(!ie)return;R&&C(R,"Downloader")&&console.log(`[DownloaderWorker] Posting OTTActions to Renderer, toggle=${e.toggle}`);const t={type:"OTT_ACTIONS",ottActions:e};ie==null||ie.postMessage(t)}function Ai(e){R&&C(R,"Downloader")&&console.log("[DownloaderWorker] Received message from Decoder:",e.data)}self.onunhandledrejection=e=>{O.error("[DownloaderWorker] Unhandled rejection",{error:e.reason}),R&&(C(R,"Errors")&&console.error("[DownloaderWorker] Unhandled rejection:",e.reason),e.preventDefault())},self.onerror=e=>{O.error("[DownloaderWorker] Unhandled error",{error:e}),R&&(C(R,"Errors")&&console.error("[DownloaderWorker] Unhandled error:",e),e instanceof Event&&e.preventDefault())}})();\n',Pt=typeof self<"u"&&self.Blob&&new Blob([It],{type:"text/javascript;charset=utf-8"});function nr(t){let e;try{if(e=Pt&&(self.URL||self.webkitURL).createObjectURL(Pt),!e)throw"";const n=new Worker(e,{name:t==null?void 0:t.name});return n.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),n}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(It),{name:t==null?void 0:t.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}const Mt='(function(){"use strict";const R=(a,n)=>!a.debug||!a.debug.on?!1:a.debug[`log${n}`];function Xt(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var gt={},Zt;function ln(){return Zt||(Zt=1,function(a){var n=function(){var e=new Date,t=4,r=3,l=2,c=1,_=t,m={setLogLevel:function(b){b==this.debug?_=c:b==this.info?_=l:b==this.warn?_=r:(b==this.error,_=t)},debug:function(b,x){console.debug===void 0&&(console.debug=console.log),c>=_&&console.debug("["+n.getDurationString(new Date-e,1e3)+"]","["+b+"]",x)},log:function(b,x){this.debug(b.msg)},info:function(b,x){l>=_&&console.info("["+n.getDurationString(new Date-e,1e3)+"]","["+b+"]",x)},warn:function(b,x){r>=_&&console.warn("["+n.getDurationString(new Date-e,1e3)+"]","["+b+"]",x)},error:function(b,x){t>=_&&console.error("["+n.getDurationString(new Date-e,1e3)+"]","["+b+"]",x)}};return m}();n.getDurationString=function(e,t){var r;function l(w,T){for(var C=""+w,I=C.split(".");I[0].length<T;)I[0]="0"+I[0];return I.join(".")}e<0?(r=!0,e=-e):r=!1;var c=t||1,_=e/c,m=Math.floor(_/3600);_-=m*3600;var b=Math.floor(_/60);_-=b*60;var x=_*1e3;return _=Math.floor(_),x-=_*1e3,x=Math.floor(x),(r?"-":"")+m+":"+l(b,2)+":"+l(_,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),c=new Uint8Array(this._buffer),_=new Uint8Array(l,0,c.length);_.set(c),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,c){var _=new Uint8Array(e,t,c),m=new Uint8Array(r,l,c);_.set(m)},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,c=r;l>c;l--,c++){var _=t[c];t[c]=t[l],t[l]=_}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 c=0;c<l&&r[c]!==0;c++);var _=String.fromCharCodeUint8.apply(null,[this.mapUint8Array(c)]);return e!=null?this.position+=l-c:c!=t&&(this.position+=1),_};var h=Math.pow(2,32);d.prototype.readInt64=function(){return this.readInt32()*h+this.readUint32()},d.prototype.readUint64=function(){return this.readUint32()*h+this.readUint32()},d.prototype.readInt64=function(){return this.readUint32()*h+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 c=Math.min(e.length,r);for(l=0;l<c;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 c=null,_="ASCII",m=this.position;switch(typeof e=="string"&&/:/.test(e)&&(l=e.split(":"),e=l[0],c=parseInt(l[1])),typeof e=="string"&&/,/.test(e)&&(l=e.split(","),e=l[0],_=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,c);break;case"string":this.writeString(t,_,c);break;case"u16string":this.writeUCS2String(t,this.endianness,c);break;case"u16stringle":this.writeUCS2String(t,d.LITTLE_ENDIAN,c);break;case"u16stringbe":this.writeUCS2String(t,d.BIG_ENDIAN,c);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}}c!=null&&(this.position=m,this._realloc(c),this.position=m+c)},d.prototype.writeUint64=function(e){var t=Math.floor(e/h);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 f=function(e){this.buffers=[],this.bufferIndex=-1,e&&(this.insertBuffer(e),this.bufferIndex=0)};f.prototype=new d(new ArrayBuffer,0,d.BIG_ENDIAN),f.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},f.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},f.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 c=l.fileStart+l.byteLength-e.fileStart,_=e.byteLength-c;if(_>0)e=this.reduceBuffer(e,c,_);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))},f.prototype.logBufferLevel=function(e){var t,r,l,c,_=[],m,b="";for(l=0,c=0,t=0;t<this.buffers.length;t++)r=this.buffers[t],t===0?(m={},_.push(m),m.start=r.fileStart,m.end=r.fileStart+r.byteLength,b+="["+m.start+"-"):m.end===r.fileStart?m.end=r.fileStart+r.byteLength:(m={},m.start=r.fileStart,b+=_[_.length-1].end-1+"], ["+m.start+"-",m.end=r.fileStart+r.byteLength,_.push(m)),l+=r.usedBytes,c+=r.byteLength;_.length>0&&(b+=m.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+"/"+c+" bytes), continuous ranges: "+b)},f.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--)},f.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},f.prototype.findPosition=function(e,t,r){var l,c=null,_=-1;for(e===!0?l=0:l=this.bufferIndex;l<this.buffers.length&&(c=this.buffers[l],c.fileStart<=t);){_=l,r&&(c.fileStart+c.byteLength<=t?c.usedBytes=c.byteLength:c.usedBytes=t-c.fileStart,this.logBufferLevel());l++}return _!==-1?(c=this.buffers[_],c.fileStart+c.byteLength>=t?(n.debug("MultiBufferStream","Found position in existing buffer #"+_),_):-1):-1},f.prototype.findEndContiguousBuf=function(e){var t,r,l,c=e!==void 0?e:this.bufferIndex;if(r=this.buffers[c],this.buffers.length>c+1)for(t=c+1;t<this.buffers.length&&(l=this.buffers[t],l.fileStart===r.fileStart+r.byteLength);t++)r=l;return r.fileStart+r.byteLength},f.prototype.getEndFilePositionAfter=function(e){var t=this.findPosition(!0,e,!1);return t!==-1?this.findEndContiguousBuf(t):e},f.prototype.addUsedBytes=function(e){this.buffer.usedBytes+=e,this.logBufferLevel()},f.prototype.setAllUsedBytes=function(){this.buffer.usedBytes=this.buffer.byteLength,this.logBufferLevel()},f.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)},f.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},f.prototype.getLength=function(){return this.byteLength},f.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=f;var u=function(){var e=3,t=4,r=5,l=6,c=[];c[e]="ES_Descriptor",c[t]="DecoderConfigDescriptor",c[r]="DecoderSpecificInfo",c[l]="SLConfigDescriptor",this.getDescriptorName=function(b){return c[b]};var _=this,m={};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 "+(c[w]||"Descriptor "+w)+", size "+x+" at position "+b.getPosition()),c[w]?T=new m[c[w]](x):T=new m.Descriptor(x),T.parse(b),T},m.Descriptor=function(b,x){this.tag=b,this.size=x,this.descs=[]},m.Descriptor.prototype.parse=function(b){this.data=b.readUint8Array(this.size)},m.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},m.Descriptor.prototype.parseRemainingDescriptors=function(b){for(var x=b.position;b.position<x+this.size;){var w=_.parseOneDescriptor(b);this.descs.push(w)}},m.ES_Descriptor=function(b){m.Descriptor.call(this,e,b)},m.ES_Descriptor.prototype=new m.Descriptor,m.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)},m.ES_Descriptor.prototype.getOTI=function(b){var x=this.findDescriptor(t);return x?x.oti:0},m.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},m.DecoderConfigDescriptor=function(b){m.Descriptor.call(this,t,b)},m.DecoderConfigDescriptor.prototype=new m.Descriptor,m.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)},m.DecoderSpecificInfo=function(b){m.Descriptor.call(this,r,b)},m.DecoderSpecificInfo.prototype=new m.Descriptor,m.SLConfigDescriptor=function(b){m.Descriptor.call(this,l,b)},m.SLConfigDescriptor.prototype=new m.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,c){s.SampleEntry.call(this,l,c),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(c){s[e+"SampleEntry"].call(this,t,c),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(c){t?s.FullBox.call(this,"uuid",c,e):r?s.ContainerBox.call(this,"uuid",c,e):s.Box.call(this,"uuid",c,e)},s.UUIDBoxes[e].prototype=t?new s.FullBox:r?new s.ContainerBox:new s.Box,l&&(t?s.UUIDBoxes[e].prototype.parse=function(c){this.parseFullHeader(c),l&&l.call(this,c)}: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,c=e.getPosition(),_=0,m,b;if(e.getEndPosition()-c<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 "+c),_=8,w=="uuid"){if(e.getEndPosition()-e.getPosition()<16||r-_<16)return e.seek(c),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),_+=16,T=b}if(x==1){if(e.getEndPosition()-e.getPosition()<8||r&&r-_<8)return e.seek(c),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(),_+=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<_?(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:_,start:c}):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:_,start:c}):x!==0&&c+x>e.getEndPosition()?(e.seek(c),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:_,start:c}):t?{code:s.OK,type:w,size:x,hdr_size:_,start:c}:(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=_,l.start=c,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),m=e.getPosition()-(l.start+l.size),m<0?(n.warn("BoxParser","Parsing of box \'"+T+"\' did not read the entire indicated box data size (missing "+-m+" bytes), seeking forward"),e.seek(l.start+l.size)):m>0&&(n.error("BoxParser","Parsing of box \'"+T+"\' read "+m+" 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 c=e.readUint8(),_=e.readUint8(),m=e.readUint8();l.fscod=c>>6,l.bsid=c>>1&31,l.bsmod=(c&1)<<4|_>>4&15,l.acmod=_>>1&7,l.lfeon=_&1,l.num_dep_sub=m>>1&15,l.num_dep_sub>0&&(l.chan_loc=(m&1)<<8|e.readUint8())}}),s.createFullBoxCtor("dfLa",function(e){var t=127,r=128,l=[],c=["STREAMINFO","PADDING","APPLICATION","SEEKTABLE","VORBIS_COMMENT","CUESHEET","PICTURE","RESERVED"];do{var _=e.readUint8(),m=Math.min(_&t,c.length-1);if(m?e.readUint8Array(e.readUint24()):(e.readUint8Array(13),this.samplerate=e.readUint32()>>12,e.readUint8Array(20)),l.push(c[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(),c=0;c<l;c++)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,c;this.configurationVersion=e.readUint8(),c=e.readUint8(),this.general_profile_space=c>>6,this.general_tier_flag=(c&32)>>5,this.general_profile_idc=c&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(),c=e.readUint8(),this.constantFrameRate=c>>6,this.numTemporalLayers=(c&13)>>3,this.temporalIdNested=(c&4)>>2,this.lengthSizeMinusOne=c&3,this.nalu_arrays=[];var _=e.readUint8();for(t=0;t<_;t++){var m=[];this.nalu_arrays.push(m),c=e.readUint8(),m.completeness=(c&128)>>7,m.nalu_type=c&63;var b=e.readUint16();for(r=0;r<b;r++){var x={};m.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 c={};if(this.items.push(c),this.version<2)c.item_ID=e.readUint16();else if(this.version===2)c.item_ID=e.readUint32();else throw"version of iloc box not supported";switch(this.version===1||this.version===2?c.construction_method=e.readUint16()&15:c.construction_method=0,c.data_reference_index=e.readUint16(),this.base_offset_size){case 0:c.base_offset=0;break;case 4:c.base_offset=e.readUint32();break;case 8:c.base_offset=e.readUint64();break;default:throw"Error reading base offset size"}var _=e.readUint16();c.extents=[];for(var m=0;m<_;m++){var b={};if(c.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 c=e.readUint8();for(l.props=[],r=0;r<c;r++){var _=e.readUint8(),m={};l.props.push(m),m.essential=(_&128)>>7===1,this.flags&1?m.property_index=(_&127)<<8|e.readUint8():m.property_index=_&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 c=e.readUint8();switch(l.padding_flag=c>>7,l.assignment_type=c&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 c=e.readUint8();for(t=0;t<c;t++){var _=[];this.nalu_arrays.push(_),l=e.readUint8(),_.completeness=(l&128)>>7,_.nalu_type=l&63;var m=e.readUint16();for(r=0;r<m;r++){var b={};_.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 c={};this.dependency.push(c),c.subSeqDirectionFlag=e.readUint8(),c.layerNumber=e.readUint8(),c.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 y(e,t){this.bad_pixel_row=e,this.bad_pixel_column=t}y.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(),c=e.readUint32();this.bad_pixels.push(new y(l,c))}}),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 c=e.readUint32();l.reference_type=c>>31&1,l.referenced_size=c&2147483647,l.subsegment_duration=e.readUint32(),c=e.readUint32(),l.starts_with_SAP=c>>31&1,l.SAP_type=c>>28&7,l.SAP_delta_time=c&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 c=e.readUint32(),_=0;_<c;_++){var m={};l.ranges.push(m),m.level=e.readUint8(),m.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,c;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"]?(c=new s[r.type+"SampleEntry"](r.size),c.hdr_size=r.hdr_size,c.start=r.start):(n.warn("BoxParser","Unknown sample entry type: "+r.type),c=new s.SampleEntry(r.type,r.size,r.hdr_size,r.start)),c.write===s.SampleEntry.prototype.write&&(n.info("BoxParser","SampleEntry "+c.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),c.parseDataAndRewind(e)),c.parse(e),this.entries.push(c);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,c;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)c=l.box,this.boxes.push(c),this[c.type]=c;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,c;for(l=e.readUint32(),this.entries=[],t=0;t<l;t++){var _={};if(this.entries[t]=_,_.sample_delta=e.readUint32(),_.subsamples=[],c=e.readUint16(),c>0)for(r=0;r<c;r++){var m={};_.subsamples.push(m),this.version==1?m.size=e.readUint32():m.size=e.readUint16(),m.priority=e.readUint8(),m.discardable=e.readUint8(),m.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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/\'/g,"&#039;")}),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,c=0;this.version===1?(l=e.readUint64(),c=e.readUint64()):(l=e.readUint32(),c=e.readUint32()),r.absolute_time=l,r.absolute_duration=c,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 k=this.held_bits>>this.num_held_bits-A&(1<<A)-1;return this.num_held_bits-=A,k}};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 c=l.extract_bits(6);l.stream_read_1_bytes(e);var _=l.extract_bits(2);this.general_constraint_info[t]=c<<2|_}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 m=l.extract_bits(1);this.ptl_sublayer_present_mask|=m<<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 I=e.readUint16();T.push({data:e.readUint8Array(I),length:I})}}}),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 c=!1,_="";for(e=5;e>=0;e--)(this.hvcC.general_constraint_indicator[e]||c)&&(_="."+s.decimalToHex(this.hvcC.general_constraint_indicator[e],0)+_,c=!0);t+=_}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=[],c=0;c|=this.vvcC.ptl_frame_only_constraint<<7,c|=this.vvcC.ptl_multilayer_enabled<<6;var _;for(e=0;e<this.vvcC.general_constraint_info.length;++e)c|=this.vvcC.general_constraint_info[e]>>2&63,l.push(c),c&&(_=e),c=this.vvcC.general_constraint_info[e]>>2&3;if(_===void 0)r=".CA";else{r=".C";var m="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",b=0,x=0;for(e=0;e<=_;++e)for(b=b<<8|l[e],x+=8;x>=5;){var w=b>>x-5&31;r+=m[w],x-=5,b&=(1<<x)-1}x&&(b<<=5-x,r+=m[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>h&&(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>h?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>h&&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,c,_;for(c=0,_=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(_++,l=0;l<this.samples_per_chunk[t];l++){if(e[c])e[c].description_index=this.sample_description_index[t],e[c].chunk_index=_;else return;c++}},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 c(w){var T=Math.floor(w/3600),C=Math.floor((w-T*3600)/60),I=Math.floor(w-T*3600-C*60),A=Math.floor((w-T*3600-C*60-I)*1e3);return""+l(T,2)+":"+l(C,2)+":"+l(I,2)+"."+l(A,3)}for(var _=this.parseSample(r),m="",b=0;b<_.length;b++){var x=_[b];m+=c(e)+" --> "+c(t)+`\\r\n`,m+=x.payl.text}return m};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 f,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 c={};this.fragmentedTracks.push(c),c.id=e,c.user=t,c.trak=l,l.nextSample=0,c.segmentStream=null,c.nb_samples=1e3,c.rapAlignement=!0,r&&(r.nbSamples&&(c.nb_samples=r.nbSamples),r.rapAlignement&&(c.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 c={};this.extractedTracks.push(c),c.id=e,c.user=t,c.trak=l,l.nextSample=0,c.nb_samples=1e3,c.samples=[],r&&r.nbSamples&&(c.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,c,_,m,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],m=l.mdia.minf.stbl.stsd.entries[0],c={},r.tracks.push(c),c.id=l.tkhd.track_id,c.name=l.mdia.hdlr.name,c.references=[],l.tref)for(t=0;t<l.tref.boxes.length;t++)_={},c.references.push(_),_.type=l.tref.boxes[t].type,_.track_ids=l.tref.boxes[t].track_ids;l.edts&&(c.edits=l.edts.elst.entries),c.created=new Date(b+l.tkhd.creation_time*1e3),c.modified=new Date(b+l.tkhd.modification_time*1e3),c.movie_duration=l.tkhd.duration,c.movie_timescale=r.timescale,c.layer=l.tkhd.layer,c.alternate_group=l.tkhd.alternate_group,c.volume=l.tkhd.volume,c.matrix=l.tkhd.matrix,c.track_width=l.tkhd.width/65536,c.track_height=l.tkhd.height/65536,c.timescale=l.mdia.mdhd.timescale,c.cts_shift=l.mdia.minf.stbl.cslg,c.duration=l.mdia.mdhd.duration,c.samples_duration=l.samples_duration,c.codec=m.getCodec(),c.kind=l.udta&&l.udta.kinds.length?l.udta.kinds[0]:{schemeURI:"",value:""},c.language=l.mdia.elng?l.mdia.elng.extended_language:l.mdia.mdhd.languageString,c.nb_samples=l.samples.length,c.size=l.samples_size,c.bitrate=c.size*8*c.timescale/c.samples_duration,m.isAudio()?(c.type="audio",r.audioTracks.push(c),c.audio={},c.audio.sample_rate=m.getSampleRate(),c.audio.channel_count=m.getChannelCount(),c.audio.sample_size=m.getSampleSize()):m.isVideo()?(c.type="video",r.videoTracks.push(c),c.video={},c.video.width=m.getWidth(),c.video.height=m.getHeight()):m.isSubtitle()?(c.type="subtitles",r.subtitleTracks.push(c)):m.isHint()?(c.type="metadata",r.hintTracks.push(c)):m.isMetadata()?(c.type="metadata",r.metadataTracks.push(c)):(c.type="metadata",r.otherTracks.push(c))}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 c=this.createFragment(l.id,r.nextSample,l.segmentStream);if(c)l.segmentStream=c,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 _=this.extractedTracks[t];for(r=_.trak;r.nextSample<r.samples.length&&this.sampleProcessingStarted;){n.debug("ISOFile","Exporting on track #"+_.id+" sample #"+r.nextSample);var m=this.getSample(r,r.nextSample);if(m)r.nextSample++,_.samples.push(m);else{this.setNextSeekPositionFromSample(r.samples[r.nextSample]);break}if((r.nextSample%_.nb_samples===0||r.nextSample>=r.samples.length)&&(n.debug("ISOFile","Sending samples on track #"+_.id+" for sample "+r.nextSample),this.onSamples&&this.onSamples(_.id,_.user,_.samples),_.samples=[],_!==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 c=l.lastValidSample;c<t;c++)r+=this.releaseSample(l,c);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,c,_=1/0,m=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(c=r.samples[l],l===0)b=0,x=c.timescale;else if(c.cts>e*c.timescale){b=l-1;break}t&&c.is_sync&&(m=l)}for(t&&(b=m),e=r.samples[b].cts,r.nextSample=b;r.samples[b].alreadyRead===r.samples[b].size&&r.samples[b+1];)b++;return _=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: "+_),{offset:_,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,c,_,m={offset:1/0,time:1/0};if(this.moov){for(_=0;_<r.traks.length;_++)l=r.traks[_],!(e>this.getTrackDuration(l))&&(c=this.seekTrack(e,t,l),c.offset<m.offset&&(m.offset=c.offset),c.time<m.time&&(m.time=c.time));return n.info("ISOFile","Seeking at time "+n.getDurationString(m.time,1)+" needs a buffer with a fileStart position of "+m.offset),m.offset===1/0?m={offset:this.nextParsePosition,time:0}:m.offset=this.stream.getEndFilePositionAfter(m.offset),n.info("ISOFile","Adjusted seek position (after checking data already in buffer): "+m.offset),m}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 c=l.add("minf");if(s[t.type+"SampleEntry"]!==void 0){var _=new s[t.type+"SampleEntry"];_.data_reference_index=1;var m="";for(var b in s.sampleEntryCodes)for(var x=s.sampleEntryCodes[b],w=0;w<x.length;w++)if(x.indexOf(t.type)>-1){m=b;break}switch(m){case"Visual":if(c.add("vmhd").set("graphicsmode",0).set("opcolor",[0,0,0]),_.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)),_.addBox(T)}else if(t.hevcDecoderConfigRecord){var C=new s.hvcCBox;C.parse(new o(t.hevcDecoderConfigRecord)),_.addBox(C)}break;case"Audio":c.add("smhd").set("balance",t.balance||0),_.set("channel_count",t.channel_count||2).set("samplesize",t.samplesize||16).set("samplerate",t.samplerate||65536);break;case"Hint":c.add("hmhd");break;case"Subtitle":switch(c.add("sthd"),t.type){case"stpp":_.set("namespace",t.namespace||"nonamespace").set("schema_location",t.schema_location||"").set("auxiliary_mime_types",t.auxiliary_mime_types||"");break}break;case"Metadata":c.add("nmhd");break;case"System":c.add("nmhd");break;default:c.add("nmhd");break}t.description&&_.addBox(t.description),t.description_boxes&&t.description_boxes.forEach(function(A){_.addBox(A)}),c.add("dinf").add("dref").addEntry(new s["url Box"]().set("flags",1));var I=c.add("stbl");return I.add("stsd").addEntry(_),I.add("stts").set("sample_counts",[]).set("sample_deltas",[]),I.add("stsc").set("first_chunk",[]).set("samples_per_chunk",[]).set("sample_description_index",[]),I.add("stco").set("chunk_offsets",[]),I.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||{},c={},_=this.getTrackById(e);if(_!==null){c.number=_.samples.length,c.track_id=_.tkhd.track_id,c.timescale=_.mdia.mdhd.timescale,c.description_index=l.sample_description_index?l.sample_description_index-1:0,c.description=_.mdia.minf.stbl.stsd.entries[c.description_index],c.data=t,c.size=t.byteLength,c.alreadyRead=c.size,c.duration=l.duration||1,c.cts=l.cts||0,c.dts=l.dts||0,c.is_sync=l.is_sync||!1,c.is_leading=l.is_leading||0,c.depends_on=l.depends_on||0,c.is_depended_on=l.is_depended_on||0,c.has_redundancy=l.has_redundancy||0,c.degradation_priority=l.degradation_priority||0,c.offset=0,c.subsamples=l.subsamples,_.samples.push(c),_.samples_size+=c.size,_.samples_duration+=c.duration,_.first_dts===void 0&&(_.first_dts=l.dts),this.processSamples();var m=this.createSingleSampleMoof(c);return this.addBox(m),m.computeSize(),m.trafs[0].truns[0].data_offset=m.size+8,this.add("mdat").data=new Uint8Array(t),c}},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"),c=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-(c.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,c,_,m,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=[],c=t.mdia.minf.stbl.stsz||t.mdia.minf.stbl.stz2,c.sample_sizes=[],_=t.mdia.minf.stbl.stts,_.sample_counts=[],_.sample_deltas=[],m=t.mdia.minf.stbl.ctts,m&&(m.sample_counts=[],m.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,c){var _,m,b,x;function w(T,C,I){this.grouping_type=T,this.grouping_type_parameter=C,this.sbgp=I,this.last_sample_in_run=-1,this.entry_index=-1}for(t&&(t.sample_groups_info=[]),e.sample_groups_info||(e.sample_groups_info=[]),m=0;m<r.length;m++){for(x=r[m].grouping_type+"/"+r[m].grouping_type_parameter,b=new w(r[m].grouping_type,r[m].grouping_type_parameter,r[m]),t&&(t.sample_groups_info[x]=b),e.sample_groups_info[x]||(e.sample_groups_info[x]=b),_=0;_<l.length;_++)l[_].grouping_type===r[m].grouping_type&&(b.description=l[_],b.description.used=!0);if(c)for(_=0;_<c.length;_++)c[_].grouping_type===r[m].grouping_type&&(b.fragment_description=c[_],b.fragment_description.used=!0,b.is_fragment=!0)}if(t){if(c)for(m=0;m<c.length;m++)!c[m].used&&c[m].version>=2&&(x=c[m].grouping_type+"/0",b=new w(c[m].grouping_type,0),b.is_fragment=!0,t.sample_groups_info[x]||(t.sample_groups_info[x]=b))}else for(m=0;m<l.length;m++)!l[m].used&&l[m].version>=2&&(x=l[m].grouping_type+"/0",b=new w(l[m].grouping_type,0),e.sample_groups_info[x]||(e.sample_groups_info[x]=b))},S.setSampleGroupProperties=function(e,t,r,l){var c,_;t.sample_groups=[];for(c in l)if(t.sample_groups[c]={},t.sample_groups[c].grouping_type=l[c].grouping_type,t.sample_groups[c].grouping_type_parameter=l[c].grouping_type_parameter,r>=l[c].last_sample_in_run&&(l[c].last_sample_in_run<0&&(l[c].last_sample_in_run=0),l[c].entry_index++,l[c].entry_index<=l[c].sbgp.entries.length-1&&(l[c].last_sample_in_run+=l[c].sbgp.entries[l[c].entry_index].sample_count)),l[c].entry_index<=l[c].sbgp.entries.length-1?t.sample_groups[c].group_description_index=l[c].sbgp.entries[l[c].entry_index].group_description_index:t.sample_groups[c].group_description_index=-1,t.sample_groups[c].group_description_index!==0){var m;l[c].fragment_description?m=l[c].fragment_description:m=l[c].description,t.sample_groups[c].group_description_index>0?(t.sample_groups[c].group_description_index>65535?_=(t.sample_groups[c].group_description_index>>16)-1:_=t.sample_groups[c].group_description_index-1,m&&_>=0&&(t.sample_groups[c].description=m.entries[_])):m&&m.version>=2&&m.default_group_description_index>0&&(t.sample_groups[c].description=m.entries[m.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,c,_,m,b,x,w,T,C,I,A,k,D,$,J,Y,M,K,Z,be,V,q;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,c=e.mdia.minf.stbl.stsz||e.mdia.minf.stbl.stz2,_=e.mdia.minf.stbl.stts,m=e.mdia.minf.stbl.ctts,b=e.mdia.minf.stbl.stss,x=e.mdia.minf.stbl.stsd,w=e.mdia.minf.stbl.subs,I=e.mdia.minf.stbl.stdp,T=e.mdia.minf.stbl.sbgps,C=e.mdia.minf.stbl.sgpds,Y=-1,M=-1,K=-1,Z=-1,be=0,V=0,q=0,S.initSampleGroups(e,null,T,C),!(typeof c>"u")){for(t=0;t<c.sample_sizes.length;t++){var B={};B.number=t,B.track_id=e.tkhd.track_id,B.timescale=e.mdia.mdhd.timescale,B.alreadyRead=0,e.samples[t]=B,B.size=c.sample_sizes[t],e.samples_size+=B.size,t===0?(k=1,A=0,B.chunk_index=k,B.chunk_run_index=A,J=l.samples_per_chunk[A],$=0,A+1<l.first_chunk.length?D=l.first_chunk[A+1]-1:D=1/0):t<J?(B.chunk_index=k,B.chunk_run_index=A):(k++,B.chunk_index=k,$=0,k<=D||(A++,A+1<l.first_chunk.length?D=l.first_chunk[A+1]-1:D=1/0),B.chunk_run_index=A,J+=l.samples_per_chunk[A]),B.description_index=l.sample_description_index[B.chunk_run_index]-1,B.description=x.entries[B.description_index],B.offset=r.chunk_offsets[B.chunk_index-1]+$,$+=B.size,t>Y&&(M++,Y<0&&(Y=0),Y+=_.sample_counts[M]),t>0?(e.samples[t-1].duration=_.sample_deltas[M],e.samples_duration+=e.samples[t-1].duration,B.dts=e.samples[t-1].dts+e.samples[t-1].duration):B.dts=0,m?(t>=K&&(Z++,K<0&&(K=0),K+=m.sample_counts[Z]),B.cts=e.samples[t].dts+m.sample_offsets[Z]):B.cts=B.dts,b?(t==b.sample_numbers[be]-1?(B.is_sync=!0,be++):(B.is_sync=!1,B.degradation_priority=0),w&&w.entries[V].sample_delta+q==t+1&&(B.subsamples=w.entries[V].subsamples,q+=w.entries[V].sample_delta,V++)):B.is_sync=!0,S.process_sdtp(e.mdia.minf.stbl.sdtp,B,B.number),I?B.degradation_priority=I.priority[t]:B.degradation_priority=0,w&&w.entries[V].sample_delta+q==t&&(B.subsamples=w.entries[V].subsamples,q+=w.entries[V].sample_delta),(T.length>0||C.length>0)&&S.setSampleGroupProperties(e,B,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,c,_,m,b,x,w,T,C,I,A,k;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),I=this.getTrexById(T.tfhd.track_id),T.tfhd.flags&s.TFHD_FLAG_SAMPLE_DESC?l=T.tfhd.default_sample_description_index:l=I?I.default_sample_description_index:1,T.tfhd.flags&s.TFHD_FLAG_SAMPLE_DUR?c=T.tfhd.default_sample_duration:c=I?I.default_sample_duration:0,T.tfhd.flags&s.TFHD_FLAG_SAMPLE_SIZE?_=T.tfhd.default_sample_size:_=I?I.default_sample_size:0,T.tfhd.flags&s.TFHD_FLAG_SAMPLE_FLAGS?m=T.tfhd.default_sample_flags:m=I?I.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 D=T.truns[t];for(r=0;r<D.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=_,D.flags&s.TRUN_FLAGS_SIZE&&(A.size=D.sample_size[r]),C.samples_size+=A.size,A.duration=c,D.flags&s.TRUN_FLAGS_DURATION&&(A.duration=D.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,D.flags&s.TRUN_FLAGS_CTS_OFFSET&&(A.cts=A.dts+D.sample_composition_time_offset[r]),k=m,D.flags&s.TRUN_FLAGS_FLAGS?k=D.sample_flags[r]:r===0&&D.flags&s.TRUN_FLAGS_FIRST_FLAG&&(k=D.first_sample_flags),A.is_sync=!(k>>16&1),A.is_leading=k>>26&3,A.depends_on=k>>24&3,A.is_depended_on=k>>22&3,A.has_redundancy=k>>20&3,A.degradation_priority=k&65535;var $=!!(T.tfhd.flags&s.TFHD_FLAG_BASE_DATA_OFFSET),J=!!(T.tfhd.flags&s.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),Y=!!(D.flags&s.TRUN_FLAGS_DATA_OFFSET),M=0;$?M=T.tfhd.base_data_offset:J||t===0?M=w.start:M=b,t===0&&r===0?Y?A.offset=M+D.data_offset:A.offset=M: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 K=T.first_sample_index;for(t=0;t<T.subs.entries.length;t++)K+=T.subs.entries[t].sample_delta,A=C.samples[K-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 c=this.stream.findPosition(!0,l.offset+l.alreadyRead,!1);if(c>-1){r=this.stream.buffers[c];var _=r.byteLength-(l.offset+l.alreadyRead-r.fileStart);if(l.size-l.alreadyRead<=_)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(_===0)return null;n.debug("ISOFile","Getting sample #"+t+" partial data (alreadyRead: "+l.alreadyRead+" offset: "+(l.offset+l.alreadyRead-r.fileStart)+" read size: "+_+" full size: "+l.size+")"),d.memcpy(l.data.buffer,l.alreadyRead,r,l.offset+l.alreadyRead-r.fileStart,_),l.alreadyRead+=_,r.usedBytes+=_,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,c,_=this.meta;if(_!=null&&_.hdlr!==void 0&&_.iinf!==void 0){for(r=0;r<_.iinf.item_infos.length;r++)c={},c.id=_.iinf.item_infos[r].item_ID,e[c.id]=c,c.ref_to=[],c.name=_.iinf.item_infos[r].item_name,_.iinf.item_infos[r].protection_index>0&&(c.protection=_.ipro.protections[_.iinf.item_infos[r].protection_index-1]),_.iinf.item_infos[r].item_type?c.type=_.iinf.item_infos[r].item_type:c.type="mime",c.content_type=_.iinf.item_infos[r].content_type,c.content_encoding=_.iinf.item_infos[r].content_encoding;if(_.grpl)for(r=0;r<_.grpl.boxes.length;r++)entity_group={},entity_group.id=_.grpl.boxes[r].group_id,entity_group.entity_ids=_.grpl.boxes[r].entity_ids,entity_group.type=_.grpl.boxes[r].type,t[entity_group.id]=entity_group;if(_.iloc)for(r=0;r<_.iloc.items.length;r++){var m=_.iloc.items[r];switch(c=e[m.item_ID],m.data_reference_index!==0&&(n.warn("Item storage with reference to other files: not supported"),c.source=_.dinf.boxes[m.data_reference_index-1]),m.construction_method){case 0:break;case 1:break;case 2:n.warn("Item storage with construction_method : not supported");break}for(c.extents=[],c.size=0,l=0;l<m.extents.length;l++)c.extents[l]={},c.extents[l].offset=m.extents[l].extent_offset+m.base_offset,m.construction_method==1&&(c.extents[l].offset+=_.idat.start+_.idat.hdr_size),c.extents[l].length=m.extents[l].extent_length,c.extents[l].alreadyRead=0,c.size+=c.extents[l].length}if(_.pitm&&(e[_.pitm.item_id].primary=!0),_.iref)for(r=0;r<_.iref.references.length;r++){var b=_.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(_.iprp)for(var x=0;x<_.iprp.ipmas.length;x++){var w=_.iprp.ipmas[x];for(r=0;r<w.associations.length;r++){var T=w.associations[r];if(c=e[T.id],c||(c=t[T.id]),c)for(c.properties===void 0&&(c.properties={},c.properties.boxes=[]),l=0;l<T.props.length;l++){var C=T.props[l];if(C.property_index>0&&C.property_index-1<_.iprp.ipco.boxes.length){var I=_.iprp.ipco.boxes[C.property_index-1];c.properties[I.type]=I,c.properties.boxes.push(I)}}}}}},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 c=r.extents[l];if(c.alreadyRead!==c.length){var _=this.stream.findPosition(!0,c.offset+c.alreadyRead,!1);if(_>-1){t=this.stream.buffers[_];var m=t.byteLength-(c.offset+c.alreadyRead-t.fileStart);if(c.length-c.alreadyRead<=m)n.debug("ISOFile","Getting item #"+e+" extent #"+l+" data (alreadyRead: "+c.alreadyRead+" offset: "+(c.offset+c.alreadyRead-t.fileStart)+" read size: "+(c.length-c.alreadyRead)+" full extent size: "+c.length+" full item size: "+r.size+")"),d.memcpy(r.data.buffer,r.alreadyRead,t,c.offset+c.alreadyRead-t.fileStart,c.length-c.alreadyRead),t.usedBytes+=c.length-c.alreadyRead,this.stream.logBufferLevel(),r.alreadyRead+=c.length-c.alreadyRead,c.alreadyRead=c.length;else return n.debug("ISOFile","Getting item #"+e+" extent #"+l+" partial data (alreadyRead: "+c.alreadyRead+" offset: "+(c.offset+c.alreadyRead-t.fileStart)+" read size: "+m+" full extent size: "+c.length+" full item size: "+r.size+")"),d.memcpy(r.data.buffer,r.alreadyRead,t,c.offset+c.alreadyRead-t.fileStart,m),c.alreadyRead+=m,r.alreadyRead+=m,t.usedBytes+=m,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 c={type:r.type,description_boxes:r.properties.boxes};r.properties.ispe&&(c.width=r.properties.ispe.image_width,c.height=r.properties.ispe.image_height);var _=l.addTrack(c);return _?(l.addSample(_,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),c=this.getSample(l,t);if(c==null)return this.setNextSeekPositionFromSample(l.samples[t]),null;var _=r||new d;_.endianness=d.BIG_ENDIAN;var m=this.createSingleSampleMoof(c);m.write(_),m.trafs[0].truns[0].data_offset=m.size+8,n.debug("MP4Box","Adjusting data_offset with new value "+m.trafs[0].truns[0].data_offset),_.adjustUint32(m.trafs[0].truns[0].data_offset_position,m.trafs[0].truns[0].data_offset);var b=new s.mdatBox;return b.data=c.data,b.write(_),_},S.writeInitializationSegment=function(e,t,r,l){var c;n.debug("ISOFile","Generating initialization segment");var _=new d;_.endianness=d.BIG_ENDIAN,e.write(_);var m=t.add("mvex");for(r&&m.add("mehd").set("fragment_duration",r),c=0;c<t.traks.length;c++)m.add("trex").set("track_id",t.traks[c].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(_),_.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 c=new s.moovBox;c.mvhd=this.moov.mvhd,c.boxes.push(c.mvhd),r=this.getTrackById(this.fragmentedTracks[e].id),c.boxes.push(r),c.traks.push(r),l={},l.id=r.tkhd.track_id,l.user=this.fragmentedTracks[e].user,l.buffer=S.writeInitializationSegment(this.ftyp,c,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>h&&(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}(gt)),gt}var yt=ln(),fn=Xt(yt),mt={exports:{}},Qt;function hn(){return Qt||(Qt=1,function(a){var n={};a.exports=n,n.parse=function(o,d){for(var h=n.bin.readUshort,f=n.bin.readUint,y=0,u={},s=new Uint8Array(o),p=s.length-4;f(s,p)!=101010256;)p--;var y=p;y+=4,y+=4;var g=h(s,y);y+=2,h(s,y),y+=2;var v=f(s,y);y+=4;var U=f(s,y);y+=4,y=U;for(var S=0;S<g;S++){f(s,y),y+=4,y+=4,y+=4,y+=4,f(s,y),y+=4;var v=f(s,y);y+=4;var E=f(s,y);y+=4;var e=h(s,y),t=h(s,y+2),r=h(s,y+4);y+=6,y+=8;var l=f(s,y);y+=4,y+=e+t+r,n._readLocal(s,l,u,v,E,d)}return u},n._readLocal=function(o,d,h,f,u,s){var p=n.bin.readUshort,y=n.bin.readUint;y(o,d),d+=4,p(o,d),d+=2,p(o,d),d+=2;var g=p(o,d);d+=2,y(o,d),d+=4,y(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){h[S]={size:u,csize:f};return}var E=new Uint8Array(o.buffer,d);if(g==0)h[S]=new Uint8Array(E.buffer.slice(d,d+f));else if(g==8){var e=new Uint8Array(u);n.inflateRaw(E,e),h[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 h=0,f=new Uint8Array(50+Math.floor(o.length*1.1));f[h]=120,f[h+1]=156,h+=2,h=n.F.deflateRaw(o,f,h,d.level);var u=n.adler(o,0,o.length);return f[h+0]=u>>>24&255,f[h+1]=u>>>16&255,f[h+2]=u>>>8&255,f[h+3]=u>>>0&255,new Uint8Array(f.buffer,0,h+4)},n.deflateRaw=function(o,d){d==null&&(d={level:6});var h=new Uint8Array(50+Math.floor(o.length*1.1)),f=n.F.deflateRaw(o,h,f,d.level);return new Uint8Array(h.buffer,0,f)},n.encode=function(o,d){d==null&&(d=!1);var h=0,f=n.bin.writeUint,u=n.bin.writeUshort,s={};for(var p in o){var y=!n._noNeed(p)&&!d,g=o[p],v=n.crc.crc(g,0,g.length);s[p]={cpr:y,usize:g.length,crc:v,file:y?n.deflateRaw(g):g}}for(var p in s)h+=s[p].file.length+30+46+2*n.bin.sizeUTF8(p);h+=22;var U=new Uint8Array(h),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 f(U,S,101010256),S+=4,S+=4,u(U,S,t),S+=2,u(U,S,t),S+=2,f(U,S,l),S+=4,f(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,h,f,u,s){var p=n.bin.writeUint,y=n.bin.writeUshort,g=f.file;p(o,d,u==0?67324752:33639248),d+=4,u==1&&(d+=2),y(o,d,20),d+=2,y(o,d,0),d+=2,y(o,d,f.cpr?8:0),d+=2,p(o,d,0),d+=4,p(o,d,f.crc),d+=4,p(o,d,g.length),d+=4,p(o,d,f.usize),d+=4,y(o,d,n.bin.sizeUTF8(h)),d+=2,y(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,h);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 h=d,f=0;f<8;f++)h&1?h=3988292384^h>>>1:h=h>>>1;o[d]=h}return o}(),update:function(o,d,h,f){for(var u=0;u<f;u++)o=n.crc.table[(o^d[h+u])&255]^o>>>8;return o},crc:function(o,d,h){return n.crc.update(4294967295,o,d,h)^4294967295}},n.adler=function(o,d,h){for(var f=1,u=0,s=d,p=d+h;s<p;){for(var y=Math.min(s+5552,p);s<y;)f+=o[s++],u+=f;f=f%65521,u=u%65521}return u<<16|f},n.bin={readUshort:function(o,d){return o[d]|o[d+1]<<8},writeUshort:function(o,d,h){o[d]=h&255,o[d+1]=h>>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,h){o[d]=h&255,o[d+1]=h>>8&255,o[d+2]=h>>16&255,o[d+3]=h>>24&255},readASCII:function(o,d,h){for(var f="",u=0;u<h;u++)f+=String.fromCharCode(o[d+u]);return f},writeASCII:function(o,d,h){for(var f=0;f<h.length;f++)o[d+f]=h.charCodeAt(f)},pad:function(o){return o.length<2?"0"+o:o},readUTF8:function(o,d,h){for(var f="",u,s=0;s<h;s++)f+="%"+n.bin.pad(o[d+s].toString(16));try{u=decodeURIComponent(f)}catch{return n.bin.readASCII(o,d,h)}return u},writeUTF8:function(o,d,h){for(var f=h.length,u=0,s=0;s<f;s++){var p=h.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,h=0,f=0;f<d;f++){var u=o.charCodeAt(f);if(!(u&4294967168))h++;else if(!(u&4294965248))h+=2;else if(!(u&4294901760))h+=3;else if(!(u&4294967295-(1<<21)+1))h+=4;else throw"e"}return h}},n.F={},n.F.deflateRaw=function(o,d,h,f){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[f],p=n.F.U,y=n.F._goodIndex;n.F._hash;var g=n.F._putsE,v=0,U=h<<3,S=0,E=o.length;if(f==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,c=0,_=0,m=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){(c>14e3||_>26697)&&E-v>100&&(S<v&&(t[c]=v-S,c+=2,S=v),U=n.F._writeBlock(v==E-1||S==E?1:0,t,c,b,o,m,v-m,d,U),c=_=b=0,m=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,I=C&65535;if(C!=0){var e=C>>>16,I=C&65535,A=y(e,p.of0);p.lhst[257+A]++;var k=y(I,p.df0);p.dhst[k]++,b+=p.exb[A]+p.dxb[k],t[c]=e<<23|v-S,t[c+1]=I<<16|A<<8|k,c+=2,S=v+e}else p.lhst[o[v]]++;_++}}for((m!=v||o.length==0)&&(S<v&&(t[c]=v-S,c+=2,S=v),U=n.F._writeBlock(1,t,c,b,o,m,v-m,d,U),c=0,_=0,c=_=b=0,m=v);U&7;)U++;return U>>>3},n.F._bestMatch=function(o,d,h,f,u,s){var p=d&32767,y=h[p],g=p-y+32768&32767;if(y==p||f!=n.F._hash(o,d-g))return 0;for(var v=0,U=0,S=Math.min(32767,d);g<=S&&--s!=0&&y!=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=h[r],c=r-l+32768&32767;c>e&&(e=c,y=r)}}}p=y,y=h[p],g+=p-y+32768&32767}return v<<16|U},n.F._howLong=function(o,d,h){if(o[d]!=o[d-h]||o[d+1]!=o[d+1-h]||o[d+2]!=o[d+2-h])return 0;var f=d,u=Math.min(o.length,d+258);for(d+=3;d<u&&o[d]==o[d-h];)d++;return d-f},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,h,f,u,s,p,y,g){var v=n.F.U,U=n.F._putsF,S=n.F._putsE,E,e,t,r,l,c,_,m,b;v.lhst[256]++,E=n.F.getTrees(),e=E[0],t=E[1],r=E[2],l=E[3],c=E[4],_=E[5],m=E[6],b=E[7];var x=(g+3&7?8-(g+3&7):0)+32+(p<<3),w=f+n.F.contSize(v.fltree,v.lhst)+n.F.contSize(v.fdtree,v.dhst),T=f+n.F.contSize(v.ltree,v.lhst)+n.F.contSize(v.dtree,v.dhst);T+=14+3*_+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 I=x<w&&x<T?0:w<T?1:2;if(U(y,g,o),U(y,g+1,I),g+=3,I==0){for(;g&7;)g++;g=n.F._copyExact(u,s,p,y,g)}else{var A,k;if(I==1&&(A=v.fltree,k=v.fdtree),I==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,k=v.dtree,S(y,g,l-257),g+=5,S(y,g,c-1),g+=5,S(y,g,_-4),g+=4;for(var D=0;D<_;D++)S(y,g+D*3,v.itree[(v.ordr[D]<<1)+1]);g+=3*_,g=n.F._codeTiny(m,v.itree,y,g),g=n.F._codeTiny(b,v.itree,y,g)}for(var $=s,J=0;J<h;J+=2){for(var Y=d[J],M=Y>>>23,K=$+(Y&(1<<23)-1);$<K;)g=n.F._writeLit(u[$++],A,y,g);if(M!=0){var Z=d[J+1],be=Z>>16,V=Z>>8&255,q=Z&255;g=n.F._writeLit(257+V,A,y,g),S(y,g,M-v.of0[V]),g+=v.exb[V],g=n.F._writeLit(q,k,y,g),U(y,g,be-v.df0[q]),g+=v.dxb[q],$+=M}}g=n.F._writeLit(256,A,y,g)}return g},n.F._copyExact=function(o,d,h,f,u){var s=u>>>3;return f[s]=h,f[s+1]=h>>>8,f[s+2]=255-f[s],f[s+3]=255-f[s+1],s+=4,f.set(new Uint8Array(o.buffer,d,h),s),u+(h+4<<3)},n.F.getTrees=function(){for(var o=n.F.U,d=n.F._hufTree(o.lhst,o.ltree,15),h=n.F._hufTree(o.dhst,o.dtree,15),f=[],u=n.F._lenCodes(o.ltree,f),s=[],p=n.F._lenCodes(o.dtree,s),y=0;y<f.length;y+=2)o.ihst[f[y]]++;for(var y=0;y<s.length;y+=2)o.ihst[s[y]]++;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,h,g,u,p,v,f,s]},n.F.getSecond=function(o){for(var d=[],h=0;h<o.length;h+=2)d.push(o[h+1]);return d},n.F.nonZero=function(o){for(var d="",h=0;h<o.length;h+=2)o[h+1]!=0&&(d+=(h>>1)+",");return d},n.F.contSize=function(o,d){for(var h=0,f=0;f<d.length;f++)h+=d[f]*o[(f<<1)+1];return h},n.F._codeTiny=function(o,d,h,f){for(var u=0;u<o.length;u+=2){var s=o[u],p=o[u+1];f=n.F._writeLit(s,d,h,f);var y=s==16?2:s==17?3:7;s>15&&(n.F._putsE(h,f,p,y),f+=y)}return f},n.F._lenCodes=function(o,d){for(var h=o.length;h!=2&&o[h-1]==0;)h-=2;for(var f=0;f<h;f+=2){var u=o[f+1],s=f+3<h?o[f+3]:-1,p=f+5<h?o[f+5]:-1,y=f==0?-1:o[f-1];if(u==0&&s==u&&p==u){for(var g=f+5;g+2<h&&o[g+2]==u;)g+=2;var v=Math.min(g+1-f>>>1,138);v<11?d.push(17,v-3):d.push(18,v-11),f+=v*2-2}else if(u==y&&s==u&&p==u){for(var g=f+5;g+2<h&&o[g+2]==u;)g+=2;var v=Math.min(g+1-f>>>1,6);d.push(16,v-3),f+=v*2-2}else d.push(u,0)}return h>>>1},n.F._hufTree=function(o,d,h){var f=[],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&&f.push({lit:p,f:o[p]});var y=f.length,g=f.slice(0);if(y==0)return 0;if(y==1){var v=f[0].lit,g=v==0?1:0;return d[(v<<1)+1]=1,d[(g<<1)+1]=1,1}f.sort(function(l,c){return l.f-c.f});var U=f[0],S=f[1],E=0,e=1,t=2;for(f[0]={lit:-1,f:U.f+S.f,l:U,r:S,d:0};e!=y-1;)E!=e&&(t==y||f[E].f<f[t].f)?U=f[E++]:U=f[t++],E!=e&&(t==y||f[E].f<f[t].f)?S=f[E++]:S=f[t++],f[e++]={lit:-1,f:U.f+S.f,l:U,r:S};var r=n.F.setDepth(f[e-1],0);for(r>h&&(n.F.restrictDepth(g,h,r),r=h),p=0;p<y;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,h){var f=0,u=1<<h-d,s=0;for(o.sort(function(y,g){return g.d==y.d?y.f-g.f:g.d-y.d}),f=0;f<o.length&&o[f].d>d;f++){var p=o[f].d;o[f].d=d,s+=u-(1<<h-p)}for(s=s>>>h-d;s>0;){var p=o[f].d;p<d?(o[f].d++,s-=1<<d-p-1):f++}for(;f>=0;f--)o[f].d==d&&s<0&&(o[f].d--,s++);s!=0&&console.log("debt left")},n.F._goodIndex=function(o,d){var h=0;return d[h|16]<=o&&(h|=16),d[h|8]<=o&&(h|=8),d[h|4]<=o&&(h|=4),d[h|2]<=o&&(h|=2),d[h|1]<=o&&(h|=1),h},n.F._writeLit=function(o,d,h,f){return n.F._putsF(h,f,d[o<<1]),f+d[(o<<1)+1]},n.F.inflate=function(o,d){var h=Uint8Array;if(o[0]==3&&o[1]==0)return d||new h(0);var f=n.F,u=f._bitsF,s=f._bitsE,p=f._decodeTiny,y=f.makeCodes,g=f.codes2map,v=f._get17,U=f.U,S=d==null;S&&(d=new h(o.length>>>2<<3));for(var E=0,e=0,t=0,r=0,l=0,c=0,_=0,m=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,m+C)),d.set(new h(o.buffer,o.byteOffset+T,C),m),b=T+C<<3,m+=C;continue}if(S&&(d=n.F._check(d,m+(1<<17))),e==1&&(x=U.flmap,w=U.fdmap,c=511,_=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 I=0;I<38;I+=2)U.itree[I]=0,U.itree[I+1]=0;for(var A=1,I=0;I<l;I++){var k=s(o,b+I*3,3);U.itree[(U.ordr[I]<<1)+1]=k,k>A&&(A=k)}b+=3*l,y(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 D=f._copyOut(U.ttree,0,t,U.ltree);c=(1<<D)-1;var $=f._copyOut(U.ttree,t,r,U.dtree);_=(1<<$)-1,y(U.ltree,D),g(U.ltree,D,x),y(U.dtree,$),g(U.dtree,$,w)}for(;;){var J=x[v(o,b)&c];b+=J&15;var Y=J>>>4;if(!(Y>>>8))d[m++]=Y;else{if(Y==256)break;var M=m+Y-254;if(Y>264){var K=U.ldef[Y-257];M=m+(K>>>3)+s(o,b,K&7),b+=K&7}var Z=w[v(o,b)&_];b+=Z&15;var be=Z>>>4,V=U.ddef[be],q=(V>>>4)+u(o,b,V&15);for(b+=V&15,S&&(d=n.F._check(d,m+(1<<17)));m<M;)d[m]=d[m++-q],d[m]=d[m++-q],d[m]=d[m++-q],d[m]=d[m++-q];m=M}}}return d.length==m?d:d.slice(0,m)},n.F._check=function(o,d){var h=o.length;if(d<=h)return o;var f=new Uint8Array(Math.max(h<<1,d));return f.set(o,0),f},n.F._decodeTiny=function(o,d,h,f,u,s){for(var p=n.F._bitsE,y=n.F._get17,g=0;g<h;){var v=o[y(f,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(f,u,2),u+=2,S=s[g-1]):U==17?(E=3+p(f,u,3),u+=3):U==18&&(E=11+p(f,u,7),u+=7);for(var e=g+E;g<e;)s[g]=S,g++}}return u},n.F._copyOut=function(o,d,h,f){for(var u=0,s=0,p=f.length>>>1;s<h;){var y=o[s+d];f[s<<1]=0,f[(s<<1)+1]=y,y>u&&(u=y),s++}for(;s<p;)f[s<<1]=0,f[(s<<1)+1]=0,s++;return u},n.F.makeCodes=function(o,d){for(var h=n.F.U,f=o.length,u,s,p,y,g,v=h.bl_count,y=0;y<=d;y++)v[y]=0;for(y=1;y<f;y+=2)v[o[y]]++;var U=h.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<f;p+=2)g=o[p+1],g!=0&&(o[p]=U[g],U[g]++)},n.F.codes2map=function(o,d,h){for(var f=o.length,u=n.F.U,s=u.rev15,p=0;p<f;p+=2)if(o[p+1]!=0)for(var y=p>>1,g=o[p+1],v=y<<4|g,U=d-g,S=o[p]<<U,E=S+(1<<U);S!=E;){var e=s[S]>>>15-d;h[e]=v,S++}},n.F.revCodes=function(o,d){for(var h=n.F.U.rev15,f=15-d,u=0;u<o.length;u+=2){var s=o[u]<<d-o[u+1];o[u]=h[s]>>>f}},n.F._putsE=function(o,d,h){h=h<<(d&7);var f=d>>>3;o[f]|=h,o[f+1]|=h>>>8},n.F._putsF=function(o,d,h){h=h<<(d&7);var f=d>>>3;o[f]|=h,o[f+1]|=h>>>8,o[f+2]|=h>>>16},n.F._bitsE=function(o,d,h){return(o[d>>>3]|o[(d>>>3)+1]<<8)>>>(d&7)&(1<<h)-1},n.F._bitsF=function(o,d,h){return(o[d>>>3]|o[(d>>>3)+1]<<8|o[(d>>>3)+2]<<16)>>>(d&7)&(1<<h)-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,h=0;h<d;h++){var f=h;f=(f&2863311530)>>>1|(f&1431655765)<<1,f=(f&3435973836)>>>2|(f&858993459)<<2,f=(f&4042322160)>>>4|(f&252645135)<<4,f=(f&4278255360)>>>8|(f&16711935)<<8,o.rev15[h]=(f>>>16|f<<16)>>>17}function u(s,p,y){for(;p--!=0;)s.push(0,y)}for(var h=0;h<32;h++)o.ldef[h]=o.of0[h]<<3|o.exb[h],o.ddef[h]=o.df0[h]<<4|o.dxb[h];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)}()}(mt)),mt.exports}var cn=hn(),un=Xt(cn);const H=class H{constructor(n,o,d,h,f){this.copy=()=>new H(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,H.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 y=this.h,g=this.m,v=this.s,U=this.f,S=this.field;const E=y*60+g,t=(E-Math.floor(E/10))*p;return y*(s*3600)+g*(s*60)+v*s+(U*2+S)-t},this.addSeconds=u=>{let s=this.copy();return s.s+=u,s.s>=60&&(s.s=0,s.m++,s.m>=60&&(s.m=0,s.h++)),s},this.addFrames=(u,s)=>{let p=this.toFrames(s);return p+=u,H.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=h||0,this.field=f||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 h=[];let f=n;for(;H.compare(f,o)<=0;)h.push(f),f=f.addSeconds(d);return h}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(n){return this.toFrames(n)*1e3/n}};H.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,h=d.videoFPScalculator.getFPS(),s=(o.currentTime-d.syncPoint.playerTime)%(60*60*24)*h+d.syncPoint.frame;if(s===0||h===0)throw new Error("Current frame is 0 or fps is 0");const p=H.calculateCurrentOffset(s,(v=n.gameParams)==null?void 0:v.offsets);if(p===void 0)throw new Error("Offset is undefined");let y=Math.floor(s-p);return y<0&&(y+=5178816),y>=5178816&&(y-=5178816),H.fromFrames(y,h)},H.calculateCurrentOffset=(n,o)=>{for(let d=1;d<o.length;d++)if(n<o[d].frame)return o[d-1].offset;return o[o.length-1].offset},H.fromFrames=(n,o)=>{let d=60,h=0;Math.floor(o)==60?(d=60,h=0):Math.floor(o)==59?(d=60,h=4):Math.floor(o)==30?(d=30,h=0):Math.floor(o)==29&&(d=30,h=2);let f=Math.floor(o*60),u=Math.floor(o*60*10),s=u*6,p=n,y=Math.floor(p/s);p-=y*s;let g=Math.floor(p/u);p-=g*u,p>=d*60&&(p+=h*(Math.floor((p-d*60)/f)+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 H(y,v,U,S,E)},H.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},H.fromStr=n=>{const d=n.split("_").map(Number);if(d.length==4){const[h,f,u,s]=d;return new H(h,f,u,s,0)}else if(d.length==5){const[h,f,u,s,p]=d;return new H(h,f,u,s,p)}else throw new Error("Invalid timecode format: "+n)},H.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[,h,f,u,s,p]=d,y=Number(h),g=Number(f),v=Number(u),U=Number(s),S=p?Number(p):0;return new H(y,g,v,U,S)};let j=H;const z={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},Q=console,fe={};Object.keys(z).forEach(a=>{fe[a]=Q[a]});const Fe="Datadog Browser SDK:",O={debug:fe.debug.bind(Q,Fe),log:fe.log.bind(Q,Fe),info:fe.info.bind(Q,Fe),warn:fe.warn.bind(Q,Fe),error:fe.error.bind(Q,Fe)},vt="https://docs.datadoghq.com",ei=`${vt}/real_user_monitoring/browser/troubleshooting`,Ye="More details:";function ti(a,n){return(...o)=>{try{return a(...o)}catch(d){O.error(n,d)}}}function Ve(a){return a!==0&&Math.random()*100<=a}function pn(a){return _n(a)&&a>=0&&a<=100}function _n(a){return typeof a=="number"}const Be=1e3,he=60*Be,ii=60*he,gn=365*(24*ii);function Le(){return new Date().getTime()}function re(){return Le()}function $e(){return performance.now()}function se(){return{relative:$e(),timeStamp:re()}}function yn(){return{relative:0,timeStamp:ni()}}function mn(a,n){return n-a}function vn(a,n){return a+n}function Sn(a){return a-ni()}let St;function ni(){return St===void 0&&(St=performance.timing.navigationStart),St}const ee=1024,ri=1024*ee,bn=/[^\\u0000-\\u007F]/;function bt(a){return bn.test(a)?window.TextEncoder!==void 0?new TextEncoder().encode(a).length:new Blob([a]).size:a.length}function xn(a){return{...a}}function si(a,n){return Object.keys(a).some(o=>a[o]===n)}function ke(a){return Object.keys(a).length===0}function oe(){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 xe(a,n){const o=oe();let d;return o.Zone&&typeof o.Zone.__symbol__=="function"&&(d=a[o.Zone.__symbol__(n)]),d||(d=a[n]),d}let je,oi=!1;function Un(a){je=a}function En(a){oi=a}function wn(a,n,o){const d=o.value;o.value=function(...h){return(je?L(d):d).apply(this,h)}}function L(a){return function(){return De(a,this,arguments)}}function De(a,n,o){try{return a.apply(n,o)}catch(d){Tn(d)}}function Tn(a){if(xt(a),je)try{je(a)}catch(n){xt(n)}}function xt(...a){oi&&O.error("[MONITOR]",...a)}function Re(a,n){return xe(oe(),"setTimeout")(L(a),n)}function ai(a){xe(oe(),"clearTimeout")(a)}function Ut(a,n){return xe(oe(),"setInterval")(L(a),n)}function di(a){xe(oe(),"clearInterval")(a)}class N{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 li(...a){return new N(n=>{const o=a.map(d=>d.subscribe(h=>n.notify(h)));return()=>o.forEach(d=>d.unsubscribe())})}function fi(a,n,o){let d=!1,h,f;return{throttled:(...u)=>{if(d){h=u;return}a(...u),d=!0,f=Re(()=>{h&&a(...h),d=!1,h=void 0},n)},cancel:()=>{ai(f),d=!1,h=void 0}}}function ae(){}function de(a){return a?(parseInt(a,10)^Math.random()*16>>parseInt(a,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,de)}const Ke=/([\\w-]+)\\s*=\\s*([^;]+)/g;function Cn(a,n){for(Ke.lastIndex=0;;){const o=Ke.exec(a);if(o){if(o[1]===n)return o[2]}else break}}function An(a){const n=new Map;for(Ke.lastIndex=0;;){const o=Ke.exec(a);if(o)n.set(o[1],o[2]);else break}return n}function In(a,n,o=""){const d=a.charCodeAt(n-1),f=d>=55296&&d<=56319?n+1:n;return a.length<=f?a:`${a.slice(0,f)}${o}`}function Fn(){return Bn()===0}let qe;function Bn(){return qe??(qe=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 Pe(a,n,o=0,d){const h=new Date;h.setTime(h.getTime()+o);const f=`expires=${h.toUTCString()}`,u=d&&d.crossSite?"none":"strict",s=d&&d.domain?`;domain=${d.domain}`:"",p=d&&d.secure?";secure":"",y=d&&d.partitioned?";partitioned":"";document.cookie=`${a}=${n};${f};path=/;samesite=${u}${s}${p}${y}`}function Et(a){return Cn(document.cookie,a)}let wt;function ce(a){return wt||(wt=An(document.cookie)),wt.get(a)}function hi(a,n){Pe(a,"",0,n)}function kn(a){if(document.cookie===void 0||document.cookie===null)return!1;try{const n=`dd_cookie_test_${de()}`,o="test";Pe(n,o,he,a);const d=Et(n)===o;return hi(n,a),d}catch(n){return O.error(n),!1}}let Tt;function Dn(){if(Tt===void 0){const a=`dd_site_test_${de()}`,n="test",o=window.location.hostname.split(".");let d=o.pop();for(;o.length&&!Et(a);)d=`${o.pop()}.${d}`,Pe(a,n,Be,{domain:d});hi(a,{domain:d}),Tt=d}return Tt}const Ue="_dd_s";function We(a){return Object.values(a)}function Rn(a){return Object.entries(a)}const Ct=4*ii,ci=15*he,Pn=gn,ze={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},ui=/^([a-zA-Z]+)=([a-z0-9-]+)$/,At="&";function zn(a){return!!a&&(a.indexOf(At)!==-1||ui.test(a))}const On="1";function ue(a,n){const o={isExpired:On};return n.trackAnonymousUser&&(a!=null&&a.anonymousId?o.anonymousId=a==null?void 0:a.anonymousId:o.anonymousId=de()),o}function Je(a){return ke(a)}function pi(a){return!Je(a)}function Xe(a){return a.isExpired!==void 0||!Mn(a)}function Mn(a){return(a.created===void 0||Le()-Number(a.created)<Ct)&&(a.expire===void 0||Le()<Number(a.expire))}function _i(a){a.expire=String(Le()+ci)}function It(a){return Rn(a).map(([n,o])=>n==="anonymousId"?`aid=${o}`:`${n}=${o}`).join(At)}function gi(a){const n={};return zn(a)&&a.split(At).forEach(o=>{const d=ui.exec(o);if(d!==null){const[,h,f]=d;h==="aid"?n.anonymousId=f:n[h]=f}}),n}const Nn="_dd",Gn="_dd_r",Hn="_dd_l",Yn="rum",Vn="logs";function $n(a){if(!ce(Ue)){const o=ce(Nn),d=ce(Gn),h=ce(Hn),f={};o&&(f.id=o),h&&/^[01]$/.test(h)&&(f[Vn]=h),d&&/^[012]$/.test(d)&&(f[Yn]=d),pi(f)&&(_i(f),a.persistSession(f))}}function yi(a){const n=Jn(a);return kn(n)?{type:ze.COOKIE,cookieOptions:n}:void 0}function jn(a,n){const o={isLockEnabled:Fn(),persistSession:Kn(n),retrieveSession:Wn,expireSession:d=>qn(n,d,a)};return $n(o),o}function Kn(a){return n=>{Pe(Ue,It(n),ci,a)}}function qn(a,n,o){const d=ue(n,o);Pe(Ue,It(d),o.trackAnonymousUser?Pn:Ct,a)}function Wn(){const a=Et(Ue);return gi(a)}function Jn(a){const n={};return n.secure=!!a.useSecureSessionCookie||!!a.usePartitionedCrossSiteSessionCookie,n.crossSite=!!a.usePartitionedCrossSiteSessionCookie,n.partitioned=!!a.usePartitionedCrossSiteSessionCookie,a.trackSessionAcrossSubdomains&&(n.domain=Dn()),n}const Xn="_dd_test_";function mi(){try{const a=de(),n=`${Xn}${a}`;localStorage.setItem(n,a);const o=localStorage.getItem(n);return localStorage.removeItem(n),a===o?{type:ze.LOCAL_STORAGE}:void 0}catch{return}}function Zn(a){return{isLockEnabled:!1,persistSession:vi,retrieveSession:Qn,expireSession:n=>er(n,a)}}function vi(a){localStorage.setItem(Ue,It(a))}function Qn(){const a=localStorage.getItem(Ue);return gi(a)}function er(a,n){vi(ue(a,n))}const tr=10,ir=100,Si=[];let Ze;function pe(a,n,o=0){var d;const{isLockEnabled:h,persistSession:f,expireSession:u}=n,s=U=>f({...U,lock:y}),p=()=>{const U=n.retrieveSession(),S=U.lock;return U.lock&&delete U.lock,{session:U,lock:S}};if(Ze||(Ze=a),a!==Ze){Si.push(a);return}if(h&&o>=ir){bi(n);return}let y,g=p();if(h){if(g.lock){Qe(a,n,o);return}if(y=de(),s(g.session),g=p(),g.lock!==y){Qe(a,n,o);return}}let v=a.process(g.session);if(h&&(g=p(),g.lock!==y)){Qe(a,n,o);return}if(v&&(Xe(v)?u(v):(_i(v),h?s(v):f(v))),h&&!(v&&Xe(v))){if(g=p(),g.lock!==y){Qe(a,n,o);return}f(g.session),v=g.session}(d=a.after)===null||d===void 0||d.call(a,v||g.session),bi(n)}function Qe(a,n,o){Re(()=>{pe(a,n,o+1)},tr)}function bi(a){Ze=void 0;const n=Si.shift();n&&pe(n,a)}const xi=Be;function nr(a){switch(a.sessionPersistence){case ze.COOKIE:return yi(a);case ze.LOCAL_STORAGE:return mi();case void 0:{let n=yi(a);return!n&&a.allowFallbackToLocalStorage&&(n=mi()),n}default:O.error(`Invalid session persistence \'${String(a.sessionPersistence)}\'`)}}function rr(a,n,o,d){const h=new N,f=new N,u=new N,s=a.type===ze.COOKIE?jn(n,a.cookieOptions):Zn(n),{expireSession:p}=s,y=Ut(E,xi);let g;t();const{throttled:v,cancel:U}=fi(()=>{pe({process:x=>{if(Je(x))return;const w=e(x);return r(w),w},after:x=>{pi(x)&&!l()&&m(x),g=x}},s)},xi);function S(){pe({process:x=>l()?e(x):void 0},s)}function E(){pe({process:x=>Xe(x)?ue(x,n):void 0,after:e},s)}function e(x){return Xe(x)&&(x=ue(x,n)),l()&&(c(x)?_():(u.notify({previousState:g,newState:x}),g=x)),x}function t(){pe({process:x=>{if(Je(x))return ue(x,n)},after:x=>{g=x}},s)}function r(x){if(Je(x))return!1;const{trackingType:w,isTracked:T}=d(x[o]);x[o]=w,delete x.isExpired,T&&!x.id&&(x.id=de(),x.created=String(Le()))}function l(){return g[o]!==void 0}function c(x){return g.id!==x.id||g[o]!==x[o]}function _(){g=ue(g,n),f.notify()}function m(x){g=x,h.notify()}function b(x){pe({process:w=>({...w,...x}),after:e},s)}return{expandOrRenewSession:v,expandSession:S,getSession:()=>g,renewObservable:h,expireObservable:f,sessionStateUpdateObservable:u,restartSession:t,expire:()=>{U(),p(g),e(ue(g,n))},stop:()=>{di(y)},updateSessionState:b}}const Ft={GRANTED:"granted",NOT_GRANTED:"not-granted"};function sr(a){const n=new N;return{tryToInit(o){a||(a=o)},update(o){a=o,n.notify()},isGranted(){return a===Ft.GRANTED},observable:n}}function _e(a,n,o){if(typeof a!="object"||a===null)return JSON.stringify(a);const d=Ee(Object.prototype),h=Ee(Array.prototype),f=Ee(Object.getPrototypeOf(a)),u=Ee(a);try{return JSON.stringify(a,n,o)}catch{return"<error: unable to serialize object>"}finally{d(),h(),f(),u()}}function Ee(a){const n=a,o=n.toJSON;return o?(delete n.toJSON,()=>{n.toJSON=o}):ae}function Bt(a){return or(a,location.href).href}function or(a,n){const o=ar();if(o)try{return n!==void 0?new o(a,n):new o(a)}catch(f){throw new Error(`Failed to construct URL: ${String(f)} ${_e({url:a,base:n})}`)}if(n===void 0&&!/:/.test(a))throw new Error(`Invalid URL: \'${a}\'`);let d=document;const h=d.createElement("a");if(n!==void 0){d=document.implementation.createHTMLDocument("");const f=d.createElement("base");f.href=n,d.head.appendChild(f),d.body.appendChild(h)}return h.href=a,h}const Ui=URL;let et;function ar(){if(et===void 0)try{et=new Ui("http://test/path").href==="http://test/path"}catch{et=!1}return et?Ui:void 0}const dr="datad0g.com",lr="dd0g-gov.com",we="datadoghq.com",fr="ddog-gov.com",hr="pci.browser-intake-datadoghq.com",cr=["ddsource","ddtags"];function Oe(a,n,o){const d=ur(a,n);return{build(h,f){const u=_r(a,n,o,h,f);return d(u)},urlPrefix:d(""),trackType:n}}function ur(a,n){const o=`/api/v2/${n}`,d=a.proxy;if(typeof d=="string"){const f=Bt(d);return u=>`${f}?ddforward=${encodeURIComponent(`${o}?${u}`)}`}if(typeof d=="function")return f=>d({path:o,parameters:f});const h=pr(n,a);return f=>`https://${h}${o}?${f}`}function pr(a,n){const{site:o=we,internalAnalyticsSubdomain:d}=n;if(a==="logs"&&n.usePciIntake&&o===we)return hr;if(d&&o===we)return`${d}.${we}`;if(o===lr)return`http-intake.logs.${o}`;const h=o.split("."),f=h.pop();return`browser-intake-${h.join("-")}.${f}`}function _r({clientToken:a,internalAnalyticsSubdomain:n},o,d,h,{retry:f,encoding:u}){const s=["sdk_version:6.5.0",`api:${h}`].concat(d);f&&s.push(`retry_count:${f.count}`,`retry_after:${f.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=${de()}`];return u&&p.push(`dd-evp-encoding=${u}`),o==="rum"&&p.push(`batch_time=${re()}`),n&&p.reverse(),p.join("&")}const gr=200;function yr(a){const{env:n,service:o,version:d,datacenter:h}=a,f=[];return n&&f.push(tt("env",n)),o&&f.push(tt("service",o)),d&&f.push(tt("version",d)),h&&f.push(tt("datacenter",h)),f}function tt(a,n){const o=gr-a.length-1;(n.length>o||mr(n))&&O.warn(`${a} value doesn\'t meet tag requirements and will be sanitized. ${Ye} ${vt}/getting_started/tagging/#defining-tags`);const d=n.replace(/,/g,"_");return`${a}:${d}`}function mr(a){return vr()?new RegExp("[^\\\\p{Ll}\\\\p{Lo}0-9_:./-]","u").test(a):!1}function vr(){try{return new RegExp("[\\\\p{Ll}]","u"),!0}catch{return!1}}function Sr(a){const n=a.site||we,o=yr(a),d=br(a,o);return{replica:xr(a,o),site:n,...d}}function br(a,n){return{logsEndpointBuilder:Oe(a,"logs",n),rumEndpointBuilder:Oe(a,"rum",n),sessionReplayEndpointBuilder:Oe(a,"replay",n)}}function xr(a,n){if(!a.replica)return;const o={...a,site:we,clientToken:a.replica.clientToken},d={logsEndpointBuilder:Oe(o,"logs",n),rumEndpointBuilder:Oe(o,"rum",n)};return{applicationId:a.replica.applicationId,...d}}function Ur(a){return cr.every(n=>a.includes(n))}function Lt(a,n){return a!=null&&typeof a!="string"?(O.error(`${n} must be defined as a string`),!1):!0}function Er(a){return a&&typeof a=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(a)?(O.error(`Site should be a valid Datadog site. ${Ye} ${vt}/getting_started/site/.`),!1):!0}function it(a,n){return a!==void 0&&!pn(a)?(O.error(`${n} Sample Rate should be a number between 0 and 100`),!1):!0}function wr(a){var n,o,d,h,f,u;if(!a||!a.clientToken){O.error("Client Token is not configured, we will not send any data.");return}if(!(!Er(a.site)||!it(a.sessionSampleRate,"Session")||!it(a.telemetrySampleRate,"Telemetry")||!it(a.telemetryConfigurationSampleRate,"Telemetry Configuration")||!it(a.telemetryUsageSampleRate,"Telemetry Usage")||!Lt(a.version,"Version")||!Lt(a.env,"Env")||!Lt(a.service,"Service"))){if(a.trackingConsent!==void 0&&!si(Ft,a.trackingConsent)){O.error(\'Tracking Consent should be either "granted" or "not-granted"\');return}return{beforeSend:a.beforeSend&&ti(a.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:nr(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:(h=a.telemetryUsageSampleRate)!==null&&h!==void 0?h:5,service:a.service||void 0,silentMultipleInit:!!a.silentMultipleInit,allowUntrustedEvents:!!a.allowUntrustedEvents,trackingConsent:(f=a.trackingConsent)!==null&&f!==void 0?f:Ft.GRANTED,trackAnonymousUser:(u=a.trackAnonymousUser)!==null&&u!==void 0?u:!0,storeContextsAcrossPages:!!a.storeContextsAcrossPages,batchBytesLimit:16*ee,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*Be,batchMessagesLimit:50,messageBytesLimit:256*ee,...Sr(a)}}}function Tr(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 kt;(function(a){a.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",a.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(kt||(kt={}));const Ei=new Set;function Cr(a){Array.isArray(a)&&Ar(a.filter(n=>si(kt,n)))}function Ar(a){a.forEach(n=>{Ei.add(n)})}function Ir(){return Ei}const Me="?";function te(a){const n=[];let o=Dt(a,"stack");const d=String(a);return o&&o.startsWith(d)&&(o=o.slice(d.length)),o&&o.split(`\n`).forEach(h=>{const f=Lr(h)||Dr(h)||Pr(h)||Mr(h);f&&(!f.func&&f.line&&(f.func=Me),n.push(f))}),{message:Dt(a,"message"),name:Dt(a,"name"),stack:n}}const wi="((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\\\w+\\\\.|\\\\/).*?)",Te="(?::(\\\\d+))",Fr=new RegExp(`^\\\\s*at (.*?) ?\\\\(${wi}${Te}?${Te}?\\\\)?\\\\s*$`,"i"),Br=new RegExp(`\\\\((\\\\S*)${Te}${Te}\\\\)`);function Lr(a){const n=Fr.exec(a);if(!n)return;const o=n[2]&&n[2].indexOf("native")===0,d=n[2]&&n[2].indexOf("eval")===0,h=Br.exec(n[2]);return d&&h&&(n[2]=h[1],n[3]=h[2],n[4]=h[3]),{args:o?[n[2]]:[],column:n[4]?+n[4]:void 0,func:n[1]||Me,line:n[3]?+n[3]:void 0,url:o?void 0:n[2]}}const kr=new RegExp(`^\\\\s*at ?${wi}${Te}?${Te}??\\\\s*$`,"i");function Dr(a){const n=kr.exec(a);if(n)return{args:[],column:n[3]?+n[3]:void 0,func:Me,line:n[2]?+n[2]:void 0,url:n[1]}}const Rr=/^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;function Pr(a){const n=Rr.exec(a);if(n)return{args:[],column:n[4]?+n[4]:void 0,func:n[1]||Me,line:+n[3],url:n[2]}}const zr=/^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i,Or=/(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;function Mr(a){const n=zr.exec(a);if(!n)return;const o=n[3]&&n[3].indexOf(" > eval")>-1,d=Or.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]||Me,line:n[4]?+n[4]:void 0,url:n[3]}}function Dt(a,n){if(typeof a!="object"||!a||!(n in a))return;const o=a[n];return typeof o=="string"?o:void 0}function Nr(a,n,o,d){const h=[{url:n,column:d,line:o}],{name:f,message:u}=Hr(a);return{name:f,message:u,stack:h}}const Gr=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\\s\\S]*)$/;function Hr(a){let n,o;return{}.toString.call(a)==="[object String]"&&([,n,o]=Gr.exec(a)),{name:n,message:o}}function nt(a){const o=new Error(a);o.name="HandlingStack";let d;return De(()=>{const h=te(o);h.stack=h.stack.slice(2),d=ge(h)}),d}function ge(a){let n=Ti(a);return a.stack.forEach(o=>{const d=o.func==="?"?"<anonymous>":o.func,h=o.args&&o.args.length>0?`(${o.args.join(", ")})`:"",f=o.line?`:${o.line}`:"",u=o.line&&o.column?`:${o.column}`:"";n+=`\n at ${d}${h} @ ${o.url}${f}${u}`}),n}function Ti(a){return`${a.name||"Error"}: ${a.message}`}function ye(a,n,o,{computeHandlingStack:d}={}){let h=a[n];if(typeof h!="function")if(n in a&&n.startsWith("on"))h=ae;else return{stop:ae};let f=!1;const u=function(){if(f)return h.apply(this,arguments);const s=Array.from(arguments);let p;De(o,null,[{target:this,parameters:s,onPostCall:g=>{p=g},handlingStack:d?nt("instrumented method"):void 0}]);const y=h.apply(this,s);return p&&De(p,null,[y]),y};return a[n]=u,{stop:()=>{f=!0,a[n]===u&&(a[n]=h)}}}const Yr=220*ee,Vr="$",$r=3;function ie(a,n=Yr){const o=Ee(Object.prototype),d=Ee(Array.prototype),h=[],f=new WeakMap,u=Rt(a,Vr,void 0,h,f),s=JSON.stringify(u);let p=s?s.length:0;if(p>n){zt(n,"discarded",a);return}for(;h.length>0&&p<n;){const y=h.shift();let g=0;if(Array.isArray(y.source))for(let v=0;v<y.source.length;v++){const U=Rt(y.source[v],y.path,v,h,f);if(U!==void 0?p+=JSON.stringify(U).length:p+=4,p+=g,g=1,p>n){zt(n,"truncated",a);break}y.target[v]=U}else for(const v in y.source)if(Object.prototype.hasOwnProperty.call(y.source,v)){const U=Rt(y.source[v],y.path,v,h,f);if(U!==void 0&&(p+=JSON.stringify(U).length+g+v.length+$r,g=1),p>n){zt(n,"truncated",a);break}y.target[v]=U}}return o(),d(),u}function Rt(a,n,o,d,h){const f=qr(a);if(!f||typeof f!="object")return jr(f);const u=Pt(f);if(u!=="[Object]"&&u!=="[Array]"&&u!=="[Error]")return u;const s=a;if(h.has(s))return`[Reference seen at ${h.get(s)}]`;const p=o!==void 0?`${n}.${o}`:n,y=Array.isArray(f)?[]:{};return h.set(s,p),d.push({source:f,target:y,path:p}),y}function jr(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 Pt(a){try{if(a instanceof Event)return Kr(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 Kr(a){return{type:a.type,isTrusted:a.isTrusted,currentTarget:a.currentTarget?Pt(a.currentTarget):null,target:a.target?Pt(a.target):null}}function qr(a){const n=a;if(n&&typeof n.toJSON=="function")try{return n.toJSON()}catch{}return a}function zt(a,n,o){O.warn(`The data provided has been ${n} as it is over the limit of ${a} characters:`,o)}const Ci="No stack, consider using an instance of Error";function Ai({stackTrace:a,originalError:n,handlingStack:o,componentStack:d,startClocks:h,nonErrorPrefix:f,source:u,handling:s}){const p=le(n),y=Wr(a,p,f,n),g=Jr(p,a)?ge(a):Ci,v=p?Bi(n,u):void 0,U=a?a.name:void 0,S=Ii(n),E=Fi(n);return{startClocks:h,source:u,handling:s,handlingStack:o,componentStack:d,originalError:n,type:U,message:y,stack:g,causes:v,fingerprint:S,context:E}}function Wr(a,n,o,d){return a!=null&&a.message&&(a!=null&&a.name)?a.message:n?"Empty message":`${o} ${_e(ie(d))}`}function Jr(a,n){return n===void 0?!1:a?!0:n.stack.length>0&&(n.stack.length>1||n.stack[0].url!==void 0)}function Ii(a){return le(a)&&"dd_fingerprint"in a?String(a.dd_fingerprint):void 0}function Fi(a){if(a!==null&&typeof a=="object"&&"dd_context"in a)return a.dd_context}function Xr(a){var n;return(n=/@ (.+)/.exec(a))===null||n===void 0?void 0:n[1]}function le(a){return a instanceof Error||Object.prototype.toString.call(a)==="[object Error]"}function Bi(a,n){let o=a;const d=[];for(;le(o==null?void 0:o.cause)&&d.length<10;){const h=te(o.cause);d.push({message:o.cause.message,source:n,type:h==null?void 0:h.name,stack:ge(h)}),o=o.cause}return d.length?d:void 0}const W={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function Zr(a){const n=(h,f)=>{const u=Ai({stackTrace:h,originalError:f,startClocks:se(),nonErrorPrefix:"Uncaught",source:W.SOURCE,handling:"unhandled"});a.notify(u)},{stop:o}=Qr(n),{stop:d}=es(n);return{stop:()=>{o(),d()}}}function Qr(a){return ye(window,"onerror",({parameters:[n,o,d,h,f]})=>{let u;le(f)?u=te(f):u=Nr(n,o,d,h),a(u,f??n)})}function es(a){return ye(window,"onunhandledrejection",({parameters:[n]})=>{const o=n.reason||"Empty reason",d=te(o);a(d,o)})}function ts(a){const n={version:"6.5.0",onReady(o){o()},...a};return Object.defineProperty(n,"_setDebug",{get(){return En},enumerable:!1}),n}function is(a,n,o){const d=a[n];d&&!d.q&&d.version&&O.warn("SDK is loaded more than once. This is unsupported and might have unexpected behavior."),a[n]=o,d&&d.q&&d.q.forEach(h=>ti(h,"onReady callback threw an error:")())}function Li(a,n){n.silentMultipleInit||O.error(`${a} is already initialized.`)}function me(a,n,o,d,h){return Ot(a,n,[o],d,h)}function Ot(a,n,o,d,{once:h,capture:f,passive:u}={}){const s=L(U=>{!U.isTrusted&&!U.__ddIsTrusted&&!a.allowUntrustedEvents||(h&&v(),d(U))}),p=u?{capture:f,passive:u}:f,y=window.EventTarget&&n instanceof EventTarget?window.EventTarget.prototype:n,g=xe(y,"addEventListener");o.forEach(U=>g.call(n,U,s,p));function v(){const U=xe(y,"removeEventListener");o.forEach(S=>U.call(n,S,s,p))}return{stop:v}}const rt={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function ns(a,n){const o=[];n.includes(rt.cspViolation)&&o.push(ss(a));const d=n.filter(h=>h!==rt.cspViolation);return d.length&&o.push(rs(d)),li(...o)}function rs(a){return new N(n=>{if(!window.ReportingObserver)return;const o=L((h,f)=>h.forEach(u=>n.notify(os(u)))),d=new window.ReportingObserver(o,{types:a,buffered:!0});return d.observe(),()=>{d.disconnect()}})}function ss(a){return new N(n=>{const{stop:o}=me(a,document,"securitypolicyviolation",d=>{n.notify(as(d))});return o})}function os(a){const{type:n,body:o}=a;return ki({type:o.id,message:`${n}: ${o.message}`,originalError:a,stack:Di(o.id,o.message,o.sourceFile,o.lineNumber,o.columnNumber)})}function as(a){const n=`\'${a.blockedURI}\' blocked by \'${a.effectiveDirective}\' directive`;return ki({type:a.effectiveDirective,message:`${rt.cspViolation}: ${n}`,originalError:a,csp:{disposition:a.disposition},stack:Di(a.effectiveDirective,a.originalPolicy?`${n} of the policy "${In(a.originalPolicy,100,"...")}"`:"no policy",a.sourceFile,a.lineNumber,a.columnNumber)})}function ki(a){return{startClocks:se(),source:W.REPORT,handling:"unhandled",...a}}function Di(a,n,o,d,h){return o?ge({name:a,message:n,stack:[{func:"?",url:o,line:d??void 0,column:h??void 0}]}):void 0}function Ri(a,n){const o=window.__ddBrowserSdkExtensionCallback;o&&o({type:a,payload:n})}function Pi(a){return a===null?"null":Array.isArray(a)?"array":typeof a}function st(a,n,o=ds()){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 h=n.flags||[n.global?"g":"",n.ignoreCase?"i":"",n.multiline?"m":"",n.sticky?"y":"",n.unicode?"u":""].join("");return new RegExp(n.source,h)}if(o.hasAlreadyBeenSeen(n))return;if(Array.isArray(n)){const h=Array.isArray(a)?a:[];for(let f=0;f<n.length;++f)h[f]=st(h[f],n[f],o);return h}const d=Pi(a)==="object"?a:{};for(const h in n)Object.prototype.hasOwnProperty.call(n,h)&&(d[h]=st(d[h],n[h],o));return d}function zi(a){return st(void 0,a)}function Ce(...a){let n;for(const o of a)o!=null&&(n=st(n,o));return n}function ds(){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 ls(){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 fs(a){const n=new Set;return a.forEach(o=>n.add(o)),Array.from(n)}function Oi(a,n){const o=a.indexOf(n);o>=0&&a.splice(o,1)}const hs=500;function Mi(){const a=[];return{add:h=>{a.push(h)>hs&&a.splice(0,1)},remove:h=>{Oi(a,h)},drain:h=>{a.forEach(f=>f(h)),a.length=0}}}const ve={log:"log",configuration:"configuration",usage:"usage"},cs=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],us=[fr];let Ni=Mi(),Ae=a=>{Ni.add(()=>Ae(a))};function ps(a,n){let o;const d=new N,h=new Set,f=!us.includes(n.site)&&Ve(n.telemetrySampleRate),u={[ve.log]:f,[ve.configuration]:f&&Ve(n.telemetryConfigurationSampleRate),[ve.usage]:f&&Ve(n.telemetryUsageSampleRate)},s=_s();Ae=y=>{const g=_e(y);if(u[y.type]&&h.size<n.maxTelemetryEventsPerPage&&!h.has(g)){const v=p(a,y,s);d.notify(v),Ri("telemetry",v),h.add(g)}},Un(Hi);function p(y,g,v){return Ce({type:"telemetry",date:re(),service:y,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:Ce(g,{runtime_env:v,connectivity:ls(),sdk_setup:"npm"}),experimental_features:Array.from(Ir())},o!==void 0?o():{})}return{setContextProvider:y=>{o=y},observable:d,enabled:f}}function _s(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function gs(){Ni.drain()}function ys(a){return a.site===dr}function Gi(a,n){xt(z.debug,a,n),Ae({type:ve.log,message:a,status:"debug",...n})}function Hi(a,n){Ae({type:ve.log,status:"error",...Ss(a),...n})}function ms(a){Ae({type:ve.configuration,configuration:a})}function vs(a){Ae({type:ve.usage,usage:a})}function Ss(a){if(le(a)){const n=te(a);return{error:{kind:n.name,stack:ge(bs(n))},message:n.message}}return{error:{stack:Ci},message:`Uncaught ${_e(a)}`}}function bs(a){return a.stack=a.stack.filter(n=>!n.url||cs.some(o=>n.url.startsWith(o))),a}const Ne=1/0,xs=he;let Ge=null;const ot=new Set;function Us(){ot.forEach(a=>a())}function Es({expireDelay:a,maxEntries:n}){let o=[];const d=[];Ge||(Ge=Ut(()=>Us(),xs));const h=()=>{const S=$e()-a;for(;o.length>0&&o[o.length-1].endTime<S;){const E=o.pop();E&&d.push(E.startTime)}};ot.add(h);function f(S,E){const e={value:S,startTime:E,endTime:Ne,remove:()=>{Oi(o,e)},close:t=>{e.endTime=t}};return n&&o.length>=n&&o.pop(),o.unshift(e),e}function u(S=Ne,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===Ne&&E.close(S)}function p(S=Ne,E=0){const e=vn(S,E);return o.filter(t=>t.startTime<=e&&S<=t.endTime).map(t=>t.value)}function y(){return o.map(({startTime:S,endTime:E,value:e})=>({startTime:S,endTime:E===Ne?"Infinity":E,value:e}))}function g(){return d}function v(){o=[]}function U(){ot.delete(h),ot.size===0&&Ge&&(di(Ge),Ge=null)}return{add:f,find:u,closeActive:s,findAll:p,reset:v,stop:U,getAllEntries:y,getDeletedEntries:g}}const ws=he,Ts=Ct;function Cs(a,n,o,d){const h=new N,f=new N,u=rr(a.sessionStoreStrategyType,a,n,o),s=Es({expireDelay:Ts});u.renewObservable.subscribe(()=>{s.add(p(),$e()),h.notify()}),u.expireObservable.subscribe(()=>{f.notify(),s.closeActive($e())}),u.expandOrRenewSession(),s.add(p(),yn().relative),d.observable.subscribe(()=>{d.isGranted()?u.expandOrRenewSession():u.expire()}),As(a,()=>{d.isGranted()&&u.expandOrRenewSession()}),Is(a,()=>u.expandSession()),Fs(a,()=>u.restartSession());function p(){return{id:u.getSession().id,trackingType:u.getSession()[n],isReplayForced:!!u.getSession().forcedReplay,anonymousId:u.getSession().anonymousId}}return{findSession:(y,g)=>s.find(y,g),renewObservable:h,expireObservable:f,sessionStateUpdateObservable:u.sessionStateUpdateObservable,expire:u.expire,updateSessionState:u.updateSessionState}}function As(a,n){Ot(a,window,["click","touchstart","keydown","scroll"],n,{capture:!0,passive:!0})}function Is(a,n){const o=()=>{document.visibilityState==="visible"&&n()};me(a,document,"visibilitychange",o),Ut(o,ws)}function Fs(a,n){me(a,window,"resume",n,{capture:!0})}function Yi(a){return a>=500}function Bs(a){try{return a.clone()}catch{return}}const Ls=80*ee,ks=32,Vi=3*ri,Ds=he,$i=Be;function ji(a,n,o,d,h){n.transportStatus===0&&n.queuedPayloads.size()===0&&n.bandwidthMonitor.canHandle(a)?qi(a,n,o,{onSuccess:()=>Wi(0,n,o,d,h),onFailure:()=>{n.queuedPayloads.enqueue(a),Ki(n,o,d,h)}}):n.queuedPayloads.enqueue(a)}function Ki(a,n,o,d){a.transportStatus===2&&Re(()=>{const h=a.queuedPayloads.first();qi(h,a,n,{onSuccess:()=>{a.queuedPayloads.dequeue(),a.currentBackoffTime=$i,Wi(1,a,n,o,d)},onFailure:()=>{a.currentBackoffTime=Math.min(Ds,a.currentBackoffTime*2),Ki(a,n,o,d)}})},a.currentBackoffTime)}function qi(a,n,o,{onSuccess:d,onFailure:h}){n.bandwidthMonitor.add(a),o(a,f=>{n.bandwidthMonitor.remove(a),Rs(f)?(n.transportStatus=n.bandwidthMonitor.ongoingRequestCount>0?1:2,a.retry={count:a.retry?a.retry.count+1:1,lastFailureStatus:f.status},h()):(n.transportStatus=0,d())})}function Wi(a,n,o,d,h){a===0&&n.queuedPayloads.isFull()&&!n.queueFullReported&&(h({message:`Reached max ${d} events size queued for upload: ${Vi/ri}MiB`,source:W.AGENT,startClocks:se()}),n.queueFullReported=!0);const f=n.queuedPayloads;for(n.queuedPayloads=Ji();f.size()>0;)ji(f.dequeue(),n,o,d,h)}function Rs(a){return a.type!=="opaque"&&(a.status===0&&!navigator.onLine||a.status===408||a.status===429||Yi(a.status))}function Ps(){return{transportStatus:0,currentBackoffTime:$i,bandwidthMonitor:zs(),queuedPayloads:Ji(),queueFullReported:!1}}function Ji(){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>=Vi}}}function zs(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(a){return this.ongoingRequestCount===0||this.ongoingByteCount+a.bytesCount<=Ls&&this.ongoingRequestCount<ks},add(a){this.ongoingRequestCount+=1,this.ongoingByteCount+=a.bytesCount},remove(a){this.ongoingRequestCount-=1,this.ongoingByteCount-=a.bytesCount}}}function Os(a,n,o){const d=Ps(),h=(f,u)=>Gs(a,n,f,u);return{send:f=>{ji(f,d,h,a.trackType,o)},sendOnExit:f=>{Ms(a,n,f)}}}function Ms(a,n,o){if(!!navigator.sendBeacon&&o.bytesCount<n)try{const f=a.build("beacon",o);if(navigator.sendBeacon(f,o.data))return}catch(f){Ns(f)}const h=a.build("xhr",o);Mt(h,o.data)}let Xi=!1;function Ns(a){Xi||(Xi=!0,Hi(a))}function Gs(a,n,o,d){if(Hs()&&o.bytesCount<n){const f=a.build("fetch",o);fetch(f,{method:"POST",body:o.data,keepalive:!0,mode:"cors"}).then(L(u=>d==null?void 0:d({status:u.status,type:u.type})),L(()=>{const u=a.build("xhr",o);Mt(u,o.data,d)}))}else{const f=a.build("xhr",o);Mt(f,o.data,d)}}function Hs(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function Mt(a,n,o){const d=new XMLHttpRequest;d.open("POST",a,!0),n instanceof Blob&&d.setRequestHeader("Content-Type",n.type),me({allowUntrustedEvents:!0},d,"loadend",()=>{o==null||o({status:d.status})},{once:!0}),d.send(n)}function Nt(){const a=Ys();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 h=d?{id:d}:void 0;a.send(JSON.stringify({eventType:n,event:o,view:h}))}}}function at(a){var n;a===void 0&&(a=(n=oe().location)===null||n===void 0?void 0:n.hostname);const o=Nt();return!!o&&o.getAllowedWebViewHosts().some(d=>a===d||a.endsWith(`.${d}`))}function Ys(){return oe().DatadogEventBridge}const dt={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function Vs(a){return new N(n=>{const{stop:o}=Ot(a,window,["visibilitychange","freeze"],h=>{h.type==="visibilitychange"&&document.visibilityState==="hidden"?n.notify({reason:dt.HIDDEN}):h.type==="freeze"&&n.notify({reason:dt.FROZEN})},{capture:!0}),d=me(a,window,"beforeunload",()=>{n.notify({reason:dt.UNLOADING})}).stop;return()=>{o(),d()}})}function $s(a){return We(dt).includes(a)}function js({encoder:a,request:n,flushController:o,messageBytesLimit:d}){let h={};const f=o.flushObservable.subscribe(v=>g(v));function u(v,U,S){o.notifyBeforeAddMessage(U),S!==void 0?(h[S]=v,o.notifyAfterAddMessage()):a.write(a.isEmpty?v:`\n${v}`,E=>{o.notifyAfterAddMessage(E-U)})}function s(v){return v!==void 0&&h[v]!==void 0}function p(v){const U=h[v];delete h[v];const S=a.estimateEncodedBytesCount(U);o.notifyAfterRemoveMessage(S)}function y(v,U){const S=_e(v),E=a.estimateEncodedBytesCount(S);if(E>=d){O.warn(`Discarded a message whose size was bigger than the maximum allowed size ${d}KB. ${Ye} ${ei}/#technical-limitations`);return}s(U)&&p(U),u(S,E,U)}function g(v){const U=We(h).join(`\n`);h={};const S=$s(v.reason),E=S?n.sendOnExit:n.send;if(S&&a.isAsync){const e=a.finishSync();e.outputBytesCount&&E(Zi(e));const t=[e.pendingData,U].filter(Boolean).join(`\n`);t&&E({data:t,bytesCount:bt(t)})}else U&&a.write(a.isEmpty?U:`\n${U}`),a.finish(e=>{E(Zi(e))})}return{flushController:o,add:y,upsert:y,stop:f.unsubscribe}}function Zi(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 Ks({messagesLimit:a,bytesLimit:n,durationLimit:o,pageExitObservable:d,sessionExpireObservable:h}){const f=d.subscribe(E=>g(E.reason)),u=h.subscribe(()=>g("session_expire")),s=new N(()=>()=>{f.unsubscribe(),u.unsubscribe()});let p=0,y=0;function g(E){if(y===0)return;const e=y,t=p;y=0,p=0,S(),s.notify({reason:E,messagesCount:e,bytesCount:t})}let v;function U(){v===void 0&&(v=Re(()=>{g("duration_limit")},o))}function S(){ai(v),v=void 0}return{flushObservable:s,get messagesCount(){return y},notifyBeforeAddMessage(E){p+E>=n&&g("bytes_limit"),y+=1,p+=E,U()},notifyAfterAddMessage(E=0){p+=E,y>=a?g("messages_limit"):p>=n&&g("bytes_limit")},notifyAfterRemoveMessage(E){p-=E,y-=1,y===0&&S()}}}function Qi(a,n,o,d,h,f,u=js){const s=y(a,n),p=o&&y(a,o);function y(g,{endpoint:v,encoder:U}){return u({encoder:U,request:Os(v,g.batchBytesLimit,d),flushController:Ks({messagesLimit:g.batchMessagesLimit,bytesLimit:g.batchBytesLimit,durationLimit:g.flushTimeout,pageExitObservable:h,sessionExpireObservable:f}),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 lt(){let a="",n=0;return{isAsync:!1,get isEmpty(){return!a},write(o,d){const h=bt(o);n+=h,a+=o,d&&d(h)},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 qs{constructor(){this.callbacks={}}notify(n,o){const d=this.callbacks[n];d&&d.forEach(h=>h(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 Ws(a,n,o){let d=0,h=!1;return{isLimitReached(){if(d===0&&Re(()=>{d=0},he),d+=1,d<=n||h)return h=!1,!1;if(d===n+1){h=!0;try{o({message:`Reached max number of ${a}s by minute: ${n}`,source:W.AGENT,startClocks:se()})}finally{h=!1}}return!0}}}let Gt;const Ht=new WeakMap;function Js(a){return Gt||(Gt=Xs(a)),Gt}function Xs(a){return new N(n=>{const{stop:o}=ye(XMLHttpRequest.prototype,"open",Zs),{stop:d}=ye(XMLHttpRequest.prototype,"send",f=>{Qs(f,a,n)},{computeHandlingStack:!0}),{stop:h}=ye(XMLHttpRequest.prototype,"abort",eo);return()=>{o(),d(),h()}})}function Zs({target:a,parameters:[n,o]}){Ht.set(a,{state:"open",method:String(n).toUpperCase(),url:Bt(String(o))})}function Qs({target:a,handlingStack:n},o,d){const h=Ht.get(a);if(!h)return;const f=h;f.state="start",f.startClocks=se(),f.isAborted=!1,f.xhr=a,f.handlingStack=n;let u=!1;const{stop:s}=ye(a,"onreadystatechange",()=>{a.readyState===XMLHttpRequest.DONE&&p()}),p=()=>{if(y(),s(),u)return;u=!0;const g=h;g.state="complete",g.duration=mn(f.startClocks.timeStamp,re()),g.status=a.status,d.notify(xn(g))},{stop:y}=me(o,a,"loadend",p);d.notify(f)}function eo({target:a}){const n=Ht.get(a);n&&(n.isAborted=!0)}let Yt;function en(){return Yt||(Yt=to()),Yt}function to(){return new N(a=>{if(!window.fetch)return;const{stop:n}=ye(window,"fetch",o=>io(o,a),{computeHandlingStack:!0});return n})}function io({parameters:a,onPostCall:n,handlingStack:o},d){const[h,f]=a;let u=f&&f.method;u===void 0&&h instanceof Request&&(u=h.method);const s=u!==void 0?String(u).toUpperCase():"GET",p=h instanceof Request?h.url:Bt(String(h)),y=se(),g={state:"start",init:f,input:h,method:s,startClocks:y,url:p,handlingStack:o};d.notify(g),a[0]=g.input,a[1]=g.init,n(v=>no(d,v,g))}function no(a,n,o){const d=o;function h(f){d.state="resolve",Object.assign(d,f),a.notify(d)}n.then(L(f=>{h({response:f,responseType:f.type,status:f.status,isAborted:!1})}),L(f=>{var u,s;h({status:0,isAborted:((s=(u=d.init)===null||u===void 0?void 0:u.signal)===null||s===void 0?void 0:s.aborted)||f instanceof DOMException&&f.code===DOMException.ABORT_ERR,error:f})}))}let Vt={};function ro(a){const n=a.map(o=>(Vt[o]||(Vt[o]=so(o)),Vt[o]));return li(...n)}function so(a){return new N(n=>{const o=Q[a];return Q[a]=(...d)=>{o.apply(console,d);const h=nt("console error");De(()=>{n.notify(oo(d,a,h))})},()=>{Q[a]=o}})}function oo(a,n,o){const d=a.map(f=>ao(f)).join(" ");let h;if(n===z.error){const f=a.find(le);h={stack:f?ge(te(f)):void 0,fingerprint:Ii(f),causes:f?Bi(f,"console"):void 0,startClocks:se(),message:d,source:W.CONSOLE,handling:"handled",handlingStack:o,context:Fi(f)}}return{api:n,message:d,error:h,handlingStack:o}}function ao(a){return typeof a=="string"?ie(a):le(a)?Ti(te(a)):_e(ie(a),void 0,2)}function lo(a){const n=Pi(a)==="object";return n||O.error("Unsupported context:",a),n}function $t(a,n,o){const d={...a};for(const[h,{required:f,type:u}]of Object.entries(n))u==="string"&&h in d&&(d[h]=String(d[h])),f&&!(h in a)&&O.warn(`The property ${h} of ${o} is required; context will not be sent to the intake.`);return d}function ft(a="",{customerDataTracker:n,propertiesConfig:o={}}={}){let d={};const h=new N,f={getContext:()=>zi(d),setContext:u=>{lo(u)?(d=ie($t(u,o,a)),n==null||n.updateCustomerData(d)):f.clearContext(),h.notify()},setContextProperty:(u,s)=>{d=ie($t({...d,[u]:s},o,a)),n==null||n.updateCustomerData(d),h.notify()},removeContextProperty:u=>{delete d[u],n==null||n.updateCustomerData(d),$t(d,o,a),h.notify()},clearContext:()=>{d={},n==null||n.resetCustomerData(),h.notify()},changeObservable:h};return f}const fo="_dd_c",ho=[];function jt(a,n,o,d){const h=co(o,d);ho.push(me(a,window,"storage",({key:y})=>{h===y&&u()})),n.changeObservable.subscribe(s);const f=Ce(p(),n.getContext());ke(f)||n.setContext(f);function u(){n.setContext(p())}function s(){localStorage.setItem(h,JSON.stringify(n.getContext()))}function p(){const y=localStorage.getItem(h);return y?JSON.parse(y):{}}}function co(a,n){return`${fo}_${a}_${n}`}const uo=3*ee,po=16*ee,_o=200;function go(a=2){const n=new Map;let o=!1;function d(h=0){if(o||a===0)return;const f=a===2?uo:po;let u=h;n.forEach(s=>{u+=s.getBytesCount()}),u>f&&(yo(f),o=!0)}return{createDetachedTracker:()=>{const h=tn(()=>d(h.getBytesCount()));return h},getOrCreateTracker:h=>(n.has(h)||n.set(h,tn(d)),n.get(h)),setCompressionStatus:h=>{a===0&&(a=h,d())},getCompressionStatus:()=>a,stop:()=>{n.forEach(h=>h.stop()),n.clear()}}}function tn(a){let n=0;const{throttled:o,cancel:d}=fi(f=>{n=bt(_e(f)),a()},_o),h=()=>{d(),n=0};return{updateCustomerData:f=>{ke(f)?h():o(f)},resetCustomerData:h,getBytesCount:()=>n,stop:()=>{d()}}}function yo(a){O.warn(`Customer data exceeds the recommended ${a/ee}KiB threshold. ${Ye} ${ei}/#customer-data-exceeds-the-recommended-threshold-warning`)}function mo(a,n,o){const d=a.getReader(),h=[];let f=0;u();function u(){d.read().then(L(p=>{if(p.done){s();return}h.push(p.value),f+=p.value.length,f>o.bytesLimit?s():u()}),L(p=>n(p)))}function s(){d.cancel().catch(ae);let p,y;{let g;if(h.length===1)g=h[0];else{g=new Uint8Array(f);let v=0;h.forEach(U=>{g.set(U,v),v+=U.length})}p=g.slice(0,o.bytesLimit),y=g.length>o.bytesLimit}n(void 0,p,y)}}const vo="datadog-synthetics-public-id",So="datadog-synthetics-result-id",bo="datadog-synthetics-injects-rum";function nn(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||ce(bo))}function xo(){const a=window._DATADOG_SYNTHETICS_PUBLIC_ID||ce(vo);return typeof a=="string"?a:void 0}function Uo(){const a=window._DATADOG_SYNTHETICS_RESULT_ID||ce(So);return typeof a=="string"?a:void 0}function ht(a,n,o){const d=o.getHandler(),h=Array.isArray(d)?d:[d];return rn[a]>=rn[o.getLevel()]&&h.includes(n)}const F={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},rn={[F.ok]:0,[F.debug]:1,[F.info]:2,[F.notice]:4,[F.warn]:5,[F.error]:6,[F.critical]:7,[F.alert]:8,[F.emerg]:9};function ct(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 Eo=function(a,n,o,d){var h=arguments.length,f=h<3?n:d===null?d=Object.getOwnPropertyDescriptor(n,o):d,u;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")f=Reflect.decorate(a,n,o,d);else for(var s=a.length-1;s>=0;s--)(u=a[s])&&(f=(h<3?u(f):h>3?u(n,o,f):u(n,o))||f);return h>3&&f&&Object.defineProperty(n,o,f),f};const He={console:"console",http:"http",silent:"silent"},wo=Object.keys(F);let X=class{constructor(n,o,d,h=He.http,f=F.debug,u={}){this.handleLogStrategy=n,this.handlerType=h,this.level=f,this.contextManager=ft("logger",{customerDataTracker:o}),this.contextManager.setContext(u),d&&this.contextManager.setContextProperty("logger",{name:d})}logImplementation(n,o,d=F.info,h,f){const u=ie(o);let s;if(h!=null){const p=Ai({stackTrace:le(h)?te(h):void 0,originalError:h,nonErrorPrefix:"Provided",source:W.LOGGER,handling:"handled",startClocks:se()});s=Ce({error:ct(p,{includeMessage:!0})},u)}else s=u;this.handleLogStrategy({message:ie(n),context:s,status:d},this,f)}log(n,o,d=F.info,h){let f;ht(d,He.http,this)&&(f=nt("log")),this.logImplementation(n,o,d,h,f)}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}};Eo([wn],X.prototype,"logImplementation",null),X.prototype.ok=ne(F.ok),X.prototype.debug=ne(F.debug),X.prototype.info=ne(F.info),X.prototype.notice=ne(F.notice),X.prototype.warn=ne(F.warn),X.prototype.error=ne(F.error),X.prototype.critical=ne(F.critical),X.prototype.alert=ne(F.alert),X.prototype.emerg=ne(F.emerg);function ne(a){return function(n,o,d){let h;ht(a,He.http,this)&&(h=nt("log")),this.logImplementation(n,o,a,d,h)}}function To(a,n,o){return{view:{referrer:document.referrer,url:window.location.href},context:a.getContext(),user:n.getContext(),account:o.getContext()}}const Co=32*ee;function Ao(a){a.usePciIntake===!0&&a.site&&a.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 n=wr(a),o=sn(a.forwardConsoleLogs,We(z),"Forward Console Logs"),d=sn(a.forwardReports,We(rt),"Forward Reports");if(!(!n||!o||!d))return a.forwardErrorsToLogs&&!o.includes(z.error)&&o.push(z.error),{forwardErrorsToLogs:a.forwardErrorsToLogs!==!1,forwardConsoleLogs:o,forwardReports:d,requestErrorResponseLengthLimit:Co,...n}}function sn(a,n,o){if(a===void 0)return[];if(!(a==="all"||Array.isArray(a)&&a.every(d=>n.includes(d)))){O.error(`${o} should be "all" or an array with allowed values "${n.join(\'", "\')}"`);return}return a==="all"?n:fs(a)}function Io(a){const n=Tr(a);return{forward_errors_to_logs:a.forwardErrorsToLogs,forward_console_logs:a.forwardConsoleLogs,forward_reports:a.forwardReports,use_pci_intake:a.usePciIntake,...n}}function Fo(a,n,o){const d=Mi();let h,f;const u=n.observable.subscribe(s);function s(){if(!f||!h||!n.isGranted())return;u.unsubscribe();const p=o(h,f);d.drain(p)}return{init(p){if(!p){O.error("Missing configuration");return}if(Cr(p.enableExperimentalFeatures),at()&&(p=Bo(p)),h=p,f){Li("DD_LOGS",p);return}const y=Ao(p);y&&(f=y,en().subscribe(ae),n.tryToInit(y.trackingConsent),s())},get initConfiguration(){return h},getInternalContext:ae,handleLog(p,y,g,v=a(),U=re()){d.add(S=>S.handleLog(p,y,g,v,U))}}}function Bo(a){return{...a,clientToken:"empty"}}const Kt="logs";function Lo(a){const n=go(),o=ft("global context",{customerDataTracker:n.getOrCreateTracker(2)}),d=ft("user",{customerDataTracker:n.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),h=ft("account",{customerDataTracker:n.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),f=sr();function u(){return To(o,d,h)}let s=Fo(u,f,(g,v)=>{g.storeContextsAcrossPages&&(jt(v,o,Kt,2),jt(v,d,Kt,1),jt(v,h,Kt,4));const U=a(g,v,u,f);return s=ko(g,U),U});const p={},y=new X((...g)=>s.handleLog(...g),n.createDetachedTracker());return ts({logger:y,init:L(g=>s.init(g)),setTrackingConsent:L(g=>{f.update(g),vs({feature:"set-tracking-consent",tracking_consent:g})}),getGlobalContext:L(()=>o.getContext()),setGlobalContext:L(g=>o.setContext(g)),setGlobalContextProperty:L((g,v)=>o.setContextProperty(g,v)),removeGlobalContextProperty:L(g=>o.removeContextProperty(g)),clearGlobalContext:L(()=>o.clearContext()),createLogger:L((g,v={})=>(p[g]=new X((...U)=>s.handleLog(...U),n.createDetachedTracker(),ie(g),v.handler,v.level,ie(v.context)),p[g])),getLogger:L(g=>p[g]),getInitConfiguration:L(()=>zi(s.initConfiguration)),getInternalContext:L(g=>s.getInternalContext(g)),setUser:L(d.setContext),getUser:L(d.getContext),setUserProperty:L(d.setContextProperty),removeUserProperty:L(d.removeContextProperty),clearUser:L(d.clearContext),setAccount:L(h.setContext),getAccount:L(h.getContext),setAccountProperty:L(h.setContextProperty),removeAccountProperty:L(h.removeContextProperty),clearAccount:L(h.clearContext)})}function ko(a,n){return{init:o=>{Li("DD_LOGS",o)},initConfiguration:a,...n}}const Do="logs";function Ro(a,n){const o=Cs(a,Do,d=>zo(a,d),n);return{findTrackedSession:(d,h={returnInactive:!1})=>{const f=o.findSession(d,h);return f&&f.trackingType==="1"?{id:f.id,anonymousId:f.anonymousId}:void 0},expireObservable:o.expireObservable}}function Po(a){const o=on(a)==="1"?{}:void 0;return{findTrackedSession:()=>o,expireObservable:new N}}function on(a){return Ve(a.sessionSampleRate)?"1":"0"}function zo(a,n){const o=Oo(n)?n:on(a);return{trackingType:o,isTracked:o==="1"}}function Oo(a){return a==="0"||a==="1"}let an=!1;function ut(a){const n=window;if(nn()){const d=o(n.DD_RUM_SYNTHETICS);return!d&&!an&&(an=!0,Gi("Logs sent before RUM is injected by the synthetics worker",{testId:xo(),resultId:Uo()})),d}return o(n.DD_RUM);function o(d){if(d&&d.getInternalContext)return d.getInternalContext(a)}}function Mo(a,n,o,d,h){const f=wo.concat(["custom"]),u={};f.forEach(s=>{u[s]=Ws(s,n.eventRateLimiterThreshold,h)}),o.subscribe(0,({rawLogsEvent:s,messageContext:p=void 0,savedCommonContext:y=void 0,domainContext:g})=>{var v,U;const S=Sn(s.date),E=a.findTrackedSession(S);if(!a.findTrackedSession(S,{returnInactive:!0}))return;const t=y||d();let r;!ke(t.account)&&t.account.id&&(r=t.account),E&&E.anonymousId&&!t.user.anonymous_id&&(t.user.anonymous_id=E.anonymousId);const l=Ce({service:n.service,session_id:E?E.id:void 0,session:E?{id:E.id}:void 0,usr:ke(t.user)?void 0:t.user,account:r,view:t.view},t.context,ut(S),s,p);((v=n.beforeSend)===null||v===void 0?void 0:v.call(n,l,g))===!1||l.origin!==W.AGENT&&((U=u[l.status])!==null&&U!==void 0?U:u.custom).isLimitReached()||o.notify(1,l)})}const No={[z.log]:F.info,[z.debug]:F.debug,[z.info]:F.info,[z.warn]:F.warn,[z.error]:F.error};function Go(a,n){const o=ro(a.forwardConsoleLogs).subscribe(d=>{var h;const f={rawLogsEvent:{date:re(),message:d.message,origin:W.CONSOLE,error:d.error&&ct(d.error),status:No[d.api]},messageContext:(h=d.error)===null||h===void 0?void 0:h.context,domainContext:{handlingStack:d.handlingStack}};n.notify(0,f)});return{stop:()=>{o.unsubscribe()}}}function Ho(a,n){const o=ns(a,a.forwardReports).subscribe(d=>{let h=d.message,f;const u=d.originalError.type==="deprecation"?F.warn:F.error;u===F.error?f=ct(d):d.stack&&(h+=` Found in ${Xr(d.stack)}`),n.notify(0,{rawLogsEvent:{date:re(),message:h,origin:W.REPORT,error:f,status:u}})});return{stop:()=>{o.unsubscribe()}}}function Yo(a,n){if(!a.forwardErrorsToLogs)return{stop:ae};const o=Js(a).subscribe(f=>{f.state==="complete"&&h("xhr",f)}),d=en().subscribe(f=>{f.state==="resolve"&&h("fetch",f)});function h(f,u){!Ur(u.url)&&(Ko(u)||Yi(u.status))&&("xhr"in u?Vo(u.xhr,a,s):u.response?jo(u.response,a,s):u.error&&$o(u.error,a,s));function s(p){const y={isAborted:u.isAborted,handlingStack:u.handlingStack};n.notify(0,{rawLogsEvent:{message:`${qo(f)} 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:F.error,origin:W.NETWORK},domainContext:y})}}return{stop:()=>{o.unsubscribe(),d.unsubscribe()}}}function Vo(a,n,o){typeof a.response=="string"?o(qt(a.response,n)):o(a.response)}function $o(a,n,o){o(qt(ge(te(a)),n))}function jo(a,n,o){const d=Bs(a);!d||!d.body?o():window.TextDecoder?Wo(d.body,n.requestErrorResponseLengthLimit,(h,f)=>{o(h?`Unable to retrieve response: ${h}`:f)}):d.text().then(L(h=>o(qt(h,n))),L(h=>o(`Unable to retrieve response: ${h}`)))}function Ko(a){return a.status===0&&a.responseType!=="opaque"}function qt(a,n){return a.length>n.requestErrorResponseLengthLimit?`${a.substring(0,n.requestErrorResponseLengthLimit)}...`:a}function qo(a){return a==="xhr"?"XHR":"Fetch"}function Wo(a,n,o){mo(a,(d,h,f)=>{if(d)o(d);else{let u=new TextDecoder().decode(h);f&&(u+="..."),o(void 0,u)}},{bytesLimit:n,collectStreamBody:!0})}function Jo(a,n){if(!a.forwardErrorsToLogs)return{stop:ae};const o=new N,{stop:d}=Zr(o),h=o.subscribe(f=>{n.notify(0,{rawLogsEvent:{message:f.message,date:f.startClocks.timeStamp,error:ct(f),origin:W.SOURCE,status:F.error},messageContext:f.context})});return{stop:()=>{d(),h.unsubscribe()}}}const Xo=qs;function Zo(a){function n(o,d,h,f,u){const s=Ce(d.getContext(),o.context);if(ht(o.status,He.console,d)&&ea(o,s),ht(o.status,He.http,d)){const p={rawLogsEvent:{date:u||re(),message:o.message,status:o.status,origin:W.LOGGER},messageContext:s,savedCommonContext:f};h&&(p.domainContext={handlingStack:h}),a.notify(0,p)}}return{handleLog:n}}const Qo={[F.ok]:z.debug,[F.debug]:z.debug,[F.info]:z.info,[F.notice]:z.info,[F.warn]:z.warn,[F.error]:z.error,[F.critical]:z.error,[F.alert]:z.error,[F.emerg]:z.error};function ea({status:a,message:n},o){fe[Qo[a]].call(Q,n,o)}function ta(a,n,o,d,h){const f=Qi(a,{endpoint:a.logsEndpointBuilder,encoder:lt()},a.replica&&{endpoint:a.replica.logsEndpointBuilder,encoder:lt()},o,d,h.expireObservable);return n.subscribe(1,u=>{f.add(u)}),f}function ia(a){const n=Nt();a.subscribe(1,o=>{n.send("log",o)})}function na(a){return{get:n=>{const o=a.findTrackedSession(n);if(o)return{session_id:o.id}}}}function ra(a){return n=>{a.notify(0,{rawLogsEvent:{message:n.message,date:n.startClocks.timeStamp,origin:W.AGENT,status:F.error}}),Gi("Error reported to customer",{"error.message":n.message})}}function sa(a,n,o,d,h){const f=ps("browser-logs-sdk",n);f.setContextProvider(()=>{var s,p,y,g,v,U;return{application:{id:(s=ut())===null||s===void 0?void 0:s.application_id},session:{id:(p=h.findTrackedSession())===null||p===void 0?void 0:p.id},view:{id:(g=(y=ut())===null||y===void 0?void 0:y.view)===null||g===void 0?void 0:g.id},action:{id:(U=(v=ut())===null||v===void 0?void 0:v.user_action)===null||U===void 0?void 0:U.id}}});const u=[];if(at()){const s=Nt(),p=f.observable.subscribe(y=>s.send("internal_telemetry",y));u.push(()=>p.unsubscribe())}else{const s=Qi(n,{endpoint:n.rumEndpointBuilder,encoder:lt()},n.replica&&{endpoint:n.replica.rumEndpointBuilder,encoder:lt()},o,d,h.expireObservable);u.push(()=>s.stop());const p=f.observable.subscribe(y=>s.add(y,ys(n)));u.push(()=>p.unsubscribe())}return gs(),ms(Io(a)),{telemetry:f,stop:()=>{u.forEach(s=>s())}}}function oa(a,n,o,d){const h=new Xo,f=[];h.subscribe(1,U=>Ri("logs",U));const u=ra(h),s=Vs(n),p=n.sessionStoreStrategyType&&!at()&&!nn()?Ro(n,d):Po(n),{stop:y}=sa(a,n,u,s,p);f.push(()=>y()),Yo(n,h),Jo(n,h),Go(n,h),Ho(n,h);const{handleLog:g}=Zo(h);if(Mo(p,n,h,o,u),at())ia(h);else{const{stop:U}=ta(n,h,u,s,p);f.push(()=>U())}const v=na(p);return{handleLog:g,getInternalContext:v.get,stop:()=>{f.forEach(U=>U())}}}const Ie=Lo(oa);is(oe(),"DD_LOGS",Ie);class P{constructor(n){this.isLoggingOn=n,n&&Ie.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!1,sessionSampleRate:100})}static setMessagePort(n){this.messagePort=n}static getMessagePort(){return this.messagePort}setLoggingOn(n){this.isLoggingOn=n}setAttributes(n){for(const o in n)Ie.logger.setContextProperty(o,n[o])}info(n,o){this.isLoggingOn&&(Ie.logger.info(n,o),console.log("[Logger] Sending info: ",n))}error(n,o){this.isLoggingOn&&(Ie.logger.error(n,o),console.log("[Logger] Sending error: ",n))}warn(n,o){this.isLoggingOn&&(Ie.logger.warn(n,o),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){P.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:n})}static info(n,o){P.messagePort.postMessage({type:"LOG",actionType:"INFO",message:n,attributes:o})}static error(n,o){P.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:n,attributes:o})}static warn(n,o){P.messagePort.postMessage({type:"LOG",actionType:"WARN",message:n,attributes:o})}}class Wt{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.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.addJob=(h,f)=>{const{alphaMp4:u,metadataList:s}=this.parseZipAndMetadata(f,h);if(!u){this.options&&R(this.options,"Decoder")&&console.log("[Decoder] No alpha.mp4 found, no decoding needed.");return}const p={timeCode:h,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&&R(this.options,"Decoder")&&console.log("[Decoder] Added job:",p)},this.clearOldJobsAndChunks=h=>{const u=j.fromStr(this.currentTimecode).totalMilliseconds(this.fps)-h;this.unchunkedJobs=this.unchunkedJobs.filter(s=>j.fromStr(s.timeCode).totalMilliseconds(this.fps)>u),this.jobsQueue=this.jobsQueue.filter(s=>j.fromStr(s.timeCode).totalMilliseconds(this.fps)>u),this.chunksQueue=this.chunksQueue.filter(s=>j.fromStr(s.timeCode).totalMilliseconds(this.fps)>u)},this.clearAllJobsAndChunks=()=>{this.unchunkedJobs=[],this.jobsQueue=[],this.chunksQueue=[]},this.updateCurrentTimecode=(h,f)=>{if(this.options){if(this.fps=59.94,this.currentTimecode){const u=j.fromStr(h).totalMilliseconds(this.fps),s=j.fromStr(this.currentTimecode).totalMilliseconds(this.fps);if(u<s||u>s+this.options.DECODER_LEAD_TIME_MILLIS){this.timecodeErrorCount++;const p=performance.now();u<s&&(p-this.loggerTimeoutStart>this.loggerTimeout&&(this.loggerTimeoutStart=p,P.error("[Decoder] Timecode is going backwards")),this.options&&R(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,P.error("[Decoder] Timecode is too far ahead")),this.options&&R(this.options,"Errors")&&console.error("[Decoder] Timecode is too far ahead")),this.timecodeErrorCount>5&&this.restartDecoder();return}}this.timecodeErrorCount=0,this.currentTimecode=h,this.clearOldJobsAndChunks(2100),this.decodeUpcomingChunks()}},this.setupMP4Box=(h=!1)=>{const f=fn.createFile();return f.onError=u=>{P.error("[Decoder] MP4 parsing error",u),this.options&&R(this.options,"Errors")&&console.error("[Decoder] MP4 parsing error:",u)},f.onReady=u=>{const s=u.tracks.find(p=>p.type==="video");if(s){if(!(h?this.reservedVideoDecoderConfigured:this.videoDecoderConfigured)){this.options&&R(this.options,"Decoder")&&console.error("[Decoder] Starting a new VideoDecoder");let y;h?(this.reservedVideoDecoder=new VideoDecoder({output:this.onFrameDecoded,error:this.onDecoderError}),y=this.reservedVideoDecoder):(this.videoDecoder=new VideoDecoder({output:this.onFrameDecoded,error:this.onDecoderError}),y=this.videoDecoder),y.configure({codec:s.codec,codedWidth:s.video.width,codedHeight:s.video.height,description:this.getDescription(f.getTrackById(s.id)),hardwareAcceleration:"prefer-hardware",optimizeForLatency:!0}),h?(this.reservedVideoDecoderConfigured=!0,this.reservedVideoDecoderNeedsKeyFrame=!0):(this.videoDecoderConfigured=!0,this.videoDecoderNeedsKeyFrame=!0)}f.setExtractionOptions(s.id),f.start()}},f.onSamples=async(u,s,p)=>{const y=[];for(const g of p){const v=new EncodedVideoChunk({type:g.is_sync?"key":"delta",timestamp:g.cts,data:new Uint8Array(g.data)});y.push(v)}this.storeChunks(y)},f},this.chunkJob=async h=>{h.chunkingTime=performance.now(),this.mp4boxfile=this.setupMP4Box(h.useReserveDecoder);const u=await new Blob([h.alphaMp4],{type:"video/mp4"}).arrayBuffer();u.fileStart=0,this.mp4boxfile.appendBuffer(u)},this.storeChunks=h=>{var s;this.options&&R(this.options,"Decoder")&&console.log("[Decoder] Storing chunks:",h);const f=this.jobChunking;if((s=this.options.debug)!=null&&s.trackPerformance&&(f.chunkingTime=performance.now()-f.chunkingTime,this.chunkCount++,this.chunkingTimeSum+=f.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=f==null?void 0:f.metadata.map((p,y)=>({timeCode:p.timecode,chunk:h[y],metadata:p,job:f,cancelled:!1,decodingTime:0}));f.chunks=u,this.chunksQueue.push(...u),this.jobsQueue.push(f),this.options&&R(this.options,"Decoder")&&console.log("[Decoder] Jobs Queue:",this.jobsQueue),this.options&&R(this.options,"Decoder")&&console.log("[Decoder] Chunks Queue:",this.chunksQueue)},this.onFrameDecoded=h=>{var s;this.options&&R(this.options,"Decoder")&&console.log("[Decoder] Frame decoded:",h);const f=this.chunksForDecodingFrames.shift();if(!f){P.error("[Decoder] No current chunk for a processed frame"),this.options&&R(this.options,"Errors")&&console.error("[Decoder] No current chunk for a processed frame");return}if(f.cancelled||this.decoderStopped){this.options&&R(this.options,"Decoder")&&console.log("[Decoder] Skipping cancelled chunk:",f.timeCode),h.close();return}const u=f.metadata;if((s=this.options.debug)!=null&&s.trackPerformance){const p=performance.now();f.decodingTime=p-f.decodingTime,this.decodingFrameCount++,this.decodingTimeSum+=f.decodingTime,this.avgDecodingTime=this.decodingTimeSum/this.decodingFrameCount,p-this.lastPerformanceCheck>=this.options.PERFORMANCE_TRACKING_INTERVAL&&(this.trackPerformance(),this.lastPerformanceCheck=p)}f.job.framesProcessed++,u.alphaMask=h,this.processedMetadata.push(u),P.setAttributes({last_decoded_frame:u.timecode}),(this.processedMetadata.length>=this.options.DECODER_FRAME_BATCH_SIZE||f.job.framesProcessed>=f.job.totalFrameCount)&&(this.postBatchToRenderer(this.processedMetadata),this.processedMetadata.forEach(p=>p.alphaMask.close()),this.processedMetadata=[])},this.onDecoderError=h=>{var s,p;P.error("[Decoder] VideoDecoder error",h),this.options&&R(this.options,"Errors")&&console.error("[Decoder] VideoDecoder error:",h),this.videoDecoderConfigured=!1,this.reservedVideoDecoderConfigured=!1,this.videoDecoderNeedsKeyFrame=!0,this.reservedVideoDecoderNeedsKeyFrame=!0;const f=this.chunksForDecodingFrames.shift();if(!f){P.error("[Decoder] No broken chunk for an error"),this.options&&R(this.options,"Errors")&&console.error("[Decoder] No broken chunk for an error");return}const u=f.job;u&&u.chunks.forEach(y=>y.cancelled=!0),(s=this.reservedVideoDecoder)==null||s.close(),(p=this.videoDecoder)==null||p.close()},this.parseZipAndMetadata=(h,f)=>{const u=un.parse(h),s=u["alpha.mp4"]||null,p=Object.keys(u).filter(e=>e.endsWith(".json")).sort(this.numericFileComparator).map(e=>{const t=JSON.parse(new TextDecoder().decode(u[e]));return t.timecode=j.toStr(j.fromMetadata(t)),t}),y=p.length;let g=120;const[v,U,S]=f.split("_").map(Number);U%10===0&&S===0?g=120:S===0&&(g=116),y!==g&&(P.error("[Decoder] Metadata count mismatch",{expected:g,actual:y,timecode:f}),this.options&&R(this.options,"Errors")&&console.error("[Decoder] Metadata count mismatch:",{expected:g,actual:y,timecode:f}));const E=p.filter(e=>e.placeholders);return{alphaMp4:s,metadataList:E}},this.numericFileComparator=(h,f)=>{const u=/^(\\d{2})_(\\d{2})_(\\d{2})_(\\d{2})(?:\\.(\\d+))?\\.(.+)$/,s=h.match(u),p=f.match(u);if(!s||!p)return 0;const[,y,g,v,U,S="0",E]=s,[,e,t,r,l,c="0",_]=p;return parseInt(y,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(c,10)||E.localeCompare(_)},this.getDescription=h=>{for(const f of h.mdia.minf.stbl.stsd.entries){const u=f.avcC||f.hvcC||f.vpcC||f.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 h=this.getAvgChunkingTime(),f=this.getAvgDecodingTime();la([{metric:"Chunking time",value:h},{metric:"Decoding time",value:f}])},this.postBatchToRenderer=n,this.restartDecoder=o,this.options=d,this.mp4boxfile=this.setupMP4Box()}decodeUpcomingChunks(){const n=j.fromStr(this.currentTimecode).totalMilliseconds(this.fps),o=n+this.options.DECODER_LEAD_TIME_MILLIS,d=this.chunksQueue.filter(f=>{const u=j.fromStr(f.timeCode).totalMilliseconds(this.fps);return u>=n&&u<=o&&!f.decoded});d.sort((f,u)=>{const s=j.fromStr(f.timeCode).totalMilliseconds(this.fps),p=j.fromStr(u.timeCode).totalMilliseconds(this.fps);return s-p});const h=d.slice(0,this.options.DECODER_FRAME_BATCH_SIZE);for(const f of h){if(f.cancelled){this.options&&R(this.options,"Decoder")&&console.log("[Decoder] Skipping cancelled chunk:",f.timeCode);continue}const u=f.job.useReserveDecoder?this.reservedVideoDecoder:this.videoDecoder;if(!u||u.state==="closed"){P.error("[Decoder] No VideoDecoder available"),this.options&&R(this.options,"Errors")&&console.error("[Decoder] No VideoDecoder available");continue}if((f.job.useReserveDecoder?this.reservedVideoDecoderNeedsKeyFrame:this.videoDecoderNeedsKeyFrame)&&f.chunk.type==="delta"){P.error("[Decoder] Decoder needs a key frame, skipping delta chunk",{chunkTimeCode:f.timeCode}),this.options&&R(this.options,"Errors")&&console.error("[Decoder] Decoder needs a key frame, skipping delta chunk:",f.timeCode),f.decoded=!0;continue}try{this.chunksForDecodingFrames.push(f),f.chunk.type==="key"&&(f.job.useReserveDecoder?this.reservedVideoDecoderNeedsKeyFrame=!1:this.videoDecoderNeedsKeyFrame=!1),f.decodingTime=performance.now(),u.decode(f.chunk)}catch(p){P.error("[Decoder] Error decoding chunk",p),this.options&&R(this.options,"Errors")&&console.error("[Decoder] Error decoding chunk:",p),this.videoDecoderConfigured=!1,this.reservedVideoDecoderConfigured=!1,this.videoDecoderNeedsKeyFrame=!0,this.reservedVideoDecoderNeedsKeyFrame=!0,f.job.chunks.forEach(g=>g.cancelled=!0),u.close()}finally{if(f.decoded=!0,f.job.framesSentToDecoder++,f.job.framesSentToDecoder>=f.job.totalFrameCount){u.flush(),f.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.clearAllJobsAndChunks();try{(n=this.videoDecoder)==null||n.close()}catch(d){P.error("[Decoder] Error closing main VideoDecoder",d),this.options&&R(this.options,"Errors")&&console.error("[Decoder] Error closing main VideoDecoder:",d)}try{(o=this.reservedVideoDecoder)==null||o.close()}catch(d){P.error("[Decoder] Error closing reserved VideoDecoder",d),this.options&&R(this.options,"Errors")&&console.error("[Decoder] Error closing reserved VideoDecoder:",d)}}}let dn=null,pt=null,Se,G;self.onmessage=async a=>{const{data:n}=a;if(n.type==="SET_LOGGER_PORT"&&P.setMessagePort(n.port),n.type==="SET_DOWNLOADER_PORT"&&(dn=n.port,dn.onmessage=aa),n.type==="SET_RENDERER_PORT"&&(pt=n.port,pt.onmessage=da),n.type==="SET_OPTIONS"&&(G=n.options,P.setMessagePort(self),Se=new Wt(Jt,_t,G)),n.type==="VIDEO_SEEKED"){if(!G)return;_t()}};function aa(a){const{data:n}=a;if(n.type==="DECODER_INPUT"){const{timeCode:o,arrayBuffer:d}=n;G&&R(G,"Decoder")&&console.log("[DecoderWorker] Received ArrayBuffer from Downloader, timeCode =",o),Se.addJob(o,d)}}function da(a){const{data:n}=a;if(n.type==="DECODER_REQUEST"){const{timeCode:o,fps:d}=n;G&&R(G,"Decoder")&&console.log("[DecoderWorker] Received TimeCode request from Renderer, timeCode =",o),Se.updateCurrentTimecode(o,d)}}function _t(){G&&(Se.stop(),Se=new Wt(Jt,_t,G))}function Jt(a){if(!pt)return;G&&R(G,"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);pt.postMessage({type:"RENDERER_INPUT",batch:a},[...o]),n.forEach(d=>d.close())}catch(o){P.error("[DecoderWorker] Error posting batch to Renderer",{error:o}),G&&R(G,"Errors")&&console.error("[DecoderWorker] Error posting batch to Renderer:",o),n.forEach(d=>d.close());return}}function la(a){const n={type:"TRACK_PERFORMANCE",data:a};self.postMessage(n)}self.onunhandledrejection=a=>{P.error("[DecoderWorker] Unhandled rejection",{error:a.reason}),G&&(R(G,"Errors")&&console.error("[DecoderWorker] Unhandled rejection:",a.reason),Se.stop(),Se=new Wt(Jt,_t,G),a.preventDefault())},self.onerror=a=>{P.error("[DecoderWorker] Unhandled error",{error:a}),G&&(R(G,"Errors")&&console.error("[DecoderWorker] Unhandled error:",a),a instanceof Event&&a.preventDefault())}})();\n',Bt=typeof self<"u"&&self.Blob&&new Blob([Mt],{type:"text/javascript;charset=utf-8"});function rr(t){let e;try{if(e=Bt&&(self.URL||self.webkitURL).createObjectURL(Bt),!e)throw"";const n=new Worker(e,{name:t==null?void 0:t.name});return n.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),n}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Mt),{name:t==null?void 0:t.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}const Nt='(function(){"use strict";const w=(t,e)=>!t.debug||!t.debug.on?!1:t.debug[`log${e}`],_={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},D=console,q={};Object.keys(_).forEach(t=>{q[t]=D[t]});const de="Datadog Browser SDK:",T={debug:q.debug.bind(D,de),log:q.log.bind(D,de),info:q.info.bind(D,de),warn:q.warn.bind(D,de),error:q.error.bind(D,de)},Ze="https://docs.datadoghq.com",Ot=`${Ze}/real_user_monitoring/browser/troubleshooting`,ve="More details:";function It(t,e){return(...n)=>{try{return t(...n)}catch(r){T.error(e,r)}}}function we(t){return t!==0&&Math.random()*100<=t}function qn(t){return Hn(t)&&t>=0&&t<=100}function Hn(t){return typeof t=="number"}const fe=1e3,H=60*fe,Ut=60*H,zn=365*(24*Ut);function he(){return new Date().getTime()}function N(){return he()}function Ce(){return performance.now()}function B(){return{relative:Ce(),timeStamp:N()}}function Vn(){return{relative:0,timeStamp:Dt()}}function Kn(t,e){return e-t}function Jn(t,e){return t+e}function Zn(t){return t-Dt()}let Qe;function Dt(){return Qe===void 0&&(Qe=performance.timing.navigationStart),Qe}const P=1024,Pt=1024*P,Qn=/[^\\u0000-\\u007F]/;function et(t){return Qn.test(t)?window.TextEncoder!==void 0?new TextEncoder().encode(t).length:new Blob([t]).size:t.length}function er(t){return{...t}}function kt(t,e){return Object.keys(t).some(n=>t[n]===e)}function me(t){return Object.keys(t).length===0}function $(){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 ne(t,e){const n=$();let r;return n.Zone&&typeof n.Zone.__symbol__=="function"&&(r=t[n.Zone.__symbol__(e)]),r||(r=t[e]),r}let xe,Mt=!1;function tr(t){xe=t}function nr(t){Mt=t}function rr(t,e,n){const r=n.value;n.value=function(...s){return(xe?b(r):r).apply(this,s)}}function b(t){return function(){return pe(t,this,arguments)}}function pe(t,e,n){try{return t.apply(e,n)}catch(r){sr(r)}}function sr(t){if(tt(t),xe)try{xe(t)}catch(e){tt(e)}}function tt(...t){Mt&&T.error("[MONITOR]",...t)}function ge(t,e){return ne($(),"setTimeout")(b(t),e)}function Ft(t){ne($(),"clearTimeout")(t)}function nt(t,e){return ne($(),"setInterval")(b(t),e)}function Nt(t){ne($(),"clearInterval")(t)}class R{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(n=>e!==n),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}}notify(e){this.observers.forEach(n=>n(e))}}function Bt(...t){return new R(e=>{const n=t.map(r=>r.subscribe(s=>e.notify(s)));return()=>n.forEach(r=>r.unsubscribe())})}function $t(t,e,n){let r=!1,s,o;return{throttled:(...i)=>{if(r){s=i;return}t(...i),r=!0,o=ge(()=>{s&&t(...s),r=!1,s=void 0},e)},cancel:()=>{Ft(o),r=!1,s=void 0}}}function G(){}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 Le=/([\\w-]+)\\s*=\\s*([^;]+)/g;function or(t,e){for(Le.lastIndex=0;;){const n=Le.exec(t);if(n){if(n[1]===e)return n[2]}else break}}function ir(t){const e=new Map;for(Le.lastIndex=0;;){const n=Le.exec(t);if(n)e.set(n[1],n[2]);else break}return e}function ar(t,e,n=""){const r=t.charCodeAt(e-1),o=r>=55296&&r<=56319?e+1:e;return t.length<=o?t:`${t.slice(0,o)}${n}`}function cr(){return ur()===0}let Oe;function ur(){return Oe??(Oe=lr())}function lr(t=window){var e;const n=t.navigator.userAgent;return t.chrome||/HeadlessChrome/.test(n)?0:((e=t.navigator.vendor)===null||e===void 0?void 0:e.indexOf("Apple"))===0||/safari/i.test(n)&&!/chrome|android/i.test(n)?1:2}function Ee(t,e,n=0,r){const s=new Date;s.setTime(s.getTime()+n);const o=`expires=${s.toUTCString()}`,i=r&&r.crossSite?"none":"strict",a=r&&r.domain?`;domain=${r.domain}`:"",u=r&&r.secure?";secure":"",c=r&&r.partitioned?";partitioned":"";document.cookie=`${t}=${e};${o};path=/;samesite=${i}${a}${u}${c}`}function rt(t){return or(document.cookie,t)}let st;function z(t){return st||(st=ir(document.cookie)),st.get(t)}function Gt(t,e){Ee(t,"",0,e)}function dr(t){if(document.cookie===void 0||document.cookie===null)return!1;try{const e=`dd_cookie_test_${j()}`,n="test";Ee(e,n,H,t);const r=rt(e)===n;return Gt(e,t),r}catch(e){return T.error(e),!1}}let ot;function fr(){if(ot===void 0){const t=`dd_site_test_${j()}`,e="test",n=window.location.hostname.split(".");let r=n.pop();for(;n.length&&!rt(t);)r=`${n.pop()}.${r}`,Ee(t,e,fe,{domain:r});Gt(t,{domain:r}),ot=r}return ot}const re="_dd_s";function Ie(t){return Object.values(t)}function hr(t){return Object.entries(t)}const it=4*Ut,jt=15*H,mr=zn,be={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},Wt=/^([a-zA-Z]+)=([a-z0-9-]+)$/,at="&";function pr(t){return!!t&&(t.indexOf(at)!==-1||Wt.test(t))}const gr="1";function V(t,e){const n={isExpired:gr};return e.trackAnonymousUser&&(t!=null&&t.anonymousId?n.anonymousId=t==null?void 0:t.anonymousId:n.anonymousId=j()),n}function Ue(t){return me(t)}function Xt(t){return!Ue(t)}function De(t){return t.isExpired!==void 0||!Er(t)}function Er(t){return(t.created===void 0||he()-Number(t.created)<it)&&(t.expire===void 0||he()<Number(t.expire))}function Yt(t){t.expire=String(he()+jt)}function ct(t){return hr(t).map(([e,n])=>e==="anonymousId"?`aid=${n}`:`${e}=${n}`).join(at)}function qt(t){const e={};return pr(t)&&t.split(at).forEach(n=>{const r=Wt.exec(n);if(r!==null){const[,s,o]=r;s==="aid"?e.anonymousId=o:e[s]=o}}),e}const br="_dd",yr="_dd_r",Sr="_dd_l",_r="rum",Tr="logs";function Rr(t){if(!z(re)){const n=z(br),r=z(yr),s=z(Sr),o={};n&&(o.id=n),s&&/^[01]$/.test(s)&&(o[Tr]=s),r&&/^[012]$/.test(r)&&(o[_r]=r),Xt(o)&&(Yt(o),t.persistSession(o))}}function Ht(t){const e=xr(t);return dr(e)?{type:be.COOKIE,cookieOptions:e}:void 0}function Ar(t,e){const n={isLockEnabled:cr(),persistSession:vr(e),retrieveSession:Cr,expireSession:r=>wr(e,r,t)};return Rr(n),n}function vr(t){return e=>{Ee(re,ct(e),jt,t)}}function wr(t,e,n){const r=V(e,n);Ee(re,ct(r),n.trackAnonymousUser?mr:it,t)}function Cr(){const t=rt(re);return qt(t)}function xr(t){const e={};return e.secure=!!t.useSecureSessionCookie||!!t.usePartitionedCrossSiteSessionCookie,e.crossSite=!!t.usePartitionedCrossSiteSessionCookie,e.partitioned=!!t.usePartitionedCrossSiteSessionCookie,t.trackSessionAcrossSubdomains&&(e.domain=fr()),e}const Lr="_dd_test_";function zt(){try{const t=j(),e=`${Lr}${t}`;localStorage.setItem(e,t);const n=localStorage.getItem(e);return localStorage.removeItem(e),t===n?{type:be.LOCAL_STORAGE}:void 0}catch{return}}function Or(t){return{isLockEnabled:!1,persistSession:Vt,retrieveSession:Ir,expireSession:e=>Ur(e,t)}}function Vt(t){localStorage.setItem(re,ct(t))}function Ir(){const t=localStorage.getItem(re);return qt(t)}function Ur(t,e){Vt(V(t,e))}const Dr=10,Pr=100,Kt=[];let Pe;function K(t,e,n=0){var r;const{isLockEnabled:s,persistSession:o,expireSession:i}=e,a=f=>o({...f,lock:c}),u=()=>{const f=e.retrieveSession(),h=f.lock;return f.lock&&delete f.lock,{session:f,lock:h}};if(Pe||(Pe=t),t!==Pe){Kt.push(t);return}if(s&&n>=Pr){Jt(e);return}let c,l=u();if(s){if(l.lock){ke(t,e,n);return}if(c=j(),a(l.session),l=u(),l.lock!==c){ke(t,e,n);return}}let d=t.process(l.session);if(s&&(l=u(),l.lock!==c)){ke(t,e,n);return}if(d&&(De(d)?i(d):(Yt(d),s?a(d):o(d))),s&&!(d&&De(d))){if(l=u(),l.lock!==c){ke(t,e,n);return}o(l.session),d=l.session}(r=t.after)===null||r===void 0||r.call(t,d||l.session),Jt(e)}function ke(t,e,n){ge(()=>{K(t,e,n+1)},Dr)}function Jt(t){Pe=void 0;const e=Kt.shift();e&&K(e,t)}const Zt=fe;function kr(t){switch(t.sessionPersistence){case be.COOKIE:return Ht(t);case be.LOCAL_STORAGE:return zt();case void 0:{let e=Ht(t);return!e&&t.allowFallbackToLocalStorage&&(e=zt()),e}default:T.error(`Invalid session persistence \'${String(t.sessionPersistence)}\'`)}}function Mr(t,e,n,r){const s=new R,o=new R,i=new R,a=t.type===be.COOKIE?Ar(e,t.cookieOptions):Or(e),{expireSession:u}=a,c=nt(m,Zt);let l;y();const{throttled:d,cancel:f}=$t(()=>{K({process:g=>{if(Ue(g))return;const le=E(g);return O(le),le},after:g=>{Xt(g)&&!x()&&zi(g),l=g}},a)},Zt);function h(){K({process:g=>x()?E(g):void 0},a)}function m(){K({process:g=>De(g)?V(g,e):void 0,after:E},a)}function E(g){return De(g)&&(g=V(g,e)),x()&&(Ae(g)?Lt():(i.notify({previousState:l,newState:g}),l=g)),g}function y(){K({process:g=>{if(Ue(g))return V(g,e)},after:g=>{l=g}},a)}function O(g){if(Ue(g))return!1;const{trackingType:le,isTracked:Ki}=r(g[n]);g[n]=le,delete g.isExpired,Ki&&!g.id&&(g.id=j(),g.created=String(he()))}function x(){return l[n]!==void 0}function Ae(g){return l.id!==g.id||l[n]!==g[n]}function Lt(){l=V(l,e),o.notify()}function zi(g){l=g,s.notify()}function Vi(g){K({process:le=>({...le,...g}),after:E},a)}return{expandOrRenewSession:d,expandSession:h,getSession:()=>l,renewObservable:s,expireObservable:o,sessionStateUpdateObservable:i,restartSession:y,expire:()=>{f(),u(l),E(V(l,e))},stop:()=>{Nt(c)},updateSessionState:Vi}}const ut={GRANTED:"granted",NOT_GRANTED:"not-granted"};function Fr(t){const e=new R;return{tryToInit(n){t||(t=n)},update(n){t=n,e.notify()},isGranted(){return t===ut.GRANTED},observable:e}}function J(t,e,n){if(typeof t!="object"||t===null)return JSON.stringify(t);const r=se(Object.prototype),s=se(Array.prototype),o=se(Object.getPrototypeOf(t)),i=se(t);try{return JSON.stringify(t,e,n)}catch{return"<error: unable to serialize object>"}finally{r(),s(),o(),i()}}function se(t){const e=t,n=e.toJSON;return n?(delete e.toJSON,()=>{e.toJSON=n}):G}function lt(t){return Nr(t,location.href).href}function Nr(t,e){const n=Br();if(n)try{return e!==void 0?new n(t,e):new n(t)}catch(o){throw new Error(`Failed to construct URL: ${String(o)} ${J({url:t,base:e})}`)}if(e===void 0&&!/:/.test(t))throw new Error(`Invalid URL: \'${t}\'`);let r=document;const s=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(s)}return s.href=t,s}const Qt=URL;let Me;function Br(){if(Me===void 0)try{Me=new Qt("http://test/path").href==="http://test/path"}catch{Me=!1}return Me?Qt:void 0}const $r="datad0g.com",Gr="dd0g-gov.com",oe="datadoghq.com",jr="ddog-gov.com",Wr="pci.browser-intake-datadoghq.com",Xr=["ddsource","ddtags"];function ye(t,e,n){const r=Yr(t,e);return{build(s,o){const i=Hr(t,e,n,s,o);return r(i)},urlPrefix:r(""),trackType:e}}function Yr(t,e){const n=`/api/v2/${e}`,r=t.proxy;if(typeof r=="string"){const o=lt(r);return i=>`${o}?ddforward=${encodeURIComponent(`${n}?${i}`)}`}if(typeof r=="function")return o=>r({path:n,parameters:o});const s=qr(e,t);return o=>`https://${s}${n}?${o}`}function qr(t,e){const{site:n=oe,internalAnalyticsSubdomain:r}=e;if(t==="logs"&&e.usePciIntake&&n===oe)return Wr;if(r&&n===oe)return`${r}.${oe}`;if(n===Gr)return`http-intake.logs.${n}`;const s=n.split("."),o=s.pop();return`browser-intake-${s.join("-")}.${o}`}function Hr({clientToken:t,internalAnalyticsSubdomain:e},n,r,s,{retry:o,encoding:i}){const a=["sdk_version:6.5.0",`api:${s}`].concat(r);o&&a.push(`retry_count:${o.count}`,`retry_after:${o.lastFailureStatus}`);const u=["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 i&&u.push(`dd-evp-encoding=${i}`),n==="rum"&&u.push(`batch_time=${N()}`),e&&u.reverse(),u.join("&")}const zr=200;function Vr(t){const{env:e,service:n,version:r,datacenter:s}=t,o=[];return e&&o.push(Fe("env",e)),n&&o.push(Fe("service",n)),r&&o.push(Fe("version",r)),s&&o.push(Fe("datacenter",s)),o}function Fe(t,e){const n=zr-t.length-1;(e.length>n||Kr(e))&&T.warn(`${t} value doesn\'t meet tag requirements and will be sanitized. ${ve} ${Ze}/getting_started/tagging/#defining-tags`);const r=e.replace(/,/g,"_");return`${t}:${r}`}function Kr(t){return Jr()?new RegExp("[^\\\\p{Ll}\\\\p{Lo}0-9_:./-]","u").test(t):!1}function Jr(){try{return new RegExp("[\\\\p{Ll}]","u"),!0}catch{return!1}}function Zr(t){const e=t.site||oe,n=Vr(t),r=Qr(t,n);return{replica:es(t,n),site:e,...r}}function Qr(t,e){return{logsEndpointBuilder:ye(t,"logs",e),rumEndpointBuilder:ye(t,"rum",e),sessionReplayEndpointBuilder:ye(t,"replay",e)}}function es(t,e){if(!t.replica)return;const n={...t,site:oe,clientToken:t.replica.clientToken},r={logsEndpointBuilder:ye(n,"logs",e),rumEndpointBuilder:ye(n,"rum",e)};return{applicationId:t.replica.applicationId,...r}}function ts(t){return Xr.every(e=>t.includes(e))}function dt(t,e){return t!=null&&typeof t!="string"?(T.error(`${e} must be defined as a string`),!1):!0}function ns(t){return t&&typeof t=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(t)?(T.error(`Site should be a valid Datadog site. ${ve} ${Ze}/getting_started/site/.`),!1):!0}function Ne(t,e){return t!==void 0&&!qn(t)?(T.error(`${e} Sample Rate should be a number between 0 and 100`),!1):!0}function rs(t){var e,n,r,s,o,i;if(!t||!t.clientToken){T.error("Client Token is not configured, we will not send any data.");return}if(!(!ns(t.site)||!Ne(t.sessionSampleRate,"Session")||!Ne(t.telemetrySampleRate,"Telemetry")||!Ne(t.telemetryConfigurationSampleRate,"Telemetry Configuration")||!Ne(t.telemetryUsageSampleRate,"Telemetry Usage")||!dt(t.version,"Version")||!dt(t.env,"Env")||!dt(t.service,"Service"))){if(t.trackingConsent!==void 0&&!kt(ut,t.trackingConsent)){T.error(\'Tracking Consent should be either "granted" or "not-granted"\');return}return{beforeSend:t.beforeSend&&It(t.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:kr(t),sessionSampleRate:(e=t.sessionSampleRate)!==null&&e!==void 0?e:100,telemetrySampleRate:(n=t.telemetrySampleRate)!==null&&n!==void 0?n:20,telemetryConfigurationSampleRate:(r=t.telemetryConfigurationSampleRate)!==null&&r!==void 0?r:5,telemetryUsageSampleRate:(s=t.telemetryUsageSampleRate)!==null&&s!==void 0?s: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*P,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*fe,batchMessagesLimit:50,messageBytesLimit:256*P,...Zr(t)}}}function ss(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 ft;(function(t){t.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",t.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(ft||(ft={}));const en=new Set;function os(t){Array.isArray(t)&&is(t.filter(e=>kt(ft,e)))}function is(t){t.forEach(e=>{en.add(e)})}function as(){return en}const Se="?";function k(t){const e=[];let n=ht(t,"stack");const r=String(t);return n&&n.startsWith(r)&&(n=n.slice(r.length)),n&&n.split(`\n`).forEach(s=>{const o=ls(s)||fs(s)||ms(s)||Es(s);o&&(!o.func&&o.line&&(o.func=Se),e.push(o))}),{message:ht(t,"message"),name:ht(t,"name"),stack:e}}const tn="((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\\\w+\\\\.|\\\\/).*?)",ie="(?::(\\\\d+))",cs=new RegExp(`^\\\\s*at (.*?) ?\\\\(${tn}${ie}?${ie}?\\\\)?\\\\s*$`,"i"),us=new RegExp(`\\\\((\\\\S*)${ie}${ie}\\\\)`);function ls(t){const e=cs.exec(t);if(!e)return;const n=e[2]&&e[2].indexOf("native")===0,r=e[2]&&e[2].indexOf("eval")===0,s=us.exec(e[2]);return r&&s&&(e[2]=s[1],e[3]=s[2],e[4]=s[3]),{args:n?[e[2]]:[],column:e[4]?+e[4]:void 0,func:e[1]||Se,line:e[3]?+e[3]:void 0,url:n?void 0:e[2]}}const ds=new RegExp(`^\\\\s*at ?${tn}${ie}?${ie}??\\\\s*$`,"i");function fs(t){const e=ds.exec(t);if(e)return{args:[],column:e[3]?+e[3]:void 0,func:Se,line:e[2]?+e[2]:void 0,url:e[1]}}const hs=/^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;function ms(t){const e=hs.exec(t);if(e)return{args:[],column:e[4]?+e[4]:void 0,func:e[1]||Se,line:+e[3],url:e[2]}}const ps=/^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i,gs=/(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;function Es(t){const e=ps.exec(t);if(!e)return;const n=e[3]&&e[3].indexOf(" > eval")>-1,r=gs.exec(e[3]);return n&&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]||Se,line:e[4]?+e[4]:void 0,url:e[3]}}function ht(t,e){if(typeof t!="object"||!t||!(e in t))return;const n=t[e];return typeof n=="string"?n:void 0}function bs(t,e,n,r){const s=[{url:e,column:r,line:n}],{name:o,message:i}=Ss(t);return{name:o,message:i,stack:s}}const ys=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\\s\\S]*)$/;function Ss(t){let e,n;return{}.toString.call(t)==="[object String]"&&([,e,n]=ys.exec(t)),{name:e,message:n}}function Be(t){const n=new Error(t);n.name="HandlingStack";let r;return pe(()=>{const s=k(n);s.stack=s.stack.slice(2),r=Z(s)}),r}function Z(t){let e=nn(t);return t.stack.forEach(n=>{const r=n.func==="?"?"<anonymous>":n.func,s=n.args&&n.args.length>0?`(${n.args.join(", ")})`:"",o=n.line?`:${n.line}`:"",i=n.line&&n.column?`:${n.column}`:"";e+=`\n at ${r}${s} @ ${n.url}${o}${i}`}),e}function nn(t){return`${t.name||"Error"}: ${t.message}`}function Q(t,e,n,{computeHandlingStack:r}={}){let s=t[e];if(typeof s!="function")if(e in t&&e.startsWith("on"))s=G;else return{stop:G};let o=!1;const i=function(){if(o)return s.apply(this,arguments);const a=Array.from(arguments);let u;pe(n,null,[{target:this,parameters:a,onPostCall:l=>{u=l},handlingStack:r?Be("instrumented method"):void 0}]);const c=s.apply(this,a);return u&&pe(u,null,[c]),c};return t[e]=i,{stop:()=>{o=!0,t[e]===i&&(t[e]=s)}}}const _s=220*P,Ts="$",Rs=3;function M(t,e=_s){const n=se(Object.prototype),r=se(Array.prototype),s=[],o=new WeakMap,i=mt(t,Ts,void 0,s,o),a=JSON.stringify(i);let u=a?a.length:0;if(u>e){gt(e,"discarded",t);return}for(;s.length>0&&u<e;){const c=s.shift();let l=0;if(Array.isArray(c.source))for(let d=0;d<c.source.length;d++){const f=mt(c.source[d],c.path,d,s,o);if(f!==void 0?u+=JSON.stringify(f).length:u+=4,u+=l,l=1,u>e){gt(e,"truncated",t);break}c.target[d]=f}else for(const d in c.source)if(Object.prototype.hasOwnProperty.call(c.source,d)){const f=mt(c.source[d],c.path,d,s,o);if(f!==void 0&&(u+=JSON.stringify(f).length+l+d.length+Rs,l=1),u>e){gt(e,"truncated",t);break}c.target[d]=f}}return n(),r(),i}function mt(t,e,n,r,s){const o=ws(t);if(!o||typeof o!="object")return As(o);const i=pt(o);if(i!=="[Object]"&&i!=="[Array]"&&i!=="[Error]")return i;const a=t;if(s.has(a))return`[Reference seen at ${s.get(a)}]`;const u=n!==void 0?`${e}.${n}`:e,c=Array.isArray(o)?[]:{};return s.set(a,u),r.push({source:o,target:c,path:u}),c}function As(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 pt(t){try{if(t instanceof Event)return vs(t);if(t instanceof RegExp)return`[RegExp] ${t.toString()}`;const n=Object.prototype.toString.call(t).match(/\\[object (.*)\\]/);if(n&&n[1])return`[${n[1]}]`}catch{}return"[Unserializable]"}function vs(t){return{type:t.type,isTrusted:t.isTrusted,currentTarget:t.currentTarget?pt(t.currentTarget):null,target:t.target?pt(t.target):null}}function ws(t){const e=t;if(e&&typeof e.toJSON=="function")try{return e.toJSON()}catch{}return t}function gt(t,e,n){T.warn(`The data provided has been ${e} as it is over the limit of ${t} characters:`,n)}const rn="No stack, consider using an instance of Error";function sn({stackTrace:t,originalError:e,handlingStack:n,componentStack:r,startClocks:s,nonErrorPrefix:o,source:i,handling:a}){const u=W(e),c=Cs(t,u,o,e),l=xs(u,t)?Z(t):rn,d=u?cn(e,i):void 0,f=t?t.name:void 0,h=on(e),m=an(e);return{startClocks:s,source:i,handling:a,handlingStack:n,componentStack:r,originalError:e,type:f,message:c,stack:l,causes:d,fingerprint:h,context:m}}function Cs(t,e,n,r){return t!=null&&t.message&&(t!=null&&t.name)?t.message:e?"Empty message":`${n} ${J(M(r))}`}function xs(t,e){return e===void 0?!1:t?!0:e.stack.length>0&&(e.stack.length>1||e.stack[0].url!==void 0)}function on(t){return W(t)&&"dd_fingerprint"in t?String(t.dd_fingerprint):void 0}function an(t){if(t!==null&&typeof t=="object"&&"dd_context"in t)return t.dd_context}function Ls(t){var e;return(e=/@ (.+)/.exec(t))===null||e===void 0?void 0:e[1]}function W(t){return t instanceof Error||Object.prototype.toString.call(t)==="[object Error]"}function cn(t,e){let n=t;const r=[];for(;W(n==null?void 0:n.cause)&&r.length<10;){const s=k(n.cause);r.push({message:n.cause.message,source:e,type:s==null?void 0:s.name,stack:Z(s)}),n=n.cause}return r.length?r:void 0}const I={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function Os(t){const e=(s,o)=>{const i=sn({stackTrace:s,originalError:o,startClocks:B(),nonErrorPrefix:"Uncaught",source:I.SOURCE,handling:"unhandled"});t.notify(i)},{stop:n}=Is(e),{stop:r}=Us(e);return{stop:()=>{n(),r()}}}function Is(t){return Q(window,"onerror",({parameters:[e,n,r,s,o]})=>{let i;W(o)?i=k(o):i=bs(e,n,r,s),t(i,o??e)})}function Us(t){return Q(window,"onunhandledrejection",({parameters:[e]})=>{const n=e.reason||"Empty reason",r=k(n);t(r,n)})}function Ds(t){const e={version:"6.5.0",onReady(n){n()},...t};return Object.defineProperty(e,"_setDebug",{get(){return nr},enumerable:!1}),e}function Ps(t,e,n){const r=t[e];r&&!r.q&&r.version&&T.warn("SDK is loaded more than once. This is unsupported and might have unexpected behavior."),t[e]=n,r&&r.q&&r.q.forEach(s=>It(s,"onReady callback threw an error:")())}function un(t,e){e.silentMultipleInit||T.error(`${t} is already initialized.`)}function ee(t,e,n,r,s){return Et(t,e,[n],r,s)}function Et(t,e,n,r,{once:s,capture:o,passive:i}={}){const a=b(f=>{!f.isTrusted&&!f.__ddIsTrusted&&!t.allowUntrustedEvents||(s&&d(),r(f))}),u=i?{capture:o,passive:i}:o,c=window.EventTarget&&e instanceof EventTarget?window.EventTarget.prototype:e,l=ne(c,"addEventListener");n.forEach(f=>l.call(e,f,a,u));function d(){const f=ne(c,"removeEventListener");n.forEach(h=>f.call(e,h,a,u))}return{stop:d}}const $e={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function ks(t,e){const n=[];e.includes($e.cspViolation)&&n.push(Fs(t));const r=e.filter(s=>s!==$e.cspViolation);return r.length&&n.push(Ms(r)),Bt(...n)}function Ms(t){return new R(e=>{if(!window.ReportingObserver)return;const n=b((s,o)=>s.forEach(i=>e.notify(Ns(i)))),r=new window.ReportingObserver(n,{types:t,buffered:!0});return r.observe(),()=>{r.disconnect()}})}function Fs(t){return new R(e=>{const{stop:n}=ee(t,document,"securitypolicyviolation",r=>{e.notify(Bs(r))});return n})}function Ns(t){const{type:e,body:n}=t;return ln({type:n.id,message:`${e}: ${n.message}`,originalError:t,stack:dn(n.id,n.message,n.sourceFile,n.lineNumber,n.columnNumber)})}function Bs(t){const e=`\'${t.blockedURI}\' blocked by \'${t.effectiveDirective}\' directive`;return ln({type:t.effectiveDirective,message:`${$e.cspViolation}: ${e}`,originalError:t,csp:{disposition:t.disposition},stack:dn(t.effectiveDirective,t.originalPolicy?`${e} of the policy "${ar(t.originalPolicy,100,"...")}"`:"no policy",t.sourceFile,t.lineNumber,t.columnNumber)})}function ln(t){return{startClocks:B(),source:I.REPORT,handling:"unhandled",...t}}function dn(t,e,n,r,s){return n?Z({name:t,message:e,stack:[{func:"?",url:n,line:r??void 0,column:s??void 0}]}):void 0}function fn(t,e){const n=window.__ddBrowserSdkExtensionCallback;n&&n({type:t,payload:e})}function hn(t){return t===null?"null":Array.isArray(t)?"array":typeof t}function Ge(t,e,n=$s()){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(n.hasAlreadyBeenSeen(e))return;if(Array.isArray(e)){const s=Array.isArray(t)?t:[];for(let o=0;o<e.length;++o)s[o]=Ge(s[o],e[o],n);return s}const r=hn(t)==="object"?t:{};for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(r[s]=Ge(r[s],e[s],n));return r}function mn(t){return Ge(void 0,t)}function ae(...t){let e;for(const n of t)n!=null&&(e=Ge(e,n));return e}function $s(){if(typeof WeakSet<"u"){const e=new WeakSet;return{hasAlreadyBeenSeen(n){const r=e.has(n);return r||e.add(n),r}}}const t=[];return{hasAlreadyBeenSeen(e){const n=t.indexOf(e)>=0;return n||t.push(e),n}}}function Gs(){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 js(t){const e=new Set;return t.forEach(n=>e.add(n)),Array.from(e)}function pn(t,e){const n=t.indexOf(e);n>=0&&t.splice(n,1)}const Ws=500;function gn(){const t=[];return{add:s=>{t.push(s)>Ws&&t.splice(0,1)},remove:s=>{pn(t,s)},drain:s=>{t.forEach(o=>o(s)),t.length=0}}}const te={log:"log",configuration:"configuration",usage:"usage"},Xs=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],Ys=[jr];let En=gn(),ce=t=>{En.add(()=>ce(t))};function qs(t,e){let n;const r=new R,s=new Set,o=!Ys.includes(e.site)&&we(e.telemetrySampleRate),i={[te.log]:o,[te.configuration]:o&&we(e.telemetryConfigurationSampleRate),[te.usage]:o&&we(e.telemetryUsageSampleRate)},a=Hs();ce=c=>{const l=J(c);if(i[c.type]&&s.size<e.maxTelemetryEventsPerPage&&!s.has(l)){const d=u(t,c,a);r.notify(d),fn("telemetry",d),s.add(l)}},tr(yn);function u(c,l,d){return ae({type:"telemetry",date:N(),service:c,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:ae(l,{runtime_env:d,connectivity:Gs(),sdk_setup:"npm"}),experimental_features:Array.from(as())},n!==void 0?n():{})}return{setContextProvider:c=>{n=c},observable:r,enabled:o}}function Hs(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function zs(){En.drain()}function Vs(t){return t.site===$r}function bn(t,e){tt(_.debug,t,e),ce({type:te.log,message:t,status:"debug",...e})}function yn(t,e){ce({type:te.log,status:"error",...Zs(t),...e})}function Ks(t){ce({type:te.configuration,configuration:t})}function Js(t){ce({type:te.usage,usage:t})}function Zs(t){if(W(t)){const e=k(t);return{error:{kind:e.name,stack:Z(Qs(e))},message:e.message}}return{error:{stack:rn},message:`Uncaught ${J(t)}`}}function Qs(t){return t.stack=t.stack.filter(e=>!e.url||Xs.some(n=>e.url.startsWith(n))),t}const _e=1/0,eo=H;let Te=null;const je=new Set;function to(){je.forEach(t=>t())}function no({expireDelay:t,maxEntries:e}){let n=[];const r=[];Te||(Te=nt(()=>to(),eo));const s=()=>{const h=Ce()-t;for(;n.length>0&&n[n.length-1].endTime<h;){const m=n.pop();m&&r.push(m.startTime)}};je.add(s);function o(h,m){const E={value:h,startTime:m,endTime:_e,remove:()=>{pn(n,E)},close:y=>{E.endTime=y}};return e&&n.length>=e&&n.pop(),n.unshift(E),E}function i(h=_e,m={returnInactive:!1}){for(const E of n)if(E.startTime<=h){if(m.returnInactive||h<=E.endTime)return E.value;break}}function a(h){const m=n[0];m&&m.endTime===_e&&m.close(h)}function u(h=_e,m=0){const E=Jn(h,m);return n.filter(y=>y.startTime<=E&&h<=y.endTime).map(y=>y.value)}function c(){return n.map(({startTime:h,endTime:m,value:E})=>({startTime:h,endTime:m===_e?"Infinity":m,value:E}))}function l(){return r}function d(){n=[]}function f(){je.delete(s),je.size===0&&Te&&(Nt(Te),Te=null)}return{add:o,find:i,closeActive:a,findAll:u,reset:d,stop:f,getAllEntries:c,getDeletedEntries:l}}const ro=H,so=it;function oo(t,e,n,r){const s=new R,o=new R,i=Mr(t.sessionStoreStrategyType,t,e,n),a=no({expireDelay:so});i.renewObservable.subscribe(()=>{a.add(u(),Ce()),s.notify()}),i.expireObservable.subscribe(()=>{o.notify(),a.closeActive(Ce())}),i.expandOrRenewSession(),a.add(u(),Vn().relative),r.observable.subscribe(()=>{r.isGranted()?i.expandOrRenewSession():i.expire()}),io(t,()=>{r.isGranted()&&i.expandOrRenewSession()}),ao(t,()=>i.expandSession()),co(t,()=>i.restartSession());function u(){return{id:i.getSession().id,trackingType:i.getSession()[e],isReplayForced:!!i.getSession().forcedReplay,anonymousId:i.getSession().anonymousId}}return{findSession:(c,l)=>a.find(c,l),renewObservable:s,expireObservable:o,sessionStateUpdateObservable:i.sessionStateUpdateObservable,expire:i.expire,updateSessionState:i.updateSessionState}}function io(t,e){Et(t,window,["click","touchstart","keydown","scroll"],e,{capture:!0,passive:!0})}function ao(t,e){const n=()=>{document.visibilityState==="visible"&&e()};ee(t,document,"visibilitychange",n),nt(n,ro)}function co(t,e){ee(t,window,"resume",e,{capture:!0})}function Sn(t){return t>=500}function uo(t){try{return t.clone()}catch{return}}const lo=80*P,fo=32,_n=3*Pt,ho=H,Tn=fe;function Rn(t,e,n,r,s){e.transportStatus===0&&e.queuedPayloads.size()===0&&e.bandwidthMonitor.canHandle(t)?vn(t,e,n,{onSuccess:()=>wn(0,e,n,r,s),onFailure:()=>{e.queuedPayloads.enqueue(t),An(e,n,r,s)}}):e.queuedPayloads.enqueue(t)}function An(t,e,n,r){t.transportStatus===2&&ge(()=>{const s=t.queuedPayloads.first();vn(s,t,e,{onSuccess:()=>{t.queuedPayloads.dequeue(),t.currentBackoffTime=Tn,wn(1,t,e,n,r)},onFailure:()=>{t.currentBackoffTime=Math.min(ho,t.currentBackoffTime*2),An(t,e,n,r)}})},t.currentBackoffTime)}function vn(t,e,n,{onSuccess:r,onFailure:s}){e.bandwidthMonitor.add(t),n(t,o=>{e.bandwidthMonitor.remove(t),mo(o)?(e.transportStatus=e.bandwidthMonitor.ongoingRequestCount>0?1:2,t.retry={count:t.retry?t.retry.count+1:1,lastFailureStatus:o.status},s()):(e.transportStatus=0,r())})}function wn(t,e,n,r,s){t===0&&e.queuedPayloads.isFull()&&!e.queueFullReported&&(s({message:`Reached max ${r} events size queued for upload: ${_n/Pt}MiB`,source:I.AGENT,startClocks:B()}),e.queueFullReported=!0);const o=e.queuedPayloads;for(e.queuedPayloads=Cn();o.size()>0;)Rn(o.dequeue(),e,n,r,s)}function mo(t){return t.type!=="opaque"&&(t.status===0&&!navigator.onLine||t.status===408||t.status===429||Sn(t.status))}function po(){return{transportStatus:0,currentBackoffTime:Tn,bandwidthMonitor:go(),queuedPayloads:Cn(),queueFullReported:!1}}function Cn(){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>=_n}}}function go(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(t){return this.ongoingRequestCount===0||this.ongoingByteCount+t.bytesCount<=lo&&this.ongoingRequestCount<fo},add(t){this.ongoingRequestCount+=1,this.ongoingByteCount+=t.bytesCount},remove(t){this.ongoingRequestCount-=1,this.ongoingByteCount-=t.bytesCount}}}function Eo(t,e,n){const r=po(),s=(o,i)=>So(t,e,o,i);return{send:o=>{Rn(o,r,s,t.trackType,n)},sendOnExit:o=>{bo(t,e,o)}}}function bo(t,e,n){if(!!navigator.sendBeacon&&n.bytesCount<e)try{const o=t.build("beacon",n);if(navigator.sendBeacon(o,n.data))return}catch(o){yo(o)}const s=t.build("xhr",n);bt(s,n.data)}let xn=!1;function yo(t){xn||(xn=!0,yn(t))}function So(t,e,n,r){if(_o()&&n.bytesCount<e){const o=t.build("fetch",n);fetch(o,{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=t.build("xhr",n);bt(i,n.data,r)}))}else{const o=t.build("xhr",n);bt(o,n.data,r)}}function _o(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function bt(t,e,n){const r=new XMLHttpRequest;r.open("POST",t,!0),e instanceof Blob&&r.setRequestHeader("Content-Type",e.type),ee({allowUntrustedEvents:!0},r,"loadend",()=>{n==null||n({status:r.status})},{once:!0}),r.send(e)}function yt(){const t=To();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,n,r){const s=r?{id:r}:void 0;t.send(JSON.stringify({eventType:e,event:n,view:s}))}}}function We(t){var e;t===void 0&&(t=(e=$().location)===null||e===void 0?void 0:e.hostname);const n=yt();return!!n&&n.getAllowedWebViewHosts().some(r=>t===r||t.endsWith(`.${r}`))}function To(){return $().DatadogEventBridge}const Xe={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function Ro(t){return new R(e=>{const{stop:n}=Et(t,window,["visibilitychange","freeze"],s=>{s.type==="visibilitychange"&&document.visibilityState==="hidden"?e.notify({reason:Xe.HIDDEN}):s.type==="freeze"&&e.notify({reason:Xe.FROZEN})},{capture:!0}),r=ee(t,window,"beforeunload",()=>{e.notify({reason:Xe.UNLOADING})}).stop;return()=>{n(),r()}})}function Ao(t){return Ie(Xe).includes(t)}function vo({encoder:t,request:e,flushController:n,messageBytesLimit:r}){let s={};const o=n.flushObservable.subscribe(d=>l(d));function i(d,f,h){n.notifyBeforeAddMessage(f),h!==void 0?(s[h]=d,n.notifyAfterAddMessage()):t.write(t.isEmpty?d:`\n${d}`,m=>{n.notifyAfterAddMessage(m-f)})}function a(d){return d!==void 0&&s[d]!==void 0}function u(d){const f=s[d];delete s[d];const h=t.estimateEncodedBytesCount(f);n.notifyAfterRemoveMessage(h)}function c(d,f){const h=J(d),m=t.estimateEncodedBytesCount(h);if(m>=r){T.warn(`Discarded a message whose size was bigger than the maximum allowed size ${r}KB. ${ve} ${Ot}/#technical-limitations`);return}a(f)&&u(f),i(h,m,f)}function l(d){const f=Ie(s).join(`\n`);s={};const h=Ao(d.reason),m=h?e.sendOnExit:e.send;if(h&&t.isAsync){const E=t.finishSync();E.outputBytesCount&&m(Ln(E));const y=[E.pendingData,f].filter(Boolean).join(`\n`);y&&m({data:y,bytesCount:et(y)})}else f&&t.write(t.isEmpty?f:`\n${f}`),t.finish(E=>{m(Ln(E))})}return{flushController:n,add:c,upsert:c,stop:o.unsubscribe}}function Ln(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 wo({messagesLimit:t,bytesLimit:e,durationLimit:n,pageExitObservable:r,sessionExpireObservable:s}){const o=r.subscribe(m=>l(m.reason)),i=s.subscribe(()=>l("session_expire")),a=new R(()=>()=>{o.unsubscribe(),i.unsubscribe()});let u=0,c=0;function l(m){if(c===0)return;const E=c,y=u;c=0,u=0,h(),a.notify({reason:m,messagesCount:E,bytesCount:y})}let d;function f(){d===void 0&&(d=ge(()=>{l("duration_limit")},n))}function h(){Ft(d),d=void 0}return{flushObservable:a,get messagesCount(){return c},notifyBeforeAddMessage(m){u+m>=e&&l("bytes_limit"),c+=1,u+=m,f()},notifyAfterAddMessage(m=0){u+=m,c>=t?l("messages_limit"):u>=e&&l("bytes_limit")},notifyAfterRemoveMessage(m){u-=m,c-=1,c===0&&h()}}}function On(t,e,n,r,s,o,i=vo){const a=c(t,e),u=n&&c(t,n);function c(l,{endpoint:d,encoder:f}){return i({encoder:f,request:Eo(d,l.batchBytesLimit,r),flushController:wo({messagesLimit:l.batchMessagesLimit,bytesLimit:l.batchBytesLimit,durationLimit:l.flushTimeout,pageExitObservable:s,sessionExpireObservable:o}),messageBytesLimit:l.messageBytesLimit})}return{flushObservable:a.flushController.flushObservable,add(l,d=!0){a.add(l),u&&d&&u.add(n.transformMessage?n.transformMessage(l):l)},upsert:(l,d)=>{a.upsert(l,d),u&&u.upsert(n.transformMessage?n.transformMessage(l):l,d)},stop:()=>{a.stop(),u&&u.stop()}}}function Ye(){let t="",e=0;return{isAsync:!1,get isEmpty(){return!t},write(n,r){const s=et(n);e+=s,t+=n,r&&r(s)},finish(n){n(this.finishSync())},finishSync(){const n={output:t,outputBytesCount:e,rawBytesCount:e,pendingData:""};return t="",e=0,n},estimateEncodedBytesCount(n){return n.length}}}class Co{constructor(){this.callbacks={}}notify(e,n){const r=this.callbacks[e];r&&r.forEach(s=>s(n))}subscribe(e,n){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(n),{unsubscribe:()=>{this.callbacks[e]=this.callbacks[e].filter(r=>n!==r)}}}}function xo(t,e,n){let r=0,s=!1;return{isLimitReached(){if(r===0&&ge(()=>{r=0},H),r+=1,r<=e||s)return s=!1,!1;if(r===e+1){s=!0;try{n({message:`Reached max number of ${t}s by minute: ${e}`,source:I.AGENT,startClocks:B()})}finally{s=!1}}return!0}}}let St;const _t=new WeakMap;function Lo(t){return St||(St=Oo(t)),St}function Oo(t){return new R(e=>{const{stop:n}=Q(XMLHttpRequest.prototype,"open",Io),{stop:r}=Q(XMLHttpRequest.prototype,"send",o=>{Uo(o,t,e)},{computeHandlingStack:!0}),{stop:s}=Q(XMLHttpRequest.prototype,"abort",Do);return()=>{n(),r(),s()}})}function Io({target:t,parameters:[e,n]}){_t.set(t,{state:"open",method:String(e).toUpperCase(),url:lt(String(n))})}function Uo({target:t,handlingStack:e},n,r){const s=_t.get(t);if(!s)return;const o=s;o.state="start",o.startClocks=B(),o.isAborted=!1,o.xhr=t,o.handlingStack=e;let i=!1;const{stop:a}=Q(t,"onreadystatechange",()=>{t.readyState===XMLHttpRequest.DONE&&u()}),u=()=>{if(c(),a(),i)return;i=!0;const l=s;l.state="complete",l.duration=Kn(o.startClocks.timeStamp,N()),l.status=t.status,r.notify(er(l))},{stop:c}=ee(n,t,"loadend",u);r.notify(o)}function Do({target:t}){const e=_t.get(t);e&&(e.isAborted=!0)}let Tt;function In(){return Tt||(Tt=Po()),Tt}function Po(){return new R(t=>{if(!window.fetch)return;const{stop:e}=Q(window,"fetch",n=>ko(n,t),{computeHandlingStack:!0});return e})}function ko({parameters:t,onPostCall:e,handlingStack:n},r){const[s,o]=t;let i=o&&o.method;i===void 0&&s instanceof Request&&(i=s.method);const a=i!==void 0?String(i).toUpperCase():"GET",u=s instanceof Request?s.url:lt(String(s)),c=B(),l={state:"start",init:o,input:s,method:a,startClocks:c,url:u,handlingStack:n};r.notify(l),t[0]=l.input,t[1]=l.init,e(d=>Mo(r,d,l))}function Mo(t,e,n){const r=n;function s(o){r.state="resolve",Object.assign(r,o),t.notify(r)}e.then(b(o=>{s({response:o,responseType:o.type,status:o.status,isAborted:!1})}),b(o=>{var i,a;s({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 Rt={};function Fo(t){const e=t.map(n=>(Rt[n]||(Rt[n]=No(n)),Rt[n]));return Bt(...e)}function No(t){return new R(e=>{const n=D[t];return D[t]=(...r)=>{n.apply(console,r);const s=Be("console error");pe(()=>{e.notify(Bo(r,t,s))})},()=>{D[t]=n}})}function Bo(t,e,n){const r=t.map(o=>$o(o)).join(" ");let s;if(e===_.error){const o=t.find(W);s={stack:o?Z(k(o)):void 0,fingerprint:on(o),causes:o?cn(o,"console"):void 0,startClocks:B(),message:r,source:I.CONSOLE,handling:"handled",handlingStack:n,context:an(o)}}return{api:e,message:r,error:s,handlingStack:n}}function $o(t){return typeof t=="string"?M(t):W(t)?nn(k(t)):J(M(t),void 0,2)}function Go(t){const e=hn(t)==="object";return e||T.error("Unsupported context:",t),e}function At(t,e,n){const r={...t};for(const[s,{required:o,type:i}]of Object.entries(e))i==="string"&&s in r&&(r[s]=String(r[s])),o&&!(s in t)&&T.warn(`The property ${s} of ${n} is required; context will not be sent to the intake.`);return r}function qe(t="",{customerDataTracker:e,propertiesConfig:n={}}={}){let r={};const s=new R,o={getContext:()=>mn(r),setContext:i=>{Go(i)?(r=M(At(i,n,t)),e==null||e.updateCustomerData(r)):o.clearContext(),s.notify()},setContextProperty:(i,a)=>{r=M(At({...r,[i]:a},n,t)),e==null||e.updateCustomerData(r),s.notify()},removeContextProperty:i=>{delete r[i],e==null||e.updateCustomerData(r),At(r,n,t),s.notify()},clearContext:()=>{r={},e==null||e.resetCustomerData(),s.notify()},changeObservable:s};return o}const jo="_dd_c",Wo=[];function vt(t,e,n,r){const s=Xo(n,r);Wo.push(ee(t,window,"storage",({key:c})=>{s===c&&i()})),e.changeObservable.subscribe(a);const o=ae(u(),e.getContext());me(o)||e.setContext(o);function i(){e.setContext(u())}function a(){localStorage.setItem(s,JSON.stringify(e.getContext()))}function u(){const c=localStorage.getItem(s);return c?JSON.parse(c):{}}}function Xo(t,e){return`${jo}_${t}_${e}`}const Yo=3*P,qo=16*P,Ho=200;function zo(t=2){const e=new Map;let n=!1;function r(s=0){if(n||t===0)return;const o=t===2?Yo:qo;let i=s;e.forEach(a=>{i+=a.getBytesCount()}),i>o&&(Vo(o),n=!0)}return{createDetachedTracker:()=>{const s=Un(()=>r(s.getBytesCount()));return s},getOrCreateTracker:s=>(e.has(s)||e.set(s,Un(r)),e.get(s)),setCompressionStatus:s=>{t===0&&(t=s,r())},getCompressionStatus:()=>t,stop:()=>{e.forEach(s=>s.stop()),e.clear()}}}function Un(t){let e=0;const{throttled:n,cancel:r}=$t(o=>{e=et(J(o)),t()},Ho),s=()=>{r(),e=0};return{updateCustomerData:o=>{me(o)?s():n(o)},resetCustomerData:s,getBytesCount:()=>e,stop:()=>{r()}}}function Vo(t){T.warn(`Customer data exceeds the recommended ${t/P}KiB threshold. ${ve} ${Ot}/#customer-data-exceeds-the-recommended-threshold-warning`)}function Ko(t,e,n){const r=t.getReader(),s=[];let o=0;i();function i(){r.read().then(b(u=>{if(u.done){a();return}s.push(u.value),o+=u.value.length,o>n.bytesLimit?a():i()}),b(u=>e(u)))}function a(){r.cancel().catch(G);let u,c;{let l;if(s.length===1)l=s[0];else{l=new Uint8Array(o);let d=0;s.forEach(f=>{l.set(f,d),d+=f.length})}u=l.slice(0,n.bytesLimit),c=l.length>n.bytesLimit}e(void 0,u,c)}}const Jo="datadog-synthetics-public-id",Zo="datadog-synthetics-result-id",Qo="datadog-synthetics-injects-rum";function Dn(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||z(Qo))}function ei(){const t=window._DATADOG_SYNTHETICS_PUBLIC_ID||z(Jo);return typeof t=="string"?t:void 0}function ti(){const t=window._DATADOG_SYNTHETICS_RESULT_ID||z(Zo);return typeof t=="string"?t:void 0}function He(t,e,n){const r=n.getHandler(),s=Array.isArray(r)?r:[r];return Pn[t]>=Pn[n.getLevel()]&&s.includes(e)}const p={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},Pn={[p.ok]:0,[p.debug]:1,[p.info]:2,[p.notice]:4,[p.warn]:5,[p.error]:6,[p.critical]:7,[p.alert]:8,[p.emerg]:9};function ze(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 ni=function(t,e,n,r){var s=arguments.length,o=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(o=(s<3?i(o):s>3?i(e,n,o):i(e,n))||o);return s>3&&o&&Object.defineProperty(e,n,o),o};const Re={console:"console",http:"http",silent:"silent"},ri=Object.keys(p);let U=class{constructor(e,n,r,s=Re.http,o=p.debug,i={}){this.handleLogStrategy=e,this.handlerType=s,this.level=o,this.contextManager=qe("logger",{customerDataTracker:n}),this.contextManager.setContext(i),r&&this.contextManager.setContextProperty("logger",{name:r})}logImplementation(e,n,r=p.info,s,o){const i=M(n);let a;if(s!=null){const u=sn({stackTrace:W(s)?k(s):void 0,originalError:s,nonErrorPrefix:"Provided",source:I.LOGGER,handling:"handled",startClocks:B()});a=ae({error:ze(u,{includeMessage:!0})},i)}else a=i;this.handleLogStrategy({message:M(e),context:a,status:r},this,o)}log(e,n,r=p.info,s){let o;He(r,Re.http,this)&&(o=Be("log")),this.logImplementation(e,n,r,s,o)}setContext(e){this.contextManager.setContext(e)}getContext(){return this.contextManager.getContext()}setContextProperty(e,n){this.contextManager.setContextProperty(e,n)}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}};ni([rr],U.prototype,"logImplementation",null),U.prototype.ok=F(p.ok),U.prototype.debug=F(p.debug),U.prototype.info=F(p.info),U.prototype.notice=F(p.notice),U.prototype.warn=F(p.warn),U.prototype.error=F(p.error),U.prototype.critical=F(p.critical),U.prototype.alert=F(p.alert),U.prototype.emerg=F(p.emerg);function F(t){return function(e,n,r){let s;He(t,Re.http,this)&&(s=Be("log")),this.logImplementation(e,n,t,r,s)}}function si(t,e,n){return{view:{referrer:document.referrer,url:window.location.href},context:t.getContext(),user:e.getContext(),account:n.getContext()}}const oi=32*P;function ii(t){t.usePciIntake===!0&&t.site&&t.site!=="datadoghq.com"&&T.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");const e=rs(t),n=kn(t.forwardConsoleLogs,Ie(_),"Forward Console Logs"),r=kn(t.forwardReports,Ie($e),"Forward Reports");if(!(!e||!n||!r))return t.forwardErrorsToLogs&&!n.includes(_.error)&&n.push(_.error),{forwardErrorsToLogs:t.forwardErrorsToLogs!==!1,forwardConsoleLogs:n,forwardReports:r,requestErrorResponseLengthLimit:oi,...e}}function kn(t,e,n){if(t===void 0)return[];if(!(t==="all"||Array.isArray(t)&&t.every(r=>e.includes(r)))){T.error(`${n} should be "all" or an array with allowed values "${e.join(\'", "\')}"`);return}return t==="all"?e:js(t)}function ai(t){const e=ss(t);return{forward_errors_to_logs:t.forwardErrorsToLogs,forward_console_logs:t.forwardConsoleLogs,forward_reports:t.forwardReports,use_pci_intake:t.usePciIntake,...e}}function ci(t,e,n){const r=gn();let s,o;const i=e.observable.subscribe(a);function a(){if(!o||!s||!e.isGranted())return;i.unsubscribe();const u=n(s,o);r.drain(u)}return{init(u){if(!u){T.error("Missing configuration");return}if(os(u.enableExperimentalFeatures),We()&&(u=ui(u)),s=u,o){un("DD_LOGS",u);return}const c=ii(u);c&&(o=c,In().subscribe(G),e.tryToInit(c.trackingConsent),a())},get initConfiguration(){return s},getInternalContext:G,handleLog(u,c,l,d=t(),f=N()){r.add(h=>h.handleLog(u,c,l,d,f))}}}function ui(t){return{...t,clientToken:"empty"}}const wt="logs";function li(t){const e=zo(),n=qe("global context",{customerDataTracker:e.getOrCreateTracker(2)}),r=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"}}}),o=Fr();function i(){return si(n,r,s)}let a=ci(i,o,(l,d)=>{l.storeContextsAcrossPages&&(vt(d,n,wt,2),vt(d,r,wt,1),vt(d,s,wt,4));const f=t(l,d,i,o);return a=di(l,f),f});const u={},c=new U((...l)=>a.handleLog(...l),e.createDetachedTracker());return Ds({logger:c,init:b(l=>a.init(l)),setTrackingConsent:b(l=>{o.update(l),Js({feature:"set-tracking-consent",tracking_consent:l})}),getGlobalContext:b(()=>n.getContext()),setGlobalContext:b(l=>n.setContext(l)),setGlobalContextProperty:b((l,d)=>n.setContextProperty(l,d)),removeGlobalContextProperty:b(l=>n.removeContextProperty(l)),clearGlobalContext:b(()=>n.clearContext()),createLogger:b((l,d={})=>(u[l]=new U((...f)=>a.handleLog(...f),e.createDetachedTracker(),M(l),d.handler,d.level,M(d.context)),u[l])),getLogger:b(l=>u[l]),getInitConfiguration:b(()=>mn(a.initConfiguration)),getInternalContext:b(l=>a.getInternalContext(l)),setUser:b(r.setContext),getUser:b(r.getContext),setUserProperty:b(r.setContextProperty),removeUserProperty:b(r.removeContextProperty),clearUser:b(r.clearContext),setAccount:b(s.setContext),getAccount:b(s.getContext),setAccountProperty:b(s.setContextProperty),removeAccountProperty:b(s.removeContextProperty),clearAccount:b(s.clearContext)})}function di(t,e){return{init:n=>{un("DD_LOGS",n)},initConfiguration:t,...e}}const fi="logs";function hi(t,e){const n=oo(t,fi,r=>pi(t,r),e);return{findTrackedSession:(r,s={returnInactive:!1})=>{const o=n.findSession(r,s);return o&&o.trackingType==="1"?{id:o.id,anonymousId:o.anonymousId}:void 0},expireObservable:n.expireObservable}}function mi(t){const n=Mn(t)==="1"?{}:void 0;return{findTrackedSession:()=>n,expireObservable:new R}}function Mn(t){return we(t.sessionSampleRate)?"1":"0"}function pi(t,e){const n=gi(e)?e:Mn(t);return{trackingType:n,isTracked:n==="1"}}function gi(t){return t==="0"||t==="1"}let Fn=!1;function Ve(t){const e=window;if(Dn()){const r=n(e.DD_RUM_SYNTHETICS);return!r&&!Fn&&(Fn=!0,bn("Logs sent before RUM is injected by the synthetics worker",{testId:ei(),resultId:ti()})),r}return n(e.DD_RUM);function n(r){if(r&&r.getInternalContext)return r.getInternalContext(t)}}function Ei(t,e,n,r,s){const o=ri.concat(["custom"]),i={};o.forEach(a=>{i[a]=xo(a,e.eventRateLimiterThreshold,s)}),n.subscribe(0,({rawLogsEvent:a,messageContext:u=void 0,savedCommonContext:c=void 0,domainContext:l})=>{var d,f;const h=Zn(a.date),m=t.findTrackedSession(h);if(!t.findTrackedSession(h,{returnInactive:!0}))return;const y=c||r();let O;!me(y.account)&&y.account.id&&(O=y.account),m&&m.anonymousId&&!y.user.anonymous_id&&(y.user.anonymous_id=m.anonymousId);const x=ae({service:e.service,session_id:m?m.id:void 0,session:m?{id:m.id}:void 0,usr:me(y.user)?void 0:y.user,account:O,view:y.view},y.context,Ve(h),a,u);((d=e.beforeSend)===null||d===void 0?void 0:d.call(e,x,l))===!1||x.origin!==I.AGENT&&((f=i[x.status])!==null&&f!==void 0?f:i.custom).isLimitReached()||n.notify(1,x)})}const bi={[_.log]:p.info,[_.debug]:p.debug,[_.info]:p.info,[_.warn]:p.warn,[_.error]:p.error};function yi(t,e){const n=Fo(t.forwardConsoleLogs).subscribe(r=>{var s;const o={rawLogsEvent:{date:N(),message:r.message,origin:I.CONSOLE,error:r.error&&ze(r.error),status:bi[r.api]},messageContext:(s=r.error)===null||s===void 0?void 0:s.context,domainContext:{handlingStack:r.handlingStack}};e.notify(0,o)});return{stop:()=>{n.unsubscribe()}}}function Si(t,e){const n=ks(t,t.forwardReports).subscribe(r=>{let s=r.message,o;const i=r.originalError.type==="deprecation"?p.warn:p.error;i===p.error?o=ze(r):r.stack&&(s+=` Found in ${Ls(r.stack)}`),e.notify(0,{rawLogsEvent:{date:N(),message:s,origin:I.REPORT,error:o,status:i}})});return{stop:()=>{n.unsubscribe()}}}function _i(t,e){if(!t.forwardErrorsToLogs)return{stop:G};const n=Lo(t).subscribe(o=>{o.state==="complete"&&s("xhr",o)}),r=In().subscribe(o=>{o.state==="resolve"&&s("fetch",o)});function s(o,i){!ts(i.url)&&(vi(i)||Sn(i.status))&&("xhr"in i?Ti(i.xhr,t,a):i.response?Ai(i.response,t,a):i.error&&Ri(i.error,t,a));function a(u){const c={isAborted:i.isAborted,handlingStack:i.handlingStack};e.notify(0,{rawLogsEvent:{message:`${wi(o)} error ${i.method} ${i.url}`,date:i.startClocks.timeStamp,error:{stack:u||"Failed to load",handling:void 0},http:{method:i.method,status_code:i.status,url:i.url},status:p.error,origin:I.NETWORK},domainContext:c})}}return{stop:()=>{n.unsubscribe(),r.unsubscribe()}}}function Ti(t,e,n){typeof t.response=="string"?n(Ct(t.response,e)):n(t.response)}function Ri(t,e,n){n(Ct(Z(k(t)),e))}function Ai(t,e,n){const r=uo(t);!r||!r.body?n():window.TextDecoder?Ci(r.body,e.requestErrorResponseLengthLimit,(s,o)=>{n(s?`Unable to retrieve response: ${s}`:o)}):r.text().then(b(s=>n(Ct(s,e))),b(s=>n(`Unable to retrieve response: ${s}`)))}function vi(t){return t.status===0&&t.responseType!=="opaque"}function Ct(t,e){return t.length>e.requestErrorResponseLengthLimit?`${t.substring(0,e.requestErrorResponseLengthLimit)}...`:t}function wi(t){return t==="xhr"?"XHR":"Fetch"}function Ci(t,e,n){Ko(t,(r,s,o)=>{if(r)n(r);else{let i=new TextDecoder().decode(s);o&&(i+="..."),n(void 0,i)}},{bytesLimit:e,collectStreamBody:!0})}function xi(t,e){if(!t.forwardErrorsToLogs)return{stop:G};const n=new R,{stop:r}=Os(n),s=n.subscribe(o=>{e.notify(0,{rawLogsEvent:{message:o.message,date:o.startClocks.timeStamp,error:ze(o),origin:I.SOURCE,status:p.error},messageContext:o.context})});return{stop:()=>{r(),s.unsubscribe()}}}const Li=Co;function Oi(t){function e(n,r,s,o,i){const a=ae(r.getContext(),n.context);if(He(n.status,Re.console,r)&&Ui(n,a),He(n.status,Re.http,r)){const u={rawLogsEvent:{date:i||N(),message:n.message,status:n.status,origin:I.LOGGER},messageContext:a,savedCommonContext:o};s&&(u.domainContext={handlingStack:s}),t.notify(0,u)}}return{handleLog:e}}const Ii={[p.ok]:_.debug,[p.debug]:_.debug,[p.info]:_.info,[p.notice]:_.info,[p.warn]:_.warn,[p.error]:_.error,[p.critical]:_.error,[p.alert]:_.error,[p.emerg]:_.error};function Ui({status:t,message:e},n){q[Ii[t]].call(D,e,n)}function Di(t,e,n,r,s){const o=On(t,{endpoint:t.logsEndpointBuilder,encoder:Ye()},t.replica&&{endpoint:t.replica.logsEndpointBuilder,encoder:Ye()},n,r,s.expireObservable);return e.subscribe(1,i=>{o.add(i)}),o}function Pi(t){const e=yt();t.subscribe(1,n=>{e.send("log",n)})}function ki(t){return{get:e=>{const n=t.findTrackedSession(e);if(n)return{session_id:n.id}}}}function Mi(t){return e=>{t.notify(0,{rawLogsEvent:{message:e.message,date:e.startClocks.timeStamp,origin:I.AGENT,status:p.error}}),bn("Error reported to customer",{"error.message":e.message})}}function Fi(t,e,n,r,s){const o=qs("browser-logs-sdk",e);o.setContextProvider(()=>{var a,u,c,l,d,f;return{application:{id:(a=Ve())===null||a===void 0?void 0:a.application_id},session:{id:(u=s.findTrackedSession())===null||u===void 0?void 0:u.id},view:{id:(l=(c=Ve())===null||c===void 0?void 0:c.view)===null||l===void 0?void 0:l.id},action:{id:(f=(d=Ve())===null||d===void 0?void 0:d.user_action)===null||f===void 0?void 0:f.id}}});const i=[];if(We()){const a=yt(),u=o.observable.subscribe(c=>a.send("internal_telemetry",c));i.push(()=>u.unsubscribe())}else{const a=On(e,{endpoint:e.rumEndpointBuilder,encoder:Ye()},e.replica&&{endpoint:e.replica.rumEndpointBuilder,encoder:Ye()},n,r,s.expireObservable);i.push(()=>a.stop());const u=o.observable.subscribe(c=>a.add(c,Vs(e)));i.push(()=>u.unsubscribe())}return zs(),Ks(ai(t)),{telemetry:o,stop:()=>{i.forEach(a=>a())}}}function Ni(t,e,n,r){const s=new Li,o=[];s.subscribe(1,f=>fn("logs",f));const i=Mi(s),a=Ro(e),u=e.sessionStoreStrategyType&&!We()&&!Dn()?hi(e,r):mi(e),{stop:c}=Fi(t,e,i,a,u);o.push(()=>c()),_i(e,s),xi(e,s),yi(e,s),Si(e,s);const{handleLog:l}=Oi(s);if(Ei(u,e,s,n,i),We())Pi(s);else{const{stop:f}=Di(e,s,i,a,u);o.push(()=>f())}const d=ki(u);return{handleLog:l,getInternalContext:d.get,stop:()=>{o.forEach(f=>f())}}}const ue=li(Ni);Ps($(),"DD_LOGS",ue);class v{constructor(e){this.isLoggingOn=e,e&&ue.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!1,sessionSampleRate:100})}static setMessagePort(e){this.messagePort=e}static getMessagePort(){return this.messagePort}setLoggingOn(e){this.isLoggingOn=e}setAttributes(e){for(const n in e)ue.logger.setContextProperty(n,e[n])}info(e,n){this.isLoggingOn&&(ue.logger.info(e,n),console.log("[Logger] Sending info: ",e))}error(e,n){this.isLoggingOn&&(ue.logger.error(e,n),console.log("[Logger] Sending error: ",e))}warn(e,n){this.isLoggingOn&&(ue.logger.warn(e,n),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){v.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:e})}static info(e,n){v.messagePort.postMessage({type:"LOG",actionType:"INFO",message:e,attributes:n})}static error(e,n){v.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:e,attributes:n})}static warn(e,n){v.messagePort.postMessage({type:"LOG",actionType:"WARN",message:e,attributes:n})}}const A=class A{constructor(e,n,r,s,o){this.copy=()=>new A(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,A.toStr(i)},this.toFrames=i=>{let a=60,u=0;Math.floor(i)==60?(a=60,u=0):Math.floor(i)==59?(a=60,u=4):Math.floor(i)==30?(a=30,u=0):Math.floor(i)==29&&(a=30,u=2);let c=this.h,l=this.m,d=this.s,f=this.f,h=this.field;const m=c*60+l,y=(m-Math.floor(m/10))*u;return c*(a*3600)+l*(a*60)+d*a+(f*2+h)-y},this.addSeconds=i=>{let a=this.copy();return a.s+=i,a.s>=60&&(a.s=0,a.m++,a.m>=60&&(a.m=0,a.h++)),a},this.addFrames=(i,a)=>{let u=this.toFrames(a);return u+=i,A.fromFrames(u,a)},this.subtractFrames=(i,a)=>this.addFrames(-i,a),this.h=e||0,this.m=n||0,this.s=r||0,this.f=s||0,this.field=o||0}static compare(e,n){return e.h!==n.h?e.h<n.h?-1:1:e.m!==n.m?e.m<n.m?-1:1:e.s!==n.s?e.s<n.s?-1:1:e.f!==n.f?e.f<n.f?-1:1:e.field!==n.field?e.field<n.field?-1:1:0}static generateTimecodeRange(e,n,r){const s=[];let o=e;for(;A.compare(o,n)<=0;)s.push(o),o=o.addSeconds(r);return s}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(e){return this.toFrames(e)*1e3/e}};A.calculateCurrentTimeCode=e=>{var d;if(!e.video||!e.clocker||!e.gameParams)throw new Error("OTTPlayer is not initialized");const n=e.video,r=e.clocker,s=r.videoFPScalculator.getFPS(),a=(n.currentTime-r.syncPoint.playerTime)%(60*60*24)*s+r.syncPoint.frame;if(a===0||s===0)throw new Error("Current frame is 0 or fps is 0");const u=A.calculateCurrentOffset(a,(d=e.gameParams)==null?void 0:d.offsets);if(u===void 0)throw new Error("Offset is undefined");let c=Math.floor(a-u);return c<0&&(c+=5178816),c>=5178816&&(c-=5178816),A.fromFrames(c,s)},A.calculateCurrentOffset=(e,n)=>{for(let r=1;r<n.length;r++)if(e<n[r].frame)return n[r-1].offset;return n[n.length-1].offset},A.fromFrames=(e,n)=>{let r=60,s=0;Math.floor(n)==60?(r=60,s=0):Math.floor(n)==59?(r=60,s=4):Math.floor(n)==30?(r=30,s=0):Math.floor(n)==29&&(r=30,s=2);let o=Math.floor(n*60),i=Math.floor(n*60*10),a=i*6,u=e,c=Math.floor(u/a);u-=c*a;let l=Math.floor(u/i);u-=l*i,u>=r*60&&(u+=s*(Math.floor((u-r*60)/o)+1));let d=Math.floor(u/(r*60));u-=d*(r*60);let f=Math.floor(u/r);u-=f*r;let h=u;d+=l*10;let m=0;return m=h%2,h=Math.floor(h/2),new A(c,d,f,h,m)},A.toStr=e=>{const n="_";let r=("0"+e.h).slice(-2)+n+("0"+e.m).slice(-2)+n+("0"+e.s).slice(-2)+n+("0"+e.f).slice(-2);return e.field&&(r+="_1"),r},A.fromStr=e=>{const r=e.split("_").map(Number);if(r.length==4){const[s,o,i,a]=r;return new A(s,o,i,a,0)}else if(r.length==5){const[s,o,i,a,u]=r;return new A(s,o,i,a,u)}else throw new Error("Invalid timecode format: "+e)},A.fromMetadata=e=>{const n=/^(\\d{2}):(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d))?$/,r=e.timecode.match(n);if(!r)throw new Error("Invalid timecode format: "+e.timecode);const[,s,o,i,a,u]=r,c=Number(s),l=Number(o),d=Number(i),f=Number(a),h=u?Number(u):0;return new A(c,l,d,f,h)};let X=A;const Bi=`\nprecision highp float;\n\nattribute vec2 a_position; // pixel coords, 6 verts / quad\nattribute vec4 a_uv; // atlas UV (min_u, min_v, max_u, max_v)\nattribute mat3 a_transform; // transformation matrix for this vertex\n\nuniform vec2 u_resolution; // full frame size\n\nvarying vec2 v_maskUV; // for alpha mask\nvarying vec4 v_adUV; // atlas UV bounds\nvarying mat3 v_transform; // pass transform to fragment shader\n\nvoid main () {\n vec2 clipSpace = 2.0 * (a_position / u_resolution) - 1.0;\n gl_Position = vec4(clipSpace * vec2(1.0,-1.0), 0.0, 1.0);\n\n v_adUV = a_uv; // Pass through all 4 UV coordinates\n v_maskUV = a_position / u_resolution;\n v_transform = a_transform;\n}\n`,$i=`\nprecision highp float;\n\nuniform sampler2D u_atlas; // packed logos\nuniform sampler2D u_alphaMask; // full-frame mask (changes every video frame)\nuniform float u_opacity;\nuniform vec2 u_resolution; // full frame size\n\nvarying vec4 v_adUV; // min_u, min_v, max_u, max_v\nvarying vec2 v_maskUV;\nvarying mat3 v_transform; // transformation matrix for this fragment\n\nconst float Directions = 16.0; // BLUR DIRECTIONS\nconst float QualityAd = 3.0; // BLUR QUALITY\nconst float BlurRadiusAd = 3.0;\n\n// Pi here is 2*pi = 6.283185..., so we can do 16 steps across 2*pi\nconst float Pi = 6.28318530718;\n\nvec4 BlurAd(sampler2D adTexture, vec2 adTexCoord) {\n // Convert our "BlurRadiusAd" to texture coords\n vec2 radius = BlurRadiusAd / u_resolution.xy;\n \n // Start by sampling once at the center\n vec4 resultColor = texture2D(adTexture, adTexCoord);\n int sampleCount = 1;\n\n // Convert float constants into integer loop bounds\n const int directions = int(Directions);\n const int quality = int(QualityAd);\n\n // For each direction around the circle...\n for (int d = 0; d < directions; d++) {\n // angle goes from 0 to 2*pi in increments of 2*pi/directions\n float angle = float(d) * (Pi / float(directions));\n\n // For each blur step outward in that direction\n for (int i = 1; i <= quality; i++) {\n // E.g. if quality=3, i goes 1..3\n float step = float(i) / float(quality);\n\n // offset is step fraction of the full radius, in polar coords\n vec2 offset = step * radius * vec2(cos(angle), sin(angle));\n\n // Accumulate that sample\n resultColor += texture2D(adTexture, adTexCoord + offset);\n sampleCount++;\n }\n }\n\n // Divide by the total sample count to average\n return resultColor / float(sampleCount);\n}\n\nvec2 transformPoint(vec2 point) {\n float x = (v_transform[0][0] * point.x + v_transform[0][1] * point.y + v_transform[0][2]) / \n (v_transform[2][0] * point.x + v_transform[2][1] * point.y + 1.0);\n float y = (v_transform[1][0] * point.x + v_transform[1][1] * point.y + v_transform[1][2]) / \n (v_transform[2][0] * point.x + v_transform[2][1] * point.y + 1.0);\n return vec2(x, y) / u_resolution;\n}\n\nvoid main () {\n // Transform the current position using the transformation matrix\n vec2 transformedUV = transformPoint(vec2(gl_FragCoord.x, u_resolution.y - gl_FragCoord.y));\n \n // If the transformed coordinate is outside [0,1], discard the fragment\n if(transformedUV.x < 0.0 || transformedUV.x > 1.0 || transformedUV.y < 0.0 || transformedUV.y > 1.0) {\n discard;\n }\n\n // Map the transformed coordinate to the atlas region\n vec2 atlasUV = mix(vec2(v_adUV.x, v_adUV.y), // min_u, min_v\n vec2(v_adUV.z, v_adUV.w), // max_u, max_v\n transformedUV); // interpolation factor\n \n float mask = texture2D(u_alphaMask, v_maskUV).r;\n vec4 ad = BlurAd(u_atlas, atlasUV);\n\n float a = ad.a * mask * u_opacity;\n gl_FragColor = vec4(ad.rgb * a, a);\n //gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); // Force black color for testing\n}\n`;class Nn{constructor(e,n){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.queryInFlight=!1,this.GPUFrameTimeCount=0,this.GPUFrameTimeSum=0,this.avgGPUFrameTime=0,this.CPUFrameTimeCount=0,this.CPUFrameTimeSum=0,this.avgCPUFrameTime=0,this.compileShader=(r,s)=>{const o=this.gl,i=o.createShader(r);return o.shaderSource(i,s),o.compileShader(i),o.getShaderParameter(i,o.COMPILE_STATUS)?i:(console.error(`Error compiling shader: ${o.getShaderInfoLog(i)}`),o.deleteShader(i),null)},this.createTextureFromVideoFrame=r=>{const s=this.gl,o=s.createTexture();return s.bindTexture(s.TEXTURE_2D,o),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,r),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.bindTexture(s.TEXTURE_2D,null),o},this.deleteTexture=r=>{this.gl.deleteTexture(r)},this.options=n,this.renderer=e,this.gl=e.glContext,this.initTiming()}init(){this.initAtlas(),this.initBuffers(),this.initPrograms()}initPrograms(){const e=this.gl;this.program=this.linkProgram(Bi,$i),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.uOpacity=e.getUniformLocation(this.program,"u_opacity"),this.uAtlas=e.getUniformLocation(this.program,"u_atlas"),this.uAlphaMask=e.getUniformLocation(this.program,"u_alphaMask"),e.useProgram(this.program)}linkProgram(e,n){const r=this.gl,s=this.compileShader(r.VERTEX_SHADER,e),o=this.compileShader(r.FRAGMENT_SHADER,n),i=r.createProgram();if(r.attachShader(i,s),r.attachShader(i,o),r.linkProgram(i),!r.getProgramParameter(i,r.LINK_STATUS)){const a=r.getProgramInfoLog(i);throw 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,n,r=1){var d;const s=performance.now();this.syncAtlasGL();const{pos:o,uv:i,transforms:a,vertCount:u}=this.buildQuadData(n);if(!u)return;if(!this.program||this.aPos===void 0||this.aUv===void 0||this.aTransform===void 0||!this.uRes||!this.uOpacity||!this.uAtlas||!this.uAlphaMask){w(this.options,"Errors")&&console.error("[Renderer] Program or attributes not initialized");return}const c=this.gl;c.useProgram(this.program),c.uniform2f(this.uRes,c.canvas.width,c.canvas.height),c.viewport(0,0,c.canvas.width,c.canvas.height),c.uniform1f(this.uOpacity,r),c.activeTexture(c.TEXTURE0),c.bindTexture(c.TEXTURE_2D,e),c.uniform1i(this.uAlphaMask,0),c.activeTexture(c.TEXTURE1),c.bindTexture(c.TEXTURE_2D,this.atlasTex),c.uniform1i(this.uAtlas,1),c.bindBuffer(c.ARRAY_BUFFER,this.posBuf),c.bufferData(c.ARRAY_BUFFER,o,c.DYNAMIC_DRAW),c.enableVertexAttribArray(this.aPos),c.vertexAttribPointer(this.aPos,2,c.FLOAT,!1,0,0),c.bindBuffer(c.ARRAY_BUFFER,this.uvBuf),c.bufferData(c.ARRAY_BUFFER,i,c.DYNAMIC_DRAW),c.enableVertexAttribArray(this.aUv),c.vertexAttribPointer(this.aUv,4,c.FLOAT,!1,0,0),c.bindBuffer(c.ARRAY_BUFFER,this.transformBuf),c.bufferData(c.ARRAY_BUFFER,a,c.DYNAMIC_DRAW);const l=9*4;for(let f=0;f<3;f++){const h=this.aTransform+f;c.enableVertexAttribArray(h),c.vertexAttribPointer(h,3,c.FLOAT,!1,l,f*3*4)}if(c.enable(c.BLEND),c.blendFunc(c.SRC_ALPHA,c.ONE_MINUS_SRC_ALPHA),c.clearColor(0,0,0,0),c.clear(c.COLOR_BUFFER_BIT),this.beginTimer(),c.drawArrays(c.TRIANGLES,0,u),this.endTimer(),(d=this.options.debug)!=null&&d.trackPerformance){const h=performance.now()-s;this.CPUFrameTimeCount++,this.CPUFrameTimeSum+=h,this.avgCPUFrameTime=this.CPUFrameTimeSum/this.CPUFrameTimeCount}}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)}buildQuadData(e){const n=[],r=[],s=[];return Object.values(e).forEach(o=>{var c,l;const i=(l=(c=this.renderer.ads)==null?void 0:c.adMap.get(o.name))==null?void 0:l.name;if(!i)return;const a=this.logoToRegion.get(i);if(!a)return;const u=o.corners;n.push(u[0].x,u[0].y,u[1].x,u[1].y,u[2].x,u[2].y,u[0].x,u[0].y,u[2].x,u[2].y,u[3].x,u[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++)s.push(...o.tranform)}),{pos:new Float32Array(n),uv:new Float32Array(r),transforms:new Float32Array(s),vertCount:n.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 n=e;return{w:n.displayWidth??n.codedWidth,h:n.displayHeight??n.codedHeight}}calculateRequiredAtlasSize(e,n){let r=e*n;this.logoToRegion.forEach(o=>{const i=(o.u1-o.u0)*this.ATLAS_SIZE,a=(o.v1-o.v0)*this.ATLAS_SIZE;r+=i*a}),r*=1.2;let s=this.INITIAL_ATLAS_SIZE;for(;s*s<r;)s*=2;return s}resizeAtlas(e,n){const r=this.calculateRequiredAtlasSize(e,n);if(r<=this.ATLAS_SIZE)return;const s=new OffscreenCanvas(r,r),o=s.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=s,this.atlasCtx=o,this.logoToRegion.forEach((a,u)=>{const c={u0:a.u0*i,v0:a.v0*i,u1:a.u1*i,v1:a.v1*i};this.logoToRegion.set(u,c)}),this.syncAtlasGL()}addToAtlas(e,n){if(this.logoToRegion.has(e))return this.logoToRegion.get(e);const{w:r,h:s}=this.getDims(n);this.nextX+r>this.ATLAS_SIZE&&(this.nextX=0,this.nextY+=this.rowH,this.rowH=0),(this.nextY+s>this.ATLAS_SIZE||this.nextX+r>this.ATLAS_SIZE)&&this.resizeAtlas(r,s),this.atlasCtx.drawImage(n,this.nextX,this.nextY,r,s);const o={u0:this.nextX/this.ATLAS_SIZE,v0:this.nextY/this.ATLAS_SIZE,u1:(this.nextX+r)/this.ATLAS_SIZE,v1:(this.nextY+s)/this.ATLAS_SIZE};return this.logoToRegion.set(e,o),this.atlasDirty=!0,this.nextX+=r,this.rowH=Math.max(this.rowH,s),o}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_MIN_FILTER,e.LINEAR),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.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,n){this.addToAtlas(e,n)}initTiming(){var e;(e=this.options.debug)!=null&&e.trackPerformance&&(this.timerExt=this.gl.getExtension("EXT_disjoint_timer_query"),this.timerExt||console.warn("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)return;this.timerExt.endQueryEXT(this.timerExt.TIME_ELAPSED_EXT),this.queryInFlight=!0;const e=()=>{if(!this.queryInFlight)return;const n=this.timerExt.getQueryObjectEXT(this.query,this.timerExt.QUERY_RESULT_AVAILABLE_EXT),r=this.gl.getParameter(this.timerExt.GPU_DISJOINT_EXT);if(n&&!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.queryInFlight=!1}else requestAnimationFrame(e)};requestAnimationFrame(e)}getAvgGPUFrameTime(){var e;if((e=this.options.debug)!=null&&e.trackPerformance){const n=this.avgGPUFrameTime;return this.GPUFrameTimeCount=0,this.GPUFrameTimeSum=0,this.avgGPUFrameTime=0,n}return 0}getAvgCPUFrameTime(){var e;if((e=this.options.debug)!=null&&e.trackPerformance){const n=this.avgCPUFrameTime;return this.CPUFrameTimeCount=0,this.CPUFrameTimeSum=0,this.avgCPUFrameTime=0,n}return 0}}const Bn=["LeftTop","MidTopLeft","MidTopRight","RightTop","LeftBottom","MidBottomLeft","MidBottomRight","RightBottom"];class $n{constructor(e,n){this.ads=[],this.getAds=async()=>{try{const r="https://dwu3k7rrxk5s3.cloudfront.net",s=await fetch(r+"/profiles/geo/",{method:"GET",redirect:"follow",cache:"no-store"});if(console.log("[ADS] adListResponse: ",s),!s.ok){v.error("[ADS] Failed to fetch ad list"),this.options&&w(this.options,"Errors")&&console.error("[ADS] Failed to fetch ad list");return}const o=await s.json();console.log("[ADS] Current JSON with ads: ",o.rootAdPath);const i=o.rootAdPath;if(!i){v.error("rootAdPath is missing in the response"),this.options&&w(this.options,"Errors")&&console.error("[ADS] rootAdPath is missing in the response");return}if(this.lastJson===JSON.stringify(o))return;this.lastJson=JSON.stringify(o),this.ads=[],console.warn("[ADS] Fetching ad image from: ",i);const a=r+i,c=await(await fetch(a)).blob(),l=await createImageBitmap(c),d={name:"ad",imageUrl:a,image:l,adUrl:"https://www.Clorox.com/"};this.ads.push(d),this.setAd("LeftTop",0),this.setAd("RightBottom",0),this.setAd("MidBottomLeft",0),this.setAd("MidTopRight",0),this.uploadAdTextures()}catch{}finally{setTimeout(this.getAds,1e4)}},this.loadAdvImage=async r=>{const s=`#${r.name}`,o=r.url;if(s.indexOf(".json")>-1)return;const a=await(await fetch(o)).blob();return await createImageBitmap(a)},this.setAd=(r,s)=>{this.adMap.set(r,this.ads[s])},this.uploadAdTextures=()=>{this.webgl.clearAtlas(),this.adMap.forEach((r,s)=>{!r||!r.image||this.webgl.generateAdTexture(r.name,r.image)})},this.getAdURLAtCoord=(r,s,o)=>{let i;return Object.keys(r).forEach(a=>{const u=r[a].corners.map(c=>({x:c.x/s.width,y:c.y/s.height}));if(this.isPointInPlaceholder(u,o)){const c=r[a].name,l=this.adMap.get(c);console.log("ad: ",l),l&&(console.log("ad.url: ",l.adUrl),i=l.adUrl)}}),i},this.isPointInPlaceholder=(r,s)=>{let o=!1;const{x:i,y:a}=s,u=r.length;for(let c=0,l=u-1;c<u;l=c++){const d=r[c].x,f=r[c].y,h=r[l].x,m=r[l].y;f>a!=m>a&&i<(h-d)*(a-f)/(m-f)+d&&(o=!o)}return o},this.placeholderNames=Bn,this.webgl=e,this.options=n,this.adMap=new Map,Bn.forEach(r=>{this.adMap.set(r,void 0)}),this.getAds()}}class Gn{constructor(e,n){this.renderDataMap=new Map,this.isRenderData=!1,this.state="OFF",this.opacity=0,this.lastStateUpdate=0,this.stateUpdateInterval=500,this.lastPerformanceCheck=performance.now(),this.setWebGLEventListeners=()=>{const r=this.glContext.canvas;r.addEventListener("webglcontextlost",s=>{console.warn("Context lost:",s),s.preventDefault()}),r.addEventListener("webglcontextrestored",()=>{console.log("Context restored!"),this.webgl=new Nn(this,this.options),this.ads=new $n(this.webgl,this.options),this.webgl.init()})},this.addMetadataBatch=r=>{r.forEach(s=>{if(s.alphaMask){this.options&&w(this.options,"Renderer")&&console.log(`[RendererWorker] Creating texture for timeCode=${s.timecode}`);try{const o=this.webgl.createTextureFromVideoFrame(s.alphaMask),i=s.timecode,a={width:s.processingWidth,height:s.processingHeight},u={alphaMask:o,placeholders:s.placeholders,processingSize:a,isLive:s.isLive};this.renderDataMap.set(i,u),v.setAttributes({last_webgl_uploaded_frame:i})}catch{this.options&&w(this.options,"Errors")&&console.error(`[RendererWorker] Error creating texture for timeCode=${s.timecode}`)}finally{s.alphaMask.close()}}})},this.handleRenderDraw=(r,s)=>{var d,f,h,m;if(!this.streamData||!((d=this.ads)!=null&&d.ads))return;const o=this.renderDataMap.get(r);if(!!o!==this.isRenderData&&(o?v.info("didStartDrawingAugmentationMedia",{timecode:r}):v.info("didEndDrawingAugmentationMedia",{timecode:r}),this.isRenderData=!!o),(o?o.isLive:!1)&&!!this.streamData.ottActions&&(this.streamData.ottActions.toggle[this.streamData.customerId]!==void 0?this.streamData.ottActions.toggle[this.streamData.customerId]&&this.streamData.ottActions.toggle.web:this.streamData.ottActions.toggle.web)?(this.state==="OFF"||this.state==="FADE_OUT")&&(this.state="FADE_IN"):(this.state==="ON"||this.state==="FADE_IN")&&(this.state="FADE_OUT"),!o)return;const u=o.alphaMask,c=o.placeholders,l=o.processingSize;if(!(!u||!c||!l)){if((this.glContext.canvas.width!==l.width||this.glContext.canvas.height!==l.height)&&(this.glContext.canvas.width=l.width,this.glContext.canvas.height=l.height),s!=0)if(s>0){const E=X.fromStr(r).addFrames(1,this.streamData.fps),y=(f=this.renderDataMap.get(X.toStr(E)))==null?void 0:f.placeholders;y&&Object.keys(y).forEach(O=>{O in c&&(c[O].tranform=c[O].tranform.map((x,Ae)=>x*(1-s)+y[O].tranform[Ae]*s))})}else{const E=Math.abs(s),y=X.fromStr(r).subtractFrames(1,this.streamData.fps),O=(h=this.renderDataMap.get(X.toStr(y)))==null?void 0:h.placeholders;O&&Object.keys(O).forEach(x=>{x in c&&(c[x].tranform=c[x].tranform.map((Ae,Lt)=>O[x].tranform[Lt]*(1-E)+Ae*E))})}if(this.options&&w(this.options,"Renderer")&&console.log(`[Renderer] Render logic: binding texture for ${r}`),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=Math.max(0,this.opacity-(performance.now()-this.lastStateUpdate)/this.stateUpdateInterval),this.lastStateUpdate=performance.now(),this.opacity===0&&(this.state="OFF")),v.setAttributes({last_rendered_frame:r,renderer_state:this.state}),this.webgl.drawAugmentation(u,c,this.opacity),this.options&&((m=this.options.debug)!=null&&m.trackPerformance)){const E=performance.now();E-this.lastPerformanceCheck>=this.options.PERFORMANCE_TRACKING_INTERVAL&&(this.trackPerformance(),this.lastPerformanceCheck=E)}}},this.handleRenderClear=()=>{this.opacity=0,this.state="OFF"},this.getAdURLByCoord=r=>{var u,c;if(!this.ads||!this.streamData||!this.streamData.timeCode||!this.renderDataMap)return null;const s=this.streamData.timeCode,o=(u=this.renderDataMap.get(s))==null?void 0:u.placeholders,i=(c=this.renderDataMap.get(s))==null?void 0:c.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 s=(o=this.renderDataMap.get(r))==null?void 0:o.alphaMask;s&&(this.webgl.deleteTexture(s),this.renderDataMap.delete(r))},this.deleteOldTextures=r=>{if(!this.streamData)return;const s=59.94,o=X.fromStr(r).totalMilliseconds(s);this.renderDataMap.forEach((i,a)=>{X.fromStr(a).totalMilliseconds(s)<o-100&&(this.options&&w(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,s)=>{this.webgl.deleteTexture(r.alphaMask),this.renderDataMap.delete(s)})},this.cleanGL=()=>{this.webgl.cleanGL()},this.updateStreamData=r=>{var o;const s=(o=this.streamData)==null?void 0:o.ottActions;this.streamData=r,s&&!r.ottActions&&(this.streamData.ottActions=s)},this.trackPerformance=()=>{const r=this.webgl.getAvgGPUFrameTime(),s=this.webgl.getAvgCPUFrameTime();Wi([{metric:"Rendering GPU time",value:r},{metric:"Rendering CPU time",value:s}],v.getMessagePort())},this.glContext=e,this.webgl=new Nn(this,n),this.options=n,this.ads=new $n(this.webgl,n),this.webgl.init()}stop(){this.cleanGL(),this.deleteAllTextures()}}let Ke=null,Je=null,jn=null,xt=null,Y=null,C=null,S,L,Wn=0,Xn=0;self.onmessage=t=>{const{data:e}=t;if(e.type==="SET_LOGGER_PORT"&&(xt=e.port,v.setMessagePort(e.port)),e.type==="INIT_OFFSCREEN"){const n=e.offscreen;if(S=e.options,Y=n.getContext("webgl"),S&&w(S,"Renderer")&&console.log("[RendererWorker] Initializing OffscreenCanvas"),!Y||Y!=null&&Y.isContextLost()){v.error("[RendererWorker] Failed to acquire WebGL context"),S&&w(S,"Errors")&&console.error("[RendererWorker] Failed to acquire WebGL context");return}C=new Gn(Y,S),S&&w(S,"Renderer")&&console.log("[RendererWorker] OffscreenCanvas initialized, gl context acquired")}if(e.type==="SET_DOWNLOADER_PORT"&&(Ke=e.port,Ke.onmessage=qi),e.type==="SET_DECODER_PORT"&&(Je=e.port,Je.onmessage=Yi),e.type==="SET_ADAPTER_PORT"&&(jn=e.port,jn.onmessage=Hi),(e.type==="RENDERER_DRAW"||e.type==="RENDERER_CLEAR")&&Yn(e),e.type==="VIDEO_CLICK"&&C){const n=C.getAdURLByCoord(e.clickData);postMessage({type:"OPEN_URL",url:n})}if(e.type==="VIDEO_SEEKED"){if(!Y||!S)return;C==null||C.stop(),C=new Gn(Y,S)}};function Gi(){!Ke||!L||Ke.postMessage({type:"DOWNLOADER_INPUT",streamData:L})}function ji(){!Je||!L||Je.postMessage({type:"DECODER_REQUEST",timeCode:L.timeCode,fps:L.fps})}function Wi(t,e){if(!xt&&!e)return;const n=xt||e,r={type:"TRACK_PERFORMANCE",data:t};n.postMessage(r)}function Yn(t){L=t.streamData,C?(L&&C.updateStreamData(L),C.cleanGL(),t.type==="RENDERER_CLEAR"&&C.handleRenderClear(),t.type==="RENDERER_DRAW"&&L&&(C.handleRenderDraw(L.timeCode,L.frameCorrection),C.deleteOldTextures(L.timeCode)),Xi()):S&&w(S,"Errors")&&console.error("[RendererWorker] WebGL context is not initialized.")}function Xi(){if(!S)return;const t=performance.now();t-Wn>S.DOWNLOADER_UPDATE_FREQUENCY&&(Gi(),Wn=t),t-Xn>S.DECODER_UPDATE_FREQUENCY&&(ji(),Xn=t)}function Yi(t){const{data:e}=t;if(e.type==="RENDERER_INPUT"){const n=e.batch;S&&w(S,"Renderer")&&console.log(`[RendererWorker] Received a batch of ${n.length} frames`),C&&C.addMetadataBatch(n)}}function qi(t){if(!L)return;const{data:e}=t;S&&w(S,"Renderer")&&console.log("[RendererWorker] Message from Downloader:",t.data),e.type==="OTT_ACTIONS"&&(L.ottActions=e.ottActions)}function Hi(t){const{data:e}=t;(e.type==="RENDERER_DRAW"||e.type==="RENDERER_CLEAR")&&Yn(e)}self.onunhandledrejection=t=>{v.error("[RendererWorker] Unhandled rejection",{error:t.reason}),S&&(w(S,"Errors")&&console.error("[RendererWorker] Unhandled rejection:",t.reason),t.preventDefault())},self.onerror=t=>{v.error("[RendererWorker] Unhandled error",{error:t}),S&&(w(S,"Errors")&&console.error("[RendererWorker] Unhandled error:",t),t instanceof Event&&t.preventDefault())}})();\n',$t=typeof self<"u"&&self.Blob&&new Blob([Nt],{type:"text/javascript;charset=utf-8"});function sr(t){let e;try{if(e=$t&&(self.URL||self.webkitURL).createObjectURL($t),!e)throw"";const n=new Worker(e,{name:t==null?void 0:t.name});return n.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),n}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Nt),{name:t==null?void 0:t.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}const zt='(function(){"use strict";const Z=(e,t)=>!e.debug||!e.debug.on?!1:e.debug[`log${t}`],Wn=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,_={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},L=console,W={};Object.keys(_).forEach(e=>{W[e]=L[e]});const le="Datadog Browser SDK:",T={debug:W.debug.bind(L,le),log:W.log.bind(L,le),info:W.info.bind(L,le),warn:W.warn.bind(L,le),error:W.error.bind(L,le)},Xe="https://docs.datadoghq.com",xt=`${Xe}/real_user_monitoring/browser/troubleshooting`,Ce="More details:";function At(e,t){return(...n)=>{try{return e(...n)}catch(r){T.error(t,r)}}}function Oe(e){return e!==0&&Math.random()*100<=e}function Hn(e){return zn(e)&&e>=0&&e<=100}function zn(e){return typeof e=="number"}const de=1e3,H=60*de,Lt=60*H,Kn=365*(24*Lt);function fe(){return new Date().getTime()}function D(){return fe()}function ve(){return performance.now()}function $(){return{relative:ve(),timeStamp:D()}}function Vn(){return{relative:0,timeStamp:It()}}function qn(e,t){return t-e}function Yn(e,t){return e+t}function Xn(e){return e-It()}let Je;function It(){return Je===void 0&&(Je=performance.timing.navigationStart),Je}const I=1024,kt=1024*I,Jn=/[^\\u0000-\\u007F]/;function Qe(e){return Jn.test(e)?window.TextEncoder!==void 0?new TextEncoder().encode(e).length:new Blob([e]).size:e.length}function Qn(e){return{...e}}function Mt(e,t){return Object.keys(e).some(n=>e[n]===t)}function pe(e){return Object.keys(e).length===0}function U(){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 ee(e,t){const n=U();let r;return n.Zone&&typeof n.Zone.__symbol__=="function"&&(r=e[n.Zone.__symbol__(t)]),r||(r=e[t]),r}let Re,Pt=!1;function Zn(e){Re=e}function er(e){Pt=e}function tr(e,t,n){const r=n.value;n.value=function(...o){return(Re?b(r):r).apply(this,o)}}function b(e){return function(){return me(e,this,arguments)}}function me(e,t,n){try{return e.apply(t,n)}catch(r){nr(r)}}function nr(e){if(Ze(e),Re)try{Re(e)}catch(t){Ze(t)}}function Ze(...e){Pt&&T.error("[MONITOR]",...e)}function ge(e,t){return ee(U(),"setTimeout")(b(e),t)}function Nt(e){ee(U(),"clearTimeout")(e)}function et(e,t){return ee(U(),"setInterval")(b(e),t)}function Ft(e){ee(U(),"clearInterval")(e)}class w{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 Dt(...e){return new w(t=>{const n=e.map(r=>r.subscribe(o=>t.notify(o)));return()=>n.forEach(r=>r.unsubscribe())})}function $t(e,t,n){let r=!1,o,s;return{throttled:(...i)=>{if(r){o=i;return}e(...i),r=!0,s=ge(()=>{o&&e(...o),r=!1,o=void 0},t)},cancel:()=>{Nt(s),r=!1,o=void 0}}}function B(){}function G(e){return e?(parseInt(e,10)^Math.random()*16>>parseInt(e,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,G)}const xe=/([\\w-]+)\\s*=\\s*([^;]+)/g;function rr(e,t){for(xe.lastIndex=0;;){const n=xe.exec(e);if(n){if(n[1]===t)return n[2]}else break}}function or(e){const t=new Map;for(xe.lastIndex=0;;){const n=xe.exec(e);if(n)t.set(n[1],n[2]);else break}return t}function sr(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 ir(){return ar()===0}let Ae;function ar(){return Ae??(Ae=cr())}function cr(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 he(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 tt(e){return rr(document.cookie,e)}let nt;function z(e){return nt||(nt=or(document.cookie)),nt.get(e)}function Ut(e,t){he(e,"",0,t)}function ur(e){if(document.cookie===void 0||document.cookie===null)return!1;try{const t=`dd_cookie_test_${G()}`,n="test";he(t,n,H,e);const r=tt(t)===n;return Ut(t,e),r}catch(t){return T.error(t),!1}}let rt;function lr(){if(rt===void 0){const e=`dd_site_test_${G()}`,t="test",n=window.location.hostname.split(".");let r=n.pop();for(;n.length&&!tt(e);)r=`${n.pop()}.${r}`,he(e,t,de,{domain:r});Ut(e,{domain:r}),rt=r}return rt}const te="_dd_s";function Le(e){return Object.values(e)}function dr(e){return Object.entries(e)}const ot=4*Lt,Bt=15*H,fr=Kn,Se={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},Gt=/^([a-zA-Z]+)=([a-z0-9-]+)$/,st="&";function pr(e){return!!e&&(e.indexOf(st)!==-1||Gt.test(e))}const mr="1";function K(e,t){const n={isExpired:mr};return t.trackAnonymousUser&&(e!=null&&e.anonymousId?n.anonymousId=e==null?void 0:e.anonymousId:n.anonymousId=G()),n}function Ie(e){return pe(e)}function jt(e){return!Ie(e)}function ke(e){return e.isExpired!==void 0||!gr(e)}function gr(e){return(e.created===void 0||fe()-Number(e.created)<ot)&&(e.expire===void 0||fe()<Number(e.expire))}function Wt(e){e.expire=String(fe()+Bt)}function it(e){return dr(e).map(([t,n])=>t==="anonymousId"?`aid=${n}`:`${t}=${n}`).join(st)}function Ht(e){const t={};return pr(e)&&e.split(st).forEach(n=>{const r=Gt.exec(n);if(r!==null){const[,o,s]=r;o==="aid"?t.anonymousId=s:t[o]=s}}),t}const hr="_dd",Sr="_dd_r",br="_dd_l",yr="rum",Er="logs";function _r(e){if(!z(te)){const n=z(hr),r=z(Sr),o=z(br),s={};n&&(s.id=n),o&&/^[01]$/.test(o)&&(s[Er]=o),r&&/^[012]$/.test(r)&&(s[yr]=r),jt(s)&&(Wt(s),e.persistSession(s))}}function zt(e){const t=vr(e);return ur(t)?{type:Se.COOKIE,cookieOptions:t}:void 0}function Tr(e,t){const n={isLockEnabled:ir(),persistSession:wr(t),retrieveSession:Or,expireSession:r=>Cr(t,r,e)};return _r(n),n}function wr(e){return t=>{he(te,it(t),Bt,e)}}function Cr(e,t,n){const r=K(t,n);he(te,it(r),n.trackAnonymousUser?fr:ot,e)}function Or(){const e=tt(te);return Ht(e)}function vr(e){const t={};return t.secure=!!e.useSecureSessionCookie||!!e.usePartitionedCrossSiteSessionCookie,t.crossSite=!!e.usePartitionedCrossSiteSessionCookie,t.partitioned=!!e.usePartitionedCrossSiteSessionCookie,e.trackSessionAcrossSubdomains&&(t.domain=lr()),t}const Rr="_dd_test_";function Kt(){try{const e=G(),t=`${Rr}${e}`;localStorage.setItem(t,e);const n=localStorage.getItem(t);return localStorage.removeItem(t),e===n?{type:Se.LOCAL_STORAGE}:void 0}catch{return}}function xr(e){return{isLockEnabled:!1,persistSession:Vt,retrieveSession:Ar,expireSession:t=>Lr(t,e)}}function Vt(e){localStorage.setItem(te,it(e))}function Ar(){const e=localStorage.getItem(te);return Ht(e)}function Lr(e,t){Vt(K(e,t))}const Ir=10,kr=100,qt=[];let Me;function V(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(),g=f.lock;return f.lock&&delete f.lock,{session:f,lock:g}};if(Me||(Me=e),e!==Me){qt.push(e);return}if(o&&n>=kr){Yt(t);return}let l,u=c();if(o){if(u.lock){Pe(e,t,n);return}if(l=G(),a(u.session),u=c(),u.lock!==l){Pe(e,t,n);return}}let d=e.process(u.session);if(o&&(u=c(),u.lock!==l)){Pe(e,t,n);return}if(d&&(ke(d)?i(d):(Wt(d),o?a(d):s(d))),o&&!(d&&ke(d))){if(u=c(),u.lock!==l){Pe(e,t,n);return}s(u.session),d=u.session}(r=e.after)===null||r===void 0||r.call(e,d||u.session),Yt(t)}function Pe(e,t,n){ge(()=>{V(e,t,n+1)},Ir)}function Yt(e){Me=void 0;const t=qt.shift();t&&V(t,e)}const Xt=de;function Mr(e){switch(e.sessionPersistence){case Se.COOKIE:return zt(e);case Se.LOCAL_STORAGE:return Kt();case void 0:{let t=zt(e);return!t&&e.allowFallbackToLocalStorage&&(t=Kt()),t}default:T.error(`Invalid session persistence \'${String(e.sessionPersistence)}\'`)}}function Pr(e,t,n,r){const o=new w,s=new w,i=new w,a=e.type===Se.COOKIE?Tr(t,e.cookieOptions):xr(t),{expireSession:c}=a,l=et(m,Xt);let u;p();const{throttled:d,cancel:f}=$t(()=>{V({process:S=>{if(Ie(S))return;const ue=y(S);return O(ue),ue},after:S=>{jt(S)&&!v()&&Gn(S),u=S}},a)},Xt);function g(){V({process:S=>v()?y(S):void 0},a)}function m(){V({process:S=>ke(S)?K(S,t):void 0,after:y},a)}function y(S){return ke(S)&&(S=K(S,t)),v()&&(F(S)?ce():(i.notify({previousState:u,newState:S}),u=S)),S}function p(){V({process:S=>{if(Ie(S))return K(S,t)},after:S=>{u=S}},a)}function O(S){if(Ie(S))return!1;const{trackingType:ue,isTracked:ji}=r(S[n]);S[n]=ue,delete S.isExpired,ji&&!S.id&&(S.id=G(),S.created=String(fe()))}function v(){return u[n]!==void 0}function F(S){return u.id!==S.id||u[n]!==S[n]}function ce(){u=K(u,t),s.notify()}function Gn(S){u=S,o.notify()}function jn(S){V({process:ue=>({...ue,...S}),after:y},a)}return{expandOrRenewSession:d,expandSession:g,getSession:()=>u,renewObservable:o,expireObservable:s,sessionStateUpdateObservable:i,restartSession:p,expire:()=>{f(),c(u),y(K(u,t))},stop:()=>{Ft(l)},updateSessionState:jn}}const at={GRANTED:"granted",NOT_GRANTED:"not-granted"};function Nr(e){const t=new w;return{tryToInit(n){e||(e=n)},update(n){e=n,t.notify()},isGranted(){return e===at.GRANTED},observable:t}}function q(e,t,n){if(typeof e!="object"||e===null)return JSON.stringify(e);const r=ne(Object.prototype),o=ne(Array.prototype),s=ne(Object.getPrototypeOf(e)),i=ne(e);try{return JSON.stringify(e,t,n)}catch{return"<error: unable to serialize object>"}finally{r(),o(),s(),i()}}function ne(e){const t=e,n=t.toJSON;return n?(delete t.toJSON,()=>{t.toJSON=n}):B}function ct(e){return Fr(e,location.href).href}function Fr(e,t){const n=Dr();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)} ${q({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 Jt=URL;let Ne;function Dr(){if(Ne===void 0)try{Ne=new Jt("http://test/path").href==="http://test/path"}catch{Ne=!1}return Ne?Jt:void 0}const $r="datad0g.com",Ur="dd0g-gov.com",re="datadoghq.com",Br="ddog-gov.com",Gr="pci.browser-intake-datadoghq.com",jr=["ddsource","ddtags"];function be(e,t,n){const r=Wr(e,t);return{build(o,s){const i=zr(e,t,n,o,s);return r(i)},urlPrefix:r(""),trackType:t}}function Wr(e,t){const n=`/api/v2/${t}`,r=e.proxy;if(typeof r=="string"){const s=ct(r);return i=>`${s}?ddforward=${encodeURIComponent(`${n}?${i}`)}`}if(typeof r=="function")return s=>r({path:n,parameters:s});const o=Hr(t,e);return s=>`https://${o}${n}?${s}`}function Hr(e,t){const{site:n=re,internalAnalyticsSubdomain:r}=t;if(e==="logs"&&t.usePciIntake&&n===re)return Gr;if(r&&n===re)return`${r}.${re}`;if(n===Ur)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=${G()}`];return i&&c.push(`dd-evp-encoding=${i}`),n==="rum"&&c.push(`batch_time=${D()}`),t&&c.reverse(),c.join("&")}const Kr=200;function Vr(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=Kr-e.length-1;(t.length>n||qr(t))&&T.warn(`${e} value doesn\'t meet tag requirements and will be sanitized. ${Ce} ${Xe}/getting_started/tagging/#defining-tags`);const r=t.replace(/,/g,"_");return`${e}:${r}`}function qr(e){return Yr()?new RegExp("[^\\\\p{Ll}\\\\p{Lo}0-9_:./-]","u").test(e):!1}function Yr(){try{return new RegExp("[\\\\p{Ll}]","u"),!0}catch{return!1}}function Xr(e){const t=e.site||re,n=Vr(e),r=Jr(e,n);return{replica:Qr(e,n),site:t,...r}}function Jr(e,t){return{logsEndpointBuilder:be(e,"logs",t),rumEndpointBuilder:be(e,"rum",t),sessionReplayEndpointBuilder:be(e,"replay",t)}}function Qr(e,t){if(!e.replica)return;const n={...e,site:re,clientToken:e.replica.clientToken},r={logsEndpointBuilder:be(n,"logs",t),rumEndpointBuilder:be(n,"rum",t)};return{applicationId:e.replica.applicationId,...r}}function Zr(e){return jr.every(t=>e.includes(t))}function ut(e,t){return e!=null&&typeof e!="string"?(T.error(`${t} must be defined as a string`),!1):!0}function eo(e){return e&&typeof e=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(e)?(T.error(`Site should be a valid Datadog site. ${Ce} ${Xe}/getting_started/site/.`),!1):!0}function De(e,t){return e!==void 0&&!Hn(e)?(T.error(`${t} Sample Rate should be a number between 0 and 100`),!1):!0}function to(e){var t,n,r,o,s,i;if(!e||!e.clientToken){T.error("Client Token is not configured, we will not send any data.");return}if(!(!eo(e.site)||!De(e.sessionSampleRate,"Session")||!De(e.telemetrySampleRate,"Telemetry")||!De(e.telemetryConfigurationSampleRate,"Telemetry Configuration")||!De(e.telemetryUsageSampleRate,"Telemetry Usage")||!ut(e.version,"Version")||!ut(e.env,"Env")||!ut(e.service,"Service"))){if(e.trackingConsent!==void 0&&!Mt(at,e.trackingConsent)){T.error(\'Tracking Consent should be either "granted" or "not-granted"\');return}return{beforeSend:e.beforeSend&&At(e.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:Mr(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:at.GRANTED,trackAnonymousUser:(i=e.trackAnonymousUser)!==null&&i!==void 0?i:!0,storeContextsAcrossPages:!!e.storeContextsAcrossPages,batchBytesLimit:16*I,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*de,batchMessagesLimit:50,messageBytesLimit:256*I,...Xr(e)}}}function no(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 lt;(function(e){e.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",e.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(lt||(lt={}));const Qt=new Set;function ro(e){Array.isArray(e)&&oo(e.filter(t=>Mt(lt,t)))}function oo(e){e.forEach(t=>{Qt.add(t)})}function so(){return Qt}const ye="?";function k(e){const t=[];let n=dt(e,"stack");const r=String(e);return n&&n.startsWith(r)&&(n=n.slice(r.length)),n&&n.split(`\n`).forEach(o=>{const s=co(o)||lo(o)||po(o)||ho(o);s&&(!s.func&&s.line&&(s.func=ye),t.push(s))}),{message:dt(e,"message"),name:dt(e,"name"),stack:t}}const Zt="((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\\\w+\\\\.|\\\\/).*?)",oe="(?::(\\\\d+))",io=new RegExp(`^\\\\s*at (.*?) ?\\\\(${Zt}${oe}?${oe}?\\\\)?\\\\s*$`,"i"),ao=new RegExp(`\\\\((\\\\S*)${oe}${oe}\\\\)`);function co(e){const t=io.exec(e);if(!t)return;const n=t[2]&&t[2].indexOf("native")===0,r=t[2]&&t[2].indexOf("eval")===0,o=ao.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]||ye,line:t[3]?+t[3]:void 0,url:n?void 0:t[2]}}const uo=new RegExp(`^\\\\s*at ?${Zt}${oe}?${oe}??\\\\s*$`,"i");function lo(e){const t=uo.exec(e);if(t)return{args:[],column:t[3]?+t[3]:void 0,func:ye,line:t[2]?+t[2]:void 0,url:t[1]}}const fo=/^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;function po(e){const t=fo.exec(e);if(t)return{args:[],column:t[4]?+t[4]:void 0,func:t[1]||ye,line:+t[3],url:t[2]}}const mo=/^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i,go=/(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;function ho(e){const t=mo.exec(e);if(!t)return;const n=t[3]&&t[3].indexOf(" > eval")>-1,r=go.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]||ye,line:t[4]?+t[4]:void 0,url:t[3]}}function dt(e,t){if(typeof e!="object"||!e||!(t in e))return;const n=e[t];return typeof n=="string"?n:void 0}function So(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 bo=/^(?:[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]=bo.exec(e)),{name:t,message:n}}function $e(e){const n=new Error(e);n.name="HandlingStack";let r;return me(()=>{const o=k(n);o.stack=o.stack.slice(2),r=Y(o)}),r}function Y(e){let t=en(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 en(e){return`${e.name||"Error"}: ${e.message}`}function X(e,t,n,{computeHandlingStack:r}={}){let o=e[t];if(typeof o!="function")if(t in e&&t.startsWith("on"))o=B;else return{stop:B};let s=!1;const i=function(){if(s)return o.apply(this,arguments);const a=Array.from(arguments);let c;me(n,null,[{target:this,parameters:a,onPostCall:u=>{c=u},handlingStack:r?$e("instrumented method"):void 0}]);const l=o.apply(this,a);return c&&me(c,null,[l]),l};return e[t]=i,{stop:()=>{s=!0,e[t]===i&&(e[t]=o)}}}const Eo=220*I,_o="$",To=3;function M(e,t=Eo){const n=ne(Object.prototype),r=ne(Array.prototype),o=[],s=new WeakMap,i=ft(e,_o,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=ft(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=ft(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){mt(t,"truncated",e);break}l.target[d]=f}}return n(),r(),i}function ft(e,t,n,r,o){const s=Oo(e);if(!s||typeof s!="object")return wo(s);const i=pt(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 pt(e){try{if(e instanceof Event)return Co(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 Co(e){return{type:e.type,isTrusted:e.isTrusted,currentTarget:e.currentTarget?pt(e.currentTarget):null,target:e.target?pt(e.target):null}}function Oo(e){const t=e;if(t&&typeof t.toJSON=="function")try{return t.toJSON()}catch{}return e}function mt(e,t,n){T.warn(`The data provided has been ${t} as it is over the limit of ${e} characters:`,n)}const tn="No stack, consider using an instance of Error";function nn({stackTrace:e,originalError:t,handlingStack:n,componentStack:r,startClocks:o,nonErrorPrefix:s,source:i,handling:a}){const c=j(t),l=vo(e,c,s,t),u=Ro(c,e)?Y(e):tn,d=c?sn(t,i):void 0,f=e?e.name:void 0,g=rn(t),m=on(t);return{startClocks:o,source:i,handling:a,handlingStack:n,componentStack:r,originalError:t,type:f,message:l,stack:u,causes:d,fingerprint:g,context:m}}function vo(e,t,n,r){return e!=null&&e.message&&(e!=null&&e.name)?e.message:t?"Empty message":`${n} ${q(M(r))}`}function Ro(e,t){return t===void 0?!1:e?!0:t.stack.length>0&&(t.stack.length>1||t.stack[0].url!==void 0)}function rn(e){return j(e)&&"dd_fingerprint"in e?String(e.dd_fingerprint):void 0}function on(e){if(e!==null&&typeof e=="object"&&"dd_context"in e)return e.dd_context}function xo(e){var t;return(t=/@ (.+)/.exec(e))===null||t===void 0?void 0:t[1]}function j(e){return e instanceof Error||Object.prototype.toString.call(e)==="[object Error]"}function sn(e,t){let n=e;const r=[];for(;j(n==null?void 0:n.cause)&&r.length<10;){const o=k(n.cause);r.push({message:n.cause.message,source:t,type:o==null?void 0:o.name,stack:Y(o)}),n=n.cause}return r.length?r:void 0}const R={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function Ao(e){const t=(o,s)=>{const i=nn({stackTrace:o,originalError:s,startClocks:$(),nonErrorPrefix:"Uncaught",source:R.SOURCE,handling:"unhandled"});e.notify(i)},{stop:n}=Lo(t),{stop:r}=Io(t);return{stop:()=>{n(),r()}}}function Lo(e){return X(window,"onerror",({parameters:[t,n,r,o,s]})=>{let i;j(s)?i=k(s):i=So(t,n,r,o),e(i,s??t)})}function Io(e){return X(window,"onunhandledrejection",({parameters:[t]})=>{const n=t.reason||"Empty reason",r=k(n);e(r,n)})}function ko(e){const t={version:"6.5.0",onReady(n){n()},...e};return Object.defineProperty(t,"_setDebug",{get(){return er},enumerable:!1}),t}function Mo(e,t,n){const r=e[t];r&&!r.q&&r.version&&T.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 an(e,t){t.silentMultipleInit||T.error(`${e} is already initialized.`)}function J(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=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=ee(l,"addEventListener");n.forEach(f=>u.call(t,f,a,c));function d(){const f=ee(l,"removeEventListener");n.forEach(g=>f.call(t,g,a,c))}return{stop:d}}const Ue={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function Po(e,t){const n=[];t.includes(Ue.cspViolation)&&n.push(Fo(e));const r=t.filter(o=>o!==Ue.cspViolation);return r.length&&n.push(No(r)),Dt(...n)}function No(e){return new w(t=>{if(!window.ReportingObserver)return;const n=b((o,s)=>o.forEach(i=>t.notify(Do(i)))),r=new window.ReportingObserver(n,{types:e,buffered:!0});return r.observe(),()=>{r.disconnect()}})}function Fo(e){return new w(t=>{const{stop:n}=J(e,document,"securitypolicyviolation",r=>{t.notify($o(r))});return n})}function Do(e){const{type:t,body:n}=e;return cn({type:n.id,message:`${t}: ${n.message}`,originalError:e,stack:un(n.id,n.message,n.sourceFile,n.lineNumber,n.columnNumber)})}function $o(e){const t=`\'${e.blockedURI}\' blocked by \'${e.effectiveDirective}\' directive`;return cn({type:e.effectiveDirective,message:`${Ue.cspViolation}: ${t}`,originalError:e,csp:{disposition:e.disposition},stack:un(e.effectiveDirective,e.originalPolicy?`${t} of the policy "${sr(e.originalPolicy,100,"...")}"`:"no policy",e.sourceFile,e.lineNumber,e.columnNumber)})}function cn(e){return{startClocks:$(),source:R.REPORT,handling:"unhandled",...e}}function un(e,t,n,r,o){return n?Y({name:e,message:t,stack:[{func:"?",url:n,line:r??void 0,column:o??void 0}]}):void 0}function ln(e,t){const n=window.__ddBrowserSdkExtensionCallback;n&&n({type:e,payload:t})}function dn(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Be(e,t,n=Uo()){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]=Be(o[s],t[s],n);return o}const r=dn(e)==="object"?e:{};for(const o in t)Object.prototype.hasOwnProperty.call(t,o)&&(r[o]=Be(r[o],t[o],n));return r}function fn(e){return Be(void 0,e)}function se(...e){let t;for(const n of e)n!=null&&(t=Be(t,n));return t}function Uo(){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 Bo(){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 Go(e){const t=new Set;return e.forEach(n=>t.add(n)),Array.from(t)}function pn(e,t){const n=e.indexOf(t);n>=0&&e.splice(n,1)}const jo=500;function mn(){const e=[];return{add:o=>{e.push(o)>jo&&e.splice(0,1)},remove:o=>{pn(e,o)},drain:o=>{e.forEach(s=>s(o)),e.length=0}}}const Q={log:"log",configuration:"configuration",usage:"usage"},Wo=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],Ho=[Br];let gn=mn(),ie=e=>{gn.add(()=>ie(e))};function zo(e,t){let n;const r=new w,o=new Set,s=!Ho.includes(t.site)&&Oe(t.telemetrySampleRate),i={[Q.log]:s,[Q.configuration]:s&&Oe(t.telemetryConfigurationSampleRate),[Q.usage]:s&&Oe(t.telemetryUsageSampleRate)},a=Ko();ie=l=>{const u=q(l);if(i[l.type]&&o.size<t.maxTelemetryEventsPerPage&&!o.has(u)){const d=c(e,l,a);r.notify(d),ln("telemetry",d),o.add(u)}},Zn(Sn);function c(l,u,d){return se({type:"telemetry",date:D(),service:l,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:se(u,{runtime_env:d,connectivity:Bo(),sdk_setup:"npm"}),experimental_features:Array.from(so())},n!==void 0?n():{})}return{setContextProvider:l=>{n=l},observable:r,enabled:s}}function Ko(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function Vo(){gn.drain()}function qo(e){return e.site===$r}function hn(e,t){Ze(_.debug,e,t),ie({type:Q.log,message:e,status:"debug",...t})}function Sn(e,t){ie({type:Q.log,status:"error",...Jo(e),...t})}function Yo(e){ie({type:Q.configuration,configuration:e})}function Xo(e){ie({type:Q.usage,usage:e})}function Jo(e){if(j(e)){const t=k(e);return{error:{kind:t.name,stack:Y(Qo(t))},message:t.message}}return{error:{stack:tn},message:`Uncaught ${q(e)}`}}function Qo(e){return e.stack=e.stack.filter(t=>!t.url||Wo.some(n=>t.url.startsWith(n))),e}const Ee=1/0,Zo=H;let _e=null;const Ge=new Set;function es(){Ge.forEach(e=>e())}function ts({expireDelay:e,maxEntries:t}){let n=[];const r=[];_e||(_e=et(()=>es(),Zo));const o=()=>{const g=ve()-e;for(;n.length>0&&n[n.length-1].endTime<g;){const m=n.pop();m&&r.push(m.startTime)}};Ge.add(o);function s(g,m){const y={value:g,startTime:m,endTime:Ee,remove:()=>{pn(n,y)},close:p=>{y.endTime=p}};return t&&n.length>=t&&n.pop(),n.unshift(y),y}function i(g=Ee,m={returnInactive:!1}){for(const y of n)if(y.startTime<=g){if(m.returnInactive||g<=y.endTime)return y.value;break}}function a(g){const m=n[0];m&&m.endTime===Ee&&m.close(g)}function c(g=Ee,m=0){const y=Yn(g,m);return n.filter(p=>p.startTime<=y&&g<=p.endTime).map(p=>p.value)}function l(){return n.map(({startTime:g,endTime:m,value:y})=>({startTime:g,endTime:m===Ee?"Infinity":m,value:y}))}function u(){return r}function d(){n=[]}function f(){Ge.delete(o),Ge.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 ns=H,rs=ot;function os(e,t,n,r){const o=new w,s=new w,i=Pr(e.sessionStoreStrategyType,e,t,n),a=ts({expireDelay:rs});i.renewObservable.subscribe(()=>{a.add(c(),ve()),o.notify()}),i.expireObservable.subscribe(()=>{s.notify(),a.closeActive(ve())}),i.expandOrRenewSession(),a.add(c(),Vn().relative),r.observable.subscribe(()=>{r.isGranted()?i.expandOrRenewSession():i.expire()}),ss(e,()=>{r.isGranted()&&i.expandOrRenewSession()}),is(e,()=>i.expandSession()),as(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 ss(e,t){gt(e,window,["click","touchstart","keydown","scroll"],t,{capture:!0,passive:!0})}function is(e,t){const n=()=>{document.visibilityState==="visible"&&t()};J(e,document,"visibilitychange",n),et(n,ns)}function as(e,t){J(e,window,"resume",t,{capture:!0})}function bn(e){return e>=500}function cs(e){try{return e.clone()}catch{return}}const us=80*I,ls=32,yn=3*kt,ds=H,En=de;function _n(e,t,n,r,o){t.transportStatus===0&&t.queuedPayloads.size()===0&&t.bandwidthMonitor.canHandle(e)?wn(e,t,n,{onSuccess:()=>Cn(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&&ge(()=>{const o=e.queuedPayloads.first();wn(o,e,t,{onSuccess:()=>{e.queuedPayloads.dequeue(),e.currentBackoffTime=En,Cn(1,e,t,n,r)},onFailure:()=>{e.currentBackoffTime=Math.min(ds,e.currentBackoffTime*2),Tn(e,t,n,r)}})},e.currentBackoffTime)}function wn(e,t,n,{onSuccess:r,onFailure:o}){t.bandwidthMonitor.add(e),n(e,s=>{t.bandwidthMonitor.remove(e),fs(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: ${yn/kt}MiB`,source:R.AGENT,startClocks:$()}),t.queueFullReported=!0);const s=t.queuedPayloads;for(t.queuedPayloads=On();s.size()>0;)_n(s.dequeue(),t,n,r,o)}function fs(e){return e.type!=="opaque"&&(e.status===0&&!navigator.onLine||e.status===408||e.status===429||bn(e.status))}function ps(){return{transportStatus:0,currentBackoffTime:En,bandwidthMonitor:ms(),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 ms(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(e){return this.ongoingRequestCount===0||this.ongoingByteCount+e.bytesCount<=us&&this.ongoingRequestCount<ls},add(e){this.ongoingRequestCount+=1,this.ongoingByteCount+=e.bytesCount},remove(e){this.ongoingRequestCount-=1,this.ongoingByteCount-=e.bytesCount}}}function gs(e,t,n){const r=ps(),o=(s,i)=>bs(e,t,s,i);return{send:s=>{_n(s,r,o,e.trackType,n)},sendOnExit:s=>{hs(e,t,s)}}}function hs(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){Ss(s)}const o=e.build("xhr",n);ht(o,n.data)}let vn=!1;function Ss(e){vn||(vn=!0,Sn(e))}function bs(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);ht(i,n.data,r)}))}else{const s=e.build("xhr",n);ht(s,n.data,r)}}function ys(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function ht(e,t,n){const r=new XMLHttpRequest;r.open("POST",e,!0),t instanceof Blob&&r.setRequestHeader("Content-Type",t.type),J({allowUntrustedEvents:!0},r,"loadend",()=>{n==null||n({status:r.status})},{once:!0}),r.send(t)}function St(){const e=Es();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 je(e){var t;e===void 0&&(e=(t=U().location)===null||t===void 0?void 0:t.hostname);const n=St();return!!n&&n.getAllowedWebViewHosts().some(r=>e===r||e.endsWith(`.${r}`))}function Es(){return U().DatadogEventBridge}const We={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function _s(e){return new w(t=>{const{stop:n}=gt(e,window,["visibilitychange","freeze"],o=>{o.type==="visibilitychange"&&document.visibilityState==="hidden"?t.notify({reason:We.HIDDEN}):o.type==="freeze"&&t.notify({reason:We.FROZEN})},{capture:!0}),r=J(e,window,"beforeunload",()=>{t.notify({reason:We.UNLOADING})}).stop;return()=>{n(),r()}})}function Ts(e){return Le(We).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,g){n.notifyBeforeAddMessage(f),g!==void 0?(o[g]=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 g=e.estimateEncodedBytesCount(f);n.notifyAfterRemoveMessage(g)}function l(d,f){const g=q(d),m=e.estimateEncodedBytesCount(g);if(m>=r){T.warn(`Discarded a message whose size was bigger than the maximum allowed size ${r}KB. ${Ce} ${xt}/#technical-limitations`);return}a(f)&&c(f),i(g,m,f)}function u(d){const f=Le(o).join(`\n`);o={};const g=Ts(d.reason),m=g?t.sendOnExit:t.send;if(g&&e.isAsync){const y=e.finishSync();y.outputBytesCount&&m(Rn(y));const p=[y.pendingData,f].filter(Boolean).join(`\n`);p&&m({data:p,bytesCount:Qe(p)})}else f&&e.write(e.isEmpty?f:`\n${f}`),e.finish(y=>{m(Rn(y))})}return{flushController:n,add:l,upsert:l,stop:s.unsubscribe}}function Rn(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 Cs({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 w(()=>()=>{s.unsubscribe(),i.unsubscribe()});let c=0,l=0;function u(m){if(l===0)return;const y=l,p=c;l=0,c=0,g(),a.notify({reason:m,messagesCount:y,bytesCount:p})}let d;function f(){d===void 0&&(d=ge(()=>{u("duration_limit")},n))}function g(){Nt(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&&g()}}}function xn(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:gs(d,u.batchBytesLimit,r),flushController:Cs({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 Os{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 vs(e,t,n){let r=0,o=!1;return{isLimitReached(){if(r===0&&ge(()=>{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:R.AGENT,startClocks:$()})}finally{o=!1}}return!0}}}let bt;const yt=new WeakMap;function Rs(e){return bt||(bt=xs(e)),bt}function xs(e){return new w(t=>{const{stop:n}=X(XMLHttpRequest.prototype,"open",As),{stop:r}=X(XMLHttpRequest.prototype,"send",s=>{Ls(s,e,t)},{computeHandlingStack:!0}),{stop:o}=X(XMLHttpRequest.prototype,"abort",Is);return()=>{n(),r(),o()}})}function As({target:e,parameters:[t,n]}){yt.set(e,{state:"open",method:String(t).toUpperCase(),url:ct(String(n))})}function Ls({target:e,handlingStack:t},n,r){const o=yt.get(e);if(!o)return;const s=o;s.state="start",s.startClocks=$(),s.isAborted=!1,s.xhr=e,s.handlingStack=t;let i=!1;const{stop:a}=X(e,"onreadystatechange",()=>{e.readyState===XMLHttpRequest.DONE&&c()}),c=()=>{if(l(),a(),i)return;i=!0;const u=o;u.state="complete",u.duration=qn(s.startClocks.timeStamp,D()),u.status=e.status,r.notify(Qn(u))},{stop:l}=J(n,e,"loadend",c);r.notify(s)}function Is({target:e}){const t=yt.get(e);t&&(t.isAborted=!0)}let Et;function An(){return Et||(Et=ks()),Et}function ks(){return new w(e=>{if(!window.fetch)return;const{stop:t}=X(window,"fetch",n=>Ms(n,e),{computeHandlingStack:!0});return t})}function Ms({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:ct(String(o)),l=$(),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=>Ps(r,d,u))}function Ps(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 _t={};function Ns(e){const t=e.map(n=>(_t[n]||(_t[n]=Fs(n)),_t[n]));return Dt(...t)}function Fs(e){return new w(t=>{const n=L[e];return L[e]=(...r)=>{n.apply(console,r);const o=$e("console error");me(()=>{t.notify(Ds(r,e,o))})},()=>{L[e]=n}})}function Ds(e,t,n){const r=e.map(s=>$s(s)).join(" ");let o;if(t===_.error){const s=e.find(j);o={stack:s?Y(k(s)):void 0,fingerprint:rn(s),causes:s?sn(s,"console"):void 0,startClocks:$(),message:r,source:R.CONSOLE,handling:"handled",handlingStack:n,context:on(s)}}return{api:t,message:r,error:o,handlingStack:n}}function $s(e){return typeof e=="string"?M(e):j(e)?en(k(e)):q(M(e),void 0,2)}function Us(e){const t=dn(e)==="object";return t||T.error("Unsupported context:",e),t}function Tt(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)&&T.warn(`The property ${o} of ${n} is required; context will not be sent to the intake.`);return r}function ze(e="",{customerDataTracker:t,propertiesConfig:n={}}={}){let r={};const o=new w,s={getContext:()=>fn(r),setContext:i=>{Us(i)?(r=M(Tt(i,n,e)),t==null||t.updateCustomerData(r)):s.clearContext(),o.notify()},setContextProperty:(i,a)=>{r=M(Tt({...r,[i]:a},n,e)),t==null||t.updateCustomerData(r),o.notify()},removeContextProperty:i=>{delete r[i],t==null||t.updateCustomerData(r),Tt(r,n,e),o.notify()},clearContext:()=>{r={},t==null||t.resetCustomerData(),o.notify()},changeObservable:o};return s}const Bs="_dd_c",Gs=[];function wt(e,t,n,r){const o=js(n,r);Gs.push(J(e,window,"storage",({key:l})=>{o===l&&i()})),t.changeObservable.subscribe(a);const s=se(c(),t.getContext());pe(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 js(e,t){return`${Bs}_${e}_${t}`}const Ws=3*I,Hs=16*I,zs=200;function Ks(e=2){const t=new Map;let n=!1;function r(o=0){if(n||e===0)return;const s=e===2?Ws:Hs;let i=o;t.forEach(a=>{i+=a.getBytesCount()}),i>s&&(Vs(s),n=!0)}return{createDetachedTracker:()=>{const o=Ln(()=>r(o.getBytesCount()));return o},getOrCreateTracker:o=>(t.has(o)||t.set(o,Ln(r)),t.get(o)),setCompressionStatus:o=>{e===0&&(e=o,r())},getCompressionStatus:()=>e,stop:()=>{t.forEach(o=>o.stop()),t.clear()}}}function Ln(e){let t=0;const{throttled:n,cancel:r}=$t(s=>{t=Qe(q(s)),e()},zs),o=()=>{r(),t=0};return{updateCustomerData:s=>{pe(s)?o():n(s)},resetCustomerData:o,getBytesCount:()=>t,stop:()=>{r()}}}function Vs(e){T.warn(`Customer data exceeds the recommended ${e/I}KiB threshold. ${Ce} ${xt}/#customer-data-exceeds-the-recommended-threshold-warning`)}function qs(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(B);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 Ys="datadog-synthetics-public-id",Xs="datadog-synthetics-result-id",Js="datadog-synthetics-injects-rum";function In(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||z(Js))}function Qs(){const e=window._DATADOG_SYNTHETICS_PUBLIC_ID||z(Ys);return typeof e=="string"?e:void 0}function Zs(){const e=window._DATADOG_SYNTHETICS_RESULT_ID||z(Xs);return typeof e=="string"?e:void 0}function Ke(e,t,n){const r=n.getHandler(),o=Array.isArray(r)?r:[r];return kn[e]>=kn[n.getLevel()]&&o.includes(t)}const h={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},kn={[h.ok]:0,[h.debug]:1,[h.info]:2,[h.notice]:4,[h.warn]:5,[h.error]:6,[h.critical]:7,[h.alert]:8,[h.emerg]:9};function Ve(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 ei=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 Te={console:"console",http:"http",silent:"silent"},ti=Object.keys(h);let A=class{constructor(t,n,r,o=Te.http,s=h.debug,i={}){this.handleLogStrategy=t,this.handlerType=o,this.level=s,this.contextManager=ze("logger",{customerDataTracker:n}),this.contextManager.setContext(i),r&&this.contextManager.setContextProperty("logger",{name:r})}logImplementation(t,n,r=h.info,o,s){const i=M(n);let a;if(o!=null){const c=nn({stackTrace:j(o)?k(o):void 0,originalError:o,nonErrorPrefix:"Provided",source:R.LOGGER,handling:"handled",startClocks:$()});a=se({error:Ve(c,{includeMessage:!0})},i)}else a=i;this.handleLogStrategy({message:M(t),context:a,status:r},this,s)}log(t,n,r=h.info,o){let s;Ke(r,Te.http,this)&&(s=$e("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}};ei([tr],A.prototype,"logImplementation",null),A.prototype.ok=P(h.ok),A.prototype.debug=P(h.debug),A.prototype.info=P(h.info),A.prototype.notice=P(h.notice),A.prototype.warn=P(h.warn),A.prototype.error=P(h.error),A.prototype.critical=P(h.critical),A.prototype.alert=P(h.alert),A.prototype.emerg=P(h.emerg);function P(e){return function(t,n,r){let o;Ke(e,Te.http,this)&&(o=$e("log")),this.logImplementation(t,n,e,r,o)}}function ni(e,t,n){return{view:{referrer:document.referrer,url:window.location.href},context:e.getContext(),user:t.getContext(),account:n.getContext()}}const ri=32*I;function oi(e){e.usePciIntake===!0&&e.site&&e.site!=="datadoghq.com"&&T.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");const t=to(e),n=Mn(e.forwardConsoleLogs,Le(_),"Forward Console Logs"),r=Mn(e.forwardReports,Le(Ue),"Forward Reports");if(!(!t||!n||!r))return e.forwardErrorsToLogs&&!n.includes(_.error)&&n.push(_.error),{forwardErrorsToLogs:e.forwardErrorsToLogs!==!1,forwardConsoleLogs:n,forwardReports:r,requestErrorResponseLengthLimit:ri,...t}}function Mn(e,t,n){if(e===void 0)return[];if(!(e==="all"||Array.isArray(e)&&e.every(r=>t.includes(r)))){T.error(`${n} should be "all" or an array with allowed values "${t.join(\'", "\')}"`);return}return e==="all"?t:Go(e)}function si(e){const t=no(e);return{forward_errors_to_logs:e.forwardErrorsToLogs,forward_console_logs:e.forwardConsoleLogs,forward_reports:e.forwardReports,use_pci_intake:e.usePciIntake,...t}}function ii(e,t,n){const r=mn();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){T.error("Missing configuration");return}if(ro(c.enableExperimentalFeatures),je()&&(c=ai(c)),o=c,s){an("DD_LOGS",c);return}const l=oi(c);l&&(s=l,An().subscribe(B),t.tryToInit(l.trackingConsent),a())},get initConfiguration(){return o},getInternalContext:B,handleLog(c,l,u,d=e(),f=D()){r.add(g=>g.handleLog(c,l,u,d,f))}}}function ai(e){return{...e,clientToken:"empty"}}const Ct="logs";function ci(e){const t=Ks(),n=ze("global context",{customerDataTracker:t.getOrCreateTracker(2)}),r=ze("user",{customerDataTracker:t.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),o=ze("account",{customerDataTracker:t.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),s=Nr();function i(){return ni(n,r,o)}let a=ii(i,s,(u,d)=>{u.storeContextsAcrossPages&&(wt(d,n,Ct,2),wt(d,r,Ct,1),wt(d,o,Ct,4));const f=e(u,d,i,s);return a=ui(u,f),f});const c={},l=new A((...u)=>a.handleLog(...u),t.createDetachedTracker());return ko({logger:l,init:b(u=>a.init(u)),setTrackingConsent:b(u=>{s.update(u),Xo({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 A((...f)=>a.handleLog(...f),t.createDetachedTracker(),M(u),d.handler,d.level,M(d.context)),c[u])),getLogger:b(u=>c[u]),getInitConfiguration:b(()=>fn(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 ui(e,t){return{init:n=>{an("DD_LOGS",n)},initConfiguration:e,...t}}const li="logs";function di(e,t){const n=os(e,li,r=>pi(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 fi(e){const n=Pn(e)==="1"?{}:void 0;return{findTrackedSession:()=>n,expireObservable:new w}}function Pn(e){return Oe(e.sessionSampleRate)?"1":"0"}function pi(e,t){const n=mi(t)?t:Pn(e);return{trackingType:n,isTracked:n==="1"}}function mi(e){return e==="0"||e==="1"}let Nn=!1;function qe(e){const t=window;if(In()){const r=n(t.DD_RUM_SYNTHETICS);return!r&&!Nn&&(Nn=!0,hn("Logs sent before RUM is injected by the synthetics worker",{testId:Qs(),resultId:Zs()})),r}return n(t.DD_RUM);function n(r){if(r&&r.getInternalContext)return r.getInternalContext(e)}}function gi(e,t,n,r,o){const s=ti.concat(["custom"]),i={};s.forEach(a=>{i[a]=vs(a,t.eventRateLimiterThreshold,o)}),n.subscribe(0,({rawLogsEvent:a,messageContext:c=void 0,savedCommonContext:l=void 0,domainContext:u})=>{var d,f;const g=Xn(a.date),m=e.findTrackedSession(g);if(!e.findTrackedSession(g,{returnInactive:!0}))return;const p=l||r();let O;!pe(p.account)&&p.account.id&&(O=p.account),m&&m.anonymousId&&!p.user.anonymous_id&&(p.user.anonymous_id=m.anonymousId);const v=se({service:t.service,session_id:m?m.id:void 0,session:m?{id:m.id}:void 0,usr:pe(p.user)?void 0:p.user,account:O,view:p.view},p.context,qe(g),a,c);((d=t.beforeSend)===null||d===void 0?void 0:d.call(t,v,u))===!1||v.origin!==R.AGENT&&((f=i[v.status])!==null&&f!==void 0?f:i.custom).isLimitReached()||n.notify(1,v)})}const hi={[_.log]:h.info,[_.debug]:h.debug,[_.info]:h.info,[_.warn]:h.warn,[_.error]:h.error};function Si(e,t){const n=Ns(e.forwardConsoleLogs).subscribe(r=>{var o;const s={rawLogsEvent:{date:D(),message:r.message,origin:R.CONSOLE,error:r.error&&Ve(r.error),status:hi[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 bi(e,t){const n=Po(e,e.forwardReports).subscribe(r=>{let o=r.message,s;const i=r.originalError.type==="deprecation"?h.warn:h.error;i===h.error?s=Ve(r):r.stack&&(o+=` Found in ${xo(r.stack)}`),t.notify(0,{rawLogsEvent:{date:D(),message:o,origin:R.REPORT,error:s,status:i}})});return{stop:()=>{n.unsubscribe()}}}function yi(e,t){if(!e.forwardErrorsToLogs)return{stop:B};const n=Rs(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?Ei(i.xhr,e,a):i.response?Ti(i.response,e,a):i.error&&_i(i.error,e,a));function a(c){const l={isAborted:i.isAborted,handlingStack:i.handlingStack};t.notify(0,{rawLogsEvent:{message:`${Ci(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:h.error,origin:R.NETWORK},domainContext:l})}}return{stop:()=>{n.unsubscribe(),r.unsubscribe()}}}function Ei(e,t,n){typeof e.response=="string"?n(Ot(e.response,t)):n(e.response)}function _i(e,t,n){n(Ot(Y(k(e)),t))}function Ti(e,t,n){const r=cs(e);!r||!r.body?n():window.TextDecoder?Oi(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 Ci(e){return e==="xhr"?"XHR":"Fetch"}function Oi(e,t,n){qs(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 vi(e,t){if(!e.forwardErrorsToLogs)return{stop:B};const n=new w,{stop:r}=Ao(n),o=n.subscribe(s=>{t.notify(0,{rawLogsEvent:{message:s.message,date:s.startClocks.timeStamp,error:Ve(s),origin:R.SOURCE,status:h.error},messageContext:s.context})});return{stop:()=>{r(),o.unsubscribe()}}}const Ri=Os;function xi(e){function t(n,r,o,s,i){const a=se(r.getContext(),n.context);if(Ke(n.status,Te.console,r)&&Li(n,a),Ke(n.status,Te.http,r)){const c={rawLogsEvent:{date:i||D(),message:n.message,status:n.status,origin:R.LOGGER},messageContext:a,savedCommonContext:s};o&&(c.domainContext={handlingStack:o}),e.notify(0,c)}}return{handleLog:t}}const Ai={[h.ok]:_.debug,[h.debug]:_.debug,[h.info]:_.info,[h.notice]:_.info,[h.warn]:_.warn,[h.error]:_.error,[h.critical]:_.error,[h.alert]:_.error,[h.emerg]:_.error};function Li({status:e,message:t},n){W[Ai[e]].call(L,t,n)}function Ii(e,t,n,r,o){const s=xn(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=St();e.subscribe(1,n=>{t.send("log",n)})}function Mi(e){return{get:t=>{const n=e.findTrackedSession(t);if(n)return{session_id:n.id}}}}function Pi(e){return t=>{e.notify(0,{rawLogsEvent:{message:t.message,date:t.startClocks.timeStamp,origin:R.AGENT,status:h.error}}),hn("Error reported to customer",{"error.message":t.message})}}function Ni(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=qe())===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=qe())===null||l===void 0?void 0:l.view)===null||u===void 0?void 0:u.id},action:{id:(f=(d=qe())===null||d===void 0?void 0:d.user_action)===null||f===void 0?void 0:f.id}}});const i=[];if(je()){const a=St(),c=s.observable.subscribe(l=>a.send("internal_telemetry",l));i.push(()=>c.unsubscribe())}else{const a=xn(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,qo(t)));i.push(()=>c.unsubscribe())}return Vo(),Yo(si(e)),{telemetry:s,stop:()=>{i.forEach(a=>a())}}}function Fi(e,t,n,r){const o=new Ri,s=[];o.subscribe(1,f=>ln("logs",f));const i=Pi(o),a=_s(t),c=t.sessionStoreStrategyType&&!je()&&!In()?di(t,r):fi(t),{stop:l}=Ni(e,t,i,a,c);s.push(()=>l()),yi(t,o),vi(t,o),Si(t,o),bi(t,o);const{handleLog:u}=xi(o);if(gi(c,t,o,n,i),je())ki(o);else{const{stop:f}=Ii(t,o,i,a,c);s.push(()=>f())}const d=Mi(c);return{handleLog:u,getInternalContext:d.get,stop:()=>{s.forEach(f=>f())}}}const ae=ci(Fi);Mo(U(),"DD_LOGS",ae);class N{constructor(t){this.isLoggingOn=t,t&&ae.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!1,sessionSampleRate:100})}static setMessagePort(t){this.messagePort=t}static getMessagePort(){return this.messagePort}setLoggingOn(t){this.isLoggingOn=t}setAttributes(t){for(const n in t)ae.logger.setContextProperty(n,t[n])}info(t,n){this.isLoggingOn&&(ae.logger.info(t,n),console.log("[Logger] Sending info: ",t))}error(t,n){this.isLoggingOn&&(ae.logger.error(t,n),console.log("[Logger] Sending error: ",t))}warn(t,n){this.isLoggingOn&&(ae.logger.warn(t,n),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){N.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:t})}static info(t,n){N.messagePort.postMessage({type:"LOG",actionType:"INFO",message:t,attributes:n})}static error(t,n){N.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:t,attributes:n})}static warn(t,n){N.messagePort.postMessage({type:"LOG",actionType:"WARN",message:t,attributes:n})}}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 v=this.header.join(" ");return this.matchItem(v,this.dataos)},matchItem(v,F){for(let ce=0;ce<F.length;ce+=1)if(new RegExp(F[ce].value,"i").test(v))return F[ce].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"}})(),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,g=this.field;const m=l*60+u,p=(m-Math.floor(m/10))*c;return l*(a*3600)+u*(a*60)+d*a+(f*2+g)-p},this.addSeconds=i=>{let a=this.copy();return a.s+=i,a.s>=60&&(a.s=0,a.m++,a.m>=60&&(a.m=0,a.h++)),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 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 g=c;d+=u*10;let m=0;return m=g%2,g=Math.floor(g/2),new C(l,d,f,g,m)},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),g=c?Number(c):0;return new C(l,u,d,f,g)};let we=C;class Di{constructor(){this.start=0,this.end=0,this.startTimeoutForSeconds=t=>{this.start=performance.now(),this.end=this.start+t*1e3},this.isTimeout=()=>{const t=performance.now()>=this.end;return t&&(this.start=0,this.end=0),!t}}}const vt={lastRendererFrameSent:0,isRAFSeen:!1,isRVFCSeen:!1,RVFCmissed:!1,RVFCframeExpected:0,compensationMode:!1,compensationCounter:0,frameCorrection:0,lastMessageSent:""};let Ye=null,x,E,Dn=new Di;self.onmessage=async e=>{const{data:t}=e;t.type==="SET_LOGGER_PORT"&&N.setMessagePort(t.port),t.type==="SET_RENDERER_PORT"&&(Ye=t.port,Ye.onmessage=$i),t.type==="ADAPTER_UPDATE_DATA"&&(E=t.data,$n()),t.type==="SET_OPTIONS"&&(x=t.options,N.setMessagePort(self))};function $i(e){x&&Z(x,"Adapter")&&console.log("[AdapterWorker] Message from Renderer:",e.data)}const $n=()=>{!E||E.siData.isVideoPaused||(Fn.isChromeMac()?Ui():Fn.isSafariMac()&&Bi())},Ui=()=>{if(!E||E.siData.isVideoPaused||!E.vfcData.lastFrameMetadata)return;const{siData:e,vfcData:t,afData:n,debugControls:r}=E;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 v=parseInt(r["Frame Correction"],10);isNaN(v)||(i=v);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 g=u.expectedDisplayTime-s,m=[];for(let p=-10;p<10;p++)m.push(g+p*c);let y=null;f.forEach((p,O)=>{l>p&&l<m[O]&&(y=O-10)}),y!==null?setTimeout(p=>Rt(t.lastCalculatedMediaTimeVideoFrame+p*Math.round(60/t.videoFPS)+i),a,y):Rt(vt.lastRendererFrameSent)}},Bi=()=>{if(!E||E.siData.isVideoPaused||!E.vfcData.lastFrameMetadata)return;const{siData:e,vfcData:t,afData:n}=E;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),Rt(i,s)},Rt=(e,t)=>{if(!E)return;vt.lastRendererFrameSent=e,E.siData.workingFps;const n=we.fromFrames(e,6e4/1001);if(Dn.isTimeout())Un(n);else{const r=E.vfcData.videoFPS;if(r<=10||r>70){console.error("Video FPS is out of supported range: "+r),Dn.startTimeoutForSeconds(3),Un(n);return}E.afData.animationFPS,Gi(n,t)}},Gi=(e,t)=>{const n=we.toStr(e);vt.lastMessageSent=n,x&&Z(x,"Adapter")&&console.log(`[AdapterWorker] Rendering augmentation for timecode: ${n} , ${e}`),Bn(n,t)},Un=e=>{const t=we.toStr(e);x&&Z(x,"Adapter")&&console.log("[AdapterWorker] Clearing augmentation"),Bn(t,0,!0)},Bn=(e,t,n)=>{if(!Ye||!E)return;const r=e;x&&Z(x,"Adapter")&&console.log(`[AdapterWorker] Sending current time code to the Renderer: ${r}`);const o={timeCode:r,frameCorrection:t||0,fps:Wn(E.siData.workingFps),cloudFrontURL:E.cloudFrontURL,bucketName:E.bucketName,customerId:E.customerId,offsets:E.offsets},i={type:n?"RENDERER_CLEAR":"RENDERER_DRAW",streamData:o};Ye.postMessage(i)};self.onunhandledrejection=e=>{N.error("[AdapterWorker] Unhandled rejection",{error:e.reason}),x&&(Z(x,"Errors")&&console.error("[AdapterWorker] Unhandled rejection:",e.reason),e.preventDefault())},self.onerror=e=>{N.error("[AdapterWorker] Unhandled error",{error:e}),x&&(Z(x,"Errors")&&console.error("[AdapterWorker] Unhandled error:",e),e instanceof Event&&e.preventDefault())},setInterval($n,2)})();\n',Gt=typeof self<"u"&&self.Blob&&new Blob([zt],{type:"text/javascript;charset=utf-8"});function ir(t){let e;try{if(e=Gt&&(self.URL||self.webkitURL).createObjectURL(Gt),!e)throw"";const n=new Worker(e,{name:t==null?void 0:t.name});return n.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),n}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)}}class Vt{constructor(){this.metrics=new Map,this.containers=[],this.createContainer=()=>{const e=document.createElement("div");e.style.display="flex",e.style.gap="10px",e.style.marginBottom="5px",e.style.fontSize="14px";const n={div:e,metrics:[]};return this.containers.push(n),document.body.appendChild(e),n},this.createMetric=(e,n)=>{const r=document.createElement("span"),s={name:e,value:"",span:r};return n.metrics.push(s),r.textContent=`${e}: ${s.value}`,n.div.appendChild(r),this.metrics.set(e,s),s},this.updateMetric=(e,n)=>{const r=this.metrics.get(e);if(!r){console.error("Metric does not exist");return}typeof n=="boolean"?r.value=n?"true":"false":r.value=n,r.span.textContent=`${e}: ${r.value}`}}delete(){this.containers.forEach(e=>{e.div.remove()})}}class or{constructor(e){if(this.canPlayListner=()=>this.setupCanvas(),this.clickListner=n=>{this.clicker.click(n)},this.mediaTime=0,this.timecodeChecker=new er(0),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 Vt;const n=this.metrics.createContainer();if(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 r=this.metrics.createContainer();this.metrics.createMetric("Rendering GPU time",r),this.metrics.createMetric("Rendering CPU time",r),this.metrics.createMetric("Chunking time",r),this.metrics.createMetric("Decoding time",r)}}this.downloaderWorker=new nr,this.decoderWorker=new rr,this.rendererWorker=new sr,this.adapterWorker=new ir,window.BB.workerInstances.push(this.downloaderWorker,this.decoderWorker,this.rendererWorker,this.adapterWorker),this.rendererToDownloader=new MessageChannel,this.rendererToMain=new MessageChannel,this.downloaderToDecoder=new MessageChannel,this.decoderToRenderer=new MessageChannel,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 tr(this.OTTPlayer.video,this.rendererWorker),this.segmentFirstFrameTimecode=new O,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(n=>{n.update()}),this.animationFrameLoopId=requestAnimationFrame(e)};this.animationFrameLoopId=requestAnimationFrame(e)}startVideoFrameCallbackLoop(){const e=(n,r)=>{this.mediaTime=r.mediaTime,this.videoFPScalculator.addTimestamp(r.mediaTime),this.videoFrameCallbackLoopId=this.OTTPlayer.video.requestVideoFrameCallback(e)};this.videoFrameCallbackLoopId=this.OTTPlayer.video.requestVideoFrameCallback(e)}setupCanvas(){const e=this.OTTPlayer.video,n=e.parentElement;this.canvas.width=e.videoWidth,this.canvas.height=e.videoHeight,this.canvas.style.zIndex="3000",this.canvas.style.position="absolute",this.canvas.style.top="50%",this.canvas.style.transform="translateY(-50%)",this.canvas.style.left="0",this.canvas.style.width=n.style.width,this.canvas.style.height=n.style.height,this.canvas.style.pointerEvents="none",n.addEventListener("click",this.clickListner),n.style.position="relative",n.appendChild(this.canvas);const r=this.canvas.transferControlToOffscreen(),s={type:"INIT_OFFSCREEN",offscreen:r,options:this.options};this.rendererWorker.postMessage(s,[r]),e.onseeked=()=>{this.onVideoSeeked()},e.onseeking=()=>{this.onVideoSeeked()}}setupWorkers(){this.downloaderWorker.onmessage=e=>{e.data.type==="LOG"?this.logger.handleMessageFromWorker(e.data):e.data.type==="TRACK_PERFORMANCE"&&this.trackPerformance(e.data)},this.decoderWorker.onmessage=e=>{e.data.type==="LOG"?(e.data.actionType==="SET_ATTRIBUTES"&&e.data.attributes.last_decoded_frame&&this.metrics&&this.metrics.updateMetric("Last Decoded Frame",e.data.attributes.last_decoded_frame),this.logger.handleMessageFromWorker(e.data)):e.data.type==="TRACK_PERFORMANCE"&&this.trackPerformance(e.data)},this.rendererWorker.onmessage=e=>{e.data.type==="LOG"?(e.data.actionType==="SET_ATTRIBUTES"&&this.metrics&&(e.data.attributes.last_webgl_uploaded_frame&&this.metrics.updateMetric("Last WebGL Uploaded Frame",e.data.attributes.last_webgl_uploaded_frame),e.data.attributes.last_rendered_frame&&this.metrics.updateMetric("Last Rendered Frame",e.data.attributes.last_rendered_frame),e.data.attributes.renderer_state&&this.metrics.updateMetric("Renderer State",e.data.attributes.renderer_state)),this.logger.handleMessageFromWorker(e.data)):e.data.type==="TRACK_PERFORMANCE"&&this.trackPerformance(e.data)},this.adapterWorker.onmessage=e=>{e.data.type==="LOG"?this.logger.handleMessageFromWorker(e.data):e.data.type==="TRACK_PERFORMANCE"&&this.trackPerformance(e.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.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=e=>{e.data.type==="LOG"?(e.data.actionType==="SET_ATTRIBUTES"&&this.metrics&&(e.data.attributes.last_webgl_uploaded_frame&&this.metrics.updateMetric("Last WebGL Uploaded Frame",e.data.attributes.last_webgl_uploaded_frame),e.data.attributes.last_rendered_frame&&this.metrics.updateMetric("Last Rendered Frame",e.data.attributes.last_rendered_frame),e.data.attributes.renderer_state&&this.metrics.updateMetric("Renderer State",e.data.attributes.renderer_state)),this.logger.handleMessageFromWorker(e.data)):e.data.type==="TRACK_PERFORMANCE"&&this.trackPerformance(e.data)},this.downloaderWorker.postMessage({type:"SET_OPTIONS",options:this.options}),this.decoderWorker.postMessage({type:"SET_OPTIONS",options:this.options}),this.adapterWorker.postMessage({type:"SET_OPTIONS",options:this.options}),this.rendererWorker.postMessage({type:"SET_OPTIONS",options:this.options})}callAdapterWorker(e){this.adapterWorker.postMessage({type:"ADAPTER_UPDATE_DATA",data:e})}callRendererWorker(e,n,r){this.options&&L(this.options,"Clocker")&&console.log(`[Clocker] Sending current time code to the Renderer: ${e}`);const s=r?"RENDERER_CLEAR":"RENDERER_DRAW";if(!e||!this.OTTPlayer.gameParams||!this.OTTPlayer.gameParams.bucketName||!this.OTTPlayer.gameParams.offsets){const a={type:s};this.rendererWorker.postMessage(a);return}const i={timeCode:e,frameCorrection:n||0,fps:he(this.videoFPScalculator.getFPS()),cloudFrontURL:this.OTTPlayer.options.cloudFrontURL,bucketName:this.OTTPlayer.gameParams.bucketName,offsets:this.OTTPlayer.gameParams.offsets,customerId:this.OTTPlayer.gameParams.customerId},o={type:s,streamData:i};this.rendererWorker.postMessage(o),r||this.logger.setAttributes({last_timecode:e})}onVideoSeeked(){this.downloaderWorker.postMessage({type:"VIDEO_SEEKED"}),this.decoderWorker.postMessage({type:"VIDEO_SEEKED"}),this.rendererWorker.postMessage({type:"VIDEO_SEEKED"}),this.OTTPlayer.adapter&&this.OTTPlayer.adapter.onVideoSeeked(),this.logger.info("didSeek")}trackPerformance(e){var n;if((n=this.options.debug)!=null&&n.trackPerformance&&this.metrics)for(let r of e.data)this.metrics.updateMetric(r.metric,r.value.toFixed(2))}delete(){const e=this.OTTPlayer.video,n=e.parentElement;n.removeChild(this.canvas),this.rendererWorker.terminate(),this.downloaderWorker.terminate(),this.decoderWorker.terminate(),this.adapterWorker.terminate(),this.metrics&&this.metrics.delete(),this.animationFrameLoopId&&cancelAnimationFrame(this.animationFrameLoopId),this.videoFrameCallbackLoopId&&e.cancelVideoFrameCallback(this.videoFrameCallbackLoopId),e.removeEventListener("canplay",this.canPlayListner),n.removeEventListener("click",this.clickListner)}}class ar{constructor(){this.controls=new Map,this.containers=[]}createContainer(e){const n=document.createElement("div");n.style.display="flex",n.style.flexWrap="wrap",n.style.gap="10px",n.style.padding="10px",n.style.marginBottom="10px",n.style.border="1px solid #ccc",n.style.fontSize="14px",n.style.backgroundColor="#f9f9f9";const r=document.createElement("button");r.textContent="Apply",r.style.cursor="pointer";const s={div:n,controls:[],button:r};return r.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)}),n.appendChild(r),document.body.appendChild(n),this.containers.push(s),s}createInput(e,n="",r){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(n),o.style.minWidth="60px";const a={name:e,type:"input",element:o,container:r,appliedValue:String(n)};this.controls.set(e,a),r.controls.push(a),s.appendChild(i),s.appendChild(o),r.div.insertBefore(s,r.button)}createSelect(e,n,r="",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(n).forEach(([l,u])=>{const d=document.createElement("option");d.textContent=l,d.value=String(u),a.appendChild(d)}),a.value=String(r);const c={name:e,type:"select",element:a,container:s,appliedValue:String(r)};this.controls.set(e,c),s.controls.push(c),i.appendChild(o),i.appendChild(a),s.div.insertBefore(i,s.button)}createCheckbox(e,n=!1,r){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=n;const a={name:e,type:"checkbox",element:o,container:r,appliedValue:String(n)};this.controls.set(e,a),r.controls.push(a),s.appendChild(i),s.appendChild(o),r.div.insertBefore(s,r.button)}exportData(){const e={};return this.controls.forEach(n=>{e[n.name]=n.appliedValue}),e}getValue(e){const n=this.controls.get(e);return n?n.appliedValue:(console.error(`No control found with name: ${e}`),"")}delete(){this.containers.forEach(e=>{e.div.remove()}),this.containers=[],this.controls.clear()}}const Ae=t=>t.toString().padStart(2,"0"),rt=":",cr=(t,e,n=!1)=>{let r="";return Array.isArray(t)?(r=[Ae(t[0]),Ae(t[1]),Ae(t[2]),Ae(t[3])].join(":"),n==!0?t[4]==1&&e?r+=".2":r+=".1":t[4]==1&&e&&(r+=".1")):(r=("0"+t.h).slice(-2)+rt+("0"+t.m).slice(-2)+rt+("0"+t.s).slice(-2)+rt+("0"+t.f).slice(-2),r+="."+(t.field?"1":"2")),r},lr=(t,e,n)=>{let r=60,s=0;Math.floor(e)==60?(r=60,s=0):Math.floor(e)==59?(r=60,s=4):Math.floor(e)==30?(r=30,s=0):Math.floor(e)==29&&(r=30,s=2);let i=0,a=Math.floor(e*60*10)*6,c=t[0],l=t[1],u=t[2],d=t[3],f=t[4];return i+=c*a,i+=l*(r*60),i+=u*r,i+=d*2+f,i-=s*l,i+=s*Math.floor(l/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",n=()=>t()==="iPad",r=()=>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,w){for(let C=0;C<w.length;C+=1)if(new RegExp(w[C].value,"i").test(b))return w[C].name;return"unknown"}}).init(),l=()=>{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:n,isiPhone:r,isApple:s,isWindows:i,isAndroid:o,getDeviceDescription:a,getDeviceName:c,getBrowserName:l,isSafariMac:()=>e()&&l()==="Safari",isChromeMac:()=>e()&&l()==="Chrome",isChromeWin:()=>i()&&l()==="Chrome",isFirefoxMac:()=>e()&&l()==="Firefox",isFirefoxWin:()=>i()&&l()==="Firefox"}})();class ur{constructor(){this.start=0,this.end=0,this.startTimeoutForSeconds=e=>{this.start=performance.now(),this.end=this.start+e*1e3},this.isTimeout=()=>{const e=performance.now()>=this.end;return e&&(this.start=0,this.end=0),!e}}}class dr{constructor(e){if(this.platformSupported=!0,this.firstFrameTimecodeSet=!1,this.firstFrameTimecode=[0,0,0,0,0],this.firstVideoFrameCallbackFired=!1,this.timeout=new ur,this.loggerTimeoutStart=0,this.loggerTimeout=1e4,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.onAnimationFrame=n=>{if(this.video.paused||!this.OTTPlayer.clocker||!this.OTTPlayer.gameParams||!this.syncPoint){window.requestAnimationFrame(this.onAnimationFrame);return}this.afData.counter++,this.afData.previousTimestamp=this.afData.lastTimestamp,this.afData.lastTimestamp=performance.now(),this.afData.lastMetadataNow=n,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 r=(this.video.currentTime-this.syncPoint.playerTime)*(6e4/1001);this.afData.lastPlayerTimeFromSync=r;const s=Math.floor(r)+this.syncPoint.frame;this.afData.playerTimeOffset=O.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=r-Math.floor(r),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&&L(this.options,"Adapter")&&console.error(o)}window.requestAnimationFrame(this.onAnimationFrame),this.determineFrameUpdate()},this.onVideoFrame=(n,r)=>{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.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=(r.mediaTime-this.syncPoint.playerTime)*(6e4/1001);this.vfcData.lastMediaTimeFromSync=s;const i=Math.floor(s+.1)+this.syncPoint.frame;this.vfcData.mediaTimeOffset=O.calculateCurrentOffset(i,this.OTTPlayer.gameParams.offsets);let o=i-this.vfcData.mediaTimeOffset;o<0&&(o+=5178816),o++,this.vfcData.lastCalculatedMediaTimeVideoFrame=o,this.vfcData.lastFrameMetadata=r,this.vfcData.storedMetadata.push(r),this.vfcData.storedMetadata.length>10&&this.vfcData.storedMetadata.shift(),this.vfcData.timePerformanceNowToExpectedDisplayTime=r.expectedDisplayTime-this.vfcData.lastTimestamp,this.vfcData.timeRVFCnowToExpectedDisplayTime=r.expectedDisplayTime-n,this.vfcData.lastFrameMetadataNow=n,this.metrics&&(this.metrics.updateMetric("RVFC calls",this.vfcData.counter),this.metrics.updateMetric("Last metadata media time",r.mediaTime.toFixed(4)),this.metrics.updateMetric("Last metadata media time frame",this.vfcData.lastCalculatedMediaTimeVideoFrame),this.metrics.updateMetric("Time to presentation time",(r.presentationTime-n).toFixed(4)),this.metrics.updateMetric("Metadata presented frames",r.presentedFrames),this.metrics.updateMetric("Metadata processing duration",r.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.video.requestVideoFrameCallback(this.onVideoFrame),this.determineFrameUpdate()},this.determineFrameUpdate=()=>{var n,r,s,i;if(!(!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata))if(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(),!this.OTTPlayer.options.ADAPTER_RUN_IN_WORKER)this.platformSpecificFrameUpdate();else{const o={siData:this.siData,vfcData:this.vfcData,afData:this.afData,debugControls:(n=this.debugControls)==null?void 0:n.exportData(),cloudFrontURL:this.OTTPlayer.options.cloudFrontURL,bucketName:((r=this.OTTPlayer.gameParams)==null?void 0:r.bucketName)||"",offsets:((s=this.OTTPlayer.gameParams)==null?void 0:s.offsets)||[],customerId:((i=this.OTTPlayer.gameParams)==null?void 0:i.customerId)||""};this.OTTPlayer.clocker.callAdapterWorker(o)}},this.determineFrameUpdateChromeMac=()=>{const n=Math.round(1e3/this.vfcData.timeRVFCnowToExpectedDisplayTime);if(n>0&&n<500&&(this.expectedRefreshRateCalculator.addFrameDuration(this.vfcData.timeRVFCnowToExpectedDisplayTime/1e3),Math.abs(this.siData.expectedRefreshRate-n)>3?this.siData.newRefreshRateFrames++:(this.siData.expectedRefreshRate=n,this.siData.avgExpectedRefreshRate=this.expectedRefreshRateCalculator.getPerciseFPS()),this.siData.newRefreshRateFrames>10&&(this.siData.newRefreshRateFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedRefreshRate=n,this.siData.isRVFCpatternDetected=!1)),this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;const r=20,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*r<=i.length;o++){for(let a=0;a+o*r<=i.length;a++){let c=!0;for(let l=0;l<r-1;l++){const u=i.slice(a+l*o,a+(l+1)*o),d=i.slice(a+(l+1)*o,a+(l+2)*o);if(!u.every((f,p)=>f===d[p])){c=!1;break}}if(c){const l=i.slice(a,a+o),u=l.every(p=>!p),d=l.every(p=>p),f=this.afData.animationFPS-this.vfcData.videoFPS;if(u||d&&f>5)continue;this.siData.RVFCpattern=l,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 l=!0;for(let u=0;u<i.length;u++)if(i[u]!==o[c+u]){l=!1;break}if(l){a=c;break}}if(a>=0){const c=(o.length-a)%i.length,l=i[c];this.siData.patternTrackingIndex=c,this.siData.patternNextValue=l?1:0}if(o.length>=i.length*5){o.slice(o.length-i.length*5);let c=0,l=0;for(let u=0;u+i.length<=o.length;u++)o.slice(u,u+i.length).every((f,p)=>f===i[p])?(c++,l=Math.max(l,c),u+=i.length-1):c=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 i=[this.afData.lastTimestamp,this.vfcData.lastTimestamp,this.afData.previousTimestamp,this.vfcData.previousTimestamp].sort((l,u)=>u-l),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(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 i=0,o=1,a=5;if(this.debugControls){const c=parseInt(this.debugControls.getValue("Pattern offset"),10);isNaN(c)||(i=c);const l=parseInt(this.debugControls.getValue("Frame Correction"),10);isNaN(l)||(o=l);const u=parseInt(this.debugControls.getValue("Timeout time"),10);isNaN(u)||(a=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+i)%this.siData.RVFCpattern.length]?setTimeout(()=>this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+o),a):this.callRenderer(this.siData.lastRendererFrameSent)}else this.siData.isRVFCpatternDetected||this.clearAugmentation()},this.determineFrameUpdateChromeWin=()=>{const n=Math.round(1e3/this.vfcData.timeRVFCnowToExpectedDisplayTime);if(n>0&&n<500&&(this.expectedRefreshRateCalculator.addFrameDuration(this.vfcData.timeRVFCnowToExpectedDisplayTime/1e3),Math.abs(this.siData.expectedRefreshRate-n)>3?this.siData.newRefreshRateFrames++:(this.siData.expectedRefreshRate=n,this.siData.avgExpectedRefreshRate=this.expectedRefreshRateCalculator.getPerciseFPS()),this.siData.newRefreshRateFrames>10&&(this.siData.newRefreshRateFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedRefreshRate=n,this.siData.isRVFCpatternDetected=!1)),this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;const r=20,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*r<=i.length;o++){for(let a=0;a+o*r<=i.length;a++){let c=!0;for(let l=0;l<r-1;l++){const u=i.slice(a+l*o,a+(l+1)*o),d=i.slice(a+(l+1)*o,a+(l+2)*o);if(!u.every((f,p)=>f===d[p])){c=!1;break}}if(c){const l=i.slice(a,a+o),u=l.every(p=>!p),d=l.every(p=>p),f=this.afData.animationFPS-this.vfcData.videoFPS;if(u||d&&f>5)continue;this.siData.RVFCpattern=l,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 l=!0;for(let u=0;u<i.length;u++)if(i[u]!==o[c+u]){l=!1;break}if(l){a=c;break}}if(a>=0){const c=(o.length-a)%i.length,l=i[c];this.siData.patternTrackingIndex=c,this.siData.patternNextValue=l?1:0}if(o.length>=i.length*5){o.slice(o.length-i.length*5);let c=0,l=0;for(let u=0;u+i.length<=o.length;u++)o.slice(u,u+i.length).every((f,p)=>f===i[p])?(c++,l=Math.max(l,c),u+=i.length-1):c=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 i=[this.afData.lastTimestamp,this.vfcData.lastTimestamp,this.afData.previousTimestamp,this.vfcData.previousTimestamp].sort((l,u)=>u-l),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(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 i=0,o=2,a=!1;if(this.debugControls){const u=parseInt(this.debugControls.getValue("Pattern offset"),10);isNaN(u)||(i=u);const d=parseInt(this.debugControls.getValue("Frame Correction"),10);isNaN(d)||(o=d),parseInt(this.debugControls.getValue("Timeout time"),10);const f=this.debugControls.getValue("Video Captur Card Mode");console.log("selectVideoCaptureCardMode",f),f==="true"&&(a=!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})),a&&(i+=1);const c=(this.siData.patternTrackingIndex+this.siData.RVFCpattern.length-1+i)%this.siData.RVFCpattern.length,l=(c+this.siData.RVFCpattern.length-1)%this.siData.RVFCpattern.length;if(this.siData.RVFCpattern[c]){let u=0;a&&this.siData.lastRendererFrameSent==this.vfcData.lastCalculatedMediaTimeVideoFrame&&this.siData.RVFCpattern[l]&&(u=2),this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+u+o)}}else this.siData.isRVFCpatternDetected||this.clearAugmentation()},this.determineFrameUpdateSifariMac=()=>{if(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 n=Math.abs(this.siData.refreshRate-this.siData.workingFps)<2?8:20,r=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,l=1e3/this.afData.animationFPS,u=Math.round(l/4+.1),d=this.vfcData.timeRVFCnowToExpectedDisplayTime;if(this.siData.isRVFCSeen)this.metrics;else{const h=(-d-u)/l,m=Math.ceil(h),g=(Math.round(h)-h)*l,S=Math.abs(g)<=i,w=g<=0?m-1:m+1,C=Math.abs(-d-u)<=i;if(this.metrics&&(this.metrics.updateMetric("Is Smoothing Needed",S),this.metrics.updateMetric("Is More Than Border",m),this.metrics.updateMetric("Is Smoothed",w)),S&&!C){const k=Math.min(m,w),T=Math.max(m,w);this.metrics&&this.metrics.updateMetric("Pssblty next index",""+k+" "+T),this.siData.possibilityTracking[this.siData.possibilityTracking.length-k]=2,this.siData.possibilityTracking[this.siData.possibilityTracking.length-T]=1}else S&&C&&(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(-d<u)this.siData.expectedDisplayTimeReminder=-d;else if(c>l&&-d-(c-l)<=u)this.siData.expectedDisplayTimeReminder=-d-(c-l);else{let k=-d-c,T=0,y=this.siData.determineFramesIntervals.length-1;for(let A=this.siData.determineAFIntervals.length-1;A>=0&&(y--,!(this.siData.determineAFIntervals[A]>l&&k-(this.siData.determineAFIntervals[A]-l)<=u||k<=u||this.siData.determineFramesIntervals[y].includes("vf")&&this.siData.workingFps<40));A--)k-=this.siData.determineAFIntervals[A],T+=1;if(this.siData.patternTracking.length<T+1){this.siData.patternTracking=[!0];for(let A=0;A<T;A++)this.siData.patternTracking.push(!1)}else this.siData.patternTracking[this.siData.patternTracking.length-1-T]=!0;this.siData.animationFramesToDisplayTime=T}}if(this.siData.isRAFSeen||(this.siData.expectedDisplayTimeReminder?(this.siData.expectedDisplayTimeReminder-u,this.siData.expectedDisplayTimeReminder+c<=u?(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>r&&this.siData.patternTracking.shift(),this.siData.possibilityTracking.length>r&&this.siData.possibilityTracking.shift(),!this.siData.isRVFCpatternDetected){const h=this.siData.patternTracking;for(let m=1;m*n<=h.length;m++){for(let g=0;g+m*n<=h.length;g++){let S=!0;for(let b=0;b<n-1;b++){const w=h.slice(g+b*m,g+(b+1)*m),C=h.slice(g+(b+1)*m,g+(b+2)*m);if(!w.every((k,T)=>k===C[T])){S=!1;break}}if(S){const b=h.slice(g,g+m),w=b.every(T=>!T),C=b.every(T=>T),k=this.afData.animationFPS-this.vfcData.videoFPS;if(w||C&&k>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 w=0;w<h.length*5;w++)if(h[w%h.length]!==m[S+w]){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 w=0;w+h.length<=m.length;w++)m.slice(w,w+h.length).every((k,T)=>k===h[T])?(S++,b=Math.max(b,S),w+=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(Ue=>Ue?1:0).join("").repeat(S),w=(this.siData.RVFCpattern.length-this.siData.patternTrackingIndex)%this.siData.RVFCpattern.length,C=b.slice(0,w==0?-this.siData.RVFCpattern.length:-w);let k=0;const T=this.siData.possibilityTracking.length-1-this.siData.animationFramesToDisplayTime;C[C.length-1-this.siData.animationFramesToDisplayTime]=="0"&&this.siData.possibilityTracking[T]==1&&(k=-1);const y=this.siData.animationFramesToDisplayTime+k,A=y<=0?"":C.slice(-y);let Re=A.split("").filter(Ue=>Ue==="1").length*Math.round(60/this.siData.workingFps);this.siData.workingFps<40&&(Re+=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(Ue=>Ue===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+Re+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+Re+m?(this.callRenderer(this.siData.lastRendererFrameSent+1,this.siData.compensationCounter),this.siData.compensationMode=!0):this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+Re+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",Re),this.metrics.updateMetric("Compensation Counter",this.siData.compensationCounter),this.metrics.updateMetric("Repeated Pattern",b),this.metrics.updateMetric("Trimmed Pattern",C),this.metrics.updateMetric("Sliced Pattern",A),this.metrics.updateMetric("AF To Display Time Correction",k)),this.siData.previousPossibilityValue=p}else this.callRenderer(this.siData.lastRendererFrameSent)}else this.siData.isRVFCpatternDetected||this.clearAugmentation()},this.callRenderer=(n,r)=>{if(!this.OTTPlayer.clocker||!this.OTTPlayer)return;this.siData.lastRendererFrameSent=n,this.metrics&&this.metrics.updateMetric("Last sent frame",n);const s=this.OTTPlayer.clocker.videoFPScalculator.getFPS();this.metrics&&this.metrics.updateMetric("FPS",s.toFixed(2));const i=O.fromFrames(n,6e4/1001);if(this.timeout.isTimeout())this.clearAugmentation(i);else{const o=this.OTTPlayer.clocker.videoFPScalculator.getPerciseFPS();if(o<=20||o>70){this.logger.error("Video FPS is out of supported range: "+o),console.error("Video FPS is out of supported range: "+o),this.timeout.startTimeoutForSeconds(3),this.clearAugmentation(i);return}this.OTTPlayer.clocker.animationFPScalculator.getPerciseFPS(),this.renderAugmentation(i,r)}},this.playbackTimeDelta=0,this.wallClockTimeDelta=0,this.dateTimeDelta=0,this.renderAugmentation=(n,r)=>{if(!this.OTTPlayer||!this.OTTPlayer.clocker)throw new Error("OTTPlayer is not initialized");const s=O.toStr(n);this.siData.lastMessageSent=s,this.options&&L(this.options,"Adapter")&&console.log(`Rendering augmentation for timecode: ${s} , ${n}`),this.metrics&&this.metrics.updateMetric("Last sent timecode",s),this.OTTPlayer.clocker.callRendererWorker(s,r)},this.onVideoSeeked=()=>{this.firstFrameTimecode=[0,0,0,0,0],this.firstFrameTimecodeSet=!1},this.clearAugmentation=n=>{if(!this.OTTPlayer||!this.OTTPlayer.clocker)throw new Error("OTTPlayer is not initialized");const r=n?O.toStr(n):void 0;this.options&&L(this.options,"Adapter")&&console.log("Clearing augmentation"),this.OTTPlayer.clocker.callRendererWorker(r,0,!0)},this.logger=e.logger,this.OTTPlayer=e,this.options=e.options,this.options&&L(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 if(I.isSafariMac())this.platformSpecificFrameUpdate=this.determineFrameUpdateSifariMac;else{I.isFirefoxMac();{this.platformSpecificFrameUpdate=()=>{};const n=I.getCurrentPlatform(),r=I.getBrowserName();this.logger.error("Unsupported platform: "+n+" "+r),console.error("Unsupported platform: "+n+" "+r),this.platformSupported=!1;return}}if(this.debug){this.metrics=new Vt;const n=this.metrics.createContainer(),r=this.metrics.createContainer(),s=this.metrics.createContainer(),i=this.metrics.createContainer(),o=this.metrics.createContainer(),a=this.metrics.createContainer(),c=this.metrics.createContainer(),l=this.metrics.createContainer(),u=this.metrics.createContainer(),d=this.metrics.createContainer(),f=this.metrics.createContainer(),p=this.metrics.createContainer(),h=this.metrics.createContainer();this.metrics.createMetric("RAF calls",n),this.metrics.createMetric("RVFC calls",n),this.metrics.createMetric("RVFC missed",n),this.metrics.createMetric("Last sent frame",n),this.metrics.createMetric("Last sent timecode",n),this.metrics.createMetric("Last metadata media time",r),this.metrics.createMetric("Last player time",r),this.metrics.createMetric("RVFC to expected display time",r),this.metrics.createMetric("Performance Now to expected display time",r),this.metrics.createMetric("Last metadata media time frame",s),this.metrics.createMetric("Last player time frame",s),this.metrics.createMetric("Last player time fraction",s),this.metrics.createMetric("Last media time double frame",i),this.metrics.createMetric("Last player time double frame",i),this.metrics.createMetric("Compensation Counter",i),this.metrics.createMetric("AF metadata now - perf.now()",o),this.metrics.createMetric("VF metadata now - perf.now()",o),this.metrics.createMetric("VF ExpDispTime - AF metadata now",o),this.metrics.createMetric("Time to presentation time",a),this.metrics.createMetric("Metadata presented frames",a),this.metrics.createMetric("Metadata processing duration",a),this.metrics.createMetric("FPS",c),this.metrics.createMetric("Refresh rate",c),this.metrics.createMetric("Last RAF call",c),this.metrics.createMetric("Last RVFC call",c),this.metrics.createMetric("RAF - RVFC dif",c),this.metrics.createMetric("Determine frames intervals",l),this.metrics.createMetric("Last AF to VF time",u),this.metrics.createMetric("AF frames intervals",u),this.metrics.createMetric("Expected Refresh Rate",d),this.metrics.createMetric("Avg Expected Refresh Rate",d),this.metrics.createMetric("New Refresh Rate Frames",d),this.metrics.createMetric("AF To Display Time",d),this.metrics.createMetric("AF To Display Time Correction",d),this.metrics.createMetric("Call Renderer Reached",d),this.metrics.createMetric("Is Smoothing Needed",f),this.metrics.createMetric("Is More Than Border",f),this.metrics.createMetric("Is Smoothed",f),this.metrics.createMetric("Correction",f),this.metrics.createMetric("Repeated Pattern",f),this.metrics.createMetric("Trimmed Pattern",f),this.metrics.createMetric("Sliced Pattern",f),this.metrics.createMetric("Pattern found",p),this.metrics.createMetric("Pattern array",p),this.metrics.createMetric("Pattern tracking",p),this.metrics.createMetric("Pattern next index",p),this.metrics.createMetric("Pattern next value",p),this.metrics.createMetric("Pssblty found",h),this.metrics.createMetric("Pssblty array",h),this.metrics.createMetric("Pssblty tracking",h),this.metrics.createMetric("Pssblty next index",h),this.metrics.createMetric("Pssblty next value",h),this.debugControls=new ar;const m=this.debugControls.createContainer(),g=this.debugControls.createContainer();this.debugControls.createInput("Window Start (ms)",4,m),this.debugControls.createInput("Window End (ms)",-11,m),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",m),this.debugControls.createCheckbox("Video Captur Card Mode",!1,m),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",g):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",g):this.debugControls.createSelect("Frame Correction",{"-4":-4,"-3":-3,"-2":-2,"-1":-1,0:0,1:1,2:2,3:3,4:4},"1",g),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",g)}this.platformSupported&&(this.OTTPlayer.video.readyState>=3?this.setupAdapter():this.OTTPlayer.video.addEventListener("canplay",()=>this.setupAdapter(),{once:!0}))}setupAdapter(){const e=this.video;if(this.debug){const n=typeof wmcsdk<"u"?wmcsdk:wmcPlayer;console.log(n);const r=n.getAvailableVideoQualities(),s={};r.forEach(a=>{s[a.label]=a.id});const i=a=>{n.doSetVideoQuality(a.videoQuality)},o=this.debugControls.createContainer(i);this.debugControls.createSelect("videoQuality",s,r[0].id,o)}this.animationFrameLoopId=window.requestAnimationFrame(this.onAnimationFrame),this.videoFrameCallbackLoopId=e.requestVideoFrameCallback(this.onVideoFrame)}onNewSegmentForMetadata(e){if(!this.firstFrameTimecodeSet){const l=performance.now();l-this.loggerTimeoutStart>this.loggerTimeout&&(this.loggerTimeoutStart=l,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 n=lr(this.firstFrameTimecode,6e4/1001);if(console.log(e),!e.mimeType.includes("video"))return;const r=cr(this.firstFrameTimecode,!0,!0);this.options&&L(this.options,"Adapter")&&console.log("New segment ("+e.url+"): "+r+" ("+n+") playing at "+e.playbackTime);const s=e.playbackTime,i=s-this.playbackTimeDelta;this.playbackTimeDelta=s,console.log("Delta playback: ",i);const o=e.wallClockTime/1e3,a=o-this.wallClockTimeDelta;if(this.wallClockTimeDelta=o,console.log("Delta wallClock: ",a),e.dateTime instanceof Date){const l=e.dateTime.getTime()/1e3,u=l-this.dateTimeDelta;this.dateTimeDelta=l,console.log("Delta dateTime: ",u)}const c={frame:n,playerTime:s,stringTime:r,lastUpdate:performance.now()};this.syncPoint=c,this.metrics,this.options&&L(this.options,"Adapter")&&console.log("url: "+e.url)}onNewMetadata(e){if(e&&e.metadata&&e.metadata.id==0||I.isSafariMac()){if(e.metadata.messageData)e.metadata.messageData=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(r=>r.info&&r.info.toLowerCase().includes("ntc"));if(n.length){const r=`${n[n.length-1].info}\0${String.fromCharCode(...n[n.length-1].data)}`;e.metadata.messageData=this.processTimedMetadata(r,e.metadata.presentationTime)}}if(e.metadata.id==0||I.isSafariMac()&&this.timecode_offset==0){e.metadata.presentationTime*1e3;const n=new Date(this.tcTimeStamp-this.timecode_offset);let r=Math.round(n.getUTCMilliseconds()*30*2/1001)/2;const s=r%1;let i=1;s==.5&&(r=Math.floor(r),i=2),this.firstFrameTimecode=[n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),Math.floor(r),i==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: ",this.firstFrameTimecode)}}}processTimedMetadata(e,n){let r="";if(e&&e.includes("www.mediakind.com/NTC")){const s=e.replace(/.*NTC./,"");let i=0;for(;i+8<=s.length;){const o=s.substring(i,i+4),a=((s.charCodeAt(i+4)*256+s.charCodeAt(i+5))*256+s.charCodeAt(i+6))*256+s.charCodeAt(i+7);if(i+8+a>s.length)break;const c=s.substring(i+8,i+8+a);o=="utc_"&&new Date(parseInt(c)).getTime()/1e3,o=="tc__"&&(this.tcTimeStamp=new Date(parseInt(c)).getTime()),o==="offs"&&(this.timecode_offset=parseInt(c)/90),i+=8+a}}return r}delete(){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()}}class W{constructor(e,n){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=n,this.container=n.parentElement,this.corner=e;const r=document.createElement("div");r.style.position="absolute",r.style.width=`${this.size}px`,r.style.height=`${this.size}px`,r.style.transition="background-color 0s",r.style.zIndex="100000",this.element=r,this.container.appendChild(r),this.positionElement()}getRandomColor(){const r=Math.floor(Math.random()*11)+0;return`rgb(${r},${r},${r})`}update(){this.element.style.backgroundColor=this.getRandomColor(),this.positionElement()}delete(){this.container.removeChild(this.element)}static createInAllCorners(e){return[new W("left-top",e),new W("right-top",e),new W("right-bottom",e),new W("left-bottom",e)]}static updateAll(e){e.forEach(n=>n.update())}static deleteAll(e){e.forEach(n=>n.delete())}}const x={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},P=console,Y={};Object.keys(x).forEach(t=>{Y[t]=P[t]});const me="Datadog Browser SDK:",E={debug:Y.debug.bind(P,me),log:Y.log.bind(P,me),info:Y.info.bind(P,me),warn:Y.warn.bind(P,me),error:Y.error.bind(P,me)},st="https://docs.datadoghq.com",jt=`${st}/real_user_monitoring/browser/troubleshooting`,De="More details:";function Ht(t,e){return(...n)=>{try{return t(...n)}catch(r){E.error(e,r)}}}function Fe(t){return t!==0&&Math.random()*100<=t}function fr(t){return hr(t)&&t>=0&&t<=100}function hr(t){return typeof t=="number"}const ge=1e3,K=60*ge,qt=60*K,pr=365*(24*qt);function ye(){return new Date().getTime()}function z(){return ye()}function Oe(){return performance.now()}function G(){return{relative:Oe(),timeStamp:z()}}function mr(){return{relative:0,timeStamp:Wt()}}function gr(t,e){return e-t}function yr(t,e){return t+e}function _r(t){return t-Wt()}let it;function Wt(){return it===void 0&&(it=performance.timing.navigationStart),it}const M=1024,Yt=1024*M,br=/[^\u0000-\u007F]/;function ot(t){return br.test(t)?window.TextEncoder!==void 0?new TextEncoder().encode(t).length:new Blob([t]).size:t.length}function vr(t){return{...t}}function Kt(t,e){return Object.keys(t).some(n=>t[n]===e)}function _e(t){return Object.keys(t).length===0}function V(){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 se(t,e){const n=V();let r;return n.Zone&&typeof n.Zone.__symbol__=="function"&&(r=t[n.Zone.__symbol__(e)]),r||(r=t[e]),r}let Le,Jt=!1;function Sr(t){Le=t}function wr(t){Jt=t}function Tr(t,e,n){const r=n.value;n.value=function(...s){return(Le?v(r):r).apply(this,s)}}function v(t){return function(){return be(t,this,arguments)}}function be(t,e,n){try{return t.apply(e,n)}catch(r){xr(r)}}function xr(t){if(at(t),Le)try{Le(t)}catch(e){at(e)}}function at(...t){Jt&&E.error("[MONITOR]",...t)}function ve(t,e){return se(V(),"setTimeout")(v(t),e)}function Xt(t){se(V(),"clearTimeout")(t)}function ct(t,e){return se(V(),"setInterval")(v(t),e)}function Zt(t){se(V(),"clearInterval")(t)}class R{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(n=>e!==n),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}}notify(e){this.observers.forEach(n=>n(e))}}function Qt(...t){return new R(e=>{const n=t.map(r=>r.subscribe(s=>e.notify(s)));return()=>n.forEach(r=>r.unsubscribe())})}function en(t,e,n){let r=!1,s,i;return{throttled:(...o)=>{if(r){s=o;return}t(...o),r=!0,i=ve(()=>{s&&t(...s),r=!1,s=void 0},e)},cancel:()=>{Xt(i),r=!1,s=void 0}}}function j(){}function H(t){return t?(parseInt(t,10)^Math.random()*16>>parseInt(t,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,H)}const Ie=/([\w-]+)\s*=\s*([^;]+)/g;function Er(t,e){for(Ie.lastIndex=0;;){const n=Ie.exec(t);if(n){if(n[1]===e)return n[2]}else break}}function Cr(t){const e=new Map;for(Ie.lastIndex=0;;){const n=Ie.exec(t);if(n)e.set(n[1],n[2]);else break}return e}function kr(t,e,n=""){const r=t.charCodeAt(e-1),i=r>=55296&&r<=56319?e+1:e;return t.length<=i?t:`${t.slice(0,i)}${n}`}function Rr(){return Ur()===0}let Pe;function Ur(){return Pe??(Pe=Ar())}function Ar(t=window){var e;const n=t.navigator.userAgent;return t.chrome||/HeadlessChrome/.test(n)?0:((e=t.navigator.vendor)===null||e===void 0?void 0:e.indexOf("Apple"))===0||/safari/i.test(n)&&!/chrome|android/i.test(n)?1:2}function Se(t,e,n=0,r){const s=new Date;s.setTime(s.getTime()+n);const i=`expires=${s.toUTCString()}`,o=r&&r.crossSite?"none":"strict",a=r&&r.domain?`;domain=${r.domain}`:"",c=r&&r.secure?";secure":"",l=r&&r.partitioned?";partitioned":"";document.cookie=`${t}=${e};${i};path=/;samesite=${o}${a}${c}${l}`}function lt(t){return Er(document.cookie,t)}let ut;function J(t){return ut||(ut=Cr(document.cookie)),ut.get(t)}function tn(t,e){Se(t,"",0,e)}function Dr(t){if(document.cookie===void 0||document.cookie===null)return!1;try{const e=`dd_cookie_test_${H()}`,n="test";Se(e,n,K,t);const r=lt(e)===n;return tn(e,t),r}catch(e){return E.error(e),!1}}let dt;function Fr(){if(dt===void 0){const t=`dd_site_test_${H()}`,e="test",n=window.location.hostname.split(".");let r=n.pop();for(;n.length&&!lt(t);)r=`${n.pop()}.${r}`,Se(t,e,ge,{domain:r});tn(t,{domain:r}),dt=r}return dt}const ie="_dd_s";function Me(t){return Object.values(t)}function Or(t){return Object.entries(t)}const ft=4*qt,nn=15*K,Lr=pr,we={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},rn=/^([a-zA-Z]+)=([a-z0-9-]+)$/,ht="&";function Ir(t){return!!t&&(t.indexOf(ht)!==-1||rn.test(t))}const Pr="1";function X(t,e){const n={isExpired:Pr};return e.trackAnonymousUser&&(t!=null&&t.anonymousId?n.anonymousId=t==null?void 0:t.anonymousId:n.anonymousId=H()),n}function Be(t){return _e(t)}function sn(t){return!Be(t)}function Ne(t){return t.isExpired!==void 0||!Mr(t)}function Mr(t){return(t.created===void 0||ye()-Number(t.created)<ft)&&(t.expire===void 0||ye()<Number(t.expire))}function on(t){t.expire=String(ye()+nn)}function pt(t){return Or(t).map(([e,n])=>e==="anonymousId"?`aid=${n}`:`${e}=${n}`).join(ht)}function an(t){const e={};return Ir(t)&&t.split(ht).forEach(n=>{const r=rn.exec(n);if(r!==null){const[,s,i]=r;s==="aid"?e.anonymousId=i:e[s]=i}}),e}const Br="_dd",Nr="_dd_r",$r="_dd_l",zr="rum",Gr="logs";function Vr(t){if(!J(ie)){const n=J(Br),r=J(Nr),s=J($r),i={};n&&(i.id=n),s&&/^[01]$/.test(s)&&(i[Gr]=s),r&&/^[012]$/.test(r)&&(i[zr]=r),sn(i)&&(on(i),t.persistSession(i))}}function cn(t){const e=Yr(t);return Dr(e)?{type:we.COOKIE,cookieOptions:e}:void 0}function jr(t,e){const n={isLockEnabled:Rr(),persistSession:Hr(e),retrieveSession:Wr,expireSession:r=>qr(e,r,t)};return Vr(n),n}function Hr(t){return e=>{Se(ie,pt(e),nn,t)}}function qr(t,e,n){const r=X(e,n);Se(ie,pt(r),n.trackAnonymousUser?Lr:ft,t)}function Wr(){const t=lt(ie);return an(t)}function Yr(t){const e={};return e.secure=!!t.useSecureSessionCookie||!!t.usePartitionedCrossSiteSessionCookie,e.crossSite=!!t.usePartitionedCrossSiteSessionCookie,e.partitioned=!!t.usePartitionedCrossSiteSessionCookie,t.trackSessionAcrossSubdomains&&(e.domain=Fr()),e}const Kr="_dd_test_";function ln(){try{const t=H(),e=`${Kr}${t}`;localStorage.setItem(e,t);const n=localStorage.getItem(e);return localStorage.removeItem(e),t===n?{type:we.LOCAL_STORAGE}:void 0}catch{return}}function Jr(t){return{isLockEnabled:!1,persistSession:un,retrieveSession:Xr,expireSession:e=>Zr(e,t)}}function un(t){localStorage.setItem(ie,pt(t))}function Xr(){const t=localStorage.getItem(ie);return an(t)}function Zr(t,e){un(X(t,e))}const Qr=10,es=100,dn=[];let $e;function Z(t,e,n=0){var r;const{isLockEnabled:s,persistSession:i,expireSession:o}=e,a=f=>i({...f,lock:l}),c=()=>{const f=e.retrieveSession(),p=f.lock;return f.lock&&delete f.lock,{session:f,lock:p}};if($e||($e=t),t!==$e){dn.push(t);return}if(s&&n>=es){fn(e);return}let l,u=c();if(s){if(u.lock){ze(t,e,n);return}if(l=H(),a(u.session),u=c(),u.lock!==l){ze(t,e,n);return}}let d=t.process(u.session);if(s&&(u=c(),u.lock!==l)){ze(t,e,n);return}if(d&&(Ne(d)?o(d):(on(d),s?a(d):i(d))),s&&!(d&&Ne(d))){if(u=c(),u.lock!==l){ze(t,e,n);return}i(u.session),d=u.session}(r=t.after)===null||r===void 0||r.call(t,d||u.session),fn(e)}function ze(t,e,n){ve(()=>{Z(t,e,n+1)},Qr)}function fn(t){$e=void 0;const e=dn.shift();e&&Z(e,t)}const hn=ge;function ts(t){switch(t.sessionPersistence){case we.COOKIE:return cn(t);case we.LOCAL_STORAGE:return ln();case void 0:{let e=cn(t);return!e&&t.allowFallbackToLocalStorage&&(e=ln()),e}default:E.error(`Invalid session persistence '${String(t.sessionPersistence)}'`)}}function ns(t,e,n,r){const s=new R,i=new R,o=new R,a=t.type===we.COOKIE?jr(e,t.cookieOptions):Jr(e),{expireSession:c}=a,l=ct(h,hn);let u;g();const{throttled:d,cancel:f}=en(()=>{Z({process:y=>{if(Be(y))return;const A=m(y);return S(A),A},after:y=>{sn(y)&&!b()&&k(y),u=y}},a)},hn);function p(){Z({process:y=>b()?m(y):void 0},a)}function h(){Z({process:y=>Ne(y)?X(y,e):void 0,after:m},a)}function m(y){return Ne(y)&&(y=X(y,e)),b()&&(w(y)?C():(o.notify({previousState:u,newState:y}),u=y)),y}function g(){Z({process:y=>{if(Be(y))return X(y,e)},after:y=>{u=y}},a)}function S(y){if(Be(y))return!1;const{trackingType:A,isTracked:Lt}=r(y[n]);y[n]=A,delete y.isExpired,Lt&&!y.id&&(y.id=H(),y.created=String(ye()))}function b(){return u[n]!==void 0}function w(y){return u.id!==y.id||u[n]!==y[n]}function C(){u=X(u,e),i.notify()}function k(y){u=y,s.notify()}function T(y){Z({process:A=>({...A,...y}),after:m},a)}return{expandOrRenewSession:d,expandSession:p,getSession:()=>u,renewObservable:s,expireObservable:i,sessionStateUpdateObservable:o,restartSession:g,expire:()=>{f(),c(u),m(X(u,e))},stop:()=>{Zt(l)},updateSessionState:T}}const mt={GRANTED:"granted",NOT_GRANTED:"not-granted"};function rs(t){const e=new R;return{tryToInit(n){t||(t=n)},update(n){t=n,e.notify()},isGranted(){return t===mt.GRANTED},observable:e}}function Q(t,e,n){if(typeof t!="object"||t===null)return JSON.stringify(t);const r=oe(Object.prototype),s=oe(Array.prototype),i=oe(Object.getPrototypeOf(t)),o=oe(t);try{return JSON.stringify(t,e,n)}catch{return"<error: unable to serialize object>"}finally{r(),s(),i(),o()}}function oe(t){const e=t,n=e.toJSON;return n?(delete e.toJSON,()=>{e.toJSON=n}):j}function gt(t){return ss(t,location.href).href}function ss(t,e){const n=is();if(n)try{return e!==void 0?new n(t,e):new n(t)}catch(i){throw new Error(`Failed to construct URL: ${String(i)} ${Q({url:t,base:e})}`)}if(e===void 0&&!/:/.test(t))throw new Error(`Invalid URL: '${t}'`);let r=document;const s=r.createElement("a");if(e!==void 0){r=document.implementation.createHTMLDocument("");const i=r.createElement("base");i.href=e,r.head.appendChild(i),r.body.appendChild(s)}return s.href=t,s}const pn=URL;let Ge;function is(){if(Ge===void 0)try{Ge=new pn("http://test/path").href==="http://test/path"}catch{Ge=!1}return Ge?pn:void 0}const os="datad0g.com",as="dd0g-gov.com",ae="datadoghq.com",cs="ddog-gov.com",ls="pci.browser-intake-datadoghq.com",us=["ddsource","ddtags"];function Te(t,e,n){const r=ds(t,e);return{build(s,i){const o=hs(t,e,n,s,i);return r(o)},urlPrefix:r(""),trackType:e}}function ds(t,e){const n=`/api/v2/${e}`,r=t.proxy;if(typeof r=="string"){const i=gt(r);return o=>`${i}?ddforward=${encodeURIComponent(`${n}?${o}`)}`}if(typeof r=="function")return i=>r({path:n,parameters:i});const s=fs(e,t);return i=>`https://${s}${n}?${i}`}function fs(t,e){const{site:n=ae,internalAnalyticsSubdomain:r}=e;if(t==="logs"&&e.usePciIntake&&n===ae)return ls;if(r&&n===ae)return`${r}.${ae}`;if(n===as)return`http-intake.logs.${n}`;const s=n.split("."),i=s.pop();return`browser-intake-${s.join("-")}.${i}`}function hs({clientToken:t,internalAnalyticsSubdomain:e},n,r,s,{retry:i,encoding:o}){const a=["sdk_version:6.5.0",`api:${s}`].concat(r);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=${H()}`];return o&&c.push(`dd-evp-encoding=${o}`),n==="rum"&&c.push(`batch_time=${z()}`),e&&c.reverse(),c.join("&")}const ps=200;function ms(t){const{env:e,service:n,version:r,datacenter:s}=t,i=[];return e&&i.push(Ve("env",e)),n&&i.push(Ve("service",n)),r&&i.push(Ve("version",r)),s&&i.push(Ve("datacenter",s)),i}function Ve(t,e){const n=ps-t.length-1;(e.length>n||gs(e))&&E.warn(`${t} value doesn't meet tag requirements and will be sanitized. ${De} ${st}/getting_started/tagging/#defining-tags`);const r=e.replace(/,/g,"_");return`${t}:${r}`}function gs(t){return ys()?new RegExp("[^\\p{Ll}\\p{Lo}0-9_:./-]","u").test(t):!1}function ys(){try{return new RegExp("[\\p{Ll}]","u"),!0}catch{return!1}}function _s(t){const e=t.site||ae,n=ms(t),r=bs(t,n);return{replica:vs(t,n),site:e,...r}}function bs(t,e){return{logsEndpointBuilder:Te(t,"logs",e),rumEndpointBuilder:Te(t,"rum",e),sessionReplayEndpointBuilder:Te(t,"replay",e)}}function vs(t,e){if(!t.replica)return;const n={...t,site:ae,clientToken:t.replica.clientToken},r={logsEndpointBuilder:Te(n,"logs",e),rumEndpointBuilder:Te(n,"rum",e)};return{applicationId:t.replica.applicationId,...r}}function Ss(t){return us.every(e=>t.includes(e))}function yt(t,e){return t!=null&&typeof t!="string"?(E.error(`${e} must be defined as a string`),!1):!0}function ws(t){return t&&typeof t=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(t)?(E.error(`Site should be a valid Datadog site. ${De} ${st}/getting_started/site/.`),!1):!0}function je(t,e){return t!==void 0&&!fr(t)?(E.error(`${e} Sample Rate should be a number between 0 and 100`),!1):!0}function Ts(t){var e,n,r,s,i,o;if(!t||!t.clientToken){E.error("Client Token is not configured, we will not send any data.");return}if(!(!ws(t.site)||!je(t.sessionSampleRate,"Session")||!je(t.telemetrySampleRate,"Telemetry")||!je(t.telemetryConfigurationSampleRate,"Telemetry Configuration")||!je(t.telemetryUsageSampleRate,"Telemetry Usage")||!yt(t.version,"Version")||!yt(t.env,"Env")||!yt(t.service,"Service"))){if(t.trackingConsent!==void 0&&!Kt(mt,t.trackingConsent)){E.error('Tracking Consent should be either "granted" or "not-granted"');return}return{beforeSend:t.beforeSend&&Ht(t.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:ts(t),sessionSampleRate:(e=t.sessionSampleRate)!==null&&e!==void 0?e:100,telemetrySampleRate:(n=t.telemetrySampleRate)!==null&&n!==void 0?n:20,telemetryConfigurationSampleRate:(r=t.telemetryConfigurationSampleRate)!==null&&r!==void 0?r: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:mt.GRANTED,trackAnonymousUser:(o=t.trackAnonymousUser)!==null&&o!==void 0?o:!0,storeContextsAcrossPages:!!t.storeContextsAcrossPages,batchBytesLimit:16*M,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*ge,batchMessagesLimit:50,messageBytesLimit:256*M,..._s(t)}}}function xs(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 _t;(function(t){t.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",t.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(_t||(_t={}));const mn=new Set;function Es(t){Array.isArray(t)&&Cs(t.filter(e=>Kt(_t,e)))}function Cs(t){t.forEach(e=>{mn.add(e)})}function ks(){return mn}const xe="?";function B(t){const e=[];let n=bt(t,"stack");const r=String(t);return n&&n.startsWith(r)&&(n=n.slice(r.length)),n&&n.split(`
2
- `).forEach(s=>{const i=As(s)||Fs(s)||Ls(s)||Ms(s);i&&(!i.func&&i.line&&(i.func=xe),e.push(i))}),{message:bt(t,"message"),name:bt(t,"name"),stack:e}}const gn="((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\w+\\.|\\/).*?)",ce="(?::(\\d+))",Rs=new RegExp(`^\\s*at (.*?) ?\\(${gn}${ce}?${ce}?\\)?\\s*$`,"i"),Us=new RegExp(`\\((\\S*)${ce}${ce}\\)`);function As(t){const e=Rs.exec(t);if(!e)return;const n=e[2]&&e[2].indexOf("native")===0,r=e[2]&&e[2].indexOf("eval")===0,s=Us.exec(e[2]);return r&&s&&(e[2]=s[1],e[3]=s[2],e[4]=s[3]),{args:n?[e[2]]:[],column:e[4]?+e[4]:void 0,func:e[1]||xe,line:e[3]?+e[3]:void 0,url:n?void 0:e[2]}}const Ds=new RegExp(`^\\s*at ?${gn}${ce}?${ce}??\\s*$`,"i");function Fs(t){const e=Ds.exec(t);if(e)return{args:[],column:e[3]?+e[3]:void 0,func:xe,line:e[2]?+e[2]:void 0,url:e[1]}}const Os=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;function Ls(t){const e=Os.exec(t);if(e)return{args:[],column:e[4]?+e[4]:void 0,func:e[1]||xe,line:+e[3],url:e[2]}}const Is=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i,Ps=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i;function Ms(t){const e=Is.exec(t);if(!e)return;const n=e[3]&&e[3].indexOf(" > eval")>-1,r=Ps.exec(e[3]);return n&&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]||xe,line:e[4]?+e[4]:void 0,url:e[3]}}function bt(t,e){if(typeof t!="object"||!t||!(e in t))return;const n=t[e];return typeof n=="string"?n:void 0}function Bs(t,e,n,r){const s=[{url:e,column:r,line:n}],{name:i,message:o}=$s(t);return{name:i,message:o,stack:s}}const Ns=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\s\S]*)$/;function $s(t){let e,n;return{}.toString.call(t)==="[object String]"&&([,e,n]=Ns.exec(t)),{name:e,message:n}}function He(t){const n=new Error(t);n.name="HandlingStack";let r;return be(()=>{const s=B(n);s.stack=s.stack.slice(2),r=ee(s)}),r}function ee(t){let e=yn(t);return t.stack.forEach(n=>{const r=n.func==="?"?"<anonymous>":n.func,s=n.args&&n.args.length>0?`(${n.args.join(", ")})`:"",i=n.line?`:${n.line}`:"",o=n.line&&n.column?`:${n.column}`:"";e+=`
3
- at ${r}${s} @ ${n.url}${i}${o}`}),e}function yn(t){return`${t.name||"Error"}: ${t.message}`}function te(t,e,n,{computeHandlingStack:r}={}){let s=t[e];if(typeof s!="function")if(e in t&&e.startsWith("on"))s=j;else return{stop:j};let i=!1;const o=function(){if(i)return s.apply(this,arguments);const a=Array.from(arguments);let c;be(n,null,[{target:this,parameters:a,onPostCall:u=>{c=u},handlingStack:r?He("instrumented method"):void 0}]);const l=s.apply(this,a);return c&&be(c,null,[l]),l};return t[e]=o,{stop:()=>{i=!0,t[e]===o&&(t[e]=s)}}}const zs=220*M,Gs="$",Vs=3;function N(t,e=zs){const n=oe(Object.prototype),r=oe(Array.prototype),s=[],i=new WeakMap,o=vt(t,Gs,void 0,s,i),a=JSON.stringify(o);let c=a?a.length:0;if(c>e){wt(e,"discarded",t);return}for(;s.length>0&&c<e;){const l=s.shift();let u=0;if(Array.isArray(l.source))for(let d=0;d<l.source.length;d++){const f=vt(l.source[d],l.path,d,s,i);if(f!==void 0?c+=JSON.stringify(f).length:c+=4,c+=u,u=1,c>e){wt(e,"truncated",t);break}l.target[d]=f}else for(const d in l.source)if(Object.prototype.hasOwnProperty.call(l.source,d)){const f=vt(l.source[d],l.path,d,s,i);if(f!==void 0&&(c+=JSON.stringify(f).length+u+d.length+Vs,u=1),c>e){wt(e,"truncated",t);break}l.target[d]=f}}return n(),r(),o}function vt(t,e,n,r,s){const i=qs(t);if(!i||typeof i!="object")return js(i);const o=St(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=n!==void 0?`${e}.${n}`:e,l=Array.isArray(i)?[]:{};return s.set(a,c),r.push({source:i,target:l,path:c}),l}function js(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 St(t){try{if(t instanceof Event)return Hs(t);if(t instanceof RegExp)return`[RegExp] ${t.toString()}`;const n=Object.prototype.toString.call(t).match(/\[object (.*)\]/);if(n&&n[1])return`[${n[1]}]`}catch{}return"[Unserializable]"}function Hs(t){return{type:t.type,isTrusted:t.isTrusted,currentTarget:t.currentTarget?St(t.currentTarget):null,target:t.target?St(t.target):null}}function qs(t){const e=t;if(e&&typeof e.toJSON=="function")try{return e.toJSON()}catch{}return t}function wt(t,e,n){E.warn(`The data provided has been ${e} as it is over the limit of ${t} characters:`,n)}const _n="No stack, consider using an instance of Error";function bn({stackTrace:t,originalError:e,handlingStack:n,componentStack:r,startClocks:s,nonErrorPrefix:i,source:o,handling:a}){const c=q(e),l=Ws(t,c,i,e),u=Ys(c,t)?ee(t):_n,d=c?wn(e,o):void 0,f=t?t.name:void 0,p=vn(e),h=Sn(e);return{startClocks:s,source:o,handling:a,handlingStack:n,componentStack:r,originalError:e,type:f,message:l,stack:u,causes:d,fingerprint:p,context:h}}function Ws(t,e,n,r){return t!=null&&t.message&&(t!=null&&t.name)?t.message:e?"Empty message":`${n} ${Q(N(r))}`}function Ys(t,e){return e===void 0?!1:t?!0:e.stack.length>0&&(e.stack.length>1||e.stack[0].url!==void 0)}function vn(t){return q(t)&&"dd_fingerprint"in t?String(t.dd_fingerprint):void 0}function Sn(t){if(t!==null&&typeof t=="object"&&"dd_context"in t)return t.dd_context}function Ks(t){var e;return(e=/@ (.+)/.exec(t))===null||e===void 0?void 0:e[1]}function q(t){return t instanceof Error||Object.prototype.toString.call(t)==="[object Error]"}function wn(t,e){let n=t;const r=[];for(;q(n==null?void 0:n.cause)&&r.length<10;){const s=B(n.cause);r.push({message:n.cause.message,source:e,type:s==null?void 0:s.name,stack:ee(s)}),n=n.cause}return r.length?r:void 0}const D={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function Js(t){const e=(s,i)=>{const o=bn({stackTrace:s,originalError:i,startClocks:G(),nonErrorPrefix:"Uncaught",source:D.SOURCE,handling:"unhandled"});t.notify(o)},{stop:n}=Xs(e),{stop:r}=Zs(e);return{stop:()=>{n(),r()}}}function Xs(t){return te(window,"onerror",({parameters:[e,n,r,s,i]})=>{let o;q(i)?o=B(i):o=Bs(e,n,r,s),t(o,i??e)})}function Zs(t){return te(window,"onunhandledrejection",({parameters:[e]})=>{const n=e.reason||"Empty reason",r=B(n);t(r,n)})}function Qs(t){const e={version:"6.5.0",onReady(n){n()},...t};return Object.defineProperty(e,"_setDebug",{get(){return wr},enumerable:!1}),e}function ei(t,e,n){const r=t[e];r&&!r.q&&r.version&&E.warn("SDK is loaded more than once. This is unsupported and might have unexpected behavior."),t[e]=n,r&&r.q&&r.q.forEach(s=>Ht(s,"onReady callback threw an error:")())}function Tn(t,e){e.silentMultipleInit||E.error(`${t} is already initialized.`)}function ne(t,e,n,r,s){return Tt(t,e,[n],r,s)}function Tt(t,e,n,r,{once:s,capture:i,passive:o}={}){const a=v(f=>{!f.isTrusted&&!f.__ddIsTrusted&&!t.allowUntrustedEvents||(s&&d(),r(f))}),c=o?{capture:i,passive:o}:i,l=window.EventTarget&&e instanceof EventTarget?window.EventTarget.prototype:e,u=se(l,"addEventListener");n.forEach(f=>u.call(e,f,a,c));function d(){const f=se(l,"removeEventListener");n.forEach(p=>f.call(e,p,a,c))}return{stop:d}}const qe={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function ti(t,e){const n=[];e.includes(qe.cspViolation)&&n.push(ri(t));const r=e.filter(s=>s!==qe.cspViolation);return r.length&&n.push(ni(r)),Qt(...n)}function ni(t){return new R(e=>{if(!window.ReportingObserver)return;const n=v((s,i)=>s.forEach(o=>e.notify(si(o)))),r=new window.ReportingObserver(n,{types:t,buffered:!0});return r.observe(),()=>{r.disconnect()}})}function ri(t){return new R(e=>{const{stop:n}=ne(t,document,"securitypolicyviolation",r=>{e.notify(ii(r))});return n})}function si(t){const{type:e,body:n}=t;return xn({type:n.id,message:`${e}: ${n.message}`,originalError:t,stack:En(n.id,n.message,n.sourceFile,n.lineNumber,n.columnNumber)})}function ii(t){const e=`'${t.blockedURI}' blocked by '${t.effectiveDirective}' directive`;return xn({type:t.effectiveDirective,message:`${qe.cspViolation}: ${e}`,originalError:t,csp:{disposition:t.disposition},stack:En(t.effectiveDirective,t.originalPolicy?`${e} of the policy "${kr(t.originalPolicy,100,"...")}"`:"no policy",t.sourceFile,t.lineNumber,t.columnNumber)})}function xn(t){return{startClocks:G(),source:D.REPORT,handling:"unhandled",...t}}function En(t,e,n,r,s){return n?ee({name:t,message:e,stack:[{func:"?",url:n,line:r??void 0,column:s??void 0}]}):void 0}function Cn(t,e){const n=window.__ddBrowserSdkExtensionCallback;n&&n({type:t,payload:e})}function kn(t){return t===null?"null":Array.isArray(t)?"array":typeof t}function We(t,e,n=oi()){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(n.hasAlreadyBeenSeen(e))return;if(Array.isArray(e)){const s=Array.isArray(t)?t:[];for(let i=0;i<e.length;++i)s[i]=We(s[i],e[i],n);return s}const r=kn(t)==="object"?t:{};for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(r[s]=We(r[s],e[s],n));return r}function Rn(t){return We(void 0,t)}function le(...t){let e;for(const n of t)n!=null&&(e=We(e,n));return e}function oi(){if(typeof WeakSet<"u"){const e=new WeakSet;return{hasAlreadyBeenSeen(n){const r=e.has(n);return r||e.add(n),r}}}const t=[];return{hasAlreadyBeenSeen(e){const n=t.indexOf(e)>=0;return n||t.push(e),n}}}function ai(){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 ci(t){const e=new Set;return t.forEach(n=>e.add(n)),Array.from(e)}function Un(t,e){const n=t.indexOf(e);n>=0&&t.splice(n,1)}const li=500;function An(){const t=[];return{add:s=>{t.push(s)>li&&t.splice(0,1)},remove:s=>{Un(t,s)},drain:s=>{t.forEach(i=>i(s)),t.length=0}}}const re={log:"log",configuration:"configuration",usage:"usage"},ui=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],di=[cs];let Dn=An(),ue=t=>{Dn.add(()=>ue(t))};function fi(t,e){let n;const r=new R,s=new Set,i=!di.includes(e.site)&&Fe(e.telemetrySampleRate),o={[re.log]:i,[re.configuration]:i&&Fe(e.telemetryConfigurationSampleRate),[re.usage]:i&&Fe(e.telemetryUsageSampleRate)},a=hi();ue=l=>{const u=Q(l);if(o[l.type]&&s.size<e.maxTelemetryEventsPerPage&&!s.has(u)){const d=c(t,l,a);r.notify(d),Cn("telemetry",d),s.add(u)}},Sr(On);function c(l,u,d){return le({type:"telemetry",date:z(),service:l,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:le(u,{runtime_env:d,connectivity:ai(),sdk_setup:"npm"}),experimental_features:Array.from(ks())},n!==void 0?n():{})}return{setContextProvider:l=>{n=l},observable:r,enabled:i}}function hi(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function pi(){Dn.drain()}function mi(t){return t.site===os}function Fn(t,e){at(x.debug,t,e),ue({type:re.log,message:t,status:"debug",...e})}function On(t,e){ue({type:re.log,status:"error",..._i(t),...e})}function gi(t){ue({type:re.configuration,configuration:t})}function yi(t){ue({type:re.usage,usage:t})}function _i(t){if(q(t)){const e=B(t);return{error:{kind:e.name,stack:ee(bi(e))},message:e.message}}return{error:{stack:_n},message:`Uncaught ${Q(t)}`}}function bi(t){return t.stack=t.stack.filter(e=>!e.url||ui.some(n=>e.url.startsWith(n))),t}const Ee=1/0,vi=K;let Ce=null;const Ye=new Set;function Si(){Ye.forEach(t=>t())}function wi({expireDelay:t,maxEntries:e}){let n=[];const r=[];Ce||(Ce=ct(()=>Si(),vi));const s=()=>{const p=Oe()-t;for(;n.length>0&&n[n.length-1].endTime<p;){const h=n.pop();h&&r.push(h.startTime)}};Ye.add(s);function i(p,h){const m={value:p,startTime:h,endTime:Ee,remove:()=>{Un(n,m)},close:g=>{m.endTime=g}};return e&&n.length>=e&&n.pop(),n.unshift(m),m}function o(p=Ee,h={returnInactive:!1}){for(const m of n)if(m.startTime<=p){if(h.returnInactive||p<=m.endTime)return m.value;break}}function a(p){const h=n[0];h&&h.endTime===Ee&&h.close(p)}function c(p=Ee,h=0){const m=yr(p,h);return n.filter(g=>g.startTime<=m&&p<=g.endTime).map(g=>g.value)}function l(){return n.map(({startTime:p,endTime:h,value:m})=>({startTime:p,endTime:h===Ee?"Infinity":h,value:m}))}function u(){return r}function d(){n=[]}function f(){Ye.delete(s),Ye.size===0&&Ce&&(Zt(Ce),Ce=null)}return{add:i,find:o,closeActive:a,findAll:c,reset:d,stop:f,getAllEntries:l,getDeletedEntries:u}}const Ti=K,xi=ft;function Ei(t,e,n,r){const s=new R,i=new R,o=ns(t.sessionStoreStrategyType,t,e,n),a=wi({expireDelay:xi});o.renewObservable.subscribe(()=>{a.add(c(),Oe()),s.notify()}),o.expireObservable.subscribe(()=>{i.notify(),a.closeActive(Oe())}),o.expandOrRenewSession(),a.add(c(),mr().relative),r.observable.subscribe(()=>{r.isGranted()?o.expandOrRenewSession():o.expire()}),Ci(t,()=>{r.isGranted()&&o.expandOrRenewSession()}),ki(t,()=>o.expandSession()),Ri(t,()=>o.restartSession());function c(){return{id:o.getSession().id,trackingType:o.getSession()[e],isReplayForced:!!o.getSession().forcedReplay,anonymousId:o.getSession().anonymousId}}return{findSession:(l,u)=>a.find(l,u),renewObservable:s,expireObservable:i,sessionStateUpdateObservable:o.sessionStateUpdateObservable,expire:o.expire,updateSessionState:o.updateSessionState}}function Ci(t,e){Tt(t,window,["click","touchstart","keydown","scroll"],e,{capture:!0,passive:!0})}function ki(t,e){const n=()=>{document.visibilityState==="visible"&&e()};ne(t,document,"visibilitychange",n),ct(n,Ti)}function Ri(t,e){ne(t,window,"resume",e,{capture:!0})}function Ln(t){return t>=500}function Ui(t){try{return t.clone()}catch{return}}const Ai=80*M,Di=32,In=3*Yt,Fi=K,Pn=ge;function Mn(t,e,n,r,s){e.transportStatus===0&&e.queuedPayloads.size()===0&&e.bandwidthMonitor.canHandle(t)?Nn(t,e,n,{onSuccess:()=>$n(0,e,n,r,s),onFailure:()=>{e.queuedPayloads.enqueue(t),Bn(e,n,r,s)}}):e.queuedPayloads.enqueue(t)}function Bn(t,e,n,r){t.transportStatus===2&&ve(()=>{const s=t.queuedPayloads.first();Nn(s,t,e,{onSuccess:()=>{t.queuedPayloads.dequeue(),t.currentBackoffTime=Pn,$n(1,t,e,n,r)},onFailure:()=>{t.currentBackoffTime=Math.min(Fi,t.currentBackoffTime*2),Bn(t,e,n,r)}})},t.currentBackoffTime)}function Nn(t,e,n,{onSuccess:r,onFailure:s}){e.bandwidthMonitor.add(t),n(t,i=>{e.bandwidthMonitor.remove(t),Oi(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,r())})}function $n(t,e,n,r,s){t===0&&e.queuedPayloads.isFull()&&!e.queueFullReported&&(s({message:`Reached max ${r} events size queued for upload: ${In/Yt}MiB`,source:D.AGENT,startClocks:G()}),e.queueFullReported=!0);const i=e.queuedPayloads;for(e.queuedPayloads=zn();i.size()>0;)Mn(i.dequeue(),e,n,r,s)}function Oi(t){return t.type!=="opaque"&&(t.status===0&&!navigator.onLine||t.status===408||t.status===429||Ln(t.status))}function Li(){return{transportStatus:0,currentBackoffTime:Pn,bandwidthMonitor:Ii(),queuedPayloads:zn(),queueFullReported:!1}}function zn(){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>=In}}}function Ii(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(t){return this.ongoingRequestCount===0||this.ongoingByteCount+t.bytesCount<=Ai&&this.ongoingRequestCount<Di},add(t){this.ongoingRequestCount+=1,this.ongoingByteCount+=t.bytesCount},remove(t){this.ongoingRequestCount-=1,this.ongoingByteCount-=t.bytesCount}}}function Pi(t,e,n){const r=Li(),s=(i,o)=>Ni(t,e,i,o);return{send:i=>{Mn(i,r,s,t.trackType,n)},sendOnExit:i=>{Mi(t,e,i)}}}function Mi(t,e,n){if(!!navigator.sendBeacon&&n.bytesCount<e)try{const i=t.build("beacon",n);if(navigator.sendBeacon(i,n.data))return}catch(i){Bi(i)}const s=t.build("xhr",n);xt(s,n.data)}let Gn=!1;function Bi(t){Gn||(Gn=!0,On(t))}function Ni(t,e,n,r){if($i()&&n.bytesCount<e){const i=t.build("fetch",n);fetch(i,{method:"POST",body:n.data,keepalive:!0,mode:"cors"}).then(v(o=>r==null?void 0:r({status:o.status,type:o.type})),v(()=>{const o=t.build("xhr",n);xt(o,n.data,r)}))}else{const i=t.build("xhr",n);xt(i,n.data,r)}}function $i(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function xt(t,e,n){const r=new XMLHttpRequest;r.open("POST",t,!0),e instanceof Blob&&r.setRequestHeader("Content-Type",e.type),ne({allowUntrustedEvents:!0},r,"loadend",()=>{n==null||n({status:r.status})},{once:!0}),r.send(e)}function Et(){const t=zi();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,n,r){const s=r?{id:r}:void 0;t.send(JSON.stringify({eventType:e,event:n,view:s}))}}}function Ke(t){var e;t===void 0&&(t=(e=V().location)===null||e===void 0?void 0:e.hostname);const n=Et();return!!n&&n.getAllowedWebViewHosts().some(r=>t===r||t.endsWith(`.${r}`))}function zi(){return V().DatadogEventBridge}const Je={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function Gi(t){return new R(e=>{const{stop:n}=Tt(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}),r=ne(t,window,"beforeunload",()=>{e.notify({reason:Je.UNLOADING})}).stop;return()=>{n(),r()}})}function Vi(t){return Me(Je).includes(t)}function ji({encoder:t,request:e,flushController:n,messageBytesLimit:r}){let s={};const i=n.flushObservable.subscribe(d=>u(d));function o(d,f,p){n.notifyBeforeAddMessage(f),p!==void 0?(s[p]=d,n.notifyAfterAddMessage()):t.write(t.isEmpty?d:`
4
- ${d}`,h=>{n.notifyAfterAddMessage(h-f)})}function a(d){return d!==void 0&&s[d]!==void 0}function c(d){const f=s[d];delete s[d];const p=t.estimateEncodedBytesCount(f);n.notifyAfterRemoveMessage(p)}function l(d,f){const p=Q(d),h=t.estimateEncodedBytesCount(p);if(h>=r){E.warn(`Discarded a message whose size was bigger than the maximum allowed size ${r}KB. ${De} ${jt}/#technical-limitations`);return}a(f)&&c(f),o(p,h,f)}function u(d){const f=Me(s).join(`
5
- `);s={};const p=Vi(d.reason),h=p?e.sendOnExit:e.send;if(p&&t.isAsync){const m=t.finishSync();m.outputBytesCount&&h(Vn(m));const g=[m.pendingData,f].filter(Boolean).join(`
1
+ (function(he,pe){typeof exports=="object"&&typeof module<"u"?module.exports=pe():typeof define=="function"&&define.amd?define(pe):(he=typeof globalThis<"u"?globalThis:he||self,he.OTTPlayer=pe())})(this,function(){"use strict";const he=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,pe=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 n=e-this.lastTimestamp;return this.lastTimestamp=e,this.addFrameDuration(n)}calculateAverage(){if(this.frameDurations.length===0)return 0;const n=this.frameDurations.reduce((o,a)=>o+a,0)/this.frameDurations.length,r=this.frameDurations.filter(o=>Math.abs(o-n)<=n*.2);return r.reduce((o,a)=>o+a,0)/r.length||n}getFPS(){const e=this.calculateAverage();if(e===0)return 0;const n=1/e;return pe(n)}getPerciseFPS(){const e=this.calculateAverage();return e===0?0:1/e}}const U=class U{constructor(e,n,r,i,s){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 l=this.h,u=this.m,d=this.s,f=this.f,p=this.field;const h=l*60+u,g=(h-Math.floor(h/10))*c;return l*(a*3600)+u*(a*60)+d*a+(f*2+p)-g},this.addSeconds=o=>{let a=this.copy();return a.s+=o,a.s>=60&&(a.s=0,a.m++,a.m>=60&&(a.m=0,a.h++)),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=n||0,this.s=r||0,this.f=i||0,this.field=s||0}static compare(e,n){return e.h!==n.h?e.h<n.h?-1:1:e.m!==n.m?e.m<n.m?-1:1:e.s!==n.s?e.s<n.s?-1:1:e.f!==n.f?e.f<n.f?-1:1:e.field!==n.field?e.field<n.field?-1:1:0}static generateTimecodeRange(e,n,r){const i=[];let s=e;for(;U.compare(s,n)<=0;)i.push(s),s=s.addSeconds(r);return i}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(e){return this.toFrames(e)*1e3/e}};U.calculateCurrentTimeCode=e=>{var d;if(!e.video||!e.clocker||!e.gameParams)throw new Error("OTTPlayer is not initialized");const n=e.video,r=e.clocker,i=r.videoFPScalculator.getFPS(),a=(n.currentTime-r.syncPoint.playerTime)%(60*60*24)*i+r.syncPoint.frame;if(a===0||i===0)throw new Error("Current frame is 0 or fps is 0");const c=U.calculateCurrentOffset(a,(d=e.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),U.fromFrames(l,i)},U.calculateCurrentOffset=(e,n)=>{for(let r=1;r<n.length;r++)if(e<n[r].frame)return n[r-1].offset;return n[n.length-1].offset},U.fromFrames=(e,n)=>{let r=60,i=0;Math.floor(n)==60?(r=60,i=0):Math.floor(n)==59?(r=60,i=4):Math.floor(n)==30?(r=30,i=0):Math.floor(n)==29&&(r=30,i=2);let s=Math.floor(n*60),o=Math.floor(n*60*10),a=o*6,c=e,l=Math.floor(c/a);c-=l*a;let u=Math.floor(c/o);c-=u*o,c>=r*60&&(c+=i*(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 p=c;d+=u*10;let h=0;return h=p%2,p=Math.floor(p/2),new U(l,d,f,p,h)},U.toStr=e=>{const n="_";let r=("0"+e.h).slice(-2)+n+("0"+e.m).slice(-2)+n+("0"+e.s).slice(-2)+n+("0"+e.f).slice(-2);return e.field&&(r+="_1"),r},U.fromStr=e=>{const r=e.split("_").map(Number);if(r.length==4){const[i,s,o,a]=r;return new U(i,s,o,a,0)}else if(r.length==5){const[i,s,o,a,c]=r;return new U(i,s,o,a,c)}else throw new Error("Invalid timecode format: "+e)},U.fromMetadata=e=>{const n=/^(\d{2}):(\d{2}):(\d{2}):(\d{2})(?:\.(\d))?$/,r=e.timecode.match(n);if(!r)throw new Error("Invalid timecode format: "+e.timecode);const[,i,s,o,a,c]=r,l=Number(i),u=Number(s),d=Number(o),f=Number(a),p=c?Number(c):0;return new U(l,u,d,f,p)};let F=U;const er=async t=>{let e;typeof document>"u"?e=new URL(self.location.href):e=new URL(document.location.href);const n=e.searchParams.get("config");if(n){const i=await(await fetch(n)).json();Object.assign(t,i)}},I=(t,e)=>!t.debug||!t.debug.on?!1:t.debug[`log${e}`];class tr{constructor(e){this.last10=[],this.errorsInProgress=[],this.lastFrameTC=null,this.fps=e}setFPS(e){this.fps=e}timecodeRecieved(e){if(!e)return;const n=F.fromStr(e);if(this.last10.push(n),this.last10.length>10&&this.last10.shift(),this.lastFrameTC){const r=this.incrementInterlaced(this.lastFrameTC);F.compare(n,r)!==0&&(console.warn("Timecode sequence is invalid! Detected at:",e),this.errorsInProgress.push({preTCs:[...this.last10],postTCs:[],framesAfter:0,printed:!1}))}for(const r of this.errorsInProgress)r.printed||(r.postTCs.push(n),r.framesAfter++);for(const r of this.errorsInProgress)if(!r.printed&&r.framesAfter>=10){console.error("Full 20-frame sequence around error:");const i=[...r.preTCs,...r.postTCs];console.error(i.map(s=>F.toStr(s))),r.printed=!0}this.lastFrameTC=n}incrementInterlaced(e){const n=e.copy();return n.field===0?(n.field=1,n):(n.field=0,n.f++,n.f>=30&&(n.f=0,n.s++,n.s>=60&&(n.s=0,n.m++,n.m>=60&&(n.m=0,n.h++))),n)}}class nr{constructor(e,n){this.click=async r=>{const i=this.video.getBoundingClientRect(),s=(r.clientX-i.left)/i.width,o=(r.clientY-i.top)/i.height,a={x:s,y:o};this.renderer.postMessage({type:"VIDEO_CLICK",clickData:a})},this.video=e,this.renderer=n,this.renderer.onmessage=r=>{if(r.data.type==="OPEN_URL"){const i=r.data.url;i&&window.open(i,"_blank")}}}}const Pt='(function(){"use strict";const v=(e,t)=>!e.debug||!e.debug.on?!1:e.debug[`log${t}`],T={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},L=console,H={};Object.keys(T).forEach(e=>{H[e]=L[e]});const le="Datadog Browser SDK:",_={debug:H.debug.bind(L,le),log:H.log.bind(L,le),info:H.info.bind(L,le),warn:H.warn.bind(L,le),error:H.error.bind(L,le)},Ve="https://docs.datadoghq.com",Ct=`${Ve}/real_user_monitoring/browser/troubleshooting`,Oe="More details:";function vt(e,t){return(...n)=>{try{return e(...n)}catch(r){_.error(t,r)}}}function Re(e){return e!==0&&Math.random()*100<=e}function Pn(e){return Un(e)&&e>=0&&e<=100}function Un(e){return typeof e=="number"}const de=1e3,z=60*de,At=60*z,Fn=365*(24*At);function fe(){return new Date().getTime()}function N(){return fe()}function Ce(){return performance.now()}function $(){return{relative:Ce(),timeStamp:N()}}function Bn(){return{relative:0,timeStamp:It()}}function Gn(e,t){return t-e}function jn(e,t){return e+t}function Hn(e){return e-It()}let Xe;function It(){return Xe===void 0&&(Xe=performance.timing.navigationStart),Xe}const x=1024,Lt=1024*x,zn=/[^\\u0000-\\u007F]/;function Ze(e){return zn.test(e)?window.TextEncoder!==void 0?new TextEncoder().encode(e).length:new Blob([e]).size:e.length}function Jn(e){return{...e}}function xt(e,t){return Object.keys(e).some(n=>e[n]===t)}function pe(e){return Object.keys(e).length===0}function P(){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 Q(e,t){const n=P();let r;return n.Zone&&typeof n.Zone.__symbol__=="function"&&(r=e[n.Zone.__symbol__(t)]),r||(r=e[t]),r}let ve,kt=!1;function Kn(e){ve=e}function Wn(e){kt=e}function qn(e,t,n){const r=n.value;n.value=function(...o){return(ve?S(r):r).apply(this,o)}}function S(e){return function(){return ge(e,this,arguments)}}function ge(e,t,n){try{return e.apply(t,n)}catch(r){Yn(r)}}function Yn(e){if(Qe(e),ve)try{ve(e)}catch(t){Qe(t)}}function Qe(...e){kt&&_.error("[MONITOR]",...e)}function he(e,t){return Q(P(),"setTimeout")(S(e),t)}function Dt(e){Q(P(),"clearTimeout")(e)}function et(e,t){return Q(P(),"setInterval")(S(e),t)}function Mt(e){Q(P(),"clearInterval")(e)}class w{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 Nt(...e){return new w(t=>{const n=e.map(r=>r.subscribe(o=>t.notify(o)));return()=>n.forEach(r=>r.unsubscribe())})}function $t(e,t,n){let r=!1,o,s;return{throttled:(...i)=>{if(r){o=i;return}e(...i),r=!0,s=he(()=>{o&&e(...o),r=!1,o=void 0},t)},cancel:()=>{Dt(s),r=!1,o=void 0}}}function U(){}function F(e){return e?(parseInt(e,10)^Math.random()*16>>parseInt(e,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,F)}const Ae=/([\\w-]+)\\s*=\\s*([^;]+)/g;function Vn(e,t){for(Ae.lastIndex=0;;){const n=Ae.exec(e);if(n){if(n[1]===t)return n[2]}else break}}function Xn(e){const t=new Map;for(Ae.lastIndex=0;;){const n=Ae.exec(e);if(n)t.set(n[1],n[2]);else break}return t}function Zn(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 Qn(){return er()===0}let Ie;function er(){return Ie??(Ie=tr())}function tr(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 me(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",c=r&&r.domain?`;domain=${r.domain}`:"",a=r&&r.secure?";secure":"",l=r&&r.partitioned?";partitioned":"";document.cookie=`${e}=${t};${s};path=/;samesite=${i}${c}${a}${l}`}function tt(e){return Vn(document.cookie,e)}let nt;function J(e){return nt||(nt=Xn(document.cookie)),nt.get(e)}function Pt(e,t){me(e,"",0,t)}function nr(e){if(document.cookie===void 0||document.cookie===null)return!1;try{const t=`dd_cookie_test_${F()}`,n="test";me(t,n,z,e);const r=tt(t)===n;return Pt(t,e),r}catch(t){return _.error(t),!1}}let rt;function rr(){if(rt===void 0){const e=`dd_site_test_${F()}`,t="test",n=window.location.hostname.split(".");let r=n.pop();for(;n.length&&!tt(e);)r=`${n.pop()}.${r}`,me(e,t,de,{domain:r});Pt(e,{domain:r}),rt=r}return rt}const ee="_dd_s";function Le(e){return Object.values(e)}function or(e){return Object.entries(e)}const ot=4*At,Ut=15*z,sr=Fn,be={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},Ft=/^([a-zA-Z]+)=([a-z0-9-]+)$/,st="&";function ir(e){return!!e&&(e.indexOf(st)!==-1||Ft.test(e))}const cr="1";function K(e,t){const n={isExpired:cr};return t.trackAnonymousUser&&(e!=null&&e.anonymousId?n.anonymousId=e==null?void 0:e.anonymousId:n.anonymousId=F()),n}function xe(e){return pe(e)}function Bt(e){return!xe(e)}function ke(e){return e.isExpired!==void 0||!ar(e)}function ar(e){return(e.created===void 0||fe()-Number(e.created)<ot)&&(e.expire===void 0||fe()<Number(e.expire))}function Gt(e){e.expire=String(fe()+Ut)}function it(e){return or(e).map(([t,n])=>t==="anonymousId"?`aid=${n}`:`${t}=${n}`).join(st)}function jt(e){const t={};return ir(e)&&e.split(st).forEach(n=>{const r=Ft.exec(n);if(r!==null){const[,o,s]=r;o==="aid"?t.anonymousId=s:t[o]=s}}),t}const ur="_dd",lr="_dd_r",dr="_dd_l",fr="rum",pr="logs";function gr(e){if(!J(ee)){const n=J(ur),r=J(lr),o=J(dr),s={};n&&(s.id=n),o&&/^[01]$/.test(o)&&(s[pr]=o),r&&/^[012]$/.test(r)&&(s[fr]=r),Bt(s)&&(Gt(s),e.persistSession(s))}}function Ht(e){const t=yr(e);return nr(t)?{type:be.COOKIE,cookieOptions:t}:void 0}function hr(e,t){const n={isLockEnabled:Qn(),persistSession:mr(t),retrieveSession:Sr,expireSession:r=>br(t,r,e)};return gr(n),n}function mr(e){return t=>{me(ee,it(t),Ut,e)}}function br(e,t,n){const r=K(t,n);me(ee,it(r),n.trackAnonymousUser?sr:ot,e)}function Sr(){const e=tt(ee);return jt(e)}function yr(e){const t={};return t.secure=!!e.useSecureSessionCookie||!!e.usePartitionedCrossSiteSessionCookie,t.crossSite=!!e.usePartitionedCrossSiteSessionCookie,t.partitioned=!!e.usePartitionedCrossSiteSessionCookie,e.trackSessionAcrossSubdomains&&(t.domain=rr()),t}const Er="_dd_test_";function zt(){try{const e=F(),t=`${Er}${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 Tr(e){return{isLockEnabled:!1,persistSession:Jt,retrieveSession:_r,expireSession:t=>wr(t,e)}}function Jt(e){localStorage.setItem(ee,it(e))}function _r(){const e=localStorage.getItem(ee);return jt(e)}function wr(e,t){Jt(K(e,t))}const Or=10,Rr=100,Kt=[];let De;function W(e,t,n=0){var r;const{isLockEnabled:o,persistSession:s,expireSession:i}=t,c=f=>s({...f,lock:l}),a=()=>{const f=t.retrieveSession(),g=f.lock;return f.lock&&delete f.lock,{session:f,lock:g}};if(De||(De=e),e!==De){Kt.push(e);return}if(o&&n>=Rr){Wt(t);return}let l,u=a();if(o){if(u.lock){Me(e,t,n);return}if(l=F(),c(u.session),u=a(),u.lock!==l){Me(e,t,n);return}}let d=e.process(u.session);if(o&&(u=a(),u.lock!==l)){Me(e,t,n);return}if(d&&(ke(d)?i(d):(Gt(d),o?c(d):s(d))),o&&!(d&&ke(d))){if(u=a(),u.lock!==l){Me(e,t,n);return}s(u.session),d=u.session}(r=e.after)===null||r===void 0||r.call(e,d||u.session),Wt(t)}function Me(e,t,n){he(()=>{W(e,t,n+1)},Or)}function Wt(e){De=void 0;const t=Kt.shift();t&&W(t,e)}const qt=de;function Cr(e){switch(e.sessionPersistence){case be.COOKIE:return Ht(e);case be.LOCAL_STORAGE:return zt();case void 0:{let t=Ht(e);return!t&&e.allowFallbackToLocalStorage&&(t=zt()),t}default:_.error(`Invalid session persistence \'${String(e.sessionPersistence)}\'`)}}function vr(e,t,n,r){const o=new w,s=new w,i=new w,c=e.type===be.COOKIE?hr(t,e.cookieOptions):Tr(t),{expireSession:a}=c,l=et(p,qt);let u;E();const{throttled:d,cancel:f}=$t(()=>{W({process:b=>{if(xe(b))return;const ue=y(b);return we(ue),ue},after:b=>{Bt(b)&&!j()&&Mi(b),u=b}},c)},qt);function g(){W({process:b=>j()?y(b):void 0},c)}function p(){W({process:b=>ke(b)?K(b,t):void 0,after:y},c)}function y(b){return ke(b)&&(b=K(b,t)),j()&&(ki(b)?Di():(i.notify({previousState:u,newState:b}),u=b)),b}function E(){W({process:b=>{if(xe(b))return K(b,t)},after:b=>{u=b}},c)}function we(b){if(xe(b))return!1;const{trackingType:ue,isTracked:$i}=r(b[n]);b[n]=ue,delete b.isExpired,$i&&!b.id&&(b.id=F(),b.created=String(fe()))}function j(){return u[n]!==void 0}function ki(b){return u.id!==b.id||u[n]!==b[n]}function Di(){u=K(u,t),s.notify()}function Mi(b){u=b,o.notify()}function Ni(b){W({process:ue=>({...ue,...b}),after:y},c)}return{expandOrRenewSession:d,expandSession:g,getSession:()=>u,renewObservable:o,expireObservable:s,sessionStateUpdateObservable:i,restartSession:E,expire:()=>{f(),a(u),y(K(u,t))},stop:()=>{Mt(l)},updateSessionState:Ni}}const ct={GRANTED:"granted",NOT_GRANTED:"not-granted"};function Ar(e){const t=new w;return{tryToInit(n){e||(e=n)},update(n){e=n,t.notify()},isGranted(){return e===ct.GRANTED},observable:t}}function q(e,t,n){if(typeof e!="object"||e===null)return JSON.stringify(e);const r=te(Object.prototype),o=te(Array.prototype),s=te(Object.getPrototypeOf(e)),i=te(e);try{return JSON.stringify(e,t,n)}catch{return"<error: unable to serialize object>"}finally{r(),o(),s(),i()}}function te(e){const t=e,n=t.toJSON;return n?(delete t.toJSON,()=>{t.toJSON=n}):U}function at(e){return Ir(e,location.href).href}function Ir(e,t){const n=Lr();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)} ${q({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 Yt=URL;let Ne;function Lr(){if(Ne===void 0)try{Ne=new Yt("http://test/path").href==="http://test/path"}catch{Ne=!1}return Ne?Yt:void 0}const xr="datad0g.com",kr="dd0g-gov.com",ne="datadoghq.com",Dr="ddog-gov.com",Mr="pci.browser-intake-datadoghq.com",Nr=["ddsource","ddtags"];function Se(e,t,n){const r=$r(e,t);return{build(o,s){const i=Ur(e,t,n,o,s);return r(i)},urlPrefix:r(""),trackType:t}}function $r(e,t){const n=`/api/v2/${t}`,r=e.proxy;if(typeof r=="string"){const s=at(r);return i=>`${s}?ddforward=${encodeURIComponent(`${n}?${i}`)}`}if(typeof r=="function")return s=>r({path:n,parameters:s});const o=Pr(t,e);return s=>`https://${o}${n}?${s}`}function Pr(e,t){const{site:n=ne,internalAnalyticsSubdomain:r}=t;if(e==="logs"&&t.usePciIntake&&n===ne)return Mr;if(r&&n===ne)return`${r}.${ne}`;if(n===kr)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 c=["sdk_version:6.5.0",`api:${o}`].concat(r);s&&c.push(`retry_count:${s.count}`,`retry_after:${s.lastFailureStatus}`);const a=["ddsource=browser",`ddtags=${encodeURIComponent(c.join(","))}`,`dd-api-key=${e}`,`dd-evp-origin-version=${encodeURIComponent("6.5.0")}`,"dd-evp-origin=browser",`dd-request-id=${F()}`];return i&&a.push(`dd-evp-encoding=${i}`),n==="rum"&&a.push(`batch_time=${N()}`),t&&a.reverse(),a.join("&")}const Fr=200;function Br(e){const{env:t,service:n,version:r,datacenter:o}=e,s=[];return t&&s.push($e("env",t)),n&&s.push($e("service",n)),r&&s.push($e("version",r)),o&&s.push($e("datacenter",o)),s}function $e(e,t){const n=Fr-e.length-1;(t.length>n||Gr(t))&&_.warn(`${e} value doesn\'t meet tag requirements and will be sanitized. ${Oe} ${Ve}/getting_started/tagging/#defining-tags`);const r=t.replace(/,/g,"_");return`${e}:${r}`}function Gr(e){return jr()?new RegExp("[^\\\\p{Ll}\\\\p{Lo}0-9_:./-]","u").test(e):!1}function jr(){try{return new RegExp("[\\\\p{Ll}]","u"),!0}catch{return!1}}function Hr(e){const t=e.site||ne,n=Br(e),r=zr(e,n);return{replica:Jr(e,n),site:t,...r}}function zr(e,t){return{logsEndpointBuilder:Se(e,"logs",t),rumEndpointBuilder:Se(e,"rum",t),sessionReplayEndpointBuilder:Se(e,"replay",t)}}function Jr(e,t){if(!e.replica)return;const n={...e,site:ne,clientToken:e.replica.clientToken},r={logsEndpointBuilder:Se(n,"logs",t),rumEndpointBuilder:Se(n,"rum",t)};return{applicationId:e.replica.applicationId,...r}}function Kr(e){return Nr.every(t=>e.includes(t))}function ut(e,t){return e!=null&&typeof e!="string"?(_.error(`${t} must be defined as a string`),!1):!0}function Wr(e){return e&&typeof e=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(e)?(_.error(`Site should be a valid Datadog site. ${Oe} ${Ve}/getting_started/site/.`),!1):!0}function Pe(e,t){return e!==void 0&&!Pn(e)?(_.error(`${t} Sample Rate should be a number between 0 and 100`),!1):!0}function qr(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(!(!Wr(e.site)||!Pe(e.sessionSampleRate,"Session")||!Pe(e.telemetrySampleRate,"Telemetry")||!Pe(e.telemetryConfigurationSampleRate,"Telemetry Configuration")||!Pe(e.telemetryUsageSampleRate,"Telemetry Usage")||!ut(e.version,"Version")||!ut(e.env,"Env")||!ut(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&&vt(e.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:Cr(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*x,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*de,batchMessagesLimit:50,messageBytesLimit:256*x,...Hr(e)}}}function Yr(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 lt;(function(e){e.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",e.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(lt||(lt={}));const Vt=new Set;function Vr(e){Array.isArray(e)&&Xr(e.filter(t=>xt(lt,t)))}function Xr(e){e.forEach(t=>{Vt.add(t)})}function Zr(){return Vt}const ye="?";function k(e){const t=[];let n=dt(e,"stack");const r=String(e);return n&&n.startsWith(r)&&(n=n.slice(r.length)),n&&n.split(`\n`).forEach(o=>{const s=to(o)||ro(o)||so(o)||ao(o);s&&(!s.func&&s.line&&(s.func=ye),t.push(s))}),{message:dt(e,"message"),name:dt(e,"name"),stack:t}}const Xt="((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\\\w+\\\\.|\\\\/).*?)",re="(?::(\\\\d+))",Qr=new RegExp(`^\\\\s*at (.*?) ?\\\\(${Xt}${re}?${re}?\\\\)?\\\\s*$`,"i"),eo=new RegExp(`\\\\((\\\\S*)${re}${re}\\\\)`);function to(e){const t=Qr.exec(e);if(!t)return;const n=t[2]&&t[2].indexOf("native")===0,r=t[2]&&t[2].indexOf("eval")===0,o=eo.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]||ye,line:t[3]?+t[3]:void 0,url:n?void 0:t[2]}}const no=new RegExp(`^\\\\s*at ?${Xt}${re}?${re}??\\\\s*$`,"i");function ro(e){const t=no.exec(e);if(t)return{args:[],column:t[3]?+t[3]:void 0,func:ye,line:t[2]?+t[2]:void 0,url:t[1]}}const oo=/^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;function so(e){const t=oo.exec(e);if(t)return{args:[],column:t[4]?+t[4]:void 0,func:t[1]||ye,line:+t[3],url:t[2]}}const io=/^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i,co=/(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;function ao(e){const t=io.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]||ye,line:t[4]?+t[4]:void 0,url:t[3]}}function dt(e,t){if(typeof e!="object"||!e||!(t in e))return;const n=e[t];return typeof n=="string"?n:void 0}function uo(e,t,n,r){const o=[{url:t,column:r,line:n}],{name:s,message:i}=fo(e);return{name:s,message:i,stack:o}}const lo=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\\s\\S]*)$/;function fo(e){let t,n;return{}.toString.call(e)==="[object String]"&&([,t,n]=lo.exec(e)),{name:t,message:n}}function Ue(e){const n=new Error(e);n.name="HandlingStack";let r;return ge(()=>{const o=k(n);o.stack=o.stack.slice(2),r=Y(o)}),r}function Y(e){let t=Zt(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 Zt(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=U;else return{stop:U};let s=!1;const i=function(){if(s)return o.apply(this,arguments);const c=Array.from(arguments);let a;ge(n,null,[{target:this,parameters:c,onPostCall:u=>{a=u},handlingStack:r?Ue("instrumented method"):void 0}]);const l=o.apply(this,c);return a&&ge(a,null,[l]),l};return e[t]=i,{stop:()=>{s=!0,e[t]===i&&(e[t]=o)}}}const po=220*x,go="$",ho=3;function D(e,t=po){const n=te(Object.prototype),r=te(Array.prototype),o=[],s=new WeakMap,i=ft(e,go,void 0,o,s),c=JSON.stringify(i);let a=c?c.length:0;if(a>t){gt(t,"discarded",e);return}for(;o.length>0&&a<t;){const l=o.shift();let u=0;if(Array.isArray(l.source))for(let d=0;d<l.source.length;d++){const f=ft(l.source[d],l.path,d,o,s);if(f!==void 0?a+=JSON.stringify(f).length:a+=4,a+=u,u=1,a>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=ft(l.source[d],l.path,d,o,s);if(f!==void 0&&(a+=JSON.stringify(f).length+u+d.length+ho,u=1),a>t){gt(t,"truncated",e);break}l.target[d]=f}}return n(),r(),i}function ft(e,t,n,r,o){const s=So(e);if(!s||typeof s!="object")return mo(s);const i=pt(s);if(i!=="[Object]"&&i!=="[Array]"&&i!=="[Error]")return i;const c=e;if(o.has(c))return`[Reference seen at ${o.get(c)}]`;const a=n!==void 0?`${t}.${n}`:t,l=Array.isArray(s)?[]:{};return o.set(c,a),r.push({source:s,target:l,path:a}),l}function mo(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 pt(e){try{if(e instanceof Event)return bo(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 bo(e){return{type:e.type,isTrusted:e.isTrusted,currentTarget:e.currentTarget?pt(e.currentTarget):null,target:e.target?pt(e.target):null}}function So(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 Qt="No stack, consider using an instance of Error";function en({stackTrace:e,originalError:t,handlingStack:n,componentStack:r,startClocks:o,nonErrorPrefix:s,source:i,handling:c}){const a=B(t),l=yo(e,a,s,t),u=Eo(a,e)?Y(e):Qt,d=a?rn(t,i):void 0,f=e?e.name:void 0,g=tn(t),p=nn(t);return{startClocks:o,source:i,handling:c,handlingStack:n,componentStack:r,originalError:t,type:f,message:l,stack:u,causes:d,fingerprint:g,context:p}}function yo(e,t,n,r){return e!=null&&e.message&&(e!=null&&e.name)?e.message:t?"Empty message":`${n} ${q(D(r))}`}function Eo(e,t){return t===void 0?!1:e?!0:t.stack.length>0&&(t.stack.length>1||t.stack[0].url!==void 0)}function tn(e){return B(e)&&"dd_fingerprint"in e?String(e.dd_fingerprint):void 0}function nn(e){if(e!==null&&typeof e=="object"&&"dd_context"in e)return e.dd_context}function To(e){var t;return(t=/@ (.+)/.exec(e))===null||t===void 0?void 0:t[1]}function B(e){return e instanceof Error||Object.prototype.toString.call(e)==="[object Error]"}function rn(e,t){let n=e;const r=[];for(;B(n==null?void 0:n.cause)&&r.length<10;){const o=k(n.cause);r.push({message:n.cause.message,source:t,type:o==null?void 0:o.name,stack:Y(o)}),n=n.cause}return r.length?r:void 0}const A={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function _o(e){const t=(o,s)=>{const i=en({stackTrace:o,originalError:s,startClocks:$(),nonErrorPrefix:"Uncaught",source:A.SOURCE,handling:"unhandled"});e.notify(i)},{stop:n}=wo(t),{stop:r}=Oo(t);return{stop:()=>{n(),r()}}}function wo(e){return V(window,"onerror",({parameters:[t,n,r,o,s]})=>{let i;B(s)?i=k(s):i=uo(t,n,r,o),e(i,s??t)})}function Oo(e){return V(window,"onunhandledrejection",({parameters:[t]})=>{const n=t.reason||"Empty reason",r=k(n);e(r,n)})}function Ro(e){const t={version:"6.5.0",onReady(n){n()},...e};return Object.defineProperty(t,"_setDebug",{get(){return Wn},enumerable:!1}),t}function Co(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=>vt(o,"onReady callback threw an error:")())}function on(e,t){t.silentMultipleInit||_.error(`${e} is already initialized.`)}function X(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 c=S(f=>{!f.isTrusted&&!f.__ddIsTrusted&&!e.allowUntrustedEvents||(o&&d(),r(f))}),a=i?{capture:s,passive:i}:s,l=window.EventTarget&&t instanceof EventTarget?window.EventTarget.prototype:t,u=Q(l,"addEventListener");n.forEach(f=>u.call(t,f,c,a));function d(){const f=Q(l,"removeEventListener");n.forEach(g=>f.call(t,g,c,a))}return{stop:d}}const Fe={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function vo(e,t){const n=[];t.includes(Fe.cspViolation)&&n.push(Io(e));const r=t.filter(o=>o!==Fe.cspViolation);return r.length&&n.push(Ao(r)),Nt(...n)}function Ao(e){return new w(t=>{if(!window.ReportingObserver)return;const n=S((o,s)=>o.forEach(i=>t.notify(Lo(i)))),r=new window.ReportingObserver(n,{types:e,buffered:!0});return r.observe(),()=>{r.disconnect()}})}function Io(e){return new w(t=>{const{stop:n}=X(e,document,"securitypolicyviolation",r=>{t.notify(xo(r))});return n})}function Lo(e){const{type:t,body:n}=e;return sn({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 sn({type:e.effectiveDirective,message:`${Fe.cspViolation}: ${t}`,originalError:e,csp:{disposition:e.disposition},stack:cn(e.effectiveDirective,e.originalPolicy?`${t} of the policy "${Zn(e.originalPolicy,100,"...")}"`:"no policy",e.sourceFile,e.lineNumber,e.columnNumber)})}function sn(e){return{startClocks:$(),source:A.REPORT,handling:"unhandled",...e}}function cn(e,t,n,r,o){return n?Y({name:e,message:t,stack:[{func:"?",url:n,line:r??void 0,column:o??void 0}]}):void 0}function an(e,t){const n=window.__ddBrowserSdkExtensionCallback;n&&n({type:e,payload:t})}function un(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function Be(e,t,n=ko()){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]=Be(o[s],t[s],n);return o}const r=un(e)==="object"?e:{};for(const o in t)Object.prototype.hasOwnProperty.call(t,o)&&(r[o]=Be(r[o],t[o],n));return r}function ln(e){return Be(void 0,e)}function oe(...e){let t;for(const n of e)n!=null&&(t=Be(t,n));return t}function ko(){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 Do(){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 Mo(e){const t=new Set;return e.forEach(n=>t.add(n)),Array.from(t)}function dn(e,t){const n=e.indexOf(t);n>=0&&e.splice(n,1)}const No=500;function fn(){const e=[];return{add:o=>{e.push(o)>No&&e.splice(0,1)},remove:o=>{dn(e,o)},drain:o=>{e.forEach(s=>s(o)),e.length=0}}}const Z={log:"log",configuration:"configuration",usage:"usage"},$o=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],Po=[Dr];let pn=fn(),se=e=>{pn.add(()=>se(e))};function Uo(e,t){let n;const r=new w,o=new Set,s=!Po.includes(t.site)&&Re(t.telemetrySampleRate),i={[Z.log]:s,[Z.configuration]:s&&Re(t.telemetryConfigurationSampleRate),[Z.usage]:s&&Re(t.telemetryUsageSampleRate)},c=Fo();se=l=>{const u=q(l);if(i[l.type]&&o.size<t.maxTelemetryEventsPerPage&&!o.has(u)){const d=a(e,l,c);r.notify(d),an("telemetry",d),o.add(u)}},Kn(hn);function a(l,u,d){return oe({type:"telemetry",date:N(),service:l,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:oe(u,{runtime_env:d,connectivity:Do(),sdk_setup:"npm"}),experimental_features:Array.from(Zr())},n!==void 0?n():{})}return{setContextProvider:l=>{n=l},observable:r,enabled:s}}function Fo(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function Bo(){pn.drain()}function Go(e){return e.site===xr}function gn(e,t){Qe(T.debug,e,t),se({type:Z.log,message:e,status:"debug",...t})}function hn(e,t){se({type:Z.log,status:"error",...zo(e),...t})}function jo(e){se({type:Z.configuration,configuration:e})}function Ho(e){se({type:Z.usage,usage:e})}function zo(e){if(B(e)){const t=k(e);return{error:{kind:t.name,stack:Y(Jo(t))},message:t.message}}return{error:{stack:Qt},message:`Uncaught ${q(e)}`}}function Jo(e){return e.stack=e.stack.filter(t=>!t.url||$o.some(n=>t.url.startsWith(n))),e}const Ee=1/0,Ko=z;let Te=null;const Ge=new Set;function Wo(){Ge.forEach(e=>e())}function qo({expireDelay:e,maxEntries:t}){let n=[];const r=[];Te||(Te=et(()=>Wo(),Ko));const o=()=>{const g=Ce()-e;for(;n.length>0&&n[n.length-1].endTime<g;){const p=n.pop();p&&r.push(p.startTime)}};Ge.add(o);function s(g,p){const y={value:g,startTime:p,endTime:Ee,remove:()=>{dn(n,y)},close:E=>{y.endTime=E}};return t&&n.length>=t&&n.pop(),n.unshift(y),y}function i(g=Ee,p={returnInactive:!1}){for(const y of n)if(y.startTime<=g){if(p.returnInactive||g<=y.endTime)return y.value;break}}function c(g){const p=n[0];p&&p.endTime===Ee&&p.close(g)}function a(g=Ee,p=0){const y=jn(g,p);return n.filter(E=>E.startTime<=y&&g<=E.endTime).map(E=>E.value)}function l(){return n.map(({startTime:g,endTime:p,value:y})=>({startTime:g,endTime:p===Ee?"Infinity":p,value:y}))}function u(){return r}function d(){n=[]}function f(){Ge.delete(o),Ge.size===0&&Te&&(Mt(Te),Te=null)}return{add:s,find:i,closeActive:c,findAll:a,reset:d,stop:f,getAllEntries:l,getDeletedEntries:u}}const Yo=z,Vo=ot;function Xo(e,t,n,r){const o=new w,s=new w,i=vr(e.sessionStoreStrategyType,e,t,n),c=qo({expireDelay:Vo});i.renewObservable.subscribe(()=>{c.add(a(),Ce()),o.notify()}),i.expireObservable.subscribe(()=>{s.notify(),c.closeActive(Ce())}),i.expandOrRenewSession(),c.add(a(),Bn().relative),r.observable.subscribe(()=>{r.isGranted()?i.expandOrRenewSession():i.expire()}),Zo(e,()=>{r.isGranted()&&i.expandOrRenewSession()}),Qo(e,()=>i.expandSession()),es(e,()=>i.restartSession());function a(){return{id:i.getSession().id,trackingType:i.getSession()[t],isReplayForced:!!i.getSession().forcedReplay,anonymousId:i.getSession().anonymousId}}return{findSession:(l,u)=>c.find(l,u),renewObservable:o,expireObservable:s,sessionStateUpdateObservable:i.sessionStateUpdateObservable,expire:i.expire,updateSessionState:i.updateSessionState}}function Zo(e,t){ht(e,window,["click","touchstart","keydown","scroll"],t,{capture:!0,passive:!0})}function Qo(e,t){const n=()=>{document.visibilityState==="visible"&&t()};X(e,document,"visibilitychange",n),et(n,Yo)}function es(e,t){X(e,window,"resume",t,{capture:!0})}function mn(e){return e>=500}function ts(e){try{return e.clone()}catch{return}}const ns=80*x,rs=32,bn=3*Lt,os=z,Sn=de;function yn(e,t,n,r,o){t.transportStatus===0&&t.queuedPayloads.size()===0&&t.bandwidthMonitor.canHandle(e)?Tn(e,t,n,{onSuccess:()=>_n(0,t,n,r,o),onFailure:()=>{t.queuedPayloads.enqueue(e),En(t,n,r,o)}}):t.queuedPayloads.enqueue(e)}function En(e,t,n,r){e.transportStatus===2&&he(()=>{const o=e.queuedPayloads.first();Tn(o,e,t,{onSuccess:()=>{e.queuedPayloads.dequeue(),e.currentBackoffTime=Sn,_n(1,e,t,n,r)},onFailure:()=>{e.currentBackoffTime=Math.min(os,e.currentBackoffTime*2),En(e,t,n,r)}})},e.currentBackoffTime)}function Tn(e,t,n,{onSuccess:r,onFailure:o}){t.bandwidthMonitor.add(e),n(e,s=>{t.bandwidthMonitor.remove(e),ss(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 _n(e,t,n,r,o){e===0&&t.queuedPayloads.isFull()&&!t.queueFullReported&&(o({message:`Reached max ${r} events size queued for upload: ${bn/Lt}MiB`,source:A.AGENT,startClocks:$()}),t.queueFullReported=!0);const s=t.queuedPayloads;for(t.queuedPayloads=wn();s.size()>0;)yn(s.dequeue(),t,n,r,o)}function ss(e){return e.type!=="opaque"&&(e.status===0&&!navigator.onLine||e.status===408||e.status===429||mn(e.status))}function is(){return{transportStatus:0,currentBackoffTime:Sn,bandwidthMonitor:cs(),queuedPayloads:wn(),queueFullReported:!1}}function wn(){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>=bn}}}function cs(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(e){return this.ongoingRequestCount===0||this.ongoingByteCount+e.bytesCount<=ns&&this.ongoingRequestCount<rs},add(e){this.ongoingRequestCount+=1,this.ongoingByteCount+=e.bytesCount},remove(e){this.ongoingRequestCount-=1,this.ongoingByteCount-=e.bytesCount}}}function as(e,t,n){const r=is(),o=(s,i)=>ds(e,t,s,i);return{send:s=>{yn(s,r,o,e.trackType,n)},sendOnExit:s=>{us(e,t,s)}}}function us(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){ls(s)}const o=e.build("xhr",n);mt(o,n.data)}let On=!1;function ls(e){On||(On=!0,hn(e))}function ds(e,t,n,r){if(fs()&&n.bytesCount<t){const s=e.build("fetch",n);fetch(s,{method:"POST",body:n.data,keepalive:!0,mode:"cors"}).then(S(i=>r==null?void 0:r({status:i.status,type:i.type})),S(()=>{const i=e.build("xhr",n);mt(i,n.data,r)}))}else{const s=e.build("xhr",n);mt(s,n.data,r)}}function fs(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function mt(e,t,n){const r=new XMLHttpRequest;r.open("POST",e,!0),t instanceof Blob&&r.setRequestHeader("Content-Type",t.type),X({allowUntrustedEvents:!0},r,"loadend",()=>{n==null||n({status:r.status})},{once:!0}),r.send(t)}function bt(){const e=ps();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 je(e){var t;e===void 0&&(e=(t=P().location)===null||t===void 0?void 0:t.hostname);const n=bt();return!!n&&n.getAllowedWebViewHosts().some(r=>e===r||e.endsWith(`.${r}`))}function ps(){return P().DatadogEventBridge}const He={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function gs(e){return new w(t=>{const{stop:n}=ht(e,window,["visibilitychange","freeze"],o=>{o.type==="visibilitychange"&&document.visibilityState==="hidden"?t.notify({reason:He.HIDDEN}):o.type==="freeze"&&t.notify({reason:He.FROZEN})},{capture:!0}),r=X(e,window,"beforeunload",()=>{t.notify({reason:He.UNLOADING})}).stop;return()=>{n(),r()}})}function hs(e){return Le(He).includes(e)}function ms({encoder:e,request:t,flushController:n,messageBytesLimit:r}){let o={};const s=n.flushObservable.subscribe(d=>u(d));function i(d,f,g){n.notifyBeforeAddMessage(f),g!==void 0?(o[g]=d,n.notifyAfterAddMessage()):e.write(e.isEmpty?d:`\n${d}`,p=>{n.notifyAfterAddMessage(p-f)})}function c(d){return d!==void 0&&o[d]!==void 0}function a(d){const f=o[d];delete o[d];const g=e.estimateEncodedBytesCount(f);n.notifyAfterRemoveMessage(g)}function l(d,f){const g=q(d),p=e.estimateEncodedBytesCount(g);if(p>=r){_.warn(`Discarded a message whose size was bigger than the maximum allowed size ${r}KB. ${Oe} ${Ct}/#technical-limitations`);return}c(f)&&a(f),i(g,p,f)}function u(d){const f=Le(o).join(`\n`);o={};const g=hs(d.reason),p=g?t.sendOnExit:t.send;if(g&&e.isAsync){const y=e.finishSync();y.outputBytesCount&&p(Rn(y));const E=[y.pendingData,f].filter(Boolean).join(`\n`);E&&p({data:E,bytesCount:Ze(E)})}else f&&e.write(e.isEmpty?f:`\n${f}`),e.finish(y=>{p(Rn(y))})}return{flushController:n,add:l,upsert:l,stop:s.unsubscribe}}function Rn(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 bs({messagesLimit:e,bytesLimit:t,durationLimit:n,pageExitObservable:r,sessionExpireObservable:o}){const s=r.subscribe(p=>u(p.reason)),i=o.subscribe(()=>u("session_expire")),c=new w(()=>()=>{s.unsubscribe(),i.unsubscribe()});let a=0,l=0;function u(p){if(l===0)return;const y=l,E=a;l=0,a=0,g(),c.notify({reason:p,messagesCount:y,bytesCount:E})}let d;function f(){d===void 0&&(d=he(()=>{u("duration_limit")},n))}function g(){Dt(d),d=void 0}return{flushObservable:c,get messagesCount(){return l},notifyBeforeAddMessage(p){a+p>=t&&u("bytes_limit"),l+=1,a+=p,f()},notifyAfterAddMessage(p=0){a+=p,l>=e?u("messages_limit"):a>=t&&u("bytes_limit")},notifyAfterRemoveMessage(p){a-=p,l-=1,l===0&&g()}}}function Cn(e,t,n,r,o,s,i=ms){const c=l(e,t),a=n&&l(e,n);function l(u,{endpoint:d,encoder:f}){return i({encoder:f,request:as(d,u.batchBytesLimit,r),flushController:bs({messagesLimit:u.batchMessagesLimit,bytesLimit:u.batchBytesLimit,durationLimit:u.flushTimeout,pageExitObservable:o,sessionExpireObservable:s}),messageBytesLimit:u.messageBytesLimit})}return{flushObservable:c.flushController.flushObservable,add(u,d=!0){c.add(u),a&&d&&a.add(n.transformMessage?n.transformMessage(u):u)},upsert:(u,d)=>{c.upsert(u,d),a&&a.upsert(n.transformMessage?n.transformMessage(u):u,d)},stop:()=>{c.stop(),a&&a.stop()}}}function ze(){let e="",t=0;return{isAsync:!1,get isEmpty(){return!e},write(n,r){const o=Ze(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 Ss{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 ys(e,t,n){let r=0,o=!1;return{isLimitReached(){if(r===0&&he(()=>{r=0},z),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:A.AGENT,startClocks:$()})}finally{o=!1}}return!0}}}let St;const yt=new WeakMap;function Es(e){return St||(St=Ts(e)),St}function Ts(e){return new w(t=>{const{stop:n}=V(XMLHttpRequest.prototype,"open",_s),{stop:r}=V(XMLHttpRequest.prototype,"send",s=>{ws(s,e,t)},{computeHandlingStack:!0}),{stop:o}=V(XMLHttpRequest.prototype,"abort",Os);return()=>{n(),r(),o()}})}function _s({target:e,parameters:[t,n]}){yt.set(e,{state:"open",method:String(t).toUpperCase(),url:at(String(n))})}function ws({target:e,handlingStack:t},n,r){const o=yt.get(e);if(!o)return;const s=o;s.state="start",s.startClocks=$(),s.isAborted=!1,s.xhr=e,s.handlingStack=t;let i=!1;const{stop:c}=V(e,"onreadystatechange",()=>{e.readyState===XMLHttpRequest.DONE&&a()}),a=()=>{if(l(),c(),i)return;i=!0;const u=o;u.state="complete",u.duration=Gn(s.startClocks.timeStamp,N()),u.status=e.status,r.notify(Jn(u))},{stop:l}=X(n,e,"loadend",a);r.notify(s)}function Os({target:e}){const t=yt.get(e);t&&(t.isAborted=!0)}let Et;function vn(){return Et||(Et=Rs()),Et}function Rs(){return new w(e=>{if(!window.fetch)return;const{stop:t}=V(window,"fetch",n=>Cs(n,e),{computeHandlingStack:!0});return t})}function Cs({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 c=i!==void 0?String(i).toUpperCase():"GET",a=o instanceof Request?o.url:at(String(o)),l=$(),u={state:"start",init:s,input:o,method:c,startClocks:l,url:a,handlingStack:n};r.notify(u),e[0]=u.input,e[1]=u.init,t(d=>vs(r,d,u))}function vs(e,t,n){const r=n;function o(s){r.state="resolve",Object.assign(r,s),e.notify(r)}t.then(S(s=>{o({response:s,responseType:s.type,status:s.status,isAborted:!1})}),S(s=>{var i,c;o({status:0,isAborted:((c=(i=r.init)===null||i===void 0?void 0:i.signal)===null||c===void 0?void 0:c.aborted)||s instanceof DOMException&&s.code===DOMException.ABORT_ERR,error:s})}))}let Tt={};function As(e){const t=e.map(n=>(Tt[n]||(Tt[n]=Is(n)),Tt[n]));return Nt(...t)}function Is(e){return new w(t=>{const n=L[e];return L[e]=(...r)=>{n.apply(console,r);const o=Ue("console error");ge(()=>{t.notify(Ls(r,e,o))})},()=>{L[e]=n}})}function Ls(e,t,n){const r=e.map(s=>xs(s)).join(" ");let o;if(t===T.error){const s=e.find(B);o={stack:s?Y(k(s)):void 0,fingerprint:tn(s),causes:s?rn(s,"console"):void 0,startClocks:$(),message:r,source:A.CONSOLE,handling:"handled",handlingStack:n,context:nn(s)}}return{api:t,message:r,error:o,handlingStack:n}}function xs(e){return typeof e=="string"?D(e):B(e)?Zt(k(e)):q(D(e),void 0,2)}function ks(e){const t=un(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 Je(e="",{customerDataTracker:t,propertiesConfig:n={}}={}){let r={};const o=new w,s={getContext:()=>ln(r),setContext:i=>{ks(i)?(r=D(_t(i,n,e)),t==null||t.updateCustomerData(r)):s.clearContext(),o.notify()},setContextProperty:(i,c)=>{r=D(_t({...r,[i]:c},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 Ds="_dd_c",Ms=[];function wt(e,t,n,r){const o=Ns(n,r);Ms.push(X(e,window,"storage",({key:l})=>{o===l&&i()})),t.changeObservable.subscribe(c);const s=oe(a(),t.getContext());pe(s)||t.setContext(s);function i(){t.setContext(a())}function c(){localStorage.setItem(o,JSON.stringify(t.getContext()))}function a(){const l=localStorage.getItem(o);return l?JSON.parse(l):{}}}function Ns(e,t){return`${Ds}_${e}_${t}`}const $s=3*x,Ps=16*x,Us=200;function Fs(e=2){const t=new Map;let n=!1;function r(o=0){if(n||e===0)return;const s=e===2?$s:Ps;let i=o;t.forEach(c=>{i+=c.getBytesCount()}),i>s&&(Bs(s),n=!0)}return{createDetachedTracker:()=>{const o=An(()=>r(o.getBytesCount()));return o},getOrCreateTracker:o=>(t.has(o)||t.set(o,An(r)),t.get(o)),setCompressionStatus:o=>{e===0&&(e=o,r())},getCompressionStatus:()=>e,stop:()=>{t.forEach(o=>o.stop()),t.clear()}}}function An(e){let t=0;const{throttled:n,cancel:r}=$t(s=>{t=Ze(q(s)),e()},Us),o=()=>{r(),t=0};return{updateCustomerData:s=>{pe(s)?o():n(s)},resetCustomerData:o,getBytesCount:()=>t,stop:()=>{r()}}}function Bs(e){_.warn(`Customer data exceeds the recommended ${e/x}KiB threshold. ${Oe} ${Ct}/#customer-data-exceeds-the-recommended-threshold-warning`)}function Gs(e,t,n){const r=e.getReader(),o=[];let s=0;i();function i(){r.read().then(S(a=>{if(a.done){c();return}o.push(a.value),s+=a.value.length,s>n.bytesLimit?c():i()}),S(a=>t(a)))}function c(){r.cancel().catch(U);let a,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})}a=u.slice(0,n.bytesLimit),l=u.length>n.bytesLimit}t(void 0,a,l)}}const js="datadog-synthetics-public-id",Hs="datadog-synthetics-result-id",zs="datadog-synthetics-injects-rum";function In(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||J(zs))}function Js(){const e=window._DATADOG_SYNTHETICS_PUBLIC_ID||J(js);return typeof e=="string"?e:void 0}function Ks(){const e=window._DATADOG_SYNTHETICS_RESULT_ID||J(Hs);return typeof e=="string"?e:void 0}function Ke(e,t,n){const r=n.getHandler(),o=Array.isArray(r)?r:[r];return Ln[e]>=Ln[n.getLevel()]&&o.includes(t)}const m={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},Ln={[m.ok]:0,[m.debug]:1,[m.info]:2,[m.notice]:4,[m.warn]:5,[m.error]:6,[m.critical]:7,[m.alert]:8,[m.emerg]:9};function We(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 Ws=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 c=e.length-1;c>=0;c--)(i=e[c])&&(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 _e={console:"console",http:"http",silent:"silent"},qs=Object.keys(m);let I=class{constructor(t,n,r,o=_e.http,s=m.debug,i={}){this.handleLogStrategy=t,this.handlerType=o,this.level=s,this.contextManager=Je("logger",{customerDataTracker:n}),this.contextManager.setContext(i),r&&this.contextManager.setContextProperty("logger",{name:r})}logImplementation(t,n,r=m.info,o,s){const i=D(n);let c;if(o!=null){const a=en({stackTrace:B(o)?k(o):void 0,originalError:o,nonErrorPrefix:"Provided",source:A.LOGGER,handling:"handled",startClocks:$()});c=oe({error:We(a,{includeMessage:!0})},i)}else c=i;this.handleLogStrategy({message:D(t),context:c,status:r},this,s)}log(t,n,r=m.info,o){let s;Ke(r,_e.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}};Ws([qn],I.prototype,"logImplementation",null),I.prototype.ok=M(m.ok),I.prototype.debug=M(m.debug),I.prototype.info=M(m.info),I.prototype.notice=M(m.notice),I.prototype.warn=M(m.warn),I.prototype.error=M(m.error),I.prototype.critical=M(m.critical),I.prototype.alert=M(m.alert),I.prototype.emerg=M(m.emerg);function M(e){return function(t,n,r){let o;Ke(e,_e.http,this)&&(o=Ue("log")),this.logImplementation(t,n,e,r,o)}}function Ys(e,t,n){return{view:{referrer:document.referrer,url:window.location.href},context:e.getContext(),user:t.getContext(),account:n.getContext()}}const Vs=32*x;function Xs(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=qr(e),n=xn(e.forwardConsoleLogs,Le(T),"Forward Console Logs"),r=xn(e.forwardReports,Le(Fe),"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:Vs,...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:Mo(e)}function Zs(e){const t=Yr(e);return{forward_errors_to_logs:e.forwardErrorsToLogs,forward_console_logs:e.forwardConsoleLogs,forward_reports:e.forwardReports,use_pci_intake:e.usePciIntake,...t}}function Qs(e,t,n){const r=fn();let o,s;const i=t.observable.subscribe(c);function c(){if(!s||!o||!t.isGranted())return;i.unsubscribe();const a=n(o,s);r.drain(a)}return{init(a){if(!a){_.error("Missing configuration");return}if(Vr(a.enableExperimentalFeatures),je()&&(a=ei(a)),o=a,s){on("DD_LOGS",a);return}const l=Xs(a);l&&(s=l,vn().subscribe(U),t.tryToInit(l.trackingConsent),c())},get initConfiguration(){return o},getInternalContext:U,handleLog(a,l,u,d=e(),f=N()){r.add(g=>g.handleLog(a,l,u,d,f))}}}function ei(e){return{...e,clientToken:"empty"}}const Ot="logs";function ti(e){const t=Fs(),n=Je("global context",{customerDataTracker:t.getOrCreateTracker(2)}),r=Je("user",{customerDataTracker:t.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),o=Je("account",{customerDataTracker:t.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),s=Ar();function i(){return Ys(n,r,o)}let c=Qs(i,s,(u,d)=>{u.storeContextsAcrossPages&&(wt(d,n,Ot,2),wt(d,r,Ot,1),wt(d,o,Ot,4));const f=e(u,d,i,s);return c=ni(u,f),f});const a={},l=new I((...u)=>c.handleLog(...u),t.createDetachedTracker());return Ro({logger:l,init:S(u=>c.init(u)),setTrackingConsent:S(u=>{s.update(u),Ho({feature:"set-tracking-consent",tracking_consent:u})}),getGlobalContext:S(()=>n.getContext()),setGlobalContext:S(u=>n.setContext(u)),setGlobalContextProperty:S((u,d)=>n.setContextProperty(u,d)),removeGlobalContextProperty:S(u=>n.removeContextProperty(u)),clearGlobalContext:S(()=>n.clearContext()),createLogger:S((u,d={})=>(a[u]=new I((...f)=>c.handleLog(...f),t.createDetachedTracker(),D(u),d.handler,d.level,D(d.context)),a[u])),getLogger:S(u=>a[u]),getInitConfiguration:S(()=>ln(c.initConfiguration)),getInternalContext:S(u=>c.getInternalContext(u)),setUser:S(r.setContext),getUser:S(r.getContext),setUserProperty:S(r.setContextProperty),removeUserProperty:S(r.removeContextProperty),clearUser:S(r.clearContext),setAccount:S(o.setContext),getAccount:S(o.getContext),setAccountProperty:S(o.setContextProperty),removeAccountProperty:S(o.removeContextProperty),clearAccount:S(o.clearContext)})}function ni(e,t){return{init:n=>{on("DD_LOGS",n)},initConfiguration:e,...t}}const ri="logs";function oi(e,t){const n=Xo(e,ri,r=>ii(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 si(e){const n=kn(e)==="1"?{}:void 0;return{findTrackedSession:()=>n,expireObservable:new w}}function kn(e){return Re(e.sessionSampleRate)?"1":"0"}function ii(e,t){const n=ci(t)?t:kn(e);return{trackingType:n,isTracked:n==="1"}}function ci(e){return e==="0"||e==="1"}let Dn=!1;function qe(e){const t=window;if(In()){const r=n(t.DD_RUM_SYNTHETICS);return!r&&!Dn&&(Dn=!0,gn("Logs sent before RUM is injected by the synthetics worker",{testId:Js(),resultId:Ks()})),r}return n(t.DD_RUM);function n(r){if(r&&r.getInternalContext)return r.getInternalContext(e)}}function ai(e,t,n,r,o){const s=qs.concat(["custom"]),i={};s.forEach(c=>{i[c]=ys(c,t.eventRateLimiterThreshold,o)}),n.subscribe(0,({rawLogsEvent:c,messageContext:a=void 0,savedCommonContext:l=void 0,domainContext:u})=>{var d,f;const g=Hn(c.date),p=e.findTrackedSession(g);if(!e.findTrackedSession(g,{returnInactive:!0}))return;const E=l||r();let we;!pe(E.account)&&E.account.id&&(we=E.account),p&&p.anonymousId&&!E.user.anonymous_id&&(E.user.anonymous_id=p.anonymousId);const j=oe({service:t.service,session_id:p?p.id:void 0,session:p?{id:p.id}:void 0,usr:pe(E.user)?void 0:E.user,account:we,view:E.view},E.context,qe(g),c,a);((d=t.beforeSend)===null||d===void 0?void 0:d.call(t,j,u))===!1||j.origin!==A.AGENT&&((f=i[j.status])!==null&&f!==void 0?f:i.custom).isLimitReached()||n.notify(1,j)})}const ui={[T.log]:m.info,[T.debug]:m.debug,[T.info]:m.info,[T.warn]:m.warn,[T.error]:m.error};function li(e,t){const n=As(e.forwardConsoleLogs).subscribe(r=>{var o;const s={rawLogsEvent:{date:N(),message:r.message,origin:A.CONSOLE,error:r.error&&We(r.error),status:ui[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 di(e,t){const n=vo(e,e.forwardReports).subscribe(r=>{let o=r.message,s;const i=r.originalError.type==="deprecation"?m.warn:m.error;i===m.error?s=We(r):r.stack&&(o+=` Found in ${To(r.stack)}`),t.notify(0,{rawLogsEvent:{date:N(),message:o,origin:A.REPORT,error:s,status:i}})});return{stop:()=>{n.unsubscribe()}}}function fi(e,t){if(!e.forwardErrorsToLogs)return{stop:U};const n=Es(e).subscribe(s=>{s.state==="complete"&&o("xhr",s)}),r=vn().subscribe(s=>{s.state==="resolve"&&o("fetch",s)});function o(s,i){!Kr(i.url)&&(mi(i)||mn(i.status))&&("xhr"in i?pi(i.xhr,e,c):i.response?hi(i.response,e,c):i.error&&gi(i.error,e,c));function c(a){const l={isAborted:i.isAborted,handlingStack:i.handlingStack};t.notify(0,{rawLogsEvent:{message:`${bi(s)} error ${i.method} ${i.url}`,date:i.startClocks.timeStamp,error:{stack:a||"Failed to load",handling:void 0},http:{method:i.method,status_code:i.status,url:i.url},status:m.error,origin:A.NETWORK},domainContext:l})}}return{stop:()=>{n.unsubscribe(),r.unsubscribe()}}}function pi(e,t,n){typeof e.response=="string"?n(Rt(e.response,t)):n(e.response)}function gi(e,t,n){n(Rt(Y(k(e)),t))}function hi(e,t,n){const r=ts(e);!r||!r.body?n():window.TextDecoder?Si(r.body,t.requestErrorResponseLengthLimit,(o,s)=>{n(o?`Unable to retrieve response: ${o}`:s)}):r.text().then(S(o=>n(Rt(o,t))),S(o=>n(`Unable to retrieve response: ${o}`)))}function mi(e){return e.status===0&&e.responseType!=="opaque"}function Rt(e,t){return e.length>t.requestErrorResponseLengthLimit?`${e.substring(0,t.requestErrorResponseLengthLimit)}...`:e}function bi(e){return e==="xhr"?"XHR":"Fetch"}function Si(e,t,n){Gs(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 yi(e,t){if(!e.forwardErrorsToLogs)return{stop:U};const n=new w,{stop:r}=_o(n),o=n.subscribe(s=>{t.notify(0,{rawLogsEvent:{message:s.message,date:s.startClocks.timeStamp,error:We(s),origin:A.SOURCE,status:m.error},messageContext:s.context})});return{stop:()=>{r(),o.unsubscribe()}}}const Ei=Ss;function Ti(e){function t(n,r,o,s,i){const c=oe(r.getContext(),n.context);if(Ke(n.status,_e.console,r)&&wi(n,c),Ke(n.status,_e.http,r)){const a={rawLogsEvent:{date:i||N(),message:n.message,status:n.status,origin:A.LOGGER},messageContext:c,savedCommonContext:s};o&&(a.domainContext={handlingStack:o}),e.notify(0,a)}}return{handleLog:t}}const _i={[m.ok]:T.debug,[m.debug]:T.debug,[m.info]:T.info,[m.notice]:T.info,[m.warn]:T.warn,[m.error]:T.error,[m.critical]:T.error,[m.alert]:T.error,[m.emerg]:T.error};function wi({status:e,message:t},n){H[_i[e]].call(L,t,n)}function Oi(e,t,n,r,o){const s=Cn(e,{endpoint:e.logsEndpointBuilder,encoder:ze()},e.replica&&{endpoint:e.replica.logsEndpointBuilder,encoder:ze()},n,r,o.expireObservable);return t.subscribe(1,i=>{s.add(i)}),s}function Ri(e){const t=bt();e.subscribe(1,n=>{t.send("log",n)})}function Ci(e){return{get:t=>{const n=e.findTrackedSession(t);if(n)return{session_id:n.id}}}}function vi(e){return t=>{e.notify(0,{rawLogsEvent:{message:t.message,date:t.startClocks.timeStamp,origin:A.AGENT,status:m.error}}),gn("Error reported to customer",{"error.message":t.message})}}function Ai(e,t,n,r,o){const s=Uo("browser-logs-sdk",t);s.setContextProvider(()=>{var c,a,l,u,d,f;return{application:{id:(c=qe())===null||c===void 0?void 0:c.application_id},session:{id:(a=o.findTrackedSession())===null||a===void 0?void 0:a.id},view:{id:(u=(l=qe())===null||l===void 0?void 0:l.view)===null||u===void 0?void 0:u.id},action:{id:(f=(d=qe())===null||d===void 0?void 0:d.user_action)===null||f===void 0?void 0:f.id}}});const i=[];if(je()){const c=bt(),a=s.observable.subscribe(l=>c.send("internal_telemetry",l));i.push(()=>a.unsubscribe())}else{const c=Cn(t,{endpoint:t.rumEndpointBuilder,encoder:ze()},t.replica&&{endpoint:t.replica.rumEndpointBuilder,encoder:ze()},n,r,o.expireObservable);i.push(()=>c.stop());const a=s.observable.subscribe(l=>c.add(l,Go(t)));i.push(()=>a.unsubscribe())}return Bo(),jo(Zs(e)),{telemetry:s,stop:()=>{i.forEach(c=>c())}}}function Ii(e,t,n,r){const o=new Ei,s=[];o.subscribe(1,f=>an("logs",f));const i=vi(o),c=gs(t),a=t.sessionStoreStrategyType&&!je()&&!In()?oi(t,r):si(t),{stop:l}=Ai(e,t,i,c,a);s.push(()=>l()),fi(t,o),yi(t,o),li(t,o),di(t,o);const{handleLog:u}=Ti(o);if(ai(a,t,o,n,i),je())Ri(o);else{const{stop:f}=Oi(t,o,i,c,a);s.push(()=>f())}const d=Ci(a);return{handleLog:u,getInternalContext:d.get,stop:()=>{s.forEach(f=>f())}}}const ie=ti(Ii);Co(P(),"DD_LOGS",ie);const O=class O{constructor(t,n,r,o,s){this.copy=()=>new O(this.h,this.m,this.s,this.f,this.field),this.print=()=>{const i=":";let c=("0"+this.h).slice(-2)+i+("0"+this.m).slice(-2)+i+("0"+this.s).slice(-2)+i+("0"+this.f).slice(-2);return c+="."+(this.field?"1":"2"),c},this.toZipTimeCodeString=()=>{const i=this.copy();return i.f=0,i.s=i.s%2===0?i.s:i.s-1,i.field=0,O.toStr(i)},this.toFrames=i=>{let c=60,a=0;Math.floor(i)==60?(c=60,a=0):Math.floor(i)==59?(c=60,a=4):Math.floor(i)==30?(c=30,a=0):Math.floor(i)==29&&(c=30,a=2);let l=this.h,u=this.m,d=this.s,f=this.f,g=this.field;const p=l*60+u,E=(p-Math.floor(p/10))*a;return l*(c*3600)+u*(c*60)+d*c+(f*2+g)-E},this.addSeconds=i=>{let c=this.copy();return c.s+=i,c.s>=60&&(c.s=0,c.m++,c.m>=60&&(c.m=0,c.h++)),c},this.addFrames=(i,c)=>{let a=this.toFrames(c);return a+=i,O.fromFrames(a,c)},this.subtractFrames=(i,c)=>this.addFrames(-i,c),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(;O.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}};O.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(),c=(n.currentTime-r.syncPoint.playerTime)%(60*60*24)*o+r.syncPoint.frame;if(c===0||o===0)throw new Error("Current frame is 0 or fps is 0");const a=O.calculateCurrentOffset(c,(d=t.gameParams)==null?void 0:d.offsets);if(a===void 0)throw new Error("Offset is undefined");let l=Math.floor(c-a);return l<0&&(l+=5178816),l>=5178816&&(l-=5178816),O.fromFrames(l,o)},O.calculateCurrentOffset=(t,n)=>{for(let r=1;r<n.length;r++)if(t<n[r].frame)return n[r-1].offset;return n[n.length-1].offset},O.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),c=i*6,a=t,l=Math.floor(a/c);a-=l*c;let u=Math.floor(a/i);a-=u*i,a>=r*60&&(a+=o*(Math.floor((a-r*60)/s)+1));let d=Math.floor(a/(r*60));a-=d*(r*60);let f=Math.floor(a/r);a-=f*r;let g=a;d+=u*10;let p=0;return p=g%2,g=Math.floor(g/2),new O(l,d,f,g,p)},O.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},O.fromStr=t=>{const r=t.split("_").map(Number);if(r.length==4){const[o,s,i,c]=r;return new O(o,s,i,c,0)}else if(r.length==5){const[o,s,i,c,a]=r;return new O(o,s,i,c,a)}else throw new Error("Invalid timecode format: "+t)},O.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,c,a]=r,l=Number(o),u=Number(s),d=Number(i),f=Number(c),g=a?Number(a):0;return new O(l,u,d,f,g)};let G=O;const h=class h{constructor(t){this.isLoggingOn=t.LOG_TO_DATADOG,this.isLoggingOn&&ie.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!1,sessionSampleRate:100}),h.tracking.dev=`${t.platform}_${t.browserName}`,h.beatHandle||(console.log("[Logger] Starting tracking beat"),h.beatHandle=window.setInterval(h.flushTracking,15e3))}static setMessagePort(t){this.messagePort=t}static getMessagePort(){return this.messagePort}setLoggingOn(t){this.isLoggingOn=t}setAttributes(t){h.processAttributes(t);for(const n in t)ie.logger.setContextProperty(n,t[n])}info(t,n){n&&h.processAttributes(n),this.isLoggingOn&&(ie.logger.info(t,n),console.log("[Logger] Sending info: ",t))}error(t,n){n&&h.processAttributes(n),this.isLoggingOn&&(ie.logger.error(t,n),h.tracking.err_time=Date.now().toFixed(0),h.tracking.err_desc=t,console.log("[Logger] Sending error: ",t))}warn(t,n){n&&h.processAttributes(n),this.isLoggingOn&&(ie.logger.warn(t,n),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){h.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:t})}static info(t,n){h.messagePort.postMessage({type:"LOG",actionType:"INFO",message:t,attributes:n})}static error(t,n){h.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:t,attributes:n})}static warn(t,n){h.messagePort.postMessage({type:"LOG",actionType:"WARN",message:t,attributes:n})}static processAttributes(t){t.player_version&&(h.tracking.sdk=t.player_version),t.media_id&&(h.tracking.gid=t.media_id),t.game_id&&(h.tracking.buc=t.game_id),t.bb_session_id&&(h.tracking.sid=t.bb_session_id,console.log("[Logger] Setting bb_session_id:",h.tracking.sid)),t.last_timecode&&(h.tracking.tc=t.last_timecode,h.lastTimecodeMillis=G.fromStr(t.last_timecode).totalMilliseconds(59.94),h.lastTimecodeMillis&&h.lastZipMillis&&(h.tracking.cache=(h.lastZipMillis-h.lastTimecodeMillis).toFixed(0))),t.last_offset&&(h.tracking.off=t.last_offset),t.last_loading_zip&&(h.tracking.zip=t.last_loading_zip,h.lastZipMillis=G.fromStr(t.last_loading_zip).totalMilliseconds(59.94),h.lastTimecodeMillis&&h.lastZipMillis&&(h.tracking.cache=(h.lastZipMillis-h.lastTimecodeMillis).toFixed(0))),t.last_rendered_frame&&(h.tracking.aug_time=Date.now().toFixed(0)),t.asset&&(h.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("&")}};h.tracking={start:Date.now().toFixed(0),dev:"",sdk:"",mac:"",gid:"",sid:"",off:"",zip:"",aug_time:"",err_time:"",err_desc:"",tc:"",png:"",asset:"",cache:"",buc:""},h.lastTimecodeMillis=0,h.lastZipMillis=0,h.flushTracking=()=>{const t=Date.now().toFixed(0);h.tracking.now=t;const r=`https://dwu3k7rrxk5s3.cloudfront.net/metrics/1.gif?${h.objectToQuery(h.tracking)}`;console.log("[Logger] Flushing tracking data:",r),fetch(r,{method:"GET",mode:"no-cors",keepalive:!0}).catch(()=>{})};let R=h;class Mn{constructor(t,n,r){this.jobsQueue=[],this.processedTimecodes=[],this.downloaderStopped=!1,this.firstDownload=!0,this.updateStreamData=o=>{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.initiateJobs=(o,s,i)=>{if(!this.streamData){R.error("[Downloader] Stream data is not available"),this.options&&v(this.options,"Errors")&&console.error("[Downloader] Stream data is not available");return}const c=G.fromStr(this.streamData.timeCode),a=c.addSeconds(o),l=c.addSeconds(s),u=G.generateTimecodeRange(a,l,i);for(const d of u){const f=d.toZipTimeCodeString();this.processedTimecodes.includes(f)||(this.processedTimecodes.push(f),this.addJob(f))}},this.clearOldJobs=o=>{if(!this.streamData){R.error("[Downloader] Stream data is not available"),this.options&&v(this.options,"Errors")&&console.error("[Downloader] Stream data is not available");return}const i=G.fromStr(this.streamData.timeCode).totalSeconds()-o;this.processedTimecodes=this.processedTimecodes.filter(c=>G.fromStr(c).totalSeconds()>i)},this.clearAllJobs=()=>{this.jobsQueue=[],this.currentJob=void 0,this.processedTimecodes=[]},this.addJob=o=>{if(this.jobsQueue.some(s=>s===o)){this.options&&v(this.options,"Downloader")&&console.log(`[Downloader] Job already exists for timeCode=${o}`);return}this.jobsQueue.push(o),this.startNextJob()},this.startNextJob=()=>{!this.currentJob&&this.jobsQueue.length>0&&(this.currentJob=this.jobsQueue.shift(),this.options&&v(this.options,"Downloader")&&console.log(`[Downloader] Starting job timeCode=${this.currentJob}`),this.downloadZip(this.currentJob))},this.jobDone=()=>{this.currentJob=void 0,this.startNextJob()},this.downloadZip=async o=>{if(!this.streamData){R.error("[Downloader] Stream data is not available"),this.options&&v(this.options,"Errors")&&console.error("[Downloader] Stream data is not available");return}this.firstDownload&&(this.firstDownload=!1,R.info("didStartAugmentationDownload",{timestamp:o}));const{fps:s,cloudFrontURL:i,bucketName:c}=this.streamData;try{this.options&&v(this.options,"Downloader")&&console.log(`[Downloader] Fetching zip for timeCode=${o}`);const{arrayBuffer:a,ottActions:l}=await this.fetchMetadata(i,c,s,o);if(this.downloaderStopped)return;if(this.postArrayBufferToDecoder(o,a),R.setAttributes({last_loading_zip:o}),!this.ottActions||this.ottActions.toggle.web!==l.toggle.web||l.toggle[this.streamData.customerId]!==void 0&&(this.ottActions.toggle[this.streamData.customerId]===void 0||this.ottActions.toggle[this.streamData.customerId]!==l.toggle[this.streamData.customerId])||l.toggle[this.streamData.customerId]===void 0&&this.ottActions.toggle[this.streamData.customerId]!==void 0){const d=l.toggle[this.streamData.customerId]!==void 0?l.toggle[this.streamData.customerId]&&l.toggle.web:l.toggle.web;this.ottActions&&R.info("didToggleGlobalAugmentationDrawing",{isEnabled:d}),this.ottActions=l,this.postOTTActionsToRenderer(l)}}catch(a){R.error("[Downloader] Error fetching zip",a),this.options&&v(this.options,"Errors")&&console.error("[Downloader] Error fetching zip:",a)}this.jobDone()},this.fetchMetadata=async(o,s,i,c)=>{const l=`${`${o}/${s}`}/manifests/59.94/${c}.zip`;this.options&&v(this.options,"Fetcher")&&console.log(`[Fetcher] Fetching metadata from ${l}`);const u=performance.now(),d=await fetch(l),f=await d.arrayBuffer(),p=(performance.now()-u)/1e3,y=d.headers.get("x-tgi-ott-actions");let E;if(y?E=JSON.parse(y):E={toggle:{ios:!0,android:!0,web:!0}},!d.ok)throw new Error(`HTTP error! Status: ${d.status}`);return p>1&&R.warn("didFetchZip",{downloadTaskURL:l,downloadTime:p}),{arrayBuffer:f,ottActions:E}},this.stop=()=>{this.downloaderStopped=!0,this.clearAllJobs()},this.postArrayBufferToDecoder=t,this.postOTTActionsToRenderer=n,this.options=r}}let ce=null,ae=null,Ye,C;self.onmessage=async e=>{const{data:t}=e;if(t.type==="SET_LOGGER_PORT"&&R.setMessagePort(t.port),t.type==="SET_RENDERER_PORT"&&(ce=t.port,ce.onmessage=Li),t.type==="SET_DECODER_PORT"&&(ae=t.port,ae.onmessage=xi),t.type==="SET_OPTIONS"&&(C=t.options,R.setMessagePort(self),Ye=new Mn(Nn,$n,C)),t.type==="VIDEO_SEEKED"){if(!C)return;Ye.stop(),Ye=new Mn(Nn,$n,C)}};async function Li(e){const{data:t}=e;self.postMessage(t),t.type==="DOWNLOADER_INPUT"&&Ye.updateStreamData(t.streamData)}function Nn(e,t){if(!ae)return;C&&v(C,"Downloader")&&console.log(`[DownloaderWorker] Posting an ArrayBuffer to Decoder, timeCode=${e}`);const n={type:"DECODER_INPUT",timeCode:e,arrayBuffer:t};ae==null||ae.postMessage(n,{transfer:[t]})}function $n(e){if(!ce)return;C&&v(C,"Downloader")&&console.log(`[DownloaderWorker] Posting OTTActions to Renderer, toggle=${e.toggle}`);const t={type:"OTT_ACTIONS",ottActions:e};ce==null||ce.postMessage(t)}function xi(e){C&&v(C,"Downloader")&&console.log("[DownloaderWorker] Received message from Decoder:",e.data)}self.onunhandledrejection=e=>{R.error("[DownloaderWorker] Unhandled rejection",{error:e.reason}),C&&(v(C,"Errors")&&console.error("[DownloaderWorker] Unhandled rejection:",e.reason),e.preventDefault())},self.onerror=e=>{R.error("[DownloaderWorker] Unhandled error",{error:e}),C&&(v(C,"Errors")&&console.error("[DownloaderWorker] Unhandled error:",e),e instanceof Event&&e.preventDefault())}})();\n',Mt=typeof self<"u"&&self.Blob&&new Blob([Pt],{type:"text/javascript;charset=utf-8"});function rr(t){let e;try{if(e=Mt&&(self.URL||self.webkitURL).createObjectURL(Mt),!e)throw"";const n=new Worker(e,{name:t==null?void 0:t.name});return n.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),n}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Pt),{name:t==null?void 0:t.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}const Bt='(function(){"use strict";const R=(a,n)=>!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,U){console.debug===void 0&&(console.debug=console.log),h>=m&&console.debug("["+n.getDurationString(new Date-e,1e3)+"]","["+b+"]",U)},log:function(b,U){this.debug(b.msg)},info:function(b,U){l>=m&&console.info("["+n.getDurationString(new Date-e,1e3)+"]","["+b+"]",U)},warn:function(b,U){r>=m&&console.warn("["+n.getDurationString(new Date-e,1e3)+"]","["+b+"]",U)},error:function(b,U){t>=m&&console.error("["+n.getDurationString(new Date-e,1e3)+"]","["+b+"]",U)}};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 U=m*1e3;return m=Math.floor(m),U-=m*1e3,U=Math.floor(U),(r?"-":"")+y+":"+l(b,2)+":"+l(m,2)+"."+l(U,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],U=0;U<t.length;U++)this.writeType(b,t[U]);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 U=e?n.info:n.debug;this.buffers.length===0?U("MultiBufferStream","No more buffer in memory"):U("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 U=0,w,T,C;for(w=b.readUint8(),C=b.readUint8();C&128;)U=(U<<7)+(C&127),C=b.readUint8();return U=(U<<7)+(C&127),n.debug("MPEG4DescriptorParser","Found "+(h[w]||"Descriptor "+w)+", size "+U+" at position "+b.getPosition()),h[w]?T=new y[h[w]](U):T=new y.Descriptor(U),T.parse(b),T},y.Descriptor=function(b,U){this.tag=b,this.size=U,this.descs=[]},y.Descriptor.prototype.parse=function(b){this.data=b.readUint8Array(this.size)},y.Descriptor.prototype.findDescriptor=function(b){for(var U=0;U<this.descs.length;U++)if(this.descs[U].tag==b)return this.descs[U];return null},y.Descriptor.prototype.parseRemainingDescriptors=function(b){for(var U=b.position;b.position<U+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 U=b.readUint8();this.URL=b.readString(U),this.size-=U+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 U=this.findDescriptor(t);return U?U.oti:0},y.ES_Descriptor.prototype.getAudioConfig=function(b){var U=this.findDescriptor(t);if(!U)return null;var w=U.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 U=e.readUint32(),w=e.readString(4),T=w;if(n.debug("BoxParser","Found box of type \'"+w+"\' and size "+U+" 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(U==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};U=e.readUint64(),m+=8}else if(U===0){if(r)U=r;else if(w!=="mdat")return n.error("BoxParser","Unlimited box size not supported for type: \'"+w+"\'"),l=new s.Box(w,U),{code:s.OK,box:l,size:l.size}}return U!==0&&U<m?(n.error("BoxParser","Box of type "+w+" has an invalid size "+U+" (too small to be a box)"),{code:s.ERR_NOT_ENOUGH_DATA,type:w,size:U,hdr_size:m,start:h}):U!==0&&r&&U>r?(n.error("BoxParser","Box of type \'"+w+"\' has a size "+U+" greater than its container size "+r),{code:s.ERR_NOT_ENOUGH_DATA,type:w,size:U,hdr_size:m,start:h}):U!==0&&h+U>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:U,hdr_size:m,start:h}):t?{code:s.OK,type:w,size:U,hdr_size:m,start:h}:(s[w+"Box"]?l=new s[w+"Box"](U):w!=="uuid"?(n.warn("BoxParser","Unknown box type: \'"+w+"\'"),l=new s.Box(w,U),l.has_unparsed_data=!0):s.UUIDBoxes[b]?l=new s.UUIDBoxes[b](U):(n.warn("BoxParser","Unknown uuid type: \'"+b+"\'"),l=new s.Box(w,U),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 U={};y.push(U),l=e.readUint16(),U.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 U=e.readUint16();b.data=e.readUint8Array(U)}}}),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 g(e,t){this.bad_pixel_row=e,this.bad_pixel_column=t}g.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 g(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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/\'/g,"&#039;")}),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 D=this.held_bits>>this.num_held_bits-A&(1<<A)-1;return this.num_held_bits-=A,D}};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,U=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!=U&&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,U=0;for(e=0;e<=m;++e)for(b=b<<8|l[e],U+=8;U>=5;){var w=b>>U-5&31;r+=y[w],U-=5,b&=(1<<U)-1}U&&(b<<=5-U,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 _=function(){};_.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},_.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 U=m[b];y+=h(e)+" --> "+h(t)+`\\r\n`,y+=U.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 x=function(){};x.prototype.parseSample=function(e){var t,r=new o(e.data.buffer);return t=r.readString(e.data.length),t},x.prototype.parseConfig=function(e){var t,r=new o(e.buffer);return r.readUint32(),t=r.readCString(),t},a.VTTin4Parser=_,a.XMLSubtitlein4Parser=v,a.Textin4Parser=x;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,U;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,U=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,U)+" and offset: "+m),{offset:m,time:e/U}},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 U=s.sampleEntryCodes[b],w=0;w<U.length;w++)if(U.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 U=t.mdia.minf.stbl.boxes.indexOf(b);U!=-1&&(t.mdia.minf.stbl.boxes[U]=null)}},S.initSampleGroups=function(e,t,r,l,h){var m,y,b,U;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(U=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[U]=b),e.sample_groups_info[U]||(e.sample_groups_info[U]=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&&(U=h[y].grouping_type+"/0",b=new w(h[y].grouping_type,0),b.is_fragment=!0,t.sample_groups_info[U]||(t.sample_groups_info[U]=b))}else for(y=0;y<l.length;y++)!l[y].used&&l[y].version>=2&&(U=l[y].grouping_type+"/0",b=new w(l[y].grouping_type,0),e.sample_groups_info[U]||(e.sample_groups_info[U]=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,U,w,T,C,F,A,D,P,K,X,V,N,q,Q,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,U=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,Q=-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 k={};k.number=t,k.track_id=e.tkhd.track_id,k.timescale=e.mdia.mdhd.timescale,k.alreadyRead=0,e.samples[t]=k,k.size=h.sample_sizes[t],e.samples_size+=k.size,t===0?(D=1,A=0,k.chunk_index=D,k.chunk_run_index=A,X=l.samples_per_chunk[A],K=0,A+1<l.first_chunk.length?P=l.first_chunk[A+1]-1:P=1/0):t<X?(k.chunk_index=D,k.chunk_run_index=A):(D++,k.chunk_index=D,K=0,D<=P||(A++,A+1<l.first_chunk.length?P=l.first_chunk[A+1]-1:P=1/0),k.chunk_run_index=A,X+=l.samples_per_chunk[A]),k.description_index=l.sample_description_index[k.chunk_run_index]-1,k.description=U.entries[k.description_index],k.offset=r.chunk_offsets[k.chunk_index-1]+K,K+=k.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,k.dts=e.samples[t-1].dts+e.samples[t-1].duration):k.dts=0,y?(t>=q&&(Q++,q<0&&(q=0),q+=y.sample_counts[Q]),k.cts=e.samples[t].dts+y.sample_offsets[Q]):k.cts=k.dts,b?(t==b.sample_numbers[xe]-1?(k.is_sync=!0,xe++):(k.is_sync=!1,k.degradation_priority=0),w&&w.entries[j].sample_delta+W==t+1&&(k.subsamples=w.entries[j].subsamples,W+=w.entries[j].sample_delta,j++)):k.is_sync=!0,S.process_sdtp(e.mdia.minf.stbl.sdtp,k,k.number),F?k.degradation_priority=F.priority[t]:k.degradation_priority=0,w&&w.entries[j].sample_delta+W==t&&(k.subsamples=w.entries[j].subsamples,W+=w.entries[j].sample_delta),(T.length>0||C.length>0)&&S.setSampleGroupProperties(e,k,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,U,w,T,C,F,A,D;if(this.moov!==void 0){for(;this.lastMoofIndex<this.moofs.length;)if(U=this.moofs[this.lastMoofIndex],this.lastMoofIndex++,U.type=="moof")for(w=U,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]),D=y,P.flags&s.TRUN_FLAGS_FLAGS?D=P.sample_flags[r]:r===0&&P.flags&s.TRUN_FLAGS_FIRST_FLAG&&(D=P.first_sample_flags),A.is_sync=!(D>>16&1),A.is_leading=D>>26&3,A.depends_on=D>>24&3,A.is_depended_on=D>>22&3,A.has_redundancy=D>>20&3,A.degradation_priority=D&65535;var K=!!(T.tfhd.flags&s.TFHD_FLAG_BASE_DATA_OFFSET),X=!!(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:X||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 U=0;U<m.iprp.ipmas.length;U++){var w=m.iprp.ipmas[U];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,g=0,u={},s=new Uint8Array(o),p=s.length-4;c(s,p)!=101010256;)p--;var g=p;g+=4,g+=4;var _=f(s,g);g+=2,f(s,g),g+=2;var v=c(s,g);g+=4;var x=c(s,g);g+=4,g=x;for(var S=0;S<_;S++){c(s,g),g+=4,g+=4,g+=4,g+=4,c(s,g),g+=4;var v=c(s,g);g+=4;var E=c(s,g);g+=4;var e=f(s,g),t=f(s,g+2),r=f(s,g+4);g+=6,g+=8;var l=c(s,g);g+=4,g+=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,g=n.bin.readUint;g(o,d),d+=4,p(o,d),d+=2,p(o,d),d+=2;var _=p(o,d);d+=2,g(o,d),d+=4,g(o,d),d+=4,d+=8;var v=p(o,d);d+=2;var x=p(o,d);d+=2;var S=n.bin.readUTF8(o,d,v);if(d+=v,d+=x,s){f[S]={size:u,csize:c};return}var E=new Uint8Array(o.buffer,d);if(_==0)f[S]=new Uint8Array(E.buffer.slice(d,d+c));else if(_==8){var e=new Uint8Array(u);n.inflateRaw(E,e),f[S]=e}else throw"unknown compression method: "+_},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 g=!n._noNeed(p)&&!d,_=o[p],v=n.crc.crc(_,0,_.length);s[p]={cpr:g,usize:_.length,crc:v,file:g?n.deflateRaw(_):_}}for(var p in s)f+=s[p].file.length+30+46+2*n.bin.sizeUTF8(p);f+=22;var x=new Uint8Array(f),S=0,E=[];for(var p in s){var e=s[p];E.push(S),S=n._writeHeader(x,S,p,e,0)}var t=0,r=S;for(var p in s){var e=s[p];E.push(S),S=n._writeHeader(x,S,p,e,1,E[t++])}var l=S-r;return c(x,S,101010256),S+=4,S+=4,u(x,S,t),S+=2,u(x,S,t),S+=2,c(x,S,l),S+=4,c(x,S,r),S+=4,S+=2,x.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,g=n.bin.writeUshort,_=c.file;p(o,d,u==0?67324752:33639248),d+=4,u==1&&(d+=2),g(o,d,20),d+=2,g(o,d,0),d+=2,g(o,d,c.cpr?8:0),d+=2,p(o,d,0),d+=4,p(o,d,c.crc),d+=4,p(o,d,_.length),d+=4,p(o,d,c.usize),d+=4,g(o,d,n.bin.sizeUTF8(f)),d+=2,g(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(_,d),d+=_.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 g=Math.min(s+5552,p);s<g;)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,g=n.F._goodIndex;n.F._hash;var _=n.F._putsE,v=0,x=f<<3,S=0,E=o.length;if(c==0){for(;v<E;){var e=Math.min(65535,E-v);_(d,x,v+e==E?1:0),x=n.F._copyExact(o,v,e,d,x+8),v+=e}return x>>>3}var t=p.lits,r=p.strt,l=p.prev,h=0,m=0,y=0,b=0,U=0,w=0;for(E>2&&(w=n.F._hash(o,0),r[w]=0),v=0;v<E;v++){if(U=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),x=n.F._writeBlock(v==E-1||S==E?1:0,t,h,b,o,y,v-y,d,x),h=m=b=0,y=v);var C=0;v<E-2&&(C=n.F._bestMatch(o,v,l,U,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=g(e,p.of0);p.lhst[257+A]++;var D=g(F,p.df0);p.dhst[D]++,b+=p.exb[A]+p.dxb[D],t[h]=e<<23|v-S,t[h+1]=F<<16|A<<8|D,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),x=n.F._writeBlock(1,t,h,b,o,y,v-y,d,x),h=0,m=0,h=m=b=0,y=v);x&7;)x++;return x>>>3},n.F._bestMatch=function(o,d,f,c,u,s){var p=d&32767,g=f[p],_=p-g+32768&32767;if(g==p||c!=n.F._hash(o,d-_))return 0;for(var v=0,x=0,S=Math.min(32767,d);_<=S&&--s!=0&&g!=p;){if(v==0||o[d+v]==o[d+v-_]){var E=n.F._howLong(o,d,_);if(E>v){if(v=E,x=_,v>=u)break;_+2<E&&(E=_+2);for(var e=0,t=0;t<E-2;t++){var r=d-_+t+32768&32767,l=f[r],h=r-l+32768&32767;h>e&&(e=h,g=r)}}}p=g,g=f[p],_+=p-g+32768&32767}return v<<16|x},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,x=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 U=(_+3&7?8-(_+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=U<w&&U<T?0:w<T?1:2;if(x(g,_,o),x(g,_+1,F),_+=3,F==0){for(;_&7;)_++;_=n.F._copyExact(u,s,p,g,_)}else{var A,D;if(F==1&&(A=v.fltree,D=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,D=v.dtree,S(g,_,l-257),_+=5,S(g,_,h-1),_+=5,S(g,_,m-4),_+=4;for(var P=0;P<m;P++)S(g,_+P*3,v.itree[(v.ordr[P]<<1)+1]);_+=3*m,_=n.F._codeTiny(y,v.itree,g,_),_=n.F._codeTiny(b,v.itree,g,_)}for(var K=s,X=0;X<f;X+=2){for(var V=d[X],N=V>>>23,q=K+(V&(1<<23)-1);K<q;)_=n.F._writeLit(u[K++],A,g,_);if(N!=0){var Q=d[X+1],xe=Q>>16,j=Q>>8&255,W=Q&255;_=n.F._writeLit(257+j,A,g,_),S(g,_,N-v.of0[j]),_+=v.exb[j],_=n.F._writeLit(W,D,g,_),x(g,_,xe-v.df0[W]),_+=v.dxb[W],K+=N}}_=n.F._writeLit(256,A,g,_)}return _},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),g=0;g<c.length;g+=2)o.ihst[c[g]]++;for(var g=0;g<s.length;g+=2)o.ihst[s[g]]++;for(var _=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,_,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 g=s==16?2:s==17?3:7;s>15&&(n.F._putsE(f,c,p,g),c+=g)}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,g=c==0?-1:o[c-1];if(u==0&&s==u&&p==u){for(var _=c+5;_+2<f&&o[_+2]==u;)_+=2;var v=Math.min(_+1-c>>>1,138);v<11?d.push(17,v-3):d.push(18,v-11),c+=v*2-2}else if(u==g&&s==u&&p==u){for(var _=c+5;_+2<f&&o[_+2]==u;)_+=2;var v=Math.min(_+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 g=c.length,_=c.slice(0);if(g==0)return 0;if(g==1){var v=c[0].lit,_=v==0?1:0;return d[(v<<1)+1]=1,d[(_<<1)+1]=1,1}c.sort(function(l,h){return l.f-h.f});var x=c[0],S=c[1],E=0,e=1,t=2;for(c[0]={lit:-1,f:x.f+S.f,l:x,r:S,d:0};e!=g-1;)E!=e&&(t==g||c[E].f<c[t].f)?x=c[E++]:x=c[t++],E!=e&&(t==g||c[E].f<c[t].f)?S=c[E++]:S=c[t++],c[e++]={lit:-1,f:x.f+S.f,l:x,r:S};var r=n.F.setDepth(c[e-1],0);for(r>f&&(n.F.restrictDepth(_,f,r),r=f),p=0;p<g;p++)d[(_[p].lit<<1)+1]=_[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 _.d==g.d?g.f-_.f:_.d-g.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,g=c.makeCodes,_=c.codes2map,v=c._get17,x=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,U,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&&(U=x.flmap,w=x.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)x.itree[F]=0,x.itree[F+1]=0;for(var A=1,F=0;F<l;F++){var D=s(o,b+F*3,3);x.itree[(x.ordr[F]<<1)+1]=D,D>A&&(A=D)}b+=3*l,g(x.itree,A),_(x.itree,A,x.imap),U=x.lmap,w=x.dmap,b=p(x.imap,(1<<A)-1,t+r,o,b,x.ttree);var P=c._copyOut(x.ttree,0,t,x.ltree);h=(1<<P)-1;var K=c._copyOut(x.ttree,t,r,x.dtree);m=(1<<K)-1,g(x.ltree,P),_(x.ltree,P,U),g(x.dtree,K),_(x.dtree,K,w)}for(;;){var X=U[v(o,b)&h];b+=X&15;var V=X>>>4;if(!(V>>>8))d[y++]=V;else{if(V==256)break;var N=y+V-254;if(V>264){var q=x.ldef[V-257];N=y+(q>>>3)+s(o,b,q&7),b+=q&7}var Q=w[v(o,b)&m];b+=Q&15;var xe=Q>>>4,j=x.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,g=n.F._get17,_=0;_<f;){var v=o[g(c,u)&d];u+=v&15;var x=v>>>4;if(x<=15)s[_]=x,_++;else{var S=0,E=0;x==16?(E=3+p(c,u,2),u+=2,S=s[_-1]):x==17?(E=3+p(c,u,3),u+=3):x==18&&(E=11+p(c,u,7),u+=7);for(var e=_+E;_<e;)s[_]=S,_++}}return u},n.F._copyOut=function(o,d,f,c){for(var u=0,s=0,p=c.length>>>1;s<f;){var g=o[s+d];c[s<<1]=0,c[(s<<1)+1]=g,g>u&&(u=g),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,g=0;g<=d;g++)v[g]=0;for(g=1;g<c;g+=2)v[o[g]]++;var x=f.next_code;for(u=0,v[0]=0,s=1;s<=d;s++)u=u+v[s-1]<<1,x[s]=u;for(p=0;p<c;p+=2)_=o[p+1],_!=0&&(o[p]=x[_],x[_]++)},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 g=p>>1,_=o[p+1],v=g<<4|_,x=d-_,S=o[p]<<x,E=S+(1<<x);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,g){for(;p--!=0;)s.push(0,g)}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 g=this.h,_=this.m,v=this.s,x=this.f,S=this.field;const E=g*60+_,t=(E-Math.floor(E/10))*p;return g*(s*3600)+_*(s*60)+v*s+(x*2+S)-t},this.addSeconds=u=>{let s=this.copy();return s.s+=u,s.s>=60&&(s.s=0,s.m++,s.m>=60&&(s.m=0,s.h++)),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 g=Math.floor(s-p);return g<0&&(g+=5178816),g>=5178816&&(g-=5178816),Y.fromFrames(g,f)},Y.calculateCurrentOffset=(n,o)=>{for(let d=1;d<o.length;d++)if(n<o[d].frame)return o[d-1].offset;return 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,g=Math.floor(p/s);p-=g*s;let _=Math.floor(p/u);p-=_*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 x=Math.floor(p/d);p-=x*d;let S=p;v+=_*10;let E=0;return E=S%2,S=Math.floor(S/2),new Y(g,v,x,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,g=Number(f),_=Number(c),v=Number(u),x=Number(s),S=p?Number(p):0;return new Y(g,_,v,x,S)};let $=Y;const z={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},ee=console,ce={};Object.keys(z).forEach(a=>{ce[a]=ee[a]});const Be="Datadog Browser SDK:",O={debug:ce.debug.bind(ee,Be),log:ce.log.bind(ee,Be),info:ce.info.bind(ee,Be),warn:ce.warn.bind(ee,Be),error:ce.error.bind(ee,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){O.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,he=60*ke,ni=60*he,mn=365*(24*ni);function Le(){return new Date().getTime()}function se(){return Le()}function je(){return performance.now()}function oe(){return{relative:je(),timeStamp:se()}}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 te=1024,si=1024*te,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 ae(){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=ae();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?L(d):d).apply(this,f)}}function L(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&&O.error("[MONITOR]",...a)}function Pe(a,n){return Ue(ae(),"setTimeout")(L(a),n)}function di(a){Ue(ae(),"clearTimeout")(a)}function Et(a,n){return Ue(ae(),"setInterval")(L(a),n)}function li(a){Ue(ae(),"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 de(){}function le(a){return a?(parseInt(a,10)^Math.random()*16>>parseInt(a,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,le)}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 Fn(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 In(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":"",g=d&&d.partitioned?";partitioned":"";document.cookie=`${a}=${n};${c};path=/;samesite=${u}${s}${p}${g}`}function wt(a){return An(document.cookie,a)}let Tt;function ue(a){return Tt||(Tt=Fn(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_${le()}`,o="test";ze(n,o,he,a);const d=wt(n)===o;return hi(n,a),d}catch(n){return O.error(n),!1}}let Ct;function Rn(){if(Ct===void 0){const a=`dd_site_test_${le()}`,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*he,zn=mn,Oe={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},pi=/^([a-zA-Z]+)=([a-z0-9-]+)$/,Ft="&";function On(a){return!!a&&(a.indexOf(Ft)!==-1||pi.test(a))}const Mn="1";function pe(a,n){const o={isExpired:Mn};return n.trackAnonymousUser&&(a!=null&&a.anonymousId?o.anonymousId=a==null?void 0:a.anonymousId:o.anonymousId=le()),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 It(a){return Pn(a).map(([n,o])=>n==="anonymousId"?`aid=${o}`:`${n}=${o}`).join(Ft)}function mi(a){const n={};return On(a)&&a.split(Ft).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(!ue(Ee)){const o=ue(Gn),d=ue(Hn),f=ue(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,It(n),ui,a)}}function Wn(a,n,o){const d=pe(n,o);ze(Ee,It(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=le(),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,It(a))}function er(){const a=localStorage.getItem(Ee);return mi(a)}function tr(a,n){Si(pe(a,n))}const ir=10,nr=100,bi=[];let Qe;function _e(a,n,o=0){var d;const{isLockEnabled:f,persistSession:c,expireSession:u}=n,s=x=>c({...x,lock:g}),p=()=>{const x=n.retrieveSession(),S=x.lock;return x.lock&&delete x.lock,{session:x,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(_.lock){et(a,n,o);return}if(g=le(),s(_.session),_=p(),_.lock!==g){et(a,n,o);return}}let v=a.process(_.session);if(f&&(_=p(),_.lock!==g)){et(a,n,o);return}if(v&&(Ze(v)?u(v):(gi(v),f?s(v):c(v))),f&&!(v&&Ze(v))){if(_=p(),_.lock!==g){et(a,n,o);return}c(_.session),v=_.session}(d=a.after)===null||d===void 0||d.call(a,v||_.session),xi(n)}function et(a,n,o){Pe(()=>{_e(a,n,o+1)},ir)}function xi(a){Qe=void 0;const n=bi.shift();n&&_e(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:O.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,g=Et(E,Ui);let _;t();const{throttled:v,cancel:x}=ci(()=>{_e({process:U=>{if(Xe(U))return;const w=e(U);return r(w),w},after:U=>{_i(U)&&!l()&&y(U),_=U}},s)},Ui);function S(){_e({process:U=>l()?e(U):void 0},s)}function E(){_e({process:U=>Ze(U)?pe(U,n):void 0,after:e},s)}function e(U){return Ze(U)&&(U=pe(U,n)),l()&&(h(U)?m():(u.notify({previousState:_,newState:U}),_=U)),U}function t(){_e({process:U=>{if(Xe(U))return pe(U,n)},after:U=>{_=U}},s)}function r(U){if(Xe(U))return!1;const{trackingType:w,isTracked:T}=d(U[o]);U[o]=w,delete U.isExpired,T&&!U.id&&(U.id=le(),U.created=String(Le()))}function l(){return _[o]!==void 0}function h(U){return _.id!==U.id||_[o]!==U[o]}function m(){_=pe(_,n),c.notify()}function y(U){_=U,f.notify()}function b(U){_e({process:w=>({...w,...U}),after:e},s)}return{expandOrRenewSession:v,expandSession:S,getSession:()=>_,renewObservable:f,expireObservable:c,sessionStateUpdateObservable:u,restartSession:t,expire:()=>{x(),p(_),e(pe(_,n))},stop:()=>{li(g)},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 ge(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}):de}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)} ${ge({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=${le()}`];return u&&p.push(`dd-evp-encoding=${u}`),o==="rum"&&p.push(`batch_time=${se()}`),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))&&O.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"?(O.error(`${n} must be defined as a string`),!1):!0}function wr(a){return a&&typeof a=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(a)?(O.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)?(O.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){O.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)){O.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*te,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*ke,batchMessagesLimit:50,messageBytesLimit:256*te,...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)&&Fr(a.filter(n=>oi(Dt,n)))}function Fr(a){a.forEach(n=>{wi.add(n)})}function Ir(){return wi}const Ne="?";function ie(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=ie(o);f.stack=f.stack.slice(2),d=me(f)}),d}function me(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 ye(a,n,o,{computeHandlingStack:d}={}){let f=a[n];if(typeof f!="function")if(n in a&&n.startsWith("on"))f=de;else return{stop:de};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:_=>{p=_},handlingStack:d?rt("instrumented method"):void 0}]);const g=f.apply(this,s);return p&&Re(p,null,[g]),g};return a[n]=u,{stop:()=>{c=!0,a[n]===u&&(a[n]=f)}}}const Vr=220*te,$r="$",jr=3;function ne(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 g=f.shift();let _=0;if(Array.isArray(g.source))for(let v=0;v<g.source.length;v++){const x=Pt(g.source[v],g.path,v,f,c);if(x!==void 0?p+=JSON.stringify(x).length:p+=4,p+=_,_=1,p>n){Ot(n,"truncated",a);break}g.target[v]=x}else for(const v in g.source)if(Object.prototype.hasOwnProperty.call(g.source,v)){const x=Pt(g.source[v],g.path,v,f,c);if(x!==void 0&&(p+=JSON.stringify(x).length+_+v.length+jr,_=1),p>n){Ot(n,"truncated",a);break}g.target[v]=x}}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,g=Array.isArray(c)?[]:{};return f.set(s,p),d.push({source:c,target:g,path:p}),g}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){O.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 Fi({stackTrace:a,originalError:n,handlingStack:o,componentStack:d,startClocks:f,nonErrorPrefix:c,source:u,handling:s}){const p=fe(n),g=Jr(a,p,c,n),_=Xr(p,a)?me(a):Ai,v=p?ki(n,u):void 0,x=a?a.name:void 0,S=Ii(n),E=Bi(n);return{startClocks:f,source:u,handling:s,handlingStack:o,componentStack:d,originalError:n,type:x,message:g,stack:_,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} ${ge(ne(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 Ii(a){return fe(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 fe(a){return a instanceof Error||Object.prototype.toString.call(a)==="[object Error]"}function ki(a,n){let o=a;const d=[];for(;fe(o==null?void 0:o.cause)&&d.length<10;){const f=ie(o.cause);d.push({message:o.cause.message,source:n,type:f==null?void 0:f.name,stack:me(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=Fi({stackTrace:f,originalError:c,startClocks:oe(),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 ye(window,"onerror",({parameters:[n,o,d,f,c]})=>{let u;fe(c)?u=ie(c):u=Gr(n,o,d,f),a(u,c??n)})}function ts(a){return ye(window,"onunhandledrejection",({parameters:[n]})=>{const o=n.reason||"Empty reason",d=ie(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&&O.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||O.error(`${a} is already initialized.`)}function ve(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=L(x=>{!x.isTrusted&&!x.__ddIsTrusted&&!a.allowUntrustedEvents||(f&&v(),d(x))}),p=u?{capture:c,passive:u}:c,g=window.EventTarget&&n instanceof EventTarget?window.EventTarget.prototype:n,_=Ue(g,"addEventListener");o.forEach(x=>_.call(n,x,s,p));function v(){const x=Ue(g,"removeEventListener");o.forEach(S=>x.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=L((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}=ve(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 "${In(a.originalPolicy,100,"...")}"`:"no policy",a.sourceFile,a.lineNumber,a.columnNumber)})}function Di(a){return{startClocks:oe(),source:J.REPORT,handling:"unhandled",...a}}function Ri(a,n,o,d,f){return o?me({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 Se={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(),Fe=a=>{Gi.add(()=>Fe(a))};function _s(a,n){let o;const d=new G,f=new Set,c=!ps.includes(n.site)&&$e(n.telemetrySampleRate),u={[Se.log]:c,[Se.configuration]:c&&$e(n.telemetryConfigurationSampleRate),[Se.usage]:c&&$e(n.telemetryUsageSampleRate)},s=gs();Fe=g=>{const _=ge(g);if(u[g.type]&&f.size<n.maxTelemetryEventsPerPage&&!f.has(_)){const v=p(a,g,s);d.notify(v),Pi("telemetry",v),f.add(_)}},En(Yi);function p(g,_,v){return Ae({type:"telemetry",date:se(),service:g,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:Ae(_,{runtime_env:v,connectivity:fs(),sdk_setup:"npm"}),experimental_features:Array.from(Ir())},o!==void 0?o():{})}return{setContextProvider:g=>{o=g},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(z.debug,a,n),Fe({type:Se.log,message:a,status:"debug",...n})}function Yi(a,n){Fe({type:Se.log,status:"error",...bs(a),...n})}function vs(a){Fe({type:Se.configuration,configuration:a})}function Ss(a){Fe({type:Se.usage,usage:a})}function bs(a){if(fe(a)){const n=ie(a);return{error:{kind:n.name,stack:me(xs(n))},message:n.message}}return{error:{stack:Ai},message:`Uncaught ${ge(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=he;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 g(){return o.map(({startTime:S,endTime:E,value:e})=>({startTime:S,endTime:E===Ge?"Infinity":E,value:e}))}function _(){return d}function v(){o=[]}function x(){at.delete(f),at.size===0&&He&&(li(He),He=null)}return{add:c,find:u,closeActive:s,findAll:p,reset:v,stop:x,getAllEntries:g,getDeletedEntries:_}}const Ts=he,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()}),Fs(a,()=>{d.isGranted()&&u.expandOrRenewSession()}),Is(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 Fs(a,n){Mt(a,window,["click","touchstart","keydown","scroll"],n,{capture:!0,passive:!0})}function Is(a,n){const o=()=>{document.visibilityState==="visible"&&n()};ve(a,document,"visibilitychange",o),Et(o,Ts)}function Bs(a,n){ve(a,window,"resume",n,{capture:!0})}function Vi(a){return a>=500}function ks(a){try{return a.clone()}catch{return}}const Ls=80*te,Ds=32,$i=3*si,Rs=he,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:oe()}),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(L(u=>d==null?void 0:d({status:u.status,type:u.type})),L(()=>{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),ve({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=ae().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 ae().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=ve(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=>_(v));function u(v,x,S){o.notifyBeforeAddMessage(x),S!==void 0?(f[S]=v,o.notifyAfterAddMessage()):a.write(a.isEmpty?v:`\n${v}`,E=>{o.notifyAfterAddMessage(E-x)})}function s(v){return v!==void 0&&f[v]!==void 0}function p(v){const x=f[v];delete f[v];const S=a.estimateEncodedBytesCount(x);o.notifyAfterRemoveMessage(S)}function g(v,x){const S=ge(v),E=a.estimateEncodedBytesCount(S);if(E>=d){O.warn(`Discarded a message whose size was bigger than the maximum allowed size ${d}KB. ${Ve} ${ti}/#technical-limitations`);return}s(x)&&p(x),u(S,E,x)}function _(v){const x=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,x].filter(Boolean).join(`\n`);t&&E({data:t,bytesCount:xt(t)})}else x&&a.write(a.isEmpty?x:`\n${x}`),a.finish(e=>{E(Qi(e))})}return{flushController:o,add:g,upsert:g,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=>_(E.reason)),u=f.subscribe(()=>_("session_expire")),s=new G(()=>()=>{c.unsubscribe(),u.unsubscribe()});let p=0,g=0;function _(E){if(g===0)return;const e=g,t=p;g=0,p=0,S(),s.notify({reason:E,messagesCount:e,bytesCount:t})}let v;function x(){v===void 0&&(v=Pe(()=>{_("duration_limit")},o))}function S(){di(v),v=void 0}return{flushObservable:s,get messagesCount(){return g},notifyBeforeAddMessage(E){p+E>=n&&_("bytes_limit"),g+=1,p+=E,x()},notifyAfterAddMessage(E=0){p+=E,g>=a?_("messages_limit"):p>=n&&_("bytes_limit")},notifyAfterRemoveMessage(E){p-=E,g-=1,g===0&&S()}}}function en(a,n,o,d,f,c,u=Ks){const s=g(a,n),p=o&&g(a,o);function g(_,{endpoint:v,encoder:x}){return u({encoder:x,request:Ms(v,_.batchBytesLimit,d),flushController:qs({messagesLimit:_.batchMessagesLimit,bytesLimit:_.batchBytesLimit,durationLimit:_.flushTimeout,pageExitObservable:f,sessionExpireObservable:c}),messageBytesLimit:_.messageBytesLimit})}return{flushObservable:s.flushController.flushObservable,add(_,v=!0){s.add(_),p&&v&&p.add(o.transformMessage?o.transformMessage(_):_)},upsert:(_,v)=>{s.upsert(_,v),p&&p.upsert(o.transformMessage?o.transformMessage(_):_,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},he),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:oe()})}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}=ye(XMLHttpRequest.prototype,"open",Qs),{stop:d}=ye(XMLHttpRequest.prototype,"send",c=>{eo(c,a,n)},{computeHandlingStack:!0}),{stop:f}=ye(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=oe(),c.isAborted=!1,c.xhr=a,c.handlingStack=n;let u=!1;const{stop:s}=ye(a,"onreadystatechange",()=>{a.readyState===XMLHttpRequest.DONE&&p()}),p=()=>{if(g(),s(),u)return;u=!0;const _=f;_.state="complete",_.duration=vn(c.startClocks.timeStamp,se()),_.status=a.status,d.notify(Un(_))},{stop:g}=ve(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}=ye(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)),g=oe(),_={state:"start",init:c,input:f,method:s,startClocks:g,url:p,handlingStack:o};d.notify(_),a[0]=_.input,a[1]=_.init,n(v=>ro(d,v,_))}function ro(a,n,o){const d=o;function f(c){d.state="resolve",Object.assign(d,c),a.notify(d)}n.then(L(c=>{f({response:c,responseType:c.type,status:c.status,isAborted:!1})}),L(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=ee[a];return ee[a]=(...d)=>{o.apply(console,d);const f=rt("console error");Re(()=>{n.notify(ao(d,a,f))})},()=>{ee[a]=o}})}function ao(a,n,o){const d=a.map(c=>lo(c)).join(" ");let f;if(n===z.error){const c=a.find(fe);f={stack:c?me(ie(c)):void 0,fingerprint:Ii(c),causes:c?ki(c,"console"):void 0,startClocks:oe(),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"?ne(a):fe(a)?Ci(ie(a)):ge(ne(a),void 0,2)}function fo(a){const n=zi(a)==="object";return n||O.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)&&O.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=ne(jt(u,o,a)),n==null||n.updateCustomerData(d)):c.clearContext(),f.notify()},setContextProperty:(u,s)=>{d=ne(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(ve(a,window,"storage",({key:g})=>{f===g&&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 g=localStorage.getItem(f);return g?JSON.parse(g):{}}}function uo(a,n){return`${co}_${a}_${n}`}const po=3*te,_o=16*te,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(ge(c)),a()},go),f=()=>{d(),n=0};return{updateCustomerData:c=>{De(c)?f():o(c)},resetCustomerData:f,getBytesCount:()=>n,stop:()=>{d()}}}function yo(a){O.warn(`Customer data exceeds the recommended ${a/te}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(L(p=>{if(p.done){s();return}f.push(p.value),c+=p.value.length,c>o.bytesLimit?s():u()}),L(p=>n(p)))}function s(){d.cancel().catch(de);let p,g;{let _;if(f.length===1)_=f[0];else{_=new Uint8Array(c);let v=0;f.forEach(x=>{_.set(x,v),v+=x.length})}p=_.slice(0,o.bytesLimit),g=_.length>o.bytesLimit}n(void 0,p,g)}}const So="datadog-synthetics-public-id",bo="datadog-synthetics-result-id",xo="datadog-synthetics-injects-rum";function rn(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||ue(xo))}function Uo(){const a=window._DATADOG_SYNTHETICS_PUBLIC_ID||ue(So);return typeof a=="string"?a:void 0}function Eo(){const a=window._DATADOG_SYNTHETICS_RESULT_ID||ue(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 Z=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=ne(o);let s;if(f!=null){const p=Fi({stackTrace:fe(f)?ie(f):void 0,originalError:f,nonErrorPrefix:"Provided",source:J.LOGGER,handling:"handled",startClocks:oe()});s=Ae({error:ut(p,{includeMessage:!0})},u)}else s=u;this.handleLogStrategy({message:ne(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],Z.prototype,"logImplementation",null),Z.prototype.ok=re(B.ok),Z.prototype.debug=re(B.debug),Z.prototype.info=re(B.info),Z.prototype.notice=re(B.notice),Z.prototype.warn=re(B.warn),Z.prototype.error=re(B.error),Z.prototype.critical=re(B.critical),Z.prototype.alert=re(B.alert),Z.prototype.emerg=re(B.emerg);function re(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*te;function Fo(a){a.usePciIntake===!0&&a.site&&a.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 n=Tr(a),o=on(a.forwardConsoleLogs,Je(z),"Forward Console Logs"),d=on(a.forwardReports,Je(st),"Forward Reports");if(!(!n||!o||!d))return a.forwardErrorsToLogs&&!o.includes(z.error)&&o.push(z.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)))){O.error(`${o} should be "all" or an array with allowed values "${n.join(\'", "\')}"`);return}return a==="all"?n:cs(a)}function Io(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){O.error("Missing configuration");return}if(Ar(p.enableExperimentalFeatures),dt()&&(p=ko(p)),f=p,c){Li("DD_LOGS",p);return}const g=Fo(p);g&&(c=g,tn().subscribe(de),n.tryToInit(g.trackingConsent),s())},get initConfiguration(){return f},getInternalContext:de,handleLog(p,g,_,v=a(),x=se()){d.add(S=>S.handleLog(p,g,_,v,x))}}}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,(_,v)=>{_.storeContextsAcrossPages&&(Kt(v,o,qt,2),Kt(v,d,qt,1),Kt(v,f,qt,4));const x=a(_,v,u,c);return s=Do(_,x),x});const p={},g=new Z((..._)=>s.handleLog(..._),n.createDetachedTracker());return is({logger:g,init:L(_=>s.init(_)),setTrackingConsent:L(_=>{c.update(_),Ss({feature:"set-tracking-consent",tracking_consent:_})}),getGlobalContext:L(()=>o.getContext()),setGlobalContext:L(_=>o.setContext(_)),setGlobalContextProperty:L((_,v)=>o.setContextProperty(_,v)),removeGlobalContextProperty:L(_=>o.removeContextProperty(_)),clearGlobalContext:L(()=>o.clearContext()),createLogger:L((_,v={})=>(p[_]=new Z((...x)=>s.handleLog(...x),n.createDetachedTracker(),ne(_),v.handler,v.level,ne(v.context)),p[_])),getLogger:L(_=>p[_]),getInitConfiguration:L(()=>Oi(s.initConfiguration)),getInternalContext:L(_=>s.getInternalContext(_)),setUser:L(d.setContext),getUser:L(d.getContext),setUserProperty:L(d.setContextProperty),removeUserProperty:L(d.removeContextProperty),clearUser:L(d.clearContext),setAccount:L(f.setContext),getAccount:L(f.getContext),setAccountProperty:L(f.setContextProperty),removeAccountProperty:L(f.removeContextProperty),clearAccount:L(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:g=void 0,domainContext:_})=>{var v,x;const S=bn(s.date),E=a.findTrackedSession(S);if(!a.findTrackedSession(S,{returnInactive:!0}))return;const t=g||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,_))===!1||l.origin!==J.AGENT&&((x=u[l.status])!==null&&x!==void 0?x:u.custom).isLimitReached()||o.notify(1,l)})}const Go={[z.log]:B.info,[z.debug]:B.debug,[z.info]:B.info,[z.warn]:B.warn,[z.error]:B.error};function Ho(a,n){const o=so(a.forwardConsoleLogs).subscribe(d=>{var f;const c={rawLogsEvent:{date:se(),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:se(),message:f,origin:J.REPORT,error:c,status:u}})});return{stop:()=>{o.unsubscribe()}}}function Vo(a,n){if(!a.forwardErrorsToLogs)return{stop:de};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 g={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:g})}}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(me(ie(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(L(f=>o(Wt(f,n))),L(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:de};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||se(),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]:z.debug,[B.debug]:z.debug,[B.info]:z.info,[B.notice]:z.info,[B.warn]:z.warn,[B.error]:z.error,[B.critical]:z.error,[B.alert]:z.error,[B.emerg]:z.error};function ta({status:a,message:n},o){ce[ea[a]].call(ee,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,x;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||g===void 0?void 0:g.view)===null||_===void 0?void 0:_.id},action:{id:(x=(v=pt())===null||v===void 0?void 0:v.user_action)===null||x===void 0?void 0:x.id}}});const u=[];if(dt()){const s=Gt(),p=c.observable.subscribe(g=>s.send("internal_telemetry",g));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(g=>s.add(g,ys(n)));u.push(()=>p.unsubscribe())}return ms(),vs(Io(a)),{telemetry:c,stop:()=>{u.forEach(s=>s())}}}function aa(a,n,o,d){const f=new Zo,c=[];f.subscribe(1,x=>Pi("logs",x));const u=sa(f),s=$s(n),p=n.sessionStoreStrategyType&&!dt()&&!rn()?Po(n,d):zo(n),{stop:g}=oa(a,n,u,s,p);c.push(()=>g()),Vo(n,f),Xo(n,f),Ho(n,f),Yo(n,f);const{handleLog:_}=Qo(f);if(No(p,n,f,o,u),dt())na(f);else{const{stop:x}=ia(n,f,u,s,p);c.push(()=>x())}const v=ra(p);return{handleLog:_,getInternalContext:v.get,stop:()=>{c.forEach(x=>x())}}}const Ie=Lo(aa);ns(ae(),"DD_LOGS",Ie);const I=class I{constructor(n){this.isLoggingOn=n.LOG_TO_DATADOG,this.isLoggingOn&&Ie.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!1,sessionSampleRate:100}),I.tracking.dev=`${n.platform}_${n.browserName}`,I.beatHandle||(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}setAttributes(n){I.processAttributes(n);for(const o in n)Ie.logger.setContextProperty(o,n[o])}info(n,o){o&&I.processAttributes(o),this.isLoggingOn&&(Ie.logger.info(n,o),console.log("[Logger] Sending info: ",n))}error(n,o){o&&I.processAttributes(o),this.isLoggingOn&&(Ie.logger.error(n,o),I.tracking.err_time=Date.now().toFixed(0),I.tracking.err_desc=n,console.log("[Logger] Sending error: ",n))}warn(n,o){o&&I.processAttributes(o),this.isLoggingOn&&(Ie.logger.warn(n,o),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){I.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:n})}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){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,console.log("[Logger] Setting bb_session_id:",I.tracking.sid)),n.last_timecode&&(I.tracking.tc=n.last_timecode,I.lastTimecodeMillis=$.fromStr(n.last_timecode).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,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("&")}};I.tracking={start:Date.now().toFixed(0),dev:"",sdk:"",mac:"",gid:"",sid:"",off:"",zip:"",aug_time:"",err_time:"",err_desc:"",tc:"",png:"",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)}`;console.log("[Logger] Flushing tracking data:",d),fetch(d,{method:"GET",mode:"no-cors",keepalive:!0}).catch(()=>{})};let M=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.addJob=(f,c)=>{const{alphaMp4:u,metadataList:s}=this.parseZipAndMetadata(c,f);if(!u){this.options&&R(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&&R(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.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++;const p=performance.now();u<s&&(p-this.loggerTimeoutStart>this.loggerTimeout&&(this.loggerTimeoutStart=p,M.error("[Decoder] Timecode is going backwards")),this.options&&R(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,M.error("[Decoder] Timecode is too far ahead")),this.options&&R(this.options,"Errors")&&console.error("[Decoder] Timecode is too far ahead")),this.timecodeErrorCount>5&&this.restartDecoder();return}}this.timecodeErrorCount=0,this.currentTimecode=f,this.clearOldJobsAndChunks(2100),this.decodeUpcomingChunks()}},this.setupMP4Box=(f=!1)=>{const c=cn.createFile();return c.onError=u=>{M.error("[Decoder] MP4 parsing error",u),this.options&&R(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&&R(this.options,"Decoder")&&console.error("[Decoder] Starting a new VideoDecoder");let g;f?(this.reservedVideoDecoder=new VideoDecoder({output:this.onFrameDecoded,error:this.onDecoderError}),g=this.reservedVideoDecoder):(this.videoDecoder=new VideoDecoder({output:this.onFrameDecoded,error:this.onDecoderError}),g=this.videoDecoder),g.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)}c.setExtractionOptions(s.id),c.start()}},c.onSamples=async(u,s,p)=>{const g=[];let _=0,v=0;if(this.options.browserName==="Firefox"){const x=p.map(E=>E.cts).sort((E,e)=>E-e);_=200-x[0],v=x[x.length-1]+_}for(const x of p){const S=this.options.browserName==="Firefox"?x.cts+this.lastJobEndTimecode+_:x.cts,E=new EncodedVideoChunk({type:x.is_sync?"key":"delta",timestamp:S,data:new Uint8Array(x.data)});g.push(E)}this.storeChunks(g),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&&R(this.options,"Decoder")&&console.log("[Decoder] Storing chunks:",f);const c=this.jobChunking;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,g)=>({timeCode:p.timecode,chunk:f[g],metadata:p,job:c,cancelled:!1,decodingTime:0}));c.chunks=u,this.chunksQueue.push(...u),this.jobsQueue.push(c),this.options&&R(this.options,"Decoder")&&console.log("[Decoder] Jobs Queue:",this.jobsQueue),this.options&&R(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 g=f.timestamp;if(g!==c){if(this.options&&R(this.options,"Decoder")&&console.log("[Decoder] Frame out of order, storing frame:",g),this.storedFrames.push(f),this.storedFrames.sort((_,v)=>_.timestamp-v.timestamp),this.storedFrames[0].timestamp===c){const _=this.storedFrames.shift();_&&this.onFrameDecoded(_)}this.storedFrames.sort((_,v)=>_.timestamp-v.timestamp);return}this.lastProcessedFrameTimecode=g}this.options&&R(this.options,"Decoder")&&console.log("[Decoder] Frame decoded:",f);const u=this.chunksForDecodingFrames.shift();if(!u){M.error("[Decoder] No current chunk for a processed frame"),this.options&&R(this.options,"Errors")&&console.error("[Decoder] No current chunk for a processed frame");return}if(u.cancelled||this.decoderStopped){this.options&&R(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 g=performance.now();u.decodingTime=g-u.decodingTime,this.decodingFrameCount++,this.decodingTimeSum+=u.decodingTime,this.avgDecodingTime=this.decodingTimeSum/this.decodingFrameCount,g-this.lastPerformanceCheck>=this.options.PERFORMANCE_TRACKING_INTERVAL&&(this.trackPerformance(),this.lastPerformanceCheck=g)}if(u.job.framesProcessed++,s.alphaMask=f,this.processedMetadata.push(s),M.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(g=>g.alphaMask.close()),this.processedMetadata=[]),this.options.browserName==="Firefox"&&this.storedFrames.length>0){const g=(c+200)%24200||400;if(this.storedFrames[0].timestamp===g){const _=this.storedFrames.shift();_&&this.onFrameDecoded(_)}}},this.onDecoderError=f=>{var s,p;M.error("[Decoder] VideoDecoder error",f),this.options&&R(this.options,"Errors")&&console.error("[Decoder] VideoDecoder error:",f),this.videoDecoderConfigured=!1,this.reservedVideoDecoderConfigured=!1,this.videoDecoderNeedsKeyFrame=!0,this.reservedVideoDecoderNeedsKeyFrame=!0;const c=this.chunksForDecodingFrames.shift();if(!c){M.error("[Decoder] No broken chunk for an error"),this.options&&R(this.options,"Errors")&&console.error("[Decoder] No broken chunk for an error");return}const u=c.job;u&&u.chunks.forEach(g=>g.cancelled=!0),(s=this.reservedVideoDecoder)==null||s.close(),(p=this.videoDecoder)==null||p.close()},this.parseZipAndMetadata=(f,c)=>{const u=pn.parse(f),s=u["alpha.mp4"]||null,p=Object.keys(u).filter(e=>e.endsWith(".json")).sort(this.numericFileComparator).map(e=>{const t=JSON.parse(new TextDecoder().decode(u[e]));return t.timecode=$.toStr($.fromMetadata(t)),t}),g=p.length;let _=120;const[v,x,S]=c.split("_").map(Number);x%10===0&&S===0?_=120:S===0&&(_=116),g!==_&&(M.error("[Decoder] Metadata count mismatch",{expected:_,actual:g,timecode:c}),this.options&&R(this.options,"Errors")&&console.error("[Decoder] Metadata count mismatch:",{expected:_,actual:g,timecode:c}));const E=p.filter(e=>e.placeholders);return{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,x,S="0",E]=s,[,e,t,r,l,h="0",m]=p;return parseInt(g,10)-parseInt(e,10)||parseInt(_,10)-parseInt(t,10)||parseInt(v,10)-parseInt(r,10)||parseInt(x,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()}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&&R(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"){M.error("[Decoder] No VideoDecoder available"),this.options&&R(this.options,"Errors")&&console.error("[Decoder] No VideoDecoder available");continue}if((c.job.useReserveDecoder?this.reservedVideoDecoderNeedsKeyFrame:this.videoDecoderNeedsKeyFrame)&&c.chunk.type==="delta"){M.error("[Decoder] Decoder needs a key frame, skipping delta chunk",{chunkTimeCode:c.timeCode}),this.options&&R(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){M.error("[Decoder] Error decoding chunk",p),this.options&&R(this.options,"Errors")&&console.error("[Decoder] Error decoding chunk:",p),this.videoDecoderConfigured=!1,this.reservedVideoDecoderConfigured=!1,this.videoDecoderNeedsKeyFrame=!0,this.reservedVideoDecoderNeedsKeyFrame=!0,c.job.chunks.forEach(_=>_.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.clearAllJobsAndChunks();try{(n=this.videoDecoder)==null||n.close()}catch(d){M.error("[Decoder] Error closing main VideoDecoder",d),this.options&&R(this.options,"Errors")&&console.error("[Decoder] Error closing main VideoDecoder:",d)}try{(o=this.reservedVideoDecoder)==null||o.close()}catch(d){M.error("[Decoder] Error closing reserved VideoDecoder",d),this.options&&R(this.options,"Errors")&&console.error("[Decoder] Error closing reserved VideoDecoder:",d)}}}let ln=null,_t=null,be,H;self.onmessage=async a=>{const{data:n}=a;if(n.type==="SET_LOGGER_PORT"&&M.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,M.setMessagePort(self),be=new Jt(Xt,gt,H)),n.type==="VIDEO_SEEKED"){if(!H)return;gt()}};function da(a){const{data:n}=a;if(n.type==="DECODER_INPUT"){const{timeCode:o,arrayBuffer:d}=n;H&&R(H,"Decoder")&&console.log("[DecoderWorker] Received ArrayBuffer from Downloader, timeCode =",o),be.addJob(o,d)}}function la(a){const{data:n}=a;if(n.type==="DECODER_REQUEST"){const{timeCode:o,fps:d}=n;H&&R(H,"Decoder")&&console.log("[DecoderWorker] Received TimeCode request from Renderer, timeCode =",o),be.updateCurrentTimecode(o,d)}}function gt(){H&&(be.stop(),be=new Jt(Xt,gt,H))}function Xt(a){if(!_t)return;H&&R(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){M.error("[DecoderWorker] Error posting batch to Renderer",{error:o}),H&&R(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=>{M.error("[DecoderWorker] Unhandled rejection",{error:a.reason}),H&&(R(H,"Errors")&&console.error("[DecoderWorker] Unhandled rejection:",a.reason),be.stop(),be=new Jt(Xt,gt,H),a.preventDefault())},self.onerror=a=>{M.error("[DecoderWorker] Unhandled error",{error:a}),H&&(R(H,"Errors")&&console.error("[DecoderWorker] Unhandled error:",a),a instanceof Event&&a.preventDefault())}})();\n',Nt=typeof self<"u"&&self.Blob&&new Blob([Bt],{type:"text/javascript;charset=utf-8"});function sr(t){let e;try{if(e=Nt&&(self.URL||self.webkitURL).createObjectURL(Nt),!e)throw"";const n=new Worker(e,{name:t==null?void 0:t.name});return n.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),n}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 $t='(function(){"use strict";const O=(t,e)=>!t.debug||!t.debug.on?!1:t.debug[`log${e}`],_={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},D=console,z={};Object.keys(_).forEach(t=>{z[t]=D[t]});const fe="Datadog Browser SDK:",R={debug:z.debug.bind(D,fe),log:z.log.bind(D,fe),info:z.info.bind(D,fe),warn:z.warn.bind(D,fe),error:z.error.bind(D,fe)},Qe="https://docs.datadoghq.com",It=`${Qe}/real_user_monitoring/browser/troubleshooting`,we="More details:";function kt(t,e){return(...n)=>{try{return t(...n)}catch(r){R.error(e,r)}}}function xe(t){return t!==0&&Math.random()*100<=t}function zn(t){return Hn(t)&&t>=0&&t<=100}function Hn(t){return typeof t=="number"}const he=1e3,H=60*he,Ut=60*H,Vn=365*(24*Ut);function me(){return new Date().getTime()}function $(){return me()}function Ce(){return performance.now()}function G(){return{relative:Ce(),timeStamp:$()}}function Kn(){return{relative:0,timeStamp:Dt()}}function Zn(t,e){return e-t}function Jn(t,e){return t+e}function Qn(t){return t-Dt()}let et;function Dt(){return et===void 0&&(et=performance.timing.navigationStart),et}const M=1024,Pt=1024*M,er=/[^\\u0000-\\u007F]/;function tt(t){return er.test(t)?window.TextEncoder!==void 0?new TextEncoder().encode(t).length:new Blob([t]).size:t.length}function tr(t){return{...t}}function Mt(t,e){return Object.keys(t).some(n=>t[n]===e)}function pe(t){return Object.keys(t).length===0}function j(){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 re(t,e){const n=j();let r;return n.Zone&&typeof n.Zone.__symbol__=="function"&&(r=t[n.Zone.__symbol__(e)]),r||(r=t[e]),r}let Le,Ft=!1;function nr(t){Le=t}function rr(t){Ft=t}function sr(t,e,n){const r=n.value;n.value=function(...s){return(Le?b(r):r).apply(this,s)}}function b(t){return function(){return ge(t,this,arguments)}}function ge(t,e,n){try{return t.apply(e,n)}catch(r){or(r)}}function or(t){if(nt(t),Le)try{Le(t)}catch(e){nt(e)}}function nt(...t){Ft&&R.error("[MONITOR]",...t)}function Ee(t,e){return re(j(),"setTimeout")(b(t),e)}function Nt(t){re(j(),"clearTimeout")(t)}function rt(t,e){return re(j(),"setInterval")(b(t),e)}function Bt(t){re(j(),"clearInterval")(t)}class A{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(n=>e!==n),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}}notify(e){this.observers.forEach(n=>n(e))}}function $t(...t){return new A(e=>{const n=t.map(r=>r.subscribe(s=>e.notify(s)));return()=>n.forEach(r=>r.unsubscribe())})}function Gt(t,e,n){let r=!1,s,o;return{throttled:(...i)=>{if(r){s=i;return}t(...i),r=!0,o=Ee(()=>{s&&t(...s),r=!1,s=void 0},e)},cancel:()=>{Nt(o),r=!1,s=void 0}}}function W(){}function X(t){return t?(parseInt(t,10)^Math.random()*16>>parseInt(t,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,X)}const Oe=/([\\w-]+)\\s*=\\s*([^;]+)/g;function ir(t,e){for(Oe.lastIndex=0;;){const n=Oe.exec(t);if(n){if(n[1]===e)return n[2]}else break}}function ar(t){const e=new Map;for(Oe.lastIndex=0;;){const n=Oe.exec(t);if(n)e.set(n[1],n[2]);else break}return e}function cr(t,e,n=""){const r=t.charCodeAt(e-1),o=r>=55296&&r<=56319?e+1:e;return t.length<=o?t:`${t.slice(0,o)}${n}`}function ur(){return lr()===0}let Ie;function lr(){return Ie??(Ie=dr())}function dr(t=window){var e;const n=t.navigator.userAgent;return t.chrome||/HeadlessChrome/.test(n)?0:((e=t.navigator.vendor)===null||e===void 0?void 0:e.indexOf("Apple"))===0||/safari/i.test(n)&&!/chrome|android/i.test(n)?1:2}function ye(t,e,n=0,r){const s=new Date;s.setTime(s.getTime()+n);const o=`expires=${s.toUTCString()}`,i=r&&r.crossSite?"none":"strict",a=r&&r.domain?`;domain=${r.domain}`:"",u=r&&r.secure?";secure":"",c=r&&r.partitioned?";partitioned":"";document.cookie=`${t}=${e};${o};path=/;samesite=${i}${a}${u}${c}`}function st(t){return ir(document.cookie,t)}let ot;function V(t){return ot||(ot=ar(document.cookie)),ot.get(t)}function jt(t,e){ye(t,"",0,e)}function fr(t){if(document.cookie===void 0||document.cookie===null)return!1;try{const e=`dd_cookie_test_${X()}`,n="test";ye(e,n,H,t);const r=st(e)===n;return jt(e,t),r}catch(e){return R.error(e),!1}}let it;function hr(){if(it===void 0){const t=`dd_site_test_${X()}`,e="test",n=window.location.hostname.split(".");let r=n.pop();for(;n.length&&!st(t);)r=`${n.pop()}.${r}`,ye(t,e,he,{domain:r});jt(t,{domain:r}),it=r}return it}const se="_dd_s";function ke(t){return Object.values(t)}function mr(t){return Object.entries(t)}const at=4*Ut,Wt=15*H,pr=Vn,be={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},Xt=/^([a-zA-Z]+)=([a-z0-9-]+)$/,ct="&";function gr(t){return!!t&&(t.indexOf(ct)!==-1||Xt.test(t))}const Er="1";function K(t,e){const n={isExpired:Er};return e.trackAnonymousUser&&(t!=null&&t.anonymousId?n.anonymousId=t==null?void 0:t.anonymousId:n.anonymousId=X()),n}function Ue(t){return pe(t)}function qt(t){return!Ue(t)}function De(t){return t.isExpired!==void 0||!yr(t)}function yr(t){return(t.created===void 0||me()-Number(t.created)<at)&&(t.expire===void 0||me()<Number(t.expire))}function Yt(t){t.expire=String(me()+Wt)}function ut(t){return mr(t).map(([e,n])=>e==="anonymousId"?`aid=${n}`:`${e}=${n}`).join(ct)}function zt(t){const e={};return gr(t)&&t.split(ct).forEach(n=>{const r=Xt.exec(n);if(r!==null){const[,s,o]=r;s==="aid"?e.anonymousId=o:e[s]=o}}),e}const br="_dd",Sr="_dd_r",Tr="_dd_l",_r="rum",Rr="logs";function Ar(t){if(!V(se)){const n=V(br),r=V(Sr),s=V(Tr),o={};n&&(o.id=n),s&&/^[01]$/.test(s)&&(o[Rr]=s),r&&/^[012]$/.test(r)&&(o[_r]=r),qt(o)&&(Yt(o),t.persistSession(o))}}function Ht(t){const e=Lr(t);return fr(e)?{type:be.COOKIE,cookieOptions:e}:void 0}function vr(t,e){const n={isLockEnabled:ur(),persistSession:wr(e),retrieveSession:Cr,expireSession:r=>xr(e,r,t)};return Ar(n),n}function wr(t){return e=>{ye(se,ut(e),Wt,t)}}function xr(t,e,n){const r=K(e,n);ye(se,ut(r),n.trackAnonymousUser?pr:at,t)}function Cr(){const t=st(se);return zt(t)}function Lr(t){const e={};return e.secure=!!t.useSecureSessionCookie||!!t.usePartitionedCrossSiteSessionCookie,e.crossSite=!!t.usePartitionedCrossSiteSessionCookie,e.partitioned=!!t.usePartitionedCrossSiteSessionCookie,t.trackSessionAcrossSubdomains&&(e.domain=hr()),e}const Or="_dd_test_";function Vt(){try{const t=X(),e=`${Or}${t}`;localStorage.setItem(e,t);const n=localStorage.getItem(e);return localStorage.removeItem(e),t===n?{type:be.LOCAL_STORAGE}:void 0}catch{return}}function Ir(t){return{isLockEnabled:!1,persistSession:Kt,retrieveSession:kr,expireSession:e=>Ur(e,t)}}function Kt(t){localStorage.setItem(se,ut(t))}function kr(){const t=localStorage.getItem(se);return zt(t)}function Ur(t,e){Kt(K(t,e))}const Dr=10,Pr=100,Zt=[];let Pe;function Z(t,e,n=0){var r;const{isLockEnabled:s,persistSession:o,expireSession:i}=e,a=f=>o({...f,lock:c}),u=()=>{const f=e.retrieveSession(),h=f.lock;return f.lock&&delete f.lock,{session:f,lock:h}};if(Pe||(Pe=t),t!==Pe){Zt.push(t);return}if(s&&n>=Pr){Jt(e);return}let c,l=u();if(s){if(l.lock){Me(t,e,n);return}if(c=X(),a(l.session),l=u(),l.lock!==c){Me(t,e,n);return}}let d=t.process(l.session);if(s&&(l=u(),l.lock!==c)){Me(t,e,n);return}if(d&&(De(d)?i(d):(Yt(d),s?a(d):o(d))),s&&!(d&&De(d))){if(l=u(),l.lock!==c){Me(t,e,n);return}o(l.session),d=l.session}(r=t.after)===null||r===void 0||r.call(t,d||l.session),Jt(e)}function Me(t,e,n){Ee(()=>{Z(t,e,n+1)},Dr)}function Jt(t){Pe=void 0;const e=Zt.shift();e&&Z(e,t)}const Qt=he;function Mr(t){switch(t.sessionPersistence){case be.COOKIE:return Ht(t);case be.LOCAL_STORAGE:return Vt();case void 0:{let e=Ht(t);return!e&&t.allowFallbackToLocalStorage&&(e=Vt()),e}default:R.error(`Invalid session persistence \'${String(t.sessionPersistence)}\'`)}}function Fr(t,e,n,r){const s=new A,o=new A,i=new A,a=t.type===be.COOKIE?vr(e,t.cookieOptions):Ir(e),{expireSession:u}=a,c=rt(m,Qt);let l;S();const{throttled:d,cancel:f}=Gt(()=>{Z({process:E=>{if(Ue(E))return;const de=y(E);return L(de),de},after:E=>{qt(E)&&!x()&&Vi(E),l=E}},a)},Qt);function h(){Z({process:E=>x()?y(E):void 0},a)}function m(){Z({process:E=>De(E)?K(E,e):void 0,after:y},a)}function y(E){return De(E)&&(E=K(E,e)),x()&&(ve(E)?Ot():(i.notify({previousState:l,newState:E}),l=E)),E}function S(){Z({process:E=>{if(Ue(E))return K(E,e)},after:E=>{l=E}},a)}function L(E){if(Ue(E))return!1;const{trackingType:de,isTracked:Zi}=r(E[n]);E[n]=de,delete E.isExpired,Zi&&!E.id&&(E.id=X(),E.created=String(me()))}function x(){return l[n]!==void 0}function ve(E){return l.id!==E.id||l[n]!==E[n]}function Ot(){l=K(l,e),o.notify()}function Vi(E){l=E,s.notify()}function Ki(E){Z({process:de=>({...de,...E}),after:y},a)}return{expandOrRenewSession:d,expandSession:h,getSession:()=>l,renewObservable:s,expireObservable:o,sessionStateUpdateObservable:i,restartSession:S,expire:()=>{f(),u(l),y(K(l,e))},stop:()=>{Bt(c)},updateSessionState:Ki}}const lt={GRANTED:"granted",NOT_GRANTED:"not-granted"};function Nr(t){const e=new A;return{tryToInit(n){t||(t=n)},update(n){t=n,e.notify()},isGranted(){return t===lt.GRANTED},observable:e}}function J(t,e,n){if(typeof t!="object"||t===null)return JSON.stringify(t);const r=oe(Object.prototype),s=oe(Array.prototype),o=oe(Object.getPrototypeOf(t)),i=oe(t);try{return JSON.stringify(t,e,n)}catch{return"<error: unable to serialize object>"}finally{r(),s(),o(),i()}}function oe(t){const e=t,n=e.toJSON;return n?(delete e.toJSON,()=>{e.toJSON=n}):W}function dt(t){return Br(t,location.href).href}function Br(t,e){const n=$r();if(n)try{return e!==void 0?new n(t,e):new n(t)}catch(o){throw new Error(`Failed to construct URL: ${String(o)} ${J({url:t,base:e})}`)}if(e===void 0&&!/:/.test(t))throw new Error(`Invalid URL: \'${t}\'`);let r=document;const s=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(s)}return s.href=t,s}const en=URL;let Fe;function $r(){if(Fe===void 0)try{Fe=new en("http://test/path").href==="http://test/path"}catch{Fe=!1}return Fe?en:void 0}const Gr="datad0g.com",jr="dd0g-gov.com",ie="datadoghq.com",Wr="ddog-gov.com",Xr="pci.browser-intake-datadoghq.com",qr=["ddsource","ddtags"];function Se(t,e,n){const r=Yr(t,e);return{build(s,o){const i=Hr(t,e,n,s,o);return r(i)},urlPrefix:r(""),trackType:e}}function Yr(t,e){const n=`/api/v2/${e}`,r=t.proxy;if(typeof r=="string"){const o=dt(r);return i=>`${o}?ddforward=${encodeURIComponent(`${n}?${i}`)}`}if(typeof r=="function")return o=>r({path:n,parameters:o});const s=zr(e,t);return o=>`https://${s}${n}?${o}`}function zr(t,e){const{site:n=ie,internalAnalyticsSubdomain:r}=e;if(t==="logs"&&e.usePciIntake&&n===ie)return Xr;if(r&&n===ie)return`${r}.${ie}`;if(n===jr)return`http-intake.logs.${n}`;const s=n.split("."),o=s.pop();return`browser-intake-${s.join("-")}.${o}`}function Hr({clientToken:t,internalAnalyticsSubdomain:e},n,r,s,{retry:o,encoding:i}){const a=["sdk_version:6.5.0",`api:${s}`].concat(r);o&&a.push(`retry_count:${o.count}`,`retry_after:${o.lastFailureStatus}`);const u=["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=${X()}`];return i&&u.push(`dd-evp-encoding=${i}`),n==="rum"&&u.push(`batch_time=${$()}`),e&&u.reverse(),u.join("&")}const Vr=200;function Kr(t){const{env:e,service:n,version:r,datacenter:s}=t,o=[];return e&&o.push(Ne("env",e)),n&&o.push(Ne("service",n)),r&&o.push(Ne("version",r)),s&&o.push(Ne("datacenter",s)),o}function Ne(t,e){const n=Vr-t.length-1;(e.length>n||Zr(e))&&R.warn(`${t} value doesn\'t meet tag requirements and will be sanitized. ${we} ${Qe}/getting_started/tagging/#defining-tags`);const r=e.replace(/,/g,"_");return`${t}:${r}`}function Zr(t){return Jr()?new RegExp("[^\\\\p{Ll}\\\\p{Lo}0-9_:./-]","u").test(t):!1}function Jr(){try{return new RegExp("[\\\\p{Ll}]","u"),!0}catch{return!1}}function Qr(t){const e=t.site||ie,n=Kr(t),r=es(t,n);return{replica:ts(t,n),site:e,...r}}function es(t,e){return{logsEndpointBuilder:Se(t,"logs",e),rumEndpointBuilder:Se(t,"rum",e),sessionReplayEndpointBuilder:Se(t,"replay",e)}}function ts(t,e){if(!t.replica)return;const n={...t,site:ie,clientToken:t.replica.clientToken},r={logsEndpointBuilder:Se(n,"logs",e),rumEndpointBuilder:Se(n,"rum",e)};return{applicationId:t.replica.applicationId,...r}}function ns(t){return qr.every(e=>t.includes(e))}function ft(t,e){return t!=null&&typeof t!="string"?(R.error(`${e} must be defined as a string`),!1):!0}function rs(t){return t&&typeof t=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(t)?(R.error(`Site should be a valid Datadog site. ${we} ${Qe}/getting_started/site/.`),!1):!0}function Be(t,e){return t!==void 0&&!zn(t)?(R.error(`${e} Sample Rate should be a number between 0 and 100`),!1):!0}function ss(t){var e,n,r,s,o,i;if(!t||!t.clientToken){R.error("Client Token is not configured, we will not send any data.");return}if(!(!rs(t.site)||!Be(t.sessionSampleRate,"Session")||!Be(t.telemetrySampleRate,"Telemetry")||!Be(t.telemetryConfigurationSampleRate,"Telemetry Configuration")||!Be(t.telemetryUsageSampleRate,"Telemetry Usage")||!ft(t.version,"Version")||!ft(t.env,"Env")||!ft(t.service,"Service"))){if(t.trackingConsent!==void 0&&!Mt(lt,t.trackingConsent)){R.error(\'Tracking Consent should be either "granted" or "not-granted"\');return}return{beforeSend:t.beforeSend&&kt(t.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:Mr(t),sessionSampleRate:(e=t.sessionSampleRate)!==null&&e!==void 0?e:100,telemetrySampleRate:(n=t.telemetrySampleRate)!==null&&n!==void 0?n:20,telemetryConfigurationSampleRate:(r=t.telemetryConfigurationSampleRate)!==null&&r!==void 0?r:5,telemetryUsageSampleRate:(s=t.telemetryUsageSampleRate)!==null&&s!==void 0?s:5,service:t.service||void 0,silentMultipleInit:!!t.silentMultipleInit,allowUntrustedEvents:!!t.allowUntrustedEvents,trackingConsent:(o=t.trackingConsent)!==null&&o!==void 0?o:lt.GRANTED,trackAnonymousUser:(i=t.trackAnonymousUser)!==null&&i!==void 0?i:!0,storeContextsAcrossPages:!!t.storeContextsAcrossPages,batchBytesLimit:16*M,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*he,batchMessagesLimit:50,messageBytesLimit:256*M,...Qr(t)}}}function os(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 ht;(function(t){t.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",t.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(ht||(ht={}));const tn=new Set;function is(t){Array.isArray(t)&&as(t.filter(e=>Mt(ht,e)))}function as(t){t.forEach(e=>{tn.add(e)})}function cs(){return tn}const Te="?";function F(t){const e=[];let n=mt(t,"stack");const r=String(t);return n&&n.startsWith(r)&&(n=n.slice(r.length)),n&&n.split(`\n`).forEach(s=>{const o=ds(s)||hs(s)||ps(s)||ys(s);o&&(!o.func&&o.line&&(o.func=Te),e.push(o))}),{message:mt(t,"message"),name:mt(t,"name"),stack:e}}const nn="((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\\\w+\\\\.|\\\\/).*?)",ae="(?::(\\\\d+))",us=new RegExp(`^\\\\s*at (.*?) ?\\\\(${nn}${ae}?${ae}?\\\\)?\\\\s*$`,"i"),ls=new RegExp(`\\\\((\\\\S*)${ae}${ae}\\\\)`);function ds(t){const e=us.exec(t);if(!e)return;const n=e[2]&&e[2].indexOf("native")===0,r=e[2]&&e[2].indexOf("eval")===0,s=ls.exec(e[2]);return r&&s&&(e[2]=s[1],e[3]=s[2],e[4]=s[3]),{args:n?[e[2]]:[],column:e[4]?+e[4]:void 0,func:e[1]||Te,line:e[3]?+e[3]:void 0,url:n?void 0:e[2]}}const fs=new RegExp(`^\\\\s*at ?${nn}${ae}?${ae}??\\\\s*$`,"i");function hs(t){const e=fs.exec(t);if(e)return{args:[],column:e[3]?+e[3]:void 0,func:Te,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 ps(t){const e=ms.exec(t);if(e)return{args:[],column:e[4]?+e[4]:void 0,func:e[1]||Te,line:+e[3],url:e[2]}}const gs=/^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i,Es=/(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;function ys(t){const e=gs.exec(t);if(!e)return;const n=e[3]&&e[3].indexOf(" > eval")>-1,r=Es.exec(e[3]);return n&&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]||Te,line:e[4]?+e[4]:void 0,url:e[3]}}function mt(t,e){if(typeof t!="object"||!t||!(e in t))return;const n=t[e];return typeof n=="string"?n:void 0}function bs(t,e,n,r){const s=[{url:e,column:r,line:n}],{name:o,message:i}=Ts(t);return{name:o,message:i,stack:s}}const Ss=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\\s\\S]*)$/;function Ts(t){let e,n;return{}.toString.call(t)==="[object String]"&&([,e,n]=Ss.exec(t)),{name:e,message:n}}function $e(t){const n=new Error(t);n.name="HandlingStack";let r;return ge(()=>{const s=F(n);s.stack=s.stack.slice(2),r=Q(s)}),r}function Q(t){let e=rn(t);return t.stack.forEach(n=>{const r=n.func==="?"?"<anonymous>":n.func,s=n.args&&n.args.length>0?`(${n.args.join(", ")})`:"",o=n.line?`:${n.line}`:"",i=n.line&&n.column?`:${n.column}`:"";e+=`\n at ${r}${s} @ ${n.url}${o}${i}`}),e}function rn(t){return`${t.name||"Error"}: ${t.message}`}function ee(t,e,n,{computeHandlingStack:r}={}){let s=t[e];if(typeof s!="function")if(e in t&&e.startsWith("on"))s=W;else return{stop:W};let o=!1;const i=function(){if(o)return s.apply(this,arguments);const a=Array.from(arguments);let u;ge(n,null,[{target:this,parameters:a,onPostCall:l=>{u=l},handlingStack:r?$e("instrumented method"):void 0}]);const c=s.apply(this,a);return u&&ge(u,null,[c]),c};return t[e]=i,{stop:()=>{o=!0,t[e]===i&&(t[e]=s)}}}const _s=220*M,Rs="$",As=3;function N(t,e=_s){const n=oe(Object.prototype),r=oe(Array.prototype),s=[],o=new WeakMap,i=pt(t,Rs,void 0,s,o),a=JSON.stringify(i);let u=a?a.length:0;if(u>e){Et(e,"discarded",t);return}for(;s.length>0&&u<e;){const c=s.shift();let l=0;if(Array.isArray(c.source))for(let d=0;d<c.source.length;d++){const f=pt(c.source[d],c.path,d,s,o);if(f!==void 0?u+=JSON.stringify(f).length:u+=4,u+=l,l=1,u>e){Et(e,"truncated",t);break}c.target[d]=f}else for(const d in c.source)if(Object.prototype.hasOwnProperty.call(c.source,d)){const f=pt(c.source[d],c.path,d,s,o);if(f!==void 0&&(u+=JSON.stringify(f).length+l+d.length+As,l=1),u>e){Et(e,"truncated",t);break}c.target[d]=f}}return n(),r(),i}function pt(t,e,n,r,s){const o=xs(t);if(!o||typeof o!="object")return vs(o);const i=gt(o);if(i!=="[Object]"&&i!=="[Array]"&&i!=="[Error]")return i;const a=t;if(s.has(a))return`[Reference seen at ${s.get(a)}]`;const u=n!==void 0?`${e}.${n}`:e,c=Array.isArray(o)?[]:{};return s.set(a,u),r.push({source:o,target:c,path:u}),c}function vs(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 gt(t){try{if(t instanceof Event)return ws(t);if(t instanceof RegExp)return`[RegExp] ${t.toString()}`;const n=Object.prototype.toString.call(t).match(/\\[object (.*)\\]/);if(n&&n[1])return`[${n[1]}]`}catch{}return"[Unserializable]"}function ws(t){return{type:t.type,isTrusted:t.isTrusted,currentTarget:t.currentTarget?gt(t.currentTarget):null,target:t.target?gt(t.target):null}}function xs(t){const e=t;if(e&&typeof e.toJSON=="function")try{return e.toJSON()}catch{}return t}function Et(t,e,n){R.warn(`The data provided has been ${e} as it is over the limit of ${t} characters:`,n)}const sn="No stack, consider using an instance of Error";function on({stackTrace:t,originalError:e,handlingStack:n,componentStack:r,startClocks:s,nonErrorPrefix:o,source:i,handling:a}){const u=q(e),c=Cs(t,u,o,e),l=Ls(u,t)?Q(t):sn,d=u?un(e,i):void 0,f=t?t.name:void 0,h=an(e),m=cn(e);return{startClocks:s,source:i,handling:a,handlingStack:n,componentStack:r,originalError:e,type:f,message:c,stack:l,causes:d,fingerprint:h,context:m}}function Cs(t,e,n,r){return t!=null&&t.message&&(t!=null&&t.name)?t.message:e?"Empty message":`${n} ${J(N(r))}`}function Ls(t,e){return e===void 0?!1:t?!0:e.stack.length>0&&(e.stack.length>1||e.stack[0].url!==void 0)}function an(t){return q(t)&&"dd_fingerprint"in t?String(t.dd_fingerprint):void 0}function cn(t){if(t!==null&&typeof t=="object"&&"dd_context"in t)return t.dd_context}function Os(t){var e;return(e=/@ (.+)/.exec(t))===null||e===void 0?void 0:e[1]}function q(t){return t instanceof Error||Object.prototype.toString.call(t)==="[object Error]"}function un(t,e){let n=t;const r=[];for(;q(n==null?void 0:n.cause)&&r.length<10;){const s=F(n.cause);r.push({message:n.cause.message,source:e,type:s==null?void 0:s.name,stack:Q(s)}),n=n.cause}return r.length?r:void 0}const I={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function Is(t){const e=(s,o)=>{const i=on({stackTrace:s,originalError:o,startClocks:G(),nonErrorPrefix:"Uncaught",source:I.SOURCE,handling:"unhandled"});t.notify(i)},{stop:n}=ks(e),{stop:r}=Us(e);return{stop:()=>{n(),r()}}}function ks(t){return ee(window,"onerror",({parameters:[e,n,r,s,o]})=>{let i;q(o)?i=F(o):i=bs(e,n,r,s),t(i,o??e)})}function Us(t){return ee(window,"onunhandledrejection",({parameters:[e]})=>{const n=e.reason||"Empty reason",r=F(n);t(r,n)})}function Ds(t){const e={version:"6.5.0",onReady(n){n()},...t};return Object.defineProperty(e,"_setDebug",{get(){return rr},enumerable:!1}),e}function Ps(t,e,n){const r=t[e];r&&!r.q&&r.version&&R.warn("SDK is loaded more than once. This is unsupported and might have unexpected behavior."),t[e]=n,r&&r.q&&r.q.forEach(s=>kt(s,"onReady callback threw an error:")())}function ln(t,e){e.silentMultipleInit||R.error(`${t} is already initialized.`)}function te(t,e,n,r,s){return yt(t,e,[n],r,s)}function yt(t,e,n,r,{once:s,capture:o,passive:i}={}){const a=b(f=>{!f.isTrusted&&!f.__ddIsTrusted&&!t.allowUntrustedEvents||(s&&d(),r(f))}),u=i?{capture:o,passive:i}:o,c=window.EventTarget&&e instanceof EventTarget?window.EventTarget.prototype:e,l=re(c,"addEventListener");n.forEach(f=>l.call(e,f,a,u));function d(){const f=re(c,"removeEventListener");n.forEach(h=>f.call(e,h,a,u))}return{stop:d}}const Ge={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function Ms(t,e){const n=[];e.includes(Ge.cspViolation)&&n.push(Ns(t));const r=e.filter(s=>s!==Ge.cspViolation);return r.length&&n.push(Fs(r)),$t(...n)}function Fs(t){return new A(e=>{if(!window.ReportingObserver)return;const n=b((s,o)=>s.forEach(i=>e.notify(Bs(i)))),r=new window.ReportingObserver(n,{types:t,buffered:!0});return r.observe(),()=>{r.disconnect()}})}function Ns(t){return new A(e=>{const{stop:n}=te(t,document,"securitypolicyviolation",r=>{e.notify($s(r))});return n})}function Bs(t){const{type:e,body:n}=t;return dn({type:n.id,message:`${e}: ${n.message}`,originalError:t,stack:fn(n.id,n.message,n.sourceFile,n.lineNumber,n.columnNumber)})}function $s(t){const e=`\'${t.blockedURI}\' blocked by \'${t.effectiveDirective}\' directive`;return dn({type:t.effectiveDirective,message:`${Ge.cspViolation}: ${e}`,originalError:t,csp:{disposition:t.disposition},stack:fn(t.effectiveDirective,t.originalPolicy?`${e} of the policy "${cr(t.originalPolicy,100,"...")}"`:"no policy",t.sourceFile,t.lineNumber,t.columnNumber)})}function dn(t){return{startClocks:G(),source:I.REPORT,handling:"unhandled",...t}}function fn(t,e,n,r,s){return n?Q({name:t,message:e,stack:[{func:"?",url:n,line:r??void 0,column:s??void 0}]}):void 0}function hn(t,e){const n=window.__ddBrowserSdkExtensionCallback;n&&n({type:t,payload:e})}function mn(t){return t===null?"null":Array.isArray(t)?"array":typeof t}function je(t,e,n=Gs()){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(n.hasAlreadyBeenSeen(e))return;if(Array.isArray(e)){const s=Array.isArray(t)?t:[];for(let o=0;o<e.length;++o)s[o]=je(s[o],e[o],n);return s}const r=mn(t)==="object"?t:{};for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(r[s]=je(r[s],e[s],n));return r}function pn(t){return je(void 0,t)}function ce(...t){let e;for(const n of t)n!=null&&(e=je(e,n));return e}function Gs(){if(typeof WeakSet<"u"){const e=new WeakSet;return{hasAlreadyBeenSeen(n){const r=e.has(n);return r||e.add(n),r}}}const t=[];return{hasAlreadyBeenSeen(e){const n=t.indexOf(e)>=0;return n||t.push(e),n}}}function js(){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 Ws(t){const e=new Set;return t.forEach(n=>e.add(n)),Array.from(e)}function gn(t,e){const n=t.indexOf(e);n>=0&&t.splice(n,1)}const Xs=500;function En(){const t=[];return{add:s=>{t.push(s)>Xs&&t.splice(0,1)},remove:s=>{gn(t,s)},drain:s=>{t.forEach(o=>o(s)),t.length=0}}}const ne={log:"log",configuration:"configuration",usage:"usage"},qs=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],Ys=[Wr];let yn=En(),ue=t=>{yn.add(()=>ue(t))};function zs(t,e){let n;const r=new A,s=new Set,o=!Ys.includes(e.site)&&xe(e.telemetrySampleRate),i={[ne.log]:o,[ne.configuration]:o&&xe(e.telemetryConfigurationSampleRate),[ne.usage]:o&&xe(e.telemetryUsageSampleRate)},a=Hs();ue=c=>{const l=J(c);if(i[c.type]&&s.size<e.maxTelemetryEventsPerPage&&!s.has(l)){const d=u(t,c,a);r.notify(d),hn("telemetry",d),s.add(l)}},nr(Sn);function u(c,l,d){return ce({type:"telemetry",date:$(),service:c,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:ce(l,{runtime_env:d,connectivity:js(),sdk_setup:"npm"}),experimental_features:Array.from(cs())},n!==void 0?n():{})}return{setContextProvider:c=>{n=c},observable:r,enabled:o}}function Hs(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function Vs(){yn.drain()}function Ks(t){return t.site===Gr}function bn(t,e){nt(_.debug,t,e),ue({type:ne.log,message:t,status:"debug",...e})}function Sn(t,e){ue({type:ne.log,status:"error",...Qs(t),...e})}function Zs(t){ue({type:ne.configuration,configuration:t})}function Js(t){ue({type:ne.usage,usage:t})}function Qs(t){if(q(t)){const e=F(t);return{error:{kind:e.name,stack:Q(eo(e))},message:e.message}}return{error:{stack:sn},message:`Uncaught ${J(t)}`}}function eo(t){return t.stack=t.stack.filter(e=>!e.url||qs.some(n=>e.url.startsWith(n))),t}const _e=1/0,to=H;let Re=null;const We=new Set;function no(){We.forEach(t=>t())}function ro({expireDelay:t,maxEntries:e}){let n=[];const r=[];Re||(Re=rt(()=>no(),to));const s=()=>{const h=Ce()-t;for(;n.length>0&&n[n.length-1].endTime<h;){const m=n.pop();m&&r.push(m.startTime)}};We.add(s);function o(h,m){const y={value:h,startTime:m,endTime:_e,remove:()=>{gn(n,y)},close:S=>{y.endTime=S}};return e&&n.length>=e&&n.pop(),n.unshift(y),y}function i(h=_e,m={returnInactive:!1}){for(const y of n)if(y.startTime<=h){if(m.returnInactive||h<=y.endTime)return y.value;break}}function a(h){const m=n[0];m&&m.endTime===_e&&m.close(h)}function u(h=_e,m=0){const y=Jn(h,m);return n.filter(S=>S.startTime<=y&&h<=S.endTime).map(S=>S.value)}function c(){return n.map(({startTime:h,endTime:m,value:y})=>({startTime:h,endTime:m===_e?"Infinity":m,value:y}))}function l(){return r}function d(){n=[]}function f(){We.delete(s),We.size===0&&Re&&(Bt(Re),Re=null)}return{add:o,find:i,closeActive:a,findAll:u,reset:d,stop:f,getAllEntries:c,getDeletedEntries:l}}const so=H,oo=at;function io(t,e,n,r){const s=new A,o=new A,i=Fr(t.sessionStoreStrategyType,t,e,n),a=ro({expireDelay:oo});i.renewObservable.subscribe(()=>{a.add(u(),Ce()),s.notify()}),i.expireObservable.subscribe(()=>{o.notify(),a.closeActive(Ce())}),i.expandOrRenewSession(),a.add(u(),Kn().relative),r.observable.subscribe(()=>{r.isGranted()?i.expandOrRenewSession():i.expire()}),ao(t,()=>{r.isGranted()&&i.expandOrRenewSession()}),co(t,()=>i.expandSession()),uo(t,()=>i.restartSession());function u(){return{id:i.getSession().id,trackingType:i.getSession()[e],isReplayForced:!!i.getSession().forcedReplay,anonymousId:i.getSession().anonymousId}}return{findSession:(c,l)=>a.find(c,l),renewObservable:s,expireObservable:o,sessionStateUpdateObservable:i.sessionStateUpdateObservable,expire:i.expire,updateSessionState:i.updateSessionState}}function ao(t,e){yt(t,window,["click","touchstart","keydown","scroll"],e,{capture:!0,passive:!0})}function co(t,e){const n=()=>{document.visibilityState==="visible"&&e()};te(t,document,"visibilitychange",n),rt(n,so)}function uo(t,e){te(t,window,"resume",e,{capture:!0})}function Tn(t){return t>=500}function lo(t){try{return t.clone()}catch{return}}const fo=80*M,ho=32,_n=3*Pt,mo=H,Rn=he;function An(t,e,n,r,s){e.transportStatus===0&&e.queuedPayloads.size()===0&&e.bandwidthMonitor.canHandle(t)?wn(t,e,n,{onSuccess:()=>xn(0,e,n,r,s),onFailure:()=>{e.queuedPayloads.enqueue(t),vn(e,n,r,s)}}):e.queuedPayloads.enqueue(t)}function vn(t,e,n,r){t.transportStatus===2&&Ee(()=>{const s=t.queuedPayloads.first();wn(s,t,e,{onSuccess:()=>{t.queuedPayloads.dequeue(),t.currentBackoffTime=Rn,xn(1,t,e,n,r)},onFailure:()=>{t.currentBackoffTime=Math.min(mo,t.currentBackoffTime*2),vn(t,e,n,r)}})},t.currentBackoffTime)}function wn(t,e,n,{onSuccess:r,onFailure:s}){e.bandwidthMonitor.add(t),n(t,o=>{e.bandwidthMonitor.remove(t),po(o)?(e.transportStatus=e.bandwidthMonitor.ongoingRequestCount>0?1:2,t.retry={count:t.retry?t.retry.count+1:1,lastFailureStatus:o.status},s()):(e.transportStatus=0,r())})}function xn(t,e,n,r,s){t===0&&e.queuedPayloads.isFull()&&!e.queueFullReported&&(s({message:`Reached max ${r} events size queued for upload: ${_n/Pt}MiB`,source:I.AGENT,startClocks:G()}),e.queueFullReported=!0);const o=e.queuedPayloads;for(e.queuedPayloads=Cn();o.size()>0;)An(o.dequeue(),e,n,r,s)}function po(t){return t.type!=="opaque"&&(t.status===0&&!navigator.onLine||t.status===408||t.status===429||Tn(t.status))}function go(){return{transportStatus:0,currentBackoffTime:Rn,bandwidthMonitor:Eo(),queuedPayloads:Cn(),queueFullReported:!1}}function Cn(){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>=_n}}}function Eo(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(t){return this.ongoingRequestCount===0||this.ongoingByteCount+t.bytesCount<=fo&&this.ongoingRequestCount<ho},add(t){this.ongoingRequestCount+=1,this.ongoingByteCount+=t.bytesCount},remove(t){this.ongoingRequestCount-=1,this.ongoingByteCount-=t.bytesCount}}}function yo(t,e,n){const r=go(),s=(o,i)=>To(t,e,o,i);return{send:o=>{An(o,r,s,t.trackType,n)},sendOnExit:o=>{bo(t,e,o)}}}function bo(t,e,n){if(!!navigator.sendBeacon&&n.bytesCount<e)try{const o=t.build("beacon",n);if(navigator.sendBeacon(o,n.data))return}catch(o){So(o)}const s=t.build("xhr",n);bt(s,n.data)}let Ln=!1;function So(t){Ln||(Ln=!0,Sn(t))}function To(t,e,n,r){if(_o()&&n.bytesCount<e){const o=t.build("fetch",n);fetch(o,{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=t.build("xhr",n);bt(i,n.data,r)}))}else{const o=t.build("xhr",n);bt(o,n.data,r)}}function _o(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function bt(t,e,n){const r=new XMLHttpRequest;r.open("POST",t,!0),e instanceof Blob&&r.setRequestHeader("Content-Type",e.type),te({allowUntrustedEvents:!0},r,"loadend",()=>{n==null||n({status:r.status})},{once:!0}),r.send(e)}function St(){const t=Ro();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,n,r){const s=r?{id:r}:void 0;t.send(JSON.stringify({eventType:e,event:n,view:s}))}}}function Xe(t){var e;t===void 0&&(t=(e=j().location)===null||e===void 0?void 0:e.hostname);const n=St();return!!n&&n.getAllowedWebViewHosts().some(r=>t===r||t.endsWith(`.${r}`))}function Ro(){return j().DatadogEventBridge}const qe={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function Ao(t){return new A(e=>{const{stop:n}=yt(t,window,["visibilitychange","freeze"],s=>{s.type==="visibilitychange"&&document.visibilityState==="hidden"?e.notify({reason:qe.HIDDEN}):s.type==="freeze"&&e.notify({reason:qe.FROZEN})},{capture:!0}),r=te(t,window,"beforeunload",()=>{e.notify({reason:qe.UNLOADING})}).stop;return()=>{n(),r()}})}function vo(t){return ke(qe).includes(t)}function wo({encoder:t,request:e,flushController:n,messageBytesLimit:r}){let s={};const o=n.flushObservable.subscribe(d=>l(d));function i(d,f,h){n.notifyBeforeAddMessage(f),h!==void 0?(s[h]=d,n.notifyAfterAddMessage()):t.write(t.isEmpty?d:`\n${d}`,m=>{n.notifyAfterAddMessage(m-f)})}function a(d){return d!==void 0&&s[d]!==void 0}function u(d){const f=s[d];delete s[d];const h=t.estimateEncodedBytesCount(f);n.notifyAfterRemoveMessage(h)}function c(d,f){const h=J(d),m=t.estimateEncodedBytesCount(h);if(m>=r){R.warn(`Discarded a message whose size was bigger than the maximum allowed size ${r}KB. ${we} ${It}/#technical-limitations`);return}a(f)&&u(f),i(h,m,f)}function l(d){const f=ke(s).join(`\n`);s={};const h=vo(d.reason),m=h?e.sendOnExit:e.send;if(h&&t.isAsync){const y=t.finishSync();y.outputBytesCount&&m(On(y));const S=[y.pendingData,f].filter(Boolean).join(`\n`);S&&m({data:S,bytesCount:tt(S)})}else f&&t.write(t.isEmpty?f:`\n${f}`),t.finish(y=>{m(On(y))})}return{flushController:n,add:c,upsert:c,stop:o.unsubscribe}}function On(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 xo({messagesLimit:t,bytesLimit:e,durationLimit:n,pageExitObservable:r,sessionExpireObservable:s}){const o=r.subscribe(m=>l(m.reason)),i=s.subscribe(()=>l("session_expire")),a=new A(()=>()=>{o.unsubscribe(),i.unsubscribe()});let u=0,c=0;function l(m){if(c===0)return;const y=c,S=u;c=0,u=0,h(),a.notify({reason:m,messagesCount:y,bytesCount:S})}let d;function f(){d===void 0&&(d=Ee(()=>{l("duration_limit")},n))}function h(){Nt(d),d=void 0}return{flushObservable:a,get messagesCount(){return c},notifyBeforeAddMessage(m){u+m>=e&&l("bytes_limit"),c+=1,u+=m,f()},notifyAfterAddMessage(m=0){u+=m,c>=t?l("messages_limit"):u>=e&&l("bytes_limit")},notifyAfterRemoveMessage(m){u-=m,c-=1,c===0&&h()}}}function In(t,e,n,r,s,o,i=wo){const a=c(t,e),u=n&&c(t,n);function c(l,{endpoint:d,encoder:f}){return i({encoder:f,request:yo(d,l.batchBytesLimit,r),flushController:xo({messagesLimit:l.batchMessagesLimit,bytesLimit:l.batchBytesLimit,durationLimit:l.flushTimeout,pageExitObservable:s,sessionExpireObservable:o}),messageBytesLimit:l.messageBytesLimit})}return{flushObservable:a.flushController.flushObservable,add(l,d=!0){a.add(l),u&&d&&u.add(n.transformMessage?n.transformMessage(l):l)},upsert:(l,d)=>{a.upsert(l,d),u&&u.upsert(n.transformMessage?n.transformMessage(l):l,d)},stop:()=>{a.stop(),u&&u.stop()}}}function Ye(){let t="",e=0;return{isAsync:!1,get isEmpty(){return!t},write(n,r){const s=tt(n);e+=s,t+=n,r&&r(s)},finish(n){n(this.finishSync())},finishSync(){const n={output:t,outputBytesCount:e,rawBytesCount:e,pendingData:""};return t="",e=0,n},estimateEncodedBytesCount(n){return n.length}}}class Co{constructor(){this.callbacks={}}notify(e,n){const r=this.callbacks[e];r&&r.forEach(s=>s(n))}subscribe(e,n){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(n),{unsubscribe:()=>{this.callbacks[e]=this.callbacks[e].filter(r=>n!==r)}}}}function Lo(t,e,n){let r=0,s=!1;return{isLimitReached(){if(r===0&&Ee(()=>{r=0},H),r+=1,r<=e||s)return s=!1,!1;if(r===e+1){s=!0;try{n({message:`Reached max number of ${t}s by minute: ${e}`,source:I.AGENT,startClocks:G()})}finally{s=!1}}return!0}}}let Tt;const _t=new WeakMap;function Oo(t){return Tt||(Tt=Io(t)),Tt}function Io(t){return new A(e=>{const{stop:n}=ee(XMLHttpRequest.prototype,"open",ko),{stop:r}=ee(XMLHttpRequest.prototype,"send",o=>{Uo(o,t,e)},{computeHandlingStack:!0}),{stop:s}=ee(XMLHttpRequest.prototype,"abort",Do);return()=>{n(),r(),s()}})}function ko({target:t,parameters:[e,n]}){_t.set(t,{state:"open",method:String(e).toUpperCase(),url:dt(String(n))})}function Uo({target:t,handlingStack:e},n,r){const s=_t.get(t);if(!s)return;const o=s;o.state="start",o.startClocks=G(),o.isAborted=!1,o.xhr=t,o.handlingStack=e;let i=!1;const{stop:a}=ee(t,"onreadystatechange",()=>{t.readyState===XMLHttpRequest.DONE&&u()}),u=()=>{if(c(),a(),i)return;i=!0;const l=s;l.state="complete",l.duration=Zn(o.startClocks.timeStamp,$()),l.status=t.status,r.notify(tr(l))},{stop:c}=te(n,t,"loadend",u);r.notify(o)}function Do({target:t}){const e=_t.get(t);e&&(e.isAborted=!0)}let Rt;function kn(){return Rt||(Rt=Po()),Rt}function Po(){return new A(t=>{if(!window.fetch)return;const{stop:e}=ee(window,"fetch",n=>Mo(n,t),{computeHandlingStack:!0});return e})}function Mo({parameters:t,onPostCall:e,handlingStack:n},r){const[s,o]=t;let i=o&&o.method;i===void 0&&s instanceof Request&&(i=s.method);const a=i!==void 0?String(i).toUpperCase():"GET",u=s instanceof Request?s.url:dt(String(s)),c=G(),l={state:"start",init:o,input:s,method:a,startClocks:c,url:u,handlingStack:n};r.notify(l),t[0]=l.input,t[1]=l.init,e(d=>Fo(r,d,l))}function Fo(t,e,n){const r=n;function s(o){r.state="resolve",Object.assign(r,o),t.notify(r)}e.then(b(o=>{s({response:o,responseType:o.type,status:o.status,isAborted:!1})}),b(o=>{var i,a;s({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 At={};function No(t){const e=t.map(n=>(At[n]||(At[n]=Bo(n)),At[n]));return $t(...e)}function Bo(t){return new A(e=>{const n=D[t];return D[t]=(...r)=>{n.apply(console,r);const s=$e("console error");ge(()=>{e.notify($o(r,t,s))})},()=>{D[t]=n}})}function $o(t,e,n){const r=t.map(o=>Go(o)).join(" ");let s;if(e===_.error){const o=t.find(q);s={stack:o?Q(F(o)):void 0,fingerprint:an(o),causes:o?un(o,"console"):void 0,startClocks:G(),message:r,source:I.CONSOLE,handling:"handled",handlingStack:n,context:cn(o)}}return{api:e,message:r,error:s,handlingStack:n}}function Go(t){return typeof t=="string"?N(t):q(t)?rn(F(t)):J(N(t),void 0,2)}function jo(t){const e=mn(t)==="object";return e||R.error("Unsupported context:",t),e}function vt(t,e,n){const r={...t};for(const[s,{required:o,type:i}]of Object.entries(e))i==="string"&&s in r&&(r[s]=String(r[s])),o&&!(s in t)&&R.warn(`The property ${s} of ${n} is required; context will not be sent to the intake.`);return r}function ze(t="",{customerDataTracker:e,propertiesConfig:n={}}={}){let r={};const s=new A,o={getContext:()=>pn(r),setContext:i=>{jo(i)?(r=N(vt(i,n,t)),e==null||e.updateCustomerData(r)):o.clearContext(),s.notify()},setContextProperty:(i,a)=>{r=N(vt({...r,[i]:a},n,t)),e==null||e.updateCustomerData(r),s.notify()},removeContextProperty:i=>{delete r[i],e==null||e.updateCustomerData(r),vt(r,n,t),s.notify()},clearContext:()=>{r={},e==null||e.resetCustomerData(),s.notify()},changeObservable:s};return o}const Wo="_dd_c",Xo=[];function wt(t,e,n,r){const s=qo(n,r);Xo.push(te(t,window,"storage",({key:c})=>{s===c&&i()})),e.changeObservable.subscribe(a);const o=ce(u(),e.getContext());pe(o)||e.setContext(o);function i(){e.setContext(u())}function a(){localStorage.setItem(s,JSON.stringify(e.getContext()))}function u(){const c=localStorage.getItem(s);return c?JSON.parse(c):{}}}function qo(t,e){return`${Wo}_${t}_${e}`}const Yo=3*M,zo=16*M,Ho=200;function Vo(t=2){const e=new Map;let n=!1;function r(s=0){if(n||t===0)return;const o=t===2?Yo:zo;let i=s;e.forEach(a=>{i+=a.getBytesCount()}),i>o&&(Ko(o),n=!0)}return{createDetachedTracker:()=>{const s=Un(()=>r(s.getBytesCount()));return s},getOrCreateTracker:s=>(e.has(s)||e.set(s,Un(r)),e.get(s)),setCompressionStatus:s=>{t===0&&(t=s,r())},getCompressionStatus:()=>t,stop:()=>{e.forEach(s=>s.stop()),e.clear()}}}function Un(t){let e=0;const{throttled:n,cancel:r}=Gt(o=>{e=tt(J(o)),t()},Ho),s=()=>{r(),e=0};return{updateCustomerData:o=>{pe(o)?s():n(o)},resetCustomerData:s,getBytesCount:()=>e,stop:()=>{r()}}}function Ko(t){R.warn(`Customer data exceeds the recommended ${t/M}KiB threshold. ${we} ${It}/#customer-data-exceeds-the-recommended-threshold-warning`)}function Zo(t,e,n){const r=t.getReader(),s=[];let o=0;i();function i(){r.read().then(b(u=>{if(u.done){a();return}s.push(u.value),o+=u.value.length,o>n.bytesLimit?a():i()}),b(u=>e(u)))}function a(){r.cancel().catch(W);let u,c;{let l;if(s.length===1)l=s[0];else{l=new Uint8Array(o);let d=0;s.forEach(f=>{l.set(f,d),d+=f.length})}u=l.slice(0,n.bytesLimit),c=l.length>n.bytesLimit}e(void 0,u,c)}}const Jo="datadog-synthetics-public-id",Qo="datadog-synthetics-result-id",ei="datadog-synthetics-injects-rum";function Dn(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||V(ei))}function ti(){const t=window._DATADOG_SYNTHETICS_PUBLIC_ID||V(Jo);return typeof t=="string"?t:void 0}function ni(){const t=window._DATADOG_SYNTHETICS_RESULT_ID||V(Qo);return typeof t=="string"?t:void 0}function He(t,e,n){const r=n.getHandler(),s=Array.isArray(r)?r:[r];return Pn[t]>=Pn[n.getLevel()]&&s.includes(e)}const g={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},Pn={[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 Ve(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 ri=function(t,e,n,r){var s=arguments.length,o=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(o=(s<3?i(o):s>3?i(e,n,o):i(e,n))||o);return s>3&&o&&Object.defineProperty(e,n,o),o};const Ae={console:"console",http:"http",silent:"silent"},si=Object.keys(g);let k=class{constructor(e,n,r,s=Ae.http,o=g.debug,i={}){this.handleLogStrategy=e,this.handlerType=s,this.level=o,this.contextManager=ze("logger",{customerDataTracker:n}),this.contextManager.setContext(i),r&&this.contextManager.setContextProperty("logger",{name:r})}logImplementation(e,n,r=g.info,s,o){const i=N(n);let a;if(s!=null){const u=on({stackTrace:q(s)?F(s):void 0,originalError:s,nonErrorPrefix:"Provided",source:I.LOGGER,handling:"handled",startClocks:G()});a=ce({error:Ve(u,{includeMessage:!0})},i)}else a=i;this.handleLogStrategy({message:N(e),context:a,status:r},this,o)}log(e,n,r=g.info,s){let o;He(r,Ae.http,this)&&(o=$e("log")),this.logImplementation(e,n,r,s,o)}setContext(e){this.contextManager.setContext(e)}getContext(){return this.contextManager.getContext()}setContextProperty(e,n){this.contextManager.setContextProperty(e,n)}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}};ri([sr],k.prototype,"logImplementation",null),k.prototype.ok=B(g.ok),k.prototype.debug=B(g.debug),k.prototype.info=B(g.info),k.prototype.notice=B(g.notice),k.prototype.warn=B(g.warn),k.prototype.error=B(g.error),k.prototype.critical=B(g.critical),k.prototype.alert=B(g.alert),k.prototype.emerg=B(g.emerg);function B(t){return function(e,n,r){let s;He(t,Ae.http,this)&&(s=$e("log")),this.logImplementation(e,n,t,r,s)}}function oi(t,e,n){return{view:{referrer:document.referrer,url:window.location.href},context:t.getContext(),user:e.getContext(),account:n.getContext()}}const ii=32*M;function ai(t){t.usePciIntake===!0&&t.site&&t.site!=="datadoghq.com"&&R.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");const e=ss(t),n=Mn(t.forwardConsoleLogs,ke(_),"Forward Console Logs"),r=Mn(t.forwardReports,ke(Ge),"Forward Reports");if(!(!e||!n||!r))return t.forwardErrorsToLogs&&!n.includes(_.error)&&n.push(_.error),{forwardErrorsToLogs:t.forwardErrorsToLogs!==!1,forwardConsoleLogs:n,forwardReports:r,requestErrorResponseLengthLimit:ii,...e}}function Mn(t,e,n){if(t===void 0)return[];if(!(t==="all"||Array.isArray(t)&&t.every(r=>e.includes(r)))){R.error(`${n} should be "all" or an array with allowed values "${e.join(\'", "\')}"`);return}return t==="all"?e:Ws(t)}function ci(t){const e=os(t);return{forward_errors_to_logs:t.forwardErrorsToLogs,forward_console_logs:t.forwardConsoleLogs,forward_reports:t.forwardReports,use_pci_intake:t.usePciIntake,...e}}function ui(t,e,n){const r=En();let s,o;const i=e.observable.subscribe(a);function a(){if(!o||!s||!e.isGranted())return;i.unsubscribe();const u=n(s,o);r.drain(u)}return{init(u){if(!u){R.error("Missing configuration");return}if(is(u.enableExperimentalFeatures),Xe()&&(u=li(u)),s=u,o){ln("DD_LOGS",u);return}const c=ai(u);c&&(o=c,kn().subscribe(W),e.tryToInit(c.trackingConsent),a())},get initConfiguration(){return s},getInternalContext:W,handleLog(u,c,l,d=t(),f=$()){r.add(h=>h.handleLog(u,c,l,d,f))}}}function li(t){return{...t,clientToken:"empty"}}const xt="logs";function di(t){const e=Vo(),n=ze("global context",{customerDataTracker:e.getOrCreateTracker(2)}),r=ze("user",{customerDataTracker:e.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),s=ze("account",{customerDataTracker:e.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),o=Nr();function i(){return oi(n,r,s)}let a=ui(i,o,(l,d)=>{l.storeContextsAcrossPages&&(wt(d,n,xt,2),wt(d,r,xt,1),wt(d,s,xt,4));const f=t(l,d,i,o);return a=fi(l,f),f});const u={},c=new k((...l)=>a.handleLog(...l),e.createDetachedTracker());return Ds({logger:c,init:b(l=>a.init(l)),setTrackingConsent:b(l=>{o.update(l),Js({feature:"set-tracking-consent",tracking_consent:l})}),getGlobalContext:b(()=>n.getContext()),setGlobalContext:b(l=>n.setContext(l)),setGlobalContextProperty:b((l,d)=>n.setContextProperty(l,d)),removeGlobalContextProperty:b(l=>n.removeContextProperty(l)),clearGlobalContext:b(()=>n.clearContext()),createLogger:b((l,d={})=>(u[l]=new k((...f)=>a.handleLog(...f),e.createDetachedTracker(),N(l),d.handler,d.level,N(d.context)),u[l])),getLogger:b(l=>u[l]),getInitConfiguration:b(()=>pn(a.initConfiguration)),getInternalContext:b(l=>a.getInternalContext(l)),setUser:b(r.setContext),getUser:b(r.getContext),setUserProperty:b(r.setContextProperty),removeUserProperty:b(r.removeContextProperty),clearUser:b(r.clearContext),setAccount:b(s.setContext),getAccount:b(s.getContext),setAccountProperty:b(s.setContextProperty),removeAccountProperty:b(s.removeContextProperty),clearAccount:b(s.clearContext)})}function fi(t,e){return{init:n=>{ln("DD_LOGS",n)},initConfiguration:t,...e}}const hi="logs";function mi(t,e){const n=io(t,hi,r=>gi(t,r),e);return{findTrackedSession:(r,s={returnInactive:!1})=>{const o=n.findSession(r,s);return o&&o.trackingType==="1"?{id:o.id,anonymousId:o.anonymousId}:void 0},expireObservable:n.expireObservable}}function pi(t){const n=Fn(t)==="1"?{}:void 0;return{findTrackedSession:()=>n,expireObservable:new A}}function Fn(t){return xe(t.sessionSampleRate)?"1":"0"}function gi(t,e){const n=Ei(e)?e:Fn(t);return{trackingType:n,isTracked:n==="1"}}function Ei(t){return t==="0"||t==="1"}let Nn=!1;function Ke(t){const e=window;if(Dn()){const r=n(e.DD_RUM_SYNTHETICS);return!r&&!Nn&&(Nn=!0,bn("Logs sent before RUM is injected by the synthetics worker",{testId:ti(),resultId:ni()})),r}return n(e.DD_RUM);function n(r){if(r&&r.getInternalContext)return r.getInternalContext(t)}}function yi(t,e,n,r,s){const o=si.concat(["custom"]),i={};o.forEach(a=>{i[a]=Lo(a,e.eventRateLimiterThreshold,s)}),n.subscribe(0,({rawLogsEvent:a,messageContext:u=void 0,savedCommonContext:c=void 0,domainContext:l})=>{var d,f;const h=Qn(a.date),m=t.findTrackedSession(h);if(!t.findTrackedSession(h,{returnInactive:!0}))return;const S=c||r();let L;!pe(S.account)&&S.account.id&&(L=S.account),m&&m.anonymousId&&!S.user.anonymous_id&&(S.user.anonymous_id=m.anonymousId);const x=ce({service:e.service,session_id:m?m.id:void 0,session:m?{id:m.id}:void 0,usr:pe(S.user)?void 0:S.user,account:L,view:S.view},S.context,Ke(h),a,u);((d=e.beforeSend)===null||d===void 0?void 0:d.call(e,x,l))===!1||x.origin!==I.AGENT&&((f=i[x.status])!==null&&f!==void 0?f:i.custom).isLimitReached()||n.notify(1,x)})}const bi={[_.log]:g.info,[_.debug]:g.debug,[_.info]:g.info,[_.warn]:g.warn,[_.error]:g.error};function Si(t,e){const n=No(t.forwardConsoleLogs).subscribe(r=>{var s;const o={rawLogsEvent:{date:$(),message:r.message,origin:I.CONSOLE,error:r.error&&Ve(r.error),status:bi[r.api]},messageContext:(s=r.error)===null||s===void 0?void 0:s.context,domainContext:{handlingStack:r.handlingStack}};e.notify(0,o)});return{stop:()=>{n.unsubscribe()}}}function Ti(t,e){const n=Ms(t,t.forwardReports).subscribe(r=>{let s=r.message,o;const i=r.originalError.type==="deprecation"?g.warn:g.error;i===g.error?o=Ve(r):r.stack&&(s+=` Found in ${Os(r.stack)}`),e.notify(0,{rawLogsEvent:{date:$(),message:s,origin:I.REPORT,error:o,status:i}})});return{stop:()=>{n.unsubscribe()}}}function _i(t,e){if(!t.forwardErrorsToLogs)return{stop:W};const n=Oo(t).subscribe(o=>{o.state==="complete"&&s("xhr",o)}),r=kn().subscribe(o=>{o.state==="resolve"&&s("fetch",o)});function s(o,i){!ns(i.url)&&(wi(i)||Tn(i.status))&&("xhr"in i?Ri(i.xhr,t,a):i.response?vi(i.response,t,a):i.error&&Ai(i.error,t,a));function a(u){const c={isAborted:i.isAborted,handlingStack:i.handlingStack};e.notify(0,{rawLogsEvent:{message:`${xi(o)} error ${i.method} ${i.url}`,date:i.startClocks.timeStamp,error:{stack:u||"Failed to load",handling:void 0},http:{method:i.method,status_code:i.status,url:i.url},status:g.error,origin:I.NETWORK},domainContext:c})}}return{stop:()=>{n.unsubscribe(),r.unsubscribe()}}}function Ri(t,e,n){typeof t.response=="string"?n(Ct(t.response,e)):n(t.response)}function Ai(t,e,n){n(Ct(Q(F(t)),e))}function vi(t,e,n){const r=lo(t);!r||!r.body?n():window.TextDecoder?Ci(r.body,e.requestErrorResponseLengthLimit,(s,o)=>{n(s?`Unable to retrieve response: ${s}`:o)}):r.text().then(b(s=>n(Ct(s,e))),b(s=>n(`Unable to retrieve response: ${s}`)))}function wi(t){return t.status===0&&t.responseType!=="opaque"}function Ct(t,e){return t.length>e.requestErrorResponseLengthLimit?`${t.substring(0,e.requestErrorResponseLengthLimit)}...`:t}function xi(t){return t==="xhr"?"XHR":"Fetch"}function Ci(t,e,n){Zo(t,(r,s,o)=>{if(r)n(r);else{let i=new TextDecoder().decode(s);o&&(i+="..."),n(void 0,i)}},{bytesLimit:e,collectStreamBody:!0})}function Li(t,e){if(!t.forwardErrorsToLogs)return{stop:W};const n=new A,{stop:r}=Is(n),s=n.subscribe(o=>{e.notify(0,{rawLogsEvent:{message:o.message,date:o.startClocks.timeStamp,error:Ve(o),origin:I.SOURCE,status:g.error},messageContext:o.context})});return{stop:()=>{r(),s.unsubscribe()}}}const Oi=Co;function Ii(t){function e(n,r,s,o,i){const a=ce(r.getContext(),n.context);if(He(n.status,Ae.console,r)&&Ui(n,a),He(n.status,Ae.http,r)){const u={rawLogsEvent:{date:i||$(),message:n.message,status:n.status,origin:I.LOGGER},messageContext:a,savedCommonContext:o};s&&(u.domainContext={handlingStack:s}),t.notify(0,u)}}return{handleLog:e}}const ki={[g.ok]:_.debug,[g.debug]:_.debug,[g.info]:_.info,[g.notice]:_.info,[g.warn]:_.warn,[g.error]:_.error,[g.critical]:_.error,[g.alert]:_.error,[g.emerg]:_.error};function Ui({status:t,message:e},n){z[ki[t]].call(D,e,n)}function Di(t,e,n,r,s){const o=In(t,{endpoint:t.logsEndpointBuilder,encoder:Ye()},t.replica&&{endpoint:t.replica.logsEndpointBuilder,encoder:Ye()},n,r,s.expireObservable);return e.subscribe(1,i=>{o.add(i)}),o}function Pi(t){const e=St();t.subscribe(1,n=>{e.send("log",n)})}function Mi(t){return{get:e=>{const n=t.findTrackedSession(e);if(n)return{session_id:n.id}}}}function Fi(t){return e=>{t.notify(0,{rawLogsEvent:{message:e.message,date:e.startClocks.timeStamp,origin:I.AGENT,status:g.error}}),bn("Error reported to customer",{"error.message":e.message})}}function Ni(t,e,n,r,s){const o=zs("browser-logs-sdk",e);o.setContextProvider(()=>{var a,u,c,l,d,f;return{application:{id:(a=Ke())===null||a===void 0?void 0:a.application_id},session:{id:(u=s.findTrackedSession())===null||u===void 0?void 0:u.id},view:{id:(l=(c=Ke())===null||c===void 0?void 0:c.view)===null||l===void 0?void 0:l.id},action:{id:(f=(d=Ke())===null||d===void 0?void 0:d.user_action)===null||f===void 0?void 0:f.id}}});const i=[];if(Xe()){const a=St(),u=o.observable.subscribe(c=>a.send("internal_telemetry",c));i.push(()=>u.unsubscribe())}else{const a=In(e,{endpoint:e.rumEndpointBuilder,encoder:Ye()},e.replica&&{endpoint:e.replica.rumEndpointBuilder,encoder:Ye()},n,r,s.expireObservable);i.push(()=>a.stop());const u=o.observable.subscribe(c=>a.add(c,Ks(e)));i.push(()=>u.unsubscribe())}return Vs(),Zs(ci(t)),{telemetry:o,stop:()=>{i.forEach(a=>a())}}}function Bi(t,e,n,r){const s=new Oi,o=[];s.subscribe(1,f=>hn("logs",f));const i=Fi(s),a=Ao(e),u=e.sessionStoreStrategyType&&!Xe()&&!Dn()?mi(e,r):pi(e),{stop:c}=Ni(t,e,i,a,u);o.push(()=>c()),_i(e,s),Li(e,s),Si(e,s),Ti(e,s);const{handleLog:l}=Ii(s);if(yi(u,e,s,n,i),Xe())Pi(s);else{const{stop:f}=Di(e,s,i,a,u);o.push(()=>f())}const d=Mi(u);return{handleLog:l,getInternalContext:d.get,stop:()=>{o.forEach(f=>f())}}}const le=di(Bi);Ps(j(),"DD_LOGS",le);const v=class v{constructor(e,n,r,s,o){this.copy=()=>new v(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,v.toStr(i)},this.toFrames=i=>{let a=60,u=0;Math.floor(i)==60?(a=60,u=0):Math.floor(i)==59?(a=60,u=4):Math.floor(i)==30?(a=30,u=0):Math.floor(i)==29&&(a=30,u=2);let c=this.h,l=this.m,d=this.s,f=this.f,h=this.field;const m=c*60+l,S=(m-Math.floor(m/10))*u;return c*(a*3600)+l*(a*60)+d*a+(f*2+h)-S},this.addSeconds=i=>{let a=this.copy();return a.s+=i,a.s>=60&&(a.s=0,a.m++,a.m>=60&&(a.m=0,a.h++)),a},this.addFrames=(i,a)=>{let u=this.toFrames(a);return u+=i,v.fromFrames(u,a)},this.subtractFrames=(i,a)=>this.addFrames(-i,a),this.h=e||0,this.m=n||0,this.s=r||0,this.f=s||0,this.field=o||0}static compare(e,n){return e.h!==n.h?e.h<n.h?-1:1:e.m!==n.m?e.m<n.m?-1:1:e.s!==n.s?e.s<n.s?-1:1:e.f!==n.f?e.f<n.f?-1:1:e.field!==n.field?e.field<n.field?-1:1:0}static generateTimecodeRange(e,n,r){const s=[];let o=e;for(;v.compare(o,n)<=0;)s.push(o),o=o.addSeconds(r);return s}totalSeconds(){return this.h*3600+this.m*60+this.s}totalMilliseconds(e){return this.toFrames(e)*1e3/e}};v.calculateCurrentTimeCode=e=>{var d;if(!e.video||!e.clocker||!e.gameParams)throw new Error("OTTPlayer is not initialized");const n=e.video,r=e.clocker,s=r.videoFPScalculator.getFPS(),a=(n.currentTime-r.syncPoint.playerTime)%(60*60*24)*s+r.syncPoint.frame;if(a===0||s===0)throw new Error("Current frame is 0 or fps is 0");const u=v.calculateCurrentOffset(a,(d=e.gameParams)==null?void 0:d.offsets);if(u===void 0)throw new Error("Offset is undefined");let c=Math.floor(a-u);return c<0&&(c+=5178816),c>=5178816&&(c-=5178816),v.fromFrames(c,s)},v.calculateCurrentOffset=(e,n)=>{for(let r=1;r<n.length;r++)if(e<n[r].frame)return n[r-1].offset;return n[n.length-1].offset},v.fromFrames=(e,n)=>{let r=60,s=0;Math.floor(n)==60?(r=60,s=0):Math.floor(n)==59?(r=60,s=4):Math.floor(n)==30?(r=30,s=0):Math.floor(n)==29&&(r=30,s=2);let o=Math.floor(n*60),i=Math.floor(n*60*10),a=i*6,u=e,c=Math.floor(u/a);u-=c*a;let l=Math.floor(u/i);u-=l*i,u>=r*60&&(u+=s*(Math.floor((u-r*60)/o)+1));let d=Math.floor(u/(r*60));u-=d*(r*60);let f=Math.floor(u/r);u-=f*r;let h=u;d+=l*10;let m=0;return m=h%2,h=Math.floor(h/2),new v(c,d,f,h,m)},v.toStr=e=>{const n="_";let r=("0"+e.h).slice(-2)+n+("0"+e.m).slice(-2)+n+("0"+e.s).slice(-2)+n+("0"+e.f).slice(-2);return e.field&&(r+="_1"),r},v.fromStr=e=>{const r=e.split("_").map(Number);if(r.length==4){const[s,o,i,a]=r;return new v(s,o,i,a,0)}else if(r.length==5){const[s,o,i,a,u]=r;return new v(s,o,i,a,u)}else throw new Error("Invalid timecode format: "+e)},v.fromMetadata=e=>{const n=/^(\\d{2}):(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d))?$/,r=e.timecode.match(n);if(!r)throw new Error("Invalid timecode format: "+e.timecode);const[,s,o,i,a,u]=r,c=Number(s),l=Number(o),d=Number(i),f=Number(a),h=u?Number(u):0;return new v(c,l,d,f,h)};let P=v;const p=class p{constructor(e){this.isLoggingOn=e.LOG_TO_DATADOG,this.isLoggingOn&&le.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!1,sessionSampleRate:100}),p.tracking.dev=`${e.platform}_${e.browserName}`,p.beatHandle||(console.log("[Logger] Starting tracking beat"),p.beatHandle=window.setInterval(p.flushTracking,15e3))}static setMessagePort(e){this.messagePort=e}static getMessagePort(){return this.messagePort}setLoggingOn(e){this.isLoggingOn=e}setAttributes(e){p.processAttributes(e);for(const n in e)le.logger.setContextProperty(n,e[n])}info(e,n){n&&p.processAttributes(n),this.isLoggingOn&&(le.logger.info(e,n),console.log("[Logger] Sending info: ",e))}error(e,n){n&&p.processAttributes(n),this.isLoggingOn&&(le.logger.error(e,n),p.tracking.err_time=Date.now().toFixed(0),p.tracking.err_desc=e,console.log("[Logger] Sending error: ",e))}warn(e,n){n&&p.processAttributes(n),this.isLoggingOn&&(le.logger.warn(e,n),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){p.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:e})}static info(e,n){p.messagePort.postMessage({type:"LOG",actionType:"INFO",message:e,attributes:n})}static error(e,n){p.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:e,attributes:n})}static warn(e,n){p.messagePort.postMessage({type:"LOG",actionType:"WARN",message:e,attributes:n})}static processAttributes(e){e.player_version&&(p.tracking.sdk=e.player_version),e.media_id&&(p.tracking.gid=e.media_id),e.game_id&&(p.tracking.buc=e.game_id),e.bb_session_id&&(p.tracking.sid=e.bb_session_id,console.log("[Logger] Setting bb_session_id:",p.tracking.sid)),e.last_timecode&&(p.tracking.tc=e.last_timecode,p.lastTimecodeMillis=P.fromStr(e.last_timecode).totalMilliseconds(59.94),p.lastTimecodeMillis&&p.lastZipMillis&&(p.tracking.cache=(p.lastZipMillis-p.lastTimecodeMillis).toFixed(0))),e.last_offset&&(p.tracking.off=e.last_offset),e.last_loading_zip&&(p.tracking.zip=e.last_loading_zip,p.lastZipMillis=P.fromStr(e.last_loading_zip).totalMilliseconds(59.94),p.lastTimecodeMillis&&p.lastZipMillis&&(p.tracking.cache=(p.lastZipMillis-p.lastTimecodeMillis).toFixed(0))),e.last_rendered_frame&&(p.tracking.aug_time=Date.now().toFixed(0)),e.asset&&(p.tracking.asset=e.asset)}static objectToQuery(e){return Object.entries(e).filter(([n,r])=>r!==0&&r!=="").map(([n,r])=>`${encodeURIComponent(n)}=${encodeURIComponent(String(r))}`).join("&")}};p.tracking={start:Date.now().toFixed(0),dev:"",sdk:"",mac:"",gid:"",sid:"",off:"",zip:"",aug_time:"",err_time:"",err_desc:"",tc:"",png:"",asset:"",cache:"",buc:""},p.lastTimecodeMillis=0,p.lastZipMillis=0,p.flushTracking=()=>{const e=Date.now().toFixed(0);p.tracking.now=e;const r=`https://dwu3k7rrxk5s3.cloudfront.net/metrics/1.gif?${p.objectToQuery(p.tracking)}`;console.log("[Logger] Flushing tracking data:",r),fetch(r,{method:"GET",mode:"no-cors",keepalive:!0}).catch(()=>{})};let U=p;const $i=`\nprecision highp float;\n\nattribute vec2 a_position; // pixel coords, 6 verts / quad\nattribute vec4 a_uv; // atlas UV (min_u, min_v, max_u, max_v)\nattribute mat3 a_transform; // transformation matrix for this vertex\n\nuniform vec2 u_resolution; // full frame size\n\nvarying vec2 v_maskUV; // for alpha mask\nvarying vec4 v_adUV; // atlas UV bounds\nvarying mat3 v_transform; // pass transform to fragment shader\n\nvoid main () {\n vec2 clipSpace = 2.0 * (a_position / u_resolution) - 1.0;\n gl_Position = vec4(clipSpace * vec2(1.0,-1.0), 0.0, 1.0);\n\n v_adUV = a_uv; // Pass through all 4 UV coordinates\n v_maskUV = a_position / u_resolution;\n v_transform = a_transform;\n}\n`,Gi=`\nprecision highp float;\n\nuniform sampler2D u_atlas; // packed logos\nuniform sampler2D u_alphaMask; // full-frame mask (changes every video frame)\nuniform float u_opacity;\nuniform vec2 u_resolution; // full frame size\n\nvarying vec4 v_adUV; // min_u, min_v, max_u, max_v\nvarying vec2 v_maskUV;\nvarying mat3 v_transform; // transformation matrix for this fragment\n\nconst float Directions = 16.0; // BLUR DIRECTIONS\nconst float QualityAd = 3.0; // BLUR QUALITY\nconst float BlurRadiusAd = 3.0;\n\n// Pi here is 2*pi = 6.283185..., so we can do 16 steps across 2*pi\nconst float Pi = 6.28318530718;\n\nvec4 BlurAd(sampler2D adTexture, vec2 adTexCoord) {\n // Convert our "BlurRadiusAd" to texture coords\n vec2 radius = BlurRadiusAd / u_resolution.xy;\n \n // Start by sampling once at the center\n vec4 resultColor = texture2D(adTexture, adTexCoord);\n int sampleCount = 1;\n\n // Convert float constants into integer loop bounds\n const int directions = int(Directions);\n const int quality = int(QualityAd);\n\n // For each direction around the circle...\n for (int d = 0; d < directions; d++) {\n // angle goes from 0 to 2*pi in increments of 2*pi/directions\n float angle = float(d) * (Pi / float(directions));\n\n // For each blur step outward in that direction\n for (int i = 1; i <= quality; i++) {\n // E.g. if quality=3, i goes 1..3\n float step = float(i) / float(quality);\n\n // offset is step fraction of the full radius, in polar coords\n vec2 offset = step * radius * vec2(cos(angle), sin(angle));\n\n // Accumulate that sample\n resultColor += texture2D(adTexture, adTexCoord + offset);\n sampleCount++;\n }\n }\n\n // Divide by the total sample count to average\n return resultColor / float(sampleCount);\n}\n\nvec2 transformPoint(vec2 point) {\n float x = (v_transform[0][0] * point.x + v_transform[0][1] * point.y + v_transform[0][2]) / \n (v_transform[2][0] * point.x + v_transform[2][1] * point.y + 1.0);\n float y = (v_transform[1][0] * point.x + v_transform[1][1] * point.y + v_transform[1][2]) / \n (v_transform[2][0] * point.x + v_transform[2][1] * point.y + 1.0);\n return vec2(x, y) / u_resolution;\n}\n\nvoid main () {\n // Transform the current position using the transformation matrix\n vec2 transformedUV = transformPoint(vec2(gl_FragCoord.x, u_resolution.y - gl_FragCoord.y));\n \n // If the transformed coordinate is outside [0,1], discard the fragment\n if(transformedUV.x < 0.0 || transformedUV.x > 1.0 || transformedUV.y < 0.0 || transformedUV.y > 1.0) {\n discard;\n }\n\n // Map the transformed coordinate to the atlas region\n vec2 atlasUV = mix(vec2(v_adUV.x, v_adUV.y), // min_u, min_v\n vec2(v_adUV.z, v_adUV.w), // max_u, max_v\n transformedUV); // interpolation factor\n \n float mask = texture2D(u_alphaMask, v_maskUV).r;\n vec4 ad = BlurAd(u_atlas, atlasUV);\n\n float a = ad.a * mask * u_opacity;\n gl_FragColor = vec4(ad.rgb * a, a);\n //gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); // Force black color for testing\n //gl_FragColor = texture2D(u_alphaMask, v_maskUV) * (1. + a * 0.); // Force alpha mask color for testing\n}\n`;class Bn{constructor(e,n){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.queryInFlight=!1,this.GPUFrameTimeCount=0,this.GPUFrameTimeSum=0,this.avgGPUFrameTime=0,this.CPUFrameTimeCount=0,this.CPUFrameTimeSum=0,this.avgCPUFrameTime=0,this.compileShader=(r,s)=>{const o=this.gl,i=o.createShader(r);return o.shaderSource(i,s),o.compileShader(i),o.getShaderParameter(i,o.COMPILE_STATUS)?i:(console.error(`Error compiling shader: ${o.getShaderInfoLog(i)}`),o.deleteShader(i),null)},this.createTextureFromVideoFrame=r=>{const s=this.gl,o=s.createTexture();return s.bindTexture(s.TEXTURE_2D,o),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,r),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.bindTexture(s.TEXTURE_2D,null),o},this.deleteTexture=r=>{this.gl.deleteTexture(r)},this.options=n,this.renderer=e,this.gl=e.glContext,this.initTiming()}init(){this.initAtlas(),this.initBuffers(),this.initPrograms()}initPrograms(){const e=this.gl;this.program=this.linkProgram($i,Gi),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.uOpacity=e.getUniformLocation(this.program,"u_opacity"),this.uAtlas=e.getUniformLocation(this.program,"u_atlas"),this.uAlphaMask=e.getUniformLocation(this.program,"u_alphaMask"),e.useProgram(this.program)}linkProgram(e,n){const r=this.gl,s=this.compileShader(r.VERTEX_SHADER,e),o=this.compileShader(r.FRAGMENT_SHADER,n),i=r.createProgram();if(r.attachShader(i,s),r.attachShader(i,o),r.linkProgram(i),!r.getProgramParameter(i,r.LINK_STATUS)){const a=r.getProgramInfoLog(i);throw 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,n,r=1){var d;const s=performance.now();this.syncAtlasGL();const{pos:o,uv:i,transforms:a,vertCount:u}=this.buildQuadData(n);if(!u)return;if(!this.program||this.aPos===void 0||this.aUv===void 0||this.aTransform===void 0||!this.uRes||!this.uOpacity||!this.uAtlas||!this.uAlphaMask){O(this.options,"Errors")&&console.error("[Renderer] Program or attributes not initialized");return}const c=this.gl;c.useProgram(this.program),c.uniform2f(this.uRes,c.canvas.width,c.canvas.height),c.viewport(0,0,c.canvas.width,c.canvas.height),c.uniform1f(this.uOpacity,r),c.activeTexture(c.TEXTURE0),c.bindTexture(c.TEXTURE_2D,e),c.uniform1i(this.uAlphaMask,0),c.activeTexture(c.TEXTURE1),c.bindTexture(c.TEXTURE_2D,this.atlasTex),c.uniform1i(this.uAtlas,1),c.bindBuffer(c.ARRAY_BUFFER,this.posBuf),c.bufferData(c.ARRAY_BUFFER,o,c.DYNAMIC_DRAW),c.enableVertexAttribArray(this.aPos),c.vertexAttribPointer(this.aPos,2,c.FLOAT,!1,0,0),c.bindBuffer(c.ARRAY_BUFFER,this.uvBuf),c.bufferData(c.ARRAY_BUFFER,i,c.DYNAMIC_DRAW),c.enableVertexAttribArray(this.aUv),c.vertexAttribPointer(this.aUv,4,c.FLOAT,!1,0,0),c.bindBuffer(c.ARRAY_BUFFER,this.transformBuf),c.bufferData(c.ARRAY_BUFFER,a,c.DYNAMIC_DRAW);const l=9*4;for(let f=0;f<3;f++){const h=this.aTransform+f;c.enableVertexAttribArray(h),c.vertexAttribPointer(h,3,c.FLOAT,!1,l,f*3*4)}if(c.enable(c.BLEND),c.blendFunc(c.SRC_ALPHA,c.ONE_MINUS_SRC_ALPHA),c.clearColor(0,0,0,0),c.clear(c.COLOR_BUFFER_BIT),this.beginTimer(),c.drawArrays(c.TRIANGLES,0,u),this.endTimer(),(d=this.options.debug)!=null&&d.trackPerformance){const h=performance.now()-s;this.CPUFrameTimeCount++,this.CPUFrameTimeSum+=h,this.avgCPUFrameTime=this.CPUFrameTimeSum/this.CPUFrameTimeCount}}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)}buildQuadData(e){const n=[],r=[],s=[];return Object.values(e).forEach(o=>{var c,l;const i=(l=(c=this.renderer.ads)==null?void 0:c.adMap.get(o.name))==null?void 0:l.name;if(!i)return;const a=this.logoToRegion.get(i);if(!a)return;const u=o.corners;n.push(u[0].x,u[0].y,u[1].x,u[1].y,u[2].x,u[2].y,u[0].x,u[0].y,u[2].x,u[2].y,u[3].x,u[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++)s.push(...o.tranform)}),{pos:new Float32Array(n),uv:new Float32Array(r),transforms:new Float32Array(s),vertCount:n.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 n=e;return{w:n.displayWidth??n.codedWidth,h:n.displayHeight??n.codedHeight}}calculateRequiredAtlasSize(e,n){let r=e*n;this.logoToRegion.forEach(o=>{const i=(o.u1-o.u0)*this.ATLAS_SIZE,a=(o.v1-o.v0)*this.ATLAS_SIZE;r+=i*a}),r*=1.2;let s=this.INITIAL_ATLAS_SIZE;for(;s*s<r;)s*=2;return s}resizeAtlas(e,n){const r=this.calculateRequiredAtlasSize(e,n);if(r<=this.ATLAS_SIZE)return;const s=new OffscreenCanvas(r,r),o=s.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=s,this.atlasCtx=o,this.logoToRegion.forEach((a,u)=>{const c={u0:a.u0*i,v0:a.v0*i,u1:a.u1*i,v1:a.v1*i};this.logoToRegion.set(u,c)}),this.syncAtlasGL()}addToAtlas(e,n){if(this.logoToRegion.has(e))return this.logoToRegion.get(e);const{w:r,h:s}=this.getDims(n);this.nextX+r>this.ATLAS_SIZE&&(this.nextX=0,this.nextY+=this.rowH,this.rowH=0),(this.nextY+s>this.ATLAS_SIZE||this.nextX+r>this.ATLAS_SIZE)&&this.resizeAtlas(r,s),this.atlasCtx.drawImage(n,this.nextX,this.nextY,r,s);const o={u0:this.nextX/this.ATLAS_SIZE,v0:this.nextY/this.ATLAS_SIZE,u1:(this.nextX+r)/this.ATLAS_SIZE,v1:(this.nextY+s)/this.ATLAS_SIZE};return this.logoToRegion.set(e,o),this.atlasDirty=!0,this.nextX+=r,this.rowH=Math.max(this.rowH,s),o}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_MIN_FILTER,e.LINEAR),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.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,n){U.setAttributes({asset:e}),this.addToAtlas(e,n)}initTiming(){var e;(e=this.options.debug)!=null&&e.trackPerformance&&(this.timerExt=this.gl.getExtension("EXT_disjoint_timer_query"),this.timerExt||console.warn("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)return;this.timerExt.endQueryEXT(this.timerExt.TIME_ELAPSED_EXT),this.queryInFlight=!0;const e=()=>{if(!this.queryInFlight)return;const n=this.timerExt.getQueryObjectEXT(this.query,this.timerExt.QUERY_RESULT_AVAILABLE_EXT),r=this.gl.getParameter(this.timerExt.GPU_DISJOINT_EXT);if(n&&!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.queryInFlight=!1}else requestAnimationFrame(e)};requestAnimationFrame(e)}getAvgGPUFrameTime(){var e;if((e=this.options.debug)!=null&&e.trackPerformance){const n=this.avgGPUFrameTime;return this.GPUFrameTimeCount=0,this.GPUFrameTimeSum=0,this.avgGPUFrameTime=0,n}return 0}getAvgCPUFrameTime(){var e;if((e=this.options.debug)!=null&&e.trackPerformance){const n=this.avgCPUFrameTime;return this.CPUFrameTimeCount=0,this.CPUFrameTimeSum=0,this.avgCPUFrameTime=0,n}return 0}}const $n=["LeftTop","MidTopLeft","MidTopRight","RightTop","LeftBottom","MidBottomLeft","MidBottomRight","RightBottom"];class Gn{constructor(e,n){this.ads=[],this.getAds=async()=>{try{const r="https://dwu3k7rrxk5s3.cloudfront.net/assets/asia/BurgerKing.png",o=await(await fetch(r)).blob(),i=await createImageBitmap(o),a={name:"BurgerKing",imageUrl:r,image:i,adUrl:"https://www.BurgerKing.com/"};this.ads.push(a),this.setAd("LeftTop",0),this.setAd("RightBottom",0),this.setAd("MidBottomLeft",0),this.setAd("MidTopRight",0),this.uploadAdTextures()}catch{}finally{setTimeout(this.getAds,1e4)}},this.loadAdvImage=async r=>{const s=`#${r.name}`,o=r.url;if(s.indexOf(".json")>-1)return;const a=await(await fetch(o)).blob();return await createImageBitmap(a)},this.setAd=(r,s)=>{this.adMap.set(r,this.ads[s])},this.uploadAdTextures=()=>{this.webgl.clearAtlas(),this.adMap.forEach((r,s)=>{!r||!r.image||this.webgl.generateAdTexture(r.name,r.image)})},this.getAdURLAtCoord=(r,s,o)=>{let i;return Object.keys(r).forEach(a=>{const u=r[a].corners.map(c=>({x:c.x/s.width,y:c.y/s.height}));if(this.isPointInPlaceholder(u,o)){const c=r[a].name,l=this.adMap.get(c);console.log("ad: ",l),l&&(console.log("ad.url: ",l.adUrl),i=l.adUrl)}}),i},this.isPointInPlaceholder=(r,s)=>{let o=!1;const{x:i,y:a}=s,u=r.length;for(let c=0,l=u-1;c<u;l=c++){const d=r[c].x,f=r[c].y,h=r[l].x,m=r[l].y;f>a!=m>a&&i<(h-d)*(a-f)/(m-f)+d&&(o=!o)}return o},this.placeholderNames=$n,this.webgl=e,this.options=n,this.adMap=new Map,$n.forEach(r=>{this.adMap.set(r,void 0)}),this.getAds()}}class jn{constructor(e,n){this.renderDataMap=new Map,this.isRenderData=!1,this.state="OFF",this.opacity=0,this.lastStateUpdate=0,this.stateUpdateInterval=500,this.lastPerformanceCheck=performance.now(),this.setWebGLEventListeners=()=>{const r=this.glContext.canvas;r.addEventListener("webglcontextlost",s=>{console.warn("Context lost:",s),s.preventDefault()}),r.addEventListener("webglcontextrestored",()=>{console.log("Context restored!"),this.webgl=new Bn(this,this.options),this.ads=new Gn(this.webgl,this.options),this.webgl.init()})},this.addMetadataBatch=r=>{r.forEach(s=>{if(s.alphaMask){this.options&&O(this.options,"Renderer")&&console.log(`[RendererWorker] Creating texture for timeCode=${s.timecode}`);try{const o=this.webgl.createTextureFromVideoFrame(s.alphaMask),i=s.timecode,a={width:s.processingWidth,height:s.processingHeight},u={alphaMask:o,placeholders:s.placeholders,processingSize:a,isLive:s.isLive};this.renderDataMap.set(i,u),U.setAttributes({last_webgl_uploaded_frame:i})}catch{this.options&&O(this.options,"Errors")&&console.error(`[RendererWorker] Error creating texture for timeCode=${s.timecode}`)}finally{s.alphaMask.close()}}})},this.handleRenderDraw=(r,s)=>{var d,f,h,m;if(!this.streamData||!((d=this.ads)!=null&&d.ads))return;const o=this.renderDataMap.get(r);if(!!o!==this.isRenderData&&(o?U.info("didStartDrawingAugmentationMedia",{timecode:r}):U.info("didEndDrawingAugmentationMedia",{timecode:r}),this.isRenderData=!!o),(o?o.isLive:!1)&&!!this.streamData.ottActions&&(this.streamData.ottActions.toggle[this.streamData.customerId]!==void 0?this.streamData.ottActions.toggle[this.streamData.customerId]&&this.streamData.ottActions.toggle.web:this.streamData.ottActions.toggle.web)?(this.state==="OFF"||this.state==="FADE_OUT")&&(this.state="FADE_IN"):(this.state==="ON"||this.state==="FADE_IN")&&(this.state="FADE_OUT"),!o)return;const u=o.alphaMask,c=o.placeholders,l=o.processingSize;if(!(!u||!c||!l)){if((this.glContext.canvas.width!==l.width||this.glContext.canvas.height!==l.height)&&(this.glContext.canvas.width=l.width,this.glContext.canvas.height=l.height),s!=0)if(s>0){const y=P.fromStr(r).addFrames(1,this.streamData.fps),S=(f=this.renderDataMap.get(P.toStr(y)))==null?void 0:f.placeholders;S&&Object.keys(S).forEach(L=>{L in c&&(c[L].tranform=c[L].tranform.map((x,ve)=>x*(1-s)+S[L].tranform[ve]*s))})}else{const y=Math.abs(s),S=P.fromStr(r).subtractFrames(1,this.streamData.fps),L=(h=this.renderDataMap.get(P.toStr(S)))==null?void 0:h.placeholders;L&&Object.keys(L).forEach(x=>{x in c&&(c[x].tranform=c[x].tranform.map((ve,Ot)=>L[x].tranform[Ot]*(1-y)+ve*y))})}if(this.options&&O(this.options,"Renderer")&&console.log(`[Renderer] Render logic: binding texture for ${r}`),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=Math.max(0,this.opacity-(performance.now()-this.lastStateUpdate)/this.stateUpdateInterval),this.lastStateUpdate=performance.now(),this.opacity===0&&(this.state="OFF")),U.setAttributes({last_rendered_frame:r,renderer_state:this.state}),this.webgl.drawAugmentation(u,c,this.opacity),this.options&&((m=this.options.debug)!=null&&m.trackPerformance)){const y=performance.now();y-this.lastPerformanceCheck>=this.options.PERFORMANCE_TRACKING_INTERVAL&&(this.trackPerformance(),this.lastPerformanceCheck=y)}}},this.handleRenderClear=()=>{this.opacity=0,this.state="OFF"},this.getAdURLByCoord=r=>{var u,c;if(!this.ads||!this.streamData||!this.streamData.timeCode||!this.renderDataMap)return null;const s=this.streamData.timeCode,o=(u=this.renderDataMap.get(s))==null?void 0:u.placeholders,i=(c=this.renderDataMap.get(s))==null?void 0:c.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 s=(o=this.renderDataMap.get(r))==null?void 0:o.alphaMask;s&&(this.webgl.deleteTexture(s),this.renderDataMap.delete(r))},this.deleteOldTextures=r=>{if(!this.streamData)return;const s=59.94,o=P.fromStr(r).totalMilliseconds(s);this.renderDataMap.forEach((i,a)=>{P.fromStr(a).totalMilliseconds(s)<o-100&&(this.options&&O(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,s)=>{this.webgl.deleteTexture(r.alphaMask),this.renderDataMap.delete(s)})},this.cleanGL=()=>{this.webgl.cleanGL()},this.updateStreamData=r=>{var o;const s=(o=this.streamData)==null?void 0:o.ottActions;this.streamData=r,s&&!r.ottActions&&(this.streamData.ottActions=s)},this.trackPerformance=()=>{const r=this.webgl.getAvgGPUFrameTime(),s=this.webgl.getAvgCPUFrameTime();Xi([{metric:"Rendering GPU time",value:r},{metric:"Rendering CPU time",value:s}],U.getMessagePort())},this.glContext=e,this.webgl=new Bn(this,n),this.options=n,this.ads=new Gn(this.webgl,n),this.webgl.init()}stop(){this.cleanGL(),this.deleteAllTextures()}}let Ze=null,Je=null,Wn=null,Lt=null,Y=null,w=null,T,C,Xn=0,qn=0;self.onmessage=t=>{const{data:e}=t;if(e.type==="SET_LOGGER_PORT"&&(Lt=e.port,U.setMessagePort(e.port)),e.type==="INIT_OFFSCREEN"){const n=e.offscreen;if(T=e.options,Y=n.getContext("webgl"),T&&O(T,"Renderer")&&console.log("[RendererWorker] Initializing OffscreenCanvas"),!Y||Y!=null&&Y.isContextLost()){U.error("[RendererWorker] Failed to acquire WebGL context"),T&&O(T,"Errors")&&console.error("[RendererWorker] Failed to acquire WebGL context");return}w=new jn(Y,T),T&&O(T,"Renderer")&&console.log("[RendererWorker] OffscreenCanvas initialized, gl context acquired")}if(e.type==="SET_DOWNLOADER_PORT"&&(Ze=e.port,Ze.onmessage=zi),e.type==="SET_DECODER_PORT"&&(Je=e.port,Je.onmessage=Yi),e.type==="SET_ADAPTER_PORT"&&(Wn=e.port,Wn.onmessage=Hi),(e.type==="RENDERER_DRAW"||e.type==="RENDERER_CLEAR")&&Yn(e),e.type==="VIDEO_CLICK"&&w){const n=w.getAdURLByCoord(e.clickData);postMessage({type:"OPEN_URL",url:n})}if(e.type==="VIDEO_SEEKED"){if(!Y||!T)return;w==null||w.stop(),w=new jn(Y,T)}};function ji(){!Ze||!C||Ze.postMessage({type:"DOWNLOADER_INPUT",streamData:C})}function Wi(){!Je||!C||Je.postMessage({type:"DECODER_REQUEST",timeCode:C.timeCode,fps:C.fps})}function Xi(t,e){if(!Lt&&!e)return;const n=Lt||e,r={type:"TRACK_PERFORMANCE",data:t};n.postMessage(r)}function Yn(t){C=t.streamData,w?(C&&w.updateStreamData(C),w.cleanGL(),t.type==="RENDERER_CLEAR"&&w.handleRenderClear(),t.type==="RENDERER_DRAW"&&C&&(w.handleRenderDraw(C.timeCode,C.frameCorrection),w.deleteOldTextures(C.timeCode)),qi()):T&&O(T,"Errors")&&console.error("[RendererWorker] WebGL context is not initialized.")}function qi(){if(!T)return;const t=performance.now();t-Xn>T.DOWNLOADER_UPDATE_FREQUENCY&&(ji(),Xn=t),t-qn>T.DECODER_UPDATE_FREQUENCY&&(Wi(),qn=t)}function Yi(t){const{data:e}=t;if(e.type==="RENDERER_INPUT"){const n=e.batch;T&&O(T,"Renderer")&&console.log(`[RendererWorker] Received a batch of ${n.length} frames`),w&&w.addMetadataBatch(n)}}function zi(t){if(!C)return;const{data:e}=t;T&&O(T,"Renderer")&&console.log("[RendererWorker] Message from Downloader:",t.data),e.type==="OTT_ACTIONS"&&(C.ottActions=e.ottActions)}function Hi(t){const{data:e}=t;(e.type==="RENDERER_DRAW"||e.type==="RENDERER_CLEAR")&&Yn(e)}self.onunhandledrejection=t=>{U.error("[RendererWorker] Unhandled rejection",{error:t.reason}),T&&(O(T,"Errors")&&console.error("[RendererWorker] Unhandled rejection:",t.reason),t.preventDefault())},self.onerror=t=>{U.error("[RendererWorker] Unhandled error",{error:t}),T&&(O(T,"Errors")&&console.error("[RendererWorker] Unhandled error:",t),t instanceof Event&&t.preventDefault())}})();\n',zt=typeof self<"u"&&self.Blob&&new Blob([$t],{type:"text/javascript;charset=utf-8"});function ir(t){let e;try{if(e=zt&&(self.URL||self.webkitURL).createObjectURL(zt),!e)throw"";const n=new Worker(e,{name:t==null?void 0:t.name});return n.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),n}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent($t),{name:t==null?void 0:t.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}const Gt='(function(){"use strict";const ee=(e,t)=>!e.debug||!e.debug.on?!1:e.debug[`log${t}`],Hn=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,_={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},L=console,W={};Object.keys(_).forEach(e=>{W[e]=L[e]});const fe="Datadog Browser SDK:",w={debug:W.debug.bind(L,fe),log:W.log.bind(L,fe),info:W.info.bind(L,fe),warn:W.warn.bind(L,fe),error:W.error.bind(L,fe)},Je="https://docs.datadoghq.com",At=`${Je}/real_user_monitoring/browser/troubleshooting`,Oe="More details:";function kt(e,t){return(...n)=>{try{return e(...n)}catch(r){w.error(t,r)}}}function ve(e){return e!==0&&Math.random()*100<=e}function zn(e){return Kn(e)&&e>=0&&e<=100}function Kn(e){return typeof e=="number"}const pe=1e3,H=60*pe,Lt=60*H,Vn=365*(24*Lt);function me(){return new Date().getTime()}function D(){return me()}function Re(){return performance.now()}function $(){return{relative:Re(),timeStamp:D()}}function qn(){return{relative:0,timeStamp:It()}}function Yn(e,t){return t-e}function Xn(e,t){return e+t}function Jn(e){return e-It()}let Ze;function It(){return Ze===void 0&&(Ze=performance.timing.navigationStart),Ze}const I=1024,Mt=1024*I,Zn=/[^\\u0000-\\u007F]/;function Qe(e){return Zn.test(e)?window.TextEncoder!==void 0?new TextEncoder().encode(e).length:new Blob([e]).size:e.length}function Qn(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 U(){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=U();let r;return n.Zone&&typeof n.Zone.__symbol__=="function"&&(r=e[n.Zone.__symbol__(t)]),r||(r=e[t]),r}let xe,Nt=!1;function er(e){xe=e}function tr(e){Nt=e}function nr(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){rr(r)}}function rr(e){if(et(e),xe)try{xe(e)}catch(t){et(t)}}function et(...e){Nt&&w.error("[MONITOR]",...e)}function Se(e,t){return te(U(),"setTimeout")(b(e),t)}function Ft(e){te(U(),"clearTimeout")(e)}function tt(e,t){return te(U(),"setInterval")(b(e),t)}function Dt(e){te(U(),"clearInterval")(e)}class C{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 C(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:()=>{Ft(s),r=!1,o=void 0}}}function B(){}function G(e){return e?(parseInt(e,10)^Math.random()*16>>parseInt(e,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,G)}const Ae=/([\\w-]+)\\s*=\\s*([^;]+)/g;function or(e,t){for(Ae.lastIndex=0;;){const n=Ae.exec(e);if(n){if(n[1]===t)return n[2]}else break}}function sr(e){const t=new Map;for(Ae.lastIndex=0;;){const n=Ae.exec(e);if(n)t.set(n[1],n[2]);else break}return t}function ir(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 ar(){return cr()===0}let ke;function cr(){return ke??(ke=ur())}function ur(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 or(document.cookie,e)}let rt;function z(e){return rt||(rt=sr(document.cookie)),rt.get(e)}function Bt(e,t){ye(e,"",0,t)}function lr(e){if(document.cookie===void 0||document.cookie===null)return!1;try{const t=`dd_cookie_test_${G()}`,n="test";ye(t,n,H,e);const r=nt(t)===n;return Bt(t,e),r}catch(t){return w.error(t),!1}}let ot;function dr(){if(ot===void 0){const e=`dd_site_test_${G()}`,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 Le(e){return Object.values(e)}function fr(e){return Object.entries(e)}const st=4*Lt,Gt=15*H,pr=Vn,be={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},jt=/^([a-zA-Z]+)=([a-z0-9-]+)$/,it="&";function mr(e){return!!e&&(e.indexOf(it)!==-1||jt.test(e))}const gr="1";function K(e,t){const n={isExpired:gr};return t.trackAnonymousUser&&(e!=null&&e.anonymousId?n.anonymousId=e==null?void 0:e.anonymousId:n.anonymousId=G()),n}function Ie(e){return ge(e)}function Wt(e){return!Ie(e)}function Me(e){return e.isExpired!==void 0||!hr(e)}function hr(e){return(e.created===void 0||me()-Number(e.created)<st)&&(e.expire===void 0||me()<Number(e.expire))}function Ht(e){e.expire=String(me()+Gt)}function at(e){return fr(e).map(([t,n])=>t==="anonymousId"?`aid=${n}`:`${t}=${n}`).join(it)}function zt(e){const t={};return mr(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 Sr="_dd",yr="_dd_r",br="_dd_l",Er="rum",Tr="logs";function _r(e){if(!z(ne)){const n=z(Sr),r=z(yr),o=z(br),s={};n&&(s.id=n),o&&/^[01]$/.test(o)&&(s[Tr]=o),r&&/^[012]$/.test(r)&&(s[Er]=r),Wt(s)&&(Ht(s),e.persistSession(s))}}function Kt(e){const t=Rr(e);return lr(t)?{type:be.COOKIE,cookieOptions:t}:void 0}function wr(e,t){const n={isLockEnabled:ar(),persistSession:Cr(t),retrieveSession:vr,expireSession:r=>Or(t,r,e)};return _r(n),n}function Cr(e){return t=>{ye(ne,at(t),Gt,e)}}function Or(e,t,n){const r=K(t,n);ye(ne,at(r),n.trackAnonymousUser?pr:st,e)}function vr(){const e=nt(ne);return zt(e)}function Rr(e){const t={};return t.secure=!!e.useSecureSessionCookie||!!e.usePartitionedCrossSiteSessionCookie,t.crossSite=!!e.usePartitionedCrossSiteSessionCookie,t.partitioned=!!e.usePartitionedCrossSiteSessionCookie,e.trackSessionAcrossSubdomains&&(t.domain=dr()),t}const xr="_dd_test_";function Vt(){try{const e=G(),t=`${xr}${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 Ar(e){return{isLockEnabled:!1,persistSession:qt,retrieveSession:kr,expireSession:t=>Lr(t,e)}}function qt(e){localStorage.setItem(ne,at(e))}function kr(){const e=localStorage.getItem(ne);return zt(e)}function Lr(e,t){qt(K(e,t))}const Ir=10,Mr=100,Yt=[];let Pe;function V(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(),g=f.lock;return f.lock&&delete f.lock,{session:f,lock:g}};if(Pe||(Pe=e),e!==Pe){Yt.push(e);return}if(o&&n>=Mr){Xt(t);return}let l,u=c();if(o){if(u.lock){Ne(e,t,n);return}if(l=G(),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&&(Me(d)?i(d):(Ht(d),o?a(d):s(d))),o&&!(d&&Me(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),Xt(t)}function Ne(e,t,n){Se(()=>{V(e,t,n+1)},Ir)}function Xt(e){Pe=void 0;const t=Yt.shift();t&&V(t,e)}const Jt=pe;function Pr(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:w.error(`Invalid session persistence \'${String(e.sessionPersistence)}\'`)}}function Nr(e,t,n,r){const o=new C,s=new C,i=new C,a=e.type===be.COOKIE?wr(t,e.cookieOptions):Ar(t),{expireSession:c}=a,l=tt(m,Jt);let u;p();const{throttled:d,cancel:f}=Ut(()=>{V({process:y=>{if(Ie(y))return;const de=E(y);return v(de),de},after:y=>{Wt(y)&&!R()&&jn(y),u=y}},a)},Jt);function g(){V({process:y=>R()?E(y):void 0},a)}function m(){V({process:y=>Me(y)?K(y,t):void 0,after:E},a)}function E(y){return Me(y)&&(y=K(y,t)),R()&&(F(y)?le():(i.notify({previousState:u,newState:y}),u=y)),y}function p(){V({process:y=>{if(Ie(y))return K(y,t)},after:y=>{u=y}},a)}function v(y){if(Ie(y))return!1;const{trackingType:de,isTracked:Wi}=r(y[n]);y[n]=de,delete y.isExpired,Wi&&!y.id&&(y.id=G(),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=K(u,t),s.notify()}function jn(y){u=y,o.notify()}function Wn(y){V({process:de=>({...de,...y}),after:E},a)}return{expandOrRenewSession:d,expandSession:g,getSession:()=>u,renewObservable:o,expireObservable:s,sessionStateUpdateObservable:i,restartSession:p,expire:()=>{f(),c(u),E(K(u,t))},stop:()=>{Dt(l)},updateSessionState:Wn}}const ct={GRANTED:"granted",NOT_GRANTED:"not-granted"};function Fr(e){const t=new C;return{tryToInit(n){e||(e=n)},update(n){e=n,t.notify()},isGranted(){return e===ct.GRANTED},observable:t}}function q(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}):B}function ut(e){return Dr(e,location.href).href}function Dr(e,t){const n=$r();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)} ${q({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 Fe;function $r(){if(Fe===void 0)try{Fe=new Zt("http://test/path").href==="http://test/path"}catch{Fe=!1}return Fe?Zt:void 0}const Ur="datad0g.com",Br="dd0g-gov.com",oe="datadoghq.com",Gr="ddog-gov.com",jr="pci.browser-intake-datadoghq.com",Wr=["ddsource","ddtags"];function Ee(e,t,n){const r=Hr(e,t);return{build(o,s){const i=Kr(e,t,n,o,s);return r(i)},urlPrefix:r(""),trackType:t}}function Hr(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=zr(t,e);return s=>`https://${o}${n}?${s}`}function zr(e,t){const{site:n=oe,internalAnalyticsSubdomain:r}=t;if(e==="logs"&&t.usePciIntake&&n===oe)return jr;if(r&&n===oe)return`${r}.${oe}`;if(n===Br)return`http-intake.logs.${n}`;const o=n.split("."),s=o.pop();return`browser-intake-${o.join("-")}.${s}`}function Kr({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=${G()}`];return i&&c.push(`dd-evp-encoding=${i}`),n==="rum"&&c.push(`batch_time=${D()}`),t&&c.reverse(),c.join("&")}const Vr=200;function qr(e){const{env:t,service:n,version:r,datacenter:o}=e,s=[];return t&&s.push(De("env",t)),n&&s.push(De("service",n)),r&&s.push(De("version",r)),o&&s.push(De("datacenter",o)),s}function De(e,t){const n=Vr-e.length-1;(t.length>n||Yr(t))&&w.warn(`${e} value doesn\'t meet tag requirements and will be sanitized. ${Oe} ${Je}/getting_started/tagging/#defining-tags`);const r=t.replace(/,/g,"_");return`${e}:${r}`}function Yr(e){return Xr()?new RegExp("[^\\\\p{Ll}\\\\p{Lo}0-9_:./-]","u").test(e):!1}function Xr(){try{return new RegExp("[\\\\p{Ll}]","u"),!0}catch{return!1}}function Jr(e){const t=e.site||oe,n=qr(e),r=Zr(e,n);return{replica:Qr(e,n),site:t,...r}}function Zr(e,t){return{logsEndpointBuilder:Ee(e,"logs",t),rumEndpointBuilder:Ee(e,"rum",t),sessionReplayEndpointBuilder:Ee(e,"replay",t)}}function Qr(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 eo(e){return Wr.every(t=>e.includes(t))}function lt(e,t){return e!=null&&typeof e!="string"?(w.error(`${t} must be defined as a string`),!1):!0}function to(e){return e&&typeof e=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(e)?(w.error(`Site should be a valid Datadog site. ${Oe} ${Je}/getting_started/site/.`),!1):!0}function $e(e,t){return e!==void 0&&!zn(e)?(w.error(`${t} Sample Rate should be a number between 0 and 100`),!1):!0}function no(e){var t,n,r,o,s,i;if(!e||!e.clientToken){w.error("Client Token is not configured, we will not send any data.");return}if(!(!to(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)){w.error(\'Tracking Consent should be either "granted" or "not-granted"\');return}return{beforeSend:e.beforeSend&&kt(e.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:Pr(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*I,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*pe,batchMessagesLimit:50,messageBytesLimit:256*I,...Jr(e)}}}function ro(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 oo(e){Array.isArray(e)&&so(e.filter(t=>Pt(dt,t)))}function so(e){e.forEach(t=>{Qt.add(t)})}function io(){return Qt}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=uo(o)||fo(o)||mo(o)||So(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+))",ao=new RegExp(`^\\\\s*at (.*?) ?\\\\(${en}${se}?${se}?\\\\)?\\\\s*$`,"i"),co=new RegExp(`\\\\((\\\\S*)${se}${se}\\\\)`);function uo(e){const t=ao.exec(e);if(!t)return;const n=t[2]&&t[2].indexOf("native")===0,r=t[2]&&t[2].indexOf("eval")===0,o=co.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 lo=new RegExp(`^\\\\s*at ?${en}${se}?${se}??\\\\s*$`,"i");function fo(e){const t=lo.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 po=/^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;function mo(e){const t=po.exec(e);if(t)return{args:[],column:t[4]?+t[4]:void 0,func:t[1]||Te,line:+t[3],url:t[2]}}const go=/^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\\[native).*?|[^@]*bundle)(?::(\\d+))?(?::(\\d+))?\\s*$/i,ho=/(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;function So(e){const t=go.exec(e);if(!t)return;const n=t[3]&&t[3].indexOf(" > eval")>-1,r=ho.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 yo(e,t,n,r){const o=[{url:t,column:r,line:n}],{name:s,message:i}=Eo(e);return{name:s,message:i,stack:o}}const bo=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\\s\\S]*)$/;function Eo(e){let t,n;return{}.toString.call(e)==="[object String]"&&([,t,n]=bo.exec(e)),{name:t,message:n}}function Ue(e){const n=new Error(e);n.name="HandlingStack";let r;return he(()=>{const o=M(n);o.stack=o.stack.slice(2),r=Y(o)}),r}function Y(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 X(e,t,n,{computeHandlingStack:r}={}){let o=e[t];if(typeof o!="function")if(t in e&&t.startsWith("on"))o=B;else return{stop:B};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 To=220*I,_o="$",wo=3;function P(e,t=To){const n=re(Object.prototype),r=re(Array.prototype),o=[],s=new WeakMap,i=pt(e,_o,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+wo,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 Co(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 Co(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 Oo(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 Oo(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){w.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=j(t),l=Ro(e,c,s,t),u=xo(c,e)?Y(e):nn,d=c?an(t,i):void 0,f=e?e.name:void 0,g=on(t),m=sn(t);return{startClocks:o,source:i,handling:a,handlingStack:n,componentStack:r,originalError:t,type:f,message:l,stack:u,causes:d,fingerprint:g,context:m}}function Ro(e,t,n,r){return e!=null&&e.message&&(e!=null&&e.name)?e.message:t?"Empty message":`${n} ${q(P(r))}`}function xo(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 j(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 Ao(e){var t;return(t=/@ (.+)/.exec(e))===null||t===void 0?void 0:t[1]}function j(e){return e instanceof Error||Object.prototype.toString.call(e)==="[object Error]"}function an(e,t){let n=e;const r=[];for(;j(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:Y(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 ko(e){const t=(o,s)=>{const i=rn({stackTrace:o,originalError:s,startClocks:$(),nonErrorPrefix:"Uncaught",source:x.SOURCE,handling:"unhandled"});e.notify(i)},{stop:n}=Lo(t),{stop:r}=Io(t);return{stop:()=>{n(),r()}}}function Lo(e){return X(window,"onerror",({parameters:[t,n,r,o,s]})=>{let i;j(s)?i=M(s):i=yo(t,n,r,o),e(i,s??t)})}function Io(e){return X(window,"onunhandledrejection",({parameters:[t]})=>{const n=t.reason||"Empty reason",r=M(n);e(r,n)})}function Mo(e){const t={version:"6.5.0",onReady(n){n()},...e};return Object.defineProperty(t,"_setDebug",{get(){return tr},enumerable:!1}),t}function Po(e,t,n){const r=e[t];r&&!r.q&&r.version&&w.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=>kt(o,"onReady callback threw an error:")())}function cn(e,t){t.silentMultipleInit||w.error(`${e} is already initialized.`)}function J(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(g=>f.call(t,g,a,c))}return{stop:d}}const Be={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function No(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(Fo(r)),$t(...n)}function Fo(e){return new C(t=>{if(!window.ReportingObserver)return;const n=b((o,s)=>o.forEach(i=>t.notify($o(i)))),r=new window.ReportingObserver(n,{types:e,buffered:!0});return r.observe(),()=>{r.disconnect()}})}function Do(e){return new C(t=>{const{stop:n}=J(e,document,"securitypolicyviolation",r=>{t.notify(Uo(r))});return n})}function $o(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 Uo(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 "${ir(e.originalPolicy,100,"...")}"`:"no policy",e.sourceFile,e.lineNumber,e.columnNumber)})}function un(e){return{startClocks:$(),source:x.REPORT,handling:"unhandled",...e}}function ln(e,t,n,r,o){return n?Y({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=Bo()){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 Bo(){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 Go(){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 jo(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 Wo=500;function gn(){const e=[];return{add:o=>{e.push(o)>Wo&&e.splice(0,1)},remove:o=>{mn(e,o)},drain:o=>{e.forEach(s=>s(o)),e.length=0}}}const Z={log:"log",configuration:"configuration",usage:"usage"},Ho=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],zo=[Gr];let hn=gn(),ae=e=>{hn.add(()=>ae(e))};function Ko(e,t){let n;const r=new C,o=new Set,s=!zo.includes(t.site)&&ve(t.telemetrySampleRate),i={[Z.log]:s,[Z.configuration]:s&&ve(t.telemetryConfigurationSampleRate),[Z.usage]:s&&ve(t.telemetryUsageSampleRate)},a=Vo();ae=l=>{const u=q(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)}},er(yn);function c(l,u,d){return ie({type:"telemetry",date:D(),service:l,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:ie(u,{runtime_env:d,connectivity:Go(),sdk_setup:"npm"}),experimental_features:Array.from(io())},n!==void 0?n():{})}return{setContextProvider:l=>{n=l},observable:r,enabled:s}}function Vo(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function qo(){hn.drain()}function Yo(e){return e.site===Ur}function Sn(e,t){et(_.debug,e,t),ae({type:Z.log,message:e,status:"debug",...t})}function yn(e,t){ae({type:Z.log,status:"error",...Zo(e),...t})}function Xo(e){ae({type:Z.configuration,configuration:e})}function Jo(e){ae({type:Z.usage,usage:e})}function Zo(e){if(j(e)){const t=M(e);return{error:{kind:t.name,stack:Y(Qo(t))},message:t.message}}return{error:{stack:nn},message:`Uncaught ${q(e)}`}}function Qo(e){return e.stack=e.stack.filter(t=>!t.url||Ho.some(n=>t.url.startsWith(n))),e}const _e=1/0,es=H;let we=null;const je=new Set;function ts(){je.forEach(e=>e())}function ns({expireDelay:e,maxEntries:t}){let n=[];const r=[];we||(we=tt(()=>ts(),es));const o=()=>{const g=Re()-e;for(;n.length>0&&n[n.length-1].endTime<g;){const m=n.pop();m&&r.push(m.startTime)}};je.add(o);function s(g,m){const E={value:g,startTime:m,endTime:_e,remove:()=>{mn(n,E)},close:p=>{E.endTime=p}};return t&&n.length>=t&&n.pop(),n.unshift(E),E}function i(g=_e,m={returnInactive:!1}){for(const E of n)if(E.startTime<=g){if(m.returnInactive||g<=E.endTime)return E.value;break}}function a(g){const m=n[0];m&&m.endTime===_e&&m.close(g)}function c(g=_e,m=0){const E=Xn(g,m);return n.filter(p=>p.startTime<=E&&g<=p.endTime).map(p=>p.value)}function l(){return n.map(({startTime:g,endTime:m,value:E})=>({startTime:g,endTime:m===_e?"Infinity":m,value:E}))}function u(){return r}function d(){n=[]}function f(){je.delete(o),je.size===0&&we&&(Dt(we),we=null)}return{add:s,find:i,closeActive:a,findAll:c,reset:d,stop:f,getAllEntries:l,getDeletedEntries:u}}const rs=H,os=st;function ss(e,t,n,r){const o=new C,s=new C,i=Nr(e.sessionStoreStrategyType,e,t,n),a=ns({expireDelay:os});i.renewObservable.subscribe(()=>{a.add(c(),Re()),o.notify()}),i.expireObservable.subscribe(()=>{s.notify(),a.closeActive(Re())}),i.expandOrRenewSession(),a.add(c(),qn().relative),r.observable.subscribe(()=>{r.isGranted()?i.expandOrRenewSession():i.expire()}),is(e,()=>{r.isGranted()&&i.expandOrRenewSession()}),as(e,()=>i.expandSession()),cs(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 is(e,t){ht(e,window,["click","touchstart","keydown","scroll"],t,{capture:!0,passive:!0})}function as(e,t){const n=()=>{document.visibilityState==="visible"&&t()};J(e,document,"visibilitychange",n),tt(n,rs)}function cs(e,t){J(e,window,"resume",t,{capture:!0})}function bn(e){return e>=500}function us(e){try{return e.clone()}catch{return}}const ls=80*I,ds=32,En=3*Mt,fs=H,Tn=pe;function _n(e,t,n,r,o){t.transportStatus===0&&t.queuedPayloads.size()===0&&t.bandwidthMonitor.canHandle(e)?Cn(e,t,n,{onSuccess:()=>On(0,t,n,r,o),onFailure:()=>{t.queuedPayloads.enqueue(e),wn(t,n,r,o)}}):t.queuedPayloads.enqueue(e)}function wn(e,t,n,r){e.transportStatus===2&&Se(()=>{const o=e.queuedPayloads.first();Cn(o,e,t,{onSuccess:()=>{e.queuedPayloads.dequeue(),e.currentBackoffTime=Tn,On(1,e,t,n,r)},onFailure:()=>{e.currentBackoffTime=Math.min(fs,e.currentBackoffTime*2),wn(e,t,n,r)}})},e.currentBackoffTime)}function Cn(e,t,n,{onSuccess:r,onFailure:o}){t.bandwidthMonitor.add(e),n(e,s=>{t.bandwidthMonitor.remove(e),ps(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 On(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:$()}),t.queueFullReported=!0);const s=t.queuedPayloads;for(t.queuedPayloads=vn();s.size()>0;)_n(s.dequeue(),t,n,r,o)}function ps(e){return e.type!=="opaque"&&(e.status===0&&!navigator.onLine||e.status===408||e.status===429||bn(e.status))}function ms(){return{transportStatus:0,currentBackoffTime:Tn,bandwidthMonitor:gs(),queuedPayloads:vn(),queueFullReported:!1}}function vn(){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 gs(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(e){return this.ongoingRequestCount===0||this.ongoingByteCount+e.bytesCount<=ls&&this.ongoingRequestCount<ds},add(e){this.ongoingRequestCount+=1,this.ongoingByteCount+=e.bytesCount},remove(e){this.ongoingRequestCount-=1,this.ongoingByteCount-=e.bytesCount}}}function hs(e,t,n){const r=ms(),o=(s,i)=>bs(e,t,s,i);return{send:s=>{_n(s,r,o,e.trackType,n)},sendOnExit:s=>{Ss(e,t,s)}}}function Ss(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){ys(s)}const o=e.build("xhr",n);St(o,n.data)}let Rn=!1;function ys(e){Rn||(Rn=!0,yn(e))}function bs(e,t,n,r){if(Es()&&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 Es(){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),J({allowUntrustedEvents:!0},r,"loadend",()=>{n==null||n({status:r.status})},{once:!0}),r.send(t)}function yt(){const e=Ts();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=U().location)===null||t===void 0?void 0:t.hostname);const n=yt();return!!n&&n.getAllowedWebViewHosts().some(r=>e===r||e.endsWith(`.${r}`))}function Ts(){return U().DatadogEventBridge}const He={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function _s(e){return new C(t=>{const{stop:n}=ht(e,window,["visibilitychange","freeze"],o=>{o.type==="visibilitychange"&&document.visibilityState==="hidden"?t.notify({reason:He.HIDDEN}):o.type==="freeze"&&t.notify({reason:He.FROZEN})},{capture:!0}),r=J(e,window,"beforeunload",()=>{t.notify({reason:He.UNLOADING})}).stop;return()=>{n(),r()}})}function ws(e){return Le(He).includes(e)}function Cs({encoder:e,request:t,flushController:n,messageBytesLimit:r}){let o={};const s=n.flushObservable.subscribe(d=>u(d));function i(d,f,g){n.notifyBeforeAddMessage(f),g!==void 0?(o[g]=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 g=e.estimateEncodedBytesCount(f);n.notifyAfterRemoveMessage(g)}function l(d,f){const g=q(d),m=e.estimateEncodedBytesCount(g);if(m>=r){w.warn(`Discarded a message whose size was bigger than the maximum allowed size ${r}KB. ${Oe} ${At}/#technical-limitations`);return}a(f)&&c(f),i(g,m,f)}function u(d){const f=Le(o).join(`\n`);o={};const g=ws(d.reason),m=g?t.sendOnExit:t.send;if(g&&e.isAsync){const E=e.finishSync();E.outputBytesCount&&m(xn(E));const p=[E.pendingData,f].filter(Boolean).join(`\n`);p&&m({data:p,bytesCount:Qe(p)})}else f&&e.write(e.isEmpty?f:`\n${f}`),e.finish(E=>{m(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 Os({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 C(()=>()=>{s.unsubscribe(),i.unsubscribe()});let c=0,l=0;function u(m){if(l===0)return;const E=l,p=c;l=0,c=0,g(),a.notify({reason:m,messagesCount:E,bytesCount:p})}let d;function f(){d===void 0&&(d=Se(()=>{u("duration_limit")},n))}function g(){Ft(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&&g()}}}function An(e,t,n,r,o,s,i=Cs){const a=l(e,t),c=n&&l(e,n);function l(u,{endpoint:d,encoder:f}){return i({encoder:f,request:hs(d,u.batchBytesLimit,r),flushController:Os({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 ze(){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 Rs(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:$()})}finally{o=!1}}return!0}}}let bt;const Et=new WeakMap;function xs(e){return bt||(bt=As(e)),bt}function As(e){return new C(t=>{const{stop:n}=X(XMLHttpRequest.prototype,"open",ks),{stop:r}=X(XMLHttpRequest.prototype,"send",s=>{Ls(s,e,t)},{computeHandlingStack:!0}),{stop:o}=X(XMLHttpRequest.prototype,"abort",Is);return()=>{n(),r(),o()}})}function ks({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=$(),s.isAborted=!1,s.xhr=e,s.handlingStack=t;let i=!1;const{stop:a}=X(e,"onreadystatechange",()=>{e.readyState===XMLHttpRequest.DONE&&c()}),c=()=>{if(l(),a(),i)return;i=!0;const u=o;u.state="complete",u.duration=Yn(s.startClocks.timeStamp,D()),u.status=e.status,r.notify(Qn(u))},{stop:l}=J(n,e,"loadend",c);r.notify(s)}function Is({target:e}){const t=Et.get(e);t&&(t.isAborted=!0)}let Tt;function kn(){return Tt||(Tt=Ms()),Tt}function Ms(){return new C(e=>{if(!window.fetch)return;const{stop:t}=X(window,"fetch",n=>Ps(n,e),{computeHandlingStack:!0});return t})}function Ps({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={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=>Ns(r,d,u))}function Ns(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 _t={};function Fs(e){const t=e.map(n=>(_t[n]||(_t[n]=Ds(n)),_t[n]));return $t(...t)}function Ds(e){return new C(t=>{const n=L[e];return L[e]=(...r)=>{n.apply(console,r);const o=Ue("console error");he(()=>{t.notify($s(r,e,o))})},()=>{L[e]=n}})}function $s(e,t,n){const r=e.map(s=>Us(s)).join(" ");let o;if(t===_.error){const s=e.find(j);o={stack:s?Y(M(s)):void 0,fingerprint:on(s),causes:s?an(s,"console"):void 0,startClocks:$(),message:r,source:x.CONSOLE,handling:"handled",handlingStack:n,context:sn(s)}}return{api:t,message:r,error:o,handlingStack:n}}function Us(e){return typeof e=="string"?P(e):j(e)?tn(M(e)):q(P(e),void 0,2)}function Bs(e){const t=fn(e)==="object";return t||w.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)&&w.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 C,s={getContext:()=>pn(r),setContext:i=>{Bs(i)?(r=P(wt(i,n,e)),t==null||t.updateCustomerData(r)):s.clearContext(),o.notify()},setContextProperty:(i,a)=>{r=P(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 Gs="_dd_c",js=[];function Ct(e,t,n,r){const o=Ws(n,r);js.push(J(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 Ws(e,t){return`${Gs}_${e}_${t}`}const Hs=3*I,zs=16*I,Ks=200;function Vs(e=2){const t=new Map;let n=!1;function r(o=0){if(n||e===0)return;const s=e===2?Hs:zs;let i=o;t.forEach(a=>{i+=a.getBytesCount()}),i>s&&(qs(s),n=!0)}return{createDetachedTracker:()=>{const o=Ln(()=>r(o.getBytesCount()));return o},getOrCreateTracker:o=>(t.has(o)||t.set(o,Ln(r)),t.get(o)),setCompressionStatus:o=>{e===0&&(e=o,r())},getCompressionStatus:()=>e,stop:()=>{t.forEach(o=>o.stop()),t.clear()}}}function Ln(e){let t=0;const{throttled:n,cancel:r}=Ut(s=>{t=Qe(q(s)),e()},Ks),o=()=>{r(),t=0};return{updateCustomerData:s=>{ge(s)?o():n(s)},resetCustomerData:o,getBytesCount:()=>t,stop:()=>{r()}}}function qs(e){w.warn(`Customer data exceeds the recommended ${e/I}KiB threshold. ${Oe} ${At}/#customer-data-exceeds-the-recommended-threshold-warning`)}function Ys(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(B);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 Xs="datadog-synthetics-public-id",Js="datadog-synthetics-result-id",Zs="datadog-synthetics-injects-rum";function In(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||z(Zs))}function Qs(){const e=window._DATADOG_SYNTHETICS_PUBLIC_ID||z(Xs);return typeof e=="string"?e:void 0}function ei(){const e=window._DATADOG_SYNTHETICS_RESULT_ID||z(Js);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 ti=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 Ce={console:"console",http:"http",silent:"silent"},ni=Object.keys(S);let k=class{constructor(t,n,r,o=Ce.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=P(n);let a;if(o!=null){const c=rn({stackTrace:j(o)?M(o):void 0,originalError:o,nonErrorPrefix:"Provided",source:x.LOGGER,handling:"handled",startClocks:$()});a=ie({error:qe(c,{includeMessage:!0})},i)}else a=i;this.handleLogStrategy({message:P(t),context:a,status:r},this,s)}log(t,n,r=S.info,o){let s;Ve(r,Ce.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}};ti([nr],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,Ce.http,this)&&(o=Ue("log")),this.logImplementation(t,n,e,r,o)}}function ri(e,t,n){return{view:{referrer:document.referrer,url:window.location.href},context:e.getContext(),user:t.getContext(),account:n.getContext()}}const oi=32*I;function si(e){e.usePciIntake===!0&&e.site&&e.site!=="datadoghq.com"&&w.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");const t=no(e),n=Pn(e.forwardConsoleLogs,Le(_),"Forward Console Logs"),r=Pn(e.forwardReports,Le(Be),"Forward Reports");if(!(!t||!n||!r))return e.forwardErrorsToLogs&&!n.includes(_.error)&&n.push(_.error),{forwardErrorsToLogs:e.forwardErrorsToLogs!==!1,forwardConsoleLogs:n,forwardReports:r,requestErrorResponseLengthLimit:oi,...t}}function Pn(e,t,n){if(e===void 0)return[];if(!(e==="all"||Array.isArray(e)&&e.every(r=>t.includes(r)))){w.error(`${n} should be "all" or an array with allowed values "${t.join(\'", "\')}"`);return}return e==="all"?t:jo(e)}function ii(e){const t=ro(e);return{forward_errors_to_logs:e.forwardErrorsToLogs,forward_console_logs:e.forwardConsoleLogs,forward_reports:e.forwardReports,use_pci_intake:e.usePciIntake,...t}}function ai(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){w.error("Missing configuration");return}if(oo(c.enableExperimentalFeatures),We()&&(c=ci(c)),o=c,s){cn("DD_LOGS",c);return}const l=si(c);l&&(s=l,kn().subscribe(B),t.tryToInit(l.trackingConsent),a())},get initConfiguration(){return o},getInternalContext:B,handleLog(c,l,u,d=e(),f=D()){r.add(g=>g.handleLog(c,l,u,d,f))}}}function ci(e){return{...e,clientToken:"empty"}}const Ot="logs";function ui(e){const t=Vs(),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=Fr();function i(){return ri(n,r,o)}let a=ai(i,s,(u,d)=>{u.storeContextsAcrossPages&&(Ct(d,n,Ot,2),Ct(d,r,Ot,1),Ct(d,o,Ot,4));const f=e(u,d,i,s);return a=li(u,f),f});const c={},l=new k((...u)=>a.handleLog(...u),t.createDetachedTracker());return Mo({logger:l,init:b(u=>a.init(u)),setTrackingConsent:b(u=>{s.update(u),Jo({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(),P(u),d.handler,d.level,P(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 li(e,t){return{init:n=>{cn("DD_LOGS",n)},initConfiguration:e,...t}}const di="logs";function fi(e,t){const n=ss(e,di,r=>mi(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 pi(e){const n=Nn(e)==="1"?{}:void 0;return{findTrackedSession:()=>n,expireObservable:new C}}function Nn(e){return ve(e.sessionSampleRate)?"1":"0"}function mi(e,t){const n=gi(t)?t:Nn(e);return{trackingType:n,isTracked:n==="1"}}function gi(e){return e==="0"||e==="1"}let Fn=!1;function Ye(e){const t=window;if(In()){const r=n(t.DD_RUM_SYNTHETICS);return!r&&!Fn&&(Fn=!0,Sn("Logs sent before RUM is injected by the synthetics worker",{testId:Qs(),resultId:ei()})),r}return n(t.DD_RUM);function n(r){if(r&&r.getInternalContext)return r.getInternalContext(e)}}function hi(e,t,n,r,o){const s=ni.concat(["custom"]),i={};s.forEach(a=>{i[a]=Rs(a,t.eventRateLimiterThreshold,o)}),n.subscribe(0,({rawLogsEvent:a,messageContext:c=void 0,savedCommonContext:l=void 0,domainContext:u})=>{var d,f;const g=Jn(a.date),m=e.findTrackedSession(g);if(!e.findTrackedSession(g,{returnInactive:!0}))return;const p=l||r();let v;!ge(p.account)&&p.account.id&&(v=p.account),m&&m.anonymousId&&!p.user.anonymous_id&&(p.user.anonymous_id=m.anonymousId);const R=ie({service:t.service,session_id:m?m.id:void 0,session:m?{id:m.id}:void 0,usr:ge(p.user)?void 0:p.user,account:v,view:p.view},p.context,Ye(g),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 Si={[_.log]:S.info,[_.debug]:S.debug,[_.info]:S.info,[_.warn]:S.warn,[_.error]:S.error};function yi(e,t){const n=Fs(e.forwardConsoleLogs).subscribe(r=>{var o;const s={rawLogsEvent:{date:D(),message:r.message,origin:x.CONSOLE,error:r.error&&qe(r.error),status:Si[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 bi(e,t){const n=No(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 ${Ao(r.stack)}`),t.notify(0,{rawLogsEvent:{date:D(),message:o,origin:x.REPORT,error:s,status:i}})});return{stop:()=>{n.unsubscribe()}}}function Ei(e,t){if(!e.forwardErrorsToLogs)return{stop:B};const n=xs(e).subscribe(s=>{s.state==="complete"&&o("xhr",s)}),r=kn().subscribe(s=>{s.state==="resolve"&&o("fetch",s)});function o(s,i){!eo(i.url)&&(Ci(i)||bn(i.status))&&("xhr"in i?Ti(i.xhr,e,a):i.response?wi(i.response,e,a):i.error&&_i(i.error,e,a));function a(c){const l={isAborted:i.isAborted,handlingStack:i.handlingStack};t.notify(0,{rawLogsEvent:{message:`${Oi(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 Ti(e,t,n){typeof e.response=="string"?n(vt(e.response,t)):n(e.response)}function _i(e,t,n){n(vt(Y(M(e)),t))}function wi(e,t,n){const r=us(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(vt(o,t))),b(o=>n(`Unable to retrieve response: ${o}`)))}function Ci(e){return e.status===0&&e.responseType!=="opaque"}function vt(e,t){return e.length>t.requestErrorResponseLengthLimit?`${e.substring(0,t.requestErrorResponseLengthLimit)}...`:e}function Oi(e){return e==="xhr"?"XHR":"Fetch"}function vi(e,t,n){Ys(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 Ri(e,t){if(!e.forwardErrorsToLogs)return{stop:B};const n=new C,{stop:r}=ko(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 xi=vs;function Ai(e){function t(n,r,o,s,i){const a=ie(r.getContext(),n.context);if(Ve(n.status,Ce.console,r)&&Li(n,a),Ve(n.status,Ce.http,r)){const c={rawLogsEvent:{date:i||D(),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 ki={[S.ok]:_.debug,[S.debug]:_.debug,[S.info]:_.info,[S.notice]:_.info,[S.warn]:_.warn,[S.error]:_.error,[S.critical]:_.error,[S.alert]:_.error,[S.emerg]:_.error};function Li({status:e,message:t},n){W[ki[e]].call(L,t,n)}function Ii(e,t,n,r,o){const s=An(e,{endpoint:e.logsEndpointBuilder,encoder:ze()},e.replica&&{endpoint:e.replica.logsEndpointBuilder,encoder:ze()},n,r,o.expireObservable);return t.subscribe(1,i=>{s.add(i)}),s}function Mi(e){const t=yt();e.subscribe(1,n=>{t.send("log",n)})}function Pi(e){return{get:t=>{const n=e.findTrackedSession(t);if(n)return{session_id:n.id}}}}function Ni(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 Fi(e,t,n,r,o){const s=Ko("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=An(t,{endpoint:t.rumEndpointBuilder,encoder:ze()},t.replica&&{endpoint:t.replica.rumEndpointBuilder,encoder:ze()},n,r,o.expireObservable);i.push(()=>a.stop());const c=s.observable.subscribe(l=>a.add(l,Yo(t)));i.push(()=>c.unsubscribe())}return qo(),Xo(ii(e)),{telemetry:s,stop:()=>{i.forEach(a=>a())}}}function Di(e,t,n,r){const o=new xi,s=[];o.subscribe(1,f=>dn("logs",f));const i=Ni(o),a=_s(t),c=t.sessionStoreStrategyType&&!We()&&!In()?fi(t,r):pi(t),{stop:l}=Fi(e,t,i,a,c);s.push(()=>l()),Ei(t,o),Ri(t,o),yi(t,o),bi(t,o);const{handleLog:u}=Ai(o);if(hi(c,t,o,n,i),We())Mi(o);else{const{stop:f}=Ii(t,o,i,a,c);s.push(()=>f())}const d=Pi(c);return{handleLog:u,getInternalContext:d.get,stop:()=>{s.forEach(f=>f())}}}const ce=ui(Di);Po(U(),"DD_LOGS",ce);const O=class O{constructor(t,n,r,o,s){this.copy=()=>new O(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,O.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,g=this.field;const m=l*60+u,p=(m-Math.floor(m/10))*c;return l*(a*3600)+u*(a*60)+d*a+(f*2+g)-p},this.addSeconds=i=>{let a=this.copy();return a.s+=i,a.s>=60&&(a.s=0,a.m++,a.m>=60&&(a.m=0,a.h++)),a},this.addFrames=(i,a)=>{let c=this.toFrames(a);return c+=i,O.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(;O.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}};O.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=O.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),O.fromFrames(l,o)},O.calculateCurrentOffset=(t,n)=>{for(let r=1;r<n.length;r++)if(t<n[r].frame)return n[r-1].offset;return n[n.length-1].offset},O.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 g=c;d+=u*10;let m=0;return m=g%2,g=Math.floor(g/2),new O(l,d,f,g,m)},O.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},O.fromStr=t=>{const r=t.split("_").map(Number);if(r.length==4){const[o,s,i,a]=r;return new O(o,s,i,a,0)}else if(r.length==5){const[o,s,i,a,c]=r;return new O(o,s,i,a,c)}else throw new Error("Invalid timecode format: "+t)},O.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),g=c?Number(c):0;return new O(l,u,d,f,g)};let Q=O;const h=class h{constructor(t){this.isLoggingOn=t.LOG_TO_DATADOG,this.isLoggingOn&&ce.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!1,sessionSampleRate:100}),h.tracking.dev=`${t.platform}_${t.browserName}`,h.beatHandle||(console.log("[Logger] Starting tracking beat"),h.beatHandle=window.setInterval(h.flushTracking,15e3))}static setMessagePort(t){this.messagePort=t}static getMessagePort(){return this.messagePort}setLoggingOn(t){this.isLoggingOn=t}setAttributes(t){h.processAttributes(t);for(const n in t)ce.logger.setContextProperty(n,t[n])}info(t,n){n&&h.processAttributes(n),this.isLoggingOn&&(ce.logger.info(t,n),console.log("[Logger] Sending info: ",t))}error(t,n){n&&h.processAttributes(n),this.isLoggingOn&&(ce.logger.error(t,n),h.tracking.err_time=Date.now().toFixed(0),h.tracking.err_desc=t,console.log("[Logger] Sending error: ",t))}warn(t,n){n&&h.processAttributes(n),this.isLoggingOn&&(ce.logger.warn(t,n),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){h.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:t})}static info(t,n){h.messagePort.postMessage({type:"LOG",actionType:"INFO",message:t,attributes:n})}static error(t,n){h.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:t,attributes:n})}static warn(t,n){h.messagePort.postMessage({type:"LOG",actionType:"WARN",message:t,attributes:n})}static processAttributes(t){t.player_version&&(h.tracking.sdk=t.player_version),t.media_id&&(h.tracking.gid=t.media_id),t.game_id&&(h.tracking.buc=t.game_id),t.bb_session_id&&(h.tracking.sid=t.bb_session_id,console.log("[Logger] Setting bb_session_id:",h.tracking.sid)),t.last_timecode&&(h.tracking.tc=t.last_timecode,h.lastTimecodeMillis=Q.fromStr(t.last_timecode).totalMilliseconds(59.94),h.lastTimecodeMillis&&h.lastZipMillis&&(h.tracking.cache=(h.lastZipMillis-h.lastTimecodeMillis).toFixed(0))),t.last_offset&&(h.tracking.off=t.last_offset),t.last_loading_zip&&(h.tracking.zip=t.last_loading_zip,h.lastZipMillis=Q.fromStr(t.last_loading_zip).totalMilliseconds(59.94),h.lastTimecodeMillis&&h.lastZipMillis&&(h.tracking.cache=(h.lastZipMillis-h.lastTimecodeMillis).toFixed(0))),t.last_rendered_frame&&(h.tracking.aug_time=Date.now().toFixed(0)),t.asset&&(h.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("&")}};h.tracking={start:Date.now().toFixed(0),dev:"",sdk:"",mac:"",gid:"",sid:"",off:"",zip:"",aug_time:"",err_time:"",err_desc:"",tc:"",png:"",asset:"",cache:"",buc:""},h.lastTimecodeMillis=0,h.lastZipMillis=0,h.flushTracking=()=>{const t=Date.now().toFixed(0);h.tracking.now=t;const r=`https://dwu3k7rrxk5s3.cloudfront.net/metrics/1.gif?${h.objectToQuery(h.tracking)}`;console.log("[Logger] Flushing tracking data:",r),fetch(r,{method:"GET",mode:"no-cors",keepalive:!0}).catch(()=>{})};let ue=h;const Dn=(()=>{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"}})();class $i{constructor(){this.start=0,this.end=0,this.startTimeoutForSeconds=t=>{this.start=performance.now(),this.end=this.start+t*1e3},this.isTimeout=()=>{const t=performance.now()>=this.end;return t&&(this.start=0,this.end=0),!t}}}const Rt={lastRendererFrameSent:0,isRAFSeen:!1,isRVFCSeen:!1,RVFCmissed:!1,RVFCframeExpected:0,compensationMode:!1,compensationCounter:0,frameCorrection:0,lastMessageSent:""};let Xe=null,A,T,$n=new $i;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=Ui),t.type==="ADAPTER_UPDATE_DATA"&&(T=t.data,Un()),t.type==="SET_OPTIONS"&&(A=t.options,ue.setMessagePort(self))};function Ui(e){A&&ee(A,"Adapter")&&console.log("[AdapterWorker] Message from Renderer:",e.data)}const Un=()=>{!T||T.siData.isVideoPaused||(Dn.isChromeMac()?Bi():Dn.isSafariMac()&&Gi())},Bi=()=>{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 v=parseInt(r["Window End (ms)"],10);isNaN(v)||(s=v);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,v)=>Math.abs(v.expectedDisplayTime-l)<Math.abs(p.expectedDisplayTime-l)?v:p),d=u.expectedDisplayTime-o,f=[];for(let p=-10;p<10;p++)f.push(d+p*c);const g=u.expectedDisplayTime-s,m=[];for(let p=-10;p<10;p++)m.push(g+p*c);let E=null;f.forEach((p,v)=>{l>p&&l<m[v]&&(E=v-10)}),E!==null?setTimeout(p=>xt(t.lastCalculatedMediaTimeVideoFrame+p*Math.round(60/t.videoFPS)+i),a,E):xt(Rt.lastRendererFrameSent)}},Gi=()=>{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=Q.fromFrames(e,6e4/1001);if($n.isTimeout())Bn(n);else{const r=T.vfcData.videoFPS;if(r<=10||r>70){console.error("Video FPS is out of supported range: "+r),$n.startTimeoutForSeconds(3),Bn(n);return}T.afData.animationFPS,ji(n,t)}},ji=(e,t)=>{const n=Q.toStr(e);Rt.lastMessageSent=n,A&&ee(A,"Adapter")&&console.log(`[AdapterWorker] Rendering augmentation for timecode: ${n} , ${e}`),Gn(n,t)},Bn=e=>{const t=Q.toStr(e);A&&ee(A,"Adapter")&&console.log("[AdapterWorker] Clearing augmentation"),Gn(t,0,!0)},Gn=(e,t,n)=>{if(!Xe||!T)return;const r=e;A&&ee(A,"Adapter")&&console.log(`[AdapterWorker] Sending current time code to the Renderer: ${r}`);const o={timeCode:r,frameCorrection:t||0,fps:Hn(T.siData.workingFps),cloudFrontURL:T.cloudFrontURL,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}),A&&(ee(A,"Errors")&&console.error("[AdapterWorker] Unhandled rejection:",e.reason),e.preventDefault())},self.onerror=e=>{ue.error("[AdapterWorker] Unhandled error",{error:e}),A&&(ee(A,"Errors")&&console.error("[AdapterWorker] Unhandled error:",e),e instanceof Event&&e.preventDefault())},setInterval(Un,2)})();\n',Vt=typeof self<"u"&&self.Blob&&new Blob([Gt],{type:"text/javascript;charset=utf-8"});function or(t){let e;try{if(e=Vt&&(self.URL||self.webkitURL).createObjectURL(Vt),!e)throw"";const n=new Worker(e,{name:t==null?void 0:t.name});return n.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),n}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)}}class jt{constructor(){this.metrics=new Map,this.containers=[],this.createContainer=()=>{const e=document.createElement("div");e.style.display="flex",e.style.gap="10px",e.style.marginBottom="5px",e.style.fontSize="14px";const n={div:e,metrics:[]};return this.containers.push(n),document.body.appendChild(e),n},this.createMetric=(e,n)=>{const r=document.createElement("span"),i={name:e,value:"",span:r};return n.metrics.push(i),r.textContent=`${e}: ${i.value}`,n.div.appendChild(r),this.metrics.set(e,i),i},this.updateMetric=(e,n)=>{const r=this.metrics.get(e);if(!r){console.error("Metric does not exist");return}typeof n=="boolean"?r.value=n?"true":"false":r.value=n,r.span.textContent=`${e}: ${r.value}`}}delete(){this.containers.forEach(e=>{e.div.remove()})}}class ar{constructor(e){if(this.canPlayListner=()=>this.setupCanvas(),this.clickListner=n=>{this.clicker.click(n)},this.mediaTime=0,this.timecodeChecker=new tr(0),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 r=this.metrics.createContainer();this.metrics.createMetric("Rendering GPU time",r),this.metrics.createMetric("Rendering CPU time",r),this.metrics.createMetric("Chunking time",r),this.metrics.createMetric("Decoding time",r)}}this.downloaderWorker=new rr,this.decoderWorker=new sr,this.rendererWorker=new ir,this.adapterWorker=new or,window.BB.workerInstances.push(this.downloaderWorker,this.decoderWorker,this.rendererWorker,this.adapterWorker),this.rendererToDownloader=new MessageChannel,this.rendererToMain=new MessageChannel,this.downloaderToDecoder=new MessageChannel,this.decoderToRenderer=new MessageChannel,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 nr(this.OTTPlayer.video,this.rendererWorker),this.segmentFirstFrameTimecode=new F,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(n=>{n.update()}),this.animationFrameLoopId=requestAnimationFrame(e)};this.animationFrameLoopId=requestAnimationFrame(e)}startVideoFrameCallbackLoop(){const e=(n,r)=>{this.mediaTime=r.mediaTime,this.videoFPScalculator.addTimestamp(r.mediaTime),this.videoFrameCallbackLoopId=this.OTTPlayer.video.requestVideoFrameCallback(e)};this.videoFrameCallbackLoopId=this.OTTPlayer.video.requestVideoFrameCallback(e)}setupCanvas(){const e=this.OTTPlayer.video,n=e.parentElement;this.canvas.width=e.videoWidth,this.canvas.height=e.videoHeight,this.canvas.style.zIndex="3000",this.canvas.style.position="absolute",this.canvas.style.top="50%",this.canvas.style.transform="translateY(-50%)",this.canvas.style.left="0",this.canvas.style.width=n.style.width,this.canvas.style.height=n.style.height,this.canvas.style.pointerEvents="none",n.addEventListener("click",this.clickListner),n.style.position="relative",n.appendChild(this.canvas);const r=this.canvas.transferControlToOffscreen(),i={type:"INIT_OFFSCREEN",offscreen:r,options:this.options};this.rendererWorker.postMessage(i,[r]),e.onseeked=()=>{this.onVideoSeeked()},e.onseeking=()=>{this.onVideoSeeked()}}setupWorkers(){this.downloaderWorker.onmessage=e=>{e.data.type==="LOG"?(e.data.actionType==="SET_ATTRIBUTES"&&e.data.attributes.last_loading_zip&&this.metrics&&this.metrics.updateMetric("Last Downloaded Zip",e.data.attributes.last_loading_zip),this.logger.handleMessageFromWorker(e.data)):e.data.type==="TRACK_PERFORMANCE"&&this.trackPerformance(e.data)},this.decoderWorker.onmessage=e=>{e.data.type==="LOG"?(e.data.actionType==="SET_ATTRIBUTES"&&e.data.attributes.last_decoded_frame&&this.metrics&&this.metrics.updateMetric("Last Decoded Frame",e.data.attributes.last_decoded_frame),this.logger.handleMessageFromWorker(e.data)):e.data.type==="TRACK_PERFORMANCE"&&this.trackPerformance(e.data)},this.rendererWorker.onmessage=e=>{e.data.type==="LOG"?(e.data.actionType==="SET_ATTRIBUTES"&&this.metrics&&(e.data.attributes.last_webgl_uploaded_frame&&this.metrics.updateMetric("Last WebGL Uploaded Frame",e.data.attributes.last_webgl_uploaded_frame),e.data.attributes.last_rendered_frame&&this.metrics.updateMetric("Last Rendered Frame",e.data.attributes.last_rendered_frame),e.data.attributes.renderer_state&&this.metrics.updateMetric("Renderer State",e.data.attributes.renderer_state)),this.logger.handleMessageFromWorker(e.data)):e.data.type==="TRACK_PERFORMANCE"&&this.trackPerformance(e.data)},this.adapterWorker.onmessage=e=>{e.data.type==="LOG"?this.logger.handleMessageFromWorker(e.data):e.data.type==="TRACK_PERFORMANCE"&&this.trackPerformance(e.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.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=e=>{e.data.type==="LOG"?(e.data.actionType==="SET_ATTRIBUTES"&&this.metrics&&(e.data.attributes.last_webgl_uploaded_frame&&this.metrics.updateMetric("Last WebGL Uploaded Frame",e.data.attributes.last_webgl_uploaded_frame),e.data.attributes.last_rendered_frame&&this.metrics.updateMetric("Last Rendered Frame",e.data.attributes.last_rendered_frame),e.data.attributes.renderer_state&&this.metrics.updateMetric("Renderer State",e.data.attributes.renderer_state)),this.logger.handleMessageFromWorker(e.data)):e.data.type==="TRACK_PERFORMANCE"&&this.trackPerformance(e.data)},this.downloaderWorker.postMessage({type:"SET_OPTIONS",options:this.options}),this.decoderWorker.postMessage({type:"SET_OPTIONS",options:this.options}),this.adapterWorker.postMessage({type:"SET_OPTIONS",options:this.options}),this.rendererWorker.postMessage({type:"SET_OPTIONS",options:this.options})}callAdapterWorker(e){this.adapterWorker.postMessage({type:"ADAPTER_UPDATE_DATA",data:e})}callRendererWorker(e,n,r){this.options&&I(this.options,"Clocker")&&console.log(`[Clocker] Sending current time code to the Renderer: ${e}`);const i=r?"RENDERER_CLEAR":"RENDERER_DRAW";if(!e||!this.OTTPlayer.gameParams||!this.OTTPlayer.gameParams.bucketName||!this.OTTPlayer.gameParams.offsets){const a={type:i};this.rendererWorker.postMessage(a);return}const s={timeCode:e,frameCorrection:n||0,fps:he(this.videoFPScalculator.getFPS()),cloudFrontURL:this.OTTPlayer.options.cloudFrontURL,bucketName:this.OTTPlayer.gameParams.bucketName,offsets:this.OTTPlayer.gameParams.offsets,customerId:this.OTTPlayer.gameParams.customerId},o={type:i,streamData:s};this.rendererWorker.postMessage(o),r||this.logger.setAttributes({last_timecode:e})}onVideoSeeked(){this.downloaderWorker.postMessage({type:"VIDEO_SEEKED"}),this.decoderWorker.postMessage({type:"VIDEO_SEEKED"}),this.rendererWorker.postMessage({type:"VIDEO_SEEKED"}),this.OTTPlayer.adapter&&this.OTTPlayer.adapter.onVideoSeeked(),this.logger.info("didSeek")}trackPerformance(e){var n;if((n=this.options.debug)!=null&&n.trackPerformance&&this.metrics)for(let r of e.data)this.metrics.updateMetric(r.metric,r.value.toFixed(2))}delete(){const e=this.OTTPlayer.video,n=e.parentElement;n.removeChild(this.canvas),this.rendererWorker.terminate(),this.downloaderWorker.terminate(),this.decoderWorker.terminate(),this.adapterWorker.terminate(),this.metrics&&this.metrics.delete(),this.animationFrameLoopId&&cancelAnimationFrame(this.animationFrameLoopId),this.videoFrameCallbackLoopId&&e.cancelVideoFrameCallback(this.videoFrameCallbackLoopId),e.removeEventListener("canplay",this.canPlayListner),n.removeEventListener("click",this.clickListner)}}class cr{constructor(){this.controls=new Map,this.containers=[]}createContainer(e){const n=document.createElement("div");n.style.display="flex",n.style.flexWrap="wrap",n.style.gap="10px",n.style.padding="10px",n.style.marginBottom="10px",n.style.border="1px solid #ccc",n.style.fontSize="14px",n.style.backgroundColor="#f9f9f9";const r=document.createElement("button");r.textContent="Apply",r.style.cursor="pointer";const i={div:n,controls:[],button:r};return r.addEventListener("click",()=>{const s={};i.controls.forEach(o=>{o.type==="input"||o.type==="select"?o.appliedValue=o.element.value:o.type==="checkbox"&&(o.appliedValue=String(o.element.checked)),s[o.name]=o.appliedValue}),e&&e(s)}),n.appendChild(r),document.body.appendChild(n),this.containers.push(i),i}createInput(e,n="",r){const i=document.createElement("label");i.style.display="flex",i.style.flexDirection="column",i.style.fontWeight="bold";const s=document.createElement("span");s.textContent=e,s.style.marginBottom="3px";const o=document.createElement("input");o.type="text",o.value=String(n),o.style.minWidth="60px";const a={name:e,type:"input",element:o,container:r,appliedValue:String(n)};this.controls.set(e,a),r.controls.push(a),i.appendChild(s),i.appendChild(o),r.div.insertBefore(i,r.button)}createSelect(e,n,r="",i){const s=document.createElement("label");s.style.display="flex",s.style.flexDirection="column",s.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(n).forEach(([l,u])=>{const d=document.createElement("option");d.textContent=l,d.value=String(u),a.appendChild(d)}),a.value=String(r);const c={name:e,type:"select",element:a,container:i,appliedValue:String(r)};this.controls.set(e,c),i.controls.push(c),s.appendChild(o),s.appendChild(a),i.div.insertBefore(s,i.button)}createCheckbox(e,n=!1,r){const i=document.createElement("label");i.style.display="flex",i.style.fontWeight="bold";const s=document.createElement("span");s.textContent=e,s.style.marginRight="5px";const o=document.createElement("input");o.type="checkbox",o.checked=n;const a={name:e,type:"checkbox",element:o,container:r,appliedValue:String(n)};this.controls.set(e,a),r.controls.push(a),i.appendChild(s),i.appendChild(o),r.div.insertBefore(i,r.button)}exportData(){const e={};return this.controls.forEach(n=>{e[n.name]=n.appliedValue}),e}getValue(e){const n=this.controls.get(e);return n?n.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"),rt=":",lr=(t,e,n=!1)=>{let r="";return Array.isArray(t)?(r=[Ue(t[0]),Ue(t[1]),Ue(t[2]),Ue(t[3])].join(":"),n==!0?t[4]==1&&e?r+=".2":r+=".1":t[4]==1&&e&&(r+=".1")):(r=("0"+t.h).slice(-2)+rt+("0"+t.m).slice(-2)+rt+("0"+t.s).slice(-2)+rt+("0"+t.f).slice(-2),r+="."+(t.field?"1":"2")),r},ur=(t,e,n)=>{let r=60,i=0;Math.floor(e)==60?(r=60,i=0):Math.floor(e)==59?(r=60,i=4):Math.floor(e)==30?(r=30,i=0):Math.floor(e)==29&&(r=30,i=2);let s=0,a=Math.floor(e*60*10)*6,c=t[0],l=t[1],u=t[2],d=t[3],f=t[4];return s+=c*a,s+=l*(r*60),s+=u*r,s+=d*2+f,s-=i*l,s+=i*Math.floor(l/10),s},P=(()=>{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",n=()=>t()==="iPad",r=()=>t()==="iOS",i=()=>{const g=t();return g==="iOS"||g==="Mac"||g==="iPad"},s=()=>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 v=this.header.join(" ");return this.matchItem(v,this.dataos)},matchItem(v,T){for(let k=0;k<T.length;k+=1)if(new RegExp(T[k].value,"i").test(v))return T[k].name;return"unknown"}}).init(),l=()=>{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:n,isiPhone:r,isApple:i,isWindows:s,isAndroid:o,getDeviceDescription:a,getDeviceName:c,getBrowserName:l,isSafariMac:()=>e()&&l()==="Safari",isChromeMac:()=>e()&&l()==="Chrome",isChromeWin:()=>s()&&l()==="Chrome",isFirefoxMac:()=>e()&&l()==="Firefox",isFirefoxWin:()=>s()&&l()==="Firefox"}})();class dr{constructor(){this.start=0,this.end=0,this.startTimeoutForSeconds=e=>{this.start=performance.now(),this.end=this.start+e*1e3},this.isTimeout=()=>{const e=performance.now()>=this.end;return e&&(this.start=0,this.end=0),!e}}}class fr{constructor(e){if(this.platformSupported=!0,this.firstFrameTimecodeSet=!1,this.firstFrameTimecode=[0,0,0,0,0],this.firstVideoFrameCallbackFired=!1,this.timeout=new dr,this.loggerTimeoutStart=0,this.loggerTimeout=1e4,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.onAnimationFrame=n=>{if(this.video.paused||!this.OTTPlayer.clocker||!this.OTTPlayer.gameParams||!this.syncPoint){window.requestAnimationFrame(this.onAnimationFrame);return}this.afData.counter++,this.afData.previousTimestamp=this.afData.lastTimestamp,this.afData.lastTimestamp=performance.now(),this.afData.lastMetadataNow=n,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 r=(this.video.currentTime-this.syncPoint.playerTime)*(6e4/1001);this.afData.lastPlayerTimeFromSync=r;const i=Math.floor(r)+this.syncPoint.frame;this.afData.playerTimeOffset=F.calculateCurrentOffset(i,this.OTTPlayer.gameParams.offsets);let s=i-this.afData.playerTimeOffset;if(s<0&&(s+=5178816),s++,this.afData.lastCalculatedPlayerTimeVideoFrame=s,this.afData.previousCalculatedPlayerTimeFraction=this.afData.lastCalculatedPlayerTimeFraction,this.afData.lastCalculatedPlayerTimeFraction=r-Math.floor(r),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&&I(this.options,"Adapter")&&console.error(o)}window.requestAnimationFrame(this.onAnimationFrame),this.determineFrameUpdate()},this.onVideoFrame=(n,r)=>{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.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 i=(r.mediaTime-this.syncPoint.playerTime)*(6e4/1001);this.vfcData.lastMediaTimeFromSync=i;const s=Math.floor(i+.1)+this.syncPoint.frame;this.vfcData.mediaTimeOffset=F.calculateCurrentOffset(s,this.OTTPlayer.gameParams.offsets);let o=s-this.vfcData.mediaTimeOffset;o<0&&(o+=5178816),o++,this.vfcData.lastCalculatedMediaTimeVideoFrame=o,this.vfcData.lastFrameMetadata=r,this.vfcData.storedMetadata.push(r),this.vfcData.storedMetadata.length>10&&this.vfcData.storedMetadata.shift(),this.vfcData.timePerformanceNowToExpectedDisplayTime=r.expectedDisplayTime-this.vfcData.lastTimestamp,this.vfcData.timeRVFCnowToExpectedDisplayTime=r.expectedDisplayTime-n,this.vfcData.lastFrameMetadataNow=n,this.metrics&&(this.metrics.updateMetric("RVFC calls",this.vfcData.counter),this.metrics.updateMetric("Last metadata media time",r.mediaTime.toFixed(4)),this.metrics.updateMetric("Last metadata media time frame",this.vfcData.lastCalculatedMediaTimeVideoFrame),this.metrics.updateMetric("Time to presentation time",(r.presentationTime-n).toFixed(4)),this.metrics.updateMetric("Metadata presented frames",r.presentedFrames),this.metrics.updateMetric("Metadata processing duration",r.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.video.requestVideoFrameCallback(this.onVideoFrame),this.determineFrameUpdate()},this.determineFrameUpdate=()=>{var n,r,i,s;if(!(!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata))if(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(),!this.OTTPlayer.options.ADAPTER_RUN_IN_WORKER)this.platformSpecificFrameUpdate();else{const o={siData:this.siData,vfcData:this.vfcData,afData:this.afData,debugControls:(n=this.debugControls)==null?void 0:n.exportData(),cloudFrontURL:this.OTTPlayer.options.cloudFrontURL,bucketName:((r=this.OTTPlayer.gameParams)==null?void 0:r.bucketName)||"",offsets:((i=this.OTTPlayer.gameParams)==null?void 0:i.offsets)||[],customerId:((s=this.OTTPlayer.gameParams)==null?void 0:s.customerId)||""};this.OTTPlayer.clocker.callAdapterWorker(o)}},this.determineFrameUpdateChromeMac=()=>{const n=Math.round(1e3/this.vfcData.timeRVFCnowToExpectedDisplayTime);if(n>0&&n<500&&(this.expectedRefreshRateCalculator.addFrameDuration(this.vfcData.timeRVFCnowToExpectedDisplayTime/1e3),Math.abs(this.siData.expectedRefreshRate-n)>3?this.siData.newRefreshRateFrames++:(this.siData.expectedRefreshRate=n,this.siData.avgExpectedRefreshRate=this.expectedRefreshRateCalculator.getPerciseFPS()),this.siData.newRefreshRateFrames>10&&(this.siData.newRefreshRateFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedRefreshRate=n,this.siData.isRVFCpatternDetected=!1)),this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;const r=20,i=1e3;if(!this.siData.isRVFCSeen){const s=Math.round(this.vfcData.timeRVFCnowToExpectedDisplayTime/(1e3/this.afData.animationFPS));if(s<=0&&this.siData.patternTracking.length<=1-s){this.siData.patternTracking=[!0];for(let o=0;o<1-s;o++)this.siData.patternTracking.push(!1)}else s<=1&&(this.siData.patternTracking[this.siData.patternTracking.length-2+s]=!0)}if(this.siData.isRAFSeen||this.siData.patternTracking.push(!1),this.siData.patternTracking.length>i&&this.siData.patternTracking.shift(),!this.siData.isRVFCpatternDetected){const s=this.siData.patternTracking;for(let o=1;o*r<=s.length;o++){for(let a=0;a+o*r<=s.length;a++){let c=!0;for(let l=0;l<r-1;l++){const u=s.slice(a+l*o,a+(l+1)*o),d=s.slice(a+(l+1)*o,a+(l+2)*o);if(!u.every((f,p)=>f===d[p])){c=!1;break}}if(c){const l=s.slice(a,a+o),u=l.every(p=>!p),d=l.every(p=>p),f=this.afData.animationFPS-this.vfcData.videoFPS;if(u||d&&f>5)continue;this.siData.RVFCpattern=l,this.siData.isRVFCpatternDetected=!0;break}}if(this.siData.isRVFCpatternDetected)break}}if(this.siData.RVFCpattern.length>0){const s=this.siData.RVFCpattern,o=this.siData.patternTracking;let a=-1;for(let c=o.length-s.length;c>=0;c--){let l=!0;for(let u=0;u<s.length;u++)if(s[u]!==o[c+u]){l=!1;break}if(l){a=c;break}}if(a>=0){const c=(o.length-a)%s.length,l=s[c];this.siData.patternTrackingIndex=c,this.siData.patternNextValue=l?1:0}if(o.length>=s.length*5){o.slice(o.length-s.length*5);let c=0,l=0;for(let u=0;u+s.length<=o.length;u++)o.slice(u,u+s.length).every((f,p)=>f===s[p])?(c++,l=Math.max(l,c),u+=s.length-1):c=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 s=[this.afData.lastTimestamp,this.vfcData.lastTimestamp,this.afData.previousTimestamp,this.vfcData.previousTimestamp].sort((l,u)=>u-l),o=s[0],a=s[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(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 s=0,o=1,a=5;if(this.debugControls){const c=parseInt(this.debugControls.getValue("Pattern offset"),10);isNaN(c)||(s=c);const l=parseInt(this.debugControls.getValue("Frame Correction"),10);isNaN(l)||(o=l);const u=parseInt(this.debugControls.getValue("Timeout time"),10);isNaN(u)||(a=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+s)%this.siData.RVFCpattern.length]?setTimeout(()=>this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+o),a):this.callRenderer(this.siData.lastRendererFrameSent)}else this.siData.isRVFCpatternDetected||this.clearAugmentation()},this.determineFrameUpdateChromeWin=()=>{const n=Math.round(1e3/this.vfcData.timeRVFCnowToExpectedDisplayTime);if(n>0&&n<500&&(this.expectedRefreshRateCalculator.addFrameDuration(this.vfcData.timeRVFCnowToExpectedDisplayTime/1e3),Math.abs(this.siData.expectedRefreshRate-n)>3?this.siData.newRefreshRateFrames++:(this.siData.expectedRefreshRate=n,this.siData.avgExpectedRefreshRate=this.expectedRefreshRateCalculator.getPerciseFPS()),this.siData.newRefreshRateFrames>10&&(this.siData.newRefreshRateFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedRefreshRate=n,this.siData.isRVFCpatternDetected=!1)),this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;const r=20,i=1e3;if(!this.siData.isRVFCSeen){const s=Math.round(this.vfcData.timeRVFCnowToExpectedDisplayTime/(1e3/this.afData.animationFPS));if(s<=0&&this.siData.patternTracking.length<=1-s){this.siData.patternTracking=[!0];for(let o=0;o<1-s;o++)this.siData.patternTracking.push(!1)}else s<=1&&(this.siData.patternTracking[this.siData.patternTracking.length-2+s]=!0)}if(this.siData.isRAFSeen||this.siData.patternTracking.push(!1),this.siData.patternTracking.length>i&&this.siData.patternTracking.shift(),!this.siData.isRVFCpatternDetected){const s=this.siData.patternTracking;for(let o=1;o*r<=s.length;o++){for(let a=0;a+o*r<=s.length;a++){let c=!0;for(let l=0;l<r-1;l++){const u=s.slice(a+l*o,a+(l+1)*o),d=s.slice(a+(l+1)*o,a+(l+2)*o);if(!u.every((f,p)=>f===d[p])){c=!1;break}}if(c){const l=s.slice(a,a+o),u=l.every(p=>!p),d=l.every(p=>p),f=this.afData.animationFPS-this.vfcData.videoFPS;if(u||d&&f>5)continue;this.siData.RVFCpattern=l,this.siData.isRVFCpatternDetected=!0;break}}if(this.siData.isRVFCpatternDetected)break}}if(this.siData.RVFCpattern.length>0){const s=this.siData.RVFCpattern,o=this.siData.patternTracking;let a=-1;for(let c=o.length-s.length;c>=0;c--){let l=!0;for(let u=0;u<s.length;u++)if(s[u]!==o[c+u]){l=!1;break}if(l){a=c;break}}if(a>=0){const c=(o.length-a)%s.length,l=s[c];this.siData.patternTrackingIndex=c,this.siData.patternNextValue=l?1:0}if(o.length>=s.length*5){o.slice(o.length-s.length*5);let c=0,l=0;for(let u=0;u+s.length<=o.length;u++)o.slice(u,u+s.length).every((f,p)=>f===s[p])?(c++,l=Math.max(l,c),u+=s.length-1):c=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 s=[this.afData.lastTimestamp,this.vfcData.lastTimestamp,this.afData.previousTimestamp,this.vfcData.previousTimestamp].sort((l,u)=>u-l),o=s[0],a=s[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(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 s=0,o=2,a=!1;if(this.debugControls){const u=parseInt(this.debugControls.getValue("Pattern offset"),10);isNaN(u)||(s=u);const d=parseInt(this.debugControls.getValue("Frame Correction"),10);isNaN(d)||(o=d),parseInt(this.debugControls.getValue("Timeout time"),10);const f=this.debugControls.getValue("Video Captur Card Mode");console.log("selectVideoCaptureCardMode",f),f==="true"&&(a=!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})),a&&(s+=1);const c=(this.siData.patternTrackingIndex+this.siData.RVFCpattern.length-1+s)%this.siData.RVFCpattern.length,l=(c+this.siData.RVFCpattern.length-1)%this.siData.RVFCpattern.length;if(this.siData.RVFCpattern[c]){let u=0;a&&this.siData.lastRendererFrameSent==this.vfcData.lastCalculatedMediaTimeVideoFrame&&this.siData.RVFCpattern[l]&&(u=2),this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+u+o)}}else this.siData.isRVFCpatternDetected||this.clearAugmentation()},this.determineFrameUpdateSifariMac=()=>{if(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 n=Math.abs(this.siData.refreshRate-this.siData.workingFps)<2?8:20,r=1e3,i=[this.afData.lastTimestamp,this.vfcData.lastTimestamp,this.afData.previousTimestamp,this.vfcData.previousTimestamp].sort((h,m)=>m-h),s=2,o=i[0],a=i[1],c=o-a,l=1e3/this.afData.animationFPS,u=Math.round(l/4+.1),d=this.vfcData.timeRVFCnowToExpectedDisplayTime;if(this.siData.isRVFCSeen)this.metrics;else{const h=(-d-u)/l,m=Math.ceil(h),g=(Math.round(h)-h)*l,w=Math.abs(g)<=s,T=g<=0?m-1:m+1,k=Math.abs(-d-u)<=s;if(this.metrics&&(this.metrics.updateMetric("Is Smoothing Needed",w),this.metrics.updateMetric("Is More Than Border",m),this.metrics.updateMetric("Is Smoothed",T)),w&&!k){const R=Math.min(m,T),x=Math.max(m,T);this.metrics&&this.metrics.updateMetric("Pssblty next index",""+R+" "+x),this.siData.possibilityTracking[this.siData.possibilityTracking.length-R]=2,this.siData.possibilityTracking[this.siData.possibilityTracking.length-x]=1}else w&&k&&(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(-d<u)this.siData.expectedDisplayTimeReminder=-d;else if(c>l&&-d-(c-l)<=u)this.siData.expectedDisplayTimeReminder=-d-(c-l);else{let R=-d-c,x=0,_=this.siData.determineFramesIntervals.length-1;for(let A=this.siData.determineAFIntervals.length-1;A>=0&&(_--,!(this.siData.determineAFIntervals[A]>l&&R-(this.siData.determineAFIntervals[A]-l)<=u||R<=u||this.siData.determineFramesIntervals[_].includes("vf")&&this.siData.workingFps<40));A--)R-=this.siData.determineAFIntervals[A],x+=1;if(this.siData.patternTracking.length<x+1){this.siData.patternTracking=[!0];for(let A=0;A<x;A++)this.siData.patternTracking.push(!1)}else this.siData.patternTracking[this.siData.patternTracking.length-1-x]=!0;this.siData.animationFramesToDisplayTime=x}}if(this.siData.isRAFSeen||(this.siData.expectedDisplayTimeReminder?(this.siData.expectedDisplayTimeReminder-u,this.siData.expectedDisplayTimeReminder+c<=u?(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>r&&this.siData.patternTracking.shift(),this.siData.possibilityTracking.length>r&&this.siData.possibilityTracking.shift(),!this.siData.isRVFCpatternDetected){const h=this.siData.patternTracking;for(let m=1;m*n<=h.length;m++){for(let g=0;g+m*n<=h.length;g++){let w=!0;for(let v=0;v<n-1;v++){const T=h.slice(g+v*m,g+(v+1)*m),k=h.slice(g+(v+1)*m,g+(v+2)*m);if(!T.every((R,x)=>R===k[x])){w=!1;break}}if(w){const v=h.slice(g,g+m),T=v.every(x=>!x),k=v.every(x=>x),R=this.afData.animationFPS-this.vfcData.videoFPS;if(T||k&&R>5)continue;this.siData.RVFCpattern=v,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 w=m.length-h.length*5;w>=0;w--){let v=!0;for(let T=0;T<h.length*5;T++)if(h[T%h.length]!==m[w+T]){v=!1;break}if(v){g=w;break}}if(g>=0){const w=(m.length-g)%h.length,v=h[w];this.siData.patternTrackingIndex=w,this.siData.patternNextValue=v?1:0}if(m.length>=h.length*5){m.slice(m.length-h.length*5);let w=0,v=0;for(let T=0;T+h.length<=m.length;T++)m.slice(T,T+h.length).every((R,x)=>R===h[x])?(w++,v=Math.max(v,w),T+=h.length-1):w=0;v<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 w=parseInt(this.debugControls.getValue("Pattern offset"),10);isNaN(w)||(h=w);const v=parseInt(this.debugControls.getValue("Frame Correction"),10);isNaN(v)||(m=v),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 w=Math.ceil(this.siData.animationFramesToDisplayTime/this.siData.RVFCpattern.length)+1,v=this.siData.RVFCpattern.map(De=>De?1:0).join("").repeat(w),T=(this.siData.RVFCpattern.length-this.siData.patternTrackingIndex)%this.siData.RVFCpattern.length,k=v.slice(0,T==0?-this.siData.RVFCpattern.length:-T);let R=0;const x=this.siData.possibilityTracking.length-1-this.siData.animationFramesToDisplayTime;k[k.length-1-this.siData.animationFramesToDisplayTime]=="0"&&this.siData.possibilityTracking[x]==1&&(R=-1);const _=this.siData.animationFramesToDisplayTime+R,A=_<=0?"":k.slice(-_);let Re=A.split("").filter(De=>De==="1").length*Math.round(60/this.siData.workingFps);this.siData.workingFps<40&&(Re+=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(De=>De===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+Re+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+Re+m?(this.callRenderer(this.siData.lastRendererFrameSent+1,this.siData.compensationCounter),this.siData.compensationMode=!0):this.callRenderer(this.vfcData.lastCalculatedMediaTimeVideoFrame+Re+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",Re),this.metrics.updateMetric("Compensation Counter",this.siData.compensationCounter),this.metrics.updateMetric("Repeated Pattern",v),this.metrics.updateMetric("Trimmed Pattern",k),this.metrics.updateMetric("Sliced Pattern",A),this.metrics.updateMetric("AF To Display Time Correction",R)),this.siData.previousPossibilityValue=p}else this.callRenderer(this.siData.lastRendererFrameSent)}else this.siData.isRVFCpatternDetected||this.clearAugmentation()},this.determineFrameUpdateFirefoxMac=()=>{const n=Math.round(1e3/this.vfcData.timeRVFCnowToExpectedDisplayTime);if(n>0&&n<500&&(this.expectedRefreshRateCalculator.addFrameDuration(this.vfcData.timeRVFCnowToExpectedDisplayTime/1e3),Math.abs(this.siData.expectedRefreshRate-n)>3?this.siData.newRefreshRateFrames++:(this.siData.expectedRefreshRate=n,this.siData.avgExpectedRefreshRate=this.expectedRefreshRateCalculator.getPerciseFPS()),this.siData.newRefreshRateFrames>10&&(this.siData.newRefreshRateFrames=0,this.siData.RVFCpattern=[],this.siData.patternTracking=[],this.siData.expectedRefreshRate=n,this.siData.isRVFCpatternDetected=!1)),this.video.paused||!this.OTTPlayer.clocker||!this.vfcData.lastFrameMetadata)return;const r=5,i=1e3;if(!this.siData.isRVFCSeen){const s=Math.round(this.vfcData.timeRVFCnowToExpectedDisplayTime/(1e3/this.afData.animationFPS));if(s<=0&&this.siData.patternTracking.length<=1-s){this.siData.patternTracking=[!0];for(let o=0;o<1-s;o++)this.siData.patternTracking.push(!1)}else s<=1&&(this.siData.patternTracking[this.siData.patternTracking.length-2+s]=!0)}if(this.siData.isRAFSeen||this.siData.patternTracking.push(!1),this.siData.patternTracking.length>i&&this.siData.patternTracking.shift(),!this.siData.isRVFCpatternDetected){const s=this.siData.patternTracking;for(let o=1;o*r<=s.length;o++){for(let a=0;a+o*r<=s.length;a++){let c=!0;for(let l=0;l<r-1;l++){const u=s.slice(a+l*o,a+(l+1)*o),d=s.slice(a+(l+1)*o,a+(l+2)*o);if(!u.every((f,p)=>f===d[p])){c=!1;break}}if(c){const l=s.slice(a,a+o),u=l.every(p=>!p),d=l.every(p=>p),f=this.afData.animationFPS-this.vfcData.videoFPS;if(u||d&&f>5)continue;this.siData.RVFCpattern=l,this.siData.isRVFCpatternDetected=!0;break}}if(this.siData.isRVFCpatternDetected)break}}if(this.siData.RVFCpattern.length>0){const s=this.siData.RVFCpattern,o=this.siData.patternTracking;let a=-1;for(let c=o.length-s.length;c>=0;c--){let l=!0;for(let u=0;u<s.length;u++)if(s[u]!==o[c+u]){l=!1;break}if(l){a=c;break}}if(a>=0){const c=(o.length-a)%s.length,l=s[c];this.siData.patternTrackingIndex=c,this.siData.patternNextValue=l?1:0}if(o.length>=s.length*5){o.slice(o.length-s.length*5);let c=0,l=0;for(let u=0;u+s.length<=o.length;u++)o.slice(u,u+s.length).every((f,p)=>f===s[p])?(c++,l=Math.max(l,c),u+=s.length-1):c=0;l<5&&(this.siData.isRVFCpatternDetected=!1)}Math.abs(this.siData.avgExpectedRefreshRate-this.siData.refreshRate)>3&&(this.siData.isRVFCpatternDetected=!1)}if(this.metrics){performance.now();const s=[this.afData.lastTimestamp,this.vfcData.lastTimestamp,this.afData.previousTimestamp,this.vfcData.previousTimestamp].sort((l,u)=>u-l),o=s[0],a=s[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(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 s=0,o=1;if(this.debugControls){const a=parseInt(this.debugControls.getValue("Pattern offset"),10);isNaN(a)||(s=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+s)%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)}else this.siData.isRVFCpatternDetected||this.clearAugmentation()},this.callRenderer=(n,r)=>{if(!this.OTTPlayer.clocker||!this.OTTPlayer)return;this.siData.lastRendererFrameSent=n,this.metrics&&this.metrics.updateMetric("Last sent frame",n);const i=this.OTTPlayer.clocker.videoFPScalculator.getFPS();this.metrics&&this.metrics.updateMetric("FPS",i.toFixed(2));const s=F.fromFrames(n,6e4/1001);this.timeout.isTimeout()?this.clearAugmentation(s):(this.OTTPlayer.clocker.videoFPScalculator.getPerciseFPS(),this.OTTPlayer.clocker.animationFPScalculator.getPerciseFPS(),this.renderAugmentation(s,r))},this.playbackTimeDelta=0,this.wallClockTimeDelta=0,this.dateTimeDelta=0,this.renderAugmentation=(n,r)=>{if(!this.OTTPlayer||!this.OTTPlayer.clocker)throw new Error("OTTPlayer is not initialized");const i=F.toStr(n);this.siData.lastMessageSent=i,this.options&&I(this.options,"Adapter")&&console.log(`Rendering augmentation for timecode: ${i} , ${n}`),this.metrics&&this.metrics.updateMetric("Last sent timecode",i),this.OTTPlayer.clocker.callRendererWorker(i,r)},this.onVideoSeeked=()=>{this.firstFrameTimecode=[0,0,0,0,0],this.firstFrameTimecodeSet=!1},this.clearAugmentation=n=>{if(!this.OTTPlayer||!this.OTTPlayer.clocker)throw new Error("OTTPlayer is not initialized");const r=n?F.toStr(n):void 0;this.options&&I(this.options,"Adapter")&&console.log("Clearing augmentation"),this.OTTPlayer.clocker.callRendererWorker(r,0,!0)},this.logger=e.logger,this.OTTPlayer=e,this.options=e.options,this.options&&I(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),P.isChromeMac())this.platformSpecificFrameUpdate=this.determineFrameUpdateChromeMac;else if(P.isChromeWin())this.platformSpecificFrameUpdate=this.determineFrameUpdateChromeWin;else if(P.isSafariMac())this.platformSpecificFrameUpdate=this.determineFrameUpdateSifariMac;else{P.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 n=this.metrics.createContainer(),r=this.metrics.createContainer(),i=this.metrics.createContainer(),s=this.metrics.createContainer(),o=this.metrics.createContainer(),a=this.metrics.createContainer(),c=this.metrics.createContainer(),l=this.metrics.createContainer(),u=this.metrics.createContainer(),d=this.metrics.createContainer(),f=this.metrics.createContainer(),p=this.metrics.createContainer(),h=this.metrics.createContainer();this.metrics.createMetric("RAF calls",n),this.metrics.createMetric("RVFC calls",n),this.metrics.createMetric("RVFC missed",n),this.metrics.createMetric("Last sent frame",n),this.metrics.createMetric("Last sent timecode",n),this.metrics.createMetric("Last metadata media time",r),this.metrics.createMetric("Last player time",r),this.metrics.createMetric("RVFC to expected display time",r),this.metrics.createMetric("Performance Now to expected display time",r),this.metrics.createMetric("Last metadata media time frame",i),this.metrics.createMetric("Last player time frame",i),this.metrics.createMetric("Last player time fraction",i),this.metrics.createMetric("Last media time double frame",s),this.metrics.createMetric("Last player time double frame",s),this.metrics.createMetric("Compensation Counter",s),this.metrics.createMetric("AF metadata now - perf.now()",o),this.metrics.createMetric("VF metadata now - perf.now()",o),this.metrics.createMetric("VF ExpDispTime - AF metadata now",o),this.metrics.createMetric("Time to presentation time",a),this.metrics.createMetric("Metadata presented frames",a),this.metrics.createMetric("Metadata processing duration",a),this.metrics.createMetric("FPS",c),this.metrics.createMetric("Refresh rate",c),this.metrics.createMetric("Last RAF call",c),this.metrics.createMetric("Last RVFC call",c),this.metrics.createMetric("RAF - RVFC dif",c),this.metrics.createMetric("Determine frames intervals",l),this.metrics.createMetric("Last AF to VF time",u),this.metrics.createMetric("AF frames intervals",u),this.metrics.createMetric("Expected Refresh Rate",d),this.metrics.createMetric("Avg Expected Refresh Rate",d),this.metrics.createMetric("New Refresh Rate Frames",d),this.metrics.createMetric("AF To Display Time",d),this.metrics.createMetric("AF To Display Time Correction",d),this.metrics.createMetric("Call Renderer Reached",d),this.metrics.createMetric("Is Smoothing Needed",f),this.metrics.createMetric("Is More Than Border",f),this.metrics.createMetric("Is Smoothed",f),this.metrics.createMetric("Correction",f),this.metrics.createMetric("Repeated Pattern",f),this.metrics.createMetric("Trimmed Pattern",f),this.metrics.createMetric("Sliced Pattern",f),this.metrics.createMetric("Pattern found",p),this.metrics.createMetric("Pattern array",p),this.metrics.createMetric("Pattern tracking",p),this.metrics.createMetric("Pattern next index",p),this.metrics.createMetric("Pattern next value",p),this.metrics.createMetric("Pssblty found",h),this.metrics.createMetric("Pssblty array",h),this.metrics.createMetric("Pssblty tracking",h),this.metrics.createMetric("Pssblty next index",h),this.metrics.createMetric("Pssblty next value",h),this.debugControls=new cr;const m=this.debugControls.createContainer(),g=this.debugControls.createContainer();this.debugControls.createInput("Window Start (ms)",4,m),this.debugControls.createInput("Window End (ms)",-11,m),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",m),this.debugControls.createCheckbox("Video Captur Card Mode",!1,m),P.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",g):P.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",g):this.debugControls.createSelect("Frame Correction",{"-4":-4,"-3":-3,"-2":-2,"-1":-1,0:0,1:1,2:2,3:3,4:4},"1",g),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",g)}this.platformSupported&&(this.OTTPlayer.video.readyState>=3?this.setupAdapter():this.OTTPlayer.video.addEventListener("canplay",()=>this.setupAdapter(),{once:!0}))}setupAdapter(){const e=this.video;if(this.debug){const n=typeof wmcsdk<"u"?wmcsdk:wmcPlayer;console.log(n);const r=n.getAvailableVideoQualities(),i={};r.forEach(a=>{i[a.label]=a.id});const s=a=>{n.doSetVideoQuality(a.videoQuality)},o=this.debugControls.createContainer(s);this.debugControls.createSelect("videoQuality",i,r[0].id,o)}this.animationFrameLoopId=window.requestAnimationFrame(this.onAnimationFrame),this.videoFrameCallbackLoopId=e.requestVideoFrameCallback(this.onVideoFrame)}onNewSegmentForMetadata(e){if(!this.firstFrameTimecodeSet){const l=performance.now();l-this.loggerTimeoutStart>this.loggerTimeout&&(this.loggerTimeoutStart=l,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 n=ur(this.firstFrameTimecode,6e4/1001);if(console.log(e),!e.mimeType.includes("video"))return;const r=lr(this.firstFrameTimecode,!0,!0);this.options&&I(this.options,"Adapter")&&console.log("New segment ("+e.url+"): "+r+" ("+n+") playing at "+e.playbackTime);const i=e.playbackTime,s=i-this.playbackTimeDelta;this.playbackTimeDelta=i,console.log("Delta playback: ",s);const o=e.wallClockTime/1e3,a=o-this.wallClockTimeDelta;if(this.wallClockTimeDelta=o,console.log("Delta wallClock: ",a),e.dateTime instanceof Date){const l=e.dateTime.getTime()/1e3,u=l-this.dateTimeDelta;this.dateTimeDelta=l,console.log("Delta dateTime: ",u)}const c={frame:n,playerTime:i,stringTime:r,lastUpdate:performance.now()};this.syncPoint=c,this.metrics,this.options&&I(this.options,"Adapter")&&console.log("url: "+e.url)}onNewMetadata(e){if(e&&e.metadata&&e.metadata.id==0||P.isSafariMac()){if(e.metadata.messageData)e.metadata.messageData=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(r=>r.info&&r.info.toLowerCase().includes("ntc"));if(n.length){const r=`${n[n.length-1].info}\0${String.fromCharCode(...n[n.length-1].data)}`;e.metadata.messageData=this.processTimedMetadata(r,e.metadata.presentationTime)}}if(e.metadata.id==0||P.isSafariMac()&&this.timecode_offset==0){e.metadata.presentationTime*1e3;const n=new Date(this.tcTimeStamp-this.timecode_offset);let r=Math.round(n.getUTCMilliseconds()*30*2/1001)/2;const i=r%1;let s=1;i==.5&&(r=Math.floor(r),s=2),this.firstFrameTimecode=[n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),Math.floor(r),s==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: ",this.firstFrameTimecode)}}}processTimedMetadata(e,n){let r="";if(e&&e.includes("www.mediakind.com/NTC")){const i=e.replace(/.*NTC./,"");let s=0;for(;s+8<=i.length;){const o=i.substring(s,s+4),a=((i.charCodeAt(s+4)*256+i.charCodeAt(s+5))*256+i.charCodeAt(s+6))*256+i.charCodeAt(s+7);if(s+8+a>i.length)break;const c=i.substring(s+8,s+8+a);o=="utc_"&&new Date(parseInt(c)).getTime()/1e3,o=="tc__"&&(this.tcTimeStamp=new Date(parseInt(c)).getTime()),o==="offs"&&(this.timecode_offset=parseInt(c)/90),s+=8+a}}return r}delete(){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()}}class Y{constructor(e,n){this.size=1,this.positionElement=()=>{let i=0,s=0;this.corner=="left-top"?(this.element.style.top=`${i}px`,this.element.style.left=`${s}px`):this.corner=="right-top"?(this.element.style.top=`${i}px`,this.element.style.left=`${s+this.video.offsetWidth-this.size}px`):this.corner=="right-bottom"?(this.element.style.top=`${i+this.video.offsetHeight-this.size}px`,this.element.style.left=`${s+this.video.offsetWidth-this.size}px`):this.corner=="left-bottom"&&(this.element.style.top=`${i+this.video.offsetHeight-this.size}px`,this.element.style.left=`${s}px`)},this.video=n,this.container=n.parentElement,this.corner=e;const r=document.createElement("div");r.style.position="absolute",r.style.width=`${this.size}px`,r.style.height=`${this.size}px`,r.style.transition="background-color 0s",r.style.zIndex="100000",this.element=r,this.container.appendChild(r),this.positionElement()}getRandomColor(){const r=Math.floor(Math.random()*11)+0;return`rgb(${r},${r},${r})`}update(){this.element.style.backgroundColor=this.getRandomColor(),this.positionElement()}delete(){this.container.removeChild(this.element)}static createInAllCorners(e){return[new Y("left-top",e),new Y("right-top",e),new Y("right-bottom",e),new Y("left-bottom",e)]}static updateAll(e){e.forEach(n=>n.update())}static deleteAll(e){e.forEach(n=>n.delete())}}const E={log:"log",debug:"debug",info:"info",warn:"warn",error:"error"},M=console,K={};Object.keys(E).forEach(t=>{K[t]=M[t]});const me="Datadog Browser SDK:",C={debug:K.debug.bind(M,me),log:K.log.bind(M,me),info:K.info.bind(M,me),warn:K.warn.bind(M,me),error:K.error.bind(M,me)},st="https://docs.datadoghq.com",Ht=`${st}/real_user_monitoring/browser/troubleshooting`,Ae="More details:";function qt(t,e){return(...n)=>{try{return t(...n)}catch(r){C.error(e,r)}}}function Fe(t){return t!==0&&Math.random()*100<=t}function hr(t){return pr(t)&&t>=0&&t<=100}function pr(t){return typeof t=="number"}const ge=1e3,J=60*ge,Wt=60*J,mr=365*(24*Wt);function ye(){return new Date().getTime()}function G(){return ye()}function Oe(){return performance.now()}function V(){return{relative:Oe(),timeStamp:G()}}function gr(){return{relative:0,timeStamp:Yt()}}function yr(t,e){return e-t}function _r(t,e){return t+e}function br(t){return t-Yt()}let it;function Yt(){return it===void 0&&(it=performance.timing.navigationStart),it}const B=1024,Kt=1024*B,vr=/[^\u0000-\u007F]/;function ot(t){return vr.test(t)?window.TextEncoder!==void 0?new TextEncoder().encode(t).length:new Blob([t]).size:t.length}function Sr(t){return{...t}}function Jt(t,e){return Object.keys(t).some(n=>t[n]===e)}function _e(t){return Object.keys(t).length===0}function j(){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 ie(t,e){const n=j();let r;return n.Zone&&typeof n.Zone.__symbol__=="function"&&(r=t[n.Zone.__symbol__(e)]),r||(r=t[e]),r}let Le,Xt=!1;function wr(t){Le=t}function Tr(t){Xt=t}function xr(t,e,n){const r=n.value;n.value=function(...i){return(Le?S(r):r).apply(this,i)}}function S(t){return function(){return be(t,this,arguments)}}function be(t,e,n){try{return t.apply(e,n)}catch(r){Er(r)}}function Er(t){if(at(t),Le)try{Le(t)}catch(e){at(e)}}function at(...t){Xt&&C.error("[MONITOR]",...t)}function ve(t,e){return ie(j(),"setTimeout")(S(t),e)}function Zt(t){ie(j(),"clearTimeout")(t)}function ct(t,e){return ie(j(),"setInterval")(S(t),e)}function Qt(t){ie(j(),"clearInterval")(t)}class D{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(n=>e!==n),!this.observers.length&&this.onLastUnsubscribe&&this.onLastUnsubscribe()}}}notify(e){this.observers.forEach(n=>n(e))}}function en(...t){return new D(e=>{const n=t.map(r=>r.subscribe(i=>e.notify(i)));return()=>n.forEach(r=>r.unsubscribe())})}function tn(t,e,n){let r=!1,i,s;return{throttled:(...o)=>{if(r){i=o;return}t(...o),r=!0,s=ve(()=>{i&&t(...i),r=!1,i=void 0},e)},cancel:()=>{Zt(s),r=!1,i=void 0}}}function H(){}function q(t){return t?(parseInt(t,10)^Math.random()*16>>parseInt(t,10)/4).toString(16):`10000000-1000-4000-8000-${1e11}`.replace(/[018]/g,q)}const Ie=/([\w-]+)\s*=\s*([^;]+)/g;function Cr(t,e){for(Ie.lastIndex=0;;){const n=Ie.exec(t);if(n){if(n[1]===e)return n[2]}else break}}function kr(t){const e=new Map;for(Ie.lastIndex=0;;){const n=Ie.exec(t);if(n)e.set(n[1],n[2]);else break}return e}function Rr(t,e,n=""){const r=t.charCodeAt(e-1),s=r>=55296&&r<=56319?e+1:e;return t.length<=s?t:`${t.slice(0,s)}${n}`}function Dr(){return Ur()===0}let Pe;function Ur(){return Pe??(Pe=Ar())}function Ar(t=window){var e;const n=t.navigator.userAgent;return t.chrome||/HeadlessChrome/.test(n)?0:((e=t.navigator.vendor)===null||e===void 0?void 0:e.indexOf("Apple"))===0||/safari/i.test(n)&&!/chrome|android/i.test(n)?1:2}function Se(t,e,n=0,r){const i=new Date;i.setTime(i.getTime()+n);const s=`expires=${i.toUTCString()}`,o=r&&r.crossSite?"none":"strict",a=r&&r.domain?`;domain=${r.domain}`:"",c=r&&r.secure?";secure":"",l=r&&r.partitioned?";partitioned":"";document.cookie=`${t}=${e};${s};path=/;samesite=${o}${a}${c}${l}`}function lt(t){return Cr(document.cookie,t)}let ut;function X(t){return ut||(ut=kr(document.cookie)),ut.get(t)}function nn(t,e){Se(t,"",0,e)}function Fr(t){if(document.cookie===void 0||document.cookie===null)return!1;try{const e=`dd_cookie_test_${q()}`,n="test";Se(e,n,J,t);const r=lt(e)===n;return nn(e,t),r}catch(e){return C.error(e),!1}}let dt;function Or(){if(dt===void 0){const t=`dd_site_test_${q()}`,e="test",n=window.location.hostname.split(".");let r=n.pop();for(;n.length&&!lt(t);)r=`${n.pop()}.${r}`,Se(t,e,ge,{domain:r});nn(t,{domain:r}),dt=r}return dt}const oe="_dd_s";function Me(t){return Object.values(t)}function Lr(t){return Object.entries(t)}const ft=4*Wt,rn=15*J,Ir=mr,we={COOKIE:"cookie",LOCAL_STORAGE:"local-storage"},sn=/^([a-zA-Z]+)=([a-z0-9-]+)$/,ht="&";function Pr(t){return!!t&&(t.indexOf(ht)!==-1||sn.test(t))}const Mr="1";function Z(t,e){const n={isExpired:Mr};return e.trackAnonymousUser&&(t!=null&&t.anonymousId?n.anonymousId=t==null?void 0:t.anonymousId:n.anonymousId=q()),n}function Be(t){return _e(t)}function on(t){return!Be(t)}function Ne(t){return t.isExpired!==void 0||!Br(t)}function Br(t){return(t.created===void 0||ye()-Number(t.created)<ft)&&(t.expire===void 0||ye()<Number(t.expire))}function an(t){t.expire=String(ye()+rn)}function pt(t){return Lr(t).map(([e,n])=>e==="anonymousId"?`aid=${n}`:`${e}=${n}`).join(ht)}function cn(t){const e={};return Pr(t)&&t.split(ht).forEach(n=>{const r=sn.exec(n);if(r!==null){const[,i,s]=r;i==="aid"?e.anonymousId=s:e[i]=s}}),e}const Nr="_dd",$r="_dd_r",zr="_dd_l",Gr="rum",Vr="logs";function jr(t){if(!X(oe)){const n=X(Nr),r=X($r),i=X(zr),s={};n&&(s.id=n),i&&/^[01]$/.test(i)&&(s[Vr]=i),r&&/^[012]$/.test(r)&&(s[Gr]=r),on(s)&&(an(s),t.persistSession(s))}}function ln(t){const e=Kr(t);return Fr(e)?{type:we.COOKIE,cookieOptions:e}:void 0}function Hr(t,e){const n={isLockEnabled:Dr(),persistSession:qr(e),retrieveSession:Yr,expireSession:r=>Wr(e,r,t)};return jr(n),n}function qr(t){return e=>{Se(oe,pt(e),rn,t)}}function Wr(t,e,n){const r=Z(e,n);Se(oe,pt(r),n.trackAnonymousUser?Ir:ft,t)}function Yr(){const t=lt(oe);return cn(t)}function Kr(t){const e={};return e.secure=!!t.useSecureSessionCookie||!!t.usePartitionedCrossSiteSessionCookie,e.crossSite=!!t.usePartitionedCrossSiteSessionCookie,e.partitioned=!!t.usePartitionedCrossSiteSessionCookie,t.trackSessionAcrossSubdomains&&(e.domain=Or()),e}const Jr="_dd_test_";function un(){try{const t=q(),e=`${Jr}${t}`;localStorage.setItem(e,t);const n=localStorage.getItem(e);return localStorage.removeItem(e),t===n?{type:we.LOCAL_STORAGE}:void 0}catch{return}}function Xr(t){return{isLockEnabled:!1,persistSession:dn,retrieveSession:Zr,expireSession:e=>Qr(e,t)}}function dn(t){localStorage.setItem(oe,pt(t))}function Zr(){const t=localStorage.getItem(oe);return cn(t)}function Qr(t,e){dn(Z(t,e))}const es=10,ts=100,fn=[];let $e;function Q(t,e,n=0){var r;const{isLockEnabled:i,persistSession:s,expireSession:o}=e,a=f=>s({...f,lock:l}),c=()=>{const f=e.retrieveSession(),p=f.lock;return f.lock&&delete f.lock,{session:f,lock:p}};if($e||($e=t),t!==$e){fn.push(t);return}if(i&&n>=ts){hn(e);return}let l,u=c();if(i){if(u.lock){ze(t,e,n);return}if(l=q(),a(u.session),u=c(),u.lock!==l){ze(t,e,n);return}}let d=t.process(u.session);if(i&&(u=c(),u.lock!==l)){ze(t,e,n);return}if(d&&(Ne(d)?o(d):(an(d),i?a(d):s(d))),i&&!(d&&Ne(d))){if(u=c(),u.lock!==l){ze(t,e,n);return}s(u.session),d=u.session}(r=t.after)===null||r===void 0||r.call(t,d||u.session),hn(e)}function ze(t,e,n){ve(()=>{Q(t,e,n+1)},es)}function hn(t){$e=void 0;const e=fn.shift();e&&Q(e,t)}const pn=ge;function ns(t){switch(t.sessionPersistence){case we.COOKIE:return ln(t);case we.LOCAL_STORAGE:return un();case void 0:{let e=ln(t);return!e&&t.allowFallbackToLocalStorage&&(e=un()),e}default:C.error(`Invalid session persistence '${String(t.sessionPersistence)}'`)}}function rs(t,e,n,r){const i=new D,s=new D,o=new D,a=t.type===we.COOKIE?Hr(e,t.cookieOptions):Xr(e),{expireSession:c}=a,l=ct(h,pn);let u;g();const{throttled:d,cancel:f}=tn(()=>{Q({process:_=>{if(Be(_))return;const A=m(_);return w(A),A},after:_=>{on(_)&&!v()&&R(_),u=_}},a)},pn);function p(){Q({process:_=>v()?m(_):void 0},a)}function h(){Q({process:_=>Ne(_)?Z(_,e):void 0,after:m},a)}function m(_){return Ne(_)&&(_=Z(_,e)),v()&&(T(_)?k():(o.notify({previousState:u,newState:_}),u=_)),_}function g(){Q({process:_=>{if(Be(_))return Z(_,e)},after:_=>{u=_}},a)}function w(_){if(Be(_))return!1;const{trackingType:A,isTracked:It}=r(_[n]);_[n]=A,delete _.isExpired,It&&!_.id&&(_.id=q(),_.created=String(ye()))}function v(){return u[n]!==void 0}function T(_){return u.id!==_.id||u[n]!==_[n]}function k(){u=Z(u,e),s.notify()}function R(_){u=_,i.notify()}function x(_){Q({process:A=>({...A,..._}),after:m},a)}return{expandOrRenewSession:d,expandSession:p,getSession:()=>u,renewObservable:i,expireObservable:s,sessionStateUpdateObservable:o,restartSession:g,expire:()=>{f(),c(u),m(Z(u,e))},stop:()=>{Qt(l)},updateSessionState:x}}const mt={GRANTED:"granted",NOT_GRANTED:"not-granted"};function ss(t){const e=new D;return{tryToInit(n){t||(t=n)},update(n){t=n,e.notify()},isGranted(){return t===mt.GRANTED},observable:e}}function ee(t,e,n){if(typeof t!="object"||t===null)return JSON.stringify(t);const r=ae(Object.prototype),i=ae(Array.prototype),s=ae(Object.getPrototypeOf(t)),o=ae(t);try{return JSON.stringify(t,e,n)}catch{return"<error: unable to serialize object>"}finally{r(),i(),s(),o()}}function ae(t){const e=t,n=e.toJSON;return n?(delete e.toJSON,()=>{e.toJSON=n}):H}function gt(t){return is(t,location.href).href}function is(t,e){const n=os();if(n)try{return e!==void 0?new n(t,e):new n(t)}catch(s){throw new Error(`Failed to construct URL: ${String(s)} ${ee({url:t,base:e})}`)}if(e===void 0&&!/:/.test(t))throw new Error(`Invalid URL: '${t}'`);let r=document;const i=r.createElement("a");if(e!==void 0){r=document.implementation.createHTMLDocument("");const s=r.createElement("base");s.href=e,r.head.appendChild(s),r.body.appendChild(i)}return i.href=t,i}const mn=URL;let Ge;function os(){if(Ge===void 0)try{Ge=new mn("http://test/path").href==="http://test/path"}catch{Ge=!1}return Ge?mn:void 0}const as="datad0g.com",cs="dd0g-gov.com",ce="datadoghq.com",ls="ddog-gov.com",us="pci.browser-intake-datadoghq.com",ds=["ddsource","ddtags"];function Te(t,e,n){const r=fs(t,e);return{build(i,s){const o=ps(t,e,n,i,s);return r(o)},urlPrefix:r(""),trackType:e}}function fs(t,e){const n=`/api/v2/${e}`,r=t.proxy;if(typeof r=="string"){const s=gt(r);return o=>`${s}?ddforward=${encodeURIComponent(`${n}?${o}`)}`}if(typeof r=="function")return s=>r({path:n,parameters:s});const i=hs(e,t);return s=>`https://${i}${n}?${s}`}function hs(t,e){const{site:n=ce,internalAnalyticsSubdomain:r}=e;if(t==="logs"&&e.usePciIntake&&n===ce)return us;if(r&&n===ce)return`${r}.${ce}`;if(n===cs)return`http-intake.logs.${n}`;const i=n.split("."),s=i.pop();return`browser-intake-${i.join("-")}.${s}`}function ps({clientToken:t,internalAnalyticsSubdomain:e},n,r,i,{retry:s,encoding:o}){const a=["sdk_version:6.5.0",`api:${i}`].concat(r);s&&a.push(`retry_count:${s.count}`,`retry_after:${s.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=${q()}`];return o&&c.push(`dd-evp-encoding=${o}`),n==="rum"&&c.push(`batch_time=${G()}`),e&&c.reverse(),c.join("&")}const ms=200;function gs(t){const{env:e,service:n,version:r,datacenter:i}=t,s=[];return e&&s.push(Ve("env",e)),n&&s.push(Ve("service",n)),r&&s.push(Ve("version",r)),i&&s.push(Ve("datacenter",i)),s}function Ve(t,e){const n=ms-t.length-1;(e.length>n||ys(e))&&C.warn(`${t} value doesn't meet tag requirements and will be sanitized. ${Ae} ${st}/getting_started/tagging/#defining-tags`);const r=e.replace(/,/g,"_");return`${t}:${r}`}function ys(t){return _s()?new RegExp("[^\\p{Ll}\\p{Lo}0-9_:./-]","u").test(t):!1}function _s(){try{return new RegExp("[\\p{Ll}]","u"),!0}catch{return!1}}function bs(t){const e=t.site||ce,n=gs(t),r=vs(t,n);return{replica:Ss(t,n),site:e,...r}}function vs(t,e){return{logsEndpointBuilder:Te(t,"logs",e),rumEndpointBuilder:Te(t,"rum",e),sessionReplayEndpointBuilder:Te(t,"replay",e)}}function Ss(t,e){if(!t.replica)return;const n={...t,site:ce,clientToken:t.replica.clientToken},r={logsEndpointBuilder:Te(n,"logs",e),rumEndpointBuilder:Te(n,"rum",e)};return{applicationId:t.replica.applicationId,...r}}function ws(t){return ds.every(e=>t.includes(e))}function yt(t,e){return t!=null&&typeof t!="string"?(C.error(`${e} must be defined as a string`),!1):!0}function Ts(t){return t&&typeof t=="string"&&!/(datadog|ddog|datad0g|dd0g)/.test(t)?(C.error(`Site should be a valid Datadog site. ${Ae} ${st}/getting_started/site/.`),!1):!0}function je(t,e){return t!==void 0&&!hr(t)?(C.error(`${e} Sample Rate should be a number between 0 and 100`),!1):!0}function xs(t){var e,n,r,i,s,o;if(!t||!t.clientToken){C.error("Client Token is not configured, we will not send any data.");return}if(!(!Ts(t.site)||!je(t.sessionSampleRate,"Session")||!je(t.telemetrySampleRate,"Telemetry")||!je(t.telemetryConfigurationSampleRate,"Telemetry Configuration")||!je(t.telemetryUsageSampleRate,"Telemetry Usage")||!yt(t.version,"Version")||!yt(t.env,"Env")||!yt(t.service,"Service"))){if(t.trackingConsent!==void 0&&!Jt(mt,t.trackingConsent)){C.error('Tracking Consent should be either "granted" or "not-granted"');return}return{beforeSend:t.beforeSend&&qt(t.beforeSend,"beforeSend threw an error:"),sessionStoreStrategyType:ns(t),sessionSampleRate:(e=t.sessionSampleRate)!==null&&e!==void 0?e:100,telemetrySampleRate:(n=t.telemetrySampleRate)!==null&&n!==void 0?n:20,telemetryConfigurationSampleRate:(r=t.telemetryConfigurationSampleRate)!==null&&r!==void 0?r:5,telemetryUsageSampleRate:(i=t.telemetryUsageSampleRate)!==null&&i!==void 0?i:5,service:t.service||void 0,silentMultipleInit:!!t.silentMultipleInit,allowUntrustedEvents:!!t.allowUntrustedEvents,trackingConsent:(s=t.trackingConsent)!==null&&s!==void 0?s:mt.GRANTED,trackAnonymousUser:(o=t.trackAnonymousUser)!==null&&o!==void 0?o:!0,storeContextsAcrossPages:!!t.storeContextsAcrossPages,batchBytesLimit:16*B,eventRateLimiterThreshold:3e3,maxTelemetryEventsPerPage:15,flushTimeout:30*ge,batchMessagesLimit:50,messageBytesLimit:256*B,...bs(t)}}}function Es(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 _t;(function(t){t.WRITABLE_RESOURCE_GRAPHQL="writable_resource_graphql",t.MISSING_URL_CONTEXT_TELEMETRY="missing_url_context_telemetry"})(_t||(_t={}));const gn=new Set;function Cs(t){Array.isArray(t)&&ks(t.filter(e=>Jt(_t,e)))}function ks(t){t.forEach(e=>{gn.add(e)})}function Rs(){return gn}const xe="?";function N(t){const e=[];let n=bt(t,"stack");const r=String(t);return n&&n.startsWith(r)&&(n=n.slice(r.length)),n&&n.split(`
2
+ `).forEach(i=>{const s=As(i)||Os(i)||Is(i)||Bs(i);s&&(!s.func&&s.line&&(s.func=xe),e.push(s))}),{message:bt(t,"message"),name:bt(t,"name"),stack:e}}const yn="((?:file|https?|blob|chrome-extension|electron|native|eval|webpack|snippet|<anonymous>|\\w+\\.|\\/).*?)",le="(?::(\\d+))",Ds=new RegExp(`^\\s*at (.*?) ?\\(${yn}${le}?${le}?\\)?\\s*$`,"i"),Us=new RegExp(`\\((\\S*)${le}${le}\\)`);function As(t){const e=Ds.exec(t);if(!e)return;const n=e[2]&&e[2].indexOf("native")===0,r=e[2]&&e[2].indexOf("eval")===0,i=Us.exec(e[2]);return r&&i&&(e[2]=i[1],e[3]=i[2],e[4]=i[3]),{args:n?[e[2]]:[],column:e[4]?+e[4]:void 0,func:e[1]||xe,line:e[3]?+e[3]:void 0,url:n?void 0:e[2]}}const Fs=new RegExp(`^\\s*at ?${yn}${le}?${le}??\\s*$`,"i");function Os(t){const e=Fs.exec(t);if(e)return{args:[],column:e[3]?+e[3]:void 0,func:xe,line:e[2]?+e[2]:void 0,url:e[1]}}const Ls=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;function Is(t){const e=Ls.exec(t);if(e)return{args:[],column:e[4]?+e[4]:void 0,func:e[1]||xe,line:+e[3],url:e[2]}}const Ps=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i,Ms=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i;function Bs(t){const e=Ps.exec(t);if(!e)return;const n=e[3]&&e[3].indexOf(" > eval")>-1,r=Ms.exec(e[3]);return n&&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]||xe,line:e[4]?+e[4]:void 0,url:e[3]}}function bt(t,e){if(typeof t!="object"||!t||!(e in t))return;const n=t[e];return typeof n=="string"?n:void 0}function Ns(t,e,n,r){const i=[{url:e,column:r,line:n}],{name:s,message:o}=zs(t);return{name:s,message:o,stack:i}}const $s=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?([\s\S]*)$/;function zs(t){let e,n;return{}.toString.call(t)==="[object String]"&&([,e,n]=$s.exec(t)),{name:e,message:n}}function He(t){const n=new Error(t);n.name="HandlingStack";let r;return be(()=>{const i=N(n);i.stack=i.stack.slice(2),r=te(i)}),r}function te(t){let e=_n(t);return t.stack.forEach(n=>{const r=n.func==="?"?"<anonymous>":n.func,i=n.args&&n.args.length>0?`(${n.args.join(", ")})`:"",s=n.line?`:${n.line}`:"",o=n.line&&n.column?`:${n.column}`:"";e+=`
3
+ at ${r}${i} @ ${n.url}${s}${o}`}),e}function _n(t){return`${t.name||"Error"}: ${t.message}`}function ne(t,e,n,{computeHandlingStack:r}={}){let i=t[e];if(typeof i!="function")if(e in t&&e.startsWith("on"))i=H;else return{stop:H};let s=!1;const o=function(){if(s)return i.apply(this,arguments);const a=Array.from(arguments);let c;be(n,null,[{target:this,parameters:a,onPostCall:u=>{c=u},handlingStack:r?He("instrumented method"):void 0}]);const l=i.apply(this,a);return c&&be(c,null,[l]),l};return t[e]=o,{stop:()=>{s=!0,t[e]===o&&(t[e]=i)}}}const Gs=220*B,Vs="$",js=3;function $(t,e=Gs){const n=ae(Object.prototype),r=ae(Array.prototype),i=[],s=new WeakMap,o=vt(t,Vs,void 0,i,s),a=JSON.stringify(o);let c=a?a.length:0;if(c>e){wt(e,"discarded",t);return}for(;i.length>0&&c<e;){const l=i.shift();let u=0;if(Array.isArray(l.source))for(let d=0;d<l.source.length;d++){const f=vt(l.source[d],l.path,d,i,s);if(f!==void 0?c+=JSON.stringify(f).length:c+=4,c+=u,u=1,c>e){wt(e,"truncated",t);break}l.target[d]=f}else for(const d in l.source)if(Object.prototype.hasOwnProperty.call(l.source,d)){const f=vt(l.source[d],l.path,d,i,s);if(f!==void 0&&(c+=JSON.stringify(f).length+u+d.length+js,u=1),c>e){wt(e,"truncated",t);break}l.target[d]=f}}return n(),r(),o}function vt(t,e,n,r,i){const s=Ws(t);if(!s||typeof s!="object")return Hs(s);const o=St(s);if(o!=="[Object]"&&o!=="[Array]"&&o!=="[Error]")return o;const a=t;if(i.has(a))return`[Reference seen at ${i.get(a)}]`;const c=n!==void 0?`${e}.${n}`:e,l=Array.isArray(s)?[]:{};return i.set(a,c),r.push({source:s,target:l,path:c}),l}function Hs(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 St(t){try{if(t instanceof Event)return qs(t);if(t instanceof RegExp)return`[RegExp] ${t.toString()}`;const n=Object.prototype.toString.call(t).match(/\[object (.*)\]/);if(n&&n[1])return`[${n[1]}]`}catch{}return"[Unserializable]"}function qs(t){return{type:t.type,isTrusted:t.isTrusted,currentTarget:t.currentTarget?St(t.currentTarget):null,target:t.target?St(t.target):null}}function Ws(t){const e=t;if(e&&typeof e.toJSON=="function")try{return e.toJSON()}catch{}return t}function wt(t,e,n){C.warn(`The data provided has been ${e} as it is over the limit of ${t} characters:`,n)}const bn="No stack, consider using an instance of Error";function vn({stackTrace:t,originalError:e,handlingStack:n,componentStack:r,startClocks:i,nonErrorPrefix:s,source:o,handling:a}){const c=W(e),l=Ys(t,c,s,e),u=Ks(c,t)?te(t):bn,d=c?Tn(e,o):void 0,f=t?t.name:void 0,p=Sn(e),h=wn(e);return{startClocks:i,source:o,handling:a,handlingStack:n,componentStack:r,originalError:e,type:f,message:l,stack:u,causes:d,fingerprint:p,context:h}}function Ys(t,e,n,r){return t!=null&&t.message&&(t!=null&&t.name)?t.message:e?"Empty message":`${n} ${ee($(r))}`}function Ks(t,e){return e===void 0?!1:t?!0:e.stack.length>0&&(e.stack.length>1||e.stack[0].url!==void 0)}function Sn(t){return W(t)&&"dd_fingerprint"in t?String(t.dd_fingerprint):void 0}function wn(t){if(t!==null&&typeof t=="object"&&"dd_context"in t)return t.dd_context}function Js(t){var e;return(e=/@ (.+)/.exec(t))===null||e===void 0?void 0:e[1]}function W(t){return t instanceof Error||Object.prototype.toString.call(t)==="[object Error]"}function Tn(t,e){let n=t;const r=[];for(;W(n==null?void 0:n.cause)&&r.length<10;){const i=N(n.cause);r.push({message:n.cause.message,source:e,type:i==null?void 0:i.name,stack:te(i)}),n=n.cause}return r.length?r:void 0}const O={AGENT:"agent",CONSOLE:"console",CUSTOM:"custom",LOGGER:"logger",NETWORK:"network",SOURCE:"source",REPORT:"report"};function Xs(t){const e=(i,s)=>{const o=vn({stackTrace:i,originalError:s,startClocks:V(),nonErrorPrefix:"Uncaught",source:O.SOURCE,handling:"unhandled"});t.notify(o)},{stop:n}=Zs(e),{stop:r}=Qs(e);return{stop:()=>{n(),r()}}}function Zs(t){return ne(window,"onerror",({parameters:[e,n,r,i,s]})=>{let o;W(s)?o=N(s):o=Ns(e,n,r,i),t(o,s??e)})}function Qs(t){return ne(window,"onunhandledrejection",({parameters:[e]})=>{const n=e.reason||"Empty reason",r=N(n);t(r,n)})}function ei(t){const e={version:"6.5.0",onReady(n){n()},...t};return Object.defineProperty(e,"_setDebug",{get(){return Tr},enumerable:!1}),e}function ti(t,e,n){const r=t[e];r&&!r.q&&r.version&&C.warn("SDK is loaded more than once. This is unsupported and might have unexpected behavior."),t[e]=n,r&&r.q&&r.q.forEach(i=>qt(i,"onReady callback threw an error:")())}function xn(t,e){e.silentMultipleInit||C.error(`${t} is already initialized.`)}function re(t,e,n,r,i){return Tt(t,e,[n],r,i)}function Tt(t,e,n,r,{once:i,capture:s,passive:o}={}){const a=S(f=>{!f.isTrusted&&!f.__ddIsTrusted&&!t.allowUntrustedEvents||(i&&d(),r(f))}),c=o?{capture:s,passive:o}:s,l=window.EventTarget&&e instanceof EventTarget?window.EventTarget.prototype:e,u=ie(l,"addEventListener");n.forEach(f=>u.call(e,f,a,c));function d(){const f=ie(l,"removeEventListener");n.forEach(p=>f.call(e,p,a,c))}return{stop:d}}const qe={intervention:"intervention",deprecation:"deprecation",cspViolation:"csp_violation"};function ni(t,e){const n=[];e.includes(qe.cspViolation)&&n.push(si(t));const r=e.filter(i=>i!==qe.cspViolation);return r.length&&n.push(ri(r)),en(...n)}function ri(t){return new D(e=>{if(!window.ReportingObserver)return;const n=S((i,s)=>i.forEach(o=>e.notify(ii(o)))),r=new window.ReportingObserver(n,{types:t,buffered:!0});return r.observe(),()=>{r.disconnect()}})}function si(t){return new D(e=>{const{stop:n}=re(t,document,"securitypolicyviolation",r=>{e.notify(oi(r))});return n})}function ii(t){const{type:e,body:n}=t;return En({type:n.id,message:`${e}: ${n.message}`,originalError:t,stack:Cn(n.id,n.message,n.sourceFile,n.lineNumber,n.columnNumber)})}function oi(t){const e=`'${t.blockedURI}' blocked by '${t.effectiveDirective}' directive`;return En({type:t.effectiveDirective,message:`${qe.cspViolation}: ${e}`,originalError:t,csp:{disposition:t.disposition},stack:Cn(t.effectiveDirective,t.originalPolicy?`${e} of the policy "${Rr(t.originalPolicy,100,"...")}"`:"no policy",t.sourceFile,t.lineNumber,t.columnNumber)})}function En(t){return{startClocks:V(),source:O.REPORT,handling:"unhandled",...t}}function Cn(t,e,n,r,i){return n?te({name:t,message:e,stack:[{func:"?",url:n,line:r??void 0,column:i??void 0}]}):void 0}function kn(t,e){const n=window.__ddBrowserSdkExtensionCallback;n&&n({type:t,payload:e})}function Rn(t){return t===null?"null":Array.isArray(t)?"array":typeof t}function We(t,e,n=ai()){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 i=e.flags||[e.global?"g":"",e.ignoreCase?"i":"",e.multiline?"m":"",e.sticky?"y":"",e.unicode?"u":""].join("");return new RegExp(e.source,i)}if(n.hasAlreadyBeenSeen(e))return;if(Array.isArray(e)){const i=Array.isArray(t)?t:[];for(let s=0;s<e.length;++s)i[s]=We(i[s],e[s],n);return i}const r=Rn(t)==="object"?t:{};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=We(r[i],e[i],n));return r}function Dn(t){return We(void 0,t)}function ue(...t){let e;for(const n of t)n!=null&&(e=We(e,n));return e}function ai(){if(typeof WeakSet<"u"){const e=new WeakSet;return{hasAlreadyBeenSeen(n){const r=e.has(n);return r||e.add(n),r}}}const t=[];return{hasAlreadyBeenSeen(e){const n=t.indexOf(e)>=0;return n||t.push(e),n}}}function ci(){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 li(t){const e=new Set;return t.forEach(n=>e.add(n)),Array.from(e)}function Un(t,e){const n=t.indexOf(e);n>=0&&t.splice(n,1)}const ui=500;function An(){const t=[];return{add:i=>{t.push(i)>ui&&t.splice(0,1)},remove:i=>{Un(t,i)},drain:i=>{t.forEach(s=>s(i)),t.length=0}}}const se={log:"log",configuration:"configuration",usage:"usage"},di=["https://www.datadoghq-browser-agent.com","https://www.datad0g-browser-agent.com","https://d3uc069fcn7uxw.cloudfront.net","https://d20xtzwzcl0ceb.cloudfront.net","http://localhost","<anonymous>"],fi=[ls];let Fn=An(),de=t=>{Fn.add(()=>de(t))};function hi(t,e){let n;const r=new D,i=new Set,s=!fi.includes(e.site)&&Fe(e.telemetrySampleRate),o={[se.log]:s,[se.configuration]:s&&Fe(e.telemetryConfigurationSampleRate),[se.usage]:s&&Fe(e.telemetryUsageSampleRate)},a=pi();de=l=>{const u=ee(l);if(o[l.type]&&i.size<e.maxTelemetryEventsPerPage&&!i.has(u)){const d=c(t,l,a);r.notify(d),kn("telemetry",d),i.add(u)}},wr(Ln);function c(l,u,d){return ue({type:"telemetry",date:G(),service:l,version:"6.5.0",source:"browser",_dd:{format_version:2},telemetry:ue(u,{runtime_env:d,connectivity:ci(),sdk_setup:"npm"}),experimental_features:Array.from(Rs())},n!==void 0?n():{})}return{setContextProvider:l=>{n=l},observable:r,enabled:s}}function pi(){return{is_local_file:window.location.protocol==="file:",is_worker:"WorkerGlobalScope"in self}}function mi(){Fn.drain()}function gi(t){return t.site===as}function On(t,e){at(E.debug,t,e),de({type:se.log,message:t,status:"debug",...e})}function Ln(t,e){de({type:se.log,status:"error",...bi(t),...e})}function yi(t){de({type:se.configuration,configuration:t})}function _i(t){de({type:se.usage,usage:t})}function bi(t){if(W(t)){const e=N(t);return{error:{kind:e.name,stack:te(vi(e))},message:e.message}}return{error:{stack:bn},message:`Uncaught ${ee(t)}`}}function vi(t){return t.stack=t.stack.filter(e=>!e.url||di.some(n=>e.url.startsWith(n))),t}const Ee=1/0,Si=J;let Ce=null;const Ye=new Set;function wi(){Ye.forEach(t=>t())}function Ti({expireDelay:t,maxEntries:e}){let n=[];const r=[];Ce||(Ce=ct(()=>wi(),Si));const i=()=>{const p=Oe()-t;for(;n.length>0&&n[n.length-1].endTime<p;){const h=n.pop();h&&r.push(h.startTime)}};Ye.add(i);function s(p,h){const m={value:p,startTime:h,endTime:Ee,remove:()=>{Un(n,m)},close:g=>{m.endTime=g}};return e&&n.length>=e&&n.pop(),n.unshift(m),m}function o(p=Ee,h={returnInactive:!1}){for(const m of n)if(m.startTime<=p){if(h.returnInactive||p<=m.endTime)return m.value;break}}function a(p){const h=n[0];h&&h.endTime===Ee&&h.close(p)}function c(p=Ee,h=0){const m=_r(p,h);return n.filter(g=>g.startTime<=m&&p<=g.endTime).map(g=>g.value)}function l(){return n.map(({startTime:p,endTime:h,value:m})=>({startTime:p,endTime:h===Ee?"Infinity":h,value:m}))}function u(){return r}function d(){n=[]}function f(){Ye.delete(i),Ye.size===0&&Ce&&(Qt(Ce),Ce=null)}return{add:s,find:o,closeActive:a,findAll:c,reset:d,stop:f,getAllEntries:l,getDeletedEntries:u}}const xi=J,Ei=ft;function Ci(t,e,n,r){const i=new D,s=new D,o=rs(t.sessionStoreStrategyType,t,e,n),a=Ti({expireDelay:Ei});o.renewObservable.subscribe(()=>{a.add(c(),Oe()),i.notify()}),o.expireObservable.subscribe(()=>{s.notify(),a.closeActive(Oe())}),o.expandOrRenewSession(),a.add(c(),gr().relative),r.observable.subscribe(()=>{r.isGranted()?o.expandOrRenewSession():o.expire()}),ki(t,()=>{r.isGranted()&&o.expandOrRenewSession()}),Ri(t,()=>o.expandSession()),Di(t,()=>o.restartSession());function c(){return{id:o.getSession().id,trackingType:o.getSession()[e],isReplayForced:!!o.getSession().forcedReplay,anonymousId:o.getSession().anonymousId}}return{findSession:(l,u)=>a.find(l,u),renewObservable:i,expireObservable:s,sessionStateUpdateObservable:o.sessionStateUpdateObservable,expire:o.expire,updateSessionState:o.updateSessionState}}function ki(t,e){Tt(t,window,["click","touchstart","keydown","scroll"],e,{capture:!0,passive:!0})}function Ri(t,e){const n=()=>{document.visibilityState==="visible"&&e()};re(t,document,"visibilitychange",n),ct(n,xi)}function Di(t,e){re(t,window,"resume",e,{capture:!0})}function In(t){return t>=500}function Ui(t){try{return t.clone()}catch{return}}const Ai=80*B,Fi=32,Pn=3*Kt,Oi=J,Mn=ge;function Bn(t,e,n,r,i){e.transportStatus===0&&e.queuedPayloads.size()===0&&e.bandwidthMonitor.canHandle(t)?$n(t,e,n,{onSuccess:()=>zn(0,e,n,r,i),onFailure:()=>{e.queuedPayloads.enqueue(t),Nn(e,n,r,i)}}):e.queuedPayloads.enqueue(t)}function Nn(t,e,n,r){t.transportStatus===2&&ve(()=>{const i=t.queuedPayloads.first();$n(i,t,e,{onSuccess:()=>{t.queuedPayloads.dequeue(),t.currentBackoffTime=Mn,zn(1,t,e,n,r)},onFailure:()=>{t.currentBackoffTime=Math.min(Oi,t.currentBackoffTime*2),Nn(t,e,n,r)}})},t.currentBackoffTime)}function $n(t,e,n,{onSuccess:r,onFailure:i}){e.bandwidthMonitor.add(t),n(t,s=>{e.bandwidthMonitor.remove(t),Li(s)?(e.transportStatus=e.bandwidthMonitor.ongoingRequestCount>0?1:2,t.retry={count:t.retry?t.retry.count+1:1,lastFailureStatus:s.status},i()):(e.transportStatus=0,r())})}function zn(t,e,n,r,i){t===0&&e.queuedPayloads.isFull()&&!e.queueFullReported&&(i({message:`Reached max ${r} events size queued for upload: ${Pn/Kt}MiB`,source:O.AGENT,startClocks:V()}),e.queueFullReported=!0);const s=e.queuedPayloads;for(e.queuedPayloads=Gn();s.size()>0;)Bn(s.dequeue(),e,n,r,i)}function Li(t){return t.type!=="opaque"&&(t.status===0&&!navigator.onLine||t.status===408||t.status===429||In(t.status))}function Ii(){return{transportStatus:0,currentBackoffTime:Mn,bandwidthMonitor:Pi(),queuedPayloads:Gn(),queueFullReported:!1}}function Gn(){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>=Pn}}}function Pi(){return{ongoingRequestCount:0,ongoingByteCount:0,canHandle(t){return this.ongoingRequestCount===0||this.ongoingByteCount+t.bytesCount<=Ai&&this.ongoingRequestCount<Fi},add(t){this.ongoingRequestCount+=1,this.ongoingByteCount+=t.bytesCount},remove(t){this.ongoingRequestCount-=1,this.ongoingByteCount-=t.bytesCount}}}function Mi(t,e,n){const r=Ii(),i=(s,o)=>$i(t,e,s,o);return{send:s=>{Bn(s,r,i,t.trackType,n)},sendOnExit:s=>{Bi(t,e,s)}}}function Bi(t,e,n){if(!!navigator.sendBeacon&&n.bytesCount<e)try{const s=t.build("beacon",n);if(navigator.sendBeacon(s,n.data))return}catch(s){Ni(s)}const i=t.build("xhr",n);xt(i,n.data)}let Vn=!1;function Ni(t){Vn||(Vn=!0,Ln(t))}function $i(t,e,n,r){if(zi()&&n.bytesCount<e){const s=t.build("fetch",n);fetch(s,{method:"POST",body:n.data,keepalive:!0,mode:"cors"}).then(S(o=>r==null?void 0:r({status:o.status,type:o.type})),S(()=>{const o=t.build("xhr",n);xt(o,n.data,r)}))}else{const s=t.build("xhr",n);xt(s,n.data,r)}}function zi(){try{return window.Request&&"keepalive"in new Request("http://a")}catch{return!1}}function xt(t,e,n){const r=new XMLHttpRequest;r.open("POST",t,!0),e instanceof Blob&&r.setRequestHeader("Content-Type",e.type),re({allowUntrustedEvents:!0},r,"loadend",()=>{n==null||n({status:r.status})},{once:!0}),r.send(e)}function Et(){const t=Gi();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,n,r){const i=r?{id:r}:void 0;t.send(JSON.stringify({eventType:e,event:n,view:i}))}}}function Ke(t){var e;t===void 0&&(t=(e=j().location)===null||e===void 0?void 0:e.hostname);const n=Et();return!!n&&n.getAllowedWebViewHosts().some(r=>t===r||t.endsWith(`.${r}`))}function Gi(){return j().DatadogEventBridge}const Je={HIDDEN:"visibility_hidden",UNLOADING:"before_unload",PAGEHIDE:"page_hide",FROZEN:"page_frozen"};function Vi(t){return new D(e=>{const{stop:n}=Tt(t,window,["visibilitychange","freeze"],i=>{i.type==="visibilitychange"&&document.visibilityState==="hidden"?e.notify({reason:Je.HIDDEN}):i.type==="freeze"&&e.notify({reason:Je.FROZEN})},{capture:!0}),r=re(t,window,"beforeunload",()=>{e.notify({reason:Je.UNLOADING})}).stop;return()=>{n(),r()}})}function ji(t){return Me(Je).includes(t)}function Hi({encoder:t,request:e,flushController:n,messageBytesLimit:r}){let i={};const s=n.flushObservable.subscribe(d=>u(d));function o(d,f,p){n.notifyBeforeAddMessage(f),p!==void 0?(i[p]=d,n.notifyAfterAddMessage()):t.write(t.isEmpty?d:`
4
+ ${d}`,h=>{n.notifyAfterAddMessage(h-f)})}function a(d){return d!==void 0&&i[d]!==void 0}function c(d){const f=i[d];delete i[d];const p=t.estimateEncodedBytesCount(f);n.notifyAfterRemoveMessage(p)}function l(d,f){const p=ee(d),h=t.estimateEncodedBytesCount(p);if(h>=r){C.warn(`Discarded a message whose size was bigger than the maximum allowed size ${r}KB. ${Ae} ${Ht}/#technical-limitations`);return}a(f)&&c(f),o(p,h,f)}function u(d){const f=Me(i).join(`
5
+ `);i={};const p=ji(d.reason),h=p?e.sendOnExit:e.send;if(p&&t.isAsync){const m=t.finishSync();m.outputBytesCount&&h(jn(m));const g=[m.pendingData,f].filter(Boolean).join(`
6
6
  `);g&&h({data:g,bytesCount:ot(g)})}else f&&t.write(t.isEmpty?f:`
7
- ${f}`),t.finish(m=>{h(Vn(m))})}return{flushController:n,add:l,upsert:l,stop:i.unsubscribe}}function Vn(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 Hi({messagesLimit:t,bytesLimit:e,durationLimit:n,pageExitObservable:r,sessionExpireObservable:s}){const i=r.subscribe(h=>u(h.reason)),o=s.subscribe(()=>u("session_expire")),a=new R(()=>()=>{i.unsubscribe(),o.unsubscribe()});let c=0,l=0;function u(h){if(l===0)return;const m=l,g=c;l=0,c=0,p(),a.notify({reason:h,messagesCount:m,bytesCount:g})}let d;function f(){d===void 0&&(d=ve(()=>{u("duration_limit")},n))}function p(){Xt(d),d=void 0}return{flushObservable:a,get messagesCount(){return l},notifyBeforeAddMessage(h){c+h>=e&&u("bytes_limit"),l+=1,c+=h,f()},notifyAfterAddMessage(h=0){c+=h,l>=t?u("messages_limit"):c>=e&&u("bytes_limit")},notifyAfterRemoveMessage(h){c-=h,l-=1,l===0&&p()}}}function jn(t,e,n,r,s,i,o=ji){const a=l(t,e),c=n&&l(t,n);function l(u,{endpoint:d,encoder:f}){return o({encoder:f,request:Pi(d,u.batchBytesLimit,r),flushController:Hi({messagesLimit:u.batchMessagesLimit,bytesLimit:u.batchBytesLimit,durationLimit:u.flushTimeout,pageExitObservable:s,sessionExpireObservable:i}),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 Xe(){let t="",e=0;return{isAsync:!1,get isEmpty(){return!t},write(n,r){const s=ot(n);e+=s,t+=n,r&&r(s)},finish(n){n(this.finishSync())},finishSync(){const n={output:t,outputBytesCount:e,rawBytesCount:e,pendingData:""};return t="",e=0,n},estimateEncodedBytesCount(n){return n.length}}}class qi{constructor(){this.callbacks={}}notify(e,n){const r=this.callbacks[e];r&&r.forEach(s=>s(n))}subscribe(e,n){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(n),{unsubscribe:()=>{this.callbacks[e]=this.callbacks[e].filter(r=>n!==r)}}}}function Wi(t,e,n){let r=0,s=!1;return{isLimitReached(){if(r===0&&ve(()=>{r=0},K),r+=1,r<=e||s)return s=!1,!1;if(r===e+1){s=!0;try{n({message:`Reached max number of ${t}s by minute: ${e}`,source:D.AGENT,startClocks:G()})}finally{s=!1}}return!0}}}let Ct;const kt=new WeakMap;function Yi(t){return Ct||(Ct=Ki(t)),Ct}function Ki(t){return new R(e=>{const{stop:n}=te(XMLHttpRequest.prototype,"open",Ji),{stop:r}=te(XMLHttpRequest.prototype,"send",i=>{Xi(i,t,e)},{computeHandlingStack:!0}),{stop:s}=te(XMLHttpRequest.prototype,"abort",Zi);return()=>{n(),r(),s()}})}function Ji({target:t,parameters:[e,n]}){kt.set(t,{state:"open",method:String(e).toUpperCase(),url:gt(String(n))})}function Xi({target:t,handlingStack:e},n,r){const s=kt.get(t);if(!s)return;const i=s;i.state="start",i.startClocks=G(),i.isAborted=!1,i.xhr=t,i.handlingStack=e;let o=!1;const{stop:a}=te(t,"onreadystatechange",()=>{t.readyState===XMLHttpRequest.DONE&&c()}),c=()=>{if(l(),a(),o)return;o=!0;const u=s;u.state="complete",u.duration=gr(i.startClocks.timeStamp,z()),u.status=t.status,r.notify(vr(u))},{stop:l}=ne(n,t,"loadend",c);r.notify(i)}function Zi({target:t}){const e=kt.get(t);e&&(e.isAborted=!0)}let Rt;function Hn(){return Rt||(Rt=Qi()),Rt}function Qi(){return new R(t=>{if(!window.fetch)return;const{stop:e}=te(window,"fetch",n=>eo(n,t),{computeHandlingStack:!0});return e})}function eo({parameters:t,onPostCall:e,handlingStack:n},r){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:gt(String(s)),l=G(),u={state:"start",init:i,input:s,method:a,startClocks:l,url:c,handlingStack:n};r.notify(u),t[0]=u.input,t[1]=u.init,e(d=>to(r,d,u))}function to(t,e,n){const r=n;function s(i){r.state="resolve",Object.assign(r,i),t.notify(r)}e.then(v(i=>{s({response:i,responseType:i.type,status:i.status,isAborted:!1})}),v(i=>{var o,a;s({status:0,isAborted:((a=(o=r.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 no(t){const e=t.map(n=>(Ut[n]||(Ut[n]=ro(n)),Ut[n]));return Qt(...e)}function ro(t){return new R(e=>{const n=P[t];return P[t]=(...r)=>{n.apply(console,r);const s=He("console error");be(()=>{e.notify(so(r,t,s))})},()=>{P[t]=n}})}function so(t,e,n){const r=t.map(i=>io(i)).join(" ");let s;if(e===x.error){const i=t.find(q);s={stack:i?ee(B(i)):void 0,fingerprint:vn(i),causes:i?wn(i,"console"):void 0,startClocks:G(),message:r,source:D.CONSOLE,handling:"handled",handlingStack:n,context:Sn(i)}}return{api:e,message:r,error:s,handlingStack:n}}function io(t){return typeof t=="string"?N(t):q(t)?yn(B(t)):Q(N(t),void 0,2)}function oo(t){const e=kn(t)==="object";return e||E.error("Unsupported context:",t),e}function At(t,e,n){const r={...t};for(const[s,{required:i,type:o}]of Object.entries(e))o==="string"&&s in r&&(r[s]=String(r[s])),i&&!(s in t)&&E.warn(`The property ${s} of ${n} is required; context will not be sent to the intake.`);return r}function Ze(t="",{customerDataTracker:e,propertiesConfig:n={}}={}){let r={};const s=new R,i={getContext:()=>Rn(r),setContext:o=>{oo(o)?(r=N(At(o,n,t)),e==null||e.updateCustomerData(r)):i.clearContext(),s.notify()},setContextProperty:(o,a)=>{r=N(At({...r,[o]:a},n,t)),e==null||e.updateCustomerData(r),s.notify()},removeContextProperty:o=>{delete r[o],e==null||e.updateCustomerData(r),At(r,n,t),s.notify()},clearContext:()=>{r={},e==null||e.resetCustomerData(),s.notify()},changeObservable:s};return i}const ao="_dd_c",co=[];function Dt(t,e,n,r){const s=lo(n,r);co.push(ne(t,window,"storage",({key:l})=>{s===l&&o()})),e.changeObservable.subscribe(a);const i=le(c(),e.getContext());_e(i)||e.setContext(i);function o(){e.setContext(c())}function a(){localStorage.setItem(s,JSON.stringify(e.getContext()))}function c(){const l=localStorage.getItem(s);return l?JSON.parse(l):{}}}function lo(t,e){return`${ao}_${t}_${e}`}const uo=3*M,fo=16*M,ho=200;function po(t=2){const e=new Map;let n=!1;function r(s=0){if(n||t===0)return;const i=t===2?uo:fo;let o=s;e.forEach(a=>{o+=a.getBytesCount()}),o>i&&(mo(i),n=!0)}return{createDetachedTracker:()=>{const s=qn(()=>r(s.getBytesCount()));return s},getOrCreateTracker:s=>(e.has(s)||e.set(s,qn(r)),e.get(s)),setCompressionStatus:s=>{t===0&&(t=s,r())},getCompressionStatus:()=>t,stop:()=>{e.forEach(s=>s.stop()),e.clear()}}}function qn(t){let e=0;const{throttled:n,cancel:r}=en(i=>{e=ot(Q(i)),t()},ho),s=()=>{r(),e=0};return{updateCustomerData:i=>{_e(i)?s():n(i)},resetCustomerData:s,getBytesCount:()=>e,stop:()=>{r()}}}function mo(t){E.warn(`Customer data exceeds the recommended ${t/M}KiB threshold. ${De} ${jt}/#customer-data-exceeds-the-recommended-threshold-warning`)}function go(t,e,n){const r=t.getReader(),s=[];let i=0;o();function o(){r.read().then(v(c=>{if(c.done){a();return}s.push(c.value),i+=c.value.length,i>n.bytesLimit?a():o()}),v(c=>e(c)))}function a(){r.cancel().catch(j);let c,l;{let u;if(s.length===1)u=s[0];else{u=new Uint8Array(i);let d=0;s.forEach(f=>{u.set(f,d),d+=f.length})}c=u.slice(0,n.bytesLimit),l=u.length>n.bytesLimit}e(void 0,c,l)}}const yo="datadog-synthetics-public-id",_o="datadog-synthetics-result-id",bo="datadog-synthetics-injects-rum";function Wn(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||J(bo))}function vo(){const t=window._DATADOG_SYNTHETICS_PUBLIC_ID||J(yo);return typeof t=="string"?t:void 0}function So(){const t=window._DATADOG_SYNTHETICS_RESULT_ID||J(_o);return typeof t=="string"?t:void 0}function Qe(t,e,n){const r=n.getHandler(),s=Array.isArray(r)?r:[r];return Yn[t]>=Yn[n.getLevel()]&&s.includes(e)}const _={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},Yn={[_.ok]:0,[_.debug]:1,[_.info]:2,[_.notice]:4,[_.warn]:5,[_.error]:6,[_.critical]:7,[_.alert]:8,[_.emerg]:9};function et(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 wo=function(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i};const ke={console:"console",http:"http",silent:"silent"},To=Object.keys(_);let F=class{constructor(e,n,r,s=ke.http,i=_.debug,o={}){this.handleLogStrategy=e,this.handlerType=s,this.level=i,this.contextManager=Ze("logger",{customerDataTracker:n}),this.contextManager.setContext(o),r&&this.contextManager.setContextProperty("logger",{name:r})}logImplementation(e,n,r=_.info,s,i){const o=N(n);let a;if(s!=null){const c=bn({stackTrace:q(s)?B(s):void 0,originalError:s,nonErrorPrefix:"Provided",source:D.LOGGER,handling:"handled",startClocks:G()});a=le({error:et(c,{includeMessage:!0})},o)}else a=o;this.handleLogStrategy({message:N(e),context:a,status:r},this,i)}log(e,n,r=_.info,s){let i;Qe(r,ke.http,this)&&(i=He("log")),this.logImplementation(e,n,r,s,i)}setContext(e){this.contextManager.setContext(e)}getContext(){return this.contextManager.getContext()}setContextProperty(e,n){this.contextManager.setContextProperty(e,n)}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}};wo([Tr],F.prototype,"logImplementation",null),F.prototype.ok=$(_.ok),F.prototype.debug=$(_.debug),F.prototype.info=$(_.info),F.prototype.notice=$(_.notice),F.prototype.warn=$(_.warn),F.prototype.error=$(_.error),F.prototype.critical=$(_.critical),F.prototype.alert=$(_.alert),F.prototype.emerg=$(_.emerg);function $(t){return function(e,n,r){let s;Qe(t,ke.http,this)&&(s=He("log")),this.logImplementation(e,n,t,r,s)}}function xo(t,e,n){return{view:{referrer:document.referrer,url:window.location.href},context:t.getContext(),user:e.getContext(),account:n.getContext()}}const Eo=32*M;function Co(t){t.usePciIntake===!0&&t.site&&t.site!=="datadoghq.com"&&E.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");const e=Ts(t),n=Kn(t.forwardConsoleLogs,Me(x),"Forward Console Logs"),r=Kn(t.forwardReports,Me(qe),"Forward Reports");if(!(!e||!n||!r))return t.forwardErrorsToLogs&&!n.includes(x.error)&&n.push(x.error),{forwardErrorsToLogs:t.forwardErrorsToLogs!==!1,forwardConsoleLogs:n,forwardReports:r,requestErrorResponseLengthLimit:Eo,...e}}function Kn(t,e,n){if(t===void 0)return[];if(!(t==="all"||Array.isArray(t)&&t.every(r=>e.includes(r)))){E.error(`${n} should be "all" or an array with allowed values "${e.join('", "')}"`);return}return t==="all"?e:ci(t)}function ko(t){const e=xs(t);return{forward_errors_to_logs:t.forwardErrorsToLogs,forward_console_logs:t.forwardConsoleLogs,forward_reports:t.forwardReports,use_pci_intake:t.usePciIntake,...e}}function Ro(t,e,n){const r=An();let s,i;const o=e.observable.subscribe(a);function a(){if(!i||!s||!e.isGranted())return;o.unsubscribe();const c=n(s,i);r.drain(c)}return{init(c){if(!c){E.error("Missing configuration");return}if(Es(c.enableExperimentalFeatures),Ke()&&(c=Uo(c)),s=c,i){Tn("DD_LOGS",c);return}const l=Co(c);l&&(i=l,Hn().subscribe(j),e.tryToInit(l.trackingConsent),a())},get initConfiguration(){return s},getInternalContext:j,handleLog(c,l,u,d=t(),f=z()){r.add(p=>p.handleLog(c,l,u,d,f))}}}function Uo(t){return{...t,clientToken:"empty"}}const Ft="logs";function Ao(t){const e=po(),n=Ze("global context",{customerDataTracker:e.getOrCreateTracker(2)}),r=Ze("user",{customerDataTracker:e.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),s=Ze("account",{customerDataTracker:e.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),i=rs();function o(){return xo(n,r,s)}let a=Ro(o,i,(u,d)=>{u.storeContextsAcrossPages&&(Dt(d,n,Ft,2),Dt(d,r,Ft,1),Dt(d,s,Ft,4));const f=t(u,d,o,i);return a=Do(u,f),f});const c={},l=new F((...u)=>a.handleLog(...u),e.createDetachedTracker());return Qs({logger:l,init:v(u=>a.init(u)),setTrackingConsent:v(u=>{i.update(u),yi({feature:"set-tracking-consent",tracking_consent:u})}),getGlobalContext:v(()=>n.getContext()),setGlobalContext:v(u=>n.setContext(u)),setGlobalContextProperty:v((u,d)=>n.setContextProperty(u,d)),removeGlobalContextProperty:v(u=>n.removeContextProperty(u)),clearGlobalContext:v(()=>n.clearContext()),createLogger:v((u,d={})=>(c[u]=new F((...f)=>a.handleLog(...f),e.createDetachedTracker(),N(u),d.handler,d.level,N(d.context)),c[u])),getLogger:v(u=>c[u]),getInitConfiguration:v(()=>Rn(a.initConfiguration)),getInternalContext:v(u=>a.getInternalContext(u)),setUser:v(r.setContext),getUser:v(r.getContext),setUserProperty:v(r.setContextProperty),removeUserProperty:v(r.removeContextProperty),clearUser:v(r.clearContext),setAccount:v(s.setContext),getAccount:v(s.getContext),setAccountProperty:v(s.setContextProperty),removeAccountProperty:v(s.removeContextProperty),clearAccount:v(s.clearContext)})}function Do(t,e){return{init:n=>{Tn("DD_LOGS",n)},initConfiguration:t,...e}}const Fo="logs";function Oo(t,e){const n=Ei(t,Fo,r=>Io(t,r),e);return{findTrackedSession:(r,s={returnInactive:!1})=>{const i=n.findSession(r,s);return i&&i.trackingType==="1"?{id:i.id,anonymousId:i.anonymousId}:void 0},expireObservable:n.expireObservable}}function Lo(t){const n=Jn(t)==="1"?{}:void 0;return{findTrackedSession:()=>n,expireObservable:new R}}function Jn(t){return Fe(t.sessionSampleRate)?"1":"0"}function Io(t,e){const n=Po(e)?e:Jn(t);return{trackingType:n,isTracked:n==="1"}}function Po(t){return t==="0"||t==="1"}let Xn=!1;function tt(t){const e=window;if(Wn()){const r=n(e.DD_RUM_SYNTHETICS);return!r&&!Xn&&(Xn=!0,Fn("Logs sent before RUM is injected by the synthetics worker",{testId:vo(),resultId:So()})),r}return n(e.DD_RUM);function n(r){if(r&&r.getInternalContext)return r.getInternalContext(t)}}function Mo(t,e,n,r,s){const i=To.concat(["custom"]),o={};i.forEach(a=>{o[a]=Wi(a,e.eventRateLimiterThreshold,s)}),n.subscribe(0,({rawLogsEvent:a,messageContext:c=void 0,savedCommonContext:l=void 0,domainContext:u})=>{var d,f;const p=_r(a.date),h=t.findTrackedSession(p);if(!t.findTrackedSession(p,{returnInactive:!0}))return;const g=l||r();let S;!_e(g.account)&&g.account.id&&(S=g.account),h&&h.anonymousId&&!g.user.anonymous_id&&(g.user.anonymous_id=h.anonymousId);const b=le({service:e.service,session_id:h?h.id:void 0,session:h?{id:h.id}:void 0,usr:_e(g.user)?void 0:g.user,account:S,view:g.view},g.context,tt(p),a,c);((d=e.beforeSend)===null||d===void 0?void 0:d.call(e,b,u))===!1||b.origin!==D.AGENT&&((f=o[b.status])!==null&&f!==void 0?f:o.custom).isLimitReached()||n.notify(1,b)})}const Bo={[x.log]:_.info,[x.debug]:_.debug,[x.info]:_.info,[x.warn]:_.warn,[x.error]:_.error};function No(t,e){const n=no(t.forwardConsoleLogs).subscribe(r=>{var s;const i={rawLogsEvent:{date:z(),message:r.message,origin:D.CONSOLE,error:r.error&&et(r.error),status:Bo[r.api]},messageContext:(s=r.error)===null||s===void 0?void 0:s.context,domainContext:{handlingStack:r.handlingStack}};e.notify(0,i)});return{stop:()=>{n.unsubscribe()}}}function $o(t,e){const n=ti(t,t.forwardReports).subscribe(r=>{let s=r.message,i;const o=r.originalError.type==="deprecation"?_.warn:_.error;o===_.error?i=et(r):r.stack&&(s+=` Found in ${Ks(r.stack)}`),e.notify(0,{rawLogsEvent:{date:z(),message:s,origin:D.REPORT,error:i,status:o}})});return{stop:()=>{n.unsubscribe()}}}function zo(t,e){if(!t.forwardErrorsToLogs)return{stop:j};const n=Yi(t).subscribe(i=>{i.state==="complete"&&s("xhr",i)}),r=Hn().subscribe(i=>{i.state==="resolve"&&s("fetch",i)});function s(i,o){!Ss(o.url)&&(Ho(o)||Ln(o.status))&&("xhr"in o?Go(o.xhr,t,a):o.response?jo(o.response,t,a):o.error&&Vo(o.error,t,a));function a(c){const l={isAborted:o.isAborted,handlingStack:o.handlingStack};e.notify(0,{rawLogsEvent:{message:`${qo(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:_.error,origin:D.NETWORK},domainContext:l})}}return{stop:()=>{n.unsubscribe(),r.unsubscribe()}}}function Go(t,e,n){typeof t.response=="string"?n(Ot(t.response,e)):n(t.response)}function Vo(t,e,n){n(Ot(ee(B(t)),e))}function jo(t,e,n){const r=Ui(t);!r||!r.body?n():window.TextDecoder?Wo(r.body,e.requestErrorResponseLengthLimit,(s,i)=>{n(s?`Unable to retrieve response: ${s}`:i)}):r.text().then(v(s=>n(Ot(s,e))),v(s=>n(`Unable to retrieve response: ${s}`)))}function Ho(t){return t.status===0&&t.responseType!=="opaque"}function Ot(t,e){return t.length>e.requestErrorResponseLengthLimit?`${t.substring(0,e.requestErrorResponseLengthLimit)}...`:t}function qo(t){return t==="xhr"?"XHR":"Fetch"}function Wo(t,e,n){go(t,(r,s,i)=>{if(r)n(r);else{let o=new TextDecoder().decode(s);i&&(o+="..."),n(void 0,o)}},{bytesLimit:e,collectStreamBody:!0})}function Yo(t,e){if(!t.forwardErrorsToLogs)return{stop:j};const n=new R,{stop:r}=Js(n),s=n.subscribe(i=>{e.notify(0,{rawLogsEvent:{message:i.message,date:i.startClocks.timeStamp,error:et(i),origin:D.SOURCE,status:_.error},messageContext:i.context})});return{stop:()=>{r(),s.unsubscribe()}}}const Ko=qi;function Jo(t){function e(n,r,s,i,o){const a=le(r.getContext(),n.context);if(Qe(n.status,ke.console,r)&&Zo(n,a),Qe(n.status,ke.http,r)){const c={rawLogsEvent:{date:o||z(),message:n.message,status:n.status,origin:D.LOGGER},messageContext:a,savedCommonContext:i};s&&(c.domainContext={handlingStack:s}),t.notify(0,c)}}return{handleLog:e}}const Xo={[_.ok]:x.debug,[_.debug]:x.debug,[_.info]:x.info,[_.notice]:x.info,[_.warn]:x.warn,[_.error]:x.error,[_.critical]:x.error,[_.alert]:x.error,[_.emerg]:x.error};function Zo({status:t,message:e},n){Y[Xo[t]].call(P,e,n)}function Qo(t,e,n,r,s){const i=jn(t,{endpoint:t.logsEndpointBuilder,encoder:Xe()},t.replica&&{endpoint:t.replica.logsEndpointBuilder,encoder:Xe()},n,r,s.expireObservable);return e.subscribe(1,o=>{i.add(o)}),i}function ea(t){const e=Et();t.subscribe(1,n=>{e.send("log",n)})}function ta(t){return{get:e=>{const n=t.findTrackedSession(e);if(n)return{session_id:n.id}}}}function na(t){return e=>{t.notify(0,{rawLogsEvent:{message:e.message,date:e.startClocks.timeStamp,origin:D.AGENT,status:_.error}}),Fn("Error reported to customer",{"error.message":e.message})}}function ra(t,e,n,r,s){const i=fi("browser-logs-sdk",e);i.setContextProvider(()=>{var a,c,l,u,d,f;return{application:{id:(a=tt())===null||a===void 0?void 0:a.application_id},session:{id:(c=s.findTrackedSession())===null||c===void 0?void 0:c.id},view:{id:(u=(l=tt())===null||l===void 0?void 0:l.view)===null||u===void 0?void 0:u.id},action:{id:(f=(d=tt())===null||d===void 0?void 0:d.user_action)===null||f===void 0?void 0:f.id}}});const o=[];if(Ke()){const a=Et(),c=i.observable.subscribe(l=>a.send("internal_telemetry",l));o.push(()=>c.unsubscribe())}else{const a=jn(e,{endpoint:e.rumEndpointBuilder,encoder:Xe()},e.replica&&{endpoint:e.replica.rumEndpointBuilder,encoder:Xe()},n,r,s.expireObservable);o.push(()=>a.stop());const c=i.observable.subscribe(l=>a.add(l,mi(e)));o.push(()=>c.unsubscribe())}return pi(),gi(ko(t)),{telemetry:i,stop:()=>{o.forEach(a=>a())}}}function sa(t,e,n,r){const s=new Ko,i=[];s.subscribe(1,f=>Cn("logs",f));const o=na(s),a=Gi(e),c=e.sessionStoreStrategyType&&!Ke()&&!Wn()?Oo(e,r):Lo(e),{stop:l}=ra(t,e,o,a,c);i.push(()=>l()),zo(e,s),Yo(e,s),No(e,s),$o(e,s);const{handleLog:u}=Jo(s);if(Mo(c,e,s,n,o),Ke())ea(s);else{const{stop:f}=Qo(e,s,o,a,c);i.push(()=>f())}const d=ta(c);return{handleLog:u,getInternalContext:d.get,stop:()=>{i.forEach(f=>f())}}}const de=Ao(sa);ei(V(),"DD_LOGS",de);class fe{constructor(e){this.isLoggingOn=e,e&&de.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!1,sessionSampleRate:100})}static setMessagePort(e){this.messagePort=e}static getMessagePort(){return this.messagePort}setLoggingOn(e){this.isLoggingOn=e}setAttributes(e){for(const n in e)de.logger.setContextProperty(n,e[n])}info(e,n){this.isLoggingOn&&(de.logger.info(e,n),console.log("[Logger] Sending info: ",e))}error(e,n){this.isLoggingOn&&(de.logger.error(e,n),console.log("[Logger] Sending error: ",e))}warn(e,n){this.isLoggingOn&&(de.logger.warn(e,n),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){fe.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:e})}static info(e,n){fe.messagePort.postMessage({type:"LOG",actionType:"INFO",message:e,attributes:n})}static error(e,n){fe.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:e,attributes:n})}static warn(e,n){fe.messagePort.postMessage({type:"LOG",actionType:"WARN",message:e,attributes:n})}}class Zn{constructor(e,n,r){this.RUN_PIXEL_TICKERS=!0,this.pixelTickers=[],this.fetchGameParams=async()=>{try{L(this.options,"OTTPlayer")&&console.log("[OTTPlayer] GameId: ",this.options.gameId);let i;const o=`${this.options.cloudFrontURL}/${this.options.gameId}.json`;if(L(this.options,"OTTPlayer")&&console.log(`Fetching GameParams from ${o}`),i=await fetch(o),!i.ok)throw new Error(`Unable to fetch game params for ${this.options.gameId}. HTTP error. Status: ${i.status}`);const a=await i.json();if(a.hasOwnProperty("bucketName")&&a.hasOwnProperty("offsets"))i=a;else throw new Error(`Game params for ${this.options.gameId} not found in JSON`);if(this.logger.setAttributes({game_id:i.bucketName,customer_name:i.customerName,customer_id:i.customerId}),this.gameParams){const c=JSON.stringify(this.gameParams),l=JSON.stringify(i);c!==l&&this.logger.info("didChangeGameParams",{oldParams:this.gameParams,newParams:i})}else this.logger.info("didFetchGameInfo",this.gameParams);this.gameParams=i}catch(i){this.logger.error("[OTTPlayer] Error fetching game params",{error:i}),L(this.options,"Errors")&&console.error("[OTTPlayer] Error fetching game params:",i)}setTimeout(()=>this.fetchGameParams(),1e4)};const s="1.0.60";console.log("OTTPlayer v"+s),this.video=e,this.options={...r,cloudFrontURL:"https://d1ze2lfw5ong7.cloudfront.net",augmentation:{channelName:"nba"},LOG_TO_DATADOG:!0,ADAPTER_RUN_IN_WORKER:!1,DOWNLOADER_UPDATE_FREQUENCY:1e3,DOWNLOADER_ZIP_START_OFFSET:2,DOWNLOADER_ZIP_END_OFFSET:4,DOWNLOADER_ZIP_LENGTH_SECONDS:2,DECODER_UPDATE_FREQUENCY:30,DECODER_FRAME_BATCH_SIZE:3,DECODER_LEAD_TIME_MILLIS:180,PERFORMANCE_TRACKING_INTERVAL:1e3},this.logger=new fe(this.options.LOG_TO_DATADOG),this.logger.setAttributes({player_version:s,bb_session_id:crypto.randomUUID(),media_id:r.gameId}),this.logger.info("didGetConfiguration",{...r,fps:n}),Qn(this.options).then(()=>{window.BB.playerInstances.length>0&&window.BB.playerInstances.forEach(i=>{i.delete()}),window.BB.workerInstances.length>0&&window.BB.workerInstances.forEach(i=>{i.terminate()}),this.clocker=new or(this),this.adapter=new dr(this),this.RUN_PIXEL_TICKERS&&(this.pixelTickers=W.createInAllCorners(this.video)),this.fetchGameParams(),window.BB.playerInstances.push(this)})}onNewMetadata(e){this.adapter&&this.adapter.onNewMetadata(e)}onNewSegment(e){this.adapter&&this.adapter.onNewSegmentForMetadata(e)}toggle(e){this.options.enabled=e}setFps(e){this.fps=e}delete(){var n;(n=this.clocker)==null||n.delete(),this.clocker=void 0,this.adapter&&(this.adapter.delete(),this.adapter=void 0),W.deleteAll(this.pixelTickers),this.pixelTickers=[];const e=window.BB.playerInstances.indexOf(this);e>=0&&window.BB.playerInstances.splice(e,1)}}return window.BB={OTTPlayer:Zn,playerInstances:[],workerInstances:[]},Zn});
7
+ ${f}`),t.finish(m=>{h(jn(m))})}return{flushController:n,add:l,upsert:l,stop:s.unsubscribe}}function jn(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 qi({messagesLimit:t,bytesLimit:e,durationLimit:n,pageExitObservable:r,sessionExpireObservable:i}){const s=r.subscribe(h=>u(h.reason)),o=i.subscribe(()=>u("session_expire")),a=new D(()=>()=>{s.unsubscribe(),o.unsubscribe()});let c=0,l=0;function u(h){if(l===0)return;const m=l,g=c;l=0,c=0,p(),a.notify({reason:h,messagesCount:m,bytesCount:g})}let d;function f(){d===void 0&&(d=ve(()=>{u("duration_limit")},n))}function p(){Zt(d),d=void 0}return{flushObservable:a,get messagesCount(){return l},notifyBeforeAddMessage(h){c+h>=e&&u("bytes_limit"),l+=1,c+=h,f()},notifyAfterAddMessage(h=0){c+=h,l>=t?u("messages_limit"):c>=e&&u("bytes_limit")},notifyAfterRemoveMessage(h){c-=h,l-=1,l===0&&p()}}}function Hn(t,e,n,r,i,s,o=Hi){const a=l(t,e),c=n&&l(t,n);function l(u,{endpoint:d,encoder:f}){return o({encoder:f,request:Mi(d,u.batchBytesLimit,r),flushController:qi({messagesLimit:u.batchMessagesLimit,bytesLimit:u.batchBytesLimit,durationLimit:u.flushTimeout,pageExitObservable:i,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 Xe(){let t="",e=0;return{isAsync:!1,get isEmpty(){return!t},write(n,r){const i=ot(n);e+=i,t+=n,r&&r(i)},finish(n){n(this.finishSync())},finishSync(){const n={output:t,outputBytesCount:e,rawBytesCount:e,pendingData:""};return t="",e=0,n},estimateEncodedBytesCount(n){return n.length}}}class Wi{constructor(){this.callbacks={}}notify(e,n){const r=this.callbacks[e];r&&r.forEach(i=>i(n))}subscribe(e,n){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(n),{unsubscribe:()=>{this.callbacks[e]=this.callbacks[e].filter(r=>n!==r)}}}}function Yi(t,e,n){let r=0,i=!1;return{isLimitReached(){if(r===0&&ve(()=>{r=0},J),r+=1,r<=e||i)return i=!1,!1;if(r===e+1){i=!0;try{n({message:`Reached max number of ${t}s by minute: ${e}`,source:O.AGENT,startClocks:V()})}finally{i=!1}}return!0}}}let Ct;const kt=new WeakMap;function Ki(t){return Ct||(Ct=Ji(t)),Ct}function Ji(t){return new D(e=>{const{stop:n}=ne(XMLHttpRequest.prototype,"open",Xi),{stop:r}=ne(XMLHttpRequest.prototype,"send",s=>{Zi(s,t,e)},{computeHandlingStack:!0}),{stop:i}=ne(XMLHttpRequest.prototype,"abort",Qi);return()=>{n(),r(),i()}})}function Xi({target:t,parameters:[e,n]}){kt.set(t,{state:"open",method:String(e).toUpperCase(),url:gt(String(n))})}function Zi({target:t,handlingStack:e},n,r){const i=kt.get(t);if(!i)return;const s=i;s.state="start",s.startClocks=V(),s.isAborted=!1,s.xhr=t,s.handlingStack=e;let o=!1;const{stop:a}=ne(t,"onreadystatechange",()=>{t.readyState===XMLHttpRequest.DONE&&c()}),c=()=>{if(l(),a(),o)return;o=!0;const u=i;u.state="complete",u.duration=yr(s.startClocks.timeStamp,G()),u.status=t.status,r.notify(Sr(u))},{stop:l}=re(n,t,"loadend",c);r.notify(s)}function Qi({target:t}){const e=kt.get(t);e&&(e.isAborted=!0)}let Rt;function qn(){return Rt||(Rt=eo()),Rt}function eo(){return new D(t=>{if(!window.fetch)return;const{stop:e}=ne(window,"fetch",n=>to(n,t),{computeHandlingStack:!0});return e})}function to({parameters:t,onPostCall:e,handlingStack:n},r){const[i,s]=t;let o=s&&s.method;o===void 0&&i instanceof Request&&(o=i.method);const a=o!==void 0?String(o).toUpperCase():"GET",c=i instanceof Request?i.url:gt(String(i)),l=V(),u={state:"start",init:s,input:i,method:a,startClocks:l,url:c,handlingStack:n};r.notify(u),t[0]=u.input,t[1]=u.init,e(d=>no(r,d,u))}function no(t,e,n){const r=n;function i(s){r.state="resolve",Object.assign(r,s),t.notify(r)}e.then(S(s=>{i({response:s,responseType:s.type,status:s.status,isAborted:!1})}),S(s=>{var o,a;i({status:0,isAborted:((a=(o=r.init)===null||o===void 0?void 0:o.signal)===null||a===void 0?void 0:a.aborted)||s instanceof DOMException&&s.code===DOMException.ABORT_ERR,error:s})}))}let Dt={};function ro(t){const e=t.map(n=>(Dt[n]||(Dt[n]=so(n)),Dt[n]));return en(...e)}function so(t){return new D(e=>{const n=M[t];return M[t]=(...r)=>{n.apply(console,r);const i=He("console error");be(()=>{e.notify(io(r,t,i))})},()=>{M[t]=n}})}function io(t,e,n){const r=t.map(s=>oo(s)).join(" ");let i;if(e===E.error){const s=t.find(W);i={stack:s?te(N(s)):void 0,fingerprint:Sn(s),causes:s?Tn(s,"console"):void 0,startClocks:V(),message:r,source:O.CONSOLE,handling:"handled",handlingStack:n,context:wn(s)}}return{api:e,message:r,error:i,handlingStack:n}}function oo(t){return typeof t=="string"?$(t):W(t)?_n(N(t)):ee($(t),void 0,2)}function ao(t){const e=Rn(t)==="object";return e||C.error("Unsupported context:",t),e}function Ut(t,e,n){const r={...t};for(const[i,{required:s,type:o}]of Object.entries(e))o==="string"&&i in r&&(r[i]=String(r[i])),s&&!(i in t)&&C.warn(`The property ${i} of ${n} is required; context will not be sent to the intake.`);return r}function Ze(t="",{customerDataTracker:e,propertiesConfig:n={}}={}){let r={};const i=new D,s={getContext:()=>Dn(r),setContext:o=>{ao(o)?(r=$(Ut(o,n,t)),e==null||e.updateCustomerData(r)):s.clearContext(),i.notify()},setContextProperty:(o,a)=>{r=$(Ut({...r,[o]:a},n,t)),e==null||e.updateCustomerData(r),i.notify()},removeContextProperty:o=>{delete r[o],e==null||e.updateCustomerData(r),Ut(r,n,t),i.notify()},clearContext:()=>{r={},e==null||e.resetCustomerData(),i.notify()},changeObservable:i};return s}const co="_dd_c",lo=[];function At(t,e,n,r){const i=uo(n,r);lo.push(re(t,window,"storage",({key:l})=>{i===l&&o()})),e.changeObservable.subscribe(a);const s=ue(c(),e.getContext());_e(s)||e.setContext(s);function o(){e.setContext(c())}function a(){localStorage.setItem(i,JSON.stringify(e.getContext()))}function c(){const l=localStorage.getItem(i);return l?JSON.parse(l):{}}}function uo(t,e){return`${co}_${t}_${e}`}const fo=3*B,ho=16*B,po=200;function mo(t=2){const e=new Map;let n=!1;function r(i=0){if(n||t===0)return;const s=t===2?fo:ho;let o=i;e.forEach(a=>{o+=a.getBytesCount()}),o>s&&(go(s),n=!0)}return{createDetachedTracker:()=>{const i=Wn(()=>r(i.getBytesCount()));return i},getOrCreateTracker:i=>(e.has(i)||e.set(i,Wn(r)),e.get(i)),setCompressionStatus:i=>{t===0&&(t=i,r())},getCompressionStatus:()=>t,stop:()=>{e.forEach(i=>i.stop()),e.clear()}}}function Wn(t){let e=0;const{throttled:n,cancel:r}=tn(s=>{e=ot(ee(s)),t()},po),i=()=>{r(),e=0};return{updateCustomerData:s=>{_e(s)?i():n(s)},resetCustomerData:i,getBytesCount:()=>e,stop:()=>{r()}}}function go(t){C.warn(`Customer data exceeds the recommended ${t/B}KiB threshold. ${Ae} ${Ht}/#customer-data-exceeds-the-recommended-threshold-warning`)}function yo(t,e,n){const r=t.getReader(),i=[];let s=0;o();function o(){r.read().then(S(c=>{if(c.done){a();return}i.push(c.value),s+=c.value.length,s>n.bytesLimit?a():o()}),S(c=>e(c)))}function a(){r.cancel().catch(H);let c,l;{let u;if(i.length===1)u=i[0];else{u=new Uint8Array(s);let d=0;i.forEach(f=>{u.set(f,d),d+=f.length})}c=u.slice(0,n.bytesLimit),l=u.length>n.bytesLimit}e(void 0,c,l)}}const _o="datadog-synthetics-public-id",bo="datadog-synthetics-result-id",vo="datadog-synthetics-injects-rum";function Yn(){return!!(window._DATADOG_SYNTHETICS_INJECTS_RUM||X(vo))}function So(){const t=window._DATADOG_SYNTHETICS_PUBLIC_ID||X(_o);return typeof t=="string"?t:void 0}function wo(){const t=window._DATADOG_SYNTHETICS_RESULT_ID||X(bo);return typeof t=="string"?t:void 0}function Qe(t,e,n){const r=n.getHandler(),i=Array.isArray(r)?r:[r];return Kn[t]>=Kn[n.getLevel()]&&i.includes(e)}const b={ok:"ok",debug:"debug",info:"info",notice:"notice",warn:"warn",error:"error",critical:"critical",alert:"alert",emerg:"emerg"},Kn={[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 et(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 To=function(t,e,n,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,n,s):o(e,n))||s);return i>3&&s&&Object.defineProperty(e,n,s),s};const ke={console:"console",http:"http",silent:"silent"},xo=Object.keys(b);let L=class{constructor(e,n,r,i=ke.http,s=b.debug,o={}){this.handleLogStrategy=e,this.handlerType=i,this.level=s,this.contextManager=Ze("logger",{customerDataTracker:n}),this.contextManager.setContext(o),r&&this.contextManager.setContextProperty("logger",{name:r})}logImplementation(e,n,r=b.info,i,s){const o=$(n);let a;if(i!=null){const c=vn({stackTrace:W(i)?N(i):void 0,originalError:i,nonErrorPrefix:"Provided",source:O.LOGGER,handling:"handled",startClocks:V()});a=ue({error:et(c,{includeMessage:!0})},o)}else a=o;this.handleLogStrategy({message:$(e),context:a,status:r},this,s)}log(e,n,r=b.info,i){let s;Qe(r,ke.http,this)&&(s=He("log")),this.logImplementation(e,n,r,i,s)}setContext(e){this.contextManager.setContext(e)}getContext(){return this.contextManager.getContext()}setContextProperty(e,n){this.contextManager.setContextProperty(e,n)}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}};To([xr],L.prototype,"logImplementation",null),L.prototype.ok=z(b.ok),L.prototype.debug=z(b.debug),L.prototype.info=z(b.info),L.prototype.notice=z(b.notice),L.prototype.warn=z(b.warn),L.prototype.error=z(b.error),L.prototype.critical=z(b.critical),L.prototype.alert=z(b.alert),L.prototype.emerg=z(b.emerg);function z(t){return function(e,n,r){let i;Qe(t,ke.http,this)&&(i=He("log")),this.logImplementation(e,n,t,r,i)}}function Eo(t,e,n){return{view:{referrer:document.referrer,url:window.location.href},context:t.getContext(),user:e.getContext(),account:n.getContext()}}const Co=32*B;function ko(t){t.usePciIntake===!0&&t.site&&t.site!=="datadoghq.com"&&C.warn("PCI compliance for Logs is only available for Datadog organizations in the US1 site. Default intake will be used.");const e=xs(t),n=Jn(t.forwardConsoleLogs,Me(E),"Forward Console Logs"),r=Jn(t.forwardReports,Me(qe),"Forward Reports");if(!(!e||!n||!r))return t.forwardErrorsToLogs&&!n.includes(E.error)&&n.push(E.error),{forwardErrorsToLogs:t.forwardErrorsToLogs!==!1,forwardConsoleLogs:n,forwardReports:r,requestErrorResponseLengthLimit:Co,...e}}function Jn(t,e,n){if(t===void 0)return[];if(!(t==="all"||Array.isArray(t)&&t.every(r=>e.includes(r)))){C.error(`${n} should be "all" or an array with allowed values "${e.join('", "')}"`);return}return t==="all"?e:li(t)}function Ro(t){const e=Es(t);return{forward_errors_to_logs:t.forwardErrorsToLogs,forward_console_logs:t.forwardConsoleLogs,forward_reports:t.forwardReports,use_pci_intake:t.usePciIntake,...e}}function Do(t,e,n){const r=An();let i,s;const o=e.observable.subscribe(a);function a(){if(!s||!i||!e.isGranted())return;o.unsubscribe();const c=n(i,s);r.drain(c)}return{init(c){if(!c){C.error("Missing configuration");return}if(Cs(c.enableExperimentalFeatures),Ke()&&(c=Uo(c)),i=c,s){xn("DD_LOGS",c);return}const l=ko(c);l&&(s=l,qn().subscribe(H),e.tryToInit(l.trackingConsent),a())},get initConfiguration(){return i},getInternalContext:H,handleLog(c,l,u,d=t(),f=G()){r.add(p=>p.handleLog(c,l,u,d,f))}}}function Uo(t){return{...t,clientToken:"empty"}}const Ft="logs";function Ao(t){const e=mo(),n=Ze("global context",{customerDataTracker:e.getOrCreateTracker(2)}),r=Ze("user",{customerDataTracker:e.getOrCreateTracker(1),propertiesConfig:{id:{type:"string"},name:{type:"string"},email:{type:"string"}}}),i=Ze("account",{customerDataTracker:e.getOrCreateTracker(1),propertiesConfig:{id:{type:"string",required:!0},name:{type:"string"}}}),s=ss();function o(){return Eo(n,r,i)}let a=Do(o,s,(u,d)=>{u.storeContextsAcrossPages&&(At(d,n,Ft,2),At(d,r,Ft,1),At(d,i,Ft,4));const f=t(u,d,o,s);return a=Fo(u,f),f});const c={},l=new L((...u)=>a.handleLog(...u),e.createDetachedTracker());return ei({logger:l,init:S(u=>a.init(u)),setTrackingConsent:S(u=>{s.update(u),_i({feature:"set-tracking-consent",tracking_consent:u})}),getGlobalContext:S(()=>n.getContext()),setGlobalContext:S(u=>n.setContext(u)),setGlobalContextProperty:S((u,d)=>n.setContextProperty(u,d)),removeGlobalContextProperty:S(u=>n.removeContextProperty(u)),clearGlobalContext:S(()=>n.clearContext()),createLogger:S((u,d={})=>(c[u]=new L((...f)=>a.handleLog(...f),e.createDetachedTracker(),$(u),d.handler,d.level,$(d.context)),c[u])),getLogger:S(u=>c[u]),getInitConfiguration:S(()=>Dn(a.initConfiguration)),getInternalContext:S(u=>a.getInternalContext(u)),setUser:S(r.setContext),getUser:S(r.getContext),setUserProperty:S(r.setContextProperty),removeUserProperty:S(r.removeContextProperty),clearUser:S(r.clearContext),setAccount:S(i.setContext),getAccount:S(i.getContext),setAccountProperty:S(i.setContextProperty),removeAccountProperty:S(i.removeContextProperty),clearAccount:S(i.clearContext)})}function Fo(t,e){return{init:n=>{xn("DD_LOGS",n)},initConfiguration:t,...e}}const Oo="logs";function Lo(t,e){const n=Ci(t,Oo,r=>Po(t,r),e);return{findTrackedSession:(r,i={returnInactive:!1})=>{const s=n.findSession(r,i);return s&&s.trackingType==="1"?{id:s.id,anonymousId:s.anonymousId}:void 0},expireObservable:n.expireObservable}}function Io(t){const n=Xn(t)==="1"?{}:void 0;return{findTrackedSession:()=>n,expireObservable:new D}}function Xn(t){return Fe(t.sessionSampleRate)?"1":"0"}function Po(t,e){const n=Mo(e)?e:Xn(t);return{trackingType:n,isTracked:n==="1"}}function Mo(t){return t==="0"||t==="1"}let Zn=!1;function tt(t){const e=window;if(Yn()){const r=n(e.DD_RUM_SYNTHETICS);return!r&&!Zn&&(Zn=!0,On("Logs sent before RUM is injected by the synthetics worker",{testId:So(),resultId:wo()})),r}return n(e.DD_RUM);function n(r){if(r&&r.getInternalContext)return r.getInternalContext(t)}}function Bo(t,e,n,r,i){const s=xo.concat(["custom"]),o={};s.forEach(a=>{o[a]=Yi(a,e.eventRateLimiterThreshold,i)}),n.subscribe(0,({rawLogsEvent:a,messageContext:c=void 0,savedCommonContext:l=void 0,domainContext:u})=>{var d,f;const p=br(a.date),h=t.findTrackedSession(p);if(!t.findTrackedSession(p,{returnInactive:!0}))return;const g=l||r();let w;!_e(g.account)&&g.account.id&&(w=g.account),h&&h.anonymousId&&!g.user.anonymous_id&&(g.user.anonymous_id=h.anonymousId);const v=ue({service:e.service,session_id:h?h.id:void 0,session:h?{id:h.id}:void 0,usr:_e(g.user)?void 0:g.user,account:w,view:g.view},g.context,tt(p),a,c);((d=e.beforeSend)===null||d===void 0?void 0:d.call(e,v,u))===!1||v.origin!==O.AGENT&&((f=o[v.status])!==null&&f!==void 0?f:o.custom).isLimitReached()||n.notify(1,v)})}const No={[E.log]:b.info,[E.debug]:b.debug,[E.info]:b.info,[E.warn]:b.warn,[E.error]:b.error};function $o(t,e){const n=ro(t.forwardConsoleLogs).subscribe(r=>{var i;const s={rawLogsEvent:{date:G(),message:r.message,origin:O.CONSOLE,error:r.error&&et(r.error),status:No[r.api]},messageContext:(i=r.error)===null||i===void 0?void 0:i.context,domainContext:{handlingStack:r.handlingStack}};e.notify(0,s)});return{stop:()=>{n.unsubscribe()}}}function zo(t,e){const n=ni(t,t.forwardReports).subscribe(r=>{let i=r.message,s;const o=r.originalError.type==="deprecation"?b.warn:b.error;o===b.error?s=et(r):r.stack&&(i+=` Found in ${Js(r.stack)}`),e.notify(0,{rawLogsEvent:{date:G(),message:i,origin:O.REPORT,error:s,status:o}})});return{stop:()=>{n.unsubscribe()}}}function Go(t,e){if(!t.forwardErrorsToLogs)return{stop:H};const n=Ki(t).subscribe(s=>{s.state==="complete"&&i("xhr",s)}),r=qn().subscribe(s=>{s.state==="resolve"&&i("fetch",s)});function i(s,o){!ws(o.url)&&(qo(o)||In(o.status))&&("xhr"in o?Vo(o.xhr,t,a):o.response?Ho(o.response,t,a):o.error&&jo(o.error,t,a));function a(c){const l={isAborted:o.isAborted,handlingStack:o.handlingStack};e.notify(0,{rawLogsEvent:{message:`${Wo(s)} 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:b.error,origin:O.NETWORK},domainContext:l})}}return{stop:()=>{n.unsubscribe(),r.unsubscribe()}}}function Vo(t,e,n){typeof t.response=="string"?n(Ot(t.response,e)):n(t.response)}function jo(t,e,n){n(Ot(te(N(t)),e))}function Ho(t,e,n){const r=Ui(t);!r||!r.body?n():window.TextDecoder?Yo(r.body,e.requestErrorResponseLengthLimit,(i,s)=>{n(i?`Unable to retrieve response: ${i}`:s)}):r.text().then(S(i=>n(Ot(i,e))),S(i=>n(`Unable to retrieve response: ${i}`)))}function qo(t){return t.status===0&&t.responseType!=="opaque"}function Ot(t,e){return t.length>e.requestErrorResponseLengthLimit?`${t.substring(0,e.requestErrorResponseLengthLimit)}...`:t}function Wo(t){return t==="xhr"?"XHR":"Fetch"}function Yo(t,e,n){yo(t,(r,i,s)=>{if(r)n(r);else{let o=new TextDecoder().decode(i);s&&(o+="..."),n(void 0,o)}},{bytesLimit:e,collectStreamBody:!0})}function Ko(t,e){if(!t.forwardErrorsToLogs)return{stop:H};const n=new D,{stop:r}=Xs(n),i=n.subscribe(s=>{e.notify(0,{rawLogsEvent:{message:s.message,date:s.startClocks.timeStamp,error:et(s),origin:O.SOURCE,status:b.error},messageContext:s.context})});return{stop:()=>{r(),i.unsubscribe()}}}const Jo=Wi;function Xo(t){function e(n,r,i,s,o){const a=ue(r.getContext(),n.context);if(Qe(n.status,ke.console,r)&&Qo(n,a),Qe(n.status,ke.http,r)){const c={rawLogsEvent:{date:o||G(),message:n.message,status:n.status,origin:O.LOGGER},messageContext:a,savedCommonContext:s};i&&(c.domainContext={handlingStack:i}),t.notify(0,c)}}return{handleLog:e}}const Zo={[b.ok]:E.debug,[b.debug]:E.debug,[b.info]:E.info,[b.notice]:E.info,[b.warn]:E.warn,[b.error]:E.error,[b.critical]:E.error,[b.alert]:E.error,[b.emerg]:E.error};function Qo({status:t,message:e},n){K[Zo[t]].call(M,e,n)}function ea(t,e,n,r,i){const s=Hn(t,{endpoint:t.logsEndpointBuilder,encoder:Xe()},t.replica&&{endpoint:t.replica.logsEndpointBuilder,encoder:Xe()},n,r,i.expireObservable);return e.subscribe(1,o=>{s.add(o)}),s}function ta(t){const e=Et();t.subscribe(1,n=>{e.send("log",n)})}function na(t){return{get:e=>{const n=t.findTrackedSession(e);if(n)return{session_id:n.id}}}}function ra(t){return e=>{t.notify(0,{rawLogsEvent:{message:e.message,date:e.startClocks.timeStamp,origin:O.AGENT,status:b.error}}),On("Error reported to customer",{"error.message":e.message})}}function sa(t,e,n,r,i){const s=hi("browser-logs-sdk",e);s.setContextProvider(()=>{var a,c,l,u,d,f;return{application:{id:(a=tt())===null||a===void 0?void 0:a.application_id},session:{id:(c=i.findTrackedSession())===null||c===void 0?void 0:c.id},view:{id:(u=(l=tt())===null||l===void 0?void 0:l.view)===null||u===void 0?void 0:u.id},action:{id:(f=(d=tt())===null||d===void 0?void 0:d.user_action)===null||f===void 0?void 0:f.id}}});const o=[];if(Ke()){const a=Et(),c=s.observable.subscribe(l=>a.send("internal_telemetry",l));o.push(()=>c.unsubscribe())}else{const a=Hn(e,{endpoint:e.rumEndpointBuilder,encoder:Xe()},e.replica&&{endpoint:e.replica.rumEndpointBuilder,encoder:Xe()},n,r,i.expireObservable);o.push(()=>a.stop());const c=s.observable.subscribe(l=>a.add(l,gi(e)));o.push(()=>c.unsubscribe())}return mi(),yi(Ro(t)),{telemetry:s,stop:()=>{o.forEach(a=>a())}}}function ia(t,e,n,r){const i=new Jo,s=[];i.subscribe(1,f=>kn("logs",f));const o=ra(i),a=Vi(e),c=e.sessionStoreStrategyType&&!Ke()&&!Yn()?Lo(e,r):Io(e),{stop:l}=sa(t,e,o,a,c);s.push(()=>l()),Go(e,i),Ko(e,i),$o(e,i),zo(e,i);const{handleLog:u}=Xo(i);if(Bo(c,e,i,n,o),Ke())ta(i);else{const{stop:f}=ea(e,i,o,a,c);s.push(()=>f())}const d=na(c);return{handleLog:u,getInternalContext:d.get,stop:()=>{s.forEach(f=>f())}}}const fe=Ao(ia);ti(j(),"DD_LOGS",fe);const y=class y{constructor(e){this.isLoggingOn=e.LOG_TO_DATADOG,this.isLoggingOn&&fe.init({clientToken:"pub86577b481b35700b8fcfe3b4993f007a",service:"BBMediaKitDemoWeb",site:"us3.datadoghq.com",forwardErrorsToLogs:!1,sessionSampleRate:100}),y.tracking.dev=`${e.platform}_${e.browserName}`,y.beatHandle||(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}setAttributes(e){y.processAttributes(e);for(const n in e)fe.logger.setContextProperty(n,e[n])}info(e,n){n&&y.processAttributes(n),this.isLoggingOn&&(fe.logger.info(e,n),console.log("[Logger] Sending info: ",e))}error(e,n){n&&y.processAttributes(n),this.isLoggingOn&&(fe.logger.error(e,n),y.tracking.err_time=Date.now().toFixed(0),y.tracking.err_desc=e,console.log("[Logger] Sending error: ",e))}warn(e,n){n&&y.processAttributes(n),this.isLoggingOn&&(fe.logger.warn(e,n),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){y.messagePort.postMessage({type:"LOG",actionType:"SET_ATTRIBUTES",attributes:e})}static info(e,n){y.messagePort.postMessage({type:"LOG",actionType:"INFO",message:e,attributes:n})}static error(e,n){y.messagePort.postMessage({type:"LOG",actionType:"ERROR",message:e,attributes:n})}static warn(e,n){y.messagePort.postMessage({type:"LOG",actionType:"WARN",message:e,attributes:n})}static processAttributes(e){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,console.log("[Logger] Setting bb_session_id:",y.tracking.sid)),e.last_timecode&&(y.tracking.tc=e.last_timecode,y.lastTimecodeMillis=F.fromStr(e.last_timecode).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,y.lastZipMillis=F.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(([n,r])=>r!==0&&r!=="").map(([n,r])=>`${encodeURIComponent(n)}=${encodeURIComponent(String(r))}`).join("&")}};y.tracking={start:Date.now().toFixed(0),dev:"",sdk:"",mac:"",gid:"",sid:"",off:"",zip:"",aug_time:"",err_time:"",err_desc:"",tc:"",png:"",asset:"",cache:"",buc:""},y.lastTimecodeMillis=0,y.lastZipMillis=0,y.flushTracking=()=>{const e=Date.now().toFixed(0);y.tracking.now=e;const r=`https://dwu3k7rrxk5s3.cloudfront.net/metrics/1.gif?${y.objectToQuery(y.tracking)}`;console.log("[Logger] Flushing tracking data:",r),fetch(r,{method:"GET",mode:"no-cors",keepalive:!0}).catch(()=>{})};let Lt=y;class Qn{constructor(e,n,r){this.RUN_PIXEL_TICKERS=!0,this.pixelTickers=[],this.fetchGameParams=async()=>{try{I(this.options,"OTTPlayer")&&console.log("[OTTPlayer] GameId: ",this.options.gameId);let s;const o=`${this.options.cloudFrontURL}/${this.options.gameId}.json`;if(I(this.options,"OTTPlayer")&&console.log(`Fetching GameParams from ${o}`),s=await fetch(o),!s.ok)throw new Error(`Unable to fetch game params for ${this.options.gameId}. HTTP error. Status: ${s.status}`);const a=await s.json();if(a.hasOwnProperty("bucketName")&&a.hasOwnProperty("offsets"))s=a;else throw new Error(`Game params for ${this.options.gameId} not found in JSON`);if(this.logger.setAttributes({game_id:s.bucketName,customer_name:s.customerName,customer_id:s.customerId}),this.gameParams){const c=JSON.stringify(this.gameParams),l=JSON.stringify(s);c!==l&&this.logger.info("didChangeGameParams",{oldParams:this.gameParams,newParams:s})}else this.logger.info("didFetchGameInfo",this.gameParams);this.gameParams=s}catch(s){this.logger.error("[OTTPlayer] Error fetching game params",{error:s}),I(this.options,"Errors")&&console.error("[OTTPlayer] Error fetching game params:",s)}setTimeout(()=>this.fetchGameParams(),1e4)};const i="OTTPlayer_v1.0.63";console.log(i),this.video=e,this.options={...r,cloudFrontURL:"https://d1ze2lfw5ong7.cloudfront.net",platform:P.getCurrentPlatform(),browserName:P.getBrowserName(),augmentation:{channelName:"nba"},LOG_TO_DATADOG:!0,ADAPTER_RUN_IN_WORKER:!1,DOWNLOADER_UPDATE_FREQUENCY:1e3,DOWNLOADER_ZIP_START_OFFSET:2,DOWNLOADER_ZIP_END_OFFSET:4,DOWNLOADER_ZIP_LENGTH_SECONDS:2,DECODER_UPDATE_FREQUENCY:30,DECODER_FRAME_BATCH_SIZE:3,DECODER_LEAD_TIME_MILLIS:180,PERFORMANCE_TRACKING_INTERVAL:1e3},this.options.browserName==="Firefox"&&(this.options.DECODER_LEAD_TIME_MILLIS=300),this.logger=new Lt(this.options),this.logger.setAttributes({player_version:i,bb_session_id:crypto.randomUUID(),media_id:r.gameId}),this.logger.info("didGetConfiguration",{...r,fps:n}),er(this.options).then(()=>{window.BB.playerInstances.length>0&&window.BB.playerInstances.forEach(s=>{s.delete()}),window.BB.workerInstances.length>0&&window.BB.workerInstances.forEach(s=>{s.terminate()}),this.clocker=new ar(this),this.adapter=new fr(this),this.RUN_PIXEL_TICKERS&&(this.pixelTickers=Y.createInAllCorners(this.video)),this.fetchGameParams(),window.BB.playerInstances.push(this)})}onNewMetadata(e){this.adapter&&this.adapter.onNewMetadata(e)}onNewSegment(e){this.adapter&&this.adapter.onNewSegmentForMetadata(e)}toggle(e){this.options.enabled=e}setFps(e){this.fps=e}setMediaInfo(e){e.fps&&this.setFps(e.fps),e.bitrate&&(this.bitrate=e.bitrate)}delete(){var n;(n=this.clocker)==null||n.delete(),this.clocker=void 0,this.adapter&&(this.adapter.delete(),this.adapter=void 0),Y.deleteAll(this.pixelTickers),this.pixelTickers=[];const e=window.BB.playerInstances.indexOf(this);e>=0&&window.BB.playerInstances.splice(e,1)}}return window.BB={OTTPlayer:Qn,playerInstances:[],workerInstances:[]},Qn});