var f$=Object.defineProperty;var S1=t=>{throw TypeError(t)};var p$=(t,e,n)=>e in t?f$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Cm=(t,e,n)=>p$(t,typeof e!="symbol"?e+"":e,n),t_=(t,e,n)=>e.has(t)||S1("Cannot "+n);var ue=(t,e,n)=>(t_(t,e,"read from private field"),n?n.call(t):e.get(t)),gt=(t,e,n)=>e.has(t)?S1("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),et=(t,e,n,r)=>(t_(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),Wt=(t,e,n)=>(t_(t,e,"access private method"),n);var Lm=(t,e,n,r)=>({set _(i){et(t,e,i,n)},get _(){return ue(t,e,r)}});function m$(t,e){for(var n=0;n<e.length;n++){const r=e[n];if(typeof r!="string"&&!Array.isArray(r)){for(const i in r)if(i!=="default"&&!(i in t)){const s=Object.getOwnPropertyDescriptor(r,i);s&&Object.defineProperty(t,i,s.get?s:{enumerable:!0,get:()=>r[i]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const a of s.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();var E1=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function k0(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var DD={exports:{}},I0={};/**
 * @license React
 * react-jsx-runtime.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var g$=Symbol.for("react.transitional.element"),y$=Symbol.for("react.fragment");function OD(t,e,n){var r=null;if(n!==void 0&&(r=""+n),e.key!==void 0&&(r=""+e.key),"key"in e){n={};for(var i in e)i!=="key"&&(n[i]=e[i])}else n=e;return e=n.ref,{$$typeof:g$,type:t,key:r,ref:e!==void 0?e:null,props:n}}I0.Fragment=y$;I0.jsx=OD;I0.jsxs=OD;DD.exports=I0;var y=DD.exports,ND={exports:{}},P0={},MD={exports:{}},BD={};/**
 * @license React
 * scheduler.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */(function(t){function e(X,oe){var Q=X.length;X.push(oe);e:for(;0<Q;){var G=Q-1>>>1,H=X[G];if(0<i(H,oe))X[G]=oe,X[Q]=H,Q=G;else break e}}function n(X){return X.length===0?null:X[0]}function r(X){if(X.length===0)return null;var oe=X[0],Q=X.pop();if(Q!==oe){X[0]=Q;e:for(var G=0,H=X.length,Y=H>>>1;G<Y;){var ie=2*(G+1)-1,Ce=X[ie],Le=ie+1,ke=X[Le];if(0>i(Ce,Q))Le<H&&0>i(ke,Ce)?(X[G]=ke,X[Le]=Q,G=Le):(X[G]=Ce,X[ie]=Q,G=ie);else if(Le<H&&0>i(ke,Q))X[G]=ke,X[Le]=Q,G=Le;else break e}}return oe}function i(X,oe){var Q=X.sortIndex-oe.sortIndex;return Q!==0?Q:X.id-oe.id}if(t.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var s=performance;t.unstable_now=function(){return s.now()}}else{var a=Date,o=a.now();t.unstable_now=function(){return a.now()-o}}var l=[],c=[],u=1,d=null,h=3,f=!1,p=!1,m=!1,g=!1,b=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,S=typeof setImmediate<"u"?setImmediate:null;function E(X){for(var oe=n(c);oe!==null;){if(oe.callback===null)r(c);else if(oe.startTime<=X)r(c),oe.sortIndex=oe.expirationTime,e(l,oe);else break;oe=n(c)}}function L(X){if(m=!1,E(X),!p)if(n(l)!==null)p=!0,U||(U=!0,z());else{var oe=n(c);oe!==null&&re(L,oe.startTime-X)}}var U=!1,O=-1,k=5,I=-1;function R(){return g?!0:!(t.unstable_now()-I<k)}function M(){if(g=!1,U){var X=t.unstable_now();I=X;var oe=!0;try{e:{p=!1,m&&(m=!1,v(O),O=-1),f=!0;var Q=h;try{t:{for(E(X),d=n(l);d!==null&&!(d.expirationTime>X&&R());){var G=d.callback;if(typeof G=="function"){d.callback=null,h=d.priorityLevel;var H=G(d.expirationTime<=X);if(X=t.unstable_now(),typeof H=="function"){d.callback=H,E(X),oe=!0;break t}d===n(l)&&r(l),E(X)}else r(l);d=n(l)}if(d!==null)oe=!0;else{var Y=n(c);Y!==null&&re(L,Y.startTime-X),oe=!1}}break e}finally{d=null,h=Q,f=!1}oe=void 0}}finally{oe?z():U=!1}}}var z;if(typeof S=="function")z=function(){S(M)};else if(typeof MessageChannel<"u"){var Z=new MessageChannel,W=Z.port2;Z.port1.onmessage=M,z=function(){W.postMessage(null)}}else z=function(){b(M,0)};function re(X,oe){O=b(function(){X(t.unstable_now())},oe)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(X){X.callback=null},t.unstable_forceFrameRate=function(X){0>X||125<X?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):k=0<X?Math.floor(1e3/X):5},t.unstable_getCurrentPriorityLevel=function(){return h},t.unstable_next=function(X){switch(h){case 1:case 2:case 3:var oe=3;break;default:oe=h}var Q=h;h=oe;try{return X()}finally{h=Q}},t.unstable_requestPaint=function(){g=!0},t.unstable_runWithPriority=function(X,oe){switch(X){case 1:case 2:case 3:case 4:case 5:break;default:X=3}var Q=h;h=X;try{return oe()}finally{h=Q}},t.unstable_scheduleCallback=function(X,oe,Q){var G=t.unstable_now();switch(typeof Q=="object"&&Q!==null?(Q=Q.delay,Q=typeof Q=="number"&&0<Q?G+Q:G):Q=G,X){case 1:var H=-1;break;case 2:H=250;break;case 5:H=1073741823;break;case 4:H=1e4;break;default:H=5e3}return H=Q+H,X={id:u++,callback:oe,priorityLevel:X,startTime:Q,expirationTime:H,sortIndex:-1},Q>G?(X.sortIndex=Q,e(c,X),n(l)===null&&X===n(c)&&(m?(v(O),O=-1):m=!0,re(L,Q-G))):(X.sortIndex=H,e(l,X),p||f||(p=!0,U||(U=!0,z()))),X},t.unstable_shouldYield=R,t.unstable_wrapCallback=function(X){var oe=h;return function(){var Q=h;h=oe;try{return X.apply(this,arguments)}finally{h=Q}}}})(BD);MD.exports=BD;var v$=MD.exports,UD={exports:{}},Nt={};/**
 * @license React
 * react.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var iw=Symbol.for("react.transitional.element"),_$=Symbol.for("react.portal"),b$=Symbol.for("react.fragment"),x$=Symbol.for("react.strict_mode"),S$=Symbol.for("react.profiler"),E$=Symbol.for("react.consumer"),w$=Symbol.for("react.context"),T$=Symbol.for("react.forward_ref"),A$=Symbol.for("react.suspense"),R$=Symbol.for("react.memo"),jD=Symbol.for("react.lazy"),w1=Symbol.iterator;function C$(t){return t===null||typeof t!="object"?null:(t=w1&&t[w1]||t["@@iterator"],typeof t=="function"?t:null)}var FD={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},$D=Object.assign,VD={};function rh(t,e,n){this.props=t,this.context=e,this.refs=VD,this.updater=n||FD}rh.prototype.isReactComponent={};rh.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};rh.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function GD(){}GD.prototype=rh.prototype;function sw(t,e,n){this.props=t,this.context=e,this.refs=VD,this.updater=n||FD}var aw=sw.prototype=new GD;aw.constructor=sw;$D(aw,rh.prototype);aw.isPureReactComponent=!0;var T1=Array.isArray,In={H:null,A:null,T:null,S:null,V:null},HD=Object.prototype.hasOwnProperty;function ow(t,e,n,r,i,s){return n=s.ref,{$$typeof:iw,type:t,key:e,ref:n!==void 0?n:null,props:s}}function L$(t,e){return ow(t.type,e,void 0,void 0,void 0,t.props)}function lw(t){return typeof t=="object"&&t!==null&&t.$$typeof===iw}function k$(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(n){return e[n]})}var A1=/\/+/g;function n_(t,e){return typeof t=="object"&&t!==null&&t.key!=null?k$(""+t.key):e.toString(36)}function R1(){}function I$(t){switch(t.status){case"fulfilled":return t.value;case"rejected":throw t.reason;default:switch(typeof t.status=="string"?t.then(R1,R1):(t.status="pending",t.then(function(e){t.status==="pending"&&(t.status="fulfilled",t.value=e)},function(e){t.status==="pending"&&(t.status="rejected",t.reason=e)})),t.status){case"fulfilled":return t.value;case"rejected":throw t.reason}}throw t}function Cu(t,e,n,r,i){var s=typeof t;(s==="undefined"||s==="boolean")&&(t=null);var a=!1;if(t===null)a=!0;else switch(s){case"bigint":case"string":case"number":a=!0;break;case"object":switch(t.$$typeof){case iw:case _$:a=!0;break;case jD:return a=t._init,Cu(a(t._payload),e,n,r,i)}}if(a)return i=i(t),a=r===""?"."+n_(t,0):r,T1(i)?(n="",a!=null&&(n=a.replace(A1,"$&/")+"/"),Cu(i,e,n,"",function(c){return c})):i!=null&&(lw(i)&&(i=L$(i,n+(i.key==null||t&&t.key===i.key?"":(""+i.key).replace(A1,"$&/")+"/")+a)),e.push(i)),1;a=0;var o=r===""?".":r+":";if(T1(t))for(var l=0;l<t.length;l++)r=t[l],s=o+n_(r,l),a+=Cu(r,e,n,s,i);else if(l=C$(t),typeof l=="function")for(t=l.call(t),l=0;!(r=t.next()).done;)r=r.value,s=o+n_(r,l++),a+=Cu(r,e,n,s,i);else if(s==="object"){if(typeof t.then=="function")return Cu(I$(t),e,n,r,i);throw e=String(t),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.")}return a}function km(t,e,n){if(t==null)return t;var r=[],i=0;return Cu(t,r,"","",function(s){return e.call(n,s,i++)}),r}function P$(t){if(t._status===-1){var e=t._result;e=e(),e.then(function(n){(t._status===0||t._status===-1)&&(t._status=1,t._result=n)},function(n){(t._status===0||t._status===-1)&&(t._status=2,t._result=n)}),t._status===-1&&(t._status=0,t._result=e)}if(t._status===1)return t._result.default;throw t._result}var C1=typeof reportError=="function"?reportError:function(t){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var e=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof t=="object"&&t!==null&&typeof t.message=="string"?String(t.message):String(t),error:t});if(!window.dispatchEvent(e))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",t);return}console.error(t)};function D$(){}Nt.Children={map:km,forEach:function(t,e,n){km(t,function(){e.apply(this,arguments)},n)},count:function(t){var e=0;return km(t,function(){e++}),e},toArray:function(t){return km(t,function(e){return e})||[]},only:function(t){if(!lw(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};Nt.Component=rh;Nt.Fragment=b$;Nt.Profiler=S$;Nt.PureComponent=sw;Nt.StrictMode=x$;Nt.Suspense=A$;Nt.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=In;Nt.__COMPILER_RUNTIME={__proto__:null,c:function(t){return In.H.useMemoCache(t)}};Nt.cache=function(t){return function(){return t.apply(null,arguments)}};Nt.cloneElement=function(t,e,n){if(t==null)throw Error("The argument must be a React element, but you passed "+t+".");var r=$D({},t.props),i=t.key,s=void 0;if(e!=null)for(a in e.ref!==void 0&&(s=void 0),e.key!==void 0&&(i=""+e.key),e)!HD.call(e,a)||a==="key"||a==="__self"||a==="__source"||a==="ref"&&e.ref===void 0||(r[a]=e[a]);var a=arguments.length-2;if(a===1)r.children=n;else if(1<a){for(var o=Array(a),l=0;l<a;l++)o[l]=arguments[l+2];r.children=o}return ow(t.type,i,void 0,void 0,s,r)};Nt.createContext=function(t){return t={$$typeof:w$,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null},t.Provider=t,t.Consumer={$$typeof:E$,_context:t},t};Nt.createElement=function(t,e,n){var r,i={},s=null;if(e!=null)for(r in e.key!==void 0&&(s=""+e.key),e)HD.call(e,r)&&r!=="key"&&r!=="__self"&&r!=="__source"&&(i[r]=e[r]);var a=arguments.length-2;if(a===1)i.children=n;else if(1<a){for(var o=Array(a),l=0;l<a;l++)o[l]=arguments[l+2];i.children=o}if(t&&t.defaultProps)for(r in a=t.defaultProps,a)i[r]===void 0&&(i[r]=a[r]);return ow(t,s,void 0,void 0,null,i)};Nt.createRef=function(){return{current:null}};Nt.forwardRef=function(t){return{$$typeof:T$,render:t}};Nt.isValidElement=lw;Nt.lazy=function(t){return{$$typeof:jD,_payload:{_status:-1,_result:t},_init:P$}};Nt.memo=function(t,e){return{$$typeof:R$,type:t,compare:e===void 0?null:e}};Nt.startTransition=function(t){var e=In.T,n={};In.T=n;try{var r=t(),i=In.S;i!==null&&i(n,r),typeof r=="object"&&r!==null&&typeof r.then=="function"&&r.then(D$,C1)}catch(s){C1(s)}finally{In.T=e}};Nt.unstable_useCacheRefresh=function(){return In.H.useCacheRefresh()};Nt.use=function(t){return In.H.use(t)};Nt.useActionState=function(t,e,n){return In.H.useActionState(t,e,n)};Nt.useCallback=function(t,e){return In.H.useCallback(t,e)};Nt.useContext=function(t){return In.H.useContext(t)};Nt.useDebugValue=function(){};Nt.useDeferredValue=function(t,e){return In.H.useDeferredValue(t,e)};Nt.useEffect=function(t,e,n){var r=In.H;if(typeof n=="function")throw Error("useEffect CRUD overload is not enabled in this build of React.");return r.useEffect(t,e)};Nt.useId=function(){return In.H.useId()};Nt.useImperativeHandle=function(t,e,n){return In.H.useImperativeHandle(t,e,n)};Nt.useInsertionEffect=function(t,e){return In.H.useInsertionEffect(t,e)};Nt.useLayoutEffect=function(t,e){return In.H.useLayoutEffect(t,e)};Nt.useMemo=function(t,e){return In.H.useMemo(t,e)};Nt.useOptimistic=function(t,e){return In.H.useOptimistic(t,e)};Nt.useReducer=function(t,e,n){return In.H.useReducer(t,e,n)};Nt.useRef=function(t){return In.H.useRef(t)};Nt.useState=function(t){return In.H.useState(t)};Nt.useSyncExternalStore=function(t,e,n){return In.H.useSyncExternalStore(t,e,n)};Nt.useTransition=function(){return In.H.useTransition()};Nt.version="19.1.0";UD.exports=Nt;var D=UD.exports;const Fe=k0(D),cw=m$({__proto__:null,default:Fe},[D]);var KD={exports:{}},ai={};/**
 * @license React
 * react-dom.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var O$=D;function zD(t){var e="https://react.dev/errors/"+t;if(1<arguments.length){e+="?args[]="+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)e+="&args[]="+encodeURIComponent(arguments[n])}return"Minified React error #"+t+"; visit "+e+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function Eo(){}var ti={d:{f:Eo,r:function(){throw Error(zD(522))},D:Eo,C:Eo,L:Eo,m:Eo,X:Eo,S:Eo,M:Eo},p:0,findDOMNode:null},N$=Symbol.for("react.portal");function M$(t,e,n){var r=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:N$,key:r==null?null:""+r,children:t,containerInfo:e,implementation:n}}var af=O$.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function D0(t,e){if(t==="font")return"";if(typeof e=="string")return e==="use-credentials"?e:""}ai.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=ti;ai.createPortal=function(t,e){var n=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)throw Error(zD(299));return M$(t,e,null,n)};ai.flushSync=function(t){var e=af.T,n=ti.p;try{if(af.T=null,ti.p=2,t)return t()}finally{af.T=e,ti.p=n,ti.d.f()}};ai.preconnect=function(t,e){typeof t=="string"&&(e?(e=e.crossOrigin,e=typeof e=="string"?e==="use-credentials"?e:"":void 0):e=null,ti.d.C(t,e))};ai.prefetchDNS=function(t){typeof t=="string"&&ti.d.D(t)};ai.preinit=function(t,e){if(typeof t=="string"&&e&&typeof e.as=="string"){var n=e.as,r=D0(n,e.crossOrigin),i=typeof e.integrity=="string"?e.integrity:void 0,s=typeof e.fetchPriority=="string"?e.fetchPriority:void 0;n==="style"?ti.d.S(t,typeof e.precedence=="string"?e.precedence:void 0,{crossOrigin:r,integrity:i,fetchPriority:s}):n==="script"&&ti.d.X(t,{crossOrigin:r,integrity:i,fetchPriority:s,nonce:typeof e.nonce=="string"?e.nonce:void 0})}};ai.preinitModule=function(t,e){if(typeof t=="string")if(typeof e=="object"&&e!==null){if(e.as==null||e.as==="script"){var n=D0(e.as,e.crossOrigin);ti.d.M(t,{crossOrigin:n,integrity:typeof e.integrity=="string"?e.integrity:void 0,nonce:typeof e.nonce=="string"?e.nonce:void 0})}}else e==null&&ti.d.M(t)};ai.preload=function(t,e){if(typeof t=="string"&&typeof e=="object"&&e!==null&&typeof e.as=="string"){var n=e.as,r=D0(n,e.crossOrigin);ti.d.L(t,n,{crossOrigin:r,integrity:typeof e.integrity=="string"?e.integrity:void 0,nonce:typeof e.nonce=="string"?e.nonce:void 0,type:typeof e.type=="string"?e.type:void 0,fetchPriority:typeof e.fetchPriority=="string"?e.fetchPriority:void 0,referrerPolicy:typeof e.referrerPolicy=="string"?e.referrerPolicy:void 0,imageSrcSet:typeof e.imageSrcSet=="string"?e.imageSrcSet:void 0,imageSizes:typeof e.imageSizes=="string"?e.imageSizes:void 0,media:typeof e.media=="string"?e.media:void 0})}};ai.preloadModule=function(t,e){if(typeof t=="string")if(e){var n=D0(e.as,e.crossOrigin);ti.d.m(t,{as:typeof e.as=="string"&&e.as!=="script"?e.as:void 0,crossOrigin:n,integrity:typeof e.integrity=="string"?e.integrity:void 0})}else ti.d.m(t)};ai.requestFormReset=function(t){ti.d.r(t)};ai.unstable_batchedUpdates=function(t,e){return t(e)};ai.useFormState=function(t,e,n){return af.H.useFormState(t,e,n)};ai.useFormStatus=function(){return af.H.useHostTransitionStatus()};ai.version="19.1.0";function qD(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(qD)}catch(t){console.error(t)}}qD(),KD.exports=ai;var Np=KD.exports;const WD=k0(Np);/**
 * @license React
 * react-dom-client.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var gr=v$,YD=D,B$=Np;function Ue(t){var e="https://react.dev/errors/"+t;if(1<arguments.length){e+="?args[]="+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)e+="&args[]="+encodeURIComponent(arguments[n])}return"Minified React error #"+t+"; visit "+e+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function XD(t){return!(!t||t.nodeType!==1&&t.nodeType!==9&&t.nodeType!==11)}function Mp(t){var e=t,n=t;if(t.alternate)for(;e.return;)e=e.return;else{t=e;do e=t,e.flags&4098&&(n=e.return),t=e.return;while(t)}return e.tag===3?n:null}function QD(t){if(t.tag===13){var e=t.memoizedState;if(e===null&&(t=t.alternate,t!==null&&(e=t.memoizedState)),e!==null)return e.dehydrated}return null}function L1(t){if(Mp(t)!==t)throw Error(Ue(188))}function U$(t){var e=t.alternate;if(!e){if(e=Mp(t),e===null)throw Error(Ue(188));return e!==t?null:t}for(var n=t,r=e;;){var i=n.return;if(i===null)break;var s=i.alternate;if(s===null){if(r=i.return,r!==null){n=r;continue}break}if(i.child===s.child){for(s=i.child;s;){if(s===n)return L1(i),t;if(s===r)return L1(i),e;s=s.sibling}throw Error(Ue(188))}if(n.return!==r.return)n=i,r=s;else{for(var a=!1,o=i.child;o;){if(o===n){a=!0,n=i,r=s;break}if(o===r){a=!0,r=i,n=s;break}o=o.sibling}if(!a){for(o=s.child;o;){if(o===n){a=!0,n=s,r=i;break}if(o===r){a=!0,r=s,n=i;break}o=o.sibling}if(!a)throw Error(Ue(189))}}if(n.alternate!==r)throw Error(Ue(190))}if(n.tag!==3)throw Error(Ue(188));return n.stateNode.current===n?t:e}function JD(t){var e=t.tag;if(e===5||e===26||e===27||e===6)return t;for(t=t.child;t!==null;){if(e=JD(t),e!==null)return e;t=t.sibling}return null}var Rn=Object.assign,j$=Symbol.for("react.element"),Im=Symbol.for("react.transitional.element"),Wh=Symbol.for("react.portal"),ju=Symbol.for("react.fragment"),ZD=Symbol.for("react.strict_mode"),cx=Symbol.for("react.profiler"),F$=Symbol.for("react.provider"),eO=Symbol.for("react.consumer"),Ya=Symbol.for("react.context"),uw=Symbol.for("react.forward_ref"),ux=Symbol.for("react.suspense"),dx=Symbol.for("react.suspense_list"),dw=Symbol.for("react.memo"),Oo=Symbol.for("react.lazy"),hx=Symbol.for("react.activity"),$$=Symbol.for("react.memo_cache_sentinel"),k1=Symbol.iterator;function Ih(t){return t===null||typeof t!="object"?null:(t=k1&&t[k1]||t["@@iterator"],typeof t=="function"?t:null)}var V$=Symbol.for("react.client.reference");function fx(t){if(t==null)return null;if(typeof t=="function")return t.$$typeof===V$?null:t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case ju:return"Fragment";case cx:return"Profiler";case ZD:return"StrictMode";case ux:return"Suspense";case dx:return"SuspenseList";case hx:return"Activity"}if(typeof t=="object")switch(t.$$typeof){case Wh:return"Portal";case Ya:return(t.displayName||"Context")+".Provider";case eO:return(t._context.displayName||"Context")+".Consumer";case uw:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case dw:return e=t.displayName||null,e!==null?e:fx(t.type)||"Memo";case Oo:e=t._payload,t=t._init;try{return fx(t(e))}catch{}}return null}var Yh=Array.isArray,xt=YD.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,en=B$.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,bc={pending:!1,data:null,method:null,action:null},px=[],Fu=-1;function va(t){return{current:t}}function Tr(t){0>Fu||(t.current=px[Fu],px[Fu]=null,Fu--)}function Pn(t,e){Fu++,px[Fu]=t.current,t.current=e}var la=va(null),$f=va(null),al=va(null),my=va(null);function gy(t,e){switch(Pn(al,e),Pn($f,t),Pn(la,null),e.nodeType){case 9:case 11:t=(t=e.documentElement)&&(t=t.namespaceURI)?NR(t):0;break;default:if(t=e.tagName,e=e.namespaceURI)e=NR(e),t=yM(e,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}Tr(la),Pn(la,t)}function Nd(){Tr(la),Tr($f),Tr(al)}function mx(t){t.memoizedState!==null&&Pn(my,t);var e=la.current,n=yM(e,t.type);e!==n&&(Pn($f,t),Pn(la,n))}function yy(t){$f.current===t&&(Tr(la),Tr($f)),my.current===t&&(Tr(my),Qf._currentValue=bc)}var gx=Object.prototype.hasOwnProperty,hw=gr.unstable_scheduleCallback,r_=gr.unstable_cancelCallback,G$=gr.unstable_shouldYield,H$=gr.unstable_requestPaint,ca=gr.unstable_now,K$=gr.unstable_getCurrentPriorityLevel,tO=gr.unstable_ImmediatePriority,nO=gr.unstable_UserBlockingPriority,vy=gr.unstable_NormalPriority,z$=gr.unstable_LowPriority,rO=gr.unstable_IdlePriority,q$=gr.log,W$=gr.unstable_setDisableYieldValue,Bp=null,ji=null;function el(t){if(typeof q$=="function"&&W$(t),ji&&typeof ji.setStrictMode=="function")try{ji.setStrictMode(Bp,t)}catch{}}var Fi=Math.clz32?Math.clz32:Q$,Y$=Math.log,X$=Math.LN2;function Q$(t){return t>>>=0,t===0?32:31-(Y$(t)/X$|0)|0}var Pm=256,Dm=4194304;function Yl(t){var e=t&42;if(e!==0)return e;switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t&4194048;case 4194304:case 8388608:case 16777216:case 33554432:return t&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return t}}function O0(t,e,n){var r=t.pendingLanes;if(r===0)return 0;var i=0,s=t.suspendedLanes,a=t.pingedLanes;t=t.warmLanes;var o=r&134217727;return o!==0?(r=o&~s,r!==0?i=Yl(r):(a&=o,a!==0?i=Yl(a):n||(n=o&~t,n!==0&&(i=Yl(n))))):(o=r&~s,o!==0?i=Yl(o):a!==0?i=Yl(a):n||(n=r&~t,n!==0&&(i=Yl(n)))),i===0?0:e!==0&&e!==i&&!(e&s)&&(s=i&-i,n=e&-e,s>=n||s===32&&(n&4194048)!==0)?e:i}function Up(t,e){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&e)===0}function J$(t,e){switch(t){case 1:case 2:case 4:case 8:case 64:return e+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function iO(){var t=Pm;return Pm<<=1,!(Pm&4194048)&&(Pm=256),t}function sO(){var t=Dm;return Dm<<=1,!(Dm&62914560)&&(Dm=4194304),t}function i_(t){for(var e=[],n=0;31>n;n++)e.push(t);return e}function jp(t,e){t.pendingLanes|=e,e!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function Z$(t,e,n,r,i,s){var a=t.pendingLanes;t.pendingLanes=n,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=n,t.entangledLanes&=n,t.errorRecoveryDisabledLanes&=n,t.shellSuspendCounter=0;var o=t.entanglements,l=t.expirationTimes,c=t.hiddenUpdates;for(n=a&~n;0<n;){var u=31-Fi(n),d=1<<u;o[u]=0,l[u]=-1;var h=c[u];if(h!==null)for(c[u]=null,u=0;u<h.length;u++){var f=h[u];f!==null&&(f.lane&=-536870913)}n&=~d}r!==0&&aO(t,r,0),s!==0&&i===0&&t.tag!==0&&(t.suspendedLanes|=s&~(a&~e))}function aO(t,e,n){t.pendingLanes|=e,t.suspendedLanes&=~e;var r=31-Fi(e);t.entangledLanes|=e,t.entanglements[r]=t.entanglements[r]|1073741824|n&4194090}function oO(t,e){var n=t.entangledLanes|=e;for(t=t.entanglements;n;){var r=31-Fi(n),i=1<<r;i&e|t[r]&e&&(t[r]|=e),n&=~i}}function fw(t){switch(t){case 2:t=1;break;case 8:t=4;break;case 32:t=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:t=128;break;case 268435456:t=134217728;break;default:t=0}return t}function pw(t){return t&=-t,2<t?8<t?t&134217727?32:268435456:8:2}function lO(){var t=en.p;return t!==0?t:(t=window.event,t===void 0?32:RM(t.type))}function e5(t,e){var n=en.p;try{return en.p=t,e()}finally{en.p=n}}var kl=Math.random().toString(36).slice(2),Hr="__reactFiber$"+kl,xi="__reactProps$"+kl,ih="__reactContainer$"+kl,yx="__reactEvents$"+kl,t5="__reactListeners$"+kl,n5="__reactHandles$"+kl,I1="__reactResources$"+kl,Fp="__reactMarker$"+kl;function mw(t){delete t[Hr],delete t[xi],delete t[yx],delete t[t5],delete t[n5]}function $u(t){var e=t[Hr];if(e)return e;for(var n=t.parentNode;n;){if(e=n[ih]||n[Hr]){if(n=e.alternate,e.child!==null||n!==null&&n.child!==null)for(t=UR(t);t!==null;){if(n=t[Hr])return n;t=UR(t)}return e}t=n,n=t.parentNode}return null}function sh(t){if(t=t[Hr]||t[ih]){var e=t.tag;if(e===5||e===6||e===13||e===26||e===27||e===3)return t}return null}function Xh(t){var e=t.tag;if(e===5||e===26||e===27||e===6)return t.stateNode;throw Error(Ue(33))}function sd(t){var e=t[I1];return e||(e=t[I1]={hoistableStyles:new Map,hoistableScripts:new Map}),e}function Er(t){t[Fp]=!0}var cO=new Set,uO={};function Kc(t,e){Md(t,e),Md(t+"Capture",e)}function Md(t,e){for(uO[t]=e,t=0;t<e.length;t++)cO.add(e[t])}var r5=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"),P1={},D1={};function i5(t){return gx.call(D1,t)?!0:gx.call(P1,t)?!1:r5.test(t)?D1[t]=!0:(P1[t]=!0,!1)}function Dg(t,e,n){if(i5(e))if(n===null)t.removeAttribute(e);else{switch(typeof n){case"undefined":case"function":case"symbol":t.removeAttribute(e);return;case"boolean":var r=e.toLowerCase().slice(0,5);if(r!=="data-"&&r!=="aria-"){t.removeAttribute(e);return}}t.setAttribute(e,""+n)}}function Om(t,e,n){if(n===null)t.removeAttribute(e);else{switch(typeof n){case"undefined":case"function":case"symbol":case"boolean":t.removeAttribute(e);return}t.setAttribute(e,""+n)}}function La(t,e,n,r){if(r===null)t.removeAttribute(n);else{switch(typeof r){case"undefined":case"function":case"symbol":case"boolean":t.removeAttribute(n);return}t.setAttributeNS(e,n,""+r)}}var s_,O1;function Lu(t){if(s_===void 0)try{throw Error()}catch(n){var e=n.stack.trim().match(/\n( *(at )?)/);s_=e&&e[1]||"",O1=-1<n.stack.indexOf(`
    at`)?" (<anonymous>)":-1<n.stack.indexOf("@")?"@unknown:0:0":""}return`
`+s_+t+O1}var a_=!1;function o_(t,e){if(!t||a_)return"";a_=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var r={DetermineComponentFrameRoot:function(){try{if(e){var d=function(){throw Error()};if(Object.defineProperty(d.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(d,[])}catch(f){var h=f}Reflect.construct(t,[],d)}else{try{d.call()}catch(f){h=f}t.call(d.prototype)}}else{try{throw Error()}catch(f){h=f}(d=t())&&typeof d.catch=="function"&&d.catch(function(){})}}catch(f){if(f&&h&&typeof f.stack=="string")return[f.stack,h.stack]}return[null,null]}};r.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var i=Object.getOwnPropertyDescriptor(r.DetermineComponentFrameRoot,"name");i&&i.configurable&&Object.defineProperty(r.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var s=r.DetermineComponentFrameRoot(),a=s[0],o=s[1];if(a&&o){var l=a.split(`
`),c=o.split(`
`);for(i=r=0;r<l.length&&!l[r].includes("DetermineComponentFrameRoot");)r++;for(;i<c.length&&!c[i].includes("DetermineComponentFrameRoot");)i++;if(r===l.length||i===c.length)for(r=l.length-1,i=c.length-1;1<=r&&0<=i&&l[r]!==c[i];)i--;for(;1<=r&&0<=i;r--,i--)if(l[r]!==c[i]){if(r!==1||i!==1)do if(r--,i--,0>i||l[r]!==c[i]){var u=`
`+l[r].replace(" at new "," at ");return t.displayName&&u.includes("<anonymous>")&&(u=u.replace("<anonymous>",t.displayName)),u}while(1<=r&&0<=i);break}}}finally{a_=!1,Error.prepareStackTrace=n}return(n=t?t.displayName||t.name:"")?Lu(n):""}function s5(t){switch(t.tag){case 26:case 27:case 5:return Lu(t.type);case 16:return Lu("Lazy");case 13:return Lu("Suspense");case 19:return Lu("SuspenseList");case 0:case 15:return o_(t.type,!1);case 11:return o_(t.type.render,!1);case 1:return o_(t.type,!0);case 31:return Lu("Activity");default:return""}}function N1(t){try{var e="";do e+=s5(t),t=t.return;while(t);return e}catch(n){return`
Error generating stack: `+n.message+`
`+n.stack}}function as(t){switch(typeof t){case"bigint":case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function dO(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function a5(t){var e=dO(t)?"checked":"value",n=Object.getOwnPropertyDescriptor(t.constructor.prototype,e),r=""+t[e];if(!t.hasOwnProperty(e)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var i=n.get,s=n.set;return Object.defineProperty(t,e,{configurable:!0,get:function(){return i.call(this)},set:function(a){r=""+a,s.call(this,a)}}),Object.defineProperty(t,e,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(a){r=""+a},stopTracking:function(){t._valueTracker=null,delete t[e]}}}}function _y(t){t._valueTracker||(t._valueTracker=a5(t))}function hO(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var n=e.getValue(),r="";return t&&(r=dO(t)?t.checked?"true":"false":t.value),t=r,t!==n?(e.setValue(t),!0):!1}function by(t){if(t=t||(typeof document<"u"?document:void 0),typeof t>"u")return null;try{return t.activeElement||t.body}catch{return t.body}}var o5=/[\n"\\]/g;function cs(t){return t.replace(o5,function(e){return"\\"+e.charCodeAt(0).toString(16)+" "})}function vx(t,e,n,r,i,s,a,o){t.name="",a!=null&&typeof a!="function"&&typeof a!="symbol"&&typeof a!="boolean"?t.type=a:t.removeAttribute("type"),e!=null?a==="number"?(e===0&&t.value===""||t.value!=e)&&(t.value=""+as(e)):t.value!==""+as(e)&&(t.value=""+as(e)):a!=="submit"&&a!=="reset"||t.removeAttribute("value"),e!=null?_x(t,a,as(e)):n!=null?_x(t,a,as(n)):r!=null&&t.removeAttribute("value"),i==null&&s!=null&&(t.defaultChecked=!!s),i!=null&&(t.checked=i&&typeof i!="function"&&typeof i!="symbol"),o!=null&&typeof o!="function"&&typeof o!="symbol"&&typeof o!="boolean"?t.name=""+as(o):t.removeAttribute("name")}function fO(t,e,n,r,i,s,a,o){if(s!=null&&typeof s!="function"&&typeof s!="symbol"&&typeof s!="boolean"&&(t.type=s),e!=null||n!=null){if(!(s!=="submit"&&s!=="reset"||e!=null))return;n=n!=null?""+as(n):"",e=e!=null?""+as(e):n,o||e===t.value||(t.value=e),t.defaultValue=e}r=r??i,r=typeof r!="function"&&typeof r!="symbol"&&!!r,t.checked=o?t.checked:!!r,t.defaultChecked=!!r,a!=null&&typeof a!="function"&&typeof a!="symbol"&&typeof a!="boolean"&&(t.name=a)}function _x(t,e,n){e==="number"&&by(t.ownerDocument)===t||t.defaultValue===""+n||(t.defaultValue=""+n)}function ad(t,e,n,r){if(t=t.options,e){e={};for(var i=0;i<n.length;i++)e["$"+n[i]]=!0;for(n=0;n<t.length;n++)i=e.hasOwnProperty("$"+t[n].value),t[n].selected!==i&&(t[n].selected=i),i&&r&&(t[n].defaultSelected=!0)}else{for(n=""+as(n),e=null,i=0;i<t.length;i++){if(t[i].value===n){t[i].selected=!0,r&&(t[i].defaultSelected=!0);return}e!==null||t[i].disabled||(e=t[i])}e!==null&&(e.selected=!0)}}function pO(t,e,n){if(e!=null&&(e=""+as(e),e!==t.value&&(t.value=e),n==null)){t.defaultValue!==e&&(t.defaultValue=e);return}t.defaultValue=n!=null?""+as(n):""}function mO(t,e,n,r){if(e==null){if(r!=null){if(n!=null)throw Error(Ue(92));if(Yh(r)){if(1<r.length)throw Error(Ue(93));r=r[0]}n=r}n==null&&(n=""),e=n}n=as(e),t.defaultValue=n,r=t.textContent,r===n&&r!==""&&r!==null&&(t.value=r)}function Bd(t,e){if(e){var n=t.firstChild;if(n&&n===t.lastChild&&n.nodeType===3){n.nodeValue=e;return}}t.textContent=e}var l5=new Set("animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(" "));function M1(t,e,n){var r=e.indexOf("--")===0;n==null||typeof n=="boolean"||n===""?r?t.setProperty(e,""):e==="float"?t.cssFloat="":t[e]="":r?t.setProperty(e,n):typeof n!="number"||n===0||l5.has(e)?e==="float"?t.cssFloat=n:t[e]=(""+n).trim():t[e]=n+"px"}function gO(t,e,n){if(e!=null&&typeof e!="object")throw Error(Ue(62));if(t=t.style,n!=null){for(var r in n)!n.hasOwnProperty(r)||e!=null&&e.hasOwnProperty(r)||(r.indexOf("--")===0?t.setProperty(r,""):r==="float"?t.cssFloat="":t[r]="");for(var i in e)r=e[i],e.hasOwnProperty(i)&&n[i]!==r&&M1(t,i,r)}else for(var s in e)e.hasOwnProperty(s)&&M1(t,s,e[s])}function gw(t){if(t.indexOf("-")===-1)return!1;switch(t){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var c5=new Map([["acceptCharset","accept-charset"],["htmlFor","for"],["httpEquiv","http-equiv"],["crossOrigin","crossorigin"],["accentHeight","accent-height"],["alignmentBaseline","alignment-baseline"],["arabicForm","arabic-form"],["baselineShift","baseline-shift"],["capHeight","cap-height"],["clipPath","clip-path"],["clipRule","clip-rule"],["colorInterpolation","color-interpolation"],["colorInterpolationFilters","color-interpolation-filters"],["colorProfile","color-profile"],["colorRendering","color-rendering"],["dominantBaseline","dominant-baseline"],["enableBackground","enable-background"],["fillOpacity","fill-opacity"],["fillRule","fill-rule"],["floodColor","flood-color"],["floodOpacity","flood-opacity"],["fontFamily","font-family"],["fontSize","font-size"],["fontSizeAdjust","font-size-adjust"],["fontStretch","font-stretch"],["fontStyle","font-style"],["fontVariant","font-variant"],["fontWeight","font-weight"],["glyphName","glyph-name"],["glyphOrientationHorizontal","glyph-orientation-horizontal"],["glyphOrientationVertical","glyph-orientation-vertical"],["horizAdvX","horiz-adv-x"],["horizOriginX","horiz-origin-x"],["imageRendering","image-rendering"],["letterSpacing","letter-spacing"],["lightingColor","lighting-color"],["markerEnd","marker-end"],["markerMid","marker-mid"],["markerStart","marker-start"],["overlinePosition","overline-position"],["overlineThickness","overline-thickness"],["paintOrder","paint-order"],["panose-1","panose-1"],["pointerEvents","pointer-events"],["renderingIntent","rendering-intent"],["shapeRendering","shape-rendering"],["stopColor","stop-color"],["stopOpacity","stop-opacity"],["strikethroughPosition","strikethrough-position"],["strikethroughThickness","strikethrough-thickness"],["strokeDasharray","stroke-dasharray"],["strokeDashoffset","stroke-dashoffset"],["strokeLinecap","stroke-linecap"],["strokeLinejoin","stroke-linejoin"],["strokeMiterlimit","stroke-miterlimit"],["strokeOpacity","stroke-opacity"],["strokeWidth","stroke-width"],["textAnchor","text-anchor"],["textDecoration","text-decoration"],["textRendering","text-rendering"],["transformOrigin","transform-origin"],["underlinePosition","underline-position"],["underlineThickness","underline-thickness"],["unicodeBidi","unicode-bidi"],["unicodeRange","unicode-range"],["unitsPerEm","units-per-em"],["vAlphabetic","v-alphabetic"],["vHanging","v-hanging"],["vIdeographic","v-ideographic"],["vMathematical","v-mathematical"],["vectorEffect","vector-effect"],["vertAdvY","vert-adv-y"],["vertOriginX","vert-origin-x"],["vertOriginY","vert-origin-y"],["wordSpacing","word-spacing"],["writingMode","writing-mode"],["xmlnsXlink","xmlns:xlink"],["xHeight","x-height"]]),u5=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;function Og(t){return u5.test(""+t)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":t}var bx=null;function yw(t){return t=t.target||t.srcElement||window,t.correspondingUseElement&&(t=t.correspondingUseElement),t.nodeType===3?t.parentNode:t}var Vu=null,od=null;function B1(t){var e=sh(t);if(e&&(t=e.stateNode)){var n=t[xi]||null;e:switch(t=e.stateNode,e.type){case"input":if(vx(t,n.value,n.defaultValue,n.defaultValue,n.checked,n.defaultChecked,n.type,n.name),e=n.name,n.type==="radio"&&e!=null){for(n=t;n.parentNode;)n=n.parentNode;for(n=n.querySelectorAll('input[name="'+cs(""+e)+'"][type="radio"]'),e=0;e<n.length;e++){var r=n[e];if(r!==t&&r.form===t.form){var i=r[xi]||null;if(!i)throw Error(Ue(90));vx(r,i.value,i.defaultValue,i.defaultValue,i.checked,i.defaultChecked,i.type,i.name)}}for(e=0;e<n.length;e++)r=n[e],r.form===t.form&&hO(r)}break e;case"textarea":pO(t,n.value,n.defaultValue);break e;case"select":e=n.value,e!=null&&ad(t,!!n.multiple,e,!1)}}}var l_=!1;function yO(t,e,n){if(l_)return t(e,n);l_=!0;try{var r=t(e);return r}finally{if(l_=!1,(Vu!==null||od!==null)&&(H0(),Vu&&(e=Vu,t=od,od=Vu=null,B1(e),t)))for(e=0;e<t.length;e++)B1(t[e])}}function Vf(t,e){var n=t.stateNode;if(n===null)return null;var r=n[xi]||null;if(r===null)return null;n=r[e];e:switch(e){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(r=!r.disabled)||(t=t.type,r=!(t==="button"||t==="input"||t==="select"||t==="textarea")),t=!r;break e;default:t=!1}if(t)return null;if(n&&typeof n!="function")throw Error(Ue(231,e,typeof n));return n}var io=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),xx=!1;if(io)try{var Ph={};Object.defineProperty(Ph,"passive",{get:function(){xx=!0}}),window.addEventListener("test",Ph,Ph),window.removeEventListener("test",Ph,Ph)}catch{xx=!1}var tl=null,vw=null,Ng=null;function vO(){if(Ng)return Ng;var t,e=vw,n=e.length,r,i="value"in tl?tl.value:tl.textContent,s=i.length;for(t=0;t<n&&e[t]===i[t];t++);var a=n-t;for(r=1;r<=a&&e[n-r]===i[s-r];r++);return Ng=i.slice(t,1<r?1-r:void 0)}function Mg(t){var e=t.keyCode;return"charCode"in t?(t=t.charCode,t===0&&e===13&&(t=13)):t=e,t===10&&(t=13),32<=t||t===13?t:0}function Nm(){return!0}function U1(){return!1}function Si(t){function e(n,r,i,s,a){this._reactName=n,this._targetInst=i,this.type=r,this.nativeEvent=s,this.target=a,this.currentTarget=null;for(var o in t)t.hasOwnProperty(o)&&(n=t[o],this[o]=n?n(s):s[o]);return this.isDefaultPrevented=(s.defaultPrevented!=null?s.defaultPrevented:s.returnValue===!1)?Nm:U1,this.isPropagationStopped=U1,this}return Rn(e.prototype,{preventDefault:function(){this.defaultPrevented=!0;var n=this.nativeEvent;n&&(n.preventDefault?n.preventDefault():typeof n.returnValue!="unknown"&&(n.returnValue=!1),this.isDefaultPrevented=Nm)},stopPropagation:function(){var n=this.nativeEvent;n&&(n.stopPropagation?n.stopPropagation():typeof n.cancelBubble!="unknown"&&(n.cancelBubble=!0),this.isPropagationStopped=Nm)},persist:function(){},isPersistent:Nm}),e}var zc={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(t){return t.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},N0=Si(zc),$p=Rn({},zc,{view:0,detail:0}),d5=Si($p),c_,u_,Dh,M0=Rn({},$p,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:_w,button:0,buttons:0,relatedTarget:function(t){return t.relatedTarget===void 0?t.fromElement===t.srcElement?t.toElement:t.fromElement:t.relatedTarget},movementX:function(t){return"movementX"in t?t.movementX:(t!==Dh&&(Dh&&t.type==="mousemove"?(c_=t.screenX-Dh.screenX,u_=t.screenY-Dh.screenY):u_=c_=0,Dh=t),c_)},movementY:function(t){return"movementY"in t?t.movementY:u_}}),j1=Si(M0),h5=Rn({},M0,{dataTransfer:0}),f5=Si(h5),p5=Rn({},$p,{relatedTarget:0}),d_=Si(p5),m5=Rn({},zc,{animationName:0,elapsedTime:0,pseudoElement:0}),g5=Si(m5),y5=Rn({},zc,{clipboardData:function(t){return"clipboardData"in t?t.clipboardData:window.clipboardData}}),v5=Si(y5),_5=Rn({},zc,{data:0}),F1=Si(_5),b5={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},x5={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},S5={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function E5(t){var e=this.nativeEvent;return e.getModifierState?e.getModifierState(t):(t=S5[t])?!!e[t]:!1}function _w(){return E5}var w5=Rn({},$p,{key:function(t){if(t.key){var e=b5[t.key]||t.key;if(e!=="Unidentified")return e}return t.type==="keypress"?(t=Mg(t),t===13?"Enter":String.fromCharCode(t)):t.type==="keydown"||t.type==="keyup"?x5[t.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:_w,charCode:function(t){return t.type==="keypress"?Mg(t):0},keyCode:function(t){return t.type==="keydown"||t.type==="keyup"?t.keyCode:0},which:function(t){return t.type==="keypress"?Mg(t):t.type==="keydown"||t.type==="keyup"?t.keyCode:0}}),T5=Si(w5),A5=Rn({},M0,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),$1=Si(A5),R5=Rn({},$p,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:_w}),C5=Si(R5),L5=Rn({},zc,{propertyName:0,elapsedTime:0,pseudoElement:0}),k5=Si(L5),I5=Rn({},M0,{deltaX:function(t){return"deltaX"in t?t.deltaX:"wheelDeltaX"in t?-t.wheelDeltaX:0},deltaY:function(t){return"deltaY"in t?t.deltaY:"wheelDeltaY"in t?-t.wheelDeltaY:"wheelDelta"in t?-t.wheelDelta:0},deltaZ:0,deltaMode:0}),P5=Si(I5),D5=Rn({},zc,{newState:0,oldState:0}),O5=Si(D5),N5=[9,13,27,32],bw=io&&"CompositionEvent"in window,of=null;io&&"documentMode"in document&&(of=document.documentMode);var M5=io&&"TextEvent"in window&&!of,_O=io&&(!bw||of&&8<of&&11>=of),V1=" ",G1=!1;function bO(t,e){switch(t){case"keyup":return N5.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function xO(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var Gu=!1;function B5(t,e){switch(t){case"compositionend":return xO(e);case"keypress":return e.which!==32?null:(G1=!0,V1);case"textInput":return t=e.data,t===V1&&G1?null:t;default:return null}}function U5(t,e){if(Gu)return t==="compositionend"||!bw&&bO(t,e)?(t=vO(),Ng=vw=tl=null,Gu=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1<e.char.length)return e.char;if(e.which)return String.fromCharCode(e.which)}return null;case"compositionend":return _O&&e.locale!=="ko"?null:e.data;default:return null}}var j5={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function H1(t){var e=t&&t.nodeName&&t.nodeName.toLowerCase();return e==="input"?!!j5[t.type]:e==="textarea"}function SO(t,e,n,r){Vu?od?od.push(r):od=[r]:Vu=r,e=Uy(e,"onChange"),0<e.length&&(n=new N0("onChange","change",null,n,r),t.push({event:n,listeners:e}))}var lf=null,Gf=null;function F5(t){pM(t,0)}function B0(t){var e=Xh(t);if(hO(e))return t}function K1(t,e){if(t==="change")return e}var EO=!1;if(io){var h_;if(io){var f_="oninput"in document;if(!f_){var z1=document.createElement("div");z1.setAttribute("oninput","return;"),f_=typeof z1.oninput=="function"}h_=f_}else h_=!1;EO=h_&&(!document.documentMode||9<document.documentMode)}function q1(){lf&&(lf.detachEvent("onpropertychange",wO),Gf=lf=null)}function wO(t){if(t.propertyName==="value"&&B0(Gf)){var e=[];SO(e,Gf,t,yw(t)),yO(F5,e)}}function $5(t,e,n){t==="focusin"?(q1(),lf=e,Gf=n,lf.attachEvent("onpropertychange",wO)):t==="focusout"&&q1()}function V5(t){if(t==="selectionchange"||t==="keyup"||t==="keydown")return B0(Gf)}function G5(t,e){if(t==="click")return B0(e)}function H5(t,e){if(t==="input"||t==="change")return B0(e)}function K5(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var zi=typeof Object.is=="function"?Object.is:K5;function Hf(t,e){if(zi(t,e))return!0;if(typeof t!="object"||t===null||typeof e!="object"||e===null)return!1;var n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(r=0;r<n.length;r++){var i=n[r];if(!gx.call(e,i)||!zi(t[i],e[i]))return!1}return!0}function W1(t){for(;t&&t.firstChild;)t=t.firstChild;return t}function Y1(t,e){var n=W1(t);t=0;for(var r;n;){if(n.nodeType===3){if(r=t+n.textContent.length,t<=e&&r>=e)return{node:n,offset:e-t};t=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=W1(n)}}function TO(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?TO(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function AO(t){t=t!=null&&t.ownerDocument!=null&&t.ownerDocument.defaultView!=null?t.ownerDocument.defaultView:window;for(var e=by(t.document);e instanceof t.HTMLIFrameElement;){try{var n=typeof e.contentWindow.location.href=="string"}catch{n=!1}if(n)t=e.contentWindow;else break;e=by(t.document)}return e}function xw(t){var e=t&&t.nodeName&&t.nodeName.toLowerCase();return e&&(e==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||e==="textarea"||t.contentEditable==="true")}var z5=io&&"documentMode"in document&&11>=document.documentMode,Hu=null,Sx=null,cf=null,Ex=!1;function X1(t,e,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Ex||Hu==null||Hu!==by(r)||(r=Hu,"selectionStart"in r&&xw(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),cf&&Hf(cf,r)||(cf=r,r=Uy(Sx,"onSelect"),0<r.length&&(e=new N0("onSelect","select",null,e,n),t.push({event:e,listeners:r}),e.target=Hu)))}function $l(t,e){var n={};return n[t.toLowerCase()]=e.toLowerCase(),n["Webkit"+t]="webkit"+e,n["Moz"+t]="moz"+e,n}var Ku={animationend:$l("Animation","AnimationEnd"),animationiteration:$l("Animation","AnimationIteration"),animationstart:$l("Animation","AnimationStart"),transitionrun:$l("Transition","TransitionRun"),transitionstart:$l("Transition","TransitionStart"),transitioncancel:$l("Transition","TransitionCancel"),transitionend:$l("Transition","TransitionEnd")},p_={},RO={};io&&(RO=document.createElement("div").style,"AnimationEvent"in window||(delete Ku.animationend.animation,delete Ku.animationiteration.animation,delete Ku.animationstart.animation),"TransitionEvent"in window||delete Ku.transitionend.transition);function qc(t){if(p_[t])return p_[t];if(!Ku[t])return t;var e=Ku[t],n;for(n in e)if(e.hasOwnProperty(n)&&n in RO)return p_[t]=e[n];return t}var CO=qc("animationend"),LO=qc("animationiteration"),kO=qc("animationstart"),q5=qc("transitionrun"),W5=qc("transitionstart"),Y5=qc("transitioncancel"),IO=qc("transitionend"),PO=new Map,wx="abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");wx.push("scrollEnd");function Ns(t,e){PO.set(t,e),Kc(e,[t])}var Q1=new WeakMap;function us(t,e){if(typeof t=="object"&&t!==null){var n=Q1.get(t);return n!==void 0?n:(e={value:t,source:e,stack:N1(e)},Q1.set(t,e),e)}return{value:t,source:e,stack:N1(e)}}var ss=[],zu=0,Sw=0;function U0(){for(var t=zu,e=Sw=zu=0;e<t;){var n=ss[e];ss[e++]=null;var r=ss[e];ss[e++]=null;var i=ss[e];ss[e++]=null;var s=ss[e];if(ss[e++]=null,r!==null&&i!==null){var a=r.pending;a===null?i.next=i:(i.next=a.next,a.next=i),r.pending=i}s!==0&&DO(n,i,s)}}function j0(t,e,n,r){ss[zu++]=t,ss[zu++]=e,ss[zu++]=n,ss[zu++]=r,Sw|=r,t.lanes|=r,t=t.alternate,t!==null&&(t.lanes|=r)}function Ew(t,e,n,r){return j0(t,e,n,r),xy(t)}function ah(t,e){return j0(t,null,null,e),xy(t)}function DO(t,e,n){t.lanes|=n;var r=t.alternate;r!==null&&(r.lanes|=n);for(var i=!1,s=t.return;s!==null;)s.childLanes|=n,r=s.alternate,r!==null&&(r.childLanes|=n),s.tag===22&&(t=s.stateNode,t===null||t._visibility&1||(i=!0)),t=s,s=s.return;return t.tag===3?(s=t.stateNode,i&&e!==null&&(i=31-Fi(n),t=s.hiddenUpdates,r=t[i],r===null?t[i]=[e]:r.push(e),e.lane=n|536870912),s):null}function xy(t){if(50<_f)throw _f=0,Kx=null,Error(Ue(185));for(var e=t.return;e!==null;)t=e,e=t.return;return t.tag===3?t.stateNode:null}var qu={};function X5(t,e,n,r){this.tag=t,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=e,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Bi(t,e,n,r){return new X5(t,e,n,r)}function ww(t){return t=t.prototype,!(!t||!t.isReactComponent)}function eo(t,e){var n=t.alternate;return n===null?(n=Bi(t.tag,e,t.key,t.mode),n.elementType=t.elementType,n.type=t.type,n.stateNode=t.stateNode,n.alternate=t,t.alternate=n):(n.pendingProps=e,n.type=t.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=t.flags&65011712,n.childLanes=t.childLanes,n.lanes=t.lanes,n.child=t.child,n.memoizedProps=t.memoizedProps,n.memoizedState=t.memoizedState,n.updateQueue=t.updateQueue,e=t.dependencies,n.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext},n.sibling=t.sibling,n.index=t.index,n.ref=t.ref,n.refCleanup=t.refCleanup,n}function OO(t,e){t.flags&=65011714;var n=t.alternate;return n===null?(t.childLanes=0,t.lanes=e,t.child=null,t.subtreeFlags=0,t.memoizedProps=null,t.memoizedState=null,t.updateQueue=null,t.dependencies=null,t.stateNode=null):(t.childLanes=n.childLanes,t.lanes=n.lanes,t.child=n.child,t.subtreeFlags=0,t.deletions=null,t.memoizedProps=n.memoizedProps,t.memoizedState=n.memoizedState,t.updateQueue=n.updateQueue,t.type=n.type,e=n.dependencies,t.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext}),t}function Bg(t,e,n,r,i,s){var a=0;if(r=t,typeof t=="function")ww(t)&&(a=1);else if(typeof t=="string")a=J8(t,n,la.current)?26:t==="html"||t==="head"||t==="body"?27:5;else e:switch(t){case hx:return t=Bi(31,n,e,i),t.elementType=hx,t.lanes=s,t;case ju:return xc(n.children,i,s,e);case ZD:a=8,i|=24;break;case cx:return t=Bi(12,n,e,i|2),t.elementType=cx,t.lanes=s,t;case ux:return t=Bi(13,n,e,i),t.elementType=ux,t.lanes=s,t;case dx:return t=Bi(19,n,e,i),t.elementType=dx,t.lanes=s,t;default:if(typeof t=="object"&&t!==null)switch(t.$$typeof){case F$:case Ya:a=10;break e;case eO:a=9;break e;case uw:a=11;break e;case dw:a=14;break e;case Oo:a=16,r=null;break e}a=29,n=Error(Ue(130,t===null?"null":typeof t,"")),r=null}return e=Bi(a,n,e,i),e.elementType=t,e.type=r,e.lanes=s,e}function xc(t,e,n,r){return t=Bi(7,t,r,e),t.lanes=n,t}function m_(t,e,n){return t=Bi(6,t,null,e),t.lanes=n,t}function g_(t,e,n){return e=Bi(4,t.children!==null?t.children:[],t.key,e),e.lanes=n,e.stateNode={containerInfo:t.containerInfo,pendingChildren:null,implementation:t.implementation},e}var Wu=[],Yu=0,Sy=null,Ey=0,os=[],ls=0,Sc=null,Xa=1,Qa="";function Xl(t,e){Wu[Yu++]=Ey,Wu[Yu++]=Sy,Sy=t,Ey=e}function NO(t,e,n){os[ls++]=Xa,os[ls++]=Qa,os[ls++]=Sc,Sc=t;var r=Xa;t=Qa;var i=32-Fi(r)-1;r&=~(1<<i),n+=1;var s=32-Fi(e)+i;if(30<s){var a=i-i%5;s=(r&(1<<a)-1).toString(32),r>>=a,i-=a,Xa=1<<32-Fi(e)+i|n<<i|r,Qa=s+t}else Xa=1<<s|n<<i|r,Qa=t}function Tw(t){t.return!==null&&(Xl(t,1),NO(t,1,0))}function Aw(t){for(;t===Sy;)Sy=Wu[--Yu],Wu[Yu]=null,Ey=Wu[--Yu],Wu[Yu]=null;for(;t===Sc;)Sc=os[--ls],os[ls]=null,Qa=os[--ls],os[ls]=null,Xa=os[--ls],os[ls]=null}var ei=null,Kn=null,Zt=!1,Ec=null,ea=!1,Tx=Error(Ue(519));function Pc(t){var e=Error(Ue(418,""));throw Kf(us(e,t)),Tx}function J1(t){var e=t.stateNode,n=t.type,r=t.memoizedProps;switch(e[Hr]=t,e[xi]=r,n){case"dialog":Kt("cancel",e),Kt("close",e);break;case"iframe":case"object":case"embed":Kt("load",e);break;case"video":case"audio":for(n=0;n<Wf.length;n++)Kt(Wf[n],e);break;case"source":Kt("error",e);break;case"img":case"image":case"link":Kt("error",e),Kt("load",e);break;case"details":Kt("toggle",e);break;case"input":Kt("invalid",e),fO(e,r.value,r.defaultValue,r.checked,r.defaultChecked,r.type,r.name,!0),_y(e);break;case"select":Kt("invalid",e);break;case"textarea":Kt("invalid",e),mO(e,r.value,r.defaultValue,r.children),_y(e)}n=r.children,typeof n!="string"&&typeof n!="number"&&typeof n!="bigint"||e.textContent===""+n||r.suppressHydrationWarning===!0||gM(e.textContent,n)?(r.popover!=null&&(Kt("beforetoggle",e),Kt("toggle",e)),r.onScroll!=null&&Kt("scroll",e),r.onScrollEnd!=null&&Kt("scrollend",e),r.onClick!=null&&(e.onclick=q0),e=!0):e=!1,e||Pc(t)}function Z1(t){for(ei=t.return;ei;)switch(ei.tag){case 5:case 13:ea=!1;return;case 27:case 3:ea=!0;return;default:ei=ei.return}}function Oh(t){if(t!==ei)return!1;if(!Zt)return Z1(t),Zt=!0,!1;var e=t.tag,n;if((n=e!==3&&e!==27)&&((n=e===5)&&(n=t.type,n=!(n!=="form"&&n!=="button")||Qx(t.type,t.memoizedProps)),n=!n),n&&Kn&&Pc(t),Z1(t),e===13){if(t=t.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(Ue(317));e:{for(t=t.nextSibling,e=0;t;){if(t.nodeType===8)if(n=t.data,n==="/$"){if(e===0){Kn=Is(t.nextSibling);break e}e--}else n!=="$"&&n!=="$!"&&n!=="$?"||e++;t=t.nextSibling}Kn=null}}else e===27?(e=Kn,Il(t.type)?(t=eS,eS=null,Kn=t):Kn=e):Kn=ei?Is(t.stateNode.nextSibling):null;return!0}function Vp(){Kn=ei=null,Zt=!1}function eR(){var t=Ec;return t!==null&&(yi===null?yi=t:yi.push.apply(yi,t),Ec=null),t}function Kf(t){Ec===null?Ec=[t]:Ec.push(t)}var Ax=va(null),Wc=null,Ja=null;function jo(t,e,n){Pn(Ax,e._currentValue),e._currentValue=n}function to(t){t._currentValue=Ax.current,Tr(Ax)}function Rx(t,e,n){for(;t!==null;){var r=t.alternate;if((t.childLanes&e)!==e?(t.childLanes|=e,r!==null&&(r.childLanes|=e)):r!==null&&(r.childLanes&e)!==e&&(r.childLanes|=e),t===n)break;t=t.return}}function Cx(t,e,n,r){var i=t.child;for(i!==null&&(i.return=t);i!==null;){var s=i.dependencies;if(s!==null){var a=i.child;s=s.firstContext;e:for(;s!==null;){var o=s;s=i;for(var l=0;l<e.length;l++)if(o.context===e[l]){s.lanes|=n,o=s.alternate,o!==null&&(o.lanes|=n),Rx(s.return,n,t),r||(a=null);break e}s=o.next}}else if(i.tag===18){if(a=i.return,a===null)throw Error(Ue(341));a.lanes|=n,s=a.alternate,s!==null&&(s.lanes|=n),Rx(a,n,t),a=null}else a=i.child;if(a!==null)a.return=i;else for(a=i;a!==null;){if(a===t){a=null;break}if(i=a.sibling,i!==null){i.return=a.return,a=i;break}a=a.return}i=a}}function Gp(t,e,n,r){t=null;for(var i=e,s=!1;i!==null;){if(!s){if(i.flags&524288)s=!0;else if(i.flags&262144)break}if(i.tag===10){var a=i.alternate;if(a===null)throw Error(Ue(387));if(a=a.memoizedProps,a!==null){var o=i.type;zi(i.pendingProps.value,a.value)||(t!==null?t.push(o):t=[o])}}else if(i===my.current){if(a=i.alternate,a===null)throw Error(Ue(387));a.memoizedState.memoizedState!==i.memoizedState.memoizedState&&(t!==null?t.push(Qf):t=[Qf])}i=i.return}t!==null&&Cx(e,t,n,r),e.flags|=262144}function wy(t){for(t=t.firstContext;t!==null;){if(!zi(t.context._currentValue,t.memoizedValue))return!0;t=t.next}return!1}function Dc(t){Wc=t,Ja=null,t=t.dependencies,t!==null&&(t.firstContext=null)}function Kr(t){return MO(Wc,t)}function Mm(t,e){return Wc===null&&Dc(t),MO(t,e)}function MO(t,e){var n=e._currentValue;if(e={context:e,memoizedValue:n,next:null},Ja===null){if(t===null)throw Error(Ue(308));Ja=e,t.dependencies={lanes:0,firstContext:e},t.flags|=524288}else Ja=Ja.next=e;return n}var Q5=typeof AbortController<"u"?AbortController:function(){var t=[],e=this.signal={aborted:!1,addEventListener:function(n,r){t.push(r)}};this.abort=function(){e.aborted=!0,t.forEach(function(n){return n()})}},J5=gr.unstable_scheduleCallback,Z5=gr.unstable_NormalPriority,fr={$$typeof:Ya,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function Rw(){return{controller:new Q5,data:new Map,refCount:0}}function Hp(t){t.refCount--,t.refCount===0&&J5(Z5,function(){t.controller.abort()})}var uf=null,Lx=0,Ud=0,ld=null;function e8(t,e){if(uf===null){var n=uf=[];Lx=0,Ud=Xw(),ld={status:"pending",value:void 0,then:function(r){n.push(r)}}}return Lx++,e.then(tR,tR),e}function tR(){if(--Lx===0&&uf!==null){ld!==null&&(ld.status="fulfilled");var t=uf;uf=null,Ud=0,ld=null;for(var e=0;e<t.length;e++)(0,t[e])()}}function t8(t,e){var n=[],r={status:"pending",value:null,reason:null,then:function(i){n.push(i)}};return t.then(function(){r.status="fulfilled",r.value=e;for(var i=0;i<n.length;i++)(0,n[i])(e)},function(i){for(r.status="rejected",r.reason=i,i=0;i<n.length;i++)(0,n[i])(void 0)}),r}var nR=xt.S;xt.S=function(t,e){typeof e=="object"&&e!==null&&typeof e.then=="function"&&e8(t,e),nR!==null&&nR(t,e)};var wc=va(null);function Cw(){var t=wc.current;return t!==null?t:xn.pooledCache}function Ug(t,e){e===null?Pn(wc,wc.current):Pn(wc,e.pool)}function BO(){var t=Cw();return t===null?null:{parent:fr._currentValue,pool:t}}var Kp=Error(Ue(460)),UO=Error(Ue(474)),F0=Error(Ue(542)),kx={then:function(){}};function rR(t){return t=t.status,t==="fulfilled"||t==="rejected"}function Bm(){}function jO(t,e,n){switch(n=t[n],n===void 0?t.push(e):n!==e&&(e.then(Bm,Bm),e=n),e.status){case"fulfilled":return e.value;case"rejected":throw t=e.reason,sR(t),t;default:if(typeof e.status=="string")e.then(Bm,Bm);else{if(t=xn,t!==null&&100<t.shellSuspendCounter)throw Error(Ue(482));t=e,t.status="pending",t.then(function(r){if(e.status==="pending"){var i=e;i.status="fulfilled",i.value=r}},function(r){if(e.status==="pending"){var i=e;i.status="rejected",i.reason=r}})}switch(e.status){case"fulfilled":return e.value;case"rejected":throw t=e.reason,sR(t),t}throw df=e,Kp}}var df=null;function iR(){if(df===null)throw Error(Ue(459));var t=df;return df=null,t}function sR(t){if(t===Kp||t===F0)throw Error(Ue(483))}var No=!1;function Lw(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Ix(t,e){t=t.updateQueue,e.updateQueue===t&&(e.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,callbacks:null})}function ol(t){return{lane:t,tag:0,payload:null,callback:null,next:null}}function ll(t,e,n){var r=t.updateQueue;if(r===null)return null;if(r=r.shared,cn&2){var i=r.pending;return i===null?e.next=e:(e.next=i.next,i.next=e),r.pending=e,e=xy(t),DO(t,null,n),e}return j0(t,r,e,n),xy(t)}function hf(t,e,n){if(e=e.updateQueue,e!==null&&(e=e.shared,(n&4194048)!==0)){var r=e.lanes;r&=t.pendingLanes,n|=r,e.lanes=n,oO(t,n)}}function y_(t,e){var n=t.updateQueue,r=t.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,s=null;if(n=n.firstBaseUpdate,n!==null){do{var a={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};s===null?i=s=a:s=s.next=a,n=n.next}while(n!==null);s===null?i=s=e:s=s.next=e}else i=s=e;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:s,shared:r.shared,callbacks:r.callbacks},t.updateQueue=n;return}t=n.lastBaseUpdate,t===null?n.firstBaseUpdate=e:t.next=e,n.lastBaseUpdate=e}var Px=!1;function ff(){if(Px){var t=ld;if(t!==null)throw t}}function pf(t,e,n,r){Px=!1;var i=t.updateQueue;No=!1;var s=i.firstBaseUpdate,a=i.lastBaseUpdate,o=i.shared.pending;if(o!==null){i.shared.pending=null;var l=o,c=l.next;l.next=null,a===null?s=c:a.next=c,a=l;var u=t.alternate;u!==null&&(u=u.updateQueue,o=u.lastBaseUpdate,o!==a&&(o===null?u.firstBaseUpdate=c:o.next=c,u.lastBaseUpdate=l))}if(s!==null){var d=i.baseState;a=0,u=c=l=null,o=s;do{var h=o.lane&-536870913,f=h!==o.lane;if(f?(Qt&h)===h:(r&h)===h){h!==0&&h===Ud&&(Px=!0),u!==null&&(u=u.next={lane:0,tag:o.tag,payload:o.payload,callback:null,next:null});e:{var p=t,m=o;h=e;var g=n;switch(m.tag){case 1:if(p=m.payload,typeof p=="function"){d=p.call(g,d,h);break e}d=p;break e;case 3:p.flags=p.flags&-65537|128;case 0:if(p=m.payload,h=typeof p=="function"?p.call(g,d,h):p,h==null)break e;d=Rn({},d,h);break e;case 2:No=!0}}h=o.callback,h!==null&&(t.flags|=64,f&&(t.flags|=8192),f=i.callbacks,f===null?i.callbacks=[h]:f.push(h))}else f={lane:h,tag:o.tag,payload:o.payload,callback:o.callback,next:null},u===null?(c=u=f,l=d):u=u.next=f,a|=h;if(o=o.next,o===null){if(o=i.shared.pending,o===null)break;f=o,o=f.next,f.next=null,i.lastBaseUpdate=f,i.shared.pending=null}}while(!0);u===null&&(l=d),i.baseState=l,i.firstBaseUpdate=c,i.lastBaseUpdate=u,s===null&&(i.shared.lanes=0),bl|=a,t.lanes=a,t.memoizedState=d}}function FO(t,e){if(typeof t!="function")throw Error(Ue(191,t));t.call(e)}function $O(t,e){var n=t.callbacks;if(n!==null)for(t.callbacks=null,t=0;t<n.length;t++)FO(n[t],e)}var jd=va(null),Ty=va(0);function aR(t,e){t=oo,Pn(Ty,t),Pn(jd,e),oo=t|e.baseLanes}function Dx(){Pn(Ty,oo),Pn(jd,jd.current)}function kw(){oo=Ty.current,Tr(jd),Tr(Ty)}var vl=0,Ut=null,hn=null,ir=null,Ay=!1,cd=!1,Oc=!1,Ry=0,zf=0,ud=null,n8=0;function Qn(){throw Error(Ue(321))}function Iw(t,e){if(e===null)return!1;for(var n=0;n<e.length&&n<t.length;n++)if(!zi(t[n],e[n]))return!1;return!0}function Pw(t,e,n,r,i,s){return vl=s,Ut=e,e.memoizedState=null,e.updateQueue=null,e.lanes=0,xt.H=t===null||t.memoizedState===null?vN:_N,Oc=!1,s=n(r,i),Oc=!1,cd&&(s=GO(e,n,r,i)),VO(t),s}function VO(t){xt.H=Cy;var e=hn!==null&&hn.next!==null;if(vl=0,ir=hn=Ut=null,Ay=!1,zf=0,ud=null,e)throw Error(Ue(300));t===null||wr||(t=t.dependencies,t!==null&&wy(t)&&(wr=!0))}function GO(t,e,n,r){Ut=t;var i=0;do{if(cd&&(ud=null),zf=0,cd=!1,25<=i)throw Error(Ue(301));if(i+=1,ir=hn=null,t.updateQueue!=null){var s=t.updateQueue;s.lastEffect=null,s.events=null,s.stores=null,s.memoCache!=null&&(s.memoCache.index=0)}xt.H=c8,s=e(n,r)}while(cd);return s}function r8(){var t=xt.H,e=t.useState()[0];return e=typeof e.then=="function"?zp(e):e,t=t.useState()[0],(hn!==null?hn.memoizedState:null)!==t&&(Ut.flags|=1024),e}function Dw(){var t=Ry!==0;return Ry=0,t}function Ow(t,e,n){e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~n}function Nw(t){if(Ay){for(t=t.memoizedState;t!==null;){var e=t.queue;e!==null&&(e.pending=null),t=t.next}Ay=!1}vl=0,ir=hn=Ut=null,cd=!1,zf=Ry=0,ud=null}function mi(){var t={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return ir===null?Ut.memoizedState=ir=t:ir=ir.next=t,ir}function sr(){if(hn===null){var t=Ut.alternate;t=t!==null?t.memoizedState:null}else t=hn.next;var e=ir===null?Ut.memoizedState:ir.next;if(e!==null)ir=e,hn=t;else{if(t===null)throw Ut.alternate===null?Error(Ue(467)):Error(Ue(310));hn=t,t={memoizedState:hn.memoizedState,baseState:hn.baseState,baseQueue:hn.baseQueue,queue:hn.queue,next:null},ir===null?Ut.memoizedState=ir=t:ir=ir.next=t}return ir}function Mw(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function zp(t){var e=zf;return zf+=1,ud===null&&(ud=[]),t=jO(ud,t,e),e=Ut,(ir===null?e.memoizedState:ir.next)===null&&(e=e.alternate,xt.H=e===null||e.memoizedState===null?vN:_N),t}function $0(t){if(t!==null&&typeof t=="object"){if(typeof t.then=="function")return zp(t);if(t.$$typeof===Ya)return Kr(t)}throw Error(Ue(438,String(t)))}function Bw(t){var e=null,n=Ut.updateQueue;if(n!==null&&(e=n.memoCache),e==null){var r=Ut.alternate;r!==null&&(r=r.updateQueue,r!==null&&(r=r.memoCache,r!=null&&(e={data:r.data.map(function(i){return i.slice()}),index:0})))}if(e==null&&(e={data:[],index:0}),n===null&&(n=Mw(),Ut.updateQueue=n),n.memoCache=e,n=e.data[e.index],n===void 0)for(n=e.data[e.index]=Array(t),r=0;r<t;r++)n[r]=$$;return e.index++,n}function so(t,e){return typeof e=="function"?e(t):e}function jg(t){var e=sr();return Uw(e,hn,t)}function Uw(t,e,n){var r=t.queue;if(r===null)throw Error(Ue(311));r.lastRenderedReducer=n;var i=t.baseQueue,s=r.pending;if(s!==null){if(i!==null){var a=i.next;i.next=s.next,s.next=a}e.baseQueue=i=s,r.pending=null}if(s=t.baseState,i===null)t.memoizedState=s;else{e=i.next;var o=a=null,l=null,c=e,u=!1;do{var d=c.lane&-536870913;if(d!==c.lane?(Qt&d)===d:(vl&d)===d){var h=c.revertLane;if(h===0)l!==null&&(l=l.next={lane:0,revertLane:0,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null}),d===Ud&&(u=!0);else if((vl&h)===h){c=c.next,h===Ud&&(u=!0);continue}else d={lane:0,revertLane:c.revertLane,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null},l===null?(o=l=d,a=s):l=l.next=d,Ut.lanes|=h,bl|=h;d=c.action,Oc&&n(s,d),s=c.hasEagerState?c.eagerState:n(s,d)}else h={lane:d,revertLane:c.revertLane,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null},l===null?(o=l=h,a=s):l=l.next=h,Ut.lanes|=d,bl|=d;c=c.next}while(c!==null&&c!==e);if(l===null?a=s:l.next=o,!zi(s,t.memoizedState)&&(wr=!0,u&&(n=ld,n!==null)))throw n;t.memoizedState=s,t.baseState=a,t.baseQueue=l,r.lastRenderedState=s}return i===null&&(r.lanes=0),[t.memoizedState,r.dispatch]}function v_(t){var e=sr(),n=e.queue;if(n===null)throw Error(Ue(311));n.lastRenderedReducer=t;var r=n.dispatch,i=n.pending,s=e.memoizedState;if(i!==null){n.pending=null;var a=i=i.next;do s=t(s,a.action),a=a.next;while(a!==i);zi(s,e.memoizedState)||(wr=!0),e.memoizedState=s,e.baseQueue===null&&(e.baseState=s),n.lastRenderedState=s}return[s,r]}function HO(t,e,n){var r=Ut,i=sr(),s=Zt;if(s){if(n===void 0)throw Error(Ue(407));n=n()}else n=e();var a=!zi((hn||i).memoizedState,n);a&&(i.memoizedState=n,wr=!0),i=i.queue;var o=qO.bind(null,r,i,t);if(qp(2048,8,o,[t]),i.getSnapshot!==e||a||ir!==null&&ir.memoizedState.tag&1){if(r.flags|=2048,Fd(9,V0(),zO.bind(null,r,i,n,e),null),xn===null)throw Error(Ue(349));s||vl&124||KO(r,e,n)}return n}function KO(t,e,n){t.flags|=16384,t={getSnapshot:e,value:n},e=Ut.updateQueue,e===null?(e=Mw(),Ut.updateQueue=e,e.stores=[t]):(n=e.stores,n===null?e.stores=[t]:n.push(t))}function zO(t,e,n,r){e.value=n,e.getSnapshot=r,WO(e)&&YO(t)}function qO(t,e,n){return n(function(){WO(e)&&YO(t)})}function WO(t){var e=t.getSnapshot;t=t.value;try{var n=e();return!zi(t,n)}catch{return!0}}function YO(t){var e=ah(t,2);e!==null&&Vi(e,t,2)}function Ox(t){var e=mi();if(typeof t=="function"){var n=t;if(t=n(),Oc){el(!0);try{n()}finally{el(!1)}}}return e.memoizedState=e.baseState=t,e.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:so,lastRenderedState:t},e}function XO(t,e,n,r){return t.baseState=n,Uw(t,hn,typeof r=="function"?r:so)}function i8(t,e,n,r,i){if(G0(t))throw Error(Ue(485));if(t=e.action,t!==null){var s={payload:i,action:t,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(a){s.listeners.push(a)}};xt.T!==null?n(!0):s.isTransition=!1,r(s),n=e.pending,n===null?(s.next=e.pending=s,QO(e,s)):(s.next=n.next,e.pending=n.next=s)}}function QO(t,e){var n=e.action,r=e.payload,i=t.state;if(e.isTransition){var s=xt.T,a={};xt.T=a;try{var o=n(i,r),l=xt.S;l!==null&&l(a,o),oR(t,e,o)}catch(c){Nx(t,e,c)}finally{xt.T=s}}else try{s=n(i,r),oR(t,e,s)}catch(c){Nx(t,e,c)}}function oR(t,e,n){n!==null&&typeof n=="object"&&typeof n.then=="function"?n.then(function(r){lR(t,e,r)},function(r){return Nx(t,e,r)}):lR(t,e,n)}function lR(t,e,n){e.status="fulfilled",e.value=n,JO(e),t.state=n,e=t.pending,e!==null&&(n=e.next,n===e?t.pending=null:(n=n.next,e.next=n,QO(t,n)))}function Nx(t,e,n){var r=t.pending;if(t.pending=null,r!==null){r=r.next;do e.status="rejected",e.reason=n,JO(e),e=e.next;while(e!==r)}t.action=null}function JO(t){t=t.listeners;for(var e=0;e<t.length;e++)(0,t[e])()}function ZO(t,e){return e}function cR(t,e){if(Zt){var n=xn.formState;if(n!==null){e:{var r=Ut;if(Zt){if(Kn){t:{for(var i=Kn,s=ea;i.nodeType!==8;){if(!s){i=null;break t}if(i=Is(i.nextSibling),i===null){i=null;break t}}s=i.data,i=s==="F!"||s==="F"?i:null}if(i){Kn=Is(i.nextSibling),r=i.data==="F!";break e}}Pc(r)}r=!1}r&&(e=n[0])}}return n=mi(),n.memoizedState=n.baseState=e,r={pending:null,lanes:0,dispatch:null,lastRenderedReducer:ZO,lastRenderedState:e},n.queue=r,n=mN.bind(null,Ut,r),r.dispatch=n,r=Ox(!1),s=Vw.bind(null,Ut,!1,r.queue),r=mi(),i={state:e,dispatch:null,action:t,pending:null},r.queue=i,n=i8.bind(null,Ut,i,s,n),i.dispatch=n,r.memoizedState=t,[e,n,!1]}function uR(t){var e=sr();return eN(e,hn,t)}function eN(t,e,n){if(e=Uw(t,e,ZO)[0],t=jg(so)[0],typeof e=="object"&&e!==null&&typeof e.then=="function")try{var r=zp(e)}catch(a){throw a===Kp?F0:a}else r=e;e=sr();var i=e.queue,s=i.dispatch;return n!==e.memoizedState&&(Ut.flags|=2048,Fd(9,V0(),s8.bind(null,i,n),null)),[r,s,t]}function s8(t,e){t.action=e}function dR(t){var e=sr(),n=hn;if(n!==null)return eN(e,n,t);sr(),e=e.memoizedState,n=sr();var r=n.queue.dispatch;return n.memoizedState=t,[e,r,!1]}function Fd(t,e,n,r){return t={tag:t,create:n,deps:r,inst:e,next:null},e=Ut.updateQueue,e===null&&(e=Mw(),Ut.updateQueue=e),n=e.lastEffect,n===null?e.lastEffect=t.next=t:(r=n.next,n.next=t,t.next=r,e.lastEffect=t),t}function V0(){return{destroy:void 0,resource:void 0}}function tN(){return sr().memoizedState}function Fg(t,e,n,r){var i=mi();r=r===void 0?null:r,Ut.flags|=t,i.memoizedState=Fd(1|e,V0(),n,r)}function qp(t,e,n,r){var i=sr();r=r===void 0?null:r;var s=i.memoizedState.inst;hn!==null&&r!==null&&Iw(r,hn.memoizedState.deps)?i.memoizedState=Fd(e,s,n,r):(Ut.flags|=t,i.memoizedState=Fd(1|e,s,n,r))}function hR(t,e){Fg(8390656,8,t,e)}function nN(t,e){qp(2048,8,t,e)}function rN(t,e){return qp(4,2,t,e)}function iN(t,e){return qp(4,4,t,e)}function sN(t,e){if(typeof e=="function"){t=t();var n=e(t);return function(){typeof n=="function"?n():e(null)}}if(e!=null)return t=t(),e.current=t,function(){e.current=null}}function aN(t,e,n){n=n!=null?n.concat([t]):null,qp(4,4,sN.bind(null,e,t),n)}function jw(){}function oN(t,e){var n=sr();e=e===void 0?null:e;var r=n.memoizedState;return e!==null&&Iw(e,r[1])?r[0]:(n.memoizedState=[t,e],t)}function lN(t,e){var n=sr();e=e===void 0?null:e;var r=n.memoizedState;if(e!==null&&Iw(e,r[1]))return r[0];if(r=t(),Oc){el(!0);try{t()}finally{el(!1)}}return n.memoizedState=[r,e],r}function Fw(t,e,n){return n===void 0||vl&1073741824?t.memoizedState=e:(t.memoizedState=n,t=JN(),Ut.lanes|=t,bl|=t,n)}function cN(t,e,n,r){return zi(n,e)?n:jd.current!==null?(t=Fw(t,n,r),zi(t,e)||(wr=!0),t):vl&42?(t=JN(),Ut.lanes|=t,bl|=t,e):(wr=!0,t.memoizedState=n)}function uN(t,e,n,r,i){var s=en.p;en.p=s!==0&&8>s?s:8;var a=xt.T,o={};xt.T=o,Vw(t,!1,e,n);try{var l=i(),c=xt.S;if(c!==null&&c(o,l),l!==null&&typeof l=="object"&&typeof l.then=="function"){var u=t8(l,r);mf(t,e,u,$i(t))}else mf(t,e,r,$i(t))}catch(d){mf(t,e,{then:function(){},status:"rejected",reason:d},$i())}finally{en.p=s,xt.T=a}}function a8(){}function Mx(t,e,n,r){if(t.tag!==5)throw Error(Ue(476));var i=dN(t).queue;uN(t,i,e,bc,n===null?a8:function(){return hN(t),n(r)})}function dN(t){var e=t.memoizedState;if(e!==null)return e;e={memoizedState:bc,baseState:bc,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:so,lastRenderedState:bc},next:null};var n={};return e.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:so,lastRenderedState:n},next:null},t.memoizedState=e,t=t.alternate,t!==null&&(t.memoizedState=e),e}function hN(t){var e=dN(t).next.queue;mf(t,e,{},$i())}function $w(){return Kr(Qf)}function fN(){return sr().memoizedState}function pN(){return sr().memoizedState}function o8(t){for(var e=t.return;e!==null;){switch(e.tag){case 24:case 3:var n=$i();t=ol(n);var r=ll(e,t,n);r!==null&&(Vi(r,e,n),hf(r,e,n)),e={cache:Rw()},t.payload=e;return}e=e.return}}function l8(t,e,n){var r=$i();n={lane:r,revertLane:0,action:n,hasEagerState:!1,eagerState:null,next:null},G0(t)?gN(e,n):(n=Ew(t,e,n,r),n!==null&&(Vi(n,t,r),yN(n,e,r)))}function mN(t,e,n){var r=$i();mf(t,e,n,r)}function mf(t,e,n,r){var i={lane:r,revertLane:0,action:n,hasEagerState:!1,eagerState:null,next:null};if(G0(t))gN(e,i);else{var s=t.alternate;if(t.lanes===0&&(s===null||s.lanes===0)&&(s=e.lastRenderedReducer,s!==null))try{var a=e.lastRenderedState,o=s(a,n);if(i.hasEagerState=!0,i.eagerState=o,zi(o,a))return j0(t,e,i,0),xn===null&&U0(),!1}catch{}finally{}if(n=Ew(t,e,i,r),n!==null)return Vi(n,t,r),yN(n,e,r),!0}return!1}function Vw(t,e,n,r){if(r={lane:2,revertLane:Xw(),action:r,hasEagerState:!1,eagerState:null,next:null},G0(t)){if(e)throw Error(Ue(479))}else e=Ew(t,n,r,2),e!==null&&Vi(e,t,2)}function G0(t){var e=t.alternate;return t===Ut||e!==null&&e===Ut}function gN(t,e){cd=Ay=!0;var n=t.pending;n===null?e.next=e:(e.next=n.next,n.next=e),t.pending=e}function yN(t,e,n){if(n&4194048){var r=e.lanes;r&=t.pendingLanes,n|=r,e.lanes=n,oO(t,n)}}var Cy={readContext:Kr,use:$0,useCallback:Qn,useContext:Qn,useEffect:Qn,useImperativeHandle:Qn,useLayoutEffect:Qn,useInsertionEffect:Qn,useMemo:Qn,useReducer:Qn,useRef:Qn,useState:Qn,useDebugValue:Qn,useDeferredValue:Qn,useTransition:Qn,useSyncExternalStore:Qn,useId:Qn,useHostTransitionStatus:Qn,useFormState:Qn,useActionState:Qn,useOptimistic:Qn,useMemoCache:Qn,useCacheRefresh:Qn},vN={readContext:Kr,use:$0,useCallback:function(t,e){return mi().memoizedState=[t,e===void 0?null:e],t},useContext:Kr,useEffect:hR,useImperativeHandle:function(t,e,n){n=n!=null?n.concat([t]):null,Fg(4194308,4,sN.bind(null,e,t),n)},useLayoutEffect:function(t,e){return Fg(4194308,4,t,e)},useInsertionEffect:function(t,e){Fg(4,2,t,e)},useMemo:function(t,e){var n=mi();e=e===void 0?null:e;var r=t();if(Oc){el(!0);try{t()}finally{el(!1)}}return n.memoizedState=[r,e],r},useReducer:function(t,e,n){var r=mi();if(n!==void 0){var i=n(e);if(Oc){el(!0);try{n(e)}finally{el(!1)}}}else i=e;return r.memoizedState=r.baseState=i,t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:i},r.queue=t,t=t.dispatch=l8.bind(null,Ut,t),[r.memoizedState,t]},useRef:function(t){var e=mi();return t={current:t},e.memoizedState=t},useState:function(t){t=Ox(t);var e=t.queue,n=mN.bind(null,Ut,e);return e.dispatch=n,[t.memoizedState,n]},useDebugValue:jw,useDeferredValue:function(t,e){var n=mi();return Fw(n,t,e)},useTransition:function(){var t=Ox(!1);return t=uN.bind(null,Ut,t.queue,!0,!1),mi().memoizedState=t,[!1,t]},useSyncExternalStore:function(t,e,n){var r=Ut,i=mi();if(Zt){if(n===void 0)throw Error(Ue(407));n=n()}else{if(n=e(),xn===null)throw Error(Ue(349));Qt&124||KO(r,e,n)}i.memoizedState=n;var s={value:n,getSnapshot:e};return i.queue=s,hR(qO.bind(null,r,s,t),[t]),r.flags|=2048,Fd(9,V0(),zO.bind(null,r,s,n,e),null),n},useId:function(){var t=mi(),e=xn.identifierPrefix;if(Zt){var n=Qa,r=Xa;n=(r&~(1<<32-Fi(r)-1)).toString(32)+n,e="«"+e+"R"+n,n=Ry++,0<n&&(e+="H"+n.toString(32)),e+="»"}else n=n8++,e="«"+e+"r"+n.toString(32)+"»";return t.memoizedState=e},useHostTransitionStatus:$w,useFormState:cR,useActionState:cR,useOptimistic:function(t){var e=mi();e.memoizedState=e.baseState=t;var n={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return e.queue=n,e=Vw.bind(null,Ut,!0,n),n.dispatch=e,[t,e]},useMemoCache:Bw,useCacheRefresh:function(){return mi().memoizedState=o8.bind(null,Ut)}},_N={readContext:Kr,use:$0,useCallback:oN,useContext:Kr,useEffect:nN,useImperativeHandle:aN,useInsertionEffect:rN,useLayoutEffect:iN,useMemo:lN,useReducer:jg,useRef:tN,useState:function(){return jg(so)},useDebugValue:jw,useDeferredValue:function(t,e){var n=sr();return cN(n,hn.memoizedState,t,e)},useTransition:function(){var t=jg(so)[0],e=sr().memoizedState;return[typeof t=="boolean"?t:zp(t),e]},useSyncExternalStore:HO,useId:fN,useHostTransitionStatus:$w,useFormState:uR,useActionState:uR,useOptimistic:function(t,e){var n=sr();return XO(n,hn,t,e)},useMemoCache:Bw,useCacheRefresh:pN},c8={readContext:Kr,use:$0,useCallback:oN,useContext:Kr,useEffect:nN,useImperativeHandle:aN,useInsertionEffect:rN,useLayoutEffect:iN,useMemo:lN,useReducer:v_,useRef:tN,useState:function(){return v_(so)},useDebugValue:jw,useDeferredValue:function(t,e){var n=sr();return hn===null?Fw(n,t,e):cN(n,hn.memoizedState,t,e)},useTransition:function(){var t=v_(so)[0],e=sr().memoizedState;return[typeof t=="boolean"?t:zp(t),e]},useSyncExternalStore:HO,useId:fN,useHostTransitionStatus:$w,useFormState:dR,useActionState:dR,useOptimistic:function(t,e){var n=sr();return hn!==null?XO(n,hn,t,e):(n.baseState=t,[t,n.queue.dispatch])},useMemoCache:Bw,useCacheRefresh:pN},dd=null,qf=0;function Um(t){var e=qf;return qf+=1,dd===null&&(dd=[]),jO(dd,t,e)}function Nh(t,e){e=e.props.ref,t.ref=e!==void 0?e:null}function jm(t,e){throw e.$$typeof===j$?Error(Ue(525)):(t=Object.prototype.toString.call(e),Error(Ue(31,t==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":t)))}function fR(t){var e=t._init;return e(t._payload)}function bN(t){function e(b,v){if(t){var S=b.deletions;S===null?(b.deletions=[v],b.flags|=16):S.push(v)}}function n(b,v){if(!t)return null;for(;v!==null;)e(b,v),v=v.sibling;return null}function r(b){for(var v=new Map;b!==null;)b.key!==null?v.set(b.key,b):v.set(b.index,b),b=b.sibling;return v}function i(b,v){return b=eo(b,v),b.index=0,b.sibling=null,b}function s(b,v,S){return b.index=S,t?(S=b.alternate,S!==null?(S=S.index,S<v?(b.flags|=67108866,v):S):(b.flags|=67108866,v)):(b.flags|=1048576,v)}function a(b){return t&&b.alternate===null&&(b.flags|=67108866),b}function o(b,v,S,E){return v===null||v.tag!==6?(v=m_(S,b.mode,E),v.return=b,v):(v=i(v,S),v.return=b,v)}function l(b,v,S,E){var L=S.type;return L===ju?u(b,v,S.props.children,E,S.key):v!==null&&(v.elementType===L||typeof L=="object"&&L!==null&&L.$$typeof===Oo&&fR(L)===v.type)?(v=i(v,S.props),Nh(v,S),v.return=b,v):(v=Bg(S.type,S.key,S.props,null,b.mode,E),Nh(v,S),v.return=b,v)}function c(b,v,S,E){return v===null||v.tag!==4||v.stateNode.containerInfo!==S.containerInfo||v.stateNode.implementation!==S.implementation?(v=g_(S,b.mode,E),v.return=b,v):(v=i(v,S.children||[]),v.return=b,v)}function u(b,v,S,E,L){return v===null||v.tag!==7?(v=xc(S,b.mode,E,L),v.return=b,v):(v=i(v,S),v.return=b,v)}function d(b,v,S){if(typeof v=="string"&&v!==""||typeof v=="number"||typeof v=="bigint")return v=m_(""+v,b.mode,S),v.return=b,v;if(typeof v=="object"&&v!==null){switch(v.$$typeof){case Im:return S=Bg(v.type,v.key,v.props,null,b.mode,S),Nh(S,v),S.return=b,S;case Wh:return v=g_(v,b.mode,S),v.return=b,v;case Oo:var E=v._init;return v=E(v._payload),d(b,v,S)}if(Yh(v)||Ih(v))return v=xc(v,b.mode,S,null),v.return=b,v;if(typeof v.then=="function")return d(b,Um(v),S);if(v.$$typeof===Ya)return d(b,Mm(b,v),S);jm(b,v)}return null}function h(b,v,S,E){var L=v!==null?v.key:null;if(typeof S=="string"&&S!==""||typeof S=="number"||typeof S=="bigint")return L!==null?null:o(b,v,""+S,E);if(typeof S=="object"&&S!==null){switch(S.$$typeof){case Im:return S.key===L?l(b,v,S,E):null;case Wh:return S.key===L?c(b,v,S,E):null;case Oo:return L=S._init,S=L(S._payload),h(b,v,S,E)}if(Yh(S)||Ih(S))return L!==null?null:u(b,v,S,E,null);if(typeof S.then=="function")return h(b,v,Um(S),E);if(S.$$typeof===Ya)return h(b,v,Mm(b,S),E);jm(b,S)}return null}function f(b,v,S,E,L){if(typeof E=="string"&&E!==""||typeof E=="number"||typeof E=="bigint")return b=b.get(S)||null,o(v,b,""+E,L);if(typeof E=="object"&&E!==null){switch(E.$$typeof){case Im:return b=b.get(E.key===null?S:E.key)||null,l(v,b,E,L);case Wh:return b=b.get(E.key===null?S:E.key)||null,c(v,b,E,L);case Oo:var U=E._init;return E=U(E._payload),f(b,v,S,E,L)}if(Yh(E)||Ih(E))return b=b.get(S)||null,u(v,b,E,L,null);if(typeof E.then=="function")return f(b,v,S,Um(E),L);if(E.$$typeof===Ya)return f(b,v,S,Mm(v,E),L);jm(v,E)}return null}function p(b,v,S,E){for(var L=null,U=null,O=v,k=v=0,I=null;O!==null&&k<S.length;k++){O.index>k?(I=O,O=null):I=O.sibling;var R=h(b,O,S[k],E);if(R===null){O===null&&(O=I);break}t&&O&&R.alternate===null&&e(b,O),v=s(R,v,k),U===null?L=R:U.sibling=R,U=R,O=I}if(k===S.length)return n(b,O),Zt&&Xl(b,k),L;if(O===null){for(;k<S.length;k++)O=d(b,S[k],E),O!==null&&(v=s(O,v,k),U===null?L=O:U.sibling=O,U=O);return Zt&&Xl(b,k),L}for(O=r(O);k<S.length;k++)I=f(O,b,k,S[k],E),I!==null&&(t&&I.alternate!==null&&O.delete(I.key===null?k:I.key),v=s(I,v,k),U===null?L=I:U.sibling=I,U=I);return t&&O.forEach(function(M){return e(b,M)}),Zt&&Xl(b,k),L}function m(b,v,S,E){if(S==null)throw Error(Ue(151));for(var L=null,U=null,O=v,k=v=0,I=null,R=S.next();O!==null&&!R.done;k++,R=S.next()){O.index>k?(I=O,O=null):I=O.sibling;var M=h(b,O,R.value,E);if(M===null){O===null&&(O=I);break}t&&O&&M.alternate===null&&e(b,O),v=s(M,v,k),U===null?L=M:U.sibling=M,U=M,O=I}if(R.done)return n(b,O),Zt&&Xl(b,k),L;if(O===null){for(;!R.done;k++,R=S.next())R=d(b,R.value,E),R!==null&&(v=s(R,v,k),U===null?L=R:U.sibling=R,U=R);return Zt&&Xl(b,k),L}for(O=r(O);!R.done;k++,R=S.next())R=f(O,b,k,R.value,E),R!==null&&(t&&R.alternate!==null&&O.delete(R.key===null?k:R.key),v=s(R,v,k),U===null?L=R:U.sibling=R,U=R);return t&&O.forEach(function(z){return e(b,z)}),Zt&&Xl(b,k),L}function g(b,v,S,E){if(typeof S=="object"&&S!==null&&S.type===ju&&S.key===null&&(S=S.props.children),typeof S=="object"&&S!==null){switch(S.$$typeof){case Im:e:{for(var L=S.key;v!==null;){if(v.key===L){if(L=S.type,L===ju){if(v.tag===7){n(b,v.sibling),E=i(v,S.props.children),E.return=b,b=E;break e}}else if(v.elementType===L||typeof L=="object"&&L!==null&&L.$$typeof===Oo&&fR(L)===v.type){n(b,v.sibling),E=i(v,S.props),Nh(E,S),E.return=b,b=E;break e}n(b,v);break}else e(b,v);v=v.sibling}S.type===ju?(E=xc(S.props.children,b.mode,E,S.key),E.return=b,b=E):(E=Bg(S.type,S.key,S.props,null,b.mode,E),Nh(E,S),E.return=b,b=E)}return a(b);case Wh:e:{for(L=S.key;v!==null;){if(v.key===L)if(v.tag===4&&v.stateNode.containerInfo===S.containerInfo&&v.stateNode.implementation===S.implementation){n(b,v.sibling),E=i(v,S.children||[]),E.return=b,b=E;break e}else{n(b,v);break}else e(b,v);v=v.sibling}E=g_(S,b.mode,E),E.return=b,b=E}return a(b);case Oo:return L=S._init,S=L(S._payload),g(b,v,S,E)}if(Yh(S))return p(b,v,S,E);if(Ih(S)){if(L=Ih(S),typeof L!="function")throw Error(Ue(150));return S=L.call(S),m(b,v,S,E)}if(typeof S.then=="function")return g(b,v,Um(S),E);if(S.$$typeof===Ya)return g(b,v,Mm(b,S),E);jm(b,S)}return typeof S=="string"&&S!==""||typeof S=="number"||typeof S=="bigint"?(S=""+S,v!==null&&v.tag===6?(n(b,v.sibling),E=i(v,S),E.return=b,b=E):(n(b,v),E=m_(S,b.mode,E),E.return=b,b=E),a(b)):n(b,v)}return function(b,v,S,E){try{qf=0;var L=g(b,v,S,E);return dd=null,L}catch(O){if(O===Kp||O===F0)throw O;var U=Bi(29,O,null,b.mode);return U.lanes=E,U.return=b,U}finally{}}}var $d=bN(!0),xN=bN(!1),ms=va(null),ua=null;function Fo(t){var e=t.alternate;Pn(mr,mr.current&1),Pn(ms,t),ua===null&&(e===null||jd.current!==null||e.memoizedState!==null)&&(ua=t)}function SN(t){if(t.tag===22){if(Pn(mr,mr.current),Pn(ms,t),ua===null){var e=t.alternate;e!==null&&e.memoizedState!==null&&(ua=t)}}else $o()}function $o(){Pn(mr,mr.current),Pn(ms,ms.current)}function Za(t){Tr(ms),ua===t&&(ua=null),Tr(mr)}var mr=va(0);function Ly(t){for(var e=t;e!==null;){if(e.tag===13){var n=e.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||n.data==="$?"||Zx(n)))return e}else if(e.tag===19&&e.memoizedProps.revealOrder!==void 0){if(e.flags&128)return e}else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break;for(;e.sibling===null;){if(e.return===null||e.return===t)return null;e=e.return}e.sibling.return=e.return,e=e.sibling}return null}function __(t,e,n,r){e=t.memoizedState,n=n(r,e),n=n==null?e:Rn({},e,n),t.memoizedState=n,t.lanes===0&&(t.updateQueue.baseState=n)}var Bx={enqueueSetState:function(t,e,n){t=t._reactInternals;var r=$i(),i=ol(r);i.payload=e,n!=null&&(i.callback=n),e=ll(t,i,r),e!==null&&(Vi(e,t,r),hf(e,t,r))},enqueueReplaceState:function(t,e,n){t=t._reactInternals;var r=$i(),i=ol(r);i.tag=1,i.payload=e,n!=null&&(i.callback=n),e=ll(t,i,r),e!==null&&(Vi(e,t,r),hf(e,t,r))},enqueueForceUpdate:function(t,e){t=t._reactInternals;var n=$i(),r=ol(n);r.tag=2,e!=null&&(r.callback=e),e=ll(t,r,n),e!==null&&(Vi(e,t,n),hf(e,t,n))}};function pR(t,e,n,r,i,s,a){return t=t.stateNode,typeof t.shouldComponentUpdate=="function"?t.shouldComponentUpdate(r,s,a):e.prototype&&e.prototype.isPureReactComponent?!Hf(n,r)||!Hf(i,s):!0}function mR(t,e,n,r){t=e.state,typeof e.componentWillReceiveProps=="function"&&e.componentWillReceiveProps(n,r),typeof e.UNSAFE_componentWillReceiveProps=="function"&&e.UNSAFE_componentWillReceiveProps(n,r),e.state!==t&&Bx.enqueueReplaceState(e,e.state,null)}function Nc(t,e){var n=e;if("ref"in e){n={};for(var r in e)r!=="ref"&&(n[r]=e[r])}if(t=t.defaultProps){n===e&&(n=Rn({},n));for(var i in t)n[i]===void 0&&(n[i]=t[i])}return n}var ky=typeof reportError=="function"?reportError:function(t){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var e=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof t=="object"&&t!==null&&typeof t.message=="string"?String(t.message):String(t),error:t});if(!window.dispatchEvent(e))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",t);return}console.error(t)};function EN(t){ky(t)}function wN(t){console.error(t)}function TN(t){ky(t)}function Iy(t,e){try{var n=t.onUncaughtError;n(e.value,{componentStack:e.stack})}catch(r){setTimeout(function(){throw r})}}function gR(t,e,n){try{var r=t.onCaughtError;r(n.value,{componentStack:n.stack,errorBoundary:e.tag===1?e.stateNode:null})}catch(i){setTimeout(function(){throw i})}}function Ux(t,e,n){return n=ol(n),n.tag=3,n.payload={element:null},n.callback=function(){Iy(t,e)},n}function AN(t){return t=ol(t),t.tag=3,t}function RN(t,e,n,r){var i=n.type.getDerivedStateFromError;if(typeof i=="function"){var s=r.value;t.payload=function(){return i(s)},t.callback=function(){gR(e,n,r)}}var a=n.stateNode;a!==null&&typeof a.componentDidCatch=="function"&&(t.callback=function(){gR(e,n,r),typeof i!="function"&&(cl===null?cl=new Set([this]):cl.add(this));var o=r.stack;this.componentDidCatch(r.value,{componentStack:o!==null?o:""})})}function u8(t,e,n,r,i){if(n.flags|=32768,r!==null&&typeof r=="object"&&typeof r.then=="function"){if(e=n.alternate,e!==null&&Gp(e,n,i,!0),n=ms.current,n!==null){switch(n.tag){case 13:return ua===null?zx():n.alternate===null&&zn===0&&(zn=3),n.flags&=-257,n.flags|=65536,n.lanes=i,r===kx?n.flags|=16384:(e=n.updateQueue,e===null?n.updateQueue=new Set([r]):e.add(r),k_(t,r,i)),!1;case 22:return n.flags|=65536,r===kx?n.flags|=16384:(e=n.updateQueue,e===null?(e={transitions:null,markerInstances:null,retryQueue:new Set([r])},n.updateQueue=e):(n=e.retryQueue,n===null?e.retryQueue=new Set([r]):n.add(r)),k_(t,r,i)),!1}throw Error(Ue(435,n.tag))}return k_(t,r,i),zx(),!1}if(Zt)return e=ms.current,e!==null?(!(e.flags&65536)&&(e.flags|=256),e.flags|=65536,e.lanes=i,r!==Tx&&(t=Error(Ue(422),{cause:r}),Kf(us(t,n)))):(r!==Tx&&(e=Error(Ue(423),{cause:r}),Kf(us(e,n))),t=t.current.alternate,t.flags|=65536,i&=-i,t.lanes|=i,r=us(r,n),i=Ux(t.stateNode,r,i),y_(t,i),zn!==4&&(zn=2)),!1;var s=Error(Ue(520),{cause:r});if(s=us(s,n),vf===null?vf=[s]:vf.push(s),zn!==4&&(zn=2),e===null)return!0;r=us(r,n),n=e;do{switch(n.tag){case 3:return n.flags|=65536,t=i&-i,n.lanes|=t,t=Ux(n.stateNode,r,t),y_(n,t),!1;case 1:if(e=n.type,s=n.stateNode,(n.flags&128)===0&&(typeof e.getDerivedStateFromError=="function"||s!==null&&typeof s.componentDidCatch=="function"&&(cl===null||!cl.has(s))))return n.flags|=65536,i&=-i,n.lanes|=i,i=AN(i),RN(i,t,n,r),y_(n,i),!1}n=n.return}while(n!==null);return!1}var CN=Error(Ue(461)),wr=!1;function Ir(t,e,n,r){e.child=t===null?xN(e,null,n,r):$d(e,t.child,n,r)}function yR(t,e,n,r,i){n=n.render;var s=e.ref;if("ref"in r){var a={};for(var o in r)o!=="ref"&&(a[o]=r[o])}else a=r;return Dc(e),r=Pw(t,e,n,a,s,i),o=Dw(),t!==null&&!wr?(Ow(t,e,i),ao(t,e,i)):(Zt&&o&&Tw(e),e.flags|=1,Ir(t,e,r,i),e.child)}function vR(t,e,n,r,i){if(t===null){var s=n.type;return typeof s=="function"&&!ww(s)&&s.defaultProps===void 0&&n.compare===null?(e.tag=15,e.type=s,LN(t,e,s,r,i)):(t=Bg(n.type,null,r,e,e.mode,i),t.ref=e.ref,t.return=e,e.child=t)}if(s=t.child,!Gw(t,i)){var a=s.memoizedProps;if(n=n.compare,n=n!==null?n:Hf,n(a,r)&&t.ref===e.ref)return ao(t,e,i)}return e.flags|=1,t=eo(s,r),t.ref=e.ref,t.return=e,e.child=t}function LN(t,e,n,r,i){if(t!==null){var s=t.memoizedProps;if(Hf(s,r)&&t.ref===e.ref)if(wr=!1,e.pendingProps=r=s,Gw(t,i))t.flags&131072&&(wr=!0);else return e.lanes=t.lanes,ao(t,e,i)}return jx(t,e,n,r,i)}function kN(t,e,n){var r=e.pendingProps,i=r.children,s=t!==null?t.memoizedState:null;if(r.mode==="hidden"){if(e.flags&128){if(r=s!==null?s.baseLanes|n:n,t!==null){for(i=e.child=t.child,s=0;i!==null;)s=s|i.lanes|i.childLanes,i=i.sibling;e.childLanes=s&~r}else e.childLanes=0,e.child=null;return _R(t,e,r,n)}if(n&536870912)e.memoizedState={baseLanes:0,cachePool:null},t!==null&&Ug(e,s!==null?s.cachePool:null),s!==null?aR(e,s):Dx(),SN(e);else return e.lanes=e.childLanes=536870912,_R(t,e,s!==null?s.baseLanes|n:n,n)}else s!==null?(Ug(e,s.cachePool),aR(e,s),$o(),e.memoizedState=null):(t!==null&&Ug(e,null),Dx(),$o());return Ir(t,e,i,n),e.child}function _R(t,e,n,r){var i=Cw();return i=i===null?null:{parent:fr._currentValue,pool:i},e.memoizedState={baseLanes:n,cachePool:i},t!==null&&Ug(e,null),Dx(),SN(e),t!==null&&Gp(t,e,r,!0),null}function $g(t,e){var n=e.ref;if(n===null)t!==null&&t.ref!==null&&(e.flags|=4194816);else{if(typeof n!="function"&&typeof n!="object")throw Error(Ue(284));(t===null||t.ref!==n)&&(e.flags|=4194816)}}function jx(t,e,n,r,i){return Dc(e),n=Pw(t,e,n,r,void 0,i),r=Dw(),t!==null&&!wr?(Ow(t,e,i),ao(t,e,i)):(Zt&&r&&Tw(e),e.flags|=1,Ir(t,e,n,i),e.child)}function bR(t,e,n,r,i,s){return Dc(e),e.updateQueue=null,n=GO(e,r,n,i),VO(t),r=Dw(),t!==null&&!wr?(Ow(t,e,s),ao(t,e,s)):(Zt&&r&&Tw(e),e.flags|=1,Ir(t,e,n,s),e.child)}function xR(t,e,n,r,i){if(Dc(e),e.stateNode===null){var s=qu,a=n.contextType;typeof a=="object"&&a!==null&&(s=Kr(a)),s=new n(r,s),e.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,s.updater=Bx,e.stateNode=s,s._reactInternals=e,s=e.stateNode,s.props=r,s.state=e.memoizedState,s.refs={},Lw(e),a=n.contextType,s.context=typeof a=="object"&&a!==null?Kr(a):qu,s.state=e.memoizedState,a=n.getDerivedStateFromProps,typeof a=="function"&&(__(e,n,a,r),s.state=e.memoizedState),typeof n.getDerivedStateFromProps=="function"||typeof s.getSnapshotBeforeUpdate=="function"||typeof s.UNSAFE_componentWillMount!="function"&&typeof s.componentWillMount!="function"||(a=s.state,typeof s.componentWillMount=="function"&&s.componentWillMount(),typeof s.UNSAFE_componentWillMount=="function"&&s.UNSAFE_componentWillMount(),a!==s.state&&Bx.enqueueReplaceState(s,s.state,null),pf(e,r,s,i),ff(),s.state=e.memoizedState),typeof s.componentDidMount=="function"&&(e.flags|=4194308),r=!0}else if(t===null){s=e.stateNode;var o=e.memoizedProps,l=Nc(n,o);s.props=l;var c=s.context,u=n.contextType;a=qu,typeof u=="object"&&u!==null&&(a=Kr(u));var d=n.getDerivedStateFromProps;u=typeof d=="function"||typeof s.getSnapshotBeforeUpdate=="function",o=e.pendingProps!==o,u||typeof s.UNSAFE_componentWillReceiveProps!="function"&&typeof s.componentWillReceiveProps!="function"||(o||c!==a)&&mR(e,s,r,a),No=!1;var h=e.memoizedState;s.state=h,pf(e,r,s,i),ff(),c=e.memoizedState,o||h!==c||No?(typeof d=="function"&&(__(e,n,d,r),c=e.memoizedState),(l=No||pR(e,n,l,r,h,c,a))?(u||typeof s.UNSAFE_componentWillMount!="function"&&typeof s.componentWillMount!="function"||(typeof s.componentWillMount=="function"&&s.componentWillMount(),typeof s.UNSAFE_componentWillMount=="function"&&s.UNSAFE_componentWillMount()),typeof s.componentDidMount=="function"&&(e.flags|=4194308)):(typeof s.componentDidMount=="function"&&(e.flags|=4194308),e.memoizedProps=r,e.memoizedState=c),s.props=r,s.state=c,s.context=a,r=l):(typeof s.componentDidMount=="function"&&(e.flags|=4194308),r=!1)}else{s=e.stateNode,Ix(t,e),a=e.memoizedProps,u=Nc(n,a),s.props=u,d=e.pendingProps,h=s.context,c=n.contextType,l=qu,typeof c=="object"&&c!==null&&(l=Kr(c)),o=n.getDerivedStateFromProps,(c=typeof o=="function"||typeof s.getSnapshotBeforeUpdate=="function")||typeof s.UNSAFE_componentWillReceiveProps!="function"&&typeof s.componentWillReceiveProps!="function"||(a!==d||h!==l)&&mR(e,s,r,l),No=!1,h=e.memoizedState,s.state=h,pf(e,r,s,i),ff();var f=e.memoizedState;a!==d||h!==f||No||t!==null&&t.dependencies!==null&&wy(t.dependencies)?(typeof o=="function"&&(__(e,n,o,r),f=e.memoizedState),(u=No||pR(e,n,u,r,h,f,l)||t!==null&&t.dependencies!==null&&wy(t.dependencies))?(c||typeof s.UNSAFE_componentWillUpdate!="function"&&typeof s.componentWillUpdate!="function"||(typeof s.componentWillUpdate=="function"&&s.componentWillUpdate(r,f,l),typeof s.UNSAFE_componentWillUpdate=="function"&&s.UNSAFE_componentWillUpdate(r,f,l)),typeof s.componentDidUpdate=="function"&&(e.flags|=4),typeof s.getSnapshotBeforeUpdate=="function"&&(e.flags|=1024)):(typeof s.componentDidUpdate!="function"||a===t.memoizedProps&&h===t.memoizedState||(e.flags|=4),typeof s.getSnapshotBeforeUpdate!="function"||a===t.memoizedProps&&h===t.memoizedState||(e.flags|=1024),e.memoizedProps=r,e.memoizedState=f),s.props=r,s.state=f,s.context=l,r=u):(typeof s.componentDidUpdate!="function"||a===t.memoizedProps&&h===t.memoizedState||(e.flags|=4),typeof s.getSnapshotBeforeUpdate!="function"||a===t.memoizedProps&&h===t.memoizedState||(e.flags|=1024),r=!1)}return s=r,$g(t,e),r=(e.flags&128)!==0,s||r?(s=e.stateNode,n=r&&typeof n.getDerivedStateFromError!="function"?null:s.render(),e.flags|=1,t!==null&&r?(e.child=$d(e,t.child,null,i),e.child=$d(e,null,n,i)):Ir(t,e,n,i),e.memoizedState=s.state,t=e.child):t=ao(t,e,i),t}function SR(t,e,n,r){return Vp(),e.flags|=256,Ir(t,e,n,r),e.child}var b_={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function x_(t){return{baseLanes:t,cachePool:BO()}}function S_(t,e,n){return t=t!==null?t.childLanes&~n:0,e&&(t|=ds),t}function IN(t,e,n){var r=e.pendingProps,i=!1,s=(e.flags&128)!==0,a;if((a=s)||(a=t!==null&&t.memoizedState===null?!1:(mr.current&2)!==0),a&&(i=!0,e.flags&=-129),a=(e.flags&32)!==0,e.flags&=-33,t===null){if(Zt){if(i?Fo(e):$o(),Zt){var o=Kn,l;if(l=o){e:{for(l=o,o=ea;l.nodeType!==8;){if(!o){o=null;break e}if(l=Is(l.nextSibling),l===null){o=null;break e}}o=l}o!==null?(e.memoizedState={dehydrated:o,treeContext:Sc!==null?{id:Xa,overflow:Qa}:null,retryLane:536870912,hydrationErrors:null},l=Bi(18,null,null,0),l.stateNode=o,l.return=e,e.child=l,ei=e,Kn=null,l=!0):l=!1}l||Pc(e)}if(o=e.memoizedState,o!==null&&(o=o.dehydrated,o!==null))return Zx(o)?e.lanes=32:e.lanes=536870912,null;Za(e)}return o=r.children,r=r.fallback,i?($o(),i=e.mode,o=Py({mode:"hidden",children:o},i),r=xc(r,i,n,null),o.return=e,r.return=e,o.sibling=r,e.child=o,i=e.child,i.memoizedState=x_(n),i.childLanes=S_(t,a,n),e.memoizedState=b_,r):(Fo(e),Fx(e,o))}if(l=t.memoizedState,l!==null&&(o=l.dehydrated,o!==null)){if(s)e.flags&256?(Fo(e),e.flags&=-257,e=E_(t,e,n)):e.memoizedState!==null?($o(),e.child=t.child,e.flags|=128,e=null):($o(),i=r.fallback,o=e.mode,r=Py({mode:"visible",children:r.children},o),i=xc(i,o,n,null),i.flags|=2,r.return=e,i.return=e,r.sibling=i,e.child=r,$d(e,t.child,null,n),r=e.child,r.memoizedState=x_(n),r.childLanes=S_(t,a,n),e.memoizedState=b_,e=i);else if(Fo(e),Zx(o)){if(a=o.nextSibling&&o.nextSibling.dataset,a)var c=a.dgst;a=c,r=Error(Ue(419)),r.stack="",r.digest=a,Kf({value:r,source:null,stack:null}),e=E_(t,e,n)}else if(wr||Gp(t,e,n,!1),a=(n&t.childLanes)!==0,wr||a){if(a=xn,a!==null&&(r=n&-n,r=r&42?1:fw(r),r=r&(a.suspendedLanes|n)?0:r,r!==0&&r!==l.retryLane))throw l.retryLane=r,ah(t,r),Vi(a,t,r),CN;o.data==="$?"||zx(),e=E_(t,e,n)}else o.data==="$?"?(e.flags|=192,e.child=t.child,e=null):(t=l.treeContext,Kn=Is(o.nextSibling),ei=e,Zt=!0,Ec=null,ea=!1,t!==null&&(os[ls++]=Xa,os[ls++]=Qa,os[ls++]=Sc,Xa=t.id,Qa=t.overflow,Sc=e),e=Fx(e,r.children),e.flags|=4096);return e}return i?($o(),i=r.fallback,o=e.mode,l=t.child,c=l.sibling,r=eo(l,{mode:"hidden",children:r.children}),r.subtreeFlags=l.subtreeFlags&65011712,c!==null?i=eo(c,i):(i=xc(i,o,n,null),i.flags|=2),i.return=e,r.return=e,r.sibling=i,e.child=r,r=i,i=e.child,o=t.child.memoizedState,o===null?o=x_(n):(l=o.cachePool,l!==null?(c=fr._currentValue,l=l.parent!==c?{parent:c,pool:c}:l):l=BO(),o={baseLanes:o.baseLanes|n,cachePool:l}),i.memoizedState=o,i.childLanes=S_(t,a,n),e.memoizedState=b_,r):(Fo(e),n=t.child,t=n.sibling,n=eo(n,{mode:"visible",children:r.children}),n.return=e,n.sibling=null,t!==null&&(a=e.deletions,a===null?(e.deletions=[t],e.flags|=16):a.push(t)),e.child=n,e.memoizedState=null,n)}function Fx(t,e){return e=Py({mode:"visible",children:e},t.mode),e.return=t,t.child=e}function Py(t,e){return t=Bi(22,t,null,e),t.lanes=0,t.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null},t}function E_(t,e,n){return $d(e,t.child,null,n),t=Fx(e,e.pendingProps.children),t.flags|=2,e.memoizedState=null,t}function ER(t,e,n){t.lanes|=e;var r=t.alternate;r!==null&&(r.lanes|=e),Rx(t.return,e,n)}function w_(t,e,n,r,i){var s=t.memoizedState;s===null?t.memoizedState={isBackwards:e,rendering:null,renderingStartTime:0,last:r,tail:n,tailMode:i}:(s.isBackwards=e,s.rendering=null,s.renderingStartTime=0,s.last=r,s.tail=n,s.tailMode=i)}function PN(t,e,n){var r=e.pendingProps,i=r.revealOrder,s=r.tail;if(Ir(t,e,r.children,n),r=mr.current,r&2)r=r&1|2,e.flags|=128;else{if(t!==null&&t.flags&128)e:for(t=e.child;t!==null;){if(t.tag===13)t.memoizedState!==null&&ER(t,n,e);else if(t.tag===19)ER(t,n,e);else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break e;for(;t.sibling===null;){if(t.return===null||t.return===e)break e;t=t.return}t.sibling.return=t.return,t=t.sibling}r&=1}switch(Pn(mr,r),i){case"forwards":for(n=e.child,i=null;n!==null;)t=n.alternate,t!==null&&Ly(t)===null&&(i=n),n=n.sibling;n=i,n===null?(i=e.child,e.child=null):(i=n.sibling,n.sibling=null),w_(e,!1,i,n,s);break;case"backwards":for(n=null,i=e.child,e.child=null;i!==null;){if(t=i.alternate,t!==null&&Ly(t)===null){e.child=i;break}t=i.sibling,i.sibling=n,n=i,i=t}w_(e,!0,n,null,s);break;case"together":w_(e,!1,null,null,void 0);break;default:e.memoizedState=null}return e.child}function ao(t,e,n){if(t!==null&&(e.dependencies=t.dependencies),bl|=e.lanes,!(n&e.childLanes))if(t!==null){if(Gp(t,e,n,!1),(n&e.childLanes)===0)return null}else return null;if(t!==null&&e.child!==t.child)throw Error(Ue(153));if(e.child!==null){for(t=e.child,n=eo(t,t.pendingProps),e.child=n,n.return=e;t.sibling!==null;)t=t.sibling,n=n.sibling=eo(t,t.pendingProps),n.return=e;n.sibling=null}return e.child}function Gw(t,e){return t.lanes&e?!0:(t=t.dependencies,!!(t!==null&&wy(t)))}function d8(t,e,n){switch(e.tag){case 3:gy(e,e.stateNode.containerInfo),jo(e,fr,t.memoizedState.cache),Vp();break;case 27:case 5:mx(e);break;case 4:gy(e,e.stateNode.containerInfo);break;case 10:jo(e,e.type,e.memoizedProps.value);break;case 13:var r=e.memoizedState;if(r!==null)return r.dehydrated!==null?(Fo(e),e.flags|=128,null):n&e.child.childLanes?IN(t,e,n):(Fo(e),t=ao(t,e,n),t!==null?t.sibling:null);Fo(e);break;case 19:var i=(t.flags&128)!==0;if(r=(n&e.childLanes)!==0,r||(Gp(t,e,n,!1),r=(n&e.childLanes)!==0),i){if(r)return PN(t,e,n);e.flags|=128}if(i=e.memoizedState,i!==null&&(i.rendering=null,i.tail=null,i.lastEffect=null),Pn(mr,mr.current),r)break;return null;case 22:case 23:return e.lanes=0,kN(t,e,n);case 24:jo(e,fr,t.memoizedState.cache)}return ao(t,e,n)}function DN(t,e,n){if(t!==null)if(t.memoizedProps!==e.pendingProps)wr=!0;else{if(!Gw(t,n)&&!(e.flags&128))return wr=!1,d8(t,e,n);wr=!!(t.flags&131072)}else wr=!1,Zt&&e.flags&1048576&&NO(e,Ey,e.index);switch(e.lanes=0,e.tag){case 16:e:{t=e.pendingProps;var r=e.elementType,i=r._init;if(r=i(r._payload),e.type=r,typeof r=="function")ww(r)?(t=Nc(r,t),e.tag=1,e=xR(null,e,r,t,n)):(e.tag=0,e=jx(null,e,r,t,n));else{if(r!=null){if(i=r.$$typeof,i===uw){e.tag=11,e=yR(null,e,r,t,n);break e}else if(i===dw){e.tag=14,e=vR(null,e,r,t,n);break e}}throw e=fx(r)||r,Error(Ue(306,e,""))}}return e;case 0:return jx(t,e,e.type,e.pendingProps,n);case 1:return r=e.type,i=Nc(r,e.pendingProps),xR(t,e,r,i,n);case 3:e:{if(gy(e,e.stateNode.containerInfo),t===null)throw Error(Ue(387));r=e.pendingProps;var s=e.memoizedState;i=s.element,Ix(t,e),pf(e,r,null,n);var a=e.memoizedState;if(r=a.cache,jo(e,fr,r),r!==s.cache&&Cx(e,[fr],n,!0),ff(),r=a.element,s.isDehydrated)if(s={element:r,isDehydrated:!1,cache:a.cache},e.updateQueue.baseState=s,e.memoizedState=s,e.flags&256){e=SR(t,e,r,n);break e}else if(r!==i){i=us(Error(Ue(424)),e),Kf(i),e=SR(t,e,r,n);break e}else{switch(t=e.stateNode.containerInfo,t.nodeType){case 9:t=t.body;break;default:t=t.nodeName==="HTML"?t.ownerDocument.body:t}for(Kn=Is(t.firstChild),ei=e,Zt=!0,Ec=null,ea=!0,n=xN(e,null,r,n),e.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling}else{if(Vp(),r===i){e=ao(t,e,n);break e}Ir(t,e,r,n)}e=e.child}return e;case 26:return $g(t,e),t===null?(n=FR(e.type,null,e.pendingProps,null))?e.memoizedState=n:Zt||(n=e.type,t=e.pendingProps,r=jy(al.current).createElement(n),r[Hr]=e,r[xi]=t,Ur(r,n,t),Er(r),e.stateNode=r):e.memoizedState=FR(e.type,t.memoizedProps,e.pendingProps,t.memoizedState),null;case 27:return mx(e),t===null&&Zt&&(r=e.stateNode=_M(e.type,e.pendingProps,al.current),ei=e,ea=!0,i=Kn,Il(e.type)?(eS=i,Kn=Is(r.firstChild)):Kn=i),Ir(t,e,e.pendingProps.children,n),$g(t,e),t===null&&(e.flags|=4194304),e.child;case 5:return t===null&&Zt&&((i=r=Kn)&&(r=j8(r,e.type,e.pendingProps,ea),r!==null?(e.stateNode=r,ei=e,Kn=Is(r.firstChild),ea=!1,i=!0):i=!1),i||Pc(e)),mx(e),i=e.type,s=e.pendingProps,a=t!==null?t.memoizedProps:null,r=s.children,Qx(i,s)?r=null:a!==null&&Qx(i,a)&&(e.flags|=32),e.memoizedState!==null&&(i=Pw(t,e,r8,null,null,n),Qf._currentValue=i),$g(t,e),Ir(t,e,r,n),e.child;case 6:return t===null&&Zt&&((t=n=Kn)&&(n=F8(n,e.pendingProps,ea),n!==null?(e.stateNode=n,ei=e,Kn=null,t=!0):t=!1),t||Pc(e)),null;case 13:return IN(t,e,n);case 4:return gy(e,e.stateNode.containerInfo),r=e.pendingProps,t===null?e.child=$d(e,null,r,n):Ir(t,e,r,n),e.child;case 11:return yR(t,e,e.type,e.pendingProps,n);case 7:return Ir(t,e,e.pendingProps,n),e.child;case 8:return Ir(t,e,e.pendingProps.children,n),e.child;case 12:return Ir(t,e,e.pendingProps.children,n),e.child;case 10:return r=e.pendingProps,jo(e,e.type,r.value),Ir(t,e,r.children,n),e.child;case 9:return i=e.type._context,r=e.pendingProps.children,Dc(e),i=Kr(i),r=r(i),e.flags|=1,Ir(t,e,r,n),e.child;case 14:return vR(t,e,e.type,e.pendingProps,n);case 15:return LN(t,e,e.type,e.pendingProps,n);case 19:return PN(t,e,n);case 31:return r=e.pendingProps,n=e.mode,r={mode:r.mode,children:r.children},t===null?(n=Py(r,n),n.ref=e.ref,e.child=n,n.return=e,e=n):(n=eo(t.child,r),n.ref=e.ref,e.child=n,n.return=e,e=n),e;case 22:return kN(t,e,n);case 24:return Dc(e),r=Kr(fr),t===null?(i=Cw(),i===null&&(i=xn,s=Rw(),i.pooledCache=s,s.refCount++,s!==null&&(i.pooledCacheLanes|=n),i=s),e.memoizedState={parent:r,cache:i},Lw(e),jo(e,fr,i)):(t.lanes&n&&(Ix(t,e),pf(e,null,null,n),ff()),i=t.memoizedState,s=e.memoizedState,i.parent!==r?(i={parent:r,cache:r},e.memoizedState=i,e.lanes===0&&(e.memoizedState=e.updateQueue.baseState=i),jo(e,fr,r)):(r=s.cache,jo(e,fr,r),r!==i.cache&&Cx(e,[fr],n,!0))),Ir(t,e,e.pendingProps.children,n),e.child;case 29:throw e.pendingProps}throw Error(Ue(156,e.tag))}function ka(t){t.flags|=4}function wR(t,e){if(e.type!=="stylesheet"||e.state.loading&4)t.flags&=-16777217;else if(t.flags|=16777216,!SM(e)){if(e=ms.current,e!==null&&((Qt&4194048)===Qt?ua!==null:(Qt&62914560)!==Qt&&!(Qt&536870912)||e!==ua))throw df=kx,UO;t.flags|=8192}}function Fm(t,e){e!==null&&(t.flags|=4),t.flags&16384&&(e=t.tag!==22?sO():536870912,t.lanes|=e,Vd|=e)}function Mh(t,e){if(!Zt)switch(t.tailMode){case"hidden":e=t.tail;for(var n=null;e!==null;)e.alternate!==null&&(n=e),e=e.sibling;n===null?t.tail=null:n.sibling=null;break;case"collapsed":n=t.tail;for(var r=null;n!==null;)n.alternate!==null&&(r=n),n=n.sibling;r===null?e||t.tail===null?t.tail=null:t.tail.sibling=null:r.sibling=null}}function Nn(t){var e=t.alternate!==null&&t.alternate.child===t.child,n=0,r=0;if(e)for(var i=t.child;i!==null;)n|=i.lanes|i.childLanes,r|=i.subtreeFlags&65011712,r|=i.flags&65011712,i.return=t,i=i.sibling;else for(i=t.child;i!==null;)n|=i.lanes|i.childLanes,r|=i.subtreeFlags,r|=i.flags,i.return=t,i=i.sibling;return t.subtreeFlags|=r,t.childLanes=n,e}function h8(t,e,n){var r=e.pendingProps;switch(Aw(e),e.tag){case 31:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Nn(e),null;case 1:return Nn(e),null;case 3:return n=e.stateNode,r=null,t!==null&&(r=t.memoizedState.cache),e.memoizedState.cache!==r&&(e.flags|=2048),to(fr),Nd(),n.pendingContext&&(n.context=n.pendingContext,n.pendingContext=null),(t===null||t.child===null)&&(Oh(e)?ka(e):t===null||t.memoizedState.isDehydrated&&!(e.flags&256)||(e.flags|=1024,eR())),Nn(e),null;case 26:return n=e.memoizedState,t===null?(ka(e),n!==null?(Nn(e),wR(e,n)):(Nn(e),e.flags&=-16777217)):n?n!==t.memoizedState?(ka(e),Nn(e),wR(e,n)):(Nn(e),e.flags&=-16777217):(t.memoizedProps!==r&&ka(e),Nn(e),e.flags&=-16777217),null;case 27:yy(e),n=al.current;var i=e.type;if(t!==null&&e.stateNode!=null)t.memoizedProps!==r&&ka(e);else{if(!r){if(e.stateNode===null)throw Error(Ue(166));return Nn(e),null}t=la.current,Oh(e)?J1(e):(t=_M(i,r,n),e.stateNode=t,ka(e))}return Nn(e),null;case 5:if(yy(e),n=e.type,t!==null&&e.stateNode!=null)t.memoizedProps!==r&&ka(e);else{if(!r){if(e.stateNode===null)throw Error(Ue(166));return Nn(e),null}if(t=la.current,Oh(e))J1(e);else{switch(i=jy(al.current),t){case 1:t=i.createElementNS("http://www.w3.org/2000/svg",n);break;case 2:t=i.createElementNS("http://www.w3.org/1998/Math/MathML",n);break;default:switch(n){case"svg":t=i.createElementNS("http://www.w3.org/2000/svg",n);break;case"math":t=i.createElementNS("http://www.w3.org/1998/Math/MathML",n);break;case"script":t=i.createElement("div"),t.innerHTML="<script><\/script>",t=t.removeChild(t.firstChild);break;case"select":t=typeof r.is=="string"?i.createElement("select",{is:r.is}):i.createElement("select"),r.multiple?t.multiple=!0:r.size&&(t.size=r.size);break;default:t=typeof r.is=="string"?i.createElement(n,{is:r.is}):i.createElement(n)}}t[Hr]=e,t[xi]=r;e:for(i=e.child;i!==null;){if(i.tag===5||i.tag===6)t.appendChild(i.stateNode);else if(i.tag!==4&&i.tag!==27&&i.child!==null){i.child.return=i,i=i.child;continue}if(i===e)break e;for(;i.sibling===null;){if(i.return===null||i.return===e)break e;i=i.return}i.sibling.return=i.return,i=i.sibling}e.stateNode=t;e:switch(Ur(t,n,r),n){case"button":case"input":case"select":case"textarea":t=!!r.autoFocus;break e;case"img":t=!0;break e;default:t=!1}t&&ka(e)}}return Nn(e),e.flags&=-16777217,null;case 6:if(t&&e.stateNode!=null)t.memoizedProps!==r&&ka(e);else{if(typeof r!="string"&&e.stateNode===null)throw Error(Ue(166));if(t=al.current,Oh(e)){if(t=e.stateNode,n=e.memoizedProps,r=null,i=ei,i!==null)switch(i.tag){case 27:case 5:r=i.memoizedProps}t[Hr]=e,t=!!(t.nodeValue===n||r!==null&&r.suppressHydrationWarning===!0||gM(t.nodeValue,n)),t||Pc(e)}else t=jy(t).createTextNode(r),t[Hr]=e,e.stateNode=t}return Nn(e),null;case 13:if(r=e.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(i=Oh(e),r!==null&&r.dehydrated!==null){if(t===null){if(!i)throw Error(Ue(318));if(i=e.memoizedState,i=i!==null?i.dehydrated:null,!i)throw Error(Ue(317));i[Hr]=e}else Vp(),!(e.flags&128)&&(e.memoizedState=null),e.flags|=4;Nn(e),i=!1}else i=eR(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=i),i=!0;if(!i)return e.flags&256?(Za(e),e):(Za(e),null)}if(Za(e),e.flags&128)return e.lanes=n,e;if(n=r!==null,t=t!==null&&t.memoizedState!==null,n){r=e.child,i=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(i=r.alternate.memoizedState.cachePool.pool);var s=null;r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(s=r.memoizedState.cachePool.pool),s!==i&&(r.flags|=2048)}return n!==t&&n&&(e.child.flags|=8192),Fm(e,e.updateQueue),Nn(e),null;case 4:return Nd(),t===null&&Qw(e.stateNode.containerInfo),Nn(e),null;case 10:return to(e.type),Nn(e),null;case 19:if(Tr(mr),i=e.memoizedState,i===null)return Nn(e),null;if(r=(e.flags&128)!==0,s=i.rendering,s===null)if(r)Mh(i,!1);else{if(zn!==0||t!==null&&t.flags&128)for(t=e.child;t!==null;){if(s=Ly(t),s!==null){for(e.flags|=128,Mh(i,!1),t=s.updateQueue,e.updateQueue=t,Fm(e,t),e.subtreeFlags=0,t=n,n=e.child;n!==null;)OO(n,t),n=n.sibling;return Pn(mr,mr.current&1|2),e.child}t=t.sibling}i.tail!==null&&ca()>Oy&&(e.flags|=128,r=!0,Mh(i,!1),e.lanes=4194304)}else{if(!r)if(t=Ly(s),t!==null){if(e.flags|=128,r=!0,t=t.updateQueue,e.updateQueue=t,Fm(e,t),Mh(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Zt)return Nn(e),null}else 2*ca()-i.renderingStartTime>Oy&&n!==536870912&&(e.flags|=128,r=!0,Mh(i,!1),e.lanes=4194304);i.isBackwards?(s.sibling=e.child,e.child=s):(t=i.last,t!==null?t.sibling=s:e.child=s,i.last=s)}return i.tail!==null?(e=i.tail,i.rendering=e,i.tail=e.sibling,i.renderingStartTime=ca(),e.sibling=null,t=mr.current,Pn(mr,r?t&1|2:t&1),e):(Nn(e),null);case 22:case 23:return Za(e),kw(),r=e.memoizedState!==null,t!==null?t.memoizedState!==null!==r&&(e.flags|=8192):r&&(e.flags|=8192),r?n&536870912&&!(e.flags&128)&&(Nn(e),e.subtreeFlags&6&&(e.flags|=8192)):Nn(e),n=e.updateQueue,n!==null&&Fm(e,n.retryQueue),n=null,t!==null&&t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(n=t.memoizedState.cachePool.pool),r=null,e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(r=e.memoizedState.cachePool.pool),r!==n&&(e.flags|=2048),t!==null&&Tr(wc),null;case 24:return n=null,t!==null&&(n=t.memoizedState.cache),e.memoizedState.cache!==n&&(e.flags|=2048),to(fr),Nn(e),null;case 25:return null;case 30:return null}throw Error(Ue(156,e.tag))}function f8(t,e){switch(Aw(e),e.tag){case 1:return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return to(fr),Nd(),t=e.flags,t&65536&&!(t&128)?(e.flags=t&-65537|128,e):null;case 26:case 27:case 5:return yy(e),null;case 13:if(Za(e),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(Ue(340));Vp()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return Tr(mr),null;case 4:return Nd(),null;case 10:return to(e.type),null;case 22:case 23:return Za(e),kw(),t!==null&&Tr(wc),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 24:return to(fr),null;case 25:return null;default:return null}}function ON(t,e){switch(Aw(e),e.tag){case 3:to(fr),Nd();break;case 26:case 27:case 5:yy(e);break;case 4:Nd();break;case 13:Za(e);break;case 19:Tr(mr);break;case 10:to(e.type);break;case 22:case 23:Za(e),kw(),t!==null&&Tr(wc);break;case 24:to(fr)}}function Wp(t,e){try{var n=e.updateQueue,r=n!==null?n.lastEffect:null;if(r!==null){var i=r.next;n=i;do{if((n.tag&t)===t){r=void 0;var s=n.create,a=n.inst;r=s(),a.destroy=r}n=n.next}while(n!==i)}}catch(o){mn(e,e.return,o)}}function _l(t,e,n){try{var r=e.updateQueue,i=r!==null?r.lastEffect:null;if(i!==null){var s=i.next;r=s;do{if((r.tag&t)===t){var a=r.inst,o=a.destroy;if(o!==void 0){a.destroy=void 0,i=e;var l=n,c=o;try{c()}catch(u){mn(i,l,u)}}}r=r.next}while(r!==s)}}catch(u){mn(e,e.return,u)}}function NN(t){var e=t.updateQueue;if(e!==null){var n=t.stateNode;try{$O(e,n)}catch(r){mn(t,t.return,r)}}}function MN(t,e,n){n.props=Nc(t.type,t.memoizedProps),n.state=t.memoizedState;try{n.componentWillUnmount()}catch(r){mn(t,e,r)}}function gf(t,e){try{var n=t.ref;if(n!==null){switch(t.tag){case 26:case 27:case 5:var r=t.stateNode;break;case 30:r=t.stateNode;break;default:r=t.stateNode}typeof n=="function"?t.refCleanup=n(r):n.current=r}}catch(i){mn(t,e,i)}}function na(t,e){var n=t.ref,r=t.refCleanup;if(n!==null)if(typeof r=="function")try{r()}catch(i){mn(t,e,i)}finally{t.refCleanup=null,t=t.alternate,t!=null&&(t.refCleanup=null)}else if(typeof n=="function")try{n(null)}catch(i){mn(t,e,i)}else n.current=null}function BN(t){var e=t.type,n=t.memoizedProps,r=t.stateNode;try{e:switch(e){case"button":case"input":case"select":case"textarea":n.autoFocus&&r.focus();break e;case"img":n.src?r.src=n.src:n.srcSet&&(r.srcset=n.srcSet)}}catch(i){mn(t,t.return,i)}}function T_(t,e,n){try{var r=t.stateNode;O8(r,t.type,n,e),r[xi]=e}catch(i){mn(t,t.return,i)}}function UN(t){return t.tag===5||t.tag===3||t.tag===26||t.tag===27&&Il(t.type)||t.tag===4}function A_(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||UN(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.tag===27&&Il(t.type)||t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function $x(t,e,n){var r=t.tag;if(r===5||r===6)t=t.stateNode,e?(n.nodeType===9?n.body:n.nodeName==="HTML"?n.ownerDocument.body:n).insertBefore(t,e):(e=n.nodeType===9?n.body:n.nodeName==="HTML"?n.ownerDocument.body:n,e.appendChild(t),n=n._reactRootContainer,n!=null||e.onclick!==null||(e.onclick=q0));else if(r!==4&&(r===27&&Il(t.type)&&(n=t.stateNode,e=null),t=t.child,t!==null))for($x(t,e,n),t=t.sibling;t!==null;)$x(t,e,n),t=t.sibling}function Dy(t,e,n){var r=t.tag;if(r===5||r===6)t=t.stateNode,e?n.insertBefore(t,e):n.appendChild(t);else if(r!==4&&(r===27&&Il(t.type)&&(n=t.stateNode),t=t.child,t!==null))for(Dy(t,e,n),t=t.sibling;t!==null;)Dy(t,e,n),t=t.sibling}function jN(t){var e=t.stateNode,n=t.memoizedProps;try{for(var r=t.type,i=e.attributes;i.length;)e.removeAttributeNode(i[0]);Ur(e,r,n),e[Hr]=t,e[xi]=n}catch(s){mn(t,t.return,s)}}var Wa=!1,Jn=!1,R_=!1,TR=typeof WeakSet=="function"?WeakSet:Set,Sr=null;function p8(t,e){if(t=t.containerInfo,Yx=Gy,t=AO(t),xw(t)){if("selectionStart"in t)var n={start:t.selectionStart,end:t.selectionEnd};else e:{n=(n=t.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var i=r.anchorOffset,s=r.focusNode;r=r.focusOffset;try{n.nodeType,s.nodeType}catch{n=null;break e}var a=0,o=-1,l=-1,c=0,u=0,d=t,h=null;t:for(;;){for(var f;d!==n||i!==0&&d.nodeType!==3||(o=a+i),d!==s||r!==0&&d.nodeType!==3||(l=a+r),d.nodeType===3&&(a+=d.nodeValue.length),(f=d.firstChild)!==null;)h=d,d=f;for(;;){if(d===t)break t;if(h===n&&++c===i&&(o=a),h===s&&++u===r&&(l=a),(f=d.nextSibling)!==null)break;d=h,h=d.parentNode}d=f}n=o===-1||l===-1?null:{start:o,end:l}}else n=null}n=n||{start:0,end:0}}else n=null;for(Xx={focusedElem:t,selectionRange:n},Gy=!1,Sr=e;Sr!==null;)if(e=Sr,t=e.child,(e.subtreeFlags&1024)!==0&&t!==null)t.return=e,Sr=t;else for(;Sr!==null;){switch(e=Sr,s=e.alternate,t=e.flags,e.tag){case 0:break;case 11:case 15:break;case 1:if(t&1024&&s!==null){t=void 0,n=e,i=s.memoizedProps,s=s.memoizedState,r=n.stateNode;try{var p=Nc(n.type,i,n.elementType===n.type);t=r.getSnapshotBeforeUpdate(p,s),r.__reactInternalSnapshotBeforeUpdate=t}catch(m){mn(n,n.return,m)}}break;case 3:if(t&1024){if(t=e.stateNode.containerInfo,n=t.nodeType,n===9)Jx(t);else if(n===1)switch(t.nodeName){case"HEAD":case"HTML":case"BODY":Jx(t);break;default:t.textContent=""}}break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if(t&1024)throw Error(Ue(163))}if(t=e.sibling,t!==null){t.return=e.return,Sr=t;break}Sr=e.return}}function FN(t,e,n){var r=n.flags;switch(n.tag){case 0:case 11:case 15:wo(t,n),r&4&&Wp(5,n);break;case 1:if(wo(t,n),r&4)if(t=n.stateNode,e===null)try{t.componentDidMount()}catch(a){mn(n,n.return,a)}else{var i=Nc(n.type,e.memoizedProps);e=e.memoizedState;try{t.componentDidUpdate(i,e,t.__reactInternalSnapshotBeforeUpdate)}catch(a){mn(n,n.return,a)}}r&64&&NN(n),r&512&&gf(n,n.return);break;case 3:if(wo(t,n),r&64&&(t=n.updateQueue,t!==null)){if(e=null,n.child!==null)switch(n.child.tag){case 27:case 5:e=n.child.stateNode;break;case 1:e=n.child.stateNode}try{$O(t,e)}catch(a){mn(n,n.return,a)}}break;case 27:e===null&&r&4&&jN(n);case 26:case 5:wo(t,n),e===null&&r&4&&BN(n),r&512&&gf(n,n.return);break;case 12:wo(t,n);break;case 13:wo(t,n),r&4&&GN(t,n),r&64&&(t=n.memoizedState,t!==null&&(t=t.dehydrated,t!==null&&(n=E8.bind(null,n),$8(t,n))));break;case 22:if(r=n.memoizedState!==null||Wa,!r){e=e!==null&&e.memoizedState!==null||Jn,i=Wa;var s=Jn;Wa=r,(Jn=e)&&!s?Lo(t,n,(n.subtreeFlags&8772)!==0):wo(t,n),Wa=i,Jn=s}break;case 30:break;default:wo(t,n)}}function $N(t){var e=t.alternate;e!==null&&(t.alternate=null,$N(e)),t.child=null,t.deletions=null,t.sibling=null,t.tag===5&&(e=t.stateNode,e!==null&&mw(e)),t.stateNode=null,t.return=null,t.dependencies=null,t.memoizedProps=null,t.memoizedState=null,t.pendingProps=null,t.stateNode=null,t.updateQueue=null}var Ln=null,gi=!1;function Ia(t,e,n){for(n=n.child;n!==null;)VN(t,e,n),n=n.sibling}function VN(t,e,n){if(ji&&typeof ji.onCommitFiberUnmount=="function")try{ji.onCommitFiberUnmount(Bp,n)}catch{}switch(n.tag){case 26:Jn||na(n,e),Ia(t,e,n),n.memoizedState?n.memoizedState.count--:n.stateNode&&(n=n.stateNode,n.parentNode.removeChild(n));break;case 27:Jn||na(n,e);var r=Ln,i=gi;Il(n.type)&&(Ln=n.stateNode,gi=!1),Ia(t,e,n),bf(n.stateNode),Ln=r,gi=i;break;case 5:Jn||na(n,e);case 6:if(r=Ln,i=gi,Ln=null,Ia(t,e,n),Ln=r,gi=i,Ln!==null)if(gi)try{(Ln.nodeType===9?Ln.body:Ln.nodeName==="HTML"?Ln.ownerDocument.body:Ln).removeChild(n.stateNode)}catch(s){mn(n,e,s)}else try{Ln.removeChild(n.stateNode)}catch(s){mn(n,e,s)}break;case 18:Ln!==null&&(gi?(t=Ln,BR(t.nodeType===9?t.body:t.nodeName==="HTML"?t.ownerDocument.body:t,n.stateNode),ep(t)):BR(Ln,n.stateNode));break;case 4:r=Ln,i=gi,Ln=n.stateNode.containerInfo,gi=!0,Ia(t,e,n),Ln=r,gi=i;break;case 0:case 11:case 14:case 15:Jn||_l(2,n,e),Jn||_l(4,n,e),Ia(t,e,n);break;case 1:Jn||(na(n,e),r=n.stateNode,typeof r.componentWillUnmount=="function"&&MN(n,e,r)),Ia(t,e,n);break;case 21:Ia(t,e,n);break;case 22:Jn=(r=Jn)||n.memoizedState!==null,Ia(t,e,n),Jn=r;break;default:Ia(t,e,n)}}function GN(t,e){if(e.memoizedState===null&&(t=e.alternate,t!==null&&(t=t.memoizedState,t!==null&&(t=t.dehydrated,t!==null))))try{ep(t)}catch(n){mn(e,e.return,n)}}function m8(t){switch(t.tag){case 13:case 19:var e=t.stateNode;return e===null&&(e=t.stateNode=new TR),e;case 22:return t=t.stateNode,e=t._retryCache,e===null&&(e=t._retryCache=new TR),e;default:throw Error(Ue(435,t.tag))}}function C_(t,e){var n=m8(t);e.forEach(function(r){var i=w8.bind(null,t,r);n.has(r)||(n.add(r),r.then(i,i))})}function Ti(t,e){var n=e.deletions;if(n!==null)for(var r=0;r<n.length;r++){var i=n[r],s=t,a=e,o=a;e:for(;o!==null;){switch(o.tag){case 27:if(Il(o.type)){Ln=o.stateNode,gi=!1;break e}break;case 5:Ln=o.stateNode,gi=!1;break e;case 3:case 4:Ln=o.stateNode.containerInfo,gi=!0;break e}o=o.return}if(Ln===null)throw Error(Ue(160));VN(s,a,i),Ln=null,gi=!1,s=i.alternate,s!==null&&(s.return=null),i.return=null}if(e.subtreeFlags&13878)for(e=e.child;e!==null;)HN(e,t),e=e.sibling}var ks=null;function HN(t,e){var n=t.alternate,r=t.flags;switch(t.tag){case 0:case 11:case 14:case 15:Ti(e,t),Ai(t),r&4&&(_l(3,t,t.return),Wp(3,t),_l(5,t,t.return));break;case 1:Ti(e,t),Ai(t),r&512&&(Jn||n===null||na(n,n.return)),r&64&&Wa&&(t=t.updateQueue,t!==null&&(r=t.callbacks,r!==null&&(n=t.shared.hiddenCallbacks,t.shared.hiddenCallbacks=n===null?r:n.concat(r))));break;case 26:var i=ks;if(Ti(e,t),Ai(t),r&512&&(Jn||n===null||na(n,n.return)),r&4){var s=n!==null?n.memoizedState:null;if(r=t.memoizedState,n===null)if(r===null)if(t.stateNode===null){e:{r=t.type,n=t.memoizedProps,i=i.ownerDocument||i;t:switch(r){case"title":s=i.getElementsByTagName("title")[0],(!s||s[Fp]||s[Hr]||s.namespaceURI==="http://www.w3.org/2000/svg"||s.hasAttribute("itemprop"))&&(s=i.createElement(r),i.head.insertBefore(s,i.querySelector("head > title"))),Ur(s,r,n),s[Hr]=t,Er(s),r=s;break e;case"link":var a=VR("link","href",i).get(r+(n.href||""));if(a){for(var o=0;o<a.length;o++)if(s=a[o],s.getAttribute("href")===(n.href==null||n.href===""?null:n.href)&&s.getAttribute("rel")===(n.rel==null?null:n.rel)&&s.getAttribute("title")===(n.title==null?null:n.title)&&s.getAttribute("crossorigin")===(n.crossOrigin==null?null:n.crossOrigin)){a.splice(o,1);break t}}s=i.createElement(r),Ur(s,r,n),i.head.appendChild(s);break;case"meta":if(a=VR("meta","content",i).get(r+(n.content||""))){for(o=0;o<a.length;o++)if(s=a[o],s.getAttribute("content")===(n.content==null?null:""+n.content)&&s.getAttribute("name")===(n.name==null?null:n.name)&&s.getAttribute("property")===(n.property==null?null:n.property)&&s.getAttribute("http-equiv")===(n.httpEquiv==null?null:n.httpEquiv)&&s.getAttribute("charset")===(n.charSet==null?null:n.charSet)){a.splice(o,1);break t}}s=i.createElement(r),Ur(s,r,n),i.head.appendChild(s);break;default:throw Error(Ue(468,r))}s[Hr]=t,Er(s),r=s}t.stateNode=r}else GR(i,t.type,t.stateNode);else t.stateNode=$R(i,r,t.memoizedProps);else s!==r?(s===null?n.stateNode!==null&&(n=n.stateNode,n.parentNode.removeChild(n)):s.count--,r===null?GR(i,t.type,t.stateNode):$R(i,r,t.memoizedProps)):r===null&&t.stateNode!==null&&T_(t,t.memoizedProps,n.memoizedProps)}break;case 27:Ti(e,t),Ai(t),r&512&&(Jn||n===null||na(n,n.return)),n!==null&&r&4&&T_(t,t.memoizedProps,n.memoizedProps);break;case 5:if(Ti(e,t),Ai(t),r&512&&(Jn||n===null||na(n,n.return)),t.flags&32){i=t.stateNode;try{Bd(i,"")}catch(f){mn(t,t.return,f)}}r&4&&t.stateNode!=null&&(i=t.memoizedProps,T_(t,i,n!==null?n.memoizedProps:i)),r&1024&&(R_=!0);break;case 6:if(Ti(e,t),Ai(t),r&4){if(t.stateNode===null)throw Error(Ue(162));r=t.memoizedProps,n=t.stateNode;try{n.nodeValue=r}catch(f){mn(t,t.return,f)}}break;case 3:if(Hg=null,i=ks,ks=Fy(e.containerInfo),Ti(e,t),ks=i,Ai(t),r&4&&n!==null&&n.memoizedState.isDehydrated)try{ep(e.containerInfo)}catch(f){mn(t,t.return,f)}R_&&(R_=!1,KN(t));break;case 4:r=ks,ks=Fy(t.stateNode.containerInfo),Ti(e,t),Ai(t),ks=r;break;case 12:Ti(e,t),Ai(t);break;case 13:Ti(e,t),Ai(t),t.child.flags&8192&&t.memoizedState!==null!=(n!==null&&n.memoizedState!==null)&&(Ww=ca()),r&4&&(r=t.updateQueue,r!==null&&(t.updateQueue=null,C_(t,r)));break;case 22:i=t.memoizedState!==null;var l=n!==null&&n.memoizedState!==null,c=Wa,u=Jn;if(Wa=c||i,Jn=u||l,Ti(e,t),Jn=u,Wa=c,Ai(t),r&8192)e:for(e=t.stateNode,e._visibility=i?e._visibility&-2:e._visibility|1,i&&(n===null||l||Wa||Jn||Ql(t)),n=null,e=t;;){if(e.tag===5||e.tag===26){if(n===null){l=n=e;try{if(s=l.stateNode,i)a=s.style,typeof a.setProperty=="function"?a.setProperty("display","none","important"):a.display="none";else{o=l.stateNode;var d=l.memoizedProps.style,h=d!=null&&d.hasOwnProperty("display")?d.display:null;o.style.display=h==null||typeof h=="boolean"?"":(""+h).trim()}}catch(f){mn(l,l.return,f)}}}else if(e.tag===6){if(n===null){l=e;try{l.stateNode.nodeValue=i?"":l.memoizedProps}catch(f){mn(l,l.return,f)}}}else if((e.tag!==22&&e.tag!==23||e.memoizedState===null||e===t)&&e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;e.sibling===null;){if(e.return===null||e.return===t)break e;n===e&&(n=null),e=e.return}n===e&&(n=null),e.sibling.return=e.return,e=e.sibling}r&4&&(r=t.updateQueue,r!==null&&(n=r.retryQueue,n!==null&&(r.retryQueue=null,C_(t,n))));break;case 19:Ti(e,t),Ai(t),r&4&&(r=t.updateQueue,r!==null&&(t.updateQueue=null,C_(t,r)));break;case 30:break;case 21:break;default:Ti(e,t),Ai(t)}}function Ai(t){var e=t.flags;if(e&2){try{for(var n,r=t.return;r!==null;){if(UN(r)){n=r;break}r=r.return}if(n==null)throw Error(Ue(160));switch(n.tag){case 27:var i=n.stateNode,s=A_(t);Dy(t,s,i);break;case 5:var a=n.stateNode;n.flags&32&&(Bd(a,""),n.flags&=-33);var o=A_(t);Dy(t,o,a);break;case 3:case 4:var l=n.stateNode.containerInfo,c=A_(t);$x(t,c,l);break;default:throw Error(Ue(161))}}catch(u){mn(t,t.return,u)}t.flags&=-3}e&4096&&(t.flags&=-4097)}function KN(t){if(t.subtreeFlags&1024)for(t=t.child;t!==null;){var e=t;KN(e),e.tag===5&&e.flags&1024&&e.stateNode.reset(),t=t.sibling}}function wo(t,e){if(e.subtreeFlags&8772)for(e=e.child;e!==null;)FN(t,e.alternate,e),e=e.sibling}function Ql(t){for(t=t.child;t!==null;){var e=t;switch(e.tag){case 0:case 11:case 14:case 15:_l(4,e,e.return),Ql(e);break;case 1:na(e,e.return);var n=e.stateNode;typeof n.componentWillUnmount=="function"&&MN(e,e.return,n),Ql(e);break;case 27:bf(e.stateNode);case 26:case 5:na(e,e.return),Ql(e);break;case 22:e.memoizedState===null&&Ql(e);break;case 30:Ql(e);break;default:Ql(e)}t=t.sibling}}function Lo(t,e,n){for(n=n&&(e.subtreeFlags&8772)!==0,e=e.child;e!==null;){var r=e.alternate,i=t,s=e,a=s.flags;switch(s.tag){case 0:case 11:case 15:Lo(i,s,n),Wp(4,s);break;case 1:if(Lo(i,s,n),r=s,i=r.stateNode,typeof i.componentDidMount=="function")try{i.componentDidMount()}catch(c){mn(r,r.return,c)}if(r=s,i=r.updateQueue,i!==null){var o=r.stateNode;try{var l=i.shared.hiddenCallbacks;if(l!==null)for(i.shared.hiddenCallbacks=null,i=0;i<l.length;i++)FO(l[i],o)}catch(c){mn(r,r.return,c)}}n&&a&64&&NN(s),gf(s,s.return);break;case 27:jN(s);case 26:case 5:Lo(i,s,n),n&&r===null&&a&4&&BN(s),gf(s,s.return);break;case 12:Lo(i,s,n);break;case 13:Lo(i,s,n),n&&a&4&&GN(i,s);break;case 22:s.memoizedState===null&&Lo(i,s,n),gf(s,s.return);break;case 30:break;default:Lo(i,s,n)}e=e.sibling}}function Hw(t,e){var n=null;t!==null&&t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(n=t.memoizedState.cachePool.pool),t=null,e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(t=e.memoizedState.cachePool.pool),t!==n&&(t!=null&&t.refCount++,n!=null&&Hp(n))}function Kw(t,e){t=null,e.alternate!==null&&(t=e.alternate.memoizedState.cache),e=e.memoizedState.cache,e!==t&&(e.refCount++,t!=null&&Hp(t))}function $s(t,e,n,r){if(e.subtreeFlags&10256)for(e=e.child;e!==null;)zN(t,e,n,r),e=e.sibling}function zN(t,e,n,r){var i=e.flags;switch(e.tag){case 0:case 11:case 15:$s(t,e,n,r),i&2048&&Wp(9,e);break;case 1:$s(t,e,n,r);break;case 3:$s(t,e,n,r),i&2048&&(t=null,e.alternate!==null&&(t=e.alternate.memoizedState.cache),e=e.memoizedState.cache,e!==t&&(e.refCount++,t!=null&&Hp(t)));break;case 12:if(i&2048){$s(t,e,n,r),t=e.stateNode;try{var s=e.memoizedProps,a=s.id,o=s.onPostCommit;typeof o=="function"&&o(a,e.alternate===null?"mount":"update",t.passiveEffectDuration,-0)}catch(l){mn(e,e.return,l)}}else $s(t,e,n,r);break;case 13:$s(t,e,n,r);break;case 23:break;case 22:s=e.stateNode,a=e.alternate,e.memoizedState!==null?s._visibility&2?$s(t,e,n,r):yf(t,e):s._visibility&2?$s(t,e,n,r):(s._visibility|=2,ku(t,e,n,r,(e.subtreeFlags&10256)!==0)),i&2048&&Hw(a,e);break;case 24:$s(t,e,n,r),i&2048&&Kw(e.alternate,e);break;default:$s(t,e,n,r)}}function ku(t,e,n,r,i){for(i=i&&(e.subtreeFlags&10256)!==0,e=e.child;e!==null;){var s=t,a=e,o=n,l=r,c=a.flags;switch(a.tag){case 0:case 11:case 15:ku(s,a,o,l,i),Wp(8,a);break;case 23:break;case 22:var u=a.stateNode;a.memoizedState!==null?u._visibility&2?ku(s,a,o,l,i):yf(s,a):(u._visibility|=2,ku(s,a,o,l,i)),i&&c&2048&&Hw(a.alternate,a);break;case 24:ku(s,a,o,l,i),i&&c&2048&&Kw(a.alternate,a);break;default:ku(s,a,o,l,i)}e=e.sibling}}function yf(t,e){if(e.subtreeFlags&10256)for(e=e.child;e!==null;){var n=t,r=e,i=r.flags;switch(r.tag){case 22:yf(n,r),i&2048&&Hw(r.alternate,r);break;case 24:yf(n,r),i&2048&&Kw(r.alternate,r);break;default:yf(n,r)}e=e.sibling}}var Qh=8192;function au(t){if(t.subtreeFlags&Qh)for(t=t.child;t!==null;)qN(t),t=t.sibling}function qN(t){switch(t.tag){case 26:au(t),t.flags&Qh&&t.memoizedState!==null&&eV(ks,t.memoizedState,t.memoizedProps);break;case 5:au(t);break;case 3:case 4:var e=ks;ks=Fy(t.stateNode.containerInfo),au(t),ks=e;break;case 22:t.memoizedState===null&&(e=t.alternate,e!==null&&e.memoizedState!==null?(e=Qh,Qh=16777216,au(t),Qh=e):au(t));break;default:au(t)}}function WN(t){var e=t.alternate;if(e!==null&&(t=e.child,t!==null)){e.child=null;do e=t.sibling,t.sibling=null,t=e;while(t!==null)}}function Bh(t){var e=t.deletions;if(t.flags&16){if(e!==null)for(var n=0;n<e.length;n++){var r=e[n];Sr=r,XN(r,t)}WN(t)}if(t.subtreeFlags&10256)for(t=t.child;t!==null;)YN(t),t=t.sibling}function YN(t){switch(t.tag){case 0:case 11:case 15:Bh(t),t.flags&2048&&_l(9,t,t.return);break;case 3:Bh(t);break;case 12:Bh(t);break;case 22:var e=t.stateNode;t.memoizedState!==null&&e._visibility&2&&(t.return===null||t.return.tag!==13)?(e._visibility&=-3,Vg(t)):Bh(t);break;default:Bh(t)}}function Vg(t){var e=t.deletions;if(t.flags&16){if(e!==null)for(var n=0;n<e.length;n++){var r=e[n];Sr=r,XN(r,t)}WN(t)}for(t=t.child;t!==null;){switch(e=t,e.tag){case 0:case 11:case 15:_l(8,e,e.return),Vg(e);break;case 22:n=e.stateNode,n._visibility&2&&(n._visibility&=-3,Vg(e));break;default:Vg(e)}t=t.sibling}}function XN(t,e){for(;Sr!==null;){var n=Sr;switch(n.tag){case 0:case 11:case 15:_l(8,n,e);break;case 23:case 22:if(n.memoizedState!==null&&n.memoizedState.cachePool!==null){var r=n.memoizedState.cachePool.pool;r!=null&&r.refCount++}break;case 24:Hp(n.memoizedState.cache)}if(r=n.child,r!==null)r.return=n,Sr=r;else e:for(n=t;Sr!==null;){r=Sr;var i=r.sibling,s=r.return;if($N(r),r===n){Sr=null;break e}if(i!==null){i.return=s,Sr=i;break e}Sr=s}}}var g8={getCacheForType:function(t){var e=Kr(fr),n=e.data.get(t);return n===void 0&&(n=t(),e.data.set(t,n)),n}},y8=typeof WeakMap=="function"?WeakMap:Map,cn=0,xn=null,zt=null,Qt=0,an=0,Ii=null,nl=!1,oh=!1,zw=!1,oo=0,zn=0,bl=0,Tc=0,qw=0,ds=0,Vd=0,vf=null,yi=null,Vx=!1,Ww=0,Oy=1/0,Ny=null,cl=null,Mr=0,ul=null,Gd=null,hd=0,Gx=0,Hx=null,QN=null,_f=0,Kx=null;function $i(){if(cn&2&&Qt!==0)return Qt&-Qt;if(xt.T!==null){var t=Ud;return t!==0?t:Xw()}return lO()}function JN(){ds===0&&(ds=!(Qt&536870912)||Zt?iO():536870912);var t=ms.current;return t!==null&&(t.flags|=32),ds}function Vi(t,e,n){(t===xn&&(an===2||an===9)||t.cancelPendingCommit!==null)&&(Hd(t,0),rl(t,Qt,ds,!1)),jp(t,n),(!(cn&2)||t!==xn)&&(t===xn&&(!(cn&2)&&(Tc|=n),zn===4&&rl(t,Qt,ds,!1)),_a(t))}function ZN(t,e,n){if(cn&6)throw Error(Ue(327));var r=!n&&(e&124)===0&&(e&t.expiredLanes)===0||Up(t,e),i=r?b8(t,e):L_(t,e,!0),s=r;do{if(i===0){oh&&!r&&rl(t,e,0,!1);break}else{if(n=t.current.alternate,s&&!v8(n)){i=L_(t,e,!1),s=!1;continue}if(i===2){if(s=e,t.errorRecoveryDisabledLanes&s)var a=0;else a=t.pendingLanes&-536870913,a=a!==0?a:a&536870912?536870912:0;if(a!==0){e=a;e:{var o=t;i=vf;var l=o.current.memoizedState.isDehydrated;if(l&&(Hd(o,a).flags|=256),a=L_(o,a,!1),a!==2){if(zw&&!l){o.errorRecoveryDisabledLanes|=s,Tc|=s,i=4;break e}s=yi,yi=i,s!==null&&(yi===null?yi=s:yi.push.apply(yi,s))}i=a}if(s=!1,i!==2)continue}}if(i===1){Hd(t,0),rl(t,e,0,!0);break}e:{switch(r=t,s=i,s){case 0:case 1:throw Error(Ue(345));case 4:if((e&4194048)!==e)break;case 6:rl(r,e,ds,!nl);break e;case 2:yi=null;break;case 3:case 5:break;default:throw Error(Ue(329))}if((e&62914560)===e&&(i=Ww+300-ca(),10<i)){if(rl(r,e,ds,!nl),O0(r,0,!0)!==0)break e;r.timeoutHandle=vM(AR.bind(null,r,n,yi,Ny,Vx,e,ds,Tc,Vd,nl,s,2,-0,0),i);break e}AR(r,n,yi,Ny,Vx,e,ds,Tc,Vd,nl,s,0,-0,0)}}break}while(!0);_a(t)}function AR(t,e,n,r,i,s,a,o,l,c,u,d,h,f){if(t.timeoutHandle=-1,d=e.subtreeFlags,(d&8192||(d&16785408)===16785408)&&(Xf={stylesheets:null,count:0,unsuspend:Z8},qN(e),d=tV(),d!==null)){t.cancelPendingCommit=d(CR.bind(null,t,e,s,n,r,i,a,o,l,u,1,h,f)),rl(t,s,a,!c);return}CR(t,e,s,n,r,i,a,o,l)}function v8(t){for(var e=t;;){var n=e.tag;if((n===0||n===11||n===15)&&e.flags&16384&&(n=e.updateQueue,n!==null&&(n=n.stores,n!==null)))for(var r=0;r<n.length;r++){var i=n[r],s=i.getSnapshot;i=i.value;try{if(!zi(s(),i))return!1}catch{return!1}}if(n=e.child,e.subtreeFlags&16384&&n!==null)n.return=e,e=n;else{if(e===t)break;for(;e.sibling===null;){if(e.return===null||e.return===t)return!0;e=e.return}e.sibling.return=e.return,e=e.sibling}}return!0}function rl(t,e,n,r){e&=~qw,e&=~Tc,t.suspendedLanes|=e,t.pingedLanes&=~e,r&&(t.warmLanes|=e),r=t.expirationTimes;for(var i=e;0<i;){var s=31-Fi(i),a=1<<s;r[s]=-1,i&=~a}n!==0&&aO(t,n,e)}function H0(){return cn&6?!0:(Yp(0),!1)}function Yw(){if(zt!==null){if(an===0)var t=zt.return;else t=zt,Ja=Wc=null,Nw(t),dd=null,qf=0,t=zt;for(;t!==null;)ON(t.alternate,t),t=t.return;zt=null}}function Hd(t,e){var n=t.timeoutHandle;n!==-1&&(t.timeoutHandle=-1,M8(n)),n=t.cancelPendingCommit,n!==null&&(t.cancelPendingCommit=null,n()),Yw(),xn=t,zt=n=eo(t.current,null),Qt=e,an=0,Ii=null,nl=!1,oh=Up(t,e),zw=!1,Vd=ds=qw=Tc=bl=zn=0,yi=vf=null,Vx=!1,e&8&&(e|=e&32);var r=t.entangledLanes;if(r!==0)for(t=t.entanglements,r&=e;0<r;){var i=31-Fi(r),s=1<<i;e|=t[i],r&=~s}return oo=e,U0(),n}function eM(t,e){Ut=null,xt.H=Cy,e===Kp||e===F0?(e=iR(),an=3):e===UO?(e=iR(),an=4):an=e===CN?8:e!==null&&typeof e=="object"&&typeof e.then=="function"?6:1,Ii=e,zt===null&&(zn=1,Iy(t,us(e,t.current)))}function tM(){var t=xt.H;return xt.H=Cy,t===null?Cy:t}function nM(){var t=xt.A;return xt.A=g8,t}function zx(){zn=4,nl||(Qt&4194048)!==Qt&&ms.current!==null||(oh=!0),!(bl&134217727)&&!(Tc&134217727)||xn===null||rl(xn,Qt,ds,!1)}function L_(t,e,n){var r=cn;cn|=2;var i=tM(),s=nM();(xn!==t||Qt!==e)&&(Ny=null,Hd(t,e)),e=!1;var a=zn;e:do try{if(an!==0&&zt!==null){var o=zt,l=Ii;switch(an){case 8:Yw(),a=6;break e;case 3:case 2:case 9:case 6:ms.current===null&&(e=!0);var c=an;if(an=0,Ii=null,Xu(t,o,l,c),n&&oh){a=0;break e}break;default:c=an,an=0,Ii=null,Xu(t,o,l,c)}}_8(),a=zn;break}catch(u){eM(t,u)}while(!0);return e&&t.shellSuspendCounter++,Ja=Wc=null,cn=r,xt.H=i,xt.A=s,zt===null&&(xn=null,Qt=0,U0()),a}function _8(){for(;zt!==null;)rM(zt)}function b8(t,e){var n=cn;cn|=2;var r=tM(),i=nM();xn!==t||Qt!==e?(Ny=null,Oy=ca()+500,Hd(t,e)):oh=Up(t,e);e:do try{if(an!==0&&zt!==null){e=zt;var s=Ii;t:switch(an){case 1:an=0,Ii=null,Xu(t,e,s,1);break;case 2:case 9:if(rR(s)){an=0,Ii=null,RR(e);break}e=function(){an!==2&&an!==9||xn!==t||(an=7),_a(t)},s.then(e,e);break e;case 3:an=7;break e;case 4:an=5;break e;case 7:rR(s)?(an=0,Ii=null,RR(e)):(an=0,Ii=null,Xu(t,e,s,7));break;case 5:var a=null;switch(zt.tag){case 26:a=zt.memoizedState;case 5:case 27:var o=zt;if(!a||SM(a)){an=0,Ii=null;var l=o.sibling;if(l!==null)zt=l;else{var c=o.return;c!==null?(zt=c,K0(c)):zt=null}break t}}an=0,Ii=null,Xu(t,e,s,5);break;case 6:an=0,Ii=null,Xu(t,e,s,6);break;case 8:Yw(),zn=6;break e;default:throw Error(Ue(462))}}x8();break}catch(u){eM(t,u)}while(!0);return Ja=Wc=null,xt.H=r,xt.A=i,cn=n,zt!==null?0:(xn=null,Qt=0,U0(),zn)}function x8(){for(;zt!==null&&!G$();)rM(zt)}function rM(t){var e=DN(t.alternate,t,oo);t.memoizedProps=t.pendingProps,e===null?K0(t):zt=e}function RR(t){var e=t,n=e.alternate;switch(e.tag){case 15:case 0:e=bR(n,e,e.pendingProps,e.type,void 0,Qt);break;case 11:e=bR(n,e,e.pendingProps,e.type.render,e.ref,Qt);break;case 5:Nw(e);default:ON(n,e),e=zt=OO(e,oo),e=DN(n,e,oo)}t.memoizedProps=t.pendingProps,e===null?K0(t):zt=e}function Xu(t,e,n,r){Ja=Wc=null,Nw(e),dd=null,qf=0;var i=e.return;try{if(u8(t,i,e,n,Qt)){zn=1,Iy(t,us(n,t.current)),zt=null;return}}catch(s){if(i!==null)throw zt=i,s;zn=1,Iy(t,us(n,t.current)),zt=null;return}e.flags&32768?(Zt||r===1?t=!0:oh||Qt&536870912?t=!1:(nl=t=!0,(r===2||r===9||r===3||r===6)&&(r=ms.current,r!==null&&r.tag===13&&(r.flags|=16384))),iM(e,t)):K0(e)}function K0(t){var e=t;do{if(e.flags&32768){iM(e,nl);return}t=e.return;var n=h8(e.alternate,e,oo);if(n!==null){zt=n;return}if(e=e.sibling,e!==null){zt=e;return}zt=e=t}while(e!==null);zn===0&&(zn=5)}function iM(t,e){do{var n=f8(t.alternate,t);if(n!==null){n.flags&=32767,zt=n;return}if(n=t.return,n!==null&&(n.flags|=32768,n.subtreeFlags=0,n.deletions=null),!e&&(t=t.sibling,t!==null)){zt=t;return}zt=t=n}while(t!==null);zn=6,zt=null}function CR(t,e,n,r,i,s,a,o,l){t.cancelPendingCommit=null;do z0();while(Mr!==0);if(cn&6)throw Error(Ue(327));if(e!==null){if(e===t.current)throw Error(Ue(177));if(s=e.lanes|e.childLanes,s|=Sw,Z$(t,n,s,a,o,l),t===xn&&(zt=xn=null,Qt=0),Gd=e,ul=t,hd=n,Gx=s,Hx=i,QN=r,e.subtreeFlags&10256||e.flags&10256?(t.callbackNode=null,t.callbackPriority=0,T8(vy,function(){return cM(),null})):(t.callbackNode=null,t.callbackPriority=0),r=(e.flags&13878)!==0,e.subtreeFlags&13878||r){r=xt.T,xt.T=null,i=en.p,en.p=2,a=cn,cn|=4;try{p8(t,e,n)}finally{cn=a,en.p=i,xt.T=r}}Mr=1,sM(),aM(),oM()}}function sM(){if(Mr===1){Mr=0;var t=ul,e=Gd,n=(e.flags&13878)!==0;if(e.subtreeFlags&13878||n){n=xt.T,xt.T=null;var r=en.p;en.p=2;var i=cn;cn|=4;try{HN(e,t);var s=Xx,a=AO(t.containerInfo),o=s.focusedElem,l=s.selectionRange;if(a!==o&&o&&o.ownerDocument&&TO(o.ownerDocument.documentElement,o)){if(l!==null&&xw(o)){var c=l.start,u=l.end;if(u===void 0&&(u=c),"selectionStart"in o)o.selectionStart=c,o.selectionEnd=Math.min(u,o.value.length);else{var d=o.ownerDocument||document,h=d&&d.defaultView||window;if(h.getSelection){var f=h.getSelection(),p=o.textContent.length,m=Math.min(l.start,p),g=l.end===void 0?m:Math.min(l.end,p);!f.extend&&m>g&&(a=g,g=m,m=a);var b=Y1(o,m),v=Y1(o,g);if(b&&v&&(f.rangeCount!==1||f.anchorNode!==b.node||f.anchorOffset!==b.offset||f.focusNode!==v.node||f.focusOffset!==v.offset)){var S=d.createRange();S.setStart(b.node,b.offset),f.removeAllRanges(),m>g?(f.addRange(S),f.extend(v.node,v.offset)):(S.setEnd(v.node,v.offset),f.addRange(S))}}}}for(d=[],f=o;f=f.parentNode;)f.nodeType===1&&d.push({element:f,left:f.scrollLeft,top:f.scrollTop});for(typeof o.focus=="function"&&o.focus(),o=0;o<d.length;o++){var E=d[o];E.element.scrollLeft=E.left,E.element.scrollTop=E.top}}Gy=!!Yx,Xx=Yx=null}finally{cn=i,en.p=r,xt.T=n}}t.current=e,Mr=2}}function aM(){if(Mr===2){Mr=0;var t=ul,e=Gd,n=(e.flags&8772)!==0;if(e.subtreeFlags&8772||n){n=xt.T,xt.T=null;var r=en.p;en.p=2;var i=cn;cn|=4;try{FN(t,e.alternate,e)}finally{cn=i,en.p=r,xt.T=n}}Mr=3}}function oM(){if(Mr===4||Mr===3){Mr=0,H$();var t=ul,e=Gd,n=hd,r=QN;e.subtreeFlags&10256||e.flags&10256?Mr=5:(Mr=0,Gd=ul=null,lM(t,t.pendingLanes));var i=t.pendingLanes;if(i===0&&(cl=null),pw(n),e=e.stateNode,ji&&typeof ji.onCommitFiberRoot=="function")try{ji.onCommitFiberRoot(Bp,e,void 0,(e.current.flags&128)===128)}catch{}if(r!==null){e=xt.T,i=en.p,en.p=2,xt.T=null;try{for(var s=t.onRecoverableError,a=0;a<r.length;a++){var o=r[a];s(o.value,{componentStack:o.stack})}}finally{xt.T=e,en.p=i}}hd&3&&z0(),_a(t),i=t.pendingLanes,n&4194090&&i&42?t===Kx?_f++:(_f=0,Kx=t):_f=0,Yp(0)}}function lM(t,e){(t.pooledCacheLanes&=e)===0&&(e=t.pooledCache,e!=null&&(t.pooledCache=null,Hp(e)))}function z0(t){return sM(),aM(),oM(),cM()}function cM(){if(Mr!==5)return!1;var t=ul,e=Gx;Gx=0;var n=pw(hd),r=xt.T,i=en.p;try{en.p=32>n?32:n,xt.T=null,n=Hx,Hx=null;var s=ul,a=hd;if(Mr=0,Gd=ul=null,hd=0,cn&6)throw Error(Ue(331));var o=cn;if(cn|=4,YN(s.current),zN(s,s.current,a,n),cn=o,Yp(0,!1),ji&&typeof ji.onPostCommitFiberRoot=="function")try{ji.onPostCommitFiberRoot(Bp,s)}catch{}return!0}finally{en.p=i,xt.T=r,lM(t,e)}}function LR(t,e,n){e=us(n,e),e=Ux(t.stateNode,e,2),t=ll(t,e,2),t!==null&&(jp(t,2),_a(t))}function mn(t,e,n){if(t.tag===3)LR(t,t,n);else for(;e!==null;){if(e.tag===3){LR(e,t,n);break}else if(e.tag===1){var r=e.stateNode;if(typeof e.type.getDerivedStateFromError=="function"||typeof r.componentDidCatch=="function"&&(cl===null||!cl.has(r))){t=us(n,t),n=AN(2),r=ll(e,n,2),r!==null&&(RN(n,r,e,t),jp(r,2),_a(r));break}}e=e.return}}function k_(t,e,n){var r=t.pingCache;if(r===null){r=t.pingCache=new y8;var i=new Set;r.set(e,i)}else i=r.get(e),i===void 0&&(i=new Set,r.set(e,i));i.has(n)||(zw=!0,i.add(n),t=S8.bind(null,t,e,n),e.then(t,t))}function S8(t,e,n){var r=t.pingCache;r!==null&&r.delete(e),t.pingedLanes|=t.suspendedLanes&n,t.warmLanes&=~n,xn===t&&(Qt&n)===n&&(zn===4||zn===3&&(Qt&62914560)===Qt&&300>ca()-Ww?!(cn&2)&&Hd(t,0):qw|=n,Vd===Qt&&(Vd=0)),_a(t)}function uM(t,e){e===0&&(e=sO()),t=ah(t,e),t!==null&&(jp(t,e),_a(t))}function E8(t){var e=t.memoizedState,n=0;e!==null&&(n=e.retryLane),uM(t,n)}function w8(t,e){var n=0;switch(t.tag){case 13:var r=t.stateNode,i=t.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=t.stateNode;break;case 22:r=t.stateNode._retryCache;break;default:throw Error(Ue(314))}r!==null&&r.delete(e),uM(t,n)}function T8(t,e){return hw(t,e)}var My=null,Iu=null,qx=!1,By=!1,I_=!1,Ac=0;function _a(t){t!==Iu&&t.next===null&&(Iu===null?My=Iu=t:Iu=Iu.next=t),By=!0,qx||(qx=!0,R8())}function Yp(t,e){if(!I_&&By){I_=!0;do for(var n=!1,r=My;r!==null;){if(t!==0){var i=r.pendingLanes;if(i===0)var s=0;else{var a=r.suspendedLanes,o=r.pingedLanes;s=(1<<31-Fi(42|t)+1)-1,s&=i&~(a&~o),s=s&201326741?s&201326741|1:s?s|2:0}s!==0&&(n=!0,kR(r,s))}else s=Qt,s=O0(r,r===xn?s:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(s&3)||Up(r,s)||(n=!0,kR(r,s));r=r.next}while(n);I_=!1}}function A8(){dM()}function dM(){By=qx=!1;var t=0;Ac!==0&&(N8()&&(t=Ac),Ac=0);for(var e=ca(),n=null,r=My;r!==null;){var i=r.next,s=hM(r,e);s===0?(r.next=null,n===null?My=i:n.next=i,i===null&&(Iu=n)):(n=r,(t!==0||s&3)&&(By=!0)),r=i}Yp(t)}function hM(t,e){for(var n=t.suspendedLanes,r=t.pingedLanes,i=t.expirationTimes,s=t.pendingLanes&-62914561;0<s;){var a=31-Fi(s),o=1<<a,l=i[a];l===-1?(!(o&n)||o&r)&&(i[a]=J$(o,e)):l<=e&&(t.expiredLanes|=o),s&=~o}if(e=xn,n=Qt,n=O0(t,t===e?n:0,t.cancelPendingCommit!==null||t.timeoutHandle!==-1),r=t.callbackNode,n===0||t===e&&(an===2||an===9)||t.cancelPendingCommit!==null)return r!==null&&r!==null&&r_(r),t.callbackNode=null,t.callbackPriority=0;if(!(n&3)||Up(t,n)){if(e=n&-n,e===t.callbackPriority)return e;switch(r!==null&&r_(r),pw(n)){case 2:case 8:n=nO;break;case 32:n=vy;break;case 268435456:n=rO;break;default:n=vy}return r=fM.bind(null,t),n=hw(n,r),t.callbackPriority=e,t.callbackNode=n,e}return r!==null&&r!==null&&r_(r),t.callbackPriority=2,t.callbackNode=null,2}function fM(t,e){if(Mr!==0&&Mr!==5)return t.callbackNode=null,t.callbackPriority=0,null;var n=t.callbackNode;if(z0()&&t.callbackNode!==n)return null;var r=Qt;return r=O0(t,t===xn?r:0,t.cancelPendingCommit!==null||t.timeoutHandle!==-1),r===0?null:(ZN(t,r,e),hM(t,ca()),t.callbackNode!=null&&t.callbackNode===n?fM.bind(null,t):null)}function kR(t,e){if(z0())return null;ZN(t,e,!0)}function R8(){B8(function(){cn&6?hw(tO,A8):dM()})}function Xw(){return Ac===0&&(Ac=iO()),Ac}function IR(t){return t==null||typeof t=="symbol"||typeof t=="boolean"?null:typeof t=="function"?t:Og(""+t)}function PR(t,e){var n=e.ownerDocument.createElement("input");return n.name=e.name,n.value=e.value,t.id&&n.setAttribute("form",t.id),e.parentNode.insertBefore(n,e),t=new FormData(t),n.parentNode.removeChild(n),t}function C8(t,e,n,r,i){if(e==="submit"&&n&&n.stateNode===i){var s=IR((i[xi]||null).action),a=r.submitter;a&&(e=(e=a[xi]||null)?IR(e.formAction):a.getAttribute("formAction"),e!==null&&(s=e,a=null));var o=new N0("action","action",null,r,i);t.push({event:o,listeners:[{instance:null,listener:function(){if(r.defaultPrevented){if(Ac!==0){var l=a?PR(i,a):new FormData(i);Mx(n,{pending:!0,data:l,method:i.method,action:s},null,l)}}else typeof s=="function"&&(o.preventDefault(),l=a?PR(i,a):new FormData(i),Mx(n,{pending:!0,data:l,method:i.method,action:s},s,l))},currentTarget:i}]})}}for(var P_=0;P_<wx.length;P_++){var D_=wx[P_],L8=D_.toLowerCase(),k8=D_[0].toUpperCase()+D_.slice(1);Ns(L8,"on"+k8)}Ns(CO,"onAnimationEnd");Ns(LO,"onAnimationIteration");Ns(kO,"onAnimationStart");Ns("dblclick","onDoubleClick");Ns("focusin","onFocus");Ns("focusout","onBlur");Ns(q5,"onTransitionRun");Ns(W5,"onTransitionStart");Ns(Y5,"onTransitionCancel");Ns(IO,"onTransitionEnd");Md("onMouseEnter",["mouseout","mouseover"]);Md("onMouseLeave",["mouseout","mouseover"]);Md("onPointerEnter",["pointerout","pointerover"]);Md("onPointerLeave",["pointerout","pointerover"]);Kc("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));Kc("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));Kc("onBeforeInput",["compositionend","keypress","textInput","paste"]);Kc("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));Kc("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));Kc("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Wf="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),I8=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(Wf));function pM(t,e){e=(e&4)!==0;for(var n=0;n<t.length;n++){var r=t[n],i=r.event;r=r.listeners;e:{var s=void 0;if(e)for(var a=r.length-1;0<=a;a--){var o=r[a],l=o.instance,c=o.currentTarget;if(o=o.listener,l!==s&&i.isPropagationStopped())break e;s=o,i.currentTarget=c;try{s(i)}catch(u){ky(u)}i.currentTarget=null,s=l}else for(a=0;a<r.length;a++){if(o=r[a],l=o.instance,c=o.currentTarget,o=o.listener,l!==s&&i.isPropagationStopped())break e;s=o,i.currentTarget=c;try{s(i)}catch(u){ky(u)}i.currentTarget=null,s=l}}}}function Kt(t,e){var n=e[yx];n===void 0&&(n=e[yx]=new Set);var r=t+"__bubble";n.has(r)||(mM(e,t,2,!1),n.add(r))}function O_(t,e,n){var r=0;e&&(r|=4),mM(n,t,r,e)}var $m="_reactListening"+Math.random().toString(36).slice(2);function Qw(t){if(!t[$m]){t[$m]=!0,cO.forEach(function(n){n!=="selectionchange"&&(I8.has(n)||O_(n,!1,t),O_(n,!0,t))});var e=t.nodeType===9?t:t.ownerDocument;e===null||e[$m]||(e[$m]=!0,O_("selectionchange",!1,e))}}function mM(t,e,n,r){switch(RM(e)){case 2:var i=iV;break;case 8:i=sV;break;default:i=tT}n=i.bind(null,e,n,t),i=void 0,!xx||e!=="touchstart"&&e!=="touchmove"&&e!=="wheel"||(i=!0),r?i!==void 0?t.addEventListener(e,n,{capture:!0,passive:i}):t.addEventListener(e,n,!0):i!==void 0?t.addEventListener(e,n,{passive:i}):t.addEventListener(e,n,!1)}function N_(t,e,n,r,i){var s=r;if(!(e&1)&&!(e&2)&&r!==null)e:for(;;){if(r===null)return;var a=r.tag;if(a===3||a===4){var o=r.stateNode.containerInfo;if(o===i)break;if(a===4)for(a=r.return;a!==null;){var l=a.tag;if((l===3||l===4)&&a.stateNode.containerInfo===i)return;a=a.return}for(;o!==null;){if(a=$u(o),a===null)return;if(l=a.tag,l===5||l===6||l===26||l===27){r=s=a;continue e}o=o.parentNode}}r=r.return}yO(function(){var c=s,u=yw(n),d=[];e:{var h=PO.get(t);if(h!==void 0){var f=N0,p=t;switch(t){case"keypress":if(Mg(n)===0)break e;case"keydown":case"keyup":f=T5;break;case"focusin":p="focus",f=d_;break;case"focusout":p="blur",f=d_;break;case"beforeblur":case"afterblur":f=d_;break;case"click":if(n.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":f=j1;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":f=f5;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":f=C5;break;case CO:case LO:case kO:f=g5;break;case IO:f=k5;break;case"scroll":case"scrollend":f=d5;break;case"wheel":f=P5;break;case"copy":case"cut":case"paste":f=v5;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":f=$1;break;case"toggle":case"beforetoggle":f=O5}var m=(e&4)!==0,g=!m&&(t==="scroll"||t==="scrollend"),b=m?h!==null?h+"Capture":null:h;m=[];for(var v=c,S;v!==null;){var E=v;if(S=E.stateNode,E=E.tag,E!==5&&E!==26&&E!==27||S===null||b===null||(E=Vf(v,b),E!=null&&m.push(Yf(v,E,S))),g)break;v=v.return}0<m.length&&(h=new f(h,p,null,n,u),d.push({event:h,listeners:m}))}}if(!(e&7)){e:{if(h=t==="mouseover"||t==="pointerover",f=t==="mouseout"||t==="pointerout",h&&n!==bx&&(p=n.relatedTarget||n.fromElement)&&($u(p)||p[ih]))break e;if((f||h)&&(h=u.window===u?u:(h=u.ownerDocument)?h.defaultView||h.parentWindow:window,f?(p=n.relatedTarget||n.toElement,f=c,p=p?$u(p):null,p!==null&&(g=Mp(p),m=p.tag,p!==g||m!==5&&m!==27&&m!==6)&&(p=null)):(f=null,p=c),f!==p)){if(m=j1,E="onMouseLeave",b="onMouseEnter",v="mouse",(t==="pointerout"||t==="pointerover")&&(m=$1,E="onPointerLeave",b="onPointerEnter",v="pointer"),g=f==null?h:Xh(f),S=p==null?h:Xh(p),h=new m(E,v+"leave",f,n,u),h.target=g,h.relatedTarget=S,E=null,$u(u)===c&&(m=new m(b,v+"enter",p,n,u),m.target=S,m.relatedTarget=g,E=m),g=E,f&&p)t:{for(m=f,b=p,v=0,S=m;S;S=ou(S))v++;for(S=0,E=b;E;E=ou(E))S++;for(;0<v-S;)m=ou(m),v--;for(;0<S-v;)b=ou(b),S--;for(;v--;){if(m===b||b!==null&&m===b.alternate)break t;m=ou(m),b=ou(b)}m=null}else m=null;f!==null&&DR(d,h,f,m,!1),p!==null&&g!==null&&DR(d,g,p,m,!0)}}e:{if(h=c?Xh(c):window,f=h.nodeName&&h.nodeName.toLowerCase(),f==="select"||f==="input"&&h.type==="file")var L=K1;else if(H1(h))if(EO)L=H5;else{L=V5;var U=$5}else f=h.nodeName,!f||f.toLowerCase()!=="input"||h.type!=="checkbox"&&h.type!=="radio"?c&&gw(c.elementType)&&(L=K1):L=G5;if(L&&(L=L(t,c))){SO(d,L,n,u);break e}U&&U(t,h,c),t==="focusout"&&c&&h.type==="number"&&c.memoizedProps.value!=null&&_x(h,"number",h.value)}switch(U=c?Xh(c):window,t){case"focusin":(H1(U)||U.contentEditable==="true")&&(Hu=U,Sx=c,cf=null);break;case"focusout":cf=Sx=Hu=null;break;case"mousedown":Ex=!0;break;case"contextmenu":case"mouseup":case"dragend":Ex=!1,X1(d,n,u);break;case"selectionchange":if(z5)break;case"keydown":case"keyup":X1(d,n,u)}var O;if(bw)e:{switch(t){case"compositionstart":var k="onCompositionStart";break e;case"compositionend":k="onCompositionEnd";break e;case"compositionupdate":k="onCompositionUpdate";break e}k=void 0}else Gu?bO(t,n)&&(k="onCompositionEnd"):t==="keydown"&&n.keyCode===229&&(k="onCompositionStart");k&&(_O&&n.locale!=="ko"&&(Gu||k!=="onCompositionStart"?k==="onCompositionEnd"&&Gu&&(O=vO()):(tl=u,vw="value"in tl?tl.value:tl.textContent,Gu=!0)),U=Uy(c,k),0<U.length&&(k=new F1(k,t,null,n,u),d.push({event:k,listeners:U}),O?k.data=O:(O=xO(n),O!==null&&(k.data=O)))),(O=M5?B5(t,n):U5(t,n))&&(k=Uy(c,"onBeforeInput"),0<k.length&&(U=new F1("onBeforeInput","beforeinput",null,n,u),d.push({event:U,listeners:k}),U.data=O)),C8(d,t,c,n,u)}pM(d,e)})}function Yf(t,e,n){return{instance:t,listener:e,currentTarget:n}}function Uy(t,e){for(var n=e+"Capture",r=[];t!==null;){var i=t,s=i.stateNode;if(i=i.tag,i!==5&&i!==26&&i!==27||s===null||(i=Vf(t,n),i!=null&&r.unshift(Yf(t,i,s)),i=Vf(t,e),i!=null&&r.push(Yf(t,i,s))),t.tag===3)return r;t=t.return}return[]}function ou(t){if(t===null)return null;do t=t.return;while(t&&t.tag!==5&&t.tag!==27);return t||null}function DR(t,e,n,r,i){for(var s=e._reactName,a=[];n!==null&&n!==r;){var o=n,l=o.alternate,c=o.stateNode;if(o=o.tag,l!==null&&l===r)break;o!==5&&o!==26&&o!==27||c===null||(l=c,i?(c=Vf(n,s),c!=null&&a.unshift(Yf(n,c,l))):i||(c=Vf(n,s),c!=null&&a.push(Yf(n,c,l)))),n=n.return}a.length!==0&&t.push({event:e,listeners:a})}var P8=/\r\n?/g,D8=/\u0000|\uFFFD/g;function OR(t){return(typeof t=="string"?t:""+t).replace(P8,`
`).replace(D8,"")}function gM(t,e){return e=OR(e),OR(t)===e}function q0(){}function dn(t,e,n,r,i,s){switch(n){case"children":typeof r=="string"?e==="body"||e==="textarea"&&r===""||Bd(t,r):(typeof r=="number"||typeof r=="bigint")&&e!=="body"&&Bd(t,""+r);break;case"className":Om(t,"class",r);break;case"tabIndex":Om(t,"tabindex",r);break;case"dir":case"role":case"viewBox":case"width":case"height":Om(t,n,r);break;case"style":gO(t,r,s);break;case"data":if(e!=="object"){Om(t,"data",r);break}case"src":case"href":if(r===""&&(e!=="a"||n!=="href")){t.removeAttribute(n);break}if(r==null||typeof r=="function"||typeof r=="symbol"||typeof r=="boolean"){t.removeAttribute(n);break}r=Og(""+r),t.setAttribute(n,r);break;case"action":case"formAction":if(typeof r=="function"){t.setAttribute(n,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof s=="function"&&(n==="formAction"?(e!=="input"&&dn(t,e,"name",i.name,i,null),dn(t,e,"formEncType",i.formEncType,i,null),dn(t,e,"formMethod",i.formMethod,i,null),dn(t,e,"formTarget",i.formTarget,i,null)):(dn(t,e,"encType",i.encType,i,null),dn(t,e,"method",i.method,i,null),dn(t,e,"target",i.target,i,null)));if(r==null||typeof r=="symbol"||typeof r=="boolean"){t.removeAttribute(n);break}r=Og(""+r),t.setAttribute(n,r);break;case"onClick":r!=null&&(t.onclick=q0);break;case"onScroll":r!=null&&Kt("scroll",t);break;case"onScrollEnd":r!=null&&Kt("scrollend",t);break;case"dangerouslySetInnerHTML":if(r!=null){if(typeof r!="object"||!("__html"in r))throw Error(Ue(61));if(n=r.__html,n!=null){if(i.children!=null)throw Error(Ue(60));t.innerHTML=n}}break;case"multiple":t.multiple=r&&typeof r!="function"&&typeof r!="symbol";break;case"muted":t.muted=r&&typeof r!="function"&&typeof r!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(r==null||typeof r=="function"||typeof r=="boolean"||typeof r=="symbol"){t.removeAttribute("xlink:href");break}n=Og(""+r),t.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",n);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":r!=null&&typeof r!="function"&&typeof r!="symbol"?t.setAttribute(n,""+r):t.removeAttribute(n);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":r&&typeof r!="function"&&typeof r!="symbol"?t.setAttribute(n,""):t.removeAttribute(n);break;case"capture":case"download":r===!0?t.setAttribute(n,""):r!==!1&&r!=null&&typeof r!="function"&&typeof r!="symbol"?t.setAttribute(n,r):t.removeAttribute(n);break;case"cols":case"rows":case"size":case"span":r!=null&&typeof r!="function"&&typeof r!="symbol"&&!isNaN(r)&&1<=r?t.setAttribute(n,r):t.removeAttribute(n);break;case"rowSpan":case"start":r==null||typeof r=="function"||typeof r=="symbol"||isNaN(r)?t.removeAttribute(n):t.setAttribute(n,r);break;case"popover":Kt("beforetoggle",t),Kt("toggle",t),Dg(t,"popover",r);break;case"xlinkActuate":La(t,"http://www.w3.org/1999/xlink","xlink:actuate",r);break;case"xlinkArcrole":La(t,"http://www.w3.org/1999/xlink","xlink:arcrole",r);break;case"xlinkRole":La(t,"http://www.w3.org/1999/xlink","xlink:role",r);break;case"xlinkShow":La(t,"http://www.w3.org/1999/xlink","xlink:show",r);break;case"xlinkTitle":La(t,"http://www.w3.org/1999/xlink","xlink:title",r);break;case"xlinkType":La(t,"http://www.w3.org/1999/xlink","xlink:type",r);break;case"xmlBase":La(t,"http://www.w3.org/XML/1998/namespace","xml:base",r);break;case"xmlLang":La(t,"http://www.w3.org/XML/1998/namespace","xml:lang",r);break;case"xmlSpace":La(t,"http://www.w3.org/XML/1998/namespace","xml:space",r);break;case"is":Dg(t,"is",r);break;case"innerText":case"textContent":break;default:(!(2<n.length)||n[0]!=="o"&&n[0]!=="O"||n[1]!=="n"&&n[1]!=="N")&&(n=c5.get(n)||n,Dg(t,n,r))}}function Wx(t,e,n,r,i,s){switch(n){case"style":gO(t,r,s);break;case"dangerouslySetInnerHTML":if(r!=null){if(typeof r!="object"||!("__html"in r))throw Error(Ue(61));if(n=r.__html,n!=null){if(i.children!=null)throw Error(Ue(60));t.innerHTML=n}}break;case"children":typeof r=="string"?Bd(t,r):(typeof r=="number"||typeof r=="bigint")&&Bd(t,""+r);break;case"onScroll":r!=null&&Kt("scroll",t);break;case"onScrollEnd":r!=null&&Kt("scrollend",t);break;case"onClick":r!=null&&(t.onclick=q0);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!uO.hasOwnProperty(n))e:{if(n[0]==="o"&&n[1]==="n"&&(i=n.endsWith("Capture"),e=n.slice(2,i?n.length-7:void 0),s=t[xi]||null,s=s!=null?s[n]:null,typeof s=="function"&&t.removeEventListener(e,s,i),typeof r=="function")){typeof s!="function"&&s!==null&&(n in t?t[n]=null:t.hasAttribute(n)&&t.removeAttribute(n)),t.addEventListener(e,r,i);break e}n in t?t[n]=r:r===!0?t.setAttribute(n,""):Dg(t,n,r)}}}function Ur(t,e,n){switch(e){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":Kt("error",t),Kt("load",t);var r=!1,i=!1,s;for(s in n)if(n.hasOwnProperty(s)){var a=n[s];if(a!=null)switch(s){case"src":r=!0;break;case"srcSet":i=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(Ue(137,e));default:dn(t,e,s,a,n,null)}}i&&dn(t,e,"srcSet",n.srcSet,n,null),r&&dn(t,e,"src",n.src,n,null);return;case"input":Kt("invalid",t);var o=s=a=i=null,l=null,c=null;for(r in n)if(n.hasOwnProperty(r)){var u=n[r];if(u!=null)switch(r){case"name":i=u;break;case"type":a=u;break;case"checked":l=u;break;case"defaultChecked":c=u;break;case"value":s=u;break;case"defaultValue":o=u;break;case"children":case"dangerouslySetInnerHTML":if(u!=null)throw Error(Ue(137,e));break;default:dn(t,e,r,u,n,null)}}fO(t,s,o,l,c,a,i,!1),_y(t);return;case"select":Kt("invalid",t),r=a=s=null;for(i in n)if(n.hasOwnProperty(i)&&(o=n[i],o!=null))switch(i){case"value":s=o;break;case"defaultValue":a=o;break;case"multiple":r=o;default:dn(t,e,i,o,n,null)}e=s,n=a,t.multiple=!!r,e!=null?ad(t,!!r,e,!1):n!=null&&ad(t,!!r,n,!0);return;case"textarea":Kt("invalid",t),s=i=r=null;for(a in n)if(n.hasOwnProperty(a)&&(o=n[a],o!=null))switch(a){case"value":r=o;break;case"defaultValue":i=o;break;case"children":s=o;break;case"dangerouslySetInnerHTML":if(o!=null)throw Error(Ue(91));break;default:dn(t,e,a,o,n,null)}mO(t,r,i,s),_y(t);return;case"option":for(l in n)if(n.hasOwnProperty(l)&&(r=n[l],r!=null))switch(l){case"selected":t.selected=r&&typeof r!="function"&&typeof r!="symbol";break;default:dn(t,e,l,r,n,null)}return;case"dialog":Kt("beforetoggle",t),Kt("toggle",t),Kt("cancel",t),Kt("close",t);break;case"iframe":case"object":Kt("load",t);break;case"video":case"audio":for(r=0;r<Wf.length;r++)Kt(Wf[r],t);break;case"image":Kt("error",t),Kt("load",t);break;case"details":Kt("toggle",t);break;case"embed":case"source":case"link":Kt("error",t),Kt("load",t);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(c in n)if(n.hasOwnProperty(c)&&(r=n[c],r!=null))switch(c){case"children":case"dangerouslySetInnerHTML":throw Error(Ue(137,e));default:dn(t,e,c,r,n,null)}return;default:if(gw(e)){for(u in n)n.hasOwnProperty(u)&&(r=n[u],r!==void 0&&Wx(t,e,u,r,n,void 0));return}}for(o in n)n.hasOwnProperty(o)&&(r=n[o],r!=null&&dn(t,e,o,r,n,null))}function O8(t,e,n,r){switch(e){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var i=null,s=null,a=null,o=null,l=null,c=null,u=null;for(f in n){var d=n[f];if(n.hasOwnProperty(f)&&d!=null)switch(f){case"checked":break;case"value":break;case"defaultValue":l=d;default:r.hasOwnProperty(f)||dn(t,e,f,null,r,d)}}for(var h in r){var f=r[h];if(d=n[h],r.hasOwnProperty(h)&&(f!=null||d!=null))switch(h){case"type":s=f;break;case"name":i=f;break;case"checked":c=f;break;case"defaultChecked":u=f;break;case"value":a=f;break;case"defaultValue":o=f;break;case"children":case"dangerouslySetInnerHTML":if(f!=null)throw Error(Ue(137,e));break;default:f!==d&&dn(t,e,h,f,r,d)}}vx(t,a,o,l,c,u,s,i);return;case"select":f=a=o=h=null;for(s in n)if(l=n[s],n.hasOwnProperty(s)&&l!=null)switch(s){case"value":break;case"multiple":f=l;default:r.hasOwnProperty(s)||dn(t,e,s,null,r,l)}for(i in r)if(s=r[i],l=n[i],r.hasOwnProperty(i)&&(s!=null||l!=null))switch(i){case"value":h=s;break;case"defaultValue":o=s;break;case"multiple":a=s;default:s!==l&&dn(t,e,i,s,r,l)}e=o,n=a,r=f,h!=null?ad(t,!!n,h,!1):!!r!=!!n&&(e!=null?ad(t,!!n,e,!0):ad(t,!!n,n?[]:"",!1));return;case"textarea":f=h=null;for(o in n)if(i=n[o],n.hasOwnProperty(o)&&i!=null&&!r.hasOwnProperty(o))switch(o){case"value":break;case"children":break;default:dn(t,e,o,null,r,i)}for(a in r)if(i=r[a],s=n[a],r.hasOwnProperty(a)&&(i!=null||s!=null))switch(a){case"value":h=i;break;case"defaultValue":f=i;break;case"children":break;case"dangerouslySetInnerHTML":if(i!=null)throw Error(Ue(91));break;default:i!==s&&dn(t,e,a,i,r,s)}pO(t,h,f);return;case"option":for(var p in n)if(h=n[p],n.hasOwnProperty(p)&&h!=null&&!r.hasOwnProperty(p))switch(p){case"selected":t.selected=!1;break;default:dn(t,e,p,null,r,h)}for(l in r)if(h=r[l],f=n[l],r.hasOwnProperty(l)&&h!==f&&(h!=null||f!=null))switch(l){case"selected":t.selected=h&&typeof h!="function"&&typeof h!="symbol";break;default:dn(t,e,l,h,r,f)}return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var m in n)h=n[m],n.hasOwnProperty(m)&&h!=null&&!r.hasOwnProperty(m)&&dn(t,e,m,null,r,h);for(c in r)if(h=r[c],f=n[c],r.hasOwnProperty(c)&&h!==f&&(h!=null||f!=null))switch(c){case"children":case"dangerouslySetInnerHTML":if(h!=null)throw Error(Ue(137,e));break;default:dn(t,e,c,h,r,f)}return;default:if(gw(e)){for(var g in n)h=n[g],n.hasOwnProperty(g)&&h!==void 0&&!r.hasOwnProperty(g)&&Wx(t,e,g,void 0,r,h);for(u in r)h=r[u],f=n[u],!r.hasOwnProperty(u)||h===f||h===void 0&&f===void 0||Wx(t,e,u,h,r,f);return}}for(var b in n)h=n[b],n.hasOwnProperty(b)&&h!=null&&!r.hasOwnProperty(b)&&dn(t,e,b,null,r,h);for(d in r)h=r[d],f=n[d],!r.hasOwnProperty(d)||h===f||h==null&&f==null||dn(t,e,d,h,r,f)}var Yx=null,Xx=null;function jy(t){return t.nodeType===9?t:t.ownerDocument}function NR(t){switch(t){case"http://www.w3.org/2000/svg":return 1;case"http://www.w3.org/1998/Math/MathML":return 2;default:return 0}}function yM(t,e){if(t===0)switch(e){case"svg":return 1;case"math":return 2;default:return 0}return t===1&&e==="foreignObject"?0:t}function Qx(t,e){return t==="textarea"||t==="noscript"||typeof e.children=="string"||typeof e.children=="number"||typeof e.children=="bigint"||typeof e.dangerouslySetInnerHTML=="object"&&e.dangerouslySetInnerHTML!==null&&e.dangerouslySetInnerHTML.__html!=null}var M_=null;function N8(){var t=window.event;return t&&t.type==="popstate"?t===M_?!1:(M_=t,!0):(M_=null,!1)}var vM=typeof setTimeout=="function"?setTimeout:void 0,M8=typeof clearTimeout=="function"?clearTimeout:void 0,MR=typeof Promise=="function"?Promise:void 0,B8=typeof queueMicrotask=="function"?queueMicrotask:typeof MR<"u"?function(t){return MR.resolve(null).then(t).catch(U8)}:vM;function U8(t){setTimeout(function(){throw t})}function Il(t){return t==="head"}function BR(t,e){var n=e,r=0,i=0;do{var s=n.nextSibling;if(t.removeChild(n),s&&s.nodeType===8)if(n=s.data,n==="/$"){if(0<r&&8>r){n=r;var a=t.ownerDocument;if(n&1&&bf(a.documentElement),n&2&&bf(a.body),n&4)for(n=a.head,bf(n),a=n.firstChild;a;){var o=a.nextSibling,l=a.nodeName;a[Fp]||l==="SCRIPT"||l==="STYLE"||l==="LINK"&&a.rel.toLowerCase()==="stylesheet"||n.removeChild(a),a=o}}if(i===0){t.removeChild(s),ep(e);return}i--}else n==="$"||n==="$?"||n==="$!"?i++:r=n.charCodeAt(0)-48;else r=0;n=s}while(n);ep(e)}function Jx(t){var e=t.firstChild;for(e&&e.nodeType===10&&(e=e.nextSibling);e;){var n=e;switch(e=e.nextSibling,n.nodeName){case"HTML":case"HEAD":case"BODY":Jx(n),mw(n);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(n.rel.toLowerCase()==="stylesheet")continue}t.removeChild(n)}}function j8(t,e,n,r){for(;t.nodeType===1;){var i=n;if(t.nodeName.toLowerCase()!==e.toLowerCase()){if(!r&&(t.nodeName!=="INPUT"||t.type!=="hidden"))break}else if(r){if(!t[Fp])switch(e){case"meta":if(!t.hasAttribute("itemprop"))break;return t;case"link":if(s=t.getAttribute("rel"),s==="stylesheet"&&t.hasAttribute("data-precedence"))break;if(s!==i.rel||t.getAttribute("href")!==(i.href==null||i.href===""?null:i.href)||t.getAttribute("crossorigin")!==(i.crossOrigin==null?null:i.crossOrigin)||t.getAttribute("title")!==(i.title==null?null:i.title))break;return t;case"style":if(t.hasAttribute("data-precedence"))break;return t;case"script":if(s=t.getAttribute("src"),(s!==(i.src==null?null:i.src)||t.getAttribute("type")!==(i.type==null?null:i.type)||t.getAttribute("crossorigin")!==(i.crossOrigin==null?null:i.crossOrigin))&&s&&t.hasAttribute("async")&&!t.hasAttribute("itemprop"))break;return t;default:return t}}else if(e==="input"&&t.type==="hidden"){var s=i.name==null?null:""+i.name;if(i.type==="hidden"&&t.getAttribute("name")===s)return t}else return t;if(t=Is(t.nextSibling),t===null)break}return null}function F8(t,e,n){if(e==="")return null;for(;t.nodeType!==3;)if((t.nodeType!==1||t.nodeName!=="INPUT"||t.type!=="hidden")&&!n||(t=Is(t.nextSibling),t===null))return null;return t}function Zx(t){return t.data==="$!"||t.data==="$?"&&t.ownerDocument.readyState==="complete"}function $8(t,e){var n=t.ownerDocument;if(t.data!=="$?"||n.readyState==="complete")e();else{var r=function(){e(),n.removeEventListener("DOMContentLoaded",r)};n.addEventListener("DOMContentLoaded",r),t._reactRetry=r}}function Is(t){for(;t!=null;t=t.nextSibling){var e=t.nodeType;if(e===1||e===3)break;if(e===8){if(e=t.data,e==="$"||e==="$!"||e==="$?"||e==="F!"||e==="F")break;if(e==="/$")return null}}return t}var eS=null;function UR(t){t=t.previousSibling;for(var e=0;t;){if(t.nodeType===8){var n=t.data;if(n==="$"||n==="$!"||n==="$?"){if(e===0)return t;e--}else n==="/$"&&e++}t=t.previousSibling}return null}function _M(t,e,n){switch(e=jy(n),t){case"html":if(t=e.documentElement,!t)throw Error(Ue(452));return t;case"head":if(t=e.head,!t)throw Error(Ue(453));return t;case"body":if(t=e.body,!t)throw Error(Ue(454));return t;default:throw Error(Ue(451))}}function bf(t){for(var e=t.attributes;e.length;)t.removeAttributeNode(e[0]);mw(t)}var gs=new Map,jR=new Set;function Fy(t){return typeof t.getRootNode=="function"?t.getRootNode():t.nodeType===9?t:t.ownerDocument}var ho=en.d;en.d={f:V8,r:G8,D:H8,C:K8,L:z8,m:q8,X:Y8,S:W8,M:X8};function V8(){var t=ho.f(),e=H0();return t||e}function G8(t){var e=sh(t);e!==null&&e.tag===5&&e.type==="form"?hN(e):ho.r(t)}var lh=typeof document>"u"?null:document;function bM(t,e,n){var r=lh;if(r&&typeof e=="string"&&e){var i=cs(e);i='link[rel="'+t+'"][href="'+i+'"]',typeof n=="string"&&(i+='[crossorigin="'+n+'"]'),jR.has(i)||(jR.add(i),t={rel:t,crossOrigin:n,href:e},r.querySelector(i)===null&&(e=r.createElement("link"),Ur(e,"link",t),Er(e),r.head.appendChild(e)))}}function H8(t){ho.D(t),bM("dns-prefetch",t,null)}function K8(t,e){ho.C(t,e),bM("preconnect",t,e)}function z8(t,e,n){ho.L(t,e,n);var r=lh;if(r&&t&&e){var i='link[rel="preload"][as="'+cs(e)+'"]';e==="image"&&n&&n.imageSrcSet?(i+='[imagesrcset="'+cs(n.imageSrcSet)+'"]',typeof n.imageSizes=="string"&&(i+='[imagesizes="'+cs(n.imageSizes)+'"]')):i+='[href="'+cs(t)+'"]';var s=i;switch(e){case"style":s=Kd(t);break;case"script":s=ch(t)}gs.has(s)||(t=Rn({rel:"preload",href:e==="image"&&n&&n.imageSrcSet?void 0:t,as:e},n),gs.set(s,t),r.querySelector(i)!==null||e==="style"&&r.querySelector(Xp(s))||e==="script"&&r.querySelector(Qp(s))||(e=r.createElement("link"),Ur(e,"link",t),Er(e),r.head.appendChild(e)))}}function q8(t,e){ho.m(t,e);var n=lh;if(n&&t){var r=e&&typeof e.as=="string"?e.as:"script",i='link[rel="modulepreload"][as="'+cs(r)+'"][href="'+cs(t)+'"]',s=i;switch(r){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":s=ch(t)}if(!gs.has(s)&&(t=Rn({rel:"modulepreload",href:t},e),gs.set(s,t),n.querySelector(i)===null)){switch(r){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(n.querySelector(Qp(s)))return}r=n.createElement("link"),Ur(r,"link",t),Er(r),n.head.appendChild(r)}}}function W8(t,e,n){ho.S(t,e,n);var r=lh;if(r&&t){var i=sd(r).hoistableStyles,s=Kd(t);e=e||"default";var a=i.get(s);if(!a){var o={loading:0,preload:null};if(a=r.querySelector(Xp(s)))o.loading=5;else{t=Rn({rel:"stylesheet",href:t,"data-precedence":e},n),(n=gs.get(s))&&Jw(t,n);var l=a=r.createElement("link");Er(l),Ur(l,"link",t),l._p=new Promise(function(c,u){l.onload=c,l.onerror=u}),l.addEventListener("load",function(){o.loading|=1}),l.addEventListener("error",function(){o.loading|=2}),o.loading|=4,Gg(a,e,r)}a={type:"stylesheet",instance:a,count:1,state:o},i.set(s,a)}}}function Y8(t,e){ho.X(t,e);var n=lh;if(n&&t){var r=sd(n).hoistableScripts,i=ch(t),s=r.get(i);s||(s=n.querySelector(Qp(i)),s||(t=Rn({src:t,async:!0},e),(e=gs.get(i))&&Zw(t,e),s=n.createElement("script"),Er(s),Ur(s,"link",t),n.head.appendChild(s)),s={type:"script",instance:s,count:1,state:null},r.set(i,s))}}function X8(t,e){ho.M(t,e);var n=lh;if(n&&t){var r=sd(n).hoistableScripts,i=ch(t),s=r.get(i);s||(s=n.querySelector(Qp(i)),s||(t=Rn({src:t,async:!0,type:"module"},e),(e=gs.get(i))&&Zw(t,e),s=n.createElement("script"),Er(s),Ur(s,"link",t),n.head.appendChild(s)),s={type:"script",instance:s,count:1,state:null},r.set(i,s))}}function FR(t,e,n,r){var i=(i=al.current)?Fy(i):null;if(!i)throw Error(Ue(446));switch(t){case"meta":case"title":return null;case"style":return typeof n.precedence=="string"&&typeof n.href=="string"?(e=Kd(n.href),n=sd(i).hoistableStyles,r=n.get(e),r||(r={type:"style",instance:null,count:0,state:null},n.set(e,r)),r):{type:"void",instance:null,count:0,state:null};case"link":if(n.rel==="stylesheet"&&typeof n.href=="string"&&typeof n.precedence=="string"){t=Kd(n.href);var s=sd(i).hoistableStyles,a=s.get(t);if(a||(i=i.ownerDocument||i,a={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},s.set(t,a),(s=i.querySelector(Xp(t)))&&!s._p&&(a.instance=s,a.state.loading=5),gs.has(t)||(n={rel:"preload",as:"style",href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},gs.set(t,n),s||Q8(i,t,n,a.state))),e&&r===null)throw Error(Ue(528,""));return a}if(e&&r!==null)throw Error(Ue(529,""));return null;case"script":return e=n.async,n=n.src,typeof n=="string"&&e&&typeof e!="function"&&typeof e!="symbol"?(e=ch(n),n=sd(i).hoistableScripts,r=n.get(e),r||(r={type:"script",instance:null,count:0,state:null},n.set(e,r)),r):{type:"void",instance:null,count:0,state:null};default:throw Error(Ue(444,t))}}function Kd(t){return'href="'+cs(t)+'"'}function Xp(t){return'link[rel="stylesheet"]['+t+"]"}function xM(t){return Rn({},t,{"data-precedence":t.precedence,precedence:null})}function Q8(t,e,n,r){t.querySelector('link[rel="preload"][as="style"]['+e+"]")?r.loading=1:(e=t.createElement("link"),r.preload=e,e.addEventListener("load",function(){return r.loading|=1}),e.addEventListener("error",function(){return r.loading|=2}),Ur(e,"link",n),Er(e),t.head.appendChild(e))}function ch(t){return'[src="'+cs(t)+'"]'}function Qp(t){return"script[async]"+t}function $R(t,e,n){if(e.count++,e.instance===null)switch(e.type){case"style":var r=t.querySelector('style[data-href~="'+cs(n.href)+'"]');if(r)return e.instance=r,Er(r),r;var i=Rn({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(t.ownerDocument||t).createElement("style"),Er(r),Ur(r,"style",i),Gg(r,n.precedence,t),e.instance=r;case"stylesheet":i=Kd(n.href);var s=t.querySelector(Xp(i));if(s)return e.state.loading|=4,e.instance=s,Er(s),s;r=xM(n),(i=gs.get(i))&&Jw(r,i),s=(t.ownerDocument||t).createElement("link"),Er(s);var a=s;return a._p=new Promise(function(o,l){a.onload=o,a.onerror=l}),Ur(s,"link",r),e.state.loading|=4,Gg(s,n.precedence,t),e.instance=s;case"script":return s=ch(n.src),(i=t.querySelector(Qp(s)))?(e.instance=i,Er(i),i):(r=n,(i=gs.get(s))&&(r=Rn({},n),Zw(r,i)),t=t.ownerDocument||t,i=t.createElement("script"),Er(i),Ur(i,"link",r),t.head.appendChild(i),e.instance=i);case"void":return null;default:throw Error(Ue(443,e.type))}else e.type==="stylesheet"&&!(e.state.loading&4)&&(r=e.instance,e.state.loading|=4,Gg(r,n.precedence,t));return e.instance}function Gg(t,e,n){for(var r=n.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),i=r.length?r[r.length-1]:null,s=i,a=0;a<r.length;a++){var o=r[a];if(o.dataset.precedence===e)s=o;else if(s!==i)break}s?s.parentNode.insertBefore(t,s.nextSibling):(e=n.nodeType===9?n.head:n,e.insertBefore(t,e.firstChild))}function Jw(t,e){t.crossOrigin==null&&(t.crossOrigin=e.crossOrigin),t.referrerPolicy==null&&(t.referrerPolicy=e.referrerPolicy),t.title==null&&(t.title=e.title)}function Zw(t,e){t.crossOrigin==null&&(t.crossOrigin=e.crossOrigin),t.referrerPolicy==null&&(t.referrerPolicy=e.referrerPolicy),t.integrity==null&&(t.integrity=e.integrity)}var Hg=null;function VR(t,e,n){if(Hg===null){var r=new Map,i=Hg=new Map;i.set(n,r)}else i=Hg,r=i.get(n),r||(r=new Map,i.set(n,r));if(r.has(t))return r;for(r.set(t,null),n=n.getElementsByTagName(t),i=0;i<n.length;i++){var s=n[i];if(!(s[Fp]||s[Hr]||t==="link"&&s.getAttribute("rel")==="stylesheet")&&s.namespaceURI!=="http://www.w3.org/2000/svg"){var a=s.getAttribute(e)||"";a=t+a;var o=r.get(a);o?o.push(s):r.set(a,[s])}}return r}function GR(t,e,n){t=t.ownerDocument||t,t.head.insertBefore(n,e==="title"?t.querySelector("head > title"):null)}function J8(t,e,n){if(n===1||e.itemProp!=null)return!1;switch(t){case"meta":case"title":return!0;case"style":if(typeof e.precedence!="string"||typeof e.href!="string"||e.href==="")break;return!0;case"link":if(typeof e.rel!="string"||typeof e.href!="string"||e.href===""||e.onLoad||e.onError)break;switch(e.rel){case"stylesheet":return t=e.disabled,typeof e.precedence=="string"&&t==null;default:return!0}case"script":if(e.async&&typeof e.async!="function"&&typeof e.async!="symbol"&&!e.onLoad&&!e.onError&&e.src&&typeof e.src=="string")return!0}return!1}function SM(t){return!(t.type==="stylesheet"&&!(t.state.loading&3))}var Xf=null;function Z8(){}function eV(t,e,n){if(Xf===null)throw Error(Ue(475));var r=Xf;if(e.type==="stylesheet"&&(typeof n.media!="string"||matchMedia(n.media).matches!==!1)&&!(e.state.loading&4)){if(e.instance===null){var i=Kd(n.href),s=t.querySelector(Xp(i));if(s){t=s._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(r.count++,r=$y.bind(r),t.then(r,r)),e.state.loading|=4,e.instance=s,Er(s);return}s=t.ownerDocument||t,n=xM(n),(i=gs.get(i))&&Jw(n,i),s=s.createElement("link"),Er(s);var a=s;a._p=new Promise(function(o,l){a.onload=o,a.onerror=l}),Ur(s,"link",n),e.instance=s}r.stylesheets===null&&(r.stylesheets=new Map),r.stylesheets.set(e,t),(t=e.state.preload)&&!(e.state.loading&3)&&(r.count++,e=$y.bind(r),t.addEventListener("load",e),t.addEventListener("error",e))}}function tV(){if(Xf===null)throw Error(Ue(475));var t=Xf;return t.stylesheets&&t.count===0&&tS(t,t.stylesheets),0<t.count?function(e){var n=setTimeout(function(){if(t.stylesheets&&tS(t,t.stylesheets),t.unsuspend){var r=t.unsuspend;t.unsuspend=null,r()}},6e4);return t.unsuspend=e,function(){t.unsuspend=null,clearTimeout(n)}}:null}function $y(){if(this.count--,this.count===0){if(this.stylesheets)tS(this,this.stylesheets);else if(this.unsuspend){var t=this.unsuspend;this.unsuspend=null,t()}}}var Vy=null;function tS(t,e){t.stylesheets=null,t.unsuspend!==null&&(t.count++,Vy=new Map,e.forEach(nV,t),Vy=null,$y.call(t))}function nV(t,e){if(!(e.state.loading&4)){var n=Vy.get(t);if(n)var r=n.get(null);else{n=new Map,Vy.set(t,n);for(var i=t.querySelectorAll("link[data-precedence],style[data-precedence]"),s=0;s<i.length;s++){var a=i[s];(a.nodeName==="LINK"||a.getAttribute("media")!=="not all")&&(n.set(a.dataset.precedence,a),r=a)}r&&n.set(null,r)}i=e.instance,a=i.getAttribute("data-precedence"),s=n.get(a)||r,s===r&&n.set(null,i),n.set(a,i),this.count++,r=$y.bind(this),i.addEventListener("load",r),i.addEventListener("error",r),s?s.parentNode.insertBefore(i,s.nextSibling):(t=t.nodeType===9?t.head:t,t.insertBefore(i,t.firstChild)),e.state.loading|=4}}var Qf={$$typeof:Ya,Provider:null,Consumer:null,_currentValue:bc,_currentValue2:bc,_threadCount:0};function rV(t,e,n,r,i,s,a,o){this.tag=1,this.containerInfo=t,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=i_(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=i_(0),this.hiddenUpdates=i_(null),this.identifierPrefix=r,this.onUncaughtError=i,this.onCaughtError=s,this.onRecoverableError=a,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=o,this.incompleteTransitions=new Map}function EM(t,e,n,r,i,s,a,o,l,c,u,d){return t=new rV(t,e,n,a,o,l,c,d),e=1,s===!0&&(e|=24),s=Bi(3,null,null,e),t.current=s,s.stateNode=t,e=Rw(),e.refCount++,t.pooledCache=e,e.refCount++,s.memoizedState={element:r,isDehydrated:n,cache:e},Lw(s),t}function wM(t){return t?(t=qu,t):qu}function TM(t,e,n,r,i,s){i=wM(i),r.context===null?r.context=i:r.pendingContext=i,r=ol(e),r.payload={element:n},s=s===void 0?null:s,s!==null&&(r.callback=s),n=ll(t,r,e),n!==null&&(Vi(n,t,e),hf(n,t,e))}function HR(t,e){if(t=t.memoizedState,t!==null&&t.dehydrated!==null){var n=t.retryLane;t.retryLane=n!==0&&n<e?n:e}}function eT(t,e){HR(t,e),(t=t.alternate)&&HR(t,e)}function AM(t){if(t.tag===13){var e=ah(t,67108864);e!==null&&Vi(e,t,67108864),eT(t,67108864)}}var Gy=!0;function iV(t,e,n,r){var i=xt.T;xt.T=null;var s=en.p;try{en.p=2,tT(t,e,n,r)}finally{en.p=s,xt.T=i}}function sV(t,e,n,r){var i=xt.T;xt.T=null;var s=en.p;try{en.p=8,tT(t,e,n,r)}finally{en.p=s,xt.T=i}}function tT(t,e,n,r){if(Gy){var i=nS(r);if(i===null)N_(t,e,r,Hy,n),KR(t,r);else if(oV(i,t,e,n,r))r.stopPropagation();else if(KR(t,r),e&4&&-1<aV.indexOf(t)){for(;i!==null;){var s=sh(i);if(s!==null)switch(s.tag){case 3:if(s=s.stateNode,s.current.memoizedState.isDehydrated){var a=Yl(s.pendingLanes);if(a!==0){var o=s;for(o.pendingLanes|=2,o.entangledLanes|=2;a;){var l=1<<31-Fi(a);o.entanglements[1]|=l,a&=~l}_a(s),!(cn&6)&&(Oy=ca()+500,Yp(0))}}break;case 13:o=ah(s,2),o!==null&&Vi(o,s,2),H0(),eT(s,2)}if(s=nS(r),s===null&&N_(t,e,r,Hy,n),s===i)break;i=s}i!==null&&r.stopPropagation()}else N_(t,e,r,null,n)}}function nS(t){return t=yw(t),nT(t)}var Hy=null;function nT(t){if(Hy=null,t=$u(t),t!==null){var e=Mp(t);if(e===null)t=null;else{var n=e.tag;if(n===13){if(t=QD(e),t!==null)return t;t=null}else if(n===3){if(e.stateNode.current.memoizedState.isDehydrated)return e.tag===3?e.stateNode.containerInfo:null;t=null}else e!==t&&(t=null)}}return Hy=t,null}function RM(t){switch(t){case"beforetoggle":case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"toggle":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 2;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 8;case"message":switch(K$()){case tO:return 2;case nO:return 8;case vy:case z$:return 32;case rO:return 268435456;default:return 32}default:return 32}}var rS=!1,dl=null,hl=null,fl=null,Jf=new Map,Zf=new Map,Vo=[],aV="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(" ");function KR(t,e){switch(t){case"focusin":case"focusout":dl=null;break;case"dragenter":case"dragleave":hl=null;break;case"mouseover":case"mouseout":fl=null;break;case"pointerover":case"pointerout":Jf.delete(e.pointerId);break;case"gotpointercapture":case"lostpointercapture":Zf.delete(e.pointerId)}}function Uh(t,e,n,r,i,s){return t===null||t.nativeEvent!==s?(t={blockedOn:e,domEventName:n,eventSystemFlags:r,nativeEvent:s,targetContainers:[i]},e!==null&&(e=sh(e),e!==null&&AM(e)),t):(t.eventSystemFlags|=r,e=t.targetContainers,i!==null&&e.indexOf(i)===-1&&e.push(i),t)}function oV(t,e,n,r,i){switch(e){case"focusin":return dl=Uh(dl,t,e,n,r,i),!0;case"dragenter":return hl=Uh(hl,t,e,n,r,i),!0;case"mouseover":return fl=Uh(fl,t,e,n,r,i),!0;case"pointerover":var s=i.pointerId;return Jf.set(s,Uh(Jf.get(s)||null,t,e,n,r,i)),!0;case"gotpointercapture":return s=i.pointerId,Zf.set(s,Uh(Zf.get(s)||null,t,e,n,r,i)),!0}return!1}function CM(t){var e=$u(t.target);if(e!==null){var n=Mp(e);if(n!==null){if(e=n.tag,e===13){if(e=QD(n),e!==null){t.blockedOn=e,e5(t.priority,function(){if(n.tag===13){var r=$i();r=fw(r);var i=ah(n,r);i!==null&&Vi(i,n,r),eT(n,r)}});return}}else if(e===3&&n.stateNode.current.memoizedState.isDehydrated){t.blockedOn=n.tag===3?n.stateNode.containerInfo:null;return}}}t.blockedOn=null}function Kg(t){if(t.blockedOn!==null)return!1;for(var e=t.targetContainers;0<e.length;){var n=nS(t.nativeEvent);if(n===null){n=t.nativeEvent;var r=new n.constructor(n.type,n);bx=r,n.target.dispatchEvent(r),bx=null}else return e=sh(n),e!==null&&AM(e),t.blockedOn=n,!1;e.shift()}return!0}function zR(t,e,n){Kg(t)&&n.delete(e)}function lV(){rS=!1,dl!==null&&Kg(dl)&&(dl=null),hl!==null&&Kg(hl)&&(hl=null),fl!==null&&Kg(fl)&&(fl=null),Jf.forEach(zR),Zf.forEach(zR)}function Vm(t,e){t.blockedOn===e&&(t.blockedOn=null,rS||(rS=!0,gr.unstable_scheduleCallback(gr.unstable_NormalPriority,lV)))}var Gm=null;function qR(t){Gm!==t&&(Gm=t,gr.unstable_scheduleCallback(gr.unstable_NormalPriority,function(){Gm===t&&(Gm=null);for(var e=0;e<t.length;e+=3){var n=t[e],r=t[e+1],i=t[e+2];if(typeof r!="function"){if(nT(r||n)===null)continue;break}var s=sh(n);s!==null&&(t.splice(e,3),e-=3,Mx(s,{pending:!0,data:i,method:n.method,action:r},r,i))}}))}function ep(t){function e(l){return Vm(l,t)}dl!==null&&Vm(dl,t),hl!==null&&Vm(hl,t),fl!==null&&Vm(fl,t),Jf.forEach(e),Zf.forEach(e);for(var n=0;n<Vo.length;n++){var r=Vo[n];r.blockedOn===t&&(r.blockedOn=null)}for(;0<Vo.length&&(n=Vo[0],n.blockedOn===null);)CM(n),n.blockedOn===null&&Vo.shift();if(n=(t.ownerDocument||t).$$reactFormReplay,n!=null)for(r=0;r<n.length;r+=3){var i=n[r],s=n[r+1],a=i[xi]||null;if(typeof s=="function")a||qR(n);else if(a){var o=null;if(s&&s.hasAttribute("formAction")){if(i=s,a=s[xi]||null)o=a.formAction;else if(nT(i)!==null)continue}else o=a.action;typeof o=="function"?n[r+1]=o:(n.splice(r,3),r-=3),qR(n)}}}function rT(t){this._internalRoot=t}W0.prototype.render=rT.prototype.render=function(t){var e=this._internalRoot;if(e===null)throw Error(Ue(409));var n=e.current,r=$i();TM(n,r,t,e,null,null)};W0.prototype.unmount=rT.prototype.unmount=function(){var t=this._internalRoot;if(t!==null){this._internalRoot=null;var e=t.containerInfo;TM(t.current,2,null,t,null,null),H0(),e[ih]=null}};function W0(t){this._internalRoot=t}W0.prototype.unstable_scheduleHydration=function(t){if(t){var e=lO();t={blockedOn:null,target:t,priority:e};for(var n=0;n<Vo.length&&e!==0&&e<Vo[n].priority;n++);Vo.splice(n,0,t),n===0&&CM(t)}};var WR=YD.version;if(WR!=="19.1.0")throw Error(Ue(527,WR,"19.1.0"));en.findDOMNode=function(t){var e=t._reactInternals;if(e===void 0)throw typeof t.render=="function"?Error(Ue(188)):(t=Object.keys(t).join(","),Error(Ue(268,t)));return t=U$(e),t=t!==null?JD(t):null,t=t===null?null:t.stateNode,t};var cV={bundleType:0,version:"19.1.0",rendererPackageName:"react-dom",currentDispatcherRef:xt,reconcilerVersion:"19.1.0"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Hm=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Hm.isDisabled&&Hm.supportsFiber)try{Bp=Hm.inject(cV),ji=Hm}catch{}}P0.createRoot=function(t,e){if(!XD(t))throw Error(Ue(299));var n=!1,r="",i=EN,s=wN,a=TN,o=null;return e!=null&&(e.unstable_strictMode===!0&&(n=!0),e.identifierPrefix!==void 0&&(r=e.identifierPrefix),e.onUncaughtError!==void 0&&(i=e.onUncaughtError),e.onCaughtError!==void 0&&(s=e.onCaughtError),e.onRecoverableError!==void 0&&(a=e.onRecoverableError),e.unstable_transitionCallbacks!==void 0&&(o=e.unstable_transitionCallbacks)),e=EM(t,1,!1,null,null,n,r,i,s,a,o,null),t[ih]=e.current,Qw(t),new rT(e)};P0.hydrateRoot=function(t,e,n){if(!XD(t))throw Error(Ue(299));var r=!1,i="",s=EN,a=wN,o=TN,l=null,c=null;return n!=null&&(n.unstable_strictMode===!0&&(r=!0),n.identifierPrefix!==void 0&&(i=n.identifierPrefix),n.onUncaughtError!==void 0&&(s=n.onUncaughtError),n.onCaughtError!==void 0&&(a=n.onCaughtError),n.onRecoverableError!==void 0&&(o=n.onRecoverableError),n.unstable_transitionCallbacks!==void 0&&(l=n.unstable_transitionCallbacks),n.formState!==void 0&&(c=n.formState)),e=EM(t,1,!0,e,n??null,r,i,s,a,o,l,c),e.context=wM(null),n=e.current,r=$i(),r=fw(r),i=ol(r),i.callback=null,ll(n,i,r),n=r,e.current.lanes=n,jp(e,n),_a(e),t[ih]=e.current,Qw(t),new W0(e)};P0.version="19.1.0";function LM(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(LM)}catch(t){console.error(t)}}LM(),ND.exports=P0;var uV=ND.exports,Jp=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},dc,zo,Sd,ED,dV=(ED=class extends Jp{constructor(){super();gt(this,dc);gt(this,zo);gt(this,Sd);et(this,Sd,e=>{if(typeof window<"u"&&window.addEventListener){const n=()=>e();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){ue(this,zo)||this.setEventListener(ue(this,Sd))}onUnsubscribe(){var e;this.hasListeners()||((e=ue(this,zo))==null||e.call(this),et(this,zo,void 0))}setEventListener(e){var n;et(this,Sd,e),(n=ue(this,zo))==null||n.call(this),et(this,zo,e(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(e){ue(this,dc)!==e&&(et(this,dc,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(n=>{n(e)})}isFocused(){var e;return typeof ue(this,dc)=="boolean"?ue(this,dc):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},dc=new WeakMap,zo=new WeakMap,Sd=new WeakMap,ED),iT=new dV,hV={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},qo,rw,wD,fV=(wD=class{constructor(){gt(this,qo,hV);gt(this,rw,!1)}setTimeoutProvider(t){et(this,qo,t)}setTimeout(t,e){return ue(this,qo).setTimeout(t,e)}clearTimeout(t){ue(this,qo).clearTimeout(t)}setInterval(t,e){return ue(this,qo).setInterval(t,e)}clearInterval(t){ue(this,qo).clearInterval(t)}},qo=new WeakMap,rw=new WeakMap,wD),ic=new fV;function pV(t){setTimeout(t,0)}var mV=typeof window>"u"||"Deno"in globalThis;function _i(){}function gV(t,e){return typeof t=="function"?t(e):t}function iS(t){return typeof t=="number"&&t>=0&&t!==1/0}function kM(t,e){return Math.max(t+(e||0)-Date.now(),0)}function pl(t,e){return typeof t=="function"?t(e):t}function Di(t,e){return typeof t=="function"?t(e):t}function YR(t,e){const{type:n="all",exact:r,fetchStatus:i,predicate:s,queryKey:a,stale:o}=t;if(a){if(r){if(e.queryHash!==sT(a,e.options))return!1}else if(!np(e.queryKey,a))return!1}if(n!=="all"){const l=e.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof o=="boolean"&&e.isStale()!==o||i&&i!==e.state.fetchStatus||s&&!s(e))}function XR(t,e){const{exact:n,status:r,predicate:i,mutationKey:s}=t;if(s){if(!e.options.mutationKey)return!1;if(n){if(tp(e.options.mutationKey)!==tp(s))return!1}else if(!np(e.options.mutationKey,s))return!1}return!(r&&e.state.status!==r||i&&!i(e))}function sT(t,e){return((e==null?void 0:e.queryKeyHashFn)||tp)(t)}function tp(t){return JSON.stringify(t,(e,n)=>aS(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function np(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(n=>np(t[n],e[n])):!1}var yV=Object.prototype.hasOwnProperty;function IM(t,e,n=0){if(t===e)return t;if(n>500)return e;const r=QR(t)&&QR(e);if(!r&&!(aS(t)&&aS(e)))return e;const s=(r?t:Object.keys(t)).length,a=r?e:Object.keys(e),o=a.length,l=r?new Array(o):{};let c=0;for(let u=0;u<o;u++){const d=r?u:a[u],h=t[d],f=e[d];if(h===f){l[d]=h,(r?u<s:yV.call(t,d))&&c++;continue}if(h===null||f===null||typeof h!="object"||typeof f!="object"){l[d]=f;continue}const p=IM(h,f,n+1);l[d]=p,p===h&&c++}return s===o&&c===s?t:l}function sS(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(const n in t)if(t[n]!==e[n])return!1;return!0}function QR(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function aS(t){if(!JR(t))return!1;const e=t.constructor;if(e===void 0)return!0;const n=e.prototype;return!(!JR(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}function JR(t){return Object.prototype.toString.call(t)==="[object Object]"}function vV(t){return new Promise(e=>{ic.setTimeout(e,t)})}function oS(t,e,n){return typeof n.structuralSharing=="function"?n.structuralSharing(t,e):n.structuralSharing!==!1?IM(t,e):e}function _V(t,e,n=0){const r=[...t,e];return n&&r.length>n?r.slice(1):r}function bV(t,e,n=0){const r=[e,...t];return n&&r.length>n?r.slice(0,-1):r}var aT=Symbol();function PM(t,e){return!t.queryFn&&(e!=null&&e.initialPromise)?()=>e.initialPromise:!t.queryFn||t.queryFn===aT?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function DM(t,e){return typeof t=="function"?t(...e):!!t}function xV(t,e,n){let r=!1,i;return Object.defineProperty(t,"signal",{enumerable:!0,get:()=>(i??(i=e()),r||(r=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),t}var rp=(()=>{let t=()=>mV;return{isServer(){return t()},setIsServer(e){t=e}}})();function lS(){let t,e;const n=new Promise((i,s)=>{t=i,e=s});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),t(i)},n.reject=i=>{r({status:"rejected",reason:i}),e(i)},n}var SV=pV;function EV(){let t=[],e=0,n=o=>{o()},r=o=>{o()},i=SV;const s=o=>{e?t.push(o):i(()=>{n(o)})},a=()=>{const o=t;t=[],o.length&&i(()=>{r(()=>{o.forEach(l=>{n(l)})})})};return{batch:o=>{let l;e++;try{l=o()}finally{e--,e||a()}return l},batchCalls:o=>(...l)=>{s(()=>{o(...l)})},schedule:s,setNotifyFunction:o=>{n=o},setBatchNotifyFunction:o=>{r=o},setScheduler:o=>{i=o}}}var Or=EV(),Ed,Wo,wd,TD,wV=(TD=class extends Jp{constructor(){super();gt(this,Ed,!0);gt(this,Wo);gt(this,wd);et(this,wd,e=>{if(typeof window<"u"&&window.addEventListener){const n=()=>e(!0),r=()=>e(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){ue(this,Wo)||this.setEventListener(ue(this,wd))}onUnsubscribe(){var e;this.hasListeners()||((e=ue(this,Wo))==null||e.call(this),et(this,Wo,void 0))}setEventListener(e){var n;et(this,wd,e),(n=ue(this,Wo))==null||n.call(this),et(this,Wo,e(this.setOnline.bind(this)))}setOnline(e){ue(this,Ed)!==e&&(et(this,Ed,e),this.listeners.forEach(r=>{r(e)}))}isOnline(){return ue(this,Ed)}},Ed=new WeakMap,Wo=new WeakMap,wd=new WeakMap,TD),Ky=new wV;function TV(t){return Math.min(1e3*2**t,3e4)}function OM(t){return(t??"online")==="online"?Ky.isOnline():!0}var cS=class extends Error{constructor(t){super("CancelledError"),this.revert=t==null?void 0:t.revert,this.silent=t==null?void 0:t.silent}};function NM(t){let e=!1,n=0,r;const i=lS(),s=()=>i.status!=="pending",a=m=>{var g;if(!s()){const b=new cS(m);h(b),(g=t.onCancel)==null||g.call(t,b)}},o=()=>{e=!0},l=()=>{e=!1},c=()=>iT.isFocused()&&(t.networkMode==="always"||Ky.isOnline())&&t.canRun(),u=()=>OM(t.networkMode)&&t.canRun(),d=m=>{s()||(r==null||r(),i.resolve(m))},h=m=>{s()||(r==null||r(),i.reject(m))},f=()=>new Promise(m=>{var g;r=b=>{(s()||c())&&m(b)},(g=t.onPause)==null||g.call(t)}).then(()=>{var m;r=void 0,s()||(m=t.onContinue)==null||m.call(t)}),p=()=>{if(s())return;let m;const g=n===0?t.initialPromise:void 0;try{m=g??t.fn()}catch(b){m=Promise.reject(b)}Promise.resolve(m).then(d).catch(b=>{var U;if(s())return;const v=t.retry??(rp.isServer()?0:3),S=t.retryDelay??TV,E=typeof S=="function"?S(n,b):S,L=v===!0||typeof v=="number"&&n<v||typeof v=="function"&&v(n,b);if(e||!L){h(b);return}n++,(U=t.onFail)==null||U.call(t,n,b),vV(E).then(()=>c()?void 0:f()).then(()=>{e?h(b):p()})})};return{promise:i,status:()=>i.status,cancel:a,continue:()=>(r==null||r(),i),cancelRetry:o,continueRetry:l,canStart:u,start:()=>(u()?p():f().then(p),i)}}var hc,AD,MM=(AD=class{constructor(){gt(this,hc)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),iS(this.gcTime)&&et(this,hc,ic.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(rp.isServer()?1/0:5*60*1e3))}clearGcTimeout(){ue(this,hc)!==void 0&&(ic.clearTimeout(ue(this,hc)),et(this,hc,void 0))}},hc=new WeakMap,AD);function AV(t){return{onFetch:(e,n)=>{var u,d,h,f,p;const r=e.options,i=(h=(d=(u=e.fetchOptions)==null?void 0:u.meta)==null?void 0:d.fetchMore)==null?void 0:h.direction,s=((f=e.state.data)==null?void 0:f.pages)||[],a=((p=e.state.data)==null?void 0:p.pageParams)||[];let o={pages:[],pageParams:[]},l=0;const c=async()=>{let m=!1;const g=S=>{xV(S,()=>e.signal,()=>m=!0)},b=PM(e.options,e.fetchOptions),v=async(S,E,L)=>{if(m)return Promise.reject(e.signal.reason);if(E==null&&S.pages.length)return Promise.resolve(S);const O=(()=>{const M={client:e.client,queryKey:e.queryKey,pageParam:E,direction:L?"backward":"forward",meta:e.options.meta};return g(M),M})(),k=await b(O),{maxPages:I}=e.options,R=L?bV:_V;return{pages:R(S.pages,k,I),pageParams:R(S.pageParams,E,I)}};if(i&&s.length){const S=i==="backward",E=S?RV:ZR,L={pages:s,pageParams:a},U=E(r,L);o=await v(L,U,S)}else{const S=t??s.length;do{const E=l===0?a[0]??r.initialPageParam:ZR(r,o);if(l>0&&E==null)break;o=await v(o,E),l++}while(l<S)}return o};e.options.persister?e.fetchFn=()=>{var m,g;return(g=(m=e.options).persister)==null?void 0:g.call(m,c,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},n)}:e.fetchFn=c}}}function ZR(t,{pages:e,pageParams:n}){const r=e.length-1;return e.length>0?t.getNextPageParam(e[r],e,n[r],n):void 0}function RV(t,{pages:e,pageParams:n}){var r;return e.length>0?(r=t.getPreviousPageParam)==null?void 0:r.call(t,e[0],e,n[0],n):void 0}var Td,fc,Ad,is,pc,xr,kp,mc,Pi,BM,Fa,RD,CV=(RD=class extends MM{constructor(e){super();gt(this,Pi);gt(this,Td);gt(this,fc);gt(this,Ad);gt(this,is);gt(this,pc);gt(this,xr);gt(this,kp);gt(this,mc);et(this,mc,!1),et(this,kp,e.defaultOptions),this.setOptions(e.options),this.observers=[],et(this,pc,e.client),et(this,is,ue(this,pc).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,et(this,fc,tC(this.options)),this.state=e.state??ue(this,fc),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return ue(this,Td)}get promise(){var e;return(e=ue(this,xr))==null?void 0:e.promise}setOptions(e){if(this.options={...ue(this,kp),...e},e!=null&&e._type&&et(this,Td,e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=tC(this.options);n.data!==void 0&&(this.setState(eC(n.data,n.dataUpdatedAt)),et(this,fc,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&ue(this,is).remove(this)}setData(e,n){const r=oS(this.state.data,e,this.options);return Wt(this,Pi,Fa).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(e){Wt(this,Pi,Fa).call(this,{type:"setState",state:e})}cancel(e){var r,i;const n=(r=ue(this,xr))==null?void 0:r.promise;return(i=ue(this,xr))==null||i.cancel(e),n?n.then(_i).catch(_i):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return ue(this,fc)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>Di(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===aT||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>pl(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!kM(this.state.dataUpdatedAt,e)}onFocus(){var n;const e=this.observers.find(r=>r.shouldFetchOnWindowFocus());e==null||e.refetch({cancelRefetch:!1}),(n=ue(this,xr))==null||n.continue()}onOnline(){var n;const e=this.observers.find(r=>r.shouldFetchOnReconnect());e==null||e.refetch({cancelRefetch:!1}),(n=ue(this,xr))==null||n.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),ue(this,is).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(n=>n!==e),this.observers.length||(ue(this,xr)&&(ue(this,mc)||Wt(this,Pi,BM).call(this)?ue(this,xr).cancel({revert:!0}):ue(this,xr).cancelRetry()),this.scheduleGc()),ue(this,is).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Wt(this,Pi,Fa).call(this,{type:"invalidate"})}async fetch(e,n){var c,u,d,h,f,p,m,g,b,v,S;if(this.state.fetchStatus!=="idle"&&((c=ue(this,xr))==null?void 0:c.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(ue(this,xr))return ue(this,xr).continueRetry(),ue(this,xr).promise}if(e&&this.setOptions(e),!this.options.queryFn){const E=this.observers.find(L=>L.options.queryFn);E&&this.setOptions(E.options)}const r=new AbortController,i=E=>{Object.defineProperty(E,"signal",{enumerable:!0,get:()=>(et(this,mc,!0),r.signal)})},s=()=>{const E=PM(this.options,n),U=(()=>{const O={client:ue(this,pc),queryKey:this.queryKey,meta:this.meta};return i(O),O})();return et(this,mc,!1),this.options.persister?this.options.persister(E,U,this):E(U)},o=(()=>{const E={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:ue(this,pc),state:this.state,fetchFn:s};return i(E),E})(),l=ue(this,Td)==="infinite"?AV(this.options.pages):this.options.behavior;l==null||l.onFetch(o,this),et(this,Ad,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((u=o.fetchOptions)==null?void 0:u.meta))&&Wt(this,Pi,Fa).call(this,{type:"fetch",meta:(d=o.fetchOptions)==null?void 0:d.meta}),et(this,xr,NM({initialPromise:n==null?void 0:n.initialPromise,fn:o.fetchFn,onCancel:E=>{E instanceof cS&&E.revert&&this.setState({...ue(this,Ad),fetchStatus:"idle"}),r.abort()},onFail:(E,L)=>{Wt(this,Pi,Fa).call(this,{type:"failed",failureCount:E,error:L})},onPause:()=>{Wt(this,Pi,Fa).call(this,{type:"pause"})},onContinue:()=>{Wt(this,Pi,Fa).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0}));try{const E=await ue(this,xr).start();if(E===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(E),(f=(h=ue(this,is).config).onSuccess)==null||f.call(h,E,this),(m=(p=ue(this,is).config).onSettled)==null||m.call(p,E,this.state.error,this),E}catch(E){if(E instanceof cS){if(E.silent)return ue(this,xr).promise;if(E.revert){if(this.state.data===void 0)throw E;return this.state.data}}throw Wt(this,Pi,Fa).call(this,{type:"error",error:E}),(b=(g=ue(this,is).config).onError)==null||b.call(g,E,this),(S=(v=ue(this,is).config).onSettled)==null||S.call(v,this.state.data,E,this),E}finally{this.scheduleGc()}}},Td=new WeakMap,fc=new WeakMap,Ad=new WeakMap,is=new WeakMap,pc=new WeakMap,xr=new WeakMap,kp=new WeakMap,mc=new WeakMap,Pi=new WeakSet,BM=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Fa=function(e){const n=r=>{switch(e.type){case"failed":return{...r,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...UM(r.data,this.options),fetchMeta:e.meta??null};case"success":const i={...r,...eC(e.data,e.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return et(this,Ad,e.manual?i:void 0),i;case"error":const s=e.error;return{...r,error:s,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:s,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...e.state}}};this.state=n(this.state),Or.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),ue(this,is).notify({query:this,type:"updated",action:e})})},RD);function UM(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:OM(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function eC(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function tC(t){const e=typeof t.initialData=="function"?t.initialData():t.initialData,n=e!==void 0,r=n?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var pi,Yt,Ip,Zr,gc,Rd,za,Yo,Pp,Cd,Ld,yc,vc,Xo,kd,rn,Jh,uS,dS,hS,fS,pS,mS,gS,jM,CD,LV=(CD=class extends Jp{constructor(e,n){super();gt(this,rn);gt(this,pi);gt(this,Yt);gt(this,Ip);gt(this,Zr);gt(this,gc);gt(this,Rd);gt(this,za);gt(this,Yo);gt(this,Pp);gt(this,Cd);gt(this,Ld);gt(this,yc);gt(this,vc);gt(this,Xo);gt(this,kd,new Set);this.options=n,et(this,pi,e),et(this,Yo,null),et(this,za,lS()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(ue(this,Yt).addObserver(this),nC(ue(this,Yt),this.options)?Wt(this,rn,Jh).call(this):this.updateResult(),Wt(this,rn,fS).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return yS(ue(this,Yt),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return yS(ue(this,Yt),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Wt(this,rn,pS).call(this),Wt(this,rn,mS).call(this),ue(this,Yt).removeObserver(this)}setOptions(e){const n=this.options,r=ue(this,Yt);if(this.options=ue(this,pi).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Di(this.options.enabled,ue(this,Yt))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Wt(this,rn,gS).call(this),ue(this,Yt).setOptions(this.options),n._defaulted&&!sS(this.options,n)&&ue(this,pi).getQueryCache().notify({type:"observerOptionsUpdated",query:ue(this,Yt),observer:this});const i=this.hasListeners();i&&rC(ue(this,Yt),r,this.options,n)&&Wt(this,rn,Jh).call(this),this.updateResult(),i&&(ue(this,Yt)!==r||Di(this.options.enabled,ue(this,Yt))!==Di(n.enabled,ue(this,Yt))||pl(this.options.staleTime,ue(this,Yt))!==pl(n.staleTime,ue(this,Yt)))&&Wt(this,rn,uS).call(this);const s=Wt(this,rn,dS).call(this);i&&(ue(this,Yt)!==r||Di(this.options.enabled,ue(this,Yt))!==Di(n.enabled,ue(this,Yt))||s!==ue(this,Xo))&&Wt(this,rn,hS).call(this,s)}getOptimisticResult(e){const n=ue(this,pi).getQueryCache().build(ue(this,pi),e),r=this.createResult(n,e);return IV(this,r)&&(et(this,Zr,r),et(this,Rd,this.options),et(this,gc,ue(this,Yt).state)),r}getCurrentResult(){return ue(this,Zr)}trackResult(e,n){return new Proxy(e,{get:(r,i)=>(this.trackProp(i),n==null||n(i),i==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&ue(this,za).status==="pending"&&ue(this,za).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,i))})}trackProp(e){ue(this,kd).add(e)}getCurrentQuery(){return ue(this,Yt)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const n=ue(this,pi).defaultQueryOptions(e),r=ue(this,pi).getQueryCache().build(ue(this,pi),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(e){return Wt(this,rn,Jh).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),ue(this,Zr)))}createResult(e,n){var I;const r=ue(this,Yt),i=this.options,s=ue(this,Zr),a=ue(this,gc),o=ue(this,Rd),c=e!==r?e.state:ue(this,Ip),{state:u}=e;let d={...u},h=!1,f;if(n._optimisticResults){const R=this.hasListeners(),M=!R&&nC(e,n),z=R&&rC(e,r,n,i);(M||z)&&(d={...d,...UM(u.data,e.options)}),n._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:p,errorUpdatedAt:m,status:g}=d;f=d.data;let b=!1;if(n.placeholderData!==void 0&&f===void 0&&g==="pending"){let R;s!=null&&s.isPlaceholderData&&n.placeholderData===(o==null?void 0:o.placeholderData)?(R=s.data,b=!0):R=typeof n.placeholderData=="function"?n.placeholderData((I=ue(this,Ld))==null?void 0:I.state.data,ue(this,Ld)):n.placeholderData,R!==void 0&&(g="success",f=oS(s==null?void 0:s.data,R,n),h=!0)}if(n.select&&f!==void 0&&!b)if(s&&f===(a==null?void 0:a.data)&&n.select===ue(this,Pp))f=ue(this,Cd);else try{et(this,Pp,n.select),f=n.select(f),f=oS(s==null?void 0:s.data,f,n),et(this,Cd,f),et(this,Yo,null)}catch(R){et(this,Yo,R)}ue(this,Yo)&&(p=ue(this,Yo),f=ue(this,Cd),m=Date.now(),g="error");const v=d.fetchStatus==="fetching",S=g==="pending",E=g==="error",L=S&&v,U=f!==void 0,k={status:g,fetchStatus:d.fetchStatus,isPending:S,isSuccess:g==="success",isError:E,isInitialLoading:L,isLoading:L,data:f,dataUpdatedAt:d.dataUpdatedAt,error:p,errorUpdatedAt:m,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:d.dataUpdateCount>c.dataUpdateCount||d.errorUpdateCount>c.errorUpdateCount,isFetching:v,isRefetching:v&&!S,isLoadingError:E&&!U,isPaused:d.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:E&&U,isStale:oT(e,n),refetch:this.refetch,promise:ue(this,za),isEnabled:Di(n.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const R=k.data!==void 0,M=k.status==="error"&&!R,z=re=>{M?re.reject(k.error):R&&re.resolve(k.data)},Z=()=>{const re=et(this,za,k.promise=lS());z(re)},W=ue(this,za);switch(W.status){case"pending":e.queryHash===r.queryHash&&z(W);break;case"fulfilled":(M||k.data!==W.value)&&Z();break;case"rejected":(!M||k.error!==W.reason)&&Z();break}}return k}updateResult(){const e=ue(this,Zr),n=this.createResult(ue(this,Yt),this.options);if(et(this,gc,ue(this,Yt).state),et(this,Rd,this.options),ue(this,gc).data!==void 0&&et(this,Ld,ue(this,Yt)),sS(n,e))return;et(this,Zr,n);const r=()=>{if(!e)return!0;const{notifyOnChangeProps:i}=this.options,s=typeof i=="function"?i():i;if(s==="all"||!s&&!ue(this,kd).size)return!0;const a=new Set(s??ue(this,kd));return this.options.throwOnError&&a.add("error"),Object.keys(ue(this,Zr)).some(o=>{const l=o;return ue(this,Zr)[l]!==e[l]&&a.has(l)})};Wt(this,rn,jM).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Wt(this,rn,fS).call(this)}},pi=new WeakMap,Yt=new WeakMap,Ip=new WeakMap,Zr=new WeakMap,gc=new WeakMap,Rd=new WeakMap,za=new WeakMap,Yo=new WeakMap,Pp=new WeakMap,Cd=new WeakMap,Ld=new WeakMap,yc=new WeakMap,vc=new WeakMap,Xo=new WeakMap,kd=new WeakMap,rn=new WeakSet,Jh=function(e){Wt(this,rn,gS).call(this);let n=ue(this,Yt).fetch(this.options,e);return e!=null&&e.throwOnError||(n=n.catch(_i)),n},uS=function(){Wt(this,rn,pS).call(this);const e=pl(this.options.staleTime,ue(this,Yt));if(rp.isServer()||ue(this,Zr).isStale||!iS(e))return;const r=kM(ue(this,Zr).dataUpdatedAt,e)+1;et(this,yc,ic.setTimeout(()=>{ue(this,Zr).isStale||this.updateResult()},r))},dS=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(ue(this,Yt)):this.options.refetchInterval)??!1},hS=function(e){Wt(this,rn,mS).call(this),et(this,Xo,e),!(rp.isServer()||Di(this.options.enabled,ue(this,Yt))===!1||!iS(ue(this,Xo))||ue(this,Xo)===0)&&et(this,vc,ic.setInterval(()=>{(this.options.refetchIntervalInBackground||iT.isFocused())&&Wt(this,rn,Jh).call(this)},ue(this,Xo)))},fS=function(){Wt(this,rn,uS).call(this),Wt(this,rn,hS).call(this,Wt(this,rn,dS).call(this))},pS=function(){ue(this,yc)!==void 0&&(ic.clearTimeout(ue(this,yc)),et(this,yc,void 0))},mS=function(){ue(this,vc)!==void 0&&(ic.clearInterval(ue(this,vc)),et(this,vc,void 0))},gS=function(){const e=ue(this,pi).getQueryCache().build(ue(this,pi),this.options);if(e===ue(this,Yt))return;const n=ue(this,Yt);et(this,Yt,e),et(this,Ip,e.state),this.hasListeners()&&(n==null||n.removeObserver(this),e.addObserver(this))},jM=function(e){Or.batch(()=>{e.listeners&&this.listeners.forEach(n=>{n(ue(this,Zr))}),ue(this,pi).getQueryCache().notify({query:ue(this,Yt),type:"observerResultsUpdated"})})},CD);function kV(t,e){return Di(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&Di(e.retryOnMount,t)===!1)}function nC(t,e){return kV(t,e)||t.state.data!==void 0&&yS(t,e,e.refetchOnMount)}function yS(t,e,n){if(Di(e.enabled,t)!==!1&&pl(e.staleTime,t)!=="static"){const r=typeof n=="function"?n(t):n;return r==="always"||r!==!1&&oT(t,e)}return!1}function rC(t,e,n,r){return(t!==e||Di(r.enabled,t)===!1)&&(!n.suspense||t.state.status!=="error")&&oT(t,n)}function oT(t,e){return Di(e.enabled,t)!==!1&&t.isStaleByTime(pl(e.staleTime,t))}function IV(t,e){return!sS(t.getCurrentResult(),e)}var Dp,Ws,Gr,_c,Ys,ko,LD,PV=(LD=class extends MM{constructor(e){super();gt(this,Ys);gt(this,Dp);gt(this,Ws);gt(this,Gr);gt(this,_c);et(this,Dp,e.client),this.mutationId=e.mutationId,et(this,Gr,e.mutationCache),et(this,Ws,[]),this.state=e.state||DV(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){ue(this,Ws).includes(e)||(ue(this,Ws).push(e),this.clearGcTimeout(),ue(this,Gr).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){et(this,Ws,ue(this,Ws).filter(n=>n!==e)),this.scheduleGc(),ue(this,Gr).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){ue(this,Ws).length||(this.state.status==="pending"?this.scheduleGc():ue(this,Gr).remove(this))}continue(){var e;return((e=ue(this,_c))==null?void 0:e.continue())??this.execute(this.state.variables)}async execute(e){var a,o,l,c,u,d,h,f,p,m,g,b,v,S,E,L,U,O;const n=()=>{Wt(this,Ys,ko).call(this,{type:"continue"})},r={client:ue(this,Dp),meta:this.options.meta,mutationKey:this.options.mutationKey};et(this,_c,NM({fn:()=>this.options.mutationFn?this.options.mutationFn(e,r):Promise.reject(new Error("No mutationFn found")),onFail:(k,I)=>{Wt(this,Ys,ko).call(this,{type:"failed",failureCount:k,error:I})},onPause:()=>{Wt(this,Ys,ko).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>ue(this,Gr).canRun(this)}));const i=this.state.status==="pending",s=!ue(this,_c).canStart();try{if(i)n();else{Wt(this,Ys,ko).call(this,{type:"pending",variables:e,isPaused:s}),ue(this,Gr).config.onMutate&&await ue(this,Gr).config.onMutate(e,this,r);const I=await((o=(a=this.options).onMutate)==null?void 0:o.call(a,e,r));I!==this.state.context&&Wt(this,Ys,ko).call(this,{type:"pending",context:I,variables:e,isPaused:s})}const k=await ue(this,_c).start();return await((c=(l=ue(this,Gr).config).onSuccess)==null?void 0:c.call(l,k,e,this.state.context,this,r)),await((d=(u=this.options).onSuccess)==null?void 0:d.call(u,k,e,this.state.context,r)),await((f=(h=ue(this,Gr).config).onSettled)==null?void 0:f.call(h,k,null,this.state.variables,this.state.context,this,r)),await((m=(p=this.options).onSettled)==null?void 0:m.call(p,k,null,e,this.state.context,r)),Wt(this,Ys,ko).call(this,{type:"success",data:k}),k}catch(k){try{await((b=(g=ue(this,Gr).config).onError)==null?void 0:b.call(g,k,e,this.state.context,this,r))}catch(I){Promise.reject(I)}try{await((S=(v=this.options).onError)==null?void 0:S.call(v,k,e,this.state.context,r))}catch(I){Promise.reject(I)}try{await((L=(E=ue(this,Gr).config).onSettled)==null?void 0:L.call(E,void 0,k,this.state.variables,this.state.context,this,r))}catch(I){Promise.reject(I)}try{await((O=(U=this.options).onSettled)==null?void 0:O.call(U,void 0,k,e,this.state.context,r))}catch(I){Promise.reject(I)}throw Wt(this,Ys,ko).call(this,{type:"error",error:k}),k}finally{ue(this,Gr).runNext(this)}}},Dp=new WeakMap,Ws=new WeakMap,Gr=new WeakMap,_c=new WeakMap,Ys=new WeakSet,ko=function(e){const n=r=>{switch(e.type){case"failed":return{...r,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...r,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:e.error,failureCount:r.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=n(this.state),Or.batch(()=>{ue(this,Ws).forEach(r=>{r.onMutationUpdate(e)}),ue(this,Gr).notify({mutation:this,type:"updated",action:e})})},LD);function DV(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var qa,Ls,Op,kD,OV=(kD=class extends Jp{constructor(e={}){super();gt(this,qa);gt(this,Ls);gt(this,Op);this.config=e,et(this,qa,new Set),et(this,Ls,new Map),et(this,Op,0)}build(e,n,r){const i=new PV({client:e,mutationCache:this,mutationId:++Lm(this,Op)._,options:e.defaultMutationOptions(n),state:r});return this.add(i),i}add(e){ue(this,qa).add(e);const n=Km(e);if(typeof n=="string"){const r=ue(this,Ls).get(n);r?r.push(e):ue(this,Ls).set(n,[e])}this.notify({type:"added",mutation:e})}remove(e){if(ue(this,qa).delete(e)){const n=Km(e);if(typeof n=="string"){const r=ue(this,Ls).get(n);if(r)if(r.length>1){const i=r.indexOf(e);i!==-1&&r.splice(i,1)}else r[0]===e&&ue(this,Ls).delete(n)}}this.notify({type:"removed",mutation:e})}canRun(e){const n=Km(e);if(typeof n=="string"){const r=ue(this,Ls).get(n),i=r==null?void 0:r.find(s=>s.state.status==="pending");return!i||i===e}else return!0}runNext(e){var r;const n=Km(e);if(typeof n=="string"){const i=(r=ue(this,Ls).get(n))==null?void 0:r.find(s=>s!==e&&s.state.isPaused);return(i==null?void 0:i.continue())??Promise.resolve()}else return Promise.resolve()}clear(){Or.batch(()=>{ue(this,qa).forEach(e=>{this.notify({type:"removed",mutation:e})}),ue(this,qa).clear(),ue(this,Ls).clear()})}getAll(){return Array.from(ue(this,qa))}find(e){const n={exact:!0,...e};return this.getAll().find(r=>XR(n,r))}findAll(e={}){return this.getAll().filter(n=>XR(e,n))}notify(e){Or.batch(()=>{this.listeners.forEach(n=>{n(e)})})}resumePausedMutations(){const e=this.getAll().filter(n=>n.state.isPaused);return Or.batch(()=>Promise.all(e.map(n=>n.continue().catch(_i))))}},qa=new WeakMap,Ls=new WeakMap,Op=new WeakMap,kD);function Km(t){var e;return(e=t.options.scope)==null?void 0:e.id}var Xs,ID,NV=(ID=class extends Jp{constructor(e={}){super();gt(this,Xs);this.config=e,et(this,Xs,new Map)}build(e,n,r){const i=n.queryKey,s=n.queryHash??sT(i,n);let a=this.get(s);return a||(a=new CV({client:e,queryKey:i,queryHash:s,options:e.defaultQueryOptions(n),state:r,defaultOptions:e.getQueryDefaults(i)}),this.add(a)),a}add(e){ue(this,Xs).has(e.queryHash)||(ue(this,Xs).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const n=ue(this,Xs).get(e.queryHash);n&&(e.destroy(),n===e&&ue(this,Xs).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Or.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return ue(this,Xs).get(e)}getAll(){return[...ue(this,Xs).values()]}find(e){const n={exact:!0,...e};return this.getAll().find(r=>YR(n,r))}findAll(e={}){const n=this.getAll();return Object.keys(e).length>0?n.filter(r=>YR(e,r)):n}notify(e){Or.batch(()=>{this.listeners.forEach(n=>{n(e)})})}onFocus(){Or.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Or.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Xs=new WeakMap,ID),Vn,Qo,Jo,Id,Pd,Zo,Dd,Od,PD,MV=(PD=class{constructor(t={}){gt(this,Vn);gt(this,Qo);gt(this,Jo);gt(this,Id);gt(this,Pd);gt(this,Zo);gt(this,Dd);gt(this,Od);et(this,Vn,t.queryCache||new NV),et(this,Qo,t.mutationCache||new OV),et(this,Jo,t.defaultOptions||{}),et(this,Id,new Map),et(this,Pd,new Map),et(this,Zo,0)}mount(){Lm(this,Zo)._++,ue(this,Zo)===1&&(et(this,Dd,iT.subscribe(async t=>{t&&(await this.resumePausedMutations(),ue(this,Vn).onFocus())})),et(this,Od,Ky.subscribe(async t=>{t&&(await this.resumePausedMutations(),ue(this,Vn).onOnline())})))}unmount(){var t,e;Lm(this,Zo)._--,ue(this,Zo)===0&&((t=ue(this,Dd))==null||t.call(this),et(this,Dd,void 0),(e=ue(this,Od))==null||e.call(this),et(this,Od,void 0))}isFetching(t){return ue(this,Vn).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return ue(this,Qo).findAll({...t,status:"pending"}).length}getQueryData(t){var n;const e=this.defaultQueryOptions({queryKey:t});return(n=ue(this,Vn).get(e.queryHash))==null?void 0:n.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),n=ue(this,Vn).build(this,e),r=n.state.data;return r===void 0?this.fetchQuery(t):(t.revalidateIfStale&&n.isStaleByTime(pl(e.staleTime,n))&&this.prefetchQuery(e),Promise.resolve(r))}getQueriesData(t){return ue(this,Vn).findAll(t).map(({queryKey:e,state:n})=>{const r=n.data;return[e,r]})}setQueryData(t,e,n){const r=this.defaultQueryOptions({queryKey:t}),i=ue(this,Vn).get(r.queryHash),s=i==null?void 0:i.state.data,a=gV(e,s);if(a!==void 0)return ue(this,Vn).build(this,r).setData(a,{...n,manual:!0})}setQueriesData(t,e,n){return Or.batch(()=>ue(this,Vn).findAll(t).map(({queryKey:r})=>[r,this.setQueryData(r,e,n)]))}getQueryState(t){var n;const e=this.defaultQueryOptions({queryKey:t});return(n=ue(this,Vn).get(e.queryHash))==null?void 0:n.state}removeQueries(t){const e=ue(this,Vn);Or.batch(()=>{e.findAll(t).forEach(n=>{e.remove(n)})})}resetQueries(t,e){const n=ue(this,Vn);return Or.batch(()=>(n.findAll(t).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){const n={revert:!0,...e},r=Or.batch(()=>ue(this,Vn).findAll(t).map(i=>i.cancel(n)));return Promise.all(r).then(_i).catch(_i)}invalidateQueries(t,e={}){return Or.batch(()=>(ue(this,Vn).findAll(t).forEach(n=>{n.invalidate()}),(t==null?void 0:t.refetchType)==="none"?Promise.resolve():this.refetchQueries({...t,type:(t==null?void 0:t.refetchType)??(t==null?void 0:t.type)??"active"},e)))}refetchQueries(t,e={}){const n={...e,cancelRefetch:e.cancelRefetch??!0},r=Or.batch(()=>ue(this,Vn).findAll(t).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let s=i.fetch(void 0,n);return n.throwOnError||(s=s.catch(_i)),i.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(r).then(_i)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const n=ue(this,Vn).build(this,e);return n.isStaleByTime(pl(e.staleTime,n))?n.fetch(e):Promise.resolve(n.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(_i).catch(_i)}fetchInfiniteQuery(t){return t._type="infinite",this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(_i).catch(_i)}ensureInfiniteQueryData(t){return t._type="infinite",this.ensureQueryData(t)}resumePausedMutations(){return Ky.isOnline()?ue(this,Qo).resumePausedMutations():Promise.resolve()}getQueryCache(){return ue(this,Vn)}getMutationCache(){return ue(this,Qo)}getDefaultOptions(){return ue(this,Jo)}setDefaultOptions(t){et(this,Jo,t)}setQueryDefaults(t,e){ue(this,Id).set(tp(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...ue(this,Id).values()],n={};return e.forEach(r=>{np(t,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(t,e){ue(this,Pd).set(tp(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...ue(this,Pd).values()],n={};return e.forEach(r=>{np(t,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(t){if(t._defaulted)return t;const e={...ue(this,Jo).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=sT(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===aT&&(e.enabled=!1),e}defaultMutationOptions(t){return t!=null&&t._defaulted?t:{...ue(this,Jo).mutations,...(t==null?void 0:t.mutationKey)&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){ue(this,Vn).clear(),ue(this,Qo).clear()}},Vn=new WeakMap,Qo=new WeakMap,Jo=new WeakMap,Id=new WeakMap,Pd=new WeakMap,Zo=new WeakMap,Dd=new WeakMap,Od=new WeakMap,PD),FM=D.createContext(void 0),lT=t=>{const e=D.useContext(FM);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},BV=({client:t,children:e})=>(D.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),y.jsx(FM.Provider,{value:t,children:e})),$M=D.createContext(!1),UV=()=>D.useContext($M);$M.Provider;function jV(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var FV=D.createContext(jV()),$V=()=>D.useContext(FV),VV=(t,e,n)=>{const r=n!=null&&n.state.error&&typeof t.throwOnError=="function"?DM(t.throwOnError,[n.state.error,n]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||r)&&(e.isReset()||(t.retryOnMount=!1))},GV=t=>{D.useEffect(()=>{t.clearReset()},[t])},HV=({result:t,errorResetBoundary:e,throwOnError:n,query:r,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&r&&(i&&t.data===void 0||DM(n,[t.error,r])),KV=t=>{if(t.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),r=t.staleTime;t.staleTime=typeof r=="function"?(...i)=>n(r(...i)):n(r),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},zV=(t,e)=>t.isLoading&&t.isFetching&&!e,qV=(t,e)=>(t==null?void 0:t.suspense)&&e.isPending,iC=(t,e,n)=>e.fetchOptimistic(t).catch(()=>{n.clearReset()});function WV(t,e,n){var h,f,p,m;const r=UV(),i=$V(),s=lT(),a=s.defaultQueryOptions(t);(f=(h=s.getDefaultOptions().queries)==null?void 0:h._experimental_beforeQuery)==null||f.call(h,a);const o=s.getQueryCache().get(a.queryHash);a._optimisticResults=r?"isRestoring":"optimistic",KV(a),VV(a,i,o),GV(i);const l=!s.getQueryCache().get(a.queryHash),[c]=D.useState(()=>new e(s,a)),u=c.getOptimisticResult(a),d=!r&&t.subscribed!==!1;if(D.useSyncExternalStore(D.useCallback(g=>{const b=d?c.subscribe(Or.batchCalls(g)):_i;return c.updateResult(),b},[c,d]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),D.useEffect(()=>{c.setOptions(a)},[a,c]),qV(a,u))throw iC(a,c,i);if(HV({result:u,errorResetBoundary:i,throwOnError:a.throwOnError,query:o,suspense:a.suspense}))throw u.error;if((m=(p=s.getDefaultOptions().queries)==null?void 0:p._experimental_afterQuery)==null||m.call(p,a,u),a.experimental_prefetchInRender&&!rp.isServer()&&zV(u,r)){const g=l?iC(a,c,i):o==null?void 0:o.promise;g==null||g.catch(_i).finally(()=>{c.updateResult()})}return a.notifyOnChangeProps?u:c.trackResult(u)}function uh(t,e){return WV(t,LV)}/**
 * @remix-run/router v1.23.2
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */function ip(){return ip=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},ip.apply(this,arguments)}var il;(function(t){t.Pop="POP",t.Push="PUSH",t.Replace="REPLACE"})(il||(il={}));const sC="popstate";function YV(t){t===void 0&&(t={});function e(r,i){let{pathname:s,search:a,hash:o}=r.location;return vS("",{pathname:s,search:a,hash:o},i.state&&i.state.usr||null,i.state&&i.state.key||"default")}function n(r,i){return typeof i=="string"?i:zy(i)}return QV(e,n,null,t)}function er(t,e){if(t===!1||t===null||typeof t>"u")throw new Error(e)}function cT(t,e){if(!t){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function XV(){return Math.random().toString(36).substr(2,8)}function aC(t,e){return{usr:t.state,key:t.key,idx:e}}function vS(t,e,n,r){return n===void 0&&(n=null),ip({pathname:typeof t=="string"?t:t.pathname,search:"",hash:""},typeof e=="string"?dh(e):e,{state:n,key:e&&e.key||r||XV()})}function zy(t){let{pathname:e="/",search:n="",hash:r=""}=t;return n&&n!=="?"&&(e+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(e+=r.charAt(0)==="#"?r:"#"+r),e}function dh(t){let e={};if(t){let n=t.indexOf("#");n>=0&&(e.hash=t.substr(n),t=t.substr(0,n));let r=t.indexOf("?");r>=0&&(e.search=t.substr(r),t=t.substr(0,r)),t&&(e.pathname=t)}return e}function QV(t,e,n,r){r===void 0&&(r={});let{window:i=document.defaultView,v5Compat:s=!1}=r,a=i.history,o=il.Pop,l=null,c=u();c==null&&(c=0,a.replaceState(ip({},a.state,{idx:c}),""));function u(){return(a.state||{idx:null}).idx}function d(){o=il.Pop;let g=u(),b=g==null?null:g-c;c=g,l&&l({action:o,location:m.location,delta:b})}function h(g,b){o=il.Push;let v=vS(m.location,g,b);c=u()+1;let S=aC(v,c),E=m.createHref(v);try{a.pushState(S,"",E)}catch(L){if(L instanceof DOMException&&L.name==="DataCloneError")throw L;i.location.assign(E)}s&&l&&l({action:o,location:m.location,delta:1})}function f(g,b){o=il.Replace;let v=vS(m.location,g,b);c=u();let S=aC(v,c),E=m.createHref(v);a.replaceState(S,"",E),s&&l&&l({action:o,location:m.location,delta:0})}function p(g){let b=i.location.origin!=="null"?i.location.origin:i.location.href,v=typeof g=="string"?g:zy(g);return v=v.replace(/ $/,"%20"),er(b,"No window.location.(origin|href) available to create URL for href: "+v),new URL(v,b)}let m={get action(){return o},get location(){return t(i,a)},listen(g){if(l)throw new Error("A history only accepts one active listener");return i.addEventListener(sC,d),l=g,()=>{i.removeEventListener(sC,d),l=null}},createHref(g){return e(i,g)},createURL:p,encodeLocation(g){let b=p(g);return{pathname:b.pathname,search:b.search,hash:b.hash}},push:h,replace:f,go(g){return a.go(g)}};return m}var oC;(function(t){t.data="data",t.deferred="deferred",t.redirect="redirect",t.error="error"})(oC||(oC={}));function JV(t,e,n){return n===void 0&&(n="/"),ZV(t,e,n)}function ZV(t,e,n,r){let i=typeof e=="string"?dh(e):e,s=uT(i.pathname||"/",n);if(s==null)return null;let a=VM(t);e6(a);let o=null;for(let l=0;o==null&&l<a.length;++l){let c=h6(s);o=c6(a[l],c)}return o}function VM(t,e,n,r){e===void 0&&(e=[]),n===void 0&&(n=[]),r===void 0&&(r="");let i=(s,a,o)=>{let l={relativePath:o===void 0?s.path||"":o,caseSensitive:s.caseSensitive===!0,childrenIndex:a,route:s};l.relativePath.startsWith("/")&&(er(l.relativePath.startsWith(r),'Absolute route path "'+l.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),l.relativePath=l.relativePath.slice(r.length));let c=ml([r,l.relativePath]),u=n.concat(l);s.children&&s.children.length>0&&(er(s.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+c+'".')),VM(s.children,e,u,c)),!(s.path==null&&!s.index)&&e.push({path:c,score:o6(c,s.index),routesMeta:u})};return t.forEach((s,a)=>{var o;if(s.path===""||!((o=s.path)!=null&&o.includes("?")))i(s,a);else for(let l of GM(s.path))i(s,a,l)}),e}function GM(t){let e=t.split("/");if(e.length===0)return[];let[n,...r]=e,i=n.endsWith("?"),s=n.replace(/\?$/,"");if(r.length===0)return i?[s,""]:[s];let a=GM(r.join("/")),o=[];return o.push(...a.map(l=>l===""?s:[s,l].join("/"))),i&&o.push(...a),o.map(l=>t.startsWith("/")&&l===""?"/":l)}function e6(t){t.sort((e,n)=>e.score!==n.score?n.score-e.score:l6(e.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const t6=/^:[\w-]+$/,n6=3,r6=2,i6=1,s6=10,a6=-2,lC=t=>t==="*";function o6(t,e){let n=t.split("/"),r=n.length;return n.some(lC)&&(r+=a6),e&&(r+=r6),n.filter(i=>!lC(i)).reduce((i,s)=>i+(t6.test(s)?n6:s===""?i6:s6),r)}function l6(t,e){return t.length===e.length&&t.slice(0,-1).every((r,i)=>r===e[i])?t[t.length-1]-e[e.length-1]:0}function c6(t,e,n){let{routesMeta:r}=t,i={},s="/",a=[];for(let o=0;o<r.length;++o){let l=r[o],c=o===r.length-1,u=s==="/"?e:e.slice(s.length)||"/",d=u6({path:l.relativePath,caseSensitive:l.caseSensitive,end:c},u),h=l.route;if(!d)return null;Object.assign(i,d.params),a.push({params:i,pathname:ml([s,d.pathname]),pathnameBase:y6(ml([s,d.pathnameBase])),route:h}),d.pathnameBase!=="/"&&(s=ml([s,d.pathnameBase]))}return a}function u6(t,e){typeof t=="string"&&(t={path:t,caseSensitive:!1,end:!0});let[n,r]=d6(t.path,t.caseSensitive,t.end),i=e.match(n);if(!i)return null;let s=i[0],a=s.replace(/(.)\/+$/,"$1"),o=i.slice(1);return{params:r.reduce((c,u,d)=>{let{paramName:h,isOptional:f}=u;if(h==="*"){let m=o[d]||"";a=s.slice(0,s.length-m.length).replace(/(.)\/+$/,"$1")}const p=o[d];return f&&!p?c[h]=void 0:c[h]=(p||"").replace(/%2F/g,"/"),c},{}),pathname:s,pathnameBase:a,pattern:t}}function d6(t,e,n){e===void 0&&(e=!1),n===void 0&&(n=!0),cT(t==="*"||!t.endsWith("*")||t.endsWith("/*"),'Route path "'+t+'" will be treated as if it were '+('"'+t.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+t.replace(/\*$/,"/*")+'".'));let r=[],i="^"+t.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(a,o,l)=>(r.push({paramName:o,isOptional:l!=null}),l?"/?([^\\/]+)?":"/([^\\/]+)"));return t.endsWith("*")?(r.push({paramName:"*"}),i+=t==="*"||t==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?i+="\\/*$":t!==""&&t!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,e?void 0:"i"),r]}function h6(t){try{return t.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return cT(!1,'The URL path "'+t+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+e+").")),t}}function uT(t,e){if(e==="/")return t;if(!t.toLowerCase().startsWith(e.toLowerCase()))return null;let n=e.endsWith("/")?e.length-1:e.length,r=t.charAt(n);return r&&r!=="/"?null:t.slice(n)||"/"}const f6=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,p6=t=>f6.test(t);function m6(t,e){e===void 0&&(e="/");let{pathname:n,search:r="",hash:i=""}=typeof t=="string"?dh(t):t,s;if(n)if(p6(n))s=n;else{if(n.includes("//")){let a=n;n=n.replace(/\/\/+/g,"/"),cT(!1,"Pathnames cannot have embedded double slashes - normalizing "+(a+" -> "+n))}n.startsWith("/")?s=cC(n.substring(1),"/"):s=cC(n,e)}else s=e;return{pathname:s,search:v6(r),hash:_6(i)}}function cC(t,e){let n=e.replace(/\/+$/,"").split("/");return t.split("/").forEach(i=>{i===".."?n.length>1&&n.pop():i!=="."&&n.push(i)}),n.length>1?n.join("/"):"/"}function B_(t,e,n,r){return"Cannot include a '"+t+"' character in a manually specified "+("`to."+e+"` field ["+JSON.stringify(r)+"].  Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in <Link to="..."> and the router will parse it for you.'}function g6(t){return t.filter((e,n)=>n===0||e.route.path&&e.route.path.length>0)}function dT(t,e){let n=g6(t);return e?n.map((r,i)=>i===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function hT(t,e,n,r){r===void 0&&(r=!1);let i;typeof t=="string"?i=dh(t):(i=ip({},t),er(!i.pathname||!i.pathname.includes("?"),B_("?","pathname","search",i)),er(!i.pathname||!i.pathname.includes("#"),B_("#","pathname","hash",i)),er(!i.search||!i.search.includes("#"),B_("#","search","hash",i)));let s=t===""||i.pathname==="",a=s?"/":i.pathname,o;if(a==null)o=n;else{let d=e.length-1;if(!r&&a.startsWith("..")){let h=a.split("/");for(;h[0]==="..";)h.shift(),d-=1;i.pathname=h.join("/")}o=d>=0?e[d]:"/"}let l=m6(i,o),c=a&&a!=="/"&&a.endsWith("/"),u=(s||a===".")&&n.endsWith("/");return!l.pathname.endsWith("/")&&(c||u)&&(l.pathname+="/"),l}const ml=t=>t.join("/").replace(/\/\/+/g,"/"),y6=t=>t.replace(/\/+$/,"").replace(/^\/*/,"/"),v6=t=>!t||t==="?"?"":t.startsWith("?")?t:"?"+t,_6=t=>!t||t==="#"?"":t.startsWith("#")?t:"#"+t;function b6(t){return t!=null&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.internal=="boolean"&&"data"in t}const HM=["post","put","patch","delete"];new Set(HM);const x6=["get",...HM];new Set(x6);/**
 * React Router v6.30.3
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */function sp(){return sp=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},sp.apply(this,arguments)}const fT=D.createContext(null),S6=D.createContext(null),Pl=D.createContext(null),Y0=D.createContext(null),Dl=D.createContext({outlet:null,matches:[],isDataRoute:!1}),KM=D.createContext(null);function E6(t,e){let{relative:n}=e===void 0?{}:e;hh()||er(!1);let{basename:r,navigator:i}=D.useContext(Pl),{hash:s,pathname:a,search:o}=qM(t,{relative:n}),l=a;return r!=="/"&&(l=a==="/"?r:ml([r,a])),i.createHref({pathname:l,search:o,hash:s})}function hh(){return D.useContext(Y0)!=null}function ba(){return hh()||er(!1),D.useContext(Y0).location}function zM(t){D.useContext(Pl).static||D.useLayoutEffect(t)}function qr(){let{isDataRoute:t}=D.useContext(Dl);return t?M6():w6()}function w6(){hh()||er(!1);let t=D.useContext(fT),{basename:e,future:n,navigator:r}=D.useContext(Pl),{matches:i}=D.useContext(Dl),{pathname:s}=ba(),a=JSON.stringify(dT(i,n.v7_relativeSplatPath)),o=D.useRef(!1);return zM(()=>{o.current=!0}),D.useCallback(function(c,u){if(u===void 0&&(u={}),!o.current)return;if(typeof c=="number"){r.go(c);return}let d=hT(c,JSON.parse(a),s,u.relative==="path");t==null&&e!=="/"&&(d.pathname=d.pathname==="/"?e:ml([e,d.pathname])),(u.replace?r.replace:r.push)(d,u.state,u)},[e,r,a,s,t])}function qM(t,e){let{relative:n}=e===void 0?{}:e,{future:r}=D.useContext(Pl),{matches:i}=D.useContext(Dl),{pathname:s}=ba(),a=JSON.stringify(dT(i,r.v7_relativeSplatPath));return D.useMemo(()=>hT(t,JSON.parse(a),s,n==="path"),[t,a,s,n])}function T6(t,e){return A6(t,e)}function A6(t,e,n,r){hh()||er(!1);let{navigator:i}=D.useContext(Pl),{matches:s}=D.useContext(Dl),a=s[s.length-1],o=a?a.params:{};a&&a.pathname;let l=a?a.pathnameBase:"/";a&&a.route;let c=ba(),u;if(e){var d;let g=typeof e=="string"?dh(e):e;l==="/"||(d=g.pathname)!=null&&d.startsWith(l)||er(!1),u=g}else u=c;let h=u.pathname||"/",f=h;if(l!=="/"){let g=l.replace(/^\//,"").split("/");f="/"+h.replace(/^\//,"").split("/").slice(g.length).join("/")}let p=JV(t,{pathname:f}),m=I6(p&&p.map(g=>Object.assign({},g,{params:Object.assign({},o,g.params),pathname:ml([l,i.encodeLocation?i.encodeLocation(g.pathname).pathname:g.pathname]),pathnameBase:g.pathnameBase==="/"?l:ml([l,i.encodeLocation?i.encodeLocation(g.pathnameBase).pathname:g.pathnameBase])})),s,n,r);return e&&m?D.createElement(Y0.Provider,{value:{location:sp({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:il.Pop}},m):m}function R6(){let t=N6(),e=b6(t)?t.status+" "+t.statusText:t instanceof Error?t.message:JSON.stringify(t),n=t instanceof Error?t.stack:null,i={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return D.createElement(D.Fragment,null,D.createElement("h2",null,"Unexpected Application Error!"),D.createElement("h3",{style:{fontStyle:"italic"}},e),n?D.createElement("pre",{style:i},n):null,null)}const C6=D.createElement(R6,null);class L6 extends D.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,n){return n.location!==e.location||n.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:n.error,location:n.location,revalidation:e.revalidation||n.revalidation}}componentDidCatch(e,n){console.error("React Router caught the following error during render",e,n)}render(){return this.state.error!==void 0?D.createElement(Dl.Provider,{value:this.props.routeContext},D.createElement(KM.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function k6(t){let{routeContext:e,match:n,children:r}=t,i=D.useContext(fT);return i&&i.static&&i.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=n.route.id),D.createElement(Dl.Provider,{value:e},r)}function I6(t,e,n,r){var i;if(e===void 0&&(e=[]),n===void 0&&(n=null),r===void 0&&(r=null),t==null){var s;if(!n)return null;if(n.errors)t=n.matches;else if((s=r)!=null&&s.v7_partialHydration&&e.length===0&&!n.initialized&&n.matches.length>0)t=n.matches;else return null}let a=t,o=(i=n)==null?void 0:i.errors;if(o!=null){let u=a.findIndex(d=>d.route.id&&(o==null?void 0:o[d.route.id])!==void 0);u>=0||er(!1),a=a.slice(0,Math.min(a.length,u+1))}let l=!1,c=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u<a.length;u++){let d=a[u];if((d.route.HydrateFallback||d.route.hydrateFallbackElement)&&(c=u),d.route.id){let{loaderData:h,errors:f}=n,p=d.route.loader&&h[d.route.id]===void 0&&(!f||f[d.route.id]===void 0);if(d.route.lazy||p){l=!0,c>=0?a=a.slice(0,c+1):a=[a[0]];break}}}return a.reduceRight((u,d,h)=>{let f,p=!1,m=null,g=null;n&&(f=o&&d.route.id?o[d.route.id]:void 0,m=d.route.errorElement||C6,l&&(c<0&&h===0?(B6("route-fallback"),p=!0,g=null):c===h&&(p=!0,g=d.route.hydrateFallbackElement||null)));let b=e.concat(a.slice(0,h+1)),v=()=>{let S;return f?S=m:p?S=g:d.route.Component?S=D.createElement(d.route.Component,null):d.route.element?S=d.route.element:S=u,D.createElement(k6,{match:d,routeContext:{outlet:u,matches:b,isDataRoute:n!=null},children:S})};return n&&(d.route.ErrorBoundary||d.route.errorElement||h===0)?D.createElement(L6,{location:n.location,revalidation:n.revalidation,component:m,error:f,children:v(),routeContext:{outlet:null,matches:b,isDataRoute:!0}}):v()},null)}var WM=function(t){return t.UseBlocker="useBlocker",t.UseRevalidator="useRevalidator",t.UseNavigateStable="useNavigate",t}(WM||{}),YM=function(t){return t.UseBlocker="useBlocker",t.UseLoaderData="useLoaderData",t.UseActionData="useActionData",t.UseRouteError="useRouteError",t.UseNavigation="useNavigation",t.UseRouteLoaderData="useRouteLoaderData",t.UseMatches="useMatches",t.UseRevalidator="useRevalidator",t.UseNavigateStable="useNavigate",t.UseRouteId="useRouteId",t}(YM||{});function P6(t){let e=D.useContext(fT);return e||er(!1),e}function D6(t){let e=D.useContext(S6);return e||er(!1),e}function O6(t){let e=D.useContext(Dl);return e||er(!1),e}function XM(t){let e=O6(),n=e.matches[e.matches.length-1];return n.route.id||er(!1),n.route.id}function N6(){var t;let e=D.useContext(KM),n=D6(),r=XM();return e!==void 0?e:(t=n.errors)==null?void 0:t[r]}function M6(){let{router:t}=P6(WM.UseNavigateStable),e=XM(YM.UseNavigateStable),n=D.useRef(!1);return zM(()=>{n.current=!0}),D.useCallback(function(i,s){s===void 0&&(s={}),n.current&&(typeof i=="number"?t.navigate(i):t.navigate(i,sp({fromRouteId:e},s)))},[t,e])}const uC={};function B6(t,e,n){uC[t]||(uC[t]=!0)}function U6(t,e){t==null||t.v7_startTransition,t==null||t.v7_relativeSplatPath}function qy(t){let{to:e,replace:n,state:r,relative:i}=t;hh()||er(!1);let{future:s,static:a}=D.useContext(Pl),{matches:o}=D.useContext(Dl),{pathname:l}=ba(),c=qr(),u=hT(e,dT(o,s.v7_relativeSplatPath),l,i==="path"),d=JSON.stringify(u);return D.useEffect(()=>c(JSON.parse(d),{replace:n,state:r,relative:i}),[c,d,i,n,r]),null}function fi(t){er(!1)}function j6(t){let{basename:e="/",children:n=null,location:r,navigationType:i=il.Pop,navigator:s,static:a=!1,future:o}=t;hh()&&er(!1);let l=e.replace(/^\/*/,"/"),c=D.useMemo(()=>({basename:l,navigator:s,static:a,future:sp({v7_relativeSplatPath:!1},o)}),[l,o,s,a]);typeof r=="string"&&(r=dh(r));let{pathname:u="/",search:d="",hash:h="",state:f=null,key:p="default"}=r,m=D.useMemo(()=>{let g=uT(u,l);return g==null?null:{location:{pathname:g,search:d,hash:h,state:f,key:p},navigationType:i}},[l,u,d,h,f,p,i]);return m==null?null:D.createElement(Pl.Provider,{value:c},D.createElement(Y0.Provider,{children:n,value:m}))}function F6(t){let{children:e,location:n}=t;return T6(_S(e),n)}new Promise(()=>{});function _S(t,e){e===void 0&&(e=[]);let n=[];return D.Children.forEach(t,(r,i)=>{if(!D.isValidElement(r))return;let s=[...e,i];if(r.type===D.Fragment){n.push.apply(n,_S(r.props.children,s));return}r.type!==fi&&er(!1),!r.props.index||!r.props.children||er(!1);let a={id:r.props.id||s.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(a.children=_S(r.props.children,s)),n.push(a)}),n}/**
 * React Router DOM v6.30.3
 *
 * Copyright (c) Remix Software Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.md file in the root directory of this source tree.
 *
 * @license MIT
 */function bS(){return bS=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},bS.apply(this,arguments)}function $6(t,e){if(t==null)return{};var n={},r=Object.keys(t),i,s;for(s=0;s<r.length;s++)i=r[s],!(e.indexOf(i)>=0)&&(n[i]=t[i]);return n}function V6(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}function G6(t,e){return t.button===0&&(!e||e==="_self")&&!V6(t)}function xS(t){return t===void 0&&(t=""),new URLSearchParams(typeof t=="string"||Array.isArray(t)||t instanceof URLSearchParams?t:Object.keys(t).reduce((e,n)=>{let r=t[n];return e.concat(Array.isArray(r)?r.map(i=>[n,i]):[[n,r]])},[]))}function H6(t,e){let n=xS(t);return e&&e.forEach((r,i)=>{n.has(i)||e.getAll(i).forEach(s=>{n.append(i,s)})}),n}const K6=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],z6="6";try{window.__reactRouterVersion=z6}catch{}const q6="startTransition",dC=cw[q6];function W6(t){let{basename:e,children:n,future:r,window:i}=t,s=D.useRef();s.current==null&&(s.current=YV({window:i,v5Compat:!0}));let a=s.current,[o,l]=D.useState({action:a.action,location:a.location}),{v7_startTransition:c}=r||{},u=D.useCallback(d=>{c&&dC?dC(()=>l(d)):l(d)},[l,c]);return D.useLayoutEffect(()=>a.listen(u),[a,u]),D.useEffect(()=>U6(r),[r]),D.createElement(j6,{basename:e,children:n,location:o.location,navigationType:o.action,navigator:a,future:r})}const Y6=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",X6=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,pT=D.forwardRef(function(e,n){let{onClick:r,relative:i,reloadDocument:s,replace:a,state:o,target:l,to:c,preventScrollReset:u,viewTransition:d}=e,h=$6(e,K6),{basename:f}=D.useContext(Pl),p,m=!1;if(typeof c=="string"&&X6.test(c)&&(p=c,Y6))try{let S=new URL(window.location.href),E=c.startsWith("//")?new URL(S.protocol+c):new URL(c),L=uT(E.pathname,f);E.origin===S.origin&&L!=null?c=L+E.search+E.hash:m=!0}catch{}let g=E6(c,{relative:i}),b=Q6(c,{replace:a,state:o,target:l,preventScrollReset:u,relative:i,viewTransition:d});function v(S){r&&r(S),S.defaultPrevented||b(S)}return D.createElement("a",bS({},h,{href:p||g,onClick:m||s?r:v,ref:n,target:l}))});var hC;(function(t){t.UseScrollRestoration="useScrollRestoration",t.UseSubmit="useSubmit",t.UseSubmitFetcher="useSubmitFetcher",t.UseFetcher="useFetcher",t.useViewTransitionState="useViewTransitionState"})(hC||(hC={}));var fC;(function(t){t.UseFetcher="useFetcher",t.UseFetchers="useFetchers",t.UseScrollRestoration="useScrollRestoration"})(fC||(fC={}));function Q6(t,e){let{target:n,replace:r,state:i,preventScrollReset:s,relative:a,viewTransition:o}=e===void 0?{}:e,l=qr(),c=ba(),u=qM(t,{relative:a});return D.useCallback(d=>{if(G6(d,n)){d.preventDefault();let h=r!==void 0?r:zy(c)===zy(u);l(t,{replace:h,state:i,preventScrollReset:s,relative:a,viewTransition:o})}},[c,l,u,r,i,n,t,s,a,o])}function QM(t){let e=D.useRef(xS(t)),n=D.useRef(!1),r=ba(),i=D.useMemo(()=>H6(r.search,n.current?null:e.current),[r.search]),s=qr(),a=D.useCallback((o,l)=>{const c=xS(typeof o=="function"?o(i):o);n.current=!0,s("?"+c,l)},[s,i]);return[i,a]}var pC=["light","dark"],J6="(prefers-color-scheme: dark)",Z6=D.createContext(void 0),eG={setTheme:t=>{},themes:[]},tG=()=>{var t;return(t=D.useContext(Z6))!=null?t:eG};D.memo(({forcedTheme:t,storageKey:e,attribute:n,enableSystem:r,enableColorScheme:i,defaultTheme:s,value:a,attrs:o,nonce:l})=>{let c=s==="system",u=n==="class"?`var d=document.documentElement,c=d.classList;${`c.remove(${o.map(p=>`'${p}'`).join(",")})`};`:`var d=document.documentElement,n='${n}',s='setAttribute';`,d=i?pC.includes(s)&&s?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${s}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",h=(p,m=!1,g=!0)=>{let b=a?a[p]:p,v=m?p+"|| ''":`'${b}'`,S="";return i&&g&&!m&&pC.includes(p)&&(S+=`d.style.colorScheme = '${p}';`),n==="class"?m||b?S+=`c.add(${v})`:S+="null":b&&(S+=`d[s](n,${v})`),S},f=t?`!function(){${u}${h(t)}}()`:r?`!function(){try{${u}var e=localStorage.getItem('${e}');if('system'===e||(!e&&${c})){var t='${J6}',m=window.matchMedia(t);if(m.media!==t||m.matches){${h("dark")}}else{${h("light")}}}else if(e){${a?`var x=${JSON.stringify(a)};`:""}${h(a?"x[e]":"e",!0)}}${c?"":"else{"+h(s,!1,!1)+"}"}${d}}catch(e){}}()`:`!function(){try{${u}var e=localStorage.getItem('${e}');if(e){${a?`var x=${JSON.stringify(a)};`:""}${h(a?"x[e]":"e",!0)}}else{${h(s,!1,!1)};}${d}}catch(t){}}();`;return D.createElement("script",{nonce:l,dangerouslySetInnerHTML:{__html:f}})});var nG=t=>{switch(t){case"success":return sG;case"info":return oG;case"warning":return aG;case"error":return lG;default:return null}},rG=Array(12).fill(0),iG=({visible:t,className:e})=>Fe.createElement("div",{className:["sonner-loading-wrapper",e].filter(Boolean).join(" "),"data-visible":t},Fe.createElement("div",{className:"sonner-spinner"},rG.map((n,r)=>Fe.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),sG=Fe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Fe.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),aG=Fe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},Fe.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),oG=Fe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Fe.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),lG=Fe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Fe.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),cG=Fe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},Fe.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),Fe.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),uG=()=>{let[t,e]=Fe.useState(document.hidden);return Fe.useEffect(()=>{let n=()=>{e(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),t},SS=1,dG=class{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{let e=this.subscribers.indexOf(t);this.subscribers.splice(e,1)}),this.publish=t=>{this.subscribers.forEach(e=>e(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var e;let{message:n,...r}=t,i=typeof(t==null?void 0:t.id)=="number"||((e=t.id)==null?void 0:e.length)>0?t.id:SS++,s=this.toasts.find(o=>o.id===i),a=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(i)&&this.dismissedToasts.delete(i),s?this.toasts=this.toasts.map(o=>o.id===i?(this.publish({...o,...t,id:i,title:n}),{...o,...t,id:i,dismissible:a,title:n}):o):this.addToast({title:n,...r,dismissible:a,id:i}),i},this.dismiss=t=>(this.dismissedToasts.add(t),t||this.toasts.forEach(e=>{this.subscribers.forEach(n=>n({id:e.id,dismiss:!0}))}),this.subscribers.forEach(e=>e({id:t,dismiss:!0})),t),this.message=(t,e)=>this.create({...e,message:t}),this.error=(t,e)=>this.create({...e,message:t,type:"error"}),this.success=(t,e)=>this.create({...e,type:"success",message:t}),this.info=(t,e)=>this.create({...e,type:"info",message:t}),this.warning=(t,e)=>this.create({...e,type:"warning",message:t}),this.loading=(t,e)=>this.create({...e,type:"loading",message:t}),this.promise=(t,e)=>{if(!e)return;let n;e.loading!==void 0&&(n=this.create({...e,promise:t,type:"loading",message:e.loading,description:typeof e.description!="function"?e.description:void 0}));let r=t instanceof Promise?t:t(),i=n!==void 0,s,a=r.then(async l=>{if(s=["resolve",l],Fe.isValidElement(l))i=!1,this.create({id:n,type:"default",message:l});else if(fG(l)&&!l.ok){i=!1;let c=typeof e.error=="function"?await e.error(`HTTP error! status: ${l.status}`):e.error,u=typeof e.description=="function"?await e.description(`HTTP error! status: ${l.status}`):e.description;this.create({id:n,type:"error",message:c,description:u})}else if(e.success!==void 0){i=!1;let c=typeof e.success=="function"?await e.success(l):e.success,u=typeof e.description=="function"?await e.description(l):e.description;this.create({id:n,type:"success",message:c,description:u})}}).catch(async l=>{if(s=["reject",l],e.error!==void 0){i=!1;let c=typeof e.error=="function"?await e.error(l):e.error,u=typeof e.description=="function"?await e.description(l):e.description;this.create({id:n,type:"error",message:c,description:u})}}).finally(()=>{var l;i&&(this.dismiss(n),n=void 0),(l=e.finally)==null||l.call(e)}),o=()=>new Promise((l,c)=>a.then(()=>s[0]==="reject"?c(s[1]):l(s[1])).catch(c));return typeof n!="string"&&typeof n!="number"?{unwrap:o}:Object.assign(n,{unwrap:o})},this.custom=(t,e)=>{let n=(e==null?void 0:e.id)||SS++;return this.create({jsx:t(n),id:n,...e}),n},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},vi=new dG,hG=(t,e)=>{let n=(e==null?void 0:e.id)||SS++;return vi.addToast({title:t,...e,id:n}),n},fG=t=>t&&typeof t=="object"&&"ok"in t&&typeof t.ok=="boolean"&&"status"in t&&typeof t.status=="number",pG=hG,mG=()=>vi.toasts,gG=()=>vi.getActiveToasts(),Mt=Object.assign(pG,{success:vi.success,info:vi.info,warning:vi.warning,error:vi.error,custom:vi.custom,message:vi.message,promise:vi.promise,dismiss:vi.dismiss,loading:vi.loading},{getHistory:mG,getToasts:gG});function yG(t,{insertAt:e}={}){if(typeof document>"u")return;let n=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",e==="top"&&n.firstChild?n.insertBefore(r,n.firstChild):n.appendChild(r),r.styleSheet?r.styleSheet.cssText=t:r.appendChild(document.createTextNode(t))}yG(`:where(html[dir="ltr"]),:where([data-sonner-toaster][dir="ltr"]){--toast-icon-margin-start: -3px;--toast-icon-margin-end: 4px;--toast-svg-margin-start: -1px;--toast-svg-margin-end: 0px;--toast-button-margin-start: auto;--toast-button-margin-end: 0;--toast-close-button-start: 0;--toast-close-button-end: unset;--toast-close-button-transform: translate(-35%, -35%)}:where(html[dir="rtl"]),:where([data-sonner-toaster][dir="rtl"]){--toast-icon-margin-start: 4px;--toast-icon-margin-end: -3px;--toast-svg-margin-start: 0px;--toast-svg-margin-end: -1px;--toast-button-margin-start: 0;--toast-button-margin-end: auto;--toast-close-button-start: unset;--toast-close-button-end: 0;--toast-close-button-transform: translate(35%, -35%)}:where([data-sonner-toaster]){position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1: hsl(0, 0%, 99%);--gray2: hsl(0, 0%, 97.3%);--gray3: hsl(0, 0%, 95.1%);--gray4: hsl(0, 0%, 93%);--gray5: hsl(0, 0%, 90.9%);--gray6: hsl(0, 0%, 88.7%);--gray7: hsl(0, 0%, 85.8%);--gray8: hsl(0, 0%, 78%);--gray9: hsl(0, 0%, 56.1%);--gray10: hsl(0, 0%, 52.3%);--gray11: hsl(0, 0%, 43.5%);--gray12: hsl(0, 0%, 9%);--border-radius: 8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:none;z-index:999999999;transition:transform .4s ease}:where([data-sonner-toaster][data-lifted="true"]){transform:translateY(-10px)}@media (hover: none) and (pointer: coarse){:where([data-sonner-toaster][data-lifted="true"]){transform:none}}:where([data-sonner-toaster][data-x-position="right"]){right:var(--offset-right)}:where([data-sonner-toaster][data-x-position="left"]){left:var(--offset-left)}:where([data-sonner-toaster][data-x-position="center"]){left:50%;transform:translate(-50%)}:where([data-sonner-toaster][data-y-position="top"]){top:var(--offset-top)}:where([data-sonner-toaster][data-y-position="bottom"]){bottom:var(--offset-bottom)}:where([data-sonner-toast]){--y: translateY(100%);--lift-amount: calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);filter:blur(0);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:none;overflow-wrap:anywhere}:where([data-sonner-toast][data-styled="true"]){padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px #0000001a;width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}:where([data-sonner-toast]:focus-visible){box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast][data-y-position="top"]){top:0;--y: translateY(-100%);--lift: 1;--lift-amount: calc(1 * var(--gap))}:where([data-sonner-toast][data-y-position="bottom"]){bottom:0;--y: translateY(100%);--lift: -1;--lift-amount: calc(var(--lift) * var(--gap))}:where([data-sonner-toast]) :where([data-description]){font-weight:400;line-height:1.4;color:inherit}:where([data-sonner-toast]) :where([data-title]){font-weight:500;line-height:1.5;color:inherit}:where([data-sonner-toast]) :where([data-icon]){display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}:where([data-sonner-toast][data-promise="true"]) :where([data-icon])>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}:where([data-sonner-toast]) :where([data-icon])>*{flex-shrink:0}:where([data-sonner-toast]) :where([data-icon]) svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}:where([data-sonner-toast]) :where([data-content]){display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;cursor:pointer;outline:none;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}:where([data-sonner-toast]) :where([data-button]):focus-visible{box-shadow:0 0 0 2px #0006}:where([data-sonner-toast]) :where([data-button]):first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}:where([data-sonner-toast]) :where([data-cancel]){color:var(--normal-text);background:rgba(0,0,0,.08)}:where([data-sonner-toast][data-theme="dark"]) :where([data-cancel]){background:rgba(255,255,255,.3)}:where([data-sonner-toast]) :where([data-close-button]){position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast] [data-close-button]{background:var(--gray1)}:where([data-sonner-toast]) :where([data-close-button]):focus-visible{box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast]) :where([data-disabled="true"]){cursor:not-allowed}:where([data-sonner-toast]):hover :where([data-close-button]):hover{background:var(--gray2);border-color:var(--gray5)}:where([data-sonner-toast][data-swiping="true"]):before{content:"";position:absolute;left:-50%;right:-50%;height:100%;z-index:-1}:where([data-sonner-toast][data-y-position="top"][data-swiping="true"]):before{bottom:50%;transform:scaleY(3) translateY(50%)}:where([data-sonner-toast][data-y-position="bottom"][data-swiping="true"]):before{top:50%;transform:scaleY(3) translateY(-50%)}:where([data-sonner-toast][data-swiping="false"][data-removed="true"]):before{content:"";position:absolute;inset:0;transform:scaleY(2)}:where([data-sonner-toast]):after{content:"";position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}:where([data-sonner-toast][data-mounted="true"]){--y: translateY(0);opacity:1}:where([data-sonner-toast][data-expanded="false"][data-front="false"]){--scale: var(--toasts-before) * .05 + 1;--y: translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}:where([data-sonner-toast])>*{transition:opacity .4s}:where([data-sonner-toast][data-expanded="false"][data-front="false"][data-styled="true"])>*{opacity:0}:where([data-sonner-toast][data-visible="false"]){opacity:0;pointer-events:none}:where([data-sonner-toast][data-mounted="true"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}:where([data-sonner-toast][data-removed="true"][data-front="true"][data-swipe-out="false"]){--y: translateY(calc(var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="false"]){--y: translateY(40%);opacity:0;transition:transform .5s,opacity .2s}:where([data-sonner-toast][data-removed="true"][data-front="false"]):before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y, 0px)) translate(var(--swipe-amount-x, 0px));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width: 600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-theme=light]{--normal-bg: #fff;--normal-border: var(--gray4);--normal-text: var(--gray12);--success-bg: hsl(143, 85%, 96%);--success-border: hsl(145, 92%, 91%);--success-text: hsl(140, 100%, 27%);--info-bg: hsl(208, 100%, 97%);--info-border: hsl(221, 91%, 91%);--info-text: hsl(210, 92%, 45%);--warning-bg: hsl(49, 100%, 97%);--warning-border: hsl(49, 91%, 91%);--warning-text: hsl(31, 92%, 45%);--error-bg: hsl(359, 100%, 97%);--error-border: hsl(359, 100%, 94%);--error-text: hsl(360, 100%, 45%)}[data-sonner-toaster][data-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg: #000;--normal-border: hsl(0, 0%, 20%);--normal-text: var(--gray1)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg: #fff;--normal-border: var(--gray3);--normal-text: var(--gray12)}[data-sonner-toaster][data-theme=dark]{--normal-bg: #000;--normal-bg-hover: hsl(0, 0%, 12%);--normal-border: hsl(0, 0%, 20%);--normal-border-hover: hsl(0, 0%, 25%);--normal-text: var(--gray1);--success-bg: hsl(150, 100%, 6%);--success-border: hsl(147, 100%, 12%);--success-text: hsl(150, 86%, 65%);--info-bg: hsl(215, 100%, 6%);--info-border: hsl(223, 100%, 12%);--info-text: hsl(216, 87%, 65%);--warning-bg: hsl(64, 100%, 6%);--warning-border: hsl(60, 100%, 12%);--warning-text: hsl(46, 87%, 65%);--error-bg: hsl(358, 76%, 10%);--error-border: hsl(357, 89%, 16%);--error-text: hsl(358, 100%, 81%)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success],[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info],[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning],[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error],[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size: 16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:nth-child(1){animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}to{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}to{opacity:.15}}@media (prefers-reduced-motion){[data-sonner-toast],[data-sonner-toast]>*,.sonner-loading-bar{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}
`);function zm(t){return t.label!==void 0}var vG=3,_G="32px",bG="16px",mC=4e3,xG=356,SG=14,EG=20,wG=200;function Ss(...t){return t.filter(Boolean).join(" ")}function TG(t){let[e,n]=t.split("-"),r=[];return e&&r.push(e),n&&r.push(n),r}var AG=t=>{var e,n,r,i,s,a,o,l,c,u,d;let{invert:h,toast:f,unstyled:p,interacting:m,setHeights:g,visibleToasts:b,heights:v,index:S,toasts:E,expanded:L,removeToast:U,defaultRichColors:O,closeButton:k,style:I,cancelButtonStyle:R,actionButtonStyle:M,className:z="",descriptionClassName:Z="",duration:W,position:re,gap:X,loadingIcon:oe,expandByDefault:Q,classNames:G,icons:H,closeButtonAriaLabel:Y="Close toast",pauseWhenPageIsHidden:ie}=t,[Ce,Le]=Fe.useState(null),[ke,Ne]=Fe.useState(null),[ye,Ie]=Fe.useState(!1),[Ae,Ee]=Fe.useState(!1),[je,Me]=Fe.useState(!1),[Pt,tn]=Fe.useState(!1),[Dn,lt]=Fe.useState(!1),[un,Sn]=Fe.useState(0),[tr,Un]=Fe.useState(0),En=Fe.useRef(f.duration||W||mC),Yr=Fe.useRef(null),vr=Fe.useRef(null),_s=S===0,Wi=S+1<=b,Xt=f.type,or=f.dismissible!==!1,Ta=f.className||"",Yi=f.descriptionClassName||"",Ei=Fe.useMemo(()=>v.findIndex(vt=>vt.toastId===f.id)||0,[v,f.id]),li=Fe.useMemo(()=>{var vt;return(vt=f.closeButton)!=null?vt:k},[f.closeButton,k]),Xi=Fe.useMemo(()=>f.duration||W||mC,[f.duration,W]),js=Fe.useRef(0),Qi=Fe.useRef(0),ci=Fe.useRef(0),nt=Fe.useRef(null),[Aa,bs]=re.split("-"),Ra=Fe.useMemo(()=>v.reduce((vt,jt,sn)=>sn>=Ei?vt:vt+jt.height,0),[v,Ei]),Qe=uG(),Ml=f.invert||h,_o=Xt==="loading";Qi.current=Fe.useMemo(()=>Ei*X+Ra,[Ei,Ra]),Fe.useEffect(()=>{En.current=Xi},[Xi]),Fe.useEffect(()=>{Ie(!0)},[]),Fe.useEffect(()=>{let vt=vr.current;if(vt){let jt=vt.getBoundingClientRect().height;return Un(jt),g(sn=>[{toastId:f.id,height:jt,position:f.position},...sn]),()=>g(sn=>sn.filter(qn=>qn.toastId!==f.id))}},[g,f.id]),Fe.useLayoutEffect(()=>{if(!ye)return;let vt=vr.current,jt=vt.style.height;vt.style.height="auto";let sn=vt.getBoundingClientRect().height;vt.style.height=jt,Un(sn),g(qn=>qn.find(Wn=>Wn.toastId===f.id)?qn.map(Wn=>Wn.toastId===f.id?{...Wn,height:sn}:Wn):[{toastId:f.id,height:sn,position:f.position},...qn])},[ye,f.title,f.description,g,f.id]);let ui=Fe.useCallback(()=>{Ee(!0),Sn(Qi.current),g(vt=>vt.filter(jt=>jt.toastId!==f.id)),setTimeout(()=>{U(f)},wG)},[f,U,g,Qi]);Fe.useEffect(()=>{if(f.promise&&Xt==="loading"||f.duration===1/0||f.type==="loading")return;let vt;return L||m||ie&&Qe?(()=>{if(ci.current<js.current){let jt=new Date().getTime()-js.current;En.current=En.current-jt}ci.current=new Date().getTime()})():En.current!==1/0&&(js.current=new Date().getTime(),vt=setTimeout(()=>{var jt;(jt=f.onAutoClose)==null||jt.call(f,f),ui()},En.current)),()=>clearTimeout(vt)},[L,m,f,Xt,ie,Qe,ui]),Fe.useEffect(()=>{f.delete&&ui()},[ui,f.delete]);function Qc(){var vt,jt,sn;return H!=null&&H.loading?Fe.createElement("div",{className:Ss(G==null?void 0:G.loader,(vt=f==null?void 0:f.classNames)==null?void 0:vt.loader,"sonner-loader"),"data-visible":Xt==="loading"},H.loading):oe?Fe.createElement("div",{className:Ss(G==null?void 0:G.loader,(jt=f==null?void 0:f.classNames)==null?void 0:jt.loader,"sonner-loader"),"data-visible":Xt==="loading"},oe):Fe.createElement(iG,{className:Ss(G==null?void 0:G.loader,(sn=f==null?void 0:f.classNames)==null?void 0:sn.loader),visible:Xt==="loading"})}return Fe.createElement("li",{tabIndex:0,ref:vr,className:Ss(z,Ta,G==null?void 0:G.toast,(e=f==null?void 0:f.classNames)==null?void 0:e.toast,G==null?void 0:G.default,G==null?void 0:G[Xt],(n=f==null?void 0:f.classNames)==null?void 0:n[Xt]),"data-sonner-toast":"","data-rich-colors":(r=f.richColors)!=null?r:O,"data-styled":!(f.jsx||f.unstyled||p),"data-mounted":ye,"data-promise":!!f.promise,"data-swiped":Dn,"data-removed":Ae,"data-visible":Wi,"data-y-position":Aa,"data-x-position":bs,"data-index":S,"data-front":_s,"data-swiping":je,"data-dismissible":or,"data-type":Xt,"data-invert":Ml,"data-swipe-out":Pt,"data-swipe-direction":ke,"data-expanded":!!(L||Q&&ye),style:{"--index":S,"--toasts-before":S,"--z-index":E.length-S,"--offset":`${Ae?un:Qi.current}px`,"--initial-height":Q?"auto":`${tr}px`,...I,...f.style},onDragEnd:()=>{Me(!1),Le(null),nt.current=null},onPointerDown:vt=>{_o||!or||(Yr.current=new Date,Sn(Qi.current),vt.target.setPointerCapture(vt.pointerId),vt.target.tagName!=="BUTTON"&&(Me(!0),nt.current={x:vt.clientX,y:vt.clientY}))},onPointerUp:()=>{var vt,jt,sn,qn;if(Pt||!or)return;nt.current=null;let Wn=Number(((vt=vr.current)==null?void 0:vt.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),lr=Number(((jt=vr.current)==null?void 0:jt.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Xr=new Date().getTime()-((sn=Yr.current)==null?void 0:sn.getTime()),At=Ce==="x"?Wn:lr,nn=Math.abs(At)/Xr;if(Math.abs(At)>=EG||nn>.11){Sn(Qi.current),(qn=f.onDismiss)==null||qn.call(f,f),Ne(Ce==="x"?Wn>0?"right":"left":lr>0?"down":"up"),ui(),tn(!0),lt(!1);return}Me(!1),Le(null)},onPointerMove:vt=>{var jt,sn,qn,Wn;if(!nt.current||!or||((jt=window.getSelection())==null?void 0:jt.toString().length)>0)return;let lr=vt.clientY-nt.current.y,Xr=vt.clientX-nt.current.x,At=(sn=t.swipeDirections)!=null?sn:TG(re);!Ce&&(Math.abs(Xr)>1||Math.abs(lr)>1)&&Le(Math.abs(Xr)>Math.abs(lr)?"x":"y");let nn={x:0,y:0};Ce==="y"?(At.includes("top")||At.includes("bottom"))&&(At.includes("top")&&lr<0||At.includes("bottom")&&lr>0)&&(nn.y=lr):Ce==="x"&&(At.includes("left")||At.includes("right"))&&(At.includes("left")&&Xr<0||At.includes("right")&&Xr>0)&&(nn.x=Xr),(Math.abs(nn.x)>0||Math.abs(nn.y)>0)&&lt(!0),(qn=vr.current)==null||qn.style.setProperty("--swipe-amount-x",`${nn.x}px`),(Wn=vr.current)==null||Wn.style.setProperty("--swipe-amount-y",`${nn.y}px`)}},li&&!f.jsx?Fe.createElement("button",{"aria-label":Y,"data-disabled":_o,"data-close-button":!0,onClick:_o||!or?()=>{}:()=>{var vt;ui(),(vt=f.onDismiss)==null||vt.call(f,f)},className:Ss(G==null?void 0:G.closeButton,(i=f==null?void 0:f.classNames)==null?void 0:i.closeButton)},(s=H==null?void 0:H.close)!=null?s:cG):null,f.jsx||D.isValidElement(f.title)?f.jsx?f.jsx:typeof f.title=="function"?f.title():f.title:Fe.createElement(Fe.Fragment,null,Xt||f.icon||f.promise?Fe.createElement("div",{"data-icon":"",className:Ss(G==null?void 0:G.icon,(a=f==null?void 0:f.classNames)==null?void 0:a.icon)},f.promise||f.type==="loading"&&!f.icon?f.icon||Qc():null,f.type!=="loading"?f.icon||(H==null?void 0:H[Xt])||nG(Xt):null):null,Fe.createElement("div",{"data-content":"",className:Ss(G==null?void 0:G.content,(o=f==null?void 0:f.classNames)==null?void 0:o.content)},Fe.createElement("div",{"data-title":"",className:Ss(G==null?void 0:G.title,(l=f==null?void 0:f.classNames)==null?void 0:l.title)},typeof f.title=="function"?f.title():f.title),f.description?Fe.createElement("div",{"data-description":"",className:Ss(Z,Yi,G==null?void 0:G.description,(c=f==null?void 0:f.classNames)==null?void 0:c.description)},typeof f.description=="function"?f.description():f.description):null),D.isValidElement(f.cancel)?f.cancel:f.cancel&&zm(f.cancel)?Fe.createElement("button",{"data-button":!0,"data-cancel":!0,style:f.cancelButtonStyle||R,onClick:vt=>{var jt,sn;zm(f.cancel)&&or&&((sn=(jt=f.cancel).onClick)==null||sn.call(jt,vt),ui())},className:Ss(G==null?void 0:G.cancelButton,(u=f==null?void 0:f.classNames)==null?void 0:u.cancelButton)},f.cancel.label):null,D.isValidElement(f.action)?f.action:f.action&&zm(f.action)?Fe.createElement("button",{"data-button":!0,"data-action":!0,style:f.actionButtonStyle||M,onClick:vt=>{var jt,sn;zm(f.action)&&((sn=(jt=f.action).onClick)==null||sn.call(jt,vt),!vt.defaultPrevented&&ui())},className:Ss(G==null?void 0:G.actionButton,(d=f==null?void 0:f.classNames)==null?void 0:d.actionButton)},f.action.label):null))};function gC(){if(typeof window>"u"||typeof document>"u")return"ltr";let t=document.documentElement.getAttribute("dir");return t==="auto"||!t?window.getComputedStyle(document.documentElement).direction:t}function RG(t,e){let n={};return[t,e].forEach((r,i)=>{let s=i===1,a=s?"--mobile-offset":"--offset",o=s?bG:_G;function l(c){["top","right","bottom","left"].forEach(u=>{n[`${a}-${u}`]=typeof c=="number"?`${c}px`:c})}typeof r=="number"||typeof r=="string"?l(r):typeof r=="object"?["top","right","bottom","left"].forEach(c=>{r[c]===void 0?n[`${a}-${c}`]=o:n[`${a}-${c}`]=typeof r[c]=="number"?`${r[c]}px`:r[c]}):l(o)}),n}var CG=D.forwardRef(function(t,e){let{invert:n,position:r="bottom-right",hotkey:i=["altKey","KeyT"],expand:s,closeButton:a,className:o,offset:l,mobileOffset:c,theme:u="light",richColors:d,duration:h,style:f,visibleToasts:p=vG,toastOptions:m,dir:g=gC(),gap:b=SG,loadingIcon:v,icons:S,containerAriaLabel:E="Notifications",pauseWhenPageIsHidden:L}=t,[U,O]=Fe.useState([]),k=Fe.useMemo(()=>Array.from(new Set([r].concat(U.filter(ie=>ie.position).map(ie=>ie.position)))),[U,r]),[I,R]=Fe.useState([]),[M,z]=Fe.useState(!1),[Z,W]=Fe.useState(!1),[re,X]=Fe.useState(u!=="system"?u:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),oe=Fe.useRef(null),Q=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),G=Fe.useRef(null),H=Fe.useRef(!1),Y=Fe.useCallback(ie=>{O(Ce=>{var Le;return(Le=Ce.find(ke=>ke.id===ie.id))!=null&&Le.delete||vi.dismiss(ie.id),Ce.filter(({id:ke})=>ke!==ie.id)})},[]);return Fe.useEffect(()=>vi.subscribe(ie=>{if(ie.dismiss){O(Ce=>Ce.map(Le=>Le.id===ie.id?{...Le,delete:!0}:Le));return}setTimeout(()=>{WD.flushSync(()=>{O(Ce=>{let Le=Ce.findIndex(ke=>ke.id===ie.id);return Le!==-1?[...Ce.slice(0,Le),{...Ce[Le],...ie},...Ce.slice(Le+1)]:[ie,...Ce]})})})}),[]),Fe.useEffect(()=>{if(u!=="system"){X(u);return}if(u==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?X("dark"):X("light")),typeof window>"u")return;let ie=window.matchMedia("(prefers-color-scheme: dark)");try{ie.addEventListener("change",({matches:Ce})=>{X(Ce?"dark":"light")})}catch{ie.addListener(({matches:Le})=>{try{X(Le?"dark":"light")}catch(ke){console.error(ke)}})}},[u]),Fe.useEffect(()=>{U.length<=1&&z(!1)},[U]),Fe.useEffect(()=>{let ie=Ce=>{var Le,ke;i.every(Ne=>Ce[Ne]||Ce.code===Ne)&&(z(!0),(Le=oe.current)==null||Le.focus()),Ce.code==="Escape"&&(document.activeElement===oe.current||(ke=oe.current)!=null&&ke.contains(document.activeElement))&&z(!1)};return document.addEventListener("keydown",ie),()=>document.removeEventListener("keydown",ie)},[i]),Fe.useEffect(()=>{if(oe.current)return()=>{G.current&&(G.current.focus({preventScroll:!0}),G.current=null,H.current=!1)}},[oe.current]),Fe.createElement("section",{ref:e,"aria-label":`${E} ${Q}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},k.map((ie,Ce)=>{var Le;let[ke,Ne]=ie.split("-");return U.length?Fe.createElement("ol",{key:ie,dir:g==="auto"?gC():g,tabIndex:-1,ref:oe,className:o,"data-sonner-toaster":!0,"data-theme":re,"data-y-position":ke,"data-lifted":M&&U.length>1&&!s,"data-x-position":Ne,style:{"--front-toast-height":`${((Le=I[0])==null?void 0:Le.height)||0}px`,"--width":`${xG}px`,"--gap":`${b}px`,...f,...RG(l,c)},onBlur:ye=>{H.current&&!ye.currentTarget.contains(ye.relatedTarget)&&(H.current=!1,G.current&&(G.current.focus({preventScroll:!0}),G.current=null))},onFocus:ye=>{ye.target instanceof HTMLElement&&ye.target.dataset.dismissible==="false"||H.current||(H.current=!0,G.current=ye.relatedTarget)},onMouseEnter:()=>z(!0),onMouseMove:()=>z(!0),onMouseLeave:()=>{Z||z(!1)},onDragEnd:()=>z(!1),onPointerDown:ye=>{ye.target instanceof HTMLElement&&ye.target.dataset.dismissible==="false"||W(!0)},onPointerUp:()=>W(!1)},U.filter(ye=>!ye.position&&Ce===0||ye.position===ie).map((ye,Ie)=>{var Ae,Ee;return Fe.createElement(AG,{key:ye.id,icons:S,index:Ie,toast:ye,defaultRichColors:d,duration:(Ae=m==null?void 0:m.duration)!=null?Ae:h,className:m==null?void 0:m.className,descriptionClassName:m==null?void 0:m.descriptionClassName,invert:n,visibleToasts:p,closeButton:(Ee=m==null?void 0:m.closeButton)!=null?Ee:a,interacting:Z,position:ie,style:m==null?void 0:m.style,unstyled:m==null?void 0:m.unstyled,classNames:m==null?void 0:m.classNames,cancelButtonStyle:m==null?void 0:m.cancelButtonStyle,actionButtonStyle:m==null?void 0:m.actionButtonStyle,removeToast:Y,toasts:U.filter(je=>je.position==ye.position),heights:I.filter(je=>je.position==ye.position),setHeights:R,expandByDefault:s,gap:b,loadingIcon:v,expanded:M,pauseWhenPageIsHidden:L,swipeDirections:t.swipeDirections})})):null}))});const LG=({...t})=>{const{theme:e="system"}=tG();return y.jsx(CG,{theme:e,className:"toaster group",toastOptions:{classNames:{toast:"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground"}},...t})},kG=1,IG=1e6;let U_=0;function PG(){return U_=(U_+1)%Number.MAX_SAFE_INTEGER,U_.toString()}const j_=new Map,yC=t=>{if(j_.has(t))return;const e=setTimeout(()=>{j_.delete(t),xf({type:"REMOVE_TOAST",toastId:t})},IG);j_.set(t,e)},DG=(t,e)=>{switch(e.type){case"ADD_TOAST":return{...t,toasts:[e.toast,...t.toasts].slice(0,kG)};case"UPDATE_TOAST":return{...t,toasts:t.toasts.map(n=>n.id===e.toast.id?{...n,...e.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=e;return n?yC(n):t.toasts.forEach(r=>{yC(r.id)}),{...t,toasts:t.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return e.toastId===void 0?{...t,toasts:[]}:{...t,toasts:t.toasts.filter(n=>n.id!==e.toastId)}}},zg=[];let qg={toasts:[]};function xf(t){qg=DG(qg,t),zg.forEach(e=>{e(qg)})}function OG({...t}){const e=PG(),n=i=>xf({type:"UPDATE_TOAST",toast:{...i,id:e}}),r=()=>xf({type:"DISMISS_TOAST",toastId:e});return xf({type:"ADD_TOAST",toast:{...t,id:e,open:!0,onOpenChange:i=>{i||r()}}}),{id:e,dismiss:r,update:n}}function NG(){const[t,e]=D.useState(qg);return D.useEffect(()=>(zg.push(e),()=>{const n=zg.indexOf(e);n>-1&&zg.splice(n,1)}),[t]),{...t,toast:OG,dismiss:n=>xf({type:"DISMISS_TOAST",toastId:n})}}function kn(t,e,{checkForDefaultPrevented:n=!0}={}){return function(i){if(t==null||t(i),n===!1||!i.defaultPrevented)return e==null?void 0:e(i)}}function vC(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function X0(...t){return e=>{let n=!1;const r=t.map(i=>{const s=vC(i,e);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let i=0;i<r.length;i++){const s=r[i];typeof s=="function"?s():vC(t[i],null)}}}}function si(...t){return D.useCallback(X0(...t),t)}function MG(t,e){const n=D.createContext(e),r=s=>{const{children:a,...o}=s,l=D.useMemo(()=>o,Object.values(o));return y.jsx(n.Provider,{value:l,children:a})};r.displayName=t+"Provider";function i(s){const a=D.useContext(n);if(a)return a;if(e!==void 0)return e;throw new Error(`\`${s}\` must be used within \`${t}\``)}return[r,i]}function Zp(t,e=[]){let n=[];function r(s,a){const o=D.createContext(a),l=n.length;n=[...n,a];const c=d=>{var b;const{scope:h,children:f,...p}=d,m=((b=h==null?void 0:h[t])==null?void 0:b[l])||o,g=D.useMemo(()=>p,Object.values(p));return y.jsx(m.Provider,{value:g,children:f})};c.displayName=s+"Provider";function u(d,h){var m;const f=((m=h==null?void 0:h[t])==null?void 0:m[l])||o,p=D.useContext(f);if(p)return p;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${s}\``)}return[c,u]}const i=()=>{const s=n.map(a=>D.createContext(a));return function(o){const l=(o==null?void 0:o[t])||s;return D.useMemo(()=>({[`__scope${t}`]:{...o,[t]:l}}),[o,l])}};return i.scopeName=t,[r,BG(i,...e)]}function BG(...t){const e=t[0];if(t.length===1)return e;const n=()=>{const r=t.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(s){const a=r.reduce((o,{useScope:l,scopeName:c})=>{const d=l(s)[`__scope${c}`];return{...o,...d}},{});return D.useMemo(()=>({[`__scope${e.scopeName}`]:a}),[a])}};return n.scopeName=e.scopeName,n}function _C(t){const e=UG(t),n=D.forwardRef((r,i)=>{const{children:s,...a}=r,o=D.Children.toArray(s),l=o.find(FG);if(l){const c=l.props.children,u=o.map(d=>d===l?D.Children.count(c)>1?D.Children.only(null):D.isValidElement(c)?c.props.children:null:d);return y.jsx(e,{...a,ref:i,children:D.isValidElement(c)?D.cloneElement(c,void 0,u):null})}return y.jsx(e,{...a,ref:i,children:s})});return n.displayName=`${t}.Slot`,n}function UG(t){const e=D.forwardRef((n,r)=>{const{children:i,...s}=n;if(D.isValidElement(i)){const a=VG(i),o=$G(s,i.props);return i.type!==D.Fragment&&(o.ref=r?X0(r,a):a),D.cloneElement(i,o)}return D.Children.count(i)>1?D.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var jG=Symbol("radix.slottable");function FG(t){return D.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===jG}function $G(t,e){const n={...e};for(const r in e){const i=t[r],s=e[r];/^on[A-Z]/.test(r)?i&&s?n[r]=(...o)=>{const l=s(...o);return i(...o),l}:i&&(n[r]=i):r==="style"?n[r]={...i,...s}:r==="className"&&(n[r]=[i,s].filter(Boolean).join(" "))}return{...t,...n}}function VG(t){var r,i;let e=(r=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:r.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=(i=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:i.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}function GG(t){const e=t+"CollectionProvider",[n,r]=Zp(e),[i,s]=n(e,{collectionRef:{current:null},itemMap:new Map}),a=m=>{const{scope:g,children:b}=m,v=Fe.useRef(null),S=Fe.useRef(new Map).current;return y.jsx(i,{scope:g,itemMap:S,collectionRef:v,children:b})};a.displayName=e;const o=t+"CollectionSlot",l=_C(o),c=Fe.forwardRef((m,g)=>{const{scope:b,children:v}=m,S=s(o,b),E=si(g,S.collectionRef);return y.jsx(l,{ref:E,children:v})});c.displayName=o;const u=t+"CollectionItemSlot",d="data-radix-collection-item",h=_C(u),f=Fe.forwardRef((m,g)=>{const{scope:b,children:v,...S}=m,E=Fe.useRef(null),L=si(g,E),U=s(u,b);return Fe.useEffect(()=>(U.itemMap.set(E,{ref:E,...S}),()=>void U.itemMap.delete(E))),y.jsx(h,{[d]:"",ref:L,children:v})});f.displayName=u;function p(m){const g=s(t+"CollectionConsumer",m);return Fe.useCallback(()=>{const v=g.collectionRef.current;if(!v)return[];const S=Array.from(v.querySelectorAll(`[${d}]`));return Array.from(g.itemMap.values()).sort((U,O)=>S.indexOf(U.ref.current)-S.indexOf(O.ref.current))},[g.collectionRef,g.itemMap])}return[{Provider:a,Slot:c,ItemSlot:f},p,r]}function HG(t){const e=KG(t),n=D.forwardRef((r,i)=>{const{children:s,...a}=r,o=D.Children.toArray(s),l=o.find(qG);if(l){const c=l.props.children,u=o.map(d=>d===l?D.Children.count(c)>1?D.Children.only(null):D.isValidElement(c)?c.props.children:null:d);return y.jsx(e,{...a,ref:i,children:D.isValidElement(c)?D.cloneElement(c,void 0,u):null})}return y.jsx(e,{...a,ref:i,children:s})});return n.displayName=`${t}.Slot`,n}function KG(t){const e=D.forwardRef((n,r)=>{const{children:i,...s}=n;if(D.isValidElement(i)){const a=YG(i),o=WG(s,i.props);return i.type!==D.Fragment&&(o.ref=r?X0(r,a):a),D.cloneElement(i,o)}return D.Children.count(i)>1?D.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var zG=Symbol("radix.slottable");function qG(t){return D.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===zG}function WG(t,e){const n={...e};for(const r in e){const i=t[r],s=e[r];/^on[A-Z]/.test(r)?i&&s?n[r]=(...o)=>{const l=s(...o);return i(...o),l}:i&&(n[r]=i):r==="style"?n[r]={...i,...s}:r==="className"&&(n[r]=[i,s].filter(Boolean).join(" "))}return{...t,...n}}function YG(t){var r,i;let e=(r=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:r.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=(i=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:i.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var XG=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ar=XG.reduce((t,e)=>{const n=HG(`Primitive.${e}`),r=D.forwardRef((i,s)=>{const{asChild:a,...o}=i,l=a?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),y.jsx(l,{...o,ref:s})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});function JM(t,e){t&&Np.flushSync(()=>t.dispatchEvent(e))}function fa(t){const e=D.useRef(t);return D.useEffect(()=>{e.current=t}),D.useMemo(()=>(...n)=>{var r;return(r=e.current)==null?void 0:r.call(e,...n)},[])}function QG(t,e=globalThis==null?void 0:globalThis.document){const n=fa(t);D.useEffect(()=>{const r=i=>{i.key==="Escape"&&n(i)};return e.addEventListener("keydown",r,{capture:!0}),()=>e.removeEventListener("keydown",r,{capture:!0})},[n,e])}var JG="DismissableLayer",ES="dismissableLayer.update",ZG="dismissableLayer.pointerDownOutside",eH="dismissableLayer.focusOutside",bC,ZM=D.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Q0=D.forwardRef((t,e)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:a,onDismiss:o,...l}=t,c=D.useContext(ZM),[u,d]=D.useState(null),h=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,f]=D.useState({}),p=si(e,O=>d(O)),m=Array.from(c.layers),[g]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),b=m.indexOf(g),v=u?m.indexOf(u):-1,S=c.layersWithOutsidePointerEventsDisabled.size>0,E=v>=b,L=nH(O=>{const k=O.target,I=[...c.branches].some(R=>R.contains(k));!E||I||(i==null||i(O),a==null||a(O),O.defaultPrevented||o==null||o())},h),U=rH(O=>{const k=O.target;[...c.branches].some(R=>R.contains(k))||(s==null||s(O),a==null||a(O),O.defaultPrevented||o==null||o())},h);return QG(O=>{v===c.layers.size-1&&(r==null||r(O),!O.defaultPrevented&&o&&(O.preventDefault(),o()))},h),D.useEffect(()=>{if(u)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(bC=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(u)),c.layers.add(u),xC(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=bC)}},[u,h,n,c]),D.useEffect(()=>()=>{u&&(c.layers.delete(u),c.layersWithOutsidePointerEventsDisabled.delete(u),xC())},[u,c]),D.useEffect(()=>{const O=()=>f({});return document.addEventListener(ES,O),()=>document.removeEventListener(ES,O)},[]),y.jsx(ar.div,{...l,ref:p,style:{pointerEvents:S?E?"auto":"none":void 0,...t.style},onFocusCapture:kn(t.onFocusCapture,U.onFocusCapture),onBlurCapture:kn(t.onBlurCapture,U.onBlurCapture),onPointerDownCapture:kn(t.onPointerDownCapture,L.onPointerDownCapture)})});Q0.displayName=JG;var tH="DismissableLayerBranch",e2=D.forwardRef((t,e)=>{const n=D.useContext(ZM),r=D.useRef(null),i=si(e,r);return D.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),y.jsx(ar.div,{...t,ref:i})});e2.displayName=tH;function nH(t,e=globalThis==null?void 0:globalThis.document){const n=fa(t),r=D.useRef(!1),i=D.useRef(()=>{});return D.useEffect(()=>{const s=o=>{if(o.target&&!r.current){let l=function(){t2(ZG,n,c,{discrete:!0})};const c={originalEvent:o};o.pointerType==="touch"?(e.removeEventListener("click",i.current),i.current=l,e.addEventListener("click",i.current,{once:!0})):l()}else e.removeEventListener("click",i.current);r.current=!1},a=window.setTimeout(()=>{e.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(a),e.removeEventListener("pointerdown",s),e.removeEventListener("click",i.current)}},[e,n]),{onPointerDownCapture:()=>r.current=!0}}function rH(t,e=globalThis==null?void 0:globalThis.document){const n=fa(t),r=D.useRef(!1);return D.useEffect(()=>{const i=s=>{s.target&&!r.current&&t2(eH,n,{originalEvent:s},{discrete:!1})};return e.addEventListener("focusin",i),()=>e.removeEventListener("focusin",i)},[e,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function xC(){const t=new CustomEvent(ES);document.dispatchEvent(t)}function t2(t,e,n,{discrete:r}){const i=n.originalEvent.target,s=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:n});e&&i.addEventListener(t,e,{once:!0}),r?JM(i,s):i.dispatchEvent(s)}var iH=Q0,sH=e2,lo=globalThis!=null&&globalThis.document?D.useLayoutEffect:()=>{},aH="Portal",mT=D.forwardRef((t,e)=>{var o;const{container:n,...r}=t,[i,s]=D.useState(!1);lo(()=>s(!0),[]);const a=n||i&&((o=globalThis==null?void 0:globalThis.document)==null?void 0:o.body);return a?WD.createPortal(y.jsx(ar.div,{...r,ref:e}),a):null});mT.displayName=aH;function oH(t,e){return D.useReducer((n,r)=>e[n][r]??n,t)}var fh=t=>{const{present:e,children:n}=t,r=lH(e),i=typeof n=="function"?n({present:r.isPresent}):D.Children.only(n),s=si(r.ref,cH(i));return typeof n=="function"||r.isPresent?D.cloneElement(i,{ref:s}):null};fh.displayName="Presence";function lH(t){const[e,n]=D.useState(),r=D.useRef(null),i=D.useRef(t),s=D.useRef("none"),a=t?"mounted":"unmounted",[o,l]=oH(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return D.useEffect(()=>{const c=qm(r.current);s.current=o==="mounted"?c:"none"},[o]),lo(()=>{const c=r.current,u=i.current;if(u!==t){const h=s.current,f=qm(c);t?l("MOUNT"):f==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(u&&h!==f?"ANIMATION_OUT":"UNMOUNT"),i.current=t}},[t,l]),lo(()=>{if(e){let c;const u=e.ownerDocument.defaultView??window,d=f=>{const m=qm(r.current).includes(CSS.escape(f.animationName));if(f.target===e&&m&&(l("ANIMATION_END"),!i.current)){const g=e.style.animationFillMode;e.style.animationFillMode="forwards",c=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=g)})}},h=f=>{f.target===e&&(s.current=qm(r.current))};return e.addEventListener("animationstart",h),e.addEventListener("animationcancel",d),e.addEventListener("animationend",d),()=>{u.clearTimeout(c),e.removeEventListener("animationstart",h),e.removeEventListener("animationcancel",d),e.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[e,l]),{isPresent:["mounted","unmountSuspended"].includes(o),ref:D.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function qm(t){return(t==null?void 0:t.animationName)||"none"}function cH(t){var r,i;let e=(r=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:r.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=(i=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:i.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var uH=cw[" useInsertionEffect ".trim().toString()]||lo;function n2({prop:t,defaultProp:e,onChange:n=()=>{},caller:r}){const[i,s,a]=dH({defaultProp:e,onChange:n}),o=t!==void 0,l=o?t:i;{const u=D.useRef(t!==void 0);D.useEffect(()=>{const d=u.current;d!==o&&console.warn(`${r} is changing from ${d?"controlled":"uncontrolled"} to ${o?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=o},[o,r])}const c=D.useCallback(u=>{var d;if(o){const h=hH(u)?u(t):u;h!==t&&((d=a.current)==null||d.call(a,h))}else s(u)},[o,t,s,a]);return[l,c]}function dH({defaultProp:t,onChange:e}){const[n,r]=D.useState(t),i=D.useRef(n),s=D.useRef(e);return uH(()=>{s.current=e},[e]),D.useEffect(()=>{var a;i.current!==n&&((a=s.current)==null||a.call(s,n),i.current=n)},[n,i]),[n,r,s]}function hH(t){return typeof t=="function"}var fH=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),pH="VisuallyHidden",J0=D.forwardRef((t,e)=>y.jsx(ar.span,{...t,ref:e,style:{...fH,...t.style}}));J0.displayName=pH;var mH=J0,gT="ToastProvider",[yT,gH,yH]=GG("Toast"),[r2]=Zp("Toast",[yH]),[vH,Z0]=r2(gT),i2=t=>{const{__scopeToast:e,label:n="Notification",duration:r=5e3,swipeDirection:i="right",swipeThreshold:s=50,children:a}=t,[o,l]=D.useState(null),[c,u]=D.useState(0),d=D.useRef(!1),h=D.useRef(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${gT}\`. Expected non-empty \`string\`.`),y.jsx(yT.Provider,{scope:e,children:y.jsx(vH,{scope:e,label:n,duration:r,swipeDirection:i,swipeThreshold:s,toastCount:c,viewport:o,onViewportChange:l,onToastAdd:D.useCallback(()=>u(f=>f+1),[]),onToastRemove:D.useCallback(()=>u(f=>f-1),[]),isFocusedToastEscapeKeyDownRef:d,isClosePausedRef:h,children:a})})};i2.displayName=gT;var s2="ToastViewport",_H=["F8"],wS="toast.viewportPause",TS="toast.viewportResume",a2=D.forwardRef((t,e)=>{const{__scopeToast:n,hotkey:r=_H,label:i="Notifications ({hotkey})",...s}=t,a=Z0(s2,n),o=gH(n),l=D.useRef(null),c=D.useRef(null),u=D.useRef(null),d=D.useRef(null),h=si(e,d,a.onViewportChange),f=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),p=a.toastCount>0;D.useEffect(()=>{const g=b=>{var S;r.length!==0&&r.every(E=>b[E]||b.code===E)&&((S=d.current)==null||S.focus())};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[r]),D.useEffect(()=>{const g=l.current,b=d.current;if(p&&g&&b){const v=()=>{if(!a.isClosePausedRef.current){const U=new CustomEvent(wS);b.dispatchEvent(U),a.isClosePausedRef.current=!0}},S=()=>{if(a.isClosePausedRef.current){const U=new CustomEvent(TS);b.dispatchEvent(U),a.isClosePausedRef.current=!1}},E=U=>{!g.contains(U.relatedTarget)&&S()},L=()=>{g.contains(document.activeElement)||S()};return g.addEventListener("focusin",v),g.addEventListener("focusout",E),g.addEventListener("pointermove",v),g.addEventListener("pointerleave",L),window.addEventListener("blur",v),window.addEventListener("focus",S),()=>{g.removeEventListener("focusin",v),g.removeEventListener("focusout",E),g.removeEventListener("pointermove",v),g.removeEventListener("pointerleave",L),window.removeEventListener("blur",v),window.removeEventListener("focus",S)}}},[p,a.isClosePausedRef]);const m=D.useCallback(({tabbingDirection:g})=>{const v=o().map(S=>{const E=S.ref.current,L=[E,...PH(E)];return g==="forwards"?L:L.reverse()});return(g==="forwards"?v.reverse():v).flat()},[o]);return D.useEffect(()=>{const g=d.current;if(g){const b=v=>{var L,U,O;const S=v.altKey||v.ctrlKey||v.metaKey;if(v.key==="Tab"&&!S){const k=document.activeElement,I=v.shiftKey;if(v.target===g&&I){(L=c.current)==null||L.focus();return}const z=m({tabbingDirection:I?"backwards":"forwards"}),Z=z.findIndex(W=>W===k);F_(z.slice(Z+1))?v.preventDefault():I?(U=c.current)==null||U.focus():(O=u.current)==null||O.focus()}};return g.addEventListener("keydown",b),()=>g.removeEventListener("keydown",b)}},[o,m]),y.jsxs(sH,{ref:l,role:"region","aria-label":i.replace("{hotkey}",f),tabIndex:-1,style:{pointerEvents:p?void 0:"none"},children:[p&&y.jsx(AS,{ref:c,onFocusFromOutsideViewport:()=>{const g=m({tabbingDirection:"forwards"});F_(g)}}),y.jsx(yT.Slot,{scope:n,children:y.jsx(ar.ol,{tabIndex:-1,...s,ref:h})}),p&&y.jsx(AS,{ref:u,onFocusFromOutsideViewport:()=>{const g=m({tabbingDirection:"backwards"});F_(g)}})]})});a2.displayName=s2;var o2="ToastFocusProxy",AS=D.forwardRef((t,e)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...i}=t,s=Z0(o2,n);return y.jsx(J0,{tabIndex:0,...i,ref:e,style:{position:"fixed"},onFocus:a=>{var c;const o=a.relatedTarget;!((c=s.viewport)!=null&&c.contains(o))&&r()}})});AS.displayName=o2;var em="Toast",bH="toast.swipeStart",xH="toast.swipeMove",SH="toast.swipeCancel",EH="toast.swipeEnd",l2=D.forwardRef((t,e)=>{const{forceMount:n,open:r,defaultOpen:i,onOpenChange:s,...a}=t,[o,l]=n2({prop:r,defaultProp:i??!0,onChange:s,caller:em});return y.jsx(fh,{present:n||o,children:y.jsx(AH,{open:o,...a,ref:e,onClose:()=>l(!1),onPause:fa(t.onPause),onResume:fa(t.onResume),onSwipeStart:kn(t.onSwipeStart,c=>{c.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:kn(t.onSwipeMove,c=>{const{x:u,y:d}=c.detail.delta;c.currentTarget.setAttribute("data-swipe","move"),c.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${u}px`),c.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${d}px`)}),onSwipeCancel:kn(t.onSwipeCancel,c=>{c.currentTarget.setAttribute("data-swipe","cancel"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),c.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),c.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:kn(t.onSwipeEnd,c=>{const{x:u,y:d}=c.detail.delta;c.currentTarget.setAttribute("data-swipe","end"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),c.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${u}px`),c.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${d}px`),l(!1)})})})});l2.displayName=em;var[wH,TH]=r2(em,{onClose(){}}),AH=D.forwardRef((t,e)=>{const{__scopeToast:n,type:r="foreground",duration:i,open:s,onClose:a,onEscapeKeyDown:o,onPause:l,onResume:c,onSwipeStart:u,onSwipeMove:d,onSwipeCancel:h,onSwipeEnd:f,...p}=t,m=Z0(em,n),[g,b]=D.useState(null),v=si(e,W=>b(W)),S=D.useRef(null),E=D.useRef(null),L=i||m.duration,U=D.useRef(0),O=D.useRef(L),k=D.useRef(0),{onToastAdd:I,onToastRemove:R}=m,M=fa(()=>{var re;(g==null?void 0:g.contains(document.activeElement))&&((re=m.viewport)==null||re.focus()),a()}),z=D.useCallback(W=>{!W||W===1/0||(window.clearTimeout(k.current),U.current=new Date().getTime(),k.current=window.setTimeout(M,W))},[M]);D.useEffect(()=>{const W=m.viewport;if(W){const re=()=>{z(O.current),c==null||c()},X=()=>{const oe=new Date().getTime()-U.current;O.current=O.current-oe,window.clearTimeout(k.current),l==null||l()};return W.addEventListener(wS,X),W.addEventListener(TS,re),()=>{W.removeEventListener(wS,X),W.removeEventListener(TS,re)}}},[m.viewport,L,l,c,z]),D.useEffect(()=>{s&&!m.isClosePausedRef.current&&z(L)},[s,L,m.isClosePausedRef,z]),D.useEffect(()=>(I(),()=>R()),[I,R]);const Z=D.useMemo(()=>g?m2(g):null,[g]);return m.viewport?y.jsxs(y.Fragment,{children:[Z&&y.jsx(RH,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite",children:Z}),y.jsx(wH,{scope:n,onClose:M,children:Np.createPortal(y.jsx(yT.ItemSlot,{scope:n,children:y.jsx(iH,{asChild:!0,onEscapeKeyDown:kn(o,()=>{m.isFocusedToastEscapeKeyDownRef.current||M(),m.isFocusedToastEscapeKeyDownRef.current=!1}),children:y.jsx(ar.li,{tabIndex:0,"data-state":s?"open":"closed","data-swipe-direction":m.swipeDirection,...p,ref:v,style:{userSelect:"none",touchAction:"none",...t.style},onKeyDown:kn(t.onKeyDown,W=>{W.key==="Escape"&&(o==null||o(W.nativeEvent),W.nativeEvent.defaultPrevented||(m.isFocusedToastEscapeKeyDownRef.current=!0,M()))}),onPointerDown:kn(t.onPointerDown,W=>{W.button===0&&(S.current={x:W.clientX,y:W.clientY})}),onPointerMove:kn(t.onPointerMove,W=>{if(!S.current)return;const re=W.clientX-S.current.x,X=W.clientY-S.current.y,oe=!!E.current,Q=["left","right"].includes(m.swipeDirection),G=["left","up"].includes(m.swipeDirection)?Math.min:Math.max,H=Q?G(0,re):0,Y=Q?0:G(0,X),ie=W.pointerType==="touch"?10:2,Ce={x:H,y:Y},Le={originalEvent:W,delta:Ce};oe?(E.current=Ce,Wm(xH,d,Le,{discrete:!1})):SC(Ce,m.swipeDirection,ie)?(E.current=Ce,Wm(bH,u,Le,{discrete:!1}),W.target.setPointerCapture(W.pointerId)):(Math.abs(re)>ie||Math.abs(X)>ie)&&(S.current=null)}),onPointerUp:kn(t.onPointerUp,W=>{const re=E.current,X=W.target;if(X.hasPointerCapture(W.pointerId)&&X.releasePointerCapture(W.pointerId),E.current=null,S.current=null,re){const oe=W.currentTarget,Q={originalEvent:W,delta:re};SC(re,m.swipeDirection,m.swipeThreshold)?Wm(EH,f,Q,{discrete:!0}):Wm(SH,h,Q,{discrete:!0}),oe.addEventListener("click",G=>G.preventDefault(),{once:!0})}})})})}),m.viewport)})]}):null}),RH=t=>{const{__scopeToast:e,children:n,...r}=t,i=Z0(em,e),[s,a]=D.useState(!1),[o,l]=D.useState(!1);return kH(()=>a(!0)),D.useEffect(()=>{const c=window.setTimeout(()=>l(!0),1e3);return()=>window.clearTimeout(c)},[]),o?null:y.jsx(mT,{asChild:!0,children:y.jsx(J0,{...r,children:s&&y.jsxs(y.Fragment,{children:[i.label," ",n]})})})},CH="ToastTitle",c2=D.forwardRef((t,e)=>{const{__scopeToast:n,...r}=t;return y.jsx(ar.div,{...r,ref:e})});c2.displayName=CH;var LH="ToastDescription",u2=D.forwardRef((t,e)=>{const{__scopeToast:n,...r}=t;return y.jsx(ar.div,{...r,ref:e})});u2.displayName=LH;var d2="ToastAction",h2=D.forwardRef((t,e)=>{const{altText:n,...r}=t;return n.trim()?y.jsx(p2,{altText:n,asChild:!0,children:y.jsx(vT,{...r,ref:e})}):(console.error(`Invalid prop \`altText\` supplied to \`${d2}\`. Expected non-empty \`string\`.`),null)});h2.displayName=d2;var f2="ToastClose",vT=D.forwardRef((t,e)=>{const{__scopeToast:n,...r}=t,i=TH(f2,n);return y.jsx(p2,{asChild:!0,children:y.jsx(ar.button,{type:"button",...r,ref:e,onClick:kn(t.onClick,i.onClose)})})});vT.displayName=f2;var p2=D.forwardRef((t,e)=>{const{__scopeToast:n,altText:r,...i}=t;return y.jsx(ar.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...i,ref:e})});function m2(t){const e=[];return Array.from(t.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&e.push(r.textContent),IH(r)){const i=r.ariaHidden||r.hidden||r.style.display==="none",s=r.dataset.radixToastAnnounceExclude==="";if(!i)if(s){const a=r.dataset.radixToastAnnounceAlt;a&&e.push(a)}else e.push(...m2(r))}}),e}function Wm(t,e,n,{discrete:r}){const i=n.originalEvent.currentTarget,s=new CustomEvent(t,{bubbles:!0,cancelable:!0,detail:n});e&&i.addEventListener(t,e,{once:!0}),r?JM(i,s):i.dispatchEvent(s)}var SC=(t,e,n=0)=>{const r=Math.abs(t.x),i=Math.abs(t.y),s=r>i;return e==="left"||e==="right"?s&&r>n:!s&&i>n};function kH(t=()=>{}){const e=fa(t);lo(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(e)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[e])}function IH(t){return t.nodeType===t.ELEMENT_NODE}function PH(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)e.push(n.currentNode);return e}function F_(t){const e=document.activeElement;return t.some(n=>n===e?!0:(n.focus(),document.activeElement!==e))}var DH=i2,g2=a2,y2=l2,v2=c2,_2=u2,b2=h2,x2=vT;function S2(t){var e,n,r="";if(typeof t=="string"||typeof t=="number")r+=t;else if(typeof t=="object")if(Array.isArray(t)){var i=t.length;for(e=0;e<i;e++)t[e]&&(n=S2(t[e]))&&(r&&(r+=" "),r+=n)}else for(n in t)t[n]&&(r&&(r+=" "),r+=n);return r}function E2(){for(var t,e,n=0,r="",i=arguments.length;n<i;n++)(t=arguments[n])&&(e=S2(t))&&(r&&(r+=" "),r+=e);return r}const EC=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,wC=E2,OH=(t,e)=>n=>{var r;if((e==null?void 0:e.variants)==null)return wC(t,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:i,defaultVariants:s}=e,a=Object.keys(i).map(c=>{const u=n==null?void 0:n[c],d=s==null?void 0:s[c];if(u===null)return null;const h=EC(u)||EC(d);return i[c][h]}),o=n&&Object.entries(n).reduce((c,u)=>{let[d,h]=u;return h===void 0||(c[d]=h),c},{}),l=e==null||(r=e.compoundVariants)===null||r===void 0?void 0:r.reduce((c,u)=>{let{class:d,className:h,...f}=u;return Object.entries(f).every(p=>{let[m,g]=p;return Array.isArray(g)?g.includes({...s,...o}[m]):{...s,...o}[m]===g})?[...c,d,h]:c},[]);return wC(t,a,l,n==null?void 0:n.class,n==null?void 0:n.className)};/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const w2=(...t)=>t.filter((e,n,r)=>!!e&&e.trim()!==""&&r.indexOf(e)===n).join(" ").trim();/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const NH=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const MH=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,r)=>r?r.toUpperCase():n.toLowerCase());/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const TC=t=>{const e=MH(t);return e.charAt(0).toUpperCase()+e.slice(1)};/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */var $_={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const BH=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1},UH=D.createContext({}),jH=()=>D.useContext(UH),FH=D.forwardRef(({color:t,size:e,strokeWidth:n,absoluteStrokeWidth:r,className:i="",children:s,iconNode:a,...o},l)=>{const{size:c=24,strokeWidth:u=2,absoluteStrokeWidth:d=!1,color:h="currentColor",className:f=""}=jH()??{},p=r??d?Number(n??u)*24/Number(e??c):n??u;return D.createElement("svg",{ref:l,...$_,width:e??c??$_.width,height:e??c??$_.height,stroke:t??h,strokeWidth:p,className:w2("lucide",f,i),...!s&&!BH(o)&&{"aria-hidden":"true"},...o},[...a.map(([m,g])=>D.createElement(m,g)),...Array.isArray(s)?s:[s]])});/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const mt=(t,e)=>{const n=D.forwardRef(({className:r,...i},s)=>D.createElement(FH,{ref:s,iconNode:e,className:w2(`lucide-${NH(TC(t))}`,`lucide-${t}`,r),...i}));return n.displayName=TC(t),n};/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const $H=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],ev=mt("arrow-left",$H);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const VH=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],GH=mt("calendar",VH);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const HH=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Ol=mt("check",HH);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const KH=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],tv=mt("chevron-down",KH);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const zH=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],qH=mt("circle-check",zH);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const WH=[["path",{d:"M17.925 20.056a6 6 0 0 0-11.851.001",key:"z69sun"}],["circle",{cx:"12",cy:"11",r:"4",key:"1gt34v"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],YH=mt("circle-user-round",WH);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const XH=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662",key:"154egf"}]],Rc=mt("circle-user",XH);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const QH=[["path",{d:"m12.296 3.464 3.02 3.956",key:"qash78"}],["path",{d:"M20.2 6 3 11l-.9-2.4c-.3-1.1.3-2.2 1.3-2.5l13.5-4c1.1-.3 2.2.3 2.5 1.3z",key:"1h7j8b"}],["path",{d:"M3 11h18v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"4lm6w1"}],["path",{d:"m6.18 5.276 3.1 3.899",key:"zjj9t3"}]],nv=mt("clapperboard",QH);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const JH=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],T2=mt("clock",JH);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const ZH=[["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}],["path",{d:"M15.947 12.65a4 4 0 0 0-5.925-4.128",key:"dpwdj0"}],["path",{d:"M13 22H7a5 5 0 1 1 4.9-6H13a3 3 0 0 1 0 6Z",key:"s09mg5"}]],RS=mt("cloud-sun",ZH);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const eK=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],tK=mt("copy",eK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const nK=[["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M17 20v2",key:"1rnc9c"}],["path",{d:"M17 2v2",key:"11trls"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M2 17h2",key:"7oei6x"}],["path",{d:"M2 7h2",key:"asdhe0"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"M20 17h2",key:"1fpfkl"}],["path",{d:"M20 7h2",key:"1o8tra"}],["path",{d:"M7 20v2",key:"4gnj0m"}],["path",{d:"M7 2v2",key:"1i4yhu"}],["rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",key:"1vbyd7"}],["rect",{x:"8",y:"8",width:"8",height:"8",rx:"1",key:"z9xiuo"}]],CS=mt("cpu",nK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const rK=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],_T=mt("download",rK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const iK=[["path",{d:"M21.54 15H17a2 2 0 0 0-2 2v4.54",key:"1djwo0"}],["path",{d:"M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17",key:"1tzkfa"}],["path",{d:"M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05",key:"14pb5j"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],LS=mt("earth",iK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const sK=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],no=mt("external-link",sK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const aK=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],bT=mt("file-text",aK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const oK=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 3v18",key:"bbkbws"}],["path",{d:"M3 7.5h4",key:"zfgn84"}],["path",{d:"M3 12h18",key:"1i2n21"}],["path",{d:"M3 16.5h4",key:"1230mu"}],["path",{d:"M17 3v18",key:"in4fa5"}],["path",{d:"M17 7.5h4",key:"myr1c1"}],["path",{d:"M17 16.5h4",key:"go4c1d"}]],xT=mt("film",oK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const lK=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],cK=mt("globe",lK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const uK=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],dK=mt("house",uK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const hK=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],fK=mt("info",hK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const pK=[["path",{d:"M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]],rv=mt("key-round",pK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const mK=[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]],gK=mt("layout-grid",mK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const yK=[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]],Wy=mt("link-2",yK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const vK=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],kS=mt("link",vK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const _K=[["path",{d:"M3 5h.01",key:"18ugdj"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 19h.01",key:"noohij"}],["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 19h13",key:"m83p4d"}]],bK=mt("list",_K);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const xK=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],yr=mt("loader-circle",xK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const SK=[["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m16.2 7.8 2.9-2.9",key:"r700ao"}],["path",{d:"M18 12h4",key:"wj9ykh"}],["path",{d:"m16.2 16.2 2.9 2.9",key:"1bxg5t"}],["path",{d:"M12 18v4",key:"jadmvz"}],["path",{d:"m4.9 19.1 2.9-2.9",key:"bwix9q"}],["path",{d:"M2 12h4",key:"j09sii"}],["path",{d:"m4.9 4.9 2.9 2.9",key:"giyufr"}]],EK=mt("loader",SK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const wK=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],TK=mt("lock",wK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const AK=[["path",{d:"m10 17 5-5-5-5",key:"1bsop3"}],["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",key:"u53s6r"}]],RK=mt("log-in",AK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const CK=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],A2=mt("log-out",CK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const LK=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]],kK=mt("mail",LK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const IK=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],R2=mt("message-circle",IK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const PK=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],DK=mt("pen",PK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const OK=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],sc=mt("play",OK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const NK=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]],MK=mt("plug",NK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const BK=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],gl=mt("plus",BK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const UK=[["path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"14sxne"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16",key:"1hlbsb"}],["path",{d:"M16 16h5v5",key:"ccwih5"}]],jK=mt("refresh-ccw",UK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const FK=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],tm=mt("refresh-cw",FK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const $K=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],VK=mt("save",$K);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const GK=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],ST=mt("search",GK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const HK=[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]],Cc=mt("server",HK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const KK=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],C2=mt("settings",KK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const zK=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],ap=mt("shield-check",zK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const qK=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],AC=mt("smartphone",qK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const WK=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],L2=mt("sparkles",WK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const YK=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],Sf=mt("star",YK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const XK=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],nm=mt("trash-2",XK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const QK=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],JK=mt("triangle-alert",QK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const ZK=[["path",{d:"m17 2-5 5-5-5",key:"16satq"}],["rect",{width:"20",height:"15",x:"2",y:"7",rx:"2",key:"1e6viu"}]],xa=mt("tv",ZK);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const ez=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],ET=mt("upload",ez);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const tz=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]],fo=mt("user",tz);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const nz=[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M2 8.82a15 15 0 0 1 20 0",key:"dnpr2z"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]],rz=mt("wifi",nz);/**
 * @license lucide-react v1.11.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const iz=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Sa=mt("x",iz),wT="-",sz=t=>{const e=oz(t),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:a=>{const o=a.split(wT);return o[0]===""&&o.length!==1&&o.shift(),k2(o,e)||az(a)},getConflictingClassGroupIds:(a,o)=>{const l=n[a]||[];return o&&r[a]?[...l,...r[a]]:l}}},k2=(t,e)=>{var a;if(t.length===0)return e.classGroupId;const n=t[0],r=e.nextPart.get(n),i=r?k2(t.slice(1),r):void 0;if(i)return i;if(e.validators.length===0)return;const s=t.join(wT);return(a=e.validators.find(({validator:o})=>o(s)))==null?void 0:a.classGroupId},RC=/^\[(.+)\]$/,az=t=>{if(RC.test(t)){const e=RC.exec(t)[1],n=e==null?void 0:e.substring(0,e.indexOf(":"));if(n)return"arbitrary.."+n}},oz=t=>{const{theme:e,prefix:n}=t,r={nextPart:new Map,validators:[]};return cz(Object.entries(t.classGroups),n).forEach(([s,a])=>{IS(a,r,s,e)}),r},IS=(t,e,n,r)=>{t.forEach(i=>{if(typeof i=="string"){const s=i===""?e:CC(e,i);s.classGroupId=n;return}if(typeof i=="function"){if(lz(i)){IS(i(r),e,n,r);return}e.validators.push({validator:i,classGroupId:n});return}Object.entries(i).forEach(([s,a])=>{IS(a,CC(e,s),n,r)})})},CC=(t,e)=>{let n=t;return e.split(wT).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},lz=t=>t.isThemeGetter,cz=(t,e)=>e?t.map(([n,r])=>{const i=r.map(s=>typeof s=="string"?e+s:typeof s=="object"?Object.fromEntries(Object.entries(s).map(([a,o])=>[e+a,o])):s);return[n,i]}):t,uz=t=>{if(t<1)return{get:()=>{},set:()=>{}};let e=0,n=new Map,r=new Map;const i=(s,a)=>{n.set(s,a),e++,e>t&&(e=0,r=n,n=new Map)};return{get(s){let a=n.get(s);if(a!==void 0)return a;if((a=r.get(s))!==void 0)return i(s,a),a},set(s,a){n.has(s)?n.set(s,a):i(s,a)}}},I2="!",dz=t=>{const{separator:e,experimentalParseClassName:n}=t,r=e.length===1,i=e[0],s=e.length,a=o=>{const l=[];let c=0,u=0,d;for(let g=0;g<o.length;g++){let b=o[g];if(c===0){if(b===i&&(r||o.slice(g,g+s)===e)){l.push(o.slice(u,g)),u=g+s;continue}if(b==="/"){d=g;continue}}b==="["?c++:b==="]"&&c--}const h=l.length===0?o:o.substring(u),f=h.startsWith(I2),p=f?h.substring(1):h,m=d&&d>u?d-u:void 0;return{modifiers:l,hasImportantModifier:f,baseClassName:p,maybePostfixModifierPosition:m}};return n?o=>n({className:o,parseClassName:a}):a},hz=t=>{if(t.length<=1)return t;const e=[];let n=[];return t.forEach(r=>{r[0]==="["?(e.push(...n.sort(),r),n=[]):n.push(r)}),e.push(...n.sort()),e},fz=t=>({cache:uz(t.cacheSize),parseClassName:dz(t),...sz(t)}),pz=/\s+/,mz=(t,e)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i}=e,s=[],a=t.trim().split(pz);let o="";for(let l=a.length-1;l>=0;l-=1){const c=a[l],{modifiers:u,hasImportantModifier:d,baseClassName:h,maybePostfixModifierPosition:f}=n(c);let p=!!f,m=r(p?h.substring(0,f):h);if(!m){if(!p){o=c+(o.length>0?" "+o:o);continue}if(m=r(h),!m){o=c+(o.length>0?" "+o:o);continue}p=!1}const g=hz(u).join(":"),b=d?g+I2:g,v=b+m;if(s.includes(v))continue;s.push(v);const S=i(m,p);for(let E=0;E<S.length;++E){const L=S[E];s.push(b+L)}o=c+(o.length>0?" "+o:o)}return o};function gz(){let t=0,e,n,r="";for(;t<arguments.length;)(e=arguments[t++])&&(n=P2(e))&&(r&&(r+=" "),r+=n);return r}const P2=t=>{if(typeof t=="string")return t;let e,n="";for(let r=0;r<t.length;r++)t[r]&&(e=P2(t[r]))&&(n&&(n+=" "),n+=e);return n};function yz(t,...e){let n,r,i,s=a;function a(l){const c=e.reduce((u,d)=>d(u),t());return n=fz(c),r=n.cache.get,i=n.cache.set,s=o,o(l)}function o(l){const c=r(l);if(c)return c;const u=mz(l,n);return i(l,u),u}return function(){return s(gz.apply(null,arguments))}}const wn=t=>{const e=n=>n[t]||[];return e.isThemeGetter=!0,e},D2=/^\[(?:([a-z-]+):)?(.+)\]$/i,vz=/^\d+\/\d+$/,_z=new Set(["px","full","screen"]),bz=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,xz=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Sz=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Ez=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,wz=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Pa=t=>fd(t)||_z.has(t)||vz.test(t),To=t=>ph(t,"length",Pz),fd=t=>!!t&&!Number.isNaN(Number(t)),V_=t=>ph(t,"number",fd),jh=t=>!!t&&Number.isInteger(Number(t)),Tz=t=>t.endsWith("%")&&fd(t.slice(0,-1)),Dt=t=>D2.test(t),Ao=t=>bz.test(t),Az=new Set(["length","size","percentage"]),Rz=t=>ph(t,Az,O2),Cz=t=>ph(t,"position",O2),Lz=new Set(["image","url"]),kz=t=>ph(t,Lz,Oz),Iz=t=>ph(t,"",Dz),Fh=()=>!0,ph=(t,e,n)=>{const r=D2.exec(t);return r?r[1]?typeof e=="string"?r[1]===e:e.has(r[1]):n(r[2]):!1},Pz=t=>xz.test(t)&&!Sz.test(t),O2=()=>!1,Dz=t=>Ez.test(t),Oz=t=>wz.test(t),Nz=()=>{const t=wn("colors"),e=wn("spacing"),n=wn("blur"),r=wn("brightness"),i=wn("borderColor"),s=wn("borderRadius"),a=wn("borderSpacing"),o=wn("borderWidth"),l=wn("contrast"),c=wn("grayscale"),u=wn("hueRotate"),d=wn("invert"),h=wn("gap"),f=wn("gradientColorStops"),p=wn("gradientColorStopPositions"),m=wn("inset"),g=wn("margin"),b=wn("opacity"),v=wn("padding"),S=wn("saturate"),E=wn("scale"),L=wn("sepia"),U=wn("skew"),O=wn("space"),k=wn("translate"),I=()=>["auto","contain","none"],R=()=>["auto","hidden","clip","visible","scroll"],M=()=>["auto",Dt,e],z=()=>[Dt,e],Z=()=>["",Pa,To],W=()=>["auto",fd,Dt],re=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],X=()=>["solid","dashed","dotted","double","none"],oe=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Q=()=>["start","end","center","between","around","evenly","stretch"],G=()=>["","0",Dt],H=()=>["auto","avoid","all","avoid-page","page","left","right","column"],Y=()=>[fd,Dt];return{cacheSize:500,separator:":",theme:{colors:[Fh],spacing:[Pa,To],blur:["none","",Ao,Dt],brightness:Y(),borderColor:[t],borderRadius:["none","","full",Ao,Dt],borderSpacing:z(),borderWidth:Z(),contrast:Y(),grayscale:G(),hueRotate:Y(),invert:G(),gap:z(),gradientColorStops:[t],gradientColorStopPositions:[Tz,To],inset:M(),margin:M(),opacity:Y(),padding:z(),saturate:Y(),scale:Y(),sepia:G(),skew:Y(),space:z(),translate:z()},classGroups:{aspect:[{aspect:["auto","square","video",Dt]}],container:["container"],columns:[{columns:[Ao]}],"break-after":[{"break-after":H()}],"break-before":[{"break-before":H()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...re(),Dt]}],overflow:[{overflow:R()}],"overflow-x":[{"overflow-x":R()}],"overflow-y":[{"overflow-y":R()}],overscroll:[{overscroll:I()}],"overscroll-x":[{"overscroll-x":I()}],"overscroll-y":[{"overscroll-y":I()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[m]}],"inset-x":[{"inset-x":[m]}],"inset-y":[{"inset-y":[m]}],start:[{start:[m]}],end:[{end:[m]}],top:[{top:[m]}],right:[{right:[m]}],bottom:[{bottom:[m]}],left:[{left:[m]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",jh,Dt]}],basis:[{basis:M()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Dt]}],grow:[{grow:G()}],shrink:[{shrink:G()}],order:[{order:["first","last","none",jh,Dt]}],"grid-cols":[{"grid-cols":[Fh]}],"col-start-end":[{col:["auto",{span:["full",jh,Dt]},Dt]}],"col-start":[{"col-start":W()}],"col-end":[{"col-end":W()}],"grid-rows":[{"grid-rows":[Fh]}],"row-start-end":[{row:["auto",{span:[jh,Dt]},Dt]}],"row-start":[{"row-start":W()}],"row-end":[{"row-end":W()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Dt]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Dt]}],gap:[{gap:[h]}],"gap-x":[{"gap-x":[h]}],"gap-y":[{"gap-y":[h]}],"justify-content":[{justify:["normal",...Q()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...Q(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...Q(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[v]}],px:[{px:[v]}],py:[{py:[v]}],ps:[{ps:[v]}],pe:[{pe:[v]}],pt:[{pt:[v]}],pr:[{pr:[v]}],pb:[{pb:[v]}],pl:[{pl:[v]}],m:[{m:[g]}],mx:[{mx:[g]}],my:[{my:[g]}],ms:[{ms:[g]}],me:[{me:[g]}],mt:[{mt:[g]}],mr:[{mr:[g]}],mb:[{mb:[g]}],ml:[{ml:[g]}],"space-x":[{"space-x":[O]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[O]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Dt,e]}],"min-w":[{"min-w":[Dt,e,"min","max","fit"]}],"max-w":[{"max-w":[Dt,e,"none","full","min","max","fit","prose",{screen:[Ao]},Ao]}],h:[{h:[Dt,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Dt,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Dt,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Dt,e,"auto","min","max","fit"]}],"font-size":[{text:["base",Ao,To]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",V_]}],"font-family":[{font:[Fh]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Dt]}],"line-clamp":[{"line-clamp":["none",fd,V_]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Pa,Dt]}],"list-image":[{"list-image":["none",Dt]}],"list-style-type":[{list:["none","disc","decimal",Dt]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[b]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[b]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...X(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Pa,To]}],"underline-offset":[{"underline-offset":["auto",Pa,Dt]}],"text-decoration-color":[{decoration:[t]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:z()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Dt]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Dt]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[b]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...re(),Cz]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",Rz]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},kz]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[p]}],"gradient-via-pos":[{via:[p]}],"gradient-to-pos":[{to:[p]}],"gradient-from":[{from:[f]}],"gradient-via":[{via:[f]}],"gradient-to":[{to:[f]}],rounded:[{rounded:[s]}],"rounded-s":[{"rounded-s":[s]}],"rounded-e":[{"rounded-e":[s]}],"rounded-t":[{"rounded-t":[s]}],"rounded-r":[{"rounded-r":[s]}],"rounded-b":[{"rounded-b":[s]}],"rounded-l":[{"rounded-l":[s]}],"rounded-ss":[{"rounded-ss":[s]}],"rounded-se":[{"rounded-se":[s]}],"rounded-ee":[{"rounded-ee":[s]}],"rounded-es":[{"rounded-es":[s]}],"rounded-tl":[{"rounded-tl":[s]}],"rounded-tr":[{"rounded-tr":[s]}],"rounded-br":[{"rounded-br":[s]}],"rounded-bl":[{"rounded-bl":[s]}],"border-w":[{border:[o]}],"border-w-x":[{"border-x":[o]}],"border-w-y":[{"border-y":[o]}],"border-w-s":[{"border-s":[o]}],"border-w-e":[{"border-e":[o]}],"border-w-t":[{"border-t":[o]}],"border-w-r":[{"border-r":[o]}],"border-w-b":[{"border-b":[o]}],"border-w-l":[{"border-l":[o]}],"border-opacity":[{"border-opacity":[b]}],"border-style":[{border:[...X(),"hidden"]}],"divide-x":[{"divide-x":[o]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[o]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[b]}],"divide-style":[{divide:X()}],"border-color":[{border:[i]}],"border-color-x":[{"border-x":[i]}],"border-color-y":[{"border-y":[i]}],"border-color-s":[{"border-s":[i]}],"border-color-e":[{"border-e":[i]}],"border-color-t":[{"border-t":[i]}],"border-color-r":[{"border-r":[i]}],"border-color-b":[{"border-b":[i]}],"border-color-l":[{"border-l":[i]}],"divide-color":[{divide:[i]}],"outline-style":[{outline:["",...X()]}],"outline-offset":[{"outline-offset":[Pa,Dt]}],"outline-w":[{outline:[Pa,To]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:Z()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[b]}],"ring-offset-w":[{"ring-offset":[Pa,To]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",Ao,Iz]}],"shadow-color":[{shadow:[Fh]}],opacity:[{opacity:[b]}],"mix-blend":[{"mix-blend":[...oe(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":oe()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[l]}],"drop-shadow":[{"drop-shadow":["","none",Ao,Dt]}],grayscale:[{grayscale:[c]}],"hue-rotate":[{"hue-rotate":[u]}],invert:[{invert:[d]}],saturate:[{saturate:[S]}],sepia:[{sepia:[L]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[l]}],"backdrop-grayscale":[{"backdrop-grayscale":[c]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[u]}],"backdrop-invert":[{"backdrop-invert":[d]}],"backdrop-opacity":[{"backdrop-opacity":[b]}],"backdrop-saturate":[{"backdrop-saturate":[S]}],"backdrop-sepia":[{"backdrop-sepia":[L]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[a]}],"border-spacing-x":[{"border-spacing-x":[a]}],"border-spacing-y":[{"border-spacing-y":[a]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Dt]}],duration:[{duration:Y()}],ease:[{ease:["linear","in","out","in-out",Dt]}],delay:[{delay:Y()}],animate:[{animate:["none","spin","ping","pulse","bounce",Dt]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[E]}],"scale-x":[{"scale-x":[E]}],"scale-y":[{"scale-y":[E]}],rotate:[{rotate:[jh,Dt]}],"translate-x":[{"translate-x":[k]}],"translate-y":[{"translate-y":[k]}],"skew-x":[{"skew-x":[U]}],"skew-y":[{"skew-y":[U]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Dt]}],accent:[{accent:["auto",t]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Dt]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":z()}],"scroll-mx":[{"scroll-mx":z()}],"scroll-my":[{"scroll-my":z()}],"scroll-ms":[{"scroll-ms":z()}],"scroll-me":[{"scroll-me":z()}],"scroll-mt":[{"scroll-mt":z()}],"scroll-mr":[{"scroll-mr":z()}],"scroll-mb":[{"scroll-mb":z()}],"scroll-ml":[{"scroll-ml":z()}],"scroll-p":[{"scroll-p":z()}],"scroll-px":[{"scroll-px":z()}],"scroll-py":[{"scroll-py":z()}],"scroll-ps":[{"scroll-ps":z()}],"scroll-pe":[{"scroll-pe":z()}],"scroll-pt":[{"scroll-pt":z()}],"scroll-pr":[{"scroll-pr":z()}],"scroll-pb":[{"scroll-pb":z()}],"scroll-pl":[{"scroll-pl":z()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Dt]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[Pa,To,V_]}],stroke:[{stroke:[t,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},Mz=yz(Nz);function oi(...t){return Mz(E2(t))}const Bz=DH,N2=D.forwardRef(({className:t,...e},n)=>y.jsx(g2,{ref:n,className:oi("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",t),...e}));N2.displayName=g2.displayName;const Uz=OH("group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),M2=D.forwardRef(({className:t,variant:e,...n},r)=>y.jsx(y2,{ref:r,className:oi(Uz({variant:e}),t),...n}));M2.displayName=y2.displayName;const jz=D.forwardRef(({className:t,...e},n)=>y.jsx(b2,{ref:n,className:oi("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors group-[.destructive]:border-muted/40 hover:bg-secondary group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 group-[.destructive]:focus:ring-destructive disabled:pointer-events-none disabled:opacity-50",t),...e}));jz.displayName=b2.displayName;const B2=D.forwardRef(({className:t,...e},n)=>y.jsx(x2,{ref:n,className:oi("absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity group-hover:opacity-100 group-[.destructive]:text-red-300 hover:text-foreground group-[.destructive]:hover:text-red-50 focus:opacity-100 focus:outline-none focus:ring-2 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",t),"toast-close":"",...e,children:y.jsx(Sa,{className:"h-4 w-4"})}));B2.displayName=x2.displayName;const U2=D.forwardRef(({className:t,...e},n)=>y.jsx(v2,{ref:n,className:oi("text-sm font-semibold",t),...e}));U2.displayName=v2.displayName;const j2=D.forwardRef(({className:t,...e},n)=>y.jsx(_2,{ref:n,className:oi("text-sm opacity-90",t),...e}));j2.displayName=_2.displayName;function Fz(){const{toasts:t}=NG();return y.jsxs(Bz,{children:[t.map(function({id:e,title:n,description:r,action:i,...s}){return y.jsxs(M2,{...s,children:[y.jsxs("div",{className:"grid gap-1",children:[n&&y.jsx(U2,{children:n}),r&&y.jsx(j2,{children:r})]}),i,y.jsx(B2,{})]},e)}),y.jsx(N2,{})]})}var $z=cw[" useId ".trim().toString()]||(()=>{}),Vz=0;function G_(t){const[e,n]=D.useState($z());return lo(()=>{n(r=>r??String(Vz++))},[t]),t||(e?`radix-${e}`:"")}const Gz=["top","right","bottom","left"],xl=Math.min,Oi=Math.max,Yy=Math.round,Ym=Math.floor,da=t=>({x:t,y:t}),Hz={left:"right",right:"left",bottom:"top",top:"bottom"};function PS(t,e,n){return Oi(t,xl(e,n))}function co(t,e){return typeof t=="function"?t(e):t}function uo(t){return t.split("-")[0]}function mh(t){return t.split("-")[1]}function TT(t){return t==="x"?"y":"x"}function AT(t){return t==="y"?"height":"width"}function ra(t){const e=t[0];return e==="t"||e==="b"?"y":"x"}function RT(t){return TT(ra(t))}function Kz(t,e,n){n===void 0&&(n=!1);const r=mh(t),i=RT(t),s=AT(i);let a=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return e.reference[s]>e.floating[s]&&(a=Xy(a)),[a,Xy(a)]}function zz(t){const e=Xy(t);return[DS(t),e,DS(e)]}function DS(t){return t.includes("start")?t.replace("start","end"):t.replace("end","start")}const LC=["left","right"],kC=["right","left"],qz=["top","bottom"],Wz=["bottom","top"];function Yz(t,e,n){switch(t){case"top":case"bottom":return n?e?kC:LC:e?LC:kC;case"left":case"right":return e?qz:Wz;default:return[]}}function Xz(t,e,n,r){const i=mh(t);let s=Yz(uo(t),n==="start",r);return i&&(s=s.map(a=>a+"-"+i),e&&(s=s.concat(s.map(DS)))),s}function Xy(t){const e=uo(t);return Hz[e]+t.slice(e.length)}function Qz(t){return{top:0,right:0,bottom:0,left:0,...t}}function F2(t){return typeof t!="number"?Qz(t):{top:t,right:t,bottom:t,left:t}}function Qy(t){const{x:e,y:n,width:r,height:i}=t;return{width:r,height:i,top:n,left:e,right:e+r,bottom:n+i,x:e,y:n}}function IC(t,e,n){let{reference:r,floating:i}=t;const s=ra(e),a=RT(e),o=AT(a),l=uo(e),c=s==="y",u=r.x+r.width/2-i.width/2,d=r.y+r.height/2-i.height/2,h=r[o]/2-i[o]/2;let f;switch(l){case"top":f={x:u,y:r.y-i.height};break;case"bottom":f={x:u,y:r.y+r.height};break;case"right":f={x:r.x+r.width,y:d};break;case"left":f={x:r.x-i.width,y:d};break;default:f={x:r.x,y:r.y}}switch(mh(e)){case"start":f[a]-=h*(n&&c?-1:1);break;case"end":f[a]+=h*(n&&c?-1:1);break}return f}async function Jz(t,e){var n;e===void 0&&(e={});const{x:r,y:i,platform:s,rects:a,elements:o,strategy:l}=t,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:d="floating",altBoundary:h=!1,padding:f=0}=co(e,t),p=F2(f),g=o[h?d==="floating"?"reference":"floating":d],b=Qy(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(g)))==null||n?g:g.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(o.floating)),boundary:c,rootBoundary:u,strategy:l})),v=d==="floating"?{x:r,y:i,width:a.floating.width,height:a.floating.height}:a.reference,S=await(s.getOffsetParent==null?void 0:s.getOffsetParent(o.floating)),E=await(s.isElement==null?void 0:s.isElement(S))?await(s.getScale==null?void 0:s.getScale(S))||{x:1,y:1}:{x:1,y:1},L=Qy(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:v,offsetParent:S,strategy:l}):v);return{top:(b.top-L.top+p.top)/E.y,bottom:(L.bottom-b.bottom+p.bottom)/E.y,left:(b.left-L.left+p.left)/E.x,right:(L.right-b.right+p.right)/E.x}}const Zz=50,e9=async(t,e,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:s=[],platform:a}=n,o=a.detectOverflow?a:{...a,detectOverflow:Jz},l=await(a.isRTL==null?void 0:a.isRTL(e));let c=await a.getElementRects({reference:t,floating:e,strategy:i}),{x:u,y:d}=IC(c,r,l),h=r,f=0;const p={};for(let m=0;m<s.length;m++){const g=s[m];if(!g)continue;const{name:b,fn:v}=g,{x:S,y:E,data:L,reset:U}=await v({x:u,y:d,initialPlacement:r,placement:h,strategy:i,middlewareData:p,rects:c,platform:o,elements:{reference:t,floating:e}});u=S??u,d=E??d,p[b]={...p[b],...L},U&&f<Zz&&(f++,typeof U=="object"&&(U.placement&&(h=U.placement),U.rects&&(c=U.rects===!0?await a.getElementRects({reference:t,floating:e,strategy:i}):U.rects),{x:u,y:d}=IC(c,h,l)),m=-1)}return{x:u,y:d,placement:h,strategy:i,middlewareData:p}},t9=t=>({name:"arrow",options:t,async fn(e){const{x:n,y:r,placement:i,rects:s,platform:a,elements:o,middlewareData:l}=e,{element:c,padding:u=0}=co(t,e)||{};if(c==null)return{};const d=F2(u),h={x:n,y:r},f=RT(i),p=AT(f),m=await a.getDimensions(c),g=f==="y",b=g?"top":"left",v=g?"bottom":"right",S=g?"clientHeight":"clientWidth",E=s.reference[p]+s.reference[f]-h[f]-s.floating[p],L=h[f]-s.reference[f],U=await(a.getOffsetParent==null?void 0:a.getOffsetParent(c));let O=U?U[S]:0;(!O||!await(a.isElement==null?void 0:a.isElement(U)))&&(O=o.floating[S]||s.floating[p]);const k=E/2-L/2,I=O/2-m[p]/2-1,R=xl(d[b],I),M=xl(d[v],I),z=R,Z=O-m[p]-M,W=O/2-m[p]/2+k,re=PS(z,W,Z),X=!l.arrow&&mh(i)!=null&&W!==re&&s.reference[p]/2-(W<z?R:M)-m[p]/2<0,oe=X?W<z?W-z:W-Z:0;return{[f]:h[f]+oe,data:{[f]:re,centerOffset:W-re-oe,...X&&{alignmentOffset:oe}},reset:X}}}),n9=function(t){return t===void 0&&(t={}),{name:"flip",options:t,async fn(e){var n,r;const{placement:i,middlewareData:s,rects:a,initialPlacement:o,platform:l,elements:c}=e,{mainAxis:u=!0,crossAxis:d=!0,fallbackPlacements:h,fallbackStrategy:f="bestFit",fallbackAxisSideDirection:p="none",flipAlignment:m=!0,...g}=co(t,e);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const b=uo(i),v=ra(o),S=uo(o)===o,E=await(l.isRTL==null?void 0:l.isRTL(c.floating)),L=h||(S||!m?[Xy(o)]:zz(o)),U=p!=="none";!h&&U&&L.push(...Xz(o,m,p,E));const O=[o,...L],k=await l.detectOverflow(e,g),I=[];let R=((r=s.flip)==null?void 0:r.overflows)||[];if(u&&I.push(k[b]),d){const W=Kz(i,a,E);I.push(k[W[0]],k[W[1]])}if(R=[...R,{placement:i,overflows:I}],!I.every(W=>W<=0)){var M,z;const W=(((M=s.flip)==null?void 0:M.index)||0)+1,re=O[W];if(re&&(!(d==="alignment"?v!==ra(re):!1)||R.every(Q=>ra(Q.placement)===v?Q.overflows[0]>0:!0)))return{data:{index:W,overflows:R},reset:{placement:re}};let X=(z=R.filter(oe=>oe.overflows[0]<=0).sort((oe,Q)=>oe.overflows[1]-Q.overflows[1])[0])==null?void 0:z.placement;if(!X)switch(f){case"bestFit":{var Z;const oe=(Z=R.filter(Q=>{if(U){const G=ra(Q.placement);return G===v||G==="y"}return!0}).map(Q=>[Q.placement,Q.overflows.filter(G=>G>0).reduce((G,H)=>G+H,0)]).sort((Q,G)=>Q[1]-G[1])[0])==null?void 0:Z[0];oe&&(X=oe);break}case"initialPlacement":X=o;break}if(i!==X)return{reset:{placement:X}}}return{}}}};function PC(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function DC(t){return Gz.some(e=>t[e]>=0)}const r9=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(e){const{rects:n,platform:r}=e,{strategy:i="referenceHidden",...s}=co(t,e);switch(i){case"referenceHidden":{const a=await r.detectOverflow(e,{...s,elementContext:"reference"}),o=PC(a,n.reference);return{data:{referenceHiddenOffsets:o,referenceHidden:DC(o)}}}case"escaped":{const a=await r.detectOverflow(e,{...s,altBoundary:!0}),o=PC(a,n.floating);return{data:{escapedOffsets:o,escaped:DC(o)}}}default:return{}}}}},$2=new Set(["left","top"]);async function i9(t,e){const{placement:n,platform:r,elements:i}=t,s=await(r.isRTL==null?void 0:r.isRTL(i.floating)),a=uo(n),o=mh(n),l=ra(n)==="y",c=$2.has(a)?-1:1,u=s&&l?-1:1,d=co(e,t);let{mainAxis:h,crossAxis:f,alignmentAxis:p}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return o&&typeof p=="number"&&(f=o==="end"?p*-1:p),l?{x:f*u,y:h*c}:{x:h*c,y:f*u}}const s9=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(e){var n,r;const{x:i,y:s,placement:a,middlewareData:o}=e,l=await i9(e,t);return a===((n=o.offset)==null?void 0:n.placement)&&(r=o.arrow)!=null&&r.alignmentOffset?{}:{x:i+l.x,y:s+l.y,data:{...l,placement:a}}}}},a9=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(e){const{x:n,y:r,placement:i,platform:s}=e,{mainAxis:a=!0,crossAxis:o=!1,limiter:l={fn:b=>{let{x:v,y:S}=b;return{x:v,y:S}}},...c}=co(t,e),u={x:n,y:r},d=await s.detectOverflow(e,c),h=ra(uo(i)),f=TT(h);let p=u[f],m=u[h];if(a){const b=f==="y"?"top":"left",v=f==="y"?"bottom":"right",S=p+d[b],E=p-d[v];p=PS(S,p,E)}if(o){const b=h==="y"?"top":"left",v=h==="y"?"bottom":"right",S=m+d[b],E=m-d[v];m=PS(S,m,E)}const g=l.fn({...e,[f]:p,[h]:m});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[f]:a,[h]:o}}}}}},o9=function(t){return t===void 0&&(t={}),{options:t,fn(e){const{x:n,y:r,placement:i,rects:s,middlewareData:a}=e,{offset:o=0,mainAxis:l=!0,crossAxis:c=!0}=co(t,e),u={x:n,y:r},d=ra(i),h=TT(d);let f=u[h],p=u[d];const m=co(o,e),g=typeof m=="number"?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(l){const S=h==="y"?"height":"width",E=s.reference[h]-s.floating[S]+g.mainAxis,L=s.reference[h]+s.reference[S]-g.mainAxis;f<E?f=E:f>L&&(f=L)}if(c){var b,v;const S=h==="y"?"width":"height",E=$2.has(uo(i)),L=s.reference[d]-s.floating[S]+(E&&((b=a.offset)==null?void 0:b[d])||0)+(E?0:g.crossAxis),U=s.reference[d]+s.reference[S]+(E?0:((v=a.offset)==null?void 0:v[d])||0)-(E?g.crossAxis:0);p<L?p=L:p>U&&(p=U)}return{[h]:f,[d]:p}}}},l9=function(t){return t===void 0&&(t={}),{name:"size",options:t,async fn(e){var n,r;const{placement:i,rects:s,platform:a,elements:o}=e,{apply:l=()=>{},...c}=co(t,e),u=await a.detectOverflow(e,c),d=uo(i),h=mh(i),f=ra(i)==="y",{width:p,height:m}=s.floating;let g,b;d==="top"||d==="bottom"?(g=d,b=h===(await(a.isRTL==null?void 0:a.isRTL(o.floating))?"start":"end")?"left":"right"):(b=d,g=h==="end"?"top":"bottom");const v=m-u.top-u.bottom,S=p-u.left-u.right,E=xl(m-u[g],v),L=xl(p-u[b],S),U=!e.middlewareData.shift;let O=E,k=L;if((n=e.middlewareData.shift)!=null&&n.enabled.x&&(k=S),(r=e.middlewareData.shift)!=null&&r.enabled.y&&(O=v),U&&!h){const R=Oi(u.left,0),M=Oi(u.right,0),z=Oi(u.top,0),Z=Oi(u.bottom,0);f?k=p-2*(R!==0||M!==0?R+M:Oi(u.left,u.right)):O=m-2*(z!==0||Z!==0?z+Z:Oi(u.top,u.bottom))}await l({...e,availableWidth:k,availableHeight:O});const I=await a.getDimensions(o.floating);return p!==I.width||m!==I.height?{reset:{rects:!0}}:{}}}};function iv(){return typeof window<"u"}function gh(t){return V2(t)?(t.nodeName||"").toLowerCase():"#document"}function Gi(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function Ea(t){var e;return(e=(V2(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function V2(t){return iv()?t instanceof Node||t instanceof Gi(t).Node:!1}function Ds(t){return iv()?t instanceof Element||t instanceof Gi(t).Element:!1}function po(t){return iv()?t instanceof HTMLElement||t instanceof Gi(t).HTMLElement:!1}function OC(t){return!iv()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof Gi(t).ShadowRoot}function rm(t){const{overflow:e,overflowX:n,overflowY:r,display:i}=Os(t);return/auto|scroll|overlay|hidden|clip/.test(e+r+n)&&i!=="inline"&&i!=="contents"}function c9(t){return/^(table|td|th)$/.test(gh(t))}function sv(t){try{if(t.matches(":popover-open"))return!0}catch{}try{return t.matches(":modal")}catch{return!1}}const u9=/transform|translate|scale|rotate|perspective|filter/,d9=/paint|layout|strict|content/,Vl=t=>!!t&&t!=="none";let H_;function CT(t){const e=Ds(t)?Os(t):t;return Vl(e.transform)||Vl(e.translate)||Vl(e.scale)||Vl(e.rotate)||Vl(e.perspective)||!LT()&&(Vl(e.backdropFilter)||Vl(e.filter))||u9.test(e.willChange||"")||d9.test(e.contain||"")}function h9(t){let e=Sl(t);for(;po(e)&&!zd(e);){if(CT(e))return e;if(sv(e))return null;e=Sl(e)}return null}function LT(){return H_==null&&(H_=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),H_}function zd(t){return/^(html|body|#document)$/.test(gh(t))}function Os(t){return Gi(t).getComputedStyle(t)}function av(t){return Ds(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function Sl(t){if(gh(t)==="html")return t;const e=t.assignedSlot||t.parentNode||OC(t)&&t.host||Ea(t);return OC(e)?e.host:e}function G2(t){const e=Sl(t);return zd(e)?t.ownerDocument?t.ownerDocument.body:t.body:po(e)&&rm(e)?e:G2(e)}function op(t,e,n){var r;e===void 0&&(e=[]),n===void 0&&(n=!0);const i=G2(t),s=i===((r=t.ownerDocument)==null?void 0:r.body),a=Gi(i);if(s){const o=OS(a);return e.concat(a,a.visualViewport||[],rm(i)?i:[],o&&n?op(o):[])}else return e.concat(i,op(i,[],n))}function OS(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function H2(t){const e=Os(t);let n=parseFloat(e.width)||0,r=parseFloat(e.height)||0;const i=po(t),s=i?t.offsetWidth:n,a=i?t.offsetHeight:r,o=Yy(n)!==s||Yy(r)!==a;return o&&(n=s,r=a),{width:n,height:r,$:o}}function kT(t){return Ds(t)?t:t.contextElement}function pd(t){const e=kT(t);if(!po(e))return da(1);const n=e.getBoundingClientRect(),{width:r,height:i,$:s}=H2(e);let a=(s?Yy(n.width):n.width)/r,o=(s?Yy(n.height):n.height)/i;return(!a||!Number.isFinite(a))&&(a=1),(!o||!Number.isFinite(o))&&(o=1),{x:a,y:o}}const f9=da(0);function K2(t){const e=Gi(t);return!LT()||!e.visualViewport?f9:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function p9(t,e,n){return e===void 0&&(e=!1),!n||e&&n!==Gi(t)?!1:e}function Mc(t,e,n,r){e===void 0&&(e=!1),n===void 0&&(n=!1);const i=t.getBoundingClientRect(),s=kT(t);let a=da(1);e&&(r?Ds(r)&&(a=pd(r)):a=pd(t));const o=p9(s,n,r)?K2(s):da(0);let l=(i.left+o.x)/a.x,c=(i.top+o.y)/a.y,u=i.width/a.x,d=i.height/a.y;if(s){const h=Gi(s),f=r&&Ds(r)?Gi(r):r;let p=h,m=OS(p);for(;m&&r&&f!==p;){const g=pd(m),b=m.getBoundingClientRect(),v=Os(m),S=b.left+(m.clientLeft+parseFloat(v.paddingLeft))*g.x,E=b.top+(m.clientTop+parseFloat(v.paddingTop))*g.y;l*=g.x,c*=g.y,u*=g.x,d*=g.y,l+=S,c+=E,p=Gi(m),m=OS(p)}}return Qy({width:u,height:d,x:l,y:c})}function ov(t,e){const n=av(t).scrollLeft;return e?e.left+n:Mc(Ea(t)).left+n}function z2(t,e){const n=t.getBoundingClientRect(),r=n.left+e.scrollLeft-ov(t,n),i=n.top+e.scrollTop;return{x:r,y:i}}function m9(t){let{elements:e,rect:n,offsetParent:r,strategy:i}=t;const s=i==="fixed",a=Ea(r),o=e?sv(e.floating):!1;if(r===a||o&&s)return n;let l={scrollLeft:0,scrollTop:0},c=da(1);const u=da(0),d=po(r);if((d||!d&&!s)&&((gh(r)!=="body"||rm(a))&&(l=av(r)),d)){const f=Mc(r);c=pd(r),u.x=f.x+r.clientLeft,u.y=f.y+r.clientTop}const h=a&&!d&&!s?z2(a,l):da(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+u.x+h.x,y:n.y*c.y-l.scrollTop*c.y+u.y+h.y}}function g9(t){return Array.from(t.getClientRects())}function y9(t){const e=Ea(t),n=av(t),r=t.ownerDocument.body,i=Oi(e.scrollWidth,e.clientWidth,r.scrollWidth,r.clientWidth),s=Oi(e.scrollHeight,e.clientHeight,r.scrollHeight,r.clientHeight);let a=-n.scrollLeft+ov(t);const o=-n.scrollTop;return Os(r).direction==="rtl"&&(a+=Oi(e.clientWidth,r.clientWidth)-i),{width:i,height:s,x:a,y:o}}const NC=25;function v9(t,e){const n=Gi(t),r=Ea(t),i=n.visualViewport;let s=r.clientWidth,a=r.clientHeight,o=0,l=0;if(i){s=i.width,a=i.height;const u=LT();(!u||u&&e==="fixed")&&(o=i.offsetLeft,l=i.offsetTop)}const c=ov(r);if(c<=0){const u=r.ownerDocument,d=u.body,h=getComputedStyle(d),f=u.compatMode==="CSS1Compat"&&parseFloat(h.marginLeft)+parseFloat(h.marginRight)||0,p=Math.abs(r.clientWidth-d.clientWidth-f);p<=NC&&(s-=p)}else c<=NC&&(s+=c);return{width:s,height:a,x:o,y:l}}function _9(t,e){const n=Mc(t,!0,e==="fixed"),r=n.top+t.clientTop,i=n.left+t.clientLeft,s=po(t)?pd(t):da(1),a=t.clientWidth*s.x,o=t.clientHeight*s.y,l=i*s.x,c=r*s.y;return{width:a,height:o,x:l,y:c}}function MC(t,e,n){let r;if(e==="viewport")r=v9(t,n);else if(e==="document")r=y9(Ea(t));else if(Ds(e))r=_9(e,n);else{const i=K2(t);r={x:e.x-i.x,y:e.y-i.y,width:e.width,height:e.height}}return Qy(r)}function q2(t,e){const n=Sl(t);return n===e||!Ds(n)||zd(n)?!1:Os(n).position==="fixed"||q2(n,e)}function b9(t,e){const n=e.get(t);if(n)return n;let r=op(t,[],!1).filter(o=>Ds(o)&&gh(o)!=="body"),i=null;const s=Os(t).position==="fixed";let a=s?Sl(t):t;for(;Ds(a)&&!zd(a);){const o=Os(a),l=CT(a);!l&&o.position==="fixed"&&(i=null),(s?!l&&!i:!l&&o.position==="static"&&!!i&&(i.position==="absolute"||i.position==="fixed")||rm(a)&&!l&&q2(t,a))?r=r.filter(u=>u!==a):i=o,a=Sl(a)}return e.set(t,r),r}function x9(t){let{element:e,boundary:n,rootBoundary:r,strategy:i}=t;const a=[...n==="clippingAncestors"?sv(e)?[]:b9(e,this._c):[].concat(n),r],o=MC(e,a[0],i);let l=o.top,c=o.right,u=o.bottom,d=o.left;for(let h=1;h<a.length;h++){const f=MC(e,a[h],i);l=Oi(f.top,l),c=xl(f.right,c),u=xl(f.bottom,u),d=Oi(f.left,d)}return{width:c-d,height:u-l,x:d,y:l}}function S9(t){const{width:e,height:n}=H2(t);return{width:e,height:n}}function E9(t,e,n){const r=po(e),i=Ea(e),s=n==="fixed",a=Mc(t,!0,s,e);let o={scrollLeft:0,scrollTop:0};const l=da(0);function c(){l.x=ov(i)}if(r||!r&&!s)if((gh(e)!=="body"||rm(i))&&(o=av(e)),r){const f=Mc(e,!0,s,e);l.x=f.x+e.clientLeft,l.y=f.y+e.clientTop}else i&&c();s&&!r&&i&&c();const u=i&&!r&&!s?z2(i,o):da(0),d=a.left+o.scrollLeft-l.x-u.x,h=a.top+o.scrollTop-l.y-u.y;return{x:d,y:h,width:a.width,height:a.height}}function K_(t){return Os(t).position==="static"}function BC(t,e){if(!po(t)||Os(t).position==="fixed")return null;if(e)return e(t);let n=t.offsetParent;return Ea(t)===n&&(n=n.ownerDocument.body),n}function W2(t,e){const n=Gi(t);if(sv(t))return n;if(!po(t)){let i=Sl(t);for(;i&&!zd(i);){if(Ds(i)&&!K_(i))return i;i=Sl(i)}return n}let r=BC(t,e);for(;r&&c9(r)&&K_(r);)r=BC(r,e);return r&&zd(r)&&K_(r)&&!CT(r)?n:r||h9(t)||n}const w9=async function(t){const e=this.getOffsetParent||W2,n=this.getDimensions,r=await n(t.floating);return{reference:E9(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function T9(t){return Os(t).direction==="rtl"}const A9={convertOffsetParentRelativeRectToViewportRelativeRect:m9,getDocumentElement:Ea,getClippingRect:x9,getOffsetParent:W2,getElementRects:w9,getClientRects:g9,getDimensions:S9,getScale:pd,isElement:Ds,isRTL:T9};function Y2(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}function R9(t,e){let n=null,r;const i=Ea(t);function s(){var o;clearTimeout(r),(o=n)==null||o.disconnect(),n=null}function a(o,l){o===void 0&&(o=!1),l===void 0&&(l=1),s();const c=t.getBoundingClientRect(),{left:u,top:d,width:h,height:f}=c;if(o||e(),!h||!f)return;const p=Ym(d),m=Ym(i.clientWidth-(u+h)),g=Ym(i.clientHeight-(d+f)),b=Ym(u),S={rootMargin:-p+"px "+-m+"px "+-g+"px "+-b+"px",threshold:Oi(0,xl(1,l))||1};let E=!0;function L(U){const O=U[0].intersectionRatio;if(O!==l){if(!E)return a();O?a(!1,O):r=setTimeout(()=>{a(!1,1e-7)},1e3)}O===1&&!Y2(c,t.getBoundingClientRect())&&a(),E=!1}try{n=new IntersectionObserver(L,{...S,root:i.ownerDocument})}catch{n=new IntersectionObserver(L,S)}n.observe(t)}return a(!0),s}function C9(t,e,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:s=!0,elementResize:a=typeof ResizeObserver=="function",layoutShift:o=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,c=kT(t),u=i||s?[...c?op(c):[],...e?op(e):[]]:[];u.forEach(b=>{i&&b.addEventListener("scroll",n,{passive:!0}),s&&b.addEventListener("resize",n)});const d=c&&o?R9(c,n):null;let h=-1,f=null;a&&(f=new ResizeObserver(b=>{let[v]=b;v&&v.target===c&&f&&e&&(f.unobserve(e),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var S;(S=f)==null||S.observe(e)})),n()}),c&&!l&&f.observe(c),e&&f.observe(e));let p,m=l?Mc(t):null;l&&g();function g(){const b=Mc(t);m&&!Y2(m,b)&&n(),m=b,p=requestAnimationFrame(g)}return n(),()=>{var b;u.forEach(v=>{i&&v.removeEventListener("scroll",n),s&&v.removeEventListener("resize",n)}),d==null||d(),(b=f)==null||b.disconnect(),f=null,l&&cancelAnimationFrame(p)}}const L9=s9,k9=a9,I9=n9,P9=l9,D9=r9,UC=t9,O9=o9,N9=(t,e,n)=>{const r=new Map,i={platform:A9,...n},s={...i.platform,_c:r};return e9(t,e,{...i,platform:s})};var M9=typeof document<"u",B9=function(){},Wg=M9?D.useLayoutEffect:B9;function Jy(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(typeof t=="function"&&t.toString()===e.toString())return!0;let n,r,i;if(t&&e&&typeof t=="object"){if(Array.isArray(t)){if(n=t.length,n!==e.length)return!1;for(r=n;r--!==0;)if(!Jy(t[r],e[r]))return!1;return!0}if(i=Object.keys(t),n=i.length,n!==Object.keys(e).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(e,i[r]))return!1;for(r=n;r--!==0;){const s=i[r];if(!(s==="_owner"&&t.$$typeof)&&!Jy(t[s],e[s]))return!1}return!0}return t!==t&&e!==e}function X2(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function jC(t,e){const n=X2(t);return Math.round(e*n)/n}function z_(t){const e=D.useRef(t);return Wg(()=>{e.current=t}),e}function U9(t){t===void 0&&(t={});const{placement:e="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:s,floating:a}={},transform:o=!0,whileElementsMounted:l,open:c}=t,[u,d]=D.useState({x:0,y:0,strategy:n,placement:e,middlewareData:{},isPositioned:!1}),[h,f]=D.useState(r);Jy(h,r)||f(r);const[p,m]=D.useState(null),[g,b]=D.useState(null),v=D.useCallback(Q=>{Q!==U.current&&(U.current=Q,m(Q))},[]),S=D.useCallback(Q=>{Q!==O.current&&(O.current=Q,b(Q))},[]),E=s||p,L=a||g,U=D.useRef(null),O=D.useRef(null),k=D.useRef(u),I=l!=null,R=z_(l),M=z_(i),z=z_(c),Z=D.useCallback(()=>{if(!U.current||!O.current)return;const Q={placement:e,strategy:n,middleware:h};M.current&&(Q.platform=M.current),N9(U.current,O.current,Q).then(G=>{const H={...G,isPositioned:z.current!==!1};W.current&&!Jy(k.current,H)&&(k.current=H,Np.flushSync(()=>{d(H)}))})},[h,e,n,M,z]);Wg(()=>{c===!1&&k.current.isPositioned&&(k.current.isPositioned=!1,d(Q=>({...Q,isPositioned:!1})))},[c]);const W=D.useRef(!1);Wg(()=>(W.current=!0,()=>{W.current=!1}),[]),Wg(()=>{if(E&&(U.current=E),L&&(O.current=L),E&&L){if(R.current)return R.current(E,L,Z);Z()}},[E,L,Z,R,I]);const re=D.useMemo(()=>({reference:U,floating:O,setReference:v,setFloating:S}),[v,S]),X=D.useMemo(()=>({reference:E,floating:L}),[E,L]),oe=D.useMemo(()=>{const Q={position:n,left:0,top:0};if(!X.floating)return Q;const G=jC(X.floating,u.x),H=jC(X.floating,u.y);return o?{...Q,transform:"translate("+G+"px, "+H+"px)",...X2(X.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:G,top:H}},[n,o,X.floating,u.x,u.y]);return D.useMemo(()=>({...u,update:Z,refs:re,elements:X,floatingStyles:oe}),[u,Z,re,X,oe])}const j9=t=>{function e(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:t,fn(n){const{element:r,padding:i}=typeof t=="function"?t(n):t;return r&&e(r)?r.current!=null?UC({element:r.current,padding:i}).fn(n):{}:r?UC({element:r,padding:i}).fn(n):{}}}},F9=(t,e)=>{const n=L9(t);return{name:n.name,fn:n.fn,options:[t,e]}},$9=(t,e)=>{const n=k9(t);return{name:n.name,fn:n.fn,options:[t,e]}},V9=(t,e)=>({fn:O9(t).fn,options:[t,e]}),G9=(t,e)=>{const n=I9(t);return{name:n.name,fn:n.fn,options:[t,e]}},H9=(t,e)=>{const n=P9(t);return{name:n.name,fn:n.fn,options:[t,e]}},K9=(t,e)=>{const n=D9(t);return{name:n.name,fn:n.fn,options:[t,e]}},z9=(t,e)=>{const n=j9(t);return{name:n.name,fn:n.fn,options:[t,e]}};var q9="Arrow",Q2=D.forwardRef((t,e)=>{const{children:n,width:r=10,height:i=5,...s}=t;return y.jsx(ar.svg,{...s,ref:e,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:t.asChild?n:y.jsx("polygon",{points:"0,0 30,0 15,10"})})});Q2.displayName=q9;var W9=Q2;function Y9(t){const[e,n]=D.useState(void 0);return lo(()=>{if(t){n({width:t.offsetWidth,height:t.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const s=i[0];let a,o;if("borderBoxSize"in s){const l=s.borderBoxSize,c=Array.isArray(l)?l[0]:l;a=c.inlineSize,o=c.blockSize}else a=t.offsetWidth,o=t.offsetHeight;n({width:a,height:o})});return r.observe(t,{box:"border-box"}),()=>r.unobserve(t)}else n(void 0)},[t]),e}var J2="Popper",[Z2,eB]=Zp(J2),[ppe,tB]=Z2(J2),nB="PopperAnchor",rB=D.forwardRef((t,e)=>{const{__scopePopper:n,virtualRef:r,...i}=t,s=tB(nB,n),a=D.useRef(null),o=si(e,a),l=D.useRef(null);return D.useEffect(()=>{const c=l.current;l.current=(r==null?void 0:r.current)||a.current,c!==l.current&&s.onAnchorChange(l.current)}),r?null:y.jsx(ar.div,{...i,ref:o})});rB.displayName=nB;var IT="PopperContent",[X9,Q9]=Z2(IT),iB=D.forwardRef((t,e)=>{var ye,Ie,Ae,Ee,je,Me;const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:s="center",alignOffset:a=0,arrowPadding:o=0,avoidCollisions:l=!0,collisionBoundary:c=[],collisionPadding:u=0,sticky:d="partial",hideWhenDetached:h=!1,updatePositionStrategy:f="optimized",onPlaced:p,...m}=t,g=tB(IT,n),[b,v]=D.useState(null),S=si(e,Pt=>v(Pt)),[E,L]=D.useState(null),U=Y9(E),O=(U==null?void 0:U.width)??0,k=(U==null?void 0:U.height)??0,I=r+(s!=="center"?"-"+s:""),R=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},M=Array.isArray(c)?c:[c],z=M.length>0,Z={padding:R,boundary:M.filter(Z9),altBoundary:z},{refs:W,floatingStyles:re,placement:X,isPositioned:oe,middlewareData:Q}=U9({strategy:"fixed",placement:I,whileElementsMounted:(...Pt)=>C9(...Pt,{animationFrame:f==="always"}),elements:{reference:g.anchor},middleware:[F9({mainAxis:i+k,alignmentAxis:a}),l&&$9({mainAxis:!0,crossAxis:!1,limiter:d==="partial"?V9():void 0,...Z}),l&&G9({...Z}),H9({...Z,apply:({elements:Pt,rects:tn,availableWidth:Dn,availableHeight:lt})=>{const{width:un,height:Sn}=tn.reference,tr=Pt.floating.style;tr.setProperty("--radix-popper-available-width",`${Dn}px`),tr.setProperty("--radix-popper-available-height",`${lt}px`),tr.setProperty("--radix-popper-anchor-width",`${un}px`),tr.setProperty("--radix-popper-anchor-height",`${Sn}px`)}}),E&&z9({element:E,padding:o}),eq({arrowWidth:O,arrowHeight:k}),h&&K9({strategy:"referenceHidden",...Z})]}),[G,H]=oB(X),Y=fa(p);lo(()=>{oe&&(Y==null||Y())},[oe,Y]);const ie=(ye=Q.arrow)==null?void 0:ye.x,Ce=(Ie=Q.arrow)==null?void 0:Ie.y,Le=((Ae=Q.arrow)==null?void 0:Ae.centerOffset)!==0,[ke,Ne]=D.useState();return lo(()=>{b&&Ne(window.getComputedStyle(b).zIndex)},[b]),y.jsx("div",{ref:W.setFloating,"data-radix-popper-content-wrapper":"",style:{...re,transform:oe?re.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ke,"--radix-popper-transform-origin":[(Ee=Q.transformOrigin)==null?void 0:Ee.x,(je=Q.transformOrigin)==null?void 0:je.y].join(" "),...((Me=Q.hide)==null?void 0:Me.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:y.jsx(X9,{scope:n,placedSide:G,onArrowChange:L,arrowX:ie,arrowY:Ce,shouldHideArrow:Le,children:y.jsx(ar.div,{"data-side":G,"data-align":H,...m,ref:S,style:{...m.style,animation:oe?void 0:"none"}})})})});iB.displayName=IT;var sB="PopperArrow",J9={top:"bottom",right:"left",bottom:"top",left:"right"},aB=D.forwardRef(function(e,n){const{__scopePopper:r,...i}=e,s=Q9(sB,r),a=J9[s.placedSide];return y.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[a]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:y.jsx(W9,{...i,ref:n,style:{...i.style,display:"block"}})})});aB.displayName=sB;function Z9(t){return t!==null}var eq=t=>({name:"transformOrigin",options:t,fn(e){var g,b,v;const{placement:n,rects:r,middlewareData:i}=e,a=((g=i.arrow)==null?void 0:g.centerOffset)!==0,o=a?0:t.arrowWidth,l=a?0:t.arrowHeight,[c,u]=oB(n),d={start:"0%",center:"50%",end:"100%"}[u],h=(((b=i.arrow)==null?void 0:b.x)??0)+o/2,f=(((v=i.arrow)==null?void 0:v.y)??0)+l/2;let p="",m="";return c==="bottom"?(p=a?d:`${h}px`,m=`${-l}px`):c==="top"?(p=a?d:`${h}px`,m=`${r.floating.height+l}px`):c==="right"?(p=`${-l}px`,m=a?d:`${f}px`):c==="left"&&(p=`${r.floating.width+l}px`,m=a?d:`${f}px`),{data:{x:p,y:m}}}});function oB(t){const[e,n="center"]=t.split("-");return[e,n]}var tq=rB,nq=iB,rq=aB,iq=Symbol("radix.slottable");function sq(t){const e=({children:n})=>y.jsx(y.Fragment,{children:n});return e.displayName=`${t}.Slottable`,e.__radixId=iq,e}var[lv]=Zp("Tooltip",[eB]),PT=eB(),lB="TooltipProvider",aq=700,FC="tooltip.open",[oq,cB]=lv(lB),uB=t=>{const{__scopeTooltip:e,delayDuration:n=aq,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:s}=t,a=D.useRef(!0),o=D.useRef(!1),l=D.useRef(0);return D.useEffect(()=>{const c=l.current;return()=>window.clearTimeout(c)},[]),y.jsx(oq,{scope:e,isOpenDelayedRef:a,delayDuration:n,onOpen:D.useCallback(()=>{window.clearTimeout(l.current),a.current=!1},[]),onClose:D.useCallback(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>a.current=!0,r)},[r]),isPointerInTransitRef:o,onPointerInTransitChange:D.useCallback(c=>{o.current=c},[]),disableHoverableContent:i,children:s})};uB.displayName=lB;var dB="Tooltip",[mpe,cv]=lv(dB),NS="TooltipTrigger",lq=D.forwardRef((t,e)=>{const{__scopeTooltip:n,...r}=t,i=cv(NS,n),s=cB(NS,n),a=PT(n),o=D.useRef(null),l=si(e,o,i.onTriggerChange),c=D.useRef(!1),u=D.useRef(!1),d=D.useCallback(()=>c.current=!1,[]);return D.useEffect(()=>()=>document.removeEventListener("pointerup",d),[d]),y.jsx(tq,{asChild:!0,...a,children:y.jsx(ar.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:l,onPointerMove:kn(t.onPointerMove,h=>{h.pointerType!=="touch"&&!u.current&&!s.isPointerInTransitRef.current&&(i.onTriggerEnter(),u.current=!0)}),onPointerLeave:kn(t.onPointerLeave,()=>{i.onTriggerLeave(),u.current=!1}),onPointerDown:kn(t.onPointerDown,()=>{i.open&&i.onClose(),c.current=!0,document.addEventListener("pointerup",d,{once:!0})}),onFocus:kn(t.onFocus,()=>{c.current||i.onOpen()}),onBlur:kn(t.onBlur,i.onClose),onClick:kn(t.onClick,i.onClose)})})});lq.displayName=NS;var cq="TooltipPortal",[gpe,uq]=lv(cq,{forceMount:void 0}),qd="TooltipContent",hB=D.forwardRef((t,e)=>{const n=uq(qd,t.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...s}=t,a=cv(qd,t.__scopeTooltip);return y.jsx(fh,{present:r||a.open,children:a.disableHoverableContent?y.jsx(fB,{side:i,...s,ref:e}):y.jsx(dq,{side:i,...s,ref:e})})}),dq=D.forwardRef((t,e)=>{const n=cv(qd,t.__scopeTooltip),r=cB(qd,t.__scopeTooltip),i=D.useRef(null),s=si(e,i),[a,o]=D.useState(null),{trigger:l,onClose:c}=n,u=i.current,{onPointerInTransitChange:d}=r,h=D.useCallback(()=>{o(null),d(!1)},[d]),f=D.useCallback((p,m)=>{const g=p.currentTarget,b={x:p.clientX,y:p.clientY},v=gq(b,g.getBoundingClientRect()),S=yq(b,v),E=vq(m.getBoundingClientRect()),L=bq([...S,...E]);o(L),d(!0)},[d]);return D.useEffect(()=>()=>h(),[h]),D.useEffect(()=>{if(l&&u){const p=g=>f(g,u),m=g=>f(g,l);return l.addEventListener("pointerleave",p),u.addEventListener("pointerleave",m),()=>{l.removeEventListener("pointerleave",p),u.removeEventListener("pointerleave",m)}}},[l,u,f,h]),D.useEffect(()=>{if(a){const p=m=>{const g=m.target,b={x:m.clientX,y:m.clientY},v=(l==null?void 0:l.contains(g))||(u==null?void 0:u.contains(g)),S=!_q(b,a);v?h():S&&(h(),c())};return document.addEventListener("pointermove",p),()=>document.removeEventListener("pointermove",p)}},[l,u,a,c,h]),y.jsx(fB,{...t,ref:s})}),[hq,fq]=lv(dB,{isInside:!1}),pq=sq("TooltipContent"),fB=D.forwardRef((t,e)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:s,onPointerDownOutside:a,...o}=t,l=cv(qd,n),c=PT(n),{onClose:u}=l;return D.useEffect(()=>(document.addEventListener(FC,u),()=>document.removeEventListener(FC,u)),[u]),D.useEffect(()=>{if(l.trigger){const d=h=>{const f=h.target;f!=null&&f.contains(l.trigger)&&u()};return window.addEventListener("scroll",d,{capture:!0}),()=>window.removeEventListener("scroll",d,{capture:!0})}},[l.trigger,u]),y.jsx(Q0,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:s,onPointerDownOutside:a,onFocusOutside:d=>d.preventDefault(),onDismiss:u,children:y.jsxs(nq,{"data-state":l.stateAttribute,...c,...o,ref:e,style:{...o.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[y.jsx(pq,{children:r}),y.jsx(hq,{scope:n,isInside:!0,children:y.jsx(mH,{id:l.contentId,role:"tooltip",children:i||r})})]})})});hB.displayName=qd;var pB="TooltipArrow",mq=D.forwardRef((t,e)=>{const{__scopeTooltip:n,...r}=t,i=PT(n);return fq(pB,n).isInside?null:y.jsx(rq,{...i,...r,ref:e})});mq.displayName=pB;function gq(t,e){const n=Math.abs(e.top-t.y),r=Math.abs(e.bottom-t.y),i=Math.abs(e.right-t.x),s=Math.abs(e.left-t.x);switch(Math.min(n,r,i,s)){case s:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function yq(t,e,n=5){const r=[];switch(e){case"top":r.push({x:t.x-n,y:t.y+n},{x:t.x+n,y:t.y+n});break;case"bottom":r.push({x:t.x-n,y:t.y-n},{x:t.x+n,y:t.y-n});break;case"left":r.push({x:t.x+n,y:t.y-n},{x:t.x+n,y:t.y+n});break;case"right":r.push({x:t.x-n,y:t.y-n},{x:t.x-n,y:t.y+n});break}return r}function vq(t){const{top:e,right:n,bottom:r,left:i}=t;return[{x:i,y:e},{x:n,y:e},{x:n,y:r},{x:i,y:r}]}function _q(t,e){const{x:n,y:r}=t;let i=!1;for(let s=0,a=e.length-1;s<e.length;a=s++){const o=e[s],l=e[a],c=o.x,u=o.y,d=l.x,h=l.y;u>r!=h>r&&n<(d-c)*(r-u)/(h-u)+c&&(i=!i)}return i}function bq(t){const e=t.slice();return e.sort((n,r)=>n.x<r.x?-1:n.x>r.x?1:n.y<r.y?-1:n.y>r.y?1:0),xq(e)}function xq(t){if(t.length<=1)return t.slice();const e=[];for(let r=0;r<t.length;r++){const i=t[r];for(;e.length>=2;){const s=e[e.length-1],a=e[e.length-2];if((s.x-a.x)*(i.y-a.y)>=(s.y-a.y)*(i.x-a.x))e.pop();else break}e.push(i)}e.pop();const n=[];for(let r=t.length-1;r>=0;r--){const i=t[r];for(;n.length>=2;){const s=n[n.length-1],a=n[n.length-2];if((s.x-a.x)*(i.y-a.y)>=(s.y-a.y)*(i.x-a.x))n.pop();else break}n.push(i)}return n.pop(),e.length===1&&n.length===1&&e[0].x===n[0].x&&e[0].y===n[0].y?e:e.concat(n)}var Sq=uB,mB=hB;const Eq=Sq,wq=D.forwardRef(({className:t,sideOffset:e=4,...n},r)=>y.jsx(mB,{ref:r,sideOffset:e,className:oi("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...n}));wq.displayName=mB.displayName;const DT=D.createContext({});function OT(t){const e=D.useRef(null);return e.current===null&&(e.current=t()),e.current}const Tq=typeof window<"u",gB=Tq?D.useLayoutEffect:D.useEffect,uv=D.createContext(null);function NT(t,e){t.indexOf(e)===-1&&t.push(e)}function Zy(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const pa=(t,e,n)=>n>e?e:n<t?t:n;let MT=()=>{};const El={},yB=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function vB(t){return typeof t=="object"&&t!==null}const _B=t=>/^0[^.\s]+$/u.test(t);function bB(t){let e;return()=>(e===void 0&&(e=t()),e)}const fs=t=>t,Aq=(t,e)=>n=>e(t(n)),im=(...t)=>t.reduce(Aq),lp=(t,e,n)=>{const r=e-t;return r===0?1:(n-t)/r};class BT{constructor(){this.subscriptions=[]}add(e){return NT(this.subscriptions,e),()=>Zy(this.subscriptions,e)}notify(e,n,r){const i=this.subscriptions.length;if(i)if(i===1)this.subscriptions[0](e,n,r);else for(let s=0;s<i;s++){const a=this.subscriptions[s];a&&a(e,n,r)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const Hi=t=>t*1e3,hs=t=>t/1e3;function xB(t,e){return e?t*(1e3/e):0}const SB=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t,Rq=1e-7,Cq=12;function Lq(t,e,n,r,i){let s,a,o=0;do a=e+(n-e)/2,s=SB(a,r,i)-t,s>0?n=a:e=a;while(Math.abs(s)>Rq&&++o<Cq);return a}function sm(t,e,n,r){if(t===e&&n===r)return fs;const i=s=>Lq(s,0,1,t,n);return s=>s===0||s===1?s:SB(i(s),e,r)}const EB=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,wB=t=>e=>1-t(1-e),TB=sm(.33,1.53,.69,.99),UT=wB(TB),AB=EB(UT),RB=t=>t>=1?1:(t*=2)<1?.5*UT(t):.5*(2-Math.pow(2,-10*(t-1))),jT=t=>1-Math.sin(Math.acos(t)),CB=wB(jT),LB=EB(jT),kq=sm(.42,0,1,1),Iq=sm(0,0,.58,1),kB=sm(.42,0,.58,1),Pq=t=>Array.isArray(t)&&typeof t[0]!="number",IB=t=>Array.isArray(t)&&typeof t[0]=="number",Dq={linear:fs,easeIn:kq,easeInOut:kB,easeOut:Iq,circIn:jT,circInOut:LB,circOut:CB,backIn:UT,backInOut:AB,backOut:TB,anticipate:RB},Oq=t=>typeof t=="string",$C=t=>{if(IB(t)){MT(t.length===4);const[e,n,r,i]=t;return sm(e,n,r,i)}else if(Oq(t))return Dq[t];return t},Xm=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function Nq(t,e){let n=new Set,r=new Set,i=!1,s=!1;const a=new WeakSet;let o={delta:0,timestamp:0,isProcessing:!1};function l(u){a.has(u)&&(c.schedule(u),t()),u(o)}const c={schedule:(u,d=!1,h=!1)=>{const p=h&&i?n:r;return d&&a.add(u),p.add(u),u},cancel:u=>{r.delete(u),a.delete(u)},process:u=>{if(o=u,i){s=!0;return}i=!0;const d=n;n=r,r=d,n.forEach(l),n.clear(),i=!1,s&&(s=!1,c.process(u))}};return c}const Mq=40;function PB(t,e){let n=!1,r=!0;const i={delta:0,timestamp:0,isProcessing:!1},s=()=>n=!0,a=Xm.reduce((S,E)=>(S[E]=Nq(s),S),{}),{setup:o,read:l,resolveKeyframes:c,preUpdate:u,update:d,preRender:h,render:f,postRender:p}=a,m=()=>{const S=El.useManualTiming,E=S?i.timestamp:performance.now();n=!1,S||(i.delta=r?1e3/60:Math.max(Math.min(E-i.timestamp,Mq),1)),i.timestamp=E,i.isProcessing=!0,o.process(i),l.process(i),c.process(i),u.process(i),d.process(i),h.process(i),f.process(i),p.process(i),i.isProcessing=!1,n&&e&&(r=!1,t(m))},g=()=>{n=!0,r=!0,i.isProcessing||t(m)};return{schedule:Xm.reduce((S,E)=>{const L=a[E];return S[E]=(U,O=!1,k=!1)=>(n||g(),L.schedule(U,O,k)),S},{}),cancel:S=>{for(let E=0;E<Xm.length;E++)a[Xm[E]].cancel(S)},state:i,steps:a}}const{schedule:gn,cancel:wl,state:kr,steps:q_}=PB(typeof requestAnimationFrame<"u"?requestAnimationFrame:fs,!0);let Yg;function Bq(){Yg=void 0}const ni={now:()=>(Yg===void 0&&ni.set(kr.isProcessing||El.useManualTiming?kr.timestamp:performance.now()),Yg),set:t=>{Yg=t,queueMicrotask(Bq)}},DB=t=>e=>typeof e=="string"&&e.startsWith(t),OB=DB("--"),Uq=DB("var(--"),FT=t=>Uq(t)?jq.test(t.split("/*")[0].trim()):!1,jq=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function VC(t){return typeof t!="string"?!1:t.split("/*")[0].includes("var(--")}const yh={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},cp={...yh,transform:t=>pa(0,1,t)},Qm={...yh,default:1},Ef=t=>Math.round(t*1e5)/1e5,$T=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Fq(t){return t==null}const $q=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,VT=(t,e)=>n=>!!(typeof n=="string"&&$q.test(n)&&n.startsWith(t)||e&&!Fq(n)&&Object.prototype.hasOwnProperty.call(n,e)),NB=(t,e,n)=>r=>{if(typeof r!="string")return r;const[i,s,a,o]=r.match($T);return{[t]:parseFloat(i),[e]:parseFloat(s),[n]:parseFloat(a),alpha:o!==void 0?parseFloat(o):1}},Vq=t=>pa(0,255,t),W_={...yh,transform:t=>Math.round(Vq(t))},ac={test:VT("rgb","red"),parse:NB("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:r=1})=>"rgba("+W_.transform(t)+", "+W_.transform(e)+", "+W_.transform(n)+", "+Ef(cp.transform(r))+")"};function Gq(t){let e="",n="",r="",i="";return t.length>5?(e=t.substring(1,3),n=t.substring(3,5),r=t.substring(5,7),i=t.substring(7,9)):(e=t.substring(1,2),n=t.substring(2,3),r=t.substring(3,4),i=t.substring(4,5),e+=e,n+=n,r+=r,i+=i),{red:parseInt(e,16),green:parseInt(n,16),blue:parseInt(r,16),alpha:i?parseInt(i,16)/255:1}}const MS={test:VT("#"),parse:Gq,transform:ac.transform},am=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),Io=am("deg"),ha=am("%"),at=am("px"),Hq=am("vh"),Kq=am("vw"),GC={...ha,parse:t=>ha.parse(t)/100,transform:t=>ha.transform(t*100)},Qu={test:VT("hsl","hue"),parse:NB("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:r=1})=>"hsla("+Math.round(t)+", "+ha.transform(Ef(e))+", "+ha.transform(Ef(n))+", "+Ef(cp.transform(r))+")"},rr={test:t=>ac.test(t)||MS.test(t)||Qu.test(t),parse:t=>ac.test(t)?ac.parse(t):Qu.test(t)?Qu.parse(t):MS.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?ac.transform(t):Qu.transform(t),getAnimatableNone:t=>{const e=rr.parse(t);return e.alpha=0,rr.transform(e)}},zq=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function qq(t){var e,n;return isNaN(t)&&typeof t=="string"&&(((e=t.match($T))==null?void 0:e.length)||0)+(((n=t.match(zq))==null?void 0:n.length)||0)>0}const MB="number",BB="color",Wq="var",Yq="var(",HC="${}",Xq=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function Wd(t){const e=t.toString(),n=[],r={color:[],number:[],var:[]},i=[];let s=0;const o=e.replace(Xq,l=>(rr.test(l)?(r.color.push(s),i.push(BB),n.push(rr.parse(l))):l.startsWith(Yq)?(r.var.push(s),i.push(Wq),n.push(l)):(r.number.push(s),i.push(MB),n.push(parseFloat(l))),++s,HC)).split(HC);return{values:n,split:o,indexes:r,types:i}}function Qq(t){return Wd(t).values}function UB({split:t,types:e}){const n=t.length;return r=>{let i="";for(let s=0;s<n;s++)if(i+=t[s],r[s]!==void 0){const a=e[s];a===MB?i+=Ef(r[s]):a===BB?i+=rr.transform(r[s]):i+=r[s]}return i}}function Jq(t){return UB(Wd(t))}const Zq=t=>typeof t=="number"?0:rr.test(t)?rr.getAnimatableNone(t):t,e7=(t,e)=>typeof t=="number"?e!=null&&e.trim().endsWith("/")?t:0:Zq(t);function t7(t){const e=Wd(t);return UB(e)(e.values.map((r,i)=>e7(r,e.split[i])))}const Ps={test:qq,parse:Qq,createTransformer:Jq,getAnimatableNone:t7};function Y_(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+(e-t)*6*n:n<1/2?e:n<2/3?t+(e-t)*(2/3-n)*6:t}function n7({hue:t,saturation:e,lightness:n,alpha:r}){t/=360,e/=100,n/=100;let i=0,s=0,a=0;if(!e)i=s=a=n;else{const o=n<.5?n*(1+e):n+e-n*e,l=2*n-o;i=Y_(l,o,t+1/3),s=Y_(l,o,t),a=Y_(l,o,t-1/3)}return{red:Math.round(i*255),green:Math.round(s*255),blue:Math.round(a*255),alpha:r}}function e0(t,e){return n=>n>0?e:t}const An=(t,e,n)=>t+(e-t)*n,X_=(t,e,n)=>{const r=t*t,i=n*(e*e-r)+r;return i<0?0:Math.sqrt(i)},r7=[MS,ac,Qu],i7=t=>r7.find(e=>e.test(t));function KC(t){const e=i7(t);if(!e)return!1;let n=e.parse(t);return e===Qu&&(n=n7(n)),n}const zC=(t,e)=>{const n=KC(t),r=KC(e);if(!n||!r)return e0(t,e);const i={...n};return s=>(i.red=X_(n.red,r.red,s),i.green=X_(n.green,r.green,s),i.blue=X_(n.blue,r.blue,s),i.alpha=An(n.alpha,r.alpha,s),ac.transform(i))},BS=new Set(["none","hidden"]);function s7(t,e){return BS.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function a7(t,e){return n=>An(t,e,n)}function GT(t){return typeof t=="number"?a7:typeof t=="string"?FT(t)?e0:rr.test(t)?zC:c7:Array.isArray(t)?jB:typeof t=="object"?rr.test(t)?zC:o7:e0}function jB(t,e){const n=[...t],r=n.length,i=t.map((s,a)=>GT(s)(s,e[a]));return s=>{for(let a=0;a<r;a++)n[a]=i[a](s);return n}}function o7(t,e){const n={...t,...e},r={};for(const i in n)t[i]!==void 0&&e[i]!==void 0&&(r[i]=GT(t[i])(t[i],e[i]));return i=>{for(const s in r)n[s]=r[s](i);return n}}function l7(t,e){const n=[],r={color:0,var:0,number:0};for(let i=0;i<e.values.length;i++){const s=e.types[i],a=t.indexes[s][r[s]],o=t.values[a]??0;n[i]=o,r[s]++}return n}const c7=(t,e)=>{const n=Ps.createTransformer(e),r=Wd(t),i=Wd(e);return r.indexes.var.length===i.indexes.var.length&&r.indexes.color.length===i.indexes.color.length&&r.indexes.number.length>=i.indexes.number.length?BS.has(t)&&!i.values.length||BS.has(e)&&!r.values.length?s7(t,e):im(jB(l7(r,i),i.values),n):e0(t,e)};function FB(t,e,n){return typeof t=="number"&&typeof e=="number"&&typeof n=="number"?An(t,e,n):GT(t)(t,e)}const u7=t=>{const e=({timestamp:n})=>t(n);return{start:(n=!0)=>gn.update(e,n),stop:()=>wl(e),now:()=>kr.isProcessing?kr.timestamp:ni.now()}},$B=(t,e,n=10)=>{let r="";const i=Math.max(Math.round(e/n),2);for(let s=0;s<i;s++)r+=Math.round(t(s/(i-1))*1e4)/1e4+", ";return`linear(${r.substring(0,r.length-2)})`},t0=2e4;function HT(t){let e=0;const n=50;let r=t.next(e);for(;!r.done&&e<t0;)e+=n,r=t.next(e);return e>=t0?1/0:e}function d7(t,e=100,n){const r=n({...t,keyframes:[0,e]}),i=Math.min(HT(r),t0);return{type:"keyframes",ease:s=>r.next(i*s).value/e,duration:hs(i)}}const Hn={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1};function US(t,e){return t*Math.sqrt(1-e*e)}const h7=12;function f7(t,e,n){let r=n;for(let i=1;i<h7;i++)r=r-t(r)/e(r);return r}const Q_=.001;function p7({duration:t=Hn.duration,bounce:e=Hn.bounce,velocity:n=Hn.velocity,mass:r=Hn.mass}){let i,s,a=1-e;a=pa(Hn.minDamping,Hn.maxDamping,a),t=pa(Hn.minDuration,Hn.maxDuration,hs(t)),a<1?(i=c=>{const u=c*a,d=u*t,h=u-n,f=US(c,a),p=Math.exp(-d);return Q_-h/f*p},s=c=>{const d=c*a*t,h=d*n+n,f=Math.pow(a,2)*Math.pow(c,2)*t,p=Math.exp(-d),m=US(Math.pow(c,2),a);return(-i(c)+Q_>0?-1:1)*((h-f)*p)/m}):(i=c=>{const u=Math.exp(-c*t),d=(c-n)*t+1;return-Q_+u*d},s=c=>{const u=Math.exp(-c*t),d=(n-c)*(t*t);return u*d});const o=5/t,l=f7(i,s,o);if(t=Hi(t),isNaN(l))return{stiffness:Hn.stiffness,damping:Hn.damping,duration:t};{const c=Math.pow(l,2)*r;return{stiffness:c,damping:a*2*Math.sqrt(r*c),duration:t}}}const m7=["duration","bounce"],g7=["stiffness","damping","mass"];function qC(t,e){return e.some(n=>t[n]!==void 0)}function y7(t){let e={velocity:Hn.velocity,stiffness:Hn.stiffness,damping:Hn.damping,mass:Hn.mass,isResolvedFromDuration:!1,...t};if(!qC(t,g7)&&qC(t,m7))if(e.velocity=0,t.visualDuration){const n=t.visualDuration,r=2*Math.PI/(n*1.2),i=r*r,s=2*pa(.05,1,1-(t.bounce||0))*Math.sqrt(i);e={...e,mass:Hn.mass,stiffness:i,damping:s}}else{const n=p7({...t,velocity:0});e={...e,...n,mass:Hn.mass},e.isResolvedFromDuration=!0}return e}function n0(t=Hn.visualDuration,e=Hn.bounce){const n=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:r,restDelta:i}=n;const s=n.keyframes[0],a=n.keyframes[n.keyframes.length-1],o={done:!1,value:s},{stiffness:l,damping:c,mass:u,duration:d,velocity:h,isResolvedFromDuration:f}=y7({...n,velocity:-hs(n.velocity||0)}),p=h||0,m=c/(2*Math.sqrt(l*u)),g=a-s,b=hs(Math.sqrt(l/u)),v=Math.abs(g)<5;r||(r=v?Hn.restSpeed.granular:Hn.restSpeed.default),i||(i=v?Hn.restDelta.granular:Hn.restDelta.default);let S,E,L,U,O,k;if(m<1)L=US(b,m),U=(p+m*b*g)/L,S=R=>{const M=Math.exp(-m*b*R);return a-M*(U*Math.sin(L*R)+g*Math.cos(L*R))},O=m*b*U+g*L,k=m*b*g-U*L,E=R=>Math.exp(-m*b*R)*(O*Math.sin(L*R)+k*Math.cos(L*R));else if(m===1){S=M=>a-Math.exp(-b*M)*(g+(p+b*g)*M);const R=p+b*g;E=M=>Math.exp(-b*M)*(b*R*M-p)}else{const R=b*Math.sqrt(m*m-1);S=W=>{const re=Math.exp(-m*b*W),X=Math.min(R*W,300);return a-re*((p+m*b*g)*Math.sinh(X)+R*g*Math.cosh(X))/R};const M=(p+m*b*g)/R,z=m*b*M-g*R,Z=m*b*g-M*R;E=W=>{const re=Math.exp(-m*b*W),X=Math.min(R*W,300);return re*(z*Math.sinh(X)+Z*Math.cosh(X))}}const I={calculatedDuration:f&&d||null,velocity:R=>Hi(E(R)),next:R=>{if(!f&&m<1){const z=Math.exp(-m*b*R),Z=Math.sin(L*R),W=Math.cos(L*R),re=a-z*(U*Z+g*W),X=Hi(z*(O*Z+k*W));return o.done=Math.abs(X)<=r&&Math.abs(a-re)<=i,o.value=o.done?a:re,o}const M=S(R);if(f)o.done=R>=d;else{const z=Hi(E(R));o.done=Math.abs(z)<=r&&Math.abs(a-M)<=i}return o.value=o.done?a:M,o},toString:()=>{const R=Math.min(HT(I),t0),M=$B(z=>I.next(R*z).value,R,30);return R+"ms "+M},toTransition:()=>{}};return I}n0.applyToOptions=t=>{const e=d7(t,100,n0);return t.ease=e.ease,t.duration=Hi(e.duration),t.type="keyframes",t};const v7=5;function VB(t,e,n){const r=Math.max(e-v7,0);return xB(n-t(r),e-r)}function jS({keyframes:t,velocity:e=0,power:n=.8,timeConstant:r=325,bounceDamping:i=10,bounceStiffness:s=500,modifyTarget:a,min:o,max:l,restDelta:c=.5,restSpeed:u}){const d=t[0],h={done:!1,value:d},f=k=>o!==void 0&&k<o||l!==void 0&&k>l,p=k=>o===void 0?l:l===void 0||Math.abs(o-k)<Math.abs(l-k)?o:l;let m=n*e;const g=d+m,b=a===void 0?g:a(g);b!==g&&(m=b-d);const v=k=>-m*Math.exp(-k/r),S=k=>b+v(k),E=k=>{const I=v(k),R=S(k);h.done=Math.abs(I)<=c,h.value=h.done?b:R};let L,U;const O=k=>{f(h.value)&&(L=k,U=n0({keyframes:[h.value,p(h.value)],velocity:VB(S,k,h.value),damping:i,stiffness:s,restDelta:c,restSpeed:u}))};return O(0),{calculatedDuration:null,next:k=>{let I=!1;return!U&&L===void 0&&(I=!0,E(k),O(k)),L!==void 0&&k>=L?U.next(k-L):(!I&&E(k),h)}}}function _7(t,e,n){const r=[],i=n||El.mix||FB,s=t.length-1;for(let a=0;a<s;a++){let o=i(t[a],t[a+1]);if(e){const l=Array.isArray(e)?e[a]||fs:e;o=im(l,o)}r.push(o)}return r}function b7(t,e,{clamp:n=!0,ease:r,mixer:i}={}){const s=t.length;if(MT(s===e.length),s===1)return()=>e[0];if(s===2&&e[0]===e[1])return()=>e[1];const a=t[0]===t[1];t[0]>t[s-1]&&(t=[...t].reverse(),e=[...e].reverse());const o=_7(e,r,i),l=o.length,c=u=>{if(a&&u<t[0])return e[0];let d=0;if(l>1)for(;d<t.length-2&&!(u<t[d+1]);d++);const h=lp(t[d],t[d+1],u);return o[d](h)};return n?u=>c(pa(t[0],t[s-1],u)):c}function x7(t,e){const n=t[t.length-1];for(let r=1;r<=e;r++){const i=lp(0,e,r);t.push(An(n,1,i))}}function S7(t){const e=[0];return x7(e,t.length-1),e}function E7(t,e){return t.map(n=>n*e)}function w7(t,e){return t.map(()=>e||kB).splice(0,t.length-1)}function wf({duration:t=300,keyframes:e,times:n,ease:r="easeInOut"}){const i=Pq(r)?r.map($C):$C(r),s={done:!1,value:e[0]},a=E7(n&&n.length===e.length?n:S7(e),t),o=b7(a,e,{ease:Array.isArray(i)?i:w7(e,i)});return{calculatedDuration:t,next:l=>(s.value=o(l),s.done=l>=t,s)}}const T7=t=>t!==null;function dv(t,{repeat:e,repeatType:n="loop"},r,i=1){const s=t.filter(T7),o=i<0||e&&n!=="loop"&&e%2===1?0:s.length-1;return!o||r===void 0?s[o]:r}const A7={decay:jS,inertia:jS,tween:wf,keyframes:wf,spring:n0};function GB(t){typeof t.type=="string"&&(t.type=A7[t.type])}class KT{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,n){return this.finished.then(e,n)}}const R7=t=>t/100;class r0 extends KT{constructor(e){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.delayState={done:!1,value:void 0},this.stop=()=>{var r,i;const{motionValue:n}=this.options;n&&n.updatedAt!==ni.now()&&this.tick(ni.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(i=(r=this.options).onStop)==null||i.call(r))},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){const{options:e}=this;GB(e);const{type:n=wf,repeat:r=0,repeatDelay:i=0,repeatType:s,velocity:a=0}=e;let{keyframes:o}=e;const l=n||wf;l!==wf&&typeof o[0]!="number"&&(this.mixKeyframes=im(R7,FB(o[0],o[1])),o=[0,100]);const c=l({...e,keyframes:o});s==="mirror"&&(this.mirroredGenerator=l({...e,keyframes:[...o].reverse(),velocity:-a})),c.calculatedDuration===null&&(c.calculatedDuration=HT(c));const{calculatedDuration:u}=c;this.calculatedDuration=u,this.resolvedDuration=u+i,this.totalDuration=this.resolvedDuration*(r+1)-i,this.generator=c}updateTime(e){const n=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(e,n=!1){const{generator:r,totalDuration:i,mixKeyframes:s,mirroredGenerator:a,resolvedDuration:o,calculatedDuration:l}=this;if(this.startTime===null)return r.next(0);const{delay:c=0,keyframes:u,repeat:d,repeatType:h,repeatDelay:f,type:p,onUpdate:m,finalKeyframe:g}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-i/this.speed,this.startTime)),n?this.currentTime=e:this.updateTime(e);const b=this.currentTime-c*(this.playbackSpeed>=0?1:-1),v=this.playbackSpeed>=0?b<0:b>i;this.currentTime=Math.max(b,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=i);let S=this.currentTime,E=r;if(d){const k=Math.min(this.currentTime,i)/o;let I=Math.floor(k),R=k%1;!R&&k>=1&&(R=1),R===1&&I--,I=Math.min(I,d+1),!!(I%2)&&(h==="reverse"?(R=1-R,f&&(R-=f/o)):h==="mirror"&&(E=a)),S=pa(0,1,R)*o}let L;v?(this.delayState.value=u[0],L=this.delayState):L=E.next(S),s&&!v&&(L.value=s(L.value));let{done:U}=L;!v&&l!==null&&(U=this.playbackSpeed>=0?this.currentTime>=i:this.currentTime<=0);const O=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&U);return O&&p!==jS&&(L.value=dv(u,this.options,g,this.speed)),m&&m(L.value),O&&this.finish(),L}then(e,n){return this.finished.then(e,n)}get duration(){return hs(this.calculatedDuration)}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+hs(e)}get time(){return hs(this.currentTime)}set time(e){e=Hi(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),this.driver?this.driver.start(!1):(this.startTime=0,this.state="paused",this.holdTime=e,this.tick(e))}getGeneratorVelocity(){const e=this.currentTime;if(e<=0)return this.options.velocity||0;if(this.generator.velocity)return this.generator.velocity(e);const n=this.generator.next(e).value;return VB(r=>this.generator.next(r).value,e,n)}get speed(){return this.playbackSpeed}set speed(e){const n=this.playbackSpeed!==e;n&&this.driver&&this.updateTime(ni.now()),this.playbackSpeed=e,n&&this.driver&&(this.time=hs(this.currentTime))}play(){var i,s;if(this.isStopped)return;const{driver:e=u7,startTime:n}=this.options;this.driver||(this.driver=e(a=>this.tick(a))),(s=(i=this.options).onPlay)==null||s.call(i);const r=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=r):this.holdTime!==null?this.startTime=r-this.holdTime:this.startTime||(this.startTime=n??r),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(ni.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var e,n;this.notifyFinished(),this.teardown(),this.state="finished",(n=(e=this.options).onComplete)==null||n.call(e)}cancel(){var e,n;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(n=(e=this.options).onCancel)==null||n.call(e)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){var n;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(n=this.driver)==null||n.stop(),e.observe(this)}}function C7(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const oc=t=>t*180/Math.PI,FS=t=>{const e=oc(Math.atan2(t[1],t[0]));return $S(e)},L7={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:FS,rotateZ:FS,skewX:t=>oc(Math.atan(t[1])),skewY:t=>oc(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},$S=t=>(t=t%360,t<0&&(t+=360),t),WC=FS,YC=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),XC=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),k7={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:YC,scaleY:XC,scale:t=>(YC(t)+XC(t))/2,rotateX:t=>$S(oc(Math.atan2(t[6],t[5]))),rotateY:t=>$S(oc(Math.atan2(-t[2],t[0]))),rotateZ:WC,rotate:WC,skewX:t=>oc(Math.atan(t[4])),skewY:t=>oc(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function VS(t){return t.includes("scale")?1:0}function GS(t,e){if(!t||t==="none")return VS(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,i;if(n)r=k7,i=n;else{const o=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=L7,i=o}if(!i)return VS(e);const s=r[e],a=i[1].split(",").map(P7);return typeof s=="function"?s(a):a[s]}const I7=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return GS(n,e)};function P7(t){return parseFloat(t.trim())}const vh=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],_h=new Set(vh),QC=t=>t===yh||t===at,D7=new Set(["x","y","z"]),O7=vh.filter(t=>!D7.has(t));function N7(t){const e=[];return O7.forEach(n=>{const r=t.getValue(n);r!==void 0&&(e.push([n,r.get()]),r.set(n.startsWith("scale")?1:0))}),e}const sl={width:({x:t},{paddingLeft:e="0",paddingRight:n="0",boxSizing:r})=>{const i=t.max-t.min;return r==="border-box"?i:i-parseFloat(e)-parseFloat(n)},height:({y:t},{paddingTop:e="0",paddingBottom:n="0",boxSizing:r})=>{const i=t.max-t.min;return r==="border-box"?i:i-parseFloat(e)-parseFloat(n)},top:(t,{top:e})=>parseFloat(e),left:(t,{left:e})=>parseFloat(e),bottom:({y:t},{top:e})=>parseFloat(e)+(t.max-t.min),right:({x:t},{left:e})=>parseFloat(e)+(t.max-t.min),x:(t,{transform:e})=>GS(e,"x"),y:(t,{transform:e})=>GS(e,"y")};sl.translateX=sl.x;sl.translateY=sl.y;const Lc=new Set;let HS=!1,KS=!1,zS=!1;function HB(){if(KS){const t=Array.from(Lc).filter(r=>r.needsMeasurement),e=new Set(t.map(r=>r.element)),n=new Map;e.forEach(r=>{const i=N7(r);i.length&&(n.set(r,i),r.render())}),t.forEach(r=>r.measureInitialState()),e.forEach(r=>{r.render();const i=n.get(r);i&&i.forEach(([s,a])=>{var o;(o=r.getValue(s))==null||o.set(a)})}),t.forEach(r=>r.measureEndState()),t.forEach(r=>{r.suspendedScrollY!==void 0&&window.scrollTo(0,r.suspendedScrollY)})}KS=!1,HS=!1,Lc.forEach(t=>t.complete(zS)),Lc.clear()}function KB(){Lc.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(KS=!0)})}function M7(){zS=!0,KB(),HB(),zS=!1}class zT{constructor(e,n,r,i,s,a=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=n,this.name=r,this.motionValue=i,this.element=s,this.isAsync=a}scheduleResolve(){this.state="scheduled",this.isAsync?(Lc.add(this),HS||(HS=!0,gn.read(KB),gn.resolveKeyframes(HB))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:n,element:r,motionValue:i}=this;if(e[0]===null){const s=i==null?void 0:i.get(),a=e[e.length-1];if(s!==void 0)e[0]=s;else if(r&&n){const o=r.readValue(n,a);o!=null&&(e[0]=o)}e[0]===void 0&&(e[0]=a),i&&s===void 0&&i.set(e[0])}C7(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Lc.delete(this)}cancel(){this.state==="scheduled"&&(Lc.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const B7=t=>t.startsWith("--");function zB(t,e,n){B7(e)?t.style.setProperty(e,n):t.style[e]=n}const U7={};function qB(t,e){const n=bB(t);return()=>U7[e]??n()}const j7=qB(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),WB=qB(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Zh=([t,e,n,r])=>`cubic-bezier(${t}, ${e}, ${n}, ${r})`,JC={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Zh([0,.65,.55,1]),circOut:Zh([.55,0,1,.45]),backIn:Zh([.31,.01,.66,-.59]),backOut:Zh([.33,1.53,.69,.99])};function YB(t,e){if(t)return typeof t=="function"?WB()?$B(t,e):"ease-out":IB(t)?Zh(t):Array.isArray(t)?t.map(n=>YB(n,e)||JC.easeOut):JC[t]}function F7(t,e,n,{delay:r=0,duration:i=300,repeat:s=0,repeatType:a="loop",ease:o="easeOut",times:l}={},c=void 0){const u={[e]:n};l&&(u.offset=l);const d=YB(o,i);Array.isArray(d)&&(u.easing=d);const h={delay:r,duration:i,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:s+1,direction:a==="reverse"?"alternate":"normal"};return c&&(h.pseudoElement=c),t.animate(u,h)}function XB(t){return typeof t=="function"&&"applyToOptions"in t}function $7({type:t,...e}){return XB(t)&&WB()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class QB extends KT{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!e)return;const{element:n,name:r,keyframes:i,pseudoElement:s,allowFlatten:a=!1,finalKeyframe:o,onComplete:l}=e;this.isPseudoElement=!!s,this.allowFlatten=a,this.options=e,MT(typeof e.type!="string");const c=$7(e);this.animation=F7(n,r,i,c,s),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!s){const u=dv(i,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(u),zB(n,r,u),this.animation.cancel()}l==null||l(),this.notifyFinished()}}play(){this.isStopped||(this.manualStartTime=null,this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var e,n;(n=(e=this.animation).finish)==null||n.call(e)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:e}=this;e==="idle"||e==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var n,r,i;const e=(n=this.options)==null?void 0:n.element;!this.isPseudoElement&&(e!=null&&e.isConnected)&&((i=(r=this.animation).commitStyles)==null||i.call(r))}get duration(){var n,r;const e=((r=(n=this.animation.effect)==null?void 0:n.getComputedTiming)==null?void 0:r.call(n).duration)||0;return hs(Number(e))}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+hs(e)}get time(){return hs(Number(this.animation.currentTime)||0)}set time(e){const n=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=Hi(e),n&&this.animation.pause()}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return this.manualStartTime??Number(this.animation.startTime)}set startTime(e){this.manualStartTime=this.animation.startTime=e}attachTimeline({timeline:e,rangeStart:n,rangeEnd:r,observe:i}){var s;return this.allowFlatten&&((s=this.animation.effect)==null||s.updateTiming({easing:"linear"})),this.animation.onfinish=null,e&&j7()?(this.animation.timeline=e,n&&(this.animation.rangeStart=n),r&&(this.animation.rangeEnd=r),fs):i(this)}}const JB={anticipate:RB,backInOut:AB,circInOut:LB};function V7(t){return t in JB}function G7(t){typeof t.ease=="string"&&V7(t.ease)&&(t.ease=JB[t.ease])}const J_=10;class H7 extends QB{constructor(e){G7(e),GB(e),super(e),e.startTime!==void 0&&e.autoplay!==!1&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:n,onUpdate:r,onComplete:i,element:s,...a}=this.options;if(!n)return;if(e!==void 0){n.set(e);return}const o=new r0({...a,autoplay:!1}),l=Math.max(J_,ni.now()-this.startTime),c=pa(0,J_,l-J_),u=o.sample(l).value,{name:d}=this.options;s&&d&&zB(s,d,u),n.setWithVelocity(o.sample(Math.max(0,l-c)).value,u,c),o.stop()}}const ZC=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Ps.test(t)||t==="0")&&!t.startsWith("url("));function K7(t){const e=t[0];if(t.length===1)return!0;for(let n=0;n<t.length;n++)if(t[n]!==e)return!0}function z7(t,e,n,r){const i=t[0];if(i===null)return!1;if(e==="display"||e==="visibility")return!0;const s=t[t.length-1],a=ZC(i,e),o=ZC(s,e);return!a||!o?!1:K7(t)||(n==="spring"||XB(n))&&r}function qS(t){t.duration=0,t.type="keyframes"}const ZB=new Set(["opacity","clipPath","filter","transform"]),q7=/^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/;function W7(t){for(let e=0;e<t.length;e++)if(typeof t[e]=="string"&&q7.test(t[e]))return!0;return!1}const Y7=new Set(["color","backgroundColor","outlineColor","fill","stroke","borderColor","borderTopColor","borderRightColor","borderBottomColor","borderLeftColor"]),X7=bB(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Q7(t){var d;const{motionValue:e,name:n,repeatDelay:r,repeatType:i,damping:s,type:a,keyframes:o}=t;if(!(((d=e==null?void 0:e.owner)==null?void 0:d.current)instanceof HTMLElement))return!1;const{onUpdate:c,transformTemplate:u}=e.owner.getProps();return X7()&&n&&(ZB.has(n)||Y7.has(n)&&W7(o))&&(n!=="transform"||!u)&&!c&&!r&&i!=="mirror"&&s!==0&&a!=="inertia"}const J7=40;class Z7 extends KT{constructor({autoplay:e=!0,delay:n=0,type:r="keyframes",repeat:i=0,repeatDelay:s=0,repeatType:a="loop",keyframes:o,name:l,motionValue:c,element:u,...d}){var p;super(),this.stop=()=>{var m,g;this._animation&&(this._animation.stop(),(m=this.stopTimeline)==null||m.call(this)),(g=this.keyframeResolver)==null||g.cancel()},this.createdAt=ni.now();const h={autoplay:e,delay:n,type:r,repeat:i,repeatDelay:s,repeatType:a,name:l,motionValue:c,element:u,...d},f=(u==null?void 0:u.KeyframeResolver)||zT;this.keyframeResolver=new f(o,(m,g,b)=>this.onKeyframesResolved(m,g,h,!b),l,c,u),(p=this.keyframeResolver)==null||p.scheduleResolve()}onKeyframesResolved(e,n,r,i){var b,v;this.keyframeResolver=void 0;const{name:s,type:a,velocity:o,delay:l,isHandoff:c,onUpdate:u}=r;this.resolvedAt=ni.now();let d=!0;z7(e,s,a,o)||(d=!1,(El.instantAnimations||!l)&&(u==null||u(dv(e,r,n))),e[0]=e[e.length-1],qS(r),r.repeat=0);const f={startTime:i?this.resolvedAt?this.resolvedAt-this.createdAt>J7?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...r,keyframes:e},p=d&&!c&&Q7(f),m=(v=(b=f.motionValue)==null?void 0:b.owner)==null?void 0:v.current;let g;if(p)try{g=new H7({...f,element:m})}catch{g=new r0(f)}else g=new r0(f);g.finished.then(()=>{this.notifyFinished()}).catch(fs),this.pendingTimeline&&(this.stopTimeline=g.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=g}get finished(){return this._animation?this.animation.finished:this._finished}then(e,n){return this.finished.finally(e).then(()=>{})}get animation(){var e;return this._animation||((e=this.keyframeResolver)==null||e.resume(),M7()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(e){this.animation.time=e}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(e){this.animation.speed=e}get startTime(){return this.animation.startTime}attachTimeline(e){return this._animation?this.stopTimeline=this.animation.attachTimeline(e):this.pendingTimeline=e,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){var e;this._animation&&this.animation.cancel(),(e=this.keyframeResolver)==null||e.cancel()}}function eU(t,e,n,r=0,i=1){const s=Array.from(t).sort((c,u)=>c.sortNodePosition(u)).indexOf(e),a=t.size,o=(a-1)*r;return typeof n=="function"?n(s,a):i===1?s*r:o-s*r}const eW=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function tW(t){const e=eW.exec(t);if(!e)return[,];const[,n,r,i]=e;return[`--${n??r}`,i]}function tU(t,e,n=1){const[r,i]=tW(t);if(!r)return;const s=window.getComputedStyle(e).getPropertyValue(r);if(s){const a=s.trim();return yB(a)?parseFloat(a):a}return FT(i)?tU(i,e,n+1):i}const nW={type:"spring",stiffness:500,damping:25,restSpeed:10},rW=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),iW={type:"keyframes",duration:.8},sW={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},aW=(t,{keyframes:e})=>e.length>2?iW:_h.has(t)?t.startsWith("scale")?rW(e[1]):nW:sW;function nU(t,e){if(t!=null&&t.inherit&&e){const{inherit:n,...r}=t;return{...e,...r}}return t}function qT(t,e){const n=(t==null?void 0:t[e])??(t==null?void 0:t.default)??t;return n!==t?nU(n,t):n}const oW=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function lW(t){for(const e in t)if(!oW.has(e))return!0;return!1}const WT=(t,e,n,r={},i,s)=>a=>{const o=qT(r,t)||{},l=o.delay||r.delay||0;let{elapsed:c=0}=r;c=c-Hi(l);const u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:e.getVelocity(),...o,delay:-c,onUpdate:h=>{e.set(h),o.onUpdate&&o.onUpdate(h)},onComplete:()=>{a(),o.onComplete&&o.onComplete()},name:t,motionValue:e,element:s?void 0:i};lW(o)||Object.assign(u,aW(t,u)),u.duration&&(u.duration=Hi(u.duration)),u.repeatDelay&&(u.repeatDelay=Hi(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(qS(u),u.delay===0&&(d=!0)),(El.instantAnimations||El.skipAnimations||i!=null&&i.shouldSkipAnimations)&&(d=!0,qS(u),u.delay=0),u.allowFlatten=!o.type&&!o.ease,d&&!s&&e.get()!==void 0){const h=dv(u.keyframes,o);if(h!==void 0){gn.update(()=>{u.onUpdate(h),u.onComplete()});return}}return o.isSync?new r0(u):new Z7(u)};function eL(t){const e=[{},{}];return t==null||t.values.forEach((n,r)=>{e[0][r]=n.get(),e[1][r]=n.getVelocity()}),e}function YT(t,e,n,r){if(typeof e=="function"){const[i,s]=eL(r);e=e(n!==void 0?n:t.custom,i,s)}if(typeof e=="string"&&(e=t.variants&&t.variants[e]),typeof e=="function"){const[i,s]=eL(r);e=e(n!==void 0?n:t.custom,i,s)}return e}function kc(t,e,n){const r=t.getProps();return YT(r,e,n!==void 0?n:r.custom,t)}const rU=new Set(["width","height","top","left","right","bottom",...vh]),tL=30,cW=t=>!isNaN(parseFloat(t));class uW{constructor(e,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var s;const i=ni.now();if(this.updatedAt!==i&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(r),this.current!==this.prev&&((s=this.events.change)==null||s.notify(this.current),this.dependents))for(const a of this.dependents)a.dirty()},this.hasAnimated=!1,this.setCurrent(e),this.owner=n.owner}setCurrent(e){this.current=e,this.updatedAt=ni.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=cW(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on("change",e)}on(e,n){this.events[e]||(this.events[e]=new BT);const r=this.events[e].add(n);return e==="change"?()=>{r(),gn.read(()=>{this.events.change.getSize()||this.stop()})}:r}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,n){this.passiveEffect=e,this.stopPassiveEffect=n}set(e){this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e)}setWithVelocity(e,n,r){this.set(n),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-r}jump(e,n=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var e;(e=this.events.change)==null||e.notify(this.current)}addDependent(e){this.dependents||(this.dependents=new Set),this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const e=ni.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>tL)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,tL);return xB(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(e){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=e(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){var e,n;(e=this.dependents)==null||e.clear(),(n=this.events.destroy)==null||n.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function Yd(t,e){return new uW(t,e)}const WS=t=>Array.isArray(t);function dW(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,Yd(n))}function hW(t){return WS(t)?t[t.length-1]||0:t}function fW(t,e){const n=kc(t,e);let{transitionEnd:r={},transition:i={},...s}=n||{};s={...s,...r};for(const a in s){const o=hW(s[a]);dW(t,a,o)}}const Br=t=>!!(t&&t.getVelocity);function pW(t){return!!(Br(t)&&t.add)}function YS(t,e){const n=t.getValue("willChange");if(pW(n))return n.add(e);if(!n&&El.WillChange){const r=new El.WillChange("auto");t.addValue("willChange",r),r.add(e)}}function XT(t){return t.replace(/([A-Z])/g,e=>`-${e.toLowerCase()}`)}const mW="framerAppearId",iU="data-"+XT(mW);function sU(t){return t.props[iU]}function gW({protectedKeys:t,needsAnimating:e},n){const r=t.hasOwnProperty(n)&&e[n]!==!0;return e[n]=!1,r}function aU(t,e,{delay:n=0,transitionOverride:r,type:i}={}){let{transition:s,transitionEnd:a,...o}=e;const l=t.getDefaultTransition();s=s?nU(s,l):l;const c=s==null?void 0:s.reduceMotion;r&&(s=r);const u=[],d=i&&t.animationState&&t.animationState.getState()[i];for(const h in o){const f=t.getValue(h,t.latestValues[h]??null),p=o[h];if(p===void 0||d&&gW(d,h))continue;const m={delay:n,...qT(s||{},h)},g=f.get();if(g!==void 0&&!f.isAnimating()&&!Array.isArray(p)&&p===g&&!m.velocity){gn.update(()=>f.set(p));continue}let b=!1;if(window.MotionHandoffAnimation){const E=sU(t);if(E){const L=window.MotionHandoffAnimation(E,h,gn);L!==null&&(m.startTime=L,b=!0)}}YS(t,h);const v=c??t.shouldReduceMotion;f.start(WT(h,f,p,v&&rU.has(h)?{type:!1}:m,t,b));const S=f.animation;S&&u.push(S)}if(a){const h=()=>gn.update(()=>{a&&fW(t,a)});u.length?Promise.all(u).then(h):h()}return u}function XS(t,e,n={}){var l;const r=kc(t,e,n.type==="exit"?(l=t.presenceContext)==null?void 0:l.custom:void 0);let{transition:i=t.getDefaultTransition()||{}}=r||{};n.transitionOverride&&(i=n.transitionOverride);const s=r?()=>Promise.all(aU(t,r,n)):()=>Promise.resolve(),a=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:h}=i;return yW(t,e,c,u,d,h,n)}:()=>Promise.resolve(),{when:o}=i;if(o){const[c,u]=o==="beforeChildren"?[s,a]:[a,s];return c().then(()=>u())}else return Promise.all([s(),a(n.delay)])}function yW(t,e,n=0,r=0,i=0,s=1,a){const o=[];for(const l of t.variantChildren)l.notify("AnimationStart",e),o.push(XS(l,e,{...a,delay:n+(typeof r=="function"?0:r)+eU(t.variantChildren,l,r,i,s)}).then(()=>l.notify("AnimationComplete",e)));return Promise.all(o)}function vW(t,e,n={}){t.notify("AnimationStart",e);let r;if(Array.isArray(e)){const i=e.map(s=>XS(t,s,n));r=Promise.all(i)}else if(typeof e=="string")r=XS(t,e,n);else{const i=typeof e=="function"?kc(t,e,n.custom):e;r=Promise.all(aU(t,i,n))}return r.then(()=>{t.notify("AnimationComplete",e)})}const _W={test:t=>t==="auto",parse:t=>t},oU=t=>e=>e.test(t),lU=[yh,at,ha,Io,Kq,Hq,_W],nL=t=>lU.find(oU(t));function bW(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||_B(t):!0}const xW=new Set(["brightness","contrast","saturate","opacity"]);function SW(t){const[e,n]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[r]=n.match($T)||[];if(!r)return t;const i=n.replace(r,"");let s=xW.has(e)?1:0;return r!==n&&(s*=100),e+"("+s+i+")"}const EW=/\b([a-z-]*)\(.*?\)/gu,QS={...Ps,getAnimatableNone:t=>{const e=t.match(EW);return e?e.map(SW).join(" "):t}},JS={...Ps,getAnimatableNone:t=>{const e=Ps.parse(t);return Ps.createTransformer(t)(e.map(r=>typeof r=="number"?0:typeof r=="object"?{...r,alpha:1}:r))}},rL={...yh,transform:Math.round},wW={rotate:Io,rotateX:Io,rotateY:Io,rotateZ:Io,scale:Qm,scaleX:Qm,scaleY:Qm,scaleZ:Qm,skew:Io,skewX:Io,skewY:Io,distance:at,translateX:at,translateY:at,translateZ:at,x:at,y:at,z:at,perspective:at,transformPerspective:at,opacity:cp,originX:GC,originY:GC,originZ:at},QT={borderWidth:at,borderTopWidth:at,borderRightWidth:at,borderBottomWidth:at,borderLeftWidth:at,borderRadius:at,borderTopLeftRadius:at,borderTopRightRadius:at,borderBottomRightRadius:at,borderBottomLeftRadius:at,width:at,maxWidth:at,height:at,maxHeight:at,top:at,right:at,bottom:at,left:at,inset:at,insetBlock:at,insetBlockStart:at,insetBlockEnd:at,insetInline:at,insetInlineStart:at,insetInlineEnd:at,padding:at,paddingTop:at,paddingRight:at,paddingBottom:at,paddingLeft:at,paddingBlock:at,paddingBlockStart:at,paddingBlockEnd:at,paddingInline:at,paddingInlineStart:at,paddingInlineEnd:at,margin:at,marginTop:at,marginRight:at,marginBottom:at,marginLeft:at,marginBlock:at,marginBlockStart:at,marginBlockEnd:at,marginInline:at,marginInlineStart:at,marginInlineEnd:at,fontSize:at,backgroundPositionX:at,backgroundPositionY:at,...wW,zIndex:rL,fillOpacity:cp,strokeOpacity:cp,numOctaves:rL},TW={...QT,color:rr,backgroundColor:rr,outlineColor:rr,fill:rr,stroke:rr,borderColor:rr,borderTopColor:rr,borderRightColor:rr,borderBottomColor:rr,borderLeftColor:rr,filter:QS,WebkitFilter:QS,mask:JS,WebkitMask:JS},cU=t=>TW[t],AW=new Set([QS,JS]);function uU(t,e){let n=cU(t);return AW.has(n)||(n=Ps),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const RW=new Set(["auto","none","0"]);function CW(t,e,n){let r=0,i;for(;r<t.length&&!i;){const s=t[r];typeof s=="string"&&!RW.has(s)&&Wd(s).values.length&&(i=t[r]),r++}if(i&&n)for(const s of e)t[s]=uU(n,i)}class LW extends zT{constructor(e,n,r,i,s){super(e,n,r,i,s,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:n,name:r}=this;if(!n||!n.current)return;super.readKeyframes();for(let u=0;u<e.length;u++){let d=e[u];if(typeof d=="string"&&(d=d.trim(),FT(d))){const h=tU(d,n.current);h!==void 0&&(e[u]=h),u===e.length-1&&(this.finalKeyframe=d)}}if(this.resolveNoneKeyframes(),!rU.has(r)||e.length!==2)return;const[i,s]=e,a=nL(i),o=nL(s),l=VC(i),c=VC(s);if(l!==c&&sl[r]){this.needsMeasurement=!0;return}if(a!==o)if(QC(a)&&QC(o))for(let u=0;u<e.length;u++){const d=e[u];typeof d=="string"&&(e[u]=parseFloat(d))}else sl[r]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:n}=this,r=[];for(let i=0;i<e.length;i++)(e[i]===null||bW(e[i]))&&r.push(i);r.length&&CW(e,r,n)}measureInitialState(){const{element:e,unresolvedKeyframes:n,name:r}=this;if(!e||!e.current)return;r==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=sl[r](e.measureViewportBox(),window.getComputedStyle(e.current)),n[0]=this.measuredOrigin;const i=n[n.length-1];i!==void 0&&e.getValue(r,i).jump(i,!1)}measureEndState(){var o;const{element:e,name:n,unresolvedKeyframes:r}=this;if(!e||!e.current)return;const i=e.getValue(n);i&&i.jump(this.measuredOrigin,!1);const s=r.length-1,a=r[s];r[s]=sl[n](e.measureViewportBox(),window.getComputedStyle(e.current)),a!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=a),(o=this.removedTransforms)!=null&&o.length&&this.removedTransforms.forEach(([l,c])=>{e.getValue(l).set(c)}),this.resolveNoneKeyframes()}}function dU(t,e,n){if(t==null)return[];if(t instanceof EventTarget)return[t];if(typeof t=="string"){let r=document;const i=(n==null?void 0:n[t])??r.querySelectorAll(t);return i?Array.from(i):[]}return Array.from(t).filter(r=>r!=null)}const hU=(t,e)=>e&&typeof t=="number"?e.transform(t):t;function Xg(t){return vB(t)&&"offsetHeight"in t&&!("ownerSVGElement"in t)}const{schedule:JT}=PB(queueMicrotask,!1),As={x:!1,y:!1};function fU(){return As.x||As.y}function kW(t){return t==="x"||t==="y"?As[t]?null:(As[t]=!0,()=>{As[t]=!1}):As.x||As.y?null:(As.x=As.y=!0,()=>{As.x=As.y=!1})}function pU(t,e){const n=dU(t),r=new AbortController,i={passive:!0,...e,signal:r.signal};return[n,i,()=>r.abort()]}function IW(t){return!(t.pointerType==="touch"||fU())}function PW(t,e,n={}){const[r,i,s]=pU(t,n);return r.forEach(a=>{let o=!1,l=!1,c;const u=()=>{a.removeEventListener("pointerleave",p)},d=g=>{c&&(c(g),c=void 0),u()},h=g=>{o=!1,window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",h),l&&(l=!1,d(g))},f=()=>{o=!0,window.addEventListener("pointerup",h,i),window.addEventListener("pointercancel",h,i)},p=g=>{if(g.pointerType!=="touch"){if(o){l=!0;return}d(g)}},m=g=>{if(!IW(g))return;l=!1;const b=e(a,g);typeof b=="function"&&(c=b,a.addEventListener("pointerleave",p,i))};a.addEventListener("pointerenter",m,i),a.addEventListener("pointerdown",f,i)}),s}const mU=(t,e)=>e?t===e?!0:mU(t,e.parentElement):!1,ZT=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,DW=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function OW(t){return DW.has(t.tagName)||t.isContentEditable===!0}const NW=new Set(["INPUT","SELECT","TEXTAREA"]);function MW(t){return NW.has(t.tagName)||t.isContentEditable===!0}const Qg=new WeakSet;function iL(t){return e=>{e.key==="Enter"&&t(e)}}function Z_(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const BW=(t,e)=>{const n=t.currentTarget;if(!n)return;const r=iL(()=>{if(Qg.has(n))return;Z_(n,"down");const i=iL(()=>{Z_(n,"up")}),s=()=>Z_(n,"cancel");n.addEventListener("keyup",i,e),n.addEventListener("blur",s,e)});n.addEventListener("keydown",r,e),n.addEventListener("blur",()=>n.removeEventListener("keydown",r),e)};function sL(t){return ZT(t)&&!fU()}const aL=new WeakSet;function UW(t,e,n={}){const[r,i,s]=pU(t,n),a=o=>{const l=o.currentTarget;if(!sL(o)||aL.has(o))return;Qg.add(l),n.stopPropagation&&aL.add(o);const c=e(l,o),u=(f,p)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",h),Qg.has(l)&&Qg.delete(l),sL(f)&&typeof c=="function"&&c(f,{success:p})},d=f=>{u(f,l===window||l===document||n.useGlobalTarget||mU(l,f.target))},h=f=>{u(f,!1)};window.addEventListener("pointerup",d,i),window.addEventListener("pointercancel",h,i)};return r.forEach(o=>{(n.useGlobalTarget?window:o).addEventListener("pointerdown",a,i),Xg(o)&&(o.addEventListener("focus",c=>BW(c,i)),!OW(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),s}function eA(t){return vB(t)&&"ownerSVGElement"in t}const Jg=new WeakMap;let Po;const gU=(t,e,n)=>(r,i)=>i&&i[0]?i[0][t+"Size"]:eA(r)&&"getBBox"in r?r.getBBox()[e]:r[n],jW=gU("inline","width","offsetWidth"),FW=gU("block","height","offsetHeight");function $W({target:t,borderBoxSize:e}){var n;(n=Jg.get(t))==null||n.forEach(r=>{r(t,{get width(){return jW(t,e)},get height(){return FW(t,e)}})})}function VW(t){t.forEach($W)}function GW(){typeof ResizeObserver>"u"||(Po=new ResizeObserver(VW))}function HW(t,e){Po||GW();const n=dU(t);return n.forEach(r=>{let i=Jg.get(r);i||(i=new Set,Jg.set(r,i)),i.add(e),Po==null||Po.observe(r)}),()=>{n.forEach(r=>{const i=Jg.get(r);i==null||i.delete(e),i!=null&&i.size||Po==null||Po.unobserve(r)})}}const Zg=new Set;let Ju;function KW(){Ju=()=>{const t={get width(){return window.innerWidth},get height(){return window.innerHeight}};Zg.forEach(e=>e(t))},window.addEventListener("resize",Ju)}function zW(t){return Zg.add(t),Ju||KW(),()=>{Zg.delete(t),!Zg.size&&typeof Ju=="function"&&(window.removeEventListener("resize",Ju),Ju=void 0)}}function oL(t,e){return typeof t=="function"?zW(t):HW(t,e)}function qW(t){return eA(t)&&t.tagName==="svg"}const WW=[...lU,rr,Ps],YW=t=>WW.find(oU(t)),lL=()=>({translate:0,scale:1,origin:0,originPoint:0}),Zu=()=>({x:lL(),y:lL()}),cL=()=>({min:0,max:0}),dr=()=>({x:cL(),y:cL()}),XW=new WeakMap;function hv(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function up(t){return typeof t=="string"||Array.isArray(t)}const tA=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],nA=["initial",...tA];function fv(t){return hv(t.animate)||nA.some(e=>up(t[e]))}function yU(t){return!!(fv(t)||t.variants)}function QW(t,e,n){for(const r in e){const i=e[r],s=n[r];if(Br(i))t.addValue(r,i);else if(Br(s))t.addValue(r,Yd(i,{owner:t}));else if(s!==i)if(t.hasValue(r)){const a=t.getValue(r);a.liveStyle===!0?a.jump(i):a.hasAnimated||a.set(i)}else{const a=t.getStaticValue(r);t.addValue(r,Yd(a!==void 0?a:i,{owner:t}))}}for(const r in n)e[r]===void 0&&t.removeValue(r);return e}const ZS={current:null},vU={current:!1},JW=typeof window<"u";function ZW(){if(vU.current=!0,!!JW)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>ZS.current=t.matches;t.addEventListener("change",e),e()}else ZS.current=!1}const uL=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let i0={};function _U(t){i0=t}function eY(){return i0}class tY{scrapeMotionValuesFromProps(e,n,r){return{}}constructor({parent:e,props:n,presenceContext:r,reducedMotionConfig:i,skipAnimations:s,blockInitialAnimation:a,visualState:o},l={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.shouldSkipAnimations=!1,this.values=new Map,this.KeyframeResolver=zT,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const f=ni.now();this.renderScheduledAt<f&&(this.renderScheduledAt=f,gn.render(this.render,!1,!0))};const{latestValues:c,renderState:u}=o;this.latestValues=c,this.baseTarget={...c},this.initialValues=n.initial?{...c}:{},this.renderState=u,this.parent=e,this.props=n,this.presenceContext=r,this.depth=e?e.depth+1:0,this.reducedMotionConfig=i,this.skipAnimationsConfig=s,this.options=l,this.blockInitialAnimation=!!a,this.isControllingVariants=fv(n),this.isVariantNode=yU(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:d,...h}=this.scrapeMotionValuesFromProps(n,{},this);for(const f in h){const p=h[f];c[f]!==void 0&&Br(p)&&p.set(c[f])}}mount(e){var n,r;if(this.hasBeenMounted)for(const i in this.initialValues)(n=this.values.get(i))==null||n.jump(this.initialValues[i]),this.latestValues[i]=this.initialValues[i];this.current=e,XW.set(e,this),this.projection&&!this.projection.instance&&this.projection.mount(e),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((i,s)=>this.bindToMotionValue(s,i)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(vU.current||ZW(),this.shouldReduceMotion=ZS.current),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,(r=this.parent)==null||r.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){var e;this.projection&&this.projection.unmount(),wl(this.notifyUpdate),wl(this.render),this.valueSubscriptions.forEach(n=>n()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),(e=this.parent)==null||e.removeChild(this);for(const n in this.events)this.events[n].clear();for(const n in this.features){const r=this.features[n];r&&(r.unmount(),r.isMounted=!1)}this.current=null}addChild(e){this.children.add(e),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(e)}removeChild(e){this.children.delete(e),this.enteringChildren&&this.enteringChildren.delete(e)}bindToMotionValue(e,n){if(this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)(),n.accelerate&&ZB.has(e)&&this.current instanceof HTMLElement){const{factory:a,keyframes:o,times:l,ease:c,duration:u}=n.accelerate,d=new QB({element:this.current,name:e,keyframes:o,times:l,ease:c,duration:Hi(u)}),h=a(d);this.valueSubscriptions.set(e,()=>{h(),d.cancel()});return}const r=_h.has(e);r&&this.onBindTransform&&this.onBindTransform();const i=n.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&gn.preRender(this.notifyUpdate),r&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let s;typeof window<"u"&&window.MotionCheckAppearSync&&(s=window.MotionCheckAppearSync(this,e,n)),this.valueSubscriptions.set(e,()=>{i(),s&&s(),n.owner&&n.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e="animation";for(e in i0){const n=i0[e];if(!n)continue;const{isEnabled:r,Feature:i}=n;if(!this.features[e]&&i&&r(this.props)&&(this.features[e]=new i(this)),this.features[e]){const s=this.features[e];s.isMounted?s.update():(s.mount(),s.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):dr()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,n){this.latestValues[e]=n}update(e,n){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let r=0;r<uL.length;r++){const i=uL[r];this.propEventSubscriptions[i]&&(this.propEventSubscriptions[i](),delete this.propEventSubscriptions[i]);const s="on"+i,a=e[s];a&&(this.propEventSubscriptions[i]=this.on(i,a))}this.prevMotionValues=QW(this,this.scrapeMotionValuesFromProps(e,this.prevProps||{},this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(e){return this.props.variants?this.props.variants[e]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(e){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(e),()=>n.variantChildren.delete(e)}addValue(e,n){const r=this.values.get(e);n!==r&&(r&&this.removeValue(e),this.bindToMotionValue(e,n),this.values.set(e,n),this.latestValues[e]=n.get())}removeValue(e){this.values.delete(e);const n=this.valueSubscriptions.get(e);n&&(n(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,n){if(this.props.values&&this.props.values[e])return this.props.values[e];let r=this.values.get(e);return r===void 0&&n!==void 0&&(r=Yd(n===null?void 0:n,{owner:this}),this.addValue(e,r)),r}readValue(e,n){let r=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return r!=null&&(typeof r=="string"&&(yB(r)||_B(r))?r=parseFloat(r):!YW(r)&&Ps.test(n)&&(r=uU(e,n)),this.setBaseTarget(e,Br(r)?r.get():r)),Br(r)?r.get():r}setBaseTarget(e,n){this.baseTarget[e]=n}getBaseTarget(e){var s;const{initial:n}=this.props;let r;if(typeof n=="string"||typeof n=="object"){const a=YT(this.props,n,(s=this.presenceContext)==null?void 0:s.custom);a&&(r=a[e])}if(n&&r!==void 0)return r;const i=this.getBaseTargetFromProps(this.props,e);return i!==void 0&&!Br(i)?i:this.initialValues[e]!==void 0&&r===void 0?void 0:this.baseTarget[e]}on(e,n){return this.events[e]||(this.events[e]=new BT),this.events[e].add(n)}notify(e,...n){this.events[e]&&this.events[e].notify(...n)}scheduleRenderMicrotask(){JT.render(this.render)}}class bU extends tY{constructor(){super(...arguments),this.KeyframeResolver=LW}sortInstanceNodePosition(e,n){return e.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(e,n){const r=e.style;return r?r[n]:void 0}removeValueFromRenderState(e,{vars:n,style:r}){delete n[e],delete r[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:e}=this.props;Br(e)&&(this.childSubscription=e.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}class Nl{constructor(e){this.isMounted=!1,this.node=e}update(){}}function xU({top:t,left:e,right:n,bottom:r}){return{x:{min:e,max:n},y:{min:t,max:r}}}function nY({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function rY(t,e){if(!e)return t;const n=e({x:t.left,y:t.top}),r=e({x:t.right,y:t.bottom});return{top:n.y,left:n.x,bottom:r.y,right:r.x}}function eb(t){return t===void 0||t===1}function eE({scale:t,scaleX:e,scaleY:n}){return!eb(t)||!eb(e)||!eb(n)}function Jl(t){return eE(t)||SU(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function SU(t){return dL(t.x)||dL(t.y)}function dL(t){return t&&t!=="0%"}function s0(t,e,n){const r=t-n,i=e*r;return n+i}function hL(t,e,n,r,i){return i!==void 0&&(t=s0(t,i,r)),s0(t,n,r)+e}function tE(t,e=0,n=1,r,i){t.min=hL(t.min,e,n,r,i),t.max=hL(t.max,e,n,r,i)}function EU(t,{x:e,y:n}){tE(t.x,e.translate,e.scale,e.originPoint),tE(t.y,n.translate,n.scale,n.originPoint)}const fL=.999999999999,pL=1.0000000000001;function iY(t,e,n,r=!1){var o;const i=n.length;if(!i)return;e.x=e.y=1;let s,a;for(let l=0;l<i;l++){s=n[l],a=s.projectionDelta;const{visualElement:c}=s.options;c&&c.props.style&&c.props.style.display==="contents"||(r&&s.options.layoutScroll&&s.scroll&&s!==s.root&&(Qs(t.x,-s.scroll.offset.x),Qs(t.y,-s.scroll.offset.y)),a&&(e.x*=a.x.scale,e.y*=a.y.scale,EU(t,a)),r&&Jl(s.latestValues)&&ey(t,s.latestValues,(o=s.layout)==null?void 0:o.layoutBox))}e.x<pL&&e.x>fL&&(e.x=1),e.y<pL&&e.y>fL&&(e.y=1)}function Qs(t,e){t.min+=e,t.max+=e}function mL(t,e,n,r,i=.5){const s=An(t.min,t.max,i);tE(t,e,n,s,r)}function gL(t,e){return typeof t=="string"?parseFloat(t)/100*(e.max-e.min):t}function ey(t,e,n){const r=n??t;mL(t.x,gL(e.x,r.x),e.scaleX,e.scale,e.originX),mL(t.y,gL(e.y,r.y),e.scaleY,e.scale,e.originY)}function wU(t,e){return xU(rY(t.getBoundingClientRect(),e))}function sY(t,e,n){const r=wU(t,n),{scroll:i}=e;return i&&(Qs(r.x,i.offset.x),Qs(r.y,i.offset.y)),r}const aY={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},oY=vh.length;function lY(t,e,n){let r="",i=!0;for(let s=0;s<oY;s++){const a=vh[s],o=t[a];if(o===void 0)continue;let l=!0;if(typeof o=="number")l=o===(a.startsWith("scale")?1:0);else{const c=parseFloat(o);l=a.startsWith("scale")?c===1:c===0}if(!l||n){const c=hU(o,QT[a]);if(!l){i=!1;const u=aY[a]||a;r+=`${u}(${c}) `}n&&(e[a]=c)}}return r=r.trim(),n?r=n(e,i?"":r):i&&(r="none"),r}function rA(t,e,n){const{style:r,vars:i,transformOrigin:s}=t;let a=!1,o=!1;for(const l in e){const c=e[l];if(_h.has(l)){a=!0;continue}else if(OB(l)){i[l]=c;continue}else{const u=hU(c,QT[l]);l.startsWith("origin")?(o=!0,s[l]=u):r[l]=u}}if(e.transform||(a||n?r.transform=lY(e,t.transform,n):r.transform&&(r.transform="none")),o){const{originX:l="50%",originY:c="50%",originZ:u=0}=s;r.transformOrigin=`${l} ${c} ${u}`}}function TU(t,{style:e,vars:n},r,i){const s=t.style;let a;for(a in e)s[a]=e[a];i==null||i.applyProjectionStyles(s,r);for(a in n)s.setProperty(a,n[a])}function yL(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const $h={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(at.test(t))t=parseFloat(t);else return t;const n=yL(t,e.target.x),r=yL(t,e.target.y);return`${n}% ${r}%`}},cY={correct:(t,{treeScale:e,projectionDelta:n})=>{const r=t,i=Ps.parse(t);if(i.length>5)return r;const s=Ps.createTransformer(t),a=typeof i[0]!="number"?1:0,o=n.x.scale*e.x,l=n.y.scale*e.y;i[0+a]/=o,i[1+a]/=l;const c=An(o,l,.5);return typeof i[2+a]=="number"&&(i[2+a]/=c),typeof i[3+a]=="number"&&(i[3+a]/=c),s(i)}},nE={borderRadius:{...$h,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:$h,borderTopRightRadius:$h,borderBottomLeftRadius:$h,borderBottomRightRadius:$h,boxShadow:cY};function AU(t,{layout:e,layoutId:n}){return _h.has(t)||t.startsWith("origin")||(e||n!==void 0)&&(!!nE[t]||t==="opacity")}function iA(t,e,n){var a;const r=t.style,i=e==null?void 0:e.style,s={};if(!r)return s;for(const o in r)(Br(r[o])||i&&Br(i[o])||AU(o,t)||((a=n==null?void 0:n.getValue(o))==null?void 0:a.liveStyle)!==void 0)&&(s[o]=r[o]);return s}function uY(t){return window.getComputedStyle(t)}class dY extends bU{constructor(){super(...arguments),this.type="html",this.renderInstance=TU}readValueFromInstance(e,n){var r;if(_h.has(n))return(r=this.projection)!=null&&r.isProjecting?VS(n):I7(e,n);{const i=uY(e),s=(OB(n)?i.getPropertyValue(n):i[n])||0;return typeof s=="string"?s.trim():s}}measureInstanceViewportBox(e,{transformPagePoint:n}){return wU(e,n)}build(e,n,r){rA(e,n,r.transformTemplate)}scrapeMotionValuesFromProps(e,n,r){return iA(e,n,r)}}const hY={offset:"stroke-dashoffset",array:"stroke-dasharray"},fY={offset:"strokeDashoffset",array:"strokeDasharray"};function pY(t,e,n=1,r=0,i=!0){t.pathLength=1;const s=i?hY:fY;t[s.offset]=`${-r}`,t[s.array]=`${e} ${n}`}const mY=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function RU(t,{attrX:e,attrY:n,attrScale:r,pathLength:i,pathSpacing:s=1,pathOffset:a=0,...o},l,c,u){if(rA(t,o,c),l){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:d,style:h}=t;d.transform&&(h.transform=d.transform,delete d.transform),(h.transform||d.transformOrigin)&&(h.transformOrigin=d.transformOrigin??"50% 50%",delete d.transformOrigin),h.transform&&(h.transformBox=(u==null?void 0:u.transformBox)??"fill-box",delete d.transformBox);for(const f of mY)d[f]!==void 0&&(h[f]=d[f],delete d[f]);e!==void 0&&(d.x=e),n!==void 0&&(d.y=n),r!==void 0&&(d.scale=r),i!==void 0&&pY(d,i,s,a,!1)}const CU=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]),LU=t=>typeof t=="string"&&t.toLowerCase()==="svg";function gY(t,e,n,r){TU(t,e,void 0,r);for(const i in e.attrs)t.setAttribute(CU.has(i)?i:XT(i),e.attrs[i])}function kU(t,e,n){const r=iA(t,e,n);for(const i in t)if(Br(t[i])||Br(e[i])){const s=vh.indexOf(i)!==-1?"attr"+i.charAt(0).toUpperCase()+i.substring(1):i;r[s]=t[i]}return r}class yY extends bU{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=dr}getBaseTargetFromProps(e,n){return e[n]}readValueFromInstance(e,n){if(_h.has(n)){const r=cU(n);return r&&r.default||0}return n=CU.has(n)?n:XT(n),e.getAttribute(n)}scrapeMotionValuesFromProps(e,n,r){return kU(e,n,r)}build(e,n,r){RU(e,n,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(e,n,r,i){gY(e,n,r,i)}mount(e){this.isSVGTag=LU(e.tagName),super.mount(e)}}const vY=nA.length;function IU(t){if(!t)return;if(!t.isControllingVariants){const n=t.parent?IU(t.parent)||{}:{};return t.props.initial!==void 0&&(n.initial=t.props.initial),n}const e={};for(let n=0;n<vY;n++){const r=nA[n],i=t.props[r];(up(i)||i===!1)&&(e[r]=i)}return e}function PU(t,e){if(!Array.isArray(e))return!1;const n=e.length;if(n!==t.length)return!1;for(let r=0;r<n;r++)if(e[r]!==t[r])return!1;return!0}const _Y=[...tA].reverse(),bY=tA.length;function xY(t){return e=>Promise.all(e.map(({animation:n,options:r})=>vW(t,n,r)))}function SY(t){let e=xY(t),n=vL(),r=!0,i=!1;const s=c=>(u,d)=>{var f;const h=kc(t,d,c==="exit"?(f=t.presenceContext)==null?void 0:f.custom:void 0);if(h){const{transition:p,transitionEnd:m,...g}=h;u={...u,...g,...m}}return u};function a(c){e=c(t)}function o(c){const{props:u}=t,d=IU(t.parent)||{},h=[],f=new Set;let p={},m=1/0;for(let b=0;b<bY;b++){const v=_Y[b],S=n[v],E=u[v]!==void 0?u[v]:d[v],L=up(E),U=v===c?S.isActive:null;U===!1&&(m=b);let O=E===d[v]&&E!==u[v]&&L;if(O&&(r||i)&&t.manuallyAnimateOnMount&&(O=!1),S.protectedKeys={...p},!S.isActive&&U===null||!E&&!S.prevProp||hv(E)||typeof E=="boolean")continue;if(v==="exit"&&S.isActive&&U!==!0){S.prevResolvedValues&&(p={...p,...S.prevResolvedValues});continue}const k=EY(S.prevProp,E);let I=k||v===c&&S.isActive&&!O&&L||b>m&&L,R=!1;const M=Array.isArray(E)?E:[E];let z=M.reduce(s(v),{});U===!1&&(z={});const{prevResolvedValues:Z={}}=S,W={...Z,...z},re=Q=>{I=!0,f.has(Q)&&(R=!0,f.delete(Q)),S.needsAnimating[Q]=!0;const G=t.getValue(Q);G&&(G.liveStyle=!1)};for(const Q in W){const G=z[Q],H=Z[Q];if(p.hasOwnProperty(Q))continue;let Y=!1;WS(G)&&WS(H)?Y=!PU(G,H):Y=G!==H,Y?G!=null?re(Q):f.add(Q):G!==void 0&&f.has(Q)?re(Q):S.protectedKeys[Q]=!0}S.prevProp=E,S.prevResolvedValues=z,S.isActive&&(p={...p,...z}),(r||i)&&t.blockInitialAnimation&&(I=!1);const X=O&&k;I&&(!X||R)&&h.push(...M.map(Q=>{const G={type:v};if(typeof Q=="string"&&(r||i)&&!X&&t.manuallyAnimateOnMount&&t.parent){const{parent:H}=t,Y=kc(H,Q);if(H.enteringChildren&&Y){const{delayChildren:ie}=Y.transition||{};G.delay=eU(H.enteringChildren,t,ie)}}return{animation:Q,options:G}}))}if(f.size){const b={};if(typeof u.initial!="boolean"){const v=kc(t,Array.isArray(u.initial)?u.initial[0]:u.initial);v&&v.transition&&(b.transition=v.transition)}f.forEach(v=>{const S=t.getBaseTarget(v),E=t.getValue(v);E&&(E.liveStyle=!0),b[v]=S??null}),h.push({animation:b})}let g=!!h.length;return r&&(u.initial===!1||u.initial===u.animate)&&!t.manuallyAnimateOnMount&&(g=!1),r=!1,i=!1,g?e(h):Promise.resolve()}function l(c,u){var h;if(n[c].isActive===u)return Promise.resolve();(h=t.variantChildren)==null||h.forEach(f=>{var p;return(p=f.animationState)==null?void 0:p.setActive(c,u)}),n[c].isActive=u;const d=o(c);for(const f in n)n[f].protectedKeys={};return d}return{animateChanges:o,setActive:l,setAnimateFunction:a,getState:()=>n,reset:()=>{n=vL(),i=!0}}}function EY(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!PU(e,t):!1}function Gl(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function vL(){return{animate:Gl(!0),whileInView:Gl(),whileHover:Gl(),whileTap:Gl(),whileDrag:Gl(),whileFocus:Gl(),exit:Gl()}}function rE(t,e){t.min=e.min,t.max=e.max}function Es(t,e){rE(t.x,e.x),rE(t.y,e.y)}function _L(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}const DU=1e-4,wY=1-DU,TY=1+DU,OU=.01,AY=0-OU,RY=0+OU;function ri(t){return t.max-t.min}function CY(t,e,n){return Math.abs(t-e)<=n}function bL(t,e,n,r=.5){t.origin=r,t.originPoint=An(e.min,e.max,t.origin),t.scale=ri(n)/ri(e),t.translate=An(n.min,n.max,t.origin)-t.originPoint,(t.scale>=wY&&t.scale<=TY||isNaN(t.scale))&&(t.scale=1),(t.translate>=AY&&t.translate<=RY||isNaN(t.translate))&&(t.translate=0)}function Tf(t,e,n,r){bL(t.x,e.x,n.x,r?r.originX:void 0),bL(t.y,e.y,n.y,r?r.originY:void 0)}function xL(t,e,n,r=0){const i=r?An(n.min,n.max,r):n.min;t.min=i+e.min,t.max=t.min+ri(e)}function LY(t,e,n,r){xL(t.x,e.x,n.x,r==null?void 0:r.x),xL(t.y,e.y,n.y,r==null?void 0:r.y)}function SL(t,e,n,r=0){const i=r?An(n.min,n.max,r):n.min;t.min=e.min-i,t.max=t.min+ri(e)}function a0(t,e,n,r){SL(t.x,e.x,n.x,r==null?void 0:r.x),SL(t.y,e.y,n.y,r==null?void 0:r.y)}function EL(t,e,n,r,i){return t-=e,t=s0(t,1/n,r),i!==void 0&&(t=s0(t,1/i,r)),t}function kY(t,e=0,n=1,r=.5,i,s=t,a=t){if(ha.test(e)&&(e=parseFloat(e),e=An(a.min,a.max,e/100)-a.min),typeof e!="number")return;let o=An(s.min,s.max,r);t===s&&(o-=e),t.min=EL(t.min,e,n,o,i),t.max=EL(t.max,e,n,o,i)}function wL(t,e,[n,r,i],s,a){kY(t,e[n],e[r],e[i],e.scale,s,a)}const IY=["x","scaleX","originX"],PY=["y","scaleY","originY"];function TL(t,e,n,r){wL(t.x,e,IY,n?n.x:void 0,r?r.x:void 0),wL(t.y,e,PY,n?n.y:void 0,r?r.y:void 0)}function AL(t){return t.translate===0&&t.scale===1}function NU(t){return AL(t.x)&&AL(t.y)}function RL(t,e){return t.min===e.min&&t.max===e.max}function DY(t,e){return RL(t.x,e.x)&&RL(t.y,e.y)}function CL(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function MU(t,e){return CL(t.x,e.x)&&CL(t.y,e.y)}function LL(t){return ri(t.x)/ri(t.y)}function kL(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}function Ks(t){return[t("x"),t("y")]}function OY(t,e,n){let r="";const i=t.x.translate/e.x,s=t.y.translate/e.y,a=(n==null?void 0:n.z)||0;if((i||s||a)&&(r=`translate3d(${i}px, ${s}px, ${a}px) `),(e.x!==1||e.y!==1)&&(r+=`scale(${1/e.x}, ${1/e.y}) `),n){const{transformPerspective:c,rotate:u,rotateX:d,rotateY:h,skewX:f,skewY:p}=n;c&&(r=`perspective(${c}px) ${r}`),u&&(r+=`rotate(${u}deg) `),d&&(r+=`rotateX(${d}deg) `),h&&(r+=`rotateY(${h}deg) `),f&&(r+=`skewX(${f}deg) `),p&&(r+=`skewY(${p}deg) `)}const o=t.x.scale*e.x,l=t.y.scale*e.y;return(o!==1||l!==1)&&(r+=`scale(${o}, ${l})`),r||"none"}const BU=["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],NY=BU.length,IL=t=>typeof t=="string"?parseFloat(t):t,PL=t=>typeof t=="number"||at.test(t);function MY(t,e,n,r,i,s){i?(t.opacity=An(0,n.opacity??1,BY(r)),t.opacityExit=An(e.opacity??1,0,UY(r))):s&&(t.opacity=An(e.opacity??1,n.opacity??1,r));for(let a=0;a<NY;a++){const o=BU[a];let l=DL(e,o),c=DL(n,o);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||PL(l)===PL(c)?(t[o]=Math.max(An(IL(l),IL(c),r),0),(ha.test(c)||ha.test(l))&&(t[o]+="%")):t[o]=c}(e.rotate||n.rotate)&&(t.rotate=An(e.rotate||0,n.rotate||0,r))}function DL(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const BY=UU(0,.5,CB),UY=UU(.5,.95,fs);function UU(t,e,n){return r=>r<t?0:r>e?1:n(lp(t,e,r))}function jY(t,e,n){const r=Br(t)?t:Yd(t);return r.start(WT("",r,e,n)),r.animation}function dp(t,e,n,r={passive:!0}){return t.addEventListener(e,n,r),()=>t.removeEventListener(e,n)}const FY=(t,e)=>t.depth-e.depth;class $Y{constructor(){this.children=[],this.isDirty=!1}add(e){NT(this.children,e),this.isDirty=!0}remove(e){Zy(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(FY),this.isDirty=!1,this.children.forEach(e)}}function VY(t,e){const n=ni.now(),r=({timestamp:i})=>{const s=i-n;s>=e&&(wl(r),t(s-e))};return gn.setup(r,!0),()=>wl(r)}function ty(t){return Br(t)?t.get():t}class GY{constructor(){this.members=[]}add(e){NT(this.members,e);for(let n=this.members.length-1;n>=0;n--){const r=this.members[n];if(r===e||r===this.lead||r===this.prevLead)continue;const i=r.instance;(!i||i.isConnected===!1)&&!r.snapshot&&(Zy(this.members,r),r.unmount())}e.scheduleRender()}remove(e){if(Zy(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(e){var n;for(let r=this.members.indexOf(e)-1;r>=0;r--){const i=this.members[r];if(i.isPresent!==!1&&((n=i.instance)==null?void 0:n.isConnected)!==!1)return this.promote(i),!0}return!1}promote(e,n){var i;const r=this.lead;if(e!==r&&(this.prevLead=r,this.lead=e,e.show(),r)){r.updateSnapshot(),e.scheduleRender();const{layoutDependency:s}=r.options,{layoutDependency:a}=e.options;(s===void 0||s!==a)&&(e.resumeFrom=r,n&&(r.preserveOpacity=!0),r.snapshot&&(e.snapshot=r.snapshot,e.snapshot.latestValues=r.animationValues||r.latestValues),(i=e.root)!=null&&i.isUpdating&&(e.isLayoutDirty=!0)),e.options.crossfade===!1&&r.hide()}}exitAnimationComplete(){this.members.forEach(e=>{var n,r,i,s,a;(r=(n=e.options).onExitComplete)==null||r.call(n),(a=(i=e.resumingFrom)==null?void 0:(s=i.options).onExitComplete)==null||a.call(s)})}scheduleRender(){this.members.forEach(e=>e.instance&&e.scheduleRender(!1))}removeLeadSnapshot(){var e;(e=this.lead)!=null&&e.snapshot&&(this.lead.snapshot=void 0)}}const ny={hasAnimatedSinceResize:!0,hasEverUpdated:!1},tb=["","X","Y","Z"],HY=1e3;let KY=0;function nb(t,e,n,r){const{latestValues:i}=e;i[t]&&(n[t]=i[t],e.setStaticValue(t,0),r&&(r[t]=0))}function jU(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const n=sU(e);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:i,layoutId:s}=t.options;window.MotionCancelOptimisedAnimation(n,"transform",gn,!(i||s))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&jU(r)}function FU({attachResizeListener:t,defaultParent:e,measureScroll:n,checkIsScrollRoot:r,resetTransform:i}){return class{constructor(a={},o=e==null?void 0:e()){this.id=KY++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.layoutVersion=0,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(WY),this.nodes.forEach(eX),this.nodes.forEach(tX),this.nodes.forEach(YY)},this.resolvedRelativeTargetAt=0,this.linkedParentVersion=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=a,this.root=o?o.root||o:this,this.path=o?[...o.path,o]:[],this.parent=o,this.depth=o?o.depth+1:0;for(let l=0;l<this.path.length;l++)this.path[l].shouldResetTransform=!0;this.root===this&&(this.nodes=new $Y)}addEventListener(a,o){return this.eventHandlers.has(a)||this.eventHandlers.set(a,new BT),this.eventHandlers.get(a).add(o)}notifyListeners(a,...o){const l=this.eventHandlers.get(a);l&&l.notify(...o)}hasListeners(a){return this.eventHandlers.has(a)}mount(a){if(this.instance)return;this.isSVG=eA(a)&&!qW(a),this.instance=a;const{layoutId:o,layout:l,visualElement:c}=this.options;if(c&&!c.current&&c.mount(a),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(l||o)&&(this.isLayoutDirty=!0),t){let u,d=0;const h=()=>this.root.updateBlockedByResize=!1;gn.read(()=>{d=window.innerWidth}),t(a,()=>{const f=window.innerWidth;f!==d&&(d=f,this.root.updateBlockedByResize=!0,u&&u(),u=VY(h,250),ny.hasAnimatedSinceResize&&(ny.hasAnimatedSinceResize=!1,this.nodes.forEach(ML)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&c&&(o||l)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:d,hasRelativeLayoutChanged:h,layout:f})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const p=this.options.transition||c.getDefaultTransition()||aX,{onLayoutAnimationStart:m,onLayoutAnimationComplete:g}=c.getProps(),b=!this.targetLayout||!MU(this.targetLayout,f),v=!d&&h;if(this.options.layoutRoot||this.resumeFrom||v||d&&(b||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const S={...qT(p,"layout"),onPlay:m,onComplete:g};(c.shouldReduceMotion||this.options.layoutRoot)&&(S.delay=0,S.type=!1),this.startAnimation(S),this.setAnimationOrigin(u,v)}else d||ML(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=f})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const a=this.getStack();a&&a.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),wl(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(nX),this.animationId++)}getTransformTemplate(){const{visualElement:a}=this.options;return a&&a.getProps().transformTemplate}willUpdate(a=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&jU(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let u=0;u<this.path.length;u++){const d=this.path[u];d.shouldResetTransform=!0,(typeof d.latestValues.x=="string"||typeof d.latestValues.y=="string")&&(d.isLayoutDirty=!0),d.updateScroll("snapshot"),d.options.layoutRoot&&d.willUpdate(!1)}const{layoutId:o,layout:l}=this.options;if(o===void 0&&!l)return;const c=this.getTransformTemplate();this.prevTransformTemplateValue=c?c(this.latestValues,""):void 0,this.updateSnapshot(),a&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){const l=this.updateBlockedByResize;this.unblockUpdate(),this.updateBlockedByResize=!1,this.clearAllSnapshots(),l&&this.nodes.forEach(QY),this.nodes.forEach(OL);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(NL);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(JY),this.nodes.forEach(ZY),this.nodes.forEach(zY),this.nodes.forEach(qY)):this.nodes.forEach(NL),this.clearAllSnapshots();const o=ni.now();kr.delta=pa(0,1e3/60,o-kr.timestamp),kr.timestamp=o,kr.isProcessing=!0,q_.update.process(kr),q_.preRender.process(kr),q_.render.process(kr),kr.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,JT.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(XY),this.sharedNodes.forEach(rX)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,gn.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){gn.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!ri(this.snapshot.measuredBox.x)&&!ri(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let l=0;l<this.path.length;l++)this.path[l].updateScroll();const a=this.layout;this.layout=this.measure(!1),this.layoutVersion++,this.layoutCorrected||(this.layoutCorrected=dr()),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:o}=this.options;o&&o.notify("LayoutMeasure",this.layout.layoutBox,a?a.layoutBox:void 0)}updateScroll(a="measure"){let o=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===a&&(o=!1),o&&this.instance){const l=r(this.instance);this.scroll={animationId:this.root.animationId,phase:a,isRoot:l,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:l}}}resetTransform(){if(!i)return;const a=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,o=this.projectionDelta&&!NU(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,u=c!==this.prevTransformTemplateValue;a&&this.instance&&(o||Jl(this.latestValues)||u)&&(i(this.instance,c),this.shouldResetTransform=!1,this.scheduleRender())}measure(a=!0){const o=this.measurePageBox();let l=this.removeElementScroll(o);return a&&(l=this.removeTransform(l)),oX(l),{animationId:this.root.animationId,measuredBox:o,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){var c;const{visualElement:a}=this.options;if(!a)return dr();const o=a.measureViewportBox();if(!(((c=this.scroll)==null?void 0:c.wasRoot)||this.path.some(lX))){const{scroll:u}=this.root;u&&(Qs(o.x,u.offset.x),Qs(o.y,u.offset.y))}return o}removeElementScroll(a){var l;const o=dr();if(Es(o,a),(l=this.scroll)!=null&&l.wasRoot)return o;for(let c=0;c<this.path.length;c++){const u=this.path[c],{scroll:d,options:h}=u;u!==this.root&&d&&h.layoutScroll&&(d.wasRoot&&Es(o,a),Qs(o.x,d.offset.x),Qs(o.y,d.offset.y))}return o}applyTransform(a,o=!1,l){var u,d;const c=l||dr();Es(c,a);for(let h=0;h<this.path.length;h++){const f=this.path[h];!o&&f.options.layoutScroll&&f.scroll&&f!==f.root&&(Qs(c.x,-f.scroll.offset.x),Qs(c.y,-f.scroll.offset.y)),Jl(f.latestValues)&&ey(c,f.latestValues,(u=f.layout)==null?void 0:u.layoutBox)}return Jl(this.latestValues)&&ey(c,this.latestValues,(d=this.layout)==null?void 0:d.layoutBox),c}removeTransform(a){var l;const o=dr();Es(o,a);for(let c=0;c<this.path.length;c++){const u=this.path[c];if(!Jl(u.latestValues))continue;let d;u.instance&&(eE(u.latestValues)&&u.updateSnapshot(),d=dr(),Es(d,u.measurePageBox())),TL(o,u.latestValues,(l=u.snapshot)==null?void 0:l.layoutBox,d)}return Jl(this.latestValues)&&TL(o,this.latestValues),o}setTargetDelta(a){this.targetDelta=a,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(a){this.options={...this.options,...a,crossfade:a.crossfade!==void 0?a.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==kr.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(a=!1){var f;const o=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=o.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=o.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=o.isSharedProjectionDirty);const l=!!this.resumingFrom||this!==o;if(!(a||l&&this.isSharedProjectionDirty||this.isProjectionDirty||(f=this.parent)!=null&&f.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:u,layoutId:d}=this.options;if(!this.layout||!(u||d))return;this.resolvedRelativeTargetAt=kr.timestamp;const h=this.getClosestProjectingParent();h&&this.linkedParentVersion!==h.layoutVersion&&!h.options.layoutRoot&&this.removeRelativeTarget(),!this.targetDelta&&!this.relativeTarget&&(this.options.layoutAnchor!==!1&&h&&h.layout?this.createRelativeTarget(h,this.layout.layoutBox,h.layout.layoutBox):this.removeRelativeTarget()),!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=dr(),this.targetWithTransforms=dr()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),LY(this.target,this.relativeTarget,this.relativeParent.target,this.options.layoutAnchor||void 0)):this.targetDelta?(this.resumingFrom?this.applyTransform(this.layout.layoutBox,!1,this.target):Es(this.target,this.layout.layoutBox),EU(this.target,this.targetDelta)):Es(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget&&(this.attemptToResolveRelativeTarget=!1,this.options.layoutAnchor!==!1&&h&&!!h.resumingFrom==!!this.resumingFrom&&!h.options.layoutScroll&&h.target&&this.animationProgress!==1?this.createRelativeTarget(h,this.target,h.target):this.relativeParent=this.relativeTarget=void 0))}getClosestProjectingParent(){if(!(!this.parent||eE(this.parent.latestValues)||SU(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}createRelativeTarget(a,o,l){this.relativeParent=a,this.linkedParentVersion=a.layoutVersion,this.forceRelativeParentToResolveTarget(),this.relativeTarget=dr(),this.relativeTargetOrigin=dr(),a0(this.relativeTargetOrigin,o,l,this.options.layoutAnchor||void 0),Es(this.relativeTarget,this.relativeTargetOrigin)}removeRelativeTarget(){this.relativeParent=this.relativeTarget=void 0}calcProjection(){var p;const a=this.getLead(),o=!!this.resumingFrom||this!==a;let l=!0;if((this.isProjectionDirty||(p=this.parent)!=null&&p.isProjectionDirty)&&(l=!1),o&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(l=!1),this.resolvedRelativeTargetAt===kr.timestamp&&(l=!1),l)return;const{layout:c,layoutId:u}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(c||u))return;Es(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,h=this.treeScale.y;iY(this.layoutCorrected,this.treeScale,this.path,o),a.layout&&!a.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(a.target=a.layout.layoutBox,a.targetWithTransforms=dr());const{target:f}=a;if(!f){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(_L(this.prevProjectionDelta.x,this.projectionDelta.x),_L(this.prevProjectionDelta.y,this.projectionDelta.y)),Tf(this.projectionDelta,this.layoutCorrected,f,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==h||!kL(this.projectionDelta.x,this.prevProjectionDelta.x)||!kL(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",f))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(a=!0){var o;if((o=this.options.visualElement)==null||o.scheduleRender(),a){const l=this.getStack();l&&l.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=Zu(),this.projectionDelta=Zu(),this.projectionDeltaWithTransform=Zu()}setAnimationOrigin(a,o=!1){const l=this.snapshot,c=l?l.latestValues:{},u={...this.latestValues},d=Zu();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!o;const h=dr(),f=l?l.source:void 0,p=this.layout?this.layout.source:void 0,m=f!==p,g=this.getStack(),b=!g||g.members.length<=1,v=!!(m&&!b&&this.options.crossfade===!0&&!this.path.some(sX));this.animationProgress=0;let S;this.mixTargetDelta=E=>{const L=E/1e3;BL(d.x,a.x,L),BL(d.y,a.y,L),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(a0(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),iX(this.relativeTarget,this.relativeTargetOrigin,h,L),S&&DY(this.relativeTarget,S)&&(this.isProjectionDirty=!1),S||(S=dr()),Es(S,this.relativeTarget)),m&&(this.animationValues=u,MY(u,c,this.latestValues,L,v,b)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=L},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(a){var o,l,c;this.notifyListeners("animationStart"),(o=this.currentAnimation)==null||o.stop(),(c=(l=this.resumingFrom)==null?void 0:l.currentAnimation)==null||c.stop(),this.pendingAnimation&&(wl(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=gn.update(()=>{ny.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Yd(0)),this.motionValue.jump(0,!1),this.currentAnimation=jY(this.motionValue,[0,1e3],{...a,velocity:0,isSync:!0,onUpdate:u=>{this.mixTargetDelta(u),a.onUpdate&&a.onUpdate(u)},onStop:()=>{},onComplete:()=>{a.onComplete&&a.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const a=this.getStack();a&&a.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(HY),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const a=this.getLead();let{targetWithTransforms:o,target:l,layout:c,latestValues:u}=a;if(!(!o||!l||!c)){if(this!==a&&this.layout&&c&&$U(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||dr();const d=ri(this.layout.layoutBox.x);l.x.min=a.target.x.min,l.x.max=l.x.min+d;const h=ri(this.layout.layoutBox.y);l.y.min=a.target.y.min,l.y.max=l.y.min+h}Es(o,l),ey(o,u),Tf(this.projectionDeltaWithTransform,this.layoutCorrected,o,u)}}registerSharedNode(a,o){this.sharedNodes.has(a)||this.sharedNodes.set(a,new GY),this.sharedNodes.get(a).add(o);const c=o.options.initialPromotionConfig;o.promote({transition:c?c.transition:void 0,preserveFollowOpacity:c&&c.shouldPreserveFollowOpacity?c.shouldPreserveFollowOpacity(o):void 0})}isLead(){const a=this.getStack();return a?a.lead===this:!0}getLead(){var o;const{layoutId:a}=this.options;return a?((o=this.getStack())==null?void 0:o.lead)||this:this}getPrevLead(){var o;const{layoutId:a}=this.options;return a?(o=this.getStack())==null?void 0:o.prevLead:void 0}getStack(){const{layoutId:a}=this.options;if(a)return this.root.sharedNodes.get(a)}promote({needsReset:a,transition:o,preserveFollowOpacity:l}={}){const c=this.getStack();c&&c.promote(this,l),a&&(this.projectionDelta=void 0,this.needsReset=!0),o&&this.setOptions({transition:o})}relegate(){const a=this.getStack();return a?a.relegate(this):!1}resetSkewAndRotation(){const{visualElement:a}=this.options;if(!a)return;let o=!1;const{latestValues:l}=a;if((l.z||l.rotate||l.rotateX||l.rotateY||l.rotateZ||l.skewX||l.skewY)&&(o=!0),!o)return;const c={};l.z&&nb("z",a,c,this.animationValues);for(let u=0;u<tb.length;u++)nb(`rotate${tb[u]}`,a,c,this.animationValues),nb(`skew${tb[u]}`,a,c,this.animationValues);a.render();for(const u in c)a.setStaticValue(u,c[u]),this.animationValues&&(this.animationValues[u]=c[u]);a.scheduleRender()}applyProjectionStyles(a,o){if(!this.instance||this.isSVG)return;if(!this.isVisible){a.visibility="hidden";return}const l=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,a.visibility="",a.opacity="",a.pointerEvents=ty(o==null?void 0:o.pointerEvents)||"",a.transform=l?l(this.latestValues,""):"none";return}const c=this.getLead();if(!this.projectionDelta||!this.layout||!c.target){this.options.layoutId&&(a.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,a.pointerEvents=ty(o==null?void 0:o.pointerEvents)||""),this.hasProjected&&!Jl(this.latestValues)&&(a.transform=l?l({},""):"none",this.hasProjected=!1);return}a.visibility="";const u=c.animationValues||c.latestValues;this.applyTransformsToTarget();let d=OY(this.projectionDeltaWithTransform,this.treeScale,u);l&&(d=l(u,d)),a.transform=d;const{x:h,y:f}=this.projectionDelta;a.transformOrigin=`${h.origin*100}% ${f.origin*100}% 0`,c.animationValues?a.opacity=c===this?u.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:u.opacityExit:a.opacity=c===this?u.opacity!==void 0?u.opacity:"":u.opacityExit!==void 0?u.opacityExit:0;for(const p in nE){if(u[p]===void 0)continue;const{correct:m,applyTo:g,isCSSVariable:b}=nE[p],v=d==="none"?u[p]:m(u[p],c);if(g){const S=g.length;for(let E=0;E<S;E++)a[g[E]]=v}else b?this.options.visualElement.renderState.vars[p]=v:a[p]=v}this.options.layoutId&&(a.pointerEvents=c===this?ty(o==null?void 0:o.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(a=>{var o;return(o=a.currentAnimation)==null?void 0:o.stop()}),this.root.nodes.forEach(OL),this.root.sharedNodes.clear()}}}function zY(t){t.updateLayout()}function qY(t){var n;const e=((n=t.resumeFrom)==null?void 0:n.snapshot)||t.snapshot;if(t.isLead()&&t.layout&&e&&t.hasListeners("didUpdate")){const{layoutBox:r,measuredBox:i}=t.layout,{animationType:s}=t.options,a=e.source!==t.layout.source;if(s==="size")Ks(d=>{const h=a?e.measuredBox[d]:e.layoutBox[d],f=ri(h);h.min=r[d].min,h.max=h.min+f});else if(s==="x"||s==="y"){const d=s==="x"?"y":"x";rE(a?e.measuredBox[d]:e.layoutBox[d],r[d])}else $U(s,e.layoutBox,r)&&Ks(d=>{const h=a?e.measuredBox[d]:e.layoutBox[d],f=ri(r[d]);h.max=h.min+f,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[d].max=t.relativeTarget[d].min+f)});const o=Zu();Tf(o,r,e.layoutBox);const l=Zu();a?Tf(l,t.applyTransform(i,!0),e.measuredBox):Tf(l,r,e.layoutBox);const c=!NU(o);let u=!1;if(!t.resumeFrom){const d=t.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:h,layout:f}=d;if(h&&f){const p=t.options.layoutAnchor||void 0,m=dr();a0(m,e.layoutBox,h.layoutBox,p);const g=dr();a0(g,r,f.layoutBox,p),MU(m,g)||(u=!0),d.options.layoutRoot&&(t.relativeTarget=g,t.relativeTargetOrigin=m,t.relativeParent=d)}}}t.notifyListeners("didUpdate",{layout:r,snapshot:e,delta:l,layoutDelta:o,hasLayoutChanged:c,hasRelativeLayoutChanged:u})}else if(t.isLead()){const{onExitComplete:r}=t.options;r&&r()}t.options.transition=void 0}function WY(t){t.parent&&(t.isProjecting()||(t.isProjectionDirty=t.parent.isProjectionDirty),t.isSharedProjectionDirty||(t.isSharedProjectionDirty=!!(t.isProjectionDirty||t.parent.isProjectionDirty||t.parent.isSharedProjectionDirty)),t.isTransformDirty||(t.isTransformDirty=t.parent.isTransformDirty))}function YY(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function XY(t){t.clearSnapshot()}function OL(t){t.clearMeasurements()}function QY(t){t.isLayoutDirty=!0,t.updateLayout()}function NL(t){t.isLayoutDirty=!1}function JY(t){t.isAnimationBlocked&&t.layout&&!t.isLayoutDirty&&(t.snapshot=t.layout,t.isLayoutDirty=!0)}function ZY(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function ML(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function eX(t){t.resolveTargetDelta()}function tX(t){t.calcProjection()}function nX(t){t.resetSkewAndRotation()}function rX(t){t.removeLeadSnapshot()}function BL(t,e,n){t.translate=An(e.translate,0,n),t.scale=An(e.scale,1,n),t.origin=e.origin,t.originPoint=e.originPoint}function UL(t,e,n,r){t.min=An(e.min,n.min,r),t.max=An(e.max,n.max,r)}function iX(t,e,n,r){UL(t.x,e.x,n.x,r),UL(t.y,e.y,n.y,r)}function sX(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const aX={duration:.45,ease:[.4,0,.1,1]},jL=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),FL=jL("applewebkit/")&&!jL("chrome/")?Math.round:fs;function $L(t){t.min=FL(t.min),t.max=FL(t.max)}function oX(t){$L(t.x),$L(t.y)}function $U(t,e,n){return t==="position"||t==="preserve-aspect"&&!CY(LL(e),LL(n),.2)}function lX(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const cX=FU({attachResizeListener:(t,e)=>dp(t,"resize",e),measureScroll:()=>{var t,e;return{x:document.documentElement.scrollLeft||((t=document.body)==null?void 0:t.scrollLeft)||0,y:document.documentElement.scrollTop||((e=document.body)==null?void 0:e.scrollTop)||0}},checkIsScrollRoot:()=>!0}),rb={current:void 0},VU=FU({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!rb.current){const t=new cX({});t.mount(window),t.setOptions({layoutScroll:!0}),rb.current=t}return rb.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),sA=D.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function VL(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function uX(...t){return e=>{let n=!1;const r=t.map(i=>{const s=VL(i,e);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let i=0;i<r.length;i++){const s=r[i];typeof s=="function"?s():VL(t[i],null)}}}}function dX(...t){return D.useCallback(uX(...t),t)}class hX extends D.Component{getSnapshotBeforeUpdate(e){const n=this.props.childRef.current;if(Xg(n)&&e.isPresent&&!this.props.isPresent&&this.props.pop!==!1){const r=n.offsetParent,i=Xg(r)&&r.offsetWidth||0,s=Xg(r)&&r.offsetHeight||0,a=getComputedStyle(n),o=this.props.sizeRef.current;o.height=parseFloat(a.height),o.width=parseFloat(a.width),o.top=n.offsetTop,o.left=n.offsetLeft,o.right=i-o.width-o.left,o.bottom=s-o.height-o.top}return null}componentDidUpdate(){}render(){return this.props.children}}function fX({children:t,isPresent:e,anchorX:n,anchorY:r,root:i,pop:s}){var h;const a=D.useId(),o=D.useRef(null),l=D.useRef({width:0,height:0,top:0,left:0,right:0,bottom:0}),{nonce:c}=D.useContext(sA),u=((h=t.props)==null?void 0:h.ref)??(t==null?void 0:t.ref),d=dX(o,u);return D.useInsertionEffect(()=>{const{width:f,height:p,top:m,left:g,right:b,bottom:v}=l.current;if(e||s===!1||!o.current||!f||!p)return;const S=n==="left"?`left: ${g}`:`right: ${b}`,E=r==="bottom"?`bottom: ${v}`:`top: ${m}`;o.current.dataset.motionPopId=a;const L=document.createElement("style");c&&(L.nonce=c);const U=i??document.head;return U.appendChild(L),L.sheet&&L.sheet.insertRule(`
          [data-motion-pop-id="${a}"] {
            position: absolute !important;
            width: ${f}px !important;
            height: ${p}px !important;
            ${S}px !important;
            ${E}px !important;
          }
        `),()=>{var O;(O=o.current)==null||O.removeAttribute("data-motion-pop-id"),U.contains(L)&&U.removeChild(L)}},[e]),y.jsx(hX,{isPresent:e,childRef:o,sizeRef:l,pop:s,children:s===!1?t:D.cloneElement(t,{ref:d})})}const pX=({children:t,initial:e,isPresent:n,onExitComplete:r,custom:i,presenceAffectsLayout:s,mode:a,anchorX:o,anchorY:l,root:c})=>{const u=OT(mX),d=D.useId();let h=!0,f=D.useMemo(()=>(h=!1,{id:d,initial:e,isPresent:n,custom:i,onExitComplete:p=>{u.set(p,!0);for(const m of u.values())if(!m)return;r&&r()},register:p=>(u.set(p,!1),()=>u.delete(p))}),[n,u,r]);return s&&h&&(f={...f}),D.useMemo(()=>{u.forEach((p,m)=>u.set(m,!1))},[n]),D.useEffect(()=>{!n&&!u.size&&r&&r()},[n]),t=y.jsx(fX,{pop:a==="popLayout",isPresent:n,anchorX:o,anchorY:l,root:c,children:t}),y.jsx(uv.Provider,{value:f,children:t})};function mX(){return new Map}function GU(t=!0){const e=D.useContext(uv);if(e===null)return[!0,null];const{isPresent:n,onExitComplete:r,register:i}=e,s=D.useId();D.useEffect(()=>{if(t)return i(s)},[t]);const a=D.useCallback(()=>t&&r&&r(s),[s,r,t]);return!n&&r?[!1,a]:[!0]}const Jm=t=>t.key||"";function GL(t){const e=[];return D.Children.forEach(t,n=>{D.isValidElement(n)&&e.push(n)}),e}const bh=({children:t,custom:e,initial:n=!0,onExitComplete:r,presenceAffectsLayout:i=!0,mode:s="sync",propagate:a=!1,anchorX:o="left",anchorY:l="top",root:c})=>{const[u,d]=GU(a),h=D.useMemo(()=>GL(t),[t]),f=a&&!u?[]:h.map(Jm),p=D.useRef(!0),m=D.useRef(h),g=OT(()=>new Map),b=D.useRef(new Set),[v,S]=D.useState(h),[E,L]=D.useState(h);gB(()=>{p.current=!1,m.current=h;for(let k=0;k<E.length;k++){const I=Jm(E[k]);f.includes(I)?(g.delete(I),b.current.delete(I)):g.get(I)!==!0&&g.set(I,!1)}},[E,f.length,f.join("-")]);const U=[];if(h!==v){let k=[...h];for(let I=0;I<E.length;I++){const R=E[I],M=Jm(R);f.includes(M)||(k.splice(I,0,R),U.push(R))}return s==="wait"&&U.length&&(k=U),L(GL(k)),S(h),null}const{forceRender:O}=D.useContext(DT);return y.jsx(y.Fragment,{children:E.map(k=>{const I=Jm(k),R=a&&!u?!1:h===E||f.includes(I),M=()=>{if(b.current.has(I))return;if(g.has(I))b.current.add(I),g.set(I,!0);else return;let z=!0;g.forEach(Z=>{Z||(z=!1)}),z&&(O==null||O(),L(m.current),a&&(d==null||d()),r&&r())};return y.jsx(pX,{isPresent:R,initial:!p.current||n?void 0:!1,custom:e,presenceAffectsLayout:i,mode:s,root:c,onExitComplete:R?void 0:M,anchorX:o,anchorY:l,children:k},I)})})},HU=D.createContext({strict:!1}),HL={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]};let KL=!1;function gX(){if(KL)return;const t={};for(const e in HL)t[e]={isEnabled:n=>HL[e].some(r=>!!n[r])};_U(t),KL=!0}function KU(){return gX(),eY()}function yX(t){const e=KU();for(const n in t)e[n]={...e[n],...t[n]};_U(e)}const vX=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","propagate","ignoreStrict","viewport"]);function o0(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||vX.has(t)}let zU=t=>!o0(t);function _X(t){typeof t=="function"&&(zU=e=>e.startsWith("on")?!o0(e):t(e))}try{_X(require("@emotion/is-prop-valid").default)}catch{}function bX(t,e,n){const r={};for(const i in t)i==="values"&&typeof t.values=="object"||Br(t[i])||(zU(i)||n===!0&&o0(i)||!e&&!o0(i)||t.draggable&&i.startsWith("onDrag"))&&(r[i]=t[i]);return r}const pv=D.createContext({});function xX(t,e){if(fv(t)){const{initial:n,animate:r}=t;return{initial:n===!1||up(n)?n:void 0,animate:up(r)?r:void 0}}return t.inherit!==!1?e:{}}function SX(t){const{initial:e,animate:n}=xX(t,D.useContext(pv));return D.useMemo(()=>({initial:e,animate:n}),[zL(e),zL(n)])}function zL(t){return Array.isArray(t)?t.join(" "):t}const aA=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function qU(t,e,n){for(const r in e)!Br(e[r])&&!AU(r,n)&&(t[r]=e[r])}function EX({transformTemplate:t},e){return D.useMemo(()=>{const n=aA();return rA(n,e,t),Object.assign({},n.vars,n.style)},[e])}function wX(t,e){const n=t.style||{},r={};return qU(r,n,t),Object.assign(r,EX(t,e)),r}function TX(t,e){const n={},r=wX(t,e);return t.drag&&t.dragListener!==!1&&(n.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout="none",r.touchAction=t.drag===!0?"none":`pan-${t.drag==="x"?"y":"x"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(n.tabIndex=0),n.style=r,n}const WU=()=>({...aA(),attrs:{}});function AX(t,e,n,r){const i=D.useMemo(()=>{const s=WU();return RU(s,e,LU(r),t.transformTemplate,t.style),{...s.attrs,style:{...s.style}}},[e]);if(t.style){const s={};qU(s,t.style,t),i.style={...s,...i.style}}return i}const RX=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function oA(t){return typeof t!="string"||t.includes("-")?!1:!!(RX.indexOf(t)>-1||/[A-Z]/u.test(t))}function CX(t,e,n,{latestValues:r},i,s=!1,a){const l=(a??oA(t)?AX:TX)(e,r,i,t),c=bX(e,typeof t=="string",s),u=t!==D.Fragment?{...c,...l,ref:n}:{},{children:d}=e,h=D.useMemo(()=>Br(d)?d.get():d,[d]);return D.createElement(t,{...u,children:h})}function LX({scrapeMotionValuesFromProps:t,createRenderState:e},n,r,i){return{latestValues:kX(n,r,i,t),renderState:e()}}function kX(t,e,n,r){const i={},s=r(t,{});for(const h in s)i[h]=ty(s[h]);let{initial:a,animate:o}=t;const l=fv(t),c=yU(t);e&&c&&!l&&t.inherit!==!1&&(a===void 0&&(a=e.initial),o===void 0&&(o=e.animate));let u=n?n.initial===!1:!1;u=u||a===!1;const d=u?o:a;if(d&&typeof d!="boolean"&&!hv(d)){const h=Array.isArray(d)?d:[d];for(let f=0;f<h.length;f++){const p=YT(t,h[f]);if(p){const{transitionEnd:m,transition:g,...b}=p;for(const v in b){let S=b[v];if(Array.isArray(S)){const E=u?S.length-1:0;S=S[E]}S!==null&&(i[v]=S)}for(const v in m)i[v]=m[v]}}}return i}const YU=t=>(e,n)=>{const r=D.useContext(pv),i=D.useContext(uv),s=()=>LX(t,e,r,i);return n?s():OT(s)},IX=YU({scrapeMotionValuesFromProps:iA,createRenderState:aA}),PX=YU({scrapeMotionValuesFromProps:kU,createRenderState:WU}),DX=Symbol.for("motionComponentSymbol");function OX(t,e,n){const r=D.useRef(n);D.useInsertionEffect(()=>{r.current=n});const i=D.useRef(null);return D.useCallback(s=>{var o;s&&((o=t.onMount)==null||o.call(t,s));const a=r.current;if(typeof a=="function")if(s){const l=a(s);typeof l=="function"&&(i.current=l)}else i.current?(i.current(),i.current=null):a(s);else a&&(a.current=s);e&&(s?e.mount(s):e.unmount())},[e])}const XU=D.createContext({});function Pu(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function NX(t,e,n,r,i,s){var S,E;const{visualElement:a}=D.useContext(pv),o=D.useContext(HU),l=D.useContext(uv),c=D.useContext(sA),u=c.reducedMotion,d=c.skipAnimations,h=D.useRef(null),f=D.useRef(!1);r=r||o.renderer,!h.current&&r&&(h.current=r(t,{visualState:e,parent:a,props:n,presenceContext:l,blockInitialAnimation:l?l.initial===!1:!1,reducedMotionConfig:u,skipAnimations:d,isSVG:s}),f.current&&h.current&&(h.current.manuallyAnimateOnMount=!0));const p=h.current,m=D.useContext(XU);p&&!p.projection&&i&&(p.type==="html"||p.type==="svg")&&MX(h.current,n,i,m);const g=D.useRef(!1);D.useInsertionEffect(()=>{p&&g.current&&p.update(n,l)});const b=n[iU],v=D.useRef(!!b&&typeof window<"u"&&!((S=window.MotionHandoffIsComplete)!=null&&S.call(window,b))&&((E=window.MotionHasOptimisedAnimation)==null?void 0:E.call(window,b)));return gB(()=>{f.current=!0,p&&(g.current=!0,window.MotionIsMounted=!0,p.updateFeatures(),p.scheduleRenderMicrotask(),v.current&&p.animationState&&p.animationState.animateChanges())}),D.useEffect(()=>{p&&(!v.current&&p.animationState&&p.animationState.animateChanges(),v.current&&(queueMicrotask(()=>{var L;(L=window.MotionHandoffMarkAsComplete)==null||L.call(window,b)}),v.current=!1),p.enteringChildren=void 0)}),p}function MX(t,e,n,r){const{layoutId:i,layout:s,drag:a,dragConstraints:o,layoutScroll:l,layoutRoot:c,layoutAnchor:u,layoutCrossfade:d}=e;t.projection=new n(t.latestValues,e["data-framer-portal-id"]?void 0:QU(t.parent)),t.projection.setOptions({layoutId:i,layout:s,alwaysMeasureLayout:!!a||o&&Pu(o),visualElement:t,animationType:typeof s=="string"?s:"both",initialPromotionConfig:r,crossfade:d,layoutScroll:l,layoutRoot:c,layoutAnchor:u})}function QU(t){if(t)return t.options.allowProjection!==!1?t.projection:QU(t.parent)}function ib(t,{forwardMotionProps:e=!1,type:n}={},r,i){r&&yX(r);const s=n?n==="svg":oA(t),a=s?PX:IX;function o(c,u){let d;const h={...D.useContext(sA),...c,layoutId:BX(c)},{isStatic:f}=h,p=SX(c),m=a(c,f);if(!f&&typeof window<"u"){UX();const g=jX(h);d=g.MeasureLayout,p.visualElement=NX(t,m,h,i,g.ProjectionNode,s)}return y.jsxs(pv.Provider,{value:p,children:[d&&p.visualElement?y.jsx(d,{visualElement:p.visualElement,...h}):null,CX(t,c,OX(m,p.visualElement,u),m,f,e,s)]})}o.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const l=D.forwardRef(o);return l[DX]=t,l}function BX({layoutId:t}){const e=D.useContext(DT).id;return e&&t!==void 0?e+"-"+t:t}function UX(t,e){D.useContext(HU).strict}function jX(t){const e=KU(),{drag:n,layout:r}=e;if(!n&&!r)return{};const i={...n,...r};return{MeasureLayout:n!=null&&n.isEnabled(t)||r!=null&&r.isEnabled(t)?i.MeasureLayout:void 0,ProjectionNode:i.ProjectionNode}}function FX(t,e){if(typeof Proxy>"u")return ib;const n=new Map,r=(s,a)=>ib(s,a,t,e),i=(s,a)=>r(s,a);return new Proxy(i,{get:(s,a)=>a==="create"?r:(n.has(a)||n.set(a,ib(a,void 0,t,e)),n.get(a))})}const $X=(t,e)=>e.isSVG??oA(t)?new yY(e):new dY(e,{allowProjection:t!==D.Fragment});class VX extends Nl{constructor(e){super(e),e.animationState||(e.animationState=SY(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();hv(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:n}=this.node.prevProps||{};e!==n&&this.updateAnimationControlsSubscription()}unmount(){var e;this.node.animationState.reset(),(e=this.unmountControls)==null||e.call(this)}}let GX=0;class HX extends Nl{constructor(){super(...arguments),this.id=GX++,this.isExitComplete=!1}update(){var s;if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:n}=this.node.presenceContext,{isPresent:r}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===r)return;if(e&&r===!1){if(this.isExitComplete){const{initial:a,custom:o}=this.node.getProps();if(typeof a=="string"){const l=kc(this.node,a,o);if(l){const{transition:c,transitionEnd:u,...d}=l;for(const h in d)(s=this.node.getValue(h))==null||s.jump(d[h])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive("exit",!1);this.isExitComplete=!1;return}const i=this.node.animationState.setActive("exit",!e);n&&!e&&i.then(()=>{this.isExitComplete=!0,n(this.id)})}mount(){const{register:e,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),e&&(this.unmount=e(this.id))}unmount(){}}const KX={animation:{Feature:VX},exit:{Feature:HX}};function om(t){return{point:{x:t.pageX,y:t.pageY}}}const zX=t=>e=>ZT(e)&&t(e,om(e));function Af(t,e,n,r){return dp(t,e,zX(n),r)}const JU=({current:t})=>t?t.ownerDocument.defaultView:null,qL=(t,e)=>Math.abs(t-e);function qX(t,e){const n=qL(t.x,e.x),r=qL(t.y,e.y);return Math.sqrt(n**2+r**2)}const WL=new Set(["auto","scroll"]);class ZU{constructor(e,n,{transformPagePoint:r,contextWindow:i=window,dragSnapToOrigin:s=!1,distanceThreshold:a=3,element:o}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=f=>{this.handleScroll(f.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=Zm(this.lastRawMoveEventInfo,this.transformPagePoint));const f=sb(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,m=qX(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!m)return;const{point:g}=f,{timestamp:b}=kr;this.history.push({...g,timestamp:b});const{onStart:v,onMove:S}=this.handlers;p||(v&&v(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),S&&S(this.lastMoveEvent,f)},this.handlePointerMove=(f,p)=>{this.lastMoveEvent=f,this.lastRawMoveEventInfo=p,this.lastMoveEventInfo=Zm(p,this.transformPagePoint),gn.update(this.updatePoint,!0)},this.handlePointerUp=(f,p)=>{this.end();const{onEnd:m,onSessionEnd:g,resumeAnimation:b}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const v=sb(f.type==="pointercancel"?this.lastMoveEventInfo:Zm(p,this.transformPagePoint),this.history);this.startEvent&&m&&m(f,v),g&&g(f,v)},!ZT(e))return;this.dragSnapToOrigin=s,this.handlers=n,this.transformPagePoint=r,this.distanceThreshold=a,this.contextWindow=i||window;const l=om(e),c=Zm(l,this.transformPagePoint),{point:u}=c,{timestamp:d}=kr;this.history=[{...u,timestamp:d}];const{onSessionStart:h}=n;h&&h(e,sb(c,this.history)),this.removeListeners=im(Af(this.contextWindow,"pointermove",this.handlePointerMove),Af(this.contextWindow,"pointerup",this.handlePointerUp),Af(this.contextWindow,"pointercancel",this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(e){let n=e.parentElement;for(;n;){const r=getComputedStyle(n);(WL.has(r.overflowX)||WL.has(r.overflowY))&&this.scrollPositions.set(n,{x:n.scrollLeft,y:n.scrollTop}),n=n.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener("scroll",this.onElementScroll,{capture:!0}),window.addEventListener("scroll",this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener("scroll",this.onElementScroll,{capture:!0}),window.removeEventListener("scroll",this.onWindowScroll)}}handleScroll(e){const n=this.scrollPositions.get(e);if(!n)return;const r=e===window,i=r?{x:window.scrollX,y:window.scrollY}:{x:e.scrollLeft,y:e.scrollTop},s={x:i.x-n.x,y:i.y-n.y};s.x===0&&s.y===0||(r?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=s.x,this.lastMoveEventInfo.point.y+=s.y):this.history.length>0&&(this.history[0].x-=s.x,this.history[0].y-=s.y),this.scrollPositions.set(e,i),gn.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),wl(this.updatePoint)}}function Zm(t,e){return e?{point:e(t.point)}:t}function YL(t,e){return{x:t.x-e.x,y:t.y-e.y}}function sb({point:t},e){return{point:t,delta:YL(t,ej(e)),offset:YL(t,WX(e)),velocity:YX(e,.1)}}function WX(t){return t[0]}function ej(t){return t[t.length-1]}function YX(t,e){if(t.length<2)return{x:0,y:0};let n=t.length-1,r=null;const i=ej(t);for(;n>=0&&(r=t[n],!(i.timestamp-r.timestamp>Hi(e)));)n--;if(!r)return{x:0,y:0};r===t[0]&&t.length>2&&i.timestamp-r.timestamp>Hi(e)*2&&(r=t[1]);const s=hs(i.timestamp-r.timestamp);if(s===0)return{x:0,y:0};const a={x:(i.x-r.x)/s,y:(i.y-r.y)/s};return a.x===1/0&&(a.x=0),a.y===1/0&&(a.y=0),a}function XX(t,{min:e,max:n},r){return e!==void 0&&t<e?t=r?An(e,t,r.min):Math.max(t,e):n!==void 0&&t>n&&(t=r?An(n,t,r.max):Math.min(t,n)),t}function XL(t,e,n){return{min:e!==void 0?t.min+e:void 0,max:n!==void 0?t.max+n-(t.max-t.min):void 0}}function QX(t,{top:e,left:n,bottom:r,right:i}){return{x:XL(t.x,n,i),y:XL(t.y,e,r)}}function QL(t,e){let n=e.min-t.min,r=e.max-t.max;return e.max-e.min<t.max-t.min&&([n,r]=[r,n]),{min:n,max:r}}function JX(t,e){return{x:QL(t.x,e.x),y:QL(t.y,e.y)}}function ZX(t,e){let n=.5;const r=ri(t),i=ri(e);return i>r?n=lp(e.min,e.max-r,t.min):r>i&&(n=lp(t.min,t.max-i,e.min)),pa(0,1,n)}function eQ(t,e){const n={};return e.min!==void 0&&(n.min=e.min-t.min),e.max!==void 0&&(n.max=e.max-t.min),n}const iE=.35;function tQ(t=iE){return t===!1?t=0:t===!0&&(t=iE),{x:JL(t,"left","right"),y:JL(t,"top","bottom")}}function JL(t,e,n){return{min:ZL(t,e),max:ZL(t,n)}}function ZL(t,e){return typeof t=="number"?t:t[e]||0}const nQ=new WeakMap;class rQ{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=dr(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:n=!1,distanceThreshold:r}={}){const{presenceContext:i}=this.visualElement;if(i&&i.isPresent===!1)return;const s=d=>{n&&this.snapToCursor(om(d).point),this.stopAnimation()},a=(d,h)=>{const{drag:f,dragPropagation:p,onDragStart:m}=this.getProps();if(f&&!p&&(this.openDragLock&&this.openDragLock(),this.openDragLock=kW(f),!this.openDragLock))return;this.latestPointerEvent=d,this.latestPanInfo=h,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Ks(b=>{let v=this.getAxisMotionValue(b).get()||0;if(ha.test(v)){const{projection:S}=this.visualElement;if(S&&S.layout){const E=S.layout.layoutBox[b];E&&(v=ri(E)*(parseFloat(v)/100))}}this.originPoint[b]=v}),m&&gn.update(()=>m(d,h),!1,!0),YS(this.visualElement,"transform");const{animationState:g}=this.visualElement;g&&g.setActive("whileDrag",!0)},o=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h;const{dragPropagation:f,dragDirectionLock:p,onDirectionLock:m,onDrag:g}=this.getProps();if(!f&&!this.openDragLock)return;const{offset:b}=h;if(p&&this.currentDirection===null){this.currentDirection=sQ(b),this.currentDirection!==null&&m&&m(this.currentDirection);return}this.updateAxis("x",h.point,b),this.updateAxis("y",h.point,b),this.visualElement.render(),g&&gn.update(()=>g(d,h),!1,!0)},l=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h,this.stop(d,h),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>{const{dragSnapToOrigin:d}=this.getProps();(d||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:u}=this.getProps();this.panSession=new ZU(e,{onSessionStart:s,onStart:a,onMove:o,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:r,contextWindow:JU(this.visualElement),element:this.visualElement.current})}stop(e,n){const r=e||this.latestPointerEvent,i=n||this.latestPanInfo,s=this.isDragging;if(this.cancel(),!s||!i||!r)return;const{velocity:a}=i;this.startAnimation(a);const{onDragEnd:o}=this.getProps();o&&gn.postRender(()=>o(r,i))}cancel(){this.isDragging=!1;const{projection:e,animationState:n}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:r}=this.getProps();!r&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(e,n,r){const{drag:i}=this.getProps();if(!r||!eg(e,i,this.currentDirection))return;const s=this.getAxisMotionValue(e);let a=this.originPoint[e]+r[e];this.constraints&&this.constraints[e]&&(a=XX(a,this.constraints[e],this.elastic[e])),s.set(a)}resolveConstraints(){var s;const{dragConstraints:e,dragElastic:n}=this.getProps(),r=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(s=this.visualElement.projection)==null?void 0:s.layout,i=this.constraints;e&&Pu(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&r?this.constraints=QX(r.layoutBox,e):this.constraints=!1,this.elastic=tQ(n),i!==this.constraints&&!Pu(e)&&r&&this.constraints&&!this.hasMutatedConstraints&&Ks(a=>{this.constraints!==!1&&this.getAxisMotionValue(a)&&(this.constraints[a]=eQ(r.layoutBox[a],this.constraints[a]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:n}=this.getProps();if(!e||!Pu(e))return!1;const r=e.current,{projection:i}=this.visualElement;if(!i||!i.layout)return!1;const s=sY(r,i.root,this.visualElement.getTransformPagePoint());let a=JX(i.layout.layoutBox,s);if(n){const o=n(nY(a));this.hasMutatedConstraints=!!o,o&&(a=xU(o))}return a}startAnimation(e){const{drag:n,dragMomentum:r,dragElastic:i,dragTransition:s,dragSnapToOrigin:a,onDragTransitionEnd:o}=this.getProps(),l=this.constraints||{},c=Ks(u=>{if(!eg(u,n,this.currentDirection))return;let d=l&&l[u]||{};(a===!0||a===u)&&(d={min:0,max:0});const h=i?200:1e6,f=i?40:1e7,p={type:"inertia",velocity:r?e[u]:0,bounceStiffness:h,bounceDamping:f,timeConstant:750,restDelta:1,restSpeed:10,...s,...d};return this.startAxisValueAnimation(u,p)});return Promise.all(c).then(o)}startAxisValueAnimation(e,n){const r=this.getAxisMotionValue(e);return YS(this.visualElement,e),r.start(WT(e,r,0,n,this.visualElement,!1))}stopAnimation(){Ks(e=>this.getAxisMotionValue(e).stop())}getAxisMotionValue(e){const n=`_drag${e.toUpperCase()}`,r=this.visualElement.getProps(),i=r[n];return i||this.visualElement.getValue(e,(r.initial?r.initial[e]:void 0)||0)}snapToCursor(e){Ks(n=>{const{drag:r}=this.getProps();if(!eg(n,r,this.currentDirection))return;const{projection:i}=this.visualElement,s=this.getAxisMotionValue(n);if(i&&i.layout){const{min:a,max:o}=i.layout.layoutBox[n],l=s.get()||0;s.set(e[n]-An(a,o,.5)+l)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:n}=this.getProps(),{projection:r}=this.visualElement;if(!Pu(n)||!r||!this.constraints)return;this.stopAnimation();const i={x:0,y:0};Ks(a=>{const o=this.getAxisMotionValue(a);if(o&&this.constraints!==!1){const l=o.get();i[a]=ZX({min:l,max:l},this.constraints[a])}});const{transformTemplate:s}=this.visualElement.getProps();this.visualElement.current.style.transform=s?s({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.constraints=!1,this.resolveConstraints(),Ks(a=>{if(!eg(a,e,null))return;const o=this.getAxisMotionValue(a),{min:l,max:c}=this.constraints[a];o.set(An(l,c,i[a]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;nQ.set(this.visualElement,this);const e=this.visualElement.current,n=Af(e,"pointerdown",c=>{const{drag:u,dragListener:d=!0}=this.getProps(),h=c.target,f=h!==e&&MW(h);u&&d&&!f&&this.start(c)});let r;const i=()=>{const{dragConstraints:c}=this.getProps();Pu(c)&&c.current&&(this.constraints=this.resolveRefConstraints(),r||(r=iQ(e,c.current,()=>this.scalePositionWithinConstraints())))},{projection:s}=this.visualElement,a=s.addEventListener("measure",i);s&&!s.layout&&(s.root&&s.root.updateScroll(),s.updateLayout()),gn.read(i);const o=dp(window,"resize",()=>this.scalePositionWithinConstraints()),l=s.addEventListener("didUpdate",({delta:c,hasLayoutChanged:u})=>{this.isDragging&&u&&(Ks(d=>{const h=this.getAxisMotionValue(d);h&&(this.originPoint[d]+=c[d].translate,h.set(h.get()+c[d].translate))}),this.visualElement.render())});return()=>{o(),n(),a(),l&&l(),r&&r()}}getProps(){const e=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:r=!1,dragPropagation:i=!1,dragConstraints:s=!1,dragElastic:a=iE,dragMomentum:o=!0}=e;return{...e,drag:n,dragDirectionLock:r,dragPropagation:i,dragConstraints:s,dragElastic:a,dragMomentum:o}}}function ek(t){let e=!0;return()=>{if(e){e=!1;return}t()}}function iQ(t,e,n){const r=oL(t,ek(n)),i=oL(e,ek(n));return()=>{r(),i()}}function eg(t,e,n){return(e===!0||e===t)&&(n===null||n===t)}function sQ(t,e=10){let n=null;return Math.abs(t.y)>e?n="y":Math.abs(t.x)>e&&(n="x"),n}class aQ extends Nl{constructor(e){super(e),this.removeGroupControls=fs,this.removeListeners=fs,this.controls=new rQ(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||fs}update(){const{dragControls:e}=this.node.getProps(),{dragControls:n}=this.node.prevProps||{};e!==n&&(this.removeGroupControls(),e&&(this.removeGroupControls=e.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const ab=t=>(e,n)=>{t&&gn.update(()=>t(e,n),!1,!0)};class oQ extends Nl{constructor(){super(...arguments),this.removePointerDownListener=fs}onPointerDown(e){this.session=new ZU(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:JU(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:n,onPan:r,onPanEnd:i}=this.node.getProps();return{onSessionStart:ab(e),onStart:ab(n),onMove:ab(r),onEnd:(s,a)=>{delete this.session,i&&gn.postRender(()=>i(s,a))}}}mount(){this.removePointerDownListener=Af(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let ob=!1;class lQ extends D.Component{componentDidMount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:r,layoutId:i}=this.props,{projection:s}=e;s&&(n.group&&n.group.add(s),r&&r.register&&i&&r.register(s),ob&&s.root.didUpdate(),s.addEventListener("animationComplete",()=>{this.safeToRemove()}),s.setOptions({...s.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),ny.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:n,visualElement:r,drag:i,isPresent:s}=this.props,{projection:a}=r;return a&&(a.isPresent=s,e.layoutDependency!==n&&a.setOptions({...a.options,layoutDependency:n}),ob=!0,i||e.layoutDependency!==n||n===void 0||e.isPresent!==s?a.willUpdate():this.safeToRemove(),e.isPresent!==s&&(s?a.promote():a.relegate()||gn.postRender(()=>{const o=a.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{visualElement:e,layoutAnchor:n}=this.props,{projection:r}=e;r&&(r.options.layoutAnchor=n,r.root.didUpdate(),JT.postRender(()=>{!r.currentAnimation&&r.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:r}=this.props,{projection:i}=e;ob=!0,i&&(i.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(i),r&&r.deregister&&r.deregister(i))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function tj(t){const[e,n]=GU(),r=D.useContext(DT);return y.jsx(lQ,{...t,layoutGroup:r,switchLayoutGroup:D.useContext(XU),isPresent:e,safeToRemove:n})}const cQ={pan:{Feature:oQ},drag:{Feature:aQ,ProjectionNode:VU,MeasureLayout:tj}};function tk(t,e,n){const{props:r}=t;t.animationState&&r.whileHover&&t.animationState.setActive("whileHover",n==="Start");const i="onHover"+n,s=r[i];s&&gn.postRender(()=>s(e,om(e)))}class uQ extends Nl{mount(){const{current:e}=this.node;e&&(this.unmount=PW(e,(n,r)=>(tk(this.node,r,"Start"),i=>tk(this.node,i,"End"))))}unmount(){}}class dQ extends Nl{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(":focus-visible")}catch{e=!0}!e||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=im(dp(this.node.current,"focus",()=>this.onFocus()),dp(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function nk(t,e,n){const{props:r}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&r.whileTap&&t.animationState.setActive("whileTap",n==="Start");const i="onTap"+(n==="End"?"":n),s=r[i];s&&gn.postRender(()=>s(e,om(e)))}class hQ extends Nl{mount(){const{current:e}=this.node;if(!e)return;const{globalTapTarget:n,propagate:r}=this.node.props;this.unmount=UW(e,(i,s)=>(nk(this.node,s,"Start"),(a,{success:o})=>nk(this.node,a,o?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:(r==null?void 0:r.tap)===!1})}unmount(){}}const sE=new WeakMap,lb=new WeakMap,fQ=t=>{const e=sE.get(t.target);e&&e(t)},pQ=t=>{t.forEach(fQ)};function mQ({root:t,...e}){const n=t||document;lb.has(n)||lb.set(n,{});const r=lb.get(n),i=JSON.stringify(e);return r[i]||(r[i]=new IntersectionObserver(pQ,{root:t,...e})),r[i]}function gQ(t,e,n){const r=mQ(e);return sE.set(t,n),r.observe(t),()=>{sE.delete(t),r.unobserve(t)}}const yQ={some:0,all:1};class vQ extends Nl{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){var l;(l=this.stopObserver)==null||l.call(this);const{viewport:e={}}=this.node.getProps(),{root:n,margin:r,amount:i="some",once:s}=e,a={root:n?n.current:void 0,rootMargin:r,threshold:typeof i=="number"?i:yQ[i]},o=c=>{const{isIntersecting:u}=c;if(this.isInView===u||(this.isInView=u,s&&!u&&this.hasEnteredView))return;u&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",u);const{onViewportEnter:d,onViewportLeave:h}=this.node.getProps(),f=u?d:h;f&&f(c)};this.stopObserver=gQ(this.node.current,a,o)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:n}=this.node;["amount","margin","root"].some(_Q(e,n))&&this.startObserver()}unmount(){var e;(e=this.stopObserver)==null||e.call(this),this.hasEnteredView=!1,this.isInView=!1}}function _Q({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}const bQ={inView:{Feature:vQ},tap:{Feature:hQ},focus:{Feature:dQ},hover:{Feature:uQ}},xQ={layout:{ProjectionNode:VU,MeasureLayout:tj}},SQ={...KX,...bQ,...cQ,...xQ},$t=FX(SQ,$X),Tt=t=>typeof t=="string",Vh=()=>{let t,e;const n=new Promise((r,i)=>{t=r,e=i});return n.resolve=t,n.reject=e,n},rk=t=>t==null?"":String(t),EQ=(t,e,n)=>{t.forEach(r=>{e[r]&&(n[r]=e[r])})},wQ=/###/g,ik=t=>t&&t.includes("###")?t.replace(wQ,"."):t,sk=t=>!t||Tt(t),Rf=(t,e,n)=>{const r=Tt(e)?e.split("."):e;let i=0;for(;i<r.length-1;){if(sk(t))return{};const s=ik(r[i]);!t[s]&&n&&(t[s]=new n),Object.prototype.hasOwnProperty.call(t,s)?t=t[s]:t={},++i}return sk(t)?{}:{obj:t,k:ik(r[i])}},ak=(t,e,n)=>{const{obj:r,k:i}=Rf(t,e,Object);if(r!==void 0||e.length===1){r[i]=n;return}let s=e[e.length-1],a=e.slice(0,e.length-1),o=Rf(t,a,Object);for(;o.obj===void 0&&a.length;)s=`${a[a.length-1]}.${s}`,a=a.slice(0,a.length-1),o=Rf(t,a,Object),o!=null&&o.obj&&typeof o.obj[`${o.k}.${s}`]<"u"&&(o.obj=void 0);o.obj[`${o.k}.${s}`]=n},TQ=(t,e,n,r)=>{const{obj:i,k:s}=Rf(t,e,Object);i[s]=i[s]||[],i[s].push(n)},l0=(t,e)=>{const{obj:n,k:r}=Rf(t,e);if(n&&Object.prototype.hasOwnProperty.call(n,r))return n[r]},AQ=(t,e,n)=>{const r=l0(t,n);return r!==void 0?r:l0(e,n)},nj=(t,e,n)=>{for(const r in e)r!=="__proto__"&&r!=="constructor"&&(r in t?Tt(t[r])||t[r]instanceof String||Tt(e[r])||e[r]instanceof String?n&&(t[r]=e[r]):nj(t[r],e[r],n):t[r]=e[r]);return t},Da=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),RQ={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"},CQ=t=>Tt(t)?t.replace(/[&<>"'\/]/g,e=>RQ[e]):t;class LQ{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const n=this.regExpMap.get(e);if(n!==void 0)return n;const r=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,r),this.regExpQueue.push(e),r}}const kQ=[" ",",","?","!",";"],IQ=new LQ(20),PQ=(t,e,n)=>{e=e||"",n=n||"";const r=kQ.filter(a=>!e.includes(a)&&!n.includes(a));if(r.length===0)return!0;const i=IQ.getRegExp(`(${r.map(a=>a==="?"?"\\?":a).join("|")})`);let s=!i.test(t);if(!s){const a=t.indexOf(n);a>0&&!i.test(t.substring(0,a))&&(s=!0)}return s},aE=(t,e,n=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const r=e.split(n);let i=t;for(let s=0;s<r.length;){if(!i||typeof i!="object")return;let a,o="";for(let l=s;l<r.length;++l)if(l!==s&&(o+=n),o+=r[l],a=i[o],a!==void 0){if(["string","number","boolean"].includes(typeof a)&&l<r.length-1)continue;s+=l-s+1;break}i=a}return i},hp=t=>t==null?void 0:t.replace(/_/g,"-"),DQ={type:"logger",log(t){this.output("log",t)},warn(t){this.output("warn",t)},error(t){this.output("error",t)},output(t,e){var n,r;(r=(n=console==null?void 0:console[t])==null?void 0:n.apply)==null||r.call(n,console,e)}};let OQ=class oE{constructor(e,n={}){this.init(e,n)}init(e,n={}){this.prefix=n.prefix||"i18next:",this.logger=e||DQ,this.options=n,this.debug=n.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,n,r,i){return i&&!this.debug?null:(e=e.map(s=>Tt(s)?s.replace(/[\r\n\x00-\x1F\x7F]/g," "):s),Tt(e[0])&&(e[0]=`${r}${this.prefix} ${e[0]}`),this.logger[n](e))}create(e){return new oE(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new oE(this.logger,e)}};var ia=new OQ;let mv=class{constructor(){this.observers={}}on(e,n){return e.split(" ").forEach(r=>{this.observers[r]||(this.observers[r]=new Map);const i=this.observers[r].get(n)||0;this.observers[r].set(n,i+1)}),this}off(e,n){if(this.observers[e]){if(!n){delete this.observers[e];return}this.observers[e].delete(n)}}once(e,n){const r=(...i)=>{n(...i),this.off(e,r)};return this.on(e,r),this}emit(e,...n){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([i,s])=>{for(let a=0;a<s;a++)i(...n)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([i,s])=>{for(let a=0;a<s;a++)i(e,...n)})}};class ok extends mv{constructor(e,n={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.includes(e)||this.options.ns.push(e)}removeNamespaces(e){const n=this.options.ns.indexOf(e);n>-1&&this.options.ns.splice(n,1)}getResource(e,n,r,i={}){var c,u;const s=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,a=i.ignoreJSONStructure!==void 0?i.ignoreJSONStructure:this.options.ignoreJSONStructure;let o;e.includes(".")?o=e.split("."):(o=[e,n],r&&(Array.isArray(r)?o.push(...r):Tt(r)&&s?o.push(...r.split(s)):o.push(r)));const l=l0(this.data,o);return!l&&!n&&!r&&e.includes(".")&&(e=o[0],n=o[1],r=o.slice(2).join(".")),l||!a||!Tt(r)?l:aE((u=(c=this.data)==null?void 0:c[e])==null?void 0:u[n],r,s)}addResource(e,n,r,i,s={silent:!1}){const a=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator;let o=[e,n];r&&(o=o.concat(a?r.split(a):r)),e.includes(".")&&(o=e.split("."),i=n,n=o[1]),this.addNamespaces(n),ak(this.data,o,i),s.silent||this.emit("added",e,n,r,i)}addResources(e,n,r,i={silent:!1}){for(const s in r)(Tt(r[s])||Array.isArray(r[s]))&&this.addResource(e,n,s,r[s],{silent:!0});i.silent||this.emit("added",e,n,r)}addResourceBundle(e,n,r,i,s,a={silent:!1,skipCopy:!1}){let o=[e,n];e.includes(".")&&(o=e.split("."),i=r,r=n,n=o[1]),this.addNamespaces(n);let l=l0(this.data,o)||{};a.skipCopy||(r=JSON.parse(JSON.stringify(r))),i?nj(l,r,s):l={...l,...r},ak(this.data,o,l),a.silent||this.emit("added",e,n,r)}removeResourceBundle(e,n){this.hasResourceBundle(e,n)&&delete this.data[e][n],this.removeNamespaces(n),this.emit("removed",e,n)}hasResourceBundle(e,n){return this.getResource(e,n)!==void 0}getResourceBundle(e,n){return n||(n=this.options.defaultNS),this.getResource(e,n)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const n=this.getDataByLanguage(e);return!!(n&&Object.keys(n)||[]).find(i=>n[i]&&Object.keys(n[i]).length>0)}toJSON(){return this.data}}var rj={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,n,r,i){return t.forEach(s=>{var a;e=((a=this.processors[s])==null?void 0:a.process(e,n,r,i))??e}),e}};const ij=Symbol("i18next/PATH_KEY");function NQ(){const t=[],e=Object.create(null);let n;return e.get=(r,i)=>{var s;return(s=n==null?void 0:n.revoke)==null||s.call(n),i===ij?t:(t.push(i),n=Proxy.revocable(r,e),n.proxy)},Proxy.revocable(Object.create(null),e).proxy}function md(t,e){const{[ij]:n}=t(NQ()),r=(e==null?void 0:e.keySeparator)??".",i=(e==null?void 0:e.nsSeparator)??":";if(n.length>1&&i){const s=e==null?void 0:e.ns,a=Array.isArray(s)?s:null;if(a&&a.length>1&&a.slice(1).includes(n[0]))return`${n[0]}${i}${n.slice(1).join(r)}`}return n.join(r)}const cb=t=>!Tt(t)&&typeof t!="boolean"&&typeof t!="number";class c0 extends mv{constructor(e,n={}){super(),EQ(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=ia.create("translator"),this.checkedLoadedFor={}}changeLanguage(e){e&&(this.language=e)}exists(e,n={interpolation:{}}){const r={...n};if(e==null)return!1;const i=this.resolve(e,r);if((i==null?void 0:i.res)===void 0)return!1;const s=cb(i.res);return!(r.returnObjects===!1&&s)}extractFromKey(e,n){let r=n.nsSeparator!==void 0?n.nsSeparator:this.options.nsSeparator;r===void 0&&(r=":");const i=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let s=n.ns||this.options.defaultNS||[];const a=r&&e.includes(r),o=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!PQ(e,r,i);if(a&&!o){const l=e.match(this.interpolator.nestingRegexp);if(l&&l.length>0)return{key:e,namespaces:Tt(s)?[s]:s};const c=e.split(r);(r!==i||r===i&&this.options.ns.includes(c[0]))&&(s=c.shift()),e=c.join(i)}return{key:e,namespaces:Tt(s)?[s]:s}}translate(e,n,r){let i=typeof n=="object"?{...n}:n;if(typeof i!="object"&&this.options.overloadTranslationOptionHandler&&(i=this.options.overloadTranslationOptionHandler(arguments)),typeof i=="object"&&(i={...i}),i||(i={}),e==null)return"";typeof e=="function"&&(e=md(e,{...this.options,...i})),Array.isArray(e)||(e=[String(e)]),e=e.map(Z=>typeof Z=="function"?md(Z,{...this.options,...i}):String(Z));const s=i.returnDetails!==void 0?i.returnDetails:this.options.returnDetails,a=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,{key:o,namespaces:l}=this.extractFromKey(e[e.length-1],i),c=l[l.length-1];let u=i.nsSeparator!==void 0?i.nsSeparator:this.options.nsSeparator;u===void 0&&(u=":");const d=i.lng||this.language,h=i.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if((d==null?void 0:d.toLowerCase())==="cimode")return h?s?{res:`${c}${u}${o}`,usedKey:o,exactUsedKey:o,usedLng:d,usedNS:c,usedParams:this.getUsedParamsDetails(i)}:`${c}${u}${o}`:s?{res:o,usedKey:o,exactUsedKey:o,usedLng:d,usedNS:c,usedParams:this.getUsedParamsDetails(i)}:o;const f=this.resolve(e,i);let p=f==null?void 0:f.res;const m=(f==null?void 0:f.usedKey)||o,g=(f==null?void 0:f.exactUsedKey)||o,b=["[object Number]","[object Function]","[object RegExp]"],v=i.joinArrays!==void 0?i.joinArrays:this.options.joinArrays,S=!this.i18nFormat||this.i18nFormat.handleAsObject,E=i.count!==void 0&&!Tt(i.count),L=c0.hasDefaultValue(i),U=E?this.pluralResolver.getSuffix(d,i.count,i):"",O=i.ordinal&&E?this.pluralResolver.getSuffix(d,i.count,{ordinal:!1}):"",k=E&&!i.ordinal&&i.count===0,I=k&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${U}`]||i[`defaultValue${O}`]||i.defaultValue;let R=p;S&&!p&&L&&(R=I);const M=cb(R),z=Object.prototype.toString.apply(R);if(S&&R&&M&&!b.includes(z)&&!(Tt(v)&&Array.isArray(R))){if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const Z=this.options.returnedObjectHandler?this.options.returnedObjectHandler(m,R,{...i,ns:l}):`key '${o} (${this.language})' returned an object instead of string.`;return s?(f.res=Z,f.usedParams=this.getUsedParamsDetails(i),f):Z}if(a){const Z=Array.isArray(R),W=Z?[]:{},re=Z?g:m;for(const X in R)if(Object.prototype.hasOwnProperty.call(R,X)){const oe=`${re}${a}${X}`;L&&!p?W[X]=this.translate(oe,{...i,defaultValue:cb(I)?I[X]:void 0,joinArrays:!1,ns:l}):W[X]=this.translate(oe,{...i,joinArrays:!1,ns:l}),W[X]===oe&&(W[X]=R[X])}p=W}}else if(S&&Tt(v)&&Array.isArray(p))p=p.join(v),p&&(p=this.extendTranslation(p,e,i,r));else{let Z=!1,W=!1;!this.isValidLookup(p)&&L&&(Z=!0,p=I),this.isValidLookup(p)||(W=!0,p=o);const X=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&W?void 0:p,oe=L&&I!==p&&this.options.updateMissing;if(W||Z||oe){if(this.logger.log(oe?"updateKey":"missingKey",d,c,E&&!oe?`${o}${this.pluralResolver.getSuffix(d,i.count,i)}`:o,oe?I:p),a){const Y=this.resolve(o,{...i,keySeparator:!1});Y&&Y.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let Q=[];const G=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if(this.options.saveMissingTo==="fallback"&&G&&G[0])for(let Y=0;Y<G.length;Y++)Q.push(G[Y]);else this.options.saveMissingTo==="all"?Q=this.languageUtils.toResolveHierarchy(i.lng||this.language):Q.push(i.lng||this.language);const H=(Y,ie,Ce)=>{var ke;const Le=L&&Ce!==p?Ce:X;this.options.missingKeyHandler?this.options.missingKeyHandler(Y,c,ie,Le,oe,i):(ke=this.backendConnector)!=null&&ke.saveMissing&&this.backendConnector.saveMissing(Y,c,ie,Le,oe,i),this.emit("missingKey",Y,c,ie,p)};this.options.saveMissing&&(this.options.saveMissingPlurals&&E?Q.forEach(Y=>{const ie=this.pluralResolver.getSuffixes(Y,i);k&&i[`defaultValue${this.options.pluralSeparator}zero`]&&!ie.includes(`${this.options.pluralSeparator}zero`)&&ie.push(`${this.options.pluralSeparator}zero`),ie.forEach(Ce=>{H([Y],o+Ce,i[`defaultValue${Ce}`]||I)})}):H(Q,o,I))}p=this.extendTranslation(p,e,i,f,r),W&&p===o&&this.options.appendNamespaceToMissingKey&&(p=`${c}${u}${o}`),(W||Z)&&this.options.parseMissingKeyHandler&&(p=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${c}${u}${o}`:o,Z?p:void 0,i))}return s?(f.res=p,f.usedParams=this.getUsedParamsDetails(i),f):p}extendTranslation(e,n,r,i,s){var l,c;if((l=this.i18nFormat)!=null&&l.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...r},r.lng||this.language||i.usedLng,i.usedNS,i.usedKey,{resolved:i});else if(!r.skipInterpolation){r.interpolation&&this.interpolator.init({...r,interpolation:{...this.options.interpolation,...r.interpolation}});const u=Tt(e)&&(((c=r==null?void 0:r.interpolation)==null?void 0:c.skipOnVariables)!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let d;if(u){const f=e.match(this.interpolator.nestingRegexp);d=f&&f.length}let h=r.replace&&!Tt(r.replace)?r.replace:r;if(this.options.interpolation.defaultVariables&&(h={...this.options.interpolation.defaultVariables,...h}),e=this.interpolator.interpolate(e,h,r.lng||this.language||i.usedLng,r),u){const f=e.match(this.interpolator.nestingRegexp),p=f&&f.length;d<p&&(r.nest=!1)}!r.lng&&i&&i.res&&(r.lng=this.language||i.usedLng),r.nest!==!1&&(e=this.interpolator.nest(e,(...f)=>(s==null?void 0:s[0])===f[0]&&!r.context?(this.logger.warn(`It seems you are nesting recursively key: ${f[0]} in key: ${n[0]}`),null):this.translate(...f,n),r)),r.interpolation&&this.interpolator.reset()}const a=r.postProcess||this.options.postProcess,o=Tt(a)?[a]:a;return e!=null&&(o!=null&&o.length)&&r.applyPostProcessor!==!1&&(e=rj.handle(o,e,n,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...i,usedParams:this.getUsedParamsDetails(r)},...r}:r,this)),e}resolve(e,n={}){let r,i,s,a,o;return Tt(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(l=>typeof l=="function"?md(l,{...this.options,...n}):l)),e.forEach(l=>{if(this.isValidLookup(r))return;const c=this.extractFromKey(l,n),u=c.key;i=u;let d=c.namespaces;this.options.fallbackNS&&(d=d.concat(this.options.fallbackNS));const h=n.count!==void 0&&!Tt(n.count),f=h&&!n.ordinal&&n.count===0,p=n.context!==void 0&&(Tt(n.context)||typeof n.context=="number")&&n.context!=="",m=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);d.forEach(g=>{var b,v;this.isValidLookup(r)||(o=g,!this.checkedLoadedFor[`${m[0]}-${g}`]&&((b=this.utils)!=null&&b.hasLoadedNamespace)&&!((v=this.utils)!=null&&v.hasLoadedNamespace(o))&&(this.checkedLoadedFor[`${m[0]}-${g}`]=!0,this.logger.warn(`key "${i}" for languages "${m.join(", ")}" won't get resolved as namespace "${o}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),m.forEach(S=>{var U;if(this.isValidLookup(r))return;a=S;const E=[u];if((U=this.i18nFormat)!=null&&U.addLookupKeys)this.i18nFormat.addLookupKeys(E,u,S,g,n);else{let O;h&&(O=this.pluralResolver.getSuffix(S,n.count,n));const k=`${this.options.pluralSeparator}zero`,I=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(h&&(n.ordinal&&O.startsWith(I)&&E.push(u+O.replace(I,this.options.pluralSeparator)),E.push(u+O),f&&E.push(u+k)),p){const R=`${u}${this.options.contextSeparator||"_"}${n.context}`;E.push(R),h&&(n.ordinal&&O.startsWith(I)&&E.push(R+O.replace(I,this.options.pluralSeparator)),E.push(R+O),f&&E.push(R+k))}}let L;for(;L=E.pop();)this.isValidLookup(r)||(s=L,r=this.getResource(S,g,L,n))}))})}),{res:r,usedKey:i,exactUsedKey:s,usedLng:a,usedNS:o}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,n,r,i={}){var s;return(s=this.i18nFormat)!=null&&s.getResource?this.i18nFormat.getResource(e,n,r,i):this.resourceStore.getResource(e,n,r,i)}getUsedParamsDetails(e={}){const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],r=e.replace&&!Tt(e.replace);let i=r?e.replace:e;if(r&&typeof e.count<"u"&&(i.count=e.count),this.options.interpolation.defaultVariables&&(i={...this.options.interpolation.defaultVariables,...i}),!r){i={...i};for(const s of n)delete i[s]}return i}static hasDefaultValue(e){const n="defaultValue";for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&r.startsWith(n)&&e[r]!==void 0)return!0;return!1}}class lk{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=ia.create("languageUtils")}getScriptPartFromCode(e){if(e=hp(e),!e||!e.includes("-"))return null;const n=e.split("-");return n.length===2||(n.pop(),n[n.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(n.join("-"))}getLanguagePartFromCode(e){if(e=hp(e),!e||!e.includes("-"))return e;const n=e.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(e){if(Tt(e)&&e.includes("-")){let n;try{n=Intl.getCanonicalLocales(e)[0]}catch{}return n&&this.options.lowerCaseLng&&(n=n.toLowerCase()),n||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.includes(e)}getBestMatchFromCodes(e){if(!e)return null;let n;return e.forEach(r=>{if(n)return;const i=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(i))&&(n=i)}),!n&&this.options.supportedLngs&&e.forEach(r=>{if(n)return;const i=this.getScriptPartFromCode(r);if(this.isSupportedCode(i))return n=i;const s=this.getLanguagePartFromCode(r);if(this.isSupportedCode(s))return n=s;n=this.options.supportedLngs.find(a=>a===s?!0:!a.includes("-")&&!s.includes("-")?!1:!!(a.includes("-")&&!s.includes("-")&&a.slice(0,a.indexOf("-"))===s||a.startsWith(s)&&s.length>1))}),n||(n=this.getFallbackCodes(this.options.fallbackLng)[0]),n}getFallbackCodes(e,n){if(!e)return[];if(typeof e=="function"&&(e=e(n)),Tt(e)&&(e=[e]),Array.isArray(e))return e;if(!n)return e.default||[];let r=e[n];return r||(r=e[this.getScriptPartFromCode(n)]),r||(r=e[this.formatLanguageCode(n)]),r||(r=e[this.getLanguagePartFromCode(n)]),r||(r=e.default),r||[]}toResolveHierarchy(e,n){const r=this.getFallbackCodes((n===!1?[]:n)||this.options.fallbackLng||[],e),i=[],s=a=>{a&&(this.isSupportedCode(a)?i.push(a):this.logger.warn(`rejecting language code not found in supportedLngs: ${a}`))};return Tt(e)&&(e.includes("-")||e.includes("_"))?(this.options.load!=="languageOnly"&&s(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&s(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&s(this.getLanguagePartFromCode(e))):Tt(e)&&s(this.formatLanguageCode(e)),r.forEach(a=>{i.includes(a)||s(this.formatLanguageCode(a))}),i}}const ck={zero:0,one:1,two:2,few:3,many:4,other:5},uk={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class MQ{constructor(e,n={}){this.languageUtils=e,this.options=n,this.logger=ia.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,n={}){const r=hp(e==="dev"?"en":e),i=n.ordinal?"ordinal":"cardinal",s=JSON.stringify({cleanedCode:r,type:i});if(s in this.pluralRulesCache)return this.pluralRulesCache[s];let a;try{a=new Intl.PluralRules(r,{type:i})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),uk;if(!e.match(/-|_/))return uk;const l=this.languageUtils.getLanguagePartFromCode(e);a=this.getRule(l,n)}return this.pluralRulesCache[s]=a,a}needsPlural(e,n={}){let r=this.getRule(e,n);return r||(r=this.getRule("dev",n)),(r==null?void 0:r.resolvedOptions().pluralCategories.length)>1}getPluralFormsOfKey(e,n,r={}){return this.getSuffixes(e,r).map(i=>`${n}${i}`)}getSuffixes(e,n={}){let r=this.getRule(e,n);return r||(r=this.getRule("dev",n)),r?r.resolvedOptions().pluralCategories.sort((i,s)=>ck[i]-ck[s]).map(i=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${i}`):[]}getSuffix(e,n,r={}){const i=this.getRule(e,r);return i?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${i.select(n)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",n,r))}}const dk=(t,e,n,r=".",i=!0)=>{let s=AQ(t,e,n);return!s&&i&&Tt(n)&&(s=aE(t,n,r),s===void 0&&(s=aE(e,n,r))),s},ub=t=>t.replace(/\$/g,"$$$$");class hk{constructor(e={}){var n;this.logger=ia.create("interpolator"),this.options=e,this.format=((n=e==null?void 0:e.interpolation)==null?void 0:n.format)||(r=>r),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:n,escapeValue:r,useRawValueToEscape:i,prefix:s,prefixEscaped:a,suffix:o,suffixEscaped:l,formatSeparator:c,unescapeSuffix:u,unescapePrefix:d,nestingPrefix:h,nestingPrefixEscaped:f,nestingSuffix:p,nestingSuffixEscaped:m,nestingOptionsSeparator:g,maxReplaces:b,alwaysFormat:v}=e.interpolation;this.escape=n!==void 0?n:CQ,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=i!==void 0?i:!1,this.prefix=s?Da(s):a||"{{",this.suffix=o?Da(o):l||"}}",this.formatSeparator=c||",",this.unescapePrefix=u?"":d?Da(d):"-",this.unescapeSuffix=this.unescapePrefix?"":u?Da(u):"",this.nestingPrefix=h?Da(h):f||Da("$t("),this.nestingSuffix=p?Da(p):m||Da(")"),this.nestingOptionsSeparator=g||",",this.maxReplaces=b||1e3,this.alwaysFormat=v!==void 0?v:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(n,r)=>(n==null?void 0:n.source)===r?(n.lastIndex=0,n):new RegExp(r,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,n,r,i){var f;let s,a,o;const l=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},c=p=>{if(!p.includes(this.formatSeparator)){const v=dk(n,l,p,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(v,void 0,r,{...i,...n,interpolationkey:p}):v}const m=p.split(this.formatSeparator),g=m.shift().trim(),b=m.join(this.formatSeparator).trim();return this.format(dk(n,l,g,this.options.keySeparator,this.options.ignoreJSONStructure),b,r,{...i,...n,interpolationkey:g})};this.resetRegExp(),!this.escapeValue&&typeof e=="string"&&/\$t\([^)]*\{[^}]*\{\{/.test(e)&&this.logger.warn("nesting options string contains interpolated variables with escapeValue: false — if any of those values are attacker-controlled they can inject additional nesting options (e.g. redirect lng/ns). Sanitise untrusted input before passing it to t(), or keep escapeValue: true.");const u=(i==null?void 0:i.missingInterpolationHandler)||this.options.missingInterpolationHandler,d=((f=i==null?void 0:i.interpolation)==null?void 0:f.skipOnVariables)!==void 0?i.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:p=>ub(p)},{regex:this.regexp,safeValue:p=>this.escapeValue?ub(this.escape(p)):ub(p)}].forEach(p=>{for(o=0;s=p.regex.exec(e);){const m=s[1].trim();if(a=c(m),a===void 0)if(typeof u=="function"){const b=u(e,s,i);a=Tt(b)?b:""}else if(i&&Object.prototype.hasOwnProperty.call(i,m))a="";else if(d){a=s[0];continue}else this.logger.warn(`missed to pass in variable ${m} for interpolating ${e}`),a="";else!Tt(a)&&!this.useRawValueToEscape&&(a=rk(a));const g=p.safeValue(a);if(e=e.replace(s[0],g),d?(p.regex.lastIndex+=a.length,p.regex.lastIndex-=s[0].length):p.regex.lastIndex=0,o++,o>=this.maxReplaces)break}}),e}nest(e,n,r={}){let i,s,a;const o=(l,c)=>{const u=this.nestingOptionsSeparator;if(!l.includes(u))return l;const d=l.split(new RegExp(`${Da(u)}[ ]*{`));let h=`{${d[1]}`;l=d[0],h=this.interpolate(h,a);const f=h.match(/'/g),p=h.match(/"/g);(((f==null?void 0:f.length)??0)%2===0&&!p||((p==null?void 0:p.length)??0)%2!==0)&&(h=h.replace(/'/g,'"'));try{a=JSON.parse(h),c&&(a={...c,...a})}catch(m){return this.logger.warn(`failed parsing options string in nesting for key ${l}`,m),`${l}${u}${h}`}return a.defaultValue&&a.defaultValue.includes(this.prefix)&&delete a.defaultValue,l};for(;i=this.nestingRegexp.exec(e);){let l=[];a={...r},a=a.replace&&!Tt(a.replace)?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;const c=/{.*}/.test(i[1])?i[1].lastIndexOf("}")+1:i[1].indexOf(this.formatSeparator);if(c!==-1&&(l=i[1].slice(c).split(this.formatSeparator).map(u=>u.trim()).filter(Boolean),i[1]=i[1].slice(0,c)),s=n(o.call(this,i[1].trim(),a),a),s&&i[0]===e&&!Tt(s))return s;Tt(s)||(s=rk(s)),s||(this.logger.warn(`missed to resolve ${i[1]} for nesting ${e}`),s=""),l.length&&(s=l.reduce((u,d)=>this.format(u,d,r.lng,{...r,interpolationkey:i[1].trim()}),s.trim())),e=e.replace(i[0],s),this.regexp.lastIndex=0}return e}}const BQ=t=>{let e=t.toLowerCase().trim();const n={};if(t.includes("(")){const r=t.split("(");e=r[0].toLowerCase().trim();const i=r[1].slice(0,-1);e==="currency"&&!i.includes(":")?n.currency||(n.currency=i.trim()):e==="relativetime"&&!i.includes(":")?n.range||(n.range=i.trim()):i.split(";").forEach(a=>{if(a){const[o,...l]=a.split(":"),c=l.join(":").trim().replace(/^'+|'+$/g,""),u=o.trim();n[u]||(n[u]=c),c==="false"&&(n[u]=!1),c==="true"&&(n[u]=!0),isNaN(c)||(n[u]=parseInt(c,10))}})}return{formatName:e,formatOptions:n}},fk=t=>{const e={};return(n,r,i)=>{let s=i;i&&i.interpolationkey&&i.formatParams&&i.formatParams[i.interpolationkey]&&i[i.interpolationkey]&&(s={...s,[i.interpolationkey]:void 0});const a=r+JSON.stringify(s);let o=e[a];return o||(o=t(hp(r),i),e[a]=o),o(n)}},UQ=t=>(e,n,r)=>t(hp(n),r)(e);class jQ{constructor(e={}){this.logger=ia.create("formatter"),this.options=e,this.init(e)}init(e,n={interpolation:{}}){this.formatSeparator=n.interpolation.formatSeparator||",";const r=n.cacheInBuiltFormats?fk:UQ;this.formats={number:r((i,s)=>{const a=new Intl.NumberFormat(i,{...s});return o=>a.format(o)}),currency:r((i,s)=>{const a=new Intl.NumberFormat(i,{...s,style:"currency"});return o=>a.format(o)}),datetime:r((i,s)=>{const a=new Intl.DateTimeFormat(i,{...s});return o=>a.format(o)}),relativetime:r((i,s)=>{const a=new Intl.RelativeTimeFormat(i,{...s});return o=>a.format(o,s.range||"day")}),list:r((i,s)=>{const a=new Intl.ListFormat(i,{...s});return o=>a.format(o)})}}add(e,n){this.formats[e.toLowerCase().trim()]=n}addCached(e,n){this.formats[e.toLowerCase().trim()]=fk(n)}format(e,n,r,i={}){if(!n||e==null)return e;const s=n.split(this.formatSeparator);if(s.length>1&&s[0].indexOf("(")>1&&!s[0].includes(")")&&s.find(o=>o.includes(")"))){const o=s.findIndex(l=>l.includes(")"));s[0]=[s[0],...s.splice(1,o)].join(this.formatSeparator)}return s.reduce((o,l)=>{var d;const{formatName:c,formatOptions:u}=BQ(l);if(this.formats[c]){let h=o;try{const f=((d=i==null?void 0:i.formatParams)==null?void 0:d[i.interpolationkey])||{},p=f.locale||f.lng||i.locale||i.lng||r;h=this.formats[c](o,p,{...u,...i,...f})}catch(f){this.logger.warn(f)}return h}else this.logger.warn(`there was no format function for ${c}`);return o},e)}}const FQ=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class $Q extends mv{constructor(e,n,r,i={}){var s,a;super(),this.backend=e,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=i,this.logger=ia.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=i.maxParallelReads||10,this.readingCalls=0,this.maxRetries=i.maxRetries>=0?i.maxRetries:5,this.retryTimeout=i.retryTimeout>=1?i.retryTimeout:350,this.state={},this.queue=[],(a=(s=this.backend)==null?void 0:s.init)==null||a.call(s,r,i.backend,i)}queueLoad(e,n,r,i){const s={},a={},o={},l={};return e.forEach(c=>{let u=!0;n.forEach(d=>{const h=`${c}|${d}`;!r.reload&&this.store.hasResourceBundle(c,d)?this.state[h]=2:this.state[h]<0||(this.state[h]===1?a[h]===void 0&&(a[h]=!0):(this.state[h]=1,u=!1,a[h]===void 0&&(a[h]=!0),s[h]===void 0&&(s[h]=!0),l[d]===void 0&&(l[d]=!0)))}),u||(o[c]=!0)}),(Object.keys(s).length||Object.keys(a).length)&&this.queue.push({pending:a,pendingCount:Object.keys(a).length,loaded:{},errors:[],callback:i}),{toLoad:Object.keys(s),pending:Object.keys(a),toLoadLanguages:Object.keys(o),toLoadNamespaces:Object.keys(l)}}loaded(e,n,r){const i=e.split("|"),s=i[0],a=i[1];n&&this.emit("failedLoading",s,a,n),!n&&r&&this.store.addResourceBundle(s,a,r,void 0,void 0,{skipCopy:!0}),this.state[e]=n?-1:2,n&&r&&(this.state[e]=0);const o={};this.queue.forEach(l=>{TQ(l.loaded,[s],a),FQ(l,e),n&&l.errors.push(n),l.pendingCount===0&&!l.done&&(Object.keys(l.loaded).forEach(c=>{o[c]||(o[c]={});const u=l.loaded[c];u.length&&u.forEach(d=>{o[c][d]===void 0&&(o[c][d]=!0)})}),l.done=!0,l.errors.length?l.callback(l.errors):l.callback())}),this.emit("loaded",o),this.queue=this.queue.filter(l=>!l.done)}read(e,n,r,i=0,s=this.retryTimeout,a){if(!e.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:n,fcName:r,tried:i,wait:s,callback:a});return}this.readingCalls++;const o=(c,u)=>{if(this.readingCalls--,this.waitingReads.length>0){const d=this.waitingReads.shift();this.read(d.lng,d.ns,d.fcName,d.tried,d.wait,d.callback)}if(c&&u&&i<this.maxRetries){setTimeout(()=>{this.read(e,n,r,i+1,s*2,a)},s);return}a(c,u)},l=this.backend[r].bind(this.backend);if(l.length===2){try{const c=l(e,n);c&&typeof c.then=="function"?c.then(u=>o(null,u)).catch(o):o(null,c)}catch(c){o(c)}return}return l(e,n,o)}prepareLoading(e,n,r={},i){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),i&&i();Tt(e)&&(e=this.languageUtils.toResolveHierarchy(e)),Tt(n)&&(n=[n]);const s=this.queueLoad(e,n,r,i);if(!s.toLoad.length)return s.pending.length||i(),null;s.toLoad.forEach(a=>{this.loadOne(a)})}load(e,n,r){this.prepareLoading(e,n,{},r)}reload(e,n,r){this.prepareLoading(e,n,{reload:!0},r)}loadOne(e,n=""){const r=e.split("|"),i=r[0],s=r[1];this.read(i,s,"read",void 0,void 0,(a,o)=>{a&&this.logger.warn(`${n}loading namespace ${s} for language ${i} failed`,a),!a&&o&&this.logger.log(`${n}loaded namespace ${s} for language ${i}`,o),this.loaded(e,a,o)})}saveMissing(e,n,r,i,s,a={},o=()=>{}){var l,c,u,d,h;if((c=(l=this.services)==null?void 0:l.utils)!=null&&c.hasLoadedNamespace&&!((d=(u=this.services)==null?void 0:u.utils)!=null&&d.hasLoadedNamespace(n))){this.logger.warn(`did not save key "${r}" as the namespace "${n}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(r==null||r==="")){if((h=this.backend)!=null&&h.create){const f={...a,isUpdate:s},p=this.backend.create.bind(this.backend);if(p.length<6)try{let m;p.length===5?m=p(e,n,r,i,f):m=p(e,n,r,i),m&&typeof m.then=="function"?m.then(g=>o(null,g)).catch(o):o(null,m)}catch(m){o(m)}else p(e,n,r,i,o,f)}!e||!e[0]||this.store.addResource(e[0],n,r,i)}}}const db=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:t=>{let e={};if(typeof t[1]=="object"&&(e=t[1]),Tt(t[1])&&(e.defaultValue=t[1]),Tt(t[2])&&(e.tDescription=t[2]),typeof t[2]=="object"||typeof t[3]=="object"){const n=t[3]||t[2];Object.keys(n).forEach(r=>{e[r]=n[r]})}return e},interpolation:{escapeValue:!0,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),pk=t=>(Tt(t.ns)&&(t.ns=[t.ns]),Tt(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),Tt(t.fallbackNS)&&(t.fallbackNS=[t.fallbackNS]),t.supportedLngs&&!t.supportedLngs.includes("cimode")&&(t.supportedLngs=t.supportedLngs.concat(["cimode"])),t),tg=()=>{},VQ=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(n=>{typeof t[n]=="function"&&(t[n]=t[n].bind(t))})};class Cf extends mv{constructor(e={},n){if(super(),this.options=pk(e),this.services={},this.logger=ia,this.modules={external:[]},VQ(this),n&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,n),this;setTimeout(()=>{this.init(e,n)},0)}}init(e={},n){this.isInitializing=!0,typeof e=="function"&&(n=e,e={}),e.defaultNS==null&&e.ns&&(Tt(e.ns)?e.defaultNS=e.ns:e.ns.includes("translation")||(e.defaultNS=e.ns[0]));const r=db();this.options={...r,...this.options,...pk(e)},this.options.interpolation={...r.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=r.overloadTranslationOptionHandler);const i=c=>c?typeof c=="function"?new c:c:null;if(!this.options.isClone){this.modules.logger?ia.init(i(this.modules.logger),this.options):ia.init(null,this.options);let c;this.modules.formatter?c=this.modules.formatter:c=jQ;const u=new lk(this.options);this.store=new ok(this.options.resources,this.options);const d=this.services;d.logger=ia,d.resourceStore=this.store,d.languageUtils=u,d.pluralResolver=new MQ(u,{prepend:this.options.pluralSeparator}),c&&(d.formatter=i(c),d.formatter.init&&d.formatter.init(d,this.options),this.options.interpolation.format=d.formatter.format.bind(d.formatter)),d.interpolator=new hk(this.options),d.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},d.backendConnector=new $Q(i(this.modules.backend),d.resourceStore,d,this.options),d.backendConnector.on("*",(h,...f)=>{this.emit(h,...f)}),this.modules.languageDetector&&(d.languageDetector=i(this.modules.languageDetector),d.languageDetector.init&&d.languageDetector.init(d,this.options.detection,this.options)),this.modules.i18nFormat&&(d.i18nFormat=i(this.modules.i18nFormat),d.i18nFormat.init&&d.i18nFormat.init(this)),this.translator=new c0(this.services,this.options),this.translator.on("*",(h,...f)=>{this.emit(h,...f)}),this.modules.external.forEach(h=>{h.init&&h.init(this)})}if(this.format=this.options.interpolation.format,n||(n=tg),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const c=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);c.length>0&&c[0]!=="dev"&&(this.options.lng=c[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(c=>{this[c]=(...u)=>this.store[c](...u)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(c=>{this[c]=(...u)=>(this.store[c](...u),this)});const o=Vh(),l=()=>{const c=(u,d)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),o.resolve(d),n(u,d)};if((this.languages||this.isLanguageChangingTo)&&!this.isInitialized)return c(null,this.t.bind(this));this.changeLanguage(this.options.lng,c)};return this.options.resources||!this.options.initAsync?l():setTimeout(l,0),o}loadResources(e,n=tg){var s,a;let r=n;const i=Tt(e)?e:this.language;if(typeof e=="function"&&(r=e),!this.options.resources||this.options.partialBundledLanguages){if((i==null?void 0:i.toLowerCase())==="cimode"&&(!this.options.preload||this.options.preload.length===0))return r();const o=[],l=c=>{if(!c||c==="cimode")return;this.services.languageUtils.toResolveHierarchy(c).forEach(d=>{d!=="cimode"&&(o.includes(d)||o.push(d))})};i?l(i):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(u=>l(u)),(a=(s=this.options.preload)==null?void 0:s.forEach)==null||a.call(s,c=>l(c)),this.services.backendConnector.load(o,this.options.ns,c=>{!c&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),r(c)})}else r(null)}reloadResources(e,n,r){const i=Vh();return typeof e=="function"&&(r=e,e=void 0),typeof n=="function"&&(r=n,n=void 0),e||(e=this.languages),n||(n=this.options.ns),r||(r=tg),this.services.backendConnector.reload(e,n,s=>{i.resolve(),r(s)}),i}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return e.type==="backend"&&(this.modules.backend=e),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&(this.modules.languageDetector=e),e.type==="i18nFormat"&&(this.modules.i18nFormat=e),e.type==="postProcessor"&&rj.addPostProcessor(e),e.type==="formatter"&&(this.modules.formatter=e),e.type==="3rdParty"&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!["cimode","dev"].includes(e)){for(let n=0;n<this.languages.length;n++){const r=this.languages[n];if(!["cimode","dev"].includes(r)&&this.store.hasLanguageSomeTranslations(r)){this.resolvedLanguage=r;break}}!this.resolvedLanguage&&!this.languages.includes(e)&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,n){this.isLanguageChangingTo=e;const r=Vh();this.emit("languageChanging",e);const i=o=>{this.language=o,this.languages=this.services.languageUtils.toResolveHierarchy(o),this.resolvedLanguage=void 0,this.setResolvedLanguage(o)},s=(o,l)=>{l?this.isLanguageChangingTo===e&&(i(l),this.translator.changeLanguage(l),this.isLanguageChangingTo=void 0,this.emit("languageChanged",l),this.logger.log("languageChanged",l)):this.isLanguageChangingTo=void 0,r.resolve((...c)=>this.t(...c)),n&&n(o,(...c)=>this.t(...c))},a=o=>{var u,d;!e&&!o&&this.services.languageDetector&&(o=[]);const l=Tt(o)?o:o&&o[0],c=this.store.hasLanguageSomeTranslations(l)?l:this.services.languageUtils.getBestMatchFromCodes(Tt(o)?[o]:o);c&&(this.language||i(c),this.translator.language||this.translator.changeLanguage(c),(d=(u=this.services.languageDetector)==null?void 0:u.cacheUserLanguage)==null||d.call(u,c)),this.loadResources(c,h=>{s(h,c)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?a(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(a):this.services.languageDetector.detect(a):a(e),r}getFixedT(e,n,r){const i=(s,a,...o)=>{let l;typeof a!="object"?l=this.options.overloadTranslationOptionHandler([s,a].concat(o)):l={...a},l.lng=l.lng||i.lng,l.lngs=l.lngs||i.lngs,l.ns=l.ns||i.ns,l.keyPrefix!==""&&(l.keyPrefix=l.keyPrefix||r||i.keyPrefix);const c={...this.options,...l};typeof l.keyPrefix=="function"&&(l.keyPrefix=md(l.keyPrefix,c));const u=this.options.keySeparator||".";let d;return l.keyPrefix&&Array.isArray(s)?d=s.map(h=>(typeof h=="function"&&(h=md(h,c)),`${l.keyPrefix}${u}${h}`)):(typeof s=="function"&&(s=md(s,c)),d=l.keyPrefix?`${l.keyPrefix}${u}${s}`:s),this.t(d,l)};return Tt(e)?i.lng=e:i.lngs=e,i.ns=n,i.keyPrefix=r,i}t(...e){var n;return(n=this.translator)==null?void 0:n.translate(...e)}exists(...e){var n;return(n=this.translator)==null?void 0:n.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,n={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const r=n.lng||this.resolvedLanguage||this.languages[0],i=this.options?this.options.fallbackLng:!1,s=this.languages[this.languages.length-1];if(r.toLowerCase()==="cimode")return!0;const a=(o,l)=>{const c=this.services.backendConnector.state[`${o}|${l}`];return c===-1||c===0||c===2};if(n.precheck){const o=n.precheck(this,a);if(o!==void 0)return o}return!!(this.hasResourceBundle(r,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||a(r,e)&&(!i||a(s,e)))}loadNamespaces(e,n){const r=Vh();return this.options.ns?(Tt(e)&&(e=[e]),e.forEach(i=>{this.options.ns.includes(i)||this.options.ns.push(i)}),this.loadResources(i=>{r.resolve(),n&&n(i)}),r):(n&&n(),Promise.resolve())}loadLanguages(e,n){const r=Vh();Tt(e)&&(e=[e]);const i=this.options.preload||[],s=e.filter(a=>!i.includes(a)&&this.services.languageUtils.isSupportedCode(a));return s.length?(this.options.preload=i.concat(s),this.loadResources(a=>{r.resolve(),n&&n(a)}),r):(n&&n(),Promise.resolve())}dir(e){var i,s;if(e||(e=this.resolvedLanguage||(((i=this.languages)==null?void 0:i.length)>0?this.languages[0]:this.language)),!e)return"rtl";try{const a=new Intl.Locale(e);if(a&&a.getTextInfo){const o=a.getTextInfo();if(o&&o.direction)return o.direction}}catch{}const n=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],r=((s=this.services)==null?void 0:s.languageUtils)||new lk(db());return e.toLowerCase().indexOf("-latn")>1?"ltr":n.includes(r.getLanguagePartFromCode(e))||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},n){const r=new Cf(e,n);return r.createInstance=Cf.createInstance,r}cloneInstance(e={},n=tg){const r=e.forkResourceStore;r&&delete e.forkResourceStore;const i={...this.options,...e,isClone:!0},s=new Cf(i);if((e.debug!==void 0||e.prefix!==void 0)&&(s.logger=s.logger.clone(e)),["store","services","language"].forEach(o=>{s[o]=this[o]}),s.services={...this.services},s.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},r){const o=Object.keys(this.store.data).reduce((l,c)=>(l[c]={...this.store.data[c]},l[c]=Object.keys(l[c]).reduce((u,d)=>(u[d]={...l[c][d]},u),l[c]),l),{});s.store=new ok(o,i),s.services.resourceStore=s.store}if(e.interpolation){const l={...db().interpolation,...this.options.interpolation,...e.interpolation},c={...i,interpolation:l};s.services.interpolator=new hk(c)}return s.translator=new c0(s.services,i),s.translator.on("*",(o,...l)=>{s.emit(o,...l)}),s.init(i,n),s.translator.options=i,s.translator.backendConnector.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},s}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const jr=Cf.createInstance();jr.createInstance;jr.dir;jr.init;jr.loadResources;jr.reloadResources;jr.use;jr.changeLanguage;jr.getFixedT;jr.t;jr.exists;jr.setDefaultNamespace;jr.hasLoadedNamespace;jr.loadNamespaces;jr.loadLanguages;const GQ=(t,e,n,r)=>{var s,a,o,l;const i=[n,{code:e,...r||{}}];if((a=(s=t==null?void 0:t.services)==null?void 0:s.logger)!=null&&a.forward)return t.services.logger.forward(i,"warn","react-i18next::",!0);Bc(i[0])&&(i[0]=`react-i18next:: ${i[0]}`),(l=(o=t==null?void 0:t.services)==null?void 0:o.logger)!=null&&l.warn?t.services.logger.warn(...i):console!=null&&console.warn&&console.warn(...i)},mk={},lE=(t,e,n,r)=>{Bc(n)&&mk[n]||(Bc(n)&&(mk[n]=new Date),GQ(t,e,n,r))},sj=(t,e)=>()=>{if(t.isInitialized)e();else{const n=()=>{setTimeout(()=>{t.off("initialized",n)},0),e()};t.on("initialized",n)}},cE=(t,e,n)=>{t.loadNamespaces(e,sj(t,n))},gk=(t,e,n,r)=>{if(Bc(n)&&(n=[n]),t.options.preload&&t.options.preload.indexOf(e)>-1)return cE(t,n,r);n.forEach(i=>{t.options.ns.indexOf(i)<0&&t.options.ns.push(i)}),t.loadLanguages(e,sj(t,r))},HQ=(t,e,n={})=>!e.languages||!e.languages.length?(lE(e,"NO_LANGUAGES","i18n.languages were undefined or empty",{languages:e.languages}),!0):e.hasLoadedNamespace(t,{lng:n.lng,precheck:(r,i)=>{if(n.bindI18n&&n.bindI18n.indexOf("languageChanging")>-1&&r.services.backendConnector.backend&&r.isLanguageChangingTo&&!i(r.isLanguageChangingTo,t))return!1}}),Bc=t=>typeof t=="string",KQ=t=>typeof t=="object"&&t!==null,zQ=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,qQ={"&amp;":"&","&#38;":"&","&lt;":"<","&#60;":"<","&gt;":">","&#62;":">","&apos;":"'","&#39;":"'","&quot;":'"',"&#34;":'"',"&nbsp;":" ","&#160;":" ","&copy;":"©","&#169;":"©","&reg;":"®","&#174;":"®","&hellip;":"…","&#8230;":"…","&#x2F;":"/","&#47;":"/"},WQ=t=>qQ[t],YQ=t=>t.replace(zQ,WQ);let uE={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:YQ,transDefaultProps:void 0};const XQ=(t={})=>{uE={...uE,...t}},QQ=()=>uE;let aj;const JQ=t=>{aj=t},ZQ=()=>aj,eJ={type:"3rdParty",init(t){XQ(t.options.react),JQ(t)}},tJ=D.createContext();class nJ{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach(n=>{this.usedNamespaces[n]||(this.usedNamespaces[n]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}var oj={exports:{}},lj={};/**
 * @license React
 * use-sync-external-store-shim.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var Xd=D;function rJ(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var iJ=typeof Object.is=="function"?Object.is:rJ,sJ=Xd.useState,aJ=Xd.useEffect,oJ=Xd.useLayoutEffect,lJ=Xd.useDebugValue;function cJ(t,e){var n=e(),r=sJ({inst:{value:n,getSnapshot:e}}),i=r[0].inst,s=r[1];return oJ(function(){i.value=n,i.getSnapshot=e,hb(i)&&s({inst:i})},[t,n,e]),aJ(function(){return hb(i)&&s({inst:i}),t(function(){hb(i)&&s({inst:i})})},[t]),lJ(n),n}function hb(t){var e=t.getSnapshot;t=t.value;try{var n=e();return!iJ(t,n)}catch{return!0}}function uJ(t,e){return e()}var dJ=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?uJ:cJ;lj.useSyncExternalStore=Xd.useSyncExternalStore!==void 0?Xd.useSyncExternalStore:dJ;oj.exports=lj;var hJ=oj.exports;const fJ=(t,e)=>{if(Bc(e))return e;if(KQ(e)&&Bc(e.defaultValue))return e.defaultValue;if(typeof t=="function")return"";if(Array.isArray(t)){const n=t[t.length-1];return typeof n=="function"?"":n}return t},pJ={t:fJ,ready:!1},mJ=()=>()=>{},Wr=(t,e={})=>{var I,R,M;const{i18n:n}=e,{i18n:r,defaultNS:i}=D.useContext(tJ)||{},s=n||r||ZQ();s&&!s.reportNamespaces&&(s.reportNamespaces=new nJ),s||lE(s,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const a=D.useMemo(()=>{var z;return{...QQ(),...(z=s==null?void 0:s.options)==null?void 0:z.react,...e}},[s,e]),{useSuspense:o,keyPrefix:l}=a,c=i||((I=s==null?void 0:s.options)==null?void 0:I.defaultNS),u=Bc(c)?[c]:c||["translation"],d=D.useMemo(()=>u,u);(M=(R=s==null?void 0:s.reportNamespaces)==null?void 0:R.addUsedNamespaces)==null||M.call(R,d);const h=D.useRef(0),f=D.useCallback(z=>{if(!s)return mJ;const{bindI18n:Z,bindI18nStore:W}=a,re=()=>{h.current+=1,z()};return Z&&s.on(Z,re),W&&s.store.on(W,re),()=>{Z&&Z.split(" ").forEach(X=>s.off(X,re)),W&&W.split(" ").forEach(X=>s.store.off(X,re))}},[s,a]),p=D.useRef(),m=D.useCallback(()=>{if(!s)return pJ;const z=!!(s.isInitialized||s.initializedStoreOnce)&&d.every(Q=>HQ(Q,s,a)),Z=e.lng||s.language,W=h.current,re=p.current;if(re&&re.ready===z&&re.lng===Z&&re.keyPrefix===l&&re.revision===W)return re;const oe={t:s.getFixedT(Z,a.nsMode==="fallback"?d:d[0],l),ready:z,lng:Z,keyPrefix:l,revision:W};return p.current=oe,oe},[s,d,l,a,e.lng]),[g,b]=D.useState(0),{t:v,ready:S}=hJ.useSyncExternalStore(f,m,m);D.useEffect(()=>{if(s&&!S&&!o){const z=()=>b(Z=>Z+1);e.lng?gk(s,e.lng,d,z):cE(s,d,z)}},[s,e.lng,d,S,o,g]);const E=s||{},L=D.useRef(null),U=D.useRef(),O=z=>{const Z=Object.getOwnPropertyDescriptors(z);Z.__original&&delete Z.__original;const W=Object.create(Object.getPrototypeOf(z),Z);if(!Object.prototype.hasOwnProperty.call(W,"__original"))try{Object.defineProperty(W,"__original",{value:z,writable:!1,enumerable:!1,configurable:!1})}catch{}return W},k=D.useMemo(()=>{const z=E,Z=z==null?void 0:z.language;let W=z;z&&(L.current&&L.current.__original===z?U.current!==Z?(W=O(z),L.current=W,U.current=Z):W=L.current:(W=O(z),L.current=W,U.current=Z));const re=!S&&!o?(...oe)=>(lE(s,"USE_T_BEFORE_READY","useTranslation: t was called before ready. When using useSuspense: false, make sure to check the ready flag before using t."),v(...oe)):v,X=[re,W,S];return X.t=re,X.i18n=W,X.ready=S,X},[v,E,S,E.resolvedLanguage,E.language,E.languages]);if(s&&o&&!S)throw new Promise(z=>{const Z=()=>z();e.lng?gk(s,e.lng,d,Z):cE(s,d,Z)});return k},gJ=3e3,yJ="nadiplay_splash_shown",vJ=({onFinish:t})=>{const[e,n]=D.useState(!0),r=D.useRef(null),{t:i}=Wr();D.useEffect(()=>{const a=new Audio("/audio/Arrival_Queued.mp3");a.volume=.9,r.current=a,a.play().catch(()=>{});const o=window.setTimeout(()=>{n(!1)},gJ);return()=>{window.clearTimeout(o);try{a.pause()}catch{}}},[]);const s=()=>{try{sessionStorage.setItem(yJ,"1")}catch{}t()};return y.jsx(bh,{onExitComplete:s,children:e&&y.jsxs($t.div,{"data-testid":"splash-screen",initial:{opacity:1},exit:{opacity:0,transition:{duration:.8,ease:"easeInOut"}},className:"fixed inset-0 z-[9999] overflow-hidden",style:{background:"radial-gradient(ellipse at center, hsl(200, 40%, 12%) 0%, hsl(200, 30%, 6%) 55%, #000 100%)"},children:[y.jsx("div",{className:"absolute inset-0 opacity-40 bg-cover bg-center",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),y.jsx("div",{className:"absolute inset-0 bg-background/50"}),y.jsx("div",{className:"absolute inset-0 opacity-[0.07] mix-blend-overlay pointer-events-none",style:{backgroundImage:`url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='140' height='140'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/></filter><rect width='100%' height='100%' filter='url(%23n)'/></svg>")`}}),[0,1,2].map(a=>y.jsx($t.div,{initial:{scale:0,opacity:.7},animate:{scale:4,opacity:0},transition:{duration:2.6,delay:a*.7,repeat:1/0,ease:"easeOut"},className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 rounded-full pointer-events-none",style:{width:220,height:220,border:"1px solid hsla(40, 80%, 55%, 0.45)",boxShadow:"0 0 40px hsla(40, 80%, 55%, 0.25)"}},a)),y.jsx($t.div,{animate:{rotate:360},transition:{duration:12,repeat:1/0,ease:"linear"},className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2",style:{width:360,height:360},children:[...Array(6)].map((a,o)=>y.jsx("div",{className:"absolute top-1/2 left-1/2 w-2 h-2 rounded-full",style:{background:"hsl(40, 85%, 65%)",boxShadow:"0 0 12px hsl(40, 85%, 65%)",transform:`rotate(${o*60}deg) translate(180px) translate(-50%, -50%)`}},o))}),y.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-6 px-6",children:[y.jsxs($t.div,{initial:{scale:0,rotate:-90,opacity:0},animate:{scale:1,rotate:0,opacity:1},transition:{type:"spring",stiffness:180,damping:14,delay:.15},className:"relative",children:[y.jsx("div",{className:"w-24 h-24 md:w-28 md:h-28 rounded-2xl glass flex items-center justify-center",style:{boxShadow:"0 0 60px hsla(40, 80%, 55%, 0.55), inset 0 0 30px hsla(40, 80%, 55%, 0.1)",border:"1px solid hsla(40, 80%, 55%, 0.4)"},children:y.jsx(xa,{className:"w-12 h-12 md:w-14 md:h-14 text-primary gold-glow",strokeWidth:1.2})}),y.jsx($t.div,{animate:{scale:[1,1.25,1],opacity:[.5,0,.5]},transition:{duration:2,repeat:1/0,ease:"easeInOut"},className:"absolute inset-0 rounded-2xl pointer-events-none",style:{border:"1px solid hsla(40, 80%, 55%, 0.6)"}})]}),y.jsx($t.h1,{initial:{opacity:0,letterSpacing:"0.8em",y:20},animate:{opacity:1,letterSpacing:"0.4em",y:0},transition:{duration:1.1,delay:.4,ease:"easeOut"},"data-testid":"splash-wordmark",className:"font-display text-4xl md:text-6xl tracking-[0.4em] gold-text text-center",style:{textShadow:"0 0 30px hsla(40, 80%, 55%, 0.35)"},children:"NADIPLAYER"}),y.jsx($t.p,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.9,delay:1},className:"text-muted-foreground text-xs md:text-sm tracking-[0.5em] uppercase",children:i("splash.tagline")}),y.jsx($t.div,{initial:{opacity:0,width:0},animate:{opacity:1,width:220},transition:{duration:.6,delay:1.2},className:"relative h-[2px] rounded-full overflow-hidden",style:{background:"hsla(40, 80%, 55%, 0.15)"},children:y.jsx($t.div,{initial:{x:"-100%"},animate:{x:"200%"},transition:{duration:1.6,repeat:1/0,ease:"easeInOut",delay:1.2},className:"absolute inset-y-0 w-1/2",style:{background:"linear-gradient(90deg, transparent, hsl(40, 85%, 65%), transparent)"}})})]}),y.jsx($t.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.4,duration:.6},className:"absolute bottom-6 left-0 right-0 text-center text-muted-foreground/70 text-[10px] tracking-[0.4em] uppercase",children:i("splash.premiumTag")})]})})},lA="nadi_auth_token",cA="nadi_auth_user",_J="",Lf=()=>{try{return localStorage.getItem(lA)}catch{return null}},yk=()=>{try{const t=localStorage.getItem(cA);return t?JSON.parse(t):null}catch{return null}},bJ=(t,e)=>{localStorage.setItem(lA,t),localStorage.setItem(cA,JSON.stringify(e))},fb=()=>{localStorage.removeItem(lA),localStorage.removeItem(cA)};function xJ(t){return t==null?"Something went wrong. Please try again.":typeof t=="string"?t:Array.isArray(t)?t.map(e=>e&&typeof e.msg=="string"?e.msg:JSON.stringify(e)).filter(Boolean).join(" "):t&&typeof t.msg=="string"?t.msg:String(t)}async function Ms(t,e,n,r=!1){const i={"Content-Type":"application/json"};if(r){const o=Lf();o&&(i.Authorization=`Bearer ${o}`)}const s=await fetch(`${_J}${e}`,{method:t,headers:i,body:n?JSON.stringify(n):void 0});let a=null;try{a=await s.json()}catch{}if(!s.ok){const o=xJ(a==null?void 0:a.detail)||`HTTP ${s.status}`;throw new Error(o)}return a}const SJ=(t,e)=>Ms("POST","/api/auth/login",{username:t,password:e}),vk=()=>Ms("GET","/api/auth/me",void 0,!0),cj=()=>Ms("GET","/api/subscription/status",void 0,!0),EJ=()=>Ms("GET","/api/admin/users",void 0,!0),wJ=t=>Ms("POST","/api/admin/users",t,!0),pb=(t,e)=>Ms("PUT",`/api/admin/users/${t}`,e,!0),TJ=t=>Ms("DELETE",`/api/admin/users/${t}`,void 0,!0),AJ=()=>Ms("GET","/api/admin/settings",void 0,!0),RJ=t=>Ms("PUT","/api/admin/settings",t,!0),CJ=()=>Ms("GET","/api/shared-profiles",void 0,!0),LJ=()=>Ms("GET","/api/public/playback-mode");var uj={exports:{}};(function(t,e){((n,r)=>{t.exports=r()})(E1,function(){var n=function(_,T){return(n=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(N,B){N.__proto__=B}:function(N,B){for(var V in B)Object.prototype.hasOwnProperty.call(B,V)&&(N[V]=B[V])}))(_,T)},r=function(){return(r=Object.assign||function(_){for(var T,N=1,B=arguments.length;N<B;N++)for(var V in T=arguments[N])Object.prototype.hasOwnProperty.call(T,V)&&(_[V]=T[V]);return _}).apply(this,arguments)};function i(_,T,N){for(var B,V=0,q=T.length;V<q;V++)!B&&V in T||((B=B||Array.prototype.slice.call(T,0,V))[V]=T[V]);return _.concat(B||Array.prototype.slice.call(T))}var s=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:E1,a=Object.keys,o=Array.isArray;function l(_,T){return typeof T=="object"&&a(T).forEach(function(N){_[N]=T[N]}),_}typeof Promise>"u"||s.Promise||(s.Promise=Promise);var c=Object.getPrototypeOf,u={}.hasOwnProperty;function d(_,T){return u.call(_,T)}function h(_,T){typeof T=="function"&&(T=T(c(_))),(typeof Reflect>"u"?a:Reflect.ownKeys)(T).forEach(function(N){p(_,N,T[N])})}var f=Object.defineProperty;function p(_,T,N,B){f(_,T,l(N&&d(N,"get")&&typeof N.get=="function"?{get:N.get,set:N.set,configurable:!0}:{value:N,configurable:!0,writable:!0},B))}function m(_){return{from:function(T){return _.prototype=Object.create(T.prototype),p(_.prototype,"constructor",_),{extend:h.bind(null,_.prototype)}}}}var g=Object.getOwnPropertyDescriptor,b=[].slice;function v(_,T,N){return b.call(_,T,N)}function S(_,T){return T(_)}function E(_){if(!_)throw new Error("Assertion Failed")}function L(_){s.setImmediate?setImmediate(_):setTimeout(_,0)}function U(_,T){if(typeof T=="string"&&d(_,T))return _[T];if(!T)return _;if(typeof T!="string"){for(var N=[],B=0,V=T.length;B<V;++B){var q=U(_,T[B]);N.push(q)}return N}var J,te=T.indexOf(".");return te===-1||(J=_[T.substr(0,te)])==null?void 0:U(J,T.substr(te+1))}function O(_,T,N){if(_&&T!==void 0&&!("isFrozen"in Object&&Object.isFrozen(_)))if(typeof T!="string"&&"length"in T){E(typeof N!="string"&&"length"in N);for(var B=0,V=T.length;B<V;++B)O(_,T[B],N[B])}else{var q,J,te=T.indexOf(".");te!==-1?(q=T.substr(0,te),(te=T.substr(te+1))===""?N===void 0?o(_)&&!isNaN(parseInt(q))?_.splice(q,1):delete _[q]:_[q]=N:O(J=(J=_[q])&&d(_,q)?J:_[q]={},te,N)):N===void 0?o(_)&&!isNaN(parseInt(T))?_.splice(T,1):delete _[T]:_[T]=N}}function k(_){var T,N={};for(T in _)d(_,T)&&(N[T]=_[T]);return N}var I=[].concat;function R(_){return I.apply([],_)}var ie="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(R([8,16,32,64].map(function(_){return["Int","Uint","Float"].map(function(T){return T+_+"Array"})}))).filter(function(_){return s[_]}),M=new Set(ie.map(function(_){return s[_]})),z=null;function Z(_){return z=new WeakMap,_=function T(N){if(!N||typeof N!="object")return N;var B=z.get(N);if(B)return B;if(o(N)){B=[],z.set(N,B);for(var V=0,q=N.length;V<q;++V)B.push(T(N[V]))}else if(M.has(N.constructor))B=N;else{var J,te=c(N);for(J in B=te===Object.prototype?{}:Object.create(te),z.set(N,B),N)d(N,J)&&(B[J]=T(N[J]))}return B}(_),z=null,_}var W={}.toString;function re(_){return W.call(_).slice(8,-1)}var X=typeof Symbol<"u"?Symbol.iterator:"@@iterator",oe=typeof X=="symbol"?function(_){var T;return _!=null&&(T=_[X])&&T.apply(_)}:function(){return null};function Q(_,T){T=_.indexOf(T),0<=T&&_.splice(T,1)}var G={};function H(_){var T,N,B,V;if(arguments.length===1){if(o(_))return _.slice();if(this===G&&typeof _=="string")return[_];if(V=oe(_))for(N=[];!(B=V.next()).done;)N.push(B.value);else{if(_==null)return[_];if(typeof(T=_.length)!="number")return[_];for(N=new Array(T);T--;)N[T]=_[T]}}else for(T=arguments.length,N=new Array(T);T--;)N[T]=arguments[T];return N}var Y=typeof Symbol<"u"?function(_){return _[Symbol.toStringTag]==="AsyncFunction"}:function(){return!1},ie=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],Xt=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(ie),Ce={VersionChanged:"Database version changed by other database connection",DatabaseClosed:"Database has been closed",Abort:"Transaction aborted",TransactionInactive:"Transaction has already completed or failed",MissingAPI:"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb"};function Le(_,T){this.name=_,this.message=T}function ke(_,T){return _+". Errors: "+Object.keys(T).map(function(N){return T[N].toString()}).filter(function(N,B,V){return V.indexOf(N)===B}).join(`
`)}function Ne(_,T,N,B){this.failures=T,this.failedKeys=B,this.successCount=N,this.message=ke(_,T)}function ye(_,T){this.name="BulkError",this.failures=Object.keys(T).map(function(N){return T[N]}),this.failuresByPos=T,this.message=ke(_,this.failures)}m(Le).from(Error).extend({toString:function(){return this.name+": "+this.message}}),m(Ne).from(Le),m(ye).from(Le);var Ie=Xt.reduce(function(_,T){return _[T]=T+"Error",_},{}),Ae=Le,Ee=Xt.reduce(function(_,T){var N=T+"Error";function B(V,q){this.name=N,V?typeof V=="string"?(this.message="".concat(V).concat(q?`
 `+q:""),this.inner=q||null):typeof V=="object"&&(this.message="".concat(V.name," ").concat(V.message),this.inner=V):(this.message=Ce[T]||N,this.inner=null)}return m(B).from(Ae),_[T]=B,_},{}),je=(Ee.Syntax=SyntaxError,Ee.Type=TypeError,Ee.Range=RangeError,ie.reduce(function(_,T){return _[T+"Error"]=Ee[T],_},{}));ie=Xt.reduce(function(_,T){return["Syntax","Type","Range"].indexOf(T)===-1&&(_[T+"Error"]=Ee[T]),_},{});function Me(){}function Pt(_){return _}function tn(_,T){return _==null||_===Pt?T:function(N){return T(_(N))}}function Dn(_,T){return function(){_.apply(this,arguments),T.apply(this,arguments)}}function lt(_,T){return _===Me?T:function(){var N=_.apply(this,arguments),B=(N!==void 0&&(arguments[0]=N),this.onsuccess),V=this.onerror,q=(this.onsuccess=null,this.onerror=null,T.apply(this,arguments));return B&&(this.onsuccess=this.onsuccess?Dn(B,this.onsuccess):B),V&&(this.onerror=this.onerror?Dn(V,this.onerror):V),q!==void 0?q:N}}function un(_,T){return _===Me?T:function(){_.apply(this,arguments);var N=this.onsuccess,B=this.onerror;this.onsuccess=this.onerror=null,T.apply(this,arguments),N&&(this.onsuccess=this.onsuccess?Dn(N,this.onsuccess):N),B&&(this.onerror=this.onerror?Dn(B,this.onerror):B)}}function Sn(_,T){return _===Me?T:function(V){var B=_.apply(this,arguments),V=(l(V,B),this.onsuccess),q=this.onerror,J=(this.onsuccess=null,this.onerror=null,T.apply(this,arguments));return V&&(this.onsuccess=this.onsuccess?Dn(V,this.onsuccess):V),q&&(this.onerror=this.onerror?Dn(q,this.onerror):q),B===void 0?J===void 0?void 0:J:l(B,J)}}function tr(_,T){return _===Me?T:function(){return T.apply(this,arguments)!==!1&&_.apply(this,arguments)}}function Un(_,T){return _===Me?T:function(){var N=_.apply(this,arguments);if(N&&typeof N.then=="function"){for(var B=this,V=arguments.length,q=new Array(V);V--;)q[V]=arguments[V];return N.then(function(){return T.apply(B,q)})}return T.apply(this,arguments)}}ie.ModifyError=Ne,ie.DexieError=Le,ie.BulkError=ye;var En=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function Yr(_){En=_}var vr={},_s=100,Wi=typeof Promise>"u"?[]:(Xt=Promise.resolve(),typeof crypto<"u"&&crypto.subtle?[Wi=crypto.subtle.digest("SHA-512",new Uint8Array([0])),c(Wi),Xt]:[Xt,c(Xt),Xt]),Xt=Wi[0],iu=Wi[1],iu=iu&&iu.then,or=Xt&&Xt.constructor,Ta=!!Wi[2],Yi=function(_,T){Aa.push([_,T]),li&&(queueMicrotask(sn),li=!1)},Ei=!0,li=!0,Xi=[],js=[],Qi=Pt,ci={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:Me,pgp:!1,env:{},finalize:Me},nt=ci,Aa=[],bs=0,Ra=[];function Qe(_){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var T=this._PSD=nt;if(typeof _!="function"){if(_!==vr)throw new TypeError("Not a function");this._state=arguments[1],this._value=arguments[2],this._state===!1&&ui(this,this._value)}else this._state=null,this._value=null,++T.ref,function N(B,V){try{V(function(q){if(B._state===null){if(q===B)throw new TypeError("A promise cannot be resolved with itself.");var J=B._lib&&qn();q&&typeof q.then=="function"?N(B,function(te,he){q instanceof Qe?q._then(te,he):q.then(te,he)}):(B._state=!0,B._value=q,Qc(B)),J&&Wn()}},ui.bind(null,B))}catch(q){ui(B,q)}}(this,_)}var Ml={get:function(){var _=nt,T=C;function N(B,V){var q=this,J=!_.global&&(_!==nt||T!==C),te=J&&!P(),he=new Qe(function(Se,pe){vt(q,new _o(se(B,_,J,te),se(V,_,J,te),Se,pe,_))});return this._consoleTask&&(he._consoleTask=this._consoleTask),he}return N.prototype=vr,N},set:function(_){p(this,"then",_&&_.prototype===vr?Ml:{get:function(){return _},set:Ml.set})}};function _o(_,T,N,B,V){this.onFulfilled=typeof _=="function"?_:null,this.onRejected=typeof T=="function"?T:null,this.resolve=N,this.reject=B,this.psd=V}function ui(_,T){var N,B;js.push(T),_._state===null&&(N=_._lib&&qn(),T=Qi(T),_._state=!1,_._value=T,B=_,Xi.some(function(V){return V._value===B._value})||Xi.push(B),Qc(_),N)&&Wn()}function Qc(_){var T=_._listeners;_._listeners=[];for(var N=0,B=T.length;N<B;++N)vt(_,T[N]);var V=_._PSD;--V.ref||V.finalize(),bs===0&&(++bs,Yi(function(){--bs==0&&lr()},[]))}function vt(_,T){if(_._state===null)_._listeners.push(T);else{var N=_._state?T.onFulfilled:T.onRejected;if(N===null)return(_._state?T.resolve:T.reject)(_._value);++T.psd.ref,++bs,Yi(jt,[N,_,T])}}function jt(_,T,N){try{var B,V=T._value;!T._state&&js.length&&(js=[]),B=En&&T._consoleTask?T._consoleTask.run(function(){return _(V)}):_(V),T._state||js.indexOf(V)!==-1||(q=>{for(var J=Xi.length;J;)if(Xi[--J]._value===q._value)return Xi.splice(J,1)})(T),N.resolve(B)}catch(q){N.reject(q)}finally{--bs==0&&lr(),--N.psd.ref||N.psd.finalize()}}function sn(){ee(ci,function(){qn()&&Wn()})}function qn(){var _=Ei;return li=Ei=!1,_}function Wn(){var _,T,N;do for(;0<Aa.length;)for(_=Aa,Aa=[],N=_.length,T=0;T<N;++T){var B=_[T];B[0].apply(null,B[1])}while(0<Aa.length);li=Ei=!0}function lr(){for(var _=Xi,T=(Xi=[],_.forEach(function(B){B._PSD.onunhandled.call(null,B._value,B)}),Ra.slice(0)),N=T.length;N;)T[--N]()}function Xr(_){return new Qe(vr,!1,_)}function At(_,T){var N=nt;return function(){var B=qn(),V=nt;try{return K(N,!0),_.apply(this,arguments)}catch(q){T&&T(q)}finally{K(V,!1),B&&Wn()}}}h(Qe.prototype,{then:Ml,_then:function(_,T){vt(this,new _o(null,null,_,T,nt))},catch:function(_){var T,N;return arguments.length===1?this.then(null,_):(T=_,N=arguments[1],typeof T=="function"?this.then(null,function(B){return(B instanceof T?N:Xr)(B)}):this.then(null,function(B){return(B&&B.name===T?N:Xr)(B)}))},finally:function(_){return this.then(function(T){return Qe.resolve(_()).then(function(){return T})},function(T){return Qe.resolve(_()).then(function(){return Xr(T)})})},timeout:function(_,T){var N=this;return _<1/0?new Qe(function(B,V){var q=setTimeout(function(){return V(new Ee.Timeout(T))},_);N.then(B,V).finally(clearTimeout.bind(null,q))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&p(Qe.prototype,Symbol.toStringTag,"Dexie.Promise"),ci.env=ne(),h(Qe,{all:function(){var _=H.apply(null,arguments).map(F);return new Qe(function(T,N){_.length===0&&T([]);var B=_.length;_.forEach(function(V,q){return Qe.resolve(V).then(function(J){_[q]=J,--B||T(_)},N)})})},resolve:function(_){return _ instanceof Qe?_:_&&typeof _.then=="function"?new Qe(function(T,N){_.then(T,N)}):new Qe(vr,!0,_)},reject:Xr,race:function(){var _=H.apply(null,arguments).map(F);return new Qe(function(T,N){_.map(function(B){return Qe.resolve(B).then(T,N)})})},PSD:{get:function(){return nt},set:function(_){return nt=_}},totalEchoes:{get:function(){return C}},newPSD:w,usePSD:ee,scheduler:{get:function(){return Yi},set:function(_){Yi=_}},rejectionMapper:{get:function(){return Qi},set:function(_){Qi=_}},follow:function(_,T){return new Qe(function(N,B){return w(function(V,q){var J=nt;J.unhandleds=[],J.onunhandled=q,J.finalize=Dn(function(){var te,he=this;te=function(){he.unhandleds.length===0?V():q(he.unhandleds[0])},Ra.push(function Se(){te(),Ra.splice(Ra.indexOf(Se),1)}),++bs,Yi(function(){--bs==0&&lr()},[])},J.finalize),_()},T,N,B)})}}),or&&(or.allSettled&&p(Qe,"allSettled",function(){var _=H.apply(null,arguments).map(F);return new Qe(function(T){_.length===0&&T([]);var N=_.length,B=new Array(N);_.forEach(function(V,q){return Qe.resolve(V).then(function(J){return B[q]={status:"fulfilled",value:J}},function(J){return B[q]={status:"rejected",reason:J}}).then(function(){return--N||T(B)})})})}),or.any&&typeof AggregateError<"u"&&p(Qe,"any",function(){var _=H.apply(null,arguments).map(F);return new Qe(function(T,N){_.length===0&&N(new AggregateError([]));var B=_.length,V=new Array(B);_.forEach(function(q,J){return Qe.resolve(q).then(function(te){return T(te)},function(te){V[J]=te,--B||N(new AggregateError(V))})})})}),or.withResolvers)&&(Qe.withResolvers=or.withResolvers);var nn={awaits:0,echoes:0,id:0},Ov=0,Cn=[],Jc=0,C=0,A=0;function w(_,J,N,B){var V=nt,q=Object.create(V),J=(q.parent=V,q.ref=0,q.global=!1,q.id=++A,ci.env,q.env=Ta?{Promise:Qe,PromiseProp:{value:Qe,configurable:!0,writable:!0},all:Qe.all,race:Qe.race,allSettled:Qe.allSettled,any:Qe.any,resolve:Qe.resolve,reject:Qe.reject}:{},J&&l(q,J),++V.ref,q.finalize=function(){--this.parent.ref||this.parent.finalize()},ee(q,_,N,B));return q.ref===0&&q.finalize(),J}function x(){return nn.id||(nn.id=++Ov),++nn.awaits,nn.echoes+=_s,nn.id}function P(){return!!nn.awaits&&(--nn.awaits==0&&(nn.id=0),nn.echoes=nn.awaits*_s,!0)}function F(_){return nn.echoes&&_&&_.constructor===or?(x(),_.then(function(T){return P(),T},function(T){return P(),ae(T)})):_}function $(){var _=Cn[Cn.length-1];Cn.pop(),K(_,!1)}function K(_,T){var N,B,V=nt;(T?!nn.echoes||Jc++&&_===nt:!Jc||--Jc&&_===nt)||queueMicrotask(T?(function(q){++C,nn.echoes&&--nn.echoes!=0||(nn.echoes=nn.awaits=nn.id=0),Cn.push(nt),K(q,!0)}).bind(null,_):$),_!==nt&&(nt=_,V===ci&&(ci.env=ne()),Ta)&&(N=ci.env.Promise,B=_.env,V.global||_.global)&&(Object.defineProperty(s,"Promise",B.PromiseProp),N.all=B.all,N.race=B.race,N.resolve=B.resolve,N.reject=B.reject,B.allSettled&&(N.allSettled=B.allSettled),B.any)&&(N.any=B.any)}function ne(){var _=s.Promise;return Ta?{Promise:_,PromiseProp:Object.getOwnPropertyDescriptor(s,"Promise"),all:_.all,race:_.race,allSettled:_.allSettled,any:_.any,resolve:_.resolve,reject:_.reject}:{}}function ee(_,T,N,B,V){var q=nt;try{return K(_,!0),T(N,B,V)}finally{K(q,!1)}}function se(_,T,N,B){return typeof _!="function"?_:function(){var V=nt;N&&x(),K(T,!0);try{return _.apply(this,arguments)}finally{K(V,!1),B&&queueMicrotask(P)}}}function le(_){Promise===or&&nn.echoes===0?Jc===0?_():enqueueNativeMicroTask(_):setTimeout(_,0)}(""+iu).indexOf("[native code]")===-1&&(x=P=Me);var ae=Qe.reject,ce="",Te="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",Be="String expected.",Pe="__dbnames",Je="readonly",Ye="readwrite";function Ge(_,T){return _?T?function(){return _.apply(this,arguments)&&T.apply(this,arguments)}:_:T}var ut={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function bt(_){return typeof _!="string"||/\./.test(_)?function(T){return T}:function(T){return T[_]===void 0&&_ in T&&delete(T=Z(T))[_],T}}function Xe(){throw Ee.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.")}function Ke(_,T){try{var N=Rt(_),B=Rt(T);if(N!==B)return N==="Array"?1:B==="Array"?-1:N==="binary"?1:B==="binary"?-1:N==="string"?1:B==="string"?-1:N==="Date"?1:B!=="Date"?NaN:-1;switch(N){case"number":case"Date":case"string":return T<_?1:_<T?-1:0;case"binary":for(var V=dt(_),q=dt(T),J=V.length,te=q.length,he=J<te?J:te,Se=0;Se<he;++Se)if(V[Se]!==q[Se])return V[Se]<q[Se]?-1:1;return J===te?0:J<te?-1:1;case"Array":for(var pe=_,de=T,fe=pe.length,_e=de.length,me=fe<_e?fe:_e,ge=0;ge<me;++ge){var ve=Ke(pe[ge],de[ge]);if(ve!==0)return ve}return fe===_e?0:fe<_e?-1:1}}catch{}return NaN}function Rt(_){var T=typeof _;return T=="object"&&(ArrayBuffer.isView(_)||(T=re(_))==="ArrayBuffer")?"binary":T}function dt(_){return _ instanceof Uint8Array?_:ArrayBuffer.isView(_)?new Uint8Array(_.buffer,_.byteOffset,_.byteLength):new Uint8Array(_)}function pt(_,T,N){var B=_.schema.yProps;return B?(T&&0<N.numFailures&&(T=T.filter(function(V,q){return!N.failures[q]})),Promise.all(B.map(function(V){return V=V.updatesTable,T?_.db.table(V).where("k").anyOf(T).delete():_.db.table(V).clear()})).then(function(){return N})):N}Jt.prototype.execute=function(_){var T=this["@@propmod"];if(T.add!==void 0){var N=T.add;if(o(N))return i(i([],o(_)?_:[],!0),N).sort();if(typeof N=="number")return(Number(_)||0)+N;if(typeof N=="bigint")try{return BigInt(_)+N}catch{return BigInt(0)+N}throw new TypeError("Invalid term ".concat(N))}if(T.remove!==void 0){var B=T.remove;if(o(B))return o(_)?_.filter(function(V){return!B.includes(V)}).sort():[];if(typeof B=="number")return Number(_)-B;if(typeof B=="bigint")try{return BigInt(_)-B}catch{return BigInt(0)-B}throw new TypeError("Invalid subtrahend ".concat(B))}return N=(N=T.replacePrefix)==null?void 0:N[0],N&&typeof _=="string"&&_.startsWith(N)?T.replacePrefix[1]+_.substring(N.length):_};var Ot=Jt;function Jt(_){this["@@propmod"]=_}function yt(_,T){for(var N=a(T),B=N.length,V=!1,q=0;q<B;++q){var J=N[q],te=T[J],he=U(_,J);te instanceof Ot?(O(_,J,te.execute(he)),V=!0):he!==te&&(O(_,J,te),V=!0)}return V}ht.prototype._trans=function(_,T,N){var B=this._tx||nt.trans,V=this.name,q=En&&typeof console<"u"&&console.createTask&&console.createTask("Dexie: ".concat(_==="readonly"?"read":"write"," ").concat(this.name));function J(Se,pe,de){if(de.schema[V])return T(de.idbtrans,de);throw new Ee.NotFound("Table "+V+" not part of transaction")}var te=qn();try{var he=B&&B.db._novip===this.db._novip?B===nt.trans?B._promise(_,J,N):w(function(){return B._promise(_,J,N)},{trans:B,transless:nt.transless||nt}):function Se(pe,de,fe,_e){if(pe.idbdb&&(pe._state.openComplete||nt.letThrough||pe._vip)){var me=pe._createTransaction(de,fe,pe._dbSchema);try{me.create(),pe._state.PR1398_maxLoop=3}catch(ge){return ge.name===Ie.InvalidState&&pe.isOpen()&&0<--pe._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),pe.close({disableAutoOpen:!1}),pe.open().then(function(){return Se(pe,de,fe,_e)})):ae(ge)}return me._promise(de,function(ge,ve){return w(function(){return nt.trans=me,_e(ge,ve,me)})}).then(function(ge){if(de==="readwrite")try{me.idbtrans.commit()}catch{}return de==="readonly"?ge:me._completion.then(function(){return ge})})}if(pe._state.openComplete)return ae(new Ee.DatabaseClosed(pe._state.dbOpenError));if(!pe._state.isBeingOpened){if(!pe._state.autoOpen)return ae(new Ee.DatabaseClosed);pe.open().catch(Me)}return pe._state.dbReadyPromise.then(function(){return Se(pe,de,fe,_e)})}(this.db,_,[this.name],J);return q&&(he._consoleTask=q,he=he.catch(function(Se){return console.trace(Se),ae(Se)})),he}finally{te&&Wn()}},ht.prototype.get=function(_,T){var N=this;return _&&_.constructor===Object?this.where(_).first(T):_==null?ae(new Ee.Type("Invalid argument to Table.get()")):this._trans("readonly",function(B){return N.core.get({trans:B,key:_}).then(function(V){return N.hook.reading.fire(V)})}).then(T)},ht.prototype.where=function(_){if(typeof _=="string")return new this.db.WhereClause(this,_);if(o(_))return new this.db.WhereClause(this,"[".concat(_.join("+"),"]"));var T=a(_);if(T.length===1)return this.where(T[0]).equals(_[T[0]]);var N=this.schema.indexes.concat(this.schema.primKey).filter(function(te){if(te.compound&&T.every(function(Se){return 0<=te.keyPath.indexOf(Se)})){for(var he=0;he<T.length;++he)if(T.indexOf(te.keyPath[he])===-1)return!1;return!0}return!1}).sort(function(te,he){return te.keyPath.length-he.keyPath.length})[0];if(N&&this.db._maxKey!==ce)return J=N.keyPath.slice(0,T.length),this.where(J).equals(J.map(function(te){return _[te]}));!N&&En&&console.warn("The query ".concat(JSON.stringify(_)," on ").concat(this.name," would benefit from a ")+"compound index [".concat(T.join("+"),"]"));var B=this.schema.idxByName;function V(te,he){return Ke(te,he)===0}var J=T.reduce(function(pe,he){var Se=pe[0],pe=pe[1],de=B[he],fe=_[he];return[Se||de,Se||!de?Ge(pe,de&&de.multi?function(_e){return _e=U(_e,he),o(_e)&&_e.some(function(me){return V(fe,me)})}:function(_e){return V(fe,U(_e,he))}):pe]},[null,null]),q=J[0],J=J[1];return q?this.where(q.name).equals(_[q.keyPath]).filter(J):N?this.filter(J):this.where(T).equals("")},ht.prototype.filter=function(_){return this.toCollection().and(_)},ht.prototype.count=function(_){return this.toCollection().count(_)},ht.prototype.offset=function(_){return this.toCollection().offset(_)},ht.prototype.limit=function(_){return this.toCollection().limit(_)},ht.prototype.each=function(_){return this.toCollection().each(_)},ht.prototype.toArray=function(_){return this.toCollection().toArray(_)},ht.prototype.toCollection=function(){return new this.db.Collection(new this.db.WhereClause(this))},ht.prototype.orderBy=function(_){return new this.db.Collection(new this.db.WhereClause(this,o(_)?"[".concat(_.join("+"),"]"):_))},ht.prototype.reverse=function(){return this.toCollection().reverse()},ht.prototype.mapToClass=function(_){for(var T=this.db,N=this.name,B=((this.schema.mappedClass=_).prototype instanceof Xe&&(_=(J=>{var te=pe,he=J;if(typeof he!="function"&&he!==null)throw new TypeError("Class extends value "+String(he)+" is not a constructor or null");function Se(){this.constructor=te}function pe(){return J!==null&&J.apply(this,arguments)||this}return n(te,he),te.prototype=he===null?Object.create(he):(Se.prototype=he.prototype,new Se),Object.defineProperty(pe.prototype,"db",{get:function(){return T},enumerable:!1,configurable:!0}),pe.prototype.table=function(){return N},pe})(_)),new Set),V=_.prototype;V;V=c(V))Object.getOwnPropertyNames(V).forEach(function(J){return B.add(J)});function q(J){if(!J)return J;var te,he=Object.create(_.prototype);for(te in J)if(!B.has(te))try{he[te]=J[te]}catch{}return he}return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=q,this.hook("reading",q),_},ht.prototype.defineClass=function(){return this.mapToClass(function(_){l(this,_)})},ht.prototype.add=function(_,T){var N=this,B=this.schema.primKey,V=B.auto,q=B.keyPath,J=_;return q&&V&&(J=bt(q)(_)),this._trans("readwrite",function(te){return N.core.mutate({trans:te,type:"add",keys:T!=null?[T]:null,values:[J]})}).then(function(te){return te.numFailures?Qe.reject(te.failures[0]):te.lastResult}).then(function(te){if(q)try{O(_,q,te)}catch{}return te})},ht.prototype.upsert=function(_,T){var N=this,B=this.schema.primKey.keyPath;return this._trans("readwrite",function(V){return N.core.get({trans:V,key:_}).then(function(q){var J=q??{};return yt(J,T),B&&O(J,B,_),N.core.mutate({trans:V,type:"put",values:[J],keys:[_],upsert:!0,updates:{keys:[_],changeSpecs:[T]}}).then(function(te){return te.numFailures?Qe.reject(te.failures[0]):!!q})})})},ht.prototype.update=function(_,T){return typeof _!="object"||o(_)?this.where(":id").equals(_).modify(T):(_=U(_,this.schema.primKey.keyPath))===void 0?ae(new Ee.InvalidArgument("Given object does not contain its primary key")):this.where(":id").equals(_).modify(T)},ht.prototype.put=function(_,T){var N=this,B=this.schema.primKey,V=B.auto,q=B.keyPath,J=_;return q&&V&&(J=bt(q)(_)),this._trans("readwrite",function(te){return N.core.mutate({trans:te,type:"put",values:[J],keys:T!=null?[T]:null})}).then(function(te){return te.numFailures?Qe.reject(te.failures[0]):te.lastResult}).then(function(te){if(q)try{O(_,q,te)}catch{}return te})},ht.prototype.delete=function(_){var T=this;return this._trans("readwrite",function(N){return T.core.mutate({trans:N,type:"delete",keys:[_]}).then(function(B){return pt(T,[_],B)}).then(function(B){return B.numFailures?Qe.reject(B.failures[0]):void 0})})},ht.prototype.clear=function(){var _=this;return this._trans("readwrite",function(T){return _.core.mutate({trans:T,type:"deleteRange",range:ut}).then(function(N){return pt(_,null,N)})}).then(function(T){return T.numFailures?Qe.reject(T.failures[0]):void 0})},ht.prototype.bulkGet=function(_){var T=this;return this._trans("readonly",function(N){return T.core.getMany({keys:_,trans:N}).then(function(B){return B.map(function(V){return T.hook.reading.fire(V)})})})},ht.prototype.bulkAdd=function(_,T,N){var B=this,V=Array.isArray(T)?T:void 0,q=(N=N||(V?void 0:T))?N.allKeys:void 0;return this._trans("readwrite",function(J){var te=B.schema.primKey,Se=te.auto,te=te.keyPath;if(te&&V)throw new Ee.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(V&&V.length!==_.length)throw new Ee.InvalidArgument("Arguments objects and keys must have the same length");var he=_.length,Se=te&&Se?_.map(bt(te)):_;return B.core.mutate({trans:J,type:"add",keys:V,values:Se,wantResults:q}).then(function(pe){var de=pe.numFailures,fe=pe.failures;if(de===0)return q?pe.results:pe.lastResult;throw new ye("".concat(B.name,".bulkAdd(): ").concat(de," of ").concat(he," operations failed"),fe)})})},ht.prototype.bulkPut=function(_,T,N){var B=this,V=Array.isArray(T)?T:void 0,q=(N=N||(V?void 0:T))?N.allKeys:void 0;return this._trans("readwrite",function(J){var te=B.schema.primKey,Se=te.auto,te=te.keyPath;if(te&&V)throw new Ee.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(V&&V.length!==_.length)throw new Ee.InvalidArgument("Arguments objects and keys must have the same length");var he=_.length,Se=te&&Se?_.map(bt(te)):_;return B.core.mutate({trans:J,type:"put",keys:V,values:Se,wantResults:q}).then(function(pe){var de=pe.numFailures,fe=pe.failures;if(de===0)return q?pe.results:pe.lastResult;throw new ye("".concat(B.name,".bulkPut(): ").concat(de," of ").concat(he," operations failed"),fe)})})},ht.prototype.bulkUpdate=function(_){var T=this,N=this.core,B=_.map(function(J){return J.key}),V=_.map(function(J){return J.changes}),q=[];return this._trans("readwrite",function(J){return N.getMany({trans:J,keys:B,cache:"clone"}).then(function(te){var he=[],Se=[],pe=(_.forEach(function(de,fe){var _e=de.key,me=de.changes,ge=te[fe];if(ge){for(var ve=0,Re=Object.keys(me);ve<Re.length;ve++){var we=Re[ve],De=me[we];if(we===T.schema.primKey.keyPath){if(Ke(De,_e)!==0)throw new Ee.Constraint("Cannot update primary key in bulkUpdate()")}else O(ge,we,De)}q.push(fe),he.push(_e),Se.push(ge)}}),he.length);return N.mutate({trans:J,type:"put",keys:he,values:Se,updates:{keys:B,changeSpecs:V}}).then(function(de){var fe=de.numFailures,_e=de.failures;if(fe===0)return pe;for(var me=0,ge=Object.keys(_e);me<ge.length;me++){var ve,Re=ge[me],we=q[Number(Re)];we!=null&&(ve=_e[Re],delete _e[Re],_e[we]=ve)}throw new ye("".concat(T.name,".bulkUpdate(): ").concat(fe," of ").concat(pe," operations failed"),_e)})})})},ht.prototype.bulkDelete=function(_){var T=this,N=_.length;return this._trans("readwrite",function(B){return T.core.mutate({trans:B,type:"delete",keys:_}).then(function(V){return pt(T,_,V)})}).then(function(B){var V=B.numFailures,q=B.failures;if(V===0)return B.lastResult;throw new ye("".concat(T.name,".bulkDelete(): ").concat(V," of ").concat(N," operations failed"),q)})};var kt=ht;function ht(){}function vn(_){function T(J,te){if(te){for(var he=arguments.length,Se=new Array(he-1);--he;)Se[he-1]=arguments[he];return N[J].subscribe.apply(null,Se),_}if(typeof J=="string")return N[J]}var N={};T.addEventType=q;for(var B=1,V=arguments.length;B<V;++B)q(arguments[B]);return T;function q(J,te,he){var Se,pe;if(typeof J!="object")return te=te||tr,pe={subscribers:[],fire:he=he||Me,subscribe:function(de){pe.subscribers.indexOf(de)===-1&&(pe.subscribers.push(de),pe.fire=te(pe.fire,de))},unsubscribe:function(de){pe.subscribers=pe.subscribers.filter(function(fe){return fe!==de}),pe.fire=pe.subscribers.reduce(te,he)}},N[J]=T[J]=pe;a(Se=J).forEach(function(de){var fe=Se[de];if(o(fe))q(de,Se[de][0],Se[de][1]);else{if(fe!=="asap")throw new Ee.InvalidArgument("Invalid event config");var _e=q(de,Pt,function(){for(var me=arguments.length,ge=new Array(me);me--;)ge[me]=arguments[me];_e.subscribers.forEach(function(ve){L(function(){ve.apply(null,ge)})})})}})}}function Ar(_,T){return m(T).from({prototype:_}),T}function On(_,T){return!(_.filter||_.algorithm||_.or)&&(T?_.justLimit:!_.replayFilter)}function Rr(_,T){_.filter=Ge(_.filter,T)}function cr(_,T,N){var B=_.replayFilter;_.replayFilter=B?function(){return Ge(B(),T())}:T,_.justLimit=N&&!B}function Yn(_,T){if(_.isPrimKey)return T.primaryKey;var N=T.getIndexByKeyPath(_.index);if(N)return N;throw new Ee.Schema("KeyPath "+_.index+" on object store "+T.name+" is not indexed")}function _r(_,T,N){var B=Yn(_,T.schema);return T.openCursor({trans:N,values:!_.keysOnly,reverse:_.dir==="prev",unique:!!_.unique,query:{index:B,range:_.range}})}function Vt(_,T,N,B){var V,q,J=_.replayFilter?Ge(_.filter,_.replayFilter()):_.filter;return _.or?(V={},q=function(te,he,Se){var pe,de;J&&!J(he,Se,function(fe){return he.stop(fe)},function(fe){return he.fail(fe)})||((de=""+(pe=he.primaryKey))=="[object ArrayBuffer]"&&(de=""+new Uint8Array(pe)),d(V,de))||(V[de]=!0,T(te,he,Se))},Promise.all([_.or._iterate(q,N),Ji(_r(_,B,N),_.algorithm,q,!_.keysOnly&&_.valueMapper)])):Ji(_r(_,B,N),Ge(_.algorithm,J),T,!_.keysOnly&&_.valueMapper)}function Ji(_,T,N,B){var V=At(B?function(q,J,te){return N(B(q),J,te)}:N);return _.then(function(q){if(q)return q.start(function(){var J=function(){return q.continue()};T&&!T(q,function(te){return J=te},function(te){q.stop(te),J=Me},function(te){q.fail(te),J=Me})||V(q.value,q,function(te){return J=te}),J()})})}Gt.prototype._read=function(_,T){var N=this._ctx;return N.error?N.table._trans(null,ae.bind(null,N.error)):N.table._trans("readonly",_).then(T)},Gt.prototype._write=function(_){var T=this._ctx;return T.error?T.table._trans(null,ae.bind(null,T.error)):T.table._trans("readwrite",_,"locked")},Gt.prototype._addAlgorithm=function(_){var T=this._ctx;T.algorithm=Ge(T.algorithm,_)},Gt.prototype._iterate=function(_,T){return Vt(this._ctx,_,T,this._ctx.table.core)},Gt.prototype.clone=function(_){var T=Object.create(this.constructor.prototype),N=Object.create(this._ctx);return _&&l(N,_),T._ctx=N,T},Gt.prototype.raw=function(){return this._ctx.valueMapper=null,this},Gt.prototype.each=function(_){var T=this._ctx;return this._read(function(N){return Vt(T,_,N,T.table.core)})},Gt.prototype.count=function(_){var T=this;return this._read(function(N){var B,V=T._ctx,q=V.table.core;return On(V,!0)?q.count({trans:N,query:{index:Yn(V,q.schema),range:V.range}}).then(function(J){return Math.min(J,V.limit)}):(B=0,Vt(V,function(){return++B,!1},N,q).then(function(){return B}))}).then(_)},Gt.prototype.sortBy=function(_,T){var N=_.split(".").reverse(),B=N[0],V=N.length-1;function q(he,Se){return Se?q(he[N[Se]],Se-1):he[B]}var J=this._ctx.dir==="next"?1:-1;function te(he,Se){return Ke(q(he,V),q(Se,V))*J}return this.toArray(function(he){return he.sort(te)}).then(T)},Gt.prototype.toArray=function(_){var T=this;return this._read(function(N){var B,V,q,J=T._ctx;return On(J,!0)&&0<J.limit?(B=J.valueMapper,V=Yn(J,J.table.core.schema),J.table.core.query({trans:N,limit:J.limit,values:!0,direction:J.dir==="prev"?"prev":void 0,query:{index:V,range:J.range}}).then(function(te){return te=te.result,B?te.map(B):te})):(q=[],Vt(J,function(te){return q.push(te)},N,J.table.core).then(function(){return q}))},_)},Gt.prototype.offset=function(_){var T=this._ctx;return _<=0||(T.offset+=_,On(T)?cr(T,function(){var N=_;return function(B,V){return N===0||(N===1?--N:V(function(){B.advance(N),N=0}),!1)}}):cr(T,function(){var N=_;return function(){return--N<0}})),this},Gt.prototype.limit=function(_){return this._ctx.limit=Math.min(this._ctx.limit,_),cr(this._ctx,function(){var T=_;return function(N,B,V){return--T<=0&&B(V),0<=T}},!0),this},Gt.prototype.until=function(_,T){return Rr(this._ctx,function(N,B,V){return!_(N.value)||(B(V),T)}),this},Gt.prototype.first=function(_){return this.limit(1).toArray(function(T){return T[0]}).then(_)},Gt.prototype.last=function(_){return this.reverse().first(_)},Gt.prototype.filter=function(_){var T;return Rr(this._ctx,function(N){return _(N.value)}),(T=this._ctx).isMatch=Ge(T.isMatch,_),this},Gt.prototype.and=function(_){return this.filter(_)},Gt.prototype.or=function(_){return new this.db.WhereClause(this._ctx.table,_,this)},Gt.prototype.reverse=function(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},Gt.prototype.desc=function(){return this.reverse()},Gt.prototype.eachKey=function(_){var T=this._ctx;return T.keysOnly=!T.isMatch,this.each(function(N,B){_(B.key,B)})},Gt.prototype.eachUniqueKey=function(_){return this._ctx.unique="unique",this.eachKey(_)},Gt.prototype.eachPrimaryKey=function(_){var T=this._ctx;return T.keysOnly=!T.isMatch,this.each(function(N,B){_(B.primaryKey,B)})},Gt.prototype.keys=function(_){var T=this._ctx,N=(T.keysOnly=!T.isMatch,[]);return this.each(function(B,V){N.push(V.key)}).then(function(){return N}).then(_)},Gt.prototype.primaryKeys=function(_){var T=this._ctx;if(On(T,!0)&&0<T.limit)return this._read(function(B){var V=Yn(T,T.table.core.schema);return T.table.core.query({trans:B,values:!1,limit:T.limit,direction:T.dir==="prev"?"prev":void 0,query:{index:V,range:T.range}})}).then(function(B){return B.result}).then(_);T.keysOnly=!T.isMatch;var N=[];return this.each(function(B,V){N.push(V.primaryKey)}).then(function(){return N}).then(_)},Gt.prototype.uniqueKeys=function(_){return this._ctx.unique="unique",this.keys(_)},Gt.prototype.firstKey=function(_){return this.limit(1).keys(function(T){return T[0]}).then(_)},Gt.prototype.lastKey=function(_){return this.reverse().firstKey(_)},Gt.prototype.distinct=function(){var _,T=this._ctx,T=T.index&&T.table.schema.idxByName[T.index];return T&&T.multi&&(_={},Rr(this._ctx,function(B){var B=B.primaryKey.toString(),V=d(_,B);return _[B]=!0,!V})),this},Gt.prototype.modify=function(_){var T=this,N=this._ctx;return this._write(function(B){function V(ge,ve){var Re=ve.failures;fe+=ge-ve.numFailures;for(var we=0,De=a(Re);we<De.length;we++){var $e=De[we];de.push(Re[$e])}}var q=typeof _=="function"?_:function(ge){return yt(ge,_)},J=N.table.core,pe=J.schema.primaryKey,te=pe.outbound,he=pe.extractKey,Se=200,pe=T.db._options.modifyChunkSize,de=(pe&&(Se=typeof pe=="object"?pe[J.name]||pe["*"]||200:pe),[]),fe=0,_e=[],me=_===wh;return T.clone().primaryKeys().then(function(ge){function ve(we){var De=Math.min(Se,ge.length-we),$e=ge.slice(we,we+De);return(me?Promise.resolve([]):J.getMany({trans:B,keys:$e,cache:"immutable"})).then(function(He){var We=[],ze=[],rt=te?[]:null,qe=me?$e:[];if(!me)for(var st=0;st<De;++st){var Ve=He[st],St={value:Z(Ve),primKey:ge[we+st]};q.call(St,St.value,St)!==!1&&(St.value==null?qe.push(ge[we+st]):te||Ke(he(Ve),he(St.value))===0?(ze.push(St.value),te&&rt.push(ge[we+st])):(qe.push(ge[we+st]),We.push(St.value)))}return Promise.resolve(0<We.length&&J.mutate({trans:B,type:"add",values:We}).then(function(Et){for(var It in Et.failures)qe.splice(parseInt(It),1);V(We.length,Et)})).then(function(){return(0<ze.length||Re&&typeof _=="object")&&J.mutate({trans:B,type:"put",keys:rt,values:ze,criteria:Re,changeSpec:typeof _!="function"&&_,isAdditionalChunk:0<we}).then(function(Et){return V(ze.length,Et)})}).then(function(){return(0<qe.length||Re&&me)&&J.mutate({trans:B,type:"delete",keys:qe,criteria:Re,isAdditionalChunk:0<we}).then(function(Et){return pt(N.table,qe,Et)}).then(function(Et){return V(qe.length,Et)})}).then(function(){return ge.length>we+De&&ve(we+Se)})})}var Re=On(N)&&N.limit===1/0&&(typeof _!="function"||me)&&{index:N.index,range:N.range};return ve(0).then(function(){if(0<de.length)throw new Ne("Error modifying one or more objects",de,fe,_e);return ge.length})})})},Gt.prototype.delete=function(){var _=this._ctx,T=_.range;return!On(_)||_.table.schema.yProps||!_.isPrimKey&&T.type!==3?this.modify(wh):this._write(function(N){var B=_.table.core.schema.primaryKey,V=T;return _.table.core.count({trans:N,query:{index:B,range:V}}).then(function(q){return _.table.core.mutate({trans:N,type:"deleteRange",range:V}).then(function(he){var te=he.failures,he=he.numFailures;if(he)throw new Ne("Could not delete some values",Object.keys(te).map(function(Se){return te[Se]}),q-he);return q-he})})})};var xs=Gt;function Gt(){}var wh=function(_,T){return T.value=null};function Nv(_,T){return _<T?-1:_===T?0:1}function pm(_,T){return T<_?-1:_===T?0:1}function ur(_,T,N){return _=_ instanceof bo?new _.Collection(_):_,_._ctx.error=new(N||TypeError)(T),_}function Zi(_){return new _.Collection(_,function(){return Zc("")}).limit(0)}function Bl(_e,T,N,B){var V,q,J,te,he,Se,pe,de=N.length;if(!N.every(function(ge){return typeof ge=="string"}))return ur(_e,Be);function fe(ge){V=ge==="next"?function(Re){return Re.toUpperCase()}:function(Re){return Re.toLowerCase()},q=ge==="next"?function(Re){return Re.toLowerCase()}:function(Re){return Re.toUpperCase()},J=ge==="next"?Nv:pm;var ve=N.map(function(Re){return{lower:q(Re),upper:V(Re)}}).sort(function(Re,we){return J(Re.lower,we.lower)});te=ve.map(function(Re){return Re.upper}),he=ve.map(function(Re){return Re.lower}),pe=(Se=ge)==="next"?"":B}fe("next");var _e=new _e.Collection(_e,function(){return es(te[0],he[de-1]+B)}),me=(_e._ondirectionchange=function(ge){fe(ge)},0);return _e._addAlgorithm(function(ge,ve,Re){var we=ge.key;if(typeof we=="string"){var De=q(we);if(T(De,he,me))return!0;for(var $e=null,He=me;He<de;++He){var We=((ze,rt,qe,st,Ve,St)=>{for(var Et=Math.min(ze.length,st.length),It=-1,qt=0;qt<Et;++qt){var wi=rt[qt];if(wi!==st[qt])return Ve(ze[qt],qe[qt])<0?ze.substr(0,qt)+qe[qt]+qe.substr(qt+1):Ve(ze[qt],st[qt])<0?ze.substr(0,qt)+st[qt]+qe.substr(qt+1):0<=It?ze.substr(0,It)+rt[It]+qe.substr(It+1):null;Ve(ze[qt],wi)<0&&(It=qt)}return Et<st.length&&St==="next"?ze+qe.substr(ze.length):Et<ze.length&&St==="prev"?ze.substr(0,qe.length):It<0?null:ze.substr(0,It)+st[It]+qe.substr(It+1)})(we,De,te[He],he[He],J,Se);We===null&&$e===null?me=He+1:($e===null||0<J($e,We))&&($e=We)}ve($e!==null?function(){ge.continue($e+pe)}:Re)}return!1}),_e}function es(_,T,N,B){return{type:2,lower:_,upper:T,lowerOpen:N,upperOpen:B}}function Zc(_){return{type:1,lower:_,upper:_}}Object.defineProperty(jn.prototype,"Collection",{get:function(){return this._ctx.table.db.Collection},enumerable:!1,configurable:!0}),jn.prototype.between=function(_,T,N,B){N=N!==!1,B=B===!0;try{return 0<this._cmp(_,T)||this._cmp(_,T)===0&&(N||B)&&(!N||!B)?Zi(this):new this.Collection(this,function(){return es(_,T,!N,!B)})}catch{return ur(this,Te)}},jn.prototype.equals=function(_){return _==null?ur(this,Te):new this.Collection(this,function(){return Zc(_)})},jn.prototype.above=function(_){return _==null?ur(this,Te):new this.Collection(this,function(){return es(_,void 0,!0)})},jn.prototype.aboveOrEqual=function(_){return _==null?ur(this,Te):new this.Collection(this,function(){return es(_,void 0,!1)})},jn.prototype.below=function(_){return _==null?ur(this,Te):new this.Collection(this,function(){return es(void 0,_,!1,!0)})},jn.prototype.belowOrEqual=function(_){return _==null?ur(this,Te):new this.Collection(this,function(){return es(void 0,_)})},jn.prototype.startsWith=function(_){return typeof _!="string"?ur(this,Be):this.between(_,_+ce,!0,!0)},jn.prototype.startsWithIgnoreCase=function(_){return _===""?this.startsWith(_):Bl(this,function(T,N){return T.indexOf(N[0])===0},[_],ce)},jn.prototype.equalsIgnoreCase=function(_){return Bl(this,function(T,N){return T===N[0]},[_],"")},jn.prototype.anyOfIgnoreCase=function(){var _=H.apply(G,arguments);return _.length===0?Zi(this):Bl(this,function(T,N){return N.indexOf(T)!==-1},_,"")},jn.prototype.startsWithAnyOfIgnoreCase=function(){var _=H.apply(G,arguments);return _.length===0?Zi(this):Bl(this,function(T,N){return N.some(function(B){return T.indexOf(B)===0})},_,ce)},jn.prototype.anyOf=function(){var _,T,N=this,B=H.apply(G,arguments),V=this._cmp;try{B.sort(V)}catch{return ur(this,Te)}return B.length===0?Zi(this):((_=new this.Collection(this,function(){return es(B[0],B[B.length-1])}))._ondirectionchange=function(q){V=q==="next"?N._ascending:N._descending,B.sort(V)},T=0,_._addAlgorithm(function(q,J,te){for(var he=q.key;0<V(he,B[T]);)if(++T===B.length)return J(te),!1;return V(he,B[T])===0||(J(function(){q.continue(B[T])}),!1)}),_)},jn.prototype.notEqual=function(_){return this.inAnyRange([[-1/0,_],[_,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})},jn.prototype.noneOf=function(){var _=H.apply(G,arguments);if(_.length===0)return new this.Collection(this);try{_.sort(this._ascending)}catch{return ur(this,Te)}var T=_.reduce(function(N,B){return N?N.concat([[N[N.length-1][1],B]]):[[-1/0,B]]},null);return T.push([_[_.length-1],this.db._maxKey]),this.inAnyRange(T,{includeLowers:!1,includeUppers:!1})},jn.prototype.inAnyRange=function(_,Re){var N=this,B=this._cmp,V=this._ascending,q=this._descending,J=this._min,te=this._max;if(_.length===0)return Zi(this);if(!_.every(function(we){return we[0]!==void 0&&we[1]!==void 0&&V(we[0],we[1])<=0}))return ur(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",Ee.InvalidArgument);var he=!Re||Re.includeLowers!==!1,Se=Re&&Re.includeUppers===!0,pe,de=V;function fe(we,De){return de(we[0],De[0])}try{(pe=_.reduce(function(we,De){for(var $e=0,He=we.length;$e<He;++$e){var We=we[$e];if(B(De[0],We[1])<0&&0<B(De[1],We[0])){We[0]=J(We[0],De[0]),We[1]=te(We[1],De[1]);break}}return $e===He&&we.push(De),we},[])).sort(fe)}catch{return ur(this,Te)}var _e=0,me=Se?function(we){return 0<V(we,pe[_e][1])}:function(we){return 0<=V(we,pe[_e][1])},ge=he?function(we){return 0<q(we,pe[_e][0])}:function(we){return 0<=q(we,pe[_e][0])},ve=me,Re=new this.Collection(this,function(){return es(pe[0][0],pe[pe.length-1][1],!he,!Se)});return Re._ondirectionchange=function(we){de=we==="next"?(ve=me,V):(ve=ge,q),pe.sort(fe)},Re._addAlgorithm(function(we,De,$e){for(var He,We=we.key;ve(We);)if(++_e===pe.length)return De($e),!1;return!me(He=We)&&!ge(He)||(N._cmp(We,pe[_e][1])===0||N._cmp(We,pe[_e][0])===0||De(function(){de===V?we.continue(pe[_e][0]):we.continue(pe[_e][1])}),!1)}),Re},jn.prototype.startsWithAnyOf=function(){var _=H.apply(G,arguments);return _.every(function(T){return typeof T=="string"})?_.length===0?Zi(this):this.inAnyRange(_.map(function(T){return[T,T+ce]})):ur(this,"startsWithAnyOf() only works with strings")};var bo=jn;function jn(){}function Qr(_){return At(function(T){return Fs(T),_(T.target.error),!1})}function Fs(_){_.stopPropagation&&_.stopPropagation(),_.preventDefault&&_.preventDefault()}var xo="storagemutated",eu="x-storagemutated-1",ts=vn(null,xo),mm=(ns.prototype._lock=function(){return E(!nt.global),++this._reculock,this._reculock!==1||nt.global||(nt.lockOwnerFor=this),this},ns.prototype._unlock=function(){if(E(!nt.global),--this._reculock==0)for(nt.global||(nt.lockOwnerFor=null);0<this._blockedFuncs.length&&!this._locked();){var _=this._blockedFuncs.shift();try{ee(_[1],_[0])}catch{}}return this},ns.prototype._locked=function(){return this._reculock&&nt.lockOwnerFor!==this},ns.prototype.create=function(_){var T=this;if(this.mode){var N=this.db.idbdb,B=this.db._state.dbOpenError;if(E(!this.idbtrans),!_&&!N)switch(B&&B.name){case"DatabaseClosedError":throw new Ee.DatabaseClosed(B);case"MissingAPIError":throw new Ee.MissingAPI(B.message,B);default:throw new Ee.OpenFailed(B)}if(!this.active)throw new Ee.TransactionInactive;E(this._completion._state===null),(_=this.idbtrans=_||(this.db.core||N).transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability})).onerror=At(function(V){Fs(V),T._reject(_.error)}),_.onabort=At(function(V){Fs(V),T.active&&T._reject(new Ee.Abort(_.error)),T.active=!1,T.on("abort").fire(V)}),_.oncomplete=At(function(){T.active=!1,T._resolve(),"mutatedParts"in _&&ts.storagemutated.fire(_.mutatedParts)})}return this},ns.prototype._promise=function(_,T,N){var B,V=this;return _==="readwrite"&&this.mode!=="readwrite"?ae(new Ee.ReadOnly("Transaction is readonly")):this.active?this._locked()?new Qe(function(q,J){V._blockedFuncs.push([function(){V._promise(_,T,N).then(q,J)},nt])}):N?w(function(){var q=new Qe(function(J,te){V._lock();var he=T(J,te,V);he&&he.then&&he.then(J,te)});return q.finally(function(){return V._unlock()}),q._lib=!0,q}):((B=new Qe(function(q,J){var te=T(q,J,V);te&&te.then&&te.then(q,J)}))._lib=!0,B):ae(new Ee.TransactionInactive)},ns.prototype._root=function(){return this.parent?this.parent._root():this},ns.prototype.waitFor=function(_){var T,N=this._root(),B=Qe.resolve(_),V=(N._waitingFor?N._waitingFor=N._waitingFor.then(function(){return B}):(N._waitingFor=B,N._waitingQueue=[],T=N.idbtrans.objectStore(N.storeNames[0]),function q(){for(++N._spinCount;N._waitingQueue.length;)N._waitingQueue.shift()();N._waitingFor&&(T.get(-1/0).onsuccess=q)}()),N._waitingFor);return new Qe(function(q,J){B.then(function(te){return N._waitingQueue.push(At(q.bind(null,te)))},function(te){return N._waitingQueue.push(At(J.bind(null,te)))}).finally(function(){N._waitingFor===V&&(N._waitingFor=null)})})},ns.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new Ee.Abort))},ns.prototype.table=function(_){var T=this._memoizedTables||(this._memoizedTables={});if(d(T,_))return T[_];var N=this.schema[_];if(N)return(N=new this.db.Table(_,N,this)).core=this.db.core.table(_),T[_]=N;throw new Ee.NotFound("Table "+_+" not part of transaction")},ns);function ns(){}function tu(_,T,N,B,V,q,J,te){return{name:_,keyPath:T,unique:N,multi:B,auto:V,compound:q,src:(N&&!J?"&":"")+(B?"*":"")+(V?"++":"")+Th(T),type:te}}function Th(_){return typeof _=="string"?_:_?"["+[].join.call(_,"+")+"]":""}function nu(_,T,N){return{name:_,primKey:T,indexes:N,mappedClass:null,idxByName:(B=function(V){return[V.name,V]},N.reduce(function(V,q,J){return q=B(q,J),q&&(V[q[0]]=q[1]),V},{}))};var B}var Ah=function(_){try{return _.only([[]]),Ah=function(){return[[]]},[[]]}catch{return Ah=function(){return ce},ce}};function Mv(_){return _==null?function(){}:typeof _=="string"?(T=_).split(".").length===1?function(N){return N[T]}:function(N){return U(N,T)}:function(N){return U(N,_)};var T}function o1(_){return[].slice.call(_)}var Q4=0;function Rh(_){return _==null?":id":typeof _=="string"?_:"[".concat(_.join("+"),"]")}function J4(_,T,J){function B(ve){if(ve.type===3)return null;if(ve.type===4)throw new Error("Cannot convert never type to IDBKeyRange");var _e=ve.lower,me=ve.upper,ge=ve.lowerOpen,ve=ve.upperOpen;return _e===void 0?me===void 0?null:T.upperBound(me,!!ve):me===void 0?T.lowerBound(_e,!!ge):T.bound(_e,me,!!ge,!!ve)}function V(fe){var _e,me,ge=fe.name;return{name:ge,schema:fe,mutate:function(ve){var Re=ve.trans,we=ve.type,De=ve.keys,$e=ve.values,He=ve.range;return new Promise(function(We,ze){We=At(We);var rt=Re.objectStore(ge),qe=rt.keyPath==null,st=we==="put"||we==="add";if(!st&&we!=="delete"&&we!=="deleteRange")throw new Error("Invalid operation type: "+we);var Ve,St=(De||$e||{length:1}).length;if(De&&$e&&De.length!==$e.length)throw new Error("Given keys array must have same length as given values array.");if(St===0)return We({numFailures:0,failures:{},results:[],lastResult:void 0});function Et(Jr){++wi,Fs(Jr)}var It=[],qt=[],wi=0;if(we==="deleteRange"){if(He.type===4)return We({numFailures:wi,failures:qt,results:[],lastResult:void 0});He.type===3?It.push(Ve=rt.clear()):It.push(Ve=rt.delete(B(He)))}else{var qe=st?qe?[$e,De]:[$e,null]:[De,null],Lt=qe[0],$r=qe[1];if(st)for(var Vr=0;Vr<St;++Vr)It.push(Ve=$r&&$r[Vr]!==void 0?rt[we](Lt[Vr],$r[Vr]):rt[we](Lt[Vr])),Ve.onerror=Et;else for(Vr=0;Vr<St;++Vr)It.push(Ve=rt[we](Lt[Vr])),Ve.onerror=Et}function Rm(Jr){Jr=Jr.target.result,It.forEach(function(Fl,e_){return Fl.error!=null&&(qt[e_]=Fl.error)}),We({numFailures:wi,failures:qt,results:we==="delete"?De:It.map(function(Fl){return Fl.result}),lastResult:Jr})}Ve.onerror=function(Jr){Et(Jr),Rm(Jr)},Ve.onsuccess=Rm})},getMany:function(ve){var Re=ve.trans,we=ve.keys;return new Promise(function(De,$e){De=At(De);for(var He,We=Re.objectStore(ge),ze=we.length,rt=new Array(ze),qe=0,st=0,Ve=function(It){It=It.target,rt[It._pos]=It.result,++st===qe&&De(rt)},St=Qr($e),Et=0;Et<ze;++Et)we[Et]!=null&&((He=We.get(we[Et]))._pos=Et,He.onsuccess=Ve,He.onerror=St,++qe);qe===0&&De(rt)})},get:function(ve){var Re=ve.trans,we=ve.key;return new Promise(function(De,$e){De=At(De);var He=Re.objectStore(ge).get(we);He.onsuccess=function(We){return De(We.target.result)},He.onerror=Qr($e)})},query:(_e=he,me=Se,function(ve){return new Promise(function(Re,we){Re=At(Re);var De,$e,He,We,St=ve.trans,ze=ve.values,rt=ve.limit,Ve=ve.query,qe=(qe=ve.direction)!=null?qe:"next",st=rt===1/0?void 0:rt,Et=Ve.index,Ve=Ve.range,St=St.objectStore(ge),St=Et.isPrimaryKey?St:St.index(Et.name),Et=B(Ve);if(rt===0)return Re({result:[]});me?(Ve={query:Et,count:st,direction:qe},(De=ze?St.getAll(Ve):St.getAllKeys(Ve)).onsuccess=function(It){return Re({result:It.target.result})},De.onerror=Qr(we)):_e&&qe==="next"?((De=ze?St.getAll(Et,st):St.getAllKeys(Et,st)).onsuccess=function(It){return Re({result:It.target.result})},De.onerror=Qr(we)):($e=0,He=!ze&&"openKeyCursor"in St?St.openKeyCursor(Et,qe):St.openCursor(Et,qe),We=[],He.onsuccess=function(){var It=He.result;return!It||(We.push(ze?It.value:It.primaryKey),++$e===rt)?Re({result:We}):void It.continue()},He.onerror=Qr(we))})}),openCursor:function(ve){var Re=ve.trans,we=ve.values,De=ve.query,$e=ve.reverse,He=ve.unique;return new Promise(function(We,ze){We=At(We);var st=De.index,rt=De.range,qe=Re.objectStore(ge),qe=st.isPrimaryKey?qe:qe.index(st.name),st=$e?He?"prevunique":"prev":He?"nextunique":"next",Ve=!we&&"openKeyCursor"in qe?qe.openKeyCursor(B(rt),st):qe.openCursor(B(rt),st);Ve.onerror=Qr(ze),Ve.onsuccess=At(function(St){var Et,It,qt,wi,Lt=Ve.result;Lt?(Lt.___id=++Q4,Lt.done=!1,Et=Lt.continue.bind(Lt),It=(It=Lt.continuePrimaryKey)&&It.bind(Lt),qt=Lt.advance.bind(Lt),wi=function(){throw new Error("Cursor not stopped")},Lt.trans=Re,Lt.stop=Lt.continue=Lt.continuePrimaryKey=Lt.advance=function(){throw new Error("Cursor not started")},Lt.fail=At(ze),Lt.next=function(){var $r=this,Vr=1;return this.start(function(){return Vr--?$r.continue():$r.stop()}).then(function(){return $r})},Lt.start=function($r){function Vr(){if(Ve.result)try{$r()}catch(Jr){Lt.fail(Jr)}else Lt.done=!0,Lt.start=function(){throw new Error("Cursor behind last entry")},Lt.stop()}var Rm=new Promise(function(Jr,Fl){Jr=At(Jr),Ve.onerror=Qr(Fl),Lt.fail=Fl,Lt.stop=function(e_){Lt.stop=Lt.continue=Lt.continuePrimaryKey=Lt.advance=wi,Jr(e_)}});return Ve.onsuccess=At(function(Jr){Ve.onsuccess=Vr,Vr()}),Lt.continue=Et,Lt.continuePrimaryKey=It,Lt.advance=qt,Vr(),Rm},We(Lt)):We(null)},ze)})},count:function(ve){var Re=ve.query,we=ve.trans,De=Re.index,$e=Re.range;return new Promise(function(He,We){var ze=we.objectStore(ge),ze=De.isPrimaryKey?ze:ze.index(De.name),rt=B($e),rt=rt?ze.count(rt):ze.count();rt.onsuccess=At(function(qe){return He(qe.target.result)}),rt.onerror=Qr(We)})}}}q=J,te=o1((J=_).objectStoreNames),pe=0<te.length?q.objectStore(te[0]):{};var q,J={schema:{name:J.name,tables:te.map(function(fe){return q.objectStore(fe)}).map(function(fe){var _e=fe.keyPath,me=fe.autoIncrement,ve=o(_e),ge={},ve={name:fe.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:_e==null,compound:ve,keyPath:_e,autoIncrement:me,unique:!0,extractKey:Mv(_e)},indexes:o1(fe.indexNames).map(function(Re){return fe.index(Re)}).map(function($e){var He=$e.name,we=$e.unique,De=$e.multiEntry,$e=$e.keyPath,He={name:He,compound:o($e),keyPath:$e,unique:we,multiEntry:De,extractKey:Mv($e)};return ge[Rh($e)]=He}),getIndexByKeyPath:function(Re){return ge[Rh(Re)]}};return ge[":id"]=ve.primaryKey,_e!=null&&(ge[Rh(_e)]=ve.primaryKey),ve})},hasGetAll:0<te.length&&"getAll"in pe&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604),hasIdb3Features:"getAllRecords"in pe},te=J.schema,he=J.hasGetAll,Se=J.hasIdb3Features,pe=te.tables.map(V),de={};return pe.forEach(function(fe){return de[fe.name]=fe}),{stack:"dbcore",transaction:_.transaction.bind(_),table:function(fe){if(de[fe])return de[fe];throw new Error("Table '".concat(fe,"' not found"))},MIN_KEY:-1/0,MAX_KEY:Ah(T),schema:te}}function Z4(_,T,N,B){return N=N.IDBKeyRange,T=J4(T,N,B),{dbcore:_.dbcore.reduce(function(V,q){return q=q.create,r(r({},V),q(V))},T)}}function gm(_,T){var N=T.db,N=Z4(_._middlewares,N,_._deps,T);_.core=N.dbcore,_.tables.forEach(function(B){var V=B.name;_.core.schema.tables.some(function(q){return q.name===V})&&(B.core=_.core.table(V),_[V]instanceof _.Table)&&(_[V].core=B.core)})}function ym(_,T,N,B){N.forEach(function(V){var q=B[V];T.forEach(function(J){var te=function he(Se,pe){return g(Se,pe)||(Se=c(Se))&&he(Se,pe)}(J,V);(!te||"value"in te&&te.value===void 0)&&(J===_.Transaction.prototype||J instanceof _.Transaction?p(J,V,{get:function(){return this.table(V)},set:function(he){f(this,V,{value:he,writable:!0,configurable:!0,enumerable:!0})}}):J[V]=new _.Table(V,q))})})}function Bv(_,T){T.forEach(function(N){for(var B in N)N[B]instanceof _.Table&&delete N[B]})}function e$(_,T){return _._cfg.version-T._cfg.version}function t$(_,T,N,B){var V=_._dbSchema,q=(N.objectStoreNames.contains("$meta")&&!V.$meta&&(V.$meta=nu("$meta",c1("")[0],[]),_._storeNames.push("$meta")),_._createTransaction("readwrite",_._storeNames,V)),J=(q.create(N),q._completion.catch(B),q._reject.bind(q)),te=nt.transless||nt;w(function(){if(nt.trans=q,nt.transless=te,T!==0)return gm(_,N),Se=T,((he=q).storeNames.includes("$meta")?he.table("$meta").get("version").then(function(pe){return pe??Se}):Qe.resolve(Se)).then(function(ve){var de=_,fe=ve,_e=q,me=N,ge=[],ve=de._versions,Re=de._dbSchema=_m(0,de.idbdb,me);return(ve=ve.filter(function(we){return we._cfg.version>=fe})).length===0?Qe.resolve():(ve.forEach(function(we){ge.push(function(){var De,$e,He,We=Re,ze=we._cfg.dbschema,rt=(bm(de,We,me),bm(de,ze,me),Re=de._dbSchema=ze,Uv(We,ze)),qe=(rt.add.forEach(function(st){jv(me,st[0],st[1].primKey,st[1].indexes)}),rt.change.forEach(function(st){if(st.recreate)throw new Ee.Upgrade("Not yet support for changing primary key");var Ve=me.objectStore(st.name);st.add.forEach(function(St){return vm(Ve,St)}),st.change.forEach(function(St){Ve.deleteIndex(St.name),vm(Ve,St)}),st.del.forEach(function(St){return Ve.deleteIndex(St)})}),we._cfg.contentUpgrade);if(qe&&we._cfg.version>fe)return gm(de,me),_e._memoizedTables={},De=k(ze),rt.del.forEach(function(st){De[st]=We[st]}),Bv(de,[de.Transaction.prototype]),ym(de,[de.Transaction.prototype],a(De),De),_e.schema=De,($e=Y(qe))&&x(),ze=Qe.follow(function(){var st;(He=qe(_e))&&$e&&(st=P.bind(null,null),He.then(st,st))}),He&&typeof He.then=="function"?Qe.resolve(He):ze.then(function(){return He})}),ge.push(function(De){var $e,He,We=we._cfg.dbschema;$e=We,He=De,[].slice.call(He.db.objectStoreNames).forEach(function(ze){return $e[ze]==null&&He.db.deleteObjectStore(ze)}),Bv(de,[de.Transaction.prototype]),ym(de,[de.Transaction.prototype],de._storeNames,de._dbSchema),_e.schema=de._dbSchema}),ge.push(function(De){de.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(de.idbdb.version/10)===we._cfg.version?(de.idbdb.deleteObjectStore("$meta"),delete de._dbSchema.$meta,de._storeNames=de._storeNames.filter(function($e){return $e!=="$meta"})):De.objectStore("$meta").put(we._cfg.version,"version"))})}),function we(){return ge.length?Qe.resolve(ge.shift()(_e.idbtrans)).then(we):Qe.resolve()}().then(function(){l1(Re,me)}))}).catch(J);var he,Se;a(V).forEach(function(pe){jv(N,pe,V[pe].primKey,V[pe].indexes)}),gm(_,N),Qe.follow(function(){return _.on.populate.fire(q)}).catch(J)})}function n$(_,T){l1(_._dbSchema,T),T.db.version%10!=0||T.objectStoreNames.contains("$meta")||T.db.createObjectStore("$meta").add(Math.ceil(T.db.version/10-1),"version");var N=_m(0,_.idbdb,T);bm(_,_._dbSchema,T);for(var B=0,V=Uv(N,_._dbSchema).change;B<V.length;B++){var q=(J=>{if(J.change.length||J.recreate)return console.warn("Unable to patch indexes of table ".concat(J.name," because it has changes on the type of index or primary key.")),{value:void 0};var te=T.objectStore(J.name);J.add.forEach(function(he){En&&console.debug("Dexie upgrade patch: Creating missing index ".concat(J.name,".").concat(he.src)),vm(te,he)})})(V[B]);if(typeof q=="object")return q.value}}function Uv(_,T){var N,B={del:[],add:[],change:[]};for(N in _)T[N]||B.del.push(N);for(N in T){var V=_[N],q=T[N];if(V){var J={name:N,def:q,recreate:!1,del:[],add:[],change:[]};if(""+(V.primKey.keyPath||"")!=""+(q.primKey.keyPath||"")||V.primKey.auto!==q.primKey.auto)J.recreate=!0,B.change.push(J);else{var te=V.idxByName,he=q.idxByName,Se=void 0;for(Se in te)he[Se]||J.del.push(Se);for(Se in he){var pe=te[Se],de=he[Se];pe?pe.src!==de.src&&J.change.push(de):J.add.push(de)}(0<J.del.length||0<J.add.length||0<J.change.length)&&B.change.push(J)}}else B.add.push([N,q])}return B}function jv(_,T,N,B){var V=_.db.createObjectStore(T,N.keyPath?{keyPath:N.keyPath,autoIncrement:N.auto}:{autoIncrement:N.auto});B.forEach(function(q){return vm(V,q)})}function l1(_,T){a(_).forEach(function(N){T.db.objectStoreNames.contains(N)||(En&&console.debug("Dexie: Creating missing table",N),jv(T,N,_[N].primKey,_[N].indexes))})}function vm(_,T){_.createIndex(T.name,T.keyPath,{unique:T.unique,multiEntry:T.multi})}function _m(_,T,N){var B={};return v(T.objectStoreNames,0).forEach(function(V){for(var q=N.objectStore(V),J=tu(Th(Se=q.keyPath),Se||"",!0,!1,!!q.autoIncrement,Se&&typeof Se!="string",!0),te=[],he=0;he<q.indexNames.length;++he){var pe=q.index(q.indexNames[he]),Se=pe.keyPath,pe=tu(pe.name,Se,!!pe.unique,!!pe.multiEntry,!1,Se&&typeof Se!="string",!1);te.push(pe)}B[V]=nu(V,J,te)}),B}function bm(_,T,N){for(var B=N.db.objectStoreNames,V=0;V<B.length;++V){var q=B[V],J=N.objectStore(q);_._hasGetAll="getAll"in J;for(var te=0;te<J.indexNames.length;++te){var he,Se=J.indexNames[te],pe=J.index(Se).keyPath,pe=typeof pe=="string"?pe:"["+v(pe).join("+")+"]";T[q]&&(he=T[q].idxByName[pe])&&(he.name=Se,delete T[q].idxByName[pe],T[q].idxByName[Se]=he)}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&s.WorkerGlobalScope&&s instanceof s.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(_._hasGetAll=!1)}function c1(_){return _.split(",").map(function(T,N){var V=T.split(":"),B=(B=V[1])==null?void 0:B.trim(),V=(T=V[0].trim()).replace(/([&*]|\+\+)/g,""),q=/^\[/.test(V)?V.match(/^\[(.*)\]$/)[1].split("+"):V;return tu(V,q||null,/\&/.test(T),/\*/.test(T),/\+\+/.test(T),o(q),N===0,B)})}ru.prototype._createTableSchema=nu,ru.prototype._parseIndexSyntax=c1,ru.prototype._parseStoresSpec=function(_,T){var N=this;a(_).forEach(function(B){if(_[B]!==null){var V=N._parseIndexSyntax(_[B]),q=V.shift();if(!q)throw new Ee.Schema("Invalid schema for table "+B+": "+_[B]);if(q.unique=!0,q.multi)throw new Ee.Schema("Primary key cannot be multiEntry*");V.forEach(function(J){if(J.auto)throw new Ee.Schema("Only primary key can be marked as autoIncrement (++)");if(!J.keyPath)throw new Ee.Schema("Index must have a name and cannot be an empty string")}),q=N._createTableSchema(B,q,V),T[B]=q}})},ru.prototype.stores=function(N){var T=this.db,N=(this._cfg.storesSource=this._cfg.storesSource?l(this._cfg.storesSource,N):N,T._versions),B={},V={};return N.forEach(function(q){l(B,q._cfg.storesSource),V=q._cfg.dbschema={},q._parseStoresSpec(B,V)}),T._dbSchema=V,Bv(T,[T._allTables,T,T.Transaction.prototype]),ym(T,[T._allTables,T,T.Transaction.prototype,this._cfg.tables],a(V),V),T._storeNames=a(V),this},ru.prototype.upgrade=function(_){return this._cfg.contentUpgrade=Un(this._cfg.contentUpgrade||Me,_),this};var r$=ru;function ru(){}var Ch=(()=>{var _,T,N;return typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"?(_=new Set,T=new FinalizationRegistry(function(B){_.delete(B)}),{toArray:function(){return Array.from(_).map(function(B){return B.deref()}).filter(function(B){return B!==void 0})},add:function(B){var V=new WeakRef(B._novip);_.add(V),T.register(B._novip,V,V),_.size>B._options.maxConnections&&(V=_.values().next().value,_.delete(V),T.unregister(V))},remove:function(B){if(B)for(var V=_.values(),q=V.next();!q.done;){var J=q.value;if(J.deref()===B._novip)return _.delete(J),void T.unregister(J);q=V.next()}}}):(N=[],{toArray:function(){return N},add:function(B){N.push(B._novip)},remove:function(B){B&&(B=N.indexOf(B._novip))!==-1&&N.splice(B,1)}})})();function Fv(_,T){var N=_._dbNamesDB;return N||(N=_._dbNamesDB=new Ca(Pe,{addons:[],indexedDB:_,IDBKeyRange:T})).version(1).stores({dbnames:"name"}),N.table("dbnames")}function $v(_){return _&&typeof _.databases=="function"}function Vv(_){return w(function(){return nt.letThrough=!0,_()})}function Gv(_){return!("from"in _)}var Fr=function(_,T){var N;if(!this)return N=new Fr,_&&"d"in _&&l(N,_),N;l(this,arguments.length?{d:1,from:_,to:1<arguments.length?T:_}:{d:0})};function Lh(_,T,N){var B=Ke(T,N);if(!isNaN(B)){if(0<B)throw RangeError();if(Gv(_))return l(_,{from:T,to:N,d:1});var B=_.l,V=_.r;if(Ke(N,_.from)<0)return B?Lh(B,T,N):_.l={from:T,to:N,d:1,l:null,r:null},d1(_);if(0<Ke(T,_.to))return V?Lh(V,T,N):_.r={from:T,to:N,d:1,l:null,r:null},d1(_);Ke(T,_.from)<0&&(_.from=T,_.l=null,_.d=V?V.d+1:1),0<Ke(N,_.to)&&(_.to=N,_.r=null,_.d=_.l?_.l.d+1:1),T=!_.r,B&&!_.l&&kh(_,B),V&&T&&kh(_,V)}}function kh(_,T){Gv(T)||function N(B,V){var q=V.from,J=V.l,te=V.r;Lh(B,q,V.to),J&&N(B,J),te&&N(B,te)}(_,T)}function u1(_,T){var N=xm(T),B=N.next();if(!B.done)for(var V=B.value,q=xm(_),J=q.next(V.from),te=J.value;!B.done&&!J.done;){if(Ke(te.from,V.to)<=0&&0<=Ke(te.to,V.from))return!0;Ke(V.from,te.from)<0?V=(B=N.next(te.from)).value:te=(J=q.next(V.from)).value}return!1}function xm(_){var T=Gv(_)?null:{s:0,n:_};return{next:function(N){for(var B=0<arguments.length;T;)switch(T.s){case 0:if(T.s=1,B)for(;T.n.l&&Ke(N,T.n.from)<0;)T={up:T,n:T.n.l,s:1};else for(;T.n.l;)T={up:T,n:T.n.l,s:1};case 1:if(T.s=2,!B||Ke(N,T.n.to)<=0)return{value:T.n,done:!1};case 2:if(T.n.r){T.s=3,T={up:T,n:T.n.r,s:0};continue}case 3:T=T.up}return{done:!0}}}}function d1(_){var T,N,B,V=(((V=_.r)==null?void 0:V.d)||0)-(((V=_.l)==null?void 0:V.d)||0),V=1<V?"r":V<-1?"l":"";V&&(T=V=="r"?"l":"r",N=r({},_),B=_[V],_.from=B.from,_.to=B.to,_[V]=B[V],N[V]=B[T],(_[T]=N).d=h1(N)),_.d=h1(_)}function h1(N){var T=N.r,N=N.l;return(T?N?Math.max(T.d,N.d):T.d:N?N.d:0)+1}function Sm(_,T){return a(T).forEach(function(N){_[N]?kh(_[N],T[N]):_[N]=function B(V){var q,J,te={};for(q in V)d(V,q)&&(J=V[q],te[q]=!J||typeof J!="object"||M.has(J.constructor)?J:B(J));return te}(T[N])}),_}function Hv(_,T){return _.all||T.all||Object.keys(_).some(function(N){return T[N]&&u1(T[N],_[N])})}h(Fr.prototype,((Xt={add:function(_){return kh(this,_),this},addKey:function(_){return Lh(this,_,_),this},addKeys:function(_){var T=this;return _.forEach(function(N){return Lh(T,N,N)}),this},hasKey:function(_){var T=xm(this).next(_).value;return T&&Ke(T.from,_)<=0&&0<=Ke(T.to,_)}})[X]=function(){return xm(this)},Xt));var Ul={},Kv={},zv=!1;function Em(_){Sm(Kv,_),zv||(zv=!0,setTimeout(function(){zv=!1,qv(Kv,!(Kv={}))},0))}function qv(_,T){T===void 0&&(T=!1);var N=new Set;if(_.all)for(var B=0,V=Object.values(Ul);B<V.length;B++)f1(te=V[B],_,N,T);else for(var q in _){var J,te,q=/^idb\:\/\/(.*)\/(.*)\//.exec(q);q&&(J=q[1],q=q[2],te=Ul["idb://".concat(J,"/").concat(q)])&&f1(te,_,N,T)}N.forEach(function(he){return he()})}function f1(_,T,N,B){for(var V=[],q=0,J=Object.entries(_.queries.query);q<J.length;q++){for(var te=J[q],he=te[0],Se=[],pe=0,de=te[1];pe<de.length;pe++){var fe=de[pe];Hv(T,fe.obsSet)?fe.subscribers.forEach(function(ve){return N.add(ve)}):B&&Se.push(fe)}B&&V.push([he,Se])}if(B)for(var _e=0,me=V;_e<me.length;_e++){var ge=me[_e],he=ge[0],Se=ge[1];_.queries.query[he]=Se}}function i$(_){var T=_._state,N=_._deps.indexedDB;if(T.isBeingOpened||_.idbdb)return T.dbReadyPromise.then(function(){return T.dbOpenError?ae(T.dbOpenError):_});T.isBeingOpened=!0,T.dbOpenError=null,T.openComplete=!1;var B=T.openCanceller,V=Math.round(10*_.verno),q=!1;function J(){if(T.openCanceller!==B)throw new Ee.DatabaseClosed("db.open() was cancelled")}function te(){return new Qe(function(fe,_e){if(J(),!N)throw new Ee.MissingAPI;var me=_.name,ge=T.autoSchema||!V?N.open(me):N.open(me,V);if(!ge)throw new Ee.MissingAPI;ge.onerror=Qr(_e),ge.onblocked=At(_._fireOnBlocked),ge.onupgradeneeded=At(function(ve){var Re;pe=ge.transaction,T.autoSchema&&!_._options.allowEmptyDB?(ge.onerror=Fs,pe.abort(),ge.result.close(),(Re=N.deleteDatabase(me)).onsuccess=Re.onerror=At(function(){_e(new Ee.NoSuchDatabase("Database ".concat(me," doesnt exist")))})):(pe.onerror=Qr(_e),Re=ve.oldVersion>Math.pow(2,62)?0:ve.oldVersion,de=Re<1,_.idbdb=ge.result,q&&n$(_,pe),t$(_,Re/10,pe,_e))},_e),ge.onsuccess=At(function(){pe=null;var ve,Re,we,De,$e,He,We=_.idbdb=ge.result,ze=v(We.objectStoreNames);if(0<ze.length)try{var rt=We.transaction(($e=ze).length===1?$e[0]:$e,"readonly");if(T.autoSchema)He=We,De=rt,(we=_).verno=He.version/10,De=we._dbSchema=_m(0,He,De),we._storeNames=v(He.objectStoreNames,0),ym(we,[we._allTables],a(De),De);else if(bm(_,_._dbSchema,rt),Re=rt,((Re=Uv(_m(0,(ve=_).idbdb,Re),ve._dbSchema)).add.length||Re.change.some(function(qe){return qe.add.length||qe.change.length}))&&!q)return console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Dexie will add missing parts and increment native version number to workaround this."),We.close(),V=We.version+1,q=!0,fe(te());gm(_,rt)}catch{}Ch.add(_),We.onversionchange=At(function(qe){T.vcFired=!0,_.on("versionchange").fire(qe)}),We.onclose=At(function(){_.close({disableAutoOpen:!1})}),de&&(ze=_._deps,$e=me,$v(He=ze.indexedDB)||$e===Pe||Fv(He,ze.IDBKeyRange).put({name:$e}).catch(Me)),fe()},_e)}).catch(function(fe){switch(fe==null?void 0:fe.name){case"UnknownError":if(0<T.PR1398_maxLoop)return T.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),te();break;case"VersionError":if(0<V)return V=0,te()}return Qe.reject(fe)})}var he,Se=T.dbReadyResolve,pe=null,de=!1;return Qe.race([B,(typeof navigator>"u"?Qe.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(fe){function _e(){return indexedDB.databases().finally(fe)}he=setInterval(_e,100),_e()}).finally(function(){return clearInterval(he)}):Promise.resolve()).then(te)]).then(function(){return J(),T.onReadyBeingFired=[],Qe.resolve(Vv(function(){return _.on.ready.fire(_.vip)})).then(function fe(){var _e;if(0<T.onReadyBeingFired.length)return _e=T.onReadyBeingFired.reduce(Un,Me),T.onReadyBeingFired=[],Qe.resolve(Vv(function(){return _e(_.vip)})).then(fe)})}).finally(function(){T.openCanceller===B&&(T.onReadyBeingFired=null,T.isBeingOpened=!1)}).catch(function(fe){T.dbOpenError=fe;try{pe&&pe.abort()}catch{}return B===T.openCanceller&&_._close(),ae(fe)}).finally(function(){T.openComplete=!0,Se()}).then(function(){var fe;return de&&(fe={},_.tables.forEach(function(_e){_e.schema.indexes.forEach(function(me){me.name&&(fe["idb://".concat(_.name,"/").concat(_e.name,"/").concat(me.name)]=new Fr(-1/0,[[[]]]))}),fe["idb://".concat(_.name,"/").concat(_e.name,"/")]=fe["idb://".concat(_.name,"/").concat(_e.name,"/:dels")]=new Fr(-1/0,[[[]]])}),ts(xo).fire(fe),qv(fe,!0)),_})}function Wv(_){function T(q){return _.next(q)}var N=V(T),B=V(function(q){return _.throw(q)});function V(q){return function(te){var te=q(te),he=te.value;return te.done?he:he&&typeof he.then=="function"?he.then(N,B):o(he)?Promise.all(he).then(N,B):N(he)}}return V(T)()}function wm(_,T,N){for(var B=o(_)?_.slice():[_],V=0;V<N;++V)B.push(T);return B}var s$={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(_){return r(r({},_),{table:function(B){var N=_.table(B),B=N.schema,V={},q=[];function J(fe,_e,me){var we=Rh(fe),ge=V[we]=V[we]||[],ve=fe==null?0:typeof fe=="string"?1:fe.length,Re=0<_e,we=r(r({},me),{name:Re?"".concat(we,"(virtual-from:").concat(me.name,")"):me.name,lowLevelIndex:me,isVirtual:Re,keyTail:_e,keyLength:ve,extractKey:Mv(fe),unique:!Re&&me.unique});return ge.push(we),we.isPrimaryKey||q.push(we),1<ve&&J(ve===2?fe[0]:fe.slice(0,ve-1),_e+1,me),ge.sort(function(De,$e){return De.keyTail-$e.keyTail}),we}var te=J(B.primaryKey.keyPath,0,B.primaryKey);V[":id"]=[te];for(var he=0,Se=B.indexes;he<Se.length;he++){var pe=Se[he];J(pe.keyPath,0,pe)}function de(fe){var _e,me=fe.query.index;return me.isVirtual?r(r({},fe),{query:{index:me.lowLevelIndex,range:(_e=fe.query.range,me=me.keyTail,{type:_e.type===1?2:_e.type,lower:wm(_e.lower,_e.lowerOpen?_.MAX_KEY:_.MIN_KEY,me),lowerOpen:!0,upper:wm(_e.upper,_e.upperOpen?_.MIN_KEY:_.MAX_KEY,me),upperOpen:!0})}}):fe}return r(r({},N),{schema:r(r({},B),{primaryKey:te,indexes:q,getIndexByKeyPath:function(fe){return(fe=V[Rh(fe)])&&fe[0]}}),count:function(fe){return N.count(de(fe))},query:function(fe){return N.query(de(fe))},openCursor:function(fe){var _e=fe.query.index,me=_e.keyTail,ge=_e.keyLength;return _e.isVirtual?N.openCursor(de(fe)).then(function(Re){return Re&&ve(Re)}):N.openCursor(fe);function ve(Re){return Object.create(Re,{continue:{value:function(we){we!=null?Re.continue(wm(we,fe.reverse?_.MAX_KEY:_.MIN_KEY,me)):fe.unique?Re.continue(Re.key.slice(0,ge).concat(fe.reverse?_.MIN_KEY:_.MAX_KEY,me)):Re.continue()}},continuePrimaryKey:{value:function(we,De){Re.continuePrimaryKey(wm(we,_.MAX_KEY,me),De)}},primaryKey:{get:function(){return Re.primaryKey}},key:{get:function(){var we=Re.key;return ge===1?we[0]:we.slice(0,ge)}},value:{get:function(){return Re.value}}})}}})}})}};function Yv(_,T,N,B){return N=N||{},B=B||"",a(_).forEach(function(V){var q,J,te;d(T,V)?(q=_[V],J=T[V],typeof q=="object"&&typeof J=="object"&&q&&J?(te=re(q))!==re(J)?N[B+V]=T[V]:te==="Object"?Yv(q,J,N,B+V+"."):q!==J&&(N[B+V]=T[V]):q!==J&&(N[B+V]=T[V])):N[B+V]=void 0}),a(T).forEach(function(V){d(_,V)||(N[B+V]=T[V])}),N}function Xv(_,T){return T.type==="delete"?T.keys:T.keys||T.values.map(_.extractKey)}var a$={stack:"dbcore",name:"HooksMiddleware",level:2,create:function(_){return r(r({},_),{table:function(T){var N=_.table(T),B=N.schema.primaryKey;return r(r({},N),{mutate:function(V){var q=nt.trans,J=q.table(T).hook,te=J.deleting,he=J.creating,Se=J.updating;switch(V.type){case"add":if(he.fire===Me)break;return q._promise("readwrite",function(){return pe(V)},!0);case"put":if(he.fire===Me&&Se.fire===Me)break;return q._promise("readwrite",function(){return pe(V)},!0);case"delete":if(te.fire===Me)break;return q._promise("readwrite",function(){return pe(V)},!0);case"deleteRange":if(te.fire===Me)break;return q._promise("readwrite",function(){return function de(fe,_e,me){return N.query({trans:fe,values:!1,query:{index:B,range:_e},limit:me}).then(function(ge){var ve=ge.result;return pe({type:"delete",keys:ve,trans:fe}).then(function(Re){return 0<Re.numFailures?Promise.reject(Re.failures[0]):ve.length<me?{failures:[],numFailures:0,lastResult:void 0}:de(fe,r(r({},_e),{lower:ve[ve.length-1],lowerOpen:!0}),me)})})}(V.trans,V.range,1e4)},!0)}return N.mutate(V);function pe(de){var fe,_e,me,ge=nt.trans,ve=de.keys||Xv(B,de);if(ve)return(de=de.type==="add"||de.type==="put"?r(r({},de),{keys:ve}):r({},de)).type!=="delete"&&(de.values=i([],de.values)),de.keys&&(de.keys=i([],de.keys)),fe=N,me=ve,((_e=de).type==="add"?Promise.resolve([]):fe.getMany({trans:_e.trans,keys:me,cache:"immutable"})).then(function(Re){var we=ve.map(function(De,$e){var He,We,ze,rt=Re[$e],qe={onerror:null,onsuccess:null};return de.type==="delete"?te.fire.call(qe,De,rt,ge):de.type==="add"||rt===void 0?(He=he.fire.call(qe,De,de.values[$e],ge),De==null&&He!=null&&(de.keys[$e]=De=He,B.outbound||O(de.values[$e],B.keyPath,De))):(He=Yv(rt,de.values[$e]),(We=Se.fire.call(qe,He,De,rt,ge))&&(ze=de.values[$e],Object.keys(We).forEach(function(st){d(ze,st)?ze[st]=We[st]:O(ze,st,We[st])}))),qe});return N.mutate(de).then(function(De){for(var $e=De.failures,He=De.results,We=De.numFailures,De=De.lastResult,ze=0;ze<ve.length;++ze){var rt=(He||ve)[ze],qe=we[ze];rt==null?qe.onerror&&qe.onerror($e[ze]):qe.onsuccess&&qe.onsuccess(de.type==="put"&&Re[ze]?de.values[ze]:rt)}return{failures:$e,results:He,numFailures:We,lastResult:De}}).catch(function(De){return we.forEach(function($e){return $e.onerror&&$e.onerror(De)}),Promise.reject(De)})});throw new Error("Keys missing")}}})}})}};function p1(_,T,N){try{if(!T||T.keys.length<_.length)return null;for(var B=[],V=0,q=0;V<T.keys.length&&q<_.length;++V)Ke(T.keys[V],_[q])===0&&(B.push(N?Z(T.values[V]):T.values[V]),++q);return B.length===_.length?B:null}catch{return null}}var o$={stack:"dbcore",level:-1,create:function(_){return{table:function(T){var N=_.table(T);return r(r({},N),{getMany:function(B){var V;return B.cache?(V=p1(B.keys,B.trans._cache,B.cache==="clone"))?Qe.resolve(V):N.getMany(B).then(function(q){return B.trans._cache={keys:B.keys,values:B.cache==="clone"?Z(q):q},q}):N.getMany(B)},mutate:function(B){return B.type!=="add"&&(B.trans._cache=null),N.mutate(B)}})}}}};function m1(_,T){return _.trans.mode==="readonly"&&!!_.subscr&&!_.trans.explicit&&_.trans.db._options.cache!=="disabled"&&!T.schema.primaryKey.outbound}function g1(_,T){switch(_){case"query":return T.values&&!T.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var l$={stack:"dbcore",level:0,name:"Observability",create:function(_){var T=_.schema.name,N=new Fr(_.MIN_KEY,_.MAX_KEY);return r(r({},_),{transaction:function(B,V,q){if(nt.subscr&&V!=="readonly")throw new Ee.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(nt.querier));return _.transaction(B,V,q)},table:function(B){function V(ve){var ge,ve=ve.query;return[ge=ve.index,new Fr((ge=(ve=ve.range).lower)!=null?ge:_.MIN_KEY,(ge=ve.upper)!=null?ge:_.MAX_KEY)]}var q=_.table(B),J=q.schema,te=J.primaryKey,he=J.indexes,Se=te.extractKey,pe=te.outbound,de=te.autoIncrement&&he.filter(function(me){return me.compound&&me.keyPath.includes(te.keyPath)}),fe=r(r({},q),{mutate:function(me){function ge(Ve){return Ve="idb://".concat(T,"/").concat(B,"/").concat(Ve),$e[Ve]||($e[Ve]=new Fr)}var ve,Re,we,De=me.trans,$e=me.mutatedParts||(me.mutatedParts={}),He=ge(""),We=ge(":dels"),ze=me.type,qe=me.type==="deleteRange"?[me.range]:me.type==="delete"?[me.keys]:me.values.length<50?[Xv(te,me).filter(function(Ve){return Ve}),me.values]:[],rt=qe[0],qe=qe[1],st=me.trans._cache;return o(rt)?(He.addKeys(rt),(ze=ze==="delete"||rt.length===qe.length?p1(rt,st):null)||We.addKeys(rt),(ze||qe)&&(ve=ge,Re=ze,we=qe,J.indexes.forEach(function(Ve){var St=ve(Ve.name||"");function Et(qt){return qt!=null?Ve.extractKey(qt):null}function It(qt){Ve.multiEntry&&o(qt)?qt.forEach(function(wi){return St.addKey(wi)}):St.addKey(qt)}(Re||we).forEach(function(qt,$r){var Lt=Re&&Et(Re[$r]),$r=we&&Et(we[$r]);Ke(Lt,$r)!==0&&(Lt!=null&&It(Lt),$r!=null)&&It($r)})}))):rt?(qe={from:(st=rt.lower)!=null?st:_.MIN_KEY,to:(ze=rt.upper)!=null?ze:_.MAX_KEY},We.add(qe),He.add(qe)):(He.add(N),We.add(N),J.indexes.forEach(function(Ve){return ge(Ve.name).add(N)})),q.mutate(me).then(function(Ve){return!rt||me.type!=="add"&&me.type!=="put"||(He.addKeys(Ve.results),de&&de.forEach(function(St){for(var Et=me.values.map(function(Lt){return St.extractKey(Lt)}),It=St.keyPath.findIndex(function(Lt){return Lt===te.keyPath}),qt=0,wi=Ve.results.length;qt<wi;++qt)Et[qt][It]=Ve.results[qt];ge(St.name).addKeys(Et)})),De.mutatedParts=Sm(De.mutatedParts||{},$e),Ve})}}),_e={get:function(me){return[te,new Fr(me.key)]},getMany:function(me){return[te,new Fr().addKeys(me.keys)]},count:V,query:V,openCursor:V};return a(_e).forEach(function(me){fe[me]=function(ge){var ve=nt.subscr,Re=!!ve,we=m1(nt,q)&&g1(me,ge)?ge.obsSet={}:ve;if(Re){var De,ve=function(qe){return qe="idb://".concat(T,"/").concat(B,"/").concat(qe),we[qe]||(we[qe]=new Fr)},$e=ve(""),He=ve(":dels"),Re=_e[me](ge),We=Re[0],Re=Re[1];if((me==="query"&&We.isPrimaryKey&&!ge.values?He:ve(We.name||"")).add(Re),!We.isPrimaryKey){if(me!=="count")return De=me==="query"&&pe&&ge.values&&q.query(r(r({},ge),{values:!1})),q[me].apply(this,arguments).then(function(qe){if(me==="query"){if(pe&&ge.values)return De.then(function(Et){return Et=Et.result,$e.addKeys(Et),qe});var st=ge.values?qe.result.map(Se):qe.result;(ge.values?$e:He).addKeys(st)}else{var Ve,St;if(me==="openCursor")return St=ge.values,(Ve=qe)&&Object.create(Ve,{key:{get:function(){return He.addKey(Ve.primaryKey),Ve.key}},primaryKey:{get:function(){var Et=Ve.primaryKey;return He.addKey(Et),Et}},value:{get:function(){return St&&$e.addKey(Ve.primaryKey),Ve.value}}})}return qe});He.add(N)}}return q[me].apply(this,arguments)}}),fe}})}};function y1(_,T,N){var B;return N.numFailures===0?T:T.type==="deleteRange"||(B=T.keys?T.keys.length:"values"in T&&T.values?T.values.length:1,N.numFailures===B)?null:(B=r({},T),o(B.keys)&&(B.keys=B.keys.filter(function(V,q){return!(q in N.failures)})),"values"in B&&o(B.values)&&(B.values=B.values.filter(function(V,q){return!(q in N.failures)})),B)}function Qv(_,T){return N=_,((B=T).lower===void 0||(B.lowerOpen?0<Ke(N,B.lower):0<=Ke(N,B.lower)))&&(N=_,(B=T).upper===void 0||(B.upperOpen?Ke(N,B.upper)<0:Ke(N,B.upper)<=0));var N,B}function v1(_,T,N,B,V,q){var J,te,he,Se,pe,de,fe;return!N||N.length===0||(J=T.query.index,te=J.multiEntry,he=T.query.range,Se=B.schema.primaryKey.extractKey,pe=J.extractKey,de=(J.lowLevelIndex||J).extractKey,(B=N.reduce(function(_e,me){var ge=_e,ve=[];if(me.type==="add"||me.type==="put")for(var Re=new Fr,we=me.values.length-1;0<=we;--we){var De,$e=me.values[we],He=Se($e);!Re.hasKey(He)&&(De=pe($e),te&&o(De)?De.some(function(st){return Qv(st,he)}):Qv(De,he))&&(Re.addKey(He),ve.push($e))}switch(me.type){case"add":var We=new Fr().addKeys(T.values?_e.map(function(Ve){return Se(Ve)}):_e),ge=_e.concat(T.values?ve.filter(function(Ve){return Ve=Se(Ve),!We.hasKey(Ve)&&(We.addKey(Ve),!0)}):ve.map(function(Ve){return Se(Ve)}).filter(function(Ve){return!We.hasKey(Ve)&&(We.addKey(Ve),!0)}));break;case"put":var ze=new Fr().addKeys(me.values.map(function(Ve){return Se(Ve)}));ge=_e.filter(function(Ve){return!ze.hasKey(T.values?Se(Ve):Ve)}).concat(T.values?ve:ve.map(function(Ve){return Se(Ve)}));break;case"delete":var rt=new Fr().addKeys(me.keys);ge=_e.filter(function(Ve){return!rt.hasKey(T.values?Se(Ve):Ve)});break;case"deleteRange":var qe=me.range;ge=_e.filter(function(Ve){return!Qv(Se(Ve),qe)})}return ge},_))===_)?_:(fe=function(_e,me){return Ke(de(_e),de(me))||Ke(Se(_e),Se(me))},B.sort(T.direction==="prev"||T.direction==="prevunique"?function(_e,me){return fe(me,_e)}:fe),T.limit&&T.limit<1/0&&(B.length>T.limit?B.length=T.limit:_.length===T.limit&&B.length<T.limit&&(V.dirty=!0)),q?Object.freeze(B):B)}function _1(_,T){return Ke(_.lower,T.lower)===0&&Ke(_.upper,T.upper)===0&&!!_.lowerOpen==!!T.lowerOpen&&!!_.upperOpen==!!T.upperOpen}function c$(_,T){return((N,B,V,q)=>{if(N===void 0)return B!==void 0?-1:0;if(B===void 0)return 1;if((N=Ke(N,B))===0){if(V&&q)return 0;if(V)return 1;if(q)return-1}return N})(_.lower,T.lower,_.lowerOpen,T.lowerOpen)<=0&&0<=((N,B,V,q)=>{if(N===void 0)return B!==void 0?1:0;if(B===void 0)return-1;if((N=Ke(N,B))===0){if(V&&q)return 0;if(V)return-1;if(q)return 1}return N})(_.upper,T.upper,_.upperOpen,T.upperOpen)}function u$(_,T,N,B){_.subscribers.add(N),B.addEventListener("abort",function(){var V,q;_.subscribers.delete(N),_.subscribers.size===0&&(V=_,q=T,setTimeout(function(){V.subscribers.size===0&&Q(q,V)},3e3))})}var d$={stack:"dbcore",level:0,name:"Cache",create:function(_){var T=_.schema.name;return r(r({},_),{transaction:function(N,B,V){var q,J,te=_.transaction(N,B,V);return B==="readwrite"&&(V=(q=new AbortController).signal,te.addEventListener("abort",(J=function(he){return function(){if(q.abort(),B==="readwrite"){for(var Se=new Set,pe=0,de=N;pe<de.length;pe++){var fe=de[pe],_e=Ul["idb://".concat(T,"/").concat(fe)];if(_e){var me=_.table(fe),ge=_e.optimisticOps.filter(function(Ve){return Ve.trans===te});if(te._explicit&&he&&te.mutatedParts)for(var ve=0,Re=Object.values(_e.queries.query);ve<Re.length;ve++)for(var we=0,De=(We=Re[ve]).slice();we<De.length;we++)Hv((ze=De[we]).obsSet,te.mutatedParts)&&(Q(We,ze),ze.subscribers.forEach(function(Ve){return Se.add(Ve)}));else if(0<ge.length){_e.optimisticOps=_e.optimisticOps.filter(function(Ve){return Ve.trans!==te});for(var $e=0,He=Object.values(_e.queries.query);$e<He.length;$e++)for(var We,ze,rt,qe=0,st=(We=He[$e]).slice();qe<st.length;qe++)(ze=st[qe]).res!=null&&te.mutatedParts&&(he&&!ze.dirty?(rt=Object.isFrozen(ze.res),rt=v1(ze.res,ze.req,ge,me,ze,rt),ze.dirty?(Q(We,ze),ze.subscribers.forEach(function(Ve){return Se.add(Ve)})):rt!==ze.res&&(ze.res=rt,ze.promise=Qe.resolve({result:rt}))):(ze.dirty&&Q(We,ze),ze.subscribers.forEach(function(Ve){return Se.add(Ve)})))}}}Se.forEach(function(Ve){return Ve()})}}})(!1),{signal:V}),te.addEventListener("error",J(!1),{signal:V}),te.addEventListener("complete",J(!0),{signal:V})),te},table:function(N){var B=_.table(N),V=B.schema.primaryKey;return r(r({},B),{mutate:function(q){var J,te=nt.trans;return!V.outbound&&te.db._options.cache!=="disabled"&&!te.explicit&&te.idbtrans.mode==="readwrite"&&(J=Ul["idb://".concat(T,"/").concat(N)])?(te=B.mutate(q),q.type!=="add"&&q.type!=="put"||!(50<=q.values.length||Xv(V,q).some(function(he){return he==null}))?(J.optimisticOps.push(q),q.mutatedParts&&Em(q.mutatedParts),te.then(function(he){0<he.numFailures&&(Q(J.optimisticOps,q),(he=y1(0,q,he))&&J.optimisticOps.push(he),q.mutatedParts)&&Em(q.mutatedParts)}),te.catch(function(){Q(J.optimisticOps,q),q.mutatedParts&&Em(q.mutatedParts)})):te.then(function(he){var Se=y1(0,r(r({},q),{values:q.values.map(function(pe,de){var fe;return he.failures[de]?pe:(O(fe=(fe=V.keyPath)!=null&&fe.includes(".")?Z(pe):r({},pe),V.keyPath,he.results[de]),fe)})}),he);J.optimisticOps.push(Se),queueMicrotask(function(){return q.mutatedParts&&Em(q.mutatedParts)})}),te):B.mutate(q)},query:function(q){var J,te,he,Se,pe,de,fe;return m1(nt,B)&&g1("query",q)?(J=((he=nt.trans)==null?void 0:he.db._options.cache)==="immutable",te=(he=nt).requery,he=he.signal,de=((_e,me,ge,ve)=>{var Re=Ul["idb://".concat(_e,"/").concat(me)];if(!Re)return[];if(!(_e=Re.queries[ge]))return[null,!1,Re,null];var we=_e[(ve.query?ve.query.index.name:null)||""];if(!we)return[null,!1,Re,null];switch(ge){case"query":var De=($e=ve.direction)!=null?$e:"next",$e=we.find(function(He){var We;return He.req.limit===ve.limit&&He.req.values===ve.values&&((We=He.req.direction)!=null?We:"next")===De&&_1(He.req.query.range,ve.query.range)});return $e?[$e,!0,Re,we]:[we.find(function(He){var We;return("limit"in He.req?He.req.limit:1/0)>=ve.limit&&((We=He.req.direction)!=null?We:"next")===De&&(!ve.values||He.req.values)&&c$(He.req.query.range,ve.query.range)}),!1,Re,we];case"count":return $e=we.find(function(He){return _1(He.req.query.range,ve.query.range)}),[$e,!!$e,Re,we]}})(T,N,"query",q),fe=de[0],Se=de[2],pe=de[3],fe&&de[1]?fe.obsSet=q.obsSet:(de=B.query(q).then(function(_e){var me=_e.result;if(fe&&(fe.res=me),J){for(var ge=0,ve=me.length;ge<ve;++ge)Object.freeze(me[ge]);Object.freeze(me)}else _e.result=Z(me);return _e}).catch(function(_e){return pe&&fe&&Q(pe,fe),Promise.reject(_e)}),fe={obsSet:q.obsSet,promise:de,subscribers:new Set,type:"query",req:q,dirty:!1},pe?pe.push(fe):(pe=[fe],(Se=Se||(Ul["idb://".concat(T,"/").concat(N)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[q.query.index.name||""]=pe)),u$(fe,pe,te,he),fe.promise.then(function(_e){return{result:v1(_e.result,q,Se==null?void 0:Se.optimisticOps,B,fe,J)}})):B.query(q)}})}})}};function Tm(_,T){return new Proxy(_,{get:function(N,B,V){return B==="db"?T:Reflect.get(N,B,V)}})}Xn.prototype.version=function(_){if(isNaN(_)||_<.1)throw new Ee.Type("Given version is not a positive number");if(_=Math.round(10*_)/10,this.idbdb||this._state.isBeingOpened)throw new Ee.Schema("Cannot add version when database is open");this.verno=Math.max(this.verno,_);var T=this._versions,N=T.filter(function(B){return B._cfg.version===_})[0];return N||(N=new this.Version(_),T.push(N),T.sort(e$),N.stores({}),this._state.autoSchema=!1),N},Xn.prototype._whenReady=function(_){var T=this;return this.idbdb&&(this._state.openComplete||nt.letThrough||this._vip)?_():new Qe(function(N,B){if(T._state.openComplete)return B(new Ee.DatabaseClosed(T._state.dbOpenError));if(!T._state.isBeingOpened){if(!T._state.autoOpen)return void B(new Ee.DatabaseClosed);T.open().catch(Me)}T._state.dbReadyPromise.then(N,B)}).then(_)},Xn.prototype.use=function(V){var T=V.stack,N=V.create,B=V.level,V=V.name,q=(V&&this.unuse({stack:T,name:V}),this._middlewares[T]||(this._middlewares[T]=[]));return q.push({stack:T,create:N,level:B??10,name:V}),q.sort(function(J,te){return J.level-te.level}),this},Xn.prototype.unuse=function(_){var T=_.stack,N=_.name,B=_.create;return T&&this._middlewares[T]&&(this._middlewares[T]=this._middlewares[T].filter(function(V){return B?V.create!==B:!!N&&V.name!==N})),this},Xn.prototype.open=function(){var _=this;return ee(ci,function(){return i$(_)})},Xn.prototype._close=function(){this.on.close.fire(new CustomEvent("close"));var _=this._state;if(Ch.remove(this),this.idbdb){try{this.idbdb.close()}catch{}this.idbdb=null}_.isBeingOpened||(_.dbReadyPromise=new Qe(function(T){_.dbReadyResolve=T}),_.openCanceller=new Qe(function(T,N){_.cancelOpen=N}))},Xn.prototype.close=function(T){var T=(T===void 0?{disableAutoOpen:!0}:T).disableAutoOpen,N=this._state;T?(N.isBeingOpened&&N.cancelOpen(new Ee.DatabaseClosed),this._close(),N.autoOpen=!1,N.dbOpenError=new Ee.DatabaseClosed):(this._close(),N.autoOpen=this._options.autoOpen||N.isBeingOpened,N.openComplete=!1,N.dbOpenError=null)},Xn.prototype.delete=function(_){var T=this,N=(_===void 0&&(_={disableAutoOpen:!0}),0<arguments.length&&typeof arguments[0]!="object"),B=this._state;return new Qe(function(V,q){function J(){T.close(_);var te=T._deps.indexedDB.deleteDatabase(T.name);te.onsuccess=At(function(){var he,Se,pe;he=T._deps,Se=T.name,$v(pe=he.indexedDB)||Se===Pe||Fv(pe,he.IDBKeyRange).delete(Se).catch(Me),V()}),te.onerror=Qr(q),te.onblocked=T._fireOnBlocked}if(N)throw new Ee.InvalidArgument("Invalid closeOptions argument to db.delete()");B.isBeingOpened?B.dbReadyPromise.then(J):J()})},Xn.prototype.backendDB=function(){return this.idbdb},Xn.prototype.isOpen=function(){return this.idbdb!==null},Xn.prototype.hasBeenClosed=function(){var _=this._state.dbOpenError;return _&&_.name==="DatabaseClosed"},Xn.prototype.hasFailed=function(){return this._state.dbOpenError!==null},Xn.prototype.dynamicallyOpened=function(){return this._state.autoSchema},Object.defineProperty(Xn.prototype,"tables",{get:function(){var _=this;return a(this._allTables).map(function(T){return _._allTables[T]})},enumerable:!1,configurable:!0}),Xn.prototype.transaction=function(){var _=(function(T,N,B){var V=arguments.length;if(V<2)throw new Ee.InvalidArgument("Too few arguments");for(var q=new Array(V-1);--V;)q[V-1]=arguments[V];return B=q.pop(),[T,R(q),B]}).apply(this,arguments);return this._transaction.apply(this,_)},Xn.prototype._transaction=function(_,T,N){var B,V,q=this,J=nt.trans,te=(J&&J.db===this&&_.indexOf("!")===-1||(J=null),_.indexOf("?")!==-1);_=_.replace("!","").replace("?","");try{if(V=T.map(function(Se){if(Se=Se instanceof q.Table?Se.name:Se,typeof Se!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return Se}),_=="r"||_===Je)B=Je;else{if(_!="rw"&&_!=Ye)throw new Ee.InvalidArgument("Invalid transaction mode: "+_);B=Ye}if(J){if(J.mode===Je&&B===Ye){if(!te)throw new Ee.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");J=null}J&&V.forEach(function(Se){if(J&&J.storeNames.indexOf(Se)===-1){if(!te)throw new Ee.SubTransaction("Table "+Se+" not included in parent transaction.");J=null}}),te&&J&&!J.active&&(J=null)}}catch(Se){return J?J._promise(null,function(pe,de){de(Se)}):ae(Se)}var he=(function Se(pe,de,fe,_e,me){return Qe.resolve().then(function(){var we=nt.transless||nt,ge=pe._createTransaction(de,fe,pe._dbSchema,_e),we=(ge.explicit=!0,{trans:ge,transless:we});if(_e)ge.idbtrans=_e.idbtrans;else try{ge.create(),ge.idbtrans._explicit=!0,pe._state.PR1398_maxLoop=3}catch(De){return De.name===Ie.InvalidState&&pe.isOpen()&&0<--pe._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),pe.close({disableAutoOpen:!1}),pe.open().then(function(){return Se(pe,de,fe,null,me)})):ae(De)}var ve,Re=Y(me),we=(Re&&x(),Qe.follow(function(){var De;(ve=me.call(ge,ge))&&(Re?(De=P.bind(null,null),ve.then(De,De)):typeof ve.next=="function"&&typeof ve.throw=="function"&&(ve=Wv(ve)))},we));return(ve&&typeof ve.then=="function"?Qe.resolve(ve).then(function(De){return ge.active?De:ae(new Ee.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):we.then(function(){return ve})).then(function(De){return _e&&ge._resolve(),ge._completion.then(function(){return De})}).catch(function(De){return ge._reject(De),ae(De)})})}).bind(null,this,B,V,J,N);return J?J._promise(B,he,"lock"):nt.trans?ee(nt.transless,function(){return q._whenReady(he)}):this._whenReady(he)},Xn.prototype.table=function(_){if(d(this._allTables,_))return this._allTables[_];throw new Ee.InvalidTable("Table ".concat(_," does not exist"))};var Ca=Xn;function Xn(_,T){var N,B,V,q,J,te=this,he=(this._middlewares={},this.verno=0,Xn.dependencies),he=(this._options=T=r({addons:Xn.addons,autoOpen:!0,indexedDB:he.indexedDB,IDBKeyRange:he.IDBKeyRange,cache:"cloned",maxConnections:1e3},T),this._deps={indexedDB:T.indexedDB,IDBKeyRange:T.IDBKeyRange},T.addons),Se=(this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this,{dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:Me,dbReadyPromise:null,cancelOpen:Me,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3,autoOpen:T.autoOpen}),pe=(Se.dbReadyPromise=new Qe(function(de){Se.dbReadyResolve=de}),Se.openCanceller=new Qe(function(de,fe){Se.cancelOpen=fe}),this._state=Se,this.name=_,this.on=vn(this,"populate","blocked","versionchange","close",{ready:[Un,Me]}),this.once=function(de,fe){var _e=function(){for(var me=[],ge=0;ge<arguments.length;ge++)me[ge]=arguments[ge];te.on(de).unsubscribe(_e),fe.apply(te,me)};return te.on(de,_e)},this.on.ready.subscribe=S(this.on.ready.subscribe,function(de){return function(fe,_e){Xn.vip(function(){var me,ge=te._state;ge.openComplete?(ge.dbOpenError||Qe.resolve().then(fe),_e&&de(fe)):ge.onReadyBeingFired?(ge.onReadyBeingFired.push(fe),_e&&de(fe)):(de(fe),me=te,_e||de(function ve(){me.on.ready.unsubscribe(fe),me.on.ready.unsubscribe(ve)}))})}}),this.Collection=(N=this,Ar(xs.prototype,function(ve,ge){this.db=N;var _e=ut,me=null;if(ge)try{_e=ge()}catch(we){me=we}var ge=ve._ctx,ve=ge.table,Re=ve.hook.reading.fire;this._ctx={table:ve,index:ge.index,isPrimKey:!ge.index||ve.schema.primKey.keyPath&&ge.index===ve.schema.primKey.name,range:_e,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:me,or:ge.or,valueMapper:Re!==Pt?Re:null}})),this.Table=(B=this,Ar(kt.prototype,function(de,fe,_e){this.db=B,this._tx=_e,this.name=de,this.schema=fe,this.hook=B._allTables[de]?B._allTables[de].hook:vn(null,{creating:[lt,Me],reading:[tn,Pt],updating:[Sn,Me],deleting:[un,Me]})})),this.Transaction=(V=this,Ar(mm.prototype,function(de,fe,_e,me,ge){var ve=this;de!=="readonly"&&fe.forEach(function(Re){Re=(Re=_e[Re])==null?void 0:Re.yProps,Re&&(fe=fe.concat(Re.map(function(we){return we.updatesTable})))}),this.db=V,this.mode=de,this.storeNames=fe,this.schema=_e,this.chromeTransactionDurability=me,this.idbtrans=null,this.on=vn(this,"complete","error","abort"),this.parent=ge||null,this.active=!0,this._reculock=0,this._blockedFuncs=[],this._resolve=null,this._reject=null,this._waitingFor=null,this._waitingQueue=null,this._spinCount=0,this._completion=new Qe(function(Re,we){ve._resolve=Re,ve._reject=we}),this._completion.then(function(){ve.active=!1,ve.on.complete.fire()},function(Re){var we=ve.active;return ve.active=!1,ve.on.error.fire(Re),ve.parent?ve.parent._reject(Re):we&&ve.idbtrans&&ve.idbtrans.abort(),ae(Re)})})),this.Version=(q=this,Ar(r$.prototype,function(de){this.db=q,this._cfg={version:de,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=(J=this,Ar(bo.prototype,function(de,fe,_e){if(this.db=J,this._ctx={table:de,index:fe===":id"?null:fe,or:_e},this._cmp=this._ascending=Ke,this._descending=function(me,ge){return Ke(ge,me)},this._max=function(me,ge){return 0<Ke(me,ge)?me:ge},this._min=function(me,ge){return Ke(me,ge)<0?me:ge},this._IDBKeyRange=J._deps.IDBKeyRange,!this._IDBKeyRange)throw new Ee.MissingAPI})),this.on("versionchange",function(de){0<de.newVersion?console.warn("Another connection wants to upgrade database '".concat(te.name,"'. Closing db now to resume the upgrade.")):console.warn("Another connection wants to delete database '".concat(te.name,"'. Closing db now to resume the delete request.")),te.close({disableAutoOpen:!1})}),this.on("blocked",function(de){!de.newVersion||de.newVersion<de.oldVersion?console.warn("Dexie.delete('".concat(te.name,"') was blocked")):console.warn("Upgrade '".concat(te.name,"' blocked by other connection holding version ").concat(de.oldVersion/10))}),this._maxKey=Ah(T.IDBKeyRange),this._createTransaction=function(de,fe,_e,me){return new te.Transaction(de,fe,_e,te._options.chromeTransactionDurability,me)},this._fireOnBlocked=function(de){te.on("blocked").fire(de),Ch.toArray().filter(function(fe){return fe.name===te.name&&fe!==te&&!fe._state.vcFired}).map(function(fe){return fe.on("versionchange").fire(de)})},this.use(o$),this.use(d$),this.use(l$),this.use(s$),this.use(a$),new Proxy(this,{get:function(de,fe,_e){var me;return fe==="_vip"||(fe==="table"?function(ge){return Tm(te.table(ge),pe)}:(me=Reflect.get(de,fe,_e))instanceof kt?Tm(me,pe):fe==="tables"?me.map(function(ge){return Tm(ge,pe)}):fe==="_createTransaction"?function(){return Tm(me.apply(this,arguments),pe)}:me)}}));this.vip=pe,he.forEach(function(de){return de(te)})}var Am,iu=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",h$=(Jv.prototype.subscribe=function(_,T,N){return this._subscribe(_&&typeof _!="function"?_:{next:_,error:T,complete:N})},Jv.prototype[iu]=function(){return this},Jv);function Jv(_){this._subscribe=_}try{Am={indexedDB:s.indexedDB||s.mozIndexedDB||s.webkitIndexedDB||s.msIndexedDB,IDBKeyRange:s.IDBKeyRange||s.webkitIDBKeyRange}}catch{Am={indexedDB:null,IDBKeyRange:null}}function b1(_){var T,N=!1,B=new h$(function(V){var q=Y(_),J,te=!1,he={},Se={},pe={get closed(){return te},unsubscribe:function(){te||(te=!0,J&&J.abort(),de&&ts.storagemutated.unsubscribe(me))}},de=(V.start&&V.start(pe),!1),fe=function(){return le(ge)};function _e(){return Hv(Se,he)}var me=function(ve){Sm(he,ve),_e()&&fe()},ge=function(){var ve,Re,we;!te&&Am.indexedDB&&(he={},ve={},J&&J.abort(),J=new AbortController,we=(De=>{var $e=qn();try{q&&x();var He=w(_,De);return He=q?He.finally(P):He}finally{$e&&Wn()}})(Re={subscr:ve,signal:J.signal,requery:fe,querier:_,trans:null}),de||(ts(xo,me),de=!0),Promise.resolve(we).then(function(De){N=!0,T=De,te||Re.signal.aborted||(_e()||(Se=ve,_e())?fe():(he={},le(function(){return!te&&V.next&&V.next(De)})))},function(De){N=!1,["DatabaseClosedError","AbortError"].includes(De==null?void 0:De.name)||te||le(function(){te||V.error&&V.error(De)})}))};return setTimeout(fe,0),pe});return B.hasValue=function(){return N},B.getValue=function(){return T},B}var jl=Ca;function Zv(_){var T=So;try{So=!0,ts.storagemutated.fire(_),qv(_,!0)}finally{So=T}}h(jl,r(r({},ie),{delete:function(_){return new jl(_,{addons:[]}).delete()},exists:function(_){return new jl(_,{addons:[]}).open().then(function(T){return T.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(_){try{return T=jl.dependencies,N=T.indexedDB,T=T.IDBKeyRange,($v(N)?Promise.resolve(N.databases()).then(function(B){return B.map(function(V){return V.name}).filter(function(V){return V!==Pe})}):Fv(N,T).toCollection().primaryKeys()).then(_)}catch{return ae(new Ee.MissingAPI)}var T,N},defineClass:function(){return function(_){l(this,_)}},ignoreTransaction:function(_){return nt.trans?ee(nt.transless||ci,_):_()},vip:Vv,async:function(_){return function(){try{var T=Wv(_.apply(this,arguments));return T&&typeof T.then=="function"?T:Qe.resolve(T)}catch(N){return ae(N)}}},spawn:function(_,T,N){try{var B=Wv(_.apply(N,T||[]));return B&&typeof B.then=="function"?B:Qe.resolve(B)}catch(V){return ae(V)}},currentTransaction:{get:function(){return nt.trans||null}},waitFor:function(_,T){return _=Qe.resolve(typeof _=="function"?jl.ignoreTransaction(_):_).timeout(T||6e4),nt.trans?nt.trans.waitFor(_):_},Promise:Qe,debug:{get:function(){return En},set:function(_){Yr(_)}},derive:m,extend:l,props:h,override:S,Events:vn,on:ts,liveQuery:b1,extendObservabilitySet:Sm,getByKeyPath:U,setByKeyPath:O,delByKeyPath:function(_,T){typeof T=="string"?O(_,T,void 0):"length"in T&&[].map.call(T,function(N){O(_,N,void 0)})},shallowClone:k,deepClone:Z,getObjectDiff:Yv,cmp:Ke,asap:L,minKey:-1/0,addons:[],connections:{get:Ch.toArray},errnames:Ie,dependencies:Am,cache:Ul,semVer:"4.4.2",version:"4.4.2".split(".").map(function(_){return parseInt(_)}).reduce(function(_,T,N){return _+T/Math.pow(10,2*N)})})),jl.maxKey=Ah(jl.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(ts(xo,function(_){So||(_=new CustomEvent(eu,{detail:_}),So=!0,dispatchEvent(_),So=!1)}),addEventListener(eu,function(_){_=_.detail,So||Zv(_)}));var su,So=!1,x1=function(){};return typeof BroadcastChannel<"u"&&((x1=function(){(su=new BroadcastChannel(eu)).onmessage=function(_){return _.data&&Zv(_.data)}})(),typeof su.unref=="function"&&su.unref(),ts(xo,function(_){So||su.postMessage(_)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(_){if(!Ca.disableBfCache&&_.persisted){En&&console.debug("Dexie: handling persisted pagehide"),su!=null&&su.close();for(var T=0,N=Ch.toArray();T<N.length;T++)N[T].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(_){!Ca.disableBfCache&&_.persisted&&(En&&console.debug("Dexie: handling persisted pageshow"),x1(),Zv({all:new Fr(-1/0,[[]])}))})),Qe.rejectionMapper=function(_,T){return!_||_ instanceof Le||_ instanceof TypeError||_ instanceof SyntaxError||!_.name||!je[_.name]?_:(T=new je[_.name](T||_.message,_),"stack"in _&&p(T,"stack",{get:function(){return this.inner.stack}}),T)},Yr(En),r(Ca,Object.freeze({__proto__:null,DEFAULT_MAX_CONNECTIONS:1e3,Dexie:Ca,Entity:Xe,PropModification:Ot,RangeSet:Fr,add:function(_){return new Ot({add:_})},cmp:Ke,default:Ca,liveQuery:b1,mergeRanges:kh,rangesOverlap:u1,remove:function(_){return new Ot({remove:_})},replacePrefix:function(_,T){return new Ot({replacePrefix:[_,T]})}}),{default:Ca}),Ca})})(uj);var kJ=uj.exports;const dE=k0(kJ),_k=Symbol.for("Dexie"),u0=globalThis[_k]||(globalThis[_k]=dE);if(dE.semVer!==u0.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${dE.semVer} and ${u0.semVer}`);const{liveQuery:_pe,mergeRanges:bpe,rangesOverlap:xpe,RangeSet:Spe,cmp:Epe,Entity:wpe,PropModification:Tpe,replacePrefix:Ape,add:Rpe,remove:Cpe,DexieYProvider:Lpe}=u0;class IJ extends u0{constructor(){super("nadiplay");Cm(this,"profiles");this.version(1).stores({profiles:"id"})}}const ed=new IJ,bk="nadiplay_profiles",xk="nadiplay_profiles_migrated_v1",PJ=async()=>{try{if(localStorage.getItem(xk)==="1")return;const t=localStorage.getItem(bk);if(t){try{const e=JSON.parse(t);Array.isArray(e)&&e.length&&await ed.profiles.bulkPut(e)}catch{}localStorage.removeItem(bk)}localStorage.setItem(xk,"1")}catch{}},lu="nadiplay_active_profile",hE="nadiplay-profiles-changed",ng=()=>window.dispatchEvent(new Event(hE)),DJ=async()=>(await PJ(),await ed.profiles.toArray()),mo=()=>{const[t,e]=D.useState([]),[n,r]=D.useState(()=>localStorage.getItem(lu)),i=D.useCallback(async()=>{try{const u=await DJ();e(u)}catch{e([])}},[]);D.useEffect(()=>{i();const u=()=>{i(),r(localStorage.getItem(lu))};return window.addEventListener(hE,u),window.addEventListener("storage",u),()=>{window.removeEventListener(hE,u),window.removeEventListener("storage",u)}},[i]);const s=D.useCallback(u=>{u?localStorage.setItem(lu,u):localStorage.removeItem(lu),r(u),ng()},[]),a=D.useCallback(u=>{const d={...u,id:crypto.randomUUID()};return e(h=>[...h,d]),ed.profiles.put(d).then(()=>ng()).catch(h=>{console.error("[nadiDb] failed to persist profile:",h)}),localStorage.getItem(lu)||s(d.id),d},[s]),o=D.useCallback(async(u,d)=>{e(h=>h.map(f=>f.id===u?{...f,...d}:f));try{await ed.profiles.update(u,d),ng()}catch(h){console.error("[nadiDb] update failed:",h)}},[]),l=D.useCallback(async u=>{var d;e(h=>h.filter(f=>f.id!==u));try{await ed.profiles.delete(u)}catch(h){console.error("[nadiDb] delete failed:",h)}if(localStorage.getItem(lu)===u){const h=await ed.profiles.toArray();s(((d=h[0])==null?void 0:d.id)??null)}ng()},[s]),c=t.find(u=>u.id===n)??null;return{profiles:t,activeProfile:c,activeProfileId:n,setActiveProfileId:s,addProfile:a,updateProfile:o,removeProfile:l}};var ta=function(){return ta=Object.assign||function(e){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},ta.apply(this,arguments)};function xh(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]]);return n}function OJ(t,e,n,r){function i(s){return s instanceof n?s:new n(function(a){a(s)})}return new(n||(n=Promise))(function(s,a){function o(u){try{c(r.next(u))}catch(d){a(d)}}function l(u){try{c(r.throw(u))}catch(d){a(d)}}function c(u){u.done?s(u.value):i(u.value).then(o,l)}c((r=r.apply(t,e||[])).next())})}function NJ(t,e,n){if(n||arguments.length===2)for(var r=0,i=e.length,s;r<i;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return t.concat(s||Array.prototype.slice.call(e))}const MJ=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);class uA extends Error{constructor(e,n="FunctionsError",r){super(e),this.name=n,this.context=r}toJSON(){return{name:this.name,message:this.message,context:this.context}}}class BJ extends uA{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class Sk extends uA{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class Ek extends uA{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var fE;(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2"})(fE||(fE={}));class UJ{constructor(e,{headers:n={},customFetch:r,region:i=fE.Any}={}){this.url=e,this.headers=n,this.region=i,this.fetch=MJ(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return OJ(this,arguments,void 0,function*(n,r={}){var i;let s,a;try{const{headers:o,method:l,body:c,signal:u,timeout:d}=r;let h={},{region:f}=r;f||(f=this.region);const p=new URL(`${this.url}/${n}`);f&&f!=="any"&&(h["x-region"]=f,p.searchParams.set("forceFunctionRegion",f));let m;c&&(o&&!Object.prototype.hasOwnProperty.call(o,"Content-Type")||!o)?typeof Blob<"u"&&c instanceof Blob||c instanceof ArrayBuffer?(h["Content-Type"]="application/octet-stream",m=c):typeof c=="string"?(h["Content-Type"]="text/plain",m=c):typeof FormData<"u"&&c instanceof FormData?m=c:(h["Content-Type"]="application/json",m=JSON.stringify(c)):c&&typeof c!="string"&&!(typeof Blob<"u"&&c instanceof Blob)&&!(c instanceof ArrayBuffer)&&!(typeof FormData<"u"&&c instanceof FormData)?m=JSON.stringify(c):m=c;let g=u;d&&(a=new AbortController,s=setTimeout(()=>a.abort(),d),u?(g=a.signal,u.addEventListener("abort",()=>a.abort())):g=a.signal);const b=yield this.fetch(p.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},h),this.headers),o),body:m,signal:g}).catch(L=>{throw new BJ(L)}),v=b.headers.get("x-relay-error");if(v&&v==="true")throw new Sk(b);if(!b.ok)throw new Ek(b);let S=((i=b.headers.get("Content-Type"))!==null&&i!==void 0?i:"text/plain").split(";")[0].trim(),E;return S==="application/json"?E=yield b.json():S==="application/octet-stream"||S==="application/pdf"?E=yield b.blob():S==="text/event-stream"?E=b:S==="multipart/form-data"?E=yield b.formData():E=yield b.text(),{data:E,error:null,response:b}}catch(o){return{data:null,error:o,response:o instanceof Ek||o instanceof Sk?o.context:void 0}}finally{s&&clearTimeout(s)}})}}const dj=3,wk=t=>Math.min(1e3*2**t,3e4),jJ=[520,503],hj=["GET","HEAD","OPTIONS"];var FJ=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function Tk(t,e){return new Promise(n=>{if(e!=null&&e.aborted){n();return}const r=setTimeout(()=>{e==null||e.removeEventListener("abort",i),n()},t);function i(){clearTimeout(r),n()}e==null||e.addEventListener("abort",i)})}function $J(t,e,n,r){return!(!r||n>=dj||!hj.includes(t)||!jJ.includes(e))}var VJ=class{constructor(t){var e,n,r,i,s;this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(n=t.isMaybeSingle)!==null&&n!==void 0?n:!1,this.shouldStripNulls=(r=t.shouldStripNulls)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(i=t.urlLengthLimit)!==null&&i!==void 0?i:8e3,this.retryEnabled=(s=t.retry)!==null&&s!==void 0?s:!0,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get("Accept")==="text/csv")throw new Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}retry(t){return this.retryEnabled=t,this}then(t,e){var n=this;if(this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json"),this.shouldStripNulls){const a=this.headers.get("Accept");a==="application/vnd.pgrst.object+json"?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):(!a||a==="application/json")&&this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}const r=this.fetch;let s=(async()=>{let a=0;for(;;){const c=new Headers(n.headers);a>0&&c.set("X-Retry-Count",String(a));let u;try{u=await r(n.url.toString(),{method:n.method,headers:c,body:JSON.stringify(n.body,(d,h)=>typeof h=="bigint"?h.toString():h),signal:n.signal})}catch(d){if((d==null?void 0:d.name)==="AbortError"||(d==null?void 0:d.code)==="ABORT_ERR"||!hj.includes(n.method))throw d;if(n.retryEnabled&&a<dj){const h=wk(a);a++,await Tk(h,n.signal);continue}throw d}if($J(n.method,u.status,a,n.retryEnabled)){var o,l;const d=(o=(l=u.headers)===null||l===void 0?void 0:l.get("Retry-After"))!==null&&o!==void 0?o:null,h=d!==null?Math.max(0,parseInt(d,10)||0)*1e3:wk(a);await u.text(),a++,await Tk(h,n.signal);continue}return await n.processResponse(u)}})();return this.shouldThrowOnError||(s=s.catch(a=>{var o;let l="",c="",u="";const d=a==null?void 0:a.cause;if(d){var h,f,p,m;const v=(h=d==null?void 0:d.message)!==null&&h!==void 0?h:"",S=(f=d==null?void 0:d.code)!==null&&f!==void 0?f:"";l=`${(p=a==null?void 0:a.name)!==null&&p!==void 0?p:"FetchError"}: ${a==null?void 0:a.message}`,l+=`

Caused by: ${(m=d==null?void 0:d.name)!==null&&m!==void 0?m:"Error"}: ${v}`,S&&(l+=` (${S})`),d!=null&&d.stack&&(l+=`
${d.stack}`)}else{var g;l=(g=a==null?void 0:a.stack)!==null&&g!==void 0?g:""}const b=this.url.toString().length;return(a==null?void 0:a.name)==="AbortError"||(a==null?void 0:a.code)==="ABORT_ERR"?(u="",c="Request was aborted (timeout or manual cancellation)",b>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${b} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):((d==null?void 0:d.name)==="HeadersOverflowError"||(d==null?void 0:d.code)==="UND_ERR_HEADERS_OVERFLOW")&&(u="",c="HTTP headers exceeded server limits (typically 16KB)",b>this.urlLengthLimit&&(c+=`. Your request URL is ${b} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${(o=a==null?void 0:a.name)!==null&&o!==void 0?o:"FetchError"}: ${a==null?void 0:a.message}`,details:l,hint:c,code:u},data:null,count:null,status:0,statusText:""}})),s.then(t,e)}async processResponse(t){var e=this;let n=null,r=null,i=null,s=t.status,a=t.statusText;if(t.ok){var o,l;if(e.method!=="HEAD"){var c;const h=await t.text();h===""||(e.headers.get("Accept")==="text/csv"||e.headers.get("Accept")&&(!((c=e.headers.get("Accept"))===null||c===void 0)&&c.includes("application/vnd.pgrst.plan+text"))?r=h:r=JSON.parse(h))}const u=(o=e.headers.get("Prefer"))===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),d=(l=t.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");u&&d&&d.length>1&&(i=parseInt(d[1])),e.isMaybeSingle&&Array.isArray(r)&&(r.length>1?(n={code:"PGRST116",details:`Results contain ${r.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},r=null,i=null,s=406,a="Not Acceptable"):r.length===1?r=r[0]:r=null)}else{const u=await t.text();try{n=JSON.parse(u),Array.isArray(n)&&t.status===404&&(r=[],n=null,s=200,a="OK")}catch{t.status===404&&u===""?(s=204,a="No Content"):n={message:u}}if(n&&e.shouldThrowOnError)throw new FJ(n)}return{success:n===null,error:n,data:r,count:i,status:s,statusText:a}}returns(){return this}overrideTypes(){return this}},GJ=class extends VJ{select(t){let e=!1;const n=(t??"*").split("").map(r=>/\s/.test(r)&&!e?"":(r==='"'&&(e=!e),r)).join("");return this.url.searchParams.set("select",n),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:n,foreignTable:r,referencedTable:i=r}={}){const s=i?`${i}.order`:"order",a=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${a?`${a},`:""}${t}.${e?"asc":"desc"}${n===void 0?"":n?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:n=e}={}){const r=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(r,`${t}`),this}range(t,e,{foreignTable:n,referencedTable:r=n}={}){const i=typeof r>"u"?"offset":`${r}.offset`,s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${t}`),this.url.searchParams.set(s,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:n=!1,buffers:r=!1,wal:i=!1,format:s="text"}={}){var a;const o=[t?"analyze":null,e?"verbose":null,n?"settings":null,r?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${s}; for="${l}"; options=${o};`),s==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}};const Ak=new RegExp("[,()]");var Du=class extends GJ{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){const n=Array.from(new Set(e)).map(r=>typeof r=="string"&&Ak.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(t,`in.(${n})`),this}notIn(t,e){const n=Array.from(new Set(e)).map(r=>typeof r=="string"&&Ak.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(t,`not.in.(${n})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:n,type:r}={}){let i="";r==="plain"?i="pl":r==="phrase"?i="ph":r==="websearch"&&(i="w");const s=n===void 0?"":`(${n})`;return this.url.searchParams.append(t,`${i}fts${s}.${e}`),this}match(t){return Object.entries(t).filter(([e,n])=>n!==void 0).forEach(([e,n])=>{this.url.searchParams.append(e,`eq.${n}`)}),this}not(t,e,n){return this.url.searchParams.append(t,`not.${e}.${n}`),this}or(t,{foreignTable:e,referencedTable:n=e}={}){const r=n?`${n}.or`:"or";return this.url.searchParams.append(r,`(${t})`),this}filter(t,e,n){return this.url.searchParams.append(t,`${e}.${n}`),this}},HJ=class{constructor(t,{headers:e={},schema:n,fetch:r,urlLengthLimit:i=8e3,retry:s}){this.url=t,this.headers=new Headers(e),this.schema=n,this.fetch=r,this.urlLengthLimit=i,this.retry=s}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){const{head:n=!1,count:r}=e??{},i=n?"HEAD":"GET";let s=!1;const a=(t??"*").split("").map(c=>/\s/.test(c)&&!s?"":(c==='"'&&(s=!s),c)).join(""),{url:o,headers:l}=this.cloneRequestState();return o.searchParams.set("select",a),r&&l.append("Prefer",`count=${r}`),new Du({method:i,url:o,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(t,{count:e,defaultToNull:n=!0}={}){var r;const i="POST",{url:s,headers:a}=this.cloneRequestState();if(e&&a.append("Prefer",`count=${e}`),n||a.append("Prefer","missing=default"),Array.isArray(t)){const o=t.reduce((l,c)=>l.concat(Object.keys(c)),[]);if(o.length>0){const l=[...new Set(o)].map(c=>`"${c}"`);s.searchParams.set("columns",l.join(","))}}return new Du({method:i,url:s,headers:a,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(t,{onConflict:e,ignoreDuplicates:n=!1,count:r,defaultToNull:i=!0}={}){var s;const a="POST",{url:o,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${n?"ignore":"merge"}-duplicates`),e!==void 0&&o.searchParams.set("on_conflict",e),r&&l.append("Prefer",`count=${r}`),i||l.append("Prefer","missing=default"),Array.isArray(t)){const c=t.reduce((u,d)=>u.concat(Object.keys(d)),[]);if(c.length>0){const u=[...new Set(c)].map(d=>`"${d}"`);o.searchParams.set("columns",u.join(","))}}return new Du({method:a,url:o,headers:l,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(t,{count:e}={}){var n;const r="PATCH",{url:i,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new Du({method:r,url:i,headers:s,schema:this.schema,body:t,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:t}={}){var e;const n="DELETE",{url:r,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new Du({method:n,url:r,headers:i,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function fp(t){"@babel/helpers - typeof";return fp=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},fp(t)}function KJ(t,e){if(fp(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(fp(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function zJ(t){var e=KJ(t,"string");return fp(e)=="symbol"?e:e+""}function qJ(t,e,n){return(e=zJ(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Rk(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function rg(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Rk(Object(n),!0).forEach(function(r){qJ(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Rk(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}var WJ=class fj{constructor(e,{headers:n={},schema:r,fetch:i,timeout:s,urlLengthLimit:a=8e3,retry:o}={}){this.url=e,this.headers=new Headers(n),this.schemaName=r,this.urlLengthLimit=a;const l=i??globalThis.fetch;s!==void 0&&s>0?this.fetch=(c,u)=>{const d=new AbortController,h=setTimeout(()=>d.abort(),s),f=u==null?void 0:u.signal;if(f){if(f.aborted)return clearTimeout(h),l(c,u);const p=()=>{clearTimeout(h),d.abort()};return f.addEventListener("abort",p,{once:!0}),l(c,rg(rg({},u),{},{signal:d.signal})).finally(()=>{clearTimeout(h),f.removeEventListener("abort",p)})}return l(c,rg(rg({},u),{},{signal:d.signal})).finally(()=>clearTimeout(h))}:this.fetch=l,this.retry=o}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new HJ(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(e){return new fj(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(e,n={},{head:r=!1,get:i=!1,count:s}={}){var a;let o;const l=new URL(`${this.url}/rpc/${e}`);let c;const u=f=>f!==null&&typeof f=="object"&&(!Array.isArray(f)||f.some(u)),d=r&&Object.values(n).some(u);d?(o="POST",c=n):r||i?(o=r?"HEAD":"GET",Object.entries(n).filter(([f,p])=>p!==void 0).map(([f,p])=>[f,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([f,p])=>{l.searchParams.append(f,p)})):(o="POST",c=n);const h=new Headers(this.headers);return d?h.set("Prefer",s?`count=${s},return=minimal`:"return=minimal"):s&&h.set("Prefer",`count=${s}`),new Du({method:o,url:l,headers:h,schema:this.schemaName,body:c,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};class YJ{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const n=globalThis.process;if(n){const r=n.versions;if(r&&r.node){const i=r.node,s=parseInt(i.replace(/^v/,"").split(".")[0]);return s>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${s} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${s} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
import ws from "ws"
new RealtimeClient(url, { transport: ws })`}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let n=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(n+=`

Suggested solution: ${e.workaround}`),new Error(n)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const XJ="2.104.1",QJ=`realtime-js/${XJ}`,JJ="1.0.0",pj="2.0.0",ZJ=pj,eZ=1e4,tZ=100,Go={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},mj={close:"phx_close",error:"phx_error",join:"phx_join",leave:"phx_leave",access_token:"access_token"},pE={connecting:"connecting",closing:"closing",closed:"closed"};class nZ{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,n){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return n(this._binaryEncodeUserBroadcastPush(e));let r=[e.join_ref,e.ref,e.topic,e.event,e.payload];return n(JSON.stringify(r))}_binaryEncodeUserBroadcastPush(e){var n;return this._isArrayBuffer((n=e.payload)===null||n===void 0?void 0:n.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var n,r;const i=(r=(n=e.payload)===null||n===void 0?void 0:n.payload)!==null&&r!==void 0?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,i)}_encodeJsonUserBroadcastPush(e){var n,r;const i=(r=(n=e.payload)===null||n===void 0?void 0:n.payload)!==null&&r!==void 0?r:{},a=new TextEncoder().encode(JSON.stringify(i)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,a)}_encodeUserBroadcastPush(e,n,r){var i,s;const a=e.topic,o=(i=e.ref)!==null&&i!==void 0?i:"",l=(s=e.join_ref)!==null&&s!==void 0?s:"",c=e.payload.event,u=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},d=Object.keys(u).length===0?"":JSON.stringify(u);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`ref length ${o.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`topic length ${a.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`userEvent length ${c.length} exceeds maximum of 255`);if(d.length>255)throw new Error(`metadata length ${d.length} exceeds maximum of 255`);const h=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+o.length+a.length+c.length+d.length,f=new ArrayBuffer(this.HEADER_LENGTH+h);let p=new DataView(f),m=0;p.setUint8(m++,this.KINDS.userBroadcastPush),p.setUint8(m++,l.length),p.setUint8(m++,o.length),p.setUint8(m++,a.length),p.setUint8(m++,c.length),p.setUint8(m++,d.length),p.setUint8(m++,n),Array.from(l,b=>p.setUint8(m++,b.charCodeAt(0))),Array.from(o,b=>p.setUint8(m++,b.charCodeAt(0))),Array.from(a,b=>p.setUint8(m++,b.charCodeAt(0))),Array.from(c,b=>p.setUint8(m++,b.charCodeAt(0))),Array.from(d,b=>p.setUint8(m++,b.charCodeAt(0)));var g=new Uint8Array(f.byteLength+r.byteLength);return g.set(new Uint8Array(f),0),g.set(new Uint8Array(r),f.byteLength),g.buffer}decode(e,n){if(this._isArrayBuffer(e)){let r=this._binaryDecode(e);return n(r)}if(typeof e=="string"){const r=JSON.parse(e),[i,s,a,o,l]=r;return n({join_ref:i,ref:s,topic:a,event:o,payload:l})}return n({})}_binaryDecode(e){const n=new DataView(e),r=n.getUint8(0),i=new TextDecoder;switch(r){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,n,i)}}_decodeUserBroadcast(e,n,r){const i=n.getUint8(1),s=n.getUint8(2),a=n.getUint8(3),o=n.getUint8(4);let l=this.HEADER_LENGTH+4;const c=r.decode(e.slice(l,l+i));l=l+i;const u=r.decode(e.slice(l,l+s));l=l+s;const d=r.decode(e.slice(l,l+a));l=l+a;const h=e.slice(l,e.byteLength),f=o===this.JSON_ENCODING?JSON.parse(r.decode(h)):h,p={type:this.BROADCAST_EVENT,event:u,payload:f};return a>0&&(p.meta=JSON.parse(d)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){var n;return e instanceof ArrayBuffer||((n=e==null?void 0:e.constructor)===null||n===void 0?void 0:n.name)==="ArrayBuffer"}_pick(e,n){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([r])=>n.includes(r)))}}var _n;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(_n||(_n={}));const Ck=(t,e,n={})=>{var r;const i=(r=n.skipTypes)!==null&&r!==void 0?r:[];return e?Object.keys(e).reduce((s,a)=>(s[a]=rZ(a,t,e,i),s),{}):{}},rZ=(t,e,n,r)=>{const i=e.find(o=>o.name===t),s=i==null?void 0:i.type,a=n[t];return s&&!r.includes(s)?gj(s,a):mE(a)},gj=(t,e)=>{if(t.charAt(0)==="_"){const n=t.slice(1,t.length);return oZ(e,n)}switch(t){case _n.bool:return iZ(e);case _n.float4:case _n.float8:case _n.int2:case _n.int4:case _n.int8:case _n.numeric:case _n.oid:return sZ(e);case _n.json:case _n.jsonb:return aZ(e);case _n.timestamp:return lZ(e);case _n.abstime:case _n.date:case _n.daterange:case _n.int4range:case _n.int8range:case _n.money:case _n.reltime:case _n.text:case _n.time:case _n.timestamptz:case _n.timetz:case _n.tsrange:case _n.tstzrange:return mE(e);default:return mE(e)}},mE=t=>t,iZ=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},sZ=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},aZ=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},oZ=(t,e)=>{if(typeof t!="string")return t;const n=t.length-1,r=t[n];if(t[0]==="{"&&r==="}"){let s;const a=t.slice(1,n);try{s=JSON.parse("["+a+"]")}catch{s=a?a.split(","):[]}return s.map(o=>gj(e,o))}return t},lZ=t=>typeof t=="string"?t.replace(" ","T"):t,yj=t=>{const e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};var kf=t=>typeof t=="function"?t:function(){return t},cZ=typeof self<"u"?self:null,Ou=typeof window<"u"?window:null,qs=cZ||Ou||globalThis,uZ="2.0.0",dZ=1e4,hZ=1e3,Js={connecting:0,open:1,closing:2,closed:3},di={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Va={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},gE={longpoll:"longpoll",websocket:"websocket"},fZ={complete:4},yE="base64url.bearer.phx.",ig=class{constructor(t,e,n,r){this.channel=t,this.event=e,this.payload=n||function(){return{}},this.receivedResp=null,this.timeout=r,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(t){this.timeout=t,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:t,response:e,_ref:n}){this.recHooks.filter(r=>r.status===t).forEach(r=>r.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},vj=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},pZ=class{constructor(t,e,n){this.state=di.closed,this.topic=t,this.params=kf(e||{}),this.socket=n,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new ig(this,Va.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new vj(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=di.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(r=>r.send()),this.pushBuffer=[]}),this.joinPush.receive("error",r=>{this.state=di.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,r),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=di.closed,this.socket.remove(this)}),this.onError(r=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,r),this.isJoining()&&this.joinPush.reset(),this.state=di.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new ig(this,Va.leave,kf({}),this.timeout).send(),this.state=di.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(Va.reply,(r,i)=>{this.trigger(this.replyEventName(i),r)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=di.closed,this.bindings=[]}onClose(t){this.on(Va.close,t)}onError(t){return this.on(Va.error,e=>t(e))}on(t,e){let n=this.bindingRef++;return this.bindings.push({event:t,ref:n,callback:e}),n}off(t,e){this.bindings=this.bindings.filter(n=>!(n.event===t&&(typeof e>"u"||e===n.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,n=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let r=new ig(this,t,function(){return e},n);return this.canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=di.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(Va.close,"leave")},n=new ig(this,Va.leave,kf({}),t);return n.receive("ok",()=>e()).receive("timeout",()=>e()),n.send(),this.canPush()||n.trigger("ok",{}),n}onMessage(t,e,n){return e}filterBindings(t,e,n){return!0}isMember(t,e,n,r){return this.topic!==t?!1:r&&r!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:n,joinRef:r}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=di.joining,this.joinPush.resend(t))}trigger(t,e,n,r){let i=this.onMessage(t,e,n,r);if(e&&!i)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let s=this.bindings.filter(a=>a.event===t&&this.filterBindings(a,e,n));for(let a=0;a<s.length;a++)s[a].callback(i,n,r||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===di.closed}isErrored(){return this.state===di.errored}isJoined(){return this.state===di.joined}isJoining(){return this.state===di.joining}isLeaving(){return this.state===di.leaving}},d0=class{static request(t,e,n,r,i,s,a){if(qs.XDomainRequest){let o=new qs.XDomainRequest;return this.xdomainRequest(o,t,e,r,i,s,a)}else if(qs.XMLHttpRequest){let o=new qs.XMLHttpRequest;return this.xhrRequest(o,t,e,n,r,i,s,a)}else{if(qs.fetch&&qs.AbortController)return this.fetchRequest(t,e,n,r,i,s,a);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,n,r,i,s,a){let o={method:t,headers:n,body:r},l=null;return i&&(l=new AbortController,setTimeout(()=>l.abort(),i),o.signal=l.signal),qs.fetch(e,o).then(c=>c.text()).then(c=>this.parseJSON(c)).then(c=>a&&a(c)).catch(c=>{c.name==="AbortError"&&s?s():a&&a(null)}),l}static xdomainRequest(t,e,n,r,i,s,a){return t.timeout=i,t.open(e,n),t.onload=()=>{let o=this.parseJSON(t.responseText);a&&a(o)},s&&(t.ontimeout=s),t.onprogress=()=>{},t.send(r),t}static xhrRequest(t,e,n,r,i,s,a,o){t.open(e,n,!0),t.timeout=s;for(let[l,c]of Object.entries(r))t.setRequestHeader(l,c);return t.onerror=()=>o&&o(null),t.onreadystatechange=()=>{if(t.readyState===fZ.complete&&o){let l=this.parseJSON(t.responseText);o(l)}},a&&(t.ontimeout=a),t.send(i),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let n=[];for(var r in t){if(!Object.prototype.hasOwnProperty.call(t,r))continue;let i=e?`${e}[${r}]`:r,s=t[r];typeof s=="object"?n.push(this.serialize(s,i)):n.push(encodeURIComponent(i)+"="+encodeURIComponent(s))}return n.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let n=t.match(/\?/)?"&":"?";return`${t}${n}${this.serialize(e)}`}},mZ=t=>{let e="",n=new Uint8Array(t),r=n.byteLength;for(let i=0;i<r;i++)e+=String.fromCharCode(n[i]);return btoa(e)},cu=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(yE)&&(this.authToken=atob(e[1].slice(yE.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=Js.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+gE.websocket),"$1/"+gE.longpoll)}endpointURL(){return d0.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,n){this.close(t,e,n),this.readyState=Js.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===Js.open||this.readyState===Js.connecting}poll(){const t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:n,token:r,messages:i}=e;if(n===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=r}else n=0;switch(n){case 200:i.forEach(s=>{setTimeout(()=>this.onmessage({data:s}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=Js.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${n}`)}})}send(t){typeof t!="string"&&(t=mZ(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},t.join(`
`),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(t,e,n){for(let i of this.reqs)i.abort();this.readyState=Js.closed;let r=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:n});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",r)):this.onclose(r)}ajax(t,e,n,r,i){let s,a=()=>{this.reqs.delete(s),r()};s=d0.request(t,this.endpointURL(),e,n,this.timeout,a,o=>{this.reqs.delete(s),this.isActive()&&i(o)}),this.reqs.add(s)}},gZ=class ef{constructor(e,n={}){let r=n.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(r.state,i=>{let{onJoin:s,onLeave:a,onSync:o}=this.caller;this.joinRef=this.channel.joinRef(),this.state=ef.syncState(this.state,i,s,a),this.pendingDiffs.forEach(l=>{this.state=ef.syncDiff(this.state,l,s,a)}),this.pendingDiffs=[],o()}),this.channel.on(r.diff,i=>{let{onJoin:s,onLeave:a,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=ef.syncDiff(this.state,i,s,a),o())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return ef.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,n,r,i){let s=this.clone(e),a={},o={};return this.map(s,(l,c)=>{n[l]||(o[l]=c)}),this.map(n,(l,c)=>{let u=s[l];if(u){let d=c.metas.map(m=>m.phx_ref),h=u.metas.map(m=>m.phx_ref),f=c.metas.filter(m=>h.indexOf(m.phx_ref)<0),p=u.metas.filter(m=>d.indexOf(m.phx_ref)<0);f.length>0&&(a[l]=c,a[l].metas=f),p.length>0&&(o[l]=this.clone(u),o[l].metas=p)}else a[l]=c}),this.syncDiff(s,{joins:a,leaves:o},r,i)}static syncDiff(e,n,r,i){let{joins:s,leaves:a}=this.clone(n);return r||(r=function(){}),i||(i=function(){}),this.map(s,(o,l)=>{let c=e[o];if(e[o]=this.clone(l),c){let u=e[o].metas.map(h=>h.phx_ref),d=c.metas.filter(h=>u.indexOf(h.phx_ref)<0);e[o].metas.unshift(...d)}r(o,c,l)}),this.map(a,(o,l)=>{let c=e[o];if(!c)return;let u=l.metas.map(d=>d.phx_ref);c.metas=c.metas.filter(d=>u.indexOf(d.phx_ref)<0),i(o,c,l),c.metas.length===0&&delete e[o]}),e}static list(e,n){return n||(n=function(r,i){return i}),this.map(e,(r,i)=>n(r,i))}static map(e,n){return Object.getOwnPropertyNames(e).map(r=>n(r,e[r]))}static clone(e){return JSON.parse(JSON.stringify(e))}},sg={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let n=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(n))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[n,r,i,s,a]=JSON.parse(t);return e({join_ref:n,ref:r,topic:i,event:s,payload:a})}},binaryEncode(t){let{join_ref:e,ref:n,event:r,topic:i,payload:s}=t,a=this.META_LENGTH+e.length+n.length+i.length+r.length,o=new ArrayBuffer(this.HEADER_LENGTH+a),l=new DataView(o),c=0;l.setUint8(c++,this.KINDS.push),l.setUint8(c++,e.length),l.setUint8(c++,n.length),l.setUint8(c++,i.length),l.setUint8(c++,r.length),Array.from(e,d=>l.setUint8(c++,d.charCodeAt(0))),Array.from(n,d=>l.setUint8(c++,d.charCodeAt(0))),Array.from(i,d=>l.setUint8(c++,d.charCodeAt(0))),Array.from(r,d=>l.setUint8(c++,d.charCodeAt(0)));var u=new Uint8Array(o.byteLength+s.byteLength);return u.set(new Uint8Array(o),0),u.set(new Uint8Array(s),o.byteLength),u.buffer},binaryDecode(t){let e=new DataView(t),n=e.getUint8(0),r=new TextDecoder;switch(n){case this.KINDS.push:return this.decodePush(t,e,r);case this.KINDS.reply:return this.decodeReply(t,e,r);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,r)}},decodePush(t,e,n){let r=e.getUint8(1),i=e.getUint8(2),s=e.getUint8(3),a=this.HEADER_LENGTH+this.META_LENGTH-1,o=n.decode(t.slice(a,a+r));a=a+r;let l=n.decode(t.slice(a,a+i));a=a+i;let c=n.decode(t.slice(a,a+s));a=a+s;let u=t.slice(a,t.byteLength);return{join_ref:o,ref:null,topic:l,event:c,payload:u}},decodeReply(t,e,n){let r=e.getUint8(1),i=e.getUint8(2),s=e.getUint8(3),a=e.getUint8(4),o=this.HEADER_LENGTH+this.META_LENGTH,l=n.decode(t.slice(o,o+r));o=o+r;let c=n.decode(t.slice(o,o+i));o=o+i;let u=n.decode(t.slice(o,o+s));o=o+s;let d=n.decode(t.slice(o,o+a));o=o+a;let h=t.slice(o,t.byteLength),f={status:d,response:h};return{join_ref:l,ref:c,topic:u,event:Va.reply,payload:f}},decodeBroadcast(t,e,n){let r=e.getUint8(1),i=e.getUint8(2),s=this.HEADER_LENGTH+2,a=n.decode(t.slice(s,s+r));s=s+r;let o=n.decode(t.slice(s,s+i));s=s+i;let l=t.slice(s,t.byteLength);return{join_ref:null,ref:null,topic:a,event:o,payload:l}}},yZ=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||dZ,this.transport=e.transport||qs.WebSocket||cu,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||qs&&qs.sessionStorage,this.establishedConnections=0,this.defaultEncoder=sg.encode.bind(sg),this.defaultDecoder=sg.decode.bind(sg),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==cu?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let n=null;Ou&&Ou.addEventListener&&(Ou.addEventListener("pagehide",r=>{this.conn&&(this.disconnect(),n=this.connectClock)}),Ou.addEventListener("pageshow",r=>{n===this.connectClock&&(n=null,this.connect())}),Ou.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??!0,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=r=>e.rejoinAfterMs?e.rejoinAfterMs(r):[1e3,2e3,5e3][r-1]||1e4,this.reconnectAfterMs=r=>e.reconnectAfterMs?e.reconnectAfterMs(r):[10,50,100,150,200,250,500,1e3,2e3][r-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(r,i,s)=>{console.log(`${r}: ${i}`,s)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=kf(e.params||{}),this.endPoint=`${t}/${gE.websocket}`,this.vsn=e.vsn||uZ,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new vj(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=e.authToken}getLongPollTransport(){return cu}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=d0.appendParams(d0.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,n){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,t&&t()},e,n)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=kf(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==cu?this.connectWithFallback(cu,this.longPollFallbackMs):this.transportConnect())}log(t,e,n){this.logger&&this.logger(t,e,n)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}onHeartbeat(t){this.heartbeatCallback=t}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),n=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let r=this.onMessage(i=>{i.ref===e&&(this.off([r]),t(Date.now()-n))});return!0}transportName(t){switch(t){case cu:return"LongPoll";default:return t.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${yE}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let n=!1,r=!0,i,s,a=this.transportName(t),o=l=>{this.log("transport",`falling back to ${a}...`,l),this.off([i,s]),r=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${a}`))return o("memorized");this.fallbackTimer=setTimeout(o,e),s=this.onError(l=>{this.log("transport","error",l),r&&!n&&(clearTimeout(this.fallbackTimer),o(l))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(n=!0,!r){let l=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${l}`,"true"),this.log("transport",`established ${l} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(o,e),this.ping(l=>{this.log("transport","connected to primary after",l),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),hZ,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,n){if(!this.conn)return t&&t();const r=this.conn;this.waitForBufferDone(r,()=>{e?r.close(e,n||""):r.close(),this.waitForSocketClosed(r,()=>{this.conn===r&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e,n=1){if(n===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,n+1)},150*n)}waitForSocketClosed(t,e,n=1){if(n===5||t.readyState===Js.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,n+1)},150*n)}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t)}onConnError(t){this.hasLogger()&&this.log("transport",t);let e=this.transport,n=this.establishedConnections;this.triggerStateCallbacks("error",t,e,n),(e===this.transport||n>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(Va.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case Js.connecting:return"connecting";case Js.open:return"open";case Js.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([n])=>t.indexOf(n)===-1)}channel(t,e={}){let n=new pZ(t,e,this);return this.channels.push(n),n}push(t){if(this.hasLogger()){let{topic:e,event:n,payload:r,ref:i,join_ref:s}=t;this.log("push",`${e} ${n} (${s}, ${i})`,r)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:n,event:r,payload:i,ref:s,join_ref:a}=e;if(s&&s===this.pendingHeartbeatRef){const o=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(i.status==="ok"?"ok":"error",o)}catch(l){this.log("error","error in heartbeat callback",l)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${i.status||""} ${n} ${r} ${s&&"("+s+")"||""}`.trim(),i);for(let o=0;o<this.channels.length;o++){const l=this.channels[o];l.isMember(n,r,i,a)&&l.trigger(r,i,s,a)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([n,r])=>{try{r(...e)}catch(i){this.log("error",`error in ${t} callback`,i)}})}catch(n){this.log("error",`error triggering ${t} callbacks`,n)}}leaveOpenTopic(t){let e=this.channels.find(n=>n.topic===t&&(n.isJoined()||n.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}};class If{constructor(e,n){const r=_Z(n);this.presence=new gZ(e.getChannel(),r),this.presence.onJoin((i,s,a)=>{const o=If.onJoinPayload(i,s,a);e.getChannel().trigger("presence",o)}),this.presence.onLeave((i,s,a)=>{const o=If.onLeavePayload(i,s,a);e.getChannel().trigger("presence",o)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return If.transformState(this.presence.state)}static transformState(e){return e=vZ(e),Object.getOwnPropertyNames(e).reduce((n,r)=>{const i=e[r];return n[r]=ry(i),n},{})}static onJoinPayload(e,n,r){const i=Lk(n),s=ry(r);return{event:"join",key:e,currentPresences:i,newPresences:s}}static onLeavePayload(e,n,r){const i=Lk(n),s=ry(r);return{event:"leave",key:e,currentPresences:i,leftPresences:s}}}function ry(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function vZ(t){return JSON.parse(JSON.stringify(t))}function _Z(t){return(t==null?void 0:t.events)&&{events:t.events}}function Lk(t){return t!=null&&t.metas?ry(t):[]}var kk;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(kk||(kk={}));class bZ{get state(){return this.presenceAdapter.state}constructor(e,n){this.channel=e,this.presenceAdapter=new If(this.channel.channelAdapter,n)}}class xZ{constructor(e,n,r){const i=SZ(r);this.channel=e.getSocket().channel(n,i),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,n){return this.channel.on(e,n)}off(e,n){this.channel.off(e,n)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,n,r){let i;try{i=this.channel.push(e,n,r)}catch{throw new Error(`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>tZ){const s=this.channel.pushBuffer.shift();s.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${s.event}`,s.payload())}return i}updateJoinPayload(e){const n=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},n),e)}canPush(){return this.socket.isConnected()&&this.state===Go.joined}isJoined(){return this.state===Go.joined}isJoining(){return this.state===Go.joining}isClosed(){return this.state===Go.closed}isLeaving(){return this.state===Go.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}}function SZ(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var Ik;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(Ik||(Ik={}));var td;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(td||(td={}));var Ga;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(Ga||(Ga={}));class Pf{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,n={config:{}},r){var i,s;if(this.topic=e,this.params=n,this.socket=r,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},n.config),this.channelAdapter=new xZ(this.socket.socketAdapter,e,this.params),this.presence=new bZ(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=yj(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((s=(i=this.params.config)===null||i===void 0?void 0:i.broadcast)===null||s===void 0)&&s.replay))throw new Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(e,n=this.timeout){var r,i,s;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){const{config:{broadcast:a,presence:o,private:l}}=this.params,c=(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(f=>f.filter))!==null&&i!==void 0?i:[],u=!!this.bindings[td.PRESENCE]&&this.bindings[td.PRESENCE].length>0||((s=this.params.config.presence)===null||s===void 0?void 0:s.enabled)===!0,d={},h={broadcast:a,presence:Object.assign(Object.assign({},o),{enabled:u}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(f=>{e==null||e(Ga.CHANNEL_ERROR,f)}),this._onClose(()=>e==null?void 0:e(Ga.CLOSED)),this.updateJoinPayload(Object.assign({config:h},d)),this._updateFilterMessage(),this.channelAdapter.subscribe(n).receive("ok",async({postgres_changes:f})=>{if(this.socket._isManualToken()||this.socket.setAuth(),f===void 0){e==null||e(Ga.SUBSCRIBED);return}this._updatePostgresBindings(f,e)}).receive("error",f=>{this.state=Go.errored,e==null||e(Ga.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(f).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(Ga.TIMED_OUT)})}return this}_updatePostgresBindings(e,n){var r;const i=this.bindings.postgres_changes,s=(r=i==null?void 0:i.length)!==null&&r!==void 0?r:0,a=[];for(let o=0;o<s;o++){const l=i[o],{filter:{event:c,schema:u,table:d,filter:h}}=l,f=e&&e[o];if(f&&f.event===c&&Pf.isFilterValueEqual(f.schema,u)&&Pf.isFilterValueEqual(f.table,d)&&Pf.isFilterValueEqual(f.filter,h))a.push(Object.assign(Object.assign({},l),{id:f.id}));else{this.unsubscribe(),this.state=Go.errored,n==null||n(Ga.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=a,this.state!=Go.errored&&n&&n(Ga.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,n={}){return await this.send({type:"presence",event:"track",payload:e},n.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,n,r){const i=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),s=e===td.PRESENCE||e===td.POSTGRES_CHANGES;if(i&&s)throw this.socket.log("channel",`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),new Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,n,r)}async httpSend(e,n,r={}){var i;if(n==null)return Promise.reject(new Error("Payload is required for httpSend()"));const s={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(s.Authorization=`Bearer ${this.socket.accessTokenValue}`);const a={method:"POST",headers:s,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:n,private:this.private}]})},o=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(i=r.timeout)!==null&&i!==void 0?i:this.timeout);if(o.status===202)return{success:!0};let l=o.statusText;try{const c=await o.json();l=c.error||c.message||l}catch{}return Promise.reject(new Error(l))}async send(e,n={}){var r,i;if(!this.channelAdapter.canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:s,payload:a}=e,o={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(o.Authorization=`Bearer ${this.socket.accessTokenValue}`);const l={method:"POST",headers:o,body:JSON.stringify({messages:[{topic:this.subTopic,event:s,payload:a,private:this.private}]})};try{const c=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(r=n.timeout)!==null&&r!==void 0?r:this.timeout);return await((i=c.body)===null||i===void 0?void 0:i.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(s=>{var a,o,l;const c=this.channelAdapter.push(e.type,e,n.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(o=(a=this.params)===null||a===void 0?void 0:a.config)===null||o===void 0?void 0:o.broadcast)===null||l===void 0)&&l.ack)&&s("ok"),c.receive("ok",()=>s("ok")),c.receive("error",()=>s("error")),c.receive("timeout",()=>s("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(n=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>n("ok")).receive("timeout",()=>n("timed out")).receive("error",()=>n("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,n,r){const i=new AbortController,s=setTimeout(()=>i.abort(),r),a=await this.socket.fetch(e,Object.assign(Object.assign({},n),{signal:i.signal}));return clearTimeout(s),a}_on(e,n,r){const i=e.toLocaleLowerCase(),s=this.channelAdapter.on(e,r),a={type:i,filter:n,callback:r,ref:s};return this.bindings[i]?this.bindings[i].push(a):this.bindings[i]=[a],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,n,r)=>{var i,s,a,o,l,c,u;const d=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(d,r))return!1;const h=(i=this.bindings[d])===null||i===void 0?void 0:i.find(f=>f.ref===e.ref);if(!h)return!0;if(["broadcast","presence","postgres_changes"].includes(d))if("id"in h){const f=h.id,p=(s=h.filter)===null||s===void 0?void 0:s.event;return f&&((a=n.ids)===null||a===void 0?void 0:a.includes(f))&&(p==="*"||(p==null?void 0:p.toLocaleLowerCase())===((o=n.data)===null||o===void 0?void 0:o.type.toLocaleLowerCase()))}else{const f=(c=(l=h==null?void 0:h.filter)===null||l===void 0?void 0:l.event)===null||c===void 0?void 0:c.toLocaleLowerCase();return f==="*"||f===((u=n==null?void 0:n.event)===null||u===void 0?void 0:u.toLocaleLowerCase())}else return h.type.toLocaleLowerCase()===d})}_notThisChannelEvent(e,n){const{close:r,error:i,leave:s,join:a}=mj;return n&&[r,i,s,a].includes(e)&&n!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,n,r)=>{if(typeof n=="object"&&"ids"in n){const i=n.data,{schema:s,table:a,commit_timestamp:o,type:l,errors:c}=i;return Object.assign(Object.assign({},{schema:s,table:a,commit_timestamp:o,eventType:l,new:{},old:{},errors:c}),this._getPayloadRecords(i))}return n})}copyBindings(e){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(const n in e.bindings)for(const r of e.bindings[n])this._on(r.type,r.filter,r.callback)}static isFilterValueEqual(e,n){return(e??void 0)===(n??void 0)}_getPayloadRecords(e){const n={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(n.new=Ck(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(n.old=Ck(e.columns,e.old_record)),n}}class EZ{constructor(e,n){this.socket=new yZ(e,n)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,n,r,i=1e4){return new Promise(s=>{setTimeout(()=>s("timeout"),i),this.socket.disconnect(()=>{e(),s("ok")},n,r)})}push(e){this.socket.push(e)}log(e,n,r){this.socket.log(e,n,r)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==pE.connecting}isDisconnecting(){return this.socket.connectionState()==pE.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}const wZ={HEARTBEAT_INTERVAL:25e3},TZ=[1e3,2e3,5e3,1e4],AZ=1e4,RZ=`
  addEventListener("message", (e) => {
    if (e.data.event === "start") {
      setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
    }
  });`;class CZ{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,n){var r;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new nZ,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._resolveFetch=s=>s?(...a)=>s(...a):(...a)=>fetch(...a),!(!((r=n==null?void 0:n.params)===null||r===void 0)&&r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=n.params.apikey;const i=this._initializeOptions(n);this.socketAdapter=new EZ(e,i),this.httpEndpoint=yj(e),this.fetch=this._resolveFetch(n==null?void 0:n.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){const n=e.message;throw n.includes("Node.js")?new Error(`${n}

To use Realtime in Node.js, you need to provide a WebSocket implementation:

Option 1: Use Node.js 22+ which has native WebSocket support
Option 2: Install and provide the "ws" package:

  npm install ws

  import ws from "ws"
  const client = new RealtimeClient(url, {
    ...options,
    transport: ws
  })`):new Error(`WebSocket not available: ${n}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,n){return this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,n)}getChannels(){return this.channels}async removeChannel(e){const n=await e.unsubscribe();return n==="ok"&&e.teardown(),this.channels.length===0&&this.disconnect(),n}async removeAllChannels(){const e=this.channels.map(async r=>{const i=await r.unsubscribe();return r.teardown(),i}),n=await Promise.all(e);return this.disconnect(),n}log(e,n,r){this.socketAdapter.log(e,n,r)}connectionState(){return this.socketAdapter.connectionState()||pE.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,n={config:{}}){const r=`realtime:${e}`,i=this.getChannels().find(s=>s.topic===r);if(i)return i;{const s=new Pf(`realtime:${e}`,n,this);return this.channels.push(s),s}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(n=>n.topic!==e.topic)}async _performAuth(e=null){let n,r=!1;if(e)n=e,r=!0;else if(this.accessToken)try{n=await this.accessToken()}catch(i){this.log("error","Error fetching access token from callback",i),n=this.accessTokenValue}else n=this.accessTokenValue;r?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=n&&(this.accessTokenValue=n,this.channels.forEach(i=>{const s={access_token:n,version:QJ};n&&i.updateJoinPayload(s),i.joinedOnce&&i.channelAdapter.isJoined()&&i.channelAdapter.push(mj.access_token,{access_token:n})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(n=>{this.log("error",`Error setting auth in ${e}`,n)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(n=>{this.log("error","error waiting for auth on connect",n)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(n,r)=>{n=="sent"&&this._setAuthSafely(),e&&e(n,r)}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=n=>{this.log("worker","worker error",n.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=n=>{n.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let n;if(e)n=e;else{const r=new Blob([RZ],{type:"application/javascript"});n=URL.createObjectURL(r)}return n}_initializeOptions(e){var n,r,i,s,a,o,l,c,u;this.worker=(n=e==null?void 0:e.worker)!==null&&n!==void 0?n:!1,this.accessToken=(r=e==null?void 0:e.accessToken)!==null&&r!==void 0?r:null;const d={};d.timeout=(i=e==null?void 0:e.timeout)!==null&&i!==void 0?i:eZ,d.heartbeatIntervalMs=(s=e==null?void 0:e.heartbeatIntervalMs)!==null&&s!==void 0?s:wZ.HEARTBEAT_INTERVAL,d.transport=(a=e==null?void 0:e.transport)!==null&&a!==void 0?a:YJ.getWebSocketConstructor(),d.params=e==null?void 0:e.params,d.logger=e==null?void 0:e.logger,d.heartbeatCallback=this._wrapHeartbeatCallback(e==null?void 0:e.heartbeatCallback),d.reconnectAfterMs=(o=e==null?void 0:e.reconnectAfterMs)!==null&&o!==void 0?o:m=>TZ[m-1]||AZ;let h,f;const p=(l=e==null?void 0:e.vsn)!==null&&l!==void 0?l:ZJ;switch(p){case JJ:h=(m,g)=>g(JSON.stringify(m)),f=(m,g)=>g(JSON.parse(m));break;case pj:h=this.serializer.encode.bind(this.serializer),f=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${d.vsn}`)}if(d.vsn=p,d.encode=(c=e==null?void 0:e.encode)!==null&&c!==void 0?c:h,d.decode=(u=e==null?void 0:e.decode)!==null&&u!==void 0?u:f,d.beforeReconnect=this._reconnectAuth.bind(this),(e!=null&&e.logLevel||e!=null&&e.log_level)&&(this.logLevel=e.logLevel||e.log_level,d.params=Object.assign(Object.assign({},d.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e==null?void 0:e.workerUrl,d.autoSendHeartbeat=!this.worker}return d}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}var pp=class extends Error{constructor(t,e){var n;super(t),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&((n=e.icebergType)==null?void 0:n.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function LZ(t,e,n){const r=new URL(e,t);if(n)for(const[i,s]of Object.entries(n))s!==void 0&&r.searchParams.set(i,s);return r.toString()}async function kZ(t){return!t||t.type==="none"?{}:t.type==="bearer"?{Authorization:`Bearer ${t.token}`}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function IZ(t){const e=t.fetchImpl??globalThis.fetch;return{async request({method:n,path:r,query:i,body:s,headers:a}){const o=LZ(t.baseUrl,r,i),l=await kZ(t.auth),c=await e(o,{method:n,headers:{...s?{"Content-Type":"application/json"}:{},...l,...a},body:s?JSON.stringify(s):void 0}),u=await c.text(),d=(c.headers.get("content-type")||"").includes("application/json"),h=d&&u?JSON.parse(u):u;if(!c.ok){const f=d?h:void 0,p=f==null?void 0:f.error;throw new pp((p==null?void 0:p.message)??`Request failed with status ${c.status}`,{status:c.status,icebergType:p==null?void 0:p.type,icebergCode:p==null?void 0:p.code,details:f})}return{status:c.status,headers:c.headers,data:h}}}}function ag(t){return t.join("")}var PZ=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){const e=t?{parent:ag(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(r=>({namespace:r}))}async createNamespace(t,e){const n={namespace:t.namespace,properties:e==null?void 0:e.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:n})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${ag(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ag(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${ag(t.namespace)}`}),!0}catch(e){if(e instanceof pp&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(n){if(n instanceof pp&&n.status===409)return;throw n}}};function uu(t){return t.join("")}var DZ=class{constructor(t,e="",n){this.client=t,this.prefix=e,this.accessDelegation=n}async listTables(t){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${uu(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){const n={};return this.accessDelegation&&(n["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${uu(t.namespace)}/tables`,body:e,headers:n})).data.metadata}async updateTable(t,e){const n=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${uu(t.namespace)}/tables/${t.name}`,body:e});return{"metadata-location":n.data["metadata-location"],metadata:n.data.metadata}}async dropTable(t,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${uu(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String((e==null?void 0:e.purge)??!1)}})}async loadTable(t){const e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${uu(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){const e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${uu(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(n){if(n instanceof pp&&n.status===404)return!1;throw n}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(n){if(n instanceof pp&&n.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw n}}},OZ=class{constructor(t){var r;let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);const n=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=IZ({baseUrl:n,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=(r=t.accessDelegation)==null?void 0:r.join(","),this.namespaceOps=new PZ(this.client,e),this.tableOps=new DZ(this.client,e,this.accessDelegation)}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t)}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e)}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}};function mp(t){"@babel/helpers - typeof";return mp=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},mp(t)}function NZ(t,e){if(mp(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(mp(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function MZ(t){var e=NZ(t,"string");return mp(e)=="symbol"?e:e+""}function BZ(t,e,n){return(e=MZ(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Pk(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function _t(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Pk(Object(n),!0).forEach(function(r){BZ(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Pk(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}var gv=class extends Error{constructor(t,e="storage",n,r){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=n,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};function yv(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var vE=class extends gv{constructor(t,e,n,r="storage"){super(t,r,e,n),this.name=r==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=n}toJSON(){return _t({},super.toJSON())}},_j=class extends gv{constructor(t,e,n="storage"){super(t,n),this.name=n==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};function dA(t,e,n){const r=_t({},t),i=e.toLowerCase();for(const s of Object.keys(r))s.toLowerCase()===i&&delete r[s];return r[i]=n,r}function UZ(t){const e={};for(const[n,r]of Object.entries(t))e[n.toLowerCase()]=r;return e}const jZ=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),FZ=t=>{if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},_E=t=>{if(Array.isArray(t))return t.map(n=>_E(n));if(typeof t=="function"||t!==Object(t))return t;const e={};return Object.entries(t).forEach(([n,r])=>{const i=n.replace(/([-_][a-z])/gi,s=>s.toUpperCase().replace(/[-_]/g,""));e[i]=_E(r)}),e},$Z=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t),Dk=t=>{var e;return t.msg||t.message||t.error_description||(typeof t.error=="string"?t.error:(e=t.error)===null||e===void 0?void 0:e.message)||JSON.stringify(t)},VZ=async(t,e,n,r)=>{if(t!==null&&typeof t=="object"&&typeof t.json=="function"){const i=t;let s=parseInt(i.status,10);Number.isFinite(s)||(s=500),i.json().then(a=>{const o=(a==null?void 0:a.statusCode)||(a==null?void 0:a.code)||s+"";e(new vE(Dk(a),s,o,r))}).catch(()=>{const a=s+"";e(new vE(i.statusText||`HTTP ${s} error`,s,a,r))})}else e(new _j(Dk(t),t,r))},GZ=(t,e,n,r)=>{const i={method:t,headers:(e==null?void 0:e.headers)||{}};if(t==="GET"||t==="HEAD"||!r)return _t(_t({},i),n);if(FZ(r)){var s;const a=(e==null?void 0:e.headers)||{};let o;for(const[l,c]of Object.entries(a))l.toLowerCase()==="content-type"&&(o=c);i.headers=dA(a,"Content-Type",(s=o)!==null&&s!==void 0?s:"application/json"),i.body=JSON.stringify(r)}else i.body=r;return e!=null&&e.duplex&&(i.duplex=e.duplex),_t(_t({},i),n)};async function Gh(t,e,n,r,i,s,a){return new Promise((o,l)=>{t(n,GZ(e,r,i,s)).then(c=>{if(!c.ok)throw c;if(r!=null&&r.noResolveJson)return c;if(a==="vectors"){const u=c.headers.get("content-type");if(c.headers.get("content-length")==="0"||c.status===204)return{};if(!u||!u.includes("application/json"))return{}}return c.json()}).then(c=>o(c)).catch(c=>VZ(c,l,r,a))})}function bj(t="storage"){return{get:async(e,n,r,i)=>Gh(e,"GET",n,r,i,void 0,t),post:async(e,n,r,i,s)=>Gh(e,"POST",n,i,s,r,t),put:async(e,n,r,i,s)=>Gh(e,"PUT",n,i,s,r,t),head:async(e,n,r,i)=>Gh(e,"HEAD",n,_t(_t({},r),{},{noResolveJson:!0}),i,void 0,t),remove:async(e,n,r,i,s)=>Gh(e,"DELETE",n,i,s,r,t)}}const HZ=bj("storage"),{get:gp,post:Cs,put:bE,head:KZ,remove:hA}=HZ,Ui=bj("vectors");var Sh=class{constructor(t,e={},n,r="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=UZ(e),this.fetch=jZ(n),this.namespace=r}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=dA(this.headers,t,e),this}async handleOperation(t){var e=this;try{return{data:await t(),error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(yv(n))return{data:null,error:n};throw n}}},zZ=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e}then(t,e){return this.execute().then(t,e)}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(yv(e))return{data:null,error:e};throw e}}};let xj;xj=Symbol.toStringTag;var qZ=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[xj]="BlobDownloadBuilder",this.promise=null}asStream(){return new zZ(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(yv(e))return{data:null,error:e};throw e}}};const WZ={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Ok={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var YZ=class extends Sh{constructor(t,e={},n,r){super(t,e,r,"storage"),this.bucketId=n}async uploadOrUpdate(t,e,n,r){var i=this;return i.handleOperation(async()=>{let s;const a=_t(_t({},Ok),r);let o=_t(_t({},i.headers),t==="POST"&&{"x-upsert":String(a.upsert)});const l=a.metadata;if(typeof Blob<"u"&&n instanceof Blob?(s=new FormData,s.append("cacheControl",a.cacheControl),l&&s.append("metadata",i.encodeMetadata(l)),s.append("",n)):typeof FormData<"u"&&n instanceof FormData?(s=n,s.has("cacheControl")||s.append("cacheControl",a.cacheControl),l&&!s.has("metadata")&&s.append("metadata",i.encodeMetadata(l))):(s=n,o["cache-control"]=`max-age=${a.cacheControl}`,o["content-type"]=a.contentType,l&&(o["x-metadata"]=i.toBase64(i.encodeMetadata(l))),(typeof ReadableStream<"u"&&s instanceof ReadableStream||s&&typeof s=="object"&&"pipe"in s&&typeof s.pipe=="function")&&!a.duplex&&(a.duplex="half")),r!=null&&r.headers)for(const[h,f]of Object.entries(r.headers))o=dA(o,h,f);const c=i._removeEmptyFolders(e),u=i._getFinalPath(c),d=await(t=="PUT"?bE:Cs)(i.fetch,`${i.url}/object/${u}`,s,_t({headers:o},a!=null&&a.duplex?{duplex:a.duplex}:{}));return{path:c,id:d.Id,fullPath:d.Key}})}async upload(t,e,n){return this.uploadOrUpdate("POST",t,e,n)}async uploadToSignedUrl(t,e,n,r){var i=this;const s=i._removeEmptyFolders(t),a=i._getFinalPath(s),o=new URL(i.url+`/object/upload/sign/${a}`);return o.searchParams.set("token",e),i.handleOperation(async()=>{let l;const c=_t(_t({},Ok),r),u=_t(_t({},i.headers),{"x-upsert":String(c.upsert)});return typeof Blob<"u"&&n instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",n)):typeof FormData<"u"&&n instanceof FormData?(l=n,l.append("cacheControl",c.cacheControl)):(l=n,u["cache-control"]=`max-age=${c.cacheControl}`,u["content-type"]=c.contentType),{path:s,fullPath:(await bE(i.fetch,o.toString(),l,{headers:u})).Key}})}async createSignedUploadUrl(t,e){var n=this;return n.handleOperation(async()=>{let r=n._getFinalPath(t);const i=_t({},n.headers);e!=null&&e.upsert&&(i["x-upsert"]="true");const s=await Cs(n.fetch,`${n.url}/object/upload/sign/${r}`,{},{headers:i}),a=new URL(n.url+s.url),o=a.searchParams.get("token");if(!o)throw new gv("No token returned by API");return{signedUrl:a.toString(),path:t,token:o}})}async update(t,e,n){return this.uploadOrUpdate("PUT",t,e,n)}async move(t,e,n){var r=this;return r.handleOperation(async()=>await Cs(r.fetch,`${r.url}/object/move`,{bucketId:r.bucketId,sourceKey:t,destinationKey:e,destinationBucket:n==null?void 0:n.destinationBucket},{headers:r.headers}))}async copy(t,e,n){var r=this;return r.handleOperation(async()=>({path:(await Cs(r.fetch,`${r.url}/object/copy`,{bucketId:r.bucketId,sourceKey:t,destinationKey:e,destinationBucket:n==null?void 0:n.destinationBucket},{headers:r.headers})).Key}))}async createSignedUrl(t,e,n){var r=this;return r.handleOperation(async()=>{let i=r._getFinalPath(t);const s=typeof(n==null?void 0:n.transform)=="object"&&n.transform!==null&&Object.keys(n.transform).length>0;let a=await Cs(r.fetch,`${r.url}/object/sign/${i}`,_t({expiresIn:e},s?{transform:n.transform}:{}),{headers:r.headers});const o=new URLSearchParams;n!=null&&n.download&&o.set("download",n.download===!0?"":n.download),(n==null?void 0:n.cacheNonce)!=null&&o.set("cacheNonce",String(n.cacheNonce));const l=o.toString();return{signedUrl:encodeURI(`${r.url}${a.signedURL}${l?`&${l}`:""}`)}})}async createSignedUrls(t,e,n){var r=this;return r.handleOperation(async()=>{const i=await Cs(r.fetch,`${r.url}/object/sign/${r.bucketId}`,{expiresIn:e,paths:t},{headers:r.headers}),s=new URLSearchParams;n!=null&&n.download&&s.set("download",n.download===!0?"":n.download),(n==null?void 0:n.cacheNonce)!=null&&s.set("cacheNonce",String(n.cacheNonce));const a=s.toString();return i.map(o=>_t(_t({},o),{},{signedUrl:o.signedURL?encodeURI(`${r.url}${o.signedURL}${a?`&${a}`:""}`):null}))})}download(t,e,n){const r=typeof(e==null?void 0:e.transform)=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image/authenticated":"object",i=new URLSearchParams;e!=null&&e.transform&&this.applyTransformOptsToQuery(i,e.transform),(e==null?void 0:e.cacheNonce)!=null&&i.set("cacheNonce",String(e.cacheNonce));const s=i.toString(),a=this._getFinalPath(t),o=()=>gp(this.fetch,`${this.url}/${r}/${a}${s?`?${s}`:""}`,{headers:this.headers,noResolveJson:!0},n);return new qZ(o,this.shouldThrowOnError)}async info(t){var e=this;const n=e._getFinalPath(t);return e.handleOperation(async()=>_E(await gp(e.fetch,`${e.url}/object/info/${n}`,{headers:e.headers})))}async exists(t){var e=this;const n=e._getFinalPath(t);try{return await KZ(e.fetch,`${e.url}/object/${n}`,{headers:e.headers}),{data:!0,error:null}}catch(i){if(e.shouldThrowOnError)throw i;if(yv(i)){var r;const s=i instanceof vE?i.status:i instanceof _j?(r=i.originalError)===null||r===void 0?void 0:r.status:void 0;if(s!==void 0&&[400,404].includes(s))return{data:!1,error:i}}throw i}}getPublicUrl(t,e){const n=this._getFinalPath(t),r=new URLSearchParams;e!=null&&e.download&&r.set("download",e.download===!0?"":e.download),e!=null&&e.transform&&this.applyTransformOptsToQuery(r,e.transform),(e==null?void 0:e.cacheNonce)!=null&&r.set("cacheNonce",String(e.cacheNonce));const i=r.toString(),s=typeof(e==null?void 0:e.transform)=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${s}/public/${n}`)+(i?`?${i}`:"")}}}async remove(t){var e=this;return e.handleOperation(async()=>await hA(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,n){var r=this;return r.handleOperation(async()=>{const i=_t(_t(_t({},WZ),e),{},{prefix:t||""});return await Cs(r.fetch,`${r.url}/object/list/${r.bucketId}`,i,{headers:r.headers},n)})}async listV2(t,e){var n=this;return n.handleOperation(async()=>{const r=_t({},t);return await Cs(n.fetch,`${n.url}/object/list-v2/${n.bucketId}`,r,{headers:n.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(t,e){return e.width&&t.set("width",e.width.toString()),e.height&&t.set("height",e.height.toString()),e.resize&&t.set("resize",e.resize),e.format&&t.set("format",e.format),e.quality&&t.set("quality",e.quality.toString()),t}};const XZ="2.104.1",lm={"X-Client-Info":`storage-js/${XZ}`};var QZ=class extends Sh{constructor(t,e={},n,r){const i=new URL(t);r!=null&&r.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase."));const s=i.href.replace(/\/$/,""),a=_t(_t({},lm),e);super(s,a,n,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const n=e.listBucketOptionsToQueryString(t);return await gp(e.fetch,`${e.url}/bucket${n}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await gp(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var n=this;return n.handleOperation(async()=>await Cs(n.fetch,`${n.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:n.headers}))}async updateBucket(t,e){var n=this;return n.handleOperation(async()=>await bE(n.fetch,`${n.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:n.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await Cs(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await hA(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(t){const e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},JZ=class extends Sh{constructor(t,e={},n){const r=t.replace(/\/$/,""),i=_t(_t({},lm),e);super(r,i,n,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Cs(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const n=new URLSearchParams;(t==null?void 0:t.limit)!==void 0&&n.set("limit",t.limit.toString()),(t==null?void 0:t.offset)!==void 0&&n.set("offset",t.offset.toString()),t!=null&&t.sortColumn&&n.set("sortColumn",t.sortColumn),t!=null&&t.sortOrder&&n.set("sortOrder",t.sortOrder),t!=null&&t.search&&n.set("search",t.search);const r=n.toString(),i=r?`${e.url}/bucket?${r}`:`${e.url}/bucket`;return await gp(e.fetch,i,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await hA(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!$Z(t))throw new gv("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const n=new OZ({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),r=this.shouldThrowOnError;return new Proxy(n,{get(i,s){const a=i[s];return typeof a!="function"?a:async(...o)=>{try{return{data:await a.apply(i,o),error:null}}catch(l){if(r)throw l;return{data:null,error:l}}}}})}},ZZ=class extends Sh{constructor(t,e={},n){const r=t.replace(/\/$/,""),i=_t(_t({},lm),{},{"Content-Type":"application/json"},e);super(r,i,n,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await Ui.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var n=this;return n.handleOperation(async()=>await Ui.post(n.fetch,`${n.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:n.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await Ui.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var n=this;return n.handleOperation(async()=>await Ui.post(n.fetch,`${n.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:n.headers})||{})}},eee=class extends Sh{constructor(t,e={},n){const r=t.replace(/\/$/,""),i=_t(_t({},lm),{},{"Content-Type":"application/json"},e);super(r,i,n,"vectors")}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await Ui.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await Ui.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await Ui.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await Ui.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await Ui.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},tee=class extends Sh{constructor(t,e={},n){const r=t.replace(/\/$/,""),i=_t(_t({},lm),{},{"Content-Type":"application/json"},e);super(r,i,n,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Ui.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Ui.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await Ui.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ui.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},nee=class extends tee{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new ree(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,n=this;return e().call(n,t)}async getBucket(t){var e=()=>super.getBucket,n=this;return e().call(n,t)}async listBuckets(t={}){var e=()=>super.listBuckets,n=this;return e().call(n,t)}async deleteBucket(t){var e=()=>super.deleteBucket,n=this;return e().call(n,t)}},ree=class extends ZZ{constructor(t,e,n,r){super(t,e,r),this.vectorBucketName=n}async createIndex(t){var e=()=>super.createIndex,n=this;return e().call(n,_t(_t({},t),{},{vectorBucketName:n.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,n=this;return e().call(n,_t(_t({},t),{},{vectorBucketName:n.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,n=this;return e().call(n,n.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,n=this;return e().call(n,n.vectorBucketName,t)}index(t){return new iee(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},iee=class extends eee{constructor(t,e,n,r,i){super(t,e,i),this.vectorBucketName=n,this.indexName=r}async putVectors(t){var e=()=>super.putVectors,n=this;return e().call(n,_t(_t({},t),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async getVectors(t){var e=()=>super.getVectors,n=this;return e().call(n,_t(_t({},t),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,n=this;return e().call(n,_t(_t({},t),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,n=this;return e().call(n,_t(_t({},t),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,n=this;return e().call(n,_t(_t({},t),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}},see=class extends QZ{constructor(t,e={},n,r){super(t,e,n,r)}from(t){return new YZ(this.url,this.headers,t,this.fetch)}get vectors(){return new nee(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new JZ(this.url+"/iceberg",this.headers,this.fetch)}};const Sj="2.104.1",Nu=30*1e3,xE=3,mb=xE*Nu,aee="http://localhost:9999",oee="supabase.auth.token",lee={"X-Client-Info":`gotrue-js/${Sj}`},SE="X-Supabase-Api-Version",Ej={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},cee=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,uee=10*60*1e3;class yp extends Error{constructor(e,n,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=r}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}}function ot(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class dee extends yp{constructor(e,n,r){super(e,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function hee(t){return ot(t)&&t.name==="AuthApiError"}class nc extends yp{constructor(e,n){super(e),this.name="AuthUnknownError",this.originalError=n}}class go extends yp{constructor(e,n,r,i){super(e,r,i),this.name=n,this.status=r}}class Ri extends go{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function og(t){return ot(t)&&t.name==="AuthSessionMissingError"}class du extends go{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class lg extends go{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class cg extends go{constructor(e,n=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=n}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}function fee(t){return ot(t)&&t.name==="AuthImplicitGrantRedirectError"}class Nk extends go{constructor(e,n=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=n}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}class pee extends go{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class EE extends go{constructor(e,n){super(e,"AuthRetryableFetchError",n,void 0)}}function gb(t){return ot(t)&&t.name==="AuthRetryableFetchError"}class Mk extends go{constructor(e,n,r){super(e,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}}class wE extends go{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const h0="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Bk=` 	
\r=`.split(""),mee=(()=>{const t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<Bk.length;e+=1)t[Bk[e].charCodeAt(0)]=-2;for(let e=0;e<h0.length;e+=1)t[h0[e].charCodeAt(0)]=e;return t})();function Uk(t,e,n){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){const r=e.queue>>e.queuedBits-6&63;n(h0[r]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const r=e.queue>>e.queuedBits-6&63;n(h0[r]),e.queuedBits-=6}}function wj(t,e,n){const r=mee[t];if(r>-1)for(e.queue=e.queue<<6|r,e.queuedBits+=6;e.queuedBits>=8;)n(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(r===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function jk(t){const e=[],n=a=>{e.push(String.fromCodePoint(a))},r={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},s=a=>{vee(a,r,n)};for(let a=0;a<t.length;a+=1)wj(t.charCodeAt(a),i,s);return e.join("")}function gee(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function yee(t,e){for(let n=0;n<t.length;n+=1){let r=t.charCodeAt(n);if(r>55295&&r<=56319){const i=(r-55296)*1024&65535;r=(t.charCodeAt(n+1)-56320&65535|i)+65536,n+=1}gee(r,e)}}function vee(t,e,n){if(e.utf8seq===0){if(t<=127){n(t);return}for(let r=1;r<6;r+=1)if(!(t>>7-r&1)){e.utf8seq=r;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&n(e.codepoint)}}function gd(t){const e=[],n={queue:0,queuedBits:0},r=i=>{e.push(i)};for(let i=0;i<t.length;i+=1)wj(t.charCodeAt(i),n,r);return new Uint8Array(e)}function _ee(t){const e=[];return yee(t,n=>e.push(n)),new Uint8Array(e)}function lc(t){const e=[],n={queue:0,queuedBits:0},r=i=>{e.push(i)};return t.forEach(i=>Uk(i,n,r)),Uk(null,n,r),e.join("")}function bee(t){return Math.round(Date.now()/1e3)+t}function xee(){return Symbol("auth-callback")}const Lr=()=>typeof window<"u"&&typeof document<"u",Hl={tested:!1,writable:!1},Tj=()=>{if(!Lr())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Hl.tested)return Hl.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),Hl.tested=!0,Hl.writable=!0}catch{Hl.tested=!0,Hl.writable=!1}return Hl.writable};function See(t){const e={},n=new URL(t);if(n.hash&&n.hash[0]==="#")try{new URLSearchParams(n.hash.substring(1)).forEach((i,s)=>{e[s]=i})}catch{}return n.searchParams.forEach((r,i)=>{e[i]=r}),e}const Aj=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Eee=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Mu=async(t,e,n)=>{await t.setItem(e,JSON.stringify(n))},Kl=async(t,e)=>{const n=await t.getItem(e);if(!n)return null;try{return JSON.parse(n)}catch{return n}},Cr=async(t,e)=>{await t.removeItem(e)};class vv{constructor(){this.promise=new vv.promiseConstructor((e,n)=>{this.resolve=e,this.reject=n})}}vv.promiseConstructor=Promise;function ug(t){const e=t.split(".");if(e.length!==3)throw new wE("Invalid JWT structure");for(let r=0;r<e.length;r++)if(!cee.test(e[r]))throw new wE("JWT not in base64url format");return{header:JSON.parse(jk(e[0])),payload:JSON.parse(jk(e[1])),signature:gd(e[2]),raw:{header:e[0],payload:e[1]}}}async function wee(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function Tee(t,e){return new Promise((r,i)=>{(async()=>{for(let s=0;s<1/0;s++)try{const a=await t(s);if(!e(s,null,a)){r(a);return}}catch(a){if(!e(s,a)){i(a);return}}})()})}function Aee(t){return("0"+t.toString(16)).substr(-2)}function Ree(){const e=new Uint32Array(56);if(typeof crypto>"u"){const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=n.length;let i="";for(let s=0;s<56;s++)i+=n.charAt(Math.floor(Math.random()*r));return i}return crypto.getRandomValues(e),Array.from(e,Aee).join("")}async function Cee(t){const n=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",n),i=new Uint8Array(r);return Array.from(i).map(s=>String.fromCharCode(s)).join("")}async function Lee(t){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;const n=await Cee(t);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function hu(t,e,n=!1){const r=Ree();let i=r;n&&(i+="/recovery"),await Mu(t,`${e}-code-verifier`,i);const s=await Lee(r);return[s,r===s?"plain":"s256"]}const kee=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Iee(t){const e=t.headers.get(SE);if(!e||!e.match(kee))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Pee(t){if(!t)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function Dee(t){switch(t){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const Oee=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function fu(t){if(!Oee.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function yb(){const t={};return new Proxy(t,{get:(e,n)=>{if(n==="__isUserNotAvailableProxy")return!0;if(typeof n=="symbol"){const r=n.toString();if(r==="Symbol(Symbol.toPrimitive)"||r==="Symbol(Symbol.toStringTag)"||r==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${n}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,n)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${n}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,n)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${n}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Nee(t,e){return new Proxy(t,{get:(n,r,i)=>{if(r==="__isInsecureUserWarningProxy")return!0;if(typeof r=="symbol"){const s=r.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)"||s==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(n,r,i)}return!e.value&&typeof r=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(n,r,i)}})}function Fk(t){return JSON.parse(JSON.stringify(t))}const Zl=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),Mee=[502,503,504,520,521,522,523,524,530];async function $k(t){var e;if(!Eee(t))throw new EE(Zl(t),0);if(Mee.includes(t.status))throw new EE(Zl(t),t.status);let n;try{n=await t.json()}catch(s){throw new nc(Zl(s),s)}let r;const i=Iee(t);if(i&&i.getTime()>=Ej["2024-01-01"].timestamp&&typeof n=="object"&&n&&typeof n.code=="string"?r=n.code:typeof n=="object"&&n&&typeof n.error_code=="string"&&(r=n.error_code),r){if(r==="weak_password")throw new Mk(Zl(n),t.status,((e=n.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(r==="session_not_found")throw new Ri}else if(typeof n=="object"&&n&&typeof n.weak_password=="object"&&n.weak_password&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.reasons.reduce((s,a)=>s&&typeof a=="string",!0))throw new Mk(Zl(n),t.status,n.weak_password.reasons);throw new dee(Zl(n),t.status||500,r)}const Bee=(t,e,n,r)=>{const i={method:t,headers:(e==null?void 0:e.headers)||{}};return t==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),n))};async function ft(t,e,n,r){var i;const s=Object.assign({},r==null?void 0:r.headers);s[SE]||(s[SE]=Ej["2024-01-01"].name),r!=null&&r.jwt&&(s.Authorization=`Bearer ${r.jwt}`);const a=(i=r==null?void 0:r.query)!==null&&i!==void 0?i:{};r!=null&&r.redirectTo&&(a.redirect_to=r.redirectTo);const o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",l=await Uee(t,e,n+o,{headers:s,noResolveJson:r==null?void 0:r.noResolveJson},{},r==null?void 0:r.body);return r!=null&&r.xform?r==null?void 0:r.xform(l):{data:Object.assign({},l),error:null}}async function Uee(t,e,n,r,i,s){const a=Bee(e,r,i,s);let o;try{o=await t(n,Object.assign({},a))}catch(l){throw console.error(l),new EE(Zl(l),0)}if(o.ok||await $k(o),r!=null&&r.noResolveJson)return o;try{return await o.json()}catch(l){await $k(l)}}function Ts(t){var e;let n=null;$ee(t)&&(n=Object.assign({},t),t.expires_at||(n.expires_at=bee(t.expires_in)));const r=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:n,user:r},error:null}}function Vk(t){const e=Ts(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((n,r)=>n&&typeof r=="string",!0)&&(e.data.weak_password=t.weak_password),e}function Ho(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function jee(t){return{data:t,error:null}}function Fee(t){const{action_link:e,email_otp:n,hashed_token:r,redirect_to:i,verification_type:s}=t,a=xh(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o={action_link:e,email_otp:n,hashed_token:r,redirect_to:i,verification_type:s},l=Object.assign({},a);return{data:{properties:o,user:l},error:null}}function Gk(t){return t}function $ee(t){return t.access_token&&t.refresh_token&&t.expires_in}const vb=["global","local","others"];class Vee{constructor({url:e="",headers:n={},fetch:r}){this.url=e,this.headers=n,this.fetch=Aj(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)}}async signOut(e,n=vb[0]){if(vb.indexOf(n)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${vb.join(", ")}`);try{return await ft(this.fetch,"POST",`${this.url}/logout?scope=${n}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(ot(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,n={}){try{return await ft(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:n.data},headers:this.headers,redirectTo:n.redirectTo,xform:Ho})}catch(r){if(ot(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{const{options:n}=e,r=xh(e,["options"]),i=Object.assign(Object.assign({},r),n);return"newEmail"in r&&(i.new_email=r==null?void 0:r.newEmail,delete i.newEmail),await ft(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:Fee,redirectTo:n==null?void 0:n.redirectTo})}catch(n){if(ot(n))return{data:{properties:null,user:null},error:n};throw n}}async createUser(e){try{return await ft(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Ho})}catch(n){if(ot(n))return{data:{user:null},error:n};throw n}}async listUsers(e){var n,r,i,s,a,o,l;try{const c={nextPage:null,lastPage:0,total:0},u=await ft(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(n=e==null?void 0:e.page)===null||n===void 0?void 0:n.toString())!==null&&r!==void 0?r:"",per_page:(s=(i=e==null?void 0:e.perPage)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""},xform:Gk});if(u.error)throw u.error;const d=await u.json(),h=(a=u.headers.get("x-total-count"))!==null&&a!==void 0?a:0,f=(l=(o=u.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&l!==void 0?l:[];return f.length>0&&(f.forEach(p=>{const m=parseInt(p.split(";")[0].split("=")[1].substring(0,1)),g=JSON.parse(p.split(";")[1].split("=")[1]);c[`${g}Page`]=m}),c.total=parseInt(h)),{data:Object.assign(Object.assign({},d),c),error:null}}catch(c){if(ot(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){fu(e);try{return await ft(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Ho})}catch(n){if(ot(n))return{data:{user:null},error:n};throw n}}async updateUserById(e,n){fu(e);try{return await ft(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:n,headers:this.headers,xform:Ho})}catch(r){if(ot(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,n=!1){fu(e);try{return await ft(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:n},xform:Ho})}catch(r){if(ot(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){fu(e.userId);try{const{data:n,error:r}=await ft(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:n,error:r}}catch(n){if(ot(n))return{data:null,error:n};throw n}}async _deleteFactor(e){fu(e.userId),fu(e.id);try{return{data:await ft(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(n){if(ot(n))return{data:null,error:n};throw n}}async _listOAuthClients(e){var n,r,i,s,a,o,l;try{const c={nextPage:null,lastPage:0,total:0},u=await ft(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(n=e==null?void 0:e.page)===null||n===void 0?void 0:n.toString())!==null&&r!==void 0?r:"",per_page:(s=(i=e==null?void 0:e.perPage)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""},xform:Gk});if(u.error)throw u.error;const d=await u.json(),h=(a=u.headers.get("x-total-count"))!==null&&a!==void 0?a:0,f=(l=(o=u.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&l!==void 0?l:[];return f.length>0&&(f.forEach(p=>{const m=parseInt(p.split(";")[0].split("=")[1].substring(0,1)),g=JSON.parse(p.split(";")[1].split("=")[1]);c[`${g}Page`]=m}),c.total=parseInt(h)),{data:Object.assign(Object.assign({},d),c),error:null}}catch(c){if(ot(c))return{data:{clients:[]},error:c};throw c}}async _createOAuthClient(e){try{return await ft(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(ot(n))return{data:null,error:n};throw n}}async _getOAuthClient(e){try{return await ft(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(ot(n))return{data:null,error:n};throw n}}async _updateOAuthClient(e,n){try{return await ft(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:n,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(ot(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(e){try{return await ft(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(n){if(ot(n))return{data:null,error:n};throw n}}async _regenerateOAuthClientSecret(e){try{return await ft(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(ot(n))return{data:null,error:n};throw n}}async _listCustomProviders(e){try{const n={};return e!=null&&e.type&&(n.type=e.type),await ft(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:n,xform:r=>{var i;return{data:{providers:(i=r==null?void 0:r.providers)!==null&&i!==void 0?i:[]},error:null}}})}catch(n){if(ot(n))return{data:{providers:[]},error:n};throw n}}async _createCustomProvider(e){try{return await ft(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(ot(n))return{data:null,error:n};throw n}}async _getCustomProvider(e){try{return await ft(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(ot(n))return{data:null,error:n};throw n}}async _updateCustomProvider(e,n){try{return await ft(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:n,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(ot(r))return{data:null,error:r};throw r}}async _deleteCustomProvider(e){try{return await ft(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(n){if(ot(n))return{data:null,error:n};throw n}}}function Hk(t={}){return{getItem:e=>t[e]||null,setItem:(e,n)=>{t[e]=n},removeItem:e=>{delete t[e]}}}const Vs={debug:!!(globalThis&&Tj()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class Rj extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Kk extends Rj{}async function Gee(t,e,n){Vs.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);const r=new globalThis.AbortController;let i;e>0&&(i=setTimeout(()=>{r.abort(),Vs.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e)),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async s=>{if(s){clearTimeout(i),Vs.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,s.name);try{return await n()}finally{Vs.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,s.name)}}else{if(e===0)throw Vs.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new Kk(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(Vs.debug)try{const a=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(a,null,"  "))}catch(a){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",a)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),clearTimeout(i),await n()}})}catch(s){if(e>0&&clearTimeout(i),(s==null?void 0:s.name)==="AbortError"&&e>0){if(r.signal.aborted)return Vs.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,{mode:"exclusive",steal:!0},async a=>{if(a){Vs.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,a.name);try{return await n()}finally{Vs.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,a.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await n()}));throw Vs.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new Kk(`Lock "${t}" was released because another request stole it`)}throw s}}function Hee(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function Cj(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function Kee(t){return parseInt(t,16)}function zee(t){const e=new TextEncoder().encode(t);return"0x"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}function qee(t){var e;const{chainId:n,domain:r,expirationTime:i,issuedAt:s=new Date,nonce:a,notBefore:o,requestId:l,resources:c,scheme:u,uri:d,version:h}=t;{if(!Number.isInteger(n))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${n}`);if(!r)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!d)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(h!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${h}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}const f=Cj(t.address),p=u?`${u}://${r}`:r,m=t.statement?`${t.statement}
`:"",g=`${p} wants you to sign in with your Ethereum account:
${f}

${m}`;let b=`URI: ${d}
Version: ${h}
Chain ID: ${n}${a?`
Nonce: ${a}`:""}
Issued At: ${s.toISOString()}`;if(i&&(b+=`
Expiration Time: ${i.toISOString()}`),o&&(b+=`
Not Before: ${o.toISOString()}`),l&&(b+=`
Request ID: ${l}`),c){let v=`
Resources:`;for(const S of c){if(!S||typeof S!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${S}`);v+=`
- ${S}`}b+=v}return`${g}
${b}`}class nr extends Error{constructor({message:e,code:n,cause:r,name:i}){var s;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=(s=i??(r instanceof Error?r.name:void 0))!==null&&s!==void 0?s:"Unknown Error",this.code=n}}class f0 extends nr{constructor(e,n){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n,message:e}),this.name="WebAuthnUnknownError",this.originalError=n}}function Wee({error:t,options:e}){var n,r,i;const{publicKey:s}=e;if(!s)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new nr({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((n=s.authenticatorSelection)===null||n===void 0?void 0:n.requireResidentKey)===!0)return new nr({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((r=s.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new nr({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((i=s.authenticatorSelection)===null||i===void 0?void 0:i.userVerification)==="required")return new nr({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new nr({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new nr({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return s.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new nr({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new nr({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){const a=window.location.hostname;if(Lj(a)){if(s.rp.id!==a)return new nr({message:`The RP ID "${s.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new nr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(s.user.id.byteLength<1||s.user.id.byteLength>64)return new nr({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new nr({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new nr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Yee({error:t,options:e}){const{publicKey:n}=e;if(!n)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new nr({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new nr({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const r=window.location.hostname;if(Lj(r)){if(n.rpId!==r)return new nr({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new nr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new nr({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new nr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}class Xee{createNewAbortSignal(){if(this.controller){const n=new Error("Cancelling existing WebAuthn API call for new one");n.name="AbortError",this.controller.abort(n)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const Qee=new Xee;function Jee(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);const{challenge:e,user:n,excludeCredentials:r}=t,i=xh(t,["challenge","user","excludeCredentials"]),s=gd(e).buffer,a=Object.assign(Object.assign({},n),{id:gd(n.id).buffer}),o=Object.assign(Object.assign({},i),{challenge:s,user:a});if(r&&r.length>0){o.excludeCredentials=new Array(r.length);for(let l=0;l<r.length;l++){const c=r[l];o.excludeCredentials[l]=Object.assign(Object.assign({},c),{id:gd(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return o}function Zee(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);const{challenge:e,allowCredentials:n}=t,r=xh(t,["challenge","allowCredentials"]),i=gd(e).buffer,s=Object.assign(Object.assign({},r),{challenge:i});if(n&&n.length>0){s.allowCredentials=new Array(n.length);for(let a=0;a<n.length;a++){const o=n[a];s.allowCredentials[a]=Object.assign(Object.assign({},o),{id:gd(o.id).buffer,type:o.type||"public-key",transports:o.transports})}}return s}function ete(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const n=t;return{id:t.id,rawId:t.id,response:{attestationObject:lc(new Uint8Array(t.response.attestationObject)),clientDataJSON:lc(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=n.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function tte(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const n=t,r=t.getClientExtensionResults(),i=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:lc(new Uint8Array(i.authenticatorData)),clientDataJSON:lc(new Uint8Array(i.clientDataJSON)),signature:lc(new Uint8Array(i.signature)),userHandle:i.userHandle?lc(new Uint8Array(i.userHandle)):void 0},type:"public-key",clientExtensionResults:r,authenticatorAttachment:(e=n.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Lj(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function zk(){var t,e;return!!(Lr()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator==null?void 0:navigator.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.get)=="function")}async function nte(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new f0("Browser returned unexpected credential type",e)}:{data:null,error:new f0("Empty credential response",e)}}catch(e){return{data:null,error:Wee({error:e,options:t})}}}async function rte(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new f0("Browser returned unexpected credential type",e)}:{data:null,error:new f0("Empty credential response",e)}}catch(e){return{data:null,error:Yee({error:e,options:t})}}}const ite={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},ste={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function p0(...t){const e=i=>i!==null&&typeof i=="object"&&!Array.isArray(i),n=i=>i instanceof ArrayBuffer||ArrayBuffer.isView(i),r={};for(const i of t)if(i)for(const s in i){const a=i[s];if(a!==void 0)if(Array.isArray(a))r[s]=a;else if(n(a))r[s]=a;else if(e(a)){const o=r[s];e(o)?r[s]=p0(o,a):r[s]=p0(a)}else r[s]=a}return r}function ate(t,e){return p0(ite,t,e||{})}function ote(t,e){return p0(ste,t,e||{})}class lte{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:n,friendlyName:r,signal:i},s){var a;try{const{data:o,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:n});if(!o)return{data:null,error:l};const c=i??Qee.createNewAbortSignal();if(o.webauthn.type==="create"){const{user:u}=o.webauthn.credential_options.publicKey;if(!u.name){const d=r;if(d)u.name=`${u.id}:${d}`;else{const f=(await this.client.getUser()).data.user,p=((a=f==null?void 0:f.user_metadata)===null||a===void 0?void 0:a.name)||(f==null?void 0:f.email)||(f==null?void 0:f.id)||"User";u.name=`${u.id}:${p}`}}u.displayName||(u.displayName=u.name)}switch(o.webauthn.type){case"create":{const u=ate(o.webauthn.credential_options.publicKey,s==null?void 0:s.create),{data:d,error:h}=await nte({publicKey:u,signal:c});return d?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:d}},error:null}:{data:null,error:h}}case"request":{const u=ote(o.webauthn.credential_options.publicKey,s==null?void 0:s.request),{data:d,error:h}=await rte(Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:u,signal:c}));return d?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:d}},error:null}:{data:null,error:h}}}}catch(o){return ot(o)?{data:null,error:o}:{data:null,error:new nc("Unexpected error in challenge",o)}}}async _verify({challengeId:e,factorId:n,webauthn:r}){return this.client.mfa.verify({factorId:n,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:n=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},s){if(!n)return{data:null,error:new yp("rpId is required for WebAuthn authentication")};try{if(!zk())return{data:null,error:new nc("Browser does not support WebAuthn",null)};const{data:a,error:o}=await this.challenge({factorId:e,webauthn:{rpId:n,rpOrigins:r},signal:i},{request:s});if(!a)return{data:null,error:o};const{webauthn:l}=a;return this._verify({factorId:e,challengeId:a.challengeId,webauthn:{type:l.type,rpId:n,rpOrigins:r,credential_response:l.credential_response}})}catch(a){return ot(a)?{data:null,error:a}:{data:null,error:new nc("Unexpected error in authenticate",a)}}}async _register({friendlyName:e,webauthn:{rpId:n=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},s){if(!n)return{data:null,error:new yp("rpId is required for WebAuthn registration")};try{if(!zk())return{data:null,error:new nc("Browser does not support WebAuthn",null)};const{data:a,error:o}=await this._enroll({friendlyName:e});if(!a)return await this.client.mfa.listFactors().then(u=>{var d;return(d=u.data)===null||d===void 0?void 0:d.all.find(h=>h.factor_type==="webauthn"&&h.friendly_name===e&&h.status!=="unverified")}).then(u=>u?this.client.mfa.unenroll({factorId:u==null?void 0:u.id}):void 0),{data:null,error:o};const{data:l,error:c}=await this._challenge({factorId:a.id,friendlyName:a.friendly_name,webauthn:{rpId:n,rpOrigins:r},signal:i},{create:s});return l?this._verify({factorId:a.id,challengeId:l.challengeId,webauthn:{rpId:n,rpOrigins:r,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:c}}catch(a){return ot(a)?{data:null,error:a}:{data:null,error:new nc("Unexpected error in register",a)}}}}Hee();const cte={url:aee,storageKey:oee,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:lee,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function qk(t,e,n){return await n()}const pu={};class vp{get jwks(){var e,n;return(n=(e=pu[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&n!==void 0?n:{keys:[]}}set jwks(e){pu[this.storageKey]=Object.assign(Object.assign({},pu[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,n;return(n=(e=pu[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&n!==void 0?n:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){pu[this.storageKey]=Object.assign(Object.assign({},pu[this.storageKey]),{cachedAt:e})}constructor(e){var n,r,i;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const s=Object.assign(Object.assign({},cte),e);if(this.storageKey=s.storageKey,this.instanceID=(n=vp.nextInstanceID[this.storageKey])!==null&&n!==void 0?n:0,vp.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.instanceID>0&&Lr()){const a=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(a),this.logDebugMessages&&console.trace(a)}if(this.persistSession=s.persistSession,this.autoRefreshToken=s.autoRefreshToken,this.admin=new Vee({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=Aj(s.fetch),this.lock=s.lock||qk,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,this.throwOnError=s.throwOnError,this.lockAcquireTimeout=s.lockAcquireTimeout,s.lock?this.lock=s.lock:this.persistSession&&Lr()&&(!((r=globalThis==null?void 0:globalThis.navigator)===null||r===void 0)&&r.locks)?this.lock=Gee:this.lock=qk,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new lte(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(s.storage?this.storage=s.storage:Tj()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Hk(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=Hk(this.memoryStorage)),Lr()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(a){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",a)}(i=this.broadcastChannel)===null||i===void 0||i.addEventListener("message",async a=>{this._debug("received broadcast notification from other tab or client",a);try{await this._notifyAllSubscribers(a.data.event,a.data.session,!1)}catch(o){this._debug("#broadcastChannel","error",o)}})}s.skipAutoInitialize||this.initialize().catch(a=>{this._debug("#initialize()","error",a)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Sj}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let n={},r="none";if(Lr()&&(n=See(window.location.href),this._isImplicitGrantCallback(n)?r="implicit":await this._isPKCECallback(n)&&(r="pkce")),Lr()&&this.detectSessionInUrl&&r!=="none"){const{data:i,error:s}=await this._getSessionFromURL(n,r);if(s){if(this._debug("#_initialize()","error detecting session from URL",s),fee(s)){const l=(e=s.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:s}}return{error:s}}const{session:a,redirectType:o}=i;return this._debug("#_initialize()","detected session in URL",a,"redirect type",o),await this._saveSession(a),setTimeout(async()=>{o==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(n){return ot(n)?this._returnResult({error:n}):this._returnResult({error:new nc("Unexpected error during initialization",n)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var n,r,i;try{const s=await ft(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(n=e==null?void 0:e.options)===null||n===void 0?void 0:n.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(i=e==null?void 0:e.options)===null||i===void 0?void 0:i.captchaToken}},xform:Ts}),{data:a,error:o}=s;if(o||!a)return this._returnResult({data:{user:null,session:null},error:o});const l=a.session,c=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(s){if(ot(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signUp(e){var n,r,i;try{let s;if("email"in e){const{email:u,password:d,options:h}=e;let f=null,p=null;this.flowType==="pkce"&&([f,p]=await hu(this.storage,this.storageKey)),s=await ft(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:h==null?void 0:h.emailRedirectTo,body:{email:u,password:d,data:(n=h==null?void 0:h.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:h==null?void 0:h.captchaToken},code_challenge:f,code_challenge_method:p},xform:Ts})}else if("phone"in e){const{phone:u,password:d,options:h}=e;s=await ft(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:d,data:(r=h==null?void 0:h.data)!==null&&r!==void 0?r:{},channel:(i=h==null?void 0:h.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:h==null?void 0:h.captchaToken}},xform:Ts})}else throw new lg("You must provide either an email or phone number and a password");const{data:a,error:o}=s;if(o||!a)return await Cr(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:o});const l=a.session,c=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(s){if(await Cr(this.storage,`${this.storageKey}-code-verifier`),ot(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithPassword(e){try{let n;if("email"in e){const{email:s,password:a,options:o}=e;n=await ft(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:a,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:Vk})}else if("phone"in e){const{phone:s,password:a,options:o}=e;n=await ft(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:a,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:Vk})}else throw new lg("You must provide either an email or phone number and a password");const{data:r,error:i}=n;if(i)return this._returnResult({data:{user:null,session:null},error:i});if(!r||!r.session||!r.user){const s=new du;return this._returnResult({data:{user:null,session:null},error:s})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:i})}catch(n){if(ot(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithOAuth(e){var n,r,i,s;return await this._handleProviderSignIn(e.provider,{redirectTo:(n=e.options)===null||n===void 0?void 0:n.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(s=e.options)===null||s===void 0?void 0:s.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:n}=e;switch(n){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${n}"`)}}async signInWithEthereum(e){var n,r,i,s,a,o,l,c,u,d,h;let f,p;if("message"in e)f=e.message,p=e.signature;else{const{chain:m,wallet:g,statement:b,options:v}=e;let S;if(Lr())if(typeof g=="object")S=g;else{const I=window;if("ethereum"in I&&typeof I.ethereum=="object"&&"request"in I.ethereum&&typeof I.ethereum.request=="function")S=I.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof g!="object"||!(v!=null&&v.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");S=g}const E=new URL((n=v==null?void 0:v.url)!==null&&n!==void 0?n:window.location.href),L=await S.request({method:"eth_requestAccounts"}).then(I=>I).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!L||L.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const U=Cj(L[0]);let O=(r=v==null?void 0:v.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!O){const I=await S.request({method:"eth_chainId"});O=Kee(I)}const k={domain:E.host,address:U,statement:b,uri:E.href,version:"1",chainId:O,nonce:(i=v==null?void 0:v.signInWithEthereum)===null||i===void 0?void 0:i.nonce,issuedAt:(a=(s=v==null?void 0:v.signInWithEthereum)===null||s===void 0?void 0:s.issuedAt)!==null&&a!==void 0?a:new Date,expirationTime:(o=v==null?void 0:v.signInWithEthereum)===null||o===void 0?void 0:o.expirationTime,notBefore:(l=v==null?void 0:v.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(c=v==null?void 0:v.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(u=v==null?void 0:v.signInWithEthereum)===null||u===void 0?void 0:u.resources};f=qee(k),p=await S.request({method:"personal_sign",params:[zee(f),U]})}try{const{data:m,error:g}=await ft(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:p},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(h=e.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:Ts});if(g)throw g;if(!m||!m.session||!m.user){const b=new du;return this._returnResult({data:{user:null,session:null},error:b})}return m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session)),this._returnResult({data:Object.assign({},m),error:g})}catch(m){if(ot(m))return this._returnResult({data:{user:null,session:null},error:m});throw m}}async signInWithSolana(e){var n,r,i,s,a,o,l,c,u,d,h,f;let p,m;if("message"in e)p=e.message,m=e.signature;else{const{chain:g,wallet:b,statement:v,options:S}=e;let E;if(Lr())if(typeof b=="object")E=b;else{const U=window;if("solana"in U&&typeof U.solana=="object"&&("signIn"in U.solana&&typeof U.solana.signIn=="function"||"signMessage"in U.solana&&typeof U.solana.signMessage=="function"))E=U.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof b!="object"||!(S!=null&&S.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");E=b}const L=new URL((n=S==null?void 0:S.url)!==null&&n!==void 0?n:window.location.href);if("signIn"in E&&E.signIn){const U=await E.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},S==null?void 0:S.signInWithSolana),{version:"1",domain:L.host,uri:L.href}),v?{statement:v}:null));let O;if(Array.isArray(U)&&U[0]&&typeof U[0]=="object")O=U[0];else if(U&&typeof U=="object"&&"signedMessage"in U&&"signature"in U)O=U;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in O&&"signature"in O&&(typeof O.signedMessage=="string"||O.signedMessage instanceof Uint8Array)&&O.signature instanceof Uint8Array)p=typeof O.signedMessage=="string"?O.signedMessage:new TextDecoder().decode(O.signedMessage),m=O.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in E)||typeof E.signMessage!="function"||!("publicKey"in E)||typeof E!="object"||!E.publicKey||!("toBase58"in E.publicKey)||typeof E.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${L.host} wants you to sign in with your Solana account:`,E.publicKey.toBase58(),...v?["",v,""]:[""],"Version: 1",`URI: ${L.href}`,`Issued At: ${(i=(r=S==null?void 0:S.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&i!==void 0?i:new Date().toISOString()}`,...!((s=S==null?void 0:S.signInWithSolana)===null||s===void 0)&&s.notBefore?[`Not Before: ${S.signInWithSolana.notBefore}`]:[],...!((a=S==null?void 0:S.signInWithSolana)===null||a===void 0)&&a.expirationTime?[`Expiration Time: ${S.signInWithSolana.expirationTime}`]:[],...!((o=S==null?void 0:S.signInWithSolana)===null||o===void 0)&&o.chainId?[`Chain ID: ${S.signInWithSolana.chainId}`]:[],...!((l=S==null?void 0:S.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${S.signInWithSolana.nonce}`]:[],...!((c=S==null?void 0:S.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${S.signInWithSolana.requestId}`]:[],...!((d=(u=S==null?void 0:S.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||d===void 0)&&d.length?["Resources",...S.signInWithSolana.resources.map(O=>`- ${O}`)]:[]].join(`
`);const U=await E.signMessage(new TextEncoder().encode(p),"utf8");if(!U||!(U instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");m=U}}try{const{data:g,error:b}=await ft(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:lc(m)},!((h=e.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:Ts});if(b)throw b;if(!g||!g.session||!g.user){const v=new du;return this._returnResult({data:{user:null,session:null},error:v})}return g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",g.session)),this._returnResult({data:Object.assign({},g),error:b})}catch(g){if(ot(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async _exchangeCodeForSession(e){const n=await Kl(this.storage,`${this.storageKey}-code-verifier`),[r,i]=(n??"").split("/");try{if(!r&&this.flowType==="pkce")throw new pee;const{data:s,error:a}=await ft(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:Ts});if(await Cr(this.storage,`${this.storageKey}-code-verifier`),a)throw a;if(!s||!s.session||!s.user){const o=new du;return this._returnResult({data:{user:null,session:null,redirectType:null},error:o})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers(i==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",s.session)),this._returnResult({data:Object.assign(Object.assign({},s),{redirectType:i??null}),error:a})}catch(s){if(await Cr(this.storage,`${this.storageKey}-code-verifier`),ot(s))return this._returnResult({data:{user:null,session:null,redirectType:null},error:s});throw s}}async signInWithIdToken(e){try{const{options:n,provider:r,token:i,access_token:s,nonce:a}=e,o=await ft(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:i,access_token:s,nonce:a,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}},xform:Ts}),{data:l,error:c}=o;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l||!l.session||!l.user){const u=new du;return this._returnResult({data:{user:null,session:null},error:u})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:c})}catch(n){if(ot(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithOtp(e){var n,r,i,s,a;try{if("email"in e){const{email:o,options:l}=e;let c=null,u=null;this.flowType==="pkce"&&([c,u]=await hu(this.storage,this.storageKey));const{error:d}=await ft(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(n=l==null?void 0:l.data)!==null&&n!==void 0?n:{},create_user:(r=l==null?void 0:l.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},code_challenge:c,code_challenge_method:u},redirectTo:l==null?void 0:l.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:d})}if("phone"in e){const{phone:o,options:l}=e,{data:c,error:u}=await ft(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(i=l==null?void 0:l.data)!==null&&i!==void 0?i:{},create_user:(s=l==null?void 0:l.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},channel:(a=l==null?void 0:l.channel)!==null&&a!==void 0?a:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:u})}throw new lg("You must provide either an email or phone number.")}catch(o){if(await Cr(this.storage,`${this.storageKey}-code-verifier`),ot(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async verifyOtp(e){var n,r;try{let i,s;"options"in e&&(i=(n=e.options)===null||n===void 0?void 0:n.redirectTo,s=(r=e.options)===null||r===void 0?void 0:r.captchaToken);const{data:a,error:o}=await ft(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:s}}),redirectTo:i,xform:Ts});if(o)throw o;if(!a)throw new Error("An error occurred on token verification.");const l=a.session,c=a.user;return l!=null&&l.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if(ot(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithSSO(e){var n,r,i,s,a;try{let o=null,l=null;this.flowType==="pkce"&&([o,l]=await hu(this.storage,this.storageKey));const c=await ft(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(r=(n=e.options)===null||n===void 0?void 0:n.redirectTo)!==null&&r!==void 0?r:void 0}),!((i=e==null?void 0:e.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:l}),headers:this.headers,xform:jee});return!((s=c.data)===null||s===void 0)&&s.url&&Lr()&&!(!((a=e.options)===null||a===void 0)&&a.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(o){if(await Cr(this.storage,`${this.storageKey}-code-verifier`),ot(o))return this._returnResult({data:null,error:o});throw o}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:n},error:r}=e;if(r)throw r;if(!n)throw new Ri;const{error:i}=await ft(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return this._returnResult({data:{user:null,session:null},error:i})})}catch(e){if(ot(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const n=`${this.url}/resend`;if("email"in e){const{email:r,type:i,options:s}=e,{error:a}=await ft(this.fetch,"POST",n,{headers:this.headers,body:{email:r,type:i,gotrue_meta_security:{captcha_token:s==null?void 0:s.captchaToken}},redirectTo:s==null?void 0:s.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}else if("phone"in e){const{phone:r,type:i,options:s}=e,{data:a,error:o}=await ft(this.fetch,"POST",n,{headers:this.headers,body:{phone:r,type:i,gotrue_meta_security:{captcha_token:s==null?void 0:s.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a==null?void 0:a.message_id},error:o})}throw new lg("You must provide either an email or phone number and a type")}catch(n){if(ot(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async n=>n))}async _acquireLock(e,n){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await r,await n()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const r=n();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){const i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const n=await this.__loadSession();return await e(n)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const n=await Kl(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",n),n!==null&&(this._isValidSession(n)?e=n:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const r=e.expires_at?e.expires_at*1e3-Date.now()<mb:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.userStorage){const a=await Kl(this.userStorage,this.storageKey+"-user");a!=null&&a.user?e.user=a.user:e.user=yb()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const a={value:this.suppressGetSessionWarning};e.user=Nee(e.user,a),a.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:i,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{session:null},error:s}):this._returnResult({data:{session:i},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const n=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return n.data.user&&(this.suppressGetSessionWarning=!0),n}async _getUser(e){try{return e?await ft(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Ho}):await this._useSession(async n=>{var r,i,s;const{data:a,error:o}=n;if(o)throw o;return!(!((r=a.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Ri}:await ft(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(s=(i=a.session)===null||i===void 0?void 0:i.access_token)!==null&&s!==void 0?s:void 0,xform:Ho})})}catch(n){if(ot(n))return og(n)&&(await this._removeSession(),await Cr(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:n});throw n}}async updateUser(e,n={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,n))}async _updateUser(e,n={}){try{return await this._useSession(async r=>{const{data:i,error:s}=r;if(s)throw s;if(!i.session)throw new Ri;const a=i.session;let o=null,l=null;this.flowType==="pkce"&&e.email!=null&&([o,l]=await hu(this.storage,this.storageKey));const{data:c,error:u}=await ft(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:n==null?void 0:n.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:l}),jwt:a.access_token,xform:Ho});if(u)throw u;return a.user=c.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),this._returnResult({data:{user:a.user},error:null})})}catch(r){if(await Cr(this.storage,`${this.storageKey}-code-verifier`),ot(r))return this._returnResult({data:{user:null},error:r});throw r}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new Ri;const n=Date.now()/1e3;let r=n,i=!0,s=null;const{payload:a}=ug(e.access_token);if(a.exp&&(r=a.exp,i=r<=n),i){const{data:o,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!o)return{data:{user:null,session:null},error:null};s=o}else{const{data:o,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});s={access_token:e.access_token,refresh_token:e.refresh_token,user:o.user,token_type:"bearer",expires_in:r-n,expires_at:r},await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)}return this._returnResult({data:{user:s.user,session:s},error:null})}catch(n){if(ot(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async n=>{var r;if(!e){const{data:a,error:o}=n;if(o)throw o;e=(r=a.session)!==null&&r!==void 0?r:void 0}if(!(e!=null&&e.refresh_token))throw new Ri;const{data:i,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{user:null,session:null},error:s}):i?this._returnResult({data:{user:i.user,session:i},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(n){if(ot(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async _getSessionFromURL(e,n){var r;try{if(!Lr())throw new cg("No browser detected.");if(e.error||e.error_description||e.error_code)throw new cg(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(n){case"implicit":if(this.flowType==="pkce")throw new Nk("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new cg("Not a valid implicit grant flow url.");break;default:}if(n==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Nk("No code detected.");const{data:S,error:E}=await this._exchangeCodeForSession(e.code);if(E)throw E;const L=new URL(window.location.href);return L.searchParams.delete("code"),window.history.replaceState(window.history.state,"",L.toString()),{data:{session:S.session,redirectType:(r=S.redirectType)!==null&&r!==void 0?r:null},error:null}}const{provider_token:i,provider_refresh_token:s,access_token:a,refresh_token:o,expires_in:l,expires_at:c,token_type:u}=e;if(!a||!l||!o||!u)throw new cg("No session defined in URL");const d=Math.round(Date.now()/1e3),h=parseInt(l);let f=d+h;c&&(f=parseInt(c));const p=f-d;p*1e3<=Nu&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${h}s`);const m=f-h;d-m>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",m,f,d):d-m<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",m,f,d);const{data:g,error:b}=await this._getUser(a);if(b)throw b;const v={provider_token:i,provider_refresh_token:s,access_token:a,expires_in:h,expires_at:f,refresh_token:o,token_type:u,user:g.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:v,redirectType:e.type},error:null})}catch(i){if(ot(i))return this._returnResult({data:{session:null,redirectType:null},error:i});throw i}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){const n=await Kl(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&n)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async n=>{var r;const{data:i,error:s}=n;if(s&&!og(s))return this._returnResult({error:s});const a=(r=i.session)===null||r===void 0?void 0:r.access_token;if(a){const{error:o}=await this.admin.signOut(a,e);if(o&&!(hee(o)&&(o.status===404||o.status===401||o.status===403)||og(o)))return this._returnResult({error:o})}return e!=="others"&&(await this._removeSession(),await Cr(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const n=xee(),r={id:n,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",n),this.stateChangeEmitters.delete(n)}};return this._debug("#onAuthStateChange()","registered callback with id",n),this.stateChangeEmitters.set(n,r),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(n)})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async n=>{var r,i;try{const{data:{session:s},error:a}=n;if(a)throw a;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(s){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",s),og(s)?console.warn(s):console.error(s)}})}async resetPasswordForEmail(e,n={}){let r=null,i=null;this.flowType==="pkce"&&([r,i]=await hu(this.storage,this.storageKey,!0));try{return await ft(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:i,gotrue_meta_security:{captcha_token:n.captchaToken}},headers:this.headers,redirectTo:n.redirectTo})}catch(s){if(await Cr(this.storage,`${this.storageKey}-code-verifier`),ot(s))return this._returnResult({data:null,error:s});throw s}}async getUserIdentities(){var e;try{const{data:n,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:(e=n.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(n){if(ot(n))return this._returnResult({data:null,error:n});throw n}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var n;try{const{data:r,error:i}=await this._useSession(async s=>{var a,o,l,c,u;const{data:d,error:h}=s;if(h)throw h;const f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(a=e.options)===null||a===void 0?void 0:a.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await ft(this.fetch,"GET",f,{headers:this.headers,jwt:(u=(c=d.session)===null||c===void 0?void 0:c.access_token)!==null&&u!==void 0?u:void 0})});if(i)throw i;return Lr()&&!(!((n=e.options)===null||n===void 0)&&n.skipBrowserRedirect)&&window.location.assign(r==null?void 0:r.url),this._returnResult({data:{provider:e.provider,url:r==null?void 0:r.url},error:null})}catch(r){if(ot(r))return this._returnResult({data:{provider:e.provider,url:null},error:r});throw r}}async linkIdentityIdToken(e){return await this._useSession(async n=>{var r;try{const{error:i,data:{session:s}}=n;if(i)throw i;const{options:a,provider:o,token:l,access_token:c,nonce:u}=e,d=await ft(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=s==null?void 0:s.access_token)!==null&&r!==void 0?r:void 0,body:{provider:o,id_token:l,access_token:c,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:Ts}),{data:h,error:f}=d;return f?this._returnResult({data:{user:null,session:null},error:f}):!h||!h.session||!h.user?this._returnResult({data:{user:null,session:null},error:new du}):(h.session&&(await this._saveSession(h.session),await this._notifyAllSubscribers("USER_UPDATED",h.session)),this._returnResult({data:h,error:f}))}catch(i){if(await Cr(this.storage,`${this.storageKey}-code-verifier`),ot(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}})}async unlinkIdentity(e){try{return await this._useSession(async n=>{var r,i;const{data:s,error:a}=n;if(a)throw a;return await ft(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&i!==void 0?i:void 0})})}catch(n){if(ot(n))return this._returnResult({data:null,error:n});throw n}}async _refreshAccessToken(e){const n=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{const r=Date.now();return await Tee(async i=>(i>0&&await wee(200*Math.pow(2,i-1)),this._debug(n,"refreshing attempt",i),await ft(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Ts})),(i,s)=>{const a=200*Math.pow(2,i);return s&&gb(s)&&Date.now()+a-r<Nu})}catch(r){if(this._debug(n,"error",r),ot(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}finally{this._debug(n,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,n){const r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:n.redirectTo,scopes:n.scopes,queryParams:n.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",n,"url",r),Lr()&&!n.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e,n;const r="#_recoverAndRefresh()";this._debug(r,"begin");try{const i=await Kl(this.storage,this.storageKey);if(i&&this.userStorage){let a=await Kl(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:i.user},await Mu(this.userStorage,this.storageKey+"-user",a)),i.user=(e=a==null?void 0:a.user)!==null&&e!==void 0?e:yb()}else if(i&&!i.user&&!i.user){const a=await Kl(this.storage,this.storageKey+"-user");a&&(a!=null&&a.user)?(i.user=a.user,await Cr(this.storage,this.storageKey+"-user"),await Mu(this.storage,this.storageKey,i)):i.user=yb()}if(this._debug(r,"session from storage",i),!this._isValidSession(i)){this._debug(r,"session is not valid"),i!==null&&await this._removeSession();return}const s=((n=i.expires_at)!==null&&n!==void 0?n:1/0)*1e3-Date.now()<mb;if(this._debug(r,`session has${s?"":" not"} expired with margin of ${mb}s`),s){if(this.autoRefreshToken&&i.refresh_token){const{error:a}=await this._callRefreshToken(i.refresh_token);a&&(console.error(a),gb(a)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",a),await this._removeSession()))}}else if(i.user&&i.user.__isUserNotAvailableProxy===!0)try{const{data:a,error:o}=await this._getUser(i.access_token);!o&&(a!=null&&a.user)?(i.user=a.user,await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(a){console.error("Error getting user data:",a),this._debug(r,"error getting user data, skipping SIGNED_IN notification",a)}else await this._notifyAllSubscribers("SIGNED_IN",i)}catch(i){this._debug(r,"error",i),console.error(i);return}finally{this._debug(r,"end")}}async _callRefreshToken(e){var n,r;if(!e)throw new Ri;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new vv;const{data:s,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!s.session)throw new Ri;await this._saveSession(s.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",s.session);const o={data:s.session,error:null};return this.refreshingDeferred.resolve(o),o}catch(s){if(this._debug(i,"error",s),ot(s)){const a={data:null,error:s};return gb(s)||await this._removeSession(),(n=this.refreshingDeferred)===null||n===void 0||n.resolve(a),a}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(s),s}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,n,r=!0){const i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",n,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:n});const s=[],a=Array.from(this.stateChangeEmitters.values()).map(async o=>{try{await o.callback(e,n)}catch(l){s.push(l)}});if(await Promise.all(a),s.length>0){for(let o=0;o<s.length;o+=1)console.error(s[o]);throw s[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Cr(this.storage,`${this.storageKey}-code-verifier`);const n=Object.assign({},e),r=n.user&&n.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!r&&n.user&&await Mu(this.userStorage,this.storageKey+"-user",{user:n.user});const i=Object.assign({},n);delete i.user;const s=Fk(i);await Mu(this.storage,this.storageKey,s)}else{const i=Fk(n);await Mu(this.storage,this.storageKey,i)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Cr(this.storage,this.storageKey),await Cr(this.storage,this.storageKey+"-code-verifier"),await Cr(this.storage,this.storageKey+"-user"),this.userStorage&&await Cr(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Lr()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(n){console.error("removing visibilitychange callback failed",n)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),Nu);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const n=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=n,n&&typeof n=="object"&&typeof n.unref=="function"?n.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(n)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const n=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,n&&clearTimeout(n)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async n=>{const{data:{session:r}}=n;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const i=Math.floor((r.expires_at*1e3-e)/Nu);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Nu}ms, refresh threshold is ${xE} ticks`),i<=xE&&await this._callRefreshToken(r.refresh_token)})}catch(n){console.error("Auto refresh tick failed with error. This is likely a transient error.",n)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Rj)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Lr()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const n=`#_onVisibilityChanged(${e})`;this._debug(n,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(n,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,n,r){const i=[`provider=${encodeURIComponent(n)}`];if(r!=null&&r.redirectTo&&i.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r!=null&&r.scopes&&i.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){const[s,a]=await hu(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(s)}`,code_challenge_method:`${encodeURIComponent(a)}`});i.push(o.toString())}if(r!=null&&r.queryParams){const s=new URLSearchParams(r.queryParams);i.push(s.toString())}return r!=null&&r.skipBrowserRedirect&&i.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async n=>{var r;const{data:i,error:s}=n;return s?this._returnResult({data:null,error:s}):await ft(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token})})}catch(n){if(ot(n))return this._returnResult({data:null,error:n});throw n}}async _enroll(e){try{return await this._useSession(async n=>{var r,i;const{data:s,error:a}=n;if(a)return this._returnResult({data:null,error:a});const o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:c}=await ft(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(r=s==null?void 0:s.session)===null||r===void 0?void 0:r.access_token});return c?this._returnResult({data:null,error:c}):(e.factorType==="totp"&&l.type==="totp"&&(!((i=l==null?void 0:l.totp)===null||i===void 0)&&i.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(n){if(ot(n))return this._returnResult({data:null,error:n});throw n}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async n=>{var r;const{data:i,error:s}=n;if(s)return this._returnResult({data:null,error:s});const a=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?ete(e.webauthn.credential_response):tte(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:l}=await ft(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:a,headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),this._returnResult({data:o,error:l}))})}catch(n){if(ot(n))return this._returnResult({data:null,error:n});throw n}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async n=>{var r;const{data:i,error:s}=n;if(s)return this._returnResult({data:null,error:s});const a=await ft(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token});if(a.error)return a;const{data:o}=a;if(o.type!=="webauthn")return{data:o,error:null};switch(o.webauthn.type){case"create":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:Jee(o.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:Zee(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(n){if(ot(n))return this._returnResult({data:null,error:n});throw n}})}async _challengeAndVerify(e){const{data:n,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:n.id,code:e.code})}async _listFactors(){var e;const{data:{user:n},error:r}=await this.getUser();if(r)return{data:null,error:r};const i={all:[],phone:[],totp:[],webauthn:[]};for(const s of(e=n==null?void 0:n.factors)!==null&&e!==void 0?e:[])i.all.push(s),s.status==="verified"&&i[s.factor_type].push(s);return{data:i,error:null}}async _getAuthenticatorAssuranceLevel(e){var n,r,i,s;if(e)try{const{payload:f}=ug(e);let p=null;f.aal&&(p=f.aal);let m=p;const{data:{user:g},error:b}=await this.getUser(e);if(b)return this._returnResult({data:null,error:b});((r=(n=g==null?void 0:g.factors)===null||n===void 0?void 0:n.filter(E=>E.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(m="aal2");const S=f.amr||[];return{data:{currentLevel:p,nextLevel:m,currentAuthenticationMethods:S},error:null}}catch(f){if(ot(f))return this._returnResult({data:null,error:f});throw f}const{data:{session:a},error:o}=await this.getSession();if(o)return this._returnResult({data:null,error:o});if(!a)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:l}=ug(a.access_token);let c=null;l.aal&&(c=l.aal);let u=c;((s=(i=a.user.factors)===null||i===void 0?void 0:i.filter(f=>f.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(u="aal2");const h=l.amr||[];return{data:{currentLevel:c,nextLevel:u,currentAuthenticationMethods:h},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async n=>{const{data:{session:r},error:i}=n;return i?this._returnResult({data:null,error:i}):r?await ft(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new Ri})})}catch(n){if(ot(n))return this._returnResult({data:null,error:n});throw n}}async _approveAuthorization(e,n){try{return await this._useSession(async r=>{const{data:{session:i},error:s}=r;if(s)return this._returnResult({data:null,error:s});if(!i)return this._returnResult({data:null,error:new Ri});const a=await ft(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"approve"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&Lr()&&!(n!=null&&n.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(r){if(ot(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(e,n){try{return await this._useSession(async r=>{const{data:{session:i},error:s}=r;if(s)return this._returnResult({data:null,error:s});if(!i)return this._returnResult({data:null,error:new Ri});const a=await ft(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"deny"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&Lr()&&!(n!=null&&n.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(r){if(ot(r))return this._returnResult({data:null,error:r});throw r}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:n},error:r}=e;return r?this._returnResult({data:null,error:r}):n?await ft(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new Ri})})}catch(e){if(ot(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async n=>{const{data:{session:r},error:i}=n;return i?this._returnResult({data:null,error:i}):r?(await ft(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Ri})})}catch(n){if(ot(n))return this._returnResult({data:null,error:n});throw n}}async fetchJwk(e,n={keys:[]}){let r=n.keys.find(o=>o.kid===e);if(r)return r;const i=Date.now();if(r=this.jwks.keys.find(o=>o.kid===e),r&&this.jwks_cached_at+uee>i)return r;const{data:s,error:a}=await ft(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return!s.keys||s.keys.length===0||(this.jwks=s,this.jwks_cached_at=i,r=s.keys.find(o=>o.kid===e),!r)?null:r}async getClaims(e,n={}){try{let r=e;if(!r){const{data:f,error:p}=await this.getSession();if(p||!f.session)return this._returnResult({data:null,error:p});r=f.session.access_token}const{header:i,payload:s,signature:a,raw:{header:o,payload:l}}=ug(r);n!=null&&n.allowExpired||Pee(s.exp);const c=!i.alg||i.alg.startsWith("HS")||!i.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(i.kid,n!=null&&n.keys?{keys:n.keys}:n==null?void 0:n.jwks);if(!c){const{error:f}=await this.getUser(r);if(f)throw f;return{data:{claims:s,header:i,signature:a},error:null}}const u=Dee(i.alg),d=await crypto.subtle.importKey("jwk",c,u,!0,["verify"]);if(!await crypto.subtle.verify(u,d,a,_ee(`${o}.${l}`)))throw new wE("Invalid JWT signature");return{data:{claims:s,header:i,signature:a},error:null}}catch(r){if(ot(r))return this._returnResult({data:null,error:r});throw r}}}vp.nextInstanceID={};const ute=vp,dte="2.104.1";let tf="";typeof Deno<"u"?tf="deno":typeof document<"u"?tf="web":typeof navigator<"u"&&navigator.product==="ReactNative"?tf="react-native":tf="node";const hte={"X-Client-Info":`supabase-js-${tf}/${dte}`},fte={headers:hte},pte={schema:"public"},mte={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},gte={};function _p(t){"@babel/helpers - typeof";return _p=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_p(t)}function yte(t,e){if(_p(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(_p(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function vte(t){var e=yte(t,"string");return _p(e)=="symbol"?e:e+""}function _te(t,e,n){return(e=vte(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Wk(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Gn(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Wk(Object(n),!0).forEach(function(r){_te(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Wk(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}const bte=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),xte=()=>Headers,Ste=(t,e,n)=>{const r=bte(n),i=xte();return async(s,a)=>{var o;const l=(o=await e())!==null&&o!==void 0?o:t;let c=new i(a==null?void 0:a.headers);return c.has("apikey")||c.set("apikey",t),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),r(s,Gn(Gn({},a),{},{headers:c}))}};function Ete(t){return t.endsWith("/")?t:t+"/"}function wte(t,e){var n,r;const{db:i,auth:s,realtime:a,global:o}=t,{db:l,auth:c,realtime:u,global:d}=e,h={db:Gn(Gn({},l),i),auth:Gn(Gn({},c),s),realtime:Gn(Gn({},u),a),storage:{},global:Gn(Gn(Gn({},d),o),{},{headers:Gn(Gn({},(n=d==null?void 0:d.headers)!==null&&n!==void 0?n:{}),(r=o==null?void 0:o.headers)!==null&&r!==void 0?r:{})}),accessToken:async()=>""};return t.accessToken?h.accessToken=t.accessToken:delete h.accessToken,h}function Tte(t){const e=t==null?void 0:t.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(Ete(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Ate=class extends ute{constructor(t){super(t)}},Rte=class{constructor(t,e,n){var r,i;this.supabaseUrl=t,this.supabaseKey=e;const s=Tte(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",s),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",s),this.storageUrl=new URL("storage/v1",s),this.functionsUrl=new URL("functions/v1",s);const a=`sb-${s.hostname.split(".")[0]}-auth-token`,o={db:pte,realtime:gte,auth:Gn(Gn({},mte),{},{storageKey:a}),global:fte},l=wte(n??{},o);if(this.storageKey=(r=l.auth.storageKey)!==null&&r!==void 0?r:"",this.headers=(i=l.global.headers)!==null&&i!==void 0?i:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(u,d)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(d)} is not possible`)}});else{var c;this.auth=this._initSupabaseAuthClient((c=l.auth)!==null&&c!==void 0?c:{},this.headers,l.global.fetch)}this.fetch=Ste(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Gn({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(u=>this.realtime.setAuth(u)).catch(u=>console.warn("Failed to set initial Realtime auth token:",u)),this.rest=new WJ(new URL("rest/v1",s).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new see(this.storageUrl.href,this.headers,this.fetch,n==null?void 0:n.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new UJ(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},n={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,n)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,n;if(t.accessToken)return await t.accessToken();const{data:r}=await t.auth.getSession();return(e=(n=r.session)===null||n===void 0?void 0:n.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:n,storage:r,userStorage:i,storageKey:s,flowType:a,lock:o,debug:l,throwOnError:c},u,d){const h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Ate({url:this.authUrl.href,headers:Gn(Gn({},h),u),storageKey:s,autoRefreshToken:t,persistSession:e,detectSessionInUrl:n,storage:r,userStorage:i,flowType:a,lock:o,debug:l,throwOnError:c,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(f=>f.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new CZ(this.realtimeUrl.href,Gn(Gn({},t),{},{params:Gn(Gn({},{apikey:this.supabaseKey}),t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e==null?void 0:e.access_token)})}_handleTokenChanged(t,e,n){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==n?(this.changedAccessToken=n,this.realtime.setAuth(n)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const Cte=(t,e,n)=>new Rte(t,e,n);function Lte(){if(typeof window<"u")return!1;const t=globalThis.process;if(!t)return!1;const e=t.version;if(e==null)return!1;const n=e.match(/^v(\d+)\./);return n?parseInt(n[1],10)<=18:!1}Lte()&&console.warn("⚠️  Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const kte="https://example.supabase.co",Ite="disabled",Pte=Cte(kte,Ite,{auth:{storage:localStorage,persistSession:!0,autoRefreshToken:!0}});/*! Capacitor: https://capacitorjs.com/ - MIT License */var Qd;(function(t){t.Unimplemented="UNIMPLEMENTED",t.Unavailable="UNAVAILABLE"})(Qd||(Qd={}));class _b extends Error{constructor(e,n,r){super(e),this.message=e,this.code=n,this.data=r}}const Dte=t=>{var e,n;return t!=null&&t.androidBridge?"android":!((n=(e=t==null?void 0:t.webkit)===null||e===void 0?void 0:e.messageHandlers)===null||n===void 0)&&n.bridge?"ios":"web"},Ote=t=>{const e=t.CapacitorCustomPlatform||null,n=t.Capacitor||{},r=n.Plugins=n.Plugins||{},i=()=>e!==null?e.name:Dte(t),s=()=>i()!=="web",a=d=>{const h=c.get(d);return!!(h!=null&&h.platforms.has(i())||o(d))},o=d=>{var h;return(h=n.PluginHeaders)===null||h===void 0?void 0:h.find(f=>f.name===d)},l=d=>t.console.error(d),c=new Map,u=(d,h={})=>{const f=c.get(d);if(f)return console.warn(`Capacitor plugin "${d}" already registered. Cannot register plugins twice.`),f.proxy;const p=i(),m=o(d);let g;const b=async()=>(!g&&p in h?g=typeof h[p]=="function"?g=await h[p]():g=h[p]:e!==null&&!g&&"web"in h&&(g=typeof h.web=="function"?g=await h.web():g=h.web),g),v=(k,I)=>{var R,M;if(m){const z=m==null?void 0:m.methods.find(Z=>I===Z.name);if(z)return z.rtype==="promise"?Z=>n.nativePromise(d,I.toString(),Z):(Z,W)=>n.nativeCallback(d,I.toString(),Z,W);if(k)return(R=k[I])===null||R===void 0?void 0:R.bind(k)}else{if(k)return(M=k[I])===null||M===void 0?void 0:M.bind(k);throw new _b(`"${d}" plugin is not implemented on ${p}`,Qd.Unimplemented)}},S=k=>{let I;const R=(...M)=>{const z=b().then(Z=>{const W=v(Z,k);if(W){const re=W(...M);return I=re==null?void 0:re.remove,re}else throw new _b(`"${d}.${k}()" is not implemented on ${p}`,Qd.Unimplemented)});return k==="addListener"&&(z.remove=async()=>I()),z};return R.toString=()=>`${k.toString()}() { [capacitor code] }`,Object.defineProperty(R,"name",{value:k,writable:!1,configurable:!1}),R},E=S("addListener"),L=S("removeListener"),U=(k,I)=>{const R=E({eventName:k},I),M=async()=>{const Z=await R;L({eventName:k,callbackId:Z},I)},z=new Promise(Z=>R.then(()=>Z({remove:M})));return z.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await M()},z},O=new Proxy({},{get(k,I){switch(I){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return m?U:E;case"removeListener":return L;default:return S(I)}}});return r[d]=O,c.set(d,{name:d,proxy:O,platforms:new Set([...Object.keys(h),...m?[p]:[]])}),O};return n.convertFileSrc||(n.convertFileSrc=d=>d),n.getPlatform=i,n.handleError=l,n.isNativePlatform=s,n.isPluginAvailable=a,n.registerPlugin=u,n.Exception=_b,n.DEBUG=!!n.DEBUG,n.isLoggingEnabled=!!n.isLoggingEnabled,n},Nte=t=>t.Capacitor=Ote(t),Tl=Nte(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),cm=Tl.registerPlugin;class kj{constructor(){this.listeners={},this.retainedEventArguments={},this.windowListeners={}}addListener(e,n){let r=!1;this.listeners[e]||(this.listeners[e]=[],r=!0),this.listeners[e].push(n);const s=this.windowListeners[e];s&&!s.registered&&this.addWindowListener(s),r&&this.sendRetainedArgumentsForEvent(e);const a=async()=>this.removeListener(e,n);return Promise.resolve({remove:a})}async removeAllListeners(){this.listeners={};for(const e in this.windowListeners)this.removeWindowListener(this.windowListeners[e]);this.windowListeners={}}notifyListeners(e,n,r){const i=this.listeners[e];if(!i){if(r){let s=this.retainedEventArguments[e];s||(s=[]),s.push(n),this.retainedEventArguments[e]=s}return}i.forEach(s=>s(n))}hasListeners(e){var n;return!!(!((n=this.listeners[e])===null||n===void 0)&&n.length)}registerWindowListener(e,n){this.windowListeners[n]={registered:!1,windowEventName:e,pluginEventName:n,handler:r=>{this.notifyListeners(n,r)}}}unimplemented(e="not implemented"){return new Tl.Exception(e,Qd.Unimplemented)}unavailable(e="not available"){return new Tl.Exception(e,Qd.Unavailable)}async removeListener(e,n){const r=this.listeners[e];if(!r)return;const i=r.indexOf(n);this.listeners[e].splice(i,1),this.listeners[e].length||this.removeWindowListener(this.windowListeners[e])}addWindowListener(e){window.addEventListener(e.windowEventName,e.handler),e.registered=!0}removeWindowListener(e){e&&(window.removeEventListener(e.windowEventName,e.handler),e.registered=!1)}sendRetainedArgumentsForEvent(e){const n=this.retainedEventArguments[e];n&&(delete this.retainedEventArguments[e],n.forEach(r=>{this.notifyListeners(e,r)}))}}const Yk=t=>encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),Xk=t=>t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class Mte extends kj{async getCookies(){const e=document.cookie,n={};return e.split(";").forEach(r=>{if(r.length<=0)return;let[i,s]=r.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");i=Xk(i).trim(),s=Xk(s).trim(),n[i]=s}),n}async setCookie(e){try{const n=Yk(e.key),r=Yk(e.value),i=e.expires?`; expires=${e.expires.replace("expires=","")}`:"",s=(e.path||"/").replace("path=",""),a=e.url!=null&&e.url.length>0?`domain=${e.url}`:"";document.cookie=`${n}=${r||""}${i}; path=${s}; ${a};`}catch(n){return Promise.reject(n)}}async deleteCookie(e){try{document.cookie=`${e.key}=; Max-Age=0`}catch(n){return Promise.reject(n)}}async clearCookies(){try{const e=document.cookie.split(";")||[];for(const n of e)document.cookie=n.replace(/^ +/,"").replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`)}catch(e){return Promise.reject(e)}}async clearAllCookies(){try{await this.clearCookies()}catch(e){return Promise.reject(e)}}}cm("CapacitorCookies",{web:()=>new Mte});const Bte=async t=>new Promise((e,n)=>{const r=new FileReader;r.onload=()=>{const i=r.result;e(i.indexOf(",")>=0?i.split(",")[1]:i)},r.onerror=i=>n(i),r.readAsDataURL(t)}),Ute=(t={})=>{const e=Object.keys(t);return Object.keys(t).map(i=>i.toLocaleLowerCase()).reduce((i,s,a)=>(i[s]=t[e[a]],i),{})},jte=(t,e=!0)=>t?Object.entries(t).reduce((r,i)=>{const[s,a]=i;let o,l;return Array.isArray(a)?(l="",a.forEach(c=>{o=e?encodeURIComponent(c):c,l+=`${s}=${o}&`}),l.slice(0,-1)):(o=e?encodeURIComponent(a):a,l=`${s}=${o}`),`${r}&${l}`},"").substr(1):null,Fte=(t,e={})=>{const n=Object.assign({method:t.method||"GET",headers:t.headers},e),i=Ute(t.headers)["content-type"]||"";if(typeof t.data=="string")n.body=t.data;else if(i.includes("application/x-www-form-urlencoded")){const s=new URLSearchParams;for(const[a,o]of Object.entries(t.data||{}))s.set(a,o);n.body=s.toString()}else if(i.includes("multipart/form-data")||t.data instanceof FormData){const s=new FormData;if(t.data instanceof FormData)t.data.forEach((o,l)=>{s.append(l,o)});else for(const o of Object.keys(t.data))s.append(o,t.data[o]);n.body=s;const a=new Headers(n.headers);a.delete("content-type"),n.headers=a}else(i.includes("application/json")||typeof t.data=="object")&&(n.body=JSON.stringify(t.data));return n};class $te extends kj{async request(e){const n=Fte(e,e.webFetchExtra),r=jte(e.params,e.shouldEncodeUrlParams),i=r?`${e.url}?${r}`:e.url,s=await fetch(i,n),a=s.headers.get("content-type")||"";let{responseType:o="text"}=s.ok?e:{};a.includes("application/json")&&(o="json");let l,c;switch(o){case"arraybuffer":case"blob":c=await s.blob(),l=await Bte(c);break;case"json":l=await s.json();break;case"document":case"text":default:l=await s.text()}const u={};return s.headers.forEach((d,h)=>{u[h]=d}),{data:l,headers:u,status:s.status,url:s.url}}async get(e){return this.request(Object.assign(Object.assign({},e),{method:"GET"}))}async post(e){return this.request(Object.assign(Object.assign({},e),{method:"POST"}))}async put(e){return this.request(Object.assign(Object.assign({},e),{method:"PUT"}))}async patch(e){return this.request(Object.assign(Object.assign({},e),{method:"PATCH"}))}async delete(e){return this.request(Object.assign(Object.assign({},e),{method:"DELETE"}))}}const Vte=cm("CapacitorHttp",{web:()=>new $te}),Ko=cm("NativePlayer"),um=()=>Tl.isNativePlatform(),Gte=()=>Tl.getPlatform(),Ij=[{id:"exoplayer",label:"ExoPlayer",value:"ExoPlayer/2.19.1 (Linux;Android 13) ExoPlayerLib/2.19.1"},{id:"vlc",label:"VLC Media Player",value:"VLC/3.0.20 LibVLC/3.0.20"}],Pj="livetv.ua",sa=()=>{try{const t=localStorage.getItem(Pj);if(t)return t}catch{}return Ij[0].value},Hte=t=>{try{localStorage.setItem(Pj,t)}catch{}},bb={};var mu={};const TE="https://example.supabase.co",Qk=(bb==null?void 0:bb.REACT_APP_BACKEND_URL)||(typeof process<"u"?(mu==null?void 0:mu.VITE_BACKEND_URL)||(mu==null?void 0:mu.REACT_APP_BACKEND_URL):void 0),Dj=t=>{try{const e=new URL(t);return e.hostname.includes("placeholder")?!1:e.hostname.endsWith(".supabase.co")}catch{return!1}},Oj=()=>Dj(TE)?`${TE.replace(/\/$/,"")}/functions/v1/iptv-proxy`:Qk?`${Qk.replace(/\/$/,"")}/api/iptv-proxy`:"/api/iptv-proxy",Kte=()=>Dj(TE)?"supabase":"backend",Nj=async(t,e="json")=>{var s;if(um()){const a=await Vte.request({url:t,method:"GET",headers:{"User-Agent":sa(),Accept:e==="json"?"application/json, */*":"*/*"},responseType:e==="text"?"text":"json",connectTimeout:15e3,readTimeout:2e4});if(a.status<200||a.status>=300)throw new Error(`Upstream ${a.status}`);if(e==="text")return String(a.data);if(typeof a.data=="string")try{return JSON.parse(a.data)}catch{return a.data}return a.data}const n=Oj(),r={"Content-Type":"application/json"};if(Kte()==="supabase"){const{data:a}=await Pte.auth.getSession(),o="disabled";r.apikey=o,r.Authorization=`Bearer ${((s=a.session)==null?void 0:s.access_token)??o??""}`}const i=await fetch(n,{method:"POST",headers:r,body:JSON.stringify({url:t,responseType:e,ua:sa()})});if(!i.ok){const a=i.headers.get("x-proxy-error")||await i.text().catch(()=>"")||`Proxy ${i.status}`;throw new Error(a)}return e==="text"?await i.text():await i.json()},zte=Object.freeze(Object.defineProperty({__proto__:null,proxyFetch:Nj},Symbol.toStringTag,{value:"Module"})),Oa=(t,e,n={})=>{const r=t.serverUrl.replace(/\/$/,""),i=new URLSearchParams({username:t.username,password:t.password,...e?{action:e}:{},...n});return`${r}/player_api.php?${i.toString()}`},Na=async t=>Nj(t,"json"),ps={async authenticate(t){const e=await Na(Oa(t));if(!(e!=null&&e.user_info)||e.user_info.auth===0)throw new Error("Invalid credentials");return e},async getLiveCategories(t){return Na(Oa(t,"get_live_categories"))},async getVodCategories(t){return Na(Oa(t,"get_vod_categories"))},async getSeriesCategories(t){return Na(Oa(t,"get_series_categories"))},async getLiveStreams(t){const[e,n]=await Promise.all([Na(Oa(t,"get_live_streams")),this.getLiveCategories(t)]),r=new Map(n.map(s=>[s.category_id,s.category_name])),i=t.serverUrl.replace(/\/$/,"");return(e||[]).map(s=>({id:String(s.stream_id),name:s.name,category:r.get(String(s.category_id))??"Uncategorized",categoryId:String(s.category_id),streamUrl:`${i}/live/${t.username}/${t.password}/${s.stream_id}.m3u8`,logoUrl:s.stream_icon||void 0,epgChannelId:s.epg_channel_id||void 0}))},async getMovies(t){const[e,n]=await Promise.all([Na(Oa(t,"get_vod_streams")),this.getVodCategories(t)]),r=new Map(n.map(s=>[s.category_id,s.category_name])),i=t.serverUrl.replace(/\/$/,"");return(e||[]).map(s=>({id:String(s.stream_id),name:s.name,category:r.get(String(s.category_id))??"Uncategorized",categoryId:String(s.category_id),streamUrl:`${i}/movie/${t.username}/${t.password}/${s.stream_id}.${s.container_extension||"mp4"}`,posterUrl:s.stream_icon||void 0,rating:s.rating?String(s.rating):void 0,year:s.year||void 0,containerExtension:s.container_extension}))},async getSeries(t){const[e,n]=await Promise.all([Na(Oa(t,"get_series")),this.getSeriesCategories(t)]),r=new Map(n.map(i=>[i.category_id,i.category_name]));return(e||[]).map(i=>({id:String(i.series_id),name:i.name,category:r.get(String(i.category_id))??"Uncategorized",categoryId:String(i.category_id),posterUrl:i.cover||void 0,rating:i.rating?String(i.rating):void 0,plot:i.plot||void 0}))},async getSeriesInfo(t,e){return Na(Oa(t,"get_series_info",{series_id:e}))},async getShortEpg(t,e,n=4){const r=await Na(Oa(t,"get_short_epg",{stream_id:e,limit:String(n)})),i=a=>{try{return typeof atob=="function"?decodeURIComponent(escape(atob(a))):a}catch{return a}};return(Array.isArray(r==null?void 0:r.epg_listings)?r.epg_listings:Array.isArray(r)?r:[]).map(a=>({id:String(a.id??""),title:a.title?i(a.title):"",description:a.description?i(a.description):"",start:a.start||"",end:a.end||"",startTimestamp:Number(a.start_timestamp??0),stopTimestamp:Number(a.stop_timestamp??0),nowPlaying:Number(a.now_playing??0)===1}))},buildSeriesEpisodeUrl(t,e,n){return`${t.serverUrl.replace(/\/$/,"")}/series/${t.username}/${t.password}/${e}.${n}`}},qte="modulepreload",Wte=function(t){return"/nadiplayer/"+t},Jk={},Mj=function(e,n,r){let i=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),o=(a==null?void 0:a.nonce)||(a==null?void 0:a.getAttribute("nonce"));i=Promise.allSettled(n.map(l=>{if(l=Wte(l),l in Jk)return;Jk[l]=!0;const c=l.endsWith(".css"),u=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${u}`))return;const d=document.createElement("link");if(d.rel=c?"stylesheet":qte,c||(d.as="script"),d.crossOrigin="",d.href=l,o&&d.setAttribute("nonce",o),document.head.appendChild(d),c)return new Promise((h,f)=>{d.addEventListener("load",h),d.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${l}`)))})}))}function s(a){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=a,window.dispatchEvent(o),!o.defaultPrevented)throw a}return i.then(a=>{for(const o of a||[])o.status==="rejected"&&s(o.reason);return e().catch(s)})},Zk=t=>{const e=t.split(/\r?\n/),n=[];let r=null;for(let i=0;i<e.length;i++){const s=e[i].trim();if(s.startsWith("#EXTINF")){const a={},o=/([\w-]+)="([^"]*)"/g;let l;for(;(l=o.exec(s))!==null;)a[l[1]]=l[2];const c=s.lastIndexOf(",");r={name:c>=0?s.slice(c+1).trim():"Unknown",logo:a["tvg-logo"],group:a["group-title"]||"Uncategorized",tvgId:a["tvg-id"]}}else s&&!s.startsWith("#")&&r&&(r.url=s,n.push(r),r=null)}return n},Yte=t=>/movie|vod|film|cinema|películas|peliculas/i.test(t),Xte=t=>/serie|series|tv show|shows/i.test(t),eI=t=>/\.(mp4|mkv|avi|mov|webm|ts)(\?|$)/i.test(t),Df={async fetchPlaylist(t){const{proxyFetch:e}=await Mj(async()=>{const{proxyFetch:r}=await Promise.resolve().then(()=>zte);return{proxyFetch:r}},void 0),n=await e(t,"text");return Zk(n)},parsePlaylistText(t){return Zk(t)},classify(t){const e=[],n=[],r=new Map;return t.forEach((i,s)=>{const a=`${s}`;if(Xte(i.group)&&eI(i.url)){const o=i.name.replace(/\s*S\d+\s*E\d+.*$/i,"").trim()||i.name;r.has(o)||r.set(o,{id:`s_${r.size}`,name:o,category:i.group,categoryId:i.group,posterUrl:i.logo})}else Yte(i.group)||eI(i.url)&&!i.url.includes(".m3u8")?n.push({id:a,name:i.name,category:i.group,categoryId:i.group,streamUrl:i.url,posterUrl:i.logo}):e.push({id:a,name:i.name,category:i.group,categoryId:i.group,streamUrl:i.url,logoUrl:i.logo,epgChannelId:i.tvgId})}),{channels:e,movies:n,series:[...r.values()]}}},Qte="",Jte=/^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$/,Bj=t=>Jte.test(t.trim()),dg=async(t,e)=>{const n=await fetch(`${Qte}${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});let r=null;try{r=await n.json()}catch{}if(!n.ok){const i=(r==null?void 0:r.detail)||(typeof r=="object"?JSON.stringify(r):"")||`HTTP ${n.status}`;throw new Error(typeof i=="string"?i:JSON.stringify(i))}return r},_v={async handshake(t,e){return dg("/api/stalker/handshake",{portal_url:t,mac:e})},async fetchAll(t,e){const r=((await dg("/api/stalker/all-channels",{portal_url:t,mac:e})).channels||[]).map(a=>({id:a.id||a.epgChannelId||a.name,name:a.name,category:a.category||"Uncategorized",categoryId:a.categoryId||"0",streamUrl:`stalker-cmd:${a.cmd}`,logoUrl:a.logo||void 0,epgChannelId:a.epgChannelId||void 0}));let i=[];try{i=(await dg("/api/stalker/vod-categories",{portal_url:t,mac:e})).categories||[]}catch{i=[]}const s=i.map(a=>({id:`cat-${a.id}`,name:a.name,category:a.name,categoryId:a.id,streamUrl:""}));return{channels:r,movies:s,series:[]}},async resolveStream(t,e,n){return(await dg("/api/stalker/resolve-stream",{portal_url:t,mac:e,cmd:n})).url}},fA=1e3*60*10,Jd=t=>t.kind==="m3u",Zd=t=>t.kind==="stalker",bv=async t=>{const e=t.m3uContent&&t.m3uContent.trim().length?Df.parsePlaylistText(t.m3uContent):await Df.fetchPlaylist(t.m3uUrl);return Df.classify(e)},xv=async t=>_v.fetchAll(t.portalUrl,t.macAddress),Uj=t=>uh({queryKey:["xtream",t==null?void 0:t.id,"live"],queryFn:async()=>t?Zd(t)?(await xv(t)).channels:Jd(t)?(await bv(t)).channels:ps.getLiveStreams(t):[],enabled:!!t,staleTime:fA}),jj=t=>uh({queryKey:["xtream",t==null?void 0:t.id,"movies"],queryFn:async()=>t?Zd(t)?(await xv(t)).movies:Jd(t)?(await bv(t)).movies:ps.getMovies(t):[],enabled:!!t,staleTime:fA}),Fj=t=>uh({queryKey:["xtream",t==null?void 0:t.id,"series"],queryFn:async()=>t?Zd(t)?(await xv(t)).series:Jd(t)?(await bv(t)).series:ps.getSeries(t):[],enabled:!!t,staleTime:fA}),Sv=()=>{const t=lT();return e=>t.invalidateQueries({queryKey:["xtream",e]})},Zte=(t,e)=>uh({queryKey:["xtream",t==null?void 0:t.id,"epg",e],queryFn:async()=>{if(!t||!e||Jd(t)||Zd(t))return[];try{return await ps.getShortEpg(t,e,6)}catch{return[]}},enabled:!!t&&!!e&&!Jd(t)&&!Zd(t),staleTime:1e3*60*5}),$j=()=>{const t=lT();return async e=>{if(Zd(e)){const s=await xv(e);return t.setQueryData(["xtream",e.id,"live"],s.channels),t.setQueryData(["xtream",e.id,"movies"],s.movies),t.setQueryData(["xtream",e.id,"series"],s.series),s}if(Jd(e)){const s=await bv(e);return t.setQueryData(["xtream",e.id,"live"],s.channels),t.setQueryData(["xtream",e.id,"movies"],s.movies),t.setQueryData(["xtream",e.id,"series"],s.series),s}const[n,r,i]=await Promise.all([ps.getLiveStreams(e),ps.getMovies(e),ps.getSeries(e)]);return t.setQueryData(["xtream",e.id,"live"],n),t.setQueryData(["xtream",e.id,"movies"],r),t.setQueryData(["xtream",e.id,"series"],i),{channels:n,movies:r,series:i}}},m0="nadiplay_managed_profile_id",pA="nadiplay_managed_counts",mA=()=>{try{return localStorage.getItem(m0)}catch(t){return console.warn("[useSubscriberProfileSync] read managed id failed",t),null}},tI=()=>{try{const t=localStorage.getItem(pA);return t?JSON.parse(t):null}catch(t){return console.warn("[useSubscriberProfileSync] read managed counts failed",t),null}},Vj=t=>{try{localStorage.setItem(pA,JSON.stringify({...t,updatedAt:Date.now()})),window.dispatchEvent(new Event("nadiplay-managed-counts-changed"))}catch(e){console.warn("[useSubscriberProfileSync] write managed counts failed",e)}},Of=()=>{try{const t=localStorage.getItem(m0);if(t){const n=JSON.parse(localStorage.getItem("nadiplay_profiles")||"[]").filter(i=>i.id!==t);localStorage.setItem("nadiplay_profiles",JSON.stringify(n)),localStorage.getItem("nadiplay_active_profile")===t&&localStorage.removeItem("nadiplay_active_profile"),localStorage.removeItem(m0),localStorage.removeItem(pA),window.dispatchEvent(new Event("nadiplay-profiles-changed"))}}catch(t){console.warn("[useSubscriberProfileSync] clear managed profile failed",t)}},ene=t=>{const{profiles:e,addProfile:n,updateProfile:r,setActiveProfileId:i}=mo(),s=$j(),a=D.useRef(null);D.useEffect(()=>{if(!t||t.role!=="user"||!Lf()||a.current===t.id)return;let o=!1;return(async()=>{try{const l=await cj();if(o)return;if(l.user.is_expired){Of();return}const c=l.xtream;if(!c.server||!c.username||!c.password){Of(),Mt.message("Your subscription is active but no Xtream server is configured yet. Please contact your admin.");return}const u={name:`${l.user.username} (NADIPLAYER)`,kind:"xtream",serverUrl:c.server,username:c.username,password:c.password},d=mA(),h=d?e.find(p=>p.id===d):void 0;let f;if(h)r(h.id,u),f={...h,...u},i(h.id);else{const p=n(u);try{localStorage.setItem(m0,p.id)}catch(m){console.warn("[useSubscriberProfileSync] persist managed id failed",m)}i(p.id),f=p}a.current=t.id;try{const p=await s(f);Vj({channels:p.channels.length,movies:p.movies.length,series:p.series.length}),Mt.success(`Connected — ${p.channels.length} channels • ${p.movies.length} movies • ${p.series.length} series`)}catch(p){console.warn("[useSubscriberProfileSync] prefetch failed (user can still browse)",p)}}catch(l){console.warn("[useSubscriberProfileSync] sync failed",l)}})(),()=>{o=!0}},[t==null?void 0:t.id,t==null?void 0:t.role])},hg="nadi_is_guest",Gj=D.createContext(void 0),tne=({children:t})=>{const[e,n]=D.useState(()=>yk()),[r,i]=D.useState(()=>{try{return localStorage.getItem(hg)==="1"}catch(d){return console.warn("[useAuth] read guest flag failed",d),!1}}),[s,a]=D.useState(()=>!!Lf()&&!yk());D.useEffect(()=>{if(!Lf()){a(!1);return}let h=!1;return vk().then(f=>{h||n(f)}).catch(f=>{console.warn("[useAuth] token validation failed",f),h||(fb(),n(null))}).finally(()=>{h||a(!1)}),()=>{h=!0}},[]);const o=D.useCallback(async(d,h)=>{const f=await SJ(d,h);bJ(f.access_token,f.user),n(f.user);try{localStorage.removeItem(hg)}catch(p){console.warn("[useAuth] clear guest flag failed",p)}return i(!1),f.user.role!=="user"&&Of(),f.user},[]),l=D.useCallback(()=>{Of(),fb(),n(null);try{localStorage.removeItem(hg)}catch(d){console.warn("[useAuth] clear guest flag failed",d)}i(!1)},[]),c=D.useCallback(()=>{Of();try{localStorage.setItem(hg,"1")}catch(d){console.warn("[useAuth] set guest flag failed",d)}i(!0)},[]),u=D.useCallback(async()=>{if(Lf())try{const d=await vk();n(d)}catch(d){console.warn("[useAuth] refresh failed",d),fb(),n(null)}},[]);return y.jsx(Gj.Provider,{value:{user:e,isGuest:r,loading:s,login:o,logout:l,continueAsGuest:c,refresh:u},children:t})},Bs=()=>{const t=D.useContext(Gj);if(!t)throw new Error("useAuth must be used inside <AuthProvider>");return t},Hj="nadiplay_playback_mode",Kj=()=>{try{return localStorage.getItem(Hj)==="external"?"external":"internal"}catch{return"internal"}},nne=t=>{try{localStorage.setItem(Hj,t)}catch{}},rne=()=>{const{data:t}=uh({queryKey:["public","playback-mode"],queryFn:LJ,staleTime:3e5,refetchOnWindowFocus:!0,retry:1});return D.useEffect(()=>{t&&nne(t.external_player_enabled?"external":"internal")},[t]),t};var zj=typeof global=="object"&&global&&global.Object===Object&&global,ine=typeof self=="object"&&self&&self.Object===Object&&self,wa=zj||ine||Function("return this")(),ma=wa.Symbol,qj=Object.prototype,sne=qj.hasOwnProperty,ane=qj.toString,Hh=ma?ma.toStringTag:void 0;function one(t){var e=sne.call(t,Hh),n=t[Hh];try{t[Hh]=void 0;var r=!0}catch{}var i=ane.call(t);return r&&(e?t[Hh]=n:delete t[Hh]),i}var lne=Object.prototype,cne=lne.toString;function une(t){return cne.call(t)}var dne="[object Null]",hne="[object Undefined]",nI=ma?ma.toStringTag:void 0;function Eh(t){return t==null?t===void 0?hne:dne:nI&&nI in Object(t)?one(t):une(t)}function Uc(t){return t!=null&&typeof t=="object"}var fne="[object Symbol]";function eh(t){return typeof t=="symbol"||Uc(t)&&Eh(t)==fne}function iy(t,e){for(var n=-1,r=t==null?0:t.length,i=Array(r);++n<r;)i[n]=e(t[n],n,t);return i}var qi=Array.isArray,rI=ma?ma.prototype:void 0,iI=rI?rI.toString:void 0;function Wj(t){if(typeof t=="string")return t;if(qi(t))return iy(t,Wj)+"";if(eh(t))return iI?iI.call(t):"";var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}var pne=/\s/;function mne(t){for(var e=t.length;e--&&pne.test(t.charAt(e)););return e}var gne=/^\s+/;function yne(t){return t&&t.slice(0,mne(t)+1).replace(gne,"")}function Al(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var sI=NaN,vne=/^[-+]0x[0-9a-f]+$/i,_ne=/^0b[01]+$/i,bne=/^0o[0-7]+$/i,xne=parseInt;function aI(t){if(typeof t=="number")return t;if(eh(t))return sI;if(Al(t)){var e=typeof t.valueOf=="function"?t.valueOf():t;t=Al(e)?e+"":e}if(typeof t!="string")return t===0?t:+t;t=yne(t);var n=_ne.test(t);return n||bne.test(t)?xne(t.slice(2),n?2:8):vne.test(t)?sI:+t}function dm(t){return t}var Sne="[object AsyncFunction]",Ene="[object Function]",wne="[object GeneratorFunction]",Tne="[object Proxy]";function Yj(t){if(!Al(t))return!1;var e=Eh(t);return e==Ene||e==wne||e==Sne||e==Tne}var xb=wa["__core-js_shared__"],oI=function(){var t=/[^.]+$/.exec(xb&&xb.keys&&xb.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();function Ane(t){return!!oI&&oI in t}var Rne=Function.prototype,Cne=Rne.toString;function Yc(t){if(t!=null){try{return Cne.call(t)}catch{}try{return t+""}catch{}}return""}var Lne=/[\\^$.*+?()[\]{}|]/g,kne=/^\[object .+?Constructor\]$/,Ine=Function.prototype,Pne=Object.prototype,Dne=Ine.toString,One=Pne.hasOwnProperty,Nne=RegExp("^"+Dne.call(One).replace(Lne,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Mne(t){if(!Al(t)||Ane(t))return!1;var e=Yj(t)?Nne:kne;return e.test(Yc(t))}function Bne(t,e){return t==null?void 0:t[e]}function Xc(t,e){var n=Bne(t,e);return Mne(n)?n:void 0}var AE=Xc(wa,"WeakMap");function Une(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}function Kh(){}var jne=800,Fne=16,$ne=Date.now;function Vne(t){var e=0,n=0;return function(){var r=$ne(),i=Fne-(r-n);if(n=r,i>0){if(++e>=jne)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function Gne(t){return function(){return t}}var lI=function(){try{var t=Xc(Object,"defineProperty");return t({},"",{}),t}catch{}}(),Hne=lI?function(t,e){return lI(t,"toString",{configurable:!0,enumerable:!1,value:Gne(e),writable:!0})}:dm,Kne=Vne(Hne);function zne(t,e){for(var n=-1,r=t==null?0:t.length;++n<r&&e(t[n],n,t)!==!1;);return t}function qne(t,e,n,r){for(var i=t.length,s=n+-1;++s<i;)if(e(t[s],s,t))return s;return-1}function Wne(t){return t!==t}function Yne(t,e,n){for(var r=n-1,i=t.length;++r<i;)if(t[r]===e)return r;return-1}function Xne(t,e,n){return e===e?Yne(t,e,n):qne(t,Wne,n)}function Qne(t,e){var n=t==null?0:t.length;return!!n&&Xne(t,e,0)>-1}var Jne=9007199254740991,Zne=/^(?:0|[1-9]\d*)$/;function gA(t,e){var n=typeof t;return e=e??Jne,!!e&&(n=="number"||n!="symbol"&&Zne.test(t))&&t>-1&&t%1==0&&t<e}function yA(t,e){return t===e||t!==t&&e!==e}var cI=Math.max;function ere(t,e,n){return e=cI(e===void 0?t.length-1:e,0),function(){for(var r=arguments,i=-1,s=cI(r.length-e,0),a=Array(s);++i<s;)a[i]=r[e+i];i=-1;for(var o=Array(e+1);++i<e;)o[i]=r[i];return o[e]=n(a),Une(t,this,o)}}function Xj(t,e){return Kne(ere(t,e,dm),t+"")}var tre=9007199254740991;function vA(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=tre}function hm(t){return t!=null&&vA(t.length)&&!Yj(t)}function uI(t,e,n){if(!Al(n))return!1;var r=typeof e;return(r=="number"?hm(n)&&gA(e,n.length):r=="string"&&e in n)?yA(n[e],t):!1}var nre=Object.prototype;function rre(t){var e=t&&t.constructor,n=typeof e=="function"&&e.prototype||nre;return t===n}function ire(t,e){for(var n=-1,r=Array(t);++n<t;)r[n]=e(n);return r}var sre="[object Arguments]";function dI(t){return Uc(t)&&Eh(t)==sre}var Qj=Object.prototype,are=Qj.hasOwnProperty,ore=Qj.propertyIsEnumerable,_A=dI(function(){return arguments}())?dI:function(t){return Uc(t)&&are.call(t,"callee")&&!ore.call(t,"callee")};function lre(){return!1}var Jj=typeof exports=="object"&&exports&&!exports.nodeType&&exports,hI=Jj&&typeof module=="object"&&module&&!module.nodeType&&module,cre=hI&&hI.exports===Jj,fI=cre?wa.Buffer:void 0,ure=fI?fI.isBuffer:void 0,RE=ure||lre,dre="[object Arguments]",hre="[object Array]",fre="[object Boolean]",pre="[object Date]",mre="[object Error]",gre="[object Function]",yre="[object Map]",vre="[object Number]",_re="[object Object]",bre="[object RegExp]",xre="[object Set]",Sre="[object String]",Ere="[object WeakMap]",wre="[object ArrayBuffer]",Tre="[object DataView]",Are="[object Float32Array]",Rre="[object Float64Array]",Cre="[object Int8Array]",Lre="[object Int16Array]",kre="[object Int32Array]",Ire="[object Uint8Array]",Pre="[object Uint8ClampedArray]",Dre="[object Uint16Array]",Ore="[object Uint32Array]",Tn={};Tn[Are]=Tn[Rre]=Tn[Cre]=Tn[Lre]=Tn[kre]=Tn[Ire]=Tn[Pre]=Tn[Dre]=Tn[Ore]=!0;Tn[dre]=Tn[hre]=Tn[wre]=Tn[fre]=Tn[Tre]=Tn[pre]=Tn[mre]=Tn[gre]=Tn[yre]=Tn[vre]=Tn[_re]=Tn[bre]=Tn[xre]=Tn[Sre]=Tn[Ere]=!1;function Nre(t){return Uc(t)&&vA(t.length)&&!!Tn[Eh(t)]}function Zj(t){return function(e){return t(e)}}var eF=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Nf=eF&&typeof module=="object"&&module&&!module.nodeType&&module,Mre=Nf&&Nf.exports===eF,Sb=Mre&&zj.process,pI=function(){try{var t=Nf&&Nf.require&&Nf.require("util").types;return t||Sb&&Sb.binding&&Sb.binding("util")}catch{}}(),mI=pI&&pI.isTypedArray,tF=mI?Zj(mI):Nre,Bre=Object.prototype,Ure=Bre.hasOwnProperty;function jre(t,e){var n=qi(t),r=!n&&_A(t),i=!n&&!r&&RE(t),s=!n&&!r&&!i&&tF(t),a=n||r||i||s,o=a?ire(t.length,String):[],l=o.length;for(var c in t)Ure.call(t,c)&&!(a&&(c=="length"||i&&(c=="offset"||c=="parent")||s&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||gA(c,l)))&&o.push(c);return o}function Fre(t,e){return function(n){return t(e(n))}}var $re=Fre(Object.keys,Object),Vre=Object.prototype,Gre=Vre.hasOwnProperty;function Hre(t){if(!rre(t))return $re(t);var e=[];for(var n in Object(t))Gre.call(t,n)&&n!="constructor"&&e.push(n);return e}function bA(t){return hm(t)?jre(t):Hre(t)}var Kre=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,zre=/^\w*$/;function xA(t,e){if(qi(t))return!1;var n=typeof t;return n=="number"||n=="symbol"||n=="boolean"||t==null||eh(t)?!0:zre.test(t)||!Kre.test(t)||e!=null&&t in Object(e)}var bp=Xc(Object,"create");function qre(){this.__data__=bp?bp(null):{},this.size=0}function Wre(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var Yre="__lodash_hash_undefined__",Xre=Object.prototype,Qre=Xre.hasOwnProperty;function Jre(t){var e=this.__data__;if(bp){var n=e[t];return n===Yre?void 0:n}return Qre.call(e,t)?e[t]:void 0}var Zre=Object.prototype,eie=Zre.hasOwnProperty;function tie(t){var e=this.__data__;return bp?e[t]!==void 0:eie.call(e,t)}var nie="__lodash_hash_undefined__";function rie(t,e){var n=this.__data__;return this.size+=this.has(t)?0:1,n[t]=bp&&e===void 0?nie:e,this}function jc(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}jc.prototype.clear=qre;jc.prototype.delete=Wre;jc.prototype.get=Jre;jc.prototype.has=tie;jc.prototype.set=rie;function iie(){this.__data__=[],this.size=0}function Ev(t,e){for(var n=t.length;n--;)if(yA(t[n][0],e))return n;return-1}var sie=Array.prototype,aie=sie.splice;function oie(t){var e=this.__data__,n=Ev(e,t);if(n<0)return!1;var r=e.length-1;return n==r?e.pop():aie.call(e,n,1),--this.size,!0}function lie(t){var e=this.__data__,n=Ev(e,t);return n<0?void 0:e[n][1]}function cie(t){return Ev(this.__data__,t)>-1}function uie(t,e){var n=this.__data__,r=Ev(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this}function yo(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}yo.prototype.clear=iie;yo.prototype.delete=oie;yo.prototype.get=lie;yo.prototype.has=cie;yo.prototype.set=uie;var xp=Xc(wa,"Map");function die(){this.size=0,this.__data__={hash:new jc,map:new(xp||yo),string:new jc}}function hie(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function wv(t,e){var n=t.__data__;return hie(e)?n[typeof e=="string"?"string":"hash"]:n.map}function fie(t){var e=wv(this,t).delete(t);return this.size-=e?1:0,e}function pie(t){return wv(this,t).get(t)}function mie(t){return wv(this,t).has(t)}function gie(t,e){var n=wv(this,t),r=n.size;return n.set(t,e),this.size+=n.size==r?0:1,this}function vo(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}vo.prototype.clear=die;vo.prototype.delete=fie;vo.prototype.get=pie;vo.prototype.has=mie;vo.prototype.set=gie;var yie="Expected a function";function SA(t,e){if(typeof t!="function"||e!=null&&typeof e!="function")throw new TypeError(yie);var n=function(){var r=arguments,i=e?e.apply(this,r):r[0],s=n.cache;if(s.has(i))return s.get(i);var a=t.apply(this,r);return n.cache=s.set(i,a)||s,a};return n.cache=new(SA.Cache||vo),n}SA.Cache=vo;var vie=500;function _ie(t){var e=SA(t,function(r){return n.size===vie&&n.clear(),r}),n=e.cache;return e}var bie=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,xie=/\\(\\)?/g,Sie=_ie(function(t){var e=[];return t.charCodeAt(0)===46&&e.push(""),t.replace(bie,function(n,r,i,s){e.push(i?s.replace(xie,"$1"):r||n)}),e});function nF(t){return t==null?"":Wj(t)}function rF(t,e){return qi(t)?t:xA(t,e)?[t]:Sie(nF(t))}function Tv(t){if(typeof t=="string"||eh(t))return t;var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function EA(t,e){e=rF(e,t);for(var n=0,r=e.length;t!=null&&n<r;)t=t[Tv(e[n++])];return n&&n==r?t:void 0}function Eie(t,e,n){var r=t==null?void 0:EA(t,e);return r===void 0?n:r}function iF(t,e){for(var n=-1,r=e.length,i=t.length;++n<r;)t[i+n]=e[n];return t}var gI=ma?ma.isConcatSpreadable:void 0;function wie(t){return qi(t)||_A(t)||!!(gI&&t&&t[gI])}function sF(t,e,n,r,i){var s=-1,a=t.length;for(n||(n=wie),i||(i=[]);++s<a;){var o=t[s];n(o)?iF(i,o):r||(i[i.length]=o)}return i}function Tie(){this.__data__=new yo,this.size=0}function Aie(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n}function Rie(t){return this.__data__.get(t)}function Cie(t){return this.__data__.has(t)}var Lie=200;function kie(t,e){var n=this.__data__;if(n instanceof yo){var r=n.__data__;if(!xp||r.length<Lie-1)return r.push([t,e]),this.size=++n.size,this;n=this.__data__=new vo(r)}return n.set(t,e),this.size=n.size,this}function ro(t){var e=this.__data__=new yo(t);this.size=e.size}ro.prototype.clear=Tie;ro.prototype.delete=Aie;ro.prototype.get=Rie;ro.prototype.has=Cie;ro.prototype.set=kie;function aF(t,e){for(var n=-1,r=t==null?0:t.length,i=0,s=[];++n<r;){var a=t[n];e(a,n,t)&&(s[i++]=a)}return s}function Iie(){return[]}var Pie=Object.prototype,Die=Pie.propertyIsEnumerable,yI=Object.getOwnPropertySymbols,Oie=yI?function(t){return t==null?[]:(t=Object(t),aF(yI(t),function(e){return Die.call(t,e)}))}:Iie;function Nie(t,e,n){var r=e(t);return qi(t)?r:iF(r,n(t))}function vI(t){return Nie(t,bA,Oie)}var CE=Xc(wa,"DataView"),LE=Xc(wa,"Promise"),kE=Xc(wa,"Set"),_I="[object Map]",Mie="[object Object]",bI="[object Promise]",xI="[object Set]",SI="[object WeakMap]",EI="[object DataView]",Bie=Yc(CE),Uie=Yc(xp),jie=Yc(LE),Fie=Yc(kE),$ie=Yc(AE),Mo=Eh;(CE&&Mo(new CE(new ArrayBuffer(1)))!=EI||xp&&Mo(new xp)!=_I||LE&&Mo(LE.resolve())!=bI||kE&&Mo(new kE)!=xI||AE&&Mo(new AE)!=SI)&&(Mo=function(t){var e=Eh(t),n=e==Mie?t.constructor:void 0,r=n?Yc(n):"";if(r)switch(r){case Bie:return EI;case Uie:return _I;case jie:return bI;case Fie:return xI;case $ie:return SI}return e});var wI=wa.Uint8Array,Vie="__lodash_hash_undefined__";function Gie(t){return this.__data__.set(t,Vie),this}function Hie(t){return this.__data__.has(t)}function Sp(t){var e=-1,n=t==null?0:t.length;for(this.__data__=new vo;++e<n;)this.add(t[e])}Sp.prototype.add=Sp.prototype.push=Gie;Sp.prototype.has=Hie;function Kie(t,e){for(var n=-1,r=t==null?0:t.length;++n<r;)if(e(t[n],n,t))return!0;return!1}function oF(t,e){return t.has(e)}var zie=1,qie=2;function lF(t,e,n,r,i,s){var a=n&zie,o=t.length,l=e.length;if(o!=l&&!(a&&l>o))return!1;var c=s.get(t),u=s.get(e);if(c&&u)return c==e&&u==t;var d=-1,h=!0,f=n&qie?new Sp:void 0;for(s.set(t,e),s.set(e,t);++d<o;){var p=t[d],m=e[d];if(r)var g=a?r(m,p,d,e,t,s):r(p,m,d,t,e,s);if(g!==void 0){if(g)continue;h=!1;break}if(f){if(!Kie(e,function(b,v){if(!oF(f,v)&&(p===b||i(p,b,n,r,s)))return f.push(v)})){h=!1;break}}else if(!(p===m||i(p,m,n,r,s))){h=!1;break}}return s.delete(t),s.delete(e),h}function Wie(t){var e=-1,n=Array(t.size);return t.forEach(function(r,i){n[++e]=[i,r]}),n}function Yie(t){var e=-1,n=Array(t.size);return t.forEach(function(r){n[++e]=r}),n}var Xie=1,Qie=2,Jie="[object Boolean]",Zie="[object Date]",ese="[object Error]",tse="[object Map]",nse="[object Number]",rse="[object RegExp]",ise="[object Set]",sse="[object String]",ase="[object Symbol]",ose="[object ArrayBuffer]",lse="[object DataView]",TI=ma?ma.prototype:void 0,Eb=TI?TI.valueOf:void 0;function cse(t,e,n,r,i,s,a){switch(n){case lse:if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case ose:return!(t.byteLength!=e.byteLength||!s(new wI(t),new wI(e)));case Jie:case Zie:case nse:return yA(+t,+e);case ese:return t.name==e.name&&t.message==e.message;case rse:case sse:return t==e+"";case tse:var o=Wie;case ise:var l=r&Xie;if(o||(o=Yie),t.size!=e.size&&!l)return!1;var c=a.get(t);if(c)return c==e;r|=Qie,a.set(t,e);var u=lF(o(t),o(e),r,i,s,a);return a.delete(t),u;case ase:if(Eb)return Eb.call(t)==Eb.call(e)}return!1}var use=1,dse=Object.prototype,hse=dse.hasOwnProperty;function fse(t,e,n,r,i,s){var a=n&use,o=vI(t),l=o.length,c=vI(e),u=c.length;if(l!=u&&!a)return!1;for(var d=l;d--;){var h=o[d];if(!(a?h in e:hse.call(e,h)))return!1}var f=s.get(t),p=s.get(e);if(f&&p)return f==e&&p==t;var m=!0;s.set(t,e),s.set(e,t);for(var g=a;++d<l;){h=o[d];var b=t[h],v=e[h];if(r)var S=a?r(v,b,h,e,t,s):r(b,v,h,t,e,s);if(!(S===void 0?b===v||i(b,v,n,r,s):S)){m=!1;break}g||(g=h=="constructor")}if(m&&!g){var E=t.constructor,L=e.constructor;E!=L&&"constructor"in t&&"constructor"in e&&!(typeof E=="function"&&E instanceof E&&typeof L=="function"&&L instanceof L)&&(m=!1)}return s.delete(t),s.delete(e),m}var pse=1,AI="[object Arguments]",RI="[object Array]",fg="[object Object]",mse=Object.prototype,CI=mse.hasOwnProperty;function gse(t,e,n,r,i,s){var a=qi(t),o=qi(e),l=a?RI:Mo(t),c=o?RI:Mo(e);l=l==AI?fg:l,c=c==AI?fg:c;var u=l==fg,d=c==fg,h=l==c;if(h&&RE(t)){if(!RE(e))return!1;a=!0,u=!1}if(h&&!u)return s||(s=new ro),a||tF(t)?lF(t,e,n,r,i,s):cse(t,e,l,n,r,i,s);if(!(n&pse)){var f=u&&CI.call(t,"__wrapped__"),p=d&&CI.call(e,"__wrapped__");if(f||p){var m=f?t.value():t,g=p?e.value():e;return s||(s=new ro),i(m,g,n,r,s)}}return h?(s||(s=new ro),fse(t,e,n,r,i,s)):!1}function wA(t,e,n,r,i){return t===e?!0:t==null||e==null||!Uc(t)&&!Uc(e)?t!==t&&e!==e:gse(t,e,n,r,wA,i)}var yse=1,vse=2;function _se(t,e,n,r){var i=n.length,s=i;if(t==null)return!s;for(t=Object(t);i--;){var a=n[i];if(a[2]?a[1]!==t[a[0]]:!(a[0]in t))return!1}for(;++i<s;){a=n[i];var o=a[0],l=t[o],c=a[1];if(a[2]){if(l===void 0&&!(o in t))return!1}else{var u=new ro,d;if(!(d===void 0?wA(c,l,yse|vse,r,u):d))return!1}}return!0}function cF(t){return t===t&&!Al(t)}function bse(t){for(var e=bA(t),n=e.length;n--;){var r=e[n],i=t[r];e[n]=[r,i,cF(i)]}return e}function uF(t,e){return function(n){return n==null?!1:n[t]===e&&(e!==void 0||t in Object(n))}}function xse(t){var e=bse(t);return e.length==1&&e[0][2]?uF(e[0][0],e[0][1]):function(n){return n===t||_se(n,t,e)}}function Sse(t,e){return t!=null&&e in Object(t)}function Ese(t,e,n){e=rF(e,t);for(var r=-1,i=e.length,s=!1;++r<i;){var a=Tv(e[r]);if(!(s=t!=null&&n(t,a)))break;t=t[a]}return s||++r!=i?s:(i=t==null?0:t.length,!!i&&vA(i)&&gA(a,i)&&(qi(t)||_A(t)))}function wse(t,e){return t!=null&&Ese(t,e,Sse)}var Tse=1,Ase=2;function Rse(t,e){return xA(t)&&cF(e)?uF(Tv(t),e):function(n){var r=Eie(n,t);return r===void 0&&r===e?wse(n,t):wA(e,r,Tse|Ase)}}function Cse(t){return function(e){return e==null?void 0:e[t]}}function Lse(t){return function(e){return EA(e,t)}}function kse(t){return xA(t)?Cse(Tv(t)):Lse(t)}function TA(t){return typeof t=="function"?t:t==null?dm:typeof t=="object"?qi(t)?Rse(t[0],t[1]):xse(t):kse(t)}function Ise(t){return function(e,n,r){for(var i=-1,s=Object(e),a=r(e),o=a.length;o--;){var l=a[++i];if(n(s[l],l,s)===!1)break}return e}}var Pse=Ise();function AA(t,e){return t&&Pse(t,e,bA)}function Dse(t,e){return function(n,r){if(n==null)return n;if(!hm(n))return t(n,r);for(var i=n.length,s=-1,a=Object(n);++s<i&&r(a[s],s,a)!==!1;);return n}}var RA=Dse(AA),wb=function(){return wa.Date.now()},Ose="Expected a function",Nse=Math.max,Mse=Math.min;function dF(t,e,n){var r,i,s,a,o,l,c=0,u=!1,d=!1,h=!0;if(typeof t!="function")throw new TypeError(Ose);e=aI(e)||0,Al(n)&&(u=!!n.leading,d="maxWait"in n,s=d?Nse(aI(n.maxWait)||0,e):s,h="trailing"in n?!!n.trailing:h);function f(U){var O=r,k=i;return r=i=void 0,c=U,a=t.apply(k,O),a}function p(U){return c=U,o=setTimeout(b,e),u?f(U):a}function m(U){var O=U-l,k=U-c,I=e-O;return d?Mse(I,s-k):I}function g(U){var O=U-l,k=U-c;return l===void 0||O>=e||O<0||d&&k>=s}function b(){var U=wb();if(g(U))return v(U);o=setTimeout(b,m(U))}function v(U){return o=void 0,h&&r?f(U):(r=i=void 0,a)}function S(){o!==void 0&&clearTimeout(o),c=0,r=l=i=o=void 0}function E(){return o===void 0?a:v(wb())}function L(){var U=wb(),O=g(U);if(r=arguments,i=this,l=U,O){if(o===void 0)return p(l);if(d)return clearTimeout(o),o=setTimeout(b,e),f(l)}return o===void 0&&(o=setTimeout(b,e)),a}return L.cancel=S,L.flush=E,L}function LI(t){return Uc(t)&&hm(t)}var Bse=200;function Use(t,e,n,r){var i=-1,s=Qne,a=!0,o=t.length,l=[],c=e.length;if(!o)return l;e.length>=Bse&&(s=oF,a=!1,e=new Sp(e));e:for(;++i<o;){var u=t[i],d=u;if(u=u!==0?u:0,a&&d===d){for(var h=c;h--;)if(e[h]===d)continue e;l.push(u)}else s(e,d,r)||l.push(u)}return l}var kI=Xj(function(t,e){return LI(t)?Use(t,sF(e,1,LI,!0)):[]});function hF(t){return typeof t=="function"?t:dm}function II(t,e){var n=qi(t)?zne:RA;return n(t,hF(e))}function jse(t,e){var n=[];return RA(t,function(r,i,s){e(r,i,s)&&n.push(r)}),n}function Tb(t,e){var n=qi(t)?aF:jse;return n(t,TA(e))}function Fse(t,e,n){var r;return n(t,function(i,s,a){if(e(i,s,a))return r=s,!1}),r}function PI(t,e){return Fse(t,TA(e),AA)}function IE(t){return t&&t.length?t[0]:void 0}function $se(t,e){var n=-1,r=hm(t)?Array(t.length):[];return RA(t,function(i,s,a){r[++n]=e(i,s,a)}),r}function Ab(t,e){return t&&AA(t,hF(e))}function Vse(t,e){var n=t.length;for(t.sort(e);n--;)t[n]=t[n].value;return t}function Gse(t,e){if(t!==e){var n=t!==void 0,r=t===null,i=t===t,s=eh(t),a=e!==void 0,o=e===null,l=e===e,c=eh(e);if(!o&&!c&&!s&&t>e||s&&a&&l&&!o&&!c||r&&a&&l||!n&&l||!i)return 1;if(!r&&!s&&!c&&t<e||c&&n&&i&&!r&&!s||o&&n&&i||!a&&i||!l)return-1}return 0}function Hse(t,e,n){for(var r=-1,i=t.criteria,s=e.criteria,a=i.length,o=n.length;++r<a;){var l=Gse(i[r],s[r]);if(l){if(r>=o)return l;var c=n[r];return l*(c=="desc"?-1:1)}}return t.index-e.index}function Kse(t,e,n){e.length?e=iy(e,function(s){return qi(s)?function(a){return EA(a,s.length===1?s[0]:s)}:s}):e=[dm];var r=-1;e=iy(e,Zj(TA));var i=$se(t,function(s,a,o){var l=iy(e,function(c){return c(s)});return{criteria:l,index:++r,value:s}});return Vse(i,function(s,a){return Hse(s,a,n)})}var fF=Xj(function(t,e){if(t==null)return[];var n=e.length;return n>1&&uI(t,e[0],e[1])?e=[]:n>2&&uI(e[0],e[1],e[2])&&(e=[e[0]]),Kse(t,sF(e),[])}),zse="Expected a function";function qse(t,e,n){var r=!0,i=!0;if(typeof t!="function")throw new TypeError(zse);return Al(n)&&(r="leading"in n?!0:r,i="trailing"in n?!1:i),dF(t,e,{leading:r,maxWait:e,trailing:i})}var Wse=0;function Yse(t){var e=++Wse;return nF(t)+e}var nd=function(){return nd=Object.assign||function(e){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},nd.apply(this,arguments)};function Xse(t,e,n){if(arguments.length===2)for(var r=0,i=e.length,s;r<i;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return t.concat(s||Array.prototype.slice.call(e))}var PE;(function(t){t[t.LTR=0]="LTR",t[t.RTL=1]="RTL"})(PE||(PE={}));var rs=PE,rc=typeof window<"u"&&window.document,Rb=rc?window.innerWidth:0,Cb=rc?window.innerHeight:0,Qse=function(){function t(e){rc&&(this.debugCtx=t.createCanvas("sn-debug","1010",e),this.layoutsCtx=t.createCanvas("sn-layouts","1000",e),this.writingDirection=e)}return t.createCanvas=function(e,n,r){var i=document.querySelector("#".concat(e))||document.createElement("canvas");i.setAttribute("id",e),i.setAttribute("dir",r===rs.LTR?"ltr":"rtl");var s=i.getContext("2d");return i.style.zIndex=n,i.style.position="fixed",i.style.top="0",i.style.left="0",document.body.appendChild(i),i.width=Rb,i.height=Cb,s},t.prototype.clear=function(){rc&&this.debugCtx.clearRect(0,0,Rb,Cb)},t.prototype.clearLayouts=function(){rc&&this.layoutsCtx.clearRect(0,0,Rb,Cb)},t.prototype.drawLayout=function(e,n,r){if(rc){this.layoutsCtx.strokeStyle="green",this.layoutsCtx.strokeRect(e.left,e.top,e.width,e.height),this.layoutsCtx.font="8px monospace",this.layoutsCtx.fillStyle="red";var i=this.writingDirection===rs.LTR?"left":"right",s=e[i];this.layoutsCtx.fillText(n,s,e.top+10),this.layoutsCtx.fillText(r,s,e.top+25),this.layoutsCtx.fillText("".concat(i,": ").concat(s),s,e.top+40),this.layoutsCtx.fillText("top: ".concat(e.top),s,e.top+55)}},t.prototype.drawPoint=function(e,n,r,i){r===void 0&&(r="blue"),i===void 0&&(i=10),rc&&(this.debugCtx.strokeStyle=r,this.debugCtx.lineWidth=3,this.debugCtx.strokeRect(e-i/2,n-i/2,i,i))},t}(),Jse=1,DI=function(t){for(var e=t.offsetParent,n=t.offsetHeight,r=t.offsetWidth,i=t.offsetLeft,s=t.offsetTop;e&&e.nodeType===Jse;)i+=e.offsetLeft-e.scrollLeft,s+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{height:n,left:i,top:s,width:r}},Zse=function(t){var e=t&&t.parentElement;if(t&&e){var n=DI(e),r=DI(t),i=r.height,s=r.left,a=r.top,o=r.width,l=s-n.left,c=a-n.top;return{x:l,y:c,width:o,height:i,left:s,top:a,get right(){return this.left+this.width},get bottom(){return this.top+this.height}}}return{x:0,y:0,width:0,height:0,left:0,top:0,right:0,bottom:0}},eae=function(t){if(t&&t.getBoundingClientRect){var e=t.getBoundingClientRect();return{x:e.x,y:e.y,width:e.width,height:e.height,left:e.left,top:e.top,get right(){return this.left+this.width},get bottom(){return this.top+this.height}}}return{x:0,y:0,width:0,height:0,left:0,top:0,right:0,bottom:0}},zl,nf="left",rf="right",Bu="up",ec="down",DE="enter",OI=(zl={},zl[nf]=[37,"ArrowLeft"],zl[Bu]=[38,"ArrowUp"],zl[rf]=[39,"ArrowRight"],zl[ec]=[40,"ArrowDown"],zl[DE]=[13,"Enter"],zl),OE="SN:ROOT",tae=.2,nae=5,rae=1,iae=5,sae=300,NI=["#0FF","#FF0","#F0F"],aae={leading:!0,trailing:!1},oae=function(t,e){var n=e===rs.LTR?function(i){var s=i.layout;return Math.abs(s.left)+Math.abs(s.top)}:function(i){var s=i.layout;return Math.abs(window.innerWidth-s.right)+Math.abs(s.top)},r=fF(t,n);return IE(r)},lae=function(t){var e={};return Object.entries(t).forEach(function(n){var r=n[0],i=n[1];e[r]=Array.isArray(i)?i:[i]}),e},cae=function(){function t(){this.focusableComponents={},this.focusKey=null,this.parentsHavingFocusedChild=[],this.domNodeFocusOptions={},this.enabled=!1,this.nativeMode=!1,this.throttle=0,this.throttleKeypresses=!1,this.useGetBoundingClientRect=!1,this.shouldFocusDOMNode=!1,this.shouldUseNativeEvents=!1,this.writingDirection=rs.LTR,this.pressedKeys={},this.paused=!1,this.keyDownEventListener=null,this.keyUpEventListener=null,this.keyMap=OI,this.pause=this.pause.bind(this),this.resume=this.resume.bind(this),this.setFocus=this.setFocus.bind(this),this.updateAllLayouts=this.updateAllLayouts.bind(this),this.navigateByDirection=this.navigateByDirection.bind(this),this.init=this.init.bind(this),this.setThrottle=this.setThrottle.bind(this),this.destroy=this.destroy.bind(this),this.setKeyMap=this.setKeyMap.bind(this),this.getCurrentFocusKey=this.getCurrentFocusKey.bind(this),this.doesFocusableExist=this.doesFocusableExist.bind(this),this.updateRtl=this.updateRtl.bind(this),this.setFocusDebounced=dF(this.setFocus,sae,{leading:!1,trailing:!0}),this.onUtterText=void 0,this.debug=!1,this.visualDebugger=null,this.logIndex=0,this.distanceCalculationMethod="corners"}return t.getCutoffCoordinate=function(e,n,r,i,s){var a=e?i.top:s===rs.LTR?i.left:i.right,o=e?i.bottom:s===rs.LTR?i.right:i.left;return n?r?a:o:r?o:a},t.getRefCorners=function(e,n,r){var i={a:{x:0,y:0},b:{x:0,y:0}};switch(e){case Bu:{var s=n?r.bottom:r.top;i.a={x:r.left,y:s},i.b={x:r.right,y:s};break}case ec:{var s=n?r.top:r.bottom;i.a={x:r.left,y:s},i.b={x:r.right,y:s};break}case nf:{var a=n?r.right:r.left;i.a={x:a,y:r.top},i.b={x:a,y:r.bottom};break}case rf:{var a=n?r.left:r.right;i.a={x:a,y:r.top},i.b={x:a,y:r.bottom};break}}return i},t.isAdjacentSlice=function(e,n,r){var i=e.a,s=e.b,a=n.a,o=n.b,l=r?"x":"y",c=i[l],u=s[l],d=a[l],h=o[l],f=(u-c)*tae,p=Math.max(0,Math.min(u,h)-Math.max(c,d));return p>=f},t.getPrimaryAxisDistance=function(e,n,r){var i=e.a,s=n.a,a=r?"y":"x";return Math.abs(s[a]-i[a])},t.getSecondaryAxisDistance=function(e,n,r,i,s){if(s)return s(e,n,r,i);var a=e.a,o=e.b,l=n.a,c=n.b,u=r?"x":"y",d=a[u],h=o[u],f=l[u],p=c[u];if(i==="center"){var m=(d+h)/2,g=(f+p)/2;return Math.abs(m-g)}if(i==="edges"){var b=Math.min(d,h),v=Math.min(f,p),S=Math.max(d,h),E=Math.max(f,p),L=Math.abs(b-v),U=Math.abs(S-E);return Math.min(L,U)}var O=[Math.abs(f-d),Math.abs(f-h),Math.abs(p-d),Math.abs(p-h)];return Math.min.apply(Math,O)},t.prototype.sortSiblingsByPriority=function(e,n,r,i){var s=this,a=r===ec||r===Bu,o=t.getRefCorners(r,!1,n);return fF(e,function(l){var c=t.getRefCorners(r,!0,l.layout),u=t.isAdjacentSlice(o,c,a),d=u?t.getPrimaryAxisDistance:t.getSecondaryAxisDistance,h=u?t.getSecondaryAxisDistance:t.getPrimaryAxisDistance,f=d(o,c,a,s.distanceCalculationMethod,s.customDistanceCalculationFunction),p=h(o,c,a,s.distanceCalculationMethod,s.customDistanceCalculationFunction),m=f*iae+p,g=(m+1)/(u?nae:rae);return s.log("smartNavigate","distance (primary, secondary, total weighted) for ".concat(l.focusKey," relative to ").concat(i," is"),f,p,m),s.log("smartNavigate","priority for ".concat(l.focusKey," relative to ").concat(i," is"),g),s.visualDebugger&&(s.visualDebugger.drawPoint(c.a.x,c.a.y,"yellow",6),s.visualDebugger.drawPoint(c.b.x,c.b.y,"yellow",6)),g})},t.prototype.init=function(e){var n=this,r=e===void 0?{}:e,i=r.debug,s=i===void 0?!1:i,a=r.visualDebug,o=a===void 0?!1:a,l=r.nativeMode,c=l===void 0?!1:l,u=r.throttle,d=u===void 0?0:u,h=r.throttleKeypresses,f=h===void 0?!1:h,p=r.useGetBoundingClientRect,m=p===void 0?!1:p,g=r.shouldFocusDOMNode,b=g===void 0?!1:g,v=r.domNodeFocusOptions,S=v===void 0?{}:v,E=r.shouldUseNativeEvents,L=E===void 0?!1:E,U=r.rtl,O=U===void 0?!1:U,k=r.distanceCalculationMethod,I=k===void 0?"corners":k,R=r.customDistanceCalculationFunction,M=R===void 0?void 0:R,z=r.onUtterText;if(!this.enabled){if(this.domNodeFocusOptions=S,this.enabled=!0,this.nativeMode=c,this.throttleKeypresses=f,this.useGetBoundingClientRect=m,this.shouldFocusDOMNode=b&&!c,this.shouldUseNativeEvents=L,this.writingDirection=O?rs.RTL:rs.LTR,this.distanceCalculationMethod=I,this.customDistanceCalculationFunction=M,this.onUtterText=z??void 0,this.debug=s,this.nativeMode)console.warn("nativeMode option is deprecated and will be removed in the next version.");else if(Number.isInteger(d)&&d>0&&(this.throttle=d),this.bindEventHandlers(),o){this.visualDebugger=new Qse(this.writingDirection);var Z=function(){requestAnimationFrame(function(){n.visualDebugger.clearLayouts(),Ab(n.focusableComponents,function(W,re){n.visualDebugger.drawLayout(W.layout,re,W.parentFocusKey)}),Z()})};Z()}}},t.prototype.setThrottle=function(e){var n=e===void 0?{}:e,r=n.throttle,i=r===void 0?0:r,s=n.throttleKeypresses,a=s===void 0?!1:s;this.throttleKeypresses=a,this.nativeMode||(this.unbindEventHandlers(),Number.isInteger(i)&&(this.throttle=i),this.bindEventHandlers())},t.prototype.destroy=function(){this.enabled&&(this.enabled=!1,this.nativeMode=!1,this.throttle=0,this.throttleKeypresses=!1,this.focusKey=null,this.parentsHavingFocusedChild=[],this.focusableComponents={},this.paused=!1,this.keyMap=OI,this.onUtterText=void 0,this.unbindEventHandlers())},t.prototype.getEventType=function(e){return PI(this.getKeyMap(),function(n){return n.includes(e)})},t.getKeyCode=function(e){return e.keyCode||e.code||e.key},t.prototype.bindEventHandlers=function(){var e=this;typeof window<"u"&&window.addEventListener&&(this.keyDownEventListener=function(n){if(e.paused!==!0){e.debug&&(e.logIndex+=1);var r=t.getKeyCode(n),i=e.getEventType(r);if(i){e.pressedKeys[i]=e.pressedKeys[i]?e.pressedKeys[i]+1:1,e.shouldUseNativeEvents||(n.preventDefault(),n.stopPropagation());var s={pressedKeys:e.pressedKeys};if(i===DE&&e.focusKey){e.onEnterPress(s);return}var a=e.onArrowPress(i,s)===!1;if(e.visualDebugger&&e.visualDebugger.clear(),a)e.log("keyDownEventListener","default navigation prevented");else{var o=PI(e.getKeyMap(),function(l){return l.includes(r)});e.smartNavigate(o,null,{event:n})}}}},this.throttle&&(this.keyDownEventListenerThrottled=qse(this.keyDownEventListener.bind(this),this.throttle,aae)),this.keyUpEventListener=function(n){var r=t.getKeyCode(n),i=e.getEventType(r);delete e.pressedKeys[i],e.throttle&&!e.throttleKeypresses&&e.keyDownEventListenerThrottled.cancel(),i===DE&&e.focusKey&&e.onEnterRelease(),e.focusKey&&(i===nf||i===rf||i===Bu||i===ec)&&e.onArrowRelease(i)},window.addEventListener("keyup",this.keyUpEventListener),window.addEventListener("keydown",this.throttle?this.keyDownEventListenerThrottled:this.keyDownEventListener))},t.prototype.unbindEventHandlers=function(){if(typeof window<"u"&&window.removeEventListener){window.removeEventListener("keyup",this.keyUpEventListener),this.keyUpEventListener=null;var e=this.throttle?this.keyDownEventListenerThrottled:this.keyDownEventListener;window.removeEventListener("keydown",e),this.keyDownEventListener=null}},t.prototype.onEnterPress=function(e){var n=this.focusableComponents[this.focusKey];if(!n){this.log("onEnterPress","noComponent");return}if(!n.focusable){this.log("onEnterPress","componentNotFocusable");return}n.onEnterPress&&n.onEnterPress(e)},t.prototype.onEnterRelease=function(){var e=this.focusableComponents[this.focusKey];if(!e){this.log("onEnterRelease","noComponent");return}if(!e.focusable){this.log("onEnterRelease","componentNotFocusable");return}e.onEnterRelease&&e.onEnterRelease()},t.prototype.onArrowPress=function(e,n){var r=this.focusableComponents[this.focusKey];if(!r){this.log("onArrowPress","noComponent");return}return r&&r.onArrowPress&&r.onArrowPress(e,n)},t.prototype.onArrowRelease=function(e){var n=this.focusableComponents[this.focusKey];if(!n){this.log("onArrowRelease","noComponent");return}if(!n.focusable){this.log("onArrowRelease","componentNotFocusable");return}n.onArrowRelease&&n.onArrowRelease(e)},t.prototype.navigateByDirection=function(e,n){if(n===void 0&&(n={}),!(this.paused===!0||!this.enabled||this.nativeMode)){var r=[ec,Bu,nf,rf];r.includes(e)?(this.log("navigateByDirection","direction",e),this.smartNavigate(e,null,n)):this.log("navigateByDirection","Invalid direction. You passed: `".concat(e,"`, but you can use only these: "),r)}},t.prototype.smartNavigate=function(e,n,r){var i=this;if(!this.nativeMode){var s=e===ec||e===Bu,a=e===ec||(this.writingDirection===rs.LTR?e===rf:e===nf);this.log("smartNavigate","direction",e),this.log("smartNavigate","fromParentFocusKey",n),this.log("smartNavigate","this.focusKey",this.focusKey),n||Ab(this.focusableComponents,function(S){S.layoutUpdated=!1});var o=this.focusableComponents[n||this.focusKey];if(!n&&!o){var l=this.getForcedFocusKey();l?this.setFocus(l):this.log("smartNavigate","Aborted due to missing current component and force-focusable key");return}if(this.log("smartNavigate","currentComponent",o?o.focusKey:void 0,o?o.node:void 0,o),o){this.updateLayout(o.focusKey);var c=o.parentFocusKey,u=o.focusKey,d=o.layout,h=t.getCutoffCoordinate(s,a,!1,d,this.writingDirection),f=Tb(this.focusableComponents,function(S){if(S.parentFocusKey===c&&S.focusable){i.updateLayout(S.focusKey);var E=t.getCutoffCoordinate(s,a,!0,S.layout,i.writingDirection);return s||i.writingDirection===rs.LTR?a?E>=h:E<=h:a?E<=h:E>=h}return!1});if(this.debug&&(this.log("smartNavigate","currentCutoffCoordinate",h),this.log("smartNavigate","siblings","".concat(f.length," elements:"),f.map(function(S){return S.focusKey}).join(", "),f.map(function(S){return S.node}),f.map(function(S){return S}))),this.visualDebugger){var p=t.getRefCorners(e,!1,d);this.visualDebugger.drawPoint(p.a.x,p.a.y),this.visualDebugger.drawPoint(p.b.x,p.b.y)}var m=this.sortSiblingsByPriority(f,d,e,u),g=IE(m);if(this.log("smartNavigate","nextComponent",g?g.focusKey:void 0,g?g.node:void 0,g),g)this.setFocus(g.focusKey,r);else{var b=this.focusableComponents[c],v=b!=null&&b.isFocusBoundary?b.focusBoundaryDirections||[e]:[];(!b||!v.includes(e))&&this.smartNavigate(e,c,r)}}}},t.prototype.saveLastFocusedChildKey=function(e,n){e&&(this.log("saveLastFocusedChildKey","".concat(e.focusKey," lastFocusedChildKey set"),n),e.lastFocusedChildKey=n)},t.prototype.log=function(e,n){for(var r=[],i=2;i<arguments.length;i++)r[i-2]=arguments[i];this.debug&&console.log.apply(console,Xse(["%c".concat(e,"%c").concat(n),"background: ".concat(NI[this.logIndex%NI.length],"; color: black; padding: 1px 5px;"),"background: #333; color: #BADA55; padding: 1px 5px;"],r,!1))},t.prototype.getCurrentFocusKey=function(){return this.focusKey},t.prototype.getForcedFocusKey=function(){var e,n=Tb(this.focusableComponents,function(i){return i.focusable&&i.forceFocus}),r=this.sortSiblingsByPriority(n,{x:0,y:0,width:0,height:0,left:0,top:0,right:0,bottom:0,node:null},"down",OE);return(e=IE(r))===null||e===void 0?void 0:e.focusKey},t.prototype.getNextFocusKey=function(e){var n=this,r=this.focusableComponents[e];if(!r||this.nativeMode)return e;var i=Tb(this.focusableComponents,function(l){return l.parentFocusKey===e&&l.focusable});if(i.length>0){var s=r.lastFocusedChildKey,a=r.preferredChildFocusKey;if(this.log("getNextFocusKey","lastFocusedChildKey is",s),this.log("getNextFocusKey","preferredChildFocusKey is",a),s&&r.saveLastFocusedChild&&this.isParticipatingFocusableComponent(s))return this.log("getNextFocusKey","lastFocusedChildKey will be focused",s),this.getNextFocusKey(s);if(a&&this.isParticipatingFocusableComponent(a))return this.log("getNextFocusKey","preferredChildFocusKey will be focused",a),this.getNextFocusKey(a);i.forEach(function(l){return n.updateLayout(l.focusKey)});var o=oae(i,this.writingDirection).focusKey;return this.log("getNextFocusKey","childKey will be focused",o),this.getNextFocusKey(o)}return this.log("getNextFocusKey","targetFocusKey",e),e},t.prototype.addFocusable=function(e){var n=e.focusKey,r=e.node,i=e.parentFocusKey,s=e.onEnterPress,a=e.onEnterRelease,o=e.onArrowPress,l=e.onArrowRelease,c=e.onFocus,u=e.onBlur,d=e.saveLastFocusedChild,h=e.trackChildren,f=e.onUpdateFocus,p=e.onUpdateHasFocusedChild,m=e.preferredChildFocusKey,g=e.autoRestoreFocus,b=e.forceFocus,v=e.focusable,S=e.isFocusBoundary,E=e.focusBoundaryDirections,L=e.accessibilityLabel;if(this.focusableComponents[n]={focusKey:n,node:r,parentFocusKey:i,onEnterPress:s,onEnterRelease:a,onArrowPress:o,onArrowRelease:l,onFocus:c,onBlur:u,onUpdateFocus:f,onUpdateHasFocusedChild:p,saveLastFocusedChild:d,trackChildren:h,preferredChildFocusKey:m,focusable:v,isFocusBoundary:S,focusBoundaryDirections:E,autoRestoreFocus:g,forceFocus:b,accessibilityLabel:L,lastFocusedChildKey:null,layout:{x:0,y:0,width:0,height:0,left:0,top:0,right:0,bottom:0,node:r},layoutUpdated:!1},r||console.warn('Component added without a node reference. This will result in its coordinates being empty and may cause lost focus. Check the "ref" passed to "useFocusable": ',this.focusableComponents[n]),!this.nativeMode){this.updateLayout(n),this.log("addFocusable","Component added: ",this.focusableComponents[n]),n===this.focusKey&&this.setFocus(m||n);for(var U=this.focusableComponents[this.focusKey];U;){if(U.parentFocusKey===n){this.updateParentsHasFocusedChild(this.focusKey,{}),this.updateParentsLastFocusedChild(this.focusKey);break}U=this.focusableComponents[U.parentFocusKey]}}},t.prototype.removeFocusable=function(e){var n=e.focusKey,r=this.focusableComponents[n];if(r){var i=r.parentFocusKey,s=r.onUpdateFocus;s(!1),this.log("removeFocusable","Component removed: ",r),delete this.focusableComponents[n];var a=this.parentsHavingFocusedChild.includes(n);this.parentsHavingFocusedChild=this.parentsHavingFocusedChild.filter(function(c){return c!==n});var o=this.focusableComponents[i],l=n===this.focusKey;if(o&&o.lastFocusedChildKey===n&&(o.lastFocusedChildKey=null),this.nativeMode)return;(l||a)&&o&&o.autoRestoreFocus&&(this.log("removeFocusable","Component removed: ",l?"Leaf component":"Container component","Auto restoring focus to: ",i),this.setFocusDebounced(i))}},t.prototype.getNodeLayoutByFocusKey=function(e){var n=this.focusableComponents[e];return n?(this.updateLayout(n.focusKey),n.layout):null},t.prototype.setCurrentFocusedKey=function(e,n){var r,i,s,a;if(this.isFocusableComponent(this.focusKey)&&e!==this.focusKey){var o=this.focusableComponents[this.focusKey];o.onUpdateFocus(!1),o.onBlur(this.getNodeLayoutByFocusKey(this.focusKey),n),(i=(r=o.node)===null||r===void 0?void 0:r.removeAttribute)===null||i===void 0||i.call(r,"data-focused"),this.log("setCurrentFocusedKey","onBlur",o)}if(this.focusKey=e,this.isFocusableComponent(this.focusKey)){var l=this.focusableComponents[this.focusKey];this.shouldFocusDOMNode&&l.node&&l.node.focus(this.domNodeFocusOptions),(a=(s=l.node)===null||s===void 0?void 0:s.setAttribute)===null||a===void 0||a.call(s,"data-focused","true"),l.onUpdateFocus(!0),l.onFocus(this.getNodeLayoutByFocusKey(this.focusKey),n),this.log("setCurrentFocusedKey","onFocus",l)}},t.prototype.updateParentsHasFocusedChild=function(e,n){for(var r=this,i=[],s=this.focusableComponents[e];s;){var a=s.parentFocusKey,o=this.focusableComponents[a];if(o){var l=o.focusKey;i.push(l)}s=o}var c=kI(this.parentsHavingFocusedChild,i),u=kI(i,this.parentsHavingFocusedChild);II(c,function(d){var h=r.focusableComponents[d];h&&h.trackChildren&&h.onUpdateHasFocusedChild(!1),r.onIntermediateNodeBecameBlurred(d,n)}),II(u,function(d){var h=r.focusableComponents[d];h&&h.trackChildren&&h.onUpdateHasFocusedChild(!0),r.onIntermediateNodeBecameFocused(d,n)}),this.parentsHavingFocusedChild=i},t.prototype.updateParentsLastFocusedChild=function(e){for(var n=this.focusableComponents[e];n;){var r=n.parentFocusKey,i=this.focusableComponents[r];i&&this.saveLastFocusedChildKey(i,n.focusKey),n=i}},t.prototype.getKeyMap=function(){return this.keyMap},t.prototype.setKeyMap=function(e){this.keyMap=nd(nd({},this.getKeyMap()),lae(e))},t.prototype.isFocusableComponent=function(e){return!!this.focusableComponents[e]},t.prototype.isParticipatingFocusableComponent=function(e){return this.isFocusableComponent(e)&&this.focusableComponents[e].focusable},t.prototype.onIntermediateNodeBecameFocused=function(e,n){this.isParticipatingFocusableComponent(e)&&this.focusableComponents[e].onFocus(this.getNodeLayoutByFocusKey(e),n)},t.prototype.onIntermediateNodeBecameBlurred=function(e,n){this.isParticipatingFocusableComponent(e)&&this.focusableComponents[e].onBlur(this.getNodeLayoutByFocusKey(e),n)},t.prototype.pause=function(){this.paused=!0},t.prototype.resume=function(){this.paused=!1},t.prototype.utterAccessibilityLabels=function(e){var n=this;if(this.onUtterText&&e!==this.focusKey){var r=this.focusableComponents[e];if(r){for(var i=[],s=this.focusableComponents[e];s;){var a=s.parentFocusKey,o=this.focusableComponents[a];o&&i.push(a),s=o}var l=i.filter(function(u){return!n.parentsHavingFocusedChild.includes(u)});l.reverse();var c=[];l.forEach(function(u){var d=n.focusableComponents[u];d!=null&&d.accessibilityLabel&&c.push(d.accessibilityLabel)}),r.accessibilityLabel&&c.push(r.accessibilityLabel),c.length>0&&this.onUtterText(c.join(", "))}}},t.prototype.setFocus=function(e,n){if(n===void 0&&(n={}),this.setFocusDebounced.cancel(),!!this.enabled){if(this.log("setFocus","focusKey",e),(!e||e===OE)&&(e=this.getForcedFocusKey(),!e)){this.log("setFocus","Aborted due to missing force-focusable key");return}var r=this.getNextFocusKey(e);if(!r){this.log("setFocus","Aborted due to missing next focus key");return}this.log("setFocus","newFocusKey",r),this.utterAccessibilityLabels(r),this.setCurrentFocusedKey(r,n),this.updateParentsHasFocusedChild(r,n),this.updateParentsLastFocusedChild(r)}},t.prototype.updateAllLayouts=function(){var e=this;!this.enabled||this.nativeMode||Ab(this.focusableComponents,function(n,r){e.updateLayout(r)})},t.prototype.updateLayout=function(e){var n=this.focusableComponents[e];if(!(!n||this.nativeMode||n.layoutUpdated)){var r=n.node,i=this.useGetBoundingClientRect?eae(r):Zse(r);n.layout=nd(nd({},i),{node:r})}},t.prototype.updateFocusable=function(e,n){var r=n.node,i=n.preferredChildFocusKey,s=n.focusable,a=n.isFocusBoundary,o=n.focusBoundaryDirections,l=n.onEnterPress,c=n.onEnterRelease,u=n.onArrowPress,d=n.onFocus,h=n.onBlur,f=n.accessibilityLabel;if(!this.nativeMode){var p=this.focusableComponents[e];p&&(p.preferredChildFocusKey=i,p.focusable=s,p.isFocusBoundary=a,p.focusBoundaryDirections=o,p.onEnterPress=l,p.onEnterRelease=c,p.onArrowPress=u,p.onFocus=d,p.onBlur=h,p.accessibilityLabel=f,r&&(p.node=r))}},t.prototype.isNativeMode=function(){return this.nativeMode},t.prototype.doesFocusableExist=function(e){return!!this.focusableComponents[e]},t.prototype.updateRtl=function(e){this.writingDirection=e?rs.RTL:rs.LTR},t}(),zr=new cae,uae=zr.init;zr.setThrottle;zr.destroy;zr.setKeyMap;zr.setFocus;zr.navigateByDirection;zr.pause;zr.resume;zr.updateAllLayouts;zr.getCurrentFocusKey;zr.doesFocusableExist;zr.updateRtl;var Av=D.createContext(OE);Av.displayName="FocusContext";var dae=function(){return D.useContext(Av)},hae=function(t){var e=t===void 0?{}:t,n=e.focusable,r=n===void 0?!0:n,i=e.saveLastFocusedChild,s=i===void 0?!0:i,a=e.trackChildren,o=a===void 0?!1:a,l=e.autoRestoreFocus,c=l===void 0?!0:l,u=e.forceFocus,d=u===void 0?!1:u,h=e.isFocusBoundary,f=h===void 0?!1:h,p=e.focusBoundaryDirections,m=e.focusKey,g=e.preferredChildFocusKey,b=e.onEnterPress,v=b===void 0?Kh:b,S=e.onEnterRelease,E=S===void 0?Kh:S,L=e.onArrowPress,U=L===void 0?function(){return!0}:L,O=e.onArrowRelease,k=O===void 0?Kh:O,I=e.onFocus,R=I===void 0?Kh:I,M=e.onBlur,z=M===void 0?Kh:M,Z=e.extraProps,W=e.accessibilityLabel,re=D.useCallback(function(je){v(Z,je)},[v,Z]),X=D.useCallback(function(){E(Z)},[E,Z]),oe=D.useCallback(function(je,Me){return U(je,Z,Me)},[Z,U]),Q=D.useCallback(function(je){k(je,Z)},[k,Z]),G=D.useCallback(function(je,Me){R(je,Z,Me)},[Z,R]),H=D.useCallback(function(je,Me){z(je,Z,Me)},[Z,z]),Y=D.useRef(null),ie=D.useState(!1),Ce=ie[0],Le=ie[1],ke=D.useState(!1),Ne=ke[0],ye=ke[1],Ie=dae(),Ae=D.useMemo(function(){return m||Yse("sn:focusable-item-")},[m]),Ee=D.useCallback(function(je){je===void 0&&(je={}),zr.setFocus(Ae,je)},[Ae]);return D.useEffect(function(){var je=Y.current;return zr.addFocusable({focusKey:Ae,node:je,parentFocusKey:Ie,preferredChildFocusKey:g,onEnterPress:re,onEnterRelease:X,onArrowPress:oe,onArrowRelease:Q,onFocus:G,onBlur:H,onUpdateFocus:function(Me){return Me===void 0&&(Me=!1),Le(Me)},onUpdateHasFocusedChild:function(Me){return Me===void 0&&(Me=!1),ye(Me)},saveLastFocusedChild:s,trackChildren:o,isFocusBoundary:f,focusBoundaryDirections:p,autoRestoreFocus:c,forceFocus:d,focusable:r,accessibilityLabel:W}),function(){zr.removeFocusable({focusKey:Ae})}},[]),D.useEffect(function(){var je=Y.current;zr.updateFocusable(Ae,{node:je,preferredChildFocusKey:g,focusable:r,isFocusBoundary:f,focusBoundaryDirections:p,onEnterPress:re,onEnterRelease:X,onArrowPress:oe,onArrowRelease:Q,onFocus:G,onBlur:H,accessibilityLabel:W})},[Ae,g,r,f,p,re,X,oe,Q,G,H,W]),{ref:Y,focusSelf:Ee,focused:Ce,hasFocusedChild:Ne,focusKey:Ae}},Rv=hae;let cc=null,uc=null;const fae="nadiplay_nav_sounds";function pF(){if(typeof window>"u")return!1;const t=localStorage.getItem(fae);return t!==null?t==="1":!0}function pae(){if(!(typeof window>"u"))try{cc=new Audio("/audio/nav-move.mp3"),cc.preload="auto",cc.volume=.4,uc=new Audio("/audio/nav-select.mp3"),uc.preload="auto",uc.volume=.5}catch(t){console.warn("Failed to preload nav sounds:",t)}}function mF(){if(pF())try{cc||(cc=new Audio("/audio/nav-move.mp3"),cc.volume=.4);const t=cc.cloneNode();t.volume=.4,t.play().catch(()=>{})}catch{}}function g0(){if(pF())try{uc||(uc=new Audio("/audio/nav-select.mp3"),uc.volume=.5);const t=uc.cloneNode();t.volume=.5,t.play().catch(()=>{})}catch{}}let MI=!1;const mae=()=>{if(MI)return;MI=!0,pae();const t=(()=>{try{return localStorage.getItem("nadiplay_sn_debug")==="1"}catch{return!1}})();uae({debug:t,visualDebug:t,throttle:80,throttleKeypresses:!0})},gae=({children:t})=>{D.useEffect(()=>{mae()},[]);const{ref:e,focusKey:n}=Rv({focusable:!1,trackChildren:!0,isFocusBoundary:!1});return y.jsx(Av.Provider,{value:n,children:y.jsx("div",{ref:e,style:{display:"contents"},children:t})})},Cv=D.forwardRef(({className:t,focusClassName:e,focusKey:n,onClick:r,onEnter:i,subtle:s,children:a,disabled:o,...l},c)=>{const{ref:u,focused:d}=Rv({focusKey:n,focusable:!o,onEnterPress:()=>{var f;o||(g0(),(f=i??r)==null||f({currentTarget:u.current}))},onFocus:()=>{mF()},extraProps:{label:typeof a=="string"?a:void 0}});D.useImperativeHandle(c,()=>u.current);const h=f=>{g0(),r==null||r(f)};return y.jsx("button",{ref:u,"data-focused":d||void 0,disabled:o,onClick:h,className:oi(s?"focusable focusable-chip":"focusable",d&&"is-focused",t,d&&e),...l,children:a})});Cv.displayName="FocusableButton";const Fc=D.forwardRef(({className:t,focusKey:e,onClick:n,onEnter:r,subtle:i,children:s,...a},o)=>{const{ref:l,focused:c}=Rv({focusKey:e,onEnterPress:()=>{var d;g0(),(d=r??n)==null||d({currentTarget:l.current})},onFocus:({node:d})=>{mF(),d&&d.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})}});D.useImperativeHandle(o,()=>l.current);const u=d=>{g0(),n==null||n(d)};return y.jsx("div",{ref:l,role:"button",tabIndex:-1,"data-focused":c||void 0,onClick:u,className:oi("focusable",!i&&"focusable-tile",c&&"is-focused",t),...a,children:s})});Fc.displayName="FocusableTile";const Rl=({focusKey:t,className:e,trap:n,children:r,as:i="div",...s})=>{const{ref:a,focusKey:o}=Rv({focusKey:t,focusable:!1,trackChildren:!0,isFocusBoundary:!!n,saveLastFocusedChild:!0}),l=i;return y.jsx(Av.Provider,{value:o,children:y.jsx(l,{ref:a,className:oi(e),...s,children:r})})},{slice:yae,forEach:vae}=[];function _ae(t){return vae.call(yae.call(arguments,1),e=>{if(e)for(const n in e)t[n]===void 0&&(t[n]=e[n])}),t}function bae(t){return typeof t!="string"?!1:[/<\s*script.*?>/i,/<\s*\/\s*script\s*>/i,/<\s*img.*?on\w+\s*=/i,/<\s*\w+\s*on\w+\s*=.*?>/i,/javascript\s*:/i,/vbscript\s*:/i,/expression\s*\(/i,/eval\s*\(/i,/alert\s*\(/i,/document\.cookie/i,/document\.write\s*\(/i,/window\.location/i,/innerHTML/i].some(n=>n.test(t))}const BI=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,xae=function(t,e){const r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},i=encodeURIComponent(e);let s=`${t}=${i}`;if(r.maxAge>0){const a=r.maxAge-0;if(Number.isNaN(a))throw new Error("maxAge should be a Number");s+=`; Max-Age=${Math.floor(a)}`}if(r.domain){if(!BI.test(r.domain))throw new TypeError("option domain is invalid");s+=`; Domain=${r.domain}`}if(r.path){if(!BI.test(r.path))throw new TypeError("option path is invalid");s+=`; Path=${r.path}`}if(r.expires){if(typeof r.expires.toUTCString!="function")throw new TypeError("option expires is invalid");s+=`; Expires=${r.expires.toUTCString()}`}if(r.httpOnly&&(s+="; HttpOnly"),r.secure&&(s+="; Secure"),r.sameSite)switch(typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite){case!0:s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"strict":s+="; SameSite=Strict";break;case"none":s+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return r.partitioned&&(s+="; Partitioned"),s},UI={create(t,e,n,r){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};n&&(i.expires=new Date,i.expires.setTime(i.expires.getTime()+n*60*1e3)),r&&(i.domain=r),document.cookie=xae(t,e,i)},read(t){const e=`${t}=`,n=document.cookie.split(";");for(let r=0;r<n.length;r++){let i=n[r];for(;i.charAt(0)===" ";)i=i.substring(1,i.length);if(i.indexOf(e)===0)return i.substring(e.length,i.length)}return null},remove(t,e){this.create(t,"",-1,e)}};var Sae={name:"cookie",lookup(t){let{lookupCookie:e}=t;if(e&&typeof document<"u")return UI.read(e)||void 0},cacheUserLanguage(t,e){let{lookupCookie:n,cookieMinutes:r,cookieDomain:i,cookieOptions:s}=e;n&&typeof document<"u"&&UI.create(n,t,r,i,s)}},Eae={name:"querystring",lookup(t){var r;let{lookupQuerystring:e}=t,n;if(typeof window<"u"){let{search:i}=window.location;!window.location.search&&((r=window.location.hash)==null?void 0:r.indexOf("?"))>-1&&(i=window.location.hash.substring(window.location.hash.indexOf("?")));const a=i.substring(1).split("&");for(let o=0;o<a.length;o++){const l=a[o].indexOf("=");l>0&&a[o].substring(0,l)===e&&(n=a[o].substring(l+1))}}return n}},wae={name:"hash",lookup(t){var i;let{lookupHash:e,lookupFromHashIndex:n}=t,r;if(typeof window<"u"){const{hash:s}=window.location;if(s&&s.length>2){const a=s.substring(1);if(e){const o=a.split("&");for(let l=0;l<o.length;l++){const c=o[l].indexOf("=");c>0&&o[l].substring(0,c)===e&&(r=o[l].substring(c+1))}}if(r)return r;if(!r&&n>-1){const o=s.match(/\/([a-zA-Z-]*)/g);return Array.isArray(o)?(i=o[typeof n=="number"?n:0])==null?void 0:i.replace("/",""):void 0}}}return r}};let gu=null;const jI=()=>{if(gu!==null)return gu;try{if(gu=typeof window<"u"&&window.localStorage!==null,!gu)return!1;const t="i18next.translate.boo";window.localStorage.setItem(t,"foo"),window.localStorage.removeItem(t)}catch{gu=!1}return gu};var Tae={name:"localStorage",lookup(t){let{lookupLocalStorage:e}=t;if(e&&jI())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupLocalStorage:n}=e;n&&jI()&&window.localStorage.setItem(n,t)}};let yu=null;const FI=()=>{if(yu!==null)return yu;try{if(yu=typeof window<"u"&&window.sessionStorage!==null,!yu)return!1;const t="i18next.translate.boo";window.sessionStorage.setItem(t,"foo"),window.sessionStorage.removeItem(t)}catch{yu=!1}return yu};var Aae={name:"sessionStorage",lookup(t){let{lookupSessionStorage:e}=t;if(e&&FI())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupSessionStorage:n}=e;n&&FI()&&window.sessionStorage.setItem(n,t)}},Rae={name:"navigator",lookup(t){const e=[];if(typeof navigator<"u"){const{languages:n,userLanguage:r,language:i}=navigator;if(n)for(let s=0;s<n.length;s++)e.push(n[s]);r&&e.push(r),i&&e.push(i)}return e.length>0?e:void 0}},Cae={name:"htmlTag",lookup(t){let{htmlTag:e}=t,n;const r=e||(typeof document<"u"?document.documentElement:null);return r&&typeof r.getAttribute=="function"&&(n=r.getAttribute("lang")),n}},Lae={name:"path",lookup(t){var i;let{lookupFromPathIndex:e}=t;if(typeof window>"u")return;const n=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(n)?(i=n[typeof e=="number"?e:0])==null?void 0:i.replace("/",""):void 0}},kae={name:"subdomain",lookup(t){var i,s;let{lookupFromSubdomainIndex:e}=t;const n=typeof e=="number"?e+1:1,r=typeof window<"u"&&((s=(i=window.location)==null?void 0:i.hostname)==null?void 0:s.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i));if(r)return r[n]}};let gF=!1;try{document.cookie,gF=!0}catch{}const yF=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];gF||yF.splice(1,1);const Iae=()=>({order:yF,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:t=>t});class vF{constructor(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(e,n)}init(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=e,this.options=_ae(n,this.options||{},Iae()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=i=>i.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=r,this.addDetector(Sae),this.addDetector(Eae),this.addDetector(Tae),this.addDetector(Aae),this.addDetector(Rae),this.addDetector(Cae),this.addDetector(Lae),this.addDetector(kae),this.addDetector(wae)}addDetector(e){return this.detectors[e.name]=e,this}detect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,n=[];return e.forEach(r=>{if(this.detectors[r]){let i=this.detectors[r].lookup(this.options);i&&typeof i=="string"&&(i=[i]),i&&(n=n.concat(i))}}),n=n.filter(r=>r!=null&&!bae(r)).map(r=>this.options.convertDetectedLanguage(r)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?n:n.length>0?n[0]:null}cacheUserLanguage(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;n&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||n.forEach(r=>{this.detectors[r]&&this.detectors[r].cacheUserLanguage(e,this.options)}))}}vF.type="languageDetector";const Mf=[{code:"en",label:"English",flag:"🇬🇧",dir:"ltr"},{code:"ar",label:"العربية",flag:"🇸🇦",dir:"rtl"},{code:"fr",label:"Français",flag:"🇫🇷",dir:"ltr"},{code:"es",label:"Español",flag:"🇪🇸",dir:"ltr"},{code:"ru",label:"Русский",flag:"🇷🇺",dir:"ltr"},{code:"ko",label:"한국어",flag:"🇰🇷",dir:"ltr"},{code:"fil",label:"Filipino",flag:"🇵🇭",dir:"ltr"}],it={translation:{common:{cancel:"Cancel",save:"Save",saving:"Saving...",delete:"Delete",edit:"Edit",close:"Close",loading:"Loading...",connect:"Connect",connecting:"Connecting...",refresh:"Refresh",back:"Back",logout:"Logout",search:"Search",all:"All",yes:"Yes",no:"No",timeshift:"Timeshift",active:"Active",setActive:"Set Active",test:"Test",username:"Username",password:"Password",add:"Add",create:"Create",update:"Update",open:"Open",retry:"Retry"},welcome:{title:"NADIPLAYER",chooseHowToContinue:"Choose how to continue",guest:"GUEST",guestHint:"Enter with your own Xtream server — manage everything locally.",enter:"Enter",login:"LOGIN",loginHint:"Subscribers: sign in with the username & password provided by your admin.",signIn:"Sign In",premiumTag:"Premium IPTV Experience",language:"Language"},login:{subtitle:"Subscriber Sign-In",username:"Username",password:"Password",submit:"Sign In",submitting:"Signing in...",contactAdmin:"No account? Contact your NADIPLAYER administrator to get credentials.",back:"Back"},home:{logout:"Logout",profile:"Profile",guestMode:"Guest Mode",connected:"Connected.",awaiting:"Awaiting server sync.",waiting:"Waiting to connect.",subscriber:"Subscriber",expires:"Expires",noExpiry:"No expiry set",daysRemaining_one:"{{count}} day remaining",daysRemaining_other:"{{count}} days remaining",expired:"EXPIRED",timeshift:"Timeshift",categories:{liveTv:"Live TV",movies:"Movies",series:"Series",liveTvCount:"+5000 Channels",moviesCount:"+1200 Movies",seriesCount:"+500 Series"},infoBar:"LIVE: +5000 Channels. MOVIES: +1200 Titles. SERIES: +500 Series."},expired:{title:"SUBSCRIPTION EXPIRED",hi:"Hi",message:"Your NADIPLAYER subscription has ended. To continue watching, please contact us on WhatsApp to renew.",contactWhatsapp:"Contact on WhatsApp",signOut:"Sign Out",whatsappPrefill:"Hi, my NADIPLAYER subscription ({{username}}) has expired. I'd like to renew."},splash:{tagline:"Tune In to the Universe",premiumTag:"Premium IPTV Experience"},pageLayout:{weatherCity:"Los Angeles 24°"},notFound:{title:"404",message:"Oops! Page not found",goHome:"Return to Home"},account:{title:"ACCOUNT",profilesCount_one:"{{count}} profile",profilesCount_other:"{{count}} profiles",addServer:"Add Server",devicePairing:"Device Pairing",devicePairingDesc:"Link a Smart TV or streaming device to your IPTV account using a 6-digit PIN — no typing long URLs on your remote.",imOnDevice:"I'm on the Device",iHavePin:"I have a PIN",playbackMode:"Playback Mode",playbackModeDesc:"Where streams open when you click a channel. External opens the stream directly in your chosen player app — each viewer streams from their own IP, so providers can't ban a shared app IP.",internal:"Internal (built-in)",external:"External",externalOn:"External player mode on",internalOn:"Internal player mode on",externalPlayer:"External Player",externalPlayerDesc:"The app that opens when you click a channel in External mode. VidoPlay is the default — install it once, then enjoy one-tap launch on every channel.",default:"DEFAULT",install:"Install",externalPlayerSet:"External player → {{name}}",playerIdentity:"Player Identity",playerIdentityDesc:"The User-Agent header sent with stream & API requests. Choose the one your IPTV provider expects.",sending:"Sending",userAgentSet:"User-Agent → {{name}}",noProfiles:"No profiles yet",noProfilesDesc:"Add an Xtream Codes server to get started.",profileName:"Profile Name",serverUrl:"Server URL",user:"user",profileUpdated:"Profile updated",playlistReloaded:"Playlist reloaded",profileRemoved:"Profile removed",confirmDelete:"Delete this profile?",connectedSuccess:"{{name}} connected successfully",connectFailed:"{{name}}: {{error}}",reloadPlaylist:"Reload Playlist"},liveTV:{title:"LIVE TV",searchPlaceholder:"Search channels…",noActiveServer:"No active server.",addProfile:"Add a profile",contactAdmin:"Contact your admin",favs:"Favs",listView:"List view",gridView:"Grid view",selectChannel:"Select a channel",failedLoad:"Failed to load. Check credentials.",noChannels:"No channels found.",nowPrefix:"Now: {{title}}",reopen:"Re-open",channels_one:"{{count}} channel",channels_other:"{{count}} channels",epgFor:"EPG · {{name}}",openingInApp:"Opening {{channel}} in {{app}}",sentToApp:"Sent to {{app}}. Install the APK for reliable auto-launch.",couldntOpen:"Couldn't open {{app}}. Install it from Account → External Player."},movies:{title:"MOVIES",searchPlaceholder:"Search movies...",noActiveServer:"No active server.",addProfile:"Add a profile",contactAdmin:"Contact your admin",failedLoad:"Failed to load movies."},series:{title:"SERIES",searchPlaceholder:"Search series...",noActiveServer:"No active server.",addProfile:"Add a profile",contactAdmin:"Contact your admin",failedLoad:"Failed to load series.",season:"Season {{n}}",episodePrefix:"E{{n}}"},addServer:{title:"ADD PLAYLIST",xtreamTab:"Xtream Codes",m3uTab:"M3U URL",advanced:"Advanced",shared:"Shared",ownServer:"Own server",sharedHint:"Uses the Xtream server configured by the admin in Global Settings.",ownHint:"Enter your personal Xtream server credentials.",loadingShared:"Loading shared server details...",sharedNotConfigured:"The admin hasn't configured a shared server yet. Switch to Own server or ask your admin to set it up.",autoFilled:"Shared server · Auto-filled from Global Settings",profileNamePlaceholder:"Profile Name (e.g., Family TV)",serverUrlPlaceholder:"Server URL (http://...)",usernamePlaceholder:"Username",passwordPlaceholder:"Password",m3uPlaceholder:"https://example.com/playlist.m3u",hintShared:"Pick Shared to reuse the NADIPLAYER global server.",hintOwn:"Enter your Xtream Codes credentials to load TV, Movies & Series.",hintM3u:"Paste any M3U / M3U8 playlist URL to import."},admin:{title:"NADIPLAYER ADMIN",subtitle:"Subscriber Control Panel",logout:"Logout",settingsHeading:"GLOBAL SETTINGS",whatsapp:"WhatsApp (e.g. +15551234567)",sharedServer:"Shared Xtream Server",sharedUsername:"Shared Xtream Username",sharedPassword:"Shared Xtream Password",saveSettings:"Save Settings",settingsSaved:"Settings saved",createHeading:"CREATE SUBSCRIBER",usernameLabel:"Username",passwordLabel:"Password",daysLabel:"Days",xtreamMode:"Xtream Mode",modeShared:"Shared (global)",modeOwn:"Own server (per-user)",serverUrl:"Xtream Server URL",xtreamUsername:"Xtream Username",xtreamPassword:"Xtream Password",createUser:"Create User",creating:"Creating...",userCreated:"User created",subscribersHeading:"SUBSCRIBERS ({{count}})",noSubscribers:"No subscribers yet.",noExpiry:"no expiry",daysLeft_one:"{{count}} day left",daysLeft_other:"{{count}} days left",expired:"EXPIRED",advanced:"Advanced",server:"Server",xtUser:"Xt. User",xtPass:"Xt. Pass",saveXtream:"Save Xtream",xtreamSaved:"Xtream saved",newPassword:"New password",updatePassword:"Update password",passwordUpdated:"Password updated",addDays:"+{{n}}d",subDays:"-{{n}}d",dayAdded_one:"Added {{count}} day",dayAdded_other:"Added {{count}} days",dayRemoved_one:"Removed {{count}} day",dayRemoved_other:"Removed {{count}} days",deleteUser:"Delete",userDeleted:"User deleted",confirmDeleteUser:'Delete user "{{username}}"?',loadFailed:"Failed to load",opFailed:"Failed"}}},Pae={translation:{common:{cancel:"إلغاء",save:"حفظ",saving:"جاري الحفظ...",delete:"حذف",edit:"تعديل",close:"إغلاق",loading:"جاري التحميل...",connect:"اتصال",connecting:"جاري الاتصال...",refresh:"تحديث",back:"رجوع",logout:"تسجيل الخروج",search:"بحث",all:"الكل",yes:"نعم",no:"لا",timeshift:"تقديم وتأخير",active:"نشط",setActive:"تفعيل",test:"اختبار",username:"اسم المستخدم",password:"كلمة المرور",add:"إضافة",create:"إنشاء",update:"تحديث",open:"فتح",retry:"إعادة المحاولة"},welcome:{title:"NADIPLAYER",chooseHowToContinue:"اختر كيفية المتابعة",guest:"ضيف",guestHint:"ادخل بسيرفر Xtream الخاص بك — تحكم بكل شيء محليا.",enter:"دخول",login:"تسجيل الدخول",loginHint:"للمشتركين: سجل الدخول باسم المستخدم وكلمة المرور من المسؤول.",signIn:"تسجيل الدخول",premiumTag:"تجربة IPTV مميزة",language:"اللغة"},login:{subtitle:"تسجيل دخول المشترك",username:"اسم المستخدم",password:"كلمة المرور",submit:"تسجيل الدخول",submitting:"جاري تسجيل الدخول...",contactAdmin:"لا يوجد حساب؟ تواصل مع مسؤول NADIPLAYER للحصول على بيانات الاعتماد.",back:"رجوع"},home:{logout:"تسجيل الخروج",profile:"الملف",guestMode:"وضع الضيف",connected:"متصل.",awaiting:"بانتظار مزامنة السيرفر.",waiting:"بانتظار الاتصال.",subscriber:"مشترك",expires:"ينتهي في",noExpiry:"بدون تاريخ انتهاء",daysRemaining_zero:"لا أيام متبقية",daysRemaining_one:"متبقي يوم واحد",daysRemaining_two:"متبقي يومان",daysRemaining_few:"متبقي {{count}} أيام",daysRemaining_many:"متبقي {{count}} يوما",daysRemaining_other:"متبقي {{count}} يوم",expired:"منتهي",timeshift:"تقديم وتأخير",categories:{liveTv:"بث مباشر",movies:"أفلام",series:"مسلسلات",liveTvCount:"+5000 قناة",moviesCount:"+1200 فيلم",seriesCount:"+500 مسلسل"},infoBar:"مباشر: +5000 قناة. أفلام: +1200 عنوان. مسلسلات: +500 مسلسل."},expired:{title:"انتهى الاشتراك",hi:"مرحبا",message:"لقد انتهى اشتراك NADIPLAYER الخاص بك. لمتابعة المشاهدة، يرجى التواصل معنا عبر واتساب لتجديد الاشتراك.",contactWhatsapp:"تواصل عبر واتساب",signOut:"تسجيل الخروج",whatsappPrefill:"مرحبا، انتهى اشتراك NADIPLAYER الخاص بي ({{username}}). أرغب بالتجديد."},splash:{tagline:"اضبط على الكون",premiumTag:"تجربة IPTV مميزة"},pageLayout:{weatherCity:"لوس أنجلوس 24°"},notFound:{title:"404",message:"عذرا! الصفحة غير موجودة",goHome:"العودة إلى الرئيسية"},account:{title:"الحساب",profilesCount_zero:"لا ملفات شخصية",profilesCount_one:"ملف شخصي واحد",profilesCount_two:"ملفان شخصيان",profilesCount_few:"{{count}} ملفات شخصية",profilesCount_many:"{{count}} ملفا شخصيا",profilesCount_other:"{{count}} ملف شخصي",addServer:"إضافة سيرفر",devicePairing:"إقران الجهاز",devicePairingDesc:"اربط تلفزيون ذكي أو جهاز بث بحساب IPTV الخاص بك باستخدام رمز PIN مكون من 6 أرقام - دون كتابة روابط طويلة على جهاز التحكم.",imOnDevice:"أنا على الجهاز",iHavePin:"لدي رمز PIN",playbackMode:"وضع التشغيل",playbackModeDesc:"أين تفتح المشاهدات عند الضغط على قناة. الوضع الخارجي يفتح مباشرة في مشغلك المفضل — كل مشاهد يبث من IP الخاص به، لذا لا يمكن لمزودي الخدمة حظر IP التطبيق المشترك.",internal:"داخلي (مدمج)",external:"خارجي",externalOn:"تم تفعيل المشغل الخارجي",internalOn:"تم تفعيل المشغل الداخلي",externalPlayer:"المشغل الخارجي",externalPlayerDesc:"التطبيق الذي يفتح عند الضغط على قناة في الوضع الخارجي. VidoPlay هو الافتراضي — ثبته مرة واحدة ثم استمتع بفتح بنقرة واحدة لكل قناة.",default:"افتراضي",install:"تثبيت",externalPlayerSet:"المشغل الخارجي ← {{name}}",playerIdentity:"هوية المشغل",playerIdentityDesc:"ترويسة User-Agent المرسلة مع طلبات البث وواجهة API. اختر الذي يتوقعه مزود IPTV.",sending:"إرسال",userAgentSet:"User-Agent ← {{name}}",noProfiles:"لا توجد ملفات شخصية بعد",noProfilesDesc:"أضف سيرفر Xtream Codes للبدء.",profileName:"اسم الملف الشخصي",serverUrl:"رابط السيرفر",user:"المستخدم",profileUpdated:"تم تحديث الملف الشخصي",playlistReloaded:"تم إعادة تحميل القائمة",profileRemoved:"تم حذف الملف الشخصي",confirmDelete:"حذف هذا الملف الشخصي؟",connectedSuccess:"تم الاتصال بـ {{name}} بنجاح",connectFailed:"{{name}}: {{error}}",reloadPlaylist:"إعادة تحميل القائمة"},liveTV:{title:"البث المباشر",searchPlaceholder:"ابحث عن قنوات…",noActiveServer:"لا يوجد سيرفر نشط.",addProfile:"أضف ملفا شخصيا",contactAdmin:"تواصل مع المسؤول",favs:"المفضلة",listView:"عرض قائمة",gridView:"عرض شبكي",selectChannel:"اختر قناة",failedLoad:"فشل التحميل. تحقق من بيانات الاعتماد.",noChannels:"لم يتم العثور على قنوات.",nowPrefix:"الآن: {{title}}",reopen:"إعادة الفتح",channels_one:"قناة واحدة",channels_other:"{{count}} قناة",epgFor:"دليل البرامج · {{name}}",openingInApp:"جاري فتح {{channel}} في {{app}}",sentToApp:"تم الإرسال إلى {{app}}. ثبت APK للتشغيل التلقائي الموثوق.",couldntOpen:"تعذر فتح {{app}}. ثبته من الحساب ← المشغل الخارجي."},movies:{title:"الأفلام",searchPlaceholder:"ابحث عن أفلام...",noActiveServer:"لا يوجد سيرفر نشط.",addProfile:"أضف ملفا شخصيا",contactAdmin:"تواصل مع المسؤول",failedLoad:"فشل تحميل الأفلام."},series:{title:"المسلسلات",searchPlaceholder:"ابحث عن مسلسلات...",noActiveServer:"لا يوجد سيرفر نشط.",addProfile:"أضف ملفا شخصيا",contactAdmin:"تواصل مع المسؤول",failedLoad:"فشل تحميل المسلسلات.",season:"الموسم {{n}}",episodePrefix:"ح{{n}}"},addServer:{title:"إضافة قائمة",xtreamTab:"Xtream Codes",m3uTab:"رابط M3U",advanced:"متقدم",shared:"مشترك",ownServer:"سيرفر خاص",sharedHint:"يستخدم سيرفر Xtream الذي ضبطه المسؤول في الإعدادات العامة.",ownHint:"أدخل بيانات اعتماد سيرفر Xtream الخاص بك.",loadingShared:"جاري تحميل تفاصيل السيرفر المشترك...",sharedNotConfigured:"لم يقم المسؤول بضبط سيرفر مشترك بعد. بدل إلى سيرفر خاص أو اطلب من المسؤول ضبطه.",autoFilled:"سيرفر مشترك · تم التعبئة من الإعدادات العامة",profileNamePlaceholder:"اسم الملف (مثال: تلفزيون العائلة)",serverUrlPlaceholder:"رابط السيرفر (http://...)",usernamePlaceholder:"اسم المستخدم",passwordPlaceholder:"كلمة المرور",m3uPlaceholder:"https://example.com/playlist.m3u",hintShared:"اختر مشترك لاستخدام سيرفر NADIPLAYER العام.",hintOwn:"أدخل بيانات Xtream Codes لتحميل التلفزيون والأفلام والمسلسلات.",hintM3u:"الصق أي رابط قائمة M3U / M3U8 للاستيراد."},admin:{title:"إدارة NADIPLAYER",subtitle:"لوحة التحكم بالمشتركين",logout:"تسجيل الخروج",settingsHeading:"الإعدادات العامة",whatsapp:"واتساب (مثال +15551234567)",sharedServer:"سيرفر Xtream المشترك",sharedUsername:"اسم مستخدم Xtream المشترك",sharedPassword:"كلمة مرور Xtream المشتركة",saveSettings:"حفظ الإعدادات",settingsSaved:"تم حفظ الإعدادات",createHeading:"إنشاء مشترك",usernameLabel:"اسم المستخدم",passwordLabel:"كلمة المرور",daysLabel:"الأيام",xtreamMode:"وضع Xtream",modeShared:"مشترك (عام)",modeOwn:"سيرفر خاص (لكل مستخدم)",serverUrl:"رابط سيرفر Xtream",xtreamUsername:"اسم مستخدم Xtream",xtreamPassword:"كلمة مرور Xtream",createUser:"إنشاء مستخدم",creating:"جاري الإنشاء...",userCreated:"تم إنشاء المستخدم",subscribersHeading:"المشتركون ({{count}})",noSubscribers:"لا يوجد مشتركون بعد.",noExpiry:"بدون انتهاء",daysLeft_zero:"لا أيام متبقية",daysLeft_one:"متبقي يوم واحد",daysLeft_two:"متبقي يومان",daysLeft_few:"متبقي {{count}} أيام",daysLeft_many:"متبقي {{count}} يوما",daysLeft_other:"متبقي {{count}} يوم",expired:"منتهي",advanced:"متقدم",server:"السيرفر",xtUser:"مستخدم Xt",xtPass:"كلمة Xt",saveXtream:"حفظ Xtream",xtreamSaved:"تم حفظ Xtream",newPassword:"كلمة مرور جديدة",updatePassword:"تحديث كلمة المرور",passwordUpdated:"تم تحديث كلمة المرور",addDays:"+{{n}} يوم",subDays:"-{{n}} يوم",dayAdded_one:"تمت إضافة يوم واحد",dayAdded_other:"تمت إضافة {{count}} أيام",dayRemoved_one:"تم حذف يوم واحد",dayRemoved_other:"تم حذف {{count}} أيام",deleteUser:"حذف",userDeleted:"تم حذف المستخدم",confirmDeleteUser:'حذف المستخدم "{{username}}"؟',loadFailed:"فشل التحميل",opFailed:"فشل"}}},Dae={translation:{...it.translation,welcome:{...it.translation.welcome,chooseHowToContinue:"Choisissez comment continuer",guest:"INVITÉ",guestHint:"Entrez avec votre propre serveur Xtream — gérez tout localement.",enter:"Entrer",login:"CONNEXION",loginHint:"Abonnés : connectez-vous avec le nom d'utilisateur et le mot de passe fournis par votre administrateur.",signIn:"Se connecter",premiumTag:"Expérience IPTV Premium",language:"Langue"},login:{...it.translation.login,subtitle:"Connexion Abonné",username:"Nom d'utilisateur",password:"Mot de passe",submit:"Se connecter",submitting:"Connexion...",contactAdmin:"Pas de compte ? Contactez votre administrateur NADIPLAYER pour obtenir les identifiants.",back:"Retour"},home:{...it.translation.home,logout:"Déconnexion",profile:"Profil",guestMode:"Mode Invité",connected:"Connecté.",awaiting:"En attente de synchronisation.",waiting:"En attente de connexion.",subscriber:"Abonné",expires:"Expire le",noExpiry:"Aucune date d'expiration",daysRemaining_one:"{{count}} jour restant",daysRemaining_other:"{{count}} jours restants",expired:"EXPIRÉ",timeshift:"Timeshift",categories:{...it.translation.home.categories,liveTv:"TV en direct",movies:"Films",series:"Séries",liveTvCount:"+5000 Chaînes",moviesCount:"+1200 Films",seriesCount:"+500 Séries"},infoBar:"DIRECT : +5000 Chaînes. FILMS : +1200. SÉRIES : +500."},expired:{...it.translation.expired,title:"ABONNEMENT EXPIRÉ",hi:"Bonjour",message:"Votre abonnement NADIPLAYER a pris fin. Pour continuer à regarder, contactez-nous sur WhatsApp pour renouveler.",contactWhatsapp:"Contacter sur WhatsApp",signOut:"Se déconnecter",whatsappPrefill:"Bonjour, mon abonnement NADIPLAYER ({{username}}) a expiré. Je souhaite renouveler."},splash:{tagline:"Branchez-vous sur l'univers",premiumTag:"Expérience IPTV Premium"},notFound:{...it.translation.notFound,message:"Oups ! Page introuvable",goHome:"Retour à l'accueil"},liveTV:{...it.translation.liveTV,title:"TV EN DIRECT",searchPlaceholder:"Rechercher des chaînes…",noActiveServer:"Aucun serveur actif.",addProfile:"Ajouter un profil",favs:"Favoris",selectChannel:"Sélectionnez une chaîne",noChannels:"Aucune chaîne trouvée.",failedLoad:"Échec du chargement. Vérifiez les identifiants.",channels_one:"{{count}} chaîne",channels_other:"{{count}} chaînes"},movies:{...it.translation.movies,title:"FILMS",searchPlaceholder:"Rechercher des films...",noActiveServer:"Aucun serveur actif.",addProfile:"Ajouter un profil",failedLoad:"Échec du chargement des films."},series:{...it.translation.series,title:"SÉRIES",searchPlaceholder:"Rechercher des séries...",noActiveServer:"Aucun serveur actif.",addProfile:"Ajouter un profil",failedLoad:"Échec du chargement des séries.",season:"Saison {{n}}"},addServer:{...it.translation.addServer,title:"AJOUTER UNE LISTE",advanced:"Avancé",shared:"Partagé",ownServer:"Serveur propre",profileNamePlaceholder:"Nom du profil (ex. TV Famille)",usernamePlaceholder:"Nom d'utilisateur",passwordPlaceholder:"Mot de passe"},admin:{...it.translation.admin,title:"NADIPLAYER ADMIN",subtitle:"Panneau de contrôle des abonnés",settingsHeading:"PARAMÈTRES GLOBAUX",createHeading:"CRÉER UN ABONNÉ",subscribersHeading:"ABONNÉS ({{count}})",createUser:"Créer l'utilisateur",saveSettings:"Enregistrer"},account:{...it.translation.account,title:"COMPTE",addServer:"Ajouter un serveur",devicePairing:"Appairage d'appareil",playbackMode:"Mode de lecture",externalPlayer:"Lecteur externe",playerIdentity:"Identité du lecteur"}}},Oae={translation:{...it.translation,welcome:{...it.translation.welcome,chooseHowToContinue:"Elige cómo continuar",guest:"INVITADO",guestHint:"Entra con tu propio servidor Xtream — gestiona todo localmente.",enter:"Entrar",login:"INICIAR SESIÓN",loginHint:"Suscriptores: inicia sesión con el usuario y contraseña que te dio tu administrador.",signIn:"Iniciar Sesión",premiumTag:"Experiencia IPTV Premium",language:"Idioma"},login:{...it.translation.login,subtitle:"Acceso de Suscriptor",username:"Usuario",password:"Contraseña",submit:"Iniciar Sesión",submitting:"Accediendo...",contactAdmin:"¿No tienes cuenta? Contacta a tu administrador de NADIPLAYER para obtener credenciales.",back:"Atrás"},home:{...it.translation.home,logout:"Cerrar Sesión",profile:"Perfil",guestMode:"Modo Invitado",connected:"Conectado.",awaiting:"Esperando sincronización.",waiting:"Esperando conexión.",subscriber:"Suscriptor",expires:"Expira",noExpiry:"Sin fecha de expiración",daysRemaining_one:"Queda {{count}} día",daysRemaining_other:"Quedan {{count}} días",expired:"EXPIRADO",categories:{...it.translation.home.categories,liveTv:"TV en Vivo",movies:"Películas",series:"Series",liveTvCount:"+5000 Canales",moviesCount:"+1200 Películas",seriesCount:"+500 Series"},infoBar:"EN VIVO: +5000 Canales. PELÍCULAS: +1200. SERIES: +500."},expired:{...it.translation.expired,title:"SUSCRIPCIÓN EXPIRADA",hi:"Hola",message:"Tu suscripción NADIPLAYER ha finalizado. Para seguir viendo, contáctanos por WhatsApp para renovar.",contactWhatsapp:"Contactar por WhatsApp",signOut:"Cerrar Sesión",whatsappPrefill:"Hola, mi suscripción NADIPLAYER ({{username}}) ha expirado. Me gustaría renovarla."},splash:{tagline:"Sintoniza con el universo",premiumTag:"Experiencia IPTV Premium"},notFound:{...it.translation.notFound,message:"¡Ups! Página no encontrada",goHome:"Volver al inicio"},liveTV:{...it.translation.liveTV,title:"TV EN VIVO",searchPlaceholder:"Buscar canales…",noActiveServer:"Sin servidor activo.",addProfile:"Añadir perfil",favs:"Favs",selectChannel:"Selecciona un canal",noChannels:"No se encontraron canales.",channels_one:"{{count}} canal",channels_other:"{{count}} canales"},movies:{...it.translation.movies,title:"PELÍCULAS",searchPlaceholder:"Buscar películas...",noActiveServer:"Sin servidor activo.",addProfile:"Añadir perfil",failedLoad:"Error al cargar películas."},series:{...it.translation.series,title:"SERIES",searchPlaceholder:"Buscar series...",noActiveServer:"Sin servidor activo.",addProfile:"Añadir perfil",failedLoad:"Error al cargar series.",season:"Temporada {{n}}"},addServer:{...it.translation.addServer,title:"AÑADIR PLAYLIST",advanced:"Avanzado",shared:"Compartido",ownServer:"Servidor propio"},admin:{...it.translation.admin,subtitle:"Panel de control de suscriptores",settingsHeading:"AJUSTES GLOBALES",createHeading:"CREAR SUSCRIPTOR",subscribersHeading:"SUSCRIPTORES ({{count}})",createUser:"Crear usuario",saveSettings:"Guardar"},account:{...it.translation.account,title:"CUENTA",addServer:"Añadir servidor",devicePairing:"Emparejar dispositivo",playbackMode:"Modo de reproducción",externalPlayer:"Reproductor externo",playerIdentity:"Identidad del reproductor"}}},Nae={translation:{...it.translation,welcome:{...it.translation.welcome,chooseHowToContinue:"Выберите, как продолжить",guest:"ГОСТЬ",guestHint:"Войдите со своим собственным сервером Xtream.",enter:"Войти",login:"ВХОД",loginHint:"Подписчики: войдите с данными от администратора.",signIn:"Войти",premiumTag:"Премиум IPTV-опыт",language:"Язык"},login:{...it.translation.login,subtitle:"Вход подписчика",username:"Имя пользователя",password:"Пароль",submit:"Войти",submitting:"Вход...",contactAdmin:"Нет аккаунта? Свяжитесь с администратором NADIPLAYER.",back:"Назад"},home:{...it.translation.home,logout:"Выйти",profile:"Профиль",guestMode:"Режим гостя",connected:"Подключено.",awaiting:"Ожидание синхронизации.",waiting:"Ожидание подключения.",subscriber:"Подписчик",expires:"Истекает",noExpiry:"Без срока действия",daysRemaining_one:"Осталось {{count}} день",daysRemaining_other:"Осталось {{count}} дней",expired:"ИСТЁК",categories:{...it.translation.home.categories,liveTv:"ТВ",movies:"Фильмы",series:"Сериалы",liveTvCount:"+5000 каналов",moviesCount:"+1200 фильмов",seriesCount:"+500 сериалов"},infoBar:"ТВ: +5000 каналов. ФИЛЬМЫ: +1200. СЕРИАЛЫ: +500."},expired:{...it.translation.expired,title:"ПОДПИСКА ИСТЕКЛА",hi:"Привет",message:"Ваша подписка NADIPLAYER закончилась. Свяжитесь с нами в WhatsApp для продления.",contactWhatsapp:"Написать в WhatsApp",signOut:"Выйти",whatsappPrefill:"Здравствуйте, моя подписка NADIPLAYER ({{username}}) истекла. Хочу продлить."},splash:{tagline:"Настройтесь на вселенную",premiumTag:"Премиум IPTV-опыт"},notFound:{...it.translation.notFound,message:"Упс! Страница не найдена",goHome:"На главную"},liveTV:{...it.translation.liveTV,title:"ЖИВОЕ ТВ",searchPlaceholder:"Поиск каналов…",noActiveServer:"Нет активного сервера.",addProfile:"Добавить профиль",favs:"Избранное",selectChannel:"Выберите канал",noChannels:"Каналы не найдены.",channels_one:"{{count}} канал",channels_other:"{{count}} каналов"},movies:{...it.translation.movies,title:"ФИЛЬМЫ",searchPlaceholder:"Поиск фильмов...",noActiveServer:"Нет активного сервера.",addProfile:"Добавить профиль",failedLoad:"Не удалось загрузить фильмы."},series:{...it.translation.series,title:"СЕРИАЛЫ",searchPlaceholder:"Поиск сериалов...",noActiveServer:"Нет активного сервера.",addProfile:"Добавить профиль",failedLoad:"Не удалось загрузить сериалы.",season:"Сезон {{n}}"},addServer:{...it.translation.addServer,title:"ДОБАВИТЬ ПЛЕЙЛИСТ",advanced:"Расширенные",shared:"Общий",ownServer:"Свой сервер"},admin:{...it.translation.admin,subtitle:"Панель управления подписчиками",settingsHeading:"ГЛОБАЛЬНЫЕ НАСТРОЙКИ",createHeading:"СОЗДАТЬ ПОДПИСЧИКА",subscribersHeading:"ПОДПИСЧИКИ ({{count}})",createUser:"Создать",saveSettings:"Сохранить"},account:{...it.translation.account,title:"АККАУНТ",addServer:"Добавить сервер",devicePairing:"Связать устройство",playbackMode:"Режим воспроизведения",externalPlayer:"Внешний плеер",playerIdentity:"Идентификатор плеера"}}},Mae={translation:{...it.translation,welcome:{...it.translation.welcome,chooseHowToContinue:"계속하는 방법을 선택하세요",guest:"게스트",guestHint:"자신의 Xtream 서버로 입장하세요.",enter:"입장",login:"로그인",loginHint:"가입자: 관리자가 제공한 아이디와 비밀번호로 로그인하세요.",signIn:"로그인",premiumTag:"프리미엄 IPTV 경험",language:"언어"},login:{...it.translation.login,subtitle:"가입자 로그인",username:"사용자 이름",password:"비밀번호",submit:"로그인",submitting:"로그인 중...",contactAdmin:"계정이 없으신가요? NADIPLAYER 관리자에게 문의하세요.",back:"뒤로"},home:{...it.translation.home,logout:"로그아웃",profile:"프로필",guestMode:"게스트 모드",connected:"연결됨.",awaiting:"서버 동기화 대기 중.",waiting:"연결 대기 중.",subscriber:"가입자",expires:"만료일",noExpiry:"만료일 없음",daysRemaining_one:"{{count}}일 남음",daysRemaining_other:"{{count}}일 남음",expired:"만료됨",categories:{...it.translation.home.categories,liveTv:"실시간 TV",movies:"영화",series:"시리즈",liveTvCount:"+5000 채널",moviesCount:"+1200 영화",seriesCount:"+500 시리즈"},infoBar:"실시간: +5000 채널. 영화: +1200. 시리즈: +500."},expired:{...it.translation.expired,title:"구독 만료됨",hi:"안녕하세요",message:"NADIPLAYER 구독이 종료되었습니다. 갱신을 위해 WhatsApp으로 문의하세요.",contactWhatsapp:"WhatsApp으로 문의",signOut:"로그아웃",whatsappPrefill:"안녕하세요, 제 NADIPLAYER 구독 ({{username}})이 만료되었습니다. 갱신하고 싶습니다."},splash:{tagline:"우주에 맞추세요",premiumTag:"프리미엄 IPTV 경험"},notFound:{...it.translation.notFound,message:"페이지를 찾을 수 없습니다",goHome:"홈으로"},liveTV:{...it.translation.liveTV,title:"실시간 TV",searchPlaceholder:"채널 검색…",noActiveServer:"활성 서버 없음.",addProfile:"프로필 추가",favs:"즐겨찾기",selectChannel:"채널을 선택하세요",noChannels:"채널을 찾을 수 없습니다.",channels_one:"{{count}}개 채널",channels_other:"{{count}}개 채널"},movies:{...it.translation.movies,title:"영화",searchPlaceholder:"영화 검색...",noActiveServer:"활성 서버 없음.",addProfile:"프로필 추가",failedLoad:"영화 로드 실패."},series:{...it.translation.series,title:"시리즈",searchPlaceholder:"시리즈 검색...",noActiveServer:"활성 서버 없음.",addProfile:"프로필 추가",failedLoad:"시리즈 로드 실패.",season:"시즌 {{n}}"},addServer:{...it.translation.addServer,title:"플레이리스트 추가",advanced:"고급",shared:"공유",ownServer:"자체 서버"},admin:{...it.translation.admin,subtitle:"가입자 제어판",settingsHeading:"전체 설정",createHeading:"가입자 생성",subscribersHeading:"가입자 ({{count}})",createUser:"사용자 생성",saveSettings:"저장"},account:{...it.translation.account,title:"계정",addServer:"서버 추가",devicePairing:"기기 연결",playbackMode:"재생 모드",externalPlayer:"외부 플레이어",playerIdentity:"플레이어 신원"}}},Bae={translation:{...it.translation,welcome:{...it.translation.welcome,chooseHowToContinue:"Pumili kung paano magpatuloy",guest:"BISITA",guestHint:"Pumasok gamit ang sarili mong Xtream server.",enter:"Pumasok",login:"MAG-LOGIN",loginHint:"Mga Subscriber: mag-sign in gamit ang username at password mula sa admin.",signIn:"Mag-Sign In",premiumTag:"Premium IPTV Experience",language:"Wika"},login:{...it.translation.login,subtitle:"Subscriber Sign-In",submit:"Mag-Sign In",submitting:"Nag-sa-sign in...",contactAdmin:"Walang account? Makipag-ugnayan sa iyong NADIPLAYER administrator.",back:"Bumalik"},home:{...it.translation.home,logout:"Mag-Log Out",profile:"Profile",guestMode:"Guest Mode",connected:"Nakakonekta.",awaiting:"Naghihintay ng server sync.",waiting:"Naghihintay na kumonekta.",subscriber:"Subscriber",expires:"Mag-e-expire",noExpiry:"Walang takdang expiry",daysRemaining_one:"{{count}} araw na natitira",daysRemaining_other:"{{count}} araw na natitira",expired:"EXPIRED",categories:{...it.translation.home.categories,liveTv:"Live TV",movies:"Pelikula",series:"Series",liveTvCount:"+5000 Channel",moviesCount:"+1200 Pelikula",seriesCount:"+500 Series"},infoBar:"LIVE: +5000 Channel. PELIKULA: +1200. SERIES: +500."},expired:{...it.translation.expired,title:"EXPIRED ANG SUBSCRIPTION",hi:"Hi",message:"Natapos na ang iyong NADIPLAYER subscription. Makipag-ugnayan sa WhatsApp upang mag-renew.",contactWhatsapp:"Makipag-ugnayan sa WhatsApp",signOut:"Mag-Sign Out",whatsappPrefill:"Hi, expired na ang aking NADIPLAYER subscription ({{username}}). Gusto kong mag-renew."},splash:{tagline:"I-tune in sa Sanlibutan",premiumTag:"Premium IPTV Experience"},notFound:{...it.translation.notFound,message:"Hindi nahanap ang pahina",goHome:"Bumalik sa home"},liveTV:{...it.translation.liveTV,title:"LIVE TV",searchPlaceholder:"Hanapin ang channel…",noActiveServer:"Walang aktibong server.",addProfile:"Magdagdag ng profile",favs:"Favs",selectChannel:"Pumili ng channel",noChannels:"Walang nakitang channel.",channels_one:"{{count}} channel",channels_other:"{{count}} channels"},movies:{...it.translation.movies,title:"MGA PELIKULA",searchPlaceholder:"Hanapin ang pelikula...",noActiveServer:"Walang aktibong server.",addProfile:"Magdagdag ng profile",failedLoad:"Hindi ma-load ang mga pelikula."},series:{...it.translation.series,title:"SERIES",searchPlaceholder:"Hanapin ang series...",noActiveServer:"Walang aktibong server.",addProfile:"Magdagdag ng profile",failedLoad:"Hindi ma-load ang series.",season:"Season {{n}}"},addServer:{...it.translation.addServer,title:"MAGDAGDAG NG PLAYLIST",advanced:"Advanced",shared:"Shared",ownServer:"Sariling server"},admin:{...it.translation.admin,subtitle:"Subscriber Control Panel",settingsHeading:"GLOBAL SETTINGS",createHeading:"GUMAWA NG SUBSCRIBER",subscribersHeading:"MGA SUBSCRIBER ({{count}})",createUser:"Gumawa ng user",saveSettings:"I-save"},account:{...it.translation.account,title:"ACCOUNT",addServer:"Magdagdag ng server",devicePairing:"Pairing ng Device",playbackMode:"Playback Mode",externalPlayer:"External Player",playerIdentity:"Identity ng Player"}}},Uae={en:it,ar:Pae,fr:Dae,es:Oae,ru:Nae,ko:Mae,fil:Bae};jr.use(vF).use(eJ).init({resources:Uae,fallbackLng:"en",supportedLngs:Mf.map(t=>t.code),interpolation:{escapeValue:!1},detection:{order:["localStorage","navigator"],lookupLocalStorage:"nadiplay_lang",caches:["localStorage"]}});const _F=t=>{const e=Mf.find(n=>n.code===t);typeof document<"u"&&(document.documentElement.dir=(e==null?void 0:e.dir)??"ltr",document.documentElement.lang=t)};_F(jr.language||"en");jr.on("languageChanged",_F);const fm=({align:t="right"})=>{const{i18n:e}=Wr(),[n,r]=D.useState(!1),i=D.useRef(null);D.useEffect(()=>{const a=o=>{i.current&&!i.current.contains(o.target)&&r(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[]);const s=Mf.find(a=>a.code===e.language)??Mf[0];return y.jsxs("div",{ref:i,className:"relative",children:[y.jsxs("button",{"data-testid":"lang-select-btn",onClick:()=>r(a=>!a),className:"flex items-center gap-2 px-3 sm:px-4 h-10 rounded-full glass text-foreground/90 hover:border-primary/40 transition-colors text-sm",children:[y.jsx(cK,{className:"w-4 h-4 text-primary shrink-0"}),y.jsx("span",{className:"text-lg leading-none",children:s.flag}),y.jsx("span",{className:"hidden sm:inline text-xs tracking-wider",children:s.label}),y.jsx(tv,{className:`w-3.5 h-3.5 text-muted-foreground transition-transform ${n?"rotate-180":""}`})]}),n&&y.jsx("div",{"data-testid":"lang-select-menu",className:`absolute top-12 ${t==="right"?"right-0":"left-0"} z-50 glass-card rounded-xl p-1 w-48 max-h-72 overflow-y-auto`,children:Mf.map(a=>{const o=a.code===s.code;return y.jsxs("button",{"data-testid":`lang-option-${a.code}`,onClick:()=>{e.changeLanguage(a.code),r(!1)},className:`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors ${o?"bg-primary/15 text-primary":"text-foreground/80 hover:bg-primary/10 hover:text-foreground"}`,children:[y.jsx("span",{className:"text-lg leading-none",children:a.flag}),y.jsx("span",{className:"flex-1 text-start",children:a.label}),o&&y.jsx(Ol,{className:"w-4 h-4"})]},a.code)})})]})};var Lb="focusScope.autoFocusOnMount",kb="focusScope.autoFocusOnUnmount",$I={bubbles:!1,cancelable:!0},jae="FocusScope",bF=D.forwardRef((t,e)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:i,onUnmountAutoFocus:s,...a}=t,[o,l]=D.useState(null),c=fa(i),u=fa(s),d=D.useRef(null),h=si(e,m=>l(m)),f=D.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;D.useEffect(()=>{if(r){let m=function(S){if(f.paused||!o)return;const E=S.target;o.contains(E)?d.current=E:Do(d.current,{select:!0})},g=function(S){if(f.paused||!o)return;const E=S.relatedTarget;E!==null&&(o.contains(E)||Do(d.current,{select:!0}))},b=function(S){if(document.activeElement===document.body)for(const L of S)L.removedNodes.length>0&&Do(o)};document.addEventListener("focusin",m),document.addEventListener("focusout",g);const v=new MutationObserver(b);return o&&v.observe(o,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",g),v.disconnect()}}},[r,o,f.paused]),D.useEffect(()=>{if(o){GI.add(f);const m=document.activeElement;if(!o.contains(m)){const b=new CustomEvent(Lb,$I);o.addEventListener(Lb,c),o.dispatchEvent(b),b.defaultPrevented||(Fae(Kae(xF(o)),{select:!0}),document.activeElement===m&&Do(o))}return()=>{o.removeEventListener(Lb,c),setTimeout(()=>{const b=new CustomEvent(kb,$I);o.addEventListener(kb,u),o.dispatchEvent(b),b.defaultPrevented||Do(m??document.body,{select:!0}),o.removeEventListener(kb,u),GI.remove(f)},0)}}},[o,c,u,f]);const p=D.useCallback(m=>{if(!n&&!r||f.paused)return;const g=m.key==="Tab"&&!m.altKey&&!m.ctrlKey&&!m.metaKey,b=document.activeElement;if(g&&b){const v=m.currentTarget,[S,E]=$ae(v);S&&E?!m.shiftKey&&b===E?(m.preventDefault(),n&&Do(S,{select:!0})):m.shiftKey&&b===S&&(m.preventDefault(),n&&Do(E,{select:!0})):b===v&&m.preventDefault()}},[n,r,f.paused]);return y.jsx(ar.div,{tabIndex:-1,...a,ref:h,onKeyDown:p})});bF.displayName=jae;function Fae(t,{select:e=!1}={}){const n=document.activeElement;for(const r of t)if(Do(r,{select:e}),document.activeElement!==n)return}function $ae(t){const e=xF(t),n=VI(e,t),r=VI(e.reverse(),t);return[n,r]}function xF(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const i=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||i?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)e.push(n.currentNode);return e}function VI(t,e){for(const n of t)if(!Vae(n,{upTo:e}))return n}function Vae(t,{upTo:e}){if(getComputedStyle(t).visibility==="hidden")return!0;for(;t;){if(e!==void 0&&t===e)return!1;if(getComputedStyle(t).display==="none")return!0;t=t.parentElement}return!1}function Gae(t){return t instanceof HTMLInputElement&&"select"in t}function Do(t,{select:e=!1}={}){if(t&&t.focus){const n=document.activeElement;t.focus({preventScroll:!0}),t!==n&&Gae(t)&&e&&t.select()}}var GI=Hae();function Hae(){let t=[];return{add(e){const n=t[0];e!==n&&(n==null||n.pause()),t=HI(t,e),t.unshift(e)},remove(e){var n;t=HI(t,e),(n=t[0])==null||n.resume()}}}function HI(t,e){const n=[...t],r=n.indexOf(e);return r!==-1&&n.splice(r,1),n}function Kae(t){return t.filter(e=>e.tagName!=="A")}var Ib=0;function zae(){D.useEffect(()=>{const t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??KI()),document.body.insertAdjacentElement("beforeend",t[1]??KI()),Ib++,()=>{Ib===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),Ib--}},[])}function KI(){const t=document.createElement("span");return t.setAttribute("data-radix-focus-guard",""),t.tabIndex=0,t.style.outline="none",t.style.opacity="0",t.style.position="fixed",t.style.pointerEvents="none",t}var sy="right-scroll-bar-position",ay="width-before-scroll-bar",qae="with-scroll-bars-hidden",Wae="--removed-body-scroll-bar-size";function Pb(t,e){return typeof t=="function"?t(e):t&&(t.current=e),t}function Yae(t,e){var n=D.useState(function(){return{value:t,callback:e,facade:{get current(){return n.value},set current(r){var i=n.value;i!==r&&(n.value=r,n.callback(r,i))}}}})[0];return n.callback=e,n.facade}var Xae=typeof window<"u"?D.useLayoutEffect:D.useEffect,zI=new WeakMap;function Qae(t,e){var n=Yae(null,function(r){return t.forEach(function(i){return Pb(i,r)})});return Xae(function(){var r=zI.get(n);if(r){var i=new Set(r),s=new Set(t),a=n.current;i.forEach(function(o){s.has(o)||Pb(o,null)}),s.forEach(function(o){i.has(o)||Pb(o,a)})}zI.set(n,t)},[t]),n}function Jae(t){return t}function Zae(t,e){e===void 0&&(e=Jae);var n=[],r=!1,i={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:t},useMedium:function(s){var a=e(s,r);return n.push(a),function(){n=n.filter(function(o){return o!==a})}},assignSyncMedium:function(s){for(r=!0;n.length;){var a=n;n=[],a.forEach(s)}n={push:function(o){return s(o)},filter:function(){return n}}},assignMedium:function(s){r=!0;var a=[];if(n.length){var o=n;n=[],o.forEach(s),a=n}var l=function(){var u=a;a=[],u.forEach(s)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(u){a.push(u),c()},filter:function(u){return a=a.filter(u),n}}}};return i}function eoe(t){t===void 0&&(t={});var e=Zae(null);return e.options=ta({async:!0,ssr:!1},t),e}var SF=function(t){var e=t.sideCar,n=xh(t,["sideCar"]);if(!e)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=e.read();if(!r)throw new Error("Sidecar medium not found");return D.createElement(r,ta({},n))};SF.isSideCarExport=!0;function toe(t,e){return t.useMedium(e),SF}var EF=eoe(),Db=function(){},Lv=D.forwardRef(function(t,e){var n=D.useRef(null),r=D.useState({onScrollCapture:Db,onWheelCapture:Db,onTouchMoveCapture:Db}),i=r[0],s=r[1],a=t.forwardProps,o=t.children,l=t.className,c=t.removeScrollBar,u=t.enabled,d=t.shards,h=t.sideCar,f=t.noRelative,p=t.noIsolation,m=t.inert,g=t.allowPinchZoom,b=t.as,v=b===void 0?"div":b,S=t.gapMode,E=xh(t,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),L=h,U=Qae([n,e]),O=ta(ta({},E),i);return D.createElement(D.Fragment,null,u&&D.createElement(L,{sideCar:EF,removeScrollBar:c,shards:d,noRelative:f,noIsolation:p,inert:m,setCallbacks:s,allowPinchZoom:!!g,lockRef:n,gapMode:S}),a?D.cloneElement(D.Children.only(o),ta(ta({},O),{ref:U})):D.createElement(v,ta({},O,{className:l,ref:U}),o))});Lv.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Lv.classNames={fullWidth:ay,zeroRight:sy};var noe=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function roe(){if(!document)return null;var t=document.createElement("style");t.type="text/css";var e=noe();return e&&t.setAttribute("nonce",e),t}function ioe(t,e){t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e))}function soe(t){var e=document.head||document.getElementsByTagName("head")[0];e.appendChild(t)}var aoe=function(){var t=0,e=null;return{add:function(n){t==0&&(e=roe())&&(ioe(e,n),soe(e)),t++},remove:function(){t--,!t&&e&&(e.parentNode&&e.parentNode.removeChild(e),e=null)}}},ooe=function(){var t=aoe();return function(e,n){D.useEffect(function(){return t.add(e),function(){t.remove()}},[e&&n])}},wF=function(){var t=ooe(),e=function(n){var r=n.styles,i=n.dynamic;return t(r,i),null};return e},loe={left:0,top:0,right:0,gap:0},Ob=function(t){return parseInt(t||"",10)||0},coe=function(t){var e=window.getComputedStyle(document.body),n=e[t==="padding"?"paddingLeft":"marginLeft"],r=e[t==="padding"?"paddingTop":"marginTop"],i=e[t==="padding"?"paddingRight":"marginRight"];return[Ob(n),Ob(r),Ob(i)]},uoe=function(t){if(t===void 0&&(t="margin"),typeof window>"u")return loe;var e=coe(t),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:e[0],top:e[1],right:e[2],gap:Math.max(0,r-n+e[2]-e[0])}},doe=wF(),yd="data-scroll-locked",hoe=function(t,e,n,r){var i=t.left,s=t.top,a=t.right,o=t.gap;return n===void 0&&(n="margin"),`
  .`.concat(qae,` {
   overflow: hidden `).concat(r,`;
   padding-right: `).concat(o,"px ").concat(r,`;
  }
  body[`).concat(yd,`] {
    overflow: hidden `).concat(r,`;
    overscroll-behavior: contain;
    `).concat([e&&"position: relative ".concat(r,";"),n==="margin"&&`
    padding-left: `.concat(i,`px;
    padding-top: `).concat(s,`px;
    padding-right: `).concat(a,`px;
    margin-left:0;
    margin-top:0;
    margin-right: `).concat(o,"px ").concat(r,`;
    `),n==="padding"&&"padding-right: ".concat(o,"px ").concat(r,";")].filter(Boolean).join(""),`
  }
  
  .`).concat(sy,` {
    right: `).concat(o,"px ").concat(r,`;
  }
  
  .`).concat(ay,` {
    margin-right: `).concat(o,"px ").concat(r,`;
  }
  
  .`).concat(sy," .").concat(sy,` {
    right: 0 `).concat(r,`;
  }
  
  .`).concat(ay," .").concat(ay,` {
    margin-right: 0 `).concat(r,`;
  }
  
  body[`).concat(yd,`] {
    `).concat(Wae,": ").concat(o,`px;
  }
`)},qI=function(){var t=parseInt(document.body.getAttribute(yd)||"0",10);return isFinite(t)?t:0},foe=function(){D.useEffect(function(){return document.body.setAttribute(yd,(qI()+1).toString()),function(){var t=qI()-1;t<=0?document.body.removeAttribute(yd):document.body.setAttribute(yd,t.toString())}},[])},poe=function(t){var e=t.noRelative,n=t.noImportant,r=t.gapMode,i=r===void 0?"margin":r;foe();var s=D.useMemo(function(){return uoe(i)},[i]);return D.createElement(doe,{styles:hoe(s,!e,i,n?"":"!important")})},NE=!1;if(typeof window<"u")try{var pg=Object.defineProperty({},"passive",{get:function(){return NE=!0,!0}});window.addEventListener("test",pg,pg),window.removeEventListener("test",pg,pg)}catch{NE=!1}var vu=NE?{passive:!1}:!1,moe=function(t){return t.tagName==="TEXTAREA"},TF=function(t,e){if(!(t instanceof Element))return!1;var n=window.getComputedStyle(t);return n[e]!=="hidden"&&!(n.overflowY===n.overflowX&&!moe(t)&&n[e]==="visible")},goe=function(t){return TF(t,"overflowY")},yoe=function(t){return TF(t,"overflowX")},WI=function(t,e){var n=e.ownerDocument,r=e;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var i=AF(t,r);if(i){var s=RF(t,r),a=s[1],o=s[2];if(a>o)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},voe=function(t){var e=t.scrollTop,n=t.scrollHeight,r=t.clientHeight;return[e,n,r]},_oe=function(t){var e=t.scrollLeft,n=t.scrollWidth,r=t.clientWidth;return[e,n,r]},AF=function(t,e){return t==="v"?goe(e):yoe(e)},RF=function(t,e){return t==="v"?voe(e):_oe(e)},boe=function(t,e){return t==="h"&&e==="rtl"?-1:1},xoe=function(t,e,n,r,i){var s=boe(t,window.getComputedStyle(e).direction),a=s*r,o=n.target,l=e.contains(o),c=!1,u=a>0,d=0,h=0;do{if(!o)break;var f=RF(t,o),p=f[0],m=f[1],g=f[2],b=m-g-s*p;(p||b)&&AF(t,o)&&(d+=b,h+=p);var v=o.parentNode;o=v&&v.nodeType===Node.DOCUMENT_FRAGMENT_NODE?v.host:v}while(!l&&o!==document.body||l&&(e.contains(o)||e===o));return(u&&Math.abs(d)<1||!u&&Math.abs(h)<1)&&(c=!0),c},mg=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},YI=function(t){return[t.deltaX,t.deltaY]},XI=function(t){return t&&"current"in t?t.current:t},Soe=function(t,e){return t[0]===e[0]&&t[1]===e[1]},Eoe=function(t){return`
  .block-interactivity-`.concat(t,` {pointer-events: none;}
  .allow-interactivity-`).concat(t,` {pointer-events: all;}
`)},woe=0,_u=[];function Toe(t){var e=D.useRef([]),n=D.useRef([0,0]),r=D.useRef(),i=D.useState(woe++)[0],s=D.useState(wF)[0],a=D.useRef(t);D.useEffect(function(){a.current=t},[t]),D.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(i));var m=NJ([t.lockRef.current],(t.shards||[]).map(XI),!0).filter(Boolean);return m.forEach(function(g){return g.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),m.forEach(function(g){return g.classList.remove("allow-interactivity-".concat(i))})}}},[t.inert,t.lockRef.current,t.shards]);var o=D.useCallback(function(m,g){if("touches"in m&&m.touches.length===2||m.type==="wheel"&&m.ctrlKey)return!a.current.allowPinchZoom;var b=mg(m),v=n.current,S="deltaX"in m?m.deltaX:v[0]-b[0],E="deltaY"in m?m.deltaY:v[1]-b[1],L,U=m.target,O=Math.abs(S)>Math.abs(E)?"h":"v";if("touches"in m&&O==="h"&&U.type==="range")return!1;var k=window.getSelection(),I=k&&k.anchorNode,R=I?I===U||I.contains(U):!1;if(R)return!1;var M=WI(O,U);if(!M)return!0;if(M?L=O:(L=O==="v"?"h":"v",M=WI(O,U)),!M)return!1;if(!r.current&&"changedTouches"in m&&(S||E)&&(r.current=L),!L)return!0;var z=r.current||L;return xoe(z,g,m,z==="h"?S:E)},[]),l=D.useCallback(function(m){var g=m;if(!(!_u.length||_u[_u.length-1]!==s)){var b="deltaY"in g?YI(g):mg(g),v=e.current.filter(function(L){return L.name===g.type&&(L.target===g.target||g.target===L.shadowParent)&&Soe(L.delta,b)})[0];if(v&&v.should){g.cancelable&&g.preventDefault();return}if(!v){var S=(a.current.shards||[]).map(XI).filter(Boolean).filter(function(L){return L.contains(g.target)}),E=S.length>0?o(g,S[0]):!a.current.noIsolation;E&&g.cancelable&&g.preventDefault()}}},[]),c=D.useCallback(function(m,g,b,v){var S={name:m,delta:g,target:b,should:v,shadowParent:Aoe(b)};e.current.push(S),setTimeout(function(){e.current=e.current.filter(function(E){return E!==S})},1)},[]),u=D.useCallback(function(m){n.current=mg(m),r.current=void 0},[]),d=D.useCallback(function(m){c(m.type,YI(m),m.target,o(m,t.lockRef.current))},[]),h=D.useCallback(function(m){c(m.type,mg(m),m.target,o(m,t.lockRef.current))},[]);D.useEffect(function(){return _u.push(s),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:h}),document.addEventListener("wheel",l,vu),document.addEventListener("touchmove",l,vu),document.addEventListener("touchstart",u,vu),function(){_u=_u.filter(function(m){return m!==s}),document.removeEventListener("wheel",l,vu),document.removeEventListener("touchmove",l,vu),document.removeEventListener("touchstart",u,vu)}},[]);var f=t.removeScrollBar,p=t.inert;return D.createElement(D.Fragment,null,p?D.createElement(s,{styles:Eoe(i)}):null,f?D.createElement(poe,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function Aoe(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}const Roe=toe(EF,Toe);var CF=D.forwardRef(function(t,e){return D.createElement(Lv,ta({},t,{ref:e,sideCar:Roe}))});CF.classNames=Lv.classNames;var Coe=function(t){if(typeof document>"u")return null;var e=Array.isArray(t)?t[0]:t;return e.ownerDocument.body},bu=new WeakMap,gg=new WeakMap,yg={},Nb=0,LF=function(t){return t&&(t.host||LF(t.parentNode))},Loe=function(t,e){return e.map(function(n){if(t.contains(n))return n;var r=LF(n);return r&&t.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",t,". Doing nothing"),null)}).filter(function(n){return!!n})},koe=function(t,e,n,r){var i=Loe(e,Array.isArray(t)?t:[t]);yg[n]||(yg[n]=new WeakMap);var s=yg[n],a=[],o=new Set,l=new Set(i),c=function(d){!d||o.has(d)||(o.add(d),c(d.parentNode))};i.forEach(c);var u=function(d){!d||l.has(d)||Array.prototype.forEach.call(d.children,function(h){if(o.has(h))u(h);else try{var f=h.getAttribute(r),p=f!==null&&f!=="false",m=(bu.get(h)||0)+1,g=(s.get(h)||0)+1;bu.set(h,m),s.set(h,g),a.push(h),m===1&&p&&gg.set(h,!0),g===1&&h.setAttribute(n,"true"),p||h.setAttribute(r,"true")}catch(b){console.error("aria-hidden: cannot operate on ",h,b)}})};return u(e),o.clear(),Nb++,function(){a.forEach(function(d){var h=bu.get(d)-1,f=s.get(d)-1;bu.set(d,h),s.set(d,f),h||(gg.has(d)||d.removeAttribute(r),gg.delete(d)),f||d.removeAttribute(n)}),Nb--,Nb||(bu=new WeakMap,bu=new WeakMap,gg=new WeakMap,yg={})}},Ioe=function(t,e,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(t)?t:[t]),i=Coe(t);return i?(r.push.apply(r,Array.from(i.querySelectorAll("[aria-live], script"))),koe(r,i,n,"aria-hidden")):function(){return null}};function Poe(t){const e=Doe(t),n=D.forwardRef((r,i)=>{const{children:s,...a}=r,o=D.Children.toArray(s),l=o.find(Noe);if(l){const c=l.props.children,u=o.map(d=>d===l?D.Children.count(c)>1?D.Children.only(null):D.isValidElement(c)?c.props.children:null:d);return y.jsx(e,{...a,ref:i,children:D.isValidElement(c)?D.cloneElement(c,void 0,u):null})}return y.jsx(e,{...a,ref:i,children:s})});return n.displayName=`${t}.Slot`,n}function Doe(t){const e=D.forwardRef((n,r)=>{const{children:i,...s}=n;if(D.isValidElement(i)){const a=Boe(i),o=Moe(s,i.props);return i.type!==D.Fragment&&(o.ref=r?X0(r,a):a),D.cloneElement(i,o)}return D.Children.count(i)>1?D.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var Ooe=Symbol("radix.slottable");function Noe(t){return D.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===Ooe}function Moe(t,e){const n={...e};for(const r in e){const i=t[r],s=e[r];/^on[A-Z]/.test(r)?i&&s?n[r]=(...o)=>{const l=s(...o);return i(...o),l}:i&&(n[r]=i):r==="style"?n[r]={...i,...s}:r==="className"&&(n[r]=[i,s].filter(Boolean).join(" "))}return{...t,...n}}function Boe(t){var r,i;let e=(r=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:r.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=(i=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:i.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var kv="Dialog",[kF]=Zp(kv),[Uoe,Us]=kF(kv),IF=t=>{const{__scopeDialog:e,children:n,open:r,defaultOpen:i,onOpenChange:s,modal:a=!0}=t,o=D.useRef(null),l=D.useRef(null),[c,u]=n2({prop:r,defaultProp:i??!1,onChange:s,caller:kv});return y.jsx(Uoe,{scope:e,triggerRef:o,contentRef:l,contentId:G_(),titleId:G_(),descriptionId:G_(),open:c,onOpenChange:u,onOpenToggle:D.useCallback(()=>u(d=>!d),[u]),modal:a,children:n})};IF.displayName=kv;var PF="DialogTrigger",joe=D.forwardRef((t,e)=>{const{__scopeDialog:n,...r}=t,i=Us(PF,n),s=si(e,i.triggerRef);return y.jsx(ar.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":kA(i.open),...r,ref:s,onClick:kn(t.onClick,i.onOpenToggle)})});joe.displayName=PF;var CA="DialogPortal",[Foe,DF]=kF(CA,{forceMount:void 0}),OF=t=>{const{__scopeDialog:e,forceMount:n,children:r,container:i}=t,s=Us(CA,e);return y.jsx(Foe,{scope:e,forceMount:n,children:D.Children.map(r,a=>y.jsx(fh,{present:n||s.open,children:y.jsx(mT,{asChild:!0,container:i,children:a})}))})};OF.displayName=CA;var y0="DialogOverlay",NF=D.forwardRef((t,e)=>{const n=DF(y0,t.__scopeDialog),{forceMount:r=n.forceMount,...i}=t,s=Us(y0,t.__scopeDialog);return s.modal?y.jsx(fh,{present:r||s.open,children:y.jsx(Voe,{...i,ref:e})}):null});NF.displayName=y0;var $oe=Poe("DialogOverlay.RemoveScroll"),Voe=D.forwardRef((t,e)=>{const{__scopeDialog:n,...r}=t,i=Us(y0,n);return y.jsx(CF,{as:$oe,allowPinchZoom:!0,shards:[i.contentRef],children:y.jsx(ar.div,{"data-state":kA(i.open),...r,ref:e,style:{pointerEvents:"auto",...r.style}})})}),$c="DialogContent",MF=D.forwardRef((t,e)=>{const n=DF($c,t.__scopeDialog),{forceMount:r=n.forceMount,...i}=t,s=Us($c,t.__scopeDialog);return y.jsx(fh,{present:r||s.open,children:s.modal?y.jsx(Goe,{...i,ref:e}):y.jsx(Hoe,{...i,ref:e})})});MF.displayName=$c;var Goe=D.forwardRef((t,e)=>{const n=Us($c,t.__scopeDialog),r=D.useRef(null),i=si(e,n.contentRef,r);return D.useEffect(()=>{const s=r.current;if(s)return Ioe(s)},[]),y.jsx(BF,{...t,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:kn(t.onCloseAutoFocus,s=>{var a;s.preventDefault(),(a=n.triggerRef.current)==null||a.focus()}),onPointerDownOutside:kn(t.onPointerDownOutside,s=>{const a=s.detail.originalEvent,o=a.button===0&&a.ctrlKey===!0;(a.button===2||o)&&s.preventDefault()}),onFocusOutside:kn(t.onFocusOutside,s=>s.preventDefault())})}),Hoe=D.forwardRef((t,e)=>{const n=Us($c,t.__scopeDialog),r=D.useRef(!1),i=D.useRef(!1);return y.jsx(BF,{...t,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var a,o;(a=t.onCloseAutoFocus)==null||a.call(t,s),s.defaultPrevented||(r.current||(o=n.triggerRef.current)==null||o.focus(),s.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:s=>{var l,c;(l=t.onInteractOutside)==null||l.call(t,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const a=s.target;((c=n.triggerRef.current)==null?void 0:c.contains(a))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&i.current&&s.preventDefault()}})}),BF=D.forwardRef((t,e)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:s,...a}=t,o=Us($c,n),l=D.useRef(null),c=si(e,l);return zae(),y.jsxs(y.Fragment,{children:[y.jsx(bF,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:s,children:y.jsx(Q0,{role:"dialog",id:o.contentId,"aria-describedby":o.descriptionId,"aria-labelledby":o.titleId,"data-state":kA(o.open),...a,ref:c,onDismiss:()=>o.onOpenChange(!1)})}),y.jsxs(y.Fragment,{children:[y.jsx(Koe,{titleId:o.titleId}),y.jsx(qoe,{contentRef:l,descriptionId:o.descriptionId})]})]})}),LA="DialogTitle",UF=D.forwardRef((t,e)=>{const{__scopeDialog:n,...r}=t,i=Us(LA,n);return y.jsx(ar.h2,{id:i.titleId,...r,ref:e})});UF.displayName=LA;var jF="DialogDescription",FF=D.forwardRef((t,e)=>{const{__scopeDialog:n,...r}=t,i=Us(jF,n);return y.jsx(ar.p,{id:i.descriptionId,...r,ref:e})});FF.displayName=jF;var $F="DialogClose",VF=D.forwardRef((t,e)=>{const{__scopeDialog:n,...r}=t,i=Us($F,n);return y.jsx(ar.button,{type:"button",...r,ref:e,onClick:kn(t.onClick,()=>i.onOpenChange(!1))})});VF.displayName=$F;function kA(t){return t?"open":"closed"}var GF="DialogTitleWarning",[kpe,HF]=MG(GF,{contentName:$c,titleName:LA,docsSlug:"dialog"}),Koe=({titleId:t})=>{const e=HF(GF),n=`\`${e.contentName}\` requires a \`${e.titleName}\` for the component to be accessible for screen reader users.

If you want to hide the \`${e.titleName}\`, you can wrap it with our VisuallyHidden component.

For more information, see https://radix-ui.com/primitives/docs/components/${e.docsSlug}`;return D.useEffect(()=>{t&&(document.getElementById(t)||console.error(n))},[n,t]),null},zoe="DialogDescriptionWarning",qoe=({contentRef:t,descriptionId:e})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${HF(zoe).contentName}}.`;return D.useEffect(()=>{var s;const i=(s=t.current)==null?void 0:s.getAttribute("aria-describedby");e&&i&&(document.getElementById(e)||console.warn(r))},[r,t,e]),null},Woe=IF,Yoe=OF,KF=NF,zF=MF,qF=UF,WF=FF,Xoe=VF;const Qoe=Woe,Joe=Yoe,YF=D.forwardRef(({className:t,...e},n)=>y.jsx(KF,{ref:n,className:oi("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...e}));YF.displayName=KF.displayName;const XF=D.forwardRef(({className:t,children:e,...n},r)=>y.jsxs(Joe,{children:[y.jsx(YF,{}),y.jsxs(zF,{ref:r,className:oi("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...n,children:[e,y.jsxs(Xoe,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity data-[state=open]:bg-accent data-[state=open]:text-muted-foreground hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[y.jsx(Sa,{className:"h-4 w-4"}),y.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));XF.displayName=zF.displayName;const QF=({className:t,...e})=>y.jsx("div",{className:oi("flex flex-col space-y-1.5 text-center sm:text-left",t),...e});QF.displayName="DialogHeader";const JF=D.forwardRef(({className:t,...e},n)=>y.jsx(qF,{ref:n,className:oi("text-lg font-semibold leading-none tracking-tight",t),...e}));JF.displayName=qF.displayName;const ZF=D.forwardRef(({className:t,...e},n)=>y.jsx(WF,{ref:n,className:oi("text-sm text-muted-foreground",t),...e}));ZF.displayName=WF.displayName;const Zoe=[{key:"exoplayer",label:"Just Player (ExoPlayer)",packageName:"com.brouken.player",playStoreUrl:"https://play.google.com/store/apps/details?id=com.brouken.player",iconUrl:"data:image/svg+xml;utf8,"+encodeURIComponent("<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'><rect width='64' height='64' rx='14' fill='#c89a4a'/><polygon points='24,18 48,32 24,46' fill='#ffffff'/></svg>"),description:"ExoPlayer-powered player — best for IPTV & HLS streams."},{key:"vlc",label:"VLC Media Player",packageName:"org.videolan.vlc",playStoreUrl:"https://play.google.com/store/apps/details?id=org.videolan.vlc",iconUrl:"data:image/svg+xml;utf8,"+encodeURIComponent("<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'><rect width='64' height='64' rx='14' fill='#ff8800'/><polygon points='20,46 32,14 44,46' fill='#ffffff'/><rect x='18' y='44' width='28' height='4' fill='#ffffff'/></svg>"),description:"Universal player — handles any codec or format."}],QI="nadiplay.playerNotice.dismissed.v1",ele=()=>{const[t,e]=D.useState(!1);D.useEffect(()=>{try{localStorage.getItem(QI)==="1"||e(!0)}catch{e(!0)}},[]);const n=i=>{um()?Ko.openPlayStore({package:i.packageName}).catch(()=>{window.open(i.playStoreUrl,"_blank","noopener,noreferrer")}):window.open(i.playStoreUrl,"_blank","noopener,noreferrer")},r=()=>{try{localStorage.setItem(QI,"1")}catch{}e(!1)};return y.jsx(Qoe,{open:t,onOpenChange:i=>!i&&r(),children:y.jsxs(XF,{"data-testid":"player-notice-dialog",className:"max-w-md border-primary/30 bg-background/95 backdrop-blur-xl",children:[y.jsxs(QF,{children:[y.jsx("div",{className:"mx-auto mb-2 flex h-12 w-12 items-center justify-center rounded-full bg-primary/15",children:y.jsx(_T,{className:"h-6 w-6 text-primary",strokeWidth:1.8})}),y.jsx(JF,{className:"text-center text-lg tracking-wide gold-text",children:"Install a video player"}),y.jsxs(ZF,{className:"text-center text-sm text-muted-foreground",children:["You must download ",y.jsx("span",{className:"text-primary font-medium",children:"ExoPlayer"})," or"," ",y.jsx("span",{className:"text-primary font-medium",children:"VLC"})," from Google Play to let this app work. If you already have one installed, just tap “I already have it”."]})]}),y.jsx("div",{className:"mt-2 flex flex-col gap-2.5",children:Zoe.map(i=>y.jsxs("button",{"data-testid":`install-${i.key}`,onClick:()=>n(i),className:"group flex items-center gap-3 rounded-xl border border-border/70 bg-card/60 px-3 py-2.5 text-left transition hover:border-primary/50 hover:bg-primary/5 active:scale-[0.99]",children:[y.jsx("img",{src:i.iconUrl,alt:i.label,className:"h-11 w-11 flex-none rounded-lg bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}),y.jsxs("div",{className:"min-w-0 flex-1",children:[y.jsxs("div",{className:"flex items-center gap-1.5 text-sm font-medium text-foreground",children:[y.jsx("span",{className:"truncate",children:i.label}),y.jsx(no,{className:"h-3 w-3 text-muted-foreground opacity-0 transition group-hover:opacity-100"})]}),y.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:i.description})]}),y.jsx("div",{className:"text-[10px] font-medium uppercase tracking-widest text-primary/80",children:"Install"})]},i.key))}),y.jsxs("button",{"data-testid":"player-notice-dismiss",onClick:r,className:"mt-3 flex items-center justify-center gap-2 rounded-xl border border-border/70 bg-muted/40 py-2.5 text-sm text-foreground/90 transition hover:bg-muted",children:[y.jsx(Ol,{className:"h-4 w-4 text-primary"}),"I already have it"]})]})})},tle=()=>{const t=qr(),{t:e}=Wr(),{continueAsGuest:n}=Bs(),r=()=>{n(),t("/")},i=()=>{t("/login")};return y.jsxs(Rl,{focusKey:"welcome-page",className:"relative min-h-screen w-full overflow-hidden flex flex-col","data-testid":"welcome-page",children:[y.jsx("div",{className:"absolute inset-0 bg-cover bg-center",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),y.jsx("div",{className:"absolute inset-0 bg-background/55"}),y.jsx("div",{className:"relative z-20 flex items-center justify-end px-4 sm:px-8 pt-5",children:y.jsx(fm,{align:"right"})}),y.jsxs("header",{className:"relative z-10 flex flex-col items-center pt-4 sm:pt-8",children:[y.jsx($t.h1,{initial:{opacity:0,y:-20,letterSpacing:"0.8em"},animate:{opacity:1,y:0,letterSpacing:"0.4em"},transition:{duration:.9,ease:"easeOut"},className:"font-display text-3xl sm:text-4xl md:text-5xl tracking-[0.4em] gold-text",style:{textShadow:"0 0 30px hsla(40, 80%, 55%, 0.35)"},children:e("welcome.title")}),y.jsx($t.p,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.4,duration:.6},className:"text-muted-foreground text-[10px] sm:text-xs md:text-sm tracking-[0.4em] sm:tracking-[0.5em] uppercase mt-3 text-center px-4",children:e("welcome.chooseHowToContinue")})]}),y.jsx("main",{className:"relative z-10 flex-1 flex items-center justify-center px-4 py-6 sm:py-10",children:y.jsxs(Rl,{focusKey:"welcome-cards",className:"flex flex-col md:flex-row gap-4 sm:gap-6 md:gap-10 w-full max-w-4xl",children:[y.jsxs(Fc,{focusKey:"guest-card",onEnter:r,onClick:r,"data-testid":"welcome-guest-btn",className:"group relative flex-1 rounded-3xl overflow-hidden text-start cursor-pointer min-h-[220px] md:min-h-[300px] border-transparent",children:[y.jsx("div",{className:"absolute inset-0 glass-card"}),y.jsx("div",{className:"absolute -inset-px rounded-3xl pointer-events-none opacity-0 group-hover:opacity-100 transition-opacity",style:{boxShadow:"0 0 50px hsla(40, 80%, 55%, 0.25), inset 0 0 40px hsla(40, 80%, 55%, 0.08)",border:"1px solid hsla(40, 80%, 55%, 0.3)"}}),y.jsxs("div",{className:"relative z-10 h-full flex flex-col items-center justify-center gap-4 sm:gap-5 p-6 sm:p-10",children:[y.jsx("div",{className:"w-16 h-16 sm:w-20 sm:h-20 rounded-2xl glass flex items-center justify-center",style:{border:"1px solid hsla(40, 80%, 55%, 0.3)"},children:y.jsx(YH,{className:"w-8 h-8 sm:w-10 sm:h-10 text-primary gold-glow",strokeWidth:1.4})}),y.jsx("h2",{className:"font-display text-xl sm:text-2xl tracking-[0.3em] gold-text",children:e("welcome.guest")}),y.jsx("p",{className:"text-muted-foreground text-xs sm:text-sm text-center max-w-xs tracking-wide",children:e("welcome.guestHint")}),y.jsxs("span",{className:"text-primary/80 text-[10px] sm:text-xs tracking-[0.4em] uppercase mt-1 sm:mt-2",children:[e("welcome.enter")," →"]})]})]}),y.jsxs(Fc,{focusKey:"login-card",onEnter:i,onClick:i,"data-testid":"welcome-login-btn",className:"group relative flex-1 rounded-3xl overflow-hidden text-start cursor-pointer min-h-[220px] md:min-h-[300px] border-transparent",children:[y.jsx("div",{className:"absolute inset-0 glass-card"}),y.jsx("div",{className:"absolute -inset-px rounded-3xl pointer-events-none opacity-0 group-hover:opacity-100 transition-opacity",style:{boxShadow:"0 0 50px hsla(40, 80%, 55%, 0.35), inset 0 0 40px hsla(40, 80%, 55%, 0.08)",border:"1px solid hsla(40, 80%, 55%, 0.4)"}}),y.jsxs("div",{className:"relative z-10 h-full flex flex-col items-center justify-center gap-4 sm:gap-5 p-6 sm:p-10",children:[y.jsx("div",{className:"w-16 h-16 sm:w-20 sm:h-20 rounded-2xl glass flex items-center justify-center",style:{border:"1px solid hsla(40, 80%, 55%, 0.4)",boxShadow:"0 0 30px hsla(40, 80%, 55%, 0.2)"},children:y.jsx(RK,{className:"w-8 h-8 sm:w-10 sm:h-10 text-primary gold-glow",strokeWidth:1.4})}),y.jsx("h2",{className:"font-display text-xl sm:text-2xl tracking-[0.3em] gold-text",children:e("welcome.login")}),y.jsx("p",{className:"text-muted-foreground text-xs sm:text-sm text-center max-w-xs tracking-wide",children:e("welcome.loginHint")}),y.jsxs("span",{className:"text-primary/80 text-[10px] sm:text-xs tracking-[0.4em] uppercase mt-1 sm:mt-2",children:[e("welcome.signIn")," →"]})]})]})]})}),y.jsxs("footer",{className:"relative z-10 pb-5 sm:pb-8 text-center text-muted-foreground/60 text-[10px] tracking-[0.3em] sm:tracking-[0.4em] uppercase",children:[e("welcome.premiumTag"),y.jsx("div",{className:"mt-2 tracking-normal normal-case",children:y.jsx(Cv,{focusKey:"privacy-link",onEnter:()=>t("/privacy"),onClick:()=>t("/privacy"),subtle:!0,className:"text-[11px] tracking-wide text-primary/70 hover:text-primary transition-colors underline-offset-4 hover:underline bg-transparent border-transparent","data-testid":"welcome-privacy-link",children:"Privacy Policy"})})]}),y.jsx(ele,{})]})},nle=()=>{const t=qr(),{t:e}=Wr(),{login:n}=Bs(),[r,i]=D.useState(""),[s,a]=D.useState(""),[o,l]=D.useState(null),[c,u]=D.useState(!1),d=async h=>{if(h.preventDefault(),!(!r||!s)){l(null),u(!0);try{(await n(r.trim(),s)).role==="admin"?t("/admin"):t("/")}catch(f){l(f instanceof Error?f.message:String(f))}finally{u(!1)}}};return y.jsxs("div",{"data-testid":"login-page",className:"relative min-h-screen w-full overflow-hidden flex items-center justify-center px-4 py-10",children:[y.jsx("div",{className:"absolute inset-0 bg-cover bg-center bg-no-repeat",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),y.jsx("div",{className:"absolute inset-0 bg-background/60"}),y.jsx("button",{type:"button",onClick:()=>t("/welcome"),"data-testid":"login-back-btn",className:"absolute z-20 top-4 sm:top-6 start-4 sm:start-6 w-10 h-10 sm:w-11 sm:h-11 rounded-full glass flex items-center justify-center text-muted-foreground hover:text-foreground hover:border-primary/40 transition-colors",children:y.jsx(ev,{className:"w-5 h-5 rtl:rotate-180"})}),y.jsx("div",{className:"absolute z-20 top-4 sm:top-6 end-4 sm:end-6",children:y.jsx(fm,{align:"right"})}),y.jsxs($t.form,{onSubmit:d,initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.6,ease:"easeOut"},className:"relative z-10 glass-card rounded-3xl p-6 sm:p-8 w-full max-w-md",children:[y.jsxs("div",{className:"flex flex-col items-center mb-6",children:[y.jsx("div",{className:"w-14 h-14 sm:w-16 sm:h-16 rounded-2xl glass flex items-center justify-center mb-3",style:{border:"1px solid hsla(40, 80%, 55%, 0.4)",boxShadow:"0 0 40px hsla(40, 80%, 55%, 0.3)"},children:y.jsx(xa,{className:"w-7 h-7 sm:w-8 sm:h-8 text-primary gold-glow",strokeWidth:1.4})}),y.jsx("h1",{className:"font-display text-xl sm:text-2xl tracking-[0.3em] gold-text",children:"NADIPLAYER"}),y.jsx("p",{className:"text-muted-foreground text-[10px] sm:text-xs tracking-[0.25em] uppercase mt-2 text-center",children:e("login.subtitle")})]}),y.jsxs("div",{className:"space-y-3",children:[y.jsxs("div",{className:"flex items-center gap-3 glass-input rounded-xl px-4 py-3",children:[y.jsx(fo,{className:"w-5 h-5 text-muted-foreground shrink-0"}),y.jsx("input",{"data-testid":"login-username-input",type:"text",placeholder:e("login.username"),value:r,onChange:h=>i(h.target.value),className:"flex-1 min-w-0 bg-transparent text-foreground placeholder:text-muted-foreground outline-none text-sm",autoComplete:"username",autoFocus:!0})]}),y.jsxs("div",{className:"flex items-center gap-3 glass-input rounded-xl px-4 py-3",children:[y.jsx(rv,{className:"w-5 h-5 text-muted-foreground shrink-0"}),y.jsx("input",{"data-testid":"login-password-input",type:"password",placeholder:e("login.password"),value:s,onChange:h=>a(h.target.value),className:"flex-1 min-w-0 bg-transparent text-foreground placeholder:text-muted-foreground outline-none text-sm",autoComplete:"current-password"})]})]}),o&&y.jsx("div",{"data-testid":"login-error",className:"mt-4 text-destructive text-xs bg-destructive/10 border border-destructive/30 rounded-lg px-3 py-2",children:o}),y.jsxs("button",{type:"submit",disabled:c||!r||!s,"data-testid":"login-submit-btn",className:"w-full mt-6 py-3 rounded-xl bg-gradient-to-r from-primary/80 to-primary/60 text-primary-foreground font-medium text-sm hover:from-primary hover:to-primary/80 transition-all flex items-center justify-center gap-2 disabled:opacity-60",children:[c&&y.jsx(yr,{className:"w-4 h-4 animate-spin"}),e(c?"login.submitting":"login.submit")]}),y.jsx("p",{className:"mt-5 text-center text-muted-foreground text-[10px] sm:text-[11px] tracking-wide",children:e("login.contactAdmin")})]})]})},IA=({portalUrl:t,mac:e,testId:n,compact:r=!1})=>{const[i,s]=D.useState("idle"),[a,o]=D.useState(""),l=i==="loading"||!t.trim()||!Bj(e.trim()),c=async()=>{if(l)return;s("loading"),o("");const h=Mt.loading("Contacting Stalker portal…");try{const f=await _v.handshake(t.trim(),e.trim().toUpperCase());s("ok");const p=f.profile.expire_billing_date,m=f.profile.name||f.profile.mac||"device";o(p?`Active until ${p}`:"Connection OK"),Mt.success(`Stalker portal accepted ${m}`+(p?` · expires ${p}`:""),{id:h})}catch(f){s("fail");const p=(f==null?void 0:f.message)||"Connection failed";o(p),Mt.error(`Test failed: ${p}`,{id:h})}},u=i==="loading"?yr:i==="ok"?Ol:i==="fail"?Sa:MK,d=i==="ok"?"text-emerald-400 border-emerald-500/40":i==="fail"?"text-destructive border-destructive/40":"text-primary hover:border-primary/40";return r?y.jsx("button",{type:"button",onClick:c,disabled:l,"data-testid":n,title:"Test connection",className:`flex items-center justify-center w-8 h-8 rounded-lg glass border transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${d}`,children:y.jsx(u,{className:`w-3.5 h-3.5 ${i==="loading"?"animate-spin":""}`})}):y.jsxs("div",{className:"space-y-1.5",children:[y.jsxs("button",{type:"button",onClick:c,disabled:l,"data-testid":n,className:`w-full flex items-center justify-center gap-2 py-2 rounded-lg glass border text-xs font-medium tracking-[0.15em] uppercase transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${d}`,children:[y.jsx(u,{className:`w-3.5 h-3.5 ${i==="loading"?"animate-spin":""}`}),i==="loading"?"Testing…":i==="ok"?"Connected":i==="fail"?"Failed — try again":"Test Connection"]}),a&&y.jsx("p",{"data-testid":n?`${n}-detail`:void 0,className:`text-[10px] px-1 leading-relaxed ${i==="ok"?"text-emerald-400/80":"text-muted-foreground"}`,children:a})]})},rle=()=>{const t=qr(),{t:e}=Wr(),{user:n,logout:r}=Bs(),[i,s]=D.useState([]),[a,o]=D.useState(null),[l,c]=D.useState(!0),[u,d]=D.useState(null),[h,f]=D.useState(""),[p,m]=D.useState(""),[g,b]=D.useState(30),[v,S]=D.useState("shared"),[E,L]=D.useState(""),[U,O]=D.useState(""),[k,I]=D.useState(""),[R,M]=D.useState(!1),z=X=>{d(X),window.setTimeout(()=>d(null),2400)};D.useEffect(()=>{if(!n||n.role!=="admin"){t("/welcome");return}Z()},[n]);const Z=async()=>{c(!0);try{const[X,oe]=await Promise.all([EJ(),AJ()]);s(X),o(oe)}catch(X){z(X instanceof Error?X.message:e("admin.loadFailed"))}finally{c(!1)}},W=async X=>{if(X.preventDefault(),!(!h||!p)){M(!0);try{await wJ({username:h.trim(),password:p,days:g,xtream_mode:v,xtream_server:E||void 0,xtream_username:U||void 0,xtream_password:k||void 0}),f(""),m(""),b(30),S("shared"),L(""),O(""),I(""),z(e("admin.userCreated")),await Z()}catch(oe){z(oe instanceof Error?oe.message:e("admin.opFailed"))}finally{M(!1)}}},re=()=>{r(),t("/welcome")};return y.jsxs("div",{"data-testid":"admin-page",className:"relative min-h-screen w-full overflow-hidden",children:[y.jsx("div",{className:"absolute inset-0 bg-cover bg-center",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),y.jsx("div",{className:"absolute inset-0 bg-background/70"}),y.jsxs("div",{className:"relative z-10 min-h-screen flex flex-col",children:[y.jsxs("header",{className:"flex flex-wrap items-center justify-between px-4 sm:px-6 md:px-10 pt-6 gap-3",children:[y.jsxs("div",{className:"flex items-center gap-3",children:[y.jsx("div",{className:"w-10 h-10 sm:w-12 sm:h-12 rounded-xl glass flex items-center justify-center",style:{border:"1px solid hsla(40, 80%, 55%, 0.4)"},children:y.jsx(xa,{className:"w-5 h-5 text-primary gold-glow"})}),y.jsxs("div",{children:[y.jsx("h1",{className:"font-display text-lg sm:text-xl md:text-2xl tracking-[0.2em] sm:tracking-[0.3em] gold-text",children:e("admin.title")}),y.jsx("p",{className:"text-muted-foreground text-[9px] sm:text-[10px] tracking-[0.3em] uppercase",children:e("admin.subtitle")})]})]}),y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx(fm,{align:"right"}),y.jsx("button",{onClick:Z,"data-testid":"admin-refresh-btn",className:"w-10 h-10 sm:w-11 sm:h-11 rounded-full glass flex items-center justify-center text-muted-foreground hover:text-primary hover:border-primary/40 transition-colors",title:e("common.refresh"),children:y.jsx(jK,{className:`w-5 h-5 ${l?"animate-spin":""}`})}),y.jsxs("button",{onClick:re,"data-testid":"admin-logout-btn",className:"flex items-center gap-2 px-3 sm:px-4 py-2 rounded-full glass text-muted-foreground hover:text-foreground hover:border-primary/40 transition-colors text-xs sm:text-sm",children:[y.jsx(A2,{className:"w-4 h-4"})," ",y.jsx("span",{className:"hidden sm:inline",children:e("admin.logout")})]})]})]}),u&&y.jsx($t.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},className:"fixed top-6 left-1/2 -translate-x-1/2 z-50 glass-card rounded-full px-5 py-2 text-sm text-primary border border-primary/30",children:u}),y.jsxs("main",{className:"flex-1 px-3 sm:px-4 md:px-10 py-6 sm:py-8 space-y-6 sm:space-y-8 max-w-7xl mx-auto w-full",children:[y.jsx(sle,{settings:a,onSaved:X=>{o(X),z(e("admin.settingsSaved"))}}),y.jsxs("section",{className:"glass-card rounded-2xl p-6",children:[y.jsx("h2",{className:"font-display text-lg tracking-[0.2em] gold-text mb-4",children:e("admin.createHeading")}),y.jsxs("form",{onSubmit:W,className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3",children:[y.jsx(bn,{label:e("admin.usernameLabel"),value:h,onChange:f,testId:"nu-username",required:!0}),y.jsx(bn,{label:e("admin.passwordLabel"),value:p,onChange:m,type:"text",testId:"nu-password",required:!0}),y.jsx(bn,{label:e("admin.daysLabel"),value:String(g),onChange:X=>b(Math.max(1,parseInt(X||"0")||1)),type:"number",testId:"nu-days"}),y.jsxs("div",{children:[y.jsx("label",{className:"text-[11px] text-muted-foreground tracking-[0.2em] uppercase block mb-1",children:e("admin.xtreamMode")}),y.jsxs("select",{value:v,onChange:X=>S(X.target.value),"data-testid":"nu-mode",className:"w-full glass-input rounded-lg px-3 py-2 text-sm text-foreground outline-none",children:[y.jsx("option",{value:"shared",children:e("admin.modeShared")}),y.jsx("option",{value:"own",children:e("admin.modeOwn")})]})]}),v==="own"&&y.jsxs(y.Fragment,{children:[y.jsx(bn,{label:e("admin.serverUrl"),value:E,onChange:L,testId:"nu-server"}),y.jsx(bn,{label:e("admin.xtreamUsername"),value:U,onChange:O,testId:"nu-xuser"}),y.jsx(bn,{label:e("admin.xtreamPassword"),value:k,onChange:I,testId:"nu-xpass"})]}),y.jsx("div",{className:"md:col-span-2 lg:col-span-4 flex justify-end",children:y.jsxs("button",{type:"submit",disabled:R,"data-testid":"nu-submit",className:"flex items-center gap-2 px-5 py-2.5 rounded-xl bg-primary/80 hover:bg-primary text-primary-foreground font-medium text-sm transition-colors disabled:opacity-60",children:[R?y.jsx(yr,{className:"w-4 h-4 animate-spin"}):y.jsx(gl,{className:"w-4 h-4"}),e(R?"admin.creating":"admin.createUser")]})})]})]}),y.jsxs("section",{className:"glass-card rounded-2xl p-6",children:[y.jsx("h2",{className:"font-display text-lg tracking-[0.2em] gold-text mb-4",children:e("admin.subscribersHeading",{count:i.length})}),i.length===0?y.jsx("p",{className:"text-muted-foreground text-sm",children:e("admin.noSubscribers")}):y.jsx("div",{className:"space-y-3",children:i.map(X=>y.jsx(ale,{user:X,onChanged:Z,onToast:z},X.id))})]})]})]})]})},ile=({idx:t,content:e,onChange:n})=>{const[r,i]=D.useState(""),[s,a]=D.useState(!1),o=async d=>{if(d){a(!0);try{const h=await d.text();n(h),i(d.name)}finally{a(!1)}}},l=()=>{n(""),i("")},c=!!(e&&e.trim().length),u=c?e.split(/\r?\n/).filter(Boolean).length:0;return y.jsxs("div",{children:[y.jsx("label",{className:"text-[11px] text-muted-foreground tracking-[0.2em] uppercase block mb-1",children:"M3U File (optional)"}),y.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[y.jsxs("label",{"data-testid":`profile-m3u-file-${t}`,className:"cursor-pointer flex items-center gap-2 px-3 py-2 rounded-lg glass text-xs text-primary hover:border-primary/40 transition-colors",children:[s?y.jsx(yr,{className:"w-3.5 h-3.5 animate-spin"}):y.jsx(ET,{className:"w-3.5 h-3.5"}),y.jsx("span",{children:s?"Reading…":"Upload .m3u"}),y.jsx("input",{type:"file",accept:".m3u,.m3u8,audio/x-mpegurl,application/vnd.apple.mpegurl,text/plain",onChange:d=>{var h;return void o(((h=d.target.files)==null?void 0:h[0])??null)},className:"hidden"})]}),c&&y.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0 text-xs text-muted-foreground",children:[y.jsx(bT,{className:"w-3.5 h-3.5 text-primary shrink-0"}),y.jsxs("span",{className:"truncate",children:[r||"uploaded file"," · ",u," lines"]}),y.jsx("button",{type:"button",onClick:l,"data-testid":`profile-m3u-file-clear-${t}`,className:"ml-1 text-muted-foreground hover:text-destructive",title:"Remove uploaded file",children:y.jsx(Sa,{className:"w-3.5 h-3.5"})})]})]}),y.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Upload a playlist file directly. When set, this is used instead of the URL above."})]})},bn=({label:t,value:e,onChange:n,type:r="text",testId:i,required:s})=>y.jsxs("div",{children:[y.jsx("label",{className:"text-[11px] text-muted-foreground tracking-[0.2em] uppercase block mb-1",children:t}),y.jsx("input",{type:r,value:e,onChange:a=>n(a.target.value),"data-testid":i,required:s,className:"w-full glass-input rounded-lg px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground outline-none"})]}),sle=({settings:t,onSaved:e})=>{const{t:n}=Wr(),[r,i]=D.useState((t==null?void 0:t.whatsapp_number)??""),[s,a]=D.useState((t==null?void 0:t.shared_profiles)??[]),[o,l]=D.useState((t==null?void 0:t.external_player_enabled)??!1),[c,u]=D.useState((t==null?void 0:t.update_enabled)??!1),[d,h]=D.useState((t==null?void 0:t.app_version)??"1.0.0"),[f,p]=D.useState((t==null?void 0:t.min_supported_version)??"1.0.0"),[m,g]=D.useState((t==null?void 0:t.update_apk_url)??""),[b,v]=D.useState((t==null?void 0:t.update_play_url)??""),[S,E]=D.useState((t==null?void 0:t.update_changelog)??""),[L,U]=D.useState((t==null?void 0:t.whatsapp_message)??""),[O,k]=D.useState((t==null?void 0:t.support_email)??""),[I,R]=D.useState((t==null?void 0:t.creator_name)??""),[M,z]=D.useState((t==null?void 0:t.creator_role)??""),[Z,W]=D.useState((t==null?void 0:t.creator_avatar_url)??""),[re,X]=D.useState((t==null?void 0:t.creator_bio)??""),[oe,Q]=D.useState((t==null?void 0:t.privacy_policy_text)??""),[G,H]=D.useState(!1);D.useEffect(()=>{i((t==null?void 0:t.whatsapp_number)??""),a((t==null?void 0:t.shared_profiles)??[]),l((t==null?void 0:t.external_player_enabled)??!1),u((t==null?void 0:t.update_enabled)??!1),h((t==null?void 0:t.app_version)??"1.0.0"),p((t==null?void 0:t.min_supported_version)??"1.0.0"),g((t==null?void 0:t.update_apk_url)??""),v((t==null?void 0:t.update_play_url)??""),E((t==null?void 0:t.update_changelog)??""),U((t==null?void 0:t.whatsapp_message)??""),k((t==null?void 0:t.support_email)??""),R((t==null?void 0:t.creator_name)??""),z((t==null?void 0:t.creator_role)??""),W((t==null?void 0:t.creator_avatar_url)??""),X((t==null?void 0:t.creator_bio)??""),Q((t==null?void 0:t.privacy_policy_text)??"")},[t]);const Y=ke=>{a(Ne=>[...Ne,{id:`tmp-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,name:ke==="xtream"?"New Xtream":ke==="stalker"?"New Stalker":"New M3U",kind:ke,server:"",username:"",password:"",m3u_url:"",m3u_content:"",portal_url:"",mac_address:""}])},ie=(ke,Ne)=>a(ye=>ye.map((Ie,Ae)=>Ae===ke?{...Ie,...Ne}:Ie)),Ce=ke=>a(Ne=>Ne.filter((ye,Ie)=>Ie!==ke)),Le=async()=>{H(!0);try{const ke=await RJ({whatsapp_number:r,shared_profiles:s,external_player_enabled:o,update_enabled:c,app_version:d,min_supported_version:f,update_apk_url:m,update_play_url:b,update_changelog:S,whatsapp_message:L,support_email:O,creator_name:I,creator_role:M,creator_avatar_url:Z,creator_bio:re,privacy_policy_text:oe});e(ke)}catch(ke){alert(ke instanceof Error?ke.message:"Save failed")}finally{H(!1)}};return y.jsxs("section",{className:"glass-card rounded-2xl p-6 space-y-5",children:[y.jsx("h2",{className:"font-display text-lg tracking-[0.2em] gold-text",children:n("admin.settingsHeading")}),y.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:y.jsx(bn,{label:n("admin.whatsapp"),value:r,onChange:i,testId:"set-whatsapp"})}),y.jsx("div",{className:"glass rounded-xl p-4 border border-border/60",children:y.jsxs("label",{className:"flex items-start gap-3 cursor-pointer select-none",children:[y.jsx("input",{type:"checkbox",checked:o,onChange:ke=>l(ke.target.checked),"data-testid":"toggle-external-player",className:"mt-1 w-4 h-4 accent-primary cursor-pointer"}),y.jsxs("div",{className:"flex-1 min-w-0",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("span",{className:"text-sm font-medium text-foreground",children:"External Player"}),y.jsx("span",{className:`text-[10px] px-2 py-0.5 rounded-full ${o?"bg-amber-500/20 text-amber-400":"bg-primary/20 text-primary"}`,children:o?"ON":"OFF"})]}),y.jsx("p",{className:"text-xs text-muted-foreground mt-1 leading-relaxed",children:o?"Videos open in VLC / MX Player / Brouken. If users don't have one installed, playback will fail.":"Videos play inside the app using the built-in ExoPlayer. No third-party app needed — recommended."})]})]})}),y.jsxs("div",{className:"rounded-2xl border border-border/60 bg-background/30 p-4 space-y-3","data-testid":"admin-update-section",children:[y.jsxs("div",{className:"flex items-center justify-between gap-2",children:[y.jsx("h3",{className:"text-sm font-medium text-foreground/90 tracking-wide",children:"In-App Update"}),y.jsxs("label",{className:"flex items-center gap-2 cursor-pointer select-none",children:[y.jsx("input",{type:"checkbox",checked:c,onChange:ke=>u(ke.target.checked),"data-testid":"set-update-enabled",className:"w-4 h-4 accent-primary cursor-pointer"}),y.jsx("span",{className:`text-[10px] px-2 py-0.5 rounded-full ${c?"bg-primary/20 text-primary":"bg-muted/40 text-muted-foreground"}`,children:c?"ENABLED":"DISABLED"})]})]}),y.jsxs("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:["When enabled, every user (logged in or guest) sees a popup if their installed version is older than"," ",y.jsx("code",{className:"text-primary",children:"Latest version"}),". If their version is older than"," ",y.jsx("code",{className:"text-primary",children:"Min supported version"}),", the popup BLOCKS the app entirely until they update."]}),y.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[y.jsx(bn,{label:"Latest version (e.g. 1.2.0)",value:d,onChange:h,testId:"set-app-version"}),y.jsx(bn,{label:"Min supported version (force-update threshold)",value:f,onChange:p,testId:"set-min-version"}),y.jsx(bn,{label:"Direct APK download URL",value:m,onChange:g,testId:"set-apk-url"}),y.jsx(bn,{label:"Google Play Store URL",value:b,onChange:v,testId:"set-play-url"})]}),y.jsxs("div",{children:[y.jsx("label",{className:"text-[11px] text-muted-foreground tracking-[0.2em] uppercase block mb-1",children:"What's new (changelog)"}),y.jsx("textarea",{value:S,onChange:ke=>E(ke.target.value),"data-testid":"set-changelog",rows:4,placeholder:`• Faster startup
• Bug fixes
• New languages`,className:"w-full glass-input rounded-lg px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground outline-none resize-y"})]})]}),y.jsxs("div",{className:"rounded-2xl border border-border/60 bg-background/30 p-4 space-y-3","data-testid":"admin-creator-section",children:[y.jsx("h3",{className:"text-sm font-medium text-foreground/90 tracking-wide",children:"Creator Info"}),y.jsx("p",{className:"text-[11px] text-muted-foreground",children:`Shown on every user's Account page under "Help & About".`}),y.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[y.jsx(bn,{label:"Creator name",value:I,onChange:R,testId:"set-creator-name"}),y.jsx(bn,{label:"Role / title (e.g. Developer)",value:M,onChange:z,testId:"set-creator-role"}),y.jsx("div",{className:"md:col-span-2",children:y.jsx(bn,{label:"Avatar URL (https://…)",value:Z,onChange:W,testId:"set-creator-avatar"})})]}),y.jsxs("div",{children:[y.jsx("label",{className:"text-[11px] text-muted-foreground tracking-[0.2em] uppercase block mb-1",children:"Short bio"}),y.jsx("textarea",{value:re,onChange:ke=>X(ke.target.value),"data-testid":"set-creator-bio",rows:3,className:"w-full glass-input rounded-lg px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground outline-none resize-y"})]})]}),y.jsxs("div",{className:"rounded-2xl border border-border/60 bg-background/30 p-4 space-y-3","data-testid":"admin-support-section",children:[y.jsx("h3",{className:"text-sm font-medium text-foreground/90 tracking-wide",children:"Support & Privacy"}),y.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[y.jsx(bn,{label:"Support email",value:O,onChange:k,testId:"set-support-email"}),y.jsx(bn,{label:"WhatsApp prefilled message",value:L,onChange:U,testId:"set-wa-message"})]}),y.jsxs("div",{children:[y.jsx("label",{className:"text-[11px] text-muted-foreground tracking-[0.2em] uppercase block mb-1",children:"Privacy policy text"}),y.jsx("textarea",{value:oe,onChange:ke=>Q(ke.target.value),"data-testid":"set-privacy-text",rows:6,className:"w-full glass-input rounded-lg px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground outline-none resize-y leading-relaxed"}),y.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Plain text or markdown — shown verbatim on the /privacy page."})]})]}),y.jsxs("div",{children:[y.jsxs("div",{className:"flex items-center justify-between mb-3",children:[y.jsx("h3",{className:"text-sm font-medium text-foreground/90 tracking-wide",children:"Shared Profiles"}),y.jsxs("div",{className:"flex gap-2",children:[y.jsxs("button",{onClick:()=>Y("xtream"),"data-testid":"add-xtream-profile",className:"flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-lg glass hover:border-primary/40 text-foreground",children:[y.jsx(gl,{className:"w-3.5 h-3.5"})," Xtream"]}),y.jsxs("button",{onClick:()=>Y("m3u"),"data-testid":"add-m3u-profile",className:"flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-lg glass hover:border-primary/40 text-foreground",children:[y.jsx(gl,{className:"w-3.5 h-3.5"})," M3U"]}),y.jsxs("button",{onClick:()=>Y("stalker"),"data-testid":"add-stalker-profile",className:"flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-lg glass hover:border-primary/40 text-foreground",children:[y.jsx(gl,{className:"w-3.5 h-3.5"})," Stalker"]})]})]}),s.length===0?y.jsx("p",{className:"text-muted-foreground text-xs bg-muted/30 border border-border rounded-lg px-3 py-3",children:"No shared profiles yet. Add one above — logged-in users will be able to pick it from the playlist dialog. Guests never see these."}):y.jsx("div",{className:"space-y-3",children:s.map((ke,Ne)=>y.jsxs("div",{"data-testid":`profile-row-${Ne}`,className:"glass rounded-xl p-3 border border-border/60",children:[y.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[y.jsx("span",{className:"text-[10px] uppercase tracking-widest text-primary/80 bg-primary/10 px-2 py-0.5 rounded",children:ke.kind==="m3u"?"M3U":ke.kind==="stalker"?"Stalker":"Xtream"}),y.jsx("button",{onClick:()=>Ce(Ne),"data-testid":`remove-profile-${Ne}`,className:"ml-auto text-muted-foreground hover:text-destructive transition-colors","aria-label":"Remove",children:y.jsx(nm,{className:"w-4 h-4"})})]}),y.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:[y.jsx(bn,{label:"Profile Name",value:ke.name,onChange:ye=>ie(Ne,{name:ye}),testId:`profile-name-${Ne}`}),ke.kind==="xtream"?y.jsxs(y.Fragment,{children:[y.jsx(bn,{label:"Server URL",value:ke.server??"",onChange:ye=>ie(Ne,{server:ye}),testId:`profile-server-${Ne}`}),y.jsx(bn,{label:"Username",value:ke.username??"",onChange:ye=>ie(Ne,{username:ye}),testId:`profile-user-${Ne}`}),y.jsx(bn,{label:"Password",value:ke.password??"",onChange:ye=>ie(Ne,{password:ye}),testId:`profile-pass-${Ne}`})]}):ke.kind==="stalker"?y.jsxs(y.Fragment,{children:[y.jsx(bn,{label:"Portal URL",value:ke.portal_url??"",onChange:ye=>ie(Ne,{portal_url:ye}),testId:`profile-portal-${Ne}`}),y.jsx(bn,{label:"MAC Address (00:1A:79:XX:XX:XX)",value:ke.mac_address??"",onChange:ye=>{var Ie;return ie(Ne,{mac_address:((Ie=ye.replace(/[^0-9A-Fa-f]/g,"").toUpperCase().slice(0,12).match(/.{1,2}/g))==null?void 0:Ie.join(":"))??""})},testId:`profile-mac-${Ne}`}),y.jsx("div",{className:"md:col-span-2",children:y.jsx(IA,{portalUrl:ke.portal_url??"",mac:ke.mac_address??"",testId:`profile-stalker-test-${Ne}`})})]}):y.jsxs("div",{className:"md:col-span-2 space-y-2",children:[y.jsx(bn,{label:"M3U URL",value:ke.m3u_url??"",onChange:ye=>ie(Ne,{m3u_url:ye}),testId:`profile-m3u-${Ne}`}),y.jsx(ile,{idx:Ne,content:ke.m3u_content??"",onChange:ye=>ie(Ne,{m3u_content:ye})})]})]})]},ke.id||Ne))})]}),y.jsx("div",{className:"flex justify-end",children:y.jsxs("button",{onClick:Le,disabled:G,"data-testid":"set-save",className:"flex items-center gap-2 px-5 py-2.5 rounded-xl bg-primary/80 hover:bg-primary text-primary-foreground font-medium text-sm transition-colors disabled:opacity-60",children:[G?y.jsx(yr,{className:"w-4 h-4 animate-spin"}):y.jsx(VK,{className:"w-4 h-4"}),n(G?"common.saving":"admin.saveSettings")]})})]})},ale=({user:t,onChanged:e,onToast:n})=>{const{t:r}=Wr(),[i,s]=D.useState(!1),[a,o]=D.useState(""),[l,c]=D.useState(t.xtream_mode||"shared"),[u,d]=D.useState(t.xtream_server||""),[h,f]=D.useState(t.xtream_username||""),[p,m]=D.useState(t.xtream_password||""),g=async L=>{s(!0);try{await pb(t.id,{extend_days:L}),n(L>0?r("admin.dayAdded",{count:L}):r("admin.dayRemoved",{count:-L})),e()}catch(U){n(U instanceof Error?U.message:r("admin.opFailed"))}finally{s(!1)}},b=async()=>{if(a){s(!0);try{await pb(t.id,{password:a}),n(r("admin.passwordUpdated")),o(""),e()}catch(L){n(L instanceof Error?L.message:r("admin.opFailed"))}finally{s(!1)}}},v=async()=>{s(!0);try{await pb(t.id,{xtream_mode:l,xtream_server:u,xtream_username:h,xtream_password:p}),n(r("admin.xtreamSaved")),e()}catch(L){n(L instanceof Error?L.message:r("admin.opFailed"))}finally{s(!1)}},S=async()=>{if(window.confirm(r("admin.confirmDeleteUser",{username:t.username}))){s(!0);try{await TJ(t.id),n(r("admin.userDeleted")),e()}catch(L){n(L instanceof Error?L.message:r("admin.opFailed"))}finally{s(!1)}}},E=t.is_expired?"text-destructive":(t.days_remaining??0)<=3?"text-amber-400":"text-primary";return y.jsxs("div",{className:"rounded-xl border border-border/40 glass p-4",children:[y.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-3",children:[y.jsxs("div",{className:"flex items-center gap-4",children:[y.jsx("div",{className:"w-10 h-10 rounded-full glass flex items-center justify-center",children:y.jsx(xa,{className:"w-4 h-4 text-primary"})}),y.jsxs("div",{children:[y.jsx("p",{"data-testid":`user-${t.username}-name`,className:"text-foreground font-medium",children:t.username}),y.jsxs("p",{className:"text-muted-foreground text-xs flex items-center gap-2",children:[y.jsx(GH,{className:"w-3 h-3"}),t.expiry_at?new Date(t.expiry_at).toLocaleDateString():r("admin.noExpiry"),y.jsx("span",{className:`ms-2 ${E}`,children:t.is_expired?r("admin.expired"):t.days_remaining!=null?r("admin.daysLeft",{count:t.days_remaining}):""})]})]})]}),y.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[y.jsx("button",{onClick:()=>g(30),disabled:i,"data-testid":`user-${t.username}-add30`,className:"px-3 py-1.5 rounded-lg glass text-xs text-primary hover:border-primary/40 transition-colors disabled:opacity-60",children:r("admin.addDays",{n:30})}),y.jsx("button",{onClick:()=>g(7),disabled:i,className:"px-3 py-1.5 rounded-lg glass text-xs text-primary hover:border-primary/40 transition-colors disabled:opacity-60",children:r("admin.addDays",{n:7})}),y.jsx("button",{onClick:()=>g(-7),disabled:i,className:"px-3 py-1.5 rounded-lg glass text-xs text-muted-foreground hover:border-destructive/40 transition-colors disabled:opacity-60",children:r("admin.subDays",{n:7})}),y.jsxs("button",{onClick:S,disabled:i,"data-testid":`user-${t.username}-delete`,className:"px-3 py-1.5 rounded-lg glass text-xs text-destructive hover:border-destructive/40 transition-colors disabled:opacity-60 flex items-center gap-1",children:[y.jsx(nm,{className:"w-3 h-3"})," ",r("admin.deleteUser")]})]})]}),y.jsxs("details",{className:"mt-3",children:[y.jsx("summary",{className:"cursor-pointer text-xs text-muted-foreground tracking-[0.2em] uppercase hover:text-primary",children:r("admin.advanced")}),y.jsxs("div",{className:"mt-3 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3",children:[y.jsxs("div",{children:[y.jsx("label",{className:"text-[11px] text-muted-foreground tracking-[0.2em] uppercase block mb-1",children:r("admin.xtreamMode")}),y.jsxs("select",{value:l,onChange:L=>c(L.target.value),className:"w-full glass-input rounded-lg px-3 py-2 text-sm text-foreground outline-none",children:[y.jsx("option",{value:"shared",children:r("admin.modeShared")}),y.jsx("option",{value:"own",children:r("admin.modeOwn")})]})]}),y.jsx(bn,{label:r("admin.server"),value:u,onChange:d}),y.jsx(bn,{label:r("admin.xtUser"),value:h,onChange:f}),y.jsx(bn,{label:r("admin.xtPass"),value:p,onChange:m}),y.jsx("div",{className:"lg:col-span-4 flex gap-2 justify-end",children:y.jsxs("button",{onClick:v,disabled:i,className:"flex items-center gap-2 px-4 py-2 rounded-lg glass text-xs text-primary hover:border-primary/40 transition-colors disabled:opacity-60",children:[y.jsx(Cc,{className:"w-3 h-3"})," ",r("admin.saveXtream")]})}),y.jsxs("div",{className:"lg:col-span-4 flex items-center gap-2",children:[y.jsx("input",{type:"text",value:a,onChange:L=>o(L.target.value),placeholder:r("admin.newPassword"),className:"flex-1 glass-input rounded-lg px-3 py-2 text-sm text-foreground outline-none"}),y.jsx("button",{onClick:b,disabled:i||!a,className:"px-4 py-2 rounded-lg glass text-xs text-primary hover:border-primary/40 transition-colors disabled:opacity-60",children:r("admin.updatePassword")})]})]})]})]})},PA=()=>{const{addProfile:t,setActiveProfileId:e}=mo(),n=$j();return async r=>{const i=Mt.loading(`Connecting to ${r.name}...`);try{const s={name:r.name,kind:r.kind,serverUrl:r.serverUrl,username:r.username,password:r.password,m3uUrl:r.m3uUrl,m3uContent:r.m3uContent,portalUrl:r.portalUrl,macAddress:r.macAddress};if(r.kind==="xtream")await ps.authenticate(s);else if(r.kind==="m3u"){if(!(!!(r.m3uContent&&r.m3uContent.trim().length)?Df.parsePlaylistText(r.m3uContent):await Df.fetchPlaylist(r.m3uUrl)).length)throw new Error("Empty playlist")}else if(r.kind==="stalker"){if(!r.portalUrl)throw new Error("Portal URL is required");if(!r.macAddress||!Bj(r.macAddress))throw new Error("MAC must be in 00:1A:79:XX:XX:XX format");if((await _v.handshake(r.portalUrl,r.macAddress)).profile.blocked)throw new Error("This MAC is blocked on the portal")}const a=t(s);e(a.id),Mt.loading("Loading channels, movies & series...",{id:i});const o=await n(a);return Mt.success(`Connected! ${o.channels.length} channels • ${o.movies.length} movies • ${o.series.length} series`,{id:i}),a}catch(s){return Mt.error(`Failed: ${s.message||"Connection error"}`,{id:i}),null}}},JI=(t="",e="")=>({key:`r-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,name:t,url:e,content:"",fileName:""}),ole=()=>{const t=qr(),[e]=QM(),n=PA(),[r,i]=D.useState(e.get("type")||"xtream"),[s,a]=D.useState(e.get("name")||""),[o,l]=D.useState(e.get("server")||""),[c,u]=D.useState(e.get("user")||""),[d,h]=D.useState(e.get("pass")||""),[f,p]=D.useState(e.get("portal")||""),[m,g]=D.useState(e.get("mac")||""),[b,v]=D.useState([JI(e.get("name")||"",e.get("url")||"")]),[S,E]=D.useState(!1),L=M=>{var Z;return((Z=M.replace(/[^0-9A-Fa-f]/g,"").toUpperCase().slice(0,12).match(/.{1,2}/g))==null?void 0:Z.join(":"))??""},U=(M,z)=>v(Z=>Z.map((W,re)=>re===M?{...W,...z}:W)),O=()=>v(M=>[...M,JI()]),k=M=>v(z=>z.length>1?z.filter((Z,W)=>W!==M):z),I=async(M,z)=>{if(!z)return;const Z=await z.text();U(M,{content:Z,fileName:z.name})},R=async M=>{if(M==null||M.preventDefault(),r==="xtream"){if(!s||!o||!c||!d)return;E(!0);const W=await n({kind:r,name:s,serverUrl:o,username:c,password:d});E(!1),W&&t("/");return}if(r==="stalker"){const W=/^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$/.test(m.trim());if(!s||!f.trim()||!W)return;E(!0);const re=await n({kind:r,name:s,serverUrl:"",username:"",password:"",portalUrl:f.trim(),macAddress:m.trim().toUpperCase()});E(!1),re&&t("/");return}const z=b.map((W,re)=>({...W,name:(W.name||s||`Playlist ${re+1}`).trim(),url:W.url.trim()})).filter(W=>W.url.length>0||W.content.trim().length>0);if(z.length===0)return;E(!0);let Z=null;for(const W of z)Z=await n({kind:"m3u",name:W.name,serverUrl:"",username:"",password:"",m3uUrl:W.url||void 0,m3uContent:W.content||void 0});E(!1),Z&&t("/")};return D.useEffect(()=>{e.get("auto")==="1"&&R()},[]),y.jsxs("div",{className:"relative min-h-screen w-full overflow-hidden flex items-center justify-center px-4 py-8",children:[y.jsx("div",{className:"absolute inset-0 bg-cover bg-center bg-no-repeat",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),y.jsx("div",{className:"absolute inset-0 bg-background/60"}),y.jsxs($t.form,{onSubmit:R,initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"relative z-10 glass-card rounded-3xl p-8 w-full max-w-md",children:[y.jsxs("div",{className:"flex flex-col items-center mb-6",children:[y.jsx("div",{className:"w-14 h-14 rounded-2xl glass flex items-center justify-center mb-3",children:y.jsx(xa,{className:"w-6 h-6 text-primary"})}),y.jsx("h1",{className:"font-display text-2xl tracking-[0.25em] gold-text",children:"NADIPLAYER"}),y.jsx("p",{className:"text-muted-foreground text-xs mt-1",children:"Connect your IPTV service"})]}),y.jsx("div",{className:"flex glass rounded-xl p-1 mb-5",children:["xtream","m3u","stalker"].map(M=>y.jsx("button",{type:"button",onClick:()=>i(M),"data-testid":`kind-${M}`,className:`flex-1 py-2 rounded-lg text-xs font-medium transition-all ${r===M?"bg-primary/20 text-primary":"text-muted-foreground"}`,children:M==="xtream"?"Xtream":M==="m3u"?"M3U":"Stalker"},M))}),r==="xtream"?y.jsxs("div",{className:"space-y-3",children:[y.jsx(Ma,{icon:Rc,placeholder:"Profile Name",value:s,onChange:a}),y.jsx(Ma,{icon:Cc,placeholder:"Server URL (http://...)",value:o,onChange:l}),y.jsx(Ma,{icon:fo,placeholder:"Username",value:c,onChange:u}),y.jsx(Ma,{icon:rv,placeholder:"Password",value:d,onChange:h,type:"password"})]}):r==="stalker"?y.jsxs("div",{className:"space-y-3","data-testid":"login-stalker-form",children:[y.jsx(Ma,{icon:Rc,placeholder:"Profile Name",value:s,onChange:a,testId:"login-stalker-name"}),y.jsx(Ma,{icon:LS,placeholder:"Portal URL (http://portal.com:8080/c/)",value:f,onChange:p,testId:"login-stalker-portal"}),y.jsx(Ma,{icon:CS,placeholder:"MAC Address (00:1A:79:XX:XX:XX)",value:m,onChange:M=>g(L(M)),testId:"login-stalker-mac"}),y.jsx(IA,{portalUrl:f,mac:m,testId:"login-stalker-test"}),y.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed px-1",children:"Stalker / MAG portal. Authenticates as a MAG250 STB using your MAC."})]}):y.jsxs("div",{className:"space-y-3",children:[b.map((M,z)=>y.jsxs("div",{"data-testid":`login-m3u-row-${z}`,className:"glass rounded-xl p-3 border border-border/40 space-y-2",children:[y.jsxs("div",{className:"flex items-center justify-between",children:[y.jsxs("span",{className:"text-[10px] uppercase tracking-widest text-primary/80",children:["Playlist #",z+1]}),b.length>1&&y.jsx("button",{type:"button",onClick:()=>k(z),"data-testid":`login-m3u-row-remove-${z}`,className:"text-muted-foreground hover:text-destructive transition-colors","aria-label":"Remove row",children:y.jsx(nm,{className:"w-3.5 h-3.5"})})]}),y.jsx(Ma,{icon:Rc,placeholder:"Profile Name",value:M.name,onChange:Z=>U(z,{name:Z})}),y.jsx(Ma,{icon:kS,placeholder:"https://example.com/playlist.m3u",value:M.url,onChange:Z=>U(z,{url:Z})}),y.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[y.jsxs("label",{"data-testid":`login-m3u-file-${z}`,className:"cursor-pointer flex items-center gap-2 px-3 py-2 rounded-lg glass text-xs text-primary hover:border-primary/40 transition-colors",children:[y.jsx(ET,{className:"w-3.5 h-3.5"}),y.jsx("span",{children:"Upload .m3u file"}),y.jsx("input",{type:"file",accept:".m3u,.m3u8,audio/x-mpegurl,application/vnd.apple.mpegurl,text/plain",onChange:Z=>{var W;return void I(z,((W=Z.target.files)==null?void 0:W[0])??null)},className:"hidden"})]}),M.content&&M.content.trim().length>0&&y.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0 text-xs text-muted-foreground",children:[y.jsx(bT,{className:"w-3.5 h-3.5 text-primary shrink-0"}),y.jsx("span",{className:"truncate",children:M.fileName||"uploaded.m3u"}),y.jsx("button",{type:"button",onClick:()=>U(z,{content:"",fileName:""}),className:"ml-1 text-muted-foreground hover:text-destructive",children:y.jsx(Sa,{className:"w-3.5 h-3.5"})})]})]})]},M.key)),y.jsxs("button",{type:"button",onClick:O,"data-testid":"login-add-m3u-row-btn",className:"w-full flex items-center justify-center gap-2 py-2.5 rounded-xl border border-dashed border-primary/40 text-primary hover:bg-primary/10 transition-colors text-xs font-medium tracking-[0.2em] uppercase",children:[y.jsx(gl,{className:"w-4 h-4"})," Add Playlist"]})]}),y.jsxs("button",{type:"submit",disabled:S,className:"w-full mt-6 py-3 rounded-xl bg-gradient-to-r from-primary/80 to-primary/60 text-primary-foreground font-medium text-sm hover:from-primary hover:to-primary/80 transition-all flex items-center justify-center gap-2 disabled:opacity-60",children:[S&&y.jsx(yr,{className:"w-4 h-4 animate-spin"}),S?"Connecting...":"Connect & Load"]}),y.jsx("button",{type:"button",onClick:()=>t("/"),className:"w-full mt-3 text-muted-foreground text-xs hover:text-foreground transition-colors",children:"Skip for now"})]})]})},Ma=({icon:t,placeholder:e,value:n,onChange:r,type:i="text",testId:s})=>y.jsxs("div",{className:"flex items-center gap-3 glass-input rounded-xl px-4 py-3",children:[y.jsx(t,{className:"w-5 h-5 text-muted-foreground shrink-0"}),y.jsx("input",{type:i,placeholder:e,value:n,onChange:a=>r(a.target.value),"data-testid":s,className:"flex-1 bg-transparent text-foreground placeholder:text-muted-foreground outline-none text-sm",autoComplete:"off"})]}),Mb=()=>({key:`r-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,name:"",url:"",content:"",fileName:""}),e3=({open:t,onClose:e,onSubmit:n})=>{const{t:r}=Wr(),{user:i,isGuest:s}=Bs(),a=s||!i,[o,l]=D.useState("xtream"),[c,u]=D.useState(a?"own":"shared"),[d,h]=D.useState(""),[f,p]=D.useState(""),[m,g]=D.useState(""),[b,v]=D.useState(""),[S,E]=D.useState(""),[L,U]=D.useState(""),[O,k]=D.useState([Mb()]),[I,R]=D.useState(!1),[M,z]=D.useState([]),[Z,W]=D.useState(!1),[re,X]=D.useState(null),[oe,Q]=D.useState(null),G=()=>{h(""),p(""),g(""),v(""),k([Mb()]),Q(null),E(""),U("")};D.useEffect(()=>{if(!t||a)return;let Ae=!1;return W(!0),X(null),CJ().then(Ee=>{Ae||z(Ee.profiles||[])}).catch(Ee=>{Ae||X(Ee instanceof Error?Ee.message:"Failed")}).finally(()=>{Ae||W(!1)}),()=>{Ae=!0}},[t,a]),D.useEffect(()=>{t||(u(a?"own":"shared"),l("xtream"),G())},[t,a]);const H=Ae=>{Q(Ae.id||Ae.name),h(Ae.name||""),Ae.kind==="m3u"?(l("m3u"),k([{key:`r-${Date.now()}`,name:Ae.name||"",url:Ae.m3u_url||"",content:Ae.m3u_content||"",fileName:Ae.m3u_content?"shared.m3u":""}])):Ae.kind==="stalker"?(l("stalker"),E(Ae.portal_url||""),U(Ae.mac_address||"")):(l("xtream"),p(Ae.server||""),g(Ae.username||""),v(Ae.password||""))},Y=(Ae,Ee)=>k(je=>je.map((Me,Pt)=>Pt===Ae?{...Me,...Ee}:Me)),ie=()=>k(Ae=>[...Ae,Mb()]),Ce=Ae=>k(Ee=>Ee.length>1?Ee.filter((je,Me)=>Me!==Ae):Ee),Le=async(Ae,Ee)=>{if(!Ee)return;const je=await Ee.text();Y(Ae,{content:je,fileName:Ee.name})},ke=Ae=>Y(Ae,{content:"",fileName:""}),Ne=async()=>{var je;const Ae=c==="shared"&&oe&&((je=M.find(Me=>(Me.id||Me.name)===oe))==null?void 0:je.kind)||o;if(Ae==="xtream"){if(!d||!f||!m||!b)return;R(!0);try{await n({kind:"xtream",name:d,serverUrl:f,username:m,password:b}),G()}finally{R(!1)}return}if(Ae==="stalker"){const Me=/^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$/.test(L.trim());if(!d||!S.trim()||!Me)return;R(!0);try{await n({kind:"stalker",name:d,serverUrl:"",username:"",password:"",portalUrl:S.trim(),macAddress:L.trim().toUpperCase()}),G()}finally{R(!1)}return}const Ee=O.map(Me=>({...Me,name:(Me.name||d||"").trim(),url:Me.url.trim(),content:Me.content})).filter(Me=>Me.url.length>0||Me.content.trim().length>0).map((Me,Pt,tn)=>({...Me,name:Me.name||(tn.length>1?`Playlist ${Pt+1}`:"M3U Playlist")}));if(Ee.length!==0){R(!0);try{for(const Me of Ee)await n({kind:"m3u",name:Me.name,serverUrl:"",username:"",password:"",m3uUrl:Me.url||void 0,m3uContent:Me.content||void 0});G()}finally{R(!1)}}},Ie=I||c==="shared"&&!a&&!(c==="shared"&&oe!==null&&!Z);return y.jsx(bh,{children:t&&y.jsxs($t.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-50 flex items-end sm:items-center justify-center",onClick:e,children:[y.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),y.jsxs($t.div,{initial:{scale:.95,y:20,opacity:0},animate:{scale:1,y:0,opacity:1},exit:{scale:.95,y:20,opacity:0},onClick:Ae=>Ae.stopPropagation(),className:"relative glass-card rounded-t-3xl sm:rounded-3xl p-5 sm:p-8 w-full sm:max-w-lg mx-0 sm:mx-4 max-h-[90vh] overflow-y-auto",children:[y.jsx("h2",{"data-testid":"add-server-title",className:"text-foreground text-xl sm:text-2xl font-display tracking-[0.2em] gold-text text-center mb-5",children:r("addServer.title")}),!a&&M.length>0&&y.jsxs("div",{className:"mb-4",children:[y.jsx("label",{className:"text-[11px] text-muted-foreground tracking-[0.25em] uppercase block mb-2",children:r("addServer.advanced")}),y.jsxs("div",{className:"flex glass rounded-xl p-1",children:[y.jsxs("button",{onClick:()=>u("shared"),"data-testid":"add-mode-shared",className:`flex-1 py-2 rounded-lg text-xs font-medium transition-all flex items-center justify-center gap-2 ${c==="shared"?"bg-primary/20 text-primary":"text-muted-foreground"}`,children:[y.jsx(LS,{className:"w-3.5 h-3.5"}),r("addServer.shared")]}),y.jsxs("button",{onClick:()=>{u("own"),Q(null),G()},"data-testid":"add-mode-own",className:`flex-1 py-2 rounded-lg text-xs font-medium transition-all flex items-center justify-center gap-2 ${c==="own"?"bg-primary/20 text-primary":"text-muted-foreground"}`,children:[y.jsx(Cc,{className:"w-3.5 h-3.5"}),r("addServer.ownServer")]})]})]}),!a&&c==="shared"?y.jsxs("div",{className:"space-y-2","data-testid":"shared-profile-picker",children:[Z&&y.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-2 py-2",children:[y.jsx(yr,{className:"w-3 h-3 animate-spin"})," Loading profiles…"]}),re&&y.jsx("div",{className:"text-destructive text-xs",children:re}),!Z&&M.length===0&&y.jsx("div",{className:"text-muted-foreground text-xs bg-muted/30 border border-border rounded-lg px-3 py-3",children:"No shared profiles have been configured yet."}),!Z&&M.map(Ae=>{const Ee=Ae.id||Ae.name,je=oe===Ee;return y.jsxs("button",{onClick:()=>H(Ae),"data-testid":`profile-pick-${Ee}`,className:`w-full flex items-center gap-3 px-3 py-2.5 rounded-xl border text-left transition-all ${je?"bg-primary/10 border-primary/50":"glass border-transparent hover:border-primary/30"}`,children:[Ae.kind==="m3u"?y.jsx(kS,{className:"w-4 h-4 text-primary shrink-0"}):Ae.kind==="stalker"?y.jsx(CS,{className:"w-4 h-4 text-primary shrink-0"}):y.jsx(Cc,{className:"w-4 h-4 text-primary shrink-0"}),y.jsxs("div",{className:"flex-1 min-w-0",children:[y.jsx("p",{className:`text-sm font-medium truncate ${je?"text-primary":"text-foreground"}`,children:Ae.name}),y.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-widest",children:Ae.kind==="m3u"?Ae.m3u_content?"M3U file (shared)":"M3U playlist":Ae.kind==="stalker"?"Stalker / MAC portal":"Xtream codes"})]}),je&&y.jsx(Ol,{className:"w-4 h-4 text-primary"})]},Ee)})]}):y.jsxs(y.Fragment,{children:[y.jsx("div",{className:"flex glass rounded-xl p-1 mb-4",children:["xtream","m3u","stalker"].map(Ae=>y.jsx("button",{onClick:()=>l(Ae),"data-testid":`add-kind-${Ae}`,className:`flex-1 py-2 rounded-lg text-xs font-medium transition-all ${o===Ae?"bg-primary/20 text-primary":"text-muted-foreground"}`,children:Ae==="xtream"?r("addServer.xtreamTab"):Ae==="m3u"?r("addServer.m3uTab"):"Stalker / MAC"},Ae))}),o==="xtream"?y.jsxs("div",{className:"space-y-3",children:[y.jsx(Ba,{icon:Rc,placeholder:r("addServer.profileNamePlaceholder"),value:d,onChange:h,testId:"add-name"}),y.jsx(Ba,{icon:Cc,placeholder:r("addServer.serverUrlPlaceholder"),value:f,onChange:p,testId:"add-server-url"}),y.jsx(Ba,{icon:fo,placeholder:r("addServer.usernamePlaceholder"),value:m,onChange:g,testId:"add-user"}),y.jsx(Ba,{icon:rv,placeholder:r("addServer.passwordPlaceholder"),value:b,onChange:v,type:"password",testId:"add-pass"})]}):o==="stalker"?y.jsxs("div",{className:"space-y-3","data-testid":"stalker-form",children:[y.jsx(Ba,{icon:Rc,placeholder:r("addServer.profileNamePlaceholder"),value:d,onChange:h,testId:"add-stalker-name"}),y.jsx(Ba,{icon:LS,placeholder:"Portal URL (e.g. http://portal.com:8080/c/)",value:S,onChange:E,testId:"add-stalker-portal"}),y.jsx(Ba,{icon:CS,placeholder:"MAC Address (00:1A:79:XX:XX:XX)",value:L,onChange:Ae=>U(lle(Ae)),testId:"add-stalker-mac"}),y.jsx(IA,{portalUrl:S,mac:L,testId:"add-stalker-test"}),y.jsxs("p",{className:"text-[11px] text-muted-foreground leading-relaxed px-1",children:["Stalker / MAG portal login. The app impersonates a MAG250 set-top box (User-Agent: ",y.jsx("code",{children:"QtStalker"}),", X-User-Agent: ",y.jsx("code",{children:"Model: MAG250"}),") and authenticates using your MAC address."]})]}):y.jsxs("div",{className:"space-y-3",children:[O.map((Ae,Ee)=>y.jsxs("div",{"data-testid":`m3u-row-${Ee}`,className:"glass rounded-xl p-3 border border-border/40 space-y-2",children:[y.jsxs("div",{className:"flex items-center justify-between",children:[y.jsxs("span",{className:"text-[10px] uppercase tracking-widest text-primary/80",children:["Playlist #",Ee+1]}),O.length>1&&y.jsx("button",{type:"button",onClick:()=>Ce(Ee),"data-testid":`m3u-row-remove-${Ee}`,className:"text-muted-foreground hover:text-destructive transition-colors","aria-label":"Remove row",children:y.jsx(nm,{className:"w-3.5 h-3.5"})})]}),y.jsx(Ba,{icon:Rc,placeholder:r("addServer.profileNamePlaceholder"),value:Ae.name,onChange:je=>Y(Ee,{name:je}),testId:`add-m3u-name-${Ee}`}),y.jsx(Ba,{icon:kS,placeholder:r("addServer.m3uPlaceholder"),value:Ae.url,onChange:je=>Y(Ee,{url:je}),testId:`add-m3u-url-${Ee}`}),y.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[y.jsxs("label",{"data-testid":`add-m3u-file-${Ee}`,className:"cursor-pointer flex items-center gap-2 px-3 py-2 rounded-lg glass text-xs text-primary hover:border-primary/40 transition-colors",children:[y.jsx(ET,{className:"w-3.5 h-3.5"}),y.jsx("span",{children:"Upload .m3u file"}),y.jsx("input",{type:"file",accept:".m3u,.m3u8,audio/x-mpegurl,application/vnd.apple.mpegurl,text/plain",onChange:je=>{var Me;return void Le(Ee,((Me=je.target.files)==null?void 0:Me[0])??null)},className:"hidden"})]}),Ae.content&&Ae.content.trim().length>0&&y.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0 text-xs text-muted-foreground",children:[y.jsx(bT,{className:"w-3.5 h-3.5 text-primary shrink-0"}),y.jsx("span",{className:"truncate",children:Ae.fileName||"uploaded.m3u"}),y.jsx("button",{type:"button",onClick:()=>ke(Ee),"data-testid":`add-m3u-file-clear-${Ee}`,className:"ml-1 text-muted-foreground hover:text-destructive",children:y.jsx(Sa,{className:"w-3.5 h-3.5"})})]})]})]},Ae.key)),y.jsxs("button",{type:"button",onClick:ie,"data-testid":"add-m3u-row-btn",className:"w-full flex items-center justify-center gap-2 py-2.5 rounded-xl border border-dashed border-primary/40 text-primary hover:bg-primary/10 transition-colors text-xs font-medium tracking-[0.2em] uppercase",children:[y.jsx(gl,{className:"w-4 h-4"})," Add Playlist"]})]})]}),y.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-6",children:[y.jsxs("button",{onClick:Ne,disabled:Ie,"data-testid":"add-submit",className:"flex-1 bg-primary/80 hover:bg-primary text-primary-foreground font-medium py-3 rounded-xl transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2",children:[I?y.jsx(yr,{className:"w-4 h-4 animate-spin"}):null,r("common.save")]}),y.jsx("button",{onClick:e,"data-testid":"add-cancel",className:"px-6 py-3 rounded-xl glass hover:border-primary/40 text-foreground text-sm",children:r("common.cancel")})]})]})]})})},Ba=({icon:t,placeholder:e,value:n,onChange:r,type:i="text",testId:s})=>y.jsxs("div",{className:"relative",children:[y.jsx(t,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),y.jsx("input",{type:i,value:n,onChange:a=>r(a.target.value),placeholder:e,"data-testid":s,className:"w-full glass-input rounded-xl pl-10 pr-4 py-3 text-sm text-foreground placeholder:text-muted-foreground outline-none focus:ring-1 focus:ring-primary/40"})]}),lle=t=>{var n;return((n=t.replace(/[^0-9A-Fa-f]/g,"").toUpperCase().slice(0,12).match(/.{1,2}/g))==null?void 0:n.join(":"))??""},cle=({username:t,whatsappNumber:e,onLogout:n})=>{const{t:r}=Wr(),i=(e||"").replace(/[^\d+]/g,""),s=i?`https://wa.me/${i.replace(/^\+/,"")}?text=${encodeURIComponent(r("expired.whatsappPrefill",{username:t}))}`:"#";return y.jsx($t.div,{"data-testid":"expired-overlay",initial:{opacity:0},animate:{opacity:1},className:"fixed inset-0 z-[200] flex items-center justify-center px-4",style:{background:"radial-gradient(ellipse at center, hsl(200, 40%, 10%) 0%, #000 80%)"},children:y.jsxs($t.div,{initial:{y:20,opacity:0},animate:{y:0,opacity:1},transition:{duration:.6,ease:"easeOut"},className:"glass-card rounded-3xl p-6 sm:p-10 w-full max-w-lg text-center",children:[y.jsx("div",{className:"w-16 h-16 sm:w-20 sm:h-20 mx-auto rounded-2xl glass flex items-center justify-center mb-5",style:{border:"1px solid hsla(0, 70%, 55%, 0.4)",boxShadow:"0 0 40px hsla(0, 70%, 55%, 0.25)"},children:y.jsx(TK,{className:"w-8 h-8 sm:w-10 sm:h-10 text-destructive",strokeWidth:1.4})}),y.jsx("h2",{className:"font-display text-xl sm:text-2xl md:text-3xl tracking-[0.2em] sm:tracking-[0.25em] gold-text mb-3",children:r("expired.title")}),y.jsxs("p",{className:"text-foreground/80 text-sm md:text-base mb-1",children:[r("expired.hi")," ",y.jsx("span",{className:"text-primary font-medium",children:t}),","]}),y.jsx("p",{className:"text-muted-foreground text-sm md:text-base mb-6 leading-relaxed",children:r("expired.message")}),y.jsxs("a",{href:s,target:"_blank",rel:"noopener noreferrer","data-testid":"expired-whatsapp-btn",className:"inline-flex items-center gap-2 px-5 sm:px-6 py-3 rounded-xl bg-[#25D366] hover:bg-[#1ebe57] text-white font-medium text-sm transition-colors",children:[y.jsx(R2,{className:"w-5 h-5"}),r("expired.contactWhatsapp")]}),e&&y.jsx("p",{className:"text-muted-foreground text-xs mt-4",children:e}),y.jsx("button",{onClick:n,"data-testid":"expired-logout-btn",className:"block mx-auto mt-6 text-muted-foreground hover:text-foreground text-xs tracking-[0.3em] uppercase transition-colors",children:r("expired.signOut")})]})})},ule=[{key:"liveTv",icon:xa,route:"/live-tv"},{key:"movies",icon:xT,route:"/movies"},{key:"series",icon:nv,route:"/series"}],dle=({title:t,count:e,icon:n,index:r,isSelected:i,onClick:s,onDoubleClick:a})=>y.jsx($t.div,{layout:!0,initial:{opacity:0,y:30},animate:{opacity:1,y:0,scale:i?1.1:.92,zIndex:i?10:1},transition:{type:"spring",stiffness:300,damping:25,delay:r*.1},whileHover:{scale:i?1.14:.95},whileTap:{scale:i?1.08:.88},onClick:s,onDoubleClick:a,className:"relative cursor-pointer select-none w-[46%] md:w-auto",style:{},children:y.jsxs("div",{className:`relative ${i?"w-full md:w-[260px] lg:w-[280px] aspect-[7/5] md:aspect-[8/5]":"w-full md:w-[200px] lg:w-[220px] aspect-[7/5] md:aspect-[8/5]"}`,children:[y.jsx("div",{className:"absolute inset-0 rounded-2xl overflow-hidden glass-card"}),y.jsx(bh,{children:i&&y.jsx($t.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"absolute -inset-1 rounded-2xl pointer-events-none",style:{boxShadow:"0 0 30px hsla(40, 80%, 55%, 0.25), inset 0 0 30px hsla(40, 80%, 55%, 0.05)",border:"1px solid hsla(40, 80%, 55%, 0.2)",borderRadius:"1rem"}})}),y.jsxs("div",{className:"relative z-10 h-full flex flex-col items-center justify-center gap-2 sm:gap-3 p-4 sm:p-5",children:[y.jsx(n,{className:`transition-all duration-500 ${i?"w-10 h-10 sm:w-14 sm:h-14 md:w-16 md:h-16 text-primary gold-glow animate-glow-pulse":"w-8 h-8 sm:w-10 sm:h-10 md:w-12 md:h-12 text-muted-foreground/40"}`,strokeWidth:1.2}),y.jsx("h3",{className:"text-foreground text-sm sm:text-base md:text-lg font-medium",children:t}),y.jsx("p",{className:"text-muted-foreground text-[10px] sm:text-xs",children:e})]})]})}),hle=()=>{const[t,e]=D.useState(0),[n,r]=D.useState(!1),i=qr(),{t:s}=Wr(),{activeProfile:a}=mo(),o=PA(),{user:l,isGuest:c,logout:u}=Bs(),d=!!l&&l.role==="user",[h,f]=D.useState(null);D.useEffect(()=>{if(!d)return;let E=!1;return cj().then(L=>{E||f(L)}).catch(()=>{}),()=>{E=!0}},[d,l==null?void 0:l.id]);const p=(h==null?void 0:h.user.days_remaining)??(l==null?void 0:l.days_remaining)??null,m=(h==null?void 0:h.user.is_expired)??(l==null?void 0:l.is_expired)??!1,g=(h==null?void 0:h.user.expiry_at)??(l==null?void 0:l.expiry_at)??null,b=(h==null?void 0:h.whatsapp_number)??"",[v]=D.useState(()=>new Date().toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!0})),S=()=>{u(),i("/welcome")};return y.jsxs("div",{className:"relative min-h-screen w-full overflow-hidden",children:[y.jsx("div",{className:"absolute inset-0 bg-cover bg-center bg-no-repeat",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),y.jsx("div",{className:"absolute inset-0 bg-background/40"}),y.jsxs("div",{className:"relative z-10 min-h-screen flex flex-col",children:[y.jsxs("header",{className:"flex items-center justify-between px-4 sm:px-6 md:px-8 pt-4 sm:pt-6 gap-2",children:[y.jsx("div",{className:"w-11 h-11 sm:w-14 sm:h-14 rounded-xl glass overflow-hidden flex items-center justify-center shrink-0",children:y.jsx(xa,{className:"w-5 h-5 text-muted-foreground"})}),y.jsx($t.h1,{initial:{opacity:0,y:-20},animate:{opacity:1,y:0},transition:{duration:.8},className:"font-display text-xl sm:text-2xl md:text-3xl lg:text-4xl tracking-[0.25em] sm:tracking-[0.3em] gold-text flex-1 text-center truncate",children:"NADIPLAYER"}),y.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 shrink-0",children:[y.jsx(fm,{align:"right"}),!d&&y.jsx("button",{"data-testid":"index-add-server-btn",onClick:()=>r(!0),className:"w-10 h-10 sm:w-11 sm:h-11 rounded-full glass flex items-center justify-center hover:border-primary/40 transition-colors",children:y.jsx(gl,{className:"w-5 h-5 text-muted-foreground"})}),!d&&y.jsx("button",{onClick:()=>i("/account"),className:"hidden sm:flex w-10 h-10 sm:w-11 sm:h-11 rounded-full glass items-center justify-center hover:border-primary/40 transition-colors",children:y.jsx(C2,{className:"w-5 h-5 text-muted-foreground"})}),d?y.jsxs("button",{"data-testid":"index-logout-btn",onClick:S,className:"flex items-center gap-2 px-3 sm:px-4 h-10 sm:h-11 rounded-full glass text-muted-foreground hover:text-foreground hover:border-primary/40 transition-colors text-[10px] sm:text-xs tracking-[0.2em] uppercase",children:[y.jsx(A2,{className:"w-4 h-4"}),y.jsx("span",{className:"hidden sm:inline",children:s("home.logout")})]}):y.jsx("button",{onClick:()=>i("/welcome"),className:"w-10 h-10 sm:w-11 sm:h-11 rounded-full border-2 border-primary/50 overflow-hidden glass flex items-center justify-center",title:"Back to welcome",children:y.jsx(fo,{className:"w-5 h-5 text-muted-foreground"})})]})]}),d?y.jsxs("div",{"data-testid":"subscription-strip",className:"mx-4 sm:mx-6 md:mx-8 mt-4 glass-card rounded-xl px-4 sm:px-5 py-3 flex flex-wrap items-center justify-between gap-3",children:[y.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[y.jsx(ap,{className:"w-5 h-5 text-primary gold-glow shrink-0"}),y.jsxs("div",{className:"min-w-0",children:[y.jsxs("p",{className:"text-foreground text-sm font-medium truncate",children:[l==null?void 0:l.username,y.jsxs("span",{className:"ms-2 text-muted-foreground text-xs",children:["· ",s("home.subscriber")]})]}),y.jsx("p",{className:"text-[10px] sm:text-[11px] tracking-[0.12em] sm:tracking-[0.15em] uppercase text-muted-foreground",children:g?y.jsxs(y.Fragment,{children:[s("home.expires")," ",y.jsx("span",{className:"text-foreground",children:new Date(g).toLocaleDateString()})]}):s("home.noExpiry")})]})]}),y.jsx("div",{className:"flex items-center gap-3",children:y.jsx("span",{className:`px-3 py-1.5 rounded-full text-[11px] sm:text-xs font-medium tracking-wider ${m?"bg-destructive/20 text-destructive border border-destructive/40":p!=null&&p<=3?"bg-amber-500/20 text-amber-400 border border-amber-500/40":"bg-primary/15 text-primary border border-primary/40"}`,children:m?s("home.expired"):p!=null?s("home.daysRemaining",{count:p}):""})})]}):a&&y.jsx("div",{className:"text-center mt-2",children:y.jsxs("span",{className:"text-muted-foreground text-xs",children:[s("home.profile"),":"," ",y.jsx("span",{className:"text-primary",children:a.name})]})}),c&&!l&&y.jsx("div",{className:"text-center mt-2",children:y.jsx("span",{className:"text-muted-foreground text-[10px] sm:text-[11px] tracking-[0.3em] uppercase",children:s("home.guestMode")})}),y.jsx("main",{className:"flex-1 flex items-center justify-center px-2 sm:px-4 py-4 sm:py-0",children:y.jsx("div",{className:"flex flex-wrap items-center justify-center gap-3 sm:gap-4 md:gap-6 w-full max-w-4xl",children:ule.map((E,L)=>y.jsx(dle,{title:s(`home.categories.${E.key}`),count:s(`home.categories.${E.key}Count`),icon:E.icon,index:L,isSelected:t===L,onClick:()=>{e(L),i(E.route)}},E.key))})}),y.jsxs("div",{className:"text-center text-muted-foreground text-[10px] sm:text-xs px-4 pb-2",children:[s("home.infoBar")," ",d?h!=null&&h.xtream.server?s("home.connected"):s("home.awaiting"):s(a?"home.connected":"home.waiting")]}),y.jsxs("footer",{className:"flex items-center justify-between px-4 sm:px-6 md:px-8 pb-4 sm:pb-6 gap-2",children:[y.jsxs($t.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:.6},className:"flex items-center gap-2 sm:gap-3",children:[y.jsx("div",{className:"w-9 h-9 sm:w-10 sm:h-10 rounded-full glass flex items-center justify-center",children:y.jsx(T2,{className:"w-4 h-4 sm:w-5 sm:h-5 text-muted-foreground"})}),y.jsx("span",{className:"text-foreground text-xs sm:text-sm font-medium",children:s("home.timeshift")})]}),y.jsxs($t.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.7},className:"flex items-center gap-3 sm:gap-4 md:gap-6",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx(RS,{className:"w-4 h-4 sm:w-5 sm:h-5 text-primary"}),y.jsx("span",{className:"text-foreground text-sm sm:text-base md:text-lg font-light",children:v})]}),y.jsx("div",{className:"hidden sm:block h-6 w-px bg-border"}),y.jsxs("div",{className:"hidden sm:flex items-center gap-2",children:[y.jsx("span",{className:"text-foreground text-sm",children:"Los Angeles"}),y.jsx(RS,{className:"w-4 h-4 text-muted-foreground"}),y.jsx("span",{className:"text-foreground text-sm",children:"24°"})]})]})]})]}),!d&&y.jsx(e3,{open:n,onClose:()=>r(!1),onSubmit:async E=>{await o(E)&&r(!1)}}),d&&m&&y.jsx(cle,{username:(l==null?void 0:l.username)||"subscriber",whatsappNumber:b,onLogout:S})]})},Vc=({title:t,children:e})=>{const n=qr(),{t:r}=Wr(),[i]=D.useState(()=>new Date().toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!0}));return y.jsxs("div",{className:"relative min-h-screen w-full overflow-hidden",children:[y.jsx("div",{className:"absolute inset-0 bg-cover bg-center bg-no-repeat",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),y.jsx("div",{className:"absolute inset-0 bg-background/40"}),y.jsxs("div",{className:"relative z-10 min-h-screen flex flex-col",children:[y.jsxs("header",{className:"flex items-center justify-between px-4 sm:px-6 pt-4 gap-2",children:[y.jsx("button",{onClick:()=>n("/"),className:"w-10 h-10 rounded-full glass flex items-center justify-center hover:border-primary/40 transition-colors shrink-0",children:y.jsx(ev,{className:"w-5 h-5 text-muted-foreground rtl:rotate-180"})}),y.jsx($t.h1,{initial:{opacity:0},animate:{opacity:1},className:"font-display text-base sm:text-xl tracking-[0.2em] gold-text truncate",children:t}),y.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[y.jsx(fm,{align:"right"}),y.jsx("button",{onClick:()=>n("/account"),className:"hidden sm:flex w-9 h-9 rounded-full glass items-center justify-center hover:border-primary/40",children:y.jsx(C2,{className:"w-4 h-4 text-muted-foreground"})}),y.jsx("button",{onClick:()=>n("/account"),className:"w-9 h-9 rounded-full border-2 border-primary/50 glass flex items-center justify-center",children:y.jsx(fo,{className:"w-4 h-4 text-muted-foreground"})})]})]}),y.jsx("main",{className:"flex-1 overflow-hidden px-3 sm:px-4 py-3",children:e}),y.jsxs("footer",{className:"flex items-center justify-between px-4 sm:px-6 pb-4 gap-2",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx(T2,{className:"w-4 h-4 text-muted-foreground"}),y.jsx("span",{className:"text-foreground text-xs",children:r("common.timeshift")})]}),y.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 text-sm",children:[y.jsx(RS,{className:"w-4 h-4 text-primary"}),y.jsx("span",{className:"text-foreground font-light",children:i}),y.jsx("div",{className:"hidden sm:block h-4 w-px bg-border"}),y.jsx("span",{className:"hidden sm:inline text-foreground text-xs",children:r("pageLayout.weatherCity")})]})]})]})]})},Ze=Number.isFinite||function(t){return typeof t=="number"&&isFinite(t)},fle=Number.isSafeInteger||function(t){return typeof t=="number"&&Math.abs(t)<=ple},ple=Number.MAX_SAFE_INTEGER||9007199254740991;let ct=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),xe=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",t.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",t.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.ASSET_LIST_LOAD_ERROR="assetListLoadError",t.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",t.ASSET_LIST_PARSING_ERROR="assetListParsingError",t.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.ATTACH_MEDIA_ERROR="attachMediaError",t.UNKNOWN="unknown",t}({}),j=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.MEDIA_ENDED="hlsMediaEnded",t.STALL_RESOLVED="hlsStallResolved",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFERED_TO_END="hlsBufferedToEnd",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t.ASSET_LIST_LOADING="hlsAssetListLoading",t.ASSET_LIST_LOADED="hlsAssetListLoaded",t.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",t.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",t.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",t.INTERSTITIAL_STARTED="hlsInterstitialStarted",t.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",t.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",t.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",t.INTERSTITIAL_ENDED="hlsInterstitialEnded",t.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",t.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",t.EVENT_CUE_ENTER="hlsEventCueEnter",t}({});var Ft={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},tt={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class xu{constructor(e,n=0,r=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=n,this.totalWeight_=r}sample(e,n){const r=Math.pow(this.alpha_,e);this.estimate_=n*(1-r)+r*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class mle{constructor(e,n,r,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new xu(e),this.fast_=new xu(n),this.defaultTTFB_=i,this.ttfb_=new xu(e)}update(e,n){const{slow_:r,fast_:i,ttfb_:s}=this;r.halfLife!==e&&(this.slow_=new xu(e,r.getEstimate(),r.getTotalWeight())),i.halfLife!==n&&(this.fast_=new xu(n,i.getEstimate(),i.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new xu(e,s.getEstimate(),s.getTotalWeight()))}sample(e,n){e=Math.max(e,this.minDelayMs_);const r=8*n,i=e/1e3,s=r/i;this.fast_.sample(i,s),this.slow_.sample(i,s)}sampleTTFB(e){const n=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(n,2)/2);this.ttfb_.sample(r,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function gle(t,e,n){return(e=vle(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function fn(){return fn=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},fn.apply(null,arguments)}function ZI(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function on(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?ZI(Object(n),!0).forEach(function(r){gle(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):ZI(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function yle(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function vle(t){var e=yle(t,"string");return typeof e=="symbol"?e:e+""}class vs{constructor(e,n){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const r=`[${e}]:`;this.trace=Bo,this.debug=n.debug.bind(null,r),this.log=n.log.bind(null,r),this.warn=n.warn.bind(null,r),this.info=n.info.bind(null,r),this.error=n.error.bind(null,r)}}const Bo=function(){},_le={trace:Bo,debug:Bo,log:Bo,warn:Bo,info:Bo,error:Bo};function ME(){return fn({},_le)}function ble(t,e){const n=self.console[t];return n?n.bind(self.console,`${e?"["+e+"] ":""}[${t}] >`):Bo}function eP(t,e,n){return e[t]?e[t].bind(e):ble(t,n)}const BE=ME();function xle(t,e,n){const r=ME();if(typeof console=="object"&&t===!0||typeof t=="object"){const i=["debug","log","info","warn","error"];i.forEach(s=>{r[s]=eP(s,t,n)});try{r.log(`Debug logs enabled for "${e}" in hls.js version 1.6.16`)}catch{return ME()}i.forEach(s=>{BE[s]=eP(s,t)})}else fn(BE,r);return r}const ln=BE;function Cl(t=!0){return typeof self>"u"?void 0:(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Sle(t){return typeof self<"u"&&t===self.ManagedMediaSource}function t3(t,e){const n=Object.keys(t),r=Object.keys(e),i=n.length,s=r.length;return!i||!s||i===s&&!n.some(a=>r.indexOf(a)===-1)}function Ki(t,e=!1){if(typeof TextDecoder<"u"){const c=new TextDecoder("utf-8").decode(t);if(e){const u=c.indexOf("\0");return u!==-1?c.substring(0,u):c}return c.replace(/\0/g,"")}const n=t.length;let r,i,s,a="",o=0;for(;o<n;){if(r=t[o++],r===0&&e)return a;if(r===0||r===3)continue;switch(r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(r);break;case 12:case 13:i=t[o++],a+=String.fromCharCode((r&31)<<6|i&63);break;case 14:i=t[o++],s=t[o++],a+=String.fromCharCode((r&15)<<12|(i&63)<<6|(s&63)<<0);break}}return a}function Dr(t){let e="";for(let n=0;n<t.length;n++){let r=t[n].toString(16);r.length<2&&(r="0"+r),e+=r}return e}function n3(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Ele(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Bb={exports:{}},tP;function wle(){return tP||(tP=1,function(t,e){(function(n){var r=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,c,u){if(u=u||{},l=l.trim(),c=c.trim(),!c){if(!u.alwaysNormalize)return l;var d=o.parseURL(l);if(!d)throw new Error("Error trying to parse base URL.");return d.path=o.normalizePath(d.path),o.buildURLFromParts(d)}var h=o.parseURL(c);if(!h)throw new Error("Error trying to parse relative URL.");if(h.scheme)return u.alwaysNormalize?(h.path=o.normalizePath(h.path),o.buildURLFromParts(h)):c;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var p=i.exec(f.path);f.netLoc=p[1],f.path=p[2]}f.netLoc&&!f.path&&(f.path="/");var m={scheme:f.scheme,netLoc:h.netLoc,path:null,params:h.params,query:h.query,fragment:h.fragment};if(!h.netLoc&&(m.netLoc=f.netLoc,h.path[0]!=="/"))if(!h.path)m.path=f.path,h.params||(m.params=f.params,h.query||(m.query=f.query));else{var g=f.path,b=g.substring(0,g.lastIndexOf("/")+1)+h.path;m.path=o.normalizePath(b)}return m.path===null&&(m.path=u.alwaysNormalize?o.normalizePath(h.path):h.path),o.buildURLFromParts(m)},parseURL:function(l){var c=r.exec(l);return c?{scheme:c[1]||"",netLoc:c[2]||"",path:c[3]||"",params:c[4]||"",query:c[5]||"",fragment:c[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(s,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};t.exports=o})()}(Bb)),Bb.exports}var DA=wle();class OA{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var pn={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class r3{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,Ale(this,"stats")}setByteRange(e,n){const r=e.split("@",2);let i;r.length===1?i=(n==null?void 0:n.byteRangeEndOffset)||0:i=parseInt(r[1]),this._byteRange=[i,parseInt(r[0])+i]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[pn.AUDIO]:null,[pn.VIDEO]:null,[pn.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new OA),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=DA.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[pn.AUDIO]=null,e[pn.VIDEO]=null,e[pn.AUDIOVIDEO]=null}}function Zn(t){return t.sn!=="initSegment"}class Ub extends r3{constructor(e,n){super(n),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],n=this.byteRange[1];if(Ze(e)&&Ze(n))return n-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:n}=this;if(!n||n.NONE)return null;if(n.identity)this._decryptdata||(this._decryptdata=n.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const r=Object.keys(n);if(r.length===1){const i=this._decryptdata=n[r[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,n))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=Ze(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var n;const r=Object.keys(this.levelkeys),i=r.length;if(i>1||i===1&&(n=this.levelkeys[r[0]])!=null&&n.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!Ze(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Zn(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const n=this.levelkeys;if(n){var r;const i=n[e];i&&!((r=this._decryptdata)!=null&&r.keyId)&&(this._decryptdata=i.getDecryptData(this.sn,n))}}abortRequests(){var e,n;(e=this.loader)==null||e.abort(),(n=this.keyLoader)==null||n.abort()}setElementaryStreamInfo(e,n,r,i,s,a=!1){const{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:n,endPTS:r,startDTS:i,endDTS:s,partial:a};return}l.startPTS=Math.min(l.startPTS,n),l.endPTS=Math.max(l.endPTS,r),l.startDTS=Math.min(l.startDTS,i),l.endDTS=Math.max(l.endDTS,s)}}class Tle extends r3{constructor(e,n,r,i,s){super(r),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=n,this.index=i;const a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function i3(t,e){const n=Object.getPrototypeOf(t);if(n){const r=Object.getOwnPropertyDescriptor(n,e);return r||i3(n,e)}}function Ale(t,e){const n=i3(t,e);n&&(n.enumerable=!0,Object.defineProperty(t,e,n))}const nP=Math.pow(2,32)-1,Rle=[].push,s3={video:1,audio:2,id3:3,text:4};function hr(t){return String.fromCharCode.apply(null,t)}function a3(t,e){const n=t[e]<<8|t[e+1];return n<0?65536+n:n}function wt(t,e){const n=o3(t,e);return n<0?4294967296+n:n}function rP(t,e){let n=wt(t,e);return n*=Math.pow(2,32),n+=wt(t,e+4),n}function o3(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function Cle(t){const e=t.byteLength;for(let n=0;n<e;){const r=wt(t,n);if(r>8&&t[n+4]===109&&t[n+5]===111&&t[n+6]===111&&t[n+7]===102)return!0;n=r>1?n+r:e}return!1}function Bt(t,e){const n=[];if(!e.length)return n;const r=t.byteLength;for(let i=0;i<r;){const s=wt(t,i),a=hr(t.subarray(i+4,i+8)),o=s>1?i+s:r;if(a===e[0])if(e.length===1)n.push(t.subarray(i+8,o));else{const l=Bt(t.subarray(i+8,o),e.slice(1));l.length&&Rle.apply(n,l)}i=o}return n}function Lle(t){const e=[],n=t[0];let r=8;const i=wt(t,r);r+=4;let s=0,a=0;n===0?(s=wt(t,r),a=wt(t,r+4),r+=8):(s=rP(t,r),a=rP(t,r+8),r+=16),r+=2;let o=t.length+a;const l=a3(t,r);r+=2;for(let c=0;c<l;c++){let u=r;const d=wt(t,u);u+=4;const h=d&2147483647;if((d&2147483648)>>>31===1)return ln.warn("SIDX has hierarchical references (not supported)"),null;const p=wt(t,u);u+=4,e.push({referenceSize:h,subsegmentDuration:p,info:{duration:p/i,start:o,end:o+h-1}}),o+=h,u+=4,r=u}return{earliestPresentationTime:s,timescale:i,version:n,referencesCount:l,references:e}}function l3(t){const e=[],n=Bt(t,["moov","trak"]);for(let i=0;i<n.length;i++){const s=n[i],a=Bt(s,["tkhd"])[0];if(a){let o=a[0];const l=wt(a,o===0?12:20),c=Bt(s,["mdia","mdhd"])[0];if(c){o=c[0];const u=wt(c,o===0?12:20),d=Bt(s,["mdia","hdlr"])[0];if(d){const h=hr(d.subarray(8,12)),f={soun:pn.AUDIO,vide:pn.VIDEO}[h],p=Bt(s,["mdia","minf","stbl","stsd"])[0],m=kle(p);f?(e[l]={timescale:u,type:f,stsd:m},e[f]=on({timescale:u,id:l},m)):e[l]={timescale:u,type:h,stsd:m}}}}}return Bt(t,["moov","mvex","trex"]).forEach(i=>{const s=wt(i,4),a=e[s];a&&(a.default={duration:wt(i,12),flags:wt(i,20)})}),e}function kle(t){const e=t.subarray(8),n=e.subarray(86),r=hr(e.subarray(4,8));let i=r,s;const a=r==="enca"||r==="encv";if(a){const c=Bt(e,[r])[0].subarray(r==="enca"?28:78);Bt(c,["sinf"]).forEach(d=>{const h=Bt(d,["schm"])[0];if(h){const f=hr(h.subarray(4,8));if(f==="cbcs"||f==="cenc"){const p=Bt(d,["frma"])[0];p&&(i=hr(p))}}})}const o=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const l=Bt(n,["avcC"])[0];l&&l.length>3&&(i+="."+_g(l[1])+_g(l[2])+_g(l[3]),s=vg(o==="avc1"?"dva1":"dvav",n));break}case"mp4a":{const l=Bt(e,[r])[0],c=Bt(l.subarray(28),["esds"])[0];if(c&&c.length>7){let u=4;if(c[u++]!==3)break;u=jb(c,u),u+=2;const d=c[u++];if(d&128&&(u+=2),d&64&&(u+=c[u++]),c[u++]!==4)break;u=jb(c,u);const h=c[u++];if(h===64)i+="."+_g(h);else break;if(u+=12,c[u++]!==5)break;u=jb(c,u);const f=c[u++];let p=(f&248)>>3;p===31&&(p+=1+((f&7)<<3)+((c[u]&224)>>5)),i+="."+p}break}case"hvc1":case"hev1":{const l=Bt(n,["hvcC"])[0];if(l&&l.length>12){const c=l[1],u=["","A","B","C"][c>>6],d=c&31,h=wt(l,2),f=(c&32)>>5?"H":"L",p=l[12],m=l.subarray(6,12);i+="."+u+d,i+="."+Ile(h).toString(16).toUpperCase(),i+="."+f+p;let g="";for(let b=m.length;b--;){const v=m[b];(v||g)&&(g="."+v.toString(16).toUpperCase()+g)}i+=g}s=vg(o=="hev1"?"dvhe":"dvh1",n);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=vg(i,n)||i;break}case"vp09":{const l=Bt(n,["vpcC"])[0];if(l&&l.length>6){const c=l[4],u=l[5],d=l[6]>>4&15;i+="."+zs(c)+"."+zs(u)+"."+zs(d)}break}case"av01":{const l=Bt(n,["av1C"])[0];if(l&&l.length>2){const c=l[1]>>>5,u=l[1]&31,d=l[2]>>>7?"H":"M",h=(l[2]&64)>>6,f=(l[2]&32)>>5,p=c===2&&h?f?12:10:h?10:8,m=(l[2]&16)>>4,g=(l[2]&8)>>3,b=(l[2]&4)>>2,v=l[2]&3;i+="."+c+"."+zs(u)+d+"."+zs(p)+"."+m+"."+g+b+v+"."+zs(1)+"."+zs(1)+"."+zs(1)+"."+0,s=vg("dav1",n)}break}}return{codec:i,encrypted:a,supplemental:s}}function vg(t,e){const n=Bt(e,["dvvC"]),r=n.length?n[0]:Bt(e,["dvcC"])[0];if(r){const i=r[2]>>1&127,s=r[2]<<5&32|r[3]>>3&31;return t+"."+zs(i)+"."+zs(s)}}function Ile(t){let e=0;for(let n=0;n<32;n++)e|=(t>>n&1)<<31-n;return e>>>0}function jb(t,e){const n=e+5;for(;t[e++]&128&&e<n;);return e}function _g(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function zs(t){return(t<10?"0":"")+t}function Ple(t,e){if(!t||!e)return;const n=e.keyId;n&&e.isCommonEncryption&&c3(t,(r,i)=>{const s=r.subarray(8,24);s.some(a=>a!==0)||(ln.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${Dr(s)} -> ${Dr(n)}`),r.set(n,8))})}function Dle(t){const e=[];return c3(t,n=>e.push(n.subarray(8,24))),e}function c3(t,e){Bt(t,["moov","trak"]).forEach(r=>{const i=Bt(r,["mdia","minf","stbl","stsd"])[0];if(!i)return;const s=i.subarray(8);let a=Bt(s,["enca"]);const o=a.length>0;o||(a=Bt(s,["encv"])),a.forEach(l=>{const c=o?l.subarray(28):l.subarray(78);Bt(c,["sinf"]).forEach(d=>{const h=u3(d);h&&e(h,o)})})})}function u3(t){const e=Bt(t,["schm"])[0];if(e){const n=hr(e.subarray(4,8));if(n==="cbcs"||n==="cenc"){const r=Bt(t,["schi","tenc"])[0];if(r)return r}}}function Ole(t,e,n){const r={},i=Bt(t,["moof","traf"]);for(let s=0;s<i.length;s++){const a=i[s],o=Bt(a,["tfhd"])[0],l=wt(o,4),c=e[l];if(!c)continue;r[l]||(r[l]={start:NaN,duration:0,sampleCount:0,timescale:c.timescale,type:c.type});const u=r[l],d=Bt(a,["tfdt"])[0];if(d){const S=d[0];let E=wt(d,4);S===1&&(E===nP?n.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(E*=nP+1,E+=wt(d,8))),Ze(E)&&(!Ze(u.start)||E<u.start)&&(u.start=E)}const h=c.default,f=wt(o,0)|(h==null?void 0:h.flags);let p=(h==null?void 0:h.duration)||0;f&8&&(f&2?p=wt(o,12):p=wt(o,8));const m=Bt(a,["trun"]);let g=u.start||0,b=0,v=p;for(let S=0;S<m.length;S++){const E=m[S],L=wt(E,4),U=u.sampleCount;u.sampleCount+=L;const O=E[3]&1,k=E[3]&4,I=E[2]&1,R=E[2]&2,M=E[2]&4,z=E[2]&8;let Z=8,W=L;for(O&&(Z+=4),k&&L&&(!(E[Z+1]&1)&&u.keyFrameIndex===void 0&&(u.keyFrameIndex=U),Z+=4,I?(v=wt(E,Z),Z+=4):v=p,R&&(Z+=4),z&&(Z+=4),g+=v,b+=v,W--);W--;)I?(v=wt(E,Z),Z+=4):v=p,R&&(Z+=4),M&&(E[Z+1]&1||u.keyFrameIndex===void 0&&(u.keyFrameIndex=u.sampleCount-(W+1),u.keyFrameStart=g),Z+=4),z&&(Z+=4),g+=v,b+=v;!b&&p&&(b+=p*L)}u.duration+=b}if(!Object.keys(r).some(s=>r[s].duration)){let s=1/0,a=0;const o=Bt(t,["sidx"]);for(let l=0;l<o.length;l++){const c=Lle(o[l]);if(c!=null&&c.references){s=Math.min(s,c.earliestPresentationTime/c.timescale);const u=c.references.reduce((d,h)=>d+h.info.duration||0,0);a=Math.max(a,u+c.earliestPresentationTime/c.timescale)}}a&&Ze(a)&&Object.keys(r).forEach(l=>{r[l].duration||(r[l].duration=a*r[l].timescale-r[l].start)})}return r}function Nle(t){const e={valid:null,remainder:null},n=Bt(t,["moof"]);if(n.length<2)return e.remainder=t,e;const r=n[n.length-1];return e.valid=t.slice(0,r.byteOffset-8),e.remainder=t.slice(r.byteOffset-8),e}function ys(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}function iP(t,e){const n=[],r=e.samples,i=e.timescale,s=e.id;let a=!1;return Bt(r,["moof"]).map(l=>{const c=l.byteOffset-8;Bt(l,["traf"]).map(d=>{const h=Bt(d,["tfdt"]).map(f=>{const p=f[0];let m=wt(f,4);return p===1&&(m*=Math.pow(2,32),m+=wt(f,8)),m/i})[0];return h!==void 0&&(t=h),Bt(d,["tfhd"]).map(f=>{const p=wt(f,4),m=wt(f,0)&16777215,g=(m&1)!==0,b=(m&2)!==0,v=(m&8)!==0;let S=0;const E=(m&16)!==0;let L=0;const U=(m&32)!==0;let O=8;p===s&&(g&&(O+=8),b&&(O+=4),v&&(S=wt(f,O),O+=4),E&&(L=wt(f,O),O+=4),U&&(O+=4),e.type==="video"&&(a=Iv(e.codec)),Bt(d,["trun"]).map(k=>{const I=k[0],R=wt(k,0)&16777215,M=(R&1)!==0;let z=0;const Z=(R&4)!==0,W=(R&256)!==0;let re=0;const X=(R&512)!==0;let oe=0;const Q=(R&1024)!==0,G=(R&2048)!==0;let H=0;const Y=wt(k,4);let ie=8;M&&(z=wt(k,ie),ie+=4),Z&&(ie+=4);let Ce=z+c;for(let Le=0;Le<Y;Le++){if(W?(re=wt(k,ie),ie+=4):re=S,X?(oe=wt(k,ie),ie+=4):oe=L,Q&&(ie+=4),G&&(I===0?H=wt(k,ie):H=o3(k,ie),ie+=4),e.type===pn.VIDEO){let ke=0;for(;ke<oe;){const Ne=wt(r,Ce);if(Ce+=4,Mle(a,r[Ce])){const ye=r.subarray(Ce,Ce+Ne);NA(ye,a?2:1,t+H/i,n)}Ce+=Ne,ke+=Ne+4}}t+=re/i}}))})})}),n}function Iv(t){if(!t)return!1;const e=t.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function Mle(t,e){if(t){const n=e>>1&63;return n===39||n===40}else return(e&31)===6}function NA(t,e,n,r){const i=d3(t);let s=0;s+=e;let a=0,o=0,l=0;for(;s<i.length;){a=0;do{if(s>=i.length)break;l=i[s++],a+=l}while(l===255);o=0;do{if(s>=i.length)break;l=i[s++],o+=l}while(l===255);const c=i.length-s;let u=s;if(o<c)s+=o;else if(o>c){ln.error(`Malformed SEI payload. ${o} is too small, only ${c} bytes left to parse.`);break}if(a===4){if(i[u++]===181){const h=a3(i,u);if(u+=2,h===49){const f=wt(i,u);if(u+=4,f===1195456820){const p=i[u++];if(p===3){const m=i[u++],g=31&m,b=64&m,v=b?2+g*3:0,S=new Uint8Array(v);if(b){S[0]=m;for(let E=1;E<v;E++)S[E]=i[u++]}r.push({type:p,payloadType:a,pts:n,bytes:S})}}}}}else if(a===5&&o>16){const d=[];for(let p=0;p<16;p++){const m=i[u++].toString(16);d.push(m.length==1?"0"+m:m),(p===3||p===5||p===7||p===9)&&d.push("-")}const h=o-16,f=new Uint8Array(h);for(let p=0;p<h;p++)f[p]=i[u++];r.push({payloadType:a,pts:n,uuid:d.join(""),userData:Ki(f),userDataBytes:f})}}}function d3(t){const e=t.byteLength,n=[];let r=1;for(;r<e-2;)t[r]===0&&t[r+1]===0&&t[r+2]===3?(n.push(r+2),r+=2):r++;if(n.length===0)return t;const i=e-n.length,s=new Uint8Array(i);let a=0;for(r=0;r<i;a++,r++)a===n[0]&&(a++,n.shift()),s[r]=t[a];return s}function Ble(t){const e=t[0];let n="",r="",i=0,s=0,a=0,o=0,l=0,c=0;if(e===0){for(;hr(t.subarray(c,c+1))!=="\0";)n+=hr(t.subarray(c,c+1)),c+=1;for(n+=hr(t.subarray(c,c+1)),c+=1;hr(t.subarray(c,c+1))!=="\0";)r+=hr(t.subarray(c,c+1)),c+=1;r+=hr(t.subarray(c,c+1)),c+=1,i=wt(t,12),s=wt(t,16),o=wt(t,20),l=wt(t,24),c=28}else if(e===1){c+=4,i=wt(t,c),c+=4;const d=wt(t,c);c+=4;const h=wt(t,c);for(c+=4,a=2**32*d+h,fle(a)||(a=Number.MAX_SAFE_INTEGER,ln.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=wt(t,c),c+=4,l=wt(t,c),c+=4;hr(t.subarray(c,c+1))!=="\0";)n+=hr(t.subarray(c,c+1)),c+=1;for(n+=hr(t.subarray(c,c+1)),c+=1;hr(t.subarray(c,c+1))!=="\0";)r+=hr(t.subarray(c,c+1)),c+=1;r+=hr(t.subarray(c,c+1)),c+=1}const u=t.subarray(c,t.byteLength);return{schemeIdUri:n,value:r,timeScale:i,presentationTime:a,presentationTimeDelta:s,eventDuration:o,id:l,payload:u}}function Ule(t,...e){const n=e.length;let r=8,i=n;for(;i--;)r+=e[i].byteLength;const s=new Uint8Array(r);for(s[0]=r>>24&255,s[1]=r>>16&255,s[2]=r>>8&255,s[3]=r&255,s.set(t,4),i=0,r=8;i<n;i++)s.set(e[i],r),r+=e[i].byteLength;return s}function jle(t,e,n){if(t.byteLength!==16)throw new RangeError("Invalid system id");let r,i;r=0,i=new Uint8Array;let s;r>0?(s=new Uint8Array(4),e.length>0&&new DataView(s.buffer).setUint32(0,e.length,!1)):s=new Uint8Array;const a=new Uint8Array(4);return n.byteLength>0&&new DataView(a.buffer).setUint32(0,n.byteLength,!1),Ule([112,115,115,104],new Uint8Array([r,0,0,0]),t,s,i,a,n)}function Fle(t){const e=[];if(t instanceof ArrayBuffer){const n=t.byteLength;let r=0;for(;r+32<n;){const i=new DataView(t,r),s=$le(i);e.push(s),r+=s.size}}return e}function $le(t){const e=t.getUint32(0),n=t.byteOffset,r=t.byteLength;if(r<e)return{offset:n,size:r};if(t.getUint32(4)!==1886614376)return{offset:n,size:e};const s=t.getUint32(8)>>>24;if(s!==0&&s!==1)return{offset:n,size:e};const a=t.buffer,o=Dr(new Uint8Array(a,n+12,16));let l=null,c=null,u=0;if(s===0)u=28;else{const h=t.getUint32(28);if(!h||r<32+h*16)return{offset:n,size:e};l=[];for(let f=0;f<h;f++)l.push(new Uint8Array(a,n+32+f*16,16));u=32+h*16}if(!u)return{offset:n,size:e};const d=t.getUint32(u);return e-32<d?{offset:n,size:e}:(c=new Uint8Array(a,n+u+4,d),{version:s,systemId:o,kids:l,data:c,offset:n,size:e})}const h3=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),th={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function MA(t,e){const n=th[e];return!!n&&!!n[t.slice(0,4)]}function Ep(t,e,n=!0){return!t.split(",").some(r=>!BA(r,e,n))}function BA(t,e,n=!0){var r;const i=Cl(n);return(r=i==null?void 0:i.isTypeSupported(wp(t,e)))!=null?r:!1}function wp(t,e){return`${e}/mp4;codecs=${t}`}function sP(t){if(t){const e=t.substring(0,4);return th.video[e]}return 2}function v0(t){const e=h3();return t.split(",").reduce((n,r)=>{const s=e&&Iv(r)?9:th.video[r];return s?(s*2+n)/(n?3:2):(th.audio[r]+n)/(n?2:1)},0)}const Fb={};function Vle(t,e=!0){if(Fb[t])return Fb[t];const n={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let i=0;i<n.length;i++){var r;if(BA(n[i],"audio",e))return Fb[t]=n[i],n[i];if(n[i]==="mp3"&&(r=Cl(e))!=null&&r.isTypeSupported("audio/mpeg"))return""}return t}const Gle=/flac|opus|mp4a\.40\.34/i;function _0(t,e=!0){return t.replace(Gle,n=>Vle(n.toLowerCase(),e))}function Hle(t,e){const n=[];if(t){const r=t.split(",");for(let i=0;i<r.length;i++)MA(r[i],"video")||n.push(r[i])}return e&&n.push(e),n.join(",")}function oy(t,e){if(t&&(t.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t)!==-1)&&(aP(t,"audio")||aP(t,"video")))return t;if(e){const n=e.split(",");if(n.length>1){if(t){for(let r=n.length;r--;)if(n[r].substring(0,4)===t.substring(0,4))return n[r]}return n[0]}}return e||t}function aP(t,e){return MA(t,e)&&BA(t,e)}function Kle(t){const e=t.split(",");for(let n=0;n<e.length;n++){const r=e[n].split(".");r.length>2&&r[0]==="avc1"&&(e[n]=`avc1.${parseInt(r[1]).toString(16)}${("000"+parseInt(r[2]).toString(16)).slice(-4)}`)}return e.join(",")}function zle(t){if(t.startsWith("av01.")){const e=t.split("."),n=["0","111","01","01","01","0"];for(let r=e.length;r>4&&r<10;r++)e[r]=n[r-4];return e.join(".")}return t}function oP(t){const e=Cl(t)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function UE(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const qle={supported:!0,powerEfficient:!0,smooth:!0},Wle={supported:!1,smooth:!1,powerEfficient:!1},f3={supported:!0,configurations:[],decodingInfoResults:[qle]};function p3(t,e){return{supported:!1,configurations:e,decodingInfoResults:[Wle],error:t}}function Yle(t,e,n,r,i,s){const a=t.videoCodec,o=t.audioCodec?t.audioGroups:null,l=s==null?void 0:s.audioCodec,c=s==null?void 0:s.channels,u=c?parseInt(c):l?1/0:2;let d=null;if(o!=null&&o.length)try{o.length===1&&o[0]?d=e.groups[o[0]].channels:d=o.reduce((h,f)=>{if(f){const p=e.groups[f];if(!p)throw new Error(`Audio track group ${f} not found`);Object.keys(p.channels).forEach(m=>{h[m]=(h[m]||0)+p.channels[m]})}return h},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(h=>Iv(h))||t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(r,30)||t.videoRange!=="SDR"&&t.videoRange!==n||t.bitrate>Math.max(i,8e6))||!!d&&Ze(u)&&Object.keys(d).some(h=>parseInt(h)>u)}function m3(t,e,n,r={}){const i=t.videoCodec;if(!i&&!t.audioCodec||!n)return Promise.resolve(f3);const s=[],a=Xle(t),o=a.length,l=Qle(t,e,o>0),c=l.length;for(let u=o||1*c||1;u--;){const d={type:"media-source"};if(o&&(d.video=a[u%o]),c){d.audio=l[u%c];const h=d.audio.bitrate;d.video&&h&&(d.video.bitrate-=h)}s.push(d)}if(i){const u=navigator.userAgent;if(i.split(",").some(d=>Iv(d))&&h3())return Promise.resolve(p3(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),s))}return Promise.all(s.map(u=>{const d=Zle(u);return r[d]||(r[d]=n.decodingInfo(u))})).then(u=>({supported:!u.some(d=>!d.supported),configurations:s,decodingInfoResults:u})).catch(u=>({supported:!1,configurations:s,decodingInfoResults:[],error:u}))}function Xle(t){var e;const n=(e=t.videoCodec)==null?void 0:e.split(","),r=g3(t),i=t.width||640,s=t.height||480,a=t.frameRate||30,o=t.videoRange.toLowerCase();return n?n.map(l=>{const c={contentType:wp(zle(l),"video"),width:i,height:s,bitrate:r,framerate:a};return o!=="sdr"&&(c.transferFunction=o),c}):[]}function Qle(t,e,n){var r;const i=(r=t.audioCodec)==null?void 0:r.split(","),s=g3(t);return i&&t.audioGroups?t.audioGroups.reduce((a,o)=>{var l;const c=o?(l=e.groups[o])==null?void 0:l.tracks:null;return c?c.reduce((u,d)=>{if(d.groupId===o){const h=parseFloat(d.channels||"");i.forEach(f=>{const p={contentType:wp(f,"audio"),bitrate:n?Jle(f,s):s};h&&(p.channels=""+h),u.push(p)})}return u},a):a},[]):[]}function Jle(t,e){if(e<=1)return 1;let n=128e3;return t==="ec-3"?n=768e3:t==="ac-3"&&(n=64e4),Math.min(e/2,n)}function g3(t){return Math.ceil(Math.max(t.bitrate*.9,t.averageBitrate)/1e3)*1e3||1}function Zle(t){let e="";const{audio:n,video:r}=t;if(r){const i=UE(r.contentType);e+=`${i}_r${r.height}x${r.width}f${Math.ceil(r.framerate)}${r.transferFunction||"sd"}_${Math.ceil(r.bitrate/1e5)}`}if(n){const i=UE(n.contentType);e+=`${r?"_":""}${i}_c${n.channels}`}return e}const jE=["NONE","TYPE-0","TYPE-1",null];function ece(t){return jE.indexOf(t)>-1}const b0=["SDR","PQ","HLG"];function tce(t){return!!t&&b0.indexOf(t)>-1}var ly={No:"",Yes:"YES",v2:"v2"};function lP(t){const{canSkipUntil:e,canSkipDateRanges:n,age:r}=t,i=r<e/2;return e&&i?n?ly.v2:ly.Yes:ly.No}class cP{constructor(e,n,r){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=n,this.skip=r}addDirectives(e){const n=new self.URL(e);return this.msn!==void 0&&n.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&n.searchParams.set("_HLS_part",this.part.toString()),this.skip&&n.searchParams.set("_HLS_skip",this.skip),n.href}}class Tp{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(r=>!!r).map(r=>r.substring(0,4)).join(","),"supplemental"in e){var n;this.supplemental=e.supplemental;const r=(n=e.supplemental)==null?void 0:n.videoCodec;r&&r!==e.videoCodec&&(this.codecSet+=`,${r.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return uP(this._audioGroups,e)}hasSubtitleGroup(e){return uP(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,n){if(n){if(e==="audio"){let r=this._audioGroups;r||(r=this._audioGroups=[]),r.indexOf(n)===-1&&r.push(n)}else if(e==="text"){let r=this._subtitleGroups;r||(r=this._subtitleGroups=[]),r.indexOf(n)===-1&&r.push(n)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function uP(t,e){return!e||!t?!1:t.indexOf(e)!==-1}function nce(){if(typeof matchMedia=="function"){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return t.matches===!0}return!1}function rce(t,e){let n=!1,r=[];if(t&&(n=t!=="SDR",r=[t]),e){r=e.allowedVideoRanges||b0.slice(0);const i=r.join("")!=="SDR"&&!e.videoCodec;n=e.preferHDR!==void 0?e.preferHDR:i&&nce(),n||(r=["SDR"])}return{preferHDR:n,allowedVideoRanges:r}}const ice=t=>{const e=new WeakSet;return(n,r)=>{if(t&&(r=t(n,r)),typeof r=="object"&&r!==null){if(e.has(r))return;e.add(r)}return r}},yn=(t,e)=>JSON.stringify(t,ice(e));function sce(t,e,n,r,i){const s=Object.keys(t),a=r==null?void 0:r.channels,o=r==null?void 0:r.audioCodec,l=i==null?void 0:i.videoCodec,c=a&&parseInt(a)===2;let u=!1,d=!1,h=1/0,f=1/0,p=1/0,m=1/0,g=0,b=[];const{preferHDR:v,allowedVideoRanges:S}=rce(e,i);for(let k=s.length;k--;){const I=t[s[k]];u||(u=I.channels[2]>0),h=Math.min(h,I.minHeight),f=Math.min(f,I.minFramerate),p=Math.min(p,I.minBitrate),S.filter(M=>I.videoRanges[M]>0).length>0&&(d=!0)}h=Ze(h)?h:0,f=Ze(f)?f:0;const E=Math.max(1080,h),L=Math.max(30,f);p=Ze(p)?p:n,n=Math.max(p,n),d||(e=void 0);const U=s.length>1;return{codecSet:s.reduce((k,I)=>{const R=t[I];if(I===k)return k;if(b=d?S.filter(M=>R.videoRanges[M]>0):[],U){if(R.minBitrate>n)return Gs(I,`min bitrate of ${R.minBitrate} > current estimate of ${n}`),k;if(!R.hasDefaultAudio)return Gs(I,"no renditions with default or auto-select sound found"),k;if(o&&I.indexOf(o.substring(0,4))%5!==0)return Gs(I,`audio codec preference "${o}" not found`),k;if(a&&!c){if(!R.channels[a])return Gs(I,`no renditions with ${a} channel sound found (channels options: ${Object.keys(R.channels)})`),k}else if((!o||c)&&u&&R.channels[2]===0)return Gs(I,"no renditions with stereo sound found"),k;if(R.minHeight>E)return Gs(I,`min resolution of ${R.minHeight} > maximum of ${E}`),k;if(R.minFramerate>L)return Gs(I,`min framerate of ${R.minFramerate} > maximum of ${L}`),k;if(!b.some(M=>R.videoRanges[M]>0))return Gs(I,`no variants with VIDEO-RANGE of ${yn(b)} found`),k;if(l&&I.indexOf(l.substring(0,4))%5!==0)return Gs(I,`video codec preference "${l}" not found`),k;if(R.maxScore<g)return Gs(I,`max score of ${R.maxScore} < selected max of ${g}`),k}return k&&(v0(I)>=v0(k)||R.fragmentError>t[k].fragmentError)?k:(m=R.minIndex,g=R.maxScore,I)},void 0),videoRanges:b,preferHDR:v,minFramerate:f,minBitrate:p,minIndex:m}}function Gs(t,e){ln.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function y3(t){return t.reduce((e,n)=>{let r=e.groups[n.groupId];r||(r=e.groups[n.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(n);const i=n.channels||"2";return r.channels[i]=(r.channels[i]||0)+1,r.hasDefault=r.hasDefault||n.default,r.hasAutoSelect=r.hasAutoSelect||n.autoselect,r.hasDefault&&(e.hasDefaultAudio=!0),r.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function ace(t,e,n,r){return t.slice(n,r+1).reduce((i,s,a)=>{if(!s.codecSet)return i;const o=s.audioGroups;let l=i[s.codecSet];l||(i[s.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,s.bitrate);const c=Math.min(s.height,s.width);return l.minHeight=Math.min(l.minHeight,c),l.minFramerate=Math.min(l.minFramerate,s.frameRate),l.minIndex=Math.min(l.minIndex,a),l.maxScore=Math.max(l.maxScore,s.score),l.fragmentError+=s.fragmentError,l.videoRanges[s.videoRange]=(l.videoRanges[s.videoRange]||0)+1,o&&o.forEach(u=>{if(!u)return;const d=e.groups[u];d&&(l.hasDefaultAudio=l.hasDefaultAudio||e.hasDefaultAudio?d.hasDefault:d.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(d.channels).forEach(h=>{l.channels[h]=(l.channels[h]||0)+d.channels[h]}))}),i},{})}function dP(t){if(!t)return t;const{lang:e,assocLang:n,characteristics:r,channels:i,audioCodec:s}=t;return{lang:e,assocLang:n,characteristics:r,channels:i,audioCodec:s}}function aa(t,e,n){if("attrs"in t){const r=e.indexOf(t);if(r!==-1)return r}for(let r=0;r<e.length;r++){const i=e[r];if(Ic(t,i,n))return r}return-1}function Ic(t,e,n){const{groupId:r,name:i,lang:s,assocLang:a,default:o}=t,l=t.forced;return(r===void 0||e.groupId===r)&&(i===void 0||e.name===i)&&(s===void 0||oce(s,e.lang))&&(s===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(l===void 0||e.forced===l)&&(!("characteristics"in t)||lce(t.characteristics||"",e.characteristics))&&(n===void 0||n(t,e))}function oce(t,e="--"){return t.length===e.length?t===e:t.startsWith(e)||e.startsWith(t)}function lce(t,e=""){const n=t.split(","),r=e.split(",");return n.length===r.length&&!n.some(i=>r.indexOf(i)===-1)}function tc(t,e){const{audioCodec:n,channels:r}=t;return(n===void 0||(e.audioCodec||"").substring(0,4)===n.substring(0,4))&&(r===void 0||r===(e.channels||"2"))}function cce(t,e,n,r,i){const s=e[r],o=e.reduce((h,f,p)=>{const m=f.uri;return(h[m]||(h[m]=[])).push(p),h},{})[s.uri];o.length>1&&(r=Math.max.apply(Math,o));const l=s.videoRange,c=s.frameRate,u=s.codecSet.substring(0,4),d=hP(e,r,h=>{if(h.videoRange!==l||h.frameRate!==c||h.codecSet.substring(0,4)!==u)return!1;const f=h.audioGroups,p=n.filter(m=>!f||f.indexOf(m.groupId)!==-1);return aa(t,p,i)>-1});return d>-1?d:hP(e,r,h=>{const f=h.audioGroups,p=n.filter(m=>!f||f.indexOf(m.groupId)!==-1);return aa(t,p,i)>-1})}function hP(t,e,n){for(let r=e;r>-1;r--)if(n(t[r]))return r;for(let r=e+1;r<t.length;r++)if(n(t[r]))return r;return-1}function x0(t,e){var n;return!!t&&t!==((n=e.loadLevelObj)==null?void 0:n.uri)}class uce extends vs{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=n=>{var r;const{fragCurrent:i,partCurrent:s,hls:a}=this,{autoLevelEnabled:o,media:l}=a;if(!i||!l)return;const c=performance.now(),u=s?s.stats:i.stats,d=s?s.duration:i.duration,h=c-u.loading.start,f=a.minAutoLevel,p=i.level,m=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||p<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const g=m>-1&&m!==p,b=!!n||g;if(!b&&(l.paused||!l.playbackRate||!l.readyState))return;const v=a.mainForwardBufferInfo;if(!b&&v===null)return;const S=this.bwEstimator.getEstimateTTFB(),E=Math.abs(l.playbackRate);if(h<=Math.max(S,1e3*(d/(E*2))))return;const L=v?v.len/E:0,U=u.loading.first?u.loading.first-u.loading.start:-1,O=u.loaded&&U>-1,k=this.getBwEstimate(),I=a.levels,R=I[p],M=Math.max(u.loaded,Math.round(d*(i.bitrate||R.averageBitrate)/8));let z=O?h-U:h;z<1&&O&&(z=Math.min(h,u.loaded*8/k));const Z=O?u.loaded*1e3/z:0,W=S/1e3,re=Z?(M-u.loaded)/Z:M*8/k+W;if(re<=L)return;const X=Z?Z*8:k,oe=((r=(n==null?void 0:n.details)||this.hls.latestLevelDetails)==null?void 0:r.live)===!0,Q=this.hls.config.abrBandWidthUpFactor;let G=Number.POSITIVE_INFINITY,H;for(H=p-1;H>f;H--){const Le=I[H].maxBitrate,ke=!I[H].details||oe;if(G=this.getTimeToLoadFrag(W,X,d*Le,ke),G<Math.min(L,d+W))break}if(G>=re||G>d*10)return;O?this.bwEstimator.sample(h-Math.min(S,U),u.loaded):this.bwEstimator.sampleTTFB(h);const Y=I[H].maxBitrate;this.getBwEstimate()*Q>Y&&this.resetEstimator(Y);const ie=this.findBestLevel(Y,f,H,0,L,1,1);ie>-1&&(H=ie),this.warn(`Fragment ${i.sn}${s?" part "+s.index:""} of level ${p} is loading too slowly;
      Fragment duration: ${i.duration.toFixed(3)}
      Time to underbuffer: ${L.toFixed(3)} s
      Estimated load time for current fragment: ${re.toFixed(3)} s
      Estimated load time for down switch fragment: ${G.toFixed(3)} s
      TTFB estimate: ${U|0} ms
      Current BW estimate: ${Ze(k)?k|0:"Unknown"} bps
      New BW estimate: ${this.getBwEstimate()|0} bps
      Switching to level ${H} @ ${Y|0} bps`),a.nextLoadLevel=a.nextAutoLevel=H,this.clearTimer();const Ce=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===H&&H>0){const Le=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${H>0?"and switching down":""}
      Fragment duration: ${i.duration.toFixed(3)} s
      Time to underbuffer: ${Le.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,H>f){let ke=this.findBestLevel(this.hls.levels[f].bitrate,f,H,0,Le,1,1);ke===-1&&(ke=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=ke,this.resetEstimator(this.hls.levels[ke].bitrate)}}};g||re>G*2?Ce():this.timer=self.setInterval(Ce,G*1e3),a.trigger(j.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:s,stats:u})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new mle(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(j.MANIFEST_LOADING,this.onManifestLoading,this),e.on(j.FRAG_LOADING,this.onFragLoading,this),e.on(j.FRAG_LOADED,this.onFragLoaded,this),e.on(j.FRAG_BUFFERED,this.onFragBuffered,this),e.on(j.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(j.LEVEL_LOADED,this.onLevelLoaded,this),e.on(j.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(j.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(j.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(j.MANIFEST_LOADING,this.onManifestLoading,this),e.off(j.FRAG_LOADING,this.onFragLoading,this),e.off(j.FRAG_LOADED,this.onFragLoaded,this),e.off(j.FRAG_BUFFERED,this.onFragBuffered,this),e.off(j.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(j.LEVEL_LOADED,this.onLevelLoaded,this),e.off(j.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(j.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(j.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,n){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,n){const r=n.frag;if(!this.ignoreFragment(r)){if(!r.bitrateTest){var i;this.fragCurrent=r,this.partCurrent=(i=n.part)!=null?i:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,n){this.clearTimer()}onError(e,n){if(!n.fatal)switch(n.details){case xe.BUFFER_ADD_CODEC_ERROR:case xe.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case xe.FRAG_LOAD_TIMEOUT:{const r=n.frag,{fragCurrent:i,partCurrent:s}=this;if(r&&i&&r.sn===i.sn&&r.level===i.level){const a=performance.now(),o=s?s.stats:r.stats,l=a-o.loading.start,c=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&c>-1){const d=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(d,c),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,n,r,i){const s=e+r/n,a=i?e+this.lastLevelLoadSec:0;return s+a}onLevelLoaded(e,n){const r=this.hls.config,{loading:i}=n.stats,s=i.end-i.first;Ze(s)&&(this.lastLevelLoadSec=s/1e3),n.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(n.levelInfo)}onFragLoaded(e,{frag:n,part:r}){const i=r?r.stats:n.stats;if(n.type===tt.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(n)){if(this.clearTimer(),n.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const s=r?r.duration:n.duration,a=this.hls.levels[n.level],o=(a.loaded?a.loaded.bytes:0)+i.loaded,l=(a.loaded?a.loaded.duration:0)+s;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(n.bitrateTest){const s={stats:i,frag:n,part:r,id:n.type};this.onFragBuffered(j.FRAG_BUFFERED,s),n.bitrateTest=!1}else this.lastLoadedFragLevel=n.level}}onFragBuffered(e,n){const{frag:r,part:i}=n,s=i!=null&&i.stats.loaded?i.stats:r.stats;if(s.aborted||this.ignoreFragment(r))return;const a=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,s.loaded),s.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==tt.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:n}=this.hls,r=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,s=this.findBestLevel(r,n,e,0,i,1,1);if(s>-1)return s;const a=this.hls.firstLevel,o=Math.min(Math.max(a,n),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,r=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!r||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const s=r&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const a=this.hls.levels;if(a.length>Math.max(e,s)&&a[e].loadError<=a[s].loadError)return e}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:n,hls:r}=this;if(r.levels.length<=1)return r.loadLevel;const{maxAutoLevel:i,config:s,minAutoLevel:a}=r,o=n?n.duration:e?e.duration:0,l=this.getBwEstimate(),c=this.getStarvationDelay();let u=s.abrBandWidthFactor,d=s.abrBandWidthUpFactor;if(c){const g=this.findBestLevel(l,a,i,c,0,u,d);if(g>=0)return this.rebufferNotice=-1,g}let h=o?Math.min(o,s.maxStarvationDelay):s.maxStarvationDelay;if(!c){const g=this.bitrateTestDelay;g&&(h=(o?Math.min(o,s.maxLoadingDelay):s.maxLoadingDelay)-g,this.info(`bitrate test took ${Math.round(1e3*g)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),u=d=1)}const f=this.findBestLevel(l,a,i,c,h,u,d);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${c?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const p=r.levels[a],m=r.loadLevelObj;return m&&(p==null?void 0:p.bitrate)<m.bitrate?a:r.loadLevel}getStarvationDelay(){const e=this.hls,n=e.media;if(!n)return 1/0;const r=n&&n.playbackRate!==0?Math.abs(n.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/r}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,n,r,i,s,a,o){var l;const c=i+s,u=this.lastLoadedFragLevel,d=u===-1?this.hls.firstLevel:u,{fragCurrent:h,partCurrent:f}=this,{levels:p,allAudioTracks:m,loadLevel:g,config:b}=this.hls;if(p.length===1)return 0;const v=p[d],S=!!((l=this.hls.latestLevelDetails)!=null&&l.live),E=g===-1||u===-1;let L,U="SDR",O=(v==null?void 0:v.frameRate)||0;const{audioPreference:k,videoPreference:I}=b,R=this.audioTracksByGroup||(this.audioTracksByGroup=y3(m));let M=-1;if(E){if(this.firstSelection!==-1)return this.firstSelection;const X=this.codecTiers||(this.codecTiers=ace(p,R,n,r)),oe=sce(X,U,e,k,I),{codecSet:Q,videoRanges:G,minFramerate:H,minBitrate:Y,minIndex:ie,preferHDR:Ce}=oe;M=ie,L=Q,U=Ce?G[G.length-1]:G[0],O=H,e=Math.max(e,Y),this.log(`picked start tier ${yn(oe)}`)}else L=v==null?void 0:v.codecSet,U=v==null?void 0:v.videoRange;const z=f?f.duration:h?h.duration:0,Z=this.bwEstimator.getEstimateTTFB()/1e3,W=[];for(let X=r;X>=n;X--){var re;const oe=p[X],Q=X>d;if(!oe)continue;if(b.useMediaCapabilities&&!oe.supportedResult&&!oe.supportedPromise){const ke=navigator.mediaCapabilities;typeof(ke==null?void 0:ke.decodingInfo)=="function"&&Yle(oe,R,U,O,e,k)?(oe.supportedPromise=m3(oe,R,ke,this.supportedCache),oe.supportedPromise.then(Ne=>{if(!this.hls)return;oe.supportedResult=Ne;const ye=this.hls.levels,Ie=ye.indexOf(oe);Ne.error?this.warn(`MediaCapabilities decodingInfo error: "${Ne.error}" for level ${Ie} ${yn(Ne)}`):Ne.supported?Ne.decodingInfoResults.some(Ae=>Ae.smooth===!1||Ae.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Ie} not smooth or powerEfficient: ${yn(Ne)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Ie} ${yn(Ne)}`),Ie>-1&&ye.length>1&&(this.log(`Removing unsupported level ${Ie}`),this.hls.removeLevel(Ie),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Ne=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Ne}`)})):oe.supportedResult=f3}if((L&&oe.codecSet!==L||U&&oe.videoRange!==U||Q&&O>oe.frameRate||!Q&&O>0&&O<oe.frameRate||(re=oe.supportedResult)!=null&&(re=re.decodingInfoResults)!=null&&re.some(ke=>ke.smooth===!1))&&(!E||X!==M)){W.push(X);continue}const G=oe.details,H=(f?G==null?void 0:G.partTarget:G==null?void 0:G.averagetargetduration)||z;let Y;Q?Y=o*e:Y=a*e;const ie=z&&i>=z*2&&s===0?oe.averageBitrate:oe.maxBitrate,Ce=this.getTimeToLoadFrag(Z,Y,ie*H,G===void 0);if(Y>=ie&&(X===u||oe.loadError===0&&oe.fragmentError===0)&&(Ce<=Z||!Ze(Ce)||S&&!this.bitrateTestDelay||Ce<c)){const ke=this.forcedAutoLevel;return X!==g&&(ke===-1||ke!==g)&&(W.length&&this.trace(`Skipped level(s) ${W.join(",")} of ${r} max with CODECS and VIDEO-RANGE:"${p[W[0]].codecs}" ${p[W[0]].videoRange}; not compatible with "${L}" ${U}`),this.info(`switch candidate:${d}->${X} adjustedbw(${Math.round(Y)})-bitrate=${Math.round(Y-ie)} ttfb:${Z.toFixed(1)} avgDuration:${H.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${Ce.toFixed(1)} firstSelection:${E} codecSet:${oe.codecSet} videoRange:${oe.videoRange} hls.loadLevel:${g}`)),E&&(this.firstSelection=X),X}}return-1}set nextAutoLevel(e){const n=this.deriveNextAutoLevel(e);this._nextAutoLevel!==n&&(this.nextAutoLevelKey="",this._nextAutoLevel=n)}deriveNextAutoLevel(e){const{maxAutoLevel:n,minAutoLevel:r}=this.hls;return Math.min(Math.max(e,r),n)}}const v3={search:function(t,e){let n=0,r=t.length-1,i=null,s=null;for(;n<=r;){i=(n+r)/2|0,s=t[i];const a=e(s);if(a>0)n=i+1;else if(a<0)r=i-1;else return s}return null}};function dce(t,e,n){if(e===null||!Array.isArray(t)||!t.length||!Ze(e))return null;const r=t[0].programDateTime;if(e<(r||0))return null;const i=t[t.length-1].endProgramDateTime;if(e>=(i||0))return null;for(let s=0;s<t.length;++s){const a=t[s];if(fce(e,n,a))return a}return null}function Gc(t,e,n=0,r=0,i=.005){let s=null;if(t){s=e[1+t.sn-e[0].sn]||null;const o=t.endDTS-n;o>0&&o<15e-7&&(n+=15e-7),s&&t.level!==s.level&&s.end<=t.end&&(s=e[2+t.sn-e[0].sn]||null)}else n===0&&e[0].start===0&&(s=e[0]);if(s&&((!t||t.level===s.level)&&fP(n,r,s)===0||hce(s,t,Math.min(i,r))))return s;const a=v3.search(e,fP.bind(null,n,r));return a&&(a!==t||!s)?a:s}function hce(t,e,n){if(e&&e.start===0&&e.level<t.level&&(e.endPTS||0)>0){const r=e.tagList.reduce((i,s)=>(s[0]==="INF"&&(i+=parseFloat(s[1])),i),n);return t.start<=r}return!1}function fP(t=0,e=0,n){if(n.start<=t&&n.start+n.duration>t)return 0;const r=Math.min(e,n.duration+(n.deltaPTS?n.deltaPTS:0));return n.start+n.duration-r<=t?1:n.start-r>t&&n.start?-1:0}function fce(t,e,n){const r=Math.min(e,n.duration+(n.deltaPTS?n.deltaPTS:0))*1e3;return(n.endProgramDateTime||0)-r>t}function _3(t,e,n){if(t&&t.startCC<=e&&t.endCC>=e){let r=t.fragments;const{fragmentHint:i}=t;i&&(r=r.concat(i));let s;return v3.search(r,a=>a.cc<e?1:a.cc>e?-1:(s=a,a.end<=n?1:a.start>n?-1:0)),s||null}return null}function S0(t){switch(t.details){case xe.FRAG_LOAD_TIMEOUT:case xe.KEY_LOAD_TIMEOUT:case xe.LEVEL_LOAD_TIMEOUT:case xe.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function b3(t){return t.details.startsWith("key")}function x3(t){return b3(t)&&!!t.frag&&!t.frag.decryptdata}function pP(t,e){const n=S0(e);return t.default[`${n?"timeout":"error"}Retry`]}function UA(t,e){const n=t.backoff==="linear"?1:Math.pow(2,e);return Math.min(n*t.retryDelayMs,t.maxRetryDelayMs)}function mP(t){return on(on({},t),{errorRetry:null,timeoutRetry:null})}function E0(t,e,n,r){if(!t)return!1;const i=r==null?void 0:r.code,s=e<t.maxNumRetry&&(pce(i)||!!n);return t.shouldRetry?t.shouldRetry(t,e,n,r,s):s}function pce(t){return FE(t)||!!t&&(t<400||t>499)}function FE(t){return t===0&&navigator.onLine===!1}var Pr={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Li={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class mce extends vs{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(j.ERROR,this.onError,this),e.on(j.MANIFEST_LOADING,this.onManifestLoading,this),e.on(j.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(j.ERROR,this.onError,this),e.off(j.ERROR,this.onErrorOut,this),e.off(j.MANIFEST_LOADING,this.onManifestLoading,this),e.off(j.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===tt.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const n=this.hls,r=n.currentLevel;return(e=n.loadLevelObj)!=null&&e.details||r===-1?n.loadLevel:r}variantHasKey(e,n){if(e){var r;if((r=e.details)!=null&&r.hasKey(n))return!0;const i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(a=>i.indexOf(a.groupId)>=0).some(a=>{var o;return(o=a.details)==null?void 0:o.hasKey(n)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,n){var r;if(n.fatal)return;const i=this.hls,s=n.context;switch(n.details){case xe.FRAG_LOAD_ERROR:case xe.FRAG_LOAD_TIMEOUT:case xe.KEY_LOAD_ERROR:case xe.KEY_LOAD_TIMEOUT:n.errorAction=this.getFragRetryOrSwitchAction(n);return;case xe.FRAG_PARSING_ERROR:if((r=n.frag)!=null&&r.gap){n.errorAction=vd();return}case xe.FRAG_GAP:case xe.FRAG_DECRYPT_ERROR:{n.errorAction=this.getFragRetryOrSwitchAction(n),n.errorAction.action=Pr.SendAlternateToPenaltyBox;return}case xe.LEVEL_EMPTY_ERROR:case xe.LEVEL_PARSING_ERROR:{var a;const l=n.parent===tt.MAIN?n.level:i.loadLevel;n.details===xe.LEVEL_EMPTY_ERROR&&((a=n.context)!=null&&(a=a.levelDetails)!=null&&a.live)?n.errorAction=this.getPlaylistRetryOrSwitchAction(n,l):(n.levelRetry=!1,n.errorAction=this.getLevelSwitchAction(n,l))}return;case xe.LEVEL_LOAD_ERROR:case xe.LEVEL_LOAD_TIMEOUT:typeof(s==null?void 0:s.level)=="number"&&(n.errorAction=this.getPlaylistRetryOrSwitchAction(n,s.level));return;case xe.AUDIO_TRACK_LOAD_ERROR:case xe.AUDIO_TRACK_LOAD_TIMEOUT:case xe.SUBTITLE_LOAD_ERROR:case xe.SUBTITLE_TRACK_LOAD_TIMEOUT:if(s){const l=i.loadLevelObj;if(l&&(s.type===Ft.AUDIO_TRACK&&l.hasAudioGroup(s.groupId)||s.type===Ft.SUBTITLE_TRACK&&l.hasSubtitleGroup(s.groupId))){n.errorAction=this.getPlaylistRetryOrSwitchAction(n,i.loadLevel),n.errorAction.action=Pr.SendAlternateToPenaltyBox,n.errorAction.flags=Li.MoveAllAlternatesMatchingHost;return}}return;case xe.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:n.errorAction={action:Pr.SendAlternateToPenaltyBox,flags:Li.MoveAllAlternatesMatchingHDCP};return;case xe.KEY_SYSTEM_SESSION_UPDATE_FAILED:case xe.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case xe.KEY_SYSTEM_NO_SESSION:n.errorAction={action:Pr.SendAlternateToPenaltyBox,flags:Li.MoveAllAlternatesMatchingKey};return;case xe.BUFFER_ADD_CODEC_ERROR:case xe.REMUX_ALLOC_ERROR:case xe.BUFFER_APPEND_ERROR:if(!n.errorAction){var o;n.errorAction=this.getLevelSwitchAction(n,(o=n.level)!=null?o:i.loadLevel)}return;case xe.INTERNAL_EXCEPTION:case xe.BUFFER_APPENDING_ERROR:case xe.BUFFER_FULL_ERROR:case xe.LEVEL_SWITCH_ERROR:case xe.BUFFER_STALLED_ERROR:case xe.BUFFER_SEEK_OVER_HOLE:case xe.BUFFER_NUDGE_ON_STALL:n.errorAction=vd();return}n.type===ct.KEY_SYSTEM_ERROR&&(n.levelRetry=!1,n.errorAction=vd())}getPlaylistRetryOrSwitchAction(e,n){const r=this.hls,i=pP(r.config.playlistLoadPolicy,e),s=this.playlistError++;if(E0(i,s,S0(e),e.response))return{action:Pr.RetryRequest,flags:Li.None,retryConfig:i,retryCount:s};const o=this.getLevelSwitchAction(e,n);return i&&(o.retryConfig=i,o.retryCount=s),o}getFragRetryOrSwitchAction(e){const n=this.hls,r=this.getVariantLevelIndex(e.frag),i=n.levels[r],{fragLoadPolicy:s,keyLoadPolicy:a}=n.config,o=pP(b3(e)?a:s,e),l=n.levels.reduce((u,d)=>u+d.fragmentError,0);if(i&&(e.details!==xe.FRAG_GAP&&i.fragmentError++,!x3(e)&&E0(o,l,S0(e),e.response)))return{action:Pr.RetryRequest,flags:Li.None,retryConfig:o,retryCount:l};const c=this.getLevelSwitchAction(e,r);return o&&(c.retryConfig=o,c.retryCount=l),c}getLevelSwitchAction(e,n){const r=this.hls;n==null&&(n=r.loadLevel);const i=this.hls.levels[n];if(i){var s,a;const c=e.details;i.loadError++,c===xe.BUFFER_APPEND_ERROR&&i.fragmentError++;let u=-1;const{levels:d,loadLevel:h,minAutoLevel:f,maxAutoLevel:p}=r;!r.autoLevelEnabled&&!r.config.preserveManualLevelOnError&&(r.loadLevel=-1);const m=(s=e.frag)==null?void 0:s.type,b=(m===tt.AUDIO&&c===xe.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(c===xe.BUFFER_ADD_CODEC_ERROR||c===xe.BUFFER_APPEND_ERROR))&&d.some(({audioCodec:U})=>i.audioCodec!==U),S=e.sourceBufferName==="video"&&(c===xe.BUFFER_ADD_CODEC_ERROR||c===xe.BUFFER_APPEND_ERROR)&&d.some(({codecSet:U,audioCodec:O})=>i.codecSet!==U&&i.audioCodec===O),{type:E,groupId:L}=(a=e.context)!=null?a:{};for(let U=d.length;U--;){const O=(U+h)%d.length;if(O!==h&&O>=f&&O<=p&&d[O].loadError===0){var o,l;const k=d[O];if(c===xe.FRAG_GAP&&m===tt.MAIN&&e.frag){const I=d[O].details;if(I){const R=Gc(e.frag,I.fragments,e.frag.start);if(R!=null&&R.gap)continue}}else{if(E===Ft.AUDIO_TRACK&&k.hasAudioGroup(L)||E===Ft.SUBTITLE_TRACK&&k.hasSubtitleGroup(L))continue;if(m===tt.AUDIO&&(o=i.audioGroups)!=null&&o.some(I=>k.hasAudioGroup(I))||m===tt.SUBTITLE&&(l=i.subtitleGroups)!=null&&l.some(I=>k.hasSubtitleGroup(I))||b&&i.audioCodec===k.audioCodec||S&&i.codecSet===k.codecSet||!b&&i.codecSet!==k.codecSet)continue}u=O;break}}if(u>-1&&r.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:Pr.SendAlternateToPenaltyBox,flags:Li.None,nextAutoLevel:u}}return{action:Pr.SendAlternateToPenaltyBox,flags:Li.MoveAllAlternatesMatchingHost}}onErrorOut(e,n){var r;switch((r=n.errorAction)==null?void 0:r.action){case Pr.DoNothing:break;case Pr.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(n),!n.errorAction.resolved&&n.details!==xe.FRAG_GAP?n.fatal=!0:/MediaSource readyState: ended/.test(n.error.message)&&(this.warn(`MediaSource ended after "${n.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(n.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const n=this.hls,r=e.errorAction;if(!r)return;const{flags:i}=r,s=r.nextAutoLevel;switch(i){case Li.None:this.switchLevel(e,s);break;case Li.MoveAllAlternatesMatchingHDCP:{const l=this.getVariantLevelIndex(e.frag),c=n.levels[l],u=c==null?void 0:c.attrs["HDCP-LEVEL"];if(r.hdcpLevel=u,u==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(u){n.maxHdcpLevel=jE[jE.indexOf(u)-1],r.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${n.maxHdcpLevel}" or lower`);break}}case Li.MoveAllAlternatesMatchingKey:{const l=e.decryptdata;if(l){const c=this.hls.levels,u=c.length;for(let h=u;h--;)if(this.variantHasKey(c[h],l)){var a,o;this.log(`Banned key found in level ${h} (${c[h].bitrate}bps) or audio group "${(a=c[h].audioGroups)==null?void 0:a.join(",")}" (${(o=e.frag)==null?void 0:o.type} fragment) ${Dr(l.keyId||[])}`),c[h].fragmentError++,c[h].loadError++,this.log(`Removing level ${h} with key error (${e.error})`),this.hls.removeLevel(h)}const d=e.frag;if(this.hls.levels.length<u)r.resolved=!0;else if(d&&d.type!==tt.MAIN){const h=d.decryptdata;h&&!l.matches(h)&&(r.resolved=!0)}}break}}r.resolved||this.switchLevel(e,s)}switchLevel(e,n){if(n!==void 0&&e.errorAction&&(this.warn(`switching to level ${n} after ${e.details}`),this.hls.nextAutoLevel=n,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===xe.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const r=UE(e.mimeType),i=this.hls.levels;for(let s=i.length;s--;)i[s][`${e.sourceBufferName}Codec`]===r&&(this.log(`Removing level ${s} for ${e.details} ("${r}" not supported)`),this.hls.removeLevel(s))}}}function vd(t){const e={action:Pr.DoNothing,flags:Li.None};return t&&(e.resolved=!0),e}var pr={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class gce{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(j.MANIFEST_LOADING,this.onManifestLoading,this),e.on(j.BUFFER_APPENDED,this.onBufferAppended,this),e.on(j.FRAG_BUFFERED,this.onFragBuffered,this),e.on(j.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(j.MANIFEST_LOADING,this.onManifestLoading,this),e.off(j.BUFFER_APPENDED,this.onBufferAppended,this),e.off(j.FRAG_BUFFERED,this.onFragBuffered,this),e.off(j.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,n){const r=this.activePartLists[n];if(r)for(let i=r.length;i--;){const s=r[i];if(!s)break;if(s.start<=e&&e<=s.end&&s.loaded)return s}return this.getBufferedFrag(e,n)}getBufferedFrag(e,n){return this.getFragAtPos(e,n,!0)}getFragAtPos(e,n,r){const{fragments:i}=this,s=Object.keys(i);for(let a=s.length;a--;){const o=i[s[a]];if((o==null?void 0:o.body.type)===n&&(!r||o.buffered)){const l=o.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,n,r,i,s){this.timeRanges&&(this.timeRanges[e]=n);const a=(i==null?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach(o=>{const l=this.fragments[o];if(!l||a>=l.body.sn)return;if(!l.buffered&&(!l.loaded||s)){l.body.type===r&&this.removeFragment(l.body);return}const c=l.range[e];if(c){if(c.time.length===0){this.removeFragment(l.body);return}c.time.some(u=>{const d=!this.isTimeBuffered(u.startPTS,u.endPTS,n);return d&&this.removeFragment(l.body),d})}})}detectPartialFragments(e){const n=this.timeRanges;if(!n||e.frag.sn==="initSegment")return;const r=e.frag,i=Su(r),s=this.fragments[i];if(!s||s.buffered&&r.gap)return;const a=!r.relurl;Object.keys(n).forEach(o=>{const l=r.elementaryStreams[o];if(!l)return;const c=n[o],u=a||l.partial===!0;s.range[o]=this.getBufferedTimes(r,e.part,u,c)}),s.loaded=null,Object.keys(s.range).length?(this.bufferedEnd(s,r),bg(s)||this.removeParts(r.sn-1,r.type)):this.removeFragment(s.body)}bufferedEnd(e,n){e.buffered=!0,(e.body.endList=n.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,n){const r=this.activePartLists[n];r&&(this.activePartLists[n]=gP(r,i=>i.fragment.sn>=e))}fragBuffered(e,n){const r=Su(e);let i=this.fragments[r];!i&&n&&(i=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e))}getBufferedTimes(e,n,r,i){const s={time:[],partial:r},a=e.start,o=e.end,l=e.minEndPTS||o,c=e.maxStartPTS||a;for(let u=0;u<i.length;u++){const d=i.start(u)-this.bufferPadding,h=i.end(u)+this.bufferPadding;if(c>=d&&l<=h){s.time.push({startPTS:Math.max(a,i.start(u)),endPTS:Math.min(o,i.end(u))});break}else if(a<h&&o>d){const f=Math.max(a,i.start(u)),p=Math.min(o,i.end(u));p>f&&(s.partial=!0,s.time.push({startPTS:f,endPTS:p}))}else if(o<=d)break}return s}getPartialFragment(e){let n=null,r,i,s,a=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(c=>{const u=l[c];u&&bg(u)&&(i=u.body.start-o,s=u.body.end+o,e>=i&&e<=s&&(r=Math.min(e-i,s-e),a<=r&&(n=u.body,a=r)))}),n}isEndListAppended(e){const n=this.endListFragments[e];return n!==void 0&&(n.buffered||bg(n))}getState(e){const n=Su(e),r=this.fragments[n];return r?r.buffered?bg(r)?pr.PARTIAL:pr.OK:pr.APPENDING:pr.NOT_LOADED}isTimeBuffered(e,n,r){let i,s;for(let a=0;a<r.length;a++){if(i=r.start(a)-this.bufferPadding,s=r.end(a)+this.bufferPadding,e>=i&&n<=s)return!0;if(n<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,n){if(n.frag.sn==="initSegment"||n.frag.bitrateTest)return;const r=n.frag,i=n.part?null:n,s=Su(r);this.fragments[s]={body:r,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,n){const{frag:r,part:i,timeRanges:s,type:a}=n;if(r.sn==="initSegment")return;const o=r.type;if(i){let c=this.activePartLists[o];c||(this.activePartLists[o]=c=[]),c.push(i)}this.timeRanges=s;const l=s[a];this.detectEvictedFragments(a,l,o,i)}onFragBuffered(e,n){this.detectPartialFragments(n)}hasFragment(e){const n=Su(e);return!!this.fragments[n]}hasFragments(e){const{fragments:n}=this,r=Object.keys(n);if(!e)return r.length>0;for(let i=r.length;i--;){const s=n[r[i]];if((s==null?void 0:s.body.type)===e)return!0}return!1}hasParts(e){var n;return!!((n=this.activePartLists[e])!=null&&n.length)}removeFragmentsInRange(e,n,r,i,s){i&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const l=o.body;l.type!==r||i&&!l.gap||l.start<n&&l.end>e&&(o.buffered||s)&&this.removeFragment(l)})}removeFragment(e){const n=Su(e);e.clearElementaryStreamInfo();const r=this.activePartLists[e.type];if(r){const i=e.sn;this.activePartLists[e.type]=gP(r,s=>s.fragment.sn!==i)}delete this.fragments[n],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const n=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;n&&n.forEach(r=>r.clearElementaryStreamInfo())}}function bg(t){var e,n,r;return t.buffered&&!!(t.body.gap||(e=t.range.video)!=null&&e.partial||(n=t.range.audio)!=null&&n.partial||(r=t.range.audiovideo)!=null&&r.partial)}function Su(t){return`${t.type}_${t.level}_${t.sn}`}function gP(t,e){return t.filter(n=>{const r=e(n);return r||n.clearElementaryStreamInfo(),r})}var Ll={cbc:0,ctr:1};class yce{constructor(e,n,r){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=n,this.aesMode=r}decrypt(e,n){switch(this.aesMode){case Ll.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},n,e);case Ll.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},n,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function vce(t){const e=t.byteLength,n=e&&new DataView(t.buffer).getUint8(e-1);return n?t.slice(0,e-n):t}class _ce{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const n=new DataView(e),r=new Uint32Array(4);for(let i=0;i<4;i++)r[i]=n.getUint32(i*4);return r}initTable(){const e=this.sBox,n=this.invSBox,r=this.subMix,i=r[0],s=r[1],a=r[2],o=r[3],l=this.invSubMix,c=l[0],u=l[1],d=l[2],h=l[3],f=new Uint32Array(256);let p=0,m=0,g=0;for(g=0;g<256;g++)g<128?f[g]=g<<1:f[g]=g<<1^283;for(g=0;g<256;g++){let b=m^m<<1^m<<2^m<<3^m<<4;b=b>>>8^b&255^99,e[p]=b,n[b]=p;const v=f[p],S=f[v],E=f[S];let L=f[b]*257^b*16843008;i[p]=L<<24|L>>>8,s[p]=L<<16|L>>>16,a[p]=L<<8|L>>>24,o[p]=L,L=E*16843009^S*65537^v*257^p*16843008,c[b]=L<<24|L>>>8,u[b]=L<<16|L>>>16,d[b]=L<<8|L>>>24,h[b]=L,p?(p=v^f[f[f[E^v]]],m^=f[f[m]]):p=m=1}}expandKey(e){const n=this.uint8ArrayToUint32Array_(e);let r=!0,i=0;for(;i<n.length&&r;)r=n[i]===this.key[i],i++;if(r)return;this.key=n;const s=this.keySize=n.length;if(s!==4&&s!==6&&s!==8)throw new Error("Invalid aes key size="+s);const a=this.ksRows=(s+6+1)*4;let o,l;const c=this.keySchedule=new Uint32Array(a),u=this.invKeySchedule=new Uint32Array(a),d=this.sBox,h=this.rcon,f=this.invSubMix,p=f[0],m=f[1],g=f[2],b=f[3];let v,S;for(o=0;o<a;o++){if(o<s){v=c[o]=n[o];continue}S=v,o%s===0?(S=S<<8|S>>>24,S=d[S>>>24]<<24|d[S>>>16&255]<<16|d[S>>>8&255]<<8|d[S&255],S^=h[o/s|0]<<24):s>6&&o%s===4&&(S=d[S>>>24]<<24|d[S>>>16&255]<<16|d[S>>>8&255]<<8|d[S&255]),c[o]=v=(c[o-s]^S)>>>0}for(l=0;l<a;l++)o=a-l,l&3?S=c[o]:S=c[o-4],l<4||o<=4?u[l]=S:u[l]=p[d[S>>>24]]^m[d[S>>>16&255]]^g[d[S>>>8&255]]^b[d[S&255]],u[l]=u[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,n,r){const i=this.keySize+6,s=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],c=o[1],u=o[2],d=o[3],h=this.uint8ArrayToUint32Array_(r);let f=h[0],p=h[1],m=h[2],g=h[3];const b=new Int32Array(e),v=new Int32Array(b.length);let S,E,L,U,O,k,I,R,M,z,Z,W,re,X;const oe=this.networkToHostOrderSwap;for(;n<b.length;){for(M=oe(b[n]),z=oe(b[n+1]),Z=oe(b[n+2]),W=oe(b[n+3]),O=M^s[0],k=W^s[1],I=Z^s[2],R=z^s[3],re=4,X=1;X<i;X++)S=l[O>>>24]^c[k>>16&255]^u[I>>8&255]^d[R&255]^s[re],E=l[k>>>24]^c[I>>16&255]^u[R>>8&255]^d[O&255]^s[re+1],L=l[I>>>24]^c[R>>16&255]^u[O>>8&255]^d[k&255]^s[re+2],U=l[R>>>24]^c[O>>16&255]^u[k>>8&255]^d[I&255]^s[re+3],O=S,k=E,I=L,R=U,re=re+4;S=a[O>>>24]<<24^a[k>>16&255]<<16^a[I>>8&255]<<8^a[R&255]^s[re],E=a[k>>>24]<<24^a[I>>16&255]<<16^a[R>>8&255]<<8^a[O&255]^s[re+1],L=a[I>>>24]<<24^a[R>>16&255]<<16^a[O>>8&255]<<8^a[k&255]^s[re+2],U=a[R>>>24]<<24^a[O>>16&255]<<16^a[k>>8&255]<<8^a[I&255]^s[re+3],v[n]=oe(S^f),v[n+1]=oe(U^p),v[n+2]=oe(L^m),v[n+3]=oe(E^g),f=M,p=z,m=Z,g=W,n=n+4}return v.buffer}}class bce{constructor(e,n,r){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=n,this.aesMode=r}expandKey(){const e=xce(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function xce(t){switch(t){case Ll.cbc:return"AES-CBC";case Ll.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${t}`)}}const Sce=16;class jA{constructor(e,{removePKCS7Padding:n=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=n,n)try{const r=self.crypto;r&&(this.subtle=r.subtle||r.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:n}=this;if(!e||n)return this.reset(),null;const r=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?vce(r):r}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,n,r,i){return this.useSoftware?new Promise((s,a)=>{const o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,n,r,i);const l=this.flush();l?s(l.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),n,r,i)}softwareDecrypt(e,n,r,i){const{currentIV:s,currentResult:a,remainderData:o}=this;if(i!==Ll.cbc||n.byteLength!==16)return ln.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=ys(o,e),this.remainderData=null);const l=this.getValidChunk(e);if(!l.length)return null;s&&(r=s);let c=this.softwareDecrypter;c||(c=this.softwareDecrypter=new _ce),c.expandKey(n);const u=a;return this.currentResult=c.decrypt(l.buffer,0,r),this.currentIV=l.slice(-16).buffer,u||null}webCryptoDecrypt(e,n,r,i){if(this.key!==n||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,n,r,i));this.key=n,this.fastAesKey=new bce(this.subtle,n,i)}return this.fastAesKey.expandKey().then(s=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new yce(this.subtle,new Uint8Array(r),i).decrypt(e.buffer,s)):Promise.reject(new Error("web crypto not initialized"))).catch(s=>(ln.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${s.name}: ${s.message}`),this.onWebCryptoError(e,n,r,i)))}onWebCryptoError(e,n,r,i){const s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,n,r,i);const a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(s?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let n=e;const r=e.length-e.length%Sce;return r!==e.length&&(n=e.slice(0,r),this.remainderData=e.slice(r)),n}logOnce(e){this.logEnabled&&(ln.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const yP=Math.pow(2,17);class Ece{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,n){const r=e.url;if(!r)return Promise.reject(new Ha({type:ct.NETWORK_ERROR,details:xe.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${r?"part list":"url"}`),networkDetails:null}));this.abort();const i=this.config,s=i.fLoader,a=i.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(p=>p[0]==="GAP")){l(_P(e));return}else e.gap=!1;const c=this.loader=s?new s(i):new a(i),u=vP(e);e.loader=c;const d=mP(i.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:yP};e.stats=c.stats;const f={onSuccess:(p,m,g,b)=>{this.resetLoader(e,c);let v=p.data;g.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(v.slice(0,16)),v=v.slice(16)),o({frag:e,part:null,payload:v,networkDetails:b})},onError:(p,m,g,b)=>{this.resetLoader(e,c),l(new Ha({type:ct.NETWORK_ERROR,details:xe.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:on({url:r,data:void 0},p),error:new Error(`HTTP Error ${p.code} ${p.text}`),networkDetails:g,stats:b}))},onAbort:(p,m,g)=>{this.resetLoader(e,c),l(new Ha({type:ct.NETWORK_ERROR,details:xe.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:g,stats:p}))},onTimeout:(p,m,g)=>{this.resetLoader(e,c),l(new Ha({type:ct.NETWORK_ERROR,details:xe.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:g,stats:p}))}};n&&(f.onProgress=(p,m,g,b)=>n({frag:e,part:null,payload:g,networkDetails:b})),c.load(u,h,f)})}loadPart(e,n,r){this.abort();const i=this.config,s=i.fLoader,a=i.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||n.gap){l(_P(e,n));return}const c=this.loader=s?new s(i):new a(i),u=vP(e,n);e.loader=c;const d=mP(i.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:yP};n.stats=c.stats,c.load(u,h,{onSuccess:(f,p,m,g)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,n);const b={frag:e,part:n,payload:f.data,networkDetails:g};r(b),o(b)},onError:(f,p,m,g)=>{this.resetLoader(e,c),l(new Ha({type:ct.NETWORK_ERROR,details:xe.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:n,response:on({url:u.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:m,stats:g}))},onAbort:(f,p,m)=>{e.stats.aborted=n.stats.aborted,this.resetLoader(e,c),l(new Ha({type:ct.NETWORK_ERROR,details:xe.INTERNAL_ABORTED,fatal:!1,frag:e,part:n,error:new Error("Aborted"),networkDetails:m,stats:f}))},onTimeout:(f,p,m)=>{this.resetLoader(e,c),l(new Ha({type:ct.NETWORK_ERROR,details:xe.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:n,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:m,stats:f}))}})})}updateStatsFromPart(e,n){const r=e.stats,i=n.stats,s=i.total;if(r.loaded+=i.loaded,s){const l=Math.round(e.duration/n.duration),c=Math.min(Math.round(r.loaded/s),l),d=(l-c)*Math.round(r.loaded/c);r.total=r.loaded+d}else r.total=Math.max(r.loaded,r.total);const a=r.loading,o=i.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,n){e.loader=null,this.loader===n&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),n.destroy()}}function vP(t,e=null){const n=e||t,r={frag:t,part:e,responseType:"arraybuffer",url:n.url,headers:{},rangeStart:0,rangeEnd:0},i=n.byteRangeStartOffset,s=n.byteRangeEndOffset;if(Ze(i)&&Ze(s)){var a;let o=i,l=s;if(t.sn==="initSegment"&&wce((a=t.decryptdata)==null?void 0:a.method)){const c=s-i;c%16&&(l=s+(16-c%16)),i!==0&&(r.resetIV=!0,o=i-16)}r.rangeStart=o,r.rangeEnd=l}return r}function _P(t,e){const n=new Error(`GAP ${t.gap?"tag":"attribute"} found`),r={type:ct.MEDIA_ERROR,details:xe.FRAG_GAP,fatal:!1,frag:t,error:n,networkDetails:null};return e&&(r.part=e),(e||t).stats.aborted=!0,new Ha(r)}function wce(t){return t==="AES-128"||t==="AES-256"}class Ha extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class S3 extends vs{constructor(e,n){super(e,n),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class FA{constructor(e,n,r,i=0,s=-1,a=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=xg(),this.buffering={audio:xg(),video:xg(),audiovideo:xg()},this.level=e,this.sn=n,this.id=r,this.size=i,this.part=s,this.partial=a}}function xg(){return{start:0,executeStart:0,executeEnd:0,end:0}}const bP={length:0,start:()=>0,end:()=>0};class Ct{static isBuffered(e,n){if(e){const r=Ct.getBuffered(e);for(let i=r.length;i--;)if(n>=r.start(i)&&n<=r.end(i))return!0}return!1}static bufferedRanges(e){if(e){const n=Ct.getBuffered(e);return Ct.timeRangesToArray(n)}return[]}static timeRangesToArray(e){const n=[];for(let r=0;r<e.length;r++)n.push({start:e.start(r),end:e.end(r)});return n}static bufferInfo(e,n,r){if(e){const i=Ct.bufferedRanges(e);if(i.length)return Ct.bufferedInfo(i,n,r)}return{len:0,start:n,end:n,bufferedIndex:-1}}static bufferedInfo(e,n,r){n=Math.max(0,n),e.length>1&&e.sort((u,d)=>u.start-d.start||d.end-u.end);let i=-1,s=[];if(r)for(let u=0;u<e.length;u++){n>=e[u].start&&n<=e[u].end&&(i=u);const d=s.length;if(d){const h=s[d-1].end;e[u].start-h<r?e[u].end>h&&(s[d-1].end=e[u].end):s.push(e[u])}else s.push(e[u])}else s=e;let a=0,o,l=n,c=n;for(let u=0;u<s.length;u++){const d=s[u].start,h=s[u].end;if(i===-1&&n>=d&&n<=h&&(i=u),n+r>=d&&n<h)l=d,c=h,a=c-n;else if(n+r<d){o=d;break}}return{len:a,start:l||0,end:c||0,nextStart:o,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||bP}catch(n){return ln.log("failed to get media.buffered",n),bP}}}const E3=/\{\$([a-zA-Z0-9-_]+)\}/g;function xP(t){return E3.test(t)}function $E(t,e){if(t.variableList!==null||t.hasVariableRefs){const n=t.variableList;return e.replace(E3,r=>{const i=r.substring(2,r.length-1),s=n==null?void 0:n[i];return s===void 0?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),r):s})}return e}function SP(t,e,n){let r=t.variableList;r||(t.variableList=r={});let i,s;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{const a=new self.URL(n).searchParams;if(a.has(i))s=a.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${n}"`)}catch(a){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else i=e.NAME,s=e.VALUE;i in r?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):r[i]=s||""}function Tce(t,e,n){const r=e.IMPORT;if(n&&r in n){let i=t.variableList;i||(t.variableList=i={}),i[r]=n[r]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}const Ace=/^(\d+)x(\d+)$/,EP=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Mn{constructor(e,n){typeof e=="string"&&(e=Mn.parseAttrList(e,n)),fn(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const n=parseInt(this[e],10);return n>Number.MAX_SAFE_INTEGER?1/0:n}hexadecimalInteger(e){if(this[e]){let n=(this[e]||"0x").slice(2);n=(n.length&1?"0":"")+n;const r=new Uint8Array(n.length/2);for(let i=0;i<n.length/2;i++)r[i]=parseInt(n.slice(i*2,i*2+2),16);return r}return null}hexadecimalIntegerAsNumber(e){const n=parseInt(this[e],16);return n>Number.MAX_SAFE_INTEGER?1/0:n}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,n){const r=this[e];return r?parseFloat(r):n}enumeratedString(e){return this[e]}enumeratedStringList(e,n){const r=this[e];return(r?r.split(/[ ,]+/):[]).reduce((i,s)=>(i[s.toLowerCase()]=!0,i),n)}bool(e){return this[e]==="YES"}decimalResolution(e){const n=Ace.exec(this[e]);if(n!==null)return{width:parseInt(n[1],10),height:parseInt(n[2],10)}}static parseAttrList(e,n){let r;const i={},s='"';for(EP.lastIndex=0;(r=EP.exec(e))!==null;){const a=r[1].trim();let o=r[2];const l=o.indexOf(s)===0&&o.lastIndexOf(s)===o.length-1;let c=!1;if(l)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":c=!0}if(n&&(l||c))o=$E(n,o);else if(!c&&!l)switch(a){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":ln.warn(`${e}: attribute ${a} is missing quotes`)}i[a]=o}return i}}const Rce="com.apple.hls.interstitial";function Cce(t){return t!=="ID"&&t!=="CLASS"&&t!=="CUE"&&t!=="START-DATE"&&t!=="DURATION"&&t!=="END-DATE"&&t!=="END-ON-NEXT"}function Lce(t){return t==="SCTE35-OUT"||t==="SCTE35-IN"||t==="SCTE35-CMD"}class w3{constructor(e,n,r=0){var i;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(n==null?void 0:n.tagAnchor)||null,this.tagOrder=(i=n==null?void 0:n.tagOrder)!=null?i:r,n){const s=n.attr;for(const a in s)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==s[a]){ln.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=fn(new Mn({}),s,e)}if(this.attr=e,n?(this._startDate=n._startDate,this._cue=n._cue,this._endDate=n._endDate,this._dateAtEnd=n._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const s=(n==null?void 0:n.endDate)||new Date(this.attr["END-DATE"]);Ze(s.getTime())&&(this._endDate=s)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(ln.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const n=this.duration;return n!==null?this._dateAtEnd=new Date(this._startDate.getTime()+n*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(Ze(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===Rce}get isValid(){return!!this.id&&!this._badValueForSameId&&Ze(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const kce=10;class Ice{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const n=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!n||!this.live,this.advanced=this.endSN>e.endSN||n>0||n===0&&r>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(n=>{let r=n.decryptdata;return r||(n.setKeyFormat(e.keyFormat),r=n.decryptdata),!!r&&e.matches(r)})}get hasProgramDateTime(){return this.fragments.length?Ze(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||kce}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const n=this.lastPartIndex;if(n!==-1){for(let r=e.length;r--;)if(e[r].index>n)return e[r].index;return n}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function w0(t,e){return t.length===e.length?!t.some((n,r)=>n!==e[r]):!1}function wP(t,e){return!t&&!e?!0:!t||!e?!1:w0(t,e)}function _d(t){return t==="AES-128"||t==="AES-256"||t==="AES-256-CTR"}function $A(t){switch(t){case"AES-128":case"AES-256":return Ll.cbc;case"AES-256-CTR":return Ll.ctr;default:throw new Error(`invalid full segment method ${t}`)}}function VA(t){return Uint8Array.from(atob(t),e=>e.charCodeAt(0))}function VE(t){return Uint8Array.from(unescape(encodeURIComponent(t)),e=>e.charCodeAt(0))}function Pce(t){const e=VE(t).subarray(0,16),n=new Uint8Array(16);return n.set(e,16-e.length),n}function T3(t){const e=function(r,i,s){const a=r[i];r[i]=r[s],r[s]=a};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}function A3(t){const e=t.split(":");let n=null;if(e[0]==="data"&&e.length===2){const r=e[1].split(";"),i=r[r.length-1].split(",");if(i.length===2){const s=i[0]==="base64",a=i[1];s?(r.splice(-1,1),n=VA(a)):n=Pce(a)}}return n}const T0=typeof self<"u"?self:void 0;var Bn={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Nr={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function cy(t){switch(t){case Nr.FAIRPLAY:return Bn.FAIRPLAY;case Nr.PLAYREADY:return Bn.PLAYREADY;case Nr.WIDEVINE:return Bn.WIDEVINE;case Nr.CLEARKEY:return Bn.CLEARKEY}}function $b(t){switch(t){case Bn.FAIRPLAY:return Nr.FAIRPLAY;case Bn.PLAYREADY:return Nr.PLAYREADY;case Bn.WIDEVINE:return Nr.WIDEVINE;case Bn.CLEARKEY:return Nr.CLEARKEY}}function sf(t){const{drmSystems:e,widevineLicenseUrl:n}=t,r=e?[Bn.FAIRPLAY,Bn.WIDEVINE,Bn.PLAYREADY,Bn.CLEARKEY].filter(i=>!!e[i]):[];return!r[Bn.WIDEVINE]&&n&&r.push(Bn.WIDEVINE),r}const R3=function(t){return T0!=null&&(t=T0.navigator)!=null&&t.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function Dce(t,e,n,r){let i;switch(t){case Bn.FAIRPLAY:i=["cenc","sinf"];break;case Bn.WIDEVINE:case Bn.PLAYREADY:i=["cenc"];break;case Bn.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return Oce(i,e,n,r)}function Oce(t,e,n,r){return[{initDataTypes:t,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:e.map(s=>({contentType:`audio/mp4; codecs=${s}`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null})),videoCapabilities:n.map(s=>({contentType:`video/mp4; codecs=${s}`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}))}]}function Nce(t){var e;return!!t&&(t.sessionType==="persistent-license"||!!((e=t.sessionTypes)!=null&&e.some(n=>n==="persistent-license")))}function C3(t){const e=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),n=String.fromCharCode.apply(null,Array.from(e)),r=n.substring(n.indexOf("<"),n.length),a=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(a){const o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){const l=VA(o).subarray(0,16);return T3(l),l}}return null}let Eu={};class yl{static clearKeyUriToKeyIdMap(){Eu={}}static setKeyIdForUri(e,n){Eu[e]=n}static addKeyIdForUri(e){const n=Object.keys(Eu).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,n),Eu[e]=r,r}constructor(e,n,r,i=[1],s=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=n,this.keyFormat=r,this.keyFormatVersions=i,this.iv=s,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!_d(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(n3(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&w0(e.keyFormatVersions,this.keyFormatVersions)&&wP(e.iv,this.iv)&&wP(e.keyId,this.keyId)}isSupported(){if(this.method){if(_d(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Nr.FAIRPLAY:case Nr.WIDEVINE:case Nr.PLAYREADY:case Nr.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,n){if(!this.encrypted||!this.uri)return null;if(_d(this.method)){let s=this.iv;return s||(typeof e!="number"&&(ln.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),s=Bce(e)),new yl(this.method,this.uri,"identity",this.keyFormatVersions,s)}if(this.keyId){const s=Eu[this.uri];if(s&&!w0(this.keyId,s)&&yl.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const r=A3(this.uri);if(r)switch(this.keyFormat){case Nr.WIDEVINE:if(this.pssh=r,!this.keyId){const s=Fle(r.buffer);if(s.length){var i;const a=s[0];this.keyId=(i=a.kids)!=null&&i.length?a.kids[0]:null}}this.keyId||(this.keyId=TP(n));break;case Nr.PLAYREADY:{const s=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=jle(s,null,r),this.keyId=C3(r);break}default:{let s=r.subarray(0,16);if(s.length!==16){const a=new Uint8Array(16);a.set(s,16-s.length),s=a}this.keyId=s;break}}if(!this.keyId||this.keyId.byteLength!==16){let s;s=Mce(n),s||(s=TP(n),s||(s=Eu[this.uri])),s&&(this.keyId=s,yl.setKeyIdForUri(this.uri,s))}return this}}function Mce(t){const e=t==null?void 0:t[Nr.WIDEVINE];return e?e.keyId:null}function TP(t){const e=t==null?void 0:t[Nr.PLAYREADY];if(e){const n=A3(e.uri);if(n)return C3(n)}return null}function Bce(t){const e=new Uint8Array(16);for(let n=12;n<16;n++)e[n]=t>>8*(15-n)&255;return e}const AP=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,RP=/#EXT-X-MEDIA:(.*)/g,Uce=/^#EXT(?:INF|-X-TARGETDURATION):/m,Vb=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),jce=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class oa{static findGroup(e,n){for(let r=0;r<e.length;r++){const i=e[r];if(i.id===n)return i}}static resolve(e,n){return DA.buildAbsoluteURL(n,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Uce.test(e)}static parseMasterPlaylist(e,n){const r=xP(e),i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:r},s=[];if(AP.lastIndex=0,!e.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let a;for(;(a=AP.exec(e))!=null;)if(a[1]){var o;const c=new Mn(a[1],i),u=$E(i,a[2]),d={attrs:c,bitrate:c.decimalInteger("BANDWIDTH")||c.decimalInteger("AVERAGE-BANDWIDTH"),name:c.NAME,url:oa.resolve(u,n)},h=c.decimalResolution("RESOLUTION");h&&(d.width=h.width,d.height=h.height),kP(c.CODECS,d);const f=c["SUPPLEMENTAL-CODECS"];f&&(d.supplemental={},kP(f,d.supplemental)),(o=d.unknownCodecs)!=null&&o.length||s.push(d),i.levels.push(d)}else if(a[3]){const c=a[3],u=a[4];switch(c){case"SESSION-DATA":{const d=new Mn(u,i),h=d["DATA-ID"];h&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[h]=d);break}case"SESSION-KEY":{const d=CP(u,n,i);d.encrypted&&d.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(d)):ln.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{const d=new Mn(u,i);SP(i,d,n)}break}case"CONTENT-STEERING":{const d=new Mn(u,i);i.contentSteering={uri:oa.resolve(d["SERVER-URI"],n),pathwayId:d["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=LP(u);break}}}const l=s.length>0&&s.length<i.levels.length;return i.levels=l?s:i.levels,i.levels.length===0&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,n,r){let i;const s={},a=r.levels,o={AUDIO:a.map(c=>({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:a.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(RP.lastIndex=0;(i=RP.exec(e))!==null;){const c=new Mn(i[1],r),u=c.TYPE;if(u){const d=o[u],h=s[u]||[];s[u]=h;const f=c.LANGUAGE,p=c["ASSOC-LANGUAGE"],m=c.CHANNELS,g=c.CHARACTERISTICS,b=c["INSTREAM-ID"],v={attrs:c,bitrate:0,id:l++,groupId:c["GROUP-ID"]||"",name:c.NAME||f||"",type:u,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:f,url:c.URI?oa.resolve(c.URI,n):""};if(p&&(v.assocLang=p),m&&(v.channels=m),g&&(v.characteristics=g),b&&(v.instreamId=b),d!=null&&d.length){const S=oa.findGroup(d,v.groupId)||d[0];IP(v,S,"audioCodec"),IP(v,S,"textCodec")}h.push(v)}}return s}static parseLevelPlaylist(e,n,r,i,s,a){var o;const l={url:n},c=new Ice(n),u=c.fragments,d=[];let h=null,f=0,p=0,m=0,g=0,b=0,v=null,S=new Ub(i,l),E,L,U,O=-1,k=!1,I=null,R;if(Vb.lastIndex=0,c.m3u8=e,c.hasVariableRefs=xP(e),((o=Vb.exec(e))==null?void 0:o[0])!=="#EXTM3U")return c.playlistParsingError=new Error("Missing format identifier #EXTM3U"),c;for(;(E=Vb.exec(e))!==null;){k&&(k=!1,S=new Ub(i,l),S.playlistOffset=m,S.setStart(m),S.sn=f,S.cc=g,b&&(S.bitrate=b),S.level=r,h&&(S.initSegment=h,h.rawProgramDateTime&&(S.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null),I&&(S.setByteRange(I),I=null)));const W=E[1];if(W){S.duration=parseFloat(W);const re=(" "+E[2]).slice(1);S.title=re||null,S.tagList.push(re?["INF",W,re]:["INF",W])}else if(E[3]){if(Ze(S.duration)){S.playlistOffset=m,S.setStart(m),U&&DP(S,U,c),S.sn=f,S.level=r,S.cc=g,u.push(S);const re=(" "+E[3]).slice(1);S.relurl=$E(c,re),GE(S,v,d),v=S,m+=S.duration,f++,p=0,k=!0}}else{if(E=E[0].match(jce),!E){ln.warn("No matches on slow regex match for level playlist!");continue}for(L=1;L<E.length&&E[L]===void 0;L++);const re=(" "+E[L]).slice(1),X=(" "+E[L+1]).slice(1),oe=E[L+2]?(" "+E[L+2]).slice(1):null;switch(re){case"BYTERANGE":v?S.setByteRange(X,v):S.setByteRange(X);break;case"PROGRAM-DATE-TIME":S.rawProgramDateTime=X,S.tagList.push(["PROGRAM-DATE-TIME",X]),O===-1&&(O=u.length);break;case"PLAYLIST-TYPE":c.type&&Ua(c,re,E),c.type=X.toUpperCase();break;case"MEDIA-SEQUENCE":c.startSN!==0?Ua(c,re,E):u.length>0&&OP(c,re,E),f=c.startSN=parseInt(X);break;case"SKIP":{c.skippedSegments&&Ua(c,re,E);const Q=new Mn(X,c),G=Q.decimalInteger("SKIPPED-SEGMENTS");if(Ze(G)){c.skippedSegments+=G;for(let Y=G;Y--;)u.push(null);f+=G}const H=Q.enumeratedString("RECENTLY-REMOVED-DATERANGES");H&&(c.recentlyRemovedDateranges=(c.recentlyRemovedDateranges||[]).concat(H.split("	")));break}case"TARGETDURATION":c.targetduration!==0&&Ua(c,re,E),c.targetduration=Math.max(parseInt(X),1);break;case"VERSION":c.version!==null&&Ua(c,re,E),c.version=parseInt(X);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":c.live||Ua(c,re,E),c.live=!1;break;case"#":(X||oe)&&S.tagList.push(oe?[X,oe]:[X]);break;case"DISCONTINUITY":g++,S.tagList.push(["DIS"]);break;case"GAP":S.gap=!0,S.tagList.push([re]);break;case"BITRATE":S.tagList.push([re,X]),b=parseInt(X)*1e3,Ze(b)?S.bitrate=b:b=0;break;case"DATERANGE":{const Q=new Mn(X,c),G=new w3(Q,c.dateRanges[Q.ID],c.dateRangeTagCount);c.dateRangeTagCount++,G.isValid||c.skippedSegments?c.dateRanges[G.id]=G:ln.warn(`Ignoring invalid DATERANGE tag: "${X}"`),S.tagList.push(["EXT-X-DATERANGE",X]);break}case"DEFINE":{{const Q=new Mn(X,c);"IMPORT"in Q?Tce(c,Q,a):SP(c,Q,n)}break}case"DISCONTINUITY-SEQUENCE":c.startCC!==0?Ua(c,re,E):u.length>0&&OP(c,re,E),c.startCC=g=parseInt(X);break;case"KEY":{const Q=CP(X,n,c);if(Q.isSupported()){if(Q.method==="NONE"){U=void 0;break}U||(U={});const G=U[Q.keyFormat];G!=null&&G.matches(Q)||(G&&(U=fn({},U)),U[Q.keyFormat]=Q)}else ln.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${X}"`);break}case"START":c.startTimeOffset=LP(X);break;case"MAP":{const Q=new Mn(X,c);if(S.duration){const G=new Ub(i,l);PP(G,Q,r,U),h=G,S.initSegment=h,h.rawProgramDateTime&&!S.rawProgramDateTime&&(S.rawProgramDateTime=h.rawProgramDateTime)}else{const G=S.byteRangeEndOffset;if(G){const H=S.byteRangeStartOffset;I=`${G-H}@${H}`}else I=null;PP(S,Q,r,U),h=S,k=!0}h.cc=g;break}case"SERVER-CONTROL":{R&&Ua(c,re,E),R=new Mn(X),c.canBlockReload=R.bool("CAN-BLOCK-RELOAD"),c.canSkipUntil=R.optionalFloat("CAN-SKIP-UNTIL",0),c.canSkipDateRanges=c.canSkipUntil>0&&R.bool("CAN-SKIP-DATERANGES"),c.partHoldBack=R.optionalFloat("PART-HOLD-BACK",0),c.holdBack=R.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{c.partTarget&&Ua(c,re,E);const Q=new Mn(X);c.partTarget=Q.decimalFloatingPoint("PART-TARGET");break}case"PART":{let Q=c.partList;Q||(Q=c.partList=[]);const G=p>0?Q[Q.length-1]:void 0,H=p++,Y=new Mn(X,c),ie=new Tle(Y,S,l,H,G);Q.push(ie),S.duration+=ie.duration;break}case"PRELOAD-HINT":{const Q=new Mn(X,c);c.preloadHint=Q;break}case"RENDITION-REPORT":{const Q=new Mn(X,c);c.renditionReports=c.renditionReports||[],c.renditionReports.push(Q);break}default:ln.warn(`line parsed but not handled: ${E}`);break}}}v&&!v.relurl?(u.pop(),m-=v.duration,c.partList&&(c.fragmentHint=v)):c.partList&&(GE(S,v,d),S.cc=g,c.fragmentHint=S,U&&DP(S,U,c)),c.targetduration||(c.playlistParsingError=new Error("Missing Target Duration"));const M=u.length,z=u[0],Z=u[M-1];if(m+=c.skippedSegments*c.targetduration,m>0&&M&&Z){c.averagetargetduration=m/M;const W=Z.sn;c.endSN=W!=="initSegment"?W:0,c.live||(Z.endList=!0),O>0&&($ce(u,O),z&&d.unshift(z))}return c.fragmentHint&&(m+=c.fragmentHint.duration),c.totalduration=m,d.length&&c.dateRangeTagCount&&z&&L3(d,c),c.endCC=g,c}}function L3(t,e){let n=t.length;if(!n)if(e.hasProgramDateTime){const o=e.fragments[e.fragments.length-1];t.push(o),n++}else return;const r=t[n-1],i=e.live?1/0:e.totalduration,s=Object.keys(e.dateRanges);for(let o=s.length;o--;){const l=e.dateRanges[s[o]],c=l.startDate.getTime();l.tagAnchor=r.ref;for(let u=n;u--;){var a;if(((a=t[u])==null?void 0:a.sn)<e.startSN)break;const d=Fce(e,c,t,u,i);if(d!==-1){l.tagAnchor=e.fragments[d].ref;break}}}}function Fce(t,e,n,r,i){const s=n[r];if(s){const o=s.programDateTime;if(e>=o||r===0){var a;const l=(((a=n[r+1])==null?void 0:a.start)||i)-s.start;if(e<=o+l*1e3){const c=n[r].sn-t.startSN;if(c<0)return-1;const u=t.fragments;if(u.length>n.length){const h=(n[r+1]||u[u.length-1]).sn-t.startSN;for(let f=h;f>c;f--){const p=u[f].programDateTime;if(e>=p&&e<p+u[f].duration*1e3)return f}}return c}}}return-1}function CP(t,e,n){var r,i;const s=new Mn(t,n),a=(r=s.METHOD)!=null?r:"",o=s.URI,l=s.hexadecimalInteger("IV"),c=s.KEYFORMATVERSIONS,u=(i=s.KEYFORMAT)!=null?i:"identity";o&&s.IV&&!l&&ln.error(`Invalid IV: ${s.IV}`);const d=o?oa.resolve(o,e):"",h=(c||"1").split("/").map(Number).filter(Number.isFinite);return new yl(a,d,u,h,l,s.KEYID)}function LP(t){const n=new Mn(t).decimalFloatingPoint("TIME-OFFSET");return Ze(n)?n:null}function kP(t,e){let n=(t||"").split(/[ ,]+/).filter(r=>r);["video","audio","text"].forEach(r=>{const i=n.filter(s=>MA(s,r));i.length&&(e[`${r}Codec`]=i.map(s=>s.split("/")[0]).join(","),n=n.filter(s=>i.indexOf(s)===-1))}),e.unknownCodecs=n}function IP(t,e,n){const r=e[n];r&&(t[n]=r)}function $ce(t,e){let n=t[e];for(let r=e;r--;){const i=t[r];if(!i)return;i.programDateTime=n.programDateTime-i.duration*1e3,n=i}}function GE(t,e,n){t.rawProgramDateTime?n.push(t):e!=null&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function PP(t,e,n,r){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=n,t.sn="initSegment",r&&(t.levelkeys=r),t.initSegment=null}function DP(t,e,n){t.levelkeys=e;const{encryptedFragments:r}=n;(!r.length||r[r.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&r.push(t)}function Ua(t,e,n){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${n[0]})`)}function OP(t,e,n){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${n[0]})`)}function Gb(t,e){const n=e.startPTS;if(Ze(n)){let r=0,i;e.sn>t.sn?(r=n-t.start,i=t):(r=t.start-n,i=e),i.duration!==r&&i.setDuration(r)}else e.sn>t.sn?t.cc===e.cc&&t.minEndPTS?e.setStart(t.start+(t.minEndPTS-t.start)):e.setStart(t.start+t.duration):e.setStart(Math.max(t.start-e.duration,0))}function k3(t,e,n,r,i,s,a){r-n<=0&&(a.warn("Fragment should have a positive duration",e),r=n+e.duration,s=i+e.duration);let l=n,c=r;const u=e.startPTS,d=e.endPTS;if(Ze(u)){const b=Math.abs(u-n);t&&b>t.totalduration?a.warn(`media timestamps and playlist times differ by ${b}s for level ${e.level} ${t.url}`):Ze(e.deltaPTS)?e.deltaPTS=Math.max(b,e.deltaPTS):e.deltaPTS=b,l=Math.max(n,u),n=Math.min(n,u),i=e.startDTS!==void 0?Math.min(i,e.startDTS):i,c=Math.min(r,d),r=Math.max(r,d),s=e.endDTS!==void 0?Math.max(s,e.endDTS):s}const h=n-e.start;e.start!==0&&e.setStart(n),e.setDuration(r-e.start),e.startPTS=n,e.maxStartPTS=l,e.startDTS=i,e.endPTS=r,e.minEndPTS=c,e.endDTS=s;const f=e.sn;if(!t||f<t.startSN||f>t.endSN)return 0;let p;const m=f-t.startSN,g=t.fragments;for(g[m]=e,p=m;p>0;p--)Gb(g[p],g[p-1]);for(p=m;p<g.length-1;p++)Gb(g[p],g[p+1]);return t.fragmentHint&&Gb(g[g.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,h}function Vce(t,e,n){if(t===e)return;let r=null;const i=t.fragments;for(let u=i.length-1;u>=0;u--){const d=i[u].initSegment;if(d){r=d;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;let s;Kce(t,e,(u,d,h,f)=>{if((!e.startCC||e.skippedSegments)&&d.cc!==u.cc){const p=u.cc-d.cc;for(let m=h;m<f.length;m++)f[m].cc+=p;e.endCC=f[f.length-1].cc}Ze(u.startPTS)&&Ze(u.endPTS)&&(d.setStart(d.startPTS=u.startPTS),d.startDTS=u.startDTS,d.maxStartPTS=u.maxStartPTS,d.endPTS=u.endPTS,d.endDTS=u.endDTS,d.minEndPTS=u.minEndPTS,d.setDuration(u.endPTS-u.startPTS),d.duration&&(s=d),e.PTSKnown=e.alignedSliding=!0),u.hasStreams&&(d.elementaryStreams=u.elementaryStreams),d.loader=u.loader,u.hasStats&&(d.stats=u.stats),u.initSegment&&(d.initSegment=u.initSegment,r=u.initSegment)});const a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(r&&o.forEach(u=>{var d;u&&(!u.initSegment||u.initSegment.relurl===((d=r)==null?void 0:d.relurl))&&(u.initSegment=r)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(u=>!u),e.deltaUpdateFailed){n.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let u=e.skippedSegments;u--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=Gce(t.dateRanges,e,n));const u=t.fragments.filter(d=>d.rawProgramDateTime);if(t.hasProgramDateTime&&!e.hasProgramDateTime)for(let d=1;d<o.length;d++)o[d].programDateTime===null&&GE(o[d],o[d-1],u);L3(u,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;const u=D3(t,e.startSN-1);e.startCC=(l=u==null?void 0:u.cc)!=null?l:a[0].cc}Hce(t.partList,e.partList,(u,d)=>{d.elementaryStreams=u.elementaryStreams,d.stats=u.stats}),s?k3(e,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS,n):I3(t,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const c=e.advancedDateTime;if(e.advanced&&c){const u=e.edge;e.driftStart||(e.driftStartTime=c,e.driftStart=u),e.driftEndTime=c,e.driftEnd=u}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=t.requestScheduled)}function Gce(t,e,n){const{dateRanges:r,recentlyRemovedDateranges:i}=e,s=fn({},t);i&&i.forEach(l=>{delete s[l]});const o=Object.keys(s).length;return o?(Object.keys(r).forEach(l=>{const c=s[l],u=new w3(r[l].attr,c);u.isValid?(s[l]=u,c||(u.tagOrder+=o)):n.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${yn(r[l].attr)}"`)}),s):r}function Hce(t,e,n){if(t&&e){let r=0;for(let i=0,s=t.length;i<=s;i++){const a=t[i],o=e[i+r];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?n(a,o):r--}}}function Kce(t,e,n){const r=e.skippedSegments,i=Math.max(t.startSN,e.startSN)-e.startSN,s=(t.fragmentHint?1:0)+(r?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,a=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let c=i;c<=s;c++){const u=l[a+c];let d=o[c];if(r&&!d&&u&&(d=e.fragments[c]=u),u&&d){n(u,d,c,o);const h=u.relurl,f=d.relurl;if(h&&zce(h,f)){e.playlistParsingError=NP(`media sequence mismatch ${d.sn}:`,t,e,u,d);return}else if(u.cc!==d.cc){e.playlistParsingError=NP(`discontinuity sequence mismatch (${u.cc}!=${d.cc})`,t,e,u,d);return}}}}function NP(t,e,n,r,i){return new Error(`${t} ${i.url}
Playlist starting @${e.startSN}
${e.m3u8}

Playlist starting @${n.startSN}
${n.m3u8}`)}function I3(t,e,n=!0){const r=e.startSN+e.skippedSegments-t.startSN,i=t.fragments,s=r>=0;let a=0;if(s&&r<i.length)a=i[r].start;else if(s&&e.startSN===t.endSN+1)a=t.fragmentEnd;else if(s&&n)a=t.fragmentStart+r*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)a=t.fragmentStart;else return;HE(e,a)}function HE(t,e){if(e){const n=t.fragments;for(let r=t.skippedSegments;r<n.length;r++)n[r].addStart(e);t.fragmentHint&&t.fragmentHint.addStart(e)}}function P3(t,e=1/0){let n=1e3*t.targetduration;if(t.updated){const r=t.fragments;if(r.length&&n*4>e){const s=r[r.length-1].duration*1e3;s<n&&(n=s)}}else n/=2;return Math.round(n)}function D3(t,e,n){if(!t)return null;let r=t.fragments[e-t.startSN];return r||(r=t.fragmentHint,r&&r.sn===e)?r:e<t.startSN&&n&&n.sn===e?n:null}function MP(t,e,n){return t?O3(t.partList,e,n):null}function O3(t,e,n){if(t)for(let r=t.length;r--;){const i=t[r];if(i.index===n&&i.fragment.sn===e)return i}return null}function N3(t){t.forEach((e,n)=>{var r;(r=e.details)==null||r.fragments.forEach(i=>{i.level=n,i.initSegment&&(i.initSegment.level=n)})})}function zce(t,e){return t!==e&&e?BP(t)!==BP(e):!1}function BP(t){return t.replace(/\?[^?]*$/,"")}function Bf(t,e){for(let r=0,i=t.length;r<i;r++){var n;if(((n=t[r])==null?void 0:n.cc)===e)return t[r]}return null}function qce(t,e){return!!(t&&e.startCC<t.endCC&&e.endCC>t.startCC)}function UP(t,e){const n=t.start+e;t.startPTS=n,t.setStart(n),t.endPTS=n+t.duration}function M3(t,e){const n=e.fragments;for(let r=0,i=n.length;r<i;r++)UP(n[r],t);e.fragmentHint&&UP(e.fragmentHint,t),e.alignedSliding=!0}function Wce(t,e){t&&(B3(e,t),e.alignedSliding||A0(e,t),!e.alignedSliding&&!e.skippedSegments&&I3(t,e,!1))}function B3(t,e){if(!qce(e,t))return;const n=Math.min(e.endCC,t.endCC),r=Bf(e.fragments,n),i=Bf(t.fragments,n);if(!r||!i)return;ln.log(`Aligning playlist at start of dicontinuity sequence ${n}`);const s=r.start-i.start;M3(s,t)}function A0(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const n=t.fragments,r=e.fragments;if(!n.length||!r.length)return;let i,s;const a=Math.min(e.endCC,t.endCC);e.startCC<a&&t.startCC<a&&(i=Bf(r,a),s=Bf(n,a)),(!i||!s)&&(i=r[Math.floor(r.length/2)],s=Bf(n,i.cc)||n[Math.floor(n.length/2)]);const o=i.programDateTime,l=s.programDateTime;if(!o||!l)return;const c=(l-o)/1e3-(s.start-i.start);M3(c,t)}function ii(t,e,n){bi(t,e,n),t.addEventListener(e,n)}function bi(t,e,n){t.removeEventListener(e,n)}const Yce={toString:function(t){let e="";const n=t.length;for(let r=0;r<n;r++)e+=`[${t.start(r).toFixed(3)}-${t.end(r).toFixed(3)}]`;return e}},Oe={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class GA extends S3{constructor(e,n,r,i,s){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Oe.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:a,fragCurrent:o,media:l,mediaBuffer:c,state:u}=this,d=l?l.currentTime:0,h=Ct.bufferInfo(c||l,d,a.maxBufferHole),f=!h.len;if(this.log(`Media seeking to ${Ze(d)?d.toFixed(3):d}, state: ${u}, ${f?"out of":"in"} buffer`),this.state===Oe.ENDED)this.resetLoadingState();else if(o){const p=a.maxFragLookUpTolerance,m=o.start-p,g=o.start+o.duration+p;if(f||g<h.start||m>h.end){const b=d>g;(d<m||b)&&(b&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(l){this.fragmentTracker.removeFragmentsInRange(d,1/0,this.playlistType,!0);const p=this.lastCurrentTime;if(d>p&&(this.lastCurrentTime=d),!this.loadingParts){const m=Math.max(h.end,d),g=this.shouldLoadParts(this.getLevelDetails(),m);g&&(this.log(`LL-Part loading ON after seeking to ${d.toFixed(2)} with buffer @${m.toFixed(2)}`),this.loadingParts=g)}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${d} for seek without enough to start`),this.nextLoadPosition=d,f&&(this.startPosition=d)),f&&this.state===Oe.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=s,this.hls=e,this.fragmentLoader=new Ece(e.config),this.keyLoader=r,this.fragmentTracker=n,this.config=e.config,this.decrypter=new jA(e.config)}registerListeners(){const{hls:e}=this;e.on(j.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(j.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(j.MANIFEST_LOADING,this.onManifestLoading,this),e.on(j.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(j.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(j.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(j.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(j.MANIFEST_LOADING,this.onManifestLoading,this),e.off(j.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(j.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===Oe.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Oe.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:n}=this;return n===-1&&e?e:n}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,n){if(n.live||!this.media)return!1;const r=e.end||0,i=this.config.timelineOffset||0;if(r<=i)return!1;const s=e.buffered;this.config.maxBufferHole&&s&&s.length>1&&(e=Ct.bufferedInfo(s,e.start,0));const a=e.nextStart;if(a&&a>i&&a<n.edge||this.media.currentTime<e.start)return!1;const l=n.partList;if(l!=null&&l.length){const u=l[l.length-1];return Ct.isBuffered(this.media,u.start+u.duration/2)}const c=n.fragments[n.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(c)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var n;return((n=this.getLevelDetails())==null?void 0:n.appliedTimelineOffset)||e}return 0}onMediaAttached(e,n){const r=this.media=this.mediaBuffer=n.media;ii(r,"seeking",this.onMediaSeeking),ii(r,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===Oe.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(e,n){const r=!!n.transferMedia,i=this.media;if(i!==null){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),bi(i,"seeking",this.onMediaSeeking),bi(i,"ended",this.onMediaEnded),this.keyLoader&&!r&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,r){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,n){}onManifestLoaded(e,n){this.startTimeOffset=n.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=Oe.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,n,r){this.startFragRequested=!0,this._loadFragForPlayback(e,n,r)}_loadFragForPlayback(e,n,r){const i=s=>{const a=s.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${s.part?" part: "+s.part.index:""} of ${this.fragInfo(a,!1,s.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(a);return}a.stats.chunkCount++,this._handleFragmentLoadProgress(s)};this._doFragLoad(e,n,r,i).then(s=>{if(!s)return;const a=this.state,o=s.frag;if(this.fragContextChanged(o)){(a===Oe.FRAG_LOADING||!this.fragCurrent&&a===Oe.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=Oe.IDLE);return}"payload"in s&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(j.FRAG_LOADED,s)),this._handleFragmentLoadComplete(s)}).catch(s=>{this.state===Oe.STOPPED||this.state===Oe.ERROR||(this.warn(`Frag error: ${(s==null?void 0:s.message)||s}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var n;const{fragmentTracker:r}=this;if(r.getState(e)===pr.APPENDING){const s=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,s),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&r.removeFragment(e)}else((n=this.mediaBuffer)==null?void 0:n.buffered.length)===0?r.removeAllFragments():r.hasParts(e.type)&&(r.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),r.getState(e)===pr.PARTIAL&&r.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const n=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:n,part:null,stats:n.stats,id:n.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const n=e.details;return(n==null?void 0:n.live)&&n.type!=="EVENT"&&(this.levelLastLoaded!==e||n.expired)}flushMainBuffer(e,n,r=null){if(!(e-n))return;const i={startOffset:e,endOffset:n,type:r};this.hls.trigger(j.BUFFER_FLUSHING,i)}_loadInitSegment(e,n){this._doFragLoad(e,n).then(r=>{const i=r==null?void 0:r.frag;if(!i||this.fragContextChanged(i)||!this.levels)throw new Error("init load aborted");return r}).then(r=>{const{hls:i}=this,{frag:s,payload:a}=r,o=s.decryptdata;if(a&&a.byteLength>0&&o!=null&&o.key&&o.iv&&_d(o.method)){const l=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,$A(o.method)).catch(c=>{throw i.trigger(j.ERROR,{type:ct.MEDIA_ERROR,details:xe.FRAG_DECRYPT_ERROR,fatal:!1,error:c,reason:c.message,frag:s}),c}).then(c=>{const u=self.performance.now();return i.trigger(j.FRAG_DECRYPTED,{frag:s,payload:c,stats:{tstart:l,tdecrypt:u}}),r.payload=c,this.completeInitSegmentLoad(r)})}return this.completeInitSegmentLoad(r)}).catch(r=>{this.state===Oe.STOPPED||this.state===Oe.ERROR||(this.warn(r),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:n}=this;if(!n)throw new Error("init load aborted, missing levels");const r=e.frag.stats;this.state!==Oe.STOPPED&&(this.state=Oe.IDLE),e.frag.data=new Uint8Array(e.payload),r.parsing.start=r.buffering.start=self.performance.now(),r.parsing.end=r.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,n){var r,i;const s=e.tracks;if(s&&!n.encrypted&&((r=s.audio)!=null&&r.encrypted||(i=s.video)!=null&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(n)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?!1:(this.hls.trigger(j.ERROR,{type:ct.KEY_SYSTEM_ERROR,details:xe.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:n}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:n}=this;return!e||!n||e.sn!==n.sn||e.level!==n.level}fragBufferedComplete(e,n){const r=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${n?" part: "+n.index:""} of ${this.fragInfo(e,!1,n)} > buffer:${r?Yce.toString(Ct.getBuffered(r)):"(detached)"})`),Zn(e)){var i;if(e.type!==tt.SUBTITLE){const a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=Oe.IDLE;return}}const s=(i=this.levels)==null?void 0:i[e.level];s!=null&&s.fragmentError&&(this.log(`Resetting level fragment error count of ${s.fragmentError} on frag buffered`),s.fragmentError=0)}this.state=Oe.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:n}=this;if(!n)return;const{frag:r,part:i,partsLoaded:s}=e,a=!s||s.length===0||s.some(l=>!l),o=new FA(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!a);n.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,n,r=null,i){var s;this.fragCurrent=e;const a=n.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(e.encrypted&&!((s=e.decryptdata)!=null&&s.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=Oe.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(h=>{if(!this.fragContextChanged(h.frag))return this.hls.trigger(j.KEY_LOADED,h),this.state===Oe.KEY_LOADING&&(this.state=Oe.IDLE),h}),this.hls.trigger(j.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,a.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));const l=this.fragPrevious;if(Zn(e)&&(!l||e.sn!==l.sn)){const h=this.shouldLoadParts(n.details,e.end);h!==this.loadingParts&&(this.log(`LL-Part loading ${h?"ON":"OFF"} loading sn ${l==null?void 0:l.sn}->${e.sn}`),this.loadingParts=h)}if(r=Math.max(e.start,r||0),this.loadingParts&&Zn(e)){const h=a.partList;if(h&&i){r>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);const f=this.getNextPart(h,e,r);if(f>-1){const p=h[f];e=this.fragCurrent=p.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${p.index} (${f}/${h.length-1}) of ${this.fragInfo(e,!1,p)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=p.start+p.duration,this.state=Oe.FRAG_LOADING;let m;return o?m=o.then(g=>!g||this.fragContextChanged(g.frag)?null:this.doFragPartsLoad(e,p,n,i)).catch(g=>this.handleFragLoadError(g)):m=this.doFragPartsLoad(e,p,n,i).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(j.FRAG_LOADING,{frag:e,part:p,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):m}else if(!e.url||this.loadedEndOfParts(h,r))return Promise.resolve(null)}}if(Zn(e)&&this.loadingParts){var c;this.log(`LL-Part loading OFF after next part miss @${r.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(c=a.partList)==null?void 0:c.filter(h=>h.loaded).map(h=>`[${h.start}-${h.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${parseFloat(r.toFixed(3))}`),Ze(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Oe.FRAG_LOADING;const u=this.config.progressive&&e.type!==tt.SUBTITLE;let d;return u&&o?d=o.then(h=>!h||this.fragContextChanged(h.frag)?null:this.fragmentLoader.load(e,i)).catch(h=>this.handleFragLoadError(h)):d=Promise.all([this.fragmentLoader.load(e,u?i:void 0),o]).then(([h])=>(!u&&i&&i(h),h)).catch(h=>this.handleFragLoadError(h)),this.hls.trigger(j.FRAG_LOADING,{frag:e,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):d}doFragPartsLoad(e,n,r,i){return new Promise((s,a)=>{var o;const l=[],c=(o=r.details)==null?void 0:o.partList,u=d=>{this.fragmentLoader.loadPart(e,d,i).then(h=>{l[d.index]=h;const f=h.part;this.hls.trigger(j.FRAG_LOADED,h);const p=MP(r.details,e.sn,d.index+1)||O3(c,e.sn,d.index+1);if(p)u(p);else return s({frag:e,part:f,partsLoaded:l})}).catch(a)};u(n)})}handleFragLoadError(e){if("data"in e){const n=e.data;n.frag&&n.details===xe.INTERNAL_ABORTED?this.handleFragLoadAborted(n.frag,n.part):n.frag&&n.type===ct.KEY_SYSTEM_ERROR?(n.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(n.frag)):this.hls.trigger(j.ERROR,n)}else this.hls.trigger(j.ERROR,{type:ct.OTHER_ERROR,details:xe.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const n=this.getCurrentContext(e);if(!n||this.state!==Oe.PARSING){!this.fragCurrent&&this.state!==Oe.STOPPED&&this.state!==Oe.ERROR&&(this.state=Oe.IDLE);return}const{frag:r,part:i,level:s}=n,a=self.performance.now();r.stats.parsing.end=a,i&&(i.stats.parsing.end=a);const o=this.getLevelDetails(),c=o&&r.sn>o.endSN||this.shouldLoadParts(o,r.end);c!==this.loadingParts&&(this.log(`LL-Part loading ${c?"ON":"OFF"} after parsing segment ending @${r.end.toFixed(2)}`),this.loadingParts=c),this.updateLevelTiming(r,i,s,e.partial)}shouldLoadParts(e,n){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var r;const s=e.partList[0];if(s.fragment.type===tt.SUBTITLE)return!1;const a=s.end+(((r=e.fragmentHint)==null?void 0:r.duration)||0);if(n>=a){var i;if((this.hls.hasEnoughToStart?((i=this.media)==null?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>s.start-s.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:n,fragCurrent:r}=this,{level:i,sn:s,part:a}=e;if(!(n!=null&&n[i]))return this.warn(`Levels object was unset while buffering fragment ${s} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const o=n[i],l=o.details,c=a>-1?MP(l,s,a):null,u=c?c.fragment:D3(l,s,r);return u?(r&&r!==u&&(u.stats=r.stats),{frag:u,part:c,level:o}):null}bufferFragmentData(e,n,r,i,s){if(this.state!==Oe.PARSING)return;const{data1:a,data2:o}=e;let l=a;if(o&&(l=ys(a,o)),!l.length)return;const c=this.initPTS[n.cc],u=c?-c.baseTime/c.timescale:void 0,d={type:e.type,frag:n,part:r,chunkMeta:i,offset:u,parent:n.type,data:l};if(this.hls.trigger(j.BUFFER_APPENDING,d),e.dropped&&e.independent&&!r){if(s)return;this.flushBufferGap(n)}}flushBufferGap(e){const n=this.media;if(!n)return;if(!Ct.isBuffered(n,n.currentTime)){this.flushMainBuffer(0,e.start);return}const r=n.currentTime,i=Ct.bufferInfo(n,r,0),s=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,s*.25),o=Math.max(Math.min(e.start-a,i.end-a),r+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,n){var r;const i=this.getLoadPosition();if(!Ze(i))return null;const a=this.lastCurrentTime>i||(r=this.media)!=null&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,n,a)}getFwdBufferInfoAtPos(e,n,r,i){const s=Ct.bufferInfo(e,n,i);if(s.len===0&&s.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(n,r);if(a&&(s.nextStart<=a.end||a.gap)){const o=Math.max(Math.min(s.nextStart,a.end)-n,i);return Ct.bufferInfo(e,n,o)}}return s}getMaxBufferLength(e){const{config:n}=this;let r;return e?r=Math.max(8*n.maxBufferSize/e,n.maxBufferLength):r=n.maxBufferLength,Math.min(r,n.maxMaxBufferLength)}exceedsMaxBuffer(e,n,r){const i=e.nextStart;if(i&&r.start>i){const s=e.buffered;if(s){let a=e.len;const o=e.bufferedIndex;for(let l=s.length-1;l>o;l--)s[l].start<r.start&&(a+=s[l].end-s[l].start);return a>=n}}return!1}reduceMaxBufferLength(e,n){const r=this.config,i=Math.max(Math.min(e-n,r.maxBufferLength),n),s=Math.max(e-n*3,r.maxMaxBufferLength/2,i);return s>=i?(r.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0):!1}getAppendedFrag(e,n=tt.MAIN){const r=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,n):null;return r&&"fragment"in r?r.fragment:r}getNextFragment(e,n){const r=n.fragments,i=r.length;if(!i)return null;const{config:s}=this,a=n.fragmentStart,o=s.lowLatencyMode&&!!n.partList;let l=null;if(n.live){const d=s.initialLiveManifestSize;if(i<d)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${d})`),null;if(!n.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var c;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),l=this.getInitialLiveFragment(n);const h=this.config.startPosition,f=this.hls.startPosition,p=this.hls.liveSyncPosition,m=((c=l)==null?void 0:c.start)||0;let g,b;f!==-1&&f>=a?(g=f,b=f===h?"config":"next load start"):p!==null?(g=p,b="live edge"):(g=e,b="buffer pos"),g<m&&(g=m,b="live frag start"),g<a&&(g=a,b="playlist start"),(this.startPosition!=g||this.nextLoadPosition!=g)&&(this.log(`Setting startPosition to ${g.toFixed(3)} ${f===-1?"":`(from ${h}) `}based on ${b}. live edge: ${p} live frag start: ${m.toFixed(3)} playlist start: ${a.toFixed(3)} buffer pos: ${e}`),this.startPosition=this.nextLoadPosition=g)}}else e<=a&&(l=r[0]);if(!l){const d=this.loadingParts?n.partEnd:n.fragmentEnd;l=this.getFragmentAtPosition(e,d,n)}let u=this.filterReplacedPrimary(l,n);if(!u&&l){const d=l.sn-n.startSN;u=this.filterReplacedPrimary(r[d+1]||null,n)}return this.mapToInitFragWhenRequired(u)}isLoopLoading(e,n){if(this.nextLoadPosition<=n)return!1;const r=this.fragmentTracker.getState(e);return r===pr.OK||r===pr.PARTIAL&&!!e.gap}getNextFragmentLoopLoading(e,n,r,i,s){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,n),a&&!a.gap&&r.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,i,0);if(o!==null&&r.len+o.len>=s){const l=a.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(jP(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,n){if(!e)return e;if(jP(this.config)&&e.type!==tt.SUBTITLE){const r=this.hls.interstitialsManager,i=r==null?void 0:r.bufferingItem;if(i){const a=i.event;if(a){if(a.appendInPlace||Math.abs(e.start-i.start)>1||i.start===0)return null}else if(e.end<=i.start&&(n==null?void 0:n.live)===!1||e.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||e.start-i.end>1))return null}const s=r==null?void 0:r.playerQueue;if(s)for(let a=s.length;a--;){const o=s[a].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,n,r){let i=-1,s=!1,a=!0;for(let o=0,l=e.length;o<l;o++){const c=e[o];if(a=a&&!c.independent,i>-1&&r<c.start)break;const u=c.loaded;u?i=-1:(s||(c.independent||a)&&c.fragment===n)&&(c.fragment!==n&&this.warn(`Need buffer at ${r} but next unloaded part starts at ${c.start}`),i=o),s=u}return i}loadedEndOfParts(e,n){let r;for(let i=e.length;i--;){if(r=e[i],!r.loaded)return!1;if(n>r.start)return!0}return!1}getInitialLiveFragment(e){const n=e.fragments,r=this.fragPrevious;let i=null;if(r){if(e.hasProgramDateTime&&(i=dce(n,r.endProgramDateTime,this.config.maxFragLookUpTolerance),i&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${r.programDateTime}`)),!i){const s=r.sn+1;if(s>=e.startSN&&s<=e.endSN){const a=n[s-e.startSN];r.cc===a.cc&&(i=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=_3(e,r.cc,r.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const s=this.hls.liveSyncPosition;s!==null&&(i=this.getFragmentAtPosition(s,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,n,r){const{config:i}=this;let{fragPrevious:s}=this,{fragments:a,endSN:o}=r;const{fragmentHint:l}=r,{maxFragLookUpTolerance:c}=i,u=r.partList,d=!!(this.loadingParts&&u!=null&&u.length&&l);d&&!this.bitrateTest&&u[u.length-1].fragment.sn===l.sn&&(a=a.concat(l),o=l.sn);let h;if(e<n){var f;const m=e<this.lastCurrentTime||e>n-c||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:c;h=Gc(s,a,e,m)}else h=a[a.length-1];if(h){const p=h.sn-r.startSN,m=this.fragmentTracker.getState(h);if((m===pr.OK||m===pr.PARTIAL&&h.gap)&&(s=h),s&&h.sn===s.sn&&(!d||u[0].fragment.sn>h.sn||!r.live)&&h.level===s.level){const b=a[p+1];h.sn<o&&this.fragmentTracker.getState(b)!==pr.OK?h=b:h=null}}return h}alignPlaylists(e,n,r){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const s=e.fragmentStart,a=!n,o=e.alignedSliding&&Ze(s);if(a||!o&&!s){Wce(r,e);const l=e.fragmentStart;return this.log(`Live playlist sliding: ${l.toFixed(2)} start-sn: ${n?n.startSN:"na"}->${e.startSN} fragments: ${i}`),l}return s}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,n){let r=this.startPosition;r<n&&(r=-1);const i=this.timelineOffset;if(r===-1){const s=this.startTimeOffset!==null,a=s?this.startTimeOffset:e.startTimeOffset;a!==null&&Ze(a)?(r=n+a,a<0&&(r+=e.edge),r=Math.min(Math.max(n,r),n+e.totalduration),this.log(`Setting startPosition to ${r} for start time offset ${a} found in ${s?"multivariant":"media"} playlist`),this.startPosition=r):e.live?(r=this.hls.liveSyncPosition||n,this.log(`Setting startPosition to -1 to start at live edge ${r}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=r=0),this.lastCurrentTime=r+i}this.nextLoadPosition=r+i}getLoadPosition(){var e;const{media:n}=this;let r=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&n?r=n.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r}handleFragLoadAborted(e,n){this.transmuxer&&e.type===this.playlistType&&Zn(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${n?" part "+n.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==Oe.FRAG_LOADING_WAITING_RETRY)&&(this.state=Oe.IDLE)}onFragmentOrKeyLoadError(e,n){var r;if(n.chunkMeta&&!n.frag){const b=this.getCurrentContext(n.chunkMeta);b&&(n.frag=b.frag)}const i=n.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var s;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(s=this.fragCurrent)==null?void 0:s.url}`);return}const a=n.details===xe.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(i,!0);const o=n.errorAction;if(!o){this.state=Oe.ERROR;return}const{action:l,flags:c,retryCount:u=0,retryConfig:d}=o,h=!!d,f=h&&l===Pr.RetryRequest,p=h&&!o.resolved&&c===Li.MoveAllAlternatesMatchingHost,m=(r=this.hls.latestLevelDetails)==null?void 0:r.live;if(!f&&p&&Zn(i)&&!i.endList&&m&&!x3(n))this.resetFragmentErrors(e),this.treatAsGap(i),o.resolved=!0;else if((f||p)&&u<d.maxNumRetry){var g;const b=FE((g=n.response)==null?void 0:g.code),v=UA(d,u);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+v,this.state=Oe.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,b){this.log("Waiting for connection (offline)"),this.retryDate=1/0,n.reason="offline";return}this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${n.details}, retrying loading ${u+1}/${d.maxNumRetry} in ${v}ms`)}else if(d)if(this.resetFragmentErrors(e),u<d.maxNumRetry)!a&&l!==Pr.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${n.details} reached or exceeded max retry (${u})`);return}else l===Pr.SendAlternateToPenaltyBox?this.state=Oe.WAITING_LEVEL:this.state=Oe.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),n=this.retryDate,r=n===1/0;(!n||e>=n||r&&!FE(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Oe.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===Oe.PARSING||this.state===Oe.PARSED){const n=e.frag,r=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,r),s=i&&i.len>.5;s&&this.reduceMaxBufferLength(i.len,(n==null?void 0:n.duration)||10);const a=!s;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${r} buffer`),n&&(this.fragmentTracker.removeFragment(n),this.nextLoadPosition=n.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===tt.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Oe.STOPPED&&(this.state=Oe.IDLE)}afterBufferFlushed(e,n,r){if(!e)return;const i=Ct.getBuffered(e);this.fragmentTracker.detectEvictedFragments(n,i,r),this.state===Oe.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Oe.STOPPED&&(this.state=Oe.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,n=e?e.details:null;n!=null&&n.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(n,n.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,n,r,i){const s=r.details;if(!s){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,c)=>{const u=e.elementaryStreams[c];if(u){const d=u.endPTS-u.startPTS;if(d<=0)return this.warn(`Could not parse fragment ${e.sn} ${c} duration reliably (${d})`),l||!1;const h=i?0:k3(s,e,u.startPTS,u.endPTS,u.startDTS,u.endDTS,this);return this.hls.trigger(j.LEVEL_PTS_UPDATED,{details:s,level:r,drift:h,type:c,frag:e,start:u.startPTS,end:u.endPTS}),!0}return l},!1)){var o;const l=((o=this.transmuxer)==null?void 0:o.error)===null;if((r.fragmentError===0||l&&(r.fragmentError<2||e.endList))&&this.treatAsGap(e,r),l){const c=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(c.message),this.hls.trigger(j.ERROR,{type:ct.MEDIA_ERROR,details:xe.FRAG_PARSING_ERROR,fatal:!1,error:c,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${r.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Oe.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${n?" part: "+n.index:""} of ${this.fragInfo(e,!1,n)})`),this.hls.trigger(j.FRAG_PARSED,{frag:e,part:n})}playlistLabel(){return this.playlistType===tt.MAIN?"level":"track"}fragInfo(e,n=!0,r){var i,s;return`${this.playlistLabel()} ${e.level} (${r?"part":"frag"}:[${((i=n&&!r?e.startPTS:(r||e).start)!=null?i:NaN).toFixed(3)}-${((s=n&&!r?e.endPTS:(r||e).end)!=null?s:NaN).toFixed(3)}]${r&&e.type==="main"?"INDEPENDENT="+(r.independent?"YES":"NO"):""}`}treatAsGap(e,n){n&&n.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const n=this._state;n!==e&&(this._state=e,this.log(`${n}->${e}`))}get state(){return this._state}}function jP(t){return!!t.interstitialsController&&t.enableInterstitialPlayback!==!1}class U3{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:n}=this;let r;if(e.length)e.length===1?r=e[0]:r=Xce(e,n);else return new Uint8Array(0);return this.reset(),r}reset(){this.chunks.length=0,this.dataLength=0}}function Xce(t,e){const n=new Uint8Array(e);let r=0;for(let i=0;i<t.length;i++){const s=t[i];n.set(s,r),r+=s.length}return n}var Hb={exports:{}},FP;function Qce(){return FP||(FP=1,function(t){var e=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function i(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function s(l,c,u,d,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new i(u,d||l,h),p=n?n+c:c;return l._events[p]?l._events[p].fn?l._events[p]=[l._events[p],f]:l._events[p].push(f):(l._events[p]=f,l._eventsCount++),l}function a(l,c){--l._eventsCount===0?l._events=new r:delete l._events[c]}function o(){this._events=new r,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],u,d;if(this._eventsCount===0)return c;for(d in u=this._events)e.call(u,d)&&c.push(n?d.slice(1):d);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},o.prototype.listeners=function(c){var u=n?n+c:c,d=this._events[u];if(!d)return[];if(d.fn)return[d.fn];for(var h=0,f=d.length,p=new Array(f);h<f;h++)p[h]=d[h].fn;return p},o.prototype.listenerCount=function(c){var u=n?n+c:c,d=this._events[u];return d?d.fn?1:d.length:0},o.prototype.emit=function(c,u,d,h,f,p){var m=n?n+c:c;if(!this._events[m])return!1;var g=this._events[m],b=arguments.length,v,S;if(g.fn){switch(g.once&&this.removeListener(c,g.fn,void 0,!0),b){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,u),!0;case 3:return g.fn.call(g.context,u,d),!0;case 4:return g.fn.call(g.context,u,d,h),!0;case 5:return g.fn.call(g.context,u,d,h,f),!0;case 6:return g.fn.call(g.context,u,d,h,f,p),!0}for(S=1,v=new Array(b-1);S<b;S++)v[S-1]=arguments[S];g.fn.apply(g.context,v)}else{var E=g.length,L;for(S=0;S<E;S++)switch(g[S].once&&this.removeListener(c,g[S].fn,void 0,!0),b){case 1:g[S].fn.call(g[S].context);break;case 2:g[S].fn.call(g[S].context,u);break;case 3:g[S].fn.call(g[S].context,u,d);break;case 4:g[S].fn.call(g[S].context,u,d,h);break;default:if(!v)for(L=1,v=new Array(b-1);L<b;L++)v[L-1]=arguments[L];g[S].fn.apply(g[S].context,v)}}return!0},o.prototype.on=function(c,u,d){return s(this,c,u,d,!1)},o.prototype.once=function(c,u,d){return s(this,c,u,d,!0)},o.prototype.removeListener=function(c,u,d,h){var f=n?n+c:c;if(!this._events[f])return this;if(!u)return a(this,f),this;var p=this._events[f];if(p.fn)p.fn===u&&(!h||p.once)&&(!d||p.context===d)&&a(this,f);else{for(var m=0,g=[],b=p.length;m<b;m++)(p[m].fn!==u||h&&!p[m].once||d&&p[m].context!==d)&&g.push(p[m]);g.length?this._events[f]=g.length===1?g[0]:g:a(this,f)}return this},o.prototype.removeAllListeners=function(c){var u;return c?(u=n?n+c:c,this._events[u]&&a(this,u)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=n,o.EventEmitter=o,t.exports=o}(Hb)),Hb.exports}var Jce=Qce(),HA=Ele(Jce);const Ap="1.6.16",nh={};function Zce(){return typeof __HLS_WORKER_BUNDLE__=="function"}function eue(){const t=nh[Ap];if(t)return t.clientCount++,t;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),n=self.URL.createObjectURL(e),i={worker:new self.Worker(n),objectURL:n,clientCount:1};return nh[Ap]=i,i}function tue(t){const e=nh[t];if(e)return e.clientCount++,e;const n=new self.URL(t,self.location.href).href,i={worker:new self.Worker(n),scriptURL:n,clientCount:1};return nh[t]=i,i}function nue(t){const e=nh[t||Ap];if(e&&e.clientCount--===1){const{worker:r,objectURL:i}=e;delete nh[t||Ap],i&&self.URL.revokeObjectURL(i),r.terminate()}}function j3(t,e){return e+10<=t.length&&t[e]===51&&t[e+1]===68&&t[e+2]===73&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function KA(t,e){return e+10<=t.length&&t[e]===73&&t[e+1]===68&&t[e+2]===51&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function Pv(t,e){let n=0;return n=(t[e]&127)<<21,n|=(t[e+1]&127)<<14,n|=(t[e+2]&127)<<7,n|=t[e+3]&127,n}function Rp(t,e){const n=e;let r=0;for(;KA(t,e);){r+=10;const i=Pv(t,e+6);r+=i,j3(t,e+10)&&(r+=10),e+=r}if(r>0)return t.subarray(n,n+r)}function rue(t,e,n,r){const i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],s=e[n+2],a=s>>2&15;if(a>12){const f=new Error(`invalid ADTS sampling index:${a}`);t.emit(j.ERROR,j.ERROR,{type:ct.MEDIA_ERROR,details:xe.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}const o=(s>>6&3)+1,l=e[n+3]>>6&3|(s&1)<<2,c="mp4a.40."+o,u=i[a];let d=a;(o===5||o===29)&&(d-=3);const h=[o<<3|(d&14)>>1,(d&1)<<7|l<<3];return ln.log(`manifest codec:${r}, parsed codec:${c}, channels:${l}, rate:${u} (ADTS object type:${o} sampling index:${a})`),{config:h,samplerate:u,channelCount:l,codec:c,parsedCodec:c,manifestCodec:r}}function F3(t,e){return t[e]===255&&(t[e+1]&246)===240}function $3(t,e){return t[e+1]&1?7:9}function zA(t,e){return(t[e+3]&3)<<11|t[e+4]<<3|(t[e+5]&224)>>>5}function iue(t,e){return e+5<t.length}function R0(t,e){return e+1<t.length&&F3(t,e)}function sue(t,e){return iue(t,e)&&F3(t,e)&&zA(t,e)<=t.length-e}function aue(t,e){if(R0(t,e)){const n=$3(t,e);if(e+n>=t.length)return!1;const r=zA(t,e);if(r<=n)return!1;const i=e+r;return i===t.length||R0(t,i)}return!1}function V3(t,e,n,r,i){if(!t.samplerate){const s=rue(e,n,r,i);if(!s)return;fn(t,s)}}function G3(t){return 1024*9e4/t}function oue(t,e){const n=$3(t,e);if(e+n<=t.length){const r=zA(t,e)-n;if(r>0)return{headerLength:n,frameLength:r}}}function H3(t,e,n,r,i){const s=G3(t.samplerate),a=r+i*s,o=oue(e,n);let l;if(o){const{frameLength:d,headerLength:h}=o,f=h+d,p=Math.max(0,n+f-e.length);p?(l=new Uint8Array(f-h),l.set(e.subarray(n+h,e.length),0)):l=e.subarray(n+h,n+f);const m={unit:l,pts:a};return p||t.samples.push(m),{sample:m,length:f,missing:p}}const c=e.length-n;return l=new Uint8Array(c),l.set(e.subarray(n,e.length),0),{sample:{unit:l,pts:a},length:c,missing:-1}}function lue(t,e){return KA(t,e)&&Pv(t,e+6)+10<=t.length-e}function cue(t){return t instanceof ArrayBuffer?t:t.byteOffset==0&&t.byteLength==t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}function Kb(t,e=0,n=1/0){return uue(t,e,n,Uint8Array)}function uue(t,e,n,r){const i=due(t);let s=1;"BYTES_PER_ELEMENT"in r&&(s=r.BYTES_PER_ELEMENT);const a=hue(t)?t.byteOffset:0,o=(a+t.byteLength)/s,l=(a+e)/s,c=Math.floor(Math.max(0,Math.min(l,o))),u=Math.floor(Math.min(c+Math.max(n,0),o));return new r(i,c,u-c)}function due(t){return t instanceof ArrayBuffer?t:t.buffer}function hue(t){return t&&t.buffer instanceof ArrayBuffer&&t.byteLength!==void 0&&t.byteOffset!==void 0}function fue(t){const e={key:t.type,description:"",data:"",mimeType:null,pictureType:null},n=3;if(t.size<2)return;if(t.data[0]!==n){console.log("Ignore frame with unrecognized character encoding");return}const r=t.data.subarray(1).indexOf(0);if(r===-1)return;const i=Ki(Kb(t.data,1,r)),s=t.data[2+r],a=t.data.subarray(3+r).indexOf(0);if(a===-1)return;const o=Ki(Kb(t.data,3+r,a));let l;return i==="-->"?l=Ki(Kb(t.data,4+r+a)):l=cue(t.data.subarray(4+r+a)),e.mimeType=i,e.pictureType=s,e.description=o,e.data=l,e}function pue(t){if(t.size<2)return;const e=Ki(t.data,!0),n=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:n.buffer}}function mue(t){if(t.size<2)return;if(t.type==="TXXX"){let n=1;const r=Ki(t.data.subarray(n),!0);n+=r.length+1;const i=Ki(t.data.subarray(n));return{key:t.type,info:r,data:i}}const e=Ki(t.data.subarray(1));return{key:t.type,info:"",data:e}}function gue(t){if(t.type==="WXXX"){if(t.size<2)return;let n=1;const r=Ki(t.data.subarray(n),!0);n+=r.length+1;const i=Ki(t.data.subarray(n));return{key:t.type,info:r,data:i}}const e=Ki(t.data);return{key:t.type,info:"",data:e}}function yue(t){return t.type==="PRIV"?pue(t):t.type[0]==="W"?gue(t):t.type==="APIC"?fue(t):mue(t)}function vue(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),n=Pv(t,4),r=10;return{type:e,size:n,data:t.subarray(r,r+n)}}const Sg=10,_ue=10;function K3(t){let e=0;const n=[];for(;KA(t,e);){const r=Pv(t,e+6);t[e+5]>>6&1&&(e+=Sg),e+=Sg;const i=e+r;for(;e+_ue<i;){const s=vue(t.subarray(e)),a=yue(s);a&&n.push(a),e+=s.size+Sg}j3(t,e)&&(e+=Sg)}return n}function z3(t){return t&&t.key==="PRIV"&&t.info==="com.apple.streaming.transportStreamTimestamp"}function bue(t){if(t.data.byteLength===8){const e=new Uint8Array(t.data),n=e[3]&1;let r=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return r/=45,n&&(r+=4772185884e-2),Math.round(r)}}function qA(t){const e=K3(t);for(let n=0;n<e.length;n++){const r=e[n];if(z3(r))return bue(r)}}let Ni=function(t){return t.audioId3="org.id3",t.dateRange="com.apple.quicktime.HLS",t.emsg="https://aomedia.org/emsg/ID3",t.misbklv="urn:misb:KLV:bin:1910.1",t}({});function Zs(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class WA{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,n,r,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,n){return!1}appendFrame(e,n,r){}demux(e,n){this.cachedData&&(e=ys(this.cachedData,e),this.cachedData=null);let r=Rp(e,0),i=r?r.length:0,s;const a=this._audioTrack,o=this._id3Track,l=r?qA(r):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&Ze(l))&&(this.basePTS=xue(l,n,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),r&&r.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Ni.audioId3,duration:Number.POSITIVE_INFINITY});i<c;){if(this.canParse(e,i)){const u=this.appendFrame(a,e,i);u?(this.frameIndex++,this.lastPTS=u.sample.pts,i+=u.length,s=i):i=c}else lue(e,i)?(r=Rp(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Ni.audioId3,duration:Number.POSITIVE_INFINITY}),i+=r.length,s=i):i++;if(i===c&&s!==c){const u=e.slice(s);this.cachedData?this.cachedData=ys(this.cachedData,u):this.cachedData=u}}return{audioTrack:a,videoTrack:Zs(),id3Track:o,textTrack:Zs()}}demuxSampleAes(e,n,r){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const n=this.cachedData;return n&&(this.cachedData=null,this.demux(n,0)),{audioTrack:this._audioTrack,videoTrack:Zs(),id3Track:this._id3Track,textTrack:Zs()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const xue=(t,e,n)=>{if(Ze(t))return t*90;const r=n?n.baseTime*9e4/n.timescale:0;return e*9e4+r};let Eg=null;const Sue=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],Eue=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],wue=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Tue=[0,1,1,4];function q3(t,e,n,r,i){if(n+24>e.length)return;const s=W3(e,n);if(s&&n+s.frameLength<=e.length){const a=s.samplesPerFrame*9e4/s.sampleRate,o=r+i*a,l={unit:e.subarray(n,n+s.frameLength),pts:o,dts:o};return t.config=[],t.channelCount=s.channelCount,t.samplerate=s.sampleRate,t.samples.push(l),{sample:l,length:s.frameLength,missing:0}}}function W3(t,e){const n=t[e+1]>>3&3,r=t[e+1]>>1&3,i=t[e+2]>>4&15,s=t[e+2]>>2&3;if(n!==1&&i!==0&&i!==15&&s!==3){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=n===3?3-r:r===3?3:4,c=Sue[l*14+i-1]*1e3,d=Eue[(n===3?0:n===2?1:2)*3+s],h=o===3?1:2,f=wue[n][r],p=Tue[r],m=f*8*p,g=Math.floor(f*c/d+a)*p;if(Eg===null){const S=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Eg=S?parseInt(S[1]):0}return!!Eg&&Eg<=87&&r===2&&c>=224e3&&o===0&&(t[e+3]=t[e+3]|128),{sampleRate:d,channelCount:h,frameLength:g,samplesPerFrame:m}}}function YA(t,e){return t[e]===255&&(t[e+1]&224)===224&&(t[e+1]&6)!==0}function Y3(t,e){return e+1<t.length&&YA(t,e)}function Aue(t,e){return YA(t,e)&&4<=t.length-e}function X3(t,e){if(e+1<t.length&&YA(t,e)){const r=W3(t,e);let i=4;r!=null&&r.frameLength&&(i=r.frameLength);const s=e+i;return s===t.length||Y3(t,s)}return!1}class Rue extends WA{constructor(e,n){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=n}resetInitSegment(e,n,r,i){super.resetInitSegment(e,n,r,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:n,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,n){if(!e)return!1;const r=Rp(e,0);let i=(r==null?void 0:r.length)||0;if(X3(e,i))return!1;for(let s=e.length;i<s;i++)if(aue(e,i))return n.log("ADTS sync word found !"),!0;return!1}canParse(e,n){return sue(e,n)}appendFrame(e,n,r){V3(e,this.observer,n,r,e.manifestCodec);const i=H3(e,n,r,this.basePTS,this.frameIndex);if(i&&i.missing===0)return i}}const Q3=(t,e)=>{let n=0,r=5;e+=r;const i=new Uint32Array(1),s=new Uint32Array(1),a=new Uint8Array(1);for(;r>0;){a[0]=t[e];const o=Math.min(r,8),l=8-o;s[0]=4278190080>>>24+l<<l,i[0]=(a[0]&s[0])>>l,n=n?n<<o|i[0]:i[0],e+=1,r-=o}return n};class Cue extends WA{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,n,r,i){super.resetInitSegment(e,n,r,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:n,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,n){return n+64<e.length}appendFrame(e,n,r){const i=J3(e,n,r,this.basePTS,this.frameIndex);if(i!==-1)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}static probe(e){if(!e)return!1;const n=Rp(e,0);if(!n)return!1;const r=n.length;return e[r]===11&&e[r+1]===119&&qA(n)!==void 0&&Q3(e,r)<16}}function J3(t,e,n,r,i){if(n+8>e.length||e[n]!==11||e[n+1]!==119)return-1;const s=e[n+4]>>6;if(s>=3)return-1;const o=[48e3,44100,32e3][s],l=e[n+4]&63,u=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+s]*2;if(n+u>e.length)return-1;const d=e[n+6]>>5;let h=0;d===2?h+=2:(d&1&&d!==1&&(h+=2),d&4&&(h+=2));const f=(e[n+6]<<8|e[n+7])>>12-h&1,m=[2,1,2,3,3,4,4,5][d]+f,g=e[n+5]>>3,b=e[n+5]&7,v=new Uint8Array([s<<6|g<<1|b>>2,(b&3)<<6|d<<3|f<<2|l>>4,l<<4&224]),S=1536/o*9e4,E=r+i*S,L=e.subarray(n,n+u);return t.config=v,t.channelCount=m,t.samplerate=o,t.samples.push({unit:L,pts:E}),u}class Lue extends WA{resetInitSegment(e,n,r,i){super.resetInitSegment(e,n,r,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:n,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const n=Rp(e,0);let r=(n==null?void 0:n.length)||0;if(n&&e[r]===11&&e[r+1]===119&&qA(n)!==void 0&&Q3(e,r)<=16)return!1;for(let i=e.length;r<i;r++)if(X3(e,r))return ln.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,n){return Aue(e,n)}appendFrame(e,n,r){if(this.basePTS!==null)return q3(e,n,r,this.basePTS,this.frameIndex)}}const kue=/\/emsg[-/]ID3/i;class Iue{constructor(e,n){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=n}resetTimeStamp(){}resetInitSegment(e,n,r,i){const s=this.videoTrack=Zs("video",1),a=this.audioTrack=Zs("audio",1),o=this.txtTrack=Zs("text",1);if(this.id3Track=Zs("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=l3(e);if(l.video){const{id:c,timescale:u,codec:d,supplemental:h}=l.video;s.id=c,s.timescale=o.timescale=u,s.codec=d,s.supplemental=h}if(l.audio){const{id:c,timescale:u,codec:d}=l.audio;a.id=c,a.timescale=u,a.codec=d}o.id=s3.text,s.sampleDuration=0,s.duration=a.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return Cle(e)}demux(e,n){this.timeOffset=n;let r=e;const i=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=ys(this.remainderData,e));const o=Nle(r);this.remainderData=o.remainder,i.samples=o.valid||new Uint8Array}else i.samples=r;const a=this.extractID3Track(i,n);return s.samples=iP(n,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,n=this.videoTrack,r=this.txtTrack;n.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(n,this.timeOffset);return r.samples=iP(e,n),{videoTrack:n,audioTrack:Zs(),id3Track:i,textTrack:Zs()}}extractID3Track(e,n){const r=this.id3Track;if(e.samples.length){const i=Bt(e.samples,["emsg"]);i&&i.forEach(s=>{const a=Ble(s);if(kue.test(a.schemeIdUri)){const o=$P(a,n);let l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const c=a.payload;r.samples.push({data:c,len:c.byteLength,dts:o,pts:o,type:Ni.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=$P(a,n);r.samples.push({data:a.payload,len:a.payload.byteLength,dts:o,pts:o,type:Ni.misbklv,duration:Number.POSITIVE_INFINITY})}})}return r}demuxSampleAes(e,n,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function $P(t,e){return Ze(t.presentationTime)?t.presentationTime/t.timeScale:e+t.presentationTimeDelta/t.timeScale}class Pue{constructor(e,n,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new jA(n,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Ll.cbc)}decryptAacSample(e,n,r){const i=e[n].unit;if(i.length<=16)return;const s=i.subarray(16,i.length-i.length%16),a=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(a).then(o=>{const l=new Uint8Array(o);i.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,n+1,r)}).catch(r)}decryptAacSamples(e,n,r){for(;;n++){if(n>=e.length){r();return}if(!(e[n].unit.length<32)&&(this.decryptAacSample(e,n,r),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const n=Math.floor((e.length-48)/160)*16+16,r=new Int8Array(n);let i=0;for(let s=32;s<e.length-16;s+=160,i+=16)r.set(e.subarray(s,s+16),i);return r}getAvcDecryptedUnit(e,n){const r=new Uint8Array(n);let i=0;for(let s=32;s<e.length-16;s+=160,i+=16)e.set(r.subarray(i,i+16),s);return e}decryptAvcSample(e,n,r,i,s){const a=d3(s.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{s.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,n,r+1,i)}).catch(i)}decryptAvcSamples(e,n,r,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;n++,r=0){if(n>=e.length){i();return}const s=e[n].units;for(;!(r>=s.length);r++){const a=s[r];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,n,r,i,a),!this.decrypter.isSync()))return}}}}class Z3{constructor(){this.VideoSample=null}createVideoSample(e,n,r){return{key:e,frame:!1,pts:n,dts:r,units:[],length:0}}getLastNalUnit(e){var n;let r=this.VideoSample,i;if((!r||r.units.length===0)&&(r=e[e.length-1]),(n=r)!=null&&n.units){const s=r.units;i=s[s.length-1]}return i}pushAccessUnit(e,n){if(e.units.length&&e.frame){if(e.pts===void 0){const r=n.samples,i=r.length;if(i){const s=r[i-1];e.pts=s.pts,e.dts=s.dts}else{n.dropped++;return}}n.samples.push(e)}}parseNALu(e,n,r){const i=n.byteLength;let s=e.naluState||0;const a=s,o=[];let l=0,c,u,d,h=-1,f=0;for(s===-1&&(h=0,f=this.getNALuType(n,0),s=0,l=1);l<i;){if(c=n[l++],!s){s=c?0:1;continue}if(s===1){s=c?0:2;continue}if(!c)s=3;else if(c===1){if(u=l-s-1,h>=0){const p={data:n.subarray(h,u),type:f};o.push(p)}else{const p=this.getLastNalUnit(e.samples);p&&(a&&l<=4-a&&p.state&&(p.data=p.data.subarray(0,p.data.byteLength-a)),u>0&&(p.data=ys(p.data,n.subarray(0,u)),p.state=0))}l<i?(d=this.getNALuType(n,l),h=l,f=d,s=0):s=-1}else s=0}if(h>=0&&s>=0){const p={data:n.subarray(h,i),type:f,state:s};o.push(p)}if(o.length===0){const p=this.getLastNalUnit(e.samples);p&&(p.data=ys(p.data,n))}return e.naluState=s,o}}class Uf{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,n=this.bytesAvailable,r=e.byteLength-n,i=new Uint8Array(4),s=Math.min(4,n);if(s===0)throw new Error("no bytes available");i.set(e.subarray(r,r+s)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=s*8,this.bytesAvailable-=s}skipBits(e){let n;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,n=e>>3,e-=n<<3,this.bytesAvailable-=n,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let n=Math.min(this.bitsAvailable,e);const r=this.word>>>32-n;if(e>32&&ln.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=n,this.bitsAvailable>0)this.word<<=n;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return n=e-n,n>0&&this.bitsAvailable?r<<n|this.readBits(n):r}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class Due extends Z3{parsePES(e,n,r,i){const s=this.parseNALu(e,r.data,i);let a=this.VideoSample,o,l=!1;r.data=null,a&&s.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),s.forEach(c=>{var u,d;switch(c.type){case 1:{let m=!1;o=!0;const g=c.data;if(l&&g.length>4){const b=this.readSliceType(g);(b===2||b===4||b===7||b===9)&&(m=!0)}if(m){var h;(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),a.frame=!0,a.key=m;break}case 5:o=!0,(u=a)!=null&&u.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),a.key=!0,a.frame=!0;break;case 6:{o=!0,NA(c.data,1,r.pts,n.samples);break}case 7:{var f,p;o=!0,l=!0;const m=c.data,g=this.readSPS(m);if(!e.sps||e.width!==g.width||e.height!==g.height||((f=e.pixelRatio)==null?void 0:f[0])!==g.pixelRatio[0]||((p=e.pixelRatio)==null?void 0:p[1])!==g.pixelRatio[1]){e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.sps=[m];const b=m.subarray(1,4);let v="avc1.";for(let S=0;S<3;S++){let E=b[S].toString(16);E.length<2&&(E="0"+E),v+=E}e.codec=v}break}case 8:o=!0,e.pps=[c.data];break;case 9:o=!0,e.audFound=!0,(d=a)!=null&&d.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;case 12:o=!0;break;default:o=!1;break}a&&o&&a.units.push(c)}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,n){return e[n]&31}readSliceType(e){const n=new Uf(e);return n.readUByte(),n.readUEG(),n.readUEG()}skipScalingList(e,n){let r=8,i=8,s;for(let a=0;a<e;a++)i!==0&&(s=n.readEG(),i=(r+s+256)%256),r=i===0?r:i}readSPS(e){const n=new Uf(e);let r=0,i=0,s=0,a=0,o,l,c;const u=n.readUByte.bind(n),d=n.readBits.bind(n),h=n.readUEG.bind(n),f=n.readBoolean.bind(n),p=n.skipBits.bind(n),m=n.skipEG.bind(n),g=n.skipUEG.bind(n),b=this.skipScalingList.bind(this);u();const v=u();if(d(5),p(3),u(),g(),v===100||v===110||v===122||v===244||v===44||v===83||v===86||v===118||v===128){const k=h();if(k===3&&p(1),g(),g(),p(1),f())for(l=k!==3?8:12,c=0;c<l;c++)f()&&(c<6?b(16,n):b(64,n))}g();const S=h();if(S===0)h();else if(S===1)for(p(1),m(),m(),o=h(),c=0;c<o;c++)m();g(),p(1);const E=h(),L=h(),U=d(1);U===0&&p(1),p(1),f()&&(r=h(),i=h(),s=h(),a=h());let O=[1,1];if(f()&&f())switch(u()){case 1:O=[1,1];break;case 2:O=[12,11];break;case 3:O=[10,11];break;case 4:O=[16,11];break;case 5:O=[40,33];break;case 6:O=[24,11];break;case 7:O=[20,11];break;case 8:O=[32,11];break;case 9:O=[80,33];break;case 10:O=[18,11];break;case 11:O=[15,11];break;case 12:O=[64,33];break;case 13:O=[160,99];break;case 14:O=[4,3];break;case 15:O=[3,2];break;case 16:O=[2,1];break;case 255:{O=[u()<<8|u(),u()<<8|u()];break}}return{width:Math.ceil((E+1)*16-r*2-i*2),height:(2-U)*(L+1)*16-(U?2:4)*(s+a),pixelRatio:O}}}class Oue extends Z3{constructor(...e){super(...e),this.initVPS=null}parsePES(e,n,r,i){const s=this.parseNALu(e,r.data,i);let a=this.VideoSample,o,l=!1;r.data=null,a&&s.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),s.forEach(c=>{var u,d;switch(c.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,l){var h;(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(u=a)!=null&&u.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),a.key=!0,a.frame=!0;break;case 39:o=!0,NA(c.data,2,r.pts,n.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=fn(e.params,this.readVPS(c.data)),this.initVPS=c.data),e.vps=[c.data];break;case 33:if(o=!0,l=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],c.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const f=this.readSPS(c.data);e.width=f.width,e.height=f.height,e.pixelRatio=f.pixelRatio,e.codec=f.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const p in f.params)e.params[p]=f.params[p]}this.pushParameterSet(e.sps,c.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),a.key=!0;break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const f=this.readPPS(c.data);for(const p in f)e.params[p]=f[p]}this.pushParameterSet(e.pps,c.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(d=a)!=null&&d.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;default:o=!1;break}a&&o&&a.units.push(c)}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,n,r){(r&&r[0]===this.initVPS||!r&&!e.length)&&e.push(n)}getNALuType(e,n){return(e[n]&126)>>>1}ebsp2rbsp(e){const n=new Uint8Array(e.byteLength);let r=0;for(let i=0;i<e.byteLength;i++)i>=2&&e[i]===3&&e[i-1]===0&&e[i-2]===0||(n[r]=e[i],r++);return new Uint8Array(n.buffer,0,r)}pushAccessUnit(e,n){super.pushAccessUnit(e,n),this.initVPS&&(this.initVPS=null)}readVPS(e){const n=new Uf(e);n.readUByte(),n.readUByte(),n.readBits(4),n.skipBits(2),n.readBits(6);const r=n.readBits(3),i=n.readBoolean();return{numTemporalLayers:r+1,temporalIdNested:i}}readSPS(e){const n=new Uf(this.ebsp2rbsp(e));n.readUByte(),n.readUByte(),n.readBits(4);const r=n.readBits(3);n.readBoolean();const i=n.readBits(2),s=n.readBoolean(),a=n.readBits(5),o=n.readUByte(),l=n.readUByte(),c=n.readUByte(),u=n.readUByte(),d=n.readUByte(),h=n.readUByte(),f=n.readUByte(),p=n.readUByte(),m=n.readUByte(),g=n.readUByte(),b=n.readUByte(),v=[],S=[];for(let lt=0;lt<r;lt++)v.push(n.readBoolean()),S.push(n.readBoolean());if(r>0)for(let lt=r;lt<8;lt++)n.readBits(2);for(let lt=0;lt<r;lt++)v[lt]&&(n.readUByte(),n.readUByte(),n.readUByte(),n.readUByte(),n.readUByte(),n.readUByte(),n.readUByte(),n.readUByte(),n.readUByte(),n.readUByte(),n.readUByte()),S[lt]&&n.readUByte();n.readUEG();const E=n.readUEG();E==3&&n.skipBits(1);const L=n.readUEG(),U=n.readUEG(),O=n.readBoolean();let k=0,I=0,R=0,M=0;O&&(k+=n.readUEG(),I+=n.readUEG(),R+=n.readUEG(),M+=n.readUEG());const z=n.readUEG(),Z=n.readUEG(),W=n.readUEG(),re=n.readBoolean();for(let lt=re?0:r;lt<=r;lt++)n.skipUEG(),n.skipUEG(),n.skipUEG();if(n.skipUEG(),n.skipUEG(),n.skipUEG(),n.skipUEG(),n.skipUEG(),n.skipUEG(),n.readBoolean()&&n.readBoolean())for(let un=0;un<4;un++)for(let Sn=0;Sn<(un===3?2:6);Sn++)if(!n.readBoolean())n.readUEG();else{const Un=Math.min(64,1<<4+(un<<1));un>1&&n.readEG();for(let En=0;En<Un;En++)n.readEG()}n.readBoolean(),n.readBoolean(),n.readBoolean()&&(n.readUByte(),n.skipUEG(),n.skipUEG(),n.readBoolean());const Q=n.readUEG();let G=0;for(let lt=0;lt<Q;lt++){let un=!1;if(lt!==0&&(un=n.readBoolean()),un){lt===Q&&n.readUEG(),n.readBoolean(),n.readUEG();let Sn=0;for(let tr=0;tr<=G;tr++){const Un=n.readBoolean();let En=!1;Un||(En=n.readBoolean()),(Un||En)&&Sn++}G=Sn}else{const Sn=n.readUEG(),tr=n.readUEG();G=Sn+tr;for(let Un=0;Un<Sn;Un++)n.readUEG(),n.readBoolean();for(let Un=0;Un<tr;Un++)n.readUEG(),n.readBoolean()}}if(n.readBoolean()){const lt=n.readUEG();for(let un=0;un<lt;un++){for(let Sn=0;Sn<W+4;Sn++)n.readBits(1);n.readBits(1)}}let Y=0,ie=1,Ce=1,Le=!0,ke=1,Ne=0;n.readBoolean(),n.readBoolean();let ye=!1;if(n.readBoolean()){if(n.readBoolean()){const Yr=n.readUByte(),vr=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],_s=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];Yr>0&&Yr<16?(ie=vr[Yr-1],Ce=_s[Yr-1]):Yr===255&&(ie=n.readBits(16),Ce=n.readBits(16))}if(n.readBoolean()&&n.readBoolean(),n.readBoolean()&&(n.readBits(3),n.readBoolean(),n.readBoolean()&&(n.readUByte(),n.readUByte(),n.readUByte())),n.readBoolean()&&(n.readUEG(),n.readUEG()),n.readBoolean(),n.readBoolean(),n.readBoolean(),ye=n.readBoolean(),ye&&(n.skipUEG(),n.skipUEG(),n.skipUEG(),n.skipUEG()),n.readBoolean()&&(ke=n.readBits(32),Ne=n.readBits(32),n.readBoolean()&&n.readUEG(),n.readBoolean())){const _s=n.readBoolean(),Wi=n.readBoolean();let Xt=!1;(_s||Wi)&&(Xt=n.readBoolean(),Xt&&(n.readUByte(),n.readBits(5),n.readBoolean(),n.readBits(5)),n.readBits(4),n.readBits(4),Xt&&n.readBits(4),n.readBits(5),n.readBits(5),n.readBits(5));for(let or=0;or<=r;or++){Le=n.readBoolean();const Ta=Le||n.readBoolean();let Yi=!1;Ta?n.readEG():Yi=n.readBoolean();const Ei=Yi?1:n.readUEG()+1;if(_s)for(let li=0;li<Ei;li++)n.readUEG(),n.readUEG(),Xt&&(n.readUEG(),n.readUEG()),n.skipBits(1);if(Wi)for(let li=0;li<Ei;li++)n.readUEG(),n.readUEG(),Xt&&(n.readUEG(),n.readUEG()),n.skipBits(1)}}n.readBoolean()&&(n.readBoolean(),n.readBoolean(),n.readBoolean(),Y=n.readUEG())}let Ae=L,Ee=U;if(O){let lt=1,un=1;E===1?lt=un=2:E==2&&(lt=2),Ae=L-lt*I-lt*k,Ee=U-un*M-un*R}const je=i?["A","B","C"][i]:"",Me=o<<24|l<<16|c<<8|u;let Pt=0;for(let lt=0;lt<32;lt++)Pt=(Pt|(Me>>lt&1)<<31-lt)>>>0;let tn=Pt.toString(16);return a===1&&tn==="2"&&(tn="6"),{codecString:`hvc1.${je}${a}.${tn}.${s?"H":"L"}${b}.B0`,params:{general_tier_flag:s,general_profile_idc:a,general_profile_space:i,general_profile_compatibility_flags:[o,l,c,u],general_constraint_indicator_flags:[d,h,f,p,m,g],general_level_idc:b,bit_depth:z+8,bit_depth_luma_minus8:z,bit_depth_chroma_minus8:Z,min_spatial_segmentation_idc:Y,chroma_format_idc:E,frame_rate:{fixed:Le,fps:Ne/ke}},width:Ae,height:Ee,pixelRatio:[ie,Ce]}}readPPS(e){const n=new Uf(this.ebsp2rbsp(e));n.readUByte(),n.readUByte(),n.skipUEG(),n.skipUEG(),n.skipBits(2),n.skipBits(3),n.skipBits(2),n.skipUEG(),n.skipUEG(),n.skipEG(),n.skipBits(2),n.readBoolean()&&n.skipUEG(),n.skipEG(),n.skipEG(),n.skipBits(4);const i=n.readBoolean(),s=n.readBoolean();let a=1;return s&&i?a=0:s?a=3:i&&(a=2),{parallelismType:a}}matchSPS(e,n){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,n).substr(3)}}const br=188;class Uo{constructor(e,n,r,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=n,this.typeSupported=r,this.logger=i,this.videoParser=null}static probe(e,n){const r=Uo.syncOffset(e);return r>0&&n.warn(`MPEG2-TS detected but first sync word found @ offset ${r}`),r!==-1}static syncOffset(e){const n=e.length;let r=Math.min(br*5,n-br)+1,i=0;for(;i<r;){let s=!1,a=-1,o=0;for(let l=i;l<n;l+=br)if(e[l]===71&&(n-l===br||e[l+br]===71)){if(o++,a===-1&&(a=l,a!==0&&(r=Math.min(a+br*99,e.length-br)+1)),s||(s=KE(e,l)===0),s&&o>1&&(a===0&&o>2||l+br>r))return a}else{if(o)return-1;break}i++}return-1}static createTrack(e,n){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:s3[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?n:void 0}}resetInitSegment(e,n,r,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Uo.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=Uo.createTrack("audio",i),this._id3Track=Uo.createTrack("id3"),this._txtTrack=Uo.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=n,this.videoCodec=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:n,_id3Track:r}=this;e&&(e.pesData=null),n&&(n.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,n,r=!1,i=!1){r||(this.sampleAes=null);let s;const a=this._videoTrack,o=this._audioTrack,l=this._id3Track,c=this._txtTrack;let u=a.pid,d=a.pesData,h=o.pid,f=l.pid,p=o.pesData,m=l.pesData,g=null,b=this.pmtParsed,v=this._pmtId,S=e.length;if(this.remainderData&&(e=ys(this.remainderData,e),S=e.length,this.remainderData=null),S<br&&!i)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:c};const E=Math.max(0,Uo.syncOffset(e));S-=(S-E)%br,S<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,S,e.buffer.byteLength-S));let L=0;for(let O=E;O<S;O+=br)if(e[O]===71){const k=!!(e[O+1]&64),I=KE(e,O),R=(e[O+3]&48)>>4;let M;if(R>1){if(M=O+5+e[O+4],M===O+br)continue}else M=O+4;switch(I){case u:k&&(d&&(s=wu(d,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,c,s,!1)),d={data:[],size:0}),d&&(d.data.push(e.subarray(M,O+br)),d.size+=O+br-M);break;case h:if(k){if(p&&(s=wu(p,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,s);break;case"mp3":this.parseMPEGPES(o,s);break;case"ac3":this.parseAC3PES(o,s);break}p={data:[],size:0}}p&&(p.data.push(e.subarray(M,O+br)),p.size+=O+br-M);break;case f:k&&(m&&(s=wu(m,this.logger))&&this.parseID3PES(l,s),m={data:[],size:0}),m&&(m.data.push(e.subarray(M,O+br)),m.size+=O+br-M);break;case 0:k&&(M+=e[M]+1),v=this._pmtId=Nue(e,M);break;case v:{k&&(M+=e[M]+1);const z=Mue(e,M,this.typeSupported,r,this.observer,this.logger);u=z.videoPid,u>0&&(a.pid=u,a.segmentCodec=z.segmentVideoCodec),h=z.audioPid,h>0&&(o.pid=h,o.segmentCodec=z.segmentAudioCodec),f=z.id3Pid,f>0&&(l.pid=f),g!==null&&!b&&(this.logger.warn(`MPEG-TS PMT found at ${O} after unknown PID '${g}'. Backtracking to sync byte @${E} to parse all TS packets.`),g=null,O=E-188),b=this.pmtParsed=!0;break}case 17:case 8191:break;default:g=I;break}}else L++;L>0&&zE(this.observer,new Error(`Found ${L} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=d,o.pesData=p,l.pesData=m;const U={audioTrack:o,videoTrack:a,id3Track:l,textTrack:c};return i&&this.extractRemainingSamples(U),U}flush(){const{remainderData:e}=this;this.remainderData=null;let n;return e?n=this.demux(e,-1,!1,!0):n={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(n),this.sampleAes?this.decrypt(n,this.sampleAes):n}extractRemainingSamples(e){const{audioTrack:n,videoTrack:r,id3Track:i,textTrack:s}=e,a=r.pesData,o=n.pesData,l=i.pesData;let c;if(a&&(c=wu(a,this.logger))?(this.readyVideoParser(r.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(r,s,c,!0),r.pesData=null)):r.pesData=a,o&&(c=wu(o,this.logger))){switch(n.segmentCodec){case"aac":this.parseAACPES(n,c);break;case"mp3":this.parseMPEGPES(n,c);break;case"ac3":this.parseAC3PES(n,c);break}n.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),n.pesData=o;l&&(c=wu(l,this.logger))?(this.parseID3PES(i,c),i.pesData=null):i.pesData=l}demuxSampleAes(e,n,r){const i=this.demux(e,r,!0,!this.config.progressive),s=this.sampleAes=new Pue(this.observer,this.config,n);return this.decrypt(i,s)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new Due:e==="hevc"&&(this.videoParser=new Oue))}decrypt(e,n){return new Promise(r=>{const{audioTrack:i,videoTrack:s}=e;i.samples&&i.segmentCodec==="aac"?n.decryptAacSamples(i.samples,0,()=>{s.samples?n.decryptAvcSamples(s.samples,0,0,()=>{r(e)}):r(e)}):s.samples&&n.decryptAvcSamples(s.samples,0,0,()=>{r(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,n){let r=0;const i=this.aacOverFlow;let s=n.data;if(i){this.aacOverFlow=null;const d=i.missing,h=i.sample.unit.byteLength;if(d===-1)s=ys(i.sample.unit,s);else{const f=h-d;i.sample.unit.set(s.subarray(0,d),f),e.samples.push(i.sample),r=i.missing}}let a,o;for(a=r,o=s.length;a<o-1&&!R0(s,a);a++);if(a!==r){let d;const h=a<o-1;if(h?d=`AAC PES did not start with ADTS header,offset:${a}`:d="No ADTS header found in AAC PES",zE(this.observer,new Error(d),h,this.logger),!h)return}V3(e,this.observer,s,a,this.audioCodec);let l;if(n.pts!==void 0)l=n.pts;else if(i){const d=G3(e.samplerate);l=i.sample.pts+d}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let c=0,u;for(;a<o;)if(u=H3(e,s,a,l,c),a+=u.length,u.missing){this.aacOverFlow=u;break}else for(c++;a<o-1&&!R0(s,a);a++);}parseMPEGPES(e,n){const r=n.data,i=r.length;let s=0,a=0;const o=n.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<i;)if(Y3(r,a)){const l=q3(e,r,a,o,s);if(l)a+=l.length,s++;else break}else a++}parseAC3PES(e,n){{const r=n.data,i=n.pts;if(i===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const s=r.length;let a=0,o=0,l;for(;o<s&&(l=J3(e,r,o,i,a++))>0;)o+=l}}parseID3PES(e,n){if(n.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const r=fn({},n,{type:this._videoTrack?Ni.emsg:Ni.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}}function KE(t,e){return((t[e+1]&31)<<8)+t[e+2]}function Nue(t,e){return(t[e+10]&31)<<8|t[e+11]}function Mue(t,e,n,r,i,s){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(t[e+1]&15)<<8|t[e+2],l=e+3+o-4,c=(t[e+10]&15)<<8|t[e+11];for(e+=12+c;e<l;){const u=KE(t,e),d=(t[e+3]&15)<<8|t[e+4];switch(t[e]){case 207:if(!r){zb("ADTS AAC",s);break}case 15:a.audioPid===-1&&(a.audioPid=u);break;case 21:a.id3Pid===-1&&(a.id3Pid=u);break;case 219:if(!r){zb("H.264",s);break}case 27:a.videoPid===-1&&(a.videoPid=u);break;case 3:case 4:!n.mpeg&&!n.mp3?s.log("MPEG audio found, not supported in this browser"):a.audioPid===-1&&(a.audioPid=u,a.segmentAudioCodec="mp3");break;case 193:if(!r){zb("AC-3",s);break}case 129:n.ac3?a.audioPid===-1&&(a.audioPid=u,a.segmentAudioCodec="ac3"):s.log("AC-3 audio found, not supported in this browser");break;case 6:if(a.audioPid===-1&&d>0){let h=e+5,f=d;for(;f>2;){switch(t[h]){case 106:n.ac3!==!0?s.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=u,a.segmentAudioCodec="ac3");break}const m=t[h+1]+2;h+=m,f-=m}}break;case 194:case 135:return zE(i,new Error("Unsupported EC-3 in M2TS found"),void 0,s),a;case 36:a.videoPid===-1&&(a.videoPid=u,a.segmentVideoCodec="hevc",s.log("HEVC in M2TS found"));break}e+=d+5}return a}function zE(t,e,n,r){r.warn(`parsing error: ${e.message}`),t.emit(j.ERROR,j.ERROR,{type:ct.MEDIA_ERROR,details:xe.FRAG_PARSING_ERROR,fatal:!1,levelRetry:n,error:e,reason:e.message})}function zb(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function wu(t,e){let n=0,r,i,s,a,o;const l=t.data;if(!t||t.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=ys(l[0],l[1]),l.splice(1,1);if(r=l[0],(r[0]<<16)+(r[1]<<8)+r[2]===1){if(i=(r[4]<<8)+r[5],i&&i>t.size-6)return null;const u=r[7];u&192&&(a=(r[9]&14)*536870912+(r[10]&255)*4194304+(r[11]&254)*16384+(r[12]&255)*128+(r[13]&254)/2,u&64?(o=(r[14]&14)*536870912+(r[15]&255)*4194304+(r[16]&254)*16384+(r[17]&255)*128+(r[18]&254)/2,a-o>60*9e4&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),s=r[8];let d=s+9;if(t.size<=d)return null;t.size-=d;const h=new Uint8Array(t.size);for(let f=0,p=l.length;f<p;f++){r=l[f];let m=r.byteLength;if(d)if(d>m){d-=m;continue}else r=r.subarray(d),m-=d,d=0;h.set(r,n),n+=m}return i&&(i-=s+3),{data:h,pts:a,dts:o,len:i}}return null}class Bue{static getSilentFrame(e,n){switch(e){case"mp4a.40.2":if(n===1)return new Uint8Array([0,200,0,128,35,128]);if(n===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(n===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(n===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(n===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(n===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(n===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(n===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(n===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}const Ro=Math.pow(2,32)-1;class be{static init(){be.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in be.types)be.types.hasOwnProperty(e)&&(be.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const n=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);be.HDLR_TYPES={video:n,audio:r};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);be.STTS=be.STSC=be.STCO=s,be.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),be.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),be.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),be.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);be.FTYP=be.box(be.types.ftyp,a,l,a,o),be.DINF=be.box(be.types.dinf,be.box(be.types.dref,i))}static box(e,...n){let r=8,i=n.length;const s=i;for(;i--;)r+=n[i].byteLength;const a=new Uint8Array(r);for(a[0]=r>>24&255,a[1]=r>>16&255,a[2]=r>>8&255,a[3]=r&255,a.set(e,4),i=0,r=8;i<s;i++)a.set(n[i],r),r+=n[i].byteLength;return a}static hdlr(e){return be.box(be.types.hdlr,be.HDLR_TYPES[e])}static mdat(e){return be.box(be.types.mdat,e)}static mdhd(e,n){n*=e;const r=Math.floor(n/(Ro+1)),i=Math.floor(n%(Ro+1));return be.box(be.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,r>>24,r>>16&255,r>>8&255,r&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return be.box(be.types.mdia,be.mdhd(e.timescale||0,e.duration||0),be.hdlr(e.type),be.minf(e))}static mfhd(e){return be.box(be.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?be.box(be.types.minf,be.box(be.types.smhd,be.SMHD),be.DINF,be.stbl(e)):be.box(be.types.minf,be.box(be.types.vmhd,be.VMHD),be.DINF,be.stbl(e))}static moof(e,n,r){return be.box(be.types.moof,be.mfhd(e),be.traf(r,n))}static moov(e){let n=e.length;const r=[];for(;n--;)r[n]=be.trak(e[n]);return be.box.apply(null,[be.types.moov,be.mvhd(e[0].timescale||0,e[0].duration||0)].concat(r).concat(be.mvex(e)))}static mvex(e){let n=e.length;const r=[];for(;n--;)r[n]=be.trex(e[n]);return be.box.apply(null,[be.types.mvex,...r])}static mvhd(e,n){n*=e;const r=Math.floor(n/(Ro+1)),i=Math.floor(n%(Ro+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,r>>24,r>>16&255,r>>8&255,r&255,i>>24,i>>16&255,i>>8&255,i&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return be.box(be.types.mvhd,s)}static sdtp(e){const n=e.samples||[],r=new Uint8Array(4+n.length);let i,s;for(i=0;i<n.length;i++)s=n[i].flags,r[i+4]=s.dependsOn<<4|s.isDependedOn<<2|s.hasRedundancy;return be.box(be.types.sdtp,r)}static stbl(e){return be.box(be.types.stbl,be.stsd(e),be.box(be.types.stts,be.STTS),be.box(be.types.stsc,be.STSC),be.box(be.types.stsz,be.STSZ),be.box(be.types.stco,be.STCO))}static avc1(e){let n=[],r=[],i,s,a;for(i=0;i<e.sps.length;i++)s=e.sps[i],a=s.byteLength,n.push(a>>>8&255),n.push(a&255),n=n.concat(Array.prototype.slice.call(s));for(i=0;i<e.pps.length;i++)s=e.pps[i],a=s.byteLength,r.push(a>>>8&255),r.push(a&255),r=r.concat(Array.prototype.slice.call(s));const o=be.box(be.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|e.sps.length].concat(n).concat([e.pps.length]).concat(r))),l=e.width,c=e.height,u=e.pixelRatio[0],d=e.pixelRatio[1];return be.box(be.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,be.box(be.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),be.box(be.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,d>>24,d>>16&255,d>>8&255,d&255])))}static esds(e){const n=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...n,6,1,2])}static audioStsd(e){const n=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,n>>8&255,n&255,0,0])}static mp4a(e){return be.box(be.types.mp4a,be.audioStsd(e),be.box(be.types.esds,be.esds(e)))}static mp3(e){return be.box(be.types[".mp3"],be.audioStsd(e))}static ac3(e){return be.box(be.types["ac-3"],be.audioStsd(e),be.box(be.types.dac3,e.config))}static stsd(e){const{segmentCodec:n}=e;if(e.type==="audio"){if(n==="aac")return be.box(be.types.stsd,be.STSD,be.mp4a(e));if(n==="ac3"&&e.config)return be.box(be.types.stsd,be.STSD,be.ac3(e));if(n==="mp3"&&e.codec==="mp3")return be.box(be.types.stsd,be.STSD,be.mp3(e))}else if(e.pps&&e.sps){if(n==="avc")return be.box(be.types.stsd,be.STSD,be.avc1(e));if(n==="hevc"&&e.vps)return be.box(be.types.stsd,be.STSD,be.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${n}/${e.codec})`)}static tkhd(e){const n=e.id,r=(e.duration||0)*(e.timescale||0),i=e.width||0,s=e.height||0,a=Math.floor(r/(Ro+1)),o=Math.floor(r%(Ro+1));return be.box(be.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,n>>24&255,n>>16&255,n>>8&255,n&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,i&255,0,0,s>>8&255,s&255,0,0]))}static traf(e,n){const r=be.sdtp(e),i=e.id,s=Math.floor(n/(Ro+1)),a=Math.floor(n%(Ro+1));return be.box(be.types.traf,be.box(be.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),be.box(be.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,s&255,a>>24,a>>16&255,a>>8&255,a&255])),be.trun(e,r.length+16+20+8+16+8+8),r)}static trak(e){return e.duration=e.duration||4294967295,be.box(be.types.trak,be.tkhd(e),be.mdia(e))}static trex(e){const n=e.id;return be.box(be.types.trex,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,n){const r=e.samples||[],i=r.length,s=12+16*i,a=new Uint8Array(s);let o,l,c,u,d,h;for(n+=8+s,a.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255],0),o=0;o<i;o++)l=r[o],c=l.duration,u=l.size,d=l.flags,h=l.cts,a.set([c>>>24&255,c>>>16&255,c>>>8&255,c&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,d.degradPrio&61440,d.degradPrio&15,h>>>24&255,h>>>16&255,h>>>8&255,h&255],12+16*o);return be.box(be.types.trun,a)}static initSegment(e){be.types||be.init();const n=be.moov(e);return ys(be.FTYP,n)}static hvc1(e){const n=e.params,r=[e.vps,e.sps,e.pps],i=4,s=new Uint8Array([1,n.general_profile_space<<6|(n.general_tier_flag?32:0)|n.general_profile_idc,n.general_profile_compatibility_flags[0],n.general_profile_compatibility_flags[1],n.general_profile_compatibility_flags[2],n.general_profile_compatibility_flags[3],n.general_constraint_indicator_flags[0],n.general_constraint_indicator_flags[1],n.general_constraint_indicator_flags[2],n.general_constraint_indicator_flags[3],n.general_constraint_indicator_flags[4],n.general_constraint_indicator_flags[5],n.general_level_idc,240|n.min_spatial_segmentation_idc>>8,255&n.min_spatial_segmentation_idc,252|n.parallelismType,252|n.chroma_format_idc,248|n.bit_depth_luma_minus8,248|n.bit_depth_chroma_minus8,0,parseInt(n.frame_rate.fps),i-1|n.temporal_id_nested<<2|n.num_temporal_layers<<3|(n.frame_rate.fixed?64:0),r.length]);let a=s.length;for(let p=0;p<r.length;p+=1){a+=3;for(let m=0;m<r[p].length;m+=1)a+=2+r[p][m].length}const o=new Uint8Array(a);o.set(s,0),a=s.length;const l=r.length-1;for(let p=0;p<r.length;p+=1){o.set(new Uint8Array([32+p|(p===l?128:0),0,r[p].length]),a),a+=3;for(let m=0;m<r[p].length;m+=1)o.set(new Uint8Array([r[p][m].length>>8,r[p][m].length&255]),a),a+=2,o.set(r[p][m],a),a+=r[p][m].length}const c=be.box(be.types.hvcC,o),u=e.width,d=e.height,h=e.pixelRatio[0],f=e.pixelRatio[1];return be.box(be.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,u>>8&255,u&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),c,be.box(be.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),be.box(be.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,f>>24,f>>16&255,f>>8&255,f&255])))}}be.types=void 0;be.HDLR_TYPES=void 0;be.STTS=void 0;be.STSC=void 0;be.STCO=void 0;be.STSZ=void 0;be.VMHD=void 0;be.SMHD=void 0;be.STSD=void 0;be.FTYP=void 0;be.DINF=void 0;const e4=9e4;function XA(t,e,n=1,r=!1){const i=t*e*n;return r?Math.round(i):i}function Uue(t,e,n=1,r=!1){return XA(t,e,1/n,r)}function zh(t,e=!1){return XA(t,1e3,1/e4,e)}function jue(t,e=1){return XA(t,e4,1/e)}function VP(t){const{baseTime:e,timescale:n,trackId:r}=t;return`${e/n} (${e}/${n}) trackId: ${r}`}const Fue=10*1e3,$ue=1024,Vue=1152,Gue=1536;let Tu=null,qb=null;function GP(t,e,n,r){return{duration:e,size:n,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}class uy extends vs{constructor(e,n,r,i){if(super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=n,this.typeSupported=r,this.ISGenerated=!1,Tu===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Tu=a?parseInt(a[1]):0}if(qb===null){const s=navigator.userAgent.match(/Safari\/(\d+)/i);qb=s?parseInt(s[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const n=this._initPTS;(!n||!e||e.trackId!==n.trackId||e.baseTime!==n.baseTime||e.timescale!==n.timescale)&&this.log(`Reset initPTS: ${n&&VP(n)} > ${e&&VP(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let n=!1;const r=e[0].pts,i=e.reduce((s,a)=>{let o=a.pts,l=o-s;return l<-4294967296&&(n=!0,o=ki(o,r),l=o-s),l>0?s:o},r);return n&&this.debug("PTS rollover detected"),i}remux(e,n,r,i,s,a,o,l){let c,u,d,h,f,p,m=s,g=s;const b=e.pid>-1,v=n.pid>-1,S=n.samples.length,E=e.samples.length>0,L=o&&S>0||S>1;if((!b||E)&&(!v||L)||this.ISGenerated||o){if(this.ISGenerated){var O,k,I,R;const W=this.videoTrackConfig;(W&&(n.width!==W.width||n.height!==W.height||((O=n.pixelRatio)==null?void 0:O[0])!==((k=W.pixelRatio)==null?void 0:k[0])||((I=n.pixelRatio)==null?void 0:I[1])!==((R=W.pixelRatio)==null?void 0:R[1]))||!W&&L||this.nextAudioTs===null&&E)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,n,s,a));const M=this.isVideoContiguous;let z=-1,Z;if(L&&(z=Hue(n.samples),!M&&this.config.forceKeyFrameOnDiscontinuity))if(p=!0,z>0){this.warn(`Dropped ${z} out of ${S} video samples due to a missing keyframe`);const W=this.getVideoStartPts(n.samples);n.samples=n.samples.slice(z),n.dropped+=z,g+=(n.samples[0].pts-W)/n.inputTimeScale,Z=g}else z===-1&&(this.warn(`No keyframe found out of ${S} video samples`),p=!1);if(this.ISGenerated){if(E&&L){const W=this.getVideoStartPts(n.samples),X=(ki(e.samples[0].pts,W)-W)/n.inputTimeScale;m+=Math.max(0,X),g+=Math.max(0,-X)}if(E){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(e,n,s,a)),u=this.remuxAudio(e,m,this.isAudioContiguous,a,v||L||l===tt.AUDIO?g:void 0),L){const W=u?u.endPTS-u.startPTS:0;n.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(e,n,s,a)),c=this.remuxVideo(n,g,M,W)}}else L&&(c=this.remuxVideo(n,g,M,0));c&&(c.firstKeyFrame=z,c.independent=z!==-1,c.firstKeyFramePTS=Z)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(f=t4(r,s,this._initPTS,this._initDTS)),i.samples.length&&(h=n4(i,s,this._initPTS))),{audio:u,video:c,initSegment:d,independent:p,text:h,id3:f}}computeInitPts(e,n,r,i){const s=Math.round(r*n);let a=ki(e,s);if(a<s+n)for(this.log(`Adjusting PTS for rollover in timeline near ${(s-a)/n} ${i}`);a<s+n;)a+=8589934592;return a-s}generateIS(e,n,r,i){const s=e.samples,a=n.samples,o=this.typeSupported,l={},c=this._initPTS;let u=!c||i,d="audio/mp4",h,f,p,m=-1;if(u&&(h=f=1/0),e.config&&s.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(d="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}l.audio={id:"audio",container:d,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):be.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(m=e.id,p=e.inputTimeScale,!c||p!==c.timescale?h=f=this.computeInitPts(s[0].pts,p,r,"audio"):u=!1)}if(n.sps&&n.pps&&a.length){if(n.timescale=n.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:n.codec,initSegment:be.initSegment([n]),metadata:{width:n.width,height:n.height}},u)if(m=n.id,p=n.inputTimeScale,!c||p!==c.timescale){const g=this.getVideoStartPts(a),b=ki(a[0].dts,g),v=this.computeInitPts(b,p,r,"video"),S=this.computeInitPts(g,p,r,"video");f=Math.min(f,v),h=Math.min(h,S)}else u=!1;this.videoTrackConfig={width:n.width,height:n.height,pixelRatio:n.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,u?(c&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${r} ${h/p} != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${h/p} (${h}/${p}) trackId: ${m}`),this._initPTS={baseTime:h,timescale:p,trackId:m},this._initDTS={baseTime:f,timescale:p,trackId:m}):h=p=void 0,{tracks:l,initPTS:h,timescale:p,trackId:m}}remuxVideo(e,n,r,i){const s=e.inputTimeScale,a=e.samples,o=[],l=a.length,c=this._initPTS,u=c.baseTime*s/c.timescale;let d=this.nextVideoTs,h=8,f=this.videoSampleDuration,p,m,g=Number.POSITIVE_INFINITY,b=Number.NEGATIVE_INFINITY,v=!1;if(!r||d===null){const Y=u+n*s,ie=a[0].pts-ki(a[0].dts,a[0].pts);Tu&&d!==null&&Math.abs(Y-ie-(d+u))<15e3?r=!0:d=Y-ie-u}const S=d+u;for(let Y=0;Y<l;Y++){const ie=a[Y];ie.pts=ki(ie.pts,S),ie.dts=ki(ie.dts,S),ie.dts<a[Y>0?Y-1:Y].dts&&(v=!0)}v&&a.sort(function(Y,ie){const Ce=Y.dts-ie.dts,Le=Y.pts-ie.pts;return Ce||Le}),p=a[0].dts,m=a[a.length-1].dts;const E=m-p,L=E?Math.round(E/(l-1)):f||e.inputTimeScale/30;if(r){const Y=p-S,ie=Y>L,Ce=Y<-1;if((ie||Ce)&&(ie?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${zh(Y,!0)} ms (${Y}dts) hole between fragments detected at ${n.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${zh(-Y,!0)} ms (${Y}dts) overlapping between fragments detected at ${n.toFixed(3)}`),!Ce||S>=a[0].pts||Tu)){p=S;const Le=a[0].pts-Y;if(ie)a[0].dts=p,a[0].pts=Le;else{let ke=!0;for(let Ne=0;Ne<a.length&&!(a[Ne].dts>Le&&ke);Ne++){const ye=a[Ne].pts;if(a[Ne].dts-=Y,a[Ne].pts-=Y,Ne<a.length-1){const Ie=a[Ne+1].pts,Ae=a[Ne].pts,Ee=Ie<=Ae,je=Ie<=ye;ke=Ee==je}}}this.log(`Video: Initial PTS/DTS adjusted: ${zh(Le,!0)}/${zh(p,!0)}, delta: ${zh(Y,!0)} ms`)}}p=Math.max(0,p);let U=0,O=0,k=p;for(let Y=0;Y<l;Y++){const ie=a[Y],Ce=ie.units,Le=Ce.length;let ke=0;for(let Ne=0;Ne<Le;Ne++)ke+=Ce[Ne].data.length;O+=ke,U+=Le,ie.length=ke,ie.dts<k?(ie.dts=k,k+=L/4|0||1):k=ie.dts,g=Math.min(ie.pts,g),b=Math.max(ie.pts,b)}m=a[l-1].dts;const I=O+4*U+8;let R;try{R=new Uint8Array(I)}catch(Y){this.observer.emit(j.ERROR,j.ERROR,{type:ct.MUX_ERROR,details:xe.REMUX_ALLOC_ERROR,fatal:!1,error:Y,bytes:I,reason:`fail allocating video mdat ${I}`});return}const M=new DataView(R.buffer);M.setUint32(0,I),R.set(be.types.mdat,4);let z=!1,Z=Number.POSITIVE_INFINITY,W=Number.POSITIVE_INFINITY,re=Number.NEGATIVE_INFINITY,X=Number.NEGATIVE_INFINITY;for(let Y=0;Y<l;Y++){const ie=a[Y],Ce=ie.units;let Le=0;for(let ye=0,Ie=Ce.length;ye<Ie;ye++){const Ae=Ce[ye],Ee=Ae.data,je=Ae.data.byteLength;M.setUint32(h,je),h+=4,R.set(Ee,h),h+=je,Le+=4+je}let ke;if(Y<l-1)f=a[Y+1].dts-ie.dts,ke=a[Y+1].pts-ie.pts;else{const ye=this.config,Ie=Y>0?ie.dts-a[Y-1].dts:L;if(ke=Y>0?ie.pts-a[Y-1].pts:L,ye.stretchShortVideoTrack&&this.nextAudioTs!==null){const Ae=Math.floor(ye.maxBufferHole*s),Ee=(i?g+i*s:this.nextAudioTs+u)-ie.pts;Ee>Ae?(f=Ee-Ie,f<0?f=Ie:z=!0,this.log(`It is approximately ${Ee/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=Ie}else f=Ie}const Ne=Math.round(ie.pts-ie.dts);Z=Math.min(Z,f),re=Math.max(re,f),W=Math.min(W,ke),X=Math.max(X,ke),o.push(GP(ie.key,f,Le,Ne))}if(o.length){if(Tu){if(Tu<70){const Y=o[0].flags;Y.dependsOn=2,Y.isNonSync=0}}else if(qb&&X-W<re-Z&&L/re<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let Y=p;for(let ie=0,Ce=o.length;ie<Ce;ie++){const Le=Y+o[ie].duration,ke=Y+o[ie].cts;if(ie<Ce-1){const Ne=Le+o[ie+1].cts;o[ie].duration=Ne-ke}else o[ie].duration=ie?o[ie-1].duration:L;o[ie].cts=0,Y=Le}}}f=z||!f?L:f;const oe=m+f;this.nextVideoTs=d=oe-u,this.videoSampleDuration=f,this.isVideoContiguous=!0;const H={data1:be.moof(e.sequenceNumber++,p,fn(e,{samples:o})),data2:R,startPTS:(g-u)/s,endPTS:(b+f-u)/s,startDTS:(p-u)/s,endDTS:d/s,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,H}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return Vue;case"ac3":return Gue;default:return $ue}}remuxAudio(e,n,r,i,s){const a=e.inputTimeScale,o=e.samplerate?e.samplerate:a,l=a/o,c=this.getSamplesPerFrame(e),u=c*l,d=this._initPTS,h=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],p=s!==void 0;let m=e.samples,g=h?0:8,b=this.nextAudioTs||-1;const v=d.baseTime*a/d.timescale,S=v+n*a;if(this.isAudioContiguous=r=r||m.length&&b>0&&(i&&Math.abs(S-(b+v))<9e3||Math.abs(ki(m[0].pts,S)-(b+v))<20*u),m.forEach(function(X){X.pts=ki(X.pts,S)}),!r||b<0){const X=m.length;if(m=m.filter(oe=>oe.pts>=0),X!==m.length&&this.warn(`Removed ${m.length-X} of ${X} samples (initPTS ${v} / ${a})`),!m.length)return;s===0?b=0:i&&!p?b=Math.max(0,S-v):b=m[0].pts-v}if(e.segmentCodec==="aac"){const X=this.config.maxAudioFramesDrift;for(let oe=0,Q=b+v;oe<m.length;oe++){const G=m[oe],H=G.pts,Y=H-Q,ie=Math.abs(1e3*Y/a);if(Y<=-X*u&&p)oe===0&&(this.warn(`Audio frame @ ${(H/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*Y/a)} ms.`),this.nextAudioTs=b=H-v,Q=H);else if(Y>=X*u&&ie<Fue&&p){let Ce=Math.round(Y/u);for(Q=H-Ce*u;Q<0&&Ce&&u;)Ce--,Q+=u;oe===0&&(this.nextAudioTs=b=Q-v),this.warn(`Injecting ${Ce} audio frames @ ${((Q-v)/a).toFixed(3)}s due to ${Math.round(1e3*Y/a)} ms gap.`);for(let Le=0;Le<Ce;Le++){let ke=Bue.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);ke||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),ke=G.unit.subarray()),m.splice(oe,0,{unit:ke,pts:Q}),Q+=u,oe++}}G.pts=Q,Q+=u}}let E=null,L=null,U,O=0,k=m.length;for(;k--;)O+=m[k].unit.byteLength;for(let X=0,oe=m.length;X<oe;X++){const Q=m[X],G=Q.unit;let H=Q.pts;if(L!==null){const ie=f[X-1];ie.duration=Math.round((H-L)/l)}else if(r&&e.segmentCodec==="aac"&&(H=b+v),E=H,O>0){O+=g;try{U=new Uint8Array(O)}catch(ie){this.observer.emit(j.ERROR,j.ERROR,{type:ct.MUX_ERROR,details:xe.REMUX_ALLOC_ERROR,fatal:!1,error:ie,bytes:O,reason:`fail allocating audio mdat ${O}`});return}h||(new DataView(U.buffer).setUint32(0,O),U.set(be.types.mdat,4))}else return;U.set(G,g);const Y=G.byteLength;g+=Y,f.push(GP(!0,c,Y,0)),L=H}const I=f.length;if(!I)return;const R=f[f.length-1];b=L-v,this.nextAudioTs=b+l*R.duration;const M=h?new Uint8Array(0):be.moof(e.sequenceNumber++,E/l,fn({},e,{samples:f}));e.samples=[];const z=(E-v)/a,Z=this.nextAudioTs/a,re={data1:M,data2:U,startPTS:z,endPTS:Z,startDTS:z,endDTS:Z,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,re}}function ki(t,e){let n;if(e===null)return t;for(e<t?n=-8589934592:n=8589934592;Math.abs(t-e)>4294967296;)t+=n;return t}function Hue(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}function t4(t,e,n,r){const i=t.samples.length;if(!i)return;const s=t.inputTimeScale;for(let o=0;o<i;o++){const l=t.samples[o];l.pts=ki(l.pts-n.baseTime*s/n.timescale,e*s)/s,l.dts=ki(l.dts-r.baseTime*s/r.timescale,e*s)/s}const a=t.samples;return t.samples=[],{samples:a}}function n4(t,e,n){const r=t.samples.length;if(!r)return;const i=t.inputTimeScale;for(let a=0;a<r;a++){const o=t.samples[a];o.pts=ki(o.pts-n.baseTime*i/n.timescale,e*i)/i}t.samples.sort((a,o)=>a.pts-o.pts);const s=t.samples;return t.samples=[],{samples:s}}class Kue extends vs{constructor(e,n,r,i){super("passthrough-remuxer",i),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const n=this.initPTS;n&&e&&n.baseTime===e.baseTime&&n.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,n,r,i){this.audioCodec=n,this.videoCodec=r,this.generateInitSegment(e,i),this.emitInitSegment=!0}generateInitSegment(e,n){let{audioCodec:r,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:s,video:a}=this.initData=l3(e);if(n)Ple(e,n);else{const l=s||a;l!=null&&l.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${l.codec}")!`)}s&&(r=HP(s,pn.AUDIO,this)),a&&(i=HP(a,pn.VIDEO,this));const o={};s&&a?o.audiovideo={container:"video/mp4",codec:r+","+i,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:s?o.audio={container:"audio/mp4",codec:r,encrypted:s.encrypted,initSegment:e,id:"audio"}:a?o.video={container:"video/mp4",codec:i,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,n,r,i,s,a){var o,l;let{initPTS:c,lastEndTime:u}=this;const d={audio:void 0,video:void 0,text:i,id3:r,initSegment:void 0};Ze(u)||(u=this.lastEndTime=s||0);const h=n.samples;if(!h.length)return d;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let p=this.initData;if((o=p)!=null&&o.length||(this.generateInitSegment(h),p=this.initData),!((l=p)!=null&&l.length))return this.warn("Failed to generate initSegment."),d;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const m=Ole(h,p,this),g=p.audio?m[p.audio.id]:null,b=p.video?m[p.video.id]:null,v=wg(b,1/0),S=wg(g,1/0),E=wg(b,0,!0),L=wg(g,0,!0);let U=s,O=0;const k=g&&(!b||!c&&S<v||c&&c.trackId===p.audio.id),I=k?g:b;if(I){const Q=I.timescale,G=I.start-s*Q,H=k?p.audio.id:p.video.id;U=I.start/Q,O=k?L-S:E-v,(a||!c)&&(zue(c,U,s,O)||Q!==c.timescale)&&(c&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${s} ${G/Q} != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${U-s} (${G}/${Q}) trackId: ${H}`),c=null,f.initPTS=G,f.timescale=Q,f.trackId=H)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${s}`);c?(f.initPTS=c.baseTime,f.timescale=c.timescale,f.trackId=c.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=U,f.timescale=1,f.trackId=-1),this.initPTS=c={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});const R=U-c.baseTime/c.timescale,M=R+O;O>0?this.lastEndTime=M:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const z=!!p.audio,Z=!!p.video;let W="";z&&(W+="audio"),Z&&(W+="video");const re=(p.audio?p.audio.encrypted:!1)||(p.video?p.video.encrypted:!1),X={data1:h,startPTS:R,startDTS:R,endPTS:M,endDTS:M,type:W,hasAudio:z,hasVideo:Z,nb:1,dropped:0,encrypted:re};d.audio=z&&!Z?X:void 0,d.video=Z?X:void 0;const oe=b==null?void 0:b.sampleCount;if(oe){const Q=b.keyFrameIndex,G=Q!==-1;X.nb=oe,X.dropped=Q===0||this.isVideoContiguous?0:G?Q:oe,X.independent=G,X.firstKeyFrame=Q,G&&b.keyFrameStart&&(X.firstKeyFramePTS=(b.keyFrameStart-c.baseTime)/c.timescale),this.isVideoContiguous||(d.independent=G),this.isVideoContiguous||(this.isVideoContiguous=G),X.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${Q}/${oe} dropped: ${X.dropped} start: ${X.firstKeyFramePTS||"NA"}`)}return d.initSegment=f,d.id3=t4(r,s,c,c),i.samples.length&&(d.text=n4(i,s,c)),d}}function wg(t,e,n=!1){return(t==null?void 0:t.start)!==void 0?(t.start+(n?t.duration:0))/t.timescale:e}function zue(t,e,n,r){if(t===null)return!0;const i=Math.max(r,1),s=e-t.baseTime/t.timescale;return Math.abs(s-n)>i}function HP(t,e,n){const r=t.codec;return r&&r.length>4?r:e===pn.AUDIO?r==="ec-3"||r==="ac-3"||r==="alac"?r:r==="fLaC"||r==="Opus"?_0(r,!1):(n.warn(`Unhandled audio codec "${r}" in mp4 MAP`),r||"mp4a"):(n.warn(`Unhandled video codec "${r}" in mp4 MAP`),r||"avc1")}let Ka;try{Ka=self.performance.now.bind(self.performance)}catch{Ka=Date.now}const dy=[{demux:Iue,remux:Kue},{demux:Uo,remux:uy},{demux:Rue,remux:uy},{demux:Lue,remux:uy}];dy.splice(2,0,{demux:Cue,remux:uy});class KP{constructor(e,n,r,i,s,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=n,this.config=r,this.id=s,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,n,r,i){const s=r.transmuxing;s.executeStart=Ka();let a=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:l}=this;i&&(this.currentTransmuxState=i);const{contiguous:c,discontinuity:u,trackSwitch:d,accurateTimeOffset:h,timeOffset:f,initSegmentChange:p}=i||o,{audioCodec:m,videoCodec:g,defaultInitPts:b,duration:v,initSegmentData:S}=l,E=que(a,n);if(E&&_d(E.method)){const k=this.getDecrypter(),I=$A(E.method);if(k.isSync()){let R=k.softwareDecrypt(a,E.key.buffer,E.iv.buffer,I);if(r.part>-1){const z=k.flush();R=z&&z.buffer}if(!R)return s.executeEnd=Ka(),Wb(r);a=new Uint8Array(R)}else return this.asyncResult=!0,this.decryptionPromise=k.webCryptoDecrypt(a,E.key.buffer,E.iv.buffer,I).then(R=>{const M=this.push(R,null,r);return this.decryptionPromise=null,M}),this.decryptionPromise}const L=this.needsProbing(u,d);if(L){const k=this.configureTransmuxer(a);if(k)return this.logger.warn(`[transmuxer] ${k.message}`),this.observer.emit(j.ERROR,j.ERROR,{type:ct.MEDIA_ERROR,details:xe.FRAG_PARSING_ERROR,fatal:!1,error:k,reason:k.message}),s.executeEnd=Ka(),Wb(r)}(u||d||p||L)&&this.resetInitSegment(S,m,g,v,n),(u||p||L)&&this.resetInitialTimestamp(b),c||this.resetContiguity();const U=this.transmux(a,E,f,h,r);this.asyncResult=Cp(U);const O=this.currentTransmuxState;return O.contiguous=!0,O.discontinuity=!1,O.trackSwitch=!1,s.executeEnd=Ka(),U}flush(e){const n=e.transmuxing;n.executeStart=Ka();const{decrypter:r,currentTransmuxState:i,decryptionPromise:s}=this;if(s)return this.asyncResult=!0,s.then(()=>this.flush(e));const a=[],{timeOffset:o}=i;if(r){const d=r.flush();d&&a.push(this.push(d.buffer,null,e))}const{demuxer:l,remuxer:c}=this;if(!l||!c){n.executeEnd=Ka();const d=[Wb(e)];return this.asyncResult?Promise.resolve(d):d}const u=l.flush(o);return Cp(u)?(this.asyncResult=!0,u.then(d=>(this.flushRemux(a,d,e),a))):(this.flushRemux(a,u,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,n,r){const{audioTrack:i,videoTrack:s,id3Track:a,textTrack:o}=n,{accurateTimeOffset:l,timeOffset:c}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${r.sn}${r.part>-1?" part: "+r.part:""} of ${this.id===tt.MAIN?"level":"track"} ${r.level}`);const u=this.remuxer.remux(i,s,a,o,c,l,!0,this.id);e.push({remuxResult:u,chunkMeta:r}),r.transmuxing.executeEnd=Ka()}resetInitialTimestamp(e){const{demuxer:n,remuxer:r}=this;!n||!r||(n.resetTimeStamp(e),r.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:n}=this;!e||!n||(e.resetContiguity(),n.resetNextTimestamp())}resetInitSegment(e,n,r,i,s){const{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,n,r,i),o.resetInitSegment(e,n,r,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,n,r,i,s){let a;return n&&n.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,n,r,i,s):a=this.transmuxUnencrypted(e,r,i,s),a}transmuxUnencrypted(e,n,r,i){const{audioTrack:s,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(e,n,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,a,o,l,n,r,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,n,r,i,s){return this.demuxer.demuxSampleAes(e,n,r).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,r,i,!1,this.id),chunkMeta:s}))}configureTransmuxer(e){const{config:n,observer:r,typeSupported:i}=this;let s;for(let d=0,h=dy.length;d<h;d++){var a;if((a=dy[d].demux)!=null&&a.probe(e,this.logger)){s=dy[d];break}}if(!s)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,l=this.remuxer,c=s.remux,u=s.demux;(!l||!(l instanceof c))&&(this.remuxer=new c(r,n,i,this.logger)),(!o||!(o instanceof u))&&(this.demuxer=new u(r,n,i,this.logger),this.probe=u.probe)}needsProbing(e,n){return!this.demuxer||!this.remuxer||e||n}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new jA(this.config)),e}}function que(t,e){let n=null;return t.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(n=e),n}const Wb=t=>({remuxResult:{},chunkMeta:t});function Cp(t){return"then"in t&&t.then instanceof Function}class Wue{constructor(e,n,r,i,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=n,this.initSegmentData=r,this.duration=i,this.defaultInitPts=s||null}}class Yue{constructor(e,n,r,i,s,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=n,this.accurateTimeOffset=r,this.trackSwitch=i,this.timeOffset=s,this.initSegmentChange=a}}let zP=0;class r4{constructor(e,n,r,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=zP++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=l=>{const c=l.data,u=this.hls;if(!(!u||!(c!=null&&c.event)||c.instanceNo!==this.instanceNo))switch(c.event){case"init":{var d;const h=(d=this.workerContext)==null?void 0:d.objectURL;h&&self.URL.revokeObjectURL(h);break}case"transmuxComplete":{this.handleTransmuxComplete(c.data);break}case"flush":{this.onFlush(c.data);break}case"workerLog":{u.logger[c.data.logType]&&u.logger[c.data.logType](c.data.message);break}default:{c.data=c.data||{},c.data.frag=this.frag,c.data.part=this.part,c.data.id=this.id,u.trigger(c.event,c.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;const c=new Error(`${l.message}  (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(j.ERROR,{type:ct.OTHER_ERROR,details:xe.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:c})};const s=e.config;this.hls=e,this.id=n,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=r,this.onFlush=i;const a=(l,c)=>{c=c||{},c.frag=this.frag||void 0,l===j.ERROR&&(c=c,c.parent=this.id,c.part=this.part,this.error=c.error),this.hls.trigger(l,c)};this.observer=new HA,this.observer.on(j.FRAG_DECRYPTED,a),this.observer.on(j.ERROR,a);const o=oP(s.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const l=this.hls.logger;if(s.workerPath||Zce()){try{s.workerPath?(l.log(`loading Web Worker ${s.workerPath} for "${n}"`),this.workerContext=tue(s.workerPath)):(l.log(`injecting Web Worker for "${n}"`),this.workerContext=eue());const{worker:u}=this.workerContext;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:n,config:yn(s)})}catch(u){l.warn(`Error setting up "${n}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new KP(this.observer,o,s,"",n,e.logger)}return}}this.transmuxer=new KP(this.observer,o,s,"",n,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=zP++;const n=this.hls.config,r=oP(n.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:r,id:this.id,config:yn(n)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),nue(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const n=this.transmuxer;n&&(n.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,n,r,i,s,a,o,l,c,u){var d,h;c.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:p}=this,m=a?a.start:s.start,g=s.decryptdata,b=this.frag,v=!(b&&s.cc===b.cc),S=!(b&&c.level===b.level),E=b?c.sn-b.sn:-1,L=this.part?c.part-this.part.index:-1,U=E===0&&c.id>1&&c.id===(b==null?void 0:b.stats.chunkCount),O=!S&&(E===1||E===0&&(L===1||U&&L<=0)),k=self.performance.now();(S||E||s.stats.parsing.start===0)&&(s.stats.parsing.start=k),a&&(L||!O)&&(a.stats.parsing.start=k);const I=!(b&&((d=s.initSegment)==null?void 0:d.url)===((h=b.initSegment)==null?void 0:h.url)),R=new Yue(v,O,l,S,m,I);if(!O||v||I){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${s.type} sn: ${c.sn}${c.part>-1?" part: "+c.part:""} ${this.id===tt.MAIN?"level":"track"}: ${c.level} id: ${c.id}
        discontinuity: ${v}
        trackSwitch: ${S}
        contiguous: ${O}
        accurateTimeOffset: ${l}
        timeOffset: ${m}
        initSegmentChange: ${I}`);const M=new Wue(r,i,n,o,u);this.configureTransmuxer(M)}if(this.frag=s,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:g,chunkMeta:c,state:R},e instanceof ArrayBuffer?[e]:[]);else if(p){const M=p.push(e,g,c,R);Cp(M)?M.then(z=>{this.handleTransmuxComplete(z)}).catch(z=>{this.transmuxerError(z,c,"transmuxer-interface push error")}):this.handleTransmuxComplete(M)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:n,transmuxer:r}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:n,cmd:"flush",chunkMeta:e});else if(r){const i=r.flush(e);Cp(i)?i.then(s=>{this.handleFlushResult(s,e)}).catch(s=>{this.transmuxerError(s,e,"transmuxer-interface flush error")}):this.handleFlushResult(i,e)}}transmuxerError(e,n,r){this.hls&&(this.error=e,this.hls.trigger(j.ERROR,{type:ct.MEDIA_ERROR,details:xe.FRAG_PARSING_ERROR,chunkMeta:n,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:r}))}handleFlushResult(e,n){e.forEach(r=>{this.handleTransmuxComplete(r)}),this.onFlush(n)}configureTransmuxer(e){const{instanceNo:n,transmuxer:r}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:n,cmd:"configure",config:e}):r&&r.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const qP=100;class Xue extends GA{constructor(e,n,r){super(e,n,r,"audio-stream-controller",tt.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(j.LEVEL_LOADED,this.onLevelLoaded,this),e.on(j.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(j.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(j.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(j.BUFFER_RESET,this.onBufferReset,this),e.on(j.BUFFER_CREATED,this.onBufferCreated,this),e.on(j.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(j.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(j.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(j.FRAG_LOADING,this.onFragLoading,this),e.on(j.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(j.LEVEL_LOADED,this.onLevelLoaded,this),e.off(j.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(j.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(j.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(j.BUFFER_RESET,this.onBufferReset,this),e.off(j.BUFFER_CREATED,this.onBufferCreated,this),e.off(j.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(j.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(j.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(j.FRAG_LOADING,this.onFragLoading,this),e.off(j.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:n,id:r,initPTS:i,timescale:s,trackId:a}){if(r===tt.MAIN){const o=n.cc,l=this.fragCurrent;if(this.initPTS[o]={baseTime:i,timescale:s,trackId:a},this.log(`InitPTS for cc: ${o} found from main: ${i/s} (${i}/${s}) trackId: ${a}`),this.mainAnchor=n,this.state===Oe.WAITING_INIT_PTS){const c=this.waitingData;(!c&&!this.loadingParts||c&&c.frag.cc!==o)&&this.syncWithAnchor(n,c==null?void 0:c.frag)}else!this.hls.hasEnoughToStart&&l&&l.cc!==o?(l.abortRequests(),this.syncWithAnchor(n,l)):this.state===Oe.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,n){var r;const i=((r=this.mainFragLoading)==null?void 0:r.frag)||null;if(n&&(i==null?void 0:i.cc)===n.cc)return;const s=(i||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),l=_3(a,s,o);l&&(this.log(`Syncing with main frag at ${l.start} cc ${l.cc}`),this.startFragRequested=!1,this.nextLoadPosition=l.start,this.resetLoadingState(),this.state===Oe.IDLE&&this.doTickIdle())}startLoad(e,n){if(!this.levels){this.startPosition=e,this.state=Oe.STOPPED;return}const r=this.lastCurrentTime;this.stopLoad(),this.setInterval(qP),r>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r,this.state=Oe.IDLE):this.state=Oe.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=n?-1:e,this.tick()}doTick(){switch(this.state){case Oe.IDLE:this.doTickIdle();break;case Oe.WAITING_TRACK:{const{levels:e,trackId:n}=this,r=e==null?void 0:e[n],i=r==null?void 0:r.details;if(i&&!this.waitForLive(r)){if(this.waitForCdnTuneIn(i))break;this.state=Oe.WAITING_INIT_PTS}break}case Oe.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case Oe.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:n,part:r,cache:i,complete:s}=e,a=this.mainAnchor;if(this.initPTS[n.cc]!==void 0){this.waitingData=null,this.state=Oe.FRAG_LOADING;const o=i.flush().buffer,l={frag:n,part:r,payload:o,networkDetails:null};this._handleFragmentLoadProgress(l),s&&super._handleFragmentLoadComplete(l)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=Oe.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:n,levels:r,media:i,trackId:s}=this,a=n.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(r!=null&&r[s]))return;const o=r[s],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=Oe.WAITING_TRACK,this.startFragRequested=!1;return}const c=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&c&&(this.bufferFlushed=!1,this.afterBufferFlushed(c,pn.AUDIO,tt.AUDIO));const u=this.getFwdBufferInfo(c,tt.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,l)){n.trigger(j.BUFFER_EOS,{type:"audio"}),this.state=Oe.ENDED;return}const d=u.len,h=n.maxBufferLength,f=l.fragments,p=f[0].start,m=this.getLoadPosition(),g=this.flushing?m:u.end;if(this.switchingTrack&&i){const S=m;l.PTSKnown&&S<p&&(u.end>p||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=p+.05)}if(d>=h&&!this.switchingTrack&&g<f[f.length-1].start)return;let b=this.getNextFragment(g,l);if(b&&this.isLoopLoading(b,g)&&(b=this.getNextFragmentLoopLoading(b,l,u,tt.MAIN,h)),!b){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(u,h,b))return;let v=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&Zn(b)&&!b.endList&&(!l.live||!this.loadingParts&&g<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===pr.OK&&(this.mainFragLoading=v=null),v&&Zn(v))){if(b.start>v.end){const E=this.fragmentTracker.getFragAtPos(g,tt.MAIN);E&&E.end>v.end&&(v=E,this.mainFragLoading={frag:E,targetBufferTime:null})}if(b.start>v.end)return}this.loadFragment(b,o,g)}onMediaDetaching(e,n){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,n)}onAudioTracksUpdated(e,{audioTracks:n}){this.resetTransmuxer(),this.levels=n.map(r=>new Tp(r))}onAudioTrackSwitching(e,n){const r=!!n.url;this.trackId=n.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),r?(this.switchingTrack=n,this.flushAudioIfNeeded(n),this.state!==Oe.STOPPED&&(this.setInterval(qP),this.state=Oe.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=n,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,n){this.mainDetails=n.details;const r=this.cachedTrackLoadedData;r&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(j.AUDIO_TRACK_LOADED,r))}onAudioTrackLoaded(e,n){var r;const{levels:i}=this,{details:s,id:a,groupId:o,track:l}=n;if(!i){this.warn(`Audio tracks reset while loading track ${a} "${l.name}" of "${o}"`);return}const c=this.mainDetails;if(!c||s.endCC>c.endCC||c.expired){this.cachedTrackLoadedData=n,this.state!==Oe.STOPPED&&(this.state=Oe.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${l.name}" of "${o}" loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);const u=i[a];let d=0;if(s.live||(r=u.details)!=null&&r.live){if(this.checkLiveUpdate(s),s.deltaUpdateFailed)return;if(u.details){var h;d=this.alignPlaylists(s,u.details,(h=this.levelLastLoaded)==null?void 0:h.details)}s.alignedSliding||(B3(s,c),s.alignedSliding||A0(s,c),d=s.fragmentStart)}u.details=s,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(c,d),this.hls.trigger(j.AUDIO_TRACK_UPDATED,{details:s,id:a,groupId:n.groupId}),this.state===Oe.WAITING_TRACK&&!this.waitForCdnTuneIn(s)&&(this.state=Oe.IDLE),this.tick()}_handleFragmentLoadProgress(e){var n;const r=e.frag,{part:i,payload:s}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);return}const c=l[o];if(!c){this.warn("Audio track is undefined on fragment load progress");return}const u=c.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(r.start);return}const d=a.defaultAudioCodec||c.audioCodec||"mp4a.40.2";let h=this.transmuxer;h||(h=this.transmuxer=new r4(this.hls,tt.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[r.cc],p=(n=r.initSegment)==null?void 0:n.data;if(f!==void 0){const g=i?i.index:-1,b=g!==-1,v=new FA(r.level,r.sn,r.stats.chunkCount,s.byteLength,g,b);h.push(s,p,d,"",r,i,u.totalduration,!1,v,f)}else{this.log(`Unknown video PTS for cc ${r.cc}, waiting for video PTS before demuxing audio frag ${r.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);const{cache:m}=this.waitingData=this.waitingData||{frag:r,part:i,cache:new U3,complete:!1};m.push(new Uint8Array(s)),this.state!==Oe.STOPPED&&(this.state=Oe.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,n){this.bufferFlushed=this.flushing=!1;const r=n.tracks.audio;r&&(this.mediaBuffer=r.buffer||null)}onFragLoading(e,n){!this.audioOnly&&n.frag.type===tt.MAIN&&Zn(n.frag)&&(this.mainFragLoading=n,this.state===Oe.IDLE&&this.tick())}onFragBuffered(e,n){const{frag:r,part:i}=n;if(r.type!==tt.AUDIO){!this.audioOnly&&r.type===tt.MAIN&&!r.elementaryStreams.video&&!r.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(r)){this.warn(`Fragment ${r.sn}${i?" p: "+i.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Zn(r)){this.fragPrevious=r;const s=this.switchingTrack;s&&(this.bufferedTrack=s,this.switchingTrack=null,this.hls.trigger(j.AUDIO_TRACK_SWITCHED,on({},s)))}this.fragBufferedComplete(r,i),this.media&&this.tick()}onError(e,n){var r;if(n.fatal){this.state=Oe.ERROR;return}switch(n.details){case xe.FRAG_GAP:case xe.FRAG_PARSING_ERROR:case xe.FRAG_DECRYPT_ERROR:case xe.FRAG_LOAD_ERROR:case xe.FRAG_LOAD_TIMEOUT:case xe.KEY_LOAD_ERROR:case xe.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(tt.AUDIO,n);break;case xe.AUDIO_TRACK_LOAD_ERROR:case xe.AUDIO_TRACK_LOAD_TIMEOUT:case xe.LEVEL_PARSING_ERROR:!n.levelRetry&&this.state===Oe.WAITING_TRACK&&((r=n.context)==null?void 0:r.type)===Ft.AUDIO_TRACK&&(this.state=Oe.IDLE);break;case xe.BUFFER_ADD_CODEC_ERROR:case xe.BUFFER_APPEND_ERROR:if(n.parent!=="audio")return;this.reduceLengthAndFlushBuffer(n)||this.resetLoadingState();break;case xe.BUFFER_FULL_ERROR:if(n.parent!=="audio")return;this.reduceLengthAndFlushBuffer(n)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case xe.INTERNAL_EXCEPTION:this.recoverWorkerError(n);break}}onBufferFlushing(e,{type:n}){n!==pn.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:n}){if(n!==pn.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Oe.ENDED&&(this.state=Oe.IDLE);const r=this.mediaBuffer||this.media;r&&(this.afterBufferFlushed(r,n,tt.AUDIO),this.tick())}}_handleTransmuxComplete(e){var n;const r="audio",{hls:i}=this,{remuxResult:s,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:c,level:u}=o,{details:d}=u,{audio:h,text:f,id3:p,initSegment:m}=s;if(this.fragContextChanged(l)||!d){this.fragmentTracker.removeFragment(l);return}if(this.state=Oe.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),m!=null&&m.tracks){const g=l.initSegment||l;if(this.unhandledEncryptionError(m,l))return;this._bufferInitSegment(u,m.tracks,g,a),i.trigger(j.FRAG_PARSING_INIT_SEGMENT,{frag:g,id:r,tracks:m.tracks})}if(h){const{startPTS:g,endPTS:b,startDTS:v,endDTS:S}=h;c&&(c.elementaryStreams[pn.AUDIO]={startPTS:g,endPTS:b,startDTS:v,endDTS:S}),l.setElementaryStreamInfo(pn.AUDIO,g,b,v,S),this.bufferFragmentData(h,l,c,a)}if(p!=null&&(n=p.samples)!=null&&n.length){const g=fn({id:r,frag:l,details:d},p);i.trigger(j.FRAG_PARSING_METADATA,g)}if(f){const g=fn({id:r,frag:l,details:d},f);i.trigger(j.FRAG_PARSING_USERDATA,g)}}_bufferInitSegment(e,n,r,i){if(this.state!==Oe.PARSING||(n.video&&delete n.video,n.audiovideo&&delete n.audiovideo,!n.audio))return;const s=n.audio;s.id=tt.AUDIO;const a=e.audioCodec;this.log(`Init audio buffer, container:${s.container}, codecs[level/parsed]=[${a}/${s.codec}]`),a&&a.split(",").length===1&&(s.levelCodec=a),this.hls.trigger(j.BUFFER_CODECS,n);const o=s.initSegment;if(o!=null&&o.byteLength){const l={type:"audio",frag:r,part:null,chunkMeta:i,parent:r.type,data:o};this.hls.trigger(j.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,n,r){const i=this.fragmentTracker.getState(e);if(this.switchingTrack||i===pr.NOT_LOADED||i===pr.PARTIAL){var s;if(!Zn(e))this._loadInitSegment(e,n);else if((s=n.details)!=null&&s.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=Oe.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragmentStart!==n.details.fragmentStart&&A0(n.details,a)}else super.loadFragment(e,n,r)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:n,lang:r,assocLang:i,characteristics:s,audioCodec:a,channels:o}=this.bufferedTrack;Ic({name:n,lang:r,assocLang:i,characteristics:s,audioCodec:a,channels:o},e,tc)||(x0(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:n}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,n.trigger(j.AUDIO_TRACK_SWITCHED,on({},e))}}class QA extends vs{constructor(e,n){super(n,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,n,r){const i=n==null?void 0:n.renditionReports;if(i){let s=-1;for(let a=0;a<i.length;a++){const o=i[a];let l;try{l=new self.URL(o.URI,n.url).href}catch(c){this.warn(`Could not construct new URL for Rendition Report: ${c}`),l=o.URI||""}if(l===e){s=a;break}else l===e.substring(0,l.length)&&(s=a)}if(s!==-1){const a=i[s],o=parseInt(a["LAST-MSN"])||n.lastPartSn;let l=parseInt(a["LAST-PART"])||n.lastPartIndex;if(this.hls.config.lowLatencyMode){const u=Math.min(n.age-n.partTarget,n.targetduration);l>=0&&u>n.partTarget&&(l+=1)}const c=r&&lP(r);return new cP(o,l>=0?l:void 0,c)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,n){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,n){if(n)try{return n.addDirectives(e)}catch(r){this.warn(`Could not construct new URL with HLS Delivery Directives: ${r}`)}return e}playlistLoaded(e,n,r){const{details:i,stats:s}=n,a=self.performance.now(),o=s.loading.first?Math.max(0,a-s.loading.first):0;i.advancedDateTime=Date.now()-o;const l=this.hls.config.timelineOffset;if(l!==i.appliedTimelineOffset){const u=Math.max(l||0,0);i.appliedTimelineOffset=u,i.fragments.forEach(d=>{d.setStart(d.playlistOffset+u)})}if(i.live||r!=null&&r.live){const u="levelInfo"in n?n.levelInfo:n.track;if(i.reloaded(r),r&&i.fragments.length>0){Vce(r,i,this);const v=i.playlistParsingError;if(v){this.warn(v);const S=this.hls;if(!S.config.ignorePlaylistParsingErrors){var c;const{networkDetails:E}=n;S.trigger(j.ERROR,{type:ct.NETWORK_ERROR,details:xe.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:v,reason:v.message,level:n.level||void 0,parent:(c=i.fragments[0])==null?void 0:c.type,networkDetails:E,stats:s});return}i.playlistParsingError=null}}i.requestScheduled===-1&&(i.requestScheduled=s.loading.start);const d=this.hls.mainForwardBufferInfo,h=d?d.end-d.len:0,f=(i.edge-h)*1e3,p=P3(i,f);if(i.requestScheduled+p<a?i.requestScheduled=a:i.requestScheduled+=p,this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),!this.canLoad||!i.live)return;let m,g,b;if(i.canBlockReload&&i.endSN&&i.advanced){const v=this.hls.config.lowLatencyMode,S=i.lastPartSn,E=i.endSN,L=i.lastPartIndex,U=L!==-1,O=S===E;U?O?(g=E+1,b=v?0:L):(g=S,b=v?L+1:i.maxPartIndex):g=E+1;const k=i.age,I=k+i.ageHeader;let R=Math.min(I-i.partTarget,i.targetduration*1.5);if(R>0){if(I>i.targetduration*3)this.log(`Playlist last advanced ${k.toFixed(2)}s ago. Omitting segment and part directives.`),g=void 0,b=void 0;else if(r!=null&&r.tuneInGoal&&I-i.partTarget>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${R} with playlist age: ${i.age}`),R=0;else{const M=Math.floor(R/i.targetduration);if(g+=M,b!==void 0){const z=Math.round(R%i.targetduration/i.partTarget);b+=z}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${k.toFixed(2)}s goal: ${R} skip sn ${M} to part ${b}`)}i.tuneInGoal=R}if(m=this.getDeliveryDirectives(i,n.deliveryDirectives,g,b),v||!O){i.requestScheduled=a,this.loadingPlaylist(u,m);return}}else(i.canBlockReload||i.canSkipUntil)&&(m=this.getDeliveryDirectives(i,n.deliveryDirectives,g,b));m&&g!==void 0&&i.canBlockReload&&(i.requestScheduled=s.loading.first+Math.max(p-o*2,p/2)),this.scheduleLoading(u,m,i)}else this.clearTimer()}scheduleLoading(e,n,r){const i=r||e.details;if(!i){this.loadingPlaylist(e,n);return}const s=self.performance.now(),a=i.requestScheduled;if(s>=a){this.loadingPlaylist(e,n);return}const o=a-s;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,n),o)}getDeliveryDirectives(e,n,r,i){let s=lP(e);return n!=null&&n.skip&&e.deltaUpdateFailed&&(r=n.msn,i=n.part,s=ly.No),new cP(r,i,s)}checkRetry(e){const n=e.details,r=S0(e),i=e.errorAction,{action:s,retryCount:a=0,retryConfig:o}=i||{},l=!!i&&!!o&&(s===Pr.RetryRequest||!i.resolved&&s===Pr.SendAlternateToPenaltyBox);if(l){var c;if(a>=o.maxNumRetry)return!1;if(r&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${n}" without delivery-directives`),this.loadPlaylist();else{const u=UA(o,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),u),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${n}" in ${u}ms`)}e.levelRetry=!0,i.resolved=!0}return l}}function i4(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(!Lp(t[n].attrs,e[n].attrs))return!1;return!0}function Lp(t,e,n){const r=t["STABLE-RENDITION-ID"];return r&&!n?r===e["STABLE-RENDITION-ID"]:!(n||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>t[i]!==e[i])}function qE(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}class Que extends QA{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(j.MANIFEST_LOADING,this.onManifestLoading,this),e.on(j.MANIFEST_PARSED,this.onManifestParsed,this),e.on(j.LEVEL_LOADING,this.onLevelLoading,this),e.on(j.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(j.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(j.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(j.MANIFEST_LOADING,this.onManifestLoading,this),e.off(j.MANIFEST_PARSED,this.onManifestParsed,this),e.off(j.LEVEL_LOADING,this.onLevelLoading,this),e.off(j.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(j.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(j.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,n){this.tracks=n.audioTracks||[]}onAudioTrackLoaded(e,n){const{id:r,groupId:i,details:s}=n,a=this.tracksInGroup[r];if(!a||a.groupId!==i){this.warn(`Audio track with id:${r} and group:${i} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=n.details,this.log(`Audio track ${r} "${a.name}" lang:${a.lang} group:${i} loaded [${s.startSN}-${s.endSN}]`),r===this.trackId&&this.playlistLoaded(r,n,o)}onLevelLoading(e,n){this.switchLevel(n.level)}onLevelSwitching(e,n){this.switchLevel(n.level)}switchLevel(e){const n=this.hls.levels[e];if(!n)return;const r=n.audioGroups||null,i=this.groupIds;let s=this.currentTrack;if(!r||(i==null?void 0:i.length)!==(r==null?void 0:r.length)||r!=null&&r.some(o=>(i==null?void 0:i.indexOf(o))===-1)){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(h=>!r||r.indexOf(h.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(h=>h.default)&&(this.selectDefaultTrack=!1),o.forEach((h,f)=>{h.id=f});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const l=this.hls.config.audioPreference;if(!s&&l){const h=aa(l,o,tc);if(h>-1)s=o[h];else{const f=aa(l,this.tracks);s=this.tracks[f]}}let c=this.findTrackId(s);c===-1&&s&&(c=this.findTrackId(null));const u={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${r==null?void 0:r.join(",")}`),this.hls.trigger(j.AUDIO_TRACKS_UPDATED,u);const d=this.trackId;if(c!==-1&&d===-1)this.setAudioTrack(c);else if(o.length&&d===-1){var a;const h=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(h.message),this.hls.trigger(j.ERROR,{type:ct.MEDIA_ERROR,details:xe.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:h})}}}onError(e,n){n.fatal||!n.context||n.context.type===Ft.AUDIO_TRACK&&n.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(n.context.groupId)!==-1)&&this.checkRetry(n)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const n=this.hls;if(n.config.audioPreference=e,e){const r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){const i=this.currentTrack;if(i&&Ic(e,i,tc))return i;const s=aa(e,this.tracksInGroup,tc);if(s>-1){const a=this.tracksInGroup[s];return this.setAudioTrack(s),a}else if(i){let a=n.loadLevel;a===-1&&(a=n.firstAutoLevel);const o=cce(e,n.levels,r,a,tc);if(o===-1)return null;n.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=aa(e,r);if(a>-1)return r[a]}}}return null}setAudioTrack(e){const n=this.tracksInGroup;if(e<0||e>=n.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const r=this.currentTrack,i=n[e],s=i.details&&!i.details.live;if(e===this.trackId&&i===r&&s||(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(j.AUDIO_TRACK_SWITCHING,on({},i)),s))return;const a=this.switchParams(i.url,r==null?void 0:r.details,i.details);this.loadPlaylist(a)}findTrackId(e){const n=this.tracksInGroup;for(let r=0;r<n.length;r++){const i=n[r];if(!(this.selectDefaultTrack&&!i.default)&&(!e||Ic(e,i,tc)))return r}if(e){const{name:r,lang:i,assocLang:s,characteristics:a,audioCodec:o,channels:l}=e;for(let c=0;c<n.length;c++){const u=n[c];if(Ic({name:r,lang:i,assocLang:s,characteristics:a,audioCodec:o,channels:l},u,tc))return c}for(let c=0;c<n.length;c++){const u=n[c];if(Lp(e.attrs,u.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return c}for(let c=0;c<n.length;c++){const u=n[c];if(Lp(e.attrs,u.attrs,["LANGUAGE"]))return c}}return-1}loadPlaylist(e){super.loadPlaylist();const n=this.currentTrack;this.shouldLoadPlaylist(n)&&x0(n.url,this.hls)&&this.scheduleLoading(n,e)}loadingPlaylist(e,n){super.loadingPlaylist(e,n);const r=e.id,i=e.groupId,s=this.getUrlWithDirectives(e.url,n),a=e.details,o=a==null?void 0:a.age;this.log(`Loading audio-track ${r} "${e.name}" lang:${e.lang} group:${i}${(n==null?void 0:n.msn)!==void 0?" at sn "+n.msn+" part "+n.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${s}`),this.hls.trigger(j.AUDIO_TRACK_LOADING,{url:s,id:r,groupId:i,deliveryDirectives:n||null,track:e})}}class Jue{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,n,r){if(this.queues===null||this.tracks===null)return;const i=this.queues[n];i.push(e),i.length===1&&!r&&this.executeNext(n)}appendBlocker(e){return new Promise(n=>{const r={label:"async-blocker",execute:n,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(r,e)})}prependBlocker(e){return new Promise(n=>{if(this.queues){const r={label:"async-blocker-prepend",execute:n,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(r)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var n;const r=(n=e[0])==null?void 0:n.label;(r==="async-blocker"||r==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const n=this.queues[e];if(n.length){const i=n[0];try{i.execute()}catch(s){var r;if(i.onError(s),this.queues===null||this.tracks===null)return;const a=(r=this.tracks[e])==null?void 0:r.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var n;return((n=this.queues)==null?void 0:n[e][0])||null}toString(){const{queues:e,tracks:n}=this;return e===null||n===null?"<destroyed>":`
${this.list("video")}
${this.list("audio")}
${this.list("audiovideo")}}`}list(e){var n,r;return(n=this.queues)!=null&&n[e]||(r=this.tracks)!=null&&r[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var n;const r=(n=this.tracks)==null?void 0:n[e],i=r==null?void 0:r.buffer;return i?`SourceBuffer${i.updating?" updating":""}${r.ended?" ended":""}${r.ending?" ending":""}`:"none"}listOps(e){var n;return((n=this.queues)==null?void 0:n[e].map(r=>r.label).join(", "))||""}}const WP=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,s4="HlsJsTrackRemovedError";class Zue extends Error{constructor(e){super(e),this.name=s4}}class ede extends vs{constructor(e,n){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=r=>{var i;this.hls&&((i=this.mediaSource)==null?void 0:i.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=r=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=r=>{const{media:i,mediaSource:s}=this;r&&this.log("Media source opened"),!(!i||!s)&&(s.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(j.MEDIA_ATTACHED,{media:i,mediaSource:s}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:r,_objectUrl:i}=this;r!==i&&this.error(`Media element src was set while attaching MediaSource (${i} > ${r})`)},this.hls=e,this.fragmentTracker=n,this.appendSource=Sle(Cl(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(j.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(j.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(j.MANIFEST_LOADING,this.onManifestLoading,this),e.on(j.MANIFEST_PARSED,this.onManifestParsed,this),e.on(j.BUFFER_RESET,this.onBufferReset,this),e.on(j.BUFFER_APPENDING,this.onBufferAppending,this),e.on(j.BUFFER_CODECS,this.onBufferCodecs,this),e.on(j.BUFFER_EOS,this.onBufferEos,this),e.on(j.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(j.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(j.FRAG_PARSED,this.onFragParsed,this),e.on(j.FRAG_CHANGED,this.onFragChanged,this),e.on(j.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(j.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(j.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(j.MANIFEST_LOADING,this.onManifestLoading,this),e.off(j.MANIFEST_PARSED,this.onManifestParsed,this),e.off(j.BUFFER_RESET,this.onBufferReset,this),e.off(j.BUFFER_APPENDING,this.onBufferAppending,this),e.off(j.BUFFER_CODECS,this.onBufferCodecs,this),e.off(j.BUFFER_EOS,this.onBufferEos,this),e.off(j.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(j.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(j.FRAG_PARSED,this.onFragParsed,this),e.off(j.FRAG_CHANGED,this.onFragChanged,this),e.off(j.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:n}=this;if(!e)return null;const r={};if(this.operationQueue){const s=this.isUpdating();s||this.operationQueue.removeBlockers();const a=this.isQueued();(s||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${s?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===n?fn(r,i.tracks):this.sourceBuffers.forEach(s=>{const[a]=s;a&&(r[a]=fn({},this.tracks[a]),this.removeBuffer(a)),s[0]=s[1]=null}),{media:e,mediaSource:n,tracks:r}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,n){var r;let i=2;(n.audio&&!n.video||!n.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),(r=this.transferData)!=null&&r.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,n){const r=this.media=n.media;this.transferData=this.overrides=void 0;const i=Cl(this.appendSource);if(i){const s=!!n.mediaSource;(s||n.overrides)&&(this.transferData=n,this.overrides=n.overrides);const a=this.mediaSource=n.mediaSource||new i;if(this.assignMediaSource(a),s)this._objectUrl=r.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{r.removeAttribute("src");const l=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||l&&a instanceof l,YP(r),tde(r,o),r.load()}catch{r.src=o}else r.src=o}r.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var n,r;this.log(`${((n=this.transferData)==null?void 0:n.mediaSource)===e?"transferred":"created"} media source: ${(r=e.constructor)==null?void 0:r.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,n=this.transferData;if(!n||!e)return;const r=this.tracks,i=n.tracks,s=i?Object.keys(i):null,a=s?s.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&s&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
required tracks: ${yn(r,(l,c)=>l==="initSegment"?void 0:c)};
transfer tracks: ${yn(i,(l,c)=>l==="initSegment"?void 0:c)}}`),!t3(i,r)){n.mediaSource=null,n.tracks=void 0;const l=e.currentTime,c=this.details,u=Math.max(l,(c==null?void 0:c.fragments[0].start)||0);if(u-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${u}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(r)}") start time: ${u} currentTime: ${l}`),this.onMediaDetaching(j.MEDIA_DETACHING,{}),this.onMediaAttaching(j.MEDIA_ATTACHING,n),e.currentTime=u;return}this.transferData=void 0,s.forEach(l=>{const c=l,u=i[c];if(u){const d=u.buffer;if(d){const h=this.fragmentTracker,f=u.id;if(h.hasFragments(f)||h.hasParts(f)){const g=Ct.getBuffered(d);h.detectEvictedFragments(c,g,f,null,!0)}const p=Yb(c),m=[c,d];this.sourceBuffers[p]=m,d.updating&&this.operationQueue&&this.operationQueue.prependBlocker(c),this.trackSourceBuffer(c,u)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;const n=(e=this.mediaSource)==null?void 0:e.readyState;return n==="open"||n==="ended"}onMediaDetaching(e,n){const r=!!n.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:s,_objectUrl:a}=this;if(s){if(this.log(`media source ${r?"transferring":"detaching"}`),r)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=s.readyState==="open";try{const l=s.sourceBuffers;for(let c=l.length;c--;)o&&l[c].abort(),s.removeSourceBuffer(l[c]);o&&s.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}s.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("sourceended",this._onMediaSourceEnded),s.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(s.removeEventListener("startstreaming",this._onStartStreaming),s.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(i.removeEventListener("emptied",this._onMediaEmptied),r||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(i.removeAttribute("src"),this.appendSource&&YP(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(j.MEDIA_DETACHED,n)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var n;const r=(n=this.tracks[e])==null?void 0:n.buffer;if(this.removeBuffer(e),r)try{var i;(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(s){this.warn(`onBufferReset ${e}`,s)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Yb(e)]=[null,null];const n=this.tracks[e];n&&(n.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Jue(this.tracks)}onBufferCodecs(e,n){var r;const i=this.tracks,s=Object.keys(n);this.log(`BUFFER_CODECS: "${s}" (current SB count ${this.sourceBufferCount})`);const a="audiovideo"in n&&(i.audio||i.video)||i.audiovideo&&("audio"in n||"video"in n),o=!a&&this.sourceBufferCount&&this.media&&s.some(l=>!i[l]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${s}" SourceBuffers`);return}s.forEach(l=>{var c,u;const d=n[l],{id:h,codec:f,levelCodec:p,container:m,metadata:g,supplemental:b}=d;let v=i[l];const S=(c=this.transferData)==null||(c=c.tracks)==null?void 0:c[l],E=S!=null&&S.buffer?S:v,L=(E==null?void 0:E.pendingCodec)||(E==null?void 0:E.codec),U=E==null?void 0:E.levelCodec;v||(v=i[l]={buffer:void 0,listeners:[],codec:f,supplemental:b,container:m,levelCodec:p,metadata:g,id:h});const O=oy(L,U),k=O==null?void 0:O.replace(WP,"$1");let I=oy(f,p);const R=(u=I)==null?void 0:u.replace(WP,"$1");I&&O&&k!==R&&(l.slice(0,5)==="audio"&&(I=_0(I,this.appendSource)),this.log(`switching codec ${L} to ${I}`),I!==(v.pendingCodec||v.codec)&&(v.pendingCodec=I),v.container=m,this.appendChangeType(l,m,I))}),(this.tracksReady||this.sourceBufferCount)&&(n.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!n.video&&((r=n.audio)==null?void 0:r.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,n)=>{const r=this.tracks[n];return e[n]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},e},{})}appendChangeType(e,n,r){const i=`${n};codecs=${r}`,s={label:`change-type=${i}`,execute:()=>{const a=this.tracks[e];if(a){const o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),o.changeType(i),a.codec=r,a.container=n)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(s,e,this.isPending(this.tracks[e]))}blockAudio(e){var n;const r=e.start,i=r+e.duration*.05;if(((n=this.fragmentTracker.getAppendedFrag(r,tt.MAIN))==null?void 0:n.gap)===!0)return;const a={label:"block-audio",execute:()=>{var o;const l=this.tracks.video;(this.lastVideoAppendEnd>i||l!=null&&l.buffer&&Ct.isBuffered(l.buffer,i)||((o=this.fragmentTracker.getAppendedFrag(i,tt.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:a,frag:e},this.append(a,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:n}=this;e&&n&&(this.blockedAudioAppend=null,n.unblockAudio(e.op))}onBufferAppending(e,n){const{tracks:r}=this,{data:i,type:s,parent:a,frag:o,part:l,chunkMeta:c,offset:u}=n,d=c.buffering[s],{sn:h,cc:f}=o,p=self.performance.now();d.start=p;const m=o.stats.buffering,g=l?l.stats.buffering:null;m.start===0&&(m.start=p),g&&g.start===0&&(g.start=p);const b=r.audio;let v=!1;s==="audio"&&(b==null?void 0:b.container)==="audio/mpeg"&&(v=!this.lastMpegAudioChunk||c.id===1||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);const S=r.video,E=S==null?void 0:S.buffer;if(E&&h!=="initSegment"){const O=l||o,k=this.blockedAudioAppend;if(s==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(S.ending||S.ended)){const R=O.start+O.duration*.05,M=E.buffered,z=this.currentOp("video");!M.length&&!z?this.blockAudio(O):!z&&!Ct.isBuffered(E,R)&&this.lastVideoAppendEnd<R&&this.blockAudio(O)}else if(s==="video"){const I=O.end;if(k){const R=k.frag.start;(I>R||I<this.lastVideoAppendEnd||Ct.isBuffered(E,R))&&this.unblockAudio()}this.lastVideoAppendEnd=I}}const L=(l||o).start,U={label:`append-${s}`,execute:()=>{var O;d.executeStart=self.performance.now();const k=(O=this.tracks[s])==null?void 0:O.buffer;k&&(v?this.updateTimestampOffset(k,L,.1,s,h,f):u!==void 0&&Ze(u)&&this.updateTimestampOffset(k,u,1e-6,s,h,f)),this.appendExecutor(i,s)},onStart:()=>{},onComplete:()=>{const O=self.performance.now();d.executeEnd=d.end=O,m.first===0&&(m.first=O),g&&g.first===0&&(g.first=O);const k={};this.sourceBuffers.forEach(([I,R])=>{I&&(k[I]=Ct.getBuffered(R))}),this.appendErrors[s]=0,s==="audio"||s==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(j.BUFFER_APPENDED,{type:s,frag:o,part:l,chunkMeta:c,parent:o.type,timeRanges:k})},onError:O=>{var k;const I={type:ct.MEDIA_ERROR,parent:o.type,details:xe.BUFFER_APPEND_ERROR,sourceBufferName:s,frag:o,part:l,chunkMeta:c,error:O,err:O,fatal:!1},R=(k=this.media)==null?void 0:k.error;if(O.code===DOMException.QUOTA_EXCEEDED_ERR||O.name=="QuotaExceededError"||"quota"in O)I.details=xe.BUFFER_FULL_ERROR;else if(O.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!R)I.errorAction=vd(!0);else if(O.name===s4&&this.sourceBufferCount===0)I.errorAction=vd(!0);else{const M=++this.appendErrors[s];this.warn(`Failed ${M}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${s}" sourceBuffer (${R||"no media error"})`),(M>=this.hls.config.appendErrorMaxRetry||R)&&(I.fatal=!0)}this.hls.trigger(j.ERROR,I)}};this.log(`queuing "${s}" append sn: ${h}${l?" p: "+l.index:""} of ${o.type===tt.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(U,s,this.isPending(this.tracks[s]))}getFlushOp(e,n,r){return this.log(`queuing "${e}" remove ${n}-${r}`),{label:"remove",execute:()=>{this.removeExecutor(e,n,r)},onStart:()=>{},onComplete:()=>{this.hls.trigger(j.BUFFER_FLUSHED,{type:e})},onError:i=>{this.warn(`Failed to remove ${n}-${r} from "${e}" SourceBuffer`,i)}}}onBufferFlushing(e,n){const{type:r,startOffset:i,endOffset:s}=n;r?this.append(this.getFlushOp(r,i,s),r):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,i,s),a)})}onFragParsed(e,n){const{frag:r,part:i}=n,s=[],a=i?i.elementaryStreams:r.elementaryStreams;a[pn.AUDIOVIDEO]?s.push("audiovideo"):(a[pn.AUDIO]&&s.push("audio"),a[pn.VIDEO]&&s.push("video"));const o=()=>{const l=self.performance.now();r.stats.buffering.end=l,i&&(i.stats.buffering.end=l);const c=i?i.stats:r.stats;this.hls.trigger(j.FRAG_BUFFERED,{frag:r,part:i,stats:c,id:r.type})};s.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${r.type} level: ${r.level} sn: ${r.sn}`),this.blockBuffers(o,s).catch(l=>{this.warn(`Fragment buffered callback ${l}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,n){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const n=this.tracks[e];if(n)return!n.ended||n.ending}return!1})}onBufferEos(e,n){var r;this.sourceBuffers.forEach(([a])=>{if(a){const o=this.tracks[a];(!n.type||n.type===a)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${a} buffer reached EOS`)))}});const i=((r=this.overrides)==null?void 0:r.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})?i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:a}=this;if(!a||a.readyState!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(j.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(j.BUFFERED_TO_END,void 0)):n.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const n=this.tracks[e];n&&(n.ending=!1)}})}onLevelUpdated(e,{details:n}){n.fragments.length&&(this.details=n,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,n){if(n.details===xe.BUFFER_APPEND_ERROR&&n.frag){var r;const i=(r=n.errorAction)==null?void 0:r.nextAutoLevel;Ze(i)&&i!==n.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:n,media:r}=this;if(!r||n===null||!this.sourceBufferCount)return;const i=e.config,s=r.currentTime,a=n.levelTargetDuration,o=n.live&&i.liveBackBufferLength!==null?i.liveBackBufferLength:i.backBufferLength;if(Ze(o)&&o>=0){const c=Math.max(o,a),u=Math.floor(s/a)*a-c;this.flushBackBuffer(s,a,u)}const l=i.frontBufferFlushThreshold;if(Ze(l)&&l>0){const c=Math.max(i.maxBufferLength,l),u=Math.max(c,a),d=Math.floor(s/a)*a+u;this.flushFrontBuffer(s,a,d)}}flushBackBuffer(e,n,r){this.sourceBuffers.forEach(([i,s])=>{if(s){const o=Ct.getBuffered(s);if(o.length>0&&r>o.start(0)){var a;this.hls.trigger(j.BACK_BUFFER_REACHED,{bufferEnd:r});const l=this.tracks[i];if((a=this.details)!=null&&a.live)this.hls.trigger(j.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(l!=null&&l.ended){this.log(`Cannot flush ${i} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(j.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:i})}}})}flushFrontBuffer(e,n,r){this.sourceBuffers.forEach(([i,s])=>{if(s){const a=Ct.getBuffered(s),o=a.length;if(o<2)return;const l=a.start(o-1),c=a.end(o-1);if(r>l||e>=l&&e<=c)return;this.hls.trigger(j.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:i})}})}getDurationAndRange(){var e;const{details:n,mediaSource:r}=this;if(!n||!this.media||(r==null?void 0:r.readyState)!=="open")return null;const i=n.edge;if(n.live&&this.hls.config.liveDurationInfinity){if(n.fragments.length&&r.setLiveSeekableRange){const c=Math.max(0,n.fragmentStart),u=Math.max(c,i);return{duration:1/0,start:c,end:u}}return{duration:1/0}}const s=(e=this.overrides)==null?void 0:e.duration;if(s)return Ze(s)?{duration:s}:null;const a=this.media.duration,o=Ze(r.duration)?r.duration:0;return i>o&&i>a||!Ze(a)?{duration:i}:null}updateMediaSource({duration:e,start:n,end:r}){const i=this.mediaSource;!this.media||!i||i.readyState!=="open"||(i.duration!==e&&(Ze(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),n!==void 0&&r!==void 0&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${n}-${r}.`),i.setLiveSeekableRange(n,r)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:n,tracks:r}=this;if(this.log(`checkPendingTracks (pending: ${n} codec events expected: ${e}) ${yn(r)}`),this.tracksReady){var i;const s=(i=this.transferData)==null?void 0:i.tracks;s&&Object.keys(s).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([n,r])=>{if(n){const i=this.tracks[n];e[n]={buffer:r,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(j.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([n])=>{this.executeNext(n)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(j.ERROR,{type:ct.MEDIA_ERROR,details:xe.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:n,mediaSource:r}=this;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(const s in e){const a=s,o=e[a];if(this.isPending(o)){const l=this.getTrackCodec(o,a),c=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${c})${this.currentOp(a)?" Queued":""} ${yn(o)}`);try{const u=r.addSourceBuffer(c),d=Yb(a),h=[a,u];n[d]=h,o.buffer=u}catch(u){var i;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(a),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[a],this.hls.trigger(j.ERROR,{type:ct.MEDIA_ERROR,details:xe.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:a,mimeType:c,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(e,n){const r=e.supplemental;let i=e.codec;r&&(n==="video"||n==="audiovideo")&&Ep(r,"video")&&(i=Hle(i,r));const s=oy(i,e.levelCodec);return s?n.slice(0,5)==="audio"?_0(s,this.appendSource):s:""}trackSourceBuffer(e,n){const r=n.buffer;if(!r)return;const i=this.getTrackCodec(n,e);this.tracks[e]={buffer:r,codec:i,container:n.container,levelCodec:n.levelCodec,supplemental:n.supplemental,metadata:n.metadata,id:n.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(s,a)=>{const o=a.removedRanges;o!=null&&o.length&&this.hls.trigger(j.BUFFER_FLUSHED,{type:s})})}get mediaSrc(){var e,n;const r=((e=this.media)==null||(n=e.querySelector)==null?void 0:n.call(e,"source"))||this.media;return r==null?void 0:r.src}onSBUpdateStart(e){const n=this.currentOp(e);n&&n.onStart()}onSBUpdateEnd(e){var n;if(((n=this.mediaSource)==null?void 0:n.readyState)==="closed"){this.resetBuffer(e);return}const r=this.currentOp(e);r&&(r.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,n){var r;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(r=this.mediaSource)==null?void 0:r.readyState}`);this.error(`${i}`,n),this.hls.trigger(j.ERROR,{type:ct.MEDIA_ERROR,details:xe.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const s=this.currentOp(e);s&&s.onError(i)}updateTimestampOffset(e,n,r,i,s,a){const o=n-e.timestampOffset;Math.abs(o)>=r&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${n} (sn: ${s} cc: ${a})`),e.timestampOffset=n)}removeExecutor(e,n,r){const{media:i,mediaSource:s}=this,a=this.tracks[e],o=a==null?void 0:a.buffer;if(!i||!s||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const l=Ze(i.duration)?i.duration:1/0,c=Ze(s.duration)?s.duration:1/0,u=Math.max(0,n),d=Math.min(r,l,c);d>u&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${u},${d}] from the ${e} SourceBuffer`),o.remove(u,d)):this.shiftAndExecuteNext(e)}appendExecutor(e,n){const r=this.tracks[n],i=r==null?void 0:r.buffer;if(!i)throw new Zue(`Attempting to append to the ${n} SourceBuffer, but it does not exist`);r.ending=!1,r.ended=!1,i.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(n=>{this.warn(`SourceBuffer blocked callback ${n}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(n){this.warn(`Callback run without blocking ${this.operationQueue} ${n}`)}}isUpdating(){return this.sourceBuffers.some(([e,n])=>e&&n.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,n=this.sourceBufferTypes){if(!n.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:r}=this,i=n.map(a=>this.appendBlocker(a));return n.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then(a=>{r===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(n=>{var r;const i=(r=this.tracks[n])==null?void 0:r.buffer;!i||i.updating||this.shiftAndExecuteNext(n)})}append(e,n,r){this.operationQueue&&this.operationQueue.append(e,n,r)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,n)=>e+(this.isPending(this.tracks[n])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[n])=>e+(n?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,n,r){const i=this.tracks[e];if(!i)return;const s=i.buffer;if(!s)return;const a=r.bind(this,e);i.listeners.push({event:n,listener:a}),s.addEventListener(n,a)}removeBufferListeners(e){const n=this.tracks[e];if(!n)return;const r=n.buffer;r&&(n.listeners.forEach(i=>{r.removeEventListener(i.event,i.listener)}),n.listeners.length=0)}}function YP(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(n=>{t.removeChild(n)})}function tde(t,e){const n=self.document.createElement("source");n.type="video/mp4",n.src=e,t.appendChild(n)}function Yb(t){return t==="audio"?1:0}class JA{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(j.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(j.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(j.MANIFEST_PARSED,this.onManifestParsed,this),e.on(j.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(j.BUFFER_CODECS,this.onBufferCodecs,this),e.on(j.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(j.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(j.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(j.MANIFEST_PARSED,this.onManifestParsed,this),e.off(j.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(j.BUFFER_CODECS,this.onBufferCodecs,this),e.off(j.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,n){const r=this.hls.levels[n.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}onMediaAttaching(e,n){this.media=n.media instanceof HTMLVideoElement?n.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,n){const r=this.hls;this.restrictedLevels=[],this.firstLevel=n.firstLevel,r.config.capLevelToPlayerSize&&n.video&&this.startCapping()}onLevelsUpdated(e,n){this.timer&&Ze(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,n){this.hls.config.capLevelToPlayerSize&&n.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const n=this.hls,r=this.getMaxLevel(e.length-1);r!==this.autoLevelCapping&&n.logger.log(`Setting autoLevelCapping to ${r}: ${e[r].height}p@${e[r].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),n.autoLevelCapping=r,n.autoLevelEnabled&&n.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=n.autoLevelCapping}}}getMaxLevel(e){const n=this.hls.levels;if(!n.length)return-1;const r=n.filter((i,s)=>this.isLevelAllowed(i)&&s<=e);return this.clientRect=null,JA.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,n={width:0,height:0};if(e){const r=e.getBoundingClientRect();n.width=r.width,n.height=r.height,!n.width&&!n.height&&(n.width=r.right-r.left||e.width||0,n.height=r.bottom-r.top||e.height||0)}return this.clientRect=n,n}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(r=>e.bitrate===r.bitrate&&e.width===r.width&&e.height===r.height)}static getMaxLevelByMediaSize(e,n,r){if(!(e!=null&&e.length))return-1;const i=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let s=e.length-1;const a=Math.max(n,r);for(let o=0;o<e.length;o+=1){const l=e[o];if((l.width>=a||l.height>=a)&&i(l,e[o+1])){s=o;break}}return s}}const nde={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},hi=nde,rde={HLS:"h"},ide=rde;class ga{constructor(e,n){Array.isArray(e)&&(e=e.map(r=>r instanceof ga?r:new ga(r))),this.value=e,this.params=n}}const sde="Dict";function ade(t){return Array.isArray(t)?JSON.stringify(t):t instanceof Map?"Map{}":t instanceof Set?"Set{}":typeof t=="object"?JSON.stringify(t):String(t)}function ode(t,e,n,r){return new Error(`failed to ${t} "${ade(e)}" as ${n}`,{cause:r})}function ya(t,e,n){return ode("serialize",t,e,n)}class a4{constructor(e){this.description=e}}const XP="Bare Item",lde="Boolean";function cde(t){if(typeof t!="boolean")throw ya(t,lde);return t?"?1":"?0"}function ude(t){return btoa(String.fromCharCode(...t))}const dde="Byte Sequence";function hde(t){if(ArrayBuffer.isView(t)===!1)throw ya(t,dde);return`:${ude(t)}:`}const fde="Integer";function pde(t){return t<-999999999999999||999999999999999<t}function o4(t){if(pde(t))throw ya(t,fde);return t.toString()}function mde(t){return`@${o4(t.getTime()/1e3)}`}function l4(t,e){if(t<0)return-l4(-t,e);const n=Math.pow(10,e);if(Math.abs(t*n%1-.5)<Number.EPSILON){const i=Math.floor(t*n);return(i%2===0?i:i+1)/n}else return Math.round(t*n)/n}const gde="Decimal";function yde(t){const e=l4(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw ya(t,gde);const n=e.toString();return n.includes(".")?n:`${n}.0`}const vde="String",_de=/[\x00-\x1f\x7f]+/;function bde(t){if(_de.test(t))throw ya(t,vde);return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function xde(t){return t.description||t.toString().slice(7,-1)}const Sde="Token";function QP(t){const e=xde(t);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw ya(e,Sde);return e}function WE(t){switch(typeof t){case"number":if(!Ze(t))throw ya(t,XP);return Number.isInteger(t)?o4(t):yde(t);case"string":return bde(t);case"symbol":return QP(t);case"boolean":return cde(t);case"object":if(t instanceof Date)return mde(t);if(t instanceof Uint8Array)return hde(t);if(t instanceof a4)return QP(t);default:throw ya(t,XP)}}const Ede="Key";function YE(t){if(/^[a-z*][a-z0-9\-_.*]*$/.test(t)===!1)throw ya(t,Ede);return t}function ZA(t){return t==null?"":Object.entries(t).map(([e,n])=>n===!0?`;${YE(e)}`:`;${YE(e)}=${WE(n)}`).join("")}function c4(t){return t instanceof ga?`${WE(t.value)}${ZA(t.params)}`:WE(t)}function wde(t){return`(${t.value.map(c4).join(" ")})${ZA(t.params)}`}function Tde(t,e={whitespace:!0}){if(typeof t!="object"||t==null)throw ya(t,sde);const n=t instanceof Map?t.entries():Object.entries(t),r=e!=null&&e.whitespace?" ":"";return Array.from(n).map(([i,s])=>{s instanceof ga||(s=new ga(s));let a=YE(i);return s.value===!0?a+=ZA(s.params):(a+="=",Array.isArray(s.value)?a+=wde(s):a+=c4(s)),a}).join(`,${r}`)}function u4(t,e){return Tde(t,e)}const Hs="CMCD-Object",Fn="CMCD-Request",ql="CMCD-Session",Co="CMCD-Status",Ade={br:Hs,ab:Hs,d:Hs,ot:Hs,tb:Hs,tpb:Hs,lb:Hs,tab:Hs,lab:Hs,url:Hs,pb:Fn,bl:Fn,tbl:Fn,dl:Fn,ltc:Fn,mtp:Fn,nor:Fn,nrr:Fn,rc:Fn,sn:Fn,sta:Fn,su:Fn,ttfb:Fn,ttfbb:Fn,ttlb:Fn,cmsdd:Fn,cmsds:Fn,smrt:Fn,df:Fn,cs:Fn,ts:Fn,cid:ql,pr:ql,sf:ql,sid:ql,st:ql,v:ql,msd:ql,bs:Co,bsd:Co,cdn:Co,rtp:Co,bg:Co,pt:Co,ec:Co,e:Co},Rde={REQUEST:Fn};function Cde(t){return Object.keys(t).reduce((e,n)=>{var r;return(r=t[n])===null||r===void 0||r.forEach(i=>e[i]=n),e},{})}function Lde(t,e){const n={};if(!t)return n;const r=Object.keys(t),i=e?Cde(e):{};return r.reduce((s,a)=>{var o;const l=Ade[a]||i[a]||Rde.REQUEST,c=(o=s[l])!==null&&o!==void 0?o:s[l]={};return c[a]=t[a],s},n)}function kde(t){return["ot","sf","st","e","sta"].includes(t)}function Ide(t){return typeof t=="number"?Ze(t):t!=null&&t!==""&&t!==!1}const d4="event";function Pde(t,e){const n=new URL(t),r=new URL(e);if(n.origin!==r.origin)return t;const i=n.pathname.split("/").slice(1),s=r.pathname.split("/").slice(1,-1);for(;i[0]===s[0];)i.shift(),s.shift();for(;s.length;)s.shift(),i.unshift("..");return i.join("/")+n.search+n.hash}const hy=t=>Math.round(t),XE=(t,e)=>Array.isArray(t)?t.map(n=>XE(n,e)):t instanceof ga&&typeof t.value=="string"?new ga(XE(t.value,e),t.params):(e.baseUrl&&(t=Pde(t,e.baseUrl)),e.version===1?encodeURIComponent(t):t),Tg=t=>hy(t/100)*100,Dde=(t,e)=>{let n=t;return e.version>=2&&(t instanceof ga&&typeof t.value=="string"?n=new ga([t]):typeof t=="string"&&(n=[t])),XE(n,e)},Ode={br:hy,d:hy,bl:Tg,dl:Tg,mtp:Tg,nor:Dde,rtp:Tg,tb:hy},h4="request",f4="response",e1=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],Nde=["e"],Mde=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Dv(t){return Mde.test(t)}function Bde(t){return e1.includes(t)||Nde.includes(t)||Dv(t)}const p4=["d","dl","nor","ot","rtp","su"];function Ude(t){return e1.includes(t)||p4.includes(t)||Dv(t)}const jde=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function Fde(t){return e1.includes(t)||p4.includes(t)||jde.includes(t)||Dv(t)}const $de=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function Vde(t){return $de.includes(t)||Dv(t)}const Gde={[f4]:Fde,[d4]:Bde,[h4]:Ude};function m4(t,e={}){const n={};if(t==null||typeof t!="object")return n;const r=e.version||t.v||1,i=e.reportingMode||h4,s=r===1?Vde:Gde[i];let a=Object.keys(t).filter(s);const o=e.filter;typeof o=="function"&&(a=a.filter(o));const l=i===f4||i===d4;l&&!a.includes("ts")&&a.push("ts"),r>1&&!a.includes("v")&&a.push("v");const c=fn({},Ode,e.formatters),u={version:r,reportingMode:i,baseUrl:e.baseUrl};return a.sort().forEach(d=>{let h=t[d];const f=c[d];if(typeof f=="function"&&(h=f(h,u)),d==="v"){if(r===1)return;h=r}d=="pr"&&h===1||(l&&d==="ts"&&!Ze(h)&&(h=Date.now()),Ide(h)&&(kde(d)&&typeof h=="string"&&(h=new a4(h)),n[d]=h))}),n}function Hde(t,e={}){const n={};if(!t)return n;const r=m4(t,e),i=Lde(r,e==null?void 0:e.customHeaderMap);return Object.entries(i).reduce((s,[a,o])=>{const l=u4(o,{whitespace:!1});return l&&(s[a]=l),s},n)}function Kde(t,e,n){return fn(t,Hde(e,n))}const zde="CMCD";function qde(t,e={}){return t?u4(m4(t,e),{whitespace:!1}):""}function Wde(t,e={}){if(!t)return"";const n=qde(t,e);return encodeURIComponent(n)}function Yde(t,e={}){if(!t)return"";const n=Wde(t,e);return`${zde}=${n}`}const JP=/CMCD=[^&#]+/;function Xde(t,e,n){const r=Yde(e,n);if(!r)return t;if(JP.test(t))return t.replace(JP,r);const i=t.includes("?")?"&":"?";return`${t}${i}${r}`}class Qde{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=i=>{try{this.apply(i,{ot:hi.MANIFEST,su:!this.initialized})}catch(s){this.hls.logger.warn("Could not generate manifest CMCD data.",s)}},this.applyFragmentData=i=>{try{const{frag:s,part:a}=i,o=this.hls.levels[s.level],l=this.getObjectType(s),c={d:(a||s).duration*1e3,ot:l};(l===hi.VIDEO||l===hi.AUDIO||l==hi.MUXED)&&(c.br=o.bitrate/1e3,c.tb=this.getTopBandwidth(l)/1e3,c.bl=this.getBufferLength(l));const u=a?this.getNextPart(a):this.getNextFrag(s);u!=null&&u.url&&u.url!==s.url&&(c.nor=u.url),this.apply(i,c)}catch(s){this.hls.logger.warn("Could not generate segment CMCD data.",s)}},this.hls=e;const n=this.config=e.config,{cmcd:r}=n;r!=null&&(n.pLoader=this.createPlaylistLoader(),n.fLoader=this.createFragmentLoader(),this.sid=r.sessionId||e.sessionId,this.cid=r.contentId,this.useHeaders=r.useHeaders===!0,this.includeKeys=r.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(j.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(j.MEDIA_DETACHED,this.onMediaDetached,this),e.on(j.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(j.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(j.MEDIA_DETACHED,this.onMediaDetached,this),e.off(j.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,n){this.media=n.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,n){var r,i;this.audioBuffer=(r=n.tracks.audio)==null?void 0:r.buffer,this.videoBuffer=(i=n.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:1,sf:ide.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,n={}){fn(n,this.createData());const r=n.ot===hi.INIT||n.ot===hi.VIDEO||n.ot===hi.MUXED;this.starved&&r&&(n.bs=!0,n.su=!0,this.starved=!1),n.su==null&&(n.su=this.buffering);const{includeKeys:i}=this;i&&(n=Object.keys(n).reduce((a,o)=>(i.includes(o)&&(a[o]=n[o]),a),{}));const s={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),Kde(e.headers,n,s)):e.url=Xde(e.url,n,s)}getNextFrag(e){var n;const r=(n=this.hls.levels[e.level])==null?void 0:n.details;if(r){const i=e.sn-r.startSN;return r.fragments[i+1]}}getNextPart(e){var n;const{index:r,fragment:i}=e,s=(n=this.hls.levels[i.level])==null||(n=n.details)==null?void 0:n.partList;if(s){const{sn:a}=i;for(let o=s.length-1;o>=0;o--){const l=s[o];if(l.index===r&&l.fragment.sn===a)return s[o+1]}}}getObjectType(e){const{type:n}=e;if(n==="subtitle")return hi.TIMED_TEXT;if(e.sn==="initSegment")return hi.INIT;if(n==="audio")return hi.AUDIO;if(n==="main")return this.hls.audioTracks.length?hi.VIDEO:hi.MUXED}getTopBandwidth(e){let n=0,r;const i=this.hls;if(e===hi.AUDIO)r=i.audioTracks;else{const s=i.maxAutoLevel,a=s>-1?s+1:i.levels.length;r=i.levels.slice(0,a)}return r.forEach(s=>{s.bitrate>n&&(n=s.bitrate)}),n>0?n:NaN}getBufferLength(e){const n=this.media,r=e===hi.AUDIO?this.audioBuffer:this.videoBuffer;return!r||!n?NaN:Ct.bufferInfo(r,n.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,n=this.applyPlaylistData,r=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new r(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,a,o){n(s),this.loader.load(s,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,n=this.applyFragmentData,r=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new r(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,a,o){n(s),this.loader.load(s,a,o)}}}}const Jde=3e5;class Zde extends vs{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(j.MANIFEST_LOADING,this.onManifestLoading,this),e.on(j.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(j.MANIFEST_PARSED,this.onManifestParsed,this),e.on(j.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(j.MANIFEST_LOADING,this.onManifestLoading,this),e.off(j.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(j.MANIFEST_PARSED,this.onManifestParsed,this),e.off(j.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,n)=>(e.indexOf(n.pathwayId)===-1&&e.push(n.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const n=this.levels;n&&(this.levels=n.filter(r=>r!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,n){const{contentSteering:r}=n;r!==null&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}onManifestParsed(e,n){this.audioTracks=n.audioTracks,this.subtitleTracks=n.subtitleTracks}onError(e,n){const{errorAction:r}=n;if((r==null?void 0:r.action)===Pr.SendAlternateToPenaltyBox&&r.flags===Li.MoveAllAlternatesMatchingHost){const i=this.levels;let s=this._pathwayPriority,a=this.pathwayId;if(n.context){const{groupId:o,pathwayId:l,type:c}=n.context;o&&i?a=this.getPathwayForGroupId(o,c,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!s&&i&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),r.resolved=this.pathwayId!==a),n.details===xe.BUFFER_APPEND_ERROR&&!n.fatal?r.resolved=!0:r.resolved||this.warn(`Could not resolve ${n.details} ("${n.error.message}") with content-steering for Pathway: ${a} levels: ${i&&i.length} priorities: ${yn(s)} penalized: ${yn(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let n=this.getLevelsForPathway(this.pathwayId);if(n.length===0){const r=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${r}"`),n=this.getLevelsForPathway(r),this.pathwayId=r}return n.length!==e.length&&this.log(`Found ${n.length}/${e.length} levels in Pathway "${this.pathwayId}"`),n}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(n=>e===n.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let n;const r=this.penalizedPathways,i=performance.now();Object.keys(r).forEach(s=>{i-r[s]>Jde&&delete r[s]});for(let s=0;s<e.length;s++){const a=e[s];if(a in r)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(n=this.getLevelsForPathway(a),n.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,N3(n),this.hls.trigger(j.LEVELS_UPDATED,{levels:n});const c=this.hls.levels[o];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,n,r){const i=this.getLevelsForPathway(r).concat(this.levels||[]);for(let s=0;s<i.length;s++)if(n===Ft.AUDIO_TRACK&&i[s].hasAudioGroup(e)||n===Ft.SUBTITLE_TRACK&&i[s].hasSubtitleGroup(e))return i[s].pathwayId;return r}clonePathways(e){const n=this.levels;if(!n)return;const r={},i={};e.forEach(s=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=s;if(n.some(u=>u.pathwayId===a))return;const c=this.getLevelsForPathway(o).map(u=>{const d=new Mn(u.attrs);d["PATHWAY-ID"]=a;const h=d.AUDIO&&`${d.AUDIO}_clone_${a}`,f=d.SUBTITLES&&`${d.SUBTITLES}_clone_${a}`;h&&(r[d.AUDIO]=h,d.AUDIO=h),f&&(i[d.SUBTITLES]=f,d.SUBTITLES=f);const p=g4(u.uri,d["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),m=new Tp({attrs:d,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:p,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let g=1;g<u.audioGroups.length;g++)m.addGroupId("audio",`${u.audioGroups[g]}_clone_${a}`);if(u.subtitleGroups)for(let g=1;g<u.subtitleGroups.length;g++)m.addGroupId("text",`${u.subtitleGroups[g]}_clone_${a}`);return m});n.push(...c),ZP(this.audioTracks,r,l,a),ZP(this.subtitleTracks,i,l,a)})}loadSteeringManifest(e){const n=this.hls.config,r=n.loader;this.loader&&this.loader.destroy(),this.loader=new r(n);let i;try{i=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(i.protocol!=="data:"){const u=(this.hls.bandwidthEstimate||n.abrEwmaDefaultEstimate)|0;i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+u)}const s={responseType:"json",url:i.href},a=n.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(u,d,h,f)=>{this.log(`Loaded steering manifest: "${i}"`);const p=u.data;if((p==null?void 0:p.VERSION)!==1){this.log(`Steering VERSION ${p.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=p.TTL;const{"RELOAD-URI":m,"PATHWAY-CLONES":g,"PATHWAY-PRIORITY":b}=p;if(m)try{this.uri=new self.URL(m,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${m}`);return}this.scheduleRefresh(this.uri||h.url),g&&this.clonePathways(g);const v={steeringManifest:p,url:i.toString()};this.hls.trigger(j.STEERING_MANIFEST_LOADED,v),b&&this.updatePathwayPriority(b)},onError:(u,d,h,f)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${d.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${d.url} no longer available`);return}let p=this.timeToLoad*1e3;if(u.code===429){const m=this.loader;if(typeof(m==null?void 0:m.getResponseHeader)=="function"){const g=m.getResponseHeader("Retry-After");g&&(p=parseFloat(g)*1e3)}this.log(`Steering manifest ${d.url} rate limited`);return}this.scheduleRefresh(this.uri||d.url,p)},onTimeout:(u,d,h)=>{this.log(`Timeout loading steering manifest (${d.url})`),this.scheduleRefresh(this.uri||d.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(s,l,c)}scheduleRefresh(e,n=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var r;const i=(r=this.hls)==null?void 0:r.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},n)}}function ZP(t,e,n,r){t&&Object.keys(e).forEach(i=>{const s=t.filter(a=>a.groupId===i).map(a=>{const o=fn({},a);return o.details=void 0,o.attrs=new Mn(o.attrs),o.url=o.attrs.URI=g4(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",n),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=r,o});t.push(...s)})}function g4(t,e,n,r){const{HOST:i,PARAMS:s,[n]:a}=r;let o;e&&(o=a==null?void 0:a[e],o&&(t=o));const l=new self.URL(t);return i&&!o&&(l.host=i),s&&Object.keys(s).sort().forEach(c=>{c&&l.searchParams.set(c,s[c])}),l.href}class bd extends vs{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=bd.CDMCleanupPromise?[bd.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=n=>{const{initDataType:r,initData:i}=n,s=`"${n.type}" event: init data type: "${r}"`;if(this.debug(s),i!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=sf(this.config));const o=a.map($b).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{const o=cy(a);if(r!=="sinf"||o!==Bn.FAIRPLAY){this.log(`Ignoring "${n.type}" event with init data type: "${r}" for selected key-system ${o}`);return}let l;try{const f=hr(new Uint8Array(i)),p=VA(JSON.parse(f).sinf),m=u3(p);if(!m)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");l=new Uint8Array(m.subarray(8,24))}catch(f){this.warn(`${s} Failed to parse sinf: ${f}`);return}const c=Dr(l),{keyIdToKeySessionPromise:u,mediaKeySessions:d}=this;let h=u[c];for(let f=0;f<d.length;f++){const p=d[f],m=p.decryptdata;if(!m.keyId)continue;const g=Dr(m.keyId);if(w0(l,m.keyId)||m.uri.replace(/-/g,"").indexOf(c)!==-1){if(h=u[g],!h)continue;if(m.pssh)break;delete u[g],m.pssh=new Uint8Array(i),m.keyId=l,h=u[c]=h.then(()=>this.generateRequestWithPreferredKeySession(p,r,i,"encrypted-event-key-match")),h.catch(b=>this.handleError(b));break}}h||this.handleError(new Error(`Key ID ${c} not encountered in playlist. Key-system sessions ${d.length}.`))}).catch(a=>this.handleError(a))}},this.onWaitingForKey=n=>{this.log(`"${n.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(j.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(j.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(j.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(j.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(j.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(j.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(j.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(j.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(j.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(j.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:n,widevineLicenseUrl:r}=this.config,i=n==null?void 0:n[e];if(i)return i.licenseUrl;if(e===Bn.WIDEVINE&&r)return r}getLicenseServerUrlOrThrow(e){const n=this.getLicenseServerUrl(e);if(n===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return n}getServerCertificateUrl(e){const{drmSystems:n}=this.config,r=n==null?void 0:n[e];if(r)return r.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const n=this.hls.levels,r=(a,o,l)=>!!a&&l.indexOf(a)===o,i=n.map(a=>a.audioCodec).filter(r),s=n.map(a=>a.videoCodec).filter(r);return i.length+s.length===0&&s.push("avc1.42e01e"),new Promise((a,o)=>{const l=c=>{const u=c.shift();this.getMediaKeysPromise(u,i,s).then(d=>a({keySystem:u,mediaKeys:d})).catch(d=>{c.length?l(c):d instanceof Ci?o(d):o(new Ci({type:ct.KEY_SYSTEM_ERROR,details:xe.KEY_SYSTEM_NO_ACCESS,error:d,fatal:!0},d.message))})};l(e)})}requestMediaKeySystemAccess(e,n){const{requestMediaKeySystemAccessFunc:r}=this.config;if(typeof r!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${r}`;return R3===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return r(e,n)}getMediaKeysPromise(e,n,r){var i;const s=Dce(e,n,r,this.config.drmSystemOptions||{});let a=this.keySystemAccessPromises[e],o=(i=a)==null?void 0:i.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${yn(s)}`),o=this.requestMediaKeySystemAccess(e,s);const l=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(c=>{this.log(`Failed to obtain access to key-system "${e}": ${c}`)}),o.then(c=>{this.log(`Access for key-system "${c.keySystem}" obtained`);const u=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const d=l.mediaKeys=c.createMediaKeys().then(h=>(this.log(`Media-keys created for "${e}"`),l.hasMediaKeys=!0,u.then(f=>f?this.setMediaKeysServerCertificate(h,e,f):h)));return d.catch(h=>{this.error(`Failed to create media-keys for "${e}"}: ${h}`)}),d})}return o.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:n,mediaKeys:r}){this.log(`Creating key-system session "${n}" keyId: ${Dr(e.keyId||[])} keyUri: ${e.uri}`);const i=r.createSession(),s={decryptdata:e,keySystem:n,mediaKeys:r,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){const n=e.decryptdata;if(n.pssh){const r=this.createMediaKeySessionContext(e),i=Ag(n),s="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(r,s,n.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,n){const r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyId ${Dr(e.decryptdata.keyId||[])}
      } (data length: ${n.byteLength})`),r.update(n)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>$b(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:n,mediaKeys:r})=>this.attemptSetMediaKeys(n,r))}selectKeySystem(e){return new Promise((n,r)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:i})=>{const s=$b(i);s?n(s):r(new Error(`Unable to find format for key-system "${i}"`))}).catch(r)})}selectKeySystemFormat(e){const n=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${n.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(n)),this.keyFormatPromise}getKeyFormatPromise(e){const n=sf(this.config),r=e.map(cy).filter(i=>!!i&&n.indexOf(i)!==-1);return this.selectKeySystem(r)}getKeyStatus(e){const{mediaKeySessions:n}=this;for(let r=0;r<n.length;r++){const i=ehe(e,n[r]);if(i)return i}}loadKey(e){const n=e.keyInfo.decryptdata,r=Ag(n),i=this.bannedKeyIds[r];if(i||this.getKeyStatus(n)==="internal-error"){const o=eD(i||"internal-error",n);return this.handleError(o,e.frag),Promise.reject(o)}const s=`(keyId: ${r} format: "${n.keyFormat}" method: ${n.method} uri: ${n.uri})`;this.log(`Starting session for key ${s}`);const a=this.keyIdToKeySessionPromise[r];if(!a){const o=this.getKeySystemForKeyPromise(n).then(({keySystem:l,mediaKeys:c})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${s}`),this.attemptSetMediaKeys(l,c).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:l,mediaKeys:c,decryptdata:n}))))).then(l=>{const c="cenc",u=n.pssh?n.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(l,c,u,"playlist-key")});return o.catch(l=>this.handleError(l,e.frag)),this.keyIdToKeySessionPromise[r]=o,o}return a.catch(o=>{if(o instanceof Ci){const l=on({},o.data);this.getKeyStatus(n)==="internal-error"&&(l.decryptdata=n);const c=new Ci(l,o.message);this.handleError(c,e.frag)}}),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,n){if(this.hls)if(e instanceof Ci){n&&(e.data.frag=n);const r=e.data.decryptdata;this.error(`${e.message}${r?` (${Dr(r.keyId||[])})`:""}`),this.hls.trigger(j.ERROR,e.data)}else this.error(e.message),this.hls.trigger(j.ERROR,{type:ct.KEY_SYSTEM_ERROR,details:xe.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const n=Ag(e),r=this.keyIdToKeySessionPromise[n];if(!r){const i=cy(e.keyFormat),s=i?[i]:sf(this.config);return this.attemptKeySystemAccess(s)}return r}getKeySystemSelectionPromise(e){if(e.length||(e=sf(this.config)),e.length===0)throw new Ci({type:ct.KEY_SYSTEM_ERROR,details:xe.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${yn({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,n){if(this.mediaResolved=void 0,this.mediaKeys===n)return Promise.resolve();const r=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(r).then(()=>this.media?this.media.setMediaKeys(n):new Promise((s,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=n,this.media.setMediaKeys(n).then(s).catch(a)}}));return this.mediaKeys=n,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),r.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(s=>r.indexOf(s)===-1)})}generateRequestWithPreferredKeySession(e,n,r,i){var s;const a=(s=this.config.drmSystems)==null||(s=s[e.keySystem])==null?void 0:s.generateRequest;if(a)try{const p=a.call(this.hls,n,r,e);if(!p)throw new Error("Invalid response from configured generateRequest filter");n=p.initDataType,r=p.initData?p.initData:null,e.decryptdata.pssh=r?new Uint8Array(r):null}catch(p){if(this.warn(p.message),this.hls&&this.hls.config.debug)throw p}if(r===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const o=Ag(e.decryptdata),l=e.decryptdata.uri;this.log(`Generating key-session request for "${i}" keyId: ${o} URI: ${l} (init data type: ${n} length: ${r.byteLength})`);const c=new HA,u=e._onmessage=p=>{const m=e.mediaKeysSession;if(!m){c.emit("error",new Error("invalid state"));return}const{messageType:g,message:b}=p;this.log(`"${g}" message event for session "${m.sessionId}" message size: ${b.byteLength}`),g==="license-request"||g==="license-renewal"?this.renewLicense(e,b).catch(v=>{c.eventNames().length?c.emit("error",v):this.handleError(v)}):g==="license-release"?e.keySystem===Bn.FAIRPLAY&&this.updateKeySession(e,VE("acknowledged")).then(()=>this.removeSession(e)).catch(v=>this.handleError(v)):this.warn(`unhandled media key message type "${g}"`)},d=(p,m)=>{m.keyStatus=p;let g;p.startsWith("usable")?c.emit("resolved"):p==="internal-error"||p==="output-restricted"||p==="output-downscaled"?g=eD(p,m.decryptdata):p==="expired"?g=new Error(`key expired (keyId: ${o})`):p==="released"?g=new Error("key released"):p==="status-pending"||this.warn(`unhandled key status change "${p}" (keyId: ${o})`),g&&(c.eventNames().length?c.emit("error",g):this.handleError(g))},h=e._onkeystatuseschange=p=>{if(!e.mediaKeysSession){c.emit("error",new Error("invalid state"));return}const g=this.getKeyStatuses(e);if(!Object.keys(g).some(E=>g[E]!=="status-pending"))return;if(g[o]==="expired"){this.log(`Expired key ${yn(g)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let v=g[o];if(v)d(v,e);else{var S;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(S=e.keyStatusTimeouts)[o]||(S[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const L=this.getKeyStatus(e.decryptdata);if(L&&L!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${L} from other session.`),d(L,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),v="internal-error",d(v,e)},1e3)),this.log(`No status for keyId ${o} (${yn(g)}).`)}};ii(e.mediaKeysSession,"message",u),ii(e.mediaKeysSession,"keystatuseschange",h);const f=new Promise((p,m)=>{c.on("error",m),c.on("resolved",p)});return e.mediaKeysSession.generateRequest(n,r).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${l}`)}).catch(p=>{throw new Ci({type:ct.KEY_SYSTEM_ERROR,details:xe.KEY_SYSTEM_NO_SESSION,error:p,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${p}`)}).then(()=>f).catch(p=>(c.removeAllListeners(),this.removeSession(e).then(()=>{throw p}))).then(()=>(c.removeAllListeners(),e))}getKeyStatuses(e){const n={};return e.mediaKeysSession.keyStatuses.forEach((r,i)=>{if(typeof i=="string"&&typeof r=="object"){const o=i;i=r,r=o}const s="buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);if(e.keySystem===Bn.PLAYREADY&&s.length===16){const o=Dr(s);n[o]=r,T3(s)}const a=Dr(s);r==="internal-error"&&(this.bannedKeyIds[a]=r),this.log(`key status change "${r}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),n[a]=r}),n}fetchServerCertificate(e){const n=this.config,r=n.loader,i=new r(n),s=this.getServerCertificateUrl(e);return s?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:s},c=n.certLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(h,f,p,m)=>{a(h.data)},onError:(h,f,p,m)=>{o(new Ci({type:ct.KEY_SYSTEM_ERROR,details:xe.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:p,response:on({url:l.url,data:void 0},h)},`"${e}" certificate request failed (${s}). Status: ${h.code} (${h.text})`))},onTimeout:(h,f,p)=>{o(new Ci({type:ct.KEY_SYSTEM_ERROR,details:xe.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:p,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${s})`))},onAbort:(h,f,p)=>{o(new Error("aborted"))}};i.load(l,u,d)})):Promise.resolve()}setMediaKeysServerCertificate(e,n,r){return new Promise((i,s)=>{e.setServerCertificate(r).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${r.byteLength}) on "${n}"`),i(e)}).catch(a=>{s(new Ci({type:ct.KEY_SYSTEM_ERROR,details:xe.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,n){return this.requestLicense(e,new Uint8Array(n)).then(r=>this.updateKeySession(e,new Uint8Array(r)).catch(i=>{throw new Ci({type:ct.KEY_SYSTEM_ERROR,details:xe.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:i,fatal:!1},i.message)}))}unpackPlayReadyKeyMessage(e,n){const r=String.fromCharCode.apply(null,new Uint16Array(n.buffer));if(!r.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),n;const i=new DOMParser().parseFromString(r,"application/xml"),s=i.querySelectorAll("HttpHeader");if(s.length>0){let u;for(let d=0,h=s.length;d<h;d++){var a,o;u=s[d];const f=(a=u.querySelector("name"))==null?void 0:a.textContent,p=(o=u.querySelector("value"))==null?void 0:o.textContent;f&&p&&e.setRequestHeader(f,p)}}const l=i.querySelector("Challenge"),c=l==null?void 0:l.textContent;if(!c)throw new Error("Cannot find <Challenge> in key message");return VE(atob(c))}setupLicenseXHR(e,n,r,i){const s=this.config.licenseXhrSetup;return s?Promise.resolve().then(()=>{if(!r.decryptdata)throw new Error("Key removed");return s.call(this.hls,e,n,r,i)}).catch(a=>{if(!r.decryptdata)throw a;return e.open("POST",n,!0),s.call(this.hls,e,n,r,i)}).then(a=>(e.readyState||e.open("POST",n,!0),{xhr:e,licenseChallenge:a||i})):(e.open("POST",n,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,n){const r=this.config.keyLoadPolicy.default;return new Promise((i,s)=>{const a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const c=this.config.licenseResponseCallback;if(c)try{l=c.call(this.hls,o,a,e)}catch(u){this.error(u)}i(l)}else{const l=r.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||o.status>=400&&o.status<500)s(new Ci({type:ct.KEY_SYSTEM_ERROR,details:xe.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const u=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(e,n).then(i,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,n).then(({xhr:l,licenseChallenge:c})=>{e.keySystem==Bn.PLAYREADY&&(c=this.unpackPlayReadyKeyMessage(l,c)),l.send(c)}).catch(s)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,n){if(!this.config.emeEnabled)return;const r=n.media;this.media=r,ii(r,"encrypted",this.onMediaEncrypted),ii(r,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=r.mediaKeys}onMediaDetached(){const e=this.media;e&&(bi(e,"encrypted",this.onMediaEncrypted),bi(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const n=this.mediaResolved;if(n&&n(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const r=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,yl.clearKeyUriToKeyIdMap();const s=i.length;bd.CDMCleanupPromise=Promise.all(i.map(a=>this.removeSession(a)).concat((r==null||(e=r.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(j.ERROR,{type:ct.OTHER_ERROR,details:xe.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(j.ERROR,{type:ct.OTHER_ERROR,details:xe.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{s&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:n}){if(!(!n||!this.config.emeEnabled)&&!this.keyFormatPromise){const r=n.reduce((i,s)=>(i.indexOf(s.keyFormat)===-1&&i.push(s.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${r.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(r)}}removeSession(e){const{mediaKeysSession:n,licenseXhr:r,decryptdata:i}=e;if(n){this.log(`Remove licenses and keys and close session "${n.sessionId}" keyId: ${Dr((i==null?void 0:i.keyId)||[])}`),e._onmessage&&(n.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(n.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),r&&r.readyState!==XMLHttpRequest.DONE&&r.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const s=this.mediaKeySessions.indexOf(e);s>-1&&this.mediaKeySessions.splice(s,1);const{keyStatusTimeouts:a}=e;a&&Object.keys(a).forEach(c=>self.clearTimeout(a[c]));const{drmSystemOptions:o}=this.config;return(Nce(o)?new Promise((c,u)=>{self.setTimeout(()=>u(new Error("MediaKeySession.remove() timeout")),8e3),n.remove().then(c).catch(u)}):Promise.resolve()).catch(c=>{this.log(`Could not remove session: ${c}`),this.hls&&this.hls.trigger(j.ERROR,{type:ct.OTHER_ERROR,details:xe.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${c}`)})}).then(()=>n.close()).catch(c=>{this.log(`Could not close session: ${c}`),this.hls&&this.hls.trigger(j.ERROR,{type:ct.OTHER_ERROR,details:xe.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${c}`)})})}return Promise.resolve()}}bd.CDMCleanupPromise=void 0;function Ag(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(t.keyId===null)throw new Error("keyId is null");return Dr(t.keyId)}function ehe(t,e){if(t.keyId&&e.mediaKeysSession.keyStatuses.has(t.keyId))return e.mediaKeysSession.keyStatuses.get(t.keyId);if(t.matches(e.decryptdata))return e.keyStatus}class Ci extends Error{constructor(e,n){super(n),this.data=void 0,e.error||(e.error=new Error(n)),this.data=e,e.err=e.error}}function eD(t,e){const n=t==="output-restricted",r=n?xe.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:xe.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Ci({type:ct.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:e},n?"HDCP level output restricted":`key status changed to "${t}"`)}class the{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(j.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(j.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(j.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(j.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,n){const r=this.hls.config;if(r.capLevelOnFPSDrop){const i=n.media instanceof self.HTMLVideoElement?n.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,n,r){const i=performance.now();if(n){if(this.lastTime){const s=i-this.lastTime,a=r-this.lastDroppedFrames,o=n-this.lastDecodedFrames,l=1e3*a/s,c=this.hls;if(c.trigger(j.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:r}),l>0&&a>c.config.fpsDroppedMonitoringThreshold*o){let u=c.currentLevel;c.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(c.autoLevelCapping===-1||c.autoLevelCapping>=u)&&(u=u-1,c.trigger(j.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:c.currentLevel}),c.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=n}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const n=e.getVideoPlaybackQuality();this.checkFPS(e,n.totalVideoFrames,n.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function y4(t,e){let n;try{n=new Event("addtrack")}catch{n=document.createEvent("Event"),n.initEvent("addtrack",!1,!1)}n.track=t,e.dispatchEvent(n)}function v4(t,e){const n=t.mode;if(n==="disabled"&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(r){ln.debug(`[texttrack-utils]: ${r}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,t.addCue(i)}catch(i){ln.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}n==="disabled"&&(t.mode=n)}function rd(t,e){const n=t.mode;if(n==="disabled"&&(t.mode="hidden"),t.cues)for(let r=t.cues.length;r--;)e&&t.cues[r].removeEventListener("enter",e),t.removeCue(t.cues[r]);n==="disabled"&&(t.mode=n)}function QE(t,e,n,r){const i=t.mode;if(i==="disabled"&&(t.mode="hidden"),t.cues&&t.cues.length>0){const s=rhe(t.cues,e,n);for(let a=0;a<s.length;a++)(!r||r(s[a]))&&t.removeCue(s[a])}i==="disabled"&&(t.mode=i)}function nhe(t,e){if(e<=t[0].startTime)return 0;const n=t.length-1;if(e>t[n].endTime)return-1;let r=0,i=n,s;for(;r<=i;)if(s=Math.floor((i+r)/2),e<t[s].startTime)i=s-1;else if(e>t[s].startTime&&r<n)r=s+1;else return s;return t[r].startTime-e<e-t[i].startTime?r:i}function rhe(t,e,n){const r=[],i=nhe(t,e);if(i>-1)for(let s=i,a=t.length;s<a;s++){const o=t[s];if(o.startTime>=e&&o.endTime<=n)r.push(o);else if(o.startTime>n)return r}return r}function fy(t){const e=[];for(let n=0;n<t.length;n++){const r=t[n];(r.kind==="subtitles"||r.kind==="captions")&&r.label&&e.push(t[n])}return e}class ihe extends QA{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let n=null;const r=fy(this.media.textTracks);for(let s=0;s<r.length;s++)if(r[s].mode==="hidden")n=r[s];else if(r[s].mode==="showing"){n=r[s];break}const i=this.findTrackForTextTrack(n);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(j.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(j.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(j.MANIFEST_LOADING,this.onManifestLoading,this),e.on(j.MANIFEST_PARSED,this.onManifestParsed,this),e.on(j.LEVEL_LOADING,this.onLevelLoading,this),e.on(j.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(j.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(j.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(j.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(j.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(j.MANIFEST_LOADING,this.onManifestLoading,this),e.off(j.MANIFEST_PARSED,this.onManifestParsed,this),e.off(j.LEVEL_LOADING,this.onLevelLoading,this),e.off(j.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(j.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(j.ERROR,this.onError,this)}onMediaAttached(e,n){this.media=n.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,n){const r=this.media;if(!r)return;const i=!!n.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||r.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,i)return;fy(r.textTracks).forEach(a=>{rd(a)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,n){this.tracks=n.subtitleTracks}onSubtitleTrackLoaded(e,n){const{id:r,groupId:i,details:s}=n,a=this.tracksInGroup[r];if(!a||a.groupId!==i){this.warn(`Subtitle track with id:${r} and group:${i} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=n.details,this.log(`Subtitle track ${r} "${a.name}" lang:${a.lang} group:${i} loaded [${s.startSN}-${s.endSN}]`),r===this.trackId&&this.playlistLoaded(r,n,o)}onLevelLoading(e,n){this.switchLevel(n.level)}onLevelSwitching(e,n){this.switchLevel(n.level)}switchLevel(e){const n=this.hls.levels[e];if(!n)return;const r=n.subtitleGroups||null,i=this.groupIds;let s=this.currentTrack;if(!r||(i==null?void 0:i.length)!==(r==null?void 0:r.length)||r!=null&&r.some(a=>(i==null?void 0:i.indexOf(a))===-1)){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(u=>!r||r.indexOf(u.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(u=>u.default)&&(this.selectDefaultTrack=!1),a.forEach((u,d)=>{u.id=d});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const o=this.hls.config.subtitlePreference;if(!s&&o){this.selectDefaultTrack=!1;const u=aa(o,a);if(u>-1)s=a[u];else{const d=aa(o,this.tracks);s=this.tracks[d]}}let l=this.findTrackId(s);l===-1&&s&&(l=this.findTrackId(null));const c={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${r==null?void 0:r.join(",")}" group-id`),this.hls.trigger(j.SUBTITLE_TRACKS_UPDATED,c),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}}findTrackId(e){const n=this.tracksInGroup,r=this.selectDefaultTrack;for(let i=0;i<n.length;i++){const s=n[i];if(!(r&&!s.default||!r&&!e)&&(!e||Ic(s,e)))return i}if(e){for(let i=0;i<n.length;i++){const s=n[i];if(Lp(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<n.length;i++){const s=n[i];if(Lp(e.attrs,s.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(e){if(e){const n=this.tracksInGroup;for(let r=0;r<n.length;r++){const i=n[r];if(qE(i,e))return r}}return-1}onError(e,n){n.fatal||!n.context||n.context.type===Ft.SUBTITLE_TRACK&&n.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(n.context.groupId)!==-1)&&this.checkRetry(n)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const n=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,n.length){const r=this.currentTrack;if(r&&Ic(e,r))return r;const i=aa(e,this.tracksInGroup);if(i>-1){const s=this.tracksInGroup[i];return this.setSubtitleTrack(i),s}else{if(r)return null;{const s=aa(e,n);if(s>-1)return n[s]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,n){super.loadingPlaylist(e,n);const r=e.id,i=e.groupId,s=this.getUrlWithDirectives(e.url,n),a=e.details,o=a==null?void 0:a.age;this.log(`Loading subtitle ${r} "${e.name}" lang:${e.lang} group:${i}${(n==null?void 0:n.msn)!==void 0?" at sn "+n.msn+" part "+n.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${s}`),this.hls.trigger(j.SUBTITLE_TRACK_LOADING,{url:s,id:r,groupId:i,deliveryDirectives:n||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const n=fy(e.textTracks),r=this.currentTrack;let i;if(r&&(i=n.filter(s=>qE(r,s))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${r.name}" and language "${r.lang}"`)),[].slice.call(n).forEach(s=>{s.mode!=="disabled"&&s!==i&&(s.mode="disabled")}),i){const s=this.subtitleDisplay?"showing":"hidden";i.mode!==s&&(i.mode=s)}}setSubtitleTrack(e){const n=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=n.length||!Ze(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const r=this.currentTrack,i=n[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i){this.hls.trigger(j.SUBTITLE_TRACK_SWITCH,{id:e});return}const s=!!i.details&&!i.details.live;if(e===this.trackId&&i===r&&s)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:a,groupId:o="",name:l,type:c,url:u}=i;this.hls.trigger(j.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:c,url:u});const d=this.switchParams(i.url,r==null?void 0:r.details,i.details);this.loadPlaylist(d)}}function she(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),n=e.toString();return URL.revokeObjectURL(e),n.slice(n.lastIndexOf("/")+1)}catch{let n=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{const s=(n+Math.random()*16)%16|0;return n=Math.floor(n/16),(i=="x"?s:s&3|8).toString(16)})}}}function jf(t){let e=5381,n=t.length;for(;n;)e=e*33^t.charCodeAt(--n);return(e>>>0).toString()}const xd=.025;let C0=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({});function ahe(t,e,n){return`${t.identifier}-${n+1}-${jf(e)}`}class ohe{constructor(e,n){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=n,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var n;if(e>0&&e>=this.assetList.length)return!0;const r=this.playoutLimit;return e<=0||isNaN(r)?!1:r===0?!0:(((n=this.assetList[e])==null?void 0:n.startOffset)||0)>r}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const n=this.dateRange.tagAnchor;if(n)return Xb(e,n)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const n=this.dateRange.startTime,r=Xb(n,e);return n-r<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,n=Ze(e)?e:this.duration;return this.cumulativeDuration+n}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const n=this.resumeAnchor;if(n)return Xb(e,n)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<xd))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let n;return this._duration!==null?n=this._duration:this.dateRange.duration?n=this.dateRange.duration:n=this.dateRange.plannedDuration||0,!isNaN(e)&&e<n&&(n=e),n}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?C0.Range:C0.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return lhe(this)}}function Xb(t,e){return t-e.start<e.duration/2&&!(Math.abs(t-(e.start+e.duration))<xd)?e.start:e.start+e.duration}function _4(t,e,n){const r=new self.URL(t,n);return r.protocol!=="data:"&&r.searchParams.set("_HLS_primary_id",e),r}function Qb(t,e){for(;(n=t.assetList[++e])!=null&&n.error;)var n;return e}function lhe(t){return`["${t.identifier}" ${t.cue.pre?"<pre>":t.cue.post?"<post>":""}${t.timelineStart.toFixed(2)}-${t.resumeTime.toFixed(2)}]`}function Uu(t){const e=t.timelineStart,n=t.duration||0;return`["${t.identifier}" ${e.toFixed(2)}-${(e+n).toFixed(2)}]`}class che{constructor(e,n,r,i){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(j.PLAYOUT_LIMIT_REACHED,{})};const s=this.hls=new e(n);this.interstitial=r,this.assetItem=i;const a=()=>{this.hasDetails=!0};s.once(j.LEVEL_LOADED,a),s.once(j.AUDIO_TRACK_LOADED,a),s.once(j.SUBTITLE_TRACK_LOADED,a),s.on(j.MEDIA_ATTACHING,(o,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&s.on(j.BUFFER_APPENDED,()=>{const u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,s.trigger(j.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let n=this.assetItem.uri;try{n=_4(n,e.config.primarySessionId||"").href}catch{}e.loadSource(n)}}bufferedInPlaceToEnd(e){var n;if(!this.appendInPlace)return!1;if((n=this.hls)!=null&&n.bufferedToEnd)return!0;if(!e)return!1;const r=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset,s=Ct.bufferInfo(e,i,0);return this.getAssetTime(s.end)>=r-.02}reachedPlayout(e){const r=this.interstitial.playoutLimit;return this.startOffset+e>=r}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const n=Ct.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(n.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const n=this.interstitial.playoutLimit;if(n){const r=n-this.startOffset;if(r>0&&r<e)return r}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const n=this.timelineOffset;if(e!==n){const r=e-n;if(Math.abs(r)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const n=this.timelineOffset,r=this.duration;return Math.min(Math.max(0,e-n),r)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var n;this.loadSource(),(n=this.hls)==null||n.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const n=r=>delete r.details;e.levels.forEach(n),e.allAudioTracks.forEach(n),e.allSubtitleTracks.forEach(n),this.hasDetails=!1}}on(e,n,r){var i;(i=this.hls)==null||i.on(e,n)}once(e,n,r){var i;(i=this.hls)==null||i.once(e,n)}off(e,n,r){var i;(i=this.hls)==null||i.off(e,n)}toString(){var e;return`HlsAssetPlayer: ${Uu(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const tD=.033;class uhe extends vs{constructor(e,n){super("interstitials-sched",n),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,n){return this.events?this.events.reduce((r,i)=>e<=i.startOffset&&n>i.startOffset?(delete i.error,r+1):r,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,n){if(e.event)return this.findEventIndex(e.event.identifier);let r=-1;e.nextEvent?r=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(r=this.findEventIndex(e.previousEvent.identifier)+1);const i=this.items;if(i)for(i[r]||(n===void 0&&(n=e.start),r=this.findItemIndexAtTime(n));r>=0&&(s=i[r])!=null&&s.event;){var s;r--}return r}findItemIndexAtTime(e,n){const r=this.items;if(r)for(let i=0;i<r.length;i++){let s=r[i];if(n&&n!=="primary"&&(s=s[n]),e===s.start||e>s.start&&e<s.end)return i}return-1}findJumpRestrictedIndex(e,n){const r=this.items;if(r)for(let i=e;i<=n&&r[i];i++){const s=r[i].event;if(s!=null&&s.restrictions.jump&&!s.appendInPlace)return i}return-1}findEventIndex(e){const n=this.items;if(n)for(let i=n.length;i--;){var r;if(((r=n[i].event)==null?void 0:r.identifier)===e)return i}return-1}findAssetIndex(e,n){const r=e.assetList,i=r.length;if(i>1)for(let s=0;s<i;s++){const a=r[s];if(!a.error){const o=a.timelineStart;if(n===o||n>o&&(n<o+(a.duration||0)||s===i-1))return s}}return 0}get assetIdAtEnd(){var e;const n=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(n){const r=n.assetList,i=r[r.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(e,n){const r=e.main.details,{dateRanges:i}=r,s=this.events,a=this.parseDateRanges(i,{url:r.url},n),o=Object.keys(i),l=s?s.filter(c=>!o.includes(c.identifier)):[];a.length&&a.sort((c,u)=>{const d=c.cue.pre,h=c.cue.post,f=u.cue.pre,p=u.cue.post;if(d&&!f)return-1;if(f&&!d||h&&!p)return 1;if(p&&!h)return-1;if(!d&&!f&&!h&&!p){const m=c.startTime,g=u.startTime;if(m!==g)return m-g}return c.dateRange.tagOrder-u.dateRange.tagOrder}),this.events=a,l.forEach(c=>{this.removeEvent(c)}),this.updateSchedule(e,l)}updateSchedule(e,n=[],r=!1){const i=this.events||[];if(i.length||n.length||this.length<2){const s=this.items,a=this.parseSchedule(i,e);(r||n.length||(s==null?void 0:s.length)!==a.length||a.some((l,c)=>Math.abs(l.playout.start-s[c].playout.start)>.005||Math.abs(l.playout.end-s[c].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(n,s))}}parseDateRanges(e,n,r){const i=[],s=Object.keys(e);for(let a=0;a<s.length;a++){const o=s[a],l=e[o];if(l.isInterstitial){let c=this.eventMap[o];c?c.setDateRange(l):(c=new ohe(l,n),this.eventMap[o]=c,r===!1&&(c.appendInPlace=r)),i.push(c)}}return i}parseSchedule(e,n){const r=[],i=n.main.details,s=i.live?1/0:i.edge;let a=0;if(e=e.filter(l=>!l.error&&!(l.cue.once&&l.hasPlayed)),e.length){this.resolveOffsets(e,n);let l=0,c=0;if(e.forEach((u,d)=>{const h=u.cue.pre,f=u.cue.post,p=e[d-1]||null,m=u.appendInPlace,g=f?s:u.startOffset,b=u.duration,v=u.timelineOccupancy===C0.Range?b:0,S=u.resumptionOffset,E=(p==null?void 0:p.startTime)===g,L=g+u.cumulativeDuration;let U=m?L+b:g+S;if(h||!f&&g<=0){const k=c;c+=v,u.timelineStart=L;const I=a;a+=b,r.push({event:u,start:L,end:U,playout:{start:I,end:a},integrated:{start:k,end:c}})}else if(g<=s){if(!E){const R=g-l;if(R>tD){const M=l,z=c;c+=R;const Z=a;a+=R;const W={previousEvent:e[d-1]||null,nextEvent:u,start:M,end:M+R,playout:{start:Z,end:a},integrated:{start:z,end:c}};r.push(W)}else R>0&&p&&(p.cumulativeDuration+=R,r[r.length-1].end=g)}f&&(U=L),u.timelineStart=L;const k=c;c+=v;const I=a;a+=b,r.push({event:u,start:L,end:U,playout:{start:I,end:a},integrated:{start:k,end:c}})}else return;const O=u.resumeTime;f||O>s?l=s:l=O}),l<s){var o;const u=l,d=c,h=s-l;c+=h;const f=a;a+=h,r.push({previousEvent:((o=r[r.length-1])==null?void 0:o.event)||null,nextEvent:null,start:l,end:u+h,playout:{start:f,end:a},integrated:{start:d,end:c}})}this.setDurations(s,a,c)}else r.push({previousEvent:null,nextEvent:null,start:0,end:s,playout:{start:0,end:s},integrated:{start:0,end:s}}),this.setDurations(s,s,s);return r}setDurations(e,n,r){this.durations={primary:e,playout:n,integrated:r}}resolveOffsets(e,n){const r=n.main.details,i=r.live?1/0:r.edge;let s=0,a=-1;e.forEach((o,l)=>{const c=o.cue.pre,u=o.cue.post,d=c?0:u?i:o.startTime;this.updateAssetDurations(o),a===d?o.cumulativeDuration=s:(s=0,a=d),!u&&o.snapOptions.in&&(o.resumeAnchor=Gc(null,r.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,n)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<tD&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const f=Ze(o.resumeOffset)?o.resumeOffset:o.duration;s+=f})}primaryCanResumeInPlaceAt(e,n){const r=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(r-i)>xd?(this.log(`"${e.identifier}" resumption ${r} not aligned with estimated timeline end ${i}`),!1):!Object.keys(n).some(a=>{const o=n[a].details,l=o.edge;if(r>=l)return this.log(`"${e.identifier}" resumption ${r} past ${a} playlist end ${l}`),!1;const c=Gc(null,o.fragments,r);if(!c)return this.log(`"${e.identifier}" resumption ${r} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const u=a==="audio"?.175:0;return Math.abs(c.start-r)<xd+u||Math.abs(c.end-r)<xd+u?!1:(this.log(`"${e.identifier}" resumption ${r} not aligned with ${a} fragment bounds (${c.start}-${c.end} sn: ${c.sn} cc: ${c.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const n=e.timelineStart;let r=0,i=!1,s=!1;for(let a=0;a<e.assetList.length;a++){const o=e.assetList[a],l=n+r;o.startOffset=r,o.timelineStart=l,i||(i=o.duration===null),s||(s=!!o.error);const c=o.error?0:o.duration||0;r+=c}i&&!s?e.duration=Math.max(r,e.duration):e.duration=r}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function ws(t){return`[${t.event?'"'+t.event.identifier+'"':"primary"}: ${t.start.toFixed(2)}-${t.end.toFixed(2)}]`}class dhe{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,n){const r=e.assetListUrl;let i;try{i=_4(r,this.hls.sessionId,e.baseUrl)}catch(h){const f=this.assignAssetListError(e,xe.ASSET_LIST_LOAD_ERROR,h,r);this.hls.trigger(j.ERROR,f);return}n&&i.protocol!=="data:"&&i.searchParams.set("_HLS_start_offset",""+n);const s=this.hls.config,a=s.loader,o=new a(s),l={responseType:"json",url:i.href},c=s.interstitialAssetListLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(h,f,p,m)=>{const g=h.data,b=g==null?void 0:g.ASSETS;if(!Array.isArray(b)){const v=this.assignAssetListError(e,xe.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),p.url,f,m);this.hls.trigger(j.ERROR,v);return}e.assetListResponse=g,this.hls.trigger(j.ASSET_LIST_LOADED,{event:e,assetListResponse:g,networkDetails:m})},onError:(h,f,p,m)=>{const g=this.assignAssetListError(e,xe.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${h.code} ${h.text} (${f.url})`),f.url,m,p);this.hls.trigger(j.ERROR,g)},onTimeout:(h,f,p)=>{const m=this.assignAssetListError(e,xe.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,h,p);this.hls.trigger(j.ERROR,m)}};return o.load(l,u,d),this.hls.trigger(j.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,n,r,i,s,a){return e.error=r,{type:ct.NETWORK_ERROR,details:n,fatal:!1,interstitial:e,url:i,error:r,networkDetails:a,stats:s}}}function nD(t){var e;t==null||(e=t.play())==null||e.catch(()=>{})}function Au(t,e){return`[${t}] Advancing timeline position to ${e}`}class hhe extends vs{constructor(e,n){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const r=this.currentTime;if(r===void 0||this.playbackDisabled||!this.schedule)return;const i=r-this.timelinePos;if(Math.abs(i)<1/7056e5)return;const a=i<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=r,this.bufferedPos=r;const o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(r,r-i)&&this.updateSchedule(!0),this.checkBuffer(),a&&r<o.start||r>=o.end){var l;const f=this.findItemIndex(o);let p=this.schedule.findItemIndexAtTime(r);if(p===-1&&(p=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${r} (resolving from ${f} to ${p})`)),!this.isInterstitial(o)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=!1),!a&&p>f){const m=this.schedule.findJumpRestrictedIndex(f+1,p);if(m>f){this.setSchedulePosition(m);return}}this.setSchedulePosition(p);return}const c=this.playingAsset;if(!c){if(this.playingLastItem&&this.isInterstitial(o)){const f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(r,f))}return}const u=c.timelineStart,d=c.duration||0;if(a&&r<u||r>=u+d){var h;(h=o.event)!=null&&h.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(r)),this.setScheduleToAssetAtTime(r,c)}},this.onTimeupdate=()=>{const r=this.currentTime;if(r===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),r>this.timelinePos)this.timelinePos=r,r>this.bufferedPos&&this.checkBuffer();else return;const i=this.playingItem;if(!i||this.playingLastItem)return;if(r>=i.end){this.timelinePos=i.end;const o=this.findItemIndex(i);this.setSchedulePosition(o+1)}const s=this.playingAsset;if(!s)return;const a=s.timelineStart+(s.duration||0);r>=a&&this.setScheduleToAssetAtTime(r,s)},this.onScheduleUpdate=(r,i)=>{const s=this.schedule;if(!s)return;const a=this.playingItem,o=s.events||[],l=s.items||[],c=s.durations,u=r.map(m=>m.identifier),d=!!(o.length||u.length);(d||i)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
Schedule: ${l.map(m=>ws(m))} pos: ${this.timelinePos}`),u.length&&this.log(`Removed events ${u}`);let h=null,f=null;a&&(h=this.updateItem(a,this.timelinePos),this.itemsMatch(a,h)?this.playingItem=h:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const p=this.bufferingItem;if(p&&(f=this.updateItem(p,this.bufferedPos),this.itemsMatch(p,f)?this.bufferingItem=f:p.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(p.event,null))),r.forEach(m=>{m.assetList.forEach(g=>{this.clearAssetPlayer(g.identifier,null)})}),this.playerQueue.forEach(m=>{if(m.interstitial.appendInPlace){const g=m.assetItem.timelineStart,b=m.timelineOffset-g;if(b)try{m.timelineOffset=g}catch(v){Math.abs(b)>xd&&this.warn(`${v} ("${m.assetId}" ${m.timelineOffset}->${g})`)}}}),d||i){if(this.hls.trigger(j.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:l.slice(0),durations:c,removedIds:u}),this.isInterstitial(a)&&u.includes(a.event.identifier)){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(h,a),p&&f!==h&&this.trimInPlace(f,p),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=n,this.assetListLoader=new dhe(e),this.schedule=new uhe(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(j.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(j.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(j.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(j.MANIFEST_LOADING,this.onManifestLoading,this),e.on(j.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(j.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(j.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(j.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(j.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(j.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(j.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(j.BUFFER_APPENDED,this.onBufferAppended,this),e.on(j.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(j.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(j.MEDIA_ENDED,this.onMediaEnded,this),e.on(j.ERROR,this.onError,this),e.on(j.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(j.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(j.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(j.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(j.MANIFEST_LOADING,this.onManifestLoading,this),e.off(j.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(j.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(j.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(j.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(j.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(j.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(j.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(j.BUFFER_CODECS,this.onBufferCodecs,this),e.off(j.BUFFER_APPENDED,this.onBufferAppended,this),e.off(j.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(j.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(j.MEDIA_ENDED,this.onMediaEnded,this),e.off(j.ERROR,this.onError,this),e.off(j.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){bi(e,"play",this.onPlay),bi(e,"pause",this.onPause),bi(e,"seeking",this.onSeeking),bi(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,n){const r=this.media=n.media;ii(r,"seeking",this.onSeeking),ii(r,"timeupdate",this.onTimeupdate),ii(r,"play",this.onPlay),ii(r,"pause",this.onPause)}onMediaAttached(e,n){const r=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,r===null)this.checkStart();else if(!i){this.clearScheduleState();const s=this.findItemIndex(r);this.setSchedulePosition(s)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,n){const r=!!n.transferMedia,i=this.media;if(this.media=null,!r&&(i&&this.removeMediaListeners(i),this.detachedData)){const s=this.getBufferingPlayer();s&&(this.log(`Removing schedule state for detachedData and ${s}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,s.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,n=()=>e.bufferingItem||e.waitingItem,r=d=>d&&e.getAssetPlayer(d.identifier),i=(d,h,f,p,m)=>{if(d){let g=d[h].start;const b=d.event;if(b){if(h==="playout"||b.timelineOccupancy!==C0.Point){const v=r(f);(v==null?void 0:v.interstitial)===b&&(g+=v.assetItem.startOffset+v[m])}}else{const v=p==="bufferedPos"?a():e[p];g+=v-d.start}return g}return 0},s=(d,h)=>{var f;if(d!==0&&h!=="primary"&&(f=e.schedule)!=null&&f.length){var p;const m=e.schedule.findItemIndexAtTime(d),g=(p=e.schedule.items)==null?void 0:p[m];if(g){const b=g[h].start-g.start;return d+b}}return d},a=()=>{const d=e.bufferedPos;return d===Number.MAX_VALUE?o("primary"):Math.max(d,0)},o=d=>{var h,f;return(h=e.primaryDetails)!=null&&h.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[d])||0},l=(d,h)=>{var f,p;const m=e.effectivePlayingItem;if(m!=null&&(f=m.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${d} "${h}"`);const g=e.effectivePlayingItem,b=e.schedule.findItemIndexAtTime(d,h),v=(p=e.schedule.items)==null?void 0:p[b],S=e.getBufferingPlayer(),E=S==null?void 0:S.interstitial,L=E==null?void 0:E.appendInPlace,U=g&&e.itemsMatch(g,v);if(g&&(L||U)){const O=r(e.playingAsset),k=(O==null?void 0:O.media)||e.primaryMedia;if(k){const I=h==="primary"?k.currentTime:i(g,h,e.playingAsset,"timelinePos","currentTime"),R=d-I,M=(L?I:k.currentTime)+R;if(M>=0&&(!O||L||M<=O.duration)){k.currentTime=M;return}}}if(v){let O=d;if(h!=="primary"){const I=v[h].start,R=d-I;O=v.start+R}const k=!e.isInterstitial(v);if((!e.isInterstitial(g)||g.event.appendInPlace)&&(k||v.event.appendInPlace)){const I=e.media||(L?S==null?void 0:S.media:null);I&&(I.currentTime=O)}else if(g){const I=e.findItemIndex(g);if(b>I){const M=e.schedule.findJumpRestrictedIndex(I+1,b);if(M>I){e.setSchedulePosition(M);return}}let R=0;if(k)e.timelinePos=O,e.checkBuffer();else{const M=v.event.assetList,z=d-(v[h]||v).start;for(let Z=M.length;Z--;){const W=M[Z];if(W.duration&&z>=W.startOffset&&z<W.startOffset+W.duration){R=Z;break}}}e.setSchedulePosition(b,R)}}},c=()=>{const d=e.effectivePlayingItem;if(e.isInterstitial(d))return d;const h=n();return e.isInterstitial(h)?h:null},u={get bufferedEnd(){const d=n(),h=e.bufferingItem;if(h&&h===d){var f;return i(h,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-h.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){const d=c(),h=e.effectivePlayingItem;return h&&h===d?i(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(d){const h=c(),f=e.effectivePlayingItem;f&&f===h&&l(d+f.playout.start,"playout")},get duration(){const d=c();return d?d.playout.end-d.playout.start:0},get assetPlayers(){var d;const h=(d=c())==null?void 0:d.event.assetList;return h?h.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var d;const h=(d=c())==null?void 0:d.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return c()}};return this.manager={get events(){var d;return((d=e.schedule)==null||(d=d.events)==null?void 0:d.slice(0))||[]},get schedule(){var d;return((d=e.schedule)==null||(d=d.items)==null?void 0:d.slice(0))||[]},get interstitialPlayer(){return c()?u:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return n()},get bufferingIndex(){const d=n();return e.findItemIndex(d)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const d=e.effectivePlayingItem;return e.findItemIndex(d)},primary:{get bufferedEnd(){return a()},get currentTime(){const d=e.timelinePos;return d>0?d:0},set currentTime(d){l(d,"primary")},get duration(){return o("primary")},get seekableStart(){var d;return((d=e.primaryDetails)==null?void 0:d.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(n(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(d){l(d,"integrated")},get duration(){return o("integrated")},get seekableStart(){var d;return s(((d=e.primaryDetails)==null?void 0:d.fragmentStart)||0,"integrated")}},skip:()=>{const d=e.effectivePlayingItem,h=d==null?void 0:d.event;if(h&&!h.restrictions.skip){const f=e.findItemIndex(d);if(h.appendInPlace){const p=d.playout.start+d.event.duration;l(p+.001,"playout")}else e.advanceAfterAssetEnded(h,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const n=this.playingItem,r=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!n||!r?!1:this.findItemIndex(n)===r.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,n;if(this.mediaSelection===null)return;const r=this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&!r.event.appendInPlace)return;let i=this.media;!i&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(i=this.primaryMedia);const s=(n=i)==null?void 0:n.currentTime;if(!(s===void 0||!Ze(s)))return s}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,n){const r=this.getAssetPlayer(e);r&&this.transferMediaFromPlayer(r,n)}transferMediaFromPlayer(e,n){const r=e.interstitial.appendInPlace,i=e.media;if(r&&i===this.primaryMedia){if(this.bufferingAsset=null,(!n||this.isInterstitial(n)&&!n.event.appendInPlace)&&n&&i){this.detachedData={media:i};return}const s=e.transferMedia();this.log(`transfer MediaSource from ${e} ${yn(s)}`),this.detachedData=s}else n&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,n){var r,i;if(e.media===n)return;let s=null;const a=this.hls,o=e!==a,l=o&&e.interstitial.appendInPlace,c=(r=this.detachedData)==null?void 0:r.mediaSource;let u;if(a.media)l&&(s=a.transferMedia(),this.detachedData=s),u="Primary";else if(c){const p=this.getBufferingPlayer();p?(s=p.transferMedia(),u=`${p}`):u="detached MediaSource"}else u="detached media";if(!s){if(c)s=this.detachedData,this.log(`using detachedData: MediaSource ${yn(s)}`);else if(!this.detachedData||a.media===n){const p=this.playerQueue;p.length>1&&p.forEach(m=>{if(o&&m.interstitial.appendInPlace!==l){const g=m.interstitial;this.clearInterstitial(m.interstitial,null),g.appendInPlace=!1,g.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${g}`)}}),this.hls.detachMedia(),this.detachedData={media:n}}}const d=s&&"mediaSource"in s&&((i=s.mediaSource)==null?void 0:i.readyState)!=="closed",h=d&&s?s:n;this.log(`${d?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${u} (media.currentTime: ${n.currentTime})`);const f=this.schedule;if(h===s&&f){const p=o&&e.assetId===f.assetIdAtEnd;h.overrides={duration:f.duration,endOfStream:!o||p,cueRemoval:!o}}e.attachMedia(h)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,n=e==null?void 0:e.events;if(!n||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const r=this.timelinePos,i=this.effectivePlayingItem;if(r===-1){const s=this.hls.startPosition;if(this.timelinePos=s,n.length===0)this.setSchedulePosition(0);else if(n[0].cue.pre){this.log(Au("checkStart (preroll)",s));const a=e.findEventIndex(n[0].identifier);this.setSchedulePosition(a)}else if(s>=0||!this.primaryLive){this.log(Au("checkStart",s));const a=this.timelinePos=s>0?s:0,o=e.findItemIndexAtTime(a);this.setSchedulePosition(o)}else this.hls.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(i&&!this.playingItem){this.log(Au("checkStart (playing item)",i.start));const s=e.findItemIndex(i);this.setSchedulePosition(s)}}advanceAssetBuffering(e,n){const r=e.event,i=r.findAssetIndex(n),s=Qb(r,i);if(!r.isAssetPastPlayoutLimit(s))this.bufferedToEvent(e,s);else if(this.schedule){var a;const o=(a=this.schedule.items)==null?void 0:a[this.findItemIndex(e)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(e,n,r){const i=Qb(e,r);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){const s=this.schedule.items;if(s){const a=n+1,o=s.length;if(a>=o){this.setSchedulePosition(-1);return}const l=e.resumeTime;this.timelinePos<l&&(this.log(Au("advanceAfterAssetEnded",l)),this.timelinePos=l,e.appendInPlace&&this.advanceInPlace(l),this.checkBuffer(this.bufferedPos<l)),this.setSchedulePosition(a)}}}else{if(e.appendInPlace){const s=e.assetList[i];s&&this.advanceInPlace(s.timelineStart)}this.setSchedulePosition(n,i)}}setScheduleToAssetAtTime(e,n){const r=this.schedule;if(!r)return;const i=n.parentIdentifier,s=r.getEvent(i);if(s){const a=r.findEventIndex(i),o=r.findAssetIndex(s,e);this.advanceAfterAssetEnded(s,a,o-1)}}setSchedulePosition(e,n){var r;const i=(r=this.schedule)==null?void 0:r.items;if(!i||this.playbackDisabled)return;const s=e>=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${n} (${s&&ws(s)}) pos: ${this.timelinePos}`);const a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){const u=a.event,d=this.playingAsset,h=d==null?void 0:d.identifier,f=h?this.getAssetPlayer(h):null;if(f&&h&&(!this.eventItemsMatch(a,s)||n!==void 0&&h!==u.assetList[n].identifier)){var l;const p=u.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${p+1}/${u.assetList.length} ${Uu(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(j.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:p,event:u,schedule:i.slice(0),scheduleIndex:e,player:f}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(u,this.findItemIndex(this.playingItem),p);return}this.retreiveMediaSource(h,s),f.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(a,s)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${u} ${ws(a)}`),u.hasPlayed=!0,this.hls.trigger(j.INTERSTITIAL_ENDED,{event:u,schedule:i.slice(0),scheduleIndex:e}),u.cue.once)){var c;this.updateSchedule();const p=(c=this.schedule)==null?void 0:c.items;if(s&&p){const m=this.findItemIndex(s);this.advanceSchedule(m,p,n,a,o)}return}}this.advanceSchedule(e,i,n,a,o)}advanceSchedule(e,n,r,i,s){const a=this.schedule;if(!a)return;const o=n[e]||null,l=this.primaryMedia,c=this.playerQueue;if(c.length&&c.forEach(u=>{const d=u.interstitial,h=a.findEventIndex(d.identifier);(h<e||h>e+1)&&this.clearInterstitial(d,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const u=o.event;if(r===void 0){r=a.findAssetIndex(u,this.timelinePos);const p=Qb(u,r-1);if(u.isAssetPastPlayoutLimit(p)||u.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(u,e,r);return}r=p}const d=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let h=this.preloadAssets(u,r);if(this.eventItemsMatch(o,d||i)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${ws(o)} ${u.appendInPlace?"append in place":""}`),this.hls.trigger(j.INTERSTITIAL_STARTED,{event:u,schedule:n.slice(0),scheduleIndex:e})),!u.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${u}`);return}if(u.assetListLoader&&(u.assetListLoader.destroy(),u.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${u}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const f=u.assetList[r];if(!f){this.advanceAfterAssetEnded(u,e,r||0);return}if(h||(h=this.getAssetPlayer(f.identifier)),h===null||h.destroyed){const p=u.assetList.length;this.warn(`asset ${r+1}/${p} player destroyed ${u}`),h=this.createAssetPlayer(u,f,r),h.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(h,r,n,e,l),this.shouldPlay&&nD(h.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&nD(this.hls.media)):s&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,n,r){var i,s;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${ws(e)}`),!((i=this.detachedData)!=null&&i.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,n),this.log(Au("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e)}if(!r)return;const a=(s=this.schedule)==null?void 0:s.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${ws(e)}`),this.hls.trigger(j.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:n}),this.checkBuffer())}getPrimaryResumption(e,n){const r=e.start;if(this.primaryLive){const i=this.primaryDetails;if(n===0)return this.hls.startPosition;if(i&&(r<i.fragmentStart||r>i.edge))return this.hls.liveSyncPosition||-1}return r}isAssetBuffered(e){const n=this.getAssetPlayer(e.identifier);return n!=null&&n.hls?n.hls.bufferedToEnd:Ct.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,n,r){n?this.setBufferingItem(n):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const s=this.hls;s.media?this.checkBuffer():(this.transferMediaTo(s,i),r&&this.startLoadingPrimaryAt(e,r)),r||(this.log(Au("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,r))}startLoadingPrimaryAt(e,n){var r;const i=this.hls;!i.loadingEnabled||!i.media||Math.abs((((r=i.mainForwardBufferInfo)==null?void 0:r.start)||i.media.currentTime)-e)>.5?i.startLoad(e,n):i.bufferingEnabled||i.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(j.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(j.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,n){if(n.level===-1||!this.schedule)return;const r=this.hls.levels[n.level];if(!r.details)return;const i=on(on({},this.mediaSelection||this.altSelection),{},{main:r});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,n){const r=this.hls.audioTracks[n.id],i=this.mediaSelection;if(!i){this.altSelection=on(on({},this.altSelection),{},{audio:r});return}const s=on(on({},i),{},{audio:r});this.mediaSelection=s}onSubtitleTrackUpdated(e,n){const r=this.hls.subtitleTracks[n.id],i=this.mediaSelection;if(!i){this.altSelection=on(on({},this.altSelection),{},{subtitles:r});return}const s=on(on({},i),{},{subtitles:r});this.mediaSelection=s}onAudioTrackSwitching(e,n){const r=dP(n);this.playerQueue.forEach(({hls:i})=>i&&(i.setAudioOption(n)||i.setAudioOption(r)))}onSubtitleTrackSwitch(e,n){const r=dP(n);this.playerQueue.forEach(({hls:i})=>i&&(i.setSubtitleOption(n)||n.id!==-1&&i.setSubtitleOption(r)))}onBufferCodecs(e,n){const r=n.tracks;r&&(this.requiredTracks=r)}onBufferAppended(e,n){this.checkBuffer()}onBufferFlushed(e,n){const r=this.playingItem;if(r&&!this.itemsMatch(r,this.bufferingItem)&&!this.isInterstitial(r)){const i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const n=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&n){for(let i=0;i<n.length;i++){const s=n[i];if(s.cue.post){var r;const a=this.schedule.findEventIndex(s.identifier),o=(r=this.schedule.items)==null?void 0:r[a];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const n=this.playingItem;if(!this.playingLastItem&&n){const r=this.findItemIndex(n);this.setSchedulePosition(r+1)}else this.shouldPlay=!1}updateItem(e,n){var r;const i=(r=this.schedule)==null?void 0:r.items;if(e&&i){const s=this.findItemIndex(e,n);return i[s]||null}return null}trimInPlace(e,n){if(this.isInterstitial(e)&&e.event.appendInPlace&&n.end-e.end>.25){e.event.assetList.forEach((s,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(s.identifier,null)});const r=e.end+.25,i=Ct.bufferInfo(this.primaryMedia,r,0);(i.end>r||(i.nextStart||0)>r)&&(this.log(`trim buffered interstitial ${ws(e)} (was ${ws(n)})`),this.attachPrimary(r,null,!0),this.flushFrontBuffer(r))}}itemsMatch(e,n){return!!n&&(e===n||e.event&&n.event&&this.eventItemsMatch(e,n)||!e.event&&!n.event&&this.findItemIndex(e)===this.findItemIndex(n))}eventItemsMatch(e,n){var r;return!!n&&(e===n||e.event.identifier===((r=n.event)==null?void 0:r.identifier))}findItemIndex(e,n){return e&&this.schedule?this.schedule.findItemIndex(e,n):-1}updateSchedule(e=!1){var n;const r=this.mediaSelection;r&&((n=this.schedule)==null||n.updateSchedule(r,[],e))}checkBuffer(e){var n;const r=(n=this.schedule)==null?void 0:n.items;if(!r)return;const i=Ct.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,r,e)}updateBufferedPos(e,n,r){const i=this.schedule,s=this.bufferingItem;if(this.bufferedPos>e||!i)return;if(n.length===1&&this.itemsMatch(n[0],s)){this.bufferedPos=e;return}const a=this.playingItem,o=this.findItemIndex(a);let l=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var c;const u=this.findItemIndex(s),d=Math.min(u+1,n.length-1),h=n[d];if((l===-1&&s&&e>=s.end||(c=h.event)!=null&&c.appendInPlace&&e+.01>=h.start)&&(l=d),this.isInterstitial(s)){const f=s.event;if(d-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,l>u&&l>o)this.bufferedToItem(h);else{const f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&h.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(h)&&this.preloadAssets(h.event,0)}}else r&&a&&!this.itemsMatch(a,s)&&(l===o?this.bufferedToItem(a):l===o+1&&this.bufferedToItem(n[l]))}assetsBuffered(e,n){return e.event.assetList.length===0?!1:!e.event.assetList.some(i=>{const s=this.getAssetPlayer(i.identifier);return!(s!=null&&s.bufferedInPlaceToEnd(n))})}setBufferingItem(e){const n=this.bufferingItem,r=this.schedule;if(!this.itemsMatch(e,n)&&r){const{items:i,events:s}=r;if(!i||!s)return n;const a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const l=o?o.remaining:n?n.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${ws(e)}`+(n?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){const c=r.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((u,d)=>{const h=this.getAssetPlayer(u.identifier);h&&(d===c&&h.loadSource(),h.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(c=>c.pauseBuffering());this.hls.trigger(j.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:s.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return n}bufferedToItem(e,n=0){const r=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,n);else if(r!==null){this.bufferingAsset=null;const i=this.detachedData;i?i.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const n=this.findItemIndex(e),r=this.getPrimaryResumption(e,n);this.startLoadingPrimaryAt(r)}bufferedToEvent(e,n){const r=e.event,i=r.assetList.length===0&&!r.assetListLoader,s=r.cue.once;if(i||!s){const a=this.preloadAssets(r,n);if(a!=null&&a.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,n){const r=e.assetUrl,i=e.assetList.length,s=i===0&&!e.assetListLoader,a=e.cue.once;if(s){const l=e.timelineStart;if(e.appendInPlace){var o;const h=this.playingItem;!this.isInterstitial(h)&&(h==null||(o=h.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(l+.25)}let c,u=0;if(!this.playingItem&&this.primaryLive&&(u=this.hls.startPosition,u===-1&&(u=this.hls.liveSyncPosition||0)),u&&!(e.cue.pre||e.cue.post)){const h=u-l;h>0&&(c=Math.round(h*1e3)/1e3)}if(this.log(`Load interstitial asset ${n+1}/${r?1:i} ${e}${c?` live-start: ${u} start-offset: ${c}`:""}`),r)return this.createAsset(e,0,0,l,e.duration,r);const d=this.assetListLoader.loadAssetList(e,c);d&&(e.assetListLoader=d)}else if(!a&&i){for(let c=n;c<i;c++){const u=e.assetList[c],d=this.getAssetPlayerQueueIndex(u.identifier);(d===-1||this.playerQueue[d].destroyed)&&!u.error&&this.createAssetPlayer(e,u,c)}const l=e.assetList[n];if(l){const c=this.getAssetPlayer(l.identifier);return c&&c.loadSource(),c}}return null}flushFrontBuffer(e){const n=this.requiredTracks;if(!n)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(n).forEach(i=>{this.hls.trigger(j.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})})}getAssetPlayerQueueIndex(e){const n=this.playerQueue;for(let r=0;r<n.length;r++)if(e===n[r].assetId)return r;return-1}getAssetPlayer(e){const n=this.getAssetPlayerQueueIndex(e);return this.playerQueue[n]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:n}=this;if(n){for(let r=0;r<e.length;r++)if(e[r].media===n)return e[r]}return null}createAsset(e,n,r,i,s,a){const o={parentIdentifier:e.identifier,identifier:ahe(e,a,n),duration:s,startOffset:r,timelineStart:i,uri:a};return this.createAssetPlayer(e,o,n)}createAssetPlayer(e,n,r){const i=this.hls,s=i.userConfig;let a=s.videoPreference;const o=i.loadLevelObj||i.levels[i.currentLevel];(a||o)&&(a=fn({},a),o.videoCodec&&(a.videoCodec=o.videoCodec),o.videoRange&&(a.allowedVideoRanges=[o.videoRange]));const l=i.audioTracks[i.audioTrack],c=i.subtitleTracks[i.subtitleTrack];let u=0;if(this.primaryLive||e.appendInPlace){const E=this.timelinePos-n.timelineStart;if(E>1){const L=n.duration;L&&E<L&&(u=E)}}const d=n.identifier,h=on(on({},s),{},{maxMaxBufferLength:Math.min(180,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:d,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:l||s.audioPreference,subtitlePreference:c||s.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,n.timelineStart&&(h.timelineOffset=n.timelineStart));const f=h.cmcd;f!=null&&f.sessionId&&f.contentId&&(h.cmcd=fn({},f,{contentId:jf(n.uri)})),this.getAssetPlayer(d)&&this.warn(`Duplicate date range identifier ${e} and asset ${d}`);const p=new che(this.HlsPlayerClass,h,e,n);this.playerQueue.push(p),e.assetList[r]=n;let m=!0;const g=E=>{if(E.live){var L;const k=new Error(`Interstitials MUST be VOD assets ${e}`),I={fatal:!0,type:ct.OTHER_ERROR,details:xe.INTERSTITIAL_ASSET_ITEM_ERROR,error:k},R=((L=this.schedule)==null?void 0:L.findEventIndex(e.identifier))||-1;this.handleAssetItemError(I,e,R,r,k.message);return}const U=E.edge-E.fragmentStart,O=n.duration;(m||O===null||U>O)&&(m=!1,this.log(`Interstitial asset "${d}" duration change ${O} > ${U}`),n.duration=U,this.updateSchedule())};p.on(j.LEVEL_UPDATED,(E,{details:L})=>g(L)),p.on(j.LEVEL_PTS_UPDATED,(E,{details:L})=>g(L)),p.on(j.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const b=(E,L)=>{const U=this.getAssetPlayer(d);if(U&&L.tracks){U.off(j.BUFFER_CODECS,b),U.tracks=L.tracks;const O=this.primaryMedia;this.bufferingAsset===U.assetItem&&O&&!U.media&&this.bufferAssetPlayer(U,O)}};p.on(j.BUFFER_CODECS,b);const v=()=>{var E;const L=this.getAssetPlayer(d);if(this.log(`buffered to end of asset ${L}`),!L||!this.schedule)return;const U=this.schedule.findEventIndex(e.identifier),O=(E=this.schedule.items)==null?void 0:E[U];this.isInterstitial(O)&&this.advanceAssetBuffering(O,n)};p.on(j.BUFFERED_TO_END,v);const S=E=>()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;this.shouldPlay=!0;const U=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,U,E)};return p.once(j.MEDIA_ENDED,S(r)),p.once(j.PLAYOUT_LIMIT_REACHED,S(1/0)),p.on(j.ERROR,(E,L)=>{if(!this.schedule)return;const U=this.getAssetPlayer(d);if(L.details===xe.BUFFER_STALLED_ERROR){if(U!=null&&U.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(L,e,this.schedule.findEventIndex(e.identifier),r,`Asset player error ${L.error} ${e}`)}),p.on(j.DESTROYING,()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;const L=new Error(`Asset player destroyed unexpectedly ${d}`),U={fatal:!0,type:ct.OTHER_ERROR,details:xe.INTERSTITIAL_ASSET_ITEM_ERROR,error:L};this.handleAssetItemError(U,e,this.schedule.findEventIndex(e.identifier),r,L.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Uu(n)}`),this.hls.trigger(j.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:n,assetListIndex:r,event:e,player:p}),p}clearInterstitial(e,n){this.clearAssetPlayers(e,n),e.reset()}clearAssetPlayers(e,n){e.assetList.forEach(r=>{this.clearAssetPlayer(r.identifier,n)})}resetAssetPlayer(e){const n=this.getAssetPlayerQueueIndex(e);if(n!==-1){this.log(`reset asset player "${e}" after error`);const r=this.playerQueue[n];this.transferMediaFromPlayer(r,null),r.resetDetails()}}clearAssetPlayer(e,n){const r=this.getAssetPlayerQueueIndex(e);if(r!==-1){const i=this.playerQueue[r];this.log(`clear ${i} toSegment: ${n&&ws(n)}`),this.transferMediaFromPlayer(i,n),this.playerQueue.splice(r,1),i.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,n,r,i,s){const{interstitial:a,assetItem:o,assetId:l}=e,c=a.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!u||u.identifier!==l)&&(u&&(this.clearAssetPlayer(u.identifier,r[i]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${n+1}/${c} ${Uu(o)}`),this.hls.trigger(j.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:n,event:a,schedule:r.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,s)}bufferAssetPlayer(e,n){var r,i;if(!this.schedule)return;const{interstitial:s,assetItem:a}=e,o=this.schedule.findEventIndex(s.identifier),l=(r=this.schedule.items)==null?void 0:r[o];if(!l)return;e.loadSource(),this.setBufferingItem(l),this.bufferingAsset=a;const c=this.getBufferingPlayer();if(c===e)return;const u=s.appendInPlace;if(u&&(c==null?void 0:c.interstitial.appendInPlace)===!1)return;const d=(c==null?void 0:c.tracks)||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(u&&a!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(d&&!t3(d,e.tracks)){const h=new Error(`Asset ${Uu(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(d)}')`),f={fatal:!0,type:ct.OTHER_ERROR,details:xe.INTERSTITIAL_ASSET_ITEM_ERROR,error:h},p=s.findAssetIndex(a);this.handleAssetItemError(f,s,o,p,h.message);return}}this.transferMediaTo(e,n)}handleInPlaceStall(e){const n=this.schedule,r=this.primaryMedia;if(!n||!r)return;const i=r.currentTime,s=n.findAssetIndex(e,i),a=e.assetList[s];if(a){const o=this.getAssetPlayer(a.identifier);if(o){const l=o.currentTime||i-a.timelineStart,c=o.duration-l;if(this.warn(`Stalled at ${l} of ${l+c} in ${o} ${e} (media.currentTime: ${i})`),l&&(c/r.playbackRate<.5||o.bufferedInPlaceToEnd(r))&&o.hls){const u=n.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,u,s)}}}}advanceInPlace(e){const n=this.primaryMedia;n&&n.currentTime<e&&(n.currentTime=e)}handleAssetItemError(e,n,r,i,s){if(e.details===xe.BUFFER_STALLED_ERROR)return;const a=n.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&Uu(a)} ${e.error}`),!this.schedule)return;const o=(a==null?void 0:a.identifier)||"",l=this.getAssetPlayerQueueIndex(o),c=this.playerQueue[l]||null,u=this.schedule.items,d=fn({},e,{fatal:!1,errorAction:vd(!0),asset:a,assetListIndex:i,event:n,schedule:u,scheduleIndex:r,player:c});if(this.hls.trigger(j.INTERSTITIAL_ASSET_ERROR,d),!e.fatal)return;const h=this.playingAsset,f=this.bufferingAsset,p=new Error(s);if(a&&(this.clearAssetPlayer(o,null),a.error=p),!n.assetList.some(m=>!m.error))n.error=p;else for(let m=i;m<n.assetList.length;m++)this.resetAssetPlayer(n.assetList[m].identifier);this.updateSchedule(!0),n.error?this.primaryFallback(n):h&&h.identifier===o?this.advanceAfterAssetEnded(n,r,i):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){const n=e.timelineStart,r=this.effectivePlayingItem;let i=this.timelinePos;if(r){this.log(`Fallback to primary from event "${e.identifier}" start: ${n} pos: ${i} playing: ${ws(r)} error: ${e.error}`),i===-1&&(i=this.hls.startPosition);const a=this.updateItem(r,i);this.itemsMatch(r,a)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(n,null),this.flushFrontBuffer(n))}else if(i===-1){this.checkStart();return}if(!this.schedule)return;const s=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(s)}onAssetListLoaded(e,n){var r,i;const s=n.event,a=s.identifier,o=n.assetListResponse.ASSETS;if(!((r=this.schedule)!=null&&r.hasEvent(a)))return;const l=s.timelineStart,c=s.duration;let u=0;o.forEach((m,g)=>{const b=parseFloat(m.DURATION);this.createAsset(s,g,u,l+u,b,m.URI),u+=b}),s.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${c}) ${s}`);const d=this.waitingItem,h=(d==null?void 0:d.event.identifier)===a;this.updateSchedule();const f=(i=this.bufferingItem)==null?void 0:i.event;if(h){var p;const m=this.schedule.findEventIndex(a),g=(p=this.schedule.items)==null?void 0:p[m];if(g){if(!this.playingItem&&this.timelinePos>g.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==m){s.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${s}`),this.log(s.error.message),this.updateSchedule(!0),this.primaryFallback(s);return}this.setBufferingItem(g)}this.setSchedulePosition(m)}else if((f==null?void 0:f.identifier)===a){const m=s.assetList[0];if(m){const g=this.getAssetPlayer(m.identifier);if(f.appendInPlace){const b=this.primaryMedia;g&&b&&this.bufferAssetPlayer(g,b)}else g&&g.loadSource()}}}onError(e,n){if(this.schedule)switch(n.details){case xe.ASSET_LIST_PARSING_ERROR:case xe.ASSET_LIST_LOAD_ERROR:case xe.ASSET_LIST_LOAD_TIMEOUT:{const r=n.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break}case xe.BUFFER_STALLED_ERROR:{const r=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&r.event.appendInPlace){this.handleInPlaceStall(r.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const rD=500;class fhe extends GA{constructor(e,n,r){super(e,n,r,"subtitle-stream-controller",tt.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(j.LEVEL_LOADED,this.onLevelLoaded,this),e.on(j.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(j.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(j.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(j.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(j.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(j.LEVEL_LOADED,this.onLevelLoaded,this),e.off(j.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(j.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(j.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(j.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(j.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,n){this.stopLoad(),this.state=Oe.IDLE,this.setInterval(rD),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=n?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,n){this.tracksBuffered=[],super.onMediaDetaching(e,n)}onLevelLoaded(e,n){this.mainDetails=n.details}onSubtitleFragProcessed(e,n){const{frag:r,success:i}=n;if(this.fragContextChanged(r)||(Zn(r)&&(this.fragPrevious=r),this.state=Oe.IDLE),!i)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let a;const o=r.start;for(let c=0;c<s.length;c++)if(o>=s[c].start&&o<=s[c].end){a=s[c];break}const l=r.start+r.duration;a?a.end=l:(a={start:o,end:l},s.push(a)),this.fragmentTracker.fragBuffered(r),this.fragBufferedComplete(r,null),this.media&&this.tick()}onBufferFlushing(e,n){const{startOffset:r,endOffset:i}=n;if(r===0&&i!==Number.POSITIVE_INFINITY){const s=i-1;if(s<=0)return;n.endOffsetSubtitles=Math.max(0,s),this.tracksBuffered.forEach(a=>{for(let o=0;o<a.length;){if(a[o].end<=s){a.shift();continue}else if(a[o].start<s)a[o].start=s;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(r,s,tt.SUBTITLE)}}onError(e,n){const r=n.frag;(r==null?void 0:r.type)===tt.SUBTITLE&&(n.details===xe.FRAG_GAP&&this.fragmentTracker.fragBuffered(r,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Oe.STOPPED&&(this.state=Oe.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:n}){if(this.levels&&i4(this.levels,n)){this.levels=n.map(r=>new Tp(r));return}this.tracksBuffered=[],this.levels=n.map(r=>{const i=new Tp(r);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,tt.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,n){var r;if(this.currentTrackId=n.id,!((r=this.levels)!=null&&r.length)||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==Oe.STOPPED&&this.setInterval(rD)}onSubtitleTrackLoaded(e,n){var r;const{currentTrackId:i,levels:s}=this,{details:a,id:o}=n;if(!s){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const l=s[o];if(o>=s.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(a.live||(r=l.details)!=null&&r.live){if(a.deltaUpdateFailed)return;const d=this.mainDetails;if(!d){this.startFragRequested=!1;return}const h=d.fragments[0];if(!l.details)a.hasProgramDateTime&&d.hasProgramDateTime?(A0(a,d),c=a.fragmentStart):h&&(c=h.start,HE(a,c));else{var u;c=this.alignPlaylists(a,l.details,(u=this.levelLastLoaded)==null?void 0:u.details),c===0&&h&&(c=h.start,HE(a,c))}d&&!this.startFragRequested&&this.setStartPosition(d,c)}l.details=a,this.levelLastLoaded=l,o===i&&(this.hls.trigger(j.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:n.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===Oe.IDLE&&(Gc(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:n,payload:r}=e,i=n.decryptdata,s=this.hls;if(!this.fragContextChanged(n)&&r&&r.byteLength>0&&i!=null&&i.key&&i.iv&&_d(i.method)){const a=performance.now();this.decrypter.decrypt(new Uint8Array(r),i.key.buffer,i.iv.buffer,$A(i.method)).catch(o=>{throw s.trigger(j.ERROR,{type:ct.MEDIA_ERROR,details:xe.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:n}),o}).then(o=>{const l=performance.now();s.trigger(j.FRAG_DECRYPTED,{frag:n,payload:o,stats:{tstart:a,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=Oe.IDLE})}}doTick(){if(!this.media){this.state=Oe.IDLE;return}if(this.state===Oe.IDLE){const{currentTrackId:e,levels:n}=this,r=n==null?void 0:n[e];if(!r||!n.length||!r.details||this.waitForLive(r))return;const{config:i}=this,s=this.getLoadPosition(),a=Ct.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,i.maxBufferHole),{end:o,len:l}=a,c=r.details,u=this.hls.maxBufferLength+c.levelTargetDuration;if(l>u)return;const d=c.fragments,h=d.length,f=c.edge;let p=null;const m=this.fragPrevious;if(o<f){const v=i.maxFragLookUpTolerance,S=o>f-v?0:v;p=Gc(m,d,Math.max(d[0].start,o),S),!p&&m&&m.start<d[0].start&&(p=d[0])}else p=d[h-1];if(p=this.filterReplacedPrimary(p,r.details),!p)return;const g=p.sn-c.startSN,b=d[g-1];if(b&&b.cc===p.cc&&this.fragmentTracker.getState(b)===pr.NOT_LOADED&&(p=b),this.fragmentTracker.getState(p)===pr.NOT_LOADED){const v=this.mapToInitFragWhenRequired(p);v&&this.loadFragment(v,r,o)}}}loadFragment(e,n,r){Zn(e)?super.loadFragment(e,n,r):this._loadInitSegment(e,n)}get mediaBufferTimeRanges(){return new phe(this.tracksBuffered[this.currentTrackId]||[])}}class phe{constructor(e){this.buffered=void 0;const n=(r,i,s)=>{if(i=i>>>0,i>s-1)throw new DOMException(`Failed to execute '${r}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${s})`);return e[i][r]};this.buffered={get length(){return e.length},end(r){return n("end",r,e.length)},start(r){return n("start",r,e.length)}}}}const mhe={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},b4=t=>String.fromCharCode(mhe[t]||t),Rs=15,ja=100,ghe={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},yhe={17:2,18:4,21:6,22:8,23:10,19:13,20:15},vhe={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},_he={25:2,26:4,29:6,30:8,31:10,27:13,28:15},bhe=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class xhe{constructor(){this.time=null,this.verboseLevel=0}log(e,n){if(this.verboseLevel>=e){const r=typeof n=="function"?n():n;ln.log(`${this.time} [${e}] ${r}`)}}}const Wl=function(e){const n=[];for(let r=0;r<e.length;r++)n.push(e[r].toString(16));return n};class x4{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const n=["foreground","underline","italics","background","flash"];for(let r=0;r<n.length;r++){const i=n[r];e.hasOwnProperty(i)&&(this[i]=e[i])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class She{constructor(){this.uchar=" ",this.penState=new x4}reset(){this.uchar=" ",this.penState.reset()}setChar(e,n){this.uchar=e,this.penState.copy(n)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class Ehe{constructor(e){this.chars=[],this.pos=0,this.currPenState=new x4,this.cueStartTime=null,this.logger=void 0;for(let n=0;n<ja;n++)this.chars.push(new She);this.logger=e}equals(e){for(let n=0;n<ja;n++)if(!this.chars[n].equals(e.chars[n]))return!1;return!0}copy(e){for(let n=0;n<ja;n++)this.chars[n].copy(e.chars[n])}isEmpty(){let e=!0;for(let n=0;n<ja;n++)if(!this.chars[n].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>ja&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=ja)}moveCursor(e){const n=this.pos+e;if(e>1)for(let r=this.pos+1;r<n+1;r++)this.chars[r].setPenState(this.currPenState);this.setCursor(n)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const n=b4(e);if(this.pos>=ja){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+n+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(n,this.currPenState),this.moveCursor(1)}clearFromPos(e){let n;for(n=e;n<ja;n++)this.chars[n].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let n=!0;for(let r=0;r<ja;r++){const i=this.chars[r].uchar;i!==" "&&(n=!1),e.push(i)}return n?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class Jb{constructor(e){this.rows=[],this.currRow=Rs-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let n=0;n<Rs;n++)this.rows.push(new Ehe(e));this.logger=e}reset(){for(let e=0;e<Rs;e++)this.rows[e].clear();this.currRow=Rs-1}equals(e){let n=!0;for(let r=0;r<Rs;r++)if(!this.rows[r].equals(e.rows[r])){n=!1;break}return n}copy(e){for(let n=0;n<Rs;n++)this.rows[n].copy(e.rows[n])}isEmpty(){let e=!0;for(let n=0;n<Rs;n++)if(!this.rows[n].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+yn(e));let n=e.row-1;if(this.nrRollUpRows&&n<this.nrRollUpRows-1&&(n=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==n){for(let o=0;o<Rs;o++)this.rows[o].clear();const s=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[s].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let c=0;c<this.nrRollUpRows;c++)this.rows[n-this.nrRollUpRows+c+1].copy(a.rows[s+c])}}this.currRow=n;const r=this.rows[this.currRow];if(e.indent!==null){const s=e.indent,a=Math.max(s-1,0);r.setCursor(e.indent),e.color=r.chars[a].penState.foreground}const i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+yn(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,n=this.rows.splice(e,1)[0];n.clear(),this.rows.splice(this.currRow,0,n),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const n=[];let r="",i=-1;for(let s=0;s<Rs;s++){const a=this.rows[s].getTextString();a&&(i=s+1,e?n.push("Row "+i+": '"+a+"'"):n.push(a.trim()))}return n.length>0&&(e?r="["+n.join(" | ")+"]":r=n.join(`
`)),r}getTextAndFormat(){return this.rows}}class iD{constructor(e,n,r){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=n,this.mode=null,this.verbose=0,this.displayedMemory=new Jb(r),this.nonDisplayedMemory=new Jb(r),this.lastOutputScreen=new Jb(r),this.currRollUpRow=this.displayedMemory.rows[Rs-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Rs-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let r=0;r<e.length;r++)this.writeScreen.insertChar(e[r]);const n=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>n+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const n={flash:!1};if(n.underline=e%2===1,n.italics=e>=46,n.italics)n.foreground="white";else{const r=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];n.foreground=i[r]}this.logger.log(2,"MIDROW: "+yn(n)),this.writeScreen.setPen(n)}outputDataUpdate(e=!1){const n=this.logger.time;n!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=n:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,n,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:n),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class sD{constructor(e,n,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=The(),this.logger=void 0;const i=this.logger=new xhe;this.channels=[null,new iD(e,n,i),new iD(e+1,r,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,n){this.channels[e].setHandler(n)}addData(e,n){this.logger.time=e;for(let r=0;r<n.length;r+=2){const i=n[r]&127,s=n[r+1]&127;let a=!1,o=null;if(i===0&&s===0)continue;this.logger.log(3,()=>"["+Wl([n[r],n[r+1]])+"] -> ("+Wl([i,s])+")");const l=this.cmdHistory;if(i>=16&&i<=31){if(whe(i,s,l)){Rg(null,null,l),this.logger.log(3,()=>"Repeated command ("+Wl([i,s])+") is dropped");continue}Rg(i,s,this.cmdHistory),a=this.parseCmd(i,s),a||(a=this.parseMidrow(i,s)),a||(a=this.parsePAC(i,s)),a||(a=this.parseBackgroundAttributes(i,s))}else Rg(null,null,l);if(!a&&(o=this.parseChars(i,s),o)){const u=this.currentChannel;u&&u>0?this.channels[u].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Wl([i,s])+" orig: "+Wl([n[r],n[r+1]]))}}parseCmd(e,n){const r=(e===20||e===28||e===21||e===29)&&n>=32&&n<=47,i=(e===23||e===31)&&n>=33&&n<=35;if(!(r||i))return!1;const s=e===20||e===21||e===23?1:2,a=this.channels[s];return e===20||e===21||e===28||e===29?n===32?a.ccRCL():n===33?a.ccBS():n===34?a.ccAOF():n===35?a.ccAON():n===36?a.ccDER():n===37?a.ccRU(2):n===38?a.ccRU(3):n===39?a.ccRU(4):n===40?a.ccFON():n===41?a.ccRDC():n===42?a.ccTR():n===43?a.ccRTD():n===44?a.ccEDM():n===45?a.ccCR():n===46?a.ccENM():n===47&&a.ccEOC():a.ccTO(n-32),this.currentChannel=s,!0}parseMidrow(e,n){let r=0;if((e===17||e===25)&&n>=32&&n<=47){if(e===17?r=1:r=2,r!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[r];return i?(i.ccMIDROW(n),this.logger.log(3,()=>"MIDROW ("+Wl([e,n])+")"),!0):!1}return!1}parsePAC(e,n){let r;const i=(e>=17&&e<=23||e>=25&&e<=31)&&n>=64&&n<=127,s=(e===16||e===24)&&n>=64&&n<=95;if(!(i||s))return!1;const a=e<=23?1:2;n>=64&&n<=95?r=a===1?ghe[e]:vhe[e]:r=a===1?yhe[e]:_he[e];const o=this.channels[a];return o?(o.setPAC(this.interpretPAC(r,n)),this.currentChannel=a,!0):!1}interpretPAC(e,n){let r;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return n>95?r=n-96:r=n-64,i.underline=(r&1)===1,r<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((r-16)/2)*4,i}parseChars(e,n){let r,i=null,s=null;if(e>=25?(r=2,s=e-8):(r=1,s=e),s>=17&&s<=19){let a;s===17?a=n+80:s===18?a=n+112:a=n+144,this.logger.log(2,()=>"Special char '"+b4(a)+"' in channel "+r),i=[a]}else e>=32&&e<=127&&(i=n===0?[e]:[e,n]);return i&&this.logger.log(3,()=>"Char codes =  "+Wl(i).join(",")),i}parseBackgroundAttributes(e,n){const r=(e===16||e===24)&&n>=32&&n<=47,i=(e===23||e===31)&&n>=45&&n<=47;if(!(r||i))return!1;let s;const a={};e===16||e===24?(s=Math.floor((n-32)/2),a.background=bhe[s],n%2===1&&(a.background=a.background+"_semi")):n===45?a.background="transparent":(a.foreground="black",n===47&&(a.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(a),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const n=this.channels[e];n&&n.reset()}Rg(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let n=0;n<this.channels.length;n++){const r=this.channels[n];r&&r.cueSplitAtTime(e)}}}function Rg(t,e,n){n.a=t,n.b=e}function whe(t,e,n){return n.a===t&&n.b===e}function The(){return{a:null,b:null}}var t1=function(){if(T0!=null&&T0.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function n(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;const c=l.toLowerCase();return~o.indexOf(c)?c:!1}function r(o){return n(t,o)}function i(o){return n(e,o)}function s(o,...l){let c=1;for(;c<arguments.length;c++){const u=arguments[c];for(const d in u)o[d]=u[d]}return o}function a(o,l,c){const u=this,d={enumerable:!0};u.hasBeenReset=!1;let h="",f=!1,p=o,m=l,g=c,b=null,v="",S=!0,E="auto",L="start",U=50,O="middle",k=50,I="middle";Object.defineProperty(u,"id",s({},d,{get:function(){return h},set:function(R){h=""+R}})),Object.defineProperty(u,"pauseOnExit",s({},d,{get:function(){return f},set:function(R){f=!!R}})),Object.defineProperty(u,"startTime",s({},d,{get:function(){return p},set:function(R){if(typeof R!="number")throw new TypeError("Start time must be set to a number.");p=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"endTime",s({},d,{get:function(){return m},set:function(R){if(typeof R!="number")throw new TypeError("End time must be set to a number.");m=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"text",s({},d,{get:function(){return g},set:function(R){g=""+R,this.hasBeenReset=!0}})),Object.defineProperty(u,"region",s({},d,{get:function(){return b},set:function(R){b=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"vertical",s({},d,{get:function(){return v},set:function(R){const M=r(R);if(M===!1)throw new SyntaxError("An invalid or illegal string was specified.");v=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"snapToLines",s({},d,{get:function(){return S},set:function(R){S=!!R,this.hasBeenReset=!0}})),Object.defineProperty(u,"line",s({},d,{get:function(){return E},set:function(R){if(typeof R!="number"&&R!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");E=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"lineAlign",s({},d,{get:function(){return L},set:function(R){const M=i(R);if(!M)throw new SyntaxError("An invalid or illegal string was specified.");L=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"position",s({},d,{get:function(){return U},set:function(R){if(R<0||R>100)throw new Error("Position must be between 0 and 100.");U=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",s({},d,{get:function(){return O},set:function(R){const M=i(R);if(!M)throw new SyntaxError("An invalid or illegal string was specified.");O=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",s({},d,{get:function(){return k},set:function(R){if(R<0||R>100)throw new Error("Size must be between 0 and 100.");k=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",s({},d,{get:function(){return I},set:function(R){const M=i(R);if(!M)throw new SyntaxError("An invalid or illegal string was specified.");I=M,this.hasBeenReset=!0}})),u.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}();class Ahe{decode(e,n){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function S4(t){function e(r,i,s,a){return(r|0)*3600+(i|0)*60+(s|0)+parseFloat(a||0)}const n=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return n?parseFloat(n[2])>59?e(n[2],n[3],0,n[4]):e(n[1],n[2],n[3],n[4]):null}class Rhe{constructor(){this.values=Object.create(null)}set(e,n){!this.get(e)&&n!==""&&(this.values[e]=n)}get(e,n,r){return r?this.has(e)?this.values[e]:n[r]:this.has(e)?this.values[e]:n}has(e){return e in this.values}alt(e,n,r){for(let i=0;i<r.length;++i)if(n===r[i]){this.set(e,n);break}}integer(e,n){/^-?\d+$/.test(n)&&this.set(e,parseInt(n,10))}percent(e,n){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(n)){const r=parseFloat(n);if(r>=0&&r<=100)return this.set(e,r),!0}return!1}}function E4(t,e,n,r){const i=r?t.split(r):[t];for(const s in i){if(typeof i[s]!="string")continue;const a=i[s].split(n);if(a.length!==2)continue;const o=a[0],l=a[1];e(o,l)}}const JE=new t1(0,0,""),Cg=JE.align==="middle"?"middle":"center";function Che(t,e,n){const r=t;function i(){const o=S4(t);if(o===null)throw new Error("Malformed timestamp: "+r);return t=t.replace(/^[^\sa-zA-Z-]+/,""),o}function s(o,l){const c=new Rhe;E4(o,function(h,f){let p;switch(h){case"region":for(let m=n.length-1;m>=0;m--)if(n[m].id===f){c.set(h,n[m].region);break}break;case"vertical":c.alt(h,f,["rl","lr"]);break;case"line":p=f.split(","),c.integer(h,p[0]),c.percent(h,p[0])&&c.set("snapToLines",!1),c.alt(h,p[0],["auto"]),p.length===2&&c.alt("lineAlign",p[1],["start",Cg,"end"]);break;case"position":p=f.split(","),c.percent(h,p[0]),p.length===2&&c.alt("positionAlign",p[1],["start",Cg,"end","line-left","line-right","auto"]);break;case"size":c.percent(h,f);break;case"align":c.alt(h,f,["start",Cg,"end","left","right"]);break}},/:/,/\s/),l.region=c.get("region",null),l.vertical=c.get("vertical","");let u=c.get("line","auto");u==="auto"&&JE.line===-1&&(u=-1),l.line=u,l.lineAlign=c.get("lineAlign","start"),l.snapToLines=c.get("snapToLines",!0),l.size=c.get("size",100),l.align=c.get("align",Cg);let d=c.get("position","auto");d==="auto"&&JE.position===50&&(d=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=d}function a(){t=t.replace(/^\s+/,"")}if(a(),e.startTime=i(),a(),t.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+r);t=t.slice(3),a(),e.endTime=i(),a(),s(t,e)}function w4(t){return t.replace(/<br(?: \/)?>/gi,`
`)}class Lhe{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Ahe,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const n=this;e&&(n.buffer+=n.decoder.decode(e,{stream:!0}));function r(){let s=n.buffer,a=0;for(s=w4(s);a<s.length&&s[a]!=="\r"&&s[a]!==`
`;)++a;const o=s.slice(0,a);return s[a]==="\r"&&++a,s[a]===`
`&&++a,n.buffer=s.slice(a),o}function i(s){E4(s,function(a,o){},/:/)}try{let s="";if(n.state==="INITIAL"){if(!/\r\n|\n/.test(n.buffer))return this;s=r();const o=s.match(/^(ï»¿)?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");n.state="HEADER"}let a=!1;for(;n.buffer;){if(!/\r\n|\n/.test(n.buffer))return this;switch(a?a=!1:s=r(),n.state){case"HEADER":/:/.test(s)?i(s):s||(n.state="ID");continue;case"NOTE":s||(n.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(s)){n.state="NOTE";break}if(!s)continue;if(n.cue=new t1(0,0,""),n.state="CUE",s.indexOf("-->")===-1){n.cue.id=s;continue}case"CUE":if(!n.cue){n.state="BADCUE";continue}try{Che(s,n.cue,n.regionList)}catch{n.cue=null,n.state="BADCUE";continue}n.state="CUETEXT";continue;case"CUETEXT":{const o=s.indexOf("-->")!==-1;if(!s||o&&(a=!0)){n.oncue&&n.cue&&n.oncue(n.cue),n.cue=null,n.state="ID";continue}if(n.cue===null)continue;n.cue.text&&(n.cue.text+=`
`),n.cue.text+=s}continue;case"BADCUE":s||(n.state="ID")}}}catch{n.state==="CUETEXT"&&n.cue&&n.oncue&&n.oncue(n.cue),n.cue=null,n.state=n.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`

`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(n){e.onparsingerror&&e.onparsingerror(n)}return e.onflush&&e.onflush(),this}}const khe=/\r\n|\n\r|\n|\r/g,Zb=function(e,n,r=0){return e.slice(r,r+n.length)===n},Ihe=function(e){let n=parseInt(e.slice(-3));const r=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),s=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!Ze(n)||!Ze(r)||!Ze(i)||!Ze(s))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return n+=1e3*r,n+=60*1e3*i,n+=60*60*1e3*s,n};function n1(t,e,n){return jf(t.toString())+jf(e.toString())+jf(n)}const Phe=function(e,n,r){let i=e[n],s=e[i.prevCC];if(!s||!s.new&&i.new){e.ccOffset=e.presentationOffset=i.start,i.new=!1;return}for(;(a=s)!=null&&a.new;){var a;e.ccOffset+=i.start-s.start,i.new=!1,i=s,s=e[i.prevCC]}e.presentationOffset=r};function Dhe(t,e,n,r,i,s,a){const o=new Lhe,l=Ki(new Uint8Array(t)).trim().replace(khe,`
`).split(`
`),c=[],u=e?jue(e.baseTime,e.timescale):0;let d="00:00.000",h=0,f=0,p,m=!0;o.oncue=function(g){const b=n[r];let v=n.ccOffset;const S=(h-u)/9e4;if(b!=null&&b.new&&(f!==void 0?v=n.ccOffset=b.start:Phe(n,r,S)),S){if(!e){p=new Error("Missing initPTS for VTT MPEGTS");return}v=S-n.presentationOffset}const E=g.endTime-g.startTime,L=ki((g.startTime+v-f)*9e4,i*9e4)/9e4;g.startTime=Math.max(L,0),g.endTime=Math.max(L+E,0);const U=g.text.trim();g.text=decodeURIComponent(encodeURIComponent(U)),g.id||(g.id=n1(g.startTime,g.endTime,U)),g.endTime>0&&c.push(g)},o.onparsingerror=function(g){p=g},o.onflush=function(){if(p){a(p);return}s(c)},l.forEach(g=>{if(m)if(Zb(g,"X-TIMESTAMP-MAP=")){m=!1,g.slice(16).split(",").forEach(b=>{Zb(b,"LOCAL:")?d=b.slice(6):Zb(b,"MPEGTS:")&&(h=parseInt(b.slice(7)))});try{f=Ihe(d)/1e3}catch(b){p=b}return}else g===""&&(m=!1);o.parse(g+`
`)}),o.flush()}const ex="stpp.ttml.im1t",T4=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,A4=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Ohe={left:"start",center:"center",right:"end",start:"start",end:"end"};function aD(t,e,n,r){const i=Bt(new Uint8Array(t),["mdat"]);if(i.length===0){r(new Error("Could not parse IMSC1 mdat"));return}const s=i.map(o=>Ki(o)),a=Uue(e.baseTime,1,e.timescale);try{s.forEach(o=>n(Nhe(o,a)))}catch(o){r(o)}}function Nhe(t,e){const i=new DOMParser().parseFromString(t,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const s={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(s).reduce((d,h)=>(d[h]=i.getAttribute(`ttp:${h}`)||s[h],d),{}),o=i.getAttribute("xml:space")!=="preserve",l=oD(tx(i,"styling","style")),c=oD(tx(i,"layout","region")),u=tx(i,"body","[begin]");return[].map.call(u,d=>{const h=R4(d,o);if(!h||!d.hasAttribute("begin"))return null;const f=rx(d.getAttribute("begin"),a),p=rx(d.getAttribute("dur"),a);let m=rx(d.getAttribute("end"),a);if(f===null)throw lD(d);if(m===null){if(p===null)throw lD(d);m=f+p}const g=new t1(f-e,m-e,h);g.id=n1(g.startTime,g.endTime,g.text);const b=c[d.getAttribute("region")],v=l[d.getAttribute("style")],S=Mhe(b,v,l),{textAlign:E}=S;if(E){const L=Ohe[E];L&&(g.lineAlign=L),g.align=E}return fn(g,S),g}).filter(d=>d!==null)}function tx(t,e,n){const r=t.getElementsByTagName(e)[0];return r?[].slice.call(r.querySelectorAll(n)):[]}function oD(t){return t.reduce((e,n)=>{const r=n.getAttribute("xml:id");return r&&(e[r]=n),e},{})}function R4(t,e){return[].slice.call(t.childNodes).reduce((n,r,i)=>{var s;return r.nodeName==="br"&&i?n+`
`:(s=r.childNodes)!=null&&s.length?R4(r,e):e?n+r.textContent.trim().replace(/\s+/g," "):n+r.textContent},"")}function Mhe(t,e,n){const r="http://www.w3.org/ns/ttml#styling";let i=null;const s=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=t!=null&&t.hasAttribute("style")?t.getAttribute("style"):null;return a&&n.hasOwnProperty(a)&&(i=n[a]),s.reduce((o,l)=>{const c=nx(e,r,l)||nx(t,r,l)||nx(i,r,l);return c&&(o[l]=c),o},{})}function nx(t,e,n){return t&&t.hasAttributeNS(e,n)?t.getAttributeNS(e,n):null}function lD(t){return new Error(`Could not parse ttml timestamp ${t}`)}function rx(t,e){if(!t)return null;let n=S4(t);return n===null&&(T4.test(t)?n=Bhe(t,e):A4.test(t)&&(n=Uhe(t,e))),n}function Bhe(t,e){const n=T4.exec(t),r=(n[4]|0)+(n[5]|0)/e.subFrameRate;return(n[1]|0)*3600+(n[2]|0)*60+(n[3]|0)+r/e.frameRate}function Uhe(t,e){const n=A4.exec(t),r=Number(n[1]);switch(n[2]){case"h":return r*3600;case"m":return r*60;case"ms":return r*1e3;case"f":return r/e.frameRate;case"t":return r/e.tickRate}return r}class Lg{constructor(e,n){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=n}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,n,r){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=n,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class jhe{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=uD(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(j.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(j.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(j.MANIFEST_LOADING,this.onManifestLoading,this),e.on(j.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(j.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(j.FRAG_LOADING,this.onFragLoading,this),e.on(j.FRAG_LOADED,this.onFragLoaded,this),e.on(j.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(j.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(j.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(j.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(j.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(j.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(j.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(j.MANIFEST_LOADING,this.onManifestLoading,this),e.off(j.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(j.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(j.FRAG_LOADING,this.onFragLoading,this),e.off(j.FRAG_LOADED,this.onFragLoaded,this),e.off(j.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(j.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(j.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(j.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(j.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new Lg(this,"textTrack1"),n=new Lg(this,"textTrack2"),r=new Lg(this,"textTrack3"),i=new Lg(this,"textTrack4");this.cea608Parser1=new sD(1,e,n),this.cea608Parser2=new sD(3,r,i)}addCues(e,n,r,i,s){let a=!1;for(let o=s.length;o--;){const l=s[o],c=Fhe(l[0],l[1],n,r);if(c>=0&&(l[0]=Math.min(l[0],n),l[1]=Math.max(l[1],r),a=!0,c/(r-n)>.5))return}if(a||s.push([n,r]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,n,r,i)}else{const o=this.Cues.newCue(null,n,r,i);this.hls.trigger(j.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:n,id:r,initPTS:i,timescale:s,trackId:a}){const{unparsedVttFrags:o}=this;r===tt.MAIN&&(this.initPTS[n.cc]={baseTime:i,timescale:s,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(l=>{this.initPTS[l.frag.cc]?this.onFragLoaded(j.FRAG_LOADED,l):this.hls.trigger(j.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:l.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,n){const{media:r}=this;if(r)for(let i=0;i<r.textTracks.length;i++){const s=r.textTracks[i];if(cD(s,{name:e,lang:n,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return s}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:n,captionsTracks:r,media:i}=this,{label:s,languageCode:a}=n[e],o=this.getExistingTrack(s,a);if(o)r[e]=o,rd(r[e]),y4(r[e],i);else{const l=this.createTextTrack("captions",s,a);l&&(l[e]=!0,r[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const n=this.captionsProperties[e];if(!n)return;const r=n.label,i={_id:e,label:r,kind:"captions",default:n.media?!!n.media.default:!1,closedCaptions:n.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(j.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,n,r){const i=this.media;if(i)return i.addTextTrack(e,n,r)}onMediaAttaching(e,n){this.media=n.media,n.mediaSource||this._cleanTracks()}onMediaDetaching(e,n){const r=!!n.transferMedia;if(this.media=null,r)return;const{captionsTracks:i}=this;Object.keys(i).forEach(s=>{rd(i[s]),delete i[s]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=uD(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const n=e.textTracks;if(n)for(let r=0;r<n.length;r++)rd(n[r])}onSubtitleTracksUpdated(e,n){const r=n.subtitleTracks||[],i=r.some(s=>s.textCodec===ex);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(i4(this.tracks,r)){this.tracks=r;return}if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){const a=this.media,o=a?fy(a.textTracks):null;if(this.tracks.forEach((l,c)=>{let u;if(o){let d=null;for(let h=0;h<o.length;h++)if(o[h]&&cD(o[h],l)){d=o[h],o[h]=null;break}d&&(u=d)}if(u)rd(u);else{const d=C4(l);u=this.createTextTrack(d,l.name,l.lang),u&&(u.mode="disabled")}u&&this.textTracks.push(u)}),o!=null&&o.length){const l=o.filter(c=>c!==null).map(c=>c.label);l.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(j.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,n){this.config.enableCEA708Captions&&n.captions&&n.captions.forEach(r=>{const i=/(?:CC|SERVICE)([1-4])/.exec(r.instreamId);if(!i)return;const s=`textTrack${i[1]}`,a=this.captionsProperties[s];a&&(a.label=r.name,r.lang&&(a.languageCode=r.lang),a.media=r)})}closedCaptionsForLevel(e){const n=this.hls.levels[e.level];return n==null?void 0:n.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,n){if(this.enabled&&n.frag.type===tt.MAIN){var r,i;const{cea608Parser1:s,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:c}=n.frag,u=(r=(i=n.part)==null?void 0:i.index)!=null?r:-1;s&&a&&(c!==o+1||c===o&&u!==this.lastPartIndex+1||l!==this.lastCc)&&(s.reset(),a.reset()),this.lastCc=l,this.lastSn=c,this.lastPartIndex=u}}onFragLoaded(e,n){const{frag:r,payload:i}=n;if(r.type===tt.SUBTITLE)if(i.byteLength){const s=r.decryptdata,a="stats"in n;if(s==null||!s.encrypted||a){const o=this.tracks[r.level],l=this.vttCCs;l[r.cc]||(l[r.cc]={start:r.start,prevCC:this.prevCC,new:!0},this.prevCC=r.cc),o&&o.textCodec===ex?this._parseIMSC1(r,i):this._parseVTTs(n)}}else this.hls.trigger(j.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,n){const r=this.hls;aD(n,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),r.trigger(j.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{r.logger.log(`Failed to parse IMSC1: ${i}`),r.trigger(j.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var n;const{frag:r,payload:i}=e,{initPTS:s,unparsedVttFrags:a}=this,o=s.length-1;if(!s[r.cc]&&o===-1){a.push(e);return}const l=this.hls,c=(n=r.initSegment)!=null&&n.data?ys(r.initSegment.data,new Uint8Array(i)).buffer:i;Dhe(c,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,u=>{this._appendCues(u,r.level),l.trigger(j.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})},u=>{const d=u.message==="Missing initPTS for VTT MPEGTS";d?a.push(e):this._fallbackToIMSC1(r,i),l.logger.log(`Failed to parse VTT cue: ${u}`),!(d&&o>r.cc)&&l.trigger(j.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:u})})}_fallbackToIMSC1(e,n){const r=this.tracks[e.level];r.textCodec||aD(n,this.initPTS[e.cc],()=>{r.textCodec=ex,this._parseIMSC1(e,n)},()=>{r.textCodec="wvtt"})}_appendCues(e,n){const r=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[n];if(!i||i.mode==="disabled")return;e.forEach(s=>v4(i,s))}else{const i=this.tracks[n];if(!i)return;const s=i.default?"default":"subtitles"+n;r.trigger(j.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,n){const{frag:r}=n;r.type===tt.SUBTITLE&&this.onFragLoaded(j.FRAG_LOADED,n)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,n){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:r,samples:i}=n;if(!(r.type===tt.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let s=0;s<i.length;s++){const a=i[s].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(a);this.cea608Parser1.addData(i[s].pts,o[0]),this.cea608Parser2.addData(i[s].pts,o[1])}}}onBufferFlushing(e,{startOffset:n,endOffset:r,endOffsetSubtitles:i,type:s}){const{media:a}=this;if(!(!a||a.currentTime<r)){if(!s||s==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(l=>QE(o[l],n,r))}if(this.config.renderTextTracksNatively&&n===0&&i!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(l=>QE(o[l],n,i))}}}extractCea608Data(e){const n=[[],[]],r=e[0]&31;let i=2;for(let s=0;s<r;s++){const a=e[i++],o=127&e[i++],l=127&e[i++];if(o===0&&l===0)continue;if((4&a)!==0){const u=3&a;(u===0||u===1)&&(n[u].push(o),n[u].push(l))}}return n}}function C4(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function cD(t,e){return!!t&&t.kind===C4(e)&&qE(e,t)}function Fhe(t,e,n,r){return Math.min(e,r)-Math.max(t,n)}function uD(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const $he=/\s/,Vhe={newCue(t,e,n,r){const i=[];let s,a,o,l,c;const u=self.VTTCue||self.TextTrackCue;for(let h=0;h<r.rows.length;h++)if(s=r.rows[h],o=!0,l=0,c="",!s.isEmpty()){var d;for(let m=0;m<s.chars.length;m++)$he.test(s.chars[m].uchar)&&o?l++:(c+=s.chars[m].uchar,o=!1);s.cueStartTime=e,e===n&&(n+=1e-4),l>=16?l--:l++;const f=w4(c.trim()),p=n1(e,n,f);t!=null&&(d=t.cues)!=null&&d.getCueById(p)||(a=new u(e,n,f),a.id=p,a.line=h+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),i.push(a))}return t&&i.length&&(i.sort((h,f)=>h.line==="auto"||f.line==="auto"?0:h.line>8&&f.line>8?f.line-h.line:h.line-f.line),i.forEach(h=>v4(t,h))),i}};function Ghe(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const Hhe=/(\d+)-(\d+)\/(\d+)/;class dD{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||Whe,this.controller=new self.AbortController,this.stats=new OA}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,n,r){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const s=Khe(e,this.controller.signal),a=e.responseType==="arraybuffer",o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:c}=n.loadPolicy;this.context=e,this.config=n,this.callbacks=r,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),n.timeout=l&&Ze(l)?l:c,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},n.timeout),(Cp(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(d=>{var h;this.response=this.loader=d;const f=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),n.timeout=c,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},c-(f-i.loading.start)),!d.ok){const{status:m,statusText:g}=d;throw new Yhe(g||"fetch, bad network response",m,d)}i.loading.first=f,i.total=qhe(d.headers)||i.total;const p=(h=this.callbacks)==null?void 0:h.onProgress;return p&&Ze(n.highWaterMark)?this.loadProgressively(d,i,e,n.highWaterMark,p):a?d.arrayBuffer():e.responseType==="json"?d.json():d.text()}).then(d=>{var h,f;const p=this.response;if(!p)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const m=d[o];m&&(i.loaded=i.total=m);const g={url:p.url,data:d,code:p.status},b=(h=this.callbacks)==null?void 0:h.onProgress;b&&!Ze(n.highWaterMark)&&b(i,e,d,p),(f=this.callbacks)==null||f.onSuccess(g,i,e,p)}).catch(d=>{var h;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const f=d&&d.code||0,p=d?d.message:null;(h=this.callbacks)==null||h.onError({code:f,text:p},e,d?d.details:null,i)})}getCacheAge(){let e=null;if(this.response){const n=this.response.headers.get("age");e=n?parseFloat(n):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,n,r,i=0,s){const a=new U3,o=e.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return a.dataLength&&s(n,r,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const u=c.value,d=u.length;return n.loaded+=d,d<i||a.dataLength?(a.push(u),a.dataLength>=i&&s(n,r,a.flush().buffer,e)):s(n,r,u.buffer,e),l()}).catch(()=>Promise.reject());return l()}}function Khe(t,e){const n={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(fn({},t.headers))};return t.rangeEnd&&n.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)),n}function zhe(t){const e=Hhe.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}function qhe(t){const e=t.get("Content-Range");if(e){const r=zhe(e);if(Ze(r))return r}const n=t.get("Content-Length");if(n)return parseInt(n)}function Whe(t,e){return new self.Request(t.url,e)}class Yhe extends Error{constructor(e,n,r){super(e),this.code=void 0,this.details=void 0,this.code=n,this.details=r}}const Xhe=/^age:\s*[\d.]+\s*$/im;class L4{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new OA,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,n,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=n,this.callbacks=r,this.loadInternal()}loadInternal(){const{config:e,context:n}=this;if(!e||!n)return;const r=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then(()=>{if(!(this.loader!==r||this.stats.aborted))return s(r,n.url)}).catch(a=>{if(!(this.loader!==r||this.stats.aborted))return r.open("GET",n.url,!0),s(r,n.url)}).then(()=>{this.loader!==r||this.stats.aborted||this.openAndSendXhr(r,n,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:r.status,text:a.message},n,r,i)}):this.openAndSendXhr(r,n,e)}openAndSendXhr(e,n,r){e.readyState||e.open("GET",n.url,!0);const i=n.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:a}=r.loadPolicy;if(i)for(const o in i)e.setRequestHeader(o,i[o]);n.rangeEnd&&e.setRequestHeader("Range","bytes="+n.rangeStart+"-"+(n.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=n.responseType,self.clearTimeout(this.requestTimeout),r.timeout=s&&Ze(s)?s:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()}readystatechange(){const{context:e,loader:n,stats:r}=this;if(!e||!n)return;const i=n.readyState,s=this.config;if(!r.aborted&&i>=2&&(r.loading.first===0&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),n.onreadystatechange=null,n.onprogress=null;const c=n.status,u=n.responseType==="text"?n.responseText:null;if(c>=200&&c<300){const p=u??n.response;if(p!=null){var a,o;r.loading.end=Math.max(self.performance.now(),r.loading.first);const m=n.responseType==="arraybuffer"?p.byteLength:p.length;r.loaded=r.total=m,r.bwEstimate=r.total*8e3/(r.loading.end-r.loading.first);const g=(a=this.callbacks)==null?void 0:a.onProgress;g&&g(r,e,p,n);const b={url:n.responseURL,data:p,code:c};(o=this.callbacks)==null||o.onSuccess(b,r,e,n);return}}const d=s.loadPolicy.errorRetry,h=r.retry,f={url:e.url,data:void 0,code:c};if(E0(d,h,!1,f))this.retry(d);else{var l;ln.error(`${c} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:c,text:n.statusText},e,n,r)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,n=this.stats.retry;if(E0(e,n,!0))this.retry(e);else{var r;ln.warn(`timeout while loading ${(r=this.context)==null?void 0:r.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:n,stats:r}=this;this.retryDelay=UA(e,r.retry),r.retry++,ln.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${n==null?void 0:n.url}, retrying ${r.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const n=this.stats;n.loaded=e.loaded,e.lengthComputable&&(n.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Xhe.test(this.loader.getAllResponseHeaders())){const n=this.loader.getResponseHeader("age");e=n?parseFloat(n):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const Qhe={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Jhe=on(on({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:L4,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:uce,bufferController:ede,capLevelController:JA,errorController:mce,fpsController:the,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:R3,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:Qhe},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},Zhe()),{},{subtitleStreamController:fhe,subtitleTrackController:ihe,timelineController:jhe,audioStreamController:Xue,audioTrackController:Que,emeController:bd,cmcdController:Qde,contentSteeringController:Zde,interstitialsController:hhe});function Zhe(){return{cueHandler:Vhe,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function efe(t,e,n){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const r=ZE(t),i=["manifest","level","frag"],s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(a=>{const o=`${a==="level"?"playlist":a}LoadPolicy`,l=e[o]===void 0,c=[];s.forEach(u=>{const d=`${a}Loading${u}`,h=e[d];if(h!==void 0&&l){c.push(d);const f=r[o].default;switch(e[o]={default:f},u){case"TimeOut":f.maxLoadTimeMs=h,f.maxTimeToFirstByteMs=h;break;case"MaxRetry":f.errorRetry.maxNumRetry=h,f.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":f.errorRetry.retryDelayMs=h,f.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=h,f.timeoutRetry.maxRetryDelayMs=h;break}}}),c.length&&n.warn(`hls.js config: "${c.join('", "')}" setting(s) are deprecated, use "${o}": ${yn(e[o])}`)}),on(on({},r),e)}function ZE(t){return t&&typeof t=="object"?Array.isArray(t)?t.map(ZE):Object.keys(t).reduce((e,n)=>(e[n]=ZE(t[n]),e),{}):t}function tfe(t,e){const n=t.loader;n!==dD&&n!==L4?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):Ghe()&&(t.loader=dD,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const py=2,nfe=.1,rfe=.05,ife=100;class sfe extends S3{constructor(e,n){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var r;(r=this.media)!=null&&r.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var r;this.ended=((r=this.media)==null?void 0:r.currentTime)||1,this.hls.trigger(j.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=n,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(j.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(j.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(j.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(j.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(j.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(j.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,n){this.setInterval(ife),this.mediaSource=n.mediaSource;const r=this.media=n.media;ii(r,"playing",this.onMediaPlaying),ii(r,"waiting",this.onMediaWaiting),ii(r,"ended",this.onMediaEnded)}onMediaDetaching(e,n){this.clearInterval();const{media:r}=this;r&&(bi(r,"playing",this.onMediaPlaying),bi(r,"waiting",this.onMediaWaiting),bi(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,n){this.buffered=n.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const n=this.media.currentTime;this.poll(n,this.lastCurrentTime),this.lastCurrentTime=n}poll(e,n){var r,i;const s=(r=this.hls)==null?void 0:r.config;if(!s)return;const a=this.media;if(!a)return;const{seeking:o}=a,l=this.seeking&&!o,c=!this.seeking&&o,u=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==n){n&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,s.nudgeOnVideoHole&&!u&&e>n&&this.nudgeOnVideoHole(e,n)),this.waiting===0&&this.stallResolved(e);return}if(c||l){l&&this.stallResolved(e);return}if(u){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(j.MEDIA_ENDED,{stalled:!1}));return}if(!Ct.getBuffered(a).length){this.nudgeRetry=0;return}const d=Ct.bufferInfo(a,e,0),h=d.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){const U=hD(this.hls.inFlightFragments,e),O=d.len>py,k=!h||U||h-e>py&&!f.getPartialFragment(e);if(O||k)return;this.moved=!1}const p=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(d.len>0)&&!h)return;const O=Math.max(h,d.start||0)-e,I=!!(p!=null&&p.live)?p.targetduration*2:py,R=kg(e,f);if(O>0&&(O<=I||R)){a.paused||this._trySkipBufferHole(R);return}}const m=s.detectStallWithCurrentTimeMs,g=self.performance.now(),b=this.waiting;let v=this.stalled;if(v===null)if(b>0&&g-b<m)v=this.stalled=b;else{this.stalled=g;return}const S=g-v;if(!o&&(S>=m||b)&&this.hls){var E;if(((E=this.mediaSource)==null?void 0:E.readyState)==="ended"&&!(p!=null&&p.live)&&Math.abs(e-((p==null?void 0:p.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(j.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(d),!this.media||!this.hls)return}const L=Ct.bufferInfo(a,e,s.maxBufferHole);this._tryFixBufferStall(L,S,e)}stallResolved(e){const n=this.stalled;if(n&&this.hls&&(this.stalled=null,this.stallReported)){const r=self.performance.now()-n;this.log(`playback not stuck anymore @${e}, after ${Math.round(r)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(j.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,n){var r;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(r=this.buffered.audio)!=null&&r.length&&i&&i.length>1&&e>i.end(0)){const s=Ct.bufferedInfo(Ct.timeRangesToArray(this.buffered.audio),e,0);if(s.len>1&&n>=s.start){const a=Ct.timeRangesToArray(i),o=Ct.bufferedInfo(a,n,0).bufferedIndex;if(o>-1&&o<a.length-1){const l=Ct.bufferedInfo(a,e,0).bufferedIndex,c=a[o].end,u=a[o+1].start;if((l===-1||l>o)&&u-c<1&&e-c<2){const d=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${c} -> ${u} buffered index: ${l}`);this.warn(d.message),this.media.currentTime+=1e-6;let h=kg(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);const f=Ct.bufferInfo(this.media,e,0);this.hls.trigger(j.ERROR,{type:ct.MEDIA_ERROR,details:xe.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:h,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,n,r){var i,s;const{fragmentTracker:a,media:o}=this,l=(i=this.hls)==null?void 0:i.config;if(!o||!a||!l)return;const c=(s=this.hls)==null?void 0:s.latestLevelDetails,u=kg(r,a);if((u||c!=null&&c.live&&r<c.fragmentStart)&&(this._trySkipBufferHole(u)||!this.media))return;const d=e.buffered,h=this.adjacentTraversal(e,r);(d&&d.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-r<l.maxBufferHole||h))&&(n>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,n){const r=this.fragmentTracker,i=e.nextStart;if(r&&i){const s=r.getFragAtPos(n,tt.MAIN),a=r.getFragAtPos(i,tt.MAIN);if(s&&a)return a.sn-s.sn<2}return!1}_reportStall(e){const{hls:n,media:r,stallReported:i,stalled:s}=this;if(!i&&s!==null&&r&&n){this.stallReported=!0;const a=new Error(`Playback stalling at @${r.currentTime} due to low buffer (${yn(e)})`);this.warn(a.message),n.trigger(j.ERROR,{type:ct.MEDIA_ERROR,details:xe.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:s}})}}_trySkipBufferHole(e){var n;const{fragmentTracker:r,media:i}=this,s=(n=this.hls)==null?void 0:n.config;if(!i||!r||!s)return 0;const a=i.currentTime,o=Ct.bufferInfo(i,a,0),l=a<o.start?o.start:o.nextStart;if(l&&this.hls){const u=o.len<=s.maxBufferHole,d=o.len>0&&o.len<1&&i.readyState<3,h=l-a;if(h>0&&(u||d)){if(h>s.maxBufferHole){let p=!1;if(a===0){const m=r.getAppendedFrag(0,tt.MAIN);m&&l<m.end&&(p=!0)}if(!p&&e){var c;if(!((c=this.hls.loadLevelObj)!=null&&c.details)||hD(this.hls.inFlightFragments,l))return 0;let g=!1,b=e.end;for(;b<l;){const v=kg(b,r);if(v)b+=v.duration;else{g=!0;break}}if(g)return 0}}const f=Math.max(l+rfe,a+nfe);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`),this.moved=!0,i.currentTime=f,!(e!=null&&e.gap)){const p=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`),m={type:ct.MEDIA_ERROR,details:xe.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:p,reason:p.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?m.part=e:m.frag=e),this.hls.trigger(j.ERROR,m)}return f}}return 0}_tryNudgeBuffer(e){const{hls:n,media:r,nudgeRetry:i}=this,s=n==null?void 0:n.config;if(!r||!s)return 0;const a=r.currentTime;if(this.nudgeRetry++,i<s.nudgeMaxRetry){const o=a+(i+1)*s.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(l.message),r.currentTime=o,n.trigger(j.ERROR,{type:ct.MEDIA_ERROR,details:xe.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error(`Playhead still not moving while enough data buffered @${a} after ${s.nudgeMaxRetry} nudges`);this.error(o.message),n.trigger(j.ERROR,{type:ct.MEDIA_ERROR,details:xe.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function hD(t,e){const n=fD(t.main);if(n&&n.start<=e)return n;const r=fD(t.audio);return r&&r.start<=e?r:null}function fD(t){if(!t)return null;switch(t.state){case Oe.IDLE:case Oe.STOPPED:case Oe.ENDED:case Oe.ERROR:return null}return t.frag}function kg(t,e){return e.getAppendedFrag(t,tt.MAIN)||e.getPartialFragment(t)}const afe=.25;function ew(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function ix(t,e,n,r,i){let s=new t(e,n,"");try{s.value=r,i&&(s.type=i)}catch{s=new t(e,n,yn(i?on({type:i},r):r))}return s}const Ig=(()=>{const t=ew();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class ofe{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(j.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(j.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(j.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(j.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(j.MANIFEST_LOADING,this.onManifestLoading,this),e.on(j.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(j.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(j.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(j.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(j.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(j.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(j.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(j.MANIFEST_LOADING,this.onManifestLoading,this),e.off(j.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(j.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(j.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(j.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,n){var r;this.media=n.media,((r=n.overrides)==null?void 0:r.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const n=(e=this.hls)==null?void 0:e.latestLevelDetails;n&&this.updateDateRangeCues(n)}onMediaDetaching(e,n){this.media=null,!n.transferMedia&&(this.id3Track&&(this.removeCues&&rd(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const n=this.getID3Track(e.textTracks);return n.mode="hidden",n}getID3Track(e){if(this.media){for(let n=0;n<e.length;n++){const r=e[n];if(r.kind==="metadata"&&r.label==="id3")return y4(r,this.media),r}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,n){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:r,enableID3MetadataCues:i}=this.hls.config;if(!r&&!i)return;const{samples:s}=n;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=ew();if(a)for(let o=0;o<s.length;o++){const l=s[o].type;if(l===Ni.emsg&&!r||!i)continue;const c=K3(s[o].data),u=s[o].pts;let d=u+s[o].duration;d>Ig&&(d=Ig),d-u<=0&&(d=u+afe);for(let f=0;f<c.length;f++){const p=c[f];if(!z3(p)){this.updateId3CueEnds(u,l);const m=ix(a,u,d,p,l);m&&this.id3Track.addCue(m)}}}}updateId3CueEnds(e,n){var r;const i=(r=this.id3Track)==null?void 0:r.cues;if(i)for(let s=i.length;s--;){const a=i[s];a.type===n&&a.startTime<e&&a.endTime===Ig&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:n,endOffset:r,type:i}){const{id3Track:s,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(s&&(o||l)){let c;i==="audio"?c=u=>u.type===Ni.audioId3&&l:i==="video"?c=u=>u.type===Ni.emsg&&o:c=u=>u.type===Ni.audioId3&&l||u.type===Ni.emsg&&o,QE(s,n,r,c)}}onLevelUpdated(e,{details:n}){this.updateDateRangeCues(n,!0)}onLevelPtsUpdated(e,n){Math.abs(n.drift)>.01&&this.updateDateRangeCues(n.details)}updateDateRangeCues(e,n){if(!this.hls||!this.media)return;const{assetPlayerId:r,timelineOffset:i,enableDateRangeMetadataCues:s,interstitialsController:a}=this.hls.config;if(!s)return;const o=ew();if(r&&i&&!a){const{fragmentStart:m,fragmentEnd:g}=e;let b=this.assetCue;b?(b.startTime=m,b.endTime=g):o&&(b=this.assetCue=ix(o,m,g,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),b&&(b.id=r,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(b),b.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:l}=this,{dateRanges:c}=e,u=Object.keys(c);let d=this.dateRangeCuesAppended;if(l&&n){var h;if((h=l.cues)!=null&&h.length){const m=Object.keys(d).filter(g=>!u.includes(g));for(let g=m.length;g--;){var f;const b=m[g],v=(f=d[b])==null?void 0:f.cues;delete d[b],v&&Object.keys(v).forEach(S=>{const E=v[S];if(E){E.removeEventListener("enter",this.onEventCueEnter);try{l.removeCue(E)}catch{}}})}}else d=this.dateRangeCuesAppended={}}const p=e.fragments[e.fragments.length-1];if(!(u.length===0||!Ze(p==null?void 0:p.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let m=0;m<u.length;m++){const g=u[m],b=c[g],v=b.startTime,S=d[g],E=(S==null?void 0:S.cues)||{};let L=(S==null?void 0:S.durationKnown)||!1,U=Ig;const{duration:O,endDate:k}=b;if(k&&O!==null)U=v+O,L=!0;else if(b.endOnNext&&!L){const R=u.reduce((M,z)=>{if(z!==b.id){const Z=c[z];if(Z.class===b.class&&Z.startDate>b.startDate&&(!M||b.startDate<M.startDate))return Z}return M},null);R&&(U=R.startTime,L=!0)}const I=Object.keys(b.attr);for(let R=0;R<I.length;R++){const M=I[R];if(!Cce(M))continue;const z=E[M];if(z)L&&!(S!=null&&S.durationKnown)?z.endTime=U:Math.abs(z.startTime-v)>.01&&(z.startTime=v,z.endTime=U);else if(o){let Z=b.attr[M];Lce(M)&&(Z=n3(Z));const re=ix(o,v,U,{key:M,data:Z},Ni.dateRange);re&&(re.id=g,this.id3Track.addCue(re),E[M]=re,a&&(M==="X-ASSET-LIST"||M==="X-ASSET-URL")&&re.addEventListener("enter",this.onEventCueEnter))}}d[g]={cues:E,dateRange:b,durationKnown:L}}}}}class lfe{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:n}=this,r=this.levelDetails;if(!n||!r)return;this.currentTime=n.currentTime;const i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:a}=this.config;if(!s||a===1||!r.live)return;const o=this.targetLatency;if(o===null)return;const l=i-o,c=Math.min(this.maxLatency,o+r.targetduration);if(l<c&&l>.05&&this.forwardBufferLength>1){const d=Math.min(2,Math.max(1,a)),h=Math.round(2/(1+Math.exp(-.75*l-this.edgeStalled))*20)/20,f=Math.min(d,Math.max(1,h));this.changeMediaPlaybackRate(n,f)}else n.playbackRate!==1&&n.playbackRate!==0&&this.changeMediaPlaybackRate(n,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const n=this.levelDetails;return n?e.liveMaxLatencyDurationCount*n.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:n,partHoldBack:r,targetduration:i}=e,{liveSyncDuration:s,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig;let c=o&&r||n;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||c===0)&&(c=s!==void 0?s:a*i);const u=i;return c+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,u)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),n=this.targetLatency;if(e===null||n===null)return null;const r=this.levelDetails;if(r===null)return null;const i=r.edge,s=e-n-this.edgeStalled,a=i-r.totalduration,o=i-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(a,s),o)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const n=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-n,0)}get forwardBufferLength(){const{media:e}=this,n=this.levelDetails;if(!e||!n)return 0;const r=e.buffered.length;return(r?e.buffered.end(r-1):n.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(j.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(j.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(j.MANIFEST_LOADING,this.onManifestLoading,this),e.on(j.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(j.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(j.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(j.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(j.MANIFEST_LOADING,this.onManifestLoading,this),e.off(j.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(j.ERROR,this.onError,this))}onMediaAttached(e,n){this.media=n.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:n}){n.advanced&&this.onTimeupdate(),!n.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,n){var r;n.details===xe.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(r=this.levelDetails)!=null&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,n){var r,i;e.playbackRate!==n&&((r=this.hls)==null||r.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(i=this.targetLatency)==null?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${n}`),e.playbackRate=n)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}class cfe extends QA{constructor(e,n){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=n,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(j.MANIFEST_LOADING,this.onManifestLoading,this),e.on(j.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(j.LEVEL_LOADED,this.onLevelLoaded,this),e.on(j.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(j.FRAG_BUFFERED,this.onFragBuffered,this),e.on(j.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(j.MANIFEST_LOADING,this.onManifestLoading,this),e.off(j.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(j.LEVEL_LOADED,this.onLevelLoaded,this),e.off(j.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(j.FRAG_BUFFERED,this.onFragBuffered,this),e.off(j.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(n=>{n.loadError=0,n.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,n){this.resetLevels()}onManifestLoaded(e,n){const r=this.hls.config.preferManagedMediaSource,i=[],s={},a={};let o=!1,l=!1,c=!1;n.levels.forEach(u=>{const d=u.attrs;let{audioCodec:h,videoCodec:f}=u;h&&(u.audioCodec=h=_0(h,r)||void 0),f&&(f=u.videoCodec=Kle(f));const{width:p,height:m,unknownCodecs:g}=u,b=(g==null?void 0:g.length)||0;if(o||(o=!!(p&&m)),l||(l=!!f),c||(c=!!h),b||h&&!this.isAudioSupported(h)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${d.CODECS}"`);return}const{CODECS:v,"FRAME-RATE":S,"HDCP-LEVEL":E,"PATHWAY-ID":L,RESOLUTION:U,"VIDEO-RANGE":O}=d,I=`${`${L||"."}-`}${u.bitrate}-${U}-${S}-${v}-${O}-${E}`;if(s[I])if(s[I].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const R=a[I]+=1;u.attrs["PATHWAY-ID"]=new Array(R+1).join(".");const M=this.createLevel(u);s[I]=M,i.push(M)}else s[I].addGroupId("audio",d.AUDIO),s[I].addGroupId("text",d.SUBTITLES);else{const R=this.createLevel(u);s[I]=R,a[I]=1,i.push(R)}}),this.filterAndSortMediaOptions(i,n,o,l,c)}createLevel(e){const n=new Tp(e),r=e.supplemental;if(r!=null&&r.videoCodec&&!this.isVideoSupported(r.videoCodec)){const i=new Error(`SUPPLEMENTAL-CODECS not supported "${r.videoCodec}"`);this.log(i.message),n.supportedResult=p3(i,[])}return n}isAudioSupported(e){return Ep(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Ep(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,n,r,i,s){var a;let o=[],l=[],c=e;const u=((a=n.stats)==null?void 0:a.parsing)||{};if((r||i)&&s&&(c=c.filter(({videoCodec:v,videoRange:S,width:E,height:L})=>(!!v||!!(E&&L))&&tce(S))),c.length===0){Promise.resolve().then(()=>{if(this.hls){let v="no level with compatible codecs found in manifest",S=v;n.levels.length&&(S=`one or more CODECS in variant not supported: ${yn(n.levels.map(L=>L.attrs.CODECS).filter((L,U,O)=>O.indexOf(L)===U))}`,this.warn(S),v+=` (${S})`);const E=new Error(v);this.hls.trigger(j.ERROR,{type:ct.MEDIA_ERROR,details:xe.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:n.url,error:E,reason:S})}}),u.end=performance.now();return}n.audioTracks&&(o=n.audioTracks.filter(v=>!v.audioCodec||this.isAudioSupported(v.audioCodec)),pD(o)),n.subtitles&&(l=n.subtitles,pD(l));const d=c.slice(0);c.sort((v,S)=>{if(v.attrs["HDCP-LEVEL"]!==S.attrs["HDCP-LEVEL"])return(v.attrs["HDCP-LEVEL"]||"")>(S.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&v.height!==S.height)return v.height-S.height;if(v.frameRate!==S.frameRate)return v.frameRate-S.frameRate;if(v.videoRange!==S.videoRange)return b0.indexOf(v.videoRange)-b0.indexOf(S.videoRange);if(v.videoCodec!==S.videoCodec){const E=sP(v.videoCodec),L=sP(S.videoCodec);if(E!==L)return L-E}if(v.uri===S.uri&&v.codecSet!==S.codecSet){const E=v0(v.codecSet),L=v0(S.codecSet);if(E!==L)return L-E}return v.averageBitrate!==S.averageBitrate?v.averageBitrate-S.averageBitrate:0});let h=d[0];if(this.steering&&(c=this.steering.filterParsedLevels(c),c.length!==d.length)){for(let v=0;v<d.length;v++)if(d[v].pathwayId===c[0].pathwayId){h=d[v];break}}this._levels=c;for(let v=0;v<c.length;v++)if(c[v]===h){var f;this._firstLevel=v;const S=h.bitrate,E=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${c.length} level(s) found, first bitrate: ${S}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){const L=Math.min(S,this.hls.config.abrEwmaDefaultEstimateMax);L>E&&E===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=L)}break}const p=s&&!i,m=this.hls.config,g=!!(m.audioStreamController&&m.audioTrackController),b={levels:c,audioTracks:o,subtitleTracks:l,sessionData:n.sessionData,sessionKeys:n.sessionKeys,firstLevel:this._firstLevel,stats:n.stats,audio:s,video:i,altAudio:g&&!p&&o.some(v=>!!v.url)};u.end=performance.now(),this.hls.trigger(j.MANIFEST_PARSED,b)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const n=this._levels;if(n.length===0)return;if(e<0||e>=n.length){const u=new Error("invalid level idx"),d=e<0;if(this.hls.trigger(j.ERROR,{type:ct.OTHER_ERROR,details:xe.LEVEL_SWITCH_ERROR,level:e,fatal:d,error:u,reason:u.message}),d)return;e=Math.min(e,n.length-1)}const r=this.currentLevelIndex,i=this.currentLevel,s=i?i.attrs["PATHWAY-ID"]:void 0,a=n[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,r===e&&i&&s===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${r}${s?" with Pathway "+s:""}`);const l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(j.LEVEL_SWITCHING,l);const c=a.details;if(!c||c.live){const u=this.switchParams(a.uri,i==null?void 0:i.details,c);this.loadPlaylist(u)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const n=this.steering.pathways(),r=e.filter(i=>n.indexOf(i)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${n}`);return}this.steering.pathwayPriority=r}}onError(e,n){n.fatal||!n.context||n.context.type===Ft.LEVEL&&n.context.level===this.level&&this.checkRetry(n)}onFragBuffered(e,{frag:n}){if(n!==void 0&&n.type===tt.MAIN){const r=n.elementaryStreams;if(!Object.keys(r).some(s=>!!r[s]))return;const i=this._levels[n.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,n){var r;const{level:i,details:s}=n,a=n.levelInfo;if(!a){var o;this.warn(`Invalid level index ${i}`),(o=n.deliveryDirectives)!=null&&o.skip&&(s.deltaUpdateFailed=!0);return}if(a===this.currentLevel||n.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let l=a.details;l===n.details&&l.advanced&&(l=void 0),this.playlistLoaded(i,n,l)}else(r=n.deliveryDirectives)!=null&&r.skip&&(s.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,n){super.loadingPlaylist(e,n);const r=this.getUrlWithDirectives(e.uri,n),i=this.currentLevelIndex,s=e.attrs["PATHWAY-ID"],a=e.details,o=a==null?void 0:a.age;this.log(`Loading level index ${i}${(n==null?void 0:n.msn)!==void 0?" at sn "+n.msn+" part "+n.part:""}${s?" Pathway "+s:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(j.LEVEL_LOADING,{url:r,level:i,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:n||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var n;if(this._levels.length===1)return;const r=this._levels.filter((s,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(s),s===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,s.details&&s.details.fragments.forEach(o=>o.level=-1)),!1));N3(r),this._levels=r,this.currentLevelIndex>-1&&(n=this.currentLevel)!=null&&n.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=r.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(j.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(e,{levels:n}){this._levels=n}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:n,maxHdcpLevel:r}=this.hls;this._maxAutoLevel!==n&&(this._maxAutoLevel=n,this.hls.trigger(j.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:n,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}function pD(t){const e={};t.forEach(n=>{const r=n.groupId||"";n.id=e[r]=e[r]||0,e[r]++})}function k4(){return self.SourceBuffer||self.WebKitSourceBuffer}function I4(){if(!Cl())return!1;const e=k4();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function ufe(){if(!I4())return!1;const t=Cl();return typeof(t==null?void 0:t.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>t.isTypeSupported(wp(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported(wp(e,"audio"))))}function dfe(){var t;const e=k4();return typeof(e==null||(t=e.prototype)==null?void 0:t.changeType)=="function"}const hfe=100;class ffe extends GA{constructor(e,n,r){super(e,n,r,"stream-controller",tt.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const i=this.media,s=i?i.currentTime:null;if(s===null||!Ze(s)||(this.log(`Media seeked to ${s.toFixed(3)}`),!this.getBufferedFrag(s)))return;const a=this.getFwdBufferInfoAtPos(i,s,tt.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${s} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(j.MANIFEST_PARSED,this.onManifestParsed,this),e.on(j.LEVEL_LOADING,this.onLevelLoading,this),e.on(j.LEVEL_LOADED,this.onLevelLoaded,this),e.on(j.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(j.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(j.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(j.BUFFER_CREATED,this.onBufferCreated,this),e.on(j.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(j.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(j.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(j.MANIFEST_PARSED,this.onManifestParsed,this),e.off(j.LEVEL_LOADED,this.onLevelLoaded,this),e.off(j.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(j.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(j.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(j.BUFFER_CREATED,this.onBufferCreated,this),e.off(j.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(j.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(j.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,n){if(this.levels){const{lastCurrentTime:r,hls:i}=this;if(this.stopLoad(),this.setInterval(hfe),this.level=-1,!this.startFragRequested){let s=i.startLevel;s===-1&&(i.config.testBandwidth&&this.levels.length>1?(s=0,this.bitrateTest=!0):s=i.firstAutoLevel),i.nextLoadLevel=s,this.level=i.loadLevel,this._hasEnoughToStart=!!n}r>0&&e===-1&&!n&&(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r),this.state=Oe.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=n?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=Oe.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Oe.WAITING_LEVEL:{const{levels:e,level:n}=this,r=e==null?void 0:e[n],i=r==null?void 0:r.details;if(i&&(!i.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(i))break;this.state=Oe.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=Oe.IDLE;break}break}case Oe.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===Oe.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:n,levels:r,media:i}=this;if(n===null||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const s=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(r!=null&&r[s]))return;const a=r[s],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const m={};this.altAudio===2&&(m.type="video"),this.hls.trigger(j.BUFFER_EOS,m),this.state=Oe.ENDED;return}if(!this.buffering)return;e.loadLevel!==s&&e.manualLevel===-1&&this.log(`Adapting to level ${s} from level ${this.level}`),this.level=e.nextLoadLevel=s;const c=a.details;if(!c||this.state===Oe.WAITING_LEVEL||this.waitForLive(a)){this.level=s,this.state=Oe.WAITING_LEVEL,this.startFragRequested=!1;return}const u=o.len,d=this.getMaxBufferLength(a.maxBitrate);if(u>=d)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(h,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&Zn(f)&&this.fragmentTracker.getState(f)!==pr.OK){var p;const g=((p=this.backtrackFragment)!=null?p:f).sn-c.startSN,b=c.fragments[g-1];b&&f.cc===b.cc&&(f=b,this.fragmentTracker.removeFragment(b))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){const g=this.audioOnly&&!this.altAudio?pn.AUDIO:pn.VIDEO,b=(g===pn.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;b&&this.afterBufferFlushed(b,g,tt.MAIN)}f=this.getNextFragmentLoopLoading(f,c,o,tt.MAIN,d)}f&&(this.exceedsMaxBuffer(o,d,f)||(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,h)))}loadFragment(e,n,r){const i=this.fragmentTracker.getState(e);i===pr.NOT_LOADED||i===pr.PARTIAL?Zn(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,n)):super.loadFragment(e,n,r):this._loadInitSegment(e,n):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,tt.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==0){var e;(((e=this.getLevelDetails())==null?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}nextLevelSwitch(){const{levels:e,media:n}=this;if(n!=null&&n.readyState){let r;const i=this.getAppendedFrag(n.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const s=this.getLevelDetails();if(s!=null&&s.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<s.targetduration*2)return}if(!n.paused&&e){const o=this.hls.nextLoadLevel,l=e[o],c=this.fragLastKbps;c&&this.fragCurrent?r=this.fragCurrent.duration*l.maxBitrate/(1e3*c)+1:r=0}else r=0;const a=this.getBufferedFrag(n.currentTime+r);if(a){const o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();const l=o.maxStartPTS?o.maxStartPTS:o.start,c=o.duration,u=Math.max(a.end,l+Math.min(Math.max(c-this.config.maxFragLookUpTolerance,c*(this.couldBacktrack?.5:.125)),c*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(u,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case Oe.KEY_LOADING:case Oe.FRAG_LOADING:case Oe.FRAG_LOADING_WAITING_RETRY:case Oe.PARSING:case Oe.PARSED:this.state=Oe.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,n){super.flushMainBuffer(e,n,this.altAudio===2?"video":null)}onMediaAttached(e,n){super.onMediaAttached(e,n);const r=n.media;ii(r,"playing",this.onMediaPlaying),ii(r,"seeked",this.onMediaSeeked)}onMediaDetaching(e,n){const{media:r}=this;r&&(bi(r,"playing",this.onMediaPlaying),bi(r,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,n),!n.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(j.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,n){let r=!1,i=!1;for(let s=0;s<n.levels.length;s++){const a=n.levels[s].audioCodec;a&&(r=r||a.indexOf("mp4a.40.2")!==-1,i=i||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=r&&i&&!dfe(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=n.levels,this.startFragRequested=!1}onLevelLoading(e,n){const{levels:r}=this;if(!r||this.state!==Oe.IDLE)return;const i=n.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=Oe.WAITING_LEVEL)}onLevelLoaded(e,n){var r;const{levels:i,startFragRequested:s}=this,a=n.level,o=n.details,l=o.totalduration;if(!i){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);const c=n.levelInfo,u=this.fragCurrent;u&&(this.state===Oe.FRAG_LOADING||this.state===Oe.FRAG_LOADING_WAITING_RETRY)&&u.level!==n.level&&u.loader&&this.abortCurrentFrag();let d=0;if(o.live||(r=c.details)!=null&&r.live){var h;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;d=this.alignPlaylists(o,c.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(c.details=o,this.levelLastLoaded=c,s||this.setStartPosition(o,d),this.hls.trigger(j.LEVEL_UPDATED,{details:o,level:a}),this.state===Oe.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=Oe.IDLE}s&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){const{config:n,media:r}=this;if(!r)return;const i=this.hls.liveSyncPosition,s=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,l=s>=a-n.maxFragLookUpTolerance&&s<=o;if(i!==null&&r.duration>i&&(s<i||!l)){const u=n.liveMaxLatencyDuration!==void 0?n.liveMaxLatencyDuration:n.liveMaxLatencyDurationCount*e.targetduration;if((!l&&r.readyState<4||s<o-u)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),r.readyState))if(this.warn(`Playback: ${s.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${i.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var c;const d=Ct.bufferInfo(r,i,0);if(!((c=d.buffered)!=null&&c.length)){r.currentTime=i;return}if(d.start<=s){r.currentTime=i;return}const{nextStart:f}=Ct.bufferedInfo(d.buffered,s,0);f&&(r.currentTime=f)}else r.currentTime=i}}_handleFragmentLoadProgress(e){var n;const r=e.frag,{part:i,payload:s}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);return}const o=a[r.level];if(!o){this.warn(`Level ${r.level} not found on progress`);return}const l=o.details;if(!l){this.warn(`Dropping fragment ${r.sn} of level ${r.level} after level details were reset`),this.fragmentTracker.removeFragment(r);return}const c=o.videoCodec,u=l.PTSKnown||!l.live,d=(n=r.initSegment)==null?void 0:n.data,h=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new r4(this.hls,tt.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),p=i?i.index:-1,m=p!==-1,g=new FA(r.level,r.sn,r.stats.chunkCount,s.byteLength,p,m),b=this.initPTS[r.cc];f.push(s,d,h,c,r,i,l.totalduration,u,g,b)}onAudioTrackSwitching(e,n){const r=this.hls,i=this.altAudio!==0;if(x0(n.url,r))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i){this.altAudio=0,this.fragmentTracker.removeAllFragments(),r.once(j.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(j.AUDIO_TRACK_SWITCHED,n)}),r.trigger(j.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}r.trigger(j.AUDIO_TRACK_SWITCHED,n)}}onAudioTrackSwitched(e,n){const r=x0(n.url,this.hls);if(r){const i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=r?2:0,this.tick()}onBufferCreated(e,n){const r=n.tracks;let i,s,a=!1;for(const o in r){const l=r[o];if(l.id==="main"){if(s=o,i=l,o==="video"){const c=r[o];c&&(this.videoBuffer=c.buffer)}}else a=!0}a&&i?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,n){const{frag:r,part:i}=n,s=r.type===tt.MAIN;if(s){if(this.fragContextChanged(r)){this.warn(`Fragment ${r.sn}${i?" p: "+i.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}`),this.state===Oe.PARSED&&(this.state=Oe.IDLE);return}const o=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),Zn(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}const a=this.media;a&&(!this._hasEnoughToStart&&Ct.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),s&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,n){var r;if(n.fatal){this.state=Oe.ERROR;return}switch(n.details){case xe.FRAG_GAP:case xe.FRAG_PARSING_ERROR:case xe.FRAG_DECRYPT_ERROR:case xe.FRAG_LOAD_ERROR:case xe.FRAG_LOAD_TIMEOUT:case xe.KEY_LOAD_ERROR:case xe.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(tt.MAIN,n);break;case xe.LEVEL_LOAD_ERROR:case xe.LEVEL_LOAD_TIMEOUT:case xe.LEVEL_PARSING_ERROR:!n.levelRetry&&this.state===Oe.WAITING_LEVEL&&((r=n.context)==null?void 0:r.type)===Ft.LEVEL&&(this.state=Oe.IDLE);break;case xe.BUFFER_ADD_CODEC_ERROR:case xe.BUFFER_APPEND_ERROR:if(n.parent!=="main")return;this.reduceLengthAndFlushBuffer(n)&&this.resetLoadingState();break;case xe.BUFFER_FULL_ERROR:if(n.parent!=="main")return;this.reduceLengthAndFlushBuffer(n)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case xe.INTERNAL_EXCEPTION:this.recoverWorkerError(n);break}}onFragLoadEmergencyAborted(){this.state=Oe.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:n}){if(n!==pn.AUDIO||!this.altAudio){const r=(n===pn.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,n,tt.MAIN),this.tick())}}onLevelsUpdated(e,n){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=n.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const n=e.currentTime;let r=this.startPosition;if(r>=0&&n<r){if(e.seeking){this.log(`could not seek to ${r}, already seeking at ${n}`);return}const i=this.timelineOffset;i&&r&&(r+=i);const s=this.getLevelDetails(),a=Ct.getBuffered(e),o=a.length?a.start(0):0,l=o-r,c=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<c||this.loadingParts&&l<2*((s==null?void 0:s.partTarget)||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),r+=l,this.startPosition=r),n<r&&(this.log(`seek to target start position ${r} from current time ${n} buffer start ${o}`),e.currentTime=r)}}_getAudioCodec(e){let n=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&n&&(this.log("Swapping audio codec"),n.indexOf("mp4a.40.5")!==-1?n="mp4a.40.2":n="mp4a.40.5"),n}_loadBitrateTestFrag(e,n){e.bitrateTest=!0,this._doFragLoad(e,n).then(r=>{const{hls:i}=this,s=r==null?void 0:r.frag;if(!s||this.fragContextChanged(s))return;n.fragmentError=0,this.state=Oe.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=s.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),i.trigger(j.FRAG_LOADED,r),s.bitrateTest=!1}).catch(r=>{this.state===Oe.STOPPED||this.state===Oe.ERROR||(this.warn(r),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const n=this.playlistType,{hls:r}=this,{remuxResult:i,chunkMeta:s}=e,a=this.getCurrentContext(s);if(!a){this.resetWhenMissingContext(s);return}const{frag:o,part:l,level:c}=a,{video:u,text:d,id3:h,initSegment:f}=i,{details:p}=c,m=this.altAudio?void 0:i.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=Oe.PARSING,f){const g=f.tracks;if(g){const E=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(c,g,E,s),r.trigger(j.FRAG_PARSING_INIT_SEGMENT,{frag:E,id:n,tracks:g})}const b=f.initPTS,v=f.timescale,S=this.initPTS[o.cc];if(Ze(b)&&(!S||S.baseTime!==b||S.timescale!==v)){const E=f.trackId;this.initPTS[o.cc]={baseTime:b,timescale:v,trackId:E},r.trigger(j.INIT_PTS_FOUND,{frag:o,id:n,initPTS:b,timescale:v,trackId:E})}}if(u&&p){m&&u.type==="audiovideo"&&this.logMuxedErr(o);const g=p.fragments[o.sn-1-p.startSN],b=o.sn===p.startSN,v=!g||o.cc>g.cc;if(i.independent!==!1){const{startPTS:S,endPTS:E,startDTS:L,endDTS:U}=u;if(l)l.elementaryStreams[u.type]={startPTS:S,endPTS:E,startDTS:L,endDTS:U};else if(u.firstKeyFrame&&u.independent&&s.id===1&&!v&&(this.couldBacktrack=!0),u.dropped&&u.independent){const O=this.getMainFwdBufferInfo(),k=(O?O.end:this.getLoadPosition())+this.config.maxBufferHole,I=u.firstKeyFramePTS?u.firstKeyFramePTS:S;if(!b&&k<I-this.config.maxBufferHole&&!v){this.backtrack(o);return}else v&&(o.gap=!0);o.setElementaryStreamInfo(u.type,o.start,E,o.start,U,!0)}else b&&S-(p.appliedTimelineOffset||0)>py&&(o.gap=!0);o.setElementaryStreamInfo(u.type,S,E,L,U),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,l,s,b||v)}else if(b||v)o.gap=!0;else{this.backtrack(o);return}}if(m){const{startPTS:g,endPTS:b,startDTS:v,endDTS:S}=m;l&&(l.elementaryStreams[pn.AUDIO]={startPTS:g,endPTS:b,startDTS:v,endDTS:S}),o.setElementaryStreamInfo(pn.AUDIO,g,b,v,S),this.bufferFragmentData(m,o,l,s)}if(p&&h!=null&&h.samples.length){const g={id:n,frag:o,details:p,samples:h.samples};r.trigger(j.FRAG_PARSING_METADATA,g)}if(p&&d){const g={id:n,frag:o,details:p,samples:d.samples};r.trigger(j.FRAG_PARSING_USERDATA,g)}}logMuxedErr(e){this.warn(`${Zn(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,n,r,i){if(this.state!==Oe.PARSING)return;this.audioOnly=!!n.audio&&!n.video,this.altAudio&&!this.audioOnly&&(delete n.audio,n.audiovideo&&this.logMuxedErr(r));const{audio:s,video:a,audiovideo:o}=n;if(s){const c=e.audioCodec;let u=oy(s.codec,c);u==="mp4a"&&(u="mp4a.40.5");const d=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){u&&(u.indexOf("mp4a.40.5")!==-1?u="mp4a.40.2":u="mp4a.40.5");const h=s.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&d.indexOf("firefox")===-1&&(u="mp4a.40.5")}u&&u.indexOf("mp4a.40.5")!==-1&&d.indexOf("android")!==-1&&s.container!=="audio/mpeg"&&(u="mp4a.40.2",this.log(`Android: force audio codec to ${u}`)),c&&c!==u&&this.log(`Swapping manifest audio codec "${c}" for "${u}"`),s.levelCodec=u,s.id=tt.MAIN,this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${u||""}/${c||""}/${s.codec}]`),delete n.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=tt.MAIN;const c=a.codec;if((c==null?void 0:c.length)===4)switch(c){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${c}]${a.codec!==c?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete n.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete n.video,delete n.audio);const l=Object.keys(n);if(l.length){if(this.hls.trigger(j.BUFFER_CODECS,n),!this.hls)return;l.forEach(c=>{const d=n[c].initSegment;d!=null&&d.byteLength&&this.hls.trigger(j.BUFFER_APPENDING,{type:c,data:d,frag:r,part:null,chunkMeta:i,parent:r.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,tt.MAIN)}get maxBufferLength(){const{levels:e,level:n}=this,r=e==null?void 0:e[n];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=Oe.IDLE}checkFragmentChanged(){const e=this.media;let n=null;if(e&&e.readyState>1&&e.seeking===!1){const r=e.currentTime;if(Ct.isBuffered(e,r)?n=this.getAppendedFrag(r):Ct.isBuffered(e,r+.1)&&(n=this.getAppendedFrag(r+.1)),n){this.backtrackFragment=null;const i=this.fragPlaying,s=n.level;(!i||n.sn!==i.sn||i.level!==s)&&(this.fragPlaying=n,this.hls.trigger(j.FRAG_CHANGED,{frag:n}),(!i||i.level!==s)&&this.hls.trigger(j.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const n=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return Ze(n)?this.getAppendedFrag(n):null}get currentProgramDateTime(){var e;const n=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(Ze(n)){const r=this.getLevelDetails(),i=this.currentFrag||(r?Gc(null,r.fragments,n):null);if(i){const s=i.programDateTime;if(s!==null){const a=s+(n-i.start)*1e3;return new Date(a)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class pfe extends vs{constructor(e,n){super("key-loader",n),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const r in this.keyIdToKeyInfo){const i=this.keyIdToKeyInfo[r].loader;if(i){var n;if(e&&e!==((n=i.context)==null?void 0:n.frag.type))return;i.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const n=this.keyIdToKeyInfo[e];(n.mediaKeySessionContext||n.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const n=this.keyIdToKeyInfo[e].loader;n&&n.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,n=xe.KEY_LOAD_ERROR,r,i,s){return new Ha({type:ct.NETWORK_ERROR,details:n,fatal:!1,frag:e,response:s,error:r,networkDetails:i})}loadClear(e,n,r){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(n.length)for(let i=0,s=n.length;i<s;i++){const a=n[i];if(e.cc<=a.cc&&(!Zn(e)||!Zn(a)||e.sn<a.sn)||!r&&i==s-1)return this.emeController.selectKeySystemFormat(a).then(o=>{if(!this.emeController)return;a.setKeyFormat(o);const l=cy(o);if(l)return this.emeController.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){const i=sf(this.config);if(i.length)return this.emeController.getKeySystemAccess(i)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(n=>this.loadInternal(e,n)):this.loadInternal(e)}loadInternal(e,n){var r,i;n&&e.setKeyFormat(n);const s=e.decryptdata;if(!s){const c=new Error(n?`Expected frag.decryptdata to be defined after setting format ${n}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,xe.KEY_LOAD_ERROR,c))}const a=s.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,xe.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));const o=sx(s);let l=this.keyIdToKeyInfo[o];if((r=l)!=null&&r.decryptdata.key)return s.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&(i=l)!=null&&i.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then(u=>{const{keyInfo:d}=u;return s.key=d.decryptdata.key,{frag:e,keyInfo:d}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${s.keyId?" keyId: "+Dr(s.keyId):""} URI: ${s.uri} from ${e.type} ${e.level}`),l=this.keyIdToKeyInfo[o]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return s.keyFormat==="identity"?this.loadKeyHTTP(l,e):this.loadKeyEME(l,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,xe.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e,n){const r={frag:n,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i;if(!e.decryptdata.keyId&&(i=n.initSegment)!=null&&i.data){const a=Dle(n.initSegment.data);if(a.length){let o=a[0];o.some(l=>l!==0)?(this.log(`Using keyId found in init segment ${Dr(o)}`),yl.setKeyIdForUri(e.decryptdata.uri,o)):(o=yl.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Dr(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!Zn(n))return Promise.resolve(r);const s=this.emeController.loadKey(r);return(e.keyLoadPromise=s.then(a=>(e.mediaKeySessionContext=a,r))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=n),a})}return Promise.resolve(r)}loadKeyHTTP(e,n){const r=this.config,i=r.loader,s=new i(r);return n.keyLoader=e.loader=s,e.keyLoadPromise=new Promise((a,o)=>{const l={keyInfo:e,frag:n,responseType:"arraybuffer",url:e.decryptdata.uri},c=r.keyLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(h,f,p,m)=>{const{frag:g,keyInfo:b}=p,v=sx(b.decryptdata);if(!g.decryptdata||b!==this.keyIdToKeyInfo[v])return o(this.createKeyLoadError(g,xe.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),m));b.decryptdata.key=g.decryptdata.key=new Uint8Array(h.data),g.keyLoader=null,b.loader=null,a({frag:g,keyInfo:b})},onError:(h,f,p,m)=>{this.resetLoader(f),o(this.createKeyLoadError(n,xe.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),p,on({url:l.url,data:void 0},h)))},onTimeout:(h,f,p)=>{this.resetLoader(f),o(this.createKeyLoadError(n,xe.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),p))},onAbort:(h,f,p)=>{this.resetLoader(f),o(this.createKeyLoadError(n,xe.INTERNAL_ABORTED,new Error("key loading aborted"),p))}};s.load(l,u,d)})}resetLoader(e){const{frag:n,keyInfo:r,url:i}=e,s=r.loader;n.keyLoader===s&&(n.keyLoader=null,r.loader=null);const a=sx(r.decryptdata)||i;delete this.keyIdToKeyInfo[a],s&&s.destroy()}}function sx(t){if(t.keyFormat!==Nr.FAIRPLAY){const e=t.keyId;if(e)return Dr(e)}return t.uri}function mD(t){const{type:e}=t;switch(e){case Ft.AUDIO_TRACK:return tt.AUDIO;case Ft.SUBTITLE_TRACK:return tt.SUBTITLE;default:return tt.MAIN}}function ax(t,e){let n=t.url;return(n===void 0||n.indexOf("data:")===0)&&(n=e.url),n}class mfe{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(j.MANIFEST_LOADING,this.onManifestLoading,this),e.on(j.LEVEL_LOADING,this.onLevelLoading,this),e.on(j.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(j.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(j.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(j.MANIFEST_LOADING,this.onManifestLoading,this),e.off(j.LEVEL_LOADING,this.onLevelLoading,this),e.off(j.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(j.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(j.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const n=this.hls.config,r=n.pLoader,i=n.loader,s=r||i,a=new s(n);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const n=this.loaders[e];n&&n.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,n){const{url:r}=n;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Ft.MANIFEST,url:r,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,n){const{id:r,level:i,pathwayId:s,url:a,deliveryDirectives:o,levelInfo:l}=n;this.load({id:r,level:i,pathwayId:s,responseType:"text",type:Ft.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(e,n){const{id:r,groupId:i,url:s,deliveryDirectives:a,track:o}=n;this.load({id:r,groupId:i,level:null,responseType:"text",type:Ft.AUDIO_TRACK,url:s,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,n){const{id:r,groupId:i,url:s,deliveryDirectives:a,track:o}=n;this.load({id:r,groupId:i,level:null,responseType:"text",type:Ft.SUBTITLE_TRACK,url:s,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,n){const r=this.loaders[Ft.LEVEL];if(r){const i=r.context;i&&!n.levels.some(s=>s===i.levelOrTrack)&&(r.abort(),delete this.loaders[Ft.LEVEL])}}load(e){var n;const r=this.hls.config;let i=this.getInternalLoader(e);if(i){const c=this.hls.logger,u=i.context;if(u&&u.levelOrTrack===e.levelOrTrack&&(u.url===e.url||u.deliveryDirectives&&!e.deliveryDirectives)){u.url===e.url?c.log(`[playlist-loader]: ignore ${e.url} ongoing request`):c.log(`[playlist-loader]: ignore ${e.url} in favor of ${u.url}`);return}c.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let s;if(e.type===Ft.MANIFEST?s=r.manifestLoadPolicy.default:s=fn({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),Ze((n=e.deliveryDirectives)==null?void 0:n.part)){let c;if(e.type===Ft.LEVEL&&e.level!==null?c=this.hls.levels[e.level].details:e.type===Ft.AUDIO_TRACK&&e.id!==null?c=this.hls.audioTracks[e.id].details:e.type===Ft.SUBTITLE_TRACK&&e.id!==null&&(c=this.hls.subtitleTracks[e.id].details),c){const u=c.partTarget,d=c.targetduration;if(u&&d){const h=Math.max(u*3,d*.8)*1e3;s=fn({},s,{maxTimeToFirstByteMs:Math.min(h,s.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(h,s.maxTimeToFirstByteMs)})}}}const a=s.errorRetry||s.timeoutRetry||{},o={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(c,u,d,h)=>{const f=this.getInternalLoader(d);this.resetInternalLoader(d.type);const p=c.data;u.parsing.start=performance.now(),oa.isMediaPlaylist(p)||d.type!==Ft.MANIFEST?this.handleTrackOrLevelPlaylist(c,u,d,h||null,f):this.handleMasterPlaylist(c,u,d,h)},onError:(c,u,d,h)=>{this.handleNetworkError(u,d,!1,c,h)},onTimeout:(c,u,d)=>{this.handleNetworkError(u,d,!0,void 0,c)}};i.load(e,o,l)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:n},forceStartLoad:r}=this.hls;(e||r)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${n}`),this.hls.startLoad(n))}handleMasterPlaylist(e,n,r,i){const s=this.hls,a=e.data,o=ax(e,r),l=oa.parseMasterPlaylist(a,o);if(l.playlistParsingError){n.parsing.end=performance.now(),this.handleManifestParsingError(e,r,l.playlistParsingError,i,n);return}const{contentSteering:c,levels:u,sessionData:d,sessionKeys:h,startTimeOffset:f,variableList:p}=l;this.variableList=p,u.forEach(v=>{const{unknownCodecs:S}=v;if(S){const{preferManagedMediaSource:E}=this.hls.config;let{audioCodec:L,videoCodec:U}=v;for(let O=S.length;O--;){const k=S[O];Ep(k,"audio",E)?(v.audioCodec=L=L?`${L},${k}`:k,th.audio[L.substring(0,4)]=2,S.splice(O,1)):Ep(k,"video",E)&&(v.videoCodec=U=U?`${U},${k}`:k,th.video[U.substring(0,4)]=2,S.splice(O,1))}}});const{AUDIO:m=[],SUBTITLES:g,"CLOSED-CAPTIONS":b}=oa.parseMasterPlaylistMedia(a,o,l);m.length&&!m.some(S=>!S.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Mn({}),bitrate:0,url:""})),s.trigger(j.MANIFEST_LOADED,{levels:u,audioTracks:m,subtitles:g,captions:b,contentSteering:c,url:o,stats:n,networkDetails:i,sessionData:d,sessionKeys:h,startTimeOffset:f,variableList:p})}handleTrackOrLevelPlaylist(e,n,r,i,s){const a=this.hls,{id:o,level:l,type:c}=r,u=ax(e,r),d=Ze(l)?l:Ze(o)?o:0,h=mD(r),f=oa.parseLevelPlaylist(e.data,u,d,h,0,this.variableList);if(c===Ft.MANIFEST){const p={attrs:new Mn({}),bitrate:0,details:f,name:"",url:u};f.requestScheduled=n.loading.start+P3(f,0),a.trigger(j.MANIFEST_LOADED,{levels:[p],audioTracks:[],url:u,stats:n,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}n.parsing.end=performance.now(),r.levelDetails=f,this.handlePlaylistLoaded(f,e,n,r,i,s)}handleManifestParsingError(e,n,r,i,s){this.hls.trigger(j.ERROR,{type:ct.NETWORK_ERROR,details:xe.MANIFEST_PARSING_ERROR,fatal:n.type===Ft.MANIFEST,url:e.url,err:r,error:r,reason:r.message,response:e,context:n,networkDetails:i,stats:s})}handleNetworkError(e,n,r=!1,i,s){let a=`A network ${r?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===Ft.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===Ft.AUDIO_TRACK||e.type===Ft.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=xe.UNKNOWN,c=!1;const u=this.getInternalLoader(e);switch(e.type){case Ft.MANIFEST:l=r?xe.MANIFEST_LOAD_TIMEOUT:xe.MANIFEST_LOAD_ERROR,c=!0;break;case Ft.LEVEL:l=r?xe.LEVEL_LOAD_TIMEOUT:xe.LEVEL_LOAD_ERROR,c=!1;break;case Ft.AUDIO_TRACK:l=r?xe.AUDIO_TRACK_LOAD_TIMEOUT:xe.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case Ft.SUBTITLE_TRACK:l=r?xe.SUBTITLE_TRACK_LOAD_TIMEOUT:xe.SUBTITLE_LOAD_ERROR,c=!1;break}u&&this.resetInternalLoader(e.type);const d={type:ct.NETWORK_ERROR,details:l,fatal:c,url:e.url,loader:u,context:e,error:o,networkDetails:n,stats:s};if(i){const h=(n==null?void 0:n.url)||e.url;d.response=on({url:h,data:void 0},i)}this.hls.trigger(j.ERROR,d)}handlePlaylistLoaded(e,n,r,i,s,a){const o=this.hls,{type:l,level:c,levelOrTrack:u,id:d,groupId:h,deliveryDirectives:f}=i,p=ax(n,i),m=mD(i);let g=typeof i.level=="number"&&m===tt.MAIN?c:void 0;const b=e.playlistParsingError;if(b){if(this.hls.logger.warn(`${b} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(j.ERROR,{type:ct.NETWORK_ERROR,details:xe.LEVEL_PARSING_ERROR,fatal:!1,url:p,error:b,reason:b.message,response:n,context:i,level:g,parent:m,networkDetails:s,stats:r});return}e.playlistParsingError=null}if(!e.fragments.length){const v=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(j.ERROR,{type:ct.NETWORK_ERROR,details:xe.LEVEL_EMPTY_ERROR,fatal:!1,url:p,error:v,reason:v.message,response:n,context:i,level:g,parent:m,networkDetails:s,stats:r});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case Ft.MANIFEST:case Ft.LEVEL:if(g){if(!u)g=0;else if(u!==o.levels[g]){const v=o.levels.indexOf(u);v>-1&&(g=v)}}o.trigger(j.LEVEL_LOADED,{details:e,levelInfo:u||o.levels[0],level:g||0,id:d||0,stats:r,networkDetails:s,deliveryDirectives:f,withoutMultiVariant:l===Ft.MANIFEST});break;case Ft.AUDIO_TRACK:o.trigger(j.AUDIO_TRACK_LOADED,{details:e,track:u,id:d||0,groupId:h||"",stats:r,networkDetails:s,deliveryDirectives:f});break;case Ft.SUBTITLE_TRACK:o.trigger(j.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:d||0,groupId:h||"",stats:r,networkDetails:s,deliveryDirectives:f});break}}}class Mi{static get version(){return Ap}static isMSESupported(){return I4()}static isSupported(){return ufe()}static getMediaSource(){return Cl()}static get Events(){return j}static get MetadataSchema(){return Ni}static get ErrorTypes(){return ct}static get ErrorDetails(){return xe}static get DefaultConfig(){return Mi.defaultConfig?Mi.defaultConfig:Jhe}static set DefaultConfig(e){Mi.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new HA,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const n=this.logger=xle(e.debug||!1,"Hls instance",e.assetPlayerId),r=this.config=efe(Mi.DefaultConfig,e,n);this.userConfig=e,r.progressive&&tfe(r,n);const{abrController:i,bufferController:s,capLevelController:a,errorController:o,fpsController:l}=r,c=new o(this),u=this.abrController=new i(this),d=new gce(this),h=r.interstitialsController,f=h?this.interstitialsController=new h(this,Mi):null,p=this.bufferController=new s(this,d),m=this.capLevelController=new a(this),g=new l(this),b=new mfe(this),v=r.contentSteeringController,S=v?new v(this):null,E=this.levelController=new cfe(this,S),L=new ofe(this),U=new pfe(this.config,this.logger),O=this.streamController=new ffe(this,d,U),k=this.gapController=new sfe(this,d);m.setStreamController(O),g.setStreamController(O);const I=[b,E,O];f&&I.splice(1,0,f),S&&I.splice(1,0,S),this.networkControllers=I;const R=[u,p,k,m,g,L,d];this.audioTrackController=this.createController(r.audioTrackController,I);const M=r.audioStreamController;M&&I.push(this.audioStreamController=new M(this,d,U)),this.subtitleTrackController=this.createController(r.subtitleTrackController,I);const z=r.subtitleStreamController;z&&I.push(this.subtititleStreamController=new z(this,d,U)),this.createController(r.timelineController,R),U.emeController=this.emeController=this.createController(r.emeController,R),this.cmcdController=this.createController(r.cmcdController,R),this.latencyController=this.createController(lfe,R),this.coreComponents=R,I.push(c);const Z=c.onErrorOut;typeof Z=="function"&&this.on(j.ERROR,Z,c),this.on(j.MANIFEST_LOADED,b.onManifestLoaded,b)}createController(e,n){if(e){const r=new e(this);return n&&n.push(r),r}return null}on(e,n,r=this){this._emitter.on(e,n,r)}once(e,n,r=this){this._emitter.once(e,n,r)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,n,r=this,i){this._emitter.off(e,n,r,i)}listeners(e){return this._emitter.listeners(e)}emit(e,n,r){return this._emitter.emit(e,n,r)}trigger(e,n){if(this.config.debug)return this.emit(e,e,n);try{return this.emit(e,e,n)}catch(r){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+r.message+'". Here is a stacktrace:',r),!this.triggeringException){this.triggeringException=!0;const i=e===j.ERROR;this.trigger(j.ERROR,{type:ct.OTHER_ERROR,details:xe.INTERNAL_EXCEPTION,fatal:i,event:e,error:r}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(j.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(n=>n.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(n=>n.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const s=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(j.ERROR,{type:ct.OTHER_ERROR,details:xe.ATTACH_MEDIA_ERROR,fatal:!0,error:s});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const n="media"in e,r=n?e.media:e,i=n?e:{media:r};this._media=r,this.trigger(j.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia"),this.trigger(j.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(j.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const n=this.media,r=this._url,i=this._url=DA.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),n&&r&&(r!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(n)),this.trigger(j.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,n){this.logger.log(`startLoad(${e+(n?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let r=0;r<this.networkControllers.length&&(this.networkControllers[r].startLoad(e,n),!(!this.started||!this.networkControllers));r++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[tt.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[tt.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[tt.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,n=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),n&&this.startLoad(n))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=she()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const n=!!e;n!==this.config.capLevelToPlayerSize&&(n?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=n)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){ece(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:n}}=this;if(!e)return 0;const r=e.length;for(let i=0;i<r;i++)if(e[i].maxBitrate>=n)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:n,maxHdcpLevel:r}=this;let i;if(n===-1&&e!=null&&e.length?i=e.length-1:i=n,r)for(let s=i;s--;){const a=e[s].attrs["HDCP-LEVEL"];if(a&&a<=r)return s}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var n;return((n=this.audioTrackController)==null?void 0:n.setAudioOption(e))||null}setSubtitleOption(e){var n;return((n=this.subtitleTrackController)==null?void 0:n.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const n=this.audioTrackController;n&&(n.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const n=this.subtitleTrackController;n&&(n.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const n=this.subtitleTrackController;n&&(n.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,n=this.allAudioTracks){const r=y3(n);return m3(e,r,navigator.mediaCapabilities)}}Mi.defaultConfig=void 0;var P4={exports:{}};(function(t,e){(function(n,r){t.exports=r()})(window,function(){return function(n){var r={};function i(s){if(r[s])return r[s].exports;var a=r[s]={i:s,l:!1,exports:{}};return n[s].call(a.exports,a,a.exports,i),a.l=!0,a.exports}return i.m=n,i.c=r,i.d=function(s,a,o){i.o(s,a)||Object.defineProperty(s,a,{enumerable:!0,get:o})},i.r=function(s){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(s,"__esModule",{value:!0})},i.t=function(s,a){if(1&a&&(s=i(s)),8&a||4&a&&typeof s=="object"&&s&&s.__esModule)return s;var o=Object.create(null);if(i.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:s}),2&a&&typeof s!="string")for(var l in s)i.d(o,l,(function(c){return s[c]}).bind(null,l));return o},i.n=function(s){var a=s&&s.__esModule?function(){return s.default}:function(){return s};return i.d(a,"a",a),a},i.o=function(s,a){return Object.prototype.hasOwnProperty.call(s,a)},i.p="",i(i.s=20)}([function(n,r,i){var s=i(9),a=i.n(s),o=function(){function l(){}return l.e=function(c,u){c&&!l.FORCE_GLOBAL_TAG||(c=l.GLOBAL_TAG);var d="[".concat(c,"] > ").concat(u);l.ENABLE_CALLBACK&&l.emitter.emit("log","error",d),l.ENABLE_ERROR&&(console.error?console.error(d):console.warn?console.warn(d):console.log(d))},l.i=function(c,u){c&&!l.FORCE_GLOBAL_TAG||(c=l.GLOBAL_TAG);var d="[".concat(c,"] > ").concat(u);l.ENABLE_CALLBACK&&l.emitter.emit("log","info",d),l.ENABLE_INFO&&(console.info?console.info(d):console.log(d))},l.w=function(c,u){c&&!l.FORCE_GLOBAL_TAG||(c=l.GLOBAL_TAG);var d="[".concat(c,"] > ").concat(u);l.ENABLE_CALLBACK&&l.emitter.emit("log","warn",d),l.ENABLE_WARN&&(console.warn?console.warn(d):console.log(d))},l.d=function(c,u){c&&!l.FORCE_GLOBAL_TAG||(c=l.GLOBAL_TAG);var d="[".concat(c,"] > ").concat(u);l.ENABLE_CALLBACK&&l.emitter.emit("log","debug",d),l.ENABLE_DEBUG&&(console.debug?console.debug(d):console.log(d))},l.v=function(c,u){c&&!l.FORCE_GLOBAL_TAG||(c=l.GLOBAL_TAG);var d="[".concat(c,"] > ").concat(u);l.ENABLE_CALLBACK&&l.emitter.emit("log","verbose",d),l.ENABLE_VERBOSE&&console.log(d)},l}();o.GLOBAL_TAG="mpegts.js",o.FORCE_GLOBAL_TAG=!1,o.ENABLE_ERROR=!0,o.ENABLE_INFO=!0,o.ENABLE_WARN=!0,o.ENABLE_DEBUG=!0,o.ENABLE_VERBOSE=!0,o.ENABLE_CALLBACK=!1,o.emitter=new a.a,r.a=o},function(n,r,i){var s;(function(a){a.IO_ERROR="io_error",a.DEMUX_ERROR="demux_error",a.INIT_SEGMENT="init_segment",a.MEDIA_SEGMENT="media_segment",a.LOADING_COMPLETE="loading_complete",a.RECOVERED_EARLY_EOF="recovered_early_eof",a.MEDIA_INFO="media_info",a.METADATA_ARRIVED="metadata_arrived",a.SCRIPTDATA_ARRIVED="scriptdata_arrived",a.TIMED_ID3_METADATA_ARRIVED="timed_id3_metadata_arrived",a.SYNCHRONOUS_KLV_METADATA_ARRIVED="synchronous_klv_metadata_arrived",a.ASYNCHRONOUS_KLV_METADATA_ARRIVED="asynchronous_klv_metadata_arrived",a.SMPTE2038_METADATA_ARRIVED="smpte2038_metadata_arrived",a.SCTE35_METADATA_ARRIVED="scte35_metadata_arrived",a.PES_PRIVATE_DATA_DESCRIPTOR="pes_private_data_descriptor",a.PES_PRIVATE_DATA_ARRIVED="pes_private_data_arrived",a.STATISTICS_INFO="statistics_info",a.RECOMMEND_SEEKPOINT="recommend_seekpoint"})(s||(s={})),r.a=s},function(n,r,i){i.d(r,"c",function(){return a}),i.d(r,"b",function(){return o}),i.d(r,"a",function(){return l});var s=i(3),a={kIdle:0,kConnecting:1,kBuffering:2,kError:3,kComplete:4},o={OK:"OK",EXCEPTION:"Exception",HTTP_STATUS_CODE_INVALID:"HttpStatusCodeInvalid",CONNECTING_TIMEOUT:"ConnectingTimeout",EARLY_EOF:"EarlyEof",UNRECOVERABLE_EARLY_EOF:"UnrecoverableEarlyEof"},l=function(){function c(u){this._type=u||"undefined",this._status=a.kIdle,this._needStash=!1,this._onContentLengthKnown=null,this._onURLRedirect=null,this._onDataArrival=null,this._onError=null,this._onComplete=null}return c.prototype.destroy=function(){this._status=a.kIdle,this._onContentLengthKnown=null,this._onURLRedirect=null,this._onDataArrival=null,this._onError=null,this._onComplete=null},c.prototype.isWorking=function(){return this._status===a.kConnecting||this._status===a.kBuffering},Object.defineProperty(c.prototype,"type",{get:function(){return this._type},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"status",{get:function(){return this._status},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"needStashBuffer",{get:function(){return this._needStash},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"onContentLengthKnown",{get:function(){return this._onContentLengthKnown},set:function(u){this._onContentLengthKnown=u},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"onURLRedirect",{get:function(){return this._onURLRedirect},set:function(u){this._onURLRedirect=u},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"onDataArrival",{get:function(){return this._onDataArrival},set:function(u){this._onDataArrival=u},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"onError",{get:function(){return this._onError},set:function(u){this._onError=u},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"onComplete",{get:function(){return this._onComplete},set:function(u){this._onComplete=u},enumerable:!1,configurable:!0}),c.prototype.open=function(u,d){throw new s.c("Unimplemented abstract function!")},c.prototype.abort=function(){throw new s.c("Unimplemented abstract function!")},c}()},function(n,r,i){i.d(r,"d",function(){return o}),i.d(r,"a",function(){return l}),i.d(r,"b",function(){return c}),i.d(r,"c",function(){return u});var s,a=(s=function(d,h){return(s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(f,p){f.__proto__=p}||function(f,p){for(var m in p)Object.prototype.hasOwnProperty.call(p,m)&&(f[m]=p[m])})(d,h)},function(d,h){if(typeof h!="function"&&h!==null)throw new TypeError("Class extends value "+String(h)+" is not a constructor or null");function f(){this.constructor=d}s(d,h),d.prototype=h===null?Object.create(h):(f.prototype=h.prototype,new f)}),o=function(){function d(h){this._message=h}return Object.defineProperty(d.prototype,"name",{get:function(){return"RuntimeException"},enumerable:!1,configurable:!0}),Object.defineProperty(d.prototype,"message",{get:function(){return this._message},enumerable:!1,configurable:!0}),d.prototype.toString=function(){return this.name+": "+this.message},d}(),l=function(d){function h(f){return d.call(this,f)||this}return a(h,d),Object.defineProperty(h.prototype,"name",{get:function(){return"IllegalStateException"},enumerable:!1,configurable:!0}),h}(o),c=function(d){function h(f){return d.call(this,f)||this}return a(h,d),Object.defineProperty(h.prototype,"name",{get:function(){return"InvalidArgumentException"},enumerable:!1,configurable:!0}),h}(o),u=function(d){function h(f){return d.call(this,f)||this}return a(h,d),Object.defineProperty(h.prototype,"name",{get:function(){return"NotImplementedException"},enumerable:!1,configurable:!0}),h}(o)},function(n,r,i){var s;(function(a){a.ERROR="error",a.LOADING_COMPLETE="loading_complete",a.RECOVERED_EARLY_EOF="recovered_early_eof",a.MEDIA_INFO="media_info",a.METADATA_ARRIVED="metadata_arrived",a.SCRIPTDATA_ARRIVED="scriptdata_arrived",a.TIMED_ID3_METADATA_ARRIVED="timed_id3_metadata_arrived",a.SYNCHRONOUS_KLV_METADATA_ARRIVED="synchronous_klv_metadata_arrived",a.ASYNCHRONOUS_KLV_METADATA_ARRIVED="asynchronous_klv_metadata_arrived",a.SMPTE2038_METADATA_ARRIVED="smpte2038_metadata_arrived",a.SCTE35_METADATA_ARRIVED="scte35_metadata_arrived",a.PES_PRIVATE_DATA_DESCRIPTOR="pes_private_data_descriptor",a.PES_PRIVATE_DATA_ARRIVED="pes_private_data_arrived",a.STATISTICS_INFO="statistics_info",a.DESTROYING="destroying"})(s||(s={})),r.a=s},function(n,r,i){var s={};(function(){var a=self.navigator.userAgent.toLowerCase(),o=/(edge)\/([\w.]+)/.exec(a)||/(opr)[\/]([\w.]+)/.exec(a)||/(chrome)[ \/]([\w.]+)/.exec(a)||/(iemobile)[\/]([\w.]+)/.exec(a)||/(version)(applewebkit)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+).*(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("trident")>=0&&/(rv)(?::| )([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(firefox)[ \/]([\w.]+)/.exec(a)||[],l=/(ipad)/.exec(a)||/(ipod)/.exec(a)||/(windows phone)/.exec(a)||/(iphone)/.exec(a)||/(kindle)/.exec(a)||/(android)/.exec(a)||/(windows)/.exec(a)||/(mac)/.exec(a)||/(linux)/.exec(a)||/(cros)/.exec(a)||[],c={browser:o[5]||o[3]||o[1]||"",version:o[2]||o[4]||"0",majorVersion:o[4]||o[2]||"0",platform:l[0]||""},u={};if(c.browser){u[c.browser]=!0;var d=c.majorVersion.split(".");u.version={major:parseInt(c.majorVersion,10),string:c.version},d.length>1&&(u.version.minor=parseInt(d[1],10)),d.length>2&&(u.version.build=parseInt(d[2],10))}c.platform&&(u[c.platform]=!0),(u.chrome||u.opr||u.safari)&&(u.webkit=!0),(u.rv||u.iemobile)&&(u.rv&&delete u.rv,c.browser="msie",u.msie=!0),u.edge&&(delete u.edge,c.browser="msedge",u.msedge=!0),u.opr&&(c.browser="opera",u.opera=!0),u.safari&&u.android&&(c.browser="android",u.android=!0);for(var h in u.name=c.browser,u.platform=c.platform,s)s.hasOwnProperty(h)&&delete s[h];Object.assign(s,u)})(),r.a=s},function(n,r,i){r.a={OK:"OK",FORMAT_ERROR:"FormatError",FORMAT_UNSUPPORTED:"FormatUnsupported",CODEC_UNSUPPORTED:"CodecUnsupported"}},function(n,r,i){var s;(function(a){a.ERROR="error",a.SOURCE_OPEN="source_open",a.UPDATE_END="update_end",a.BUFFER_FULL="buffer_full",a.START_STREAMING="start_streaming",a.END_STREAMING="end_streaming"})(s||(s={})),r.a=s},function(n,r,i){var s=i(9),a=i.n(s),o=i(0),l=function(){function c(){}return Object.defineProperty(c,"forceGlobalTag",{get:function(){return o.a.FORCE_GLOBAL_TAG},set:function(u){o.a.FORCE_GLOBAL_TAG=u,c._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(c,"globalTag",{get:function(){return o.a.GLOBAL_TAG},set:function(u){o.a.GLOBAL_TAG=u,c._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(c,"enableAll",{get:function(){return o.a.ENABLE_VERBOSE&&o.a.ENABLE_DEBUG&&o.a.ENABLE_INFO&&o.a.ENABLE_WARN&&o.a.ENABLE_ERROR},set:function(u){o.a.ENABLE_VERBOSE=u,o.a.ENABLE_DEBUG=u,o.a.ENABLE_INFO=u,o.a.ENABLE_WARN=u,o.a.ENABLE_ERROR=u,c._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(c,"enableDebug",{get:function(){return o.a.ENABLE_DEBUG},set:function(u){o.a.ENABLE_DEBUG=u,c._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(c,"enableVerbose",{get:function(){return o.a.ENABLE_VERBOSE},set:function(u){o.a.ENABLE_VERBOSE=u,c._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(c,"enableInfo",{get:function(){return o.a.ENABLE_INFO},set:function(u){o.a.ENABLE_INFO=u,c._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(c,"enableWarn",{get:function(){return o.a.ENABLE_WARN},set:function(u){o.a.ENABLE_WARN=u,c._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(c,"enableError",{get:function(){return o.a.ENABLE_ERROR},set:function(u){o.a.ENABLE_ERROR=u,c._notifyChange()},enumerable:!1,configurable:!0}),c.getConfig=function(){return{globalTag:o.a.GLOBAL_TAG,forceGlobalTag:o.a.FORCE_GLOBAL_TAG,enableVerbose:o.a.ENABLE_VERBOSE,enableDebug:o.a.ENABLE_DEBUG,enableInfo:o.a.ENABLE_INFO,enableWarn:o.a.ENABLE_WARN,enableError:o.a.ENABLE_ERROR,enableCallback:o.a.ENABLE_CALLBACK}},c.applyConfig=function(u){o.a.GLOBAL_TAG=u.globalTag,o.a.FORCE_GLOBAL_TAG=u.forceGlobalTag,o.a.ENABLE_VERBOSE=u.enableVerbose,o.a.ENABLE_DEBUG=u.enableDebug,o.a.ENABLE_INFO=u.enableInfo,o.a.ENABLE_WARN=u.enableWarn,o.a.ENABLE_ERROR=u.enableError,o.a.ENABLE_CALLBACK=u.enableCallback},c._notifyChange=function(){var u=c.emitter;if(u.listenerCount("change")>0){var d=c.getConfig();u.emit("change",d)}},c.registerListener=function(u){c.emitter.addListener("change",u)},c.removeListener=function(u){c.emitter.removeListener("change",u)},c.addLogListener=function(u){o.a.emitter.addListener("log",u),o.a.emitter.listenerCount("log")>0&&(o.a.ENABLE_CALLBACK=!0,c._notifyChange())},c.removeLogListener=function(u){o.a.emitter.removeListener("log",u),o.a.emitter.listenerCount("log")===0&&(o.a.ENABLE_CALLBACK=!1,c._notifyChange())},c}();l.emitter=new a.a,r.a=l},function(n,r,i){var s,a=typeof Reflect=="object"?Reflect:null,o=a&&typeof a.apply=="function"?a.apply:function(E,L,U){return Function.prototype.apply.call(E,L,U)};s=a&&typeof a.ownKeys=="function"?a.ownKeys:Object.getOwnPropertySymbols?function(E){return Object.getOwnPropertyNames(E).concat(Object.getOwnPropertySymbols(E))}:function(E){return Object.getOwnPropertyNames(E)};var l=Number.isNaN||function(E){return E!=E};function c(){c.init.call(this)}n.exports=c,n.exports.once=function(E,L){return new Promise(function(U,O){function k(R){E.removeListener(L,I),O(R)}function I(){typeof E.removeListener=="function"&&E.removeListener("error",k),U([].slice.call(arguments))}S(E,L,I,{once:!0}),L!=="error"&&function(R,M,z){typeof R.on=="function"&&S(R,"error",M,z)}(E,k,{once:!0})})},c.EventEmitter=c,c.prototype._events=void 0,c.prototype._eventsCount=0,c.prototype._maxListeners=void 0;var u=10;function d(E){if(typeof E!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof E)}function h(E){return E._maxListeners===void 0?c.defaultMaxListeners:E._maxListeners}function f(E,L,U,O){var k,I,R,M;if(d(U),(I=E._events)===void 0?(I=E._events=Object.create(null),E._eventsCount=0):(I.newListener!==void 0&&(E.emit("newListener",L,U.listener?U.listener:U),I=E._events),R=I[L]),R===void 0)R=I[L]=U,++E._eventsCount;else if(typeof R=="function"?R=I[L]=O?[U,R]:[R,U]:O?R.unshift(U):R.push(U),(k=h(E))>0&&R.length>k&&!R.warned){R.warned=!0;var z=new Error("Possible EventEmitter memory leak detected. "+R.length+" "+String(L)+" listeners added. Use emitter.setMaxListeners() to increase limit");z.name="MaxListenersExceededWarning",z.emitter=E,z.type=L,z.count=R.length,M=z,console&&console.warn&&console.warn(M)}return E}function p(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function m(E,L,U){var O={fired:!1,wrapFn:void 0,target:E,type:L,listener:U},k=p.bind(O);return k.listener=U,O.wrapFn=k,k}function g(E,L,U){var O=E._events;if(O===void 0)return[];var k=O[L];return k===void 0?[]:typeof k=="function"?U?[k.listener||k]:[k]:U?function(I){for(var R=new Array(I.length),M=0;M<R.length;++M)R[M]=I[M].listener||I[M];return R}(k):v(k,k.length)}function b(E){var L=this._events;if(L!==void 0){var U=L[E];if(typeof U=="function")return 1;if(U!==void 0)return U.length}return 0}function v(E,L){for(var U=new Array(L),O=0;O<L;++O)U[O]=E[O];return U}function S(E,L,U,O){if(typeof E.on=="function")O.once?E.once(L,U):E.on(L,U);else{if(typeof E.addEventListener!="function")throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof E);E.addEventListener(L,function k(I){O.once&&E.removeEventListener(L,k),U(I)})}}Object.defineProperty(c,"defaultMaxListeners",{enumerable:!0,get:function(){return u},set:function(E){if(typeof E!="number"||E<0||l(E))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+E+".");u=E}}),c.init=function(){this._events!==void 0&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},c.prototype.setMaxListeners=function(E){if(typeof E!="number"||E<0||l(E))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+E+".");return this._maxListeners=E,this},c.prototype.getMaxListeners=function(){return h(this)},c.prototype.emit=function(E){for(var L=[],U=1;U<arguments.length;U++)L.push(arguments[U]);var O=E==="error",k=this._events;if(k!==void 0)O=O&&k.error===void 0;else if(!O)return!1;if(O){var I;if(L.length>0&&(I=L[0]),I instanceof Error)throw I;var R=new Error("Unhandled error."+(I?" ("+I.message+")":""));throw R.context=I,R}var M=k[E];if(M===void 0)return!1;if(typeof M=="function")o(M,this,L);else{var z=M.length,Z=v(M,z);for(U=0;U<z;++U)o(Z[U],this,L)}return!0},c.prototype.addListener=function(E,L){return f(this,E,L,!1)},c.prototype.on=c.prototype.addListener,c.prototype.prependListener=function(E,L){return f(this,E,L,!0)},c.prototype.once=function(E,L){return d(L),this.on(E,m(this,E,L)),this},c.prototype.prependOnceListener=function(E,L){return d(L),this.prependListener(E,m(this,E,L)),this},c.prototype.removeListener=function(E,L){var U,O,k,I,R;if(d(L),(O=this._events)===void 0)return this;if((U=O[E])===void 0)return this;if(U===L||U.listener===L)--this._eventsCount==0?this._events=Object.create(null):(delete O[E],O.removeListener&&this.emit("removeListener",E,U.listener||L));else if(typeof U!="function"){for(k=-1,I=U.length-1;I>=0;I--)if(U[I]===L||U[I].listener===L){R=U[I].listener,k=I;break}if(k<0)return this;k===0?U.shift():function(M,z){for(;z+1<M.length;z++)M[z]=M[z+1];M.pop()}(U,k),U.length===1&&(O[E]=U[0]),O.removeListener!==void 0&&this.emit("removeListener",E,R||L)}return this},c.prototype.off=c.prototype.removeListener,c.prototype.removeAllListeners=function(E){var L,U,O;if((U=this._events)===void 0)return this;if(U.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):U[E]!==void 0&&(--this._eventsCount==0?this._events=Object.create(null):delete U[E]),this;if(arguments.length===0){var k,I=Object.keys(U);for(O=0;O<I.length;++O)(k=I[O])!=="removeListener"&&this.removeAllListeners(k);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(typeof(L=U[E])=="function")this.removeListener(E,L);else if(L!==void 0)for(O=L.length-1;O>=0;O--)this.removeListener(E,L[O]);return this},c.prototype.listeners=function(E){return g(this,E,!0)},c.prototype.rawListeners=function(E){return g(this,E,!1)},c.listenerCount=function(E,L){return typeof E.listenerCount=="function"?E.listenerCount(L):b.call(E,L)},c.prototype.listenerCount=b,c.prototype.eventNames=function(){return this._eventsCount>0?s(this._events):[]}},function(n,r,i){i.d(r,"b",function(){return o}),i.d(r,"a",function(){return l});var s=i(2),a=i(6),o={NETWORK_ERROR:"NetworkError",MEDIA_ERROR:"MediaError",OTHER_ERROR:"OtherError"},l={NETWORK_EXCEPTION:s.b.EXCEPTION,NETWORK_STATUS_CODE_INVALID:s.b.HTTP_STATUS_CODE_INVALID,NETWORK_TIMEOUT:s.b.CONNECTING_TIMEOUT,NETWORK_UNRECOVERABLE_EARLY_EOF:s.b.UNRECOVERABLE_EARLY_EOF,MEDIA_MSE_ERROR:"MediaMSEError",MEDIA_FORMAT_ERROR:a.a.FORMAT_ERROR,MEDIA_FORMAT_UNSUPPORTED:a.a.FORMAT_UNSUPPORTED,MEDIA_CODEC_UNSUPPORTED:a.a.CODEC_UNSUPPORTED}},function(n,r,i){i.d(r,"d",function(){return s}),i.d(r,"b",function(){return a}),i.d(r,"a",function(){return o}),i.d(r,"c",function(){return l});var s=function(c,u,d,h,f){this.dts=c,this.pts=u,this.duration=d,this.originalDts=h,this.isSyncPoint=f,this.fileposition=null},a=function(){function c(){this.beginDts=0,this.endDts=0,this.beginPts=0,this.endPts=0,this.originalBeginDts=0,this.originalEndDts=0,this.syncPoints=[],this.firstSample=null,this.lastSample=null}return c.prototype.appendSyncPoint=function(u){u.isSyncPoint=!0,this.syncPoints.push(u)},c}(),o=function(){function c(){this._list=[]}return c.prototype.clear=function(){this._list=[]},c.prototype.appendArray=function(u){var d=this._list;u.length!==0&&(d.length>0&&u[0].originalDts<d[d.length-1].originalDts&&this.clear(),Array.prototype.push.apply(d,u))},c.prototype.getLastSyncPointBeforeDts=function(u){if(this._list.length==0)return null;var d=this._list,h=0,f=d.length-1,p=0,m=0,g=f;for(u<d[0].dts&&(h=0,m=g+1);m<=g;){if((p=m+Math.floor((g-m)/2))===f||u>=d[p].dts&&u<d[p+1].dts){h=p;break}d[p].dts<u?m=p+1:g=p-1}return this._list[h]},c}(),l=function(){function c(u){this._type=u,this._list=[],this._lastAppendLocation=-1}return Object.defineProperty(c.prototype,"type",{get:function(){return this._type},enumerable:!1,configurable:!0}),Object.defineProperty(c.prototype,"length",{get:function(){return this._list.length},enumerable:!1,configurable:!0}),c.prototype.isEmpty=function(){return this._list.length===0},c.prototype.clear=function(){this._list=[],this._lastAppendLocation=-1},c.prototype._searchNearestSegmentBefore=function(u){var d=this._list;if(d.length===0)return-2;var h=d.length-1,f=0,p=0,m=h,g=0;if(u<d[0].originalBeginDts)return g=-1;for(;p<=m;){if((f=p+Math.floor((m-p)/2))===h||u>d[f].lastSample.originalDts&&u<d[f+1].originalBeginDts){g=f;break}d[f].originalBeginDts<u?p=f+1:m=f-1}return g},c.prototype._searchNearestSegmentAfter=function(u){return this._searchNearestSegmentBefore(u)+1},c.prototype.append=function(u){var d=this._list,h=u,f=this._lastAppendLocation,p=0;f!==-1&&f<d.length&&h.originalBeginDts>=d[f].lastSample.originalDts&&(f===d.length-1||f<d.length-1&&h.originalBeginDts<d[f+1].originalBeginDts)?p=f+1:d.length>0&&(p=this._searchNearestSegmentBefore(h.originalBeginDts)+1),this._lastAppendLocation=p,this._list.splice(p,0,h)},c.prototype.getLastSegmentBefore=function(u){var d=this._searchNearestSegmentBefore(u);return d>=0?this._list[d]:null},c.prototype.getLastSampleBefore=function(u){var d=this.getLastSegmentBefore(u);return d!=null?d.lastSample:null},c.prototype.getLastSyncPointBefore=function(u){for(var d=this._searchNearestSegmentBefore(u),h=this._list[d].syncPoints;h.length===0&&d>0;)d--,h=this._list[d].syncPoints;return h.length>0?h[h.length-1]:null},c}()},function(n,r,i){var s=function(){function a(){this.mimeType=null,this.duration=null,this.hasAudio=null,this.hasVideo=null,this.audioCodec=null,this.videoCodec=null,this.audioDataRate=null,this.videoDataRate=null,this.audioSampleRate=null,this.audioChannelCount=null,this.width=null,this.height=null,this.fps=null,this.profile=null,this.level=null,this.refFrames=null,this.chromaFormat=null,this.sarNum=null,this.sarDen=null,this.metadata=null,this.segments=null,this.segmentCount=null,this.hasKeyframesIndex=null,this.keyframesIndex=null}return a.prototype.isComplete=function(){var o=this.hasAudio===!1||this.hasAudio===!0&&this.audioCodec!=null&&this.audioSampleRate!=null&&this.audioChannelCount!=null,l=this.hasVideo===!1||this.hasVideo===!0&&this.videoCodec!=null&&this.width!=null&&this.height!=null&&this.fps!=null&&this.profile!=null&&this.level!=null&&this.refFrames!=null&&this.chromaFormat!=null&&this.sarNum!=null&&this.sarDen!=null;return this.mimeType!=null&&o&&l},a.prototype.isSeekable=function(){return this.hasKeyframesIndex===!0},a.prototype.getNearestKeyframe=function(o){if(this.keyframesIndex==null)return null;var l=this.keyframesIndex,c=this._search(l.times,o);return{index:c,milliseconds:l.times[c],fileposition:l.filepositions[c]}},a.prototype._search=function(o,l){var c=0,u=o.length-1,d=0,h=0,f=u;for(l<o[0]&&(c=0,h=f+1);h<=f;){if((d=h+Math.floor((f-h)/2))===u||l>=o[d]&&l<o[d+1]){c=d;break}o[d]<l?h=d+1:f=d-1}return c},a}();r.a=s},function(n,r,i){var s=i(9),a=i.n(s),o=i(0),l=i(5),c=i(12);function u(C,A,w){var x=C;if(A+w<x.length){for(;w--;)if((192&x[++A])!=128)return!1;return!0}return!1}var d,h=function(C){for(var A=[],w=C,x=0,P=C.length;x<P;)if(w[x]<128)A.push(String.fromCharCode(w[x])),++x;else{if(!(w[x]<192)){if(w[x]<224){if(u(w,x,1)&&(F=(31&w[x])<<6|63&w[x+1])>=128){A.push(String.fromCharCode(65535&F)),x+=2;continue}}else if(w[x]<240){if(u(w,x,2)&&(F=(15&w[x])<<12|(63&w[x+1])<<6|63&w[x+2])>=2048&&(63488&F)!=55296){A.push(String.fromCharCode(65535&F)),x+=3;continue}}else if(w[x]<248){var F;if(u(w,x,3)&&(F=(7&w[x])<<18|(63&w[x+1])<<12|(63&w[x+2])<<6|63&w[x+3])>65536&&F<1114112){F-=65536,A.push(String.fromCharCode(F>>>10|55296)),A.push(String.fromCharCode(1023&F|56320)),x+=4;continue}}}A.push("�"),++x}return A.join("")},f=i(3),p=(d=new ArrayBuffer(2),new DataView(d).setInt16(0,256,!0),new Int16Array(d)[0]===256),m=function(){function C(){}return C.parseScriptData=function(A,w,x){var P={};try{var F=C.parseValue(A,w,x),$=C.parseValue(A,w+F.size,x-F.size);P[F.data]=$.data}catch(K){o.a.e("AMF",K.toString())}return P},C.parseObject=function(A,w,x){if(x<3)throw new f.a("Data not enough when parse ScriptDataObject");var P=C.parseString(A,w,x),F=C.parseValue(A,w+P.size,x-P.size),$=F.objectEnd;return{data:{name:P.data,value:F.data},size:P.size+F.size,objectEnd:$}},C.parseVariable=function(A,w,x){return C.parseObject(A,w,x)},C.parseString=function(A,w,x){if(x<2)throw new f.a("Data not enough when parse String");var P=new DataView(A,w,x).getUint16(0,!p);return{data:P>0?h(new Uint8Array(A,w+2,P)):"",size:2+P}},C.parseLongString=function(A,w,x){if(x<4)throw new f.a("Data not enough when parse LongString");var P=new DataView(A,w,x).getUint32(0,!p);return{data:P>0?h(new Uint8Array(A,w+4,P)):"",size:4+P}},C.parseDate=function(A,w,x){if(x<10)throw new f.a("Data size invalid when parse Date");var P=new DataView(A,w,x),F=P.getFloat64(0,!p),$=P.getInt16(8,!p);return{data:new Date(F+=60*$*1e3),size:10}},C.parseValue=function(A,w,x){if(x<1)throw new f.a("Data not enough when parse Value");var P,F=new DataView(A,w,x),$=1,K=F.getUint8(0),ne=!1;try{switch(K){case 0:P=F.getFloat64(1,!p),$+=8;break;case 1:P=!!F.getUint8(1),$+=1;break;case 2:var ee=C.parseString(A,w+1,x-1);P=ee.data,$+=ee.size;break;case 3:P={};var se=0;for((16777215&F.getUint32(x-4,!p))==9&&(se=3);$<x-4;){var le=C.parseObject(A,w+$,x-$-se);if(le.objectEnd)break;P[le.data.name]=le.data.value,$+=le.size}$<=x-3&&(16777215&F.getUint32($-1,!p))===9&&($+=3);break;case 8:for(P={},$+=4,se=0,(16777215&F.getUint32(x-4,!p))==9&&(se=3);$<x-8;){var ae=C.parseVariable(A,w+$,x-$-se);if(ae.objectEnd)break;P[ae.data.name]=ae.data.value,$+=ae.size}$<=x-3&&(16777215&F.getUint32($-1,!p))===9&&($+=3);break;case 9:P=void 0,$=1,ne=!0;break;case 10:P=[];var ce=F.getUint32(1,!p);$+=4;for(var Te=0;Te<ce;Te++){var Be=C.parseValue(A,w+$,x-$);P.push(Be.data),$+=Be.size}break;case 11:var Pe=C.parseDate(A,w+1,x-1);P=Pe.data,$+=Pe.size;break;case 12:var Je=C.parseString(A,w+1,x-1);P=Je.data,$+=Je.size;break;default:$=x,o.a.w("AMF","Unsupported AMF value type "+K)}}catch(Ye){o.a.e("AMF",Ye.toString())}return{data:P,size:$,objectEnd:ne}},C}(),g=function(){function C(A){this.TAG="ExpGolomb",this._buffer=A,this._buffer_index=0,this._total_bytes=A.byteLength,this._total_bits=8*A.byteLength,this._current_word=0,this._current_word_bits_left=0}return C.prototype.destroy=function(){this._buffer=null},C.prototype._fillCurrentWord=function(){var A=this._total_bytes-this._buffer_index;if(A<=0)throw new f.a("ExpGolomb: _fillCurrentWord() but no bytes available");var w=Math.min(4,A),x=new Uint8Array(4);x.set(this._buffer.subarray(this._buffer_index,this._buffer_index+w)),this._current_word=new DataView(x.buffer).getUint32(0,!1),this._buffer_index+=w,this._current_word_bits_left=8*w},C.prototype.readBits=function(A){if(A>32)throw new f.b("ExpGolomb: readBits() bits exceeded max 32bits!");if(A<=this._current_word_bits_left){var w=this._current_word>>>32-A;return this._current_word<<=A,this._current_word_bits_left-=A,w}var x=this._current_word_bits_left?this._current_word:0;x>>>=32-this._current_word_bits_left;var P=A-this._current_word_bits_left;this._fillCurrentWord();var F=Math.min(P,this._current_word_bits_left),$=this._current_word>>>32-F;return this._current_word<<=F,this._current_word_bits_left-=F,x=x<<F|$},C.prototype.readBool=function(){return this.readBits(1)===1},C.prototype.readByte=function(){return this.readBits(8)},C.prototype._skipLeadingZero=function(){var A;for(A=0;A<this._current_word_bits_left;A++)if(this._current_word&2147483648>>>A)return this._current_word<<=A,this._current_word_bits_left-=A,A;return this._fillCurrentWord(),A+this._skipLeadingZero()},C.prototype.readUEG=function(){var A=this._skipLeadingZero();return this.readBits(A+1)-1},C.prototype.readSEG=function(){var A=this.readUEG();return 1&A?A+1>>>1:-1*(A>>>1)},C}(),b=function(){function C(){}return C._ebsp2rbsp=function(A){for(var w=A,x=w.byteLength,P=new Uint8Array(x),F=0,$=0;$<x;$++)$>=2&&w[$]===3&&w[$-1]===0&&w[$-2]===0||(P[F]=w[$],F++);return new Uint8Array(P.buffer,0,F)},C.parseSPS=function(A){for(var w=A.subarray(1,4),x="avc1.",P=0;P<3;P++){var F=w[P].toString(16);F.length<2&&(F="0"+F),x+=F}var $=C._ebsp2rbsp(A),K=new g($);K.readByte();var ne=K.readByte();K.readByte();var ee=K.readByte();K.readUEG();var se=C.getProfileString(ne),le=C.getLevelString(ee),ae=1,ce=420,Te=8,Be=8;if((ne===100||ne===110||ne===122||ne===244||ne===44||ne===83||ne===86||ne===118||ne===128||ne===138||ne===144)&&((ae=K.readUEG())===3&&K.readBits(1),ae<=3&&(ce=[0,420,422,444][ae]),Te=K.readUEG()+8,Be=K.readUEG()+8,K.readBits(1),K.readBool()))for(var Pe=ae!==3?8:12,Je=0;Je<Pe;Je++)K.readBool()&&(Je<6?C._skipScalingList(K,16):C._skipScalingList(K,64));K.readUEG();var Ye=K.readUEG();if(Ye===0)K.readUEG();else if(Ye===1){K.readBits(1),K.readSEG(),K.readSEG();var Ge=K.readUEG();for(Je=0;Je<Ge;Je++)K.readSEG()}var ut=K.readUEG();K.readBits(1);var bt=K.readUEG(),Xe=K.readUEG(),Ke=K.readBits(1);Ke===0&&K.readBits(1),K.readBits(1);var Rt=0,dt=0,pt=0,Ot=0;K.readBool()&&(Rt=K.readUEG(),dt=K.readUEG(),pt=K.readUEG(),Ot=K.readUEG());var Jt=1,yt=1,kt=0,ht=!0,vn=0,Ar=0;if(K.readBool()){if(K.readBool()){var On=K.readByte();On>0&&On<16?(Jt=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][On-1],yt=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][On-1]):On===255&&(Jt=K.readByte()<<8|K.readByte(),yt=K.readByte()<<8|K.readByte())}if(K.readBool()&&K.readBool(),K.readBool()&&(K.readBits(4),K.readBool()&&K.readBits(24)),K.readBool()&&(K.readUEG(),K.readUEG()),K.readBool()){var Rr=K.readBits(32),cr=K.readBits(32);ht=K.readBool(),kt=(vn=cr)/(Ar=2*Rr)}}var Yn=1;Jt===1&&yt===1||(Yn=Jt/yt);var _r=0,Vt=0;ae===0?(_r=1,Vt=2-Ke):(_r=ae===3?1:2,Vt=(ae===1?2:1)*(2-Ke));var Ji=16*(bt+1),xs=16*(Xe+1)*(2-Ke);Ji-=(Rt+dt)*_r,xs-=(pt+Ot)*Vt;var Gt=Math.ceil(Ji*Yn);return K.destroy(),K=null,{codec_mimetype:x,profile_idc:ne,level_idc:ee,profile_string:se,level_string:le,chroma_format_idc:ae,bit_depth:Te,bit_depth_luma:Te,bit_depth_chroma:Be,ref_frames:ut,chroma_format:ce,chroma_format_string:C.getChromaFormatString(ce),frame_rate:{fixed:ht,fps:kt,fps_den:Ar,fps_num:vn},sar_ratio:{width:Jt,height:yt},codec_size:{width:Ji,height:xs},present_size:{width:Gt,height:xs}}},C._skipScalingList=function(A,w){for(var x=8,P=8,F=0;F<w;F++)P!==0&&(P=(x+A.readSEG()+256)%256),x=P===0?x:P},C.getProfileString=function(A){switch(A){case 66:return"Baseline";case 77:return"Main";case 88:return"Extended";case 100:return"High";case 110:return"High10";case 122:return"High422";case 244:return"High444";default:return"Unknown"}},C.getLevelString=function(A){return(A/10).toFixed(1)},C.getChromaFormatString=function(A){switch(A){case 420:return"4:2:0";case 422:return"4:2:2";case 444:return"4:4:4";default:return"Unknown"}},C}(),v=i(6),S=function(){function C(){}return C._ebsp2rbsp=function(A){for(var w=A,x=w.byteLength,P=new Uint8Array(x),F=0,$=0;$<x;$++)$>=2&&w[$]===3&&w[$-1]===0&&w[$-2]===0||(P[F]=w[$],F++);return new Uint8Array(P.buffer,0,F)},C.parseVPS=function(A){var w=C._ebsp2rbsp(A),x=new g(w);return x.readByte(),x.readByte(),x.readBits(4),x.readBits(2),x.readBits(6),{num_temporal_layers:x.readBits(3)+1,temporal_id_nested:x.readBool()}},C.parseSPS=function(A){var w=C._ebsp2rbsp(A),x=new g(w);x.readByte(),x.readByte();for(var P=0,F=0,$=0,K=0,ne=(x.readBits(4),x.readBits(3)),ee=(x.readBool(),x.readBits(2)),se=x.readBool(),le=x.readBits(5),ae=x.readByte(),ce=x.readByte(),Te=x.readByte(),Be=x.readByte(),Pe=x.readByte(),Je=x.readByte(),Ye=x.readByte(),Ge=x.readByte(),ut=x.readByte(),bt=x.readByte(),Xe=x.readByte(),Ke=[],Rt=[],dt=0;dt<ne;dt++)Ke.push(x.readBool()),Rt.push(x.readBool());if(ne>0)for(dt=ne;dt<8;dt++)x.readBits(2);for(dt=0;dt<ne;dt++)Ke[dt]&&(x.readByte(),x.readByte(),x.readByte(),x.readByte(),x.readByte(),x.readByte(),x.readByte(),x.readByte(),x.readByte(),x.readByte(),x.readByte()),Rt[dt]&&x.readByte();x.readUEG();var pt=x.readUEG();pt==3&&x.readBits(1);var Ot=x.readUEG(),Jt=x.readUEG();x.readBool()&&(P+=x.readUEG(),F+=x.readUEG(),$+=x.readUEG(),K+=x.readUEG());var yt=x.readUEG(),kt=x.readUEG(),ht=x.readUEG();for(dt=x.readBool()?0:ne;dt<=ne;dt++)x.readUEG(),x.readUEG(),x.readUEG();if(x.readUEG(),x.readUEG(),x.readUEG(),x.readUEG(),x.readUEG(),x.readUEG(),x.readBool()&&x.readBool())for(var vn=0;vn<4;vn++)for(var Ar=0;Ar<(vn===3?2:6);Ar++)if(x.readBool()){var On=Math.min(64,1<<4+(vn<<1));for(vn>1&&x.readSEG(),dt=0;dt<On;dt++)x.readSEG()}else x.readUEG();x.readBool(),x.readBool(),x.readBool()&&(x.readByte(),x.readUEG(),x.readUEG(),x.readBool());var Rr=x.readUEG(),cr=0;for(dt=0;dt<Rr;dt++){var Yn=!1;if(dt!==0&&(Yn=x.readBool()),Yn){dt===Rr&&x.readUEG(),x.readBool(),x.readUEG();for(var _r=0,Vt=0;Vt<=cr;Vt++){var Ji=x.readBool(),xs=!1;Ji||(xs=x.readBool()),(Ji||xs)&&_r++}cr=_r}else{var Gt=x.readUEG(),wh=x.readUEG();for(cr=Gt+wh,Vt=0;Vt<Gt;Vt++)x.readUEG(),x.readBool();for(Vt=0;Vt<wh;Vt++)x.readUEG(),x.readBool()}}if(x.readBool()){var Nv=x.readUEG();for(dt=0;dt<Nv;dt++){for(Vt=0;Vt<ht+4;Vt++)x.readBits(1);x.readBits(1)}}var pm=0,ur=1,Zi=1,Bl=!1,es=1,Zc=1;if(x.readBool(),x.readBool(),x.readBool()){if(x.readBool()){var bo=x.readByte();bo>0&&bo<=16?(ur=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][bo-1],Zi=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][bo-1]):bo===255&&(ur=x.readBits(16),Zi=x.readBits(16))}if(x.readBool()&&x.readBool(),x.readBool()&&(x.readBits(3),x.readBool(),x.readBool()&&(x.readByte(),x.readByte(),x.readByte())),x.readBool()&&(x.readUEG(),x.readUEG()),x.readBool(),x.readBool(),x.readBool(),x.readBool()&&(x.readUEG(),x.readUEG(),x.readUEG(),x.readUEG()),x.readBool()&&(es=x.readBits(32),Zc=x.readBits(32),x.readBool()&&x.readUEG(),x.readBool())){var jn=!1,Qr=!1,Fs=!1;for(jn=x.readBool(),Qr=x.readBool(),(jn||Qr)&&((Fs=x.readBool())&&(x.readByte(),x.readBits(5),x.readBool(),x.readBits(5)),x.readBits(4),x.readBits(4),Fs&&x.readBits(4),x.readBits(5),x.readBits(5),x.readBits(5)),dt=0;dt<=ne;dt++){var xo=x.readBool();Bl=xo;var eu=!0,ts=1;xo||(eu=x.readBool());var mm=!1;if(eu?x.readUEG():mm=x.readBool(),mm||(ts=x.readUEG()+1),jn){for(Vt=0;Vt<ts;Vt++)x.readUEG(),x.readUEG(),Fs&&(x.readUEG(),x.readUEG());x.readBool()}if(Qr){for(Vt=0;Vt<ts;Vt++)x.readUEG(),x.readUEG(),Fs&&(x.readUEG(),x.readUEG());x.readBool()}}}x.readBool()&&(x.readBool(),x.readBool(),x.readBool(),pm=x.readUEG(),x.readUEG(),x.readUEG(),x.readUEG(),x.readUEG())}x.readBool();var ns="hvc1.".concat(le,".1.L").concat(Xe,".B0"),tu=Ot-(P+F)*(pt===1||pt===2?2:1),Th=Jt-($+K)*(pt===1?2:1),nu=1;return ur!==1&&Zi!==1&&(nu=ur/Zi),x.destroy(),x=null,{codec_mimetype:ns,profile_string:C.getProfileString(le),level_string:C.getLevelString(Xe),profile_idc:le,bit_depth:yt+8,ref_frames:1,chroma_format:pt,chroma_format_string:C.getChromaFormatString(pt),general_level_idc:Xe,general_profile_space:ee,general_tier_flag:se,general_profile_idc:le,general_profile_compatibility_flags_1:ae,general_profile_compatibility_flags_2:ce,general_profile_compatibility_flags_3:Te,general_profile_compatibility_flags_4:Be,general_constraint_indicator_flags_1:Pe,general_constraint_indicator_flags_2:Je,general_constraint_indicator_flags_3:Ye,general_constraint_indicator_flags_4:Ge,general_constraint_indicator_flags_5:ut,general_constraint_indicator_flags_6:bt,min_spatial_segmentation_idc:pm,constant_frame_rate:0,chroma_format_idc:pt,bit_depth_luma_minus8:yt,bit_depth_chroma_minus8:kt,frame_rate:{fixed:Bl,fps:Zc/es,fps_den:es,fps_num:Zc},sar_ratio:{width:ur,height:Zi},codec_size:{width:tu,height:Th},present_size:{width:tu*nu,height:Th}}},C.parsePPS=function(A){var w=C._ebsp2rbsp(A),x=new g(w);x.readByte(),x.readByte(),x.readUEG(),x.readUEG(),x.readBool(),x.readBool(),x.readBits(3),x.readBool(),x.readBool(),x.readUEG(),x.readUEG(),x.readSEG(),x.readBool(),x.readBool(),x.readBool()&&x.readUEG(),x.readSEG(),x.readSEG(),x.readBool(),x.readBool(),x.readBool(),x.readBool();var P=x.readBool(),F=x.readBool(),$=1;return F&&P?$=0:F?$=3:P&&($=2),{parallelismType:$}},C.getChromaFormatString=function(A){switch(A){case 0:return"4:0:0";case 1:return"4:2:0";case 2:return"4:2:2";case 3:return"4:4:4";default:return"Unknown"}},C.getProfileString=function(A){switch(A){case 1:return"Main";case 2:return"Main10";case 3:return"MainSP";case 4:return"Rext";case 9:return"SCC";default:return"Unknown"}},C.getLevelString=function(A){return(A/30).toFixed(1)},C}();function E(C){return C.byteOffset%2==0&&C.byteLength%2==0}function L(C){return C.byteOffset%4==0&&C.byteLength%4==0}function U(C,A){for(var w=0;w<C.length;w++)if(C[w]!==A[w])return!1;return!0}var O=function(C,A){return C.byteLength===A.byteLength&&(L(C)&&L(A)?function(w,x){return U(new Uint32Array(w.buffer,w.byteOffset,w.byteLength/4),new Uint32Array(x.buffer,x.byteOffset,x.byteLength/4))}(C,A):E(C)&&E(A)?function(w,x){return U(new Uint16Array(w.buffer,w.byteOffset,w.byteLength/2),new Uint16Array(x.buffer,x.byteOffset,x.byteLength/2))}(C,A):function(w,x){return U(w,x)}(C,A))},k=function(){return(k=Object.assign||function(C){for(var A,w=1,x=arguments.length;w<x;w++)for(var P in A=arguments[w])Object.prototype.hasOwnProperty.call(A,P)&&(C[P]=A[P]);return C}).apply(this,arguments)},I=function(){function C(){}return C.parseOBUs=function(A,w){for(var x=0;x<A.byteLength;){var P=x,F=(A[x],(120&A[x])>>3),$=(4&A[x])!=0,K=(2&A[x])!=0;A[x],x+=1,$&&(x+=1);var ne=Number.POSITIVE_INFINITY;if(K){ne=0;for(var ee=0;;ee++){var se=A[x++];if(ne|=(127&se)<<7*ee,(128&se)==0)break}}console.log(F),F===1?w=k(k({},C.parseSeuqneceHeader(A.subarray(x,x+ne))),{sequence_header_data:A.subarray(P,x+ne)}):(F==3&&w||F==6&&w)&&(w=C.parseOBUFrameHeader(A.subarray(x,x+ne),0,0,w)),x+=ne}return w},C.parseSeuqneceHeader=function(A){var w=new g(A),x=w.readBits(3),P=(w.readBool(),w.readBool()),F=!0,$=0,K=1,ne=void 0,ee=[];if(P)ee.push({operating_point_idc:0,level:w.readBits(5),tier:0});else{if(w.readBool()){var se=w.readBits(32),le=w.readBits(32),ae=w.readBool();if(ae){for(var ce=0;w.readBits(1)===0;)ce+=1;ce>=32||(1<<ce)-1+w.readBits(ce)}($=le)/(K=se),F=ae,w.readBool()&&(w.readBits(5),w.readBits(32),ne=w.readBits(5),w.readBits(5))}for(var Te=w.readBool(),Be=w.readBits(5),Pe=0;Pe<=Be;Pe++){var Je=w.readBits(12),Ye=w.readBits(5),Ge=Ye>7?w.readBits(1):0;ee.push({operating_point_idc:Je,level:Ye,tier:Ge}),Te&&w.readBool()&&w.readBits(4)}}var ut=ee[0],bt=ut.level,Xe=ut.tier,Ke=w.readBits(4),Rt=w.readBits(4),dt=w.readBits(Ke+1)+1,pt=w.readBits(Rt+1)+1,Ot=!1;P||(Ot=w.readBool()),Ot&&(w.readBits(4),w.readBits(4)),w.readBool(),w.readBool(),w.readBool();var Jt=!1,yt=2,kt=2,ht=0;P||(w.readBool(),w.readBool(),w.readBool(),w.readBool(),(Jt=w.readBool())&&(w.readBool(),w.readBool()),(yt=w.readBool()?2:w.readBits(1))?kt=w.readBool()?2:w.readBits(1):kt=2,Jt?ht=w.readBits(3)+1:ht=0);var vn=w.readBool(),Ar=(w.readBool(),w.readBool(),w.readBool()),On=8;x===2&&Ar?On=w.readBool()?12:10:On=Ar?10:8;var Rr=!1;x!==1&&(Rr=w.readBool()),w.readBool()&&(w.readBits(8),w.readBits(8),w.readBits(8));var cr=1,Yn=1;return Rr?(w.readBits(1),cr=1,Yn=1):(w.readBits(1),x==0?(cr=1,Yn=1):x==1?(cr=0,Yn=0):On==12?w.readBits(1)&&w.readBits(1):(cr=1,Yn=0),cr&&Yn&&w.readBits(2),w.readBits(1)),w.readBool(),w.destroy(),w=null,{codec_mimetype:"av01.".concat(x,".").concat(C.getLevelString(bt,Xe),".").concat(On.toString(10).padStart(2,"0")),level:bt,tier:Xe,level_string:C.getLevelString(bt,Xe),profile_idc:x,profile_string:"".concat(x),bit_depth:On,ref_frames:1,chroma_format:C.getChromaFormat(Rr,cr,Yn),chroma_format_string:C.getChromaFormatString(Rr,cr,Yn),sequence_header:{frame_id_numbers_present_flag:Ot,additional_frame_id_length_minus_1:void 0,delta_frame_id_length_minus_2:void 0,reduced_still_picture_header:P,decoder_model_info_present_flag:!1,operating_points:ee,buffer_removal_time_length_minus_1:ne,equal_picture_interval:F,seq_force_screen_content_tools:yt,seq_force_integer_mv:kt,enable_order_hint:Jt,order_hint_bits:ht,enable_superres:vn,frame_width_bit:Ke+1,frame_height_bit:Rt+1,max_frame_width:dt,max_frame_height:pt},keyframe:void 0,frame_rate:{fixed:F,fps:$/K,fps_den:K,fps_num:$}}},C.parseOBUFrameHeader=function(A,w,x,P){var F=P.sequence_header,$=new g(A),K=(F.max_frame_width,F.max_frame_height,0);F.frame_id_numbers_present_flag&&(K=F.additional_frame_id_length_minus_1+F.delta_frame_id_length_minus_2+3);var ne=0,ee=!0,se=!0,le=!1;if(!F.reduced_still_picture_header){if($.readBool())return P;ee=(ne=$.readBits(2))===2||ne===0,(se=$.readBool())&&F.decoder_model_info_present_flag&&F.equal_picture_interval,se&&$.readBool(),le=!!(ne===3||ne===0&&se)||$.readBool()}P.keyframe=ee,$.readBool();var ae=F.seq_force_screen_content_tools;F.seq_force_screen_content_tools===2&&(ae=$.readBits(1)),ae&&(F.seq_force_integer_mv,F.seq_force_integer_mv==2&&$.readBits(1)),F.frame_id_numbers_present_flag&&$.readBits(K);var ce=!1;if(ce=ne==3||!F.reduced_still_picture_header&&$.readBool(),$.readBits(F.order_hint_bits),ee||le||$.readBits(3),F.decoder_model_info_present_flag&&$.readBool()){for(var Te=0;Te<=F.operating_points_cnt_minus_1;Te++)if(F.operating_points[Te].decoder_model_present_for_this_op[Te]){var Be=F.operating_points[Te].operating_point_idc;(Be===0||Be>>w&1&&Be>>x+8&1)&&$.readBits(F.buffer_removal_time_length_minus_1+1)}}var Pe=255;if(ne===3||ne==0&&se||(Pe=$.readBits(8)),(ee||Pe!==255)&&le&&F.enable_order_hint)for(var Je=0;Je<8;Je++)$.readBits(F.order_hint_bits);if(ee){var Ye=C.frameSizeAndRenderSize($,ce,F);P.codec_size={width:Ye.FrameWidth,height:Ye.FrameHeight},P.present_size={width:Ye.RenderWidth,height:Ye.RenderHeight},P.sar_ratio={width:Ye.RenderWidth/Ye.FrameWidth,height:Ye.RenderHeight/Ye.FrameHeight}}return $.destroy(),$=null,P},C.frameSizeAndRenderSize=function(A,w,x){var P=x.max_frame_width,F=x.max_frame_height;w&&(P=A.readBits(x.frame_width_bit)+1,F=A.readBits(x.frame_height_bit)+1);var $=!1;x.enable_superres&&($=A.readBool());var K=8;$&&(K=A.readBits(3)+9);var ne=P;P=Math.floor((8*ne+K/2)/K);var ee=ne,se=F;if(A.readBool()){var le=A.readBits(16)+1,ae=A.readBits(16)+1;ee=A.readBits(le)+1,se=A.readBits(ae)+1}return{UpscaledWidth:ne,FrameWidth:P,FrameHeight:F,RenderWidth:ee,RenderHeight:se}},C.getLevelString=function(A,w){return"".concat(A.toString(10).padStart(2,"0")).concat(w===0?"M":"H")},C.getChromaFormat=function(A,w,x){return A?0:w===0&&x===0?3:w===1&&x===0?2:w===1&&x===1?1:Number.NaN},C.getChromaFormatString=function(A,w,x){return A?"4:0:0":w===0&&x===0?"4:4:4":w===1&&x===0?"4:2:2":w===1&&x===1?"4:2:0":"Unknown"},C}(),R,M=function(){function C(A,w){this.TAG="FLVDemuxer",this._config=w,this._onError=null,this._onMediaInfo=null,this._onMetaDataArrived=null,this._onScriptDataArrived=null,this._onTrackMetadata=null,this._onDataAvailable=null,this._dataOffset=A.dataOffset,this._firstParse=!0,this._dispatch=!1,this._hasAudio=A.hasAudioTrack,this._hasVideo=A.hasVideoTrack,this._hasAudioFlagOverrided=!1,this._hasVideoFlagOverrided=!1,this._audioInitialMetadataDispatched=!1,this._videoInitialMetadataDispatched=!1,this._mediaInfo=new c.a,this._mediaInfo.hasAudio=this._hasAudio,this._mediaInfo.hasVideo=this._hasVideo,this._metadata=null,this._audioMetadata=null,this._videoMetadata=null,this._naluLengthSize=4,this._timestampBase=0,this._timescale=1e3,this._duration=0,this._durationOverrided=!1,this._referenceFrameRate={fixed:!0,fps:23.976,fps_num:23976,fps_den:1e3},this._flvSoundRateTable=[5500,11025,22050,44100,48e3],this._mpegSamplingRates=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],this._mpegAudioV10SampleRateTable=[44100,48e3,32e3,0],this._mpegAudioV20SampleRateTable=[22050,24e3,16e3,0],this._mpegAudioV25SampleRateTable=[11025,12e3,8e3,0],this._mpegAudioL1BitRateTable=[0,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1],this._mpegAudioL2BitRateTable=[0,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1],this._mpegAudioL3BitRateTable=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1],this._videoTrack={type:"video",id:1,sequenceNumber:0,samples:[],length:0},this._audioTrack={type:"audio",id:2,sequenceNumber:0,samples:[],length:0},this._littleEndian=function(){var x=new ArrayBuffer(2);return new DataView(x).setInt16(0,256,!0),new Int16Array(x)[0]===256}()}return C.prototype.destroy=function(){this._mediaInfo=null,this._metadata=null,this._audioMetadata=null,this._videoMetadata=null,this._videoTrack=null,this._audioTrack=null,this._onError=null,this._onMediaInfo=null,this._onMetaDataArrived=null,this._onScriptDataArrived=null,this._onTrackMetadata=null,this._onDataAvailable=null},C.probe=function(A){var w=new Uint8Array(A);if(w.byteLength<9)return{needMoreData:!0};var x={match:!1};if(w[0]!==70||w[1]!==76||w[2]!==86||w[3]!==1)return x;var P,F,$=(4&w[4])>>>2!=0,K=(1&w[4])!=0,ne=(P=w)[F=5]<<24|P[F+1]<<16|P[F+2]<<8|P[F+3];return ne<9?x:{match:!0,consumed:ne,dataOffset:ne,hasAudioTrack:$,hasVideoTrack:K}},C.prototype.bindDataSource=function(A){return A.onDataArrival=this.parseChunks.bind(this),this},Object.defineProperty(C.prototype,"onTrackMetadata",{get:function(){return this._onTrackMetadata},set:function(A){this._onTrackMetadata=A},enumerable:!1,configurable:!0}),Object.defineProperty(C.prototype,"onMediaInfo",{get:function(){return this._onMediaInfo},set:function(A){this._onMediaInfo=A},enumerable:!1,configurable:!0}),Object.defineProperty(C.prototype,"onMetaDataArrived",{get:function(){return this._onMetaDataArrived},set:function(A){this._onMetaDataArrived=A},enumerable:!1,configurable:!0}),Object.defineProperty(C.prototype,"onScriptDataArrived",{get:function(){return this._onScriptDataArrived},set:function(A){this._onScriptDataArrived=A},enumerable:!1,configurable:!0}),Object.defineProperty(C.prototype,"onError",{get:function(){return this._onError},set:function(A){this._onError=A},enumerable:!1,configurable:!0}),Object.defineProperty(C.prototype,"onDataAvailable",{get:function(){return this._onDataAvailable},set:function(A){this._onDataAvailable=A},enumerable:!1,configurable:!0}),Object.defineProperty(C.prototype,"timestampBase",{get:function(){return this._timestampBase},set:function(A){this._timestampBase=A},enumerable:!1,configurable:!0}),Object.defineProperty(C.prototype,"overridedDuration",{get:function(){return this._duration},set:function(A){this._durationOverrided=!0,this._duration=A,this._mediaInfo.duration=A},enumerable:!1,configurable:!0}),Object.defineProperty(C.prototype,"overridedHasAudio",{set:function(A){this._hasAudioFlagOverrided=!0,this._hasAudio=A,this._mediaInfo.hasAudio=A},enumerable:!1,configurable:!0}),Object.defineProperty(C.prototype,"overridedHasVideo",{set:function(A){this._hasVideoFlagOverrided=!0,this._hasVideo=A,this._mediaInfo.hasVideo=A},enumerable:!1,configurable:!0}),C.prototype.resetMediaInfo=function(){this._mediaInfo=new c.a},C.prototype._isInitialMetadataDispatched=function(){return this._hasAudio&&this._hasVideo?this._audioInitialMetadataDispatched&&this._videoInitialMetadataDispatched:this._hasAudio&&!this._hasVideo?this._audioInitialMetadataDispatched:!(this._hasAudio||!this._hasVideo)&&this._videoInitialMetadataDispatched},C.prototype.parseChunks=function(A,w){if(!(this._onError&&this._onMediaInfo&&this._onTrackMetadata&&this._onDataAvailable))throw new f.a("Flv: onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified");var x=0,P=this._littleEndian;if(w===0){if(!(A.byteLength>13))return 0;x=C.probe(A).dataOffset}for(this._firstParse&&(this._firstParse=!1,w+x!==this._dataOffset&&o.a.w(this.TAG,"First time parsing but chunk byteStart invalid!"),(F=new DataView(A,x)).getUint32(0,!P)!==0&&o.a.w(this.TAG,"PrevTagSize0 !== 0 !!!"),x+=4);x<A.byteLength;){this._dispatch=!0;var F=new DataView(A,x);if(x+11+4>A.byteLength)break;var $=F.getUint8(0),K=16777215&F.getUint32(0,!P);if(x+11+K+4>A.byteLength)break;if($===8||$===9||$===18){var ne=F.getUint8(4),ee=F.getUint8(5),se=F.getUint8(6)|ee<<8|ne<<16|F.getUint8(7)<<24;16777215&F.getUint32(7,!P)&&o.a.w(this.TAG,"Meet tag which has StreamID != 0!");var le=x+11;switch($){case 8:this._parseAudioData(A,le,K,se);break;case 9:this._parseVideoData(A,le,K,se,w+x);break;case 18:this._parseScriptData(A,le,K)}var ae=F.getUint32(11+K,!P);ae!==11+K&&o.a.w(this.TAG,"Invalid PrevTagSize ".concat(ae)),x+=11+K+4}else o.a.w(this.TAG,"Unsupported tag type ".concat($,", skipped")),x+=11+K+4}return this._isInitialMetadataDispatched()&&this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack),x},C.prototype._parseScriptData=function(A,w,x){var P=m.parseScriptData(A,w,x);if(P.hasOwnProperty("onMetaData")){if(P.onMetaData==null||typeof P.onMetaData!="object")return void o.a.w(this.TAG,"Invalid onMetaData structure!");this._metadata&&o.a.w(this.TAG,"Found another onMetaData tag!"),this._metadata=P;var F=this._metadata.onMetaData;if(this._onMetaDataArrived&&this._onMetaDataArrived(Object.assign({},F)),typeof F.hasAudio=="boolean"&&this._hasAudioFlagOverrided===!1&&(this._hasAudio=F.hasAudio,this._mediaInfo.hasAudio=this._hasAudio),typeof F.hasVideo=="boolean"&&this._hasVideoFlagOverrided===!1&&(this._hasVideo=F.hasVideo,this._mediaInfo.hasVideo=this._hasVideo),typeof F.audiodatarate=="number"&&(this._mediaInfo.audioDataRate=F.audiodatarate),typeof F.videodatarate=="number"&&(this._mediaInfo.videoDataRate=F.videodatarate),typeof F.width=="number"&&(this._mediaInfo.width=F.width),typeof F.height=="number"&&(this._mediaInfo.height=F.height),typeof F.duration=="number"){if(!this._durationOverrided){var $=Math.floor(F.duration*this._timescale);this._duration=$,this._mediaInfo.duration=$}}else this._mediaInfo.duration=0;if(typeof F.framerate=="number"){var K=Math.floor(1e3*F.framerate);if(K>0){var ne=K/1e3;this._referenceFrameRate.fixed=!0,this._referenceFrameRate.fps=ne,this._referenceFrameRate.fps_num=K,this._referenceFrameRate.fps_den=1e3,this._mediaInfo.fps=ne}}if(typeof F.keyframes=="object"){this._mediaInfo.hasKeyframesIndex=!0;var ee=F.keyframes;this._mediaInfo.keyframesIndex=this._parseKeyframesIndex(ee),F.keyframes=null}else this._mediaInfo.hasKeyframesIndex=!1;this._dispatch=!1,this._mediaInfo.metadata=F,o.a.v(this.TAG,"Parsed onMetaData"),this._mediaInfo.isComplete()&&this._onMediaInfo(this._mediaInfo)}Object.keys(P).length>0&&this._onScriptDataArrived&&this._onScriptDataArrived(Object.assign({},P))},C.prototype._parseKeyframesIndex=function(A){for(var w=[],x=[],P=1;P<A.times.length;P++){var F=this._timestampBase+Math.floor(1e3*A.times[P]);w.push(F),x.push(A.filepositions[P])}return{times:w,filepositions:x}},C.prototype._parseAudioData=function(A,w,x,P){if(x<=1)o.a.w(this.TAG,"Flv: Invalid audio packet, missing SoundData payload!");else if(this._hasAudioFlagOverrided!==!0||this._hasAudio!==!1){this._littleEndian;var F=new DataView(A,w,x).getUint8(0),$=F>>>4;if($!==9)if($===2||$===10){var K=0,ne=(12&F)>>>2;if(ne>=0&&ne<=4){K=this._flvSoundRateTable[ne];var ee=1&F,se=this._audioMetadata,le=this._audioTrack;if(se||(this._hasAudio===!1&&this._hasAudioFlagOverrided===!1&&(this._hasAudio=!0,this._mediaInfo.hasAudio=!0),(se=this._audioMetadata={}).type="audio",se.id=le.id,se.timescale=this._timescale,se.duration=this._duration,se.audioSampleRate=K,se.channelCount=ee===0?1:2),$===10){var ae=this._parseAACAudioData(A,w+1,x-1);if(ae==null)return;if(ae.packetType===0){if(se.config){if(O(ae.data.config,se.config))return;o.a.w(this.TAG,"AudioSpecificConfig has been changed, re-generate initialization segment")}var ce=ae.data;se.audioSampleRate=ce.samplingRate,se.channelCount=ce.channelCount,se.codec=ce.codec,se.originalCodec=ce.originalCodec,se.config=ce.config,se.refSampleDuration=1024/se.audioSampleRate*se.timescale,o.a.v(this.TAG,"Parsed AudioSpecificConfig"),this._isInitialMetadataDispatched()?this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack):this._audioInitialMetadataDispatched=!0,this._dispatch=!1,this._onTrackMetadata("audio",se),(Pe=this._mediaInfo).audioCodec=se.originalCodec,Pe.audioSampleRate=se.audioSampleRate,Pe.audioChannelCount=se.channelCount,Pe.hasVideo?Pe.videoCodec!=null&&(Pe.mimeType='video/x-flv; codecs="'+Pe.videoCodec+","+Pe.audioCodec+'"'):Pe.mimeType='video/x-flv; codecs="'+Pe.audioCodec+'"',Pe.isComplete()&&this._onMediaInfo(Pe)}else if(ae.packetType===1){var Te=this._timestampBase+P,Be={unit:ae.data,length:ae.data.byteLength,dts:Te,pts:Te};le.samples.push(Be),le.length+=ae.data.length}else o.a.e(this.TAG,"Flv: Unsupported AAC data type ".concat(ae.packetType))}else if($===2){if(!se.codec){var Pe;if((ce=this._parseMP3AudioData(A,w+1,x-1,!0))==null)return;se.audioSampleRate=ce.samplingRate,se.channelCount=ce.channelCount,se.codec=ce.codec,se.originalCodec=ce.originalCodec,se.refSampleDuration=1152/se.audioSampleRate*se.timescale,o.a.v(this.TAG,"Parsed MPEG Audio Frame Header"),this._audioInitialMetadataDispatched=!0,this._onTrackMetadata("audio",se),(Pe=this._mediaInfo).audioCodec=se.codec,Pe.audioSampleRate=se.audioSampleRate,Pe.audioChannelCount=se.channelCount,Pe.audioDataRate=ce.bitRate,Pe.hasVideo?Pe.videoCodec!=null&&(Pe.mimeType='video/x-flv; codecs="'+Pe.videoCodec+","+Pe.audioCodec+'"'):Pe.mimeType='video/x-flv; codecs="'+Pe.audioCodec+'"',Pe.isComplete()&&this._onMediaInfo(Pe)}var Je=this._parseMP3AudioData(A,w+1,x-1,!1);if(Je==null)return;Te=this._timestampBase+P;var Ye={unit:Je,length:Je.byteLength,dts:Te,pts:Te};le.samples.push(Ye),le.length+=Je.length}}else this._onError(v.a.FORMAT_ERROR,"Flv: Invalid audio sample rate idx: "+ne)}else this._onError(v.a.CODEC_UNSUPPORTED,"Flv: Unsupported audio codec idx: "+$);else{if(x<=5)return void o.a.w(this.TAG,"Flv: Invalid audio packet, missing AudioFourCC in Ehnanced FLV payload!");var Ge=15&F,ut=String.fromCharCode.apply(String,new Uint8Array(A,w,x).slice(1,5));switch(ut){case"Opus":this._parseOpusAudioPacket(A,w+5,x-5,P,Ge);break;case"fLaC":this._parseFlacAudioPacket(A,w+5,x-5,P,Ge);break;default:this._onError(v.a.CODEC_UNSUPPORTED,"Flv: Unsupported audio codec: "+ut)}}}},C.prototype._parseAACAudioData=function(A,w,x){if(!(x<=1)){var P={},F=new Uint8Array(A,w,x);return P.packetType=F[0],F[0]===0?P.data=this._parseAACAudioSpecificConfig(A,w+1,x-1):P.data=F.subarray(1),P}o.a.w(this.TAG,"Flv: Invalid AAC packet, missing AACPacketType or/and Data!")},C.prototype._parseAACAudioSpecificConfig=function(A,w,x){var P,F,$=new Uint8Array(A,w,x),K=null,ne=0,ee=null;if(ne=P=$[0]>>>3,(F=(7&$[0])<<1|$[1]>>>7)<0||F>=this._mpegSamplingRates.length)this._onError(v.a.FORMAT_ERROR,"Flv: AAC invalid sampling frequency index!");else{var se=this._mpegSamplingRates[F],le=(120&$[1])>>>3;if(!(le<0||le>=8)){ne===5&&(ee=(7&$[1])<<1|$[2]>>>7,(124&$[2])>>>2);var ae=self.navigator.userAgent.toLowerCase();return ae.indexOf("firefox")!==-1?F>=6?(ne=5,K=new Array(4),ee=F-3):(ne=2,K=new Array(2),ee=F):ae.indexOf("android")!==-1?(ne=2,K=new Array(2),ee=F):(ne=5,ee=F,K=new Array(4),F>=6?ee=F-3:le===1&&(ne=2,K=new Array(2),ee=F)),K[0]=ne<<3,K[0]|=(15&F)>>>1,K[1]=(15&F)<<7,K[1]|=(15&le)<<3,ne===5&&(K[1]|=(15&ee)>>>1,K[2]=(1&ee)<<7,K[2]|=8,K[3]=0),{config:K,samplingRate:se,channelCount:le,codec:"mp4a.40."+ne,originalCodec:"mp4a.40."+P}}this._onError(v.a.FORMAT_ERROR,"Flv: AAC invalid channel configuration")}},C.prototype._parseMP3AudioData=function(A,w,x,P){if(!(x<4)){this._littleEndian;var F=new Uint8Array(A,w,x),$=null;if(P){if(F[0]!==255)return;var K=F[1]>>>3&3,ne=(6&F[1])>>1,ee=(240&F[2])>>>4,se=(12&F[2])>>>2,le=(F[3]>>>6&3)!==3?2:1,ae=0,ce=0;switch(K){case 0:ae=this._mpegAudioV25SampleRateTable[se];break;case 2:ae=this._mpegAudioV20SampleRateTable[se];break;case 3:ae=this._mpegAudioV10SampleRateTable[se]}switch(ne){case 1:ee<this._mpegAudioL3BitRateTable.length&&(ce=this._mpegAudioL3BitRateTable[ee]);break;case 2:ee<this._mpegAudioL2BitRateTable.length&&(ce=this._mpegAudioL2BitRateTable[ee]);break;case 3:ee<this._mpegAudioL1BitRateTable.length&&(ce=this._mpegAudioL1BitRateTable[ee])}$={bitRate:ce,samplingRate:ae,channelCount:le,codec:"mp3",originalCodec:"mp3"}}else $=F;return $}o.a.w(this.TAG,"Flv: Invalid MP3 packet, header missing!")},C.prototype._parseOpusAudioPacket=function(A,w,x,P,F){if(F===0)this._parseOpusSequenceHeader(A,w,x);else if(F===1)this._parseOpusAudioData(A,w,x,P);else if(F!==2)return void this._onError(v.a.FORMAT_ERROR,"Flv: Invalid video packet type ".concat(F))},C.prototype._parseOpusSequenceHeader=function(A,w,x){if(x<=16)o.a.w(this.TAG,"Flv: Invalid OpusSequenceHeader, lack of data!");else{var P=this._audioMetadata,F=this._audioTrack;P||(this._hasAudio===!1&&this._hasAudioFlagOverrided===!1&&(this._hasAudio=!0,this._mediaInfo.hasAudio=!0),(P=this._audioMetadata={}).type="audio",P.id=F.id,P.timescale=this._timescale,P.duration=this._duration);var $=new DataView(A,w,x);$.setUint8(8,0);var K=$.getUint8(9);$.setUint16(10,$.getUint16(10,!0),!1);var ne=$.getUint32(12,!0);$.setUint32(12,$.getUint32(12,!0),!1);var ee={config:new Uint8Array(A,w+8,x-8),channelCount:K,samplingFrequence:ne,codec:"opus",originalCodec:"opus"};if(P.config){if(O(ee.config,P.config))return;o.a.w(this.TAG,"OpusSequenceHeader has been changed, re-generate initialization segment")}P.audioSampleRate=ee.samplingFrequence,P.channelCount=ee.channelCount,P.codec=ee.codec,P.originalCodec=ee.originalCodec,P.config=ee.config,P.refSampleDuration=20,o.a.v(this.TAG,"Parsed OpusSequenceHeader"),this._isInitialMetadataDispatched()?this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack):this._audioInitialMetadataDispatched=!0,this._dispatch=!1,this._onTrackMetadata("audio",P);var se=this._mediaInfo;se.audioCodec=P.originalCodec,se.audioSampleRate=P.audioSampleRate,se.audioChannelCount=P.channelCount,se.hasVideo?se.videoCodec!=null&&(se.mimeType='video/x-flv; codecs="'+se.videoCodec+","+se.audioCodec+'"'):se.mimeType='video/x-flv; codecs="'+se.audioCodec+'"',se.isComplete()&&this._onMediaInfo(se)}},C.prototype._parseOpusAudioData=function(A,w,x,P){var F=this._audioTrack,$=new Uint8Array(A,w,x),K=this._timestampBase+P,ne={unit:$,length:$.byteLength,dts:K,pts:K};F.samples.push(ne),F.length+=$.length},C.prototype._parseFlacAudioPacket=function(A,w,x,P,F){if(F===0)this._parseFlacSequenceHeader(A,w,x);else if(F===1)this._parseFlacAudioData(A,w,x,P);else if(F!==2)return void this._onError(v.a.FORMAT_ERROR,"Flv: Invalid Flac audio packet type ".concat(F))},C.prototype._parseFlacSequenceHeader=function(A,w,x){var P=this._audioMetadata,F=this._audioTrack;P||(this._hasAudio===!1&&this._hasAudioFlagOverrided===!1&&(this._hasAudio=!0,this._mediaInfo.hasAudio=!0),(P=this._audioMetadata={}).type="audio",P.id=F.id,P.timescale=this._timescale,P.duration=this._duration);var $=new Uint8Array(A,w+4,x-4),K=new g($),ne=K.readBits(16),ee=K.readBits(16),se=ee===ne?ee:null;K.readBits(24),K.readBits(24);var le=K.readBits(20),ae=K.readBits(3)+1,ce=K.readBits(5)+1;K.destroy();var Te=new Uint8Array($.byteLength+4);Te.set($,4),Te[0]=128,Te[1]=$.byteLength>>>16&255,Te[2]=$.byteLength>>>8&255,Te[3]=$.byteLength>>>0&255;var Be={config:Te,channelCount:ae,samplingFrequence:le,sampleSize:ce,codec:"flac",originalCodec:"flac"};if(P.config){if(O(Be.config,P.config))return;o.a.w(this.TAG,"FlacSequenceHeader has been changed, re-generate initialization segment")}P.audioSampleRate=Be.samplingFrequence,P.channelCount=Be.channelCount,P.sampleSize=Be.sampleSize,P.codec=Be.codec,P.originalCodec=Be.originalCodec,P.config=Be.config,P.refSampleDuration=se!=null?1e3*se/Be.samplingFrequence:null,o.a.v(this.TAG,"Parsed FlacSequenceHeader"),this._isInitialMetadataDispatched()?this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack):this._audioInitialMetadataDispatched=!0,this._dispatch=!1,this._onTrackMetadata("audio",P);var Pe=this._mediaInfo;Pe.audioCodec=P.originalCodec,Pe.audioSampleRate=P.audioSampleRate,Pe.audioChannelCount=P.channelCount,Pe.hasVideo?Pe.videoCodec!=null&&(Pe.mimeType='video/x-flv; codecs="'+Pe.videoCodec+","+Pe.audioCodec+'"'):Pe.mimeType='video/x-flv; codecs="'+Pe.audioCodec+'"',Pe.isComplete()&&this._onMediaInfo(Pe)},C.prototype._parseFlacAudioData=function(A,w,x,P){var F=this._audioTrack,$=new Uint8Array(A,w,x),K=this._timestampBase+P,ne={unit:$,length:$.byteLength,dts:K,pts:K};F.samples.push(ne),F.length+=$.length},C.prototype._parseVideoData=function(A,w,x,P,F){if(x<=1)o.a.w(this.TAG,"Flv: Invalid video packet, missing VideoData payload!");else if(this._hasVideoFlagOverrided!==!0||this._hasVideo!==!1){var $=new Uint8Array(A,w,x)[0],K=(112&$)>>>4;if(128&$){var ne=15&$,ee=String.fromCharCode.apply(String,new Uint8Array(A,w,x).slice(1,5));if(ee==="hvc1")this._parseEnhancedHEVCVideoPacket(A,w+5,x-5,P,F,K,ne);else{if(ee!=="av01")return void this._onError(v.a.CODEC_UNSUPPORTED,"Flv: Unsupported codec in video frame: ".concat(ee));this._parseEnhancedAV1VideoPacket(A,w+5,x-5,P,F,K,ne)}}else{var se=15&$;if(se===7)this._parseAVCVideoPacket(A,w+1,x-1,P,F,K);else{if(se!==12)return void this._onError(v.a.CODEC_UNSUPPORTED,"Flv: Unsupported codec in video frame: ".concat(se));this._parseHEVCVideoPacket(A,w+1,x-1,P,F,K)}}}},C.prototype._parseAVCVideoPacket=function(A,w,x,P,F,$){if(x<4)o.a.w(this.TAG,"Flv: Invalid AVC packet, missing AVCPacketType or/and CompositionTime");else{var K=this._littleEndian,ne=new DataView(A,w,x),ee=ne.getUint8(0),se=(16777215&ne.getUint32(0,!K))<<8>>8;if(ee===0)this._parseAVCDecoderConfigurationRecord(A,w+4,x-4);else if(ee===1)this._parseAVCVideoData(A,w+4,x-4,P,F,$,se);else if(ee!==2)return void this._onError(v.a.FORMAT_ERROR,"Flv: Invalid video packet type ".concat(ee))}},C.prototype._parseHEVCVideoPacket=function(A,w,x,P,F,$){if(x<4)o.a.w(this.TAG,"Flv: Invalid HEVC packet, missing HEVCPacketType or/and CompositionTime");else{var K=this._littleEndian,ne=new DataView(A,w,x),ee=ne.getUint8(0),se=(16777215&ne.getUint32(0,!K))<<8>>8;if(ee===0)this._parseHEVCDecoderConfigurationRecord(A,w+4,x-4);else if(ee===1)this._parseHEVCVideoData(A,w+4,x-4,P,F,$,se);else if(ee!==2)return void this._onError(v.a.FORMAT_ERROR,"Flv: Invalid video packet type ".concat(ee))}},C.prototype._parseEnhancedHEVCVideoPacket=function(A,w,x,P,F,$,K){var ne=this._littleEndian,ee=new DataView(A,w,x);if(K===0)this._parseHEVCDecoderConfigurationRecord(A,w,x);else if(K===1){var se=(4294967040&ee.getUint32(0,!ne))>>8;this._parseHEVCVideoData(A,w+3,x-3,P,F,$,se)}else if(K===3)this._parseHEVCVideoData(A,w,x,P,F,$,0);else if(K!==2)return void this._onError(v.a.FORMAT_ERROR,"Flv: Invalid video packet type ".concat(K))},C.prototype._parseEnhancedAV1VideoPacket=function(A,w,x,P,F,$,K){if(this._littleEndian,K===0)this._parseAV1CodecConfigurationRecord(A,w,x);else if(K===1)this._parseAV1VideoData(A,w,x,P,F,$,0);else{if(K===5)return void this._onError(v.a.FORMAT_ERROR,"Flv: Not Supported MP2T AV1 video packet type ".concat(K));if(K!==2)return void this._onError(v.a.FORMAT_ERROR,"Flv: Invalid video packet type ".concat(K))}},C.prototype._parseAVCDecoderConfigurationRecord=function(A,w,x){if(x<7)o.a.w(this.TAG,"Flv: Invalid AVCDecoderConfigurationRecord, lack of data!");else{var P=this._videoMetadata,F=this._videoTrack,$=this._littleEndian,K=new DataView(A,w,x);if(P){if(P.avcc!==void 0){var ne=new Uint8Array(A,w,x);if(O(ne,P.avcc))return;o.a.w(this.TAG,"AVCDecoderConfigurationRecord has been changed, re-generate initialization segment")}}else this._hasVideo===!1&&this._hasVideoFlagOverrided===!1&&(this._hasVideo=!0,this._mediaInfo.hasVideo=!0),(P=this._videoMetadata={}).type="video",P.id=F.id,P.timescale=this._timescale,P.duration=this._duration;var ee=K.getUint8(0),se=K.getUint8(1);if(K.getUint8(2),K.getUint8(3),ee===1&&se!==0)if(this._naluLengthSize=1+(3&K.getUint8(4)),this._naluLengthSize===3||this._naluLengthSize===4){var le=31&K.getUint8(5);if(le!==0){le>1&&o.a.w(this.TAG,"Flv: Strange AVCDecoderConfigurationRecord: SPS Count = ".concat(le));for(var ae=6,ce=0;ce<le;ce++){var Te=K.getUint16(ae,!$);if(ae+=2,Te!==0){var Be=new Uint8Array(A,w+ae,Te);ae+=Te;var Pe=b.parseSPS(Be);if(ce===0){P.codecWidth=Pe.codec_size.width,P.codecHeight=Pe.codec_size.height,P.presentWidth=Pe.present_size.width,P.presentHeight=Pe.present_size.height,P.profile=Pe.profile_string,P.level=Pe.level_string,P.bitDepth=Pe.bit_depth,P.chromaFormat=Pe.chroma_format,P.sarRatio=Pe.sar_ratio,P.frameRate=Pe.frame_rate,Pe.frame_rate.fixed!==!1&&Pe.frame_rate.fps_num!==0&&Pe.frame_rate.fps_den!==0||(P.frameRate=this._referenceFrameRate);var Je=P.frameRate.fps_den,Ye=P.frameRate.fps_num;P.refSampleDuration=P.timescale*(Je/Ye);for(var Ge=Be.subarray(1,4),ut="avc1.",bt=0;bt<3;bt++){var Xe=Ge[bt].toString(16);Xe.length<2&&(Xe="0"+Xe),ut+=Xe}P.codec=ut;var Ke=this._mediaInfo;Ke.width=P.codecWidth,Ke.height=P.codecHeight,Ke.fps=P.frameRate.fps,Ke.profile=P.profile,Ke.level=P.level,Ke.refFrames=Pe.ref_frames,Ke.chromaFormat=Pe.chroma_format_string,Ke.sarNum=P.sarRatio.width,Ke.sarDen=P.sarRatio.height,Ke.videoCodec=ut,Ke.hasAudio?Ke.audioCodec!=null&&(Ke.mimeType='video/x-flv; codecs="'+Ke.videoCodec+","+Ke.audioCodec+'"'):Ke.mimeType='video/x-flv; codecs="'+Ke.videoCodec+'"',Ke.isComplete()&&this._onMediaInfo(Ke)}}}var Rt=K.getUint8(ae);if(Rt!==0){for(Rt>1&&o.a.w(this.TAG,"Flv: Strange AVCDecoderConfigurationRecord: PPS Count = ".concat(Rt)),ae++,ce=0;ce<Rt;ce++)Te=K.getUint16(ae,!$),ae+=2,Te!==0&&(ae+=Te);P.avcc=new Uint8Array(x),P.avcc.set(new Uint8Array(A,w,x),0),o.a.v(this.TAG,"Parsed AVCDecoderConfigurationRecord"),this._isInitialMetadataDispatched()?this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack):this._videoInitialMetadataDispatched=!0,this._dispatch=!1,this._onTrackMetadata("video",P)}else this._onError(v.a.FORMAT_ERROR,"Flv: Invalid AVCDecoderConfigurationRecord: No PPS")}else this._onError(v.a.FORMAT_ERROR,"Flv: Invalid AVCDecoderConfigurationRecord: No SPS")}else this._onError(v.a.FORMAT_ERROR,"Flv: Strange NaluLengthSizeMinusOne: ".concat(this._naluLengthSize-1));else this._onError(v.a.FORMAT_ERROR,"Flv: Invalid AVCDecoderConfigurationRecord")}},C.prototype._parseHEVCDecoderConfigurationRecord=function(A,w,x){if(x<22)o.a.w(this.TAG,"Flv: Invalid HEVCDecoderConfigurationRecord, lack of data!");else{var P=this._videoMetadata,F=this._videoTrack,$=this._littleEndian,K=new DataView(A,w,x);if(P){if(P.hvcc!==void 0){var ne=new Uint8Array(A,w,x);if(O(ne,P.hvcc))return;o.a.w(this.TAG,"HEVCDecoderConfigurationRecord has been changed, re-generate initialization segment")}}else this._hasVideo===!1&&this._hasVideoFlagOverrided===!1&&(this._hasVideo=!0,this._mediaInfo.hasVideo=!0),(P=this._videoMetadata={}).type="video",P.id=F.id,P.timescale=this._timescale,P.duration=this._duration;var ee=K.getUint8(0),se=31&K.getUint8(1);if(ee!==0&&ee!==1||se===0)this._onError(v.a.FORMAT_ERROR,"Flv: Invalid HEVCDecoderConfigurationRecord");else if(this._naluLengthSize=1+(3&K.getUint8(21)),this._naluLengthSize===3||this._naluLengthSize===4){for(var le=K.getUint8(22),ae=0,ce=23;ae<le;ae++){var Te=63&K.getUint8(ce+0),Be=K.getUint16(ce+1,!$);ce+=3;for(var Pe=0;Pe<Be;Pe++){var Je=K.getUint16(ce+0,!$);if(Pe===0)if(Te===33){ce+=2;var Ye=new Uint8Array(A,w+ce,Je),Ge=S.parseSPS(Ye);P.codecWidth=Ge.codec_size.width,P.codecHeight=Ge.codec_size.height,P.presentWidth=Ge.present_size.width,P.presentHeight=Ge.present_size.height,P.profile=Ge.profile_string,P.level=Ge.level_string,P.bitDepth=Ge.bit_depth,P.chromaFormat=Ge.chroma_format,P.sarRatio=Ge.sar_ratio,P.frameRate=Ge.frame_rate,Ge.frame_rate.fixed!==!1&&Ge.frame_rate.fps_num!==0&&Ge.frame_rate.fps_den!==0||(P.frameRate=this._referenceFrameRate);var ut=P.frameRate.fps_den,bt=P.frameRate.fps_num;P.refSampleDuration=P.timescale*(ut/bt),P.codec=Ge.codec_mimetype;var Xe=this._mediaInfo;Xe.width=P.codecWidth,Xe.height=P.codecHeight,Xe.fps=P.frameRate.fps,Xe.profile=P.profile,Xe.level=P.level,Xe.refFrames=Ge.ref_frames,Xe.chromaFormat=Ge.chroma_format_string,Xe.sarNum=P.sarRatio.width,Xe.sarDen=P.sarRatio.height,Xe.videoCodec=Ge.codec_mimetype,Xe.hasAudio?Xe.audioCodec!=null&&(Xe.mimeType='video/x-flv; codecs="'+Xe.videoCodec+","+Xe.audioCodec+'"'):Xe.mimeType='video/x-flv; codecs="'+Xe.videoCodec+'"',Xe.isComplete()&&this._onMediaInfo(Xe),ce+=Je}else ce+=2+Je;else ce+=2+Je}}P.hvcc=new Uint8Array(x),P.hvcc.set(new Uint8Array(A,w,x),0),o.a.v(this.TAG,"Parsed HEVCDecoderConfigurationRecord"),this._isInitialMetadataDispatched()?this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack):this._videoInitialMetadataDispatched=!0,this._dispatch=!1,this._onTrackMetadata("video",P)}else this._onError(v.a.FORMAT_ERROR,"Flv: Strange NaluLengthSizeMinusOne: ".concat(this._naluLengthSize-1))}},C.prototype._parseAV1CodecConfigurationRecord=function(A,w,x){if(x<4)o.a.w(this.TAG,"Flv: Invalid AV1CodecConfigurationRecord, lack of data!");else{var P=this._videoMetadata,F=this._videoTrack,$=(this._littleEndian,new DataView(A,w,x));P?P.av1c!==void 0&&o.a.w(this.TAG,"Found another AV1CodecConfigurationRecord!"):(this._hasVideo===!1&&this._hasVideoFlagOverrided===!1&&(this._hasVideo=!0,this._mediaInfo.hasVideo=!0),(P=this._videoMetadata={}).type="video",P.id=F.id,P.timescale=this._timescale,P.duration=this._duration);var K=127&$.getUint8(0);if($.getUint8(1),$.getUint8(1),$.getUint8(2),K===1){var ne=I.parseOBUs(new Uint8Array(A,w+4,x-4));if(ne!=null){P.profile=ne.profile_string,P.level=ne.level_string,P.bitDepth=ne.bit_depth,P.chromaFormat=ne.chroma_format,P.frameRate=ne.frame_rate,ne.frame_rate.fixed!==!1&&ne.frame_rate.fps_num!==0&&ne.frame_rate.fps_den!==0||(P.frameRate=this._referenceFrameRate);var ee=P.frameRate.fps_den,se=P.frameRate.fps_num;P.refSampleDuration=P.timescale*(ee/se),P.codec=ne.codec_mimetype,P.extra=ne;var le=this._mediaInfo;le.fps=P.frameRate.fps,le.profile=P.profile,le.level=P.level,le.refFrames=ne.ref_frames,le.chromaFormat=ne.chroma_format_string,le.videoCodec=ne.codec_mimetype,le.hasAudio?le.audioCodec!=null&&(le.mimeType='video/x-flv; codecs="'+le.videoCodec+","+le.audioCodec+'"'):le.mimeType='video/x-flv; codecs="'+le.videoCodec+'"',le.isComplete()&&this._onMediaInfo(le),P.av1c=new Uint8Array(x),P.av1c.set(new Uint8Array(A,w,x),0),o.a.v(this.TAG,"Preparing AV1CodecConfigurationRecord")}else this._onError(v.a.FORMAT_ERROR,"Flv: Invalid AV1CodecConfigurationRecord")}else this._onError(v.a.FORMAT_ERROR,"Flv: Invalid AV1CodecConfigurationRecord")}},C.prototype._parseAVCVideoData=function(A,w,x,P,F,$,K){for(var ne=this._littleEndian,ee=new DataView(A,w,x),se=[],le=0,ae=0,ce=this._naluLengthSize,Te=this._timestampBase+P,Be=$===1;ae<x;){if(ae+4>=x){o.a.w(this.TAG,"Malformed Nalu near timestamp ".concat(Te,", offset = ").concat(ae,", dataSize = ").concat(x));break}var Pe=ee.getUint32(ae,!ne);if(ce===3&&(Pe>>>=8),Pe>x-ce)return void o.a.w(this.TAG,"Malformed Nalus near timestamp ".concat(Te,", NaluSize > DataSize!"));var Je=31&ee.getUint8(ae+ce);Je===5&&(Be=!0);var Ye=new Uint8Array(A,w+ae,ce+Pe),Ge={type:Je,data:Ye};se.push(Ge),le+=Ye.byteLength,ae+=ce+Pe}if(se.length){var ut=this._videoTrack,bt={units:se,length:le,isKeyframe:Be,dts:Te,cts:K,pts:Te+K};Be&&(bt.fileposition=F),ut.samples.push(bt),ut.length+=le}},C.prototype._parseHEVCVideoData=function(A,w,x,P,F,$,K){for(var ne=this._littleEndian,ee=new DataView(A,w,x),se=[],le=0,ae=0,ce=this._naluLengthSize,Te=this._timestampBase+P,Be=$===1;ae<x;){if(ae+4>=x){o.a.w(this.TAG,"Malformed Nalu near timestamp ".concat(Te,", offset = ").concat(ae,", dataSize = ").concat(x));break}var Pe=ee.getUint32(ae,!ne);if(ce===3&&(Pe>>>=8),Pe>x-ce)return void o.a.w(this.TAG,"Malformed Nalus near timestamp ".concat(Te,", NaluSize > DataSize!"));var Je=ee.getUint8(ae+ce)>>1&63;Je!==19&&Je!==20&&Je!==21||(Be=!0);var Ye=new Uint8Array(A,w+ae,ce+Pe),Ge={type:Je,data:Ye};se.push(Ge),le+=Ye.byteLength,ae+=ce+Pe}if(se.length){var ut=this._videoTrack,bt={units:se,length:le,isKeyframe:Be,dts:Te,cts:K,pts:Te+K};Be&&(bt.fileposition=F),ut.samples.push(bt),ut.length+=le}},C.prototype._parseAV1VideoData=function(A,w,x,P,F,$,K){this._littleEndian;var ne,ee=[],se=this._timestampBase+P,le=$===1;if(le){var ae=this._videoMetadata,ce=I.parseOBUs(new Uint8Array(A,w,x),ae.extra);if(ce==null)return void this._onError(v.a.FORMAT_ERROR,"Flv: Invalid AV1 VideoData");console.log(ce),ae.codecWidth=ce.codec_size.width,ae.codecHeight=ce.codec_size.height,ae.presentWidth=ce.present_size.width,ae.presentHeight=ce.present_size.height,ae.sarRatio=ce.sar_ratio;var Te=this._mediaInfo;Te.width=ae.codecWidth,Te.height=ae.codecHeight,Te.sarNum=ae.sarRatio.width,Te.sarDen=ae.sarRatio.height,o.a.v(this.TAG,"Parsed AV1DecoderConfigurationRecord"),this._isInitialMetadataDispatched()?this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack):this._videoInitialMetadataDispatched=!0,this._dispatch=!1,this._onTrackMetadata("video",ae)}if(ne=x,ee.push({unitType:0,data:new Uint8Array(A,w+0,x)}),ee.length){var Be=this._videoTrack,Pe={units:ee,length:ne,isKeyframe:le,dts:se,cts:K,pts:se+K};le&&(Pe.fileposition=F),Be.samples.push(Pe),Be.length+=ne}},C}(),z=function(){function C(){}return C.prototype.destroy=function(){this.onError=null,this.onMediaInfo=null,this.onMetaDataArrived=null,this.onTrackMetadata=null,this.onDataAvailable=null,this.onTimedID3Metadata=null,this.onSynchronousKLVMetadata=null,this.onAsynchronousKLVMetadata=null,this.onSMPTE2038Metadata=null,this.onSCTE35Metadata=null,this.onPESPrivateData=null,this.onPESPrivateDataDescriptor=null},C}(),Z=function(){this.program_pmt_pid={}};(function(C){C[C.kMPEG1Audio=3]="kMPEG1Audio",C[C.kMPEG2Audio=4]="kMPEG2Audio",C[C.kPESPrivateData=6]="kPESPrivateData",C[C.kADTSAAC=15]="kADTSAAC",C[C.kLOASAAC=17]="kLOASAAC",C[C.kAC3=129]="kAC3",C[C.kEAC3=135]="kEAC3",C[C.kMetadata=21]="kMetadata",C[C.kSCTE35=134]="kSCTE35",C[C.kH264=27]="kH264",C[C.kH265=36]="kH265"})(R||(R={}));var W,re=function(){this.pid_stream_type={},this.common_pids={h264:void 0,h265:void 0,av1:void 0,adts_aac:void 0,loas_aac:void 0,opus:void 0,ac3:void 0,eac3:void 0,mp3:void 0},this.pes_private_data_pids={},this.timed_id3_pids={},this.synchronous_klv_pids={},this.asynchronous_klv_pids={},this.scte_35_pids={},this.smpte2038_pids={}},X=function(){},oe=function(){},Q=function(){this.slices=[],this.total_length=0,this.expected_length=0,this.file_position=0};(function(C){C[C.kUnspecified=0]="kUnspecified",C[C.kSliceNonIDR=1]="kSliceNonIDR",C[C.kSliceDPA=2]="kSliceDPA",C[C.kSliceDPB=3]="kSliceDPB",C[C.kSliceDPC=4]="kSliceDPC",C[C.kSliceIDR=5]="kSliceIDR",C[C.kSliceSEI=6]="kSliceSEI",C[C.kSliceSPS=7]="kSliceSPS",C[C.kSlicePPS=8]="kSlicePPS",C[C.kSliceAUD=9]="kSliceAUD",C[C.kEndOfSequence=10]="kEndOfSequence",C[C.kEndOfStream=11]="kEndOfStream",C[C.kFiller=12]="kFiller",C[C.kSPSExt=13]="kSPSExt",C[C.kReserved0=14]="kReserved0"})(W||(W={}));var G,H,Y=function(){},ie=function(C){var A=C.data.byteLength;this.type=C.type,this.data=new Uint8Array(4+A),new DataView(this.data.buffer).setUint32(0,A),this.data.set(C.data,4)},Ce=function(){function C(A){this.TAG="H264AnnexBParser",this.current_startcode_offset_=0,this.eof_flag_=!1,this.data_=A,this.current_startcode_offset_=this.findNextStartCodeOffset(0),this.eof_flag_&&o.a.e(this.TAG,"Could not find H264 startcode until payload end!")}return C.prototype.findNextStartCodeOffset=function(A){for(var w=A,x=this.data_;;){if(w+3>=x.byteLength)return this.eof_flag_=!0,x.byteLength;var P=x[w+0]<<24|x[w+1]<<16|x[w+2]<<8|x[w+3],F=x[w+0]<<16|x[w+1]<<8|x[w+2];if(P===1||F===1)return w;w++}},C.prototype.readNextNaluPayload=function(){for(var A=this.data_,w=null;w==null&&!this.eof_flag_;){var x=this.current_startcode_offset_,P=31&A[x+=(A[x]<<24|A[x+1]<<16|A[x+2]<<8|A[x+3])===1?4:3],F=(128&A[x])>>>7,$=this.findNextStartCodeOffset(x);if(this.current_startcode_offset_=$,!(P>=W.kReserved0)&&F===0){var K=A.subarray(x,$);(w=new Y).type=P,w.data=K}}return w},C}(),Le=function(){function C(A,w,x){var P=8+A.byteLength+1+2+w.byteLength,F=!1;A[3]!==66&&A[3]!==77&&A[3]!==88&&(F=!0,P+=4);var $=this.data=new Uint8Array(P);$[0]=1,$[1]=A[1],$[2]=A[2],$[3]=A[3],$[4]=255,$[5]=225;var K=A.byteLength;$[6]=K>>>8,$[7]=255&K;var ne=8;$.set(A,8),$[ne+=K]=1;var ee=w.byteLength;$[ne+1]=ee>>>8,$[ne+2]=255&ee,$.set(w,ne+3),ne+=3+ee,F&&($[ne]=252|x.chroma_format_idc,$[ne+1]=248|x.bit_depth_luma-8,$[ne+2]=248|x.bit_depth_chroma-8,$[ne+3]=0,ne+=4)}return C.prototype.getData=function(){return this.data},C}();(function(C){C[C.kNull=0]="kNull",C[C.kAACMain=1]="kAACMain",C[C.kAAC_LC=2]="kAAC_LC",C[C.kAAC_SSR=3]="kAAC_SSR",C[C.kAAC_LTP=4]="kAAC_LTP",C[C.kAAC_SBR=5]="kAAC_SBR",C[C.kAAC_Scalable=6]="kAAC_Scalable",C[C.kLayer1=32]="kLayer1",C[C.kLayer2=33]="kLayer2",C[C.kLayer3=34]="kLayer3"})(G||(G={})),function(C){C[C.k96000Hz=0]="k96000Hz",C[C.k88200Hz=1]="k88200Hz",C[C.k64000Hz=2]="k64000Hz",C[C.k48000Hz=3]="k48000Hz",C[C.k44100Hz=4]="k44100Hz",C[C.k32000Hz=5]="k32000Hz",C[C.k24000Hz=6]="k24000Hz",C[C.k22050Hz=7]="k22050Hz",C[C.k16000Hz=8]="k16000Hz",C[C.k12000Hz=9]="k12000Hz",C[C.k11025Hz=10]="k11025Hz",C[C.k8000Hz=11]="k8000Hz",C[C.k7350Hz=12]="k7350Hz"}(H||(H={}));var ke,Ne,ye=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Ie=(ke=function(C,A){return(ke=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(w,x){w.__proto__=x}||function(w,x){for(var P in x)Object.prototype.hasOwnProperty.call(x,P)&&(w[P]=x[P])})(C,A)},function(C,A){if(typeof A!="function"&&A!==null)throw new TypeError("Class extends value "+String(A)+" is not a constructor or null");function w(){this.constructor=C}ke(C,A),C.prototype=A===null?Object.create(A):(w.prototype=A.prototype,new w)}),Ae=function(){},Ee=function(C){function A(){return C!==null&&C.apply(this,arguments)||this}return Ie(A,C),A}(Ae),je=function(){function C(A){this.TAG="AACADTSParser",this.data_=A,this.current_syncword_offset_=this.findNextSyncwordOffset(0),this.eof_flag_&&o.a.e(this.TAG,"Could not found ADTS syncword until payload end")}return C.prototype.findNextSyncwordOffset=function(A){for(var w=A,x=this.data_;;){if(w+7>=x.byteLength)return this.eof_flag_=!0,x.byteLength;if((x[w+0]<<8|x[w+1])>>>4===4095)return w;w++}},C.prototype.readNextAACFrame=function(){for(var A=this.data_,w=null;w==null&&!this.eof_flag_;){var x=this.current_syncword_offset_,P=(8&A[x+1])>>>3,F=(6&A[x+1])>>>1,$=1&A[x+1],K=(192&A[x+2])>>>6,ne=(60&A[x+2])>>>2,ee=(1&A[x+2])<<2|(192&A[x+3])>>>6,se=(3&A[x+3])<<11|A[x+4]<<3|(224&A[x+5])>>>5;if(A[x+6],x+se>this.data_.byteLength){this.eof_flag_=!0,this.has_last_incomplete_data=!0;break}var le=$===1?7:9,ae=se-le;x+=le;var ce=this.findNextSyncwordOffset(x+ae);if(this.current_syncword_offset_=ce,(P===0||P===1)&&F===0){var Te=A.subarray(x,x+ae);(w=new Ae).audio_object_type=K+1,w.sampling_freq_index=ne,w.sampling_frequency=ye[ne],w.channel_config=ee,w.data=Te}}return w},C.prototype.hasIncompleteData=function(){return this.has_last_incomplete_data},C.prototype.getIncompleteData=function(){return this.has_last_incomplete_data?this.data_.subarray(this.current_syncword_offset_):null},C}(),Me=function(){function C(A){this.TAG="AACLOASParser",this.data_=A,this.current_syncword_offset_=this.findNextSyncwordOffset(0),this.eof_flag_&&o.a.e(this.TAG,"Could not found LOAS syncword until payload end")}return C.prototype.findNextSyncwordOffset=function(A){for(var w=A,x=this.data_;;){if(w+1>=x.byteLength)return this.eof_flag_=!0,x.byteLength;if((x[w+0]<<3|x[w+1]>>>5)===695)return w;w++}},C.prototype.getLATMValue=function(A){for(var w=A.readBits(2),x=0,P=0;P<=w;P++)x<<=8,x|=A.readByte();return x},C.prototype.readNextAACFrame=function(A){for(var w=this.data_,x=null;x==null&&!this.eof_flag_;){var P=this.current_syncword_offset_,F=(31&w[P+1])<<8|w[P+2];if(P+3+F>=this.data_.byteLength){this.eof_flag_=!0,this.has_last_incomplete_data=!0;break}var $=new g(w.subarray(P+3,P+3+F)),K=null;if($.readBool()){if(A==null){o.a.w(this.TAG,"StreamMuxConfig Missing"),this.current_syncword_offset_=this.findNextSyncwordOffset(P+3+F),$.destroy();continue}K=A}else{var ne=$.readBool();if(ne&&$.readBool()){o.a.e(this.TAG,"audioMuxVersionA is Not Supported"),$.destroy();break}if(ne&&this.getLATMValue($),!$.readBool()){o.a.e(this.TAG,"allStreamsSameTimeFraming zero is Not Supported"),$.destroy();break}if($.readBits(6)!==0){o.a.e(this.TAG,"more than 2 numSubFrames Not Supported"),$.destroy();break}if($.readBits(4)!==0){o.a.e(this.TAG,"more than 2 numProgram Not Supported"),$.destroy();break}if($.readBits(3)!==0){o.a.e(this.TAG,"more than 2 numLayer Not Supported"),$.destroy();break}var ee=ne?this.getLATMValue($):0,se=$.readBits(5);ee-=5;var le=$.readBits(4);ee-=4;var ae=$.readBits(4);ee-=4,$.readBits(3),(ee-=3)>0&&$.readBits(ee);var ce=$.readBits(3);if(ce!==0){o.a.e(this.TAG,"frameLengthType = ".concat(ce,". Only frameLengthType = 0 Supported")),$.destroy();break}$.readByte();var Te=$.readBool();if(Te)if(ne)this.getLATMValue($);else{for(var Be=0;;){Be<<=8;var Pe=$.readBool();if(Be+=$.readByte(),!Pe)break}console.log(Be)}$.readBool()&&$.readByte(),(K=new Ee).audio_object_type=se,K.sampling_freq_index=le,K.sampling_frequency=ye[K.sampling_freq_index],K.channel_config=ae,K.other_data_present=Te}for(var Je=0;;){var Ye=$.readByte();if(Je+=Ye,Ye!==255)break}for(var Ge=new Uint8Array(Je),ut=0;ut<Je;ut++)Ge[ut]=$.readByte();(x=new Ee).audio_object_type=K.audio_object_type,x.sampling_freq_index=K.sampling_freq_index,x.sampling_frequency=ye[K.sampling_freq_index],x.channel_config=K.channel_config,x.other_data_present=K.other_data_present,x.data=Ge,this.current_syncword_offset_=this.findNextSyncwordOffset(P+3+F)}return x},C.prototype.hasIncompleteData=function(){return this.has_last_incomplete_data},C.prototype.getIncompleteData=function(){return this.has_last_incomplete_data?this.data_.subarray(this.current_syncword_offset_):null},C}(),Pt=function(C){var A=null,w=C.audio_object_type,x=C.audio_object_type,P=C.sampling_freq_index,F=C.channel_config,$=0,K=navigator.userAgent.toLowerCase();K.indexOf("firefox")!==-1?P>=6?(x=5,A=new Array(4),$=P-3):(x=2,A=new Array(2),$=P):K.indexOf("android")!==-1?(x=2,A=new Array(2),$=P):(x=5,$=P,A=new Array(4),P>=6?$=P-3:F===1&&(x=2,A=new Array(2),$=P)),A[0]=x<<3,A[0]|=(15&P)>>>1,A[1]=(15&P)<<7,A[1]|=(15&F)<<3,x===5&&(A[1]|=(15&$)>>>1,A[2]=(1&$)<<7,A[2]|=8,A[3]=0),this.config=A,this.sampling_rate=ye[P],this.channel_count=F,this.codec_mimetype="mp4a.40."+x,this.original_codec_mimetype="mp4a.40."+w},tn=function(){},Dn=function(){};(function(C){C[C.kSpliceNull=0]="kSpliceNull",C[C.kSpliceSchedule=4]="kSpliceSchedule",C[C.kSpliceInsert=5]="kSpliceInsert",C[C.kTimeSignal=6]="kTimeSignal",C[C.kBandwidthReservation=7]="kBandwidthReservation",C[C.kPrivateCommand=255]="kPrivateCommand"})(Ne||(Ne={}));var lt,un=function(C){var A=C.readBool();return A?(C.readBits(6),{time_specified_flag:A,pts_time:4*C.readBits(31)+C.readBits(2)}):(C.readBits(7),{time_specified_flag:A})},Sn=function(C){var A=C.readBool();return C.readBits(6),{auto_return:A,duration:4*C.readBits(31)+C.readBits(2)}},tr=function(C,A){var w=A.readBits(8);return C?{component_tag:w}:{component_tag:w,splice_time:un(A)}},Un=function(C){return{component_tag:C.readBits(8),utc_splice_time:C.readBits(32)}},En=function(C){var A=C.readBits(32),w=C.readBool();C.readBits(7);var x={splice_event_id:A,splice_event_cancel_indicator:w};if(w)return x;if(x.out_of_network_indicator=C.readBool(),x.program_splice_flag=C.readBool(),x.duration_flag=C.readBool(),C.readBits(5),x.program_splice_flag)x.utc_splice_time=C.readBits(32);else{x.component_count=C.readBits(8),x.components=[];for(var P=0;P<x.component_count;P++)x.components.push(Un(C))}return x.duration_flag&&(x.break_duration=Sn(C)),x.unique_program_id=C.readBits(16),x.avail_num=C.readBits(8),x.avails_expected=C.readBits(8),x},Yr=function(C,A,w,x){return{descriptor_tag:C,descriptor_length:A,identifier:w,provider_avail_id:x.readBits(32)}},vr=function(C,A,w,x){var P=x.readBits(8),F=x.readBits(3);x.readBits(5);for(var $="",K=0;K<F;K++)$+=String.fromCharCode(x.readBits(8));return{descriptor_tag:C,descriptor_length:A,identifier:w,preroll:P,dtmf_count:F,DTMF_char:$}},_s=function(C){var A=C.readBits(8);return C.readBits(7),{component_tag:A,pts_offset:4*C.readBits(31)+C.readBits(2)}},Wi=function(C,A,w,x){var P=x.readBits(32),F=x.readBool();x.readBits(7);var $={descriptor_tag:C,descriptor_length:A,identifier:w,segmentation_event_id:P,segmentation_event_cancel_indicator:F};if(F)return $;if($.program_segmentation_flag=x.readBool(),$.segmentation_duration_flag=x.readBool(),$.delivery_not_restricted_flag=x.readBool(),$.delivery_not_restricted_flag?x.readBits(5):($.web_delivery_allowed_flag=x.readBool(),$.no_regional_blackout_flag=x.readBool(),$.archive_allowed_flag=x.readBool(),$.device_restrictions=x.readBits(2)),!$.program_segmentation_flag){$.component_count=x.readBits(8),$.components=[];for(var K=0;K<$.component_count;K++)$.components.push(_s(x))}$.segmentation_duration_flag&&($.segmentation_duration=x.readBits(40)),$.segmentation_upid_type=x.readBits(8),$.segmentation_upid_length=x.readBits(8);var ne=new Uint8Array($.segmentation_upid_length);for(K=0;K<$.segmentation_upid_length;K++)ne[K]=x.readBits(8);return $.segmentation_upid=ne.buffer,$.segmentation_type_id=x.readBits(8),$.segment_num=x.readBits(8),$.segments_expected=x.readBits(8),$.segmentation_type_id!==52&&$.segmentation_type_id!==54&&$.segmentation_type_id!==56&&$.segmentation_type_id!==58||($.sub_segment_num=x.readBits(8),$.sub_segments_expected=x.readBits(8)),$},Xt=function(C,A,w,x){return{descriptor_tag:C,descriptor_length:A,identifier:w,TAI_seconds:x.readBits(48),TAI_ns:x.readBits(32),UTC_offset:x.readBits(16)}},or=function(C){return{component_tag:C.readBits(8),ISO_code:String.fromCharCode(C.readBits(8),C.readBits(8),C.readBits(8)),Bit_Stream_Mode:C.readBits(3),Num_Channels:C.readBits(4),Full_Srvc_Audio:C.readBool()}},Ta=function(C,A,w,x){for(var P=x.readBits(4),F=[],$=0;$<P;$++)F.push(or(x));return{descriptor_tag:C,descriptor_length:A,identifier:w,audio_count:P,components:F}},Yi=function(C){var A=new g(C),w=A.readBits(8),x=A.readBool(),P=A.readBool();A.readBits(2);var F=A.readBits(12),$=A.readBits(8),K=A.readBool(),ne=A.readBits(6),ee=4*A.readBits(31)+A.readBits(2),se=A.readBits(8),le=A.readBits(12),ae=A.readBits(12),ce=A.readBits(8),Te=null;ce===Ne.kSpliceNull?Te={}:ce===Ne.kSpliceSchedule?Te=function(pt){for(var Ot=pt.readBits(8),Jt=[],yt=0;yt<Ot;yt++)Jt.push(En(pt));return{splice_count:Ot,events:Jt}}(A):ce===Ne.kSpliceInsert?Te=function(pt){var Ot=pt.readBits(32),Jt=pt.readBool();pt.readBits(7);var yt={splice_event_id:Ot,splice_event_cancel_indicator:Jt};if(Jt)return yt;if(yt.out_of_network_indicator=pt.readBool(),yt.program_splice_flag=pt.readBool(),yt.duration_flag=pt.readBool(),yt.splice_immediate_flag=pt.readBool(),pt.readBits(4),yt.program_splice_flag&&!yt.splice_immediate_flag&&(yt.splice_time=un(pt)),!yt.program_splice_flag){yt.component_count=pt.readBits(8),yt.components=[];for(var kt=0;kt<yt.component_count;kt++)yt.components.push(tr(yt.splice_immediate_flag,pt))}return yt.duration_flag&&(yt.break_duration=Sn(pt)),yt.unique_program_id=pt.readBits(16),yt.avail_num=pt.readBits(8),yt.avails_expected=pt.readBits(8),yt}(A):ce===Ne.kTimeSignal?Te=function(pt){return{splice_time:un(pt)}}(A):ce===Ne.kBandwidthReservation?Te={}:ce===Ne.kPrivateCommand?Te=function(pt,Ot){for(var Jt=String.fromCharCode(Ot.readBits(8),Ot.readBits(8),Ot.readBits(8),Ot.readBits(8)),yt=new Uint8Array(pt-4),kt=0;kt<pt-4;kt++)yt[kt]=Ot.readBits(8);return{identifier:Jt,private_data:yt.buffer}}(ae,A):A.readBits(8*ae);for(var Be=[],Pe=A.readBits(16),Je=0;Je<Pe;){var Ye=A.readBits(8),Ge=A.readBits(8),ut=String.fromCharCode(A.readBits(8),A.readBits(8),A.readBits(8),A.readBits(8));Ye===0?Be.push(Yr(Ye,Ge,ut,A)):Ye===1?Be.push(vr(Ye,Ge,ut,A)):Ye===2?Be.push(Wi(Ye,Ge,ut,A)):Ye===3?Be.push(Xt(Ye,Ge,ut,A)):Ye===4?Be.push(Ta(Ye,Ge,ut,A)):A.readBits(8*(Ge-4)),Je+=2+Ge}var bt={table_id:w,section_syntax_indicator:x,private_indicator:P,section_length:F,protocol_version:$,encrypted_packet:K,encryption_algorithm:ne,pts_adjustment:ee,cw_index:se,tier:le,splice_command_length:ae,splice_command_type:ce,splice_command:Te,descriptor_loop_length:Pe,splice_descriptors:Be,E_CRC32:K?A.readBits(32):void 0,CRC32:A.readBits(32)};if(ce===Ne.kSpliceInsert){var Xe=Te;if(Xe.splice_event_cancel_indicator)return{splice_command_type:ce,detail:bt,data:C};if(Xe.program_splice_flag&&!Xe.splice_immediate_flag){var Ke=Xe.duration_flag?Xe.break_duration.auto_return:void 0,Rt=Xe.duration_flag?Xe.break_duration.duration/90:void 0;return Xe.splice_time.time_specified_flag?{splice_command_type:ce,pts:(ee+Xe.splice_time.pts_time)%Math.pow(2,33),auto_return:Ke,duraiton:Rt,detail:bt,data:C}:{splice_command_type:ce,auto_return:Ke,duraiton:Rt,detail:bt,data:C}}return{splice_command_type:ce,auto_return:Ke=Xe.duration_flag?Xe.break_duration.auto_return:void 0,duraiton:Rt=Xe.duration_flag?Xe.break_duration.duration/90:void 0,detail:bt,data:C}}if(ce===Ne.kTimeSignal){var dt=Te;return dt.splice_time.time_specified_flag?{splice_command_type:ce,pts:(ee+dt.splice_time.pts_time)%Math.pow(2,33),detail:bt,data:C}:{splice_command_type:ce,detail:bt,data:C}}return{splice_command_type:ce,detail:bt,data:C}};(function(C){C[C.kSliceIDR_W_RADL=19]="kSliceIDR_W_RADL",C[C.kSliceIDR_N_LP=20]="kSliceIDR_N_LP",C[C.kSliceCRA_NUT=21]="kSliceCRA_NUT",C[C.kSliceVPS=32]="kSliceVPS",C[C.kSliceSPS=33]="kSliceSPS",C[C.kSlicePPS=34]="kSlicePPS",C[C.kSliceAUD=35]="kSliceAUD"})(lt||(lt={}));var Ei=function(){},li=function(C){var A=C.data.byteLength;this.type=C.type,this.data=new Uint8Array(4+A),new DataView(this.data.buffer).setUint32(0,A),this.data.set(C.data,4)},Xi=function(){function C(A){this.TAG="H265AnnexBParser",this.current_startcode_offset_=0,this.eof_flag_=!1,this.data_=A,this.current_startcode_offset_=this.findNextStartCodeOffset(0),this.eof_flag_&&o.a.e(this.TAG,"Could not find H265 startcode until payload end!")}return C.prototype.findNextStartCodeOffset=function(A){for(var w=A,x=this.data_;;){if(w+3>=x.byteLength)return this.eof_flag_=!0,x.byteLength;var P=x[w+0]<<24|x[w+1]<<16|x[w+2]<<8|x[w+3],F=x[w+0]<<16|x[w+1]<<8|x[w+2];if(P===1||F===1)return w;w++}},C.prototype.readNextNaluPayload=function(){for(var A=this.data_,w=null;w==null&&!this.eof_flag_;){var x=this.current_startcode_offset_,P=A[x+=(A[x]<<24|A[x+1]<<16|A[x+2]<<8|A[x+3])===1?4:3]>>1&63,F=(128&A[x])>>>7,$=this.findNextStartCodeOffset(x);if(this.current_startcode_offset_=$,F===0){var K=A.subarray(x,$);(w=new Ei).type=P,w.data=K}}return w},C}(),js=function(){function C(A,w,x,P){var F=23+(5+A.byteLength)+(5+w.byteLength)+(5+x.byteLength),$=this.data=new Uint8Array(F);$[0]=1,$[1]=(3&P.general_profile_space)<<6|(P.general_tier_flag?1:0)<<5|31&P.general_profile_idc,$[2]=P.general_profile_compatibility_flags_1,$[3]=P.general_profile_compatibility_flags_2,$[4]=P.general_profile_compatibility_flags_3,$[5]=P.general_profile_compatibility_flags_4,$[6]=P.general_constraint_indicator_flags_1,$[7]=P.general_constraint_indicator_flags_2,$[8]=P.general_constraint_indicator_flags_3,$[9]=P.general_constraint_indicator_flags_4,$[10]=P.general_constraint_indicator_flags_5,$[11]=P.general_constraint_indicator_flags_6,$[12]=P.general_level_idc,$[13]=240|(3840&P.min_spatial_segmentation_idc)>>8,$[14]=255&P.min_spatial_segmentation_idc,$[15]=252|3&P.parallelismType,$[16]=252|3&P.chroma_format_idc,$[17]=248|7&P.bit_depth_luma_minus8,$[18]=248|7&P.bit_depth_chroma_minus8,$[19]=0,$[20]=0,$[21]=(3&P.constant_frame_rate)<<6|(7&P.num_temporal_layers)<<3|(P.temporal_id_nested?1:0)<<2|3,$[22]=3,$[23]=128|lt.kSliceVPS,$[24]=0,$[25]=1,$[26]=(65280&A.byteLength)>>8,$[27]=(255&A.byteLength)>>0,$.set(A,28),$[23+(5+A.byteLength)+0]=128|lt.kSliceSPS,$[23+(5+A.byteLength)+1]=0,$[23+(5+A.byteLength)+2]=1,$[23+(5+A.byteLength)+3]=(65280&w.byteLength)>>8,$[23+(5+A.byteLength)+4]=(255&w.byteLength)>>0,$.set(w,23+(5+A.byteLength)+5),$[23+(5+A.byteLength+5+w.byteLength)+0]=128|lt.kSlicePPS,$[23+(5+A.byteLength+5+w.byteLength)+1]=0,$[23+(5+A.byteLength+5+w.byteLength)+2]=1,$[23+(5+A.byteLength+5+w.byteLength)+3]=(65280&x.byteLength)>>8,$[23+(5+A.byteLength+5+w.byteLength)+4]=(255&x.byteLength)>>0,$.set(x,23+(5+A.byteLength+5+w.byteLength)+5)}return C.prototype.getData=function(){return this.data},C}(),Qi=function(){},ci=function(){},nt=function(){},Aa=[[64,64,80,80,96,96,112,112,128,128,160,160,192,192,224,224,256,256,320,320,384,384,448,448,512,512,640,640,768,768,896,896,1024,1024,1152,1152,1280,1280],[69,70,87,88,104,105,121,122,139,140,174,175,208,209,243,244,278,279,348,349,417,418,487,488,557,558,696,697,835,836,975,976,1114,1115,1253,1254,1393,1394],[96,96,120,120,144,144,168,168,192,192,240,240,288,288,336,336,384,384,480,480,576,576,672,672,768,768,960,960,1152,1152,1344,1344,1536,1536,1728,1728,1920,1920]],bs=function(){function C(A){this.TAG="AC3Parser",this.data_=A,this.current_syncword_offset_=this.findNextSyncwordOffset(0),this.eof_flag_&&o.a.e(this.TAG,"Could not found AC3 syncword until payload end")}return C.prototype.findNextSyncwordOffset=function(A){for(var w=A,x=this.data_;;){if(w+7>=x.byteLength)return this.eof_flag_=!0,x.byteLength;if((x[w+0]<<8|x[w+1]<<0)===2935)return w;w++}},C.prototype.readNextAC3Frame=function(){for(var A=this.data_,w=null;w==null&&!this.eof_flag_;){var x=this.current_syncword_offset_,P=A[x+4]>>6,F=[48e3,44200,33e3][P],$=63&A[x+4],K=2*Aa[P][$];if(isNaN(K)||x+K>this.data_.byteLength){this.eof_flag_=!0,this.has_last_incomplete_data=!0;break}var ne=this.findNextSyncwordOffset(x+K);this.current_syncword_offset_=ne;var ee=A[x+5]>>3,se=7&A[x+5],le=A[x+6]>>5,ae=0;1&le&&le!==1&&(ae+=2),4&le&&(ae+=2),le===2&&(ae+=2);var ce=(A[x+6]<<8|A[x+7]<<0)>>12-ae&1,Te=[2,1,2,3,3,4,4,5][le]+ce;(w=new nt).sampling_frequency=F,w.channel_count=Te,w.channel_mode=le,w.bit_stream_identification=ee,w.low_frequency_effects_channel_on=ce,w.bit_stream_mode=se,w.frame_size_code=$,w.data=A.subarray(x,x+K)}return w},C.prototype.hasIncompleteData=function(){return this.has_last_incomplete_data},C.prototype.getIncompleteData=function(){return this.has_last_incomplete_data?this.data_.subarray(this.current_syncword_offset_):null},C}(),Ra=function(C){var A;A=[C.sampling_rate_code<<6|C.bit_stream_identification<<1|C.bit_stream_mode>>2,(3&C.bit_stream_mode)<<6|C.channel_mode<<3|C.low_frequency_effects_channel_on<<2|C.frame_size_code>>4,C.frame_size_code<<4&224],this.config=A,this.sampling_rate=C.sampling_frequency,this.bit_stream_identification=C.bit_stream_identification,this.bit_stream_mode=C.bit_stream_mode,this.low_frequency_effects_channel_on=C.low_frequency_effects_channel_on,this.channel_count=C.channel_count,this.channel_mode=C.channel_mode,this.codec_mimetype="ac-3",this.original_codec_mimetype="ac-3"},Qe=function(){},Ml=function(){function C(A){this.TAG="EAC3Parser",this.data_=A,this.current_syncword_offset_=this.findNextSyncwordOffset(0),this.eof_flag_&&o.a.e(this.TAG,"Could not found AC3 syncword until payload end")}return C.prototype.findNextSyncwordOffset=function(A){for(var w=A,x=this.data_;;){if(w+7>=x.byteLength)return this.eof_flag_=!0,x.byteLength;if((x[w+0]<<8|x[w+1]<<0)===2935)return w;w++}},C.prototype.readNextEAC3Frame=function(){for(var A=this.data_,w=null;w==null&&!this.eof_flag_;){var x=this.current_syncword_offset_,P=new g(A.subarray(x+2)),F=(P.readBits(2),P.readBits(3),P.readBits(11)+1<<1),$=P.readBits(2),K=null,ne=null;$===3?(K=[24e3,22060,16e3][$=P.readBits(2)],ne=3):(K=[48e3,44100,32e3][$],ne=P.readBits(2));var ee=P.readBits(3),se=P.readBits(1),le=P.readBits(5);if(x+F>this.data_.byteLength){this.eof_flag_=!0,this.has_last_incomplete_data=!0;break}var ae=this.findNextSyncwordOffset(x+F);this.current_syncword_offset_=ae;var ce=[2,1,2,3,3,4,4,5][ee]+se;P.destroy(),(w=new Qe).sampling_frequency=K,w.channel_count=ce,w.channel_mode=ee,w.bit_stream_identification=le,w.low_frequency_effects_channel_on=se,w.frame_size=F,w.num_blks=[1,2,3,6][ne],w.data=A.subarray(x,x+F)}return w},C.prototype.hasIncompleteData=function(){return this.has_last_incomplete_data},C.prototype.getIncompleteData=function(){return this.has_last_incomplete_data?this.data_.subarray(this.current_syncword_offset_):null},C}(),_o=function(C){var A,w=Math.floor(C.frame_size*C.sampling_frequency/(16*C.num_blks));A=[255&w,248&w,C.sampling_rate_code<<6|C.bit_stream_identification<<1|0,0|C.channel_mode<<1|C.low_frequency_effects_channel_on<<0,0],this.config=A,this.sampling_rate=C.sampling_frequency,this.bit_stream_identification=C.bit_stream_identification,this.num_blks=C.num_blks,this.low_frequency_effects_channel_on=C.low_frequency_effects_channel_on,this.channel_count=C.channel_count,this.channel_mode=C.channel_mode,this.codec_mimetype="ec-3",this.original_codec_mimetype="ec-3"},ui=function(){},Qc=function(){function C(A){this.TAG="AV1OBUInMpegTsParser",this.current_startcode_offset_=0,this.eof_flag_=!1,this.data_=A,this.current_startcode_offset_=this.findNextStartCodeOffset(0),this.eof_flag_&&o.a.e(this.TAG,"Could not find AV1 startcode until payload end!")}return C._ebsp2rbsp=function(A){for(var w=A,x=w.byteLength,P=new Uint8Array(x),F=0,$=0;$<x;$++)$>=2&&w[$]===3&&w[$-1]===0&&w[$-2]===0||(P[F]=w[$],F++);return new Uint8Array(P.buffer,0,F)},C.prototype.findNextStartCodeOffset=function(A){for(var w=A,x=this.data_;;){if(w+2>=x.byteLength)return this.eof_flag_=!0,x.byteLength;if((x[w+0]<<16|x[w+1]<<8|x[w+2])===1)return w;w++}},C.prototype.readNextOBUPayload=function(){for(var A=this.data_,w=null;w==null&&!this.eof_flag_;){var x=this.current_startcode_offset_+3,P=this.findNextStartCodeOffset(x);this.current_startcode_offset_=P,w=C._ebsp2rbsp(A.subarray(x,P))}return w},C}(),vt=function(){var C=function(A,w){return(C=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(x,P){x.__proto__=P}||function(x,P){for(var F in P)Object.prototype.hasOwnProperty.call(P,F)&&(x[F]=P[F])})(A,w)};return function(A,w){if(typeof w!="function"&&w!==null)throw new TypeError("Class extends value "+String(w)+" is not a constructor or null");function x(){this.constructor=A}C(A,w),A.prototype=w===null?Object.create(w):(x.prototype=w.prototype,new x)}}(),jt=function(){return(jt=Object.assign||function(C){for(var A,w=1,x=arguments.length;w<x;w++)for(var P in A=arguments[w])Object.prototype.hasOwnProperty.call(A,P)&&(C[P]=A[P]);return C}).apply(this,arguments)},sn=function(C){function A(w,x){var P=C.call(this)||this;return P.TAG="TSDemuxer",P.first_parse_=!0,P.media_info_=new c.a,P.timescale_=90,P.duration_=0,P.current_pmt_pid_=-1,P.program_pmt_map_={},P.pes_slice_queues_={},P.section_slice_queues_={},P.video_metadata_={vps:void 0,sps:void 0,pps:void 0,av1c:void 0,details:void 0},P.audio_metadata_={codec:void 0,audio_object_type:void 0,sampling_freq_index:void 0,sampling_frequency:void 0,channel_config:void 0},P.last_pcr_base_=NaN,P.timestamp_offset_=0,P.audio_last_sample_pts_=void 0,P.aac_last_incomplete_data_=null,P.has_video_=!1,P.has_audio_=!1,P.video_init_segment_dispatched_=!1,P.audio_init_segment_dispatched_=!1,P.video_metadata_changed_=!1,P.audio_metadata_changed_=!1,P.loas_previous_frame=null,P.video_track_={type:"video",id:1,sequenceNumber:0,samples:[],length:0},P.audio_track_={type:"audio",id:2,sequenceNumber:0,samples:[],length:0},P.ts_packet_size_=w.ts_packet_size,P.sync_offset_=w.sync_offset,P.config_=x,P}return vt(A,C),A.prototype.destroy=function(){this.media_info_=null,this.pes_slice_queues_=null,this.section_slice_queues_=null,this.video_metadata_=null,this.audio_metadata_=null,this.aac_last_incomplete_data_=null,this.video_track_=null,this.audio_track_=null,C.prototype.destroy.call(this)},A.probe=function(w){var x=new Uint8Array(w),P=-1,F=188;if(x.byteLength<=3*F)return{needMoreData:!0};for(;P===-1;){for(var $=Math.min(1e3,x.byteLength-3*F),K=0;K<$;){if(x[K]===71&&x[K+F]===71&&x[K+2*F]===71){P=K;break}K++}if(P===-1)if(F===188)F=192;else{if(F!==192)break;F=204}}return P===-1?{match:!1}:(F===192&&P>=4?(o.a.v("TSDemuxer","ts_packet_size = 192, m2ts mode"),P-=4):F===204&&o.a.v("TSDemuxer","ts_packet_size = 204, RS encoded MPEG2-TS stream"),{match:!0,consumed:0,ts_packet_size:F,sync_offset:P})},A.prototype.bindDataSource=function(w){return w.onDataArrival=this.parseChunks.bind(this),this},A.prototype.resetMediaInfo=function(){this.media_info_=new c.a},A.prototype.parseChunks=function(w,x){if(!(this.onError&&this.onMediaInfo&&this.onTrackMetadata&&this.onDataAvailable))throw new f.a("onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified");var P=0;for(this.first_parse_&&(this.first_parse_=!1,P=this.sync_offset_);P+this.ts_packet_size_<=w.byteLength;){var F=x+P;this.ts_packet_size_===192&&(P+=4);var $=new Uint8Array(w,P,188),K=$[0];if(K!==71){o.a.e(this.TAG,"sync_byte = ".concat(K,", not 0x47"));break}var ne=(64&$[1])>>>6,ee=($[1],(31&$[1])<<8|$[2]),se=(48&$[3])>>>4,le=15&$[3],ae=!(!this.pmt_||this.pmt_.pcr_pid!==ee),ce={},Te=4;if(se==2||se==3){var Be=$[4];if(Be>0&&(ae||se==3)&&(ce.discontinuity_indicator=(128&$[5])>>>7,ce.random_access_indicator=(64&$[5])>>>6,ce.elementary_stream_priority_indicator=(32&$[5])>>>5,(16&$[5])>>>4)){var Pe=300*this.getPcrBase($)+((1&$[10])<<8|$[11]);this.last_pcr_=Pe}if(se==2||5+Be===188){P+=188,this.ts_packet_size_===204&&(P+=16);continue}Te=5+Be}if(se==1||se==3){if(ee===0||ee===this.current_pmt_pid_||this.pmt_!=null&&this.pmt_.pid_stream_type[ee]===R.kSCTE35){var Je=188-Te;this.handleSectionSlice(w,P+Te,Je,{pid:ee,file_position:F,payload_unit_start_indicator:ne,continuity_conunter:le,random_access_indicator:ce.random_access_indicator})}else if(this.pmt_!=null&&this.pmt_.pid_stream_type[ee]!=null){Je=188-Te;var Ye=this.pmt_.pid_stream_type[ee];ee!==this.pmt_.common_pids.h264&&ee!==this.pmt_.common_pids.h265&&ee!==this.pmt_.common_pids.av1&&ee!==this.pmt_.common_pids.adts_aac&&ee!==this.pmt_.common_pids.loas_aac&&ee!==this.pmt_.common_pids.ac3&&ee!==this.pmt_.common_pids.eac3&&ee!==this.pmt_.common_pids.opus&&ee!==this.pmt_.common_pids.mp3&&this.pmt_.pes_private_data_pids[ee]!==!0&&this.pmt_.timed_id3_pids[ee]!==!0&&this.pmt_.synchronous_klv_pids[ee]!==!0&&this.pmt_.asynchronous_klv_pids[ee]!==!0||this.handlePESSlice(w,P+Te,Je,{pid:ee,stream_type:Ye,file_position:F,payload_unit_start_indicator:ne,continuity_conunter:le,random_access_indicator:ce.random_access_indicator})}}P+=188,this.ts_packet_size_===204&&(P+=16)}return this.dispatchAudioVideoMediaSegment(),P},A.prototype.handleSectionSlice=function(w,x,P,F){var $=new Uint8Array(w,x,P),K=this.section_slice_queues_[F.pid];if(F.payload_unit_start_indicator){var ne=$[0];if(K!=null&&K.total_length!==0){var ee=new Uint8Array(w,x+1,Math.min(P,ne));K.slices.push(ee),K.total_length+=ee.byteLength,K.total_length===K.expected_length?this.emitSectionSlices(K,F):this.clearSlices(K,F)}for(var se=1+ne;se<$.byteLength&&$[se+0]!==255;){var le=(15&$[se+1])<<8|$[se+2];this.section_slice_queues_[F.pid]=new Q,(K=this.section_slice_queues_[F.pid]).expected_length=le+3,K.file_position=F.file_position,K.random_access_indicator=F.random_access_indicator,ee=new Uint8Array(w,x+se,Math.min(P-se,K.expected_length-K.total_length)),K.slices.push(ee),K.total_length+=ee.byteLength,K.total_length===K.expected_length?this.emitSectionSlices(K,F):K.total_length>=K.expected_length&&this.clearSlices(K,F),se+=ee.byteLength}}else K!=null&&K.total_length!==0&&(ee=new Uint8Array(w,x,Math.min(P,K.expected_length-K.total_length)),K.slices.push(ee),K.total_length+=ee.byteLength,K.total_length===K.expected_length?this.emitSectionSlices(K,F):K.total_length>=K.expected_length&&this.clearSlices(K,F))},A.prototype.handlePESSlice=function(w,x,P,F){var $=new Uint8Array(w,x,P),K=$[0]<<16|$[1]<<8|$[2],ne=($[3],$[4]<<8|$[5]);if(F.payload_unit_start_indicator){if(K!==1)return void o.a.e(this.TAG,"handlePESSlice: packet_start_code_prefix should be 1 but with value ".concat(K));var ee=this.pes_slice_queues_[F.pid];ee&&(ee.expected_length===0||ee.expected_length===ee.total_length?this.emitPESSlices(ee,F):this.clearSlices(ee,F)),this.pes_slice_queues_[F.pid]=new Q,this.pes_slice_queues_[F.pid].file_position=F.file_position,this.pes_slice_queues_[F.pid].random_access_indicator=F.random_access_indicator}if(this.pes_slice_queues_[F.pid]!=null){var se=this.pes_slice_queues_[F.pid];se.slices.push($),F.payload_unit_start_indicator&&(se.expected_length=ne===0?0:ne+6),se.total_length+=$.byteLength,se.expected_length>0&&se.expected_length===se.total_length?this.emitPESSlices(se,F):se.expected_length>0&&se.expected_length<se.total_length&&this.clearSlices(se,F)}},A.prototype.emitSectionSlices=function(w,x){for(var P=new Uint8Array(w.total_length),F=0,$=0;F<w.slices.length;F++){var K=w.slices[F];P.set(K,$),$+=K.byteLength}w.slices=[],w.expected_length=-1,w.total_length=0;var ne=new oe;ne.pid=x.pid,ne.data=P,ne.file_position=w.file_position,ne.random_access_indicator=w.random_access_indicator,this.parseSection(ne)},A.prototype.emitPESSlices=function(w,x){for(var P=new Uint8Array(w.total_length),F=0,$=0;F<w.slices.length;F++){var K=w.slices[F];P.set(K,$),$+=K.byteLength}w.slices=[],w.expected_length=-1,w.total_length=0;var ne=new X;ne.pid=x.pid,ne.data=P,ne.stream_type=x.stream_type,ne.file_position=w.file_position,ne.random_access_indicator=w.random_access_indicator,this.parsePES(ne)},A.prototype.clearSlices=function(w,x){w.slices=[],w.expected_length=-1,w.total_length=0},A.prototype.parseSection=function(w){var x=w.data,P=w.pid;P===0?this.parsePAT(x):P===this.current_pmt_pid_?this.parsePMT(x):this.pmt_!=null&&this.pmt_.scte_35_pids[P]&&this.parseSCTE35(x)},A.prototype.parsePES=function(w){var x=w.data,P=x[0]<<16|x[1]<<8|x[2],F=x[3],$=x[4]<<8|x[5];if(P===1)if(F!==188&&F!==190&&F!==191&&F!==240&&F!==241&&F!==255&&F!==242&&F!==248){x[6];var K=(192&x[7])>>>6,ne=x[8],ee=void 0,se=void 0;K!==2&&K!==3||(ee=this.getTimestamp(x,9),se=K===3?this.getTimestamp(x,14):ee);var le=9+ne,ae=void 0;if($!==0){if($<3+ne)return void o.a.v(this.TAG,"Malformed PES: PES_packet_length < 3 + PES_header_data_length");ae=$-3-ne}else ae=x.byteLength-le;var ce=x.subarray(le,le+ae);switch(w.stream_type){case R.kMPEG1Audio:case R.kMPEG2Audio:this.parseMP3Payload(ce,ee);break;case R.kPESPrivateData:this.pmt_.common_pids.av1===w.pid?this.parseAV1Payload(ce,ee,se,w.file_position,w.random_access_indicator):this.pmt_.common_pids.opus===w.pid?this.parseOpusPayload(ce,ee):this.pmt_.common_pids.ac3===w.pid?this.parseAC3Payload(ce,ee):this.pmt_.common_pids.eac3===w.pid?this.parseEAC3Payload(ce,ee):this.pmt_.asynchronous_klv_pids[w.pid]?this.parseAsynchronousKLVMetadataPayload(ce,w.pid,F):this.pmt_.smpte2038_pids[w.pid]?this.parseSMPTE2038MetadataPayload(ce,ee,se,w.pid,F):this.parsePESPrivateDataPayload(ce,ee,se,w.pid,F);break;case R.kADTSAAC:this.parseADTSAACPayload(ce,ee);break;case R.kLOASAAC:this.parseLOASAACPayload(ce,ee);break;case R.kAC3:this.parseAC3Payload(ce,ee);break;case R.kEAC3:this.parseEAC3Payload(ce,ee);break;case R.kMetadata:this.pmt_.timed_id3_pids[w.pid]?this.parseTimedID3MetadataPayload(ce,ee,se,w.pid,F):this.pmt_.synchronous_klv_pids[w.pid]&&this.parseSynchronousKLVMetadataPayload(ce,ee,se,w.pid,F);break;case R.kH264:this.parseH264Payload(ce,ee,se,w.file_position,w.random_access_indicator);break;case R.kH265:this.parseH265Payload(ce,ee,se,w.file_position,w.random_access_indicator)}}else(F===188||F===191||F===240||F===241||F===255||F===242||F===248)&&w.stream_type===R.kPESPrivateData&&(le=6,ae=void 0,ae=$!==0?$:x.byteLength-le,ce=x.subarray(le,le+ae),this.parsePESPrivateDataPayload(ce,void 0,void 0,w.pid,F));else o.a.e(this.TAG,"parsePES: packet_start_code_prefix should be 1 but with value ".concat(P))},A.prototype.parsePAT=function(w){var x=w[0];if(x===0){var P=(15&w[1])<<8|w[2],F=(w[3],w[4],(62&w[5])>>>1),$=1&w[5],K=w[6],ne=(w[7],null);if($===1&&K===0)(ne=new Z).version_number=F;else if((ne=this.pat_)==null)return;for(var ee=P-5-4,se=-1,le=-1,ae=8;ae<8+ee;ae+=4){var ce=w[ae]<<8|w[ae+1],Te=(31&w[ae+2])<<8|w[ae+3];ce===0?ne.network_pid=Te:(ne.program_pmt_pid[ce]=Te,se===-1&&(se=ce),le===-1&&(le=Te))}$===1&&K===0&&(this.pat_==null&&o.a.v(this.TAG,"Parsed first PAT: ".concat(JSON.stringify(ne))),this.pat_=ne,this.current_program_=se,this.current_pmt_pid_=le)}else o.a.e(this.TAG,"parsePAT: table_id ".concat(x," is not corresponded to PAT!"))},A.prototype.parsePMT=function(w){var x=w[0];if(x===2){var P=(15&w[1])<<8|w[2],F=w[3]<<8|w[4],$=(62&w[5])>>>1,K=1&w[5],ne=w[6],ee=(w[7],null);if(K===1&&ne===0)(ee=new re).program_number=F,ee.version_number=$,this.program_pmt_map_[F]=ee;else if((ee=this.program_pmt_map_[F])==null)return;ee.pcr_pid=(31&w[8])<<8|w[9];for(var se=(15&w[10])<<8|w[11],le=12+se,ae=P-9-se-4,ce=le;ce<le+ae;){var Te=w[ce],Be=(31&w[ce+1])<<8|w[ce+2],Pe=(15&w[ce+3])<<8|w[ce+4];ee.pid_stream_type[Be]=Te;var Je=ee.common_pids.h264||ee.common_pids.h265,Ye=ee.common_pids.adts_aac||ee.common_pids.loas_aac||ee.common_pids.ac3||ee.common_pids.eac3||ee.common_pids.opus||ee.common_pids.mp3;if(Te!==R.kH264||Je)if(Te!==R.kH265||Je)if(Te!==R.kADTSAAC||Ye)if(Te!==R.kLOASAAC||Ye)if(Te!==R.kAC3||Ye)if(Te!==R.kEAC3||Ye)if(Te!==R.kMPEG1Audio&&Te!==R.kMPEG2Audio||Ye)if(Te===R.kPESPrivateData){if(ee.pes_private_data_pids[Be]=!0,Pe>0){for(var Ge=ce+5;Ge<ce+5+Pe;){var ut=w[Ge+0],bt=w[Ge+1];if(ut===5){var Xe=String.fromCharCode.apply(String,Array.from(w.subarray(Ge+2,Ge+2+bt)));Xe==="VANC"?ee.smpte2038_pids[Be]=!0:Xe==="AV01"?ee.common_pids.av1=Be:Xe==="Opus"?ee.common_pids.opus=Be:Xe==="KLVA"&&(ee.asynchronous_klv_pids[Be]=!0)}else if(ut===127){if(Be===ee.common_pids.opus){var Ke=null;if(w[Ge+2]===128&&(Ke=w[Ge+3]),Ke==null){o.a.e(this.TAG,"Not Supported Opus channel count.");continue}var Rt={codec:"opus",channel_count:15&Ke?15&Ke:2,channel_config_code:Ke,sample_rate:48e3},dt={codec:"opus",meta:Rt};this.audio_init_segment_dispatched_==0?(this.audio_metadata_=Rt,this.dispatchAudioInitSegment(dt)):this.detectAudioMetadataChange(dt)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(dt))}}else ut===128&&Be===ee.common_pids.av1&&(this.video_metadata_.av1c=w.subarray(Ge+2,Ge+2+bt));Ge+=2+bt}var pt=w.subarray(ce+5,ce+5+Pe);this.dispatchPESPrivateDataDescriptor(Be,Te,pt)}}else if(Te===R.kMetadata){if(Pe>0)for(Ge=ce+5;Ge<ce+5+Pe;){ut=w[Ge+0];var Ot=w[Ge+1];if(ut===38){var Jt=w[Ge+2]<<8|w[Ge+3]<<0,yt=null;Jt===65535&&(yt=String.fromCharCode.apply(String,Array.from(w.subarray(Ge+4,Ge+4+4))));var kt=null;if(w[Ge+4+(Jt===65535?4:0)]===255){var ht=4+(Jt===65535?4:0)+1;kt=String.fromCharCode.apply(String,Array.from(w.subarray(Ge+ht,Ge+ht+4)))}yt==="ID3 "&&kt==="ID3 "?ee.timed_id3_pids[Be]=!0:kt==="KLVA"&&(ee.synchronous_klv_pids[Be]=!0)}Ge+=2+Ot}}else Te===R.kSCTE35&&(ee.scte_35_pids[Be]=!0);else ee.common_pids.mp3=Be;else ee.common_pids.eac3=Be;else ee.common_pids.ac3=Be;else ee.common_pids.loas_aac=Be;else ee.common_pids.adts_aac=Be;else ee.common_pids.h265=Be;else ee.common_pids.h264=Be;ce+=5+Pe}F===this.current_program_&&(this.pmt_==null&&o.a.v(this.TAG,"Parsed first PMT: ".concat(JSON.stringify(ee))),this.pmt_=ee,(ee.common_pids.h264||ee.common_pids.h265||ee.common_pids.av1)&&(this.has_video_=!0),(ee.common_pids.adts_aac||ee.common_pids.loas_aac||ee.common_pids.ac3||ee.common_pids.opus||ee.common_pids.mp3)&&(this.has_audio_=!0))}else o.a.e(this.TAG,"parsePMT: table_id ".concat(x," is not corresponded to PMT!"))},A.prototype.parseSCTE35=function(w){var x=Yi(w);if(x.pts!=null){var P=Math.floor(x.pts/this.timescale_);x.pts=P}else x.nearest_pts=this.getNearestTimestampMilliseconds();this.onSCTE35Metadata&&this.onSCTE35Metadata(x)},A.prototype.parseAV1Payload=function(w,x,P,F,$){for(var K=new Qc(w),ne=null,ee=[],se=0,le=!1,ae=null;(ne=K.readNextOBUPayload())!=null;){if((ae=I.parseOBUs(ne,this.video_metadata_.details))&&ae.keyframe===!0)if(this.video_init_segment_dispatched_){if(this.detectVideoMetadataChange(null,ae)===!0){var ce;this.video_metadata_changed_=!0,this.dispatchVideoMediaSegment(),(ce=new Uint8Array(new ArrayBuffer(this.video_metadata_.av1c.byteLength+ae.sequence_header_data.byteLength))).set(this.video_metadata_.av1c,0),ce.set(ae.sequence_header_data,this.video_metadata_.av1c.byteLength),ae.av1c=ce,this.dispatchVideoInitSegment()}}else(ce=new Uint8Array(new ArrayBuffer(this.video_metadata_.av1c.byteLength+ae.sequence_header_data.byteLength))).set(this.video_metadata_.av1c,0),ce.set(ae.sequence_header_data,this.video_metadata_.av1c.byteLength),ae.av1c=ce,this.video_metadata_.details=ae,this.dispatchVideoInitSegment();this.video_metadata_.details=ae,le||(le=ae.keyframe),ee.push({data:ne}),se+=ne.byteLength}var Te=Math.floor(x/this.timescale_),Be=Math.floor(P/this.timescale_);if(ee.length){var Pe=this.video_track_,Je={units:ee,length:se,isKeyframe:le,dts:Be,pts:Te,cts:Te-Be,file_position:F};Pe.samples.push(Je),Pe.length+=se}},A.prototype.parseH264Payload=function(w,x,P,F,$){for(var K=new Ce(w),ne=null,ee=[],se=0,le=!1;(ne=K.readNextNaluPayload())!=null;){var ae=new ie(ne);if(ae.type===W.kSliceSPS){var ce=b.parseSPS(ne.data);this.video_init_segment_dispatched_?this.detectVideoMetadataChange(ae,ce)===!0&&(o.a.v(this.TAG,"H264: Critical h264 metadata has been changed, attempt to re-generate InitSegment"),this.video_metadata_changed_=!0,this.video_metadata_={vps:void 0,sps:ae,pps:void 0,av1c:void 0,details:ce}):(this.video_metadata_.sps=ae,this.video_metadata_.details=ce)}else ae.type===W.kSlicePPS?this.video_init_segment_dispatched_&&!this.video_metadata_changed_||(this.video_metadata_.pps=ae,this.video_metadata_.sps&&this.video_metadata_.pps&&(this.video_metadata_changed_&&this.dispatchVideoMediaSegment(),this.dispatchVideoInitSegment())):(ae.type===W.kSliceIDR||ae.type===W.kSliceNonIDR&&$===1)&&(le=!0);this.video_init_segment_dispatched_&&(ee.push(ae),se+=ae.data.byteLength)}var Te=Math.floor(x/this.timescale_),Be=Math.floor(P/this.timescale_);if(ee.length){var Pe=this.video_track_,Je={units:ee,length:se,isKeyframe:le,dts:Be,pts:Te,cts:Te-Be,file_position:F};Pe.samples.push(Je),Pe.length+=se}},A.prototype.parseH265Payload=function(w,x,P,F,$){for(var K=new Xi(w),ne=null,ee=[],se=0,le=!1;(ne=K.readNextNaluPayload())!=null;){var ae=new li(ne);if(ae.type===lt.kSliceVPS){if(!this.video_init_segment_dispatched_){var ce=S.parseVPS(ne.data);this.video_metadata_.vps=ae,this.video_metadata_.details=jt(jt({},this.video_metadata_.details),ce)}}else ae.type===lt.kSliceSPS?(ce=S.parseSPS(ne.data),this.video_init_segment_dispatched_?this.detectVideoMetadataChange(ae,ce)===!0&&(o.a.v(this.TAG,"H265: Critical h265 metadata has been changed, attempt to re-generate InitSegment"),this.video_metadata_changed_=!0,this.video_metadata_={vps:void 0,sps:ae,pps:void 0,av1c:void 0,details:ce}):(this.video_metadata_.sps=ae,this.video_metadata_.details=jt(jt({},this.video_metadata_.details),ce))):ae.type===lt.kSlicePPS?(!this.video_init_segment_dispatched_||this.video_metadata_changed_)&&(ce=S.parsePPS(ne.data),this.video_metadata_.pps=ae,this.video_metadata_.details=jt(jt({},this.video_metadata_.details),ce),this.video_metadata_.vps&&this.video_metadata_.sps&&this.video_metadata_.pps&&(this.video_metadata_changed_&&this.dispatchVideoMediaSegment(),this.dispatchVideoInitSegment())):ae.type!==lt.kSliceIDR_W_RADL&&ae.type!==lt.kSliceIDR_N_LP&&ae.type!==lt.kSliceCRA_NUT||(le=!0);this.video_init_segment_dispatched_&&(ee.push(ae),se+=ae.data.byteLength)}var Te=Math.floor(x/this.timescale_),Be=Math.floor(P/this.timescale_);if(ee.length){var Pe=this.video_track_,Je={units:ee,length:se,isKeyframe:le,dts:Be,pts:Te,cts:Te-Be,file_position:F};Pe.samples.push(Je),Pe.length+=se}},A.prototype.detectVideoMetadataChange=function(w,x){if(x.codec_mimetype!==this.video_metadata_.details.codec_mimetype)return o.a.v(this.TAG,"Video: Codec mimeType changed from "+"".concat(this.video_metadata_.details.codec_mimetype," to ").concat(x.codec_mimetype)),!0;if(x.codec_size.width!==this.video_metadata_.details.codec_size.width||x.codec_size.height!==this.video_metadata_.details.codec_size.height){var P=this.video_metadata_.details.codec_size,F=x.codec_size;return o.a.v(this.TAG,"Video: Coded Resolution changed from "+"".concat(P.width,"x").concat(P.height," to ").concat(F.width,"x").concat(F.height)),!0}return x.present_size.width!==this.video_metadata_.details.present_size.width&&(o.a.v(this.TAG,"Video: Present resolution width changed from "+"".concat(this.video_metadata_.details.present_size.width," to ").concat(x.present_size.width)),!0)},A.prototype.isInitSegmentDispatched=function(){return this.has_video_&&this.has_audio_?this.video_init_segment_dispatched_&&this.audio_init_segment_dispatched_:this.has_video_&&!this.has_audio_?this.video_init_segment_dispatched_:!(this.has_video_||!this.has_audio_)&&this.audio_init_segment_dispatched_},A.prototype.dispatchVideoInitSegment=function(){var w=this.video_metadata_.details,x={type:"video"};x.id=this.video_track_.id,x.timescale=1e3,x.duration=this.duration_,x.codecWidth=w.codec_size.width,x.codecHeight=w.codec_size.height,x.presentWidth=w.present_size.width,x.presentHeight=w.present_size.height,x.profile=w.profile_string,x.level=w.level_string,x.bitDepth=w.bit_depth,x.chromaFormat=w.chroma_format,x.sarRatio=w.sar_ratio,x.frameRate=w.frame_rate;var P=x.frameRate.fps_den,F=x.frameRate.fps_num;if(x.refSampleDuration=P/F*1e3,x.codec=w.codec_mimetype,this.video_metadata_.av1c)x.av1c=this.video_metadata_.av1c,this.video_init_segment_dispatched_==0&&o.a.v(this.TAG,"Generated first AV1 for mimeType: ".concat(x.codec));else if(this.video_metadata_.vps){var $=this.video_metadata_.vps.data.subarray(4),K=this.video_metadata_.sps.data.subarray(4),ne=this.video_metadata_.pps.data.subarray(4),ee=new js($,K,ne,w);x.hvcc=ee.getData(),this.video_init_segment_dispatched_==0&&o.a.v(this.TAG,"Generated first HEVCDecoderConfigurationRecord for mimeType: ".concat(x.codec))}else{K=this.video_metadata_.sps.data.subarray(4),ne=this.video_metadata_.pps.data.subarray(4);var se=new Le(K,ne,w);x.avcc=se.getData(),this.video_init_segment_dispatched_==0&&o.a.v(this.TAG,"Generated first AVCDecoderConfigurationRecord for mimeType: ".concat(x.codec))}this.onTrackMetadata("video",x),this.video_init_segment_dispatched_=!0,this.video_metadata_changed_=!1;var le=this.media_info_;le.hasVideo=!0,le.width=x.codecWidth,le.height=x.codecHeight,le.fps=x.frameRate.fps,le.profile=x.profile,le.level=x.level,le.refFrames=w.ref_frames,le.chromaFormat=w.chroma_format_string,le.sarNum=x.sarRatio.width,le.sarDen=x.sarRatio.height,le.videoCodec=x.codec,le.hasAudio&&le.audioCodec?le.mimeType='video/mp2t; codecs="'.concat(le.videoCodec,",").concat(le.audioCodec,'"'):le.mimeType='video/mp2t; codecs="'.concat(le.videoCodec,'"'),le.isComplete()&&this.onMediaInfo(le)},A.prototype.dispatchVideoMediaSegment=function(){this.isInitSegmentDispatched()&&this.video_track_.length&&this.onDataAvailable(null,this.video_track_)},A.prototype.dispatchAudioMediaSegment=function(){this.isInitSegmentDispatched()&&this.audio_track_.length&&this.onDataAvailable(this.audio_track_,null)},A.prototype.dispatchAudioVideoMediaSegment=function(){this.isInitSegmentDispatched()&&(this.audio_track_.length||this.video_track_.length)&&this.onDataAvailable(this.audio_track_,this.video_track_)},A.prototype.parseADTSAACPayload=function(w,x){if(!this.has_video_||this.video_init_segment_dispatched_){if(this.aac_last_incomplete_data_){var P=new Uint8Array(w.byteLength+this.aac_last_incomplete_data_.byteLength);P.set(this.aac_last_incomplete_data_,0),P.set(w,this.aac_last_incomplete_data_.byteLength),w=P}var F,$;if(x!=null&&($=x/this.timescale_),this.audio_metadata_.codec==="aac"){if(x==null&&this.audio_last_sample_pts_!=null)F=1024/this.audio_metadata_.sampling_frequency*1e3,$=this.audio_last_sample_pts_+F;else if(x==null)return void o.a.w(this.TAG,"AAC: Unknown pts");if(this.aac_last_incomplete_data_&&this.audio_last_sample_pts_){F=1024/this.audio_metadata_.sampling_frequency*1e3;var K=this.audio_last_sample_pts_+F;Math.abs(K-$)>1&&(o.a.w(this.TAG,"AAC: Detected pts overlapped, "+"expected: ".concat(K,"ms, PES pts: ").concat($,"ms")),$=K)}}for(var ne,ee=new je(w),se=null,le=$;(se=ee.readNextAACFrame())!=null;){F=1024/se.sampling_frequency*1e3;var ae={codec:"aac",data:se};this.audio_init_segment_dispatched_==0?(this.audio_metadata_={codec:"aac",audio_object_type:se.audio_object_type,sampling_freq_index:se.sampling_freq_index,sampling_frequency:se.sampling_frequency,channel_config:se.channel_config},this.dispatchAudioInitSegment(ae)):this.detectAudioMetadataChange(ae)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(ae)),ne=le;var ce=Math.floor(le),Te={unit:se.data,length:se.data.byteLength,pts:ce,dts:ce};this.audio_track_.samples.push(Te),this.audio_track_.length+=se.data.byteLength,le+=F}ee.hasIncompleteData()&&(this.aac_last_incomplete_data_=ee.getIncompleteData()),ne&&(this.audio_last_sample_pts_=ne)}},A.prototype.parseLOASAACPayload=function(w,x){var P;if(!this.has_video_||this.video_init_segment_dispatched_){if(this.aac_last_incomplete_data_){var F=new Uint8Array(w.byteLength+this.aac_last_incomplete_data_.byteLength);F.set(this.aac_last_incomplete_data_,0),F.set(w,this.aac_last_incomplete_data_.byteLength),w=F}var $,K;if(x!=null&&(K=x/this.timescale_),this.audio_metadata_.codec==="aac"){if(x==null&&this.audio_last_sample_pts_!=null)$=1024/this.audio_metadata_.sampling_frequency*1e3,K=this.audio_last_sample_pts_+$;else if(x==null)return void o.a.w(this.TAG,"AAC: Unknown pts");if(this.aac_last_incomplete_data_&&this.audio_last_sample_pts_){$=1024/this.audio_metadata_.sampling_frequency*1e3;var ne=this.audio_last_sample_pts_+$;Math.abs(ne-K)>1&&(o.a.w(this.TAG,"AAC: Detected pts overlapped, "+"expected: ".concat(ne,"ms, PES pts: ").concat(K,"ms")),K=ne)}}for(var ee,se=new Me(w),le=null,ae=K;(le=se.readNextAACFrame((P=this.loas_previous_frame)!==null&&P!==void 0?P:void 0))!=null;){this.loas_previous_frame=le,$=1024/le.sampling_frequency*1e3;var ce={codec:"aac",data:le};this.audio_init_segment_dispatched_==0?(this.audio_metadata_={codec:"aac",audio_object_type:le.audio_object_type,sampling_freq_index:le.sampling_freq_index,sampling_frequency:le.sampling_frequency,channel_config:le.channel_config},this.dispatchAudioInitSegment(ce)):this.detectAudioMetadataChange(ce)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(ce)),ee=ae;var Te=Math.floor(ae),Be={unit:le.data,length:le.data.byteLength,pts:Te,dts:Te};this.audio_track_.samples.push(Be),this.audio_track_.length+=le.data.byteLength,ae+=$}se.hasIncompleteData()&&(this.aac_last_incomplete_data_=se.getIncompleteData()),ee&&(this.audio_last_sample_pts_=ee)}},A.prototype.parseAC3Payload=function(w,x){if(!this.has_video_||this.video_init_segment_dispatched_){var P,F;if(x!=null&&(F=x/this.timescale_),this.audio_metadata_.codec==="ac-3"){if(x==null&&this.audio_last_sample_pts_!=null)P=1536/this.audio_metadata_.sampling_frequency*1e3,F=this.audio_last_sample_pts_+P;else if(x==null)return void o.a.w(this.TAG,"AC3: Unknown pts")}for(var $,K=new bs(w),ne=null,ee=F;(ne=K.readNextAC3Frame())!=null;){P=1536/ne.sampling_frequency*1e3;var se={codec:"ac-3",data:ne};this.audio_init_segment_dispatched_==0?(this.audio_metadata_={codec:"ac-3",sampling_frequency:ne.sampling_frequency,bit_stream_identification:ne.bit_stream_identification,bit_stream_mode:ne.bit_stream_mode,low_frequency_effects_channel_on:ne.low_frequency_effects_channel_on,channel_mode:ne.channel_mode},this.dispatchAudioInitSegment(se)):this.detectAudioMetadataChange(se)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(se)),$=ee;var le=Math.floor(ee),ae={unit:ne.data,length:ne.data.byteLength,pts:le,dts:le};this.audio_track_.samples.push(ae),this.audio_track_.length+=ne.data.byteLength,ee+=P}$&&(this.audio_last_sample_pts_=$)}},A.prototype.parseEAC3Payload=function(w,x){if(!this.has_video_||this.video_init_segment_dispatched_){var P,F;if(x!=null&&(F=x/this.timescale_),this.audio_metadata_.codec==="ec-3"){if(x==null&&this.audio_last_sample_pts_!=null)P=256*this.audio_metadata_.num_blks/this.audio_metadata_.sampling_frequency*1e3,F=this.audio_last_sample_pts_+P;else if(x==null)return void o.a.w(this.TAG,"EAC3: Unknown pts")}for(var $,K=new Ml(w),ne=null,ee=F;(ne=K.readNextEAC3Frame())!=null;){P=1536/ne.sampling_frequency*1e3;var se={codec:"ec-3",data:ne};this.audio_init_segment_dispatched_==0?(this.audio_metadata_={codec:"ec-3",sampling_frequency:ne.sampling_frequency,bit_stream_identification:ne.bit_stream_identification,low_frequency_effects_channel_on:ne.low_frequency_effects_channel_on,num_blks:ne.num_blks,channel_mode:ne.channel_mode},this.dispatchAudioInitSegment(se)):this.detectAudioMetadataChange(se)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(se)),$=ee;var le=Math.floor(ee),ae={unit:ne.data,length:ne.data.byteLength,pts:le,dts:le};this.audio_track_.samples.push(ae),this.audio_track_.length+=ne.data.byteLength,ee+=P}$&&(this.audio_last_sample_pts_=$)}},A.prototype.parseOpusPayload=function(w,x){if(!this.has_video_||this.video_init_segment_dispatched_){var P,F;if(x!=null&&(F=x/this.timescale_),this.audio_metadata_.codec==="opus"){if(x==null&&this.audio_last_sample_pts_!=null)P=20,F=this.audio_last_sample_pts_+P;else if(x==null)return void o.a.w(this.TAG,"Opus: Unknown pts")}for(var $,K=F,ne=0;ne<w.length;){P=20;for(var ee=(16&w[ne+1])!=0,se=(8&w[ne+1])!=0,le=ne+2,ae=0;w[le]===255;)ae+=255,le+=1;ae+=w[le],le+=1,le+=ee?2:0,le+=se?2:0,$=K;var ce=Math.floor(K),Te=w.slice(le,le+ae),Be={unit:Te,length:Te.byteLength,pts:ce,dts:ce};this.audio_track_.samples.push(Be),this.audio_track_.length+=Te.byteLength,K+=P,ne=le+ae}$&&(this.audio_last_sample_pts_=$)}},A.prototype.parseMP3Payload=function(w,x){if(!this.has_video_||this.video_init_segment_dispatched_){var P=[0,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1],F=[0,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1],$=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1],K=w[1]>>>3&3,ne=(6&w[1])>>1,ee=(240&w[2])>>>4,se=(12&w[2])>>>2,le=(w[3]>>>6&3)!==3?2:1,ae=0,ce=34;switch(K){case 0:ae=[11025,12e3,8e3,0][se];break;case 2:ae=[22050,24e3,16e3,0][se];break;case 3:ae=[44100,48e3,32e3,0][se]}switch(ne){case 1:ce=34,ee<$.length&&$[ee];break;case 2:ce=33,ee<F.length&&F[ee];break;case 3:ce=32,ee<P.length&&P[ee]}var Te=new ci;Te.object_type=ce,Te.sample_rate=ae,Te.channel_count=le,Te.data=w;var Be={codec:"mp3",data:Te};this.audio_init_segment_dispatched_==0?(this.audio_metadata_={codec:"mp3",object_type:ce,sample_rate:ae,channel_count:le},this.dispatchAudioInitSegment(Be)):this.detectAudioMetadataChange(Be)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(Be));var Pe={unit:w,length:w.byteLength,pts:x/this.timescale_,dts:x/this.timescale_};this.audio_track_.samples.push(Pe),this.audio_track_.length+=w.byteLength}},A.prototype.detectAudioMetadataChange=function(w){if(w.codec!==this.audio_metadata_.codec)return o.a.v(this.TAG,"Audio: Audio Codecs changed from "+"".concat(this.audio_metadata_.codec," to ").concat(w.codec)),!0;if(w.codec==="aac"&&this.audio_metadata_.codec==="aac"){if((x=w.data).audio_object_type!==this.audio_metadata_.audio_object_type)return o.a.v(this.TAG,"AAC: AudioObjectType changed from "+"".concat(this.audio_metadata_.audio_object_type," to ").concat(x.audio_object_type)),!0;if(x.sampling_freq_index!==this.audio_metadata_.sampling_freq_index)return o.a.v(this.TAG,"AAC: SamplingFrequencyIndex changed from "+"".concat(this.audio_metadata_.sampling_freq_index," to ").concat(x.sampling_freq_index)),!0;if(x.channel_config!==this.audio_metadata_.channel_config)return o.a.v(this.TAG,"AAC: Channel configuration changed from "+"".concat(this.audio_metadata_.channel_config," to ").concat(x.channel_config)),!0}else if(w.codec==="ac-3"&&this.audio_metadata_.codec==="ac-3"){var x;if((x=w.data).sampling_frequency!==this.audio_metadata_.sampling_frequency)return o.a.v(this.TAG,"AC3: Sampling Frequency changed from "+"".concat(this.audio_metadata_.sampling_frequency," to ").concat(x.sampling_frequency)),!0;if(x.bit_stream_identification!==this.audio_metadata_.bit_stream_identification)return o.a.v(this.TAG,"AC3: Bit Stream Identification changed from "+"".concat(this.audio_metadata_.bit_stream_identification," to ").concat(x.bit_stream_identification)),!0;if(x.bit_stream_mode!==this.audio_metadata_.bit_stream_mode)return o.a.v(this.TAG,"AC3: BitStream Mode changed from "+"".concat(this.audio_metadata_.bit_stream_mode," to ").concat(x.bit_stream_mode)),!0;if(x.channel_mode!==this.audio_metadata_.channel_mode)return o.a.v(this.TAG,"AC3: Channel Mode changed from "+"".concat(this.audio_metadata_.channel_mode," to ").concat(x.channel_mode)),!0;if(x.low_frequency_effects_channel_on!==this.audio_metadata_.low_frequency_effects_channel_on)return o.a.v(this.TAG,"AC3: Low Frequency Effects Channel On changed from "+"".concat(this.audio_metadata_.low_frequency_effects_channel_on," to ").concat(x.low_frequency_effects_channel_on)),!0}else if(w.codec==="opus"&&this.audio_metadata_.codec==="opus"){if((P=w.meta).sample_rate!==this.audio_metadata_.sample_rate)return o.a.v(this.TAG,"Opus: SamplingFrequencyIndex changed from "+"".concat(this.audio_metadata_.sample_rate," to ").concat(P.sample_rate)),!0;if(P.channel_count!==this.audio_metadata_.channel_count)return o.a.v(this.TAG,"Opus: Channel count changed from "+"".concat(this.audio_metadata_.channel_count," to ").concat(P.channel_count)),!0}else if(w.codec==="mp3"&&this.audio_metadata_.codec==="mp3"){var P;if((P=w.data).object_type!==this.audio_metadata_.object_type)return o.a.v(this.TAG,"MP3: AudioObjectType changed from "+"".concat(this.audio_metadata_.object_type," to ").concat(P.object_type)),!0;if(P.sample_rate!==this.audio_metadata_.sample_rate)return o.a.v(this.TAG,"MP3: SamplingFrequencyIndex changed from "+"".concat(this.audio_metadata_.sample_rate," to ").concat(P.sample_rate)),!0;if(P.channel_count!==this.audio_metadata_.channel_count)return o.a.v(this.TAG,"MP3: Channel count changed from "+"".concat(this.audio_metadata_.channel_count," to ").concat(P.channel_count)),!0}return!1},A.prototype.dispatchAudioInitSegment=function(w){var x={type:"audio"};if(x.id=this.audio_track_.id,x.timescale=1e3,x.duration=this.duration_,this.audio_metadata_.codec==="aac"){var P=w.codec==="aac"?w.data:null,F=new Pt(P);x.audioSampleRate=F.sampling_rate,x.channelCount=F.channel_count,x.codec=F.codec_mimetype,x.originalCodec=F.original_codec_mimetype,x.config=F.config,x.refSampleDuration=1024/x.audioSampleRate*x.timescale}else if(this.audio_metadata_.codec==="ac-3"){var $=w.codec==="ac-3"?w.data:null,K=new Ra($);x.audioSampleRate=K.sampling_rate,x.channelCount=K.channel_count,x.codec=K.codec_mimetype,x.originalCodec=K.original_codec_mimetype,x.config=K.config,x.refSampleDuration=1536/x.audioSampleRate*x.timescale}else if(this.audio_metadata_.codec==="ec-3"){var ne=w.codec==="ec-3"?w.data:null,ee=new _o(ne);x.audioSampleRate=ee.sampling_rate,x.channelCount=ee.channel_count,x.codec=ee.codec_mimetype,x.originalCodec=ee.original_codec_mimetype,x.config=ee.config,x.refSampleDuration=256*ee.num_blks/x.audioSampleRate*x.timescale}else this.audio_metadata_.codec==="opus"?(x.audioSampleRate=this.audio_metadata_.sample_rate,x.channelCount=this.audio_metadata_.channel_count,x.channelConfigCode=this.audio_metadata_.channel_config_code,x.codec="opus",x.originalCodec="opus",x.config=void 0,x.refSampleDuration=20):this.audio_metadata_.codec==="mp3"&&(x.audioSampleRate=this.audio_metadata_.sample_rate,x.channelCount=this.audio_metadata_.channel_count,x.codec="mp3",x.originalCodec="mp3",x.config=void 0);this.audio_init_segment_dispatched_==0&&o.a.v(this.TAG,"Generated first AudioSpecificConfig for mimeType: ".concat(x.codec)),this.onTrackMetadata("audio",x),this.audio_init_segment_dispatched_=!0,this.video_metadata_changed_=!1;var se=this.media_info_;se.hasAudio=!0,se.audioCodec=x.originalCodec,se.audioSampleRate=x.audioSampleRate,se.audioChannelCount=x.channelCount,se.hasVideo&&se.videoCodec?se.mimeType='video/mp2t; codecs="'.concat(se.videoCodec,",").concat(se.audioCodec,'"'):se.mimeType='video/mp2t; codecs="'.concat(se.audioCodec,'"'),se.isComplete()&&this.onMediaInfo(se)},A.prototype.dispatchPESPrivateDataDescriptor=function(w,x,P){var F=new Dn;F.pid=w,F.stream_type=x,F.descriptor=P,this.onPESPrivateDataDescriptor&&this.onPESPrivateDataDescriptor(F)},A.prototype.parsePESPrivateDataPayload=function(w,x,P,F,$){var K=new tn;if(K.pid=F,K.stream_id=$,K.len=w.byteLength,K.data=w,x!=null){var ne=Math.floor(x/this.timescale_);K.pts=ne}else K.nearest_pts=this.getNearestTimestampMilliseconds();if(P!=null){var ee=Math.floor(P/this.timescale_);K.dts=ee}this.onPESPrivateData&&this.onPESPrivateData(K)},A.prototype.parseTimedID3MetadataPayload=function(w,x,P,F,$){var K=new tn;if(K.pid=F,K.stream_id=$,K.len=w.byteLength,K.data=w,x!=null){var ne=Math.floor(x/this.timescale_);K.pts=ne}if(P!=null){var ee=Math.floor(P/this.timescale_);K.dts=ee}this.onTimedID3Metadata&&this.onTimedID3Metadata(K)},A.prototype.parseSynchronousKLVMetadataPayload=function(w,x,P,F,$){var K=new ui;if(K.pid=F,K.stream_id=$,K.len=w.byteLength,K.data=w,x!=null){var ne=Math.floor(x/this.timescale_);K.pts=ne}if(P!=null){var ee=Math.floor(P/this.timescale_);K.dts=ee}K.access_units=function(se){for(var le=[],ae=0;ae+5<se.byteLength;){var ce=se[ae+0],Te=se[ae+1],Be=se[ae+2],Pe=se[ae+3]<<8|se[ae+4]<<0,Je=se.slice(ae+5,ae+5+Pe);le.push({service_id:ce,sequence_number:Te,flags:Be,data:Je}),ae+=5+Pe}return le}(w),this.onSynchronousKLVMetadata&&this.onSynchronousKLVMetadata(K)},A.prototype.parseAsynchronousKLVMetadataPayload=function(w,x,P){var F=new tn;F.pid=x,F.stream_id=P,F.len=w.byteLength,F.data=w,this.onAsynchronousKLVMetadata&&this.onAsynchronousKLVMetadata(F)},A.prototype.parseSMPTE2038MetadataPayload=function(w,x,P,F,$){var K=new Qi;if(K.pid=F,K.stream_id=$,K.len=w.byteLength,K.data=w,x!=null){var ne=Math.floor(x/this.timescale_);K.pts=ne}if(K.nearest_pts=this.getNearestTimestampMilliseconds(),P!=null){var ee=Math.floor(P/this.timescale_);K.dts=ee}K.ancillaries=function(se){for(var le=new g(se),ae=0,ce=[];ae+=6,le.readBits(6)===0;){var Te=le.readBool();ae+=1;var Be=le.readBits(11);ae+=11;var Pe=le.readBits(12);ae+=12;var Je=255&le.readBits(10);ae+=10;var Ye=255&le.readBits(10);ae+=10;var Ge=255&le.readBits(10);ae+=10;for(var ut=new Uint8Array(Ge),bt=0;bt<Ge;bt++){var Xe=255&le.readBits(10);ae+=10,ut[bt]=Xe}le.readBits(10),ae+=10;var Ke="User Defined";Je===65?Ye===7&&(Ke="SCTE-104"):Je===95?Ye===220?Ke="ARIB STD-B37 (1SEG)":Ye===221?Ke="ARIB STD-B37 (ANALOG)":Ye===222?Ke="ARIB STD-B37 (SD)":Ye===223&&(Ke="ARIB STD-B37 (HD)"):Je===97&&(Ye===1?Ke="EIA-708":Ye===2&&(Ke="EIA-608")),ce.push({yc_indicator:Te,line_number:Be,horizontal_offset:Pe,did:Je,sdid:Ye,user_data:ut,description:Ke,information:{}}),le.readBits(8-(ae-Math.floor(ae/8))%8),ae+=(8-(ae-Math.floor(ae/8)))%8}return le.destroy(),le=null,ce}(w),this.onSMPTE2038Metadata&&this.onSMPTE2038Metadata(K)},A.prototype.getNearestTimestampMilliseconds=function(){return this.audio_last_sample_pts_!=null?Math.floor(this.audio_last_sample_pts_):this.last_pcr_!=null?Math.floor(this.last_pcr_/300/this.timescale_):void 0},A.prototype.getPcrBase=function(w){var x=33554432*w[6]+131072*w[7]+512*w[8]+2*w[9]+(128&w[10])/128+this.timestamp_offset_;return x+4294967296<this.last_pcr_base_&&(x+=8589934592,this.timestamp_offset_+=8589934592),this.last_pcr_base_=x,x},A.prototype.getTimestamp=function(w,x){var P=536870912*(14&w[x])+4194304*(255&w[x+1])+16384*(254&w[x+2])+128*(255&w[x+3])+(254&w[x+4])/2+this.timestamp_offset_;return P+4294967296<this.last_pcr_base_&&(P+=8589934592),P},A}(z),qn=function(C,A,w){for(var x,P=0,F=A.length;P<F;P++)!x&&P in A||(x||(x=Array.prototype.slice.call(A,0,P)),x[P]=A[P]);return C.concat(x||Array.prototype.slice.call(A))},Wn=function(){function C(){}return C.init=function(){for(var A in C.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],hvc1:[],hvcC:[],av01:[],av1C:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],mvex:[],mvhd:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[],".mp3":[],Opus:[],dOps:[],"ac-3":[],dac3:[],"ec-3":[],dec3:[],fLaC:[],dfLa:[]},C.types)C.types.hasOwnProperty(A)&&(C.types[A]=[A.charCodeAt(0),A.charCodeAt(1),A.charCodeAt(2),A.charCodeAt(3)]);var w=C.constants={};w.FTYP=new Uint8Array([105,115,111,109,0,0,0,1,105,115,111,109,97,118,99,49]),w.STSD_PREFIX=new Uint8Array([0,0,0,0,0,0,0,1]),w.STTS=new Uint8Array([0,0,0,0,0,0,0,0]),w.STSC=w.STCO=w.STTS,w.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),w.HDLR_VIDEO=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),w.HDLR_AUDIO=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]),w.DREF=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),w.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),w.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0])},C.box=function(A){for(var w=8,x=null,P=Array.prototype.slice.call(arguments,1),F=P.length,$=0;$<F;$++)w+=P[$].byteLength;(x=new Uint8Array(w))[0]=w>>>24&255,x[1]=w>>>16&255,x[2]=w>>>8&255,x[3]=255&w,x.set(A,4);var K=8;for($=0;$<F;$++)x.set(P[$],K),K+=P[$].byteLength;return x},C.generateInitSegment=function(A){var w=C.box(C.types.ftyp,C.constants.FTYP),x=C.moov(A),P=new Uint8Array(w.byteLength+x.byteLength);return P.set(w,0),P.set(x,w.byteLength),P},C.moov=function(A){var w=C.mvhd(A.timescale,A.duration),x=C.trak(A),P=C.mvex(A);return C.box(C.types.moov,w,x,P)},C.mvhd=function(A,w){return C.box(C.types.mvhd,new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,A>>>24&255,A>>>16&255,A>>>8&255,255&A,w>>>24&255,w>>>16&255,w>>>8&255,255&w,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]))},C.trak=function(A){return C.box(C.types.trak,C.tkhd(A),C.mdia(A))},C.tkhd=function(A){var w=A.id,x=A.duration,P=A.presentWidth,F=A.presentHeight;return C.box(C.types.tkhd,new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,w>>>24&255,w>>>16&255,w>>>8&255,255&w,0,0,0,0,x>>>24&255,x>>>16&255,x>>>8&255,255&x,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,P>>>8&255,255&P,0,0,F>>>8&255,255&F,0,0]))},C.mdia=function(A){return C.box(C.types.mdia,C.mdhd(A),C.hdlr(A),C.minf(A))},C.mdhd=function(A){var w=A.timescale,x=A.duration;return C.box(C.types.mdhd,new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,w>>>24&255,w>>>16&255,w>>>8&255,255&w,x>>>24&255,x>>>16&255,x>>>8&255,255&x,85,196,0,0]))},C.hdlr=function(A){var w=null;return w=A.type==="audio"?C.constants.HDLR_AUDIO:C.constants.HDLR_VIDEO,C.box(C.types.hdlr,w)},C.minf=function(A){var w=null;return w=A.type==="audio"?C.box(C.types.smhd,C.constants.SMHD):C.box(C.types.vmhd,C.constants.VMHD),C.box(C.types.minf,w,C.dinf(),C.stbl(A))},C.dinf=function(){return C.box(C.types.dinf,C.box(C.types.dref,C.constants.DREF))},C.stbl=function(A){return C.box(C.types.stbl,C.stsd(A),C.box(C.types.stts,C.constants.STTS),C.box(C.types.stsc,C.constants.STSC),C.box(C.types.stsz,C.constants.STSZ),C.box(C.types.stco,C.constants.STCO))},C.stsd=function(A){return A.type==="audio"?A.codec==="mp3"?C.box(C.types.stsd,C.constants.STSD_PREFIX,C.mp3(A)):A.codec==="ac-3"?C.box(C.types.stsd,C.constants.STSD_PREFIX,C.ac3(A)):A.codec==="ec-3"?C.box(C.types.stsd,C.constants.STSD_PREFIX,C.ec3(A)):A.codec==="opus"?C.box(C.types.stsd,C.constants.STSD_PREFIX,C.Opus(A)):A.codec=="flac"?C.box(C.types.stsd,C.constants.STSD_PREFIX,C.fLaC(A)):C.box(C.types.stsd,C.constants.STSD_PREFIX,C.mp4a(A)):A.type==="video"&&A.codec.startsWith("hvc1")?C.box(C.types.stsd,C.constants.STSD_PREFIX,C.hvc1(A)):A.type==="video"&&A.codec.startsWith("av01")?C.box(C.types.stsd,C.constants.STSD_PREFIX,C.av01(A)):C.box(C.types.stsd,C.constants.STSD_PREFIX,C.avc1(A))},C.mp3=function(A){var w=A.channelCount,x=A.audioSampleRate,P=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,w,0,16,0,0,0,0,x>>>8&255,255&x,0,0]);return C.box(C.types[".mp3"],P)},C.mp4a=function(A){var w=A.channelCount,x=A.audioSampleRate,P=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,w,0,16,0,0,0,0,x>>>8&255,255&x,0,0]);return C.box(C.types.mp4a,P,C.esds(A))},C.ac3=function(A){var w=A.channelCount,x=A.audioSampleRate,P=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,w,0,16,0,0,0,0,x>>>8&255,255&x,0,0]);return C.box(C.types["ac-3"],P,C.box(C.types.dac3,new Uint8Array(A.config)))},C.ec3=function(A){var w=A.channelCount,x=A.audioSampleRate,P=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,w,0,16,0,0,0,0,x>>>8&255,255&x,0,0]);return C.box(C.types["ec-3"],P,C.box(C.types.dec3,new Uint8Array(A.config)))},C.esds=function(A){var w=A.config||[],x=w.length,P=new Uint8Array([0,0,0,0,3,23+x,0,1,0,4,15+x,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([x]).concat(w).concat([6,1,2]));return C.box(C.types.esds,P)},C.Opus=function(A){var w=A.channelCount,x=A.audioSampleRate,P=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,w,0,16,0,0,0,0,x>>>8&255,255&x,0,0]);return C.box(C.types.Opus,P,C.dOps(A))},C.dOps=function(A){var w=A.channelCount,x=A.channelConfigCode,P=A.audioSampleRate;if(A.config)return C.box(C.types.dOps,A.config);var F=[];switch(x){case 1:case 2:F=[0];break;case 0:F=[255,1,1,0,1];break;case 128:F=[255,2,0,0,1];break;case 3:F=[1,2,1,0,2,1];break;case 4:F=[1,2,2,0,1,2,3];break;case 5:F=[1,3,2,0,4,1,2,3];break;case 6:F=[1,4,2,0,4,1,2,3,5];break;case 7:F=[1,4,2,0,4,1,2,3,5,6];break;case 8:F=[1,5,3,0,6,1,2,3,4,5,7];break;case 130:F=[1,1,2,0,1];break;case 131:F=[1,1,3,0,1,2];break;case 132:F=[1,1,4,0,1,2,3];break;case 133:F=[1,1,5,0,1,2,3,4];break;case 134:F=[1,1,6,0,1,2,3,4,5];break;case 135:F=[1,1,7,0,1,2,3,4,5,6];break;case 136:F=[1,1,8,0,1,2,3,4,5,6,7]}var $=new Uint8Array(qn([0,w,0,0,P>>>24&255,P>>>17&255,P>>>8&255,P>>>0&255,0,0],F));return C.box(C.types.dOps,$)},C.fLaC=function(A){var w=A.channelCount,x=Math.min(A.audioSampleRate,65535),P=A.sampleSize,F=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,w,0,P,0,0,0,0,x>>>8&255,255&x,0,0]);return C.box(C.types.fLaC,F,C.dfLa(A))},C.dfLa=function(A){var w=new Uint8Array(qn([0,0,0,0],A.config));return C.box(C.types.dfLa,w)},C.avc1=function(A){var w=A.avcc,x=A.codecWidth,P=A.codecHeight,F=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,x>>>8&255,255&x,P>>>8&255,255&P,0,72,0,0,0,72,0,0,0,0,0,0,0,1,10,120,113,113,47,102,108,118,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,255,255]);return C.box(C.types.avc1,F,C.box(C.types.avcC,w))},C.hvc1=function(A){var w=A.hvcc,x=A.codecWidth,P=A.codecHeight,F=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,x>>>8&255,255&x,P>>>8&255,255&P,0,72,0,0,0,72,0,0,0,0,0,0,0,1,10,120,113,113,47,102,108,118,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,255,255]);return C.box(C.types.hvc1,F,C.box(C.types.hvcC,w))},C.av01=function(A){var w=A.av1c,x=A.codecWidth||192,P=A.codecHeight||108,F=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,x>>>8&255,255&x,P>>>8&255,255&P,0,72,0,0,0,72,0,0,0,0,0,0,0,1,10,120,113,113,47,102,108,118,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,255,255]);return C.box(C.types.av01,F,C.box(C.types.av1C,w))},C.mvex=function(A){return C.box(C.types.mvex,C.trex(A))},C.trex=function(A){var w=A.id,x=new Uint8Array([0,0,0,0,w>>>24&255,w>>>16&255,w>>>8&255,255&w,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return C.box(C.types.trex,x)},C.moof=function(A,w){return C.box(C.types.moof,C.mfhd(A.sequenceNumber),C.traf(A,w))},C.mfhd=function(A){var w=new Uint8Array([0,0,0,0,A>>>24&255,A>>>16&255,A>>>8&255,255&A]);return C.box(C.types.mfhd,w)},C.traf=function(A,w){var x=A.id,P=C.box(C.types.tfhd,new Uint8Array([0,0,0,0,x>>>24&255,x>>>16&255,x>>>8&255,255&x])),F=C.box(C.types.tfdt,new Uint8Array([0,0,0,0,w>>>24&255,w>>>16&255,w>>>8&255,255&w])),$=C.sdtp(A),K=C.trun(A,$.byteLength+16+16+8+16+8+8);return C.box(C.types.traf,P,F,K,$)},C.sdtp=function(A){for(var w=A.samples||[],x=w.length,P=new Uint8Array(4+x),F=0;F<x;F++){var $=w[F].flags;P[F+4]=$.isLeading<<6|$.dependsOn<<4|$.isDependedOn<<2|$.hasRedundancy}return C.box(C.types.sdtp,P)},C.trun=function(A,w){var x=A.samples||[],P=x.length,F=12+16*P,$=new Uint8Array(F);w+=8+F,$.set([0,0,15,1,P>>>24&255,P>>>16&255,P>>>8&255,255&P,w>>>24&255,w>>>16&255,w>>>8&255,255&w],0);for(var K=0;K<P;K++){var ne=x[K].duration,ee=x[K].size,se=x[K].flags,le=x[K].cts;$.set([ne>>>24&255,ne>>>16&255,ne>>>8&255,255&ne,ee>>>24&255,ee>>>16&255,ee>>>8&255,255&ee,se.isLeading<<2|se.dependsOn,se.isDependedOn<<6|se.hasRedundancy<<4|se.isNonSync,0,0,le>>>24&255,le>>>16&255,le>>>8&255,255&le],12+16*K)}return C.box(C.types.trun,$)},C.mdat=function(A){return C.box(C.types.mdat,A)},C}();Wn.init();var lr=Wn,Xr=function(){function C(){}return C.getSilentFrame=function(A,w){if(A==="mp4a.40.2"){if(w===1)return new Uint8Array([0,200,0,128,35,128]);if(w===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(w===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(w===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(w===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(w===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(w===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(w===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(w===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}return null},C}(),At=i(11),nn=function(){function C(A){this.TAG="MP4Remuxer",this._config=A,this._isLive=A.isLive===!0,this._dtsBase=-1,this._dtsBaseInited=!1,this._audioDtsBase=1/0,this._videoDtsBase=1/0,this._audioNextDts=void 0,this._videoNextDts=void 0,this._audioStashedLastSample=null,this._videoStashedLastSample=null,this._audioMeta=null,this._videoMeta=null,this._audioSegmentInfoList=new At.c("audio"),this._videoSegmentInfoList=new At.c("video"),this._onInitSegment=null,this._onMediaSegment=null,this._forceFirstIDR=!(!l.a.chrome||!(l.a.version.major<50||l.a.version.major===50&&l.a.version.build<2661)),this._fillSilentAfterSeek=l.a.msedge||l.a.msie,this._mp3UseMpegAudio=!l.a.firefox,this._fillAudioTimestampGap=this._config.fixAudioTimestampGap}return C.prototype.destroy=function(){this._dtsBase=-1,this._dtsBaseInited=!1,this._audioMeta=null,this._videoMeta=null,this._audioSegmentInfoList.clear(),this._audioSegmentInfoList=null,this._videoSegmentInfoList.clear(),this._videoSegmentInfoList=null,this._onInitSegment=null,this._onMediaSegment=null},C.prototype.bindDataSource=function(A){return A.onDataAvailable=this.remux.bind(this),A.onTrackMetadata=this._onTrackMetadataReceived.bind(this),this},Object.defineProperty(C.prototype,"onInitSegment",{get:function(){return this._onInitSegment},set:function(A){this._onInitSegment=A},enumerable:!1,configurable:!0}),Object.defineProperty(C.prototype,"onMediaSegment",{get:function(){return this._onMediaSegment},set:function(A){this._onMediaSegment=A},enumerable:!1,configurable:!0}),C.prototype.insertDiscontinuity=function(){this._audioNextDts=this._videoNextDts=void 0},C.prototype.seek=function(A){this._audioStashedLastSample=null,this._videoStashedLastSample=null,this._videoSegmentInfoList.clear(),this._audioSegmentInfoList.clear()},C.prototype.remux=function(A,w){if(!this._onMediaSegment)throw new f.a("MP4Remuxer: onMediaSegment callback must be specificed!");this._dtsBaseInited||this._calculateDtsBase(A,w),w&&this._remuxVideo(w),A&&this._remuxAudio(A)},C.prototype._onTrackMetadataReceived=function(A,w){var x=null,P="mp4",F=w.codec;if(A==="audio")this._audioMeta=w,w.codec==="mp3"&&this._mp3UseMpegAudio?(P="mpeg",F="",x=new Uint8Array):x=lr.generateInitSegment(w);else{if(A!=="video")return;this._videoMeta=w,x=lr.generateInitSegment(w)}if(!this._onInitSegment)throw new f.a("MP4Remuxer: onInitSegment callback must be specified!");this._onInitSegment(A,{type:A,data:x.buffer,codec:F,container:"".concat(A,"/").concat(P),mediaDuration:w.duration})},C.prototype._calculateDtsBase=function(A,w){this._dtsBaseInited||(A&&A.samples&&A.samples.length&&(this._audioDtsBase=A.samples[0].dts),w&&w.samples&&w.samples.length&&(this._videoDtsBase=w.samples[0].dts),this._dtsBase=Math.min(this._audioDtsBase,this._videoDtsBase),this._dtsBaseInited=!0)},C.prototype.getTimestampBase=function(){if(this._dtsBaseInited)return this._dtsBase},C.prototype.flushStashedSamples=function(){var A=this._videoStashedLastSample,w=this._audioStashedLastSample,x={type:"video",id:1,sequenceNumber:0,samples:[],length:0};A!=null&&(x.samples.push(A),x.length=A.length);var P={type:"audio",id:2,sequenceNumber:0,samples:[],length:0};w!=null&&(P.samples.push(w),P.length=w.length),this._videoStashedLastSample=null,this._audioStashedLastSample=null,this._remuxVideo(x,!0),this._remuxAudio(P,!0)},C.prototype._remuxAudio=function(A,w){if(this._audioMeta!=null){var x,P=A,F=P.samples,$=void 0,K=-1,ne=this._audioMeta.refSampleDuration,ee=this._audioMeta.codec==="mp3"&&this._mp3UseMpegAudio,se=this._dtsBaseInited&&this._audioNextDts===void 0,le=!1;if(F&&F.length!==0&&(F.length!==1||w)){var ae=0,ce=null,Te=0;ee?(ae=0,Te=P.length):(ae=8,Te=8+P.length);var Be=null;if(F.length>1&&(Te-=(Be=F.pop()).length),this._audioStashedLastSample!=null){var Pe=this._audioStashedLastSample;this._audioStashedLastSample=null,F.unshift(Pe),Te+=Pe.length}Be!=null&&(this._audioStashedLastSample=Be);var Je=F[0].dts-this._dtsBase;if(this._audioNextDts)$=Je-this._audioNextDts;else if(this._audioSegmentInfoList.isEmpty())$=0,this._fillSilentAfterSeek&&!this._videoSegmentInfoList.isEmpty()&&this._audioMeta.originalCodec!=="mp3"&&(le=!0);else{var Ye=this._audioSegmentInfoList.getLastSampleBefore(Je);if(Ye!=null){var Ge=Je-(Ye.originalDts+Ye.duration);Ge<=3&&(Ge=0),$=Je-(Ye.dts+Ye.duration+Ge)}else $=0}if(le){var ut=Je-$,bt=this._videoSegmentInfoList.getLastSegmentBefore(Je);if(bt!=null&&bt.beginDts<ut){if(vn=Xr.getSilentFrame(this._audioMeta.originalCodec,this._audioMeta.channelCount)){var Xe=bt.beginDts,Ke=ut-bt.beginDts;o.a.v(this.TAG,"InsertPrefixSilentAudio: dts: ".concat(Xe,", duration: ").concat(Ke)),F.unshift({unit:vn,dts:Xe,pts:Xe}),Te+=vn.byteLength}}else le=!1}for(var Rt=[],dt=0;dt<F.length;dt++){var pt=(Pe=F[dt]).unit,Ot=Pe.dts-this._dtsBase,Jt=(Xe=Ot,!1),yt=null,kt=0;if(!(Ot<-.001)){if(this._audioMeta.codec!=="mp3"&&ne!=null){var ht=Ot;if(this._audioNextDts&&(ht=this._audioNextDts),($=Ot-ht)<=-3*ne){o.a.w(this.TAG,"Dropping 1 audio frame (originalDts: ".concat(Ot," ms ,curRefDts: ").concat(ht," ms)  due to dtsCorrection: ").concat($," ms overlap."));continue}if($>=3*ne&&this._fillAudioTimestampGap&&!l.a.safari){Jt=!0;var vn,Ar=Math.floor($/ne);o.a.w(this.TAG,`Large audio timestamp gap detected, may cause AV sync to drift. Silent frames will be generated to avoid unsync.
`+"originalDts: ".concat(Ot," ms, curRefDts: ").concat(ht," ms, ")+"dtsCorrection: ".concat(Math.round($)," ms, generate: ").concat(Ar," frames")),Xe=Math.floor(ht),kt=Math.floor(ht+ne)-Xe,(vn=Xr.getSilentFrame(this._audioMeta.originalCodec,this._audioMeta.channelCount))==null&&(o.a.w(this.TAG,"Unable to generate silent frame for "+"".concat(this._audioMeta.originalCodec," with ").concat(this._audioMeta.channelCount," channels, repeat last frame")),vn=pt),yt=[];for(var On=0;On<Ar;On++){ht+=ne;var Rr=Math.floor(ht),cr=Math.floor(ht+ne)-Rr,Yn={dts:Rr,pts:Rr,cts:0,unit:vn,size:vn.byteLength,duration:cr,originalDts:Ot,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0}};yt.push(Yn),Te+=Yn.size}this._audioNextDts=ht+ne}else Xe=Math.floor(ht),kt=Math.floor(ht+ne)-Xe,this._audioNextDts=ht+ne}else Xe=Ot-$,dt!==F.length-1?kt=F[dt+1].dts-this._dtsBase-$-Xe:Be!=null?kt=Be.dts-this._dtsBase-$-Xe:kt=Rt.length>=1?Rt[Rt.length-1].duration:Math.floor(ne),this._audioNextDts=Xe+kt;K===-1&&(K=Xe),Rt.push({dts:Xe,pts:Xe,cts:0,unit:Pe.unit,size:Pe.unit.byteLength,duration:kt,originalDts:Ot,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0}}),Jt&&Rt.push.apply(Rt,yt)}}if(Rt.length===0)return P.samples=[],void(P.length=0);for(ee?ce=new Uint8Array(Te):((ce=new Uint8Array(Te))[0]=Te>>>24&255,ce[1]=Te>>>16&255,ce[2]=Te>>>8&255,ce[3]=255&Te,ce.set(lr.types.mdat,4)),dt=0;dt<Rt.length;dt++)pt=Rt[dt].unit,ce.set(pt,ae),ae+=pt.byteLength;var _r=Rt[Rt.length-1];x=_r.dts+_r.duration;var Vt=new At.b;Vt.beginDts=K,Vt.endDts=x,Vt.beginPts=K,Vt.endPts=x,Vt.originalBeginDts=Rt[0].originalDts,Vt.originalEndDts=_r.originalDts+_r.duration,Vt.firstSample=new At.d(Rt[0].dts,Rt[0].pts,Rt[0].duration,Rt[0].originalDts,!1),Vt.lastSample=new At.d(_r.dts,_r.pts,_r.duration,_r.originalDts,!1),this._isLive||this._audioSegmentInfoList.append(Vt),P.samples=Rt,P.sequenceNumber++;var Ji=null;Ji=ee?new Uint8Array:lr.moof(P,K),P.samples=[],P.length=0;var xs={type:"audio",data:this._mergeBoxes(Ji,ce).buffer,sampleCount:Rt.length,info:Vt};ee&&se&&(xs.timestampOffset=K),this._onMediaSegment("audio",xs)}}},C.prototype._remuxVideo=function(A,w){if(this._videoMeta!=null){var x,P,F=A,$=F.samples,K=void 0,ne=-1,ee=-1;if($&&$.length!==0&&($.length!==1||w)){var se=8,le=null,ae=8+A.length,ce=null;if($.length>1&&(ae-=(ce=$.pop()).length),this._videoStashedLastSample!=null){var Te=this._videoStashedLastSample;this._videoStashedLastSample=null,$.unshift(Te),ae+=Te.length}ce!=null&&(this._videoStashedLastSample=ce);var Be=$[0].dts-this._dtsBase;if(this._videoNextDts)K=Be-this._videoNextDts;else if(this._videoSegmentInfoList.isEmpty())K=0;else{var Pe=this._videoSegmentInfoList.getLastSampleBefore(Be);if(Pe!=null){var Je=Be-(Pe.originalDts+Pe.duration);Je<=3&&(Je=0),K=Be-(Pe.dts+Pe.duration+Je)}else K=0}for(var Ye=new At.b,Ge=[],ut=0;ut<$.length;ut++){var bt=(Te=$[ut]).dts-this._dtsBase,Xe=Te.isKeyframe,Ke=bt-K,Rt=Te.cts,dt=Ke+Rt;ne===-1&&(ne=Ke,ee=dt);var pt=0;if(ut!==$.length-1?pt=$[ut+1].dts-this._dtsBase-K-Ke:ce!=null?pt=ce.dts-this._dtsBase-K-Ke:pt=Ge.length>=1?Ge[Ge.length-1].duration:Math.floor(this._videoMeta.refSampleDuration),Xe){var Ot=new At.d(Ke,dt,pt,Te.dts,!0);Ot.fileposition=Te.fileposition,Ye.appendSyncPoint(Ot)}Ge.push({dts:Ke,pts:dt,cts:Rt,units:Te.units,size:Te.length,isKeyframe:Xe,duration:pt,originalDts:bt,flags:{isLeading:0,dependsOn:Xe?2:1,isDependedOn:Xe?1:0,hasRedundancy:0,isNonSync:Xe?0:1}})}for((le=new Uint8Array(ae))[0]=ae>>>24&255,le[1]=ae>>>16&255,le[2]=ae>>>8&255,le[3]=255&ae,le.set(lr.types.mdat,4),ut=0;ut<Ge.length;ut++)for(var Jt=Ge[ut].units;Jt.length;){var yt=Jt.shift().data;le.set(yt,se),se+=yt.byteLength}var kt=Ge[Ge.length-1];if(x=kt.dts+kt.duration,P=kt.pts+kt.duration,this._videoNextDts=x,Ye.beginDts=ne,Ye.endDts=x,Ye.beginPts=ee,Ye.endPts=P,Ye.originalBeginDts=Ge[0].originalDts,Ye.originalEndDts=kt.originalDts+kt.duration,Ye.firstSample=new At.d(Ge[0].dts,Ge[0].pts,Ge[0].duration,Ge[0].originalDts,Ge[0].isKeyframe),Ye.lastSample=new At.d(kt.dts,kt.pts,kt.duration,kt.originalDts,kt.isKeyframe),this._isLive||this._videoSegmentInfoList.append(Ye),F.samples=Ge,F.sequenceNumber++,this._forceFirstIDR){var ht=Ge[0].flags;ht.dependsOn=2,ht.isNonSync=0}var vn=lr.moof(F,ne);F.samples=[],F.length=0,this._onMediaSegment("video",{type:"video",data:this._mergeBoxes(vn,le).buffer,sampleCount:Ge.length,info:Ye})}}},C.prototype._mergeBoxes=function(A,w){var x=new Uint8Array(A.byteLength+w.byteLength);return x.set(A,0),x.set(w,A.byteLength),x},C}(),Ov=i(14),Cn=i(1),Jc=(i(2),function(){function C(A,w){this.TAG="TransmuxingController",this._emitter=new a.a,this._config=w,A.segments||(A.segments=[{duration:A.duration,filesize:A.filesize,url:A.url}]),typeof A.cors!="boolean"&&(A.cors=!0),typeof A.withCredentials!="boolean"&&(A.withCredentials=!1),this._mediaDataSource=A,this._currentSegmentIndex=0;var x=0;this._mediaDataSource.segments.forEach(function(P){P.timestampBase=x,x+=P.duration,P.cors=A.cors,P.withCredentials=A.withCredentials,w.referrerPolicy&&(P.referrerPolicy=w.referrerPolicy)}),isNaN(x)||this._mediaDataSource.duration===x||(this._mediaDataSource.duration=x),this._mediaInfo=null,this._demuxer=null,this._remuxer=null,this._ioctl=null,this._pendingSeekTime=null,this._pendingResolveSeekPoint=null,this._statisticsReporter=null}return C.prototype.destroy=function(){this._mediaInfo=null,this._mediaDataSource=null,this._statisticsReporter&&this._disableStatisticsReporter(),this._ioctl&&(this._ioctl.destroy(),this._ioctl=null),this._demuxer&&(this._demuxer.destroy(),this._demuxer=null),this._remuxer&&(this._remuxer.destroy(),this._remuxer=null),this._emitter.removeAllListeners(),this._emitter=null},C.prototype.on=function(A,w){this._emitter.addListener(A,w)},C.prototype.off=function(A,w){this._emitter.removeListener(A,w)},C.prototype.start=function(){this._loadSegment(0),this._enableStatisticsReporter()},C.prototype._loadSegment=function(A,w){this._currentSegmentIndex=A;var x=this._mediaDataSource.segments[A],P=this._ioctl=new Ov.a(x,this._config,A);P.onError=this._onIOException.bind(this),P.onSeeked=this._onIOSeeked.bind(this),P.onComplete=this._onIOComplete.bind(this),P.onRedirect=this._onIORedirect.bind(this),P.onRecoveredEarlyEof=this._onIORecoveredEarlyEof.bind(this),w?this._demuxer.bindDataSource(this._ioctl):P.onDataArrival=this._onInitChunkArrival.bind(this),P.open(w)},C.prototype.stop=function(){this._internalAbort(),this._disableStatisticsReporter()},C.prototype._internalAbort=function(){this._ioctl&&(this._ioctl.destroy(),this._ioctl=null)},C.prototype.pause=function(){this._ioctl&&this._ioctl.isWorking()&&(this._ioctl.pause(),this._disableStatisticsReporter())},C.prototype.resume=function(){this._ioctl&&this._ioctl.isPaused()&&(this._ioctl.resume(),this._enableStatisticsReporter())},C.prototype.seek=function(A){if(this._mediaInfo!=null&&this._mediaInfo.isSeekable()){var w=this._searchSegmentIndexContains(A);if(w===this._currentSegmentIndex){var x=this._mediaInfo.segments[w];if(x==null)this._pendingSeekTime=A;else{var P=x.getNearestKeyframe(A);this._remuxer.seek(P.milliseconds),this._ioctl.seek(P.fileposition),this._pendingResolveSeekPoint=P.milliseconds}}else{var F=this._mediaInfo.segments[w];F==null?(this._pendingSeekTime=A,this._internalAbort(),this._remuxer.seek(),this._remuxer.insertDiscontinuity(),this._loadSegment(w)):(P=F.getNearestKeyframe(A),this._internalAbort(),this._remuxer.seek(A),this._remuxer.insertDiscontinuity(),this._demuxer.resetMediaInfo(),this._demuxer.timestampBase=this._mediaDataSource.segments[w].timestampBase,this._loadSegment(w,P.fileposition),this._pendingResolveSeekPoint=P.milliseconds,this._reportSegmentMediaInfo(w))}this._enableStatisticsReporter()}},C.prototype._searchSegmentIndexContains=function(A){for(var w=this._mediaDataSource.segments,x=w.length-1,P=0;P<w.length;P++)if(A<w[P].timestampBase){x=P-1;break}return x},C.prototype._onInitChunkArrival=function(A,w){var x=this,P=0;if(w>0)this._demuxer.bindDataSource(this._ioctl),this._demuxer.timestampBase=this._mediaDataSource.segments[this._currentSegmentIndex].timestampBase,P=this._demuxer.parseChunks(A,w);else{var F=null;(F=M.probe(A)).match&&(this._setupFLVDemuxerRemuxer(F),P=this._demuxer.parseChunks(A,w)),F.match||F.needMoreData||(F=sn.probe(A)).match&&(this._setupTSDemuxerRemuxer(F),P=this._demuxer.parseChunks(A,w)),F.match||F.needMoreData||(F=null,o.a.e(this.TAG,"Non MPEG-TS/FLV, Unsupported media type!"),Promise.resolve().then(function(){x._internalAbort()}),this._emitter.emit(Cn.a.DEMUX_ERROR,v.a.FORMAT_UNSUPPORTED,"Non MPEG-TS/FLV, Unsupported media type!"))}return P},C.prototype._setupFLVDemuxerRemuxer=function(A){this._demuxer=new M(A,this._config),this._remuxer||(this._remuxer=new nn(this._config));var w=this._mediaDataSource;w.duration==null||isNaN(w.duration)||(this._demuxer.overridedDuration=w.duration),typeof w.hasAudio=="boolean"&&(this._demuxer.overridedHasAudio=w.hasAudio),typeof w.hasVideo=="boolean"&&(this._demuxer.overridedHasVideo=w.hasVideo),this._demuxer.timestampBase=w.segments[this._currentSegmentIndex].timestampBase,this._demuxer.onError=this._onDemuxException.bind(this),this._demuxer.onMediaInfo=this._onMediaInfo.bind(this),this._demuxer.onMetaDataArrived=this._onMetaDataArrived.bind(this),this._demuxer.onScriptDataArrived=this._onScriptDataArrived.bind(this),this._remuxer.bindDataSource(this._demuxer.bindDataSource(this._ioctl)),this._remuxer.onInitSegment=this._onRemuxerInitSegmentArrival.bind(this),this._remuxer.onMediaSegment=this._onRemuxerMediaSegmentArrival.bind(this)},C.prototype._setupTSDemuxerRemuxer=function(A){var w=this._demuxer=new sn(A,this._config);this._remuxer||(this._remuxer=new nn(this._config)),w.onError=this._onDemuxException.bind(this),w.onMediaInfo=this._onMediaInfo.bind(this),w.onMetaDataArrived=this._onMetaDataArrived.bind(this),w.onTimedID3Metadata=this._onTimedID3Metadata.bind(this),w.onSynchronousKLVMetadata=this._onSynchronousKLVMetadata.bind(this),w.onAsynchronousKLVMetadata=this._onAsynchronousKLVMetadata.bind(this),w.onSMPTE2038Metadata=this._onSMPTE2038Metadata.bind(this),w.onSCTE35Metadata=this._onSCTE35Metadata.bind(this),w.onPESPrivateDataDescriptor=this._onPESPrivateDataDescriptor.bind(this),w.onPESPrivateData=this._onPESPrivateData.bind(this),this._remuxer.bindDataSource(this._demuxer),this._demuxer.bindDataSource(this._ioctl),this._remuxer.onInitSegment=this._onRemuxerInitSegmentArrival.bind(this),this._remuxer.onMediaSegment=this._onRemuxerMediaSegmentArrival.bind(this)},C.prototype._onMediaInfo=function(A){var w=this;this._mediaInfo==null&&(this._mediaInfo=Object.assign({},A),this._mediaInfo.keyframesIndex=null,this._mediaInfo.segments=[],this._mediaInfo.segmentCount=this._mediaDataSource.segments.length,Object.setPrototypeOf(this._mediaInfo,c.a.prototype));var x=Object.assign({},A);Object.setPrototypeOf(x,c.a.prototype),this._mediaInfo.segments[this._currentSegmentIndex]=x,this._reportSegmentMediaInfo(this._currentSegmentIndex),this._pendingSeekTime!=null&&Promise.resolve().then(function(){var P=w._pendingSeekTime;w._pendingSeekTime=null,w.seek(P)})},C.prototype._onMetaDataArrived=function(A){this._emitter.emit(Cn.a.METADATA_ARRIVED,A)},C.prototype._onScriptDataArrived=function(A){this._emitter.emit(Cn.a.SCRIPTDATA_ARRIVED,A)},C.prototype._onTimedID3Metadata=function(A){var w=this._remuxer.getTimestampBase();w!=null&&(A.pts!=null&&(A.pts-=w),A.dts!=null&&(A.dts-=w),this._emitter.emit(Cn.a.TIMED_ID3_METADATA_ARRIVED,A))},C.prototype._onSynchronousKLVMetadata=function(A){var w=this._remuxer.getTimestampBase();w!=null&&(A.pts!=null&&(A.pts-=w),A.dts!=null&&(A.dts-=w),this._emitter.emit(Cn.a.SYNCHRONOUS_KLV_METADATA_ARRIVED,A))},C.prototype._onAsynchronousKLVMetadata=function(A){this._emitter.emit(Cn.a.ASYNCHRONOUS_KLV_METADATA_ARRIVED,A)},C.prototype._onSMPTE2038Metadata=function(A){var w=this._remuxer.getTimestampBase();w!=null&&(A.pts!=null&&(A.pts-=w),A.dts!=null&&(A.dts-=w),A.nearest_pts!=null&&(A.nearest_pts-=w),this._emitter.emit(Cn.a.SMPTE2038_METADATA_ARRIVED,A))},C.prototype._onSCTE35Metadata=function(A){var w=this._remuxer.getTimestampBase();w!=null&&(A.pts!=null&&(A.pts-=w),A.nearest_pts!=null&&(A.nearest_pts-=w),this._emitter.emit(Cn.a.SCTE35_METADATA_ARRIVED,A))},C.prototype._onPESPrivateDataDescriptor=function(A){this._emitter.emit(Cn.a.PES_PRIVATE_DATA_DESCRIPTOR,A)},C.prototype._onPESPrivateData=function(A){var w=this._remuxer.getTimestampBase();w!=null&&(A.pts!=null&&(A.pts-=w),A.nearest_pts!=null&&(A.nearest_pts-=w),A.dts!=null&&(A.dts-=w),this._emitter.emit(Cn.a.PES_PRIVATE_DATA_ARRIVED,A))},C.prototype._onIOSeeked=function(){this._remuxer.insertDiscontinuity()},C.prototype._onIOComplete=function(A){var w=A+1;w<this._mediaDataSource.segments.length?(this._internalAbort(),this._remuxer&&this._remuxer.flushStashedSamples(),this._loadSegment(w)):(this._remuxer&&this._remuxer.flushStashedSamples(),this._emitter.emit(Cn.a.LOADING_COMPLETE),this._disableStatisticsReporter())},C.prototype._onIORedirect=function(A){var w=this._ioctl.extraData;this._mediaDataSource.segments[w].redirectedURL=A},C.prototype._onIORecoveredEarlyEof=function(){this._emitter.emit(Cn.a.RECOVERED_EARLY_EOF)},C.prototype._onIOException=function(A,w){o.a.e(this.TAG,"IOException: type = ".concat(A,", code = ").concat(w.code,", msg = ").concat(w.msg)),this._emitter.emit(Cn.a.IO_ERROR,A,w),this._disableStatisticsReporter()},C.prototype._onDemuxException=function(A,w){o.a.e(this.TAG,"DemuxException: type = ".concat(A,", info = ").concat(w)),this._emitter.emit(Cn.a.DEMUX_ERROR,A,w)},C.prototype._onRemuxerInitSegmentArrival=function(A,w){this._emitter.emit(Cn.a.INIT_SEGMENT,A,w)},C.prototype._onRemuxerMediaSegmentArrival=function(A,w){if(this._pendingSeekTime==null&&(this._emitter.emit(Cn.a.MEDIA_SEGMENT,A,w),this._pendingResolveSeekPoint!=null&&A==="video")){var x=w.info.syncPoints,P=this._pendingResolveSeekPoint;this._pendingResolveSeekPoint=null,l.a.safari&&x.length>0&&x[0].originalDts===P&&(P=x[0].pts),this._emitter.emit(Cn.a.RECOMMEND_SEEKPOINT,P)}},C.prototype._enableStatisticsReporter=function(){this._statisticsReporter==null&&(this._statisticsReporter=self.setInterval(this._reportStatisticsInfo.bind(this),this._config.statisticsInfoReportInterval))},C.prototype._disableStatisticsReporter=function(){this._statisticsReporter&&(self.clearInterval(this._statisticsReporter),this._statisticsReporter=null)},C.prototype._reportSegmentMediaInfo=function(A){var w=this._mediaInfo.segments[A],x=Object.assign({},w);x.duration=this._mediaInfo.duration,x.segmentCount=this._mediaInfo.segmentCount,delete x.segments,delete x.keyframesIndex,this._emitter.emit(Cn.a.MEDIA_INFO,x)},C.prototype._reportStatisticsInfo=function(){var A={};A.url=this._ioctl.currentURL,A.hasRedirect=this._ioctl.hasRedirect,A.hasRedirect&&(A.redirectedURL=this._ioctl.currentRedirectedURL),A.speed=this._ioctl.currentSpeed,A.loaderType=this._ioctl.loaderType,A.currentSegmentIndex=this._currentSegmentIndex,A.totalSegmentCount=this._mediaDataSource.segments.length,this._emitter.emit(Cn.a.STATISTICS_INFO,A)},C}());r.a=Jc},function(n,r,i){var s,a=i(0),o=function(){function O(){this._firstCheckpoint=0,this._lastCheckpoint=0,this._intervalBytes=0,this._totalBytes=0,this._lastSecondBytes=0,self.performance&&self.performance.now?this._now=self.performance.now.bind(self.performance):this._now=Date.now}return O.prototype.reset=function(){this._firstCheckpoint=this._lastCheckpoint=0,this._totalBytes=this._intervalBytes=0,this._lastSecondBytes=0},O.prototype.addBytes=function(k){this._firstCheckpoint===0?(this._firstCheckpoint=this._now(),this._lastCheckpoint=this._firstCheckpoint,this._intervalBytes+=k,this._totalBytes+=k):this._now()-this._lastCheckpoint<1e3?(this._intervalBytes+=k,this._totalBytes+=k):(this._lastSecondBytes=this._intervalBytes,this._intervalBytes=k,this._totalBytes+=k,this._lastCheckpoint=this._now())},Object.defineProperty(O.prototype,"currentKBps",{get:function(){this.addBytes(0);var k=(this._now()-this._lastCheckpoint)/1e3;return k==0&&(k=1),this._intervalBytes/k/1024},enumerable:!1,configurable:!0}),Object.defineProperty(O.prototype,"lastSecondKBps",{get:function(){return this.addBytes(0),this._lastSecondBytes!==0?this._lastSecondBytes/1024:this._now()-this._lastCheckpoint>=500?this.currentKBps:0},enumerable:!1,configurable:!0}),Object.defineProperty(O.prototype,"averageKBps",{get:function(){var k=(this._now()-this._firstCheckpoint)/1e3;return this._totalBytes/k/1024},enumerable:!1,configurable:!0}),O}(),l=i(2),c=i(5),u=i(3),d=(s=function(O,k){return(s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(I,R){I.__proto__=R}||function(I,R){for(var M in R)Object.prototype.hasOwnProperty.call(R,M)&&(I[M]=R[M])})(O,k)},function(O,k){if(typeof k!="function"&&k!==null)throw new TypeError("Class extends value "+String(k)+" is not a constructor or null");function I(){this.constructor=O}s(O,k),O.prototype=k===null?Object.create(k):(I.prototype=k.prototype,new I)}),h=function(O){function k(I,R){var M=O.call(this,"fetch-stream-loader")||this;return M.TAG="FetchStreamLoader",M._seekHandler=I,M._config=R,M._needStash=!0,M._requestAbort=!1,M._abortController=null,M._contentLength=null,M._receivedLength=0,M}return d(k,O),k.isSupported=function(){try{var I=c.a.msedge&&c.a.version.minor>=15048,R=!c.a.msedge||I;return self.fetch&&self.ReadableStream&&R}catch{return!1}},k.prototype.destroy=function(){this.isWorking()&&this.abort(),O.prototype.destroy.call(this)},k.prototype.open=function(I,R){var M=this;this._dataSource=I,this._range=R;var z=I.url;this._config.reuseRedirectedURL&&I.redirectedURL!=null&&(z=I.redirectedURL);var Z=this._seekHandler.getConfig(z,R),W=new self.Headers;if(typeof Z.headers=="object"){var re=Z.headers;for(var X in re)re.hasOwnProperty(X)&&W.append(X,re[X])}var oe={method:"GET",headers:W,mode:"cors",cache:"default",referrerPolicy:"no-referrer-when-downgrade"};if(typeof this._config.headers=="object")for(var X in this._config.headers)W.append(X,this._config.headers[X]);I.cors===!1&&(oe.mode="same-origin"),I.withCredentials&&(oe.credentials="include"),I.referrerPolicy&&(oe.referrerPolicy=I.referrerPolicy),self.AbortController&&(this._abortController=new self.AbortController,oe.signal=this._abortController.signal),this._status=l.c.kConnecting,self.fetch(Z.url,oe).then(function(Q){if(M._requestAbort)return M._status=l.c.kIdle,void Q.body.cancel();if(Q.ok&&Q.status>=200&&Q.status<=299){if(Q.url!==Z.url&&M._onURLRedirect){var G=M._seekHandler.removeURLParameters(Q.url);M._onURLRedirect(G)}var H=Q.headers.get("Content-Length");return H!=null&&(M._contentLength=parseInt(H),M._contentLength!==0&&M._onContentLengthKnown&&M._onContentLengthKnown(M._contentLength)),M._pump.call(M,Q.body.getReader())}if(M._status=l.c.kError,!M._onError)throw new u.d("FetchStreamLoader: Http code invalid, "+Q.status+" "+Q.statusText);M._onError(l.b.HTTP_STATUS_CODE_INVALID,{code:Q.status,msg:Q.statusText})}).catch(function(Q){if(!M._abortController||!M._abortController.signal.aborted){if(M._status=l.c.kError,!M._onError)throw Q;M._onError(l.b.EXCEPTION,{code:-1,msg:Q.message})}})},k.prototype.abort=function(){if(this._requestAbort=!0,(this._status!==l.c.kBuffering||!c.a.chrome)&&this._abortController)try{this._abortController.abort()}catch{}},k.prototype._pump=function(I){var R=this;return I.read().then(function(M){if(M.done)if(R._contentLength!==null&&R._receivedLength<R._contentLength){R._status=l.c.kError;var z=l.b.EARLY_EOF,Z={code:-1,msg:"Fetch stream meet Early-EOF"};if(!R._onError)throw new u.d(Z.msg);R._onError(z,Z)}else R._status=l.c.kComplete,R._onComplete&&R._onComplete(R._range.from,R._range.from+R._receivedLength-1);else{if(R._abortController&&R._abortController.signal.aborted)return void(R._status=l.c.kComplete);if(R._requestAbort===!0)return R._status=l.c.kComplete,I.cancel();R._status=l.c.kBuffering;var W=M.value.buffer,re=R._range.from+R._receivedLength;R._receivedLength+=W.byteLength,R._onDataArrival&&R._onDataArrival(W,re,R._receivedLength),R._pump(I)}}).catch(function(M){if(R._abortController&&R._abortController.signal.aborted)R._status=l.c.kComplete;else if(M.code!==11||!c.a.msedge){R._status=l.c.kError;var z=0,Z=null;if(M.code!==19&&M.message!=="network error"||!(R._contentLength===null||R._contentLength!==null&&R._receivedLength<R._contentLength)?(z=l.b.EXCEPTION,Z={code:M.code,msg:M.message}):(z=l.b.EARLY_EOF,Z={code:M.code,msg:"Fetch stream meet Early-EOF"}),!R._onError)throw new u.d(Z.msg);R._onError(z,Z)}})},k}(l.a),f=function(){var O=function(k,I){return(O=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(R,M){R.__proto__=M}||function(R,M){for(var z in M)Object.prototype.hasOwnProperty.call(M,z)&&(R[z]=M[z])})(k,I)};return function(k,I){if(typeof I!="function"&&I!==null)throw new TypeError("Class extends value "+String(I)+" is not a constructor or null");function R(){this.constructor=k}O(k,I),k.prototype=I===null?Object.create(I):(R.prototype=I.prototype,new R)}}(),p=function(O){function k(I,R){var M=O.call(this,"xhr-moz-chunked-loader")||this;return M.TAG="MozChunkedLoader",M._seekHandler=I,M._config=R,M._needStash=!0,M._xhr=null,M._requestAbort=!1,M._contentLength=null,M._receivedLength=0,M}return f(k,O),k.isSupported=function(){try{var I=new XMLHttpRequest;return I.open("GET","https://example.com",!0),I.responseType="moz-chunked-arraybuffer",I.responseType==="moz-chunked-arraybuffer"}catch(R){return a.a.w("MozChunkedLoader",R.message),!1}},k.prototype.destroy=function(){this.isWorking()&&this.abort(),this._xhr&&(this._xhr.onreadystatechange=null,this._xhr.onprogress=null,this._xhr.onloadend=null,this._xhr.onerror=null,this._xhr=null),O.prototype.destroy.call(this)},k.prototype.open=function(I,R){this._dataSource=I,this._range=R;var M=I.url;this._config.reuseRedirectedURL&&I.redirectedURL!=null&&(M=I.redirectedURL);var z=this._seekHandler.getConfig(M,R);this._requestURL=z.url;var Z=this._xhr=new XMLHttpRequest;if(Z.open("GET",z.url,!0),Z.responseType="moz-chunked-arraybuffer",Z.onreadystatechange=this._onReadyStateChange.bind(this),Z.onprogress=this._onProgress.bind(this),Z.onloadend=this._onLoadEnd.bind(this),Z.onerror=this._onXhrError.bind(this),I.withCredentials&&(Z.withCredentials=!0),typeof z.headers=="object"){var W=z.headers;for(var re in W)W.hasOwnProperty(re)&&Z.setRequestHeader(re,W[re])}if(typeof this._config.headers=="object"){W=this._config.headers;for(var re in W)W.hasOwnProperty(re)&&Z.setRequestHeader(re,W[re])}this._status=l.c.kConnecting,Z.send()},k.prototype.abort=function(){this._requestAbort=!0,this._xhr&&this._xhr.abort(),this._status=l.c.kComplete},k.prototype._onReadyStateChange=function(I){var R=I.target;if(R.readyState===2){if(R.responseURL!=null&&R.responseURL!==this._requestURL&&this._onURLRedirect){var M=this._seekHandler.removeURLParameters(R.responseURL);this._onURLRedirect(M)}if(R.status!==0&&(R.status<200||R.status>299)){if(this._status=l.c.kError,!this._onError)throw new u.d("MozChunkedLoader: Http code invalid, "+R.status+" "+R.statusText);this._onError(l.b.HTTP_STATUS_CODE_INVALID,{code:R.status,msg:R.statusText})}else this._status=l.c.kBuffering}},k.prototype._onProgress=function(I){if(this._status!==l.c.kError){this._contentLength===null&&I.total!==null&&I.total!==0&&(this._contentLength=I.total,this._onContentLengthKnown&&this._onContentLengthKnown(this._contentLength));var R=I.target.response,M=this._range.from+this._receivedLength;this._receivedLength+=R.byteLength,this._onDataArrival&&this._onDataArrival(R,M,this._receivedLength)}},k.prototype._onLoadEnd=function(I){this._requestAbort!==!0?this._status!==l.c.kError&&(this._status=l.c.kComplete,this._onComplete&&this._onComplete(this._range.from,this._range.from+this._receivedLength-1)):this._requestAbort=!1},k.prototype._onXhrError=function(I){this._status=l.c.kError;var R=0,M=null;if(this._contentLength&&I.loaded<this._contentLength?(R=l.b.EARLY_EOF,M={code:-1,msg:"Moz-Chunked stream meet Early-Eof"}):(R=l.b.EXCEPTION,M={code:-1,msg:I.constructor.name+" "+I.type}),!this._onError)throw new u.d(M.msg);this._onError(R,M)},k}(l.a),m=function(){var O=function(k,I){return(O=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(R,M){R.__proto__=M}||function(R,M){for(var z in M)Object.prototype.hasOwnProperty.call(M,z)&&(R[z]=M[z])})(k,I)};return function(k,I){if(typeof I!="function"&&I!==null)throw new TypeError("Class extends value "+String(I)+" is not a constructor or null");function R(){this.constructor=k}O(k,I),k.prototype=I===null?Object.create(I):(R.prototype=I.prototype,new R)}}(),g=(function(O){function k(I,R){var M=O.call(this,"xhr-msstream-loader")||this;return M.TAG="MSStreamLoader",M._seekHandler=I,M._config=R,M._needStash=!0,M._xhr=null,M._reader=null,M._totalRange=null,M._currentRange=null,M._currentRequestURL=null,M._currentRedirectedURL=null,M._contentLength=null,M._receivedLength=0,M._bufferLimit=16777216,M._lastTimeBufferSize=0,M._isReconnecting=!1,M}m(k,O),k.isSupported=function(){try{if(self.MSStream===void 0||self.MSStreamReader===void 0)return!1;var I=new XMLHttpRequest;return I.open("GET","https://example.com",!0),I.responseType="ms-stream",I.responseType==="ms-stream"}catch(R){return a.a.w("MSStreamLoader",R.message),!1}},k.prototype.destroy=function(){this.isWorking()&&this.abort(),this._reader&&(this._reader.onprogress=null,this._reader.onload=null,this._reader.onerror=null,this._reader=null),this._xhr&&(this._xhr.onreadystatechange=null,this._xhr=null),O.prototype.destroy.call(this)},k.prototype.open=function(I,R){this._internalOpen(I,R,!1)},k.prototype._internalOpen=function(I,R,M){this._dataSource=I,M?this._currentRange=R:this._totalRange=R;var z=I.url;this._config.reuseRedirectedURL&&(this._currentRedirectedURL!=null?z=this._currentRedirectedURL:I.redirectedURL!=null&&(z=I.redirectedURL));var Z=this._seekHandler.getConfig(z,R);this._currentRequestURL=Z.url;var W=this._reader=new self.MSStreamReader;W.onprogress=this._msrOnProgress.bind(this),W.onload=this._msrOnLoad.bind(this),W.onerror=this._msrOnError.bind(this);var re=this._xhr=new XMLHttpRequest;if(re.open("GET",Z.url,!0),re.responseType="ms-stream",re.onreadystatechange=this._xhrOnReadyStateChange.bind(this),re.onerror=this._xhrOnError.bind(this),I.withCredentials&&(re.withCredentials=!0),typeof Z.headers=="object"){var X=Z.headers;for(var oe in X)X.hasOwnProperty(oe)&&re.setRequestHeader(oe,X[oe])}if(typeof this._config.headers=="object"){X=this._config.headers;for(var oe in X)X.hasOwnProperty(oe)&&re.setRequestHeader(oe,X[oe])}this._isReconnecting?this._isReconnecting=!1:this._status=l.c.kConnecting,re.send()},k.prototype.abort=function(){this._internalAbort(),this._status=l.c.kComplete},k.prototype._internalAbort=function(){this._reader&&(this._reader.readyState===1&&this._reader.abort(),this._reader.onprogress=null,this._reader.onload=null,this._reader.onerror=null,this._reader=null),this._xhr&&(this._xhr.abort(),this._xhr.onreadystatechange=null,this._xhr=null)},k.prototype._xhrOnReadyStateChange=function(I){var R=I.target;if(R.readyState===2)if(R.status>=200&&R.status<=299){if(this._status=l.c.kBuffering,R.responseURL!=null){var M=this._seekHandler.removeURLParameters(R.responseURL);R.responseURL!==this._currentRequestURL&&M!==this._currentRedirectedURL&&(this._currentRedirectedURL=M,this._onURLRedirect&&this._onURLRedirect(M))}var z=R.getResponseHeader("Content-Length");if(z!=null&&this._contentLength==null){var Z=parseInt(z);Z>0&&(this._contentLength=Z,this._onContentLengthKnown&&this._onContentLengthKnown(this._contentLength))}}else{if(this._status=l.c.kError,!this._onError)throw new u.d("MSStreamLoader: Http code invalid, "+R.status+" "+R.statusText);this._onError(l.b.HTTP_STATUS_CODE_INVALID,{code:R.status,msg:R.statusText})}else if(R.readyState===3&&R.status>=200&&R.status<=299){this._status=l.c.kBuffering;var W=R.response;this._reader.readAsArrayBuffer(W)}},k.prototype._xhrOnError=function(I){this._status=l.c.kError;var R=l.b.EXCEPTION,M={code:-1,msg:I.constructor.name+" "+I.type};if(!this._onError)throw new u.d(M.msg);this._onError(R,M)},k.prototype._msrOnProgress=function(I){var R=I.target.result;if(R!=null){var M=R.slice(this._lastTimeBufferSize);this._lastTimeBufferSize=R.byteLength;var z=this._totalRange.from+this._receivedLength;this._receivedLength+=M.byteLength,this._onDataArrival&&this._onDataArrival(M,z,this._receivedLength),R.byteLength>=this._bufferLimit&&(a.a.v(this.TAG,"MSStream buffer exceeded max size near ".concat(z+M.byteLength,", reconnecting...")),this._doReconnectIfNeeded())}else this._doReconnectIfNeeded()},k.prototype._doReconnectIfNeeded=function(){if(this._contentLength==null||this._receivedLength<this._contentLength){this._isReconnecting=!0,this._lastTimeBufferSize=0,this._internalAbort();var I={from:this._totalRange.from+this._receivedLength,to:-1};this._internalOpen(this._dataSource,I,!0)}},k.prototype._msrOnLoad=function(I){this._status=l.c.kComplete,this._onComplete&&this._onComplete(this._totalRange.from,this._totalRange.from+this._receivedLength-1)},k.prototype._msrOnError=function(I){this._status=l.c.kError;var R=0,M=null;if(this._contentLength&&this._receivedLength<this._contentLength?(R=l.b.EARLY_EOF,M={code:-1,msg:"MSStream meet Early-Eof"}):(R=l.b.EARLY_EOF,M={code:-1,msg:I.constructor.name+" "+I.type}),!this._onError)throw new u.d(M.msg);this._onError(R,M)}}(l.a),function(){var O=function(k,I){return(O=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(R,M){R.__proto__=M}||function(R,M){for(var z in M)Object.prototype.hasOwnProperty.call(M,z)&&(R[z]=M[z])})(k,I)};return function(k,I){if(typeof I!="function"&&I!==null)throw new TypeError("Class extends value "+String(I)+" is not a constructor or null");function R(){this.constructor=k}O(k,I),k.prototype=I===null?Object.create(I):(R.prototype=I.prototype,new R)}}()),b=function(O){function k(I,R){var M=O.call(this,"xhr-range-loader")||this;return M.TAG="RangeLoader",M._seekHandler=I,M._config=R,M._needStash=!1,M._chunkSizeKBList=[128,256,384,512,768,1024,1536,2048,3072,4096,5120,6144,7168,8192],M._currentChunkSizeKB=384,M._currentSpeedNormalized=0,M._zeroSpeedChunkCount=0,M._xhr=null,M._speedSampler=new o,M._requestAbort=!1,M._waitForTotalLength=!1,M._totalLengthReceived=!1,M._currentRequestURL=null,M._currentRedirectedURL=null,M._currentRequestRange=null,M._totalLength=null,M._contentLength=null,M._receivedLength=0,M._lastTimeLoaded=0,M}return g(k,O),k.isSupported=function(){try{var I=new XMLHttpRequest;return I.open("GET","https://example.com",!0),I.responseType="arraybuffer",I.responseType==="arraybuffer"}catch(R){return a.a.w("RangeLoader",R.message),!1}},k.prototype.destroy=function(){this.isWorking()&&this.abort(),this._xhr&&(this._xhr.onreadystatechange=null,this._xhr.onprogress=null,this._xhr.onload=null,this._xhr.onerror=null,this._xhr=null),O.prototype.destroy.call(this)},Object.defineProperty(k.prototype,"currentSpeed",{get:function(){return this._speedSampler.lastSecondKBps},enumerable:!1,configurable:!0}),k.prototype.open=function(I,R){this._dataSource=I,this._range=R,this._status=l.c.kConnecting;var M=!1;this._dataSource.filesize!=null&&this._dataSource.filesize!==0&&(M=!0,this._totalLength=this._dataSource.filesize),this._totalLengthReceived||M?this._openSubRange():(this._waitForTotalLength=!0,this._internalOpen(this._dataSource,{from:0,to:-1}))},k.prototype._openSubRange=function(){var I=1024*this._currentChunkSizeKB,R=this._range.from+this._receivedLength,M=R+I;this._contentLength!=null&&M-this._range.from>=this._contentLength&&(M=this._range.from+this._contentLength-1),this._currentRequestRange={from:R,to:M},this._internalOpen(this._dataSource,this._currentRequestRange)},k.prototype._internalOpen=function(I,R){this._lastTimeLoaded=0;var M=I.url;this._config.reuseRedirectedURL&&(this._currentRedirectedURL!=null?M=this._currentRedirectedURL:I.redirectedURL!=null&&(M=I.redirectedURL));var z=this._seekHandler.getConfig(M,R);this._currentRequestURL=z.url;var Z=this._xhr=new XMLHttpRequest;if(Z.open("GET",z.url,!0),Z.responseType="arraybuffer",Z.onreadystatechange=this._onReadyStateChange.bind(this),Z.onprogress=this._onProgress.bind(this),Z.onload=this._onLoad.bind(this),Z.onerror=this._onXhrError.bind(this),I.withCredentials&&(Z.withCredentials=!0),typeof z.headers=="object"){var W=z.headers;for(var re in W)W.hasOwnProperty(re)&&Z.setRequestHeader(re,W[re])}if(typeof this._config.headers=="object"){W=this._config.headers;for(var re in W)W.hasOwnProperty(re)&&Z.setRequestHeader(re,W[re])}Z.send()},k.prototype.abort=function(){this._requestAbort=!0,this._internalAbort(),this._status=l.c.kComplete},k.prototype._internalAbort=function(){this._xhr&&(this._xhr.onreadystatechange=null,this._xhr.onprogress=null,this._xhr.onload=null,this._xhr.onerror=null,this._xhr.abort(),this._xhr=null)},k.prototype._onReadyStateChange=function(I){var R=I.target;if(R.readyState===2){if(R.responseURL!=null){var M=this._seekHandler.removeURLParameters(R.responseURL);R.responseURL!==this._currentRequestURL&&M!==this._currentRedirectedURL&&(this._currentRedirectedURL=M,this._onURLRedirect&&this._onURLRedirect(M))}if(R.status>=200&&R.status<=299){if(this._waitForTotalLength)return;this._status=l.c.kBuffering}else{if(this._status=l.c.kError,!this._onError)throw new u.d("RangeLoader: Http code invalid, "+R.status+" "+R.statusText);this._onError(l.b.HTTP_STATUS_CODE_INVALID,{code:R.status,msg:R.statusText})}}},k.prototype._onProgress=function(I){if(this._status!==l.c.kError){if(this._contentLength===null){var R=!1;if(this._waitForTotalLength){this._waitForTotalLength=!1,this._totalLengthReceived=!0,R=!0;var M=I.total;this._internalAbort(),M!=null&M!==0&&(this._totalLength=M)}if(this._range.to===-1?this._contentLength=this._totalLength-this._range.from:this._contentLength=this._range.to-this._range.from+1,R)return void this._openSubRange();this._onContentLengthKnown&&this._onContentLengthKnown(this._contentLength)}var z=I.loaded-this._lastTimeLoaded;this._lastTimeLoaded=I.loaded,this._speedSampler.addBytes(z)}},k.prototype._normalizeSpeed=function(I){var R=this._chunkSizeKBList,M=R.length-1,z=0,Z=0,W=M;if(I<R[0])return R[0];for(;Z<=W;){if((z=Z+Math.floor((W-Z)/2))===M||I>=R[z]&&I<R[z+1])return R[z];R[z]<I?Z=z+1:W=z-1}},k.prototype._onLoad=function(I){if(this._status!==l.c.kError)if(this._waitForTotalLength)this._waitForTotalLength=!1;else{this._lastTimeLoaded=0;var R=this._speedSampler.lastSecondKBps;if(R===0&&(this._zeroSpeedChunkCount++,this._zeroSpeedChunkCount>=3&&(R=this._speedSampler.currentKBps)),R!==0){var M=this._normalizeSpeed(R);this._currentSpeedNormalized!==M&&(this._currentSpeedNormalized=M,this._currentChunkSizeKB=M)}var z=I.target.response,Z=this._range.from+this._receivedLength;this._receivedLength+=z.byteLength;var W=!1;this._contentLength!=null&&this._receivedLength<this._contentLength?this._openSubRange():W=!0,this._onDataArrival&&this._onDataArrival(z,Z,this._receivedLength),W&&(this._status=l.c.kComplete,this._onComplete&&this._onComplete(this._range.from,this._range.from+this._receivedLength-1))}},k.prototype._onXhrError=function(I){this._status=l.c.kError;var R=0,M=null;if(this._contentLength&&this._receivedLength>0&&this._receivedLength<this._contentLength?(R=l.b.EARLY_EOF,M={code:-1,msg:"RangeLoader meet Early-Eof"}):(R=l.b.EXCEPTION,M={code:-1,msg:I.constructor.name+" "+I.type}),!this._onError)throw new u.d(M.msg);this._onError(R,M)},k}(l.a),v=function(){var O=function(k,I){return(O=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(R,M){R.__proto__=M}||function(R,M){for(var z in M)Object.prototype.hasOwnProperty.call(M,z)&&(R[z]=M[z])})(k,I)};return function(k,I){if(typeof I!="function"&&I!==null)throw new TypeError("Class extends value "+String(I)+" is not a constructor or null");function R(){this.constructor=k}O(k,I),k.prototype=I===null?Object.create(I):(R.prototype=I.prototype,new R)}}(),S=function(O){function k(){var I=O.call(this,"websocket-loader")||this;return I.TAG="WebSocketLoader",I._needStash=!0,I._ws=null,I._requestAbort=!1,I._receivedLength=0,I}return v(k,O),k.isSupported=function(){try{return self.WebSocket!==void 0}catch{return!1}},k.prototype.destroy=function(){this._ws&&this.abort(),O.prototype.destroy.call(this)},k.prototype.open=function(I){try{var R=this._ws=new self.WebSocket(I.url);R.binaryType="arraybuffer",R.onopen=this._onWebSocketOpen.bind(this),R.onclose=this._onWebSocketClose.bind(this),R.onmessage=this._onWebSocketMessage.bind(this),R.onerror=this._onWebSocketError.bind(this),this._status=l.c.kConnecting}catch(z){this._status=l.c.kError;var M={code:z.code,msg:z.message};if(!this._onError)throw new u.d(M.msg);this._onError(l.b.EXCEPTION,M)}},k.prototype.abort=function(){var I=this._ws;!I||I.readyState!==0&&I.readyState!==1||(this._requestAbort=!0,I.close()),this._ws=null,this._status=l.c.kComplete},k.prototype._onWebSocketOpen=function(I){this._status=l.c.kBuffering},k.prototype._onWebSocketClose=function(I){this._requestAbort!==!0?(this._status=l.c.kComplete,this._onComplete&&this._onComplete(0,this._receivedLength-1)):this._requestAbort=!1},k.prototype._onWebSocketMessage=function(I){var R=this;if(I.data instanceof ArrayBuffer)this._dispatchArrayBuffer(I.data);else if(I.data instanceof Blob){var M=new FileReader;M.onload=function(){R._dispatchArrayBuffer(M.result)},M.readAsArrayBuffer(I.data)}else{this._status=l.c.kError;var z={code:-1,msg:"Unsupported WebSocket message type: "+I.data.constructor.name};if(!this._onError)throw new u.d(z.msg);this._onError(l.b.EXCEPTION,z)}},k.prototype._dispatchArrayBuffer=function(I){var R=I,M=this._receivedLength;this._receivedLength+=R.byteLength,this._onDataArrival&&this._onDataArrival(R,M,this._receivedLength)},k.prototype._onWebSocketError=function(I){this._status=l.c.kError;var R={code:I.code,msg:I.message};if(!this._onError)throw new u.d(R.msg);this._onError(l.b.EXCEPTION,R)},k}(l.a),E=function(){function O(k){this._zeroStart=k||!1}return O.prototype.getConfig=function(k,I){var R={};if(I.from!==0||I.to!==-1){var M=void 0;M=I.to!==-1?"bytes=".concat(I.from.toString(),"-").concat(I.to.toString()):"bytes=".concat(I.from.toString(),"-"),R.Range=M}else this._zeroStart&&(R.Range="bytes=0-");return{url:k,headers:R}},O.prototype.removeURLParameters=function(k){return k},O}(),L=function(){function O(k,I){this._startName=k,this._endName=I}return O.prototype.getConfig=function(k,I){var R=k;if(I.from!==0||I.to!==-1){var M=!0;R.indexOf("?")===-1&&(R+="?",M=!1),M&&(R+="&"),R+="".concat(this._startName,"=").concat(I.from.toString()),I.to!==-1&&(R+="&".concat(this._endName,"=").concat(I.to.toString()))}return{url:R,headers:{}}},O.prototype.removeURLParameters=function(k){var I=k.split("?")[0],R=void 0,M=k.indexOf("?");M!==-1&&(R=k.substring(M+1));var z="";if(R!=null&&R.length>0)for(var Z=R.split("&"),W=0;W<Z.length;W++){var re=Z[W].split("="),X=W>0;re[0]!==this._startName&&re[0]!==this._endName&&(X&&(z+="&"),z+=Z[W])}return z.length===0?I:I+"?"+z},O}(),U=function(){function O(k,I,R){this.TAG="IOController",this._config=I,this._extraData=R,this._stashInitialSize=65536,I.stashInitialSize!=null&&I.stashInitialSize>0&&(this._stashInitialSize=I.stashInitialSize),this._stashUsed=0,this._stashSize=this._stashInitialSize,this._bufferSize=Math.max(this._stashSize,3145728),this._stashBuffer=new ArrayBuffer(this._bufferSize),this._stashByteStart=0,this._enableStash=!0,I.enableStashBuffer===!1&&(this._enableStash=!1),this._loader=null,this._loaderClass=null,this._seekHandler=null,this._dataSource=k,this._isWebSocketURL=/wss?:\/\/(.+?)/.test(k.url),this._refTotalLength=k.filesize?k.filesize:null,this._totalLength=this._refTotalLength,this._fullRequestFlag=!1,this._currentRange=null,this._redirectedURL=null,this._speedNormalized=0,this._speedSampler=new o,this._speedNormalizeList=[32,64,96,128,192,256,384,512,768,1024,1536,2048,3072,4096],this._isEarlyEofReconnecting=!1,this._paused=!1,this._resumeFrom=0,this._onDataArrival=null,this._onSeeked=null,this._onError=null,this._onComplete=null,this._onRedirect=null,this._onRecoveredEarlyEof=null,this._selectSeekHandler(),this._selectLoader(),this._createLoader()}return O.prototype.destroy=function(){this._loader.isWorking()&&this._loader.abort(),this._loader.destroy(),this._loader=null,this._loaderClass=null,this._dataSource=null,this._stashBuffer=null,this._stashUsed=this._stashSize=this._bufferSize=this._stashByteStart=0,this._currentRange=null,this._speedSampler=null,this._isEarlyEofReconnecting=!1,this._onDataArrival=null,this._onSeeked=null,this._onError=null,this._onComplete=null,this._onRedirect=null,this._onRecoveredEarlyEof=null,this._extraData=null},O.prototype.isWorking=function(){return this._loader&&this._loader.isWorking()&&!this._paused},O.prototype.isPaused=function(){return this._paused},Object.defineProperty(O.prototype,"status",{get:function(){return this._loader.status},enumerable:!1,configurable:!0}),Object.defineProperty(O.prototype,"extraData",{get:function(){return this._extraData},set:function(k){this._extraData=k},enumerable:!1,configurable:!0}),Object.defineProperty(O.prototype,"onDataArrival",{get:function(){return this._onDataArrival},set:function(k){this._onDataArrival=k},enumerable:!1,configurable:!0}),Object.defineProperty(O.prototype,"onSeeked",{get:function(){return this._onSeeked},set:function(k){this._onSeeked=k},enumerable:!1,configurable:!0}),Object.defineProperty(O.prototype,"onError",{get:function(){return this._onError},set:function(k){this._onError=k},enumerable:!1,configurable:!0}),Object.defineProperty(O.prototype,"onComplete",{get:function(){return this._onComplete},set:function(k){this._onComplete=k},enumerable:!1,configurable:!0}),Object.defineProperty(O.prototype,"onRedirect",{get:function(){return this._onRedirect},set:function(k){this._onRedirect=k},enumerable:!1,configurable:!0}),Object.defineProperty(O.prototype,"onRecoveredEarlyEof",{get:function(){return this._onRecoveredEarlyEof},set:function(k){this._onRecoveredEarlyEof=k},enumerable:!1,configurable:!0}),Object.defineProperty(O.prototype,"currentURL",{get:function(){return this._dataSource.url},enumerable:!1,configurable:!0}),Object.defineProperty(O.prototype,"hasRedirect",{get:function(){return this._redirectedURL!=null||this._dataSource.redirectedURL!=null},enumerable:!1,configurable:!0}),Object.defineProperty(O.prototype,"currentRedirectedURL",{get:function(){return this._redirectedURL||this._dataSource.redirectedURL},enumerable:!1,configurable:!0}),Object.defineProperty(O.prototype,"currentSpeed",{get:function(){return this._loaderClass===b?this._loader.currentSpeed:this._speedSampler.lastSecondKBps},enumerable:!1,configurable:!0}),Object.defineProperty(O.prototype,"loaderType",{get:function(){return this._loader.type},enumerable:!1,configurable:!0}),O.prototype._selectSeekHandler=function(){var k=this._config;if(k.seekType==="range")this._seekHandler=new E(this._config.rangeLoadZeroStart);else if(k.seekType==="param"){var I=k.seekParamStart||"bstart",R=k.seekParamEnd||"bend";this._seekHandler=new L(I,R)}else{if(k.seekType!=="custom")throw new u.b("Invalid seekType in config: ".concat(k.seekType));if(typeof k.customSeekHandler!="function")throw new u.b("Custom seekType specified in config but invalid customSeekHandler!");this._seekHandler=new k.customSeekHandler}},O.prototype._selectLoader=function(){if(this._config.customLoader!=null)this._loaderClass=this._config.customLoader;else if(this._isWebSocketURL)this._loaderClass=S;else if(h.isSupported())this._loaderClass=h;else if(p.isSupported())this._loaderClass=p;else{if(!b.isSupported())throw new u.d("Your browser doesn't support xhr with arraybuffer responseType!");this._loaderClass=b}},O.prototype._createLoader=function(){this._loader=new this._loaderClass(this._seekHandler,this._config),this._loader.needStashBuffer===!1&&(this._enableStash=!1),this._loader.onContentLengthKnown=this._onContentLengthKnown.bind(this),this._loader.onURLRedirect=this._onURLRedirect.bind(this),this._loader.onDataArrival=this._onLoaderChunkArrival.bind(this),this._loader.onComplete=this._onLoaderComplete.bind(this),this._loader.onError=this._onLoaderError.bind(this)},O.prototype.open=function(k){this._currentRange={from:0,to:-1},k&&(this._currentRange.from=k),this._speedSampler.reset(),k||(this._fullRequestFlag=!0),this._loader.open(this._dataSource,Object.assign({},this._currentRange))},O.prototype.abort=function(){this._loader.abort(),this._paused&&(this._paused=!1,this._resumeFrom=0)},O.prototype.pause=function(){this.isWorking()&&(this._loader.abort(),this._stashUsed!==0?(this._resumeFrom=this._stashByteStart,this._currentRange.to=this._stashByteStart-1):this._resumeFrom=this._currentRange.to+1,this._stashUsed=0,this._stashByteStart=0,this._paused=!0)},O.prototype.resume=function(){if(this._paused){this._paused=!1;var k=this._resumeFrom;this._resumeFrom=0,this._internalSeek(k,!0)}},O.prototype.seek=function(k){this._paused=!1,this._stashUsed=0,this._stashByteStart=0,this._internalSeek(k,!0)},O.prototype._internalSeek=function(k,I){this._loader.isWorking()&&this._loader.abort(),this._flushStashBuffer(I),this._loader.destroy(),this._loader=null;var R={from:k,to:-1};this._currentRange={from:R.from,to:-1},this._speedSampler.reset(),this._stashSize=this._stashInitialSize,this._createLoader(),this._loader.open(this._dataSource,R),this._onSeeked&&this._onSeeked()},O.prototype.updateUrl=function(k){if(!k||typeof k!="string"||k.length===0)throw new u.b("Url must be a non-empty string!");this._dataSource.url=k},O.prototype._expandBuffer=function(k){for(var I=this._stashSize;I+1048576<k;)I*=2;if((I+=1048576)!==this._bufferSize){var R=new ArrayBuffer(I);if(this._stashUsed>0){var M=new Uint8Array(this._stashBuffer,0,this._stashUsed);new Uint8Array(R,0,I).set(M,0)}this._stashBuffer=R,this._bufferSize=I}},O.prototype._normalizeSpeed=function(k){var I=this._speedNormalizeList,R=I.length-1,M=0,z=0,Z=R;if(k<I[0])return I[0];for(;z<=Z;){if((M=z+Math.floor((Z-z)/2))===R||k>=I[M]&&k<I[M+1])return I[M];I[M]<k?z=M+1:Z=M-1}},O.prototype._adjustStashSize=function(k){var I=0;(I=this._config.isLive?k/8:k<512?k:k>=512&&k<=1024?Math.floor(1.5*k):2*k)>8192&&(I=8192);var R=1024*I+1048576;this._bufferSize<R&&this._expandBuffer(R),this._stashSize=1024*I},O.prototype._dispatchChunks=function(k,I){return this._currentRange.to=I+k.byteLength-1,this._onDataArrival(k,I)},O.prototype._onURLRedirect=function(k){this._redirectedURL=k,this._onRedirect&&this._onRedirect(k)},O.prototype._onContentLengthKnown=function(k){k&&this._fullRequestFlag&&(this._totalLength=k,this._fullRequestFlag=!1)},O.prototype._onLoaderChunkArrival=function(k,I,R){if(!this._onDataArrival)throw new u.a("IOController: No existing consumer (onDataArrival) callback!");if(!this._paused){this._isEarlyEofReconnecting&&(this._isEarlyEofReconnecting=!1,this._onRecoveredEarlyEof&&this._onRecoveredEarlyEof()),this._speedSampler.addBytes(k.byteLength);var M=this._speedSampler.lastSecondKBps;if(M!==0){var z=this._normalizeSpeed(M);this._speedNormalized!==z&&(this._speedNormalized=z,this._adjustStashSize(z))}if(this._enableStash)if(this._stashUsed===0&&this._stashByteStart===0&&(this._stashByteStart=I),this._stashUsed+k.byteLength<=this._stashSize)(re=new Uint8Array(this._stashBuffer,0,this._stashSize)).set(new Uint8Array(k),this._stashUsed),this._stashUsed+=k.byteLength;else if(re=new Uint8Array(this._stashBuffer,0,this._bufferSize),this._stashUsed>0){var Z=this._stashBuffer.slice(0,this._stashUsed);(X=this._dispatchChunks(Z,this._stashByteStart))<Z.byteLength?X>0&&(oe=new Uint8Array(Z,X),re.set(oe,0),this._stashUsed=oe.byteLength,this._stashByteStart+=X):(this._stashUsed=0,this._stashByteStart+=X),this._stashUsed+k.byteLength>this._bufferSize&&(this._expandBuffer(this._stashUsed+k.byteLength),re=new Uint8Array(this._stashBuffer,0,this._bufferSize)),re.set(new Uint8Array(k),this._stashUsed),this._stashUsed+=k.byteLength}else(X=this._dispatchChunks(k,I))<k.byteLength&&((W=k.byteLength-X)>this._bufferSize&&(this._expandBuffer(W),re=new Uint8Array(this._stashBuffer,0,this._bufferSize)),re.set(new Uint8Array(k,X),0),this._stashUsed+=W,this._stashByteStart=I+X);else if(this._stashUsed===0){var W;(X=this._dispatchChunks(k,I))<k.byteLength&&((W=k.byteLength-X)>this._bufferSize&&this._expandBuffer(W),(re=new Uint8Array(this._stashBuffer,0,this._bufferSize)).set(new Uint8Array(k,X),0),this._stashUsed+=W,this._stashByteStart=I+X)}else{var re,X;if(this._stashUsed+k.byteLength>this._bufferSize&&this._expandBuffer(this._stashUsed+k.byteLength),(re=new Uint8Array(this._stashBuffer,0,this._bufferSize)).set(new Uint8Array(k),this._stashUsed),this._stashUsed+=k.byteLength,(X=this._dispatchChunks(this._stashBuffer.slice(0,this._stashUsed),this._stashByteStart))<this._stashUsed&&X>0){var oe=new Uint8Array(this._stashBuffer,X);re.set(oe,0)}this._stashUsed-=X,this._stashByteStart+=X}}},O.prototype._flushStashBuffer=function(k){if(this._stashUsed>0){var I=this._stashBuffer.slice(0,this._stashUsed),R=this._dispatchChunks(I,this._stashByteStart),M=I.byteLength-R;if(R<I.byteLength){if(!k){if(R>0){var z=new Uint8Array(this._stashBuffer,0,this._bufferSize),Z=new Uint8Array(I,R);z.set(Z,0),this._stashUsed=Z.byteLength,this._stashByteStart+=R}return 0}a.a.w(this.TAG,"".concat(M," bytes unconsumed data remain when flush buffer, dropped"))}return this._stashUsed=0,this._stashByteStart=0,M}return 0},O.prototype._onLoaderComplete=function(k,I){this._flushStashBuffer(!0),this._onComplete&&this._onComplete(this._extraData)},O.prototype._onLoaderError=function(k,I){switch(a.a.e(this.TAG,"Loader error, code = ".concat(I.code,", msg = ").concat(I.msg)),this._flushStashBuffer(!1),this._isEarlyEofReconnecting&&(this._isEarlyEofReconnecting=!1,k=l.b.UNRECOVERABLE_EARLY_EOF),k){case l.b.EARLY_EOF:if(!this._config.isLive&&this._totalLength){var R=this._currentRange.to+1;return void(R<this._totalLength&&(a.a.w(this.TAG,"Connection lost, trying reconnect..."),this._isEarlyEofReconnecting=!0,this._internalSeek(R,!1)))}k=l.b.UNRECOVERABLE_EARLY_EOF;break;case l.b.UNRECOVERABLE_EARLY_EOF:case l.b.CONNECTING_TIMEOUT:case l.b.HTTP_STATUS_CODE_INVALID:case l.b.EXCEPTION:}if(!this._onError)throw new u.d("IOException: "+I.msg);this._onError(k,I)},O}();r.a=U},function(n,r,i){var s=function(){function a(){}return a.install=function(){Object.setPrototypeOf=Object.setPrototypeOf||function(o,l){return o.__proto__=l,o},Object.assign=Object.assign||function(o){if(o==null)throw new TypeError("Cannot convert undefined or null to object");for(var l=Object(o),c=1;c<arguments.length;c++){var u=arguments[c];if(u!=null)for(var d in u)u.hasOwnProperty(d)&&(l[d]=u[d])}return l},String.prototype.startsWith||Object.defineProperty(String.prototype,"startsWith",{value:function(o,l){var c=l>0?0|l:0;return this.substring(c,c+o.length)===o}}),typeof self.Promise!="function"&&i(21).polyfill()},a}();s.install(),r.a=s},function(n,r,i){var s=i(9),a=i.n(s),o=i(0),l=i(5),c=i(7),u=i(3),d=function(){function h(f){this.TAG="MSEController",this._config=f,this._emitter=new a.a,this._config.isLive&&this._config.autoCleanupSourceBuffer==null&&(this._config.autoCleanupSourceBuffer=!0),this.e={onSourceOpen:this._onSourceOpen.bind(this),onSourceEnded:this._onSourceEnded.bind(this),onSourceClose:this._onSourceClose.bind(this),onStartStreaming:this._onStartStreaming.bind(this),onEndStreaming:this._onEndStreaming.bind(this),onQualityChange:this._onQualityChange.bind(this),onSourceBufferError:this._onSourceBufferError.bind(this),onSourceBufferUpdateEnd:this._onSourceBufferUpdateEnd.bind(this)},this._useManagedMediaSource="ManagedMediaSource"in self&&!("MediaSource"in self),this._mediaSource=null,this._mediaSourceObjectURL=null,this._mediaElementProxy=null,this._isBufferFull=!1,this._hasPendingEos=!1,this._requireSetMediaDuration=!1,this._pendingMediaDuration=0,this._pendingSourceBufferInit=[],this._mimeTypes={video:null,audio:null},this._sourceBuffers={video:null,audio:null},this._lastInitSegments={video:null,audio:null},this._pendingSegments={video:[],audio:[]},this._pendingRemoveRanges={video:[],audio:[]}}return h.prototype.destroy=function(){this._mediaSource&&this.shutdown(),this._mediaSourceObjectURL&&this.revokeObjectURL(),this.e=null,this._emitter.removeAllListeners(),this._emitter=null},h.prototype.on=function(f,p){this._emitter.addListener(f,p)},h.prototype.off=function(f,p){this._emitter.removeListener(f,p)},h.prototype.initialize=function(f){if(this._mediaSource)throw new u.a("MediaSource has been attached to an HTMLMediaElement!");this._useManagedMediaSource&&o.a.v(this.TAG,"Using ManagedMediaSource");var p=this._mediaSource=this._useManagedMediaSource?new self.ManagedMediaSource:new self.MediaSource;p.addEventListener("sourceopen",this.e.onSourceOpen),p.addEventListener("sourceended",this.e.onSourceEnded),p.addEventListener("sourceclose",this.e.onSourceClose),this._useManagedMediaSource&&(p.addEventListener("startstreaming",this.e.onStartStreaming),p.addEventListener("endstreaming",this.e.onEndStreaming),p.addEventListener("qualitychange",this.e.onQualityChange)),this._mediaElementProxy=f},h.prototype.shutdown=function(){if(this._mediaSource){var f=this._mediaSource;for(var p in this._sourceBuffers){var m=this._pendingSegments[p];m.splice(0,m.length),this._pendingSegments[p]=null,this._pendingRemoveRanges[p]=null,this._lastInitSegments[p]=null;var g=this._sourceBuffers[p];if(g){if(f.readyState!=="closed"){try{f.removeSourceBuffer(g)}catch(b){o.a.e(this.TAG,b.message)}g.removeEventListener("error",this.e.onSourceBufferError),g.removeEventListener("updateend",this.e.onSourceBufferUpdateEnd)}this._mimeTypes[p]=null,this._sourceBuffers[p]=null}}if(f.readyState==="open")try{f.endOfStream()}catch(b){o.a.e(this.TAG,b.message)}this._mediaElementProxy=null,f.removeEventListener("sourceopen",this.e.onSourceOpen),f.removeEventListener("sourceended",this.e.onSourceEnded),f.removeEventListener("sourceclose",this.e.onSourceClose),this._useManagedMediaSource&&(f.removeEventListener("startstreaming",this.e.onStartStreaming),f.removeEventListener("endstreaming",this.e.onEndStreaming),f.removeEventListener("qualitychange",this.e.onQualityChange)),this._pendingSourceBufferInit=[],this._isBufferFull=!1,this._mediaSource=null}},h.prototype.isManagedMediaSource=function(){return this._useManagedMediaSource},h.prototype.getObject=function(){if(!this._mediaSource)throw new u.a("MediaSource has not been initialized yet!");return this._mediaSource},h.prototype.getHandle=function(){if(!this._mediaSource)throw new u.a("MediaSource has not been initialized yet!");return this._mediaSource.handle},h.prototype.getObjectURL=function(){if(!this._mediaSource)throw new u.a("MediaSource has not been initialized yet!");return this._mediaSourceObjectURL==null&&(this._mediaSourceObjectURL=URL.createObjectURL(this._mediaSource)),this._mediaSourceObjectURL},h.prototype.revokeObjectURL=function(){this._mediaSourceObjectURL&&(URL.revokeObjectURL(this._mediaSourceObjectURL),this._mediaSourceObjectURL=null)},h.prototype.appendInitSegment=function(f,p){if(p===void 0&&(p=void 0),!this._mediaSource||this._mediaSource.readyState!=="open"||this._mediaSource.streaming===!1)return this._pendingSourceBufferInit.push(f),void this._pendingSegments[f.type].push(f);var m=f,g="".concat(m.container);m.codec&&m.codec.length>0&&(m.codec==="opus"&&l.a.safari&&(m.codec="Opus"),g+=";codecs=".concat(m.codec));var b=!1;if(o.a.v(this.TAG,"Received Initialization Segment, mimeType: "+g),this._lastInitSegments[m.type]=m,g!==this._mimeTypes[m.type]){if(this._mimeTypes[m.type])o.a.v(this.TAG,"Notice: ".concat(m.type," mimeType changed, origin: ").concat(this._mimeTypes[m.type],", target: ").concat(g));else{b=!0;try{var v=this._sourceBuffers[m.type]=this._mediaSource.addSourceBuffer(g);v.addEventListener("error",this.e.onSourceBufferError),v.addEventListener("updateend",this.e.onSourceBufferUpdateEnd)}catch(S){return o.a.e(this.TAG,S.message),void this._emitter.emit(c.a.ERROR,{code:S.code,msg:S.message})}}this._mimeTypes[m.type]=g}p||this._pendingSegments[m.type].push(m),b||this._sourceBuffers[m.type]&&!this._sourceBuffers[m.type].updating&&this._doAppendSegments(),l.a.safari&&m.container==="audio/mpeg"&&m.mediaDuration>0&&(this._requireSetMediaDuration=!0,this._pendingMediaDuration=m.mediaDuration/1e3,this._updateMediaSourceDuration())},h.prototype.appendMediaSegment=function(f){var p=f;this._pendingSegments[p.type].push(p),this._config.autoCleanupSourceBuffer&&this._needCleanupSourceBuffer()&&this._doCleanupSourceBuffer();var m=this._sourceBuffers[p.type];!m||m.updating||this._hasPendingRemoveRanges()||this._doAppendSegments()},h.prototype.flush=function(){for(var f in this._sourceBuffers)if(this._sourceBuffers[f]){var p=this._sourceBuffers[f];if(this._mediaSource.readyState==="open")try{p.abort()}catch(E){o.a.e(this.TAG,E.message)}var m=this._pendingSegments[f];if(m.splice(0,m.length),this._mediaSource.readyState!=="closed"){for(var g=0;g<p.buffered.length;g++){var b=p.buffered.start(g),v=p.buffered.end(g);this._pendingRemoveRanges[f].push({start:b,end:v})}if(p.updating||this._doRemoveRanges(),l.a.safari){var S=this._lastInitSegments[f];S&&(this._pendingSegments[f].push(S),p.updating||this._doAppendSegments())}}}},h.prototype.endOfStream=function(){var f=this._mediaSource,p=this._sourceBuffers;f&&f.readyState==="open"?p.video&&p.video.updating||p.audio&&p.audio.updating?this._hasPendingEos=!0:(this._hasPendingEos=!1,f.endOfStream()):f&&f.readyState==="closed"&&this._hasPendingSegments()&&(this._hasPendingEos=!0)},h.prototype._needCleanupSourceBuffer=function(){if(!this._config.autoCleanupSourceBuffer)return!1;var f=this._mediaElementProxy.getCurrentTime();for(var p in this._sourceBuffers){var m=this._sourceBuffers[p];if(m){var g=m.buffered;if(g.length>=1&&f-g.start(0)>=this._config.autoCleanupMaxBackwardDuration)return!0}}return!1},h.prototype._doCleanupSourceBuffer=function(){var f=this._mediaElementProxy.getCurrentTime();for(var p in this._sourceBuffers){var m=this._sourceBuffers[p];if(m){for(var g=m.buffered,b=!1,v=0;v<g.length;v++){var S=g.start(v),E=g.end(v);if(S<=f&&f<E+3){if(f-S>=this._config.autoCleanupMaxBackwardDuration){b=!0;var L=f-this._config.autoCleanupMinBackwardDuration;this._pendingRemoveRanges[p].push({start:S,end:L})}}else E<f&&(b=!0,this._pendingRemoveRanges[p].push({start:S,end:E}))}b&&!m.updating&&this._doRemoveRanges()}}},h.prototype._updateMediaSourceDuration=function(){var f=this._sourceBuffers;if(this._mediaElementProxy.getReadyState()!==0&&this._mediaSource.readyState==="open"&&!(f.video&&f.video.updating||f.audio&&f.audio.updating)){var p=this._mediaSource.duration,m=this._pendingMediaDuration;m>0&&(isNaN(p)||m>p)&&(o.a.v(this.TAG,"Update MediaSource duration from ".concat(p," to ").concat(m)),this._mediaSource.duration=m),this._requireSetMediaDuration=!1,this._pendingMediaDuration=0}},h.prototype._doRemoveRanges=function(){for(var f in this._pendingRemoveRanges)if(this._sourceBuffers[f]&&!this._sourceBuffers[f].updating)for(var p=this._sourceBuffers[f],m=this._pendingRemoveRanges[f];m.length&&!p.updating;){var g=m.shift();p.remove(g.start,g.end)}},h.prototype._doAppendSegments=function(){var f=this._pendingSegments;for(var p in f)if(this._sourceBuffers[p]&&!this._sourceBuffers[p].updating&&this._mediaSource.streaming!==!1&&f[p].length>0){var m=f[p].shift();if(typeof m.timestampOffset=="number"&&isFinite(m.timestampOffset)){var g=this._sourceBuffers[p].timestampOffset,b=m.timestampOffset/1e3;Math.abs(g-b)>.1&&(o.a.v(this.TAG,"Update MPEG audio timestampOffset from ".concat(g," to ").concat(b)),this._sourceBuffers[p].timestampOffset=b),delete m.timestampOffset}if(!m.data||m.data.byteLength===0)continue;try{this._sourceBuffers[p].appendBuffer(m.data),this._isBufferFull=!1}catch(v){this._pendingSegments[p].unshift(m),v.code===22?(this._isBufferFull||this._emitter.emit(c.a.BUFFER_FULL),this._isBufferFull=!0):(o.a.e(this.TAG,v.message),this._emitter.emit(c.a.ERROR,{code:v.code,msg:v.message}))}}},h.prototype._onSourceOpen=function(){if(o.a.v(this.TAG,"MediaSource onSourceOpen"),this._mediaSource.removeEventListener("sourceopen",this.e.onSourceOpen),this._pendingSourceBufferInit.length>0)for(var f=this._pendingSourceBufferInit;f.length;){var p=f.shift();this.appendInitSegment(p,!0)}this._hasPendingSegments()&&this._doAppendSegments(),this._emitter.emit(c.a.SOURCE_OPEN)},h.prototype._onStartStreaming=function(){o.a.v(this.TAG,"ManagedMediaSource onStartStreaming"),this._emitter.emit(c.a.START_STREAMING)},h.prototype._onEndStreaming=function(){o.a.v(this.TAG,"ManagedMediaSource onEndStreaming"),this._emitter.emit(c.a.END_STREAMING)},h.prototype._onQualityChange=function(){o.a.v(this.TAG,"ManagedMediaSource onQualityChange")},h.prototype._onSourceEnded=function(){o.a.v(this.TAG,"MediaSource onSourceEnded")},h.prototype._onSourceClose=function(){o.a.v(this.TAG,"MediaSource onSourceClose"),this._mediaSource&&this.e!=null&&(this._mediaSource.removeEventListener("sourceopen",this.e.onSourceOpen),this._mediaSource.removeEventListener("sourceended",this.e.onSourceEnded),this._mediaSource.removeEventListener("sourceclose",this.e.onSourceClose),this._useManagedMediaSource&&(this._mediaSource.removeEventListener("startstreaming",this.e.onStartStreaming),this._mediaSource.removeEventListener("endstreaming",this.e.onEndStreaming),this._mediaSource.removeEventListener("qualitychange",this.e.onQualityChange)))},h.prototype._hasPendingSegments=function(){var f=this._pendingSegments;return f.video.length>0||f.audio.length>0},h.prototype._hasPendingRemoveRanges=function(){var f=this._pendingRemoveRanges;return f.video.length>0||f.audio.length>0},h.prototype._onSourceBufferUpdateEnd=function(){this._requireSetMediaDuration?this._updateMediaSourceDuration():this._hasPendingRemoveRanges()?this._doRemoveRanges():this._hasPendingSegments()?this._doAppendSegments():this._hasPendingEos&&this.endOfStream(),this._emitter.emit(c.a.UPDATE_END)},h.prototype._onSourceBufferError=function(f){o.a.e(this.TAG,"SourceBuffer Error: ".concat(f))},h}();r.a=d},function(n,r,i){var s=i(9),a=i.n(s),o=i(18),l=i.n(o),c=i(0),u=i(8),d=i(13),h=i(1),f=(i(19),i(12)),p=function(){function m(g,b){if(this.TAG="Transmuxer",this._emitter=new a.a,b.enableWorker&&typeof Worker<"u")try{this._worker=l()(19),this._workerDestroying=!1,this._worker.addEventListener("message",this._onWorkerMessage.bind(this)),this._worker.postMessage({cmd:"init",param:[g,b]}),this.e={onLoggingConfigChanged:this._onLoggingConfigChanged.bind(this)},u.a.registerListener(this.e.onLoggingConfigChanged),this._worker.postMessage({cmd:"logging_config",param:u.a.getConfig()})}catch{c.a.e(this.TAG,"Error while initialize transmuxing worker, fallback to inline transmuxing"),this._worker=null,this._controller=new d.a(g,b)}else this._controller=new d.a(g,b);if(this._controller){var v=this._controller;v.on(h.a.IO_ERROR,this._onIOError.bind(this)),v.on(h.a.DEMUX_ERROR,this._onDemuxError.bind(this)),v.on(h.a.INIT_SEGMENT,this._onInitSegment.bind(this)),v.on(h.a.MEDIA_SEGMENT,this._onMediaSegment.bind(this)),v.on(h.a.LOADING_COMPLETE,this._onLoadingComplete.bind(this)),v.on(h.a.RECOVERED_EARLY_EOF,this._onRecoveredEarlyEof.bind(this)),v.on(h.a.MEDIA_INFO,this._onMediaInfo.bind(this)),v.on(h.a.METADATA_ARRIVED,this._onMetaDataArrived.bind(this)),v.on(h.a.SCRIPTDATA_ARRIVED,this._onScriptDataArrived.bind(this)),v.on(h.a.TIMED_ID3_METADATA_ARRIVED,this._onTimedID3MetadataArrived.bind(this)),v.on(h.a.SYNCHRONOUS_KLV_METADATA_ARRIVED,this._onSynchronousKLVMetadataArrived.bind(this)),v.on(h.a.ASYNCHRONOUS_KLV_METADATA_ARRIVED,this._onAsynchronousKLVMetadataArrived.bind(this)),v.on(h.a.SMPTE2038_METADATA_ARRIVED,this._onSMPTE2038MetadataArrived.bind(this)),v.on(h.a.SCTE35_METADATA_ARRIVED,this._onSCTE35MetadataArrived.bind(this)),v.on(h.a.PES_PRIVATE_DATA_DESCRIPTOR,this._onPESPrivateDataDescriptor.bind(this)),v.on(h.a.PES_PRIVATE_DATA_ARRIVED,this._onPESPrivateDataArrived.bind(this)),v.on(h.a.STATISTICS_INFO,this._onStatisticsInfo.bind(this)),v.on(h.a.RECOMMEND_SEEKPOINT,this._onRecommendSeekpoint.bind(this))}}return m.prototype.destroy=function(){this._worker?this._workerDestroying||(this._workerDestroying=!0,this._worker.postMessage({cmd:"destroy"}),u.a.removeListener(this.e.onLoggingConfigChanged),this.e=null):(this._controller.destroy(),this._controller=null),this._emitter.removeAllListeners(),this._emitter=null},m.prototype.on=function(g,b){this._emitter.addListener(g,b)},m.prototype.off=function(g,b){this._emitter.removeListener(g,b)},m.prototype.hasWorker=function(){return this._worker!=null},m.prototype.open=function(){this._worker?this._worker.postMessage({cmd:"start"}):this._controller.start()},m.prototype.close=function(){this._worker?this._worker.postMessage({cmd:"stop"}):this._controller.stop()},m.prototype.seek=function(g){this._worker?this._worker.postMessage({cmd:"seek",param:g}):this._controller.seek(g)},m.prototype.pause=function(){this._worker?this._worker.postMessage({cmd:"pause"}):this._controller.pause()},m.prototype.resume=function(){this._worker?this._worker.postMessage({cmd:"resume"}):this._controller.resume()},m.prototype._onInitSegment=function(g,b){var v=this;Promise.resolve().then(function(){v._emitter.emit(h.a.INIT_SEGMENT,g,b)})},m.prototype._onMediaSegment=function(g,b){var v=this;Promise.resolve().then(function(){v._emitter.emit(h.a.MEDIA_SEGMENT,g,b)})},m.prototype._onLoadingComplete=function(){var g=this;Promise.resolve().then(function(){g._emitter.emit(h.a.LOADING_COMPLETE)})},m.prototype._onRecoveredEarlyEof=function(){var g=this;Promise.resolve().then(function(){g._emitter.emit(h.a.RECOVERED_EARLY_EOF)})},m.prototype._onMediaInfo=function(g){var b=this;Promise.resolve().then(function(){b._emitter.emit(h.a.MEDIA_INFO,g)})},m.prototype._onMetaDataArrived=function(g){var b=this;Promise.resolve().then(function(){b._emitter.emit(h.a.METADATA_ARRIVED,g)})},m.prototype._onScriptDataArrived=function(g){var b=this;Promise.resolve().then(function(){b._emitter.emit(h.a.SCRIPTDATA_ARRIVED,g)})},m.prototype._onTimedID3MetadataArrived=function(g){var b=this;Promise.resolve().then(function(){b._emitter.emit(h.a.TIMED_ID3_METADATA_ARRIVED,g)})},m.prototype._onSynchronousKLVMetadataArrived=function(g){var b=this;Promise.resolve().then(function(){b._emitter.emit(h.a.SYNCHRONOUS_KLV_METADATA_ARRIVED,g)})},m.prototype._onAsynchronousKLVMetadataArrived=function(g){var b=this;Promise.resolve().then(function(){b._emitter.emit(h.a.ASYNCHRONOUS_KLV_METADATA_ARRIVED,g)})},m.prototype._onSMPTE2038MetadataArrived=function(g){var b=this;Promise.resolve().then(function(){b._emitter.emit(h.a.SMPTE2038_METADATA_ARRIVED,g)})},m.prototype._onSCTE35MetadataArrived=function(g){var b=this;Promise.resolve().then(function(){b._emitter.emit(h.a.SCTE35_METADATA_ARRIVED,g)})},m.prototype._onPESPrivateDataDescriptor=function(g){var b=this;Promise.resolve().then(function(){b._emitter.emit(h.a.PES_PRIVATE_DATA_DESCRIPTOR,g)})},m.prototype._onPESPrivateDataArrived=function(g){var b=this;Promise.resolve().then(function(){b._emitter.emit(h.a.PES_PRIVATE_DATA_ARRIVED,g)})},m.prototype._onStatisticsInfo=function(g){var b=this;Promise.resolve().then(function(){b._emitter.emit(h.a.STATISTICS_INFO,g)})},m.prototype._onIOError=function(g,b){var v=this;Promise.resolve().then(function(){v._emitter.emit(h.a.IO_ERROR,g,b)})},m.prototype._onDemuxError=function(g,b){var v=this;Promise.resolve().then(function(){v._emitter.emit(h.a.DEMUX_ERROR,g,b)})},m.prototype._onRecommendSeekpoint=function(g){var b=this;Promise.resolve().then(function(){b._emitter.emit(h.a.RECOMMEND_SEEKPOINT,g)})},m.prototype._onLoggingConfigChanged=function(g){this._worker&&this._worker.postMessage({cmd:"logging_config",param:g})},m.prototype._onWorkerMessage=function(g){var b=g.data,v=b.data;if(b.msg==="destroyed"||this._workerDestroying)return this._workerDestroying=!1,this._worker.terminate(),void(this._worker=null);switch(b.msg){case h.a.INIT_SEGMENT:case h.a.MEDIA_SEGMENT:this._emitter.emit(b.msg,v.type,v.data);break;case h.a.LOADING_COMPLETE:case h.a.RECOVERED_EARLY_EOF:this._emitter.emit(b.msg);break;case h.a.MEDIA_INFO:Object.setPrototypeOf(v,f.a.prototype),this._emitter.emit(b.msg,v);break;case h.a.METADATA_ARRIVED:case h.a.SCRIPTDATA_ARRIVED:case h.a.TIMED_ID3_METADATA_ARRIVED:case h.a.SYNCHRONOUS_KLV_METADATA_ARRIVED:case h.a.ASYNCHRONOUS_KLV_METADATA_ARRIVED:case h.a.SMPTE2038_METADATA_ARRIVED:case h.a.SCTE35_METADATA_ARRIVED:case h.a.PES_PRIVATE_DATA_DESCRIPTOR:case h.a.PES_PRIVATE_DATA_ARRIVED:case h.a.STATISTICS_INFO:this._emitter.emit(b.msg,v);break;case h.a.IO_ERROR:case h.a.DEMUX_ERROR:this._emitter.emit(b.msg,v.type,v.info);break;case h.a.RECOMMEND_SEEKPOINT:this._emitter.emit(b.msg,v);break;case"logcat_callback":c.a.emitter.emit("log",v.type,v.logcat)}},m}();r.a=p},function(n,r,i){function s(c){var u={};function d(f){if(u[f])return u[f].exports;var p=u[f]={i:f,l:!1,exports:{}};return c[f].call(p.exports,p,p.exports,d),p.l=!0,p.exports}d.m=c,d.c=u,d.i=function(f){return f},d.d=function(f,p,m){d.o(f,p)||Object.defineProperty(f,p,{configurable:!1,enumerable:!0,get:m})},d.r=function(f){Object.defineProperty(f,"__esModule",{value:!0})},d.n=function(f){var p=f&&f.__esModule?function(){return f.default}:function(){return f};return d.d(p,"a",p),p},d.o=function(f,p){return Object.prototype.hasOwnProperty.call(f,p)},d.p="/",d.oe=function(f){throw console.error(f),f};var h=d(d.s=ENTRY_MODULE);return h.default||h}function a(c){return(c+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function o(c,u,d){var h={};h[d]=[];var f=u.toString(),p=f.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/);if(!p)return h;for(var m,g=p[1],b=new RegExp("(\\\\n|\\W)"+a(g)+"\\(\\s*(/\\*.*?\\*/)?\\s*.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)","g");m=b.exec(f);)m[3]!=="dll-reference"&&h[d].push(m[3]);for(b=new RegExp("\\("+a(g)+'\\("(dll-reference\\s([\\.|\\-|\\+|\\w|/|@]+))"\\)\\)\\(\\s*(/\\*.*?\\*/)?\\s*.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)',"g");m=b.exec(f);)c[m[2]]||(h[d].push(m[1]),c[m[2]]=i(m[1]).m),h[m[2]]=h[m[2]]||[],h[m[2]].push(m[4]);for(var v,S=Object.keys(h),E=0;E<S.length;E++)for(var L=0;L<h[S[E]].length;L++)v=h[S[E]][L],isNaN(1*v)||(h[S[E]][L]=1*h[S[E]][L]);return h}function l(c){return Object.keys(c).reduce(function(u,d){return u||c[d].length>0},!1)}n.exports=function(c,u){u=u||{};var d={main:i.m},h=u.all?{main:Object.keys(d.main)}:function(b,v){for(var S={main:[v]},E={main:[]},L={main:{}};l(S);)for(var U=Object.keys(S),O=0;O<U.length;O++){var k=U[O],I=S[k].pop();if(L[k]=L[k]||{},!L[k][I]&&b[k][I]){L[k][I]=!0,E[k]=E[k]||[],E[k].push(I);for(var R=o(b,b[k][I],k),M=Object.keys(R),z=0;z<M.length;z++)S[M[z]]=S[M[z]]||[],S[M[z]]=S[M[z]].concat(R[M[z]])}}return E}(d,c),f="";Object.keys(h).filter(function(b){return b!=="main"}).forEach(function(b){for(var v=0;h[b][v];)v++;h[b].push(v),d[b][v]="(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })",f=f+"var "+b+" = ("+s.toString().replace("ENTRY_MODULE",JSON.stringify(v))+")({"+h[b].map(function(S){return JSON.stringify(S)+": "+d[b][S].toString()}).join(",")+`});
`}),f=f+"new (("+s.toString().replace("ENTRY_MODULE",JSON.stringify(c))+")({"+h.main.map(function(b){return JSON.stringify(b)+": "+d.main[b].toString()}).join(",")+"}))(self);";var p=new self.Blob([f],{type:"text/javascript"});if(u.bare)return p;var m=(self.URL||self.webkitURL||self.mozURL||self.msURL).createObjectURL(p),g=new self.Worker(m);return g.objectURL=m,g}},function(n,r,i){i.r(r),i(0);var s=i(8),a=i(15),o=i(13),l=i(1);r.default=function(c){var u=null,d=(function(W,re){c.postMessage({msg:"logcat_callback",data:{type:W,logcat:re}})}).bind(this);function h(W,re){var X={msg:l.a.INIT_SEGMENT,data:{type:W,data:re}};c.postMessage(X,[re.data])}function f(W,re){var X={msg:l.a.MEDIA_SEGMENT,data:{type:W,data:re}};c.postMessage(X,[re.data])}function p(){var W={msg:l.a.LOADING_COMPLETE};c.postMessage(W)}function m(){var W={msg:l.a.RECOVERED_EARLY_EOF};c.postMessage(W)}function g(W){var re={msg:l.a.MEDIA_INFO,data:W};c.postMessage(re)}function b(W){var re={msg:l.a.METADATA_ARRIVED,data:W};c.postMessage(re)}function v(W){var re={msg:l.a.SCRIPTDATA_ARRIVED,data:W};c.postMessage(re)}function S(W){var re={msg:l.a.TIMED_ID3_METADATA_ARRIVED,data:W};c.postMessage(re)}function E(W){var re={msg:l.a.SYNCHRONOUS_KLV_METADATA_ARRIVED,data:W};c.postMessage(re)}function L(W){var re={msg:l.a.ASYNCHRONOUS_KLV_METADATA_ARRIVED,data:W};c.postMessage(re)}function U(W){var re={msg:l.a.SMPTE2038_METADATA_ARRIVED,data:W};c.postMessage(re)}function O(W){var re={msg:l.a.SCTE35_METADATA_ARRIVED,data:W};c.postMessage(re)}function k(W){var re={msg:l.a.PES_PRIVATE_DATA_DESCRIPTOR,data:W};c.postMessage(re)}function I(W){var re={msg:l.a.PES_PRIVATE_DATA_ARRIVED,data:W};c.postMessage(re)}function R(W){var re={msg:l.a.STATISTICS_INFO,data:W};c.postMessage(re)}function M(W,re){c.postMessage({msg:l.a.IO_ERROR,data:{type:W,info:re}})}function z(W,re){c.postMessage({msg:l.a.DEMUX_ERROR,data:{type:W,info:re}})}function Z(W){c.postMessage({msg:l.a.RECOMMEND_SEEKPOINT,data:W})}a.a.install(),c.addEventListener("message",function(W){switch(W.data.cmd){case"init":(u=new o.a(W.data.param[0],W.data.param[1])).on(l.a.IO_ERROR,M.bind(this)),u.on(l.a.DEMUX_ERROR,z.bind(this)),u.on(l.a.INIT_SEGMENT,h.bind(this)),u.on(l.a.MEDIA_SEGMENT,f.bind(this)),u.on(l.a.LOADING_COMPLETE,p.bind(this)),u.on(l.a.RECOVERED_EARLY_EOF,m.bind(this)),u.on(l.a.MEDIA_INFO,g.bind(this)),u.on(l.a.METADATA_ARRIVED,b.bind(this)),u.on(l.a.SCRIPTDATA_ARRIVED,v.bind(this)),u.on(l.a.TIMED_ID3_METADATA_ARRIVED,S.bind(this)),u.on(l.a.SYNCHRONOUS_KLV_METADATA_ARRIVED,E.bind(this)),u.on(l.a.ASYNCHRONOUS_KLV_METADATA_ARRIVED,L.bind(this)),u.on(l.a.SMPTE2038_METADATA_ARRIVED,U.bind(this)),u.on(l.a.SCTE35_METADATA_ARRIVED,O.bind(this)),u.on(l.a.PES_PRIVATE_DATA_DESCRIPTOR,k.bind(this)),u.on(l.a.PES_PRIVATE_DATA_ARRIVED,I.bind(this)),u.on(l.a.STATISTICS_INFO,R.bind(this)),u.on(l.a.RECOMMEND_SEEKPOINT,Z.bind(this));break;case"destroy":u&&(u.destroy(),u=null),c.postMessage({msg:"destroyed"});break;case"start":u.start();break;case"stop":u.stop();break;case"seek":u.seek(W.data.param);break;case"pause":u.pause();break;case"resume":u.resume();break;case"logging_config":var re=W.data.param;s.a.applyConfig(re),re.enableCallback===!0?s.a.addLogListener(d):s.a.removeLogListener(d)}})}},function(n,r,i){n.exports=i(25).default},function(n,r,i){(function(s,a){/*!
 * @overview es6-promise - a tiny implementation of Promises/A+.
 * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
 * @license   Licensed under MIT license
 *            See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
 * @version   v4.2.8+1e68dce6
 */var o;o=function(){function l(ye){return typeof ye=="function"}var c=Array.isArray?Array.isArray:function(ye){return Object.prototype.toString.call(ye)==="[object Array]"},u=0,d=void 0,h=void 0,f=function(ye,Ie){E[u]=ye,E[u+1]=Ie,(u+=2)===2&&(h?h(L):R())},p=typeof window<"u"?window:void 0,m=p||{},g=m.MutationObserver||m.WebKitMutationObserver,b=typeof self>"u"&&s!==void 0&&{}.toString.call(s)==="[object process]",v=typeof Uint8ClampedArray<"u"&&typeof importScripts<"u"&&typeof MessageChannel<"u";function S(){var ye=setTimeout;return function(){return ye(L,1)}}var E=new Array(1e3);function L(){for(var ye=0;ye<u;ye+=2)(0,E[ye])(E[ye+1]),E[ye]=void 0,E[ye+1]=void 0;u=0}var U,O,k,I,R=void 0;function M(ye,Ie){var Ae=this,Ee=new this.constructor(W);Ee[Z]===void 0&&Le(Ee);var je=Ae._state;if(je){var Me=arguments[je-1];f(function(){return ie(je,Ee,Me,Ae._result)})}else H(Ae,Ee,ye,Ie);return Ee}function z(ye){if(ye&&typeof ye=="object"&&ye.constructor===this)return ye;var Ie=new this(W);return X(Ie,ye),Ie}b?R=function(){return s.nextTick(L)}:g?(O=0,k=new g(L),I=document.createTextNode(""),k.observe(I,{characterData:!0}),R=function(){I.data=O=++O%2}):v?((U=new MessageChannel).port1.onmessage=L,R=function(){return U.port2.postMessage(0)}):R=p===void 0?function(){try{var ye=Function("return this")().require("vertx");return(d=ye.runOnLoop||ye.runOnContext)!==void 0?function(){d(L)}:S()}catch{return S()}}():S();var Z=Math.random().toString(36).substring(2);function W(){}function re(ye,Ie,Ae){Ie.constructor===ye.constructor&&Ae===M&&Ie.constructor.resolve===z?function(Ee,je){je._state===1?Q(Ee,je._result):je._state===2?G(Ee,je._result):H(je,void 0,function(Me){return X(Ee,Me)},function(Me){return G(Ee,Me)})}(ye,Ie):Ae===void 0?Q(ye,Ie):l(Ae)?function(Ee,je,Me){f(function(Pt){var tn=!1,Dn=function(lt,un,Sn,tr){try{lt.call(un,Sn,tr)}catch(Un){return Un}}(Me,je,function(lt){tn||(tn=!0,je!==lt?X(Pt,lt):Q(Pt,lt))},function(lt){tn||(tn=!0,G(Pt,lt))},Pt._label);!tn&&Dn&&(tn=!0,G(Pt,Dn))},Ee)}(ye,Ie,Ae):Q(ye,Ie)}function X(ye,Ie){if(ye===Ie)G(ye,new TypeError("You cannot resolve a promise with itself"));else if(je=typeof(Ee=Ie),Ee===null||je!=="object"&&je!=="function")Q(ye,Ie);else{var Ae=void 0;try{Ae=Ie.then}catch(Me){return void G(ye,Me)}re(ye,Ie,Ae)}var Ee,je}function oe(ye){ye._onerror&&ye._onerror(ye._result),Y(ye)}function Q(ye,Ie){ye._state===void 0&&(ye._result=Ie,ye._state=1,ye._subscribers.length!==0&&f(Y,ye))}function G(ye,Ie){ye._state===void 0&&(ye._state=2,ye._result=Ie,f(oe,ye))}function H(ye,Ie,Ae,Ee){var je=ye._subscribers,Me=je.length;ye._onerror=null,je[Me]=Ie,je[Me+1]=Ae,je[Me+2]=Ee,Me===0&&ye._state&&f(Y,ye)}function Y(ye){var Ie=ye._subscribers,Ae=ye._state;if(Ie.length!==0){for(var Ee=void 0,je=void 0,Me=ye._result,Pt=0;Pt<Ie.length;Pt+=3)Ee=Ie[Pt],je=Ie[Pt+Ae],Ee?ie(Ae,Ee,je,Me):je(Me);ye._subscribers.length=0}}function ie(ye,Ie,Ae,Ee){var je=l(Ae),Me=void 0,Pt=void 0,tn=!0;if(je){try{Me=Ae(Ee)}catch(Dn){tn=!1,Pt=Dn}if(Ie===Me)return void G(Ie,new TypeError("A promises callback cannot return that same promise."))}else Me=Ee;Ie._state!==void 0||(je&&tn?X(Ie,Me):tn===!1?G(Ie,Pt):ye===1?Q(Ie,Me):ye===2&&G(Ie,Me))}var Ce=0;function Le(ye){ye[Z]=Ce++,ye._state=void 0,ye._result=void 0,ye._subscribers=[]}var ke=function(){function ye(Ie,Ae){this._instanceConstructor=Ie,this.promise=new Ie(W),this.promise[Z]||Le(this.promise),c(Ae)?(this.length=Ae.length,this._remaining=Ae.length,this._result=new Array(this.length),this.length===0?Q(this.promise,this._result):(this.length=this.length||0,this._enumerate(Ae),this._remaining===0&&Q(this.promise,this._result))):G(this.promise,new Error("Array Methods must be provided an Array"))}return ye.prototype._enumerate=function(Ie){for(var Ae=0;this._state===void 0&&Ae<Ie.length;Ae++)this._eachEntry(Ie[Ae],Ae)},ye.prototype._eachEntry=function(Ie,Ae){var Ee=this._instanceConstructor,je=Ee.resolve;if(je===z){var Me=void 0,Pt=void 0,tn=!1;try{Me=Ie.then}catch(lt){tn=!0,Pt=lt}if(Me===M&&Ie._state!==void 0)this._settledAt(Ie._state,Ae,Ie._result);else if(typeof Me!="function")this._remaining--,this._result[Ae]=Ie;else if(Ee===Ne){var Dn=new Ee(W);tn?G(Dn,Pt):re(Dn,Ie,Me),this._willSettleAt(Dn,Ae)}else this._willSettleAt(new Ee(function(lt){return lt(Ie)}),Ae)}else this._willSettleAt(je(Ie),Ae)},ye.prototype._settledAt=function(Ie,Ae,Ee){var je=this.promise;je._state===void 0&&(this._remaining--,Ie===2?G(je,Ee):this._result[Ae]=Ee),this._remaining===0&&Q(je,this._result)},ye.prototype._willSettleAt=function(Ie,Ae){var Ee=this;H(Ie,void 0,function(je){return Ee._settledAt(1,Ae,je)},function(je){return Ee._settledAt(2,Ae,je)})},ye}(),Ne=function(){function ye(Ie){this[Z]=Ce++,this._result=this._state=void 0,this._subscribers=[],W!==Ie&&(typeof Ie!="function"&&function(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}(),this instanceof ye?function(Ae,Ee){try{Ee(function(je){X(Ae,je)},function(je){G(Ae,je)})}catch(je){G(Ae,je)}}(this,Ie):function(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}())}return ye.prototype.catch=function(Ie){return this.then(null,Ie)},ye.prototype.finally=function(Ie){var Ae=this.constructor;return l(Ie)?this.then(function(Ee){return Ae.resolve(Ie()).then(function(){return Ee})},function(Ee){return Ae.resolve(Ie()).then(function(){throw Ee})}):this.then(Ie,Ie)},ye}();return Ne.prototype.then=M,Ne.all=function(ye){return new ke(this,ye).promise},Ne.race=function(ye){var Ie=this;return c(ye)?new Ie(function(Ae,Ee){for(var je=ye.length,Me=0;Me<je;Me++)Ie.resolve(ye[Me]).then(Ae,Ee)}):new Ie(function(Ae,Ee){return Ee(new TypeError("You must pass an array to race."))})},Ne.resolve=z,Ne.reject=function(ye){var Ie=new this(W);return G(Ie,ye),Ie},Ne._setScheduler=function(ye){h=ye},Ne._setAsap=function(ye){f=ye},Ne._asap=f,Ne.polyfill=function(){var ye=void 0;if(a!==void 0)ye=a;else if(typeof self<"u")ye=self;else try{ye=Function("return this")()}catch{throw new Error("polyfill failed because global object is unavailable in this environment")}var Ie=ye.Promise;if(Ie){var Ae=null;try{Ae=Object.prototype.toString.call(Ie.resolve())}catch{}if(Ae==="[object Promise]"&&!Ie.cast)return}ye.Promise=Ne},Ne.Promise=Ne,Ne},n.exports=o()}).call(this,i(22),i(23))},function(n,r){var i,s,a=n.exports={};function o(){throw new Error("setTimeout has not been defined")}function l(){throw new Error("clearTimeout has not been defined")}function c(v){if(i===setTimeout)return setTimeout(v,0);if((i===o||!i)&&setTimeout)return i=setTimeout,setTimeout(v,0);try{return i(v,0)}catch{try{return i.call(null,v,0)}catch{return i.call(this,v,0)}}}(function(){try{i=typeof setTimeout=="function"?setTimeout:o}catch{i=o}try{s=typeof clearTimeout=="function"?clearTimeout:l}catch{s=l}})();var u,d=[],h=!1,f=-1;function p(){h&&u&&(h=!1,u.length?d=u.concat(d):f=-1,d.length&&m())}function m(){if(!h){var v=c(p);h=!0;for(var S=d.length;S;){for(u=d,d=[];++f<S;)u&&u[f].run();f=-1,S=d.length}u=null,h=!1,function(E){if(s===clearTimeout)return clearTimeout(E);if((s===l||!s)&&clearTimeout)return s=clearTimeout,clearTimeout(E);try{s(E)}catch{try{return s.call(null,E)}catch{return s.call(this,E)}}}(v)}}function g(v,S){this.fun=v,this.array=S}function b(){}a.nextTick=function(v){var S=new Array(arguments.length-1);if(arguments.length>1)for(var E=1;E<arguments.length;E++)S[E-1]=arguments[E];d.push(new g(v,S)),d.length!==1||h||c(m)},g.prototype.run=function(){this.fun.apply(null,this.array)},a.title="browser",a.browser=!0,a.env={},a.argv=[],a.version="",a.versions={},a.on=b,a.addListener=b,a.once=b,a.off=b,a.removeListener=b,a.removeAllListeners=b,a.emit=b,a.prependListener=b,a.prependOnceListener=b,a.listeners=function(v){return[]},a.binding=function(v){throw new Error("process.binding is not supported")},a.cwd=function(){return"/"},a.chdir=function(v){throw new Error("process.chdir is not supported")},a.umask=function(){return 0}},function(n,r){var i;i=function(){return this}();try{i=i||new Function("return this")()}catch{typeof window=="object"&&(i=window)}n.exports=i},function(n,r,i){i.r(r);var s=i(0),a=i(8),o=i(3),l=i(7),c=i(16),u=i(17),d=i(1),h=i(4),f=i(10);r.default=function(p){var m="PlayerEngineWorker",g=(function(G,H){p.postMessage({msg:"logcat_callback",type:G,logcat:H})}).bind(void 0),b=null,v=null,S=null,E=null,L=!1,U=!1,O=0,k=0,I=!1;function R(){S&&(S.shutdown(),S.destroy(),S=null)}function M(){if(b==null||v==null)throw new o.a("Worker not initialized");if(E)throw new o.a("Transmuxer has been initialized");U||(!v.deferLoadAfterSourceOpen||L?((E=new u.a(b,v)).on(d.a.INIT_SEGMENT,function(G,H){S.appendInitSegment(H)}),E.on(d.a.MEDIA_SEGMENT,function(G,H){S.appendMediaSegment(H),p.postMessage({msg:"buffered_position_changed",buffered_position_milliseconds:H.info.endDts})}),E.on(d.a.LOADING_COMPLETE,function(){S.endOfStream(),p.postMessage({msg:"player_event",event:h.a.LOADING_COMPLETE})}),E.on(d.a.RECOVERED_EARLY_EOF,function(){p.postMessage({msg:"player_event",event:h.a.RECOVERED_EARLY_EOF})}),E.on(d.a.IO_ERROR,function(G,H){p.postMessage({msg:"player_event",event:h.a.ERROR,error_type:f.b.NETWORK_ERROR,error_detail:G,info:H})}),E.on(d.a.DEMUX_ERROR,function(G,H){p.postMessage({msg:"player_event",event:h.a.ERROR,error_type:f.b.MEDIA_ERROR,error_detail:G,info:H})}),E.on(d.a.MEDIA_INFO,function(G){oe(d.a.MEDIA_INFO,G)}),E.on(d.a.STATISTICS_INFO,function(G){oe(d.a.STATISTICS_INFO,G)}),E.on(d.a.RECOMMEND_SEEKPOINT,function(G){(function(H){p.postMessage({msg:"transmuxing_event",event:d.a.RECOMMEND_SEEKPOINT,milliseconds:H})})(G)}),E.on(d.a.METADATA_ARRIVED,function(G){Q(h.a.METADATA_ARRIVED,G)}),E.on(d.a.SCRIPTDATA_ARRIVED,function(G){Q(h.a.SCRIPTDATA_ARRIVED,G)}),E.on(d.a.TIMED_ID3_METADATA_ARRIVED,function(G){Q(h.a.TIMED_ID3_METADATA_ARRIVED,G)}),E.on(d.a.SYNCHRONOUS_KLV_METADATA_ARRIVED,function(G){Q(h.a.SYNCHRONOUS_KLV_METADATA_ARRIVED,G)}),E.on(d.a.ASYNCHRONOUS_KLV_METADATA_ARRIVED,function(G){Q(h.a.ASYNCHRONOUS_KLV_METADATA_ARRIVED,G)}),E.on(d.a.SMPTE2038_METADATA_ARRIVED,function(G){Q(h.a.SMPTE2038_METADATA_ARRIVED,G)}),E.on(d.a.SCTE35_METADATA_ARRIVED,function(G){Q(h.a.SCTE35_METADATA_ARRIVED,G)}),E.on(d.a.PES_PRIVATE_DATA_DESCRIPTOR,function(G){Q(h.a.PES_PRIVATE_DATA_DESCRIPTOR,G)}),E.on(d.a.PES_PRIVATE_DATA_ARRIVED,function(G){Q(h.a.PES_PRIVATE_DATA_ARRIVED,G)}),E.open()):U=!0)}function z(){S&&S.flush(),E&&(E.close(),E.destroy(),E=null)}function Z(){L=!0,U&&(U=!1,M())}function W(){p.postMessage({msg:"mse_event",event:l.a.UPDATE_END})}function re(){s.a.v(m,"MSE SourceBuffer is full, report to main thread"),p.postMessage({msg:"mse_event",event:l.a.BUFFER_FULL})}function X(G){p.postMessage({msg:"player_event",event:h.a.ERROR,error_type:f.b.MEDIA_ERROR,error_detail:f.b.MEDIA_MSE_ERROR,info:G})}function oe(G,H){p.postMessage({msg:"transmuxing_event",event:G,info:H})}function Q(G,H){p.postMessage({msg:"player_event",event:G,extraData:H})}p.addEventListener("message",function(G){if(!I){var H=G.data;switch(H.cmd){case"logging_config":var Y=H;a.a.applyConfig(Y.logging_config),Y.logging_config.enableCallback===!0?a.a.addLogListener(g):a.a.removeLogListener(g);break;case"init":b=(Y=H).media_data_source,v=Y.config;break;case"destroy":(function(){E&&z(),S&&R(),I=!0,p.postMessage({msg:"destroyed"})})();break;case"initialize_mse":(function(){s.a.v(m,"Initializing MediaSource in DedicatedWorker"),(S=new c.a(v)).on(l.a.SOURCE_OPEN,Z.bind(this)),S.on(l.a.UPDATE_END,W.bind(this)),S.on(l.a.BUFFER_FULL,re.bind(this)),S.on(l.a.ERROR,X.bind(this)),S.initialize({getCurrentTime:function(){return O},getReadyState:function(){return k}});var ie=S.getHandle();p.postMessage({msg:"mse_init",handle:ie},[ie])})();break;case"shutdown_mse":R();break;case"load":M();break;case"unload":z();break;case"unbuffered_seek":Y=H,S.flush(),E.seek(Y.milliseconds);break;case"timeupdate":O=(Y=H).current_time;break;case"readystatechange":k=(Y=H).ready_state;break;case"pause_transmuxer":E.pause();break;case"resume_transmuxer":E.resume()}}})}},function(n,r,i){i.r(r);var s=i(15),a=i(14),o={enableWorker:!1,enableWorkerForMSE:!1,enableStashBuffer:!0,stashInitialSize:void 0,isLive:!1,liveBufferLatencyChasing:!1,liveBufferLatencyChasingOnPaused:!1,liveBufferLatencyMaxLatency:1.5,liveBufferLatencyMinRemain:.5,liveSync:!1,liveSyncMaxLatency:1.2,liveSyncTargetLatency:.8,liveSyncPlaybackRate:1.2,lazyLoad:!0,lazyLoadMaxDuration:180,lazyLoadRecoverDuration:30,deferLoadAfterSourceOpen:!0,autoCleanupMaxBackwardDuration:180,autoCleanupMinBackwardDuration:120,statisticsInfoReportInterval:600,fixAudioTimestampGap:!0,accurateSeek:!1,seekType:"range",seekParamStart:"bstart",seekParamEnd:"bend",rangeLoadZeroStart:!1,customSeekHandler:void 0,reuseRedirectedURL:!1,headers:void 0,customLoader:void 0};function l(){return Object.assign({},o)}var c=function(){function G(){}return G.supportMSEH264Playback=function(){var H=self.MediaSource&&self.MediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),Y=self.ManagedMediaSource&&self.ManagedMediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"');return H||Y},G.supportMSEH265Playback=function(){var H=self.MediaSource&&self.MediaSource.isTypeSupported('video/mp4; codecs="hvc1.1.6.L93.B0"'),Y=self.ManagedMediaSource&&self.ManagedMediaSource.isTypeSupported('video/mp4; codecs="hvc1.1.6.L93.B0"');return H||Y},G.supportNetworkStreamIO=function(){var H=new a.a({},l()),Y=H.loaderType;return H.destroy(),Y=="fetch-stream-loader"||Y=="xhr-moz-chunked-loader"},G.getNetworkLoaderTypeName=function(){var H=new a.a({},l()),Y=H.loaderType;return H.destroy(),Y},G.supportNativeMediaPlayback=function(H){G.videoElement==null&&(G.videoElement=window.document.createElement("video"));var Y=G.videoElement.canPlayType(H);return Y==="probably"||Y=="maybe"},G.getFeatureList=function(){var H={msePlayback:!1,mseLivePlayback:!1,mseH265Playback:!1,networkStreamIO:!1,networkLoaderName:"",nativeMP4H264Playback:!1,nativeMP4H265Playback:!1,nativeWebmVP8Playback:!1,nativeWebmVP9Playback:!1};return H.msePlayback=G.supportMSEH264Playback(),H.networkStreamIO=G.supportNetworkStreamIO(),H.networkLoaderName=G.getNetworkLoaderTypeName(),H.mseLivePlayback=H.msePlayback&&H.networkStreamIO,H.mseH265Playback=G.supportMSEH265Playback(),H.nativeMP4H264Playback=G.supportNativeMediaPlayback('video/mp4; codecs="avc1.42001E, mp4a.40.2"'),H.nativeMP4H265Playback=G.supportNativeMediaPlayback('video/mp4; codecs="hvc1.1.6.L93.B0"'),H.nativeWebmVP8Playback=G.supportNativeMediaPlayback('video/webm; codecs="vp8.0, vorbis"'),H.nativeWebmVP9Playback=G.supportNativeMediaPlayback('video/webm; codecs="vp9"'),H},G}(),u=i(2),d=i(0),h=i(9),f=i.n(h),p=i(16),m=i(4),g=i(17),b=i(7),v=i(10),S=i(3),E=i(1),L=i(5),U=i(11),O=function(){function G(H,Y,ie){this.TAG="SeekingHandler",this._config=null,this._media_element=null,this._always_seek_keyframe=!1,this._on_unbuffered_seek=null,this._request_set_current_time=!1,this._seek_request_record_clocktime=null,this._idr_sample_list=new U.a,this.e=null,this._config=H,this._media_element=Y,this._on_unbuffered_seek=ie,this.e={onMediaSeeking:this._onMediaSeeking.bind(this)};var Ce=L.a.chrome&&(L.a.version.major<50||L.a.version.major===50&&L.a.version.build<2661);this._always_seek_keyframe=!!(Ce||L.a.msedge||L.a.msie),this._always_seek_keyframe&&(this._config.accurateSeek=!1),this._media_element.addEventListener("seeking",this.e.onMediaSeeking)}return G.prototype.destroy=function(){this._idr_sample_list.clear(),this._idr_sample_list=null,this._media_element.removeEventListener("seeking",this.e.onMediaSeeking),this._media_element=null,this._on_unbuffered_seek=null},G.prototype.seek=function(H){var Y=this._isPositionBuffered(H),ie=!1;if(H<1&&this._media_element.buffered.length>0){var Ce=this._media_element.buffered.start(0);(Ce<1&&H<Ce||L.a.safari)&&(ie=!0,H=L.a.safari?.1:Ce)}if(ie)this.directSeek(H);else if(Y)if(this._always_seek_keyframe){var Le=this._getNearestKeyframe(Math.floor(1e3*H));Le!=null&&(H=Le.dts/1e3),this.directSeek(H)}else this.directSeek(H);else this._idr_sample_list.clear(),this._on_unbuffered_seek(Math.floor(1e3*H)),this._config.accurateSeek&&this.directSeek(H)},G.prototype.directSeek=function(H){this._request_set_current_time=!0,this._media_element.currentTime=H},G.prototype.appendSyncPoints=function(H){this._idr_sample_list.appendArray(H)},G.prototype._onMediaSeeking=function(H){if(this._request_set_current_time)this._request_set_current_time=!1;else{var Y=this._media_element.currentTime,ie=this._media_element.buffered;if(Y<1&&ie.length>0){var Ce=ie.start(0);if(Ce<1&&Y<Ce||L.a.safari){var Le=L.a.safari?.1:Ce;return void this.directSeek(Le)}}if(this._isPositionBuffered(Y)){if(this._always_seek_keyframe){var ke=this._getNearestKeyframe(Math.floor(1e3*Y));ke!=null&&(Y=ke.dts/1e3,this.directSeek(Y))}}else this._seek_request_record_clocktime=G._getClockTime(),window.setTimeout(this._pollAndApplyUnbufferedSeek.bind(this),50)}},G.prototype._pollAndApplyUnbufferedSeek=function(){if(this._seek_request_record_clocktime!=null)if(this._seek_request_record_clocktime<=G._getClockTime()-100){var H=this._media_element.currentTime;this._seek_request_record_clocktime=null,this._isPositionBuffered(H)||(this._idr_sample_list.clear(),this._on_unbuffered_seek(Math.floor(1e3*H)),this._config.accurateSeek&&this.directSeek(H))}else window.setTimeout(this._pollAndApplyUnbufferedSeek.bind(this),50)},G.prototype._isPositionBuffered=function(H){for(var Y=this._media_element.buffered,ie=0;ie<Y.length;ie++){var Ce=Y.start(ie),Le=Y.end(ie);if(H>=Ce&&H<Le)return!0}return!1},G.prototype._getNearestKeyframe=function(H){return this._idr_sample_list.getLastSyncPointBeforeDts(H)},G._getClockTime=function(){return self.performance&&self.performance.now?self.performance.now():Date.now()},G}(),k=function(){function G(H,Y,ie,Ce){this.TAG="LoadingController",this._config=null,this._media_element=null,this._on_pause_transmuxer=null,this._on_resume_transmuxer=null,this._paused=!1,this.e=null,this._config=H,this._media_element=Y,this._on_pause_transmuxer=ie,this._on_resume_transmuxer=Ce,this.e={onMediaTimeUpdate:this._onMediaTimeUpdate.bind(this)}}return G.prototype.destroy=function(){this._media_element.removeEventListener("timeupdate",this.e.onMediaTimeUpdate),this.e=null,this._media_element=null,this._config=null,this._on_pause_transmuxer=null,this._on_resume_transmuxer=null},G.prototype.notifyBufferedPositionChanged=function(H){!this._config.isLive&&this._config.lazyLoad&&(H==null?this._suspendTransmuxerIfNeeded():this._suspendTransmuxerIfBufferedPositionExceeded(H))},G.prototype._onMediaTimeUpdate=function(H){this._paused&&this._resumeTransmuxerIfNeeded()},G.prototype._suspendTransmuxerIfNeeded=function(){for(var H=this._media_element.buffered,Y=this._media_element.currentTime,ie=0,Ce=0;Ce<H.length;Ce++){var Le=H.start(Ce),ke=H.end(Ce);if(Le<=Y&&Y<ke){ie=ke;break}}ie>0&&this._suspendTransmuxerIfBufferedPositionExceeded(ie)},G.prototype._suspendTransmuxerIfBufferedPositionExceeded=function(H){H>=this._media_element.currentTime+this._config.lazyLoadMaxDuration&&!this._paused&&(d.a.v(this.TAG,"Maximum buffering duration exceeded, suspend transmuxing task"),this.suspendTransmuxer(),this._media_element.addEventListener("timeupdate",this.e.onMediaTimeUpdate))},G.prototype.suspendTransmuxer=function(){this._paused=!0,this._on_pause_transmuxer()},G.prototype._resumeTransmuxerIfNeeded=function(){for(var H=this._media_element.buffered,Y=this._media_element.currentTime,ie=this._config.lazyLoadRecoverDuration,Ce=!1,Le=0;Le<H.length;Le++){var ke=H.start(Le),Ne=H.end(Le);if(Y>=ke&&Y<Ne){Y>=Ne-ie&&(Ce=!0);break}}Ce&&(d.a.v(this.TAG,"Continue loading from paused position"),this.resumeTransmuxer(),this._media_element.removeEventListener("timeupdate",this.e.onMediaTimeUpdate))},G.prototype.resumeTransmuxer=function(){this._paused=!1,this._on_resume_transmuxer()},G}(),I=function(){function G(H,Y){this.TAG="StartupStallJumper",this._media_element=null,this._on_direct_seek=null,this._canplay_received=!1,this.e=null,this._media_element=H,this._on_direct_seek=Y,this.e={onMediaCanPlay:this._onMediaCanPlay.bind(this),onMediaStalled:this._onMediaStalled.bind(this),onMediaProgress:this._onMediaProgress.bind(this)},this._media_element.addEventListener("canplay",this.e.onMediaCanPlay),this._media_element.addEventListener("stalled",this.e.onMediaStalled),this._media_element.addEventListener("progress",this.e.onMediaProgress)}return G.prototype.destroy=function(){this._media_element.removeEventListener("canplay",this.e.onMediaCanPlay),this._media_element.removeEventListener("stalled",this.e.onMediaStalled),this._media_element.removeEventListener("progress",this.e.onMediaProgress),this._media_element=null,this._on_direct_seek=null},G.prototype._onMediaCanPlay=function(H){this._canplay_received=!0,this._media_element.removeEventListener("canplay",this.e.onMediaCanPlay)},G.prototype._onMediaStalled=function(H){this._detectAndFixStuckPlayback(!0)},G.prototype._onMediaProgress=function(H){this._detectAndFixStuckPlayback()},G.prototype._detectAndFixStuckPlayback=function(H){var Y=this._media_element,ie=Y.buffered;H||!this._canplay_received||Y.readyState<2?ie.length>0&&Y.currentTime<ie.start(0)&&(d.a.w(this.TAG,"Playback seems stuck at ".concat(Y.currentTime,", seek to ").concat(ie.start(0))),this._on_direct_seek(ie.start(0)),this._media_element.removeEventListener("progress",this.e.onMediaProgress)):this._media_element.removeEventListener("progress",this.e.onMediaProgress)},G}(),R=function(){function G(H,Y,ie){this._config=null,this._media_element=null,this._on_direct_seek=null,this._config=H,this._media_element=Y,this._on_direct_seek=ie}return G.prototype.destroy=function(){this._on_direct_seek=null,this._media_element=null,this._config=null},G.prototype.notifyBufferedRangeUpdate=function(){this._chaseLiveLatency()},G.prototype._chaseLiveLatency=function(){var H=this._media_element.buffered,Y=this._media_element.currentTime,ie=this._media_element.paused;if(this._config.isLive&&this._config.liveBufferLatencyChasing&&H.length!=0&&(this._config.liveBufferLatencyChasingOnPaused||!ie)){var Ce=H.end(H.length-1);if(Ce>this._config.liveBufferLatencyMaxLatency&&Ce-Y>this._config.liveBufferLatencyMaxLatency){var Le=Ce-this._config.liveBufferLatencyMinRemain;this._on_direct_seek(Le)}}},G}(),M=function(){function G(H,Y){this._config=null,this._media_element=null,this.e=null,this._config=H,this._media_element=Y,this.e={onMediaTimeUpdate:this._onMediaTimeUpdate.bind(this)},this._media_element.addEventListener("timeupdate",this.e.onMediaTimeUpdate)}return G.prototype.destroy=function(){this._media_element.removeEventListener("timeupdate",this.e.onMediaTimeUpdate),this._media_element=null,this._config=null},G.prototype._onMediaTimeUpdate=function(H){if(this._config.isLive&&this._config.liveSync){var Y=this._getCurrentLatency();if(Y>this._config.liveSyncMaxLatency){var ie=Math.min(2,Math.max(1,this._config.liveSyncPlaybackRate));this._media_element.playbackRate=ie}else Y>this._config.liveSyncTargetLatency||this._media_element.playbackRate!==1&&this._media_element.playbackRate!==0&&(this._media_element.playbackRate=1)}},G.prototype._getCurrentLatency=function(){if(!this._media_element)return 0;var H=this._media_element.buffered,Y=this._media_element.currentTime;return H.length==0?0:H.end(H.length-1)-Y},G}(),z=function(){function G(H,Y){this.TAG="PlayerEngineMainThread",this._emitter=new h,this._media_element=null,this._mse_controller=null,this._transmuxer=null,this._pending_seek_time=null,this._seeking_handler=null,this._loading_controller=null,this._startup_stall_jumper=null,this._live_latency_chaser=null,this._live_latency_synchronizer=null,this._mse_source_opened=!1,this._has_pending_load=!1,this._loaded_metadata_received=!1,this._media_info=null,this._statistics_info=null,this.e=null,this._media_data_source=H,this._config=l(),typeof Y=="object"&&Object.assign(this._config,Y),H.isLive===!0&&(this._config.isLive=!0),this.e={onMediaLoadedMetadata:this._onMediaLoadedMetadata.bind(this)}}return G.prototype.destroy=function(){this._emitter.emit(m.a.DESTROYING),this._transmuxer&&this.unload(),this._media_element&&this.detachMediaElement(),this.e=null,this._media_data_source=null,this._emitter.removeAllListeners(),this._emitter=null},G.prototype.on=function(H,Y){var ie=this;this._emitter.addListener(H,Y),H===m.a.MEDIA_INFO&&this._media_info?Promise.resolve().then(function(){return ie._emitter.emit(m.a.MEDIA_INFO,ie.mediaInfo)}):H==m.a.STATISTICS_INFO&&this._statistics_info&&Promise.resolve().then(function(){return ie._emitter.emit(m.a.STATISTICS_INFO,ie.statisticsInfo)})},G.prototype.off=function(H,Y){this._emitter.removeListener(H,Y)},G.prototype.attachMediaElement=function(H){var Y=this;this._media_element=H,H.src="",H.removeAttribute("src"),H.srcObject=null,H.load(),H.addEventListener("loadedmetadata",this.e.onMediaLoadedMetadata),this._mse_controller=new p.a(this._config),this._mse_controller.on(b.a.UPDATE_END,this._onMSEUpdateEnd.bind(this)),this._mse_controller.on(b.a.BUFFER_FULL,this._onMSEBufferFull.bind(this)),this._mse_controller.on(b.a.SOURCE_OPEN,this._onMSESourceOpen.bind(this)),this._mse_controller.on(b.a.ERROR,this._onMSEError.bind(this)),this._mse_controller.on(b.a.START_STREAMING,this._onMSEStartStreaming.bind(this)),this._mse_controller.on(b.a.END_STREAMING,this._onMSEEndStreaming.bind(this)),this._mse_controller.initialize({getCurrentTime:function(){return Y._media_element.currentTime},getReadyState:function(){return Y._media_element.readyState}}),this._mse_controller.isManagedMediaSource()?(H.disableRemotePlayback=!0,H.srcObject=this._mse_controller.getObject()):H.src=this._mse_controller.getObjectURL()},G.prototype.detachMediaElement=function(){this._media_element&&(this._mse_controller.shutdown(),this._media_element.removeEventListener("loadedmetadata",this.e.onMediaLoadedMetadata),this._media_element.src="",this._media_element.removeAttribute("src"),this._media_element.srcObject=null,this._media_element.load(),this._media_element=null,this._mse_controller.revokeObjectURL()),this._mse_controller&&(this._mse_controller.destroy(),this._mse_controller=null)},G.prototype.load=function(){var H=this;if(!this._media_element)throw new S.a("HTMLMediaElement must be attached before load()!");if(this._transmuxer)throw new S.a("load() has been called, please call unload() first!");this._has_pending_load||(!this._config.deferLoadAfterSourceOpen||this._mse_source_opened?(this._transmuxer=new g.a(this._media_data_source,this._config),this._transmuxer.on(E.a.INIT_SEGMENT,function(Y,ie){H._mse_controller.appendInitSegment(ie)}),this._transmuxer.on(E.a.MEDIA_SEGMENT,function(Y,ie){H._mse_controller.appendMediaSegment(ie),!H._config.isLive&&Y==="video"&&ie.data&&ie.data.byteLength>0&&"info"in ie&&H._seeking_handler.appendSyncPoints(ie.info.syncPoints),H._loading_controller.notifyBufferedPositionChanged(ie.info.endDts/1e3)}),this._transmuxer.on(E.a.LOADING_COMPLETE,function(){H._mse_controller.endOfStream(),H._emitter.emit(m.a.LOADING_COMPLETE)}),this._transmuxer.on(E.a.RECOVERED_EARLY_EOF,function(){H._emitter.emit(m.a.RECOVERED_EARLY_EOF)}),this._transmuxer.on(E.a.IO_ERROR,function(Y,ie){H._emitter.emit(m.a.ERROR,v.b.NETWORK_ERROR,Y,ie)}),this._transmuxer.on(E.a.DEMUX_ERROR,function(Y,ie){H._emitter.emit(m.a.ERROR,v.b.MEDIA_ERROR,Y,ie)}),this._transmuxer.on(E.a.MEDIA_INFO,function(Y){H._media_info=Y,H._emitter.emit(m.a.MEDIA_INFO,Object.assign({},Y))}),this._transmuxer.on(E.a.STATISTICS_INFO,function(Y){H._statistics_info=H._fillStatisticsInfo(Y),H._emitter.emit(m.a.STATISTICS_INFO,Object.assign({},Y))}),this._transmuxer.on(E.a.RECOMMEND_SEEKPOINT,function(Y){H._media_element&&!H._config.accurateSeek&&H._seeking_handler.directSeek(Y/1e3)}),this._transmuxer.on(E.a.METADATA_ARRIVED,function(Y){H._emitter.emit(m.a.METADATA_ARRIVED,Y)}),this._transmuxer.on(E.a.SCRIPTDATA_ARRIVED,function(Y){H._emitter.emit(m.a.SCRIPTDATA_ARRIVED,Y)}),this._transmuxer.on(E.a.TIMED_ID3_METADATA_ARRIVED,function(Y){H._emitter.emit(m.a.TIMED_ID3_METADATA_ARRIVED,Y)}),this._transmuxer.on(E.a.SYNCHRONOUS_KLV_METADATA_ARRIVED,function(Y){H._emitter.emit(m.a.SYNCHRONOUS_KLV_METADATA_ARRIVED,Y)}),this._transmuxer.on(E.a.ASYNCHRONOUS_KLV_METADATA_ARRIVED,function(Y){H._emitter.emit(m.a.ASYNCHRONOUS_KLV_METADATA_ARRIVED,Y)}),this._transmuxer.on(E.a.SMPTE2038_METADATA_ARRIVED,function(Y){H._emitter.emit(m.a.SMPTE2038_METADATA_ARRIVED,Y)}),this._transmuxer.on(E.a.SCTE35_METADATA_ARRIVED,function(Y){H._emitter.emit(m.a.SCTE35_METADATA_ARRIVED,Y)}),this._transmuxer.on(E.a.PES_PRIVATE_DATA_DESCRIPTOR,function(Y){H._emitter.emit(m.a.PES_PRIVATE_DATA_DESCRIPTOR,Y)}),this._transmuxer.on(E.a.PES_PRIVATE_DATA_ARRIVED,function(Y){H._emitter.emit(m.a.PES_PRIVATE_DATA_ARRIVED,Y)}),this._seeking_handler=new O(this._config,this._media_element,this._onRequiredUnbufferedSeek.bind(this)),this._loading_controller=new k(this._config,this._media_element,this._onRequestPauseTransmuxer.bind(this),this._onRequestResumeTransmuxer.bind(this)),this._startup_stall_jumper=new I(this._media_element,this._onRequestDirectSeek.bind(this)),this._config.isLive&&this._config.liveBufferLatencyChasing&&(this._live_latency_chaser=new R(this._config,this._media_element,this._onRequestDirectSeek.bind(this))),this._config.isLive&&this._config.liveSync&&(this._live_latency_synchronizer=new M(this._config,this._media_element)),this._media_element.readyState>0&&this._seeking_handler.directSeek(0),this._transmuxer.open()):this._has_pending_load=!0)},G.prototype.unload=function(){var H,Y,ie,Ce,Le,ke,Ne,ye,Ie;(H=this._media_element)===null||H===void 0||H.pause(),(Y=this._live_latency_synchronizer)===null||Y===void 0||Y.destroy(),this._live_latency_synchronizer=null,(ie=this._live_latency_chaser)===null||ie===void 0||ie.destroy(),this._live_latency_chaser=null,(Ce=this._startup_stall_jumper)===null||Ce===void 0||Ce.destroy(),this._startup_stall_jumper=null,(Le=this._loading_controller)===null||Le===void 0||Le.destroy(),this._loading_controller=null,(ke=this._seeking_handler)===null||ke===void 0||ke.destroy(),this._seeking_handler=null,(Ne=this._mse_controller)===null||Ne===void 0||Ne.flush(),(ye=this._transmuxer)===null||ye===void 0||ye.close(),(Ie=this._transmuxer)===null||Ie===void 0||Ie.destroy(),this._transmuxer=null},G.prototype.play=function(){return this._media_element.play()},G.prototype.pause=function(){this._media_element.pause()},G.prototype.seek=function(H){this._media_element&&this._seeking_handler?this._seeking_handler.seek(H):this._pending_seek_time=H},Object.defineProperty(G.prototype,"mediaInfo",{get:function(){return Object.assign({},this._media_info)},enumerable:!1,configurable:!0}),Object.defineProperty(G.prototype,"statisticsInfo",{get:function(){return Object.assign({},this._statistics_info)},enumerable:!1,configurable:!0}),G.prototype._onMSESourceOpen=function(){this._mse_source_opened=!0,this._has_pending_load&&(this._has_pending_load=!1,this.load())},G.prototype._onMSEUpdateEnd=function(){this._config.isLive&&this._config.liveBufferLatencyChasing&&this._live_latency_chaser&&this._live_latency_chaser.notifyBufferedRangeUpdate(),this._loading_controller.notifyBufferedPositionChanged()},G.prototype._onMSEBufferFull=function(){d.a.v(this.TAG,"MSE SourceBuffer is full, suspend transmuxing task"),this._loading_controller.suspendTransmuxer()},G.prototype._onMSEError=function(H){this._emitter.emit(m.a.ERROR,v.b.MEDIA_ERROR,v.a.MEDIA_MSE_ERROR,H)},G.prototype._onMSEStartStreaming=function(){this._loaded_metadata_received&&(this._config.isLive||(d.a.v(this.TAG,"Resume transmuxing task due to ManagedMediaSource onStartStreaming"),this._loading_controller.resumeTransmuxer()))},G.prototype._onMSEEndStreaming=function(){this._config.isLive||(d.a.v(this.TAG,"Suspend transmuxing task due to ManagedMediaSource onEndStreaming"),this._loading_controller.suspendTransmuxer())},G.prototype._onMediaLoadedMetadata=function(H){this._loaded_metadata_received=!0,this._pending_seek_time!=null&&(this._seeking_handler.seek(this._pending_seek_time),this._pending_seek_time=null)},G.prototype._onRequestDirectSeek=function(H){this._seeking_handler.directSeek(H)},G.prototype._onRequiredUnbufferedSeek=function(H){this._mse_controller.flush(),this._transmuxer.seek(H)},G.prototype._onRequestPauseTransmuxer=function(){this._transmuxer.pause()},G.prototype._onRequestResumeTransmuxer=function(){this._transmuxer.resume()},G.prototype._fillStatisticsInfo=function(H){if(H.playerType="MSEPlayer",!(this._media_element instanceof HTMLVideoElement))return H;var Y=!0,ie=0,Ce=0;if(this._media_element.getVideoPlaybackQuality){var Le=this._media_element.getVideoPlaybackQuality();ie=Le.totalVideoFrames,Ce=Le.droppedVideoFrames}else this._media_element.webkitDecodedFrameCount!=null?(ie=this._media_element.webkitDecodedFrameCount,Ce=this._media_element.webkitDroppedFrameCount):Y=!1;return Y&&(H.decodedFrames=ie,H.droppedFrames=Ce),H},G}(),Z=i(18),W=i(8),re=function(){function G(H,Y){this.TAG="PlayerEngineDedicatedThread",this._emitter=new h,this._media_element=null,this._worker_destroying=!1,this._seeking_handler=null,this._loading_controller=null,this._startup_stall_jumper=null,this._live_latency_chaser=null,this._live_latency_synchronizer=null,this._pending_seek_time=null,this._media_info=null,this._statistics_info=null,this.e=null,this._media_data_source=H,this._config=l(),typeof Y=="object"&&Object.assign(this._config,Y),H.isLive===!0&&(this._config.isLive=!0),this.e={onLoggingConfigChanged:this._onLoggingConfigChanged.bind(this),onMediaLoadedMetadata:this._onMediaLoadedMetadata.bind(this),onMediaTimeUpdate:this._onMediaTimeUpdate.bind(this),onMediaReadyStateChanged:this._onMediaReadyStateChange.bind(this)},W.a.registerListener(this.e.onLoggingConfigChanged),this._worker=Z(24,{all:!0}),this._worker.addEventListener("message",this._onWorkerMessage.bind(this)),this._worker.postMessage({cmd:"init",media_data_source:this._media_data_source,config:this._config}),this._worker.postMessage({cmd:"logging_config",logging_config:W.a.getConfig()})}return G.isSupported=function(){return!!self.Worker&&(!(!self.MediaSource||!("canConstructInDedicatedWorker"in self.MediaSource)||self.MediaSource.canConstructInDedicatedWorker!==!0)||!(!self.ManagedMediaSource||!("canConstructInDedicatedWorker"in self.ManagedMediaSource)||self.ManagedMediaSource.canConstructInDedicatedWorker!==!0))},G.prototype.destroy=function(){this._emitter.emit(m.a.DESTROYING),this.unload(),this.detachMediaElement(),this._worker_destroying=!0,this._worker.postMessage({cmd:"destroy"}),W.a.removeListener(this.e.onLoggingConfigChanged),this.e=null,this._media_data_source=null,this._emitter.removeAllListeners(),this._emitter=null},G.prototype.on=function(H,Y){var ie=this;this._emitter.addListener(H,Y),H===m.a.MEDIA_INFO&&this._media_info?Promise.resolve().then(function(){return ie._emitter.emit(m.a.MEDIA_INFO,ie.mediaInfo)}):H==m.a.STATISTICS_INFO&&this._statistics_info&&Promise.resolve().then(function(){return ie._emitter.emit(m.a.STATISTICS_INFO,ie.statisticsInfo)})},G.prototype.off=function(H,Y){this._emitter.removeListener(H,Y)},G.prototype.attachMediaElement=function(H){this._media_element=H,this._media_element.src="",this._media_element.removeAttribute("src"),this._media_element.srcObject=null,this._media_element.load(),this._media_element.addEventListener("loadedmetadata",this.e.onMediaLoadedMetadata),this._media_element.addEventListener("timeupdate",this.e.onMediaTimeUpdate),this._media_element.addEventListener("readystatechange",this.e.onMediaReadyStateChanged),this._worker.postMessage({cmd:"initialize_mse"})},G.prototype.detachMediaElement=function(){this._worker.postMessage({cmd:"shutdown_mse"}),this._media_element&&(this._media_element.removeEventListener("loadedmetadata",this.e.onMediaLoadedMetadata),this._media_element.removeEventListener("timeupdate",this.e.onMediaTimeUpdate),this._media_element.removeEventListener("readystatechange",this.e.onMediaReadyStateChanged),this._media_element.src="",this._media_element.removeAttribute("src"),this._media_element.srcObject=null,this._media_element.load(),this._media_element=null)},G.prototype.load=function(){this._worker.postMessage({cmd:"load"}),this._seeking_handler=new O(this._config,this._media_element,this._onRequiredUnbufferedSeek.bind(this)),this._loading_controller=new k(this._config,this._media_element,this._onRequestPauseTransmuxer.bind(this),this._onRequestResumeTransmuxer.bind(this)),this._startup_stall_jumper=new I(this._media_element,this._onRequestDirectSeek.bind(this)),this._config.isLive&&this._config.liveBufferLatencyChasing&&(this._live_latency_chaser=new R(this._config,this._media_element,this._onRequestDirectSeek.bind(this))),this._config.isLive&&this._config.liveSync&&(this._live_latency_synchronizer=new M(this._config,this._media_element)),this._media_element.readyState>0&&this._seeking_handler.directSeek(0)},G.prototype.unload=function(){var H,Y,ie,Ce,Le,ke;(H=this._media_element)===null||H===void 0||H.pause(),this._worker.postMessage({cmd:"unload"}),(Y=this._live_latency_synchronizer)===null||Y===void 0||Y.destroy(),this._live_latency_synchronizer=null,(ie=this._live_latency_chaser)===null||ie===void 0||ie.destroy(),this._live_latency_chaser=null,(Ce=this._startup_stall_jumper)===null||Ce===void 0||Ce.destroy(),this._startup_stall_jumper=null,(Le=this._loading_controller)===null||Le===void 0||Le.destroy(),this._loading_controller=null,(ke=this._seeking_handler)===null||ke===void 0||ke.destroy(),this._seeking_handler=null},G.prototype.play=function(){return this._media_element.play()},G.prototype.pause=function(){this._media_element.pause()},G.prototype.seek=function(H){this._media_element&&this._seeking_handler?this._seeking_handler.seek(H):this._pending_seek_time=H},Object.defineProperty(G.prototype,"mediaInfo",{get:function(){return Object.assign({},this._media_info)},enumerable:!1,configurable:!0}),Object.defineProperty(G.prototype,"statisticsInfo",{get:function(){return Object.assign({},this._statistics_info)},enumerable:!1,configurable:!0}),G.prototype._onLoggingConfigChanged=function(H){var Y;(Y=this._worker)===null||Y===void 0||Y.postMessage({cmd:"logging_config",logging_config:H})},G.prototype._onMSEUpdateEnd=function(){this._config.isLive&&this._config.liveBufferLatencyChasing&&this._live_latency_chaser&&this._live_latency_chaser.notifyBufferedRangeUpdate(),this._loading_controller.notifyBufferedPositionChanged()},G.prototype._onMSEBufferFull=function(){d.a.v(this.TAG,"MSE SourceBuffer is full, suspend transmuxing task"),this._loading_controller.suspendTransmuxer()},G.prototype._onMediaLoadedMetadata=function(H){this._pending_seek_time!=null&&(this._seeking_handler.seek(this._pending_seek_time),this._pending_seek_time=null)},G.prototype._onRequestDirectSeek=function(H){this._seeking_handler.directSeek(H)},G.prototype._onRequiredUnbufferedSeek=function(H){this._worker.postMessage({cmd:"unbuffered_seek",milliseconds:H})},G.prototype._onRequestPauseTransmuxer=function(){this._worker.postMessage({cmd:"pause_transmuxer"})},G.prototype._onRequestResumeTransmuxer=function(){this._worker.postMessage({cmd:"resume_transmuxer"})},G.prototype._onMediaTimeUpdate=function(H){this._worker.postMessage({cmd:"timeupdate",current_time:H.target.currentTime})},G.prototype._onMediaReadyStateChange=function(H){this._worker.postMessage({cmd:"readystatechange",ready_state:H.target.readyState})},G.prototype._onWorkerMessage=function(H){var Y,ie=H.data,Ce=ie.msg;if(Ce=="destroyed"||this._worker_destroying)return this._worker_destroying=!1,(Y=this._worker)===null||Y===void 0||Y.terminate(),void(this._worker=null);switch(Ce){case"mse_init":var Le=ie;"ManagedMediaSource"in self&&!("MediaSource"in self)&&(this._media_element.disableRemotePlayback=!0),this._media_element.srcObject=Le.handle;break;case"mse_event":(Le=ie).event==b.a.UPDATE_END?this._onMSEUpdateEnd():Le.event==b.a.BUFFER_FULL&&this._onMSEBufferFull();break;case"transmuxing_event":if((Le=ie).event==E.a.MEDIA_INFO){var ke=ie;this._media_info=ke.info,this._emitter.emit(m.a.MEDIA_INFO,Object.assign({},ke.info))}else if(Le.event==E.a.STATISTICS_INFO){var Ne=ie;this._statistics_info=this._fillStatisticsInfo(Ne.info),this._emitter.emit(m.a.STATISTICS_INFO,Object.assign({},Ne.info))}else if(Le.event==E.a.RECOMMEND_SEEKPOINT){var ye=ie;this._media_element&&!this._config.accurateSeek&&this._seeking_handler.directSeek(ye.milliseconds/1e3)}break;case"player_event":if((Le=ie).event==m.a.ERROR){var Ie=ie;this._emitter.emit(m.a.ERROR,Ie.error_type,Ie.error_detail,Ie.info)}else if("extraData"in Le){var Ae=ie;this._emitter.emit(Ae.event,Ae.extraData)}break;case"logcat_callback":Le=ie,d.a.emitter.emit("log",Le.type,Le.logcat);break;case"buffered_position_changed":Le=ie,this._loading_controller.notifyBufferedPositionChanged(Le.buffered_position_milliseconds/1e3)}},G.prototype._fillStatisticsInfo=function(H){if(H.playerType="MSEPlayer",!(this._media_element instanceof HTMLVideoElement))return H;var Y=!0,ie=0,Ce=0;if(this._media_element.getVideoPlaybackQuality){var Le=this._media_element.getVideoPlaybackQuality();ie=Le.totalVideoFrames,Ce=Le.droppedVideoFrames}else this._media_element.webkitDecodedFrameCount!=null?(ie=this._media_element.webkitDecodedFrameCount,Ce=this._media_element.webkitDroppedFrameCount):Y=!1;return Y&&(H.decodedFrames=ie,H.droppedFrames=Ce),H},G}(),X=function(){function G(H,Y){this.TAG="MSEPlayer",this._type="MSEPlayer",this._media_element=null,this._player_engine=null;var ie=H.type.toLowerCase();if(ie!=="mse"&&ie!=="mpegts"&&ie!=="m2ts"&&ie!=="flv")throw new S.b("MSEPlayer requires an mpegts/m2ts/flv MediaDataSource input!");if(Y&&Y.enableWorkerForMSE&&re.isSupported())try{this._player_engine=new re(H,Y)}catch{d.a.e(this.TAG,"Error while initializing PlayerEngineDedicatedThread, fallback to PlayerEngineMainThread"),this._player_engine=new z(H,Y)}else this._player_engine=new z(H,Y)}return G.prototype.destroy=function(){this._player_engine.destroy(),this._player_engine=null,this._media_element=null},G.prototype.on=function(H,Y){this._player_engine.on(H,Y)},G.prototype.off=function(H,Y){this._player_engine.off(H,Y)},G.prototype.attachMediaElement=function(H){this._media_element=H,this._player_engine.attachMediaElement(H)},G.prototype.detachMediaElement=function(){this._media_element=null,this._player_engine.detachMediaElement()},G.prototype.load=function(){this._player_engine.load()},G.prototype.unload=function(){this._player_engine.unload()},G.prototype.play=function(){return this._player_engine.play()},G.prototype.pause=function(){this._player_engine.pause()},Object.defineProperty(G.prototype,"type",{get:function(){return this._type},enumerable:!1,configurable:!0}),Object.defineProperty(G.prototype,"buffered",{get:function(){return this._media_element.buffered},enumerable:!1,configurable:!0}),Object.defineProperty(G.prototype,"duration",{get:function(){return this._media_element.duration},enumerable:!1,configurable:!0}),Object.defineProperty(G.prototype,"volume",{get:function(){return this._media_element.volume},set:function(H){this._media_element.volume=H},enumerable:!1,configurable:!0}),Object.defineProperty(G.prototype,"muted",{get:function(){return this._media_element.muted},set:function(H){this._media_element.muted=H},enumerable:!1,configurable:!0}),Object.defineProperty(G.prototype,"currentTime",{get:function(){return this._media_element?this._media_element.currentTime:0},set:function(H){this._player_engine.seek(H)},enumerable:!1,configurable:!0}),Object.defineProperty(G.prototype,"mediaInfo",{get:function(){return this._player_engine.mediaInfo},enumerable:!1,configurable:!0}),Object.defineProperty(G.prototype,"statisticsInfo",{get:function(){return this._player_engine.statisticsInfo},enumerable:!1,configurable:!0}),G}(),oe=function(){function G(H,Y){this.TAG="NativePlayer",this._type="NativePlayer",this._emitter=new f.a,this._config=l(),typeof Y=="object"&&Object.assign(this._config,Y);var ie=H.type.toLowerCase();if(ie==="mse"||ie==="mpegts"||ie==="m2ts"||ie==="flv")throw new S.b("NativePlayer does't support mse/mpegts/m2ts/flv MediaDataSource input!");if(H.hasOwnProperty("segments"))throw new S.b("NativePlayer(".concat(H.type,") doesn't support multipart playback!"));this.e={onvLoadedMetadata:this._onvLoadedMetadata.bind(this)},this._pendingSeekTime=null,this._statisticsReporter=null,this._mediaDataSource=H,this._mediaElement=null}return G.prototype.destroy=function(){this._emitter.emit(m.a.DESTROYING),this._mediaElement&&(this.unload(),this.detachMediaElement()),this.e=null,this._mediaDataSource=null,this._emitter.removeAllListeners(),this._emitter=null},G.prototype.on=function(H,Y){var ie=this;H===m.a.MEDIA_INFO?this._mediaElement!=null&&this._mediaElement.readyState!==0&&Promise.resolve().then(function(){ie._emitter.emit(m.a.MEDIA_INFO,ie.mediaInfo)}):H===m.a.STATISTICS_INFO&&this._mediaElement!=null&&this._mediaElement.readyState!==0&&Promise.resolve().then(function(){ie._emitter.emit(m.a.STATISTICS_INFO,ie.statisticsInfo)}),this._emitter.addListener(H,Y)},G.prototype.off=function(H,Y){this._emitter.removeListener(H,Y)},G.prototype.attachMediaElement=function(H){if(this._mediaElement=H,H.addEventListener("loadedmetadata",this.e.onvLoadedMetadata),this._pendingSeekTime!=null)try{H.currentTime=this._pendingSeekTime,this._pendingSeekTime=null}catch{}},G.prototype.detachMediaElement=function(){this._mediaElement&&(this._mediaElement.src="",this._mediaElement.removeAttribute("src"),this._mediaElement.removeEventListener("loadedmetadata",this.e.onvLoadedMetadata),this._mediaElement=null),this._statisticsReporter!=null&&(window.clearInterval(this._statisticsReporter),this._statisticsReporter=null)},G.prototype.load=function(){if(!this._mediaElement)throw new S.a("HTMLMediaElement must be attached before load()!");this._mediaElement.src=this._mediaDataSource.url,this._mediaElement.readyState>0&&(this._mediaElement.currentTime=0),this._mediaElement.preload="auto",this._mediaElement.load(),this._statisticsReporter=window.setInterval(this._reportStatisticsInfo.bind(this),this._config.statisticsInfoReportInterval)},G.prototype.unload=function(){this._mediaElement&&(this._mediaElement.src="",this._mediaElement.removeAttribute("src")),this._statisticsReporter!=null&&(window.clearInterval(this._statisticsReporter),this._statisticsReporter=null)},G.prototype.play=function(){return this._mediaElement.play()},G.prototype.pause=function(){this._mediaElement.pause()},Object.defineProperty(G.prototype,"type",{get:function(){return this._type},enumerable:!1,configurable:!0}),Object.defineProperty(G.prototype,"buffered",{get:function(){return this._mediaElement.buffered},enumerable:!1,configurable:!0}),Object.defineProperty(G.prototype,"duration",{get:function(){return this._mediaElement.duration},enumerable:!1,configurable:!0}),Object.defineProperty(G.prototype,"volume",{get:function(){return this._mediaElement.volume},set:function(H){this._mediaElement.volume=H},enumerable:!1,configurable:!0}),Object.defineProperty(G.prototype,"muted",{get:function(){return this._mediaElement.muted},set:function(H){this._mediaElement.muted=H},enumerable:!1,configurable:!0}),Object.defineProperty(G.prototype,"currentTime",{get:function(){return this._mediaElement?this._mediaElement.currentTime:0},set:function(H){this._mediaElement?this._mediaElement.currentTime=H:this._pendingSeekTime=H},enumerable:!1,configurable:!0}),Object.defineProperty(G.prototype,"mediaInfo",{get:function(){var H={mimeType:(this._mediaElement instanceof HTMLAudioElement?"audio/":"video/")+this._mediaDataSource.type};return this._mediaElement&&(H.duration=Math.floor(1e3*this._mediaElement.duration),this._mediaElement instanceof HTMLVideoElement&&(H.width=this._mediaElement.videoWidth,H.height=this._mediaElement.videoHeight)),H},enumerable:!1,configurable:!0}),Object.defineProperty(G.prototype,"statisticsInfo",{get:function(){var H={playerType:this._type,url:this._mediaDataSource.url};if(!(this._mediaElement instanceof HTMLVideoElement))return H;var Y=!0,ie=0,Ce=0;if(this._mediaElement.getVideoPlaybackQuality){var Le=this._mediaElement.getVideoPlaybackQuality();ie=Le.totalVideoFrames,Ce=Le.droppedVideoFrames}else this._mediaElement.webkitDecodedFrameCount!=null?(ie=this._mediaElement.webkitDecodedFrameCount,Ce=this._mediaElement.webkitDroppedFrameCount):Y=!1;return Y&&(H.decodedFrames=ie,H.droppedFrames=Ce),H},enumerable:!1,configurable:!0}),G.prototype._onvLoadedMetadata=function(H){this._pendingSeekTime!=null&&(this._mediaElement.currentTime=this._pendingSeekTime,this._pendingSeekTime=null),this._emitter.emit(m.a.MEDIA_INFO,this.mediaInfo)},G.prototype._reportStatisticsInfo=function(){this._emitter.emit(m.a.STATISTICS_INFO,this.statisticsInfo)},G}();s.a.install();var Q={createPlayer:function(G,H){var Y=G;if(Y==null||typeof Y!="object")throw new S.b("MediaDataSource must be an javascript object!");if(!Y.hasOwnProperty("type"))throw new S.b("MediaDataSource must has type field to indicate video file type!");switch(Y.type){case"mse":case"mpegts":case"m2ts":case"flv":return new X(Y,H);default:return new oe(Y,H)}},isSupported:function(){return c.supportMSEH264Playback()},getFeatureList:function(){return c.getFeatureList()}};Q.BaseLoader=u.a,Q.LoaderStatus=u.c,Q.LoaderErrors=u.b,Q.Events=m.a,Q.ErrorTypes=v.b,Q.ErrorDetails=v.a,Q.MSEPlayer=X,Q.NativePlayer=oe,Q.LoggingControl=W.a,Object.defineProperty(Q,"version",{enumerable:!0,get:function(){return"1.8.0"}}),r.default=Q}])})})(P4);var gfe=P4.exports;const gD=k0(gfe),yfe=t=>{if(!t||Tl.isNativePlatform())return t;const e=encodeURIComponent(sa());return`${Oj()}?url=${encodeURIComponent(t)}&ua=${e}`},$a="video/*",vfe=[[/\.m3u8(\?|$)/i,$a],[/\.ts(\?|$)/i,$a],[/\.mpd(\?|$)/i,$a],[/\.mp4(\?|$)/i,$a],[/\.mkv(\?|$)/i,$a],[/\.webm(\?|$)/i,$a],[/\.avi(\?|$)/i,$a],[/\.mov(\?|$)/i,$a]],_fe=t=>{for(const[e,n]of vfe)if(e.test(t))return n;return $a},bfe=(t,e={})=>{const n=t.match(/^(https?):\/\/(.+)$/i);if(!n)return t;const[,r,i]=n,s=e.mime??_fe(t),a=[`scheme=${r}`,"action=android.intent.action.VIEW",`type=${s}`];return e.package&&a.push(`package=${e.package}`),e.title&&a.push(`S.title=${encodeURIComponent(e.title)}`),e.userAgent&&a.push(`S.User-Agent=${encodeURIComponent(e.userAgent)}`),a.push("end"),`intent://${i}#Intent;${a.join(";")}`},D4=t=>`vlc://${t}`,r1=t=>`vlc-x-callback://x-callback-url/stream?url=${encodeURIComponent(t)}`,xfe=t=>`market://details?id=${encodeURIComponent(t)}`,yD=t=>`https://play.google.com/store/apps/details?id=${encodeURIComponent(t)}`,Sfe=()=>typeof navigator>"u"?!1:/Android/i.test(navigator.userAgent),Efe=()=>typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent),O4=(t,e={})=>{if(Sfe())try{const n=bfe(t,e);let r=!1;const i=()=>{typeof document<"u"&&document.hidden&&(r=!0,document.removeEventListener("visibilitychange",i))};return typeof document<"u"&&document.addEventListener("visibilitychange",i),window.setTimeout(()=>{typeof document<"u"&&(document.removeEventListener("visibilitychange",i),!r&&!document.hidden&&e.onNotInstalled&&e.onNotInstalled(e.package))},1600),window.location.href=n,!0}catch(n){return console.warn("[externalLauncher] intent launch failed",n),!1}if(Efe())try{return window.location.href=r1(t),!0}catch(n){return console.warn("[externalLauncher] iOS launch failed",n),!1}return!1},N4=t=>{try{const e=xfe(t);window.setTimeout(()=>{window.location.href=e,window.setTimeout(()=>{typeof document<"u"&&!document.hidden&&(window.location.href=yD(t))},1200)},50)}catch(e){console.warn("[externalLauncher] openPlayStore failed",e),window.location.href=yD(t)}},wfe=t=>/\.m3u8(\?|$)/i.test(t)||/\/live\//i.test(t)||/\.ts(\?|$)/i.test(t),i1=({src:t,poster:e,title:n,autoPlay:r=!0,className:i="",isLive:s})=>{const a=D.useRef(null),o=D.useRef(null),l=D.useRef(null),c=D.useRef(null),[u,d]=D.useState(!1),h=s??wfe(t),f=um(),p=Kj(),m=D.useCallback(()=>{const v=o.current;if(v)try{v.stopLoad(),v.startLoad()}catch(S){console.warn("[VideoPlayer] restartStream failed:",S)}},[]),g=D.useCallback(async()=>{try{await Ko.play({url:t,title:n??"",userAgent:sa(),isLive:h})}catch(v){console.error("[VideoPlayer] native play failed:",v),Mt.error("Native player failed")}},[t,n,h]),b=D.useCallback(async()=>{d(!0);try{if(f){const v=async L=>await Ko.openExternal({url:t,title:n??"",userAgent:sa(),package:L}),S=await v("com.brouken.player");if(S!=null&&S.launched)return;const E=await v("org.videolan.vlc");if(E!=null&&E.launched)return;Mt.error("Please install ExoPlayer or VLC",{action:{label:"Install",onClick:()=>Ko.openPlayStore({package:"com.brouken.player"})},duration:1e4})}else O4(t,{package:"com.brouken.player",title:n??"",userAgent:sa(),onNotInstalled:S=>{Mt.error("Please install ExoPlayer or VLC",{action:{label:"Install",onClick:()=>N4(S||"com.brouken.player")},duration:1e4})}})||Mt.message('Tap "Open in player" to launch the stream')}catch(v){console.error("[VideoPlayer] external launch failed:",v),Mt.error((v==null?void 0:v.message)??"Couldn't open external player")}finally{window.setTimeout(()=>d(!1),900)}},[t,n,f]);if(D.useEffect(()=>{t&&c.current!==t&&(c.current=t,f&&r&&(p==="external"?b():g()))},[t,f,p]),D.useEffect(()=>{if(f||p==="external")return;const v=a.current;if(!v||!t)return;const S=yfe(t),E=v.canPlayType("application/vnd.apple.mpegurl")!=="";let L=!1,U=0;v.pause(),v.removeAttribute("src"),v.load();try{v.muted=!1,v.volume=1}catch(I){console.warn("[VideoPlayer] reset mute/volume failed",I)}const O=()=>{const I=new Mi({autoStartLoad:!0,enableWorker:!0,lowLatencyMode:!1,backBufferLength:60,maxBufferLength:60,maxMaxBufferLength:120,maxBufferSize:6e7,liveSyncDuration:h?10:void 0,liveMaxLatencyDuration:h?30:void 0,liveDurationInfinity:h,maxBufferHole:.5,highBufferWatchdogPeriod:3,nudgeOffset:.2,nudgeMaxRetry:10,manifestLoadingTimeOut:15e3,manifestLoadingMaxRetry:6,manifestLoadingRetryDelay:1e3,levelLoadingTimeOut:15e3,levelLoadingMaxRetry:6,levelLoadingRetryDelay:1e3,fragLoadingTimeOut:3e4,fragLoadingMaxRetry:8,fragLoadingRetryDelay:500,startFragPrefetch:!0});o.current=I,I.loadSource(S),I.attachMedia(v),I.on(Mi.Events.MANIFEST_PARSED,()=>{if(h){v.muted=!0;try{I.levels&&I.levels.length>1&&(I.currentLevel=1)}catch(R){console.warn("[VideoPlayer] set initial level failed",R)}}r&&v.play().catch(()=>{})}),I.on(Mi.Events.ERROR,(R,M)=>{if(!L&&M.fatal)switch(M.type){case Mi.ErrorTypes.NETWORK_ERROR:if(console.warn("[HLS] network error",M.details),M.details==="manifestLoadError"||M.details==="manifestLoadTimeOut"||M.details==="manifestParsingError"){try{I.destroy()}catch(z){console.warn("[VideoPlayer] hls.destroy failed (manifest error path)",z)}o.current=null,k()}else window.setTimeout(()=>{L||m()},1200);break;case Mi.ErrorTypes.MEDIA_ERROR:if(console.warn("[HLS] media error → recoverMediaError()",M.details),U<2){U++;try{I.recoverMediaError()}catch{}}else if(U<4){U++;try{I.swapAudioCodec(),I.recoverMediaError()}catch{}}else{console.error("[HLS] gave up recovering media errors");try{I.destroy()}catch{}o.current=null,h&&k()}break;default:console.error("[HLS] fatal other:",M.type,M.details);try{I.destroy()}catch{}o.current=null,h&&k();break}})},k=()=>{if(!gD.isSupported())return;const I=gD.createPlayer({type:"mpegts",isLive:h,url:S},{enableWorker:!0,liveBufferLatencyChasing:!1,lazyLoad:!1,autoCleanupSourceBuffer:!0,stashInitialSize:384});if(l.current=I,I.attachMediaElement(v),I.load(),h&&(v.muted=!0),r){const R=I.play();R&&typeof R.catch=="function"&&R.catch(()=>{})}};if(h&&Mi.isSupported())O();else if(h&&E)v.src=S,v.muted=!0,r&&v.play().catch(()=>{});else{try{v.removeAttribute("crossorigin")}catch{}if(v.src=S,v.muted=!1,r){const I=v.play();I&&typeof I.catch=="function"&&I.catch(R=>{(R==null?void 0:R.name)==="NotAllowedError"&&(v.muted=!0,v.play().catch(()=>{}))})}}return()=>{if(L=!0,o.current){try{o.current.destroy()}catch{}o.current=null}if(l.current){try{l.current.pause(),l.current.unload(),l.current.detachMediaElement(),l.current.destroy()}catch{}l.current=null}try{v.removeAttribute("src"),v.load()}catch{}}},[t,r,h,f,p]),p==="external"){const v=typeof navigator<"u"?navigator.userAgent:"",S=/iPad|iPhone|iPod/.test(v),E=/Android/i.test(v),L=S?r1(t):E?void 0:D4(t);return y.jsx("div",{className:`relative w-full h-full bg-black flex items-center justify-center ${i}`,style:e?{backgroundImage:`url(${e})`,backgroundSize:"cover",backgroundPosition:"center"}:void 0,children:f||E?y.jsxs("button",{onClick:b,className:"flex items-center gap-2 bg-primary/90 hover:bg-primary text-primary-foreground px-6 py-3 rounded-full font-medium shadow-lg backdrop-blur",children:[u?y.jsx(yr,{className:"w-5 h-5 animate-spin"}):y.jsx(no,{className:"w-5 h-5"}),"Open stream"]}):y.jsxs("a",{href:L,className:"flex items-center gap-2 bg-primary/90 hover:bg-primary text-primary-foreground px-6 py-3 rounded-full font-medium shadow-lg backdrop-blur",children:[y.jsx(no,{className:"w-5 h-5"}),"Open in VLC"]})})}if(f){const v=()=>Ko.openExternal({url:t,title:n??"",userAgent:sa(),package:"org.videolan.vlc"}).then(S=>{!(S!=null&&S.launched)&&(S==null?void 0:S.reason)==="not-installed"&&Mt.error("VLC is not installed",{action:{label:"Install",onClick:()=>Ko.openPlayStore({package:"org.videolan.vlc"})},duration:8e3})});return y.jsx("div",{className:`relative w-full h-full bg-black flex items-center justify-center ${i}`,style:e?{backgroundImage:`url(${e})`,backgroundSize:"cover",backgroundPosition:"center"}:void 0,children:y.jsxs("div",{className:"flex flex-col gap-3 items-center",children:[y.jsxs("button",{onClick:g,disabled:u,className:"flex items-center gap-2 bg-primary/90 hover:bg-primary text-primary-foreground px-6 py-3 rounded-full font-medium shadow-lg backdrop-blur disabled:opacity-60",children:[u?y.jsx(yr,{className:"w-5 h-5 animate-spin"}):y.jsx(sc,{className:"w-5 h-5"}),u?"Opening…":"Play"]}),y.jsxs("button",{onClick:v,className:"flex items-center gap-2 text-white/70 hover:text-white text-xs px-3 py-1.5 rounded-full border border-white/15 hover:border-white/30 transition",children:[y.jsx(no,{className:"w-3.5 h-3.5"}),"Open in VLC instead"]}),y.jsxs("p",{className:"text-xs text-white/50",children:[Gte()==="ios"?"AVPlayer":"ExoPlayer",n?` · ${n}`:""]})]})})}return y.jsx("video",{ref:a,poster:e,controls:!0,playsInline:!0,className:`w-full h-full bg-black ${i}`})},vD=(t,e)=>`nadiplay_fav_${t}_${e}`,s1=(t,e)=>{const[n,r]=D.useState(new Set);D.useEffect(()=>{if(!t)return r(new Set);const a=localStorage.getItem(vD(t,e));r(a?new Set(JSON.parse(a)):new Set)},[t,e]);const i=D.useCallback(a=>{t&&r(o=>{const l=new Set(o);return l.has(a)?l.delete(a):l.add(a),localStorage.setItem(vD(t,e),JSON.stringify([...l])),l})},[t,e]),s=D.useCallback(a=>n.has(a),[n]);return{favorites:n,toggle:i,isFavorite:s}},Tfe=[{id:"exoplayer",label:"Just Player (ExoPlayer)",androidPackage:"com.brouken.player",playStoreUrl:"https://play.google.com/store/apps/details?id=com.brouken.player",hint:"ExoPlayer-powered · best for IPTV & HLS"},{id:"vlc",label:"VLC Media Player",androidPackage:"org.videolan.vlc",playStoreUrl:"https://play.google.com/store/apps/details?id=org.videolan.vlc",iosScheme:"vlc-x-callback",hint:"Universal player — all codecs"}],Afe=()=>Tfe[0],Rfe=()=>{const{activeProfile:t}=mo(),{t:e}=Wr(),{user:n}=Bs(),{data:r=[],isLoading:i,error:s}=Uj(t),a=Sv(),{isFavorite:o,toggle:l}=s1(t==null?void 0:t.id,"live"),[c,u]=D.useState(""),[d,h]=D.useState("All"),[f,p]=D.useState(null),[m,g]=D.useState(!1),[b,v]=D.useState("list"),S=Kj(),E=um(),L=Afe(),U=(n==null?void 0:n.role)==="user",O=D.useMemo(()=>["All",...Array.from(new Set(r.map(Q=>Q.category)))],[r]),k=D.useMemo(()=>r.filter(Q=>{const G=Q.name.toLowerCase().includes(c.toLowerCase()),H=d==="All"||Q.category===d,Y=!m||o(Q.id);return G&&H&&Y}),[r,c,d,m,o]),{data:I=[]}=Zte(t,f==null?void 0:f.id),R=I.find(Q=>Q.nowPlaying)??I[0],M=async Q=>{let G=Q;if(G.streamUrl.startsWith("stalker-cmd:")&&(t==null?void 0:t.kind)==="stalker"){const H=G.streamUrl.slice(12),Y=Mt.loading(`Resolving ${G.name}…`);try{const ie=await _v.resolveStream(t.portalUrl,t.macAddress,H);Mt.dismiss(Y),G={...G,streamUrl:ie}}catch(ie){Mt.error(`Could not resolve stream: ${(ie==null?void 0:ie.message)||"error"}`,{id:Y});return}}if(S==="external"){try{if(E){const H=await Ko.openExternal({url:G.streamUrl,title:G.name,userAgent:sa(),package:L.androidPackage});H!=null&&H.launched?Mt.success(e("liveTV.openingInApp",{channel:G.name,app:L.label})):(H==null?void 0:H.reason)==="not-installed"&&H.package?Mt.error(`${L.label} is not installed`,{action:{label:"Install",onClick:()=>Ko.openPlayStore({package:H.package})},duration:8e3}):Mt.error(e("liveTV.couldntOpen",{app:L.label}))}else O4(G.streamUrl,{package:L.androidPackage,title:G.name,userAgent:sa(),onNotInstalled:Y=>{if(!Y){Mt.error(`No ${L.label} app handled the stream`);return}Mt.error(`${L.label} is not installed`,{action:{label:"Install",onClick:()=>N4(Y)},duration:1e4})}})?Mt.message(e("liveTV.sentToApp",{app:L.label})):Mt.message(`Tap "Open in ${L.label}" to launch`)}catch(H){Mt.error((H==null?void 0:H.message)||e("liveTV.couldntOpen",{app:L.label}))}p(G);return}p(G)},z=Q=>{const G=typeof navigator<"u"?navigator.userAgent:"";if(/iPad|iPhone|iPod/.test(G))return r1(Q);if(!/Android/i.test(G))return D4(Q)};if(!t)return y.jsx(Vc,{title:e("liveTV.title"),children:y.jsx("div",{className:"h-full flex items-center justify-center",children:y.jsxs("div",{className:"glass-card rounded-2xl p-6 text-center max-w-sm",children:[y.jsx("p",{className:"text-foreground text-sm mb-3",children:e("liveTV.noActiveServer")}),U?y.jsx("p",{className:"text-muted-foreground text-xs",children:e("liveTV.contactAdmin")}):y.jsx(pT,{to:"/account",className:"text-primary text-xs underline",children:e("liveTV.addProfile")})]})})});const Z=S==="external"?y.jsxs("div",{className:"glass-card rounded-xl px-3 py-1.5 flex items-center gap-1.5",children:[y.jsx(no,{className:"w-3 h-3 text-primary"}),y.jsx("span",{className:"text-[10px] text-foreground/80",children:L.label})]}):null,W={contentVisibility:"auto",containIntrinsicSize:"56px"},re={contentVisibility:"auto",containIntrinsicSize:"160px"},X=()=>y.jsx(Rl,{focusKey:"channel-list",className:"space-y-1",children:k.slice(0,300).map(Q=>y.jsxs(Fc,{focusKey:`ch-${Q.id}`,onEnter:()=>M(Q),onClick:()=>M(Q),subtle:!0,style:W,className:`flex items-center gap-3 px-3 py-2.5 rounded-xl cursor-pointer transition-transform active:scale-[0.98] border-transparent ${(f==null?void 0:f.id)===Q.id?"glass-card border border-primary/30":"hover:bg-white/5"}`,children:[y.jsx("div",{className:"w-10 h-7 rounded bg-muted/30 flex items-center justify-center shrink-0 overflow-hidden",children:Q.logoUrl?y.jsx("img",{src:Q.logoUrl,alt:"",loading:"lazy",decoding:"async",className:"w-full h-full object-contain",onError:G=>G.currentTarget.style.display="none"}):y.jsx(sc,{className:"w-3 h-3 text-muted-foreground"})}),y.jsxs("div",{className:"flex-1 min-w-0",children:[y.jsx("p",{className:"text-foreground text-xs font-medium truncate",children:Q.name}),y.jsx("p",{className:"text-muted-foreground text-[10px] truncate",children:Q.category})]}),y.jsx("button",{onClick:G=>{G.stopPropagation(),l(Q.id)},children:y.jsx(Sf,{className:`w-4 h-4 ${o(Q.id)?"text-primary fill-primary":"text-muted-foreground"}`})})]},Q.id))}),oe=()=>y.jsx(Rl,{focusKey:"channel-grid",className:"grid grid-cols-2 md:grid-cols-3 gap-2",children:k.slice(0,300).map(Q=>y.jsxs(Fc,{focusKey:`ch-grid-${Q.id}`,onEnter:()=>M(Q),onClick:()=>M(Q),style:re,className:`relative aspect-[4/3] flex flex-col items-center justify-center gap-1.5 rounded-xl cursor-pointer transition-transform active:scale-[0.96] p-2 border-transparent ${(f==null?void 0:f.id)===Q.id?"glass-card border border-primary/40":"glass-card hover:border-primary/20"}`,children:[y.jsx("div",{className:"w-14 h-10 rounded bg-muted/30 flex items-center justify-center overflow-hidden",children:Q.logoUrl?y.jsx("img",{src:Q.logoUrl,alt:"",loading:"lazy",decoding:"async",className:"w-full h-full object-contain",onError:G=>G.currentTarget.style.display="none"}):y.jsx(sc,{className:"w-4 h-4 text-muted-foreground"})}),y.jsx("p",{className:"text-foreground text-[11px] font-medium text-center line-clamp-2",children:Q.name}),y.jsx("button",{onClick:G=>{G.stopPropagation(),l(Q.id)},className:"absolute top-1.5 right-1.5",children:y.jsx(Sf,{className:`w-3.5 h-3.5 ${o(Q.id)?"text-primary fill-primary":"text-muted-foreground"}`})})]},Q.id))});return y.jsx(Vc,{title:e("liveTV.title"),children:y.jsxs("div",{className:"h-full flex flex-col gap-3",children:[y.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[y.jsxs("div",{className:"glass-card rounded-xl px-3 py-2 flex items-center gap-2 flex-1 min-w-[180px]",children:[y.jsx(ST,{className:"w-4 h-4 text-muted-foreground"}),y.jsx("input",{type:"text",placeholder:e("liveTV.searchPlaceholder"),value:c,onChange:Q=>u(Q.target.value),className:"bg-transparent text-foreground placeholder:text-muted-foreground text-xs outline-none flex-1"})]}),y.jsxs("div",{className:"glass-card rounded-xl px-3 py-2 flex items-center gap-2",children:[y.jsx(tv,{className:"w-4 h-4 text-muted-foreground"}),y.jsx("select",{value:d,onChange:Q=>h(Q.target.value),className:"bg-transparent text-foreground text-xs outline-none",children:O.map(Q=>y.jsx("option",{value:Q,className:"bg-background",children:Q==="All"?e("common.all"):Q},Q))})]}),y.jsxs("button",{onClick:()=>g(Q=>!Q),className:`glass-card rounded-xl px-3 py-2 flex items-center gap-1.5 ${m?"border border-primary/40":""}`,title:e("liveTV.favs"),children:[y.jsx(Sf,{className:`w-3.5 h-3.5 ${m?"text-primary fill-primary":"text-muted-foreground"}`}),y.jsx("span",{className:"text-[11px] text-foreground/80",children:e("liveTV.favs")})]}),y.jsxs("div",{className:"glass-card rounded-xl p-0.5 flex items-center",children:[y.jsx("button",{onClick:()=>v("list"),className:`px-2.5 py-1.5 rounded-lg ${b==="list"?"bg-primary/20 text-primary":"text-muted-foreground"}`,title:e("liveTV.listView"),children:y.jsx(bK,{className:"w-3.5 h-3.5"})}),y.jsx("button",{onClick:()=>v("grid"),className:`px-2.5 py-1.5 rounded-lg ${b==="grid"?"bg-primary/20 text-primary":"text-muted-foreground"}`,title:e("liveTV.gridView"),children:y.jsx(gK,{className:"w-3.5 h-3.5"})})]}),y.jsx("button",{onClick:()=>a(t.id),className:"glass-card rounded-xl p-2",title:e("common.refresh"),children:y.jsx(tm,{className:"w-3.5 h-3.5 text-muted-foreground hover:text-primary"})}),Z]}),S==="external"?y.jsxs("div",{className:"flex-1 flex flex-col gap-2 min-h-0",children:[f&&y.jsxs("div",{className:"glass-card rounded-xl px-3 py-2 flex flex-col sm:flex-row sm:items-center gap-2",children:[y.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[y.jsx("div",{className:"w-9 h-7 rounded bg-muted/30 flex items-center justify-center overflow-hidden",children:f.logoUrl?y.jsx("img",{src:f.logoUrl,alt:"",className:"w-full h-full object-contain"}):y.jsx(sc,{className:"w-3 h-3 text-muted-foreground"})}),y.jsxs("div",{className:"flex-1 min-w-0",children:[y.jsx("p",{className:"text-foreground text-xs font-medium truncate",children:f.name}),y.jsx("p",{className:"text-muted-foreground text-[10px] truncate",children:R!=null&&R.title?e("liveTV.nowPrefix",{title:R.title}):f.category})]})]}),(()=>{const Q=z(f.streamUrl);return Q?y.jsxs("a",{href:Q,className:"inline-flex items-center justify-center gap-1.5 bg-primary hover:bg-primary/90 text-primary-foreground text-xs font-medium px-4 py-2 rounded-lg shadow-lg",children:[y.jsx(no,{className:"w-3.5 h-3.5"}),"Open in ",L.label]}):y.jsxs("button",{onClick:()=>M(f),className:"inline-flex items-center justify-center gap-1.5 bg-primary hover:bg-primary/90 text-primary-foreground text-xs font-medium px-4 py-2 rounded-lg shadow-lg",children:[y.jsx(no,{className:"w-3.5 h-3.5"}),"Open in ",L.label]})})()]}),y.jsxs("div",{className:"flex-1 overflow-y-auto pr-1",children:[i&&y.jsx("div",{className:"flex items-center justify-center py-10",children:y.jsx(yr,{className:"w-5 h-5 text-primary animate-spin"})}),s&&y.jsx("p",{className:"text-destructive text-xs px-2",children:e("liveTV.failedLoad")}),!i&&k.length===0&&y.jsx("p",{className:"text-muted-foreground text-xs text-center py-6",children:e("liveTV.noChannels")}),b==="list"?X():oe()]}),f&&I.length>0&&y.jsxs("div",{className:"glass-card rounded-xl p-2 max-h-36 overflow-y-auto",children:[y.jsx("p",{className:"text-[10px] text-muted-foreground mb-1 px-1",children:e("liveTV.epgFor",{name:f.name})}),I.slice(0,6).map((Q,G)=>y.jsxs("div",{className:`flex items-center gap-2 px-2 py-1 rounded-md ${Q.nowPlaying?"bg-primary/10":""}`,children:[y.jsx("span",{className:"text-[10px] text-muted-foreground w-10 shrink-0",children:Q.start?Q.start.slice(11,16):"--:--"}),y.jsx("span",{className:`text-[11px] truncate ${Q.nowPlaying?"text-primary font-medium":"text-foreground/80"}`,children:Q.title||"—"})]},Q.id+G))]})]}):y.jsxs("div",{className:"flex-1 flex flex-col md:flex-row gap-3 min-h-0",children:[y.jsx("div",{className:"md:w-[340px] shrink-0 flex flex-col gap-2 min-h-0",children:y.jsxs("div",{className:"flex-1 overflow-y-auto pr-1",children:[i&&y.jsx("div",{className:"flex items-center justify-center py-8",children:y.jsx(yr,{className:"w-5 h-5 text-primary animate-spin"})}),s&&y.jsx("p",{className:"text-destructive text-xs px-2",children:e("liveTV.failedLoad")}),!i&&k.length===0&&y.jsx("p",{className:"text-muted-foreground text-xs text-center py-6",children:e("liveTV.noChannels")}),b==="list"?X():oe()]})}),y.jsxs("div",{className:"flex-1 flex flex-col gap-2",children:[y.jsx("div",{className:"flex-1 glass-card rounded-2xl overflow-hidden flex items-center justify-center min-h-[240px] relative",children:f?y.jsx(i1,{src:f.streamUrl,poster:f.logoUrl,title:f.name,isLive:!0}):y.jsxs("div",{className:"text-center",children:[y.jsx(sc,{className:"w-12 h-12 text-primary/50 mx-auto mb-2"}),y.jsx("p",{className:"text-muted-foreground text-sm",children:e("liveTV.selectChannel")})]})}),f&&y.jsxs("div",{className:"text-center",children:[y.jsx("p",{className:"text-foreground text-sm font-medium",children:f.name}),y.jsx("p",{className:"text-muted-foreground text-[10px]",children:R!=null&&R.title?e("liveTV.nowPrefix",{title:R.title}):f.category})]})]})]}),y.jsx("div",{className:"text-muted-foreground text-[10px] tabular-nums","data-testid":"livetv-count",children:k.length===r.length?e("liveTV.channels",{count:r.length}):`${k.length} / ${r.length} ${e("liveTV.channels",{count:r.length}).replace(/^\d+\s*/,"")}`})]})})},Cfe=()=>{const{activeProfile:t}=mo(),{t:e}=Wr(),{user:n}=Bs(),{data:r=[],isLoading:i,error:s}=jj(t),a=Sv(),{isFavorite:o,toggle:l}=s1(t==null?void 0:t.id,"movie"),[c,u]=D.useState(""),[d,h]=D.useState("All"),[f,p]=D.useState(null),m=["All",...Array.from(new Set(r.map(v=>v.category)))],g=r.filter(v=>{const S=v.name.toLowerCase().includes(c.toLowerCase()),E=d==="All"||v.category===d;return S&&E}),b=(n==null?void 0:n.role)==="user";return t?y.jsxs(Vc,{title:e("movies.title"),children:[y.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[y.jsxs("div",{className:"flex gap-2",children:[y.jsxs("div",{className:"glass-card rounded-xl px-3 py-2 flex items-center gap-2 w-40",children:[y.jsx(tv,{className:"w-4 h-4 text-muted-foreground"}),y.jsx("select",{value:d,onChange:v=>h(v.target.value),className:"bg-transparent text-foreground text-xs outline-none flex-1",children:m.map(v=>y.jsx("option",{value:v,className:"bg-background",children:v==="All"?e("common.all"):v},v))})]}),y.jsxs("div",{className:"glass-card rounded-xl px-3 py-2 flex items-center gap-2 flex-1",children:[y.jsx(ST,{className:"w-4 h-4 text-muted-foreground"}),y.jsx("input",{type:"text",placeholder:e("movies.searchPlaceholder"),value:c,onChange:v=>u(v.target.value),className:"bg-transparent text-foreground placeholder:text-muted-foreground text-xs outline-none flex-1"})]}),y.jsx("button",{onClick:()=>a(t.id),className:"glass-card rounded-xl px-3 py-2",children:y.jsx(tm,{className:"w-4 h-4 text-muted-foreground"})})]}),i&&y.jsx("div",{className:"flex items-center justify-center py-12",children:y.jsx(yr,{className:"w-6 h-6 text-primary animate-spin"})}),s&&y.jsx("p",{className:"text-destructive text-xs",children:e("movies.failedLoad")}),y.jsx(Rl,{focusKey:"movies-grid",className:"flex-1 overflow-y-auto grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3 pb-2",children:g.slice(0,300).map(v=>y.jsxs(Fc,{focusKey:`movie-${v.id}`,onEnter:()=>p(v),onClick:()=>p(v),style:{contentVisibility:"auto",containIntrinsicSize:"260px"},className:"glass-card rounded-xl overflow-hidden cursor-pointer group hover:border-primary/30 transition-all border-transparent",children:[y.jsxs("div",{className:"aspect-[2/3] bg-muted/20 flex items-center justify-center relative overflow-hidden",children:[v.posterUrl?y.jsx("img",{src:v.posterUrl,alt:v.name,loading:"lazy",decoding:"async",className:"w-full h-full object-cover",onError:S=>S.currentTarget.style.display="none"}):y.jsx(sc,{className:"w-8 h-8 text-muted-foreground/30 group-hover:text-primary/60 transition-colors"}),y.jsx("button",{onClick:S=>{S.stopPropagation(),l(v.id)},className:"absolute top-2 right-2 z-10",children:y.jsx(Sf,{className:`w-4 h-4 ${o(v.id)?"text-primary fill-primary":"text-muted-foreground/80"}`})}),v.rating&&y.jsxs("span",{className:"absolute top-2 left-2 text-[10px] bg-primary/80 text-primary-foreground px-1.5 py-0.5 rounded",children:["★ ",v.rating]})]}),y.jsxs("div",{className:"p-2.5",children:[y.jsx("p",{className:"text-foreground text-xs font-medium truncate",children:v.name}),y.jsxs("div",{className:"flex items-center justify-between mt-1",children:[y.jsx("span",{className:"text-muted-foreground text-[10px] truncate",children:v.category}),v.year&&y.jsx("span",{className:"text-muted-foreground text-[10px]",children:v.year})]})]})]},v.id))}),!i&&!s&&y.jsx("div",{className:"flex justify-center items-center py-1.5 text-[11px] text-muted-foreground tabular-nums","data-testid":"movies-count",children:g.length===r.length?`${r.length} movies`:`${g.length} / ${r.length} movies`})]}),y.jsx(bh,{children:f&&y.jsx($t.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-50 bg-black/80 backdrop-blur-sm flex items-center justify-center p-4",children:y.jsxs($t.div,{initial:{scale:.95},animate:{scale:1},exit:{scale:.95},className:"relative w-full max-w-4xl glass-card rounded-2xl overflow-hidden",children:[y.jsx("button",{onClick:()=>p(null),className:"absolute top-3 right-3 z-10 w-8 h-8 rounded-full glass flex items-center justify-center",children:y.jsx(Sa,{className:"w-4 h-4 text-foreground"})}),y.jsx("div",{className:"aspect-video bg-black",children:y.jsx(i1,{src:f.streamUrl,poster:f.posterUrl})}),y.jsxs("div",{className:"p-4",children:[y.jsx("p",{className:"text-foreground text-sm font-medium",children:f.name}),y.jsxs("p",{className:"text-muted-foreground text-xs",children:[f.category," ",f.year&&`• ${f.year}`]})]})]})})})]}):y.jsx(Vc,{title:e("movies.title"),children:y.jsx("div",{className:"h-full flex items-center justify-center",children:y.jsxs("div",{className:"glass-card rounded-2xl p-6 text-center max-w-sm",children:[y.jsx("p",{className:"text-foreground text-sm mb-3",children:e("movies.noActiveServer")}),b?y.jsx("p",{className:"text-muted-foreground text-xs",children:e("movies.contactAdmin")}):y.jsx(pT,{to:"/account",className:"text-primary text-xs underline",children:e("movies.addProfile")})]})})})},Lfe=()=>{var U;const{activeProfile:t}=mo(),{t:e}=Wr(),{user:n}=Bs(),{data:r=[],isLoading:i,error:s}=Fj(t),a=Sv(),{isFavorite:o,toggle:l}=s1(t==null?void 0:t.id,"series"),[c,u]=D.useState(""),[d,h]=D.useState("All"),[f,p]=D.useState(null),[m,g]=D.useState(null),b=["All",...Array.from(new Set(r.map(O=>O.category)))],v=r.filter(O=>{const k=O.name.toLowerCase().includes(c.toLowerCase()),I=d==="All"||O.category===d;return k&&I}),S=uh({queryKey:["xtream",t==null?void 0:t.id,"series-info",f==null?void 0:f.id],queryFn:()=>ps.getSeriesInfo(t,f.id),enabled:!!f&&!!t}),E=(n==null?void 0:n.role)==="user";if(!t)return y.jsx(Vc,{title:e("series.title"),children:y.jsx("div",{className:"h-full flex items-center justify-center",children:y.jsxs("div",{className:"glass-card rounded-2xl p-6 text-center max-w-sm",children:[y.jsx("p",{className:"text-foreground text-sm mb-3",children:e("series.noActiveServer")}),E?y.jsx("p",{className:"text-muted-foreground text-xs",children:e("series.contactAdmin")}):y.jsx(pT,{to:"/account",className:"text-primary text-xs underline",children:e("series.addProfile")})]})})});const L=((U=S.data)==null?void 0:U.episodes)??{};return y.jsxs(Vc,{title:e("series.title"),children:[y.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[y.jsxs("div",{className:"flex gap-2",children:[y.jsxs("div",{className:"glass-card rounded-xl px-3 py-2 flex items-center gap-2 w-40",children:[y.jsx(tv,{className:"w-4 h-4 text-muted-foreground"}),y.jsx("select",{value:d,onChange:O=>h(O.target.value),className:"bg-transparent text-foreground text-xs outline-none flex-1",children:b.map(O=>y.jsx("option",{value:O,className:"bg-background",children:O==="All"?e("common.all"):O},O))})]}),y.jsxs("div",{className:"glass-card rounded-xl px-3 py-2 flex items-center gap-2 flex-1",children:[y.jsx(ST,{className:"w-4 h-4 text-muted-foreground"}),y.jsx("input",{type:"text",placeholder:e("series.searchPlaceholder"),value:c,onChange:O=>u(O.target.value),className:"bg-transparent text-foreground placeholder:text-muted-foreground text-xs outline-none flex-1"})]}),y.jsx("button",{onClick:()=>a(t.id),className:"glass-card rounded-xl px-3 py-2",children:y.jsx(tm,{className:"w-4 h-4 text-muted-foreground"})})]}),i&&y.jsx("div",{className:"flex items-center justify-center py-12",children:y.jsx(yr,{className:"w-6 h-6 text-primary animate-spin"})}),s&&y.jsx("p",{className:"text-destructive text-xs",children:e("series.failedLoad")}),y.jsx(Rl,{focusKey:"series-grid",className:"flex-1 overflow-y-auto grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3 pb-2",children:v.slice(0,300).map(O=>y.jsxs(Fc,{focusKey:`series-${O.id}`,onEnter:()=>p(O),onClick:()=>p(O),style:{contentVisibility:"auto",containIntrinsicSize:"260px"},className:"glass-card rounded-xl overflow-hidden cursor-pointer group hover:border-primary/30 transition-all border-transparent",children:[y.jsxs("div",{className:"aspect-[2/3] bg-muted/20 flex items-center justify-center relative overflow-hidden",children:[O.posterUrl?y.jsx("img",{src:O.posterUrl,alt:O.name,loading:"lazy",decoding:"async",className:"w-full h-full object-cover",onError:k=>k.currentTarget.style.display="none"}):y.jsx(nv,{className:"w-8 h-8 text-muted-foreground/30 group-hover:text-primary/60 transition-colors"}),y.jsx("button",{onClick:k=>{k.stopPropagation(),l(O.id)},className:"absolute top-2 right-2 z-10",children:y.jsx(Sf,{className:`w-4 h-4 ${o(O.id)?"text-primary fill-primary":"text-muted-foreground/80"}`})}),O.rating&&y.jsxs("span",{className:"absolute top-2 left-2 text-[10px] bg-primary/80 text-primary-foreground px-1.5 py-0.5 rounded",children:["★ ",O.rating]})]}),y.jsxs("div",{className:"p-2.5",children:[y.jsx("p",{className:"text-foreground text-xs font-medium truncate",children:O.name}),y.jsx("span",{className:"text-muted-foreground text-[10px] truncate block",children:O.category})]})]},O.id))}),!i&&!s&&y.jsx("div",{className:"flex justify-center items-center py-1.5 text-[11px] text-muted-foreground tabular-nums","data-testid":"series-count",children:v.length===r.length?`${r.length} series`:`${v.length} / ${r.length} series`})]}),y.jsx(bh,{children:f&&y.jsx($t.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-50 bg-black/80 backdrop-blur-sm flex items-center justify-center p-4",onClick:()=>{p(null),g(null)},children:y.jsxs($t.div,{initial:{scale:.95},animate:{scale:1},exit:{scale:.95},onClick:O=>O.stopPropagation(),className:"relative w-full max-w-4xl max-h-[90vh] glass-card rounded-2xl overflow-hidden flex flex-col",children:[y.jsx("button",{onClick:()=>{p(null),g(null)},className:"absolute top-3 right-3 z-10 w-8 h-8 rounded-full glass flex items-center justify-center",children:y.jsx(Sa,{className:"w-4 h-4 text-foreground"})}),m?y.jsx("div",{className:"aspect-video bg-black",children:y.jsx(i1,{src:m})}):y.jsxs("div",{className:"p-5 flex gap-4 border-b border-border",children:[f.posterUrl&&y.jsx("img",{src:f.posterUrl,alt:"",className:"w-24 h-36 object-cover rounded-lg"}),y.jsxs("div",{children:[y.jsx("h2",{className:"text-foreground text-lg font-medium",children:f.name}),y.jsx("p",{className:"text-muted-foreground text-xs mb-1",children:f.category}),f.rating&&y.jsxs("p",{className:"text-primary text-xs",children:["★ ",f.rating]}),f.plot&&y.jsx("p",{className:"text-muted-foreground text-xs mt-2 line-clamp-3",children:f.plot})]})]}),y.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[S.isLoading&&y.jsx("div",{className:"flex justify-center py-6",children:y.jsx(EK,{className:"w-5 h-5 animate-spin text-primary"})}),Object.entries(L).map(([O,k])=>y.jsxs(Rl,{focusKey:`season-${O}`,children:[y.jsx("h3",{className:"text-foreground text-sm font-medium mb-2",children:e("series.season",{n:O})}),y.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:k.map(I=>y.jsxs(Cv,{focusKey:`ep-${I.id}`,onEnter:()=>g(ps.buildSeriesEpisodeUrl(t,I.id,I.container_extension||"mp4")),onClick:()=>g(ps.buildSeriesEpisodeUrl(t,I.id,I.container_extension||"mp4")),className:"flex items-center gap-2 glass rounded-lg px-3 py-2 hover:border-primary/30 transition-all text-left border-transparent",children:[y.jsx(sc,{className:"w-3 h-3 text-primary shrink-0"}),y.jsxs("span",{className:"text-foreground text-xs truncate",children:[e("series.episodePrefix",{n:I.episode_num}),": ",I.title]})]},I.id))})]},O))]})]})})})]})},kfe="",Ff="1.0.0";async function a1(){const t=await fetch(`${kfe}/api/public/app-info`,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`HTTP ${t.status}`);return await t.json()}function _D(t,e){const n=a=>(a||"0").trim().split("-")[0].split(".").map(o=>parseInt(o,10)||0),r=n(t),i=n(e),s=Math.max(r.length,i.length);for(let a=0;a<s;a++){const o=r[a]??0,l=i[a]??0;if(o>l)return 1;if(o<l)return-1}return 0}function Ife(t,e){const n=(t||"").replace(/[^\d]/g,"");if(!n)return null;const r=encodeURIComponent(e||"");return`https://wa.me/${n}${r?`?text=${r}`:""}`}const Pfe=5*60*1e3,M4="nadi_update_snoozed_for";function B4(){const[t,e]=D.useState(null),[n,r]=D.useState(!0);D.useEffect(()=>{let l=!1,c;const u=async()=>{try{const d=await a1();l||e(d)}catch{}finally{l||r(!1)}};return u(),c=setInterval(u,Pfe),()=>{l=!0,c&&clearInterval(c)}},[]);const i=t==null?void 0:t.update,s=!!(i!=null&&i.enabled),a=s&&!!(i!=null&&i.latest_version)&&_D(i.latest_version,Ff)>0,o=s&&!!(i!=null&&i.min_supported_version)&&_D(Ff,i.min_supported_version)<0;return{loading:n,info:t,installedVersion:Ff,hasUpdate:a,forced:o}}function Dfe(t){try{sessionStorage.setItem(M4,t||"")}catch{}}function Ofe(t){try{return sessionStorage.getItem(M4)===(t||"")}catch{return!1}}const Nfe=()=>{const t=qr(),{hasUpdate:e,info:n}=B4(),[r,i]=D.useState(n);D.useEffect(()=>{if(n){i(n);return}let u=!1;return a1().then(d=>{u||i(d)}).catch(()=>{}),()=>{u=!0}},[n]);const s=r==null?void 0:r.creator,a=r==null?void 0:r.support,o=r==null?void 0:r.update,l=a?Ife(a.whatsapp_number,a.whatsapp_message):null,c=(o==null?void 0:o.apk_url)||(o==null?void 0:o.play_url)||"";return y.jsxs("div",{className:"glass-card rounded-2xl p-4 space-y-4","data-testid":"account-help-about-card",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx(fK,{className:"w-4 h-4 text-primary"}),y.jsx("p",{className:"text-foreground text-sm font-medium",children:"Help & About"})]}),y.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-border/60 bg-background/30 p-3",children:[y.jsx("div",{className:"flex h-12 w-12 shrink-0 items-center justify-center overflow-hidden rounded-xl border border-primary/40 bg-primary/10",children:y.jsx("img",{src:"/icon-192.png",alt:"Nadiplayer",className:"h-12 w-12 object-cover",onError:u=>{u.currentTarget.style.display="none"},"data-testid":"account-app-icon"})}),y.jsxs("div",{className:"min-w-0 flex-1",children:[y.jsx("p",{className:"truncate text-sm font-semibold text-foreground",children:"Nadiplayer"}),y.jsxs("p",{className:"text-[11px] text-muted-foreground","data-testid":"account-app-version",children:["Version v",Ff,(o==null?void 0:o.latest_version)&&o.latest_version!==Ff&&y.jsxs("span",{className:"ml-1 text-muted-foreground/70",children:["(latest v",o.latest_version,")"]})]})]}),e&&y.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-primary/40 bg-primary/15 px-2 py-1 text-[10px] font-medium text-primary","data-testid":"account-update-badge",children:[y.jsx(L2,{className:"h-3 w-3"}),"Update"]})]}),c&&y.jsxs("a",{href:c,target:"_blank",rel:"noopener noreferrer","data-testid":"account-download-update-btn",className:"flex items-center justify-center gap-2 rounded-xl border border-primary/40 bg-primary/10 px-4 py-2.5 text-xs font-medium text-primary transition-colors hover:bg-primary/15",children:[y.jsx(_T,{className:"h-3.5 w-3.5"}),e?"Download latest version":"Check downloads"]}),((s==null?void 0:s.name)||(s==null?void 0:s.bio)||(s==null?void 0:s.role))&&y.jsxs("div",{className:"rounded-xl border border-border/60 bg-background/30 p-3","data-testid":"account-creator-card",children:[y.jsx("p",{className:"mb-2 text-[10px] font-medium uppercase tracking-[0.2em] text-muted-foreground",children:"Created by"}),y.jsxs("div",{className:"flex items-start gap-3",children:[y.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-full border border-primary/40 bg-primary/10",children:s.avatar_url?y.jsx("img",{src:s.avatar_url,alt:s.name,className:"h-10 w-10 object-cover",onError:u=>{u.currentTarget.style.display="none"}}):y.jsx(fo,{className:"h-5 w-5 text-primary"})}),y.jsxs("div",{className:"min-w-0 flex-1",children:[s.name&&y.jsx("p",{className:"truncate text-sm font-medium text-foreground","data-testid":"account-creator-name",children:s.name}),s.role&&y.jsx("p",{className:"truncate text-[11px] text-primary/80",children:s.role}),s.bio&&y.jsx("p",{className:"mt-1 whitespace-pre-wrap text-[11px] leading-relaxed text-muted-foreground",children:s.bio})]})]})]}),y.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[y.jsxs("button",{type:"button",onClick:()=>t("/privacy"),"data-testid":"account-privacy-link",className:"flex items-center gap-2 rounded-xl border border-border/60 bg-background/30 px-3 py-2.5 text-xs text-foreground transition-colors hover:border-primary/40",children:[y.jsx(ap,{className:"h-3.5 w-3.5 text-primary"}),y.jsx("span",{children:"Privacy Policy"}),y.jsx(no,{className:"ml-auto h-3 w-3 text-muted-foreground"})]}),(a==null?void 0:a.email)&&y.jsxs("a",{href:`mailto:${a.email}`,"data-testid":"account-email-link",className:"flex items-center gap-2 rounded-xl border border-border/60 bg-background/30 px-3 py-2.5 text-xs text-foreground transition-colors hover:border-primary/40",children:[y.jsx(kK,{className:"h-3.5 w-3.5 text-primary"}),y.jsx("span",{className:"truncate",children:a.email})]})]}),l&&y.jsx($t.a,{initial:{scale:.92,opacity:0},animate:{scale:1,opacity:1},whileHover:{scale:1.05},whileTap:{scale:.95},href:l,target:"_blank",rel:"noopener noreferrer","data-testid":"account-whatsapp-fab","aria-label":"Contact us on WhatsApp",className:"fixed bottom-24 right-4 z-40 flex h-12 w-12 items-center justify-center rounded-full bg-[#25D366] text-white shadow-lg shadow-[#25D366]/40 ring-2 ring-white/10 transition-shadow hover:shadow-xl",children:y.jsx(R2,{className:"h-5 w-5"})})]})},Mfe=()=>{const{profiles:t}=mo(),e=mA(),n=e?t.find(l=>l.id===e)??null:null,r=Uj(n),i=jj(n),s=Fj(n),[a,o]=D.useState(tI);return D.useEffect(()=>{const l=()=>o(tI());return window.addEventListener("nadiplay-managed-counts-changed",l),window.addEventListener("storage",l),()=>{window.removeEventListener("nadiplay-managed-counts-changed",l),window.removeEventListener("storage",l)}},[]),D.useEffect(()=>{var d,h,f;if(!n)return;const l=(d=r.data)==null?void 0:d.length,c=(h=i.data)==null?void 0:h.length,u=(f=s.data)==null?void 0:f.length;l===void 0||c===void 0||u===void 0||a&&a.channels===l&&a.movies===c&&a.series===u||(Vj({channels:l,movies:c,series:u}),o({channels:l,movies:c,series:u,updatedAt:Date.now()}))},[n,r.data,i.data,s.data,a]),e?a:null},Bfe=()=>{const{t}=Wr(),{profiles:e,activeProfileId:n,setActiveProfileId:r,updateProfile:i,removeProfile:s}=mo(),a=Sv(),o=PA(),l=mA(),c=Mfe(),[u,d]=D.useState(!1),[h,f]=D.useState(null),[p,m]=D.useState({}),[g,b]=D.useState(null),[v,S]=D.useState(sa()),E=qr(),L=R=>{f(R.id),m({name:R.name,serverUrl:R.serverUrl,username:R.username,password:R.password})},U=R=>{i(R,p),f(null),Mt.success(t("account.profileUpdated"))},O=R=>{a(R),Mt.success(t("account.playlistReloaded"))},k=async R=>{b(R.id);try{await ps.authenticate(R),Mt.success(t("account.connectedSuccess",{name:R.name}))}catch(M){Mt.error(t("account.connectFailed",{name:R.name,error:(M==null?void 0:M.message)??"Failed to connect"}))}finally{b(null)}},I=R=>{confirm(t("account.confirmDelete"))&&(s(R),Mt.success(t("account.profileRemoved")))};return y.jsxs(Vc,{title:t("account.title"),children:[y.jsxs("div",{className:"h-full flex flex-col gap-3 max-w-2xl mx-auto w-full",children:[y.jsxs("div",{className:"flex items-center justify-between",children:[y.jsx("p",{className:"text-muted-foreground text-xs",children:t("account.profilesCount",{count:e.length})}),y.jsxs("button",{onClick:()=>d(!0),className:"glass-card rounded-xl px-4 py-2 flex items-center gap-2 hover:border-primary/40 transition-all",children:[y.jsx(gl,{className:"w-4 h-4 text-primary"}),y.jsx("span",{className:"text-foreground text-xs font-medium",children:t("account.addServer")})]})]}),y.jsxs("div",{className:"flex-1 overflow-y-auto space-y-3 pr-1",children:[y.jsxs("div",{className:"glass-card rounded-2xl p-4","data-testid":"device-pairing-section",children:[y.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[y.jsx(Wy,{className:"w-4 h-4 text-primary"}),y.jsx("p",{className:"text-foreground text-sm font-medium",children:t("account.devicePairing")})]}),y.jsx("p",{className:"text-muted-foreground text-[11px] mb-3",children:t("account.devicePairingDesc")}),y.jsxs("div",{className:"flex gap-2",children:[y.jsxs("button",{onClick:()=>E("/activate"),className:"flex-1 text-[12px] px-3 py-2 rounded-lg glass hover:border-primary/40 text-foreground flex items-center justify-center gap-2 transition-all","data-testid":"go-activate-btn",children:[y.jsx(AC,{className:"w-3.5 h-3.5"})," ",t("account.imOnDevice")]}),y.jsxs("button",{onClick:()=>E("/pair"),className:"flex-1 text-[12px] px-3 py-2 rounded-lg glass hover:border-primary/40 text-foreground flex items-center justify-center gap-2 transition-all","data-testid":"go-pair-btn",children:[y.jsx(Wy,{className:"w-3.5 h-3.5"})," ",t("account.iHavePin")]})]})]}),y.jsx(Nfe,{}),y.jsxs("div",{className:"glass-card rounded-2xl p-4",children:[y.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[y.jsx(AC,{className:"w-4 h-4 text-primary"}),y.jsx("p",{className:"text-foreground text-sm font-medium",children:t("account.playerIdentity")})]}),y.jsx("p",{className:"text-muted-foreground text-[11px] mb-3",children:t("account.playerIdentityDesc")}),y.jsx("div",{className:"flex flex-wrap gap-2",children:Ij.map(R=>{const M=v===R.value;return y.jsx("button",{onClick:()=>{Hte(R.value),S(R.value),Mt.success(t("account.userAgentSet",{name:R.label}))},className:`text-[11px] px-3 py-1.5 rounded-lg transition-all ${M?"bg-primary/20 text-primary border border-primary/40":"glass hover:border-primary/40 text-foreground"}`,children:R.label},R.id)})}),y.jsxs("p",{className:"text-muted-foreground text-[10px] mt-2 truncate",children:[t("account.sending"),": ",y.jsx("span",{className:"text-foreground/70",children:v})]})]}),e.length===0&&y.jsxs("div",{className:"glass-card rounded-2xl p-8 text-center",children:[y.jsx(Cc,{className:"w-10 h-10 text-muted-foreground/40 mx-auto mb-3"}),y.jsx("p",{className:"text-foreground text-sm mb-1",children:t("account.noProfiles")}),y.jsx("p",{className:"text-muted-foreground text-xs",children:t("account.noProfilesDesc")})]}),e.map(R=>{const M=R.id===n,z=h===R.id,Z=!!l&&R.id===l;return y.jsxs($t.div,{layout:!0,"data-testid":Z?"managed-profile-card":"user-profile-card",className:`glass-card rounded-2xl p-4 border ${M?"border-primary/40":"border-transparent"}`,children:[y.jsxs("div",{className:"flex items-start gap-3",children:[y.jsx("div",{className:`w-10 h-10 rounded-full glass flex items-center justify-center shrink-0 ${M?"border border-primary":""}`,children:Z?y.jsx(ap,{className:`w-5 h-5 ${M?"text-primary":"text-muted-foreground"}`}):y.jsx(fo,{className:`w-5 h-5 ${M?"text-primary":"text-muted-foreground"}`})}),y.jsx("div",{className:"flex-1 min-w-0 space-y-2",children:z&&!Z?y.jsx(y.Fragment,{children:[{key:"name",label:"profileName"},{key:"serverUrl",label:"serverUrl"},{key:"username",label:"username"},{key:"password",label:"password"}].map(({key:W,label:re})=>y.jsx("input",{value:p[W]??"",onChange:X=>m({...p,[W]:X.target.value}),placeholder:t(re==="profileName"?"account.profileName":re==="serverUrl"?"account.serverUrl":re==="username"?"common.username":"common.password"),className:"w-full glass-input rounded-lg px-3 py-2 text-foreground text-xs outline-none"},W))}):Z?y.jsxs(y.Fragment,{children:[y.jsx("p",{className:"text-foreground text-sm font-medium truncate",children:R.name}),y.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-primary",children:[y.jsx(ap,{className:"w-3 h-3"}),y.jsx("span",{children:"Managed by admin"})]}),y.jsxs("div",{className:"flex flex-wrap gap-3 pt-1","data-testid":"managed-counts",children:[y.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-foreground/80",children:[y.jsx(xa,{className:"w-3 h-3 text-primary"}),y.jsx("span",{className:"tabular-nums",children:(c==null?void 0:c.channels)??"—"}),y.jsx("span",{className:"text-muted-foreground",children:"TV"})]}),y.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-foreground/80",children:[y.jsx(xT,{className:"w-3 h-3 text-primary"}),y.jsx("span",{className:"tabular-nums",children:(c==null?void 0:c.movies)??"—"}),y.jsx("span",{className:"text-muted-foreground",children:"Movies"})]}),y.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-foreground/80",children:[y.jsx(nv,{className:"w-3 h-3 text-primary"}),y.jsx("span",{className:"tabular-nums",children:(c==null?void 0:c.series)??"—"}),y.jsx("span",{className:"text-muted-foreground",children:"Series"})]})]})]}):y.jsxs(y.Fragment,{children:[y.jsx("p",{className:"text-foreground text-sm font-medium truncate",children:R.name}),y.jsx("p",{className:"text-muted-foreground text-xs truncate",children:R.serverUrl}),y.jsxs("p",{className:"text-muted-foreground text-[10px] truncate",children:[t("account.user"),": ",R.username]})]})}),!Z&&y.jsx("div",{className:"flex flex-col gap-1.5 shrink-0",children:z?y.jsxs(y.Fragment,{children:[y.jsx("button",{onClick:()=>U(R.id),className:"w-8 h-8 rounded-lg glass flex items-center justify-center hover:border-primary/40",children:y.jsx(Ol,{className:"w-4 h-4 text-primary"})}),y.jsx("button",{onClick:()=>f(null),className:"w-8 h-8 rounded-lg glass flex items-center justify-center",children:y.jsx(Sa,{className:"w-4 h-4 text-muted-foreground"})})]}):y.jsxs(y.Fragment,{children:[y.jsx("button",{onClick:()=>L(R),className:"w-8 h-8 rounded-lg glass flex items-center justify-center hover:border-primary/40",children:y.jsx(DK,{className:"w-3.5 h-3.5 text-muted-foreground"})}),y.jsx("button",{onClick:()=>I(R.id),className:"w-8 h-8 rounded-lg glass flex items-center justify-center hover:border-destructive/40",children:y.jsx(nm,{className:"w-3.5 h-3.5 text-destructive"})})]})})]}),!z&&y.jsxs("div",{className:"flex flex-wrap gap-2 mt-3 pt-3 border-t border-border/40",children:[y.jsx("button",{onClick:()=>r(R.id),disabled:M,className:`text-[11px] px-3 py-1.5 rounded-lg transition-all ${M?"bg-primary/20 text-primary":"glass hover:border-primary/40 text-foreground"}`,children:t(M?"common.active":"common.setActive")}),!Z&&y.jsxs("button",{onClick:()=>k(R),disabled:g===R.id,className:"text-[11px] px-3 py-1.5 rounded-lg glass hover:border-primary/40 text-foreground flex items-center gap-1.5",children:[g===R.id?y.jsx(yr,{className:"w-3 h-3 animate-spin"}):null," ",t("common.test")]}),y.jsxs("button",{onClick:()=>O(R.id),className:"text-[11px] px-3 py-1.5 rounded-lg glass hover:border-primary/40 text-foreground flex items-center gap-1.5",children:[y.jsx(tm,{className:"w-3 h-3"})," ",t("account.reloadPlaylist")]})]})]},R.id)})]})]}),y.jsx(e3,{open:u,onClose:()=>d(!1),onSubmit:async R=>{await o(R)&&d(!1)}})]})};var Ufe=Object.defineProperty,L0=Object.getOwnPropertySymbols,U4=Object.prototype.hasOwnProperty,j4=Object.prototype.propertyIsEnumerable,bD=(t,e,n)=>e in t?Ufe(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,tw=(t,e)=>{for(var n in e||(e={}))U4.call(e,n)&&bD(t,n,e[n]);if(L0)for(var n of L0(e))j4.call(e,n)&&bD(t,n,e[n]);return t},nw=(t,e)=>{var n={};for(var r in t)U4.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&L0)for(var r of L0(t))e.indexOf(r)<0&&j4.call(t,r)&&(n[r]=t[r]);return n};/**
 * @license QR Code generator library (TypeScript)
 * Copyright (c) Project Nayuki.
 * SPDX-License-Identifier: MIT
 */var Hc;(t=>{const e=class Ht{constructor(l,c,u,d){if(this.version=l,this.errorCorrectionLevel=c,this.modules=[],this.isFunction=[],l<Ht.MIN_VERSION||l>Ht.MAX_VERSION)throw new RangeError("Version value out of range");if(d<-1||d>7)throw new RangeError("Mask value out of range");this.size=l*4+17;let h=[];for(let p=0;p<this.size;p++)h.push(!1);for(let p=0;p<this.size;p++)this.modules.push(h.slice()),this.isFunction.push(h.slice());this.drawFunctionPatterns();const f=this.addEccAndInterleave(u);if(this.drawCodewords(f),d==-1){let p=1e9;for(let m=0;m<8;m++){this.applyMask(m),this.drawFormatBits(m);const g=this.getPenaltyScore();g<p&&(d=m,p=g),this.applyMask(m)}}i(0<=d&&d<=7),this.mask=d,this.applyMask(d),this.drawFormatBits(d),this.isFunction=[]}static encodeText(l,c){const u=t.QrSegment.makeSegments(l);return Ht.encodeSegments(u,c)}static encodeBinary(l,c){const u=t.QrSegment.makeBytes(l);return Ht.encodeSegments([u],c)}static encodeSegments(l,c,u=1,d=40,h=-1,f=!0){if(!(Ht.MIN_VERSION<=u&&u<=d&&d<=Ht.MAX_VERSION)||h<-1||h>7)throw new RangeError("Invalid value");let p,m;for(p=u;;p++){const S=Ht.getNumDataCodewords(p,c)*8,E=a.getTotalBits(l,p);if(E<=S){m=E;break}if(p>=d)throw new RangeError("Data too long")}for(const S of[Ht.Ecc.MEDIUM,Ht.Ecc.QUARTILE,Ht.Ecc.HIGH])f&&m<=Ht.getNumDataCodewords(p,S)*8&&(c=S);let g=[];for(const S of l){n(S.mode.modeBits,4,g),n(S.numChars,S.mode.numCharCountBits(p),g);for(const E of S.getData())g.push(E)}i(g.length==m);const b=Ht.getNumDataCodewords(p,c)*8;i(g.length<=b),n(0,Math.min(4,b-g.length),g),n(0,(8-g.length%8)%8,g),i(g.length%8==0);for(let S=236;g.length<b;S^=253)n(S,8,g);let v=[];for(;v.length*8<g.length;)v.push(0);return g.forEach((S,E)=>v[E>>>3]|=S<<7-(E&7)),new Ht(p,c,v,h)}getModule(l,c){return 0<=l&&l<this.size&&0<=c&&c<this.size&&this.modules[c][l]}getModules(){return this.modules}drawFunctionPatterns(){for(let u=0;u<this.size;u++)this.setFunctionModule(6,u,u%2==0),this.setFunctionModule(u,6,u%2==0);this.drawFinderPattern(3,3),this.drawFinderPattern(this.size-4,3),this.drawFinderPattern(3,this.size-4);const l=this.getAlignmentPatternPositions(),c=l.length;for(let u=0;u<c;u++)for(let d=0;d<c;d++)u==0&&d==0||u==0&&d==c-1||u==c-1&&d==0||this.drawAlignmentPattern(l[u],l[d]);this.drawFormatBits(0),this.drawVersion()}drawFormatBits(l){const c=this.errorCorrectionLevel.formatBits<<3|l;let u=c;for(let h=0;h<10;h++)u=u<<1^(u>>>9)*1335;const d=(c<<10|u)^21522;i(d>>>15==0);for(let h=0;h<=5;h++)this.setFunctionModule(8,h,r(d,h));this.setFunctionModule(8,7,r(d,6)),this.setFunctionModule(8,8,r(d,7)),this.setFunctionModule(7,8,r(d,8));for(let h=9;h<15;h++)this.setFunctionModule(14-h,8,r(d,h));for(let h=0;h<8;h++)this.setFunctionModule(this.size-1-h,8,r(d,h));for(let h=8;h<15;h++)this.setFunctionModule(8,this.size-15+h,r(d,h));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let l=this.version;for(let u=0;u<12;u++)l=l<<1^(l>>>11)*7973;const c=this.version<<12|l;i(c>>>18==0);for(let u=0;u<18;u++){const d=r(c,u),h=this.size-11+u%3,f=Math.floor(u/3);this.setFunctionModule(h,f,d),this.setFunctionModule(f,h,d)}}drawFinderPattern(l,c){for(let u=-4;u<=4;u++)for(let d=-4;d<=4;d++){const h=Math.max(Math.abs(d),Math.abs(u)),f=l+d,p=c+u;0<=f&&f<this.size&&0<=p&&p<this.size&&this.setFunctionModule(f,p,h!=2&&h!=4)}}drawAlignmentPattern(l,c){for(let u=-2;u<=2;u++)for(let d=-2;d<=2;d++)this.setFunctionModule(l+d,c+u,Math.max(Math.abs(d),Math.abs(u))!=1)}setFunctionModule(l,c,u){this.modules[c][l]=u,this.isFunction[c][l]=!0}addEccAndInterleave(l){const c=this.version,u=this.errorCorrectionLevel;if(l.length!=Ht.getNumDataCodewords(c,u))throw new RangeError("Invalid argument");const d=Ht.NUM_ERROR_CORRECTION_BLOCKS[u.ordinal][c],h=Ht.ECC_CODEWORDS_PER_BLOCK[u.ordinal][c],f=Math.floor(Ht.getNumRawDataModules(c)/8),p=d-f%d,m=Math.floor(f/d);let g=[];const b=Ht.reedSolomonComputeDivisor(h);for(let S=0,E=0;S<d;S++){let L=l.slice(E,E+m-h+(S<p?0:1));E+=L.length;const U=Ht.reedSolomonComputeRemainder(L,b);S<p&&L.push(0),g.push(L.concat(U))}let v=[];for(let S=0;S<g[0].length;S++)g.forEach((E,L)=>{(S!=m-h||L>=p)&&v.push(E[S])});return i(v.length==f),v}drawCodewords(l){if(l.length!=Math.floor(Ht.getNumRawDataModules(this.version)/8))throw new RangeError("Invalid argument");let c=0;for(let u=this.size-1;u>=1;u-=2){u==6&&(u=5);for(let d=0;d<this.size;d++)for(let h=0;h<2;h++){const f=u-h,m=(u+1&2)==0?this.size-1-d:d;!this.isFunction[m][f]&&c<l.length*8&&(this.modules[m][f]=r(l[c>>>3],7-(c&7)),c++)}}i(c==l.length*8)}applyMask(l){if(l<0||l>7)throw new RangeError("Mask value out of range");for(let c=0;c<this.size;c++)for(let u=0;u<this.size;u++){let d;switch(l){case 0:d=(u+c)%2==0;break;case 1:d=c%2==0;break;case 2:d=u%3==0;break;case 3:d=(u+c)%3==0;break;case 4:d=(Math.floor(u/3)+Math.floor(c/2))%2==0;break;case 5:d=u*c%2+u*c%3==0;break;case 6:d=(u*c%2+u*c%3)%2==0;break;case 7:d=((u+c)%2+u*c%3)%2==0;break;default:throw new Error("Unreachable")}!this.isFunction[c][u]&&d&&(this.modules[c][u]=!this.modules[c][u])}}getPenaltyScore(){let l=0;for(let h=0;h<this.size;h++){let f=!1,p=0,m=[0,0,0,0,0,0,0];for(let g=0;g<this.size;g++)this.modules[h][g]==f?(p++,p==5?l+=Ht.PENALTY_N1:p>5&&l++):(this.finderPenaltyAddHistory(p,m),f||(l+=this.finderPenaltyCountPatterns(m)*Ht.PENALTY_N3),f=this.modules[h][g],p=1);l+=this.finderPenaltyTerminateAndCount(f,p,m)*Ht.PENALTY_N3}for(let h=0;h<this.size;h++){let f=!1,p=0,m=[0,0,0,0,0,0,0];for(let g=0;g<this.size;g++)this.modules[g][h]==f?(p++,p==5?l+=Ht.PENALTY_N1:p>5&&l++):(this.finderPenaltyAddHistory(p,m),f||(l+=this.finderPenaltyCountPatterns(m)*Ht.PENALTY_N3),f=this.modules[g][h],p=1);l+=this.finderPenaltyTerminateAndCount(f,p,m)*Ht.PENALTY_N3}for(let h=0;h<this.size-1;h++)for(let f=0;f<this.size-1;f++){const p=this.modules[h][f];p==this.modules[h][f+1]&&p==this.modules[h+1][f]&&p==this.modules[h+1][f+1]&&(l+=Ht.PENALTY_N2)}let c=0;for(const h of this.modules)c=h.reduce((f,p)=>f+(p?1:0),c);const u=this.size*this.size,d=Math.ceil(Math.abs(c*20-u*10)/u)-1;return i(0<=d&&d<=9),l+=d*Ht.PENALTY_N4,i(0<=l&&l<=2568888),l}getAlignmentPatternPositions(){if(this.version==1)return[];{const l=Math.floor(this.version/7)+2,c=this.version==32?26:Math.ceil((this.version*4+4)/(l*2-2))*2;let u=[6];for(let d=this.size-7;u.length<l;d-=c)u.splice(1,0,d);return u}}static getNumRawDataModules(l){if(l<Ht.MIN_VERSION||l>Ht.MAX_VERSION)throw new RangeError("Version number out of range");let c=(16*l+128)*l+64;if(l>=2){const u=Math.floor(l/7)+2;c-=(25*u-10)*u-55,l>=7&&(c-=36)}return i(208<=c&&c<=29648),c}static getNumDataCodewords(l,c){return Math.floor(Ht.getNumRawDataModules(l)/8)-Ht.ECC_CODEWORDS_PER_BLOCK[c.ordinal][l]*Ht.NUM_ERROR_CORRECTION_BLOCKS[c.ordinal][l]}static reedSolomonComputeDivisor(l){if(l<1||l>255)throw new RangeError("Degree out of range");let c=[];for(let d=0;d<l-1;d++)c.push(0);c.push(1);let u=1;for(let d=0;d<l;d++){for(let h=0;h<c.length;h++)c[h]=Ht.reedSolomonMultiply(c[h],u),h+1<c.length&&(c[h]^=c[h+1]);u=Ht.reedSolomonMultiply(u,2)}return c}static reedSolomonComputeRemainder(l,c){let u=c.map(d=>0);for(const d of l){const h=d^u.shift();u.push(0),c.forEach((f,p)=>u[p]^=Ht.reedSolomonMultiply(f,h))}return u}static reedSolomonMultiply(l,c){if(l>>>8||c>>>8)throw new RangeError("Byte out of range");let u=0;for(let d=7;d>=0;d--)u=u<<1^(u>>>7)*285,u^=(c>>>d&1)*l;return i(u>>>8==0),u}finderPenaltyCountPatterns(l){const c=l[1];i(c<=this.size*3);const u=c>0&&l[2]==c&&l[3]==c*3&&l[4]==c&&l[5]==c;return(u&&l[0]>=c*4&&l[6]>=c?1:0)+(u&&l[6]>=c*4&&l[0]>=c?1:0)}finderPenaltyTerminateAndCount(l,c,u){return l&&(this.finderPenaltyAddHistory(c,u),c=0),c+=this.size,this.finderPenaltyAddHistory(c,u),this.finderPenaltyCountPatterns(u)}finderPenaltyAddHistory(l,c){c[0]==0&&(l+=this.size),c.pop(),c.unshift(l)}};e.MIN_VERSION=1,e.MAX_VERSION=40,e.PENALTY_N1=3,e.PENALTY_N2=3,e.PENALTY_N3=40,e.PENALTY_N4=10,e.ECC_CODEWORDS_PER_BLOCK=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],e.NUM_ERROR_CORRECTION_BLOCKS=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],t.QrCode=e;function n(o,l,c){if(l<0||l>31||o>>>l)throw new RangeError("Value out of range");for(let u=l-1;u>=0;u--)c.push(o>>>u&1)}function r(o,l){return(o>>>l&1)!=0}function i(o){if(!o)throw new Error("Assertion error")}const s=class $n{constructor(l,c,u){if(this.mode=l,this.numChars=c,this.bitData=u,c<0)throw new RangeError("Invalid argument");this.bitData=u.slice()}static makeBytes(l){let c=[];for(const u of l)n(u,8,c);return new $n($n.Mode.BYTE,l.length,c)}static makeNumeric(l){if(!$n.isNumeric(l))throw new RangeError("String contains non-numeric characters");let c=[];for(let u=0;u<l.length;){const d=Math.min(l.length-u,3);n(parseInt(l.substring(u,u+d),10),d*3+1,c),u+=d}return new $n($n.Mode.NUMERIC,l.length,c)}static makeAlphanumeric(l){if(!$n.isAlphanumeric(l))throw new RangeError("String contains unencodable characters in alphanumeric mode");let c=[],u;for(u=0;u+2<=l.length;u+=2){let d=$n.ALPHANUMERIC_CHARSET.indexOf(l.charAt(u))*45;d+=$n.ALPHANUMERIC_CHARSET.indexOf(l.charAt(u+1)),n(d,11,c)}return u<l.length&&n($n.ALPHANUMERIC_CHARSET.indexOf(l.charAt(u)),6,c),new $n($n.Mode.ALPHANUMERIC,l.length,c)}static makeSegments(l){return l==""?[]:$n.isNumeric(l)?[$n.makeNumeric(l)]:$n.isAlphanumeric(l)?[$n.makeAlphanumeric(l)]:[$n.makeBytes($n.toUtf8ByteArray(l))]}static makeEci(l){let c=[];if(l<0)throw new RangeError("ECI assignment value out of range");if(l<128)n(l,8,c);else if(l<16384)n(2,2,c),n(l,14,c);else if(l<1e6)n(6,3,c),n(l,21,c);else throw new RangeError("ECI assignment value out of range");return new $n($n.Mode.ECI,0,c)}static isNumeric(l){return $n.NUMERIC_REGEX.test(l)}static isAlphanumeric(l){return $n.ALPHANUMERIC_REGEX.test(l)}getData(){return this.bitData.slice()}static getTotalBits(l,c){let u=0;for(const d of l){const h=d.mode.numCharCountBits(c);if(d.numChars>=1<<h)return 1/0;u+=4+h+d.bitData.length}return u}static toUtf8ByteArray(l){l=encodeURI(l);let c=[];for(let u=0;u<l.length;u++)l.charAt(u)!="%"?c.push(l.charCodeAt(u)):(c.push(parseInt(l.substring(u+1,u+3),16)),u+=2);return c}};s.NUMERIC_REGEX=/^[0-9]*$/,s.ALPHANUMERIC_REGEX=/^[A-Z0-9 $%*+.\/:-]*$/,s.ALPHANUMERIC_CHARSET="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";let a=s;t.QrSegment=s})(Hc||(Hc={}));(t=>{(e=>{const n=class{constructor(i,s){this.ordinal=i,this.formatBits=s}};n.LOW=new n(0,1),n.MEDIUM=new n(1,0),n.QUARTILE=new n(2,3),n.HIGH=new n(3,2),e.Ecc=n})(t.QrCode||(t.QrCode={}))})(Hc||(Hc={}));(t=>{(e=>{const n=class{constructor(i,s){this.modeBits=i,this.numBitsCharCount=s}numCharCountBits(i){return this.numBitsCharCount[Math.floor((i+7)/17)]}};n.NUMERIC=new n(1,[10,12,14]),n.ALPHANUMERIC=new n(2,[9,11,13]),n.BYTE=new n(4,[8,16,16]),n.KANJI=new n(8,[8,10,12]),n.ECI=new n(7,[0,0,0]),e.Mode=n})(t.QrSegment||(t.QrSegment={}))})(Hc||(Hc={}));var id=Hc;/**
 * @license qrcode.react
 * Copyright (c) Paul O'Shannessy
 * SPDX-License-Identifier: ISC
 */var jfe={L:id.QrCode.Ecc.LOW,M:id.QrCode.Ecc.MEDIUM,Q:id.QrCode.Ecc.QUARTILE,H:id.QrCode.Ecc.HIGH},F4=128,$4="L",V4="#FFFFFF",G4="#000000",H4=!1,K4=1,Ffe=4,$fe=0,Vfe=.1;function z4(t,e=0){const n=[];return t.forEach(function(r,i){let s=null;r.forEach(function(a,o){if(!a&&s!==null){n.push(`M${s+e} ${i+e}h${o-s}v1H${s+e}z`),s=null;return}if(o===r.length-1){if(!a)return;s===null?n.push(`M${o+e},${i+e} h1v1H${o+e}z`):n.push(`M${s+e},${i+e} h${o+1-s}v1H${s+e}z`);return}a&&s===null&&(s=o)})}),n.join("")}function q4(t,e){return t.slice().map((n,r)=>r<e.y||r>=e.y+e.h?n:n.map((i,s)=>s<e.x||s>=e.x+e.w?i:!1))}function Gfe(t,e,n,r){if(r==null)return null;const i=t.length+n*2,s=Math.floor(e*Vfe),a=i/e,o=(r.width||s)*a,l=(r.height||s)*a,c=r.x==null?t.length/2-o/2:r.x*a,u=r.y==null?t.length/2-l/2:r.y*a,d=r.opacity==null?1:r.opacity;let h=null;if(r.excavate){let p=Math.floor(c),m=Math.floor(u),g=Math.ceil(o+c-p),b=Math.ceil(l+u-m);h={x:p,y:m,w:g,h:b}}const f=r.crossOrigin;return{x:c,y:u,h:l,w:o,excavation:h,opacity:d,crossOrigin:f}}function Hfe(t,e){return e!=null?Math.max(Math.floor(e),0):t?Ffe:$fe}function W4({value:t,level:e,minVersion:n,includeMargin:r,marginSize:i,imageSettings:s,size:a,boostLevel:o}){let l=Fe.useMemo(()=>{const p=(Array.isArray(t)?t:[t]).reduce((m,g)=>(m.push(...id.QrSegment.makeSegments(g)),m),[]);return id.QrCode.encodeSegments(p,jfe[e],n,void 0,void 0,o)},[t,e,n,o]);const{cells:c,margin:u,numCells:d,calculatedImageSettings:h}=Fe.useMemo(()=>{let f=l.getModules();const p=Hfe(r,i),m=f.length+p*2,g=Gfe(f,a,p,s);return{cells:f,margin:p,numCells:m,calculatedImageSettings:g}},[l,a,s,r,i]);return{qrcode:l,margin:u,cells:c,numCells:d,calculatedImageSettings:h}}var Kfe=function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0}(),zfe=Fe.forwardRef(function(e,n){const r=e,{value:i,size:s=F4,level:a=$4,bgColor:o=V4,fgColor:l=G4,includeMargin:c=H4,minVersion:u=K4,boostLevel:d,marginSize:h,imageSettings:f}=r,m=nw(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:g}=m,b=nw(m,["style"]),v=f==null?void 0:f.src,S=Fe.useRef(null),E=Fe.useRef(null),L=Fe.useCallback(W=>{S.current=W,typeof n=="function"?n(W):n&&(n.current=W)},[n]),[U,O]=Fe.useState(!1),{margin:k,cells:I,numCells:R,calculatedImageSettings:M}=W4({value:i,level:a,minVersion:u,boostLevel:d,includeMargin:c,marginSize:h,imageSettings:f,size:s});Fe.useEffect(()=>{if(S.current!=null){const W=S.current,re=W.getContext("2d");if(!re)return;let X=I;const oe=E.current,Q=M!=null&&oe!==null&&oe.complete&&oe.naturalHeight!==0&&oe.naturalWidth!==0;Q&&M.excavation!=null&&(X=q4(I,M.excavation));const G=window.devicePixelRatio||1;W.height=W.width=s*G;const H=s/R*G;re.scale(H,H),re.fillStyle=o,re.fillRect(0,0,R,R),re.fillStyle=l,Kfe?re.fill(new Path2D(z4(X,k))):I.forEach(function(Y,ie){Y.forEach(function(Ce,Le){Ce&&re.fillRect(Le+k,ie+k,1,1)})}),M&&(re.globalAlpha=M.opacity),Q&&re.drawImage(oe,M.x+k,M.y+k,M.w,M.h)}}),Fe.useEffect(()=>{O(!1)},[v]);const z=tw({height:s,width:s},g);let Z=null;return v!=null&&(Z=Fe.createElement("img",{src:v,key:v,style:{display:"none"},onLoad:()=>{O(!0)},ref:E,crossOrigin:M==null?void 0:M.crossOrigin})),Fe.createElement(Fe.Fragment,null,Fe.createElement("canvas",tw({style:z,height:s,width:s,ref:L,role:"img"},b)),Z)});zfe.displayName="QRCodeCanvas";var Y4=Fe.forwardRef(function(e,n){const r=e,{value:i,size:s=F4,level:a=$4,bgColor:o=V4,fgColor:l=G4,includeMargin:c=H4,minVersion:u=K4,boostLevel:d,title:h,marginSize:f,imageSettings:p}=r,m=nw(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:g,cells:b,numCells:v,calculatedImageSettings:S}=W4({value:i,level:a,minVersion:u,boostLevel:d,includeMargin:c,marginSize:f,imageSettings:p,size:s});let E=b,L=null;p!=null&&S!=null&&(S.excavation!=null&&(E=q4(b,S.excavation)),L=Fe.createElement("image",{href:p.src,height:S.h,width:S.w,x:S.x+g,y:S.y+g,preserveAspectRatio:"none",opacity:S.opacity,crossOrigin:S.crossOrigin}));const U=z4(E,g);return Fe.createElement("svg",tw({height:s,width:s,viewBox:`0 0 ${v} ${v}`,ref:n,role:"img"},m),!!h&&Fe.createElement("title",null,h),Fe.createElement("path",{fill:o,d:`M0,0 h${v}v${v}H0z`,shapeRendering:"crispEdges"}),Fe.createElement("path",{fill:l,d:U,shapeRendering:"crispEdges"}),L)});Y4.displayName="QRCodeSVG";const Ru="",qfe=()=>{const[t,e]=D.useState(null),[n,r]=D.useState(!0),[i,s]=D.useState(!1),[a,o]=D.useState(null),l=qr(),{addProfile:c,setActiveProfileId:u}=mo();D.useEffect(()=>{const p=localStorage.getItem("nadiplay_device");if(p)try{const m=JSON.parse(p);e(m),r(!1);return}catch(m){console.warn("[DeviceActivation] parse stored device failed",m)}(async()=>{try{const m=await fetch(`${Ru}/api/device/register`,{method:"POST"});if(!m.ok)throw new Error("Registration failed");const g=await m.json(),b={device_id:g.device_id,mac_address:g.mac_address,pin:g.pin};localStorage.setItem("nadiplay_device",JSON.stringify(b)),e(b)}catch(m){Mt.error(m.message||"Failed to register device")}finally{r(!1)}})()},[]),D.useEffect(()=>{if(!t||i)return;let p=!1,m=0;const g=async()=>{try{const v=await fetch(`${Ru}/api/device/status/${t.device_id}`);if(v.status===404){if(m++,m>=3&&!p){localStorage.removeItem("nadiplay_device"),e(null),r(!0);try{const L=await(await fetch(`${Ru}/api/device/register`,{method:"POST"})).json(),U={device_id:L.device_id,mac_address:L.mac_address,pin:L.pin};localStorage.setItem("nadiplay_device",JSON.stringify(U)),e(U)}catch(E){console.warn("[DeviceActivation] re-register failed",E)}r(!1)}return}if(!v.ok)return;if(m=0,(await v.json()).paired&&!p){s(!0);const E=await fetch(`${Ru}/api/device/config/${t.device_id}`);if(E.ok){const L=await E.json(),U=c({name:L.profile_name||"Paired Device",kind:"xtream",serverUrl:L.server_url,username:L.username,password:L.password});u(U.id),Mt.success("Device paired! Loading channels..."),setTimeout(()=>l("/"),1500)}}}catch(v){console.warn("[DeviceActivation] poll error",v)}},b=setInterval(g,3e3);return g(),()=>{p=!0,clearInterval(b)}},[t,i,c,u,l]);const d=D.useCallback((p,m)=>{navigator.clipboard.writeText(p).then(()=>{o(m),Mt.success(`${m} copied`),setTimeout(()=>o(null),2e3)})},[]),h=D.useCallback(async()=>{if(t){try{await fetch(`${Ru}/api/device/unpair/${t.device_id}`,{method:"DELETE"})}catch(p){console.warn("[DeviceActivation] unpair failed",p)}localStorage.removeItem("nadiplay_device"),e(null),s(!1),r(!0);try{const m=await(await fetch(`${Ru}/api/device/register`,{method:"POST"})).json(),g={device_id:m.device_id,mac_address:m.mac_address,pin:m.pin};localStorage.setItem("nadiplay_device",JSON.stringify(g)),e(g),Mt.success("New device code generated")}catch{Mt.error("Failed to re-register")}finally{r(!1)}}},[t]),f=`${window.location.origin}/pair`;return n?y.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:y.jsx(yr,{className:"w-8 h-8 text-primary animate-spin"})}):i?y.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background px-4",children:y.jsxs($t.div,{initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1},className:"glass-card rounded-3xl p-10 text-center max-w-md",children:[y.jsx("div",{className:"w-16 h-16 rounded-full bg-primary/20 flex items-center justify-center mx-auto mb-4",children:y.jsx(Ol,{className:"w-8 h-8 text-primary"})}),y.jsx("h2",{className:"text-foreground text-xl font-semibold mb-2",children:"Device Paired!"}),y.jsx("p",{className:"text-muted-foreground text-sm",children:"Loading your IPTV profile..."})]})}):y.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-background px-4","data-testid":"device-activation-page",children:[y.jsx("div",{className:"absolute inset-0 bg-cover bg-center bg-no-repeat opacity-30",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),y.jsx("div",{className:"absolute inset-0 bg-background/60"}),y.jsxs($t.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"relative z-10 glass-card rounded-3xl p-8 w-full max-w-lg",children:[y.jsxs("div",{className:"flex flex-col items-center mb-6",children:[y.jsx("div",{className:"w-14 h-14 rounded-2xl glass flex items-center justify-center mb-3",children:y.jsx(xa,{className:"w-6 h-6 text-primary"})}),y.jsx("h1",{className:"font-display text-2xl tracking-[0.2em] gold-text",children:"NADIPLAYER"}),y.jsx("p",{className:"text-muted-foreground text-xs mt-1",children:"Device Activation"})]}),t&&y.jsxs("div",{className:"space-y-5",children:[y.jsx("div",{className:"flex justify-center",children:y.jsx("div",{className:"bg-white p-3 rounded-2xl",children:y.jsx(Y4,{value:`${f}?pin=${t.pin}`,size:160,level:"M","data-testid":"pairing-qr-code"})})}),y.jsxs("p",{className:"text-center text-muted-foreground text-[11px]",children:["Scan this QR code or visit ",y.jsx("span",{className:"text-primary",children:f})]}),y.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[y.jsx(xD,{label:"MAC Address",value:t.mac_address,onCopy:()=>d(t.mac_address,"MAC"),isCopied:a==="MAC"}),y.jsx(xD,{label:"Device ID",value:t.device_id,onCopy:()=>d(t.device_id,"Device ID"),isCopied:a==="Device ID"})]}),y.jsxs("div",{className:"glass rounded-2xl p-5 text-center","data-testid":"device-pin-display",children:[y.jsx("p",{className:"text-muted-foreground text-xs mb-2",children:"Your Pairing PIN"}),y.jsx("div",{className:"flex justify-center gap-2",children:t.pin.split("").map((p,m)=>y.jsx("span",{className:"w-11 h-14 flex items-center justify-center rounded-xl bg-primary/10 border border-primary/30 text-primary text-2xl font-bold font-mono",children:p},`pin-digit-${m}`))}),y.jsx("p",{className:"text-muted-foreground text-[10px] mt-3",children:"Enter this PIN on the web portal to link your account"})]}),y.jsxs("div",{className:"flex items-center justify-center gap-2 text-muted-foreground",children:[y.jsx(rz,{className:"w-4 h-4 animate-pulse text-primary"}),y.jsx("span",{className:"text-xs",children:"Waiting for pairing..."})]}),y.jsxs("div",{className:"flex gap-3",children:[y.jsxs("button",{onClick:()=>l("/pair"),className:"flex-1 py-2.5 rounded-xl glass hover:border-primary/40 text-foreground text-xs flex items-center justify-center gap-2 transition-all","data-testid":"open-pair-portal-btn",children:[y.jsx(Wy,{className:"w-3.5 h-3.5"})," Open Pair Portal"]}),y.jsxs("button",{onClick:h,className:"py-2.5 px-4 rounded-xl glass hover:border-primary/40 text-muted-foreground text-xs flex items-center justify-center gap-2 transition-all","data-testid":"reset-device-btn",children:[y.jsx(tm,{className:"w-3.5 h-3.5"})," Reset"]})]})]})]})]})},xD=({label:t,value:e,onCopy:n,isCopied:r})=>y.jsxs("div",{className:"flex items-center justify-between glass rounded-xl px-4 py-3",children:[y.jsxs("div",{children:[y.jsx("p",{className:"text-muted-foreground text-[10px]",children:t}),y.jsx("p",{className:"text-foreground text-sm font-mono tracking-wider",children:e})]}),y.jsx("button",{onClick:n,className:"w-8 h-8 rounded-lg glass flex items-center justify-center hover:border-primary/40 transition-all","data-testid":`copy-${t.toLowerCase().replace(/\s/g,"-")}-btn`,children:r?y.jsx(Ol,{className:"w-3.5 h-3.5 text-primary"}):y.jsx(tK,{className:"w-3.5 h-3.5 text-muted-foreground"})})]}),Wfe="",Yfe=()=>{const[t]=QM(),e=qr(),[n,r]=D.useState(t.get("pin")||""),[i,s]=D.useState(""),[a,o]=D.useState(""),[l,c]=D.useState(""),[u,d]=D.useState("My IPTV"),[h,f]=D.useState(!1),[p,m]=D.useState(!1),[g,b]=D.useState("");D.useEffect(()=>{if(!n){const S=document.getElementById("pin-input");S&&S.focus()}},[n]);const v=async S=>{S.preventDefault(),b("");const E=n.replace(/\s/g,"");if(E.length!==6||!/^\d+$/.test(E)){b("PIN must be exactly 6 digits");return}if(!i.trim()){b("Server URL is required");return}if(!a.trim()||!l.trim()){b("Username and password are required");return}f(!0);try{const L=await fetch(`${Wfe}/api/device/pair`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pin:E,server_url:i.trim(),username:a.trim(),password:l.trim(),profile_name:u.trim()||"My IPTV"})});if(!L.ok){const U=await L.json().catch(()=>({}));throw new Error(U.detail||`Pairing failed (${L.status})`)}m(!0),Mt.success("Device paired successfully!")}catch(L){b(L.message||"Pairing failed"),Mt.error(L.message||"Pairing failed")}finally{f(!1)}};return p?y.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-background px-4",children:[y.jsx("div",{className:"absolute inset-0 bg-cover bg-center bg-no-repeat opacity-30",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),y.jsx("div",{className:"absolute inset-0 bg-background/80"}),y.jsxs($t.div,{initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1},className:"relative z-10 glass-card rounded-3xl p-10 text-center max-w-md","data-testid":"pair-success-card",children:[y.jsx("div",{className:"w-16 h-16 rounded-full bg-primary/20 flex items-center justify-center mx-auto mb-4",children:y.jsx(Ol,{className:"w-8 h-8 text-primary"})}),y.jsx("h2",{className:"text-foreground text-xl font-semibold mb-2",children:"Paired!"}),y.jsx("p",{className:"text-muted-foreground text-sm mb-6",children:"Your TV app will load the IPTV profile automatically. You can close this page now."}),y.jsx("button",{onClick:()=>e("/"),className:"text-primary text-xs underline","data-testid":"go-home-btn",children:"Go to Home"})]})]}):y.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-background px-4","data-testid":"pair-portal-page",children:[y.jsx("div",{className:"absolute inset-0 bg-cover bg-center bg-no-repeat opacity-30",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),y.jsx("div",{className:"absolute inset-0 bg-background/60"}),y.jsxs($t.form,{onSubmit:v,initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"relative z-10 glass-card rounded-3xl p-8 w-full max-w-md",children:[y.jsxs("button",{type:"button",onClick:()=>e(-1),className:"flex items-center gap-1 text-muted-foreground text-xs mb-4 hover:text-foreground transition-colors","data-testid":"back-btn",children:[y.jsx(ev,{className:"w-3.5 h-3.5"})," Back"]}),y.jsxs("div",{className:"flex flex-col items-center mb-6",children:[y.jsx("div",{className:"w-14 h-14 rounded-2xl glass flex items-center justify-center mb-3",children:y.jsx(Wy,{className:"w-6 h-6 text-primary"})}),y.jsx("h1",{className:"font-display text-2xl tracking-[0.2em] gold-text",children:"PAIR DEVICE"}),y.jsx("p",{className:"text-muted-foreground text-xs mt-1",children:"Enter the PIN shown on your TV"})]}),y.jsxs("div",{className:"mb-5",children:[y.jsx("label",{className:"text-muted-foreground text-[11px] mb-1.5 block",children:"6-Digit PIN"}),y.jsx("input",{id:"pin-input",type:"text",inputMode:"numeric",maxLength:6,value:n,onChange:S=>r(S.target.value.replace(/\D/g,"").slice(0,6)),placeholder:"000000",className:"w-full text-center text-3xl font-mono tracking-[0.5em] glass-input rounded-xl px-4 py-4 text-foreground placeholder:text-muted-foreground/30 outline-none","data-testid":"pin-input"})]}),y.jsxs("div",{className:"space-y-3 mb-5",children:[y.jsx("p",{className:"text-muted-foreground text-[11px]",children:"IPTV Server Credentials"}),y.jsx(Pg,{icon:Rc,placeholder:"Profile Name (e.g. My IPTV)",value:u,onChange:d,testId:"profile-name-input"}),y.jsx(Pg,{icon:Cc,placeholder:"Server URL (http://...)",value:i,onChange:s,testId:"server-url-input"}),y.jsx(Pg,{icon:fo,placeholder:"Username",value:a,onChange:o,testId:"username-input"}),y.jsx(Pg,{icon:rv,placeholder:"Password",value:l,onChange:c,type:"password",testId:"password-input"})]}),g&&y.jsx("p",{className:"text-destructive text-xs text-center mb-3","data-testid":"pair-error",children:g}),y.jsxs("button",{type:"submit",disabled:h,className:"w-full py-3 rounded-xl bg-gradient-to-r from-primary/80 to-primary/60 text-primary-foreground font-medium text-sm hover:from-primary hover:to-primary/80 transition-all flex items-center justify-center gap-2 disabled:opacity-60","data-testid":"pair-submit-btn",children:[h&&y.jsx(yr,{className:"w-4 h-4 animate-spin"}),h?"Pairing...":"Pair Device"]}),y.jsx("p",{className:"text-center text-muted-foreground text-[10px] mt-4",children:"Your credentials are sent directly to the device and stored securely."})]})]})},Pg=({icon:t,placeholder:e,value:n,onChange:r,type:i="text",testId:s})=>y.jsxs("div",{className:"flex items-center gap-3 glass-input rounded-xl px-4 py-3",children:[y.jsx(t,{className:"w-4 h-4 text-muted-foreground shrink-0"}),y.jsx("input",{type:i,placeholder:e,value:n,onChange:a=>r(a.target.value),className:"flex-1 bg-transparent text-foreground placeholder:text-muted-foreground text-sm outline-none",autoComplete:"off","data-testid":s})]}),Xfe=()=>{const t=ba(),{t:e}=Wr();return D.useEffect(()=>{console.error("404 Error: User attempted to access non-existent route:",t.pathname)},[t.pathname]),y.jsx("div",{className:"flex min-h-screen items-center justify-center bg-muted",children:y.jsxs("div",{className:"text-center",children:[y.jsx("h1",{className:"mb-4 text-4xl font-bold",children:e("notFound.title")}),y.jsx("p",{className:"mb-4 text-xl text-muted-foreground",children:e("notFound.message")}),y.jsx("a",{href:"/",className:"text-primary underline hover:text-primary/90",children:e("notFound.goHome")})]})})},Qfe="Nadiplayer respects your privacy. This app is a media player that plays streams from playlists you provide. We do not collect, store, or share any personal data. Playlists are stored locally on your device only.",Jfe=()=>{const t=qr(),[e,n]=D.useState(Qfe),[r,i]=D.useState(!0);return D.useEffect(()=>{let s=!1;return a1().then(a=>{s||a.privacy_policy_text&&a.privacy_policy_text.trim().length&&n(a.privacy_policy_text)}).catch(()=>{}).finally(()=>{s||i(!1)}),()=>{s=!0}},[]),y.jsxs("div",{className:"min-h-screen w-full bg-background","data-testid":"privacy-screen",children:[y.jsxs("header",{className:"sticky top-0 z-20 flex items-center gap-2 border-b border-border/60 bg-background/90 px-3 py-3 backdrop-blur-xl",children:[y.jsx("button",{onClick:()=>t(-1),className:"flex h-9 w-9 items-center justify-center rounded-full border border-border/70 bg-card/60 text-foreground transition hover:bg-muted","data-testid":"privacy-back","aria-label":"Back",children:y.jsx(ev,{className:"h-4 w-4"})}),y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx(ap,{className:"h-4 w-4 text-primary"}),y.jsx("span",{className:"text-sm font-semibold tracking-wide text-foreground",children:"Privacy Policy"})]})]}),y.jsx($t.main,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.35,ease:"easeOut"},className:"mx-auto max-w-2xl px-4 py-6 pb-28",children:y.jsxs("div",{className:"rounded-2xl border border-border/70 bg-card/70 p-5 shadow-xl backdrop-blur",children:[y.jsx("h1",{className:"text-xl font-bold text-foreground",children:"Privacy Policy"}),r?y.jsxs("div",{className:"mt-6 flex items-center gap-2 text-xs text-muted-foreground",children:[y.jsx(yr,{className:"h-3.5 w-3.5 animate-spin"})," Loading…"]}):y.jsx("pre",{className:"mt-4 whitespace-pre-wrap break-words font-sans text-sm leading-relaxed text-muted-foreground","data-testid":"privacy-text",children:e})]})})]})},Zfe=[{key:"home",label:"Home",route:"/",icon:dK},{key:"live",label:"Live TV",route:"/live-tv",icon:xa},{key:"movies",label:"Movies",route:"/movies",icon:xT},{key:"series",label:"Series",route:"/series",icon:nv},{key:"account",label:"Account",route:"/account",icon:fo}],epe=new Set(["/","/live-tv","/movies","/series","/account"]),tpe=()=>{const t=ba(),e=qr();return epe.has(t.pathname)?y.jsx("nav",{className:"fixed bottom-0 left-0 right-0 z-40 border-t border-border/60 bg-background/85 backdrop-blur-xl",style:{paddingBottom:"env(safe-area-inset-bottom, 0px)"},"data-testid":"bottom-nav",children:y.jsx(Rl,{focusKey:"bottom-nav",className:"flex items-stretch justify-around px-1 py-1.5",children:Zfe.map(n=>{const r=t.pathname===n.route,i=n.icon;return y.jsxs(Cv,{focusKey:`nav-${n.key}`,onEnter:()=>e(n.route),onClick:()=>e(n.route),subtle:!0,"data-testid":`nav-${n.key}`,className:`flex flex-1 flex-col items-center gap-0.5 rounded-lg py-1.5 transition-colors border-transparent ${r?"text-primary":"text-muted-foreground hover:text-foreground"}`,focusClassName:"!border-primary/50",children:[y.jsx(i,{className:`h-5 w-5 ${r?"":"opacity-80"}`,strokeWidth:r?2.2:1.8}),y.jsx("span",{className:"text-[10px] font-medium tracking-wide",children:n.label})]},n.key)})})}):null},SD=cm("App",{web:()=>Mj(()=>import("./web-DJJwMr32.js"),[]).then(t=>new t.AppWeb)});function X4(){var t,e;return typeof window>"u"?"web":window.webOS?"webos":window.tizen?"tizen":(e=(t=window.Capacitor)==null?void 0:t.isNativePlatform)!=null&&e.call(t)?"capacitor":"web"}function npe(){const t=X4();return t==="webos"||t==="tizen"}function rpe(){const t=window.webOS;t!=null&&t.platformBack&&t.platformBack()}function ipe(){var e;const t=window.tizen;if((e=t==null?void 0:t.application)!=null&&e.getCurrentApplication)try{t.application.getCurrentApplication().exit()}catch(n){console.warn("Tizen exit failed:",n)}}const spe=()=>{const t=qr(),e=ba(),r=["/","/welcome","/login","/admin"].includes(e.pathname),i=s=>{if(r||!s){switch(X4()){case"webos":rpe();break;case"tizen":ipe();break;case"capacitor":SD.exitApp();break;default:window.close()}return}t(-1)};return D.useEffect(()=>{if(!um())return;let s=null;return(async()=>{const a=await SD.addListener("backButton",({canGoBack:o})=>{i(o)});s=()=>a.remove()})(),()=>{s&&s()}},[t,e.pathname]),D.useEffect(()=>{if(!npe())return;const s=o=>{(o.keyCode===10009||o.keyCode===461||o.key==="Escape")&&(o.preventDefault(),o.stopPropagation(),i(window.history.length>1))},a=window.tizen;if(a!=null&&a.tvinputdevice)try{a.tvinputdevice.registerKey("MediaPlayPause"),a.tvinputdevice.registerKey("MediaPlay"),a.tvinputdevice.registerKey("MediaPause"),a.tvinputdevice.registerKey("MediaStop"),a.tvinputdevice.registerKey("MediaRewind"),a.tvinputdevice.registerKey("MediaFastForward")}catch(o){console.warn("Failed to register Tizen keys:",o)}return document.addEventListener("keydown",s,!0),()=>{document.removeEventListener("keydown",s,!0)}},[t,e.pathname]),null},ox=cm("ApkInstaller");function lx(){return Tl.isNativePlatform()&&Tl.getPlatform()==="android"}const ape=()=>{var S;const{info:t,hasUpdate:e,forced:n,installedVersion:r}=B4(),[i,s]=D.useState(!1),[a,o]=D.useState({phase:"idle"}),l=D.useRef(null);if(D.useEffect(()=>{var E;(E=t==null?void 0:t.update)!=null&&E.latest_version&&s(Ofe(t.update.latest_version))},[(S=t==null?void 0:t.update)==null?void 0:S.latest_version]),D.useEffect(()=>{if(!lx())return;let E=!0;return ox.addListener("downloadProgress",({loaded:L,total:U,percent:O})=>{E&&o(k=>k.phase==="downloading"?{phase:"downloading",percent:O,loaded:L,total:U}:k)}).then(L=>{l.current=L}),()=>{var L;E=!1,(L=l.current)==null||L.remove(),l.current=null}},[]),!t||!e||!n&&i)return null;const c=t.update,u=c.apk_url||"",d=c.play_url||"",h=u||d,f=()=>{n||a.phase==="downloading"||a.phase==="installing"||(Dfe(c.latest_version),s(!0))},p=E=>{E&&window.open(E,"_blank","noopener,noreferrer")},m=async()=>{if(lx()&&u){try{o({phase:"downloading",percent:0,loaded:0,total:0});const{path:E}=await ox.downloadApk({url:u,fileName:`nadiplayer-${c.latest_version}.apk`});o({phase:"installing"});const L=await ox.installApk({path:E});if(!L.launched&&L.reason==="needs-install-permission"){o({phase:"needs-permission"});return}o({phase:"done"})}catch(E){o({phase:"error",message:E instanceof Error?E.message:"Update failed"})}return}p(h)},g=(()=>{switch(a.phase){case"downloading":return`Downloading ${a.percent>=0?`${a.percent}%`:""}…`;case"installing":return"Opening installer…";case"needs-permission":return"Allow install — try again";case"done":return"Installer launched";case"error":return"Retry update";default:return lx()&&u?"Update now":"Download update"}})(),b=a.phase==="downloading"||a.phase==="installing",v=()=>{if(a.phase!=="downloading")return null;const E=a.percent>=0?Math.max(0,Math.min(100,a.percent)):null;return y.jsx("div",{className:"mt-2 h-1.5 w-full overflow-hidden rounded-full bg-muted","data-testid":"update-popup-progress",children:y.jsx("div",{className:"h-full bg-primary transition-[width] duration-150",style:{width:E===null?"30%":`${E}%`}})})};return y.jsx(bh,{children:y.jsx($t.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.25},className:"fixed inset-0 z-[9999] flex items-center justify-center bg-black/80 backdrop-blur-md p-4","data-testid":"update-popup-backdrop",onClick:E=>{E.target===E.currentTarget&&f()},children:y.jsxs($t.div,{initial:{opacity:0,scale:.92,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.92,y:20},transition:{duration:.3,ease:"easeOut"},className:"relative w-full max-w-md overflow-hidden rounded-3xl border border-primary/30 bg-card/95 p-6 shadow-2xl backdrop-blur-xl","data-testid":"update-popup",children:[!n&&!b&&y.jsx("button",{onClick:f,"data-testid":"update-popup-close",className:"absolute right-3 top-3 flex h-8 w-8 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground","aria-label":"Close update notice",children:y.jsx(Sa,{className:"h-4 w-4"})}),y.jsxs("div",{className:"mb-4 flex items-start gap-3",children:[y.jsx("div",{className:`flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl border ${n?"border-amber-500/50 bg-amber-500/10 text-amber-400":"border-primary/40 bg-primary/10 text-primary"}`,children:n?y.jsx(JK,{className:"h-6 w-6"}):y.jsx(L2,{className:"h-6 w-6"})}),y.jsxs("div",{className:"min-w-0 flex-1",children:[y.jsx("h2",{className:"text-lg font-semibold tracking-tight text-foreground","data-testid":"update-popup-title",children:n?"Update required":"New update available"}),y.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[y.jsxs("span",{"data-testid":"update-popup-current",children:["v",r]}),"  →  ",y.jsxs("span",{className:"font-medium text-foreground","data-testid":"update-popup-latest",children:["v",c.latest_version]})]})]})]}),n&&y.jsx("div",{className:"mb-4 rounded-xl border border-amber-500/40 bg-amber-500/5 px-3 py-2 text-[11px] leading-relaxed text-amber-300","data-testid":"update-popup-forced-notice",children:"You must install the latest version to keep using the app."}),a.phase==="needs-permission"&&y.jsxs("div",{className:"mb-3 rounded-xl border border-amber-500/40 bg-amber-500/5 px-3 py-2 text-[11px] leading-relaxed text-amber-300","data-testid":"update-popup-need-permission",children:["Please enable ",y.jsx("strong",{children:'"Allow install from this source"'})," ","for Nadiplayer in the screen we just opened, then come back and tap the button again."]}),a.phase==="error"&&y.jsx("div",{className:"mb-3 rounded-xl border border-destructive/40 bg-destructive/5 px-3 py-2 text-[11px] leading-relaxed text-destructive","data-testid":"update-popup-error",children:a.message}),a.phase==="done"&&y.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-xl border border-primary/40 bg-primary/10 px-3 py-2 text-[11px] leading-relaxed text-primary","data-testid":"update-popup-done",children:[y.jsx(qH,{className:"h-4 w-4"}),"Installer opened. Follow the on-screen prompt to install."]}),c.changelog&&y.jsxs("div",{className:"mb-5 max-h-56 overflow-y-auto rounded-xl border border-border/60 bg-background/40 px-3 py-2.5",children:[y.jsx("p",{className:"mb-1 text-[10px] font-medium uppercase tracking-[0.2em] text-muted-foreground",children:"What's new"}),y.jsx("pre",{className:"whitespace-pre-wrap break-words font-sans text-xs leading-relaxed text-foreground/90","data-testid":"update-popup-changelog",children:c.changelog})]}),y.jsxs("div",{className:"flex flex-col gap-2",children:[h?y.jsxs("button",{onClick:m,disabled:b,"data-testid":"update-popup-download-btn",className:"flex w-full items-center justify-center gap-2 rounded-xl bg-primary px-4 py-3 text-sm font-semibold text-primary-foreground shadow-lg shadow-primary/30 transition hover:brightness-110 active:scale-[0.98] disabled:opacity-70",children:[a.phase==="downloading"||a.phase==="installing"?y.jsx(yr,{className:"h-4 w-4 animate-spin"}):y.jsx(_T,{className:"h-4 w-4"}),g]}):y.jsx("p",{className:"rounded-xl border border-destructive/40 bg-destructive/10 px-3 py-2 text-center text-xs text-destructive","data-testid":"update-popup-no-url",children:"No download link configured. Contact the admin."}),v(),d&&u&&y.jsxs("button",{onClick:()=>p(d),disabled:b,"data-testid":"update-popup-play-btn",className:"flex w-full items-center justify-center gap-2 rounded-xl border border-border/60 bg-muted/40 px-4 py-2.5 text-xs font-medium text-foreground transition hover:border-primary/40 disabled:opacity-50",children:[y.jsx(no,{className:"h-3.5 w-3.5"}),"Open in Play Store"]}),!n&&!b&&y.jsx("button",{onClick:f,"data-testid":"update-popup-later-btn",className:"w-full rounded-xl px-4 py-2 text-xs text-muted-foreground transition-colors hover:text-foreground",children:"Later"})]})]},"update-card")},"update-backdrop")})},ope=new MV,lpe="nadiplay_splash_shown",qh=({children:t})=>{const{user:e,isGuest:n,loading:r}=Bs(),i=ba();return r?null:!e&&!n?y.jsx(qy,{to:"/welcome",replace:!0,state:{from:i.pathname}}):(e==null?void 0:e.role)==="admin"&&i.pathname==="/"?y.jsx(qy,{to:"/admin",replace:!0}):y.jsx(y.Fragment,{children:t})},cpe=({children:t})=>{const{user:e,loading:n}=Bs();return n?null:e?e.role!=="admin"?y.jsx(qy,{to:"/",replace:!0}):y.jsx(y.Fragment,{children:t}):y.jsx(qy,{to:"/login",replace:!0})},upe=()=>{const{user:t}=Bs();return ene(t?{id:t.id,role:t.role}:null),rne(),y.jsxs(F6,{children:[y.jsx(fi,{path:"/welcome",element:y.jsx(tle,{})}),y.jsx(fi,{path:"/login",element:y.jsx(nle,{})}),y.jsx(fi,{path:"/connect",element:y.jsx(ole,{})}),y.jsx(fi,{path:"/admin",element:y.jsx(cpe,{children:y.jsx(rle,{})})}),y.jsx(fi,{path:"/",element:y.jsx(qh,{children:y.jsx(hle,{})})}),y.jsx(fi,{path:"/live-tv",element:y.jsx(qh,{children:y.jsx(Rfe,{})})}),y.jsx(fi,{path:"/movies",element:y.jsx(qh,{children:y.jsx(Cfe,{})})}),y.jsx(fi,{path:"/series",element:y.jsx(qh,{children:y.jsx(Lfe,{})})}),y.jsx(fi,{path:"/account",element:y.jsx(qh,{children:y.jsx(Bfe,{})})}),y.jsx(fi,{path:"/activate",element:y.jsx(qfe,{})}),y.jsx(fi,{path:"/pair",element:y.jsx(Yfe,{})}),y.jsx(fi,{path:"/privacy",element:y.jsx(Jfe,{})}),y.jsx(fi,{path:"*",element:y.jsx(Xfe,{})})]})},dpe=()=>{const[t,e]=D.useState(()=>{if(typeof window>"u")return!1;try{return sessionStorage.getItem(lpe)!=="1"}catch{return!0}});return y.jsx(BV,{client:ope,children:y.jsx(Eq,{children:y.jsx(gae,{children:y.jsxs(tne,{children:[t&&y.jsx(vJ,{onFinish:()=>e(!1)}),y.jsx(Fz,{}),y.jsx(LG,{}),y.jsxs(W6,{children:[y.jsx(spe,{}),y.jsx(upe,{}),y.jsx(tpe,{}),!t&&y.jsx(ape,{})]})]})})})})};class hpe extends Fe.Component{constructor(){super(...arguments);Cm(this,"state",{error:null});Cm(this,"reset",()=>this.setState({error:null}))}static getDerivedStateFromError(n){return{error:n}}componentDidCatch(n,r){console.error("[ErrorBoundary]",n,r)}render(){return this.state.error?y.jsx("div",{className:"min-h-screen flex items-center justify-center p-6 bg-background",children:y.jsxs("div",{className:"glass-card rounded-2xl p-6 max-w-md text-center",children:[y.jsx("p",{className:"text-foreground text-sm font-medium mb-2",children:"Something went wrong rendering this page."}),y.jsx("p",{className:"text-muted-foreground text-[11px] break-all mb-4",children:this.state.error.message}),y.jsx("button",{onClick:this.reset,className:"bg-primary/90 hover:bg-primary text-primary-foreground px-5 py-2 rounded-full text-sm",children:"Try again"}),y.jsx("p",{className:"text-muted-foreground text-[10px] mt-3",children:"(This error is contained — your current stream keeps playing.)"})]})}):this.props.children}}uV.createRoot(document.getElementById("root")).render(y.jsx(hpe,{children:y.jsx(dpe,{})}));export{kj as W};
