var U$=Object.defineProperty;var oR=t=>{throw TypeError(t)};var B$=(t,e,n)=>e in t?U$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var qm=(t,e,n)=>B$(t,typeof e!="symbol"?e+"":e,n),C_=(t,e,n)=>e.has(t)||oR("Cannot "+n);var ue=(t,e,n)=>(C_(t,e,"read from private field"),n?n.call(t):e.get(t)),_t=(t,e,n)=>e.has(t)?oR("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),nt=(t,e,n,r)=>(C_(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),Qt=(t,e,n)=>(C_(t,e,"access private method"),n);var Wm=(t,e,n,r)=>({set _(s){nt(t,e,s,n)},get _(){return ue(t,e,r)}});function F$(t,e){for(var n=0;n<e.length;n++){const r=e[n];if(typeof r!="string"&&!Array.isArray(r)){for(const s in r)if(s!=="default"&&!(s in t)){const i=Object.getOwnPropertyDescriptor(r,s);i&&Object.defineProperty(t,s,i.get?i:{enumerable:!0,get:()=>r[s]})}}}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 s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();var lR=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function tv(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var FO={exports:{}},nv={};/**
 * @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 $$=Symbol.for("react.transitional.element"),V$=Symbol.for("react.fragment");function $O(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 s in e)s!=="key"&&(n[s]=e[s])}else n=e;return e=n.ref,{$$typeof:$$,type:t,key:r,ref:e!==void 0?e:null,props:n}}nv.Fragment=V$;nv.jsx=$O;nv.jsxs=$O;FO.exports=nv;var p=FO.exports,VO={exports:{}},rv={},GO={exports:{}},KO={};/**
 * @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(Z,oe){var ne=Z.length;Z.push(oe);e:for(;0<ne;){var H=ne-1>>>1,K=Z[H];if(0<s(K,oe))Z[H]=oe,Z[ne]=K,ne=H;else break e}}function n(Z){return Z.length===0?null:Z[0]}function r(Z){if(Z.length===0)return null;var oe=Z[0],ne=Z.pop();if(ne!==oe){Z[0]=ne;e:for(var H=0,K=Z.length,J=K>>>1;H<J;){var Q=2*(H+1)-1,ve=Z[Q],Te=Q+1,Ne=Z[Te];if(0>s(ve,ne))Te<K&&0>s(Ne,ve)?(Z[H]=Ne,Z[Te]=ne,H=Te):(Z[H]=ve,Z[Q]=ne,H=Q);else if(Te<K&&0>s(Ne,ne))Z[H]=Ne,Z[Te]=ne,H=Te;else break e}}return oe}function s(Z,oe){var ne=Z.sortIndex-oe.sortIndex;return ne!==0?ne:Z.id-oe.id}if(t.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var i=performance;t.unstable_now=function(){return i.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,m=!1,g=!1,y=!1,v=typeof setTimeout=="function"?setTimeout:null,_=typeof clearTimeout=="function"?clearTimeout:null,S=typeof setImmediate<"u"?setImmediate:null;function E(Z){for(var oe=n(c);oe!==null;){if(oe.callback===null)r(c);else if(oe.startTime<=Z)r(c),oe.sortIndex=oe.expirationTime,e(l,oe);else break;oe=n(c)}}function L(Z){if(g=!1,E(Z),!m)if(n(l)!==null)m=!0,U||(U=!0,G());else{var oe=n(c);oe!==null&&X(L,oe.startTime-Z)}}var U=!1,P=-1,I=5,k=-1;function R(){return y?!0:!(t.unstable_now()-k<I)}function M(){if(y=!1,U){var Z=t.unstable_now();k=Z;var oe=!0;try{e:{m=!1,g&&(g=!1,_(P),P=-1),f=!0;var ne=h;try{t:{for(E(Z),d=n(l);d!==null&&!(d.expirationTime>Z&&R());){var H=d.callback;if(typeof H=="function"){d.callback=null,h=d.priorityLevel;var K=H(d.expirationTime<=Z);if(Z=t.unstable_now(),typeof K=="function"){d.callback=K,E(Z),oe=!0;break t}d===n(l)&&r(l),E(Z)}else r(l);d=n(l)}if(d!==null)oe=!0;else{var J=n(c);J!==null&&X(L,J.startTime-Z),oe=!1}}break e}finally{d=null,h=ne,f=!1}oe=void 0}}finally{oe?G():U=!1}}}var G;if(typeof S=="function")G=function(){S(M)};else if(typeof MessageChannel<"u"){var Y=new MessageChannel,q=Y.port2;Y.port1.onmessage=M,G=function(){q.postMessage(null)}}else G=function(){v(M,0)};function X(Z,oe){P=v(function(){Z(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(Z){Z.callback=null},t.unstable_forceFrameRate=function(Z){0>Z||125<Z?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):I=0<Z?Math.floor(1e3/Z):5},t.unstable_getCurrentPriorityLevel=function(){return h},t.unstable_next=function(Z){switch(h){case 1:case 2:case 3:var oe=3;break;default:oe=h}var ne=h;h=oe;try{return Z()}finally{h=ne}},t.unstable_requestPaint=function(){y=!0},t.unstable_runWithPriority=function(Z,oe){switch(Z){case 1:case 2:case 3:case 4:case 5:break;default:Z=3}var ne=h;h=Z;try{return oe()}finally{h=ne}},t.unstable_scheduleCallback=function(Z,oe,ne){var H=t.unstable_now();switch(typeof ne=="object"&&ne!==null?(ne=ne.delay,ne=typeof ne=="number"&&0<ne?H+ne:H):ne=H,Z){case 1:var K=-1;break;case 2:K=250;break;case 5:K=1073741823;break;case 4:K=1e4;break;default:K=5e3}return K=ne+K,Z={id:u++,callback:oe,priorityLevel:Z,startTime:ne,expirationTime:K,sortIndex:-1},ne>H?(Z.sortIndex=ne,e(c,Z),n(l)===null&&Z===n(c)&&(g?(_(P),P=-1):g=!0,X(L,ne-H))):(Z.sortIndex=K,e(l,Z),m||f||(m=!0,U||(U=!0,G()))),Z},t.unstable_shouldYield=R,t.unstable_wrapCallback=function(Z){var oe=h;return function(){var ne=h;h=oe;try{return Z.apply(this,arguments)}finally{h=ne}}}})(KO);GO.exports=KO;var G$=GO.exports,HO={exports:{}},Bt={};/**
 * @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 zw=Symbol.for("react.transitional.element"),K$=Symbol.for("react.portal"),H$=Symbol.for("react.fragment"),z$=Symbol.for("react.strict_mode"),q$=Symbol.for("react.profiler"),W$=Symbol.for("react.consumer"),Y$=Symbol.for("react.context"),X$=Symbol.for("react.forward_ref"),Q$=Symbol.for("react.suspense"),J$=Symbol.for("react.memo"),zO=Symbol.for("react.lazy"),cR=Symbol.iterator;function Z$(t){return t===null||typeof t!="object"?null:(t=cR&&t[cR]||t["@@iterator"],typeof t=="function"?t:null)}var qO={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},WO=Object.assign,YO={};function Sh(t,e,n){this.props=t,this.context=e,this.refs=YO,this.updater=n||qO}Sh.prototype.isReactComponent={};Sh.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")};Sh.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function XO(){}XO.prototype=Sh.prototype;function qw(t,e,n){this.props=t,this.context=e,this.refs=YO,this.updater=n||qO}var Ww=qw.prototype=new XO;Ww.constructor=qw;WO(Ww,Sh.prototype);Ww.isPureReactComponent=!0;var uR=Array.isArray,Bn={H:null,A:null,T:null,S:null,V:null},QO=Object.prototype.hasOwnProperty;function Yw(t,e,n,r,s,i){return n=i.ref,{$$typeof:zw,type:t,key:e,ref:n!==void 0?n:null,props:i}}function e8(t,e){return Yw(t.type,e,void 0,void 0,void 0,t.props)}function Xw(t){return typeof t=="object"&&t!==null&&t.$$typeof===zw}function t8(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(n){return e[n]})}var dR=/\/+/g;function k_(t,e){return typeof t=="object"&&t!==null&&t.key!=null?t8(""+t.key):e.toString(36)}function hR(){}function n8(t){switch(t.status){case"fulfilled":return t.value;case"rejected":throw t.reason;default:switch(typeof t.status=="string"?t.then(hR,hR):(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 zu(t,e,n,r,s){var i=typeof t;(i==="undefined"||i==="boolean")&&(t=null);var a=!1;if(t===null)a=!0;else switch(i){case"bigint":case"string":case"number":a=!0;break;case"object":switch(t.$$typeof){case zw:case K$:a=!0;break;case zO:return a=t._init,zu(a(t._payload),e,n,r,s)}}if(a)return s=s(t),a=r===""?"."+k_(t,0):r,uR(s)?(n="",a!=null&&(n=a.replace(dR,"$&/")+"/"),zu(s,e,n,"",function(c){return c})):s!=null&&(Xw(s)&&(s=e8(s,n+(s.key==null||t&&t.key===s.key?"":(""+s.key).replace(dR,"$&/")+"/")+a)),e.push(s)),1;a=0;var o=r===""?".":r+":";if(uR(t))for(var l=0;l<t.length;l++)r=t[l],i=o+k_(r,l),a+=zu(r,e,n,i,s);else if(l=Z$(t),typeof l=="function")for(t=l.call(t),l=0;!(r=t.next()).done;)r=r.value,i=o+k_(r,l++),a+=zu(r,e,n,i,s);else if(i==="object"){if(typeof t.then=="function")return zu(n8(t),e,n,r,s);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 Ym(t,e,n){if(t==null)return t;var r=[],s=0;return zu(t,r,"","",function(i){return e.call(n,i,s++)}),r}function r8(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 fR=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 s8(){}Bt.Children={map:Ym,forEach:function(t,e,n){Ym(t,function(){e.apply(this,arguments)},n)},count:function(t){var e=0;return Ym(t,function(){e++}),e},toArray:function(t){return Ym(t,function(e){return e})||[]},only:function(t){if(!Xw(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};Bt.Component=Sh;Bt.Fragment=H$;Bt.Profiler=q$;Bt.PureComponent=qw;Bt.StrictMode=z$;Bt.Suspense=Q$;Bt.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=Bn;Bt.__COMPILER_RUNTIME={__proto__:null,c:function(t){return Bn.H.useMemoCache(t)}};Bt.cache=function(t){return function(){return t.apply(null,arguments)}};Bt.cloneElement=function(t,e,n){if(t==null)throw Error("The argument must be a React element, but you passed "+t+".");var r=WO({},t.props),s=t.key,i=void 0;if(e!=null)for(a in e.ref!==void 0&&(i=void 0),e.key!==void 0&&(s=""+e.key),e)!QO.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 Yw(t.type,s,void 0,void 0,i,r)};Bt.createContext=function(t){return t={$$typeof:Y$,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null},t.Provider=t,t.Consumer={$$typeof:W$,_context:t},t};Bt.createElement=function(t,e,n){var r,s={},i=null;if(e!=null)for(r in e.key!==void 0&&(i=""+e.key),e)QO.call(e,r)&&r!=="key"&&r!=="__self"&&r!=="__source"&&(s[r]=e[r]);var a=arguments.length-2;if(a===1)s.children=n;else if(1<a){for(var o=Array(a),l=0;l<a;l++)o[l]=arguments[l+2];s.children=o}if(t&&t.defaultProps)for(r in a=t.defaultProps,a)s[r]===void 0&&(s[r]=a[r]);return Yw(t,i,void 0,void 0,null,s)};Bt.createRef=function(){return{current:null}};Bt.forwardRef=function(t){return{$$typeof:X$,render:t}};Bt.isValidElement=Xw;Bt.lazy=function(t){return{$$typeof:zO,_payload:{_status:-1,_result:t},_init:r8}};Bt.memo=function(t,e){return{$$typeof:J$,type:t,compare:e===void 0?null:e}};Bt.startTransition=function(t){var e=Bn.T,n={};Bn.T=n;try{var r=t(),s=Bn.S;s!==null&&s(n,r),typeof r=="object"&&r!==null&&typeof r.then=="function"&&r.then(s8,fR)}catch(i){fR(i)}finally{Bn.T=e}};Bt.unstable_useCacheRefresh=function(){return Bn.H.useCacheRefresh()};Bt.use=function(t){return Bn.H.use(t)};Bt.useActionState=function(t,e,n){return Bn.H.useActionState(t,e,n)};Bt.useCallback=function(t,e){return Bn.H.useCallback(t,e)};Bt.useContext=function(t){return Bn.H.useContext(t)};Bt.useDebugValue=function(){};Bt.useDeferredValue=function(t,e){return Bn.H.useDeferredValue(t,e)};Bt.useEffect=function(t,e,n){var r=Bn.H;if(typeof n=="function")throw Error("useEffect CRUD overload is not enabled in this build of React.");return r.useEffect(t,e)};Bt.useId=function(){return Bn.H.useId()};Bt.useImperativeHandle=function(t,e,n){return Bn.H.useImperativeHandle(t,e,n)};Bt.useInsertionEffect=function(t,e){return Bn.H.useInsertionEffect(t,e)};Bt.useLayoutEffect=function(t,e){return Bn.H.useLayoutEffect(t,e)};Bt.useMemo=function(t,e){return Bn.H.useMemo(t,e)};Bt.useOptimistic=function(t,e){return Bn.H.useOptimistic(t,e)};Bt.useReducer=function(t,e,n){return Bn.H.useReducer(t,e,n)};Bt.useRef=function(t){return Bn.H.useRef(t)};Bt.useState=function(t){return Bn.H.useState(t)};Bt.useSyncExternalStore=function(t,e,n){return Bn.H.useSyncExternalStore(t,e,n)};Bt.useTransition=function(){return Bn.H.useTransition()};Bt.version="19.1.0";HO.exports=Bt;var C=HO.exports;const Be=tv(C),Qw=F$({__proto__:null,default:Be},[C]);var JO={exports:{}},ms={};/**
 * @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 i8=C;function ZO(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 Uo(){}var cs={d:{f:Uo,r:function(){throw Error(ZO(522))},D:Uo,C:Uo,L:Uo,m:Uo,X:Uo,S:Uo,M:Uo},p:0,findDOMNode:null},a8=Symbol.for("react.portal");function o8(t,e,n){var r=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:a8,key:r==null?null:""+r,children:t,containerInfo:e,implementation:n}}var Rf=i8.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function sv(t,e){if(t==="font")return"";if(typeof e=="string")return e==="use-credentials"?e:""}ms.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=cs;ms.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(ZO(299));return o8(t,e,null,n)};ms.flushSync=function(t){var e=Rf.T,n=cs.p;try{if(Rf.T=null,cs.p=2,t)return t()}finally{Rf.T=e,cs.p=n,cs.d.f()}};ms.preconnect=function(t,e){typeof t=="string"&&(e?(e=e.crossOrigin,e=typeof e=="string"?e==="use-credentials"?e:"":void 0):e=null,cs.d.C(t,e))};ms.prefetchDNS=function(t){typeof t=="string"&&cs.d.D(t)};ms.preinit=function(t,e){if(typeof t=="string"&&e&&typeof e.as=="string"){var n=e.as,r=sv(n,e.crossOrigin),s=typeof e.integrity=="string"?e.integrity:void 0,i=typeof e.fetchPriority=="string"?e.fetchPriority:void 0;n==="style"?cs.d.S(t,typeof e.precedence=="string"?e.precedence:void 0,{crossOrigin:r,integrity:s,fetchPriority:i}):n==="script"&&cs.d.X(t,{crossOrigin:r,integrity:s,fetchPriority:i,nonce:typeof e.nonce=="string"?e.nonce:void 0})}};ms.preinitModule=function(t,e){if(typeof t=="string")if(typeof e=="object"&&e!==null){if(e.as==null||e.as==="script"){var n=sv(e.as,e.crossOrigin);cs.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&&cs.d.M(t)};ms.preload=function(t,e){if(typeof t=="string"&&typeof e=="object"&&e!==null&&typeof e.as=="string"){var n=e.as,r=sv(n,e.crossOrigin);cs.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})}};ms.preloadModule=function(t,e){if(typeof t=="string")if(e){var n=sv(e.as,e.crossOrigin);cs.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 cs.d.m(t)};ms.requestFormReset=function(t){cs.d.r(t)};ms.unstable_batchedUpdates=function(t,e){return t(e)};ms.useFormState=function(t,e,n){return Rf.H.useFormState(t,e,n)};ms.useFormStatus=function(){return Rf.H.useHostTransitionStatus()};ms.version="19.1.0";function eN(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(eN)}catch(t){console.error(t)}}eN(),JO.exports=ms;var Zp=JO.exports;const tN=tv(Zp);/**
 * @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 Er=G$,nN=C,l8=Zp;function je(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 rN(t){return!(!t||t.nodeType!==1&&t.nodeType!==9&&t.nodeType!==11)}function em(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 sN(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 pR(t){if(em(t)!==t)throw Error(je(188))}function c8(t){var e=t.alternate;if(!e){if(e=em(t),e===null)throw Error(je(188));return e!==t?null:t}for(var n=t,r=e;;){var s=n.return;if(s===null)break;var i=s.alternate;if(i===null){if(r=s.return,r!==null){n=r;continue}break}if(s.child===i.child){for(i=s.child;i;){if(i===n)return pR(s),t;if(i===r)return pR(s),e;i=i.sibling}throw Error(je(188))}if(n.return!==r.return)n=s,r=i;else{for(var a=!1,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){for(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)throw Error(je(189))}}if(n.alternate!==r)throw Error(je(190))}if(n.tag!==3)throw Error(je(188));return n.stateNode.current===n?t:e}function iN(t){var e=t.tag;if(e===5||e===26||e===27||e===6)return t;for(t=t.child;t!==null;){if(e=iN(t),e!==null)return e;t=t.sibling}return null}var Dn=Object.assign,u8=Symbol.for("react.element"),Xm=Symbol.for("react.transitional.element"),gf=Symbol.for("react.portal"),rd=Symbol.for("react.fragment"),aN=Symbol.for("react.strict_mode"),Hx=Symbol.for("react.profiler"),d8=Symbol.for("react.provider"),oN=Symbol.for("react.consumer"),lo=Symbol.for("react.context"),Jw=Symbol.for("react.forward_ref"),zx=Symbol.for("react.suspense"),qx=Symbol.for("react.suspense_list"),Zw=Symbol.for("react.memo"),Yo=Symbol.for("react.lazy"),Wx=Symbol.for("react.activity"),h8=Symbol.for("react.memo_cache_sentinel"),mR=Symbol.iterator;function Jh(t){return t===null||typeof t!="object"?null:(t=mR&&t[mR]||t["@@iterator"],typeof t=="function"?t:null)}var f8=Symbol.for("react.client.reference");function Yx(t){if(t==null)return null;if(typeof t=="function")return t.$$typeof===f8?null:t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case rd:return"Fragment";case Hx:return"Profiler";case aN:return"StrictMode";case zx:return"Suspense";case qx:return"SuspenseList";case Wx:return"Activity"}if(typeof t=="object")switch(t.$$typeof){case gf:return"Portal";case lo:return(t.displayName||"Context")+".Provider";case oN:return(t._context.displayName||"Context")+".Consumer";case Jw:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case Zw:return e=t.displayName||null,e!==null?e:Yx(t.type)||"Memo";case Yo:e=t._payload,t=t._init;try{return Yx(t(e))}catch{}}return null}var yf=Array.isArray,wt=nN.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,sn=l8.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Nc={pending:!1,data:null,method:null,action:null},Xx=[],sd=-1;function Da(t){return{current:t}}function Pr(t){0>sd||(t.current=Xx[sd],Xx[sd]=null,sd--)}function Fn(t,e){sd++,Xx[sd]=t.current,t.current=e}var Ea=Da(null),sp=Da(null),Sl=Da(null),My=Da(null);function jy(t,e){switch(Fn(Sl,e),Fn(sp,t),Fn(Ea,null),e.nodeType){case 9:case 11:t=(t=e.documentElement)&&(t=t.namespaceURI)?bC(t):0;break;default:if(t=e.tagName,e=e.namespaceURI)e=bC(e),t=wM(e,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}Pr(Ea),Fn(Ea,t)}function eh(){Pr(Ea),Pr(sp),Pr(Sl)}function Qx(t){t.memoizedState!==null&&Fn(My,t);var e=Ea.current,n=wM(e,t.type);e!==n&&(Fn(sp,t),Fn(Ea,n))}function Uy(t){sp.current===t&&(Pr(Ea),Pr(sp)),My.current===t&&(Pr(My),pp._currentValue=Nc)}var Jx=Object.prototype.hasOwnProperty,eT=Er.unstable_scheduleCallback,L_=Er.unstable_cancelCallback,p8=Er.unstable_shouldYield,m8=Er.unstable_requestPaint,wa=Er.unstable_now,g8=Er.unstable_getCurrentPriorityLevel,lN=Er.unstable_ImmediatePriority,cN=Er.unstable_UserBlockingPriority,By=Er.unstable_NormalPriority,y8=Er.unstable_LowPriority,uN=Er.unstable_IdlePriority,v8=Er.log,_8=Er.unstable_setDisableYieldValue,tm=null,Ys=null;function gl(t){if(typeof v8=="function"&&_8(t),Ys&&typeof Ys.setStrictMode=="function")try{Ys.setStrictMode(tm,t)}catch{}}var Xs=Math.clz32?Math.clz32:S8,b8=Math.log,x8=Math.LN2;function S8(t){return t>>>=0,t===0?32:31-(b8(t)/x8|0)|0}var Qm=256,Jm=4194304;function hc(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 iv(t,e,n){var r=t.pendingLanes;if(r===0)return 0;var s=0,i=t.suspendedLanes,a=t.pingedLanes;t=t.warmLanes;var o=r&134217727;return o!==0?(r=o&~i,r!==0?s=hc(r):(a&=o,a!==0?s=hc(a):n||(n=o&~t,n!==0&&(s=hc(n))))):(o=r&~i,o!==0?s=hc(o):a!==0?s=hc(a):n||(n=r&~t,n!==0&&(s=hc(n)))),s===0?0:e!==0&&e!==s&&!(e&i)&&(i=s&-s,n=e&-e,i>=n||i===32&&(n&4194048)!==0)?e:s}function nm(t,e){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&e)===0}function E8(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 dN(){var t=Qm;return Qm<<=1,!(Qm&4194048)&&(Qm=256),t}function hN(){var t=Jm;return Jm<<=1,!(Jm&62914560)&&(Jm=4194304),t}function I_(t){for(var e=[],n=0;31>n;n++)e.push(t);return e}function rm(t,e){t.pendingLanes|=e,e!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function w8(t,e,n,r,s,i){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-Xs(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&&fN(t,r,0),i!==0&&s===0&&t.tag!==0&&(t.suspendedLanes|=i&~(a&~e))}function fN(t,e,n){t.pendingLanes|=e,t.suspendedLanes&=~e;var r=31-Xs(e);t.entangledLanes|=e,t.entanglements[r]=t.entanglements[r]|1073741824|n&4194090}function pN(t,e){var n=t.entangledLanes|=e;for(t=t.entanglements;n;){var r=31-Xs(n),s=1<<r;s&e|t[r]&e&&(t[r]|=e),n&=~s}}function tT(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 nT(t){return t&=-t,2<t?8<t?t&134217727?32:268435456:8:2}function mN(){var t=sn.p;return t!==0?t:(t=window.event,t===void 0?32:OM(t.type))}function T8(t,e){var n=sn.p;try{return sn.p=t,e()}finally{sn.p=n}}var ql=Math.random().toString(36).slice(2),es="__reactFiber$"+ql,Is="__reactProps$"+ql,Eh="__reactContainer$"+ql,Zx="__reactEvents$"+ql,A8="__reactListeners$"+ql,R8="__reactHandles$"+ql,gR="__reactResources$"+ql,sm="__reactMarker$"+ql;function rT(t){delete t[es],delete t[Is],delete t[Zx],delete t[A8],delete t[R8]}function id(t){var e=t[es];if(e)return e;for(var n=t.parentNode;n;){if(e=n[Eh]||n[es]){if(n=e.alternate,e.child!==null||n!==null&&n.child!==null)for(t=EC(t);t!==null;){if(n=t[es])return n;t=EC(t)}return e}t=n,n=t.parentNode}return null}function wh(t){if(t=t[es]||t[Eh]){var e=t.tag;if(e===5||e===6||e===13||e===26||e===27||e===3)return t}return null}function vf(t){var e=t.tag;if(e===5||e===26||e===27||e===6)return t.stateNode;throw Error(je(33))}function Sd(t){var e=t[gR];return e||(e=t[gR]={hoistableStyles:new Map,hoistableScripts:new Map}),e}function Lr(t){t[sm]=!0}var gN=new Set,yN={};function cu(t,e){th(t,e),th(t+"Capture",e)}function th(t,e){for(yN[t]=e,t=0;t<e.length;t++)gN.add(e[t])}var C8=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]*$"),yR={},vR={};function k8(t){return Jx.call(vR,t)?!0:Jx.call(yR,t)?!1:C8.test(t)?vR[t]=!0:(yR[t]=!0,!1)}function ey(t,e,n){if(k8(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 Zm(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 $a(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 P_,_R;function qu(t){if(P_===void 0)try{throw Error()}catch(n){var e=n.stack.trim().match(/\n( *(at )?)/);P_=e&&e[1]||"",_R=-1<n.stack.indexOf(`
    at`)?" (<anonymous>)":-1<n.stack.indexOf("@")?"@unknown:0:0":""}return`
`+P_+t+_R}var D_=!1;function O_(t,e){if(!t||D_)return"";D_=!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 s=Object.getOwnPropertyDescriptor(r.DetermineComponentFrameRoot,"name");s&&s.configurable&&Object.defineProperty(r.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var i=r.DetermineComponentFrameRoot(),a=i[0],o=i[1];if(a&&o){var l=a.split(`
`),c=o.split(`
`);for(s=r=0;r<l.length&&!l[r].includes("DetermineComponentFrameRoot");)r++;for(;s<c.length&&!c[s].includes("DetermineComponentFrameRoot");)s++;if(r===l.length||s===c.length)for(r=l.length-1,s=c.length-1;1<=r&&0<=s&&l[r]!==c[s];)s--;for(;1<=r&&0<=s;r--,s--)if(l[r]!==c[s]){if(r!==1||s!==1)do if(r--,s--,0>s||l[r]!==c[s]){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<=s);break}}}finally{D_=!1,Error.prepareStackTrace=n}return(n=t?t.displayName||t.name:"")?qu(n):""}function L8(t){switch(t.tag){case 26:case 27:case 5:return qu(t.type);case 16:return qu("Lazy");case 13:return qu("Suspense");case 19:return qu("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 qu("Activity");default:return""}}function bR(t){try{var e="";do e+=L8(t),t=t.return;while(t);return e}catch(n){return`
Error generating stack: `+n.message+`
`+n.stack}}function gi(t){switch(typeof t){case"bigint":case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function vN(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function I8(t){var e=vN(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 s=n.get,i=n.set;return Object.defineProperty(t,e,{configurable:!0,get:function(){return s.call(this)},set:function(a){r=""+a,i.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 Fy(t){t._valueTracker||(t._valueTracker=I8(t))}function _N(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var n=e.getValue(),r="";return t&&(r=vN(t)?t.checked?"true":"false":t.value),t=r,t!==n?(e.setValue(t),!0):!1}function $y(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 P8=/[\n"\\]/g;function bi(t){return t.replace(P8,function(e){return"\\"+e.charCodeAt(0).toString(16)+" "})}function eS(t,e,n,r,s,i,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=""+gi(e)):t.value!==""+gi(e)&&(t.value=""+gi(e)):a!=="submit"&&a!=="reset"||t.removeAttribute("value"),e!=null?tS(t,a,gi(e)):n!=null?tS(t,a,gi(n)):r!=null&&t.removeAttribute("value"),s==null&&i!=null&&(t.defaultChecked=!!i),s!=null&&(t.checked=s&&typeof s!="function"&&typeof s!="symbol"),o!=null&&typeof o!="function"&&typeof o!="symbol"&&typeof o!="boolean"?t.name=""+gi(o):t.removeAttribute("name")}function bN(t,e,n,r,s,i,a,o){if(i!=null&&typeof i!="function"&&typeof i!="symbol"&&typeof i!="boolean"&&(t.type=i),e!=null||n!=null){if(!(i!=="submit"&&i!=="reset"||e!=null))return;n=n!=null?""+gi(n):"",e=e!=null?""+gi(e):n,o||e===t.value||(t.value=e),t.defaultValue=e}r=r??s,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 tS(t,e,n){e==="number"&&$y(t.ownerDocument)===t||t.defaultValue===""+n||(t.defaultValue=""+n)}function Ed(t,e,n,r){if(t=t.options,e){e={};for(var s=0;s<n.length;s++)e["$"+n[s]]=!0;for(n=0;n<t.length;n++)s=e.hasOwnProperty("$"+t[n].value),t[n].selected!==s&&(t[n].selected=s),s&&r&&(t[n].defaultSelected=!0)}else{for(n=""+gi(n),e=null,s=0;s<t.length;s++){if(t[s].value===n){t[s].selected=!0,r&&(t[s].defaultSelected=!0);return}e!==null||t[s].disabled||(e=t[s])}e!==null&&(e.selected=!0)}}function xN(t,e,n){if(e!=null&&(e=""+gi(e),e!==t.value&&(t.value=e),n==null)){t.defaultValue!==e&&(t.defaultValue=e);return}t.defaultValue=n!=null?""+gi(n):""}function SN(t,e,n,r){if(e==null){if(r!=null){if(n!=null)throw Error(je(92));if(yf(r)){if(1<r.length)throw Error(je(93));r=r[0]}n=r}n==null&&(n=""),e=n}n=gi(e),t.defaultValue=n,r=t.textContent,r===n&&r!==""&&r!==null&&(t.value=r)}function nh(t,e){if(e){var n=t.firstChild;if(n&&n===t.lastChild&&n.nodeType===3){n.nodeValue=e;return}}t.textContent=e}var D8=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 xR(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||D8.has(e)?e==="float"?t.cssFloat=n:t[e]=(""+n).trim():t[e]=n+"px"}function EN(t,e,n){if(e!=null&&typeof e!="object")throw Error(je(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 s in e)r=e[s],e.hasOwnProperty(s)&&n[s]!==r&&xR(t,s,r)}else for(var i in e)e.hasOwnProperty(i)&&xR(t,i,e[i])}function sT(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 O8=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"]]),N8=/^[\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 ty(t){return N8.test(""+t)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":t}var nS=null;function iT(t){return t=t.target||t.srcElement||window,t.correspondingUseElement&&(t=t.correspondingUseElement),t.nodeType===3?t.parentNode:t}var ad=null,wd=null;function SR(t){var e=wh(t);if(e&&(t=e.stateNode)){var n=t[Is]||null;e:switch(t=e.stateNode,e.type){case"input":if(eS(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="'+bi(""+e)+'"][type="radio"]'),e=0;e<n.length;e++){var r=n[e];if(r!==t&&r.form===t.form){var s=r[Is]||null;if(!s)throw Error(je(90));eS(r,s.value,s.defaultValue,s.defaultValue,s.checked,s.defaultChecked,s.type,s.name)}}for(e=0;e<n.length;e++)r=n[e],r.form===t.form&&_N(r)}break e;case"textarea":xN(t,n.value,n.defaultValue);break e;case"select":e=n.value,e!=null&&Ed(t,!!n.multiple,e,!1)}}}var N_=!1;function wN(t,e,n){if(N_)return t(e,n);N_=!0;try{var r=t(e);return r}finally{if(N_=!1,(ad!==null||wd!==null)&&(mv(),ad&&(e=ad,t=wd,wd=ad=null,SR(e),t)))for(e=0;e<t.length;e++)SR(t[e])}}function ip(t,e){var n=t.stateNode;if(n===null)return null;var r=n[Is]||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(je(231,e,typeof n));return n}var xo=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),rS=!1;if(xo)try{var Zh={};Object.defineProperty(Zh,"passive",{get:function(){rS=!0}}),window.addEventListener("test",Zh,Zh),window.removeEventListener("test",Zh,Zh)}catch{rS=!1}var yl=null,aT=null,ny=null;function TN(){if(ny)return ny;var t,e=aT,n=e.length,r,s="value"in yl?yl.value:yl.textContent,i=s.length;for(t=0;t<n&&e[t]===s[t];t++);var a=n-t;for(r=1;r<=a&&e[n-r]===s[i-r];r++);return ny=s.slice(t,1<r?1-r:void 0)}function ry(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 eg(){return!0}function ER(){return!1}function Ps(t){function e(n,r,s,i,a){this._reactName=n,this._targetInst=s,this.type=r,this.nativeEvent=i,this.target=a,this.currentTarget=null;for(var o in t)t.hasOwnProperty(o)&&(n=t[o],this[o]=n?n(i):i[o]);return this.isDefaultPrevented=(i.defaultPrevented!=null?i.defaultPrevented:i.returnValue===!1)?eg:ER,this.isPropagationStopped=ER,this}return Dn(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=eg)},stopPropagation:function(){var n=this.nativeEvent;n&&(n.stopPropagation?n.stopPropagation():typeof n.cancelBubble!="unknown"&&(n.cancelBubble=!0),this.isPropagationStopped=eg)},persist:function(){},isPersistent:eg}),e}var uu={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(t){return t.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},av=Ps(uu),im=Dn({},uu,{view:0,detail:0}),M8=Ps(im),M_,j_,ef,ov=Dn({},im,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:oT,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!==ef&&(ef&&t.type==="mousemove"?(M_=t.screenX-ef.screenX,j_=t.screenY-ef.screenY):j_=M_=0,ef=t),M_)},movementY:function(t){return"movementY"in t?t.movementY:j_}}),wR=Ps(ov),j8=Dn({},ov,{dataTransfer:0}),U8=Ps(j8),B8=Dn({},im,{relatedTarget:0}),U_=Ps(B8),F8=Dn({},uu,{animationName:0,elapsedTime:0,pseudoElement:0}),$8=Ps(F8),V8=Dn({},uu,{clipboardData:function(t){return"clipboardData"in t?t.clipboardData:window.clipboardData}}),G8=Ps(V8),K8=Dn({},uu,{data:0}),TR=Ps(K8),H8={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},z8={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"},q8={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function W8(t){var e=this.nativeEvent;return e.getModifierState?e.getModifierState(t):(t=q8[t])?!!e[t]:!1}function oT(){return W8}var Y8=Dn({},im,{key:function(t){if(t.key){var e=H8[t.key]||t.key;if(e!=="Unidentified")return e}return t.type==="keypress"?(t=ry(t),t===13?"Enter":String.fromCharCode(t)):t.type==="keydown"||t.type==="keyup"?z8[t.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:oT,charCode:function(t){return t.type==="keypress"?ry(t):0},keyCode:function(t){return t.type==="keydown"||t.type==="keyup"?t.keyCode:0},which:function(t){return t.type==="keypress"?ry(t):t.type==="keydown"||t.type==="keyup"?t.keyCode:0}}),X8=Ps(Y8),Q8=Dn({},ov,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),AR=Ps(Q8),J8=Dn({},im,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:oT}),Z8=Ps(J8),e6=Dn({},uu,{propertyName:0,elapsedTime:0,pseudoElement:0}),t6=Ps(e6),n6=Dn({},ov,{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}),r6=Ps(n6),s6=Dn({},uu,{newState:0,oldState:0}),i6=Ps(s6),a6=[9,13,27,32],lT=xo&&"CompositionEvent"in window,Cf=null;xo&&"documentMode"in document&&(Cf=document.documentMode);var o6=xo&&"TextEvent"in window&&!Cf,AN=xo&&(!lT||Cf&&8<Cf&&11>=Cf),RR=" ",CR=!1;function RN(t,e){switch(t){case"keyup":return a6.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function CN(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var od=!1;function l6(t,e){switch(t){case"compositionend":return CN(e);case"keypress":return e.which!==32?null:(CR=!0,RR);case"textInput":return t=e.data,t===RR&&CR?null:t;default:return null}}function c6(t,e){if(od)return t==="compositionend"||!lT&&RN(t,e)?(t=TN(),ny=aT=yl=null,od=!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 AN&&e.locale!=="ko"?null:e.data;default:return null}}var u6={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 kR(t){var e=t&&t.nodeName&&t.nodeName.toLowerCase();return e==="input"?!!u6[t.type]:e==="textarea"}function kN(t,e,n,r){ad?wd?wd.push(r):wd=[r]:ad=r,e=i0(e,"onChange"),0<e.length&&(n=new av("onChange","change",null,n,r),t.push({event:n,listeners:e}))}var kf=null,ap=null;function d6(t){xM(t,0)}function lv(t){var e=vf(t);if(_N(e))return t}function LR(t,e){if(t==="change")return e}var LN=!1;if(xo){var B_;if(xo){var F_="oninput"in document;if(!F_){var IR=document.createElement("div");IR.setAttribute("oninput","return;"),F_=typeof IR.oninput=="function"}B_=F_}else B_=!1;LN=B_&&(!document.documentMode||9<document.documentMode)}function PR(){kf&&(kf.detachEvent("onpropertychange",IN),ap=kf=null)}function IN(t){if(t.propertyName==="value"&&lv(ap)){var e=[];kN(e,ap,t,iT(t)),wN(d6,e)}}function h6(t,e,n){t==="focusin"?(PR(),kf=e,ap=n,kf.attachEvent("onpropertychange",IN)):t==="focusout"&&PR()}function f6(t){if(t==="selectionchange"||t==="keyup"||t==="keydown")return lv(ap)}function p6(t,e){if(t==="click")return lv(e)}function m6(t,e){if(t==="input"||t==="change")return lv(e)}function g6(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var ni=typeof Object.is=="function"?Object.is:g6;function op(t,e){if(ni(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 s=n[r];if(!Jx.call(e,s)||!ni(t[s],e[s]))return!1}return!0}function DR(t){for(;t&&t.firstChild;)t=t.firstChild;return t}function OR(t,e){var n=DR(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=DR(n)}}function PN(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?PN(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function DN(t){t=t!=null&&t.ownerDocument!=null&&t.ownerDocument.defaultView!=null?t.ownerDocument.defaultView:window;for(var e=$y(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=$y(t.document)}return e}function cT(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 y6=xo&&"documentMode"in document&&11>=document.documentMode,ld=null,sS=null,Lf=null,iS=!1;function NR(t,e,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;iS||ld==null||ld!==$y(r)||(r=ld,"selectionStart"in r&&cT(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}),Lf&&op(Lf,r)||(Lf=r,r=i0(sS,"onSelect"),0<r.length&&(e=new av("onSelect","select",null,e,n),t.push({event:e,listeners:r}),e.target=ld)))}function rc(t,e){var n={};return n[t.toLowerCase()]=e.toLowerCase(),n["Webkit"+t]="webkit"+e,n["Moz"+t]="moz"+e,n}var cd={animationend:rc("Animation","AnimationEnd"),animationiteration:rc("Animation","AnimationIteration"),animationstart:rc("Animation","AnimationStart"),transitionrun:rc("Transition","TransitionRun"),transitionstart:rc("Transition","TransitionStart"),transitioncancel:rc("Transition","TransitionCancel"),transitionend:rc("Transition","TransitionEnd")},$_={},ON={};xo&&(ON=document.createElement("div").style,"AnimationEvent"in window||(delete cd.animationend.animation,delete cd.animationiteration.animation,delete cd.animationstart.animation),"TransitionEvent"in window||delete cd.transitionend.transition);function du(t){if($_[t])return $_[t];if(!cd[t])return t;var e=cd[t],n;for(n in e)if(e.hasOwnProperty(n)&&n in ON)return $_[t]=e[n];return t}var NN=du("animationend"),MN=du("animationiteration"),jN=du("animationstart"),v6=du("transitionrun"),_6=du("transitionstart"),b6=du("transitioncancel"),UN=du("transitionend"),BN=new Map,aS="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(" ");aS.push("scrollEnd");function Xi(t,e){BN.set(t,e),cu(e,[t])}var MR=new WeakMap;function xi(t,e){if(typeof t=="object"&&t!==null){var n=MR.get(t);return n!==void 0?n:(e={value:t,source:e,stack:bR(e)},MR.set(t,e),e)}return{value:t,source:e,stack:bR(e)}}var mi=[],ud=0,uT=0;function cv(){for(var t=ud,e=uT=ud=0;e<t;){var n=mi[e];mi[e++]=null;var r=mi[e];mi[e++]=null;var s=mi[e];mi[e++]=null;var i=mi[e];if(mi[e++]=null,r!==null&&s!==null){var a=r.pending;a===null?s.next=s:(s.next=a.next,a.next=s),r.pending=s}i!==0&&FN(n,s,i)}}function uv(t,e,n,r){mi[ud++]=t,mi[ud++]=e,mi[ud++]=n,mi[ud++]=r,uT|=r,t.lanes|=r,t=t.alternate,t!==null&&(t.lanes|=r)}function dT(t,e,n,r){return uv(t,e,n,r),Vy(t)}function Th(t,e){return uv(t,null,null,e),Vy(t)}function FN(t,e,n){t.lanes|=n;var r=t.alternate;r!==null&&(r.lanes|=n);for(var s=!1,i=t.return;i!==null;)i.childLanes|=n,r=i.alternate,r!==null&&(r.childLanes|=n),i.tag===22&&(t=i.stateNode,t===null||t._visibility&1||(s=!0)),t=i,i=i.return;return t.tag===3?(i=t.stateNode,s&&e!==null&&(s=31-Xs(n),t=i.hiddenUpdates,r=t[s],r===null?t[s]=[e]:r.push(e),e.lane=n|536870912),i):null}function Vy(t){if(50<Ff)throw Ff=0,RS=null,Error(je(185));for(var e=t.return;e!==null;)t=e,e=t.return;return t.tag===3?t.stateNode:null}var dd={};function x6(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 qs(t,e,n,r){return new x6(t,e,n,r)}function hT(t){return t=t.prototype,!(!t||!t.isReactComponent)}function go(t,e){var n=t.alternate;return n===null?(n=qs(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 $N(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 sy(t,e,n,r,s,i){var a=0;if(r=t,typeof t=="function")hT(t)&&(a=1);else if(typeof t=="string")a=EV(t,n,Ea.current)?26:t==="html"||t==="head"||t==="body"?27:5;else e:switch(t){case Wx:return t=qs(31,n,e,s),t.elementType=Wx,t.lanes=i,t;case rd:return Mc(n.children,s,i,e);case aN:a=8,s|=24;break;case Hx:return t=qs(12,n,e,s|2),t.elementType=Hx,t.lanes=i,t;case zx:return t=qs(13,n,e,s),t.elementType=zx,t.lanes=i,t;case qx:return t=qs(19,n,e,s),t.elementType=qx,t.lanes=i,t;default:if(typeof t=="object"&&t!==null)switch(t.$$typeof){case d8:case lo:a=10;break e;case oN:a=9;break e;case Jw:a=11;break e;case Zw:a=14;break e;case Yo:a=16,r=null;break e}a=29,n=Error(je(130,t===null?"null":typeof t,"")),r=null}return e=qs(a,n,e,s),e.elementType=t,e.type=r,e.lanes=i,e}function Mc(t,e,n,r){return t=qs(7,t,r,e),t.lanes=n,t}function V_(t,e,n){return t=qs(6,t,null,e),t.lanes=n,t}function G_(t,e,n){return e=qs(4,t.children!==null?t.children:[],t.key,e),e.lanes=n,e.stateNode={containerInfo:t.containerInfo,pendingChildren:null,implementation:t.implementation},e}var hd=[],fd=0,Gy=null,Ky=0,yi=[],vi=0,jc=null,co=1,uo="";function fc(t,e){hd[fd++]=Ky,hd[fd++]=Gy,Gy=t,Ky=e}function VN(t,e,n){yi[vi++]=co,yi[vi++]=uo,yi[vi++]=jc,jc=t;var r=co;t=uo;var s=32-Xs(r)-1;r&=~(1<<s),n+=1;var i=32-Xs(e)+s;if(30<i){var a=s-s%5;i=(r&(1<<a)-1).toString(32),r>>=a,s-=a,co=1<<32-Xs(e)+s|n<<s|r,uo=i+t}else co=1<<i|n<<s|r,uo=t}function fT(t){t.return!==null&&(fc(t,1),VN(t,1,0))}function pT(t){for(;t===Gy;)Gy=hd[--fd],hd[fd]=null,Ky=hd[--fd],hd[fd]=null;for(;t===jc;)jc=yi[--vi],yi[vi]=null,uo=yi[--vi],yi[vi]=null,co=yi[--vi],yi[vi]=null}var ls=null,Qn=null,rn=!1,Uc=null,ma=!1,oS=Error(je(519));function Yc(t){var e=Error(je(418,""));throw lp(xi(e,t)),oS}function jR(t){var e=t.stateNode,n=t.type,r=t.memoizedProps;switch(e[es]=t,e[Is]=r,n){case"dialog":Wt("cancel",e),Wt("close",e);break;case"iframe":case"object":case"embed":Wt("load",e);break;case"video":case"audio":for(n=0;n<dp.length;n++)Wt(dp[n],e);break;case"source":Wt("error",e);break;case"img":case"image":case"link":Wt("error",e),Wt("load",e);break;case"details":Wt("toggle",e);break;case"input":Wt("invalid",e),bN(e,r.value,r.defaultValue,r.checked,r.defaultChecked,r.type,r.name,!0),Fy(e);break;case"select":Wt("invalid",e);break;case"textarea":Wt("invalid",e),SN(e,r.value,r.defaultValue,r.children),Fy(e)}n=r.children,typeof n!="string"&&typeof n!="number"&&typeof n!="bigint"||e.textContent===""+n||r.suppressHydrationWarning===!0||EM(e.textContent,n)?(r.popover!=null&&(Wt("beforetoggle",e),Wt("toggle",e)),r.onScroll!=null&&Wt("scroll",e),r.onScrollEnd!=null&&Wt("scrollend",e),r.onClick!=null&&(e.onclick=vv),e=!0):e=!1,e||Yc(t)}function UR(t){for(ls=t.return;ls;)switch(ls.tag){case 5:case 13:ma=!1;return;case 27:case 3:ma=!0;return;default:ls=ls.return}}function tf(t){if(t!==ls)return!1;if(!rn)return UR(t),rn=!0,!1;var e=t.tag,n;if((n=e!==3&&e!==27)&&((n=e===5)&&(n=t.type,n=!(n!=="form"&&n!=="button")||DS(t.type,t.memoizedProps)),n=!n),n&&Qn&&Yc(t),UR(t),e===13){if(t=t.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(je(317));e:{for(t=t.nextSibling,e=0;t;){if(t.nodeType===8)if(n=t.data,n==="/$"){if(e===0){Qn=Hi(t.nextSibling);break e}e--}else n!=="$"&&n!=="$!"&&n!=="$?"||e++;t=t.nextSibling}Qn=null}}else e===27?(e=Qn,Wl(t.type)?(t=MS,MS=null,Qn=t):Qn=e):Qn=ls?Hi(t.stateNode.nextSibling):null;return!0}function am(){Qn=ls=null,rn=!1}function BR(){var t=Uc;return t!==null&&(Rs===null?Rs=t:Rs.push.apply(Rs,t),Uc=null),t}function lp(t){Uc===null?Uc=[t]:Uc.push(t)}var lS=Da(null),hu=null,ho=null;function tl(t,e,n){Fn(lS,e._currentValue),e._currentValue=n}function yo(t){t._currentValue=lS.current,Pr(lS)}function cS(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 uS(t,e,n,r){var s=t.child;for(s!==null&&(s.return=t);s!==null;){var i=s.dependencies;if(i!==null){var a=s.child;i=i.firstContext;e:for(;i!==null;){var o=i;i=s;for(var l=0;l<e.length;l++)if(o.context===e[l]){i.lanes|=n,o=i.alternate,o!==null&&(o.lanes|=n),cS(i.return,n,t),r||(a=null);break e}i=o.next}}else if(s.tag===18){if(a=s.return,a===null)throw Error(je(341));a.lanes|=n,i=a.alternate,i!==null&&(i.lanes|=n),cS(a,n,t),a=null}else a=s.child;if(a!==null)a.return=s;else for(a=s;a!==null;){if(a===t){a=null;break}if(s=a.sibling,s!==null){s.return=a.return,a=s;break}a=a.return}s=a}}function om(t,e,n,r){t=null;for(var s=e,i=!1;s!==null;){if(!i){if(s.flags&524288)i=!0;else if(s.flags&262144)break}if(s.tag===10){var a=s.alternate;if(a===null)throw Error(je(387));if(a=a.memoizedProps,a!==null){var o=s.type;ni(s.pendingProps.value,a.value)||(t!==null?t.push(o):t=[o])}}else if(s===My.current){if(a=s.alternate,a===null)throw Error(je(387));a.memoizedState.memoizedState!==s.memoizedState.memoizedState&&(t!==null?t.push(pp):t=[pp])}s=s.return}t!==null&&uS(e,t,n,r),e.flags|=262144}function Hy(t){for(t=t.firstContext;t!==null;){if(!ni(t.context._currentValue,t.memoizedValue))return!0;t=t.next}return!1}function Xc(t){hu=t,ho=null,t=t.dependencies,t!==null&&(t.firstContext=null)}function ts(t){return GN(hu,t)}function tg(t,e){return hu===null&&Xc(t),GN(t,e)}function GN(t,e){var n=e._currentValue;if(e={context:e,memoizedValue:n,next:null},ho===null){if(t===null)throw Error(je(308));ho=e,t.dependencies={lanes:0,firstContext:e},t.flags|=524288}else ho=ho.next=e;return n}var S6=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()})}},E6=Er.unstable_scheduleCallback,w6=Er.unstable_NormalPriority,br={$$typeof:lo,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function mT(){return{controller:new S6,data:new Map,refCount:0}}function lm(t){t.refCount--,t.refCount===0&&E6(w6,function(){t.controller.abort()})}var If=null,dS=0,rh=0,Td=null;function T6(t,e){if(If===null){var n=If=[];dS=0,rh=UT(),Td={status:"pending",value:void 0,then:function(r){n.push(r)}}}return dS++,e.then(FR,FR),e}function FR(){if(--dS===0&&If!==null){Td!==null&&(Td.status="fulfilled");var t=If;If=null,rh=0,Td=null;for(var e=0;e<t.length;e++)(0,t[e])()}}function A6(t,e){var n=[],r={status:"pending",value:null,reason:null,then:function(s){n.push(s)}};return t.then(function(){r.status="fulfilled",r.value=e;for(var s=0;s<n.length;s++)(0,n[s])(e)},function(s){for(r.status="rejected",r.reason=s,s=0;s<n.length;s++)(0,n[s])(void 0)}),r}var $R=wt.S;wt.S=function(t,e){typeof e=="object"&&e!==null&&typeof e.then=="function"&&T6(t,e),$R!==null&&$R(t,e)};var Bc=Da(null);function gT(){var t=Bc.current;return t!==null?t:Rn.pooledCache}function iy(t,e){e===null?Fn(Bc,Bc.current):Fn(Bc,e.pool)}function KN(){var t=gT();return t===null?null:{parent:br._currentValue,pool:t}}var cm=Error(je(460)),HN=Error(je(474)),dv=Error(je(542)),hS={then:function(){}};function VR(t){return t=t.status,t==="fulfilled"||t==="rejected"}function ng(){}function zN(t,e,n){switch(n=t[n],n===void 0?t.push(e):n!==e&&(e.then(ng,ng),e=n),e.status){case"fulfilled":return e.value;case"rejected":throw t=e.reason,KR(t),t;default:if(typeof e.status=="string")e.then(ng,ng);else{if(t=Rn,t!==null&&100<t.shellSuspendCounter)throw Error(je(482));t=e,t.status="pending",t.then(function(r){if(e.status==="pending"){var s=e;s.status="fulfilled",s.value=r}},function(r){if(e.status==="pending"){var s=e;s.status="rejected",s.reason=r}})}switch(e.status){case"fulfilled":return e.value;case"rejected":throw t=e.reason,KR(t),t}throw Pf=e,cm}}var Pf=null;function GR(){if(Pf===null)throw Error(je(459));var t=Pf;return Pf=null,t}function KR(t){if(t===cm||t===dv)throw Error(je(483))}var Xo=!1;function yT(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function fS(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 El(t){return{lane:t,tag:0,payload:null,callback:null,next:null}}function wl(t,e,n){var r=t.updateQueue;if(r===null)return null;if(r=r.shared,pn&2){var s=r.pending;return s===null?e.next=e:(e.next=s.next,s.next=e),r.pending=e,e=Vy(t),FN(t,null,n),e}return uv(t,r,e,n),Vy(t)}function Df(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,pN(t,n)}}function K_(t,e){var n=t.updateQueue,r=t.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var s=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var a={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};i===null?s=i=a:i=i.next=a,n=n.next}while(n!==null);i===null?s=i=e:i=i.next=e}else s=i=e;n={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:i,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 pS=!1;function Of(){if(pS){var t=Td;if(t!==null)throw t}}function Nf(t,e,n,r){pS=!1;var s=t.updateQueue;Xo=!1;var i=s.firstBaseUpdate,a=s.lastBaseUpdate,o=s.shared.pending;if(o!==null){s.shared.pending=null;var l=o,c=l.next;l.next=null,a===null?i=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(i!==null){var d=s.baseState;a=0,u=c=l=null,o=i;do{var h=o.lane&-536870913,f=h!==o.lane;if(f?(Zt&h)===h:(r&h)===h){h!==0&&h===rh&&(pS=!0),u!==null&&(u=u.next={lane:0,tag:o.tag,payload:o.payload,callback:null,next:null});e:{var m=t,g=o;h=e;var y=n;switch(g.tag){case 1:if(m=g.payload,typeof m=="function"){d=m.call(y,d,h);break e}d=m;break e;case 3:m.flags=m.flags&-65537|128;case 0:if(m=g.payload,h=typeof m=="function"?m.call(y,d,h):m,h==null)break e;d=Dn({},d,h);break e;case 2:Xo=!0}}h=o.callback,h!==null&&(t.flags|=64,f&&(t.flags|=8192),f=s.callbacks,f===null?s.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=s.shared.pending,o===null)break;f=o,o=f.next,f.next=null,s.lastBaseUpdate=f,s.shared.pending=null}}while(!0);u===null&&(l=d),s.baseState=l,s.firstBaseUpdate=c,s.lastBaseUpdate=u,i===null&&(s.shared.lanes=0),jl|=a,t.lanes=a,t.memoizedState=d}}function qN(t,e){if(typeof t!="function")throw Error(je(191,t));t.call(e)}function WN(t,e){var n=t.callbacks;if(n!==null)for(t.callbacks=null,t=0;t<n.length;t++)qN(n[t],e)}var sh=Da(null),zy=Da(0);function HR(t,e){t=wo,Fn(zy,t),Fn(sh,e),wo=t|e.baseLanes}function mS(){Fn(zy,wo),Fn(sh,sh.current)}function vT(){wo=zy.current,Pr(sh),Pr(zy)}var Nl=0,$t=null,yn=null,hr=null,qy=!1,Ad=!1,Qc=!1,Wy=0,cp=0,Rd=null,R6=0;function rr(){throw Error(je(321))}function _T(t,e){if(e===null)return!1;for(var n=0;n<e.length&&n<t.length;n++)if(!ni(t[n],e[n]))return!1;return!0}function bT(t,e,n,r,s,i){return Nl=i,$t=e,e.memoizedState=null,e.updateQueue=null,e.lanes=0,wt.H=t===null||t.memoizedState===null?T2:A2,Qc=!1,i=n(r,s),Qc=!1,Ad&&(i=XN(e,n,r,s)),YN(t),i}function YN(t){wt.H=Yy;var e=yn!==null&&yn.next!==null;if(Nl=0,hr=yn=$t=null,qy=!1,cp=0,Rd=null,e)throw Error(je(300));t===null||Ir||(t=t.dependencies,t!==null&&Hy(t)&&(Ir=!0))}function XN(t,e,n,r){$t=t;var s=0;do{if(Ad&&(Rd=null),cp=0,Ad=!1,25<=s)throw Error(je(301));if(s+=1,hr=yn=null,t.updateQueue!=null){var i=t.updateQueue;i.lastEffect=null,i.events=null,i.stores=null,i.memoCache!=null&&(i.memoCache.index=0)}wt.H=O6,i=e(n,r)}while(Ad);return i}function C6(){var t=wt.H,e=t.useState()[0];return e=typeof e.then=="function"?um(e):e,t=t.useState()[0],(yn!==null?yn.memoizedState:null)!==t&&($t.flags|=1024),e}function xT(){var t=Wy!==0;return Wy=0,t}function ST(t,e,n){e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~n}function ET(t){if(qy){for(t=t.memoizedState;t!==null;){var e=t.queue;e!==null&&(e.pending=null),t=t.next}qy=!1}Nl=0,hr=yn=$t=null,Ad=!1,cp=Wy=0,Rd=null}function Ts(){var t={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return hr===null?$t.memoizedState=hr=t:hr=hr.next=t,hr}function fr(){if(yn===null){var t=$t.alternate;t=t!==null?t.memoizedState:null}else t=yn.next;var e=hr===null?$t.memoizedState:hr.next;if(e!==null)hr=e,yn=t;else{if(t===null)throw $t.alternate===null?Error(je(467)):Error(je(310));yn=t,t={memoizedState:yn.memoizedState,baseState:yn.baseState,baseQueue:yn.baseQueue,queue:yn.queue,next:null},hr===null?$t.memoizedState=hr=t:hr=hr.next=t}return hr}function wT(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function um(t){var e=cp;return cp+=1,Rd===null&&(Rd=[]),t=zN(Rd,t,e),e=$t,(hr===null?e.memoizedState:hr.next)===null&&(e=e.alternate,wt.H=e===null||e.memoizedState===null?T2:A2),t}function hv(t){if(t!==null&&typeof t=="object"){if(typeof t.then=="function")return um(t);if(t.$$typeof===lo)return ts(t)}throw Error(je(438,String(t)))}function TT(t){var e=null,n=$t.updateQueue;if(n!==null&&(e=n.memoCache),e==null){var r=$t.alternate;r!==null&&(r=r.updateQueue,r!==null&&(r=r.memoCache,r!=null&&(e={data:r.data.map(function(s){return s.slice()}),index:0})))}if(e==null&&(e={data:[],index:0}),n===null&&(n=wT(),$t.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]=h8;return e.index++,n}function So(t,e){return typeof e=="function"?e(t):e}function ay(t){var e=fr();return AT(e,yn,t)}function AT(t,e,n){var r=t.queue;if(r===null)throw Error(je(311));r.lastRenderedReducer=n;var s=t.baseQueue,i=r.pending;if(i!==null){if(s!==null){var a=s.next;s.next=i.next,i.next=a}e.baseQueue=s=i,r.pending=null}if(i=t.baseState,s===null)t.memoizedState=i;else{e=s.next;var o=a=null,l=null,c=e,u=!1;do{var d=c.lane&-536870913;if(d!==c.lane?(Zt&d)===d:(Nl&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===rh&&(u=!0);else if((Nl&h)===h){c=c.next,h===rh&&(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=i):l=l.next=d,$t.lanes|=h,jl|=h;d=c.action,Qc&&n(i,d),i=c.hasEagerState?c.eagerState:n(i,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=i):l=l.next=h,$t.lanes|=d,jl|=d;c=c.next}while(c!==null&&c!==e);if(l===null?a=i:l.next=o,!ni(i,t.memoizedState)&&(Ir=!0,u&&(n=Td,n!==null)))throw n;t.memoizedState=i,t.baseState=a,t.baseQueue=l,r.lastRenderedState=i}return s===null&&(r.lanes=0),[t.memoizedState,r.dispatch]}function H_(t){var e=fr(),n=e.queue;if(n===null)throw Error(je(311));n.lastRenderedReducer=t;var r=n.dispatch,s=n.pending,i=e.memoizedState;if(s!==null){n.pending=null;var a=s=s.next;do i=t(i,a.action),a=a.next;while(a!==s);ni(i,e.memoizedState)||(Ir=!0),e.memoizedState=i,e.baseQueue===null&&(e.baseState=i),n.lastRenderedState=i}return[i,r]}function QN(t,e,n){var r=$t,s=fr(),i=rn;if(i){if(n===void 0)throw Error(je(407));n=n()}else n=e();var a=!ni((yn||s).memoizedState,n);a&&(s.memoizedState=n,Ir=!0),s=s.queue;var o=e2.bind(null,r,s,t);if(dm(2048,8,o,[t]),s.getSnapshot!==e||a||hr!==null&&hr.memoizedState.tag&1){if(r.flags|=2048,ih(9,fv(),ZN.bind(null,r,s,n,e),null),Rn===null)throw Error(je(349));i||Nl&124||JN(r,e,n)}return n}function JN(t,e,n){t.flags|=16384,t={getSnapshot:e,value:n},e=$t.updateQueue,e===null?(e=wT(),$t.updateQueue=e,e.stores=[t]):(n=e.stores,n===null?e.stores=[t]:n.push(t))}function ZN(t,e,n,r){e.value=n,e.getSnapshot=r,t2(e)&&n2(t)}function e2(t,e,n){return n(function(){t2(e)&&n2(t)})}function t2(t){var e=t.getSnapshot;t=t.value;try{var n=e();return!ni(t,n)}catch{return!0}}function n2(t){var e=Th(t,2);e!==null&&Js(e,t,2)}function gS(t){var e=Ts();if(typeof t=="function"){var n=t;if(t=n(),Qc){gl(!0);try{n()}finally{gl(!1)}}}return e.memoizedState=e.baseState=t,e.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:So,lastRenderedState:t},e}function r2(t,e,n,r){return t.baseState=n,AT(t,yn,typeof r=="function"?r:So)}function k6(t,e,n,r,s){if(pv(t))throw Error(je(485));if(t=e.action,t!==null){var i={payload:s,action:t,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(a){i.listeners.push(a)}};wt.T!==null?n(!0):i.isTransition=!1,r(i),n=e.pending,n===null?(i.next=e.pending=i,s2(e,i)):(i.next=n.next,e.pending=n.next=i)}}function s2(t,e){var n=e.action,r=e.payload,s=t.state;if(e.isTransition){var i=wt.T,a={};wt.T=a;try{var o=n(s,r),l=wt.S;l!==null&&l(a,o),zR(t,e,o)}catch(c){yS(t,e,c)}finally{wt.T=i}}else try{i=n(s,r),zR(t,e,i)}catch(c){yS(t,e,c)}}function zR(t,e,n){n!==null&&typeof n=="object"&&typeof n.then=="function"?n.then(function(r){qR(t,e,r)},function(r){return yS(t,e,r)}):qR(t,e,n)}function qR(t,e,n){e.status="fulfilled",e.value=n,i2(e),t.state=n,e=t.pending,e!==null&&(n=e.next,n===e?t.pending=null:(n=n.next,e.next=n,s2(t,n)))}function yS(t,e,n){var r=t.pending;if(t.pending=null,r!==null){r=r.next;do e.status="rejected",e.reason=n,i2(e),e=e.next;while(e!==r)}t.action=null}function i2(t){t=t.listeners;for(var e=0;e<t.length;e++)(0,t[e])()}function a2(t,e){return e}function WR(t,e){if(rn){var n=Rn.formState;if(n!==null){e:{var r=$t;if(rn){if(Qn){t:{for(var s=Qn,i=ma;s.nodeType!==8;){if(!i){s=null;break t}if(s=Hi(s.nextSibling),s===null){s=null;break t}}i=s.data,s=i==="F!"||i==="F"?s:null}if(s){Qn=Hi(s.nextSibling),r=s.data==="F!";break e}}Yc(r)}r=!1}r&&(e=n[0])}}return n=Ts(),n.memoizedState=n.baseState=e,r={pending:null,lanes:0,dispatch:null,lastRenderedReducer:a2,lastRenderedState:e},n.queue=r,n=S2.bind(null,$t,r),r.dispatch=n,r=gS(!1),i=LT.bind(null,$t,!1,r.queue),r=Ts(),s={state:e,dispatch:null,action:t,pending:null},r.queue=s,n=k6.bind(null,$t,s,i,n),s.dispatch=n,r.memoizedState=t,[e,n,!1]}function YR(t){var e=fr();return o2(e,yn,t)}function o2(t,e,n){if(e=AT(t,e,a2)[0],t=ay(So)[0],typeof e=="object"&&e!==null&&typeof e.then=="function")try{var r=um(e)}catch(a){throw a===cm?dv:a}else r=e;e=fr();var s=e.queue,i=s.dispatch;return n!==e.memoizedState&&($t.flags|=2048,ih(9,fv(),L6.bind(null,s,n),null)),[r,i,t]}function L6(t,e){t.action=e}function XR(t){var e=fr(),n=yn;if(n!==null)return o2(e,n,t);fr(),e=e.memoizedState,n=fr();var r=n.queue.dispatch;return n.memoizedState=t,[e,r,!1]}function ih(t,e,n,r){return t={tag:t,create:n,deps:r,inst:e,next:null},e=$t.updateQueue,e===null&&(e=wT(),$t.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 fv(){return{destroy:void 0,resource:void 0}}function l2(){return fr().memoizedState}function oy(t,e,n,r){var s=Ts();r=r===void 0?null:r,$t.flags|=t,s.memoizedState=ih(1|e,fv(),n,r)}function dm(t,e,n,r){var s=fr();r=r===void 0?null:r;var i=s.memoizedState.inst;yn!==null&&r!==null&&_T(r,yn.memoizedState.deps)?s.memoizedState=ih(e,i,n,r):($t.flags|=t,s.memoizedState=ih(1|e,i,n,r))}function QR(t,e){oy(8390656,8,t,e)}function c2(t,e){dm(2048,8,t,e)}function u2(t,e){return dm(4,2,t,e)}function d2(t,e){return dm(4,4,t,e)}function h2(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 f2(t,e,n){n=n!=null?n.concat([t]):null,dm(4,4,h2.bind(null,e,t),n)}function RT(){}function p2(t,e){var n=fr();e=e===void 0?null:e;var r=n.memoizedState;return e!==null&&_T(e,r[1])?r[0]:(n.memoizedState=[t,e],t)}function m2(t,e){var n=fr();e=e===void 0?null:e;var r=n.memoizedState;if(e!==null&&_T(e,r[1]))return r[0];if(r=t(),Qc){gl(!0);try{t()}finally{gl(!1)}}return n.memoizedState=[r,e],r}function CT(t,e,n){return n===void 0||Nl&1073741824?t.memoizedState=e:(t.memoizedState=n,t=iM(),$t.lanes|=t,jl|=t,n)}function g2(t,e,n,r){return ni(n,e)?n:sh.current!==null?(t=CT(t,n,r),ni(t,e)||(Ir=!0),t):Nl&42?(t=iM(),$t.lanes|=t,jl|=t,e):(Ir=!0,t.memoizedState=n)}function y2(t,e,n,r,s){var i=sn.p;sn.p=i!==0&&8>i?i:8;var a=wt.T,o={};wt.T=o,LT(t,!1,e,n);try{var l=s(),c=wt.S;if(c!==null&&c(o,l),l!==null&&typeof l=="object"&&typeof l.then=="function"){var u=A6(l,r);Mf(t,e,u,Qs(t))}else Mf(t,e,r,Qs(t))}catch(d){Mf(t,e,{then:function(){},status:"rejected",reason:d},Qs())}finally{sn.p=i,wt.T=a}}function I6(){}function vS(t,e,n,r){if(t.tag!==5)throw Error(je(476));var s=v2(t).queue;y2(t,s,e,Nc,n===null?I6:function(){return _2(t),n(r)})}function v2(t){var e=t.memoizedState;if(e!==null)return e;e={memoizedState:Nc,baseState:Nc,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:So,lastRenderedState:Nc},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 _2(t){var e=v2(t).next.queue;Mf(t,e,{},Qs())}function kT(){return ts(pp)}function b2(){return fr().memoizedState}function x2(){return fr().memoizedState}function P6(t){for(var e=t.return;e!==null;){switch(e.tag){case 24:case 3:var n=Qs();t=El(n);var r=wl(e,t,n);r!==null&&(Js(r,e,n),Df(r,e,n)),e={cache:mT()},t.payload=e;return}e=e.return}}function D6(t,e,n){var r=Qs();n={lane:r,revertLane:0,action:n,hasEagerState:!1,eagerState:null,next:null},pv(t)?E2(e,n):(n=dT(t,e,n,r),n!==null&&(Js(n,t,r),w2(n,e,r)))}function S2(t,e,n){var r=Qs();Mf(t,e,n,r)}function Mf(t,e,n,r){var s={lane:r,revertLane:0,action:n,hasEagerState:!1,eagerState:null,next:null};if(pv(t))E2(e,s);else{var i=t.alternate;if(t.lanes===0&&(i===null||i.lanes===0)&&(i=e.lastRenderedReducer,i!==null))try{var a=e.lastRenderedState,o=i(a,n);if(s.hasEagerState=!0,s.eagerState=o,ni(o,a))return uv(t,e,s,0),Rn===null&&cv(),!1}catch{}finally{}if(n=dT(t,e,s,r),n!==null)return Js(n,t,r),w2(n,e,r),!0}return!1}function LT(t,e,n,r){if(r={lane:2,revertLane:UT(),action:r,hasEagerState:!1,eagerState:null,next:null},pv(t)){if(e)throw Error(je(479))}else e=dT(t,n,r,2),e!==null&&Js(e,t,2)}function pv(t){var e=t.alternate;return t===$t||e!==null&&e===$t}function E2(t,e){Ad=qy=!0;var n=t.pending;n===null?e.next=e:(e.next=n.next,n.next=e),t.pending=e}function w2(t,e,n){if(n&4194048){var r=e.lanes;r&=t.pendingLanes,n|=r,e.lanes=n,pN(t,n)}}var Yy={readContext:ts,use:hv,useCallback:rr,useContext:rr,useEffect:rr,useImperativeHandle:rr,useLayoutEffect:rr,useInsertionEffect:rr,useMemo:rr,useReducer:rr,useRef:rr,useState:rr,useDebugValue:rr,useDeferredValue:rr,useTransition:rr,useSyncExternalStore:rr,useId:rr,useHostTransitionStatus:rr,useFormState:rr,useActionState:rr,useOptimistic:rr,useMemoCache:rr,useCacheRefresh:rr},T2={readContext:ts,use:hv,useCallback:function(t,e){return Ts().memoizedState=[t,e===void 0?null:e],t},useContext:ts,useEffect:QR,useImperativeHandle:function(t,e,n){n=n!=null?n.concat([t]):null,oy(4194308,4,h2.bind(null,e,t),n)},useLayoutEffect:function(t,e){return oy(4194308,4,t,e)},useInsertionEffect:function(t,e){oy(4,2,t,e)},useMemo:function(t,e){var n=Ts();e=e===void 0?null:e;var r=t();if(Qc){gl(!0);try{t()}finally{gl(!1)}}return n.memoizedState=[r,e],r},useReducer:function(t,e,n){var r=Ts();if(n!==void 0){var s=n(e);if(Qc){gl(!0);try{n(e)}finally{gl(!1)}}}else s=e;return r.memoizedState=r.baseState=s,t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:s},r.queue=t,t=t.dispatch=D6.bind(null,$t,t),[r.memoizedState,t]},useRef:function(t){var e=Ts();return t={current:t},e.memoizedState=t},useState:function(t){t=gS(t);var e=t.queue,n=S2.bind(null,$t,e);return e.dispatch=n,[t.memoizedState,n]},useDebugValue:RT,useDeferredValue:function(t,e){var n=Ts();return CT(n,t,e)},useTransition:function(){var t=gS(!1);return t=y2.bind(null,$t,t.queue,!0,!1),Ts().memoizedState=t,[!1,t]},useSyncExternalStore:function(t,e,n){var r=$t,s=Ts();if(rn){if(n===void 0)throw Error(je(407));n=n()}else{if(n=e(),Rn===null)throw Error(je(349));Zt&124||JN(r,e,n)}s.memoizedState=n;var i={value:n,getSnapshot:e};return s.queue=i,QR(e2.bind(null,r,i,t),[t]),r.flags|=2048,ih(9,fv(),ZN.bind(null,r,i,n,e),null),n},useId:function(){var t=Ts(),e=Rn.identifierPrefix;if(rn){var n=uo,r=co;n=(r&~(1<<32-Xs(r)-1)).toString(32)+n,e="«"+e+"R"+n,n=Wy++,0<n&&(e+="H"+n.toString(32)),e+="»"}else n=R6++,e="«"+e+"r"+n.toString(32)+"»";return t.memoizedState=e},useHostTransitionStatus:kT,useFormState:WR,useActionState:WR,useOptimistic:function(t){var e=Ts();e.memoizedState=e.baseState=t;var n={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return e.queue=n,e=LT.bind(null,$t,!0,n),n.dispatch=e,[t,e]},useMemoCache:TT,useCacheRefresh:function(){return Ts().memoizedState=P6.bind(null,$t)}},A2={readContext:ts,use:hv,useCallback:p2,useContext:ts,useEffect:c2,useImperativeHandle:f2,useInsertionEffect:u2,useLayoutEffect:d2,useMemo:m2,useReducer:ay,useRef:l2,useState:function(){return ay(So)},useDebugValue:RT,useDeferredValue:function(t,e){var n=fr();return g2(n,yn.memoizedState,t,e)},useTransition:function(){var t=ay(So)[0],e=fr().memoizedState;return[typeof t=="boolean"?t:um(t),e]},useSyncExternalStore:QN,useId:b2,useHostTransitionStatus:kT,useFormState:YR,useActionState:YR,useOptimistic:function(t,e){var n=fr();return r2(n,yn,t,e)},useMemoCache:TT,useCacheRefresh:x2},O6={readContext:ts,use:hv,useCallback:p2,useContext:ts,useEffect:c2,useImperativeHandle:f2,useInsertionEffect:u2,useLayoutEffect:d2,useMemo:m2,useReducer:H_,useRef:l2,useState:function(){return H_(So)},useDebugValue:RT,useDeferredValue:function(t,e){var n=fr();return yn===null?CT(n,t,e):g2(n,yn.memoizedState,t,e)},useTransition:function(){var t=H_(So)[0],e=fr().memoizedState;return[typeof t=="boolean"?t:um(t),e]},useSyncExternalStore:QN,useId:b2,useHostTransitionStatus:kT,useFormState:XR,useActionState:XR,useOptimistic:function(t,e){var n=fr();return yn!==null?r2(n,yn,t,e):(n.baseState=t,[t,n.queue.dispatch])},useMemoCache:TT,useCacheRefresh:x2},Cd=null,up=0;function rg(t){var e=up;return up+=1,Cd===null&&(Cd=[]),zN(Cd,t,e)}function nf(t,e){e=e.props.ref,t.ref=e!==void 0?e:null}function sg(t,e){throw e.$$typeof===u8?Error(je(525)):(t=Object.prototype.toString.call(e),Error(je(31,t==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":t)))}function JR(t){var e=t._init;return e(t._payload)}function R2(t){function e(v,_){if(t){var S=v.deletions;S===null?(v.deletions=[_],v.flags|=16):S.push(_)}}function n(v,_){if(!t)return null;for(;_!==null;)e(v,_),_=_.sibling;return null}function r(v){for(var _=new Map;v!==null;)v.key!==null?_.set(v.key,v):_.set(v.index,v),v=v.sibling;return _}function s(v,_){return v=go(v,_),v.index=0,v.sibling=null,v}function i(v,_,S){return v.index=S,t?(S=v.alternate,S!==null?(S=S.index,S<_?(v.flags|=67108866,_):S):(v.flags|=67108866,_)):(v.flags|=1048576,_)}function a(v){return t&&v.alternate===null&&(v.flags|=67108866),v}function o(v,_,S,E){return _===null||_.tag!==6?(_=V_(S,v.mode,E),_.return=v,_):(_=s(_,S),_.return=v,_)}function l(v,_,S,E){var L=S.type;return L===rd?u(v,_,S.props.children,E,S.key):_!==null&&(_.elementType===L||typeof L=="object"&&L!==null&&L.$$typeof===Yo&&JR(L)===_.type)?(_=s(_,S.props),nf(_,S),_.return=v,_):(_=sy(S.type,S.key,S.props,null,v.mode,E),nf(_,S),_.return=v,_)}function c(v,_,S,E){return _===null||_.tag!==4||_.stateNode.containerInfo!==S.containerInfo||_.stateNode.implementation!==S.implementation?(_=G_(S,v.mode,E),_.return=v,_):(_=s(_,S.children||[]),_.return=v,_)}function u(v,_,S,E,L){return _===null||_.tag!==7?(_=Mc(S,v.mode,E,L),_.return=v,_):(_=s(_,S),_.return=v,_)}function d(v,_,S){if(typeof _=="string"&&_!==""||typeof _=="number"||typeof _=="bigint")return _=V_(""+_,v.mode,S),_.return=v,_;if(typeof _=="object"&&_!==null){switch(_.$$typeof){case Xm:return S=sy(_.type,_.key,_.props,null,v.mode,S),nf(S,_),S.return=v,S;case gf:return _=G_(_,v.mode,S),_.return=v,_;case Yo:var E=_._init;return _=E(_._payload),d(v,_,S)}if(yf(_)||Jh(_))return _=Mc(_,v.mode,S,null),_.return=v,_;if(typeof _.then=="function")return d(v,rg(_),S);if(_.$$typeof===lo)return d(v,tg(v,_),S);sg(v,_)}return null}function h(v,_,S,E){var L=_!==null?_.key:null;if(typeof S=="string"&&S!==""||typeof S=="number"||typeof S=="bigint")return L!==null?null:o(v,_,""+S,E);if(typeof S=="object"&&S!==null){switch(S.$$typeof){case Xm:return S.key===L?l(v,_,S,E):null;case gf:return S.key===L?c(v,_,S,E):null;case Yo:return L=S._init,S=L(S._payload),h(v,_,S,E)}if(yf(S)||Jh(S))return L!==null?null:u(v,_,S,E,null);if(typeof S.then=="function")return h(v,_,rg(S),E);if(S.$$typeof===lo)return h(v,_,tg(v,S),E);sg(v,S)}return null}function f(v,_,S,E,L){if(typeof E=="string"&&E!==""||typeof E=="number"||typeof E=="bigint")return v=v.get(S)||null,o(_,v,""+E,L);if(typeof E=="object"&&E!==null){switch(E.$$typeof){case Xm:return v=v.get(E.key===null?S:E.key)||null,l(_,v,E,L);case gf:return v=v.get(E.key===null?S:E.key)||null,c(_,v,E,L);case Yo:var U=E._init;return E=U(E._payload),f(v,_,S,E,L)}if(yf(E)||Jh(E))return v=v.get(S)||null,u(_,v,E,L,null);if(typeof E.then=="function")return f(v,_,S,rg(E),L);if(E.$$typeof===lo)return f(v,_,S,tg(_,E),L);sg(_,E)}return null}function m(v,_,S,E){for(var L=null,U=null,P=_,I=_=0,k=null;P!==null&&I<S.length;I++){P.index>I?(k=P,P=null):k=P.sibling;var R=h(v,P,S[I],E);if(R===null){P===null&&(P=k);break}t&&P&&R.alternate===null&&e(v,P),_=i(R,_,I),U===null?L=R:U.sibling=R,U=R,P=k}if(I===S.length)return n(v,P),rn&&fc(v,I),L;if(P===null){for(;I<S.length;I++)P=d(v,S[I],E),P!==null&&(_=i(P,_,I),U===null?L=P:U.sibling=P,U=P);return rn&&fc(v,I),L}for(P=r(P);I<S.length;I++)k=f(P,v,I,S[I],E),k!==null&&(t&&k.alternate!==null&&P.delete(k.key===null?I:k.key),_=i(k,_,I),U===null?L=k:U.sibling=k,U=k);return t&&P.forEach(function(M){return e(v,M)}),rn&&fc(v,I),L}function g(v,_,S,E){if(S==null)throw Error(je(151));for(var L=null,U=null,P=_,I=_=0,k=null,R=S.next();P!==null&&!R.done;I++,R=S.next()){P.index>I?(k=P,P=null):k=P.sibling;var M=h(v,P,R.value,E);if(M===null){P===null&&(P=k);break}t&&P&&M.alternate===null&&e(v,P),_=i(M,_,I),U===null?L=M:U.sibling=M,U=M,P=k}if(R.done)return n(v,P),rn&&fc(v,I),L;if(P===null){for(;!R.done;I++,R=S.next())R=d(v,R.value,E),R!==null&&(_=i(R,_,I),U===null?L=R:U.sibling=R,U=R);return rn&&fc(v,I),L}for(P=r(P);!R.done;I++,R=S.next())R=f(P,v,I,R.value,E),R!==null&&(t&&R.alternate!==null&&P.delete(R.key===null?I:R.key),_=i(R,_,I),U===null?L=R:U.sibling=R,U=R);return t&&P.forEach(function(G){return e(v,G)}),rn&&fc(v,I),L}function y(v,_,S,E){if(typeof S=="object"&&S!==null&&S.type===rd&&S.key===null&&(S=S.props.children),typeof S=="object"&&S!==null){switch(S.$$typeof){case Xm:e:{for(var L=S.key;_!==null;){if(_.key===L){if(L=S.type,L===rd){if(_.tag===7){n(v,_.sibling),E=s(_,S.props.children),E.return=v,v=E;break e}}else if(_.elementType===L||typeof L=="object"&&L!==null&&L.$$typeof===Yo&&JR(L)===_.type){n(v,_.sibling),E=s(_,S.props),nf(E,S),E.return=v,v=E;break e}n(v,_);break}else e(v,_);_=_.sibling}S.type===rd?(E=Mc(S.props.children,v.mode,E,S.key),E.return=v,v=E):(E=sy(S.type,S.key,S.props,null,v.mode,E),nf(E,S),E.return=v,v=E)}return a(v);case gf:e:{for(L=S.key;_!==null;){if(_.key===L)if(_.tag===4&&_.stateNode.containerInfo===S.containerInfo&&_.stateNode.implementation===S.implementation){n(v,_.sibling),E=s(_,S.children||[]),E.return=v,v=E;break e}else{n(v,_);break}else e(v,_);_=_.sibling}E=G_(S,v.mode,E),E.return=v,v=E}return a(v);case Yo:return L=S._init,S=L(S._payload),y(v,_,S,E)}if(yf(S))return m(v,_,S,E);if(Jh(S)){if(L=Jh(S),typeof L!="function")throw Error(je(150));return S=L.call(S),g(v,_,S,E)}if(typeof S.then=="function")return y(v,_,rg(S),E);if(S.$$typeof===lo)return y(v,_,tg(v,S),E);sg(v,S)}return typeof S=="string"&&S!==""||typeof S=="number"||typeof S=="bigint"?(S=""+S,_!==null&&_.tag===6?(n(v,_.sibling),E=s(_,S),E.return=v,v=E):(n(v,_),E=V_(S,v.mode,E),E.return=v,v=E),a(v)):n(v,_)}return function(v,_,S,E){try{up=0;var L=y(v,_,S,E);return Cd=null,L}catch(P){if(P===cm||P===dv)throw P;var U=qs(29,P,null,v.mode);return U.lanes=E,U.return=v,U}finally{}}}var ah=R2(!0),C2=R2(!1),Ai=Da(null),Ta=null;function nl(t){var e=t.alternate;Fn(Sr,Sr.current&1),Fn(Ai,t),Ta===null&&(e===null||sh.current!==null||e.memoizedState!==null)&&(Ta=t)}function k2(t){if(t.tag===22){if(Fn(Sr,Sr.current),Fn(Ai,t),Ta===null){var e=t.alternate;e!==null&&e.memoizedState!==null&&(Ta=t)}}else rl()}function rl(){Fn(Sr,Sr.current),Fn(Ai,Ai.current)}function fo(t){Pr(Ai),Ta===t&&(Ta=null),Pr(Sr)}var Sr=Da(0);function Xy(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==="$?"||NS(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 z_(t,e,n,r){e=t.memoizedState,n=n(r,e),n=n==null?e:Dn({},e,n),t.memoizedState=n,t.lanes===0&&(t.updateQueue.baseState=n)}var _S={enqueueSetState:function(t,e,n){t=t._reactInternals;var r=Qs(),s=El(r);s.payload=e,n!=null&&(s.callback=n),e=wl(t,s,r),e!==null&&(Js(e,t,r),Df(e,t,r))},enqueueReplaceState:function(t,e,n){t=t._reactInternals;var r=Qs(),s=El(r);s.tag=1,s.payload=e,n!=null&&(s.callback=n),e=wl(t,s,r),e!==null&&(Js(e,t,r),Df(e,t,r))},enqueueForceUpdate:function(t,e){t=t._reactInternals;var n=Qs(),r=El(n);r.tag=2,e!=null&&(r.callback=e),e=wl(t,r,n),e!==null&&(Js(e,t,n),Df(e,t,n))}};function ZR(t,e,n,r,s,i,a){return t=t.stateNode,typeof t.shouldComponentUpdate=="function"?t.shouldComponentUpdate(r,i,a):e.prototype&&e.prototype.isPureReactComponent?!op(n,r)||!op(s,i):!0}function eC(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&&_S.enqueueReplaceState(e,e.state,null)}function Jc(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=Dn({},n));for(var s in t)n[s]===void 0&&(n[s]=t[s])}return n}var Qy=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 L2(t){Qy(t)}function I2(t){console.error(t)}function P2(t){Qy(t)}function Jy(t,e){try{var n=t.onUncaughtError;n(e.value,{componentStack:e.stack})}catch(r){setTimeout(function(){throw r})}}function tC(t,e,n){try{var r=t.onCaughtError;r(n.value,{componentStack:n.stack,errorBoundary:e.tag===1?e.stateNode:null})}catch(s){setTimeout(function(){throw s})}}function bS(t,e,n){return n=El(n),n.tag=3,n.payload={element:null},n.callback=function(){Jy(t,e)},n}function D2(t){return t=El(t),t.tag=3,t}function O2(t,e,n,r){var s=n.type.getDerivedStateFromError;if(typeof s=="function"){var i=r.value;t.payload=function(){return s(i)},t.callback=function(){tC(e,n,r)}}var a=n.stateNode;a!==null&&typeof a.componentDidCatch=="function"&&(t.callback=function(){tC(e,n,r),typeof s!="function"&&(Tl===null?Tl=new Set([this]):Tl.add(this));var o=r.stack;this.componentDidCatch(r.value,{componentStack:o!==null?o:""})})}function N6(t,e,n,r,s){if(n.flags|=32768,r!==null&&typeof r=="object"&&typeof r.then=="function"){if(e=n.alternate,e!==null&&om(e,n,s,!0),n=Ai.current,n!==null){switch(n.tag){case 13:return Ta===null?CS():n.alternate===null&&Jn===0&&(Jn=3),n.flags&=-257,n.flags|=65536,n.lanes=s,r===hS?n.flags|=16384:(e=n.updateQueue,e===null?n.updateQueue=new Set([r]):e.add(r),rb(t,r,s)),!1;case 22:return n.flags|=65536,r===hS?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)),rb(t,r,s)),!1}throw Error(je(435,n.tag))}return rb(t,r,s),CS(),!1}if(rn)return e=Ai.current,e!==null?(!(e.flags&65536)&&(e.flags|=256),e.flags|=65536,e.lanes=s,r!==oS&&(t=Error(je(422),{cause:r}),lp(xi(t,n)))):(r!==oS&&(e=Error(je(423),{cause:r}),lp(xi(e,n))),t=t.current.alternate,t.flags|=65536,s&=-s,t.lanes|=s,r=xi(r,n),s=bS(t.stateNode,r,s),K_(t,s),Jn!==4&&(Jn=2)),!1;var i=Error(je(520),{cause:r});if(i=xi(i,n),Bf===null?Bf=[i]:Bf.push(i),Jn!==4&&(Jn=2),e===null)return!0;r=xi(r,n),n=e;do{switch(n.tag){case 3:return n.flags|=65536,t=s&-s,n.lanes|=t,t=bS(n.stateNode,r,t),K_(n,t),!1;case 1:if(e=n.type,i=n.stateNode,(n.flags&128)===0&&(typeof e.getDerivedStateFromError=="function"||i!==null&&typeof i.componentDidCatch=="function"&&(Tl===null||!Tl.has(i))))return n.flags|=65536,s&=-s,n.lanes|=s,s=D2(s),O2(s,t,n,r),K_(n,s),!1}n=n.return}while(n!==null);return!1}var N2=Error(je(461)),Ir=!1;function Fr(t,e,n,r){e.child=t===null?C2(e,null,n,r):ah(e,t.child,n,r)}function nC(t,e,n,r,s){n=n.render;var i=e.ref;if("ref"in r){var a={};for(var o in r)o!=="ref"&&(a[o]=r[o])}else a=r;return Xc(e),r=bT(t,e,n,a,i,s),o=xT(),t!==null&&!Ir?(ST(t,e,s),Eo(t,e,s)):(rn&&o&&fT(e),e.flags|=1,Fr(t,e,r,s),e.child)}function rC(t,e,n,r,s){if(t===null){var i=n.type;return typeof i=="function"&&!hT(i)&&i.defaultProps===void 0&&n.compare===null?(e.tag=15,e.type=i,M2(t,e,i,r,s)):(t=sy(n.type,null,r,e,e.mode,s),t.ref=e.ref,t.return=e,e.child=t)}if(i=t.child,!IT(t,s)){var a=i.memoizedProps;if(n=n.compare,n=n!==null?n:op,n(a,r)&&t.ref===e.ref)return Eo(t,e,s)}return e.flags|=1,t=go(i,r),t.ref=e.ref,t.return=e,e.child=t}function M2(t,e,n,r,s){if(t!==null){var i=t.memoizedProps;if(op(i,r)&&t.ref===e.ref)if(Ir=!1,e.pendingProps=r=i,IT(t,s))t.flags&131072&&(Ir=!0);else return e.lanes=t.lanes,Eo(t,e,s)}return xS(t,e,n,r,s)}function j2(t,e,n){var r=e.pendingProps,s=r.children,i=t!==null?t.memoizedState:null;if(r.mode==="hidden"){if(e.flags&128){if(r=i!==null?i.baseLanes|n:n,t!==null){for(s=e.child=t.child,i=0;s!==null;)i=i|s.lanes|s.childLanes,s=s.sibling;e.childLanes=i&~r}else e.childLanes=0,e.child=null;return sC(t,e,r,n)}if(n&536870912)e.memoizedState={baseLanes:0,cachePool:null},t!==null&&iy(e,i!==null?i.cachePool:null),i!==null?HR(e,i):mS(),k2(e);else return e.lanes=e.childLanes=536870912,sC(t,e,i!==null?i.baseLanes|n:n,n)}else i!==null?(iy(e,i.cachePool),HR(e,i),rl(),e.memoizedState=null):(t!==null&&iy(e,null),mS(),rl());return Fr(t,e,s,n),e.child}function sC(t,e,n,r){var s=gT();return s=s===null?null:{parent:br._currentValue,pool:s},e.memoizedState={baseLanes:n,cachePool:s},t!==null&&iy(e,null),mS(),k2(e),t!==null&&om(t,e,r,!0),null}function ly(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(je(284));(t===null||t.ref!==n)&&(e.flags|=4194816)}}function xS(t,e,n,r,s){return Xc(e),n=bT(t,e,n,r,void 0,s),r=xT(),t!==null&&!Ir?(ST(t,e,s),Eo(t,e,s)):(rn&&r&&fT(e),e.flags|=1,Fr(t,e,n,s),e.child)}function iC(t,e,n,r,s,i){return Xc(e),e.updateQueue=null,n=XN(e,r,n,s),YN(t),r=xT(),t!==null&&!Ir?(ST(t,e,i),Eo(t,e,i)):(rn&&r&&fT(e),e.flags|=1,Fr(t,e,n,i),e.child)}function aC(t,e,n,r,s){if(Xc(e),e.stateNode===null){var i=dd,a=n.contextType;typeof a=="object"&&a!==null&&(i=ts(a)),i=new n(r,i),e.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,i.updater=_S,e.stateNode=i,i._reactInternals=e,i=e.stateNode,i.props=r,i.state=e.memoizedState,i.refs={},yT(e),a=n.contextType,i.context=typeof a=="object"&&a!==null?ts(a):dd,i.state=e.memoizedState,a=n.getDerivedStateFromProps,typeof a=="function"&&(z_(e,n,a,r),i.state=e.memoizedState),typeof n.getDerivedStateFromProps=="function"||typeof i.getSnapshotBeforeUpdate=="function"||typeof i.UNSAFE_componentWillMount!="function"&&typeof i.componentWillMount!="function"||(a=i.state,typeof i.componentWillMount=="function"&&i.componentWillMount(),typeof i.UNSAFE_componentWillMount=="function"&&i.UNSAFE_componentWillMount(),a!==i.state&&_S.enqueueReplaceState(i,i.state,null),Nf(e,r,i,s),Of(),i.state=e.memoizedState),typeof i.componentDidMount=="function"&&(e.flags|=4194308),r=!0}else if(t===null){i=e.stateNode;var o=e.memoizedProps,l=Jc(n,o);i.props=l;var c=i.context,u=n.contextType;a=dd,typeof u=="object"&&u!==null&&(a=ts(u));var d=n.getDerivedStateFromProps;u=typeof d=="function"||typeof i.getSnapshotBeforeUpdate=="function",o=e.pendingProps!==o,u||typeof i.UNSAFE_componentWillReceiveProps!="function"&&typeof i.componentWillReceiveProps!="function"||(o||c!==a)&&eC(e,i,r,a),Xo=!1;var h=e.memoizedState;i.state=h,Nf(e,r,i,s),Of(),c=e.memoizedState,o||h!==c||Xo?(typeof d=="function"&&(z_(e,n,d,r),c=e.memoizedState),(l=Xo||ZR(e,n,l,r,h,c,a))?(u||typeof i.UNSAFE_componentWillMount!="function"&&typeof i.componentWillMount!="function"||(typeof i.componentWillMount=="function"&&i.componentWillMount(),typeof i.UNSAFE_componentWillMount=="function"&&i.UNSAFE_componentWillMount()),typeof i.componentDidMount=="function"&&(e.flags|=4194308)):(typeof i.componentDidMount=="function"&&(e.flags|=4194308),e.memoizedProps=r,e.memoizedState=c),i.props=r,i.state=c,i.context=a,r=l):(typeof i.componentDidMount=="function"&&(e.flags|=4194308),r=!1)}else{i=e.stateNode,fS(t,e),a=e.memoizedProps,u=Jc(n,a),i.props=u,d=e.pendingProps,h=i.context,c=n.contextType,l=dd,typeof c=="object"&&c!==null&&(l=ts(c)),o=n.getDerivedStateFromProps,(c=typeof o=="function"||typeof i.getSnapshotBeforeUpdate=="function")||typeof i.UNSAFE_componentWillReceiveProps!="function"&&typeof i.componentWillReceiveProps!="function"||(a!==d||h!==l)&&eC(e,i,r,l),Xo=!1,h=e.memoizedState,i.state=h,Nf(e,r,i,s),Of();var f=e.memoizedState;a!==d||h!==f||Xo||t!==null&&t.dependencies!==null&&Hy(t.dependencies)?(typeof o=="function"&&(z_(e,n,o,r),f=e.memoizedState),(u=Xo||ZR(e,n,u,r,h,f,l)||t!==null&&t.dependencies!==null&&Hy(t.dependencies))?(c||typeof i.UNSAFE_componentWillUpdate!="function"&&typeof i.componentWillUpdate!="function"||(typeof i.componentWillUpdate=="function"&&i.componentWillUpdate(r,f,l),typeof i.UNSAFE_componentWillUpdate=="function"&&i.UNSAFE_componentWillUpdate(r,f,l)),typeof i.componentDidUpdate=="function"&&(e.flags|=4),typeof i.getSnapshotBeforeUpdate=="function"&&(e.flags|=1024)):(typeof i.componentDidUpdate!="function"||a===t.memoizedProps&&h===t.memoizedState||(e.flags|=4),typeof i.getSnapshotBeforeUpdate!="function"||a===t.memoizedProps&&h===t.memoizedState||(e.flags|=1024),e.memoizedProps=r,e.memoizedState=f),i.props=r,i.state=f,i.context=l,r=u):(typeof i.componentDidUpdate!="function"||a===t.memoizedProps&&h===t.memoizedState||(e.flags|=4),typeof i.getSnapshotBeforeUpdate!="function"||a===t.memoizedProps&&h===t.memoizedState||(e.flags|=1024),r=!1)}return i=r,ly(t,e),r=(e.flags&128)!==0,i||r?(i=e.stateNode,n=r&&typeof n.getDerivedStateFromError!="function"?null:i.render(),e.flags|=1,t!==null&&r?(e.child=ah(e,t.child,null,s),e.child=ah(e,null,n,s)):Fr(t,e,n,s),e.memoizedState=i.state,t=e.child):t=Eo(t,e,s),t}function oC(t,e,n,r){return am(),e.flags|=256,Fr(t,e,n,r),e.child}var q_={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function W_(t){return{baseLanes:t,cachePool:KN()}}function Y_(t,e,n){return t=t!==null?t.childLanes&~n:0,e&&(t|=Si),t}function U2(t,e,n){var r=e.pendingProps,s=!1,i=(e.flags&128)!==0,a;if((a=i)||(a=t!==null&&t.memoizedState===null?!1:(Sr.current&2)!==0),a&&(s=!0,e.flags&=-129),a=(e.flags&32)!==0,e.flags&=-33,t===null){if(rn){if(s?nl(e):rl(),rn){var o=Qn,l;if(l=o){e:{for(l=o,o=ma;l.nodeType!==8;){if(!o){o=null;break e}if(l=Hi(l.nextSibling),l===null){o=null;break e}}o=l}o!==null?(e.memoizedState={dehydrated:o,treeContext:jc!==null?{id:co,overflow:uo}:null,retryLane:536870912,hydrationErrors:null},l=qs(18,null,null,0),l.stateNode=o,l.return=e,e.child=l,ls=e,Qn=null,l=!0):l=!1}l||Yc(e)}if(o=e.memoizedState,o!==null&&(o=o.dehydrated,o!==null))return NS(o)?e.lanes=32:e.lanes=536870912,null;fo(e)}return o=r.children,r=r.fallback,s?(rl(),s=e.mode,o=Zy({mode:"hidden",children:o},s),r=Mc(r,s,n,null),o.return=e,r.return=e,o.sibling=r,e.child=o,s=e.child,s.memoizedState=W_(n),s.childLanes=Y_(t,a,n),e.memoizedState=q_,r):(nl(e),SS(e,o))}if(l=t.memoizedState,l!==null&&(o=l.dehydrated,o!==null)){if(i)e.flags&256?(nl(e),e.flags&=-257,e=X_(t,e,n)):e.memoizedState!==null?(rl(),e.child=t.child,e.flags|=128,e=null):(rl(),s=r.fallback,o=e.mode,r=Zy({mode:"visible",children:r.children},o),s=Mc(s,o,n,null),s.flags|=2,r.return=e,s.return=e,r.sibling=s,e.child=r,ah(e,t.child,null,n),r=e.child,r.memoizedState=W_(n),r.childLanes=Y_(t,a,n),e.memoizedState=q_,e=s);else if(nl(e),NS(o)){if(a=o.nextSibling&&o.nextSibling.dataset,a)var c=a.dgst;a=c,r=Error(je(419)),r.stack="",r.digest=a,lp({value:r,source:null,stack:null}),e=X_(t,e,n)}else if(Ir||om(t,e,n,!1),a=(n&t.childLanes)!==0,Ir||a){if(a=Rn,a!==null&&(r=n&-n,r=r&42?1:tT(r),r=r&(a.suspendedLanes|n)?0:r,r!==0&&r!==l.retryLane))throw l.retryLane=r,Th(t,r),Js(a,t,r),N2;o.data==="$?"||CS(),e=X_(t,e,n)}else o.data==="$?"?(e.flags|=192,e.child=t.child,e=null):(t=l.treeContext,Qn=Hi(o.nextSibling),ls=e,rn=!0,Uc=null,ma=!1,t!==null&&(yi[vi++]=co,yi[vi++]=uo,yi[vi++]=jc,co=t.id,uo=t.overflow,jc=e),e=SS(e,r.children),e.flags|=4096);return e}return s?(rl(),s=r.fallback,o=e.mode,l=t.child,c=l.sibling,r=go(l,{mode:"hidden",children:r.children}),r.subtreeFlags=l.subtreeFlags&65011712,c!==null?s=go(c,s):(s=Mc(s,o,n,null),s.flags|=2),s.return=e,r.return=e,r.sibling=s,e.child=r,r=s,s=e.child,o=t.child.memoizedState,o===null?o=W_(n):(l=o.cachePool,l!==null?(c=br._currentValue,l=l.parent!==c?{parent:c,pool:c}:l):l=KN(),o={baseLanes:o.baseLanes|n,cachePool:l}),s.memoizedState=o,s.childLanes=Y_(t,a,n),e.memoizedState=q_,r):(nl(e),n=t.child,t=n.sibling,n=go(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 SS(t,e){return e=Zy({mode:"visible",children:e},t.mode),e.return=t,t.child=e}function Zy(t,e){return t=qs(22,t,null,e),t.lanes=0,t.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null},t}function X_(t,e,n){return ah(e,t.child,null,n),t=SS(e,e.pendingProps.children),t.flags|=2,e.memoizedState=null,t}function lC(t,e,n){t.lanes|=e;var r=t.alternate;r!==null&&(r.lanes|=e),cS(t.return,e,n)}function Q_(t,e,n,r,s){var i=t.memoizedState;i===null?t.memoizedState={isBackwards:e,rendering:null,renderingStartTime:0,last:r,tail:n,tailMode:s}:(i.isBackwards=e,i.rendering=null,i.renderingStartTime=0,i.last=r,i.tail=n,i.tailMode=s)}function B2(t,e,n){var r=e.pendingProps,s=r.revealOrder,i=r.tail;if(Fr(t,e,r.children,n),r=Sr.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&&lC(t,n,e);else if(t.tag===19)lC(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(Fn(Sr,r),s){case"forwards":for(n=e.child,s=null;n!==null;)t=n.alternate,t!==null&&Xy(t)===null&&(s=n),n=n.sibling;n=s,n===null?(s=e.child,e.child=null):(s=n.sibling,n.sibling=null),Q_(e,!1,s,n,i);break;case"backwards":for(n=null,s=e.child,e.child=null;s!==null;){if(t=s.alternate,t!==null&&Xy(t)===null){e.child=s;break}t=s.sibling,s.sibling=n,n=s,s=t}Q_(e,!0,n,null,i);break;case"together":Q_(e,!1,null,null,void 0);break;default:e.memoizedState=null}return e.child}function Eo(t,e,n){if(t!==null&&(e.dependencies=t.dependencies),jl|=e.lanes,!(n&e.childLanes))if(t!==null){if(om(t,e,n,!1),(n&e.childLanes)===0)return null}else return null;if(t!==null&&e.child!==t.child)throw Error(je(153));if(e.child!==null){for(t=e.child,n=go(t,t.pendingProps),e.child=n,n.return=e;t.sibling!==null;)t=t.sibling,n=n.sibling=go(t,t.pendingProps),n.return=e;n.sibling=null}return e.child}function IT(t,e){return t.lanes&e?!0:(t=t.dependencies,!!(t!==null&&Hy(t)))}function M6(t,e,n){switch(e.tag){case 3:jy(e,e.stateNode.containerInfo),tl(e,br,t.memoizedState.cache),am();break;case 27:case 5:Qx(e);break;case 4:jy(e,e.stateNode.containerInfo);break;case 10:tl(e,e.type,e.memoizedProps.value);break;case 13:var r=e.memoizedState;if(r!==null)return r.dehydrated!==null?(nl(e),e.flags|=128,null):n&e.child.childLanes?U2(t,e,n):(nl(e),t=Eo(t,e,n),t!==null?t.sibling:null);nl(e);break;case 19:var s=(t.flags&128)!==0;if(r=(n&e.childLanes)!==0,r||(om(t,e,n,!1),r=(n&e.childLanes)!==0),s){if(r)return B2(t,e,n);e.flags|=128}if(s=e.memoizedState,s!==null&&(s.rendering=null,s.tail=null,s.lastEffect=null),Fn(Sr,Sr.current),r)break;return null;case 22:case 23:return e.lanes=0,j2(t,e,n);case 24:tl(e,br,t.memoizedState.cache)}return Eo(t,e,n)}function F2(t,e,n){if(t!==null)if(t.memoizedProps!==e.pendingProps)Ir=!0;else{if(!IT(t,n)&&!(e.flags&128))return Ir=!1,M6(t,e,n);Ir=!!(t.flags&131072)}else Ir=!1,rn&&e.flags&1048576&&VN(e,Ky,e.index);switch(e.lanes=0,e.tag){case 16:e:{t=e.pendingProps;var r=e.elementType,s=r._init;if(r=s(r._payload),e.type=r,typeof r=="function")hT(r)?(t=Jc(r,t),e.tag=1,e=aC(null,e,r,t,n)):(e.tag=0,e=xS(null,e,r,t,n));else{if(r!=null){if(s=r.$$typeof,s===Jw){e.tag=11,e=nC(null,e,r,t,n);break e}else if(s===Zw){e.tag=14,e=rC(null,e,r,t,n);break e}}throw e=Yx(r)||r,Error(je(306,e,""))}}return e;case 0:return xS(t,e,e.type,e.pendingProps,n);case 1:return r=e.type,s=Jc(r,e.pendingProps),aC(t,e,r,s,n);case 3:e:{if(jy(e,e.stateNode.containerInfo),t===null)throw Error(je(387));r=e.pendingProps;var i=e.memoizedState;s=i.element,fS(t,e),Nf(e,r,null,n);var a=e.memoizedState;if(r=a.cache,tl(e,br,r),r!==i.cache&&uS(e,[br],n,!0),Of(),r=a.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:a.cache},e.updateQueue.baseState=i,e.memoizedState=i,e.flags&256){e=oC(t,e,r,n);break e}else if(r!==s){s=xi(Error(je(424)),e),lp(s),e=oC(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(Qn=Hi(t.firstChild),ls=e,rn=!0,Uc=null,ma=!0,n=C2(e,null,r,n),e.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling}else{if(am(),r===s){e=Eo(t,e,n);break e}Fr(t,e,r,n)}e=e.child}return e;case 26:return ly(t,e),t===null?(n=TC(e.type,null,e.pendingProps,null))?e.memoizedState=n:rn||(n=e.type,t=e.pendingProps,r=a0(Sl.current).createElement(n),r[es]=e,r[Is]=t,qr(r,n,t),Lr(r),e.stateNode=r):e.memoizedState=TC(e.type,t.memoizedProps,e.pendingProps,t.memoizedState),null;case 27:return Qx(e),t===null&&rn&&(r=e.stateNode=AM(e.type,e.pendingProps,Sl.current),ls=e,ma=!0,s=Qn,Wl(e.type)?(MS=s,Qn=Hi(r.firstChild)):Qn=s),Fr(t,e,e.pendingProps.children,n),ly(t,e),t===null&&(e.flags|=4194304),e.child;case 5:return t===null&&rn&&((s=r=Qn)&&(r=uV(r,e.type,e.pendingProps,ma),r!==null?(e.stateNode=r,ls=e,Qn=Hi(r.firstChild),ma=!1,s=!0):s=!1),s||Yc(e)),Qx(e),s=e.type,i=e.pendingProps,a=t!==null?t.memoizedProps:null,r=i.children,DS(s,i)?r=null:a!==null&&DS(s,a)&&(e.flags|=32),e.memoizedState!==null&&(s=bT(t,e,C6,null,null,n),pp._currentValue=s),ly(t,e),Fr(t,e,r,n),e.child;case 6:return t===null&&rn&&((t=n=Qn)&&(n=dV(n,e.pendingProps,ma),n!==null?(e.stateNode=n,ls=e,Qn=null,t=!0):t=!1),t||Yc(e)),null;case 13:return U2(t,e,n);case 4:return jy(e,e.stateNode.containerInfo),r=e.pendingProps,t===null?e.child=ah(e,null,r,n):Fr(t,e,r,n),e.child;case 11:return nC(t,e,e.type,e.pendingProps,n);case 7:return Fr(t,e,e.pendingProps,n),e.child;case 8:return Fr(t,e,e.pendingProps.children,n),e.child;case 12:return Fr(t,e,e.pendingProps.children,n),e.child;case 10:return r=e.pendingProps,tl(e,e.type,r.value),Fr(t,e,r.children,n),e.child;case 9:return s=e.type._context,r=e.pendingProps.children,Xc(e),s=ts(s),r=r(s),e.flags|=1,Fr(t,e,r,n),e.child;case 14:return rC(t,e,e.type,e.pendingProps,n);case 15:return M2(t,e,e.type,e.pendingProps,n);case 19:return B2(t,e,n);case 31:return r=e.pendingProps,n=e.mode,r={mode:r.mode,children:r.children},t===null?(n=Zy(r,n),n.ref=e.ref,e.child=n,n.return=e,e=n):(n=go(t.child,r),n.ref=e.ref,e.child=n,n.return=e,e=n),e;case 22:return j2(t,e,n);case 24:return Xc(e),r=ts(br),t===null?(s=gT(),s===null&&(s=Rn,i=mT(),s.pooledCache=i,i.refCount++,i!==null&&(s.pooledCacheLanes|=n),s=i),e.memoizedState={parent:r,cache:s},yT(e),tl(e,br,s)):(t.lanes&n&&(fS(t,e),Nf(e,null,null,n),Of()),s=t.memoizedState,i=e.memoizedState,s.parent!==r?(s={parent:r,cache:r},e.memoizedState=s,e.lanes===0&&(e.memoizedState=e.updateQueue.baseState=s),tl(e,br,r)):(r=i.cache,tl(e,br,r),r!==s.cache&&uS(e,[br],n,!0))),Fr(t,e,e.pendingProps.children,n),e.child;case 29:throw e.pendingProps}throw Error(je(156,e.tag))}function Va(t){t.flags|=4}function cC(t,e){if(e.type!=="stylesheet"||e.state.loading&4)t.flags&=-16777217;else if(t.flags|=16777216,!kM(e)){if(e=Ai.current,e!==null&&((Zt&4194048)===Zt?Ta!==null:(Zt&62914560)!==Zt&&!(Zt&536870912)||e!==Ta))throw Pf=hS,HN;t.flags|=8192}}function ig(t,e){e!==null&&(t.flags|=4),t.flags&16384&&(e=t.tag!==22?hN():536870912,t.lanes|=e,oh|=e)}function rf(t,e){if(!rn)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 Vn(t){var e=t.alternate!==null&&t.alternate.child===t.child,n=0,r=0;if(e)for(var s=t.child;s!==null;)n|=s.lanes|s.childLanes,r|=s.subtreeFlags&65011712,r|=s.flags&65011712,s.return=t,s=s.sibling;else for(s=t.child;s!==null;)n|=s.lanes|s.childLanes,r|=s.subtreeFlags,r|=s.flags,s.return=t,s=s.sibling;return t.subtreeFlags|=r,t.childLanes=n,e}function j6(t,e,n){var r=e.pendingProps;switch(pT(e),e.tag){case 31:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Vn(e),null;case 1:return Vn(e),null;case 3:return n=e.stateNode,r=null,t!==null&&(r=t.memoizedState.cache),e.memoizedState.cache!==r&&(e.flags|=2048),yo(br),eh(),n.pendingContext&&(n.context=n.pendingContext,n.pendingContext=null),(t===null||t.child===null)&&(tf(e)?Va(e):t===null||t.memoizedState.isDehydrated&&!(e.flags&256)||(e.flags|=1024,BR())),Vn(e),null;case 26:return n=e.memoizedState,t===null?(Va(e),n!==null?(Vn(e),cC(e,n)):(Vn(e),e.flags&=-16777217)):n?n!==t.memoizedState?(Va(e),Vn(e),cC(e,n)):(Vn(e),e.flags&=-16777217):(t.memoizedProps!==r&&Va(e),Vn(e),e.flags&=-16777217),null;case 27:Uy(e),n=Sl.current;var s=e.type;if(t!==null&&e.stateNode!=null)t.memoizedProps!==r&&Va(e);else{if(!r){if(e.stateNode===null)throw Error(je(166));return Vn(e),null}t=Ea.current,tf(e)?jR(e):(t=AM(s,r,n),e.stateNode=t,Va(e))}return Vn(e),null;case 5:if(Uy(e),n=e.type,t!==null&&e.stateNode!=null)t.memoizedProps!==r&&Va(e);else{if(!r){if(e.stateNode===null)throw Error(je(166));return Vn(e),null}if(t=Ea.current,tf(e))jR(e);else{switch(s=a0(Sl.current),t){case 1:t=s.createElementNS("http://www.w3.org/2000/svg",n);break;case 2:t=s.createElementNS("http://www.w3.org/1998/Math/MathML",n);break;default:switch(n){case"svg":t=s.createElementNS("http://www.w3.org/2000/svg",n);break;case"math":t=s.createElementNS("http://www.w3.org/1998/Math/MathML",n);break;case"script":t=s.createElement("div"),t.innerHTML="<script><\/script>",t=t.removeChild(t.firstChild);break;case"select":t=typeof r.is=="string"?s.createElement("select",{is:r.is}):s.createElement("select"),r.multiple?t.multiple=!0:r.size&&(t.size=r.size);break;default:t=typeof r.is=="string"?s.createElement(n,{is:r.is}):s.createElement(n)}}t[es]=e,t[Is]=r;e:for(s=e.child;s!==null;){if(s.tag===5||s.tag===6)t.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===e)break e;for(;s.sibling===null;){if(s.return===null||s.return===e)break e;s=s.return}s.sibling.return=s.return,s=s.sibling}e.stateNode=t;e:switch(qr(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&&Va(e)}}return Vn(e),e.flags&=-16777217,null;case 6:if(t&&e.stateNode!=null)t.memoizedProps!==r&&Va(e);else{if(typeof r!="string"&&e.stateNode===null)throw Error(je(166));if(t=Sl.current,tf(e)){if(t=e.stateNode,n=e.memoizedProps,r=null,s=ls,s!==null)switch(s.tag){case 27:case 5:r=s.memoizedProps}t[es]=e,t=!!(t.nodeValue===n||r!==null&&r.suppressHydrationWarning===!0||EM(t.nodeValue,n)),t||Yc(e)}else t=a0(t).createTextNode(r),t[es]=e,e.stateNode=t}return Vn(e),null;case 13:if(r=e.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(s=tf(e),r!==null&&r.dehydrated!==null){if(t===null){if(!s)throw Error(je(318));if(s=e.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(je(317));s[es]=e}else am(),!(e.flags&128)&&(e.memoizedState=null),e.flags|=4;Vn(e),s=!1}else s=BR(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=s),s=!0;if(!s)return e.flags&256?(fo(e),e):(fo(e),null)}if(fo(e),e.flags&128)return e.lanes=n,e;if(n=r!==null,t=t!==null&&t.memoizedState!==null,n){r=e.child,s=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(s=r.alternate.memoizedState.cachePool.pool);var i=null;r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(i=r.memoizedState.cachePool.pool),i!==s&&(r.flags|=2048)}return n!==t&&n&&(e.child.flags|=8192),ig(e,e.updateQueue),Vn(e),null;case 4:return eh(),t===null&&BT(e.stateNode.containerInfo),Vn(e),null;case 10:return yo(e.type),Vn(e),null;case 19:if(Pr(Sr),s=e.memoizedState,s===null)return Vn(e),null;if(r=(e.flags&128)!==0,i=s.rendering,i===null)if(r)rf(s,!1);else{if(Jn!==0||t!==null&&t.flags&128)for(t=e.child;t!==null;){if(i=Xy(t),i!==null){for(e.flags|=128,rf(s,!1),t=i.updateQueue,e.updateQueue=t,ig(e,t),e.subtreeFlags=0,t=n,n=e.child;n!==null;)$N(n,t),n=n.sibling;return Fn(Sr,Sr.current&1|2),e.child}t=t.sibling}s.tail!==null&&wa()>t0&&(e.flags|=128,r=!0,rf(s,!1),e.lanes=4194304)}else{if(!r)if(t=Xy(i),t!==null){if(e.flags|=128,r=!0,t=t.updateQueue,e.updateQueue=t,ig(e,t),rf(s,!0),s.tail===null&&s.tailMode==="hidden"&&!i.alternate&&!rn)return Vn(e),null}else 2*wa()-s.renderingStartTime>t0&&n!==536870912&&(e.flags|=128,r=!0,rf(s,!1),e.lanes=4194304);s.isBackwards?(i.sibling=e.child,e.child=i):(t=s.last,t!==null?t.sibling=i:e.child=i,s.last=i)}return s.tail!==null?(e=s.tail,s.rendering=e,s.tail=e.sibling,s.renderingStartTime=wa(),e.sibling=null,t=Sr.current,Fn(Sr,r?t&1|2:t&1),e):(Vn(e),null);case 22:case 23:return fo(e),vT(),r=e.memoizedState!==null,t!==null?t.memoizedState!==null!==r&&(e.flags|=8192):r&&(e.flags|=8192),r?n&536870912&&!(e.flags&128)&&(Vn(e),e.subtreeFlags&6&&(e.flags|=8192)):Vn(e),n=e.updateQueue,n!==null&&ig(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&&Pr(Bc),null;case 24:return n=null,t!==null&&(n=t.memoizedState.cache),e.memoizedState.cache!==n&&(e.flags|=2048),yo(br),Vn(e),null;case 25:return null;case 30:return null}throw Error(je(156,e.tag))}function U6(t,e){switch(pT(e),e.tag){case 1:return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return yo(br),eh(),t=e.flags,t&65536&&!(t&128)?(e.flags=t&-65537|128,e):null;case 26:case 27:case 5:return Uy(e),null;case 13:if(fo(e),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(je(340));am()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return Pr(Sr),null;case 4:return eh(),null;case 10:return yo(e.type),null;case 22:case 23:return fo(e),vT(),t!==null&&Pr(Bc),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 24:return yo(br),null;case 25:return null;default:return null}}function $2(t,e){switch(pT(e),e.tag){case 3:yo(br),eh();break;case 26:case 27:case 5:Uy(e);break;case 4:eh();break;case 13:fo(e);break;case 19:Pr(Sr);break;case 10:yo(e.type);break;case 22:case 23:fo(e),vT(),t!==null&&Pr(Bc);break;case 24:yo(br)}}function hm(t,e){try{var n=e.updateQueue,r=n!==null?n.lastEffect:null;if(r!==null){var s=r.next;n=s;do{if((n.tag&t)===t){r=void 0;var i=n.create,a=n.inst;r=i(),a.destroy=r}n=n.next}while(n!==s)}}catch(o){xn(e,e.return,o)}}function Ml(t,e,n){try{var r=e.updateQueue,s=r!==null?r.lastEffect:null;if(s!==null){var i=s.next;r=i;do{if((r.tag&t)===t){var a=r.inst,o=a.destroy;if(o!==void 0){a.destroy=void 0,s=e;var l=n,c=o;try{c()}catch(u){xn(s,l,u)}}}r=r.next}while(r!==i)}}catch(u){xn(e,e.return,u)}}function V2(t){var e=t.updateQueue;if(e!==null){var n=t.stateNode;try{WN(e,n)}catch(r){xn(t,t.return,r)}}}function G2(t,e,n){n.props=Jc(t.type,t.memoizedProps),n.state=t.memoizedState;try{n.componentWillUnmount()}catch(r){xn(t,e,r)}}function jf(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(s){xn(t,e,s)}}function ya(t,e){var n=t.ref,r=t.refCleanup;if(n!==null)if(typeof r=="function")try{r()}catch(s){xn(t,e,s)}finally{t.refCleanup=null,t=t.alternate,t!=null&&(t.refCleanup=null)}else if(typeof n=="function")try{n(null)}catch(s){xn(t,e,s)}else n.current=null}function K2(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(s){xn(t,t.return,s)}}function J_(t,e,n){try{var r=t.stateNode;iV(r,t.type,n,e),r[Is]=e}catch(s){xn(t,t.return,s)}}function H2(t){return t.tag===5||t.tag===3||t.tag===26||t.tag===27&&Wl(t.type)||t.tag===4}function Z_(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||H2(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&&Wl(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 ES(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=vv));else if(r!==4&&(r===27&&Wl(t.type)&&(n=t.stateNode,e=null),t=t.child,t!==null))for(ES(t,e,n),t=t.sibling;t!==null;)ES(t,e,n),t=t.sibling}function e0(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&&Wl(t.type)&&(n=t.stateNode),t=t.child,t!==null))for(e0(t,e,n),t=t.sibling;t!==null;)e0(t,e,n),t=t.sibling}function z2(t){var e=t.stateNode,n=t.memoizedProps;try{for(var r=t.type,s=e.attributes;s.length;)e.removeAttributeNode(s[0]);qr(e,r,n),e[es]=t,e[Is]=n}catch(i){xn(t,t.return,i)}}var oo=!1,sr=!1,eb=!1,uC=typeof WeakSet=="function"?WeakSet:Set,kr=null;function B6(t,e){if(t=t.containerInfo,IS=u0,t=DN(t),cT(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 s=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.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||s!==0&&d.nodeType!==3||(o=a+s),d!==i||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===s&&(o=a),h===i&&++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(PS={focusedElem:t,selectionRange:n},u0=!1,kr=e;kr!==null;)if(e=kr,t=e.child,(e.subtreeFlags&1024)!==0&&t!==null)t.return=e,kr=t;else for(;kr!==null;){switch(e=kr,i=e.alternate,t=e.flags,e.tag){case 0:break;case 11:case 15:break;case 1:if(t&1024&&i!==null){t=void 0,n=e,s=i.memoizedProps,i=i.memoizedState,r=n.stateNode;try{var m=Jc(n.type,s,n.elementType===n.type);t=r.getSnapshotBeforeUpdate(m,i),r.__reactInternalSnapshotBeforeUpdate=t}catch(g){xn(n,n.return,g)}}break;case 3:if(t&1024){if(t=e.stateNode.containerInfo,n=t.nodeType,n===9)OS(t);else if(n===1)switch(t.nodeName){case"HEAD":case"HTML":case"BODY":OS(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(je(163))}if(t=e.sibling,t!==null){t.return=e.return,kr=t;break}kr=e.return}}function q2(t,e,n){var r=n.flags;switch(n.tag){case 0:case 11:case 15:Bo(t,n),r&4&&hm(5,n);break;case 1:if(Bo(t,n),r&4)if(t=n.stateNode,e===null)try{t.componentDidMount()}catch(a){xn(n,n.return,a)}else{var s=Jc(n.type,e.memoizedProps);e=e.memoizedState;try{t.componentDidUpdate(s,e,t.__reactInternalSnapshotBeforeUpdate)}catch(a){xn(n,n.return,a)}}r&64&&V2(n),r&512&&jf(n,n.return);break;case 3:if(Bo(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{WN(t,e)}catch(a){xn(n,n.return,a)}}break;case 27:e===null&&r&4&&z2(n);case 26:case 5:Bo(t,n),e===null&&r&4&&K2(n),r&512&&jf(n,n.return);break;case 12:Bo(t,n);break;case 13:Bo(t,n),r&4&&X2(t,n),r&64&&(t=n.memoizedState,t!==null&&(t=t.dehydrated,t!==null&&(n=W6.bind(null,n),hV(t,n))));break;case 22:if(r=n.memoizedState!==null||oo,!r){e=e!==null&&e.memoizedState!==null||sr,s=oo;var i=sr;oo=r,(sr=e)&&!i?Ko(t,n,(n.subtreeFlags&8772)!==0):Bo(t,n),oo=s,sr=i}break;case 30:break;default:Bo(t,n)}}function W2(t){var e=t.alternate;e!==null&&(t.alternate=null,W2(e)),t.child=null,t.deletions=null,t.sibling=null,t.tag===5&&(e=t.stateNode,e!==null&&rT(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 jn=null,As=!1;function Ga(t,e,n){for(n=n.child;n!==null;)Y2(t,e,n),n=n.sibling}function Y2(t,e,n){if(Ys&&typeof Ys.onCommitFiberUnmount=="function")try{Ys.onCommitFiberUnmount(tm,n)}catch{}switch(n.tag){case 26:sr||ya(n,e),Ga(t,e,n),n.memoizedState?n.memoizedState.count--:n.stateNode&&(n=n.stateNode,n.parentNode.removeChild(n));break;case 27:sr||ya(n,e);var r=jn,s=As;Wl(n.type)&&(jn=n.stateNode,As=!1),Ga(t,e,n),$f(n.stateNode),jn=r,As=s;break;case 5:sr||ya(n,e);case 6:if(r=jn,s=As,jn=null,Ga(t,e,n),jn=r,As=s,jn!==null)if(As)try{(jn.nodeType===9?jn.body:jn.nodeName==="HTML"?jn.ownerDocument.body:jn).removeChild(n.stateNode)}catch(i){xn(n,e,i)}else try{jn.removeChild(n.stateNode)}catch(i){xn(n,e,i)}break;case 18:jn!==null&&(As?(t=jn,SC(t.nodeType===9?t.body:t.nodeName==="HTML"?t.ownerDocument.body:t,n.stateNode),yp(t)):SC(jn,n.stateNode));break;case 4:r=jn,s=As,jn=n.stateNode.containerInfo,As=!0,Ga(t,e,n),jn=r,As=s;break;case 0:case 11:case 14:case 15:sr||Ml(2,n,e),sr||Ml(4,n,e),Ga(t,e,n);break;case 1:sr||(ya(n,e),r=n.stateNode,typeof r.componentWillUnmount=="function"&&G2(n,e,r)),Ga(t,e,n);break;case 21:Ga(t,e,n);break;case 22:sr=(r=sr)||n.memoizedState!==null,Ga(t,e,n),sr=r;break;default:Ga(t,e,n)}}function X2(t,e){if(e.memoizedState===null&&(t=e.alternate,t!==null&&(t=t.memoizedState,t!==null&&(t=t.dehydrated,t!==null))))try{yp(t)}catch(n){xn(e,e.return,n)}}function F6(t){switch(t.tag){case 13:case 19:var e=t.stateNode;return e===null&&(e=t.stateNode=new uC),e;case 22:return t=t.stateNode,e=t._retryCache,e===null&&(e=t._retryCache=new uC),e;default:throw Error(je(435,t.tag))}}function tb(t,e){var n=F6(t);e.forEach(function(r){var s=Y6.bind(null,t,r);n.has(r)||(n.add(r),r.then(s,s))})}function Ms(t,e){var n=e.deletions;if(n!==null)for(var r=0;r<n.length;r++){var s=n[r],i=t,a=e,o=a;e:for(;o!==null;){switch(o.tag){case 27:if(Wl(o.type)){jn=o.stateNode,As=!1;break e}break;case 5:jn=o.stateNode,As=!1;break e;case 3:case 4:jn=o.stateNode.containerInfo,As=!0;break e}o=o.return}if(jn===null)throw Error(je(160));Y2(i,a,s),jn=null,As=!1,i=s.alternate,i!==null&&(i.return=null),s.return=null}if(e.subtreeFlags&13878)for(e=e.child;e!==null;)Q2(e,t),e=e.sibling}var Vi=null;function Q2(t,e){var n=t.alternate,r=t.flags;switch(t.tag){case 0:case 11:case 14:case 15:Ms(e,t),js(t),r&4&&(Ml(3,t,t.return),hm(3,t),Ml(5,t,t.return));break;case 1:Ms(e,t),js(t),r&512&&(sr||n===null||ya(n,n.return)),r&64&&oo&&(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 s=Vi;if(Ms(e,t),js(t),r&512&&(sr||n===null||ya(n,n.return)),r&4){var i=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,s=s.ownerDocument||s;t:switch(r){case"title":i=s.getElementsByTagName("title")[0],(!i||i[sm]||i[es]||i.namespaceURI==="http://www.w3.org/2000/svg"||i.hasAttribute("itemprop"))&&(i=s.createElement(r),s.head.insertBefore(i,s.querySelector("head > title"))),qr(i,r,n),i[es]=t,Lr(i),r=i;break e;case"link":var a=RC("link","href",s).get(r+(n.href||""));if(a){for(var o=0;o<a.length;o++)if(i=a[o],i.getAttribute("href")===(n.href==null||n.href===""?null:n.href)&&i.getAttribute("rel")===(n.rel==null?null:n.rel)&&i.getAttribute("title")===(n.title==null?null:n.title)&&i.getAttribute("crossorigin")===(n.crossOrigin==null?null:n.crossOrigin)){a.splice(o,1);break t}}i=s.createElement(r),qr(i,r,n),s.head.appendChild(i);break;case"meta":if(a=RC("meta","content",s).get(r+(n.content||""))){for(o=0;o<a.length;o++)if(i=a[o],i.getAttribute("content")===(n.content==null?null:""+n.content)&&i.getAttribute("name")===(n.name==null?null:n.name)&&i.getAttribute("property")===(n.property==null?null:n.property)&&i.getAttribute("http-equiv")===(n.httpEquiv==null?null:n.httpEquiv)&&i.getAttribute("charset")===(n.charSet==null?null:n.charSet)){a.splice(o,1);break t}}i=s.createElement(r),qr(i,r,n),s.head.appendChild(i);break;default:throw Error(je(468,r))}i[es]=t,Lr(i),r=i}t.stateNode=r}else CC(s,t.type,t.stateNode);else t.stateNode=AC(s,r,t.memoizedProps);else i!==r?(i===null?n.stateNode!==null&&(n=n.stateNode,n.parentNode.removeChild(n)):i.count--,r===null?CC(s,t.type,t.stateNode):AC(s,r,t.memoizedProps)):r===null&&t.stateNode!==null&&J_(t,t.memoizedProps,n.memoizedProps)}break;case 27:Ms(e,t),js(t),r&512&&(sr||n===null||ya(n,n.return)),n!==null&&r&4&&J_(t,t.memoizedProps,n.memoizedProps);break;case 5:if(Ms(e,t),js(t),r&512&&(sr||n===null||ya(n,n.return)),t.flags&32){s=t.stateNode;try{nh(s,"")}catch(f){xn(t,t.return,f)}}r&4&&t.stateNode!=null&&(s=t.memoizedProps,J_(t,s,n!==null?n.memoizedProps:s)),r&1024&&(eb=!0);break;case 6:if(Ms(e,t),js(t),r&4){if(t.stateNode===null)throw Error(je(162));r=t.memoizedProps,n=t.stateNode;try{n.nodeValue=r}catch(f){xn(t,t.return,f)}}break;case 3:if(dy=null,s=Vi,Vi=o0(e.containerInfo),Ms(e,t),Vi=s,js(t),r&4&&n!==null&&n.memoizedState.isDehydrated)try{yp(e.containerInfo)}catch(f){xn(t,t.return,f)}eb&&(eb=!1,J2(t));break;case 4:r=Vi,Vi=o0(t.stateNode.containerInfo),Ms(e,t),js(t),Vi=r;break;case 12:Ms(e,t),js(t);break;case 13:Ms(e,t),js(t),t.child.flags&8192&&t.memoizedState!==null!=(n!==null&&n.memoizedState!==null)&&(MT=wa()),r&4&&(r=t.updateQueue,r!==null&&(t.updateQueue=null,tb(t,r)));break;case 22:s=t.memoizedState!==null;var l=n!==null&&n.memoizedState!==null,c=oo,u=sr;if(oo=c||s,sr=u||l,Ms(e,t),sr=u,oo=c,js(t),r&8192)e:for(e=t.stateNode,e._visibility=s?e._visibility&-2:e._visibility|1,s&&(n===null||l||oo||sr||pc(t)),n=null,e=t;;){if(e.tag===5||e.tag===26){if(n===null){l=n=e;try{if(i=l.stateNode,s)a=i.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){xn(l,l.return,f)}}}else if(e.tag===6){if(n===null){l=e;try{l.stateNode.nodeValue=s?"":l.memoizedProps}catch(f){xn(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,tb(t,n))));break;case 19:Ms(e,t),js(t),r&4&&(r=t.updateQueue,r!==null&&(t.updateQueue=null,tb(t,r)));break;case 30:break;case 21:break;default:Ms(e,t),js(t)}}function js(t){var e=t.flags;if(e&2){try{for(var n,r=t.return;r!==null;){if(H2(r)){n=r;break}r=r.return}if(n==null)throw Error(je(160));switch(n.tag){case 27:var s=n.stateNode,i=Z_(t);e0(t,i,s);break;case 5:var a=n.stateNode;n.flags&32&&(nh(a,""),n.flags&=-33);var o=Z_(t);e0(t,o,a);break;case 3:case 4:var l=n.stateNode.containerInfo,c=Z_(t);ES(t,c,l);break;default:throw Error(je(161))}}catch(u){xn(t,t.return,u)}t.flags&=-3}e&4096&&(t.flags&=-4097)}function J2(t){if(t.subtreeFlags&1024)for(t=t.child;t!==null;){var e=t;J2(e),e.tag===5&&e.flags&1024&&e.stateNode.reset(),t=t.sibling}}function Bo(t,e){if(e.subtreeFlags&8772)for(e=e.child;e!==null;)q2(t,e.alternate,e),e=e.sibling}function pc(t){for(t=t.child;t!==null;){var e=t;switch(e.tag){case 0:case 11:case 14:case 15:Ml(4,e,e.return),pc(e);break;case 1:ya(e,e.return);var n=e.stateNode;typeof n.componentWillUnmount=="function"&&G2(e,e.return,n),pc(e);break;case 27:$f(e.stateNode);case 26:case 5:ya(e,e.return),pc(e);break;case 22:e.memoizedState===null&&pc(e);break;case 30:pc(e);break;default:pc(e)}t=t.sibling}}function Ko(t,e,n){for(n=n&&(e.subtreeFlags&8772)!==0,e=e.child;e!==null;){var r=e.alternate,s=t,i=e,a=i.flags;switch(i.tag){case 0:case 11:case 15:Ko(s,i,n),hm(4,i);break;case 1:if(Ko(s,i,n),r=i,s=r.stateNode,typeof s.componentDidMount=="function")try{s.componentDidMount()}catch(c){xn(r,r.return,c)}if(r=i,s=r.updateQueue,s!==null){var o=r.stateNode;try{var l=s.shared.hiddenCallbacks;if(l!==null)for(s.shared.hiddenCallbacks=null,s=0;s<l.length;s++)qN(l[s],o)}catch(c){xn(r,r.return,c)}}n&&a&64&&V2(i),jf(i,i.return);break;case 27:z2(i);case 26:case 5:Ko(s,i,n),n&&r===null&&a&4&&K2(i),jf(i,i.return);break;case 12:Ko(s,i,n);break;case 13:Ko(s,i,n),n&&a&4&&X2(s,i);break;case 22:i.memoizedState===null&&Ko(s,i,n),jf(i,i.return);break;case 30:break;default:Ko(s,i,n)}e=e.sibling}}function PT(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&&lm(n))}function DT(t,e){t=null,e.alternate!==null&&(t=e.alternate.memoizedState.cache),e=e.memoizedState.cache,e!==t&&(e.refCount++,t!=null&&lm(t))}function na(t,e,n,r){if(e.subtreeFlags&10256)for(e=e.child;e!==null;)Z2(t,e,n,r),e=e.sibling}function Z2(t,e,n,r){var s=e.flags;switch(e.tag){case 0:case 11:case 15:na(t,e,n,r),s&2048&&hm(9,e);break;case 1:na(t,e,n,r);break;case 3:na(t,e,n,r),s&2048&&(t=null,e.alternate!==null&&(t=e.alternate.memoizedState.cache),e=e.memoizedState.cache,e!==t&&(e.refCount++,t!=null&&lm(t)));break;case 12:if(s&2048){na(t,e,n,r),t=e.stateNode;try{var i=e.memoizedProps,a=i.id,o=i.onPostCommit;typeof o=="function"&&o(a,e.alternate===null?"mount":"update",t.passiveEffectDuration,-0)}catch(l){xn(e,e.return,l)}}else na(t,e,n,r);break;case 13:na(t,e,n,r);break;case 23:break;case 22:i=e.stateNode,a=e.alternate,e.memoizedState!==null?i._visibility&2?na(t,e,n,r):Uf(t,e):i._visibility&2?na(t,e,n,r):(i._visibility|=2,Wu(t,e,n,r,(e.subtreeFlags&10256)!==0)),s&2048&&PT(a,e);break;case 24:na(t,e,n,r),s&2048&&DT(e.alternate,e);break;default:na(t,e,n,r)}}function Wu(t,e,n,r,s){for(s=s&&(e.subtreeFlags&10256)!==0,e=e.child;e!==null;){var i=t,a=e,o=n,l=r,c=a.flags;switch(a.tag){case 0:case 11:case 15:Wu(i,a,o,l,s),hm(8,a);break;case 23:break;case 22:var u=a.stateNode;a.memoizedState!==null?u._visibility&2?Wu(i,a,o,l,s):Uf(i,a):(u._visibility|=2,Wu(i,a,o,l,s)),s&&c&2048&&PT(a.alternate,a);break;case 24:Wu(i,a,o,l,s),s&&c&2048&&DT(a.alternate,a);break;default:Wu(i,a,o,l,s)}e=e.sibling}}function Uf(t,e){if(e.subtreeFlags&10256)for(e=e.child;e!==null;){var n=t,r=e,s=r.flags;switch(r.tag){case 22:Uf(n,r),s&2048&&PT(r.alternate,r);break;case 24:Uf(n,r),s&2048&&DT(r.alternate,r);break;default:Uf(n,r)}e=e.sibling}}var _f=8192;function Au(t){if(t.subtreeFlags&_f)for(t=t.child;t!==null;)eM(t),t=t.sibling}function eM(t){switch(t.tag){case 26:Au(t),t.flags&_f&&t.memoizedState!==null&&TV(Vi,t.memoizedState,t.memoizedProps);break;case 5:Au(t);break;case 3:case 4:var e=Vi;Vi=o0(t.stateNode.containerInfo),Au(t),Vi=e;break;case 22:t.memoizedState===null&&(e=t.alternate,e!==null&&e.memoizedState!==null?(e=_f,_f=16777216,Au(t),_f=e):Au(t));break;default:Au(t)}}function tM(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 sf(t){var e=t.deletions;if(t.flags&16){if(e!==null)for(var n=0;n<e.length;n++){var r=e[n];kr=r,rM(r,t)}tM(t)}if(t.subtreeFlags&10256)for(t=t.child;t!==null;)nM(t),t=t.sibling}function nM(t){switch(t.tag){case 0:case 11:case 15:sf(t),t.flags&2048&&Ml(9,t,t.return);break;case 3:sf(t);break;case 12:sf(t);break;case 22:var e=t.stateNode;t.memoizedState!==null&&e._visibility&2&&(t.return===null||t.return.tag!==13)?(e._visibility&=-3,cy(t)):sf(t);break;default:sf(t)}}function cy(t){var e=t.deletions;if(t.flags&16){if(e!==null)for(var n=0;n<e.length;n++){var r=e[n];kr=r,rM(r,t)}tM(t)}for(t=t.child;t!==null;){switch(e=t,e.tag){case 0:case 11:case 15:Ml(8,e,e.return),cy(e);break;case 22:n=e.stateNode,n._visibility&2&&(n._visibility&=-3,cy(e));break;default:cy(e)}t=t.sibling}}function rM(t,e){for(;kr!==null;){var n=kr;switch(n.tag){case 0:case 11:case 15:Ml(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:lm(n.memoizedState.cache)}if(r=n.child,r!==null)r.return=n,kr=r;else e:for(n=t;kr!==null;){r=kr;var s=r.sibling,i=r.return;if(W2(r),r===n){kr=null;break e}if(s!==null){s.return=i,kr=s;break e}kr=i}}}var $6={getCacheForType:function(t){var e=ts(br),n=e.data.get(t);return n===void 0&&(n=t(),e.data.set(t,n)),n}},V6=typeof WeakMap=="function"?WeakMap:Map,pn=0,Rn=null,Yt=null,Zt=0,dn=0,$s=null,vl=!1,Ah=!1,OT=!1,wo=0,Jn=0,jl=0,Fc=0,NT=0,Si=0,oh=0,Bf=null,Rs=null,wS=!1,MT=0,t0=1/0,n0=null,Tl=null,Hr=0,Al=null,lh=null,kd=0,TS=0,AS=null,sM=null,Ff=0,RS=null;function Qs(){if(pn&2&&Zt!==0)return Zt&-Zt;if(wt.T!==null){var t=rh;return t!==0?t:UT()}return mN()}function iM(){Si===0&&(Si=!(Zt&536870912)||rn?dN():536870912);var t=Ai.current;return t!==null&&(t.flags|=32),Si}function Js(t,e,n){(t===Rn&&(dn===2||dn===9)||t.cancelPendingCommit!==null)&&(ch(t,0),_l(t,Zt,Si,!1)),rm(t,n),(!(pn&2)||t!==Rn)&&(t===Rn&&(!(pn&2)&&(Fc|=n),Jn===4&&_l(t,Zt,Si,!1)),Oa(t))}function aM(t,e,n){if(pn&6)throw Error(je(327));var r=!n&&(e&124)===0&&(e&t.expiredLanes)===0||nm(t,e),s=r?H6(t,e):nb(t,e,!0),i=r;do{if(s===0){Ah&&!r&&_l(t,e,0,!1);break}else{if(n=t.current.alternate,i&&!G6(n)){s=nb(t,e,!1),i=!1;continue}if(s===2){if(i=e,t.errorRecoveryDisabledLanes&i)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;s=Bf;var l=o.current.memoizedState.isDehydrated;if(l&&(ch(o,a).flags|=256),a=nb(o,a,!1),a!==2){if(OT&&!l){o.errorRecoveryDisabledLanes|=i,Fc|=i,s=4;break e}i=Rs,Rs=s,i!==null&&(Rs===null?Rs=i:Rs.push.apply(Rs,i))}s=a}if(i=!1,s!==2)continue}}if(s===1){ch(t,0),_l(t,e,0,!0);break}e:{switch(r=t,i=s,i){case 0:case 1:throw Error(je(345));case 4:if((e&4194048)!==e)break;case 6:_l(r,e,Si,!vl);break e;case 2:Rs=null;break;case 3:case 5:break;default:throw Error(je(329))}if((e&62914560)===e&&(s=MT+300-wa(),10<s)){if(_l(r,e,Si,!vl),iv(r,0,!0)!==0)break e;r.timeoutHandle=TM(dC.bind(null,r,n,Rs,n0,wS,e,Si,Fc,oh,vl,i,2,-0,0),s);break e}dC(r,n,Rs,n0,wS,e,Si,Fc,oh,vl,i,0,-0,0)}}break}while(!0);Oa(t)}function dC(t,e,n,r,s,i,a,o,l,c,u,d,h,f){if(t.timeoutHandle=-1,d=e.subtreeFlags,(d&8192||(d&16785408)===16785408)&&(fp={stylesheets:null,count:0,unsuspend:wV},eM(e),d=AV(),d!==null)){t.cancelPendingCommit=d(fC.bind(null,t,e,i,n,r,s,a,o,l,u,1,h,f)),_l(t,i,a,!c);return}fC(t,e,i,n,r,s,a,o,l)}function G6(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 s=n[r],i=s.getSnapshot;s=s.value;try{if(!ni(i(),s))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 _l(t,e,n,r){e&=~NT,e&=~Fc,t.suspendedLanes|=e,t.pingedLanes&=~e,r&&(t.warmLanes|=e),r=t.expirationTimes;for(var s=e;0<s;){var i=31-Xs(s),a=1<<i;r[i]=-1,s&=~a}n!==0&&fN(t,n,e)}function mv(){return pn&6?!0:(fm(0),!1)}function jT(){if(Yt!==null){if(dn===0)var t=Yt.return;else t=Yt,ho=hu=null,ET(t),Cd=null,up=0,t=Yt;for(;t!==null;)$2(t.alternate,t),t=t.return;Yt=null}}function ch(t,e){var n=t.timeoutHandle;n!==-1&&(t.timeoutHandle=-1,oV(n)),n=t.cancelPendingCommit,n!==null&&(t.cancelPendingCommit=null,n()),jT(),Rn=t,Yt=n=go(t.current,null),Zt=e,dn=0,$s=null,vl=!1,Ah=nm(t,e),OT=!1,oh=Si=NT=Fc=jl=Jn=0,Rs=Bf=null,wS=!1,e&8&&(e|=e&32);var r=t.entangledLanes;if(r!==0)for(t=t.entanglements,r&=e;0<r;){var s=31-Xs(r),i=1<<s;e|=t[s],r&=~i}return wo=e,cv(),n}function oM(t,e){$t=null,wt.H=Yy,e===cm||e===dv?(e=GR(),dn=3):e===HN?(e=GR(),dn=4):dn=e===N2?8:e!==null&&typeof e=="object"&&typeof e.then=="function"?6:1,$s=e,Yt===null&&(Jn=1,Jy(t,xi(e,t.current)))}function lM(){var t=wt.H;return wt.H=Yy,t===null?Yy:t}function cM(){var t=wt.A;return wt.A=$6,t}function CS(){Jn=4,vl||(Zt&4194048)!==Zt&&Ai.current!==null||(Ah=!0),!(jl&134217727)&&!(Fc&134217727)||Rn===null||_l(Rn,Zt,Si,!1)}function nb(t,e,n){var r=pn;pn|=2;var s=lM(),i=cM();(Rn!==t||Zt!==e)&&(n0=null,ch(t,e)),e=!1;var a=Jn;e:do try{if(dn!==0&&Yt!==null){var o=Yt,l=$s;switch(dn){case 8:jT(),a=6;break e;case 3:case 2:case 9:case 6:Ai.current===null&&(e=!0);var c=dn;if(dn=0,$s=null,pd(t,o,l,c),n&&Ah){a=0;break e}break;default:c=dn,dn=0,$s=null,pd(t,o,l,c)}}K6(),a=Jn;break}catch(u){oM(t,u)}while(!0);return e&&t.shellSuspendCounter++,ho=hu=null,pn=r,wt.H=s,wt.A=i,Yt===null&&(Rn=null,Zt=0,cv()),a}function K6(){for(;Yt!==null;)uM(Yt)}function H6(t,e){var n=pn;pn|=2;var r=lM(),s=cM();Rn!==t||Zt!==e?(n0=null,t0=wa()+500,ch(t,e)):Ah=nm(t,e);e:do try{if(dn!==0&&Yt!==null){e=Yt;var i=$s;t:switch(dn){case 1:dn=0,$s=null,pd(t,e,i,1);break;case 2:case 9:if(VR(i)){dn=0,$s=null,hC(e);break}e=function(){dn!==2&&dn!==9||Rn!==t||(dn=7),Oa(t)},i.then(e,e);break e;case 3:dn=7;break e;case 4:dn=5;break e;case 7:VR(i)?(dn=0,$s=null,hC(e)):(dn=0,$s=null,pd(t,e,i,7));break;case 5:var a=null;switch(Yt.tag){case 26:a=Yt.memoizedState;case 5:case 27:var o=Yt;if(!a||kM(a)){dn=0,$s=null;var l=o.sibling;if(l!==null)Yt=l;else{var c=o.return;c!==null?(Yt=c,gv(c)):Yt=null}break t}}dn=0,$s=null,pd(t,e,i,5);break;case 6:dn=0,$s=null,pd(t,e,i,6);break;case 8:jT(),Jn=6;break e;default:throw Error(je(462))}}z6();break}catch(u){oM(t,u)}while(!0);return ho=hu=null,wt.H=r,wt.A=s,pn=n,Yt!==null?0:(Rn=null,Zt=0,cv(),Jn)}function z6(){for(;Yt!==null&&!p8();)uM(Yt)}function uM(t){var e=F2(t.alternate,t,wo);t.memoizedProps=t.pendingProps,e===null?gv(t):Yt=e}function hC(t){var e=t,n=e.alternate;switch(e.tag){case 15:case 0:e=iC(n,e,e.pendingProps,e.type,void 0,Zt);break;case 11:e=iC(n,e,e.pendingProps,e.type.render,e.ref,Zt);break;case 5:ET(e);default:$2(n,e),e=Yt=$N(e,wo),e=F2(n,e,wo)}t.memoizedProps=t.pendingProps,e===null?gv(t):Yt=e}function pd(t,e,n,r){ho=hu=null,ET(e),Cd=null,up=0;var s=e.return;try{if(N6(t,s,e,n,Zt)){Jn=1,Jy(t,xi(n,t.current)),Yt=null;return}}catch(i){if(s!==null)throw Yt=s,i;Jn=1,Jy(t,xi(n,t.current)),Yt=null;return}e.flags&32768?(rn||r===1?t=!0:Ah||Zt&536870912?t=!1:(vl=t=!0,(r===2||r===9||r===3||r===6)&&(r=Ai.current,r!==null&&r.tag===13&&(r.flags|=16384))),dM(e,t)):gv(e)}function gv(t){var e=t;do{if(e.flags&32768){dM(e,vl);return}t=e.return;var n=j6(e.alternate,e,wo);if(n!==null){Yt=n;return}if(e=e.sibling,e!==null){Yt=e;return}Yt=e=t}while(e!==null);Jn===0&&(Jn=5)}function dM(t,e){do{var n=U6(t.alternate,t);if(n!==null){n.flags&=32767,Yt=n;return}if(n=t.return,n!==null&&(n.flags|=32768,n.subtreeFlags=0,n.deletions=null),!e&&(t=t.sibling,t!==null)){Yt=t;return}Yt=t=n}while(t!==null);Jn=6,Yt=null}function fC(t,e,n,r,s,i,a,o,l){t.cancelPendingCommit=null;do yv();while(Hr!==0);if(pn&6)throw Error(je(327));if(e!==null){if(e===t.current)throw Error(je(177));if(i=e.lanes|e.childLanes,i|=uT,w8(t,n,i,a,o,l),t===Rn&&(Yt=Rn=null,Zt=0),lh=e,Al=t,kd=n,TS=i,AS=s,sM=r,e.subtreeFlags&10256||e.flags&10256?(t.callbackNode=null,t.callbackPriority=0,X6(By,function(){return gM(),null})):(t.callbackNode=null,t.callbackPriority=0),r=(e.flags&13878)!==0,e.subtreeFlags&13878||r){r=wt.T,wt.T=null,s=sn.p,sn.p=2,a=pn,pn|=4;try{B6(t,e,n)}finally{pn=a,sn.p=s,wt.T=r}}Hr=1,hM(),fM(),pM()}}function hM(){if(Hr===1){Hr=0;var t=Al,e=lh,n=(e.flags&13878)!==0;if(e.subtreeFlags&13878||n){n=wt.T,wt.T=null;var r=sn.p;sn.p=2;var s=pn;pn|=4;try{Q2(e,t);var i=PS,a=DN(t.containerInfo),o=i.focusedElem,l=i.selectionRange;if(a!==o&&o&&o.ownerDocument&&PN(o.ownerDocument.documentElement,o)){if(l!==null&&cT(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(),m=o.textContent.length,g=Math.min(l.start,m),y=l.end===void 0?g:Math.min(l.end,m);!f.extend&&g>y&&(a=y,y=g,g=a);var v=OR(o,g),_=OR(o,y);if(v&&_&&(f.rangeCount!==1||f.anchorNode!==v.node||f.anchorOffset!==v.offset||f.focusNode!==_.node||f.focusOffset!==_.offset)){var S=d.createRange();S.setStart(v.node,v.offset),f.removeAllRanges(),g>y?(f.addRange(S),f.extend(_.node,_.offset)):(S.setEnd(_.node,_.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}}u0=!!IS,PS=IS=null}finally{pn=s,sn.p=r,wt.T=n}}t.current=e,Hr=2}}function fM(){if(Hr===2){Hr=0;var t=Al,e=lh,n=(e.flags&8772)!==0;if(e.subtreeFlags&8772||n){n=wt.T,wt.T=null;var r=sn.p;sn.p=2;var s=pn;pn|=4;try{q2(t,e.alternate,e)}finally{pn=s,sn.p=r,wt.T=n}}Hr=3}}function pM(){if(Hr===4||Hr===3){Hr=0,m8();var t=Al,e=lh,n=kd,r=sM;e.subtreeFlags&10256||e.flags&10256?Hr=5:(Hr=0,lh=Al=null,mM(t,t.pendingLanes));var s=t.pendingLanes;if(s===0&&(Tl=null),nT(n),e=e.stateNode,Ys&&typeof Ys.onCommitFiberRoot=="function")try{Ys.onCommitFiberRoot(tm,e,void 0,(e.current.flags&128)===128)}catch{}if(r!==null){e=wt.T,s=sn.p,sn.p=2,wt.T=null;try{for(var i=t.onRecoverableError,a=0;a<r.length;a++){var o=r[a];i(o.value,{componentStack:o.stack})}}finally{wt.T=e,sn.p=s}}kd&3&&yv(),Oa(t),s=t.pendingLanes,n&4194090&&s&42?t===RS?Ff++:(Ff=0,RS=t):Ff=0,fm(0)}}function mM(t,e){(t.pooledCacheLanes&=e)===0&&(e=t.pooledCache,e!=null&&(t.pooledCache=null,lm(e)))}function yv(t){return hM(),fM(),pM(),gM()}function gM(){if(Hr!==5)return!1;var t=Al,e=TS;TS=0;var n=nT(kd),r=wt.T,s=sn.p;try{sn.p=32>n?32:n,wt.T=null,n=AS,AS=null;var i=Al,a=kd;if(Hr=0,lh=Al=null,kd=0,pn&6)throw Error(je(331));var o=pn;if(pn|=4,nM(i.current),Z2(i,i.current,a,n),pn=o,fm(0,!1),Ys&&typeof Ys.onPostCommitFiberRoot=="function")try{Ys.onPostCommitFiberRoot(tm,i)}catch{}return!0}finally{sn.p=s,wt.T=r,mM(t,e)}}function pC(t,e,n){e=xi(n,e),e=bS(t.stateNode,e,2),t=wl(t,e,2),t!==null&&(rm(t,2),Oa(t))}function xn(t,e,n){if(t.tag===3)pC(t,t,n);else for(;e!==null;){if(e.tag===3){pC(e,t,n);break}else if(e.tag===1){var r=e.stateNode;if(typeof e.type.getDerivedStateFromError=="function"||typeof r.componentDidCatch=="function"&&(Tl===null||!Tl.has(r))){t=xi(n,t),n=D2(2),r=wl(e,n,2),r!==null&&(O2(n,r,e,t),rm(r,2),Oa(r));break}}e=e.return}}function rb(t,e,n){var r=t.pingCache;if(r===null){r=t.pingCache=new V6;var s=new Set;r.set(e,s)}else s=r.get(e),s===void 0&&(s=new Set,r.set(e,s));s.has(n)||(OT=!0,s.add(n),t=q6.bind(null,t,e,n),e.then(t,t))}function q6(t,e,n){var r=t.pingCache;r!==null&&r.delete(e),t.pingedLanes|=t.suspendedLanes&n,t.warmLanes&=~n,Rn===t&&(Zt&n)===n&&(Jn===4||Jn===3&&(Zt&62914560)===Zt&&300>wa()-MT?!(pn&2)&&ch(t,0):NT|=n,oh===Zt&&(oh=0)),Oa(t)}function yM(t,e){e===0&&(e=hN()),t=Th(t,e),t!==null&&(rm(t,e),Oa(t))}function W6(t){var e=t.memoizedState,n=0;e!==null&&(n=e.retryLane),yM(t,n)}function Y6(t,e){var n=0;switch(t.tag){case 13:var r=t.stateNode,s=t.memoizedState;s!==null&&(n=s.retryLane);break;case 19:r=t.stateNode;break;case 22:r=t.stateNode._retryCache;break;default:throw Error(je(314))}r!==null&&r.delete(e),yM(t,n)}function X6(t,e){return eT(t,e)}var r0=null,Yu=null,kS=!1,s0=!1,sb=!1,$c=0;function Oa(t){t!==Yu&&t.next===null&&(Yu===null?r0=Yu=t:Yu=Yu.next=t),s0=!0,kS||(kS=!0,J6())}function fm(t,e){if(!sb&&s0){sb=!0;do for(var n=!1,r=r0;r!==null;){if(t!==0){var s=r.pendingLanes;if(s===0)var i=0;else{var a=r.suspendedLanes,o=r.pingedLanes;i=(1<<31-Xs(42|t)+1)-1,i&=s&~(a&~o),i=i&201326741?i&201326741|1:i?i|2:0}i!==0&&(n=!0,mC(r,i))}else i=Zt,i=iv(r,r===Rn?i:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(i&3)||nm(r,i)||(n=!0,mC(r,i));r=r.next}while(n);sb=!1}}function Q6(){vM()}function vM(){s0=kS=!1;var t=0;$c!==0&&(aV()&&(t=$c),$c=0);for(var e=wa(),n=null,r=r0;r!==null;){var s=r.next,i=_M(r,e);i===0?(r.next=null,n===null?r0=s:n.next=s,s===null&&(Yu=n)):(n=r,(t!==0||i&3)&&(s0=!0)),r=s}fm(t)}function _M(t,e){for(var n=t.suspendedLanes,r=t.pingedLanes,s=t.expirationTimes,i=t.pendingLanes&-62914561;0<i;){var a=31-Xs(i),o=1<<a,l=s[a];l===-1?(!(o&n)||o&r)&&(s[a]=E8(o,e)):l<=e&&(t.expiredLanes|=o),i&=~o}if(e=Rn,n=Zt,n=iv(t,t===e?n:0,t.cancelPendingCommit!==null||t.timeoutHandle!==-1),r=t.callbackNode,n===0||t===e&&(dn===2||dn===9)||t.cancelPendingCommit!==null)return r!==null&&r!==null&&L_(r),t.callbackNode=null,t.callbackPriority=0;if(!(n&3)||nm(t,n)){if(e=n&-n,e===t.callbackPriority)return e;switch(r!==null&&L_(r),nT(n)){case 2:case 8:n=cN;break;case 32:n=By;break;case 268435456:n=uN;break;default:n=By}return r=bM.bind(null,t),n=eT(n,r),t.callbackPriority=e,t.callbackNode=n,e}return r!==null&&r!==null&&L_(r),t.callbackPriority=2,t.callbackNode=null,2}function bM(t,e){if(Hr!==0&&Hr!==5)return t.callbackNode=null,t.callbackPriority=0,null;var n=t.callbackNode;if(yv()&&t.callbackNode!==n)return null;var r=Zt;return r=iv(t,t===Rn?r:0,t.cancelPendingCommit!==null||t.timeoutHandle!==-1),r===0?null:(aM(t,r,e),_M(t,wa()),t.callbackNode!=null&&t.callbackNode===n?bM.bind(null,t):null)}function mC(t,e){if(yv())return null;aM(t,e,!0)}function J6(){lV(function(){pn&6?eT(lN,Q6):vM()})}function UT(){return $c===0&&($c=dN()),$c}function gC(t){return t==null||typeof t=="symbol"||typeof t=="boolean"?null:typeof t=="function"?t:ty(""+t)}function yC(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 Z6(t,e,n,r,s){if(e==="submit"&&n&&n.stateNode===s){var i=gC((s[Is]||null).action),a=r.submitter;a&&(e=(e=a[Is]||null)?gC(e.formAction):a.getAttribute("formAction"),e!==null&&(i=e,a=null));var o=new av("action","action",null,r,s);t.push({event:o,listeners:[{instance:null,listener:function(){if(r.defaultPrevented){if($c!==0){var l=a?yC(s,a):new FormData(s);vS(n,{pending:!0,data:l,method:s.method,action:i},null,l)}}else typeof i=="function"&&(o.preventDefault(),l=a?yC(s,a):new FormData(s),vS(n,{pending:!0,data:l,method:s.method,action:i},i,l))},currentTarget:s}]})}}for(var ib=0;ib<aS.length;ib++){var ab=aS[ib],eV=ab.toLowerCase(),tV=ab[0].toUpperCase()+ab.slice(1);Xi(eV,"on"+tV)}Xi(NN,"onAnimationEnd");Xi(MN,"onAnimationIteration");Xi(jN,"onAnimationStart");Xi("dblclick","onDoubleClick");Xi("focusin","onFocus");Xi("focusout","onBlur");Xi(v6,"onTransitionRun");Xi(_6,"onTransitionStart");Xi(b6,"onTransitionCancel");Xi(UN,"onTransitionEnd");th("onMouseEnter",["mouseout","mouseover"]);th("onMouseLeave",["mouseout","mouseover"]);th("onPointerEnter",["pointerout","pointerover"]);th("onPointerLeave",["pointerout","pointerover"]);cu("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));cu("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));cu("onBeforeInput",["compositionend","keypress","textInput","paste"]);cu("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));cu("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));cu("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var dp="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(" "),nV=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(dp));function xM(t,e){e=(e&4)!==0;for(var n=0;n<t.length;n++){var r=t[n],s=r.event;r=r.listeners;e:{var i=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!==i&&s.isPropagationStopped())break e;i=o,s.currentTarget=c;try{i(s)}catch(u){Qy(u)}s.currentTarget=null,i=l}else for(a=0;a<r.length;a++){if(o=r[a],l=o.instance,c=o.currentTarget,o=o.listener,l!==i&&s.isPropagationStopped())break e;i=o,s.currentTarget=c;try{i(s)}catch(u){Qy(u)}s.currentTarget=null,i=l}}}}function Wt(t,e){var n=e[Zx];n===void 0&&(n=e[Zx]=new Set);var r=t+"__bubble";n.has(r)||(SM(e,t,2,!1),n.add(r))}function ob(t,e,n){var r=0;e&&(r|=4),SM(n,t,r,e)}var ag="_reactListening"+Math.random().toString(36).slice(2);function BT(t){if(!t[ag]){t[ag]=!0,gN.forEach(function(n){n!=="selectionchange"&&(nV.has(n)||ob(n,!1,t),ob(n,!0,t))});var e=t.nodeType===9?t:t.ownerDocument;e===null||e[ag]||(e[ag]=!0,ob("selectionchange",!1,e))}}function SM(t,e,n,r){switch(OM(e)){case 2:var s=kV;break;case 8:s=LV;break;default:s=GT}n=s.bind(null,e,n,t),s=void 0,!rS||e!=="touchstart"&&e!=="touchmove"&&e!=="wheel"||(s=!0),r?s!==void 0?t.addEventListener(e,n,{capture:!0,passive:s}):t.addEventListener(e,n,!0):s!==void 0?t.addEventListener(e,n,{passive:s}):t.addEventListener(e,n,!1)}function lb(t,e,n,r,s){var i=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===s)break;if(a===4)for(a=r.return;a!==null;){var l=a.tag;if((l===3||l===4)&&a.stateNode.containerInfo===s)return;a=a.return}for(;o!==null;){if(a=id(o),a===null)return;if(l=a.tag,l===5||l===6||l===26||l===27){r=i=a;continue e}o=o.parentNode}}r=r.return}wN(function(){var c=i,u=iT(n),d=[];e:{var h=BN.get(t);if(h!==void 0){var f=av,m=t;switch(t){case"keypress":if(ry(n)===0)break e;case"keydown":case"keyup":f=X8;break;case"focusin":m="focus",f=U_;break;case"focusout":m="blur",f=U_;break;case"beforeblur":case"afterblur":f=U_;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=wR;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":f=U8;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":f=Z8;break;case NN:case MN:case jN:f=$8;break;case UN:f=t6;break;case"scroll":case"scrollend":f=M8;break;case"wheel":f=r6;break;case"copy":case"cut":case"paste":f=G8;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":f=AR;break;case"toggle":case"beforetoggle":f=i6}var g=(e&4)!==0,y=!g&&(t==="scroll"||t==="scrollend"),v=g?h!==null?h+"Capture":null:h;g=[];for(var _=c,S;_!==null;){var E=_;if(S=E.stateNode,E=E.tag,E!==5&&E!==26&&E!==27||S===null||v===null||(E=ip(_,v),E!=null&&g.push(hp(_,E,S))),y)break;_=_.return}0<g.length&&(h=new f(h,m,null,n,u),d.push({event:h,listeners:g}))}}if(!(e&7)){e:{if(h=t==="mouseover"||t==="pointerover",f=t==="mouseout"||t==="pointerout",h&&n!==nS&&(m=n.relatedTarget||n.fromElement)&&(id(m)||m[Eh]))break e;if((f||h)&&(h=u.window===u?u:(h=u.ownerDocument)?h.defaultView||h.parentWindow:window,f?(m=n.relatedTarget||n.toElement,f=c,m=m?id(m):null,m!==null&&(y=em(m),g=m.tag,m!==y||g!==5&&g!==27&&g!==6)&&(m=null)):(f=null,m=c),f!==m)){if(g=wR,E="onMouseLeave",v="onMouseEnter",_="mouse",(t==="pointerout"||t==="pointerover")&&(g=AR,E="onPointerLeave",v="onPointerEnter",_="pointer"),y=f==null?h:vf(f),S=m==null?h:vf(m),h=new g(E,_+"leave",f,n,u),h.target=y,h.relatedTarget=S,E=null,id(u)===c&&(g=new g(v,_+"enter",m,n,u),g.target=S,g.relatedTarget=y,E=g),y=E,f&&m)t:{for(g=f,v=m,_=0,S=g;S;S=Ru(S))_++;for(S=0,E=v;E;E=Ru(E))S++;for(;0<_-S;)g=Ru(g),_--;for(;0<S-_;)v=Ru(v),S--;for(;_--;){if(g===v||v!==null&&g===v.alternate)break t;g=Ru(g),v=Ru(v)}g=null}else g=null;f!==null&&vC(d,h,f,g,!1),m!==null&&y!==null&&vC(d,y,m,g,!0)}}e:{if(h=c?vf(c):window,f=h.nodeName&&h.nodeName.toLowerCase(),f==="select"||f==="input"&&h.type==="file")var L=LR;else if(kR(h))if(LN)L=m6;else{L=f6;var U=h6}else f=h.nodeName,!f||f.toLowerCase()!=="input"||h.type!=="checkbox"&&h.type!=="radio"?c&&sT(c.elementType)&&(L=LR):L=p6;if(L&&(L=L(t,c))){kN(d,L,n,u);break e}U&&U(t,h,c),t==="focusout"&&c&&h.type==="number"&&c.memoizedProps.value!=null&&tS(h,"number",h.value)}switch(U=c?vf(c):window,t){case"focusin":(kR(U)||U.contentEditable==="true")&&(ld=U,sS=c,Lf=null);break;case"focusout":Lf=sS=ld=null;break;case"mousedown":iS=!0;break;case"contextmenu":case"mouseup":case"dragend":iS=!1,NR(d,n,u);break;case"selectionchange":if(y6)break;case"keydown":case"keyup":NR(d,n,u)}var P;if(lT)e:{switch(t){case"compositionstart":var I="onCompositionStart";break e;case"compositionend":I="onCompositionEnd";break e;case"compositionupdate":I="onCompositionUpdate";break e}I=void 0}else od?RN(t,n)&&(I="onCompositionEnd"):t==="keydown"&&n.keyCode===229&&(I="onCompositionStart");I&&(AN&&n.locale!=="ko"&&(od||I!=="onCompositionStart"?I==="onCompositionEnd"&&od&&(P=TN()):(yl=u,aT="value"in yl?yl.value:yl.textContent,od=!0)),U=i0(c,I),0<U.length&&(I=new TR(I,t,null,n,u),d.push({event:I,listeners:U}),P?I.data=P:(P=CN(n),P!==null&&(I.data=P)))),(P=o6?l6(t,n):c6(t,n))&&(I=i0(c,"onBeforeInput"),0<I.length&&(U=new TR("onBeforeInput","beforeinput",null,n,u),d.push({event:U,listeners:I}),U.data=P)),Z6(d,t,c,n,u)}xM(d,e)})}function hp(t,e,n){return{instance:t,listener:e,currentTarget:n}}function i0(t,e){for(var n=e+"Capture",r=[];t!==null;){var s=t,i=s.stateNode;if(s=s.tag,s!==5&&s!==26&&s!==27||i===null||(s=ip(t,n),s!=null&&r.unshift(hp(t,s,i)),s=ip(t,e),s!=null&&r.push(hp(t,s,i))),t.tag===3)return r;t=t.return}return[]}function Ru(t){if(t===null)return null;do t=t.return;while(t&&t.tag!==5&&t.tag!==27);return t||null}function vC(t,e,n,r,s){for(var i=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,s?(c=ip(n,i),c!=null&&a.unshift(hp(n,c,l))):s||(c=ip(n,i),c!=null&&a.push(hp(n,c,l)))),n=n.return}a.length!==0&&t.push({event:e,listeners:a})}var rV=/\r\n?/g,sV=/\u0000|\uFFFD/g;function _C(t){return(typeof t=="string"?t:""+t).replace(rV,`
`).replace(sV,"")}function EM(t,e){return e=_C(e),_C(t)===e}function vv(){}function gn(t,e,n,r,s,i){switch(n){case"children":typeof r=="string"?e==="body"||e==="textarea"&&r===""||nh(t,r):(typeof r=="number"||typeof r=="bigint")&&e!=="body"&&nh(t,""+r);break;case"className":Zm(t,"class",r);break;case"tabIndex":Zm(t,"tabindex",r);break;case"dir":case"role":case"viewBox":case"width":case"height":Zm(t,n,r);break;case"style":EN(t,r,i);break;case"data":if(e!=="object"){Zm(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=ty(""+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 i=="function"&&(n==="formAction"?(e!=="input"&&gn(t,e,"name",s.name,s,null),gn(t,e,"formEncType",s.formEncType,s,null),gn(t,e,"formMethod",s.formMethod,s,null),gn(t,e,"formTarget",s.formTarget,s,null)):(gn(t,e,"encType",s.encType,s,null),gn(t,e,"method",s.method,s,null),gn(t,e,"target",s.target,s,null)));if(r==null||typeof r=="symbol"||typeof r=="boolean"){t.removeAttribute(n);break}r=ty(""+r),t.setAttribute(n,r);break;case"onClick":r!=null&&(t.onclick=vv);break;case"onScroll":r!=null&&Wt("scroll",t);break;case"onScrollEnd":r!=null&&Wt("scrollend",t);break;case"dangerouslySetInnerHTML":if(r!=null){if(typeof r!="object"||!("__html"in r))throw Error(je(61));if(n=r.__html,n!=null){if(s.children!=null)throw Error(je(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=ty(""+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":Wt("beforetoggle",t),Wt("toggle",t),ey(t,"popover",r);break;case"xlinkActuate":$a(t,"http://www.w3.org/1999/xlink","xlink:actuate",r);break;case"xlinkArcrole":$a(t,"http://www.w3.org/1999/xlink","xlink:arcrole",r);break;case"xlinkRole":$a(t,"http://www.w3.org/1999/xlink","xlink:role",r);break;case"xlinkShow":$a(t,"http://www.w3.org/1999/xlink","xlink:show",r);break;case"xlinkTitle":$a(t,"http://www.w3.org/1999/xlink","xlink:title",r);break;case"xlinkType":$a(t,"http://www.w3.org/1999/xlink","xlink:type",r);break;case"xmlBase":$a(t,"http://www.w3.org/XML/1998/namespace","xml:base",r);break;case"xmlLang":$a(t,"http://www.w3.org/XML/1998/namespace","xml:lang",r);break;case"xmlSpace":$a(t,"http://www.w3.org/XML/1998/namespace","xml:space",r);break;case"is":ey(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=O8.get(n)||n,ey(t,n,r))}}function LS(t,e,n,r,s,i){switch(n){case"style":EN(t,r,i);break;case"dangerouslySetInnerHTML":if(r!=null){if(typeof r!="object"||!("__html"in r))throw Error(je(61));if(n=r.__html,n!=null){if(s.children!=null)throw Error(je(60));t.innerHTML=n}}break;case"children":typeof r=="string"?nh(t,r):(typeof r=="number"||typeof r=="bigint")&&nh(t,""+r);break;case"onScroll":r!=null&&Wt("scroll",t);break;case"onScrollEnd":r!=null&&Wt("scrollend",t);break;case"onClick":r!=null&&(t.onclick=vv);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!yN.hasOwnProperty(n))e:{if(n[0]==="o"&&n[1]==="n"&&(s=n.endsWith("Capture"),e=n.slice(2,s?n.length-7:void 0),i=t[Is]||null,i=i!=null?i[n]:null,typeof i=="function"&&t.removeEventListener(e,i,s),typeof r=="function")){typeof i!="function"&&i!==null&&(n in t?t[n]=null:t.hasAttribute(n)&&t.removeAttribute(n)),t.addEventListener(e,r,s);break e}n in t?t[n]=r:r===!0?t.setAttribute(n,""):ey(t,n,r)}}}function qr(t,e,n){switch(e){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":Wt("error",t),Wt("load",t);var r=!1,s=!1,i;for(i in n)if(n.hasOwnProperty(i)){var a=n[i];if(a!=null)switch(i){case"src":r=!0;break;case"srcSet":s=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(je(137,e));default:gn(t,e,i,a,n,null)}}s&&gn(t,e,"srcSet",n.srcSet,n,null),r&&gn(t,e,"src",n.src,n,null);return;case"input":Wt("invalid",t);var o=i=a=s=null,l=null,c=null;for(r in n)if(n.hasOwnProperty(r)){var u=n[r];if(u!=null)switch(r){case"name":s=u;break;case"type":a=u;break;case"checked":l=u;break;case"defaultChecked":c=u;break;case"value":i=u;break;case"defaultValue":o=u;break;case"children":case"dangerouslySetInnerHTML":if(u!=null)throw Error(je(137,e));break;default:gn(t,e,r,u,n,null)}}bN(t,i,o,l,c,a,s,!1),Fy(t);return;case"select":Wt("invalid",t),r=a=i=null;for(s in n)if(n.hasOwnProperty(s)&&(o=n[s],o!=null))switch(s){case"value":i=o;break;case"defaultValue":a=o;break;case"multiple":r=o;default:gn(t,e,s,o,n,null)}e=i,n=a,t.multiple=!!r,e!=null?Ed(t,!!r,e,!1):n!=null&&Ed(t,!!r,n,!0);return;case"textarea":Wt("invalid",t),i=s=r=null;for(a in n)if(n.hasOwnProperty(a)&&(o=n[a],o!=null))switch(a){case"value":r=o;break;case"defaultValue":s=o;break;case"children":i=o;break;case"dangerouslySetInnerHTML":if(o!=null)throw Error(je(91));break;default:gn(t,e,a,o,n,null)}SN(t,r,s,i),Fy(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:gn(t,e,l,r,n,null)}return;case"dialog":Wt("beforetoggle",t),Wt("toggle",t),Wt("cancel",t),Wt("close",t);break;case"iframe":case"object":Wt("load",t);break;case"video":case"audio":for(r=0;r<dp.length;r++)Wt(dp[r],t);break;case"image":Wt("error",t),Wt("load",t);break;case"details":Wt("toggle",t);break;case"embed":case"source":case"link":Wt("error",t),Wt("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(je(137,e));default:gn(t,e,c,r,n,null)}return;default:if(sT(e)){for(u in n)n.hasOwnProperty(u)&&(r=n[u],r!==void 0&&LS(t,e,u,r,n,void 0));return}}for(o in n)n.hasOwnProperty(o)&&(r=n[o],r!=null&&gn(t,e,o,r,n,null))}function iV(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 s=null,i=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)||gn(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":i=f;break;case"name":s=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(je(137,e));break;default:f!==d&&gn(t,e,h,f,r,d)}}eS(t,a,o,l,c,u,i,s);return;case"select":f=a=o=h=null;for(i in n)if(l=n[i],n.hasOwnProperty(i)&&l!=null)switch(i){case"value":break;case"multiple":f=l;default:r.hasOwnProperty(i)||gn(t,e,i,null,r,l)}for(s in r)if(i=r[s],l=n[s],r.hasOwnProperty(s)&&(i!=null||l!=null))switch(s){case"value":h=i;break;case"defaultValue":o=i;break;case"multiple":a=i;default:i!==l&&gn(t,e,s,i,r,l)}e=o,n=a,r=f,h!=null?Ed(t,!!n,h,!1):!!r!=!!n&&(e!=null?Ed(t,!!n,e,!0):Ed(t,!!n,n?[]:"",!1));return;case"textarea":f=h=null;for(o in n)if(s=n[o],n.hasOwnProperty(o)&&s!=null&&!r.hasOwnProperty(o))switch(o){case"value":break;case"children":break;default:gn(t,e,o,null,r,s)}for(a in r)if(s=r[a],i=n[a],r.hasOwnProperty(a)&&(s!=null||i!=null))switch(a){case"value":h=s;break;case"defaultValue":f=s;break;case"children":break;case"dangerouslySetInnerHTML":if(s!=null)throw Error(je(91));break;default:s!==i&&gn(t,e,a,s,r,i)}xN(t,h,f);return;case"option":for(var m in n)if(h=n[m],n.hasOwnProperty(m)&&h!=null&&!r.hasOwnProperty(m))switch(m){case"selected":t.selected=!1;break;default:gn(t,e,m,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:gn(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 g in n)h=n[g],n.hasOwnProperty(g)&&h!=null&&!r.hasOwnProperty(g)&&gn(t,e,g,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(je(137,e));break;default:gn(t,e,c,h,r,f)}return;default:if(sT(e)){for(var y in n)h=n[y],n.hasOwnProperty(y)&&h!==void 0&&!r.hasOwnProperty(y)&&LS(t,e,y,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||LS(t,e,u,h,r,f);return}}for(var v in n)h=n[v],n.hasOwnProperty(v)&&h!=null&&!r.hasOwnProperty(v)&&gn(t,e,v,null,r,h);for(d in r)h=r[d],f=n[d],!r.hasOwnProperty(d)||h===f||h==null&&f==null||gn(t,e,d,h,r,f)}var IS=null,PS=null;function a0(t){return t.nodeType===9?t:t.ownerDocument}function bC(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 wM(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 DS(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 cb=null;function aV(){var t=window.event;return t&&t.type==="popstate"?t===cb?!1:(cb=t,!0):(cb=null,!1)}var TM=typeof setTimeout=="function"?setTimeout:void 0,oV=typeof clearTimeout=="function"?clearTimeout:void 0,xC=typeof Promise=="function"?Promise:void 0,lV=typeof queueMicrotask=="function"?queueMicrotask:typeof xC<"u"?function(t){return xC.resolve(null).then(t).catch(cV)}:TM;function cV(t){setTimeout(function(){throw t})}function Wl(t){return t==="head"}function SC(t,e){var n=e,r=0,s=0;do{var i=n.nextSibling;if(t.removeChild(n),i&&i.nodeType===8)if(n=i.data,n==="/$"){if(0<r&&8>r){n=r;var a=t.ownerDocument;if(n&1&&$f(a.documentElement),n&2&&$f(a.body),n&4)for(n=a.head,$f(n),a=n.firstChild;a;){var o=a.nextSibling,l=a.nodeName;a[sm]||l==="SCRIPT"||l==="STYLE"||l==="LINK"&&a.rel.toLowerCase()==="stylesheet"||n.removeChild(a),a=o}}if(s===0){t.removeChild(i),yp(e);return}s--}else n==="$"||n==="$?"||n==="$!"?s++:r=n.charCodeAt(0)-48;else r=0;n=i}while(n);yp(e)}function OS(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":OS(n),rT(n);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(n.rel.toLowerCase()==="stylesheet")continue}t.removeChild(n)}}function uV(t,e,n,r){for(;t.nodeType===1;){var s=n;if(t.nodeName.toLowerCase()!==e.toLowerCase()){if(!r&&(t.nodeName!=="INPUT"||t.type!=="hidden"))break}else if(r){if(!t[sm])switch(e){case"meta":if(!t.hasAttribute("itemprop"))break;return t;case"link":if(i=t.getAttribute("rel"),i==="stylesheet"&&t.hasAttribute("data-precedence"))break;if(i!==s.rel||t.getAttribute("href")!==(s.href==null||s.href===""?null:s.href)||t.getAttribute("crossorigin")!==(s.crossOrigin==null?null:s.crossOrigin)||t.getAttribute("title")!==(s.title==null?null:s.title))break;return t;case"style":if(t.hasAttribute("data-precedence"))break;return t;case"script":if(i=t.getAttribute("src"),(i!==(s.src==null?null:s.src)||t.getAttribute("type")!==(s.type==null?null:s.type)||t.getAttribute("crossorigin")!==(s.crossOrigin==null?null:s.crossOrigin))&&i&&t.hasAttribute("async")&&!t.hasAttribute("itemprop"))break;return t;default:return t}}else if(e==="input"&&t.type==="hidden"){var i=s.name==null?null:""+s.name;if(s.type==="hidden"&&t.getAttribute("name")===i)return t}else return t;if(t=Hi(t.nextSibling),t===null)break}return null}function dV(t,e,n){if(e==="")return null;for(;t.nodeType!==3;)if((t.nodeType!==1||t.nodeName!=="INPUT"||t.type!=="hidden")&&!n||(t=Hi(t.nextSibling),t===null))return null;return t}function NS(t){return t.data==="$!"||t.data==="$?"&&t.ownerDocument.readyState==="complete"}function hV(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 Hi(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 MS=null;function EC(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 AM(t,e,n){switch(e=a0(n),t){case"html":if(t=e.documentElement,!t)throw Error(je(452));return t;case"head":if(t=e.head,!t)throw Error(je(453));return t;case"body":if(t=e.body,!t)throw Error(je(454));return t;default:throw Error(je(451))}}function $f(t){for(var e=t.attributes;e.length;)t.removeAttributeNode(e[0]);rT(t)}var Ri=new Map,wC=new Set;function o0(t){return typeof t.getRootNode=="function"?t.getRootNode():t.nodeType===9?t:t.ownerDocument}var Co=sn.d;sn.d={f:fV,r:pV,D:mV,C:gV,L:yV,m:vV,X:bV,S:_V,M:xV};function fV(){var t=Co.f(),e=mv();return t||e}function pV(t){var e=wh(t);e!==null&&e.tag===5&&e.type==="form"?_2(e):Co.r(t)}var Rh=typeof document>"u"?null:document;function RM(t,e,n){var r=Rh;if(r&&typeof e=="string"&&e){var s=bi(e);s='link[rel="'+t+'"][href="'+s+'"]',typeof n=="string"&&(s+='[crossorigin="'+n+'"]'),wC.has(s)||(wC.add(s),t={rel:t,crossOrigin:n,href:e},r.querySelector(s)===null&&(e=r.createElement("link"),qr(e,"link",t),Lr(e),r.head.appendChild(e)))}}function mV(t){Co.D(t),RM("dns-prefetch",t,null)}function gV(t,e){Co.C(t,e),RM("preconnect",t,e)}function yV(t,e,n){Co.L(t,e,n);var r=Rh;if(r&&t&&e){var s='link[rel="preload"][as="'+bi(e)+'"]';e==="image"&&n&&n.imageSrcSet?(s+='[imagesrcset="'+bi(n.imageSrcSet)+'"]',typeof n.imageSizes=="string"&&(s+='[imagesizes="'+bi(n.imageSizes)+'"]')):s+='[href="'+bi(t)+'"]';var i=s;switch(e){case"style":i=uh(t);break;case"script":i=Ch(t)}Ri.has(i)||(t=Dn({rel:"preload",href:e==="image"&&n&&n.imageSrcSet?void 0:t,as:e},n),Ri.set(i,t),r.querySelector(s)!==null||e==="style"&&r.querySelector(pm(i))||e==="script"&&r.querySelector(mm(i))||(e=r.createElement("link"),qr(e,"link",t),Lr(e),r.head.appendChild(e)))}}function vV(t,e){Co.m(t,e);var n=Rh;if(n&&t){var r=e&&typeof e.as=="string"?e.as:"script",s='link[rel="modulepreload"][as="'+bi(r)+'"][href="'+bi(t)+'"]',i=s;switch(r){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":i=Ch(t)}if(!Ri.has(i)&&(t=Dn({rel:"modulepreload",href:t},e),Ri.set(i,t),n.querySelector(s)===null)){switch(r){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(n.querySelector(mm(i)))return}r=n.createElement("link"),qr(r,"link",t),Lr(r),n.head.appendChild(r)}}}function _V(t,e,n){Co.S(t,e,n);var r=Rh;if(r&&t){var s=Sd(r).hoistableStyles,i=uh(t);e=e||"default";var a=s.get(i);if(!a){var o={loading:0,preload:null};if(a=r.querySelector(pm(i)))o.loading=5;else{t=Dn({rel:"stylesheet",href:t,"data-precedence":e},n),(n=Ri.get(i))&&FT(t,n);var l=a=r.createElement("link");Lr(l),qr(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,uy(a,e,r)}a={type:"stylesheet",instance:a,count:1,state:o},s.set(i,a)}}}function bV(t,e){Co.X(t,e);var n=Rh;if(n&&t){var r=Sd(n).hoistableScripts,s=Ch(t),i=r.get(s);i||(i=n.querySelector(mm(s)),i||(t=Dn({src:t,async:!0},e),(e=Ri.get(s))&&$T(t,e),i=n.createElement("script"),Lr(i),qr(i,"link",t),n.head.appendChild(i)),i={type:"script",instance:i,count:1,state:null},r.set(s,i))}}function xV(t,e){Co.M(t,e);var n=Rh;if(n&&t){var r=Sd(n).hoistableScripts,s=Ch(t),i=r.get(s);i||(i=n.querySelector(mm(s)),i||(t=Dn({src:t,async:!0,type:"module"},e),(e=Ri.get(s))&&$T(t,e),i=n.createElement("script"),Lr(i),qr(i,"link",t),n.head.appendChild(i)),i={type:"script",instance:i,count:1,state:null},r.set(s,i))}}function TC(t,e,n,r){var s=(s=Sl.current)?o0(s):null;if(!s)throw Error(je(446));switch(t){case"meta":case"title":return null;case"style":return typeof n.precedence=="string"&&typeof n.href=="string"?(e=uh(n.href),n=Sd(s).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=uh(n.href);var i=Sd(s).hoistableStyles,a=i.get(t);if(a||(s=s.ownerDocument||s,a={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},i.set(t,a),(i=s.querySelector(pm(t)))&&!i._p&&(a.instance=i,a.state.loading=5),Ri.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},Ri.set(t,n),i||SV(s,t,n,a.state))),e&&r===null)throw Error(je(528,""));return a}if(e&&r!==null)throw Error(je(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(s).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(je(444,t))}}function uh(t){return'href="'+bi(t)+'"'}function pm(t){return'link[rel="stylesheet"]['+t+"]"}function CM(t){return Dn({},t,{"data-precedence":t.precedence,precedence:null})}function SV(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}),qr(e,"link",n),Lr(e),t.head.appendChild(e))}function Ch(t){return'[src="'+bi(t)+'"]'}function mm(t){return"script[async]"+t}function AC(t,e,n){if(e.count++,e.instance===null)switch(e.type){case"style":var r=t.querySelector('style[data-href~="'+bi(n.href)+'"]');if(r)return e.instance=r,Lr(r),r;var s=Dn({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(t.ownerDocument||t).createElement("style"),Lr(r),qr(r,"style",s),uy(r,n.precedence,t),e.instance=r;case"stylesheet":s=uh(n.href);var i=t.querySelector(pm(s));if(i)return e.state.loading|=4,e.instance=i,Lr(i),i;r=CM(n),(s=Ri.get(s))&&FT(r,s),i=(t.ownerDocument||t).createElement("link"),Lr(i);var a=i;return a._p=new Promise(function(o,l){a.onload=o,a.onerror=l}),qr(i,"link",r),e.state.loading|=4,uy(i,n.precedence,t),e.instance=i;case"script":return i=Ch(n.src),(s=t.querySelector(mm(i)))?(e.instance=s,Lr(s),s):(r=n,(s=Ri.get(i))&&(r=Dn({},n),$T(r,s)),t=t.ownerDocument||t,s=t.createElement("script"),Lr(s),qr(s,"link",r),t.head.appendChild(s),e.instance=s);case"void":return null;default:throw Error(je(443,e.type))}else e.type==="stylesheet"&&!(e.state.loading&4)&&(r=e.instance,e.state.loading|=4,uy(r,n.precedence,t));return e.instance}function uy(t,e,n){for(var r=n.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),s=r.length?r[r.length-1]:null,i=s,a=0;a<r.length;a++){var o=r[a];if(o.dataset.precedence===e)i=o;else if(i!==s)break}i?i.parentNode.insertBefore(t,i.nextSibling):(e=n.nodeType===9?n.head:n,e.insertBefore(t,e.firstChild))}function FT(t,e){t.crossOrigin==null&&(t.crossOrigin=e.crossOrigin),t.referrerPolicy==null&&(t.referrerPolicy=e.referrerPolicy),t.title==null&&(t.title=e.title)}function $T(t,e){t.crossOrigin==null&&(t.crossOrigin=e.crossOrigin),t.referrerPolicy==null&&(t.referrerPolicy=e.referrerPolicy),t.integrity==null&&(t.integrity=e.integrity)}var dy=null;function RC(t,e,n){if(dy===null){var r=new Map,s=dy=new Map;s.set(n,r)}else s=dy,r=s.get(n),r||(r=new Map,s.set(n,r));if(r.has(t))return r;for(r.set(t,null),n=n.getElementsByTagName(t),s=0;s<n.length;s++){var i=n[s];if(!(i[sm]||i[es]||t==="link"&&i.getAttribute("rel")==="stylesheet")&&i.namespaceURI!=="http://www.w3.org/2000/svg"){var a=i.getAttribute(e)||"";a=t+a;var o=r.get(a);o?o.push(i):r.set(a,[i])}}return r}function CC(t,e,n){t=t.ownerDocument||t,t.head.insertBefore(n,e==="title"?t.querySelector("head > title"):null)}function EV(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 kM(t){return!(t.type==="stylesheet"&&!(t.state.loading&3))}var fp=null;function wV(){}function TV(t,e,n){if(fp===null)throw Error(je(475));var r=fp;if(e.type==="stylesheet"&&(typeof n.media!="string"||matchMedia(n.media).matches!==!1)&&!(e.state.loading&4)){if(e.instance===null){var s=uh(n.href),i=t.querySelector(pm(s));if(i){t=i._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(r.count++,r=l0.bind(r),t.then(r,r)),e.state.loading|=4,e.instance=i,Lr(i);return}i=t.ownerDocument||t,n=CM(n),(s=Ri.get(s))&&FT(n,s),i=i.createElement("link"),Lr(i);var a=i;a._p=new Promise(function(o,l){a.onload=o,a.onerror=l}),qr(i,"link",n),e.instance=i}r.stylesheets===null&&(r.stylesheets=new Map),r.stylesheets.set(e,t),(t=e.state.preload)&&!(e.state.loading&3)&&(r.count++,e=l0.bind(r),t.addEventListener("load",e),t.addEventListener("error",e))}}function AV(){if(fp===null)throw Error(je(475));var t=fp;return t.stylesheets&&t.count===0&&jS(t,t.stylesheets),0<t.count?function(e){var n=setTimeout(function(){if(t.stylesheets&&jS(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 l0(){if(this.count--,this.count===0){if(this.stylesheets)jS(this,this.stylesheets);else if(this.unsuspend){var t=this.unsuspend;this.unsuspend=null,t()}}}var c0=null;function jS(t,e){t.stylesheets=null,t.unsuspend!==null&&(t.count++,c0=new Map,e.forEach(RV,t),c0=null,l0.call(t))}function RV(t,e){if(!(e.state.loading&4)){var n=c0.get(t);if(n)var r=n.get(null);else{n=new Map,c0.set(t,n);for(var s=t.querySelectorAll("link[data-precedence],style[data-precedence]"),i=0;i<s.length;i++){var a=s[i];(a.nodeName==="LINK"||a.getAttribute("media")!=="not all")&&(n.set(a.dataset.precedence,a),r=a)}r&&n.set(null,r)}s=e.instance,a=s.getAttribute("data-precedence"),i=n.get(a)||r,i===r&&n.set(null,s),n.set(a,s),this.count++,r=l0.bind(this),s.addEventListener("load",r),s.addEventListener("error",r),i?i.parentNode.insertBefore(s,i.nextSibling):(t=t.nodeType===9?t.head:t,t.insertBefore(s,t.firstChild)),e.state.loading|=4}}var pp={$$typeof:lo,Provider:null,Consumer:null,_currentValue:Nc,_currentValue2:Nc,_threadCount:0};function CV(t,e,n,r,s,i,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=s,this.onCaughtError=i,this.onRecoverableError=a,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=o,this.incompleteTransitions=new Map}function LM(t,e,n,r,s,i,a,o,l,c,u,d){return t=new CV(t,e,n,a,o,l,c,d),e=1,i===!0&&(e|=24),i=qs(3,null,null,e),t.current=i,i.stateNode=t,e=mT(),e.refCount++,t.pooledCache=e,e.refCount++,i.memoizedState={element:r,isDehydrated:n,cache:e},yT(i),t}function IM(t){return t?(t=dd,t):dd}function PM(t,e,n,r,s,i){s=IM(s),r.context===null?r.context=s:r.pendingContext=s,r=El(e),r.payload={element:n},i=i===void 0?null:i,i!==null&&(r.callback=i),n=wl(t,r,e),n!==null&&(Js(n,t,e),Df(n,t,e))}function kC(t,e){if(t=t.memoizedState,t!==null&&t.dehydrated!==null){var n=t.retryLane;t.retryLane=n!==0&&n<e?n:e}}function VT(t,e){kC(t,e),(t=t.alternate)&&kC(t,e)}function DM(t){if(t.tag===13){var e=Th(t,67108864);e!==null&&Js(e,t,67108864),VT(t,67108864)}}var u0=!0;function kV(t,e,n,r){var s=wt.T;wt.T=null;var i=sn.p;try{sn.p=2,GT(t,e,n,r)}finally{sn.p=i,wt.T=s}}function LV(t,e,n,r){var s=wt.T;wt.T=null;var i=sn.p;try{sn.p=8,GT(t,e,n,r)}finally{sn.p=i,wt.T=s}}function GT(t,e,n,r){if(u0){var s=US(r);if(s===null)lb(t,e,r,d0,n),LC(t,r);else if(PV(s,t,e,n,r))r.stopPropagation();else if(LC(t,r),e&4&&-1<IV.indexOf(t)){for(;s!==null;){var i=wh(s);if(i!==null)switch(i.tag){case 3:if(i=i.stateNode,i.current.memoizedState.isDehydrated){var a=hc(i.pendingLanes);if(a!==0){var o=i;for(o.pendingLanes|=2,o.entangledLanes|=2;a;){var l=1<<31-Xs(a);o.entanglements[1]|=l,a&=~l}Oa(i),!(pn&6)&&(t0=wa()+500,fm(0))}}break;case 13:o=Th(i,2),o!==null&&Js(o,i,2),mv(),VT(i,2)}if(i=US(r),i===null&&lb(t,e,r,d0,n),i===s)break;s=i}s!==null&&r.stopPropagation()}else lb(t,e,r,null,n)}}function US(t){return t=iT(t),KT(t)}var d0=null;function KT(t){if(d0=null,t=id(t),t!==null){var e=em(t);if(e===null)t=null;else{var n=e.tag;if(n===13){if(t=sN(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 d0=t,null}function OM(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(g8()){case lN:return 2;case cN:return 8;case By:case y8:return 32;case uN:return 268435456;default:return 32}default:return 32}}var BS=!1,Rl=null,Cl=null,kl=null,mp=new Map,gp=new Map,sl=[],IV="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 LC(t,e){switch(t){case"focusin":case"focusout":Rl=null;break;case"dragenter":case"dragleave":Cl=null;break;case"mouseover":case"mouseout":kl=null;break;case"pointerover":case"pointerout":mp.delete(e.pointerId);break;case"gotpointercapture":case"lostpointercapture":gp.delete(e.pointerId)}}function af(t,e,n,r,s,i){return t===null||t.nativeEvent!==i?(t={blockedOn:e,domEventName:n,eventSystemFlags:r,nativeEvent:i,targetContainers:[s]},e!==null&&(e=wh(e),e!==null&&DM(e)),t):(t.eventSystemFlags|=r,e=t.targetContainers,s!==null&&e.indexOf(s)===-1&&e.push(s),t)}function PV(t,e,n,r,s){switch(e){case"focusin":return Rl=af(Rl,t,e,n,r,s),!0;case"dragenter":return Cl=af(Cl,t,e,n,r,s),!0;case"mouseover":return kl=af(kl,t,e,n,r,s),!0;case"pointerover":var i=s.pointerId;return mp.set(i,af(mp.get(i)||null,t,e,n,r,s)),!0;case"gotpointercapture":return i=s.pointerId,gp.set(i,af(gp.get(i)||null,t,e,n,r,s)),!0}return!1}function NM(t){var e=id(t.target);if(e!==null){var n=em(e);if(n!==null){if(e=n.tag,e===13){if(e=sN(n),e!==null){t.blockedOn=e,T8(t.priority,function(){if(n.tag===13){var r=Qs();r=tT(r);var s=Th(n,r);s!==null&&Js(s,n,r),VT(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 hy(t){if(t.blockedOn!==null)return!1;for(var e=t.targetContainers;0<e.length;){var n=US(t.nativeEvent);if(n===null){n=t.nativeEvent;var r=new n.constructor(n.type,n);nS=r,n.target.dispatchEvent(r),nS=null}else return e=wh(n),e!==null&&DM(e),t.blockedOn=n,!1;e.shift()}return!0}function IC(t,e,n){hy(t)&&n.delete(e)}function DV(){BS=!1,Rl!==null&&hy(Rl)&&(Rl=null),Cl!==null&&hy(Cl)&&(Cl=null),kl!==null&&hy(kl)&&(kl=null),mp.forEach(IC),gp.forEach(IC)}function og(t,e){t.blockedOn===e&&(t.blockedOn=null,BS||(BS=!0,Er.unstable_scheduleCallback(Er.unstable_NormalPriority,DV)))}var lg=null;function PC(t){lg!==t&&(lg=t,Er.unstable_scheduleCallback(Er.unstable_NormalPriority,function(){lg===t&&(lg=null);for(var e=0;e<t.length;e+=3){var n=t[e],r=t[e+1],s=t[e+2];if(typeof r!="function"){if(KT(r||n)===null)continue;break}var i=wh(n);i!==null&&(t.splice(e,3),e-=3,vS(i,{pending:!0,data:s,method:n.method,action:r},r,s))}}))}function yp(t){function e(l){return og(l,t)}Rl!==null&&og(Rl,t),Cl!==null&&og(Cl,t),kl!==null&&og(kl,t),mp.forEach(e),gp.forEach(e);for(var n=0;n<sl.length;n++){var r=sl[n];r.blockedOn===t&&(r.blockedOn=null)}for(;0<sl.length&&(n=sl[0],n.blockedOn===null);)NM(n),n.blockedOn===null&&sl.shift();if(n=(t.ownerDocument||t).$$reactFormReplay,n!=null)for(r=0;r<n.length;r+=3){var s=n[r],i=n[r+1],a=s[Is]||null;if(typeof i=="function")a||PC(n);else if(a){var o=null;if(i&&i.hasAttribute("formAction")){if(s=i,a=i[Is]||null)o=a.formAction;else if(KT(s)!==null)continue}else o=a.action;typeof o=="function"?n[r+1]=o:(n.splice(r,3),r-=3),PC(n)}}}function HT(t){this._internalRoot=t}_v.prototype.render=HT.prototype.render=function(t){var e=this._internalRoot;if(e===null)throw Error(je(409));var n=e.current,r=Qs();PM(n,r,t,e,null,null)};_v.prototype.unmount=HT.prototype.unmount=function(){var t=this._internalRoot;if(t!==null){this._internalRoot=null;var e=t.containerInfo;PM(t.current,2,null,t,null,null),mv(),e[Eh]=null}};function _v(t){this._internalRoot=t}_v.prototype.unstable_scheduleHydration=function(t){if(t){var e=mN();t={blockedOn:null,target:t,priority:e};for(var n=0;n<sl.length&&e!==0&&e<sl[n].priority;n++);sl.splice(n,0,t),n===0&&NM(t)}};var DC=nN.version;if(DC!=="19.1.0")throw Error(je(527,DC,"19.1.0"));sn.findDOMNode=function(t){var e=t._reactInternals;if(e===void 0)throw typeof t.render=="function"?Error(je(188)):(t=Object.keys(t).join(","),Error(je(268,t)));return t=c8(e),t=t!==null?iN(t):null,t=t===null?null:t.stateNode,t};var OV={bundleType:0,version:"19.1.0",rendererPackageName:"react-dom",currentDispatcherRef:wt,reconcilerVersion:"19.1.0"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var cg=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!cg.isDisabled&&cg.supportsFiber)try{tm=cg.inject(OV),Ys=cg}catch{}}rv.createRoot=function(t,e){if(!rN(t))throw Error(je(299));var n=!1,r="",s=L2,i=I2,a=P2,o=null;return e!=null&&(e.unstable_strictMode===!0&&(n=!0),e.identifierPrefix!==void 0&&(r=e.identifierPrefix),e.onUncaughtError!==void 0&&(s=e.onUncaughtError),e.onCaughtError!==void 0&&(i=e.onCaughtError),e.onRecoverableError!==void 0&&(a=e.onRecoverableError),e.unstable_transitionCallbacks!==void 0&&(o=e.unstable_transitionCallbacks)),e=LM(t,1,!1,null,null,n,r,s,i,a,o,null),t[Eh]=e.current,BT(t),new HT(e)};rv.hydrateRoot=function(t,e,n){if(!rN(t))throw Error(je(299));var r=!1,s="",i=L2,a=I2,o=P2,l=null,c=null;return n!=null&&(n.unstable_strictMode===!0&&(r=!0),n.identifierPrefix!==void 0&&(s=n.identifierPrefix),n.onUncaughtError!==void 0&&(i=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=LM(t,1,!0,e,n??null,r,s,i,a,o,l,c),e.context=IM(null),n=e.current,r=Qs(),r=tT(r),s=El(r),s.callback=null,wl(n,s,r),n=r,e.current.lanes=n,rm(e,n),Oa(e),t[Eh]=e.current,BT(t),new _v(e)};rv.version="19.1.0";function MM(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(MM)}catch(t){console.error(t)}}MM(),VO.exports=rv;var NV=VO.exports,gm=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(){}},Ac,ll,$d,LO,MV=(LO=class extends gm{constructor(){super();_t(this,Ac);_t(this,ll);_t(this,$d);nt(this,$d,e=>{if(typeof window<"u"&&window.addEventListener){const n=()=>e();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){ue(this,ll)||this.setEventListener(ue(this,$d))}onUnsubscribe(){var e;this.hasListeners()||((e=ue(this,ll))==null||e.call(this),nt(this,ll,void 0))}setEventListener(e){var n;nt(this,$d,e),(n=ue(this,ll))==null||n.call(this),nt(this,ll,e(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(e){ue(this,Ac)!==e&&(nt(this,Ac,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(n=>{n(e)})}isFocused(){var e;return typeof ue(this,Ac)=="boolean"?ue(this,Ac):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},Ac=new WeakMap,ll=new WeakMap,$d=new WeakMap,LO),zT=new MV,jV={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)},cl,Hw,IO,UV=(IO=class{constructor(){_t(this,cl,jV);_t(this,Hw,!1)}setTimeoutProvider(t){nt(this,cl,t)}setTimeout(t,e){return ue(this,cl).setTimeout(t,e)}clearTimeout(t){ue(this,cl).clearTimeout(t)}setInterval(t,e){return ue(this,cl).setInterval(t,e)}clearInterval(t){ue(this,cl).clearInterval(t)}},cl=new WeakMap,Hw=new WeakMap,IO),bc=new UV;function BV(t){setTimeout(t,0)}var FV=typeof window>"u"||"Deno"in globalThis;function ks(){}function $V(t,e){return typeof t=="function"?t(e):t}function FS(t){return typeof t=="number"&&t>=0&&t!==1/0}function jM(t,e){return Math.max(t+(e||0)-Date.now(),0)}function Ll(t,e){return typeof t=="function"?t(e):t}function Gs(t,e){return typeof t=="function"?t(e):t}function OC(t,e){const{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:a,stale:o}=t;if(a){if(r){if(e.queryHash!==qT(a,e.options))return!1}else if(!_p(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||s&&s!==e.state.fetchStatus||i&&!i(e))}function NC(t,e){const{exact:n,status:r,predicate:s,mutationKey:i}=t;if(i){if(!e.options.mutationKey)return!1;if(n){if(vp(e.options.mutationKey)!==vp(i))return!1}else if(!_p(e.options.mutationKey,i))return!1}return!(r&&e.state.status!==r||s&&!s(e))}function qT(t,e){return((e==null?void 0:e.queryKeyHashFn)||vp)(t)}function vp(t){return JSON.stringify(t,(e,n)=>VS(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function _p(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(n=>_p(t[n],e[n])):!1}var VV=Object.prototype.hasOwnProperty;function UM(t,e,n=0){if(t===e)return t;if(n>500)return e;const r=MC(t)&&MC(e);if(!r&&!(VS(t)&&VS(e)))return e;const i=(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<i:VV.call(t,d))&&c++;continue}if(h===null||f===null||typeof h!="object"||typeof f!="object"){l[d]=f;continue}const m=UM(h,f,n+1);l[d]=m,m===h&&c++}return i===o&&c===i?t:l}function $S(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 MC(t){return Array.isArray(t)&&t.length===Object.keys(t).length}function VS(t){if(!jC(t))return!1;const e=t.constructor;if(e===void 0)return!0;const n=e.prototype;return!(!jC(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}function jC(t){return Object.prototype.toString.call(t)==="[object Object]"}function GV(t){return new Promise(e=>{bc.setTimeout(e,t)})}function GS(t,e,n){return typeof n.structuralSharing=="function"?n.structuralSharing(t,e):n.structuralSharing!==!1?UM(t,e):e}function KV(t,e,n=0){const r=[...t,e];return n&&r.length>n?r.slice(1):r}function HV(t,e,n=0){const r=[e,...t];return n&&r.length>n?r.slice(0,-1):r}var WT=Symbol();function BM(t,e){return!t.queryFn&&(e!=null&&e.initialPromise)?()=>e.initialPromise:!t.queryFn||t.queryFn===WT?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function FM(t,e){return typeof t=="function"?t(...e):!!t}function zV(t,e,n){let r=!1,s;return Object.defineProperty(t,"signal",{enumerable:!0,get:()=>(s??(s=e()),r||(r=!0,s.aborted?n():s.addEventListener("abort",n,{once:!0})),s)}),t}var bp=(()=>{let t=()=>FV;return{isServer(){return t()},setIsServer(e){t=e}}})();function KS(){let t,e;const n=new Promise((s,i)=>{t=s,e=i});n.status="pending",n.catch(()=>{});function r(s){Object.assign(n,s),delete n.resolve,delete n.reject}return n.resolve=s=>{r({status:"fulfilled",value:s}),t(s)},n.reject=s=>{r({status:"rejected",reason:s}),e(s)},n}var qV=BV;function WV(){let t=[],e=0,n=o=>{o()},r=o=>{o()},s=qV;const i=o=>{e?t.push(o):s(()=>{n(o)})},a=()=>{const o=t;t=[],o.length&&s(()=>{r(()=>{o.forEach(l=>{n(l)})})})};return{batch:o=>{let l;e++;try{l=o()}finally{e--,e||a()}return l},batchCalls:o=>(...l)=>{i(()=>{o(...l)})},schedule:i,setNotifyFunction:o=>{n=o},setBatchNotifyFunction:o=>{r=o},setScheduler:o=>{s=o}}}var Gr=WV(),Vd,ul,Gd,PO,YV=(PO=class extends gm{constructor(){super();_t(this,Vd,!0);_t(this,ul);_t(this,Gd);nt(this,Gd,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,ul)||this.setEventListener(ue(this,Gd))}onUnsubscribe(){var e;this.hasListeners()||((e=ue(this,ul))==null||e.call(this),nt(this,ul,void 0))}setEventListener(e){var n;nt(this,Gd,e),(n=ue(this,ul))==null||n.call(this),nt(this,ul,e(this.setOnline.bind(this)))}setOnline(e){ue(this,Vd)!==e&&(nt(this,Vd,e),this.listeners.forEach(r=>{r(e)}))}isOnline(){return ue(this,Vd)}},Vd=new WeakMap,ul=new WeakMap,Gd=new WeakMap,PO),h0=new YV;function XV(t){return Math.min(1e3*2**t,3e4)}function $M(t){return(t??"online")==="online"?h0.isOnline():!0}var HS=class extends Error{constructor(t){super("CancelledError"),this.revert=t==null?void 0:t.revert,this.silent=t==null?void 0:t.silent}};function VM(t){let e=!1,n=0,r;const s=KS(),i=()=>s.status!=="pending",a=g=>{var y;if(!i()){const v=new HS(g);h(v),(y=t.onCancel)==null||y.call(t,v)}},o=()=>{e=!0},l=()=>{e=!1},c=()=>zT.isFocused()&&(t.networkMode==="always"||h0.isOnline())&&t.canRun(),u=()=>$M(t.networkMode)&&t.canRun(),d=g=>{i()||(r==null||r(),s.resolve(g))},h=g=>{i()||(r==null||r(),s.reject(g))},f=()=>new Promise(g=>{var y;r=v=>{(i()||c())&&g(v)},(y=t.onPause)==null||y.call(t)}).then(()=>{var g;r=void 0,i()||(g=t.onContinue)==null||g.call(t)}),m=()=>{if(i())return;let g;const y=n===0?t.initialPromise:void 0;try{g=y??t.fn()}catch(v){g=Promise.reject(v)}Promise.resolve(g).then(d).catch(v=>{var U;if(i())return;const _=t.retry??(bp.isServer()?0:3),S=t.retryDelay??XV,E=typeof S=="function"?S(n,v):S,L=_===!0||typeof _=="number"&&n<_||typeof _=="function"&&_(n,v);if(e||!L){h(v);return}n++,(U=t.onFail)==null||U.call(t,n,v),GV(E).then(()=>c()?void 0:f()).then(()=>{e?h(v):m()})})};return{promise:s,status:()=>s.status,cancel:a,continue:()=>(r==null||r(),s),cancelRetry:o,continueRetry:l,canStart:u,start:()=>(u()?m():f().then(m),s)}}var Rc,DO,GM=(DO=class{constructor(){_t(this,Rc)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),FS(this.gcTime)&&nt(this,Rc,bc.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(bp.isServer()?1/0:5*60*1e3))}clearGcTimeout(){ue(this,Rc)!==void 0&&(bc.clearTimeout(ue(this,Rc)),nt(this,Rc,void 0))}},Rc=new WeakMap,DO);function QV(t){return{onFetch:(e,n)=>{var u,d,h,f,m;const r=e.options,s=(h=(d=(u=e.fetchOptions)==null?void 0:u.meta)==null?void 0:d.fetchMore)==null?void 0:h.direction,i=((f=e.state.data)==null?void 0:f.pages)||[],a=((m=e.state.data)==null?void 0:m.pageParams)||[];let o={pages:[],pageParams:[]},l=0;const c=async()=>{let g=!1;const y=S=>{zV(S,()=>e.signal,()=>g=!0)},v=BM(e.options,e.fetchOptions),_=async(S,E,L)=>{if(g)return Promise.reject(e.signal.reason);if(E==null&&S.pages.length)return Promise.resolve(S);const P=(()=>{const M={client:e.client,queryKey:e.queryKey,pageParam:E,direction:L?"backward":"forward",meta:e.options.meta};return y(M),M})(),I=await v(P),{maxPages:k}=e.options,R=L?HV:KV;return{pages:R(S.pages,I,k),pageParams:R(S.pageParams,E,k)}};if(s&&i.length){const S=s==="backward",E=S?JV:UC,L={pages:i,pageParams:a},U=E(r,L);o=await _(L,U,S)}else{const S=t??i.length;do{const E=l===0?a[0]??r.initialPageParam:UC(r,o);if(l>0&&E==null)break;o=await _(o,E),l++}while(l<S)}return o};e.options.persister?e.fetchFn=()=>{var g,y;return(y=(g=e.options).persister)==null?void 0:y.call(g,c,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},n)}:e.fetchFn=c}}}function UC(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 JV(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 Kd,Cc,Hd,pi,kc,Cr,Wp,Lc,Vs,KM,Za,OO,ZV=(OO=class extends GM{constructor(e){super();_t(this,Vs);_t(this,Kd);_t(this,Cc);_t(this,Hd);_t(this,pi);_t(this,kc);_t(this,Cr);_t(this,Wp);_t(this,Lc);nt(this,Lc,!1),nt(this,Wp,e.defaultOptions),this.setOptions(e.options),this.observers=[],nt(this,kc,e.client),nt(this,pi,ue(this,kc).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,nt(this,Cc,FC(this.options)),this.state=e.state??ue(this,Cc),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return ue(this,Kd)}get promise(){var e;return(e=ue(this,Cr))==null?void 0:e.promise}setOptions(e){if(this.options={...ue(this,Wp),...e},e!=null&&e._type&&nt(this,Kd,e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=FC(this.options);n.data!==void 0&&(this.setState(BC(n.data,n.dataUpdatedAt)),nt(this,Cc,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&ue(this,pi).remove(this)}setData(e,n){const r=GS(this.state.data,e,this.options);return Qt(this,Vs,Za).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(e){Qt(this,Vs,Za).call(this,{type:"setState",state:e})}cancel(e){var r,s;const n=(r=ue(this,Cr))==null?void 0:r.promise;return(s=ue(this,Cr))==null||s.cancel(e),n?n.then(ks).catch(ks):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return ue(this,Cc)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>Gs(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===WT||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Ll(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:!jM(this.state.dataUpdatedAt,e)}onFocus(){var n;const e=this.observers.find(r=>r.shouldFetchOnWindowFocus());e==null||e.refetch({cancelRefetch:!1}),(n=ue(this,Cr))==null||n.continue()}onOnline(){var n;const e=this.observers.find(r=>r.shouldFetchOnReconnect());e==null||e.refetch({cancelRefetch:!1}),(n=ue(this,Cr))==null||n.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),ue(this,pi).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,Cr)&&(ue(this,Lc)||Qt(this,Vs,KM).call(this)?ue(this,Cr).cancel({revert:!0}):ue(this,Cr).cancelRetry()),this.scheduleGc()),ue(this,pi).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Qt(this,Vs,Za).call(this,{type:"invalidate"})}async fetch(e,n){var c,u,d,h,f,m,g,y,v,_,S;if(this.state.fetchStatus!=="idle"&&((c=ue(this,Cr))==null?void 0:c.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(ue(this,Cr))return ue(this,Cr).continueRetry(),ue(this,Cr).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,s=E=>{Object.defineProperty(E,"signal",{enumerable:!0,get:()=>(nt(this,Lc,!0),r.signal)})},i=()=>{const E=BM(this.options,n),U=(()=>{const P={client:ue(this,kc),queryKey:this.queryKey,meta:this.meta};return s(P),P})();return nt(this,Lc,!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,kc),state:this.state,fetchFn:i};return s(E),E})(),l=ue(this,Kd)==="infinite"?QV(this.options.pages):this.options.behavior;l==null||l.onFetch(o,this),nt(this,Hd,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((u=o.fetchOptions)==null?void 0:u.meta))&&Qt(this,Vs,Za).call(this,{type:"fetch",meta:(d=o.fetchOptions)==null?void 0:d.meta}),nt(this,Cr,VM({initialPromise:n==null?void 0:n.initialPromise,fn:o.fetchFn,onCancel:E=>{E instanceof HS&&E.revert&&this.setState({...ue(this,Hd),fetchStatus:"idle"}),r.abort()},onFail:(E,L)=>{Qt(this,Vs,Za).call(this,{type:"failed",failureCount:E,error:L})},onPause:()=>{Qt(this,Vs,Za).call(this,{type:"pause"})},onContinue:()=>{Qt(this,Vs,Za).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0}));try{const E=await ue(this,Cr).start();if(E===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(E),(f=(h=ue(this,pi).config).onSuccess)==null||f.call(h,E,this),(g=(m=ue(this,pi).config).onSettled)==null||g.call(m,E,this.state.error,this),E}catch(E){if(E instanceof HS){if(E.silent)return ue(this,Cr).promise;if(E.revert){if(this.state.data===void 0)throw E;return this.state.data}}throw Qt(this,Vs,Za).call(this,{type:"error",error:E}),(v=(y=ue(this,pi).config).onError)==null||v.call(y,E,this),(S=(_=ue(this,pi).config).onSettled)==null||S.call(_,this.state.data,E,this),E}finally{this.scheduleGc()}}},Kd=new WeakMap,Cc=new WeakMap,Hd=new WeakMap,pi=new WeakMap,kc=new WeakMap,Cr=new WeakMap,Wp=new WeakMap,Lc=new WeakMap,Vs=new WeakSet,KM=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Za=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,...HM(r.data,this.options),fetchMeta:e.meta??null};case"success":const s={...r,...BC(e.data,e.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return nt(this,Hd,e.manual?s:void 0),s;case"error":const i=e.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...e.state}}};this.state=n(this.state),Gr.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),ue(this,pi).notify({query:this,type:"updated",action:e})})},OO);function HM(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:$M(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function BC(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function FC(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 ws,Jt,Yp,os,Ic,zd,io,dl,Xp,qd,Wd,Pc,Dc,hl,Yd,on,bf,zS,qS,WS,YS,XS,QS,JS,zM,NO,eG=(NO=class extends gm{constructor(e,n){super();_t(this,on);_t(this,ws);_t(this,Jt);_t(this,Yp);_t(this,os);_t(this,Ic);_t(this,zd);_t(this,io);_t(this,dl);_t(this,Xp);_t(this,qd);_t(this,Wd);_t(this,Pc);_t(this,Dc);_t(this,hl);_t(this,Yd,new Set);this.options=n,nt(this,ws,e),nt(this,dl,null),nt(this,io,KS()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(ue(this,Jt).addObserver(this),$C(ue(this,Jt),this.options)?Qt(this,on,bf).call(this):this.updateResult(),Qt(this,on,YS).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return ZS(ue(this,Jt),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return ZS(ue(this,Jt),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Qt(this,on,XS).call(this),Qt(this,on,QS).call(this),ue(this,Jt).removeObserver(this)}setOptions(e){const n=this.options,r=ue(this,Jt);if(this.options=ue(this,ws).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Gs(this.options.enabled,ue(this,Jt))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Qt(this,on,JS).call(this),ue(this,Jt).setOptions(this.options),n._defaulted&&!$S(this.options,n)&&ue(this,ws).getQueryCache().notify({type:"observerOptionsUpdated",query:ue(this,Jt),observer:this});const s=this.hasListeners();s&&VC(ue(this,Jt),r,this.options,n)&&Qt(this,on,bf).call(this),this.updateResult(),s&&(ue(this,Jt)!==r||Gs(this.options.enabled,ue(this,Jt))!==Gs(n.enabled,ue(this,Jt))||Ll(this.options.staleTime,ue(this,Jt))!==Ll(n.staleTime,ue(this,Jt)))&&Qt(this,on,zS).call(this);const i=Qt(this,on,qS).call(this);s&&(ue(this,Jt)!==r||Gs(this.options.enabled,ue(this,Jt))!==Gs(n.enabled,ue(this,Jt))||i!==ue(this,hl))&&Qt(this,on,WS).call(this,i)}getOptimisticResult(e){const n=ue(this,ws).getQueryCache().build(ue(this,ws),e),r=this.createResult(n,e);return nG(this,r)&&(nt(this,os,r),nt(this,zd,this.options),nt(this,Ic,ue(this,Jt).state)),r}getCurrentResult(){return ue(this,os)}trackResult(e,n){return new Proxy(e,{get:(r,s)=>(this.trackProp(s),n==null||n(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&ue(this,io).status==="pending"&&ue(this,io).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(e){ue(this,Yd).add(e)}getCurrentQuery(){return ue(this,Jt)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const n=ue(this,ws).defaultQueryOptions(e),r=ue(this,ws).getQueryCache().build(ue(this,ws),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(e){return Qt(this,on,bf).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),ue(this,os)))}createResult(e,n){var k;const r=ue(this,Jt),s=this.options,i=ue(this,os),a=ue(this,Ic),o=ue(this,zd),c=e!==r?e.state:ue(this,Yp),{state:u}=e;let d={...u},h=!1,f;if(n._optimisticResults){const R=this.hasListeners(),M=!R&&$C(e,n),G=R&&VC(e,r,n,s);(M||G)&&(d={...d,...HM(u.data,e.options)}),n._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:m,errorUpdatedAt:g,status:y}=d;f=d.data;let v=!1;if(n.placeholderData!==void 0&&f===void 0&&y==="pending"){let R;i!=null&&i.isPlaceholderData&&n.placeholderData===(o==null?void 0:o.placeholderData)?(R=i.data,v=!0):R=typeof n.placeholderData=="function"?n.placeholderData((k=ue(this,Wd))==null?void 0:k.state.data,ue(this,Wd)):n.placeholderData,R!==void 0&&(y="success",f=GS(i==null?void 0:i.data,R,n),h=!0)}if(n.select&&f!==void 0&&!v)if(i&&f===(a==null?void 0:a.data)&&n.select===ue(this,Xp))f=ue(this,qd);else try{nt(this,Xp,n.select),f=n.select(f),f=GS(i==null?void 0:i.data,f,n),nt(this,qd,f),nt(this,dl,null)}catch(R){nt(this,dl,R)}ue(this,dl)&&(m=ue(this,dl),f=ue(this,qd),g=Date.now(),y="error");const _=d.fetchStatus==="fetching",S=y==="pending",E=y==="error",L=S&&_,U=f!==void 0,I={status:y,fetchStatus:d.fetchStatus,isPending:S,isSuccess:y==="success",isError:E,isInitialLoading:L,isLoading:L,data:f,dataUpdatedAt:d.dataUpdatedAt,error:m,errorUpdatedAt:g,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:d.dataUpdateCount>c.dataUpdateCount||d.errorUpdateCount>c.errorUpdateCount,isFetching:_,isRefetching:_&&!S,isLoadingError:E&&!U,isPaused:d.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:E&&U,isStale:YT(e,n),refetch:this.refetch,promise:ue(this,io),isEnabled:Gs(n.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const R=I.data!==void 0,M=I.status==="error"&&!R,G=X=>{M?X.reject(I.error):R&&X.resolve(I.data)},Y=()=>{const X=nt(this,io,I.promise=KS());G(X)},q=ue(this,io);switch(q.status){case"pending":e.queryHash===r.queryHash&&G(q);break;case"fulfilled":(M||I.data!==q.value)&&Y();break;case"rejected":(!M||I.error!==q.reason)&&Y();break}}return I}updateResult(){const e=ue(this,os),n=this.createResult(ue(this,Jt),this.options);if(nt(this,Ic,ue(this,Jt).state),nt(this,zd,this.options),ue(this,Ic).data!==void 0&&nt(this,Wd,ue(this,Jt)),$S(n,e))return;nt(this,os,n);const r=()=>{if(!e)return!0;const{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!ue(this,Yd).size)return!0;const a=new Set(i??ue(this,Yd));return this.options.throwOnError&&a.add("error"),Object.keys(ue(this,os)).some(o=>{const l=o;return ue(this,os)[l]!==e[l]&&a.has(l)})};Qt(this,on,zM).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Qt(this,on,YS).call(this)}},ws=new WeakMap,Jt=new WeakMap,Yp=new WeakMap,os=new WeakMap,Ic=new WeakMap,zd=new WeakMap,io=new WeakMap,dl=new WeakMap,Xp=new WeakMap,qd=new WeakMap,Wd=new WeakMap,Pc=new WeakMap,Dc=new WeakMap,hl=new WeakMap,Yd=new WeakMap,on=new WeakSet,bf=function(e){Qt(this,on,JS).call(this);let n=ue(this,Jt).fetch(this.options,e);return e!=null&&e.throwOnError||(n=n.catch(ks)),n},zS=function(){Qt(this,on,XS).call(this);const e=Ll(this.options.staleTime,ue(this,Jt));if(bp.isServer()||ue(this,os).isStale||!FS(e))return;const r=jM(ue(this,os).dataUpdatedAt,e)+1;nt(this,Pc,bc.setTimeout(()=>{ue(this,os).isStale||this.updateResult()},r))},qS=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(ue(this,Jt)):this.options.refetchInterval)??!1},WS=function(e){Qt(this,on,QS).call(this),nt(this,hl,e),!(bp.isServer()||Gs(this.options.enabled,ue(this,Jt))===!1||!FS(ue(this,hl))||ue(this,hl)===0)&&nt(this,Dc,bc.setInterval(()=>{(this.options.refetchIntervalInBackground||zT.isFocused())&&Qt(this,on,bf).call(this)},ue(this,hl)))},YS=function(){Qt(this,on,zS).call(this),Qt(this,on,WS).call(this,Qt(this,on,qS).call(this))},XS=function(){ue(this,Pc)!==void 0&&(bc.clearTimeout(ue(this,Pc)),nt(this,Pc,void 0))},QS=function(){ue(this,Dc)!==void 0&&(bc.clearInterval(ue(this,Dc)),nt(this,Dc,void 0))},JS=function(){const e=ue(this,ws).getQueryCache().build(ue(this,ws),this.options);if(e===ue(this,Jt))return;const n=ue(this,Jt);nt(this,Jt,e),nt(this,Yp,e.state),this.hasListeners()&&(n==null||n.removeObserver(this),e.addObserver(this))},zM=function(e){Gr.batch(()=>{e.listeners&&this.listeners.forEach(n=>{n(ue(this,os))}),ue(this,ws).getQueryCache().notify({query:ue(this,Jt),type:"observerResultsUpdated"})})},NO);function tG(t,e){return Gs(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&Gs(e.retryOnMount,t)===!1)}function $C(t,e){return tG(t,e)||t.state.data!==void 0&&ZS(t,e,e.refetchOnMount)}function ZS(t,e,n){if(Gs(e.enabled,t)!==!1&&Ll(e.staleTime,t)!=="static"){const r=typeof n=="function"?n(t):n;return r==="always"||r!==!1&&YT(t,e)}return!1}function VC(t,e,n,r){return(t!==e||Gs(r.enabled,t)===!1)&&(!n.suspense||t.state.status!=="error")&&YT(t,n)}function YT(t,e){return Gs(e.enabled,t)!==!1&&t.isStaleByTime(Ll(e.staleTime,t))}function nG(t,e){return!$S(t.getCurrentResult(),e)}var Qp,ca,Zr,Oc,ua,Ho,MO,rG=(MO=class extends GM{constructor(e){super();_t(this,ua);_t(this,Qp);_t(this,ca);_t(this,Zr);_t(this,Oc);nt(this,Qp,e.client),this.mutationId=e.mutationId,nt(this,Zr,e.mutationCache),nt(this,ca,[]),this.state=e.state||sG(),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,ca).includes(e)||(ue(this,ca).push(e),this.clearGcTimeout(),ue(this,Zr).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){nt(this,ca,ue(this,ca).filter(n=>n!==e)),this.scheduleGc(),ue(this,Zr).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){ue(this,ca).length||(this.state.status==="pending"?this.scheduleGc():ue(this,Zr).remove(this))}continue(){var e;return((e=ue(this,Oc))==null?void 0:e.continue())??this.execute(this.state.variables)}async execute(e){var a,o,l,c,u,d,h,f,m,g,y,v,_,S,E,L,U,P;const n=()=>{Qt(this,ua,Ho).call(this,{type:"continue"})},r={client:ue(this,Qp),meta:this.options.meta,mutationKey:this.options.mutationKey};nt(this,Oc,VM({fn:()=>this.options.mutationFn?this.options.mutationFn(e,r):Promise.reject(new Error("No mutationFn found")),onFail:(I,k)=>{Qt(this,ua,Ho).call(this,{type:"failed",failureCount:I,error:k})},onPause:()=>{Qt(this,ua,Ho).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>ue(this,Zr).canRun(this)}));const s=this.state.status==="pending",i=!ue(this,Oc).canStart();try{if(s)n();else{Qt(this,ua,Ho).call(this,{type:"pending",variables:e,isPaused:i}),ue(this,Zr).config.onMutate&&await ue(this,Zr).config.onMutate(e,this,r);const k=await((o=(a=this.options).onMutate)==null?void 0:o.call(a,e,r));k!==this.state.context&&Qt(this,ua,Ho).call(this,{type:"pending",context:k,variables:e,isPaused:i})}const I=await ue(this,Oc).start();return await((c=(l=ue(this,Zr).config).onSuccess)==null?void 0:c.call(l,I,e,this.state.context,this,r)),await((d=(u=this.options).onSuccess)==null?void 0:d.call(u,I,e,this.state.context,r)),await((f=(h=ue(this,Zr).config).onSettled)==null?void 0:f.call(h,I,null,this.state.variables,this.state.context,this,r)),await((g=(m=this.options).onSettled)==null?void 0:g.call(m,I,null,e,this.state.context,r)),Qt(this,ua,Ho).call(this,{type:"success",data:I}),I}catch(I){try{await((v=(y=ue(this,Zr).config).onError)==null?void 0:v.call(y,I,e,this.state.context,this,r))}catch(k){Promise.reject(k)}try{await((S=(_=this.options).onError)==null?void 0:S.call(_,I,e,this.state.context,r))}catch(k){Promise.reject(k)}try{await((L=(E=ue(this,Zr).config).onSettled)==null?void 0:L.call(E,void 0,I,this.state.variables,this.state.context,this,r))}catch(k){Promise.reject(k)}try{await((P=(U=this.options).onSettled)==null?void 0:P.call(U,void 0,I,e,this.state.context,r))}catch(k){Promise.reject(k)}throw Qt(this,ua,Ho).call(this,{type:"error",error:I}),I}finally{ue(this,Zr).runNext(this)}}},Qp=new WeakMap,ca=new WeakMap,Zr=new WeakMap,Oc=new WeakMap,ua=new WeakSet,Ho=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),Gr.batch(()=>{ue(this,ca).forEach(r=>{r.onMutationUpdate(e)}),ue(this,Zr).notify({mutation:this,type:"updated",action:e})})},MO);function sG(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var ao,$i,Jp,jO,iG=(jO=class extends gm{constructor(e={}){super();_t(this,ao);_t(this,$i);_t(this,Jp);this.config=e,nt(this,ao,new Set),nt(this,$i,new Map),nt(this,Jp,0)}build(e,n,r){const s=new rG({client:e,mutationCache:this,mutationId:++Wm(this,Jp)._,options:e.defaultMutationOptions(n),state:r});return this.add(s),s}add(e){ue(this,ao).add(e);const n=ug(e);if(typeof n=="string"){const r=ue(this,$i).get(n);r?r.push(e):ue(this,$i).set(n,[e])}this.notify({type:"added",mutation:e})}remove(e){if(ue(this,ao).delete(e)){const n=ug(e);if(typeof n=="string"){const r=ue(this,$i).get(n);if(r)if(r.length>1){const s=r.indexOf(e);s!==-1&&r.splice(s,1)}else r[0]===e&&ue(this,$i).delete(n)}}this.notify({type:"removed",mutation:e})}canRun(e){const n=ug(e);if(typeof n=="string"){const r=ue(this,$i).get(n),s=r==null?void 0:r.find(i=>i.state.status==="pending");return!s||s===e}else return!0}runNext(e){var r;const n=ug(e);if(typeof n=="string"){const s=(r=ue(this,$i).get(n))==null?void 0:r.find(i=>i!==e&&i.state.isPaused);return(s==null?void 0:s.continue())??Promise.resolve()}else return Promise.resolve()}clear(){Gr.batch(()=>{ue(this,ao).forEach(e=>{this.notify({type:"removed",mutation:e})}),ue(this,ao).clear(),ue(this,$i).clear()})}getAll(){return Array.from(ue(this,ao))}find(e){const n={exact:!0,...e};return this.getAll().find(r=>NC(n,r))}findAll(e={}){return this.getAll().filter(n=>NC(e,n))}notify(e){Gr.batch(()=>{this.listeners.forEach(n=>{n(e)})})}resumePausedMutations(){const e=this.getAll().filter(n=>n.state.isPaused);return Gr.batch(()=>Promise.all(e.map(n=>n.continue().catch(ks))))}},ao=new WeakMap,$i=new WeakMap,Jp=new WeakMap,jO);function ug(t){var e;return(e=t.options.scope)==null?void 0:e.id}var da,UO,aG=(UO=class extends gm{constructor(e={}){super();_t(this,da);this.config=e,nt(this,da,new Map)}build(e,n,r){const s=n.queryKey,i=n.queryHash??qT(s,n);let a=this.get(i);return a||(a=new ZV({client:e,queryKey:s,queryHash:i,options:e.defaultQueryOptions(n),state:r,defaultOptions:e.getQueryDefaults(s)}),this.add(a)),a}add(e){ue(this,da).has(e.queryHash)||(ue(this,da).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const n=ue(this,da).get(e.queryHash);n&&(e.destroy(),n===e&&ue(this,da).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Gr.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return ue(this,da).get(e)}getAll(){return[...ue(this,da).values()]}find(e){const n={exact:!0,...e};return this.getAll().find(r=>OC(n,r))}findAll(e={}){const n=this.getAll();return Object.keys(e).length>0?n.filter(r=>OC(e,r)):n}notify(e){Gr.batch(()=>{this.listeners.forEach(n=>{n(e)})})}onFocus(){Gr.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Gr.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},da=new WeakMap,UO),Wn,fl,pl,Xd,Qd,ml,Jd,Zd,BO,oG=(BO=class{constructor(t={}){_t(this,Wn);_t(this,fl);_t(this,pl);_t(this,Xd);_t(this,Qd);_t(this,ml);_t(this,Jd);_t(this,Zd);nt(this,Wn,t.queryCache||new aG),nt(this,fl,t.mutationCache||new iG),nt(this,pl,t.defaultOptions||{}),nt(this,Xd,new Map),nt(this,Qd,new Map),nt(this,ml,0)}mount(){Wm(this,ml)._++,ue(this,ml)===1&&(nt(this,Jd,zT.subscribe(async t=>{t&&(await this.resumePausedMutations(),ue(this,Wn).onFocus())})),nt(this,Zd,h0.subscribe(async t=>{t&&(await this.resumePausedMutations(),ue(this,Wn).onOnline())})))}unmount(){var t,e;Wm(this,ml)._--,ue(this,ml)===0&&((t=ue(this,Jd))==null||t.call(this),nt(this,Jd,void 0),(e=ue(this,Zd))==null||e.call(this),nt(this,Zd,void 0))}isFetching(t){return ue(this,Wn).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return ue(this,fl).findAll({...t,status:"pending"}).length}getQueryData(t){var n;const e=this.defaultQueryOptions({queryKey:t});return(n=ue(this,Wn).get(e.queryHash))==null?void 0:n.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),n=ue(this,Wn).build(this,e),r=n.state.data;return r===void 0?this.fetchQuery(t):(t.revalidateIfStale&&n.isStaleByTime(Ll(e.staleTime,n))&&this.prefetchQuery(e),Promise.resolve(r))}getQueriesData(t){return ue(this,Wn).findAll(t).map(({queryKey:e,state:n})=>{const r=n.data;return[e,r]})}setQueryData(t,e,n){const r=this.defaultQueryOptions({queryKey:t}),s=ue(this,Wn).get(r.queryHash),i=s==null?void 0:s.state.data,a=$V(e,i);if(a!==void 0)return ue(this,Wn).build(this,r).setData(a,{...n,manual:!0})}setQueriesData(t,e,n){return Gr.batch(()=>ue(this,Wn).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,Wn).get(e.queryHash))==null?void 0:n.state}removeQueries(t){const e=ue(this,Wn);Gr.batch(()=>{e.findAll(t).forEach(n=>{e.remove(n)})})}resetQueries(t,e){const n=ue(this,Wn);return Gr.batch(()=>(n.findAll(t).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){const n={revert:!0,...e},r=Gr.batch(()=>ue(this,Wn).findAll(t).map(s=>s.cancel(n)));return Promise.all(r).then(ks).catch(ks)}invalidateQueries(t,e={}){return Gr.batch(()=>(ue(this,Wn).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=Gr.batch(()=>ue(this,Wn).findAll(t).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(ks)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(ks)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const n=ue(this,Wn).build(this,e);return n.isStaleByTime(Ll(e.staleTime,n))?n.fetch(e):Promise.resolve(n.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(ks).catch(ks)}fetchInfiniteQuery(t){return t._type="infinite",this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(ks).catch(ks)}ensureInfiniteQueryData(t){return t._type="infinite",this.ensureQueryData(t)}resumePausedMutations(){return h0.isOnline()?ue(this,fl).resumePausedMutations():Promise.resolve()}getQueryCache(){return ue(this,Wn)}getMutationCache(){return ue(this,fl)}getDefaultOptions(){return ue(this,pl)}setDefaultOptions(t){nt(this,pl,t)}setQueryDefaults(t,e){ue(this,Xd).set(vp(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...ue(this,Xd).values()],n={};return e.forEach(r=>{_p(t,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(t,e){ue(this,Qd).set(vp(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...ue(this,Qd).values()],n={};return e.forEach(r=>{_p(t,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(t){if(t._defaulted)return t;const e={...ue(this,pl).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=qT(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===WT&&(e.enabled=!1),e}defaultMutationOptions(t){return t!=null&&t._defaulted?t:{...ue(this,pl).mutations,...(t==null?void 0:t.mutationKey)&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){ue(this,Wn).clear(),ue(this,fl).clear()}},Wn=new WeakMap,fl=new WeakMap,pl=new WeakMap,Xd=new WeakMap,Qd=new WeakMap,ml=new WeakMap,Jd=new WeakMap,Zd=new WeakMap,BO),qM=C.createContext(void 0),bv=t=>{const e=C.useContext(qM);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},lG=({client:t,children:e})=>(C.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),p.jsx(qM.Provider,{value:t,children:e})),WM=C.createContext(!1),cG=()=>C.useContext(WM);WM.Provider;function uG(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var dG=C.createContext(uG()),hG=()=>C.useContext(dG),fG=(t,e,n)=>{const r=n!=null&&n.state.error&&typeof t.throwOnError=="function"?FM(t.throwOnError,[n.state.error,n]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||r)&&(e.isReset()||(t.retryOnMount=!1))},pG=t=>{C.useEffect(()=>{t.clearReset()},[t])},mG=({result:t,errorResetBoundary:e,throwOnError:n,query:r,suspense:s})=>t.isError&&!e.isReset()&&!t.isFetching&&r&&(s&&t.data===void 0||FM(n,[t.error,r])),gG=t=>{if(t.suspense){const n=s=>s==="static"?s:Math.max(s??1e3,1e3),r=t.staleTime;t.staleTime=typeof r=="function"?(...s)=>n(r(...s)):n(r),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},yG=(t,e)=>t.isLoading&&t.isFetching&&!e,vG=(t,e)=>(t==null?void 0:t.suspense)&&e.isPending,GC=(t,e,n)=>e.fetchOptimistic(t).catch(()=>{n.clearReset()});function _G(t,e,n){var h,f,m,g;const r=cG(),s=hG(),i=bv(),a=i.defaultQueryOptions(t);(f=(h=i.getDefaultOptions().queries)==null?void 0:h._experimental_beforeQuery)==null||f.call(h,a);const o=i.getQueryCache().get(a.queryHash);a._optimisticResults=r?"isRestoring":"optimistic",gG(a),fG(a,s,o),pG(s);const l=!i.getQueryCache().get(a.queryHash),[c]=C.useState(()=>new e(i,a)),u=c.getOptimisticResult(a),d=!r&&t.subscribed!==!1;if(C.useSyncExternalStore(C.useCallback(y=>{const v=d?c.subscribe(Gr.batchCalls(y)):ks;return c.updateResult(),v},[c,d]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),C.useEffect(()=>{c.setOptions(a)},[a,c]),vG(a,u))throw GC(a,c,s);if(mG({result:u,errorResetBoundary:s,throwOnError:a.throwOnError,query:o,suspense:a.suspense}))throw u.error;if((g=(m=i.getDefaultOptions().queries)==null?void 0:m._experimental_afterQuery)==null||g.call(m,a,u),a.experimental_prefetchInRender&&!bp.isServer()&&yG(u,r)){const y=l?GC(a,c,s):o==null?void 0:o.promise;y==null||y.catch(ks).finally(()=>{c.updateResult()})}return a.notifyOnChangeProps?u:c.trackResult(u)}function kh(t,e){return _G(t,eG)}/**
 * @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 xp(){return xp=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},xp.apply(this,arguments)}var bl;(function(t){t.Pop="POP",t.Push="PUSH",t.Replace="REPLACE"})(bl||(bl={}));const KC="popstate";function bG(t){t===void 0&&(t={});function e(r,s){let{pathname:i,search:a,hash:o}=r.location;return f0("",{pathname:i,search:a,hash:o},s.state&&s.state.usr||null,s.state&&s.state.key||"default")}function n(r,s){return typeof s=="string"?s:Sp(s)}return YM(e,n,null,t)}function xG(t){t===void 0&&(t={});function e(s,i){let{pathname:a="/",search:o="",hash:l=""}=fu(s.location.hash.substr(1));return!a.startsWith("/")&&!a.startsWith(".")&&(a="/"+a),f0("",{pathname:a,search:o,hash:l},i.state&&i.state.usr||null,i.state&&i.state.key||"default")}function n(s,i){let a=s.document.querySelector("base"),o="";if(a&&a.getAttribute("href")){let l=s.location.href,c=l.indexOf("#");o=c===-1?l:l.slice(0,c)}return o+"#"+(typeof i=="string"?i:Sp(i))}function r(s,i){xv(s.pathname.charAt(0)==="/","relative pathnames are not supported in hash history.push("+JSON.stringify(i)+")")}return YM(e,n,r,t)}function or(t,e){if(t===!1||t===null||typeof t>"u")throw new Error(e)}function xv(t,e){if(!t){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function SG(){return Math.random().toString(36).substr(2,8)}function HC(t,e){return{usr:t.state,key:t.key,idx:e}}function f0(t,e,n,r){return n===void 0&&(n=null),xp({pathname:typeof t=="string"?t:t.pathname,search:"",hash:""},typeof e=="string"?fu(e):e,{state:n,key:e&&e.key||r||SG()})}function Sp(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 fu(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 YM(t,e,n,r){r===void 0&&(r={});let{window:s=document.defaultView,v5Compat:i=!1}=r,a=s.history,o=bl.Pop,l=null,c=u();c==null&&(c=0,a.replaceState(xp({},a.state,{idx:c}),""));function u(){return(a.state||{idx:null}).idx}function d(){o=bl.Pop;let y=u(),v=y==null?null:y-c;c=y,l&&l({action:o,location:g.location,delta:v})}function h(y,v){o=bl.Push;let _=f0(g.location,y,v);n&&n(_,y),c=u()+1;let S=HC(_,c),E=g.createHref(_);try{a.pushState(S,"",E)}catch(L){if(L instanceof DOMException&&L.name==="DataCloneError")throw L;s.location.assign(E)}i&&l&&l({action:o,location:g.location,delta:1})}function f(y,v){o=bl.Replace;let _=f0(g.location,y,v);n&&n(_,y),c=u();let S=HC(_,c),E=g.createHref(_);a.replaceState(S,"",E),i&&l&&l({action:o,location:g.location,delta:0})}function m(y){let v=s.location.origin!=="null"?s.location.origin:s.location.href,_=typeof y=="string"?y:Sp(y);return _=_.replace(/ $/,"%20"),or(v,"No window.location.(origin|href) available to create URL for href: "+_),new URL(_,v)}let g={get action(){return o},get location(){return t(s,a)},listen(y){if(l)throw new Error("A history only accepts one active listener");return s.addEventListener(KC,d),l=y,()=>{s.removeEventListener(KC,d),l=null}},createHref(y){return e(s,y)},createURL:m,encodeLocation(y){let v=m(y);return{pathname:v.pathname,search:v.search,hash:v.hash}},push:h,replace:f,go(y){return a.go(y)}};return g}var zC;(function(t){t.data="data",t.deferred="deferred",t.redirect="redirect",t.error="error"})(zC||(zC={}));function EG(t,e,n){return n===void 0&&(n="/"),wG(t,e,n)}function wG(t,e,n,r){let s=typeof e=="string"?fu(e):e,i=XT(s.pathname||"/",n);if(i==null)return null;let a=XM(t);TG(a);let o=null;for(let l=0;o==null&&l<a.length;++l){let c=jG(i);o=OG(a[l],c)}return o}function XM(t,e,n,r){e===void 0&&(e=[]),n===void 0&&(n=[]),r===void 0&&(r="");let s=(i,a,o)=>{let l={relativePath:o===void 0?i.path||"":o,caseSensitive:i.caseSensitive===!0,childrenIndex:a,route:i};l.relativePath.startsWith("/")&&(or(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=Il([r,l.relativePath]),u=n.concat(l);i.children&&i.children.length>0&&(or(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+c+'".')),XM(i.children,e,u,c)),!(i.path==null&&!i.index)&&e.push({path:c,score:PG(c,i.index),routesMeta:u})};return t.forEach((i,a)=>{var o;if(i.path===""||!((o=i.path)!=null&&o.includes("?")))s(i,a);else for(let l of QM(i.path))s(i,a,l)}),e}function QM(t){let e=t.split("/");if(e.length===0)return[];let[n,...r]=e,s=n.endsWith("?"),i=n.replace(/\?$/,"");if(r.length===0)return s?[i,""]:[i];let a=QM(r.join("/")),o=[];return o.push(...a.map(l=>l===""?i:[i,l].join("/"))),s&&o.push(...a),o.map(l=>t.startsWith("/")&&l===""?"/":l)}function TG(t){t.sort((e,n)=>e.score!==n.score?n.score-e.score:DG(e.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const AG=/^:[\w-]+$/,RG=3,CG=2,kG=1,LG=10,IG=-2,qC=t=>t==="*";function PG(t,e){let n=t.split("/"),r=n.length;return n.some(qC)&&(r+=IG),e&&(r+=CG),n.filter(s=>!qC(s)).reduce((s,i)=>s+(AG.test(i)?RG:i===""?kG:LG),r)}function DG(t,e){return t.length===e.length&&t.slice(0,-1).every((r,s)=>r===e[s])?t[t.length-1]-e[e.length-1]:0}function OG(t,e,n){let{routesMeta:r}=t,s={},i="/",a=[];for(let o=0;o<r.length;++o){let l=r[o],c=o===r.length-1,u=i==="/"?e:e.slice(i.length)||"/",d=NG({path:l.relativePath,caseSensitive:l.caseSensitive,end:c},u),h=l.route;if(!d)return null;Object.assign(s,d.params),a.push({params:s,pathname:Il([i,d.pathname]),pathnameBase:VG(Il([i,d.pathnameBase])),route:h}),d.pathnameBase!=="/"&&(i=Il([i,d.pathnameBase]))}return a}function NG(t,e){typeof t=="string"&&(t={path:t,caseSensitive:!1,end:!0});let[n,r]=MG(t.path,t.caseSensitive,t.end),s=e.match(n);if(!s)return null;let i=s[0],a=i.replace(/(.)\/+$/,"$1"),o=s.slice(1);return{params:r.reduce((c,u,d)=>{let{paramName:h,isOptional:f}=u;if(h==="*"){let g=o[d]||"";a=i.slice(0,i.length-g.length).replace(/(.)\/+$/,"$1")}const m=o[d];return f&&!m?c[h]=void 0:c[h]=(m||"").replace(/%2F/g,"/"),c},{}),pathname:i,pathnameBase:a,pattern:t}}function MG(t,e,n){e===void 0&&(e=!1),n===void 0&&(n=!0),xv(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=[],s="^"+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:"*"}),s+=t==="*"||t==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?s+="\\/*$":t!==""&&t!=="/"&&(s+="(?:(?=\\/|$))"),[new RegExp(s,e?void 0:"i"),r]}function jG(t){try{return t.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return xv(!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 XT(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 UG=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,BG=t=>UG.test(t);function FG(t,e){e===void 0&&(e="/");let{pathname:n,search:r="",hash:s=""}=typeof t=="string"?fu(t):t,i;if(n)if(BG(n))i=n;else{if(n.includes("//")){let a=n;n=n.replace(/\/\/+/g,"/"),xv(!1,"Pathnames cannot have embedded double slashes - normalizing "+(a+" -> "+n))}n.startsWith("/")?i=WC(n.substring(1),"/"):i=WC(n,e)}else i=e;return{pathname:i,search:GG(r),hash:KG(s)}}function WC(t,e){let n=e.replace(/\/+$/,"").split("/");return t.split("/").forEach(s=>{s===".."?n.length>1&&n.pop():s!=="."&&n.push(s)}),n.length>1?n.join("/"):"/"}function ub(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 $G(t){return t.filter((e,n)=>n===0||e.route.path&&e.route.path.length>0)}function QT(t,e){let n=$G(t);return e?n.map((r,s)=>s===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function JT(t,e,n,r){r===void 0&&(r=!1);let s;typeof t=="string"?s=fu(t):(s=xp({},t),or(!s.pathname||!s.pathname.includes("?"),ub("?","pathname","search",s)),or(!s.pathname||!s.pathname.includes("#"),ub("#","pathname","hash",s)),or(!s.search||!s.search.includes("#"),ub("#","search","hash",s)));let i=t===""||s.pathname==="",a=i?"/":s.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;s.pathname=h.join("/")}o=d>=0?e[d]:"/"}let l=FG(s,o),c=a&&a!=="/"&&a.endsWith("/"),u=(i||a===".")&&n.endsWith("/");return!l.pathname.endsWith("/")&&(c||u)&&(l.pathname+="/"),l}const Il=t=>t.join("/").replace(/\/\/+/g,"/"),VG=t=>t.replace(/\/+$/,"").replace(/^\/*/,"/"),GG=t=>!t||t==="?"?"":t.startsWith("?")?t:"?"+t,KG=t=>!t||t==="#"?"":t.startsWith("#")?t:"#"+t;function HG(t){return t!=null&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.internal=="boolean"&&"data"in t}const JM=["post","put","patch","delete"];new Set(JM);const zG=["get",...JM];new Set(zG);/**
 * 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 Ep(){return Ep=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},Ep.apply(this,arguments)}const ZT=C.createContext(null),qG=C.createContext(null),Yl=C.createContext(null),Sv=C.createContext(null),Xl=C.createContext({outlet:null,matches:[],isDataRoute:!1}),ZM=C.createContext(null);function WG(t,e){let{relative:n}=e===void 0?{}:e;Lh()||or(!1);let{basename:r,navigator:s}=C.useContext(Yl),{hash:i,pathname:a,search:o}=tj(t,{relative:n}),l=a;return r!=="/"&&(l=a==="/"?r:Il([r,a])),s.createHref({pathname:l,search:o,hash:i})}function Lh(){return C.useContext(Sv)!=null}function Qi(){return Lh()||or(!1),C.useContext(Sv).location}function ej(t){C.useContext(Yl).static||C.useLayoutEffect(t)}function lr(){let{isDataRoute:t}=C.useContext(Xl);return t?oK():YG()}function YG(){Lh()||or(!1);let t=C.useContext(ZT),{basename:e,future:n,navigator:r}=C.useContext(Yl),{matches:s}=C.useContext(Xl),{pathname:i}=Qi(),a=JSON.stringify(QT(s,n.v7_relativeSplatPath)),o=C.useRef(!1);return ej(()=>{o.current=!0}),C.useCallback(function(c,u){if(u===void 0&&(u={}),!o.current)return;if(typeof c=="number"){r.go(c);return}let d=JT(c,JSON.parse(a),i,u.relative==="path");t==null&&e!=="/"&&(d.pathname=d.pathname==="/"?e:Il([e,d.pathname])),(u.replace?r.replace:r.push)(d,u.state,u)},[e,r,a,i,t])}function tj(t,e){let{relative:n}=e===void 0?{}:e,{future:r}=C.useContext(Yl),{matches:s}=C.useContext(Xl),{pathname:i}=Qi(),a=JSON.stringify(QT(s,r.v7_relativeSplatPath));return C.useMemo(()=>JT(t,JSON.parse(a),i,n==="path"),[t,a,i,n])}function XG(t,e){return QG(t,e)}function QG(t,e,n,r){Lh()||or(!1);let{navigator:s}=C.useContext(Yl),{matches:i}=C.useContext(Xl),a=i[i.length-1],o=a?a.params:{};a&&a.pathname;let l=a?a.pathnameBase:"/";a&&a.route;let c=Qi(),u;if(e){var d;let y=typeof e=="string"?fu(e):e;l==="/"||(d=y.pathname)!=null&&d.startsWith(l)||or(!1),u=y}else u=c;let h=u.pathname||"/",f=h;if(l!=="/"){let y=l.replace(/^\//,"").split("/");f="/"+h.replace(/^\//,"").split("/").slice(y.length).join("/")}let m=EG(t,{pathname:f}),g=nK(m&&m.map(y=>Object.assign({},y,{params:Object.assign({},o,y.params),pathname:Il([l,s.encodeLocation?s.encodeLocation(y.pathname).pathname:y.pathname]),pathnameBase:y.pathnameBase==="/"?l:Il([l,s.encodeLocation?s.encodeLocation(y.pathnameBase).pathname:y.pathnameBase])})),i,n,r);return e&&g?C.createElement(Sv.Provider,{value:{location:Ep({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:bl.Pop}},g):g}function JG(){let t=aK(),e=HG(t)?t.status+" "+t.statusText:t instanceof Error?t.message:JSON.stringify(t),n=t instanceof Error?t.stack:null,s={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return C.createElement(C.Fragment,null,C.createElement("h2",null,"Unexpected Application Error!"),C.createElement("h3",{style:{fontStyle:"italic"}},e),n?C.createElement("pre",{style:s},n):null,null)}const ZG=C.createElement(JG,null);class eK extends C.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?C.createElement(Xl.Provider,{value:this.props.routeContext},C.createElement(ZM.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function tK(t){let{routeContext:e,match:n,children:r}=t,s=C.useContext(ZT);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),C.createElement(Xl.Provider,{value:e},r)}function nK(t,e,n,r){var s;if(e===void 0&&(e=[]),n===void 0&&(n=null),r===void 0&&(r=null),t==null){var i;if(!n)return null;if(n.errors)t=n.matches;else if((i=r)!=null&&i.v7_partialHydration&&e.length===0&&!n.initialized&&n.matches.length>0)t=n.matches;else return null}let a=t,o=(s=n)==null?void 0:s.errors;if(o!=null){let u=a.findIndex(d=>d.route.id&&(o==null?void 0:o[d.route.id])!==void 0);u>=0||or(!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,m=d.route.loader&&h[d.route.id]===void 0&&(!f||f[d.route.id]===void 0);if(d.route.lazy||m){l=!0,c>=0?a=a.slice(0,c+1):a=[a[0]];break}}}return a.reduceRight((u,d,h)=>{let f,m=!1,g=null,y=null;n&&(f=o&&d.route.id?o[d.route.id]:void 0,g=d.route.errorElement||ZG,l&&(c<0&&h===0?(lK("route-fallback"),m=!0,y=null):c===h&&(m=!0,y=d.route.hydrateFallbackElement||null)));let v=e.concat(a.slice(0,h+1)),_=()=>{let S;return f?S=g:m?S=y:d.route.Component?S=C.createElement(d.route.Component,null):d.route.element?S=d.route.element:S=u,C.createElement(tK,{match:d,routeContext:{outlet:u,matches:v,isDataRoute:n!=null},children:S})};return n&&(d.route.ErrorBoundary||d.route.errorElement||h===0)?C.createElement(eK,{location:n.location,revalidation:n.revalidation,component:g,error:f,children:_(),routeContext:{outlet:null,matches:v,isDataRoute:!0}}):_()},null)}var nj=function(t){return t.UseBlocker="useBlocker",t.UseRevalidator="useRevalidator",t.UseNavigateStable="useNavigate",t}(nj||{}),rj=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}(rj||{});function rK(t){let e=C.useContext(ZT);return e||or(!1),e}function sK(t){let e=C.useContext(qG);return e||or(!1),e}function iK(t){let e=C.useContext(Xl);return e||or(!1),e}function sj(t){let e=iK(),n=e.matches[e.matches.length-1];return n.route.id||or(!1),n.route.id}function aK(){var t;let e=C.useContext(ZM),n=sK(),r=sj();return e!==void 0?e:(t=n.errors)==null?void 0:t[r]}function oK(){let{router:t}=rK(nj.UseNavigateStable),e=sj(rj.UseNavigateStable),n=C.useRef(!1);return ej(()=>{n.current=!0}),C.useCallback(function(s,i){i===void 0&&(i={}),n.current&&(typeof s=="number"?t.navigate(s):t.navigate(s,Ep({fromRouteId:e},i)))},[t,e])}const YC={};function lK(t,e,n){YC[t]||(YC[t]=!0)}function ij(t,e){t==null||t.v7_startTransition,t==null||t.v7_relativeSplatPath}function p0(t){let{to:e,replace:n,state:r,relative:s}=t;Lh()||or(!1);let{future:i,static:a}=C.useContext(Yl),{matches:o}=C.useContext(Xl),{pathname:l}=Qi(),c=lr(),u=JT(e,QT(o,i.v7_relativeSplatPath),l,s==="path"),d=JSON.stringify(u);return C.useEffect(()=>c(JSON.parse(d),{replace:n,state:r,relative:s}),[c,d,s,n,r]),null}function jr(t){or(!1)}function aj(t){let{basename:e="/",children:n=null,location:r,navigationType:s=bl.Pop,navigator:i,static:a=!1,future:o}=t;Lh()&&or(!1);let l=e.replace(/^\/*/,"/"),c=C.useMemo(()=>({basename:l,navigator:i,static:a,future:Ep({v7_relativeSplatPath:!1},o)}),[l,o,i,a]);typeof r=="string"&&(r=fu(r));let{pathname:u="/",search:d="",hash:h="",state:f=null,key:m="default"}=r,g=C.useMemo(()=>{let y=XT(u,l);return y==null?null:{location:{pathname:y,search:d,hash:h,state:f,key:m},navigationType:s}},[l,u,d,h,f,m,s]);return g==null?null:C.createElement(Yl.Provider,{value:c},C.createElement(Sv.Provider,{children:n,value:g}))}function cK(t){let{children:e,location:n}=t;return XG(eE(e),n)}new Promise(()=>{});function eE(t,e){e===void 0&&(e=[]);let n=[];return C.Children.forEach(t,(r,s)=>{if(!C.isValidElement(r))return;let i=[...e,s];if(r.type===C.Fragment){n.push.apply(n,eE(r.props.children,i));return}r.type!==jr&&or(!1),!r.props.index||!r.props.children||or(!1);let a={id:r.props.id||i.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=eE(r.props.children,i)),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 tE(){return tE=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},tE.apply(this,arguments)}function uK(t,e){if(t==null)return{};var n={},r=Object.keys(t),s,i;for(i=0;i<r.length;i++)s=r[i],!(e.indexOf(s)>=0)&&(n[s]=t[s]);return n}function dK(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}function hK(t,e){return t.button===0&&(!e||e==="_self")&&!dK(t)}function nE(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(s=>[n,s]):[[n,r]])},[]))}function fK(t,e){let n=nE(t);return e&&e.forEach((r,s)=>{n.has(s)||e.getAll(s).forEach(i=>{n.append(s,i)})}),n}const pK=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],mK="6";try{window.__reactRouterVersion=mK}catch{}const gK="startTransition",m0=Qw[gK];function yK(t){let{basename:e,children:n,future:r,window:s}=t,i=C.useRef();i.current==null&&(i.current=bG({window:s,v5Compat:!0}));let a=i.current,[o,l]=C.useState({action:a.action,location:a.location}),{v7_startTransition:c}=r||{},u=C.useCallback(d=>{c&&m0?m0(()=>l(d)):l(d)},[l,c]);return C.useLayoutEffect(()=>a.listen(u),[a,u]),C.useEffect(()=>ij(r),[r]),C.createElement(aj,{basename:e,children:n,location:o.location,navigationType:o.action,navigator:a,future:r})}function vK(t){let{basename:e,children:n,future:r,window:s}=t,i=C.useRef();i.current==null&&(i.current=xG({window:s,v5Compat:!0}));let a=i.current,[o,l]=C.useState({action:a.action,location:a.location}),{v7_startTransition:c}=r||{},u=C.useCallback(d=>{c&&m0?m0(()=>l(d)):l(d)},[l,c]);return C.useLayoutEffect(()=>a.listen(u),[a,u]),C.useEffect(()=>ij(r),[r]),C.createElement(aj,{basename:e,children:n,location:o.location,navigationType:o.action,navigator:a,future:r})}const _K=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",bK=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,e1=C.forwardRef(function(e,n){let{onClick:r,relative:s,reloadDocument:i,replace:a,state:o,target:l,to:c,preventScrollReset:u,viewTransition:d}=e,h=uK(e,pK),{basename:f}=C.useContext(Yl),m,g=!1;if(typeof c=="string"&&bK.test(c)&&(m=c,_K))try{let S=new URL(window.location.href),E=c.startsWith("//")?new URL(S.protocol+c):new URL(c),L=XT(E.pathname,f);E.origin===S.origin&&L!=null?c=L+E.search+E.hash:g=!0}catch{}let y=WG(c,{relative:s}),v=xK(c,{replace:a,state:o,target:l,preventScrollReset:u,relative:s,viewTransition:d});function _(S){r&&r(S),S.defaultPrevented||v(S)}return C.createElement("a",tE({},h,{href:m||y,onClick:g||i?r:_,ref:n,target:l}))});var XC;(function(t){t.UseScrollRestoration="useScrollRestoration",t.UseSubmit="useSubmit",t.UseSubmitFetcher="useSubmitFetcher",t.UseFetcher="useFetcher",t.useViewTransitionState="useViewTransitionState"})(XC||(XC={}));var QC;(function(t){t.UseFetcher="useFetcher",t.UseFetchers="useFetchers",t.UseScrollRestoration="useScrollRestoration"})(QC||(QC={}));function xK(t,e){let{target:n,replace:r,state:s,preventScrollReset:i,relative:a,viewTransition:o}=e===void 0?{}:e,l=lr(),c=Qi(),u=tj(t,{relative:a});return C.useCallback(d=>{if(hK(d,n)){d.preventDefault();let h=r!==void 0?r:Sp(c)===Sp(u);l(t,{replace:h,state:s,preventScrollReset:i,relative:a,viewTransition:o})}},[c,l,u,r,s,n,t,i,a,o])}function t1(t){let e=C.useRef(nE(t)),n=C.useRef(!1),r=Qi(),s=C.useMemo(()=>fK(r.search,n.current?null:e.current),[r.search]),i=lr(),a=C.useCallback((o,l)=>{const c=nE(typeof o=="function"?o(s):o);n.current=!0,i("?"+c,l)},[i,s]);return[s,a]}var JC=["light","dark"],SK="(prefers-color-scheme: dark)",EK=C.createContext(void 0),wK={setTheme:t=>{},themes:[]},TK=()=>{var t;return(t=C.useContext(EK))!=null?t:wK};C.memo(({forcedTheme:t,storageKey:e,attribute:n,enableSystem:r,enableColorScheme:s,defaultTheme:i,value:a,attrs:o,nonce:l})=>{let c=i==="system",u=n==="class"?`var d=document.documentElement,c=d.classList;${`c.remove(${o.map(m=>`'${m}'`).join(",")})`};`:`var d=document.documentElement,n='${n}',s='setAttribute';`,d=s?JC.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",h=(m,g=!1,y=!0)=>{let v=a?a[m]:m,_=g?m+"|| ''":`'${v}'`,S="";return s&&y&&!g&&JC.includes(m)&&(S+=`d.style.colorScheme = '${m}';`),n==="class"?g||v?S+=`c.add(${_})`:S+="null":v&&(S+=`d[s](n,${_})`),S},f=t?`!function(){${u}${h(t)}}()`:r?`!function(){try{${u}var e=localStorage.getItem('${e}');if('system'===e||(!e&&${c})){var t='${SK}',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(i,!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(i,!1,!1)};}${d}}catch(t){}}();`;return C.createElement("script",{nonce:l,dangerouslySetInnerHTML:{__html:f}})});var AK=t=>{switch(t){case"success":return kK;case"info":return IK;case"warning":return LK;case"error":return PK;default:return null}},RK=Array(12).fill(0),CK=({visible:t,className:e})=>Be.createElement("div",{className:["sonner-loading-wrapper",e].filter(Boolean).join(" "),"data-visible":t},Be.createElement("div",{className:"sonner-spinner"},RK.map((n,r)=>Be.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),kK=Be.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Be.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"})),LK=Be.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},Be.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"})),IK=Be.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Be.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"})),PK=Be.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Be.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"})),DK=Be.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"},Be.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),Be.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),OK=()=>{let[t,e]=Be.useState(document.hidden);return Be.useEffect(()=>{let n=()=>{e(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),t},rE=1,NK=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,s=typeof(t==null?void 0:t.id)=="number"||((e=t.id)==null?void 0:e.length)>0?t.id:rE++,i=this.toasts.find(o=>o.id===s),a=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(s)&&this.dismissedToasts.delete(s),i?this.toasts=this.toasts.map(o=>o.id===s?(this.publish({...o,...t,id:s,title:n}),{...o,...t,id:s,dismissible:a,title:n}):o):this.addToast({title:n,...r,dismissible:a,id:s}),s},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(),s=n!==void 0,i,a=r.then(async l=>{if(i=["resolve",l],Be.isValidElement(l))s=!1,this.create({id:n,type:"default",message:l});else if(jK(l)&&!l.ok){s=!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){s=!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(i=["reject",l],e.error!==void 0){s=!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;s&&(this.dismiss(n),n=void 0),(l=e.finally)==null||l.call(e)}),o=()=>new Promise((l,c)=>a.then(()=>i[0]==="reject"?c(i[1]):l(i[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)||rE++;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}},Cs=new NK,MK=(t,e)=>{let n=(e==null?void 0:e.id)||rE++;return Cs.addToast({title:t,...e,id:n}),n},jK=t=>t&&typeof t=="object"&&"ok"in t&&typeof t.ok=="boolean"&&"status"in t&&typeof t.status=="number",UK=MK,BK=()=>Cs.toasts,FK=()=>Cs.getActiveToasts(),It=Object.assign(UK,{success:Cs.success,info:Cs.info,warning:Cs.warning,error:Cs.error,custom:Cs.custom,message:Cs.message,promise:Cs.promise,dismiss:Cs.dismiss,loading:Cs.loading},{getHistory:BK,getToasts:FK});function $K(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))}$K(`: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 dg(t){return t.label!==void 0}var VK=3,GK="32px",KK="16px",ZC=4e3,HK=356,zK=14,qK=20,WK=200;function Oi(...t){return t.filter(Boolean).join(" ")}function YK(t){let[e,n]=t.split("-"),r=[];return e&&r.push(e),n&&r.push(n),r}var XK=t=>{var e,n,r,s,i,a,o,l,c,u,d;let{invert:h,toast:f,unstyled:m,interacting:g,setHeights:y,visibleToasts:v,heights:_,index:S,toasts:E,expanded:L,removeToast:U,defaultRichColors:P,closeButton:I,style:k,cancelButtonStyle:R,actionButtonStyle:M,className:G="",descriptionClassName:Y="",duration:q,position:X,gap:Z,loadingIcon:oe,expandByDefault:ne,classNames:H,icons:K,closeButtonAriaLabel:J="Close toast",pauseWhenPageIsHidden:Q}=t,[ve,Te]=Be.useState(null),[Ne,Ke]=Be.useState(null),[be,Pe]=Be.useState(!1),[Ae,we]=Be.useState(!1),[Ue,Oe]=Be.useState(!1),[Dt,en]=Be.useState(!1),[wn,it]=Be.useState(!1),[nn,mn]=Be.useState(0),[On,Cn]=Be.useState(0),ln=Be.useRef(f.duration||q||ZC),Nn=Be.useRef(null),cr=Be.useRef(null),Ds=S===0,lt=S+1<=v,ht=f.type,Vt=f.dismissible!==!1,Dr=f.className||"",vs=f.descriptionClassName||"",Os=Be.useMemo(()=>_.findIndex(St=>St.toastId===f.id)||0,[_,f.id]),_s=Be.useMemo(()=>{var St;return(St=f.closeButton)!=null?St:I},[f.closeButton,I]),ii=Be.useMemo(()=>f.duration||q||ZC,[f.duration,q]),ea=Be.useRef(0),ai=Be.useRef(0),bs=Be.useRef(0),st=Be.useRef(null),[Ua,Pi]=X.split("-"),Ba=Be.useMemo(()=>_.reduce((St,Gt,cn)=>cn>=Os?St:St+Gt.height,0),[_,Os]),Qe=OK(),Jl=f.invert||h,Oo=ht==="loading";ai.current=Be.useMemo(()=>Os*Z+Ba,[Os,Ba]),Be.useEffect(()=>{ln.current=ii},[ii]),Be.useEffect(()=>{Pe(!0)},[]),Be.useEffect(()=>{let St=cr.current;if(St){let Gt=St.getBoundingClientRect().height;return Cn(Gt),y(cn=>[{toastId:f.id,height:Gt,position:f.position},...cn]),()=>y(cn=>cn.filter(Zn=>Zn.toastId!==f.id))}},[y,f.id]),Be.useLayoutEffect(()=>{if(!be)return;let St=cr.current,Gt=St.style.height;St.style.height="auto";let cn=St.getBoundingClientRect().height;St.style.height=Gt,Cn(cn),y(Zn=>Zn.find(er=>er.toastId===f.id)?Zn.map(er=>er.toastId===f.id?{...er,height:cn}:er):[{toastId:f.id,height:cn,position:f.position},...Zn])},[be,f.title,f.description,y,f.id]);let xs=Be.useCallback(()=>{we(!0),mn(ai.current),y(St=>St.filter(Gt=>Gt.toastId!==f.id)),setTimeout(()=>{U(f)},WK)},[f,U,y,ai]);Be.useEffect(()=>{if(f.promise&&ht==="loading"||f.duration===1/0||f.type==="loading")return;let St;return L||g||Q&&Qe?(()=>{if(bs.current<ea.current){let Gt=new Date().getTime()-ea.current;ln.current=ln.current-Gt}bs.current=new Date().getTime()})():ln.current!==1/0&&(ea.current=new Date().getTime(),St=setTimeout(()=>{var Gt;(Gt=f.onAutoClose)==null||Gt.call(f,f),xs()},ln.current)),()=>clearTimeout(St)},[L,g,f,ht,Q,Qe,xs]),Be.useEffect(()=>{f.delete&&xs()},[xs,f.delete]);function yu(){var St,Gt,cn;return K!=null&&K.loading?Be.createElement("div",{className:Oi(H==null?void 0:H.loader,(St=f==null?void 0:f.classNames)==null?void 0:St.loader,"sonner-loader"),"data-visible":ht==="loading"},K.loading):oe?Be.createElement("div",{className:Oi(H==null?void 0:H.loader,(Gt=f==null?void 0:f.classNames)==null?void 0:Gt.loader,"sonner-loader"),"data-visible":ht==="loading"},oe):Be.createElement(CK,{className:Oi(H==null?void 0:H.loader,(cn=f==null?void 0:f.classNames)==null?void 0:cn.loader),visible:ht==="loading"})}return Be.createElement("li",{tabIndex:0,ref:cr,className:Oi(G,Dr,H==null?void 0:H.toast,(e=f==null?void 0:f.classNames)==null?void 0:e.toast,H==null?void 0:H.default,H==null?void 0:H[ht],(n=f==null?void 0:f.classNames)==null?void 0:n[ht]),"data-sonner-toast":"","data-rich-colors":(r=f.richColors)!=null?r:P,"data-styled":!(f.jsx||f.unstyled||m),"data-mounted":be,"data-promise":!!f.promise,"data-swiped":wn,"data-removed":Ae,"data-visible":lt,"data-y-position":Ua,"data-x-position":Pi,"data-index":S,"data-front":Ds,"data-swiping":Ue,"data-dismissible":Vt,"data-type":ht,"data-invert":Jl,"data-swipe-out":Dt,"data-swipe-direction":Ne,"data-expanded":!!(L||ne&&be),style:{"--index":S,"--toasts-before":S,"--z-index":E.length-S,"--offset":`${Ae?nn:ai.current}px`,"--initial-height":ne?"auto":`${On}px`,...k,...f.style},onDragEnd:()=>{Oe(!1),Te(null),st.current=null},onPointerDown:St=>{Oo||!Vt||(Nn.current=new Date,mn(ai.current),St.target.setPointerCapture(St.pointerId),St.target.tagName!=="BUTTON"&&(Oe(!0),st.current={x:St.clientX,y:St.clientY}))},onPointerUp:()=>{var St,Gt,cn,Zn;if(Dt||!Vt)return;st.current=null;let er=Number(((St=cr.current)==null?void 0:St.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),mr=Number(((Gt=cr.current)==null?void 0:Gt.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),ss=new Date().getTime()-((cn=Nn.current)==null?void 0:cn.getTime()),kt=ve==="x"?er:mr,an=Math.abs(kt)/ss;if(Math.abs(kt)>=qK||an>.11){mn(ai.current),(Zn=f.onDismiss)==null||Zn.call(f,f),Ke(ve==="x"?er>0?"right":"left":mr>0?"down":"up"),xs(),en(!0),it(!1);return}Oe(!1),Te(null)},onPointerMove:St=>{var Gt,cn,Zn,er;if(!st.current||!Vt||((Gt=window.getSelection())==null?void 0:Gt.toString().length)>0)return;let mr=St.clientY-st.current.y,ss=St.clientX-st.current.x,kt=(cn=t.swipeDirections)!=null?cn:YK(X);!ve&&(Math.abs(ss)>1||Math.abs(mr)>1)&&Te(Math.abs(ss)>Math.abs(mr)?"x":"y");let an={x:0,y:0};ve==="y"?(kt.includes("top")||kt.includes("bottom"))&&(kt.includes("top")&&mr<0||kt.includes("bottom")&&mr>0)&&(an.y=mr):ve==="x"&&(kt.includes("left")||kt.includes("right"))&&(kt.includes("left")&&ss<0||kt.includes("right")&&ss>0)&&(an.x=ss),(Math.abs(an.x)>0||Math.abs(an.y)>0)&&it(!0),(Zn=cr.current)==null||Zn.style.setProperty("--swipe-amount-x",`${an.x}px`),(er=cr.current)==null||er.style.setProperty("--swipe-amount-y",`${an.y}px`)}},_s&&!f.jsx?Be.createElement("button",{"aria-label":J,"data-disabled":Oo,"data-close-button":!0,onClick:Oo||!Vt?()=>{}:()=>{var St;xs(),(St=f.onDismiss)==null||St.call(f,f)},className:Oi(H==null?void 0:H.closeButton,(s=f==null?void 0:f.classNames)==null?void 0:s.closeButton)},(i=K==null?void 0:K.close)!=null?i:DK):null,f.jsx||C.isValidElement(f.title)?f.jsx?f.jsx:typeof f.title=="function"?f.title():f.title:Be.createElement(Be.Fragment,null,ht||f.icon||f.promise?Be.createElement("div",{"data-icon":"",className:Oi(H==null?void 0:H.icon,(a=f==null?void 0:f.classNames)==null?void 0:a.icon)},f.promise||f.type==="loading"&&!f.icon?f.icon||yu():null,f.type!=="loading"?f.icon||(K==null?void 0:K[ht])||AK(ht):null):null,Be.createElement("div",{"data-content":"",className:Oi(H==null?void 0:H.content,(o=f==null?void 0:f.classNames)==null?void 0:o.content)},Be.createElement("div",{"data-title":"",className:Oi(H==null?void 0:H.title,(l=f==null?void 0:f.classNames)==null?void 0:l.title)},typeof f.title=="function"?f.title():f.title),f.description?Be.createElement("div",{"data-description":"",className:Oi(Y,vs,H==null?void 0:H.description,(c=f==null?void 0:f.classNames)==null?void 0:c.description)},typeof f.description=="function"?f.description():f.description):null),C.isValidElement(f.cancel)?f.cancel:f.cancel&&dg(f.cancel)?Be.createElement("button",{"data-button":!0,"data-cancel":!0,style:f.cancelButtonStyle||R,onClick:St=>{var Gt,cn;dg(f.cancel)&&Vt&&((cn=(Gt=f.cancel).onClick)==null||cn.call(Gt,St),xs())},className:Oi(H==null?void 0:H.cancelButton,(u=f==null?void 0:f.classNames)==null?void 0:u.cancelButton)},f.cancel.label):null,C.isValidElement(f.action)?f.action:f.action&&dg(f.action)?Be.createElement("button",{"data-button":!0,"data-action":!0,style:f.actionButtonStyle||M,onClick:St=>{var Gt,cn;dg(f.action)&&((cn=(Gt=f.action).onClick)==null||cn.call(Gt,St),!St.defaultPrevented&&xs())},className:Oi(H==null?void 0:H.actionButton,(d=f==null?void 0:f.classNames)==null?void 0:d.actionButton)},f.action.label):null))};function ek(){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 QK(t,e){let n={};return[t,e].forEach((r,s)=>{let i=s===1,a=i?"--mobile-offset":"--offset",o=i?KK:GK;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 JK=C.forwardRef(function(t,e){let{invert:n,position:r="bottom-right",hotkey:s=["altKey","KeyT"],expand:i,closeButton:a,className:o,offset:l,mobileOffset:c,theme:u="light",richColors:d,duration:h,style:f,visibleToasts:m=VK,toastOptions:g,dir:y=ek(),gap:v=zK,loadingIcon:_,icons:S,containerAriaLabel:E="Notifications",pauseWhenPageIsHidden:L}=t,[U,P]=Be.useState([]),I=Be.useMemo(()=>Array.from(new Set([r].concat(U.filter(Q=>Q.position).map(Q=>Q.position)))),[U,r]),[k,R]=Be.useState([]),[M,G]=Be.useState(!1),[Y,q]=Be.useState(!1),[X,Z]=Be.useState(u!=="system"?u:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),oe=Be.useRef(null),ne=s.join("+").replace(/Key/g,"").replace(/Digit/g,""),H=Be.useRef(null),K=Be.useRef(!1),J=Be.useCallback(Q=>{P(ve=>{var Te;return(Te=ve.find(Ne=>Ne.id===Q.id))!=null&&Te.delete||Cs.dismiss(Q.id),ve.filter(({id:Ne})=>Ne!==Q.id)})},[]);return Be.useEffect(()=>Cs.subscribe(Q=>{if(Q.dismiss){P(ve=>ve.map(Te=>Te.id===Q.id?{...Te,delete:!0}:Te));return}setTimeout(()=>{tN.flushSync(()=>{P(ve=>{let Te=ve.findIndex(Ne=>Ne.id===Q.id);return Te!==-1?[...ve.slice(0,Te),{...ve[Te],...Q},...ve.slice(Te+1)]:[Q,...ve]})})})}),[]),Be.useEffect(()=>{if(u!=="system"){Z(u);return}if(u==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?Z("dark"):Z("light")),typeof window>"u")return;let Q=window.matchMedia("(prefers-color-scheme: dark)");try{Q.addEventListener("change",({matches:ve})=>{Z(ve?"dark":"light")})}catch{Q.addListener(({matches:Te})=>{try{Z(Te?"dark":"light")}catch(Ne){console.error(Ne)}})}},[u]),Be.useEffect(()=>{U.length<=1&&G(!1)},[U]),Be.useEffect(()=>{let Q=ve=>{var Te,Ne;s.every(Ke=>ve[Ke]||ve.code===Ke)&&(G(!0),(Te=oe.current)==null||Te.focus()),ve.code==="Escape"&&(document.activeElement===oe.current||(Ne=oe.current)!=null&&Ne.contains(document.activeElement))&&G(!1)};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[s]),Be.useEffect(()=>{if(oe.current)return()=>{H.current&&(H.current.focus({preventScroll:!0}),H.current=null,K.current=!1)}},[oe.current]),Be.createElement("section",{ref:e,"aria-label":`${E} ${ne}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},I.map((Q,ve)=>{var Te;let[Ne,Ke]=Q.split("-");return U.length?Be.createElement("ol",{key:Q,dir:y==="auto"?ek():y,tabIndex:-1,ref:oe,className:o,"data-sonner-toaster":!0,"data-theme":X,"data-y-position":Ne,"data-lifted":M&&U.length>1&&!i,"data-x-position":Ke,style:{"--front-toast-height":`${((Te=k[0])==null?void 0:Te.height)||0}px`,"--width":`${HK}px`,"--gap":`${v}px`,...f,...QK(l,c)},onBlur:be=>{K.current&&!be.currentTarget.contains(be.relatedTarget)&&(K.current=!1,H.current&&(H.current.focus({preventScroll:!0}),H.current=null))},onFocus:be=>{be.target instanceof HTMLElement&&be.target.dataset.dismissible==="false"||K.current||(K.current=!0,H.current=be.relatedTarget)},onMouseEnter:()=>G(!0),onMouseMove:()=>G(!0),onMouseLeave:()=>{Y||G(!1)},onDragEnd:()=>G(!1),onPointerDown:be=>{be.target instanceof HTMLElement&&be.target.dataset.dismissible==="false"||q(!0)},onPointerUp:()=>q(!1)},U.filter(be=>!be.position&&ve===0||be.position===Q).map((be,Pe)=>{var Ae,we;return Be.createElement(XK,{key:be.id,icons:S,index:Pe,toast:be,defaultRichColors:d,duration:(Ae=g==null?void 0:g.duration)!=null?Ae:h,className:g==null?void 0:g.className,descriptionClassName:g==null?void 0:g.descriptionClassName,invert:n,visibleToasts:m,closeButton:(we=g==null?void 0:g.closeButton)!=null?we:a,interacting:Y,position:Q,style:g==null?void 0:g.style,unstyled:g==null?void 0:g.unstyled,classNames:g==null?void 0:g.classNames,cancelButtonStyle:g==null?void 0:g.cancelButtonStyle,actionButtonStyle:g==null?void 0:g.actionButtonStyle,removeToast:J,toasts:U.filter(Ue=>Ue.position==be.position),heights:k.filter(Ue=>Ue.position==be.position),setHeights:R,expandByDefault:i,gap:v,loadingIcon:_,expanded:M,pauseWhenPageIsHidden:L,swipeDirections:t.swipeDirections})})):null}))});const ZK=({...t})=>{const{theme:e="system"}=TK();return p.jsx(JK,{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})},eH=1,tH=1e6;let db=0;function nH(){return db=(db+1)%Number.MAX_SAFE_INTEGER,db.toString()}const hb=new Map,tk=t=>{if(hb.has(t))return;const e=setTimeout(()=>{hb.delete(t),Vf({type:"REMOVE_TOAST",toastId:t})},tH);hb.set(t,e)},rH=(t,e)=>{switch(e.type){case"ADD_TOAST":return{...t,toasts:[e.toast,...t.toasts].slice(0,eH)};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?tk(n):t.toasts.forEach(r=>{tk(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)}}},fy=[];let py={toasts:[]};function Vf(t){py=rH(py,t),fy.forEach(e=>{e(py)})}function sH({...t}){const e=nH(),n=s=>Vf({type:"UPDATE_TOAST",toast:{...s,id:e}}),r=()=>Vf({type:"DISMISS_TOAST",toastId:e});return Vf({type:"ADD_TOAST",toast:{...t,id:e,open:!0,onOpenChange:s=>{s||r()}}}),{id:e,dismiss:r,update:n}}function iH(){const[t,e]=C.useState(py);return C.useEffect(()=>(fy.push(e),()=>{const n=fy.indexOf(e);n>-1&&fy.splice(n,1)}),[t]),{...t,toast:sH,dismiss:n=>Vf({type:"DISMISS_TOAST",toastId:n})}}function Un(t,e,{checkForDefaultPrevented:n=!0}={}){return function(s){if(t==null||t(s),n===!1||!s.defaultPrevented)return e==null?void 0:e(s)}}function nk(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Ev(...t){return e=>{let n=!1;const r=t.map(s=>{const i=nk(s,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let s=0;s<r.length;s++){const i=r[s];typeof i=="function"?i():nk(t[s],null)}}}}function ps(...t){return C.useCallback(Ev(...t),t)}function aH(t,e){const n=C.createContext(e),r=i=>{const{children:a,...o}=i,l=C.useMemo(()=>o,Object.values(o));return p.jsx(n.Provider,{value:l,children:a})};r.displayName=t+"Provider";function s(i){const a=C.useContext(n);if(a)return a;if(e!==void 0)return e;throw new Error(`\`${i}\` must be used within \`${t}\``)}return[r,s]}function ym(t,e=[]){let n=[];function r(i,a){const o=C.createContext(a),l=n.length;n=[...n,a];const c=d=>{var v;const{scope:h,children:f,...m}=d,g=((v=h==null?void 0:h[t])==null?void 0:v[l])||o,y=C.useMemo(()=>m,Object.values(m));return p.jsx(g.Provider,{value:y,children:f})};c.displayName=i+"Provider";function u(d,h){var g;const f=((g=h==null?void 0:h[t])==null?void 0:g[l])||o,m=C.useContext(f);if(m)return m;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}const s=()=>{const i=n.map(a=>C.createContext(a));return function(o){const l=(o==null?void 0:o[t])||i;return C.useMemo(()=>({[`__scope${t}`]:{...o,[t]:l}}),[o,l])}};return s.scopeName=t,[r,oH(s,...e)]}function oH(...t){const e=t[0];if(t.length===1)return e;const n=()=>{const r=t.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(i){const a=r.reduce((o,{useScope:l,scopeName:c})=>{const d=l(i)[`__scope${c}`];return{...o,...d}},{});return C.useMemo(()=>({[`__scope${e.scopeName}`]:a}),[a])}};return n.scopeName=e.scopeName,n}function rk(t){const e=lH(t),n=C.forwardRef((r,s)=>{const{children:i,...a}=r,o=C.Children.toArray(i),l=o.find(uH);if(l){const c=l.props.children,u=o.map(d=>d===l?C.Children.count(c)>1?C.Children.only(null):C.isValidElement(c)?c.props.children:null:d);return p.jsx(e,{...a,ref:s,children:C.isValidElement(c)?C.cloneElement(c,void 0,u):null})}return p.jsx(e,{...a,ref:s,children:i})});return n.displayName=`${t}.Slot`,n}function lH(t){const e=C.forwardRef((n,r)=>{const{children:s,...i}=n;if(C.isValidElement(s)){const a=hH(s),o=dH(i,s.props);return s.type!==C.Fragment&&(o.ref=r?Ev(r,a):a),C.cloneElement(s,o)}return C.Children.count(s)>1?C.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var cH=Symbol("radix.slottable");function uH(t){return C.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===cH}function dH(t,e){const n={...e};for(const r in e){const s=t[r],i=e[r];/^on[A-Z]/.test(r)?s&&i?n[r]=(...o)=>{const l=i(...o);return s(...o),l}:s&&(n[r]=s):r==="style"?n[r]={...s,...i}:r==="className"&&(n[r]=[s,i].filter(Boolean).join(" "))}return{...t,...n}}function hH(t){var r,s;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=(s=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:s.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}function fH(t){const e=t+"CollectionProvider",[n,r]=ym(e),[s,i]=n(e,{collectionRef:{current:null},itemMap:new Map}),a=g=>{const{scope:y,children:v}=g,_=Be.useRef(null),S=Be.useRef(new Map).current;return p.jsx(s,{scope:y,itemMap:S,collectionRef:_,children:v})};a.displayName=e;const o=t+"CollectionSlot",l=rk(o),c=Be.forwardRef((g,y)=>{const{scope:v,children:_}=g,S=i(o,v),E=ps(y,S.collectionRef);return p.jsx(l,{ref:E,children:_})});c.displayName=o;const u=t+"CollectionItemSlot",d="data-radix-collection-item",h=rk(u),f=Be.forwardRef((g,y)=>{const{scope:v,children:_,...S}=g,E=Be.useRef(null),L=ps(y,E),U=i(u,v);return Be.useEffect(()=>(U.itemMap.set(E,{ref:E,...S}),()=>void U.itemMap.delete(E))),p.jsx(h,{[d]:"",ref:L,children:_})});f.displayName=u;function m(g){const y=i(t+"CollectionConsumer",g);return Be.useCallback(()=>{const _=y.collectionRef.current;if(!_)return[];const S=Array.from(_.querySelectorAll(`[${d}]`));return Array.from(y.itemMap.values()).sort((U,P)=>S.indexOf(U.ref.current)-S.indexOf(P.ref.current))},[y.collectionRef,y.itemMap])}return[{Provider:a,Slot:c,ItemSlot:f},m,r]}function pH(t){const e=mH(t),n=C.forwardRef((r,s)=>{const{children:i,...a}=r,o=C.Children.toArray(i),l=o.find(yH);if(l){const c=l.props.children,u=o.map(d=>d===l?C.Children.count(c)>1?C.Children.only(null):C.isValidElement(c)?c.props.children:null:d);return p.jsx(e,{...a,ref:s,children:C.isValidElement(c)?C.cloneElement(c,void 0,u):null})}return p.jsx(e,{...a,ref:s,children:i})});return n.displayName=`${t}.Slot`,n}function mH(t){const e=C.forwardRef((n,r)=>{const{children:s,...i}=n;if(C.isValidElement(s)){const a=_H(s),o=vH(i,s.props);return s.type!==C.Fragment&&(o.ref=r?Ev(r,a):a),C.cloneElement(s,o)}return C.Children.count(s)>1?C.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var gH=Symbol("radix.slottable");function yH(t){return C.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===gH}function vH(t,e){const n={...e};for(const r in e){const s=t[r],i=e[r];/^on[A-Z]/.test(r)?s&&i?n[r]=(...o)=>{const l=i(...o);return s(...o),l}:s&&(n[r]=s):r==="style"?n[r]={...s,...i}:r==="className"&&(n[r]=[s,i].filter(Boolean).join(" "))}return{...t,...n}}function _H(t){var r,s;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=(s=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:s.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var bH=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],pr=bH.reduce((t,e)=>{const n=pH(`Primitive.${e}`),r=C.forwardRef((s,i)=>{const{asChild:a,...o}=s,l=a?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),p.jsx(l,{...o,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});function oj(t,e){t&&Zp.flushSync(()=>t.dispatchEvent(e))}function Ca(t){const e=C.useRef(t);return C.useEffect(()=>{e.current=t}),C.useMemo(()=>(...n)=>{var r;return(r=e.current)==null?void 0:r.call(e,...n)},[])}function xH(t,e=globalThis==null?void 0:globalThis.document){const n=Ca(t);C.useEffect(()=>{const r=s=>{s.key==="Escape"&&n(s)};return e.addEventListener("keydown",r,{capture:!0}),()=>e.removeEventListener("keydown",r,{capture:!0})},[n,e])}var SH="DismissableLayer",sE="dismissableLayer.update",EH="dismissableLayer.pointerDownOutside",wH="dismissableLayer.focusOutside",sk,lj=C.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),wv=C.forwardRef((t,e)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:s,onFocusOutside:i,onInteractOutside:a,onDismiss:o,...l}=t,c=C.useContext(lj),[u,d]=C.useState(null),h=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,f]=C.useState({}),m=ps(e,P=>d(P)),g=Array.from(c.layers),[y]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),v=g.indexOf(y),_=u?g.indexOf(u):-1,S=c.layersWithOutsidePointerEventsDisabled.size>0,E=_>=v,L=AH(P=>{const I=P.target,k=[...c.branches].some(R=>R.contains(I));!E||k||(s==null||s(P),a==null||a(P),P.defaultPrevented||o==null||o())},h),U=RH(P=>{const I=P.target;[...c.branches].some(R=>R.contains(I))||(i==null||i(P),a==null||a(P),P.defaultPrevented||o==null||o())},h);return xH(P=>{_===c.layers.size-1&&(r==null||r(P),!P.defaultPrevented&&o&&(P.preventDefault(),o()))},h),C.useEffect(()=>{if(u)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(sk=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(u)),c.layers.add(u),ik(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=sk)}},[u,h,n,c]),C.useEffect(()=>()=>{u&&(c.layers.delete(u),c.layersWithOutsidePointerEventsDisabled.delete(u),ik())},[u,c]),C.useEffect(()=>{const P=()=>f({});return document.addEventListener(sE,P),()=>document.removeEventListener(sE,P)},[]),p.jsx(pr.div,{...l,ref:m,style:{pointerEvents:S?E?"auto":"none":void 0,...t.style},onFocusCapture:Un(t.onFocusCapture,U.onFocusCapture),onBlurCapture:Un(t.onBlurCapture,U.onBlurCapture),onPointerDownCapture:Un(t.onPointerDownCapture,L.onPointerDownCapture)})});wv.displayName=SH;var TH="DismissableLayerBranch",cj=C.forwardRef((t,e)=>{const n=C.useContext(lj),r=C.useRef(null),s=ps(e,r);return C.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),p.jsx(pr.div,{...t,ref:s})});cj.displayName=TH;function AH(t,e=globalThis==null?void 0:globalThis.document){const n=Ca(t),r=C.useRef(!1),s=C.useRef(()=>{});return C.useEffect(()=>{const i=o=>{if(o.target&&!r.current){let l=function(){uj(EH,n,c,{discrete:!0})};const c={originalEvent:o};o.pointerType==="touch"?(e.removeEventListener("click",s.current),s.current=l,e.addEventListener("click",s.current,{once:!0})):l()}else e.removeEventListener("click",s.current);r.current=!1},a=window.setTimeout(()=>{e.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(a),e.removeEventListener("pointerdown",i),e.removeEventListener("click",s.current)}},[e,n]),{onPointerDownCapture:()=>r.current=!0}}function RH(t,e=globalThis==null?void 0:globalThis.document){const n=Ca(t),r=C.useRef(!1);return C.useEffect(()=>{const s=i=>{i.target&&!r.current&&uj(wH,n,{originalEvent:i},{discrete:!1})};return e.addEventListener("focusin",s),()=>e.removeEventListener("focusin",s)},[e,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function ik(){const t=new CustomEvent(sE);document.dispatchEvent(t)}function uj(t,e,n,{discrete:r}){const s=n.originalEvent.target,i=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:n});e&&s.addEventListener(t,e,{once:!0}),r?oj(s,i):s.dispatchEvent(i)}var CH=wv,kH=cj,To=globalThis!=null&&globalThis.document?C.useLayoutEffect:()=>{},LH="Portal",n1=C.forwardRef((t,e)=>{var o;const{container:n,...r}=t,[s,i]=C.useState(!1);To(()=>i(!0),[]);const a=n||s&&((o=globalThis==null?void 0:globalThis.document)==null?void 0:o.body);return a?tN.createPortal(p.jsx(pr.div,{...r,ref:e}),a):null});n1.displayName=LH;function IH(t,e){return C.useReducer((n,r)=>e[n][r]??n,t)}var Ih=t=>{const{present:e,children:n}=t,r=PH(e),s=typeof n=="function"?n({present:r.isPresent}):C.Children.only(n),i=ps(r.ref,DH(s));return typeof n=="function"||r.isPresent?C.cloneElement(s,{ref:i}):null};Ih.displayName="Presence";function PH(t){const[e,n]=C.useState(),r=C.useRef(null),s=C.useRef(t),i=C.useRef("none"),a=t?"mounted":"unmounted",[o,l]=IH(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return C.useEffect(()=>{const c=hg(r.current);i.current=o==="mounted"?c:"none"},[o]),To(()=>{const c=r.current,u=s.current;if(u!==t){const h=i.current,f=hg(c);t?l("MOUNT"):f==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(u&&h!==f?"ANIMATION_OUT":"UNMOUNT"),s.current=t}},[t,l]),To(()=>{if(e){let c;const u=e.ownerDocument.defaultView??window,d=f=>{const g=hg(r.current).includes(CSS.escape(f.animationName));if(f.target===e&&g&&(l("ANIMATION_END"),!s.current)){const y=e.style.animationFillMode;e.style.animationFillMode="forwards",c=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=y)})}},h=f=>{f.target===e&&(i.current=hg(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:C.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function hg(t){return(t==null?void 0:t.animationName)||"none"}function DH(t){var r,s;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=(s=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:s.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var OH=Qw[" useInsertionEffect ".trim().toString()]||To;function dj({prop:t,defaultProp:e,onChange:n=()=>{},caller:r}){const[s,i,a]=NH({defaultProp:e,onChange:n}),o=t!==void 0,l=o?t:s;{const u=C.useRef(t!==void 0);C.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=C.useCallback(u=>{var d;if(o){const h=MH(u)?u(t):u;h!==t&&((d=a.current)==null||d.call(a,h))}else i(u)},[o,t,i,a]);return[l,c]}function NH({defaultProp:t,onChange:e}){const[n,r]=C.useState(t),s=C.useRef(n),i=C.useRef(e);return OH(()=>{i.current=e},[e]),C.useEffect(()=>{var a;s.current!==n&&((a=i.current)==null||a.call(i,n),s.current=n)},[n,s]),[n,r,i]}function MH(t){return typeof t=="function"}var jH=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"}),UH="VisuallyHidden",Tv=C.forwardRef((t,e)=>p.jsx(pr.span,{...t,ref:e,style:{...jH,...t.style}}));Tv.displayName=UH;var BH=Tv,r1="ToastProvider",[s1,FH,$H]=fH("Toast"),[hj]=ym("Toast",[$H]),[VH,Av]=hj(r1),fj=t=>{const{__scopeToast:e,label:n="Notification",duration:r=5e3,swipeDirection:s="right",swipeThreshold:i=50,children:a}=t,[o,l]=C.useState(null),[c,u]=C.useState(0),d=C.useRef(!1),h=C.useRef(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${r1}\`. Expected non-empty \`string\`.`),p.jsx(s1.Provider,{scope:e,children:p.jsx(VH,{scope:e,label:n,duration:r,swipeDirection:s,swipeThreshold:i,toastCount:c,viewport:o,onViewportChange:l,onToastAdd:C.useCallback(()=>u(f=>f+1),[]),onToastRemove:C.useCallback(()=>u(f=>f-1),[]),isFocusedToastEscapeKeyDownRef:d,isClosePausedRef:h,children:a})})};fj.displayName=r1;var pj="ToastViewport",GH=["F8"],iE="toast.viewportPause",aE="toast.viewportResume",mj=C.forwardRef((t,e)=>{const{__scopeToast:n,hotkey:r=GH,label:s="Notifications ({hotkey})",...i}=t,a=Av(pj,n),o=FH(n),l=C.useRef(null),c=C.useRef(null),u=C.useRef(null),d=C.useRef(null),h=ps(e,d,a.onViewportChange),f=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),m=a.toastCount>0;C.useEffect(()=>{const y=v=>{var S;r.length!==0&&r.every(E=>v[E]||v.code===E)&&((S=d.current)==null||S.focus())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[r]),C.useEffect(()=>{const y=l.current,v=d.current;if(m&&y&&v){const _=()=>{if(!a.isClosePausedRef.current){const U=new CustomEvent(iE);v.dispatchEvent(U),a.isClosePausedRef.current=!0}},S=()=>{if(a.isClosePausedRef.current){const U=new CustomEvent(aE);v.dispatchEvent(U),a.isClosePausedRef.current=!1}},E=U=>{!y.contains(U.relatedTarget)&&S()},L=()=>{y.contains(document.activeElement)||S()};return y.addEventListener("focusin",_),y.addEventListener("focusout",E),y.addEventListener("pointermove",_),y.addEventListener("pointerleave",L),window.addEventListener("blur",_),window.addEventListener("focus",S),()=>{y.removeEventListener("focusin",_),y.removeEventListener("focusout",E),y.removeEventListener("pointermove",_),y.removeEventListener("pointerleave",L),window.removeEventListener("blur",_),window.removeEventListener("focus",S)}}},[m,a.isClosePausedRef]);const g=C.useCallback(({tabbingDirection:y})=>{const _=o().map(S=>{const E=S.ref.current,L=[E,...nz(E)];return y==="forwards"?L:L.reverse()});return(y==="forwards"?_.reverse():_).flat()},[o]);return C.useEffect(()=>{const y=d.current;if(y){const v=_=>{var L,U,P;const S=_.altKey||_.ctrlKey||_.metaKey;if(_.key==="Tab"&&!S){const I=document.activeElement,k=_.shiftKey;if(_.target===y&&k){(L=c.current)==null||L.focus();return}const G=g({tabbingDirection:k?"backwards":"forwards"}),Y=G.findIndex(q=>q===I);fb(G.slice(Y+1))?_.preventDefault():k?(U=c.current)==null||U.focus():(P=u.current)==null||P.focus()}};return y.addEventListener("keydown",v),()=>y.removeEventListener("keydown",v)}},[o,g]),p.jsxs(kH,{ref:l,role:"region","aria-label":s.replace("{hotkey}",f),tabIndex:-1,style:{pointerEvents:m?void 0:"none"},children:[m&&p.jsx(oE,{ref:c,onFocusFromOutsideViewport:()=>{const y=g({tabbingDirection:"forwards"});fb(y)}}),p.jsx(s1.Slot,{scope:n,children:p.jsx(pr.ol,{tabIndex:-1,...i,ref:h})}),m&&p.jsx(oE,{ref:u,onFocusFromOutsideViewport:()=>{const y=g({tabbingDirection:"backwards"});fb(y)}})]})});mj.displayName=pj;var gj="ToastFocusProxy",oE=C.forwardRef((t,e)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...s}=t,i=Av(gj,n);return p.jsx(Tv,{tabIndex:0,...s,ref:e,style:{position:"fixed"},onFocus:a=>{var c;const o=a.relatedTarget;!((c=i.viewport)!=null&&c.contains(o))&&r()}})});oE.displayName=gj;var vm="Toast",KH="toast.swipeStart",HH="toast.swipeMove",zH="toast.swipeCancel",qH="toast.swipeEnd",yj=C.forwardRef((t,e)=>{const{forceMount:n,open:r,defaultOpen:s,onOpenChange:i,...a}=t,[o,l]=dj({prop:r,defaultProp:s??!0,onChange:i,caller:vm});return p.jsx(Ih,{present:n||o,children:p.jsx(XH,{open:o,...a,ref:e,onClose:()=>l(!1),onPause:Ca(t.onPause),onResume:Ca(t.onResume),onSwipeStart:Un(t.onSwipeStart,c=>{c.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:Un(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:Un(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:Un(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)})})})});yj.displayName=vm;var[WH,YH]=hj(vm,{onClose(){}}),XH=C.forwardRef((t,e)=>{const{__scopeToast:n,type:r="foreground",duration:s,open:i,onClose:a,onEscapeKeyDown:o,onPause:l,onResume:c,onSwipeStart:u,onSwipeMove:d,onSwipeCancel:h,onSwipeEnd:f,...m}=t,g=Av(vm,n),[y,v]=C.useState(null),_=ps(e,q=>v(q)),S=C.useRef(null),E=C.useRef(null),L=s||g.duration,U=C.useRef(0),P=C.useRef(L),I=C.useRef(0),{onToastAdd:k,onToastRemove:R}=g,M=Ca(()=>{var X;(y==null?void 0:y.contains(document.activeElement))&&((X=g.viewport)==null||X.focus()),a()}),G=C.useCallback(q=>{!q||q===1/0||(window.clearTimeout(I.current),U.current=new Date().getTime(),I.current=window.setTimeout(M,q))},[M]);C.useEffect(()=>{const q=g.viewport;if(q){const X=()=>{G(P.current),c==null||c()},Z=()=>{const oe=new Date().getTime()-U.current;P.current=P.current-oe,window.clearTimeout(I.current),l==null||l()};return q.addEventListener(iE,Z),q.addEventListener(aE,X),()=>{q.removeEventListener(iE,Z),q.removeEventListener(aE,X)}}},[g.viewport,L,l,c,G]),C.useEffect(()=>{i&&!g.isClosePausedRef.current&&G(L)},[i,L,g.isClosePausedRef,G]),C.useEffect(()=>(k(),()=>R()),[k,R]);const Y=C.useMemo(()=>y?wj(y):null,[y]);return g.viewport?p.jsxs(p.Fragment,{children:[Y&&p.jsx(QH,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite",children:Y}),p.jsx(WH,{scope:n,onClose:M,children:Zp.createPortal(p.jsx(s1.ItemSlot,{scope:n,children:p.jsx(CH,{asChild:!0,onEscapeKeyDown:Un(o,()=>{g.isFocusedToastEscapeKeyDownRef.current||M(),g.isFocusedToastEscapeKeyDownRef.current=!1}),children:p.jsx(pr.li,{tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":g.swipeDirection,...m,ref:_,style:{userSelect:"none",touchAction:"none",...t.style},onKeyDown:Un(t.onKeyDown,q=>{q.key==="Escape"&&(o==null||o(q.nativeEvent),q.nativeEvent.defaultPrevented||(g.isFocusedToastEscapeKeyDownRef.current=!0,M()))}),onPointerDown:Un(t.onPointerDown,q=>{q.button===0&&(S.current={x:q.clientX,y:q.clientY})}),onPointerMove:Un(t.onPointerMove,q=>{if(!S.current)return;const X=q.clientX-S.current.x,Z=q.clientY-S.current.y,oe=!!E.current,ne=["left","right"].includes(g.swipeDirection),H=["left","up"].includes(g.swipeDirection)?Math.min:Math.max,K=ne?H(0,X):0,J=ne?0:H(0,Z),Q=q.pointerType==="touch"?10:2,ve={x:K,y:J},Te={originalEvent:q,delta:ve};oe?(E.current=ve,fg(HH,d,Te,{discrete:!1})):ak(ve,g.swipeDirection,Q)?(E.current=ve,fg(KH,u,Te,{discrete:!1}),q.target.setPointerCapture(q.pointerId)):(Math.abs(X)>Q||Math.abs(Z)>Q)&&(S.current=null)}),onPointerUp:Un(t.onPointerUp,q=>{const X=E.current,Z=q.target;if(Z.hasPointerCapture(q.pointerId)&&Z.releasePointerCapture(q.pointerId),E.current=null,S.current=null,X){const oe=q.currentTarget,ne={originalEvent:q,delta:X};ak(X,g.swipeDirection,g.swipeThreshold)?fg(qH,f,ne,{discrete:!0}):fg(zH,h,ne,{discrete:!0}),oe.addEventListener("click",H=>H.preventDefault(),{once:!0})}})})})}),g.viewport)})]}):null}),QH=t=>{const{__scopeToast:e,children:n,...r}=t,s=Av(vm,e),[i,a]=C.useState(!1),[o,l]=C.useState(!1);return ez(()=>a(!0)),C.useEffect(()=>{const c=window.setTimeout(()=>l(!0),1e3);return()=>window.clearTimeout(c)},[]),o?null:p.jsx(n1,{asChild:!0,children:p.jsx(Tv,{...r,children:i&&p.jsxs(p.Fragment,{children:[s.label," ",n]})})})},JH="ToastTitle",vj=C.forwardRef((t,e)=>{const{__scopeToast:n,...r}=t;return p.jsx(pr.div,{...r,ref:e})});vj.displayName=JH;var ZH="ToastDescription",_j=C.forwardRef((t,e)=>{const{__scopeToast:n,...r}=t;return p.jsx(pr.div,{...r,ref:e})});_j.displayName=ZH;var bj="ToastAction",xj=C.forwardRef((t,e)=>{const{altText:n,...r}=t;return n.trim()?p.jsx(Ej,{altText:n,asChild:!0,children:p.jsx(i1,{...r,ref:e})}):(console.error(`Invalid prop \`altText\` supplied to \`${bj}\`. Expected non-empty \`string\`.`),null)});xj.displayName=bj;var Sj="ToastClose",i1=C.forwardRef((t,e)=>{const{__scopeToast:n,...r}=t,s=YH(Sj,n);return p.jsx(Ej,{asChild:!0,children:p.jsx(pr.button,{type:"button",...r,ref:e,onClick:Un(t.onClick,s.onClose)})})});i1.displayName=Sj;var Ej=C.forwardRef((t,e)=>{const{__scopeToast:n,altText:r,...s}=t;return p.jsx(pr.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...s,ref:e})});function wj(t){const e=[];return Array.from(t.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&e.push(r.textContent),tz(r)){const s=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!s)if(i){const a=r.dataset.radixToastAnnounceAlt;a&&e.push(a)}else e.push(...wj(r))}}),e}function fg(t,e,n,{discrete:r}){const s=n.originalEvent.currentTarget,i=new CustomEvent(t,{bubbles:!0,cancelable:!0,detail:n});e&&s.addEventListener(t,e,{once:!0}),r?oj(s,i):s.dispatchEvent(i)}var ak=(t,e,n=0)=>{const r=Math.abs(t.x),s=Math.abs(t.y),i=r>s;return e==="left"||e==="right"?i&&r>n:!i&&s>n};function ez(t=()=>{}){const e=Ca(t);To(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(e)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[e])}function tz(t){return t.nodeType===t.ELEMENT_NODE}function nz(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const s=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||s?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)e.push(n.currentNode);return e}function fb(t){const e=document.activeElement;return t.some(n=>n===e?!0:(n.focus(),document.activeElement!==e))}var rz=fj,Tj=mj,Aj=yj,Rj=vj,Cj=_j,kj=xj,Lj=i1;function Ij(t){var e,n,r="";if(typeof t=="string"||typeof t=="number")r+=t;else if(typeof t=="object")if(Array.isArray(t)){var s=t.length;for(e=0;e<s;e++)t[e]&&(n=Ij(t[e]))&&(r&&(r+=" "),r+=n)}else for(n in t)t[n]&&(r&&(r+=" "),r+=n);return r}function Pj(){for(var t,e,n=0,r="",s=arguments.length;n<s;n++)(t=arguments[n])&&(e=Ij(t))&&(r&&(r+=" "),r+=e);return r}const ok=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,lk=Pj,sz=(t,e)=>n=>{var r;if((e==null?void 0:e.variants)==null)return lk(t,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:s,defaultVariants:i}=e,a=Object.keys(s).map(c=>{const u=n==null?void 0:n[c],d=i==null?void 0:i[c];if(u===null)return null;const h=ok(u)||ok(d);return s[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(m=>{let[g,y]=m;return Array.isArray(y)?y.includes({...i,...o}[g]):{...i,...o}[g]===y})?[...c,d,h]:c},[]);return lk(t,a,l,n==null?void 0:n.class,n==null?void 0:n.className)};/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Dj=(...t)=>t.filter((e,n,r)=>!!e&&e.trim()!==""&&r.indexOf(e)===n).join(" ").trim();/**
 * @license lucide-react v1.14.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=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const az=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,r)=>r?r.toUpperCase():n.toLowerCase());/**
 * @license lucide-react v1.14.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=t=>{const e=az(t);return e.charAt(0).toUpperCase()+e.slice(1)};/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */var pb={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.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const oz=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1},lz=C.createContext({}),cz=()=>C.useContext(lz),uz=C.forwardRef(({color:t,size:e,strokeWidth:n,absoluteStrokeWidth:r,className:s="",children:i,iconNode:a,...o},l)=>{const{size:c=24,strokeWidth:u=2,absoluteStrokeWidth:d=!1,color:h="currentColor",className:f=""}=cz()??{},m=r??d?Number(n??u)*24/Number(e??c):n??u;return C.createElement("svg",{ref:l,...pb,width:e??c??pb.width,height:e??c??pb.height,stroke:t??h,strokeWidth:m,className:Dj("lucide",f,s),...!i&&!oz(o)&&{"aria-hidden":"true"},...o},[...a.map(([g,y])=>C.createElement(g,y)),...Array.isArray(i)?i:[i]])});/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Ze=(t,e)=>{const n=C.forwardRef(({className:r,...s},i)=>C.createElement(uz,{ref:i,iconNode:e,className:Dj(`lucide-${iz(ck(t))}`,`lucide-${t}`,r),...s}));return n.displayName=ck(t),n};/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const dz=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],uk=Ze("activity",dz);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const hz=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],Ph=Ze("arrow-left",hz);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const fz=[["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"}]],pz=Ze("calendar",fz);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const mz=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],qi=Ze("check",mz);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const gz=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],_m=Ze("chevron-down",gz);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const yz=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],vz=Ze("chevron-left",yz);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const _z=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],bz=Ze("chevron-right",_z);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const xz=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],Rv=Ze("circle-alert",xz);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Sz=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],a1=Ze("circle-check",Sz);/**
 * @license lucide-react v1.14.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:"M9 9.003a1 1 0 0 1 1.517-.859l4.997 2.997a1 1 0 0 1 0 1.718l-4.997 2.997A1 1 0 0 1 9 14.996z",key:"kmsa83"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],wz=Ze("circle-play",Ez);/**
 * @license lucide-react v1.14.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=[["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"}]],Vc=Ze("circle-user",Tz);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Az=[["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"}]],Rz=Ze("circle-user-round",Az);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Cz=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],kz=Ze("circle",Cz);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Lz=[["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"}]],Dh=Ze("clapperboard",Lz);/**
 * @license lucide-react v1.14.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=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],Oj=Ze("clock",Iz);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Pz=[["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"}]],Dz=Ze("copy",Pz);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Oz=[["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"}]],lE=Ze("cpu",Oz);/**
 * @license lucide-react v1.14.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=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],Mz=Ze("credit-card",Nz);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const jz=[["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"}]],o1=Ze("download",jz);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Uz=[["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"}]],cE=Ze("earth",Uz);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Bz=[["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"}]],vo=Ze("external-link",Bz);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Fz=[["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"}]],l1=Ze("file-text",Fz);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const $z=[["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"}]],bm=Ze("film",$z);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Vz=[["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"}]],Gz=Ze("globe",Vz);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Kz=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}]],Hz=Ze("heart",Kz);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const zz=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],qz=Ze("history",zz);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Wz=[["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"}]],uE=Ze("house",Wz);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Yz=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],Xz=Ze("image",Yz);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Qz=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],Jz=Ze("info",Qz);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Zz=[["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"}]],Cv=Ze("key-round",Zz);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const e9=[["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"}]],t9=Ze("layout-grid",e9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const n9=[["path",{d:"m16 6 4 14",key:"ji33uf"}],["path",{d:"M12 6v14",key:"1n7gus"}],["path",{d:"M8 8v12",key:"1gg7y9"}],["path",{d:"M4 4v16",key:"6qkkli"}]],r9=Ze("library",n9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const s9=[["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"}]],wp=Ze("link-2",s9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const i9=[["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"}]],dE=Ze("link",i9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const a9=[["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"}]],o9=Ze("list",a9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const l9=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Pn=Ze("loader-circle",l9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const c9=[["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"}]],u9=Ze("loader",c9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const d9=[["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"}]],h9=Ze("lock",d9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const f9=[["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"}]],p9=Ze("log-in",f9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const m9=[["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"}]],Nj=Ze("log-out",m9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const g9=[["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"}]],y9=Ze("mail",g9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const v9=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],_9=Ze("maximize-2",v9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const b9=[["path",{d:"M11 6a13 13 0 0 0 8.4-2.8A1 1 0 0 1 21 4v12a1 1 0 0 1-1.6.8A13 13 0 0 0 11 14H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2z",key:"q8bfy3"}],["path",{d:"M6 14a12 12 0 0 0 2.4 7.2 2 2 0 0 0 3.2-2.4A8 8 0 0 1 10 14",key:"1853fq"}],["path",{d:"M8 6v8",key:"15ugcq"}]],g0=Ze("megaphone",b9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const x9=[["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"}]],Mj=Ze("message-circle",x9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const S9=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]],E9=Ze("pause",S9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const w9=[["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"}]],T9=Ze("pen",w9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const A9=[["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"}]],va=Ze("play",A9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const R9=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],_o=Ze("plus",R9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const C9=[["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"}]],k9=Ze("plug",C9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const L9=[["path",{d:"M16.247 7.761a6 6 0 0 1 0 8.478",key:"1fwjs5"}],["path",{d:"M19.075 4.933a10 10 0 0 1 0 14.134",key:"ehdyv1"}],["path",{d:"M4.925 19.067a10 10 0 0 1 0-14.134",key:"1q22gi"}],["path",{d:"M7.753 16.239a6 6 0 0 1 0-8.478",key:"r2q7qm"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],I9=Ze("radio",L9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const P9=[["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"}]],D9=Ze("refresh-ccw",P9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const O9=[["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"}]],Oh=Ze("refresh-cw",O9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const N9=[["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"}]],M9=Ze("save",N9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const j9=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],c1=Ze("search",j9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const U9=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],dk=Ze("send",U9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const B9=[["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"}]],Gc=Ze("server",B9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const F9=[["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"}]],jj=Ze("settings",F9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const $9=[["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"}]],Ul=Ze("shield-check",$9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const V9=[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5 5a1 1 0 0 0-1 1v7c0 5 3.5 7.5 7.67 8.94a1 1 0 0 0 .67.01c2.35-.82 4.48-1.97 5.9-3.71",key:"1jlk70"}],["path",{d:"M9.309 3.652A12.252 12.252 0 0 0 11.24 2.28a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1v7a9.784 9.784 0 0 1-.08 1.264",key:"18rp1v"}]],G9=Ze("shield-off",V9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const K9=[["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"}]],H9=Ze("shield",K9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const z9=[["path",{d:"M17.971 4.285A2 2 0 0 1 21 6v12a2 2 0 0 1-3.029 1.715l-9.997-5.998a2 2 0 0 1-.003-3.432z",key:"15892j"}],["path",{d:"M3 20V4",key:"1ptbpl"}]],q9=Ze("skip-back",z9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const W9=[["path",{d:"M21 4v16",key:"7j8fe9"}],["path",{d:"M6.029 4.285A2 2 0 0 0 3 6v12a2 2 0 0 0 3.029 1.715l9.997-5.998a2 2 0 0 0 .003-3.432z",key:"zs4d6"}]],Uj=Ze("skip-forward",W9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Y9=[["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M12 21v-9",key:"17s77i"}],["path",{d:"M12 8V3",key:"13r4qs"}],["path",{d:"M17 16h4",key:"h1uq16"}],["path",{d:"M19 12V3",key:"o1uvq1"}],["path",{d:"M19 21v-5",key:"qua636"}],["path",{d:"M3 14h4",key:"bcjad9"}],["path",{d:"M5 10V3",key:"cb8scm"}],["path",{d:"M5 21v-7",key:"1w1uti"}]],X9=Ze("sliders-vertical",Y9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Q9=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],hE=Ze("smartphone",Q9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const J9=[["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"}]],kv=Ze("sparkles",J9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const Z9=[["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"}]],Gf=Ze("star",Z9);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const eq=[["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"}]],xm=Ze("trash-2",eq);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const tq=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],nq=Ze("trending-up",tq);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const rq=[["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"}]],sq=Ze("triangle-alert",rq);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const iq=[["path",{d:"m17 2-5 5-5-5",key:"16satq"}],["rect",{width:"20",height:"15",x:"2",y:"7",rx:"2",key:"1e6viu"}]],ri=Ze("tv",iq);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const aq=[["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"}]],u1=Ze("upload",aq);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const oq=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"19",x2:"19",y1:"8",y2:"14",key:"1bvyxn"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]],lq=Ze("user-plus",oq);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const cq=[["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"}]],Ji=Ze("user",cq);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const uq=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],Bj=Ze("users",uq);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const dq=[["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"}]],hq=Ze("wifi",dq);/**
 * @license lucide-react v1.14.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const fq=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Na=Ze("x",fq),d1="-",pq=t=>{const e=gq(t),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:a=>{const o=a.split(d1);return o[0]===""&&o.length!==1&&o.shift(),Fj(o,e)||mq(a)},getConflictingClassGroupIds:(a,o)=>{const l=n[a]||[];return o&&r[a]?[...l,...r[a]]:l}}},Fj=(t,e)=>{var a;if(t.length===0)return e.classGroupId;const n=t[0],r=e.nextPart.get(n),s=r?Fj(t.slice(1),r):void 0;if(s)return s;if(e.validators.length===0)return;const i=t.join(d1);return(a=e.validators.find(({validator:o})=>o(i)))==null?void 0:a.classGroupId},hk=/^\[(.+)\]$/,mq=t=>{if(hk.test(t)){const e=hk.exec(t)[1],n=e==null?void 0:e.substring(0,e.indexOf(":"));if(n)return"arbitrary.."+n}},gq=t=>{const{theme:e,prefix:n}=t,r={nextPart:new Map,validators:[]};return vq(Object.entries(t.classGroups),n).forEach(([i,a])=>{fE(a,r,i,e)}),r},fE=(t,e,n,r)=>{t.forEach(s=>{if(typeof s=="string"){const i=s===""?e:fk(e,s);i.classGroupId=n;return}if(typeof s=="function"){if(yq(s)){fE(s(r),e,n,r);return}e.validators.push({validator:s,classGroupId:n});return}Object.entries(s).forEach(([i,a])=>{fE(a,fk(e,i),n,r)})})},fk=(t,e)=>{let n=t;return e.split(d1).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},yq=t=>t.isThemeGetter,vq=(t,e)=>e?t.map(([n,r])=>{const s=r.map(i=>typeof i=="string"?e+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([a,o])=>[e+a,o])):i);return[n,s]}):t,_q=t=>{if(t<1)return{get:()=>{},set:()=>{}};let e=0,n=new Map,r=new Map;const s=(i,a)=>{n.set(i,a),e++,e>t&&(e=0,r=n,n=new Map)};return{get(i){let a=n.get(i);if(a!==void 0)return a;if((a=r.get(i))!==void 0)return s(i,a),a},set(i,a){n.has(i)?n.set(i,a):s(i,a)}}},$j="!",bq=t=>{const{separator:e,experimentalParseClassName:n}=t,r=e.length===1,s=e[0],i=e.length,a=o=>{const l=[];let c=0,u=0,d;for(let y=0;y<o.length;y++){let v=o[y];if(c===0){if(v===s&&(r||o.slice(y,y+i)===e)){l.push(o.slice(u,y)),u=y+i;continue}if(v==="/"){d=y;continue}}v==="["?c++:v==="]"&&c--}const h=l.length===0?o:o.substring(u),f=h.startsWith($j),m=f?h.substring(1):h,g=d&&d>u?d-u:void 0;return{modifiers:l,hasImportantModifier:f,baseClassName:m,maybePostfixModifierPosition:g}};return n?o=>n({className:o,parseClassName:a}):a},xq=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},Sq=t=>({cache:_q(t.cacheSize),parseClassName:bq(t),...pq(t)}),Eq=/\s+/,wq=(t,e)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:s}=e,i=[],a=t.trim().split(Eq);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 m=!!f,g=r(m?h.substring(0,f):h);if(!g){if(!m){o=c+(o.length>0?" "+o:o);continue}if(g=r(h),!g){o=c+(o.length>0?" "+o:o);continue}m=!1}const y=xq(u).join(":"),v=d?y+$j:y,_=v+g;if(i.includes(_))continue;i.push(_);const S=s(g,m);for(let E=0;E<S.length;++E){const L=S[E];i.push(v+L)}o=c+(o.length>0?" "+o:o)}return o};function Tq(){let t=0,e,n,r="";for(;t<arguments.length;)(e=arguments[t++])&&(n=Vj(e))&&(r&&(r+=" "),r+=n);return r}const Vj=t=>{if(typeof t=="string")return t;let e,n="";for(let r=0;r<t.length;r++)t[r]&&(e=Vj(t[r]))&&(n&&(n+=" "),n+=e);return n};function Aq(t,...e){let n,r,s,i=a;function a(l){const c=e.reduce((u,d)=>d(u),t());return n=Sq(c),r=n.cache.get,s=n.cache.set,i=o,o(l)}function o(l){const c=r(l);if(c)return c;const u=wq(l,n);return s(l,u),u}return function(){return i(Tq.apply(null,arguments))}}const kn=t=>{const e=n=>n[t]||[];return e.isThemeGetter=!0,e},Gj=/^\[(?:([a-z-]+):)?(.+)\]$/i,Rq=/^\d+\/\d+$/,Cq=new Set(["px","full","screen"]),kq=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Lq=/\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$/,Iq=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Pq=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Dq=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ka=t=>Ld(t)||Cq.has(t)||Rq.test(t),Fo=t=>Nh(t,"length",$q),Ld=t=>!!t&&!Number.isNaN(Number(t)),mb=t=>Nh(t,"number",Ld),of=t=>!!t&&Number.isInteger(Number(t)),Oq=t=>t.endsWith("%")&&Ld(t.slice(0,-1)),jt=t=>Gj.test(t),$o=t=>kq.test(t),Nq=new Set(["length","size","percentage"]),Mq=t=>Nh(t,Nq,Kj),jq=t=>Nh(t,"position",Kj),Uq=new Set(["image","url"]),Bq=t=>Nh(t,Uq,Gq),Fq=t=>Nh(t,"",Vq),lf=()=>!0,Nh=(t,e,n)=>{const r=Gj.exec(t);return r?r[1]?typeof e=="string"?r[1]===e:e.has(r[1]):n(r[2]):!1},$q=t=>Lq.test(t)&&!Iq.test(t),Kj=()=>!1,Vq=t=>Pq.test(t),Gq=t=>Dq.test(t),Kq=()=>{const t=kn("colors"),e=kn("spacing"),n=kn("blur"),r=kn("brightness"),s=kn("borderColor"),i=kn("borderRadius"),a=kn("borderSpacing"),o=kn("borderWidth"),l=kn("contrast"),c=kn("grayscale"),u=kn("hueRotate"),d=kn("invert"),h=kn("gap"),f=kn("gradientColorStops"),m=kn("gradientColorStopPositions"),g=kn("inset"),y=kn("margin"),v=kn("opacity"),_=kn("padding"),S=kn("saturate"),E=kn("scale"),L=kn("sepia"),U=kn("skew"),P=kn("space"),I=kn("translate"),k=()=>["auto","contain","none"],R=()=>["auto","hidden","clip","visible","scroll"],M=()=>["auto",jt,e],G=()=>[jt,e],Y=()=>["",Ka,Fo],q=()=>["auto",Ld,jt],X=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],Z=()=>["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"],ne=()=>["start","end","center","between","around","evenly","stretch"],H=()=>["","0",jt],K=()=>["auto","avoid","all","avoid-page","page","left","right","column"],J=()=>[Ld,jt];return{cacheSize:500,separator:":",theme:{colors:[lf],spacing:[Ka,Fo],blur:["none","",$o,jt],brightness:J(),borderColor:[t],borderRadius:["none","","full",$o,jt],borderSpacing:G(),borderWidth:Y(),contrast:J(),grayscale:H(),hueRotate:J(),invert:H(),gap:G(),gradientColorStops:[t],gradientColorStopPositions:[Oq,Fo],inset:M(),margin:M(),opacity:J(),padding:G(),saturate:J(),scale:J(),sepia:H(),skew:J(),space:G(),translate:G()},classGroups:{aspect:[{aspect:["auto","square","video",jt]}],container:["container"],columns:[{columns:[$o]}],"break-after":[{"break-after":K()}],"break-before":[{"break-before":K()}],"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:[...X(),jt]}],overflow:[{overflow:R()}],"overflow-x":[{"overflow-x":R()}],"overflow-y":[{"overflow-y":R()}],overscroll:[{overscroll:k()}],"overscroll-x":[{"overscroll-x":k()}],"overscroll-y":[{"overscroll-y":k()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[g]}],"inset-x":[{"inset-x":[g]}],"inset-y":[{"inset-y":[g]}],start:[{start:[g]}],end:[{end:[g]}],top:[{top:[g]}],right:[{right:[g]}],bottom:[{bottom:[g]}],left:[{left:[g]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",of,jt]}],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",jt]}],grow:[{grow:H()}],shrink:[{shrink:H()}],order:[{order:["first","last","none",of,jt]}],"grid-cols":[{"grid-cols":[lf]}],"col-start-end":[{col:["auto",{span:["full",of,jt]},jt]}],"col-start":[{"col-start":q()}],"col-end":[{"col-end":q()}],"grid-rows":[{"grid-rows":[lf]}],"row-start-end":[{row:["auto",{span:[of,jt]},jt]}],"row-start":[{"row-start":q()}],"row-end":[{"row-end":q()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",jt]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",jt]}],gap:[{gap:[h]}],"gap-x":[{"gap-x":[h]}],"gap-y":[{"gap-y":[h]}],"justify-content":[{justify:["normal",...ne()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...ne(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...ne(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[_]}],px:[{px:[_]}],py:[{py:[_]}],ps:[{ps:[_]}],pe:[{pe:[_]}],pt:[{pt:[_]}],pr:[{pr:[_]}],pb:[{pb:[_]}],pl:[{pl:[_]}],m:[{m:[y]}],mx:[{mx:[y]}],my:[{my:[y]}],ms:[{ms:[y]}],me:[{me:[y]}],mt:[{mt:[y]}],mr:[{mr:[y]}],mb:[{mb:[y]}],ml:[{ml:[y]}],"space-x":[{"space-x":[P]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[P]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",jt,e]}],"min-w":[{"min-w":[jt,e,"min","max","fit"]}],"max-w":[{"max-w":[jt,e,"none","full","min","max","fit","prose",{screen:[$o]},$o]}],h:[{h:[jt,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[jt,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[jt,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[jt,e,"auto","min","max","fit"]}],"font-size":[{text:["base",$o,Fo]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",mb]}],"font-family":[{font:[lf]}],"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",jt]}],"line-clamp":[{"line-clamp":["none",Ld,mb]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Ka,jt]}],"list-image":[{"list-image":["none",jt]}],"list-style-type":[{list:["none","disc","decimal",jt]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[v]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[v]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Z(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Ka,Fo]}],"underline-offset":[{"underline-offset":["auto",Ka,jt]}],"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:G()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",jt]}],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",jt]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[v]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...X(),jq]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",Mq]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},Bq]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[m]}],"gradient-via-pos":[{via:[m]}],"gradient-to-pos":[{to:[m]}],"gradient-from":[{from:[f]}],"gradient-via":[{via:[f]}],"gradient-to":[{to:[f]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"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":[v]}],"border-style":[{border:[...Z(),"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":[v]}],"divide-style":[{divide:Z()}],"border-color":[{border:[s]}],"border-color-x":[{"border-x":[s]}],"border-color-y":[{"border-y":[s]}],"border-color-s":[{"border-s":[s]}],"border-color-e":[{"border-e":[s]}],"border-color-t":[{"border-t":[s]}],"border-color-r":[{"border-r":[s]}],"border-color-b":[{"border-b":[s]}],"border-color-l":[{"border-l":[s]}],"divide-color":[{divide:[s]}],"outline-style":[{outline:["",...Z()]}],"outline-offset":[{"outline-offset":[Ka,jt]}],"outline-w":[{outline:[Ka,Fo]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:Y()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[v]}],"ring-offset-w":[{"ring-offset":[Ka,Fo]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",$o,Fq]}],"shadow-color":[{shadow:[lf]}],opacity:[{opacity:[v]}],"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",$o,jt]}],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":[v]}],"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",jt]}],duration:[{duration:J()}],ease:[{ease:["linear","in","out","in-out",jt]}],delay:[{delay:J()}],animate:[{animate:["none","spin","ping","pulse","bounce",jt]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[E]}],"scale-x":[{"scale-x":[E]}],"scale-y":[{"scale-y":[E]}],rotate:[{rotate:[of,jt]}],"translate-x":[{"translate-x":[I]}],"translate-y":[{"translate-y":[I]}],"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",jt]}],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",jt]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":G()}],"scroll-mx":[{"scroll-mx":G()}],"scroll-my":[{"scroll-my":G()}],"scroll-ms":[{"scroll-ms":G()}],"scroll-me":[{"scroll-me":G()}],"scroll-mt":[{"scroll-mt":G()}],"scroll-mr":[{"scroll-mr":G()}],"scroll-mb":[{"scroll-mb":G()}],"scroll-ml":[{"scroll-ml":G()}],"scroll-p":[{"scroll-p":G()}],"scroll-px":[{"scroll-px":G()}],"scroll-py":[{"scroll-py":G()}],"scroll-ps":[{"scroll-ps":G()}],"scroll-pe":[{"scroll-pe":G()}],"scroll-pt":[{"scroll-pt":G()}],"scroll-pr":[{"scroll-pr":G()}],"scroll-pb":[{"scroll-pb":G()}],"scroll-pl":[{"scroll-pl":G()}],"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",jt]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[Ka,Fo,mb]}],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"]}}},Hq=Aq(Kq);function gs(...t){return Hq(Pj(t))}const zq=rz,Hj=C.forwardRef(({className:t,...e},n)=>p.jsx(Tj,{ref:n,className:gs("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}));Hj.displayName=Tj.displayName;const qq=sz("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"}}),zj=C.forwardRef(({className:t,variant:e,...n},r)=>p.jsx(Aj,{ref:r,className:gs(qq({variant:e}),t),...n}));zj.displayName=Aj.displayName;const Wq=C.forwardRef(({className:t,...e},n)=>p.jsx(kj,{ref:n,className:gs("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}));Wq.displayName=kj.displayName;const qj=C.forwardRef(({className:t,...e},n)=>p.jsx(Lj,{ref:n,className:gs("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:p.jsx(Na,{className:"h-4 w-4"})}));qj.displayName=Lj.displayName;const Wj=C.forwardRef(({className:t,...e},n)=>p.jsx(Rj,{ref:n,className:gs("text-sm font-semibold",t),...e}));Wj.displayName=Rj.displayName;const Yj=C.forwardRef(({className:t,...e},n)=>p.jsx(Cj,{ref:n,className:gs("text-sm opacity-90",t),...e}));Yj.displayName=Cj.displayName;function Yq(){const{toasts:t}=iH();return p.jsxs(zq,{children:[t.map(function({id:e,title:n,description:r,action:s,...i}){return p.jsxs(zj,{...i,children:[p.jsxs("div",{className:"grid gap-1",children:[n&&p.jsx(Wj,{children:n}),r&&p.jsx(Yj,{children:r})]}),s,p.jsx(qj,{})]},e)}),p.jsx(Hj,{})]})}var Xq=Qw[" useId ".trim().toString()]||(()=>{}),Qq=0;function gb(t){const[e,n]=C.useState(Xq());return To(()=>{n(r=>r??String(Qq++))},[t]),t||(e?`radix-${e}`:"")}const Jq=["top","right","bottom","left"],Bl=Math.min,Ks=Math.max,y0=Math.round,pg=Math.floor,Aa=t=>({x:t,y:t}),Zq={left:"right",right:"left",bottom:"top",top:"bottom"};function pE(t,e,n){return Ks(t,Bl(e,n))}function Ao(t,e){return typeof t=="function"?t(e):t}function Ro(t){return t.split("-")[0]}function Mh(t){return t.split("-")[1]}function h1(t){return t==="x"?"y":"x"}function f1(t){return t==="y"?"height":"width"}function _a(t){const e=t[0];return e==="t"||e==="b"?"y":"x"}function p1(t){return h1(_a(t))}function e7(t,e,n){n===void 0&&(n=!1);const r=Mh(t),s=p1(t),i=f1(s);let a=s==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return e.reference[i]>e.floating[i]&&(a=v0(a)),[a,v0(a)]}function t7(t){const e=v0(t);return[mE(t),e,mE(e)]}function mE(t){return t.includes("start")?t.replace("start","end"):t.replace("end","start")}const pk=["left","right"],mk=["right","left"],n7=["top","bottom"],r7=["bottom","top"];function s7(t,e,n){switch(t){case"top":case"bottom":return n?e?mk:pk:e?pk:mk;case"left":case"right":return e?n7:r7;default:return[]}}function i7(t,e,n,r){const s=Mh(t);let i=s7(Ro(t),n==="start",r);return s&&(i=i.map(a=>a+"-"+s),e&&(i=i.concat(i.map(mE)))),i}function v0(t){const e=Ro(t);return Zq[e]+t.slice(e.length)}function a7(t){return{top:0,right:0,bottom:0,left:0,...t}}function Xj(t){return typeof t!="number"?a7(t):{top:t,right:t,bottom:t,left:t}}function _0(t){const{x:e,y:n,width:r,height:s}=t;return{width:r,height:s,top:n,left:e,right:e+r,bottom:n+s,x:e,y:n}}function gk(t,e,n){let{reference:r,floating:s}=t;const i=_a(e),a=p1(e),o=f1(a),l=Ro(e),c=i==="y",u=r.x+r.width/2-s.width/2,d=r.y+r.height/2-s.height/2,h=r[o]/2-s[o]/2;let f;switch(l){case"top":f={x:u,y:r.y-s.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-s.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 o7(t,e){var n;e===void 0&&(e={});const{x:r,y:s,platform:i,rects:a,elements:o,strategy:l}=t,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:d="floating",altBoundary:h=!1,padding:f=0}=Ao(e,t),m=Xj(f),y=o[h?d==="floating"?"reference":"floating":d],v=_0(await i.getClippingRect({element:(n=await(i.isElement==null?void 0:i.isElement(y)))==null||n?y:y.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(o.floating)),boundary:c,rootBoundary:u,strategy:l})),_=d==="floating"?{x:r,y:s,width:a.floating.width,height:a.floating.height}:a.reference,S=await(i.getOffsetParent==null?void 0:i.getOffsetParent(o.floating)),E=await(i.isElement==null?void 0:i.isElement(S))?await(i.getScale==null?void 0:i.getScale(S))||{x:1,y:1}:{x:1,y:1},L=_0(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:_,offsetParent:S,strategy:l}):_);return{top:(v.top-L.top+m.top)/E.y,bottom:(L.bottom-v.bottom+m.bottom)/E.y,left:(v.left-L.left+m.left)/E.x,right:(L.right-v.right+m.right)/E.x}}const l7=50,c7=async(t,e,n)=>{const{placement:r="bottom",strategy:s="absolute",middleware:i=[],platform:a}=n,o=a.detectOverflow?a:{...a,detectOverflow:o7},l=await(a.isRTL==null?void 0:a.isRTL(e));let c=await a.getElementRects({reference:t,floating:e,strategy:s}),{x:u,y:d}=gk(c,r,l),h=r,f=0;const m={};for(let g=0;g<i.length;g++){const y=i[g];if(!y)continue;const{name:v,fn:_}=y,{x:S,y:E,data:L,reset:U}=await _({x:u,y:d,initialPlacement:r,placement:h,strategy:s,middlewareData:m,rects:c,platform:o,elements:{reference:t,floating:e}});u=S??u,d=E??d,m[v]={...m[v],...L},U&&f<l7&&(f++,typeof U=="object"&&(U.placement&&(h=U.placement),U.rects&&(c=U.rects===!0?await a.getElementRects({reference:t,floating:e,strategy:s}):U.rects),{x:u,y:d}=gk(c,h,l)),g=-1)}return{x:u,y:d,placement:h,strategy:s,middlewareData:m}},u7=t=>({name:"arrow",options:t,async fn(e){const{x:n,y:r,placement:s,rects:i,platform:a,elements:o,middlewareData:l}=e,{element:c,padding:u=0}=Ao(t,e)||{};if(c==null)return{};const d=Xj(u),h={x:n,y:r},f=p1(s),m=f1(f),g=await a.getDimensions(c),y=f==="y",v=y?"top":"left",_=y?"bottom":"right",S=y?"clientHeight":"clientWidth",E=i.reference[m]+i.reference[f]-h[f]-i.floating[m],L=h[f]-i.reference[f],U=await(a.getOffsetParent==null?void 0:a.getOffsetParent(c));let P=U?U[S]:0;(!P||!await(a.isElement==null?void 0:a.isElement(U)))&&(P=o.floating[S]||i.floating[m]);const I=E/2-L/2,k=P/2-g[m]/2-1,R=Bl(d[v],k),M=Bl(d[_],k),G=R,Y=P-g[m]-M,q=P/2-g[m]/2+I,X=pE(G,q,Y),Z=!l.arrow&&Mh(s)!=null&&q!==X&&i.reference[m]/2-(q<G?R:M)-g[m]/2<0,oe=Z?q<G?q-G:q-Y:0;return{[f]:h[f]+oe,data:{[f]:X,centerOffset:q-X-oe,...Z&&{alignmentOffset:oe}},reset:Z}}}),d7=function(t){return t===void 0&&(t={}),{name:"flip",options:t,async fn(e){var n,r;const{placement:s,middlewareData:i,rects:a,initialPlacement:o,platform:l,elements:c}=e,{mainAxis:u=!0,crossAxis:d=!0,fallbackPlacements:h,fallbackStrategy:f="bestFit",fallbackAxisSideDirection:m="none",flipAlignment:g=!0,...y}=Ao(t,e);if((n=i.arrow)!=null&&n.alignmentOffset)return{};const v=Ro(s),_=_a(o),S=Ro(o)===o,E=await(l.isRTL==null?void 0:l.isRTL(c.floating)),L=h||(S||!g?[v0(o)]:t7(o)),U=m!=="none";!h&&U&&L.push(...i7(o,g,m,E));const P=[o,...L],I=await l.detectOverflow(e,y),k=[];let R=((r=i.flip)==null?void 0:r.overflows)||[];if(u&&k.push(I[v]),d){const q=e7(s,a,E);k.push(I[q[0]],I[q[1]])}if(R=[...R,{placement:s,overflows:k}],!k.every(q=>q<=0)){var M,G;const q=(((M=i.flip)==null?void 0:M.index)||0)+1,X=P[q];if(X&&(!(d==="alignment"?_!==_a(X):!1)||R.every(ne=>_a(ne.placement)===_?ne.overflows[0]>0:!0)))return{data:{index:q,overflows:R},reset:{placement:X}};let Z=(G=R.filter(oe=>oe.overflows[0]<=0).sort((oe,ne)=>oe.overflows[1]-ne.overflows[1])[0])==null?void 0:G.placement;if(!Z)switch(f){case"bestFit":{var Y;const oe=(Y=R.filter(ne=>{if(U){const H=_a(ne.placement);return H===_||H==="y"}return!0}).map(ne=>[ne.placement,ne.overflows.filter(H=>H>0).reduce((H,K)=>H+K,0)]).sort((ne,H)=>ne[1]-H[1])[0])==null?void 0:Y[0];oe&&(Z=oe);break}case"initialPlacement":Z=o;break}if(s!==Z)return{reset:{placement:Z}}}return{}}}};function yk(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function vk(t){return Jq.some(e=>t[e]>=0)}const h7=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(e){const{rects:n,platform:r}=e,{strategy:s="referenceHidden",...i}=Ao(t,e);switch(s){case"referenceHidden":{const a=await r.detectOverflow(e,{...i,elementContext:"reference"}),o=yk(a,n.reference);return{data:{referenceHiddenOffsets:o,referenceHidden:vk(o)}}}case"escaped":{const a=await r.detectOverflow(e,{...i,altBoundary:!0}),o=yk(a,n.floating);return{data:{escapedOffsets:o,escaped:vk(o)}}}default:return{}}}}},Qj=new Set(["left","top"]);async function f7(t,e){const{placement:n,platform:r,elements:s}=t,i=await(r.isRTL==null?void 0:r.isRTL(s.floating)),a=Ro(n),o=Mh(n),l=_a(n)==="y",c=Qj.has(a)?-1:1,u=i&&l?-1:1,d=Ao(e,t);let{mainAxis:h,crossAxis:f,alignmentAxis:m}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return o&&typeof m=="number"&&(f=o==="end"?m*-1:m),l?{x:f*u,y:h*c}:{x:h*c,y:f*u}}const p7=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(e){var n,r;const{x:s,y:i,placement:a,middlewareData:o}=e,l=await f7(e,t);return a===((n=o.offset)==null?void 0:n.placement)&&(r=o.arrow)!=null&&r.alignmentOffset?{}:{x:s+l.x,y:i+l.y,data:{...l,placement:a}}}}},m7=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(e){const{x:n,y:r,placement:s,platform:i}=e,{mainAxis:a=!0,crossAxis:o=!1,limiter:l={fn:v=>{let{x:_,y:S}=v;return{x:_,y:S}}},...c}=Ao(t,e),u={x:n,y:r},d=await i.detectOverflow(e,c),h=_a(Ro(s)),f=h1(h);let m=u[f],g=u[h];if(a){const v=f==="y"?"top":"left",_=f==="y"?"bottom":"right",S=m+d[v],E=m-d[_];m=pE(S,m,E)}if(o){const v=h==="y"?"top":"left",_=h==="y"?"bottom":"right",S=g+d[v],E=g-d[_];g=pE(S,g,E)}const y=l.fn({...e,[f]:m,[h]:g});return{...y,data:{x:y.x-n,y:y.y-r,enabled:{[f]:a,[h]:o}}}}}},g7=function(t){return t===void 0&&(t={}),{options:t,fn(e){const{x:n,y:r,placement:s,rects:i,middlewareData:a}=e,{offset:o=0,mainAxis:l=!0,crossAxis:c=!0}=Ao(t,e),u={x:n,y:r},d=_a(s),h=h1(d);let f=u[h],m=u[d];const g=Ao(o,e),y=typeof g=="number"?{mainAxis:g,crossAxis:0}:{mainAxis:0,crossAxis:0,...g};if(l){const S=h==="y"?"height":"width",E=i.reference[h]-i.floating[S]+y.mainAxis,L=i.reference[h]+i.reference[S]-y.mainAxis;f<E?f=E:f>L&&(f=L)}if(c){var v,_;const S=h==="y"?"width":"height",E=Qj.has(Ro(s)),L=i.reference[d]-i.floating[S]+(E&&((v=a.offset)==null?void 0:v[d])||0)+(E?0:y.crossAxis),U=i.reference[d]+i.reference[S]+(E?0:((_=a.offset)==null?void 0:_[d])||0)-(E?y.crossAxis:0);m<L?m=L:m>U&&(m=U)}return{[h]:f,[d]:m}}}},y7=function(t){return t===void 0&&(t={}),{name:"size",options:t,async fn(e){var n,r;const{placement:s,rects:i,platform:a,elements:o}=e,{apply:l=()=>{},...c}=Ao(t,e),u=await a.detectOverflow(e,c),d=Ro(s),h=Mh(s),f=_a(s)==="y",{width:m,height:g}=i.floating;let y,v;d==="top"||d==="bottom"?(y=d,v=h===(await(a.isRTL==null?void 0:a.isRTL(o.floating))?"start":"end")?"left":"right"):(v=d,y=h==="end"?"top":"bottom");const _=g-u.top-u.bottom,S=m-u.left-u.right,E=Bl(g-u[y],_),L=Bl(m-u[v],S),U=!e.middlewareData.shift;let P=E,I=L;if((n=e.middlewareData.shift)!=null&&n.enabled.x&&(I=S),(r=e.middlewareData.shift)!=null&&r.enabled.y&&(P=_),U&&!h){const R=Ks(u.left,0),M=Ks(u.right,0),G=Ks(u.top,0),Y=Ks(u.bottom,0);f?I=m-2*(R!==0||M!==0?R+M:Ks(u.left,u.right)):P=g-2*(G!==0||Y!==0?G+Y:Ks(u.top,u.bottom))}await l({...e,availableWidth:I,availableHeight:P});const k=await a.getDimensions(o.floating);return m!==k.width||g!==k.height?{reset:{rects:!0}}:{}}}};function Lv(){return typeof window<"u"}function jh(t){return Jj(t)?(t.nodeName||"").toLowerCase():"#document"}function Zs(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function Ma(t){var e;return(e=(Jj(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function Jj(t){return Lv()?t instanceof Node||t instanceof Zs(t).Node:!1}function Wi(t){return Lv()?t instanceof Element||t instanceof Zs(t).Element:!1}function ko(t){return Lv()?t instanceof HTMLElement||t instanceof Zs(t).HTMLElement:!1}function _k(t){return!Lv()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof Zs(t).ShadowRoot}function Sm(t){const{overflow:e,overflowX:n,overflowY:r,display:s}=Yi(t);return/auto|scroll|overlay|hidden|clip/.test(e+r+n)&&s!=="inline"&&s!=="contents"}function v7(t){return/^(table|td|th)$/.test(jh(t))}function Iv(t){try{if(t.matches(":popover-open"))return!0}catch{}try{return t.matches(":modal")}catch{return!1}}const _7=/transform|translate|scale|rotate|perspective|filter/,b7=/paint|layout|strict|content/,sc=t=>!!t&&t!=="none";let yb;function m1(t){const e=Wi(t)?Yi(t):t;return sc(e.transform)||sc(e.translate)||sc(e.scale)||sc(e.rotate)||sc(e.perspective)||!g1()&&(sc(e.backdropFilter)||sc(e.filter))||_7.test(e.willChange||"")||b7.test(e.contain||"")}function x7(t){let e=Fl(t);for(;ko(e)&&!dh(e);){if(m1(e))return e;if(Iv(e))return null;e=Fl(e)}return null}function g1(){return yb==null&&(yb=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),yb}function dh(t){return/^(html|body|#document)$/.test(jh(t))}function Yi(t){return Zs(t).getComputedStyle(t)}function Pv(t){return Wi(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function Fl(t){if(jh(t)==="html")return t;const e=t.assignedSlot||t.parentNode||_k(t)&&t.host||Ma(t);return _k(e)?e.host:e}function Zj(t){const e=Fl(t);return dh(e)?t.ownerDocument?t.ownerDocument.body:t.body:ko(e)&&Sm(e)?e:Zj(e)}function Tp(t,e,n){var r;e===void 0&&(e=[]),n===void 0&&(n=!0);const s=Zj(t),i=s===((r=t.ownerDocument)==null?void 0:r.body),a=Zs(s);if(i){const o=gE(a);return e.concat(a,a.visualViewport||[],Sm(s)?s:[],o&&n?Tp(o):[])}else return e.concat(s,Tp(s,[],n))}function gE(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function eU(t){const e=Yi(t);let n=parseFloat(e.width)||0,r=parseFloat(e.height)||0;const s=ko(t),i=s?t.offsetWidth:n,a=s?t.offsetHeight:r,o=y0(n)!==i||y0(r)!==a;return o&&(n=i,r=a),{width:n,height:r,$:o}}function y1(t){return Wi(t)?t:t.contextElement}function Id(t){const e=y1(t);if(!ko(e))return Aa(1);const n=e.getBoundingClientRect(),{width:r,height:s,$:i}=eU(e);let a=(i?y0(n.width):n.width)/r,o=(i?y0(n.height):n.height)/s;return(!a||!Number.isFinite(a))&&(a=1),(!o||!Number.isFinite(o))&&(o=1),{x:a,y:o}}const S7=Aa(0);function tU(t){const e=Zs(t);return!g1()||!e.visualViewport?S7:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function E7(t,e,n){return e===void 0&&(e=!1),!n||e&&n!==Zs(t)?!1:e}function Zc(t,e,n,r){e===void 0&&(e=!1),n===void 0&&(n=!1);const s=t.getBoundingClientRect(),i=y1(t);let a=Aa(1);e&&(r?Wi(r)&&(a=Id(r)):a=Id(t));const o=E7(i,n,r)?tU(i):Aa(0);let l=(s.left+o.x)/a.x,c=(s.top+o.y)/a.y,u=s.width/a.x,d=s.height/a.y;if(i){const h=Zs(i),f=r&&Wi(r)?Zs(r):r;let m=h,g=gE(m);for(;g&&r&&f!==m;){const y=Id(g),v=g.getBoundingClientRect(),_=Yi(g),S=v.left+(g.clientLeft+parseFloat(_.paddingLeft))*y.x,E=v.top+(g.clientTop+parseFloat(_.paddingTop))*y.y;l*=y.x,c*=y.y,u*=y.x,d*=y.y,l+=S,c+=E,m=Zs(g),g=gE(m)}}return _0({width:u,height:d,x:l,y:c})}function Dv(t,e){const n=Pv(t).scrollLeft;return e?e.left+n:Zc(Ma(t)).left+n}function nU(t,e){const n=t.getBoundingClientRect(),r=n.left+e.scrollLeft-Dv(t,n),s=n.top+e.scrollTop;return{x:r,y:s}}function w7(t){let{elements:e,rect:n,offsetParent:r,strategy:s}=t;const i=s==="fixed",a=Ma(r),o=e?Iv(e.floating):!1;if(r===a||o&&i)return n;let l={scrollLeft:0,scrollTop:0},c=Aa(1);const u=Aa(0),d=ko(r);if((d||!d&&!i)&&((jh(r)!=="body"||Sm(a))&&(l=Pv(r)),d)){const f=Zc(r);c=Id(r),u.x=f.x+r.clientLeft,u.y=f.y+r.clientTop}const h=a&&!d&&!i?nU(a,l):Aa(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 T7(t){return Array.from(t.getClientRects())}function A7(t){const e=Ma(t),n=Pv(t),r=t.ownerDocument.body,s=Ks(e.scrollWidth,e.clientWidth,r.scrollWidth,r.clientWidth),i=Ks(e.scrollHeight,e.clientHeight,r.scrollHeight,r.clientHeight);let a=-n.scrollLeft+Dv(t);const o=-n.scrollTop;return Yi(r).direction==="rtl"&&(a+=Ks(e.clientWidth,r.clientWidth)-s),{width:s,height:i,x:a,y:o}}const bk=25;function R7(t,e){const n=Zs(t),r=Ma(t),s=n.visualViewport;let i=r.clientWidth,a=r.clientHeight,o=0,l=0;if(s){i=s.width,a=s.height;const u=g1();(!u||u&&e==="fixed")&&(o=s.offsetLeft,l=s.offsetTop)}const c=Dv(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,m=Math.abs(r.clientWidth-d.clientWidth-f);m<=bk&&(i-=m)}else c<=bk&&(i+=c);return{width:i,height:a,x:o,y:l}}function C7(t,e){const n=Zc(t,!0,e==="fixed"),r=n.top+t.clientTop,s=n.left+t.clientLeft,i=ko(t)?Id(t):Aa(1),a=t.clientWidth*i.x,o=t.clientHeight*i.y,l=s*i.x,c=r*i.y;return{width:a,height:o,x:l,y:c}}function xk(t,e,n){let r;if(e==="viewport")r=R7(t,n);else if(e==="document")r=A7(Ma(t));else if(Wi(e))r=C7(e,n);else{const s=tU(t);r={x:e.x-s.x,y:e.y-s.y,width:e.width,height:e.height}}return _0(r)}function rU(t,e){const n=Fl(t);return n===e||!Wi(n)||dh(n)?!1:Yi(n).position==="fixed"||rU(n,e)}function k7(t,e){const n=e.get(t);if(n)return n;let r=Tp(t,[],!1).filter(o=>Wi(o)&&jh(o)!=="body"),s=null;const i=Yi(t).position==="fixed";let a=i?Fl(t):t;for(;Wi(a)&&!dh(a);){const o=Yi(a),l=m1(a);!l&&o.position==="fixed"&&(s=null),(i?!l&&!s:!l&&o.position==="static"&&!!s&&(s.position==="absolute"||s.position==="fixed")||Sm(a)&&!l&&rU(t,a))?r=r.filter(u=>u!==a):s=o,a=Fl(a)}return e.set(t,r),r}function L7(t){let{element:e,boundary:n,rootBoundary:r,strategy:s}=t;const a=[...n==="clippingAncestors"?Iv(e)?[]:k7(e,this._c):[].concat(n),r],o=xk(e,a[0],s);let l=o.top,c=o.right,u=o.bottom,d=o.left;for(let h=1;h<a.length;h++){const f=xk(e,a[h],s);l=Ks(f.top,l),c=Bl(f.right,c),u=Bl(f.bottom,u),d=Ks(f.left,d)}return{width:c-d,height:u-l,x:d,y:l}}function I7(t){const{width:e,height:n}=eU(t);return{width:e,height:n}}function P7(t,e,n){const r=ko(e),s=Ma(e),i=n==="fixed",a=Zc(t,!0,i,e);let o={scrollLeft:0,scrollTop:0};const l=Aa(0);function c(){l.x=Dv(s)}if(r||!r&&!i)if((jh(e)!=="body"||Sm(s))&&(o=Pv(e)),r){const f=Zc(e,!0,i,e);l.x=f.x+e.clientLeft,l.y=f.y+e.clientTop}else s&&c();i&&!r&&s&&c();const u=s&&!r&&!i?nU(s,o):Aa(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 vb(t){return Yi(t).position==="static"}function Sk(t,e){if(!ko(t)||Yi(t).position==="fixed")return null;if(e)return e(t);let n=t.offsetParent;return Ma(t)===n&&(n=n.ownerDocument.body),n}function sU(t,e){const n=Zs(t);if(Iv(t))return n;if(!ko(t)){let s=Fl(t);for(;s&&!dh(s);){if(Wi(s)&&!vb(s))return s;s=Fl(s)}return n}let r=Sk(t,e);for(;r&&v7(r)&&vb(r);)r=Sk(r,e);return r&&dh(r)&&vb(r)&&!m1(r)?n:r||x7(t)||n}const D7=async function(t){const e=this.getOffsetParent||sU,n=this.getDimensions,r=await n(t.floating);return{reference:P7(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function O7(t){return Yi(t).direction==="rtl"}const N7={convertOffsetParentRelativeRectToViewportRelativeRect:w7,getDocumentElement:Ma,getClippingRect:L7,getOffsetParent:sU,getElementRects:D7,getClientRects:T7,getDimensions:I7,getScale:Id,isElement:Wi,isRTL:O7};function iU(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}function M7(t,e){let n=null,r;const s=Ma(t);function i(){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),i();const c=t.getBoundingClientRect(),{left:u,top:d,width:h,height:f}=c;if(o||e(),!h||!f)return;const m=pg(d),g=pg(s.clientWidth-(u+h)),y=pg(s.clientHeight-(d+f)),v=pg(u),S={rootMargin:-m+"px "+-g+"px "+-y+"px "+-v+"px",threshold:Ks(0,Bl(1,l))||1};let E=!0;function L(U){const P=U[0].intersectionRatio;if(P!==l){if(!E)return a();P?a(!1,P):r=setTimeout(()=>{a(!1,1e-7)},1e3)}P===1&&!iU(c,t.getBoundingClientRect())&&a(),E=!1}try{n=new IntersectionObserver(L,{...S,root:s.ownerDocument})}catch{n=new IntersectionObserver(L,S)}n.observe(t)}return a(!0),i}function j7(t,e,n,r){r===void 0&&(r={});const{ancestorScroll:s=!0,ancestorResize:i=!0,elementResize:a=typeof ResizeObserver=="function",layoutShift:o=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,c=y1(t),u=s||i?[...c?Tp(c):[],...e?Tp(e):[]]:[];u.forEach(v=>{s&&v.addEventListener("scroll",n,{passive:!0}),i&&v.addEventListener("resize",n)});const d=c&&o?M7(c,n):null;let h=-1,f=null;a&&(f=new ResizeObserver(v=>{let[_]=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 m,g=l?Zc(t):null;l&&y();function y(){const v=Zc(t);g&&!iU(g,v)&&n(),g=v,m=requestAnimationFrame(y)}return n(),()=>{var v;u.forEach(_=>{s&&_.removeEventListener("scroll",n),i&&_.removeEventListener("resize",n)}),d==null||d(),(v=f)==null||v.disconnect(),f=null,l&&cancelAnimationFrame(m)}}const U7=p7,B7=m7,F7=d7,$7=y7,V7=h7,Ek=u7,G7=g7,K7=(t,e,n)=>{const r=new Map,s={platform:N7,...n},i={...s.platform,_c:r};return c7(t,e,{...s,platform:i})};var H7=typeof document<"u",z7=function(){},my=H7?C.useLayoutEffect:z7;function b0(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,s;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(!b0(t[r],e[r]))return!1;return!0}if(s=Object.keys(t),n=s.length,n!==Object.keys(e).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(e,s[r]))return!1;for(r=n;r--!==0;){const i=s[r];if(!(i==="_owner"&&t.$$typeof)&&!b0(t[i],e[i]))return!1}return!0}return t!==t&&e!==e}function aU(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function wk(t,e){const n=aU(t);return Math.round(e*n)/n}function _b(t){const e=C.useRef(t);return my(()=>{e.current=t}),e}function q7(t){t===void 0&&(t={});const{placement:e="bottom",strategy:n="absolute",middleware:r=[],platform:s,elements:{reference:i,floating:a}={},transform:o=!0,whileElementsMounted:l,open:c}=t,[u,d]=C.useState({x:0,y:0,strategy:n,placement:e,middlewareData:{},isPositioned:!1}),[h,f]=C.useState(r);b0(h,r)||f(r);const[m,g]=C.useState(null),[y,v]=C.useState(null),_=C.useCallback(ne=>{ne!==U.current&&(U.current=ne,g(ne))},[]),S=C.useCallback(ne=>{ne!==P.current&&(P.current=ne,v(ne))},[]),E=i||m,L=a||y,U=C.useRef(null),P=C.useRef(null),I=C.useRef(u),k=l!=null,R=_b(l),M=_b(s),G=_b(c),Y=C.useCallback(()=>{if(!U.current||!P.current)return;const ne={placement:e,strategy:n,middleware:h};M.current&&(ne.platform=M.current),K7(U.current,P.current,ne).then(H=>{const K={...H,isPositioned:G.current!==!1};q.current&&!b0(I.current,K)&&(I.current=K,Zp.flushSync(()=>{d(K)}))})},[h,e,n,M,G]);my(()=>{c===!1&&I.current.isPositioned&&(I.current.isPositioned=!1,d(ne=>({...ne,isPositioned:!1})))},[c]);const q=C.useRef(!1);my(()=>(q.current=!0,()=>{q.current=!1}),[]),my(()=>{if(E&&(U.current=E),L&&(P.current=L),E&&L){if(R.current)return R.current(E,L,Y);Y()}},[E,L,Y,R,k]);const X=C.useMemo(()=>({reference:U,floating:P,setReference:_,setFloating:S}),[_,S]),Z=C.useMemo(()=>({reference:E,floating:L}),[E,L]),oe=C.useMemo(()=>{const ne={position:n,left:0,top:0};if(!Z.floating)return ne;const H=wk(Z.floating,u.x),K=wk(Z.floating,u.y);return o?{...ne,transform:"translate("+H+"px, "+K+"px)",...aU(Z.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:H,top:K}},[n,o,Z.floating,u.x,u.y]);return C.useMemo(()=>({...u,update:Y,refs:X,elements:Z,floatingStyles:oe}),[u,Y,X,Z,oe])}const W7=t=>{function e(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:t,fn(n){const{element:r,padding:s}=typeof t=="function"?t(n):t;return r&&e(r)?r.current!=null?Ek({element:r.current,padding:s}).fn(n):{}:r?Ek({element:r,padding:s}).fn(n):{}}}},Y7=(t,e)=>{const n=U7(t);return{name:n.name,fn:n.fn,options:[t,e]}},X7=(t,e)=>{const n=B7(t);return{name:n.name,fn:n.fn,options:[t,e]}},Q7=(t,e)=>({fn:G7(t).fn,options:[t,e]}),J7=(t,e)=>{const n=F7(t);return{name:n.name,fn:n.fn,options:[t,e]}},Z7=(t,e)=>{const n=$7(t);return{name:n.name,fn:n.fn,options:[t,e]}},eW=(t,e)=>{const n=V7(t);return{name:n.name,fn:n.fn,options:[t,e]}},tW=(t,e)=>{const n=W7(t);return{name:n.name,fn:n.fn,options:[t,e]}};var nW="Arrow",oU=C.forwardRef((t,e)=>{const{children:n,width:r=10,height:s=5,...i}=t;return p.jsx(pr.svg,{...i,ref:e,width:r,height:s,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:t.asChild?n:p.jsx("polygon",{points:"0,0 30,0 15,10"})})});oU.displayName=nW;var rW=oU;function sW(t){const[e,n]=C.useState(void 0);return To(()=>{if(t){n({width:t.offsetWidth,height:t.offsetHeight});const r=new ResizeObserver(s=>{if(!Array.isArray(s)||!s.length)return;const i=s[0];let a,o;if("borderBoxSize"in i){const l=i.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 lU="Popper",[cU,uU]=ym(lU),[pye,dU]=cU(lU),hU="PopperAnchor",fU=C.forwardRef((t,e)=>{const{__scopePopper:n,virtualRef:r,...s}=t,i=dU(hU,n),a=C.useRef(null),o=ps(e,a),l=C.useRef(null);return C.useEffect(()=>{const c=l.current;l.current=(r==null?void 0:r.current)||a.current,c!==l.current&&i.onAnchorChange(l.current)}),r?null:p.jsx(pr.div,{...s,ref:o})});fU.displayName=hU;var v1="PopperContent",[iW,aW]=cU(v1),pU=C.forwardRef((t,e)=>{var be,Pe,Ae,we,Ue,Oe;const{__scopePopper:n,side:r="bottom",sideOffset:s=0,align:i="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:m,...g}=t,y=dU(v1,n),[v,_]=C.useState(null),S=ps(e,Dt=>_(Dt)),[E,L]=C.useState(null),U=sW(E),P=(U==null?void 0:U.width)??0,I=(U==null?void 0:U.height)??0,k=r+(i!=="center"?"-"+i:""),R=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},M=Array.isArray(c)?c:[c],G=M.length>0,Y={padding:R,boundary:M.filter(lW),altBoundary:G},{refs:q,floatingStyles:X,placement:Z,isPositioned:oe,middlewareData:ne}=q7({strategy:"fixed",placement:k,whileElementsMounted:(...Dt)=>j7(...Dt,{animationFrame:f==="always"}),elements:{reference:y.anchor},middleware:[Y7({mainAxis:s+I,alignmentAxis:a}),l&&X7({mainAxis:!0,crossAxis:!1,limiter:d==="partial"?Q7():void 0,...Y}),l&&J7({...Y}),Z7({...Y,apply:({elements:Dt,rects:en,availableWidth:wn,availableHeight:it})=>{const{width:nn,height:mn}=en.reference,On=Dt.floating.style;On.setProperty("--radix-popper-available-width",`${wn}px`),On.setProperty("--radix-popper-available-height",`${it}px`),On.setProperty("--radix-popper-anchor-width",`${nn}px`),On.setProperty("--radix-popper-anchor-height",`${mn}px`)}}),E&&tW({element:E,padding:o}),cW({arrowWidth:P,arrowHeight:I}),h&&eW({strategy:"referenceHidden",...Y})]}),[H,K]=yU(Z),J=Ca(m);To(()=>{oe&&(J==null||J())},[oe,J]);const Q=(be=ne.arrow)==null?void 0:be.x,ve=(Pe=ne.arrow)==null?void 0:Pe.y,Te=((Ae=ne.arrow)==null?void 0:Ae.centerOffset)!==0,[Ne,Ke]=C.useState();return To(()=>{v&&Ke(window.getComputedStyle(v).zIndex)},[v]),p.jsx("div",{ref:q.setFloating,"data-radix-popper-content-wrapper":"",style:{...X,transform:oe?X.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Ne,"--radix-popper-transform-origin":[(we=ne.transformOrigin)==null?void 0:we.x,(Ue=ne.transformOrigin)==null?void 0:Ue.y].join(" "),...((Oe=ne.hide)==null?void 0:Oe.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:p.jsx(iW,{scope:n,placedSide:H,onArrowChange:L,arrowX:Q,arrowY:ve,shouldHideArrow:Te,children:p.jsx(pr.div,{"data-side":H,"data-align":K,...g,ref:S,style:{...g.style,animation:oe?void 0:"none"}})})})});pU.displayName=v1;var mU="PopperArrow",oW={top:"bottom",right:"left",bottom:"top",left:"right"},gU=C.forwardRef(function(e,n){const{__scopePopper:r,...s}=e,i=aW(mU,r),a=oW[i.placedSide];return p.jsx("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[a]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[i.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[i.placedSide],visibility:i.shouldHideArrow?"hidden":void 0},children:p.jsx(rW,{...s,ref:n,style:{...s.style,display:"block"}})})});gU.displayName=mU;function lW(t){return t!==null}var cW=t=>({name:"transformOrigin",options:t,fn(e){var y,v,_;const{placement:n,rects:r,middlewareData:s}=e,a=((y=s.arrow)==null?void 0:y.centerOffset)!==0,o=a?0:t.arrowWidth,l=a?0:t.arrowHeight,[c,u]=yU(n),d={start:"0%",center:"50%",end:"100%"}[u],h=(((v=s.arrow)==null?void 0:v.x)??0)+o/2,f=(((_=s.arrow)==null?void 0:_.y)??0)+l/2;let m="",g="";return c==="bottom"?(m=a?d:`${h}px`,g=`${-l}px`):c==="top"?(m=a?d:`${h}px`,g=`${r.floating.height+l}px`):c==="right"?(m=`${-l}px`,g=a?d:`${f}px`):c==="left"&&(m=`${r.floating.width+l}px`,g=a?d:`${f}px`),{data:{x:m,y:g}}}});function yU(t){const[e,n="center"]=t.split("-");return[e,n]}var uW=fU,dW=pU,hW=gU,fW=Symbol("radix.slottable");function pW(t){const e=({children:n})=>p.jsx(p.Fragment,{children:n});return e.displayName=`${t}.Slottable`,e.__radixId=fW,e}var[Ov]=ym("Tooltip",[uU]),_1=uU(),vU="TooltipProvider",mW=700,Tk="tooltip.open",[gW,_U]=Ov(vU),bU=t=>{const{__scopeTooltip:e,delayDuration:n=mW,skipDelayDuration:r=300,disableHoverableContent:s=!1,children:i}=t,a=C.useRef(!0),o=C.useRef(!1),l=C.useRef(0);return C.useEffect(()=>{const c=l.current;return()=>window.clearTimeout(c)},[]),p.jsx(gW,{scope:e,isOpenDelayedRef:a,delayDuration:n,onOpen:C.useCallback(()=>{window.clearTimeout(l.current),a.current=!1},[]),onClose:C.useCallback(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>a.current=!0,r)},[r]),isPointerInTransitRef:o,onPointerInTransitChange:C.useCallback(c=>{o.current=c},[]),disableHoverableContent:s,children:i})};bU.displayName=vU;var xU="Tooltip",[mye,Nv]=Ov(xU),yE="TooltipTrigger",yW=C.forwardRef((t,e)=>{const{__scopeTooltip:n,...r}=t,s=Nv(yE,n),i=_U(yE,n),a=_1(n),o=C.useRef(null),l=ps(e,o,s.onTriggerChange),c=C.useRef(!1),u=C.useRef(!1),d=C.useCallback(()=>c.current=!1,[]);return C.useEffect(()=>()=>document.removeEventListener("pointerup",d),[d]),p.jsx(uW,{asChild:!0,...a,children:p.jsx(pr.button,{"aria-describedby":s.open?s.contentId:void 0,"data-state":s.stateAttribute,...r,ref:l,onPointerMove:Un(t.onPointerMove,h=>{h.pointerType!=="touch"&&!u.current&&!i.isPointerInTransitRef.current&&(s.onTriggerEnter(),u.current=!0)}),onPointerLeave:Un(t.onPointerLeave,()=>{s.onTriggerLeave(),u.current=!1}),onPointerDown:Un(t.onPointerDown,()=>{s.open&&s.onClose(),c.current=!0,document.addEventListener("pointerup",d,{once:!0})}),onFocus:Un(t.onFocus,()=>{c.current||s.onOpen()}),onBlur:Un(t.onBlur,s.onClose),onClick:Un(t.onClick,s.onClose)})})});yW.displayName=yE;var vW="TooltipPortal",[gye,_W]=Ov(vW,{forceMount:void 0}),hh="TooltipContent",SU=C.forwardRef((t,e)=>{const n=_W(hh,t.__scopeTooltip),{forceMount:r=n.forceMount,side:s="top",...i}=t,a=Nv(hh,t.__scopeTooltip);return p.jsx(Ih,{present:r||a.open,children:a.disableHoverableContent?p.jsx(EU,{side:s,...i,ref:e}):p.jsx(bW,{side:s,...i,ref:e})})}),bW=C.forwardRef((t,e)=>{const n=Nv(hh,t.__scopeTooltip),r=_U(hh,t.__scopeTooltip),s=C.useRef(null),i=ps(e,s),[a,o]=C.useState(null),{trigger:l,onClose:c}=n,u=s.current,{onPointerInTransitChange:d}=r,h=C.useCallback(()=>{o(null),d(!1)},[d]),f=C.useCallback((m,g)=>{const y=m.currentTarget,v={x:m.clientX,y:m.clientY},_=TW(v,y.getBoundingClientRect()),S=AW(v,_),E=RW(g.getBoundingClientRect()),L=kW([...S,...E]);o(L),d(!0)},[d]);return C.useEffect(()=>()=>h(),[h]),C.useEffect(()=>{if(l&&u){const m=y=>f(y,u),g=y=>f(y,l);return l.addEventListener("pointerleave",m),u.addEventListener("pointerleave",g),()=>{l.removeEventListener("pointerleave",m),u.removeEventListener("pointerleave",g)}}},[l,u,f,h]),C.useEffect(()=>{if(a){const m=g=>{const y=g.target,v={x:g.clientX,y:g.clientY},_=(l==null?void 0:l.contains(y))||(u==null?void 0:u.contains(y)),S=!CW(v,a);_?h():S&&(h(),c())};return document.addEventListener("pointermove",m),()=>document.removeEventListener("pointermove",m)}},[l,u,a,c,h]),p.jsx(EU,{...t,ref:i})}),[xW,SW]=Ov(xU,{isInside:!1}),EW=pW("TooltipContent"),EU=C.forwardRef((t,e)=>{const{__scopeTooltip:n,children:r,"aria-label":s,onEscapeKeyDown:i,onPointerDownOutside:a,...o}=t,l=Nv(hh,n),c=_1(n),{onClose:u}=l;return C.useEffect(()=>(document.addEventListener(Tk,u),()=>document.removeEventListener(Tk,u)),[u]),C.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]),p.jsx(wv,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:a,onFocusOutside:d=>d.preventDefault(),onDismiss:u,children:p.jsxs(dW,{"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:[p.jsx(EW,{children:r}),p.jsx(xW,{scope:n,isInside:!0,children:p.jsx(BH,{id:l.contentId,role:"tooltip",children:s||r})})]})})});SU.displayName=hh;var wU="TooltipArrow",wW=C.forwardRef((t,e)=>{const{__scopeTooltip:n,...r}=t,s=_1(n);return SW(wU,n).isInside?null:p.jsx(hW,{...s,...r,ref:e})});wW.displayName=wU;function TW(t,e){const n=Math.abs(e.top-t.y),r=Math.abs(e.bottom-t.y),s=Math.abs(e.right-t.x),i=Math.abs(e.left-t.x);switch(Math.min(n,r,s,i)){case i:return"left";case s:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function AW(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 RW(t){const{top:e,right:n,bottom:r,left:s}=t;return[{x:s,y:e},{x:n,y:e},{x:n,y:r},{x:s,y:r}]}function CW(t,e){const{x:n,y:r}=t;let s=!1;for(let i=0,a=e.length-1;i<e.length;a=i++){const o=e[i],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&&(s=!s)}return s}function kW(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),LW(e)}function LW(t){if(t.length<=1)return t.slice();const e=[];for(let r=0;r<t.length;r++){const s=t[r];for(;e.length>=2;){const i=e[e.length-1],a=e[e.length-2];if((i.x-a.x)*(s.y-a.y)>=(i.y-a.y)*(s.x-a.x))e.pop();else break}e.push(s)}e.pop();const n=[];for(let r=t.length-1;r>=0;r--){const s=t[r];for(;n.length>=2;){const i=n[n.length-1],a=n[n.length-2];if((i.x-a.x)*(s.y-a.y)>=(i.y-a.y)*(s.x-a.x))n.pop();else break}n.push(s)}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 IW=bU,TU=SU;const PW=IW,DW=C.forwardRef(({className:t,sideOffset:e=4,...n},r)=>p.jsx(TU,{ref:r,sideOffset:e,className:gs("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}));DW.displayName=TU.displayName;const b1=C.createContext({});function x1(t){const e=C.useRef(null);return e.current===null&&(e.current=t()),e.current}const OW=typeof window<"u",AU=OW?C.useLayoutEffect:C.useEffect,Mv=C.createContext(null);function S1(t,e){t.indexOf(e)===-1&&t.push(e)}function x0(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const ka=(t,e,n)=>n>e?e:n<t?t:n;let E1=()=>{};const $l={},RU=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function CU(t){return typeof t=="object"&&t!==null}const kU=t=>/^0[^.\s]+$/u.test(t);function LU(t){let e;return()=>(e===void 0&&(e=t()),e)}const Ti=t=>t,NW=(t,e)=>n=>e(t(n)),Em=(...t)=>t.reduce(NW),Ap=(t,e,n)=>{const r=e-t;return r===0?1:(n-t)/r};class w1{constructor(){this.subscriptions=[]}add(e){return S1(this.subscriptions,e),()=>x0(this.subscriptions,e)}notify(e,n,r){const s=this.subscriptions.length;if(s)if(s===1)this.subscriptions[0](e,n,r);else for(let i=0;i<s;i++){const a=this.subscriptions[i];a&&a(e,n,r)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const ei=t=>t*1e3,Ei=t=>t/1e3;function IU(t,e){return e?t*(1e3/e):0}const PU=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t,MW=1e-7,jW=12;function UW(t,e,n,r,s){let i,a,o=0;do a=e+(n-e)/2,i=PU(a,r,s)-t,i>0?n=a:e=a;while(Math.abs(i)>MW&&++o<jW);return a}function wm(t,e,n,r){if(t===e&&n===r)return Ti;const s=i=>UW(i,0,1,t,n);return i=>i===0||i===1?i:PU(s(i),e,r)}const DU=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,OU=t=>e=>1-t(1-e),NU=wm(.33,1.53,.69,.99),T1=OU(NU),MU=DU(T1),jU=t=>t>=1?1:(t*=2)<1?.5*T1(t):.5*(2-Math.pow(2,-10*(t-1))),A1=t=>1-Math.sin(Math.acos(t)),UU=OU(A1),BU=DU(A1),BW=wm(.42,0,1,1),FW=wm(0,0,.58,1),FU=wm(.42,0,.58,1),$W=t=>Array.isArray(t)&&typeof t[0]!="number",$U=t=>Array.isArray(t)&&typeof t[0]=="number",VW={linear:Ti,easeIn:BW,easeInOut:FU,easeOut:FW,circIn:A1,circInOut:BU,circOut:UU,backIn:T1,backInOut:MU,backOut:NU,anticipate:jU},GW=t=>typeof t=="string",Ak=t=>{if($U(t)){E1(t.length===4);const[e,n,r,s]=t;return wm(e,n,r,s)}else if(GW(t))return VW[t];return t},mg=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function KW(t,e){let n=new Set,r=new Set,s=!1,i=!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 m=h&&s?n:r;return d&&a.add(u),m.add(u),u},cancel:u=>{r.delete(u),a.delete(u)},process:u=>{if(o=u,s){i=!0;return}s=!0;const d=n;n=r,r=d,n.forEach(l),n.clear(),s=!1,i&&(i=!1,c.process(u))}};return c}const HW=40;function VU(t,e){let n=!1,r=!0;const s={delta:0,timestamp:0,isProcessing:!1},i=()=>n=!0,a=mg.reduce((S,E)=>(S[E]=KW(i),S),{}),{setup:o,read:l,resolveKeyframes:c,preUpdate:u,update:d,preRender:h,render:f,postRender:m}=a,g=()=>{const S=$l.useManualTiming,E=S?s.timestamp:performance.now();n=!1,S||(s.delta=r?1e3/60:Math.max(Math.min(E-s.timestamp,HW),1)),s.timestamp=E,s.isProcessing=!0,o.process(s),l.process(s),c.process(s),u.process(s),d.process(s),h.process(s),f.process(s),m.process(s),s.isProcessing=!1,n&&e&&(r=!1,t(g))},y=()=>{n=!0,r=!0,s.isProcessing||t(g)};return{schedule:mg.reduce((S,E)=>{const L=a[E];return S[E]=(U,P=!1,I=!1)=>(n||y(),L.schedule(U,P,I)),S},{}),cancel:S=>{for(let E=0;E<mg.length;E++)a[mg[E]].cancel(S)},state:s,steps:a}}const{schedule:Sn,cancel:Vl,state:Br,steps:bb}=VU(typeof requestAnimationFrame<"u"?requestAnimationFrame:Ti,!0);let gy;function zW(){gy=void 0}const us={now:()=>(gy===void 0&&us.set(Br.isProcessing||$l.useManualTiming?Br.timestamp:performance.now()),gy),set:t=>{gy=t,queueMicrotask(zW)}},GU=t=>e=>typeof e=="string"&&e.startsWith(t),KU=GU("--"),qW=GU("var(--"),R1=t=>qW(t)?WW.test(t.split("/*")[0].trim()):!1,WW=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function Rk(t){return typeof t!="string"?!1:t.split("/*")[0].includes("var(--")}const Uh={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},Rp={...Uh,transform:t=>ka(0,1,t)},gg={...Uh,default:1},Kf=t=>Math.round(t*1e5)/1e5,C1=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function YW(t){return t==null}const XW=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,k1=(t,e)=>n=>!!(typeof n=="string"&&XW.test(n)&&n.startsWith(t)||e&&!YW(n)&&Object.prototype.hasOwnProperty.call(n,e)),HU=(t,e,n)=>r=>{if(typeof r!="string")return r;const[s,i,a,o]=r.match(C1);return{[t]:parseFloat(s),[e]:parseFloat(i),[n]:parseFloat(a),alpha:o!==void 0?parseFloat(o):1}},QW=t=>ka(0,255,t),xb={...Uh,transform:t=>Math.round(QW(t))},xc={test:k1("rgb","red"),parse:HU("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:r=1})=>"rgba("+xb.transform(t)+", "+xb.transform(e)+", "+xb.transform(n)+", "+Kf(Rp.transform(r))+")"};function JW(t){let e="",n="",r="",s="";return t.length>5?(e=t.substring(1,3),n=t.substring(3,5),r=t.substring(5,7),s=t.substring(7,9)):(e=t.substring(1,2),n=t.substring(2,3),r=t.substring(3,4),s=t.substring(4,5),e+=e,n+=n,r+=r,s+=s),{red:parseInt(e,16),green:parseInt(n,16),blue:parseInt(r,16),alpha:s?parseInt(s,16)/255:1}}const vE={test:k1("#"),parse:JW,transform:xc.transform},Tm=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),zo=Tm("deg"),Ra=Tm("%"),ut=Tm("px"),ZW=Tm("vh"),eY=Tm("vw"),Ck={...Ra,parse:t=>Ra.parse(t)/100,transform:t=>Ra.transform(t*100)},md={test:k1("hsl","hue"),parse:HU("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:r=1})=>"hsla("+Math.round(t)+", "+Ra.transform(Kf(e))+", "+Ra.transform(Kf(n))+", "+Kf(Rp.transform(r))+")"},dr={test:t=>xc.test(t)||vE.test(t)||md.test(t),parse:t=>xc.test(t)?xc.parse(t):md.test(t)?md.parse(t):vE.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?xc.transform(t):md.transform(t),getAnimatableNone:t=>{const e=dr.parse(t);return e.alpha=0,dr.transform(e)}},tY=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function nY(t){var e,n;return isNaN(t)&&typeof t=="string"&&(((e=t.match(C1))==null?void 0:e.length)||0)+(((n=t.match(tY))==null?void 0:n.length)||0)>0}const zU="number",qU="color",rY="var",sY="var(",kk="${}",iY=/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 fh(t){const e=t.toString(),n=[],r={color:[],number:[],var:[]},s=[];let i=0;const o=e.replace(iY,l=>(dr.test(l)?(r.color.push(i),s.push(qU),n.push(dr.parse(l))):l.startsWith(sY)?(r.var.push(i),s.push(rY),n.push(l)):(r.number.push(i),s.push(zU),n.push(parseFloat(l))),++i,kk)).split(kk);return{values:n,split:o,indexes:r,types:s}}function aY(t){return fh(t).values}function WU({split:t,types:e}){const n=t.length;return r=>{let s="";for(let i=0;i<n;i++)if(s+=t[i],r[i]!==void 0){const a=e[i];a===zU?s+=Kf(r[i]):a===qU?s+=dr.transform(r[i]):s+=r[i]}return s}}function oY(t){return WU(fh(t))}const lY=t=>typeof t=="number"?0:dr.test(t)?dr.getAnimatableNone(t):t,cY=(t,e)=>typeof t=="number"?e!=null&&e.trim().endsWith("/")?t:0:lY(t);function uY(t){const e=fh(t);return WU(e)(e.values.map((r,s)=>cY(r,e.split[s])))}const zi={test:nY,parse:aY,createTransformer:oY,getAnimatableNone:uY};function Sb(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 dY({hue:t,saturation:e,lightness:n,alpha:r}){t/=360,e/=100,n/=100;let s=0,i=0,a=0;if(!e)s=i=a=n;else{const o=n<.5?n*(1+e):n+e-n*e,l=2*n-o;s=Sb(l,o,t+1/3),i=Sb(l,o,t),a=Sb(l,o,t-1/3)}return{red:Math.round(s*255),green:Math.round(i*255),blue:Math.round(a*255),alpha:r}}function S0(t,e){return n=>n>0?e:t}const In=(t,e,n)=>t+(e-t)*n,Eb=(t,e,n)=>{const r=t*t,s=n*(e*e-r)+r;return s<0?0:Math.sqrt(s)},hY=[vE,xc,md],fY=t=>hY.find(e=>e.test(t));function Lk(t){const e=fY(t);if(!e)return!1;let n=e.parse(t);return e===md&&(n=dY(n)),n}const Ik=(t,e)=>{const n=Lk(t),r=Lk(e);if(!n||!r)return S0(t,e);const s={...n};return i=>(s.red=Eb(n.red,r.red,i),s.green=Eb(n.green,r.green,i),s.blue=Eb(n.blue,r.blue,i),s.alpha=In(n.alpha,r.alpha,i),xc.transform(s))},_E=new Set(["none","hidden"]);function pY(t,e){return _E.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function mY(t,e){return n=>In(t,e,n)}function L1(t){return typeof t=="number"?mY:typeof t=="string"?R1(t)?S0:dr.test(t)?Ik:vY:Array.isArray(t)?YU:typeof t=="object"?dr.test(t)?Ik:gY:S0}function YU(t,e){const n=[...t],r=n.length,s=t.map((i,a)=>L1(i)(i,e[a]));return i=>{for(let a=0;a<r;a++)n[a]=s[a](i);return n}}function gY(t,e){const n={...t,...e},r={};for(const s in n)t[s]!==void 0&&e[s]!==void 0&&(r[s]=L1(t[s])(t[s],e[s]));return s=>{for(const i in r)n[i]=r[i](s);return n}}function yY(t,e){const n=[],r={color:0,var:0,number:0};for(let s=0;s<e.values.length;s++){const i=e.types[s],a=t.indexes[i][r[i]],o=t.values[a]??0;n[s]=o,r[i]++}return n}const vY=(t,e)=>{const n=zi.createTransformer(e),r=fh(t),s=fh(e);return r.indexes.var.length===s.indexes.var.length&&r.indexes.color.length===s.indexes.color.length&&r.indexes.number.length>=s.indexes.number.length?_E.has(t)&&!s.values.length||_E.has(e)&&!r.values.length?pY(t,e):Em(YU(yY(r,s),s.values),n):S0(t,e)};function XU(t,e,n){return typeof t=="number"&&typeof e=="number"&&typeof n=="number"?In(t,e,n):L1(t)(t,e)}const _Y=t=>{const e=({timestamp:n})=>t(n);return{start:(n=!0)=>Sn.update(e,n),stop:()=>Vl(e),now:()=>Br.isProcessing?Br.timestamp:us.now()}},QU=(t,e,n=10)=>{let r="";const s=Math.max(Math.round(e/n),2);for(let i=0;i<s;i++)r+=Math.round(t(i/(s-1))*1e4)/1e4+", ";return`linear(${r.substring(0,r.length-2)})`},E0=2e4;function I1(t){let e=0;const n=50;let r=t.next(e);for(;!r.done&&e<E0;)e+=n,r=t.next(e);return e>=E0?1/0:e}function bY(t,e=100,n){const r=n({...t,keyframes:[0,e]}),s=Math.min(I1(r),E0);return{type:"keyframes",ease:i=>r.next(s*i).value/e,duration:Ei(s)}}const Xn={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 bE(t,e){return t*Math.sqrt(1-e*e)}const xY=12;function SY(t,e,n){let r=n;for(let s=1;s<xY;s++)r=r-t(r)/e(r);return r}const wb=.001;function EY({duration:t=Xn.duration,bounce:e=Xn.bounce,velocity:n=Xn.velocity,mass:r=Xn.mass}){let s,i,a=1-e;a=ka(Xn.minDamping,Xn.maxDamping,a),t=ka(Xn.minDuration,Xn.maxDuration,Ei(t)),a<1?(s=c=>{const u=c*a,d=u*t,h=u-n,f=bE(c,a),m=Math.exp(-d);return wb-h/f*m},i=c=>{const d=c*a*t,h=d*n+n,f=Math.pow(a,2)*Math.pow(c,2)*t,m=Math.exp(-d),g=bE(Math.pow(c,2),a);return(-s(c)+wb>0?-1:1)*((h-f)*m)/g}):(s=c=>{const u=Math.exp(-c*t),d=(c-n)*t+1;return-wb+u*d},i=c=>{const u=Math.exp(-c*t),d=(n-c)*(t*t);return u*d});const o=5/t,l=SY(s,i,o);if(t=ei(t),isNaN(l))return{stiffness:Xn.stiffness,damping:Xn.damping,duration:t};{const c=Math.pow(l,2)*r;return{stiffness:c,damping:a*2*Math.sqrt(r*c),duration:t}}}const wY=["duration","bounce"],TY=["stiffness","damping","mass"];function Pk(t,e){return e.some(n=>t[n]!==void 0)}function AY(t){let e={velocity:Xn.velocity,stiffness:Xn.stiffness,damping:Xn.damping,mass:Xn.mass,isResolvedFromDuration:!1,...t};if(!Pk(t,TY)&&Pk(t,wY))if(e.velocity=0,t.visualDuration){const n=t.visualDuration,r=2*Math.PI/(n*1.2),s=r*r,i=2*ka(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:Xn.mass,stiffness:s,damping:i}}else{const n=EY({...t,velocity:0});e={...e,...n,mass:Xn.mass},e.isResolvedFromDuration=!0}return e}function w0(t=Xn.visualDuration,e=Xn.bounce){const n=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:r,restDelta:s}=n;const i=n.keyframes[0],a=n.keyframes[n.keyframes.length-1],o={done:!1,value:i},{stiffness:l,damping:c,mass:u,duration:d,velocity:h,isResolvedFromDuration:f}=AY({...n,velocity:-Ei(n.velocity||0)}),m=h||0,g=c/(2*Math.sqrt(l*u)),y=a-i,v=Ei(Math.sqrt(l/u)),_=Math.abs(y)<5;r||(r=_?Xn.restSpeed.granular:Xn.restSpeed.default),s||(s=_?Xn.restDelta.granular:Xn.restDelta.default);let S,E,L,U,P,I;if(g<1)L=bE(v,g),U=(m+g*v*y)/L,S=R=>{const M=Math.exp(-g*v*R);return a-M*(U*Math.sin(L*R)+y*Math.cos(L*R))},P=g*v*U+y*L,I=g*v*y-U*L,E=R=>Math.exp(-g*v*R)*(P*Math.sin(L*R)+I*Math.cos(L*R));else if(g===1){S=M=>a-Math.exp(-v*M)*(y+(m+v*y)*M);const R=m+v*y;E=M=>Math.exp(-v*M)*(v*R*M-m)}else{const R=v*Math.sqrt(g*g-1);S=q=>{const X=Math.exp(-g*v*q),Z=Math.min(R*q,300);return a-X*((m+g*v*y)*Math.sinh(Z)+R*y*Math.cosh(Z))/R};const M=(m+g*v*y)/R,G=g*v*M-y*R,Y=g*v*y-M*R;E=q=>{const X=Math.exp(-g*v*q),Z=Math.min(R*q,300);return X*(G*Math.sinh(Z)+Y*Math.cosh(Z))}}const k={calculatedDuration:f&&d||null,velocity:R=>ei(E(R)),next:R=>{if(!f&&g<1){const G=Math.exp(-g*v*R),Y=Math.sin(L*R),q=Math.cos(L*R),X=a-G*(U*Y+y*q),Z=ei(G*(P*Y+I*q));return o.done=Math.abs(Z)<=r&&Math.abs(a-X)<=s,o.value=o.done?a:X,o}const M=S(R);if(f)o.done=R>=d;else{const G=ei(E(R));o.done=Math.abs(G)<=r&&Math.abs(a-M)<=s}return o.value=o.done?a:M,o},toString:()=>{const R=Math.min(I1(k),E0),M=QU(G=>k.next(R*G).value,R,30);return R+"ms "+M},toTransition:()=>{}};return k}w0.applyToOptions=t=>{const e=bY(t,100,w0);return t.ease=e.ease,t.duration=ei(e.duration),t.type="keyframes",t};const RY=5;function JU(t,e,n){const r=Math.max(e-RY,0);return IU(n-t(r),e-r)}function xE({keyframes:t,velocity:e=0,power:n=.8,timeConstant:r=325,bounceDamping:s=10,bounceStiffness:i=500,modifyTarget:a,min:o,max:l,restDelta:c=.5,restSpeed:u}){const d=t[0],h={done:!1,value:d},f=I=>o!==void 0&&I<o||l!==void 0&&I>l,m=I=>o===void 0?l:l===void 0||Math.abs(o-I)<Math.abs(l-I)?o:l;let g=n*e;const y=d+g,v=a===void 0?y:a(y);v!==y&&(g=v-d);const _=I=>-g*Math.exp(-I/r),S=I=>v+_(I),E=I=>{const k=_(I),R=S(I);h.done=Math.abs(k)<=c,h.value=h.done?v:R};let L,U;const P=I=>{f(h.value)&&(L=I,U=w0({keyframes:[h.value,m(h.value)],velocity:JU(S,I,h.value),damping:s,stiffness:i,restDelta:c,restSpeed:u}))};return P(0),{calculatedDuration:null,next:I=>{let k=!1;return!U&&L===void 0&&(k=!0,E(I),P(I)),L!==void 0&&I>=L?U.next(I-L):(!k&&E(I),h)}}}function CY(t,e,n){const r=[],s=n||$l.mix||XU,i=t.length-1;for(let a=0;a<i;a++){let o=s(t[a],t[a+1]);if(e){const l=Array.isArray(e)?e[a]||Ti:e;o=Em(l,o)}r.push(o)}return r}function kY(t,e,{clamp:n=!0,ease:r,mixer:s}={}){const i=t.length;if(E1(i===e.length),i===1)return()=>e[0];if(i===2&&e[0]===e[1])return()=>e[1];const a=t[0]===t[1];t[0]>t[i-1]&&(t=[...t].reverse(),e=[...e].reverse());const o=CY(e,r,s),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=Ap(t[d],t[d+1],u);return o[d](h)};return n?u=>c(ka(t[0],t[i-1],u)):c}function LY(t,e){const n=t[t.length-1];for(let r=1;r<=e;r++){const s=Ap(0,e,r);t.push(In(n,1,s))}}function IY(t){const e=[0];return LY(e,t.length-1),e}function PY(t,e){return t.map(n=>n*e)}function DY(t,e){return t.map(()=>e||FU).splice(0,t.length-1)}function Hf({duration:t=300,keyframes:e,times:n,ease:r="easeInOut"}){const s=$W(r)?r.map(Ak):Ak(r),i={done:!1,value:e[0]},a=PY(n&&n.length===e.length?n:IY(e),t),o=kY(a,e,{ease:Array.isArray(s)?s:DY(e,s)});return{calculatedDuration:t,next:l=>(i.value=o(l),i.done=l>=t,i)}}const OY=t=>t!==null;function jv(t,{repeat:e,repeatType:n="loop"},r,s=1){const i=t.filter(OY),o=s<0||e&&n!=="loop"&&e%2===1?0:i.length-1;return!o||r===void 0?i[o]:r}const NY={decay:xE,inertia:xE,tween:Hf,keyframes:Hf,spring:w0};function ZU(t){typeof t.type=="string"&&(t.type=NY[t.type])}class P1{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 MY=t=>t/100;class T0 extends P1{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,s;const{motionValue:n}=this.options;n&&n.updatedAt!==us.now()&&this.tick(us.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(s=(r=this.options).onStop)==null||s.call(r))},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){const{options:e}=this;ZU(e);const{type:n=Hf,repeat:r=0,repeatDelay:s=0,repeatType:i,velocity:a=0}=e;let{keyframes:o}=e;const l=n||Hf;l!==Hf&&typeof o[0]!="number"&&(this.mixKeyframes=Em(MY,XU(o[0],o[1])),o=[0,100]);const c=l({...e,keyframes:o});i==="mirror"&&(this.mirroredGenerator=l({...e,keyframes:[...o].reverse(),velocity:-a})),c.calculatedDuration===null&&(c.calculatedDuration=I1(c));const{calculatedDuration:u}=c;this.calculatedDuration=u,this.resolvedDuration=u+s,this.totalDuration=this.resolvedDuration*(r+1)-s,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:s,mixKeyframes:i,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:m,onUpdate:g,finalKeyframe:y}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-s/this.speed,this.startTime)),n?this.currentTime=e:this.updateTime(e);const v=this.currentTime-c*(this.playbackSpeed>=0?1:-1),_=this.playbackSpeed>=0?v<0:v>s;this.currentTime=Math.max(v,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let S=this.currentTime,E=r;if(d){const I=Math.min(this.currentTime,s)/o;let k=Math.floor(I),R=I%1;!R&&I>=1&&(R=1),R===1&&k--,k=Math.min(k,d+1),!!(k%2)&&(h==="reverse"?(R=1-R,f&&(R-=f/o)):h==="mirror"&&(E=a)),S=ka(0,1,R)*o}let L;_?(this.delayState.value=u[0],L=this.delayState):L=E.next(S),i&&!_&&(L.value=i(L.value));let{done:U}=L;!_&&l!==null&&(U=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const P=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&U);return P&&m!==xE&&(L.value=jv(u,this.options,y,this.speed)),g&&g(L.value),P&&this.finish(),L}then(e,n){return this.finished.then(e,n)}get duration(){return Ei(this.calculatedDuration)}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+Ei(e)}get time(){return Ei(this.currentTime)}set time(e){e=ei(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 JU(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(us.now()),this.playbackSpeed=e,n&&this.driver&&(this.time=Ei(this.currentTime))}play(){var s,i;if(this.isStopped)return;const{driver:e=_Y,startTime:n}=this.options;this.driver||(this.driver=e(a=>this.tick(a))),(i=(s=this.options).onPlay)==null||i.call(s);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(us.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 jY(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const Sc=t=>t*180/Math.PI,SE=t=>{const e=Sc(Math.atan2(t[1],t[0]));return EE(e)},UY={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:SE,rotateZ:SE,skewX:t=>Sc(Math.atan(t[1])),skewY:t=>Sc(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},EE=t=>(t=t%360,t<0&&(t+=360),t),Dk=SE,Ok=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Nk=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),BY={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Ok,scaleY:Nk,scale:t=>(Ok(t)+Nk(t))/2,rotateX:t=>EE(Sc(Math.atan2(t[6],t[5]))),rotateY:t=>EE(Sc(Math.atan2(-t[2],t[0]))),rotateZ:Dk,rotate:Dk,skewX:t=>Sc(Math.atan(t[4])),skewY:t=>Sc(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function wE(t){return t.includes("scale")?1:0}function TE(t,e){if(!t||t==="none")return wE(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,s;if(n)r=BY,s=n;else{const o=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=UY,s=o}if(!s)return wE(e);const i=r[e],a=s[1].split(",").map($Y);return typeof i=="function"?i(a):a[i]}const FY=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return TE(n,e)};function $Y(t){return parseFloat(t.trim())}const Bh=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Fh=new Set(Bh),Mk=t=>t===Uh||t===ut,VY=new Set(["x","y","z"]),GY=Bh.filter(t=>!VY.has(t));function KY(t){const e=[];return GY.forEach(n=>{const r=t.getValue(n);r!==void 0&&(e.push([n,r.get()]),r.set(n.startsWith("scale")?1:0))}),e}const xl={width:({x:t},{paddingLeft:e="0",paddingRight:n="0",boxSizing:r})=>{const s=t.max-t.min;return r==="border-box"?s:s-parseFloat(e)-parseFloat(n)},height:({y:t},{paddingTop:e="0",paddingBottom:n="0",boxSizing:r})=>{const s=t.max-t.min;return r==="border-box"?s:s-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})=>TE(e,"x"),y:(t,{transform:e})=>TE(e,"y")};xl.translateX=xl.x;xl.translateY=xl.y;const Kc=new Set;let AE=!1,RE=!1,CE=!1;function eB(){if(RE){const t=Array.from(Kc).filter(r=>r.needsMeasurement),e=new Set(t.map(r=>r.element)),n=new Map;e.forEach(r=>{const s=KY(r);s.length&&(n.set(r,s),r.render())}),t.forEach(r=>r.measureInitialState()),e.forEach(r=>{r.render();const s=n.get(r);s&&s.forEach(([i,a])=>{var o;(o=r.getValue(i))==null||o.set(a)})}),t.forEach(r=>r.measureEndState()),t.forEach(r=>{r.suspendedScrollY!==void 0&&window.scrollTo(0,r.suspendedScrollY)})}RE=!1,AE=!1,Kc.forEach(t=>t.complete(CE)),Kc.clear()}function tB(){Kc.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(RE=!0)})}function HY(){CE=!0,tB(),eB(),CE=!1}class D1{constructor(e,n,r,s,i,a=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=n,this.name=r,this.motionValue=s,this.element=i,this.isAsync=a}scheduleResolve(){this.state="scheduled",this.isAsync?(Kc.add(this),AE||(AE=!0,Sn.read(tB),Sn.resolveKeyframes(eB))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:n,element:r,motionValue:s}=this;if(e[0]===null){const i=s==null?void 0:s.get(),a=e[e.length-1];if(i!==void 0)e[0]=i;else if(r&&n){const o=r.readValue(n,a);o!=null&&(e[0]=o)}e[0]===void 0&&(e[0]=a),s&&i===void 0&&s.set(e[0])}jY(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Kc.delete(this)}cancel(){this.state==="scheduled"&&(Kc.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const zY=t=>t.startsWith("--");function nB(t,e,n){zY(e)?t.style.setProperty(e,n):t.style[e]=n}const qY={};function rB(t,e){const n=LU(t);return()=>qY[e]??n()}const WY=rB(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),sB=rB(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),xf=([t,e,n,r])=>`cubic-bezier(${t}, ${e}, ${n}, ${r})`,jk={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:xf([0,.65,.55,1]),circOut:xf([.55,0,1,.45]),backIn:xf([.31,.01,.66,-.59]),backOut:xf([.33,1.53,.69,.99])};function iB(t,e){if(t)return typeof t=="function"?sB()?QU(t,e):"ease-out":$U(t)?xf(t):Array.isArray(t)?t.map(n=>iB(n,e)||jk.easeOut):jk[t]}function YY(t,e,n,{delay:r=0,duration:s=300,repeat:i=0,repeatType:a="loop",ease:o="easeOut",times:l}={},c=void 0){const u={[e]:n};l&&(u.offset=l);const d=iB(o,s);Array.isArray(d)&&(u.easing=d);const h={delay:r,duration:s,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:i+1,direction:a==="reverse"?"alternate":"normal"};return c&&(h.pseudoElement=c),t.animate(u,h)}function aB(t){return typeof t=="function"&&"applyToOptions"in t}function XY({type:t,...e}){return aB(t)&&sB()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class oB extends P1{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!e)return;const{element:n,name:r,keyframes:s,pseudoElement:i,allowFlatten:a=!1,finalKeyframe:o,onComplete:l}=e;this.isPseudoElement=!!i,this.allowFlatten=a,this.options=e,E1(typeof e.type!="string");const c=XY(e);this.animation=YY(n,r,s,c,i),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const u=jv(s,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(u),nB(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,s;const e=(n=this.options)==null?void 0:n.element;!this.isPseudoElement&&(e!=null&&e.isConnected)&&((s=(r=this.animation).commitStyles)==null||s.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 Ei(Number(e))}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+Ei(e)}get time(){return Ei(Number(this.animation.currentTime)||0)}set time(e){const n=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=ei(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:s}){var i;return this.allowFlatten&&((i=this.animation.effect)==null||i.updateTiming({easing:"linear"})),this.animation.onfinish=null,e&&WY()?(this.animation.timeline=e,n&&(this.animation.rangeStart=n),r&&(this.animation.rangeEnd=r),Ti):s(this)}}const lB={anticipate:jU,backInOut:MU,circInOut:BU};function QY(t){return t in lB}function JY(t){typeof t.ease=="string"&&QY(t.ease)&&(t.ease=lB[t.ease])}const Tb=10;class ZY extends oB{constructor(e){JY(e),ZU(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:s,element:i,...a}=this.options;if(!n)return;if(e!==void 0){n.set(e);return}const o=new T0({...a,autoplay:!1}),l=Math.max(Tb,us.now()-this.startTime),c=ka(0,Tb,l-Tb),u=o.sample(l).value,{name:d}=this.options;i&&d&&nB(i,d,u),n.setWithVelocity(o.sample(Math.max(0,l-c)).value,u,c),o.stop()}}const Uk=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(zi.test(t)||t==="0")&&!t.startsWith("url("));function eX(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 tX(t,e,n,r){const s=t[0];if(s===null)return!1;if(e==="display"||e==="visibility")return!0;const i=t[t.length-1],a=Uk(s,e),o=Uk(i,e);return!a||!o?!1:eX(t)||(n==="spring"||aB(n))&&r}function kE(t){t.duration=0,t.type="keyframes"}const cB=new Set(["opacity","clipPath","filter","transform"]),nX=/^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/;function rX(t){for(let e=0;e<t.length;e++)if(typeof t[e]=="string"&&nX.test(t[e]))return!0;return!1}const sX=new Set(["color","backgroundColor","outlineColor","fill","stroke","borderColor","borderTopColor","borderRightColor","borderBottomColor","borderLeftColor"]),iX=LU(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function aX(t){var d;const{motionValue:e,name:n,repeatDelay:r,repeatType:s,damping:i,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 iX()&&n&&(cB.has(n)||sX.has(n)&&rX(o))&&(n!=="transform"||!u)&&!c&&!r&&s!=="mirror"&&i!==0&&a!=="inertia"}const oX=40;class lX extends P1{constructor({autoplay:e=!0,delay:n=0,type:r="keyframes",repeat:s=0,repeatDelay:i=0,repeatType:a="loop",keyframes:o,name:l,motionValue:c,element:u,...d}){var m;super(),this.stop=()=>{var g,y;this._animation&&(this._animation.stop(),(g=this.stopTimeline)==null||g.call(this)),(y=this.keyframeResolver)==null||y.cancel()},this.createdAt=us.now();const h={autoplay:e,delay:n,type:r,repeat:s,repeatDelay:i,repeatType:a,name:l,motionValue:c,element:u,...d},f=(u==null?void 0:u.KeyframeResolver)||D1;this.keyframeResolver=new f(o,(g,y,v)=>this.onKeyframesResolved(g,y,h,!v),l,c,u),(m=this.keyframeResolver)==null||m.scheduleResolve()}onKeyframesResolved(e,n,r,s){var v,_;this.keyframeResolver=void 0;const{name:i,type:a,velocity:o,delay:l,isHandoff:c,onUpdate:u}=r;this.resolvedAt=us.now();let d=!0;tX(e,i,a,o)||(d=!1,($l.instantAnimations||!l)&&(u==null||u(jv(e,r,n))),e[0]=e[e.length-1],kE(r),r.repeat=0);const f={startTime:s?this.resolvedAt?this.resolvedAt-this.createdAt>oX?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...r,keyframes:e},m=d&&!c&&aX(f),g=(_=(v=f.motionValue)==null?void 0:v.owner)==null?void 0:_.current;let y;if(m)try{y=new ZY({...f,element:g})}catch{y=new T0(f)}else y=new T0(f);y.finished.then(()=>{this.notifyFinished()}).catch(Ti),this.pendingTimeline&&(this.stopTimeline=y.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=y}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(),HY()),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 uB(t,e,n,r=0,s=1){const i=Array.from(t).sort((c,u)=>c.sortNodePosition(u)).indexOf(e),a=t.size,o=(a-1)*r;return typeof n=="function"?n(i,a):s===1?i*r:o-i*r}const cX=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function uX(t){const e=cX.exec(t);if(!e)return[,];const[,n,r,s]=e;return[`--${n??r}`,s]}function dB(t,e,n=1){const[r,s]=uX(t);if(!r)return;const i=window.getComputedStyle(e).getPropertyValue(r);if(i){const a=i.trim();return RU(a)?parseFloat(a):a}return R1(s)?dB(s,e,n+1):s}const dX={type:"spring",stiffness:500,damping:25,restSpeed:10},hX=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),fX={type:"keyframes",duration:.8},pX={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},mX=(t,{keyframes:e})=>e.length>2?fX:Fh.has(t)?t.startsWith("scale")?hX(e[1]):dX:pX;function hB(t,e){if(t!=null&&t.inherit&&e){const{inherit:n,...r}=t;return{...e,...r}}return t}function O1(t,e){const n=(t==null?void 0:t[e])??(t==null?void 0:t.default)??t;return n!==t?hB(n,t):n}const gX=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function yX(t){for(const e in t)if(!gX.has(e))return!0;return!1}const N1=(t,e,n,r={},s,i)=>a=>{const o=O1(r,t)||{},l=o.delay||r.delay||0;let{elapsed:c=0}=r;c=c-ei(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:i?void 0:s};yX(o)||Object.assign(u,mX(t,u)),u.duration&&(u.duration=ei(u.duration)),u.repeatDelay&&(u.repeatDelay=ei(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(kE(u),u.delay===0&&(d=!0)),($l.instantAnimations||$l.skipAnimations||s!=null&&s.shouldSkipAnimations)&&(d=!0,kE(u),u.delay=0),u.allowFlatten=!o.type&&!o.ease,d&&!i&&e.get()!==void 0){const h=jv(u.keyframes,o);if(h!==void 0){Sn.update(()=>{u.onUpdate(h),u.onComplete()});return}}return o.isSync?new T0(u):new lX(u)};function Bk(t){const e=[{},{}];return t==null||t.values.forEach((n,r)=>{e[0][r]=n.get(),e[1][r]=n.getVelocity()}),e}function M1(t,e,n,r){if(typeof e=="function"){const[s,i]=Bk(r);e=e(n!==void 0?n:t.custom,s,i)}if(typeof e=="string"&&(e=t.variants&&t.variants[e]),typeof e=="function"){const[s,i]=Bk(r);e=e(n!==void 0?n:t.custom,s,i)}return e}function Hc(t,e,n){const r=t.getProps();return M1(r,e,n!==void 0?n:r.custom,t)}const fB=new Set(["width","height","top","left","right","bottom",...Bh]),Fk=30,vX=t=>!isNaN(parseFloat(t));class _X{constructor(e,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const s=us.now();if(this.updatedAt!==s&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(r),this.current!==this.prev&&((i=this.events.change)==null||i.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=us.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=vX(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 w1);const r=this.events[e].add(n);return e==="change"?()=>{r(),Sn.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=us.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Fk)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Fk);return IU(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 ph(t,e){return new _X(t,e)}const LE=t=>Array.isArray(t);function bX(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,ph(n))}function xX(t){return LE(t)?t[t.length-1]||0:t}function SX(t,e){const n=Hc(t,e);let{transitionEnd:r={},transition:s={},...i}=n||{};i={...i,...r};for(const a in i){const o=xX(i[a]);bX(t,a,o)}}const zr=t=>!!(t&&t.getVelocity);function EX(t){return!!(zr(t)&&t.add)}function IE(t,e){const n=t.getValue("willChange");if(EX(n))return n.add(e);if(!n&&$l.WillChange){const r=new $l.WillChange("auto");t.addValue("willChange",r),r.add(e)}}function j1(t){return t.replace(/([A-Z])/g,e=>`-${e.toLowerCase()}`)}const wX="framerAppearId",pB="data-"+j1(wX);function mB(t){return t.props[pB]}function TX({protectedKeys:t,needsAnimating:e},n){const r=t.hasOwnProperty(n)&&e[n]!==!0;return e[n]=!1,r}function gB(t,e,{delay:n=0,transitionOverride:r,type:s}={}){let{transition:i,transitionEnd:a,...o}=e;const l=t.getDefaultTransition();i=i?hB(i,l):l;const c=i==null?void 0:i.reduceMotion;r&&(i=r);const u=[],d=s&&t.animationState&&t.animationState.getState()[s];for(const h in o){const f=t.getValue(h,t.latestValues[h]??null),m=o[h];if(m===void 0||d&&TX(d,h))continue;const g={delay:n,...O1(i||{},h)},y=f.get();if(y!==void 0&&!f.isAnimating()&&!Array.isArray(m)&&m===y&&!g.velocity){Sn.update(()=>f.set(m));continue}let v=!1;if(window.MotionHandoffAnimation){const E=mB(t);if(E){const L=window.MotionHandoffAnimation(E,h,Sn);L!==null&&(g.startTime=L,v=!0)}}IE(t,h);const _=c??t.shouldReduceMotion;f.start(N1(h,f,m,_&&fB.has(h)?{type:!1}:g,t,v));const S=f.animation;S&&u.push(S)}if(a){const h=()=>Sn.update(()=>{a&&SX(t,a)});u.length?Promise.all(u).then(h):h()}return u}function PE(t,e,n={}){var l;const r=Hc(t,e,n.type==="exit"?(l=t.presenceContext)==null?void 0:l.custom:void 0);let{transition:s=t.getDefaultTransition()||{}}=r||{};n.transitionOverride&&(s=n.transitionOverride);const i=r?()=>Promise.all(gB(t,r,n)):()=>Promise.resolve(),a=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:h}=s;return AX(t,e,c,u,d,h,n)}:()=>Promise.resolve(),{when:o}=s;if(o){const[c,u]=o==="beforeChildren"?[i,a]:[a,i];return c().then(()=>u())}else return Promise.all([i(),a(n.delay)])}function AX(t,e,n=0,r=0,s=0,i=1,a){const o=[];for(const l of t.variantChildren)l.notify("AnimationStart",e),o.push(PE(l,e,{...a,delay:n+(typeof r=="function"?0:r)+uB(t.variantChildren,l,r,s,i)}).then(()=>l.notify("AnimationComplete",e)));return Promise.all(o)}function RX(t,e,n={}){t.notify("AnimationStart",e);let r;if(Array.isArray(e)){const s=e.map(i=>PE(t,i,n));r=Promise.all(s)}else if(typeof e=="string")r=PE(t,e,n);else{const s=typeof e=="function"?Hc(t,e,n.custom):e;r=Promise.all(gB(t,s,n))}return r.then(()=>{t.notify("AnimationComplete",e)})}const CX={test:t=>t==="auto",parse:t=>t},yB=t=>e=>e.test(t),vB=[Uh,ut,Ra,zo,eY,ZW,CX],$k=t=>vB.find(yB(t));function kX(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||kU(t):!0}const LX=new Set(["brightness","contrast","saturate","opacity"]);function IX(t){const[e,n]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[r]=n.match(C1)||[];if(!r)return t;const s=n.replace(r,"");let i=LX.has(e)?1:0;return r!==n&&(i*=100),e+"("+i+s+")"}const PX=/\b([a-z-]*)\(.*?\)/gu,DE={...zi,getAnimatableNone:t=>{const e=t.match(PX);return e?e.map(IX).join(" "):t}},OE={...zi,getAnimatableNone:t=>{const e=zi.parse(t);return zi.createTransformer(t)(e.map(r=>typeof r=="number"?0:typeof r=="object"?{...r,alpha:1}:r))}},Vk={...Uh,transform:Math.round},DX={rotate:zo,rotateX:zo,rotateY:zo,rotateZ:zo,scale:gg,scaleX:gg,scaleY:gg,scaleZ:gg,skew:zo,skewX:zo,skewY:zo,distance:ut,translateX:ut,translateY:ut,translateZ:ut,x:ut,y:ut,z:ut,perspective:ut,transformPerspective:ut,opacity:Rp,originX:Ck,originY:Ck,originZ:ut},U1={borderWidth:ut,borderTopWidth:ut,borderRightWidth:ut,borderBottomWidth:ut,borderLeftWidth:ut,borderRadius:ut,borderTopLeftRadius:ut,borderTopRightRadius:ut,borderBottomRightRadius:ut,borderBottomLeftRadius:ut,width:ut,maxWidth:ut,height:ut,maxHeight:ut,top:ut,right:ut,bottom:ut,left:ut,inset:ut,insetBlock:ut,insetBlockStart:ut,insetBlockEnd:ut,insetInline:ut,insetInlineStart:ut,insetInlineEnd:ut,padding:ut,paddingTop:ut,paddingRight:ut,paddingBottom:ut,paddingLeft:ut,paddingBlock:ut,paddingBlockStart:ut,paddingBlockEnd:ut,paddingInline:ut,paddingInlineStart:ut,paddingInlineEnd:ut,margin:ut,marginTop:ut,marginRight:ut,marginBottom:ut,marginLeft:ut,marginBlock:ut,marginBlockStart:ut,marginBlockEnd:ut,marginInline:ut,marginInlineStart:ut,marginInlineEnd:ut,fontSize:ut,backgroundPositionX:ut,backgroundPositionY:ut,...DX,zIndex:Vk,fillOpacity:Rp,strokeOpacity:Rp,numOctaves:Vk},OX={...U1,color:dr,backgroundColor:dr,outlineColor:dr,fill:dr,stroke:dr,borderColor:dr,borderTopColor:dr,borderRightColor:dr,borderBottomColor:dr,borderLeftColor:dr,filter:DE,WebkitFilter:DE,mask:OE,WebkitMask:OE},_B=t=>OX[t],NX=new Set([DE,OE]);function bB(t,e){let n=_B(t);return NX.has(n)||(n=zi),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const MX=new Set(["auto","none","0"]);function jX(t,e,n){let r=0,s;for(;r<t.length&&!s;){const i=t[r];typeof i=="string"&&!MX.has(i)&&fh(i).values.length&&(s=t[r]),r++}if(s&&n)for(const i of e)t[i]=bB(n,s)}class UX extends D1{constructor(e,n,r,s,i){super(e,n,r,s,i,!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(),R1(d))){const h=dB(d,n.current);h!==void 0&&(e[u]=h),u===e.length-1&&(this.finalKeyframe=d)}}if(this.resolveNoneKeyframes(),!fB.has(r)||e.length!==2)return;const[s,i]=e,a=$k(s),o=$k(i),l=Rk(s),c=Rk(i);if(l!==c&&xl[r]){this.needsMeasurement=!0;return}if(a!==o)if(Mk(a)&&Mk(o))for(let u=0;u<e.length;u++){const d=e[u];typeof d=="string"&&(e[u]=parseFloat(d))}else xl[r]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:n}=this,r=[];for(let s=0;s<e.length;s++)(e[s]===null||kX(e[s]))&&r.push(s);r.length&&jX(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=xl[r](e.measureViewportBox(),window.getComputedStyle(e.current)),n[0]=this.measuredOrigin;const s=n[n.length-1];s!==void 0&&e.getValue(r,s).jump(s,!1)}measureEndState(){var o;const{element:e,name:n,unresolvedKeyframes:r}=this;if(!e||!e.current)return;const s=e.getValue(n);s&&s.jump(this.measuredOrigin,!1);const i=r.length-1,a=r[i];r[i]=xl[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 xB(t,e,n){if(t==null)return[];if(t instanceof EventTarget)return[t];if(typeof t=="string"){let r=document;const s=(n==null?void 0:n[t])??r.querySelectorAll(t);return s?Array.from(s):[]}return Array.from(t).filter(r=>r!=null)}const SB=(t,e)=>e&&typeof t=="number"?e.transform(t):t;function yy(t){return CU(t)&&"offsetHeight"in t&&!("ownerSVGElement"in t)}const{schedule:B1}=VU(queueMicrotask,!1),ji={x:!1,y:!1};function EB(){return ji.x||ji.y}function BX(t){return t==="x"||t==="y"?ji[t]?null:(ji[t]=!0,()=>{ji[t]=!1}):ji.x||ji.y?null:(ji.x=ji.y=!0,()=>{ji.x=ji.y=!1})}function wB(t,e){const n=xB(t),r=new AbortController,s={passive:!0,...e,signal:r.signal};return[n,s,()=>r.abort()]}function FX(t){return!(t.pointerType==="touch"||EB())}function $X(t,e,n={}){const[r,s,i]=wB(t,n);return r.forEach(a=>{let o=!1,l=!1,c;const u=()=>{a.removeEventListener("pointerleave",m)},d=y=>{c&&(c(y),c=void 0),u()},h=y=>{o=!1,window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",h),l&&(l=!1,d(y))},f=()=>{o=!0,window.addEventListener("pointerup",h,s),window.addEventListener("pointercancel",h,s)},m=y=>{if(y.pointerType!=="touch"){if(o){l=!0;return}d(y)}},g=y=>{if(!FX(y))return;l=!1;const v=e(a,y);typeof v=="function"&&(c=v,a.addEventListener("pointerleave",m,s))};a.addEventListener("pointerenter",g,s),a.addEventListener("pointerdown",f,s)}),i}const TB=(t,e)=>e?t===e?!0:TB(t,e.parentElement):!1,F1=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,VX=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function GX(t){return VX.has(t.tagName)||t.isContentEditable===!0}const KX=new Set(["INPUT","SELECT","TEXTAREA"]);function HX(t){return KX.has(t.tagName)||t.isContentEditable===!0}const vy=new WeakSet;function Gk(t){return e=>{e.key==="Enter"&&t(e)}}function Ab(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const zX=(t,e)=>{const n=t.currentTarget;if(!n)return;const r=Gk(()=>{if(vy.has(n))return;Ab(n,"down");const s=Gk(()=>{Ab(n,"up")}),i=()=>Ab(n,"cancel");n.addEventListener("keyup",s,e),n.addEventListener("blur",i,e)});n.addEventListener("keydown",r,e),n.addEventListener("blur",()=>n.removeEventListener("keydown",r),e)};function Kk(t){return F1(t)&&!EB()}const Hk=new WeakSet;function qX(t,e,n={}){const[r,s,i]=wB(t,n),a=o=>{const l=o.currentTarget;if(!Kk(o)||Hk.has(o))return;vy.add(l),n.stopPropagation&&Hk.add(o);const c=e(l,o),u=(f,m)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",h),vy.has(l)&&vy.delete(l),Kk(f)&&typeof c=="function"&&c(f,{success:m})},d=f=>{u(f,l===window||l===document||n.useGlobalTarget||TB(l,f.target))},h=f=>{u(f,!1)};window.addEventListener("pointerup",d,s),window.addEventListener("pointercancel",h,s)};return r.forEach(o=>{(n.useGlobalTarget?window:o).addEventListener("pointerdown",a,s),yy(o)&&(o.addEventListener("focus",c=>zX(c,s)),!GX(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function $1(t){return CU(t)&&"ownerSVGElement"in t}const _y=new WeakMap;let qo;const AB=(t,e,n)=>(r,s)=>s&&s[0]?s[0][t+"Size"]:$1(r)&&"getBBox"in r?r.getBBox()[e]:r[n],WX=AB("inline","width","offsetWidth"),YX=AB("block","height","offsetHeight");function XX({target:t,borderBoxSize:e}){var n;(n=_y.get(t))==null||n.forEach(r=>{r(t,{get width(){return WX(t,e)},get height(){return YX(t,e)}})})}function QX(t){t.forEach(XX)}function JX(){typeof ResizeObserver>"u"||(qo=new ResizeObserver(QX))}function ZX(t,e){qo||JX();const n=xB(t);return n.forEach(r=>{let s=_y.get(r);s||(s=new Set,_y.set(r,s)),s.add(e),qo==null||qo.observe(r)}),()=>{n.forEach(r=>{const s=_y.get(r);s==null||s.delete(e),s!=null&&s.size||qo==null||qo.unobserve(r)})}}const by=new Set;let gd;function eQ(){gd=()=>{const t={get width(){return window.innerWidth},get height(){return window.innerHeight}};by.forEach(e=>e(t))},window.addEventListener("resize",gd)}function tQ(t){return by.add(t),gd||eQ(),()=>{by.delete(t),!by.size&&typeof gd=="function"&&(window.removeEventListener("resize",gd),gd=void 0)}}function zk(t,e){return typeof t=="function"?tQ(t):ZX(t,e)}function nQ(t){return $1(t)&&t.tagName==="svg"}const rQ=[...vB,dr,zi],sQ=t=>rQ.find(yB(t)),qk=()=>({translate:0,scale:1,origin:0,originPoint:0}),yd=()=>({x:qk(),y:qk()}),Wk=()=>({min:0,max:0}),vr=()=>({x:Wk(),y:Wk()}),iQ=new WeakMap;function Uv(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Cp(t){return typeof t=="string"||Array.isArray(t)}const V1=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],G1=["initial",...V1];function Bv(t){return Uv(t.animate)||G1.some(e=>Cp(t[e]))}function RB(t){return!!(Bv(t)||t.variants)}function aQ(t,e,n){for(const r in e){const s=e[r],i=n[r];if(zr(s))t.addValue(r,s);else if(zr(i))t.addValue(r,ph(s,{owner:t}));else if(i!==s)if(t.hasValue(r)){const a=t.getValue(r);a.liveStyle===!0?a.jump(s):a.hasAnimated||a.set(s)}else{const a=t.getStaticValue(r);t.addValue(r,ph(a!==void 0?a:s,{owner:t}))}}for(const r in n)e[r]===void 0&&t.removeValue(r);return e}const NE={current:null},CB={current:!1},oQ=typeof window<"u";function lQ(){if(CB.current=!0,!!oQ)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>NE.current=t.matches;t.addEventListener("change",e),e()}else NE.current=!1}const Yk=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let A0={};function kB(t){A0=t}function cQ(){return A0}class uQ{scrapeMotionValuesFromProps(e,n,r){return{}}constructor({parent:e,props:n,presenceContext:r,reducedMotionConfig:s,skipAnimations:i,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=D1,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=us.now();this.renderScheduledAt<f&&(this.renderScheduledAt=f,Sn.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=s,this.skipAnimationsConfig=i,this.options=l,this.blockInitialAnimation=!!a,this.isControllingVariants=Bv(n),this.isVariantNode=RB(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 m=h[f];c[f]!==void 0&&zr(m)&&m.set(c[f])}}mount(e){var n,r;if(this.hasBeenMounted)for(const s in this.initialValues)(n=this.values.get(s))==null||n.jump(this.initialValues[s]),this.latestValues[s]=this.initialValues[s];this.current=e,iQ.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((s,i)=>this.bindToMotionValue(i,s)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(CB.current||lQ(),this.shouldReduceMotion=NE.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(),Vl(this.notifyUpdate),Vl(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&&cB.has(e)&&this.current instanceof HTMLElement){const{factory:a,keyframes:o,times:l,ease:c,duration:u}=n.accelerate,d=new oB({element:this.current,name:e,keyframes:o,times:l,ease:c,duration:ei(u)}),h=a(d);this.valueSubscriptions.set(e,()=>{h(),d.cancel()});return}const r=Fh.has(e);r&&this.onBindTransform&&this.onBindTransform();const s=n.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&Sn.preRender(this.notifyUpdate),r&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let i;typeof window<"u"&&window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,e,n)),this.valueSubscriptions.set(e,()=>{s(),i&&i(),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 A0){const n=A0[e];if(!n)continue;const{isEnabled:r,Feature:s}=n;if(!this.features[e]&&s&&r(this.props)&&(this.features[e]=new s(this)),this.features[e]){const i=this.features[e];i.isMounted?i.update():(i.mount(),i.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):vr()}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<Yk.length;r++){const s=Yk[r];this.propEventSubscriptions[s]&&(this.propEventSubscriptions[s](),delete this.propEventSubscriptions[s]);const i="on"+s,a=e[i];a&&(this.propEventSubscriptions[s]=this.on(s,a))}this.prevMotionValues=aQ(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=ph(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"&&(RU(r)||kU(r))?r=parseFloat(r):!sQ(r)&&zi.test(n)&&(r=bB(e,n)),this.setBaseTarget(e,zr(r)?r.get():r)),zr(r)?r.get():r}setBaseTarget(e,n){this.baseTarget[e]=n}getBaseTarget(e){var i;const{initial:n}=this.props;let r;if(typeof n=="string"||typeof n=="object"){const a=M1(this.props,n,(i=this.presenceContext)==null?void 0:i.custom);a&&(r=a[e])}if(n&&r!==void 0)return r;const s=this.getBaseTargetFromProps(this.props,e);return s!==void 0&&!zr(s)?s:this.initialValues[e]!==void 0&&r===void 0?void 0:this.baseTarget[e]}on(e,n){return this.events[e]||(this.events[e]=new w1),this.events[e].add(n)}notify(e,...n){this.events[e]&&this.events[e].notify(...n)}scheduleRenderMicrotask(){B1.render(this.render)}}class LB extends uQ{constructor(){super(...arguments),this.KeyframeResolver=UX}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;zr(e)&&(this.childSubscription=e.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}class Ql{constructor(e){this.isMounted=!1,this.node=e}update(){}}function IB({top:t,left:e,right:n,bottom:r}){return{x:{min:e,max:n},y:{min:t,max:r}}}function dQ({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function hQ(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 Rb(t){return t===void 0||t===1}function ME({scale:t,scaleX:e,scaleY:n}){return!Rb(t)||!Rb(e)||!Rb(n)}function mc(t){return ME(t)||PB(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function PB(t){return Xk(t.x)||Xk(t.y)}function Xk(t){return t&&t!=="0%"}function R0(t,e,n){const r=t-n,s=e*r;return n+s}function Qk(t,e,n,r,s){return s!==void 0&&(t=R0(t,s,r)),R0(t,n,r)+e}function jE(t,e=0,n=1,r,s){t.min=Qk(t.min,e,n,r,s),t.max=Qk(t.max,e,n,r,s)}function DB(t,{x:e,y:n}){jE(t.x,e.translate,e.scale,e.originPoint),jE(t.y,n.translate,n.scale,n.originPoint)}const Jk=.999999999999,Zk=1.0000000000001;function fQ(t,e,n,r=!1){var o;const s=n.length;if(!s)return;e.x=e.y=1;let i,a;for(let l=0;l<s;l++){i=n[l],a=i.projectionDelta;const{visualElement:c}=i.options;c&&c.props.style&&c.props.style.display==="contents"||(r&&i.options.layoutScroll&&i.scroll&&i!==i.root&&(ha(t.x,-i.scroll.offset.x),ha(t.y,-i.scroll.offset.y)),a&&(e.x*=a.x.scale,e.y*=a.y.scale,DB(t,a)),r&&mc(i.latestValues)&&xy(t,i.latestValues,(o=i.layout)==null?void 0:o.layoutBox))}e.x<Zk&&e.x>Jk&&(e.x=1),e.y<Zk&&e.y>Jk&&(e.y=1)}function ha(t,e){t.min+=e,t.max+=e}function eL(t,e,n,r,s=.5){const i=In(t.min,t.max,s);jE(t,e,n,i,r)}function tL(t,e){return typeof t=="string"?parseFloat(t)/100*(e.max-e.min):t}function xy(t,e,n){const r=n??t;eL(t.x,tL(e.x,r.x),e.scaleX,e.scale,e.originX),eL(t.y,tL(e.y,r.y),e.scaleY,e.scale,e.originY)}function OB(t,e){return IB(hQ(t.getBoundingClientRect(),e))}function pQ(t,e,n){const r=OB(t,n),{scroll:s}=e;return s&&(ha(r.x,s.offset.x),ha(r.y,s.offset.y)),r}const mQ={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},gQ=Bh.length;function yQ(t,e,n){let r="",s=!0;for(let i=0;i<gQ;i++){const a=Bh[i],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=SB(o,U1[a]);if(!l){s=!1;const u=mQ[a]||a;r+=`${u}(${c}) `}n&&(e[a]=c)}}return r=r.trim(),n?r=n(e,s?"":r):s&&(r="none"),r}function K1(t,e,n){const{style:r,vars:s,transformOrigin:i}=t;let a=!1,o=!1;for(const l in e){const c=e[l];if(Fh.has(l)){a=!0;continue}else if(KU(l)){s[l]=c;continue}else{const u=SB(c,U1[l]);l.startsWith("origin")?(o=!0,i[l]=u):r[l]=u}}if(e.transform||(a||n?r.transform=yQ(e,t.transform,n):r.transform&&(r.transform="none")),o){const{originX:l="50%",originY:c="50%",originZ:u=0}=i;r.transformOrigin=`${l} ${c} ${u}`}}function NB(t,{style:e,vars:n},r,s){const i=t.style;let a;for(a in e)i[a]=e[a];s==null||s.applyProjectionStyles(i,r);for(a in n)i.setProperty(a,n[a])}function nL(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const cf={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(ut.test(t))t=parseFloat(t);else return t;const n=nL(t,e.target.x),r=nL(t,e.target.y);return`${n}% ${r}%`}},vQ={correct:(t,{treeScale:e,projectionDelta:n})=>{const r=t,s=zi.parse(t);if(s.length>5)return r;const i=zi.createTransformer(t),a=typeof s[0]!="number"?1:0,o=n.x.scale*e.x,l=n.y.scale*e.y;s[0+a]/=o,s[1+a]/=l;const c=In(o,l,.5);return typeof s[2+a]=="number"&&(s[2+a]/=c),typeof s[3+a]=="number"&&(s[3+a]/=c),i(s)}},UE={borderRadius:{...cf,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:cf,borderTopRightRadius:cf,borderBottomLeftRadius:cf,borderBottomRightRadius:cf,boxShadow:vQ};function MB(t,{layout:e,layoutId:n}){return Fh.has(t)||t.startsWith("origin")||(e||n!==void 0)&&(!!UE[t]||t==="opacity")}function H1(t,e,n){var a;const r=t.style,s=e==null?void 0:e.style,i={};if(!r)return i;for(const o in r)(zr(r[o])||s&&zr(s[o])||MB(o,t)||((a=n==null?void 0:n.getValue(o))==null?void 0:a.liveStyle)!==void 0)&&(i[o]=r[o]);return i}function _Q(t){return window.getComputedStyle(t)}class bQ extends LB{constructor(){super(...arguments),this.type="html",this.renderInstance=NB}readValueFromInstance(e,n){var r;if(Fh.has(n))return(r=this.projection)!=null&&r.isProjecting?wE(n):FY(e,n);{const s=_Q(e),i=(KU(n)?s.getPropertyValue(n):s[n])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(e,{transformPagePoint:n}){return OB(e,n)}build(e,n,r){K1(e,n,r.transformTemplate)}scrapeMotionValuesFromProps(e,n,r){return H1(e,n,r)}}const xQ={offset:"stroke-dashoffset",array:"stroke-dasharray"},SQ={offset:"strokeDashoffset",array:"strokeDasharray"};function EQ(t,e,n=1,r=0,s=!0){t.pathLength=1;const i=s?xQ:SQ;t[i.offset]=`${-r}`,t[i.array]=`${e} ${n}`}const wQ=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function jB(t,{attrX:e,attrY:n,attrScale:r,pathLength:s,pathSpacing:i=1,pathOffset:a=0,...o},l,c,u){if(K1(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 wQ)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),s!==void 0&&EQ(d,s,i,a,!1)}const UB=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"]),BB=t=>typeof t=="string"&&t.toLowerCase()==="svg";function TQ(t,e,n,r){NB(t,e,void 0,r);for(const s in e.attrs)t.setAttribute(UB.has(s)?s:j1(s),e.attrs[s])}function FB(t,e,n){const r=H1(t,e,n);for(const s in t)if(zr(t[s])||zr(e[s])){const i=Bh.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;r[i]=t[s]}return r}class AQ extends LB{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=vr}getBaseTargetFromProps(e,n){return e[n]}readValueFromInstance(e,n){if(Fh.has(n)){const r=_B(n);return r&&r.default||0}return n=UB.has(n)?n:j1(n),e.getAttribute(n)}scrapeMotionValuesFromProps(e,n,r){return FB(e,n,r)}build(e,n,r){jB(e,n,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(e,n,r,s){TQ(e,n,r,s)}mount(e){this.isSVGTag=BB(e.tagName),super.mount(e)}}const RQ=G1.length;function $B(t){if(!t)return;if(!t.isControllingVariants){const n=t.parent?$B(t.parent)||{}:{};return t.props.initial!==void 0&&(n.initial=t.props.initial),n}const e={};for(let n=0;n<RQ;n++){const r=G1[n],s=t.props[r];(Cp(s)||s===!1)&&(e[r]=s)}return e}function VB(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 CQ=[...V1].reverse(),kQ=V1.length;function LQ(t){return e=>Promise.all(e.map(({animation:n,options:r})=>RX(t,n,r)))}function IQ(t){let e=LQ(t),n=rL(),r=!0,s=!1;const i=c=>(u,d)=>{var f;const h=Hc(t,d,c==="exit"?(f=t.presenceContext)==null?void 0:f.custom:void 0);if(h){const{transition:m,transitionEnd:g,...y}=h;u={...u,...y,...g}}return u};function a(c){e=c(t)}function o(c){const{props:u}=t,d=$B(t.parent)||{},h=[],f=new Set;let m={},g=1/0;for(let v=0;v<kQ;v++){const _=CQ[v],S=n[_],E=u[_]!==void 0?u[_]:d[_],L=Cp(E),U=_===c?S.isActive:null;U===!1&&(g=v);let P=E===d[_]&&E!==u[_]&&L;if(P&&(r||s)&&t.manuallyAnimateOnMount&&(P=!1),S.protectedKeys={...m},!S.isActive&&U===null||!E&&!S.prevProp||Uv(E)||typeof E=="boolean")continue;if(_==="exit"&&S.isActive&&U!==!0){S.prevResolvedValues&&(m={...m,...S.prevResolvedValues});continue}const I=PQ(S.prevProp,E);let k=I||_===c&&S.isActive&&!P&&L||v>g&&L,R=!1;const M=Array.isArray(E)?E:[E];let G=M.reduce(i(_),{});U===!1&&(G={});const{prevResolvedValues:Y={}}=S,q={...Y,...G},X=ne=>{k=!0,f.has(ne)&&(R=!0,f.delete(ne)),S.needsAnimating[ne]=!0;const H=t.getValue(ne);H&&(H.liveStyle=!1)};for(const ne in q){const H=G[ne],K=Y[ne];if(m.hasOwnProperty(ne))continue;let J=!1;LE(H)&&LE(K)?J=!VB(H,K):J=H!==K,J?H!=null?X(ne):f.add(ne):H!==void 0&&f.has(ne)?X(ne):S.protectedKeys[ne]=!0}S.prevProp=E,S.prevResolvedValues=G,S.isActive&&(m={...m,...G}),(r||s)&&t.blockInitialAnimation&&(k=!1);const Z=P&&I;k&&(!Z||R)&&h.push(...M.map(ne=>{const H={type:_};if(typeof ne=="string"&&(r||s)&&!Z&&t.manuallyAnimateOnMount&&t.parent){const{parent:K}=t,J=Hc(K,ne);if(K.enteringChildren&&J){const{delayChildren:Q}=J.transition||{};H.delay=uB(K.enteringChildren,t,Q)}}return{animation:ne,options:H}}))}if(f.size){const v={};if(typeof u.initial!="boolean"){const _=Hc(t,Array.isArray(u.initial)?u.initial[0]:u.initial);_&&_.transition&&(v.transition=_.transition)}f.forEach(_=>{const S=t.getBaseTarget(_),E=t.getValue(_);E&&(E.liveStyle=!0),v[_]=S??null}),h.push({animation:v})}let y=!!h.length;return r&&(u.initial===!1||u.initial===u.animate)&&!t.manuallyAnimateOnMount&&(y=!1),r=!1,s=!1,y?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 m;return(m=f.animationState)==null?void 0:m.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=rL(),s=!0}}}function PQ(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!VB(e,t):!1}function ic(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function rL(){return{animate:ic(!0),whileInView:ic(),whileHover:ic(),whileTap:ic(),whileDrag:ic(),whileFocus:ic(),exit:ic()}}function BE(t,e){t.min=e.min,t.max=e.max}function Ni(t,e){BE(t.x,e.x),BE(t.y,e.y)}function sL(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}const GB=1e-4,DQ=1-GB,OQ=1+GB,KB=.01,NQ=0-KB,MQ=0+KB;function ds(t){return t.max-t.min}function jQ(t,e,n){return Math.abs(t-e)<=n}function iL(t,e,n,r=.5){t.origin=r,t.originPoint=In(e.min,e.max,t.origin),t.scale=ds(n)/ds(e),t.translate=In(n.min,n.max,t.origin)-t.originPoint,(t.scale>=DQ&&t.scale<=OQ||isNaN(t.scale))&&(t.scale=1),(t.translate>=NQ&&t.translate<=MQ||isNaN(t.translate))&&(t.translate=0)}function zf(t,e,n,r){iL(t.x,e.x,n.x,r?r.originX:void 0),iL(t.y,e.y,n.y,r?r.originY:void 0)}function aL(t,e,n,r=0){const s=r?In(n.min,n.max,r):n.min;t.min=s+e.min,t.max=t.min+ds(e)}function UQ(t,e,n,r){aL(t.x,e.x,n.x,r==null?void 0:r.x),aL(t.y,e.y,n.y,r==null?void 0:r.y)}function oL(t,e,n,r=0){const s=r?In(n.min,n.max,r):n.min;t.min=e.min-s,t.max=t.min+ds(e)}function C0(t,e,n,r){oL(t.x,e.x,n.x,r==null?void 0:r.x),oL(t.y,e.y,n.y,r==null?void 0:r.y)}function lL(t,e,n,r,s){return t-=e,t=R0(t,1/n,r),s!==void 0&&(t=R0(t,1/s,r)),t}function BQ(t,e=0,n=1,r=.5,s,i=t,a=t){if(Ra.test(e)&&(e=parseFloat(e),e=In(a.min,a.max,e/100)-a.min),typeof e!="number")return;let o=In(i.min,i.max,r);t===i&&(o-=e),t.min=lL(t.min,e,n,o,s),t.max=lL(t.max,e,n,o,s)}function cL(t,e,[n,r,s],i,a){BQ(t,e[n],e[r],e[s],e.scale,i,a)}const FQ=["x","scaleX","originX"],$Q=["y","scaleY","originY"];function uL(t,e,n,r){cL(t.x,e,FQ,n?n.x:void 0,r?r.x:void 0),cL(t.y,e,$Q,n?n.y:void 0,r?r.y:void 0)}function dL(t){return t.translate===0&&t.scale===1}function HB(t){return dL(t.x)&&dL(t.y)}function hL(t,e){return t.min===e.min&&t.max===e.max}function VQ(t,e){return hL(t.x,e.x)&&hL(t.y,e.y)}function fL(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function zB(t,e){return fL(t.x,e.x)&&fL(t.y,e.y)}function pL(t){return ds(t.x)/ds(t.y)}function mL(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}function aa(t){return[t("x"),t("y")]}function GQ(t,e,n){let r="";const s=t.x.translate/e.x,i=t.y.translate/e.y,a=(n==null?void 0:n.z)||0;if((s||i||a)&&(r=`translate3d(${s}px, ${i}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:m}=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) `),m&&(r+=`skewY(${m}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 qB=["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],KQ=qB.length,gL=t=>typeof t=="string"?parseFloat(t):t,yL=t=>typeof t=="number"||ut.test(t);function HQ(t,e,n,r,s,i){s?(t.opacity=In(0,n.opacity??1,zQ(r)),t.opacityExit=In(e.opacity??1,0,qQ(r))):i&&(t.opacity=In(e.opacity??1,n.opacity??1,r));for(let a=0;a<KQ;a++){const o=qB[a];let l=vL(e,o),c=vL(n,o);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||yL(l)===yL(c)?(t[o]=Math.max(In(gL(l),gL(c),r),0),(Ra.test(c)||Ra.test(l))&&(t[o]+="%")):t[o]=c}(e.rotate||n.rotate)&&(t.rotate=In(e.rotate||0,n.rotate||0,r))}function vL(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const zQ=WB(0,.5,UU),qQ=WB(.5,.95,Ti);function WB(t,e,n){return r=>r<t?0:r>e?1:n(Ap(t,e,r))}function WQ(t,e,n){const r=zr(t)?t:ph(t);return r.start(N1("",r,e,n)),r.animation}function kp(t,e,n,r={passive:!0}){return t.addEventListener(e,n,r),()=>t.removeEventListener(e,n)}const YQ=(t,e)=>t.depth-e.depth;class XQ{constructor(){this.children=[],this.isDirty=!1}add(e){S1(this.children,e),this.isDirty=!0}remove(e){x0(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(YQ),this.isDirty=!1,this.children.forEach(e)}}function QQ(t,e){const n=us.now(),r=({timestamp:s})=>{const i=s-n;i>=e&&(Vl(r),t(i-e))};return Sn.setup(r,!0),()=>Vl(r)}function Sy(t){return zr(t)?t.get():t}class JQ{constructor(){this.members=[]}add(e){S1(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 s=r.instance;(!s||s.isConnected===!1)&&!r.snapshot&&(x0(this.members,r),r.unmount())}e.scheduleRender()}remove(e){if(x0(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 s=this.members[r];if(s.isPresent!==!1&&((n=s.instance)==null?void 0:n.isConnected)!==!1)return this.promote(s),!0}return!1}promote(e,n){var s;const r=this.lead;if(e!==r&&(this.prevLead=r,this.lead=e,e.show(),r)){r.updateSnapshot(),e.scheduleRender();const{layoutDependency:i}=r.options,{layoutDependency:a}=e.options;(i===void 0||i!==a)&&(e.resumeFrom=r,n&&(r.preserveOpacity=!0),r.snapshot&&(e.snapshot=r.snapshot,e.snapshot.latestValues=r.animationValues||r.latestValues),(s=e.root)!=null&&s.isUpdating&&(e.isLayoutDirty=!0)),e.options.crossfade===!1&&r.hide()}}exitAnimationComplete(){this.members.forEach(e=>{var n,r,s,i,a;(r=(n=e.options).onExitComplete)==null||r.call(n),(a=(s=e.resumingFrom)==null?void 0:(i=s.options).onExitComplete)==null||a.call(i)})}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 Ey={hasAnimatedSinceResize:!0,hasEverUpdated:!1},Cb=["","X","Y","Z"],ZQ=1e3;let eJ=0;function kb(t,e,n,r){const{latestValues:s}=e;s[t]&&(n[t]=s[t],e.setStaticValue(t,0),r&&(r[t]=0))}function YB(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const n=mB(e);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:s,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(n,"transform",Sn,!(s||i))}const{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&YB(r)}function XB({attachResizeListener:t,defaultParent:e,measureScroll:n,checkIsScrollRoot:r,resetTransform:s}){return class{constructor(a={},o=e==null?void 0:e()){this.id=eJ++,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(rJ),this.nodes.forEach(cJ),this.nodes.forEach(uJ),this.nodes.forEach(sJ)},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 XQ)}addEventListener(a,o){return this.eventHandlers.has(a)||this.eventHandlers.set(a,new w1),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=$1(a)&&!nQ(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;Sn.read(()=>{d=window.innerWidth}),t(a,()=>{const f=window.innerWidth;f!==d&&(d=f,this.root.updateBlockedByResize=!0,u&&u(),u=QQ(h,250),Ey.hasAnimatedSinceResize&&(Ey.hasAnimatedSinceResize=!1,this.nodes.forEach(xL)))})}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 m=this.options.transition||c.getDefaultTransition()||mJ,{onLayoutAnimationStart:g,onLayoutAnimationComplete:y}=c.getProps(),v=!this.targetLayout||!zB(this.targetLayout,f),_=!d&&h;if(this.options.layoutRoot||this.resumeFrom||_||d&&(v||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const S={...O1(m,"layout"),onPlay:g,onComplete:y};(c.shouldReduceMotion||this.options.layoutRoot)&&(S.delay=0,S.type=!1),this.startAnimation(S),this.setAnimationOrigin(u,_)}else d||xL(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(),Vl(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(dJ),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&&YB(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(aJ),this.nodes.forEach(_L);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(bL);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(oJ),this.nodes.forEach(lJ),this.nodes.forEach(tJ),this.nodes.forEach(nJ)):this.nodes.forEach(bL),this.clearAllSnapshots();const o=us.now();Br.delta=ka(0,1e3/60,o-Br.timestamp),Br.timestamp=o,Br.isProcessing=!0,bb.update.process(Br),bb.preRender.process(Br),bb.render.process(Br),Br.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,B1.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(iJ),this.sharedNodes.forEach(hJ)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,Sn.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){Sn.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!ds(this.snapshot.measuredBox.x)&&!ds(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=vr()),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(!s)return;const a=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,o=this.projectionDelta&&!HB(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,u=c!==this.prevTransformTemplateValue;a&&this.instance&&(o||mc(this.latestValues)||u)&&(s(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)),gJ(l),{animationId:this.root.animationId,measuredBox:o,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){var c;const{visualElement:a}=this.options;if(!a)return vr();const o=a.measureViewportBox();if(!(((c=this.scroll)==null?void 0:c.wasRoot)||this.path.some(yJ))){const{scroll:u}=this.root;u&&(ha(o.x,u.offset.x),ha(o.y,u.offset.y))}return o}removeElementScroll(a){var l;const o=vr();if(Ni(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&&Ni(o,a),ha(o.x,d.offset.x),ha(o.y,d.offset.y))}return o}applyTransform(a,o=!1,l){var u,d;const c=l||vr();Ni(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&&(ha(c.x,-f.scroll.offset.x),ha(c.y,-f.scroll.offset.y)),mc(f.latestValues)&&xy(c,f.latestValues,(u=f.layout)==null?void 0:u.layoutBox)}return mc(this.latestValues)&&xy(c,this.latestValues,(d=this.layout)==null?void 0:d.layoutBox),c}removeTransform(a){var l;const o=vr();Ni(o,a);for(let c=0;c<this.path.length;c++){const u=this.path[c];if(!mc(u.latestValues))continue;let d;u.instance&&(ME(u.latestValues)&&u.updateSnapshot(),d=vr(),Ni(d,u.measurePageBox())),uL(o,u.latestValues,(l=u.snapshot)==null?void 0:l.layoutBox,d)}return mc(this.latestValues)&&uL(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!==Br.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=Br.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=vr(),this.targetWithTransforms=vr()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),UQ(this.target,this.relativeTarget,this.relativeParent.target,this.options.layoutAnchor||void 0)):this.targetDelta?(this.resumingFrom?this.applyTransform(this.layout.layoutBox,!1,this.target):Ni(this.target,this.layout.layoutBox),DB(this.target,this.targetDelta)):Ni(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||ME(this.parent.latestValues)||PB(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=vr(),this.relativeTargetOrigin=vr(),C0(this.relativeTargetOrigin,o,l,this.options.layoutAnchor||void 0),Ni(this.relativeTarget,this.relativeTargetOrigin)}removeRelativeTarget(){this.relativeParent=this.relativeTarget=void 0}calcProjection(){var m;const a=this.getLead(),o=!!this.resumingFrom||this!==a;let l=!0;if((this.isProjectionDirty||(m=this.parent)!=null&&m.isProjectionDirty)&&(l=!1),o&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(l=!1),this.resolvedRelativeTargetAt===Br.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;Ni(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,h=this.treeScale.y;fQ(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=vr());const{target:f}=a;if(!f){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(sL(this.prevProjectionDelta.x,this.projectionDelta.x),sL(this.prevProjectionDelta.y,this.projectionDelta.y)),zf(this.projectionDelta,this.layoutCorrected,f,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==h||!mL(this.projectionDelta.x,this.prevProjectionDelta.x)||!mL(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=yd(),this.projectionDelta=yd(),this.projectionDeltaWithTransform=yd()}setAnimationOrigin(a,o=!1){const l=this.snapshot,c=l?l.latestValues:{},u={...this.latestValues},d=yd();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!o;const h=vr(),f=l?l.source:void 0,m=this.layout?this.layout.source:void 0,g=f!==m,y=this.getStack(),v=!y||y.members.length<=1,_=!!(g&&!v&&this.options.crossfade===!0&&!this.path.some(pJ));this.animationProgress=0;let S;this.mixTargetDelta=E=>{const L=E/1e3;SL(d.x,a.x,L),SL(d.y,a.y,L),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(C0(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),fJ(this.relativeTarget,this.relativeTargetOrigin,h,L),S&&VQ(this.relativeTarget,S)&&(this.isProjectionDirty=!1),S||(S=vr()),Ni(S,this.relativeTarget)),g&&(this.animationValues=u,HQ(u,c,this.latestValues,L,_,v)),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&&(Vl(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Sn.update(()=>{Ey.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=ph(0)),this.motionValue.jump(0,!1),this.currentAnimation=WQ(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(ZQ),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&&QB(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||vr();const d=ds(this.layout.layoutBox.x);l.x.min=a.target.x.min,l.x.max=l.x.min+d;const h=ds(this.layout.layoutBox.y);l.y.min=a.target.y.min,l.y.max=l.y.min+h}Ni(o,l),xy(o,u),zf(this.projectionDeltaWithTransform,this.layoutCorrected,o,u)}}registerSharedNode(a,o){this.sharedNodes.has(a)||this.sharedNodes.set(a,new JQ),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&&kb("z",a,c,this.animationValues);for(let u=0;u<Cb.length;u++)kb(`rotate${Cb[u]}`,a,c,this.animationValues),kb(`skew${Cb[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=Sy(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=Sy(o==null?void 0:o.pointerEvents)||""),this.hasProjected&&!mc(this.latestValues)&&(a.transform=l?l({},""):"none",this.hasProjected=!1);return}a.visibility="";const u=c.animationValues||c.latestValues;this.applyTransformsToTarget();let d=GQ(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 m in UE){if(u[m]===void 0)continue;const{correct:g,applyTo:y,isCSSVariable:v}=UE[m],_=d==="none"?u[m]:g(u[m],c);if(y){const S=y.length;for(let E=0;E<S;E++)a[y[E]]=_}else v?this.options.visualElement.renderState.vars[m]=_:a[m]=_}this.options.layoutId&&(a.pointerEvents=c===this?Sy(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(_L),this.root.sharedNodes.clear()}}}function tJ(t){t.updateLayout()}function nJ(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:s}=t.layout,{animationType:i}=t.options,a=e.source!==t.layout.source;if(i==="size")aa(d=>{const h=a?e.measuredBox[d]:e.layoutBox[d],f=ds(h);h.min=r[d].min,h.max=h.min+f});else if(i==="x"||i==="y"){const d=i==="x"?"y":"x";BE(a?e.measuredBox[d]:e.layoutBox[d],r[d])}else QB(i,e.layoutBox,r)&&aa(d=>{const h=a?e.measuredBox[d]:e.layoutBox[d],f=ds(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=yd();zf(o,r,e.layoutBox);const l=yd();a?zf(l,t.applyTransform(s,!0),e.measuredBox):zf(l,r,e.layoutBox);const c=!HB(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 m=t.options.layoutAnchor||void 0,g=vr();C0(g,e.layoutBox,h.layoutBox,m);const y=vr();C0(y,r,f.layoutBox,m),zB(g,y)||(u=!0),d.options.layoutRoot&&(t.relativeTarget=y,t.relativeTargetOrigin=g,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 rJ(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 sJ(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function iJ(t){t.clearSnapshot()}function _L(t){t.clearMeasurements()}function aJ(t){t.isLayoutDirty=!0,t.updateLayout()}function bL(t){t.isLayoutDirty=!1}function oJ(t){t.isAnimationBlocked&&t.layout&&!t.isLayoutDirty&&(t.snapshot=t.layout,t.isLayoutDirty=!0)}function lJ(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function xL(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function cJ(t){t.resolveTargetDelta()}function uJ(t){t.calcProjection()}function dJ(t){t.resetSkewAndRotation()}function hJ(t){t.removeLeadSnapshot()}function SL(t,e,n){t.translate=In(e.translate,0,n),t.scale=In(e.scale,1,n),t.origin=e.origin,t.originPoint=e.originPoint}function EL(t,e,n,r){t.min=In(e.min,n.min,r),t.max=In(e.max,n.max,r)}function fJ(t,e,n,r){EL(t.x,e.x,n.x,r),EL(t.y,e.y,n.y,r)}function pJ(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const mJ={duration:.45,ease:[.4,0,.1,1]},wL=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),TL=wL("applewebkit/")&&!wL("chrome/")?Math.round:Ti;function AL(t){t.min=TL(t.min),t.max=TL(t.max)}function gJ(t){AL(t.x),AL(t.y)}function QB(t,e,n){return t==="position"||t==="preserve-aspect"&&!jQ(pL(e),pL(n),.2)}function yJ(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const vJ=XB({attachResizeListener:(t,e)=>kp(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}),Lb={current:void 0},JB=XB({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Lb.current){const t=new vJ({});t.mount(window),t.setOptions({layoutScroll:!0}),Lb.current=t}return Lb.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),z1=C.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function RL(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function _J(...t){return e=>{let n=!1;const r=t.map(s=>{const i=RL(s,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let s=0;s<r.length;s++){const i=r[s];typeof i=="function"?i():RL(t[s],null)}}}}function bJ(...t){return C.useCallback(_J(...t),t)}class xJ extends C.Component{getSnapshotBeforeUpdate(e){const n=this.props.childRef.current;if(yy(n)&&e.isPresent&&!this.props.isPresent&&this.props.pop!==!1){const r=n.offsetParent,s=yy(r)&&r.offsetWidth||0,i=yy(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=s-o.width-o.left,o.bottom=i-o.height-o.top}return null}componentDidUpdate(){}render(){return this.props.children}}function SJ({children:t,isPresent:e,anchorX:n,anchorY:r,root:s,pop:i}){var h;const a=C.useId(),o=C.useRef(null),l=C.useRef({width:0,height:0,top:0,left:0,right:0,bottom:0}),{nonce:c}=C.useContext(z1),u=((h=t.props)==null?void 0:h.ref)??(t==null?void 0:t.ref),d=bJ(o,u);return C.useInsertionEffect(()=>{const{width:f,height:m,top:g,left:y,right:v,bottom:_}=l.current;if(e||i===!1||!o.current||!f||!m)return;const S=n==="left"?`left: ${y}`:`right: ${v}`,E=r==="bottom"?`bottom: ${_}`:`top: ${g}`;o.current.dataset.motionPopId=a;const L=document.createElement("style");c&&(L.nonce=c);const U=s??document.head;return U.appendChild(L),L.sheet&&L.sheet.insertRule(`
          [data-motion-pop-id="${a}"] {
            position: absolute !important;
            width: ${f}px !important;
            height: ${m}px !important;
            ${S}px !important;
            ${E}px !important;
          }
        `),()=>{var P;(P=o.current)==null||P.removeAttribute("data-motion-pop-id"),U.contains(L)&&U.removeChild(L)}},[e]),p.jsx(xJ,{isPresent:e,childRef:o,sizeRef:l,pop:i,children:i===!1?t:C.cloneElement(t,{ref:d})})}const EJ=({children:t,initial:e,isPresent:n,onExitComplete:r,custom:s,presenceAffectsLayout:i,mode:a,anchorX:o,anchorY:l,root:c})=>{const u=x1(wJ),d=C.useId();let h=!0,f=C.useMemo(()=>(h=!1,{id:d,initial:e,isPresent:n,custom:s,onExitComplete:m=>{u.set(m,!0);for(const g of u.values())if(!g)return;r&&r()},register:m=>(u.set(m,!1),()=>u.delete(m))}),[n,u,r]);return i&&h&&(f={...f}),C.useMemo(()=>{u.forEach((m,g)=>u.set(g,!1))},[n]),C.useEffect(()=>{!n&&!u.size&&r&&r()},[n]),t=p.jsx(SJ,{pop:a==="popLayout",isPresent:n,anchorX:o,anchorY:l,root:c,children:t}),p.jsx(Mv.Provider,{value:f,children:t})};function wJ(){return new Map}function ZB(t=!0){const e=C.useContext(Mv);if(e===null)return[!0,null];const{isPresent:n,onExitComplete:r,register:s}=e,i=C.useId();C.useEffect(()=>{if(t)return s(i)},[t]);const a=C.useCallback(()=>t&&r&&r(i),[i,r,t]);return!n&&r?[!1,a]:[!0]}const yg=t=>t.key||"";function CL(t){const e=[];return C.Children.forEach(t,n=>{C.isValidElement(n)&&e.push(n)}),e}const Lo=({children:t,custom:e,initial:n=!0,onExitComplete:r,presenceAffectsLayout:s=!0,mode:i="sync",propagate:a=!1,anchorX:o="left",anchorY:l="top",root:c})=>{const[u,d]=ZB(a),h=C.useMemo(()=>CL(t),[t]),f=a&&!u?[]:h.map(yg),m=C.useRef(!0),g=C.useRef(h),y=x1(()=>new Map),v=C.useRef(new Set),[_,S]=C.useState(h),[E,L]=C.useState(h);AU(()=>{m.current=!1,g.current=h;for(let I=0;I<E.length;I++){const k=yg(E[I]);f.includes(k)?(y.delete(k),v.current.delete(k)):y.get(k)!==!0&&y.set(k,!1)}},[E,f.length,f.join("-")]);const U=[];if(h!==_){let I=[...h];for(let k=0;k<E.length;k++){const R=E[k],M=yg(R);f.includes(M)||(I.splice(k,0,R),U.push(R))}return i==="wait"&&U.length&&(I=U),L(CL(I)),S(h),null}const{forceRender:P}=C.useContext(b1);return p.jsx(p.Fragment,{children:E.map(I=>{const k=yg(I),R=a&&!u?!1:h===E||f.includes(k),M=()=>{if(v.current.has(k))return;if(y.has(k))v.current.add(k),y.set(k,!0);else return;let G=!0;y.forEach(Y=>{Y||(G=!1)}),G&&(P==null||P(),L(g.current),a&&(d==null||d()),r&&r())};return p.jsx(EJ,{isPresent:R,initial:!m.current||n?void 0:!1,custom:e,presenceAffectsLayout:s,mode:i,root:c,onExitComplete:R?void 0:M,anchorX:o,anchorY:l,children:I},k)})})},e3=C.createContext({strict:!1}),kL={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 LL=!1;function TJ(){if(LL)return;const t={};for(const e in kL)t[e]={isEnabled:n=>kL[e].some(r=>!!n[r])};kB(t),LL=!0}function t3(){return TJ(),cQ()}function AJ(t){const e=t3();for(const n in t)e[n]={...e[n],...t[n]};kB(e)}const RJ=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 k0(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||RJ.has(t)}let n3=t=>!k0(t);function CJ(t){typeof t=="function"&&(n3=e=>e.startsWith("on")?!k0(e):t(e))}try{CJ(require("@emotion/is-prop-valid").default)}catch{}function kJ(t,e,n){const r={};for(const s in t)s==="values"&&typeof t.values=="object"||zr(t[s])||(n3(s)||n===!0&&k0(s)||!e&&!k0(s)||t.draggable&&s.startsWith("onDrag"))&&(r[s]=t[s]);return r}const Fv=C.createContext({});function LJ(t,e){if(Bv(t)){const{initial:n,animate:r}=t;return{initial:n===!1||Cp(n)?n:void 0,animate:Cp(r)?r:void 0}}return t.inherit!==!1?e:{}}function IJ(t){const{initial:e,animate:n}=LJ(t,C.useContext(Fv));return C.useMemo(()=>({initial:e,animate:n}),[IL(e),IL(n)])}function IL(t){return Array.isArray(t)?t.join(" "):t}const q1=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function r3(t,e,n){for(const r in e)!zr(e[r])&&!MB(r,n)&&(t[r]=e[r])}function PJ({transformTemplate:t},e){return C.useMemo(()=>{const n=q1();return K1(n,e,t),Object.assign({},n.vars,n.style)},[e])}function DJ(t,e){const n=t.style||{},r={};return r3(r,n,t),Object.assign(r,PJ(t,e)),r}function OJ(t,e){const n={},r=DJ(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 s3=()=>({...q1(),attrs:{}});function NJ(t,e,n,r){const s=C.useMemo(()=>{const i=s3();return jB(i,e,BB(r),t.transformTemplate,t.style),{...i.attrs,style:{...i.style}}},[e]);if(t.style){const i={};r3(i,t.style,t),s.style={...i,...s.style}}return s}const MJ=["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 W1(t){return typeof t!="string"||t.includes("-")?!1:!!(MJ.indexOf(t)>-1||/[A-Z]/u.test(t))}function jJ(t,e,n,{latestValues:r},s,i=!1,a){const l=(a??W1(t)?NJ:OJ)(e,r,s,t),c=kJ(e,typeof t=="string",i),u=t!==C.Fragment?{...c,...l,ref:n}:{},{children:d}=e,h=C.useMemo(()=>zr(d)?d.get():d,[d]);return C.createElement(t,{...u,children:h})}function UJ({scrapeMotionValuesFromProps:t,createRenderState:e},n,r,s){return{latestValues:BJ(n,r,s,t),renderState:e()}}function BJ(t,e,n,r){const s={},i=r(t,{});for(const h in i)s[h]=Sy(i[h]);let{initial:a,animate:o}=t;const l=Bv(t),c=RB(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"&&!Uv(d)){const h=Array.isArray(d)?d:[d];for(let f=0;f<h.length;f++){const m=M1(t,h[f]);if(m){const{transitionEnd:g,transition:y,...v}=m;for(const _ in v){let S=v[_];if(Array.isArray(S)){const E=u?S.length-1:0;S=S[E]}S!==null&&(s[_]=S)}for(const _ in g)s[_]=g[_]}}}return s}const i3=t=>(e,n)=>{const r=C.useContext(Fv),s=C.useContext(Mv),i=()=>UJ(t,e,r,s);return n?i():x1(i)},FJ=i3({scrapeMotionValuesFromProps:H1,createRenderState:q1}),$J=i3({scrapeMotionValuesFromProps:FB,createRenderState:s3}),VJ=Symbol.for("motionComponentSymbol");function GJ(t,e,n){const r=C.useRef(n);C.useInsertionEffect(()=>{r.current=n});const s=C.useRef(null);return C.useCallback(i=>{var o;i&&((o=t.onMount)==null||o.call(t,i));const a=r.current;if(typeof a=="function")if(i){const l=a(i);typeof l=="function"&&(s.current=l)}else s.current?(s.current(),s.current=null):a(i);else a&&(a.current=i);e&&(i?e.mount(i):e.unmount())},[e])}const a3=C.createContext({});function Xu(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function KJ(t,e,n,r,s,i){var S,E;const{visualElement:a}=C.useContext(Fv),o=C.useContext(e3),l=C.useContext(Mv),c=C.useContext(z1),u=c.reducedMotion,d=c.skipAnimations,h=C.useRef(null),f=C.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:i}),f.current&&h.current&&(h.current.manuallyAnimateOnMount=!0));const m=h.current,g=C.useContext(a3);m&&!m.projection&&s&&(m.type==="html"||m.type==="svg")&&HJ(h.current,n,s,g);const y=C.useRef(!1);C.useInsertionEffect(()=>{m&&y.current&&m.update(n,l)});const v=n[pB],_=C.useRef(!!v&&typeof window<"u"&&!((S=window.MotionHandoffIsComplete)!=null&&S.call(window,v))&&((E=window.MotionHasOptimisedAnimation)==null?void 0:E.call(window,v)));return AU(()=>{f.current=!0,m&&(y.current=!0,window.MotionIsMounted=!0,m.updateFeatures(),m.scheduleRenderMicrotask(),_.current&&m.animationState&&m.animationState.animateChanges())}),C.useEffect(()=>{m&&(!_.current&&m.animationState&&m.animationState.animateChanges(),_.current&&(queueMicrotask(()=>{var L;(L=window.MotionHandoffMarkAsComplete)==null||L.call(window,v)}),_.current=!1),m.enteringChildren=void 0)}),m}function HJ(t,e,n,r){const{layoutId:s,layout:i,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:o3(t.parent)),t.projection.setOptions({layoutId:s,layout:i,alwaysMeasureLayout:!!a||o&&Xu(o),visualElement:t,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:d,layoutScroll:l,layoutRoot:c,layoutAnchor:u})}function o3(t){if(t)return t.options.allowProjection!==!1?t.projection:o3(t.parent)}function Ib(t,{forwardMotionProps:e=!1,type:n}={},r,s){r&&AJ(r);const i=n?n==="svg":W1(t),a=i?$J:FJ;function o(c,u){let d;const h={...C.useContext(z1),...c,layoutId:zJ(c)},{isStatic:f}=h,m=IJ(c),g=a(c,f);if(!f&&typeof window<"u"){qJ();const y=WJ(h);d=y.MeasureLayout,m.visualElement=KJ(t,g,h,s,y.ProjectionNode,i)}return p.jsxs(Fv.Provider,{value:m,children:[d&&m.visualElement?p.jsx(d,{visualElement:m.visualElement,...h}):null,jJ(t,c,GJ(g,m.visualElement,u),g,f,e,i)]})}o.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const l=C.forwardRef(o);return l[VJ]=t,l}function zJ({layoutId:t}){const e=C.useContext(b1).id;return e&&t!==void 0?e+"-"+t:t}function qJ(t,e){C.useContext(e3).strict}function WJ(t){const e=t3(),{drag:n,layout:r}=e;if(!n&&!r)return{};const s={...n,...r};return{MeasureLayout:n!=null&&n.isEnabled(t)||r!=null&&r.isEnabled(t)?s.MeasureLayout:void 0,ProjectionNode:s.ProjectionNode}}function YJ(t,e){if(typeof Proxy>"u")return Ib;const n=new Map,r=(i,a)=>Ib(i,a,t,e),s=(i,a)=>r(i,a);return new Proxy(s,{get:(i,a)=>a==="create"?r:(n.has(a)||n.set(a,Ib(a,void 0,t,e)),n.get(a))})}const XJ=(t,e)=>e.isSVG??W1(t)?new AQ(e):new bQ(e,{allowProjection:t!==C.Fragment});class QJ extends Ql{constructor(e){super(e),e.animationState||(e.animationState=IQ(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();Uv(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 JJ=0;class ZJ extends Ql{constructor(){super(...arguments),this.id=JJ++,this.isExitComplete=!1}update(){var i;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=Hc(this.node,a,o);if(l){const{transition:c,transitionEnd:u,...d}=l;for(const h in d)(i=this.node.getValue(h))==null||i.jump(d[h])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive("exit",!1);this.isExitComplete=!1;return}const s=this.node.animationState.setActive("exit",!e);n&&!e&&s.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 eZ={animation:{Feature:QJ},exit:{Feature:ZJ}};function Am(t){return{point:{x:t.pageX,y:t.pageY}}}const tZ=t=>e=>F1(e)&&t(e,Am(e));function qf(t,e,n,r){return kp(t,e,tZ(n),r)}const l3=({current:t})=>t?t.ownerDocument.defaultView:null,PL=(t,e)=>Math.abs(t-e);function nZ(t,e){const n=PL(t.x,e.x),r=PL(t.y,e.y);return Math.sqrt(n**2+r**2)}const DL=new Set(["auto","scroll"]);class c3{constructor(e,n,{transformPagePoint:r,contextWindow:s=window,dragSnapToOrigin:i=!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=vg(this.lastRawMoveEventInfo,this.transformPagePoint));const f=Pb(this.lastMoveEventInfo,this.history),m=this.startEvent!==null,g=nZ(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!m&&!g)return;const{point:y}=f,{timestamp:v}=Br;this.history.push({...y,timestamp:v});const{onStart:_,onMove:S}=this.handlers;m||(_&&_(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),S&&S(this.lastMoveEvent,f)},this.handlePointerMove=(f,m)=>{this.lastMoveEvent=f,this.lastRawMoveEventInfo=m,this.lastMoveEventInfo=vg(m,this.transformPagePoint),Sn.update(this.updatePoint,!0)},this.handlePointerUp=(f,m)=>{this.end();const{onEnd:g,onSessionEnd:y,resumeAnimation:v}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&v&&v(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const _=Pb(f.type==="pointercancel"?this.lastMoveEventInfo:vg(m,this.transformPagePoint),this.history);this.startEvent&&g&&g(f,_),y&&y(f,_)},!F1(e))return;this.dragSnapToOrigin=i,this.handlers=n,this.transformPagePoint=r,this.distanceThreshold=a,this.contextWindow=s||window;const l=Am(e),c=vg(l,this.transformPagePoint),{point:u}=c,{timestamp:d}=Br;this.history=[{...u,timestamp:d}];const{onSessionStart:h}=n;h&&h(e,Pb(c,this.history)),this.removeListeners=Em(qf(this.contextWindow,"pointermove",this.handlePointerMove),qf(this.contextWindow,"pointerup",this.handlePointerUp),qf(this.contextWindow,"pointercancel",this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(e){let n=e.parentElement;for(;n;){const r=getComputedStyle(n);(DL.has(r.overflowX)||DL.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,s=r?{x:window.scrollX,y:window.scrollY}:{x:e.scrollLeft,y:e.scrollTop},i={x:s.x-n.x,y:s.y-n.y};i.x===0&&i.y===0||(r?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=i.x,this.lastMoveEventInfo.point.y+=i.y):this.history.length>0&&(this.history[0].x-=i.x,this.history[0].y-=i.y),this.scrollPositions.set(e,s),Sn.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),Vl(this.updatePoint)}}function vg(t,e){return e?{point:e(t.point)}:t}function OL(t,e){return{x:t.x-e.x,y:t.y-e.y}}function Pb({point:t},e){return{point:t,delta:OL(t,u3(e)),offset:OL(t,rZ(e)),velocity:sZ(e,.1)}}function rZ(t){return t[0]}function u3(t){return t[t.length-1]}function sZ(t,e){if(t.length<2)return{x:0,y:0};let n=t.length-1,r=null;const s=u3(t);for(;n>=0&&(r=t[n],!(s.timestamp-r.timestamp>ei(e)));)n--;if(!r)return{x:0,y:0};r===t[0]&&t.length>2&&s.timestamp-r.timestamp>ei(e)*2&&(r=t[1]);const i=Ei(s.timestamp-r.timestamp);if(i===0)return{x:0,y:0};const a={x:(s.x-r.x)/i,y:(s.y-r.y)/i};return a.x===1/0&&(a.x=0),a.y===1/0&&(a.y=0),a}function iZ(t,{min:e,max:n},r){return e!==void 0&&t<e?t=r?In(e,t,r.min):Math.max(t,e):n!==void 0&&t>n&&(t=r?In(n,t,r.max):Math.min(t,n)),t}function NL(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 aZ(t,{top:e,left:n,bottom:r,right:s}){return{x:NL(t.x,n,s),y:NL(t.y,e,r)}}function ML(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 oZ(t,e){return{x:ML(t.x,e.x),y:ML(t.y,e.y)}}function lZ(t,e){let n=.5;const r=ds(t),s=ds(e);return s>r?n=Ap(e.min,e.max-r,t.min):r>s&&(n=Ap(t.min,t.max-s,e.min)),ka(0,1,n)}function cZ(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 FE=.35;function uZ(t=FE){return t===!1?t=0:t===!0&&(t=FE),{x:jL(t,"left","right"),y:jL(t,"top","bottom")}}function jL(t,e,n){return{min:UL(t,e),max:UL(t,n)}}function UL(t,e){return typeof t=="number"?t:t[e]||0}const dZ=new WeakMap;class hZ{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=vr(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:n=!1,distanceThreshold:r}={}){const{presenceContext:s}=this.visualElement;if(s&&s.isPresent===!1)return;const i=d=>{n&&this.snapToCursor(Am(d).point),this.stopAnimation()},a=(d,h)=>{const{drag:f,dragPropagation:m,onDragStart:g}=this.getProps();if(f&&!m&&(this.openDragLock&&this.openDragLock(),this.openDragLock=BX(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),aa(v=>{let _=this.getAxisMotionValue(v).get()||0;if(Ra.test(_)){const{projection:S}=this.visualElement;if(S&&S.layout){const E=S.layout.layoutBox[v];E&&(_=ds(E)*(parseFloat(_)/100))}}this.originPoint[v]=_}),g&&Sn.update(()=>g(d,h),!1,!0),IE(this.visualElement,"transform");const{animationState:y}=this.visualElement;y&&y.setActive("whileDrag",!0)},o=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h;const{dragPropagation:f,dragDirectionLock:m,onDirectionLock:g,onDrag:y}=this.getProps();if(!f&&!this.openDragLock)return;const{offset:v}=h;if(m&&this.currentDirection===null){this.currentDirection=pZ(v),this.currentDirection!==null&&g&&g(this.currentDirection);return}this.updateAxis("x",h.point,v),this.updateAxis("y",h.point,v),this.visualElement.render(),y&&Sn.update(()=>y(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 c3(e,{onSessionStart:i,onStart:a,onMove:o,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:r,contextWindow:l3(this.visualElement),element:this.visualElement.current})}stop(e,n){const r=e||this.latestPointerEvent,s=n||this.latestPanInfo,i=this.isDragging;if(this.cancel(),!i||!s||!r)return;const{velocity:a}=s;this.startAnimation(a);const{onDragEnd:o}=this.getProps();o&&Sn.postRender(()=>o(r,s))}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:s}=this.getProps();if(!r||!_g(e,s,this.currentDirection))return;const i=this.getAxisMotionValue(e);let a=this.originPoint[e]+r[e];this.constraints&&this.constraints[e]&&(a=iZ(a,this.constraints[e],this.elastic[e])),i.set(a)}resolveConstraints(){var i;const{dragConstraints:e,dragElastic:n}=this.getProps(),r=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(i=this.visualElement.projection)==null?void 0:i.layout,s=this.constraints;e&&Xu(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&r?this.constraints=aZ(r.layoutBox,e):this.constraints=!1,this.elastic=uZ(n),s!==this.constraints&&!Xu(e)&&r&&this.constraints&&!this.hasMutatedConstraints&&aa(a=>{this.constraints!==!1&&this.getAxisMotionValue(a)&&(this.constraints[a]=cZ(r.layoutBox[a],this.constraints[a]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:n}=this.getProps();if(!e||!Xu(e))return!1;const r=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const i=pQ(r,s.root,this.visualElement.getTransformPagePoint());let a=oZ(s.layout.layoutBox,i);if(n){const o=n(dQ(a));this.hasMutatedConstraints=!!o,o&&(a=IB(o))}return a}startAnimation(e){const{drag:n,dragMomentum:r,dragElastic:s,dragTransition:i,dragSnapToOrigin:a,onDragTransitionEnd:o}=this.getProps(),l=this.constraints||{},c=aa(u=>{if(!_g(u,n,this.currentDirection))return;let d=l&&l[u]||{};(a===!0||a===u)&&(d={min:0,max:0});const h=s?200:1e6,f=s?40:1e7,m={type:"inertia",velocity:r?e[u]:0,bounceStiffness:h,bounceDamping:f,timeConstant:750,restDelta:1,restSpeed:10,...i,...d};return this.startAxisValueAnimation(u,m)});return Promise.all(c).then(o)}startAxisValueAnimation(e,n){const r=this.getAxisMotionValue(e);return IE(this.visualElement,e),r.start(N1(e,r,0,n,this.visualElement,!1))}stopAnimation(){aa(e=>this.getAxisMotionValue(e).stop())}getAxisMotionValue(e){const n=`_drag${e.toUpperCase()}`,r=this.visualElement.getProps(),s=r[n];return s||this.visualElement.getValue(e,(r.initial?r.initial[e]:void 0)||0)}snapToCursor(e){aa(n=>{const{drag:r}=this.getProps();if(!_g(n,r,this.currentDirection))return;const{projection:s}=this.visualElement,i=this.getAxisMotionValue(n);if(s&&s.layout){const{min:a,max:o}=s.layout.layoutBox[n],l=i.get()||0;i.set(e[n]-In(a,o,.5)+l)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:n}=this.getProps(),{projection:r}=this.visualElement;if(!Xu(n)||!r||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};aa(a=>{const o=this.getAxisMotionValue(a);if(o&&this.constraints!==!1){const l=o.get();s[a]=lZ({min:l,max:l},this.constraints[a])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.constraints=!1,this.resolveConstraints(),aa(a=>{if(!_g(a,e,null))return;const o=this.getAxisMotionValue(a),{min:l,max:c}=this.constraints[a];o.set(In(l,c,s[a]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;dZ.set(this.visualElement,this);const e=this.visualElement.current,n=qf(e,"pointerdown",c=>{const{drag:u,dragListener:d=!0}=this.getProps(),h=c.target,f=h!==e&&HX(h);u&&d&&!f&&this.start(c)});let r;const s=()=>{const{dragConstraints:c}=this.getProps();Xu(c)&&c.current&&(this.constraints=this.resolveRefConstraints(),r||(r=fZ(e,c.current,()=>this.scalePositionWithinConstraints())))},{projection:i}=this.visualElement,a=i.addEventListener("measure",s);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),Sn.read(s);const o=kp(window,"resize",()=>this.scalePositionWithinConstraints()),l=i.addEventListener("didUpdate",({delta:c,hasLayoutChanged:u})=>{this.isDragging&&u&&(aa(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:s=!1,dragConstraints:i=!1,dragElastic:a=FE,dragMomentum:o=!0}=e;return{...e,drag:n,dragDirectionLock:r,dragPropagation:s,dragConstraints:i,dragElastic:a,dragMomentum:o}}}function BL(t){let e=!0;return()=>{if(e){e=!1;return}t()}}function fZ(t,e,n){const r=zk(t,BL(n)),s=zk(e,BL(n));return()=>{r(),s()}}function _g(t,e,n){return(e===!0||e===t)&&(n===null||n===t)}function pZ(t,e=10){let n=null;return Math.abs(t.y)>e?n="y":Math.abs(t.x)>e&&(n="x"),n}class mZ extends Ql{constructor(e){super(e),this.removeGroupControls=Ti,this.removeListeners=Ti,this.controls=new hZ(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Ti}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 Db=t=>(e,n)=>{t&&Sn.update(()=>t(e,n),!1,!0)};class gZ extends Ql{constructor(){super(...arguments),this.removePointerDownListener=Ti}onPointerDown(e){this.session=new c3(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:l3(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:n,onPan:r,onPanEnd:s}=this.node.getProps();return{onSessionStart:Db(e),onStart:Db(n),onMove:Db(r),onEnd:(i,a)=>{delete this.session,s&&Sn.postRender(()=>s(i,a))}}}mount(){this.removePointerDownListener=qf(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 yZ extends C.Component{componentDidMount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:r,layoutId:s}=this.props,{projection:i}=e;i&&(n.group&&n.group.add(i),r&&r.register&&s&&r.register(i),Ob&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Ey.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:n,visualElement:r,drag:s,isPresent:i}=this.props,{projection:a}=r;return a&&(a.isPresent=i,e.layoutDependency!==n&&a.setOptions({...a.options,layoutDependency:n}),Ob=!0,s||e.layoutDependency!==n||n===void 0||e.isPresent!==i?a.willUpdate():this.safeToRemove(),e.isPresent!==i&&(i?a.promote():a.relegate()||Sn.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(),B1.postRender(()=>{!r.currentAnimation&&r.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:r}=this.props,{projection:s}=e;Ob=!0,s&&(s.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(s),r&&r.deregister&&r.deregister(s))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function d3(t){const[e,n]=ZB(),r=C.useContext(b1);return p.jsx(yZ,{...t,layoutGroup:r,switchLayoutGroup:C.useContext(a3),isPresent:e,safeToRemove:n})}const vZ={pan:{Feature:gZ},drag:{Feature:mZ,ProjectionNode:JB,MeasureLayout:d3}};function FL(t,e,n){const{props:r}=t;t.animationState&&r.whileHover&&t.animationState.setActive("whileHover",n==="Start");const s="onHover"+n,i=r[s];i&&Sn.postRender(()=>i(e,Am(e)))}class _Z extends Ql{mount(){const{current:e}=this.node;e&&(this.unmount=$X(e,(n,r)=>(FL(this.node,r,"Start"),s=>FL(this.node,s,"End"))))}unmount(){}}class bZ extends Ql{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=Em(kp(this.node.current,"focus",()=>this.onFocus()),kp(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function $L(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 s="onTap"+(n==="End"?"":n),i=r[s];i&&Sn.postRender(()=>i(e,Am(e)))}class xZ extends Ql{mount(){const{current:e}=this.node;if(!e)return;const{globalTapTarget:n,propagate:r}=this.node.props;this.unmount=qX(e,(s,i)=>($L(this.node,i,"Start"),(a,{success:o})=>$L(this.node,a,o?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:(r==null?void 0:r.tap)===!1})}unmount(){}}const $E=new WeakMap,Nb=new WeakMap,SZ=t=>{const e=$E.get(t.target);e&&e(t)},EZ=t=>{t.forEach(SZ)};function wZ({root:t,...e}){const n=t||document;Nb.has(n)||Nb.set(n,{});const r=Nb.get(n),s=JSON.stringify(e);return r[s]||(r[s]=new IntersectionObserver(EZ,{root:t,...e})),r[s]}function TZ(t,e,n){const r=wZ(e);return $E.set(t,n),r.observe(t),()=>{$E.delete(t),r.unobserve(t)}}const AZ={some:0,all:1};class RZ extends Ql{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:s="some",once:i}=e,a={root:n?n.current:void 0,rootMargin:r,threshold:typeof s=="number"?s:AZ[s]},o=c=>{const{isIntersecting:u}=c;if(this.isInView===u||(this.isInView=u,i&&!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=TZ(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(CZ(e,n))&&this.startObserver()}unmount(){var e;(e=this.stopObserver)==null||e.call(this),this.hasEnteredView=!1,this.isInView=!1}}function CZ({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}const kZ={inView:{Feature:RZ},tap:{Feature:xZ},focus:{Feature:bZ},hover:{Feature:_Z}},LZ={layout:{ProjectionNode:JB,MeasureLayout:d3}},IZ={...eZ,...kZ,...vZ,...LZ},gt=YJ(IZ,XJ),Ct=t=>typeof t=="string",uf=()=>{let t,e;const n=new Promise((r,s)=>{t=r,e=s});return n.resolve=t,n.reject=e,n},VL=t=>t==null?"":String(t),PZ=(t,e,n)=>{t.forEach(r=>{e[r]&&(n[r]=e[r])})},DZ=/###/g,GL=t=>t&&t.includes("###")?t.replace(DZ,"."):t,KL=t=>!t||Ct(t),Wf=(t,e,n)=>{const r=Ct(e)?e.split("."):e;let s=0;for(;s<r.length-1;){if(KL(t))return{};const i=GL(r[s]);!t[i]&&n&&(t[i]=new n),Object.prototype.hasOwnProperty.call(t,i)?t=t[i]:t={},++s}return KL(t)?{}:{obj:t,k:GL(r[s])}},HL=(t,e,n)=>{const{obj:r,k:s}=Wf(t,e,Object);if(r!==void 0||e.length===1){r[s]=n;return}let i=e[e.length-1],a=e.slice(0,e.length-1),o=Wf(t,a,Object);for(;o.obj===void 0&&a.length;)i=`${a[a.length-1]}.${i}`,a=a.slice(0,a.length-1),o=Wf(t,a,Object),o!=null&&o.obj&&typeof o.obj[`${o.k}.${i}`]<"u"&&(o.obj=void 0);o.obj[`${o.k}.${i}`]=n},OZ=(t,e,n,r)=>{const{obj:s,k:i}=Wf(t,e,Object);s[i]=s[i]||[],s[i].push(n)},L0=(t,e)=>{const{obj:n,k:r}=Wf(t,e);if(n&&Object.prototype.hasOwnProperty.call(n,r))return n[r]},NZ=(t,e,n)=>{const r=L0(t,n);return r!==void 0?r:L0(e,n)},h3=(t,e,n)=>{for(const r in e)r!=="__proto__"&&r!=="constructor"&&(r in t?Ct(t[r])||t[r]instanceof String||Ct(e[r])||e[r]instanceof String?n&&(t[r]=e[r]):h3(t[r],e[r],n):t[r]=e[r]);return t},Ha=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),MZ={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"},jZ=t=>Ct(t)?t.replace(/[&<>"'\/]/g,e=>MZ[e]):t;class UZ{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 BZ=[" ",",","?","!",";"],FZ=new UZ(20),$Z=(t,e,n)=>{e=e||"",n=n||"";const r=BZ.filter(a=>!e.includes(a)&&!n.includes(a));if(r.length===0)return!0;const s=FZ.getRegExp(`(${r.map(a=>a==="?"?"\\?":a).join("|")})`);let i=!s.test(t);if(!i){const a=t.indexOf(n);a>0&&!s.test(t.substring(0,a))&&(i=!0)}return i},VE=(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 s=t;for(let i=0;i<r.length;){if(!s||typeof s!="object")return;let a,o="";for(let l=i;l<r.length;++l)if(l!==i&&(o+=n),o+=r[l],a=s[o],a!==void 0){if(["string","number","boolean"].includes(typeof a)&&l<r.length-1)continue;i+=l-i+1;break}s=a}return s},Lp=t=>t==null?void 0:t.replace(/_/g,"-"),VZ={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 GZ=class GE{constructor(e,n={}){this.init(e,n)}init(e,n={}){this.prefix=n.prefix||"i18next:",this.logger=e||VZ,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,s){return s&&!this.debug?null:(e=e.map(i=>Ct(i)?i.replace(/[\r\n\x00-\x1F\x7F]/g," "):i),Ct(e[0])&&(e[0]=`${r}${this.prefix} ${e[0]}`),this.logger[n](e))}create(e){return new GE(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new GE(this.logger,e)}};var ba=new GZ;let $v=class{constructor(){this.observers={}}on(e,n){return e.split(" ").forEach(r=>{this.observers[r]||(this.observers[r]=new Map);const s=this.observers[r].get(n)||0;this.observers[r].set(n,s+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=(...s)=>{n(...s),this.off(e,r)};return this.on(e,r),this}emit(e,...n){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([s,i])=>{for(let a=0;a<i;a++)s(...n)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([s,i])=>{for(let a=0;a<i;a++)s(e,...n)})}};class zL extends $v{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,s={}){var c,u;const i=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator,a=s.ignoreJSONStructure!==void 0?s.ignoreJSONStructure:this.options.ignoreJSONStructure;let o;e.includes(".")?o=e.split("."):(o=[e,n],r&&(Array.isArray(r)?o.push(...r):Ct(r)&&i?o.push(...r.split(i)):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||!Ct(r)?l:VE((u=(c=this.data)==null?void 0:c[e])==null?void 0:u[n],r,i)}addResource(e,n,r,s,i={silent:!1}){const a=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator;let o=[e,n];r&&(o=o.concat(a?r.split(a):r)),e.includes(".")&&(o=e.split("."),s=n,n=o[1]),this.addNamespaces(n),HL(this.data,o,s),i.silent||this.emit("added",e,n,r,s)}addResources(e,n,r,s={silent:!1}){for(const i in r)(Ct(r[i])||Array.isArray(r[i]))&&this.addResource(e,n,i,r[i],{silent:!0});s.silent||this.emit("added",e,n,r)}addResourceBundle(e,n,r,s,i,a={silent:!1,skipCopy:!1}){let o=[e,n];e.includes(".")&&(o=e.split("."),s=r,r=n,n=o[1]),this.addNamespaces(n);let l=L0(this.data,o)||{};a.skipCopy||(r=JSON.parse(JSON.stringify(r))),s?h3(l,r,i):l={...l,...r},HL(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(s=>n[s]&&Object.keys(n[s]).length>0)}toJSON(){return this.data}}var f3={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,n,r,s){return t.forEach(i=>{var a;e=((a=this.processors[i])==null?void 0:a.process(e,n,r,s))??e}),e}};const p3=Symbol("i18next/PATH_KEY");function KZ(){const t=[],e=Object.create(null);let n;return e.get=(r,s)=>{var i;return(i=n==null?void 0:n.revoke)==null||i.call(n),s===p3?t:(t.push(s),n=Proxy.revocable(r,e),n.proxy)},Proxy.revocable(Object.create(null),e).proxy}function Pd(t,e){const{[p3]:n}=t(KZ()),r=(e==null?void 0:e.keySeparator)??".",s=(e==null?void 0:e.nsSeparator)??":";if(n.length>1&&s){const i=e==null?void 0:e.ns,a=Array.isArray(i)?i:null;if(a&&a.length>1&&a.slice(1).includes(n[0]))return`${n[0]}${s}${n.slice(1).join(r)}`}return n.join(r)}const Mb=t=>!Ct(t)&&typeof t!="boolean"&&typeof t!="number";class I0 extends $v{constructor(e,n={}){super(),PZ(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=ba.create("translator"),this.checkedLoadedFor={}}changeLanguage(e){e&&(this.language=e)}exists(e,n={interpolation:{}}){const r={...n};if(e==null)return!1;const s=this.resolve(e,r);if((s==null?void 0:s.res)===void 0)return!1;const i=Mb(s.res);return!(r.returnObjects===!1&&i)}extractFromKey(e,n){let r=n.nsSeparator!==void 0?n.nsSeparator:this.options.nsSeparator;r===void 0&&(r=":");const s=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let i=n.ns||this.options.defaultNS||[];const a=r&&e.includes(r),o=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!$Z(e,r,s);if(a&&!o){const l=e.match(this.interpolator.nestingRegexp);if(l&&l.length>0)return{key:e,namespaces:Ct(i)?[i]:i};const c=e.split(r);(r!==s||r===s&&this.options.ns.includes(c[0]))&&(i=c.shift()),e=c.join(s)}return{key:e,namespaces:Ct(i)?[i]:i}}translate(e,n,r){let s=typeof n=="object"?{...n}:n;if(typeof s!="object"&&this.options.overloadTranslationOptionHandler&&(s=this.options.overloadTranslationOptionHandler(arguments)),typeof s=="object"&&(s={...s}),s||(s={}),e==null)return"";typeof e=="function"&&(e=Pd(e,{...this.options,...s})),Array.isArray(e)||(e=[String(e)]),e=e.map(Y=>typeof Y=="function"?Pd(Y,{...this.options,...s}):String(Y));const i=s.returnDetails!==void 0?s.returnDetails:this.options.returnDetails,a=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator,{key:o,namespaces:l}=this.extractFromKey(e[e.length-1],s),c=l[l.length-1];let u=s.nsSeparator!==void 0?s.nsSeparator:this.options.nsSeparator;u===void 0&&(u=":");const d=s.lng||this.language,h=s.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if((d==null?void 0:d.toLowerCase())==="cimode")return h?i?{res:`${c}${u}${o}`,usedKey:o,exactUsedKey:o,usedLng:d,usedNS:c,usedParams:this.getUsedParamsDetails(s)}:`${c}${u}${o}`:i?{res:o,usedKey:o,exactUsedKey:o,usedLng:d,usedNS:c,usedParams:this.getUsedParamsDetails(s)}:o;const f=this.resolve(e,s);let m=f==null?void 0:f.res;const g=(f==null?void 0:f.usedKey)||o,y=(f==null?void 0:f.exactUsedKey)||o,v=["[object Number]","[object Function]","[object RegExp]"],_=s.joinArrays!==void 0?s.joinArrays:this.options.joinArrays,S=!this.i18nFormat||this.i18nFormat.handleAsObject,E=s.count!==void 0&&!Ct(s.count),L=I0.hasDefaultValue(s),U=E?this.pluralResolver.getSuffix(d,s.count,s):"",P=s.ordinal&&E?this.pluralResolver.getSuffix(d,s.count,{ordinal:!1}):"",I=E&&!s.ordinal&&s.count===0,k=I&&s[`defaultValue${this.options.pluralSeparator}zero`]||s[`defaultValue${U}`]||s[`defaultValue${P}`]||s.defaultValue;let R=m;S&&!m&&L&&(R=k);const M=Mb(R),G=Object.prototype.toString.apply(R);if(S&&R&&M&&!v.includes(G)&&!(Ct(_)&&Array.isArray(R))){if(!s.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const Y=this.options.returnedObjectHandler?this.options.returnedObjectHandler(g,R,{...s,ns:l}):`key '${o} (${this.language})' returned an object instead of string.`;return i?(f.res=Y,f.usedParams=this.getUsedParamsDetails(s),f):Y}if(a){const Y=Array.isArray(R),q=Y?[]:{},X=Y?y:g;for(const Z in R)if(Object.prototype.hasOwnProperty.call(R,Z)){const oe=`${X}${a}${Z}`;L&&!m?q[Z]=this.translate(oe,{...s,defaultValue:Mb(k)?k[Z]:void 0,joinArrays:!1,ns:l}):q[Z]=this.translate(oe,{...s,joinArrays:!1,ns:l}),q[Z]===oe&&(q[Z]=R[Z])}m=q}}else if(S&&Ct(_)&&Array.isArray(m))m=m.join(_),m&&(m=this.extendTranslation(m,e,s,r));else{let Y=!1,q=!1;!this.isValidLookup(m)&&L&&(Y=!0,m=k),this.isValidLookup(m)||(q=!0,m=o);const Z=(s.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&q?void 0:m,oe=L&&k!==m&&this.options.updateMissing;if(q||Y||oe){if(this.logger.log(oe?"updateKey":"missingKey",d,c,E&&!oe?`${o}${this.pluralResolver.getSuffix(d,s.count,s)}`:o,oe?k:m),a){const J=this.resolve(o,{...s,keySeparator:!1});J&&J.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 ne=[];const H=this.languageUtils.getFallbackCodes(this.options.fallbackLng,s.lng||this.language);if(this.options.saveMissingTo==="fallback"&&H&&H[0])for(let J=0;J<H.length;J++)ne.push(H[J]);else this.options.saveMissingTo==="all"?ne=this.languageUtils.toResolveHierarchy(s.lng||this.language):ne.push(s.lng||this.language);const K=(J,Q,ve)=>{var Ne;const Te=L&&ve!==m?ve:Z;this.options.missingKeyHandler?this.options.missingKeyHandler(J,c,Q,Te,oe,s):(Ne=this.backendConnector)!=null&&Ne.saveMissing&&this.backendConnector.saveMissing(J,c,Q,Te,oe,s),this.emit("missingKey",J,c,Q,m)};this.options.saveMissing&&(this.options.saveMissingPlurals&&E?ne.forEach(J=>{const Q=this.pluralResolver.getSuffixes(J,s);I&&s[`defaultValue${this.options.pluralSeparator}zero`]&&!Q.includes(`${this.options.pluralSeparator}zero`)&&Q.push(`${this.options.pluralSeparator}zero`),Q.forEach(ve=>{K([J],o+ve,s[`defaultValue${ve}`]||k)})}):K(ne,o,k))}m=this.extendTranslation(m,e,s,f,r),q&&m===o&&this.options.appendNamespaceToMissingKey&&(m=`${c}${u}${o}`),(q||Y)&&this.options.parseMissingKeyHandler&&(m=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${c}${u}${o}`:o,Y?m:void 0,s))}return i?(f.res=m,f.usedParams=this.getUsedParamsDetails(s),f):m}extendTranslation(e,n,r,s,i){var l,c;if((l=this.i18nFormat)!=null&&l.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...r},r.lng||this.language||s.usedLng,s.usedNS,s.usedKey,{resolved:s});else if(!r.skipInterpolation){r.interpolation&&this.interpolator.init({...r,interpolation:{...this.options.interpolation,...r.interpolation}});const u=Ct(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&&!Ct(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||s.usedLng,r),u){const f=e.match(this.interpolator.nestingRegexp),m=f&&f.length;d<m&&(r.nest=!1)}!r.lng&&s&&s.res&&(r.lng=this.language||s.usedLng),r.nest!==!1&&(e=this.interpolator.nest(e,(...f)=>(i==null?void 0:i[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=Ct(a)?[a]:a;return e!=null&&(o!=null&&o.length)&&r.applyPostProcessor!==!1&&(e=f3.handle(o,e,n,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...s,usedParams:this.getUsedParamsDetails(r)},...r}:r,this)),e}resolve(e,n={}){let r,s,i,a,o;return Ct(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(l=>typeof l=="function"?Pd(l,{...this.options,...n}):l)),e.forEach(l=>{if(this.isValidLookup(r))return;const c=this.extractFromKey(l,n),u=c.key;s=u;let d=c.namespaces;this.options.fallbackNS&&(d=d.concat(this.options.fallbackNS));const h=n.count!==void 0&&!Ct(n.count),f=h&&!n.ordinal&&n.count===0,m=n.context!==void 0&&(Ct(n.context)||typeof n.context=="number")&&n.context!=="",g=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);d.forEach(y=>{var v,_;this.isValidLookup(r)||(o=y,!this.checkedLoadedFor[`${g[0]}-${y}`]&&((v=this.utils)!=null&&v.hasLoadedNamespace)&&!((_=this.utils)!=null&&_.hasLoadedNamespace(o))&&(this.checkedLoadedFor[`${g[0]}-${y}`]=!0,this.logger.warn(`key "${s}" for languages "${g.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!!!")),g.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,y,n);else{let P;h&&(P=this.pluralResolver.getSuffix(S,n.count,n));const I=`${this.options.pluralSeparator}zero`,k=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(h&&(n.ordinal&&P.startsWith(k)&&E.push(u+P.replace(k,this.options.pluralSeparator)),E.push(u+P),f&&E.push(u+I)),m){const R=`${u}${this.options.contextSeparator||"_"}${n.context}`;E.push(R),h&&(n.ordinal&&P.startsWith(k)&&E.push(R+P.replace(k,this.options.pluralSeparator)),E.push(R+P),f&&E.push(R+I))}}let L;for(;L=E.pop();)this.isValidLookup(r)||(i=L,r=this.getResource(S,y,L,n))}))})}),{res:r,usedKey:s,exactUsedKey:i,usedLng:a,usedNS:o}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,n,r,s={}){var i;return(i=this.i18nFormat)!=null&&i.getResource?this.i18nFormat.getResource(e,n,r,s):this.resourceStore.getResource(e,n,r,s)}getUsedParamsDetails(e={}){const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],r=e.replace&&!Ct(e.replace);let s=r?e.replace:e;if(r&&typeof e.count<"u"&&(s.count=e.count),this.options.interpolation.defaultVariables&&(s={...this.options.interpolation.defaultVariables,...s}),!r){s={...s};for(const i of n)delete s[i]}return s}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 qL{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=ba.create("languageUtils")}getScriptPartFromCode(e){if(e=Lp(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=Lp(e),!e||!e.includes("-"))return e;const n=e.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(e){if(Ct(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 s=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(s))&&(n=s)}),!n&&this.options.supportedLngs&&e.forEach(r=>{if(n)return;const s=this.getScriptPartFromCode(r);if(this.isSupportedCode(s))return n=s;const i=this.getLanguagePartFromCode(r);if(this.isSupportedCode(i))return n=i;n=this.options.supportedLngs.find(a=>a===i?!0:!a.includes("-")&&!i.includes("-")?!1:!!(a.includes("-")&&!i.includes("-")&&a.slice(0,a.indexOf("-"))===i||a.startsWith(i)&&i.length>1))}),n||(n=this.getFallbackCodes(this.options.fallbackLng)[0]),n}getFallbackCodes(e,n){if(!e)return[];if(typeof e=="function"&&(e=e(n)),Ct(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),s=[],i=a=>{a&&(this.isSupportedCode(a)?s.push(a):this.logger.warn(`rejecting language code not found in supportedLngs: ${a}`))};return Ct(e)&&(e.includes("-")||e.includes("_"))?(this.options.load!=="languageOnly"&&i(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&i(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&i(this.getLanguagePartFromCode(e))):Ct(e)&&i(this.formatLanguageCode(e)),r.forEach(a=>{s.includes(a)||i(this.formatLanguageCode(a))}),s}}const WL={zero:0,one:1,two:2,few:3,many:4,other:5},YL={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class HZ{constructor(e,n={}){this.languageUtils=e,this.options=n,this.logger=ba.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,n={}){const r=Lp(e==="dev"?"en":e),s=n.ordinal?"ordinal":"cardinal",i=JSON.stringify({cleanedCode:r,type:s});if(i in this.pluralRulesCache)return this.pluralRulesCache[i];let a;try{a=new Intl.PluralRules(r,{type:s})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),YL;if(!e.match(/-|_/))return YL;const l=this.languageUtils.getLanguagePartFromCode(e);a=this.getRule(l,n)}return this.pluralRulesCache[i]=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(s=>`${n}${s}`)}getSuffixes(e,n={}){let r=this.getRule(e,n);return r||(r=this.getRule("dev",n)),r?r.resolvedOptions().pluralCategories.sort((s,i)=>WL[s]-WL[i]).map(s=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${s}`):[]}getSuffix(e,n,r={}){const s=this.getRule(e,r);return s?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${s.select(n)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",n,r))}}const XL=(t,e,n,r=".",s=!0)=>{let i=NZ(t,e,n);return!i&&s&&Ct(n)&&(i=VE(t,n,r),i===void 0&&(i=VE(e,n,r))),i},jb=t=>t.replace(/\$/g,"$$$$");class QL{constructor(e={}){var n;this.logger=ba.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:s,prefix:i,prefixEscaped:a,suffix:o,suffixEscaped:l,formatSeparator:c,unescapeSuffix:u,unescapePrefix:d,nestingPrefix:h,nestingPrefixEscaped:f,nestingSuffix:m,nestingSuffixEscaped:g,nestingOptionsSeparator:y,maxReplaces:v,alwaysFormat:_}=e.interpolation;this.escape=n!==void 0?n:jZ,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=s!==void 0?s:!1,this.prefix=i?Ha(i):a||"{{",this.suffix=o?Ha(o):l||"}}",this.formatSeparator=c||",",this.unescapePrefix=u?"":d?Ha(d):"-",this.unescapeSuffix=this.unescapePrefix?"":u?Ha(u):"",this.nestingPrefix=h?Ha(h):f||Ha("$t("),this.nestingSuffix=m?Ha(m):g||Ha(")"),this.nestingOptionsSeparator=y||",",this.maxReplaces=v||1e3,this.alwaysFormat=_!==void 0?_:!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,s){var f;let i,a,o;const l=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},c=m=>{if(!m.includes(this.formatSeparator)){const _=XL(n,l,m,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(_,void 0,r,{...s,...n,interpolationkey:m}):_}const g=m.split(this.formatSeparator),y=g.shift().trim(),v=g.join(this.formatSeparator).trim();return this.format(XL(n,l,y,this.options.keySeparator,this.options.ignoreJSONStructure),v,r,{...s,...n,interpolationkey:y})};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=(s==null?void 0:s.missingInterpolationHandler)||this.options.missingInterpolationHandler,d=((f=s==null?void 0:s.interpolation)==null?void 0:f.skipOnVariables)!==void 0?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:m=>jb(m)},{regex:this.regexp,safeValue:m=>this.escapeValue?jb(this.escape(m)):jb(m)}].forEach(m=>{for(o=0;i=m.regex.exec(e);){const g=i[1].trim();if(a=c(g),a===void 0)if(typeof u=="function"){const v=u(e,i,s);a=Ct(v)?v:""}else if(s&&Object.prototype.hasOwnProperty.call(s,g))a="";else if(d){a=i[0];continue}else this.logger.warn(`missed to pass in variable ${g} for interpolating ${e}`),a="";else!Ct(a)&&!this.useRawValueToEscape&&(a=VL(a));const y=m.safeValue(a);if(e=e.replace(i[0],y),d?(m.regex.lastIndex+=a.length,m.regex.lastIndex-=i[0].length):m.regex.lastIndex=0,o++,o>=this.maxReplaces)break}}),e}nest(e,n,r={}){let s,i,a;const o=(l,c)=>{const u=this.nestingOptionsSeparator;if(!l.includes(u))return l;const d=l.split(new RegExp(`${Ha(u)}[ ]*{`));let h=`{${d[1]}`;l=d[0],h=this.interpolate(h,a);const f=h.match(/'/g),m=h.match(/"/g);(((f==null?void 0:f.length)??0)%2===0&&!m||((m==null?void 0:m.length)??0)%2!==0)&&(h=h.replace(/'/g,'"'));try{a=JSON.parse(h),c&&(a={...c,...a})}catch(g){return this.logger.warn(`failed parsing options string in nesting for key ${l}`,g),`${l}${u}${h}`}return a.defaultValue&&a.defaultValue.includes(this.prefix)&&delete a.defaultValue,l};for(;s=this.nestingRegexp.exec(e);){let l=[];a={...r},a=a.replace&&!Ct(a.replace)?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;const c=/{.*}/.test(s[1])?s[1].lastIndexOf("}")+1:s[1].indexOf(this.formatSeparator);if(c!==-1&&(l=s[1].slice(c).split(this.formatSeparator).map(u=>u.trim()).filter(Boolean),s[1]=s[1].slice(0,c)),i=n(o.call(this,s[1].trim(),a),a),i&&s[0]===e&&!Ct(i))return i;Ct(i)||(i=VL(i)),i||(this.logger.warn(`missed to resolve ${s[1]} for nesting ${e}`),i=""),l.length&&(i=l.reduce((u,d)=>this.format(u,d,r.lng,{...r,interpolationkey:s[1].trim()}),i.trim())),e=e.replace(s[0],i),this.regexp.lastIndex=0}return e}}const zZ=t=>{let e=t.toLowerCase().trim();const n={};if(t.includes("(")){const r=t.split("(");e=r[0].toLowerCase().trim();const s=r[1].slice(0,-1);e==="currency"&&!s.includes(":")?n.currency||(n.currency=s.trim()):e==="relativetime"&&!s.includes(":")?n.range||(n.range=s.trim()):s.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}},JL=t=>{const e={};return(n,r,s)=>{let i=s;s&&s.interpolationkey&&s.formatParams&&s.formatParams[s.interpolationkey]&&s[s.interpolationkey]&&(i={...i,[s.interpolationkey]:void 0});const a=r+JSON.stringify(i);let o=e[a];return o||(o=t(Lp(r),s),e[a]=o),o(n)}},qZ=t=>(e,n,r)=>t(Lp(n),r)(e);class WZ{constructor(e={}){this.logger=ba.create("formatter"),this.options=e,this.init(e)}init(e,n={interpolation:{}}){this.formatSeparator=n.interpolation.formatSeparator||",";const r=n.cacheInBuiltFormats?JL:qZ;this.formats={number:r((s,i)=>{const a=new Intl.NumberFormat(s,{...i});return o=>a.format(o)}),currency:r((s,i)=>{const a=new Intl.NumberFormat(s,{...i,style:"currency"});return o=>a.format(o)}),datetime:r((s,i)=>{const a=new Intl.DateTimeFormat(s,{...i});return o=>a.format(o)}),relativetime:r((s,i)=>{const a=new Intl.RelativeTimeFormat(s,{...i});return o=>a.format(o,i.range||"day")}),list:r((s,i)=>{const a=new Intl.ListFormat(s,{...i});return o=>a.format(o)})}}add(e,n){this.formats[e.toLowerCase().trim()]=n}addCached(e,n){this.formats[e.toLowerCase().trim()]=JL(n)}format(e,n,r,s={}){if(!n||e==null)return e;const i=n.split(this.formatSeparator);if(i.length>1&&i[0].indexOf("(")>1&&!i[0].includes(")")&&i.find(o=>o.includes(")"))){const o=i.findIndex(l=>l.includes(")"));i[0]=[i[0],...i.splice(1,o)].join(this.formatSeparator)}return i.reduce((o,l)=>{var d;const{formatName:c,formatOptions:u}=zZ(l);if(this.formats[c]){let h=o;try{const f=((d=s==null?void 0:s.formatParams)==null?void 0:d[s.interpolationkey])||{},m=f.locale||f.lng||s.locale||s.lng||r;h=this.formats[c](o,m,{...u,...s,...f})}catch(f){this.logger.warn(f)}return h}else this.logger.warn(`there was no format function for ${c}`);return o},e)}}const YZ=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class XZ extends $v{constructor(e,n,r,s={}){var i,a;super(),this.backend=e,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=s,this.logger=ba.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=s.maxParallelReads||10,this.readingCalls=0,this.maxRetries=s.maxRetries>=0?s.maxRetries:5,this.retryTimeout=s.retryTimeout>=1?s.retryTimeout:350,this.state={},this.queue=[],(a=(i=this.backend)==null?void 0:i.init)==null||a.call(i,r,s.backend,s)}queueLoad(e,n,r,s){const i={},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),i[h]===void 0&&(i[h]=!0),l[d]===void 0&&(l[d]=!0)))}),u||(o[c]=!0)}),(Object.keys(i).length||Object.keys(a).length)&&this.queue.push({pending:a,pendingCount:Object.keys(a).length,loaded:{},errors:[],callback:s}),{toLoad:Object.keys(i),pending:Object.keys(a),toLoadLanguages:Object.keys(o),toLoadNamespaces:Object.keys(l)}}loaded(e,n,r){const s=e.split("|"),i=s[0],a=s[1];n&&this.emit("failedLoading",i,a,n),!n&&r&&this.store.addResourceBundle(i,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=>{OZ(l.loaded,[i],a),YZ(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,s=0,i=this.retryTimeout,a){if(!e.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:n,fcName:r,tried:s,wait:i,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&&s<this.maxRetries){setTimeout(()=>{this.read(e,n,r,s+1,i*2,a)},i);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={},s){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),s&&s();Ct(e)&&(e=this.languageUtils.toResolveHierarchy(e)),Ct(n)&&(n=[n]);const i=this.queueLoad(e,n,r,s);if(!i.toLoad.length)return i.pending.length||s(),null;i.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("|"),s=r[0],i=r[1];this.read(s,i,"read",void 0,void 0,(a,o)=>{a&&this.logger.warn(`${n}loading namespace ${i} for language ${s} failed`,a),!a&&o&&this.logger.log(`${n}loaded namespace ${i} for language ${s}`,o),this.loaded(e,a,o)})}saveMissing(e,n,r,s,i,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:i},m=this.backend.create.bind(this.backend);if(m.length<6)try{let g;m.length===5?g=m(e,n,r,s,f):g=m(e,n,r,s),g&&typeof g.then=="function"?g.then(y=>o(null,y)).catch(o):o(null,g)}catch(g){o(g)}else m(e,n,r,s,o,f)}!e||!e[0]||this.store.addResource(e[0],n,r,s)}}}const Ub=()=>({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]),Ct(t[1])&&(e.defaultValue=t[1]),Ct(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}),ZL=t=>(Ct(t.ns)&&(t.ns=[t.ns]),Ct(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),Ct(t.fallbackNS)&&(t.fallbackNS=[t.fallbackNS]),t.supportedLngs&&!t.supportedLngs.includes("cimode")&&(t.supportedLngs=t.supportedLngs.concat(["cimode"])),t),bg=()=>{},QZ=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(n=>{typeof t[n]=="function"&&(t[n]=t[n].bind(t))})};class Yf extends $v{constructor(e={},n){if(super(),this.options=ZL(e),this.services={},this.logger=ba,this.modules={external:[]},QZ(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&&(Ct(e.ns)?e.defaultNS=e.ns:e.ns.includes("translation")||(e.defaultNS=e.ns[0]));const r=Ub();this.options={...r,...this.options,...ZL(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 s=c=>c?typeof c=="function"?new c:c:null;if(!this.options.isClone){this.modules.logger?ba.init(s(this.modules.logger),this.options):ba.init(null,this.options);let c;this.modules.formatter?c=this.modules.formatter:c=WZ;const u=new qL(this.options);this.store=new zL(this.options.resources,this.options);const d=this.services;d.logger=ba,d.resourceStore=this.store,d.languageUtils=u,d.pluralResolver=new HZ(u,{prepend:this.options.pluralSeparator}),c&&(d.formatter=s(c),d.formatter.init&&d.formatter.init(d,this.options),this.options.interpolation.format=d.formatter.format.bind(d.formatter)),d.interpolator=new QL(this.options),d.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},d.backendConnector=new XZ(s(this.modules.backend),d.resourceStore,d,this.options),d.backendConnector.on("*",(h,...f)=>{this.emit(h,...f)}),this.modules.languageDetector&&(d.languageDetector=s(this.modules.languageDetector),d.languageDetector.init&&d.languageDetector.init(d,this.options.detection,this.options)),this.modules.i18nFormat&&(d.i18nFormat=s(this.modules.i18nFormat),d.i18nFormat.init&&d.i18nFormat.init(this)),this.translator=new I0(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=bg),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=uf(),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=bg){var i,a;let r=n;const s=Ct(e)?e:this.language;if(typeof e=="function"&&(r=e),!this.options.resources||this.options.partialBundledLanguages){if((s==null?void 0:s.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))})};s?l(s):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(u=>l(u)),(a=(i=this.options.preload)==null?void 0:i.forEach)==null||a.call(i,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 s=uf();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=bg),this.services.backendConnector.reload(e,n,i=>{s.resolve(),r(i)}),s}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"&&f3.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=uf();this.emit("languageChanging",e);const s=o=>{this.language=o,this.languages=this.services.languageUtils.toResolveHierarchy(o),this.resolvedLanguage=void 0,this.setResolvedLanguage(o)},i=(o,l)=>{l?this.isLanguageChangingTo===e&&(s(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=Ct(o)?o:o&&o[0],c=this.store.hasLanguageSomeTranslations(l)?l:this.services.languageUtils.getBestMatchFromCodes(Ct(o)?[o]:o);c&&(this.language||s(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=>{i(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 s=(i,a,...o)=>{let l;typeof a!="object"?l=this.options.overloadTranslationOptionHandler([i,a].concat(o)):l={...a},l.lng=l.lng||s.lng,l.lngs=l.lngs||s.lngs,l.ns=l.ns||s.ns,l.keyPrefix!==""&&(l.keyPrefix=l.keyPrefix||r||s.keyPrefix);const c={...this.options,...l};typeof l.keyPrefix=="function"&&(l.keyPrefix=Pd(l.keyPrefix,c));const u=this.options.keySeparator||".";let d;return l.keyPrefix&&Array.isArray(i)?d=i.map(h=>(typeof h=="function"&&(h=Pd(h,c)),`${l.keyPrefix}${u}${h}`)):(typeof i=="function"&&(i=Pd(i,c)),d=l.keyPrefix?`${l.keyPrefix}${u}${i}`:i),this.t(d,l)};return Ct(e)?s.lng=e:s.lngs=e,s.ns=n,s.keyPrefix=r,s}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],s=this.options?this.options.fallbackLng:!1,i=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)&&(!s||a(i,e)))}loadNamespaces(e,n){const r=uf();return this.options.ns?(Ct(e)&&(e=[e]),e.forEach(s=>{this.options.ns.includes(s)||this.options.ns.push(s)}),this.loadResources(s=>{r.resolve(),n&&n(s)}),r):(n&&n(),Promise.resolve())}loadLanguages(e,n){const r=uf();Ct(e)&&(e=[e]);const s=this.options.preload||[],i=e.filter(a=>!s.includes(a)&&this.services.languageUtils.isSupportedCode(a));return i.length?(this.options.preload=s.concat(i),this.loadResources(a=>{r.resolve(),n&&n(a)}),r):(n&&n(),Promise.resolve())}dir(e){var s,i;if(e||(e=this.resolvedLanguage||(((s=this.languages)==null?void 0:s.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=((i=this.services)==null?void 0:i.languageUtils)||new qL(Ub());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 Yf(e,n);return r.createInstance=Yf.createInstance,r}cloneInstance(e={},n=bg){const r=e.forkResourceStore;r&&delete e.forkResourceStore;const s={...this.options,...e,isClone:!0},i=new Yf(s);if((e.debug!==void 0||e.prefix!==void 0)&&(i.logger=i.logger.clone(e)),["store","services","language"].forEach(o=>{i[o]=this[o]}),i.services={...this.services},i.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},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),{});i.store=new zL(o,s),i.services.resourceStore=i.store}if(e.interpolation){const l={...Ub().interpolation,...this.options.interpolation,...e.interpolation},c={...s,interpolation:l};i.services.interpolator=new QL(c)}return i.translator=new I0(i.services,s),i.translator.on("*",(o,...l)=>{i.emit(o,...l)}),i.init(s,n),i.translator.options=s,i.translator.backendConnector.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},i}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const Wr=Yf.createInstance();Wr.createInstance;Wr.dir;Wr.init;Wr.loadResources;Wr.reloadResources;Wr.use;Wr.changeLanguage;Wr.getFixedT;Wr.t;Wr.exists;Wr.setDefaultNamespace;Wr.hasLoadedNamespace;Wr.loadNamespaces;Wr.loadLanguages;const JZ=(t,e,n,r)=>{var i,a,o,l;const s=[n,{code:e,...r||{}}];if((a=(i=t==null?void 0:t.services)==null?void 0:i.logger)!=null&&a.forward)return t.services.logger.forward(s,"warn","react-i18next::",!0);eu(s[0])&&(s[0]=`react-i18next:: ${s[0]}`),(l=(o=t==null?void 0:t.services)==null?void 0:o.logger)!=null&&l.warn?t.services.logger.warn(...s):console!=null&&console.warn&&console.warn(...s)},eI={},KE=(t,e,n,r)=>{eu(n)&&eI[n]||(eu(n)&&(eI[n]=new Date),JZ(t,e,n,r))},m3=(t,e)=>()=>{if(t.isInitialized)e();else{const n=()=>{setTimeout(()=>{t.off("initialized",n)},0),e()};t.on("initialized",n)}},HE=(t,e,n)=>{t.loadNamespaces(e,m3(t,n))},tI=(t,e,n,r)=>{if(eu(n)&&(n=[n]),t.options.preload&&t.options.preload.indexOf(e)>-1)return HE(t,n,r);n.forEach(s=>{t.options.ns.indexOf(s)<0&&t.options.ns.push(s)}),t.loadLanguages(e,m3(t,r))},ZZ=(t,e,n={})=>!e.languages||!e.languages.length?(KE(e,"NO_LANGUAGES","i18n.languages were undefined or empty",{languages:e.languages}),!0):e.hasLoadedNamespace(t,{lng:n.lng,precheck:(r,s)=>{if(n.bindI18n&&n.bindI18n.indexOf("languageChanging")>-1&&r.services.backendConnector.backend&&r.isLanguageChangingTo&&!s(r.isLanguageChangingTo,t))return!1}}),eu=t=>typeof t=="string",eee=t=>typeof t=="object"&&t!==null,tee=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,nee={"&amp;":"&","&#38;":"&","&lt;":"<","&#60;":"<","&gt;":">","&#62;":">","&apos;":"'","&#39;":"'","&quot;":'"',"&#34;":'"',"&nbsp;":" ","&#160;":" ","&copy;":"©","&#169;":"©","&reg;":"®","&#174;":"®","&hellip;":"…","&#8230;":"…","&#x2F;":"/","&#47;":"/"},ree=t=>nee[t],see=t=>t.replace(tee,ree);let zE={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:see,transDefaultProps:void 0};const iee=(t={})=>{zE={...zE,...t}},aee=()=>zE;let g3;const oee=t=>{g3=t},lee=()=>g3,cee={type:"3rdParty",init(t){iee(t.options.react),oee(t)}},uee=C.createContext();class dee{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach(n=>{this.usedNamespaces[n]||(this.usedNamespaces[n]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}var y3={exports:{}},v3={};/**
 * @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 mh=C;function hee(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var fee=typeof Object.is=="function"?Object.is:hee,pee=mh.useState,mee=mh.useEffect,gee=mh.useLayoutEffect,yee=mh.useDebugValue;function vee(t,e){var n=e(),r=pee({inst:{value:n,getSnapshot:e}}),s=r[0].inst,i=r[1];return gee(function(){s.value=n,s.getSnapshot=e,Bb(s)&&i({inst:s})},[t,n,e]),mee(function(){return Bb(s)&&i({inst:s}),t(function(){Bb(s)&&i({inst:s})})},[t]),yee(n),n}function Bb(t){var e=t.getSnapshot;t=t.value;try{var n=e();return!fee(t,n)}catch{return!0}}function _ee(t,e){return e()}var bee=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?_ee:vee;v3.useSyncExternalStore=mh.useSyncExternalStore!==void 0?mh.useSyncExternalStore:bee;y3.exports=v3;var xee=y3.exports;const See=(t,e)=>{if(eu(e))return e;if(eee(e)&&eu(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},Eee={t:See,ready:!1},wee=()=>()=>{},wr=(t,e={})=>{var k,R,M;const{i18n:n}=e,{i18n:r,defaultNS:s}=C.useContext(uee)||{},i=n||r||lee();i&&!i.reportNamespaces&&(i.reportNamespaces=new dee),i||KE(i,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const a=C.useMemo(()=>{var G;return{...aee(),...(G=i==null?void 0:i.options)==null?void 0:G.react,...e}},[i,e]),{useSuspense:o,keyPrefix:l}=a,c=s||((k=i==null?void 0:i.options)==null?void 0:k.defaultNS),u=eu(c)?[c]:c||["translation"],d=C.useMemo(()=>u,u);(M=(R=i==null?void 0:i.reportNamespaces)==null?void 0:R.addUsedNamespaces)==null||M.call(R,d);const h=C.useRef(0),f=C.useCallback(G=>{if(!i)return wee;const{bindI18n:Y,bindI18nStore:q}=a,X=()=>{h.current+=1,G()};return Y&&i.on(Y,X),q&&i.store.on(q,X),()=>{Y&&Y.split(" ").forEach(Z=>i.off(Z,X)),q&&q.split(" ").forEach(Z=>i.store.off(Z,X))}},[i,a]),m=C.useRef(),g=C.useCallback(()=>{if(!i)return Eee;const G=!!(i.isInitialized||i.initializedStoreOnce)&&d.every(ne=>ZZ(ne,i,a)),Y=e.lng||i.language,q=h.current,X=m.current;if(X&&X.ready===G&&X.lng===Y&&X.keyPrefix===l&&X.revision===q)return X;const oe={t:i.getFixedT(Y,a.nsMode==="fallback"?d:d[0],l),ready:G,lng:Y,keyPrefix:l,revision:q};return m.current=oe,oe},[i,d,l,a,e.lng]),[y,v]=C.useState(0),{t:_,ready:S}=xee.useSyncExternalStore(f,g,g);C.useEffect(()=>{if(i&&!S&&!o){const G=()=>v(Y=>Y+1);e.lng?tI(i,e.lng,d,G):HE(i,d,G)}},[i,e.lng,d,S,o,y]);const E=i||{},L=C.useRef(null),U=C.useRef(),P=G=>{const Y=Object.getOwnPropertyDescriptors(G);Y.__original&&delete Y.__original;const q=Object.create(Object.getPrototypeOf(G),Y);if(!Object.prototype.hasOwnProperty.call(q,"__original"))try{Object.defineProperty(q,"__original",{value:G,writable:!1,enumerable:!1,configurable:!1})}catch{}return q},I=C.useMemo(()=>{const G=E,Y=G==null?void 0:G.language;let q=G;G&&(L.current&&L.current.__original===G?U.current!==Y?(q=P(G),L.current=q,U.current=Y):q=L.current:(q=P(G),L.current=q,U.current=Y));const X=!S&&!o?(...oe)=>(KE(i,"USE_T_BEFORE_READY","useTranslation: t was called before ready. When using useSuspense: false, make sure to check the ready flag before using t."),_(...oe)):_,Z=[X,q,S];return Z.t=X,Z.i18n=q,Z.ready=S,Z},[_,E,S,E.resolvedLanguage,E.language,E.languages]);if(i&&o&&!S)throw new Promise(G=>{const Y=()=>G();e.lng?tI(i,e.lng,d,Y):HE(i,d,Y)});return I},Tee=3e3,Aee="nadiplay_splash_shown",Ree=({onFinish:t})=>{const[e,n]=C.useState(!0),r=C.useRef(null),{t:s}=wr();C.useEffect(()=>{const a=new Audio("/audio/Arrival_Queued.mp3");a.volume=.9,r.current=a,a.play().catch(()=>{});const o=window.setTimeout(()=>{n(!1)},Tee);return()=>{window.clearTimeout(o);try{a.pause()}catch{}}},[]);const i=()=>{try{sessionStorage.setItem(Aee,"1")}catch{}t()};return p.jsx(Lo,{onExitComplete:i,children:e&&p.jsxs(gt.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:[p.jsx("div",{className:"absolute inset-0 opacity-40 bg-cover bg-center",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),p.jsx("div",{className:"absolute inset-0 bg-background/50"}),p.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=>p.jsx(gt.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)),p.jsx(gt.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)=>p.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))}),p.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-6 px-6",children:[p.jsxs(gt.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:[p.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:p.jsx(ri,{className:"w-12 h-12 md:w-14 md:h-14 text-primary gold-glow",strokeWidth:1.2})}),p.jsx(gt.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)"}})]}),p.jsx(gt.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"}),p.jsx(gt.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:s("splash.tagline")}),p.jsx(gt.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:p.jsx(gt.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)"}})})]}),p.jsx(gt.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:s("splash.premiumTag")})]})})};/*! Capacitor: https://capacitorjs.com/ - MIT License */var gh;(function(t){t.Unimplemented="UNIMPLEMENTED",t.Unavailable="UNAVAILABLE"})(gh||(gh={}));class Fb extends Error{constructor(e,n,r){super(e),this.message=e,this.code=n,this.data=r}}const Cee=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"},kee=t=>{const e=t.CapacitorCustomPlatform||null,n=t.Capacitor||{},r=n.Plugins=n.Plugins||{},s=()=>e!==null?e.name:Cee(t),i=()=>s()!=="web",a=d=>{const h=c.get(d);return!!(h!=null&&h.platforms.has(s())||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 m=s(),g=o(d);let y;const v=async()=>(!y&&m in h?y=typeof h[m]=="function"?y=await h[m]():y=h[m]:e!==null&&!y&&"web"in h&&(y=typeof h.web=="function"?y=await h.web():y=h.web),y),_=(I,k)=>{var R,M;if(g){const G=g==null?void 0:g.methods.find(Y=>k===Y.name);if(G)return G.rtype==="promise"?Y=>n.nativePromise(d,k.toString(),Y):(Y,q)=>n.nativeCallback(d,k.toString(),Y,q);if(I)return(R=I[k])===null||R===void 0?void 0:R.bind(I)}else{if(I)return(M=I[k])===null||M===void 0?void 0:M.bind(I);throw new Fb(`"${d}" plugin is not implemented on ${m}`,gh.Unimplemented)}},S=I=>{let k;const R=(...M)=>{const G=v().then(Y=>{const q=_(Y,I);if(q){const X=q(...M);return k=X==null?void 0:X.remove,X}else throw new Fb(`"${d}.${I}()" is not implemented on ${m}`,gh.Unimplemented)});return I==="addListener"&&(G.remove=async()=>k()),G};return R.toString=()=>`${I.toString()}() { [capacitor code] }`,Object.defineProperty(R,"name",{value:I,writable:!1,configurable:!1}),R},E=S("addListener"),L=S("removeListener"),U=(I,k)=>{const R=E({eventName:I},k),M=async()=>{const Y=await R;L({eventName:I,callbackId:Y},k)},G=new Promise(Y=>R.then(()=>Y({remove:M})));return G.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await M()},G},P=new Proxy({},{get(I,k){switch(k){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return g?U:E;case"removeListener":return L;default:return S(k)}}});return r[d]=P,c.set(d,{name:d,proxy:P,platforms:new Set([...Object.keys(h),...g?[m]:[]])}),P};return n.convertFileSrc||(n.convertFileSrc=d=>d),n.getPlatform=s,n.handleError=l,n.isNativePlatform=i,n.isPluginAvailable=a,n.registerPlugin=u,n.Exception=Fb,n.DEBUG=!!n.DEBUG,n.isLoggingEnabled=!!n.isLoggingEnabled,n},Lee=t=>t.Capacitor=kee(t),rs=Lee(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),pu=rs.registerPlugin;class _3{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 i=this.windowListeners[e];i&&!i.registered&&this.addWindowListener(i),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 s=this.listeners[e];if(!s){if(r){let i=this.retainedEventArguments[e];i||(i=[]),i.push(n),this.retainedEventArguments[e]=i}return}s.forEach(i=>i(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 rs.Exception(e,gh.Unimplemented)}unavailable(e="not available"){return new rs.Exception(e,gh.Unavailable)}async removeListener(e,n){const r=this.listeners[e];if(!r)return;const s=r.indexOf(n);this.listeners[e].splice(s,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 nI=t=>encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),rI=t=>t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class Iee extends _3{async getCookies(){const e=document.cookie,n={};return e.split(";").forEach(r=>{if(r.length<=0)return;let[s,i]=r.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");s=rI(s).trim(),i=rI(i).trim(),n[s]=i}),n}async setCookie(e){try{const n=nI(e.key),r=nI(e.value),s=e.expires?`; expires=${e.expires.replace("expires=","")}`:"",i=(e.path||"/").replace("path=",""),a=e.url!=null&&e.url.length>0?`domain=${e.url}`:"";document.cookie=`${n}=${r||""}${s}; path=${i}; ${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)}}}pu("CapacitorCookies",{web:()=>new Iee});const Pee=async t=>new Promise((e,n)=>{const r=new FileReader;r.onload=()=>{const s=r.result;e(s.indexOf(",")>=0?s.split(",")[1]:s)},r.onerror=s=>n(s),r.readAsDataURL(t)}),Dee=(t={})=>{const e=Object.keys(t);return Object.keys(t).map(s=>s.toLocaleLowerCase()).reduce((s,i,a)=>(s[i]=t[e[a]],s),{})},Oee=(t,e=!0)=>t?Object.entries(t).reduce((r,s)=>{const[i,a]=s;let o,l;return Array.isArray(a)?(l="",a.forEach(c=>{o=e?encodeURIComponent(c):c,l+=`${i}=${o}&`}),l.slice(0,-1)):(o=e?encodeURIComponent(a):a,l=`${i}=${o}`),`${r}&${l}`},"").substr(1):null,Nee=(t,e={})=>{const n=Object.assign({method:t.method||"GET",headers:t.headers},e),s=Dee(t.headers)["content-type"]||"";if(typeof t.data=="string")n.body=t.data;else if(s.includes("application/x-www-form-urlencoded")){const i=new URLSearchParams;for(const[a,o]of Object.entries(t.data||{}))i.set(a,o);n.body=i.toString()}else if(s.includes("multipart/form-data")||t.data instanceof FormData){const i=new FormData;if(t.data instanceof FormData)t.data.forEach((o,l)=>{i.append(l,o)});else for(const o of Object.keys(t.data))i.append(o,t.data[o]);n.body=i;const a=new Headers(n.headers);a.delete("content-type"),n.headers=a}else(s.includes("application/json")||typeof t.data=="object")&&(n.body=JSON.stringify(t.data));return n};class Mee extends _3{async request(e){const n=Nee(e,e.webFetchExtra),r=Oee(e.params,e.shouldEncodeUrlParams),s=r?`${e.url}?${r}`:e.url,i=await fetch(s,n),a=i.headers.get("content-type")||"";let{responseType:o="text"}=i.ok?e:{};a.includes("application/json")&&(o="json");let l,c;switch(o){case"arraybuffer":case"blob":c=await i.blob(),l=await Pee(c);break;case"json":l=await i.json();break;case"document":case"text":default:l=await i.text()}const u={};return i.headers.forEach((d,h)=>{u[h]=d}),{data:l,headers:u,status:i.status,url:i.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 b3=pu("CapacitorHttp",{web:()=>new Mee}),$b={},Y1="nadi_auth_token",X1="nadi_auth_user",jee="https://4kmovies.vip/nadiplayer";function sI(t){if(t==null)return null;const e=String(t).trim();if(!e)return null;const n=e.match(/https?:\/\/[^\s\])>"']+/i);return n?n[0].replace(/\/+$/,""):null}const x3=sI($b==null?void 0:$b.VITE_BACKEND_URL)||sI("https://nadiplayer-edit.preview.emergentagent.com")||jee;typeof console<"u"&&console.info("[nadiAuth] API base URL =",x3);const Pl=()=>{try{return localStorage.getItem(Y1)}catch{return null}},iI=()=>{try{const t=localStorage.getItem(X1);return t?JSON.parse(t):null}catch{return null}},Uee=(t,e)=>{localStorage.setItem(Y1,t),localStorage.setItem(X1,JSON.stringify(e))},Vb=()=>{localStorage.removeItem(Y1),localStorage.removeItem(X1)};function aI(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 Yr(t,e,n,r=!1){const s={"Content-Type":"application/json"};if(r){const c=Pl();c&&(s.Authorization=`Bearer ${c}`)}const i=`${x3}${e}`;if(rs&&rs.isNativePlatform&&rs.isNativePlatform()){let c;try{c=await b3.request({url:i,method:t,headers:s,data:n??void 0,responseType:"json",readTimeout:3e4,connectTimeout:3e4})}catch(f){const m=f instanceof Error?f.message:String(f);throw new Error(`Network error reaching ${i}: ${m}`)}const u=c&&c.status||0,d=c&&c.data;let h=d;if(typeof d=="string")try{h=JSON.parse(d)}catch{h=null}if(u<200||u>=300){const m=aI(h==null?void 0:h.detail)||(typeof d=="string"&&d?`HTTP ${u}: ${d.slice(0,160)}`:`HTTP ${u} from ${i}`);throw new Error(m)}if(h===null){const f=typeof d=="string"?d.slice(0,160):"";throw new Error(f?`Unexpected non-JSON response from ${i}: ${f}`:`Empty response from ${i}`)}return h}let a;try{a=await fetch(i,{method:t,headers:s,body:n?JSON.stringify(n):void 0})}catch(c){const u=c instanceof Error?c.message:String(c);throw new Error(`Network error reaching ${i}: ${u}`)}let o="";try{o=await a.text()}catch{}let l=null;if(o)try{l=JSON.parse(o)}catch{}if(!a.ok){const u=aI(l==null?void 0:l.detail)||(o?`HTTP ${a.status}: ${o.slice(0,160)}`:`HTTP ${a.status} (empty body) from ${i}`);throw new Error(u)}if(l===null&&o)throw new Error(`Unexpected non-JSON response from ${i}: ${o.slice(0,160)}`);return l}const Bee=async(t,e)=>{const n=await Yr("POST","/api/auth/login",{username:t,password:e});if(!n||typeof n!="object")throw new Error("Login failed: empty response from server. Check that the backend URL is reachable and CORS is allowed.");const r=n,s=r&&r.access_token?r:r&&r.data&&r.data.access_token?r.data:null;if(!s||!s.access_token||!s.user)throw new Error("Login failed: server response is missing access_token or user. Verify your backend at /api/auth/login.");return{access_token:s.access_token,user:s.user}},oI=()=>Yr("GET","/api/auth/me",void 0,!0),S3=()=>Yr("GET","/api/subscription/status",void 0,!0),E3=()=>Yr("GET","/api/admin/users",void 0,!0),Fee=t=>Yr("POST","/api/admin/users",t,!0),Gb=(t,e)=>Yr("PUT",`/api/admin/users/${t}`,e,!0),$ee=t=>Yr("DELETE",`/api/admin/users/${t}`,void 0,!0),Vee=()=>Yr("GET","/api/admin/settings",void 0,!0),Gee=t=>Yr("PUT","/api/admin/settings",t,!0),w3=()=>Yr("GET","/api/shared-profiles",void 0,!0),P0=()=>Yr("GET","/api/public/playback-mode"),Kee=t=>Yr("POST","/api/devices/register-token",t,!0),Hee=t=>{const e=t.target_user_id?"/api/admin/notify-user":"/api/admin/broadcast-notification";return Yr("POST",e,t,!0)},zee=()=>Yr("GET","/api/admin/stats/live",void 0,!0),qee=()=>Yr("GET","/api/admin/stats/installs",void 0,!0),Wee=(t={})=>Yr("POST","/api/stats/heartbeat",t,!0),Yee=(t=20)=>Yr("GET",`/api/admin/broadcasts?limit=${t}`,void 0,!0);var T3={exports:{}};(function(t,e){((n,r)=>{t.exports=r()})(lR,function(){var n=function(b,T){return(n=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(N,j){N.__proto__=j}:function(N,j){for(var V in j)Object.prototype.hasOwnProperty.call(j,V)&&(N[V]=j[V])}))(b,T)},r=function(){return(r=Object.assign||function(b){for(var T,N=1,j=arguments.length;N<j;N++)for(var V in T=arguments[N])Object.prototype.hasOwnProperty.call(T,V)&&(b[V]=T[V]);return b}).apply(this,arguments)};function s(b,T,N){for(var j,V=0,W=T.length;V<W;V++)!j&&V in T||((j=j||Array.prototype.slice.call(T,0,V))[V]=T[V]);return b.concat(j||Array.prototype.slice.call(T))}var i=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:lR,a=Object.keys,o=Array.isArray;function l(b,T){return typeof T=="object"&&a(T).forEach(function(N){b[N]=T[N]}),b}typeof Promise>"u"||i.Promise||(i.Promise=Promise);var c=Object.getPrototypeOf,u={}.hasOwnProperty;function d(b,T){return u.call(b,T)}function h(b,T){typeof T=="function"&&(T=T(c(b))),(typeof Reflect>"u"?a:Reflect.ownKeys)(T).forEach(function(N){m(b,N,T[N])})}var f=Object.defineProperty;function m(b,T,N,j){f(b,T,l(N&&d(N,"get")&&typeof N.get=="function"?{get:N.get,set:N.set,configurable:!0}:{value:N,configurable:!0,writable:!0},j))}function g(b){return{from:function(T){return b.prototype=Object.create(T.prototype),m(b.prototype,"constructor",b),{extend:h.bind(null,b.prototype)}}}}var y=Object.getOwnPropertyDescriptor,v=[].slice;function _(b,T,N){return v.call(b,T,N)}function S(b,T){return T(b)}function E(b){if(!b)throw new Error("Assertion Failed")}function L(b){i.setImmediate?setImmediate(b):setTimeout(b,0)}function U(b,T){if(typeof T=="string"&&d(b,T))return b[T];if(!T)return b;if(typeof T!="string"){for(var N=[],j=0,V=T.length;j<V;++j){var W=U(b,T[j]);N.push(W)}return N}var ee,re=T.indexOf(".");return re===-1||(ee=b[T.substr(0,re)])==null?void 0:U(ee,T.substr(re+1))}function P(b,T,N){if(b&&T!==void 0&&!("isFrozen"in Object&&Object.isFrozen(b)))if(typeof T!="string"&&"length"in T){E(typeof N!="string"&&"length"in N);for(var j=0,V=T.length;j<V;++j)P(b,T[j],N[j])}else{var W,ee,re=T.indexOf(".");re!==-1?(W=T.substr(0,re),(re=T.substr(re+1))===""?N===void 0?o(b)&&!isNaN(parseInt(W))?b.splice(W,1):delete b[W]:b[W]=N:P(ee=(ee=b[W])&&d(b,W)?ee:b[W]={},re,N)):N===void 0?o(b)&&!isNaN(parseInt(T))?b.splice(T,1):delete b[T]:b[T]=N}}function I(b){var T,N={};for(T in b)d(b,T)&&(N[T]=b[T]);return N}var k=[].concat;function R(b){return k.apply([],b)}var Q="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(b){return["Int","Uint","Float"].map(function(T){return T+b+"Array"})}))).filter(function(b){return i[b]}),M=new Set(Q.map(function(b){return i[b]})),G=null;function Y(b){return G=new WeakMap,b=function T(N){if(!N||typeof N!="object")return N;var j=G.get(N);if(j)return j;if(o(N)){j=[],G.set(N,j);for(var V=0,W=N.length;V<W;++V)j.push(T(N[V]))}else if(M.has(N.constructor))j=N;else{var ee,re=c(N);for(ee in j=re===Object.prototype?{}:Object.create(re),G.set(N,j),N)d(N,ee)&&(j[ee]=T(N[ee]))}return j}(b),G=null,b}var q={}.toString;function X(b){return q.call(b).slice(8,-1)}var Z=typeof Symbol<"u"?Symbol.iterator:"@@iterator",oe=typeof Z=="symbol"?function(b){var T;return b!=null&&(T=b[Z])&&T.apply(b)}:function(){return null};function ne(b,T){T=b.indexOf(T),0<=T&&b.splice(T,1)}var H={};function K(b){var T,N,j,V;if(arguments.length===1){if(o(b))return b.slice();if(this===H&&typeof b=="string")return[b];if(V=oe(b))for(N=[];!(j=V.next()).done;)N.push(j.value);else{if(b==null)return[b];if(typeof(T=b.length)!="number")return[b];for(N=new Array(T);T--;)N[T]=b[T]}}else for(T=arguments.length,N=new Array(T);T--;)N[T]=arguments[T];return N}var J=typeof Symbol<"u"?function(b){return b[Symbol.toStringTag]==="AsyncFunction"}:function(){return!1},Q=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],ht=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(Q),ve={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 Te(b,T){this.name=b,this.message=T}function Ne(b,T){return b+". Errors: "+Object.keys(T).map(function(N){return T[N].toString()}).filter(function(N,j,V){return V.indexOf(N)===j}).join(`
`)}function Ke(b,T,N,j){this.failures=T,this.failedKeys=j,this.successCount=N,this.message=Ne(b,T)}function be(b,T){this.name="BulkError",this.failures=Object.keys(T).map(function(N){return T[N]}),this.failuresByPos=T,this.message=Ne(b,this.failures)}g(Te).from(Error).extend({toString:function(){return this.name+": "+this.message}}),g(Ke).from(Te),g(be).from(Te);var Pe=ht.reduce(function(b,T){return b[T]=T+"Error",b},{}),Ae=Te,we=ht.reduce(function(b,T){var N=T+"Error";function j(V,W){this.name=N,V?typeof V=="string"?(this.message="".concat(V).concat(W?`
 `+W:""),this.inner=W||null):typeof V=="object"&&(this.message="".concat(V.name," ").concat(V.message),this.inner=V):(this.message=ve[T]||N,this.inner=null)}return g(j).from(Ae),b[T]=j,b},{}),Ue=(we.Syntax=SyntaxError,we.Type=TypeError,we.Range=RangeError,Q.reduce(function(b,T){return b[T+"Error"]=we[T],b},{}));Q=ht.reduce(function(b,T){return["Syntax","Type","Range"].indexOf(T)===-1&&(b[T+"Error"]=we[T]),b},{});function Oe(){}function Dt(b){return b}function en(b,T){return b==null||b===Dt?T:function(N){return T(b(N))}}function wn(b,T){return function(){b.apply(this,arguments),T.apply(this,arguments)}}function it(b,T){return b===Oe?T:function(){var N=b.apply(this,arguments),j=(N!==void 0&&(arguments[0]=N),this.onsuccess),V=this.onerror,W=(this.onsuccess=null,this.onerror=null,T.apply(this,arguments));return j&&(this.onsuccess=this.onsuccess?wn(j,this.onsuccess):j),V&&(this.onerror=this.onerror?wn(V,this.onerror):V),W!==void 0?W:N}}function nn(b,T){return b===Oe?T:function(){b.apply(this,arguments);var N=this.onsuccess,j=this.onerror;this.onsuccess=this.onerror=null,T.apply(this,arguments),N&&(this.onsuccess=this.onsuccess?wn(N,this.onsuccess):N),j&&(this.onerror=this.onerror?wn(j,this.onerror):j)}}function mn(b,T){return b===Oe?T:function(V){var j=b.apply(this,arguments),V=(l(V,j),this.onsuccess),W=this.onerror,ee=(this.onsuccess=null,this.onerror=null,T.apply(this,arguments));return V&&(this.onsuccess=this.onsuccess?wn(V,this.onsuccess):V),W&&(this.onerror=this.onerror?wn(W,this.onerror):W),j===void 0?ee===void 0?void 0:ee:l(j,ee)}}function On(b,T){return b===Oe?T:function(){return T.apply(this,arguments)!==!1&&b.apply(this,arguments)}}function Cn(b,T){return b===Oe?T:function(){var N=b.apply(this,arguments);if(N&&typeof N.then=="function"){for(var j=this,V=arguments.length,W=new Array(V);V--;)W[V]=arguments[V];return N.then(function(){return T.apply(j,W)})}return T.apply(this,arguments)}}Q.ModifyError=Ke,Q.DexieError=Te,Q.BulkError=be;var ln=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function Nn(b){ln=b}var cr={},Ds=100,lt=typeof Promise>"u"?[]:(ht=Promise.resolve(),typeof crypto<"u"&&crypto.subtle?[lt=crypto.subtle.digest("SHA-512",new Uint8Array([0])),c(lt),ht]:[ht,c(ht),ht]),ht=lt[0],wu=lt[1],wu=wu&&wu.then,Vt=ht&&ht.constructor,Dr=!!lt[2],vs=function(b,T){Ua.push([b,T]),_s&&(queueMicrotask(cn),_s=!1)},Os=!0,_s=!0,ii=[],ea=[],ai=Dt,bs={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:Oe,pgp:!1,env:{},finalize:Oe},st=bs,Ua=[],Pi=0,Ba=[];function Qe(b){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var T=this._PSD=st;if(typeof b!="function"){if(b!==cr)throw new TypeError("Not a function");this._state=arguments[1],this._value=arguments[2],this._state===!1&&xs(this,this._value)}else this._state=null,this._value=null,++T.ref,function N(j,V){try{V(function(W){if(j._state===null){if(W===j)throw new TypeError("A promise cannot be resolved with itself.");var ee=j._lib&&Zn();W&&typeof W.then=="function"?N(j,function(re,he){W instanceof Qe?W._then(re,he):W.then(re,he)}):(j._state=!0,j._value=W,yu(j)),ee&&er()}},xs.bind(null,j))}catch(W){xs(j,W)}}(this,b)}var Jl={get:function(){var b=st,T=D;function N(j,V){var W=this,ee=!b.global&&(b!==st||T!==D),re=ee&&!O(),he=new Qe(function(Ee,pe){St(W,new Oo(ie(j,b,ee,re),ie(V,b,ee,re),Ee,pe,b))});return this._consoleTask&&(he._consoleTask=this._consoleTask),he}return N.prototype=cr,N},set:function(b){m(this,"then",b&&b.prototype===cr?Jl:{get:function(){return b},set:Jl.set})}};function Oo(b,T,N,j,V){this.onFulfilled=typeof b=="function"?b:null,this.onRejected=typeof T=="function"?T:null,this.resolve=N,this.reject=j,this.psd=V}function xs(b,T){var N,j;ea.push(T),b._state===null&&(N=b._lib&&Zn(),T=ai(T),b._state=!1,b._value=T,j=b,ii.some(function(V){return V._value===j._value})||ii.push(j),yu(b),N)&&er()}function yu(b){var T=b._listeners;b._listeners=[];for(var N=0,j=T.length;N<j;++N)St(b,T[N]);var V=b._PSD;--V.ref||V.finalize(),Pi===0&&(++Pi,vs(function(){--Pi==0&&mr()},[]))}function St(b,T){if(b._state===null)b._listeners.push(T);else{var N=b._state?T.onFulfilled:T.onRejected;if(N===null)return(b._state?T.resolve:T.reject)(b._value);++T.psd.ref,++Pi,vs(Gt,[N,b,T])}}function Gt(b,T,N){try{var j,V=T._value;!T._state&&ea.length&&(ea=[]),j=ln&&T._consoleTask?T._consoleTask.run(function(){return b(V)}):b(V),T._state||ea.indexOf(V)!==-1||(W=>{for(var ee=ii.length;ee;)if(ii[--ee]._value===W._value)return ii.splice(ee,1)})(T),N.resolve(j)}catch(W){N.reject(W)}finally{--Pi==0&&mr(),--N.psd.ref||N.psd.finalize()}}function cn(){te(bs,function(){Zn()&&er()})}function Zn(){var b=Os;return _s=Os=!1,b}function er(){var b,T,N;do for(;0<Ua.length;)for(b=Ua,Ua=[],N=b.length,T=0;T<N;++T){var j=b[T];j[0].apply(null,j[1])}while(0<Ua.length);_s=Os=!0}function mr(){for(var b=ii,T=(ii=[],b.forEach(function(j){j._PSD.onunhandled.call(null,j._value,j)}),Ba.slice(0)),N=T.length;N;)T[--N]()}function ss(b){return new Qe(cr,!1,b)}function kt(b,T){var N=st;return function(){var j=Zn(),V=st;try{return z(N,!0),b.apply(this,arguments)}catch(W){T&&T(W)}finally{z(V,!1),j&&er()}}}h(Qe.prototype,{then:Jl,_then:function(b,T){St(this,new Oo(null,null,b,T,st))},catch:function(b){var T,N;return arguments.length===1?this.then(null,b):(T=b,N=arguments[1],typeof T=="function"?this.then(null,function(j){return(j instanceof T?N:ss)(j)}):this.then(null,function(j){return(j&&j.name===T?N:ss)(j)}))},finally:function(b){return this.then(function(T){return Qe.resolve(b()).then(function(){return T})},function(T){return Qe.resolve(b()).then(function(){return ss(T)})})},timeout:function(b,T){var N=this;return b<1/0?new Qe(function(j,V){var W=setTimeout(function(){return V(new we.Timeout(T))},b);N.then(j,V).finally(clearTimeout.bind(null,W))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&m(Qe.prototype,Symbol.toStringTag,"Dexie.Promise"),bs.env=se(),h(Qe,{all:function(){var b=K.apply(null,arguments).map(F);return new Qe(function(T,N){b.length===0&&T([]);var j=b.length;b.forEach(function(V,W){return Qe.resolve(V).then(function(ee){b[W]=ee,--j||T(b)},N)})})},resolve:function(b){return b instanceof Qe?b:b&&typeof b.then=="function"?new Qe(function(T,N){b.then(T,N)}):new Qe(cr,!0,b)},reject:ss,race:function(){var b=K.apply(null,arguments).map(F);return new Qe(function(T,N){b.map(function(j){return Qe.resolve(j).then(T,N)})})},PSD:{get:function(){return st},set:function(b){return st=b}},totalEchoes:{get:function(){return D}},newPSD:w,usePSD:te,scheduler:{get:function(){return vs},set:function(b){vs=b}},rejectionMapper:{get:function(){return ai},set:function(b){ai=b}},follow:function(b,T){return new Qe(function(N,j){return w(function(V,W){var ee=st;ee.unhandleds=[],ee.onunhandled=W,ee.finalize=wn(function(){var re,he=this;re=function(){he.unhandleds.length===0?V():W(he.unhandleds[0])},Ba.push(function Ee(){re(),Ba.splice(Ba.indexOf(Ee),1)}),++Pi,vs(function(){--Pi==0&&mr()},[])},ee.finalize),b()},T,N,j)})}}),Vt&&(Vt.allSettled&&m(Qe,"allSettled",function(){var b=K.apply(null,arguments).map(F);return new Qe(function(T){b.length===0&&T([]);var N=b.length,j=new Array(N);b.forEach(function(V,W){return Qe.resolve(V).then(function(ee){return j[W]={status:"fulfilled",value:ee}},function(ee){return j[W]={status:"rejected",reason:ee}}).then(function(){return--N||T(j)})})})}),Vt.any&&typeof AggregateError<"u"&&m(Qe,"any",function(){var b=K.apply(null,arguments).map(F);return new Qe(function(T,N){b.length===0&&N(new AggregateError([]));var j=b.length,V=new Array(j);b.forEach(function(W,ee){return Qe.resolve(W).then(function(re){return T(re)},function(re){V[ee]=re,--j||N(new AggregateError(V))})})})}),Vt.withResolvers)&&(Qe.withResolvers=Vt.withResolvers);var an={awaits:0,echoes:0,id:0},o_=0,Mn=[],vu=0,D=0,A=0;function w(b,ee,N,j){var V=st,W=Object.create(V),ee=(W.parent=V,W.ref=0,W.global=!1,W.id=++A,bs.env,W.env=Dr?{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}:{},ee&&l(W,ee),++V.ref,W.finalize=function(){--this.parent.ref||this.parent.finalize()},te(W,b,N,j));return W.ref===0&&W.finalize(),ee}function x(){return an.id||(an.id=++o_),++an.awaits,an.echoes+=Ds,an.id}function O(){return!!an.awaits&&(--an.awaits==0&&(an.id=0),an.echoes=an.awaits*Ds,!0)}function F(b){return an.echoes&&b&&b.constructor===Vt?(x(),b.then(function(T){return O(),T},function(T){return O(),ae(T)})):b}function $(){var b=Mn[Mn.length-1];Mn.pop(),z(b,!1)}function z(b,T){var N,j,V=st;(T?!an.echoes||vu++&&b===st:!vu||--vu&&b===st)||queueMicrotask(T?(function(W){++D,an.echoes&&--an.echoes!=0||(an.echoes=an.awaits=an.id=0),Mn.push(st),z(W,!0)}).bind(null,b):$),b!==st&&(st=b,V===bs&&(bs.env=se()),Dr)&&(N=bs.env.Promise,j=b.env,V.global||b.global)&&(Object.defineProperty(i,"Promise",j.PromiseProp),N.all=j.all,N.race=j.race,N.resolve=j.resolve,N.reject=j.reject,j.allSettled&&(N.allSettled=j.allSettled),j.any)&&(N.any=j.any)}function se(){var b=i.Promise;return Dr?{Promise:b,PromiseProp:Object.getOwnPropertyDescriptor(i,"Promise"),all:b.all,race:b.race,allSettled:b.allSettled,any:b.any,resolve:b.resolve,reject:b.reject}:{}}function te(b,T,N,j,V){var W=st;try{return z(b,!0),T(N,j,V)}finally{z(W,!1)}}function ie(b,T,N,j){return typeof b!="function"?b:function(){var V=st;N&&x(),z(T,!0);try{return b.apply(this,arguments)}finally{z(V,!1),j&&queueMicrotask(O)}}}function le(b){Promise===Vt&&an.echoes===0?vu===0?b():enqueueNativeMicroTask(b):setTimeout(b,0)}(""+wu).indexOf("[native code]")===-1&&(x=O=Oe);var ae=Qe.reject,ce="",Ce="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",Me="String expected.",Le="__dbnames",Je="readonly",Ye="readwrite";function Ve(b,T){return b?T?function(){return b.apply(this,arguments)&&T.apply(this,arguments)}:b:T}var pt={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function Et(b){return typeof b!="string"||/\./.test(b)?function(T){return T}:function(T){return T[b]===void 0&&b in T&&delete(T=Y(T))[b],T}}function Xe(){throw we.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.")}function He(b,T){try{var N=Lt(b),j=Lt(T);if(N!==j)return N==="Array"?1:j==="Array"?-1:N==="binary"?1:j==="binary"?-1:N==="string"?1:j==="string"?-1:N==="Date"?1:j!=="Date"?NaN:-1;switch(N){case"number":case"Date":case"string":return T<b?1:b<T?-1:0;case"binary":for(var V=mt(b),W=mt(T),ee=V.length,re=W.length,he=ee<re?ee:re,Ee=0;Ee<he;++Ee)if(V[Ee]!==W[Ee])return V[Ee]<W[Ee]?-1:1;return ee===re?0:ee<re?-1:1;case"Array":for(var pe=b,de=T,fe=pe.length,_e=de.length,me=fe<_e?fe:_e,ge=0;ge<me;++ge){var ye=He(pe[ge],de[ge]);if(ye!==0)return ye}return fe===_e?0:fe<_e?-1:1}}catch{}return NaN}function Lt(b){var T=typeof b;return T=="object"&&(ArrayBuffer.isView(b)||(T=X(b))==="ArrayBuffer")?"binary":T}function mt(b){return b instanceof Uint8Array?b:ArrayBuffer.isView(b)?new Uint8Array(b.buffer,b.byteOffset,b.byteLength):new Uint8Array(b)}function vt(b,T,N){var j=b.schema.yProps;return j?(T&&0<N.numFailures&&(T=T.filter(function(V,W){return!N.failures[W]})),Promise.all(j.map(function(V){return V=V.updatesTable,T?b.db.table(V).where("k").anyOf(T).delete():b.db.table(V).clear()})).then(function(){return N})):N}tn.prototype.execute=function(b){var T=this["@@propmod"];if(T.add!==void 0){var N=T.add;if(o(N))return s(s([],o(b)?b:[],!0),N).sort();if(typeof N=="number")return(Number(b)||0)+N;if(typeof N=="bigint")try{return BigInt(b)+N}catch{return BigInt(0)+N}throw new TypeError("Invalid term ".concat(N))}if(T.remove!==void 0){var j=T.remove;if(o(j))return o(b)?b.filter(function(V){return!j.includes(V)}).sort():[];if(typeof j=="number")return Number(b)-j;if(typeof j=="bigint")try{return BigInt(b)-j}catch{return BigInt(0)-j}throw new TypeError("Invalid subtrahend ".concat(j))}return N=(N=T.replacePrefix)==null?void 0:N[0],N&&typeof b=="string"&&b.startsWith(N)?T.replacePrefix[1]+b.substring(N.length):b};var Ut=tn;function tn(b){this["@@propmod"]=b}function bt(b,T){for(var N=a(T),j=N.length,V=!1,W=0;W<j;++W){var ee=N[W],re=T[ee],he=U(b,ee);re instanceof Ut?(P(b,ee,re.execute(he)),V=!0):he!==re&&(P(b,ee,re),V=!0)}return V}yt.prototype._trans=function(b,T,N){var j=this._tx||st.trans,V=this.name,W=ln&&typeof console<"u"&&console.createTask&&console.createTask("Dexie: ".concat(b==="readonly"?"read":"write"," ").concat(this.name));function ee(Ee,pe,de){if(de.schema[V])return T(de.idbtrans,de);throw new we.NotFound("Table "+V+" not part of transaction")}var re=Zn();try{var he=j&&j.db._novip===this.db._novip?j===st.trans?j._promise(b,ee,N):w(function(){return j._promise(b,ee,N)},{trans:j,transless:st.transless||st}):function Ee(pe,de,fe,_e){if(pe.idbdb&&(pe._state.openComplete||st.letThrough||pe._vip)){var me=pe._createTransaction(de,fe,pe._dbSchema);try{me.create(),pe._state.PR1398_maxLoop=3}catch(ge){return ge.name===Pe.InvalidState&&pe.isOpen()&&0<--pe._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),pe.close({disableAutoOpen:!1}),pe.open().then(function(){return Ee(pe,de,fe,_e)})):ae(ge)}return me._promise(de,function(ge,ye){return w(function(){return st.trans=me,_e(ge,ye,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 we.DatabaseClosed(pe._state.dbOpenError));if(!pe._state.isBeingOpened){if(!pe._state.autoOpen)return ae(new we.DatabaseClosed);pe.open().catch(Oe)}return pe._state.dbReadyPromise.then(function(){return Ee(pe,de,fe,_e)})}(this.db,b,[this.name],ee);return W&&(he._consoleTask=W,he=he.catch(function(Ee){return console.trace(Ee),ae(Ee)})),he}finally{re&&er()}},yt.prototype.get=function(b,T){var N=this;return b&&b.constructor===Object?this.where(b).first(T):b==null?ae(new we.Type("Invalid argument to Table.get()")):this._trans("readonly",function(j){return N.core.get({trans:j,key:b}).then(function(V){return N.hook.reading.fire(V)})}).then(T)},yt.prototype.where=function(b){if(typeof b=="string")return new this.db.WhereClause(this,b);if(o(b))return new this.db.WhereClause(this,"[".concat(b.join("+"),"]"));var T=a(b);if(T.length===1)return this.where(T[0]).equals(b[T[0]]);var N=this.schema.indexes.concat(this.schema.primKey).filter(function(re){if(re.compound&&T.every(function(Ee){return 0<=re.keyPath.indexOf(Ee)})){for(var he=0;he<T.length;++he)if(T.indexOf(re.keyPath[he])===-1)return!1;return!0}return!1}).sort(function(re,he){return re.keyPath.length-he.keyPath.length})[0];if(N&&this.db._maxKey!==ce)return ee=N.keyPath.slice(0,T.length),this.where(ee).equals(ee.map(function(re){return b[re]}));!N&&ln&&console.warn("The query ".concat(JSON.stringify(b)," on ").concat(this.name," would benefit from a ")+"compound index [".concat(T.join("+"),"]"));var j=this.schema.idxByName;function V(re,he){return He(re,he)===0}var ee=T.reduce(function(pe,he){var Ee=pe[0],pe=pe[1],de=j[he],fe=b[he];return[Ee||de,Ee||!de?Ve(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]),W=ee[0],ee=ee[1];return W?this.where(W.name).equals(b[W.keyPath]).filter(ee):N?this.filter(ee):this.where(T).equals("")},yt.prototype.filter=function(b){return this.toCollection().and(b)},yt.prototype.count=function(b){return this.toCollection().count(b)},yt.prototype.offset=function(b){return this.toCollection().offset(b)},yt.prototype.limit=function(b){return this.toCollection().limit(b)},yt.prototype.each=function(b){return this.toCollection().each(b)},yt.prototype.toArray=function(b){return this.toCollection().toArray(b)},yt.prototype.toCollection=function(){return new this.db.Collection(new this.db.WhereClause(this))},yt.prototype.orderBy=function(b){return new this.db.Collection(new this.db.WhereClause(this,o(b)?"[".concat(b.join("+"),"]"):b))},yt.prototype.reverse=function(){return this.toCollection().reverse()},yt.prototype.mapToClass=function(b){for(var T=this.db,N=this.name,j=((this.schema.mappedClass=b).prototype instanceof Xe&&(b=(ee=>{var re=pe,he=ee;if(typeof he!="function"&&he!==null)throw new TypeError("Class extends value "+String(he)+" is not a constructor or null");function Ee(){this.constructor=re}function pe(){return ee!==null&&ee.apply(this,arguments)||this}return n(re,he),re.prototype=he===null?Object.create(he):(Ee.prototype=he.prototype,new Ee),Object.defineProperty(pe.prototype,"db",{get:function(){return T},enumerable:!1,configurable:!0}),pe.prototype.table=function(){return N},pe})(b)),new Set),V=b.prototype;V;V=c(V))Object.getOwnPropertyNames(V).forEach(function(ee){return j.add(ee)});function W(ee){if(!ee)return ee;var re,he=Object.create(b.prototype);for(re in ee)if(!j.has(re))try{he[re]=ee[re]}catch{}return he}return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=W,this.hook("reading",W),b},yt.prototype.defineClass=function(){return this.mapToClass(function(b){l(this,b)})},yt.prototype.add=function(b,T){var N=this,j=this.schema.primKey,V=j.auto,W=j.keyPath,ee=b;return W&&V&&(ee=Et(W)(b)),this._trans("readwrite",function(re){return N.core.mutate({trans:re,type:"add",keys:T!=null?[T]:null,values:[ee]})}).then(function(re){return re.numFailures?Qe.reject(re.failures[0]):re.lastResult}).then(function(re){if(W)try{P(b,W,re)}catch{}return re})},yt.prototype.upsert=function(b,T){var N=this,j=this.schema.primKey.keyPath;return this._trans("readwrite",function(V){return N.core.get({trans:V,key:b}).then(function(W){var ee=W??{};return bt(ee,T),j&&P(ee,j,b),N.core.mutate({trans:V,type:"put",values:[ee],keys:[b],upsert:!0,updates:{keys:[b],changeSpecs:[T]}}).then(function(re){return re.numFailures?Qe.reject(re.failures[0]):!!W})})})},yt.prototype.update=function(b,T){return typeof b!="object"||o(b)?this.where(":id").equals(b).modify(T):(b=U(b,this.schema.primKey.keyPath))===void 0?ae(new we.InvalidArgument("Given object does not contain its primary key")):this.where(":id").equals(b).modify(T)},yt.prototype.put=function(b,T){var N=this,j=this.schema.primKey,V=j.auto,W=j.keyPath,ee=b;return W&&V&&(ee=Et(W)(b)),this._trans("readwrite",function(re){return N.core.mutate({trans:re,type:"put",values:[ee],keys:T!=null?[T]:null})}).then(function(re){return re.numFailures?Qe.reject(re.failures[0]):re.lastResult}).then(function(re){if(W)try{P(b,W,re)}catch{}return re})},yt.prototype.delete=function(b){var T=this;return this._trans("readwrite",function(N){return T.core.mutate({trans:N,type:"delete",keys:[b]}).then(function(j){return vt(T,[b],j)}).then(function(j){return j.numFailures?Qe.reject(j.failures[0]):void 0})})},yt.prototype.clear=function(){var b=this;return this._trans("readwrite",function(T){return b.core.mutate({trans:T,type:"deleteRange",range:pt}).then(function(N){return vt(b,null,N)})}).then(function(T){return T.numFailures?Qe.reject(T.failures[0]):void 0})},yt.prototype.bulkGet=function(b){var T=this;return this._trans("readonly",function(N){return T.core.getMany({keys:b,trans:N}).then(function(j){return j.map(function(V){return T.hook.reading.fire(V)})})})},yt.prototype.bulkAdd=function(b,T,N){var j=this,V=Array.isArray(T)?T:void 0,W=(N=N||(V?void 0:T))?N.allKeys:void 0;return this._trans("readwrite",function(ee){var re=j.schema.primKey,Ee=re.auto,re=re.keyPath;if(re&&V)throw new we.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(V&&V.length!==b.length)throw new we.InvalidArgument("Arguments objects and keys must have the same length");var he=b.length,Ee=re&&Ee?b.map(Et(re)):b;return j.core.mutate({trans:ee,type:"add",keys:V,values:Ee,wantResults:W}).then(function(pe){var de=pe.numFailures,fe=pe.failures;if(de===0)return W?pe.results:pe.lastResult;throw new be("".concat(j.name,".bulkAdd(): ").concat(de," of ").concat(he," operations failed"),fe)})})},yt.prototype.bulkPut=function(b,T,N){var j=this,V=Array.isArray(T)?T:void 0,W=(N=N||(V?void 0:T))?N.allKeys:void 0;return this._trans("readwrite",function(ee){var re=j.schema.primKey,Ee=re.auto,re=re.keyPath;if(re&&V)throw new we.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(V&&V.length!==b.length)throw new we.InvalidArgument("Arguments objects and keys must have the same length");var he=b.length,Ee=re&&Ee?b.map(Et(re)):b;return j.core.mutate({trans:ee,type:"put",keys:V,values:Ee,wantResults:W}).then(function(pe){var de=pe.numFailures,fe=pe.failures;if(de===0)return W?pe.results:pe.lastResult;throw new be("".concat(j.name,".bulkPut(): ").concat(de," of ").concat(he," operations failed"),fe)})})},yt.prototype.bulkUpdate=function(b){var T=this,N=this.core,j=b.map(function(ee){return ee.key}),V=b.map(function(ee){return ee.changes}),W=[];return this._trans("readwrite",function(ee){return N.getMany({trans:ee,keys:j,cache:"clone"}).then(function(re){var he=[],Ee=[],pe=(b.forEach(function(de,fe){var _e=de.key,me=de.changes,ge=re[fe];if(ge){for(var ye=0,ke=Object.keys(me);ye<ke.length;ye++){var Re=ke[ye],Ie=me[Re];if(Re===T.schema.primKey.keyPath){if(He(Ie,_e)!==0)throw new we.Constraint("Cannot update primary key in bulkUpdate()")}else P(ge,Re,Ie)}W.push(fe),he.push(_e),Ee.push(ge)}}),he.length);return N.mutate({trans:ee,type:"put",keys:he,values:Ee,updates:{keys:j,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 ye,ke=ge[me],Re=W[Number(ke)];Re!=null&&(ye=_e[ke],delete _e[ke],_e[Re]=ye)}throw new be("".concat(T.name,".bulkUpdate(): ").concat(fe," of ").concat(pe," operations failed"),_e)})})})},yt.prototype.bulkDelete=function(b){var T=this,N=b.length;return this._trans("readwrite",function(j){return T.core.mutate({trans:j,type:"delete",keys:b}).then(function(V){return vt(T,b,V)})}).then(function(j){var V=j.numFailures,W=j.failures;if(V===0)return j.lastResult;throw new be("".concat(T.name,".bulkDelete(): ").concat(V," of ").concat(N," operations failed"),W)})};var Nt=yt;function yt(){}function Tn(b){function T(ee,re){if(re){for(var he=arguments.length,Ee=new Array(he-1);--he;)Ee[he-1]=arguments[he];return N[ee].subscribe.apply(null,Ee),b}if(typeof ee=="string")return N[ee]}var N={};T.addEventType=W;for(var j=1,V=arguments.length;j<V;++j)W(arguments[j]);return T;function W(ee,re,he){var Ee,pe;if(typeof ee!="object")return re=re||On,pe={subscribers:[],fire:he=he||Oe,subscribe:function(de){pe.subscribers.indexOf(de)===-1&&(pe.subscribers.push(de),pe.fire=re(pe.fire,de))},unsubscribe:function(de){pe.subscribers=pe.subscribers.filter(function(fe){return fe!==de}),pe.fire=pe.subscribers.reduce(re,he)}},N[ee]=T[ee]=pe;a(Ee=ee).forEach(function(de){var fe=Ee[de];if(o(fe))W(de,Ee[de][0],Ee[de][1]);else{if(fe!=="asap")throw new we.InvalidArgument("Invalid event config");var _e=W(de,Dt,function(){for(var me=arguments.length,ge=new Array(me);me--;)ge[me]=arguments[me];_e.subscribers.forEach(function(ye){L(function(){ye.apply(null,ge)})})})}})}}function Or(b,T){return g(T).from({prototype:b}),T}function $n(b,T){return!(b.filter||b.algorithm||b.or)&&(T?b.justLimit:!b.replayFilter)}function Nr(b,T){b.filter=Ve(b.filter,T)}function gr(b,T,N){var j=b.replayFilter;b.replayFilter=j?function(){return Ve(j(),T())}:T,b.justLimit=N&&!j}function tr(b,T){if(b.isPrimKey)return T.primaryKey;var N=T.getIndexByKeyPath(b.index);if(N)return N;throw new we.Schema("KeyPath "+b.index+" on object store "+T.name+" is not indexed")}function Tr(b,T,N){var j=tr(b,T.schema);return T.openCursor({trans:N,values:!b.keysOnly,reverse:b.dir==="prev",unique:!!b.unique,query:{index:j,range:b.range}})}function Ht(b,T,N,j){var V,W,ee=b.replayFilter?Ve(b.filter,b.replayFilter()):b.filter;return b.or?(V={},W=function(re,he,Ee){var pe,de;ee&&!ee(he,Ee,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(re,he,Ee))},Promise.all([b.or._iterate(W,N),oi(Tr(b,j,N),b.algorithm,W,!b.keysOnly&&b.valueMapper)])):oi(Tr(b,j,N),Ve(b.algorithm,ee),T,!b.keysOnly&&b.valueMapper)}function oi(b,T,N,j){var V=kt(j?function(W,ee,re){return N(j(W),ee,re)}:N);return b.then(function(W){if(W)return W.start(function(){var ee=function(){return W.continue()};T&&!T(W,function(re){return ee=re},function(re){W.stop(re),ee=Oe},function(re){W.fail(re),ee=Oe})||V(W.value,W,function(re){return ee=re}),ee()})})}zt.prototype._read=function(b,T){var N=this._ctx;return N.error?N.table._trans(null,ae.bind(null,N.error)):N.table._trans("readonly",b).then(T)},zt.prototype._write=function(b){var T=this._ctx;return T.error?T.table._trans(null,ae.bind(null,T.error)):T.table._trans("readwrite",b,"locked")},zt.prototype._addAlgorithm=function(b){var T=this._ctx;T.algorithm=Ve(T.algorithm,b)},zt.prototype._iterate=function(b,T){return Ht(this._ctx,b,T,this._ctx.table.core)},zt.prototype.clone=function(b){var T=Object.create(this.constructor.prototype),N=Object.create(this._ctx);return b&&l(N,b),T._ctx=N,T},zt.prototype.raw=function(){return this._ctx.valueMapper=null,this},zt.prototype.each=function(b){var T=this._ctx;return this._read(function(N){return Ht(T,b,N,T.table.core)})},zt.prototype.count=function(b){var T=this;return this._read(function(N){var j,V=T._ctx,W=V.table.core;return $n(V,!0)?W.count({trans:N,query:{index:tr(V,W.schema),range:V.range}}).then(function(ee){return Math.min(ee,V.limit)}):(j=0,Ht(V,function(){return++j,!1},N,W).then(function(){return j}))}).then(b)},zt.prototype.sortBy=function(b,T){var N=b.split(".").reverse(),j=N[0],V=N.length-1;function W(he,Ee){return Ee?W(he[N[Ee]],Ee-1):he[j]}var ee=this._ctx.dir==="next"?1:-1;function re(he,Ee){return He(W(he,V),W(Ee,V))*ee}return this.toArray(function(he){return he.sort(re)}).then(T)},zt.prototype.toArray=function(b){var T=this;return this._read(function(N){var j,V,W,ee=T._ctx;return $n(ee,!0)&&0<ee.limit?(j=ee.valueMapper,V=tr(ee,ee.table.core.schema),ee.table.core.query({trans:N,limit:ee.limit,values:!0,direction:ee.dir==="prev"?"prev":void 0,query:{index:V,range:ee.range}}).then(function(re){return re=re.result,j?re.map(j):re})):(W=[],Ht(ee,function(re){return W.push(re)},N,ee.table.core).then(function(){return W}))},b)},zt.prototype.offset=function(b){var T=this._ctx;return b<=0||(T.offset+=b,$n(T)?gr(T,function(){var N=b;return function(j,V){return N===0||(N===1?--N:V(function(){j.advance(N),N=0}),!1)}}):gr(T,function(){var N=b;return function(){return--N<0}})),this},zt.prototype.limit=function(b){return this._ctx.limit=Math.min(this._ctx.limit,b),gr(this._ctx,function(){var T=b;return function(N,j,V){return--T<=0&&j(V),0<=T}},!0),this},zt.prototype.until=function(b,T){return Nr(this._ctx,function(N,j,V){return!b(N.value)||(j(V),T)}),this},zt.prototype.first=function(b){return this.limit(1).toArray(function(T){return T[0]}).then(b)},zt.prototype.last=function(b){return this.reverse().first(b)},zt.prototype.filter=function(b){var T;return Nr(this._ctx,function(N){return b(N.value)}),(T=this._ctx).isMatch=Ve(T.isMatch,b),this},zt.prototype.and=function(b){return this.filter(b)},zt.prototype.or=function(b){return new this.db.WhereClause(this._ctx.table,b,this)},zt.prototype.reverse=function(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},zt.prototype.desc=function(){return this.reverse()},zt.prototype.eachKey=function(b){var T=this._ctx;return T.keysOnly=!T.isMatch,this.each(function(N,j){b(j.key,j)})},zt.prototype.eachUniqueKey=function(b){return this._ctx.unique="unique",this.eachKey(b)},zt.prototype.eachPrimaryKey=function(b){var T=this._ctx;return T.keysOnly=!T.isMatch,this.each(function(N,j){b(j.primaryKey,j)})},zt.prototype.keys=function(b){var T=this._ctx,N=(T.keysOnly=!T.isMatch,[]);return this.each(function(j,V){N.push(V.key)}).then(function(){return N}).then(b)},zt.prototype.primaryKeys=function(b){var T=this._ctx;if($n(T,!0)&&0<T.limit)return this._read(function(j){var V=tr(T,T.table.core.schema);return T.table.core.query({trans:j,values:!1,limit:T.limit,direction:T.dir==="prev"?"prev":void 0,query:{index:V,range:T.range}})}).then(function(j){return j.result}).then(b);T.keysOnly=!T.isMatch;var N=[];return this.each(function(j,V){N.push(V.primaryKey)}).then(function(){return N}).then(b)},zt.prototype.uniqueKeys=function(b){return this._ctx.unique="unique",this.keys(b)},zt.prototype.firstKey=function(b){return this.limit(1).keys(function(T){return T[0]}).then(b)},zt.prototype.lastKey=function(b){return this.reverse().firstKey(b)},zt.prototype.distinct=function(){var b,T=this._ctx,T=T.index&&T.table.schema.idxByName[T.index];return T&&T.multi&&(b={},Nr(this._ctx,function(j){var j=j.primaryKey.toString(),V=d(b,j);return b[j]=!0,!V})),this},zt.prototype.modify=function(b){var T=this,N=this._ctx;return this._write(function(j){function V(ge,ye){var ke=ye.failures;fe+=ge-ye.numFailures;for(var Re=0,Ie=a(ke);Re<Ie.length;Re++){var Fe=Ie[Re];de.push(ke[Fe])}}var W=typeof b=="function"?b:function(ge){return bt(ge,b)},ee=N.table.core,pe=ee.schema.primaryKey,re=pe.outbound,he=pe.extractKey,Ee=200,pe=T.db._options.modifyChunkSize,de=(pe&&(Ee=typeof pe=="object"?pe[ee.name]||pe["*"]||200:pe),[]),fe=0,_e=[],me=b===Hh;return T.clone().primaryKeys().then(function(ge){function ye(Re){var Ie=Math.min(Ee,ge.length-Re),Fe=ge.slice(Re,Re+Ie);return(me?Promise.resolve([]):ee.getMany({trans:j,keys:Fe,cache:"immutable"})).then(function(Ge){var We=[],ze=[],at=re?[]:null,qe=me?Fe:[];if(!me)for(var ct=0;ct<Ie;++ct){var $e=Ge[ct],Tt={value:Y($e),primKey:ge[Re+ct]};W.call(Tt,Tt.value,Tt)!==!1&&(Tt.value==null?qe.push(ge[Re+ct]):re||He(he($e),he(Tt.value))===0?(ze.push(Tt.value),re&&at.push(ge[Re+ct])):(qe.push(ge[Re+ct]),We.push(Tt.value)))}return Promise.resolve(0<We.length&&ee.mutate({trans:j,type:"add",values:We}).then(function(At){for(var Mt in At.failures)qe.splice(parseInt(Mt),1);V(We.length,At)})).then(function(){return(0<ze.length||ke&&typeof b=="object")&&ee.mutate({trans:j,type:"put",keys:at,values:ze,criteria:ke,changeSpec:typeof b!="function"&&b,isAdditionalChunk:0<Re}).then(function(At){return V(ze.length,At)})}).then(function(){return(0<qe.length||ke&&me)&&ee.mutate({trans:j,type:"delete",keys:qe,criteria:ke,isAdditionalChunk:0<Re}).then(function(At){return vt(N.table,qe,At)}).then(function(At){return V(qe.length,At)})}).then(function(){return ge.length>Re+Ie&&ye(Re+Ee)})})}var ke=$n(N)&&N.limit===1/0&&(typeof b!="function"||me)&&{index:N.index,range:N.range};return ye(0).then(function(){if(0<de.length)throw new Ke("Error modifying one or more objects",de,fe,_e);return ge.length})})})},zt.prototype.delete=function(){var b=this._ctx,T=b.range;return!$n(b)||b.table.schema.yProps||!b.isPrimKey&&T.type!==3?this.modify(Hh):this._write(function(N){var j=b.table.core.schema.primaryKey,V=T;return b.table.core.count({trans:N,query:{index:j,range:V}}).then(function(W){return b.table.core.mutate({trans:N,type:"deleteRange",range:V}).then(function(he){var re=he.failures,he=he.numFailures;if(he)throw new Ke("Could not delete some values",Object.keys(re).map(function(Ee){return re[Ee]}),W-he);return W-he})})})};var Di=zt;function zt(){}var Hh=function(b,T){return T.value=null};function l_(b,T){return b<T?-1:b===T?0:1}function Dm(b,T){return T<b?-1:b===T?0:1}function yr(b,T,N){return b=b instanceof No?new b.Collection(b):b,b._ctx.error=new(N||TypeError)(T),b}function li(b){return new b.Collection(b,function(){return _u("")}).limit(0)}function Zl(_e,T,N,j){var V,W,ee,re,he,Ee,pe,de=N.length;if(!N.every(function(ge){return typeof ge=="string"}))return yr(_e,Me);function fe(ge){V=ge==="next"?function(ke){return ke.toUpperCase()}:function(ke){return ke.toLowerCase()},W=ge==="next"?function(ke){return ke.toLowerCase()}:function(ke){return ke.toUpperCase()},ee=ge==="next"?l_:Dm;var ye=N.map(function(ke){return{lower:W(ke),upper:V(ke)}}).sort(function(ke,Re){return ee(ke.lower,Re.lower)});re=ye.map(function(ke){return ke.upper}),he=ye.map(function(ke){return ke.lower}),pe=(Ee=ge)==="next"?"":j}fe("next");var _e=new _e.Collection(_e,function(){return ci(re[0],he[de-1]+j)}),me=(_e._ondirectionchange=function(ge){fe(ge)},0);return _e._addAlgorithm(function(ge,ye,ke){var Re=ge.key;if(typeof Re=="string"){var Ie=W(Re);if(T(Ie,he,me))return!0;for(var Fe=null,Ge=me;Ge<de;++Ge){var We=((ze,at,qe,ct,$e,Tt)=>{for(var At=Math.min(ze.length,ct.length),Mt=-1,Xt=0;Xt<At;++Xt){var Ns=at[Xt];if(Ns!==ct[Xt])return $e(ze[Xt],qe[Xt])<0?ze.substr(0,Xt)+qe[Xt]+qe.substr(Xt+1):$e(ze[Xt],ct[Xt])<0?ze.substr(0,Xt)+ct[Xt]+qe.substr(Xt+1):0<=Mt?ze.substr(0,Mt)+at[Mt]+qe.substr(Mt+1):null;$e(ze[Xt],Ns)<0&&(Mt=Xt)}return At<ct.length&&Tt==="next"?ze+qe.substr(ze.length):At<ze.length&&Tt==="prev"?ze.substr(0,qe.length):Mt<0?null:ze.substr(0,Mt)+ct[Mt]+qe.substr(Mt+1)})(Re,Ie,re[Ge],he[Ge],ee,Ee);We===null&&Fe===null?me=Ge+1:(Fe===null||0<ee(Fe,We))&&(Fe=We)}ye(Fe!==null?function(){ge.continue(Fe+pe)}:ke)}return!1}),_e}function ci(b,T,N,j){return{type:2,lower:b,upper:T,lowerOpen:N,upperOpen:j}}function _u(b){return{type:1,lower:b,upper:b}}Object.defineProperty(Hn.prototype,"Collection",{get:function(){return this._ctx.table.db.Collection},enumerable:!1,configurable:!0}),Hn.prototype.between=function(b,T,N,j){N=N!==!1,j=j===!0;try{return 0<this._cmp(b,T)||this._cmp(b,T)===0&&(N||j)&&(!N||!j)?li(this):new this.Collection(this,function(){return ci(b,T,!N,!j)})}catch{return yr(this,Ce)}},Hn.prototype.equals=function(b){return b==null?yr(this,Ce):new this.Collection(this,function(){return _u(b)})},Hn.prototype.above=function(b){return b==null?yr(this,Ce):new this.Collection(this,function(){return ci(b,void 0,!0)})},Hn.prototype.aboveOrEqual=function(b){return b==null?yr(this,Ce):new this.Collection(this,function(){return ci(b,void 0,!1)})},Hn.prototype.below=function(b){return b==null?yr(this,Ce):new this.Collection(this,function(){return ci(void 0,b,!1,!0)})},Hn.prototype.belowOrEqual=function(b){return b==null?yr(this,Ce):new this.Collection(this,function(){return ci(void 0,b)})},Hn.prototype.startsWith=function(b){return typeof b!="string"?yr(this,Me):this.between(b,b+ce,!0,!0)},Hn.prototype.startsWithIgnoreCase=function(b){return b===""?this.startsWith(b):Zl(this,function(T,N){return T.indexOf(N[0])===0},[b],ce)},Hn.prototype.equalsIgnoreCase=function(b){return Zl(this,function(T,N){return T===N[0]},[b],"")},Hn.prototype.anyOfIgnoreCase=function(){var b=K.apply(H,arguments);return b.length===0?li(this):Zl(this,function(T,N){return N.indexOf(T)!==-1},b,"")},Hn.prototype.startsWithAnyOfIgnoreCase=function(){var b=K.apply(H,arguments);return b.length===0?li(this):Zl(this,function(T,N){return N.some(function(j){return T.indexOf(j)===0})},b,ce)},Hn.prototype.anyOf=function(){var b,T,N=this,j=K.apply(H,arguments),V=this._cmp;try{j.sort(V)}catch{return yr(this,Ce)}return j.length===0?li(this):((b=new this.Collection(this,function(){return ci(j[0],j[j.length-1])}))._ondirectionchange=function(W){V=W==="next"?N._ascending:N._descending,j.sort(V)},T=0,b._addAlgorithm(function(W,ee,re){for(var he=W.key;0<V(he,j[T]);)if(++T===j.length)return ee(re),!1;return V(he,j[T])===0||(ee(function(){W.continue(j[T])}),!1)}),b)},Hn.prototype.notEqual=function(b){return this.inAnyRange([[-1/0,b],[b,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})},Hn.prototype.noneOf=function(){var b=K.apply(H,arguments);if(b.length===0)return new this.Collection(this);try{b.sort(this._ascending)}catch{return yr(this,Ce)}var T=b.reduce(function(N,j){return N?N.concat([[N[N.length-1][1],j]]):[[-1/0,j]]},null);return T.push([b[b.length-1],this.db._maxKey]),this.inAnyRange(T,{includeLowers:!1,includeUppers:!1})},Hn.prototype.inAnyRange=function(b,ke){var N=this,j=this._cmp,V=this._ascending,W=this._descending,ee=this._min,re=this._max;if(b.length===0)return li(this);if(!b.every(function(Re){return Re[0]!==void 0&&Re[1]!==void 0&&V(Re[0],Re[1])<=0}))return yr(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",we.InvalidArgument);var he=!ke||ke.includeLowers!==!1,Ee=ke&&ke.includeUppers===!0,pe,de=V;function fe(Re,Ie){return de(Re[0],Ie[0])}try{(pe=b.reduce(function(Re,Ie){for(var Fe=0,Ge=Re.length;Fe<Ge;++Fe){var We=Re[Fe];if(j(Ie[0],We[1])<0&&0<j(Ie[1],We[0])){We[0]=ee(We[0],Ie[0]),We[1]=re(We[1],Ie[1]);break}}return Fe===Ge&&Re.push(Ie),Re},[])).sort(fe)}catch{return yr(this,Ce)}var _e=0,me=Ee?function(Re){return 0<V(Re,pe[_e][1])}:function(Re){return 0<=V(Re,pe[_e][1])},ge=he?function(Re){return 0<W(Re,pe[_e][0])}:function(Re){return 0<=W(Re,pe[_e][0])},ye=me,ke=new this.Collection(this,function(){return ci(pe[0][0],pe[pe.length-1][1],!he,!Ee)});return ke._ondirectionchange=function(Re){de=Re==="next"?(ye=me,V):(ye=ge,W),pe.sort(fe)},ke._addAlgorithm(function(Re,Ie,Fe){for(var Ge,We=Re.key;ye(We);)if(++_e===pe.length)return Ie(Fe),!1;return!me(Ge=We)&&!ge(Ge)||(N._cmp(We,pe[_e][1])===0||N._cmp(We,pe[_e][0])===0||Ie(function(){de===V?Re.continue(pe[_e][0]):Re.continue(pe[_e][1])}),!1)}),ke},Hn.prototype.startsWithAnyOf=function(){var b=K.apply(H,arguments);return b.every(function(T){return typeof T=="string"})?b.length===0?li(this):this.inAnyRange(b.map(function(T){return[T,T+ce]})):yr(this,"startsWithAnyOf() only works with strings")};var No=Hn;function Hn(){}function is(b){return kt(function(T){return ta(T),b(T.target.error),!1})}function ta(b){b.stopPropagation&&b.stopPropagation(),b.preventDefault&&b.preventDefault()}var Mo="storagemutated",bu="x-storagemutated-1",ui=Tn(null,Mo),Om=(di.prototype._lock=function(){return E(!st.global),++this._reculock,this._reculock!==1||st.global||(st.lockOwnerFor=this),this},di.prototype._unlock=function(){if(E(!st.global),--this._reculock==0)for(st.global||(st.lockOwnerFor=null);0<this._blockedFuncs.length&&!this._locked();){var b=this._blockedFuncs.shift();try{te(b[1],b[0])}catch{}}return this},di.prototype._locked=function(){return this._reculock&&st.lockOwnerFor!==this},di.prototype.create=function(b){var T=this;if(this.mode){var N=this.db.idbdb,j=this.db._state.dbOpenError;if(E(!this.idbtrans),!b&&!N)switch(j&&j.name){case"DatabaseClosedError":throw new we.DatabaseClosed(j);case"MissingAPIError":throw new we.MissingAPI(j.message,j);default:throw new we.OpenFailed(j)}if(!this.active)throw new we.TransactionInactive;E(this._completion._state===null),(b=this.idbtrans=b||(this.db.core||N).transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability})).onerror=kt(function(V){ta(V),T._reject(b.error)}),b.onabort=kt(function(V){ta(V),T.active&&T._reject(new we.Abort(b.error)),T.active=!1,T.on("abort").fire(V)}),b.oncomplete=kt(function(){T.active=!1,T._resolve(),"mutatedParts"in b&&ui.storagemutated.fire(b.mutatedParts)})}return this},di.prototype._promise=function(b,T,N){var j,V=this;return b==="readwrite"&&this.mode!=="readwrite"?ae(new we.ReadOnly("Transaction is readonly")):this.active?this._locked()?new Qe(function(W,ee){V._blockedFuncs.push([function(){V._promise(b,T,N).then(W,ee)},st])}):N?w(function(){var W=new Qe(function(ee,re){V._lock();var he=T(ee,re,V);he&&he.then&&he.then(ee,re)});return W.finally(function(){return V._unlock()}),W._lib=!0,W}):((j=new Qe(function(W,ee){var re=T(W,ee,V);re&&re.then&&re.then(W,ee)}))._lib=!0,j):ae(new we.TransactionInactive)},di.prototype._root=function(){return this.parent?this.parent._root():this},di.prototype.waitFor=function(b){var T,N=this._root(),j=Qe.resolve(b),V=(N._waitingFor?N._waitingFor=N._waitingFor.then(function(){return j}):(N._waitingFor=j,N._waitingQueue=[],T=N.idbtrans.objectStore(N.storeNames[0]),function W(){for(++N._spinCount;N._waitingQueue.length;)N._waitingQueue.shift()();N._waitingFor&&(T.get(-1/0).onsuccess=W)}()),N._waitingFor);return new Qe(function(W,ee){j.then(function(re){return N._waitingQueue.push(kt(W.bind(null,re)))},function(re){return N._waitingQueue.push(kt(ee.bind(null,re)))}).finally(function(){N._waitingFor===V&&(N._waitingFor=null)})})},di.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new we.Abort))},di.prototype.table=function(b){var T=this._memoizedTables||(this._memoizedTables={});if(d(T,b))return T[b];var N=this.schema[b];if(N)return(N=new this.db.Table(b,N,this)).core=this.db.core.table(b),T[b]=N;throw new we.NotFound("Table "+b+" not part of transaction")},di);function di(){}function xu(b,T,N,j,V,W,ee,re){return{name:b,keyPath:T,unique:N,multi:j,auto:V,compound:W,src:(N&&!ee?"&":"")+(j?"*":"")+(V?"++":"")+zh(T),type:re}}function zh(b){return typeof b=="string"?b:b?"["+[].join.call(b,"+")+"]":""}function Su(b,T,N){return{name:b,primKey:T,indexes:N,mappedClass:null,idxByName:(j=function(V){return[V.name,V]},N.reduce(function(V,W,ee){return W=j(W,ee),W&&(V[W[0]]=W[1]),V},{}))};var j}var qh=function(b){try{return b.only([[]]),qh=function(){return[[]]},[[]]}catch{return qh=function(){return ce},ce}};function c_(b){return b==null?function(){}:typeof b=="string"?(T=b).split(".").length===1?function(N){return N[T]}:function(N){return U(N,T)}:function(N){return U(N,b)};var T}function zA(b){return[].slice.call(b)}var S$=0;function Wh(b){return b==null?":id":typeof b=="string"?b:"[".concat(b.join("+"),"]")}function E$(b,T,ee){function j(ye){if(ye.type===3)return null;if(ye.type===4)throw new Error("Cannot convert never type to IDBKeyRange");var _e=ye.lower,me=ye.upper,ge=ye.lowerOpen,ye=ye.upperOpen;return _e===void 0?me===void 0?null:T.upperBound(me,!!ye):me===void 0?T.lowerBound(_e,!!ge):T.bound(_e,me,!!ge,!!ye)}function V(fe){var _e,me,ge=fe.name;return{name:ge,schema:fe,mutate:function(ye){var ke=ye.trans,Re=ye.type,Ie=ye.keys,Fe=ye.values,Ge=ye.range;return new Promise(function(We,ze){We=kt(We);var at=ke.objectStore(ge),qe=at.keyPath==null,ct=Re==="put"||Re==="add";if(!ct&&Re!=="delete"&&Re!=="deleteRange")throw new Error("Invalid operation type: "+Re);var $e,Tt=(Ie||Fe||{length:1}).length;if(Ie&&Fe&&Ie.length!==Fe.length)throw new Error("Given keys array must have same length as given values array.");if(Tt===0)return We({numFailures:0,failures:{},results:[],lastResult:void 0});function At(as){++Ns,ta(as)}var Mt=[],Xt=[],Ns=0;if(Re==="deleteRange"){if(Ge.type===4)return We({numFailures:Ns,failures:Xt,results:[],lastResult:void 0});Ge.type===3?Mt.push($e=at.clear()):Mt.push($e=at.delete(j(Ge)))}else{var qe=ct?qe?[Fe,Ie]:[Fe,null]:[Ie,null],Ot=qe[0],Qr=qe[1];if(ct)for(var Jr=0;Jr<Tt;++Jr)Mt.push($e=Qr&&Qr[Jr]!==void 0?at[Re](Ot[Jr],Qr[Jr]):at[Re](Ot[Jr])),$e.onerror=At;else for(Jr=0;Jr<Tt;++Jr)Mt.push($e=at[Re](Ot[Jr])),$e.onerror=At}function zm(as){as=as.target.result,Mt.forEach(function(nc,R_){return nc.error!=null&&(Xt[R_]=nc.error)}),We({numFailures:Ns,failures:Xt,results:Re==="delete"?Ie:Mt.map(function(nc){return nc.result}),lastResult:as})}$e.onerror=function(as){At(as),zm(as)},$e.onsuccess=zm})},getMany:function(ye){var ke=ye.trans,Re=ye.keys;return new Promise(function(Ie,Fe){Ie=kt(Ie);for(var Ge,We=ke.objectStore(ge),ze=Re.length,at=new Array(ze),qe=0,ct=0,$e=function(Mt){Mt=Mt.target,at[Mt._pos]=Mt.result,++ct===qe&&Ie(at)},Tt=is(Fe),At=0;At<ze;++At)Re[At]!=null&&((Ge=We.get(Re[At]))._pos=At,Ge.onsuccess=$e,Ge.onerror=Tt,++qe);qe===0&&Ie(at)})},get:function(ye){var ke=ye.trans,Re=ye.key;return new Promise(function(Ie,Fe){Ie=kt(Ie);var Ge=ke.objectStore(ge).get(Re);Ge.onsuccess=function(We){return Ie(We.target.result)},Ge.onerror=is(Fe)})},query:(_e=he,me=Ee,function(ye){return new Promise(function(ke,Re){ke=kt(ke);var Ie,Fe,Ge,We,Tt=ye.trans,ze=ye.values,at=ye.limit,$e=ye.query,qe=(qe=ye.direction)!=null?qe:"next",ct=at===1/0?void 0:at,At=$e.index,$e=$e.range,Tt=Tt.objectStore(ge),Tt=At.isPrimaryKey?Tt:Tt.index(At.name),At=j($e);if(at===0)return ke({result:[]});me?($e={query:At,count:ct,direction:qe},(Ie=ze?Tt.getAll($e):Tt.getAllKeys($e)).onsuccess=function(Mt){return ke({result:Mt.target.result})},Ie.onerror=is(Re)):_e&&qe==="next"?((Ie=ze?Tt.getAll(At,ct):Tt.getAllKeys(At,ct)).onsuccess=function(Mt){return ke({result:Mt.target.result})},Ie.onerror=is(Re)):(Fe=0,Ge=!ze&&"openKeyCursor"in Tt?Tt.openKeyCursor(At,qe):Tt.openCursor(At,qe),We=[],Ge.onsuccess=function(){var Mt=Ge.result;return!Mt||(We.push(ze?Mt.value:Mt.primaryKey),++Fe===at)?ke({result:We}):void Mt.continue()},Ge.onerror=is(Re))})}),openCursor:function(ye){var ke=ye.trans,Re=ye.values,Ie=ye.query,Fe=ye.reverse,Ge=ye.unique;return new Promise(function(We,ze){We=kt(We);var ct=Ie.index,at=Ie.range,qe=ke.objectStore(ge),qe=ct.isPrimaryKey?qe:qe.index(ct.name),ct=Fe?Ge?"prevunique":"prev":Ge?"nextunique":"next",$e=!Re&&"openKeyCursor"in qe?qe.openKeyCursor(j(at),ct):qe.openCursor(j(at),ct);$e.onerror=is(ze),$e.onsuccess=kt(function(Tt){var At,Mt,Xt,Ns,Ot=$e.result;Ot?(Ot.___id=++S$,Ot.done=!1,At=Ot.continue.bind(Ot),Mt=(Mt=Ot.continuePrimaryKey)&&Mt.bind(Ot),Xt=Ot.advance.bind(Ot),Ns=function(){throw new Error("Cursor not stopped")},Ot.trans=ke,Ot.stop=Ot.continue=Ot.continuePrimaryKey=Ot.advance=function(){throw new Error("Cursor not started")},Ot.fail=kt(ze),Ot.next=function(){var Qr=this,Jr=1;return this.start(function(){return Jr--?Qr.continue():Qr.stop()}).then(function(){return Qr})},Ot.start=function(Qr){function Jr(){if($e.result)try{Qr()}catch(as){Ot.fail(as)}else Ot.done=!0,Ot.start=function(){throw new Error("Cursor behind last entry")},Ot.stop()}var zm=new Promise(function(as,nc){as=kt(as),$e.onerror=is(nc),Ot.fail=nc,Ot.stop=function(R_){Ot.stop=Ot.continue=Ot.continuePrimaryKey=Ot.advance=Ns,as(R_)}});return $e.onsuccess=kt(function(as){$e.onsuccess=Jr,Jr()}),Ot.continue=At,Ot.continuePrimaryKey=Mt,Ot.advance=Xt,Jr(),zm},We(Ot)):We(null)},ze)})},count:function(ye){var ke=ye.query,Re=ye.trans,Ie=ke.index,Fe=ke.range;return new Promise(function(Ge,We){var ze=Re.objectStore(ge),ze=Ie.isPrimaryKey?ze:ze.index(Ie.name),at=j(Fe),at=at?ze.count(at):ze.count();at.onsuccess=kt(function(qe){return Ge(qe.target.result)}),at.onerror=is(We)})}}}W=ee,re=zA((ee=b).objectStoreNames),pe=0<re.length?W.objectStore(re[0]):{};var W,ee={schema:{name:ee.name,tables:re.map(function(fe){return W.objectStore(fe)}).map(function(fe){var _e=fe.keyPath,me=fe.autoIncrement,ye=o(_e),ge={},ye={name:fe.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:_e==null,compound:ye,keyPath:_e,autoIncrement:me,unique:!0,extractKey:c_(_e)},indexes:zA(fe.indexNames).map(function(ke){return fe.index(ke)}).map(function(Fe){var Ge=Fe.name,Re=Fe.unique,Ie=Fe.multiEntry,Fe=Fe.keyPath,Ge={name:Ge,compound:o(Fe),keyPath:Fe,unique:Re,multiEntry:Ie,extractKey:c_(Fe)};return ge[Wh(Fe)]=Ge}),getIndexByKeyPath:function(ke){return ge[Wh(ke)]}};return ge[":id"]=ye.primaryKey,_e!=null&&(ge[Wh(_e)]=ye.primaryKey),ye})},hasGetAll:0<re.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},re=ee.schema,he=ee.hasGetAll,Ee=ee.hasIdb3Features,pe=re.tables.map(V),de={};return pe.forEach(function(fe){return de[fe.name]=fe}),{stack:"dbcore",transaction:b.transaction.bind(b),table:function(fe){if(de[fe])return de[fe];throw new Error("Table '".concat(fe,"' not found"))},MIN_KEY:-1/0,MAX_KEY:qh(T),schema:re}}function w$(b,T,N,j){return N=N.IDBKeyRange,T=E$(T,N,j),{dbcore:b.dbcore.reduce(function(V,W){return W=W.create,r(r({},V),W(V))},T)}}function Nm(b,T){var N=T.db,N=w$(b._middlewares,N,b._deps,T);b.core=N.dbcore,b.tables.forEach(function(j){var V=j.name;b.core.schema.tables.some(function(W){return W.name===V})&&(j.core=b.core.table(V),b[V]instanceof b.Table)&&(b[V].core=j.core)})}function Mm(b,T,N,j){N.forEach(function(V){var W=j[V];T.forEach(function(ee){var re=function he(Ee,pe){return y(Ee,pe)||(Ee=c(Ee))&&he(Ee,pe)}(ee,V);(!re||"value"in re&&re.value===void 0)&&(ee===b.Transaction.prototype||ee instanceof b.Transaction?m(ee,V,{get:function(){return this.table(V)},set:function(he){f(this,V,{value:he,writable:!0,configurable:!0,enumerable:!0})}}):ee[V]=new b.Table(V,W))})})}function u_(b,T){T.forEach(function(N){for(var j in N)N[j]instanceof b.Table&&delete N[j]})}function T$(b,T){return b._cfg.version-T._cfg.version}function A$(b,T,N,j){var V=b._dbSchema,W=(N.objectStoreNames.contains("$meta")&&!V.$meta&&(V.$meta=Su("$meta",WA("")[0],[]),b._storeNames.push("$meta")),b._createTransaction("readwrite",b._storeNames,V)),ee=(W.create(N),W._completion.catch(j),W._reject.bind(W)),re=st.transless||st;w(function(){if(st.trans=W,st.transless=re,T!==0)return Nm(b,N),Ee=T,((he=W).storeNames.includes("$meta")?he.table("$meta").get("version").then(function(pe){return pe??Ee}):Qe.resolve(Ee)).then(function(ye){var de=b,fe=ye,_e=W,me=N,ge=[],ye=de._versions,ke=de._dbSchema=Um(0,de.idbdb,me);return(ye=ye.filter(function(Re){return Re._cfg.version>=fe})).length===0?Qe.resolve():(ye.forEach(function(Re){ge.push(function(){var Ie,Fe,Ge,We=ke,ze=Re._cfg.dbschema,at=(Bm(de,We,me),Bm(de,ze,me),ke=de._dbSchema=ze,d_(We,ze)),qe=(at.add.forEach(function(ct){h_(me,ct[0],ct[1].primKey,ct[1].indexes)}),at.change.forEach(function(ct){if(ct.recreate)throw new we.Upgrade("Not yet support for changing primary key");var $e=me.objectStore(ct.name);ct.add.forEach(function(Tt){return jm($e,Tt)}),ct.change.forEach(function(Tt){$e.deleteIndex(Tt.name),jm($e,Tt)}),ct.del.forEach(function(Tt){return $e.deleteIndex(Tt)})}),Re._cfg.contentUpgrade);if(qe&&Re._cfg.version>fe)return Nm(de,me),_e._memoizedTables={},Ie=I(ze),at.del.forEach(function(ct){Ie[ct]=We[ct]}),u_(de,[de.Transaction.prototype]),Mm(de,[de.Transaction.prototype],a(Ie),Ie),_e.schema=Ie,(Fe=J(qe))&&x(),ze=Qe.follow(function(){var ct;(Ge=qe(_e))&&Fe&&(ct=O.bind(null,null),Ge.then(ct,ct))}),Ge&&typeof Ge.then=="function"?Qe.resolve(Ge):ze.then(function(){return Ge})}),ge.push(function(Ie){var Fe,Ge,We=Re._cfg.dbschema;Fe=We,Ge=Ie,[].slice.call(Ge.db.objectStoreNames).forEach(function(ze){return Fe[ze]==null&&Ge.db.deleteObjectStore(ze)}),u_(de,[de.Transaction.prototype]),Mm(de,[de.Transaction.prototype],de._storeNames,de._dbSchema),_e.schema=de._dbSchema}),ge.push(function(Ie){de.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(de.idbdb.version/10)===Re._cfg.version?(de.idbdb.deleteObjectStore("$meta"),delete de._dbSchema.$meta,de._storeNames=de._storeNames.filter(function(Fe){return Fe!=="$meta"})):Ie.objectStore("$meta").put(Re._cfg.version,"version"))})}),function Re(){return ge.length?Qe.resolve(ge.shift()(_e.idbtrans)).then(Re):Qe.resolve()}().then(function(){qA(ke,me)}))}).catch(ee);var he,Ee;a(V).forEach(function(pe){h_(N,pe,V[pe].primKey,V[pe].indexes)}),Nm(b,N),Qe.follow(function(){return b.on.populate.fire(W)}).catch(ee)})}function R$(b,T){qA(b._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=Um(0,b.idbdb,T);Bm(b,b._dbSchema,T);for(var j=0,V=d_(N,b._dbSchema).change;j<V.length;j++){var W=(ee=>{if(ee.change.length||ee.recreate)return console.warn("Unable to patch indexes of table ".concat(ee.name," because it has changes on the type of index or primary key.")),{value:void 0};var re=T.objectStore(ee.name);ee.add.forEach(function(he){ln&&console.debug("Dexie upgrade patch: Creating missing index ".concat(ee.name,".").concat(he.src)),jm(re,he)})})(V[j]);if(typeof W=="object")return W.value}}function d_(b,T){var N,j={del:[],add:[],change:[]};for(N in b)T[N]||j.del.push(N);for(N in T){var V=b[N],W=T[N];if(V){var ee={name:N,def:W,recreate:!1,del:[],add:[],change:[]};if(""+(V.primKey.keyPath||"")!=""+(W.primKey.keyPath||"")||V.primKey.auto!==W.primKey.auto)ee.recreate=!0,j.change.push(ee);else{var re=V.idxByName,he=W.idxByName,Ee=void 0;for(Ee in re)he[Ee]||ee.del.push(Ee);for(Ee in he){var pe=re[Ee],de=he[Ee];pe?pe.src!==de.src&&ee.change.push(de):ee.add.push(de)}(0<ee.del.length||0<ee.add.length||0<ee.change.length)&&j.change.push(ee)}}else j.add.push([N,W])}return j}function h_(b,T,N,j){var V=b.db.createObjectStore(T,N.keyPath?{keyPath:N.keyPath,autoIncrement:N.auto}:{autoIncrement:N.auto});j.forEach(function(W){return jm(V,W)})}function qA(b,T){a(b).forEach(function(N){T.db.objectStoreNames.contains(N)||(ln&&console.debug("Dexie: Creating missing table",N),h_(T,N,b[N].primKey,b[N].indexes))})}function jm(b,T){b.createIndex(T.name,T.keyPath,{unique:T.unique,multiEntry:T.multi})}function Um(b,T,N){var j={};return _(T.objectStoreNames,0).forEach(function(V){for(var W=N.objectStore(V),ee=xu(zh(Ee=W.keyPath),Ee||"",!0,!1,!!W.autoIncrement,Ee&&typeof Ee!="string",!0),re=[],he=0;he<W.indexNames.length;++he){var pe=W.index(W.indexNames[he]),Ee=pe.keyPath,pe=xu(pe.name,Ee,!!pe.unique,!!pe.multiEntry,!1,Ee&&typeof Ee!="string",!1);re.push(pe)}j[V]=Su(V,ee,re)}),j}function Bm(b,T,N){for(var j=N.db.objectStoreNames,V=0;V<j.length;++V){var W=j[V],ee=N.objectStore(W);b._hasGetAll="getAll"in ee;for(var re=0;re<ee.indexNames.length;++re){var he,Ee=ee.indexNames[re],pe=ee.index(Ee).keyPath,pe=typeof pe=="string"?pe:"["+_(pe).join("+")+"]";T[W]&&(he=T[W].idxByName[pe])&&(he.name=Ee,delete T[W].idxByName[pe],T[W].idxByName[Ee]=he)}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&i.WorkerGlobalScope&&i instanceof i.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(b._hasGetAll=!1)}function WA(b){return b.split(",").map(function(T,N){var V=T.split(":"),j=(j=V[1])==null?void 0:j.trim(),V=(T=V[0].trim()).replace(/([&*]|\+\+)/g,""),W=/^\[/.test(V)?V.match(/^\[(.*)\]$/)[1].split("+"):V;return xu(V,W||null,/\&/.test(T),/\*/.test(T),/\+\+/.test(T),o(W),N===0,j)})}Eu.prototype._createTableSchema=Su,Eu.prototype._parseIndexSyntax=WA,Eu.prototype._parseStoresSpec=function(b,T){var N=this;a(b).forEach(function(j){if(b[j]!==null){var V=N._parseIndexSyntax(b[j]),W=V.shift();if(!W)throw new we.Schema("Invalid schema for table "+j+": "+b[j]);if(W.unique=!0,W.multi)throw new we.Schema("Primary key cannot be multiEntry*");V.forEach(function(ee){if(ee.auto)throw new we.Schema("Only primary key can be marked as autoIncrement (++)");if(!ee.keyPath)throw new we.Schema("Index must have a name and cannot be an empty string")}),W=N._createTableSchema(j,W,V),T[j]=W}})},Eu.prototype.stores=function(N){var T=this.db,N=(this._cfg.storesSource=this._cfg.storesSource?l(this._cfg.storesSource,N):N,T._versions),j={},V={};return N.forEach(function(W){l(j,W._cfg.storesSource),V=W._cfg.dbschema={},W._parseStoresSpec(j,V)}),T._dbSchema=V,u_(T,[T._allTables,T,T.Transaction.prototype]),Mm(T,[T._allTables,T,T.Transaction.prototype,this._cfg.tables],a(V),V),T._storeNames=a(V),this},Eu.prototype.upgrade=function(b){return this._cfg.contentUpgrade=Cn(this._cfg.contentUpgrade||Oe,b),this};var C$=Eu;function Eu(){}var Yh=(()=>{var b,T,N;return typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"?(b=new Set,T=new FinalizationRegistry(function(j){b.delete(j)}),{toArray:function(){return Array.from(b).map(function(j){return j.deref()}).filter(function(j){return j!==void 0})},add:function(j){var V=new WeakRef(j._novip);b.add(V),T.register(j._novip,V,V),b.size>j._options.maxConnections&&(V=b.values().next().value,b.delete(V),T.unregister(V))},remove:function(j){if(j)for(var V=b.values(),W=V.next();!W.done;){var ee=W.value;if(ee.deref()===j._novip)return b.delete(ee),void T.unregister(ee);W=V.next()}}}):(N=[],{toArray:function(){return N},add:function(j){N.push(j._novip)},remove:function(j){j&&(j=N.indexOf(j._novip))!==-1&&N.splice(j,1)}})})();function f_(b,T){var N=b._dbNamesDB;return N||(N=b._dbNamesDB=new Fa(Le,{addons:[],indexedDB:b,IDBKeyRange:T})).version(1).stores({dbnames:"name"}),N.table("dbnames")}function p_(b){return b&&typeof b.databases=="function"}function m_(b){return w(function(){return st.letThrough=!0,b()})}function g_(b){return!("from"in b)}var Xr=function(b,T){var N;if(!this)return N=new Xr,b&&"d"in b&&l(N,b),N;l(this,arguments.length?{d:1,from:b,to:1<arguments.length?T:b}:{d:0})};function Xh(b,T,N){var j=He(T,N);if(!isNaN(j)){if(0<j)throw RangeError();if(g_(b))return l(b,{from:T,to:N,d:1});var j=b.l,V=b.r;if(He(N,b.from)<0)return j?Xh(j,T,N):b.l={from:T,to:N,d:1,l:null,r:null},XA(b);if(0<He(T,b.to))return V?Xh(V,T,N):b.r={from:T,to:N,d:1,l:null,r:null},XA(b);He(T,b.from)<0&&(b.from=T,b.l=null,b.d=V?V.d+1:1),0<He(N,b.to)&&(b.to=N,b.r=null,b.d=b.l?b.l.d+1:1),T=!b.r,j&&!b.l&&Qh(b,j),V&&T&&Qh(b,V)}}function Qh(b,T){g_(T)||function N(j,V){var W=V.from,ee=V.l,re=V.r;Xh(j,W,V.to),ee&&N(j,ee),re&&N(j,re)}(b,T)}function YA(b,T){var N=Fm(T),j=N.next();if(!j.done)for(var V=j.value,W=Fm(b),ee=W.next(V.from),re=ee.value;!j.done&&!ee.done;){if(He(re.from,V.to)<=0&&0<=He(re.to,V.from))return!0;He(V.from,re.from)<0?V=(j=N.next(re.from)).value:re=(ee=W.next(V.from)).value}return!1}function Fm(b){var T=g_(b)?null:{s:0,n:b};return{next:function(N){for(var j=0<arguments.length;T;)switch(T.s){case 0:if(T.s=1,j)for(;T.n.l&&He(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,!j||He(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 XA(b){var T,N,j,V=(((V=b.r)==null?void 0:V.d)||0)-(((V=b.l)==null?void 0:V.d)||0),V=1<V?"r":V<-1?"l":"";V&&(T=V=="r"?"l":"r",N=r({},b),j=b[V],b.from=j.from,b.to=j.to,b[V]=j[V],N[V]=j[T],(b[T]=N).d=QA(N)),b.d=QA(b)}function QA(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 $m(b,T){return a(T).forEach(function(N){b[N]?Qh(b[N],T[N]):b[N]=function j(V){var W,ee,re={};for(W in V)d(V,W)&&(ee=V[W],re[W]=!ee||typeof ee!="object"||M.has(ee.constructor)?ee:j(ee));return re}(T[N])}),b}function y_(b,T){return b.all||T.all||Object.keys(b).some(function(N){return T[N]&&YA(T[N],b[N])})}h(Xr.prototype,((ht={add:function(b){return Qh(this,b),this},addKey:function(b){return Xh(this,b,b),this},addKeys:function(b){var T=this;return b.forEach(function(N){return Xh(T,N,N)}),this},hasKey:function(b){var T=Fm(this).next(b).value;return T&&He(T.from,b)<=0&&0<=He(T.to,b)}})[Z]=function(){return Fm(this)},ht));var ec={},v_={},__=!1;function Vm(b){$m(v_,b),__||(__=!0,setTimeout(function(){__=!1,b_(v_,!(v_={}))},0))}function b_(b,T){T===void 0&&(T=!1);var N=new Set;if(b.all)for(var j=0,V=Object.values(ec);j<V.length;j++)JA(re=V[j],b,N,T);else for(var W in b){var ee,re,W=/^idb\:\/\/(.*)\/(.*)\//.exec(W);W&&(ee=W[1],W=W[2],re=ec["idb://".concat(ee,"/").concat(W)])&&JA(re,b,N,T)}N.forEach(function(he){return he()})}function JA(b,T,N,j){for(var V=[],W=0,ee=Object.entries(b.queries.query);W<ee.length;W++){for(var re=ee[W],he=re[0],Ee=[],pe=0,de=re[1];pe<de.length;pe++){var fe=de[pe];y_(T,fe.obsSet)?fe.subscribers.forEach(function(ye){return N.add(ye)}):j&&Ee.push(fe)}j&&V.push([he,Ee])}if(j)for(var _e=0,me=V;_e<me.length;_e++){var ge=me[_e],he=ge[0],Ee=ge[1];b.queries.query[he]=Ee}}function k$(b){var T=b._state,N=b._deps.indexedDB;if(T.isBeingOpened||b.idbdb)return T.dbReadyPromise.then(function(){return T.dbOpenError?ae(T.dbOpenError):b});T.isBeingOpened=!0,T.dbOpenError=null,T.openComplete=!1;var j=T.openCanceller,V=Math.round(10*b.verno),W=!1;function ee(){if(T.openCanceller!==j)throw new we.DatabaseClosed("db.open() was cancelled")}function re(){return new Qe(function(fe,_e){if(ee(),!N)throw new we.MissingAPI;var me=b.name,ge=T.autoSchema||!V?N.open(me):N.open(me,V);if(!ge)throw new we.MissingAPI;ge.onerror=is(_e),ge.onblocked=kt(b._fireOnBlocked),ge.onupgradeneeded=kt(function(ye){var ke;pe=ge.transaction,T.autoSchema&&!b._options.allowEmptyDB?(ge.onerror=ta,pe.abort(),ge.result.close(),(ke=N.deleteDatabase(me)).onsuccess=ke.onerror=kt(function(){_e(new we.NoSuchDatabase("Database ".concat(me," doesnt exist")))})):(pe.onerror=is(_e),ke=ye.oldVersion>Math.pow(2,62)?0:ye.oldVersion,de=ke<1,b.idbdb=ge.result,W&&R$(b,pe),A$(b,ke/10,pe,_e))},_e),ge.onsuccess=kt(function(){pe=null;var ye,ke,Re,Ie,Fe,Ge,We=b.idbdb=ge.result,ze=_(We.objectStoreNames);if(0<ze.length)try{var at=We.transaction((Fe=ze).length===1?Fe[0]:Fe,"readonly");if(T.autoSchema)Ge=We,Ie=at,(Re=b).verno=Ge.version/10,Ie=Re._dbSchema=Um(0,Ge,Ie),Re._storeNames=_(Ge.objectStoreNames,0),Mm(Re,[Re._allTables],a(Ie),Ie);else if(Bm(b,b._dbSchema,at),ke=at,((ke=d_(Um(0,(ye=b).idbdb,ke),ye._dbSchema)).add.length||ke.change.some(function(qe){return qe.add.length||qe.change.length}))&&!W)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,W=!0,fe(re());Nm(b,at)}catch{}Yh.add(b),We.onversionchange=kt(function(qe){T.vcFired=!0,b.on("versionchange").fire(qe)}),We.onclose=kt(function(){b.close({disableAutoOpen:!1})}),de&&(ze=b._deps,Fe=me,p_(Ge=ze.indexedDB)||Fe===Le||f_(Ge,ze.IDBKeyRange).put({name:Fe}).catch(Oe)),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()"),re();break;case"VersionError":if(0<V)return V=0,re()}return Qe.reject(fe)})}var he,Ee=T.dbReadyResolve,pe=null,de=!1;return Qe.race([j,(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(re)]).then(function(){return ee(),T.onReadyBeingFired=[],Qe.resolve(m_(function(){return b.on.ready.fire(b.vip)})).then(function fe(){var _e;if(0<T.onReadyBeingFired.length)return _e=T.onReadyBeingFired.reduce(Cn,Oe),T.onReadyBeingFired=[],Qe.resolve(m_(function(){return _e(b.vip)})).then(fe)})}).finally(function(){T.openCanceller===j&&(T.onReadyBeingFired=null,T.isBeingOpened=!1)}).catch(function(fe){T.dbOpenError=fe;try{pe&&pe.abort()}catch{}return j===T.openCanceller&&b._close(),ae(fe)}).finally(function(){T.openComplete=!0,Ee()}).then(function(){var fe;return de&&(fe={},b.tables.forEach(function(_e){_e.schema.indexes.forEach(function(me){me.name&&(fe["idb://".concat(b.name,"/").concat(_e.name,"/").concat(me.name)]=new Xr(-1/0,[[[]]]))}),fe["idb://".concat(b.name,"/").concat(_e.name,"/")]=fe["idb://".concat(b.name,"/").concat(_e.name,"/:dels")]=new Xr(-1/0,[[[]]])}),ui(Mo).fire(fe),b_(fe,!0)),b})}function x_(b){function T(W){return b.next(W)}var N=V(T),j=V(function(W){return b.throw(W)});function V(W){return function(re){var re=W(re),he=re.value;return re.done?he:he&&typeof he.then=="function"?he.then(N,j):o(he)?Promise.all(he).then(N,j):N(he)}}return V(T)()}function Gm(b,T,N){for(var j=o(b)?b.slice():[b],V=0;V<N;++V)j.push(T);return j}var L$={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(b){return r(r({},b),{table:function(j){var N=b.table(j),j=N.schema,V={},W=[];function ee(fe,_e,me){var Re=Wh(fe),ge=V[Re]=V[Re]||[],ye=fe==null?0:typeof fe=="string"?1:fe.length,ke=0<_e,Re=r(r({},me),{name:ke?"".concat(Re,"(virtual-from:").concat(me.name,")"):me.name,lowLevelIndex:me,isVirtual:ke,keyTail:_e,keyLength:ye,extractKey:c_(fe),unique:!ke&&me.unique});return ge.push(Re),Re.isPrimaryKey||W.push(Re),1<ye&&ee(ye===2?fe[0]:fe.slice(0,ye-1),_e+1,me),ge.sort(function(Ie,Fe){return Ie.keyTail-Fe.keyTail}),Re}var re=ee(j.primaryKey.keyPath,0,j.primaryKey);V[":id"]=[re];for(var he=0,Ee=j.indexes;he<Ee.length;he++){var pe=Ee[he];ee(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:Gm(_e.lower,_e.lowerOpen?b.MAX_KEY:b.MIN_KEY,me),lowerOpen:!0,upper:Gm(_e.upper,_e.upperOpen?b.MIN_KEY:b.MAX_KEY,me),upperOpen:!0})}}):fe}return r(r({},N),{schema:r(r({},j),{primaryKey:re,indexes:W,getIndexByKeyPath:function(fe){return(fe=V[Wh(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(ke){return ke&&ye(ke)}):N.openCursor(fe);function ye(ke){return Object.create(ke,{continue:{value:function(Re){Re!=null?ke.continue(Gm(Re,fe.reverse?b.MAX_KEY:b.MIN_KEY,me)):fe.unique?ke.continue(ke.key.slice(0,ge).concat(fe.reverse?b.MIN_KEY:b.MAX_KEY,me)):ke.continue()}},continuePrimaryKey:{value:function(Re,Ie){ke.continuePrimaryKey(Gm(Re,b.MAX_KEY,me),Ie)}},primaryKey:{get:function(){return ke.primaryKey}},key:{get:function(){var Re=ke.key;return ge===1?Re[0]:Re.slice(0,ge)}},value:{get:function(){return ke.value}}})}}})}})}};function S_(b,T,N,j){return N=N||{},j=j||"",a(b).forEach(function(V){var W,ee,re;d(T,V)?(W=b[V],ee=T[V],typeof W=="object"&&typeof ee=="object"&&W&&ee?(re=X(W))!==X(ee)?N[j+V]=T[V]:re==="Object"?S_(W,ee,N,j+V+"."):W!==ee&&(N[j+V]=T[V]):W!==ee&&(N[j+V]=T[V])):N[j+V]=void 0}),a(T).forEach(function(V){d(b,V)||(N[j+V]=T[V])}),N}function E_(b,T){return T.type==="delete"?T.keys:T.keys||T.values.map(b.extractKey)}var I$={stack:"dbcore",name:"HooksMiddleware",level:2,create:function(b){return r(r({},b),{table:function(T){var N=b.table(T),j=N.schema.primaryKey;return r(r({},N),{mutate:function(V){var W=st.trans,ee=W.table(T).hook,re=ee.deleting,he=ee.creating,Ee=ee.updating;switch(V.type){case"add":if(he.fire===Oe)break;return W._promise("readwrite",function(){return pe(V)},!0);case"put":if(he.fire===Oe&&Ee.fire===Oe)break;return W._promise("readwrite",function(){return pe(V)},!0);case"delete":if(re.fire===Oe)break;return W._promise("readwrite",function(){return pe(V)},!0);case"deleteRange":if(re.fire===Oe)break;return W._promise("readwrite",function(){return function de(fe,_e,me){return N.query({trans:fe,values:!1,query:{index:j,range:_e},limit:me}).then(function(ge){var ye=ge.result;return pe({type:"delete",keys:ye,trans:fe}).then(function(ke){return 0<ke.numFailures?Promise.reject(ke.failures[0]):ye.length<me?{failures:[],numFailures:0,lastResult:void 0}:de(fe,r(r({},_e),{lower:ye[ye.length-1],lowerOpen:!0}),me)})})}(V.trans,V.range,1e4)},!0)}return N.mutate(V);function pe(de){var fe,_e,me,ge=st.trans,ye=de.keys||E_(j,de);if(ye)return(de=de.type==="add"||de.type==="put"?r(r({},de),{keys:ye}):r({},de)).type!=="delete"&&(de.values=s([],de.values)),de.keys&&(de.keys=s([],de.keys)),fe=N,me=ye,((_e=de).type==="add"?Promise.resolve([]):fe.getMany({trans:_e.trans,keys:me,cache:"immutable"})).then(function(ke){var Re=ye.map(function(Ie,Fe){var Ge,We,ze,at=ke[Fe],qe={onerror:null,onsuccess:null};return de.type==="delete"?re.fire.call(qe,Ie,at,ge):de.type==="add"||at===void 0?(Ge=he.fire.call(qe,Ie,de.values[Fe],ge),Ie==null&&Ge!=null&&(de.keys[Fe]=Ie=Ge,j.outbound||P(de.values[Fe],j.keyPath,Ie))):(Ge=S_(at,de.values[Fe]),(We=Ee.fire.call(qe,Ge,Ie,at,ge))&&(ze=de.values[Fe],Object.keys(We).forEach(function(ct){d(ze,ct)?ze[ct]=We[ct]:P(ze,ct,We[ct])}))),qe});return N.mutate(de).then(function(Ie){for(var Fe=Ie.failures,Ge=Ie.results,We=Ie.numFailures,Ie=Ie.lastResult,ze=0;ze<ye.length;++ze){var at=(Ge||ye)[ze],qe=Re[ze];at==null?qe.onerror&&qe.onerror(Fe[ze]):qe.onsuccess&&qe.onsuccess(de.type==="put"&&ke[ze]?de.values[ze]:at)}return{failures:Fe,results:Ge,numFailures:We,lastResult:Ie}}).catch(function(Ie){return Re.forEach(function(Fe){return Fe.onerror&&Fe.onerror(Ie)}),Promise.reject(Ie)})});throw new Error("Keys missing")}}})}})}};function ZA(b,T,N){try{if(!T||T.keys.length<b.length)return null;for(var j=[],V=0,W=0;V<T.keys.length&&W<b.length;++V)He(T.keys[V],b[W])===0&&(j.push(N?Y(T.values[V]):T.values[V]),++W);return j.length===b.length?j:null}catch{return null}}var P$={stack:"dbcore",level:-1,create:function(b){return{table:function(T){var N=b.table(T);return r(r({},N),{getMany:function(j){var V;return j.cache?(V=ZA(j.keys,j.trans._cache,j.cache==="clone"))?Qe.resolve(V):N.getMany(j).then(function(W){return j.trans._cache={keys:j.keys,values:j.cache==="clone"?Y(W):W},W}):N.getMany(j)},mutate:function(j){return j.type!=="add"&&(j.trans._cache=null),N.mutate(j)}})}}}};function eR(b,T){return b.trans.mode==="readonly"&&!!b.subscr&&!b.trans.explicit&&b.trans.db._options.cache!=="disabled"&&!T.schema.primaryKey.outbound}function tR(b,T){switch(b){case"query":return T.values&&!T.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var D$={stack:"dbcore",level:0,name:"Observability",create:function(b){var T=b.schema.name,N=new Xr(b.MIN_KEY,b.MAX_KEY);return r(r({},b),{transaction:function(j,V,W){if(st.subscr&&V!=="readonly")throw new we.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(st.querier));return b.transaction(j,V,W)},table:function(j){function V(ye){var ge,ye=ye.query;return[ge=ye.index,new Xr((ge=(ye=ye.range).lower)!=null?ge:b.MIN_KEY,(ge=ye.upper)!=null?ge:b.MAX_KEY)]}var W=b.table(j),ee=W.schema,re=ee.primaryKey,he=ee.indexes,Ee=re.extractKey,pe=re.outbound,de=re.autoIncrement&&he.filter(function(me){return me.compound&&me.keyPath.includes(re.keyPath)}),fe=r(r({},W),{mutate:function(me){function ge($e){return $e="idb://".concat(T,"/").concat(j,"/").concat($e),Fe[$e]||(Fe[$e]=new Xr)}var ye,ke,Re,Ie=me.trans,Fe=me.mutatedParts||(me.mutatedParts={}),Ge=ge(""),We=ge(":dels"),ze=me.type,qe=me.type==="deleteRange"?[me.range]:me.type==="delete"?[me.keys]:me.values.length<50?[E_(re,me).filter(function($e){return $e}),me.values]:[],at=qe[0],qe=qe[1],ct=me.trans._cache;return o(at)?(Ge.addKeys(at),(ze=ze==="delete"||at.length===qe.length?ZA(at,ct):null)||We.addKeys(at),(ze||qe)&&(ye=ge,ke=ze,Re=qe,ee.indexes.forEach(function($e){var Tt=ye($e.name||"");function At(Xt){return Xt!=null?$e.extractKey(Xt):null}function Mt(Xt){$e.multiEntry&&o(Xt)?Xt.forEach(function(Ns){return Tt.addKey(Ns)}):Tt.addKey(Xt)}(ke||Re).forEach(function(Xt,Qr){var Ot=ke&&At(ke[Qr]),Qr=Re&&At(Re[Qr]);He(Ot,Qr)!==0&&(Ot!=null&&Mt(Ot),Qr!=null)&&Mt(Qr)})}))):at?(qe={from:(ct=at.lower)!=null?ct:b.MIN_KEY,to:(ze=at.upper)!=null?ze:b.MAX_KEY},We.add(qe),Ge.add(qe)):(Ge.add(N),We.add(N),ee.indexes.forEach(function($e){return ge($e.name).add(N)})),W.mutate(me).then(function($e){return!at||me.type!=="add"&&me.type!=="put"||(Ge.addKeys($e.results),de&&de.forEach(function(Tt){for(var At=me.values.map(function(Ot){return Tt.extractKey(Ot)}),Mt=Tt.keyPath.findIndex(function(Ot){return Ot===re.keyPath}),Xt=0,Ns=$e.results.length;Xt<Ns;++Xt)At[Xt][Mt]=$e.results[Xt];ge(Tt.name).addKeys(At)})),Ie.mutatedParts=$m(Ie.mutatedParts||{},Fe),$e})}}),_e={get:function(me){return[re,new Xr(me.key)]},getMany:function(me){return[re,new Xr().addKeys(me.keys)]},count:V,query:V,openCursor:V};return a(_e).forEach(function(me){fe[me]=function(ge){var ye=st.subscr,ke=!!ye,Re=eR(st,W)&&tR(me,ge)?ge.obsSet={}:ye;if(ke){var Ie,ye=function(qe){return qe="idb://".concat(T,"/").concat(j,"/").concat(qe),Re[qe]||(Re[qe]=new Xr)},Fe=ye(""),Ge=ye(":dels"),ke=_e[me](ge),We=ke[0],ke=ke[1];if((me==="query"&&We.isPrimaryKey&&!ge.values?Ge:ye(We.name||"")).add(ke),!We.isPrimaryKey){if(me!=="count")return Ie=me==="query"&&pe&&ge.values&&W.query(r(r({},ge),{values:!1})),W[me].apply(this,arguments).then(function(qe){if(me==="query"){if(pe&&ge.values)return Ie.then(function(At){return At=At.result,Fe.addKeys(At),qe});var ct=ge.values?qe.result.map(Ee):qe.result;(ge.values?Fe:Ge).addKeys(ct)}else{var $e,Tt;if(me==="openCursor")return Tt=ge.values,($e=qe)&&Object.create($e,{key:{get:function(){return Ge.addKey($e.primaryKey),$e.key}},primaryKey:{get:function(){var At=$e.primaryKey;return Ge.addKey(At),At}},value:{get:function(){return Tt&&Fe.addKey($e.primaryKey),$e.value}}})}return qe});Ge.add(N)}}return W[me].apply(this,arguments)}}),fe}})}};function nR(b,T,N){var j;return N.numFailures===0?T:T.type==="deleteRange"||(j=T.keys?T.keys.length:"values"in T&&T.values?T.values.length:1,N.numFailures===j)?null:(j=r({},T),o(j.keys)&&(j.keys=j.keys.filter(function(V,W){return!(W in N.failures)})),"values"in j&&o(j.values)&&(j.values=j.values.filter(function(V,W){return!(W in N.failures)})),j)}function w_(b,T){return N=b,((j=T).lower===void 0||(j.lowerOpen?0<He(N,j.lower):0<=He(N,j.lower)))&&(N=b,(j=T).upper===void 0||(j.upperOpen?He(N,j.upper)<0:He(N,j.upper)<=0));var N,j}function rR(b,T,N,j,V,W){var ee,re,he,Ee,pe,de,fe;return!N||N.length===0||(ee=T.query.index,re=ee.multiEntry,he=T.query.range,Ee=j.schema.primaryKey.extractKey,pe=ee.extractKey,de=(ee.lowLevelIndex||ee).extractKey,(j=N.reduce(function(_e,me){var ge=_e,ye=[];if(me.type==="add"||me.type==="put")for(var ke=new Xr,Re=me.values.length-1;0<=Re;--Re){var Ie,Fe=me.values[Re],Ge=Ee(Fe);!ke.hasKey(Ge)&&(Ie=pe(Fe),re&&o(Ie)?Ie.some(function(ct){return w_(ct,he)}):w_(Ie,he))&&(ke.addKey(Ge),ye.push(Fe))}switch(me.type){case"add":var We=new Xr().addKeys(T.values?_e.map(function($e){return Ee($e)}):_e),ge=_e.concat(T.values?ye.filter(function($e){return $e=Ee($e),!We.hasKey($e)&&(We.addKey($e),!0)}):ye.map(function($e){return Ee($e)}).filter(function($e){return!We.hasKey($e)&&(We.addKey($e),!0)}));break;case"put":var ze=new Xr().addKeys(me.values.map(function($e){return Ee($e)}));ge=_e.filter(function($e){return!ze.hasKey(T.values?Ee($e):$e)}).concat(T.values?ye:ye.map(function($e){return Ee($e)}));break;case"delete":var at=new Xr().addKeys(me.keys);ge=_e.filter(function($e){return!at.hasKey(T.values?Ee($e):$e)});break;case"deleteRange":var qe=me.range;ge=_e.filter(function($e){return!w_(Ee($e),qe)})}return ge},b))===b)?b:(fe=function(_e,me){return He(de(_e),de(me))||He(Ee(_e),Ee(me))},j.sort(T.direction==="prev"||T.direction==="prevunique"?function(_e,me){return fe(me,_e)}:fe),T.limit&&T.limit<1/0&&(j.length>T.limit?j.length=T.limit:b.length===T.limit&&j.length<T.limit&&(V.dirty=!0)),W?Object.freeze(j):j)}function sR(b,T){return He(b.lower,T.lower)===0&&He(b.upper,T.upper)===0&&!!b.lowerOpen==!!T.lowerOpen&&!!b.upperOpen==!!T.upperOpen}function O$(b,T){return((N,j,V,W)=>{if(N===void 0)return j!==void 0?-1:0;if(j===void 0)return 1;if((N=He(N,j))===0){if(V&&W)return 0;if(V)return 1;if(W)return-1}return N})(b.lower,T.lower,b.lowerOpen,T.lowerOpen)<=0&&0<=((N,j,V,W)=>{if(N===void 0)return j!==void 0?1:0;if(j===void 0)return-1;if((N=He(N,j))===0){if(V&&W)return 0;if(V)return-1;if(W)return 1}return N})(b.upper,T.upper,b.upperOpen,T.upperOpen)}function N$(b,T,N,j){b.subscribers.add(N),j.addEventListener("abort",function(){var V,W;b.subscribers.delete(N),b.subscribers.size===0&&(V=b,W=T,setTimeout(function(){V.subscribers.size===0&&ne(W,V)},3e3))})}var M$={stack:"dbcore",level:0,name:"Cache",create:function(b){var T=b.schema.name;return r(r({},b),{transaction:function(N,j,V){var W,ee,re=b.transaction(N,j,V);return j==="readwrite"&&(V=(W=new AbortController).signal,re.addEventListener("abort",(ee=function(he){return function(){if(W.abort(),j==="readwrite"){for(var Ee=new Set,pe=0,de=N;pe<de.length;pe++){var fe=de[pe],_e=ec["idb://".concat(T,"/").concat(fe)];if(_e){var me=b.table(fe),ge=_e.optimisticOps.filter(function($e){return $e.trans===re});if(re._explicit&&he&&re.mutatedParts)for(var ye=0,ke=Object.values(_e.queries.query);ye<ke.length;ye++)for(var Re=0,Ie=(We=ke[ye]).slice();Re<Ie.length;Re++)y_((ze=Ie[Re]).obsSet,re.mutatedParts)&&(ne(We,ze),ze.subscribers.forEach(function($e){return Ee.add($e)}));else if(0<ge.length){_e.optimisticOps=_e.optimisticOps.filter(function($e){return $e.trans!==re});for(var Fe=0,Ge=Object.values(_e.queries.query);Fe<Ge.length;Fe++)for(var We,ze,at,qe=0,ct=(We=Ge[Fe]).slice();qe<ct.length;qe++)(ze=ct[qe]).res!=null&&re.mutatedParts&&(he&&!ze.dirty?(at=Object.isFrozen(ze.res),at=rR(ze.res,ze.req,ge,me,ze,at),ze.dirty?(ne(We,ze),ze.subscribers.forEach(function($e){return Ee.add($e)})):at!==ze.res&&(ze.res=at,ze.promise=Qe.resolve({result:at}))):(ze.dirty&&ne(We,ze),ze.subscribers.forEach(function($e){return Ee.add($e)})))}}}Ee.forEach(function($e){return $e()})}}})(!1),{signal:V}),re.addEventListener("error",ee(!1),{signal:V}),re.addEventListener("complete",ee(!0),{signal:V})),re},table:function(N){var j=b.table(N),V=j.schema.primaryKey;return r(r({},j),{mutate:function(W){var ee,re=st.trans;return!V.outbound&&re.db._options.cache!=="disabled"&&!re.explicit&&re.idbtrans.mode==="readwrite"&&(ee=ec["idb://".concat(T,"/").concat(N)])?(re=j.mutate(W),W.type!=="add"&&W.type!=="put"||!(50<=W.values.length||E_(V,W).some(function(he){return he==null}))?(ee.optimisticOps.push(W),W.mutatedParts&&Vm(W.mutatedParts),re.then(function(he){0<he.numFailures&&(ne(ee.optimisticOps,W),(he=nR(0,W,he))&&ee.optimisticOps.push(he),W.mutatedParts)&&Vm(W.mutatedParts)}),re.catch(function(){ne(ee.optimisticOps,W),W.mutatedParts&&Vm(W.mutatedParts)})):re.then(function(he){var Ee=nR(0,r(r({},W),{values:W.values.map(function(pe,de){var fe;return he.failures[de]?pe:(P(fe=(fe=V.keyPath)!=null&&fe.includes(".")?Y(pe):r({},pe),V.keyPath,he.results[de]),fe)})}),he);ee.optimisticOps.push(Ee),queueMicrotask(function(){return W.mutatedParts&&Vm(W.mutatedParts)})}),re):j.mutate(W)},query:function(W){var ee,re,he,Ee,pe,de,fe;return eR(st,j)&&tR("query",W)?(ee=((he=st.trans)==null?void 0:he.db._options.cache)==="immutable",re=(he=st).requery,he=he.signal,de=((_e,me,ge,ye)=>{var ke=ec["idb://".concat(_e,"/").concat(me)];if(!ke)return[];if(!(_e=ke.queries[ge]))return[null,!1,ke,null];var Re=_e[(ye.query?ye.query.index.name:null)||""];if(!Re)return[null,!1,ke,null];switch(ge){case"query":var Ie=(Fe=ye.direction)!=null?Fe:"next",Fe=Re.find(function(Ge){var We;return Ge.req.limit===ye.limit&&Ge.req.values===ye.values&&((We=Ge.req.direction)!=null?We:"next")===Ie&&sR(Ge.req.query.range,ye.query.range)});return Fe?[Fe,!0,ke,Re]:[Re.find(function(Ge){var We;return("limit"in Ge.req?Ge.req.limit:1/0)>=ye.limit&&((We=Ge.req.direction)!=null?We:"next")===Ie&&(!ye.values||Ge.req.values)&&O$(Ge.req.query.range,ye.query.range)}),!1,ke,Re];case"count":return Fe=Re.find(function(Ge){return sR(Ge.req.query.range,ye.query.range)}),[Fe,!!Fe,ke,Re]}})(T,N,"query",W),fe=de[0],Ee=de[2],pe=de[3],fe&&de[1]?fe.obsSet=W.obsSet:(de=j.query(W).then(function(_e){var me=_e.result;if(fe&&(fe.res=me),ee){for(var ge=0,ye=me.length;ge<ye;++ge)Object.freeze(me[ge]);Object.freeze(me)}else _e.result=Y(me);return _e}).catch(function(_e){return pe&&fe&&ne(pe,fe),Promise.reject(_e)}),fe={obsSet:W.obsSet,promise:de,subscribers:new Set,type:"query",req:W,dirty:!1},pe?pe.push(fe):(pe=[fe],(Ee=Ee||(ec["idb://".concat(T,"/").concat(N)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[W.query.index.name||""]=pe)),N$(fe,pe,re,he),fe.promise.then(function(_e){return{result:rR(_e.result,W,Ee==null?void 0:Ee.optimisticOps,j,fe,ee)}})):j.query(W)}})}})}};function Km(b,T){return new Proxy(b,{get:function(N,j,V){return j==="db"?T:Reflect.get(N,j,V)}})}nr.prototype.version=function(b){if(isNaN(b)||b<.1)throw new we.Type("Given version is not a positive number");if(b=Math.round(10*b)/10,this.idbdb||this._state.isBeingOpened)throw new we.Schema("Cannot add version when database is open");this.verno=Math.max(this.verno,b);var T=this._versions,N=T.filter(function(j){return j._cfg.version===b})[0];return N||(N=new this.Version(b),T.push(N),T.sort(T$),N.stores({}),this._state.autoSchema=!1),N},nr.prototype._whenReady=function(b){var T=this;return this.idbdb&&(this._state.openComplete||st.letThrough||this._vip)?b():new Qe(function(N,j){if(T._state.openComplete)return j(new we.DatabaseClosed(T._state.dbOpenError));if(!T._state.isBeingOpened){if(!T._state.autoOpen)return void j(new we.DatabaseClosed);T.open().catch(Oe)}T._state.dbReadyPromise.then(N,j)}).then(b)},nr.prototype.use=function(V){var T=V.stack,N=V.create,j=V.level,V=V.name,W=(V&&this.unuse({stack:T,name:V}),this._middlewares[T]||(this._middlewares[T]=[]));return W.push({stack:T,create:N,level:j??10,name:V}),W.sort(function(ee,re){return ee.level-re.level}),this},nr.prototype.unuse=function(b){var T=b.stack,N=b.name,j=b.create;return T&&this._middlewares[T]&&(this._middlewares[T]=this._middlewares[T].filter(function(V){return j?V.create!==j:!!N&&V.name!==N})),this},nr.prototype.open=function(){var b=this;return te(bs,function(){return k$(b)})},nr.prototype._close=function(){this.on.close.fire(new CustomEvent("close"));var b=this._state;if(Yh.remove(this),this.idbdb){try{this.idbdb.close()}catch{}this.idbdb=null}b.isBeingOpened||(b.dbReadyPromise=new Qe(function(T){b.dbReadyResolve=T}),b.openCanceller=new Qe(function(T,N){b.cancelOpen=N}))},nr.prototype.close=function(T){var T=(T===void 0?{disableAutoOpen:!0}:T).disableAutoOpen,N=this._state;T?(N.isBeingOpened&&N.cancelOpen(new we.DatabaseClosed),this._close(),N.autoOpen=!1,N.dbOpenError=new we.DatabaseClosed):(this._close(),N.autoOpen=this._options.autoOpen||N.isBeingOpened,N.openComplete=!1,N.dbOpenError=null)},nr.prototype.delete=function(b){var T=this,N=(b===void 0&&(b={disableAutoOpen:!0}),0<arguments.length&&typeof arguments[0]!="object"),j=this._state;return new Qe(function(V,W){function ee(){T.close(b);var re=T._deps.indexedDB.deleteDatabase(T.name);re.onsuccess=kt(function(){var he,Ee,pe;he=T._deps,Ee=T.name,p_(pe=he.indexedDB)||Ee===Le||f_(pe,he.IDBKeyRange).delete(Ee).catch(Oe),V()}),re.onerror=is(W),re.onblocked=T._fireOnBlocked}if(N)throw new we.InvalidArgument("Invalid closeOptions argument to db.delete()");j.isBeingOpened?j.dbReadyPromise.then(ee):ee()})},nr.prototype.backendDB=function(){return this.idbdb},nr.prototype.isOpen=function(){return this.idbdb!==null},nr.prototype.hasBeenClosed=function(){var b=this._state.dbOpenError;return b&&b.name==="DatabaseClosed"},nr.prototype.hasFailed=function(){return this._state.dbOpenError!==null},nr.prototype.dynamicallyOpened=function(){return this._state.autoSchema},Object.defineProperty(nr.prototype,"tables",{get:function(){var b=this;return a(this._allTables).map(function(T){return b._allTables[T]})},enumerable:!1,configurable:!0}),nr.prototype.transaction=function(){var b=(function(T,N,j){var V=arguments.length;if(V<2)throw new we.InvalidArgument("Too few arguments");for(var W=new Array(V-1);--V;)W[V-1]=arguments[V];return j=W.pop(),[T,R(W),j]}).apply(this,arguments);return this._transaction.apply(this,b)},nr.prototype._transaction=function(b,T,N){var j,V,W=this,ee=st.trans,re=(ee&&ee.db===this&&b.indexOf("!")===-1||(ee=null),b.indexOf("?")!==-1);b=b.replace("!","").replace("?","");try{if(V=T.map(function(Ee){if(Ee=Ee instanceof W.Table?Ee.name:Ee,typeof Ee!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return Ee}),b=="r"||b===Je)j=Je;else{if(b!="rw"&&b!=Ye)throw new we.InvalidArgument("Invalid transaction mode: "+b);j=Ye}if(ee){if(ee.mode===Je&&j===Ye){if(!re)throw new we.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");ee=null}ee&&V.forEach(function(Ee){if(ee&&ee.storeNames.indexOf(Ee)===-1){if(!re)throw new we.SubTransaction("Table "+Ee+" not included in parent transaction.");ee=null}}),re&&ee&&!ee.active&&(ee=null)}}catch(Ee){return ee?ee._promise(null,function(pe,de){de(Ee)}):ae(Ee)}var he=(function Ee(pe,de,fe,_e,me){return Qe.resolve().then(function(){var Re=st.transless||st,ge=pe._createTransaction(de,fe,pe._dbSchema,_e),Re=(ge.explicit=!0,{trans:ge,transless:Re});if(_e)ge.idbtrans=_e.idbtrans;else try{ge.create(),ge.idbtrans._explicit=!0,pe._state.PR1398_maxLoop=3}catch(Ie){return Ie.name===Pe.InvalidState&&pe.isOpen()&&0<--pe._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),pe.close({disableAutoOpen:!1}),pe.open().then(function(){return Ee(pe,de,fe,null,me)})):ae(Ie)}var ye,ke=J(me),Re=(ke&&x(),Qe.follow(function(){var Ie;(ye=me.call(ge,ge))&&(ke?(Ie=O.bind(null,null),ye.then(Ie,Ie)):typeof ye.next=="function"&&typeof ye.throw=="function"&&(ye=x_(ye)))},Re));return(ye&&typeof ye.then=="function"?Qe.resolve(ye).then(function(Ie){return ge.active?Ie:ae(new we.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):Re.then(function(){return ye})).then(function(Ie){return _e&&ge._resolve(),ge._completion.then(function(){return Ie})}).catch(function(Ie){return ge._reject(Ie),ae(Ie)})})}).bind(null,this,j,V,ee,N);return ee?ee._promise(j,he,"lock"):st.trans?te(st.transless,function(){return W._whenReady(he)}):this._whenReady(he)},nr.prototype.table=function(b){if(d(this._allTables,b))return this._allTables[b];throw new we.InvalidTable("Table ".concat(b," does not exist"))};var Fa=nr;function nr(b,T){var N,j,V,W,ee,re=this,he=(this._middlewares={},this.verno=0,nr.dependencies),he=(this._options=T=r({addons:nr.addons,autoOpen:!0,indexedDB:he.indexedDB,IDBKeyRange:he.IDBKeyRange,cache:"cloned",maxConnections:1e3},T),this._deps={indexedDB:T.indexedDB,IDBKeyRange:T.IDBKeyRange},T.addons),Ee=(this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this,{dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:Oe,dbReadyPromise:null,cancelOpen:Oe,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3,autoOpen:T.autoOpen}),pe=(Ee.dbReadyPromise=new Qe(function(de){Ee.dbReadyResolve=de}),Ee.openCanceller=new Qe(function(de,fe){Ee.cancelOpen=fe}),this._state=Ee,this.name=b,this.on=Tn(this,"populate","blocked","versionchange","close",{ready:[Cn,Oe]}),this.once=function(de,fe){var _e=function(){for(var me=[],ge=0;ge<arguments.length;ge++)me[ge]=arguments[ge];re.on(de).unsubscribe(_e),fe.apply(re,me)};return re.on(de,_e)},this.on.ready.subscribe=S(this.on.ready.subscribe,function(de){return function(fe,_e){nr.vip(function(){var me,ge=re._state;ge.openComplete?(ge.dbOpenError||Qe.resolve().then(fe),_e&&de(fe)):ge.onReadyBeingFired?(ge.onReadyBeingFired.push(fe),_e&&de(fe)):(de(fe),me=re,_e||de(function ye(){me.on.ready.unsubscribe(fe),me.on.ready.unsubscribe(ye)}))})}}),this.Collection=(N=this,Or(Di.prototype,function(ye,ge){this.db=N;var _e=pt,me=null;if(ge)try{_e=ge()}catch(Re){me=Re}var ge=ye._ctx,ye=ge.table,ke=ye.hook.reading.fire;this._ctx={table:ye,index:ge.index,isPrimKey:!ge.index||ye.schema.primKey.keyPath&&ge.index===ye.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:ke!==Dt?ke:null}})),this.Table=(j=this,Or(Nt.prototype,function(de,fe,_e){this.db=j,this._tx=_e,this.name=de,this.schema=fe,this.hook=j._allTables[de]?j._allTables[de].hook:Tn(null,{creating:[it,Oe],reading:[en,Dt],updating:[mn,Oe],deleting:[nn,Oe]})})),this.Transaction=(V=this,Or(Om.prototype,function(de,fe,_e,me,ge){var ye=this;de!=="readonly"&&fe.forEach(function(ke){ke=(ke=_e[ke])==null?void 0:ke.yProps,ke&&(fe=fe.concat(ke.map(function(Re){return Re.updatesTable})))}),this.db=V,this.mode=de,this.storeNames=fe,this.schema=_e,this.chromeTransactionDurability=me,this.idbtrans=null,this.on=Tn(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(ke,Re){ye._resolve=ke,ye._reject=Re}),this._completion.then(function(){ye.active=!1,ye.on.complete.fire()},function(ke){var Re=ye.active;return ye.active=!1,ye.on.error.fire(ke),ye.parent?ye.parent._reject(ke):Re&&ye.idbtrans&&ye.idbtrans.abort(),ae(ke)})})),this.Version=(W=this,Or(C$.prototype,function(de){this.db=W,this._cfg={version:de,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=(ee=this,Or(No.prototype,function(de,fe,_e){if(this.db=ee,this._ctx={table:de,index:fe===":id"?null:fe,or:_e},this._cmp=this._ascending=He,this._descending=function(me,ge){return He(ge,me)},this._max=function(me,ge){return 0<He(me,ge)?me:ge},this._min=function(me,ge){return He(me,ge)<0?me:ge},this._IDBKeyRange=ee._deps.IDBKeyRange,!this._IDBKeyRange)throw new we.MissingAPI})),this.on("versionchange",function(de){0<de.newVersion?console.warn("Another connection wants to upgrade database '".concat(re.name,"'. Closing db now to resume the upgrade.")):console.warn("Another connection wants to delete database '".concat(re.name,"'. Closing db now to resume the delete request.")),re.close({disableAutoOpen:!1})}),this.on("blocked",function(de){!de.newVersion||de.newVersion<de.oldVersion?console.warn("Dexie.delete('".concat(re.name,"') was blocked")):console.warn("Upgrade '".concat(re.name,"' blocked by other connection holding version ").concat(de.oldVersion/10))}),this._maxKey=qh(T.IDBKeyRange),this._createTransaction=function(de,fe,_e,me){return new re.Transaction(de,fe,_e,re._options.chromeTransactionDurability,me)},this._fireOnBlocked=function(de){re.on("blocked").fire(de),Yh.toArray().filter(function(fe){return fe.name===re.name&&fe!==re&&!fe._state.vcFired}).map(function(fe){return fe.on("versionchange").fire(de)})},this.use(P$),this.use(M$),this.use(D$),this.use(L$),this.use(I$),new Proxy(this,{get:function(de,fe,_e){var me;return fe==="_vip"||(fe==="table"?function(ge){return Km(re.table(ge),pe)}:(me=Reflect.get(de,fe,_e))instanceof Nt?Km(me,pe):fe==="tables"?me.map(function(ge){return Km(ge,pe)}):fe==="_createTransaction"?function(){return Km(me.apply(this,arguments),pe)}:me)}}));this.vip=pe,he.forEach(function(de){return de(re)})}var Hm,wu=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",j$=(T_.prototype.subscribe=function(b,T,N){return this._subscribe(b&&typeof b!="function"?b:{next:b,error:T,complete:N})},T_.prototype[wu]=function(){return this},T_);function T_(b){this._subscribe=b}try{Hm={indexedDB:i.indexedDB||i.mozIndexedDB||i.webkitIndexedDB||i.msIndexedDB,IDBKeyRange:i.IDBKeyRange||i.webkitIDBKeyRange}}catch{Hm={indexedDB:null,IDBKeyRange:null}}function iR(b){var T,N=!1,j=new j$(function(V){var W=J(b),ee,re=!1,he={},Ee={},pe={get closed(){return re},unsubscribe:function(){re||(re=!0,ee&&ee.abort(),de&&ui.storagemutated.unsubscribe(me))}},de=(V.start&&V.start(pe),!1),fe=function(){return le(ge)};function _e(){return y_(Ee,he)}var me=function(ye){$m(he,ye),_e()&&fe()},ge=function(){var ye,ke,Re;!re&&Hm.indexedDB&&(he={},ye={},ee&&ee.abort(),ee=new AbortController,Re=(Ie=>{var Fe=Zn();try{W&&x();var Ge=w(b,Ie);return Ge=W?Ge.finally(O):Ge}finally{Fe&&er()}})(ke={subscr:ye,signal:ee.signal,requery:fe,querier:b,trans:null}),de||(ui(Mo,me),de=!0),Promise.resolve(Re).then(function(Ie){N=!0,T=Ie,re||ke.signal.aborted||(_e()||(Ee=ye,_e())?fe():(he={},le(function(){return!re&&V.next&&V.next(Ie)})))},function(Ie){N=!1,["DatabaseClosedError","AbortError"].includes(Ie==null?void 0:Ie.name)||re||le(function(){re||V.error&&V.error(Ie)})}))};return setTimeout(fe,0),pe});return j.hasValue=function(){return N},j.getValue=function(){return T},j}var tc=Fa;function A_(b){var T=jo;try{jo=!0,ui.storagemutated.fire(b),b_(b,!0)}finally{jo=T}}h(tc,r(r({},Q),{delete:function(b){return new tc(b,{addons:[]}).delete()},exists:function(b){return new tc(b,{addons:[]}).open().then(function(T){return T.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(b){try{return T=tc.dependencies,N=T.indexedDB,T=T.IDBKeyRange,(p_(N)?Promise.resolve(N.databases()).then(function(j){return j.map(function(V){return V.name}).filter(function(V){return V!==Le})}):f_(N,T).toCollection().primaryKeys()).then(b)}catch{return ae(new we.MissingAPI)}var T,N},defineClass:function(){return function(b){l(this,b)}},ignoreTransaction:function(b){return st.trans?te(st.transless||bs,b):b()},vip:m_,async:function(b){return function(){try{var T=x_(b.apply(this,arguments));return T&&typeof T.then=="function"?T:Qe.resolve(T)}catch(N){return ae(N)}}},spawn:function(b,T,N){try{var j=x_(b.apply(N,T||[]));return j&&typeof j.then=="function"?j:Qe.resolve(j)}catch(V){return ae(V)}},currentTransaction:{get:function(){return st.trans||null}},waitFor:function(b,T){return b=Qe.resolve(typeof b=="function"?tc.ignoreTransaction(b):b).timeout(T||6e4),st.trans?st.trans.waitFor(b):b},Promise:Qe,debug:{get:function(){return ln},set:function(b){Nn(b)}},derive:g,extend:l,props:h,override:S,Events:Tn,on:ui,liveQuery:iR,extendObservabilitySet:$m,getByKeyPath:U,setByKeyPath:P,delByKeyPath:function(b,T){typeof T=="string"?P(b,T,void 0):"length"in T&&[].map.call(T,function(N){P(b,N,void 0)})},shallowClone:I,deepClone:Y,getObjectDiff:S_,cmp:He,asap:L,minKey:-1/0,addons:[],connections:{get:Yh.toArray},errnames:Pe,dependencies:Hm,cache:ec,semVer:"4.4.2",version:"4.4.2".split(".").map(function(b){return parseInt(b)}).reduce(function(b,T,N){return b+T/Math.pow(10,2*N)})})),tc.maxKey=qh(tc.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(ui(Mo,function(b){jo||(b=new CustomEvent(bu,{detail:b}),jo=!0,dispatchEvent(b),jo=!1)}),addEventListener(bu,function(b){b=b.detail,jo||A_(b)}));var Tu,jo=!1,aR=function(){};return typeof BroadcastChannel<"u"&&((aR=function(){(Tu=new BroadcastChannel(bu)).onmessage=function(b){return b.data&&A_(b.data)}})(),typeof Tu.unref=="function"&&Tu.unref(),ui(Mo,function(b){jo||Tu.postMessage(b)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(b){if(!Fa.disableBfCache&&b.persisted){ln&&console.debug("Dexie: handling persisted pagehide"),Tu!=null&&Tu.close();for(var T=0,N=Yh.toArray();T<N.length;T++)N[T].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(b){!Fa.disableBfCache&&b.persisted&&(ln&&console.debug("Dexie: handling persisted pageshow"),aR(),A_({all:new Xr(-1/0,[[]])}))})),Qe.rejectionMapper=function(b,T){return!b||b instanceof Te||b instanceof TypeError||b instanceof SyntaxError||!b.name||!Ue[b.name]?b:(T=new Ue[b.name](T||b.message,b),"stack"in b&&m(T,"stack",{get:function(){return this.inner.stack}}),T)},Nn(ln),r(Fa,Object.freeze({__proto__:null,DEFAULT_MAX_CONNECTIONS:1e3,Dexie:Fa,Entity:Xe,PropModification:Ut,RangeSet:Xr,add:function(b){return new Ut({add:b})},cmp:He,default:Fa,liveQuery:iR,mergeRanges:Qh,rangesOverlap:YA,remove:function(b){return new Ut({remove:b})},replacePrefix:function(b,T){return new Ut({replacePrefix:[b,T]})}}),{default:Fa}),Fa})})(T3);var Xee=T3.exports;const qE=tv(Xee),lI=Symbol.for("Dexie"),D0=globalThis[lI]||(globalThis[lI]=qE);if(qE.semVer!==D0.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${qE.semVer} and ${D0.semVer}`);const{liveQuery:_ye,mergeRanges:bye,rangesOverlap:xye,RangeSet:Sye,cmp:Eye,Entity:wye,PropModification:Tye,replacePrefix:Aye,add:Rye,remove:Cye,DexieYProvider:kye}=D0;class Qee extends D0{constructor(){super("nadiplay");qm(this,"profiles");this.version(1).stores({profiles:"id"})}}const po=new Qee,cI="nadiplay_profiles",uI="nadiplay_profiles_migrated_v1",Jee=async()=>{try{if(localStorage.getItem(uI)==="1")return;const t=localStorage.getItem(cI);if(t){try{const e=JSON.parse(t);Array.isArray(e)&&e.length&&await po.profiles.bulkPut(e)}catch{}localStorage.removeItem(cI)}localStorage.setItem(uI,"1")}catch{}},Cu="nadiplay_active_profile",WE="nadiplay-profiles-changed",xg=()=>window.dispatchEvent(new Event(WE)),Zee=async()=>(await Jee(),await po.profiles.toArray()),Li=()=>{const[t,e]=C.useState([]),[n,r]=C.useState(()=>localStorage.getItem(Cu)),s=C.useCallback(async()=>{try{const u=await Zee();e(u)}catch{e([])}},[]);C.useEffect(()=>{s();const u=()=>{s(),r(localStorage.getItem(Cu))};return window.addEventListener(WE,u),window.addEventListener("storage",u),()=>{window.removeEventListener(WE,u),window.removeEventListener("storage",u)}},[s]);const i=C.useCallback(u=>{u?localStorage.setItem(Cu,u):localStorage.removeItem(Cu),r(u),xg()},[]),a=C.useCallback(u=>{const d={...u,id:crypto.randomUUID()};return e(h=>[...h,d]),po.profiles.put(d).then(()=>xg()).catch(h=>{console.error("[nadiDb] failed to persist profile:",h)}),localStorage.getItem(Cu)||i(d.id),d},[i]),o=C.useCallback(async(u,d)=>{e(h=>h.map(f=>f.id===u?{...f,...d}:f));try{await po.profiles.update(u,d),xg()}catch(h){console.error("[nadiDb] update failed:",h)}},[]),l=C.useCallback(async u=>{var d;e(h=>h.filter(f=>f.id!==u));try{await po.profiles.delete(u)}catch(h){console.error("[nadiDb] delete failed:",h)}if(localStorage.getItem(Cu)===u){const h=await po.profiles.toArray();i(((d=h[0])==null?void 0:d.id)??null)}xg()},[i]),c=t.find(u=>u.id===n)??null;return{profiles:t,activeProfile:c,activeProfileId:n,setActiveProfileId:i,addProfile:a,updateProfile:o,removeProfile:l}};var ga=function(){return ga=Object.assign||function(e){for(var n,r=1,s=arguments.length;r<s;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},ga.apply(this,arguments)};function $h(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 s=0,r=Object.getOwnPropertySymbols(t);s<r.length;s++)e.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(t,r[s])&&(n[r[s]]=t[r[s]]);return n}function ete(t,e,n,r){function s(i){return i instanceof n?i:new n(function(a){a(i)})}return new(n||(n=Promise))(function(i,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?i(u.value):s(u.value).then(o,l)}c((r=r.apply(t,e||[])).next())})}function tte(t,e,n){if(n||arguments.length===2)for(var r=0,s=e.length,i;r<s;r++)(i||!(r in e))&&(i||(i=Array.prototype.slice.call(e,0,r)),i[r]=e[r]);return t.concat(i||Array.prototype.slice.call(e))}const nte=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);class Q1 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 rte extends Q1{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class dI extends Q1{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class hI extends Q1{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var YE;(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"})(YE||(YE={}));class ste{constructor(e,{headers:n={},customFetch:r,region:s=YE.Any}={}){this.url=e,this.headers=n,this.region=s,this.fetch=nte(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return ete(this,arguments,void 0,function*(n,r={}){var s;let i,a;try{const{headers:o,method:l,body:c,signal:u,timeout:d}=r;let h={},{region:f}=r;f||(f=this.region);const m=new URL(`${this.url}/${n}`);f&&f!=="any"&&(h["x-region"]=f,m.searchParams.set("forceFunctionRegion",f));let g;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",g=c):typeof c=="string"?(h["Content-Type"]="text/plain",g=c):typeof FormData<"u"&&c instanceof FormData?g=c:(h["Content-Type"]="application/json",g=JSON.stringify(c)):c&&typeof c!="string"&&!(typeof Blob<"u"&&c instanceof Blob)&&!(c instanceof ArrayBuffer)&&!(typeof FormData<"u"&&c instanceof FormData)?g=JSON.stringify(c):g=c;let y=u;d&&(a=new AbortController,i=setTimeout(()=>a.abort(),d),u?(y=a.signal,u.addEventListener("abort",()=>a.abort())):y=a.signal);const v=yield this.fetch(m.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},h),this.headers),o),body:g,signal:y}).catch(L=>{throw new rte(L)}),_=v.headers.get("x-relay-error");if(_&&_==="true")throw new dI(v);if(!v.ok)throw new hI(v);let S=((s=v.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),E;return S==="application/json"?E=yield v.json():S==="application/octet-stream"||S==="application/pdf"?E=yield v.blob():S==="text/event-stream"?E=v:S==="multipart/form-data"?E=yield v.formData():E=yield v.text(),{data:E,error:null,response:v}}catch(o){return{data:null,error:o,response:o instanceof hI||o instanceof dI?o.context:void 0}}finally{i&&clearTimeout(i)}})}}const A3=3,fI=t=>Math.min(1e3*2**t,3e4),ite=[520,503],R3=["GET","HEAD","OPTIONS"];var ate=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 pI(t,e){return new Promise(n=>{if(e!=null&&e.aborted){n();return}const r=setTimeout(()=>{e==null||e.removeEventListener("abort",s),n()},t);function s(){clearTimeout(r),n()}e==null||e.addEventListener("abort",s)})}function ote(t,e,n,r){return!(!r||n>=A3||!R3.includes(t)||!ite.includes(e))}var lte=class{constructor(t){var e,n,r,s,i;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=(s=t.urlLengthLimit)!==null&&s!==void 0?s:8e3,this.retryEnabled=(i=t.retry)!==null&&i!==void 0?i:!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 i=(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"||!R3.includes(n.method))throw d;if(n.retryEnabled&&a<A3){const h=fI(a);a++,await pI(h,n.signal);continue}throw d}if(ote(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:fI(a);await u.text(),a++,await pI(h,n.signal);continue}return await n.processResponse(u)}})();return this.shouldThrowOnError||(i=i.catch(a=>{var o;let l="",c="",u="";const d=a==null?void 0:a.cause;if(d){var h,f,m,g;const _=(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=`${(m=a==null?void 0:a.name)!==null&&m!==void 0?m:"FetchError"}: ${a==null?void 0:a.message}`,l+=`

Caused by: ${(g=d==null?void 0:d.name)!==null&&g!==void 0?g:"Error"}: ${_}`,S&&(l+=` (${S})`),d!=null&&d.stack&&(l+=`
${d.stack}`)}else{var y;l=(y=a==null?void 0:a.stack)!==null&&y!==void 0?y:""}const v=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)",v>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${v} 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)",v>this.urlLengthLimit&&(c+=`. Your request URL is ${v} 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:""}})),i.then(t,e)}async processResponse(t){var e=this;let n=null,r=null,s=null,i=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&&(s=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,s=null,i=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,i=200,a="OK")}catch{t.status===404&&u===""?(i=204,a="No Content"):n={message:u}}if(n&&e.shouldThrowOnError)throw new ate(n)}return{success:n===null,error:n,data:r,count:s,status:i,statusText:a}}returns(){return this}overrideTypes(){return this}},cte=class extends lte{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:s=r}={}){const i=s?`${s}.order`:"order",a=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${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 s=typeof r>"u"?"offset":`${r}.offset`,i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${t}`),this.url.searchParams.set(i,`${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:s=!1,format:i="text"}={}){var a;const o=[t?"analyze":null,e?"verbose":null,n?"settings":null,r?"buffers":null,s?"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+${i}; for="${l}"; options=${o};`),i==="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 mI=new RegExp("[,()]");var Qu=class extends cte{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"&&mI.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"&&mI.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 s="";r==="plain"?s="pl":r==="phrase"?s="ph":r==="websearch"&&(s="w");const i=n===void 0?"":`(${n})`;return this.url.searchParams.append(t,`${s}fts${i}.${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}},ute=class{constructor(t,{headers:e={},schema:n,fetch:r,urlLengthLimit:s=8e3,retry:i}){this.url=t,this.headers=new Headers(e),this.schema=n,this.fetch=r,this.urlLengthLimit=s,this.retry=i}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){const{head:n=!1,count:r}=e??{},s=n?"HEAD":"GET";let i=!1;const a=(t??"*").split("").map(c=>/\s/.test(c)&&!i?"":(c==='"'&&(i=!i),c)).join(""),{url:o,headers:l}=this.cloneRequestState();return o.searchParams.set("select",a),r&&l.append("Prefer",`count=${r}`),new Qu({method:s,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 s="POST",{url:i,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}"`);i.searchParams.set("columns",l.join(","))}}return new Qu({method:s,url:i,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:s=!0}={}){var i;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}`),s||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 Qu({method:a,url:o,headers:l,schema:this.schema,body:t,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(t,{count:e}={}){var n;const r="PATCH",{url:s,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new Qu({method:r,url:s,headers:i,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:s}=this.cloneRequestState();return t&&s.append("Prefer",`count=${t}`),new Qu({method:n,url:r,headers:s,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function Ip(t){"@babel/helpers - typeof";return Ip=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},Ip(t)}function dte(t,e){if(Ip(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(Ip(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function hte(t){var e=dte(t,"string");return Ip(e)=="symbol"?e:e+""}function fte(t,e,n){return(e=hte(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function gI(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),n.push.apply(n,r)}return n}function Sg(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?gI(Object(n),!0).forEach(function(r){fte(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):gI(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}var pte=class C3{constructor(e,{headers:n={},schema:r,fetch:s,timeout:i,urlLengthLimit:a=8e3,retry:o}={}){this.url=e,this.headers=new Headers(n),this.schemaName=r,this.urlLengthLimit=a;const l=s??globalThis.fetch;i!==void 0&&i>0?this.fetch=(c,u)=>{const d=new AbortController,h=setTimeout(()=>d.abort(),i),f=u==null?void 0:u.signal;if(f){if(f.aborted)return clearTimeout(h),l(c,u);const m=()=>{clearTimeout(h),d.abort()};return f.addEventListener("abort",m,{once:!0}),l(c,Sg(Sg({},u),{},{signal:d.signal})).finally(()=>{clearTimeout(h),f.removeEventListener("abort",m)})}return l(c,Sg(Sg({},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 ute(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 C3(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(e,n={},{head:r=!1,get:s=!1,count:i}={}){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||s?(o=r?"HEAD":"GET",Object.entries(n).filter(([f,m])=>m!==void 0).map(([f,m])=>[f,Array.isArray(m)?`{${m.join(",")}}`:`${m}`]).forEach(([f,m])=>{l.searchParams.append(f,m)})):(o="POST",c=n);const h=new Headers(this.headers);return d?h.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&h.set("Prefer",`count=${i}`),new Qu({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 mte{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 s=r.node,i=parseInt(s.replace(/^v/,"").split(".")[0]);return i>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${i} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${i} 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 gte="2.105.1",yte=`realtime-js/${gte}`,vte="1.0.0",k3="2.0.0",_te=k3,bte=1e4,xte=100,il={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},L3={close:"phx_close",error:"phx_error",join:"phx_join",leave:"phx_leave",access_token:"access_token"},XE={connecting:"connecting",closing:"closing",closed:"closed"};class Ste{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 s=(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,s)}_encodeJsonUserBroadcastPush(e){var n,r;const s=(r=(n=e.payload)===null||n===void 0?void 0:n.payload)!==null&&r!==void 0?r:{},a=new TextEncoder().encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,a)}_encodeUserBroadcastPush(e,n,r){var s,i;const a=e.topic,o=(s=e.ref)!==null&&s!==void 0?s:"",l=(i=e.join_ref)!==null&&i!==void 0?i:"",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 m=new DataView(f),g=0;m.setUint8(g++,this.KINDS.userBroadcastPush),m.setUint8(g++,l.length),m.setUint8(g++,o.length),m.setUint8(g++,a.length),m.setUint8(g++,c.length),m.setUint8(g++,d.length),m.setUint8(g++,n),Array.from(l,v=>m.setUint8(g++,v.charCodeAt(0))),Array.from(o,v=>m.setUint8(g++,v.charCodeAt(0))),Array.from(a,v=>m.setUint8(g++,v.charCodeAt(0))),Array.from(c,v=>m.setUint8(g++,v.charCodeAt(0))),Array.from(d,v=>m.setUint8(g++,v.charCodeAt(0)));var y=new Uint8Array(f.byteLength+r.byteLength);return y.set(new Uint8Array(f),0),y.set(new Uint8Array(r),f.byteLength),y.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),[s,i,a,o,l]=r;return n({join_ref:s,ref:i,topic:a,event:o,payload:l})}return n({})}_binaryDecode(e){const n=new DataView(e),r=n.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,n,s)}}_decodeUserBroadcast(e,n,r){const s=n.getUint8(1),i=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+s));l=l+s;const u=r.decode(e.slice(l,l+i));l=l+i;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,m={type:this.BROADCAST_EVENT,event:u,payload:f};return a>0&&(m.meta=JSON.parse(d)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:m}}_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 An;(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"})(An||(An={}));const yI=(t,e,n={})=>{var r;const s=(r=n.skipTypes)!==null&&r!==void 0?r:[];return e?Object.keys(e).reduce((i,a)=>(i[a]=Ete(a,t,e,s),i),{}):{}},Ete=(t,e,n,r)=>{const s=e.find(o=>o.name===t),i=s==null?void 0:s.type,a=n[t];return i&&!r.includes(i)?I3(i,a):QE(a)},I3=(t,e)=>{if(t.charAt(0)==="_"){const n=t.slice(1,t.length);return Rte(e,n)}switch(t){case An.bool:return wte(e);case An.float4:case An.float8:case An.int2:case An.int4:case An.int8:case An.numeric:case An.oid:return Tte(e);case An.json:case An.jsonb:return Ate(e);case An.timestamp:return Cte(e);case An.abstime:case An.date:case An.daterange:case An.int4range:case An.int8range:case An.money:case An.reltime:case An.text:case An.time:case An.timestamptz:case An.timetz:case An.tsrange:case An.tstzrange:return QE(e);default:return QE(e)}},QE=t=>t,wte=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},Tte=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},Ate=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},Rte=(t,e)=>{if(typeof t!="string")return t;const n=t.length-1,r=t[n];if(t[0]==="{"&&r==="}"){let i;const a=t.slice(1,n);try{i=JSON.parse("["+a+"]")}catch{i=a?a.split(","):[]}return i.map(o=>I3(e,o))}return t},Cte=t=>typeof t=="string"?t.replace(" ","T"):t,P3=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 Xf=t=>typeof t=="function"?t:function(){return t},kte=typeof self<"u"?self:null,Ju=typeof window<"u"?window:null,la=kte||Ju||globalThis,Lte="2.0.0",Ite=1e4,Pte=1e3,fa={connecting:0,open:1,closing:2,closed:3},Ss={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},to={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},JE={longpoll:"longpoll",websocket:"websocket"},Dte={complete:4},ZE="base64url.bearer.phx.",Eg=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})}},D3=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))}},Ote=class{constructor(t,e,n){this.state=Ss.closed,this.topic=t,this.params=Xf(e||{}),this.socket=n,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new Eg(this,to.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new D3(()=>{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=Ss.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(r=>r.send()),this.pushBuffer=[]}),this.joinPush.receive("error",r=>{this.state=Ss.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=Ss.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=Ss.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 Eg(this,to.leave,Xf({}),this.timeout).send(),this.state=Ss.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(to.reply,(r,s)=>{this.trigger(this.replyEventName(s),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=Ss.closed,this.bindings=[]}onClose(t){this.on(to.close,t)}onError(t){return this.on(to.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 Eg(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=Ss.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(to.close,"leave")},n=new Eg(this,to.leave,Xf({}),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=Ss.joining,this.joinPush.resend(t))}trigger(t,e,n,r){let s=this.onMessage(t,e,n,r);if(e&&!s)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let i=this.bindings.filter(a=>a.event===t&&this.filterBindings(a,e,n));for(let a=0;a<i.length;a++)i[a].callback(s,n,r||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===Ss.closed}isErrored(){return this.state===Ss.errored}isJoined(){return this.state===Ss.joined}isJoining(){return this.state===Ss.joining}isLeaving(){return this.state===Ss.leaving}},O0=class{static request(t,e,n,r,s,i,a){if(la.XDomainRequest){let o=new la.XDomainRequest;return this.xdomainRequest(o,t,e,r,s,i,a)}else if(la.XMLHttpRequest){let o=new la.XMLHttpRequest;return this.xhrRequest(o,t,e,n,r,s,i,a)}else{if(la.fetch&&la.AbortController)return this.fetchRequest(t,e,n,r,s,i,a);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,n,r,s,i,a){let o={method:t,headers:n,body:r},l=null;return s&&(l=new AbortController,setTimeout(()=>l.abort(),s),o.signal=l.signal),la.fetch(e,o).then(c=>c.text()).then(c=>this.parseJSON(c)).then(c=>a&&a(c)).catch(c=>{c.name==="AbortError"&&i?i():a&&a(null)}),l}static xdomainRequest(t,e,n,r,s,i,a){return t.timeout=s,t.open(e,n),t.onload=()=>{let o=this.parseJSON(t.responseText);a&&a(o)},i&&(t.ontimeout=i),t.onprogress=()=>{},t.send(r),t}static xhrRequest(t,e,n,r,s,i,a,o){t.open(e,n,!0),t.timeout=i;for(let[l,c]of Object.entries(r))t.setRequestHeader(l,c);return t.onerror=()=>o&&o(null),t.onreadystatechange=()=>{if(t.readyState===Dte.complete&&o){let l=this.parseJSON(t.responseText);o(l)}},a&&(t.ontimeout=a),t.send(s),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 s=e?`${e}[${r}]`:r,i=t[r];typeof i=="object"?n.push(this.serialize(i,s)):n.push(encodeURIComponent(s)+"="+encodeURIComponent(i))}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)}`}},Nte=t=>{let e="",n=new Uint8Array(t),r=n.byteLength;for(let s=0;s<r;s++)e+=String.fromCharCode(n[s]);return btoa(e)},ku=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(ZE)&&(this.authToken=atob(e[1].slice(ZE.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=fa.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+JE.websocket),"$1/"+JE.longpoll)}endpointURL(){return O0.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,n){this.close(t,e,n),this.readyState=fa.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===fa.open||this.readyState===fa.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:s}=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:s.forEach(i=>{setTimeout(()=>this.onmessage({data:i}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=fa.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=Nte(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 s of this.reqs)s.abort();this.readyState=fa.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,s){let i,a=()=>{this.reqs.delete(i),r()};i=O0.request(t,this.endpointURL(),e,n,this.timeout,a,o=>{this.reqs.delete(i),this.isActive()&&s(o)}),this.reqs.add(i)}},Mte=class Sf{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,s=>{let{onJoin:i,onLeave:a,onSync:o}=this.caller;this.joinRef=this.channel.joinRef(),this.state=Sf.syncState(this.state,s,i,a),this.pendingDiffs.forEach(l=>{this.state=Sf.syncDiff(this.state,l,i,a)}),this.pendingDiffs=[],o()}),this.channel.on(r.diff,s=>{let{onJoin:i,onLeave:a,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=Sf.syncDiff(this.state,s,i,a),o())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return Sf.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,n,r,s){let i=this.clone(e),a={},o={};return this.map(i,(l,c)=>{n[l]||(o[l]=c)}),this.map(n,(l,c)=>{let u=i[l];if(u){let d=c.metas.map(g=>g.phx_ref),h=u.metas.map(g=>g.phx_ref),f=c.metas.filter(g=>h.indexOf(g.phx_ref)<0),m=u.metas.filter(g=>d.indexOf(g.phx_ref)<0);f.length>0&&(a[l]=c,a[l].metas=f),m.length>0&&(o[l]=this.clone(u),o[l].metas=m)}else a[l]=c}),this.syncDiff(i,{joins:a,leaves:o},r,s)}static syncDiff(e,n,r,s){let{joins:i,leaves:a}=this.clone(n);return r||(r=function(){}),s||(s=function(){}),this.map(i,(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),s(o,c,l),c.metas.length===0&&delete e[o]}),e}static list(e,n){return n||(n=function(r,s){return s}),this.map(e,(r,s)=>n(r,s))}static map(e,n){return Object.getOwnPropertyNames(e).map(r=>n(r,e[r]))}static clone(e){return JSON.parse(JSON.stringify(e))}},wg={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,s,i,a]=JSON.parse(t);return e({join_ref:n,ref:r,topic:s,event:i,payload:a})}},binaryEncode(t){let{join_ref:e,ref:n,event:r,topic:s,payload:i}=t,a=this.META_LENGTH+e.length+n.length+s.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++,s.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(s,d=>l.setUint8(c++,d.charCodeAt(0))),Array.from(r,d=>l.setUint8(c++,d.charCodeAt(0)));var u=new Uint8Array(o.byteLength+i.byteLength);return u.set(new Uint8Array(o),0),u.set(new Uint8Array(i),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),s=e.getUint8(2),i=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+s));a=a+s;let c=n.decode(t.slice(a,a+i));a=a+i;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),s=e.getUint8(2),i=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+s));o=o+s;let u=n.decode(t.slice(o,o+i));o=o+i;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:to.reply,payload:f}},decodeBroadcast(t,e,n){let r=e.getUint8(1),s=e.getUint8(2),i=this.HEADER_LENGTH+2,a=n.decode(t.slice(i,i+r));i=i+r;let o=n.decode(t.slice(i,i+s));i=i+s;let l=t.slice(i,t.byteLength);return{join_ref:null,ref:null,topic:a,event:o,payload:l}}},jte=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||Ite,this.transport=e.transport||la.WebSocket||ku,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||la&&la.sessionStorage,this.establishedConnections=0,this.defaultEncoder=wg.encode.bind(wg),this.defaultDecoder=wg.decode.bind(wg),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!==ku?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let n=null;Ju&&Ju.addEventListener&&(Ju.addEventListener("pagehide",r=>{this.conn&&(this.disconnect(),n=this.connectClock)}),Ju.addEventListener("pageshow",r=>{n===this.connectClock&&(n=null,this.connect())}),Ju.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,s,i)=>{console.log(`${r}: ${s}`,i)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=Xf(e.params||{}),this.endPoint=`${t}/${JE.websocket}`,this.vsn=e.vsn||Lte,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new D3(()=>{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 ku}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=O0.appendParams(O0.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=Xf(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==ku?this.connectWithFallback(ku,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(s=>{s.ref===e&&(this.off([r]),t(Date.now()-n))});return!0}transportName(t){switch(t){case ku:return"LongPoll";default:return t.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${ZE}${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,s,i,a=this.transportName(t),o=l=>{this.log("transport",`falling back to ${a}...`,l),this.off([s,i]),r=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${a}`))return o("memorized");this.fallbackTimer=setTimeout(o,e),i=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(new Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),Pte,"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===fa.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(t),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t)}onConnError(t){this.hasLogger()&&this.log("transport","error",t);let e=this.transport,n=this.establishedConnections;this.triggerStateCallbacks("error",t,e,n),(e===this.transport||n>0)&&this.triggerChanError(t)}triggerChanError(t){this.channels.forEach(e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(to.error,t)})}connectionState(){switch(this.conn&&this.conn.readyState){case fa.connecting:return"connecting";case fa.open:return"open";case fa.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 Ote(t,e,this);return this.channels.push(n),n}push(t){if(this.hasLogger()){let{topic:e,event:n,payload:r,ref:s,join_ref:i}=t;this.log("push",`${e} ${n} (${i}, ${s})`,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:s,ref:i,join_ref:a}=e;if(i&&i===this.pendingHeartbeatRef){const o=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(s.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",`${s.status||""} ${n} ${r} ${i&&"("+i+")"||""}`.trim(),s);for(let o=0;o<this.channels.length;o++){const l=this.channels[o];l.isMember(n,r,s,a)&&l.trigger(r,s,i,a)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([n,r])=>{try{r(...e)}catch(s){this.log("error",`error in ${t} callback`,s)}})}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 Qf{constructor(e,n){const r=Bte(n);this.presence=new Mte(e.getChannel(),r),this.presence.onJoin((s,i,a)=>{const o=Qf.onJoinPayload(s,i,a);e.getChannel().trigger("presence",o)}),this.presence.onLeave((s,i,a)=>{const o=Qf.onLeavePayload(s,i,a);e.getChannel().trigger("presence",o)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return Qf.transformState(this.presence.state)}static transformState(e){return e=Ute(e),Object.getOwnPropertyNames(e).reduce((n,r)=>{const s=e[r];return n[r]=wy(s),n},{})}static onJoinPayload(e,n,r){const s=vI(n),i=wy(r);return{event:"join",key:e,currentPresences:s,newPresences:i}}static onLeavePayload(e,n,r){const s=vI(n),i=wy(r);return{event:"leave",key:e,currentPresences:s,leftPresences:i}}}function wy(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function Ute(t){return JSON.parse(JSON.stringify(t))}function Bte(t){return(t==null?void 0:t.events)&&{events:t.events}}function vI(t){return t!=null&&t.metas?wy(t):[]}var _I;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(_I||(_I={}));class Fte{get state(){return this.presenceAdapter.state}constructor(e,n){this.channel=e,this.presenceAdapter=new Qf(this.channel.channelAdapter,n)}}function $te(t){if(t instanceof Error)return t;if(typeof t=="string")return new Error(t);if(t&&typeof t=="object"){const e=t;if(typeof e.code=="number"){const n=typeof e.reason=="string"&&e.reason?` (${e.reason})`:"";return new Error(`socket closed: ${e.code}${n}`,{cause:t})}return new Error("channel error: transport failure",{cause:t})}return new Error("channel error: connection lost")}class Vte{constructor(e,n,r){const s=Gte(r);this.channel=e.getSocket().channel(n,s),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 s;try{s=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>xte){const i=this.channel.pushBuffer.shift();i.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${i.event}`,i.payload())}return s}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===il.joined}isJoined(){return this.state===il.joined}isJoining(){return this.state===il.joining}isClosed(){return this.state===il.closed}isLeaving(){return this.state===il.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}}function Gte(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var bI;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(bI||(bI={}));var vd;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(vd||(vd={}));var no;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(no||(no={}));class Jf{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 s,i;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 Vte(this.socket.socketAdapter,e,this.params),this.presence=new Fte(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=P3(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((i=(s=this.params.config)===null||s===void 0?void 0:s.broadcast)===null||i===void 0)&&i.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,s,i;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){const{config:{broadcast:a,presence:o,private:l}}=this.params,c=(s=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(f=>f.filter))!==null&&s!==void 0?s:[],u=!!this.bindings[vd.PRESENCE]&&this.bindings[vd.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.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(no.CHANNEL_ERROR,$te(f))}),this._onClose(()=>e==null?void 0:e(no.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(no.SUBSCRIBED);return}this._updatePostgresBindings(f,e)}).receive("error",f=>{this.state=il.errored;const m=Object.values(f).join(", ")||"error";e==null||e(no.CHANNEL_ERROR,new Error(m,{cause:f}))}).receive("timeout",()=>{e==null||e(no.TIMED_OUT)})}return this}_updatePostgresBindings(e,n){var r;const s=this.bindings.postgres_changes,i=(r=s==null?void 0:s.length)!==null&&r!==void 0?r:0,a=[];for(let o=0;o<i;o++){const l=s[o],{filter:{event:c,schema:u,table:d,filter:h}}=l,f=e&&e[o];if(f&&f.event===c&&Jf.isFilterValueEqual(f.schema,u)&&Jf.isFilterValueEqual(f.table,d)&&Jf.isFilterValueEqual(f.filter,h))a.push(Object.assign(Object.assign({},l),{id:f.id}));else{this.unsubscribe(),this.state=il.errored,n==null||n(no.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=a,this.state!=il.errored&&n&&n(no.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 s=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),i=e===vd.PRESENCE||e===vd.POSTGRES_CHANGES;if(s&&i)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 s;if(n==null)return Promise.reject(new Error("Payload is required for httpSend()"));const i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);const a={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:n,private:this.private}]})},o=await this._fetchWithTimeout(this.broadcastEndpointURL,a,(s=r.timeout)!==null&&s!==void 0?s: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,s;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:i,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:i,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((s=c.body)===null||s===void 0?void 0:s.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{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)&&i("ok"),c.receive("ok",()=>i("ok")),c.receive("error",()=>i("error")),c.receive("timeout",()=>i("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 s=new AbortController,i=setTimeout(()=>s.abort(),r),a=await this.socket.fetch(e,Object.assign(Object.assign({},n),{signal:s.signal}));return clearTimeout(i),a}_on(e,n,r){const s=e.toLocaleLowerCase(),i=this.channelAdapter.on(e,r),a={type:s,filter:n,callback:r,ref:i};return this.bindings[s]?this.bindings[s].push(a):this.bindings[s]=[a],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,n,r)=>{var s,i,a,o,l,c,u;const d=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(d,r))return!1;const h=(s=this.bindings[d])===null||s===void 0?void 0:s.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,m=(i=h.filter)===null||i===void 0?void 0:i.event;return f&&((a=n.ids)===null||a===void 0?void 0:a.includes(f))&&(m==="*"||(m==null?void 0:m.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:s,leave:i,join:a}=L3;return n&&[r,s,i,a].includes(e)&&n!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,n,r)=>{if(typeof n=="object"&&"ids"in n){const s=n.data,{schema:i,table:a,commit_timestamp:o,type:l,errors:c}=s;return Object.assign(Object.assign({},{schema:i,table:a,commit_timestamp:o,eventType:l,new:{},old:{},errors:c}),this._getPayloadRecords(s))}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=yI(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(n.old=yI(e.columns,e.old_record)),n}}class Kte{constructor(e,n){this.socket=new jte(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,s=1e4){return new Promise(i=>{setTimeout(()=>i("timeout"),s),this.socket.disconnect(()=>{e(),i("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()==XE.connecting}isDisconnecting(){return this.socket.connectionState()==XE.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}const xI={HEARTBEAT_INTERVAL:25e3},Hte=[1e3,2e3,5e3,1e4],zte=1e4,qte=`
  addEventListener("message", (e) => {
    if (e.data.event === "start") {
      setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
    }
  });`;class Wte{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 Ste,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=i=>i?(...a)=>i(...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 s=this._initializeOptions(n);this.socketAdapter=new Kte(e,s),this.httpEndpoint=P3(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._cancelPendingDisconnect(),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(),n}async removeAllChannels(){const e=this.channels.map(async r=>{const s=await r.unsubscribe();return r.teardown(),s}),n=await Promise.all(e);return await this.disconnect(),n}log(e,n,r){this.socketAdapter.log(e,n,r)}connectionState(){return this.socketAdapter.connectionState()||XE.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,n={config:{}}){const r=`realtime:${e}`,s=this.getChannels().find(i=>i.topic===r);if(s)return s;{const i=new Jf(`realtime:${e}`,n,this);return this._cancelPendingDisconnect(),this.channels.push(i),i}}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),this.channels.length===0&&(this.log("transport","no channels remaining, scheduling disconnect"),this._schedulePendingDisconnect())}_schedulePendingDisconnect(){if(this._cancelPendingDisconnect(),this._disconnectOnEmptyChannelsAfterMs===0){this.log("transport","disconnecting immediately - no channels"),this.disconnect();return}this._pendingDisconnectTimer=setTimeout(()=>{this._pendingDisconnectTimer=null,this.channels.length===0&&(this.log("transport","deferred disconnect fired - no channels, disconnecting"),this.disconnect())},this._disconnectOnEmptyChannelsAfterMs),this.log("transport",`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`)}_cancelPendingDisconnect(){this._pendingDisconnectTimer!==null&&(this.log("transport","pending disconnect cancelled - channel activity detected"),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(e=null){let n,r=!1;if(e)n=e,r=!0;else if(this.accessToken)try{n=await this.accessToken()}catch(s){this.log("error","Error fetching access token from callback",s),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(s=>{const i={access_token:n,version:yte};n&&s.updateJoinPayload(i),s.joinedOnce&&s.channelAdapter.isJoined()&&s.channelAdapter.push(L3.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([qte],{type:"application/javascript"});n=URL.createObjectURL(r)}return n}_initializeOptions(e){var n,r,s,i,a,o,l,c,u,d,h;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 f={};f.timeout=(s=e==null?void 0:e.timeout)!==null&&s!==void 0?s:bte,f.heartbeatIntervalMs=(i=e==null?void 0:e.heartbeatIntervalMs)!==null&&i!==void 0?i:xI.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=(a=e==null?void 0:e.disconnectOnEmptyChannelsAfterMs)!==null&&a!==void 0?a:2*((o=e==null?void 0:e.heartbeatIntervalMs)!==null&&o!==void 0?o:xI.HEARTBEAT_INTERVAL),f.transport=(l=e==null?void 0:e.transport)!==null&&l!==void 0?l:mte.getWebSocketConstructor(),f.params=e==null?void 0:e.params,f.logger=e==null?void 0:e.logger,f.heartbeatCallback=this._wrapHeartbeatCallback(e==null?void 0:e.heartbeatCallback),f.reconnectAfterMs=(c=e==null?void 0:e.reconnectAfterMs)!==null&&c!==void 0?c:v=>Hte[v-1]||zte;let m,g;const y=(u=e==null?void 0:e.vsn)!==null&&u!==void 0?u:_te;switch(y){case vte:m=(v,_)=>_(JSON.stringify(v)),g=(v,_)=>_(JSON.parse(v));break;case k3:m=this.serializer.encode.bind(this.serializer),g=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${f.vsn}`)}if(f.vsn=y,f.encode=(d=e==null?void 0:e.encode)!==null&&d!==void 0?d:m,f.decode=(h=e==null?void 0:e.decode)!==null&&h!==void 0?h:g,f.beforeReconnect=this._reconnectAuth.bind(this),(e!=null&&e.logLevel||e!=null&&e.log_level)&&(this.logLevel=e.logLevel||e.log_level,f.params=Object.assign(Object.assign({},f.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,f.autoSendHeartbeat=!this.worker}return f}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 Yte(t,e,n){const r=new URL(e,t);if(n)for(const[s,i]of Object.entries(n))i!==void 0&&r.searchParams.set(s,i);return r.toString()}async function Xte(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 Qte(t){const e=t.fetchImpl??globalThis.fetch;return{async request({method:n,path:r,query:s,body:i,headers:a}){const o=Yte(t.baseUrl,r,s),l=await Xte(t.auth),c=await e(o,{method:n,headers:{...i?{"Content-Type":"application/json"}:{},...l,...a},body:i?JSON.stringify(i):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,m=f==null?void 0:f.error;throw new Pp((m==null?void 0:m.message)??`Request failed with status ${c.status}`,{status:c.status,icebergType:m==null?void 0:m.type,icebergCode:m==null?void 0:m.code,details:f})}return{status:c.status,headers:c.headers,data:h}}}}function Tg(t){return t.join("")}var Jte=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){const e=t?{parent:Tg(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/${Tg(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Tg(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Tg(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 Lu(t){return t.join("")}var Zte=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/${Lu(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/${Lu(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/${Lu(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/${Lu(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/${Lu(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/${Lu(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}}},ene=class{constructor(t){var r;let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);const n=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=Qte({baseUrl:n,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=(r=t.accessDelegation)==null?void 0:r.join(","),this.namespaceOps=new Jte(this.client,e),this.tableOps=new Zte(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 Dp(t){"@babel/helpers - typeof";return Dp=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},Dp(t)}function tne(t,e){if(Dp(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(Dp(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function nne(t){var e=tne(t,"string");return Dp(e)=="symbol"?e:e+""}function rne(t,e,n){return(e=nne(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function SI(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),n.push.apply(n,r)}return n}function xt(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?SI(Object(n),!0).forEach(function(r){rne(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):SI(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}var Vv=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 Gv(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var ew=class extends Vv{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 xt({},super.toJSON())}},O3=class extends Vv{constructor(t,e,n="storage"){super(t,n),this.name=n==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};function N0(t,e,n){const r=xt({},t),s=e.toLowerCase();for(const i of Object.keys(r))i.toLowerCase()===s&&delete r[i];return r[s]=n,r}function sne(t){const e={};for(const[n,r]of Object.entries(t))e[n.toLowerCase()]=r;return e}const ine=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),ane=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)},tw=t=>{if(Array.isArray(t))return t.map(n=>tw(n));if(typeof t=="function"||t!==Object(t))return t;const e={};return Object.entries(t).forEach(([n,r])=>{const s=n.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[s]=tw(r)}),e},one=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t),EI=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)},lne=async(t,e,n,r)=>{if(t!==null&&typeof t=="object"&&typeof t.json=="function"){const s=t;let i=parseInt(s.status,10);Number.isFinite(i)||(i=500),s.json().then(a=>{const o=(a==null?void 0:a.statusCode)||(a==null?void 0:a.code)||i+"";e(new ew(EI(a),i,o,r))}).catch(()=>{const a=i+"";e(new ew(s.statusText||`HTTP ${i} error`,i,a,r))})}else e(new O3(EI(t),t,r))},cne=(t,e,n,r)=>{const s={method:t,headers:(e==null?void 0:e.headers)||{}};if(t==="GET"||t==="HEAD"||!r)return xt(xt({},s),n);if(ane(r)){var i;const a=(e==null?void 0:e.headers)||{};let o;for(const[l,c]of Object.entries(a))l.toLowerCase()==="content-type"&&(o=c);s.headers=N0(a,"Content-Type",(i=o)!==null&&i!==void 0?i:"application/json"),s.body=JSON.stringify(r)}else s.body=r;return e!=null&&e.duplex&&(s.duplex=e.duplex),xt(xt({},s),n)};async function df(t,e,n,r,s,i,a){return new Promise((o,l)=>{t(n,cne(e,r,s,i)).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=>lne(c,l,r,a))})}function N3(t="storage"){return{get:async(e,n,r,s)=>df(e,"GET",n,r,s,void 0,t),post:async(e,n,r,s,i)=>df(e,"POST",n,s,i,r,t),put:async(e,n,r,s,i)=>df(e,"PUT",n,s,i,r,t),head:async(e,n,r,s)=>df(e,"HEAD",n,xt(xt({},r),{},{noResolveJson:!0}),s,void 0,t),remove:async(e,n,r,s,i)=>df(e,"DELETE",n,s,i,r,t)}}const une=N3("storage"),{get:Op,post:Fi,put:nw,head:dne,remove:J1}=une,Ws=N3("vectors");var Vh=class{constructor(t,e={},n,r="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=sne(e),this.fetch=ine(n),this.namespace=r}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=N0(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(Gv(n))return{data:null,error:n};throw n}}},hne=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(Gv(e))return{data:null,error:e};throw e}}};let M3;M3=Symbol.toStringTag;var fne=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[M3]="BlobDownloadBuilder",this.promise=null}asStream(){return new hne(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(Gv(e))return{data:null,error:e};throw e}}};const pne={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},wI={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var mne=class extends Vh{constructor(t,e={},n,r){super(t,e,r,"storage"),this.bucketId=n}async uploadOrUpdate(t,e,n,r){var s=this;return s.handleOperation(async()=>{let i;const a=xt(xt({},wI),r);let o=xt(xt({},s.headers),t==="POST"&&{"x-upsert":String(a.upsert)});const l=a.metadata;if(typeof Blob<"u"&&n instanceof Blob?(i=new FormData,i.append("cacheControl",a.cacheControl),l&&i.append("metadata",s.encodeMetadata(l)),i.append("",n)):typeof FormData<"u"&&n instanceof FormData?(i=n,i.has("cacheControl")||i.append("cacheControl",a.cacheControl),l&&!i.has("metadata")&&i.append("metadata",s.encodeMetadata(l))):(i=n,o["cache-control"]=`max-age=${a.cacheControl}`,o["content-type"]=a.contentType,l&&(o["x-metadata"]=s.toBase64(s.encodeMetadata(l))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!a.duplex&&(a.duplex="half")),r!=null&&r.headers)for(const[h,f]of Object.entries(r.headers))o=N0(o,h,f);const c=s._removeEmptyFolders(e),u=s._getFinalPath(c),d=await(t=="PUT"?nw:Fi)(s.fetch,`${s.url}/object/${u}`,i,xt({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 s=this;const i=s._removeEmptyFolders(t),a=s._getFinalPath(i),o=new URL(s.url+`/object/upload/sign/${a}`);return o.searchParams.set("token",e),s.handleOperation(async()=>{let l;const c=xt(xt({},wI),r);let u=xt(xt({},s.headers),{"x-upsert":String(c.upsert)});const d=c.metadata;if(typeof Blob<"u"&&n instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),d&&l.append("metadata",s.encodeMetadata(d)),l.append("",n)):typeof FormData<"u"&&n instanceof FormData?(l=n,l.has("cacheControl")||l.append("cacheControl",c.cacheControl),d&&!l.has("metadata")&&l.append("metadata",s.encodeMetadata(d))):(l=n,u["cache-control"]=`max-age=${c.cacheControl}`,u["content-type"]=c.contentType,d&&(u["x-metadata"]=s.toBase64(s.encodeMetadata(d))),(typeof ReadableStream<"u"&&l instanceof ReadableStream||l&&typeof l=="object"&&"pipe"in l&&typeof l.pipe=="function")&&!c.duplex&&(c.duplex="half")),r!=null&&r.headers)for(const[h,f]of Object.entries(r.headers))u=N0(u,h,f);return{path:i,fullPath:(await nw(s.fetch,o.toString(),l,xt({headers:u},c!=null&&c.duplex?{duplex:c.duplex}:{}))).Key}})}async createSignedUploadUrl(t,e){var n=this;return n.handleOperation(async()=>{let r=n._getFinalPath(t);const s=xt({},n.headers);e!=null&&e.upsert&&(s["x-upsert"]="true");const i=await Fi(n.fetch,`${n.url}/object/upload/sign/${r}`,{},{headers:s}),a=new URL(n.url+i.url),o=a.searchParams.get("token");if(!o)throw new Vv("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 Fi(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 Fi(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 s=r._getFinalPath(t);const i=typeof(n==null?void 0:n.transform)=="object"&&n.transform!==null&&Object.keys(n.transform).length>0;let a=await Fi(r.fetch,`${r.url}/object/sign/${s}`,xt({expiresIn:e},i?{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 s=await Fi(r.fetch,`${r.url}/object/sign/${r.bucketId}`,{expiresIn:e,paths:t},{headers:r.headers}),i=new URLSearchParams;n!=null&&n.download&&i.set("download",n.download===!0?"":n.download),(n==null?void 0:n.cacheNonce)!=null&&i.set("cacheNonce",String(n.cacheNonce));const a=i.toString();return s.map(o=>xt(xt({},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",s=new URLSearchParams;e!=null&&e.transform&&this.applyTransformOptsToQuery(s,e.transform),(e==null?void 0:e.cacheNonce)!=null&&s.set("cacheNonce",String(e.cacheNonce));const i=s.toString(),a=this._getFinalPath(t),o=()=>Op(this.fetch,`${this.url}/${r}/${a}${i?`?${i}`:""}`,{headers:this.headers,noResolveJson:!0},n);return new fne(o,this.shouldThrowOnError)}async info(t){var e=this;const n=e._getFinalPath(t);return e.handleOperation(async()=>tw(await Op(e.fetch,`${e.url}/object/info/${n}`,{headers:e.headers})))}async exists(t){var e=this;const n=e._getFinalPath(t);try{return await dne(e.fetch,`${e.url}/object/${n}`,{headers:e.headers}),{data:!0,error:null}}catch(s){if(e.shouldThrowOnError)throw s;if(Gv(s)){var r;const i=s instanceof ew?s.status:s instanceof O3?(r=s.originalError)===null||r===void 0?void 0:r.status:void 0;if(i!==void 0&&[400,404].includes(i))return{data:!1,error:s}}throw s}}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 s=r.toString(),i=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}/${i}/public/${n}`)+(s?`?${s}`:"")}}}async remove(t){var e=this;return e.handleOperation(async()=>await J1(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 s=xt(xt(xt({},pne),e),{},{prefix:t||""});return await Fi(r.fetch,`${r.url}/object/list/${r.bucketId}`,s,{headers:r.headers},n)})}async listV2(t,e){var n=this;return n.handleOperation(async()=>{const r=xt({},t);return await Fi(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 gne="2.105.1",Rm={"X-Client-Info":`storage-js/${gne}`};var yne=class extends Vh{constructor(t,e={},n,r){const s=new URL(t);r!=null&&r.useNewHostname&&/supabase\.(co|in|red)$/.test(s.hostname)&&!s.hostname.includes("storage.supabase.")&&(s.hostname=s.hostname.replace("supabase.","storage.supabase."));const i=s.href.replace(/\/$/,""),a=xt(xt({},Rm),e);super(i,a,n,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const n=e.listBucketOptionsToQueryString(t);return await Op(e.fetch,`${e.url}/bucket${n}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Op(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var n=this;return n.handleOperation(async()=>await Fi(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 nw(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 Fi(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await J1(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():""}},vne=class extends Vh{constructor(t,e={},n){const r=t.replace(/\/$/,""),s=xt(xt({},Rm),e);super(r,s,n,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Fi(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(),s=r?`${e.url}/bucket?${r}`:`${e.url}/bucket`;return await Op(e.fetch,s,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await J1(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!one(t))throw new Vv("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 ene({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),r=this.shouldThrowOnError;return new Proxy(n,{get(s,i){const a=s[i];return typeof a!="function"?a:async(...o)=>{try{return{data:await a.apply(s,o),error:null}}catch(l){if(r)throw l;return{data:null,error:l}}}}})}},_ne=class extends Vh{constructor(t,e={},n){const r=t.replace(/\/$/,""),s=xt(xt({},Rm),{},{"Content-Type":"application/json"},e);super(r,s,n,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await Ws.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var n=this;return n.handleOperation(async()=>await Ws.post(n.fetch,`${n.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:n.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await Ws.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var n=this;return n.handleOperation(async()=>await Ws.post(n.fetch,`${n.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:n.headers})||{})}},bne=class extends Vh{constructor(t,e={},n){const r=t.replace(/\/$/,""),s=xt(xt({},Rm),{},{"Content-Type":"application/json"},e);super(r,s,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 Ws.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await Ws.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 Ws.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await Ws.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 Ws.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},xne=class extends Vh{constructor(t,e={},n){const r=t.replace(/\/$/,""),s=xt(xt({},Rm),{},{"Content-Type":"application/json"},e);super(r,s,n,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Ws.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Ws.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await Ws.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ws.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},Sne=class extends xne{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new Ene(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)}},Ene=class extends _ne{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,xt(xt({},t),{},{vectorBucketName:n.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,n=this;return e().call(n,xt(xt({},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 wne(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},wne=class extends bne{constructor(t,e,n,r,s){super(t,e,s),this.vectorBucketName=n,this.indexName=r}async putVectors(t){var e=()=>super.putVectors,n=this;return e().call(n,xt(xt({},t),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async getVectors(t){var e=()=>super.getVectors,n=this;return e().call(n,xt(xt({},t),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,n=this;return e().call(n,xt(xt({},t),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,n=this;return e().call(n,xt(xt({},t),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,n=this;return e().call(n,xt(xt({},t),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}},Tne=class extends yne{constructor(t,e={},n,r){super(t,e,n,r)}from(t){return new mne(this.url,this.headers,t,this.fetch)}get vectors(){return new Sne(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new vne(this.url+"/iceberg",this.headers,this.fetch)}};const j3="2.105.1",Zu=30*1e3,rw=3,Kb=rw*Zu,Ane="http://localhost:9999",Rne="supabase.auth.token",Cne={"X-Client-Info":`gotrue-js/${j3}`},sw="X-Supabase-Api-Version",U3={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},kne=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Lne=10*60*1e3;class Np 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 et(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class Ine extends Np{constructor(e,n,r){super(e,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function Pne(t){return et(t)&&t.name==="AuthApiError"}class Ki extends Np{constructor(e,n){super(e),this.name="AuthUnknownError",this.originalError=n}}class Io extends Np{constructor(e,n,r,s){super(e,r,s),this.name=n,this.status=r}}class Rr extends Io{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function Ag(t){return et(t)&&t.name==="AuthSessionMissingError"}class Iu extends Io{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class Rg extends Io{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Cg extends Io{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 Dne(t){return et(t)&&t.name==="AuthImplicitGrantRedirectError"}class TI extends Io{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 One extends Io{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 iw extends Io{constructor(e,n){super(e,"AuthRetryableFetchError",n,void 0)}}function Hb(t){return et(t)&&t.name==="AuthRetryableFetchError"}class AI extends Io{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 aw extends Io{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const M0="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),RI=` 	
\r=`.split(""),Nne=(()=>{const t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<RI.length;e+=1)t[RI[e].charCodeAt(0)]=-2;for(let e=0;e<M0.length;e+=1)t[M0[e].charCodeAt(0)]=e;return t})();function CI(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(M0[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(M0[r]),e.queuedBits-=6}}function B3(t,e,n){const r=Nne[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 kI(t){const e=[],n=a=>{e.push(String.fromCodePoint(a))},r={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=a=>{Une(a,r,n)};for(let a=0;a<t.length;a+=1)B3(t.charCodeAt(a),s,i);return e.join("")}function Mne(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 jne(t,e){for(let n=0;n<t.length;n+=1){let r=t.charCodeAt(n);if(r>55295&&r<=56319){const s=(r-55296)*1024&65535;r=(t.charCodeAt(n+1)-56320&65535|s)+65536,n+=1}Mne(r,e)}}function Une(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 Dd(t){const e=[],n={queue:0,queuedBits:0},r=s=>{e.push(s)};for(let s=0;s<t.length;s+=1)B3(t.charCodeAt(s),n,r);return new Uint8Array(e)}function Bne(t){const e=[];return jne(t,n=>e.push(n)),new Uint8Array(e)}function Ec(t){const e=[],n={queue:0,queuedBits:0},r=s=>{e.push(s)};return t.forEach(s=>CI(s,n,r)),CI(null,n,r),e.join("")}function Fne(t){return Math.round(Date.now()/1e3)+t}function $ne(){return Symbol("auth-callback")}const Ur=()=>typeof window<"u"&&typeof document<"u",ac={tested:!1,writable:!1},F3=()=>{if(!Ur())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(ac.tested)return ac.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),ac.tested=!0,ac.writable=!0}catch{ac.tested=!0,ac.writable=!1}return ac.writable};function Vne(t){const e={},n=new URL(t);if(n.hash&&n.hash[0]==="#")try{new URLSearchParams(n.hash.substring(1)).forEach((s,i)=>{e[i]=s})}catch{}return n.searchParams.forEach((r,s)=>{e[s]=r}),e}const $3=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Gne=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",ed=async(t,e,n)=>{await t.setItem(e,JSON.stringify(n))},oc=async(t,e)=>{const n=await t.getItem(e);if(!n)return null;try{return JSON.parse(n)}catch{return n}},Mr=async(t,e)=>{await t.removeItem(e)};class Kv{constructor(){this.promise=new Kv.promiseConstructor((e,n)=>{this.resolve=e,this.reject=n})}}Kv.promiseConstructor=Promise;function kg(t){const e=t.split(".");if(e.length!==3)throw new aw("Invalid JWT structure");for(let r=0;r<e.length;r++)if(!kne.test(e[r]))throw new aw("JWT not in base64url format");return{header:JSON.parse(kI(e[0])),payload:JSON.parse(kI(e[1])),signature:Dd(e[2]),raw:{header:e[0],payload:e[1]}}}async function Kne(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function Hne(t,e){return new Promise((r,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{const a=await t(i);if(!e(i,null,a)){r(a);return}}catch(a){if(!e(i,a)){s(a);return}}})()})}function zne(t){return("0"+t.toString(16)).substr(-2)}function qne(){const e=new Uint32Array(56);if(typeof crypto>"u"){const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=n.length;let s="";for(let i=0;i<56;i++)s+=n.charAt(Math.floor(Math.random()*r));return s}return crypto.getRandomValues(e),Array.from(e,zne).join("")}async function Wne(t){const n=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",n),s=new Uint8Array(r);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}async function Yne(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 Wne(t);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Pu(t,e,n=!1){const r=qne();let s=r;n&&(s+="/recovery"),await ed(t,`${e}-code-verifier`,s);const i=await Yne(r);return[i,r===i?"plain":"s256"]}const Xne=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Qne(t){const e=t.headers.get(sw);if(!e||!e.match(Xne))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Jne(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 Zne(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 ere=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function za(t){if(!ere.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Ui(t){if(!t.passkey)throw new Error("@supabase/auth-js: the passkey API is experimental and disabled by default. Enable it by passing `auth: { experimental: { passkey: true } }` to createClient (or to the GoTrueClient constructor).")}function zb(){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 tre(t,e){return new Proxy(t,{get:(n,r,s)=>{if(r==="__isInsecureUserWarningProxy")return!0;if(typeof r=="symbol"){const i=r.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(n,r,s)}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,s)}})}function LI(t){return JSON.parse(JSON.stringify(t))}const gc=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),nre=[502,503,504,520,521,522,523,524,530];async function II(t){var e;if(!Gne(t))throw new iw(gc(t),0);if(nre.includes(t.status))throw new iw(gc(t),t.status);let n;try{n=await t.json()}catch(i){throw new Ki(gc(i),i)}let r;const s=Qne(t);if(s&&s.getTime()>=U3["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 AI(gc(n),t.status,((e=n.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(r==="session_not_found")throw new Rr}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((i,a)=>i&&typeof a=="string",!0))throw new AI(gc(n),t.status,n.weak_password.reasons);throw new Ine(gc(n),t.status||500,r)}const rre=(t,e,n,r)=>{const s={method:t,headers:(e==null?void 0:e.headers)||{}};return t==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),s.body=JSON.stringify(r),Object.assign(Object.assign({},s),n))};async function dt(t,e,n,r){var s;const i=Object.assign({},r==null?void 0:r.headers);i[sw]||(i[sw]=U3["2024-01-01"].name),r!=null&&r.jwt&&(i.Authorization=`Bearer ${r.jwt}`);const a=(s=r==null?void 0:r.query)!==null&&s!==void 0?s:{};r!=null&&r.redirectTo&&(a.redirect_to=r.redirectTo);const o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",l=await sre(t,e,n+o,{headers:i,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 sre(t,e,n,r,s,i){const a=rre(e,r,s,i);let o;try{o=await t(n,Object.assign({},a))}catch(l){throw console.error(l),new iw(gc(l),0)}if(o.ok||await II(o),r!=null&&r.noResolveJson)return o;try{return await o.json()}catch(l){await II(l)}}function hi(t){var e;let n=null;ore(t)&&(n=Object.assign({},t),t.expires_at||(n.expires_at=Fne(t.expires_in)));const r=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:n,user:r},error:null}}function PI(t){const e=hi(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 al(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function ire(t){return{data:t,error:null}}function are(t){const{action_link:e,email_otp:n,hashed_token:r,redirect_to:s,verification_type:i}=t,a=$h(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o={action_link:e,email_otp:n,hashed_token:r,redirect_to:s,verification_type:i},l=Object.assign({},a);return{data:{properties:o,user:l},error:null}}function DI(t){return t}function ore(t){return t.access_token&&t.refresh_token&&t.expires_in}const qb=["global","local","others"];class lre{constructor({url:e="",headers:n={},fetch:r,experimental:s}){this.url=e,this.headers=n,this.fetch=$3(r),this.experimental=s??{},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)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(e,n=qb[0]){if(qb.indexOf(n)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${qb.join(", ")}`);try{return await dt(this.fetch,"POST",`${this.url}/logout?scope=${n}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(et(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,n={}){try{return await dt(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:n.data},headers:this.headers,redirectTo:n.redirectTo,xform:al})}catch(r){if(et(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{const{options:n}=e,r=$h(e,["options"]),s=Object.assign(Object.assign({},r),n);return"newEmail"in r&&(s.new_email=r==null?void 0:r.newEmail,delete s.newEmail),await dt(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:are,redirectTo:n==null?void 0:n.redirectTo})}catch(n){if(et(n))return{data:{properties:null,user:null},error:n};throw n}}async createUser(e){try{return await dt(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:al})}catch(n){if(et(n))return{data:{user:null},error:n};throw n}}async listUsers(e){var n,r,s,i,a,o,l;try{const c={nextPage:null,lastPage:0,total:0},u=await dt(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:(i=(s=e==null?void 0:e.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:DI});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(m=>{const g=parseInt(m.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(m.split(";")[1].split("=")[1]);c[`${y}Page`]=g}),c.total=parseInt(h)),{data:Object.assign(Object.assign({},d),c),error:null}}catch(c){if(et(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){za(e);try{return await dt(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:al})}catch(n){if(et(n))return{data:{user:null},error:n};throw n}}async updateUserById(e,n){za(e);try{return await dt(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:n,headers:this.headers,xform:al})}catch(r){if(et(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,n=!1){za(e);try{return await dt(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:n},xform:al})}catch(r){if(et(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){za(e.userId);try{const{data:n,error:r}=await dt(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:n,error:r}}catch(n){if(et(n))return{data:null,error:n};throw n}}async _deleteFactor(e){za(e.userId),za(e.id);try{return{data:await dt(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(n){if(et(n))return{data:null,error:n};throw n}}async _listOAuthClients(e){var n,r,s,i,a,o,l;try{const c={nextPage:null,lastPage:0,total:0},u=await dt(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:(i=(s=e==null?void 0:e.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:DI});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(m=>{const g=parseInt(m.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(m.split(";")[1].split("=")[1]);c[`${y}Page`]=g}),c.total=parseInt(h)),{data:Object.assign(Object.assign({},d),c),error:null}}catch(c){if(et(c))return{data:{clients:[]},error:c};throw c}}async _createOAuthClient(e){try{return await dt(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(et(n))return{data:null,error:n};throw n}}async _getOAuthClient(e){try{return await dt(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(et(n))return{data:null,error:n};throw n}}async _updateOAuthClient(e,n){try{return await dt(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:n,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(et(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(e){try{return await dt(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(n){if(et(n))return{data:null,error:n};throw n}}async _regenerateOAuthClientSecret(e){try{return await dt(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(et(n))return{data:null,error:n};throw n}}async _listCustomProviders(e){try{const n={};return e!=null&&e.type&&(n.type=e.type),await dt(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:n,xform:r=>{var s;return{data:{providers:(s=r==null?void 0:r.providers)!==null&&s!==void 0?s:[]},error:null}}})}catch(n){if(et(n))return{data:{providers:[]},error:n};throw n}}async _createCustomProvider(e){try{return await dt(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(et(n))return{data:null,error:n};throw n}}async _getCustomProvider(e){try{return await dt(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(et(n))return{data:null,error:n};throw n}}async _updateCustomProvider(e,n){try{return await dt(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:n,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(et(r))return{data:null,error:r};throw r}}async _deleteCustomProvider(e){try{return await dt(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(n){if(et(n))return{data:null,error:n};throw n}}async _adminListPasskeys(e){Ui(this.experimental),za(e.userId);try{return await dt(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(et(n))return{data:null,error:n};throw n}}async _adminDeletePasskey(e){Ui(this.experimental),za(e.userId),za(e.passkeyId);try{return await dt(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(n){if(et(n))return{data:null,error:n};throw n}}}function OI(t={}){return{getItem:e=>t[e]||null,setItem:(e,n)=>{t[e]=n},removeItem:e=>{delete t[e]}}}const ra={debug:!!(globalThis&&F3()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class V3 extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class NI extends V3{}async function cre(t,e,n){ra.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);const r=new globalThis.AbortController;let s;e>0&&(s=setTimeout(()=>{r.abort(),ra.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 i=>{if(i){clearTimeout(s),ra.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,i.name);try{return await n()}finally{ra.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,i.name)}}else{if(e===0)throw ra.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new NI(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(ra.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(s),await n()}})}catch(i){if(e>0&&clearTimeout(s),(i==null?void 0:i.name)==="AbortError"&&e>0){if(r.signal.aborted)return ra.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){ra.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,a.name);try{return await n()}finally{ra.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 ra.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new NI(`Lock "${t}" was released because another request stole it`)}throw i}}function ure(){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 G3(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function dre(t){return parseInt(t,16)}function hre(t){const e=new TextEncoder().encode(t);return"0x"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}function fre(t){var e;const{chainId:n,domain:r,expirationTime:s,issuedAt:i=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=G3(t.address),m=u?`${u}://${r}`:r,g=t.statement?`${t.statement}
`:"",y=`${m} wants you to sign in with your Ethereum account:
${f}

${g}`;let v=`URI: ${d}
Version: ${h}
Chain ID: ${n}${a?`
Nonce: ${a}`:""}
Issued At: ${i.toISOString()}`;if(s&&(v+=`
Expiration Time: ${s.toISOString()}`),o&&(v+=`
Not Before: ${o.toISOString()}`),l&&(v+=`
Request ID: ${l}`),c){let _=`
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}`);_+=`
- ${S}`}v+=_}return`${y}
${v}`}class ur extends Error{constructor({message:e,code:n,cause:r,name:s}){var i;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=(i=s??(r instanceof Error?r.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=n}}class j0 extends ur{constructor(e,n){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n,message:e}),this.name="WebAuthnUnknownError",this.originalError=n}}function pre({error:t,options:e}){var n,r,s;const{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new ur({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.requireResidentKey)===!0)return new ur({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=i.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new ur({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new ur({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 ur({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new ur({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new ur({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new ur({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(K3(a)){if(i.rp.id!==a)return new ur({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new ur({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new ur({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 ur({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 ur({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function mre({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 ur({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new ur({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const r=window.location.hostname;if(K3(r)){if(n.rpId!==r)return new ur({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new ur({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new ur({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 ur({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}class gre{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 ow=new gre;function MI(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,s=$h(t,["challenge","user","excludeCredentials"]),i=Dd(e).buffer,a=Object.assign(Object.assign({},n),{id:Dd(n.id).buffer}),o=Object.assign(Object.assign({},s),{challenge:i,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:Dd(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return o}function jI(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=$h(t,["challenge","allowCredentials"]),s=Dd(e).buffer,i=Object.assign(Object.assign({},r),{challenge:s});if(n&&n.length>0){i.allowCredentials=new Array(n.length);for(let a=0;a<n.length;a++){const o=n[a];i.allowCredentials[a]=Object.assign(Object.assign({},o),{id:Dd(o.id).buffer,type:o.type||"public-key",transports:o.transports})}}return i}function UI(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:Ec(new Uint8Array(t.response.attestationObject)),clientDataJSON:Ec(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=n.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function BI(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const n=t,r=t.getClientExtensionResults(),s=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:Ec(new Uint8Array(s.authenticatorData)),clientDataJSON:Ec(new Uint8Array(s.clientDataJSON)),signature:Ec(new Uint8Array(s.signature)),userHandle:s.userHandle?Ec(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:r,authenticatorAttachment:(e=n.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function K3(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function U0(){var t,e;return!!(Ur()&&"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 H3(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new j0("Browser returned unexpected credential type",e)}:{data:null,error:new j0("Empty credential response",e)}}catch(e){return{data:null,error:pre({error:e,options:t})}}}async function z3(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new j0("Browser returned unexpected credential type",e)}:{data:null,error:new j0("Empty credential response",e)}}catch(e){return{data:null,error:mre({error:e,options:t})}}}const yre={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},vre={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function B0(...t){const e=s=>s!==null&&typeof s=="object"&&!Array.isArray(s),n=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),r={};for(const s of t)if(s)for(const i in s){const a=s[i];if(a!==void 0)if(Array.isArray(a))r[i]=a;else if(n(a))r[i]=a;else if(e(a)){const o=r[i];e(o)?r[i]=B0(o,a):r[i]=B0(a)}else r[i]=a}return r}function _re(t,e){return B0(yre,t,e||{})}function bre(t,e){return B0(vre,t,e||{})}class xre{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:s},i){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=s??ow.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,m=((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}:${m}`}}u.displayName||(u.displayName=u.name)}switch(o.webauthn.type){case"create":{const u=_re(o.webauthn.credential_options.publicKey,i==null?void 0:i.create),{data:d,error:h}=await H3({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=bre(o.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:d,error:h}=await z3(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 et(o)?{data:null,error:o}:{data:null,error:new Ki("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:s}={}},i){if(!n)return{data:null,error:new Np("rpId is required for WebAuthn authentication")};try{if(!U0())return{data:null,error:new Ki("Browser does not support WebAuthn",null)};const{data:a,error:o}=await this.challenge({factorId:e,webauthn:{rpId:n,rpOrigins:r},signal:s},{request:i});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 et(a)?{data:null,error:a}:{data:null,error:new Ki("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:s}={}},i){if(!n)return{data:null,error:new Np("rpId is required for WebAuthn registration")};try{if(!U0())return{data:null,error:new Ki("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:s},{create:i});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 et(a)?{data:null,error:a}:{data:null,error:new Ki("Unexpected error in register",a)}}}}ure();const Sre={url:Ane,storageKey:Rne,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Cne,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};async function FI(t,e,n){return await n()}const Du={};class Mp{get jwks(){var e,n;return(n=(e=Du[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&n!==void 0?n:{keys:[]}}set jwks(e){Du[this.storageKey]=Object.assign(Object.assign({},Du[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,n;return(n=(e=Du[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&n!==void 0?n:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Du[this.storageKey]=Object.assign(Object.assign({},Du[this.storageKey]),{cachedAt:e})}constructor(e){var n,r,s,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 a=Object.assign(Object.assign({},Sre),e);if(this.storageKey=a.storageKey,this.instanceID=(n=Mp.nextInstanceID[this.storageKey])!==null&&n!==void 0?n:0,Mp.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!a.debug,typeof a.debug=="function"&&(this.logger=a.debug),this.instanceID>0&&Ur()){const o=`${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(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=a.persistSession,this.autoRefreshToken=a.autoRefreshToken,this.experimental=(r=a.experimental)!==null&&r!==void 0?r:{},this.admin=new lre({url:a.url,headers:a.headers,fetch:a.fetch,experimental:this.experimental}),this.url=a.url,this.headers=a.headers,this.fetch=$3(a.fetch),this.lock=a.lock||FI,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,this.throwOnError=a.throwOnError,this.lockAcquireTimeout=a.lockAcquireTimeout,a.lock?this.lock=a.lock:this.persistSession&&Ur()&&(!((s=globalThis==null?void 0:globalThis.navigator)===null||s===void 0)&&s.locks)?this.lock=cre:this.lock=FI,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 xre(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.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(a.storage?this.storage=a.storage:F3()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=OI(this.memoryStorage)),a.userStorage&&(this.userStorage=a.userStorage)):(this.memoryStorage={},this.storage=OI(this.memoryStorage)),Ur()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(i=this.broadcastChannel)===null||i===void 0||i.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(l){this._debug("#broadcastChannel","error",l)}})}a.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${j3}) ${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(Ur()&&(n=Vne(window.location.href),this._isImplicitGrantCallback(n)?r="implicit":await this._isPKCECallback(n)&&(r="pkce")),Ur()&&this.detectSessionInUrl&&r!=="none"){const{data:s,error:i}=await this._getSessionFromURL(n,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Dne(i)){const l=(e=i.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:i}}return{error:i}}const{session:a,redirectType:o}=s;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 et(n)?this._returnResult({error:n}):this._returnResult({error:new Ki("Unexpected error during initialization",n)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var n,r,s;try{const i=await dt(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:(s=e==null?void 0:e.options)===null||s===void 0?void 0:s.captchaToken}},xform:hi}),{data:a,error:o}=i;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(i){if(et(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var n,r,s;try{let i;if("email"in e){const{email:u,password:d,options:h}=e;let f=null,m=null;this.flowType==="pkce"&&([f,m]=await Pu(this.storage,this.storageKey)),i=await dt(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:m},xform:hi})}else if("phone"in e){const{phone:u,password:d,options:h}=e;i=await dt(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:(s=h==null?void 0:h.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:h==null?void 0:h.captchaToken}},xform:hi})}else throw new Rg("You must provide either an email or phone number and a password");const{data:a,error:o}=i;if(o||!a)return await Mr(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(i){if(await Mr(this.storage,`${this.storageKey}-code-verifier`),et(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(e){try{let n;if("email"in e){const{email:i,password:a,options:o}=e;n=await dt(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:a,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:PI})}else if("phone"in e){const{phone:i,password:a,options:o}=e;n=await dt(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:a,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:PI})}else throw new Rg("You must provide either an email or phone number and a password");const{data:r,error:s}=n;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){const i=new Iu;return this._returnResult({data:{user:null,session:null},error:i})}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:s})}catch(n){if(et(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithOAuth(e){var n,r,s,i;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:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.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,s,i,a,o,l,c,u,d,h;let f,m;if("message"in e)f=e.message,m=e.signature;else{const{chain:g,wallet:y,statement:v,options:_}=e;let S;if(Ur())if(typeof y=="object")S=y;else{const k=window;if("ethereum"in k&&typeof k.ethereum=="object"&&"request"in k.ethereum&&typeof k.ethereum.request=="function")S=k.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 y!="object"||!(_!=null&&_.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");S=y}const E=new URL((n=_==null?void 0:_.url)!==null&&n!==void 0?n:window.location.href),L=await S.request({method:"eth_requestAccounts"}).then(k=>k).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=G3(L[0]);let P=(r=_==null?void 0:_.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!P){const k=await S.request({method:"eth_chainId"});P=dre(k)}const I={domain:E.host,address:U,statement:v,uri:E.href,version:"1",chainId:P,nonce:(s=_==null?void 0:_.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(a=(i=_==null?void 0:_.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&a!==void 0?a:new Date,expirationTime:(o=_==null?void 0:_.signInWithEthereum)===null||o===void 0?void 0:o.expirationTime,notBefore:(l=_==null?void 0:_.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(c=_==null?void 0:_.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(u=_==null?void 0:_.signInWithEthereum)===null||u===void 0?void 0:u.resources};f=fre(I),m=await S.request({method:"personal_sign",params:[hre(f),U]})}try{const{data:g,error:y}=await dt(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:m},!((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:hi});if(y)throw y;if(!g||!g.session||!g.user){const v=new Iu;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:y})}catch(g){if(et(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async signInWithSolana(e){var n,r,s,i,a,o,l,c,u,d,h,f;let m,g;if("message"in e)m=e.message,g=e.signature;else{const{chain:y,wallet:v,statement:_,options:S}=e;let E;if(Ur())if(typeof v=="object")E=v;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 v!="object"||!(S!=null&&S.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");E=v}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}),_?{statement:_}:null));let P;if(Array.isArray(U)&&U[0]&&typeof U[0]=="object")P=U[0];else if(U&&typeof U=="object"&&"signedMessage"in U&&"signature"in U)P=U;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in P&&"signature"in P&&(typeof P.signedMessage=="string"||P.signedMessage instanceof Uint8Array)&&P.signature instanceof Uint8Array)m=typeof P.signedMessage=="string"?P.signedMessage:new TextDecoder().decode(P.signedMessage),g=P.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");m=[`${L.host} wants you to sign in with your Solana account:`,E.publicKey.toBase58(),..._?["",_,""]:[""],"Version: 1",`URI: ${L.href}`,`Issued At: ${(s=(r=S==null?void 0:S.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=S==null?void 0:S.signInWithSolana)===null||i===void 0)&&i.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(P=>`- ${P}`)]:[]].join(`
`);const U=await E.signMessage(new TextEncoder().encode(m),"utf8");if(!U||!(U instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=U}}try{const{data:y,error:v}=await dt(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:m,signature:Ec(g)},!((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:hi});if(v)throw v;if(!y||!y.session||!y.user){const _=new Iu;return this._returnResult({data:{user:null,session:null},error:_})}return y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),this._returnResult({data:Object.assign({},y),error:v})}catch(y){if(et(y))return this._returnResult({data:{user:null,session:null},error:y});throw y}}async _exchangeCodeForSession(e){const n=await oc(this.storage,`${this.storageKey}-code-verifier`),[r,s]=(n??"").split("/");try{if(!r&&this.flowType==="pkce")throw new One;const{data:i,error:a}=await dt(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:hi});if(await Mr(this.storage,`${this.storageKey}-code-verifier`),a)throw a;if(!i||!i.session||!i.user){const o=new Iu;return this._returnResult({data:{user:null,session:null,redirectType:null},error:o})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers(s==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:s??null}),error:a})}catch(i){if(await Mr(this.storage,`${this.storageKey}-code-verifier`),et(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{const{options:n,provider:r,token:s,access_token:i,nonce:a}=e,o=await dt(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:a,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}},xform:hi}),{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 Iu;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(et(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithOtp(e){var n,r,s,i,a;try{if("email"in e){const{email:o,options:l}=e;let c=null,u=null;this.flowType==="pkce"&&([c,u]=await Pu(this.storage,this.storageKey));const{error:d}=await dt(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 dt(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(s=l==null?void 0:l.data)!==null&&s!==void 0?s:{},create_user:(i=l==null?void 0:l.shouldCreateUser)!==null&&i!==void 0?i:!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 Rg("You must provide either an email or phone number.")}catch(o){if(await Mr(this.storage,`${this.storageKey}-code-verifier`),et(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async verifyOtp(e){var n,r;try{let s,i;"options"in e&&(s=(n=e.options)===null||n===void 0?void 0:n.redirectTo,i=(r=e.options)===null||r===void 0?void 0:r.captchaToken);const{data:a,error:o}=await dt(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:hi});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(s){if(et(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(e){var n,r,s,i,a;try{let o=null,l=null;this.flowType==="pkce"&&([o,l]=await Pu(this.storage,this.storageKey));const c=await dt(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}),!((s=e==null?void 0:e.options)===null||s===void 0)&&s.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:ire});return!((i=c.data)===null||i===void 0)&&i.url&&Ur()&&!(!((a=e.options)===null||a===void 0)&&a.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(o){if(await Mr(this.storage,`${this.storageKey}-code-verifier`),et(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 Rr;const{error:s}=await dt(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(et(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:s,options:i}=e,{error:a}=await dt(this.fetch,"POST",n,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}else if("phone"in e){const{phone:r,type:s,options:i}=e,{data:a,error:o}=await dt(this.fetch,"POST",n,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a==null?void 0:a.message_id},error:o})}throw new Rg("You must provide either an email or phone number and a type")}catch(n){if(et(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(),s=(async()=>(await r,await n()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}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 s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.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 oc(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()<Kb:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.userStorage){const a=await oc(this.userStorage,this.storageKey+"-user");a!=null&&a.user?e.user=a.user:e.user=zb()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const a={value:this.suppressGetSessionWarning};e.user=tre(e.user,a),a.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:s},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 dt(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:al}):await this._useSession(async n=>{var r,s,i;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 Rr}:await dt(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=a.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:al})})}catch(n){if(et(n))return Ag(n)&&(await this._removeSession(),await Mr(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:s,error:i}=r;if(i)throw i;if(!s.session)throw new Rr;const a=s.session;let o=null,l=null;this.flowType==="pkce"&&e.email!=null&&([o,l]=await Pu(this.storage,this.storageKey));const{data:c,error:u}=await dt(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:al});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 Mr(this.storage,`${this.storageKey}-code-verifier`),et(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 Rr;const n=Date.now()/1e3;let r=n,s=!0,i=null;const{payload:a}=kg(e.access_token);if(a.exp&&(r=a.exp,s=r<=n),s){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};i=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});i={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(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(n){if(et(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 Rr;const{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(n){if(et(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async _getSessionFromURL(e,n){var r;try{if(!Ur())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 TI("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 TI("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:s,provider_refresh_token:i,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 m=f-d;m*1e3<=Zu&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${h}s`);const g=f-h;d-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,f,d):d-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",g,f,d);const{data:y,error:v}=await this._getUser(a);if(v)throw v;const _={provider_token:s,provider_refresh_token:i,access_token:a,expires_in:h,expires_at:f,refresh_token:o,token_type:u,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:_,redirectType:e.type},error:null})}catch(s){if(et(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_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 oc(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:s,error:i}=n;if(i&&!Ag(i))return this._returnResult({error:i});const a=(r=s.session)===null||r===void 0?void 0:r.access_token;if(a){const{error:o}=await this.admin.signOut(a,e);if(o&&!(Pne(o)&&(o.status===404||o.status===401||o.status===403)||Ag(o)))return this._returnResult({error:o})}return e!=="others"&&(await this._removeSession(),await Mr(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const n=$ne(),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,s;try{const{data:{session:i},error:a}=n;if(a)throw a;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),Ag(i)?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,n={}){let r=null,s=null;this.flowType==="pkce"&&([r,s]=await Pu(this.storage,this.storageKey,!0));try{return await dt(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:n.captchaToken}},headers:this.headers,redirectTo:n.redirectTo})}catch(i){if(await Mr(this.storage,`${this.storageKey}-code-verifier`),et(i))return this._returnResult({data:null,error:i});throw i}}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(et(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:s}=await this._useSession(async i=>{var a,o,l,c,u;const{data:d,error:h}=i;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 dt(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(s)throw s;return Ur()&&!(!((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(et(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:s,data:{session:i}}=n;if(s)throw s;const{options:a,provider:o,token:l,access_token:c,nonce:u}=e,d=await dt(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=i==null?void 0:i.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:hi}),{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 Iu}):(h.session&&(await this._saveSession(h.session),await this._notifyAllSubscribers("USER_UPDATED",h.session)),this._returnResult({data:h,error:f}))}catch(s){if(await Mr(this.storage,`${this.storageKey}-code-verifier`),et(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(e){try{return await this._useSession(async n=>{var r,s;const{data:i,error:a}=n;if(a)throw a;return await dt(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&s!==void 0?s:void 0})})}catch(n){if(et(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 Hne(async s=>(s>0&&await Kne(200*Math.pow(2,s-1)),this._debug(n,"refreshing attempt",s),await dt(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:hi})),(s,i)=>{const a=200*Math.pow(2,s);return i&&Hb(i)&&Date.now()+a-r<Zu})}catch(r){if(this._debug(n,"error",r),et(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),Ur()&&!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 s=await oc(this.storage,this.storageKey);if(s&&this.userStorage){let a=await oc(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:s.user},await ed(this.userStorage,this.storageKey+"-user",a)),s.user=(e=a==null?void 0:a.user)!==null&&e!==void 0?e:zb()}else if(s&&!s.user&&!s.user){const a=await oc(this.storage,this.storageKey+"-user");a&&(a!=null&&a.user)?(s.user=a.user,await Mr(this.storage,this.storageKey+"-user"),await ed(this.storage,this.storageKey,s)):s.user=zb()}if(this._debug(r,"session from storage",s),!this._isValidSession(s)){this._debug(r,"session is not valid"),s!==null&&await this._removeSession();return}const i=((n=s.expires_at)!==null&&n!==void 0?n:1/0)*1e3-Date.now()<Kb;if(this._debug(r,`session has${i?"":" not"} expired with margin of ${Kb}s`),i){if(this.autoRefreshToken&&s.refresh_token){const{error:a}=await this._callRefreshToken(s.refresh_token);a&&(console.error(a),Hb(a)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",a),await this._removeSession()))}}else if(s.user&&s.user.__isUserNotAvailableProxy===!0)try{const{data:a,error:o}=await this._getUser(s.access_token);!o&&(a!=null&&a.user)?(s.user=a.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):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",s)}catch(s){this._debug(r,"error",s),console.error(s);return}finally{this._debug(r,"end")}}async _callRefreshToken(e){var n,r;if(!e)throw new Rr;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new Kv;const{data:i,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!i.session)throw new Rr;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);const o={data:i.session,error:null};return this.refreshingDeferred.resolve(o),o}catch(i){if(this._debug(s,"error",i),et(i)){const a={data:null,error:i};return Hb(i)||await this._removeSession(),(n=this.refreshingDeferred)===null||n===void 0||n.resolve(a),a}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,n,r=!0){const s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",n,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:n});const i=[],a=Array.from(this.stateChangeEmitters.values()).map(async o=>{try{await o.callback(e,n)}catch(l){i.push(l)}});if(await Promise.all(a),i.length>0){for(let o=0;o<i.length;o+=1)console.error(i[o]);throw i[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Mr(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 ed(this.userStorage,this.storageKey+"-user",{user:n.user});const s=Object.assign({},n);delete s.user;const i=LI(s);await ed(this.storage,this.storageKey,i)}else{const s=LI(n);await ed(this.storage,this.storageKey,s)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Mr(this.storage,this.storageKey),await Mr(this.storage,this.storageKey+"-code-verifier"),await Mr(this.storage,this.storageKey+"-user"),this.userStorage&&await Mr(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Ur()&&(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(),Zu);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 s=Math.floor((r.expires_at*1e3-e)/Zu);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${Zu}ms, refresh threshold is ${rw} ticks`),s<=rw&&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 V3)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ur()||!(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 s=[`provider=${encodeURIComponent(n)}`];if(r!=null&&r.redirectTo&&s.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r!=null&&r.scopes&&s.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){const[i,a]=await Pu(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(a)}`});s.push(o.toString())}if(r!=null&&r.queryParams){const i=new URLSearchParams(r.queryParams);s.push(i.toString())}return r!=null&&r.skipBrowserRedirect&&s.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async n=>{var r;const{data:s,error:i}=n;return i?this._returnResult({data:null,error:i}):await dt(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=s==null?void 0:s.session)===null||r===void 0?void 0:r.access_token})})}catch(n){if(et(n))return this._returnResult({data:null,error:n});throw n}}async _enroll(e){try{return await this._useSession(async n=>{var r,s;const{data:i,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 dt(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token});return c?this._returnResult({data:null,error:c}):(e.factorType==="totp"&&l.type==="totp"&&(!((s=l==null?void 0:l.totp)===null||s===void 0)&&s.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(et(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:s,error:i}=n;if(i)return this._returnResult({data:null,error:i});const a=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?UI(e.webauthn.credential_response):BI(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:l}=await dt(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:a,headers:this.headers,jwt:(r=s==null?void 0:s.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(et(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:s,error:i}=n;if(i)return this._returnResult({data:null,error:i});const a=await dt(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(r=s==null?void 0:s.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:MI(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:jI(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(n){if(et(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 s={all:[],phone:[],totp:[],webauthn:[]};for(const i of(e=n==null?void 0:n.factors)!==null&&e!==void 0?e:[])s.all.push(i),i.status==="verified"&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var n,r,s,i;if(e)try{const{payload:f}=kg(e);let m=null;f.aal&&(m=f.aal);let g=m;const{data:{user:y},error:v}=await this.getUser(e);if(v)return this._returnResult({data:null,error:v});((r=(n=y==null?void 0:y.factors)===null||n===void 0?void 0:n.filter(E=>E.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(g="aal2");const S=f.amr||[];return{data:{currentLevel:m,nextLevel:g,currentAuthenticationMethods:S},error:null}}catch(f){if(et(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}=kg(a.access_token);let c=null;l.aal&&(c=l.aal);let u=c;((i=(s=a.user.factors)===null||s===void 0?void 0:s.filter(f=>f.status==="verified"))!==null&&i!==void 0?i:[]).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:s}=n;return s?this._returnResult({data:null,error:s}):r?await dt(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new Rr})})}catch(n){if(et(n))return this._returnResult({data:null,error:n});throw n}}async _approveAuthorization(e,n){try{return await this._useSession(async r=>{const{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new Rr});const a=await dt(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&Ur()&&!(n!=null&&n.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(r){if(et(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(e,n){try{return await this._useSession(async r=>{const{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new Rr});const a=await dt(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:o=>({data:o,error:null})});return a.data&&a.data.redirect_url&&Ur()&&!(n!=null&&n.skipBrowserRedirect)&&window.location.assign(a.data.redirect_url),a})}catch(r){if(et(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 dt(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new Rr})})}catch(e){if(et(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:s}=n;return s?this._returnResult({data:null,error:s}):r?(await dt(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 Rr})})}catch(n){if(et(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 s=Date.now();if(r=this.jwks.keys.find(o=>o.kid===e),r&&this.jwks_cached_at+Lne>s)return r;const{data:i,error:a}=await dt(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,r=i.keys.find(o=>o.kid===e),!r)?null:r}async getClaims(e,n={}){try{let r=e;if(!r){const{data:f,error:m}=await this.getSession();if(m||!f.session)return this._returnResult({data:null,error:m});r=f.session.access_token}const{header:s,payload:i,signature:a,raw:{header:o,payload:l}}=kg(r);n!=null&&n.allowExpired||Jne(i.exp);const c=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.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:i,header:s,signature:a},error:null}}const u=Zne(s.alg),d=await crypto.subtle.importKey("jwk",c,u,!0,["verify"]);if(!await crypto.subtle.verify(u,d,a,Bne(`${o}.${l}`)))throw new aw("Invalid JWT signature");return{data:{claims:i,header:s,signature:a},error:null}}catch(r){if(et(r))return this._returnResult({data:null,error:r});throw r}}async signInWithPasskey(e){var n,r,s;Ui(this.experimental);try{if(!U0())return this._returnResult({data:null,error:new Ki("Browser does not support WebAuthn",null)});const{data:i,error:a}=await this._startPasskeyAuthentication({options:{captchaToken:(n=e==null?void 0:e.options)===null||n===void 0?void 0:n.captchaToken}});if(a||!i)return this._returnResult({data:null,error:a});const o=jI(i.options),l=(s=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:ow.createNewAbortSignal(),{data:c,error:u}=await z3({publicKey:o,signal:l});if(u||!c)return this._returnResult({data:null,error:u??new Ki("WebAuthn ceremony failed",null)});const d=BI(c);return this._verifyPasskeyAuthentication({challengeId:i.challenge_id,credential:d})}catch(i){if(et(i))return this._returnResult({data:null,error:i});throw i}}async registerPasskey(e){var n,r;Ui(this.experimental);try{if(!U0())return this._returnResult({data:null,error:new Ki("Browser does not support WebAuthn",null)});const{data:s,error:i}=await this._startPasskeyRegistration();if(i||!s)return this._returnResult({data:null,error:i});const a=MI(s.options),o=(r=(n=e==null?void 0:e.options)===null||n===void 0?void 0:n.signal)!==null&&r!==void 0?r:ow.createNewAbortSignal(),{data:l,error:c}=await H3({publicKey:a,signal:o});if(c||!l)return this._returnResult({data:null,error:c??new Ki("WebAuthn ceremony failed",null)});const u=UI(l);return this._verifyPasskeyRegistration({challengeId:s.challenge_id,credential:u})}catch(s){if(et(s))return this._returnResult({data:null,error:s});throw s}}async _startPasskeyRegistration(){Ui(this.experimental);try{return await this._useSession(async e=>{const{data:{session:n},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!n)return this._returnResult({data:null,error:new Rr});const{data:s,error:i}=await dt(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:n.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(et(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){Ui(this.experimental);try{return await this._useSession(async n=>{const{data:{session:r},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new Rr});const{data:i,error:a}=await dt(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:r.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(n){if(et(n))return this._returnResult({data:null,error:n});throw n}}async _startPasskeyAuthentication(e){var n;Ui(this.experimental);try{const{data:r,error:s}=await dt(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(n=e==null?void 0:e.options)===null||n===void 0?void 0:n.captchaToken}}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:r,error:null})}catch(r){if(et(r))return this._returnResult({data:null,error:r});throw r}}async _verifyPasskeyAuthentication(e){Ui(this.experimental);try{const{data:n,error:r}=await dt(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:hi});return r?this._returnResult({data:null,error:r}):(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:n,error:null}))}catch(n){if(et(n))return this._returnResult({data:null,error:n});throw n}}async _listPasskeys(){Ui(this.experimental);try{return await this._useSession(async e=>{const{data:{session:n},error:r}=e;if(r)return this._returnResult({data:null,error:r});if(!n)return this._returnResult({data:null,error:new Rr});const{data:s,error:i}=await dt(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:n.access_token,xform:a=>({data:a,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:s,error:null})})}catch(e){if(et(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){Ui(this.experimental);try{return await this._useSession(async n=>{const{data:{session:r},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new Rr});const{data:i,error:a}=await dt(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,body:{friendly_name:e.friendlyName}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(n){if(et(n))return this._returnResult({data:null,error:n});throw n}}async _deletePasskey(e){Ui(this.experimental);try{return await this._useSession(async n=>{const{data:{session:r},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new Rr});const{error:i}=await dt(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:r.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(n){if(et(n))return this._returnResult({data:null,error:n});throw n}}}Mp.nextInstanceID={};const Ere=Mp,wre="2.105.1";let Ef="";typeof Deno<"u"?Ef="deno":typeof document<"u"?Ef="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ef="react-native":Ef="node";const Tre={"X-Client-Info":`supabase-js-${Ef}/${wre}`},Are={headers:Tre},Rre={schema:"public"},Cre={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},kre={};function jp(t){"@babel/helpers - typeof";return jp=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},jp(t)}function Lre(t,e){if(jp(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(jp(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Ire(t){var e=Lre(t,"string");return jp(e)=="symbol"?e:e+""}function Pre(t,e,n){return(e=Ire(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function $I(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),n.push.apply(n,r)}return n}function Yn(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?$I(Object(n),!0).forEach(function(r){Pre(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):$I(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}const Dre=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Ore=()=>Headers,Nre=(t,e,n)=>{const r=Dre(n),s=Ore();return async(i,a)=>{var o;const l=(o=await e())!==null&&o!==void 0?o:t;let c=new s(a==null?void 0:a.headers);return c.has("apikey")||c.set("apikey",t),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),r(i,Yn(Yn({},a),{},{headers:c}))}};function Mre(t){return t.endsWith("/")?t:t+"/"}function jre(t,e){var n,r;const{db:s,auth:i,realtime:a,global:o}=t,{db:l,auth:c,realtime:u,global:d}=e,h={db:Yn(Yn({},l),s),auth:Yn(Yn({},c),i),realtime:Yn(Yn({},u),a),storage:{},global:Yn(Yn(Yn({},d),o),{},{headers:Yn(Yn({},(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 Ure(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(Mre(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Bre=class extends Ere{constructor(t){super(t)}},Fre=class{constructor(t,e,n){var r,s;this.supabaseUrl=t,this.supabaseKey=e;const i=Ure(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const a=`sb-${i.hostname.split(".")[0]}-auth-token`,o={db:Rre,realtime:kre,auth:Yn(Yn({},Cre),{},{storageKey:a}),global:Are},l=jre(n??{},o);if(this.storageKey=(r=l.auth.storageKey)!==null&&r!==void 0?r:"",this.headers=(s=l.global.headers)!==null&&s!==void 0?s:{},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=Nre(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Yn({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 pte(new URL("rest/v1",i).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new Tne(this.storageUrl.href,this.headers,this.fetch,n==null?void 0:n.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new ste(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:s,storageKey:i,flowType:a,lock:o,debug:l,throwOnError:c,experimental:u},d,h){const f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Bre({url:this.authUrl.href,headers:Yn(Yn({},f),d),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:n,storage:r,userStorage:s,flowType:a,lock:o,debug:l,throwOnError:c,experimental:u,fetch:h,hasCustomAuthorizationHeader:Object.keys(this.headers).some(m=>m.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Wte(this.realtimeUrl.href,Yn(Yn({},t),{},{params:Yn(Yn({},{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 $re=(t,e,n)=>new Fre(t,e,n);function Vre(){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}Vre()&&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 Gre="https://placeholder.supabase.co",Kre="placeholder-anon-key",Hre=Gre,zre=Kre,qre=$re(Hre,zre,{auth:{storage:localStorage,persistSession:!0,autoRefreshToken:!0}}),ol=pu("NativePlayer"),Cm=()=>rs.isNativePlatform(),Wre=()=>rs.getPlatform(),q3=[{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"}],W3="livetv.ua",_i=()=>{try{const t=localStorage.getItem(W3);if(t)return t}catch{}return q3[0].value},Yre=t=>{try{localStorage.setItem(W3,t)}catch{}},Od={},lw=Od==null?void 0:Od.VITE_SUPABASE_URL,Xre=t=>{if(t==null)return;const e=String(t).trim();if(!e)return;const n=e.match(/https?:\/\/[^\s\])>"']+/i);if(n)return n[0].replace(/\/+$/,"")},Qre=(Od==null?void 0:Od.VITE_BACKEND_URL)||"https://nadiplayer-edit.preview.emergentagent.com",VI=Xre(Qre),Y3=t=>{if(!t)return!1;try{const e=new URL(t);return e.hostname.includes("placeholder")?!1:e.hostname.endsWith(".supabase.co")}catch{return!1}},X3=()=>Y3(lw)?`${lw.replace(/\/$/,"")}/functions/v1/iptv-proxy`:VI?`${VI.replace(/\/$/,"")}/api/iptv-proxy`:"/api/iptv-proxy",Jre=()=>Y3(lw)?"supabase":"backend",Q3=async(t,e="json")=>{var i;if(Cm()){const a=await b3.request({url:t,method:"GET",headers:{"User-Agent":_i(),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=X3(),r={"Content-Type":"application/json"};if(Jre()==="supabase"){const{data:a}=await qre.auth.getSession(),o=void 0;r.Authorization=`Bearer ${((i=a.session)==null?void 0:i.access_token)??o??""}`}const s=await fetch(n,{method:"POST",headers:r,body:JSON.stringify({url:t,responseType:e,ua:_i()})});if(!s.ok){const a=s.headers.get("x-proxy-error")||await s.text().catch(()=>"")||`Proxy ${s.status}`;throw new Error(a)}return e==="text"?await s.text():await s.json()},Zre=Object.freeze(Object.defineProperty({__proto__:null,proxyFetch:Q3},Symbol.toStringTag,{value:"Module"})),qa=(t,e,n={})=>{const r=t.serverUrl.replace(/\/$/,""),s=new URLSearchParams({username:t.username,password:t.password,...e?{action:e}:{},...n});return`${r}/player_api.php?${s.toString()}`},Wa=async t=>Q3(t,"json"),fs={async authenticate(t){const e=await Wa(qa(t));if(!(e!=null&&e.user_info)||e.user_info.auth===0)throw new Error("Invalid credentials");return e},async getLiveCategories(t){return Wa(qa(t,"get_live_categories"))},async getVodCategories(t){return Wa(qa(t,"get_vod_categories"))},async getSeriesCategories(t){return Wa(qa(t,"get_series_categories"))},async getLiveStreams(t){const[e,n]=await Promise.all([Wa(qa(t,"get_live_streams")),this.getLiveCategories(t)]),r=new Map(n.map(i=>[i.category_id,i.category_name])),s=t.serverUrl.replace(/\/$/,"");return(e||[]).map(i=>({id:String(i.stream_id),name:i.name,category:r.get(String(i.category_id))??"Uncategorized",categoryId:String(i.category_id),streamUrl:`${s}/live/${t.username}/${t.password}/${i.stream_id}.m3u8`,logoUrl:i.stream_icon||void 0,epgChannelId:i.epg_channel_id||void 0}))},async getMovies(t){const[e,n]=await Promise.all([Wa(qa(t,"get_vod_streams")),this.getVodCategories(t)]),r=new Map(n.map(i=>[i.category_id,i.category_name])),s=t.serverUrl.replace(/\/$/,"");return(e||[]).map(i=>({id:String(i.stream_id),name:i.name,category:r.get(String(i.category_id))??"Uncategorized",categoryId:String(i.category_id),streamUrl:`${s}/movie/${t.username}/${t.password}/${i.stream_id}.${i.container_extension||"mp4"}`,posterUrl:i.stream_icon||void 0,rating:i.rating?String(i.rating):void 0,year:i.year||void 0,containerExtension:i.container_extension}))},async getSeries(t){const[e,n]=await Promise.all([Wa(qa(t,"get_series")),this.getSeriesCategories(t)]),r=new Map(n.map(s=>[s.category_id,s.category_name]));return(e||[]).map(s=>({id:String(s.series_id),name:s.name,category:r.get(String(s.category_id))??"Uncategorized",categoryId:String(s.category_id),posterUrl:s.cover||void 0,rating:s.rating?String(s.rating):void 0,plot:s.plot||void 0}))},async getSeriesInfo(t,e){return Wa(qa(t,"get_series_info",{series_id:e}))},async getShortEpg(t,e,n=4){const r=await Wa(qa(t,"get_short_epg",{stream_id:e,limit:String(n)})),s=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?s(a.title):"",description:a.description?s(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}`}},ese="modulepreload",tse=function(t){return"/"+t},GI={},km=function(e,n,r){let s=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"));s=Promise.allSettled(n.map(l=>{if(l=tse(l),l in GI)return;GI[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":ese,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 i(a){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=a,window.dispatchEvent(o),!o.defaultPrevented)throw a}return s.then(a=>{for(const o of a||[])o.status==="rejected"&&i(o.reason);return e().catch(i)})},KI=t=>{const e=t.split(/\r?\n/),n=[];let r=null;for(let s=0;s<e.length;s++){const i=e[s].trim();if(i.startsWith("#EXTINF")){const a={},o=/([\w-]+)="([^"]*)"/g;let l;for(;(l=o.exec(i))!==null;)a[l[1]]=l[2];const c=i.lastIndexOf(",");r={name:c>=0?i.slice(c+1).trim():"Unknown",logo:a["tvg-logo"],group:a["group-title"]||"Uncategorized",tvgId:a["tvg-id"]}}else i&&!i.startsWith("#")&&r&&(r.url=i,n.push(r),r=null)}return n},nse=t=>/movie|vod|film|cinema|películas|peliculas/i.test(t),rse=t=>/serie|series|tv show|shows/i.test(t),HI=t=>/\.(mp4|mkv|avi|mov|webm|ts)(\?|$)/i.test(t),Dl={async fetchPlaylist(t){const{proxyFetch:e}=await km(async()=>{const{proxyFetch:r}=await Promise.resolve().then(()=>Zre);return{proxyFetch:r}},void 0),n=await e(t,"text");return KI(n)},parsePlaylistText(t){return KI(t)},classify(t){const e=[],n=[],r=new Map;return t.forEach((s,i)=>{const a=`${i}`;if(rse(s.group)&&HI(s.url)){const o=s.name.replace(/\s*S\d+\s*E\d+.*$/i,"").trim()||s.name;r.has(o)||r.set(o,{id:`s_${r.size}`,name:o,category:s.group,categoryId:s.group,posterUrl:s.logo})}else nse(s.group)||HI(s.url)&&!s.url.includes(".m3u8")?n.push({id:a,name:s.name,category:s.group,categoryId:s.group,streamUrl:s.url,posterUrl:s.logo}):e.push({id:a,name:s.name,category:s.group,categoryId:s.group,streamUrl:s.url,logoUrl:s.logo,epgChannelId:s.tvgId})}),{channels:e,movies:n,series:[...r.values()]}}},sse="",ise=/^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$/,J3=t=>ise.test(t.trim()),Lg=async(t,e)=>{const n=await fetch(`${sse}${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 s=(r==null?void 0:r.detail)||(typeof r=="object"?JSON.stringify(r):"")||`HTTP ${n.status}`;throw new Error(typeof s=="string"?s:JSON.stringify(s))}return r},zc={async handshake(t,e){return Lg("/api/stalker/handshake",{portal_url:t,mac:e})},async fetchAll(t,e){const r=((await Lg("/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 s=[];try{s=(await Lg("/api/stalker/vod-categories",{portal_url:t,mac:e})).categories||[]}catch{s=[]}const i=s.map(a=>({id:`cat-${a.id}`,name:a.name,category:a.name,categoryId:a.id,streamUrl:""}));return{channels:r,movies:i,series:[]}},async resolveStream(t,e,n){return(await Lg("/api/stalker/resolve-stream",{portal_url:t,mac:e,cmd:n})).url}},Z1=1e3*60*10,yh=t=>t.kind==="m3u",vh=t=>t.kind==="stalker",Hv=async t=>{const e=t.m3uContent&&t.m3uContent.trim().length?Dl.parsePlaylistText(t.m3uContent):await Dl.fetchPlaylist(t.m3uUrl);return Dl.classify(e)},zv=async t=>zc.fetchAll(t.portalUrl,t.macAddress),Z3=t=>kh({queryKey:["xtream",t==null?void 0:t.id,"live"],queryFn:async()=>t?vh(t)?(await zv(t)).channels:yh(t)?(await Hv(t)).channels:fs.getLiveStreams(t):[],enabled:!!t,staleTime:Z1}),eF=t=>kh({queryKey:["xtream",t==null?void 0:t.id,"movies"],queryFn:async()=>t?vh(t)?(await zv(t)).movies:yh(t)?(await Hv(t)).movies:fs.getMovies(t):[],enabled:!!t,staleTime:Z1}),tF=t=>kh({queryKey:["xtream",t==null?void 0:t.id,"series"],queryFn:async()=>t?vh(t)?(await zv(t)).series:yh(t)?(await Hv(t)).series:fs.getSeries(t):[],enabled:!!t,staleTime:Z1}),qv=()=>{const t=bv();return e=>t.invalidateQueries({queryKey:["xtream",e]})},ase=(t,e)=>kh({queryKey:["xtream",t==null?void 0:t.id,"epg",e],queryFn:async()=>{if(!t||!e||yh(t)||vh(t))return[];try{return await fs.getShortEpg(t,e,6)}catch{return[]}},enabled:!!t&&!!e&&!yh(t)&&!vh(t),staleTime:1e3*60*5}),nF=()=>{const t=bv();return async e=>{if(vh(e)){const i=await zv(e);return t.setQueryData(["xtream",e.id,"live"],i.channels),t.setQueryData(["xtream",e.id,"movies"],i.movies),t.setQueryData(["xtream",e.id,"series"],i.series),i}if(yh(e)){const i=await Hv(e);return t.setQueryData(["xtream",e.id,"live"],i.channels),t.setQueryData(["xtream",e.id,"movies"],i.movies),t.setQueryData(["xtream",e.id,"series"],i.series),i}const[n,r,s]=await Promise.all([fs.getLiveStreams(e),fs.getMovies(e),fs.getSeries(e)]);return t.setQueryData(["xtream",e.id,"live"],n),t.setQueryData(["xtream",e.id,"movies"],r),t.setQueryData(["xtream",e.id,"series"],s),{channels:n,movies:r,series:s}}},F0="nadiplay_managed_profile_id",eA="nadiplay_managed_counts",tA=()=>{try{return localStorage.getItem(F0)}catch(t){return console.warn("[useSubscriberProfileSync] read managed id failed",t),null}},zI=()=>{try{const t=localStorage.getItem(eA);return t?JSON.parse(t):null}catch(t){return console.warn("[useSubscriberProfileSync] read managed counts failed",t),null}},rF=t=>{try{localStorage.setItem(eA,JSON.stringify({...t,updatedAt:Date.now()})),window.dispatchEvent(new Event("nadiplay-managed-counts-changed"))}catch(e){console.warn("[useSubscriberProfileSync] write managed counts failed",e)}},Zf=()=>{try{const t=localStorage.getItem(F0);if(t){const n=JSON.parse(localStorage.getItem("nadiplay_profiles")||"[]").filter(s=>s.id!==t);localStorage.setItem("nadiplay_profiles",JSON.stringify(n)),localStorage.getItem("nadiplay_active_profile")===t&&localStorage.removeItem("nadiplay_active_profile"),localStorage.removeItem(F0),localStorage.removeItem(eA),window.dispatchEvent(new Event("nadiplay-profiles-changed"))}}catch(t){console.warn("[useSubscriberProfileSync] clear managed profile failed",t)}},ose=t=>{const{profiles:e,addProfile:n,updateProfile:r,setActiveProfileId:s}=Li(),i=nF(),a=C.useRef(null);C.useEffect(()=>{if(!t||t.role!=="user"||!Pl()||a.current===t.id)return;let o=!1;return(async()=>{try{const l=await S3();if(o)return;if(l.user.is_expired){Zf();return}const c=l.xtream;if(!c.server||!c.username||!c.password){Zf(),It.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=tA(),h=d?e.find(m=>m.id===d):void 0;let f;if(h)r(h.id,u),f={...h,...u},s(h.id);else{const m=n(u);try{localStorage.setItem(F0,m.id)}catch(g){console.warn("[useSubscriberProfileSync] persist managed id failed",g)}s(m.id),f=m}a.current=t.id;try{const m=await i(f);rF({channels:m.channels.length,movies:m.movies.length,series:m.series.length}),It.success(`Connected — ${m.channels.length} channels • ${m.movies.length} movies • ${m.series.length} series`)}catch(m){console.warn("[useSubscriberProfileSync] prefetch failed (user can still browse)",m)}}catch(l){console.warn("[useSubscriberProfileSync] sync failed",l)}})(),()=>{o=!0}},[t==null?void 0:t.id,t==null?void 0:t.role])},Ig="nadi_is_guest",sF=C.createContext(void 0),lse=({children:t})=>{const[e,n]=C.useState(()=>iI()),[r,s]=C.useState(()=>{try{return localStorage.getItem(Ig)==="1"}catch(d){return console.warn("[useAuth] read guest flag failed",d),!1}}),[i,a]=C.useState(()=>!!Pl()&&!iI());C.useEffect(()=>{if(!Pl()){a(!1);return}let h=!1;return oI().then(f=>{h||n(f)}).catch(f=>{console.warn("[useAuth] token validation failed",f),h||(Vb(),n(null))}).finally(()=>{h||a(!1)}),()=>{h=!0}},[]);const o=C.useCallback(async(d,h)=>{const f=await Bee(d,h);Uee(f.access_token,f.user),n(f.user);try{localStorage.removeItem(Ig)}catch(m){console.warn("[useAuth] clear guest flag failed",m)}return s(!1),f.user.role!=="user"&&Zf(),f.user},[]),l=C.useCallback(()=>{Zf(),Vb(),n(null);try{localStorage.removeItem(Ig)}catch(d){console.warn("[useAuth] clear guest flag failed",d)}s(!1)},[]),c=C.useCallback(()=>{Zf();try{localStorage.setItem(Ig,"1")}catch(d){console.warn("[useAuth] set guest flag failed",d)}s(!0)},[]),u=C.useCallback(async()=>{if(Pl())try{const d=await oI();n(d)}catch(d){console.warn("[useAuth] refresh failed",d),Vb(),n(null)}},[]);return p.jsx(sF.Provider,{value:{user:e,isGuest:r,loading:i,login:o,logout:l,continueAsGuest:c,refresh:u},children:t})},ys=()=>{const t=C.useContext(sF);if(!t)throw new Error("useAuth must be used inside <AuthProvider>");return t},iF="shared:",cse="nadiplay_shared_profiles_sync",use="nadiplay_active_profile",dse="nadiplay-profiles-changed",cw=t=>`${iF}${t.id||t.name}`,hse=t=>{const e={id:cw(t),name:t.name||"Shared Profile",kind:t.kind,serverUrl:"",username:"",password:""};return t.kind==="m3u"?{...e,m3uUrl:t.m3u_url||void 0,m3uContent:t.m3u_content||void 0}:t.kind==="stalker"?{...e,portalUrl:t.portal_url||"",macAddress:(t.mac_address||"").toUpperCase()}:{...e,serverUrl:t.server||"",username:t.username||"",password:t.password||""}},fse=t=>{const{setActiveProfileId:e}=Li(),n=C.useRef(null);C.useEffect(()=>{if(!t||!Pl()||n.current===t.id)return;let r=!1;return(async()=>{try{const s=await w3();if(r)return;const i=s.profiles||[],a=new Set(i.map(cw)),o=await po.profiles.toArray();for(const c of o)c.id.startsWith(iF)&&!a.has(c.id)&&await po.profiles.delete(c.id);for(const c of i)await po.profiles.put(hse(c));let l=null;try{l=localStorage.getItem(use)}catch{}!l&&i.length>0&&e(cw(i[0]));try{const c={userId:t.id,count:i.length,at:Date.now()};localStorage.setItem(cse,JSON.stringify(c))}catch{}window.dispatchEvent(new Event(dse)),n.current=t.id}catch(s){console.warn("[useSharedProfilesSync] sync failed",s)}})(),()=>{r=!0}},[t==null?void 0:t.id,t==null?void 0:t.role])},pse="nadiplay_fcm_registered_for",mse=()=>{const{user:t}=ys(),e=lr(),n=C.useRef(null);C.useEffect(()=>{if(!t||!Pl()||!rs.isNativePlatform()||n.current===t.id)return;let r=!1;return(async()=>{try{const{PushNotifications:s}=await km(async()=>{const{PushNotifications:o}=await import("./index-CQYnx2h5.js");return{PushNotifications:o}},[]);let a=(await s.checkPermissions()).receive;if((a==="prompt"||a==="prompt-with-rationale")&&(a=(await s.requestPermissions()).receive),a!=="granted")return;await s.removeAllListeners(),await s.addListener("registration",async o=>{if(!r)try{await Kee({token:o.value,device_id:gse(),platform:rs.getPlatform()==="ios"?"ios":"android"});try{localStorage.setItem(pse,t.id)}catch{}n.current=t.id}catch(l){console.warn("[push] failed to send token to backend",l)}}),await s.addListener("registrationError",o=>{console.warn("[push] registration error",o)}),await s.addListener("pushNotificationReceived",o=>{console.log("[push] received in foreground",o)}),await s.addListener("pushNotificationActionPerformed",o=>{var c;const l=((c=o.notification.data)==null?void 0:c.route)||"/";e(l)}),await s.register()}catch(s){console.warn("[push] init failed",s)}})(),()=>{r=!0}},[t==null?void 0:t.id]),C.useEffect(()=>{const r=s=>{var a;const i=(a=s.detail)==null?void 0:a.route;i&&typeof i=="string"&&i.startsWith("/")&&e(i)};return window.addEventListener("nadiplay:notification-route",r),()=>window.removeEventListener("nadiplay:notification-route",r)},[e])},gse=()=>{const t="nadiplay_device_id";try{const e=localStorage.getItem(t);if(e)return e;const n="dev-"+Math.random().toString(36).slice(2,10)+"-"+Date.now().toString(36);return localStorage.setItem(t,n),n}catch{return"dev-anon-"+Date.now().toString(36)}},aF="nadiplay_playback_mode",oF=()=>{try{return localStorage.getItem(aF)==="external"?"external":"internal"}catch{return"internal"}},yse=t=>{try{localStorage.setItem(aF,t)}catch{}},vse=()=>{const{data:t}=kh({queryKey:["public","playback-mode"],queryFn:P0,staleTime:3e5,refetchOnWindowFocus:!0,retry:1});return C.useEffect(()=>{t&&yse(t.external_player_enabled?"external":"internal")},[t]),t};var lF=typeof global=="object"&&global&&global.Object===Object&&global,_se=typeof self=="object"&&self&&self.Object===Object&&self,ja=lF||_se||Function("return this")(),La=ja.Symbol,cF=Object.prototype,bse=cF.hasOwnProperty,xse=cF.toString,hf=La?La.toStringTag:void 0;function Sse(t){var e=bse.call(t,hf),n=t[hf];try{t[hf]=void 0;var r=!0}catch{}var s=xse.call(t);return r&&(e?t[hf]=n:delete t[hf]),s}var Ese=Object.prototype,wse=Ese.toString;function Tse(t){return wse.call(t)}var Ase="[object Null]",Rse="[object Undefined]",qI=La?La.toStringTag:void 0;function Gh(t){return t==null?t===void 0?Rse:Ase:qI&&qI in Object(t)?Sse(t):Tse(t)}function tu(t){return t!=null&&typeof t=="object"}var Cse="[object Symbol]";function _h(t){return typeof t=="symbol"||tu(t)&&Gh(t)==Cse}function Ty(t,e){for(var n=-1,r=t==null?0:t.length,s=Array(r);++n<r;)s[n]=e(t[n],n,t);return s}var si=Array.isArray,WI=La?La.prototype:void 0,YI=WI?WI.toString:void 0;function uF(t){if(typeof t=="string")return t;if(si(t))return Ty(t,uF)+"";if(_h(t))return YI?YI.call(t):"";var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}var kse=/\s/;function Lse(t){for(var e=t.length;e--&&kse.test(t.charAt(e)););return e}var Ise=/^\s+/;function Pse(t){return t&&t.slice(0,Lse(t)+1).replace(Ise,"")}function Gl(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var XI=NaN,Dse=/^[-+]0x[0-9a-f]+$/i,Ose=/^0b[01]+$/i,Nse=/^0o[0-7]+$/i,Mse=parseInt;function QI(t){if(typeof t=="number")return t;if(_h(t))return XI;if(Gl(t)){var e=typeof t.valueOf=="function"?t.valueOf():t;t=Gl(e)?e+"":e}if(typeof t!="string")return t===0?t:+t;t=Pse(t);var n=Ose.test(t);return n||Nse.test(t)?Mse(t.slice(2),n?2:8):Dse.test(t)?XI:+t}function Lm(t){return t}var jse="[object AsyncFunction]",Use="[object Function]",Bse="[object GeneratorFunction]",Fse="[object Proxy]";function dF(t){if(!Gl(t))return!1;var e=Gh(t);return e==Use||e==Bse||e==jse||e==Fse}var Wb=ja["__core-js_shared__"],JI=function(){var t=/[^.]+$/.exec(Wb&&Wb.keys&&Wb.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();function $se(t){return!!JI&&JI in t}var Vse=Function.prototype,Gse=Vse.toString;function mu(t){if(t!=null){try{return Gse.call(t)}catch{}try{return t+""}catch{}}return""}var Kse=/[\\^$.*+?()[\]{}|]/g,Hse=/^\[object .+?Constructor\]$/,zse=Function.prototype,qse=Object.prototype,Wse=zse.toString,Yse=qse.hasOwnProperty,Xse=RegExp("^"+Wse.call(Yse).replace(Kse,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Qse(t){if(!Gl(t)||$se(t))return!1;var e=dF(t)?Xse:Hse;return e.test(mu(t))}function Jse(t,e){return t==null?void 0:t[e]}function gu(t,e){var n=Jse(t,e);return Qse(n)?n:void 0}var uw=gu(ja,"WeakMap");function Zse(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 ff(){}var eie=800,tie=16,nie=Date.now;function rie(t){var e=0,n=0;return function(){var r=nie(),s=tie-(r-n);if(n=r,s>0){if(++e>=eie)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function sie(t){return function(){return t}}var ZI=function(){try{var t=gu(Object,"defineProperty");return t({},"",{}),t}catch{}}(),iie=ZI?function(t,e){return ZI(t,"toString",{configurable:!0,enumerable:!1,value:sie(e),writable:!0})}:Lm,aie=rie(iie);function oie(t,e){for(var n=-1,r=t==null?0:t.length;++n<r&&e(t[n],n,t)!==!1;);return t}function lie(t,e,n,r){for(var s=t.length,i=n+-1;++i<s;)if(e(t[i],i,t))return i;return-1}function cie(t){return t!==t}function uie(t,e,n){for(var r=n-1,s=t.length;++r<s;)if(t[r]===e)return r;return-1}function die(t,e,n){return e===e?uie(t,e,n):lie(t,cie,n)}function hie(t,e){var n=t==null?0:t.length;return!!n&&die(t,e,0)>-1}var fie=9007199254740991,pie=/^(?:0|[1-9]\d*)$/;function nA(t,e){var n=typeof t;return e=e??fie,!!e&&(n=="number"||n!="symbol"&&pie.test(t))&&t>-1&&t%1==0&&t<e}function rA(t,e){return t===e||t!==t&&e!==e}var eP=Math.max;function mie(t,e,n){return e=eP(e===void 0?t.length-1:e,0),function(){for(var r=arguments,s=-1,i=eP(r.length-e,0),a=Array(i);++s<i;)a[s]=r[e+s];s=-1;for(var o=Array(e+1);++s<e;)o[s]=r[s];return o[e]=n(a),Zse(t,this,o)}}function hF(t,e){return aie(mie(t,e,Lm),t+"")}var gie=9007199254740991;function sA(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=gie}function Im(t){return t!=null&&sA(t.length)&&!dF(t)}function tP(t,e,n){if(!Gl(n))return!1;var r=typeof e;return(r=="number"?Im(n)&&nA(e,n.length):r=="string"&&e in n)?rA(n[e],t):!1}var yie=Object.prototype;function vie(t){var e=t&&t.constructor,n=typeof e=="function"&&e.prototype||yie;return t===n}function _ie(t,e){for(var n=-1,r=Array(t);++n<t;)r[n]=e(n);return r}var bie="[object Arguments]";function nP(t){return tu(t)&&Gh(t)==bie}var fF=Object.prototype,xie=fF.hasOwnProperty,Sie=fF.propertyIsEnumerable,iA=nP(function(){return arguments}())?nP:function(t){return tu(t)&&xie.call(t,"callee")&&!Sie.call(t,"callee")};function Eie(){return!1}var pF=typeof exports=="object"&&exports&&!exports.nodeType&&exports,rP=pF&&typeof module=="object"&&module&&!module.nodeType&&module,wie=rP&&rP.exports===pF,sP=wie?ja.Buffer:void 0,Tie=sP?sP.isBuffer:void 0,dw=Tie||Eie,Aie="[object Arguments]",Rie="[object Array]",Cie="[object Boolean]",kie="[object Date]",Lie="[object Error]",Iie="[object Function]",Pie="[object Map]",Die="[object Number]",Oie="[object Object]",Nie="[object RegExp]",Mie="[object Set]",jie="[object String]",Uie="[object WeakMap]",Bie="[object ArrayBuffer]",Fie="[object DataView]",$ie="[object Float32Array]",Vie="[object Float64Array]",Gie="[object Int8Array]",Kie="[object Int16Array]",Hie="[object Int32Array]",zie="[object Uint8Array]",qie="[object Uint8ClampedArray]",Wie="[object Uint16Array]",Yie="[object Uint32Array]",Ln={};Ln[$ie]=Ln[Vie]=Ln[Gie]=Ln[Kie]=Ln[Hie]=Ln[zie]=Ln[qie]=Ln[Wie]=Ln[Yie]=!0;Ln[Aie]=Ln[Rie]=Ln[Bie]=Ln[Cie]=Ln[Fie]=Ln[kie]=Ln[Lie]=Ln[Iie]=Ln[Pie]=Ln[Die]=Ln[Oie]=Ln[Nie]=Ln[Mie]=Ln[jie]=Ln[Uie]=!1;function Xie(t){return tu(t)&&sA(t.length)&&!!Ln[Gh(t)]}function mF(t){return function(e){return t(e)}}var gF=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ep=gF&&typeof module=="object"&&module&&!module.nodeType&&module,Qie=ep&&ep.exports===gF,Yb=Qie&&lF.process,iP=function(){try{var t=ep&&ep.require&&ep.require("util").types;return t||Yb&&Yb.binding&&Yb.binding("util")}catch{}}(),aP=iP&&iP.isTypedArray,yF=aP?mF(aP):Xie,Jie=Object.prototype,Zie=Jie.hasOwnProperty;function eae(t,e){var n=si(t),r=!n&&iA(t),s=!n&&!r&&dw(t),i=!n&&!r&&!s&&yF(t),a=n||r||s||i,o=a?_ie(t.length,String):[],l=o.length;for(var c in t)Zie.call(t,c)&&!(a&&(c=="length"||s&&(c=="offset"||c=="parent")||i&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||nA(c,l)))&&o.push(c);return o}function tae(t,e){return function(n){return t(e(n))}}var nae=tae(Object.keys,Object),rae=Object.prototype,sae=rae.hasOwnProperty;function iae(t){if(!vie(t))return nae(t);var e=[];for(var n in Object(t))sae.call(t,n)&&n!="constructor"&&e.push(n);return e}function aA(t){return Im(t)?eae(t):iae(t)}var aae=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,oae=/^\w*$/;function oA(t,e){if(si(t))return!1;var n=typeof t;return n=="number"||n=="symbol"||n=="boolean"||t==null||_h(t)?!0:oae.test(t)||!aae.test(t)||e!=null&&t in Object(e)}var Up=gu(Object,"create");function lae(){this.__data__=Up?Up(null):{},this.size=0}function cae(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var uae="__lodash_hash_undefined__",dae=Object.prototype,hae=dae.hasOwnProperty;function fae(t){var e=this.__data__;if(Up){var n=e[t];return n===uae?void 0:n}return hae.call(e,t)?e[t]:void 0}var pae=Object.prototype,mae=pae.hasOwnProperty;function gae(t){var e=this.__data__;return Up?e[t]!==void 0:mae.call(e,t)}var yae="__lodash_hash_undefined__";function vae(t,e){var n=this.__data__;return this.size+=this.has(t)?0:1,n[t]=Up&&e===void 0?yae:e,this}function nu(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])}}nu.prototype.clear=lae;nu.prototype.delete=cae;nu.prototype.get=fae;nu.prototype.has=gae;nu.prototype.set=vae;function _ae(){this.__data__=[],this.size=0}function Wv(t,e){for(var n=t.length;n--;)if(rA(t[n][0],e))return n;return-1}var bae=Array.prototype,xae=bae.splice;function Sae(t){var e=this.__data__,n=Wv(e,t);if(n<0)return!1;var r=e.length-1;return n==r?e.pop():xae.call(e,n,1),--this.size,!0}function Eae(t){var e=this.__data__,n=Wv(e,t);return n<0?void 0:e[n][1]}function wae(t){return Wv(this.__data__,t)>-1}function Tae(t,e){var n=this.__data__,r=Wv(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this}function Po(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])}}Po.prototype.clear=_ae;Po.prototype.delete=Sae;Po.prototype.get=Eae;Po.prototype.has=wae;Po.prototype.set=Tae;var Bp=gu(ja,"Map");function Aae(){this.size=0,this.__data__={hash:new nu,map:new(Bp||Po),string:new nu}}function Rae(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function Yv(t,e){var n=t.__data__;return Rae(e)?n[typeof e=="string"?"string":"hash"]:n.map}function Cae(t){var e=Yv(this,t).delete(t);return this.size-=e?1:0,e}function kae(t){return Yv(this,t).get(t)}function Lae(t){return Yv(this,t).has(t)}function Iae(t,e){var n=Yv(this,t),r=n.size;return n.set(t,e),this.size+=n.size==r?0:1,this}function Do(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])}}Do.prototype.clear=Aae;Do.prototype.delete=Cae;Do.prototype.get=kae;Do.prototype.has=Lae;Do.prototype.set=Iae;var Pae="Expected a function";function lA(t,e){if(typeof t!="function"||e!=null&&typeof e!="function")throw new TypeError(Pae);var n=function(){var r=arguments,s=e?e.apply(this,r):r[0],i=n.cache;if(i.has(s))return i.get(s);var a=t.apply(this,r);return n.cache=i.set(s,a)||i,a};return n.cache=new(lA.Cache||Do),n}lA.Cache=Do;var Dae=500;function Oae(t){var e=lA(t,function(r){return n.size===Dae&&n.clear(),r}),n=e.cache;return e}var Nae=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Mae=/\\(\\)?/g,jae=Oae(function(t){var e=[];return t.charCodeAt(0)===46&&e.push(""),t.replace(Nae,function(n,r,s,i){e.push(s?i.replace(Mae,"$1"):r||n)}),e});function vF(t){return t==null?"":uF(t)}function _F(t,e){return si(t)?t:oA(t,e)?[t]:jae(vF(t))}function Xv(t){if(typeof t=="string"||_h(t))return t;var e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function cA(t,e){e=_F(e,t);for(var n=0,r=e.length;t!=null&&n<r;)t=t[Xv(e[n++])];return n&&n==r?t:void 0}function Uae(t,e,n){var r=t==null?void 0:cA(t,e);return r===void 0?n:r}function bF(t,e){for(var n=-1,r=e.length,s=t.length;++n<r;)t[s+n]=e[n];return t}var oP=La?La.isConcatSpreadable:void 0;function Bae(t){return si(t)||iA(t)||!!(oP&&t&&t[oP])}function xF(t,e,n,r,s){var i=-1,a=t.length;for(n||(n=Bae),s||(s=[]);++i<a;){var o=t[i];n(o)?bF(s,o):r||(s[s.length]=o)}return s}function Fae(){this.__data__=new Po,this.size=0}function $ae(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n}function Vae(t){return this.__data__.get(t)}function Gae(t){return this.__data__.has(t)}var Kae=200;function Hae(t,e){var n=this.__data__;if(n instanceof Po){var r=n.__data__;if(!Bp||r.length<Kae-1)return r.push([t,e]),this.size=++n.size,this;n=this.__data__=new Do(r)}return n.set(t,e),this.size=n.size,this}function bo(t){var e=this.__data__=new Po(t);this.size=e.size}bo.prototype.clear=Fae;bo.prototype.delete=$ae;bo.prototype.get=Vae;bo.prototype.has=Gae;bo.prototype.set=Hae;function SF(t,e){for(var n=-1,r=t==null?0:t.length,s=0,i=[];++n<r;){var a=t[n];e(a,n,t)&&(i[s++]=a)}return i}function zae(){return[]}var qae=Object.prototype,Wae=qae.propertyIsEnumerable,lP=Object.getOwnPropertySymbols,Yae=lP?function(t){return t==null?[]:(t=Object(t),SF(lP(t),function(e){return Wae.call(t,e)}))}:zae;function Xae(t,e,n){var r=e(t);return si(t)?r:bF(r,n(t))}function cP(t){return Xae(t,aA,Yae)}var hw=gu(ja,"DataView"),fw=gu(ja,"Promise"),pw=gu(ja,"Set"),uP="[object Map]",Qae="[object Object]",dP="[object Promise]",hP="[object Set]",fP="[object WeakMap]",pP="[object DataView]",Jae=mu(hw),Zae=mu(Bp),eoe=mu(fw),toe=mu(pw),noe=mu(uw),Qo=Gh;(hw&&Qo(new hw(new ArrayBuffer(1)))!=pP||Bp&&Qo(new Bp)!=uP||fw&&Qo(fw.resolve())!=dP||pw&&Qo(new pw)!=hP||uw&&Qo(new uw)!=fP)&&(Qo=function(t){var e=Gh(t),n=e==Qae?t.constructor:void 0,r=n?mu(n):"";if(r)switch(r){case Jae:return pP;case Zae:return uP;case eoe:return dP;case toe:return hP;case noe:return fP}return e});var mP=ja.Uint8Array,roe="__lodash_hash_undefined__";function soe(t){return this.__data__.set(t,roe),this}function ioe(t){return this.__data__.has(t)}function Fp(t){var e=-1,n=t==null?0:t.length;for(this.__data__=new Do;++e<n;)this.add(t[e])}Fp.prototype.add=Fp.prototype.push=soe;Fp.prototype.has=ioe;function aoe(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 EF(t,e){return t.has(e)}var ooe=1,loe=2;function wF(t,e,n,r,s,i){var a=n&ooe,o=t.length,l=e.length;if(o!=l&&!(a&&l>o))return!1;var c=i.get(t),u=i.get(e);if(c&&u)return c==e&&u==t;var d=-1,h=!0,f=n&loe?new Fp:void 0;for(i.set(t,e),i.set(e,t);++d<o;){var m=t[d],g=e[d];if(r)var y=a?r(g,m,d,e,t,i):r(m,g,d,t,e,i);if(y!==void 0){if(y)continue;h=!1;break}if(f){if(!aoe(e,function(v,_){if(!EF(f,_)&&(m===v||s(m,v,n,r,i)))return f.push(_)})){h=!1;break}}else if(!(m===g||s(m,g,n,r,i))){h=!1;break}}return i.delete(t),i.delete(e),h}function coe(t){var e=-1,n=Array(t.size);return t.forEach(function(r,s){n[++e]=[s,r]}),n}function uoe(t){var e=-1,n=Array(t.size);return t.forEach(function(r){n[++e]=r}),n}var doe=1,hoe=2,foe="[object Boolean]",poe="[object Date]",moe="[object Error]",goe="[object Map]",yoe="[object Number]",voe="[object RegExp]",_oe="[object Set]",boe="[object String]",xoe="[object Symbol]",Soe="[object ArrayBuffer]",Eoe="[object DataView]",gP=La?La.prototype:void 0,Xb=gP?gP.valueOf:void 0;function woe(t,e,n,r,s,i,a){switch(n){case Eoe:if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case Soe:return!(t.byteLength!=e.byteLength||!i(new mP(t),new mP(e)));case foe:case poe:case yoe:return rA(+t,+e);case moe:return t.name==e.name&&t.message==e.message;case voe:case boe:return t==e+"";case goe:var o=coe;case _oe:var l=r&doe;if(o||(o=uoe),t.size!=e.size&&!l)return!1;var c=a.get(t);if(c)return c==e;r|=hoe,a.set(t,e);var u=wF(o(t),o(e),r,s,i,a);return a.delete(t),u;case xoe:if(Xb)return Xb.call(t)==Xb.call(e)}return!1}var Toe=1,Aoe=Object.prototype,Roe=Aoe.hasOwnProperty;function Coe(t,e,n,r,s,i){var a=n&Toe,o=cP(t),l=o.length,c=cP(e),u=c.length;if(l!=u&&!a)return!1;for(var d=l;d--;){var h=o[d];if(!(a?h in e:Roe.call(e,h)))return!1}var f=i.get(t),m=i.get(e);if(f&&m)return f==e&&m==t;var g=!0;i.set(t,e),i.set(e,t);for(var y=a;++d<l;){h=o[d];var v=t[h],_=e[h];if(r)var S=a?r(_,v,h,e,t,i):r(v,_,h,t,e,i);if(!(S===void 0?v===_||s(v,_,n,r,i):S)){g=!1;break}y||(y=h=="constructor")}if(g&&!y){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)&&(g=!1)}return i.delete(t),i.delete(e),g}var koe=1,yP="[object Arguments]",vP="[object Array]",Pg="[object Object]",Loe=Object.prototype,_P=Loe.hasOwnProperty;function Ioe(t,e,n,r,s,i){var a=si(t),o=si(e),l=a?vP:Qo(t),c=o?vP:Qo(e);l=l==yP?Pg:l,c=c==yP?Pg:c;var u=l==Pg,d=c==Pg,h=l==c;if(h&&dw(t)){if(!dw(e))return!1;a=!0,u=!1}if(h&&!u)return i||(i=new bo),a||yF(t)?wF(t,e,n,r,s,i):woe(t,e,l,n,r,s,i);if(!(n&koe)){var f=u&&_P.call(t,"__wrapped__"),m=d&&_P.call(e,"__wrapped__");if(f||m){var g=f?t.value():t,y=m?e.value():e;return i||(i=new bo),s(g,y,n,r,i)}}return h?(i||(i=new bo),Coe(t,e,n,r,s,i)):!1}function uA(t,e,n,r,s){return t===e?!0:t==null||e==null||!tu(t)&&!tu(e)?t!==t&&e!==e:Ioe(t,e,n,r,uA,s)}var Poe=1,Doe=2;function Ooe(t,e,n,r){var s=n.length,i=s;if(t==null)return!i;for(t=Object(t);s--;){var a=n[s];if(a[2]?a[1]!==t[a[0]]:!(a[0]in t))return!1}for(;++s<i;){a=n[s];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 bo,d;if(!(d===void 0?uA(c,l,Poe|Doe,r,u):d))return!1}}return!0}function TF(t){return t===t&&!Gl(t)}function Noe(t){for(var e=aA(t),n=e.length;n--;){var r=e[n],s=t[r];e[n]=[r,s,TF(s)]}return e}function AF(t,e){return function(n){return n==null?!1:n[t]===e&&(e!==void 0||t in Object(n))}}function Moe(t){var e=Noe(t);return e.length==1&&e[0][2]?AF(e[0][0],e[0][1]):function(n){return n===t||Ooe(n,t,e)}}function joe(t,e){return t!=null&&e in Object(t)}function Uoe(t,e,n){e=_F(e,t);for(var r=-1,s=e.length,i=!1;++r<s;){var a=Xv(e[r]);if(!(i=t!=null&&n(t,a)))break;t=t[a]}return i||++r!=s?i:(s=t==null?0:t.length,!!s&&sA(s)&&nA(a,s)&&(si(t)||iA(t)))}function Boe(t,e){return t!=null&&Uoe(t,e,joe)}var Foe=1,$oe=2;function Voe(t,e){return oA(t)&&TF(e)?AF(Xv(t),e):function(n){var r=Uae(n,t);return r===void 0&&r===e?Boe(n,t):uA(e,r,Foe|$oe)}}function Goe(t){return function(e){return e==null?void 0:e[t]}}function Koe(t){return function(e){return cA(e,t)}}function Hoe(t){return oA(t)?Goe(Xv(t)):Koe(t)}function dA(t){return typeof t=="function"?t:t==null?Lm:typeof t=="object"?si(t)?Voe(t[0],t[1]):Moe(t):Hoe(t)}function zoe(t){return function(e,n,r){for(var s=-1,i=Object(e),a=r(e),o=a.length;o--;){var l=a[++s];if(n(i[l],l,i)===!1)break}return e}}var qoe=zoe();function hA(t,e){return t&&qoe(t,e,aA)}function Woe(t,e){return function(n,r){if(n==null)return n;if(!Im(n))return t(n,r);for(var s=n.length,i=-1,a=Object(n);++i<s&&r(a[i],i,a)!==!1;);return n}}var fA=Woe(hA),Qb=function(){return ja.Date.now()},Yoe="Expected a function",Xoe=Math.max,Qoe=Math.min;function RF(t,e,n){var r,s,i,a,o,l,c=0,u=!1,d=!1,h=!0;if(typeof t!="function")throw new TypeError(Yoe);e=QI(e)||0,Gl(n)&&(u=!!n.leading,d="maxWait"in n,i=d?Xoe(QI(n.maxWait)||0,e):i,h="trailing"in n?!!n.trailing:h);function f(U){var P=r,I=s;return r=s=void 0,c=U,a=t.apply(I,P),a}function m(U){return c=U,o=setTimeout(v,e),u?f(U):a}function g(U){var P=U-l,I=U-c,k=e-P;return d?Qoe(k,i-I):k}function y(U){var P=U-l,I=U-c;return l===void 0||P>=e||P<0||d&&I>=i}function v(){var U=Qb();if(y(U))return _(U);o=setTimeout(v,g(U))}function _(U){return o=void 0,h&&r?f(U):(r=s=void 0,a)}function S(){o!==void 0&&clearTimeout(o),c=0,r=l=s=o=void 0}function E(){return o===void 0?a:_(Qb())}function L(){var U=Qb(),P=y(U);if(r=arguments,s=this,l=U,P){if(o===void 0)return m(l);if(d)return clearTimeout(o),o=setTimeout(v,e),f(l)}return o===void 0&&(o=setTimeout(v,e)),a}return L.cancel=S,L.flush=E,L}function bP(t){return tu(t)&&Im(t)}var Joe=200;function Zoe(t,e,n,r){var s=-1,i=hie,a=!0,o=t.length,l=[],c=e.length;if(!o)return l;e.length>=Joe&&(i=EF,a=!1,e=new Fp(e));e:for(;++s<o;){var u=t[s],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 i(e,d,r)||l.push(u)}return l}var xP=hF(function(t,e){return bP(t)?Zoe(t,xF(e,1,bP,!0)):[]});function CF(t){return typeof t=="function"?t:Lm}function SP(t,e){var n=si(t)?oie:fA;return n(t,CF(e))}function ele(t,e){var n=[];return fA(t,function(r,s,i){e(r,s,i)&&n.push(r)}),n}function Jb(t,e){var n=si(t)?SF:ele;return n(t,dA(e))}function tle(t,e,n){var r;return n(t,function(s,i,a){if(e(s,i,a))return r=i,!1}),r}function EP(t,e){return tle(t,dA(e),hA)}function mw(t){return t&&t.length?t[0]:void 0}function nle(t,e){var n=-1,r=Im(t)?Array(t.length):[];return fA(t,function(s,i,a){r[++n]=e(s,i,a)}),r}function Zb(t,e){return t&&hA(t,CF(e))}function rle(t,e){var n=t.length;for(t.sort(e);n--;)t[n]=t[n].value;return t}function sle(t,e){if(t!==e){var n=t!==void 0,r=t===null,s=t===t,i=_h(t),a=e!==void 0,o=e===null,l=e===e,c=_h(e);if(!o&&!c&&!i&&t>e||i&&a&&l&&!o&&!c||r&&a&&l||!n&&l||!s)return 1;if(!r&&!i&&!c&&t<e||c&&n&&s&&!r&&!i||o&&n&&s||!a&&s||!l)return-1}return 0}function ile(t,e,n){for(var r=-1,s=t.criteria,i=e.criteria,a=s.length,o=n.length;++r<a;){var l=sle(s[r],i[r]);if(l){if(r>=o)return l;var c=n[r];return l*(c=="desc"?-1:1)}}return t.index-e.index}function ale(t,e,n){e.length?e=Ty(e,function(i){return si(i)?function(a){return cA(a,i.length===1?i[0]:i)}:i}):e=[Lm];var r=-1;e=Ty(e,mF(dA));var s=nle(t,function(i,a,o){var l=Ty(e,function(c){return c(i)});return{criteria:l,index:++r,value:i}});return rle(s,function(i,a){return ile(i,a,n)})}var kF=hF(function(t,e){if(t==null)return[];var n=e.length;return n>1&&tP(t,e[0],e[1])?e=[]:n>2&&tP(e[0],e[1],e[2])&&(e=[e[0]]),ale(t,xF(e),[])}),ole="Expected a function";function lle(t,e,n){var r=!0,s=!0;if(typeof t!="function")throw new TypeError(ole);return Gl(n)&&(r="leading"in n?!0:r,s="trailing"in n?!1:s),RF(t,e,{leading:r,maxWait:e,trailing:s})}var cle=0;function ule(t){var e=++cle;return vF(t)+e}var _d=function(){return _d=Object.assign||function(e){for(var n,r=1,s=arguments.length;r<s;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},_d.apply(this,arguments)};function dle(t,e,n){if(arguments.length===2)for(var r=0,s=e.length,i;r<s;r++)(i||!(r in e))&&(i||(i=Array.prototype.slice.call(e,0,r)),i[r]=e[r]);return t.concat(i||Array.prototype.slice.call(e))}var gw;(function(t){t[t.LTR=0]="LTR",t[t.RTL=1]="RTL"})(gw||(gw={}));var fi=gw,_c=typeof window<"u"&&window.document,ex=_c?window.innerWidth:0,tx=_c?window.innerHeight:0,hle=function(){function t(e){_c&&(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 s=document.querySelector("#".concat(e))||document.createElement("canvas");s.setAttribute("id",e),s.setAttribute("dir",r===fi.LTR?"ltr":"rtl");var i=s.getContext("2d");return s.style.zIndex=n,s.style.position="fixed",s.style.top="0",s.style.left="0",document.body.appendChild(s),s.width=ex,s.height=tx,i},t.prototype.clear=function(){_c&&this.debugCtx.clearRect(0,0,ex,tx)},t.prototype.clearLayouts=function(){_c&&this.layoutsCtx.clearRect(0,0,ex,tx)},t.prototype.drawLayout=function(e,n,r){if(_c){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 s=this.writingDirection===fi.LTR?"left":"right",i=e[s];this.layoutsCtx.fillText(n,i,e.top+10),this.layoutsCtx.fillText(r,i,e.top+25),this.layoutsCtx.fillText("".concat(s,": ").concat(i),i,e.top+40),this.layoutsCtx.fillText("top: ".concat(e.top),i,e.top+55)}},t.prototype.drawPoint=function(e,n,r,s){r===void 0&&(r="blue"),s===void 0&&(s=10),_c&&(this.debugCtx.strokeStyle=r,this.debugCtx.lineWidth=3,this.debugCtx.strokeRect(e-s/2,n-s/2,s,s))},t}(),fle=1,wP=function(t){for(var e=t.offsetParent,n=t.offsetHeight,r=t.offsetWidth,s=t.offsetLeft,i=t.offsetTop;e&&e.nodeType===fle;)s+=e.offsetLeft-e.scrollLeft,i+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{height:n,left:s,top:i,width:r}},ple=function(t){var e=t&&t.parentElement;if(t&&e){var n=wP(e),r=wP(t),s=r.height,i=r.left,a=r.top,o=r.width,l=i-n.left,c=a-n.top;return{x:l,y:c,width:o,height:s,left:i,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}},mle=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}},lc,wf="left",Tf="right",td="up",yc="down",yw="enter",TP=(lc={},lc[wf]=[37,"ArrowLeft"],lc[td]=[38,"ArrowUp"],lc[Tf]=[39,"ArrowRight"],lc[yc]=[40,"ArrowDown"],lc[yw]=[13,"Enter"],lc),vw="SN:ROOT",gle=.2,yle=5,vle=1,_le=5,ble=300,AP=["#0FF","#FF0","#F0F"],xle={leading:!0,trailing:!1},Sle=function(t,e){var n=e===fi.LTR?function(s){var i=s.layout;return Math.abs(i.left)+Math.abs(i.top)}:function(s){var i=s.layout;return Math.abs(window.innerWidth-i.right)+Math.abs(i.top)},r=kF(t,n);return mw(r)},Ele=function(t){var e={};return Object.entries(t).forEach(function(n){var r=n[0],s=n[1];e[r]=Array.isArray(s)?s:[s]}),e},wle=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=fi.LTR,this.pressedKeys={},this.paused=!1,this.keyDownEventListener=null,this.keyUpEventListener=null,this.keyMap=TP,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=RF(this.setFocus,ble,{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,s,i){var a=e?s.top:i===fi.LTR?s.left:s.right,o=e?s.bottom:i===fi.LTR?s.right:s.left;return n?r?a:o:r?o:a},t.getRefCorners=function(e,n,r){var s={a:{x:0,y:0},b:{x:0,y:0}};switch(e){case td:{var i=n?r.bottom:r.top;s.a={x:r.left,y:i},s.b={x:r.right,y:i};break}case yc:{var i=n?r.top:r.bottom;s.a={x:r.left,y:i},s.b={x:r.right,y:i};break}case wf:{var a=n?r.right:r.left;s.a={x:a,y:r.top},s.b={x:a,y:r.bottom};break}case Tf:{var a=n?r.left:r.right;s.a={x:a,y:r.top},s.b={x:a,y:r.bottom};break}}return s},t.isAdjacentSlice=function(e,n,r){var s=e.a,i=e.b,a=n.a,o=n.b,l=r?"x":"y",c=s[l],u=i[l],d=a[l],h=o[l],f=(u-c)*gle,m=Math.max(0,Math.min(u,h)-Math.max(c,d));return m>=f},t.getPrimaryAxisDistance=function(e,n,r){var s=e.a,i=n.a,a=r?"y":"x";return Math.abs(i[a]-s[a])},t.getSecondaryAxisDistance=function(e,n,r,s,i){if(i)return i(e,n,r,s);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],m=c[u];if(s==="center"){var g=(d+h)/2,y=(f+m)/2;return Math.abs(g-y)}if(s==="edges"){var v=Math.min(d,h),_=Math.min(f,m),S=Math.max(d,h),E=Math.max(f,m),L=Math.abs(v-_),U=Math.abs(S-E);return Math.min(L,U)}var P=[Math.abs(f-d),Math.abs(f-h),Math.abs(m-d),Math.abs(m-h)];return Math.min.apply(Math,P)},t.prototype.sortSiblingsByPriority=function(e,n,r,s){var i=this,a=r===yc||r===td,o=t.getRefCorners(r,!1,n);return kF(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,i.distanceCalculationMethod,i.customDistanceCalculationFunction),m=h(o,c,a,i.distanceCalculationMethod,i.customDistanceCalculationFunction),g=f*_le+m,y=(g+1)/(u?yle:vle);return i.log("smartNavigate","distance (primary, secondary, total weighted) for ".concat(l.focusKey," relative to ").concat(s," is"),f,m,g),i.log("smartNavigate","priority for ".concat(l.focusKey," relative to ").concat(s," is"),y),i.visualDebugger&&(i.visualDebugger.drawPoint(c.a.x,c.a.y,"yellow",6),i.visualDebugger.drawPoint(c.b.x,c.b.y,"yellow",6)),y})},t.prototype.init=function(e){var n=this,r=e===void 0?{}:e,s=r.debug,i=s===void 0?!1:s,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,m=r.useGetBoundingClientRect,g=m===void 0?!1:m,y=r.shouldFocusDOMNode,v=y===void 0?!1:y,_=r.domNodeFocusOptions,S=_===void 0?{}:_,E=r.shouldUseNativeEvents,L=E===void 0?!1:E,U=r.rtl,P=U===void 0?!1:U,I=r.distanceCalculationMethod,k=I===void 0?"corners":I,R=r.customDistanceCalculationFunction,M=R===void 0?void 0:R,G=r.onUtterText;if(!this.enabled){if(this.domNodeFocusOptions=S,this.enabled=!0,this.nativeMode=c,this.throttleKeypresses=f,this.useGetBoundingClientRect=g,this.shouldFocusDOMNode=v&&!c,this.shouldUseNativeEvents=L,this.writingDirection=P?fi.RTL:fi.LTR,this.distanceCalculationMethod=k,this.customDistanceCalculationFunction=M,this.onUtterText=G??void 0,this.debug=i,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 hle(this.writingDirection);var Y=function(){requestAnimationFrame(function(){n.visualDebugger.clearLayouts(),Zb(n.focusableComponents,function(q,X){n.visualDebugger.drawLayout(q.layout,X,q.parentFocusKey)}),Y()})};Y()}}},t.prototype.setThrottle=function(e){var n=e===void 0?{}:e,r=n.throttle,s=r===void 0?0:r,i=n.throttleKeypresses,a=i===void 0?!1:i;this.throttleKeypresses=a,this.nativeMode||(this.unbindEventHandlers(),Number.isInteger(s)&&(this.throttle=s),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=TP,this.onUtterText=void 0,this.unbindEventHandlers())},t.prototype.getEventType=function(e){return EP(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),s=e.getEventType(r);if(s){e.pressedKeys[s]=e.pressedKeys[s]?e.pressedKeys[s]+1:1,e.shouldUseNativeEvents||(n.preventDefault(),n.stopPropagation());var i={pressedKeys:e.pressedKeys};if(s===yw&&e.focusKey){e.onEnterPress(i);return}var a=e.onArrowPress(s,i)===!1;if(e.visualDebugger&&e.visualDebugger.clear(),a)e.log("keyDownEventListener","default navigation prevented");else{var o=EP(e.getKeyMap(),function(l){return l.includes(r)});e.smartNavigate(o,null,{event:n})}}}},this.throttle&&(this.keyDownEventListenerThrottled=lle(this.keyDownEventListener.bind(this),this.throttle,xle)),this.keyUpEventListener=function(n){var r=t.getKeyCode(n),s=e.getEventType(r);delete e.pressedKeys[s],e.throttle&&!e.throttleKeypresses&&e.keyDownEventListenerThrottled.cancel(),s===yw&&e.focusKey&&e.onEnterRelease(),e.focusKey&&(s===wf||s===Tf||s===td||s===yc)&&e.onArrowRelease(s)},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=[yc,td,wf,Tf];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 s=this;if(!this.nativeMode){var i=e===yc||e===td,a=e===yc||(this.writingDirection===fi.LTR?e===Tf:e===wf);this.log("smartNavigate","direction",e),this.log("smartNavigate","fromParentFocusKey",n),this.log("smartNavigate","this.focusKey",this.focusKey),n||Zb(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(i,a,!1,d,this.writingDirection),f=Jb(this.focusableComponents,function(S){if(S.parentFocusKey===c&&S.focusable){s.updateLayout(S.focusKey);var E=t.getCutoffCoordinate(i,a,!0,S.layout,s.writingDirection);return i||s.writingDirection===fi.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 m=t.getRefCorners(e,!1,d);this.visualDebugger.drawPoint(m.a.x,m.a.y),this.visualDebugger.drawPoint(m.b.x,m.b.y)}var g=this.sortSiblingsByPriority(f,d,e,u),y=mw(g);if(this.log("smartNavigate","nextComponent",y?y.focusKey:void 0,y?y.node:void 0,y),y)this.setFocus(y.focusKey,r);else{var v=this.focusableComponents[c],_=v!=null&&v.isFocusBoundary?v.focusBoundaryDirections||[e]:[];(!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=[],s=2;s<arguments.length;s++)r[s-2]=arguments[s];this.debug&&console.log.apply(console,dle(["%c".concat(e,"%c").concat(n),"background: ".concat(AP[this.logIndex%AP.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=Jb(this.focusableComponents,function(s){return s.focusable&&s.forceFocus}),r=this.sortSiblingsByPriority(n,{x:0,y:0,width:0,height:0,left:0,top:0,right:0,bottom:0,node:null},"down",vw);return(e=mw(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 s=Jb(this.focusableComponents,function(l){return l.parentFocusKey===e&&l.focusable});if(s.length>0){var i=r.lastFocusedChildKey,a=r.preferredChildFocusKey;if(this.log("getNextFocusKey","lastFocusedChildKey is",i),this.log("getNextFocusKey","preferredChildFocusKey is",a),i&&r.saveLastFocusedChild&&this.isParticipatingFocusableComponent(i))return this.log("getNextFocusKey","lastFocusedChildKey will be focused",i),this.getNextFocusKey(i);if(a&&this.isParticipatingFocusableComponent(a))return this.log("getNextFocusKey","preferredChildFocusKey will be focused",a),this.getNextFocusKey(a);s.forEach(function(l){return n.updateLayout(l.focusKey)});var o=Sle(s,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,s=e.parentFocusKey,i=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,m=e.onUpdateHasFocusedChild,g=e.preferredChildFocusKey,y=e.autoRestoreFocus,v=e.forceFocus,_=e.focusable,S=e.isFocusBoundary,E=e.focusBoundaryDirections,L=e.accessibilityLabel;if(this.focusableComponents[n]={focusKey:n,node:r,parentFocusKey:s,onEnterPress:i,onEnterRelease:a,onArrowPress:o,onArrowRelease:l,onFocus:c,onBlur:u,onUpdateFocus:f,onUpdateHasFocusedChild:m,saveLastFocusedChild:d,trackChildren:h,preferredChildFocusKey:g,focusable:_,isFocusBoundary:S,focusBoundaryDirections:E,autoRestoreFocus:y,forceFocus:v,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(g||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 s=r.parentFocusKey,i=r.onUpdateFocus;i(!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[s],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: ",s),this.setFocusDebounced(s))}},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,s,i,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),(s=(r=o.node)===null||r===void 0?void 0:r.removeAttribute)===null||s===void 0||s.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=(i=l.node)===null||i===void 0?void 0:i.setAttribute)===null||a===void 0||a.call(i,"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,s=[],i=this.focusableComponents[e];i;){var a=i.parentFocusKey,o=this.focusableComponents[a];if(o){var l=o.focusKey;s.push(l)}i=o}var c=xP(this.parentsHavingFocusedChild,s),u=xP(s,this.parentsHavingFocusedChild);SP(c,function(d){var h=r.focusableComponents[d];h&&h.trackChildren&&h.onUpdateHasFocusedChild(!1),r.onIntermediateNodeBecameBlurred(d,n)}),SP(u,function(d){var h=r.focusableComponents[d];h&&h.trackChildren&&h.onUpdateHasFocusedChild(!0),r.onIntermediateNodeBecameFocused(d,n)}),this.parentsHavingFocusedChild=s},t.prototype.updateParentsLastFocusedChild=function(e){for(var n=this.focusableComponents[e];n;){var r=n.parentFocusKey,s=this.focusableComponents[r];s&&this.saveLastFocusedChildKey(s,n.focusKey),n=s}},t.prototype.getKeyMap=function(){return this.keyMap},t.prototype.setKeyMap=function(e){this.keyMap=_d(_d({},this.getKeyMap()),Ele(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 s=[],i=this.focusableComponents[e];i;){var a=i.parentFocusKey,o=this.focusableComponents[a];o&&s.push(a),i=o}var l=s.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===vw)&&(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||Zb(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,s=this.useGetBoundingClientRect?mle(r):ple(r);n.layout=_d(_d({},s),{node:r})}},t.prototype.updateFocusable=function(e,n){var r=n.node,s=n.preferredChildFocusKey,i=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 m=this.focusableComponents[e];m&&(m.preferredChildFocusKey=s,m.focusable=i,m.isFocusBoundary=a,m.focusBoundaryDirections=o,m.onEnterPress=l,m.onEnterRelease=c,m.onArrowPress=u,m.onFocus=d,m.onBlur=h,m.accessibilityLabel=f,r&&(m.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?fi.RTL:fi.LTR},t}(),ns=new wle,Tle=ns.init;ns.setThrottle;ns.destroy;ns.setKeyMap;var ru=ns.setFocus;ns.navigateByDirection;ns.pause;ns.resume;ns.updateAllLayouts;ns.getCurrentFocusKey;ns.doesFocusableExist;ns.updateRtl;var Qv=C.createContext(vw);Qv.displayName="FocusContext";var Ale=function(){return C.useContext(Qv)},Rle=function(t){var e=t===void 0?{}:t,n=e.focusable,r=n===void 0?!0:n,s=e.saveLastFocusedChild,i=s===void 0?!0:s,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,m=e.focusBoundaryDirections,g=e.focusKey,y=e.preferredChildFocusKey,v=e.onEnterPress,_=v===void 0?ff:v,S=e.onEnterRelease,E=S===void 0?ff:S,L=e.onArrowPress,U=L===void 0?function(){return!0}:L,P=e.onArrowRelease,I=P===void 0?ff:P,k=e.onFocus,R=k===void 0?ff:k,M=e.onBlur,G=M===void 0?ff:M,Y=e.extraProps,q=e.accessibilityLabel,X=C.useCallback(function(Ue){_(Y,Ue)},[_,Y]),Z=C.useCallback(function(){E(Y)},[E,Y]),oe=C.useCallback(function(Ue,Oe){return U(Ue,Y,Oe)},[Y,U]),ne=C.useCallback(function(Ue){I(Ue,Y)},[I,Y]),H=C.useCallback(function(Ue,Oe){R(Ue,Y,Oe)},[Y,R]),K=C.useCallback(function(Ue,Oe){G(Ue,Y,Oe)},[Y,G]),J=C.useRef(null),Q=C.useState(!1),ve=Q[0],Te=Q[1],Ne=C.useState(!1),Ke=Ne[0],be=Ne[1],Pe=Ale(),Ae=C.useMemo(function(){return g||ule("sn:focusable-item-")},[g]),we=C.useCallback(function(Ue){Ue===void 0&&(Ue={}),ns.setFocus(Ae,Ue)},[Ae]);return C.useEffect(function(){var Ue=J.current;return ns.addFocusable({focusKey:Ae,node:Ue,parentFocusKey:Pe,preferredChildFocusKey:y,onEnterPress:X,onEnterRelease:Z,onArrowPress:oe,onArrowRelease:ne,onFocus:H,onBlur:K,onUpdateFocus:function(Oe){return Oe===void 0&&(Oe=!1),Te(Oe)},onUpdateHasFocusedChild:function(Oe){return Oe===void 0&&(Oe=!1),be(Oe)},saveLastFocusedChild:i,trackChildren:o,isFocusBoundary:f,focusBoundaryDirections:m,autoRestoreFocus:c,forceFocus:d,focusable:r,accessibilityLabel:q}),function(){ns.removeFocusable({focusKey:Ae})}},[]),C.useEffect(function(){var Ue=J.current;ns.updateFocusable(Ae,{node:Ue,preferredChildFocusKey:y,focusable:r,isFocusBoundary:f,focusBoundaryDirections:m,onEnterPress:X,onEnterRelease:Z,onArrowPress:oe,onArrowRelease:ne,onFocus:H,onBlur:K,accessibilityLabel:q})},[Ae,y,r,f,m,X,Z,oe,ne,H,K,q]),{ref:J,focusSelf:we,focused:ve,hasFocusedChild:Ke,focusKey:Ae}},Kh=Rle;let wc=null,Tc=null;const Cle="nadiplay_nav_sounds";function LF(){if(typeof window>"u")return!1;const t=localStorage.getItem(Cle);return t!==null?t==="1":!0}function kle(){if(!(typeof window>"u"))try{wc=new Audio("/audio/nav-move.mp3"),wc.preload="auto",wc.volume=.4,Tc=new Audio("/audio/nav-select.mp3"),Tc.preload="auto",Tc.volume=.5}catch(t){console.warn("Failed to preload nav sounds:",t)}}function Jv(){if(LF())try{wc||(wc=new Audio("/audio/nav-move.mp3"),wc.volume=.4);const t=wc.cloneNode();t.volume=.4,t.play().catch(()=>{})}catch{}}function su(){if(LF())try{Tc||(Tc=new Audio("/audio/nav-select.mp3"),Tc.volume=.5);const t=Tc.cloneNode();t.volume=.5,t.play().catch(()=>{})}catch{}}const nx=["MediaPlay","MediaPause","MediaStop","MediaPlayPause","MediaRewind","MediaFastForward","MediaTrackNext","MediaTrackPrevious","MediaRecord","ChannelUp","ChannelDown","ColorF0Red","ColorF1Green","ColorF2Yellow","ColorF3Blue","Info","Exit","Source","Menu","Tools","0","1","2","3","4","5","6","7","8","9"];let RP=!1;const Lle=()=>{if(RP||typeof window>"u")return;const t=window.tizen,e=t==null?void 0:t.tvinputdevice;if(e)try{if(typeof e.registerKeyBatch=="function")e.registerKeyBatch([...nx]);else for(const n of nx)try{e.registerKey(n)}catch(r){console.warn(`[Tizen Remote] registerKey(${n}) failed`,r)}RP=!0,console.log("[Tizen Remote] keys registered:",nx.length)}catch(n){console.error("[Tizen Remote] registration failed:",n)}};let CP=!1;const Ile=()=>{if(CP)return;CP=!0,kle(),Lle();const t=(()=>{try{return localStorage.getItem("nadiplay_sn_debug")==="1"}catch{return!1}})();Tle({debug:t,visualDebug:t,throttle:80,throttleKeypresses:!0})},Ple=({children:t})=>{C.useEffect(()=>{Ile()},[]);const{ref:e,focusKey:n}=Kh({focusable:!1,trackChildren:!0,isFocusBoundary:!1});return p.jsx(Qv.Provider,{value:n,children:p.jsx("div",{ref:e,style:{display:"contents"},children:t})})},wi=C.forwardRef(({className:t,focusClassName:e,focusKey:n,onClick:r,onEnter:s,onMouseEnter:i,subtle:a,children:o,disabled:l,...c},u)=>{const{ref:d,focused:h,focusKey:f}=Kh({focusKey:n,focusable:!l,onEnterPress:()=>{var y;l||(su(),(y=s??r)==null||y({currentTarget:d.current}))},onFocus:()=>{Jv()},extraProps:{label:typeof o=="string"?o:void 0}});C.useImperativeHandle(u,()=>d.current);const m=y=>{su(),r==null||r(y)},g=y=>{!l&&f&&ru(f),i==null||i(y)};return p.jsx("button",{ref:d,"data-focused":h||void 0,disabled:l,onClick:m,onMouseEnter:g,className:gs(a?"focusable focusable-chip":"focusable",h&&"is-focused",t,h&&e),...c,children:o})});wi.displayName="FocusableButton";const Kl=C.forwardRef(({className:t,focusKey:e,onClick:n,onEnter:r,onMouseEnter:s,subtle:i,children:a,...o},l)=>{const{ref:c,focused:u,focusKey:d}=Kh({focusKey:e,onEnterPress:()=>{var m;su(),(m=r??n)==null||m({currentTarget:c.current})},onFocus:({node:m})=>{Jv(),m&&m.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})}});C.useImperativeHandle(l,()=>c.current);const h=m=>{su(),n==null||n(m)},f=m=>{d&&ru(d),s==null||s(m)};return p.jsx("div",{ref:c,role:"button",tabIndex:0,"data-focused":u||void 0,onClick:h,onMouseEnter:f,className:gs("focusable",!i&&"focusable-tile",u&&"is-focused",t),...o,children:a})});Kl.displayName="FocusableTile";const Ci=({focusKey:t,className:e,trap:n,autoFocus:r,children:s,as:i="div",...a})=>{const{ref:o,focusKey:l}=Kh({focusKey:t,focusable:!1,trackChildren:!0,isFocusBoundary:!!n,saveLastFocusedChild:!0});C.useEffect(()=>{if(!r||!l)return;const u=window.setTimeout(()=>ru(l),80);return()=>window.clearTimeout(u)},[r,l]);const c=i;return p.jsx(Qv.Provider,{value:l,children:p.jsx(c,{ref:o,className:gs(e),...a,children:s})})},{slice:Dle,forEach:Ole}=[];function Nle(t){return Ole.call(Dle.call(arguments,1),e=>{if(e)for(const n in e)t[n]===void 0&&(t[n]=e[n])}),t}function Mle(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 kP=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,jle=function(t,e){const r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},s=encodeURIComponent(e);let i=`${t}=${s}`;if(r.maxAge>0){const a=r.maxAge-0;if(Number.isNaN(a))throw new Error("maxAge should be a Number");i+=`; Max-Age=${Math.floor(a)}`}if(r.domain){if(!kP.test(r.domain))throw new TypeError("option domain is invalid");i+=`; Domain=${r.domain}`}if(r.path){if(!kP.test(r.path))throw new TypeError("option path is invalid");i+=`; Path=${r.path}`}if(r.expires){if(typeof r.expires.toUTCString!="function")throw new TypeError("option expires is invalid");i+=`; Expires=${r.expires.toUTCString()}`}if(r.httpOnly&&(i+="; HttpOnly"),r.secure&&(i+="; Secure"),r.sameSite)switch(typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite){case!0:i+="; SameSite=Strict";break;case"lax":i+="; SameSite=Lax";break;case"strict":i+="; SameSite=Strict";break;case"none":i+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return r.partitioned&&(i+="; Partitioned"),i},LP={create(t,e,n,r){let s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};n&&(s.expires=new Date,s.expires.setTime(s.expires.getTime()+n*60*1e3)),r&&(s.domain=r),document.cookie=jle(t,e,s)},read(t){const e=`${t}=`,n=document.cookie.split(";");for(let r=0;r<n.length;r++){let s=n[r];for(;s.charAt(0)===" ";)s=s.substring(1,s.length);if(s.indexOf(e)===0)return s.substring(e.length,s.length)}return null},remove(t,e){this.create(t,"",-1,e)}};var Ule={name:"cookie",lookup(t){let{lookupCookie:e}=t;if(e&&typeof document<"u")return LP.read(e)||void 0},cacheUserLanguage(t,e){let{lookupCookie:n,cookieMinutes:r,cookieDomain:s,cookieOptions:i}=e;n&&typeof document<"u"&&LP.create(n,t,r,s,i)}},Ble={name:"querystring",lookup(t){var r;let{lookupQuerystring:e}=t,n;if(typeof window<"u"){let{search:s}=window.location;!window.location.search&&((r=window.location.hash)==null?void 0:r.indexOf("?"))>-1&&(s=window.location.hash.substring(window.location.hash.indexOf("?")));const a=s.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}},Fle={name:"hash",lookup(t){var s;let{lookupHash:e,lookupFromHashIndex:n}=t,r;if(typeof window<"u"){const{hash:i}=window.location;if(i&&i.length>2){const a=i.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=i.match(/\/([a-zA-Z-]*)/g);return Array.isArray(o)?(s=o[typeof n=="number"?n:0])==null?void 0:s.replace("/",""):void 0}}}return r}};let Ou=null;const IP=()=>{if(Ou!==null)return Ou;try{if(Ou=typeof window<"u"&&window.localStorage!==null,!Ou)return!1;const t="i18next.translate.boo";window.localStorage.setItem(t,"foo"),window.localStorage.removeItem(t)}catch{Ou=!1}return Ou};var $le={name:"localStorage",lookup(t){let{lookupLocalStorage:e}=t;if(e&&IP())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupLocalStorage:n}=e;n&&IP()&&window.localStorage.setItem(n,t)}};let Nu=null;const PP=()=>{if(Nu!==null)return Nu;try{if(Nu=typeof window<"u"&&window.sessionStorage!==null,!Nu)return!1;const t="i18next.translate.boo";window.sessionStorage.setItem(t,"foo"),window.sessionStorage.removeItem(t)}catch{Nu=!1}return Nu};var Vle={name:"sessionStorage",lookup(t){let{lookupSessionStorage:e}=t;if(e&&PP())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupSessionStorage:n}=e;n&&PP()&&window.sessionStorage.setItem(n,t)}},Gle={name:"navigator",lookup(t){const e=[];if(typeof navigator<"u"){const{languages:n,userLanguage:r,language:s}=navigator;if(n)for(let i=0;i<n.length;i++)e.push(n[i]);r&&e.push(r),s&&e.push(s)}return e.length>0?e:void 0}},Kle={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}},Hle={name:"path",lookup(t){var s;let{lookupFromPathIndex:e}=t;if(typeof window>"u")return;const n=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(n)?(s=n[typeof e=="number"?e:0])==null?void 0:s.replace("/",""):void 0}},zle={name:"subdomain",lookup(t){var s,i;let{lookupFromSubdomainIndex:e}=t;const n=typeof e=="number"?e+1:1,r=typeof window<"u"&&((i=(s=window.location)==null?void 0:s.hostname)==null?void 0:i.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i));if(r)return r[n]}};let IF=!1;try{document.cookie,IF=!0}catch{}const PF=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];IF||PF.splice(1,1);const qle=()=>({order:PF,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:t=>t});class DF{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=Nle(n,this.options||{},qle()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=s=>s.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=r,this.addDetector(Ule),this.addDetector(Ble),this.addDetector($le),this.addDetector(Vle),this.addDetector(Gle),this.addDetector(Kle),this.addDetector(Hle),this.addDetector(zle),this.addDetector(Fle)}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 s=this.detectors[r].lookup(this.options);s&&typeof s=="string"&&(s=[s]),s&&(n=n.concat(s))}}),n=n.filter(r=>r!=null&&!Mle(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)}))}}DF.type="languageDetector";const Gi=[{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"}],ot={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"},firstRun:{title:"Choose your language",subtitle:"Use ← → to switch flags, then press Continue",continue:"Continue",hint:"You can change this later from Settings"},update:{titleNormal:"New update available",titleForced:"Update required",forcedNotice:"You must install the latest version to keep using the app.",adminPreview:"Admin preview. This popup is forced for normal users (installed v{{installed}} < min v{{min}}). You can dismiss it freely — admins are never locked out.",loginPreview:'Login is always reachable so admins can update the app version. Tap "Later" to continue to the login form.',needPermission:'Please enable "Allow install from this source" for Nadiplayer in the screen we just opened, then come back and tap the button again.',installerOpened:"Installer opened. Follow the on-screen prompt to install.",whatsNew:"What's new",noUrl:"No download link configured. Contact the admin.",downloadingPercent:"Downloading {{percent}}%…",downloading:"Downloading…",openingInstaller:"Opening installer…",allowInstallRetry:"Allow install — try again",installerLaunched:"Installer launched",retry:"Retry update",updateNow:"Update now",downloadUpdate:"Download update",openInPlayStore:"Open in Play Store",later:"Later",closeAria:"Close update notice"},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"}}},Wle={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 مميزة"},firstRun:{title:"اختر لغتك",subtitle:"استخدم ← → للتنقل بين الأعلام، ثم اضغط متابعة",continue:"متابعة",hint:"يمكنك تغيير هذا لاحقا من الإعدادات"},update:{titleNormal:"تحديث جديد متاح",titleForced:"التحديث مطلوب",forcedNotice:"يجب تثبيت أحدث إصدار لمتابعة استخدام التطبيق.",adminPreview:"معاينة المسؤول. هذه النافذة إلزامية للمستخدمين العاديين (الإصدار المثبت v{{installed}} أقل من الحد الأدنى v{{min}}). يمكنك تجاهلها بحرية — لا يتم حظر المسؤولين أبدا.",loginPreview:'صفحة تسجيل الدخول متاحة دائما حتى يتمكن المسؤولون من تحديث إصدار التطبيق. اضغط "لاحقا" للمتابعة إلى نموذج تسجيل الدخول.',needPermission:'يرجى تمكين "السماح بالتثبيت من هذا المصدر" لتطبيق Nadiplayer في الشاشة التي فتحناها للتو، ثم عد واضغط الزر مرة أخرى.',installerOpened:"تم فتح المثبت. اتبع التعليمات على الشاشة للتثبيت.",whatsNew:"ما الجديد",noUrl:"لم يتم تكوين رابط التنزيل. تواصل مع المسؤول.",downloadingPercent:"جاري التنزيل {{percent}}%…",downloading:"جاري التنزيل…",openingInstaller:"جاري فتح المثبت…",allowInstallRetry:"اسمح بالتثبيت — حاول مرة أخرى",installerLaunched:"تم تشغيل المثبت",retry:"إعادة محاولة التحديث",updateNow:"تحديث الآن",downloadUpdate:"تنزيل التحديث",openInPlayStore:"افتح في متجر Play",later:"لاحقا",closeAria:"إغلاق إشعار التحديث"},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:"فشل"}}},Yle={translation:{...ot.translation,welcome:{...ot.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:{...ot.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:{...ot.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:{...ot.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:{...ot.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"},firstRun:{title:"Choisissez votre langue",subtitle:"Utilisez ← → pour changer de drapeau, puis appuyez sur Continuer",continue:"Continuer",hint:"Vous pourrez modifier cela plus tard dans les paramètres"},update:{titleNormal:"Nouvelle mise à jour disponible",titleForced:"Mise à jour requise",forcedNotice:"Vous devez installer la dernière version pour continuer à utiliser l'application.",adminPreview:"Aperçu admin. Ce popup est forcé pour les utilisateurs normaux (installé v{{installed}} < min v{{min}}). Vous pouvez le fermer librement — les admins ne sont jamais bloqués.",loginPreview:"La connexion est toujours accessible afin que les administrateurs puissent mettre à jour la version. Appuyez sur « Plus tard » pour accéder au formulaire de connexion.",needPermission:"Veuillez activer « Autoriser l'installation depuis cette source » pour Nadiplayer dans l'écran qui vient de s'ouvrir, puis revenez et réappuyez sur le bouton.",installerOpened:"Programme d'installation ouvert. Suivez les instructions à l'écran.",whatsNew:"Nouveautés",noUrl:"Aucun lien de téléchargement configuré. Contactez l'administrateur.",downloadingPercent:"Téléchargement {{percent}}%…",downloading:"Téléchargement…",openingInstaller:"Ouverture du programme d'installation…",allowInstallRetry:"Autoriser l'installation — réessayer",installerLaunched:"Programme d'installation lancé",retry:"Réessayer la mise à jour",updateNow:"Mettre à jour",downloadUpdate:"Télécharger la mise à jour",openInPlayStore:"Ouvrir dans Play Store",later:"Plus tard",closeAria:"Fermer la notification de mise à jour"},notFound:{...ot.translation.notFound,message:"Oups ! Page introuvable",goHome:"Retour à l'accueil"},liveTV:{...ot.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:{...ot.translation.movies,title:"FILMS",searchPlaceholder:"Rechercher des films...",noActiveServer:"Aucun serveur actif.",addProfile:"Ajouter un profil",failedLoad:"Échec du chargement des films."},series:{...ot.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:{...ot.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:{...ot.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:{...ot.translation.account,title:"COMPTE",addServer:"Ajouter un serveur",devicePairing:"Appairage d'appareil",playbackMode:"Mode de lecture",externalPlayer:"Lecteur externe",playerIdentity:"Identité du lecteur"}}},Xle={translation:{...ot.translation,welcome:{...ot.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:{...ot.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:{...ot.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:{...ot.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:{...ot.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"},firstRun:{title:"Elige tu idioma",subtitle:"Usa ← → para cambiar de bandera, luego pulsa Continuar",continue:"Continuar",hint:"Puedes cambiarlo más tarde desde Ajustes"},update:{titleNormal:"Nueva actualización disponible",titleForced:"Actualización requerida",forcedNotice:"Debes instalar la última versión para seguir usando la app.",adminPreview:"Vista de admin. Este popup es obligatorio para usuarios normales (instalado v{{installed}} < min v{{min}}). Puedes cerrarlo libremente — los administradores nunca quedan bloqueados.",loginPreview:'El inicio de sesión siempre está disponible para que los administradores puedan actualizar la versión. Pulsa "Más tarde" para continuar al formulario de inicio.',needPermission:'Activa "Permitir instalación desde esta fuente" para Nadiplayer en la pantalla que abrimos, luego vuelve y pulsa el botón otra vez.',installerOpened:"Instalador abierto. Sigue las instrucciones para instalar.",whatsNew:"Novedades",noUrl:"No hay enlace de descarga configurado. Contacta al administrador.",downloadingPercent:"Descargando {{percent}}%…",downloading:"Descargando…",openingInstaller:"Abriendo instalador…",allowInstallRetry:"Permitir instalación — reintentar",installerLaunched:"Instalador iniciado",retry:"Reintentar actualización",updateNow:"Actualizar ahora",downloadUpdate:"Descargar actualización",openInPlayStore:"Abrir en Play Store",later:"Más tarde",closeAria:"Cerrar aviso de actualización"},notFound:{...ot.translation.notFound,message:"¡Ups! Página no encontrada",goHome:"Volver al inicio"},liveTV:{...ot.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:{...ot.translation.movies,title:"PELÍCULAS",searchPlaceholder:"Buscar películas...",noActiveServer:"Sin servidor activo.",addProfile:"Añadir perfil",failedLoad:"Error al cargar películas."},series:{...ot.translation.series,title:"SERIES",searchPlaceholder:"Buscar series...",noActiveServer:"Sin servidor activo.",addProfile:"Añadir perfil",failedLoad:"Error al cargar series.",season:"Temporada {{n}}"},addServer:{...ot.translation.addServer,title:"AÑADIR PLAYLIST",advanced:"Avanzado",shared:"Compartido",ownServer:"Servidor propio"},admin:{...ot.translation.admin,subtitle:"Panel de control de suscriptores",settingsHeading:"AJUSTES GLOBALES",createHeading:"CREAR SUSCRIPTOR",subscribersHeading:"SUSCRIPTORES ({{count}})",createUser:"Crear usuario",saveSettings:"Guardar"},account:{...ot.translation.account,title:"CUENTA",addServer:"Añadir servidor",devicePairing:"Emparejar dispositivo",playbackMode:"Modo de reproducción",externalPlayer:"Reproductor externo",playerIdentity:"Identidad del reproductor"}}},Qle={translation:{...ot.translation,welcome:{...ot.translation.welcome,chooseHowToContinue:"Выберите, как продолжить",guest:"ГОСТЬ",guestHint:"Войдите со своим собственным сервером Xtream.",enter:"Войти",login:"ВХОД",loginHint:"Подписчики: войдите с данными от администратора.",signIn:"Войти",premiumTag:"Премиум IPTV-опыт",language:"Язык"},login:{...ot.translation.login,subtitle:"Вход подписчика",username:"Имя пользователя",password:"Пароль",submit:"Войти",submitting:"Вход...",contactAdmin:"Нет аккаунта? Свяжитесь с администратором NADIPLAYER.",back:"Назад"},home:{...ot.translation.home,logout:"Выйти",profile:"Профиль",guestMode:"Режим гостя",connected:"Подключено.",awaiting:"Ожидание синхронизации.",waiting:"Ожидание подключения.",subscriber:"Подписчик",expires:"Истекает",noExpiry:"Без срока действия",daysRemaining_one:"Осталось {{count}} день",daysRemaining_other:"Осталось {{count}} дней",expired:"ИСТЁК",categories:{...ot.translation.home.categories,liveTv:"ТВ",movies:"Фильмы",series:"Сериалы",liveTvCount:"+5000 каналов",moviesCount:"+1200 фильмов",seriesCount:"+500 сериалов"},infoBar:"ТВ: +5000 каналов. ФИЛЬМЫ: +1200. СЕРИАЛЫ: +500."},expired:{...ot.translation.expired,title:"ПОДПИСКА ИСТЕКЛА",hi:"Привет",message:"Ваша подписка NADIPLAYER закончилась. Свяжитесь с нами в WhatsApp для продления.",contactWhatsapp:"Написать в WhatsApp",signOut:"Выйти",whatsappPrefill:"Здравствуйте, моя подписка NADIPLAYER ({{username}}) истекла. Хочу продлить."},splash:{tagline:"Настройтесь на вселенную",premiumTag:"Премиум IPTV-опыт"},firstRun:{title:"Выберите язык",subtitle:"Используйте ← → для смены флага, затем нажмите Продолжить",continue:"Продолжить",hint:"Это можно изменить позже в настройках"},update:{titleNormal:"Доступно обновление",titleForced:"Требуется обновление",forcedNotice:"Чтобы продолжить пользоваться приложением, установите последнюю версию.",adminPreview:"Предпросмотр администратора. Это окно обязательно для обычных пользователей (установлена v{{installed}} < минимум v{{min}}). Вы можете закрыть его — администраторы никогда не блокируются.",loginPreview:"Страница входа всегда доступна, чтобы администраторы могли обновить версию приложения. Нажмите «Позже», чтобы перейти к форме входа.",needPermission:"Включите «Разрешить установку из этого источника» для Nadiplayer в открытом окне, затем вернитесь и нажмите кнопку снова.",installerOpened:"Установщик открыт. Следуйте подсказкам на экране для установки.",whatsNew:"Что нового",noUrl:"Ссылка для загрузки не настроена. Свяжитесь с администратором.",downloadingPercent:"Загрузка {{percent}}%…",downloading:"Загрузка…",openingInstaller:"Открытие установщика…",allowInstallRetry:"Разрешите установку — попробуйте снова",installerLaunched:"Установщик запущен",retry:"Повторить обновление",updateNow:"Обновить сейчас",downloadUpdate:"Скачать обновление",openInPlayStore:"Открыть в Play Store",later:"Позже",closeAria:"Закрыть уведомление об обновлении"},notFound:{...ot.translation.notFound,message:"Упс! Страница не найдена",goHome:"На главную"},liveTV:{...ot.translation.liveTV,title:"ЖИВОЕ ТВ",searchPlaceholder:"Поиск каналов…",noActiveServer:"Нет активного сервера.",addProfile:"Добавить профиль",favs:"Избранное",selectChannel:"Выберите канал",noChannels:"Каналы не найдены.",channels_one:"{{count}} канал",channels_other:"{{count}} каналов"},movies:{...ot.translation.movies,title:"ФИЛЬМЫ",searchPlaceholder:"Поиск фильмов...",noActiveServer:"Нет активного сервера.",addProfile:"Добавить профиль",failedLoad:"Не удалось загрузить фильмы."},series:{...ot.translation.series,title:"СЕРИАЛЫ",searchPlaceholder:"Поиск сериалов...",noActiveServer:"Нет активного сервера.",addProfile:"Добавить профиль",failedLoad:"Не удалось загрузить сериалы.",season:"Сезон {{n}}"},addServer:{...ot.translation.addServer,title:"ДОБАВИТЬ ПЛЕЙЛИСТ",advanced:"Расширенные",shared:"Общий",ownServer:"Свой сервер"},admin:{...ot.translation.admin,subtitle:"Панель управления подписчиками",settingsHeading:"ГЛОБАЛЬНЫЕ НАСТРОЙКИ",createHeading:"СОЗДАТЬ ПОДПИСЧИКА",subscribersHeading:"ПОДПИСЧИКИ ({{count}})",createUser:"Создать",saveSettings:"Сохранить"},account:{...ot.translation.account,title:"АККАУНТ",addServer:"Добавить сервер",devicePairing:"Связать устройство",playbackMode:"Режим воспроизведения",externalPlayer:"Внешний плеер",playerIdentity:"Идентификатор плеера"}}},Jle={translation:{...ot.translation,welcome:{...ot.translation.welcome,chooseHowToContinue:"계속하는 방법을 선택하세요",guest:"게스트",guestHint:"자신의 Xtream 서버로 입장하세요.",enter:"입장",login:"로그인",loginHint:"가입자: 관리자가 제공한 아이디와 비밀번호로 로그인하세요.",signIn:"로그인",premiumTag:"프리미엄 IPTV 경험",language:"언어"},login:{...ot.translation.login,subtitle:"가입자 로그인",username:"사용자 이름",password:"비밀번호",submit:"로그인",submitting:"로그인 중...",contactAdmin:"계정이 없으신가요? NADIPLAYER 관리자에게 문의하세요.",back:"뒤로"},home:{...ot.translation.home,logout:"로그아웃",profile:"프로필",guestMode:"게스트 모드",connected:"연결됨.",awaiting:"서버 동기화 대기 중.",waiting:"연결 대기 중.",subscriber:"가입자",expires:"만료일",noExpiry:"만료일 없음",daysRemaining_one:"{{count}}일 남음",daysRemaining_other:"{{count}}일 남음",expired:"만료됨",categories:{...ot.translation.home.categories,liveTv:"실시간 TV",movies:"영화",series:"시리즈",liveTvCount:"+5000 채널",moviesCount:"+1200 영화",seriesCount:"+500 시리즈"},infoBar:"실시간: +5000 채널. 영화: +1200. 시리즈: +500."},expired:{...ot.translation.expired,title:"구독 만료됨",hi:"안녕하세요",message:"NADIPLAYER 구독이 종료되었습니다. 갱신을 위해 WhatsApp으로 문의하세요.",contactWhatsapp:"WhatsApp으로 문의",signOut:"로그아웃",whatsappPrefill:"안녕하세요, 제 NADIPLAYER 구독 ({{username}})이 만료되었습니다. 갱신하고 싶습니다."},splash:{tagline:"우주에 맞추세요",premiumTag:"프리미엄 IPTV 경험"},firstRun:{title:"언어를 선택하세요",subtitle:"← → 키로 국기를 전환한 후 계속을 누르세요",continue:"계속",hint:"나중에 설정에서 변경할 수 있습니다"},update:{titleNormal:"새 업데이트 사용 가능",titleForced:"업데이트 필요",forcedNotice:"앱을 계속 사용하려면 최신 버전을 설치해야 합니다.",adminPreview:"관리자 미리보기. 이 팝업은 일반 사용자에게 강제됩니다 (설치 v{{installed}} < 최소 v{{min}}). 자유롭게 닫을 수 있습니다 — 관리자는 절대 잠기지 않습니다.",loginPreview:'관리자가 앱 버전을 업데이트할 수 있도록 로그인은 항상 접근 가능합니다. "나중에"를 눌러 로그인 양식으로 계속하세요.',needPermission:'방금 연 화면에서 Nadiplayer에 대해 "이 출처에서 설치 허용"을 활성화한 다음, 돌아와서 버튼을 다시 누르세요.',installerOpened:"설치 프로그램이 열렸습니다. 화면 안내에 따라 설치하세요.",whatsNew:"새로운 기능",noUrl:"다운로드 링크가 구성되지 않았습니다. 관리자에게 문의하세요.",downloadingPercent:"다운로드 중 {{percent}}%…",downloading:"다운로드 중…",openingInstaller:"설치 프로그램 여는 중…",allowInstallRetry:"설치 허용 — 다시 시도",installerLaunched:"설치 프로그램 시작됨",retry:"업데이트 재시도",updateNow:"지금 업데이트",downloadUpdate:"업데이트 다운로드",openInPlayStore:"Play 스토어에서 열기",later:"나중에",closeAria:"업데이트 알림 닫기"},notFound:{...ot.translation.notFound,message:"페이지를 찾을 수 없습니다",goHome:"홈으로"},liveTV:{...ot.translation.liveTV,title:"실시간 TV",searchPlaceholder:"채널 검색…",noActiveServer:"활성 서버 없음.",addProfile:"프로필 추가",favs:"즐겨찾기",selectChannel:"채널을 선택하세요",noChannels:"채널을 찾을 수 없습니다.",channels_one:"{{count}}개 채널",channels_other:"{{count}}개 채널"},movies:{...ot.translation.movies,title:"영화",searchPlaceholder:"영화 검색...",noActiveServer:"활성 서버 없음.",addProfile:"프로필 추가",failedLoad:"영화 로드 실패."},series:{...ot.translation.series,title:"시리즈",searchPlaceholder:"시리즈 검색...",noActiveServer:"활성 서버 없음.",addProfile:"프로필 추가",failedLoad:"시리즈 로드 실패.",season:"시즌 {{n}}"},addServer:{...ot.translation.addServer,title:"플레이리스트 추가",advanced:"고급",shared:"공유",ownServer:"자체 서버"},admin:{...ot.translation.admin,subtitle:"가입자 제어판",settingsHeading:"전체 설정",createHeading:"가입자 생성",subscribersHeading:"가입자 ({{count}})",createUser:"사용자 생성",saveSettings:"저장"},account:{...ot.translation.account,title:"계정",addServer:"서버 추가",devicePairing:"기기 연결",playbackMode:"재생 모드",externalPlayer:"외부 플레이어",playerIdentity:"플레이어 신원"}}},Zle={translation:{...ot.translation,welcome:{...ot.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:{...ot.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:{...ot.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:{...ot.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:{...ot.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"},firstRun:{title:"Pumili ng iyong wika",subtitle:"Gamitin ang ← → para magpalit ng flag, pagkatapos ay pindutin ang Magpatuloy",continue:"Magpatuloy",hint:"Maaari mo itong palitan mamaya sa Settings"},update:{titleNormal:"May bagong update",titleForced:"Kailangan ng update",forcedNotice:"Kailangang i-install ang pinakabagong bersyon para magpatuloy sa paggamit ng app.",adminPreview:"Admin preview. Ang popup na ito ay sapilitan para sa mga regular na user (naka-install v{{installed}} < min v{{min}}). Maaari mong i-dismiss ng walang problema — hindi naka-lock ang mga admin.",loginPreview:'Laging maa-access ang login para ma-update ng admin ang bersyon ng app. Pindutin ang "Mamaya" para magpatuloy sa login form.',needPermission:'Paki-enable ang "Allow install from this source" para sa Nadiplayer sa screen na binuksan natin, pagkatapos ay bumalik at pindutin ulit ang button.',installerOpened:"Bukas na ang installer. Sundin ang on-screen na panuto upang i-install.",whatsNew:"Ano ang bago",noUrl:"Walang naka-configure na download link. Kontakin ang admin.",downloadingPercent:"Nagda-download {{percent}}%…",downloading:"Nagda-download…",openingInstaller:"Binubuksan ang installer…",allowInstallRetry:"Payagan ang install — subukan muli",installerLaunched:"Pinagana ang installer",retry:"Subukan muli ang update",updateNow:"Mag-update ngayon",downloadUpdate:"I-download ang update",openInPlayStore:"Buksan sa Play Store",later:"Mamaya",closeAria:"Isara ang update notice"},notFound:{...ot.translation.notFound,message:"Hindi nahanap ang pahina",goHome:"Bumalik sa home"},liveTV:{...ot.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:{...ot.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:{...ot.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:{...ot.translation.addServer,title:"MAGDAGDAG NG PLAYLIST",advanced:"Advanced",shared:"Shared",ownServer:"Sariling server"},admin:{...ot.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:{...ot.translation.account,title:"ACCOUNT",addServer:"Magdagdag ng server",devicePairing:"Pairing ng Device",playbackMode:"Playback Mode",externalPlayer:"External Player",playerIdentity:"Identity ng Player"}}},ece={en:ot,ar:Wle,fr:Yle,es:Xle,ru:Qle,ko:Jle,fil:Zle};Wr.use(DF).use(cee).init({resources:ece,fallbackLng:"en",supportedLngs:Gi.map(t=>t.code),interpolation:{escapeValue:!1},detection:{order:["localStorage","navigator"],lookupLocalStorage:"nadiplay_lang",caches:["localStorage"]}});const OF=t=>{const e=Gi.find(n=>n.code===t);typeof document<"u"&&(document.documentElement.dir=(e==null?void 0:e.dir)??"ltr",document.documentElement.lang=t)};OF(Wr.language||"en");Wr.on("languageChanged",OF);const Pm=({align:t="right"})=>{const{i18n:e}=wr(),[n,r]=C.useState(!1),s=C.useRef(null);C.useEffect(()=>{const a=o=>{s.current&&!s.current.contains(o.target)&&r(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[]);const i=Gi.find(a=>a.code===e.language)??Gi[0];return p.jsxs("div",{ref:s,className:"relative",children:[p.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:[p.jsx(Gz,{className:"w-4 h-4 text-primary shrink-0"}),p.jsx("span",{className:"text-lg leading-none",children:i.flag}),p.jsx("span",{className:"hidden sm:inline text-xs tracking-wider",children:i.label}),p.jsx(_m,{className:`w-3.5 h-3.5 text-muted-foreground transition-transform ${n?"rotate-180":""}`})]}),n&&p.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:Gi.map(a=>{const o=a.code===i.code;return p.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:[p.jsx("span",{className:"text-lg leading-none",children:a.flag}),p.jsx("span",{className:"flex-1 text-start",children:a.label}),o&&p.jsx(qi,{className:"w-4 h-4"})]},a.code)})})]})};var rx="focusScope.autoFocusOnMount",sx="focusScope.autoFocusOnUnmount",DP={bubbles:!1,cancelable:!0},tce="FocusScope",NF=C.forwardRef((t,e)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:s,onUnmountAutoFocus:i,...a}=t,[o,l]=C.useState(null),c=Ca(s),u=Ca(i),d=C.useRef(null),h=ps(e,g=>l(g)),f=C.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;C.useEffect(()=>{if(r){let g=function(S){if(f.paused||!o)return;const E=S.target;o.contains(E)?d.current=E:Wo(d.current,{select:!0})},y=function(S){if(f.paused||!o)return;const E=S.relatedTarget;E!==null&&(o.contains(E)||Wo(d.current,{select:!0}))},v=function(S){if(document.activeElement===document.body)for(const L of S)L.removedNodes.length>0&&Wo(o)};document.addEventListener("focusin",g),document.addEventListener("focusout",y);const _=new MutationObserver(v);return o&&_.observe(o,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",y),_.disconnect()}}},[r,o,f.paused]),C.useEffect(()=>{if(o){NP.add(f);const g=document.activeElement;if(!o.contains(g)){const v=new CustomEvent(rx,DP);o.addEventListener(rx,c),o.dispatchEvent(v),v.defaultPrevented||(nce(oce(MF(o)),{select:!0}),document.activeElement===g&&Wo(o))}return()=>{o.removeEventListener(rx,c),setTimeout(()=>{const v=new CustomEvent(sx,DP);o.addEventListener(sx,u),o.dispatchEvent(v),v.defaultPrevented||Wo(g??document.body,{select:!0}),o.removeEventListener(sx,u),NP.remove(f)},0)}}},[o,c,u,f]);const m=C.useCallback(g=>{if(!n&&!r||f.paused)return;const y=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,v=document.activeElement;if(y&&v){const _=g.currentTarget,[S,E]=rce(_);S&&E?!g.shiftKey&&v===E?(g.preventDefault(),n&&Wo(S,{select:!0})):g.shiftKey&&v===S&&(g.preventDefault(),n&&Wo(E,{select:!0})):v===_&&g.preventDefault()}},[n,r,f.paused]);return p.jsx(pr.div,{tabIndex:-1,...a,ref:h,onKeyDown:m})});NF.displayName=tce;function nce(t,{select:e=!1}={}){const n=document.activeElement;for(const r of t)if(Wo(r,{select:e}),document.activeElement!==n)return}function rce(t){const e=MF(t),n=OP(e,t),r=OP(e.reverse(),t);return[n,r]}function MF(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const s=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||s?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)e.push(n.currentNode);return e}function OP(t,e){for(const n of t)if(!sce(n,{upTo:e}))return n}function sce(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 ice(t){return t instanceof HTMLInputElement&&"select"in t}function Wo(t,{select:e=!1}={}){if(t&&t.focus){const n=document.activeElement;t.focus({preventScroll:!0}),t!==n&&ice(t)&&e&&t.select()}}var NP=ace();function ace(){let t=[];return{add(e){const n=t[0];e!==n&&(n==null||n.pause()),t=MP(t,e),t.unshift(e)},remove(e){var n;t=MP(t,e),(n=t[0])==null||n.resume()}}}function MP(t,e){const n=[...t],r=n.indexOf(e);return r!==-1&&n.splice(r,1),n}function oce(t){return t.filter(e=>e.tagName!=="A")}var ix=0;function lce(){C.useEffect(()=>{const t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??jP()),document.body.insertAdjacentElement("beforeend",t[1]??jP()),ix++,()=>{ix===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),ix--}},[])}function jP(){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 Ay="right-scroll-bar-position",Ry="width-before-scroll-bar",cce="with-scroll-bars-hidden",uce="--removed-body-scroll-bar-size";function ax(t,e){return typeof t=="function"?t(e):t&&(t.current=e),t}function dce(t,e){var n=C.useState(function(){return{value:t,callback:e,facade:{get current(){return n.value},set current(r){var s=n.value;s!==r&&(n.value=r,n.callback(r,s))}}}})[0];return n.callback=e,n.facade}var hce=typeof window<"u"?C.useLayoutEffect:C.useEffect,UP=new WeakMap;function fce(t,e){var n=dce(null,function(r){return t.forEach(function(s){return ax(s,r)})});return hce(function(){var r=UP.get(n);if(r){var s=new Set(r),i=new Set(t),a=n.current;s.forEach(function(o){i.has(o)||ax(o,null)}),i.forEach(function(o){s.has(o)||ax(o,a)})}UP.set(n,t)},[t]),n}function pce(t){return t}function mce(t,e){e===void 0&&(e=pce);var n=[],r=!1,s={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(i){var a=e(i,r);return n.push(a),function(){n=n.filter(function(o){return o!==a})}},assignSyncMedium:function(i){for(r=!0;n.length;){var a=n;n=[],a.forEach(i)}n={push:function(o){return i(o)},filter:function(){return n}}},assignMedium:function(i){r=!0;var a=[];if(n.length){var o=n;n=[],o.forEach(i),a=n}var l=function(){var u=a;a=[],u.forEach(i)},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 s}function gce(t){t===void 0&&(t={});var e=mce(null);return e.options=ga({async:!0,ssr:!1},t),e}var jF=function(t){var e=t.sideCar,n=$h(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 C.createElement(r,ga({},n))};jF.isSideCarExport=!0;function yce(t,e){return t.useMedium(e),jF}var UF=gce(),ox=function(){},Zv=C.forwardRef(function(t,e){var n=C.useRef(null),r=C.useState({onScrollCapture:ox,onWheelCapture:ox,onTouchMoveCapture:ox}),s=r[0],i=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,m=t.noIsolation,g=t.inert,y=t.allowPinchZoom,v=t.as,_=v===void 0?"div":v,S=t.gapMode,E=$h(t,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),L=h,U=fce([n,e]),P=ga(ga({},E),s);return C.createElement(C.Fragment,null,u&&C.createElement(L,{sideCar:UF,removeScrollBar:c,shards:d,noRelative:f,noIsolation:m,inert:g,setCallbacks:i,allowPinchZoom:!!y,lockRef:n,gapMode:S}),a?C.cloneElement(C.Children.only(o),ga(ga({},P),{ref:U})):C.createElement(_,ga({},P,{className:l,ref:U}),o))});Zv.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Zv.classNames={fullWidth:Ry,zeroRight:Ay};var vce=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function _ce(){if(!document)return null;var t=document.createElement("style");t.type="text/css";var e=vce();return e&&t.setAttribute("nonce",e),t}function bce(t,e){t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e))}function xce(t){var e=document.head||document.getElementsByTagName("head")[0];e.appendChild(t)}var Sce=function(){var t=0,e=null;return{add:function(n){t==0&&(e=_ce())&&(bce(e,n),xce(e)),t++},remove:function(){t--,!t&&e&&(e.parentNode&&e.parentNode.removeChild(e),e=null)}}},Ece=function(){var t=Sce();return function(e,n){C.useEffect(function(){return t.add(e),function(){t.remove()}},[e&&n])}},BF=function(){var t=Ece(),e=function(n){var r=n.styles,s=n.dynamic;return t(r,s),null};return e},wce={left:0,top:0,right:0,gap:0},lx=function(t){return parseInt(t||"",10)||0},Tce=function(t){var e=window.getComputedStyle(document.body),n=e[t==="padding"?"paddingLeft":"marginLeft"],r=e[t==="padding"?"paddingTop":"marginTop"],s=e[t==="padding"?"paddingRight":"marginRight"];return[lx(n),lx(r),lx(s)]},Ace=function(t){if(t===void 0&&(t="margin"),typeof window>"u")return wce;var e=Tce(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])}},Rce=BF(),Nd="data-scroll-locked",Cce=function(t,e,n,r){var s=t.left,i=t.top,a=t.right,o=t.gap;return n===void 0&&(n="margin"),`
  .`.concat(cce,` {
   overflow: hidden `).concat(r,`;
   padding-right: `).concat(o,"px ").concat(r,`;
  }
  body[`).concat(Nd,`] {
    overflow: hidden `).concat(r,`;
    overscroll-behavior: contain;
    `).concat([e&&"position: relative ".concat(r,";"),n==="margin"&&`
    padding-left: `.concat(s,`px;
    padding-top: `).concat(i,`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(Ay,` {
    right: `).concat(o,"px ").concat(r,`;
  }
  
  .`).concat(Ry,` {
    margin-right: `).concat(o,"px ").concat(r,`;
  }
  
  .`).concat(Ay," .").concat(Ay,` {
    right: 0 `).concat(r,`;
  }
  
  .`).concat(Ry," .").concat(Ry,` {
    margin-right: 0 `).concat(r,`;
  }
  
  body[`).concat(Nd,`] {
    `).concat(uce,": ").concat(o,`px;
  }
`)},BP=function(){var t=parseInt(document.body.getAttribute(Nd)||"0",10);return isFinite(t)?t:0},kce=function(){C.useEffect(function(){return document.body.setAttribute(Nd,(BP()+1).toString()),function(){var t=BP()-1;t<=0?document.body.removeAttribute(Nd):document.body.setAttribute(Nd,t.toString())}},[])},Lce=function(t){var e=t.noRelative,n=t.noImportant,r=t.gapMode,s=r===void 0?"margin":r;kce();var i=C.useMemo(function(){return Ace(s)},[s]);return C.createElement(Rce,{styles:Cce(i,!e,s,n?"":"!important")})},_w=!1;if(typeof window<"u")try{var Dg=Object.defineProperty({},"passive",{get:function(){return _w=!0,!0}});window.addEventListener("test",Dg,Dg),window.removeEventListener("test",Dg,Dg)}catch{_w=!1}var Mu=_w?{passive:!1}:!1,Ice=function(t){return t.tagName==="TEXTAREA"},FF=function(t,e){if(!(t instanceof Element))return!1;var n=window.getComputedStyle(t);return n[e]!=="hidden"&&!(n.overflowY===n.overflowX&&!Ice(t)&&n[e]==="visible")},Pce=function(t){return FF(t,"overflowY")},Dce=function(t){return FF(t,"overflowX")},FP=function(t,e){var n=e.ownerDocument,r=e;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var s=$F(t,r);if(s){var i=VF(t,r),a=i[1],o=i[2];if(a>o)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},Oce=function(t){var e=t.scrollTop,n=t.scrollHeight,r=t.clientHeight;return[e,n,r]},Nce=function(t){var e=t.scrollLeft,n=t.scrollWidth,r=t.clientWidth;return[e,n,r]},$F=function(t,e){return t==="v"?Pce(e):Dce(e)},VF=function(t,e){return t==="v"?Oce(e):Nce(e)},Mce=function(t,e){return t==="h"&&e==="rtl"?-1:1},jce=function(t,e,n,r,s){var i=Mce(t,window.getComputedStyle(e).direction),a=i*r,o=n.target,l=e.contains(o),c=!1,u=a>0,d=0,h=0;do{if(!o)break;var f=VF(t,o),m=f[0],g=f[1],y=f[2],v=g-y-i*m;(m||v)&&$F(t,o)&&(d+=v,h+=m);var _=o.parentNode;o=_&&_.nodeType===Node.DOCUMENT_FRAGMENT_NODE?_.host:_}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},Og=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},$P=function(t){return[t.deltaX,t.deltaY]},VP=function(t){return t&&"current"in t?t.current:t},Uce=function(t,e){return t[0]===e[0]&&t[1]===e[1]},Bce=function(t){return`
  .block-interactivity-`.concat(t,` {pointer-events: none;}
  .allow-interactivity-`).concat(t,` {pointer-events: all;}
`)},Fce=0,ju=[];function $ce(t){var e=C.useRef([]),n=C.useRef([0,0]),r=C.useRef(),s=C.useState(Fce++)[0],i=C.useState(BF)[0],a=C.useRef(t);C.useEffect(function(){a.current=t},[t]),C.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(s));var g=tte([t.lockRef.current],(t.shards||[]).map(VP),!0).filter(Boolean);return g.forEach(function(y){return y.classList.add("allow-interactivity-".concat(s))}),function(){document.body.classList.remove("block-interactivity-".concat(s)),g.forEach(function(y){return y.classList.remove("allow-interactivity-".concat(s))})}}},[t.inert,t.lockRef.current,t.shards]);var o=C.useCallback(function(g,y){if("touches"in g&&g.touches.length===2||g.type==="wheel"&&g.ctrlKey)return!a.current.allowPinchZoom;var v=Og(g),_=n.current,S="deltaX"in g?g.deltaX:_[0]-v[0],E="deltaY"in g?g.deltaY:_[1]-v[1],L,U=g.target,P=Math.abs(S)>Math.abs(E)?"h":"v";if("touches"in g&&P==="h"&&U.type==="range")return!1;var I=window.getSelection(),k=I&&I.anchorNode,R=k?k===U||k.contains(U):!1;if(R)return!1;var M=FP(P,U);if(!M)return!0;if(M?L=P:(L=P==="v"?"h":"v",M=FP(P,U)),!M)return!1;if(!r.current&&"changedTouches"in g&&(S||E)&&(r.current=L),!L)return!0;var G=r.current||L;return jce(G,y,g,G==="h"?S:E)},[]),l=C.useCallback(function(g){var y=g;if(!(!ju.length||ju[ju.length-1]!==i)){var v="deltaY"in y?$P(y):Og(y),_=e.current.filter(function(L){return L.name===y.type&&(L.target===y.target||y.target===L.shadowParent)&&Uce(L.delta,v)})[0];if(_&&_.should){y.cancelable&&y.preventDefault();return}if(!_){var S=(a.current.shards||[]).map(VP).filter(Boolean).filter(function(L){return L.contains(y.target)}),E=S.length>0?o(y,S[0]):!a.current.noIsolation;E&&y.cancelable&&y.preventDefault()}}},[]),c=C.useCallback(function(g,y,v,_){var S={name:g,delta:y,target:v,should:_,shadowParent:Vce(v)};e.current.push(S),setTimeout(function(){e.current=e.current.filter(function(E){return E!==S})},1)},[]),u=C.useCallback(function(g){n.current=Og(g),r.current=void 0},[]),d=C.useCallback(function(g){c(g.type,$P(g),g.target,o(g,t.lockRef.current))},[]),h=C.useCallback(function(g){c(g.type,Og(g),g.target,o(g,t.lockRef.current))},[]);C.useEffect(function(){return ju.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:h}),document.addEventListener("wheel",l,Mu),document.addEventListener("touchmove",l,Mu),document.addEventListener("touchstart",u,Mu),function(){ju=ju.filter(function(g){return g!==i}),document.removeEventListener("wheel",l,Mu),document.removeEventListener("touchmove",l,Mu),document.removeEventListener("touchstart",u,Mu)}},[]);var f=t.removeScrollBar,m=t.inert;return C.createElement(C.Fragment,null,m?C.createElement(i,{styles:Bce(s)}):null,f?C.createElement(Lce,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function Vce(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}const Gce=yce(UF,$ce);var GF=C.forwardRef(function(t,e){return C.createElement(Zv,ga({},t,{ref:e,sideCar:Gce}))});GF.classNames=Zv.classNames;var Kce=function(t){if(typeof document>"u")return null;var e=Array.isArray(t)?t[0]:t;return e.ownerDocument.body},Uu=new WeakMap,Ng=new WeakMap,Mg={},cx=0,KF=function(t){return t&&(t.host||KF(t.parentNode))},Hce=function(t,e){return e.map(function(n){if(t.contains(n))return n;var r=KF(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})},zce=function(t,e,n,r){var s=Hce(e,Array.isArray(t)?t:[t]);Mg[n]||(Mg[n]=new WeakMap);var i=Mg[n],a=[],o=new Set,l=new Set(s),c=function(d){!d||o.has(d)||(o.add(d),c(d.parentNode))};s.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),m=f!==null&&f!=="false",g=(Uu.get(h)||0)+1,y=(i.get(h)||0)+1;Uu.set(h,g),i.set(h,y),a.push(h),g===1&&m&&Ng.set(h,!0),y===1&&h.setAttribute(n,"true"),m||h.setAttribute(r,"true")}catch(v){console.error("aria-hidden: cannot operate on ",h,v)}})};return u(e),o.clear(),cx++,function(){a.forEach(function(d){var h=Uu.get(d)-1,f=i.get(d)-1;Uu.set(d,h),i.set(d,f),h||(Ng.has(d)||d.removeAttribute(r),Ng.delete(d)),f||d.removeAttribute(n)}),cx--,cx||(Uu=new WeakMap,Uu=new WeakMap,Ng=new WeakMap,Mg={})}},qce=function(t,e,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(t)?t:[t]),s=Kce(t);return s?(r.push.apply(r,Array.from(s.querySelectorAll("[aria-live], script"))),zce(r,s,n,"aria-hidden")):function(){return null}};function Wce(t){const e=Yce(t),n=C.forwardRef((r,s)=>{const{children:i,...a}=r,o=C.Children.toArray(i),l=o.find(Qce);if(l){const c=l.props.children,u=o.map(d=>d===l?C.Children.count(c)>1?C.Children.only(null):C.isValidElement(c)?c.props.children:null:d);return p.jsx(e,{...a,ref:s,children:C.isValidElement(c)?C.cloneElement(c,void 0,u):null})}return p.jsx(e,{...a,ref:s,children:i})});return n.displayName=`${t}.Slot`,n}function Yce(t){const e=C.forwardRef((n,r)=>{const{children:s,...i}=n;if(C.isValidElement(s)){const a=Zce(s),o=Jce(i,s.props);return s.type!==C.Fragment&&(o.ref=r?Ev(r,a):a),C.cloneElement(s,o)}return C.Children.count(s)>1?C.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var Xce=Symbol("radix.slottable");function Qce(t){return C.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===Xce}function Jce(t,e){const n={...e};for(const r in e){const s=t[r],i=e[r];/^on[A-Z]/.test(r)?s&&i?n[r]=(...o)=>{const l=i(...o);return s(...o),l}:s&&(n[r]=s):r==="style"?n[r]={...s,...i}:r==="className"&&(n[r]=[s,i].filter(Boolean).join(" "))}return{...t,...n}}function Zce(t){var r,s;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=(s=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:s.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var e_="Dialog",[HF]=ym(e_),[eue,Zi]=HF(e_),zF=t=>{const{__scopeDialog:e,children:n,open:r,defaultOpen:s,onOpenChange:i,modal:a=!0}=t,o=C.useRef(null),l=C.useRef(null),[c,u]=dj({prop:r,defaultProp:s??!1,onChange:i,caller:e_});return p.jsx(eue,{scope:e,triggerRef:o,contentRef:l,contentId:gb(),titleId:gb(),descriptionId:gb(),open:c,onOpenChange:u,onOpenToggle:C.useCallback(()=>u(d=>!d),[u]),modal:a,children:n})};zF.displayName=e_;var qF="DialogTrigger",tue=C.forwardRef((t,e)=>{const{__scopeDialog:n,...r}=t,s=Zi(qF,n),i=ps(e,s.triggerRef);return p.jsx(pr.button,{type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":gA(s.open),...r,ref:i,onClick:Un(t.onClick,s.onOpenToggle)})});tue.displayName=qF;var pA="DialogPortal",[nue,WF]=HF(pA,{forceMount:void 0}),YF=t=>{const{__scopeDialog:e,forceMount:n,children:r,container:s}=t,i=Zi(pA,e);return p.jsx(nue,{scope:e,forceMount:n,children:C.Children.map(r,a=>p.jsx(Ih,{present:n||i.open,children:p.jsx(n1,{asChild:!0,container:s,children:a})}))})};YF.displayName=pA;var $0="DialogOverlay",XF=C.forwardRef((t,e)=>{const n=WF($0,t.__scopeDialog),{forceMount:r=n.forceMount,...s}=t,i=Zi($0,t.__scopeDialog);return i.modal?p.jsx(Ih,{present:r||i.open,children:p.jsx(sue,{...s,ref:e})}):null});XF.displayName=$0;var rue=Wce("DialogOverlay.RemoveScroll"),sue=C.forwardRef((t,e)=>{const{__scopeDialog:n,...r}=t,s=Zi($0,n);return p.jsx(GF,{as:rue,allowPinchZoom:!0,shards:[s.contentRef],children:p.jsx(pr.div,{"data-state":gA(s.open),...r,ref:e,style:{pointerEvents:"auto",...r.style}})})}),iu="DialogContent",QF=C.forwardRef((t,e)=>{const n=WF(iu,t.__scopeDialog),{forceMount:r=n.forceMount,...s}=t,i=Zi(iu,t.__scopeDialog);return p.jsx(Ih,{present:r||i.open,children:i.modal?p.jsx(iue,{...s,ref:e}):p.jsx(aue,{...s,ref:e})})});QF.displayName=iu;var iue=C.forwardRef((t,e)=>{const n=Zi(iu,t.__scopeDialog),r=C.useRef(null),s=ps(e,n.contentRef,r);return C.useEffect(()=>{const i=r.current;if(i)return qce(i)},[]),p.jsx(JF,{...t,ref:s,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Un(t.onCloseAutoFocus,i=>{var a;i.preventDefault(),(a=n.triggerRef.current)==null||a.focus()}),onPointerDownOutside:Un(t.onPointerDownOutside,i=>{const a=i.detail.originalEvent,o=a.button===0&&a.ctrlKey===!0;(a.button===2||o)&&i.preventDefault()}),onFocusOutside:Un(t.onFocusOutside,i=>i.preventDefault())})}),aue=C.forwardRef((t,e)=>{const n=Zi(iu,t.__scopeDialog),r=C.useRef(!1),s=C.useRef(!1);return p.jsx(JF,{...t,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var a,o;(a=t.onCloseAutoFocus)==null||a.call(t,i),i.defaultPrevented||(r.current||(o=n.triggerRef.current)==null||o.focus(),i.preventDefault()),r.current=!1,s.current=!1},onInteractOutside:i=>{var l,c;(l=t.onInteractOutside)==null||l.call(t,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(s.current=!0));const a=i.target;((c=n.triggerRef.current)==null?void 0:c.contains(a))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&s.current&&i.preventDefault()}})}),JF=C.forwardRef((t,e)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:s,onCloseAutoFocus:i,...a}=t,o=Zi(iu,n),l=C.useRef(null),c=ps(e,l);return lce(),p.jsxs(p.Fragment,{children:[p.jsx(NF,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:s,onUnmountAutoFocus:i,children:p.jsx(wv,{role:"dialog",id:o.contentId,"aria-describedby":o.descriptionId,"aria-labelledby":o.titleId,"data-state":gA(o.open),...a,ref:c,onDismiss:()=>o.onOpenChange(!1)})}),p.jsxs(p.Fragment,{children:[p.jsx(oue,{titleId:o.titleId}),p.jsx(cue,{contentRef:l,descriptionId:o.descriptionId})]})]})}),mA="DialogTitle",ZF=C.forwardRef((t,e)=>{const{__scopeDialog:n,...r}=t,s=Zi(mA,n);return p.jsx(pr.h2,{id:s.titleId,...r,ref:e})});ZF.displayName=mA;var e5="DialogDescription",t5=C.forwardRef((t,e)=>{const{__scopeDialog:n,...r}=t,s=Zi(e5,n);return p.jsx(pr.p,{id:s.descriptionId,...r,ref:e})});t5.displayName=e5;var n5="DialogClose",r5=C.forwardRef((t,e)=>{const{__scopeDialog:n,...r}=t,s=Zi(n5,n);return p.jsx(pr.button,{type:"button",...r,ref:e,onClick:Un(t.onClick,()=>s.onOpenChange(!1))})});r5.displayName=n5;function gA(t){return t?"open":"closed"}var s5="DialogTitleWarning",[Lye,i5]=aH(s5,{contentName:iu,titleName:mA,docsSlug:"dialog"}),oue=({titleId:t})=>{const e=i5(s5),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 C.useEffect(()=>{t&&(document.getElementById(t)||console.error(n))},[n,t]),null},lue="DialogDescriptionWarning",cue=({contentRef:t,descriptionId:e})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${i5(lue).contentName}}.`;return C.useEffect(()=>{var i;const s=(i=t.current)==null?void 0:i.getAttribute("aria-describedby");e&&s&&(document.getElementById(e)||console.warn(r))},[r,t,e]),null},uue=zF,due=YF,a5=XF,o5=QF,l5=ZF,c5=t5,hue=r5;const fue=uue,pue=due,u5=C.forwardRef(({className:t,...e},n)=>p.jsx(a5,{ref:n,className:gs("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}));u5.displayName=a5.displayName;const d5=C.forwardRef(({className:t,children:e,...n},r)=>p.jsxs(pue,{children:[p.jsx(u5,{}),p.jsxs(o5,{ref:r,className:gs("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,p.jsxs(hue,{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:[p.jsx(Na,{className:"h-4 w-4"}),p.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));d5.displayName=o5.displayName;const h5=({className:t,...e})=>p.jsx("div",{className:gs("flex flex-col space-y-1.5 text-center sm:text-left",t),...e});h5.displayName="DialogHeader";const f5=C.forwardRef(({className:t,...e},n)=>p.jsx(l5,{ref:n,className:gs("text-lg font-semibold leading-none tracking-tight",t),...e}));f5.displayName=l5.displayName;const p5=C.forwardRef(({className:t,...e},n)=>p.jsx(c5,{ref:n,className:gs("text-sm text-muted-foreground",t),...e}));p5.displayName=c5.displayName;const mue=[{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."}],GP="nadiplay.playerNotice.dismissed.v1",jg="nadiplay.playerNotice.enabledCache.v1",KP="nadiplay.playerNotice.semantics",HP="opt-in-v2",gue=()=>{const[t,e]=C.useState(!1);C.useEffect(()=>{let s=!1;try{localStorage.getItem(KP)!==HP&&(localStorage.removeItem(jg),localStorage.setItem(KP,HP))}catch{}let i=null;try{const o=localStorage.getItem(jg);o==="0"?i=!1:o==="1"&&(i=!0)}catch{}const a=(()=>{try{return localStorage.getItem(GP)==="1"}catch{return!1}})();return i!==!0?(P0().then(o=>{if(s)return;const l=o.player_notice_enabled===!0;try{localStorage.setItem(jg,l?"1":"0")}catch{}l&&!a&&e(!0)}).catch(()=>{}),()=>{s=!0}):((async()=>{let o=!0;try{o=(await P0()).player_notice_enabled===!0;try{localStorage.setItem(jg,o?"1":"0")}catch{}}catch{}if(!s){if(!o){e(!1);return}a||e(!0)}})(),()=>{s=!0})},[]);const n=s=>{Cm()?ol.openPlayStore({package:s.packageName}).catch(()=>{window.open(s.playStoreUrl,"_blank","noopener,noreferrer")}):window.open(s.playStoreUrl,"_blank","noopener,noreferrer")},r=()=>{try{localStorage.setItem(GP,"1")}catch{}e(!1)};return p.jsx(fue,{open:t,onOpenChange:s=>!s&&r(),children:p.jsxs(d5,{"data-testid":"player-notice-dialog",className:"max-w-md border-primary/30 bg-background/95 backdrop-blur-xl",children:[p.jsxs(h5,{children:[p.jsx("div",{className:"mx-auto mb-2 flex h-12 w-12 items-center justify-center rounded-full bg-primary/15",children:p.jsx(o1,{className:"h-6 w-6 text-primary",strokeWidth:1.8})}),p.jsx(f5,{className:"text-center text-lg tracking-wide gold-text",children:"Install a video player"}),p.jsxs(p5,{className:"text-center text-sm text-muted-foreground",children:["You must download ",p.jsx("span",{className:"text-primary font-medium",children:"ExoPlayer"})," or"," ",p.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”."]})]}),p.jsx("div",{className:"mt-2 flex flex-col gap-2.5",children:mue.map(s=>p.jsxs("button",{"data-testid":`install-${s.key}`,onClick:()=>n(s),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:[p.jsx("img",{src:s.iconUrl,alt:s.label,className:"h-11 w-11 flex-none rounded-lg bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}),p.jsxs("div",{className:"min-w-0 flex-1",children:[p.jsxs("div",{className:"flex items-center gap-1.5 text-sm font-medium text-foreground",children:[p.jsx("span",{className:"truncate",children:s.label}),p.jsx(vo,{className:"h-3 w-3 text-muted-foreground opacity-0 transition group-hover:opacity-100"})]}),p.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:s.description})]}),p.jsx("div",{className:"text-[10px] font-medium uppercase tracking-widest text-primary/80",children:"Install"})]},s.key))}),p.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:[p.jsx(qi,{className:"h-4 w-4 text-primary"}),"I already have it"]})]})})},yue=()=>{const t=lr(),{t:e}=wr(),{continueAsGuest:n}=ys(),r=()=>{n(),t("/")},s=()=>{t("/login")};return p.jsxs(Ci,{focusKey:"welcome-page",className:"relative min-h-screen w-full overflow-hidden flex flex-col","data-testid":"welcome-page",children:[p.jsx("div",{className:"absolute inset-0 bg-cover bg-center",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),p.jsx("div",{className:"absolute inset-0 bg-background/55"}),p.jsx("div",{className:"relative z-20 flex items-center justify-end px-4 sm:px-8 pt-5",children:p.jsx(Pm,{align:"right"})}),p.jsxs("header",{className:"relative z-10 flex flex-col items-center pt-4 sm:pt-8",children:[p.jsx(gt.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")}),p.jsx(gt.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")})]}),p.jsx("main",{className:"relative z-10 flex-1 flex items-center justify-center px-4 py-6 sm:py-10",children:p.jsxs(Ci,{autoFocus:!0,focusKey:"welcome-cards",className:"flex flex-col md:flex-row gap-4 sm:gap-6 md:gap-10 w-full max-w-4xl",children:[p.jsxs(Kl,{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:[p.jsx("div",{className:"absolute inset-0 glass-card"}),p.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)"}}),p.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:[p.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:p.jsx(Rz,{className:"w-8 h-8 sm:w-10 sm:h-10 text-primary gold-glow",strokeWidth:1.4})}),p.jsx("h2",{className:"font-display text-xl sm:text-2xl tracking-[0.3em] gold-text",children:e("welcome.guest")}),p.jsx("p",{className:"text-muted-foreground text-xs sm:text-sm text-center max-w-xs tracking-wide",children:e("welcome.guestHint")}),p.jsxs("span",{className:"text-primary/80 text-[10px] sm:text-xs tracking-[0.4em] uppercase mt-1 sm:mt-2",children:[e("welcome.enter")," →"]})]})]}),p.jsxs(Kl,{focusKey:"login-card",onEnter:s,onClick:s,"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:[p.jsx("div",{className:"absolute inset-0 glass-card"}),p.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)"}}),p.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:[p.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:p.jsx(p9,{className:"w-8 h-8 sm:w-10 sm:h-10 text-primary gold-glow",strokeWidth:1.4})}),p.jsx("h2",{className:"font-display text-xl sm:text-2xl tracking-[0.3em] gold-text",children:e("welcome.login")}),p.jsx("p",{className:"text-muted-foreground text-xs sm:text-sm text-center max-w-xs tracking-wide",children:e("welcome.loginHint")}),p.jsxs("span",{className:"text-primary/80 text-[10px] sm:text-xs tracking-[0.4em] uppercase mt-1 sm:mt-2",children:[e("welcome.signIn")," →"]})]})]})]})}),p.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"),p.jsx("div",{className:"mt-2 tracking-normal normal-case",children:p.jsx(wi,{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"})})]}),p.jsx(gue,{})]})},zP=({focusKey:t,type:e,value:n,onChange:r,placeholder:s,icon:i,testId:a,autoFocusOnMount:o,autoComplete:l})=>{const{ref:c,focused:u,focusKey:d}=Kh({focusKey:t,onEnterPress:()=>{var f;su();const h=(f=c.current)==null?void 0:f.querySelector("input");h==null||h.focus()},onFocus:()=>Jv()});return C.useEffect(()=>{if(o&&d){const h=window.setTimeout(()=>ru(d),100);return()=>window.clearTimeout(h)}},[o,d]),p.jsxs("div",{ref:c,"data-focused":u||void 0,onMouseEnter:()=>{d&&ru(d)},onClick:()=>{var f;const h=(f=c.current)==null?void 0:f.querySelector("input");h==null||h.focus()},className:`flex items-center gap-3 glass-input rounded-xl px-4 py-3 transition-all duration-200 ${u?"ring-2 ring-primary/70 shadow-[0_0_28px_hsla(40,80%,55%,0.35)] border-primary/50":""}`,children:[p.jsx(i,{className:"w-5 h-5 text-muted-foreground shrink-0"}),p.jsx("input",{"data-testid":a,type:e,placeholder:s,value:n,onChange:h=>r(h.target.value),autoComplete:l,className:"flex-1 min-w-0 bg-transparent text-foreground placeholder:text-muted-foreground outline-none text-sm"})]})},vue=()=>{const t=lr(),{t:e}=wr(),{login:n}=ys(),[r,s]=C.useState(""),[i,a]=C.useState(""),[o,l]=C.useState(null),[c,u]=C.useState(!1),d=async h=>{var f;if((f=h==null?void 0:h.preventDefault)==null||f.call(h),!(!r||!i)){l(null),u(!0);try{(await n(r.trim(),i)).role==="admin"?t("/admin"):t("/select-profile")}catch(m){l(m instanceof Error?m.message:String(m))}finally{u(!1)}}};return p.jsxs(Ci,{focusKey:"login-page","data-testid":"login-page",className:"relative min-h-screen w-full overflow-hidden flex items-center justify-center px-4 py-10",children:[p.jsx("div",{className:"absolute inset-0 bg-cover bg-center bg-no-repeat",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),p.jsx("div",{className:"absolute inset-0 bg-background/60"}),p.jsx(wi,{focusKey:"login-back","data-testid":"login-back-btn",onEnter:()=>t("/welcome"),onClick:()=>t("/welcome"),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 outline-none",children:p.jsx(Ph,{className:"w-5 h-5 rtl:rotate-180"})}),p.jsx("div",{className:"absolute z-20 top-4 sm:top-6 end-4 sm:end-6",children:p.jsx(Pm,{align:"right"})}),p.jsxs(gt.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:[p.jsxs("div",{className:"flex flex-col items-center mb-6",children:[p.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:p.jsx(ri,{className:"w-7 h-7 sm:w-8 sm:h-8 text-primary gold-glow",strokeWidth:1.4})}),p.jsx("h1",{className:"font-display text-xl sm:text-2xl tracking-[0.3em] gold-text",children:"NADIPLAYER"}),p.jsx("p",{className:"text-muted-foreground text-[10px] sm:text-xs tracking-[0.25em] uppercase mt-2 text-center",children:e("login.subtitle")})]}),p.jsxs("div",{className:"space-y-3",children:[p.jsx(zP,{focusKey:"login-username",type:"text",value:r,onChange:s,placeholder:e("login.username"),icon:Ji,testId:"login-username-input",autoFocusOnMount:!0,autoComplete:"username"}),p.jsx(zP,{focusKey:"login-password",type:"password",value:i,onChange:a,placeholder:e("login.password"),icon:Cv,testId:"login-password-input",autoComplete:"current-password"})]}),o&&p.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}),p.jsxs(wi,{focusKey:"login-submit",type:"submit",disabled:c||!r||!i,"data-testid":"login-submit-btn",onEnter:()=>d(),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 outline-none",children:[c&&p.jsx(Pn,{className:"w-4 h-4 animate-spin"}),e(c?"login.submitting":"login.submit")]}),p.jsx("p",{className:"mt-5 text-center text-muted-foreground text-[10px] sm:text-[11px] tracking-wide",children:e("login.contactAdmin")})]})]})},yA=({portalUrl:t,mac:e,testId:n,compact:r=!1})=>{const[s,i]=C.useState("idle"),[a,o]=C.useState(""),l=s==="loading"||!t.trim()||!J3(e.trim()),c=async()=>{if(l)return;i("loading"),o("");const h=It.loading("Contacting Stalker portal…");try{const f=await zc.handshake(t.trim(),e.trim().toUpperCase());i("ok");const m=f.profile.expire_billing_date,g=f.profile.name||f.profile.mac||"device";o(m?`Active until ${m}`:"Connection OK"),It.success(`Stalker portal accepted ${g}`+(m?` · expires ${m}`:""),{id:h})}catch(f){i("fail");const m=(f==null?void 0:f.message)||"Connection failed";o(m),It.error(`Test failed: ${m}`,{id:h})}},u=s==="loading"?Pn:s==="ok"?qi:s==="fail"?Na:k9,d=s==="ok"?"text-emerald-400 border-emerald-500/40":s==="fail"?"text-destructive border-destructive/40":"text-primary hover:border-primary/40";return r?p.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:p.jsx(u,{className:`w-3.5 h-3.5 ${s==="loading"?"animate-spin":""}`})}):p.jsxs("div",{className:"space-y-1.5",children:[p.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:[p.jsx(u,{className:`w-3.5 h-3.5 ${s==="loading"?"animate-spin":""}`}),s==="loading"?"Testing…":s==="ok"?"Connected":s==="fail"?"Failed — try again":"Test Connection"]}),a&&p.jsx("p",{"data-testid":n?`${n}-detail`:void 0,className:`text-[10px] px-1 leading-relaxed ${s==="ok"?"text-emerald-400/80":"text-muted-foreground"}`,children:a})]})},_ue=()=>{const[t,e]=C.useState(null),[n,r]=C.useState(null),[s,i]=C.useState(!1),a=async()=>{i(!0);try{const[o,l]=await Promise.all([zee().catch(()=>null),qee().catch(()=>null)]);o&&e(o),l&&r(l)}finally{i(!1)}};return C.useEffect(()=>{a();const o=window.setInterval(a,3e4);return()=>window.clearInterval(o)},[]),p.jsxs("div",{className:"glass-card rounded-2xl p-4 sm:p-5","data-testid":"live-stats-card",children:[p.jsxs("div",{className:"flex items-center justify-between mb-3",children:[p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx(uk,{className:"w-4 h-4 text-primary"}),p.jsx("h3",{className:"text-foreground/90 text-sm tracking-wide",children:"Engagement"})]}),p.jsx("button",{onClick:a,disabled:s,"data-testid":"live-stats-refresh",className:"w-7 h-7 rounded-full glass flex items-center justify-center hover:border-primary/40 disabled:opacity-50",children:p.jsx(Oh,{className:`w-3.5 h-3.5 text-muted-foreground ${s?"animate-spin":""}`})})]}),p.jsxs("div",{className:"grid grid-cols-3 gap-2 sm:gap-3",children:[p.jsx(ux,{icon:uk,label:"Live now",value:(t==null?void 0:t.live_watchers)??0,accent:!0,testId:"stat-live"}),p.jsx(ux,{icon:hE,label:"Installs",value:(n==null?void 0:n.total_installs)??0,testId:"stat-installs"}),p.jsx(ux,{icon:nq,label:"Active 24h",value:(n==null?void 0:n.dau)??0,testId:"stat-dau"})]}),t&&t.top_channels.length>0&&p.jsxs("div",{className:"mt-3 pt-3 border-t border-border/40",children:[p.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground mb-1.5",children:"Top channels right now"}),p.jsx("ul",{className:"space-y-1",children:t.top_channels.slice(0,3).map(o=>p.jsxs("li",{className:"flex items-center justify-between text-[11px]",children:[p.jsx("span",{className:"truncate text-foreground/80",children:o.channel}),p.jsx("span",{className:"text-primary tabular-nums shrink-0 ml-2",children:o.viewers})]},o.channel))})]})]})},ux=({icon:t,label:e,value:n,accent:r,testId:s})=>p.jsxs("div",{className:`rounded-xl p-3 flex flex-col gap-0.5 ${r?"bg-primary/10 border border-primary/30":"glass"}`,"data-testid":s,children:[p.jsxs("div",{className:"flex items-center gap-1.5",children:[p.jsx(t,{className:`w-3 h-3 ${r?"text-primary":"text-muted-foreground"}`}),p.jsx("span",{className:`text-[10px] uppercase tracking-wider ${r?"text-primary":"text-muted-foreground"}`,children:e})]}),p.jsx("span",{className:`text-xl sm:text-2xl font-display tabular-nums ${r?"gold-text":"text-foreground"}`,children:n.toLocaleString()})]}),bue="https://nadiplayer-edit.preview.emergentagent.com",qc="1.3.0";async function m5(){const t=typeof window<"u"?window:null;if(!!!(t&&t.Capacitor&&t.Capacitor.isNativePlatform&&t.Capacitor.isNativePlatform()))return qc;try{const{App:n}=await km(async()=>{const{App:i}=await Promise.resolve().then(()=>Jge);return{App:i}},void 0),r=await n.getInfo();return(r&&r.version?String(r.version).trim():"")||qc}catch{return qc}}async function g5(){const t=await fetch(`${bue}/api/public/app-info`,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`HTTP ${t.status}`);return await t.json()}function bw(t,e){const n=a=>(a||"0").trim().split("-")[0].split(".").map(o=>parseInt(o,10)||0),r=n(t),s=n(e),i=Math.max(r.length,s.length);for(let a=0;a<i;a++){const o=r[a]??0,l=s[a]??0;if(o>l)return 1;if(o<l)return-1}return 0}function xue(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 Jo=({id:t,open:e,onToggle:n,icon:r,title:s,subtitle:i,badge:a,testId:o,children:l})=>p.jsxs("section",{className:"glass-card rounded-2xl overflow-hidden","data-testid":o??`acc-${t}`,children:[p.jsxs("button",{type:"button",onClick:n,"data-testid":`acc-${t}-btn`,className:`w-full flex items-center gap-3 px-5 sm:px-6 py-4 text-left transition-colors ${e?"bg-primary/8 border-b border-primary/20":"hover:bg-primary/5"}`,children:[p.jsx("span",{className:`flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border transition-colors ${e?"border-primary/50 bg-primary/15 text-primary":"border-border/60 bg-muted/30 text-muted-foreground"}`,children:p.jsx(r,{className:"w-5 h-5"})}),p.jsxs("span",{className:"flex-1 min-w-0",children:[p.jsx("span",{className:"block font-display text-base sm:text-lg tracking-[0.18em] gold-text uppercase",children:s}),i&&p.jsx("span",{className:"block text-[11px] sm:text-xs text-muted-foreground mt-0.5 truncate",children:i})]}),a&&p.jsx("span",{className:"shrink-0",children:a}),p.jsx(_m,{className:`w-5 h-5 text-muted-foreground transition-transform ${e?"rotate-180 text-primary":""}`})]}),p.jsx(Lo,{initial:!1,children:e&&p.jsx(gt.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.25,ease:"easeOut"},className:"overflow-hidden",children:p.jsx("div",{className:"p-5 sm:p-6",children:l})},"body")})]}),Sue=({latest:t})=>{const[e,n]=C.useState(qc);C.useEffect(()=>{let i=!1;return m5().then(a=>{i||n(a)}),()=>{i=!0}},[]);const s=bw(e,t||e)>=0;return p.jsxs("div",{className:`mb-3 flex flex-wrap items-center gap-x-3 gap-y-1 rounded-xl border px-3 py-2 text-[11px] ${s?"border-emerald-500/30 bg-emerald-500/5 text-emerald-300":"border-amber-500/30 bg-amber-500/5 text-amber-300"}`,"data-testid":"installed-version-banner",children:[p.jsx("span",{className:"font-medium tracking-[0.18em] uppercase",children:"This device"}),p.jsxs("span",{className:"opacity-80",children:["v",p.jsx("span",{"data-testid":"installed-version-value",children:e})]}),p.jsx("span",{className:"opacity-50",children:"→"}),p.jsxs("span",{className:"opacity-80",children:["target v",p.jsx("span",{"data-testid":"latest-version-value",children:t||"—"})]}),p.jsx("span",{className:"sm:ml-auto",children:s?"✓ up-to-date — no popup":"popup will appear"})]})},Eue=()=>{const t=lr(),{t:e}=wr(),{user:n,logout:r}=ys(),[s,i]=C.useState([]),[a,o]=C.useState(null),[l,c]=C.useState(!0),[u,d]=C.useState(null),[h,f]=C.useState("update"),[m,g]=C.useState(""),[y,v]=C.useState(""),[_,S]=C.useState(30),[E,L]=C.useState("shared"),[U,P]=C.useState(""),[I,k]=C.useState(""),[R,M]=C.useState(""),[G,Y]=C.useState(!1),q=ne=>{d(ne),window.setTimeout(()=>d(null),2400)};C.useEffect(()=>{if(!n||n.role!=="admin"){t("/welcome");return}X()},[n]);const X=async()=>{c(!0);try{const[ne,H]=await Promise.all([E3(),Vee()]);i(ne),o(H)}catch(ne){q(ne instanceof Error?ne.message:e("admin.loadFailed"))}finally{c(!1)}},Z=async ne=>{if(ne.preventDefault(),!(!m||!y)){Y(!0);try{await Fee({username:m.trim(),password:y,days:_,xtream_mode:E,xtream_server:U||void 0,xtream_username:I||void 0,xtream_password:R||void 0}),g(""),v(""),S(30),L("shared"),P(""),k(""),M(""),q(e("admin.userCreated")),await X()}catch(H){q(H instanceof Error?H.message:e("admin.opFailed"))}finally{Y(!1)}}},oe=()=>{r(),t("/welcome")};return p.jsxs("div",{"data-testid":"admin-page",className:"relative min-h-screen w-full overflow-hidden",children:[p.jsx("div",{className:"absolute inset-0 bg-cover bg-center",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),p.jsx("div",{className:"absolute inset-0 bg-background/70"}),p.jsxs("div",{className:"relative z-10 min-h-screen flex flex-col",children:[p.jsxs("header",{className:"flex flex-wrap items-center justify-between px-4 sm:px-6 md:px-10 pt-6 gap-3",children:[p.jsxs("div",{className:"flex items-center gap-3",children:[p.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:p.jsx(ri,{className:"w-5 h-5 text-primary gold-glow"})}),p.jsxs("div",{children:[p.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")}),p.jsx("p",{className:"text-muted-foreground text-[9px] sm:text-[10px] tracking-[0.3em] uppercase",children:e("admin.subtitle")})]})]}),p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx(Pm,{align:"right"}),p.jsxs("button",{onClick:()=>t("/admin/broadcast"),"data-testid":"admin-broadcast-btn",className:"hidden sm:flex items-center gap-2 px-3 py-2 rounded-full glass text-muted-foreground hover:text-primary hover:border-primary/40 transition-colors text-xs",title:"Broadcast notification",children:[p.jsx(g0,{className:"w-4 h-4"}),p.jsx("span",{className:"hidden md:inline",children:"Broadcast"})]}),p.jsx("button",{onClick:X,"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:p.jsx(D9,{className:`w-5 h-5 ${l?"animate-spin":""}`})}),p.jsxs("button",{onClick:oe,"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:[p.jsx(Nj,{className:"w-4 h-4"})," ",p.jsx("span",{className:"hidden sm:inline",children:e("admin.logout")})]})]})]}),u&&p.jsx(gt.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}),p.jsxs("main",{className:"flex-1 px-3 sm:px-4 md:px-10 py-6 sm:py-8 space-y-4 sm:space-y-5 max-w-7xl mx-auto w-full",children:[p.jsx(_ue,{}),p.jsx(Tue,{settings:a,openSection:h,setOpenSection:f,onSaved:ne=>{o(ne),q(e("admin.settingsSaved"))}}),p.jsx(Jo,{id:"create",open:h==="create",onToggle:()=>f(h==="create"?null:"create"),icon:lq,title:e("admin.createHeading"),subtitle:"Add a new subscriber account",testId:"admin-section-create",children:p.jsxs("form",{onSubmit:Z,className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3",children:[p.jsx(un,{label:e("admin.usernameLabel"),value:m,onChange:g,testId:"nu-username",required:!0}),p.jsx(un,{label:e("admin.passwordLabel"),value:y,onChange:v,type:"text",testId:"nu-password",required:!0}),p.jsx(un,{label:e("admin.daysLabel"),value:String(_),onChange:ne=>S(Math.max(1,parseInt(ne||"0")||1)),type:"number",testId:"nu-days"}),p.jsxs("div",{children:[p.jsx("label",{className:"text-[11px] text-muted-foreground tracking-[0.2em] uppercase block mb-1",children:e("admin.xtreamMode")}),p.jsxs("select",{value:E,onChange:ne=>L(ne.target.value),"data-testid":"nu-mode",className:"w-full glass-input rounded-lg px-3 py-2 text-sm text-foreground outline-none",children:[p.jsx("option",{value:"shared",children:e("admin.modeShared")}),p.jsx("option",{value:"own",children:e("admin.modeOwn")})]})]}),E==="own"&&p.jsxs(p.Fragment,{children:[p.jsx(un,{label:e("admin.serverUrl"),value:U,onChange:P,testId:"nu-server"}),p.jsx(un,{label:e("admin.xtreamUsername"),value:I,onChange:k,testId:"nu-xuser"}),p.jsx(un,{label:e("admin.xtreamPassword"),value:R,onChange:M,testId:"nu-xpass"})]}),p.jsx("div",{className:"md:col-span-2 lg:col-span-4 flex justify-end",children:p.jsxs("button",{type:"submit",disabled:G,"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:[G?p.jsx(Pn,{className:"w-4 h-4 animate-spin"}):p.jsx(_o,{className:"w-4 h-4"}),e(G?"admin.creating":"admin.createUser")]})})]})}),p.jsx(Jo,{id:"subscribers",open:h==="subscribers",onToggle:()=>f(h==="subscribers"?null:"subscribers"),icon:Bj,title:e("admin.subscribersHeading",{count:s.length}),subtitle:`${s.length} active subscribers`,testId:"admin-section-subscribers",badge:p.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-primary/15 text-primary tracking-widest",children:s.length}),children:s.length===0?p.jsx("p",{className:"text-muted-foreground text-sm",children:e("admin.noSubscribers")}):p.jsx("div",{className:"space-y-3",children:s.map(ne=>p.jsx(Aue,{user:ne,onChanged:X,onToast:q},ne.id))})})]})]})]})},wue=({idx:t,content:e,onChange:n})=>{const[r,s]=C.useState(""),[i,a]=C.useState(!1),o=async d=>{if(d){a(!0);try{const h=await d.text();n(h),s(d.name)}finally{a(!1)}}},l=()=>{n(""),s("")},c=!!(e&&e.trim().length),u=c?e.split(/\r?\n/).filter(Boolean).length:0;return p.jsxs("div",{children:[p.jsx("label",{className:"text-[11px] text-muted-foreground tracking-[0.2em] uppercase block mb-1",children:"M3U File (optional)"}),p.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[p.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:[i?p.jsx(Pn,{className:"w-3.5 h-3.5 animate-spin"}):p.jsx(u1,{className:"w-3.5 h-3.5"}),p.jsx("span",{children:i?"Reading…":"Upload .m3u"}),p.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&&p.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0 text-xs text-muted-foreground",children:[p.jsx(l1,{className:"w-3.5 h-3.5 text-primary shrink-0"}),p.jsxs("span",{className:"truncate",children:[r||"uploaded file"," · ",u," lines"]}),p.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:p.jsx(Na,{className:"w-3.5 h-3.5"})})]})]}),p.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."})]})},un=({label:t,value:e,onChange:n,type:r="text",testId:s,required:i})=>p.jsxs("div",{children:[p.jsx("label",{className:"text-[11px] text-muted-foreground tracking-[0.2em] uppercase block mb-1",children:t}),p.jsx("input",{type:r,value:e,onChange:a=>n(a.target.value),"data-testid":s,required:i,className:"w-full glass-input rounded-lg px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground outline-none"})]}),Tue=({settings:t,onSaved:e,openSection:n,setOpenSection:r})=>{const{t:s}=wr(),[i,a]=C.useState((t==null?void 0:t.whatsapp_number)??""),[o,l]=C.useState((t==null?void 0:t.shared_profiles)??[]),[c,u]=C.useState((t==null?void 0:t.external_player_enabled)??!1),[d,h]=C.useState((t==null?void 0:t.player_notice_enabled)??!1),[f,m]=C.useState((t==null?void 0:t.inline_preview_enabled)??!0),[g,y]=C.useState((t==null?void 0:t.update_enabled)??!1),[v,_]=C.useState((t==null?void 0:t.app_version)??"1.0.0"),[S,E]=C.useState((t==null?void 0:t.min_supported_version)??"1.0.0"),[L,U]=C.useState((t==null?void 0:t.update_apk_url)??""),[P,I]=C.useState((t==null?void 0:t.update_play_url)??""),[k,R]=C.useState((t==null?void 0:t.update_changelog)??""),[M,G]=C.useState(typeof(t==null?void 0:t.popup_delay_seconds)=="number"?t.popup_delay_seconds:10),[Y,q]=C.useState((t==null?void 0:t.whatsapp_message)??""),[X,Z]=C.useState((t==null?void 0:t.support_email)??""),[oe,ne]=C.useState((t==null?void 0:t.creator_name)??""),[H,K]=C.useState((t==null?void 0:t.creator_role)??""),[J,Q]=C.useState((t==null?void 0:t.creator_avatar_url)??""),[ve,Te]=C.useState((t==null?void 0:t.creator_bio)??""),[Ne,Ke]=C.useState((t==null?void 0:t.privacy_policy_text)??""),[be,Pe]=C.useState((t==null?void 0:t.ads_enabled)??!1),[Ae,we]=C.useState((t==null?void 0:t.ads_testing_mode)??!0),[Ue,Oe]=C.useState((t==null?void 0:t.ads_app_id)??""),[Dt,en]=C.useState((t==null?void 0:t.ads_banner_id)??""),[wn,it]=C.useState((t==null?void 0:t.ads_interstitial_id)??""),[nn,mn]=C.useState(typeof(t==null?void 0:t.ads_interstitial_every)=="number"?t.ads_interstitial_every:5),[On,Cn]=C.useState(!1);C.useEffect(()=>{a((t==null?void 0:t.whatsapp_number)??""),l((t==null?void 0:t.shared_profiles)??[]),u((t==null?void 0:t.external_player_enabled)??!1),h((t==null?void 0:t.player_notice_enabled)??!1),m((t==null?void 0:t.inline_preview_enabled)??!0),y((t==null?void 0:t.update_enabled)??!1),_((t==null?void 0:t.app_version)??"1.0.0"),E((t==null?void 0:t.min_supported_version)??"1.0.0"),U((t==null?void 0:t.update_apk_url)??""),I((t==null?void 0:t.update_play_url)??""),R((t==null?void 0:t.update_changelog)??""),G(typeof(t==null?void 0:t.popup_delay_seconds)=="number"?t.popup_delay_seconds:10),q((t==null?void 0:t.whatsapp_message)??""),Z((t==null?void 0:t.support_email)??""),ne((t==null?void 0:t.creator_name)??""),K((t==null?void 0:t.creator_role)??""),Q((t==null?void 0:t.creator_avatar_url)??""),Te((t==null?void 0:t.creator_bio)??""),Ke((t==null?void 0:t.privacy_policy_text)??""),Pe((t==null?void 0:t.ads_enabled)??!1),we((t==null?void 0:t.ads_testing_mode)??!0),Oe((t==null?void 0:t.ads_app_id)??""),en((t==null?void 0:t.ads_banner_id)??""),it((t==null?void 0:t.ads_interstitial_id)??""),mn(typeof(t==null?void 0:t.ads_interstitial_every)=="number"?t.ads_interstitial_every:5)},[t]);const ln=lt=>{l(ht=>[...ht,{id:`tmp-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,name:lt==="xtream"?"New Xtream":lt==="stalker"?"New Stalker":"New M3U",kind:lt,server:"",username:"",password:"",m3u_url:"",m3u_content:"",portal_url:"",mac_address:""}])},Nn=(lt,ht)=>l(Vt=>Vt.map((Dr,vs)=>vs===lt?{...Dr,...ht}:Dr)),cr=lt=>l(ht=>ht.filter((Vt,Dr)=>Dr!==lt)),Ds=async()=>{Cn(!0);try{const lt=await Gee({whatsapp_number:i,shared_profiles:o,external_player_enabled:c,player_notice_enabled:d,inline_preview_enabled:f,update_enabled:g,app_version:v,min_supported_version:S,update_apk_url:L,update_play_url:P,update_changelog:k,popup_delay_seconds:M,whatsapp_message:Y,support_email:X,creator_name:oe,creator_role:H,creator_avatar_url:J,creator_bio:ve,privacy_policy_text:Ne,ads_enabled:be,ads_testing_mode:Ae,ads_app_id:Ue,ads_banner_id:Dt,ads_interstitial_id:wn,ads_interstitial_every:nn});e(lt)}catch(lt){alert(lt instanceof Error?lt.message:"Save failed")}finally{Cn(!1)}};return p.jsxs(p.Fragment,{children:[p.jsx(Jo,{id:"playback",open:n==="playback",onToggle:()=>r(n==="playback"?null:"playback"),icon:wz,title:"Playback & Popups",subtitle:"WhatsApp, external player, install-video-player popup",testId:"admin-section-playback",children:p.jsxs("div",{className:"space-y-4",children:[p.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:p.jsx(un,{label:s("admin.whatsapp"),value:i,onChange:a,testId:"set-whatsapp"})}),p.jsx("div",{className:"glass rounded-xl p-4 border border-border/60",children:p.jsxs("label",{className:"flex items-start gap-3 cursor-pointer select-none",children:[p.jsx("input",{type:"checkbox",checked:c,onChange:lt=>u(lt.target.checked),"data-testid":"toggle-external-player",className:"mt-1 w-4 h-4 accent-primary cursor-pointer"}),p.jsxs("div",{className:"flex-1 min-w-0",children:[p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx("span",{className:"text-sm font-medium text-foreground",children:"External Player"}),p.jsx("span",{className:`text-[10px] px-2 py-0.5 rounded-full ${c?"bg-amber-500/20 text-amber-400":"bg-primary/20 text-primary"}`,children:c?"ON":"OFF"})]}),p.jsx("p",{className:"text-xs text-muted-foreground mt-1 leading-relaxed",children:c?"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."})]})]})}),p.jsx("div",{className:"glass rounded-xl p-4 border border-border/60",children:p.jsxs("label",{className:"flex items-start gap-3 cursor-pointer select-none",children:[p.jsx("input",{type:"checkbox",checked:d,onChange:lt=>h(lt.target.checked),"data-testid":"toggle-player-notice",className:"mt-1 w-4 h-4 accent-primary cursor-pointer"}),p.jsxs("div",{className:"flex-1 min-w-0",children:[p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx("span",{className:"text-sm font-medium text-foreground",children:'"Install Video Player" Popup'}),p.jsx("span",{className:`text-[10px] px-2 py-0.5 rounded-full ${d?"bg-primary/20 text-primary":"bg-muted/40 text-muted-foreground"}`,children:d?"ENABLED":"DISABLED"})]}),p.jsx("p",{className:"text-xs text-muted-foreground mt-1 leading-relaxed",children:d?'Users see the "Install ExoPlayer / VLC" popup once on first launch (until they tap "I already have it").':"Popup is hidden for everyone. Use this when most users already have a player installed."})]})]})}),p.jsx("div",{className:"glass rounded-xl p-4 border border-border/60",children:p.jsxs("label",{className:"flex items-start gap-3 cursor-pointer select-none",children:[p.jsx("input",{type:"checkbox",checked:f,onChange:lt=>m(lt.target.checked),"data-testid":"toggle-inline-preview",className:"mt-1 w-4 h-4 accent-primary cursor-pointer"}),p.jsxs("div",{className:"flex-1 min-w-0",children:[p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx("span",{className:"text-sm font-medium text-foreground",children:"Inline Preview Player (Live TV)"}),p.jsx("span",{className:`text-[10px] px-2 py-0.5 rounded-full ${f?"bg-primary/20 text-primary":"bg-muted/40 text-muted-foreground"}`,"data-testid":"inline-preview-status",children:f?"ENABLED":"DISABLED"})]}),p.jsx("p",{className:"text-xs text-muted-foreground mt-1 leading-relaxed",children:f?"On Live TV (TV / browser only), tapping a channel shows a small preview player with gold icon controls (prev / play-pause / next / fullscreen). Double-tap the video — or tap ⛶ — to go fullscreen. On Android / iOS native apps this setting is ignored — playback always opens directly in the system video player.":"Channels open directly in the player. Small preview on Live TV is disabled for TV / browser users."})]})]})})]})}),p.jsxs(Jo,{id:"update",open:n==="update",onToggle:()=>r(n==="update"?null:"update"),icon:X9,title:"In-App Update",subtitle:"Version, force-update threshold, popup delay timer, APK & Play Store URLs",testId:"admin-update-section",badge:p.jsx("span",{className:`text-[10px] px-2 py-0.5 rounded-full ${g?"bg-primary/20 text-primary":"bg-muted/40 text-muted-foreground"}`,children:g?"ENABLED":"DISABLED"}),children:[p.jsx("div",{className:"flex items-center justify-end mb-3",children:p.jsxs("label",{className:"flex items-center gap-2 cursor-pointer select-none",children:[p.jsx("input",{type:"checkbox",checked:g,onChange:lt=>y(lt.target.checked),"data-testid":"set-update-enabled",className:"w-4 h-4 accent-primary cursor-pointer"}),p.jsx("span",{className:"text-xs text-muted-foreground",children:"Enable update popup for users"})]})}),p.jsxs("p",{className:"text-[11px] text-muted-foreground leading-relaxed mb-3",children:["When enabled, every user (logged in or guest) sees a popup if their installed version is older than"," ",p.jsx("code",{className:"text-primary",children:"Latest version"}),". If their version is older than"," ",p.jsx("code",{className:"text-primary",children:"Min supported version"}),", the popup BLOCKS the app entirely until they update."]}),p.jsx(Sue,{latest:v}),p.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[p.jsx(un,{label:"Latest version (e.g. 1.2.0)",value:v,onChange:_,testId:"set-app-version"}),p.jsx(un,{label:"Min supported version (force-update threshold)",value:S,onChange:E,testId:"set-min-version"}),p.jsx(un,{label:"Direct APK download URL",value:L,onChange:U,testId:"set-apk-url"}),p.jsx(un,{label:"Google Play Store URL",value:P,onChange:I,testId:"set-play-url"}),p.jsxs("div",{className:"md:col-span-2 rounded-xl border border-primary/30 bg-primary/5 p-3",children:[p.jsx("label",{className:"text-[11px] text-primary tracking-[0.2em] uppercase block mb-1",children:"Popup delay (seconds) — wait this long before showing the popup"}),p.jsxs("div",{className:"flex items-center gap-3",children:[p.jsx("input",{type:"range",min:0,max:60,step:1,value:Math.min(60,M),onChange:lt=>G(parseInt(lt.target.value,10)||0),"data-testid":"set-popup-delay-range",className:"flex-1 accent-primary"}),p.jsx("input",{type:"number",min:0,max:600,step:1,value:M,onChange:lt=>G(Math.max(0,Math.min(600,parseInt(lt.target.value||"0",10)||0))),"data-testid":"set-popup-delay",className:"w-20 glass-input rounded-lg px-3 py-2 text-sm text-foreground outline-none text-center"}),p.jsx("span",{className:"text-xs text-muted-foreground tracking-[0.2em] uppercase",children:"s"})]}),p.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1.5 leading-relaxed",children:["Increase to ",p.jsx("strong",{children:"10–14s"})," (or more) so admins can log in before a forced popup appears."]})]})]}),p.jsxs("div",{className:"mt-3",children:[p.jsx("label",{className:"text-[11px] text-muted-foreground tracking-[0.2em] uppercase block mb-1",children:"What's new (changelog)"}),p.jsx("textarea",{value:k,onChange:lt=>R(lt.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"})]})]}),p.jsx(Jo,{id:"creator",open:n==="creator",onToggle:()=>r(n==="creator"?null:"creator"),icon:Hz,title:"Creator Info",subtitle:"Shown on every user's Account page under Help & About",testId:"admin-creator-section",children:p.jsxs("div",{className:"space-y-3",children:[p.jsx("p",{className:"text-[11px] text-muted-foreground",children:`Shown on every user's Account page under "Help & About".`}),p.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[p.jsx(un,{label:"Creator name",value:oe,onChange:ne,testId:"set-creator-name"}),p.jsx(un,{label:"Role / title (e.g. Developer)",value:H,onChange:K,testId:"set-creator-role"}),p.jsx("div",{className:"md:col-span-2",children:p.jsx(un,{label:"Avatar URL (https://…)",value:J,onChange:Q,testId:"set-creator-avatar"})})]}),p.jsxs("div",{children:[p.jsx("label",{className:"text-[11px] text-muted-foreground tracking-[0.2em] uppercase block mb-1",children:"Short bio"}),p.jsx("textarea",{value:ve,onChange:lt=>Te(lt.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"})]})]})}),p.jsx(Jo,{id:"support",open:n==="support",onToggle:()=>r(n==="support"?null:"support"),icon:Ul,title:"Support & Privacy",subtitle:"Email, WhatsApp message, privacy policy text",testId:"admin-support-section",children:p.jsxs("div",{className:"space-y-3",children:[p.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[p.jsx(un,{label:"Support email",value:X,onChange:Z,testId:"set-support-email"}),p.jsx(un,{label:"WhatsApp prefilled message",value:Y,onChange:q,testId:"set-wa-message"})]}),p.jsxs("div",{children:[p.jsx("label",{className:"text-[11px] text-muted-foreground tracking-[0.2em] uppercase block mb-1",children:"Privacy policy text"}),p.jsx("textarea",{value:Ne,onChange:lt=>Ke(lt.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"}),p.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Plain text or markdown — shown verbatim on the /privacy page."})]})]})}),p.jsx(Jo,{id:"ads",open:n==="ads",onToggle:()=>r(n==="ads"?null:"ads"),icon:g0,title:"Ads Settings",subtitle:"Google AdMob — banner + interstitial on player screens",testId:"admin-ads-section",badge:p.jsx("span",{className:`text-[10px] px-2 py-0.5 rounded-full tracking-widest ${be?Ae?"bg-amber-500/20 text-amber-400":"bg-green-500/20 text-green-400":"bg-muted/40 text-muted-foreground"}`,children:be?Ae?"TEST MODE":"LIVE":"OFF"}),children:p.jsxs("div",{className:"space-y-3",children:[p.jsx("div",{className:"glass rounded-xl p-4 border border-border/60",children:p.jsxs("label",{className:"flex items-start gap-3 cursor-pointer select-none",children:[p.jsx("input",{type:"checkbox",checked:be,onChange:lt=>Pe(lt.target.checked),"data-testid":"toggle-ads-enabled",className:"mt-1 w-4 h-4 accent-primary cursor-pointer"}),p.jsxs("div",{className:"flex-1 min-w-0",children:[p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx("span",{className:"text-sm font-medium text-foreground",children:"Enable Ads"}),p.jsx("span",{className:`text-[10px] px-2 py-0.5 rounded-full ${be?"bg-amber-500/20 text-amber-400":"bg-muted/40 text-muted-foreground"}`,children:be?"ON":"OFF"})]}),p.jsx("p",{className:"text-xs text-muted-foreground mt-1 leading-relaxed",children:"When ON, a banner is shown at the bottom of Live TV / Movie player screens, and an interstitial fires every N channel switches. When OFF, the app mounts no ad views at all."})]})]})}),p.jsx("div",{className:"glass rounded-xl p-4 border border-border/60",children:p.jsxs("label",{className:"flex items-start gap-3 cursor-pointer select-none",children:[p.jsx("input",{type:"checkbox",checked:Ae,onChange:lt=>we(lt.target.checked),"data-testid":"toggle-ads-testing",className:"mt-1 w-4 h-4 accent-primary cursor-pointer"}),p.jsxs("div",{className:"flex-1 min-w-0",children:[p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx("span",{className:"text-sm font-medium text-foreground",children:"Testing Mode (safe)"}),p.jsx("span",{className:`text-[10px] px-2 py-0.5 rounded-full ${Ae?"bg-green-500/20 text-green-400":"bg-red-500/20 text-red-400"}`,children:Ae?"TEST ADS":"LIVE ADS"})]}),p.jsx("p",{className:"text-xs text-muted-foreground mt-1 leading-relaxed",children:Ae?"Devices see Google's universal TEST banners/interstitials. Your AdMob account is NOT billed. Safe for development.":"⚠️ Devices see YOUR real ads. Invalid clicks can get your AdMob account flagged — only flip this once placements are verified."})]})]})}),p.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[p.jsx(un,{label:"AdMob App ID",value:Ue,onChange:Oe,testId:"set-ads-app-id"}),p.jsx(un,{label:"Banner Ad Unit ID",value:Dt,onChange:en,testId:"set-ads-banner-id"}),p.jsx(un,{label:"Interstitial Ad Unit ID",value:wn,onChange:it,testId:"set-ads-interstitial-id"})]}),p.jsxs("div",{children:[p.jsx("label",{className:"text-[11px] text-muted-foreground tracking-[0.2em] uppercase block mb-1",children:"Interstitial every N channel switches"}),p.jsxs("div",{className:"flex items-center gap-3",children:[p.jsx("input",{type:"number",min:0,max:100,value:nn,onChange:lt=>mn(Math.max(0,Math.min(100,parseInt(lt.target.value)||0))),"data-testid":"set-ads-interstitial-every",className:"w-24 glass-input rounded-lg px-3 py-2 text-sm text-foreground outline-none"}),p.jsx("span",{className:"text-xs text-muted-foreground",children:"0 = never · 3–10 recommended · default 5"})]})]}),p.jsx("div",{className:"glass rounded-xl p-3 border border-primary/20 bg-primary/5",children:p.jsxs("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:[p.jsx("strong",{className:"text-primary",children:"Note:"})," The App ID must also be baked into AndroidManifest.xml at build time (already done for v1.2.5). If you change the App ID later, you'll need to rebuild the APK. Banner + interstitial IDs are live-swappable from this panel — no rebuild needed."]})})]})}),p.jsx(Jo,{id:"profiles",open:n==="profiles",onToggle:()=>r(n==="profiles"?null:"profiles"),icon:r9,title:"Shared Profiles",subtitle:"Xtream / M3U / Stalker profiles available to logged-in users",testId:"admin-profiles-section",badge:p.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-primary/15 text-primary tracking-widest",children:o.length}),children:p.jsxs("div",{children:[p.jsxs("div",{className:"flex items-center justify-between mb-3",children:[p.jsx("span",{className:"text-xs text-muted-foreground",children:"Add a profile and save settings to make it available"}),p.jsxs("div",{className:"flex gap-2",children:[p.jsxs("button",{onClick:()=>ln("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:[p.jsx(_o,{className:"w-3.5 h-3.5"})," Xtream"]}),p.jsxs("button",{onClick:()=>ln("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:[p.jsx(_o,{className:"w-3.5 h-3.5"})," M3U"]}),p.jsxs("button",{onClick:()=>ln("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:[p.jsx(_o,{className:"w-3.5 h-3.5"})," Stalker"]})]})]}),o.length===0?p.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."}):p.jsx("div",{className:"space-y-3",children:o.map((lt,ht)=>p.jsxs("div",{"data-testid":`profile-row-${ht}`,className:"glass rounded-xl p-3 border border-border/60",children:[p.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[p.jsx("span",{className:"text-[10px] uppercase tracking-widest text-primary/80 bg-primary/10 px-2 py-0.5 rounded",children:lt.kind==="m3u"?"M3U":lt.kind==="stalker"?"Stalker":"Xtream"}),p.jsx("button",{onClick:()=>cr(ht),"data-testid":`remove-profile-${ht}`,className:"ml-auto text-muted-foreground hover:text-destructive transition-colors","aria-label":"Remove",children:p.jsx(xm,{className:"w-4 h-4"})})]}),p.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:[p.jsx(un,{label:"Profile Name",value:lt.name,onChange:Vt=>Nn(ht,{name:Vt}),testId:`profile-name-${ht}`}),lt.kind==="xtream"?p.jsxs(p.Fragment,{children:[p.jsx(un,{label:"Server URL",value:lt.server??"",onChange:Vt=>Nn(ht,{server:Vt}),testId:`profile-server-${ht}`}),p.jsx(un,{label:"Username",value:lt.username??"",onChange:Vt=>Nn(ht,{username:Vt}),testId:`profile-user-${ht}`}),p.jsx(un,{label:"Password",value:lt.password??"",onChange:Vt=>Nn(ht,{password:Vt}),testId:`profile-pass-${ht}`})]}):lt.kind==="stalker"?p.jsxs(p.Fragment,{children:[p.jsx(un,{label:"Portal URL",value:lt.portal_url??"",onChange:Vt=>Nn(ht,{portal_url:Vt}),testId:`profile-portal-${ht}`}),p.jsx(un,{label:"MAC Address (00:1A:79:XX:XX:XX)",value:lt.mac_address??"",onChange:Vt=>{var Dr;return Nn(ht,{mac_address:((Dr=Vt.replace(/[^0-9A-Fa-f]/g,"").toUpperCase().slice(0,12).match(/.{1,2}/g))==null?void 0:Dr.join(":"))??""})},testId:`profile-mac-${ht}`}),p.jsx("div",{className:"md:col-span-2",children:p.jsx(yA,{portalUrl:lt.portal_url??"",mac:lt.mac_address??"",testId:`profile-stalker-test-${ht}`})})]}):p.jsxs("div",{className:"md:col-span-2 space-y-2",children:[p.jsx(un,{label:"M3U URL",value:lt.m3u_url??"",onChange:Vt=>Nn(ht,{m3u_url:Vt}),testId:`profile-m3u-${ht}`}),p.jsx(wue,{idx:ht,content:lt.m3u_content??"",onChange:Vt=>Nn(ht,{m3u_content:Vt})})]})]})]},lt.id||ht))})]})}),p.jsx("div",{className:"flex justify-end pt-2",children:p.jsxs("button",{onClick:Ds,disabled:On,"data-testid":"set-save",className:"flex items-center gap-2 px-6 py-3 rounded-2xl bg-primary hover:brightness-110 text-primary-foreground font-semibold text-sm transition-all disabled:opacity-60 shadow-[0_8px_30px_hsla(40,80%,55%,0.35)]",children:[On?p.jsx(Pn,{className:"w-4 h-4 animate-spin"}):p.jsx(M9,{className:"w-4 h-4"}),s(On?"common.saving":"admin.saveSettings")]})})]})},Aue=({user:t,onChanged:e,onToast:n})=>{const{t:r}=wr(),[s,i]=C.useState(!1),[a,o]=C.useState(""),[l,c]=C.useState(t.xtream_mode||"shared"),[u,d]=C.useState(t.xtream_server||""),[h,f]=C.useState(t.xtream_username||""),[m,g]=C.useState(t.xtream_password||""),y=async L=>{i(!0);try{await Gb(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{i(!1)}},v=async()=>{if(a){i(!0);try{await Gb(t.id,{password:a}),n(r("admin.passwordUpdated")),o(""),e()}catch(L){n(L instanceof Error?L.message:r("admin.opFailed"))}finally{i(!1)}}},_=async()=>{i(!0);try{await Gb(t.id,{xtream_mode:l,xtream_server:u,xtream_username:h,xtream_password:m}),n(r("admin.xtreamSaved")),e()}catch(L){n(L instanceof Error?L.message:r("admin.opFailed"))}finally{i(!1)}},S=async()=>{if(window.confirm(r("admin.confirmDeleteUser",{username:t.username}))){i(!0);try{await $ee(t.id),n(r("admin.userDeleted")),e()}catch(L){n(L instanceof Error?L.message:r("admin.opFailed"))}finally{i(!1)}}},E=t.is_expired?"text-destructive":(t.days_remaining??0)<=3?"text-amber-400":"text-primary";return p.jsxs("div",{className:"rounded-xl border border-border/40 glass p-4",children:[p.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-3",children:[p.jsxs("div",{className:"flex items-center gap-4",children:[p.jsx("div",{className:"w-10 h-10 rounded-full glass flex items-center justify-center",children:p.jsx(ri,{className:"w-4 h-4 text-primary"})}),p.jsxs("div",{children:[p.jsx("p",{"data-testid":`user-${t.username}-name`,className:"text-foreground font-medium",children:t.username}),p.jsxs("p",{className:"text-muted-foreground text-xs flex items-center gap-2",children:[p.jsx(pz,{className:"w-3 h-3"}),t.expiry_at?new Date(t.expiry_at).toLocaleDateString():r("admin.noExpiry"),p.jsx("span",{className:`ms-2 ${E}`,children:t.is_expired?r("admin.expired"):t.days_remaining!=null?r("admin.daysLeft",{count:t.days_remaining}):""})]})]})]}),p.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[p.jsx("button",{onClick:()=>y(30),disabled:s,"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})}),p.jsx("button",{onClick:()=>y(7),disabled:s,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})}),p.jsx("button",{onClick:()=>y(-7),disabled:s,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})}),p.jsxs("button",{onClick:S,disabled:s,"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:[p.jsx(xm,{className:"w-3 h-3"})," ",r("admin.deleteUser")]})]})]}),p.jsxs("details",{className:"mt-3",children:[p.jsx("summary",{className:"cursor-pointer text-xs text-muted-foreground tracking-[0.2em] uppercase hover:text-primary",children:r("admin.advanced")}),p.jsxs("div",{className:"mt-3 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3",children:[p.jsxs("div",{children:[p.jsx("label",{className:"text-[11px] text-muted-foreground tracking-[0.2em] uppercase block mb-1",children:r("admin.xtreamMode")}),p.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:[p.jsx("option",{value:"shared",children:r("admin.modeShared")}),p.jsx("option",{value:"own",children:r("admin.modeOwn")})]})]}),p.jsx(un,{label:r("admin.server"),value:u,onChange:d}),p.jsx(un,{label:r("admin.xtUser"),value:h,onChange:f}),p.jsx(un,{label:r("admin.xtPass"),value:m,onChange:g}),p.jsx("div",{className:"lg:col-span-4 flex gap-2 justify-end",children:p.jsxs("button",{onClick:_,disabled:s,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:[p.jsx(Gc,{className:"w-3 h-3"})," ",r("admin.saveXtream")]})}),p.jsxs("div",{className:"lg:col-span-4 flex items-center gap-2",children:[p.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"}),p.jsx("button",{onClick:v,disabled:s||!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")})]})]})]})]})},Rue=[{value:"/live-tv",label:"Live TV",icon:ri},{value:"/movies",label:"Movies",icon:bm},{value:"/series",label:"Series",icon:Dh},{value:"/",label:"Home",icon:uE},{value:"",label:"No deep link",icon:uE}],Cue=()=>{var I;const t=lr(),[e,n]=C.useState(""),[r,s]=C.useState(""),[i,a]=C.useState("/live-tv"),[o,l]=C.useState(""),[c,u]=C.useState(""),[d,h]=C.useState(""),[f,m]=C.useState([]),[g,y]=C.useState(!1),[v,_]=C.useState(null),[S,E]=C.useState([]),L=async()=>{try{const k=await Yee(10);E(k.broadcasts||[])}catch(k){console.warn("[broadcast] history fetch failed",k)}};C.useEffect(()=>{L(),E3().then(k=>m((k.users||[]).map(R=>({id:R.id,username:R.username})))).catch(()=>m([]))},[]);const U=async k=>{if(k.preventDefault(),!e.trim()||!r.trim()){_({kind:"error",message:"Title and message are required."});return}y(!0),_(null);try{const R={title:e.trim(),body:r.trim(),route:i||null,image_url:o.trim()||null,action_label:c.trim()||null,target_user_id:d||null},M=await Hee(R);M.queued?(_({kind:"ok",total:M.total_tokens}),n(""),s(""),l(""),u(""),setTimeout(L,4e3)):_({kind:"error",message:M.error||"No registered devices yet."})}catch(R){const M=R instanceof Error?R.message:"Failed to queue broadcast.";_({kind:"error",message:M})}finally{y(!1)}},P=k=>{try{const R=new Date(k),M=Date.now(),G=Math.round((M-R.getTime())/6e4);return G<1?"just now":G<60?`${G}m ago`:G<60*24?`${Math.round(G/60)}h ago`:R.toLocaleString()}catch{return k}};return p.jsxs("div",{className:"relative min-h-screen w-full overflow-hidden",children:[p.jsx("div",{className:"absolute inset-0 bg-cover bg-center bg-no-repeat",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),p.jsx("div",{className:"absolute inset-0 bg-background/65"}),p.jsxs("div",{className:"relative z-10 max-w-3xl mx-auto px-4 py-6 sm:py-8",children:[p.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[p.jsx("button",{"data-testid":"broadcast-back-btn",onClick:()=>t("/admin"),className:"w-10 h-10 rounded-full glass flex items-center justify-center hover:border-primary/40",children:p.jsx(Ph,{className:"w-5 h-5 text-muted-foreground rtl:rotate-180"})}),p.jsxs("div",{className:"flex-1",children:[p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx(g0,{className:"w-5 h-5 text-primary"}),p.jsx("h1",{className:"font-display text-lg sm:text-xl tracking-[0.2em] gold-text",children:"BROADCAST NOTIFICATION"})]}),p.jsx("p",{className:"text-muted-foreground text-xs mt-1",children:"Push a live-match alert (or any message) to every signed-in device."})]})]}),p.jsxs("form",{onSubmit:U,className:"glass-card rounded-2xl p-5 sm:p-6 space-y-4","data-testid":"broadcast-form",children:[p.jsxs("div",{children:[p.jsx("label",{className:"block text-foreground/80 text-xs uppercase tracking-wider mb-2",children:"Title"}),p.jsx("input",{"data-testid":"broadcast-title",value:e,onChange:k=>n(k.target.value),placeholder:'e.g. "Real Madrid vs Barcelona — kick-off in 5 min"',maxLength:200,disabled:g,className:"w-full px-3.5 py-2.5 rounded-xl glass text-foreground placeholder:text-muted-foreground/60 focus:border-primary/60 outline-none border border-transparent transition"}),p.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1 tabular-nums",children:[e.length,"/200"]})]}),p.jsxs("div",{children:[p.jsx("label",{className:"block text-foreground/80 text-xs uppercase tracking-wider mb-2",children:"Message"}),p.jsx("textarea",{"data-testid":"broadcast-body",value:r,onChange:k=>s(k.target.value),placeholder:'e.g. "Tap to watch the match live now"',maxLength:1e3,rows:4,disabled:g,className:"w-full px-3.5 py-2.5 rounded-xl glass text-foreground placeholder:text-muted-foreground/60 focus:border-primary/60 outline-none border border-transparent resize-none transition"}),p.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1 tabular-nums",children:[r.length,"/1000"]})]}),p.jsxs("div",{children:[p.jsx("label",{className:"block text-foreground/80 text-xs uppercase tracking-wider mb-2",children:"Tap action — open this screen"}),p.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-5 gap-2",children:Rue.map(k=>{const R=k.icon,M=i===k.value;return p.jsxs("button",{type:"button","data-testid":`broadcast-route-${k.value||"none"}`,onClick:()=>a(k.value),disabled:g,className:`flex items-center gap-1.5 px-3 py-2 rounded-xl text-[11px] font-medium transition ${M?"bg-primary/20 text-primary border border-primary/40":"glass text-muted-foreground hover:text-foreground border border-transparent"}`,children:[p.jsx(R,{className:"w-3.5 h-3.5"}),k.label]},k.value)})})]}),p.jsxs("div",{children:[p.jsxs("label",{className:"block text-foreground/80 text-xs uppercase tracking-wider mb-2",children:[p.jsx(Xz,{className:"w-3 h-3 inline mr-1.5"}),"Image URL (optional · for live-match thumbnails)"]}),p.jsx("input",{"data-testid":"broadcast-image-url",type:"url",value:o,onChange:k=>l(k.target.value),placeholder:"https://example.com/match-thumb.jpg",maxLength:2e3,disabled:g,className:"w-full px-3.5 py-2.5 rounded-xl glass text-foreground placeholder:text-muted-foreground/60 focus:border-primary/60 outline-none border border-transparent transition"}),o&&p.jsx("div",{className:"mt-2 rounded-xl overflow-hidden bg-background/40 max-w-[260px]",children:p.jsx("img",{src:o,alt:"preview",className:"w-full h-32 object-cover",onError:k=>k.target.style.display="none"})})]}),p.jsxs("div",{children:[p.jsx("label",{className:"block text-foreground/80 text-xs uppercase tracking-wider mb-2",children:"Action button label (optional)"}),p.jsx("input",{"data-testid":"broadcast-action-label",value:c,onChange:k=>u(k.target.value),placeholder:'e.g. "Watch Now"',maxLength:30,disabled:g,className:"w-full px-3.5 py-2.5 rounded-xl glass text-foreground placeholder:text-muted-foreground/60 focus:border-primary/60 outline-none border border-transparent transition"})]}),p.jsxs("div",{children:[p.jsx("label",{className:"block text-foreground/80 text-xs uppercase tracking-wider mb-2",children:"Recipient"}),p.jsxs("div",{className:"flex flex-wrap gap-2",children:[p.jsxs("button",{type:"button","data-testid":"broadcast-target-all",onClick:()=>h(""),disabled:g,className:`flex items-center gap-1.5 px-3 py-2 rounded-xl text-[11px] font-medium transition ${d?"glass text-muted-foreground hover:text-foreground border border-transparent":"bg-primary/20 text-primary border border-primary/40"}`,children:[p.jsx(Bj,{className:"w-3.5 h-3.5"}),"All users"]}),f.length>0&&p.jsxs("select",{"data-testid":"broadcast-target-user",value:d,onChange:k=>h(k.target.value),disabled:g,className:"flex-1 px-3 py-2 rounded-xl glass text-foreground text-[11px] outline-none border border-transparent focus:border-primary/40",children:[p.jsx("option",{value:"",children:"— Single user —"}),f.map(k=>p.jsx("option",{value:k.id,children:k.username},k.id))]})]}),d&&p.jsxs("p",{className:"mt-1.5 text-[10px] text-primary flex items-center gap-1",children:[p.jsx(Ji,{className:"w-3 h-3"}),"Sending only to"," ",p.jsx("span",{className:"font-medium",children:((I=f.find(k=>k.id===d))==null?void 0:I.username)||d})]})]}),(v==null?void 0:v.kind)==="ok"&&p.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-xl bg-primary/10 border border-primary/30",children:[p.jsx(a1,{className:"w-4 h-4 text-primary mt-0.5 shrink-0"}),p.jsxs("p",{className:"text-primary text-xs",children:["Queued to ",p.jsx("span",{className:"tabular-nums",children:v.total})," ","device",v.total===1?"":"s",". Delivery typically completes in 1–5 minutes; offline devices receive the notification when they reconnect."]})]}),(v==null?void 0:v.kind)==="error"&&p.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-xl bg-destructive/15 border border-destructive/40",children:[p.jsx(Rv,{className:"w-4 h-4 text-destructive mt-0.5 shrink-0"}),p.jsx("p",{className:"text-destructive text-xs",children:v.message})]}),p.jsx("button",{type:"submit",disabled:g,"data-testid":"broadcast-send-btn",className:"w-full flex items-center justify-center gap-2 px-4 py-3 rounded-xl bg-primary text-primary-foreground font-medium disabled:bg-primary/50 disabled:cursor-not-allowed hover:bg-primary/90 transition",children:g?p.jsxs(p.Fragment,{children:[p.jsx(Pn,{className:"w-4 h-4 animate-spin"})," Sending…"]}):d?p.jsxs(p.Fragment,{children:[p.jsx(dk,{className:"w-4 h-4"})," Send to selected user"]}):p.jsxs(p.Fragment,{children:[p.jsx(dk,{className:"w-4 h-4"})," Send to All Users"]})})]}),p.jsxs("div",{className:"glass-card rounded-2xl p-5 sm:p-6 mt-6","data-testid":"broadcast-history",children:[p.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[p.jsx(qz,{className:"w-4 h-4 text-muted-foreground"}),p.jsx("h2",{className:"text-foreground/90 text-sm tracking-wide",children:"Recent broadcasts"})]}),S.length===0?p.jsx("p",{className:"text-muted-foreground text-xs py-3",children:"No broadcasts sent yet."}):p.jsx("ul",{className:"divide-y divide-border/50",children:S.map((k,R)=>p.jsxs("li",{className:"py-2.5 flex items-start gap-3",children:[p.jsx("div",{className:"w-9 h-9 rounded-lg bg-primary/10 flex items-center justify-center shrink-0",children:p.jsx(g0,{className:"w-4 h-4 text-primary"})}),p.jsxs("div",{className:"flex-1 min-w-0",children:[p.jsx("p",{className:"text-foreground text-sm font-medium truncate",children:k.title}),p.jsx("p",{className:"text-muted-foreground text-[11px] truncate",children:k.body}),p.jsxs("div",{className:"flex items-center gap-3 mt-1 text-[10px] text-muted-foreground tabular-nums",children:[p.jsx("span",{children:P(k.created_at)}),p.jsxs("span",{className:"text-primary",children:[k.sent," sent"]}),k.failed>0&&p.jsxs("span",{className:"text-destructive",children:[k.failed," failed"]}),k.pruned>0&&p.jsxs("span",{children:[k.pruned," pruned"]}),k.route&&p.jsxs("span",{className:"px-1.5 py-0.5 rounded bg-primary/10 text-primary",children:["→ ",k.route]})]})]})]},`${k.created_at}-${R}`))})]})]})]})},vA=()=>{const{addProfile:t,setActiveProfileId:e}=Li(),n=nF();return async r=>{const s=It.loading(`Connecting to ${r.name}...`);try{const i={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 fs.authenticate(i);else if(r.kind==="m3u"){if(!(!!(r.m3uContent&&r.m3uContent.trim().length)?Dl.parsePlaylistText(r.m3uContent):await Dl.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||!J3(r.macAddress))throw new Error("MAC must be in 00:1A:79:XX:XX:XX format");if((await zc.handshake(r.portalUrl,r.macAddress)).profile.blocked)throw new Error("This MAC is blocked on the portal")}const a=t(i);e(a.id),It.loading("Loading channels, movies & series...",{id:s});const o=await n(a);return It.success(`Connected! ${o.channels.length} channels • ${o.movies.length} movies • ${o.series.length} series`,{id:s}),a}catch(i){return It.error(`Failed: ${i.message||"Connection error"}`,{id:s}),null}}},qP=(t="",e="")=>({key:`r-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,name:t,url:e,content:"",fileName:""}),kue=()=>{const t=lr(),[e]=t1(),n=vA(),[r,s]=C.useState(e.get("type")||"xtream"),[i,a]=C.useState(e.get("name")||""),[o,l]=C.useState(e.get("server")||""),[c,u]=C.useState(e.get("user")||""),[d,h]=C.useState(e.get("pass")||""),[f,m]=C.useState(e.get("portal")||""),[g,y]=C.useState(e.get("mac")||""),[v,_]=C.useState([qP(e.get("name")||"",e.get("url")||"")]),[S,E]=C.useState(!1),L=M=>{var Y;return((Y=M.replace(/[^0-9A-Fa-f]/g,"").toUpperCase().slice(0,12).match(/.{1,2}/g))==null?void 0:Y.join(":"))??""},U=(M,G)=>_(Y=>Y.map((q,X)=>X===M?{...q,...G}:q)),P=()=>_(M=>[...M,qP()]),I=M=>_(G=>G.length>1?G.filter((Y,q)=>q!==M):G),k=async(M,G)=>{if(!G)return;const Y=await G.text();U(M,{content:Y,fileName:G.name})},R=async M=>{if(M==null||M.preventDefault(),r==="xtream"){if(!i||!o||!c||!d)return;E(!0);const q=await n({kind:r,name:i,serverUrl:o,username:c,password:d});E(!1),q&&t("/");return}if(r==="stalker"){const q=/^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$/.test(g.trim());if(!i||!f.trim()||!q)return;E(!0);const X=await n({kind:r,name:i,serverUrl:"",username:"",password:"",portalUrl:f.trim(),macAddress:g.trim().toUpperCase()});E(!1),X&&t("/");return}const G=v.map((q,X)=>({...q,name:(q.name||i||`Playlist ${X+1}`).trim(),url:q.url.trim()})).filter(q=>q.url.length>0||q.content.trim().length>0);if(G.length===0)return;E(!0);let Y=null;for(const q of G)Y=await n({kind:"m3u",name:q.name,serverUrl:"",username:"",password:"",m3uUrl:q.url||void 0,m3uContent:q.content||void 0});E(!1),Y&&t("/")};return C.useEffect(()=>{e.get("auto")==="1"&&R()},[]),p.jsxs("div",{className:"relative min-h-screen w-full overflow-hidden flex items-center justify-center px-4 py-8",children:[p.jsx("div",{className:"absolute inset-0 bg-cover bg-center bg-no-repeat",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),p.jsx("div",{className:"absolute inset-0 bg-background/60"}),p.jsxs(gt.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:[p.jsxs("div",{className:"flex flex-col items-center mb-6",children:[p.jsx("div",{className:"w-14 h-14 rounded-2xl glass flex items-center justify-center mb-3",children:p.jsx(ri,{className:"w-6 h-6 text-primary"})}),p.jsx("h1",{className:"font-display text-2xl tracking-[0.25em] gold-text",children:"NADIPLAYER"}),p.jsx("p",{className:"text-muted-foreground text-xs mt-1",children:"Connect your IPTV service"})]}),p.jsx("div",{className:"flex glass rounded-xl p-1 mb-5",children:["xtream","m3u","stalker"].map(M=>p.jsx("button",{type:"button",onClick:()=>s(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"?p.jsxs("div",{className:"space-y-3",children:[p.jsx(Ya,{icon:Vc,placeholder:"Profile Name",value:i,onChange:a}),p.jsx(Ya,{icon:Gc,placeholder:"Server URL (http://...)",value:o,onChange:l}),p.jsx(Ya,{icon:Ji,placeholder:"Username",value:c,onChange:u}),p.jsx(Ya,{icon:Cv,placeholder:"Password",value:d,onChange:h,type:"password"})]}):r==="stalker"?p.jsxs("div",{className:"space-y-3","data-testid":"login-stalker-form",children:[p.jsx(Ya,{icon:Vc,placeholder:"Profile Name",value:i,onChange:a,testId:"login-stalker-name"}),p.jsx(Ya,{icon:cE,placeholder:"Portal URL (http://portal.com:8080/c/)",value:f,onChange:m,testId:"login-stalker-portal"}),p.jsx(Ya,{icon:lE,placeholder:"MAC Address (00:1A:79:XX:XX:XX)",value:g,onChange:M=>y(L(M)),testId:"login-stalker-mac"}),p.jsx(yA,{portalUrl:f,mac:g,testId:"login-stalker-test"}),p.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed px-1",children:"Stalker / MAG portal. Authenticates as a MAG250 STB using your MAC."})]}):p.jsxs("div",{className:"space-y-3",children:[v.map((M,G)=>p.jsxs("div",{"data-testid":`login-m3u-row-${G}`,className:"glass rounded-xl p-3 border border-border/40 space-y-2",children:[p.jsxs("div",{className:"flex items-center justify-between",children:[p.jsxs("span",{className:"text-[10px] uppercase tracking-widest text-primary/80",children:["Playlist #",G+1]}),v.length>1&&p.jsx("button",{type:"button",onClick:()=>I(G),"data-testid":`login-m3u-row-remove-${G}`,className:"text-muted-foreground hover:text-destructive transition-colors","aria-label":"Remove row",children:p.jsx(xm,{className:"w-3.5 h-3.5"})})]}),p.jsx(Ya,{icon:Vc,placeholder:"Profile Name",value:M.name,onChange:Y=>U(G,{name:Y})}),p.jsx(Ya,{icon:dE,placeholder:"https://example.com/playlist.m3u",value:M.url,onChange:Y=>U(G,{url:Y})}),p.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[p.jsxs("label",{"data-testid":`login-m3u-file-${G}`,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:[p.jsx(u1,{className:"w-3.5 h-3.5"}),p.jsx("span",{children:"Upload .m3u file"}),p.jsx("input",{type:"file",accept:".m3u,.m3u8,audio/x-mpegurl,application/vnd.apple.mpegurl,text/plain",onChange:Y=>{var q;return void k(G,((q=Y.target.files)==null?void 0:q[0])??null)},className:"hidden"})]}),M.content&&M.content.trim().length>0&&p.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0 text-xs text-muted-foreground",children:[p.jsx(l1,{className:"w-3.5 h-3.5 text-primary shrink-0"}),p.jsx("span",{className:"truncate",children:M.fileName||"uploaded.m3u"}),p.jsx("button",{type:"button",onClick:()=>U(G,{content:"",fileName:""}),className:"ml-1 text-muted-foreground hover:text-destructive",children:p.jsx(Na,{className:"w-3.5 h-3.5"})})]})]})]},M.key)),p.jsxs("button",{type:"button",onClick:P,"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:[p.jsx(_o,{className:"w-4 h-4"})," Add Playlist"]})]}),p.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&&p.jsx(Pn,{className:"w-4 h-4 animate-spin"}),S?"Connecting...":"Connect & Load"]}),p.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"})]})]})},Ya=({icon:t,placeholder:e,value:n,onChange:r,type:s="text",testId:i})=>p.jsxs("div",{className:"flex items-center gap-3 glass-input rounded-xl px-4 py-3",children:[p.jsx(t,{className:"w-5 h-5 text-muted-foreground shrink-0"}),p.jsx("input",{type:s,placeholder:e,value:n,onChange:a=>r(a.target.value),"data-testid":i,className:"flex-1 bg-transparent text-foreground placeholder:text-muted-foreground outline-none text-sm",autoComplete:"off"})]}),WP=t=>t==="m3u"?wp:t==="stalker"?I9:va,YP=t=>t==="m3u"?"M3U Playlist":t==="stalker"?"Stalker / MAC Portal":"Xtream Codes",Lue=()=>{const t=lr(),{t:e}=wr(),{user:n,loading:r}=ys(),{profiles:s,setActiveProfileId:i}=Li(),a=bv(),o=C.useMemo(()=>s.filter(L=>L.id.startsWith("shared:")),[s]),[l,c]=C.useState(null),[u,d]=C.useState("channels"),[h,f]=C.useState({channels:0,movies:0,series:0}),[m,g]=C.useState(null);C.useEffect(()=>{if(!r&&(!n||n.role==="admin")){t((n==null?void 0:n.role)==="admin"?"/admin":"/welcome",{replace:!0});return}},[r,n,t]),C.useEffect(()=>{r||!n||n.role!=="user"||l||o.length===1&&y(o[0])},[o,r,n]),C.useEffect(()=>{if(!r&&!(!n||n.role!=="user")&&o.length===0){const L=window.setTimeout(()=>t("/",{replace:!0}),900);return()=>window.clearTimeout(L)}},[o.length,r,n,t]),C.useEffect(()=>{if(l||o.length===0)return;const L=window.setTimeout(()=>ru("select-profile-0"),200);return()=>window.clearTimeout(L)},[o.length,l]);const y=async L=>{g(null),c(L),d("channels"),f({channels:0,movies:0,series:0}),i(L.id);try{d("channels");const U=await v(L);a.setQueryData(["xtream",L.id,"live"],U),f(k=>({...k,channels:U.length})),d("movies");const P=await _(L);a.setQueryData(["xtream",L.id,"movies"],P),f(k=>({...k,movies:P.length})),d("series");const I=await S(L);a.setQueryData(["xtream",L.id,"series"],I),f(k=>({...k,series:I.length})),d("done"),await new Promise(k=>setTimeout(k,700)),t("/",{replace:!0})}catch(U){const P=U instanceof Error?U.message:"Unknown error";g(P)}},v=async L=>L.kind==="stalker"?(await zc.fetchAll(L.portalUrl,L.macAddress)).channels:L.kind==="m3u"?E(L).then(U=>U.channels):fs.getLiveStreams(L),_=async L=>L.kind==="stalker"?(await zc.fetchAll(L.portalUrl,L.macAddress)).movies:L.kind==="m3u"?E(L).then(U=>U.movies):fs.getMovies(L),S=async L=>L.kind==="stalker"?(await zc.fetchAll(L.portalUrl,L.macAddress)).series:L.kind==="m3u"?E(L).then(U=>U.series):fs.getSeries(L),E=async L=>{const U=L.m3uContent&&L.m3uContent.trim().length?Dl.parsePlaylistText(L.m3uContent):await Dl.fetchPlaylist(L.m3uUrl);return Dl.classify(U)};return p.jsxs("div",{"data-testid":"select-profile-page",className:"relative min-h-screen w-full overflow-hidden flex items-center justify-center px-4 py-8",children:[p.jsx("div",{className:"absolute inset-0 bg-cover bg-center bg-no-repeat",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),p.jsx("div",{className:"absolute inset-0 bg-background/70"}),p.jsxs(gt.div,{initial:{opacity:0,y:24},animate:{opacity:1,y:0},transition:{duration:.5},className:"relative z-10 glass-card rounded-3xl p-6 sm:p-8 w-full max-w-lg",children:[p.jsxs("div",{className:"flex flex-col items-center mb-6",children:[p.jsx("div",{className:"w-14 h-14 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.25)"},children:p.jsx(ri,{className:"w-7 h-7 text-primary gold-glow",strokeWidth:1.4})}),p.jsx("h1",{className:"font-display text-xl tracking-[0.3em] gold-text",children:e("selectProfile.title","SELECT PROFILE")}),p.jsx("p",{className:"text-muted-foreground text-[11px] tracking-[0.2em] uppercase mt-2 text-center",children:l?e("selectProfile.loading","Loading your content…"):e("selectProfile.subtitle","Pick a profile to start watching")})]}),!l&&p.jsx(Lo,{children:o.length===0?p.jsxs(gt.div,{initial:{opacity:0},animate:{opacity:1},className:"flex flex-col items-center py-10 text-center","data-testid":"select-profile-empty",children:[p.jsx(Pn,{className:"w-6 h-6 animate-spin text-primary mb-3"}),p.jsx("p",{className:"text-foreground text-sm mb-1",children:e("selectProfile.noneTitle","No profile configured yet")}),p.jsx("p",{className:"text-muted-foreground text-xs",children:e("selectProfile.noneDesc","Taking you to the home screen…")})]},"empty"):p.jsxs(Ci,{focusKey:"select-profile-list-section",className:"space-y-2","data-testid":"select-profile-list",children:[o.map((L,U)=>{const P=WP(L.kind);return p.jsxs(Kl,{focusKey:`select-profile-${U}`,onClick:()=>void y(L),onEnter:()=>void y(L),"data-testid":`select-profile-${U}`,className:"w-full flex items-center gap-3 px-4 py-3 rounded-2xl glass border border-transparent transition-all group text-start cursor-pointer outline-none",children:[p.jsx("div",{className:"w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center shrink-0 group-hover:bg-primary/20",children:p.jsx(P,{className:"w-5 h-5 text-primary"})}),p.jsxs("div",{className:"flex-1 min-w-0",children:[p.jsx("p",{className:"text-foreground text-sm font-medium truncate",children:L.name}),p.jsx("p",{className:"text-muted-foreground text-[11px] truncate",children:YP(L.kind)})]}),p.jsx(va,{className:"w-4 h-4 text-muted-foreground group-hover:text-primary",strokeWidth:2})]},L.id)}),p.jsxs("div",{className:"flex items-center gap-2 pt-3",children:[p.jsxs(wi,{focusKey:"select-profile-skip",onEnter:()=>t("/",{replace:!0}),onClick:()=>t("/",{replace:!0}),"data-testid":"select-profile-skip",className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl glass text-muted-foreground hover:text-foreground hover:border-primary/40 text-xs outline-none",children:[p.jsx(Uj,{className:"w-3.5 h-3.5"}),e("selectProfile.skip","Skip for now")]}),p.jsxs(wi,{focusKey:"select-profile-add-own",onEnter:()=>t("/account",{replace:!0}),onClick:()=>t("/account",{replace:!0}),"data-testid":"select-profile-add-own",className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl bg-primary/20 text-primary hover:bg-primary/30 text-xs font-medium outline-none",children:[p.jsx(_o,{className:"w-3.5 h-3.5"}),e("selectProfile.addOwn","Add my own")]})]})]},"list")}),l&&p.jsxs("div",{className:"space-y-2","data-testid":"select-profile-progress",children:[p.jsxs("div",{className:"glass rounded-2xl px-4 py-3 flex items-center gap-3 mb-3",children:[p.jsx("div",{className:"w-9 h-9 rounded-lg bg-primary/10 flex items-center justify-center shrink-0",children:(()=>{const L=WP(l.kind);return p.jsx(L,{className:"w-4 h-4 text-primary"})})()}),p.jsxs("div",{className:"flex-1 min-w-0",children:[p.jsx("p",{className:"text-foreground text-sm font-medium truncate",children:l.name}),p.jsx("p",{className:"text-muted-foreground text-[11px] truncate",children:YP(l.kind)})]})]}),p.jsx(hx,{icon:ri,label:e("selectProfile.stepChannels","Channels"),count:h.channels,state:dx("channels",u,!!m),testId:"progress-channels"}),p.jsx(hx,{icon:bm,label:e("selectProfile.stepMovies","Movies"),count:h.movies,state:dx("movies",u,!!m),testId:"progress-movies"}),p.jsx(hx,{icon:Dh,label:e("selectProfile.stepSeries","Series"),count:h.series,state:dx("series",u,!!m),testId:"progress-series"}),m&&p.jsxs(gt.div,{initial:{opacity:0,y:6},animate:{opacity:1,y:0},className:"mt-4 p-3 rounded-xl bg-destructive/15 border border-destructive/40 flex items-start gap-2","data-testid":"select-profile-error",children:[p.jsx(Rv,{className:"w-4 h-4 text-destructive mt-0.5 shrink-0"}),p.jsxs("div",{className:"flex-1 min-w-0",children:[p.jsx("p",{className:"text-destructive text-xs font-medium",children:e("selectProfile.errorTitle","Could not connect")}),p.jsx("p",{className:"text-destructive/80 text-[11px] mt-0.5 break-words",children:m}),p.jsxs("div",{className:"flex gap-2 mt-3",children:[p.jsx("button",{onClick:()=>c(null),className:"text-[11px] px-3 py-1.5 rounded-lg glass text-foreground hover:border-primary/40","data-testid":"select-profile-retry",children:e("selectProfile.back","Back to list")}),p.jsx("button",{onClick:()=>t("/",{replace:!0}),className:"text-[11px] px-3 py-1.5 rounded-lg bg-primary/20 text-primary hover:bg-primary/30",children:e("selectProfile.skip","Skip for now")})]})]})]}),!m&&u==="done"&&p.jsxs(gt.p,{initial:{opacity:0},animate:{opacity:1},className:"text-center text-primary text-xs mt-3 tracking-wide","data-testid":"select-profile-done",children:["✓ ",e("selectProfile.allLoaded","All loaded — let's go")]})]})]})]})},dx=(t,e,n)=>{const r=["channels","movies","series","done"],s=r.indexOf(e),i=r.indexOf(t);return n&&i===s?"error":i<s?"done":i===s?"active":"pending"},hx=({icon:t,label:e,count:n,state:r,testId:s})=>p.jsxs("div",{className:`glass rounded-2xl px-4 py-3 flex items-center gap-3 border transition-colors ${r==="active"?"border-primary/50":r==="done"?"border-primary/30":r==="error"?"border-destructive/50":"border-transparent"}`,"data-testid":s,"data-state":r,children:[p.jsx("div",{className:"w-9 h-9 rounded-lg bg-primary/10 flex items-center justify-center shrink-0",children:p.jsx(t,{className:`w-4 h-4 ${r==="pending"?"text-muted-foreground/50":"text-primary"}`})}),p.jsxs("div",{className:"flex-1 min-w-0",children:[p.jsx("p",{className:"text-foreground text-sm font-medium",children:e}),p.jsx("p",{className:"text-muted-foreground text-[11px] tabular-nums",children:r==="done"?`${n.toLocaleString()} items loaded`:r==="active"?"Loading…":r==="error"?"Failed":"Waiting"})]}),p.jsxs("div",{className:"w-5 h-5 flex items-center justify-center",children:[r==="active"&&p.jsx(Pn,{className:"w-4 h-4 animate-spin text-primary"}),r==="done"&&p.jsx(qi,{className:"w-4 h-4 text-primary"}),r==="error"&&p.jsx(Rv,{className:"w-4 h-4 text-destructive"})]})]}),fx=()=>({key:`r-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,name:"",url:"",content:"",fileName:""}),y5=({open:t,onClose:e,onSubmit:n})=>{const{t:r}=wr(),{user:s,isGuest:i}=ys(),a=i||!s,[o,l]=C.useState("xtream"),[c,u]=C.useState(a?"own":"shared"),[d,h]=C.useState(""),[f,m]=C.useState(""),[g,y]=C.useState(""),[v,_]=C.useState(""),[S,E]=C.useState(""),[L,U]=C.useState(""),[P,I]=C.useState([fx()]),[k,R]=C.useState(!1),[M,G]=C.useState([]),[Y,q]=C.useState(!1),[X,Z]=C.useState(null),[oe,ne]=C.useState(null),H=()=>{h(""),m(""),y(""),_(""),I([fx()]),ne(null),E(""),U("")};C.useEffect(()=>{if(!t||a)return;let Ae=!1;return q(!0),Z(null),w3().then(we=>{Ae||G(we.profiles||[])}).catch(we=>{Ae||Z(we instanceof Error?we.message:"Failed")}).finally(()=>{Ae||q(!1)}),()=>{Ae=!0}},[t,a]),C.useEffect(()=>{t||(u(a?"own":"shared"),l("xtream"),H())},[t,a]);const K=Ae=>{ne(Ae.id||Ae.name),h(Ae.name||""),Ae.kind==="m3u"?(l("m3u"),I([{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"),m(Ae.server||""),y(Ae.username||""),_(Ae.password||""))},J=(Ae,we)=>I(Ue=>Ue.map((Oe,Dt)=>Dt===Ae?{...Oe,...we}:Oe)),Q=()=>I(Ae=>[...Ae,fx()]),ve=Ae=>I(we=>we.length>1?we.filter((Ue,Oe)=>Oe!==Ae):we),Te=async(Ae,we)=>{if(!we)return;const Ue=await we.text();J(Ae,{content:Ue,fileName:we.name})},Ne=Ae=>J(Ae,{content:"",fileName:""}),Ke=async()=>{var Ue;const Ae=c==="shared"&&oe&&((Ue=M.find(Oe=>(Oe.id||Oe.name)===oe))==null?void 0:Ue.kind)||o;if(Ae==="xtream"){if(!d||!f||!g||!v)return;R(!0);try{await n({kind:"xtream",name:d,serverUrl:f,username:g,password:v}),H()}finally{R(!1)}return}if(Ae==="stalker"){const Oe=/^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$/.test(L.trim());if(!d||!S.trim()||!Oe)return;R(!0);try{await n({kind:"stalker",name:d,serverUrl:"",username:"",password:"",portalUrl:S.trim(),macAddress:L.trim().toUpperCase()}),H()}finally{R(!1)}return}const we=P.map(Oe=>({...Oe,name:(Oe.name||d||"").trim(),url:Oe.url.trim(),content:Oe.content})).filter(Oe=>Oe.url.length>0||Oe.content.trim().length>0).map((Oe,Dt,en)=>({...Oe,name:Oe.name||(en.length>1?`Playlist ${Dt+1}`:"M3U Playlist")}));if(we.length!==0){R(!0);try{for(const Oe of we)await n({kind:"m3u",name:Oe.name,serverUrl:"",username:"",password:"",m3uUrl:Oe.url||void 0,m3uContent:Oe.content||void 0});H()}finally{R(!1)}}},Pe=k||c==="shared"&&!a&&!(c==="shared"&&oe!==null&&!Y);return p.jsx(Lo,{children:t&&p.jsxs(gt.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:[p.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),p.jsxs(gt.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:[p.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&&p.jsxs("div",{className:"mb-4",children:[p.jsx("label",{className:"text-[11px] text-muted-foreground tracking-[0.25em] uppercase block mb-2",children:r("addServer.advanced")}),p.jsxs("div",{className:"flex glass rounded-xl p-1",children:[p.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:[p.jsx(cE,{className:"w-3.5 h-3.5"}),r("addServer.shared")]}),p.jsxs("button",{onClick:()=>{u("own"),ne(null),H()},"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:[p.jsx(Gc,{className:"w-3.5 h-3.5"}),r("addServer.ownServer")]})]})]}),!a&&c==="shared"?p.jsxs("div",{className:"space-y-2","data-testid":"shared-profile-picker",children:[Y&&p.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-2 py-2",children:[p.jsx(Pn,{className:"w-3 h-3 animate-spin"})," Loading profiles…"]}),X&&p.jsx("div",{className:"text-destructive text-xs",children:X}),!Y&&M.length===0&&p.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."}),!Y&&M.map(Ae=>{const we=Ae.id||Ae.name,Ue=oe===we;return p.jsxs("button",{onClick:()=>K(Ae),"data-testid":`profile-pick-${we}`,className:`w-full flex items-center gap-3 px-3 py-2.5 rounded-xl border text-left transition-all ${Ue?"bg-primary/10 border-primary/50":"glass border-transparent hover:border-primary/30"}`,children:[Ae.kind==="m3u"?p.jsx(dE,{className:"w-4 h-4 text-primary shrink-0"}):Ae.kind==="stalker"?p.jsx(lE,{className:"w-4 h-4 text-primary shrink-0"}):p.jsx(Gc,{className:"w-4 h-4 text-primary shrink-0"}),p.jsxs("div",{className:"flex-1 min-w-0",children:[p.jsx("p",{className:`text-sm font-medium truncate ${Ue?"text-primary":"text-foreground"}`,children:Ae.name}),p.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"})]}),Ue&&p.jsx(qi,{className:"w-4 h-4 text-primary"})]},we)})]}):p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"flex glass rounded-xl p-1 mb-4",children:["xtream","m3u","stalker"].map(Ae=>p.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"?p.jsxs("div",{className:"space-y-3",children:[p.jsx(Xa,{icon:Vc,placeholder:r("addServer.profileNamePlaceholder"),value:d,onChange:h,testId:"add-name"}),p.jsx(Xa,{icon:Gc,placeholder:r("addServer.serverUrlPlaceholder"),value:f,onChange:m,testId:"add-server-url"}),p.jsx(Xa,{icon:Ji,placeholder:r("addServer.usernamePlaceholder"),value:g,onChange:y,testId:"add-user"}),p.jsx(Xa,{icon:Cv,placeholder:r("addServer.passwordPlaceholder"),value:v,onChange:_,type:"password",testId:"add-pass"})]}):o==="stalker"?p.jsxs("div",{className:"space-y-3","data-testid":"stalker-form",children:[p.jsx(Xa,{icon:Vc,placeholder:r("addServer.profileNamePlaceholder"),value:d,onChange:h,testId:"add-stalker-name"}),p.jsx(Xa,{icon:cE,placeholder:"Portal URL (e.g. http://portal.com:8080/c/)",value:S,onChange:E,testId:"add-stalker-portal"}),p.jsx(Xa,{icon:lE,placeholder:"MAC Address (00:1A:79:XX:XX:XX)",value:L,onChange:Ae=>U(Iue(Ae)),testId:"add-stalker-mac"}),p.jsx(yA,{portalUrl:S,mac:L,testId:"add-stalker-test"}),p.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: ",p.jsx("code",{children:"QtStalker"}),", X-User-Agent: ",p.jsx("code",{children:"Model: MAG250"}),") and authenticates using your MAC address."]})]}):p.jsxs("div",{className:"space-y-3",children:[P.map((Ae,we)=>p.jsxs("div",{"data-testid":`m3u-row-${we}`,className:"glass rounded-xl p-3 border border-border/40 space-y-2",children:[p.jsxs("div",{className:"flex items-center justify-between",children:[p.jsxs("span",{className:"text-[10px] uppercase tracking-widest text-primary/80",children:["Playlist #",we+1]}),P.length>1&&p.jsx("button",{type:"button",onClick:()=>ve(we),"data-testid":`m3u-row-remove-${we}`,className:"text-muted-foreground hover:text-destructive transition-colors","aria-label":"Remove row",children:p.jsx(xm,{className:"w-3.5 h-3.5"})})]}),p.jsx(Xa,{icon:Vc,placeholder:r("addServer.profileNamePlaceholder"),value:Ae.name,onChange:Ue=>J(we,{name:Ue}),testId:`add-m3u-name-${we}`}),p.jsx(Xa,{icon:dE,placeholder:r("addServer.m3uPlaceholder"),value:Ae.url,onChange:Ue=>J(we,{url:Ue}),testId:`add-m3u-url-${we}`}),p.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[p.jsxs("label",{"data-testid":`add-m3u-file-${we}`,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:[p.jsx(u1,{className:"w-3.5 h-3.5"}),p.jsx("span",{children:"Upload .m3u file"}),p.jsx("input",{type:"file",accept:".m3u,.m3u8,audio/x-mpegurl,application/vnd.apple.mpegurl,text/plain",onChange:Ue=>{var Oe;return void Te(we,((Oe=Ue.target.files)==null?void 0:Oe[0])??null)},className:"hidden"})]}),Ae.content&&Ae.content.trim().length>0&&p.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0 text-xs text-muted-foreground",children:[p.jsx(l1,{className:"w-3.5 h-3.5 text-primary shrink-0"}),p.jsx("span",{className:"truncate",children:Ae.fileName||"uploaded.m3u"}),p.jsx("button",{type:"button",onClick:()=>Ne(we),"data-testid":`add-m3u-file-clear-${we}`,className:"ml-1 text-muted-foreground hover:text-destructive",children:p.jsx(Na,{className:"w-3.5 h-3.5"})})]})]})]},Ae.key)),p.jsxs("button",{type:"button",onClick:Q,"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:[p.jsx(_o,{className:"w-4 h-4"})," Add Playlist"]})]})]}),p.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-6",children:[p.jsxs("button",{onClick:Ke,disabled:Pe,"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:[k?p.jsx(Pn,{className:"w-4 h-4 animate-spin"}):null,r("common.save")]}),p.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")})]})]})]})})},Xa=({icon:t,placeholder:e,value:n,onChange:r,type:s="text",testId:i})=>p.jsxs("div",{className:"relative",children:[p.jsx(t,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),p.jsx("input",{type:s,value:n,onChange:a=>r(a.target.value),placeholder:e,"data-testid":i,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"})]}),Iue=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(":"))??""},Pue=({username:t,whatsappNumber:e,onLogout:n})=>{const{t:r}=wr(),s=(e||"").replace(/[^\d+]/g,""),i=s?`https://wa.me/${s.replace(/^\+/,"")}?text=${encodeURIComponent(r("expired.whatsappPrefill",{username:t}))}`:"#";return p.jsx(gt.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:p.jsxs(gt.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:[p.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:p.jsx(h9,{className:"w-8 h-8 sm:w-10 sm:h-10 text-destructive",strokeWidth:1.4})}),p.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")}),p.jsxs("p",{className:"text-foreground/80 text-sm md:text-base mb-1",children:[r("expired.hi")," ",p.jsx("span",{className:"text-primary font-medium",children:t}),","]}),p.jsx("p",{className:"text-muted-foreground text-sm md:text-base mb-6 leading-relaxed",children:r("expired.message")}),p.jsxs("a",{href:i,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:[p.jsx(Mj,{className:"w-5 h-5"}),r("expired.contactWhatsapp")]}),e&&p.jsx("p",{className:"text-muted-foreground text-xs mt-4",children:e}),p.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")})]})})},v5=({className:t="",testId:e="header-clock"})=>{const[n,r]=C.useState(()=>new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}));return C.useEffect(()=>{const s=()=>r(new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})),i=new Date,a=(60-i.getSeconds())*1e3-i.getMilliseconds();let o;const l=window.setTimeout(()=>{s(),o=window.setInterval(s,6e4)},Math.max(250,a));return()=>{window.clearTimeout(l),o!==void 0&&window.clearInterval(o)}},[]),p.jsxs("div",{className:`flex items-center gap-1.5 px-2.5 h-9 sm:h-10 rounded-full glass text-foreground/90 ${t}`,"data-testid":e,children:[p.jsx(Oj,{className:"w-3.5 h-3.5 text-primary",strokeWidth:2}),p.jsx("span",{className:"text-[11px] sm:text-xs font-medium tabular-nums tracking-wide",children:n})]})},Due="hsl(40, 80%, 55%)",Oue="hsla(40, 80%, 55%, 0.10)",Nue="hsla(40, 80%, 55%, 0.04)",Mue={idle:{scale:.94,zIndex:1,filter:"saturate(0.85) brightness(0.9)"},focused:{scale:1.1,zIndex:10,filter:"saturate(1.1) brightness(1.05)"}},jue={idle:{opacity:0},focused:{opacity:1}},Uue=({title:t,count:e,icon:n,index:r,route:s})=>{const i=lr(),a=`home-category-${r}`,{ref:o,focused:l,focusKey:c}=Kh({focusKey:a,onEnterPress:()=>{su(),i(s)},onFocus:({node:d})=>{Jv(),d&&d.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})}}),u=()=>{su(),i(s)};return p.jsxs(gt.div,{ref:o,layout:!0,initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{layout:{type:"spring",stiffness:320,damping:26},opacity:{duration:.4,delay:r*.08},y:{duration:.5,delay:r*.08}},role:"button",tabIndex:0,"data-focused":l||void 0,"data-testid":`home-category-card-${r}`,onClick:u,onMouseEnter:()=>{c&&ru(c)},onKeyDown:d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),u())},className:"relative cursor-pointer select-none w-[44%] sm:w-[180px] md:w-[240px] lg:w-[260px] outline-none",style:{containerType:"inline-size"},children:[p.jsx(gt.div,{"aria-hidden":!0,variants:jue,animate:l?"focused":"idle",transition:{duration:.3,ease:"easeOut"},className:"absolute pointer-events-none",style:{inset:"-3cqw",borderRadius:"8cqw",boxShadow:`0 0 10cqw 1cqw ${Oue}, 0 0 26cqw 3.5cqw ${Nue}`,willChange:"opacity"}}),p.jsx(gt.div,{variants:Mue,animate:l?"focused":"idle",transition:{type:"spring",stiffness:280,damping:22},className:`relative overflow-hidden
                   w-full aspect-[16/10]
                   glass-card`,style:{borderRadius:"5cqw",willChange:"transform"},children:p.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:[p.jsx(gt.div,{animate:l?{opacity:[1,0,1],color:Due}:{opacity:.6,color:"#ffffff"},transition:l?{duration:.7,repeat:1/0,ease:"easeInOut"}:{duration:.25,ease:"easeOut"},style:{willChange:"opacity, color"},children:p.jsx(n,{className:l?"w-10 h-10 sm:w-14 sm:h-14 md:w-16 md:h-16":"w-8 h-8 sm:w-10 sm:h-10 md:w-12 md:h-12",strokeWidth:1.2})}),p.jsx(gt.h3,{animate:{color:l?"#fff":"rgba(255,255,255,0.85)"},className:"text-sm sm:text-base md:text-lg font-medium tracking-wide",children:t}),p.jsx(gt.p,{animate:{opacity:l?1:.55},className:"text-muted-foreground text-[10px] sm:text-xs",children:e})]})})]})},Bue=[{key:"liveTv",icon:ri,route:"/live-tv"},{key:"movies",icon:bm,route:"/movies"},{key:"series",icon:Dh,route:"/series"}],Fue=()=>{const[t,e]=C.useState(!1),n=lr(),{t:r}=wr(),{activeProfile:s}=Li(),i=vA(),{user:a,isGuest:o,logout:l}=ys(),c=!!a&&a.role==="user",[u,d]=C.useState(null);C.useEffect(()=>{if(!c)return;let v=!1;return S3().then(_=>{v||d(_)}).catch(()=>{}),()=>{v=!0}},[c,a==null?void 0:a.id]);const h=(u==null?void 0:u.user.days_remaining)??(a==null?void 0:a.days_remaining)??null,f=(u==null?void 0:u.user.is_expired)??(a==null?void 0:a.is_expired)??!1,m=(u==null?void 0:u.user.expiry_at)??(a==null?void 0:a.expiry_at)??null,g=(u==null?void 0:u.whatsapp_number)??"",y=()=>{l(),n("/welcome")};return p.jsxs(gt.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},exit:{opacity:0,y:-12},transition:{duration:.45,ease:[.22,1,.36,1]},className:"relative min-h-screen w-full overflow-hidden","data-testid":"home-page-root",children:[p.jsx("div",{className:"absolute inset-0 bg-cover bg-center bg-no-repeat",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),p.jsx("div",{className:"absolute inset-0 bg-background/40"}),p.jsxs("div",{className:"relative z-10 min-h-screen flex flex-col",children:[p.jsxs(Ci,{focusKey:"home-header",as:"header",className:"flex items-center justify-between px-4 sm:px-6 md:px-8 pt-4 sm:pt-6 gap-2",children:[p.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:p.jsx(ri,{className:"w-5 h-5 text-muted-foreground"})}),p.jsx(gt.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"}),p.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 shrink-0",children:[p.jsx(v5,{testId:"index-header-clock"}),p.jsx(Pm,{align:"right"}),!c&&p.jsx(wi,{focusKey:"home-header-add","data-testid":"index-add-server-btn",onEnter:()=>e(!0),onClick:()=>e(!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 outline-none",children:p.jsx(_o,{className:"w-5 h-5 text-muted-foreground"})}),!c&&p.jsx(wi,{focusKey:"home-header-settings",onEnter:()=>n("/account"),onClick:()=>n("/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 outline-none",children:p.jsx(jj,{className:"w-5 h-5 text-muted-foreground"})}),c?p.jsxs(wi,{focusKey:"home-header-logout","data-testid":"index-logout-btn",onEnter:y,onClick:y,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 outline-none",children:[p.jsx(Nj,{className:"w-4 h-4"}),p.jsx("span",{className:"hidden sm:inline",children:r("home.logout")})]}):p.jsx(wi,{focusKey:"home-header-profile",onEnter:()=>n("/welcome"),onClick:()=>n("/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 outline-none",children:p.jsx(Ji,{className:"w-5 h-5 text-muted-foreground"})})]})]}),c?p.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:[p.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[p.jsx(Ul,{className:"w-5 h-5 text-primary gold-glow shrink-0"}),p.jsxs("div",{className:"min-w-0",children:[p.jsxs("p",{className:"text-foreground text-sm font-medium truncate",children:[a==null?void 0:a.username,p.jsxs("span",{className:"ms-2 text-muted-foreground text-xs",children:["· ",r("home.subscriber")]})]}),p.jsx("p",{className:"text-[10px] sm:text-[11px] tracking-[0.12em] sm:tracking-[0.15em] uppercase text-muted-foreground",children:m?p.jsxs(p.Fragment,{children:[r("home.expires")," ",p.jsx("span",{className:"text-foreground",children:new Date(m).toLocaleDateString()})]}):r("home.noExpiry")})]})]}),p.jsx("div",{className:"flex items-center gap-3",children:p.jsx("span",{className:`px-3 py-1.5 rounded-full text-[11px] sm:text-xs font-medium tracking-wider ${f?"bg-destructive/20 text-destructive border border-destructive/40":h!=null&&h<=3?"bg-amber-500/20 text-amber-400 border border-amber-500/40":"bg-primary/15 text-primary border border-primary/40"}`,children:f?r("home.expired"):h!=null?r("home.daysRemaining",{count:h}):""})})]}):s&&p.jsx("div",{className:"text-center mt-2",children:p.jsxs("span",{className:"text-muted-foreground text-xs",children:[r("home.profile"),":"," ",p.jsx("span",{className:"text-primary",children:s.name})]})}),o&&!a&&p.jsx("div",{className:"text-center mt-2",children:p.jsx("span",{className:"text-muted-foreground text-[10px] sm:text-[11px] tracking-[0.3em] uppercase",children:r("home.guestMode")})}),p.jsx("main",{className:"flex-1 flex items-center justify-center px-2 sm:px-4 pt-4 pb-20 sm:pb-12",children:p.jsx(Ci,{autoFocus:!0,focusKey:"home-categories",className:"flex flex-wrap items-center justify-center gap-3 sm:gap-4 md:gap-6 w-full max-w-4xl","data-testid":"home-categories-row",children:Bue.map((v,_)=>p.jsx(Uue,{title:r(`home.categories.${v.key}`),count:r(`home.categories.${v.key}Count`),icon:v.icon,index:_,route:v.route},v.key))})})]}),!c&&p.jsx(y5,{open:t,onClose:()=>e(!1),onSubmit:async v=>{await i(v)&&e(!1)}}),c&&f&&p.jsx(Pue,{username:(a==null?void 0:a.username)||"subscriber",whatsappNumber:g,onLogout:y})]})},au=({title:t,children:e})=>{const n=lr(),{t:r}=wr();return p.jsxs("div",{className:"relative h-screen w-full overflow-hidden",children:[p.jsx("div",{className:"absolute inset-0 bg-cover bg-center bg-no-repeat",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),p.jsx("div",{className:"absolute inset-0 bg-background/40"}),p.jsxs("div",{className:"relative z-10 h-screen flex flex-col min-h-0",children:[p.jsxs("header",{className:"flex items-center justify-between px-4 sm:px-6 pt-4 gap-2 shrink-0",children:[p.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:p.jsx(Ph,{className:"w-5 h-5 text-muted-foreground rtl:rotate-180"})}),p.jsx(gt.h1,{initial:{opacity:0},animate:{opacity:1},className:"font-display text-base sm:text-xl tracking-[0.2em] gold-text truncate",children:t}),p.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[p.jsx(v5,{testId:"page-header-clock"}),p.jsx(Pm,{align:"right"}),p.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:p.jsx(jj,{className:"w-4 h-4 text-muted-foreground"})}),p.jsx("button",{onClick:()=>n("/account"),className:"w-9 h-9 rounded-full border-2 border-primary/50 glass flex items-center justify-center",children:p.jsx(Ji,{className:"w-4 h-4 text-muted-foreground"})})]})]}),p.jsx("main",{className:"flex-1 min-h-0 overflow-hidden px-3 sm:px-4 pt-3 pb-16 sm:pb-4",children:e})]})]})},tt=Number.isFinite||function(t){return typeof t=="number"&&isFinite(t)},$ue=Number.isSafeInteger||function(t){return typeof t=="number"&&Math.abs(t)<=Vue},Vue=Number.MAX_SAFE_INTEGER||9007199254740991;let ft=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}({}),Se=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}({}),B=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 Kt={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},rt={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class Bu{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 Gue{constructor(e,n,r,s=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 Bu(e),this.fast_=new Bu(n),this.defaultTTFB_=s,this.ttfb_=new Bu(e)}update(e,n){const{slow_:r,fast_:s,ttfb_:i}=this;r.halfLife!==e&&(this.slow_=new Bu(e,r.getEstimate(),r.getTotalWeight())),s.halfLife!==n&&(this.fast_=new Bu(n,s.getEstimate(),s.getTotalWeight())),i.halfLife!==e&&(this.ttfb_=new Bu(e,i.getEstimate(),i.getTotalWeight()))}sample(e,n){e=Math.max(e,this.minDelayMs_);const r=8*n,s=e/1e3,i=r/s;this.fast_.sample(s,i),this.slow_.sample(s,i)}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 Kue(t,e,n){return(e=zue(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function vn(){return vn=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},vn.apply(null,arguments)}function XP(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),n.push.apply(n,r)}return n}function hn(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?XP(Object(n),!0).forEach(function(r){Kue(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):XP(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Hue(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 zue(t){var e=Hue(t,"string");return typeof e=="symbol"?e:e+""}class Ii{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=Zo,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 Zo=function(){},que={trace:Zo,debug:Zo,log:Zo,warn:Zo,info:Zo,error:Zo};function xw(){return vn({},que)}function Wue(t,e){const n=self.console[t];return n?n.bind(self.console,`${e?"["+e+"] ":""}[${t}] >`):Zo}function QP(t,e,n){return e[t]?e[t].bind(e):Wue(t,n)}const Sw=xw();function Yue(t,e,n){const r=xw();if(typeof console=="object"&&t===!0||typeof t=="object"){const s=["debug","log","info","warn","error"];s.forEach(i=>{r[i]=QP(i,t,n)});try{r.log(`Debug logs enabled for "${e}" in hls.js version 1.6.16`)}catch{return xw()}s.forEach(i=>{Sw[i]=QP(i,t)})}else vn(Sw,r);return r}const fn=Sw;function Hl(t=!0){return typeof self>"u"?void 0:(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Xue(t){return typeof self<"u"&&t===self.ManagedMediaSource}function _5(t,e){const n=Object.keys(t),r=Object.keys(e),s=n.length,i=r.length;return!s||!i||s===i&&!n.some(a=>r.indexOf(a)===-1)}function ti(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,s,i,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:s=t[o++],a+=String.fromCharCode((r&31)<<6|s&63);break;case 14:s=t[o++],i=t[o++],a+=String.fromCharCode((r&15)<<12|(s&63)<<6|(i&63)<<0);break}}return a}function Vr(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 b5(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Que(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var px={exports:{}},JP;function Jue(){return JP||(JP=1,function(t,e){(function(n){var r=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/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 m=s.exec(f.path);f.netLoc=m[1],f.path=m[2]}f.netLoc&&!f.path&&(f.path="/");var g={scheme:f.scheme,netLoc:h.netLoc,path:null,params:h.params,query:h.query,fragment:h.fragment};if(!h.netLoc&&(g.netLoc=f.netLoc,h.path[0]!=="/"))if(!h.path)g.path=f.path,h.params||(g.params=f.params,h.query||(g.query=f.query));else{var y=f.path,v=y.substring(0,y.lastIndexOf("/")+1)+h.path;g.path=o.normalizePath(v)}return g.path===null&&(g.path=u.alwaysNormalize?o.normalizePath(h.path):h.path),o.buildURLFromParts(g)},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(i,"");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})()}(px)),px.exports}var _A=Jue();class bA{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 bn={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class x5{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,ede(this,"stats")}setByteRange(e,n){const r=e.split("@",2);let s;r.length===1?s=(n==null?void 0:n.byteRangeEndOffset)||0:s=parseInt(r[1]),this._byteRange=[s,parseInt(r[0])+s]}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={[bn.AUDIO]:null,[bn.VIDEO]:null,[bn.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 bA),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=_A.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[bn.AUDIO]=null,e[bn.VIDEO]=null,e[bn.AUDIOVIDEO]=null}}function ar(t){return t.sn!=="initSegment"}class mx extends x5{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(tt(e)&&tt(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 s=this._decryptdata=n[r[0]]||null;s&&(this._decryptdata=s.getDecryptData(this.sn,n))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=tt(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),s=r.length;if(s>1||s===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(!tt(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return ar(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 s=n[e];s&&!((r=this._decryptdata)!=null&&r.keyId)&&(this._decryptdata=s.getDecryptData(this.sn,n))}}abortRequests(){var e,n;(e=this.loader)==null||e.abort(),(n=this.keyLoader)==null||n.abort()}setElementaryStreamInfo(e,n,r,s,i,a=!1){const{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:n,endPTS:r,startDTS:s,endDTS:i,partial:a};return}l.startPTS=Math.min(l.startPTS,n),l.endPTS=Math.max(l.endPTS,r),l.startDTS=Math.min(l.startDTS,s),l.endDTS=Math.max(l.endDTS,i)}}class Zue extends x5{constructor(e,n,r,s,i){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=s;const a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,i),i&&(this.fragOffset=i.fragOffset+i.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 S5(t,e){const n=Object.getPrototypeOf(t);if(n){const r=Object.getOwnPropertyDescriptor(n,e);return r||S5(n,e)}}function ede(t,e){const n=S5(t,e);n&&(n.enumerable=!0,Object.defineProperty(t,e,n))}const ZP=Math.pow(2,32)-1,tde=[].push,E5={video:1,audio:2,id3:3,text:4};function _r(t){return String.fromCharCode.apply(null,t)}function w5(t,e){const n=t[e]<<8|t[e+1];return n<0?65536+n:n}function Rt(t,e){const n=T5(t,e);return n<0?4294967296+n:n}function eD(t,e){let n=Rt(t,e);return n*=Math.pow(2,32),n+=Rt(t,e+4),n}function T5(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function nde(t){const e=t.byteLength;for(let n=0;n<e;){const r=Rt(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 Ft(t,e){const n=[];if(!e.length)return n;const r=t.byteLength;for(let s=0;s<r;){const i=Rt(t,s),a=_r(t.subarray(s+4,s+8)),o=i>1?s+i:r;if(a===e[0])if(e.length===1)n.push(t.subarray(s+8,o));else{const l=Ft(t.subarray(s+8,o),e.slice(1));l.length&&tde.apply(n,l)}s=o}return n}function rde(t){const e=[],n=t[0];let r=8;const s=Rt(t,r);r+=4;let i=0,a=0;n===0?(i=Rt(t,r),a=Rt(t,r+4),r+=8):(i=eD(t,r),a=eD(t,r+8),r+=16),r+=2;let o=t.length+a;const l=w5(t,r);r+=2;for(let c=0;c<l;c++){let u=r;const d=Rt(t,u);u+=4;const h=d&2147483647;if((d&2147483648)>>>31===1)return fn.warn("SIDX has hierarchical references (not supported)"),null;const m=Rt(t,u);u+=4,e.push({referenceSize:h,subsegmentDuration:m,info:{duration:m/s,start:o,end:o+h-1}}),o+=h,u+=4,r=u}return{earliestPresentationTime:i,timescale:s,version:n,referencesCount:l,references:e}}function A5(t){const e=[],n=Ft(t,["moov","trak"]);for(let s=0;s<n.length;s++){const i=n[s],a=Ft(i,["tkhd"])[0];if(a){let o=a[0];const l=Rt(a,o===0?12:20),c=Ft(i,["mdia","mdhd"])[0];if(c){o=c[0];const u=Rt(c,o===0?12:20),d=Ft(i,["mdia","hdlr"])[0];if(d){const h=_r(d.subarray(8,12)),f={soun:bn.AUDIO,vide:bn.VIDEO}[h],m=Ft(i,["mdia","minf","stbl","stsd"])[0],g=sde(m);f?(e[l]={timescale:u,type:f,stsd:g},e[f]=hn({timescale:u,id:l},g)):e[l]={timescale:u,type:h,stsd:g}}}}}return Ft(t,["moov","mvex","trex"]).forEach(s=>{const i=Rt(s,4),a=e[i];a&&(a.default={duration:Rt(s,12),flags:Rt(s,20)})}),e}function sde(t){const e=t.subarray(8),n=e.subarray(86),r=_r(e.subarray(4,8));let s=r,i;const a=r==="enca"||r==="encv";if(a){const c=Ft(e,[r])[0].subarray(r==="enca"?28:78);Ft(c,["sinf"]).forEach(d=>{const h=Ft(d,["schm"])[0];if(h){const f=_r(h.subarray(4,8));if(f==="cbcs"||f==="cenc"){const m=Ft(d,["frma"])[0];m&&(s=_r(m))}}})}const o=s;switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const l=Ft(n,["avcC"])[0];l&&l.length>3&&(s+="."+Bg(l[1])+Bg(l[2])+Bg(l[3]),i=Ug(o==="avc1"?"dva1":"dvav",n));break}case"mp4a":{const l=Ft(e,[r])[0],c=Ft(l.subarray(28),["esds"])[0];if(c&&c.length>7){let u=4;if(c[u++]!==3)break;u=gx(c,u),u+=2;const d=c[u++];if(d&128&&(u+=2),d&64&&(u+=c[u++]),c[u++]!==4)break;u=gx(c,u);const h=c[u++];if(h===64)s+="."+Bg(h);else break;if(u+=12,c[u++]!==5)break;u=gx(c,u);const f=c[u++];let m=(f&248)>>3;m===31&&(m+=1+((f&7)<<3)+((c[u]&224)>>5)),s+="."+m}break}case"hvc1":case"hev1":{const l=Ft(n,["hvcC"])[0];if(l&&l.length>12){const c=l[1],u=["","A","B","C"][c>>6],d=c&31,h=Rt(l,2),f=(c&32)>>5?"H":"L",m=l[12],g=l.subarray(6,12);s+="."+u+d,s+="."+ide(h).toString(16).toUpperCase(),s+="."+f+m;let y="";for(let v=g.length;v--;){const _=g[v];(_||y)&&(y="."+_.toString(16).toUpperCase()+y)}s+=y}i=Ug(o=="hev1"?"dvhe":"dvh1",n);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{s=Ug(s,n)||s;break}case"vp09":{const l=Ft(n,["vpcC"])[0];if(l&&l.length>6){const c=l[4],u=l[5],d=l[6]>>4&15;s+="."+oa(c)+"."+oa(u)+"."+oa(d)}break}case"av01":{const l=Ft(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,m=c===2&&h?f?12:10:h?10:8,g=(l[2]&16)>>4,y=(l[2]&8)>>3,v=(l[2]&4)>>2,_=l[2]&3;s+="."+c+"."+oa(u)+d+"."+oa(m)+"."+g+"."+y+v+_+"."+oa(1)+"."+oa(1)+"."+oa(1)+"."+0,i=Ug("dav1",n)}break}}return{codec:s,encrypted:a,supplemental:i}}function Ug(t,e){const n=Ft(e,["dvvC"]),r=n.length?n[0]:Ft(e,["dvcC"])[0];if(r){const s=r[2]>>1&127,i=r[2]<<5&32|r[3]>>3&31;return t+"."+oa(s)+"."+oa(i)}}function ide(t){let e=0;for(let n=0;n<32;n++)e|=(t>>n&1)<<31-n;return e>>>0}function gx(t,e){const n=e+5;for(;t[e++]&128&&e<n;);return e}function Bg(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function oa(t){return(t<10?"0":"")+t}function ade(t,e){if(!t||!e)return;const n=e.keyId;n&&e.isCommonEncryption&&R5(t,(r,s)=>{const i=r.subarray(8,24);i.some(a=>a!==0)||(fn.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${Vr(i)} -> ${Vr(n)}`),r.set(n,8))})}function ode(t){const e=[];return R5(t,n=>e.push(n.subarray(8,24))),e}function R5(t,e){Ft(t,["moov","trak"]).forEach(r=>{const s=Ft(r,["mdia","minf","stbl","stsd"])[0];if(!s)return;const i=s.subarray(8);let a=Ft(i,["enca"]);const o=a.length>0;o||(a=Ft(i,["encv"])),a.forEach(l=>{const c=o?l.subarray(28):l.subarray(78);Ft(c,["sinf"]).forEach(d=>{const h=C5(d);h&&e(h,o)})})})}function C5(t){const e=Ft(t,["schm"])[0];if(e){const n=_r(e.subarray(4,8));if(n==="cbcs"||n==="cenc"){const r=Ft(t,["schi","tenc"])[0];if(r)return r}}}function lde(t,e,n){const r={},s=Ft(t,["moof","traf"]);for(let i=0;i<s.length;i++){const a=s[i],o=Ft(a,["tfhd"])[0],l=Rt(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=Ft(a,["tfdt"])[0];if(d){const S=d[0];let E=Rt(d,4);S===1&&(E===ZP?n.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(E*=ZP+1,E+=Rt(d,8))),tt(E)&&(!tt(u.start)||E<u.start)&&(u.start=E)}const h=c.default,f=Rt(o,0)|(h==null?void 0:h.flags);let m=(h==null?void 0:h.duration)||0;f&8&&(f&2?m=Rt(o,12):m=Rt(o,8));const g=Ft(a,["trun"]);let y=u.start||0,v=0,_=m;for(let S=0;S<g.length;S++){const E=g[S],L=Rt(E,4),U=u.sampleCount;u.sampleCount+=L;const P=E[3]&1,I=E[3]&4,k=E[2]&1,R=E[2]&2,M=E[2]&4,G=E[2]&8;let Y=8,q=L;for(P&&(Y+=4),I&&L&&(!(E[Y+1]&1)&&u.keyFrameIndex===void 0&&(u.keyFrameIndex=U),Y+=4,k?(_=Rt(E,Y),Y+=4):_=m,R&&(Y+=4),G&&(Y+=4),y+=_,v+=_,q--);q--;)k?(_=Rt(E,Y),Y+=4):_=m,R&&(Y+=4),M&&(E[Y+1]&1||u.keyFrameIndex===void 0&&(u.keyFrameIndex=u.sampleCount-(q+1),u.keyFrameStart=y),Y+=4),G&&(Y+=4),y+=_,v+=_;!v&&m&&(v+=m*L)}u.duration+=v}if(!Object.keys(r).some(i=>r[i].duration)){let i=1/0,a=0;const o=Ft(t,["sidx"]);for(let l=0;l<o.length;l++){const c=rde(o[l]);if(c!=null&&c.references){i=Math.min(i,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&&tt(a)&&Object.keys(r).forEach(l=>{r[l].duration||(r[l].duration=a*r[l].timescale-r[l].start)})}return r}function cde(t){const e={valid:null,remainder:null},n=Ft(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 ki(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}function tD(t,e){const n=[],r=e.samples,s=e.timescale,i=e.id;let a=!1;return Ft(r,["moof"]).map(l=>{const c=l.byteOffset-8;Ft(l,["traf"]).map(d=>{const h=Ft(d,["tfdt"]).map(f=>{const m=f[0];let g=Rt(f,4);return m===1&&(g*=Math.pow(2,32),g+=Rt(f,8)),g/s})[0];return h!==void 0&&(t=h),Ft(d,["tfhd"]).map(f=>{const m=Rt(f,4),g=Rt(f,0)&16777215,y=(g&1)!==0,v=(g&2)!==0,_=(g&8)!==0;let S=0;const E=(g&16)!==0;let L=0;const U=(g&32)!==0;let P=8;m===i&&(y&&(P+=8),v&&(P+=4),_&&(S=Rt(f,P),P+=4),E&&(L=Rt(f,P),P+=4),U&&(P+=4),e.type==="video"&&(a=t_(e.codec)),Ft(d,["trun"]).map(I=>{const k=I[0],R=Rt(I,0)&16777215,M=(R&1)!==0;let G=0;const Y=(R&4)!==0,q=(R&256)!==0;let X=0;const Z=(R&512)!==0;let oe=0;const ne=(R&1024)!==0,H=(R&2048)!==0;let K=0;const J=Rt(I,4);let Q=8;M&&(G=Rt(I,Q),Q+=4),Y&&(Q+=4);let ve=G+c;for(let Te=0;Te<J;Te++){if(q?(X=Rt(I,Q),Q+=4):X=S,Z?(oe=Rt(I,Q),Q+=4):oe=L,ne&&(Q+=4),H&&(k===0?K=Rt(I,Q):K=T5(I,Q),Q+=4),e.type===bn.VIDEO){let Ne=0;for(;Ne<oe;){const Ke=Rt(r,ve);if(ve+=4,ude(a,r[ve])){const be=r.subarray(ve,ve+Ke);xA(be,a?2:1,t+K/s,n)}ve+=Ke,Ne+=Ke+4}}t+=X/s}}))})})}),n}function t_(t){if(!t)return!1;const e=t.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function ude(t,e){if(t){const n=e>>1&63;return n===39||n===40}else return(e&31)===6}function xA(t,e,n,r){const s=k5(t);let i=0;i+=e;let a=0,o=0,l=0;for(;i<s.length;){a=0;do{if(i>=s.length)break;l=s[i++],a+=l}while(l===255);o=0;do{if(i>=s.length)break;l=s[i++],o+=l}while(l===255);const c=s.length-i;let u=i;if(o<c)i+=o;else if(o>c){fn.error(`Malformed SEI payload. ${o} is too small, only ${c} bytes left to parse.`);break}if(a===4){if(s[u++]===181){const h=w5(s,u);if(u+=2,h===49){const f=Rt(s,u);if(u+=4,f===1195456820){const m=s[u++];if(m===3){const g=s[u++],y=31&g,v=64&g,_=v?2+y*3:0,S=new Uint8Array(_);if(v){S[0]=g;for(let E=1;E<_;E++)S[E]=s[u++]}r.push({type:m,payloadType:a,pts:n,bytes:S})}}}}}else if(a===5&&o>16){const d=[];for(let m=0;m<16;m++){const g=s[u++].toString(16);d.push(g.length==1?"0"+g:g),(m===3||m===5||m===7||m===9)&&d.push("-")}const h=o-16,f=new Uint8Array(h);for(let m=0;m<h;m++)f[m]=s[u++];r.push({payloadType:a,pts:n,uuid:d.join(""),userData:ti(f),userDataBytes:f})}}}function k5(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 s=e-n.length,i=new Uint8Array(s);let a=0;for(r=0;r<s;a++,r++)a===n[0]&&(a++,n.shift()),i[r]=t[a];return i}function dde(t){const e=t[0];let n="",r="",s=0,i=0,a=0,o=0,l=0,c=0;if(e===0){for(;_r(t.subarray(c,c+1))!=="\0";)n+=_r(t.subarray(c,c+1)),c+=1;for(n+=_r(t.subarray(c,c+1)),c+=1;_r(t.subarray(c,c+1))!=="\0";)r+=_r(t.subarray(c,c+1)),c+=1;r+=_r(t.subarray(c,c+1)),c+=1,s=Rt(t,12),i=Rt(t,16),o=Rt(t,20),l=Rt(t,24),c=28}else if(e===1){c+=4,s=Rt(t,c),c+=4;const d=Rt(t,c);c+=4;const h=Rt(t,c);for(c+=4,a=2**32*d+h,$ue(a)||(a=Number.MAX_SAFE_INTEGER,fn.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Rt(t,c),c+=4,l=Rt(t,c),c+=4;_r(t.subarray(c,c+1))!=="\0";)n+=_r(t.subarray(c,c+1)),c+=1;for(n+=_r(t.subarray(c,c+1)),c+=1;_r(t.subarray(c,c+1))!=="\0";)r+=_r(t.subarray(c,c+1)),c+=1;r+=_r(t.subarray(c,c+1)),c+=1}const u=t.subarray(c,t.byteLength);return{schemeIdUri:n,value:r,timeScale:s,presentationTime:a,presentationTimeDelta:i,eventDuration:o,id:l,payload:u}}function hde(t,...e){const n=e.length;let r=8,s=n;for(;s--;)r+=e[s].byteLength;const i=new Uint8Array(r);for(i[0]=r>>24&255,i[1]=r>>16&255,i[2]=r>>8&255,i[3]=r&255,i.set(t,4),s=0,r=8;s<n;s++)i.set(e[s],r),r+=e[s].byteLength;return i}function fde(t,e,n){if(t.byteLength!==16)throw new RangeError("Invalid system id");let r,s;r=0,s=new Uint8Array;let i;r>0?(i=new Uint8Array(4),e.length>0&&new DataView(i.buffer).setUint32(0,e.length,!1)):i=new Uint8Array;const a=new Uint8Array(4);return n.byteLength>0&&new DataView(a.buffer).setUint32(0,n.byteLength,!1),hde([112,115,115,104],new Uint8Array([r,0,0,0]),t,i,s,a,n)}function pde(t){const e=[];if(t instanceof ArrayBuffer){const n=t.byteLength;let r=0;for(;r+32<n;){const s=new DataView(t,r),i=mde(s);e.push(i),r+=i.size}}return e}function mde(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 i=t.getUint32(8)>>>24;if(i!==0&&i!==1)return{offset:n,size:e};const a=t.buffer,o=Vr(new Uint8Array(a,n+12,16));let l=null,c=null,u=0;if(i===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:i,systemId:o,kids:l,data:c,offset:n,size:e})}const L5=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),bh={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 SA(t,e){const n=bh[e];return!!n&&!!n[t.slice(0,4)]}function $p(t,e,n=!0){return!t.split(",").some(r=>!EA(r,e,n))}function EA(t,e,n=!0){var r;const s=Hl(n);return(r=s==null?void 0:s.isTypeSupported(Vp(t,e)))!=null?r:!1}function Vp(t,e){return`${e}/mp4;codecs=${t}`}function nD(t){if(t){const e=t.substring(0,4);return bh.video[e]}return 2}function V0(t){const e=L5();return t.split(",").reduce((n,r)=>{const i=e&&t_(r)?9:bh.video[r];return i?(i*2+n)/(n?3:2):(bh.audio[r]+n)/(n?2:1)},0)}const yx={};function gde(t,e=!0){if(yx[t])return yx[t];const n={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let s=0;s<n.length;s++){var r;if(EA(n[s],"audio",e))return yx[t]=n[s],n[s];if(n[s]==="mp3"&&(r=Hl(e))!=null&&r.isTypeSupported("audio/mpeg"))return""}return t}const yde=/flac|opus|mp4a\.40\.34/i;function G0(t,e=!0){return t.replace(yde,n=>gde(n.toLowerCase(),e))}function vde(t,e){const n=[];if(t){const r=t.split(",");for(let s=0;s<r.length;s++)SA(r[s],"video")||n.push(r[s])}return e&&n.push(e),n.join(",")}function Cy(t,e){if(t&&(t.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t)!==-1)&&(rD(t,"audio")||rD(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 rD(t,e){return SA(t,e)&&EA(t,e)}function _de(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 bde(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 sD(t){const e=Hl(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 Ew(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const xde={supported:!0,powerEfficient:!0,smooth:!0},Sde={supported:!1,smooth:!1,powerEfficient:!1},I5={supported:!0,configurations:[],decodingInfoResults:[xde]};function P5(t,e){return{supported:!1,configurations:e,decodingInfoResults:[Sde],error:t}}function Ede(t,e,n,r,s,i){const a=t.videoCodec,o=t.audioCodec?t.audioGroups:null,l=i==null?void 0:i.audioCodec,c=i==null?void 0:i.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 m=e.groups[f];if(!m)throw new Error(`Audio track group ${f} not found`);Object.keys(m.channels).forEach(g=>{h[g]=(h[g]||0)+m.channels[g]})}return h},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(h=>t_(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(s,8e6))||!!d&&tt(u)&&Object.keys(d).some(h=>parseInt(h)>u)}function D5(t,e,n,r={}){const s=t.videoCodec;if(!s&&!t.audioCodec||!n)return Promise.resolve(I5);const i=[],a=wde(t),o=a.length,l=Tde(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)}i.push(d)}if(s){const u=navigator.userAgent;if(s.split(",").some(d=>t_(d))&&L5())return Promise.resolve(P5(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),i))}return Promise.all(i.map(u=>{const d=Rde(u);return r[d]||(r[d]=n.decodingInfo(u))})).then(u=>({supported:!u.some(d=>!d.supported),configurations:i,decodingInfoResults:u})).catch(u=>({supported:!1,configurations:i,decodingInfoResults:[],error:u}))}function wde(t){var e;const n=(e=t.videoCodec)==null?void 0:e.split(","),r=O5(t),s=t.width||640,i=t.height||480,a=t.frameRate||30,o=t.videoRange.toLowerCase();return n?n.map(l=>{const c={contentType:Vp(bde(l),"video"),width:s,height:i,bitrate:r,framerate:a};return o!=="sdr"&&(c.transferFunction=o),c}):[]}function Tde(t,e,n){var r;const s=(r=t.audioCodec)==null?void 0:r.split(","),i=O5(t);return s&&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||"");s.forEach(f=>{const m={contentType:Vp(f,"audio"),bitrate:n?Ade(f,i):i};h&&(m.channels=""+h),u.push(m)})}return u},a):a},[]):[]}function Ade(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 O5(t){return Math.ceil(Math.max(t.bitrate*.9,t.averageBitrate)/1e3)*1e3||1}function Rde(t){let e="";const{audio:n,video:r}=t;if(r){const s=Ew(r.contentType);e+=`${s}_r${r.height}x${r.width}f${Math.ceil(r.framerate)}${r.transferFunction||"sd"}_${Math.ceil(r.bitrate/1e5)}`}if(n){const s=Ew(n.contentType);e+=`${r?"_":""}${s}_c${n.channels}`}return e}const ww=["NONE","TYPE-0","TYPE-1",null];function Cde(t){return ww.indexOf(t)>-1}const K0=["SDR","PQ","HLG"];function kde(t){return!!t&&K0.indexOf(t)>-1}var ky={No:"",Yes:"YES",v2:"v2"};function iD(t){const{canSkipUntil:e,canSkipDateRanges:n,age:r}=t,s=r<e/2;return e&&s?n?ky.v2:ky.Yes:ky.No}class aD{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 Gp{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 oD(this._audioGroups,e)}hasSubtitleGroup(e){return oD(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 oD(t,e){return!e||!t?!1:t.indexOf(e)!==-1}function Lde(){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 Ide(t,e){let n=!1,r=[];if(t&&(n=t!=="SDR",r=[t]),e){r=e.allowedVideoRanges||K0.slice(0);const s=r.join("")!=="SDR"&&!e.videoCodec;n=e.preferHDR!==void 0?e.preferHDR:s&&Lde(),n||(r=["SDR"])}return{preferHDR:n,allowedVideoRanges:r}}const Pde=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}},En=(t,e)=>JSON.stringify(t,Pde(e));function Dde(t,e,n,r,s){const i=Object.keys(t),a=r==null?void 0:r.channels,o=r==null?void 0:r.audioCodec,l=s==null?void 0:s.videoCodec,c=a&&parseInt(a)===2;let u=!1,d=!1,h=1/0,f=1/0,m=1/0,g=1/0,y=0,v=[];const{preferHDR:_,allowedVideoRanges:S}=Ide(e,s);for(let I=i.length;I--;){const k=t[i[I]];u||(u=k.channels[2]>0),h=Math.min(h,k.minHeight),f=Math.min(f,k.minFramerate),m=Math.min(m,k.minBitrate),S.filter(M=>k.videoRanges[M]>0).length>0&&(d=!0)}h=tt(h)?h:0,f=tt(f)?f:0;const E=Math.max(1080,h),L=Math.max(30,f);m=tt(m)?m:n,n=Math.max(m,n),d||(e=void 0);const U=i.length>1;return{codecSet:i.reduce((I,k)=>{const R=t[k];if(k===I)return I;if(v=d?S.filter(M=>R.videoRanges[M]>0):[],U){if(R.minBitrate>n)return sa(k,`min bitrate of ${R.minBitrate} > current estimate of ${n}`),I;if(!R.hasDefaultAudio)return sa(k,"no renditions with default or auto-select sound found"),I;if(o&&k.indexOf(o.substring(0,4))%5!==0)return sa(k,`audio codec preference "${o}" not found`),I;if(a&&!c){if(!R.channels[a])return sa(k,`no renditions with ${a} channel sound found (channels options: ${Object.keys(R.channels)})`),I}else if((!o||c)&&u&&R.channels[2]===0)return sa(k,"no renditions with stereo sound found"),I;if(R.minHeight>E)return sa(k,`min resolution of ${R.minHeight} > maximum of ${E}`),I;if(R.minFramerate>L)return sa(k,`min framerate of ${R.minFramerate} > maximum of ${L}`),I;if(!v.some(M=>R.videoRanges[M]>0))return sa(k,`no variants with VIDEO-RANGE of ${En(v)} found`),I;if(l&&k.indexOf(l.substring(0,4))%5!==0)return sa(k,`video codec preference "${l}" not found`),I;if(R.maxScore<y)return sa(k,`max score of ${R.maxScore} < selected max of ${y}`),I}return I&&(V0(k)>=V0(I)||R.fragmentError>t[I].fragmentError)?I:(g=R.minIndex,y=R.maxScore,k)},void 0),videoRanges:v,preferHDR:_,minFramerate:f,minBitrate:m,minIndex:g}}function sa(t,e){fn.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function N5(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 s=n.channels||"2";return r.channels[s]=(r.channels[s]||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 Ode(t,e,n,r){return t.slice(n,r+1).reduce((s,i,a)=>{if(!i.codecSet)return s;const o=i.audioGroups;let l=s[i.codecSet];l||(s[i.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,i.bitrate);const c=Math.min(i.height,i.width);return l.minHeight=Math.min(l.minHeight,c),l.minFramerate=Math.min(l.minFramerate,i.frameRate),l.minIndex=Math.min(l.minIndex,a),l.maxScore=Math.max(l.maxScore,i.score),l.fragmentError+=i.fragmentError,l.videoRanges[i.videoRange]=(l.videoRanges[i.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]}))}),s},{})}function lD(t){if(!t)return t;const{lang:e,assocLang:n,characteristics:r,channels:s,audioCodec:i}=t;return{lang:e,assocLang:n,characteristics:r,channels:s,audioCodec:i}}function xa(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 s=e[r];if(Wc(t,s,n))return r}return-1}function Wc(t,e,n){const{groupId:r,name:s,lang:i,assocLang:a,default:o}=t,l=t.forced;return(r===void 0||e.groupId===r)&&(s===void 0||e.name===s)&&(i===void 0||Nde(i,e.lang))&&(i===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(l===void 0||e.forced===l)&&(!("characteristics"in t)||Mde(t.characteristics||"",e.characteristics))&&(n===void 0||n(t,e))}function Nde(t,e="--"){return t.length===e.length?t===e:t.startsWith(e)||e.startsWith(t)}function Mde(t,e=""){const n=t.split(","),r=e.split(",");return n.length===r.length&&!n.some(s=>r.indexOf(s)===-1)}function vc(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 jde(t,e,n,r,s){const i=e[r],o=e.reduce((h,f,m)=>{const g=f.uri;return(h[g]||(h[g]=[])).push(m),h},{})[i.uri];o.length>1&&(r=Math.max.apply(Math,o));const l=i.videoRange,c=i.frameRate,u=i.codecSet.substring(0,4),d=cD(e,r,h=>{if(h.videoRange!==l||h.frameRate!==c||h.codecSet.substring(0,4)!==u)return!1;const f=h.audioGroups,m=n.filter(g=>!f||f.indexOf(g.groupId)!==-1);return xa(t,m,s)>-1});return d>-1?d:cD(e,r,h=>{const f=h.audioGroups,m=n.filter(g=>!f||f.indexOf(g.groupId)!==-1);return xa(t,m,s)>-1})}function cD(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 H0(t,e){var n;return!!t&&t!==((n=e.loadLevelObj)==null?void 0:n.uri)}class Ude extends Ii{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:s,partCurrent:i,hls:a}=this,{autoLevelEnabled:o,media:l}=a;if(!s||!l)return;const c=performance.now(),u=i?i.stats:s.stats,d=i?i.duration:s.duration,h=c-u.loading.start,f=a.minAutoLevel,m=s.level,g=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||m<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const y=g>-1&&g!==m,v=!!n||y;if(!v&&(l.paused||!l.playbackRate||!l.readyState))return;const _=a.mainForwardBufferInfo;if(!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=_?_.len/E:0,U=u.loading.first?u.loading.first-u.loading.start:-1,P=u.loaded&&U>-1,I=this.getBwEstimate(),k=a.levels,R=k[m],M=Math.max(u.loaded,Math.round(d*(s.bitrate||R.averageBitrate)/8));let G=P?h-U:h;G<1&&P&&(G=Math.min(h,u.loaded*8/I));const Y=P?u.loaded*1e3/G:0,q=S/1e3,X=Y?(M-u.loaded)/Y:M*8/I+q;if(X<=L)return;const Z=Y?Y*8:I,oe=((r=(n==null?void 0:n.details)||this.hls.latestLevelDetails)==null?void 0:r.live)===!0,ne=this.hls.config.abrBandWidthUpFactor;let H=Number.POSITIVE_INFINITY,K;for(K=m-1;K>f;K--){const Te=k[K].maxBitrate,Ne=!k[K].details||oe;if(H=this.getTimeToLoadFrag(q,Z,d*Te,Ne),H<Math.min(L,d+q))break}if(H>=X||H>d*10)return;P?this.bwEstimator.sample(h-Math.min(S,U),u.loaded):this.bwEstimator.sampleTTFB(h);const J=k[K].maxBitrate;this.getBwEstimate()*ne>J&&this.resetEstimator(J);const Q=this.findBestLevel(J,f,K,0,L,1,1);Q>-1&&(K=Q),this.warn(`Fragment ${s.sn}${i?" part "+i.index:""} of level ${m} is loading too slowly;
      Fragment duration: ${s.duration.toFixed(3)}
      Time to underbuffer: ${L.toFixed(3)} s
      Estimated load time for current fragment: ${X.toFixed(3)} s
      Estimated load time for down switch fragment: ${H.toFixed(3)} s
      TTFB estimate: ${U|0} ms
      Current BW estimate: ${tt(I)?I|0:"Unknown"} bps
      New BW estimate: ${this.getBwEstimate()|0} bps
      Switching to level ${K} @ ${J|0} bps`),a.nextLoadLevel=a.nextAutoLevel=K,this.clearTimer();const ve=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===K&&K>0){const Te=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${K>0?"and switching down":""}
      Fragment duration: ${s.duration.toFixed(3)} s
      Time to underbuffer: ${Te.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,K>f){let Ne=this.findBestLevel(this.hls.levels[f].bitrate,f,K,0,Te,1,1);Ne===-1&&(Ne=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=Ne,this.resetEstimator(this.hls.levels[Ne].bitrate)}}};y||X>H*2?ve():this.timer=self.setInterval(ve,H*1e3),a.trigger(B.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:i,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 Gue(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.FRAG_LOADING,this.onFragLoading,this),e.on(B.FRAG_LOADED,this.onFragLoaded,this),e.on(B.FRAG_BUFFERED,this.onFragBuffered,this),e.on(B.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(B.LEVEL_LOADED,this.onLevelLoaded,this),e.on(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(B.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(B.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.FRAG_LOADING,this.onFragLoading,this),e.off(B.FRAG_LOADED,this.onFragLoaded,this),e.off(B.FRAG_BUFFERED,this.onFragBuffered,this),e.off(B.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(B.LEVEL_LOADED,this.onLevelLoaded,this),e.off(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(B.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(B.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 s;this.fragCurrent=r,this.partCurrent=(s=n.part)!=null?s: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 Se.BUFFER_ADD_CODEC_ERROR:case Se.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Se.FRAG_LOAD_TIMEOUT:{const r=n.frag,{fragCurrent:s,partCurrent:i}=this;if(r&&s&&r.sn===s.sn&&r.level===s.level){const a=performance.now(),o=i?i.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,s){const i=e+r/n,a=s?e+this.lastLevelLoadSec:0;return i+a}onLevelLoaded(e,n){const r=this.hls.config,{loading:s}=n.stats,i=s.end-s.first;tt(i)&&(this.lastLevelLoadSec=i/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 s=r?r.stats:n.stats;if(n.type===rt.MAIN&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(n)){if(this.clearTimer(),n.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const i=r?r.duration:n.duration,a=this.hls.levels[n.level],o=(a.loaded?a.loaded.bytes:0)+s.loaded,l=(a.loaded?a.loaded.duration:0)+i;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(n.bitrateTest){const i={stats:s,frag:n,part:r,id:n.type};this.onFragBuffered(B.FRAG_BUFFERED,i),n.bitrateTest=!1}else this.lastLoadedFragLevel=n.level}}onFragBuffered(e,n){const{frag:r,part:s}=n,i=s!=null&&s.stats.loaded?s.stats:r.stats;if(i.aborted||this.ignoreFragment(r))return;const a=i.parsing.end-i.loading.start-Math.min(i.loading.first-i.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,i.loaded),i.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==rt.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(),s=this.hls.config.maxStarvationDelay,i=this.findBestLevel(r,n,e,0,s,1,1);if(i>-1)return i;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(),s=this.lastLoadedFragLevel>-1;if(e!==-1&&(!r||!s||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const i=r&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const a=this.hls.levels;if(a.length>Math.max(e,i)&&a[e].loadError<=a[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}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:s,config:i,minAutoLevel:a}=r,o=n?n.duration:e?e.duration:0,l=this.getBwEstimate(),c=this.getStarvationDelay();let u=i.abrBandWidthFactor,d=i.abrBandWidthUpFactor;if(c){const y=this.findBestLevel(l,a,s,c,0,u,d);if(y>=0)return this.rebufferNotice=-1,y}let h=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay;if(!c){const y=this.bitrateTestDelay;y&&(h=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-y,this.info(`bitrate test took ${Math.round(1e3*y)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),u=d=1)}const f=this.findBestLevel(l,a,s,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 m=r.levels[a],g=r.loadLevelObj;return g&&(m==null?void 0:m.bitrate)<g.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,s=e.mainForwardBufferInfo;return(s?s.len:0)/r}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,n,r,s,i,a,o){var l;const c=s+i,u=this.lastLoadedFragLevel,d=u===-1?this.hls.firstLevel:u,{fragCurrent:h,partCurrent:f}=this,{levels:m,allAudioTracks:g,loadLevel:y,config:v}=this.hls;if(m.length===1)return 0;const _=m[d],S=!!((l=this.hls.latestLevelDetails)!=null&&l.live),E=y===-1||u===-1;let L,U="SDR",P=(_==null?void 0:_.frameRate)||0;const{audioPreference:I,videoPreference:k}=v,R=this.audioTracksByGroup||(this.audioTracksByGroup=N5(g));let M=-1;if(E){if(this.firstSelection!==-1)return this.firstSelection;const Z=this.codecTiers||(this.codecTiers=Ode(m,R,n,r)),oe=Dde(Z,U,e,I,k),{codecSet:ne,videoRanges:H,minFramerate:K,minBitrate:J,minIndex:Q,preferHDR:ve}=oe;M=Q,L=ne,U=ve?H[H.length-1]:H[0],P=K,e=Math.max(e,J),this.log(`picked start tier ${En(oe)}`)}else L=_==null?void 0:_.codecSet,U=_==null?void 0:_.videoRange;const G=f?f.duration:h?h.duration:0,Y=this.bwEstimator.getEstimateTTFB()/1e3,q=[];for(let Z=r;Z>=n;Z--){var X;const oe=m[Z],ne=Z>d;if(!oe)continue;if(v.useMediaCapabilities&&!oe.supportedResult&&!oe.supportedPromise){const Ne=navigator.mediaCapabilities;typeof(Ne==null?void 0:Ne.decodingInfo)=="function"&&Ede(oe,R,U,P,e,I)?(oe.supportedPromise=D5(oe,R,Ne,this.supportedCache),oe.supportedPromise.then(Ke=>{if(!this.hls)return;oe.supportedResult=Ke;const be=this.hls.levels,Pe=be.indexOf(oe);Ke.error?this.warn(`MediaCapabilities decodingInfo error: "${Ke.error}" for level ${Pe} ${En(Ke)}`):Ke.supported?Ke.decodingInfoResults.some(Ae=>Ae.smooth===!1||Ae.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Pe} not smooth or powerEfficient: ${En(Ke)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Pe} ${En(Ke)}`),Pe>-1&&be.length>1&&(this.log(`Removing unsupported level ${Pe}`),this.hls.removeLevel(Pe),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Ke=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Ke}`)})):oe.supportedResult=I5}if((L&&oe.codecSet!==L||U&&oe.videoRange!==U||ne&&P>oe.frameRate||!ne&&P>0&&P<oe.frameRate||(X=oe.supportedResult)!=null&&(X=X.decodingInfoResults)!=null&&X.some(Ne=>Ne.smooth===!1))&&(!E||Z!==M)){q.push(Z);continue}const H=oe.details,K=(f?H==null?void 0:H.partTarget:H==null?void 0:H.averagetargetduration)||G;let J;ne?J=o*e:J=a*e;const Q=G&&s>=G*2&&i===0?oe.averageBitrate:oe.maxBitrate,ve=this.getTimeToLoadFrag(Y,J,Q*K,H===void 0);if(J>=Q&&(Z===u||oe.loadError===0&&oe.fragmentError===0)&&(ve<=Y||!tt(ve)||S&&!this.bitrateTestDelay||ve<c)){const Ne=this.forcedAutoLevel;return Z!==y&&(Ne===-1||Ne!==y)&&(q.length&&this.trace(`Skipped level(s) ${q.join(",")} of ${r} max with CODECS and VIDEO-RANGE:"${m[q[0]].codecs}" ${m[q[0]].videoRange}; not compatible with "${L}" ${U}`),this.info(`switch candidate:${d}->${Z} adjustedbw(${Math.round(J)})-bitrate=${Math.round(J-Q)} ttfb:${Y.toFixed(1)} avgDuration:${K.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${ve.toFixed(1)} firstSelection:${E} codecSet:${oe.codecSet} videoRange:${oe.videoRange} hls.loadLevel:${y}`)),E&&(this.firstSelection=Z),Z}}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 M5={search:function(t,e){let n=0,r=t.length-1,s=null,i=null;for(;n<=r;){s=(n+r)/2|0,i=t[s];const a=e(i);if(a>0)n=s+1;else if(a<0)r=s-1;else return i}return null}};function Bde(t,e,n){if(e===null||!Array.isArray(t)||!t.length||!tt(e))return null;const r=t[0].programDateTime;if(e<(r||0))return null;const s=t[t.length-1].endProgramDateTime;if(e>=(s||0))return null;for(let i=0;i<t.length;++i){const a=t[i];if($de(e,n,a))return a}return null}function ou(t,e,n=0,r=0,s=.005){let i=null;if(t){i=e[1+t.sn-e[0].sn]||null;const o=t.endDTS-n;o>0&&o<15e-7&&(n+=15e-7),i&&t.level!==i.level&&i.end<=t.end&&(i=e[2+t.sn-e[0].sn]||null)}else n===0&&e[0].start===0&&(i=e[0]);if(i&&((!t||t.level===i.level)&&uD(n,r,i)===0||Fde(i,t,Math.min(s,r))))return i;const a=M5.search(e,uD.bind(null,n,r));return a&&(a!==t||!i)?a:i}function Fde(t,e,n){if(e&&e.start===0&&e.level<t.level&&(e.endPTS||0)>0){const r=e.tagList.reduce((s,i)=>(i[0]==="INF"&&(s+=parseFloat(i[1])),s),n);return t.start<=r}return!1}function uD(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 $de(t,e,n){const r=Math.min(e,n.duration+(n.deltaPTS?n.deltaPTS:0))*1e3;return(n.endProgramDateTime||0)-r>t}function j5(t,e,n){if(t&&t.startCC<=e&&t.endCC>=e){let r=t.fragments;const{fragmentHint:s}=t;s&&(r=r.concat(s));let i;return M5.search(r,a=>a.cc<e?1:a.cc>e?-1:(i=a,a.end<=n?1:a.start>n?-1:0)),i||null}return null}function z0(t){switch(t.details){case Se.FRAG_LOAD_TIMEOUT:case Se.KEY_LOAD_TIMEOUT:case Se.LEVEL_LOAD_TIMEOUT:case Se.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function U5(t){return t.details.startsWith("key")}function B5(t){return U5(t)&&!!t.frag&&!t.frag.decryptdata}function dD(t,e){const n=z0(e);return t.default[`${n?"timeout":"error"}Retry`]}function wA(t,e){const n=t.backoff==="linear"?1:Math.pow(2,e);return Math.min(n*t.retryDelayMs,t.maxRetryDelayMs)}function hD(t){return hn(hn({},t),{errorRetry:null,timeoutRetry:null})}function q0(t,e,n,r){if(!t)return!1;const s=r==null?void 0:r.code,i=e<t.maxNumRetry&&(Vde(s)||!!n);return t.shouldRetry?t.shouldRetry(t,e,n,r,i):i}function Vde(t){return Tw(t)||!!t&&(t<400||t>499)}function Tw(t){return t===0&&navigator.onLine===!1}var $r={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Bs={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class Gde extends Ii{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(B.ERROR,this.onError,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(B.ERROR,this.onError,this),e.off(B.ERROR,this.onErrorOut,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.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)===rt.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 s=e.audioGroups;if(s)return this.hls.allAudioTracks.filter(a=>s.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 s=this.hls,i=n.context;switch(n.details){case Se.FRAG_LOAD_ERROR:case Se.FRAG_LOAD_TIMEOUT:case Se.KEY_LOAD_ERROR:case Se.KEY_LOAD_TIMEOUT:n.errorAction=this.getFragRetryOrSwitchAction(n);return;case Se.FRAG_PARSING_ERROR:if((r=n.frag)!=null&&r.gap){n.errorAction=Md();return}case Se.FRAG_GAP:case Se.FRAG_DECRYPT_ERROR:{n.errorAction=this.getFragRetryOrSwitchAction(n),n.errorAction.action=$r.SendAlternateToPenaltyBox;return}case Se.LEVEL_EMPTY_ERROR:case Se.LEVEL_PARSING_ERROR:{var a;const l=n.parent===rt.MAIN?n.level:s.loadLevel;n.details===Se.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 Se.LEVEL_LOAD_ERROR:case Se.LEVEL_LOAD_TIMEOUT:typeof(i==null?void 0:i.level)=="number"&&(n.errorAction=this.getPlaylistRetryOrSwitchAction(n,i.level));return;case Se.AUDIO_TRACK_LOAD_ERROR:case Se.AUDIO_TRACK_LOAD_TIMEOUT:case Se.SUBTITLE_LOAD_ERROR:case Se.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const l=s.loadLevelObj;if(l&&(i.type===Kt.AUDIO_TRACK&&l.hasAudioGroup(i.groupId)||i.type===Kt.SUBTITLE_TRACK&&l.hasSubtitleGroup(i.groupId))){n.errorAction=this.getPlaylistRetryOrSwitchAction(n,s.loadLevel),n.errorAction.action=$r.SendAlternateToPenaltyBox,n.errorAction.flags=Bs.MoveAllAlternatesMatchingHost;return}}return;case Se.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:n.errorAction={action:$r.SendAlternateToPenaltyBox,flags:Bs.MoveAllAlternatesMatchingHDCP};return;case Se.KEY_SYSTEM_SESSION_UPDATE_FAILED:case Se.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case Se.KEY_SYSTEM_NO_SESSION:n.errorAction={action:$r.SendAlternateToPenaltyBox,flags:Bs.MoveAllAlternatesMatchingKey};return;case Se.BUFFER_ADD_CODEC_ERROR:case Se.REMUX_ALLOC_ERROR:case Se.BUFFER_APPEND_ERROR:if(!n.errorAction){var o;n.errorAction=this.getLevelSwitchAction(n,(o=n.level)!=null?o:s.loadLevel)}return;case Se.INTERNAL_EXCEPTION:case Se.BUFFER_APPENDING_ERROR:case Se.BUFFER_FULL_ERROR:case Se.LEVEL_SWITCH_ERROR:case Se.BUFFER_STALLED_ERROR:case Se.BUFFER_SEEK_OVER_HOLE:case Se.BUFFER_NUDGE_ON_STALL:n.errorAction=Md();return}n.type===ft.KEY_SYSTEM_ERROR&&(n.levelRetry=!1,n.errorAction=Md())}getPlaylistRetryOrSwitchAction(e,n){const r=this.hls,s=dD(r.config.playlistLoadPolicy,e),i=this.playlistError++;if(q0(s,i,z0(e),e.response))return{action:$r.RetryRequest,flags:Bs.None,retryConfig:s,retryCount:i};const o=this.getLevelSwitchAction(e,n);return s&&(o.retryConfig=s,o.retryCount=i),o}getFragRetryOrSwitchAction(e){const n=this.hls,r=this.getVariantLevelIndex(e.frag),s=n.levels[r],{fragLoadPolicy:i,keyLoadPolicy:a}=n.config,o=dD(U5(e)?a:i,e),l=n.levels.reduce((u,d)=>u+d.fragmentError,0);if(s&&(e.details!==Se.FRAG_GAP&&s.fragmentError++,!B5(e)&&q0(o,l,z0(e),e.response)))return{action:$r.RetryRequest,flags:Bs.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 s=this.hls.levels[n];if(s){var i,a;const c=e.details;s.loadError++,c===Se.BUFFER_APPEND_ERROR&&s.fragmentError++;let u=-1;const{levels:d,loadLevel:h,minAutoLevel:f,maxAutoLevel:m}=r;!r.autoLevelEnabled&&!r.config.preserveManualLevelOnError&&(r.loadLevel=-1);const g=(i=e.frag)==null?void 0:i.type,v=(g===rt.AUDIO&&c===Se.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(c===Se.BUFFER_ADD_CODEC_ERROR||c===Se.BUFFER_APPEND_ERROR))&&d.some(({audioCodec:U})=>s.audioCodec!==U),S=e.sourceBufferName==="video"&&(c===Se.BUFFER_ADD_CODEC_ERROR||c===Se.BUFFER_APPEND_ERROR)&&d.some(({codecSet:U,audioCodec:P})=>s.codecSet!==U&&s.audioCodec===P),{type:E,groupId:L}=(a=e.context)!=null?a:{};for(let U=d.length;U--;){const P=(U+h)%d.length;if(P!==h&&P>=f&&P<=m&&d[P].loadError===0){var o,l;const I=d[P];if(c===Se.FRAG_GAP&&g===rt.MAIN&&e.frag){const k=d[P].details;if(k){const R=ou(e.frag,k.fragments,e.frag.start);if(R!=null&&R.gap)continue}}else{if(E===Kt.AUDIO_TRACK&&I.hasAudioGroup(L)||E===Kt.SUBTITLE_TRACK&&I.hasSubtitleGroup(L))continue;if(g===rt.AUDIO&&(o=s.audioGroups)!=null&&o.some(k=>I.hasAudioGroup(k))||g===rt.SUBTITLE&&(l=s.subtitleGroups)!=null&&l.some(k=>I.hasSubtitleGroup(k))||v&&s.audioCodec===I.audioCodec||S&&s.codecSet===I.codecSet||!v&&s.codecSet!==I.codecSet)continue}u=P;break}}if(u>-1&&r.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:$r.SendAlternateToPenaltyBox,flags:Bs.None,nextAutoLevel:u}}return{action:$r.SendAlternateToPenaltyBox,flags:Bs.MoveAllAlternatesMatchingHost}}onErrorOut(e,n){var r;switch((r=n.errorAction)==null?void 0:r.action){case $r.DoNothing:break;case $r.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(n),!n.errorAction.resolved&&n.details!==Se.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:s}=r,i=r.nextAutoLevel;switch(s){case Bs.None:this.switchLevel(e,i);break;case Bs.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=ww[ww.indexOf(u)-1],r.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${n.maxHdcpLevel}" or lower`);break}}case Bs.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) ${Vr(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!==rt.MAIN){const h=d.decryptdata;h&&!l.matches(h)&&(r.resolved=!0)}}break}}r.resolved||this.switchLevel(e,i)}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===Se.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const r=Ew(e.mimeType),s=this.hls.levels;for(let i=s.length;i--;)s[i][`${e.sourceBufferName}Codec`]===r&&(this.log(`Removing level ${i} for ${e.details} ("${r}" not supported)`),this.hls.removeLevel(i))}}}function Md(t){const e={action:$r.DoNothing,flags:Bs.None};return t&&(e.resolved=!0),e}var xr={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class Kde{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(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.BUFFER_APPENDED,this.onBufferAppended,this),e.on(B.FRAG_BUFFERED,this.onFragBuffered,this),e.on(B.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.BUFFER_APPENDED,this.onBufferAppended,this),e.off(B.FRAG_BUFFERED,this.onFragBuffered,this),e.off(B.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 s=r.length;s--;){const i=r[s];if(!i)break;if(i.start<=e&&e<=i.end&&i.loaded)return i}return this.getBufferedFrag(e,n)}getBufferedFrag(e,n){return this.getFragAtPos(e,n,!0)}getFragAtPos(e,n,r){const{fragments:s}=this,i=Object.keys(s);for(let a=i.length;a--;){const o=s[i[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,s,i){this.timeRanges&&(this.timeRanges[e]=n);const a=(s==null?void 0:s.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||i)){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,s=Fu(r),i=this.fragments[s];if(!i||i.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;i.range[o]=this.getBufferedTimes(r,e.part,u,c)}),i.loaded=null,Object.keys(i.range).length?(this.bufferedEnd(i,r),Fg(i)||this.removeParts(r.sn-1,r.type)):this.removeFragment(i.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]=fD(r,s=>s.fragment.sn>=e))}fragBuffered(e,n){const r=Fu(e);let s=this.fragments[r];!s&&n&&(s=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,this.bufferedEnd(s,e))}getBufferedTimes(e,n,r,s){const i={time:[],partial:r},a=e.start,o=e.end,l=e.minEndPTS||o,c=e.maxStartPTS||a;for(let u=0;u<s.length;u++){const d=s.start(u)-this.bufferPadding,h=s.end(u)+this.bufferPadding;if(c>=d&&l<=h){i.time.push({startPTS:Math.max(a,s.start(u)),endPTS:Math.min(o,s.end(u))});break}else if(a<h&&o>d){const f=Math.max(a,s.start(u)),m=Math.min(o,s.end(u));m>f&&(i.partial=!0,i.time.push({startPTS:f,endPTS:m}))}else if(o<=d)break}return i}getPartialFragment(e){let n=null,r,s,i,a=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(c=>{const u=l[c];u&&Fg(u)&&(s=u.body.start-o,i=u.body.end+o,e>=s&&e<=i&&(r=Math.min(e-s,i-e),a<=r&&(n=u.body,a=r)))}),n}isEndListAppended(e){const n=this.endListFragments[e];return n!==void 0&&(n.buffered||Fg(n))}getState(e){const n=Fu(e),r=this.fragments[n];return r?r.buffered?Fg(r)?xr.PARTIAL:xr.OK:xr.APPENDING:xr.NOT_LOADED}isTimeBuffered(e,n,r){let s,i;for(let a=0;a<r.length;a++){if(s=r.start(a)-this.bufferPadding,i=r.end(a)+this.bufferPadding,e>=s&&n<=i)return!0;if(n<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,n){if(n.frag.sn==="initSegment"||n.frag.bitrateTest)return;const r=n.frag,s=n.part?null:n,i=Fu(r);this.fragments[i]={body:r,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,n){const{frag:r,part:s,timeRanges:i,type:a}=n;if(r.sn==="initSegment")return;const o=r.type;if(s){let c=this.activePartLists[o];c||(this.activePartLists[o]=c=[]),c.push(s)}this.timeRanges=i;const l=i[a];this.detectEvictedFragments(a,l,o,s)}onFragBuffered(e,n){this.detectPartialFragments(n)}hasFragment(e){const n=Fu(e);return!!this.fragments[n]}hasFragments(e){const{fragments:n}=this,r=Object.keys(n);if(!e)return r.length>0;for(let s=r.length;s--;){const i=n[r[s]];if((i==null?void 0:i.body.type)===e)return!0}return!1}hasParts(e){var n;return!!((n=this.activePartLists[e])!=null&&n.length)}removeFragmentsInRange(e,n,r,s,i){s&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const l=o.body;l.type!==r||s&&!l.gap||l.start<n&&l.end>e&&(o.buffered||i)&&this.removeFragment(l)})}removeFragment(e){const n=Fu(e);e.clearElementaryStreamInfo();const r=this.activePartLists[e.type];if(r){const s=e.sn;this.activePartLists[e.type]=fD(r,i=>i.fragment.sn!==s)}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 Fg(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 Fu(t){return`${t.type}_${t.level}_${t.sn}`}function fD(t,e){return t.filter(n=>{const r=e(n);return r||n.clearElementaryStreamInfo(),r})}var zl={cbc:0,ctr:1};class Hde{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 zl.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},n,e);case zl.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 zde(t){const e=t.byteLength,n=e&&new DataView(t.buffer).getUint8(e-1);return n?t.slice(0,e-n):t}class qde{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 s=0;s<4;s++)r[s]=n.getUint32(s*4);return r}initTable(){const e=this.sBox,n=this.invSBox,r=this.subMix,s=r[0],i=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 m=0,g=0,y=0;for(y=0;y<256;y++)y<128?f[y]=y<<1:f[y]=y<<1^283;for(y=0;y<256;y++){let v=g^g<<1^g<<2^g<<3^g<<4;v=v>>>8^v&255^99,e[m]=v,n[v]=m;const _=f[m],S=f[_],E=f[S];let L=f[v]*257^v*16843008;s[m]=L<<24|L>>>8,i[m]=L<<16|L>>>16,a[m]=L<<8|L>>>24,o[m]=L,L=E*16843009^S*65537^_*257^m*16843008,c[v]=L<<24|L>>>8,u[v]=L<<16|L>>>16,d[v]=L<<8|L>>>24,h[v]=L,m?(m=_^f[f[f[E^_]]],g^=f[f[g]]):m=g=1}}expandKey(e){const n=this.uint8ArrayToUint32Array_(e);let r=!0,s=0;for(;s<n.length&&r;)r=n[s]===this.key[s],s++;if(r)return;this.key=n;const i=this.keySize=n.length;if(i!==4&&i!==6&&i!==8)throw new Error("Invalid aes key size="+i);const a=this.ksRows=(i+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,m=f[0],g=f[1],y=f[2],v=f[3];let _,S;for(o=0;o<a;o++){if(o<i){_=c[o]=n[o];continue}S=_,o%i===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/i|0]<<24):i>6&&o%i===4&&(S=d[S>>>24]<<24|d[S>>>16&255]<<16|d[S>>>8&255]<<8|d[S&255]),c[o]=_=(c[o-i]^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]=m[d[S>>>24]]^g[d[S>>>16&255]]^y[d[S>>>8&255]]^v[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 s=this.keySize+6,i=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],m=h[1],g=h[2],y=h[3];const v=new Int32Array(e),_=new Int32Array(v.length);let S,E,L,U,P,I,k,R,M,G,Y,q,X,Z;const oe=this.networkToHostOrderSwap;for(;n<v.length;){for(M=oe(v[n]),G=oe(v[n+1]),Y=oe(v[n+2]),q=oe(v[n+3]),P=M^i[0],I=q^i[1],k=Y^i[2],R=G^i[3],X=4,Z=1;Z<s;Z++)S=l[P>>>24]^c[I>>16&255]^u[k>>8&255]^d[R&255]^i[X],E=l[I>>>24]^c[k>>16&255]^u[R>>8&255]^d[P&255]^i[X+1],L=l[k>>>24]^c[R>>16&255]^u[P>>8&255]^d[I&255]^i[X+2],U=l[R>>>24]^c[P>>16&255]^u[I>>8&255]^d[k&255]^i[X+3],P=S,I=E,k=L,R=U,X=X+4;S=a[P>>>24]<<24^a[I>>16&255]<<16^a[k>>8&255]<<8^a[R&255]^i[X],E=a[I>>>24]<<24^a[k>>16&255]<<16^a[R>>8&255]<<8^a[P&255]^i[X+1],L=a[k>>>24]<<24^a[R>>16&255]<<16^a[P>>8&255]<<8^a[I&255]^i[X+2],U=a[R>>>24]<<24^a[P>>16&255]<<16^a[I>>8&255]<<8^a[k&255]^i[X+3],_[n]=oe(S^f),_[n+1]=oe(U^m),_[n+2]=oe(L^g),_[n+3]=oe(E^y),f=M,m=G,g=Y,y=q,n=n+4}return _.buffer}}class Wde{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=Yde(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function Yde(t){switch(t){case zl.cbc:return"AES-CBC";case zl.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${t}`)}}const Xde=16;class TA{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?zde(r):r}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,n,r,s){return this.useSoftware?new Promise((i,a)=>{const o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,n,r,s);const l=this.flush();l?i(l.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),n,r,s)}softwareDecrypt(e,n,r,s){const{currentIV:i,currentResult:a,remainderData:o}=this;if(s!==zl.cbc||n.byteLength!==16)return fn.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=ki(o,e),this.remainderData=null);const l=this.getValidChunk(e);if(!l.length)return null;i&&(r=i);let c=this.softwareDecrypter;c||(c=this.softwareDecrypter=new qde),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,s){if(this.key!==n||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,n,r,s));this.key=n,this.fastAesKey=new Wde(this.subtle,n,s)}return this.fastAesKey.expandKey().then(i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Hde(this.subtle,new Uint8Array(r),s).decrypt(e.buffer,i)):Promise.reject(new Error("web crypto not initialized"))).catch(i=>(fn.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(e,n,r,s)))}onWebCryptoError(e,n,r,s){const i=this.enableSoftwareAES;if(i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,n,r,s);const a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(i?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let n=e;const r=e.length-e.length%Xde;return r!==e.length&&(n=e.slice(0,r),this.remainderData=e.slice(r)),n}logOnce(e){this.logEnabled&&(fn.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const pD=Math.pow(2,17);class Qde{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 ro({type:ft.NETWORK_ERROR,details:Se.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${r?"part list":"url"}`),networkDetails:null}));this.abort();const s=this.config,i=s.fLoader,a=s.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(m=>m[0]==="GAP")){l(gD(e));return}else e.gap=!1;const c=this.loader=i?new i(s):new a(s),u=mD(e);e.loader=c;const d=hD(s.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:pD};e.stats=c.stats;const f={onSuccess:(m,g,y,v)=>{this.resetLoader(e,c);let _=m.data;y.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(_.slice(0,16)),_=_.slice(16)),o({frag:e,part:null,payload:_,networkDetails:v})},onError:(m,g,y,v)=>{this.resetLoader(e,c),l(new ro({type:ft.NETWORK_ERROR,details:Se.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:hn({url:r,data:void 0},m),error:new Error(`HTTP Error ${m.code} ${m.text}`),networkDetails:y,stats:v}))},onAbort:(m,g,y)=>{this.resetLoader(e,c),l(new ro({type:ft.NETWORK_ERROR,details:Se.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:y,stats:m}))},onTimeout:(m,g,y)=>{this.resetLoader(e,c),l(new ro({type:ft.NETWORK_ERROR,details:Se.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:y,stats:m}))}};n&&(f.onProgress=(m,g,y,v)=>n({frag:e,part:null,payload:y,networkDetails:v})),c.load(u,h,f)})}loadPart(e,n,r){this.abort();const s=this.config,i=s.fLoader,a=s.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||n.gap){l(gD(e,n));return}const c=this.loader=i?new i(s):new a(s),u=mD(e,n);e.loader=c;const d=hD(s.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:pD};n.stats=c.stats,c.load(u,h,{onSuccess:(f,m,g,y)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,n);const v={frag:e,part:n,payload:f.data,networkDetails:y};r(v),o(v)},onError:(f,m,g,y)=>{this.resetLoader(e,c),l(new ro({type:ft.NETWORK_ERROR,details:Se.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:n,response:hn({url:u.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:g,stats:y}))},onAbort:(f,m,g)=>{e.stats.aborted=n.stats.aborted,this.resetLoader(e,c),l(new ro({type:ft.NETWORK_ERROR,details:Se.INTERNAL_ABORTED,fatal:!1,frag:e,part:n,error:new Error("Aborted"),networkDetails:g,stats:f}))},onTimeout:(f,m,g)=>{this.resetLoader(e,c),l(new ro({type:ft.NETWORK_ERROR,details:Se.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:n,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:g,stats:f}))}})})}updateStatsFromPart(e,n){const r=e.stats,s=n.stats,i=s.total;if(r.loaded+=s.loaded,i){const l=Math.round(e.duration/n.duration),c=Math.min(Math.round(r.loaded/i),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=s.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 mD(t,e=null){const n=e||t,r={frag:t,part:e,responseType:"arraybuffer",url:n.url,headers:{},rangeStart:0,rangeEnd:0},s=n.byteRangeStartOffset,i=n.byteRangeEndOffset;if(tt(s)&&tt(i)){var a;let o=s,l=i;if(t.sn==="initSegment"&&Jde((a=t.decryptdata)==null?void 0:a.method)){const c=i-s;c%16&&(l=i+(16-c%16)),s!==0&&(r.resetIV=!0,o=s-16)}r.rangeStart=o,r.rangeEnd=l}return r}function gD(t,e){const n=new Error(`GAP ${t.gap?"tag":"attribute"} found`),r={type:ft.MEDIA_ERROR,details:Se.FRAG_GAP,fatal:!1,frag:t,error:n,networkDetails:null};return e&&(r.part=e),(e||t).stats.aborted=!0,new ro(r)}function Jde(t){return t==="AES-128"||t==="AES-256"}class ro extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class F5 extends Ii{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 AA{constructor(e,n,r,s=0,i=-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=$g(),this.buffering={audio:$g(),video:$g(),audiovideo:$g()},this.level=e,this.sn=n,this.id=r,this.size=s,this.part=i,this.partial=a}}function $g(){return{start:0,executeStart:0,executeEnd:0,end:0}}const yD={length:0,start:()=>0,end:()=>0};class Pt{static isBuffered(e,n){if(e){const r=Pt.getBuffered(e);for(let s=r.length;s--;)if(n>=r.start(s)&&n<=r.end(s))return!0}return!1}static bufferedRanges(e){if(e){const n=Pt.getBuffered(e);return Pt.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 s=Pt.bufferedRanges(e);if(s.length)return Pt.bufferedInfo(s,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 s=-1,i=[];if(r)for(let u=0;u<e.length;u++){n>=e[u].start&&n<=e[u].end&&(s=u);const d=i.length;if(d){const h=i[d-1].end;e[u].start-h<r?e[u].end>h&&(i[d-1].end=e[u].end):i.push(e[u])}else i.push(e[u])}else i=e;let a=0,o,l=n,c=n;for(let u=0;u<i.length;u++){const d=i[u].start,h=i[u].end;if(s===-1&&n>=d&&n<=h&&(s=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:s}}static getBuffered(e){try{return e.buffered||yD}catch(n){return fn.log("failed to get media.buffered",n),yD}}}const $5=/\{\$([a-zA-Z0-9-_]+)\}/g;function vD(t){return $5.test(t)}function Aw(t,e){if(t.variableList!==null||t.hasVariableRefs){const n=t.variableList;return e.replace($5,r=>{const s=r.substring(2,r.length-1),i=n==null?void 0:n[s];return i===void 0?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),r):i})}return e}function _D(t,e,n){let r=t.variableList;r||(t.variableList=r={});let s,i;if("QUERYPARAM"in e){s=e.QUERYPARAM;try{const a=new self.URL(n).searchParams;if(a.has(s))i=a.get(s);else throw new Error(`"${s}" does not match any query parameter in URI: "${n}"`)}catch(a){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else s=e.NAME,i=e.VALUE;s in r?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):r[s]=i||""}function Zde(t,e,n){const r=e.IMPORT;if(n&&r in n){let s=t.variableList;s||(t.variableList=s={}),s[r]=n[r]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}const ehe=/^(\d+)x(\d+)$/,bD=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Gn{constructor(e,n){typeof e=="string"&&(e=Gn.parseAttrList(e,n)),vn(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 s=0;s<n.length/2;s++)r[s]=parseInt(n.slice(s*2,s*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((s,i)=>(s[i.toLowerCase()]=!0,s),n)}bool(e){return this[e]==="YES"}decimalResolution(e){const n=ehe.exec(this[e]);if(n!==null)return{width:parseInt(n[1],10),height:parseInt(n[2],10)}}static parseAttrList(e,n){let r;const s={},i='"';for(bD.lastIndex=0;(r=bD.exec(e))!==null;){const a=r[1].trim();let o=r[2];const l=o.indexOf(i)===0&&o.lastIndexOf(i)===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=Aw(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":fn.warn(`${e}: attribute ${a} is missing quotes`)}s[a]=o}return s}}const the="com.apple.hls.interstitial";function nhe(t){return t!=="ID"&&t!=="CLASS"&&t!=="CUE"&&t!=="START-DATE"&&t!=="DURATION"&&t!=="END-DATE"&&t!=="END-ON-NEXT"}function rhe(t){return t==="SCTE35-OUT"||t==="SCTE35-IN"||t==="SCTE35-CMD"}class V5{constructor(e,n,r=0){var s;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=(s=n==null?void 0:n.tagOrder)!=null?s:r,n){const i=n.attr;for(const a in i)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==i[a]){fn.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=vn(new Gn({}),i,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 i=(n==null?void 0:n.endDate)||new Date(this.attr["END-DATE"]);tt(i.getTime())&&(this._endDate=i)}}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?(fn.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(tt(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===the}get isValid(){return!!this.id&&!this._badValueForSameId&&tt(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 she=10;class ihe{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?tt(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||she}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 xD(t,e){return!t&&!e?!0:!t||!e?!1:W0(t,e)}function jd(t){return t==="AES-128"||t==="AES-256"||t==="AES-256-CTR"}function RA(t){switch(t){case"AES-128":case"AES-256":return zl.cbc;case"AES-256-CTR":return zl.ctr;default:throw new Error(`invalid full segment method ${t}`)}}function CA(t){return Uint8Array.from(atob(t),e=>e.charCodeAt(0))}function Rw(t){return Uint8Array.from(unescape(encodeURIComponent(t)),e=>e.charCodeAt(0))}function ahe(t){const e=Rw(t).subarray(0,16),n=new Uint8Array(16);return n.set(e,16-e.length),n}function G5(t){const e=function(r,s,i){const a=r[s];r[s]=r[i],r[i]=a};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}function K5(t){const e=t.split(":");let n=null;if(e[0]==="data"&&e.length===2){const r=e[1].split(";"),s=r[r.length-1].split(",");if(s.length===2){const i=s[0]==="base64",a=s[1];i?(r.splice(-1,1),n=CA(a)):n=ahe(a)}}return n}const Y0=typeof self<"u"?self:void 0;var Kn={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Kr={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Ly(t){switch(t){case Kr.FAIRPLAY:return Kn.FAIRPLAY;case Kr.PLAYREADY:return Kn.PLAYREADY;case Kr.WIDEVINE:return Kn.WIDEVINE;case Kr.CLEARKEY:return Kn.CLEARKEY}}function vx(t){switch(t){case Kn.FAIRPLAY:return Kr.FAIRPLAY;case Kn.PLAYREADY:return Kr.PLAYREADY;case Kn.WIDEVINE:return Kr.WIDEVINE;case Kn.CLEARKEY:return Kr.CLEARKEY}}function Af(t){const{drmSystems:e,widevineLicenseUrl:n}=t,r=e?[Kn.FAIRPLAY,Kn.WIDEVINE,Kn.PLAYREADY,Kn.CLEARKEY].filter(s=>!!e[s]):[];return!r[Kn.WIDEVINE]&&n&&r.push(Kn.WIDEVINE),r}const H5=function(t){return Y0!=null&&(t=Y0.navigator)!=null&&t.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function ohe(t,e,n,r){let s;switch(t){case Kn.FAIRPLAY:s=["cenc","sinf"];break;case Kn.WIDEVINE:case Kn.PLAYREADY:s=["cenc"];break;case Kn.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return lhe(s,e,n,r)}function lhe(t,e,n,r){return[{initDataTypes:t,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:e.map(i=>({contentType:`audio/mp4; codecs=${i}`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null})),videoCapabilities:n.map(i=>({contentType:`video/mp4; codecs=${i}`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}))}]}function che(t){var e;return!!t&&(t.sessionType==="persistent-license"||!!((e=t.sessionTypes)!=null&&e.some(n=>n==="persistent-license")))}function z5(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=CA(o).subarray(0,16);return G5(l),l}}return null}let $u={};class Ol{static clearKeyUriToKeyIdMap(){$u={}}static setKeyIdForUri(e,n){$u[e]=n}static addKeyIdForUri(e){const n=Object.keys($u).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,n),$u[e]=r,r}constructor(e,n,r,s=[1],i=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=s,this.iv=i,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!jd(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(b5(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)&&xD(e.iv,this.iv)&&xD(e.keyId,this.keyId)}isSupported(){if(this.method){if(jd(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Kr.FAIRPLAY:case Kr.WIDEVINE:case Kr.PLAYREADY:case Kr.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(jd(this.method)){let i=this.iv;return i||(typeof e!="number"&&(fn.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),i=dhe(e)),new Ol(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.keyId){const i=$u[this.uri];if(i&&!W0(this.keyId,i)&&Ol.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const r=K5(this.uri);if(r)switch(this.keyFormat){case Kr.WIDEVINE:if(this.pssh=r,!this.keyId){const i=pde(r.buffer);if(i.length){var s;const a=i[0];this.keyId=(s=a.kids)!=null&&s.length?a.kids[0]:null}}this.keyId||(this.keyId=SD(n));break;case Kr.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=fde(i,null,r),this.keyId=z5(r);break}default:{let i=r.subarray(0,16);if(i.length!==16){const a=new Uint8Array(16);a.set(i,16-i.length),i=a}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i;i=uhe(n),i||(i=SD(n),i||(i=$u[this.uri])),i&&(this.keyId=i,Ol.setKeyIdForUri(this.uri,i))}return this}}function uhe(t){const e=t==null?void 0:t[Kr.WIDEVINE];return e?e.keyId:null}function SD(t){const e=t==null?void 0:t[Kr.PLAYREADY];if(e){const n=K5(e.uri);if(n)return z5(n)}return null}function dhe(t){const e=new Uint8Array(16);for(let n=12;n<16;n++)e[n]=t>>8*(15-n)&255;return e}const ED=/#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,wD=/#EXT-X-MEDIA:(.*)/g,hhe=/^#EXT(?:INF|-X-TARGETDURATION):/m,_x=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),fhe=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 Sa{static findGroup(e,n){for(let r=0;r<e.length;r++){const s=e[r];if(s.id===n)return s}}static resolve(e,n){return _A.buildAbsoluteURL(n,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return hhe.test(e)}static parseMasterPlaylist(e,n){const r=vD(e),s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:r},i=[];if(ED.lastIndex=0,!e.startsWith("#EXTM3U"))return s.playlistParsingError=new Error("no EXTM3U delimiter"),s;let a;for(;(a=ED.exec(e))!=null;)if(a[1]){var o;const c=new Gn(a[1],s),u=Aw(s,a[2]),d={attrs:c,bitrate:c.decimalInteger("BANDWIDTH")||c.decimalInteger("AVERAGE-BANDWIDTH"),name:c.NAME,url:Sa.resolve(u,n)},h=c.decimalResolution("RESOLUTION");h&&(d.width=h.width,d.height=h.height),RD(c.CODECS,d);const f=c["SUPPLEMENTAL-CODECS"];f&&(d.supplemental={},RD(f,d.supplemental)),(o=d.unknownCodecs)!=null&&o.length||i.push(d),s.levels.push(d)}else if(a[3]){const c=a[3],u=a[4];switch(c){case"SESSION-DATA":{const d=new Gn(u,s),h=d["DATA-ID"];h&&(s.sessionData===null&&(s.sessionData={}),s.sessionData[h]=d);break}case"SESSION-KEY":{const d=TD(u,n,s);d.encrypted&&d.isSupported()?(s.sessionKeys===null&&(s.sessionKeys=[]),s.sessionKeys.push(d)):fn.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{const d=new Gn(u,s);_D(s,d,n)}break}case"CONTENT-STEERING":{const d=new Gn(u,s);s.contentSteering={uri:Sa.resolve(d["SERVER-URI"],n),pathwayId:d["PATHWAY-ID"]||"."};break}case"START":{s.startTimeOffset=AD(u);break}}}const l=i.length>0&&i.length<s.levels.length;return s.levels=l?i:s.levels,s.levels.length===0&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(e,n,r){let s;const i={},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(wD.lastIndex=0;(s=wD.exec(e))!==null;){const c=new Gn(s[1],r),u=c.TYPE;if(u){const d=o[u],h=i[u]||[];i[u]=h;const f=c.LANGUAGE,m=c["ASSOC-LANGUAGE"],g=c.CHANNELS,y=c.CHARACTERISTICS,v=c["INSTREAM-ID"],_={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?Sa.resolve(c.URI,n):""};if(m&&(_.assocLang=m),g&&(_.channels=g),y&&(_.characteristics=y),v&&(_.instreamId=v),d!=null&&d.length){const S=Sa.findGroup(d,_.groupId)||d[0];CD(_,S,"audioCodec"),CD(_,S,"textCodec")}h.push(_)}}return i}static parseLevelPlaylist(e,n,r,s,i,a){var o;const l={url:n},c=new ihe(n),u=c.fragments,d=[];let h=null,f=0,m=0,g=0,y=0,v=0,_=null,S=new mx(s,l),E,L,U,P=-1,I=!1,k=null,R;if(_x.lastIndex=0,c.m3u8=e,c.hasVariableRefs=vD(e),((o=_x.exec(e))==null?void 0:o[0])!=="#EXTM3U")return c.playlistParsingError=new Error("Missing format identifier #EXTM3U"),c;for(;(E=_x.exec(e))!==null;){I&&(I=!1,S=new mx(s,l),S.playlistOffset=g,S.setStart(g),S.sn=f,S.cc=y,v&&(S.bitrate=v),S.level=r,h&&(S.initSegment=h,h.rawProgramDateTime&&(S.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null),k&&(S.setByteRange(k),k=null)));const q=E[1];if(q){S.duration=parseFloat(q);const X=(" "+E[2]).slice(1);S.title=X||null,S.tagList.push(X?["INF",q,X]:["INF",q])}else if(E[3]){if(tt(S.duration)){S.playlistOffset=g,S.setStart(g),U&&LD(S,U,c),S.sn=f,S.level=r,S.cc=y,u.push(S);const X=(" "+E[3]).slice(1);S.relurl=Aw(c,X),Cw(S,_,d),_=S,g+=S.duration,f++,m=0,I=!0}}else{if(E=E[0].match(fhe),!E){fn.warn("No matches on slow regex match for level playlist!");continue}for(L=1;L<E.length&&E[L]===void 0;L++);const X=(" "+E[L]).slice(1),Z=(" "+E[L+1]).slice(1),oe=E[L+2]?(" "+E[L+2]).slice(1):null;switch(X){case"BYTERANGE":_?S.setByteRange(Z,_):S.setByteRange(Z);break;case"PROGRAM-DATE-TIME":S.rawProgramDateTime=Z,S.tagList.push(["PROGRAM-DATE-TIME",Z]),P===-1&&(P=u.length);break;case"PLAYLIST-TYPE":c.type&&Qa(c,X,E),c.type=Z.toUpperCase();break;case"MEDIA-SEQUENCE":c.startSN!==0?Qa(c,X,E):u.length>0&&ID(c,X,E),f=c.startSN=parseInt(Z);break;case"SKIP":{c.skippedSegments&&Qa(c,X,E);const ne=new Gn(Z,c),H=ne.decimalInteger("SKIPPED-SEGMENTS");if(tt(H)){c.skippedSegments+=H;for(let J=H;J--;)u.push(null);f+=H}const K=ne.enumeratedString("RECENTLY-REMOVED-DATERANGES");K&&(c.recentlyRemovedDateranges=(c.recentlyRemovedDateranges||[]).concat(K.split("	")));break}case"TARGETDURATION":c.targetduration!==0&&Qa(c,X,E),c.targetduration=Math.max(parseInt(Z),1);break;case"VERSION":c.version!==null&&Qa(c,X,E),c.version=parseInt(Z);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":c.live||Qa(c,X,E),c.live=!1;break;case"#":(Z||oe)&&S.tagList.push(oe?[Z,oe]:[Z]);break;case"DISCONTINUITY":y++,S.tagList.push(["DIS"]);break;case"GAP":S.gap=!0,S.tagList.push([X]);break;case"BITRATE":S.tagList.push([X,Z]),v=parseInt(Z)*1e3,tt(v)?S.bitrate=v:v=0;break;case"DATERANGE":{const ne=new Gn(Z,c),H=new V5(ne,c.dateRanges[ne.ID],c.dateRangeTagCount);c.dateRangeTagCount++,H.isValid||c.skippedSegments?c.dateRanges[H.id]=H:fn.warn(`Ignoring invalid DATERANGE tag: "${Z}"`),S.tagList.push(["EXT-X-DATERANGE",Z]);break}case"DEFINE":{{const ne=new Gn(Z,c);"IMPORT"in ne?Zde(c,ne,a):_D(c,ne,n)}break}case"DISCONTINUITY-SEQUENCE":c.startCC!==0?Qa(c,X,E):u.length>0&&ID(c,X,E),c.startCC=y=parseInt(Z);break;case"KEY":{const ne=TD(Z,n,c);if(ne.isSupported()){if(ne.method==="NONE"){U=void 0;break}U||(U={});const H=U[ne.keyFormat];H!=null&&H.matches(ne)||(H&&(U=vn({},U)),U[ne.keyFormat]=ne)}else fn.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${Z}"`);break}case"START":c.startTimeOffset=AD(Z);break;case"MAP":{const ne=new Gn(Z,c);if(S.duration){const H=new mx(s,l);kD(H,ne,r,U),h=H,S.initSegment=h,h.rawProgramDateTime&&!S.rawProgramDateTime&&(S.rawProgramDateTime=h.rawProgramDateTime)}else{const H=S.byteRangeEndOffset;if(H){const K=S.byteRangeStartOffset;k=`${H-K}@${K}`}else k=null;kD(S,ne,r,U),h=S,I=!0}h.cc=y;break}case"SERVER-CONTROL":{R&&Qa(c,X,E),R=new Gn(Z),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&&Qa(c,X,E);const ne=new Gn(Z);c.partTarget=ne.decimalFloatingPoint("PART-TARGET");break}case"PART":{let ne=c.partList;ne||(ne=c.partList=[]);const H=m>0?ne[ne.length-1]:void 0,K=m++,J=new Gn(Z,c),Q=new Zue(J,S,l,K,H);ne.push(Q),S.duration+=Q.duration;break}case"PRELOAD-HINT":{const ne=new Gn(Z,c);c.preloadHint=ne;break}case"RENDITION-REPORT":{const ne=new Gn(Z,c);c.renditionReports=c.renditionReports||[],c.renditionReports.push(ne);break}default:fn.warn(`line parsed but not handled: ${E}`);break}}}_&&!_.relurl?(u.pop(),g-=_.duration,c.partList&&(c.fragmentHint=_)):c.partList&&(Cw(S,_,d),S.cc=y,c.fragmentHint=S,U&&LD(S,U,c)),c.targetduration||(c.playlistParsingError=new Error("Missing Target Duration"));const M=u.length,G=u[0],Y=u[M-1];if(g+=c.skippedSegments*c.targetduration,g>0&&M&&Y){c.averagetargetduration=g/M;const q=Y.sn;c.endSN=q!=="initSegment"?q:0,c.live||(Y.endList=!0),P>0&&(mhe(u,P),G&&d.unshift(G))}return c.fragmentHint&&(g+=c.fragmentHint.duration),c.totalduration=g,d.length&&c.dateRangeTagCount&&G&&q5(d,c),c.endCC=y,c}}function q5(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],s=e.live?1/0:e.totalduration,i=Object.keys(e.dateRanges);for(let o=i.length;o--;){const l=e.dateRanges[i[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=phe(e,c,t,u,s);if(d!==-1){l.tagAnchor=e.fragments[d].ref;break}}}}function phe(t,e,n,r,s){const i=n[r];if(i){const o=i.programDateTime;if(e>=o||r===0){var a;const l=(((a=n[r+1])==null?void 0:a.start)||s)-i.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 m=u[f].programDateTime;if(e>=m&&e<m+u[f].duration*1e3)return f}}return c}}}return-1}function TD(t,e,n){var r,s;const i=new Gn(t,n),a=(r=i.METHOD)!=null?r:"",o=i.URI,l=i.hexadecimalInteger("IV"),c=i.KEYFORMATVERSIONS,u=(s=i.KEYFORMAT)!=null?s:"identity";o&&i.IV&&!l&&fn.error(`Invalid IV: ${i.IV}`);const d=o?Sa.resolve(o,e):"",h=(c||"1").split("/").map(Number).filter(Number.isFinite);return new Ol(a,d,u,h,l,i.KEYID)}function AD(t){const n=new Gn(t).decimalFloatingPoint("TIME-OFFSET");return tt(n)?n:null}function RD(t,e){let n=(t||"").split(/[ ,]+/).filter(r=>r);["video","audio","text"].forEach(r=>{const s=n.filter(i=>SA(i,r));s.length&&(e[`${r}Codec`]=s.map(i=>i.split("/")[0]).join(","),n=n.filter(i=>s.indexOf(i)===-1))}),e.unknownCodecs=n}function CD(t,e,n){const r=e[n];r&&(t[n]=r)}function mhe(t,e){let n=t[e];for(let r=e;r--;){const s=t[r];if(!s)return;s.programDateTime=n.programDateTime-s.duration*1e3,n=s}}function Cw(t,e,n){t.rawProgramDateTime?n.push(t):e!=null&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function kD(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 LD(t,e,n){t.levelkeys=e;const{encryptedFragments:r}=n;(!r.length||r[r.length-1].levelkeys!==e)&&Object.keys(e).some(s=>e[s].isCommonEncryption)&&r.push(t)}function Qa(t,e,n){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${n[0]})`)}function ID(t,e,n){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${n[0]})`)}function bx(t,e){const n=e.startPTS;if(tt(n)){let r=0,s;e.sn>t.sn?(r=n-t.start,s=t):(r=t.start-n,s=e),s.duration!==r&&s.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 W5(t,e,n,r,s,i,a){r-n<=0&&(a.warn("Fragment should have a positive duration",e),r=n+e.duration,i=s+e.duration);let l=n,c=r;const u=e.startPTS,d=e.endPTS;if(tt(u)){const v=Math.abs(u-n);t&&v>t.totalduration?a.warn(`media timestamps and playlist times differ by ${v}s for level ${e.level} ${t.url}`):tt(e.deltaPTS)?e.deltaPTS=Math.max(v,e.deltaPTS):e.deltaPTS=v,l=Math.max(n,u),n=Math.min(n,u),s=e.startDTS!==void 0?Math.min(s,e.startDTS):s,c=Math.min(r,d),r=Math.max(r,d),i=e.endDTS!==void 0?Math.max(i,e.endDTS):i}const h=n-e.start;e.start!==0&&e.setStart(n),e.setDuration(r-e.start),e.startPTS=n,e.maxStartPTS=l,e.startDTS=s,e.endPTS=r,e.minEndPTS=c,e.endDTS=i;const f=e.sn;if(!t||f<t.startSN||f>t.endSN)return 0;let m;const g=f-t.startSN,y=t.fragments;for(y[g]=e,m=g;m>0;m--)bx(y[m],y[m-1]);for(m=g;m<y.length-1;m++)bx(y[m],y[m+1]);return t.fragmentHint&&bx(y[y.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,h}function ghe(t,e,n){if(t===e)return;let r=null;const s=t.fragments;for(let u=s.length-1;u>=0;u--){const d=s[u].initSegment;if(d){r=d;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;let i;_he(t,e,(u,d,h,f)=>{if((!e.startCC||e.skippedSegments)&&d.cc!==u.cc){const m=u.cc-d.cc;for(let g=h;g<f.length;g++)f[g].cc+=m;e.endCC=f[f.length-1].cc}tt(u.startPTS)&&tt(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&&(i=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=yhe(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&&Cw(o[d],o[d-1],u);q5(u,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;const u=Q5(t,e.startSN-1);e.startCC=(l=u==null?void 0:u.cc)!=null?l:a[0].cc}vhe(t.partList,e.partList,(u,d)=>{d.elementaryStreams=u.elementaryStreams,d.stats=u.stats}),i?W5(e,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,n):Y5(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 yhe(t,e,n){const{dateRanges:r,recentlyRemovedDateranges:s}=e,i=vn({},t);s&&s.forEach(l=>{delete i[l]});const o=Object.keys(i).length;return o?(Object.keys(r).forEach(l=>{const c=i[l],u=new V5(r[l].attr,c);u.isValid?(i[l]=u,c||(u.tagOrder+=o)):n.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${En(r[l].attr)}"`)}),i):r}function vhe(t,e,n){if(t&&e){let r=0;for(let s=0,i=t.length;s<=i;s++){const a=t[s],o=e[s+r];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?n(a,o):r--}}}function _he(t,e,n){const r=e.skippedSegments,s=Math.max(t.startSN,e.startSN)-e.startSN,i=(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=s;c<=i;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&&bhe(h,f)){e.playlistParsingError=PD(`media sequence mismatch ${d.sn}:`,t,e,u,d);return}else if(u.cc!==d.cc){e.playlistParsingError=PD(`discontinuity sequence mismatch (${u.cc}!=${d.cc})`,t,e,u,d);return}}}}function PD(t,e,n,r,s){return new Error(`${t} ${s.url}
Playlist starting @${e.startSN}
${e.m3u8}

Playlist starting @${n.startSN}
${n.m3u8}`)}function Y5(t,e,n=!0){const r=e.startSN+e.skippedSegments-t.startSN,s=t.fragments,i=r>=0;let a=0;if(i&&r<s.length)a=s[r].start;else if(i&&e.startSN===t.endSN+1)a=t.fragmentEnd;else if(i&&n)a=t.fragmentStart+r*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)a=t.fragmentStart;else return;kw(e,a)}function kw(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 X5(t,e=1/0){let n=1e3*t.targetduration;if(t.updated){const r=t.fragments;if(r.length&&n*4>e){const i=r[r.length-1].duration*1e3;i<n&&(n=i)}}else n/=2;return Math.round(n)}function Q5(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 DD(t,e,n){return t?J5(t.partList,e,n):null}function J5(t,e,n){if(t)for(let r=t.length;r--;){const s=t[r];if(s.index===n&&s.fragment.sn===e)return s}return null}function Z5(t){t.forEach((e,n)=>{var r;(r=e.details)==null||r.fragments.forEach(s=>{s.level=n,s.initSegment&&(s.initSegment.level=n)})})}function bhe(t,e){return t!==e&&e?OD(t)!==OD(e):!1}function OD(t){return t.replace(/\?[^?]*$/,"")}function tp(t,e){for(let r=0,s=t.length;r<s;r++){var n;if(((n=t[r])==null?void 0:n.cc)===e)return t[r]}return null}function xhe(t,e){return!!(t&&e.startCC<t.endCC&&e.endCC>t.startCC)}function ND(t,e){const n=t.start+e;t.startPTS=n,t.setStart(n),t.endPTS=n+t.duration}function e4(t,e){const n=e.fragments;for(let r=0,s=n.length;r<s;r++)ND(n[r],t);e.fragmentHint&&ND(e.fragmentHint,t),e.alignedSliding=!0}function She(t,e){t&&(t4(e,t),e.alignedSliding||X0(e,t),!e.alignedSliding&&!e.skippedSegments&&Y5(t,e,!1))}function t4(t,e){if(!xhe(e,t))return;const n=Math.min(e.endCC,t.endCC),r=tp(e.fragments,n),s=tp(t.fragments,n);if(!r||!s)return;fn.log(`Aligning playlist at start of dicontinuity sequence ${n}`);const i=r.start-s.start;e4(i,t)}function X0(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const n=t.fragments,r=e.fragments;if(!n.length||!r.length)return;let s,i;const a=Math.min(e.endCC,t.endCC);e.startCC<a&&t.startCC<a&&(s=tp(r,a),i=tp(n,a)),(!s||!i)&&(s=r[Math.floor(r.length/2)],i=tp(n,s.cc)||n[Math.floor(n.length/2)]);const o=s.programDateTime,l=i.programDateTime;if(!o||!l)return;const c=(l-o)/1e3-(i.start-s.start);e4(c,t)}function hs(t,e,n){Ls(t,e,n),t.addEventListener(e,n)}function Ls(t,e,n){t.removeEventListener(e,n)}const Ehe={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}},De={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 kA extends F5{constructor(e,n,r,s,i){super(s,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=De.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=Pt.bufferInfo(c||l,d,a.maxBufferHole),f=!h.len;if(this.log(`Media seeking to ${tt(d)?d.toFixed(3):d}, state: ${u}, ${f?"out of":"in"} buffer`),this.state===De.ENDED)this.resetLoadingState();else if(o){const m=a.maxFragLookUpTolerance,g=o.start-m,y=o.start+o.duration+m;if(f||y<h.start||g>h.end){const v=d>y;(d<g||v)&&(v&&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 m=this.lastCurrentTime;if(d>m&&(this.lastCurrentTime=d),!this.loadingParts){const g=Math.max(h.end,d),y=this.shouldLoadParts(this.getLevelDetails(),g);y&&(this.log(`LL-Part loading ON after seeking to ${d.toFixed(2)} with buffer @${g.toFixed(2)}`),this.loadingParts=y)}}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===De.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=i,this.hls=e,this.fragmentLoader=new Qde(e.config),this.keyLoader=r,this.fragmentTracker=n,this.config=e.config,this.decrypter=new TA(e.config)}registerListeners(){const{hls:e}=this;e.on(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(B.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(B.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===De.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=De.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,s=this.config.timelineOffset||0;if(r<=s)return!1;const i=e.buffered;this.config.maxBufferHole&&i&&i.length>1&&(e=Pt.bufferedInfo(i,e.start,0));const a=e.nextStart;if(a&&a>s&&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 Pt.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;hs(r,"seeking",this.onMediaSeeking),hs(r,"ended",this.onMediaEnded);const s=this.config;this.levels&&s.autoStartLoad&&this.state===De.STOPPED&&this.startLoad(s.startPosition)}onMediaDetaching(e,n){const r=!!n.transferMedia,s=this.media;if(s!==null){if(s.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Ls(s,"seeking",this.onMediaSeeking),Ls(s,"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=De.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 s=i=>{const a=i.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${i.part?" part: "+i.part.index:""} of ${this.fragInfo(a,!1,i.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(a);return}a.stats.chunkCount++,this._handleFragmentLoadProgress(i)};this._doFragLoad(e,n,r,s).then(i=>{if(!i)return;const a=this.state,o=i.frag;if(this.fragContextChanged(o)){(a===De.FRAG_LOADING||!this.fragCurrent&&a===De.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=De.IDLE);return}"payload"in i&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(B.FRAG_LOADED,i)),this._handleFragmentLoadComplete(i)}).catch(i=>{this.state===De.STOPPED||this.state===De.ERROR||(this.warn(`Frag error: ${(i==null?void 0:i.message)||i}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var n;const{fragmentTracker:r}=this;if(r.getState(e)===xr.APPENDING){const i=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,i),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)===xr.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 s={startOffset:e,endOffset:n,type:r};this.hls.trigger(B.BUFFER_FLUSHING,s)}_loadInitSegment(e,n){this._doFragLoad(e,n).then(r=>{const s=r==null?void 0:r.frag;if(!s||this.fragContextChanged(s)||!this.levels)throw new Error("init load aborted");return r}).then(r=>{const{hls:s}=this,{frag:i,payload:a}=r,o=i.decryptdata;if(a&&a.byteLength>0&&o!=null&&o.key&&o.iv&&jd(o.method)){const l=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,RA(o.method)).catch(c=>{throw s.trigger(B.ERROR,{type:ft.MEDIA_ERROR,details:Se.FRAG_DECRYPT_ERROR,fatal:!1,error:c,reason:c.message,frag:i}),c}).then(c=>{const u=self.performance.now();return s.trigger(B.FRAG_DECRYPTED,{frag:i,payload:c,stats:{tstart:l,tdecrypt:u}}),r.payload=c,this.completeInitSegmentLoad(r)})}return this.completeInitSegmentLoad(r)}).catch(r=>{this.state===De.STOPPED||this.state===De.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!==De.STOPPED&&(this.state=De.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,s;const i=e.tracks;if(i&&!n.encrypted&&((r=i.audio)!=null&&r.encrypted||(s=i.video)!=null&&s.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(B.ERROR,{type:ft.KEY_SYSTEM_ERROR,details:Se.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?Ehe.toString(Pt.getBuffered(r)):"(detached)"})`),ar(e)){var s;if(e.type!==rt.SUBTITLE){const a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=De.IDLE;return}}const i=(s=this.levels)==null?void 0:s[e.level];i!=null&&i.fragmentError&&(this.log(`Resetting level fragment error count of ${i.fragmentError} on frag buffered`),i.fragmentError=0)}this.state=De.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:n}=this;if(!n)return;const{frag:r,part:s,partsLoaded:i}=e,a=!i||i.length===0||i.some(l=>!l),o=new AA(r.level,r.sn,r.stats.chunkCount+1,0,s?s.index:-1,!a);n.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,n,r=null,s){var i;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&&!((i=e.decryptdata)!=null&&i.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=De.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(h=>{if(!this.fragContextChanged(h.frag))return this.hls.trigger(B.KEY_LOADED,h),this.state===De.KEY_LOADING&&(this.state=De.IDLE),h}),this.hls.trigger(B.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(ar(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&&ar(e)){const h=a.partList;if(h&&s){r>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);const f=this.getNextPart(h,e,r);if(f>-1){const m=h[f];e=this.fragCurrent=m.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${m.index} (${f}/${h.length-1}) of ${this.fragInfo(e,!1,m)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=m.start+m.duration,this.state=De.FRAG_LOADING;let g;return o?g=o.then(y=>!y||this.fragContextChanged(y.frag)?null:this.doFragPartsLoad(e,m,n,s)).catch(y=>this.handleFragLoadError(y)):g=this.doFragPartsLoad(e,m,n,s).catch(y=>this.handleFragLoadError(y)),this.hls.trigger(B.FRAG_LOADING,{frag:e,part:m,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):g}else if(!e.url||this.loadedEndOfParts(h,r))return Promise.resolve(null)}}if(ar(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))}`),tt(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=De.FRAG_LOADING;const u=this.config.progressive&&e.type!==rt.SUBTITLE;let d;return u&&o?d=o.then(h=>!h||this.fragContextChanged(h.frag)?null:this.fragmentLoader.load(e,s)).catch(h=>this.handleFragLoadError(h)):d=Promise.all([this.fragmentLoader.load(e,u?s:void 0),o]).then(([h])=>(!u&&s&&s(h),h)).catch(h=>this.handleFragLoadError(h)),this.hls.trigger(B.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,s){return new Promise((i,a)=>{var o;const l=[],c=(o=r.details)==null?void 0:o.partList,u=d=>{this.fragmentLoader.loadPart(e,d,s).then(h=>{l[d.index]=h;const f=h.part;this.hls.trigger(B.FRAG_LOADED,h);const m=DD(r.details,e.sn,d.index+1)||J5(c,e.sn,d.index+1);if(m)u(m);else return i({frag:e,part:f,partsLoaded:l})}).catch(a)};u(n)})}handleFragLoadError(e){if("data"in e){const n=e.data;n.frag&&n.details===Se.INTERNAL_ABORTED?this.handleFragLoadAborted(n.frag,n.part):n.frag&&n.type===ft.KEY_SYSTEM_ERROR?(n.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(n.frag)):this.hls.trigger(B.ERROR,n)}else this.hls.trigger(B.ERROR,{type:ft.OTHER_ERROR,details:Se.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const n=this.getCurrentContext(e);if(!n||this.state!==De.PARSING){!this.fragCurrent&&this.state!==De.STOPPED&&this.state!==De.ERROR&&(this.state=De.IDLE);return}const{frag:r,part:s,level:i}=n,a=self.performance.now();r.stats.parsing.end=a,s&&(s.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,s,i,e.partial)}shouldLoadParts(e,n){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var r;const i=e.partList[0];if(i.fragment.type===rt.SUBTITLE)return!1;const a=i.end+(((r=e.fragmentHint)==null?void 0:r.duration)||0);if(n>=a){var s;if((this.hls.hasEnoughToStart?((s=this.media)==null?void 0:s.currentTime)||this.lastCurrentTime:this.getLoadPosition())>i.start-i.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:n,fragCurrent:r}=this,{level:s,sn:i,part:a}=e;if(!(n!=null&&n[s]))return this.warn(`Levels object was unset while buffering fragment ${i} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;const o=n[s],l=o.details,c=a>-1?DD(l,i,a):null,u=c?c.fragment:Q5(l,i,r);return u?(r&&r!==u&&(u.stats=r.stats),{frag:u,part:c,level:o}):null}bufferFragmentData(e,n,r,s,i){if(this.state!==De.PARSING)return;const{data1:a,data2:o}=e;let l=a;if(o&&(l=ki(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:s,offset:u,parent:n.type,data:l};if(this.hls.trigger(B.BUFFER_APPENDING,d),e.dropped&&e.independent&&!r){if(i)return;this.flushBufferGap(n)}}flushBufferGap(e){const n=this.media;if(!n)return;if(!Pt.isBuffered(n,n.currentTime)){this.flushMainBuffer(0,e.start);return}const r=n.currentTime,s=Pt.bufferInfo(n,r,0),i=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,i*.25),o=Math.max(Math.min(e.start-a,s.end-a),r+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,n){var r;const s=this.getLoadPosition();if(!tt(s))return null;const a=this.lastCurrentTime>s||(r=this.media)!=null&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,s,n,a)}getFwdBufferInfoAtPos(e,n,r,s){const i=Pt.bufferInfo(e,n,s);if(i.len===0&&i.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(n,r);if(a&&(i.nextStart<=a.end||a.gap)){const o=Math.max(Math.min(i.nextStart,a.end)-n,s);return Pt.bufferInfo(e,n,o)}}return i}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 s=e.nextStart;if(s&&r.start>s){const i=e.buffered;if(i){let a=e.len;const o=e.bufferedIndex;for(let l=i.length-1;l>o;l--)i[l].start<r.start&&(a+=i[l].end-i[l].start);return a>=n}}return!1}reduceMaxBufferLength(e,n){const r=this.config,s=Math.max(Math.min(e-n,r.maxBufferLength),n),i=Math.max(e-n*3,r.maxMaxBufferLength/2,s);return i>=s?(r.maxMaxBufferLength=i,this.warn(`Reduce max buffer length to ${i}s`),!0):!1}getAppendedFrag(e,n=rt.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,s=r.length;if(!s)return null;const{config:i}=this,a=n.fragmentStart,o=i.lowLatencyMode&&!!n.partList;let l=null;if(n.live){const d=i.initialLiveManifestSize;if(s<d)return this.warn(`Not enough fragments to start playback (have: ${s}, 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,m=this.hls.liveSyncPosition,g=((c=l)==null?void 0:c.start)||0;let y,v;f!==-1&&f>=a?(y=f,v=f===h?"config":"next load start"):m!==null?(y=m,v="live edge"):(y=e,v="buffer pos"),y<g&&(y=g,v="live frag start"),y<a&&(y=a,v="playlist start"),(this.startPosition!=y||this.nextLoadPosition!=y)&&(this.log(`Setting startPosition to ${y.toFixed(3)} ${f===-1?"":`(from ${h}) `}based on ${v}. live edge: ${m} live frag start: ${g.toFixed(3)} playlist start: ${a.toFixed(3)} buffer pos: ${e}`),this.startPosition=this.nextLoadPosition=y)}}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===xr.OK||r===xr.PARTIAL&&!!e.gap}getNextFragmentLoopLoading(e,n,r,s,i){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,s,0);if(o!==null&&r.len+o.len>=i){const l=a.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(MD(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(MD(this.config)&&e.type!==rt.SUBTITLE){const r=this.hls.interstitialsManager,s=r==null?void 0:r.bufferingItem;if(s){const a=s.event;if(a){if(a.appendInPlace||Math.abs(e.start-s.start)>1||s.start===0)return null}else if(e.end<=s.start&&(n==null?void 0:n.live)===!1||e.start>s.end&&s.nextEvent&&(s.nextEvent.appendInPlace||e.start-s.end>1))return null}const i=r==null?void 0:r.playerQueue;if(i)for(let a=i.length;a--;){const o=i[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 s=-1,i=!1,a=!0;for(let o=0,l=e.length;o<l;o++){const c=e[o];if(a=a&&!c.independent,s>-1&&r<c.start)break;const u=c.loaded;u?s=-1:(i||(c.independent||a)&&c.fragment===n)&&(c.fragment!==n&&this.warn(`Need buffer at ${r} but next unloaded part starts at ${c.start}`),s=o),i=u}return s}loadedEndOfParts(e,n){let r;for(let s=e.length;s--;){if(r=e[s],!r.loaded)return!1;if(n>r.start)return!0}return!1}getInitialLiveFragment(e){const n=e.fragments,r=this.fragPrevious;let s=null;if(r){if(e.hasProgramDateTime&&(s=Bde(n,r.endProgramDateTime,this.config.maxFragLookUpTolerance),s&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${r.programDateTime}`)),!s){const i=r.sn+1;if(i>=e.startSN&&i<=e.endSN){const a=n[i-e.startSN];r.cc===a.cc&&(s=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=j5(e,r.cc,r.end),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const i=this.hls.liveSyncPosition;i!==null&&(s=this.getFragmentAtPosition(i,this.bitrateTest?e.fragmentEnd:e.edge,e))}return s}getFragmentAtPosition(e,n,r){const{config:s}=this;let{fragPrevious:i}=this,{fragments:a,endSN:o}=r;const{fragmentHint:l}=r,{maxFragLookUpTolerance:c}=s,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 g=e<this.lastCurrentTime||e>n-c||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:c;h=ou(i,a,e,g)}else h=a[a.length-1];if(h){const m=h.sn-r.startSN,g=this.fragmentTracker.getState(h);if((g===xr.OK||g===xr.PARTIAL&&h.gap)&&(i=h),i&&h.sn===i.sn&&(!d||u[0].fragment.sn>h.sn||!r.live)&&h.level===i.level){const v=a[m+1];h.sn<o&&this.fragmentTracker.getState(v)!==xr.OK?h=v:h=null}}return h}alignPlaylists(e,n,r){const s=e.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;const i=e.fragmentStart,a=!n,o=e.alignedSliding&&tt(i);if(a||!o&&!i){She(r,e);const l=e.fragmentStart;return this.log(`Live playlist sliding: ${l.toFixed(2)} start-sn: ${n?n.startSN:"na"}->${e.startSN} fragments: ${s}`),l}return i}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 s=this.timelineOffset;if(r===-1){const i=this.startTimeOffset!==null,a=i?this.startTimeOffset:e.startTimeOffset;a!==null&&tt(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 ${i?"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+s}this.nextLoadPosition=r+s}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&&ar(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!==De.FRAG_LOADING_WAITING_RETRY)&&(this.state=De.IDLE)}onFragmentOrKeyLoadError(e,n){var r;if(n.chunkMeta&&!n.frag){const v=this.getCurrentContext(n.chunkMeta);v&&(n.frag=v.frag)}const s=n.frag;if(!s||s.type!==e||!this.levels)return;if(this.fragContextChanged(s)){var i;this.warn(`Frag load error must match current frag to retry ${s.url} > ${(i=this.fragCurrent)==null?void 0:i.url}`);return}const a=n.details===Se.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(s,!0);const o=n.errorAction;if(!o){this.state=De.ERROR;return}const{action:l,flags:c,retryCount:u=0,retryConfig:d}=o,h=!!d,f=h&&l===$r.RetryRequest,m=h&&!o.resolved&&c===Bs.MoveAllAlternatesMatchingHost,g=(r=this.hls.latestLevelDetails)==null?void 0:r.live;if(!f&&m&&ar(s)&&!s.endList&&g&&!B5(n))this.resetFragmentErrors(e),this.treatAsGap(s),o.resolved=!0;else if((f||m)&&u<d.maxNumRetry){var y;const v=Tw((y=n.response)==null?void 0:y.code),_=wA(d,u);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+_,this.state=De.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,v){this.log("Waiting for connection (offline)"),this.retryDate=1/0,n.reason="offline";return}this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${n.details}, retrying loading ${u+1}/${d.maxNumRetry} in ${_}ms`)}else if(d)if(this.resetFragmentErrors(e),u<d.maxNumRetry)!a&&l!==$r.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${n.details} reached or exceeded max retry (${u})`);return}else l===$r.SendAlternateToPenaltyBox?this.state=De.WAITING_LEVEL:this.state=De.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),n=this.retryDate,r=n===1/0;(!n||e>=n||r&&!Tw(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=De.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===De.PARSING||this.state===De.PARSED){const n=e.frag,r=e.parent,s=this.getFwdBufferInfo(this.mediaBuffer,r),i=s&&s.len>.5;i&&this.reduceMaxBufferLength(s.len,(n==null?void 0:n.duration)||10);const a=!i;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===rt.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==De.STOPPED&&(this.state=De.IDLE)}afterBufferFlushed(e,n,r){if(!e)return;const s=Pt.getBuffered(e);this.fragmentTracker.detectEvictedFragments(n,s,r),this.state===De.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==De.STOPPED&&(this.state=De.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,s){const i=r.details;if(!i){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=s?0:W5(i,e,u.startPTS,u.endPTS,u.startDTS,u.endDTS,this);return this.hls.trigger(B.LEVEL_PTS_UPDATED,{details:i,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(B.ERROR,{type:ft.MEDIA_ERROR,details:Se.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=De.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${n?" part: "+n.index:""} of ${this.fragInfo(e,!1,n)})`),this.hls.trigger(B.FRAG_PARSED,{frag:e,part:n})}playlistLabel(){return this.playlistType===rt.MAIN?"level":"track"}fragInfo(e,n=!0,r){var s,i;return`${this.playlistLabel()} ${e.level} (${r?"part":"frag"}:[${((s=n&&!r?e.startPTS:(r||e).start)!=null?s:NaN).toFixed(3)}-${((i=n&&!r?e.endPTS:(r||e).end)!=null?i: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 MD(t){return!!t.interstitialsController&&t.enableInterstitialPlayback!==!1}class n4{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=whe(e,n);else return new Uint8Array(0);return this.reset(),r}reset(){this.chunks.length=0,this.dataLength=0}}function whe(t,e){const n=new Uint8Array(e);let r=0;for(let s=0;s<t.length;s++){const i=t[s];n.set(i,r),r+=i.length}return n}var xx={exports:{}},jD;function The(){return jD||(jD=1,function(t){var e=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function s(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function i(l,c,u,d,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new s(u,d||l,h),m=n?n+c:c;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],f]:l._events[m].push(f):(l._events[m]=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,m=new Array(f);h<f;h++)m[h]=d[h].fn;return m},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,m){var g=n?n+c:c;if(!this._events[g])return!1;var y=this._events[g],v=arguments.length,_,S;if(y.fn){switch(y.once&&this.removeListener(c,y.fn,void 0,!0),v){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,u),!0;case 3:return y.fn.call(y.context,u,d),!0;case 4:return y.fn.call(y.context,u,d,h),!0;case 5:return y.fn.call(y.context,u,d,h,f),!0;case 6:return y.fn.call(y.context,u,d,h,f,m),!0}for(S=1,_=new Array(v-1);S<v;S++)_[S-1]=arguments[S];y.fn.apply(y.context,_)}else{var E=y.length,L;for(S=0;S<E;S++)switch(y[S].once&&this.removeListener(c,y[S].fn,void 0,!0),v){case 1:y[S].fn.call(y[S].context);break;case 2:y[S].fn.call(y[S].context,u);break;case 3:y[S].fn.call(y[S].context,u,d);break;case 4:y[S].fn.call(y[S].context,u,d,h);break;default:if(!_)for(L=1,_=new Array(v-1);L<v;L++)_[L-1]=arguments[L];y[S].fn.apply(y[S].context,_)}}return!0},o.prototype.on=function(c,u,d){return i(this,c,u,d,!1)},o.prototype.once=function(c,u,d){return i(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 m=this._events[f];if(m.fn)m.fn===u&&(!h||m.once)&&(!d||m.context===d)&&a(this,f);else{for(var g=0,y=[],v=m.length;g<v;g++)(m[g].fn!==u||h&&!m[g].once||d&&m[g].context!==d)&&y.push(m[g]);y.length?this._events[f]=y.length===1?y[0]:y: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}(xx)),xx.exports}var Ahe=The(),LA=Que(Ahe);const Kp="1.6.16",xh={};function Rhe(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Che(){const t=xh[Kp];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),s={worker:new self.Worker(n),objectURL:n,clientCount:1};return xh[Kp]=s,s}function khe(t){const e=xh[t];if(e)return e.clientCount++,e;const n=new self.URL(t,self.location.href).href,s={worker:new self.Worker(n),scriptURL:n,clientCount:1};return xh[t]=s,s}function Lhe(t){const e=xh[t||Kp];if(e&&e.clientCount--===1){const{worker:r,objectURL:s}=e;delete xh[t||Kp],s&&self.URL.revokeObjectURL(s),r.terminate()}}function r4(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 IA(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 n_(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 Hp(t,e){const n=e;let r=0;for(;IA(t,e);){r+=10;const s=n_(t,e+6);r+=s,r4(t,e+10)&&(r+=10),e+=r}if(r>0)return t.subarray(n,n+r)}function Ihe(t,e,n,r){const s=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],i=e[n+2],a=i>>2&15;if(a>12){const f=new Error(`invalid ADTS sampling index:${a}`);t.emit(B.ERROR,B.ERROR,{type:ft.MEDIA_ERROR,details:Se.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}const o=(i>>6&3)+1,l=e[n+3]>>6&3|(i&1)<<2,c="mp4a.40."+o,u=s[a];let d=a;(o===5||o===29)&&(d-=3);const h=[o<<3|(d&14)>>1,(d&1)<<7|l<<3];return fn.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 s4(t,e){return t[e]===255&&(t[e+1]&246)===240}function i4(t,e){return t[e+1]&1?7:9}function PA(t,e){return(t[e+3]&3)<<11|t[e+4]<<3|(t[e+5]&224)>>>5}function Phe(t,e){return e+5<t.length}function Q0(t,e){return e+1<t.length&&s4(t,e)}function Dhe(t,e){return Phe(t,e)&&s4(t,e)&&PA(t,e)<=t.length-e}function Ohe(t,e){if(Q0(t,e)){const n=i4(t,e);if(e+n>=t.length)return!1;const r=PA(t,e);if(r<=n)return!1;const s=e+r;return s===t.length||Q0(t,s)}return!1}function a4(t,e,n,r,s){if(!t.samplerate){const i=Ihe(e,n,r,s);if(!i)return;vn(t,i)}}function o4(t){return 1024*9e4/t}function Nhe(t,e){const n=i4(t,e);if(e+n<=t.length){const r=PA(t,e)-n;if(r>0)return{headerLength:n,frameLength:r}}}function l4(t,e,n,r,s){const i=o4(t.samplerate),a=r+s*i,o=Nhe(e,n);let l;if(o){const{frameLength:d,headerLength:h}=o,f=h+d,m=Math.max(0,n+f-e.length);m?(l=new Uint8Array(f-h),l.set(e.subarray(n+h,e.length),0)):l=e.subarray(n+h,n+f);const g={unit:l,pts:a};return m||t.samples.push(g),{sample:g,length:f,missing:m}}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 Mhe(t,e){return IA(t,e)&&n_(t,e+6)+10<=t.length-e}function jhe(t){return t instanceof ArrayBuffer?t:t.byteOffset==0&&t.byteLength==t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}function Sx(t,e=0,n=1/0){return Uhe(t,e,n,Uint8Array)}function Uhe(t,e,n,r){const s=Bhe(t);let i=1;"BYTES_PER_ELEMENT"in r&&(i=r.BYTES_PER_ELEMENT);const a=Fhe(t)?t.byteOffset:0,o=(a+t.byteLength)/i,l=(a+e)/i,c=Math.floor(Math.max(0,Math.min(l,o))),u=Math.floor(Math.min(c+Math.max(n,0),o));return new r(s,c,u-c)}function Bhe(t){return t instanceof ArrayBuffer?t:t.buffer}function Fhe(t){return t&&t.buffer instanceof ArrayBuffer&&t.byteLength!==void 0&&t.byteOffset!==void 0}function $he(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 s=ti(Sx(t.data,1,r)),i=t.data[2+r],a=t.data.subarray(3+r).indexOf(0);if(a===-1)return;const o=ti(Sx(t.data,3+r,a));let l;return s==="-->"?l=ti(Sx(t.data,4+r+a)):l=jhe(t.data.subarray(4+r+a)),e.mimeType=s,e.pictureType=i,e.description=o,e.data=l,e}function Vhe(t){if(t.size<2)return;const e=ti(t.data,!0),n=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:n.buffer}}function Ghe(t){if(t.size<2)return;if(t.type==="TXXX"){let n=1;const r=ti(t.data.subarray(n),!0);n+=r.length+1;const s=ti(t.data.subarray(n));return{key:t.type,info:r,data:s}}const e=ti(t.data.subarray(1));return{key:t.type,info:"",data:e}}function Khe(t){if(t.type==="WXXX"){if(t.size<2)return;let n=1;const r=ti(t.data.subarray(n),!0);n+=r.length+1;const s=ti(t.data.subarray(n));return{key:t.type,info:r,data:s}}const e=ti(t.data);return{key:t.type,info:"",data:e}}function Hhe(t){return t.type==="PRIV"?Vhe(t):t.type[0]==="W"?Khe(t):t.type==="APIC"?$he(t):Ghe(t)}function zhe(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),n=n_(t,4),r=10;return{type:e,size:n,data:t.subarray(r,r+n)}}const Vg=10,qhe=10;function c4(t){let e=0;const n=[];for(;IA(t,e);){const r=n_(t,e+6);t[e+5]>>6&1&&(e+=Vg),e+=Vg;const s=e+r;for(;e+qhe<s;){const i=zhe(t.subarray(e)),a=Hhe(i);a&&n.push(a),e+=i.size+Vg}r4(t,e)&&(e+=Vg)}return n}function u4(t){return t&&t.key==="PRIV"&&t.info==="com.apple.streaming.transportStreamTimestamp"}function Whe(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 DA(t){const e=c4(t);for(let n=0;n<e.length;n++){const r=e[n];if(u4(r))return Whe(r)}}let Hs=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 pa(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class OA{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,s){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=ki(this.cachedData,e),this.cachedData=null);let r=Hp(e,0),s=r?r.length:0,i;const a=this._audioTrack,o=this._id3Track,l=r?DA(r):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&tt(l))&&(this.basePTS=Yhe(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:Hs.audioId3,duration:Number.POSITIVE_INFINITY});s<c;){if(this.canParse(e,s)){const u=this.appendFrame(a,e,s);u?(this.frameIndex++,this.lastPTS=u.sample.pts,s+=u.length,i=s):s=c}else Mhe(e,s)?(r=Hp(e,s),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Hs.audioId3,duration:Number.POSITIVE_INFINITY}),s+=r.length,i=s):s++;if(s===c&&i!==c){const u=e.slice(i);this.cachedData?this.cachedData=ki(this.cachedData,u):this.cachedData=u}}return{audioTrack:a,videoTrack:pa(),id3Track:o,textTrack:pa()}}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:pa(),id3Track:this._id3Track,textTrack:pa()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Yhe=(t,e,n)=>{if(tt(t))return t*90;const r=n?n.baseTime*9e4/n.timescale:0;return e*9e4+r};let Gg=null;const Xhe=[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],Qhe=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Jhe=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Zhe=[0,1,1,4];function d4(t,e,n,r,s){if(n+24>e.length)return;const i=h4(e,n);if(i&&n+i.frameLength<=e.length){const a=i.samplesPerFrame*9e4/i.sampleRate,o=r+s*a,l={unit:e.subarray(n,n+i.frameLength),pts:o,dts:o};return t.config=[],t.channelCount=i.channelCount,t.samplerate=i.sampleRate,t.samples.push(l),{sample:l,length:i.frameLength,missing:0}}}function h4(t,e){const n=t[e+1]>>3&3,r=t[e+1]>>1&3,s=t[e+2]>>4&15,i=t[e+2]>>2&3;if(n!==1&&s!==0&&s!==15&&i!==3){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=n===3?3-r:r===3?3:4,c=Xhe[l*14+s-1]*1e3,d=Qhe[(n===3?0:n===2?1:2)*3+i],h=o===3?1:2,f=Jhe[n][r],m=Zhe[r],g=f*8*m,y=Math.floor(f*c/d+a)*m;if(Gg===null){const S=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Gg=S?parseInt(S[1]):0}return!!Gg&&Gg<=87&&r===2&&c>=224e3&&o===0&&(t[e+3]=t[e+3]|128),{sampleRate:d,channelCount:h,frameLength:y,samplesPerFrame:g}}}function NA(t,e){return t[e]===255&&(t[e+1]&224)===224&&(t[e+1]&6)!==0}function f4(t,e){return e+1<t.length&&NA(t,e)}function efe(t,e){return NA(t,e)&&4<=t.length-e}function p4(t,e){if(e+1<t.length&&NA(t,e)){const r=h4(t,e);let s=4;r!=null&&r.frameLength&&(s=r.frameLength);const i=e+s;return i===t.length||f4(t,i)}return!1}class tfe extends OA{constructor(e,n){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=n}resetInitSegment(e,n,r,s){super.resetInitSegment(e,n,r,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:n,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e,n){if(!e)return!1;const r=Hp(e,0);let s=(r==null?void 0:r.length)||0;if(p4(e,s))return!1;for(let i=e.length;s<i;s++)if(Ohe(e,s))return n.log("ADTS sync word found !"),!0;return!1}canParse(e,n){return Dhe(e,n)}appendFrame(e,n,r){a4(e,this.observer,n,r,e.manifestCodec);const s=l4(e,n,r,this.basePTS,this.frameIndex);if(s&&s.missing===0)return s}}const m4=(t,e)=>{let n=0,r=5;e+=r;const s=new Uint32Array(1),i=new Uint32Array(1),a=new Uint8Array(1);for(;r>0;){a[0]=t[e];const o=Math.min(r,8),l=8-o;i[0]=4278190080>>>24+l<<l,s[0]=(a[0]&i[0])>>l,n=n?n<<o|s[0]:s[0],e+=1,r-=o}return n};class nfe extends OA{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,n,r,s){super.resetInitSegment(e,n,r,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:n,duration:s,inputTimeScale:9e4,dropped:0}}canParse(e,n){return n+64<e.length}appendFrame(e,n,r){const s=g4(e,n,r,this.basePTS,this.frameIndex);if(s!==-1)return{sample:e.samples[e.samples.length-1],length:s,missing:0}}static probe(e){if(!e)return!1;const n=Hp(e,0);if(!n)return!1;const r=n.length;return e[r]===11&&e[r+1]===119&&DA(n)!==void 0&&m4(e,r)<16}}function g4(t,e,n,r,s){if(n+8>e.length||e[n]!==11||e[n+1]!==119)return-1;const i=e[n+4]>>6;if(i>=3)return-1;const o=[48e3,44100,32e3][i],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+i]*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,g=[2,1,2,3,3,4,4,5][d]+f,y=e[n+5]>>3,v=e[n+5]&7,_=new Uint8Array([i<<6|y<<1|v>>2,(v&3)<<6|d<<3|f<<2|l>>4,l<<4&224]),S=1536/o*9e4,E=r+s*S,L=e.subarray(n,n+u);return t.config=_,t.channelCount=g,t.samplerate=o,t.samples.push({unit:L,pts:E}),u}class rfe extends OA{resetInitSegment(e,n,r,s){super.resetInitSegment(e,n,r,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:n,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const n=Hp(e,0);let r=(n==null?void 0:n.length)||0;if(n&&e[r]===11&&e[r+1]===119&&DA(n)!==void 0&&m4(e,r)<=16)return!1;for(let s=e.length;r<s;r++)if(p4(e,r))return fn.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,n){return efe(e,n)}appendFrame(e,n,r){if(this.basePTS!==null)return d4(e,n,r,this.basePTS,this.frameIndex)}}const sfe=/\/emsg[-/]ID3/i;class ife{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,s){const i=this.videoTrack=pa("video",1),a=this.audioTrack=pa("audio",1),o=this.txtTrack=pa("text",1);if(this.id3Track=pa("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=A5(e);if(l.video){const{id:c,timescale:u,codec:d,supplemental:h}=l.video;i.id=c,i.timescale=o.timescale=u,i.codec=d,i.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=E5.text,i.sampleDuration=0,i.duration=a.duration=s}resetContiguity(){this.remainderData=null}static probe(e){return nde(e)}demux(e,n){this.timeOffset=n;let r=e;const s=this.videoTrack,i=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=ki(this.remainderData,e));const o=cde(r);this.remainderData=o.remainder,s.samples=o.valid||new Uint8Array}else s.samples=r;const a=this.extractID3Track(s,n);return i.samples=tD(n,s),{videoTrack:s,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 s=this.extractID3Track(n,this.timeOffset);return r.samples=tD(e,n),{videoTrack:n,audioTrack:pa(),id3Track:s,textTrack:pa()}}extractID3Track(e,n){const r=this.id3Track;if(e.samples.length){const s=Ft(e.samples,["emsg"]);s&&s.forEach(i=>{const a=dde(i);if(sfe.test(a.schemeIdUri)){const o=UD(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:Hs.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=UD(a,n);r.samples.push({data:a.payload,len:a.payload.byteLength,dts:o,pts:o,type:Hs.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 UD(t,e){return tt(t.presentationTime)?t.presentationTime/t.timeScale:e+t.presentationTimeDelta/t.timeScale}class afe{constructor(e,n,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new TA(n,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,zl.cbc)}decryptAacSample(e,n,r){const s=e[n].unit;if(s.length<=16)return;const i=s.subarray(16,s.length-s.length%16),a=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(a).then(o=>{const l=new Uint8Array(o);s.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 s=0;for(let i=32;i<e.length-16;i+=160,s+=16)r.set(e.subarray(i,i+16),s);return r}getAvcDecryptedUnit(e,n){const r=new Uint8Array(n);let s=0;for(let i=32;i<e.length-16;i+=160,s+=16)e.set(r.subarray(s,s+16),i);return e}decryptAvcSample(e,n,r,s,i){const a=k5(i.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{i.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,n,r+1,s)}).catch(s)}decryptAvcSamples(e,n,r,s){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;n++,r=0){if(n>=e.length){s();return}const i=e[n].units;for(;!(r>=i.length);r++){const a=i[r];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,n,r,s,a),!this.decrypter.isSync()))return}}}}class y4{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,s;if((!r||r.units.length===0)&&(r=e[e.length-1]),(n=r)!=null&&n.units){const i=r.units;s=i[i.length-1]}return s}pushAccessUnit(e,n){if(e.units.length&&e.frame){if(e.pts===void 0){const r=n.samples,s=r.length;if(s){const i=r[s-1];e.pts=i.pts,e.dts=i.dts}else{n.dropped++;return}}n.samples.push(e)}}parseNALu(e,n,r){const s=n.byteLength;let i=e.naluState||0;const a=i,o=[];let l=0,c,u,d,h=-1,f=0;for(i===-1&&(h=0,f=this.getNALuType(n,0),i=0,l=1);l<s;){if(c=n[l++],!i){i=c?0:1;continue}if(i===1){i=c?0:2;continue}if(!c)i=3;else if(c===1){if(u=l-i-1,h>=0){const m={data:n.subarray(h,u),type:f};o.push(m)}else{const m=this.getLastNalUnit(e.samples);m&&(a&&l<=4-a&&m.state&&(m.data=m.data.subarray(0,m.data.byteLength-a)),u>0&&(m.data=ki(m.data,n.subarray(0,u)),m.state=0))}l<s?(d=this.getNALuType(n,l),h=l,f=d,i=0):i=-1}else i=0}if(h>=0&&i>=0){const m={data:n.subarray(h,s),type:f,state:i};o.push(m)}if(o.length===0){const m=this.getLastNalUnit(e.samples);m&&(m.data=ki(m.data,n))}return e.naluState=i,o}}class np{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,s=new Uint8Array(4),i=Math.min(4,n);if(i===0)throw new Error("no bytes available");s.set(e.subarray(r,r+i)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=i*8,this.bytesAvailable-=i}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&&fn.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 ofe extends y4{parsePES(e,n,r,s){const i=this.parseNALu(e,r.data,s);let a=this.VideoSample,o,l=!1;r.data=null,a&&i.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),i.forEach(c=>{var u,d;switch(c.type){case 1:{let g=!1;o=!0;const y=c.data;if(l&&y.length>4){const v=this.readSliceType(y);(v===2||v===4||v===7||v===9)&&(g=!0)}if(g){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=g;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,xA(c.data,1,r.pts,n.samples);break}case 7:{var f,m;o=!0,l=!0;const g=c.data,y=this.readSPS(g);if(!e.sps||e.width!==y.width||e.height!==y.height||((f=e.pixelRatio)==null?void 0:f[0])!==y.pixelRatio[0]||((m=e.pixelRatio)==null?void 0:m[1])!==y.pixelRatio[1]){e.width=y.width,e.height=y.height,e.pixelRatio=y.pixelRatio,e.sps=[g];const v=g.subarray(1,4);let _="avc1.";for(let S=0;S<3;S++){let E=v[S].toString(16);E.length<2&&(E="0"+E),_+=E}e.codec=_}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)}),s&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,n){return e[n]&31}readSliceType(e){const n=new np(e);return n.readUByte(),n.readUEG(),n.readUEG()}skipScalingList(e,n){let r=8,s=8,i;for(let a=0;a<e;a++)s!==0&&(i=n.readEG(),s=(r+i+256)%256),r=s===0?r:s}readSPS(e){const n=new np(e);let r=0,s=0,i=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),m=n.skipBits.bind(n),g=n.skipEG.bind(n),y=n.skipUEG.bind(n),v=this.skipScalingList.bind(this);u();const _=u();if(d(5),m(3),u(),y(),_===100||_===110||_===122||_===244||_===44||_===83||_===86||_===118||_===128){const I=h();if(I===3&&m(1),y(),y(),m(1),f())for(l=I!==3?8:12,c=0;c<l;c++)f()&&(c<6?v(16,n):v(64,n))}y();const S=h();if(S===0)h();else if(S===1)for(m(1),g(),g(),o=h(),c=0;c<o;c++)g();y(),m(1);const E=h(),L=h(),U=d(1);U===0&&m(1),m(1),f()&&(r=h(),s=h(),i=h(),a=h());let P=[1,1];if(f()&&f())switch(u()){case 1:P=[1,1];break;case 2:P=[12,11];break;case 3:P=[10,11];break;case 4:P=[16,11];break;case 5:P=[40,33];break;case 6:P=[24,11];break;case 7:P=[20,11];break;case 8:P=[32,11];break;case 9:P=[80,33];break;case 10:P=[18,11];break;case 11:P=[15,11];break;case 12:P=[64,33];break;case 13:P=[160,99];break;case 14:P=[4,3];break;case 15:P=[3,2];break;case 16:P=[2,1];break;case 255:{P=[u()<<8|u(),u()<<8|u()];break}}return{width:Math.ceil((E+1)*16-r*2-s*2),height:(2-U)*(L+1)*16-(U?2:4)*(i+a),pixelRatio:P}}}class lfe extends y4{constructor(...e){super(...e),this.initVPS=null}parsePES(e,n,r,s){const i=this.parseNALu(e,r.data,s);let a=this.VideoSample,o,l=!1;r.data=null,a&&i.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),i.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,xA(c.data,2,r.pts,n.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=vn(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 m in f.params)e.params[m]=f.params[m]}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 m in f)e.params[m]=f[m]}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)}),s&&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 s=0;s<e.byteLength;s++)s>=2&&e[s]===3&&e[s-1]===0&&e[s-2]===0||(n[r]=e[s],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 np(e);n.readUByte(),n.readUByte(),n.readBits(4),n.skipBits(2),n.readBits(6);const r=n.readBits(3),s=n.readBoolean();return{numTemporalLayers:r+1,temporalIdNested:s}}readSPS(e){const n=new np(this.ebsp2rbsp(e));n.readUByte(),n.readUByte(),n.readBits(4);const r=n.readBits(3);n.readBoolean();const s=n.readBits(2),i=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(),m=n.readUByte(),g=n.readUByte(),y=n.readUByte(),v=n.readUByte(),_=[],S=[];for(let it=0;it<r;it++)_.push(n.readBoolean()),S.push(n.readBoolean());if(r>0)for(let it=r;it<8;it++)n.readBits(2);for(let it=0;it<r;it++)_[it]&&(n.readUByte(),n.readUByte(),n.readUByte(),n.readUByte(),n.readUByte(),n.readUByte(),n.readUByte(),n.readUByte(),n.readUByte(),n.readUByte(),n.readUByte()),S[it]&&n.readUByte();n.readUEG();const E=n.readUEG();E==3&&n.skipBits(1);const L=n.readUEG(),U=n.readUEG(),P=n.readBoolean();let I=0,k=0,R=0,M=0;P&&(I+=n.readUEG(),k+=n.readUEG(),R+=n.readUEG(),M+=n.readUEG());const G=n.readUEG(),Y=n.readUEG(),q=n.readUEG(),X=n.readBoolean();for(let it=X?0:r;it<=r;it++)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 nn=0;nn<4;nn++)for(let mn=0;mn<(nn===3?2:6);mn++)if(!n.readBoolean())n.readUEG();else{const Cn=Math.min(64,1<<4+(nn<<1));nn>1&&n.readEG();for(let ln=0;ln<Cn;ln++)n.readEG()}n.readBoolean(),n.readBoolean(),n.readBoolean()&&(n.readUByte(),n.skipUEG(),n.skipUEG(),n.readBoolean());const ne=n.readUEG();let H=0;for(let it=0;it<ne;it++){let nn=!1;if(it!==0&&(nn=n.readBoolean()),nn){it===ne&&n.readUEG(),n.readBoolean(),n.readUEG();let mn=0;for(let On=0;On<=H;On++){const Cn=n.readBoolean();let ln=!1;Cn||(ln=n.readBoolean()),(Cn||ln)&&mn++}H=mn}else{const mn=n.readUEG(),On=n.readUEG();H=mn+On;for(let Cn=0;Cn<mn;Cn++)n.readUEG(),n.readBoolean();for(let Cn=0;Cn<On;Cn++)n.readUEG(),n.readBoolean()}}if(n.readBoolean()){const it=n.readUEG();for(let nn=0;nn<it;nn++){for(let mn=0;mn<q+4;mn++)n.readBits(1);n.readBits(1)}}let J=0,Q=1,ve=1,Te=!0,Ne=1,Ke=0;n.readBoolean(),n.readBoolean();let be=!1;if(n.readBoolean()){if(n.readBoolean()){const Nn=n.readUByte(),cr=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Ds=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];Nn>0&&Nn<16?(Q=cr[Nn-1],ve=Ds[Nn-1]):Nn===255&&(Q=n.readBits(16),ve=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(),be=n.readBoolean(),be&&(n.skipUEG(),n.skipUEG(),n.skipUEG(),n.skipUEG()),n.readBoolean()&&(Ne=n.readBits(32),Ke=n.readBits(32),n.readBoolean()&&n.readUEG(),n.readBoolean())){const Ds=n.readBoolean(),lt=n.readBoolean();let ht=!1;(Ds||lt)&&(ht=n.readBoolean(),ht&&(n.readUByte(),n.readBits(5),n.readBoolean(),n.readBits(5)),n.readBits(4),n.readBits(4),ht&&n.readBits(4),n.readBits(5),n.readBits(5),n.readBits(5));for(let Vt=0;Vt<=r;Vt++){Te=n.readBoolean();const Dr=Te||n.readBoolean();let vs=!1;Dr?n.readEG():vs=n.readBoolean();const Os=vs?1:n.readUEG()+1;if(Ds)for(let _s=0;_s<Os;_s++)n.readUEG(),n.readUEG(),ht&&(n.readUEG(),n.readUEG()),n.skipBits(1);if(lt)for(let _s=0;_s<Os;_s++)n.readUEG(),n.readUEG(),ht&&(n.readUEG(),n.readUEG()),n.skipBits(1)}}n.readBoolean()&&(n.readBoolean(),n.readBoolean(),n.readBoolean(),J=n.readUEG())}let Ae=L,we=U;if(P){let it=1,nn=1;E===1?it=nn=2:E==2&&(it=2),Ae=L-it*k-it*I,we=U-nn*M-nn*R}const Ue=s?["A","B","C"][s]:"",Oe=o<<24|l<<16|c<<8|u;let Dt=0;for(let it=0;it<32;it++)Dt=(Dt|(Oe>>it&1)<<31-it)>>>0;let en=Dt.toString(16);return a===1&&en==="2"&&(en="6"),{codecString:`hvc1.${Ue}${a}.${en}.${i?"H":"L"}${v}.B0`,params:{general_tier_flag:i,general_profile_idc:a,general_profile_space:s,general_profile_compatibility_flags:[o,l,c,u],general_constraint_indicator_flags:[d,h,f,m,g,y],general_level_idc:v,bit_depth:G+8,bit_depth_luma_minus8:G,bit_depth_chroma_minus8:Y,min_spatial_segmentation_idc:J,chroma_format_idc:E,frame_rate:{fixed:Te,fps:Ke/Ne}},width:Ae,height:we,pixelRatio:[Q,ve]}}readPPS(e){const n=new np(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 s=n.readBoolean(),i=n.readBoolean();let a=1;return i&&s?a=0:i?a=3:s&&(a=2),{parallelismType:a}}matchSPS(e,n){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,n).substr(3)}}const Ar=188;class el{constructor(e,n,r,s){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=s,this.videoParser=null}static probe(e,n){const r=el.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(Ar*5,n-Ar)+1,s=0;for(;s<r;){let i=!1,a=-1,o=0;for(let l=s;l<n;l+=Ar)if(e[l]===71&&(n-l===Ar||e[l+Ar]===71)){if(o++,a===-1&&(a=l,a!==0&&(r=Math.min(a+Ar*99,e.length-Ar)+1)),i||(i=Lw(e,l)===0),i&&o>1&&(a===0&&o>2||l+Ar>r))return a}else{if(o)return-1;break}s++}return-1}static createTrack(e,n){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:E5[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?n:void 0}}resetInitSegment(e,n,r,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=el.createTrack("video"),this._videoTrack.duration=s,this._audioTrack=el.createTrack("audio",s),this._id3Track=el.createTrack("id3"),this._txtTrack=el.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,s=!1){r||(this.sampleAes=null);let i;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,m=o.pesData,g=l.pesData,y=null,v=this.pmtParsed,_=this._pmtId,S=e.length;if(this.remainderData&&(e=ki(this.remainderData,e),S=e.length,this.remainderData=null),S<Ar&&!s)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:c};const E=Math.max(0,el.syncOffset(e));S-=(S-E)%Ar,S<e.byteLength&&!s&&(this.remainderData=new Uint8Array(e.buffer,S,e.buffer.byteLength-S));let L=0;for(let P=E;P<S;P+=Ar)if(e[P]===71){const I=!!(e[P+1]&64),k=Lw(e,P),R=(e[P+3]&48)>>4;let M;if(R>1){if(M=P+5+e[P+4],M===P+Ar)continue}else M=P+4;switch(k){case u:I&&(d&&(i=Vu(d,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,c,i,!1)),d={data:[],size:0}),d&&(d.data.push(e.subarray(M,P+Ar)),d.size+=P+Ar-M);break;case h:if(I){if(m&&(i=Vu(m,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,i);break;case"mp3":this.parseMPEGPES(o,i);break;case"ac3":this.parseAC3PES(o,i);break}m={data:[],size:0}}m&&(m.data.push(e.subarray(M,P+Ar)),m.size+=P+Ar-M);break;case f:I&&(g&&(i=Vu(g,this.logger))&&this.parseID3PES(l,i),g={data:[],size:0}),g&&(g.data.push(e.subarray(M,P+Ar)),g.size+=P+Ar-M);break;case 0:I&&(M+=e[M]+1),_=this._pmtId=cfe(e,M);break;case _:{I&&(M+=e[M]+1);const G=ufe(e,M,this.typeSupported,r,this.observer,this.logger);u=G.videoPid,u>0&&(a.pid=u,a.segmentCodec=G.segmentVideoCodec),h=G.audioPid,h>0&&(o.pid=h,o.segmentCodec=G.segmentAudioCodec),f=G.id3Pid,f>0&&(l.pid=f),y!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${P} after unknown PID '${y}'. Backtracking to sync byte @${E} to parse all TS packets.`),y=null,P=E-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=k;break}}else L++;L>0&&Iw(this.observer,new Error(`Found ${L} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=d,o.pesData=m,l.pesData=g;const U={audioTrack:o,videoTrack:a,id3Track:l,textTrack:c};return s&&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:s,textTrack:i}=e,a=r.pesData,o=n.pesData,l=s.pesData;let c;if(a&&(c=Vu(a,this.logger))?(this.readyVideoParser(r.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(r,i,c,!0),r.pesData=null)):r.pesData=a,o&&(c=Vu(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=Vu(l,this.logger))?(this.parseID3PES(s,c),s.pesData=null):s.pesData=l}demuxSampleAes(e,n,r){const s=this.demux(e,r,!0,!this.config.progressive),i=this.sampleAes=new afe(this.observer,this.config,n);return this.decrypt(s,i)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new ofe:e==="hevc"&&(this.videoParser=new lfe))}decrypt(e,n){return new Promise(r=>{const{audioTrack:s,videoTrack:i}=e;s.samples&&s.segmentCodec==="aac"?n.decryptAacSamples(s.samples,0,()=>{i.samples?n.decryptAvcSamples(i.samples,0,0,()=>{r(e)}):r(e)}):i.samples&&n.decryptAvcSamples(i.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 s=this.aacOverFlow;let i=n.data;if(s){this.aacOverFlow=null;const d=s.missing,h=s.sample.unit.byteLength;if(d===-1)i=ki(s.sample.unit,i);else{const f=h-d;s.sample.unit.set(i.subarray(0,d),f),e.samples.push(s.sample),r=s.missing}}let a,o;for(a=r,o=i.length;a<o-1&&!Q0(i,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",Iw(this.observer,new Error(d),h,this.logger),!h)return}a4(e,this.observer,i,a,this.audioCodec);let l;if(n.pts!==void 0)l=n.pts;else if(s){const d=o4(e.samplerate);l=s.sample.pts+d}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let c=0,u;for(;a<o;)if(u=l4(e,i,a,l,c),a+=u.length,u.missing){this.aacOverFlow=u;break}else for(c++;a<o-1&&!Q0(i,a);a++);}parseMPEGPES(e,n){const r=n.data,s=r.length;let i=0,a=0;const o=n.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<s;)if(f4(r,a)){const l=d4(e,r,a,o,i);if(l)a+=l.length,i++;else break}else a++}parseAC3PES(e,n){{const r=n.data,s=n.pts;if(s===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const i=r.length;let a=0,o=0,l;for(;o<i&&(l=g4(e,r,o,s,a++))>0;)o+=l}}parseID3PES(e,n){if(n.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const r=vn({},n,{type:this._videoTrack?Hs.emsg:Hs.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}}function Lw(t,e){return((t[e+1]&31)<<8)+t[e+2]}function cfe(t,e){return(t[e+10]&31)<<8|t[e+11]}function ufe(t,e,n,r,s,i){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=Lw(t,e),d=(t[e+3]&15)<<8|t[e+4];switch(t[e]){case 207:if(!r){Ex("ADTS AAC",i);break}case 15:a.audioPid===-1&&(a.audioPid=u);break;case 21:a.id3Pid===-1&&(a.id3Pid=u);break;case 219:if(!r){Ex("H.264",i);break}case 27:a.videoPid===-1&&(a.videoPid=u);break;case 3:case 4:!n.mpeg&&!n.mp3?i.log("MPEG audio found, not supported in this browser"):a.audioPid===-1&&(a.audioPid=u,a.segmentAudioCodec="mp3");break;case 193:if(!r){Ex("AC-3",i);break}case 129:n.ac3?a.audioPid===-1&&(a.audioPid=u,a.segmentAudioCodec="ac3"):i.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?i.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=u,a.segmentAudioCodec="ac3");break}const g=t[h+1]+2;h+=g,f-=g}}break;case 194:case 135:return Iw(s,new Error("Unsupported EC-3 in M2TS found"),void 0,i),a;case 36:a.videoPid===-1&&(a.videoPid=u,a.segmentVideoCodec="hevc",i.log("HEVC in M2TS found"));break}e+=d+5}return a}function Iw(t,e,n,r){r.warn(`parsing error: ${e.message}`),t.emit(B.ERROR,B.ERROR,{type:ft.MEDIA_ERROR,details:Se.FRAG_PARSING_ERROR,fatal:!1,levelRetry:n,error:e,reason:e.message})}function Ex(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function Vu(t,e){let n=0,r,s,i,a,o;const l=t.data;if(!t||t.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=ki(l[0],l[1]),l.splice(1,1);if(r=l[0],(r[0]<<16)+(r[1]<<8)+r[2]===1){if(s=(r[4]<<8)+r[5],s&&s>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),i=r[8];let d=i+9;if(t.size<=d)return null;t.size-=d;const h=new Uint8Array(t.size);for(let f=0,m=l.length;f<m;f++){r=l[f];let g=r.byteLength;if(d)if(d>g){d-=g;continue}else r=r.subarray(d),g-=d,d=0;h.set(r,n),n+=g}return s&&(s-=i+3),{data:h,pts:a,dts:o,len:s}}return null}class dfe{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 Vo=Math.pow(2,32)-1;class xe{static init(){xe.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 xe.types)xe.types.hasOwnProperty(e)&&(xe.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]);xe.HDLR_TYPES={video:n,audio:r};const s=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),i=new Uint8Array([0,0,0,0,0,0,0,0]);xe.STTS=xe.STSC=xe.STCO=i,xe.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),xe.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),xe.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),xe.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]);xe.FTYP=xe.box(xe.types.ftyp,a,l,a,o),xe.DINF=xe.box(xe.types.dinf,xe.box(xe.types.dref,s))}static box(e,...n){let r=8,s=n.length;const i=s;for(;s--;)r+=n[s].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),s=0,r=8;s<i;s++)a.set(n[s],r),r+=n[s].byteLength;return a}static hdlr(e){return xe.box(xe.types.hdlr,xe.HDLR_TYPES[e])}static mdat(e){return xe.box(xe.types.mdat,e)}static mdhd(e,n){n*=e;const r=Math.floor(n/(Vo+1)),s=Math.floor(n%(Vo+1));return xe.box(xe.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,s>>24,s>>16&255,s>>8&255,s&255,85,196,0,0]))}static mdia(e){return xe.box(xe.types.mdia,xe.mdhd(e.timescale||0,e.duration||0),xe.hdlr(e.type),xe.minf(e))}static mfhd(e){return xe.box(xe.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"?xe.box(xe.types.minf,xe.box(xe.types.smhd,xe.SMHD),xe.DINF,xe.stbl(e)):xe.box(xe.types.minf,xe.box(xe.types.vmhd,xe.VMHD),xe.DINF,xe.stbl(e))}static moof(e,n,r){return xe.box(xe.types.moof,xe.mfhd(e),xe.traf(r,n))}static moov(e){let n=e.length;const r=[];for(;n--;)r[n]=xe.trak(e[n]);return xe.box.apply(null,[xe.types.moov,xe.mvhd(e[0].timescale||0,e[0].duration||0)].concat(r).concat(xe.mvex(e)))}static mvex(e){let n=e.length;const r=[];for(;n--;)r[n]=xe.trex(e[n]);return xe.box.apply(null,[xe.types.mvex,...r])}static mvhd(e,n){n*=e;const r=Math.floor(n/(Vo+1)),s=Math.floor(n%(Vo+1)),i=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,s>>24,s>>16&255,s>>8&255,s&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 xe.box(xe.types.mvhd,i)}static sdtp(e){const n=e.samples||[],r=new Uint8Array(4+n.length);let s,i;for(s=0;s<n.length;s++)i=n[s].flags,r[s+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return xe.box(xe.types.sdtp,r)}static stbl(e){return xe.box(xe.types.stbl,xe.stsd(e),xe.box(xe.types.stts,xe.STTS),xe.box(xe.types.stsc,xe.STSC),xe.box(xe.types.stsz,xe.STSZ),xe.box(xe.types.stco,xe.STCO))}static avc1(e){let n=[],r=[],s,i,a;for(s=0;s<e.sps.length;s++)i=e.sps[s],a=i.byteLength,n.push(a>>>8&255),n.push(a&255),n=n.concat(Array.prototype.slice.call(i));for(s=0;s<e.pps.length;s++)i=e.pps[s],a=i.byteLength,r.push(a>>>8&255),r.push(a&255),r=r.concat(Array.prototype.slice.call(i));const o=xe.box(xe.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 xe.box(xe.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,xe.box(xe.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),xe.box(xe.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 xe.box(xe.types.mp4a,xe.audioStsd(e),xe.box(xe.types.esds,xe.esds(e)))}static mp3(e){return xe.box(xe.types[".mp3"],xe.audioStsd(e))}static ac3(e){return xe.box(xe.types["ac-3"],xe.audioStsd(e),xe.box(xe.types.dac3,e.config))}static stsd(e){const{segmentCodec:n}=e;if(e.type==="audio"){if(n==="aac")return xe.box(xe.types.stsd,xe.STSD,xe.mp4a(e));if(n==="ac3"&&e.config)return xe.box(xe.types.stsd,xe.STSD,xe.ac3(e));if(n==="mp3"&&e.codec==="mp3")return xe.box(xe.types.stsd,xe.STSD,xe.mp3(e))}else if(e.pps&&e.sps){if(n==="avc")return xe.box(xe.types.stsd,xe.STSD,xe.avc1(e));if(n==="hevc"&&e.vps)return xe.box(xe.types.stsd,xe.STSD,xe.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),s=e.width||0,i=e.height||0,a=Math.floor(r/(Vo+1)),o=Math.floor(r%(Vo+1));return xe.box(xe.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,s>>8&255,s&255,0,0,i>>8&255,i&255,0,0]))}static traf(e,n){const r=xe.sdtp(e),s=e.id,i=Math.floor(n/(Vo+1)),a=Math.floor(n%(Vo+1));return xe.box(xe.types.traf,xe.box(xe.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),xe.box(xe.types.tfdt,new Uint8Array([1,0,0,0,i>>24,i>>16&255,i>>8&255,i&255,a>>24,a>>16&255,a>>8&255,a&255])),xe.trun(e,r.length+16+20+8+16+8+8),r)}static trak(e){return e.duration=e.duration||4294967295,xe.box(xe.types.trak,xe.tkhd(e),xe.mdia(e))}static trex(e){const n=e.id;return xe.box(xe.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||[],s=r.length,i=12+16*s,a=new Uint8Array(i);let o,l,c,u,d,h;for(n+=8+i,a.set([e.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255],0),o=0;o<s;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 xe.box(xe.types.trun,a)}static initSegment(e){xe.types||xe.init();const n=xe.moov(e);return ki(xe.FTYP,n)}static hvc1(e){const n=e.params,r=[e.vps,e.sps,e.pps],s=4,i=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),s-1|n.temporal_id_nested<<2|n.num_temporal_layers<<3|(n.frame_rate.fixed?64:0),r.length]);let a=i.length;for(let m=0;m<r.length;m+=1){a+=3;for(let g=0;g<r[m].length;g+=1)a+=2+r[m][g].length}const o=new Uint8Array(a);o.set(i,0),a=i.length;const l=r.length-1;for(let m=0;m<r.length;m+=1){o.set(new Uint8Array([32+m|(m===l?128:0),0,r[m].length]),a),a+=3;for(let g=0;g<r[m].length;g+=1)o.set(new Uint8Array([r[m][g].length>>8,r[m][g].length&255]),a),a+=2,o.set(r[m][g],a),a+=r[m][g].length}const c=xe.box(xe.types.hvcC,o),u=e.width,d=e.height,h=e.pixelRatio[0],f=e.pixelRatio[1];return xe.box(xe.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,xe.box(xe.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),xe.box(xe.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,f>>24,f>>16&255,f>>8&255,f&255])))}}xe.types=void 0;xe.HDLR_TYPES=void 0;xe.STTS=void 0;xe.STSC=void 0;xe.STCO=void 0;xe.STSZ=void 0;xe.VMHD=void 0;xe.SMHD=void 0;xe.STSD=void 0;xe.FTYP=void 0;xe.DINF=void 0;const v4=9e4;function MA(t,e,n=1,r=!1){const s=t*e*n;return r?Math.round(s):s}function hfe(t,e,n=1,r=!1){return MA(t,e,1/n,r)}function pf(t,e=!1){return MA(t,1e3,1/v4,e)}function ffe(t,e=1){return MA(t,v4,1/e)}function BD(t){const{baseTime:e,timescale:n,trackId:r}=t;return`${e/n} (${e}/${n}) trackId: ${r}`}const pfe=10*1e3,mfe=1024,gfe=1152,yfe=1536;let Gu=null,wx=null;function FD(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 Iy extends Ii{constructor(e,n,r,s){if(super("mp4-remuxer",s),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,Gu===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Gu=a?parseInt(a[1]):0}if(wx===null){const i=navigator.userAgent.match(/Safari\/(\d+)/i);wx=i?parseInt(i[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&&BD(n)} > ${e&&BD(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,s=e.reduce((i,a)=>{let o=a.pts,l=o-i;return l<-4294967296&&(n=!0,o=Fs(o,r),l=o-i),l>0?i:o},r);return n&&this.debug("PTS rollover detected"),s}remux(e,n,r,s,i,a,o,l){let c,u,d,h,f,m,g=i,y=i;const v=e.pid>-1,_=n.pid>-1,S=n.samples.length,E=e.samples.length>0,L=o&&S>0||S>1;if((!v||E)&&(!_||L)||this.ISGenerated||o){if(this.ISGenerated){var P,I,k,R;const q=this.videoTrackConfig;(q&&(n.width!==q.width||n.height!==q.height||((P=n.pixelRatio)==null?void 0:P[0])!==((I=q.pixelRatio)==null?void 0:I[0])||((k=n.pixelRatio)==null?void 0:k[1])!==((R=q.pixelRatio)==null?void 0:R[1]))||!q&&L||this.nextAudioTs===null&&E)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,n,i,a));const M=this.isVideoContiguous;let G=-1,Y;if(L&&(G=vfe(n.samples),!M&&this.config.forceKeyFrameOnDiscontinuity))if(m=!0,G>0){this.warn(`Dropped ${G} out of ${S} video samples due to a missing keyframe`);const q=this.getVideoStartPts(n.samples);n.samples=n.samples.slice(G),n.dropped+=G,y+=(n.samples[0].pts-q)/n.inputTimeScale,Y=y}else G===-1&&(this.warn(`No keyframe found out of ${S} video samples`),m=!1);if(this.ISGenerated){if(E&&L){const q=this.getVideoStartPts(n.samples),Z=(Fs(e.samples[0].pts,q)-q)/n.inputTimeScale;g+=Math.max(0,Z),y+=Math.max(0,-Z)}if(E){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(e,n,i,a)),u=this.remuxAudio(e,g,this.isAudioContiguous,a,_||L||l===rt.AUDIO?y:void 0),L){const q=u?u.endPTS-u.startPTS:0;n.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(e,n,i,a)),c=this.remuxVideo(n,y,M,q)}}else L&&(c=this.remuxVideo(n,y,M,0));c&&(c.firstKeyFrame=G,c.independent=G!==-1,c.firstKeyFramePTS=Y)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(f=_4(r,i,this._initPTS,this._initDTS)),s.samples.length&&(h=b4(s,i,this._initPTS))),{audio:u,video:c,initSegment:d,independent:m,text:h,id3:f}}computeInitPts(e,n,r,s){const i=Math.round(r*n);let a=Fs(e,i);if(a<i+n)for(this.log(`Adjusting PTS for rollover in timeline near ${(i-a)/n} ${s}`);a<i+n;)a+=8589934592;return a-i}generateIS(e,n,r,s){const i=e.samples,a=n.samples,o=this.typeSupported,l={},c=this._initPTS;let u=!c||s,d="audio/mp4",h,f,m,g=-1;if(u&&(h=f=1/0),e.config&&i.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):xe.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(g=e.id,m=e.inputTimeScale,!c||m!==c.timescale?h=f=this.computeInitPts(i[0].pts,m,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:xe.initSegment([n]),metadata:{width:n.width,height:n.height}},u)if(g=n.id,m=n.inputTimeScale,!c||m!==c.timescale){const y=this.getVideoStartPts(a),v=Fs(a[0].dts,y),_=this.computeInitPts(v,m,r,"video"),S=this.computeInitPts(y,m,r,"video");f=Math.min(f,_),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: ${s?"":"~"}${r} ${h/m} != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${h/m} (${h}/${m}) trackId: ${g}`),this._initPTS={baseTime:h,timescale:m,trackId:g},this._initDTS={baseTime:f,timescale:m,trackId:g}):h=m=void 0,{tracks:l,initPTS:h,timescale:m,trackId:g}}remuxVideo(e,n,r,s){const i=e.inputTimeScale,a=e.samples,o=[],l=a.length,c=this._initPTS,u=c.baseTime*i/c.timescale;let d=this.nextVideoTs,h=8,f=this.videoSampleDuration,m,g,y=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,_=!1;if(!r||d===null){const J=u+n*i,Q=a[0].pts-Fs(a[0].dts,a[0].pts);Gu&&d!==null&&Math.abs(J-Q-(d+u))<15e3?r=!0:d=J-Q-u}const S=d+u;for(let J=0;J<l;J++){const Q=a[J];Q.pts=Fs(Q.pts,S),Q.dts=Fs(Q.dts,S),Q.dts<a[J>0?J-1:J].dts&&(_=!0)}_&&a.sort(function(J,Q){const ve=J.dts-Q.dts,Te=J.pts-Q.pts;return ve||Te}),m=a[0].dts,g=a[a.length-1].dts;const E=g-m,L=E?Math.round(E/(l-1)):f||e.inputTimeScale/30;if(r){const J=m-S,Q=J>L,ve=J<-1;if((Q||ve)&&(Q?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${pf(J,!0)} ms (${J}dts) hole between fragments detected at ${n.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${pf(-J,!0)} ms (${J}dts) overlapping between fragments detected at ${n.toFixed(3)}`),!ve||S>=a[0].pts||Gu)){m=S;const Te=a[0].pts-J;if(Q)a[0].dts=m,a[0].pts=Te;else{let Ne=!0;for(let Ke=0;Ke<a.length&&!(a[Ke].dts>Te&&Ne);Ke++){const be=a[Ke].pts;if(a[Ke].dts-=J,a[Ke].pts-=J,Ke<a.length-1){const Pe=a[Ke+1].pts,Ae=a[Ke].pts,we=Pe<=Ae,Ue=Pe<=be;Ne=we==Ue}}}this.log(`Video: Initial PTS/DTS adjusted: ${pf(Te,!0)}/${pf(m,!0)}, delta: ${pf(J,!0)} ms`)}}m=Math.max(0,m);let U=0,P=0,I=m;for(let J=0;J<l;J++){const Q=a[J],ve=Q.units,Te=ve.length;let Ne=0;for(let Ke=0;Ke<Te;Ke++)Ne+=ve[Ke].data.length;P+=Ne,U+=Te,Q.length=Ne,Q.dts<I?(Q.dts=I,I+=L/4|0||1):I=Q.dts,y=Math.min(Q.pts,y),v=Math.max(Q.pts,v)}g=a[l-1].dts;const k=P+4*U+8;let R;try{R=new Uint8Array(k)}catch(J){this.observer.emit(B.ERROR,B.ERROR,{type:ft.MUX_ERROR,details:Se.REMUX_ALLOC_ERROR,fatal:!1,error:J,bytes:k,reason:`fail allocating video mdat ${k}`});return}const M=new DataView(R.buffer);M.setUint32(0,k),R.set(xe.types.mdat,4);let G=!1,Y=Number.POSITIVE_INFINITY,q=Number.POSITIVE_INFINITY,X=Number.NEGATIVE_INFINITY,Z=Number.NEGATIVE_INFINITY;for(let J=0;J<l;J++){const Q=a[J],ve=Q.units;let Te=0;for(let be=0,Pe=ve.length;be<Pe;be++){const Ae=ve[be],we=Ae.data,Ue=Ae.data.byteLength;M.setUint32(h,Ue),h+=4,R.set(we,h),h+=Ue,Te+=4+Ue}let Ne;if(J<l-1)f=a[J+1].dts-Q.dts,Ne=a[J+1].pts-Q.pts;else{const be=this.config,Pe=J>0?Q.dts-a[J-1].dts:L;if(Ne=J>0?Q.pts-a[J-1].pts:L,be.stretchShortVideoTrack&&this.nextAudioTs!==null){const Ae=Math.floor(be.maxBufferHole*i),we=(s?y+s*i:this.nextAudioTs+u)-Q.pts;we>Ae?(f=we-Pe,f<0?f=Pe:G=!0,this.log(`It is approximately ${we/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=Pe}else f=Pe}const Ke=Math.round(Q.pts-Q.dts);Y=Math.min(Y,f),X=Math.max(X,f),q=Math.min(q,Ne),Z=Math.max(Z,Ne),o.push(FD(Q.key,f,Te,Ke))}if(o.length){if(Gu){if(Gu<70){const J=o[0].flags;J.dependsOn=2,J.isNonSync=0}}else if(wx&&Z-q<X-Y&&L/X<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let J=m;for(let Q=0,ve=o.length;Q<ve;Q++){const Te=J+o[Q].duration,Ne=J+o[Q].cts;if(Q<ve-1){const Ke=Te+o[Q+1].cts;o[Q].duration=Ke-Ne}else o[Q].duration=Q?o[Q-1].duration:L;o[Q].cts=0,J=Te}}}f=G||!f?L:f;const oe=g+f;this.nextVideoTs=d=oe-u,this.videoSampleDuration=f,this.isVideoContiguous=!0;const K={data1:xe.moof(e.sequenceNumber++,m,vn(e,{samples:o})),data2:R,startPTS:(y-u)/i,endPTS:(v+f-u)/i,startDTS:(m-u)/i,endDTS:d/i,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,K}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return gfe;case"ac3":return yfe;default:return mfe}}remuxAudio(e,n,r,s,i){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=[],m=i!==void 0;let g=e.samples,y=h?0:8,v=this.nextAudioTs||-1;const _=d.baseTime*a/d.timescale,S=_+n*a;if(this.isAudioContiguous=r=r||g.length&&v>0&&(s&&Math.abs(S-(v+_))<9e3||Math.abs(Fs(g[0].pts,S)-(v+_))<20*u),g.forEach(function(Z){Z.pts=Fs(Z.pts,S)}),!r||v<0){const Z=g.length;if(g=g.filter(oe=>oe.pts>=0),Z!==g.length&&this.warn(`Removed ${g.length-Z} of ${Z} samples (initPTS ${_} / ${a})`),!g.length)return;i===0?v=0:s&&!m?v=Math.max(0,S-_):v=g[0].pts-_}if(e.segmentCodec==="aac"){const Z=this.config.maxAudioFramesDrift;for(let oe=0,ne=v+_;oe<g.length;oe++){const H=g[oe],K=H.pts,J=K-ne,Q=Math.abs(1e3*J/a);if(J<=-Z*u&&m)oe===0&&(this.warn(`Audio frame @ ${(K/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*J/a)} ms.`),this.nextAudioTs=v=K-_,ne=K);else if(J>=Z*u&&Q<pfe&&m){let ve=Math.round(J/u);for(ne=K-ve*u;ne<0&&ve&&u;)ve--,ne+=u;oe===0&&(this.nextAudioTs=v=ne-_),this.warn(`Injecting ${ve} audio frames @ ${((ne-_)/a).toFixed(3)}s due to ${Math.round(1e3*J/a)} ms gap.`);for(let Te=0;Te<ve;Te++){let Ne=dfe.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);Ne||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),Ne=H.unit.subarray()),g.splice(oe,0,{unit:Ne,pts:ne}),ne+=u,oe++}}H.pts=ne,ne+=u}}let E=null,L=null,U,P=0,I=g.length;for(;I--;)P+=g[I].unit.byteLength;for(let Z=0,oe=g.length;Z<oe;Z++){const ne=g[Z],H=ne.unit;let K=ne.pts;if(L!==null){const Q=f[Z-1];Q.duration=Math.round((K-L)/l)}else if(r&&e.segmentCodec==="aac"&&(K=v+_),E=K,P>0){P+=y;try{U=new Uint8Array(P)}catch(Q){this.observer.emit(B.ERROR,B.ERROR,{type:ft.MUX_ERROR,details:Se.REMUX_ALLOC_ERROR,fatal:!1,error:Q,bytes:P,reason:`fail allocating audio mdat ${P}`});return}h||(new DataView(U.buffer).setUint32(0,P),U.set(xe.types.mdat,4))}else return;U.set(H,y);const J=H.byteLength;y+=J,f.push(FD(!0,c,J,0)),L=K}const k=f.length;if(!k)return;const R=f[f.length-1];v=L-_,this.nextAudioTs=v+l*R.duration;const M=h?new Uint8Array(0):xe.moof(e.sequenceNumber++,E/l,vn({},e,{samples:f}));e.samples=[];const G=(E-_)/a,Y=this.nextAudioTs/a,X={data1:M,data2:U,startPTS:G,endPTS:Y,startDTS:G,endDTS:Y,type:"audio",hasAudio:!0,hasVideo:!1,nb:k};return this.isAudioContiguous=!0,X}}function Fs(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 vfe(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}function _4(t,e,n,r){const s=t.samples.length;if(!s)return;const i=t.inputTimeScale;for(let o=0;o<s;o++){const l=t.samples[o];l.pts=Fs(l.pts-n.baseTime*i/n.timescale,e*i)/i,l.dts=Fs(l.dts-r.baseTime*i/r.timescale,e*i)/i}const a=t.samples;return t.samples=[],{samples:a}}function b4(t,e,n){const r=t.samples.length;if(!r)return;const s=t.inputTimeScale;for(let a=0;a<r;a++){const o=t.samples[a];o.pts=Fs(o.pts-n.baseTime*s/n.timescale,e*s)/s}t.samples.sort((a,o)=>a.pts-o.pts);const i=t.samples;return t.samples=[],{samples:i}}class _fe extends Ii{constructor(e,n,r,s){super("passthrough-remuxer",s),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,s){this.audioCodec=n,this.videoCodec=r,this.generateInitSegment(e,s),this.emitInitSegment=!0}generateInitSegment(e,n){let{audioCodec:r,videoCodec:s}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:i,video:a}=this.initData=A5(e);if(n)ade(e,n);else{const l=i||a;l!=null&&l.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${l.codec}")!`)}i&&(r=$D(i,bn.AUDIO,this)),a&&(s=$D(a,bn.VIDEO,this));const o={};i&&a?o.audiovideo={container:"video/mp4",codec:r+","+s,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:i?o.audio={container:"audio/mp4",codec:r,encrypted:i.encrypted,initSegment:e,id:"audio"}:a?o.video={container:"video/mp4",codec:s,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,s,i,a){var o,l;let{initPTS:c,lastEndTime:u}=this;const d={audio:void 0,video:void 0,text:s,id3:r,initSegment:void 0};tt(u)||(u=this.lastEndTime=i||0);const h=n.samples;if(!h.length)return d;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let m=this.initData;if((o=m)!=null&&o.length||(this.generateInitSegment(h),m=this.initData),!((l=m)!=null&&l.length))return this.warn("Failed to generate initSegment."),d;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const g=lde(h,m,this),y=m.audio?g[m.audio.id]:null,v=m.video?g[m.video.id]:null,_=Kg(v,1/0),S=Kg(y,1/0),E=Kg(v,0,!0),L=Kg(y,0,!0);let U=i,P=0;const I=y&&(!v||!c&&S<_||c&&c.trackId===m.audio.id),k=I?y:v;if(k){const ne=k.timescale,H=k.start-i*ne,K=I?m.audio.id:m.video.id;U=k.start/ne,P=I?L-S:E-_,(a||!c)&&(bfe(c,U,i,P)||ne!==c.timescale)&&(c&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${i} ${H/ne} != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${U-i} (${H}/${ne}) trackId: ${K}`),c=null,f.initPTS=H,f.timescale=ne,f.trackId=K)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${i}`);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+P;P>0?this.lastEndTime=M:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const G=!!m.audio,Y=!!m.video;let q="";G&&(q+="audio"),Y&&(q+="video");const X=(m.audio?m.audio.encrypted:!1)||(m.video?m.video.encrypted:!1),Z={data1:h,startPTS:R,startDTS:R,endPTS:M,endDTS:M,type:q,hasAudio:G,hasVideo:Y,nb:1,dropped:0,encrypted:X};d.audio=G&&!Y?Z:void 0,d.video=Y?Z:void 0;const oe=v==null?void 0:v.sampleCount;if(oe){const ne=v.keyFrameIndex,H=ne!==-1;Z.nb=oe,Z.dropped=ne===0||this.isVideoContiguous?0:H?ne:oe,Z.independent=H,Z.firstKeyFrame=ne,H&&v.keyFrameStart&&(Z.firstKeyFramePTS=(v.keyFrameStart-c.baseTime)/c.timescale),this.isVideoContiguous||(d.independent=H),this.isVideoContiguous||(this.isVideoContiguous=H),Z.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${ne}/${oe} dropped: ${Z.dropped} start: ${Z.firstKeyFramePTS||"NA"}`)}return d.initSegment=f,d.id3=_4(r,i,c,c),s.samples.length&&(d.text=b4(s,i,c)),d}}function Kg(t,e,n=!1){return(t==null?void 0:t.start)!==void 0?(t.start+(n?t.duration:0))/t.timescale:e}function bfe(t,e,n,r){if(t===null)return!0;const s=Math.max(r,1),i=e-t.baseTime/t.timescale;return Math.abs(i-n)>s}function $D(t,e,n){const r=t.codec;return r&&r.length>4?r:e===bn.AUDIO?r==="ec-3"||r==="ac-3"||r==="alac"?r:r==="fLaC"||r==="Opus"?G0(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 so;try{so=self.performance.now.bind(self.performance)}catch{so=Date.now}const Py=[{demux:ife,remux:_fe},{demux:el,remux:Iy},{demux:tfe,remux:Iy},{demux:rfe,remux:Iy}];Py.splice(2,0,{demux:nfe,remux:Iy});class VD{constructor(e,n,r,s,i,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=i,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,n,r,s){const i=r.transmuxing;i.executeStart=so();let a=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:l}=this;s&&(this.currentTransmuxState=s);const{contiguous:c,discontinuity:u,trackSwitch:d,accurateTimeOffset:h,timeOffset:f,initSegmentChange:m}=s||o,{audioCodec:g,videoCodec:y,defaultInitPts:v,duration:_,initSegmentData:S}=l,E=xfe(a,n);if(E&&jd(E.method)){const I=this.getDecrypter(),k=RA(E.method);if(I.isSync()){let R=I.softwareDecrypt(a,E.key.buffer,E.iv.buffer,k);if(r.part>-1){const G=I.flush();R=G&&G.buffer}if(!R)return i.executeEnd=so(),Tx(r);a=new Uint8Array(R)}else return this.asyncResult=!0,this.decryptionPromise=I.webCryptoDecrypt(a,E.key.buffer,E.iv.buffer,k).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 I=this.configureTransmuxer(a);if(I)return this.logger.warn(`[transmuxer] ${I.message}`),this.observer.emit(B.ERROR,B.ERROR,{type:ft.MEDIA_ERROR,details:Se.FRAG_PARSING_ERROR,fatal:!1,error:I,reason:I.message}),i.executeEnd=so(),Tx(r)}(u||d||m||L)&&this.resetInitSegment(S,g,y,_,n),(u||m||L)&&this.resetInitialTimestamp(v),c||this.resetContiguity();const U=this.transmux(a,E,f,h,r);this.asyncResult=zp(U);const P=this.currentTransmuxState;return P.contiguous=!0,P.discontinuity=!1,P.trackSwitch=!1,i.executeEnd=so(),U}flush(e){const n=e.transmuxing;n.executeStart=so();const{decrypter:r,currentTransmuxState:s,decryptionPromise:i}=this;if(i)return this.asyncResult=!0,i.then(()=>this.flush(e));const a=[],{timeOffset:o}=s;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=so();const d=[Tx(e)];return this.asyncResult?Promise.resolve(d):d}const u=l.flush(o);return zp(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:s,videoTrack:i,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===rt.MAIN?"level":"track"} ${r.level}`);const u=this.remuxer.remux(s,i,a,o,c,l,!0,this.id);e.push({remuxResult:u,chunkMeta:r}),r.transmuxing.executeEnd=so()}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,s,i){const{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,n,r,s),o.resetInitSegment(e,n,r,i))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,n,r,s,i){let a;return n&&n.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,n,r,s,i):a=this.transmuxUnencrypted(e,r,s,i),a}transmuxUnencrypted(e,n,r,s){const{audioTrack:i,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(e,n,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(i,a,o,l,n,r,!1,this.id),chunkMeta:s}}transmuxSampleAes(e,n,r,s,i){return this.demuxer.demuxSampleAes(e,n,r).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,r,s,!1,this.id),chunkMeta:i}))}configureTransmuxer(e){const{config:n,observer:r,typeSupported:s}=this;let i;for(let d=0,h=Py.length;d<h;d++){var a;if((a=Py[d].demux)!=null&&a.probe(e,this.logger)){i=Py[d];break}}if(!i)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,l=this.remuxer,c=i.remux,u=i.demux;(!l||!(l instanceof c))&&(this.remuxer=new c(r,n,s,this.logger)),(!o||!(o instanceof u))&&(this.demuxer=new u(r,n,s,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 TA(this.config)),e}}function xfe(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 Tx=t=>({remuxResult:{},chunkMeta:t});function zp(t){return"then"in t&&t.then instanceof Function}class Sfe{constructor(e,n,r,s,i){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=s,this.defaultInitPts=i||null}}class Efe{constructor(e,n,r,s,i,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=s,this.timeOffset=i,this.initSegmentChange=a}}let GD=0;class x4{constructor(e,n,r,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=GD++,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(B.ERROR,{type:ft.OTHER_ERROR,details:Se.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:c})};const i=e.config;this.hls=e,this.id=n,this.useWorker=!!i.enableWorker,this.onTransmuxComplete=r,this.onFlush=s;const a=(l,c)=>{c=c||{},c.frag=this.frag||void 0,l===B.ERROR&&(c=c,c.parent=this.id,c.part=this.part,this.error=c.error),this.hls.trigger(l,c)};this.observer=new LA,this.observer.on(B.FRAG_DECRYPTED,a),this.observer.on(B.ERROR,a);const o=sD(i.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const l=this.hls.logger;if(i.workerPath||Rhe()){try{i.workerPath?(l.log(`loading Web Worker ${i.workerPath} for "${n}"`),this.workerContext=khe(i.workerPath)):(l.log(`injecting Web Worker for "${n}"`),this.workerContext=Che());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:En(i)})}catch(u){l.warn(`Error setting up "${n}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new VD(this.observer,o,i,"",n,e.logger)}return}}this.transmuxer=new VD(this.observer,o,i,"",n,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=GD++;const n=this.hls.config,r=sD(n.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:r,id:this.id,config:En(n)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),Lhe(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,s,i,a,o,l,c,u){var d,h;c.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:m}=this,g=a?a.start:i.start,y=i.decryptdata,v=this.frag,_=!(v&&i.cc===v.cc),S=!(v&&c.level===v.level),E=v?c.sn-v.sn:-1,L=this.part?c.part-this.part.index:-1,U=E===0&&c.id>1&&c.id===(v==null?void 0:v.stats.chunkCount),P=!S&&(E===1||E===0&&(L===1||U&&L<=0)),I=self.performance.now();(S||E||i.stats.parsing.start===0)&&(i.stats.parsing.start=I),a&&(L||!P)&&(a.stats.parsing.start=I);const k=!(v&&((d=i.initSegment)==null?void 0:d.url)===((h=v.initSegment)==null?void 0:h.url)),R=new Efe(_,P,l,S,g,k);if(!P||_||k){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${c.sn}${c.part>-1?" part: "+c.part:""} ${this.id===rt.MAIN?"level":"track"}: ${c.level} id: ${c.id}
        discontinuity: ${_}
        trackSwitch: ${S}
        contiguous: ${P}
        accurateTimeOffset: ${l}
        timeOffset: ${g}
        initSegmentChange: ${k}`);const M=new Sfe(r,s,n,o,u);this.configureTransmuxer(M)}if(this.frag=i,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:y,chunkMeta:c,state:R},e instanceof ArrayBuffer?[e]:[]);else if(m){const M=m.push(e,y,c,R);zp(M)?M.then(G=>{this.handleTransmuxComplete(G)}).catch(G=>{this.transmuxerError(G,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 s=r.flush(e);zp(s)?s.then(i=>{this.handleFlushResult(i,e)}).catch(i=>{this.transmuxerError(i,e,"transmuxer-interface flush error")}):this.handleFlushResult(s,e)}}transmuxerError(e,n,r){this.hls&&(this.error=e,this.hls.trigger(B.ERROR,{type:ft.MEDIA_ERROR,details:Se.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 KD=100;class wfe extends kA{constructor(e,n,r){super(e,n,r,"audio-stream-controller",rt.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(B.LEVEL_LOADED,this.onLevelLoaded,this),e.on(B.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(B.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(B.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(B.BUFFER_RESET,this.onBufferReset,this),e.on(B.BUFFER_CREATED,this.onBufferCreated,this),e.on(B.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(B.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(B.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(B.FRAG_LOADING,this.onFragLoading,this),e.on(B.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(B.LEVEL_LOADED,this.onLevelLoaded,this),e.off(B.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(B.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(B.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(B.BUFFER_RESET,this.onBufferReset,this),e.off(B.BUFFER_CREATED,this.onBufferCreated,this),e.off(B.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(B.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(B.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(B.FRAG_LOADING,this.onFragLoading,this),e.off(B.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:n,id:r,initPTS:s,timescale:i,trackId:a}){if(r===rt.MAIN){const o=n.cc,l=this.fragCurrent;if(this.initPTS[o]={baseTime:s,timescale:i,trackId:a},this.log(`InitPTS for cc: ${o} found from main: ${s/i} (${s}/${i}) trackId: ${a}`),this.mainAnchor=n,this.state===De.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===De.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,n){var r;const s=((r=this.mainFragLoading)==null?void 0:r.frag)||null;if(n&&(s==null?void 0:s.cc)===n.cc)return;const i=(s||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),l=j5(a,i,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===De.IDLE&&this.doTickIdle())}startLoad(e,n){if(!this.levels){this.startPosition=e,this.state=De.STOPPED;return}const r=this.lastCurrentTime;this.stopLoad(),this.setInterval(KD),r>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r,this.state=De.IDLE):this.state=De.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=n?-1:e,this.tick()}doTick(){switch(this.state){case De.IDLE:this.doTickIdle();break;case De.WAITING_TRACK:{const{levels:e,trackId:n}=this,r=e==null?void 0:e[n],s=r==null?void 0:r.details;if(s&&!this.waitForLive(r)){if(this.waitForCdnTuneIn(s))break;this.state=De.WAITING_INIT_PTS}break}case De.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case De.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:n,part:r,cache:s,complete:i}=e,a=this.mainAnchor;if(this.initPTS[n.cc]!==void 0){this.waitingData=null,this.state=De.FRAG_LOADING;const o=s.flush().buffer,l={frag:n,part:r,payload:o,networkDetails:null};this._handleFragmentLoadProgress(l),i&&super._handleFragmentLoadComplete(l)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=De.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:s,trackId:i}=this,a=n.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(r!=null&&r[i]))return;const o=r[i],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=De.WAITING_TRACK,this.startFragRequested=!1;return}const c=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&c&&(this.bufferFlushed=!1,this.afterBufferFlushed(c,bn.AUDIO,rt.AUDIO));const u=this.getFwdBufferInfo(c,rt.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,l)){n.trigger(B.BUFFER_EOS,{type:"audio"}),this.state=De.ENDED;return}const d=u.len,h=n.maxBufferLength,f=l.fragments,m=f[0].start,g=this.getLoadPosition(),y=this.flushing?g:u.end;if(this.switchingTrack&&s){const S=g;l.PTSKnown&&S<m&&(u.end>m||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=m+.05)}if(d>=h&&!this.switchingTrack&&y<f[f.length-1].start)return;let v=this.getNextFragment(y,l);if(v&&this.isLoopLoading(v,y)&&(v=this.getNextFragmentLoopLoading(v,l,u,rt.MAIN,h)),!v){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(u,h,v))return;let _=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&_&&ar(v)&&!v.endList&&(!l.live||!this.loadingParts&&y<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(_)===xr.OK&&(this.mainFragLoading=_=null),_&&ar(_))){if(v.start>_.end){const E=this.fragmentTracker.getFragAtPos(y,rt.MAIN);E&&E.end>_.end&&(_=E,this.mainFragLoading={frag:E,targetBufferTime:null})}if(v.start>_.end)return}this.loadFragment(v,o,y)}onMediaDetaching(e,n){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,n)}onAudioTracksUpdated(e,{audioTracks:n}){this.resetTransmuxer(),this.levels=n.map(r=>new Gp(r))}onAudioTrackSwitching(e,n){const r=!!n.url;this.trackId=n.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),r?(this.switchingTrack=n,this.flushAudioIfNeeded(n),this.state!==De.STOPPED&&(this.setInterval(KD),this.state=De.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(B.AUDIO_TRACK_LOADED,r))}onAudioTrackLoaded(e,n){var r;const{levels:s}=this,{details:i,id:a,groupId:o,track:l}=n;if(!s){this.warn(`Audio tracks reset while loading track ${a} "${l.name}" of "${o}"`);return}const c=this.mainDetails;if(!c||i.endCC>c.endCC||c.expired){this.cachedTrackLoadedData=n,this.state!==De.STOPPED&&(this.state=De.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${l.name}" of "${o}" loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:""},duration:${i.totalduration}`);const u=s[a];let d=0;if(i.live||(r=u.details)!=null&&r.live){if(this.checkLiveUpdate(i),i.deltaUpdateFailed)return;if(u.details){var h;d=this.alignPlaylists(i,u.details,(h=this.levelLastLoaded)==null?void 0:h.details)}i.alignedSliding||(t4(i,c),i.alignedSliding||X0(i,c),d=i.fragmentStart)}u.details=i,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(c,d),this.hls.trigger(B.AUDIO_TRACK_UPDATED,{details:i,id:a,groupId:n.groupId}),this.state===De.WAITING_TRACK&&!this.waitForCdnTuneIn(i)&&(this.state=De.IDLE),this.tick()}_handleFragmentLoadProgress(e){var n;const r=e.frag,{part:s,payload:i}=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 x4(this.hls,rt.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[r.cc],m=(n=r.initSegment)==null?void 0:n.data;if(f!==void 0){const y=s?s.index:-1,v=y!==-1,_=new AA(r.level,r.sn,r.stats.chunkCount,i.byteLength,y,v);h.push(i,m,d,"",r,s,u.totalduration,!1,_,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:g}=this.waitingData=this.waitingData||{frag:r,part:s,cache:new n4,complete:!1};g.push(new Uint8Array(i)),this.state!==De.STOPPED&&(this.state=De.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===rt.MAIN&&ar(n.frag)&&(this.mainFragLoading=n,this.state===De.IDLE&&this.tick())}onFragBuffered(e,n){const{frag:r,part:s}=n;if(r.type!==rt.AUDIO){!this.audioOnly&&r.type===rt.MAIN&&!r.elementaryStreams.video&&!r.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(r)){this.warn(`Fragment ${r.sn}${s?" p: "+s.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(ar(r)){this.fragPrevious=r;const i=this.switchingTrack;i&&(this.bufferedTrack=i,this.switchingTrack=null,this.hls.trigger(B.AUDIO_TRACK_SWITCHED,hn({},i)))}this.fragBufferedComplete(r,s),this.media&&this.tick()}onError(e,n){var r;if(n.fatal){this.state=De.ERROR;return}switch(n.details){case Se.FRAG_GAP:case Se.FRAG_PARSING_ERROR:case Se.FRAG_DECRYPT_ERROR:case Se.FRAG_LOAD_ERROR:case Se.FRAG_LOAD_TIMEOUT:case Se.KEY_LOAD_ERROR:case Se.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(rt.AUDIO,n);break;case Se.AUDIO_TRACK_LOAD_ERROR:case Se.AUDIO_TRACK_LOAD_TIMEOUT:case Se.LEVEL_PARSING_ERROR:!n.levelRetry&&this.state===De.WAITING_TRACK&&((r=n.context)==null?void 0:r.type)===Kt.AUDIO_TRACK&&(this.state=De.IDLE);break;case Se.BUFFER_ADD_CODEC_ERROR:case Se.BUFFER_APPEND_ERROR:if(n.parent!=="audio")return;this.reduceLengthAndFlushBuffer(n)||this.resetLoadingState();break;case Se.BUFFER_FULL_ERROR:if(n.parent!=="audio")return;this.reduceLengthAndFlushBuffer(n)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case Se.INTERNAL_EXCEPTION:this.recoverWorkerError(n);break}}onBufferFlushing(e,{type:n}){n!==bn.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:n}){if(n!==bn.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===De.ENDED&&(this.state=De.IDLE);const r=this.mediaBuffer||this.media;r&&(this.afterBufferFlushed(r,n,rt.AUDIO),this.tick())}}_handleTransmuxComplete(e){var n;const r="audio",{hls:s}=this,{remuxResult:i,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:m,initSegment:g}=i;if(this.fragContextChanged(l)||!d){this.fragmentTracker.removeFragment(l);return}if(this.state=De.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),g!=null&&g.tracks){const y=l.initSegment||l;if(this.unhandledEncryptionError(g,l))return;this._bufferInitSegment(u,g.tracks,y,a),s.trigger(B.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:r,tracks:g.tracks})}if(h){const{startPTS:y,endPTS:v,startDTS:_,endDTS:S}=h;c&&(c.elementaryStreams[bn.AUDIO]={startPTS:y,endPTS:v,startDTS:_,endDTS:S}),l.setElementaryStreamInfo(bn.AUDIO,y,v,_,S),this.bufferFragmentData(h,l,c,a)}if(m!=null&&(n=m.samples)!=null&&n.length){const y=vn({id:r,frag:l,details:d},m);s.trigger(B.FRAG_PARSING_METADATA,y)}if(f){const y=vn({id:r,frag:l,details:d},f);s.trigger(B.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(e,n,r,s){if(this.state!==De.PARSING||(n.video&&delete n.video,n.audiovideo&&delete n.audiovideo,!n.audio))return;const i=n.audio;i.id=rt.AUDIO;const a=e.audioCodec;this.log(`Init audio buffer, container:${i.container}, codecs[level/parsed]=[${a}/${i.codec}]`),a&&a.split(",").length===1&&(i.levelCodec=a),this.hls.trigger(B.BUFFER_CODECS,n);const o=i.initSegment;if(o!=null&&o.byteLength){const l={type:"audio",frag:r,part:null,chunkMeta:s,parent:r.type,data:o};this.hls.trigger(B.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,n,r){const s=this.fragmentTracker.getState(e);if(this.switchingTrack||s===xr.NOT_LOADED||s===xr.PARTIAL){var i;if(!ar(e))this._loadInitSegment(e,n);else if((i=n.details)!=null&&i.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=De.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragmentStart!==n.details.fragmentStart&&X0(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:s,characteristics:i,audioCodec:a,channels:o}=this.bufferedTrack;Wc({name:n,lang:r,assocLang:s,characteristics:i,audioCodec:a,channels:o},e,vc)||(H0(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(B.AUDIO_TRACK_SWITCHED,hn({},e))}}class jA extends Ii{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 s=n==null?void 0:n.renditionReports;if(s){let i=-1;for(let a=0;a<s.length;a++){const o=s[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){i=a;break}else l===e.substring(0,l.length)&&(i=a)}if(i!==-1){const a=s[i],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&&iD(r);return new aD(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:s,stats:i}=n,a=self.performance.now(),o=i.loading.first?Math.max(0,a-i.loading.first):0;s.advancedDateTime=Date.now()-o;const l=this.hls.config.timelineOffset;if(l!==s.appliedTimelineOffset){const u=Math.max(l||0,0);s.appliedTimelineOffset=u,s.fragments.forEach(d=>{d.setStart(d.playlistOffset+u)})}if(s.live||r!=null&&r.live){const u="levelInfo"in n?n.levelInfo:n.track;if(s.reloaded(r),r&&s.fragments.length>0){ghe(r,s,this);const _=s.playlistParsingError;if(_){this.warn(_);const S=this.hls;if(!S.config.ignorePlaylistParsingErrors){var c;const{networkDetails:E}=n;S.trigger(B.ERROR,{type:ft.NETWORK_ERROR,details:Se.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:_,reason:_.message,level:n.level||void 0,parent:(c=s.fragments[0])==null?void 0:c.type,networkDetails:E,stats:i});return}s.playlistParsingError=null}}s.requestScheduled===-1&&(s.requestScheduled=i.loading.start);const d=this.hls.mainForwardBufferInfo,h=d?d.end-d.len:0,f=(s.edge-h)*1e3,m=X5(s,f);if(s.requestScheduled+m<a?s.requestScheduled=a:s.requestScheduled+=m,this.log(`live playlist ${e} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),!this.canLoad||!s.live)return;let g,y,v;if(s.canBlockReload&&s.endSN&&s.advanced){const _=this.hls.config.lowLatencyMode,S=s.lastPartSn,E=s.endSN,L=s.lastPartIndex,U=L!==-1,P=S===E;U?P?(y=E+1,v=_?0:L):(y=S,v=_?L+1:s.maxPartIndex):y=E+1;const I=s.age,k=I+s.ageHeader;let R=Math.min(k-s.partTarget,s.targetduration*1.5);if(R>0){if(k>s.targetduration*3)this.log(`Playlist last advanced ${I.toFixed(2)}s ago. Omitting segment and part directives.`),y=void 0,v=void 0;else if(r!=null&&r.tuneInGoal&&k-s.partTarget>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${R} with playlist age: ${s.age}`),R=0;else{const M=Math.floor(R/s.targetduration);if(y+=M,v!==void 0){const G=Math.round(R%s.targetduration/s.partTarget);v+=G}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${I.toFixed(2)}s goal: ${R} skip sn ${M} to part ${v}`)}s.tuneInGoal=R}if(g=this.getDeliveryDirectives(s,n.deliveryDirectives,y,v),_||!P){s.requestScheduled=a,this.loadingPlaylist(u,g);return}}else(s.canBlockReload||s.canSkipUntil)&&(g=this.getDeliveryDirectives(s,n.deliveryDirectives,y,v));g&&y!==void 0&&s.canBlockReload&&(s.requestScheduled=i.loading.first+Math.max(m-o*2,m/2)),this.scheduleLoading(u,g,s)}else this.clearTimer()}scheduleLoading(e,n,r){const s=r||e.details;if(!s){this.loadingPlaylist(e,n);return}const i=self.performance.now(),a=s.requestScheduled;if(i>=a){this.loadingPlaylist(e,n);return}const o=a-i;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,s){let i=iD(e);return n!=null&&n.skip&&e.deltaUpdateFailed&&(r=n.msn,s=n.part,i=ky.No),new aD(r,s,i)}checkRetry(e){const n=e.details,r=z0(e),s=e.errorAction,{action:i,retryCount:a=0,retryConfig:o}=s||{},l=!!s&&!!o&&(i===$r.RetryRequest||!s.resolved&&i===$r.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=wA(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,s.resolved=!0}return l}}function S4(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(!qp(t[n].attrs,e[n].attrs))return!1;return!0}function qp(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(s=>t[s]!==e[s])}function Pw(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}class Tfe extends jA{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(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.MANIFEST_PARSED,this.onManifestParsed,this),e.on(B.LEVEL_LOADING,this.onLevelLoading,this),e.on(B.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(B.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(B.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.MANIFEST_PARSED,this.onManifestParsed,this),e.off(B.LEVEL_LOADING,this.onLevelLoading,this),e.off(B.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(B.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(B.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:s,details:i}=n,a=this.tracksInGroup[r];if(!a||a.groupId!==s){this.warn(`Audio track with id:${r} and group:${s} 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:${s} loaded [${i.startSN}-${i.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,s=this.groupIds;let i=this.currentTrack;if(!r||(s==null?void 0:s.length)!==(r==null?void 0:r.length)||r!=null&&r.some(o=>(s==null?void 0:s.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(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const l=this.hls.config.audioPreference;if(!i&&l){const h=xa(l,o,vc);if(h>-1)i=o[h];else{const f=xa(l,this.tracks);i=this.tracks[f]}}let c=this.findTrackId(i);c===-1&&i&&(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(B.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(B.ERROR,{type:ft.MEDIA_ERROR,details:Se.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:h})}}}onError(e,n){n.fatal||!n.context||n.context.type===Kt.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 s=this.currentTrack;if(s&&Wc(e,s,vc))return s;const i=xa(e,this.tracksInGroup,vc);if(i>-1){const a=this.tracksInGroup[i];return this.setAudioTrack(i),a}else if(s){let a=n.loadLevel;a===-1&&(a=n.firstAutoLevel);const o=jde(e,n.levels,r,a,vc);if(o===-1)return null;n.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=xa(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,s=n[e],i=s.details&&!s.details.live;if(e===this.trackId&&s===r&&i||(this.log(`Switching to audio-track ${e} "${s.name}" lang:${s.lang} group:${s.groupId} channels:${s.channels}`),this.trackId=e,this.currentTrack=s,this.hls.trigger(B.AUDIO_TRACK_SWITCHING,hn({},s)),i))return;const a=this.switchParams(s.url,r==null?void 0:r.details,s.details);this.loadPlaylist(a)}findTrackId(e){const n=this.tracksInGroup;for(let r=0;r<n.length;r++){const s=n[r];if(!(this.selectDefaultTrack&&!s.default)&&(!e||Wc(e,s,vc)))return r}if(e){const{name:r,lang:s,assocLang:i,characteristics:a,audioCodec:o,channels:l}=e;for(let c=0;c<n.length;c++){const u=n[c];if(Wc({name:r,lang:s,assocLang:i,characteristics:a,audioCodec:o,channels:l},u,vc))return c}for(let c=0;c<n.length;c++){const u=n[c];if(qp(e.attrs,u.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return c}for(let c=0;c<n.length;c++){const u=n[c];if(qp(e.attrs,u.attrs,["LANGUAGE"]))return c}}return-1}loadPlaylist(e){super.loadPlaylist();const n=this.currentTrack;this.shouldLoadPlaylist(n)&&H0(n.url,this.hls)&&this.scheduleLoading(n,e)}loadingPlaylist(e,n){super.loadingPlaylist(e,n);const r=e.id,s=e.groupId,i=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:${s}${(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||""):""} ${i}`),this.hls.trigger(B.AUDIO_TRACK_LOADING,{url:i,id:r,groupId:s,deliveryDirectives:n||null,track:e})}}class Afe{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 s=this.queues[n];s.push(e),s.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 s=n[0];try{s.execute()}catch(i){var r;if(s.onError(i),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],s=r==null?void 0:r.buffer;return s?`SourceBuffer${s.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 HD=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,E4="HlsJsTrackRemovedError";class Rfe extends Error{constructor(e){super(e),this.name=E4}}class Cfe extends Ii{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 s;this.hls&&((s=this.mediaSource)==null?void 0:s.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=r=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=r=>{const{media:s,mediaSource:i}=this;r&&this.log("Media source opened"),!(!s||!i)&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(B.MEDIA_ATTACHED,{media:s,mediaSource:i}),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:s}=this;r!==s&&this.error(`Media element src was set while attaching MediaSource (${s} > ${r})`)},this.hls=e,this.fragmentTracker=n,this.appendSource=Xue(Hl(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(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.MANIFEST_PARSED,this.onManifestParsed,this),e.on(B.BUFFER_RESET,this.onBufferReset,this),e.on(B.BUFFER_APPENDING,this.onBufferAppending,this),e.on(B.BUFFER_CODECS,this.onBufferCodecs,this),e.on(B.BUFFER_EOS,this.onBufferEos,this),e.on(B.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(B.FRAG_PARSED,this.onFragParsed,this),e.on(B.FRAG_CHANGED,this.onFragChanged,this),e.on(B.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.MANIFEST_PARSED,this.onManifestParsed,this),e.off(B.BUFFER_RESET,this.onBufferReset,this),e.off(B.BUFFER_APPENDING,this.onBufferAppending,this),e.off(B.BUFFER_CODECS,this.onBufferCodecs,this),e.off(B.BUFFER_EOS,this.onBufferEos,this),e.off(B.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(B.FRAG_PARSED,this.onFragParsed,this),e.off(B.FRAG_CHANGED,this.onFragChanged,this),e.off(B.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:n}=this;if(!e)return null;const r={};if(this.operationQueue){const i=this.isUpdating();i||this.operationQueue.removeBlockers();const a=this.isQueued();(i||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${i?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const s=this.transferData;return!this.sourceBufferCount&&s&&s.mediaSource===n?vn(r,s.tracks):this.sourceBuffers.forEach(i=>{const[a]=i;a&&(r[a]=vn({},this.tracks[a]),this.removeBuffer(a)),i[0]=i[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 s=2;(n.audio&&!n.video||!n.altAudio)&&(s=1),this.bufferCodecEventsTotal=s,this.log(`${s} bufferCodec event(s) expected.`),(r=this.transferData)!=null&&r.mediaSource&&this.sourceBufferCount&&s&&this.bufferCreated()}onMediaAttaching(e,n){const r=this.media=n.media;this.transferData=this.overrides=void 0;const s=Hl(this.appendSource);if(s){const i=!!n.mediaSource;(i||n.overrides)&&(this.transferData=n,this.overrides=n.overrides);const a=this.mediaSource=n.mediaSource||new s;if(this.assignMediaSource(a),i)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,zD(r),kfe(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,s=n.tracks,i=s?Object.keys(s):null,a=i?i.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(s&&i&&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: ${En(r,(l,c)=>l==="initSegment"?void 0:c)};
transfer tracks: ${En(s,(l,c)=>l==="initSegment"?void 0:c)}}`),!_5(s,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(s)}"->"${Object.keys(r)}") start time: ${u} currentTime: ${l}`),this.onMediaDetaching(B.MEDIA_DETACHING,{}),this.onMediaAttaching(B.MEDIA_ATTACHING,n),e.currentTime=u;return}this.transferData=void 0,i.forEach(l=>{const c=l,u=s[c];if(u){const d=u.buffer;if(d){const h=this.fragmentTracker,f=u.id;if(h.hasFragments(f)||h.hasParts(f)){const y=Pt.getBuffered(d);h.detectEvictedFragments(c,y,f,null,!0)}const m=Ax(c),g=[c,d];this.sourceBuffers[m]=g,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:s,mediaSource:i,_objectUrl:a}=this;if(i){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=i.readyState==="open";try{const l=i.sourceBuffers;for(let c=l.length;c--;)o&&l[c].abort(),i.removeSourceBuffer(l[c]);o&&i.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}i.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("sourceended",this._onMediaSourceEnded),i.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(i.removeEventListener("startstreaming",this._onStartStreaming),i.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(s.removeEventListener("emptied",this._onMediaEmptied),r||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(s.removeAttribute("src"),this.appendSource&&zD(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(B.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 s;(s=this.mediaSource)!=null&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(i){this.warn(`onBufferReset ${e}`,i)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Ax(e)]=[null,null];const n=this.tracks[e];n&&(n.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Afe(this.tracks)}onBufferCodecs(e,n){var r;const s=this.tracks,i=Object.keys(n);this.log(`BUFFER_CODECS: "${i}" (current SB count ${this.sourceBufferCount})`);const a="audiovideo"in n&&(s.audio||s.video)||s.audiovideo&&("audio"in n||"video"in n),o=!a&&this.sourceBufferCount&&this.media&&i.some(l=>!s[l]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(s)}" and "${i}" SourceBuffers`);return}i.forEach(l=>{var c,u;const d=n[l],{id:h,codec:f,levelCodec:m,container:g,metadata:y,supplemental:v}=d;let _=s[l];const S=(c=this.transferData)==null||(c=c.tracks)==null?void 0:c[l],E=S!=null&&S.buffer?S:_,L=(E==null?void 0:E.pendingCodec)||(E==null?void 0:E.codec),U=E==null?void 0:E.levelCodec;_||(_=s[l]={buffer:void 0,listeners:[],codec:f,supplemental:v,container:g,levelCodec:m,metadata:y,id:h});const P=Cy(L,U),I=P==null?void 0:P.replace(HD,"$1");let k=Cy(f,m);const R=(u=k)==null?void 0:u.replace(HD,"$1");k&&P&&I!==R&&(l.slice(0,5)==="audio"&&(k=G0(k,this.appendSource)),this.log(`switching codec ${L} to ${k}`),k!==(_.pendingCodec||_.codec)&&(_.pendingCodec=k),_.container=g,this.appendChangeType(l,g,k))}),(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 s=`${n};codecs=${r}`,i={label:`change-type=${s}`,execute:()=>{const a=this.tracks[e];if(a){const o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${s}`),o.changeType(s),a.codec=r,a.container=n)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(i,e,this.isPending(this.tracks[e]))}blockAudio(e){var n;const r=e.start,s=r+e.duration*.05;if(((n=this.fragmentTracker.getAppendedFrag(r,rt.MAIN))==null?void 0:n.gap)===!0)return;const a={label:"block-audio",execute:()=>{var o;const l=this.tracks.video;(this.lastVideoAppendEnd>s||l!=null&&l.buffer&&Pt.isBuffered(l.buffer,s)||((o=this.fragmentTracker.getAppendedFrag(s,rt.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:s,type:i,parent:a,frag:o,part:l,chunkMeta:c,offset:u}=n,d=c.buffering[i],{sn:h,cc:f}=o,m=self.performance.now();d.start=m;const g=o.stats.buffering,y=l?l.stats.buffering:null;g.start===0&&(g.start=m),y&&y.start===0&&(y.start=m);const v=r.audio;let _=!1;i==="audio"&&(v==null?void 0:v.container)==="audio/mpeg"&&(_=!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 P=l||o,I=this.blockedAudioAppend;if(i==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(S.ending||S.ended)){const R=P.start+P.duration*.05,M=E.buffered,G=this.currentOp("video");!M.length&&!G?this.blockAudio(P):!G&&!Pt.isBuffered(E,R)&&this.lastVideoAppendEnd<R&&this.blockAudio(P)}else if(i==="video"){const k=P.end;if(I){const R=I.frag.start;(k>R||k<this.lastVideoAppendEnd||Pt.isBuffered(E,R))&&this.unblockAudio()}this.lastVideoAppendEnd=k}}const L=(l||o).start,U={label:`append-${i}`,execute:()=>{var P;d.executeStart=self.performance.now();const I=(P=this.tracks[i])==null?void 0:P.buffer;I&&(_?this.updateTimestampOffset(I,L,.1,i,h,f):u!==void 0&&tt(u)&&this.updateTimestampOffset(I,u,1e-6,i,h,f)),this.appendExecutor(s,i)},onStart:()=>{},onComplete:()=>{const P=self.performance.now();d.executeEnd=d.end=P,g.first===0&&(g.first=P),y&&y.first===0&&(y.first=P);const I={};this.sourceBuffers.forEach(([k,R])=>{k&&(I[k]=Pt.getBuffered(R))}),this.appendErrors[i]=0,i==="audio"||i==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(B.BUFFER_APPENDED,{type:i,frag:o,part:l,chunkMeta:c,parent:o.type,timeRanges:I})},onError:P=>{var I;const k={type:ft.MEDIA_ERROR,parent:o.type,details:Se.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:o,part:l,chunkMeta:c,error:P,err:P,fatal:!1},R=(I=this.media)==null?void 0:I.error;if(P.code===DOMException.QUOTA_EXCEEDED_ERR||P.name=="QuotaExceededError"||"quota"in P)k.details=Se.BUFFER_FULL_ERROR;else if(P.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!R)k.errorAction=Md(!0);else if(P.name===E4&&this.sourceBufferCount===0)k.errorAction=Md(!0);else{const M=++this.appendErrors[i];this.warn(`Failed ${M}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${i}" sourceBuffer (${R||"no media error"})`),(M>=this.hls.config.appendErrorMaxRetry||R)&&(k.fatal=!0)}this.hls.trigger(B.ERROR,k)}};this.log(`queuing "${i}" append sn: ${h}${l?" p: "+l.index:""} of ${o.type===rt.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(U,i,this.isPending(this.tracks[i]))}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(B.BUFFER_FLUSHED,{type:e})},onError:s=>{this.warn(`Failed to remove ${n}-${r} from "${e}" SourceBuffer`,s)}}}onBufferFlushing(e,n){const{type:r,startOffset:s,endOffset:i}=n;r?this.append(this.getFlushOp(r,s,i),r):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,s,i),a)})}onFragParsed(e,n){const{frag:r,part:s}=n,i=[],a=s?s.elementaryStreams:r.elementaryStreams;a[bn.AUDIOVIDEO]?i.push("audiovideo"):(a[bn.AUDIO]&&i.push("audio"),a[bn.VIDEO]&&i.push("video"));const o=()=>{const l=self.performance.now();r.stats.buffering.end=l,s&&(s.stats.buffering.end=l);const c=s?s.stats:r.stats;this.hls.trigger(B.FRAG_BUFFERED,{frag:r,part:s,stats:c,id:r.type})};i.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${r.type} level: ${r.level} sn: ${r.sn}`),this.blockBuffers(o,i).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 s=((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)})?s?(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(B.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(B.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===Se.BUFFER_APPEND_ERROR&&n.frag){var r;const s=(r=n.errorAction)==null?void 0:r.nextAutoLevel;tt(s)&&s!==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 s=e.config,i=r.currentTime,a=n.levelTargetDuration,o=n.live&&s.liveBackBufferLength!==null?s.liveBackBufferLength:s.backBufferLength;if(tt(o)&&o>=0){const c=Math.max(o,a),u=Math.floor(i/a)*a-c;this.flushBackBuffer(i,a,u)}const l=s.frontBufferFlushThreshold;if(tt(l)&&l>0){const c=Math.max(s.maxBufferLength,l),u=Math.max(c,a),d=Math.floor(i/a)*a+u;this.flushFrontBuffer(i,a,d)}}flushBackBuffer(e,n,r){this.sourceBuffers.forEach(([s,i])=>{if(i){const o=Pt.getBuffered(i);if(o.length>0&&r>o.start(0)){var a;this.hls.trigger(B.BACK_BUFFER_REACHED,{bufferEnd:r});const l=this.tracks[s];if((a=this.details)!=null&&a.live)this.hls.trigger(B.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(l!=null&&l.ended){this.log(`Cannot flush ${s} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(B.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:s})}}})}flushFrontBuffer(e,n,r){this.sourceBuffers.forEach(([s,i])=>{if(i){const a=Pt.getBuffered(i),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(B.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:s})}})}getDurationAndRange(){var e;const{details:n,mediaSource:r}=this;if(!n||!this.media||(r==null?void 0:r.readyState)!=="open")return null;const s=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,s);return{duration:1/0,start:c,end:u}}return{duration:1/0}}const i=(e=this.overrides)==null?void 0:e.duration;if(i)return tt(i)?{duration:i}:null;const a=this.media.duration,o=tt(r.duration)?r.duration:0;return s>o&&s>a||!tt(a)?{duration:s}:null}updateMediaSource({duration:e,start:n,end:r}){const s=this.mediaSource;!this.media||!s||s.readyState!=="open"||(s.duration!==e&&(tt(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),s.duration=e),n!==void 0&&r!==void 0&&(this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${n}-${r}.`),s.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}) ${En(r)}`),this.tracksReady){var s;const i=(s=this.transferData)==null?void 0:s.tracks;i&&Object.keys(i).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([n,r])=>{if(n){const s=this.tracks[n];e[n]={buffer:r,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(B.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(B.ERROR,{type:ft.MEDIA_ERROR,details:Se.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 i in e){const a=i,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":""} ${En(o)}`);try{const u=r.addSourceBuffer(c),d=Ax(a),h=[a,u];n[d]=h,o.buffer=u}catch(u){var s;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(a),(s=this.operationQueue)==null||s.removeBlockers(),delete this.tracks[a],this.hls.trigger(B.ERROR,{type:ft.MEDIA_ERROR,details:Se.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 s=e.codec;r&&(n==="video"||n==="audiovideo")&&$p(r,"video")&&(s=vde(s,r));const i=Cy(s,e.levelCodec);return i?n.slice(0,5)==="audio"?G0(i,this.appendSource):i:""}trackSourceBuffer(e,n){const r=n.buffer;if(!r)return;const s=this.getTrackCodec(n,e);this.tracks[e]={buffer:r,codec:s,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",(i,a)=>{const o=a.removedRanges;o!=null&&o.length&&this.hls.trigger(B.BUFFER_FLUSHED,{type:i})})}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 s=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(r=this.mediaSource)==null?void 0:r.readyState}`);this.error(`${s}`,n),this.hls.trigger(B.ERROR,{type:ft.MEDIA_ERROR,details:Se.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:s,fatal:!1});const i=this.currentOp(e);i&&i.onError(s)}updateTimestampOffset(e,n,r,s,i,a){const o=n-e.timestampOffset;Math.abs(o)>=r&&(this.log(`Updating ${s} SourceBuffer timestampOffset to ${n} (sn: ${i} cc: ${a})`),e.timestampOffset=n)}removeExecutor(e,n,r){const{media:s,mediaSource:i}=this,a=this.tracks[e],o=a==null?void 0:a.buffer;if(!s||!i||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const l=tt(s.duration)?s.duration:1/0,c=tt(i.duration)?i.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],s=r==null?void 0:r.buffer;if(!s)throw new Rfe(`Attempting to append to the ${n} SourceBuffer, but it does not exist`);r.ending=!1,r.ended=!1,s.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,s=n.map(a=>this.appendBlocker(a));return n.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then(a=>{r===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(n=>{var r;const s=(r=this.tracks[n])==null?void 0:r.buffer;!s||s.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 s=this.tracks[e];if(!s)return;const i=s.buffer;if(!i)return;const a=r.bind(this,e);s.listeners.push({event:n,listener:a}),i.addEventListener(n,a)}removeBufferListeners(e){const n=this.tracks[e];if(!n)return;const r=n.buffer;r&&(n.listeners.forEach(s=>{r.removeEventListener(s.event,s.listener)}),n.listeners.length=0)}}function zD(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(n=>{t.removeChild(n)})}function kfe(t,e){const n=self.document.createElement("source");n.type="video/mp4",n.src=e,t.appendChild(n)}function Ax(t){return t==="audio"?1:0}class UA{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(B.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(B.MANIFEST_PARSED,this.onManifestParsed,this),e.on(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(B.BUFFER_CODECS,this.onBufferCodecs,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(B.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(B.MANIFEST_PARSED,this.onManifestParsed,this),e.off(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(B.BUFFER_CODECS,this.onBufferCodecs,this),e.off(B.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&&tt(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((s,i)=>this.isLevelAllowed(s)&&i<=e);return this.clientRect=null,UA.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 s=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let i=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)&&s(l,e[o+1])){i=o;break}}return i}}const Lfe={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Es=Lfe,Ife={HLS:"h"},Pfe=Ife;class Ia{constructor(e,n){Array.isArray(e)&&(e=e.map(r=>r instanceof Ia?r:new Ia(r))),this.value=e,this.params=n}}const Dfe="Dict";function Ofe(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 Nfe(t,e,n,r){return new Error(`failed to ${t} "${Ofe(e)}" as ${n}`,{cause:r})}function Pa(t,e,n){return Nfe("serialize",t,e,n)}class w4{constructor(e){this.description=e}}const qD="Bare Item",Mfe="Boolean";function jfe(t){if(typeof t!="boolean")throw Pa(t,Mfe);return t?"?1":"?0"}function Ufe(t){return btoa(String.fromCharCode(...t))}const Bfe="Byte Sequence";function Ffe(t){if(ArrayBuffer.isView(t)===!1)throw Pa(t,Bfe);return`:${Ufe(t)}:`}const $fe="Integer";function Vfe(t){return t<-999999999999999||999999999999999<t}function T4(t){if(Vfe(t))throw Pa(t,$fe);return t.toString()}function Gfe(t){return`@${T4(t.getTime()/1e3)}`}function A4(t,e){if(t<0)return-A4(-t,e);const n=Math.pow(10,e);if(Math.abs(t*n%1-.5)<Number.EPSILON){const s=Math.floor(t*n);return(s%2===0?s:s+1)/n}else return Math.round(t*n)/n}const Kfe="Decimal";function Hfe(t){const e=A4(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Pa(t,Kfe);const n=e.toString();return n.includes(".")?n:`${n}.0`}const zfe="String",qfe=/[\x00-\x1f\x7f]+/;function Wfe(t){if(qfe.test(t))throw Pa(t,zfe);return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Yfe(t){return t.description||t.toString().slice(7,-1)}const Xfe="Token";function WD(t){const e=Yfe(t);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Pa(e,Xfe);return e}function Dw(t){switch(typeof t){case"number":if(!tt(t))throw Pa(t,qD);return Number.isInteger(t)?T4(t):Hfe(t);case"string":return Wfe(t);case"symbol":return WD(t);case"boolean":return jfe(t);case"object":if(t instanceof Date)return Gfe(t);if(t instanceof Uint8Array)return Ffe(t);if(t instanceof w4)return WD(t);default:throw Pa(t,qD)}}const Qfe="Key";function Ow(t){if(/^[a-z*][a-z0-9\-_.*]*$/.test(t)===!1)throw Pa(t,Qfe);return t}function BA(t){return t==null?"":Object.entries(t).map(([e,n])=>n===!0?`;${Ow(e)}`:`;${Ow(e)}=${Dw(n)}`).join("")}function R4(t){return t instanceof Ia?`${Dw(t.value)}${BA(t.params)}`:Dw(t)}function Jfe(t){return`(${t.value.map(R4).join(" ")})${BA(t.params)}`}function Zfe(t,e={whitespace:!0}){if(typeof t!="object"||t==null)throw Pa(t,Dfe);const n=t instanceof Map?t.entries():Object.entries(t),r=e!=null&&e.whitespace?" ":"";return Array.from(n).map(([s,i])=>{i instanceof Ia||(i=new Ia(i));let a=Ow(s);return i.value===!0?a+=BA(i.params):(a+="=",Array.isArray(i.value)?a+=Jfe(i):a+=R4(i)),a}).join(`,${r}`)}function C4(t,e){return Zfe(t,e)}const ia="CMCD-Object",zn="CMCD-Request",cc="CMCD-Session",Go="CMCD-Status",epe={br:ia,ab:ia,d:ia,ot:ia,tb:ia,tpb:ia,lb:ia,tab:ia,lab:ia,url:ia,pb:zn,bl:zn,tbl:zn,dl:zn,ltc:zn,mtp:zn,nor:zn,nrr:zn,rc:zn,sn:zn,sta:zn,su:zn,ttfb:zn,ttfbb:zn,ttlb:zn,cmsdd:zn,cmsds:zn,smrt:zn,df:zn,cs:zn,ts:zn,cid:cc,pr:cc,sf:cc,sid:cc,st:cc,v:cc,msd:cc,bs:Go,bsd:Go,cdn:Go,rtp:Go,bg:Go,pt:Go,ec:Go,e:Go},tpe={REQUEST:zn};function npe(t){return Object.keys(t).reduce((e,n)=>{var r;return(r=t[n])===null||r===void 0||r.forEach(s=>e[s]=n),e},{})}function rpe(t,e){const n={};if(!t)return n;const r=Object.keys(t),s=e?npe(e):{};return r.reduce((i,a)=>{var o;const l=epe[a]||s[a]||tpe.REQUEST,c=(o=i[l])!==null&&o!==void 0?o:i[l]={};return c[a]=t[a],i},n)}function spe(t){return["ot","sf","st","e","sta"].includes(t)}function ipe(t){return typeof t=="number"?tt(t):t!=null&&t!==""&&t!==!1}const k4="event";function ape(t,e){const n=new URL(t),r=new URL(e);if(n.origin!==r.origin)return t;const s=n.pathname.split("/").slice(1),i=r.pathname.split("/").slice(1,-1);for(;s[0]===i[0];)s.shift(),i.shift();for(;i.length;)i.shift(),s.unshift("..");return s.join("/")+n.search+n.hash}const Dy=t=>Math.round(t),Nw=(t,e)=>Array.isArray(t)?t.map(n=>Nw(n,e)):t instanceof Ia&&typeof t.value=="string"?new Ia(Nw(t.value,e),t.params):(e.baseUrl&&(t=ape(t,e.baseUrl)),e.version===1?encodeURIComponent(t):t),Hg=t=>Dy(t/100)*100,ope=(t,e)=>{let n=t;return e.version>=2&&(t instanceof Ia&&typeof t.value=="string"?n=new Ia([t]):typeof t=="string"&&(n=[t])),Nw(n,e)},lpe={br:Dy,d:Dy,bl:Hg,dl:Hg,mtp:Hg,nor:ope,rtp:Hg,tb:Dy},L4="request",I4="response",FA=["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"],cpe=["e"],upe=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function r_(t){return upe.test(t)}function dpe(t){return FA.includes(t)||cpe.includes(t)||r_(t)}const P4=["d","dl","nor","ot","rtp","su"];function hpe(t){return FA.includes(t)||P4.includes(t)||r_(t)}const fpe=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function ppe(t){return FA.includes(t)||P4.includes(t)||fpe.includes(t)||r_(t)}const mpe=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function gpe(t){return mpe.includes(t)||r_(t)}const ype={[I4]:ppe,[k4]:dpe,[L4]:hpe};function D4(t,e={}){const n={};if(t==null||typeof t!="object")return n;const r=e.version||t.v||1,s=e.reportingMode||L4,i=r===1?gpe:ype[s];let a=Object.keys(t).filter(i);const o=e.filter;typeof o=="function"&&(a=a.filter(o));const l=s===I4||s===k4;l&&!a.includes("ts")&&a.push("ts"),r>1&&!a.includes("v")&&a.push("v");const c=vn({},lpe,e.formatters),u={version:r,reportingMode:s,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"&&!tt(h)&&(h=Date.now()),ipe(h)&&(spe(d)&&typeof h=="string"&&(h=new w4(h)),n[d]=h))}),n}function vpe(t,e={}){const n={};if(!t)return n;const r=D4(t,e),s=rpe(r,e==null?void 0:e.customHeaderMap);return Object.entries(s).reduce((i,[a,o])=>{const l=C4(o,{whitespace:!1});return l&&(i[a]=l),i},n)}function _pe(t,e,n){return vn(t,vpe(e,n))}const bpe="CMCD";function xpe(t,e={}){return t?C4(D4(t,e),{whitespace:!1}):""}function Spe(t,e={}){if(!t)return"";const n=xpe(t,e);return encodeURIComponent(n)}function Epe(t,e={}){if(!t)return"";const n=Spe(t,e);return`${bpe}=${n}`}const YD=/CMCD=[^&#]+/;function wpe(t,e,n){const r=Epe(e,n);if(!r)return t;if(YD.test(t))return t.replace(YD,r);const s=t.includes("?")?"&":"?";return`${t}${s}${r}`}class Tpe{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=s=>{try{this.apply(s,{ot:Es.MANIFEST,su:!this.initialized})}catch(i){this.hls.logger.warn("Could not generate manifest CMCD data.",i)}},this.applyFragmentData=s=>{try{const{frag:i,part:a}=s,o=this.hls.levels[i.level],l=this.getObjectType(i),c={d:(a||i).duration*1e3,ot:l};(l===Es.VIDEO||l===Es.AUDIO||l==Es.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(i);u!=null&&u.url&&u.url!==i.url&&(c.nor=u.url),this.apply(s,c)}catch(i){this.hls.logger.warn("Could not generate segment CMCD data.",i)}},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(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(B.MEDIA_DETACHED,this.onMediaDetached,this),e.on(B.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(B.MEDIA_DETACHED,this.onMediaDetached,this),e.off(B.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,s;this.audioBuffer=(r=n.tracks.audio)==null?void 0:r.buffer,this.videoBuffer=(s=n.tracks.video)==null?void 0:s.buffer}createData(){var e;return{v:1,sf:Pfe.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,n={}){vn(n,this.createData());const r=n.ot===Es.INIT||n.ot===Es.VIDEO||n.ot===Es.MUXED;this.starved&&r&&(n.bs=!0,n.su=!0,this.starved=!1),n.su==null&&(n.su=this.buffering);const{includeKeys:s}=this;s&&(n=Object.keys(n).reduce((a,o)=>(s.includes(o)&&(a[o]=n[o]),a),{}));const i={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),_pe(e.headers,n,i)):e.url=wpe(e.url,n,i)}getNextFrag(e){var n;const r=(n=this.hls.levels[e.level])==null?void 0:n.details;if(r){const s=e.sn-r.startSN;return r.fragments[s+1]}}getNextPart(e){var n;const{index:r,fragment:s}=e,i=(n=this.hls.levels[s.level])==null||(n=n.details)==null?void 0:n.partList;if(i){const{sn:a}=s;for(let o=i.length-1;o>=0;o--){const l=i[o];if(l.index===r&&l.fragment.sn===a)return i[o+1]}}}getObjectType(e){const{type:n}=e;if(n==="subtitle")return Es.TIMED_TEXT;if(e.sn==="initSegment")return Es.INIT;if(n==="audio")return Es.AUDIO;if(n==="main")return this.hls.audioTracks.length?Es.VIDEO:Es.MUXED}getTopBandwidth(e){let n=0,r;const s=this.hls;if(e===Es.AUDIO)r=s.audioTracks;else{const i=s.maxAutoLevel,a=i>-1?i+1:s.levels.length;r=s.levels.slice(0,a)}return r.forEach(i=>{i.bitrate>n&&(n=i.bitrate)}),n>0?n:NaN}getBufferLength(e){const n=this.media,r=e===Es.AUDIO?this.audioBuffer:this.videoBuffer;return!r||!n?NaN:Pt.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(i){this.loader=void 0,this.loader=new r(i)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(i,a,o){n(i),this.loader.load(i,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,n=this.applyFragmentData,r=e||this.config.loader;return class{constructor(i){this.loader=void 0,this.loader=new r(i)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(i,a,o){n(i),this.loader.load(i,a,o)}}}}const Ape=3e5;class Rpe extends Ii{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(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(B.MANIFEST_PARSED,this.onManifestParsed,this),e.on(B.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(B.MANIFEST_PARSED,this.onManifestParsed,this),e.off(B.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)===$r.SendAlternateToPenaltyBox&&r.flags===Bs.MoveAllAlternatesMatchingHost){const s=this.levels;let i=this._pathwayPriority,a=this.pathwayId;if(n.context){const{groupId:o,pathwayId:l,type:c}=n.context;o&&s?a=this.getPathwayForGroupId(o,c,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!i&&s&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),r.resolved=this.pathwayId!==a),n.details===Se.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: ${s&&s.length} priorities: ${En(i)} penalized: ${En(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,s=performance.now();Object.keys(r).forEach(i=>{s-r[i]>Ape&&delete r[i]});for(let i=0;i<e.length;i++){const a=e[i];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,Z5(n),this.hls.trigger(B.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 s=this.getLevelsForPathway(r).concat(this.levels||[]);for(let i=0;i<s.length;i++)if(n===Kt.AUDIO_TRACK&&s[i].hasAudioGroup(e)||n===Kt.SUBTITLE_TRACK&&s[i].hasSubtitleGroup(e))return s[i].pathwayId;return r}clonePathways(e){const n=this.levels;if(!n)return;const r={},s={};e.forEach(i=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=i;if(n.some(u=>u.pathwayId===a))return;const c=this.getLevelsForPathway(o).map(u=>{const d=new Gn(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&&(s[d.SUBTITLES]=f,d.SUBTITLES=f);const m=O4(u.uri,d["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),g=new Gp({attrs:d,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:m,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let y=1;y<u.audioGroups.length;y++)g.addGroupId("audio",`${u.audioGroups[y]}_clone_${a}`);if(u.subtitleGroups)for(let y=1;y<u.subtitleGroups.length;y++)g.addGroupId("text",`${u.subtitleGroups[y]}_clone_${a}`);return g});n.push(...c),XD(this.audioTracks,r,l,a),XD(this.subtitleTracks,s,l,a)})}loadSteeringManifest(e){const n=this.hls.config,r=n.loader;this.loader&&this.loader.destroy(),this.loader=new r(n);let s;try{s=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(s.protocol!=="data:"){const u=(this.hls.bandwidthEstimate||n.abrEwmaDefaultEstimate)|0;s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+u)}const i={responseType:"json",url:s.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: "${s}"`);const m=u.data;if((m==null?void 0:m.VERSION)!==1){this.log(`Steering VERSION ${m.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=m.TTL;const{"RELOAD-URI":g,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":v}=m;if(g)try{this.uri=new self.URL(g,s).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${g}`);return}this.scheduleRefresh(this.uri||h.url),y&&this.clonePathways(y);const _={steeringManifest:m,url:s.toString()};this.hls.trigger(B.STEERING_MANIFEST_LOADED,_),v&&this.updatePathwayPriority(v)},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 m=this.timeToLoad*1e3;if(u.code===429){const g=this.loader;if(typeof(g==null?void 0:g.getResponseHeader)=="function"){const y=g.getResponseHeader("Retry-After");y&&(m=parseFloat(y)*1e3)}this.log(`Steering manifest ${d.url} rate limited`);return}this.scheduleRefresh(this.uri||d.url,m)},onTimeout:(u,d,h)=>{this.log(`Timeout loading steering manifest (${d.url})`),this.scheduleRefresh(this.uri||d.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(i,l,c)}scheduleRefresh(e,n=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var r;const s=(r=this.hls)==null?void 0:r.media;if(s&&!s.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},n)}}function XD(t,e,n,r){t&&Object.keys(e).forEach(s=>{const i=t.filter(a=>a.groupId===s).map(a=>{const o=vn({},a);return o.details=void 0,o.attrs=new Gn(o.attrs),o.url=o.attrs.URI=O4(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",n),o.groupId=o.attrs["GROUP-ID"]=e[s],o.attrs["PATHWAY-ID"]=r,o});t.push(...i)})}function O4(t,e,n,r){const{HOST:s,PARAMS:i,[n]:a}=r;let o;e&&(o=a==null?void 0:a[e],o&&(t=o));const l=new self.URL(t);return s&&!o&&(l.host=s),i&&Object.keys(i).sort().forEach(c=>{c&&l.searchParams.set(c,i[c])}),l.href}class Ud extends Ii{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=Ud.CDMCleanupPromise?[Ud.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=n=>{const{initDataType:r,initData:s}=n,i=`"${n.type}" event: init data type: "${r}"`;if(this.debug(i),s!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=Af(this.config));const o=a.map(vx).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{const o=Ly(a);if(r!=="sinf"||o!==Kn.FAIRPLAY){this.log(`Ignoring "${n.type}" event with init data type: "${r}" for selected key-system ${o}`);return}let l;try{const f=_r(new Uint8Array(s)),m=CA(JSON.parse(f).sinf),g=C5(m);if(!g)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");l=new Uint8Array(g.subarray(8,24))}catch(f){this.warn(`${i} Failed to parse sinf: ${f}`);return}const c=Vr(l),{keyIdToKeySessionPromise:u,mediaKeySessions:d}=this;let h=u[c];for(let f=0;f<d.length;f++){const m=d[f],g=m.decryptdata;if(!g.keyId)continue;const y=Vr(g.keyId);if(W0(l,g.keyId)||g.uri.replace(/-/g,"").indexOf(c)!==-1){if(h=u[y],!h)continue;if(g.pssh)break;delete u[y],g.pssh=new Uint8Array(s),g.keyId=l,h=u[c]=h.then(()=>this.generateRequestWithPreferredKeySession(m,r,s,"encrypted-event-key-match")),h.catch(v=>this.handleError(v));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(B.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(B.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(B.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(B.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(B.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(B.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(B.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(B.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(B.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(B.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:n,widevineLicenseUrl:r}=this.config,s=n==null?void 0:n[e];if(s)return s.licenseUrl;if(e===Kn.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,s=n.map(a=>a.audioCodec).filter(r),i=n.map(a=>a.videoCodec).filter(r);return s.length+i.length===0&&i.push("avc1.42e01e"),new Promise((a,o)=>{const l=c=>{const u=c.shift();this.getMediaKeysPromise(u,s,i).then(d=>a({keySystem:u,mediaKeys:d})).catch(d=>{c.length?l(c):d instanceof Us?o(d):o(new Us({type:ft.KEY_SYSTEM_ERROR,details:Se.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 s=`Configured requestMediaKeySystemAccess is not a function ${r}`;return H5===null&&self.location.protocol==="http:"&&(s=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(s))}return r(e,n)}getMediaKeysPromise(e,n,r){var s;const i=ohe(e,n,r,this.config.drmSystemOptions||{});let a=this.keySystemAccessPromises[e],o=(s=a)==null?void 0:s.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${En(i)}`),o=this.requestMediaKeySystemAccess(e,i);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: ${Vr(e.keyId||[])} keyUri: ${e.uri}`);const s=r.createSession(),i={decryptdata:e,keySystem:n,mediaKeys:r,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(i),i}renewKeySession(e){const n=e.decryptdata;if(n.pssh){const r=this.createMediaKeySessionContext(e),s=zg(n),i="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(r,i,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 ${Vr(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})=>vx(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:s})=>{const i=vx(s);i?n(i):r(new Error(`Unable to find format for key-system "${s}"`))}).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=Af(this.config),r=e.map(Ly).filter(s=>!!s&&n.indexOf(s)!==-1);return this.selectKeySystem(r)}getKeyStatus(e){const{mediaKeySessions:n}=this;for(let r=0;r<n.length;r++){const s=Cpe(e,n[r]);if(s)return s}}loadKey(e){const n=e.keyInfo.decryptdata,r=zg(n),s=this.bannedKeyIds[r];if(s||this.getKeyStatus(n)==="internal-error"){const o=QD(s||"internal-error",n);return this.handleError(o,e.frag),Promise.reject(o)}const i=`(keyId: ${r} format: "${n.keyFormat}" method: ${n.method} uri: ${n.uri})`;this.log(`Starting session for key ${i}`);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 ${i}`),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 Us){const l=hn({},o.data);this.getKeyStatus(n)==="internal-error"&&(l.decryptdata=n);const c=new Us(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 Us){n&&(e.data.frag=n);const r=e.data.decryptdata;this.error(`${e.message}${r?` (${Vr(r.keyId||[])})`:""}`),this.hls.trigger(B.ERROR,e.data)}else this.error(e.message),this.hls.trigger(B.ERROR,{type:ft.KEY_SYSTEM_ERROR,details:Se.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const n=zg(e),r=this.keyIdToKeySessionPromise[n];if(!r){const s=Ly(e.keyFormat),i=s?[s]:Af(this.config);return this.attemptKeySystemAccess(i)}return r}getKeySystemSelectionPromise(e){if(e.length||(e=Af(this.config)),e.length===0)throw new Us({type:ft.KEY_SYSTEM_ERROR,details:Se.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${En({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 s=Promise.all(r).then(()=>this.media?this.media.setMediaKeys(n):new Promise((i,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(i).catch(a)}}));return this.mediaKeys=n,this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${e}"`),r.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(i=>r.indexOf(i)===-1)})}generateRequestWithPreferredKeySession(e,n,r,s){var i;const a=(i=this.config.drmSystems)==null||(i=i[e.keySystem])==null?void 0:i.generateRequest;if(a)try{const m=a.call(this.hls,n,r,e);if(!m)throw new Error("Invalid response from configured generateRequest filter");n=m.initDataType,r=m.initData?m.initData:null,e.decryptdata.pssh=r?new Uint8Array(r):null}catch(m){if(this.warn(m.message),this.hls&&this.hls.config.debug)throw m}if(r===null)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(e);const o=zg(e.decryptdata),l=e.decryptdata.uri;this.log(`Generating key-session request for "${s}" keyId: ${o} URI: ${l} (init data type: ${n} length: ${r.byteLength})`);const c=new LA,u=e._onmessage=m=>{const g=e.mediaKeysSession;if(!g){c.emit("error",new Error("invalid state"));return}const{messageType:y,message:v}=m;this.log(`"${y}" message event for session "${g.sessionId}" message size: ${v.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(e,v).catch(_=>{c.eventNames().length?c.emit("error",_):this.handleError(_)}):y==="license-release"?e.keySystem===Kn.FAIRPLAY&&this.updateKeySession(e,Rw("acknowledged")).then(()=>this.removeSession(e)).catch(_=>this.handleError(_)):this.warn(`unhandled media key message type "${y}"`)},d=(m,g)=>{g.keyStatus=m;let y;m.startsWith("usable")?c.emit("resolved"):m==="internal-error"||m==="output-restricted"||m==="output-downscaled"?y=QD(m,g.decryptdata):m==="expired"?y=new Error(`key expired (keyId: ${o})`):m==="released"?y=new Error("key released"):m==="status-pending"||this.warn(`unhandled key status change "${m}" (keyId: ${o})`),y&&(c.eventNames().length?c.emit("error",y):this.handleError(y))},h=e._onkeystatuseschange=m=>{if(!e.mediaKeysSession){c.emit("error",new Error("invalid state"));return}const y=this.getKeyStatuses(e);if(!Object.keys(y).some(E=>y[E]!=="status-pending"))return;if(y[o]==="expired"){this.log(`Expired key ${En(y)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let _=y[o];if(_)d(_,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`),_="internal-error",d(_,e)},1e3)),this.log(`No status for keyId ${o} (${En(y)}).`)}};hs(e.mediaKeysSession,"message",u),hs(e.mediaKeysSession,"keystatuseschange",h);const f=new Promise((m,g)=>{c.on("error",g),c.on("resolved",m)});return e.mediaKeysSession.generateRequest(n,r).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${l}`)}).catch(m=>{throw new Us({type:ft.KEY_SYSTEM_ERROR,details:Se.KEY_SYSTEM_NO_SESSION,error:m,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${m}`)}).then(()=>f).catch(m=>(c.removeAllListeners(),this.removeSession(e).then(()=>{throw m}))).then(()=>(c.removeAllListeners(),e))}getKeyStatuses(e){const n={};return e.mediaKeysSession.keyStatuses.forEach((r,s)=>{if(typeof s=="string"&&typeof r=="object"){const o=s;s=r,r=o}const i="buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s);if(e.keySystem===Kn.PLAYREADY&&i.length===16){const o=Vr(i);n[o]=r,G5(i)}const a=Vr(i);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,s=new r(n),i=this.getServerCertificateUrl(e);return i?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:i},c=n.certLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(h,f,m,g)=>{a(h.data)},onError:(h,f,m,g)=>{o(new Us({type:ft.KEY_SYSTEM_ERROR,details:Se.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:hn({url:l.url,data:void 0},h)},`"${e}" certificate request failed (${i}). Status: ${h.code} (${h.text})`))},onTimeout:(h,f,m)=>{o(new Us({type:ft.KEY_SYSTEM_ERROR,details:Se.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${i})`))},onAbort:(h,f,m)=>{o(new Error("aborted"))}};s.load(l,u,d)})):Promise.resolve()}setMediaKeysServerCertificate(e,n,r){return new Promise((s,i)=>{e.setServerCertificate(r).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${r.byteLength}) on "${n}"`),s(e)}).catch(a=>{i(new Us({type:ft.KEY_SYSTEM_ERROR,details:Se.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(s=>{throw new Us({type:ft.KEY_SYSTEM_ERROR,details:Se.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:s,fatal:!1},s.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 s=new DOMParser().parseFromString(r,"application/xml"),i=s.querySelectorAll("HttpHeader");if(i.length>0){let u;for(let d=0,h=i.length;d<h;d++){var a,o;u=i[d];const f=(a=u.querySelector("name"))==null?void 0:a.textContent,m=(o=u.querySelector("value"))==null?void 0:o.textContent;f&&m&&e.setRequestHeader(f,m)}}const l=s.querySelector("Challenge"),c=l==null?void 0:l.textContent;if(!c)throw new Error("Cannot find <Challenge> in key message");return Rw(atob(c))}setupLicenseXHR(e,n,r,s){const i=this.config.licenseXhrSetup;return i?Promise.resolve().then(()=>{if(!r.decryptdata)throw new Error("Key removed");return i.call(this.hls,e,n,r,s)}).catch(a=>{if(!r.decryptdata)throw a;return e.open("POST",n,!0),i.call(this.hls,e,n,r,s)}).then(a=>(e.readyState||e.open("POST",n,!0),{xhr:e,licenseChallenge:a||s})):(e.open("POST",n,!0),Promise.resolve({xhr:e,licenseChallenge:s}))}requestLicense(e,n){const r=this.config.keyLoadPolicy.default;return new Promise((s,i)=>{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 i(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)}s(l)}else{const l=r.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||o.status>=400&&o.status<500)i(new Us({type:ft.KEY_SYSTEM_ERROR,details:Se.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(s,i)}}},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==Kn.PLAYREADY&&(c=this.unpackPlayReadyKeyMessage(l,c)),l.send(c)}).catch(i)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,n){if(!this.config.emeEnabled)return;const r=n.media;this.media=r,hs(r,"encrypted",this.onMediaEncrypted),hs(r,"waitingforkey",this.onWaitingForKey);const s=this.mediaResolved;s?s():this.mediaKeys=r.mediaKeys}onMediaDetached(){const e=this.media;e&&(Ls(e,"encrypted",this.onMediaEncrypted),Ls(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,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Ol.clearKeyUriToKeyIdMap();const i=s.length;Ud.CDMCleanupPromise=Promise.all(s.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(B.ERROR,{type:ft.OTHER_ERROR,details:Se.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(B.ERROR,{type:ft.OTHER_ERROR,details:Se.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{i&&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((s,i)=>(s.indexOf(i.keyFormat)===-1&&s.push(i.keyFormat),s),[]);this.log(`Selecting key-system from session-keys ${r.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(r)}}removeSession(e){const{mediaKeysSession:n,licenseXhr:r,decryptdata:s}=e;if(n){this.log(`Remove licenses and keys and close session "${n.sessionId}" keyId: ${Vr((s==null?void 0:s.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 i=this.mediaKeySessions.indexOf(e);i>-1&&this.mediaKeySessions.splice(i,1);const{keyStatusTimeouts:a}=e;a&&Object.keys(a).forEach(c=>self.clearTimeout(a[c]));const{drmSystemOptions:o}=this.config;return(che(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(B.ERROR,{type:ft.OTHER_ERROR,details:Se.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(B.ERROR,{type:ft.OTHER_ERROR,details:Se.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${c}`)})})}return Promise.resolve()}}Ud.CDMCleanupPromise=void 0;function zg(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(t.keyId===null)throw new Error("keyId is null");return Vr(t.keyId)}function Cpe(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 Us 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 QD(t,e){const n=t==="output-restricted",r=n?Se.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:Se.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Us({type:ft.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:e},n?"HDCP level output restricted":`key status changed to "${t}"`)}class kpe{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(B.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(B.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(B.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(B.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 s=n.media instanceof self.HTMLVideoElement?n.media:null;this.media=s,s&&typeof s.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 s=performance.now();if(n){if(this.lastTime){const i=s-this.lastTime,a=r-this.lastDroppedFrames,o=n-this.lastDecodedFrames,l=1e3*a/i,c=this.hls;if(c.trigger(B.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(B.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:c.currentLevel}),c.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=s,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 N4(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 M4(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){fn.debug(`[texttrack-utils]: ${r}`);try{const s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,t.addCue(s)}catch(s){fn.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${s}`)}}n==="disabled"&&(t.mode=n)}function bd(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 Mw(t,e,n,r){const s=t.mode;if(s==="disabled"&&(t.mode="hidden"),t.cues&&t.cues.length>0){const i=Ipe(t.cues,e,n);for(let a=0;a<i.length;a++)(!r||r(i[a]))&&t.removeCue(i[a])}s==="disabled"&&(t.mode=s)}function Lpe(t,e){if(e<=t[0].startTime)return 0;const n=t.length-1;if(e>t[n].endTime)return-1;let r=0,s=n,i;for(;r<=s;)if(i=Math.floor((s+r)/2),e<t[i].startTime)s=i-1;else if(e>t[i].startTime&&r<n)r=i+1;else return i;return t[r].startTime-e<e-t[s].startTime?r:s}function Ipe(t,e,n){const r=[],s=Lpe(t,e);if(s>-1)for(let i=s,a=t.length;i<a;i++){const o=t[i];if(o.startTime>=e&&o.endTime<=n)r.push(o);else if(o.startTime>n)return r}return r}function Oy(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 Ppe extends jA{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=Oy(this.media.textTracks);for(let i=0;i<r.length;i++)if(r[i].mode==="hidden")n=r[i];else if(r[i].mode==="showing"){n=r[i];break}const s=this.findTrackForTextTrack(n);this.subtitleTrack!==s&&this.setSubtitleTrack(s)},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(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.MANIFEST_PARSED,this.onManifestParsed,this),e.on(B.LEVEL_LOADING,this.onLevelLoading,this),e.on(B.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(B.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(B.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.MANIFEST_PARSED,this.onManifestParsed,this),e.off(B.LEVEL_LOADING,this.onLevelLoading,this),e.off(B.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(B.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(B.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 s=!!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,s)return;Oy(r.textTracks).forEach(a=>{bd(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:s,details:i}=n,a=this.tracksInGroup[r];if(!a||a.groupId!==s){this.warn(`Subtitle track with id:${r} and group:${s} 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:${s} loaded [${i.startSN}-${i.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,s=this.groupIds;let i=this.currentTrack;if(!r||(s==null?void 0:s.length)!==(r==null?void 0:r.length)||r!=null&&r.some(a=>(s==null?void 0:s.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(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const o=this.hls.config.subtitlePreference;if(!i&&o){this.selectDefaultTrack=!1;const u=xa(o,a);if(u>-1)i=a[u];else{const d=xa(o,this.tracks);i=this.tracks[d]}}let l=this.findTrackId(i);l===-1&&i&&(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(B.SUBTITLE_TRACKS_UPDATED,c),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}}findTrackId(e){const n=this.tracksInGroup,r=this.selectDefaultTrack;for(let s=0;s<n.length;s++){const i=n[s];if(!(r&&!i.default||!r&&!e)&&(!e||Wc(i,e)))return s}if(e){for(let s=0;s<n.length;s++){const i=n[s];if(qp(e.attrs,i.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<n.length;s++){const i=n[s];if(qp(e.attrs,i.attrs,["LANGUAGE"]))return s}}return-1}findTrackForTextTrack(e){if(e){const n=this.tracksInGroup;for(let r=0;r<n.length;r++){const s=n[r];if(Pw(s,e))return r}}return-1}onError(e,n){n.fatal||!n.context||n.context.type===Kt.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&&Wc(e,r))return r;const s=xa(e,this.tracksInGroup);if(s>-1){const i=this.tracksInGroup[s];return this.setSubtitleTrack(s),i}else{if(r)return null;{const i=xa(e,n);if(i>-1)return n[i]}}}}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,s=e.groupId,i=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:${s}${(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||""):""} ${i}`),this.hls.trigger(B.SUBTITLE_TRACK_LOADING,{url:i,id:r,groupId:s,deliveryDirectives:n||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const n=Oy(e.textTracks),r=this.currentTrack;let s;if(r&&(s=n.filter(i=>Pw(r,i))[0],s||this.warn(`Unable to find subtitle TextTrack with name "${r.name}" and language "${r.lang}"`)),[].slice.call(n).forEach(i=>{i.mode!=="disabled"&&i!==s&&(i.mode="disabled")}),s){const i=this.subtitleDisplay?"showing":"hidden";s.mode!==i&&(s.mode=i)}}setSubtitleTrack(e){const n=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=n.length||!tt(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const r=this.currentTrack,s=n[e]||null;if(this.trackId=e,this.currentTrack=s,this.toggleTrackModes(),!s){this.hls.trigger(B.SUBTITLE_TRACK_SWITCH,{id:e});return}const i=!!s.details&&!s.details.live;if(e===this.trackId&&s===r&&i)return;this.log(`Switching to subtitle-track ${e}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:""));const{id:a,groupId:o="",name:l,type:c,url:u}=s;this.hls.trigger(B.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:c,url:u});const d=this.switchParams(s.url,r==null?void 0:r.details,s.details);this.loadPlaylist(d)}}function Dpe(){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,s=>{const i=(n+Math.random()*16)%16|0;return n=Math.floor(n/16),(s=="x"?i:i&3|8).toString(16)})}}}function rp(t){let e=5381,n=t.length;for(;n;)e=e*33^t.charCodeAt(--n);return(e>>>0).toString()}const Bd=.025;let J0=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({});function Ope(t,e,n){return`${t.identifier}-${n+1}-${rp(e)}`}class Npe{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 Rx(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=Rx(n,e);return n-r<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,n=tt(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 Rx(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)<Bd))}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"?J0.Range:J0.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 Mpe(this)}}function Rx(t,e){return t-e.start<e.duration/2&&!(Math.abs(t-(e.start+e.duration))<Bd)?e.start:e.start+e.duration}function j4(t,e,n){const r=new self.URL(t,n);return r.protocol!=="data:"&&r.searchParams.set("_HLS_primary_id",e),r}function Cx(t,e){for(;(n=t.assetList[++e])!=null&&n.error;)var n;return e}function Mpe(t){return`["${t.identifier}" ${t.cue.pre?"<pre>":t.cue.post?"<post>":""}${t.timelineStart.toFixed(2)}-${t.resumeTime.toFixed(2)}]`}function nd(t){const e=t.timelineStart,n=t.duration||0;return`["${t.identifier}" ${e.toFixed(2)}-${(e+n).toFixed(2)}]`}class jpe{constructor(e,n,r,s){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(B.PLAYOUT_LIMIT_REACHED,{})};const i=this.hls=new e(n);this.interstitial=r,this.assetItem=s;const a=()=>{this.hasDetails=!0};i.once(B.LEVEL_LOADED,a),i.once(B.AUDIO_TRACK_LOADED,a),i.once(B.SUBTITLE_TRACK_LOADED,a),i.on(B.MEDIA_ATTACHING,(o,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&i.on(B.BUFFER_APPENDED,()=>{const u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,i.trigger(B.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=j4(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),s=this.timelineOffset,i=Pt.bufferInfo(e,s,0);return this.getAssetTime(i.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=Pt.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 s;(s=this.hls)==null||s.on(e,n)}once(e,n,r){var s;(s=this.hls)==null||s.once(e,n)}off(e,n,r){var s;(s=this.hls)==null||s.off(e,n)}toString(){var e;return`HlsAssetPlayer: ${nd(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const JD=.033;class Upe extends Ii{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,s)=>e<=s.startOffset&&n>s.startOffset?(delete s.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 s=this.items;if(s)for(s[r]||(n===void 0&&(n=e.start),r=this.findItemIndexAtTime(n));r>=0&&(i=s[r])!=null&&i.event;){var i;r--}return r}findItemIndexAtTime(e,n){const r=this.items;if(r)for(let s=0;s<r.length;s++){let i=r[s];if(n&&n!=="primary"&&(i=i[n]),e===i.start||e>i.start&&e<i.end)return s}return-1}findJumpRestrictedIndex(e,n){const r=this.items;if(r)for(let s=e;s<=n&&r[s];s++){const i=r[s].event;if(i!=null&&i.restrictions.jump&&!i.appendInPlace)return s}return-1}findEventIndex(e){const n=this.items;if(n)for(let s=n.length;s--;){var r;if(((r=n[s].event)==null?void 0:r.identifier)===e)return s}return-1}findAssetIndex(e,n){const r=e.assetList,s=r.length;if(s>1)for(let i=0;i<s;i++){const a=r[i];if(!a.error){const o=a.timelineStart;if(n===o||n>o&&(n<o+(a.duration||0)||i===s-1))return i}}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,s=r[r.length-1];if(s)return s.identifier}return null}parseInterstitialDateRanges(e,n){const r=e.main.details,{dateRanges:s}=r,i=this.events,a=this.parseDateRanges(s,{url:r.url},n),o=Object.keys(s),l=i?i.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,m=u.cue.post;if(d&&!f)return-1;if(f&&!d||h&&!m)return 1;if(m&&!h)return-1;if(!d&&!f&&!h&&!m){const g=c.startTime,y=u.startTime;if(g!==y)return g-y}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 s=this.events||[];if(s.length||n.length||this.length<2){const i=this.items,a=this.parseSchedule(s,e);(r||n.length||(i==null?void 0:i.length)!==a.length||a.some((l,c)=>Math.abs(l.playout.start-i[c].playout.start)>.005||Math.abs(l.playout.end-i[c].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(n,i))}}parseDateRanges(e,n,r){const s=[],i=Object.keys(e);for(let a=0;a<i.length;a++){const o=i[a],l=e[o];if(l.isInterstitial){let c=this.eventMap[o];c?c.setDateRange(l):(c=new Npe(l,n),this.eventMap[o]=c,r===!1&&(c.appendInPlace=r)),s.push(c)}}return s}parseSchedule(e,n){const r=[],s=n.main.details,i=s.live?1/0:s.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,m=e[d-1]||null,g=u.appendInPlace,y=f?i:u.startOffset,v=u.duration,_=u.timelineOccupancy===J0.Range?v:0,S=u.resumptionOffset,E=(m==null?void 0:m.startTime)===y,L=y+u.cumulativeDuration;let U=g?L+v:y+S;if(h||!f&&y<=0){const I=c;c+=_,u.timelineStart=L;const k=a;a+=v,r.push({event:u,start:L,end:U,playout:{start:k,end:a},integrated:{start:I,end:c}})}else if(y<=i){if(!E){const R=y-l;if(R>JD){const M=l,G=c;c+=R;const Y=a;a+=R;const q={previousEvent:e[d-1]||null,nextEvent:u,start:M,end:M+R,playout:{start:Y,end:a},integrated:{start:G,end:c}};r.push(q)}else R>0&&m&&(m.cumulativeDuration+=R,r[r.length-1].end=y)}f&&(U=L),u.timelineStart=L;const I=c;c+=_;const k=a;a+=v,r.push({event:u,start:L,end:U,playout:{start:k,end:a},integrated:{start:I,end:c}})}else return;const P=u.resumeTime;f||P>i?l=i:l=P}),l<i){var o;const u=l,d=c,h=i-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(i,a,c)}else r.push({previousEvent:null,nextEvent:null,start:0,end:i,playout:{start:0,end:i},integrated:{start:0,end:i}}),this.setDurations(i,i,i);return r}setDurations(e,n,r){this.durations={primary:e,playout:n,integrated:r}}resolveOffsets(e,n){const r=n.main.details,s=r.live?1/0:r.edge;let i=0,a=-1;e.forEach((o,l)=>{const c=o.cue.pre,u=o.cue.post,d=c?0:u?s:o.startTime;this.updateAssetDurations(o),a===d?o.cumulativeDuration=i:(i=0,a=d),!u&&o.snapOptions.in&&(o.resumeAnchor=ou(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<JD&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const f=tt(o.resumeOffset)?o.resumeOffset:o.duration;i+=f})}primaryCanResumeInPlaceAt(e,n){const r=e.resumeTime,s=e.startTime+e.resumptionOffset;return Math.abs(r-s)>Bd?(this.log(`"${e.identifier}" resumption ${r} not aligned with estimated timeline end ${s}`),!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=ou(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)<Bd+u||Math.abs(c.end-r)<Bd+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,s=!1,i=!1;for(let a=0;a<e.assetList.length;a++){const o=e.assetList[a],l=n+r;o.startOffset=r,o.timelineStart=l,s||(s=o.duration===null),i||(i=!!o.error);const c=o.error?0:o.duration||0;r+=c}s&&!i?e.duration=Math.max(r,e.duration):e.duration=r}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function Mi(t){return`[${t.event?'"'+t.event.identifier+'"':"primary"}: ${t.start.toFixed(2)}-${t.end.toFixed(2)}]`}class Bpe{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,n){const r=e.assetListUrl;let s;try{s=j4(r,this.hls.sessionId,e.baseUrl)}catch(h){const f=this.assignAssetListError(e,Se.ASSET_LIST_LOAD_ERROR,h,r);this.hls.trigger(B.ERROR,f);return}n&&s.protocol!=="data:"&&s.searchParams.set("_HLS_start_offset",""+n);const i=this.hls.config,a=i.loader,o=new a(i),l={responseType:"json",url:s.href},c=i.interstitialAssetListLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(h,f,m,g)=>{const y=h.data,v=y==null?void 0:y.ASSETS;if(!Array.isArray(v)){const _=this.assignAssetListError(e,Se.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),m.url,f,g);this.hls.trigger(B.ERROR,_);return}e.assetListResponse=y,this.hls.trigger(B.ASSET_LIST_LOADED,{event:e,assetListResponse:y,networkDetails:g})},onError:(h,f,m,g)=>{const y=this.assignAssetListError(e,Se.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${h.code} ${h.text} (${f.url})`),f.url,g,m);this.hls.trigger(B.ERROR,y)},onTimeout:(h,f,m)=>{const g=this.assignAssetListError(e,Se.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,h,m);this.hls.trigger(B.ERROR,g)}};return o.load(l,u,d),this.hls.trigger(B.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,n,r,s,i,a){return e.error=r,{type:ft.NETWORK_ERROR,details:n,fatal:!1,interstitial:e,url:s,error:r,networkDetails:a,stats:i}}}function ZD(t){var e;t==null||(e=t.play())==null||e.catch(()=>{})}function Ku(t,e){return`[${t}] Advancing timeline position to ${e}`}class Fpe extends Ii{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 s=r-this.timelinePos;if(Math.abs(s)<1/7056e5)return;const a=s<=-.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-s)&&this.updateSchedule(!0),this.checkBuffer(),a&&r<o.start||r>=o.end){var l;const f=this.findItemIndex(o);let m=this.schedule.findItemIndexAtTime(r);if(m===-1&&(m=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${r} (resolving from ${f} to ${m})`)),!this.isInterstitial(o)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=!1),!a&&m>f){const g=this.schedule.findJumpRestrictedIndex(f+1,m);if(g>f){this.setSchedulePosition(g);return}}this.setSchedulePosition(m);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 s=this.playingItem;if(!s||this.playingLastItem)return;if(r>=s.end){this.timelinePos=s.end;const o=this.findItemIndex(s);this.setSchedulePosition(o+1)}const i=this.playingAsset;if(!i)return;const a=i.timelineStart+(i.duration||0);r>=a&&this.setScheduleToAssetAtTime(r,i)},this.onScheduleUpdate=(r,s)=>{const i=this.schedule;if(!i)return;const a=this.playingItem,o=i.events||[],l=i.items||[],c=i.durations,u=r.map(g=>g.identifier),d=!!(o.length||u.length);(d||s)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
Schedule: ${l.map(g=>Mi(g))} 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 m=this.bufferingItem;if(m&&(f=this.updateItem(m,this.bufferedPos),this.itemsMatch(m,f)?this.bufferingItem=f:m.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(m.event,null))),r.forEach(g=>{g.assetList.forEach(y=>{this.clearAssetPlayer(y.identifier,null)})}),this.playerQueue.forEach(g=>{if(g.interstitial.appendInPlace){const y=g.assetItem.timelineStart,v=g.timelineOffset-y;if(v)try{g.timelineOffset=y}catch(_){Math.abs(v)>Bd&&this.warn(`${_} ("${g.assetId}" ${g.timelineOffset}->${y})`)}}}),d||s){if(this.hls.trigger(B.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),m&&f!==h&&this.trimInPlace(f,m),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=n,this.assetListLoader=new Bpe(e),this.schedule=new Upe(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(B.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(B.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(B.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(B.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(B.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(B.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(B.BUFFER_APPENDED,this.onBufferAppended,this),e.on(B.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(B.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(B.MEDIA_ENDED,this.onMediaEnded,this),e.on(B.ERROR,this.onError,this),e.on(B.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(B.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(B.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(B.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(B.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(B.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(B.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(B.BUFFER_CODECS,this.onBufferCodecs,this),e.off(B.BUFFER_APPENDED,this.onBufferAppended,this),e.off(B.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(B.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(B.MEDIA_ENDED,this.onMediaEnded,this),e.off(B.ERROR,this.onError,this),e.off(B.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){Ls(e,"play",this.onPlay),Ls(e,"pause",this.onPause),Ls(e,"seeking",this.onSeeking),Ls(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,n){const r=this.media=n.media;hs(r,"seeking",this.onSeeking),hs(r,"timeupdate",this.onTimeupdate),hs(r,"play",this.onPlay),hs(r,"pause",this.onPause)}onMediaAttached(e,n){const r=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,r===null)this.checkStart();else if(!s){this.clearScheduleState();const i=this.findItemIndex(r);this.setSchedulePosition(i)}}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,s=this.media;if(this.media=null,!r&&(s&&this.removeMediaListeners(s),this.detachedData)){const i=this.getBufferingPlayer();i&&(this.log(`Removing schedule state for detachedData and ${i}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,i.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),s=(d,h,f,m,g)=>{if(d){let y=d[h].start;const v=d.event;if(v){if(h==="playout"||v.timelineOccupancy!==J0.Point){const _=r(f);(_==null?void 0:_.interstitial)===v&&(y+=_.assetItem.startOffset+_[g])}}else{const _=m==="bufferedPos"?a():e[m];y+=_-d.start}return y}return 0},i=(d,h)=>{var f;if(d!==0&&h!=="primary"&&(f=e.schedule)!=null&&f.length){var m;const g=e.schedule.findItemIndexAtTime(d),y=(m=e.schedule.items)==null?void 0:m[g];if(y){const v=y[h].start-y.start;return d+v}}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,m;const g=e.effectivePlayingItem;if(g!=null&&(f=g.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${d} "${h}"`);const y=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(d,h),_=(m=e.schedule.items)==null?void 0:m[v],S=e.getBufferingPlayer(),E=S==null?void 0:S.interstitial,L=E==null?void 0:E.appendInPlace,U=y&&e.itemsMatch(y,_);if(y&&(L||U)){const P=r(e.playingAsset),I=(P==null?void 0:P.media)||e.primaryMedia;if(I){const k=h==="primary"?I.currentTime:s(y,h,e.playingAsset,"timelinePos","currentTime"),R=d-k,M=(L?k:I.currentTime)+R;if(M>=0&&(!P||L||M<=P.duration)){I.currentTime=M;return}}}if(_){let P=d;if(h!=="primary"){const k=_[h].start,R=d-k;P=_.start+R}const I=!e.isInterstitial(_);if((!e.isInterstitial(y)||y.event.appendInPlace)&&(I||_.event.appendInPlace)){const k=e.media||(L?S==null?void 0:S.media:null);k&&(k.currentTime=P)}else if(y){const k=e.findItemIndex(y);if(v>k){const M=e.schedule.findJumpRestrictedIndex(k+1,v);if(M>k){e.setSchedulePosition(M);return}}let R=0;if(I)e.timelinePos=P,e.checkBuffer();else{const M=_.event.assetList,G=d-(_[h]||_).start;for(let Y=M.length;Y--;){const q=M[Y];if(q.duration&&G>=q.startOffset&&G<q.startOffset+q.duration){R=Y;break}}}e.setSchedulePosition(v,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 s(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?s(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 s(n(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(d){l(d,"integrated")},get duration(){return o("integrated")},get seekableStart(){var d;return i(((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 m=d.playout.start+d.event.duration;l(m+.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 s=this.media;!s&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(s=this.primaryMedia);const i=(n=s)==null?void 0:n.currentTime;if(!(i===void 0||!tt(i)))return i}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,s=e.media;if(r&&s===this.primaryMedia){if(this.bufferingAsset=null,(!n||this.isInterstitial(n)&&!n.event.appendInPlace)&&n&&s){this.detachedData={media:s};return}const i=e.transferMedia();this.log(`transfer MediaSource from ${e} ${En(i)}`),this.detachedData=i}else n&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(e,n){var r,s;if(e.media===n)return;let i=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&&(i=a.transferMedia(),this.detachedData=i),u="Primary";else if(c){const m=this.getBufferingPlayer();m?(i=m.transferMedia(),u=`${m}`):u="detached MediaSource"}else u="detached media";if(!i){if(c)i=this.detachedData,this.log(`using detachedData: MediaSource ${En(i)}`);else if(!this.detachedData||a.media===n){const m=this.playerQueue;m.length>1&&m.forEach(g=>{if(o&&g.interstitial.appendInPlace!==l){const y=g.interstitial;this.clearInterstitial(g.interstitial,null),y.appendInPlace=!1,y.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${y}`)}}),this.hls.detachMedia(),this.detachedData={media:n}}}const d=i&&"mediaSource"in i&&((s=i.mediaSource)==null?void 0:s.readyState)!=="closed",h=d&&i?i:n;this.log(`${d?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${u} (media.currentTime: ${n.currentTime})`);const f=this.schedule;if(h===i&&f){const m=o&&e.assetId===f.assetIdAtEnd;h.overrides={duration:f.duration,endOfStream:!o||m,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,s=this.effectivePlayingItem;if(r===-1){const i=this.hls.startPosition;if(this.timelinePos=i,n.length===0)this.setSchedulePosition(0);else if(n[0].cue.pre){this.log(Ku("checkStart (preroll)",i));const a=e.findEventIndex(n[0].identifier);this.setSchedulePosition(a)}else if(i>=0||!this.primaryLive){this.log(Ku("checkStart",i));const a=this.timelinePos=i>0?i: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(s&&!this.playingItem){this.log(Ku("checkStart (playing item)",s.start));const i=e.findItemIndex(s);this.setSchedulePosition(i)}}advanceAssetBuffering(e,n){const r=e.event,s=r.findAssetIndex(n),i=Cx(r,s);if(!r.isAssetPastPlayoutLimit(i))this.bufferedToEvent(e,i);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 s=Cx(e,r);if(e.isAssetPastPlayoutLimit(s)){if(this.schedule){const i=this.schedule.items;if(i){const a=n+1,o=i.length;if(a>=o){this.setSchedulePosition(-1);return}const l=e.resumeTime;this.timelinePos<l&&(this.log(Ku("advanceAfterAssetEnded",l)),this.timelinePos=l,e.appendInPlace&&this.advanceInPlace(l),this.checkBuffer(this.bufferedPos<l)),this.setSchedulePosition(a)}}}else{if(e.appendInPlace){const i=e.assetList[s];i&&this.advanceInPlace(i.timelineStart)}this.setSchedulePosition(n,s)}}setScheduleToAssetAtTime(e,n){const r=this.schedule;if(!r)return;const s=n.parentIdentifier,i=r.getEvent(s);if(i){const a=r.findEventIndex(s),o=r.findAssetIndex(i,e);this.advanceAfterAssetEnded(i,a,o-1)}}setSchedulePosition(e,n){var r;const s=(r=this.schedule)==null?void 0:r.items;if(!s||this.playbackDisabled)return;const i=e>=0?s[e]:null;this.log(`setSchedulePosition ${e}, ${n} (${i&&Mi(i)}) 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,i)||n!==void 0&&h!==u.assetList[n].identifier)){var l;const m=u.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${m+1}/${u.assetList.length} ${nd(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(B.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:m,event:u,schedule:s.slice(0),scheduleIndex:e,player:f}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(u,this.findItemIndex(this.playingItem),m);return}this.retreiveMediaSource(h,i),f.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(a,i)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${u} ${Mi(a)}`),u.hasPlayed=!0,this.hls.trigger(B.INTERSTITIAL_ENDED,{event:u,schedule:s.slice(0),scheduleIndex:e}),u.cue.once)){var c;this.updateSchedule();const m=(c=this.schedule)==null?void 0:c.items;if(i&&m){const g=this.findItemIndex(i);this.advanceSchedule(g,m,n,a,o)}return}}this.advanceSchedule(e,s,n,a,o)}advanceSchedule(e,n,r,s,i){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 m=Cx(u,r-1);if(u.isAssetPastPlayoutLimit(m)||u.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(u,e,r);return}r=m}const d=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let h=this.preloadAssets(u,r);if(this.eventItemsMatch(o,d||s)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Mi(o)} ${u.appendInPlace?"append in place":""}`),this.hls.trigger(B.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 m=u.assetList.length;this.warn(`asset ${r+1}/${m} 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&&ZD(h.media)}else o?(this.resumePrimary(o,e,s),this.shouldPlay&&ZD(this.hls.media)):i&&this.isInterstitial(s)&&(this.endedItem=null,this.playingItem=s,s.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 s,i;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Mi(e)}`),!((s=this.detachedData)!=null&&s.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,n),this.log(Ku("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e)}if(!r)return;const a=(i=this.schedule)==null?void 0:i.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Mi(e)}`),this.hls.trigger(B.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:n}),this.checkBuffer())}getPrimaryResumption(e,n){const r=e.start;if(this.primaryLive){const s=this.primaryDetails;if(n===0)return this.hls.startPosition;if(s&&(r<s.fragmentStart||r>s.edge))return this.hls.liveSyncPosition||-1}return r}isAssetBuffered(e){const n=this.getAssetPlayer(e.identifier);return n!=null&&n.hls?n.hls.bufferedToEnd:Pt.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 s=this.primaryMedia;if(!s)return;const i=this.hls;i.media?this.checkBuffer():(this.transferMediaTo(i,s),r&&this.startLoadingPrimaryAt(e,r)),r||(this.log(Ku("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,r))}startLoadingPrimaryAt(e,n){var r;const s=this.hls;!s.loadingEnabled||!s.media||Math.abs((((r=s.mainForwardBufferInfo)==null?void 0:r.start)||s.media.currentTime)-e)>.5?s.startLoad(e,n):s.bufferingEnabled||s.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(B.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(B.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 s=hn(hn({},this.mediaSelection||this.altSelection),{},{main:r});this.mediaSelection=s,this.schedule.parseInterstitialDateRanges(s,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,n){const r=this.hls.audioTracks[n.id],s=this.mediaSelection;if(!s){this.altSelection=hn(hn({},this.altSelection),{},{audio:r});return}const i=hn(hn({},s),{},{audio:r});this.mediaSelection=i}onSubtitleTrackUpdated(e,n){const r=this.hls.subtitleTracks[n.id],s=this.mediaSelection;if(!s){this.altSelection=hn(hn({},this.altSelection),{},{subtitles:r});return}const i=hn(hn({},s),{},{subtitles:r});this.mediaSelection=i}onAudioTrackSwitching(e,n){const r=lD(n);this.playerQueue.forEach(({hls:s})=>s&&(s.setAudioOption(n)||s.setAudioOption(r)))}onSubtitleTrackSwitch(e,n){const r=lD(n);this.playerQueue.forEach(({hls:s})=>s&&(s.setSubtitleOption(n)||n.id!==-1&&s.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 s=this.timelinePos;this.bufferedPos=s,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const n=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&n){for(let s=0;s<n.length;s++){const i=n[s];if(i.cue.post){var r;const a=this.schedule.findEventIndex(i.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 s=(r=this.schedule)==null?void 0:r.items;if(e&&s){const i=this.findItemIndex(e,n);return s[i]||null}return null}trimInPlace(e,n){if(this.isInterstitial(e)&&e.event.appendInPlace&&n.end-e.end>.25){e.event.assetList.forEach((i,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(i.identifier,null)});const r=e.end+.25,s=Pt.bufferInfo(this.primaryMedia,r,0);(s.end>r||(s.nextStart||0)>r)&&(this.log(`trim buffered interstitial ${Mi(e)} (was ${Mi(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 s=Pt.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=s.len<1),this.updateBufferedPos(s.end,r,e)}updateBufferedPos(e,n,r){const s=this.schedule,i=this.bufferingItem;if(this.bufferedPos>e||!s)return;if(n.length===1&&this.itemsMatch(n[0],i)){this.bufferedPos=e;return}const a=this.playingItem,o=this.findItemIndex(a);let l=s.findItemIndexAtTime(e);if(this.bufferedPos<e){var c;const u=this.findItemIndex(i),d=Math.min(u+1,n.length-1),h=n[d];if((l===-1&&i&&e>=i.end||(c=h.event)!=null&&c.appendInPlace&&e+.01>=h.start)&&(l=d),this.isInterstitial(i)){const f=i.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,i)&&(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(s=>{const i=this.getAssetPlayer(s.identifier);return!(i!=null&&i.bufferedInPlaceToEnd(n))})}setBufferingItem(e){const n=this.bufferingItem,r=this.schedule;if(!this.itemsMatch(e,n)&&r){const{items:s,events:i}=r;if(!s||!i)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 ${Mi(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(B.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:i.slice(0),schedule:s.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 s=this.detachedData;s?s.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,s=r.assetList.length===0&&!r.assetListLoader,i=r.cue.once;if(s||!i){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,s=e.assetList.length,i=s===0&&!e.assetListLoader,a=e.cue.once;if(i){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:s} ${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&&s){for(let c=n;c<s;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(s=>{this.hls.trigger(B.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:s})})}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,s,i,a){const o={parentIdentifier:e.identifier,identifier:Ope(e,a,n),duration:i,startOffset:r,timelineStart:s,uri:a};return this.createAssetPlayer(e,o,n)}createAssetPlayer(e,n,r){const s=this.hls,i=s.userConfig;let a=i.videoPreference;const o=s.loadLevelObj||s.levels[s.currentLevel];(a||o)&&(a=vn({},a),o.videoCodec&&(a.videoCodec=o.videoCodec),o.videoRange&&(a.allowedVideoRanges=[o.videoRange]));const l=s.audioTracks[s.audioTrack],c=s.subtitleTracks[s.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=hn(hn({},i),{},{maxMaxBufferLength:Math.min(180,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:d,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:l||i.audioPreference,subtitlePreference:c||i.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,n.timelineStart&&(h.timelineOffset=n.timelineStart));const f=h.cmcd;f!=null&&f.sessionId&&f.contentId&&(h.cmcd=vn({},f,{contentId:rp(n.uri)})),this.getAssetPlayer(d)&&this.warn(`Duplicate date range identifier ${e} and asset ${d}`);const m=new jpe(this.HlsPlayerClass,h,e,n);this.playerQueue.push(m),e.assetList[r]=n;let g=!0;const y=E=>{if(E.live){var L;const I=new Error(`Interstitials MUST be VOD assets ${e}`),k={fatal:!0,type:ft.OTHER_ERROR,details:Se.INTERSTITIAL_ASSET_ITEM_ERROR,error:I},R=((L=this.schedule)==null?void 0:L.findEventIndex(e.identifier))||-1;this.handleAssetItemError(k,e,R,r,I.message);return}const U=E.edge-E.fragmentStart,P=n.duration;(g||P===null||U>P)&&(g=!1,this.log(`Interstitial asset "${d}" duration change ${P} > ${U}`),n.duration=U,this.updateSchedule())};m.on(B.LEVEL_UPDATED,(E,{details:L})=>y(L)),m.on(B.LEVEL_PTS_UPDATED,(E,{details:L})=>y(L)),m.on(B.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const v=(E,L)=>{const U=this.getAssetPlayer(d);if(U&&L.tracks){U.off(B.BUFFER_CODECS,v),U.tracks=L.tracks;const P=this.primaryMedia;this.bufferingAsset===U.assetItem&&P&&!U.media&&this.bufferAssetPlayer(U,P)}};m.on(B.BUFFER_CODECS,v);const _=()=>{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),P=(E=this.schedule.items)==null?void 0:E[U];this.isInterstitial(P)&&this.advanceAssetBuffering(P,n)};m.on(B.BUFFERED_TO_END,_);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 m.once(B.MEDIA_ENDED,S(r)),m.once(B.PLAYOUT_LIMIT_REACHED,S(1/0)),m.on(B.ERROR,(E,L)=>{if(!this.schedule)return;const U=this.getAssetPlayer(d);if(L.details===Se.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}`)}),m.on(B.DESTROYING,()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;const L=new Error(`Asset player destroyed unexpectedly ${d}`),U={fatal:!0,type:ft.OTHER_ERROR,details:Se.INTERSTITIAL_ASSET_ITEM_ERROR,error:L};this.handleAssetItemError(U,e,this.schedule.findEventIndex(e.identifier),r,L.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${nd(n)}`),this.hls.trigger(B.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:n,assetListIndex:r,event:e,player:m}),m}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 s=this.playerQueue[r];this.log(`clear ${s} toSegment: ${n&&Mi(n)}`),this.transferMediaFromPlayer(s,n),this.playerQueue.splice(r,1),s.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,n,r,s,i){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[s]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${n+1}/${c} ${nd(o)}`),this.hls.trigger(B.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:n,event:a,schedule:r.slice(0),scheduleIndex:s,player:e})),this.bufferAssetPlayer(e,i)}bufferAssetPlayer(e,n){var r,s;if(!this.schedule)return;const{interstitial:i,assetItem:a}=e,o=this.schedule.findEventIndex(i.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=i.appendInPlace;if(u&&(c==null?void 0:c.interstitial.appendInPlace)===!1)return;const d=(c==null?void 0:c.tracks)||((s=this.detachedData)==null?void 0:s.tracks)||this.requiredTracks;if(u&&a!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(d&&!_5(d,e.tracks)){const h=new Error(`Asset ${nd(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(d)}')`),f={fatal:!0,type:ft.OTHER_ERROR,details:Se.INTERSTITIAL_ASSET_ITEM_ERROR,error:h},m=i.findAssetIndex(a);this.handleAssetItemError(f,i,o,m,h.message);return}}this.transferMediaTo(e,n)}handleInPlaceStall(e){const n=this.schedule,r=this.primaryMedia;if(!n||!r)return;const s=r.currentTime,i=n.findAssetIndex(e,s),a=e.assetList[i];if(a){const o=this.getAssetPlayer(a.identifier);if(o){const l=o.currentTime||s-a.timelineStart,c=o.duration-l;if(this.warn(`Stalled at ${l} of ${l+c} in ${o} ${e} (media.currentTime: ${s})`),l&&(c/r.playbackRate<.5||o.bufferedInPlaceToEnd(r))&&o.hls){const u=n.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,u,i)}}}}advanceInPlace(e){const n=this.primaryMedia;n&&n.currentTime<e&&(n.currentTime=e)}handleAssetItemError(e,n,r,s,i){if(e.details===Se.BUFFER_STALLED_ERROR)return;const a=n.assetList[s]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&nd(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=vn({},e,{fatal:!1,errorAction:Md(!0),asset:a,assetListIndex:s,event:n,schedule:u,scheduleIndex:r,player:c});if(this.hls.trigger(B.INTERSTITIAL_ASSET_ERROR,d),!e.fatal)return;const h=this.playingAsset,f=this.bufferingAsset,m=new Error(i);if(a&&(this.clearAssetPlayer(o,null),a.error=m),!n.assetList.some(g=>!g.error))n.error=m;else for(let g=s;g<n.assetList.length;g++)this.resetAssetPlayer(n.assetList[g].identifier);this.updateSchedule(!0),n.error?this.primaryFallback(n):h&&h.identifier===o?this.advanceAfterAssetEnded(n,r,s):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){const n=e.timelineStart,r=this.effectivePlayingItem;let s=this.timelinePos;if(r){this.log(`Fallback to primary from event "${e.identifier}" start: ${n} pos: ${s} playing: ${Mi(r)} error: ${e.error}`),s===-1&&(s=this.hls.startPosition);const a=this.updateItem(r,s);this.itemsMatch(r,a)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(n,null),this.flushFrontBuffer(n))}else if(s===-1){this.checkStart();return}if(!this.schedule)return;const i=this.schedule.findItemIndexAtTime(s);this.setSchedulePosition(i)}onAssetListLoaded(e,n){var r,s;const i=n.event,a=i.identifier,o=n.assetListResponse.ASSETS;if(!((r=this.schedule)!=null&&r.hasEvent(a)))return;const l=i.timelineStart,c=i.duration;let u=0;o.forEach((g,y)=>{const v=parseFloat(g.DURATION);this.createAsset(i,y,u,l+u,v,g.URI),u+=v}),i.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${c}) ${i}`);const d=this.waitingItem,h=(d==null?void 0:d.event.identifier)===a;this.updateSchedule();const f=(s=this.bufferingItem)==null?void 0:s.event;if(h){var m;const g=this.schedule.findEventIndex(a),y=(m=this.schedule.items)==null?void 0:m[g];if(y){if(!this.playingItem&&this.timelinePos>y.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==g){i.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${i}`),this.log(i.error.message),this.updateSchedule(!0),this.primaryFallback(i);return}this.setBufferingItem(y)}this.setSchedulePosition(g)}else if((f==null?void 0:f.identifier)===a){const g=i.assetList[0];if(g){const y=this.getAssetPlayer(g.identifier);if(f.appendInPlace){const v=this.primaryMedia;y&&v&&this.bufferAssetPlayer(y,v)}else y&&y.loadSource()}}}onError(e,n){if(this.schedule)switch(n.details){case Se.ASSET_LIST_PARSING_ERROR:case Se.ASSET_LIST_LOAD_ERROR:case Se.ASSET_LIST_LOAD_TIMEOUT:{const r=n.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break}case Se.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 eO=500;class $pe extends kA{constructor(e,n,r){super(e,n,r,"subtitle-stream-controller",rt.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(B.LEVEL_LOADED,this.onLevelLoaded,this),e.on(B.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(B.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(B.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(B.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(B.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(B.LEVEL_LOADED,this.onLevelLoaded,this),e.off(B.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(B.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(B.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(B.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(B.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,n){this.stopLoad(),this.state=De.IDLE,this.setInterval(eO),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:s}=n;if(this.fragContextChanged(r)||(ar(r)&&(this.fragPrevious=r),this.state=De.IDLE),!s)return;const i=this.tracksBuffered[this.currentTrackId];if(!i)return;let a;const o=r.start;for(let c=0;c<i.length;c++)if(o>=i[c].start&&o<=i[c].end){a=i[c];break}const l=r.start+r.duration;a?a.end=l:(a={start:o,end:l},i.push(a)),this.fragmentTracker.fragBuffered(r),this.fragBufferedComplete(r,null),this.media&&this.tick()}onBufferFlushing(e,n){const{startOffset:r,endOffset:s}=n;if(r===0&&s!==Number.POSITIVE_INFINITY){const i=s-1;if(i<=0)return;n.endOffsetSubtitles=Math.max(0,i),this.tracksBuffered.forEach(a=>{for(let o=0;o<a.length;){if(a[o].end<=i){a.shift();continue}else if(a[o].start<i)a[o].start=i;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(r,i,rt.SUBTITLE)}}onError(e,n){const r=n.frag;(r==null?void 0:r.type)===rt.SUBTITLE&&(n.details===Se.FRAG_GAP&&this.fragmentTracker.fragBuffered(r,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==De.STOPPED&&(this.state=De.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:n}){if(this.levels&&S4(this.levels,n)){this.levels=n.map(r=>new Gp(r));return}this.tracksBuffered=[],this.levels=n.map(r=>{const s=new Gp(r);return this.tracksBuffered[s.id]=[],s}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,rt.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 s=this.levels[this.currentTrackId];s!=null&&s.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,s&&this.state!==De.STOPPED&&this.setInterval(eO)}onSubtitleTrackLoaded(e,n){var r;const{currentTrackId:s,levels:i}=this,{details:a,id:o}=n;if(!i){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const l=i[o];if(o>=i.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?(X0(a,d),c=a.fragmentStart):h&&(c=h.start,kw(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,kw(a,c))}d&&!this.startFragRequested&&this.setStartPosition(d,c)}l.details=a,this.levelLastLoaded=l,o===s&&(this.hls.trigger(B.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:n.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===De.IDLE&&(ou(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,s=n.decryptdata,i=this.hls;if(!this.fragContextChanged(n)&&r&&r.byteLength>0&&s!=null&&s.key&&s.iv&&jd(s.method)){const a=performance.now();this.decrypter.decrypt(new Uint8Array(r),s.key.buffer,s.iv.buffer,RA(s.method)).catch(o=>{throw i.trigger(B.ERROR,{type:ft.MEDIA_ERROR,details:Se.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:n}),o}).then(o=>{const l=performance.now();i.trigger(B.FRAG_DECRYPTED,{frag:n,payload:o,stats:{tstart:a,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=De.IDLE})}}doTick(){if(!this.media){this.state=De.IDLE;return}if(this.state===De.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:s}=this,i=this.getLoadPosition(),a=Pt.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],i,s.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 m=null;const g=this.fragPrevious;if(o<f){const _=s.maxFragLookUpTolerance,S=o>f-_?0:_;m=ou(g,d,Math.max(d[0].start,o),S),!m&&g&&g.start<d[0].start&&(m=d[0])}else m=d[h-1];if(m=this.filterReplacedPrimary(m,r.details),!m)return;const y=m.sn-c.startSN,v=d[y-1];if(v&&v.cc===m.cc&&this.fragmentTracker.getState(v)===xr.NOT_LOADED&&(m=v),this.fragmentTracker.getState(m)===xr.NOT_LOADED){const _=this.mapToInitFragWhenRequired(m);_&&this.loadFragment(_,r,o)}}}loadFragment(e,n,r){ar(e)?super.loadFragment(e,n,r):this._loadInitSegment(e,n)}get mediaBufferTimeRanges(){return new Vpe(this.tracksBuffered[this.currentTrackId]||[])}}class Vpe{constructor(e){this.buffered=void 0;const n=(r,s,i)=>{if(s=s>>>0,s>i-1)throw new DOMException(`Failed to execute '${r}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${i})`);return e[s][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 Gpe={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},U4=t=>String.fromCharCode(Gpe[t]||t),Bi=15,Ja=100,Kpe={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Hpe={17:2,18:4,21:6,22:8,23:10,19:13,20:15},zpe={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},qpe={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Wpe=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Ype{constructor(){this.time=null,this.verboseLevel=0}log(e,n){if(this.verboseLevel>=e){const r=typeof n=="function"?n():n;fn.log(`${this.time} [${e}] ${r}`)}}}const uc=function(e){const n=[];for(let r=0;r<e.length;r++)n.push(e[r].toString(16));return n};class B4{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 s=n[r];e.hasOwnProperty(s)&&(this[s]=e[s])}}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 Xpe{constructor(){this.uchar=" ",this.penState=new B4}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 Qpe{constructor(e){this.chars=[],this.pos=0,this.currPenState=new B4,this.cueStartTime=null,this.logger=void 0;for(let n=0;n<Ja;n++)this.chars.push(new Xpe);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=U4(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 s=this.chars[r].uchar;s!==" "&&(n=!1),e.push(s)}return n?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class kx{constructor(e){this.rows=[],this.currRow=Bi-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let n=0;n<Bi;n++)this.rows.push(new Qpe(e));this.logger=e}reset(){for(let e=0;e<Bi;e++)this.rows[e].clear();this.currRow=Bi-1}equals(e){let n=!0;for(let r=0;r<Bi;r++)if(!this.rows[r].equals(e.rows[r])){n=!1;break}return n}copy(e){for(let n=0;n<Bi;n++)this.rows[n].copy(e.rows[n])}isEmpty(){let e=!0;for(let n=0;n<Bi;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 = "+En(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<Bi;o++)this.rows[o].clear();const i=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[i].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[i+c])}}this.currRow=n;const r=this.rows[this.currRow];if(e.indent!==null){const i=e.indent,a=Math.max(i-1,0);r.setCursor(e.indent),e.color=r.chars[a].penState.foreground}const s={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+En(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="",s=-1;for(let i=0;i<Bi;i++){const a=this.rows[i].getTextString();a&&(s=i+1,e?n.push("Row "+s+": '"+a+"'"):n.push(a.trim()))}return n.length>0&&(e?r="["+n.join(" | ")+"]":r=n.join(`
`)),r}getTextAndFormat(){return this.rows}}class tO{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 kx(r),this.nonDisplayedMemory=new kx(r),this.lastOutputScreen=new kx(r),this.currRollUpRow=this.displayedMemory.rows[Bi-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[Bi-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,s=["white","green","blue","cyan","red","yellow","magenta"];n.foreground=s[r]}this.logger.log(2,"MIDROW: "+En(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 nO{constructor(e,n,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Zpe(),this.logger=void 0;const s=this.logger=new Ype;this.channels=[null,new tO(e,n,s),new tO(e+1,r,s)]}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 s=n[r]&127,i=n[r+1]&127;let a=!1,o=null;if(s===0&&i===0)continue;this.logger.log(3,()=>"["+uc([n[r],n[r+1]])+"] -> ("+uc([s,i])+")");const l=this.cmdHistory;if(s>=16&&s<=31){if(Jpe(s,i,l)){qg(null,null,l),this.logger.log(3,()=>"Repeated command ("+uc([s,i])+") is dropped");continue}qg(s,i,this.cmdHistory),a=this.parseCmd(s,i),a||(a=this.parseMidrow(s,i)),a||(a=this.parsePAC(s,i)),a||(a=this.parseBackgroundAttributes(s,i))}else qg(null,null,l);if(!a&&(o=this.parseChars(s,i),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 "+uc([s,i])+" orig: "+uc([n[r],n[r+1]]))}}parseCmd(e,n){const r=(e===20||e===28||e===21||e===29)&&n>=32&&n<=47,s=(e===23||e===31)&&n>=33&&n<=35;if(!(r||s))return!1;const i=e===20||e===21||e===23?1:2,a=this.channels[i];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=i,!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 s=this.channels[r];return s?(s.ccMIDROW(n),this.logger.log(3,()=>"MIDROW ("+uc([e,n])+")"),!0):!1}return!1}parsePAC(e,n){let r;const s=(e>=17&&e<=23||e>=25&&e<=31)&&n>=64&&n<=127,i=(e===16||e===24)&&n>=64&&n<=95;if(!(s||i))return!1;const a=e<=23?1:2;n>=64&&n<=95?r=a===1?Kpe[e]:zpe[e]:r=a===1?Hpe[e]:qpe[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 s={color:null,italics:!1,indent:null,underline:!1,row:e};return n>95?r=n-96:r=n-64,s.underline=(r&1)===1,r<=13?s.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(s.italics=!0,s.color="white"):s.indent=Math.floor((r-16)/2)*4,s}parseChars(e,n){let r,s=null,i=null;if(e>=25?(r=2,i=e-8):(r=1,i=e),i>=17&&i<=19){let a;i===17?a=n+80:i===18?a=n+112:a=n+144,this.logger.log(2,()=>"Special char '"+U4(a)+"' in channel "+r),s=[a]}else e>=32&&e<=127&&(s=n===0?[e]:[e,n]);return s&&this.logger.log(3,()=>"Char codes =  "+uc(s).join(",")),s}parseBackgroundAttributes(e,n){const r=(e===16||e===24)&&n>=32&&n<=47,s=(e===23||e===31)&&n>=45&&n<=47;if(!(r||s))return!1;let i;const a={};e===16||e===24?(i=Math.floor((n-32)/2),a.background=Wpe[i],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()}qg(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 qg(t,e,n){n.a=t,n.b=e}function Jpe(t,e,n){return n.a===t&&n.b===e}function Zpe(){return{a:null,b:null}}var $A=function(){if(Y0!=null&&Y0.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 s(o){return n(e,o)}function i(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,m=o,g=l,y=c,v=null,_="",S=!0,E="auto",L="start",U=50,P="middle",I=50,k="middle";Object.defineProperty(u,"id",i({},d,{get:function(){return h},set:function(R){h=""+R}})),Object.defineProperty(u,"pauseOnExit",i({},d,{get:function(){return f},set:function(R){f=!!R}})),Object.defineProperty(u,"startTime",i({},d,{get:function(){return m},set:function(R){if(typeof R!="number")throw new TypeError("Start time must be set to a number.");m=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"endTime",i({},d,{get:function(){return g},set:function(R){if(typeof R!="number")throw new TypeError("End time must be set to a number.");g=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"text",i({},d,{get:function(){return y},set:function(R){y=""+R,this.hasBeenReset=!0}})),Object.defineProperty(u,"region",i({},d,{get:function(){return v},set:function(R){v=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"vertical",i({},d,{get:function(){return _},set:function(R){const M=r(R);if(M===!1)throw new SyntaxError("An invalid or illegal string was specified.");_=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"snapToLines",i({},d,{get:function(){return S},set:function(R){S=!!R,this.hasBeenReset=!0}})),Object.defineProperty(u,"line",i({},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",i({},d,{get:function(){return L},set:function(R){const M=s(R);if(!M)throw new SyntaxError("An invalid or illegal string was specified.");L=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"position",i({},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",i({},d,{get:function(){return P},set:function(R){const M=s(R);if(!M)throw new SyntaxError("An invalid or illegal string was specified.");P=M,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",i({},d,{get:function(){return I},set:function(R){if(R<0||R>100)throw new Error("Size must be between 0 and 100.");I=R,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",i({},d,{get:function(){return k},set:function(R){const M=s(R);if(!M)throw new SyntaxError("An invalid or illegal string was specified.");k=M,this.hasBeenReset=!0}})),u.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}();class eme{decode(e,n){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function F4(t){function e(r,s,i,a){return(r|0)*3600+(s|0)*60+(i|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 tme{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 s=0;s<r.length;++s)if(n===r[s]){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 $4(t,e,n,r){const s=r?t.split(r):[t];for(const i in s){if(typeof s[i]!="string")continue;const a=s[i].split(n);if(a.length!==2)continue;const o=a[0],l=a[1];e(o,l)}}const jw=new $A(0,0,""),Wg=jw.align==="middle"?"middle":"center";function nme(t,e,n){const r=t;function s(){const o=F4(t);if(o===null)throw new Error("Malformed timestamp: "+r);return t=t.replace(/^[^\sa-zA-Z-]+/,""),o}function i(o,l){const c=new tme;$4(o,function(h,f){let m;switch(h){case"region":for(let g=n.length-1;g>=0;g--)if(n[g].id===f){c.set(h,n[g].region);break}break;case"vertical":c.alt(h,f,["rl","lr"]);break;case"line":m=f.split(","),c.integer(h,m[0]),c.percent(h,m[0])&&c.set("snapToLines",!1),c.alt(h,m[0],["auto"]),m.length===2&&c.alt("lineAlign",m[1],["start",Wg,"end"]);break;case"position":m=f.split(","),c.percent(h,m[0]),m.length===2&&c.alt("positionAlign",m[1],["start",Wg,"end","line-left","line-right","auto"]);break;case"size":c.percent(h,f);break;case"align":c.alt(h,f,["start",Wg,"end","left","right"]);break}},/:/,/\s/),l.region=c.get("region",null),l.vertical=c.get("vertical","");let u=c.get("line","auto");u==="auto"&&jw.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",Wg);let d=c.get("position","auto");d==="auto"&&jw.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=s(),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=s(),a(),i(t,e)}function V4(t){return t.replace(/<br(?: \/)?>/gi,`
`)}class rme{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new eme,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 i=n.buffer,a=0;for(i=V4(i);a<i.length&&i[a]!=="\r"&&i[a]!==`
`;)++a;const o=i.slice(0,a);return i[a]==="\r"&&++a,i[a]===`
`&&++a,n.buffer=i.slice(a),o}function s(i){$4(i,function(a,o){},/:/)}try{let i="";if(n.state==="INITIAL"){if(!/\r\n|\n/.test(n.buffer))return this;i=r();const o=i.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:i=r(),n.state){case"HEADER":/:/.test(i)?s(i):i||(n.state="ID");continue;case"NOTE":i||(n.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(i)){n.state="NOTE";break}if(!i)continue;if(n.cue=new $A(0,0,""),n.state="CUE",i.indexOf("-->")===-1){n.cue.id=i;continue}case"CUE":if(!n.cue){n.state="BADCUE";continue}try{nme(i,n.cue,n.regionList)}catch{n.cue=null,n.state="BADCUE";continue}n.state="CUETEXT";continue;case"CUETEXT":{const o=i.indexOf("-->")!==-1;if(!i||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+=i}continue;case"BADCUE":i||(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 sme=/\r\n|\n\r|\n|\r/g,Lx=function(e,n,r=0){return e.slice(r,r+n.length)===n},ime=function(e){let n=parseInt(e.slice(-3));const r=parseInt(e.slice(-6,-4)),s=parseInt(e.slice(-9,-7)),i=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!tt(n)||!tt(r)||!tt(s)||!tt(i))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return n+=1e3*r,n+=60*1e3*s,n+=60*60*1e3*i,n};function VA(t,e,n){return rp(t.toString())+rp(e.toString())+rp(n)}const ame=function(e,n,r){let s=e[n],i=e[s.prevCC];if(!i||!i.new&&s.new){e.ccOffset=e.presentationOffset=s.start,s.new=!1;return}for(;(a=i)!=null&&a.new;){var a;e.ccOffset+=s.start-i.start,s.new=!1,s=i,i=e[s.prevCC]}e.presentationOffset=r};function ome(t,e,n,r,s,i,a){const o=new rme,l=ti(new Uint8Array(t)).trim().replace(sme,`
`).split(`
`),c=[],u=e?ffe(e.baseTime,e.timescale):0;let d="00:00.000",h=0,f=0,m,g=!0;o.oncue=function(y){const v=n[r];let _=n.ccOffset;const S=(h-u)/9e4;if(v!=null&&v.new&&(f!==void 0?_=n.ccOffset=v.start:ame(n,r,S)),S){if(!e){m=new Error("Missing initPTS for VTT MPEGTS");return}_=S-n.presentationOffset}const E=y.endTime-y.startTime,L=Fs((y.startTime+_-f)*9e4,s*9e4)/9e4;y.startTime=Math.max(L,0),y.endTime=Math.max(L+E,0);const U=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(U)),y.id||(y.id=VA(y.startTime,y.endTime,U)),y.endTime>0&&c.push(y)},o.onparsingerror=function(y){m=y},o.onflush=function(){if(m){a(m);return}i(c)},l.forEach(y=>{if(g)if(Lx(y,"X-TIMESTAMP-MAP=")){g=!1,y.slice(16).split(",").forEach(v=>{Lx(v,"LOCAL:")?d=v.slice(6):Lx(v,"MPEGTS:")&&(h=parseInt(v.slice(7)))});try{f=ime(d)/1e3}catch(v){m=v}return}else y===""&&(g=!1);o.parse(y+`
`)}),o.flush()}const Ix="stpp.ttml.im1t",G4=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,K4=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,lme={left:"start",center:"center",right:"end",start:"start",end:"end"};function rO(t,e,n,r){const s=Ft(new Uint8Array(t),["mdat"]);if(s.length===0){r(new Error("Could not parse IMSC1 mdat"));return}const i=s.map(o=>ti(o)),a=hfe(e.baseTime,1,e.timescale);try{i.forEach(o=>n(cme(o,a)))}catch(o){r(o)}}function cme(t,e){const s=new DOMParser().parseFromString(t,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(i).reduce((d,h)=>(d[h]=s.getAttribute(`ttp:${h}`)||i[h],d),{}),o=s.getAttribute("xml:space")!=="preserve",l=sO(Px(s,"styling","style")),c=sO(Px(s,"layout","region")),u=Px(s,"body","[begin]");return[].map.call(u,d=>{const h=H4(d,o);if(!h||!d.hasAttribute("begin"))return null;const f=Ox(d.getAttribute("begin"),a),m=Ox(d.getAttribute("dur"),a);let g=Ox(d.getAttribute("end"),a);if(f===null)throw iO(d);if(g===null){if(m===null)throw iO(d);g=f+m}const y=new $A(f-e,g-e,h);y.id=VA(y.startTime,y.endTime,y.text);const v=c[d.getAttribute("region")],_=l[d.getAttribute("style")],S=ume(v,_,l),{textAlign:E}=S;if(E){const L=lme[E];L&&(y.lineAlign=L),y.align=E}return vn(y,S),y}).filter(d=>d!==null)}function Px(t,e,n){const r=t.getElementsByTagName(e)[0];return r?[].slice.call(r.querySelectorAll(n)):[]}function sO(t){return t.reduce((e,n)=>{const r=n.getAttribute("xml:id");return r&&(e[r]=n),e},{})}function H4(t,e){return[].slice.call(t.childNodes).reduce((n,r,s)=>{var i;return r.nodeName==="br"&&s?n+`
`:(i=r.childNodes)!=null&&i.length?H4(r,e):e?n+r.textContent.trim().replace(/\s+/g," "):n+r.textContent},"")}function ume(t,e,n){const r="http://www.w3.org/ns/ttml#styling";let s=null;const i=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=t!=null&&t.hasAttribute("style")?t.getAttribute("style"):null;return a&&n.hasOwnProperty(a)&&(s=n[a]),i.reduce((o,l)=>{const c=Dx(e,r,l)||Dx(t,r,l)||Dx(s,r,l);return c&&(o[l]=c),o},{})}function Dx(t,e,n){return t&&t.hasAttributeNS(e,n)?t.getAttributeNS(e,n):null}function iO(t){return new Error(`Could not parse ttml timestamp ${t}`)}function Ox(t,e){if(!t)return null;let n=F4(t);return n===null&&(G4.test(t)?n=dme(t,e):K4.test(t)&&(n=hme(t,e))),n}function dme(t,e){const n=G4.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 hme(t,e){const n=K4.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 Yg{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 fme{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=oO(),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(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(B.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(B.FRAG_LOADING,this.onFragLoading,this),e.on(B.FRAG_LOADED,this.onFragLoaded,this),e.on(B.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(B.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(B.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(B.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(B.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(B.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(B.FRAG_LOADING,this.onFragLoading,this),e.off(B.FRAG_LOADED,this.onFragLoaded,this),e.off(B.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(B.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(B.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(B.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(B.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new Yg(this,"textTrack1"),n=new Yg(this,"textTrack2"),r=new Yg(this,"textTrack3"),s=new Yg(this,"textTrack4");this.cea608Parser1=new nO(1,e,n),this.cea608Parser2=new nO(3,r,s)}addCues(e,n,r,s,i){let a=!1;for(let o=i.length;o--;){const l=i[o],c=pme(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||i.push([n,r]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,n,r,s)}else{const o=this.Cues.newCue(null,n,r,s);this.hls.trigger(B.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:n,id:r,initPTS:s,timescale:i,trackId:a}){const{unparsedVttFrags:o}=this;r===rt.MAIN&&(this.initPTS[n.cc]={baseTime:s,timescale:i,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(l=>{this.initPTS[l.frag.cc]?this.onFragLoaded(B.FRAG_LOADED,l):this.hls.trigger(B.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 s=0;s<r.textTracks.length;s++){const i=r.textTracks[s];if(aO(i,{name:e,lang:n,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return i}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:s}=this,{label:i,languageCode:a}=n[e],o=this.getExistingTrack(i,a);if(o)r[e]=o,bd(r[e]),N4(r[e],s);else{const l=this.createTextTrack("captions",i,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,s={_id:e,label:r,kind:"captions",default:n.media?!!n.media.default:!1,closedCaptions:n.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(B.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(e,n,r){const s=this.media;if(s)return s.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:s}=this;Object.keys(s).forEach(i=>{bd(s[i]),delete s[i]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=oO(),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++)bd(n[r])}onSubtitleTracksUpdated(e,n){const r=n.subtitleTracks||[],s=r.some(i=>i.textCodec===Ix);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(S4(this.tracks,r)){this.tracks=r;return}if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){const a=this.media,o=a?Oy(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]&&aO(o[h],l)){d=o[h],o[h]=null;break}d&&(u=d)}if(u)bd(u);else{const d=z4(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(B.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,n){this.config.enableCEA708Captions&&n.captions&&n.captions.forEach(r=>{const s=/(?:CC|SERVICE)([1-4])/.exec(r.instreamId);if(!s)return;const i=`textTrack${s[1]}`,a=this.captionsProperties[i];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===rt.MAIN){var r,s;const{cea608Parser1:i,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:c}=n.frag,u=(r=(s=n.part)==null?void 0:s.index)!=null?r:-1;i&&a&&(c!==o+1||c===o&&u!==this.lastPartIndex+1||l!==this.lastCc)&&(i.reset(),a.reset()),this.lastCc=l,this.lastSn=c,this.lastPartIndex=u}}onFragLoaded(e,n){const{frag:r,payload:s}=n;if(r.type===rt.SUBTITLE)if(s.byteLength){const i=r.decryptdata,a="stats"in n;if(i==null||!i.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===Ix?this._parseIMSC1(r,s):this._parseVTTs(n)}}else this.hls.trigger(B.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,n){const r=this.hls;rO(n,this.initPTS[e.cc],s=>{this._appendCues(s,e.level),r.trigger(B.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},s=>{r.logger.log(`Failed to parse IMSC1: ${s}`),r.trigger(B.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:s})})}_parseVTTs(e){var n;const{frag:r,payload:s}=e,{initPTS:i,unparsedVttFrags:a}=this,o=i.length-1;if(!i[r.cc]&&o===-1){a.push(e);return}const l=this.hls,c=(n=r.initSegment)!=null&&n.data?ki(r.initSegment.data,new Uint8Array(s)).buffer:s;ome(c,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,u=>{this._appendCues(u,r.level),l.trigger(B.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})},u=>{const d=u.message==="Missing initPTS for VTT MPEGTS";d?a.push(e):this._fallbackToIMSC1(r,s),l.logger.log(`Failed to parse VTT cue: ${u}`),!(d&&o>r.cc)&&l.trigger(B.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:u})})}_fallbackToIMSC1(e,n){const r=this.tracks[e.level];r.textCodec||rO(n,this.initPTS[e.cc],()=>{r.textCodec=Ix,this._parseIMSC1(e,n)},()=>{r.textCodec="wvtt"})}_appendCues(e,n){const r=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[n];if(!s||s.mode==="disabled")return;e.forEach(i=>M4(s,i))}else{const s=this.tracks[n];if(!s)return;const i=s.default?"default":"subtitles"+n;r.trigger(B.CUES_PARSED,{type:"subtitles",cues:e,track:i})}}onFragDecrypted(e,n){const{frag:r}=n;r.type===rt.SUBTITLE&&this.onFragLoaded(B.FRAG_LOADED,n)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,n){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:r,samples:s}=n;if(!(r.type===rt.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let i=0;i<s.length;i++){const a=s[i].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(a);this.cea608Parser1.addData(s[i].pts,o[0]),this.cea608Parser2.addData(s[i].pts,o[1])}}}onBufferFlushing(e,{startOffset:n,endOffset:r,endOffsetSubtitles:s,type:i}){const{media:a}=this;if(!(!a||a.currentTime<r)){if(!i||i==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(l=>Mw(o[l],n,r))}if(this.config.renderTextTracksNatively&&n===0&&s!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(l=>Mw(o[l],n,s))}}}extractCea608Data(e){const n=[[],[]],r=e[0]&31;let s=2;for(let i=0;i<r;i++){const a=e[s++],o=127&e[s++],l=127&e[s++];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 z4(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function aO(t,e){return!!t&&t.kind===z4(e)&&Pw(e,t)}function pme(t,e,n,r){return Math.min(e,r)-Math.max(t,n)}function oO(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const mme=/\s/,gme={newCue(t,e,n,r){const s=[];let i,a,o,l,c;const u=self.VTTCue||self.TextTrackCue;for(let h=0;h<r.rows.length;h++)if(i=r.rows[h],o=!0,l=0,c="",!i.isEmpty()){var d;for(let g=0;g<i.chars.length;g++)mme.test(i.chars[g].uchar)&&o?l++:(c+=i.chars[g].uchar,o=!1);i.cueStartTime=e,e===n&&(n+=1e-4),l>=16?l--:l++;const f=V4(c.trim()),m=VA(e,n,f);t!=null&&(d=t.cues)!=null&&d.getCueById(m)||(a=new u(e,n,f),a.id=m,a.line=h+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),s.push(a))}return t&&s.length&&(s.sort((h,f)=>h.line==="auto"||f.line==="auto"?0:h.line>8&&f.line>8?f.line-h.line:h.line-f.line),s.forEach(h=>M4(t,h))),s}};function yme(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const vme=/(\d+)-(\d+)\/(\d+)/;class lO{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||Sme,this.controller=new self.AbortController,this.stats=new bA}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 s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();const i=_me(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,i),self.clearTimeout(this.requestTimeout),n.timeout=l&&tt(l)?l:c,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},n.timeout),(zp(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(),s.loading.start);if(self.clearTimeout(this.requestTimeout),n.timeout=c,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},c-(f-s.loading.start)),!d.ok){const{status:g,statusText:y}=d;throw new Eme(y||"fetch, bad network response",g,d)}s.loading.first=f,s.total=xme(d.headers)||s.total;const m=(h=this.callbacks)==null?void 0:h.onProgress;return m&&tt(n.highWaterMark)?this.loadProgressively(d,s,e,n.highWaterMark,m):a?d.arrayBuffer():e.responseType==="json"?d.json():d.text()}).then(d=>{var h,f;const m=this.response;if(!m)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const g=d[o];g&&(s.loaded=s.total=g);const y={url:m.url,data:d,code:m.status},v=(h=this.callbacks)==null?void 0:h.onProgress;v&&!tt(n.highWaterMark)&&v(s,e,d,m),(f=this.callbacks)==null||f.onSuccess(y,s,e,m)}).catch(d=>{var h;if(self.clearTimeout(this.requestTimeout),s.aborted)return;const f=d&&d.code||0,m=d?d.message:null;(h=this.callbacks)==null||h.onError({code:f,text:m},e,d?d.details:null,s)})}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,s=0,i){const a=new n4,o=e.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return a.dataLength&&i(n,r,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const u=c.value,d=u.length;return n.loaded+=d,d<s||a.dataLength?(a.push(u),a.dataLength>=s&&i(n,r,a.flush().buffer,e)):i(n,r,u.buffer,e),l()}).catch(()=>Promise.reject());return l()}}function _me(t,e){const n={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(vn({},t.headers))};return t.rangeEnd&&n.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)),n}function bme(t){const e=vme.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}function xme(t){const e=t.get("Content-Range");if(e){const r=bme(e);if(tt(r))return r}const n=t.get("Content-Length");if(n)return parseInt(n)}function Sme(t,e){return new self.Request(t.url,e)}class Eme extends Error{constructor(e,n,r){super(e),this.code=void 0,this.details=void 0,this.code=n,this.details=r}}const wme=/^age:\s*[\d.]+\s*$/im;class q4{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 bA,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,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;const i=this.xhrSetup;i?Promise.resolve().then(()=>{if(!(this.loader!==r||this.stats.aborted))return i(r,n.url)}).catch(a=>{if(!(this.loader!==r||this.stats.aborted))return r.open("GET",n.url,!0),i(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,s)}):this.openAndSendXhr(r,n,e)}openAndSendXhr(e,n,r){e.readyState||e.open("GET",n.url,!0);const s=n.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:a}=r.loadPolicy;if(s)for(const o in s)e.setRequestHeader(o,s[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=i&&tt(i)?i: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 s=n.readyState,i=this.config;if(!r.aborted&&s>=2&&(r.loading.first===0&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),s===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 m=u??n.response;if(m!=null){var a,o;r.loading.end=Math.max(self.performance.now(),r.loading.first);const g=n.responseType==="arraybuffer"?m.byteLength:m.length;r.loaded=r.total=g,r.bwEstimate=r.total*8e3/(r.loading.end-r.loading.first);const y=(a=this.callbacks)==null?void 0:a.onProgress;y&&y(r,e,m,n);const v={url:n.responseURL,data:m,code:c};(o=this.callbacks)==null||o.onSuccess(v,r,e,n);return}}const d=i.loadPolicy.errorRetry,h=r.retry,f={url:e.url,data:void 0,code:c};if(q0(d,h,!1,f))this.retry(d);else{var l;fn.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(q0(e,n,!0))this.retry(e);else{var r;fn.warn(`timeout while loading ${(r=this.context)==null?void 0:r.url}`);const s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:n,stats:r}=this;this.retryDelay=wA(e,r.retry),r.retry++,fn.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&&wme.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 Tme={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Ame=hn(hn({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:q4,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Ude,bufferController:Cfe,capLevelController:UA,errorController:Gde,fpsController:kpe,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:H5,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:Tme},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},Rme()),{},{subtitleStreamController:$pe,subtitleTrackController:Ppe,timelineController:fme,audioStreamController:wfe,audioTrackController:Tfe,emeController:Ud,cmcdController:Tpe,contentSteeringController:Rpe,interstitialsController:Fpe});function Rme(){return{cueHandler:gme,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 Cme(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=Uw(t),s=["manifest","level","frag"],i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return s.forEach(a=>{const o=`${a==="level"?"playlist":a}LoadPolicy`,l=e[o]===void 0,c=[];i.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}": ${En(e[o])}`)}),hn(hn({},r),e)}function Uw(t){return t&&typeof t=="object"?Array.isArray(t)?t.map(Uw):Object.keys(t).reduce((e,n)=>(e[n]=Uw(t[n]),e),{}):t}function kme(t,e){const n=t.loader;n!==lO&&n!==q4?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):yme()&&(t.loader=lO,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const Ny=2,Lme=.1,Ime=.05,Pme=100;class Dme extends F5{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(B.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=n,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(B.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.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(Pme),this.mediaSource=n.mediaSource;const r=this.media=n.media;hs(r,"playing",this.onMediaPlaying),hs(r,"waiting",this.onMediaWaiting),hs(r,"ended",this.onMediaEnded)}onMediaDetaching(e,n){this.clearInterval();const{media:r}=this;r&&(Ls(r,"playing",this.onMediaPlaying),Ls(r,"waiting",this.onMediaWaiting),Ls(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,s;const i=(r=this.hls)==null?void 0:r.config;if(!i)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,i.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(B.MEDIA_ENDED,{stalled:!1}));return}if(!Pt.getBuffered(a).length){this.nudgeRetry=0;return}const d=Pt.bufferInfo(a,e,0),h=d.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){const U=cO(this.hls.inFlightFragments,e),P=d.len>Ny,I=!h||U||h-e>Ny&&!f.getPartialFragment(e);if(P||I)return;this.moved=!1}const m=(s=this.hls)==null?void 0:s.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(d.len>0)&&!h)return;const P=Math.max(h,d.start||0)-e,k=!!(m!=null&&m.live)?m.targetduration*2:Ny,R=Xg(e,f);if(P>0&&(P<=k||R)){a.paused||this._trySkipBufferHole(R);return}}const g=i.detectStallWithCurrentTimeMs,y=self.performance.now(),v=this.waiting;let _=this.stalled;if(_===null)if(v>0&&y-v<g)_=this.stalled=v;else{this.stalled=y;return}const S=y-_;if(!o&&(S>=g||v)&&this.hls){var E;if(((E=this.mediaSource)==null?void 0:E.readyState)==="ended"&&!(m!=null&&m.live)&&Math.abs(e-((m==null?void 0:m.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(B.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(d),!this.media||!this.hls)return}const L=Pt.bufferInfo(a,e,i.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(B.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,n){var r;const s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(r=this.buffered.audio)!=null&&r.length&&s&&s.length>1&&e>s.end(0)){const i=Pt.bufferedInfo(Pt.timeRangesToArray(this.buffered.audio),e,0);if(i.len>1&&n>=i.start){const a=Pt.timeRangesToArray(s),o=Pt.bufferedInfo(a,n,0).bufferedIndex;if(o>-1&&o<a.length-1){const l=Pt.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=Xg(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);const f=Pt.bufferInfo(this.media,e,0);this.hls.trigger(B.ERROR,{type:ft.MEDIA_ERROR,details:Se.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:h,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,n,r){var s,i;const{fragmentTracker:a,media:o}=this,l=(s=this.hls)==null?void 0:s.config;if(!o||!a||!l)return;const c=(i=this.hls)==null?void 0:i.latestLevelDetails,u=Xg(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,s=e.nextStart;if(r&&s){const i=r.getFragAtPos(n,rt.MAIN),a=r.getFragAtPos(s,rt.MAIN);if(i&&a)return a.sn-i.sn<2}return!1}_reportStall(e){const{hls:n,media:r,stallReported:s,stalled:i}=this;if(!s&&i!==null&&r&&n){this.stallReported=!0;const a=new Error(`Playback stalling at @${r.currentTime} due to low buffer (${En(e)})`);this.warn(a.message),n.trigger(B.ERROR,{type:ft.MEDIA_ERROR,details:Se.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:i}})}}_trySkipBufferHole(e){var n;const{fragmentTracker:r,media:s}=this,i=(n=this.hls)==null?void 0:n.config;if(!s||!r||!i)return 0;const a=s.currentTime,o=Pt.bufferInfo(s,a,0),l=a<o.start?o.start:o.nextStart;if(l&&this.hls){const u=o.len<=i.maxBufferHole,d=o.len>0&&o.len<1&&s.readyState<3,h=l-a;if(h>0&&(u||d)){if(h>i.maxBufferHole){let m=!1;if(a===0){const g=r.getAppendedFrag(0,rt.MAIN);g&&l<g.end&&(m=!0)}if(!m&&e){var c;if(!((c=this.hls.loadLevelObj)!=null&&c.details)||cO(this.hls.inFlightFragments,l))return 0;let y=!1,v=e.end;for(;v<l;){const _=Xg(v,r);if(_)v+=_.duration;else{y=!0;break}}if(y)return 0}}const f=Math.max(l+Ime,a+Lme);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`),this.moved=!0,s.currentTime=f,!(e!=null&&e.gap)){const m=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`),g={type:ft.MEDIA_ERROR,details:Se.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:m,reason:m.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?g.part=e:g.frag=e),this.hls.trigger(B.ERROR,g)}return f}}return 0}_tryNudgeBuffer(e){const{hls:n,media:r,nudgeRetry:s}=this,i=n==null?void 0:n.config;if(!r||!i)return 0;const a=r.currentTime;if(this.nudgeRetry++,s<i.nudgeMaxRetry){const o=a+(s+1)*i.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(l.message),r.currentTime=o,n.trigger(B.ERROR,{type:ft.MEDIA_ERROR,details:Se.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 ${i.nudgeMaxRetry} nudges`);this.error(o.message),n.trigger(B.ERROR,{type:ft.MEDIA_ERROR,details:Se.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function cO(t,e){const n=uO(t.main);if(n&&n.start<=e)return n;const r=uO(t.audio);return r&&r.start<=e?r:null}function uO(t){if(!t)return null;switch(t.state){case De.IDLE:case De.STOPPED:case De.ENDED:case De.ERROR:return null}return t.frag}function Xg(t,e){return e.getAppendedFrag(t,rt.MAIN)||e.getPartialFragment(t)}const Ome=.25;function Bw(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Nx(t,e,n,r,s){let i=new t(e,n,"");try{i.value=r,s&&(i.type=s)}catch{i=new t(e,n,En(s?hn({type:s},r):r))}return i}const Qg=(()=>{const t=Bw();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Nme{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(B.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(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(B.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(B.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(B.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(B.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(B.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&&bd(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 N4(r,this.media),r}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,n){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:r,enableID3MetadataCues:s}=this.hls.config;if(!r&&!s)return;const{samples:i}=n;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=Bw();if(a)for(let o=0;o<i.length;o++){const l=i[o].type;if(l===Hs.emsg&&!r||!s)continue;const c=c4(i[o].data),u=i[o].pts;let d=u+i[o].duration;d>Qg&&(d=Qg),d-u<=0&&(d=u+Ome);for(let f=0;f<c.length;f++){const m=c[f];if(!u4(m)){this.updateId3CueEnds(u,l);const g=Nx(a,u,d,m,l);g&&this.id3Track.addCue(g)}}}}updateId3CueEnds(e,n){var r;const s=(r=this.id3Track)==null?void 0:r.cues;if(s)for(let i=s.length;i--;){const a=s[i];a.type===n&&a.startTime<e&&a.endTime===Qg&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:n,endOffset:r,type:s}){const{id3Track:i,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(i&&(o||l)){let c;s==="audio"?c=u=>u.type===Hs.audioId3&&l:s==="video"?c=u=>u.type===Hs.emsg&&o:c=u=>u.type===Hs.audioId3&&l||u.type===Hs.emsg&&o,Mw(i,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:s,enableDateRangeMetadataCues:i,interstitialsController:a}=this.hls.config;if(!i)return;const o=Bw();if(r&&s&&!a){const{fragmentStart:g,fragmentEnd:y}=e;let v=this.assetCue;v?(v.startTime=g,v.endTime=y):o&&(v=this.assetCue=Nx(o,g,y,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=r,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(v),v.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 g=Object.keys(d).filter(y=>!u.includes(y));for(let y=g.length;y--;){var f;const v=g[y],_=(f=d[v])==null?void 0:f.cues;delete d[v],_&&Object.keys(_).forEach(S=>{const E=_[S];if(E){E.removeEventListener("enter",this.onEventCueEnter);try{l.removeCue(E)}catch{}}})}}else d=this.dateRangeCuesAppended={}}const m=e.fragments[e.fragments.length-1];if(!(u.length===0||!tt(m==null?void 0:m.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let g=0;g<u.length;g++){const y=u[g],v=c[y],_=v.startTime,S=d[y],E=(S==null?void 0:S.cues)||{};let L=(S==null?void 0:S.durationKnown)||!1,U=Qg;const{duration:P,endDate:I}=v;if(I&&P!==null)U=_+P,L=!0;else if(v.endOnNext&&!L){const R=u.reduce((M,G)=>{if(G!==v.id){const Y=c[G];if(Y.class===v.class&&Y.startDate>v.startDate&&(!M||v.startDate<M.startDate))return Y}return M},null);R&&(U=R.startTime,L=!0)}const k=Object.keys(v.attr);for(let R=0;R<k.length;R++){const M=k[R];if(!nhe(M))continue;const G=E[M];if(G)L&&!(S!=null&&S.durationKnown)?G.endTime=U:Math.abs(G.startTime-_)>.01&&(G.startTime=_,G.endTime=U);else if(o){let Y=v.attr[M];rhe(M)&&(Y=b5(Y));const X=Nx(o,_,U,{key:M,data:Y},Hs.dateRange);X&&(X.id=y,this.id3Track.addCue(X),E[M]=X,a&&(M==="X-ASSET-LIST"||M==="X-ASSET-URL")&&X.addEventListener("enter",this.onEventCueEnter))}}d[y]={cues:E,dateRange:v,durationKnown:L}}}}}class Mme{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 s=this.computeLatency();if(s===null)return;this._latency=s;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:a}=this.config;if(!i||a===1||!r.live)return;const o=this.targetLatency;if(o===null)return;const l=s-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:s}=e,{liveSyncDuration:i,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig;let c=o&&r||n;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||c===0)&&(c=i!==void 0?i:a*s);const u=s;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 s=r.edge,i=e-n-this.edgeStalled,a=s-r.totalduration,o=s-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(a,i),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(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(B.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(B.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(B.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(B.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===Se.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,s;e.playbackRate!==n&&((r=this.hls)==null||r.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(s=this.targetLatency)==null?void 0:s.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 jme extends jA{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(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(B.LEVEL_LOADED,this.onLevelLoaded,this),e.on(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(B.FRAG_BUFFERED,this.onFragBuffered,this),e.on(B.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(B.LEVEL_LOADED,this.onLevelLoaded,this),e.off(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(B.FRAG_BUFFERED,this.onFragBuffered,this),e.off(B.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,s=[],i={},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=G0(h,r)||void 0),f&&(f=u.videoCodec=_de(f));const{width:m,height:g,unknownCodecs:y}=u,v=(y==null?void 0:y.length)||0;if(o||(o=!!(m&&g)),l||(l=!!f),c||(c=!!h),v||h&&!this.isAudioSupported(h)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${d.CODECS}"`);return}const{CODECS:_,"FRAME-RATE":S,"HDCP-LEVEL":E,"PATHWAY-ID":L,RESOLUTION:U,"VIDEO-RANGE":P}=d,k=`${`${L||"."}-`}${u.bitrate}-${U}-${S}-${_}-${P}-${E}`;if(i[k])if(i[k].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const R=a[k]+=1;u.attrs["PATHWAY-ID"]=new Array(R+1).join(".");const M=this.createLevel(u);i[k]=M,s.push(M)}else i[k].addGroupId("audio",d.AUDIO),i[k].addGroupId("text",d.SUBTITLES);else{const R=this.createLevel(u);i[k]=R,a[k]=1,s.push(R)}}),this.filterAndSortMediaOptions(s,n,o,l,c)}createLevel(e){const n=new Gp(e),r=e.supplemental;if(r!=null&&r.videoCodec&&!this.isVideoSupported(r.videoCodec)){const s=new Error(`SUPPLEMENTAL-CODECS not supported "${r.videoCodec}"`);this.log(s.message),n.supportedResult=P5(s,[])}return n}isAudioSupported(e){return $p(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return $p(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,n,r,s,i){var a;let o=[],l=[],c=e;const u=((a=n.stats)==null?void 0:a.parsing)||{};if((r||s)&&i&&(c=c.filter(({videoCodec:_,videoRange:S,width:E,height:L})=>(!!_||!!(E&&L))&&kde(S))),c.length===0){Promise.resolve().then(()=>{if(this.hls){let _="no level with compatible codecs found in manifest",S=_;n.levels.length&&(S=`one or more CODECS in variant not supported: ${En(n.levels.map(L=>L.attrs.CODECS).filter((L,U,P)=>P.indexOf(L)===U))}`,this.warn(S),_+=` (${S})`);const E=new Error(_);this.hls.trigger(B.ERROR,{type:ft.MEDIA_ERROR,details:Se.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:n.url,error:E,reason:S})}}),u.end=performance.now();return}n.audioTracks&&(o=n.audioTracks.filter(_=>!_.audioCodec||this.isAudioSupported(_.audioCodec)),dO(o)),n.subtitles&&(l=n.subtitles,dO(l));const d=c.slice(0);c.sort((_,S)=>{if(_.attrs["HDCP-LEVEL"]!==S.attrs["HDCP-LEVEL"])return(_.attrs["HDCP-LEVEL"]||"")>(S.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&_.height!==S.height)return _.height-S.height;if(_.frameRate!==S.frameRate)return _.frameRate-S.frameRate;if(_.videoRange!==S.videoRange)return K0.indexOf(_.videoRange)-K0.indexOf(S.videoRange);if(_.videoCodec!==S.videoCodec){const E=nD(_.videoCodec),L=nD(S.videoCodec);if(E!==L)return L-E}if(_.uri===S.uri&&_.codecSet!==S.codecSet){const E=V0(_.codecSet),L=V0(S.codecSet);if(E!==L)return L-E}return _.averageBitrate!==S.averageBitrate?_.averageBitrate-S.averageBitrate:0});let h=d[0];if(this.steering&&(c=this.steering.filterParsedLevels(c),c.length!==d.length)){for(let _=0;_<d.length;_++)if(d[_].pathwayId===c[0].pathwayId){h=d[_];break}}this._levels=c;for(let _=0;_<c.length;_++)if(c[_]===h){var f;this._firstLevel=_;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 m=i&&!s,g=this.hls.config,y=!!(g.audioStreamController&&g.audioTrackController),v={levels:c,audioTracks:o,subtitleTracks:l,sessionData:n.sessionData,sessionKeys:n.sessionKeys,firstLevel:this._firstLevel,stats:n.stats,audio:i,video:s,altAudio:y&&!m&&o.some(_=>!!_.url)};u.end=performance.now(),this.hls.trigger(B.MANIFEST_PARSED,v)}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(B.ERROR,{type:ft.OTHER_ERROR,details:Se.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,s=this.currentLevel,i=s?s.attrs["PATHWAY-ID"]:void 0,a=n[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,r===e&&s&&i===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}${i?" with Pathway "+i:""}`);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(B.LEVEL_SWITCHING,l);const c=a.details;if(!c||c.live){const u=this.switchParams(a.uri,s==null?void 0:s.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(s=>n.indexOf(s)!==-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===Kt.LEVEL&&n.context.level===this.level&&this.checkRetry(n)}onFragBuffered(e,{frag:n}){if(n!==void 0&&n.type===rt.MAIN){const r=n.elementaryStreams;if(!Object.keys(r).some(i=>!!r[i]))return;const s=this._levels[n.level];s!=null&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(e,n){var r;const{level:s,details:i}=n,a=n.levelInfo;if(!a){var o;this.warn(`Invalid level index ${s}`),(o=n.deliveryDirectives)!=null&&o.skip&&(i.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(s,n,l)}else(r=n.deliveryDirectives)!=null&&r.skip&&(i.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),s=this.currentLevelIndex,i=e.attrs["PATHWAY-ID"],a=e.details,o=a==null?void 0:a.age;this.log(`Loading level index ${s}${(n==null?void 0:n.msn)!==void 0?" at sn "+n.msn+" part "+n.part:""}${i?" Pathway "+i:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(B.LEVEL_LOADING,{url:r,level:s,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((i,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(i),i===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,i.details&&i.details.fragments.forEach(o=>o.level=-1)),!1));Z5(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 s=r.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(B.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(B.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:n,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}function dO(t){const e={};t.forEach(n=>{const r=n.groupId||"";n.id=e[r]=e[r]||0,e[r]++})}function W4(){return self.SourceBuffer||self.WebKitSourceBuffer}function Y4(){if(!Hl())return!1;const e=W4();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Ume(){if(!Y4())return!1;const t=Hl();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(Vp(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported(Vp(e,"audio"))))}function Bme(){var t;const e=W4();return typeof(e==null||(t=e.prototype)==null?void 0:t.changeType)=="function"}const Fme=100;class $me extends kA{constructor(e,n,r){super(e,n,r,"stream-controller",rt.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 s=this.media,i=s?s.currentTime:null;if(i===null||!tt(i)||(this.log(`Media seeked to ${i.toFixed(3)}`),!this.getBufferedFrag(i)))return;const a=this.getFwdBufferInfoAtPos(s,i,rt.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${i} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(B.MANIFEST_PARSED,this.onManifestParsed,this),e.on(B.LEVEL_LOADING,this.onLevelLoading,this),e.on(B.LEVEL_LOADED,this.onLevelLoaded,this),e.on(B.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(B.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(B.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(B.BUFFER_CREATED,this.onBufferCreated,this),e.on(B.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(B.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(B.MANIFEST_PARSED,this.onManifestParsed,this),e.off(B.LEVEL_LOADED,this.onLevelLoaded,this),e.off(B.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(B.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(B.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(B.BUFFER_CREATED,this.onBufferCreated,this),e.off(B.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(B.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(B.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:s}=this;if(this.stopLoad(),this.setInterval(Fme),this.level=-1,!this.startFragRequested){let i=s.startLevel;i===-1&&(s.config.testBandwidth&&this.levels.length>1?(i=0,this.bitrateTest=!0):i=s.firstAutoLevel),s.nextLoadLevel=i,this.level=s.loadLevel,this._hasEnoughToStart=!!n}r>0&&e===-1&&!n&&(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r),this.state=De.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=n?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=De.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case De.WAITING_LEVEL:{const{levels:e,level:n}=this,r=e==null?void 0:e[n],s=r==null?void 0:r.details;if(s&&(!s.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(s))break;this.state=De.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=De.IDLE;break}break}case De.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===De.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:s}=this;if(n===null||!s&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const i=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(r!=null&&r[i]))return;const a=r[i],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const g={};this.altAudio===2&&(g.type="video"),this.hls.trigger(B.BUFFER_EOS,g),this.state=De.ENDED;return}if(!this.buffering)return;e.loadLevel!==i&&e.manualLevel===-1&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=e.nextLoadLevel=i;const c=a.details;if(!c||this.state===De.WAITING_LEVEL||this.waitForLive(a)){this.level=i,this.state=De.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&&ar(f)&&this.fragmentTracker.getState(f)!==xr.OK){var m;const y=((m=this.backtrackFragment)!=null?m:f).sn-c.startSN,v=c.fragments[y-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){const y=this.audioOnly&&!this.altAudio?bn.AUDIO:bn.VIDEO,v=(y===bn.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,y,rt.MAIN)}f=this.getNextFragmentLoopLoading(f,c,o,rt.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 s=this.fragmentTracker.getState(e);s===xr.NOT_LOADED||s===xr.PARTIAL?ar(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,rt.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 s=this.getAppendedFrag(n.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);const i=this.getLevelDetails();if(i!=null&&i.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<i.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 De.KEY_LOADING:case De.FRAG_LOADING:case De.FRAG_LOADING_WAITING_RETRY:case De.PARSING:case De.PARSED:this.state=De.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;hs(r,"playing",this.onMediaPlaying),hs(r,"seeked",this.onMediaSeeked)}onMediaDetaching(e,n){const{media:r}=this;r&&(Ls(r,"playing",this.onMediaPlaying),Ls(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(B.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,s=!1;for(let i=0;i<n.levels.length;i++){const a=n.levels[i].audioCodec;a&&(r=r||a.indexOf("mp4a.40.2")!==-1,s=s||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=r&&s&&!Bme(),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!==De.IDLE)return;const s=n.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=De.WAITING_LEVEL)}onLevelLoaded(e,n){var r;const{levels:s,startFragRequested:i}=this,a=n.level,o=n.details,l=o.totalduration;if(!s){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===De.FRAG_LOADING||this.state===De.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,i||this.setStartPosition(o,d),this.hls.trigger(B.LEVEL_UPDATED,{details:o,level:a}),this.state===De.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=De.IDLE}i&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){const{config:n,media:r}=this;if(!r)return;const s=this.hls.liveSyncPosition,i=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,l=i>=a-n.maxFragLookUpTolerance&&i<=o;if(s!==null&&r.duration>s&&(i<s||!l)){const u=n.liveMaxLatencyDuration!==void 0?n.liveMaxLatencyDuration:n.liveMaxLatencyDurationCount*e.targetduration;if((!l&&r.readyState<4||i<o-u)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),r.readyState))if(this.warn(`Playback: ${i.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${s.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var c;const d=Pt.bufferInfo(r,s,0);if(!((c=d.buffered)!=null&&c.length)){r.currentTime=s;return}if(d.start<=i){r.currentTime=s;return}const{nextStart:f}=Pt.bufferedInfo(d.buffered,i,0);f&&(r.currentTime=f)}else r.currentTime=s}}_handleFragmentLoadProgress(e){var n;const r=e.frag,{part:s,payload:i}=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 x4(this.hls,rt.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=s?s.index:-1,g=m!==-1,y=new AA(r.level,r.sn,r.stats.chunkCount,i.byteLength,m,g),v=this.initPTS[r.cc];f.push(i,d,h,c,r,s,l.totalduration,u,y,v)}onAudioTrackSwitching(e,n){const r=this.hls,s=this.altAudio!==0;if(H0(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(s){this.altAudio=0,this.fragmentTracker.removeAllFragments(),r.once(B.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(B.AUDIO_TRACK_SWITCHED,n)}),r.trigger(B.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}r.trigger(B.AUDIO_TRACK_SWITCHED,n)}}onAudioTrackSwitched(e,n){const r=H0(n.url,this.hls);if(r){const s=this.videoBuffer;s&&this.mediaBuffer!==s&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=s)}this.altAudio=r?2:0,this.tick()}onBufferCreated(e,n){const r=n.tracks;let s,i,a=!1;for(const o in r){const l=r[o];if(l.id==="main"){if(i=o,s=l,o==="video"){const c=r[o];c&&(this.videoBuffer=c.buffer)}}else a=!0}a&&s?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(e,n){const{frag:r,part:s}=n,i=r.type===rt.MAIN;if(i){if(this.fragContextChanged(r)){this.warn(`Fragment ${r.sn}${s?" p: "+s.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}`),this.state===De.PARSED&&(this.state=De.IDLE);return}const o=s?s.stats:r.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),ar(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,s)}const a=this.media;a&&(!this._hasEnoughToStart&&Pt.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),i&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,n){var r;if(n.fatal){this.state=De.ERROR;return}switch(n.details){case Se.FRAG_GAP:case Se.FRAG_PARSING_ERROR:case Se.FRAG_DECRYPT_ERROR:case Se.FRAG_LOAD_ERROR:case Se.FRAG_LOAD_TIMEOUT:case Se.KEY_LOAD_ERROR:case Se.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(rt.MAIN,n);break;case Se.LEVEL_LOAD_ERROR:case Se.LEVEL_LOAD_TIMEOUT:case Se.LEVEL_PARSING_ERROR:!n.levelRetry&&this.state===De.WAITING_LEVEL&&((r=n.context)==null?void 0:r.type)===Kt.LEVEL&&(this.state=De.IDLE);break;case Se.BUFFER_ADD_CODEC_ERROR:case Se.BUFFER_APPEND_ERROR:if(n.parent!=="main")return;this.reduceLengthAndFlushBuffer(n)&&this.resetLoadingState();break;case Se.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 Se.INTERNAL_EXCEPTION:this.recoverWorkerError(n);break}}onFragLoadEmergencyAborted(){this.state=De.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:n}){if(n!==bn.AUDIO||!this.altAudio){const r=(n===bn.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,n,rt.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 s=this.timelineOffset;s&&r&&(r+=s);const i=this.getLevelDetails(),a=Pt.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*((i==null?void 0:i.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:s}=this,i=r==null?void 0:r.frag;if(!i||this.fragContextChanged(i))return;n.fragmentError=0,this.state=De.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=i.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),s.trigger(B.FRAG_LOADED,r),i.bitrateTest=!1}).catch(r=>{this.state===De.STOPPED||this.state===De.ERROR||(this.warn(r),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const n=this.playlistType,{hls:r}=this,{remuxResult:s,chunkMeta:i}=e,a=this.getCurrentContext(i);if(!a){this.resetWhenMissingContext(i);return}const{frag:o,part:l,level:c}=a,{video:u,text:d,id3:h,initSegment:f}=s,{details:m}=c,g=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=De.PARSING,f){const y=f.tracks;if(y){const E=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(c,y,E,i),r.trigger(B.FRAG_PARSING_INIT_SEGMENT,{frag:E,id:n,tracks:y})}const v=f.initPTS,_=f.timescale,S=this.initPTS[o.cc];if(tt(v)&&(!S||S.baseTime!==v||S.timescale!==_)){const E=f.trackId;this.initPTS[o.cc]={baseTime:v,timescale:_,trackId:E},r.trigger(B.INIT_PTS_FOUND,{frag:o,id:n,initPTS:v,timescale:_,trackId:E})}}if(u&&m){g&&u.type==="audiovideo"&&this.logMuxedErr(o);const y=m.fragments[o.sn-1-m.startSN],v=o.sn===m.startSN,_=!y||o.cc>y.cc;if(s.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&&i.id===1&&!_&&(this.couldBacktrack=!0),u.dropped&&u.independent){const P=this.getMainFwdBufferInfo(),I=(P?P.end:this.getLoadPosition())+this.config.maxBufferHole,k=u.firstKeyFramePTS?u.firstKeyFramePTS:S;if(!v&&I<k-this.config.maxBufferHole&&!_){this.backtrack(o);return}else _&&(o.gap=!0);o.setElementaryStreamInfo(u.type,o.start,E,o.start,U,!0)}else v&&S-(m.appliedTimelineOffset||0)>Ny&&(o.gap=!0);o.setElementaryStreamInfo(u.type,S,E,L,U),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,l,i,v||_)}else if(v||_)o.gap=!0;else{this.backtrack(o);return}}if(g){const{startPTS:y,endPTS:v,startDTS:_,endDTS:S}=g;l&&(l.elementaryStreams[bn.AUDIO]={startPTS:y,endPTS:v,startDTS:_,endDTS:S}),o.setElementaryStreamInfo(bn.AUDIO,y,v,_,S),this.bufferFragmentData(g,o,l,i)}if(m&&h!=null&&h.samples.length){const y={id:n,frag:o,details:m,samples:h.samples};r.trigger(B.FRAG_PARSING_METADATA,y)}if(m&&d){const y={id:n,frag:o,details:m,samples:d.samples};r.trigger(B.FRAG_PARSING_USERDATA,y)}}logMuxedErr(e){this.warn(`${ar(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,n,r,s){if(this.state!==De.PARSING)return;this.audioOnly=!!n.audio&&!n.video,this.altAudio&&!this.audioOnly&&(delete n.audio,n.audiovideo&&this.logMuxedErr(r));const{audio:i,video:a,audiovideo:o}=n;if(i){const c=e.audioCodec;let u=Cy(i.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=i.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&&i.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}"`),i.levelCodec=u,i.id=rt.MAIN,this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${u||""}/${c||""}/${i.codec}]`),delete n.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=rt.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(B.BUFFER_CODECS,n),!this.hls)return;l.forEach(c=>{const d=n[c].initSegment;d!=null&&d.byteLength&&this.hls.trigger(B.BUFFER_APPENDING,{type:c,data:d,frag:r,part:null,chunkMeta:s,parent:r.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,rt.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=De.IDLE}checkFragmentChanged(){const e=this.media;let n=null;if(e&&e.readyState>1&&e.seeking===!1){const r=e.currentTime;if(Pt.isBuffered(e,r)?n=this.getAppendedFrag(r):Pt.isBuffered(e,r+.1)&&(n=this.getAppendedFrag(r+.1)),n){this.backtrackFragment=null;const s=this.fragPlaying,i=n.level;(!s||n.sn!==s.sn||s.level!==i)&&(this.fragPlaying=n,this.hls.trigger(B.FRAG_CHANGED,{frag:n}),(!s||s.level!==i)&&this.hls.trigger(B.LEVEL_SWITCHED,{level:i}))}}}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 tt(n)?this.getAppendedFrag(n):null}get currentProgramDateTime(){var e;const n=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(tt(n)){const r=this.getLevelDetails(),s=this.currentFrag||(r?ou(null,r.fragments,n):null);if(s){const i=s.programDateTime;if(i!==null){const a=i+(n-s.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 Vme extends Ii{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 s=this.keyIdToKeyInfo[r].loader;if(s){var n;if(e&&e!==((n=s.context)==null?void 0:n.frag.type))return;s.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=Se.KEY_LOAD_ERROR,r,s,i){return new ro({type:ft.NETWORK_ERROR,details:n,fatal:!1,frag:e,response:i,error:r,networkDetails:s})}loadClear(e,n,r){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(n.length)for(let s=0,i=n.length;s<i;s++){const a=n[s];if(e.cc<=a.cc&&(!ar(e)||!ar(a)||e.sn<a.sn)||!r&&s==i-1)return this.emeController.selectKeySystemFormat(a).then(o=>{if(!this.emeController)return;a.setKeyFormat(o);const l=Ly(o);if(l)return this.emeController.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){const s=Af(this.config);if(s.length)return this.emeController.getKeySystemAccess(s)}}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,s;n&&e.setKeyFormat(n);const i=e.decryptdata;if(!i){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,Se.KEY_LOAD_ERROR,c))}const a=i.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,Se.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));const o=Mx(i);let l=this.keyIdToKeyInfo[o];if((r=l)!=null&&r.decryptdata.key)return i.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&(s=l)!=null&&s.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then(u=>{const{keyInfo:d}=u;return i.key=d.decryptdata.key,{frag:e,keyInfo:d}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${i.keyId?" keyId: "+Vr(i.keyId):""} URI: ${i.uri} from ${e.type} ${e.level}`),l=this.keyIdToKeyInfo[o]={decryptdata:i,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},i.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return i.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,Se.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(e,n){const r={frag:n,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var s;if(!e.decryptdata.keyId&&(s=n.initSegment)!=null&&s.data){const a=ode(n.initSegment.data);if(a.length){let o=a[0];o.some(l=>l!==0)?(this.log(`Using keyId found in init segment ${Vr(o)}`),Ol.setKeyIdForUri(e.decryptdata.uri,o)):(o=Ol.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Vr(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!ar(n))return Promise.resolve(r);const i=this.emeController.loadKey(r);return(e.keyLoadPromise=i.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,s=r.loader,i=new s(r);return n.keyLoader=e.loader=i,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,m,g)=>{const{frag:y,keyInfo:v}=m,_=Mx(v.decryptdata);if(!y.decryptdata||v!==this.keyIdToKeyInfo[_])return o(this.createKeyLoadError(y,Se.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),g));v.decryptdata.key=y.decryptdata.key=new Uint8Array(h.data),y.keyLoader=null,v.loader=null,a({frag:y,keyInfo:v})},onError:(h,f,m,g)=>{this.resetLoader(f),o(this.createKeyLoadError(n,Se.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),m,hn({url:l.url,data:void 0},h)))},onTimeout:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(n,Se.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m))},onAbort:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(n,Se.INTERNAL_ABORTED,new Error("key loading aborted"),m))}};i.load(l,u,d)})}resetLoader(e){const{frag:n,keyInfo:r,url:s}=e,i=r.loader;n.keyLoader===i&&(n.keyLoader=null,r.loader=null);const a=Mx(r.decryptdata)||s;delete this.keyIdToKeyInfo[a],i&&i.destroy()}}function Mx(t){if(t.keyFormat!==Kr.FAIRPLAY){const e=t.keyId;if(e)return Vr(e)}return t.uri}function hO(t){const{type:e}=t;switch(e){case Kt.AUDIO_TRACK:return rt.AUDIO;case Kt.SUBTITLE_TRACK:return rt.SUBTITLE;default:return rt.MAIN}}function jx(t,e){let n=t.url;return(n===void 0||n.indexOf("data:")===0)&&(n=e.url),n}class Gme{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(B.MANIFEST_LOADING,this.onManifestLoading,this),e.on(B.LEVEL_LOADING,this.onLevelLoading,this),e.on(B.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(B.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(B.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(B.MANIFEST_LOADING,this.onManifestLoading,this),e.off(B.LEVEL_LOADING,this.onLevelLoading,this),e.off(B.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(B.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(B.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const n=this.hls.config,r=n.pLoader,s=n.loader,i=r||s,a=new i(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:Kt.MANIFEST,url:r,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,n){const{id:r,level:s,pathwayId:i,url:a,deliveryDirectives:o,levelInfo:l}=n;this.load({id:r,level:s,pathwayId:i,responseType:"text",type:Kt.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(e,n){const{id:r,groupId:s,url:i,deliveryDirectives:a,track:o}=n;this.load({id:r,groupId:s,level:null,responseType:"text",type:Kt.AUDIO_TRACK,url:i,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,n){const{id:r,groupId:s,url:i,deliveryDirectives:a,track:o}=n;this.load({id:r,groupId:s,level:null,responseType:"text",type:Kt.SUBTITLE_TRACK,url:i,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,n){const r=this.loaders[Kt.LEVEL];if(r){const s=r.context;s&&!n.levels.some(i=>i===s.levelOrTrack)&&(r.abort(),delete this.loaders[Kt.LEVEL])}}load(e){var n;const r=this.hls.config;let s=this.getInternalLoader(e);if(s){const c=this.hls.logger,u=s.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}`),s.abort()}let i;if(e.type===Kt.MANIFEST?i=r.manifestLoadPolicy.default:i=vn({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),tt((n=e.deliveryDirectives)==null?void 0:n.part)){let c;if(e.type===Kt.LEVEL&&e.level!==null?c=this.hls.levels[e.level].details:e.type===Kt.AUDIO_TRACK&&e.id!==null?c=this.hls.audioTracks[e.id].details:e.type===Kt.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;i=vn({},i,{maxTimeToFirstByteMs:Math.min(h,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(h,i.maxTimeToFirstByteMs)})}}}const a=i.errorRetry||i.timeoutRetry||{},o={loadPolicy:i,timeout:i.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 m=c.data;u.parsing.start=performance.now(),Sa.isMediaPlaylist(m)||d.type!==Kt.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)}};s.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,s){const i=this.hls,a=e.data,o=jx(e,r),l=Sa.parseMasterPlaylist(a,o);if(l.playlistParsingError){n.parsing.end=performance.now(),this.handleManifestParsingError(e,r,l.playlistParsingError,s,n);return}const{contentSteering:c,levels:u,sessionData:d,sessionKeys:h,startTimeOffset:f,variableList:m}=l;this.variableList=m,u.forEach(_=>{const{unknownCodecs:S}=_;if(S){const{preferManagedMediaSource:E}=this.hls.config;let{audioCodec:L,videoCodec:U}=_;for(let P=S.length;P--;){const I=S[P];$p(I,"audio",E)?(_.audioCodec=L=L?`${L},${I}`:I,bh.audio[L.substring(0,4)]=2,S.splice(P,1)):$p(I,"video",E)&&(_.videoCodec=U=U?`${U},${I}`:I,bh.video[U.substring(0,4)]=2,S.splice(P,1))}}});const{AUDIO:g=[],SUBTITLES:y,"CLOSED-CAPTIONS":v}=Sa.parseMasterPlaylistMedia(a,o,l);g.length&&!g.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"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Gn({}),bitrate:0,url:""})),i.trigger(B.MANIFEST_LOADED,{levels:u,audioTracks:g,subtitles:y,captions:v,contentSteering:c,url:o,stats:n,networkDetails:s,sessionData:d,sessionKeys:h,startTimeOffset:f,variableList:m})}handleTrackOrLevelPlaylist(e,n,r,s,i){const a=this.hls,{id:o,level:l,type:c}=r,u=jx(e,r),d=tt(l)?l:tt(o)?o:0,h=hO(r),f=Sa.parseLevelPlaylist(e.data,u,d,h,0,this.variableList);if(c===Kt.MANIFEST){const m={attrs:new Gn({}),bitrate:0,details:f,name:"",url:u};f.requestScheduled=n.loading.start+X5(f,0),a.trigger(B.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:u,stats:n,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}n.parsing.end=performance.now(),r.levelDetails=f,this.handlePlaylistLoaded(f,e,n,r,s,i)}handleManifestParsingError(e,n,r,s,i){this.hls.trigger(B.ERROR,{type:ft.NETWORK_ERROR,details:Se.MANIFEST_PARSING_ERROR,fatal:n.type===Kt.MANIFEST,url:e.url,err:r,error:r,reason:r.message,response:e,context:n,networkDetails:s,stats:i})}handleNetworkError(e,n,r=!1,s,i){let a=`A network ${r?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===Kt.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===Kt.AUDIO_TRACK||e.type===Kt.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=Se.UNKNOWN,c=!1;const u=this.getInternalLoader(e);switch(e.type){case Kt.MANIFEST:l=r?Se.MANIFEST_LOAD_TIMEOUT:Se.MANIFEST_LOAD_ERROR,c=!0;break;case Kt.LEVEL:l=r?Se.LEVEL_LOAD_TIMEOUT:Se.LEVEL_LOAD_ERROR,c=!1;break;case Kt.AUDIO_TRACK:l=r?Se.AUDIO_TRACK_LOAD_TIMEOUT:Se.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case Kt.SUBTITLE_TRACK:l=r?Se.SUBTITLE_TRACK_LOAD_TIMEOUT:Se.SUBTITLE_LOAD_ERROR,c=!1;break}u&&this.resetInternalLoader(e.type);const d={type:ft.NETWORK_ERROR,details:l,fatal:c,url:e.url,loader:u,context:e,error:o,networkDetails:n,stats:i};if(s){const h=(n==null?void 0:n.url)||e.url;d.response=hn({url:h,data:void 0},s)}this.hls.trigger(B.ERROR,d)}handlePlaylistLoaded(e,n,r,s,i,a){const o=this.hls,{type:l,level:c,levelOrTrack:u,id:d,groupId:h,deliveryDirectives:f}=s,m=jx(n,s),g=hO(s);let y=typeof s.level=="number"&&g===rt.MAIN?c:void 0;const v=e.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(B.ERROR,{type:ft.NETWORK_ERROR,details:Se.LEVEL_PARSING_ERROR,fatal:!1,url:m,error:v,reason:v.message,response:n,context:s,level:y,parent:g,networkDetails:i,stats:r});return}e.playlistParsingError=null}if(!e.fragments.length){const _=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(B.ERROR,{type:ft.NETWORK_ERROR,details:Se.LEVEL_EMPTY_ERROR,fatal:!1,url:m,error:_,reason:_.message,response:n,context:s,level:y,parent:g,networkDetails:i,stats:r});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case Kt.MANIFEST:case Kt.LEVEL:if(y){if(!u)y=0;else if(u!==o.levels[y]){const _=o.levels.indexOf(u);_>-1&&(y=_)}}o.trigger(B.LEVEL_LOADED,{details:e,levelInfo:u||o.levels[0],level:y||0,id:d||0,stats:r,networkDetails:i,deliveryDirectives:f,withoutMultiVariant:l===Kt.MANIFEST});break;case Kt.AUDIO_TRACK:o.trigger(B.AUDIO_TRACK_LOADED,{details:e,track:u,id:d||0,groupId:h||"",stats:r,networkDetails:i,deliveryDirectives:f});break;case Kt.SUBTITLE_TRACK:o.trigger(B.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:d||0,groupId:h||"",stats:r,networkDetails:i,deliveryDirectives:f});break}}}class zs{static get version(){return Kp}static isMSESupported(){return Y4()}static isSupported(){return Ume()}static getMediaSource(){return Hl()}static get Events(){return B}static get MetadataSchema(){return Hs}static get ErrorTypes(){return ft}static get ErrorDetails(){return Se}static get DefaultConfig(){return zs.defaultConfig?zs.defaultConfig:Ame}static set DefaultConfig(e){zs.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 LA,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=Yue(e.debug||!1,"Hls instance",e.assetPlayerId),r=this.config=Cme(zs.DefaultConfig,e,n);this.userConfig=e,r.progressive&&kme(r,n);const{abrController:s,bufferController:i,capLevelController:a,errorController:o,fpsController:l}=r,c=new o(this),u=this.abrController=new s(this),d=new Kde(this),h=r.interstitialsController,f=h?this.interstitialsController=new h(this,zs):null,m=this.bufferController=new i(this,d),g=this.capLevelController=new a(this),y=new l(this),v=new Gme(this),_=r.contentSteeringController,S=_?new _(this):null,E=this.levelController=new jme(this,S),L=new Nme(this),U=new Vme(this.config,this.logger),P=this.streamController=new $me(this,d,U),I=this.gapController=new Dme(this,d);g.setStreamController(P),y.setStreamController(P);const k=[v,E,P];f&&k.splice(1,0,f),S&&k.splice(1,0,S),this.networkControllers=k;const R=[u,m,I,g,y,L,d];this.audioTrackController=this.createController(r.audioTrackController,k);const M=r.audioStreamController;M&&k.push(this.audioStreamController=new M(this,d,U)),this.subtitleTrackController=this.createController(r.subtitleTrackController,k);const G=r.subtitleStreamController;G&&k.push(this.subtititleStreamController=new G(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(Mme,R),this.coreComponents=R,k.push(c);const Y=c.onErrorOut;typeof Y=="function"&&this.on(B.ERROR,Y,c),this.on(B.MANIFEST_LOADED,v.onManifestLoaded,v)}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,s){this._emitter.off(e,n,r,s)}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 s=e===B.ERROR;this.trigger(B.ERROR,{type:ft.OTHER_ERROR,details:Se.INTERNAL_EXCEPTION,fatal:s,event:e,error:r}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(B.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 i=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(B.ERROR,{type:ft.OTHER_ERROR,details:Se.ATTACH_MEDIA_ERROR,fatal:!0,error:i});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,s=n?e:{media:r};this._media=r,this.trigger(B.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia"),this.trigger(B.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(B.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const n=this.media,r=this._url,s=this._url=_A.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${s}`),n&&r&&(r!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(n)),this.trigger(B.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={[rt.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[rt.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[rt.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=Dpe()),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){Cde(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 s=0;s<r;s++)if(e[s].maxBitrate>=n)return s;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:n,maxHdcpLevel:r}=this;let s;if(n===-1&&e!=null&&e.length?s=e.length-1:s=n,r)for(let i=s;i--;){const a=e[i].attrs["HDCP-LEVEL"];if(a&&a<=r)return i}return s}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=N5(n);return D5(e,r,navigator.mediaCapabilities)}}zs.defaultConfig=void 0;var X4={exports:{}};(function(t,e){(function(n,r){t.exports=r()})(window,function(){return function(n){var r={};function s(i){if(r[i])return r[i].exports;var a=r[i]={i,l:!1,exports:{}};return n[i].call(a.exports,a,a.exports,s),a.l=!0,a.exports}return s.m=n,s.c=r,s.d=function(i,a,o){s.o(i,a)||Object.defineProperty(i,a,{enumerable:!0,get:o})},s.r=function(i){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(i,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(i,"__esModule",{value:!0})},s.t=function(i,a){if(1&a&&(i=s(i)),8&a||4&a&&typeof i=="object"&&i&&i.__esModule)return i;var o=Object.create(null);if(s.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:i}),2&a&&typeof i!="string")for(var l in i)s.d(o,l,(function(c){return i[c]}).bind(null,l));return o},s.n=function(i){var a=i&&i.__esModule?function(){return i.default}:function(){return i};return s.d(a,"a",a),a},s.o=function(i,a){return Object.prototype.hasOwnProperty.call(i,a)},s.p="",s(s.s=20)}([function(n,r,s){var i=s(9),a=s.n(i),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,s){var i;(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"})(i||(i={})),r.a=i},function(n,r,s){s.d(r,"c",function(){return a}),s.d(r,"b",function(){return o}),s.d(r,"a",function(){return l});var i=s(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 i.c("Unimplemented abstract function!")},c.prototype.abort=function(){throw new i.c("Unimplemented abstract function!")},c}()},function(n,r,s){s.d(r,"d",function(){return o}),s.d(r,"a",function(){return l}),s.d(r,"b",function(){return c}),s.d(r,"c",function(){return u});var i,a=(i=function(d,h){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(f,m){f.__proto__=m}||function(f,m){for(var g in m)Object.prototype.hasOwnProperty.call(m,g)&&(f[g]=m[g])})(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}i(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,s){var i;(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"})(i||(i={})),r.a=i},function(n,r,s){var i={};(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,i)i.hasOwnProperty(h)&&delete i[h];Object.assign(i,u)})(),r.a=i},function(n,r,s){r.a={OK:"OK",FORMAT_ERROR:"FormatError",FORMAT_UNSUPPORTED:"FormatUnsupported",CODEC_UNSUPPORTED:"CodecUnsupported"}},function(n,r,s){var i;(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"})(i||(i={})),r.a=i},function(n,r,s){var i=s(9),a=s.n(i),o=s(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,s){var i,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)};i=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,P){function I(R){E.removeListener(L,k),P(R)}function k(){typeof E.removeListener=="function"&&E.removeListener("error",I),U([].slice.call(arguments))}S(E,L,k,{once:!0}),L!=="error"&&function(R,M,G){typeof R.on=="function"&&S(R,"error",M,G)}(E,I,{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,P){var I,k,R,M;if(d(U),(k=E._events)===void 0?(k=E._events=Object.create(null),E._eventsCount=0):(k.newListener!==void 0&&(E.emit("newListener",L,U.listener?U.listener:U),k=E._events),R=k[L]),R===void 0)R=k[L]=U,++E._eventsCount;else if(typeof R=="function"?R=k[L]=P?[U,R]:[R,U]:P?R.unshift(U):R.push(U),(I=h(E))>0&&R.length>I&&!R.warned){R.warned=!0;var G=new Error("Possible EventEmitter memory leak detected. "+R.length+" "+String(L)+" listeners added. Use emitter.setMaxListeners() to increase limit");G.name="MaxListenersExceededWarning",G.emitter=E,G.type=L,G.count=R.length,M=G,console&&console.warn&&console.warn(M)}return E}function m(){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 g(E,L,U){var P={fired:!1,wrapFn:void 0,target:E,type:L,listener:U},I=m.bind(P);return I.listener=U,P.wrapFn=I,I}function y(E,L,U){var P=E._events;if(P===void 0)return[];var I=P[L];return I===void 0?[]:typeof I=="function"?U?[I.listener||I]:[I]:U?function(k){for(var R=new Array(k.length),M=0;M<R.length;++M)R[M]=k[M].listener||k[M];return R}(I):_(I,I.length)}function v(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 _(E,L){for(var U=new Array(L),P=0;P<L;++P)U[P]=E[P];return U}function S(E,L,U,P){if(typeof E.on=="function")P.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 I(k){P.once&&E.removeEventListener(L,I),U(k)})}}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 P=E==="error",I=this._events;if(I!==void 0)P=P&&I.error===void 0;else if(!P)return!1;if(P){var k;if(L.length>0&&(k=L[0]),k instanceof Error)throw k;var R=new Error("Unhandled error."+(k?" ("+k.message+")":""));throw R.context=k,R}var M=I[E];if(M===void 0)return!1;if(typeof M=="function")o(M,this,L);else{var G=M.length,Y=_(M,G);for(U=0;U<G;++U)o(Y[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,g(this,E,L)),this},c.prototype.prependOnceListener=function(E,L){return d(L),this.prependListener(E,g(this,E,L)),this},c.prototype.removeListener=function(E,L){var U,P,I,k,R;if(d(L),(P=this._events)===void 0)return this;if((U=P[E])===void 0)return this;if(U===L||U.listener===L)--this._eventsCount==0?this._events=Object.create(null):(delete P[E],P.removeListener&&this.emit("removeListener",E,U.listener||L));else if(typeof U!="function"){for(I=-1,k=U.length-1;k>=0;k--)if(U[k]===L||U[k].listener===L){R=U[k].listener,I=k;break}if(I<0)return this;I===0?U.shift():function(M,G){for(;G+1<M.length;G++)M[G]=M[G+1];M.pop()}(U,I),U.length===1&&(P[E]=U[0]),P.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,P;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 I,k=Object.keys(U);for(P=0;P<k.length;++P)(I=k[P])!=="removeListener"&&this.removeAllListeners(I);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(P=L.length-1;P>=0;P--)this.removeListener(E,L[P]);return this},c.prototype.listeners=function(E){return y(this,E,!0)},c.prototype.rawListeners=function(E){return y(this,E,!1)},c.listenerCount=function(E,L){return typeof E.listenerCount=="function"?E.listenerCount(L):v.call(E,L)},c.prototype.listenerCount=v,c.prototype.eventNames=function(){return this._eventsCount>0?i(this._events):[]}},function(n,r,s){s.d(r,"b",function(){return o}),s.d(r,"a",function(){return l});var i=s(2),a=s(6),o={NETWORK_ERROR:"NetworkError",MEDIA_ERROR:"MediaError",OTHER_ERROR:"OtherError"},l={NETWORK_EXCEPTION:i.b.EXCEPTION,NETWORK_STATUS_CODE_INVALID:i.b.HTTP_STATUS_CODE_INVALID,NETWORK_TIMEOUT:i.b.CONNECTING_TIMEOUT,NETWORK_UNRECOVERABLE_EARLY_EOF:i.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,s){s.d(r,"d",function(){return i}),s.d(r,"b",function(){return a}),s.d(r,"a",function(){return o}),s.d(r,"c",function(){return l});var i=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,m=0,g=0,y=f;for(u<d[0].dts&&(h=0,g=y+1);g<=y;){if((m=g+Math.floor((y-g)/2))===f||u>=d[m].dts&&u<d[m+1].dts){h=m;break}d[m].dts<u?g=m+1:y=m-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,m=0,g=h,y=0;if(u<d[0].originalBeginDts)return y=-1;for(;m<=g;){if((f=m+Math.floor((g-m)/2))===h||u>d[f].lastSample.originalDts&&u<d[f+1].originalBeginDts){y=f;break}d[f].originalBeginDts<u?m=f+1:g=f-1}return y},c.prototype._searchNearestSegmentAfter=function(u){return this._searchNearestSegmentBefore(u)+1},c.prototype.append=function(u){var d=this._list,h=u,f=this._lastAppendLocation,m=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)?m=f+1:d.length>0&&(m=this._searchNearestSegmentBefore(h.originalBeginDts)+1),this._lastAppendLocation=m,this._list.splice(m,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,s){var i=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=i},function(n,r,s){var i=s(9),a=s.n(i),o=s(0),l=s(5),c=s(12);function u(D,A,w){var x=D;if(A+w<x.length){for(;w--;)if((192&x[++A])!=128)return!1;return!0}return!1}var d,h=function(D){for(var A=[],w=D,x=0,O=D.length;x<O;)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=s(3),m=(d=new ArrayBuffer(2),new DataView(d).setInt16(0,256,!0),new Int16Array(d)[0]===256),g=function(){function D(){}return D.parseScriptData=function(A,w,x){var O={};try{var F=D.parseValue(A,w,x),$=D.parseValue(A,w+F.size,x-F.size);O[F.data]=$.data}catch(z){o.a.e("AMF",z.toString())}return O},D.parseObject=function(A,w,x){if(x<3)throw new f.a("Data not enough when parse ScriptDataObject");var O=D.parseString(A,w,x),F=D.parseValue(A,w+O.size,x-O.size),$=F.objectEnd;return{data:{name:O.data,value:F.data},size:O.size+F.size,objectEnd:$}},D.parseVariable=function(A,w,x){return D.parseObject(A,w,x)},D.parseString=function(A,w,x){if(x<2)throw new f.a("Data not enough when parse String");var O=new DataView(A,w,x).getUint16(0,!m);return{data:O>0?h(new Uint8Array(A,w+2,O)):"",size:2+O}},D.parseLongString=function(A,w,x){if(x<4)throw new f.a("Data not enough when parse LongString");var O=new DataView(A,w,x).getUint32(0,!m);return{data:O>0?h(new Uint8Array(A,w+4,O)):"",size:4+O}},D.parseDate=function(A,w,x){if(x<10)throw new f.a("Data size invalid when parse Date");var O=new DataView(A,w,x),F=O.getFloat64(0,!m),$=O.getInt16(8,!m);return{data:new Date(F+=60*$*1e3),size:10}},D.parseValue=function(A,w,x){if(x<1)throw new f.a("Data not enough when parse Value");var O,F=new DataView(A,w,x),$=1,z=F.getUint8(0),se=!1;try{switch(z){case 0:O=F.getFloat64(1,!m),$+=8;break;case 1:O=!!F.getUint8(1),$+=1;break;case 2:var te=D.parseString(A,w+1,x-1);O=te.data,$+=te.size;break;case 3:O={};var ie=0;for((16777215&F.getUint32(x-4,!m))==9&&(ie=3);$<x-4;){var le=D.parseObject(A,w+$,x-$-ie);if(le.objectEnd)break;O[le.data.name]=le.data.value,$+=le.size}$<=x-3&&(16777215&F.getUint32($-1,!m))===9&&($+=3);break;case 8:for(O={},$+=4,ie=0,(16777215&F.getUint32(x-4,!m))==9&&(ie=3);$<x-8;){var ae=D.parseVariable(A,w+$,x-$-ie);if(ae.objectEnd)break;O[ae.data.name]=ae.data.value,$+=ae.size}$<=x-3&&(16777215&F.getUint32($-1,!m))===9&&($+=3);break;case 9:O=void 0,$=1,se=!0;break;case 10:O=[];var ce=F.getUint32(1,!m);$+=4;for(var Ce=0;Ce<ce;Ce++){var Me=D.parseValue(A,w+$,x-$);O.push(Me.data),$+=Me.size}break;case 11:var Le=D.parseDate(A,w+1,x-1);O=Le.data,$+=Le.size;break;case 12:var Je=D.parseString(A,w+1,x-1);O=Je.data,$+=Je.size;break;default:$=x,o.a.w("AMF","Unsupported AMF value type "+z)}}catch(Ye){o.a.e("AMF",Ye.toString())}return{data:O,size:$,objectEnd:se}},D}(),y=function(){function D(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 D.prototype.destroy=function(){this._buffer=null},D.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},D.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 O=A-this._current_word_bits_left;this._fillCurrentWord();var F=Math.min(O,this._current_word_bits_left),$=this._current_word>>>32-F;return this._current_word<<=F,this._current_word_bits_left-=F,x=x<<F|$},D.prototype.readBool=function(){return this.readBits(1)===1},D.prototype.readByte=function(){return this.readBits(8)},D.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()},D.prototype.readUEG=function(){var A=this._skipLeadingZero();return this.readBits(A+1)-1},D.prototype.readSEG=function(){var A=this.readUEG();return 1&A?A+1>>>1:-1*(A>>>1)},D}(),v=function(){function D(){}return D._ebsp2rbsp=function(A){for(var w=A,x=w.byteLength,O=new Uint8Array(x),F=0,$=0;$<x;$++)$>=2&&w[$]===3&&w[$-1]===0&&w[$-2]===0||(O[F]=w[$],F++);return new Uint8Array(O.buffer,0,F)},D.parseSPS=function(A){for(var w=A.subarray(1,4),x="avc1.",O=0;O<3;O++){var F=w[O].toString(16);F.length<2&&(F="0"+F),x+=F}var $=D._ebsp2rbsp(A),z=new y($);z.readByte();var se=z.readByte();z.readByte();var te=z.readByte();z.readUEG();var ie=D.getProfileString(se),le=D.getLevelString(te),ae=1,ce=420,Ce=8,Me=8;if((se===100||se===110||se===122||se===244||se===44||se===83||se===86||se===118||se===128||se===138||se===144)&&((ae=z.readUEG())===3&&z.readBits(1),ae<=3&&(ce=[0,420,422,444][ae]),Ce=z.readUEG()+8,Me=z.readUEG()+8,z.readBits(1),z.readBool()))for(var Le=ae!==3?8:12,Je=0;Je<Le;Je++)z.readBool()&&(Je<6?D._skipScalingList(z,16):D._skipScalingList(z,64));z.readUEG();var Ye=z.readUEG();if(Ye===0)z.readUEG();else if(Ye===1){z.readBits(1),z.readSEG(),z.readSEG();var Ve=z.readUEG();for(Je=0;Je<Ve;Je++)z.readSEG()}var pt=z.readUEG();z.readBits(1);var Et=z.readUEG(),Xe=z.readUEG(),He=z.readBits(1);He===0&&z.readBits(1),z.readBits(1);var Lt=0,mt=0,vt=0,Ut=0;z.readBool()&&(Lt=z.readUEG(),mt=z.readUEG(),vt=z.readUEG(),Ut=z.readUEG());var tn=1,bt=1,Nt=0,yt=!0,Tn=0,Or=0;if(z.readBool()){if(z.readBool()){var $n=z.readByte();$n>0&&$n<16?(tn=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][$n-1],bt=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][$n-1]):$n===255&&(tn=z.readByte()<<8|z.readByte(),bt=z.readByte()<<8|z.readByte())}if(z.readBool()&&z.readBool(),z.readBool()&&(z.readBits(4),z.readBool()&&z.readBits(24)),z.readBool()&&(z.readUEG(),z.readUEG()),z.readBool()){var Nr=z.readBits(32),gr=z.readBits(32);yt=z.readBool(),Nt=(Tn=gr)/(Or=2*Nr)}}var tr=1;tn===1&&bt===1||(tr=tn/bt);var Tr=0,Ht=0;ae===0?(Tr=1,Ht=2-He):(Tr=ae===3?1:2,Ht=(ae===1?2:1)*(2-He));var oi=16*(Et+1),Di=16*(Xe+1)*(2-He);oi-=(Lt+mt)*Tr,Di-=(vt+Ut)*Ht;var zt=Math.ceil(oi*tr);return z.destroy(),z=null,{codec_mimetype:x,profile_idc:se,level_idc:te,profile_string:ie,level_string:le,chroma_format_idc:ae,bit_depth:Ce,bit_depth_luma:Ce,bit_depth_chroma:Me,ref_frames:pt,chroma_format:ce,chroma_format_string:D.getChromaFormatString(ce),frame_rate:{fixed:yt,fps:Nt,fps_den:Or,fps_num:Tn},sar_ratio:{width:tn,height:bt},codec_size:{width:oi,height:Di},present_size:{width:zt,height:Di}}},D._skipScalingList=function(A,w){for(var x=8,O=8,F=0;F<w;F++)O!==0&&(O=(x+A.readSEG()+256)%256),x=O===0?x:O},D.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"}},D.getLevelString=function(A){return(A/10).toFixed(1)},D.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"}},D}(),_=s(6),S=function(){function D(){}return D._ebsp2rbsp=function(A){for(var w=A,x=w.byteLength,O=new Uint8Array(x),F=0,$=0;$<x;$++)$>=2&&w[$]===3&&w[$-1]===0&&w[$-2]===0||(O[F]=w[$],F++);return new Uint8Array(O.buffer,0,F)},D.parseVPS=function(A){var w=D._ebsp2rbsp(A),x=new y(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()}},D.parseSPS=function(A){var w=D._ebsp2rbsp(A),x=new y(w);x.readByte(),x.readByte();for(var O=0,F=0,$=0,z=0,se=(x.readBits(4),x.readBits(3)),te=(x.readBool(),x.readBits(2)),ie=x.readBool(),le=x.readBits(5),ae=x.readByte(),ce=x.readByte(),Ce=x.readByte(),Me=x.readByte(),Le=x.readByte(),Je=x.readByte(),Ye=x.readByte(),Ve=x.readByte(),pt=x.readByte(),Et=x.readByte(),Xe=x.readByte(),He=[],Lt=[],mt=0;mt<se;mt++)He.push(x.readBool()),Lt.push(x.readBool());if(se>0)for(mt=se;mt<8;mt++)x.readBits(2);for(mt=0;mt<se;mt++)He[mt]&&(x.readByte(),x.readByte(),x.readByte(),x.readByte(),x.readByte(),x.readByte(),x.readByte(),x.readByte(),x.readByte(),x.readByte(),x.readByte()),Lt[mt]&&x.readByte();x.readUEG();var vt=x.readUEG();vt==3&&x.readBits(1);var Ut=x.readUEG(),tn=x.readUEG();x.readBool()&&(O+=x.readUEG(),F+=x.readUEG(),$+=x.readUEG(),z+=x.readUEG());var bt=x.readUEG(),Nt=x.readUEG(),yt=x.readUEG();for(mt=x.readBool()?0:se;mt<=se;mt++)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 Tn=0;Tn<4;Tn++)for(var Or=0;Or<(Tn===3?2:6);Or++)if(x.readBool()){var $n=Math.min(64,1<<4+(Tn<<1));for(Tn>1&&x.readSEG(),mt=0;mt<$n;mt++)x.readSEG()}else x.readUEG();x.readBool(),x.readBool(),x.readBool()&&(x.readByte(),x.readUEG(),x.readUEG(),x.readBool());var Nr=x.readUEG(),gr=0;for(mt=0;mt<Nr;mt++){var tr=!1;if(mt!==0&&(tr=x.readBool()),tr){mt===Nr&&x.readUEG(),x.readBool(),x.readUEG();for(var Tr=0,Ht=0;Ht<=gr;Ht++){var oi=x.readBool(),Di=!1;oi||(Di=x.readBool()),(oi||Di)&&Tr++}gr=Tr}else{var zt=x.readUEG(),Hh=x.readUEG();for(gr=zt+Hh,Ht=0;Ht<zt;Ht++)x.readUEG(),x.readBool();for(Ht=0;Ht<Hh;Ht++)x.readUEG(),x.readBool()}}if(x.readBool()){var l_=x.readUEG();for(mt=0;mt<l_;mt++){for(Ht=0;Ht<yt+4;Ht++)x.readBits(1);x.readBits(1)}}var Dm=0,yr=1,li=1,Zl=!1,ci=1,_u=1;if(x.readBool(),x.readBool(),x.readBool()){if(x.readBool()){var No=x.readByte();No>0&&No<=16?(yr=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][No-1],li=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][No-1]):No===255&&(yr=x.readBits(16),li=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()&&(ci=x.readBits(32),_u=x.readBits(32),x.readBool()&&x.readUEG(),x.readBool())){var Hn=!1,is=!1,ta=!1;for(Hn=x.readBool(),is=x.readBool(),(Hn||is)&&((ta=x.readBool())&&(x.readByte(),x.readBits(5),x.readBool(),x.readBits(5)),x.readBits(4),x.readBits(4),ta&&x.readBits(4),x.readBits(5),x.readBits(5),x.readBits(5)),mt=0;mt<=se;mt++){var Mo=x.readBool();Zl=Mo;var bu=!0,ui=1;Mo||(bu=x.readBool());var Om=!1;if(bu?x.readUEG():Om=x.readBool(),Om||(ui=x.readUEG()+1),Hn){for(Ht=0;Ht<ui;Ht++)x.readUEG(),x.readUEG(),ta&&(x.readUEG(),x.readUEG());x.readBool()}if(is){for(Ht=0;Ht<ui;Ht++)x.readUEG(),x.readUEG(),ta&&(x.readUEG(),x.readUEG());x.readBool()}}}x.readBool()&&(x.readBool(),x.readBool(),x.readBool(),Dm=x.readUEG(),x.readUEG(),x.readUEG(),x.readUEG(),x.readUEG())}x.readBool();var di="hvc1.".concat(le,".1.L").concat(Xe,".B0"),xu=Ut-(O+F)*(vt===1||vt===2?2:1),zh=tn-($+z)*(vt===1?2:1),Su=1;return yr!==1&&li!==1&&(Su=yr/li),x.destroy(),x=null,{codec_mimetype:di,profile_string:D.getProfileString(le),level_string:D.getLevelString(Xe),profile_idc:le,bit_depth:bt+8,ref_frames:1,chroma_format:vt,chroma_format_string:D.getChromaFormatString(vt),general_level_idc:Xe,general_profile_space:te,general_tier_flag:ie,general_profile_idc:le,general_profile_compatibility_flags_1:ae,general_profile_compatibility_flags_2:ce,general_profile_compatibility_flags_3:Ce,general_profile_compatibility_flags_4:Me,general_constraint_indicator_flags_1:Le,general_constraint_indicator_flags_2:Je,general_constraint_indicator_flags_3:Ye,general_constraint_indicator_flags_4:Ve,general_constraint_indicator_flags_5:pt,general_constraint_indicator_flags_6:Et,min_spatial_segmentation_idc:Dm,constant_frame_rate:0,chroma_format_idc:vt,bit_depth_luma_minus8:bt,bit_depth_chroma_minus8:Nt,frame_rate:{fixed:Zl,fps:_u/ci,fps_den:ci,fps_num:_u},sar_ratio:{width:yr,height:li},codec_size:{width:xu,height:zh},present_size:{width:xu*Su,height:zh}}},D.parsePPS=function(A){var w=D._ebsp2rbsp(A),x=new y(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 O=x.readBool(),F=x.readBool(),$=1;return F&&O?$=0:F?$=3:O&&($=2),{parallelismType:$}},D.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"}},D.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"}},D.getLevelString=function(A){return(A/30).toFixed(1)},D}();function E(D){return D.byteOffset%2==0&&D.byteLength%2==0}function L(D){return D.byteOffset%4==0&&D.byteLength%4==0}function U(D,A){for(var w=0;w<D.length;w++)if(D[w]!==A[w])return!1;return!0}var P=function(D,A){return D.byteLength===A.byteLength&&(L(D)&&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))}(D,A):E(D)&&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))}(D,A):function(w,x){return U(w,x)}(D,A))},I=function(){return(I=Object.assign||function(D){for(var A,w=1,x=arguments.length;w<x;w++)for(var O in A=arguments[w])Object.prototype.hasOwnProperty.call(A,O)&&(D[O]=A[O]);return D}).apply(this,arguments)},k=function(){function D(){}return D.parseOBUs=function(A,w){for(var x=0;x<A.byteLength;){var O=x,F=(A[x],(120&A[x])>>3),$=(4&A[x])!=0,z=(2&A[x])!=0;A[x],x+=1,$&&(x+=1);var se=Number.POSITIVE_INFINITY;if(z){se=0;for(var te=0;;te++){var ie=A[x++];if(se|=(127&ie)<<7*te,(128&ie)==0)break}}console.log(F),F===1?w=I(I({},D.parseSeuqneceHeader(A.subarray(x,x+se))),{sequence_header_data:A.subarray(O,x+se)}):(F==3&&w||F==6&&w)&&(w=D.parseOBUFrameHeader(A.subarray(x,x+se),0,0,w)),x+=se}return w},D.parseSeuqneceHeader=function(A){var w=new y(A),x=w.readBits(3),O=(w.readBool(),w.readBool()),F=!0,$=0,z=1,se=void 0,te=[];if(O)te.push({operating_point_idc:0,level:w.readBits(5),tier:0});else{if(w.readBool()){var ie=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)/(z=ie),F=ae,w.readBool()&&(w.readBits(5),w.readBits(32),se=w.readBits(5),w.readBits(5))}for(var Ce=w.readBool(),Me=w.readBits(5),Le=0;Le<=Me;Le++){var Je=w.readBits(12),Ye=w.readBits(5),Ve=Ye>7?w.readBits(1):0;te.push({operating_point_idc:Je,level:Ye,tier:Ve}),Ce&&w.readBool()&&w.readBits(4)}}var pt=te[0],Et=pt.level,Xe=pt.tier,He=w.readBits(4),Lt=w.readBits(4),mt=w.readBits(He+1)+1,vt=w.readBits(Lt+1)+1,Ut=!1;O||(Ut=w.readBool()),Ut&&(w.readBits(4),w.readBits(4)),w.readBool(),w.readBool(),w.readBool();var tn=!1,bt=2,Nt=2,yt=0;O||(w.readBool(),w.readBool(),w.readBool(),w.readBool(),(tn=w.readBool())&&(w.readBool(),w.readBool()),(bt=w.readBool()?2:w.readBits(1))?Nt=w.readBool()?2:w.readBits(1):Nt=2,tn?yt=w.readBits(3)+1:yt=0);var Tn=w.readBool(),Or=(w.readBool(),w.readBool(),w.readBool()),$n=8;x===2&&Or?$n=w.readBool()?12:10:$n=Or?10:8;var Nr=!1;x!==1&&(Nr=w.readBool()),w.readBool()&&(w.readBits(8),w.readBits(8),w.readBits(8));var gr=1,tr=1;return Nr?(w.readBits(1),gr=1,tr=1):(w.readBits(1),x==0?(gr=1,tr=1):x==1?(gr=0,tr=0):$n==12?w.readBits(1)&&w.readBits(1):(gr=1,tr=0),gr&&tr&&w.readBits(2),w.readBits(1)),w.readBool(),w.destroy(),w=null,{codec_mimetype:"av01.".concat(x,".").concat(D.getLevelString(Et,Xe),".").concat($n.toString(10).padStart(2,"0")),level:Et,tier:Xe,level_string:D.getLevelString(Et,Xe),profile_idc:x,profile_string:"".concat(x),bit_depth:$n,ref_frames:1,chroma_format:D.getChromaFormat(Nr,gr,tr),chroma_format_string:D.getChromaFormatString(Nr,gr,tr),sequence_header:{frame_id_numbers_present_flag:Ut,additional_frame_id_length_minus_1:void 0,delta_frame_id_length_minus_2:void 0,reduced_still_picture_header:O,decoder_model_info_present_flag:!1,operating_points:te,buffer_removal_time_length_minus_1:se,equal_picture_interval:F,seq_force_screen_content_tools:bt,seq_force_integer_mv:Nt,enable_order_hint:tn,order_hint_bits:yt,enable_superres:Tn,frame_width_bit:He+1,frame_height_bit:Lt+1,max_frame_width:mt,max_frame_height:vt},keyframe:void 0,frame_rate:{fixed:F,fps:$/z,fps_den:z,fps_num:$}}},D.parseOBUFrameHeader=function(A,w,x,O){var F=O.sequence_header,$=new y(A),z=(F.max_frame_width,F.max_frame_height,0);F.frame_id_numbers_present_flag&&(z=F.additional_frame_id_length_minus_1+F.delta_frame_id_length_minus_2+3);var se=0,te=!0,ie=!0,le=!1;if(!F.reduced_still_picture_header){if($.readBool())return O;te=(se=$.readBits(2))===2||se===0,(ie=$.readBool())&&F.decoder_model_info_present_flag&&F.equal_picture_interval,ie&&$.readBool(),le=!!(se===3||se===0&&ie)||$.readBool()}O.keyframe=te,$.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(z);var ce=!1;if(ce=se==3||!F.reduced_still_picture_header&&$.readBool(),$.readBits(F.order_hint_bits),te||le||$.readBits(3),F.decoder_model_info_present_flag&&$.readBool()){for(var Ce=0;Ce<=F.operating_points_cnt_minus_1;Ce++)if(F.operating_points[Ce].decoder_model_present_for_this_op[Ce]){var Me=F.operating_points[Ce].operating_point_idc;(Me===0||Me>>w&1&&Me>>x+8&1)&&$.readBits(F.buffer_removal_time_length_minus_1+1)}}var Le=255;if(se===3||se==0&&ie||(Le=$.readBits(8)),(te||Le!==255)&&le&&F.enable_order_hint)for(var Je=0;Je<8;Je++)$.readBits(F.order_hint_bits);if(te){var Ye=D.frameSizeAndRenderSize($,ce,F);O.codec_size={width:Ye.FrameWidth,height:Ye.FrameHeight},O.present_size={width:Ye.RenderWidth,height:Ye.RenderHeight},O.sar_ratio={width:Ye.RenderWidth/Ye.FrameWidth,height:Ye.RenderHeight/Ye.FrameHeight}}return $.destroy(),$=null,O},D.frameSizeAndRenderSize=function(A,w,x){var O=x.max_frame_width,F=x.max_frame_height;w&&(O=A.readBits(x.frame_width_bit)+1,F=A.readBits(x.frame_height_bit)+1);var $=!1;x.enable_superres&&($=A.readBool());var z=8;$&&(z=A.readBits(3)+9);var se=O;O=Math.floor((8*se+z/2)/z);var te=se,ie=F;if(A.readBool()){var le=A.readBits(16)+1,ae=A.readBits(16)+1;te=A.readBits(le)+1,ie=A.readBits(ae)+1}return{UpscaledWidth:se,FrameWidth:O,FrameHeight:F,RenderWidth:te,RenderHeight:ie}},D.getLevelString=function(A,w){return"".concat(A.toString(10).padStart(2,"0")).concat(w===0?"M":"H")},D.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},D.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"},D}(),R,M=function(){function D(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 D.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},D.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 O,F,$=(4&w[4])>>>2!=0,z=(1&w[4])!=0,se=(O=w)[F=5]<<24|O[F+1]<<16|O[F+2]<<8|O[F+3];return se<9?x:{match:!0,consumed:se,dataOffset:se,hasAudioTrack:$,hasVideoTrack:z}},D.prototype.bindDataSource=function(A){return A.onDataArrival=this.parseChunks.bind(this),this},Object.defineProperty(D.prototype,"onTrackMetadata",{get:function(){return this._onTrackMetadata},set:function(A){this._onTrackMetadata=A},enumerable:!1,configurable:!0}),Object.defineProperty(D.prototype,"onMediaInfo",{get:function(){return this._onMediaInfo},set:function(A){this._onMediaInfo=A},enumerable:!1,configurable:!0}),Object.defineProperty(D.prototype,"onMetaDataArrived",{get:function(){return this._onMetaDataArrived},set:function(A){this._onMetaDataArrived=A},enumerable:!1,configurable:!0}),Object.defineProperty(D.prototype,"onScriptDataArrived",{get:function(){return this._onScriptDataArrived},set:function(A){this._onScriptDataArrived=A},enumerable:!1,configurable:!0}),Object.defineProperty(D.prototype,"onError",{get:function(){return this._onError},set:function(A){this._onError=A},enumerable:!1,configurable:!0}),Object.defineProperty(D.prototype,"onDataAvailable",{get:function(){return this._onDataAvailable},set:function(A){this._onDataAvailable=A},enumerable:!1,configurable:!0}),Object.defineProperty(D.prototype,"timestampBase",{get:function(){return this._timestampBase},set:function(A){this._timestampBase=A},enumerable:!1,configurable:!0}),Object.defineProperty(D.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(D.prototype,"overridedHasAudio",{set:function(A){this._hasAudioFlagOverrided=!0,this._hasAudio=A,this._mediaInfo.hasAudio=A},enumerable:!1,configurable:!0}),Object.defineProperty(D.prototype,"overridedHasVideo",{set:function(A){this._hasVideoFlagOverrided=!0,this._hasVideo=A,this._mediaInfo.hasVideo=A},enumerable:!1,configurable:!0}),D.prototype.resetMediaInfo=function(){this._mediaInfo=new c.a},D.prototype._isInitialMetadataDispatched=function(){return this._hasAudio&&this._hasVideo?this._audioInitialMetadataDispatched&&this._videoInitialMetadataDispatched:this._hasAudio&&!this._hasVideo?this._audioInitialMetadataDispatched:!(this._hasAudio||!this._hasVideo)&&this._videoInitialMetadataDispatched},D.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,O=this._littleEndian;if(w===0){if(!(A.byteLength>13))return 0;x=D.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,!O)!==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),z=16777215&F.getUint32(0,!O);if(x+11+z+4>A.byteLength)break;if($===8||$===9||$===18){var se=F.getUint8(4),te=F.getUint8(5),ie=F.getUint8(6)|te<<8|se<<16|F.getUint8(7)<<24;16777215&F.getUint32(7,!O)&&o.a.w(this.TAG,"Meet tag which has StreamID != 0!");var le=x+11;switch($){case 8:this._parseAudioData(A,le,z,ie);break;case 9:this._parseVideoData(A,le,z,ie,w+x);break;case 18:this._parseScriptData(A,le,z)}var ae=F.getUint32(11+z,!O);ae!==11+z&&o.a.w(this.TAG,"Invalid PrevTagSize ".concat(ae)),x+=11+z+4}else o.a.w(this.TAG,"Unsupported tag type ".concat($,", skipped")),x+=11+z+4}return this._isInitialMetadataDispatched()&&this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack),x},D.prototype._parseScriptData=function(A,w,x){var O=g.parseScriptData(A,w,x);if(O.hasOwnProperty("onMetaData")){if(O.onMetaData==null||typeof O.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=O;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 z=Math.floor(1e3*F.framerate);if(z>0){var se=z/1e3;this._referenceFrameRate.fixed=!0,this._referenceFrameRate.fps=se,this._referenceFrameRate.fps_num=z,this._referenceFrameRate.fps_den=1e3,this._mediaInfo.fps=se}}if(typeof F.keyframes=="object"){this._mediaInfo.hasKeyframesIndex=!0;var te=F.keyframes;this._mediaInfo.keyframesIndex=this._parseKeyframesIndex(te),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(O).length>0&&this._onScriptDataArrived&&this._onScriptDataArrived(Object.assign({},O))},D.prototype._parseKeyframesIndex=function(A){for(var w=[],x=[],O=1;O<A.times.length;O++){var F=this._timestampBase+Math.floor(1e3*A.times[O]);w.push(F),x.push(A.filepositions[O])}return{times:w,filepositions:x}},D.prototype._parseAudioData=function(A,w,x,O){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 z=0,se=(12&F)>>>2;if(se>=0&&se<=4){z=this._flvSoundRateTable[se];var te=1&F,ie=this._audioMetadata,le=this._audioTrack;if(ie||(this._hasAudio===!1&&this._hasAudioFlagOverrided===!1&&(this._hasAudio=!0,this._mediaInfo.hasAudio=!0),(ie=this._audioMetadata={}).type="audio",ie.id=le.id,ie.timescale=this._timescale,ie.duration=this._duration,ie.audioSampleRate=z,ie.channelCount=te===0?1:2),$===10){var ae=this._parseAACAudioData(A,w+1,x-1);if(ae==null)return;if(ae.packetType===0){if(ie.config){if(P(ae.data.config,ie.config))return;o.a.w(this.TAG,"AudioSpecificConfig has been changed, re-generate initialization segment")}var ce=ae.data;ie.audioSampleRate=ce.samplingRate,ie.channelCount=ce.channelCount,ie.codec=ce.codec,ie.originalCodec=ce.originalCodec,ie.config=ce.config,ie.refSampleDuration=1024/ie.audioSampleRate*ie.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",ie),(Le=this._mediaInfo).audioCodec=ie.originalCodec,Le.audioSampleRate=ie.audioSampleRate,Le.audioChannelCount=ie.channelCount,Le.hasVideo?Le.videoCodec!=null&&(Le.mimeType='video/x-flv; codecs="'+Le.videoCodec+","+Le.audioCodec+'"'):Le.mimeType='video/x-flv; codecs="'+Le.audioCodec+'"',Le.isComplete()&&this._onMediaInfo(Le)}else if(ae.packetType===1){var Ce=this._timestampBase+O,Me={unit:ae.data,length:ae.data.byteLength,dts:Ce,pts:Ce};le.samples.push(Me),le.length+=ae.data.length}else o.a.e(this.TAG,"Flv: Unsupported AAC data type ".concat(ae.packetType))}else if($===2){if(!ie.codec){var Le;if((ce=this._parseMP3AudioData(A,w+1,x-1,!0))==null)return;ie.audioSampleRate=ce.samplingRate,ie.channelCount=ce.channelCount,ie.codec=ce.codec,ie.originalCodec=ce.originalCodec,ie.refSampleDuration=1152/ie.audioSampleRate*ie.timescale,o.a.v(this.TAG,"Parsed MPEG Audio Frame Header"),this._audioInitialMetadataDispatched=!0,this._onTrackMetadata("audio",ie),(Le=this._mediaInfo).audioCodec=ie.codec,Le.audioSampleRate=ie.audioSampleRate,Le.audioChannelCount=ie.channelCount,Le.audioDataRate=ce.bitRate,Le.hasVideo?Le.videoCodec!=null&&(Le.mimeType='video/x-flv; codecs="'+Le.videoCodec+","+Le.audioCodec+'"'):Le.mimeType='video/x-flv; codecs="'+Le.audioCodec+'"',Le.isComplete()&&this._onMediaInfo(Le)}var Je=this._parseMP3AudioData(A,w+1,x-1,!1);if(Je==null)return;Ce=this._timestampBase+O;var Ye={unit:Je,length:Je.byteLength,dts:Ce,pts:Ce};le.samples.push(Ye),le.length+=Je.length}}else this._onError(_.a.FORMAT_ERROR,"Flv: Invalid audio sample rate idx: "+se)}else this._onError(_.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 Ve=15&F,pt=String.fromCharCode.apply(String,new Uint8Array(A,w,x).slice(1,5));switch(pt){case"Opus":this._parseOpusAudioPacket(A,w+5,x-5,O,Ve);break;case"fLaC":this._parseFlacAudioPacket(A,w+5,x-5,O,Ve);break;default:this._onError(_.a.CODEC_UNSUPPORTED,"Flv: Unsupported audio codec: "+pt)}}}},D.prototype._parseAACAudioData=function(A,w,x){if(!(x<=1)){var O={},F=new Uint8Array(A,w,x);return O.packetType=F[0],F[0]===0?O.data=this._parseAACAudioSpecificConfig(A,w+1,x-1):O.data=F.subarray(1),O}o.a.w(this.TAG,"Flv: Invalid AAC packet, missing AACPacketType or/and Data!")},D.prototype._parseAACAudioSpecificConfig=function(A,w,x){var O,F,$=new Uint8Array(A,w,x),z=null,se=0,te=null;if(se=O=$[0]>>>3,(F=(7&$[0])<<1|$[1]>>>7)<0||F>=this._mpegSamplingRates.length)this._onError(_.a.FORMAT_ERROR,"Flv: AAC invalid sampling frequency index!");else{var ie=this._mpegSamplingRates[F],le=(120&$[1])>>>3;if(!(le<0||le>=8)){se===5&&(te=(7&$[1])<<1|$[2]>>>7,(124&$[2])>>>2);var ae=self.navigator.userAgent.toLowerCase();return ae.indexOf("firefox")!==-1?F>=6?(se=5,z=new Array(4),te=F-3):(se=2,z=new Array(2),te=F):ae.indexOf("android")!==-1?(se=2,z=new Array(2),te=F):(se=5,te=F,z=new Array(4),F>=6?te=F-3:le===1&&(se=2,z=new Array(2),te=F)),z[0]=se<<3,z[0]|=(15&F)>>>1,z[1]=(15&F)<<7,z[1]|=(15&le)<<3,se===5&&(z[1]|=(15&te)>>>1,z[2]=(1&te)<<7,z[2]|=8,z[3]=0),{config:z,samplingRate:ie,channelCount:le,codec:"mp4a.40."+se,originalCodec:"mp4a.40."+O}}this._onError(_.a.FORMAT_ERROR,"Flv: AAC invalid channel configuration")}},D.prototype._parseMP3AudioData=function(A,w,x,O){if(!(x<4)){this._littleEndian;var F=new Uint8Array(A,w,x),$=null;if(O){if(F[0]!==255)return;var z=F[1]>>>3&3,se=(6&F[1])>>1,te=(240&F[2])>>>4,ie=(12&F[2])>>>2,le=(F[3]>>>6&3)!==3?2:1,ae=0,ce=0;switch(z){case 0:ae=this._mpegAudioV25SampleRateTable[ie];break;case 2:ae=this._mpegAudioV20SampleRateTable[ie];break;case 3:ae=this._mpegAudioV10SampleRateTable[ie]}switch(se){case 1:te<this._mpegAudioL3BitRateTable.length&&(ce=this._mpegAudioL3BitRateTable[te]);break;case 2:te<this._mpegAudioL2BitRateTable.length&&(ce=this._mpegAudioL2BitRateTable[te]);break;case 3:te<this._mpegAudioL1BitRateTable.length&&(ce=this._mpegAudioL1BitRateTable[te])}$={bitRate:ce,samplingRate:ae,channelCount:le,codec:"mp3",originalCodec:"mp3"}}else $=F;return $}o.a.w(this.TAG,"Flv: Invalid MP3 packet, header missing!")},D.prototype._parseOpusAudioPacket=function(A,w,x,O,F){if(F===0)this._parseOpusSequenceHeader(A,w,x);else if(F===1)this._parseOpusAudioData(A,w,x,O);else if(F!==2)return void this._onError(_.a.FORMAT_ERROR,"Flv: Invalid video packet type ".concat(F))},D.prototype._parseOpusSequenceHeader=function(A,w,x){if(x<=16)o.a.w(this.TAG,"Flv: Invalid OpusSequenceHeader, lack of data!");else{var O=this._audioMetadata,F=this._audioTrack;O||(this._hasAudio===!1&&this._hasAudioFlagOverrided===!1&&(this._hasAudio=!0,this._mediaInfo.hasAudio=!0),(O=this._audioMetadata={}).type="audio",O.id=F.id,O.timescale=this._timescale,O.duration=this._duration);var $=new DataView(A,w,x);$.setUint8(8,0);var z=$.getUint8(9);$.setUint16(10,$.getUint16(10,!0),!1);var se=$.getUint32(12,!0);$.setUint32(12,$.getUint32(12,!0),!1);var te={config:new Uint8Array(A,w+8,x-8),channelCount:z,samplingFrequence:se,codec:"opus",originalCodec:"opus"};if(O.config){if(P(te.config,O.config))return;o.a.w(this.TAG,"OpusSequenceHeader has been changed, re-generate initialization segment")}O.audioSampleRate=te.samplingFrequence,O.channelCount=te.channelCount,O.codec=te.codec,O.originalCodec=te.originalCodec,O.config=te.config,O.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",O);var ie=this._mediaInfo;ie.audioCodec=O.originalCodec,ie.audioSampleRate=O.audioSampleRate,ie.audioChannelCount=O.channelCount,ie.hasVideo?ie.videoCodec!=null&&(ie.mimeType='video/x-flv; codecs="'+ie.videoCodec+","+ie.audioCodec+'"'):ie.mimeType='video/x-flv; codecs="'+ie.audioCodec+'"',ie.isComplete()&&this._onMediaInfo(ie)}},D.prototype._parseOpusAudioData=function(A,w,x,O){var F=this._audioTrack,$=new Uint8Array(A,w,x),z=this._timestampBase+O,se={unit:$,length:$.byteLength,dts:z,pts:z};F.samples.push(se),F.length+=$.length},D.prototype._parseFlacAudioPacket=function(A,w,x,O,F){if(F===0)this._parseFlacSequenceHeader(A,w,x);else if(F===1)this._parseFlacAudioData(A,w,x,O);else if(F!==2)return void this._onError(_.a.FORMAT_ERROR,"Flv: Invalid Flac audio packet type ".concat(F))},D.prototype._parseFlacSequenceHeader=function(A,w,x){var O=this._audioMetadata,F=this._audioTrack;O||(this._hasAudio===!1&&this._hasAudioFlagOverrided===!1&&(this._hasAudio=!0,this._mediaInfo.hasAudio=!0),(O=this._audioMetadata={}).type="audio",O.id=F.id,O.timescale=this._timescale,O.duration=this._duration);var $=new Uint8Array(A,w+4,x-4),z=new y($),se=z.readBits(16),te=z.readBits(16),ie=te===se?te:null;z.readBits(24),z.readBits(24);var le=z.readBits(20),ae=z.readBits(3)+1,ce=z.readBits(5)+1;z.destroy();var Ce=new Uint8Array($.byteLength+4);Ce.set($,4),Ce[0]=128,Ce[1]=$.byteLength>>>16&255,Ce[2]=$.byteLength>>>8&255,Ce[3]=$.byteLength>>>0&255;var Me={config:Ce,channelCount:ae,samplingFrequence:le,sampleSize:ce,codec:"flac",originalCodec:"flac"};if(O.config){if(P(Me.config,O.config))return;o.a.w(this.TAG,"FlacSequenceHeader has been changed, re-generate initialization segment")}O.audioSampleRate=Me.samplingFrequence,O.channelCount=Me.channelCount,O.sampleSize=Me.sampleSize,O.codec=Me.codec,O.originalCodec=Me.originalCodec,O.config=Me.config,O.refSampleDuration=ie!=null?1e3*ie/Me.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",O);var Le=this._mediaInfo;Le.audioCodec=O.originalCodec,Le.audioSampleRate=O.audioSampleRate,Le.audioChannelCount=O.channelCount,Le.hasVideo?Le.videoCodec!=null&&(Le.mimeType='video/x-flv; codecs="'+Le.videoCodec+","+Le.audioCodec+'"'):Le.mimeType='video/x-flv; codecs="'+Le.audioCodec+'"',Le.isComplete()&&this._onMediaInfo(Le)},D.prototype._parseFlacAudioData=function(A,w,x,O){var F=this._audioTrack,$=new Uint8Array(A,w,x),z=this._timestampBase+O,se={unit:$,length:$.byteLength,dts:z,pts:z};F.samples.push(se),F.length+=$.length},D.prototype._parseVideoData=function(A,w,x,O,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],z=(112&$)>>>4;if(128&$){var se=15&$,te=String.fromCharCode.apply(String,new Uint8Array(A,w,x).slice(1,5));if(te==="hvc1")this._parseEnhancedHEVCVideoPacket(A,w+5,x-5,O,F,z,se);else{if(te!=="av01")return void this._onError(_.a.CODEC_UNSUPPORTED,"Flv: Unsupported codec in video frame: ".concat(te));this._parseEnhancedAV1VideoPacket(A,w+5,x-5,O,F,z,se)}}else{var ie=15&$;if(ie===7)this._parseAVCVideoPacket(A,w+1,x-1,O,F,z);else{if(ie!==12)return void this._onError(_.a.CODEC_UNSUPPORTED,"Flv: Unsupported codec in video frame: ".concat(ie));this._parseHEVCVideoPacket(A,w+1,x-1,O,F,z)}}}},D.prototype._parseAVCVideoPacket=function(A,w,x,O,F,$){if(x<4)o.a.w(this.TAG,"Flv: Invalid AVC packet, missing AVCPacketType or/and CompositionTime");else{var z=this._littleEndian,se=new DataView(A,w,x),te=se.getUint8(0),ie=(16777215&se.getUint32(0,!z))<<8>>8;if(te===0)this._parseAVCDecoderConfigurationRecord(A,w+4,x-4);else if(te===1)this._parseAVCVideoData(A,w+4,x-4,O,F,$,ie);else if(te!==2)return void this._onError(_.a.FORMAT_ERROR,"Flv: Invalid video packet type ".concat(te))}},D.prototype._parseHEVCVideoPacket=function(A,w,x,O,F,$){if(x<4)o.a.w(this.TAG,"Flv: Invalid HEVC packet, missing HEVCPacketType or/and CompositionTime");else{var z=this._littleEndian,se=new DataView(A,w,x),te=se.getUint8(0),ie=(16777215&se.getUint32(0,!z))<<8>>8;if(te===0)this._parseHEVCDecoderConfigurationRecord(A,w+4,x-4);else if(te===1)this._parseHEVCVideoData(A,w+4,x-4,O,F,$,ie);else if(te!==2)return void this._onError(_.a.FORMAT_ERROR,"Flv: Invalid video packet type ".concat(te))}},D.prototype._parseEnhancedHEVCVideoPacket=function(A,w,x,O,F,$,z){var se=this._littleEndian,te=new DataView(A,w,x);if(z===0)this._parseHEVCDecoderConfigurationRecord(A,w,x);else if(z===1){var ie=(4294967040&te.getUint32(0,!se))>>8;this._parseHEVCVideoData(A,w+3,x-3,O,F,$,ie)}else if(z===3)this._parseHEVCVideoData(A,w,x,O,F,$,0);else if(z!==2)return void this._onError(_.a.FORMAT_ERROR,"Flv: Invalid video packet type ".concat(z))},D.prototype._parseEnhancedAV1VideoPacket=function(A,w,x,O,F,$,z){if(this._littleEndian,z===0)this._parseAV1CodecConfigurationRecord(A,w,x);else if(z===1)this._parseAV1VideoData(A,w,x,O,F,$,0);else{if(z===5)return void this._onError(_.a.FORMAT_ERROR,"Flv: Not Supported MP2T AV1 video packet type ".concat(z));if(z!==2)return void this._onError(_.a.FORMAT_ERROR,"Flv: Invalid video packet type ".concat(z))}},D.prototype._parseAVCDecoderConfigurationRecord=function(A,w,x){if(x<7)o.a.w(this.TAG,"Flv: Invalid AVCDecoderConfigurationRecord, lack of data!");else{var O=this._videoMetadata,F=this._videoTrack,$=this._littleEndian,z=new DataView(A,w,x);if(O){if(O.avcc!==void 0){var se=new Uint8Array(A,w,x);if(P(se,O.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),(O=this._videoMetadata={}).type="video",O.id=F.id,O.timescale=this._timescale,O.duration=this._duration;var te=z.getUint8(0),ie=z.getUint8(1);if(z.getUint8(2),z.getUint8(3),te===1&&ie!==0)if(this._naluLengthSize=1+(3&z.getUint8(4)),this._naluLengthSize===3||this._naluLengthSize===4){var le=31&z.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 Ce=z.getUint16(ae,!$);if(ae+=2,Ce!==0){var Me=new Uint8Array(A,w+ae,Ce);ae+=Ce;var Le=v.parseSPS(Me);if(ce===0){O.codecWidth=Le.codec_size.width,O.codecHeight=Le.codec_size.height,O.presentWidth=Le.present_size.width,O.presentHeight=Le.present_size.height,O.profile=Le.profile_string,O.level=Le.level_string,O.bitDepth=Le.bit_depth,O.chromaFormat=Le.chroma_format,O.sarRatio=Le.sar_ratio,O.frameRate=Le.frame_rate,Le.frame_rate.fixed!==!1&&Le.frame_rate.fps_num!==0&&Le.frame_rate.fps_den!==0||(O.frameRate=this._referenceFrameRate);var Je=O.frameRate.fps_den,Ye=O.frameRate.fps_num;O.refSampleDuration=O.timescale*(Je/Ye);for(var Ve=Me.subarray(1,4),pt="avc1.",Et=0;Et<3;Et++){var Xe=Ve[Et].toString(16);Xe.length<2&&(Xe="0"+Xe),pt+=Xe}O.codec=pt;var He=this._mediaInfo;He.width=O.codecWidth,He.height=O.codecHeight,He.fps=O.frameRate.fps,He.profile=O.profile,He.level=O.level,He.refFrames=Le.ref_frames,He.chromaFormat=Le.chroma_format_string,He.sarNum=O.sarRatio.width,He.sarDen=O.sarRatio.height,He.videoCodec=pt,He.hasAudio?He.audioCodec!=null&&(He.mimeType='video/x-flv; codecs="'+He.videoCodec+","+He.audioCodec+'"'):He.mimeType='video/x-flv; codecs="'+He.videoCodec+'"',He.isComplete()&&this._onMediaInfo(He)}}}var Lt=z.getUint8(ae);if(Lt!==0){for(Lt>1&&o.a.w(this.TAG,"Flv: Strange AVCDecoderConfigurationRecord: PPS Count = ".concat(Lt)),ae++,ce=0;ce<Lt;ce++)Ce=z.getUint16(ae,!$),ae+=2,Ce!==0&&(ae+=Ce);O.avcc=new Uint8Array(x),O.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",O)}else this._onError(_.a.FORMAT_ERROR,"Flv: Invalid AVCDecoderConfigurationRecord: No PPS")}else this._onError(_.a.FORMAT_ERROR,"Flv: Invalid AVCDecoderConfigurationRecord: No SPS")}else this._onError(_.a.FORMAT_ERROR,"Flv: Strange NaluLengthSizeMinusOne: ".concat(this._naluLengthSize-1));else this._onError(_.a.FORMAT_ERROR,"Flv: Invalid AVCDecoderConfigurationRecord")}},D.prototype._parseHEVCDecoderConfigurationRecord=function(A,w,x){if(x<22)o.a.w(this.TAG,"Flv: Invalid HEVCDecoderConfigurationRecord, lack of data!");else{var O=this._videoMetadata,F=this._videoTrack,$=this._littleEndian,z=new DataView(A,w,x);if(O){if(O.hvcc!==void 0){var se=new Uint8Array(A,w,x);if(P(se,O.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),(O=this._videoMetadata={}).type="video",O.id=F.id,O.timescale=this._timescale,O.duration=this._duration;var te=z.getUint8(0),ie=31&z.getUint8(1);if(te!==0&&te!==1||ie===0)this._onError(_.a.FORMAT_ERROR,"Flv: Invalid HEVCDecoderConfigurationRecord");else if(this._naluLengthSize=1+(3&z.getUint8(21)),this._naluLengthSize===3||this._naluLengthSize===4){for(var le=z.getUint8(22),ae=0,ce=23;ae<le;ae++){var Ce=63&z.getUint8(ce+0),Me=z.getUint16(ce+1,!$);ce+=3;for(var Le=0;Le<Me;Le++){var Je=z.getUint16(ce+0,!$);if(Le===0)if(Ce===33){ce+=2;var Ye=new Uint8Array(A,w+ce,Je),Ve=S.parseSPS(Ye);O.codecWidth=Ve.codec_size.width,O.codecHeight=Ve.codec_size.height,O.presentWidth=Ve.present_size.width,O.presentHeight=Ve.present_size.height,O.profile=Ve.profile_string,O.level=Ve.level_string,O.bitDepth=Ve.bit_depth,O.chromaFormat=Ve.chroma_format,O.sarRatio=Ve.sar_ratio,O.frameRate=Ve.frame_rate,Ve.frame_rate.fixed!==!1&&Ve.frame_rate.fps_num!==0&&Ve.frame_rate.fps_den!==0||(O.frameRate=this._referenceFrameRate);var pt=O.frameRate.fps_den,Et=O.frameRate.fps_num;O.refSampleDuration=O.timescale*(pt/Et),O.codec=Ve.codec_mimetype;var Xe=this._mediaInfo;Xe.width=O.codecWidth,Xe.height=O.codecHeight,Xe.fps=O.frameRate.fps,Xe.profile=O.profile,Xe.level=O.level,Xe.refFrames=Ve.ref_frames,Xe.chromaFormat=Ve.chroma_format_string,Xe.sarNum=O.sarRatio.width,Xe.sarDen=O.sarRatio.height,Xe.videoCodec=Ve.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}}O.hvcc=new Uint8Array(x),O.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",O)}else this._onError(_.a.FORMAT_ERROR,"Flv: Strange NaluLengthSizeMinusOne: ".concat(this._naluLengthSize-1))}},D.prototype._parseAV1CodecConfigurationRecord=function(A,w,x){if(x<4)o.a.w(this.TAG,"Flv: Invalid AV1CodecConfigurationRecord, lack of data!");else{var O=this._videoMetadata,F=this._videoTrack,$=(this._littleEndian,new DataView(A,w,x));O?O.av1c!==void 0&&o.a.w(this.TAG,"Found another AV1CodecConfigurationRecord!"):(this._hasVideo===!1&&this._hasVideoFlagOverrided===!1&&(this._hasVideo=!0,this._mediaInfo.hasVideo=!0),(O=this._videoMetadata={}).type="video",O.id=F.id,O.timescale=this._timescale,O.duration=this._duration);var z=127&$.getUint8(0);if($.getUint8(1),$.getUint8(1),$.getUint8(2),z===1){var se=k.parseOBUs(new Uint8Array(A,w+4,x-4));if(se!=null){O.profile=se.profile_string,O.level=se.level_string,O.bitDepth=se.bit_depth,O.chromaFormat=se.chroma_format,O.frameRate=se.frame_rate,se.frame_rate.fixed!==!1&&se.frame_rate.fps_num!==0&&se.frame_rate.fps_den!==0||(O.frameRate=this._referenceFrameRate);var te=O.frameRate.fps_den,ie=O.frameRate.fps_num;O.refSampleDuration=O.timescale*(te/ie),O.codec=se.codec_mimetype,O.extra=se;var le=this._mediaInfo;le.fps=O.frameRate.fps,le.profile=O.profile,le.level=O.level,le.refFrames=se.ref_frames,le.chromaFormat=se.chroma_format_string,le.videoCodec=se.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),O.av1c=new Uint8Array(x),O.av1c.set(new Uint8Array(A,w,x),0),o.a.v(this.TAG,"Preparing AV1CodecConfigurationRecord")}else this._onError(_.a.FORMAT_ERROR,"Flv: Invalid AV1CodecConfigurationRecord")}else this._onError(_.a.FORMAT_ERROR,"Flv: Invalid AV1CodecConfigurationRecord")}},D.prototype._parseAVCVideoData=function(A,w,x,O,F,$,z){for(var se=this._littleEndian,te=new DataView(A,w,x),ie=[],le=0,ae=0,ce=this._naluLengthSize,Ce=this._timestampBase+O,Me=$===1;ae<x;){if(ae+4>=x){o.a.w(this.TAG,"Malformed Nalu near timestamp ".concat(Ce,", offset = ").concat(ae,", dataSize = ").concat(x));break}var Le=te.getUint32(ae,!se);if(ce===3&&(Le>>>=8),Le>x-ce)return void o.a.w(this.TAG,"Malformed Nalus near timestamp ".concat(Ce,", NaluSize > DataSize!"));var Je=31&te.getUint8(ae+ce);Je===5&&(Me=!0);var Ye=new Uint8Array(A,w+ae,ce+Le),Ve={type:Je,data:Ye};ie.push(Ve),le+=Ye.byteLength,ae+=ce+Le}if(ie.length){var pt=this._videoTrack,Et={units:ie,length:le,isKeyframe:Me,dts:Ce,cts:z,pts:Ce+z};Me&&(Et.fileposition=F),pt.samples.push(Et),pt.length+=le}},D.prototype._parseHEVCVideoData=function(A,w,x,O,F,$,z){for(var se=this._littleEndian,te=new DataView(A,w,x),ie=[],le=0,ae=0,ce=this._naluLengthSize,Ce=this._timestampBase+O,Me=$===1;ae<x;){if(ae+4>=x){o.a.w(this.TAG,"Malformed Nalu near timestamp ".concat(Ce,", offset = ").concat(ae,", dataSize = ").concat(x));break}var Le=te.getUint32(ae,!se);if(ce===3&&(Le>>>=8),Le>x-ce)return void o.a.w(this.TAG,"Malformed Nalus near timestamp ".concat(Ce,", NaluSize > DataSize!"));var Je=te.getUint8(ae+ce)>>1&63;Je!==19&&Je!==20&&Je!==21||(Me=!0);var Ye=new Uint8Array(A,w+ae,ce+Le),Ve={type:Je,data:Ye};ie.push(Ve),le+=Ye.byteLength,ae+=ce+Le}if(ie.length){var pt=this._videoTrack,Et={units:ie,length:le,isKeyframe:Me,dts:Ce,cts:z,pts:Ce+z};Me&&(Et.fileposition=F),pt.samples.push(Et),pt.length+=le}},D.prototype._parseAV1VideoData=function(A,w,x,O,F,$,z){this._littleEndian;var se,te=[],ie=this._timestampBase+O,le=$===1;if(le){var ae=this._videoMetadata,ce=k.parseOBUs(new Uint8Array(A,w,x),ae.extra);if(ce==null)return void this._onError(_.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 Ce=this._mediaInfo;Ce.width=ae.codecWidth,Ce.height=ae.codecHeight,Ce.sarNum=ae.sarRatio.width,Ce.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(se=x,te.push({unitType:0,data:new Uint8Array(A,w+0,x)}),te.length){var Me=this._videoTrack,Le={units:te,length:se,isKeyframe:le,dts:ie,cts:z,pts:ie+z};le&&(Le.fileposition=F),Me.samples.push(Le),Me.length+=se}},D}(),G=function(){function D(){}return D.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},D}(),Y=function(){this.program_pmt_pid={}};(function(D){D[D.kMPEG1Audio=3]="kMPEG1Audio",D[D.kMPEG2Audio=4]="kMPEG2Audio",D[D.kPESPrivateData=6]="kPESPrivateData",D[D.kADTSAAC=15]="kADTSAAC",D[D.kLOASAAC=17]="kLOASAAC",D[D.kAC3=129]="kAC3",D[D.kEAC3=135]="kEAC3",D[D.kMetadata=21]="kMetadata",D[D.kSCTE35=134]="kSCTE35",D[D.kH264=27]="kH264",D[D.kH265=36]="kH265"})(R||(R={}));var q,X=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={}},Z=function(){},oe=function(){},ne=function(){this.slices=[],this.total_length=0,this.expected_length=0,this.file_position=0};(function(D){D[D.kUnspecified=0]="kUnspecified",D[D.kSliceNonIDR=1]="kSliceNonIDR",D[D.kSliceDPA=2]="kSliceDPA",D[D.kSliceDPB=3]="kSliceDPB",D[D.kSliceDPC=4]="kSliceDPC",D[D.kSliceIDR=5]="kSliceIDR",D[D.kSliceSEI=6]="kSliceSEI",D[D.kSliceSPS=7]="kSliceSPS",D[D.kSlicePPS=8]="kSlicePPS",D[D.kSliceAUD=9]="kSliceAUD",D[D.kEndOfSequence=10]="kEndOfSequence",D[D.kEndOfStream=11]="kEndOfStream",D[D.kFiller=12]="kFiller",D[D.kSPSExt=13]="kSPSExt",D[D.kReserved0=14]="kReserved0"})(q||(q={}));var H,K,J=function(){},Q=function(D){var A=D.data.byteLength;this.type=D.type,this.data=new Uint8Array(4+A),new DataView(this.data.buffer).setUint32(0,A),this.data.set(D.data,4)},ve=function(){function D(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 D.prototype.findNextStartCodeOffset=function(A){for(var w=A,x=this.data_;;){if(w+3>=x.byteLength)return this.eof_flag_=!0,x.byteLength;var O=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(O===1||F===1)return w;w++}},D.prototype.readNextNaluPayload=function(){for(var A=this.data_,w=null;w==null&&!this.eof_flag_;){var x=this.current_startcode_offset_,O=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_=$,!(O>=q.kReserved0)&&F===0){var z=A.subarray(x,$);(w=new J).type=O,w.data=z}}return w},D}(),Te=function(){function D(A,w,x){var O=8+A.byteLength+1+2+w.byteLength,F=!1;A[3]!==66&&A[3]!==77&&A[3]!==88&&(F=!0,O+=4);var $=this.data=new Uint8Array(O);$[0]=1,$[1]=A[1],$[2]=A[2],$[3]=A[3],$[4]=255,$[5]=225;var z=A.byteLength;$[6]=z>>>8,$[7]=255&z;var se=8;$.set(A,8),$[se+=z]=1;var te=w.byteLength;$[se+1]=te>>>8,$[se+2]=255&te,$.set(w,se+3),se+=3+te,F&&($[se]=252|x.chroma_format_idc,$[se+1]=248|x.bit_depth_luma-8,$[se+2]=248|x.bit_depth_chroma-8,$[se+3]=0,se+=4)}return D.prototype.getData=function(){return this.data},D}();(function(D){D[D.kNull=0]="kNull",D[D.kAACMain=1]="kAACMain",D[D.kAAC_LC=2]="kAAC_LC",D[D.kAAC_SSR=3]="kAAC_SSR",D[D.kAAC_LTP=4]="kAAC_LTP",D[D.kAAC_SBR=5]="kAAC_SBR",D[D.kAAC_Scalable=6]="kAAC_Scalable",D[D.kLayer1=32]="kLayer1",D[D.kLayer2=33]="kLayer2",D[D.kLayer3=34]="kLayer3"})(H||(H={})),function(D){D[D.k96000Hz=0]="k96000Hz",D[D.k88200Hz=1]="k88200Hz",D[D.k64000Hz=2]="k64000Hz",D[D.k48000Hz=3]="k48000Hz",D[D.k44100Hz=4]="k44100Hz",D[D.k32000Hz=5]="k32000Hz",D[D.k24000Hz=6]="k24000Hz",D[D.k22050Hz=7]="k22050Hz",D[D.k16000Hz=8]="k16000Hz",D[D.k12000Hz=9]="k12000Hz",D[D.k11025Hz=10]="k11025Hz",D[D.k8000Hz=11]="k8000Hz",D[D.k7350Hz=12]="k7350Hz"}(K||(K={}));var Ne,Ke,be=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Pe=(Ne=function(D,A){return(Ne=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(w,x){w.__proto__=x}||function(w,x){for(var O in x)Object.prototype.hasOwnProperty.call(x,O)&&(w[O]=x[O])})(D,A)},function(D,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=D}Ne(D,A),D.prototype=A===null?Object.create(A):(w.prototype=A.prototype,new w)}),Ae=function(){},we=function(D){function A(){return D!==null&&D.apply(this,arguments)||this}return Pe(A,D),A}(Ae),Ue=function(){function D(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 D.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++}},D.prototype.readNextAACFrame=function(){for(var A=this.data_,w=null;w==null&&!this.eof_flag_;){var x=this.current_syncword_offset_,O=(8&A[x+1])>>>3,F=(6&A[x+1])>>>1,$=1&A[x+1],z=(192&A[x+2])>>>6,se=(60&A[x+2])>>>2,te=(1&A[x+2])<<2|(192&A[x+3])>>>6,ie=(3&A[x+3])<<11|A[x+4]<<3|(224&A[x+5])>>>5;if(A[x+6],x+ie>this.data_.byteLength){this.eof_flag_=!0,this.has_last_incomplete_data=!0;break}var le=$===1?7:9,ae=ie-le;x+=le;var ce=this.findNextSyncwordOffset(x+ae);if(this.current_syncword_offset_=ce,(O===0||O===1)&&F===0){var Ce=A.subarray(x,x+ae);(w=new Ae).audio_object_type=z+1,w.sampling_freq_index=se,w.sampling_frequency=be[se],w.channel_config=te,w.data=Ce}}return w},D.prototype.hasIncompleteData=function(){return this.has_last_incomplete_data},D.prototype.getIncompleteData=function(){return this.has_last_incomplete_data?this.data_.subarray(this.current_syncword_offset_):null},D}(),Oe=function(){function D(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 D.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++}},D.prototype.getLATMValue=function(A){for(var w=A.readBits(2),x=0,O=0;O<=w;O++)x<<=8,x|=A.readByte();return x},D.prototype.readNextAACFrame=function(A){for(var w=this.data_,x=null;x==null&&!this.eof_flag_;){var O=this.current_syncword_offset_,F=(31&w[O+1])<<8|w[O+2];if(O+3+F>=this.data_.byteLength){this.eof_flag_=!0,this.has_last_incomplete_data=!0;break}var $=new y(w.subarray(O+3,O+3+F)),z=null;if($.readBool()){if(A==null){o.a.w(this.TAG,"StreamMuxConfig Missing"),this.current_syncword_offset_=this.findNextSyncwordOffset(O+3+F),$.destroy();continue}z=A}else{var se=$.readBool();if(se&&$.readBool()){o.a.e(this.TAG,"audioMuxVersionA is Not Supported"),$.destroy();break}if(se&&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 te=se?this.getLATMValue($):0,ie=$.readBits(5);te-=5;var le=$.readBits(4);te-=4;var ae=$.readBits(4);te-=4,$.readBits(3),(te-=3)>0&&$.readBits(te);var ce=$.readBits(3);if(ce!==0){o.a.e(this.TAG,"frameLengthType = ".concat(ce,". Only frameLengthType = 0 Supported")),$.destroy();break}$.readByte();var Ce=$.readBool();if(Ce)if(se)this.getLATMValue($);else{for(var Me=0;;){Me<<=8;var Le=$.readBool();if(Me+=$.readByte(),!Le)break}console.log(Me)}$.readBool()&&$.readByte(),(z=new we).audio_object_type=ie,z.sampling_freq_index=le,z.sampling_frequency=be[z.sampling_freq_index],z.channel_config=ae,z.other_data_present=Ce}for(var Je=0;;){var Ye=$.readByte();if(Je+=Ye,Ye!==255)break}for(var Ve=new Uint8Array(Je),pt=0;pt<Je;pt++)Ve[pt]=$.readByte();(x=new we).audio_object_type=z.audio_object_type,x.sampling_freq_index=z.sampling_freq_index,x.sampling_frequency=be[z.sampling_freq_index],x.channel_config=z.channel_config,x.other_data_present=z.other_data_present,x.data=Ve,this.current_syncword_offset_=this.findNextSyncwordOffset(O+3+F)}return x},D.prototype.hasIncompleteData=function(){return this.has_last_incomplete_data},D.prototype.getIncompleteData=function(){return this.has_last_incomplete_data?this.data_.subarray(this.current_syncword_offset_):null},D}(),Dt=function(D){var A=null,w=D.audio_object_type,x=D.audio_object_type,O=D.sampling_freq_index,F=D.channel_config,$=0,z=navigator.userAgent.toLowerCase();z.indexOf("firefox")!==-1?O>=6?(x=5,A=new Array(4),$=O-3):(x=2,A=new Array(2),$=O):z.indexOf("android")!==-1?(x=2,A=new Array(2),$=O):(x=5,$=O,A=new Array(4),O>=6?$=O-3:F===1&&(x=2,A=new Array(2),$=O)),A[0]=x<<3,A[0]|=(15&O)>>>1,A[1]=(15&O)<<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=be[O],this.channel_count=F,this.codec_mimetype="mp4a.40."+x,this.original_codec_mimetype="mp4a.40."+w},en=function(){},wn=function(){};(function(D){D[D.kSpliceNull=0]="kSpliceNull",D[D.kSpliceSchedule=4]="kSpliceSchedule",D[D.kSpliceInsert=5]="kSpliceInsert",D[D.kTimeSignal=6]="kTimeSignal",D[D.kBandwidthReservation=7]="kBandwidthReservation",D[D.kPrivateCommand=255]="kPrivateCommand"})(Ke||(Ke={}));var it,nn=function(D){var A=D.readBool();return A?(D.readBits(6),{time_specified_flag:A,pts_time:4*D.readBits(31)+D.readBits(2)}):(D.readBits(7),{time_specified_flag:A})},mn=function(D){var A=D.readBool();return D.readBits(6),{auto_return:A,duration:4*D.readBits(31)+D.readBits(2)}},On=function(D,A){var w=A.readBits(8);return D?{component_tag:w}:{component_tag:w,splice_time:nn(A)}},Cn=function(D){return{component_tag:D.readBits(8),utc_splice_time:D.readBits(32)}},ln=function(D){var A=D.readBits(32),w=D.readBool();D.readBits(7);var x={splice_event_id:A,splice_event_cancel_indicator:w};if(w)return x;if(x.out_of_network_indicator=D.readBool(),x.program_splice_flag=D.readBool(),x.duration_flag=D.readBool(),D.readBits(5),x.program_splice_flag)x.utc_splice_time=D.readBits(32);else{x.component_count=D.readBits(8),x.components=[];for(var O=0;O<x.component_count;O++)x.components.push(Cn(D))}return x.duration_flag&&(x.break_duration=mn(D)),x.unique_program_id=D.readBits(16),x.avail_num=D.readBits(8),x.avails_expected=D.readBits(8),x},Nn=function(D,A,w,x){return{descriptor_tag:D,descriptor_length:A,identifier:w,provider_avail_id:x.readBits(32)}},cr=function(D,A,w,x){var O=x.readBits(8),F=x.readBits(3);x.readBits(5);for(var $="",z=0;z<F;z++)$+=String.fromCharCode(x.readBits(8));return{descriptor_tag:D,descriptor_length:A,identifier:w,preroll:O,dtmf_count:F,DTMF_char:$}},Ds=function(D){var A=D.readBits(8);return D.readBits(7),{component_tag:A,pts_offset:4*D.readBits(31)+D.readBits(2)}},lt=function(D,A,w,x){var O=x.readBits(32),F=x.readBool();x.readBits(7);var $={descriptor_tag:D,descriptor_length:A,identifier:w,segmentation_event_id:O,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 z=0;z<$.component_count;z++)$.components.push(Ds(x))}$.segmentation_duration_flag&&($.segmentation_duration=x.readBits(40)),$.segmentation_upid_type=x.readBits(8),$.segmentation_upid_length=x.readBits(8);var se=new Uint8Array($.segmentation_upid_length);for(z=0;z<$.segmentation_upid_length;z++)se[z]=x.readBits(8);return $.segmentation_upid=se.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)),$},ht=function(D,A,w,x){return{descriptor_tag:D,descriptor_length:A,identifier:w,TAI_seconds:x.readBits(48),TAI_ns:x.readBits(32),UTC_offset:x.readBits(16)}},Vt=function(D){return{component_tag:D.readBits(8),ISO_code:String.fromCharCode(D.readBits(8),D.readBits(8),D.readBits(8)),Bit_Stream_Mode:D.readBits(3),Num_Channels:D.readBits(4),Full_Srvc_Audio:D.readBool()}},Dr=function(D,A,w,x){for(var O=x.readBits(4),F=[],$=0;$<O;$++)F.push(Vt(x));return{descriptor_tag:D,descriptor_length:A,identifier:w,audio_count:O,components:F}},vs=function(D){var A=new y(D),w=A.readBits(8),x=A.readBool(),O=A.readBool();A.readBits(2);var F=A.readBits(12),$=A.readBits(8),z=A.readBool(),se=A.readBits(6),te=4*A.readBits(31)+A.readBits(2),ie=A.readBits(8),le=A.readBits(12),ae=A.readBits(12),ce=A.readBits(8),Ce=null;ce===Ke.kSpliceNull?Ce={}:ce===Ke.kSpliceSchedule?Ce=function(vt){for(var Ut=vt.readBits(8),tn=[],bt=0;bt<Ut;bt++)tn.push(ln(vt));return{splice_count:Ut,events:tn}}(A):ce===Ke.kSpliceInsert?Ce=function(vt){var Ut=vt.readBits(32),tn=vt.readBool();vt.readBits(7);var bt={splice_event_id:Ut,splice_event_cancel_indicator:tn};if(tn)return bt;if(bt.out_of_network_indicator=vt.readBool(),bt.program_splice_flag=vt.readBool(),bt.duration_flag=vt.readBool(),bt.splice_immediate_flag=vt.readBool(),vt.readBits(4),bt.program_splice_flag&&!bt.splice_immediate_flag&&(bt.splice_time=nn(vt)),!bt.program_splice_flag){bt.component_count=vt.readBits(8),bt.components=[];for(var Nt=0;Nt<bt.component_count;Nt++)bt.components.push(On(bt.splice_immediate_flag,vt))}return bt.duration_flag&&(bt.break_duration=mn(vt)),bt.unique_program_id=vt.readBits(16),bt.avail_num=vt.readBits(8),bt.avails_expected=vt.readBits(8),bt}(A):ce===Ke.kTimeSignal?Ce=function(vt){return{splice_time:nn(vt)}}(A):ce===Ke.kBandwidthReservation?Ce={}:ce===Ke.kPrivateCommand?Ce=function(vt,Ut){for(var tn=String.fromCharCode(Ut.readBits(8),Ut.readBits(8),Ut.readBits(8),Ut.readBits(8)),bt=new Uint8Array(vt-4),Nt=0;Nt<vt-4;Nt++)bt[Nt]=Ut.readBits(8);return{identifier:tn,private_data:bt.buffer}}(ae,A):A.readBits(8*ae);for(var Me=[],Le=A.readBits(16),Je=0;Je<Le;){var Ye=A.readBits(8),Ve=A.readBits(8),pt=String.fromCharCode(A.readBits(8),A.readBits(8),A.readBits(8),A.readBits(8));Ye===0?Me.push(Nn(Ye,Ve,pt,A)):Ye===1?Me.push(cr(Ye,Ve,pt,A)):Ye===2?Me.push(lt(Ye,Ve,pt,A)):Ye===3?Me.push(ht(Ye,Ve,pt,A)):Ye===4?Me.push(Dr(Ye,Ve,pt,A)):A.readBits(8*(Ve-4)),Je+=2+Ve}var Et={table_id:w,section_syntax_indicator:x,private_indicator:O,section_length:F,protocol_version:$,encrypted_packet:z,encryption_algorithm:se,pts_adjustment:te,cw_index:ie,tier:le,splice_command_length:ae,splice_command_type:ce,splice_command:Ce,descriptor_loop_length:Le,splice_descriptors:Me,E_CRC32:z?A.readBits(32):void 0,CRC32:A.readBits(32)};if(ce===Ke.kSpliceInsert){var Xe=Ce;if(Xe.splice_event_cancel_indicator)return{splice_command_type:ce,detail:Et,data:D};if(Xe.program_splice_flag&&!Xe.splice_immediate_flag){var He=Xe.duration_flag?Xe.break_duration.auto_return:void 0,Lt=Xe.duration_flag?Xe.break_duration.duration/90:void 0;return Xe.splice_time.time_specified_flag?{splice_command_type:ce,pts:(te+Xe.splice_time.pts_time)%Math.pow(2,33),auto_return:He,duraiton:Lt,detail:Et,data:D}:{splice_command_type:ce,auto_return:He,duraiton:Lt,detail:Et,data:D}}return{splice_command_type:ce,auto_return:He=Xe.duration_flag?Xe.break_duration.auto_return:void 0,duraiton:Lt=Xe.duration_flag?Xe.break_duration.duration/90:void 0,detail:Et,data:D}}if(ce===Ke.kTimeSignal){var mt=Ce;return mt.splice_time.time_specified_flag?{splice_command_type:ce,pts:(te+mt.splice_time.pts_time)%Math.pow(2,33),detail:Et,data:D}:{splice_command_type:ce,detail:Et,data:D}}return{splice_command_type:ce,detail:Et,data:D}};(function(D){D[D.kSliceIDR_W_RADL=19]="kSliceIDR_W_RADL",D[D.kSliceIDR_N_LP=20]="kSliceIDR_N_LP",D[D.kSliceCRA_NUT=21]="kSliceCRA_NUT",D[D.kSliceVPS=32]="kSliceVPS",D[D.kSliceSPS=33]="kSliceSPS",D[D.kSlicePPS=34]="kSlicePPS",D[D.kSliceAUD=35]="kSliceAUD"})(it||(it={}));var Os=function(){},_s=function(D){var A=D.data.byteLength;this.type=D.type,this.data=new Uint8Array(4+A),new DataView(this.data.buffer).setUint32(0,A),this.data.set(D.data,4)},ii=function(){function D(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 D.prototype.findNextStartCodeOffset=function(A){for(var w=A,x=this.data_;;){if(w+3>=x.byteLength)return this.eof_flag_=!0,x.byteLength;var O=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(O===1||F===1)return w;w++}},D.prototype.readNextNaluPayload=function(){for(var A=this.data_,w=null;w==null&&!this.eof_flag_;){var x=this.current_startcode_offset_,O=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 z=A.subarray(x,$);(w=new Os).type=O,w.data=z}}return w},D}(),ea=function(){function D(A,w,x,O){var F=23+(5+A.byteLength)+(5+w.byteLength)+(5+x.byteLength),$=this.data=new Uint8Array(F);$[0]=1,$[1]=(3&O.general_profile_space)<<6|(O.general_tier_flag?1:0)<<5|31&O.general_profile_idc,$[2]=O.general_profile_compatibility_flags_1,$[3]=O.general_profile_compatibility_flags_2,$[4]=O.general_profile_compatibility_flags_3,$[5]=O.general_profile_compatibility_flags_4,$[6]=O.general_constraint_indicator_flags_1,$[7]=O.general_constraint_indicator_flags_2,$[8]=O.general_constraint_indicator_flags_3,$[9]=O.general_constraint_indicator_flags_4,$[10]=O.general_constraint_indicator_flags_5,$[11]=O.general_constraint_indicator_flags_6,$[12]=O.general_level_idc,$[13]=240|(3840&O.min_spatial_segmentation_idc)>>8,$[14]=255&O.min_spatial_segmentation_idc,$[15]=252|3&O.parallelismType,$[16]=252|3&O.chroma_format_idc,$[17]=248|7&O.bit_depth_luma_minus8,$[18]=248|7&O.bit_depth_chroma_minus8,$[19]=0,$[20]=0,$[21]=(3&O.constant_frame_rate)<<6|(7&O.num_temporal_layers)<<3|(O.temporal_id_nested?1:0)<<2|3,$[22]=3,$[23]=128|it.kSliceVPS,$[24]=0,$[25]=1,$[26]=(65280&A.byteLength)>>8,$[27]=(255&A.byteLength)>>0,$.set(A,28),$[23+(5+A.byteLength)+0]=128|it.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|it.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 D.prototype.getData=function(){return this.data},D}(),ai=function(){},bs=function(){},st=function(){},Ua=[[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]],Pi=function(){function D(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 D.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++}},D.prototype.readNextAC3Frame=function(){for(var A=this.data_,w=null;w==null&&!this.eof_flag_;){var x=this.current_syncword_offset_,O=A[x+4]>>6,F=[48e3,44200,33e3][O],$=63&A[x+4],z=2*Ua[O][$];if(isNaN(z)||x+z>this.data_.byteLength){this.eof_flag_=!0,this.has_last_incomplete_data=!0;break}var se=this.findNextSyncwordOffset(x+z);this.current_syncword_offset_=se;var te=A[x+5]>>3,ie=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,Ce=[2,1,2,3,3,4,4,5][le]+ce;(w=new st).sampling_frequency=F,w.channel_count=Ce,w.channel_mode=le,w.bit_stream_identification=te,w.low_frequency_effects_channel_on=ce,w.bit_stream_mode=ie,w.frame_size_code=$,w.data=A.subarray(x,x+z)}return w},D.prototype.hasIncompleteData=function(){return this.has_last_incomplete_data},D.prototype.getIncompleteData=function(){return this.has_last_incomplete_data?this.data_.subarray(this.current_syncword_offset_):null},D}(),Ba=function(D){var A;A=[D.sampling_rate_code<<6|D.bit_stream_identification<<1|D.bit_stream_mode>>2,(3&D.bit_stream_mode)<<6|D.channel_mode<<3|D.low_frequency_effects_channel_on<<2|D.frame_size_code>>4,D.frame_size_code<<4&224],this.config=A,this.sampling_rate=D.sampling_frequency,this.bit_stream_identification=D.bit_stream_identification,this.bit_stream_mode=D.bit_stream_mode,this.low_frequency_effects_channel_on=D.low_frequency_effects_channel_on,this.channel_count=D.channel_count,this.channel_mode=D.channel_mode,this.codec_mimetype="ac-3",this.original_codec_mimetype="ac-3"},Qe=function(){},Jl=function(){function D(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 D.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++}},D.prototype.readNextEAC3Frame=function(){for(var A=this.data_,w=null;w==null&&!this.eof_flag_;){var x=this.current_syncword_offset_,O=new y(A.subarray(x+2)),F=(O.readBits(2),O.readBits(3),O.readBits(11)+1<<1),$=O.readBits(2),z=null,se=null;$===3?(z=[24e3,22060,16e3][$=O.readBits(2)],se=3):(z=[48e3,44100,32e3][$],se=O.readBits(2));var te=O.readBits(3),ie=O.readBits(1),le=O.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][te]+ie;O.destroy(),(w=new Qe).sampling_frequency=z,w.channel_count=ce,w.channel_mode=te,w.bit_stream_identification=le,w.low_frequency_effects_channel_on=ie,w.frame_size=F,w.num_blks=[1,2,3,6][se],w.data=A.subarray(x,x+F)}return w},D.prototype.hasIncompleteData=function(){return this.has_last_incomplete_data},D.prototype.getIncompleteData=function(){return this.has_last_incomplete_data?this.data_.subarray(this.current_syncword_offset_):null},D}(),Oo=function(D){var A,w=Math.floor(D.frame_size*D.sampling_frequency/(16*D.num_blks));A=[255&w,248&w,D.sampling_rate_code<<6|D.bit_stream_identification<<1|0,0|D.channel_mode<<1|D.low_frequency_effects_channel_on<<0,0],this.config=A,this.sampling_rate=D.sampling_frequency,this.bit_stream_identification=D.bit_stream_identification,this.num_blks=D.num_blks,this.low_frequency_effects_channel_on=D.low_frequency_effects_channel_on,this.channel_count=D.channel_count,this.channel_mode=D.channel_mode,this.codec_mimetype="ec-3",this.original_codec_mimetype="ec-3"},xs=function(){},yu=function(){function D(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 D._ebsp2rbsp=function(A){for(var w=A,x=w.byteLength,O=new Uint8Array(x),F=0,$=0;$<x;$++)$>=2&&w[$]===3&&w[$-1]===0&&w[$-2]===0||(O[F]=w[$],F++);return new Uint8Array(O.buffer,0,F)},D.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++}},D.prototype.readNextOBUPayload=function(){for(var A=this.data_,w=null;w==null&&!this.eof_flag_;){var x=this.current_startcode_offset_+3,O=this.findNextStartCodeOffset(x);this.current_startcode_offset_=O,w=D._ebsp2rbsp(A.subarray(x,O))}return w},D}(),St=function(){var D=function(A,w){return(D=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(x,O){x.__proto__=O}||function(x,O){for(var F in O)Object.prototype.hasOwnProperty.call(O,F)&&(x[F]=O[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}D(A,w),A.prototype=w===null?Object.create(w):(x.prototype=w.prototype,new x)}}(),Gt=function(){return(Gt=Object.assign||function(D){for(var A,w=1,x=arguments.length;w<x;w++)for(var O in A=arguments[w])Object.prototype.hasOwnProperty.call(A,O)&&(D[O]=A[O]);return D}).apply(this,arguments)},cn=function(D){function A(w,x){var O=D.call(this)||this;return O.TAG="TSDemuxer",O.first_parse_=!0,O.media_info_=new c.a,O.timescale_=90,O.duration_=0,O.current_pmt_pid_=-1,O.program_pmt_map_={},O.pes_slice_queues_={},O.section_slice_queues_={},O.video_metadata_={vps:void 0,sps:void 0,pps:void 0,av1c:void 0,details:void 0},O.audio_metadata_={codec:void 0,audio_object_type:void 0,sampling_freq_index:void 0,sampling_frequency:void 0,channel_config:void 0},O.last_pcr_base_=NaN,O.timestamp_offset_=0,O.audio_last_sample_pts_=void 0,O.aac_last_incomplete_data_=null,O.has_video_=!1,O.has_audio_=!1,O.video_init_segment_dispatched_=!1,O.audio_init_segment_dispatched_=!1,O.video_metadata_changed_=!1,O.audio_metadata_changed_=!1,O.loas_previous_frame=null,O.video_track_={type:"video",id:1,sequenceNumber:0,samples:[],length:0},O.audio_track_={type:"audio",id:2,sequenceNumber:0,samples:[],length:0},O.ts_packet_size_=w.ts_packet_size,O.sync_offset_=w.sync_offset,O.config_=x,O}return St(A,D),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,D.prototype.destroy.call(this)},A.probe=function(w){var x=new Uint8Array(w),O=-1,F=188;if(x.byteLength<=3*F)return{needMoreData:!0};for(;O===-1;){for(var $=Math.min(1e3,x.byteLength-3*F),z=0;z<$;){if(x[z]===71&&x[z+F]===71&&x[z+2*F]===71){O=z;break}z++}if(O===-1)if(F===188)F=192;else{if(F!==192)break;F=204}}return O===-1?{match:!1}:(F===192&&O>=4?(o.a.v("TSDemuxer","ts_packet_size = 192, m2ts mode"),O-=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:O})},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 O=0;for(this.first_parse_&&(this.first_parse_=!1,O=this.sync_offset_);O+this.ts_packet_size_<=w.byteLength;){var F=x+O;this.ts_packet_size_===192&&(O+=4);var $=new Uint8Array(w,O,188),z=$[0];if(z!==71){o.a.e(this.TAG,"sync_byte = ".concat(z,", not 0x47"));break}var se=(64&$[1])>>>6,te=($[1],(31&$[1])<<8|$[2]),ie=(48&$[3])>>>4,le=15&$[3],ae=!(!this.pmt_||this.pmt_.pcr_pid!==te),ce={},Ce=4;if(ie==2||ie==3){var Me=$[4];if(Me>0&&(ae||ie==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 Le=300*this.getPcrBase($)+((1&$[10])<<8|$[11]);this.last_pcr_=Le}if(ie==2||5+Me===188){O+=188,this.ts_packet_size_===204&&(O+=16);continue}Ce=5+Me}if(ie==1||ie==3){if(te===0||te===this.current_pmt_pid_||this.pmt_!=null&&this.pmt_.pid_stream_type[te]===R.kSCTE35){var Je=188-Ce;this.handleSectionSlice(w,O+Ce,Je,{pid:te,file_position:F,payload_unit_start_indicator:se,continuity_conunter:le,random_access_indicator:ce.random_access_indicator})}else if(this.pmt_!=null&&this.pmt_.pid_stream_type[te]!=null){Je=188-Ce;var Ye=this.pmt_.pid_stream_type[te];te!==this.pmt_.common_pids.h264&&te!==this.pmt_.common_pids.h265&&te!==this.pmt_.common_pids.av1&&te!==this.pmt_.common_pids.adts_aac&&te!==this.pmt_.common_pids.loas_aac&&te!==this.pmt_.common_pids.ac3&&te!==this.pmt_.common_pids.eac3&&te!==this.pmt_.common_pids.opus&&te!==this.pmt_.common_pids.mp3&&this.pmt_.pes_private_data_pids[te]!==!0&&this.pmt_.timed_id3_pids[te]!==!0&&this.pmt_.synchronous_klv_pids[te]!==!0&&this.pmt_.asynchronous_klv_pids[te]!==!0||this.handlePESSlice(w,O+Ce,Je,{pid:te,stream_type:Ye,file_position:F,payload_unit_start_indicator:se,continuity_conunter:le,random_access_indicator:ce.random_access_indicator})}}O+=188,this.ts_packet_size_===204&&(O+=16)}return this.dispatchAudioVideoMediaSegment(),O},A.prototype.handleSectionSlice=function(w,x,O,F){var $=new Uint8Array(w,x,O),z=this.section_slice_queues_[F.pid];if(F.payload_unit_start_indicator){var se=$[0];if(z!=null&&z.total_length!==0){var te=new Uint8Array(w,x+1,Math.min(O,se));z.slices.push(te),z.total_length+=te.byteLength,z.total_length===z.expected_length?this.emitSectionSlices(z,F):this.clearSlices(z,F)}for(var ie=1+se;ie<$.byteLength&&$[ie+0]!==255;){var le=(15&$[ie+1])<<8|$[ie+2];this.section_slice_queues_[F.pid]=new ne,(z=this.section_slice_queues_[F.pid]).expected_length=le+3,z.file_position=F.file_position,z.random_access_indicator=F.random_access_indicator,te=new Uint8Array(w,x+ie,Math.min(O-ie,z.expected_length-z.total_length)),z.slices.push(te),z.total_length+=te.byteLength,z.total_length===z.expected_length?this.emitSectionSlices(z,F):z.total_length>=z.expected_length&&this.clearSlices(z,F),ie+=te.byteLength}}else z!=null&&z.total_length!==0&&(te=new Uint8Array(w,x,Math.min(O,z.expected_length-z.total_length)),z.slices.push(te),z.total_length+=te.byteLength,z.total_length===z.expected_length?this.emitSectionSlices(z,F):z.total_length>=z.expected_length&&this.clearSlices(z,F))},A.prototype.handlePESSlice=function(w,x,O,F){var $=new Uint8Array(w,x,O),z=$[0]<<16|$[1]<<8|$[2],se=($[3],$[4]<<8|$[5]);if(F.payload_unit_start_indicator){if(z!==1)return void o.a.e(this.TAG,"handlePESSlice: packet_start_code_prefix should be 1 but with value ".concat(z));var te=this.pes_slice_queues_[F.pid];te&&(te.expected_length===0||te.expected_length===te.total_length?this.emitPESSlices(te,F):this.clearSlices(te,F)),this.pes_slice_queues_[F.pid]=new ne,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 ie=this.pes_slice_queues_[F.pid];ie.slices.push($),F.payload_unit_start_indicator&&(ie.expected_length=se===0?0:se+6),ie.total_length+=$.byteLength,ie.expected_length>0&&ie.expected_length===ie.total_length?this.emitPESSlices(ie,F):ie.expected_length>0&&ie.expected_length<ie.total_length&&this.clearSlices(ie,F)}},A.prototype.emitSectionSlices=function(w,x){for(var O=new Uint8Array(w.total_length),F=0,$=0;F<w.slices.length;F++){var z=w.slices[F];O.set(z,$),$+=z.byteLength}w.slices=[],w.expected_length=-1,w.total_length=0;var se=new oe;se.pid=x.pid,se.data=O,se.file_position=w.file_position,se.random_access_indicator=w.random_access_indicator,this.parseSection(se)},A.prototype.emitPESSlices=function(w,x){for(var O=new Uint8Array(w.total_length),F=0,$=0;F<w.slices.length;F++){var z=w.slices[F];O.set(z,$),$+=z.byteLength}w.slices=[],w.expected_length=-1,w.total_length=0;var se=new Z;se.pid=x.pid,se.data=O,se.stream_type=x.stream_type,se.file_position=w.file_position,se.random_access_indicator=w.random_access_indicator,this.parsePES(se)},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,O=w.pid;O===0?this.parsePAT(x):O===this.current_pmt_pid_?this.parsePMT(x):this.pmt_!=null&&this.pmt_.scte_35_pids[O]&&this.parseSCTE35(x)},A.prototype.parsePES=function(w){var x=w.data,O=x[0]<<16|x[1]<<8|x[2],F=x[3],$=x[4]<<8|x[5];if(O===1)if(F!==188&&F!==190&&F!==191&&F!==240&&F!==241&&F!==255&&F!==242&&F!==248){x[6];var z=(192&x[7])>>>6,se=x[8],te=void 0,ie=void 0;z!==2&&z!==3||(te=this.getTimestamp(x,9),ie=z===3?this.getTimestamp(x,14):te);var le=9+se,ae=void 0;if($!==0){if($<3+se)return void o.a.v(this.TAG,"Malformed PES: PES_packet_length < 3 + PES_header_data_length");ae=$-3-se}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,te);break;case R.kPESPrivateData:this.pmt_.common_pids.av1===w.pid?this.parseAV1Payload(ce,te,ie,w.file_position,w.random_access_indicator):this.pmt_.common_pids.opus===w.pid?this.parseOpusPayload(ce,te):this.pmt_.common_pids.ac3===w.pid?this.parseAC3Payload(ce,te):this.pmt_.common_pids.eac3===w.pid?this.parseEAC3Payload(ce,te):this.pmt_.asynchronous_klv_pids[w.pid]?this.parseAsynchronousKLVMetadataPayload(ce,w.pid,F):this.pmt_.smpte2038_pids[w.pid]?this.parseSMPTE2038MetadataPayload(ce,te,ie,w.pid,F):this.parsePESPrivateDataPayload(ce,te,ie,w.pid,F);break;case R.kADTSAAC:this.parseADTSAACPayload(ce,te);break;case R.kLOASAAC:this.parseLOASAACPayload(ce,te);break;case R.kAC3:this.parseAC3Payload(ce,te);break;case R.kEAC3:this.parseEAC3Payload(ce,te);break;case R.kMetadata:this.pmt_.timed_id3_pids[w.pid]?this.parseTimedID3MetadataPayload(ce,te,ie,w.pid,F):this.pmt_.synchronous_klv_pids[w.pid]&&this.parseSynchronousKLVMetadataPayload(ce,te,ie,w.pid,F);break;case R.kH264:this.parseH264Payload(ce,te,ie,w.file_position,w.random_access_indicator);break;case R.kH265:this.parseH265Payload(ce,te,ie,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(O))},A.prototype.parsePAT=function(w){var x=w[0];if(x===0){var O=(15&w[1])<<8|w[2],F=(w[3],w[4],(62&w[5])>>>1),$=1&w[5],z=w[6],se=(w[7],null);if($===1&&z===0)(se=new Y).version_number=F;else if((se=this.pat_)==null)return;for(var te=O-5-4,ie=-1,le=-1,ae=8;ae<8+te;ae+=4){var ce=w[ae]<<8|w[ae+1],Ce=(31&w[ae+2])<<8|w[ae+3];ce===0?se.network_pid=Ce:(se.program_pmt_pid[ce]=Ce,ie===-1&&(ie=ce),le===-1&&(le=Ce))}$===1&&z===0&&(this.pat_==null&&o.a.v(this.TAG,"Parsed first PAT: ".concat(JSON.stringify(se))),this.pat_=se,this.current_program_=ie,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 O=(15&w[1])<<8|w[2],F=w[3]<<8|w[4],$=(62&w[5])>>>1,z=1&w[5],se=w[6],te=(w[7],null);if(z===1&&se===0)(te=new X).program_number=F,te.version_number=$,this.program_pmt_map_[F]=te;else if((te=this.program_pmt_map_[F])==null)return;te.pcr_pid=(31&w[8])<<8|w[9];for(var ie=(15&w[10])<<8|w[11],le=12+ie,ae=O-9-ie-4,ce=le;ce<le+ae;){var Ce=w[ce],Me=(31&w[ce+1])<<8|w[ce+2],Le=(15&w[ce+3])<<8|w[ce+4];te.pid_stream_type[Me]=Ce;var Je=te.common_pids.h264||te.common_pids.h265,Ye=te.common_pids.adts_aac||te.common_pids.loas_aac||te.common_pids.ac3||te.common_pids.eac3||te.common_pids.opus||te.common_pids.mp3;if(Ce!==R.kH264||Je)if(Ce!==R.kH265||Je)if(Ce!==R.kADTSAAC||Ye)if(Ce!==R.kLOASAAC||Ye)if(Ce!==R.kAC3||Ye)if(Ce!==R.kEAC3||Ye)if(Ce!==R.kMPEG1Audio&&Ce!==R.kMPEG2Audio||Ye)if(Ce===R.kPESPrivateData){if(te.pes_private_data_pids[Me]=!0,Le>0){for(var Ve=ce+5;Ve<ce+5+Le;){var pt=w[Ve+0],Et=w[Ve+1];if(pt===5){var Xe=String.fromCharCode.apply(String,Array.from(w.subarray(Ve+2,Ve+2+Et)));Xe==="VANC"?te.smpte2038_pids[Me]=!0:Xe==="AV01"?te.common_pids.av1=Me:Xe==="Opus"?te.common_pids.opus=Me:Xe==="KLVA"&&(te.asynchronous_klv_pids[Me]=!0)}else if(pt===127){if(Me===te.common_pids.opus){var He=null;if(w[Ve+2]===128&&(He=w[Ve+3]),He==null){o.a.e(this.TAG,"Not Supported Opus channel count.");continue}var Lt={codec:"opus",channel_count:15&He?15&He:2,channel_config_code:He,sample_rate:48e3},mt={codec:"opus",meta:Lt};this.audio_init_segment_dispatched_==0?(this.audio_metadata_=Lt,this.dispatchAudioInitSegment(mt)):this.detectAudioMetadataChange(mt)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(mt))}}else pt===128&&Me===te.common_pids.av1&&(this.video_metadata_.av1c=w.subarray(Ve+2,Ve+2+Et));Ve+=2+Et}var vt=w.subarray(ce+5,ce+5+Le);this.dispatchPESPrivateDataDescriptor(Me,Ce,vt)}}else if(Ce===R.kMetadata){if(Le>0)for(Ve=ce+5;Ve<ce+5+Le;){pt=w[Ve+0];var Ut=w[Ve+1];if(pt===38){var tn=w[Ve+2]<<8|w[Ve+3]<<0,bt=null;tn===65535&&(bt=String.fromCharCode.apply(String,Array.from(w.subarray(Ve+4,Ve+4+4))));var Nt=null;if(w[Ve+4+(tn===65535?4:0)]===255){var yt=4+(tn===65535?4:0)+1;Nt=String.fromCharCode.apply(String,Array.from(w.subarray(Ve+yt,Ve+yt+4)))}bt==="ID3 "&&Nt==="ID3 "?te.timed_id3_pids[Me]=!0:Nt==="KLVA"&&(te.synchronous_klv_pids[Me]=!0)}Ve+=2+Ut}}else Ce===R.kSCTE35&&(te.scte_35_pids[Me]=!0);else te.common_pids.mp3=Me;else te.common_pids.eac3=Me;else te.common_pids.ac3=Me;else te.common_pids.loas_aac=Me;else te.common_pids.adts_aac=Me;else te.common_pids.h265=Me;else te.common_pids.h264=Me;ce+=5+Le}F===this.current_program_&&(this.pmt_==null&&o.a.v(this.TAG,"Parsed first PMT: ".concat(JSON.stringify(te))),this.pmt_=te,(te.common_pids.h264||te.common_pids.h265||te.common_pids.av1)&&(this.has_video_=!0),(te.common_pids.adts_aac||te.common_pids.loas_aac||te.common_pids.ac3||te.common_pids.opus||te.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=vs(w);if(x.pts!=null){var O=Math.floor(x.pts/this.timescale_);x.pts=O}else x.nearest_pts=this.getNearestTimestampMilliseconds();this.onSCTE35Metadata&&this.onSCTE35Metadata(x)},A.prototype.parseAV1Payload=function(w,x,O,F,$){for(var z=new yu(w),se=null,te=[],ie=0,le=!1,ae=null;(se=z.readNextOBUPayload())!=null;){if((ae=k.parseOBUs(se,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),te.push({data:se}),ie+=se.byteLength}var Ce=Math.floor(x/this.timescale_),Me=Math.floor(O/this.timescale_);if(te.length){var Le=this.video_track_,Je={units:te,length:ie,isKeyframe:le,dts:Me,pts:Ce,cts:Ce-Me,file_position:F};Le.samples.push(Je),Le.length+=ie}},A.prototype.parseH264Payload=function(w,x,O,F,$){for(var z=new ve(w),se=null,te=[],ie=0,le=!1;(se=z.readNextNaluPayload())!=null;){var ae=new Q(se);if(ae.type===q.kSliceSPS){var ce=v.parseSPS(se.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===q.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===q.kSliceIDR||ae.type===q.kSliceNonIDR&&$===1)&&(le=!0);this.video_init_segment_dispatched_&&(te.push(ae),ie+=ae.data.byteLength)}var Ce=Math.floor(x/this.timescale_),Me=Math.floor(O/this.timescale_);if(te.length){var Le=this.video_track_,Je={units:te,length:ie,isKeyframe:le,dts:Me,pts:Ce,cts:Ce-Me,file_position:F};Le.samples.push(Je),Le.length+=ie}},A.prototype.parseH265Payload=function(w,x,O,F,$){for(var z=new ii(w),se=null,te=[],ie=0,le=!1;(se=z.readNextNaluPayload())!=null;){var ae=new _s(se);if(ae.type===it.kSliceVPS){if(!this.video_init_segment_dispatched_){var ce=S.parseVPS(se.data);this.video_metadata_.vps=ae,this.video_metadata_.details=Gt(Gt({},this.video_metadata_.details),ce)}}else ae.type===it.kSliceSPS?(ce=S.parseSPS(se.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=Gt(Gt({},this.video_metadata_.details),ce))):ae.type===it.kSlicePPS?(!this.video_init_segment_dispatched_||this.video_metadata_changed_)&&(ce=S.parsePPS(se.data),this.video_metadata_.pps=ae,this.video_metadata_.details=Gt(Gt({},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!==it.kSliceIDR_W_RADL&&ae.type!==it.kSliceIDR_N_LP&&ae.type!==it.kSliceCRA_NUT||(le=!0);this.video_init_segment_dispatched_&&(te.push(ae),ie+=ae.data.byteLength)}var Ce=Math.floor(x/this.timescale_),Me=Math.floor(O/this.timescale_);if(te.length){var Le=this.video_track_,Je={units:te,length:ie,isKeyframe:le,dts:Me,pts:Ce,cts:Ce-Me,file_position:F};Le.samples.push(Je),Le.length+=ie}},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 O=this.video_metadata_.details.codec_size,F=x.codec_size;return o.a.v(this.TAG,"Video: Coded Resolution changed from "+"".concat(O.width,"x").concat(O.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 O=x.frameRate.fps_den,F=x.frameRate.fps_num;if(x.refSampleDuration=O/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),z=this.video_metadata_.sps.data.subarray(4),se=this.video_metadata_.pps.data.subarray(4),te=new ea($,z,se,w);x.hvcc=te.getData(),this.video_init_segment_dispatched_==0&&o.a.v(this.TAG,"Generated first HEVCDecoderConfigurationRecord for mimeType: ".concat(x.codec))}else{z=this.video_metadata_.sps.data.subarray(4),se=this.video_metadata_.pps.data.subarray(4);var ie=new Te(z,se,w);x.avcc=ie.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 O=new Uint8Array(w.byteLength+this.aac_last_incomplete_data_.byteLength);O.set(this.aac_last_incomplete_data_,0),O.set(w,this.aac_last_incomplete_data_.byteLength),w=O}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 z=this.audio_last_sample_pts_+F;Math.abs(z-$)>1&&(o.a.w(this.TAG,"AAC: Detected pts overlapped, "+"expected: ".concat(z,"ms, PES pts: ").concat($,"ms")),$=z)}}for(var se,te=new Ue(w),ie=null,le=$;(ie=te.readNextAACFrame())!=null;){F=1024/ie.sampling_frequency*1e3;var ae={codec:"aac",data:ie};this.audio_init_segment_dispatched_==0?(this.audio_metadata_={codec:"aac",audio_object_type:ie.audio_object_type,sampling_freq_index:ie.sampling_freq_index,sampling_frequency:ie.sampling_frequency,channel_config:ie.channel_config},this.dispatchAudioInitSegment(ae)):this.detectAudioMetadataChange(ae)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(ae)),se=le;var ce=Math.floor(le),Ce={unit:ie.data,length:ie.data.byteLength,pts:ce,dts:ce};this.audio_track_.samples.push(Ce),this.audio_track_.length+=ie.data.byteLength,le+=F}te.hasIncompleteData()&&(this.aac_last_incomplete_data_=te.getIncompleteData()),se&&(this.audio_last_sample_pts_=se)}},A.prototype.parseLOASAACPayload=function(w,x){var O;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 $,z;if(x!=null&&(z=x/this.timescale_),this.audio_metadata_.codec==="aac"){if(x==null&&this.audio_last_sample_pts_!=null)$=1024/this.audio_metadata_.sampling_frequency*1e3,z=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 se=this.audio_last_sample_pts_+$;Math.abs(se-z)>1&&(o.a.w(this.TAG,"AAC: Detected pts overlapped, "+"expected: ".concat(se,"ms, PES pts: ").concat(z,"ms")),z=se)}}for(var te,ie=new Oe(w),le=null,ae=z;(le=ie.readNextAACFrame((O=this.loas_previous_frame)!==null&&O!==void 0?O: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)),te=ae;var Ce=Math.floor(ae),Me={unit:le.data,length:le.data.byteLength,pts:Ce,dts:Ce};this.audio_track_.samples.push(Me),this.audio_track_.length+=le.data.byteLength,ae+=$}ie.hasIncompleteData()&&(this.aac_last_incomplete_data_=ie.getIncompleteData()),te&&(this.audio_last_sample_pts_=te)}},A.prototype.parseAC3Payload=function(w,x){if(!this.has_video_||this.video_init_segment_dispatched_){var O,F;if(x!=null&&(F=x/this.timescale_),this.audio_metadata_.codec==="ac-3"){if(x==null&&this.audio_last_sample_pts_!=null)O=1536/this.audio_metadata_.sampling_frequency*1e3,F=this.audio_last_sample_pts_+O;else if(x==null)return void o.a.w(this.TAG,"AC3: Unknown pts")}for(var $,z=new Pi(w),se=null,te=F;(se=z.readNextAC3Frame())!=null;){O=1536/se.sampling_frequency*1e3;var ie={codec:"ac-3",data:se};this.audio_init_segment_dispatched_==0?(this.audio_metadata_={codec:"ac-3",sampling_frequency:se.sampling_frequency,bit_stream_identification:se.bit_stream_identification,bit_stream_mode:se.bit_stream_mode,low_frequency_effects_channel_on:se.low_frequency_effects_channel_on,channel_mode:se.channel_mode},this.dispatchAudioInitSegment(ie)):this.detectAudioMetadataChange(ie)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(ie)),$=te;var le=Math.floor(te),ae={unit:se.data,length:se.data.byteLength,pts:le,dts:le};this.audio_track_.samples.push(ae),this.audio_track_.length+=se.data.byteLength,te+=O}$&&(this.audio_last_sample_pts_=$)}},A.prototype.parseEAC3Payload=function(w,x){if(!this.has_video_||this.video_init_segment_dispatched_){var O,F;if(x!=null&&(F=x/this.timescale_),this.audio_metadata_.codec==="ec-3"){if(x==null&&this.audio_last_sample_pts_!=null)O=256*this.audio_metadata_.num_blks/this.audio_metadata_.sampling_frequency*1e3,F=this.audio_last_sample_pts_+O;else if(x==null)return void o.a.w(this.TAG,"EAC3: Unknown pts")}for(var $,z=new Jl(w),se=null,te=F;(se=z.readNextEAC3Frame())!=null;){O=1536/se.sampling_frequency*1e3;var ie={codec:"ec-3",data:se};this.audio_init_segment_dispatched_==0?(this.audio_metadata_={codec:"ec-3",sampling_frequency:se.sampling_frequency,bit_stream_identification:se.bit_stream_identification,low_frequency_effects_channel_on:se.low_frequency_effects_channel_on,num_blks:se.num_blks,channel_mode:se.channel_mode},this.dispatchAudioInitSegment(ie)):this.detectAudioMetadataChange(ie)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(ie)),$=te;var le=Math.floor(te),ae={unit:se.data,length:se.data.byteLength,pts:le,dts:le};this.audio_track_.samples.push(ae),this.audio_track_.length+=se.data.byteLength,te+=O}$&&(this.audio_last_sample_pts_=$)}},A.prototype.parseOpusPayload=function(w,x){if(!this.has_video_||this.video_init_segment_dispatched_){var O,F;if(x!=null&&(F=x/this.timescale_),this.audio_metadata_.codec==="opus"){if(x==null&&this.audio_last_sample_pts_!=null)O=20,F=this.audio_last_sample_pts_+O;else if(x==null)return void o.a.w(this.TAG,"Opus: Unknown pts")}for(var $,z=F,se=0;se<w.length;){O=20;for(var te=(16&w[se+1])!=0,ie=(8&w[se+1])!=0,le=se+2,ae=0;w[le]===255;)ae+=255,le+=1;ae+=w[le],le+=1,le+=te?2:0,le+=ie?2:0,$=z;var ce=Math.floor(z),Ce=w.slice(le,le+ae),Me={unit:Ce,length:Ce.byteLength,pts:ce,dts:ce};this.audio_track_.samples.push(Me),this.audio_track_.length+=Ce.byteLength,z+=O,se=le+ae}$&&(this.audio_last_sample_pts_=$)}},A.prototype.parseMP3Payload=function(w,x){if(!this.has_video_||this.video_init_segment_dispatched_){var O=[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],z=w[1]>>>3&3,se=(6&w[1])>>1,te=(240&w[2])>>>4,ie=(12&w[2])>>>2,le=(w[3]>>>6&3)!==3?2:1,ae=0,ce=34;switch(z){case 0:ae=[11025,12e3,8e3,0][ie];break;case 2:ae=[22050,24e3,16e3,0][ie];break;case 3:ae=[44100,48e3,32e3,0][ie]}switch(se){case 1:ce=34,te<$.length&&$[te];break;case 2:ce=33,te<F.length&&F[te];break;case 3:ce=32,te<O.length&&O[te]}var Ce=new bs;Ce.object_type=ce,Ce.sample_rate=ae,Ce.channel_count=le,Ce.data=w;var Me={codec:"mp3",data:Ce};this.audio_init_segment_dispatched_==0?(this.audio_metadata_={codec:"mp3",object_type:ce,sample_rate:ae,channel_count:le},this.dispatchAudioInitSegment(Me)):this.detectAudioMetadataChange(Me)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(Me));var Le={unit:w,length:w.byteLength,pts:x/this.timescale_,dts:x/this.timescale_};this.audio_track_.samples.push(Le),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((O=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(O.sample_rate)),!0;if(O.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(O.channel_count)),!0}else if(w.codec==="mp3"&&this.audio_metadata_.codec==="mp3"){var O;if((O=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(O.object_type)),!0;if(O.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(O.sample_rate)),!0;if(O.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(O.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 O=w.codec==="aac"?w.data:null,F=new Dt(O);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,z=new Ba($);x.audioSampleRate=z.sampling_rate,x.channelCount=z.channel_count,x.codec=z.codec_mimetype,x.originalCodec=z.original_codec_mimetype,x.config=z.config,x.refSampleDuration=1536/x.audioSampleRate*x.timescale}else if(this.audio_metadata_.codec==="ec-3"){var se=w.codec==="ec-3"?w.data:null,te=new Oo(se);x.audioSampleRate=te.sampling_rate,x.channelCount=te.channel_count,x.codec=te.codec_mimetype,x.originalCodec=te.original_codec_mimetype,x.config=te.config,x.refSampleDuration=256*te.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 ie=this.media_info_;ie.hasAudio=!0,ie.audioCodec=x.originalCodec,ie.audioSampleRate=x.audioSampleRate,ie.audioChannelCount=x.channelCount,ie.hasVideo&&ie.videoCodec?ie.mimeType='video/mp2t; codecs="'.concat(ie.videoCodec,",").concat(ie.audioCodec,'"'):ie.mimeType='video/mp2t; codecs="'.concat(ie.audioCodec,'"'),ie.isComplete()&&this.onMediaInfo(ie)},A.prototype.dispatchPESPrivateDataDescriptor=function(w,x,O){var F=new wn;F.pid=w,F.stream_type=x,F.descriptor=O,this.onPESPrivateDataDescriptor&&this.onPESPrivateDataDescriptor(F)},A.prototype.parsePESPrivateDataPayload=function(w,x,O,F,$){var z=new en;if(z.pid=F,z.stream_id=$,z.len=w.byteLength,z.data=w,x!=null){var se=Math.floor(x/this.timescale_);z.pts=se}else z.nearest_pts=this.getNearestTimestampMilliseconds();if(O!=null){var te=Math.floor(O/this.timescale_);z.dts=te}this.onPESPrivateData&&this.onPESPrivateData(z)},A.prototype.parseTimedID3MetadataPayload=function(w,x,O,F,$){var z=new en;if(z.pid=F,z.stream_id=$,z.len=w.byteLength,z.data=w,x!=null){var se=Math.floor(x/this.timescale_);z.pts=se}if(O!=null){var te=Math.floor(O/this.timescale_);z.dts=te}this.onTimedID3Metadata&&this.onTimedID3Metadata(z)},A.prototype.parseSynchronousKLVMetadataPayload=function(w,x,O,F,$){var z=new xs;if(z.pid=F,z.stream_id=$,z.len=w.byteLength,z.data=w,x!=null){var se=Math.floor(x/this.timescale_);z.pts=se}if(O!=null){var te=Math.floor(O/this.timescale_);z.dts=te}z.access_units=function(ie){for(var le=[],ae=0;ae+5<ie.byteLength;){var ce=ie[ae+0],Ce=ie[ae+1],Me=ie[ae+2],Le=ie[ae+3]<<8|ie[ae+4]<<0,Je=ie.slice(ae+5,ae+5+Le);le.push({service_id:ce,sequence_number:Ce,flags:Me,data:Je}),ae+=5+Le}return le}(w),this.onSynchronousKLVMetadata&&this.onSynchronousKLVMetadata(z)},A.prototype.parseAsynchronousKLVMetadataPayload=function(w,x,O){var F=new en;F.pid=x,F.stream_id=O,F.len=w.byteLength,F.data=w,this.onAsynchronousKLVMetadata&&this.onAsynchronousKLVMetadata(F)},A.prototype.parseSMPTE2038MetadataPayload=function(w,x,O,F,$){var z=new ai;if(z.pid=F,z.stream_id=$,z.len=w.byteLength,z.data=w,x!=null){var se=Math.floor(x/this.timescale_);z.pts=se}if(z.nearest_pts=this.getNearestTimestampMilliseconds(),O!=null){var te=Math.floor(O/this.timescale_);z.dts=te}z.ancillaries=function(ie){for(var le=new y(ie),ae=0,ce=[];ae+=6,le.readBits(6)===0;){var Ce=le.readBool();ae+=1;var Me=le.readBits(11);ae+=11;var Le=le.readBits(12);ae+=12;var Je=255&le.readBits(10);ae+=10;var Ye=255&le.readBits(10);ae+=10;var Ve=255&le.readBits(10);ae+=10;for(var pt=new Uint8Array(Ve),Et=0;Et<Ve;Et++){var Xe=255&le.readBits(10);ae+=10,pt[Et]=Xe}le.readBits(10),ae+=10;var He="User Defined";Je===65?Ye===7&&(He="SCTE-104"):Je===95?Ye===220?He="ARIB STD-B37 (1SEG)":Ye===221?He="ARIB STD-B37 (ANALOG)":Ye===222?He="ARIB STD-B37 (SD)":Ye===223&&(He="ARIB STD-B37 (HD)"):Je===97&&(Ye===1?He="EIA-708":Ye===2&&(He="EIA-608")),ce.push({yc_indicator:Ce,line_number:Me,horizontal_offset:Le,did:Je,sdid:Ye,user_data:pt,description:He,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(z)},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 O=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 O+4294967296<this.last_pcr_base_&&(O+=8589934592),O},A}(G),Zn=function(D,A,w){for(var x,O=0,F=A.length;O<F;O++)!x&&O in A||(x||(x=Array.prototype.slice.call(A,0,O)),x[O]=A[O]);return D.concat(x||Array.prototype.slice.call(A))},er=function(){function D(){}return D.init=function(){for(var A in D.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:[]},D.types)D.types.hasOwnProperty(A)&&(D.types[A]=[A.charCodeAt(0),A.charCodeAt(1),A.charCodeAt(2),A.charCodeAt(3)]);var w=D.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])},D.box=function(A){for(var w=8,x=null,O=Array.prototype.slice.call(arguments,1),F=O.length,$=0;$<F;$++)w+=O[$].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 z=8;for($=0;$<F;$++)x.set(O[$],z),z+=O[$].byteLength;return x},D.generateInitSegment=function(A){var w=D.box(D.types.ftyp,D.constants.FTYP),x=D.moov(A),O=new Uint8Array(w.byteLength+x.byteLength);return O.set(w,0),O.set(x,w.byteLength),O},D.moov=function(A){var w=D.mvhd(A.timescale,A.duration),x=D.trak(A),O=D.mvex(A);return D.box(D.types.moov,w,x,O)},D.mvhd=function(A,w){return D.box(D.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]))},D.trak=function(A){return D.box(D.types.trak,D.tkhd(A),D.mdia(A))},D.tkhd=function(A){var w=A.id,x=A.duration,O=A.presentWidth,F=A.presentHeight;return D.box(D.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,O>>>8&255,255&O,0,0,F>>>8&255,255&F,0,0]))},D.mdia=function(A){return D.box(D.types.mdia,D.mdhd(A),D.hdlr(A),D.minf(A))},D.mdhd=function(A){var w=A.timescale,x=A.duration;return D.box(D.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]))},D.hdlr=function(A){var w=null;return w=A.type==="audio"?D.constants.HDLR_AUDIO:D.constants.HDLR_VIDEO,D.box(D.types.hdlr,w)},D.minf=function(A){var w=null;return w=A.type==="audio"?D.box(D.types.smhd,D.constants.SMHD):D.box(D.types.vmhd,D.constants.VMHD),D.box(D.types.minf,w,D.dinf(),D.stbl(A))},D.dinf=function(){return D.box(D.types.dinf,D.box(D.types.dref,D.constants.DREF))},D.stbl=function(A){return D.box(D.types.stbl,D.stsd(A),D.box(D.types.stts,D.constants.STTS),D.box(D.types.stsc,D.constants.STSC),D.box(D.types.stsz,D.constants.STSZ),D.box(D.types.stco,D.constants.STCO))},D.stsd=function(A){return A.type==="audio"?A.codec==="mp3"?D.box(D.types.stsd,D.constants.STSD_PREFIX,D.mp3(A)):A.codec==="ac-3"?D.box(D.types.stsd,D.constants.STSD_PREFIX,D.ac3(A)):A.codec==="ec-3"?D.box(D.types.stsd,D.constants.STSD_PREFIX,D.ec3(A)):A.codec==="opus"?D.box(D.types.stsd,D.constants.STSD_PREFIX,D.Opus(A)):A.codec=="flac"?D.box(D.types.stsd,D.constants.STSD_PREFIX,D.fLaC(A)):D.box(D.types.stsd,D.constants.STSD_PREFIX,D.mp4a(A)):A.type==="video"&&A.codec.startsWith("hvc1")?D.box(D.types.stsd,D.constants.STSD_PREFIX,D.hvc1(A)):A.type==="video"&&A.codec.startsWith("av01")?D.box(D.types.stsd,D.constants.STSD_PREFIX,D.av01(A)):D.box(D.types.stsd,D.constants.STSD_PREFIX,D.avc1(A))},D.mp3=function(A){var w=A.channelCount,x=A.audioSampleRate,O=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 D.box(D.types[".mp3"],O)},D.mp4a=function(A){var w=A.channelCount,x=A.audioSampleRate,O=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 D.box(D.types.mp4a,O,D.esds(A))},D.ac3=function(A){var w=A.channelCount,x=A.audioSampleRate,O=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 D.box(D.types["ac-3"],O,D.box(D.types.dac3,new Uint8Array(A.config)))},D.ec3=function(A){var w=A.channelCount,x=A.audioSampleRate,O=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 D.box(D.types["ec-3"],O,D.box(D.types.dec3,new Uint8Array(A.config)))},D.esds=function(A){var w=A.config||[],x=w.length,O=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 D.box(D.types.esds,O)},D.Opus=function(A){var w=A.channelCount,x=A.audioSampleRate,O=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 D.box(D.types.Opus,O,D.dOps(A))},D.dOps=function(A){var w=A.channelCount,x=A.channelConfigCode,O=A.audioSampleRate;if(A.config)return D.box(D.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(Zn([0,w,0,0,O>>>24&255,O>>>17&255,O>>>8&255,O>>>0&255,0,0],F));return D.box(D.types.dOps,$)},D.fLaC=function(A){var w=A.channelCount,x=Math.min(A.audioSampleRate,65535),O=A.sampleSize,F=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,w,0,O,0,0,0,0,x>>>8&255,255&x,0,0]);return D.box(D.types.fLaC,F,D.dfLa(A))},D.dfLa=function(A){var w=new Uint8Array(Zn([0,0,0,0],A.config));return D.box(D.types.dfLa,w)},D.avc1=function(A){var w=A.avcc,x=A.codecWidth,O=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,O>>>8&255,255&O,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 D.box(D.types.avc1,F,D.box(D.types.avcC,w))},D.hvc1=function(A){var w=A.hvcc,x=A.codecWidth,O=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,O>>>8&255,255&O,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 D.box(D.types.hvc1,F,D.box(D.types.hvcC,w))},D.av01=function(A){var w=A.av1c,x=A.codecWidth||192,O=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,O>>>8&255,255&O,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 D.box(D.types.av01,F,D.box(D.types.av1C,w))},D.mvex=function(A){return D.box(D.types.mvex,D.trex(A))},D.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 D.box(D.types.trex,x)},D.moof=function(A,w){return D.box(D.types.moof,D.mfhd(A.sequenceNumber),D.traf(A,w))},D.mfhd=function(A){var w=new Uint8Array([0,0,0,0,A>>>24&255,A>>>16&255,A>>>8&255,255&A]);return D.box(D.types.mfhd,w)},D.traf=function(A,w){var x=A.id,O=D.box(D.types.tfhd,new Uint8Array([0,0,0,0,x>>>24&255,x>>>16&255,x>>>8&255,255&x])),F=D.box(D.types.tfdt,new Uint8Array([0,0,0,0,w>>>24&255,w>>>16&255,w>>>8&255,255&w])),$=D.sdtp(A),z=D.trun(A,$.byteLength+16+16+8+16+8+8);return D.box(D.types.traf,O,F,z,$)},D.sdtp=function(A){for(var w=A.samples||[],x=w.length,O=new Uint8Array(4+x),F=0;F<x;F++){var $=w[F].flags;O[F+4]=$.isLeading<<6|$.dependsOn<<4|$.isDependedOn<<2|$.hasRedundancy}return D.box(D.types.sdtp,O)},D.trun=function(A,w){var x=A.samples||[],O=x.length,F=12+16*O,$=new Uint8Array(F);w+=8+F,$.set([0,0,15,1,O>>>24&255,O>>>16&255,O>>>8&255,255&O,w>>>24&255,w>>>16&255,w>>>8&255,255&w],0);for(var z=0;z<O;z++){var se=x[z].duration,te=x[z].size,ie=x[z].flags,le=x[z].cts;$.set([se>>>24&255,se>>>16&255,se>>>8&255,255&se,te>>>24&255,te>>>16&255,te>>>8&255,255&te,ie.isLeading<<2|ie.dependsOn,ie.isDependedOn<<6|ie.hasRedundancy<<4|ie.isNonSync,0,0,le>>>24&255,le>>>16&255,le>>>8&255,255&le],12+16*z)}return D.box(D.types.trun,$)},D.mdat=function(A){return D.box(D.types.mdat,A)},D}();er.init();var mr=er,ss=function(){function D(){}return D.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},D}(),kt=s(11),an=function(){function D(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 kt.c("audio"),this._videoSegmentInfoList=new kt.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 D.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},D.prototype.bindDataSource=function(A){return A.onDataAvailable=this.remux.bind(this),A.onTrackMetadata=this._onTrackMetadataReceived.bind(this),this},Object.defineProperty(D.prototype,"onInitSegment",{get:function(){return this._onInitSegment},set:function(A){this._onInitSegment=A},enumerable:!1,configurable:!0}),Object.defineProperty(D.prototype,"onMediaSegment",{get:function(){return this._onMediaSegment},set:function(A){this._onMediaSegment=A},enumerable:!1,configurable:!0}),D.prototype.insertDiscontinuity=function(){this._audioNextDts=this._videoNextDts=void 0},D.prototype.seek=function(A){this._audioStashedLastSample=null,this._videoStashedLastSample=null,this._videoSegmentInfoList.clear(),this._audioSegmentInfoList.clear()},D.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)},D.prototype._onTrackMetadataReceived=function(A,w){var x=null,O="mp4",F=w.codec;if(A==="audio")this._audioMeta=w,w.codec==="mp3"&&this._mp3UseMpegAudio?(O="mpeg",F="",x=new Uint8Array):x=mr.generateInitSegment(w);else{if(A!=="video")return;this._videoMeta=w,x=mr.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(O),mediaDuration:w.duration})},D.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)},D.prototype.getTimestampBase=function(){if(this._dtsBaseInited)return this._dtsBase},D.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 O={type:"audio",id:2,sequenceNumber:0,samples:[],length:0};w!=null&&(O.samples.push(w),O.length=w.length),this._videoStashedLastSample=null,this._audioStashedLastSample=null,this._remuxVideo(x,!0),this._remuxAudio(O,!0)},D.prototype._remuxAudio=function(A,w){if(this._audioMeta!=null){var x,O=A,F=O.samples,$=void 0,z=-1,se=this._audioMeta.refSampleDuration,te=this._audioMeta.codec==="mp3"&&this._mp3UseMpegAudio,ie=this._dtsBaseInited&&this._audioNextDts===void 0,le=!1;if(F&&F.length!==0&&(F.length!==1||w)){var ae=0,ce=null,Ce=0;te?(ae=0,Ce=O.length):(ae=8,Ce=8+O.length);var Me=null;if(F.length>1&&(Ce-=(Me=F.pop()).length),this._audioStashedLastSample!=null){var Le=this._audioStashedLastSample;this._audioStashedLastSample=null,F.unshift(Le),Ce+=Le.length}Me!=null&&(this._audioStashedLastSample=Me);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 Ve=Je-(Ye.originalDts+Ye.duration);Ve<=3&&(Ve=0),$=Je-(Ye.dts+Ye.duration+Ve)}else $=0}if(le){var pt=Je-$,Et=this._videoSegmentInfoList.getLastSegmentBefore(Je);if(Et!=null&&Et.beginDts<pt){if(Tn=ss.getSilentFrame(this._audioMeta.originalCodec,this._audioMeta.channelCount)){var Xe=Et.beginDts,He=pt-Et.beginDts;o.a.v(this.TAG,"InsertPrefixSilentAudio: dts: ".concat(Xe,", duration: ").concat(He)),F.unshift({unit:Tn,dts:Xe,pts:Xe}),Ce+=Tn.byteLength}}else le=!1}for(var Lt=[],mt=0;mt<F.length;mt++){var vt=(Le=F[mt]).unit,Ut=Le.dts-this._dtsBase,tn=(Xe=Ut,!1),bt=null,Nt=0;if(!(Ut<-.001)){if(this._audioMeta.codec!=="mp3"&&se!=null){var yt=Ut;if(this._audioNextDts&&(yt=this._audioNextDts),($=Ut-yt)<=-3*se){o.a.w(this.TAG,"Dropping 1 audio frame (originalDts: ".concat(Ut," ms ,curRefDts: ").concat(yt," ms)  due to dtsCorrection: ").concat($," ms overlap."));continue}if($>=3*se&&this._fillAudioTimestampGap&&!l.a.safari){tn=!0;var Tn,Or=Math.floor($/se);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(Ut," ms, curRefDts: ").concat(yt," ms, ")+"dtsCorrection: ".concat(Math.round($)," ms, generate: ").concat(Or," frames")),Xe=Math.floor(yt),Nt=Math.floor(yt+se)-Xe,(Tn=ss.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")),Tn=vt),bt=[];for(var $n=0;$n<Or;$n++){yt+=se;var Nr=Math.floor(yt),gr=Math.floor(yt+se)-Nr,tr={dts:Nr,pts:Nr,cts:0,unit:Tn,size:Tn.byteLength,duration:gr,originalDts:Ut,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0}};bt.push(tr),Ce+=tr.size}this._audioNextDts=yt+se}else Xe=Math.floor(yt),Nt=Math.floor(yt+se)-Xe,this._audioNextDts=yt+se}else Xe=Ut-$,mt!==F.length-1?Nt=F[mt+1].dts-this._dtsBase-$-Xe:Me!=null?Nt=Me.dts-this._dtsBase-$-Xe:Nt=Lt.length>=1?Lt[Lt.length-1].duration:Math.floor(se),this._audioNextDts=Xe+Nt;z===-1&&(z=Xe),Lt.push({dts:Xe,pts:Xe,cts:0,unit:Le.unit,size:Le.unit.byteLength,duration:Nt,originalDts:Ut,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0}}),tn&&Lt.push.apply(Lt,bt)}}if(Lt.length===0)return O.samples=[],void(O.length=0);for(te?ce=new Uint8Array(Ce):((ce=new Uint8Array(Ce))[0]=Ce>>>24&255,ce[1]=Ce>>>16&255,ce[2]=Ce>>>8&255,ce[3]=255&Ce,ce.set(mr.types.mdat,4)),mt=0;mt<Lt.length;mt++)vt=Lt[mt].unit,ce.set(vt,ae),ae+=vt.byteLength;var Tr=Lt[Lt.length-1];x=Tr.dts+Tr.duration;var Ht=new kt.b;Ht.beginDts=z,Ht.endDts=x,Ht.beginPts=z,Ht.endPts=x,Ht.originalBeginDts=Lt[0].originalDts,Ht.originalEndDts=Tr.originalDts+Tr.duration,Ht.firstSample=new kt.d(Lt[0].dts,Lt[0].pts,Lt[0].duration,Lt[0].originalDts,!1),Ht.lastSample=new kt.d(Tr.dts,Tr.pts,Tr.duration,Tr.originalDts,!1),this._isLive||this._audioSegmentInfoList.append(Ht),O.samples=Lt,O.sequenceNumber++;var oi=null;oi=te?new Uint8Array:mr.moof(O,z),O.samples=[],O.length=0;var Di={type:"audio",data:this._mergeBoxes(oi,ce).buffer,sampleCount:Lt.length,info:Ht};te&&ie&&(Di.timestampOffset=z),this._onMediaSegment("audio",Di)}}},D.prototype._remuxVideo=function(A,w){if(this._videoMeta!=null){var x,O,F=A,$=F.samples,z=void 0,se=-1,te=-1;if($&&$.length!==0&&($.length!==1||w)){var ie=8,le=null,ae=8+A.length,ce=null;if($.length>1&&(ae-=(ce=$.pop()).length),this._videoStashedLastSample!=null){var Ce=this._videoStashedLastSample;this._videoStashedLastSample=null,$.unshift(Ce),ae+=Ce.length}ce!=null&&(this._videoStashedLastSample=ce);var Me=$[0].dts-this._dtsBase;if(this._videoNextDts)z=Me-this._videoNextDts;else if(this._videoSegmentInfoList.isEmpty())z=0;else{var Le=this._videoSegmentInfoList.getLastSampleBefore(Me);if(Le!=null){var Je=Me-(Le.originalDts+Le.duration);Je<=3&&(Je=0),z=Me-(Le.dts+Le.duration+Je)}else z=0}for(var Ye=new kt.b,Ve=[],pt=0;pt<$.length;pt++){var Et=(Ce=$[pt]).dts-this._dtsBase,Xe=Ce.isKeyframe,He=Et-z,Lt=Ce.cts,mt=He+Lt;se===-1&&(se=He,te=mt);var vt=0;if(pt!==$.length-1?vt=$[pt+1].dts-this._dtsBase-z-He:ce!=null?vt=ce.dts-this._dtsBase-z-He:vt=Ve.length>=1?Ve[Ve.length-1].duration:Math.floor(this._videoMeta.refSampleDuration),Xe){var Ut=new kt.d(He,mt,vt,Ce.dts,!0);Ut.fileposition=Ce.fileposition,Ye.appendSyncPoint(Ut)}Ve.push({dts:He,pts:mt,cts:Lt,units:Ce.units,size:Ce.length,isKeyframe:Xe,duration:vt,originalDts:Et,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(mr.types.mdat,4),pt=0;pt<Ve.length;pt++)for(var tn=Ve[pt].units;tn.length;){var bt=tn.shift().data;le.set(bt,ie),ie+=bt.byteLength}var Nt=Ve[Ve.length-1];if(x=Nt.dts+Nt.duration,O=Nt.pts+Nt.duration,this._videoNextDts=x,Ye.beginDts=se,Ye.endDts=x,Ye.beginPts=te,Ye.endPts=O,Ye.originalBeginDts=Ve[0].originalDts,Ye.originalEndDts=Nt.originalDts+Nt.duration,Ye.firstSample=new kt.d(Ve[0].dts,Ve[0].pts,Ve[0].duration,Ve[0].originalDts,Ve[0].isKeyframe),Ye.lastSample=new kt.d(Nt.dts,Nt.pts,Nt.duration,Nt.originalDts,Nt.isKeyframe),this._isLive||this._videoSegmentInfoList.append(Ye),F.samples=Ve,F.sequenceNumber++,this._forceFirstIDR){var yt=Ve[0].flags;yt.dependsOn=2,yt.isNonSync=0}var Tn=mr.moof(F,se);F.samples=[],F.length=0,this._onMediaSegment("video",{type:"video",data:this._mergeBoxes(Tn,le).buffer,sampleCount:Ve.length,info:Ye})}}},D.prototype._mergeBoxes=function(A,w){var x=new Uint8Array(A.byteLength+w.byteLength);return x.set(A,0),x.set(w,A.byteLength),x},D}(),o_=s(14),Mn=s(1),vu=(s(2),function(){function D(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(O){O.timestampBase=x,x+=O.duration,O.cors=A.cors,O.withCredentials=A.withCredentials,w.referrerPolicy&&(O.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 D.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},D.prototype.on=function(A,w){this._emitter.addListener(A,w)},D.prototype.off=function(A,w){this._emitter.removeListener(A,w)},D.prototype.start=function(){this._loadSegment(0),this._enableStatisticsReporter()},D.prototype._loadSegment=function(A,w){this._currentSegmentIndex=A;var x=this._mediaDataSource.segments[A],O=this._ioctl=new o_.a(x,this._config,A);O.onError=this._onIOException.bind(this),O.onSeeked=this._onIOSeeked.bind(this),O.onComplete=this._onIOComplete.bind(this),O.onRedirect=this._onIORedirect.bind(this),O.onRecoveredEarlyEof=this._onIORecoveredEarlyEof.bind(this),w?this._demuxer.bindDataSource(this._ioctl):O.onDataArrival=this._onInitChunkArrival.bind(this),O.open(w)},D.prototype.stop=function(){this._internalAbort(),this._disableStatisticsReporter()},D.prototype._internalAbort=function(){this._ioctl&&(this._ioctl.destroy(),this._ioctl=null)},D.prototype.pause=function(){this._ioctl&&this._ioctl.isWorking()&&(this._ioctl.pause(),this._disableStatisticsReporter())},D.prototype.resume=function(){this._ioctl&&this._ioctl.isPaused()&&(this._ioctl.resume(),this._enableStatisticsReporter())},D.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 O=x.getNearestKeyframe(A);this._remuxer.seek(O.milliseconds),this._ioctl.seek(O.fileposition),this._pendingResolveSeekPoint=O.milliseconds}}else{var F=this._mediaInfo.segments[w];F==null?(this._pendingSeekTime=A,this._internalAbort(),this._remuxer.seek(),this._remuxer.insertDiscontinuity(),this._loadSegment(w)):(O=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,O.fileposition),this._pendingResolveSeekPoint=O.milliseconds,this._reportSegmentMediaInfo(w))}this._enableStatisticsReporter()}},D.prototype._searchSegmentIndexContains=function(A){for(var w=this._mediaDataSource.segments,x=w.length-1,O=0;O<w.length;O++)if(A<w[O].timestampBase){x=O-1;break}return x},D.prototype._onInitChunkArrival=function(A,w){var x=this,O=0;if(w>0)this._demuxer.bindDataSource(this._ioctl),this._demuxer.timestampBase=this._mediaDataSource.segments[this._currentSegmentIndex].timestampBase,O=this._demuxer.parseChunks(A,w);else{var F=null;(F=M.probe(A)).match&&(this._setupFLVDemuxerRemuxer(F),O=this._demuxer.parseChunks(A,w)),F.match||F.needMoreData||(F=cn.probe(A)).match&&(this._setupTSDemuxerRemuxer(F),O=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(Mn.a.DEMUX_ERROR,_.a.FORMAT_UNSUPPORTED,"Non MPEG-TS/FLV, Unsupported media type!"))}return O},D.prototype._setupFLVDemuxerRemuxer=function(A){this._demuxer=new M(A,this._config),this._remuxer||(this._remuxer=new an(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)},D.prototype._setupTSDemuxerRemuxer=function(A){var w=this._demuxer=new cn(A,this._config);this._remuxer||(this._remuxer=new an(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)},D.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 O=w._pendingSeekTime;w._pendingSeekTime=null,w.seek(O)})},D.prototype._onMetaDataArrived=function(A){this._emitter.emit(Mn.a.METADATA_ARRIVED,A)},D.prototype._onScriptDataArrived=function(A){this._emitter.emit(Mn.a.SCRIPTDATA_ARRIVED,A)},D.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(Mn.a.TIMED_ID3_METADATA_ARRIVED,A))},D.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(Mn.a.SYNCHRONOUS_KLV_METADATA_ARRIVED,A))},D.prototype._onAsynchronousKLVMetadata=function(A){this._emitter.emit(Mn.a.ASYNCHRONOUS_KLV_METADATA_ARRIVED,A)},D.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(Mn.a.SMPTE2038_METADATA_ARRIVED,A))},D.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(Mn.a.SCTE35_METADATA_ARRIVED,A))},D.prototype._onPESPrivateDataDescriptor=function(A){this._emitter.emit(Mn.a.PES_PRIVATE_DATA_DESCRIPTOR,A)},D.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(Mn.a.PES_PRIVATE_DATA_ARRIVED,A))},D.prototype._onIOSeeked=function(){this._remuxer.insertDiscontinuity()},D.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(Mn.a.LOADING_COMPLETE),this._disableStatisticsReporter())},D.prototype._onIORedirect=function(A){var w=this._ioctl.extraData;this._mediaDataSource.segments[w].redirectedURL=A},D.prototype._onIORecoveredEarlyEof=function(){this._emitter.emit(Mn.a.RECOVERED_EARLY_EOF)},D.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(Mn.a.IO_ERROR,A,w),this._disableStatisticsReporter()},D.prototype._onDemuxException=function(A,w){o.a.e(this.TAG,"DemuxException: type = ".concat(A,", info = ").concat(w)),this._emitter.emit(Mn.a.DEMUX_ERROR,A,w)},D.prototype._onRemuxerInitSegmentArrival=function(A,w){this._emitter.emit(Mn.a.INIT_SEGMENT,A,w)},D.prototype._onRemuxerMediaSegmentArrival=function(A,w){if(this._pendingSeekTime==null&&(this._emitter.emit(Mn.a.MEDIA_SEGMENT,A,w),this._pendingResolveSeekPoint!=null&&A==="video")){var x=w.info.syncPoints,O=this._pendingResolveSeekPoint;this._pendingResolveSeekPoint=null,l.a.safari&&x.length>0&&x[0].originalDts===O&&(O=x[0].pts),this._emitter.emit(Mn.a.RECOMMEND_SEEKPOINT,O)}},D.prototype._enableStatisticsReporter=function(){this._statisticsReporter==null&&(this._statisticsReporter=self.setInterval(this._reportStatisticsInfo.bind(this),this._config.statisticsInfoReportInterval))},D.prototype._disableStatisticsReporter=function(){this._statisticsReporter&&(self.clearInterval(this._statisticsReporter),this._statisticsReporter=null)},D.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(Mn.a.MEDIA_INFO,x)},D.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(Mn.a.STATISTICS_INFO,A)},D}());r.a=vu},function(n,r,s){var i,a=s(0),o=function(){function P(){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 P.prototype.reset=function(){this._firstCheckpoint=this._lastCheckpoint=0,this._totalBytes=this._intervalBytes=0,this._lastSecondBytes=0},P.prototype.addBytes=function(I){this._firstCheckpoint===0?(this._firstCheckpoint=this._now(),this._lastCheckpoint=this._firstCheckpoint,this._intervalBytes+=I,this._totalBytes+=I):this._now()-this._lastCheckpoint<1e3?(this._intervalBytes+=I,this._totalBytes+=I):(this._lastSecondBytes=this._intervalBytes,this._intervalBytes=I,this._totalBytes+=I,this._lastCheckpoint=this._now())},Object.defineProperty(P.prototype,"currentKBps",{get:function(){this.addBytes(0);var I=(this._now()-this._lastCheckpoint)/1e3;return I==0&&(I=1),this._intervalBytes/I/1024},enumerable:!1,configurable:!0}),Object.defineProperty(P.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(P.prototype,"averageKBps",{get:function(){var I=(this._now()-this._firstCheckpoint)/1e3;return this._totalBytes/I/1024},enumerable:!1,configurable:!0}),P}(),l=s(2),c=s(5),u=s(3),d=(i=function(P,I){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(k,R){k.__proto__=R}||function(k,R){for(var M in R)Object.prototype.hasOwnProperty.call(R,M)&&(k[M]=R[M])})(P,I)},function(P,I){if(typeof I!="function"&&I!==null)throw new TypeError("Class extends value "+String(I)+" is not a constructor or null");function k(){this.constructor=P}i(P,I),P.prototype=I===null?Object.create(I):(k.prototype=I.prototype,new k)}),h=function(P){function I(k,R){var M=P.call(this,"fetch-stream-loader")||this;return M.TAG="FetchStreamLoader",M._seekHandler=k,M._config=R,M._needStash=!0,M._requestAbort=!1,M._abortController=null,M._contentLength=null,M._receivedLength=0,M}return d(I,P),I.isSupported=function(){try{var k=c.a.msedge&&c.a.version.minor>=15048,R=!c.a.msedge||k;return self.fetch&&self.ReadableStream&&R}catch{return!1}},I.prototype.destroy=function(){this.isWorking()&&this.abort(),P.prototype.destroy.call(this)},I.prototype.open=function(k,R){var M=this;this._dataSource=k,this._range=R;var G=k.url;this._config.reuseRedirectedURL&&k.redirectedURL!=null&&(G=k.redirectedURL);var Y=this._seekHandler.getConfig(G,R),q=new self.Headers;if(typeof Y.headers=="object"){var X=Y.headers;for(var Z in X)X.hasOwnProperty(Z)&&q.append(Z,X[Z])}var oe={method:"GET",headers:q,mode:"cors",cache:"default",referrerPolicy:"no-referrer-when-downgrade"};if(typeof this._config.headers=="object")for(var Z in this._config.headers)q.append(Z,this._config.headers[Z]);k.cors===!1&&(oe.mode="same-origin"),k.withCredentials&&(oe.credentials="include"),k.referrerPolicy&&(oe.referrerPolicy=k.referrerPolicy),self.AbortController&&(this._abortController=new self.AbortController,oe.signal=this._abortController.signal),this._status=l.c.kConnecting,self.fetch(Y.url,oe).then(function(ne){if(M._requestAbort)return M._status=l.c.kIdle,void ne.body.cancel();if(ne.ok&&ne.status>=200&&ne.status<=299){if(ne.url!==Y.url&&M._onURLRedirect){var H=M._seekHandler.removeURLParameters(ne.url);M._onURLRedirect(H)}var K=ne.headers.get("Content-Length");return K!=null&&(M._contentLength=parseInt(K),M._contentLength!==0&&M._onContentLengthKnown&&M._onContentLengthKnown(M._contentLength)),M._pump.call(M,ne.body.getReader())}if(M._status=l.c.kError,!M._onError)throw new u.d("FetchStreamLoader: Http code invalid, "+ne.status+" "+ne.statusText);M._onError(l.b.HTTP_STATUS_CODE_INVALID,{code:ne.status,msg:ne.statusText})}).catch(function(ne){if(!M._abortController||!M._abortController.signal.aborted){if(M._status=l.c.kError,!M._onError)throw ne;M._onError(l.b.EXCEPTION,{code:-1,msg:ne.message})}})},I.prototype.abort=function(){if(this._requestAbort=!0,(this._status!==l.c.kBuffering||!c.a.chrome)&&this._abortController)try{this._abortController.abort()}catch{}},I.prototype._pump=function(k){var R=this;return k.read().then(function(M){if(M.done)if(R._contentLength!==null&&R._receivedLength<R._contentLength){R._status=l.c.kError;var G=l.b.EARLY_EOF,Y={code:-1,msg:"Fetch stream meet Early-EOF"};if(!R._onError)throw new u.d(Y.msg);R._onError(G,Y)}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,k.cancel();R._status=l.c.kBuffering;var q=M.value.buffer,X=R._range.from+R._receivedLength;R._receivedLength+=q.byteLength,R._onDataArrival&&R._onDataArrival(q,X,R._receivedLength),R._pump(k)}}).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 G=0,Y=null;if(M.code!==19&&M.message!=="network error"||!(R._contentLength===null||R._contentLength!==null&&R._receivedLength<R._contentLength)?(G=l.b.EXCEPTION,Y={code:M.code,msg:M.message}):(G=l.b.EARLY_EOF,Y={code:M.code,msg:"Fetch stream meet Early-EOF"}),!R._onError)throw new u.d(Y.msg);R._onError(G,Y)}})},I}(l.a),f=function(){var P=function(I,k){return(P=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(R,M){R.__proto__=M}||function(R,M){for(var G in M)Object.prototype.hasOwnProperty.call(M,G)&&(R[G]=M[G])})(I,k)};return function(I,k){if(typeof k!="function"&&k!==null)throw new TypeError("Class extends value "+String(k)+" is not a constructor or null");function R(){this.constructor=I}P(I,k),I.prototype=k===null?Object.create(k):(R.prototype=k.prototype,new R)}}(),m=function(P){function I(k,R){var M=P.call(this,"xhr-moz-chunked-loader")||this;return M.TAG="MozChunkedLoader",M._seekHandler=k,M._config=R,M._needStash=!0,M._xhr=null,M._requestAbort=!1,M._contentLength=null,M._receivedLength=0,M}return f(I,P),I.isSupported=function(){try{var k=new XMLHttpRequest;return k.open("GET","https://example.com",!0),k.responseType="moz-chunked-arraybuffer",k.responseType==="moz-chunked-arraybuffer"}catch(R){return a.a.w("MozChunkedLoader",R.message),!1}},I.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),P.prototype.destroy.call(this)},I.prototype.open=function(k,R){this._dataSource=k,this._range=R;var M=k.url;this._config.reuseRedirectedURL&&k.redirectedURL!=null&&(M=k.redirectedURL);var G=this._seekHandler.getConfig(M,R);this._requestURL=G.url;var Y=this._xhr=new XMLHttpRequest;if(Y.open("GET",G.url,!0),Y.responseType="moz-chunked-arraybuffer",Y.onreadystatechange=this._onReadyStateChange.bind(this),Y.onprogress=this._onProgress.bind(this),Y.onloadend=this._onLoadEnd.bind(this),Y.onerror=this._onXhrError.bind(this),k.withCredentials&&(Y.withCredentials=!0),typeof G.headers=="object"){var q=G.headers;for(var X in q)q.hasOwnProperty(X)&&Y.setRequestHeader(X,q[X])}if(typeof this._config.headers=="object"){q=this._config.headers;for(var X in q)q.hasOwnProperty(X)&&Y.setRequestHeader(X,q[X])}this._status=l.c.kConnecting,Y.send()},I.prototype.abort=function(){this._requestAbort=!0,this._xhr&&this._xhr.abort(),this._status=l.c.kComplete},I.prototype._onReadyStateChange=function(k){var R=k.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}},I.prototype._onProgress=function(k){if(this._status!==l.c.kError){this._contentLength===null&&k.total!==null&&k.total!==0&&(this._contentLength=k.total,this._onContentLengthKnown&&this._onContentLengthKnown(this._contentLength));var R=k.target.response,M=this._range.from+this._receivedLength;this._receivedLength+=R.byteLength,this._onDataArrival&&this._onDataArrival(R,M,this._receivedLength)}},I.prototype._onLoadEnd=function(k){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},I.prototype._onXhrError=function(k){this._status=l.c.kError;var R=0,M=null;if(this._contentLength&&k.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:k.constructor.name+" "+k.type}),!this._onError)throw new u.d(M.msg);this._onError(R,M)},I}(l.a),g=function(){var P=function(I,k){return(P=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(R,M){R.__proto__=M}||function(R,M){for(var G in M)Object.prototype.hasOwnProperty.call(M,G)&&(R[G]=M[G])})(I,k)};return function(I,k){if(typeof k!="function"&&k!==null)throw new TypeError("Class extends value "+String(k)+" is not a constructor or null");function R(){this.constructor=I}P(I,k),I.prototype=k===null?Object.create(k):(R.prototype=k.prototype,new R)}}(),y=(function(P){function I(k,R){var M=P.call(this,"xhr-msstream-loader")||this;return M.TAG="MSStreamLoader",M._seekHandler=k,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}g(I,P),I.isSupported=function(){try{if(self.MSStream===void 0||self.MSStreamReader===void 0)return!1;var k=new XMLHttpRequest;return k.open("GET","https://example.com",!0),k.responseType="ms-stream",k.responseType==="ms-stream"}catch(R){return a.a.w("MSStreamLoader",R.message),!1}},I.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),P.prototype.destroy.call(this)},I.prototype.open=function(k,R){this._internalOpen(k,R,!1)},I.prototype._internalOpen=function(k,R,M){this._dataSource=k,M?this._currentRange=R:this._totalRange=R;var G=k.url;this._config.reuseRedirectedURL&&(this._currentRedirectedURL!=null?G=this._currentRedirectedURL:k.redirectedURL!=null&&(G=k.redirectedURL));var Y=this._seekHandler.getConfig(G,R);this._currentRequestURL=Y.url;var q=this._reader=new self.MSStreamReader;q.onprogress=this._msrOnProgress.bind(this),q.onload=this._msrOnLoad.bind(this),q.onerror=this._msrOnError.bind(this);var X=this._xhr=new XMLHttpRequest;if(X.open("GET",Y.url,!0),X.responseType="ms-stream",X.onreadystatechange=this._xhrOnReadyStateChange.bind(this),X.onerror=this._xhrOnError.bind(this),k.withCredentials&&(X.withCredentials=!0),typeof Y.headers=="object"){var Z=Y.headers;for(var oe in Z)Z.hasOwnProperty(oe)&&X.setRequestHeader(oe,Z[oe])}if(typeof this._config.headers=="object"){Z=this._config.headers;for(var oe in Z)Z.hasOwnProperty(oe)&&X.setRequestHeader(oe,Z[oe])}this._isReconnecting?this._isReconnecting=!1:this._status=l.c.kConnecting,X.send()},I.prototype.abort=function(){this._internalAbort(),this._status=l.c.kComplete},I.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)},I.prototype._xhrOnReadyStateChange=function(k){var R=k.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 G=R.getResponseHeader("Content-Length");if(G!=null&&this._contentLength==null){var Y=parseInt(G);Y>0&&(this._contentLength=Y,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 q=R.response;this._reader.readAsArrayBuffer(q)}},I.prototype._xhrOnError=function(k){this._status=l.c.kError;var R=l.b.EXCEPTION,M={code:-1,msg:k.constructor.name+" "+k.type};if(!this._onError)throw new u.d(M.msg);this._onError(R,M)},I.prototype._msrOnProgress=function(k){var R=k.target.result;if(R!=null){var M=R.slice(this._lastTimeBufferSize);this._lastTimeBufferSize=R.byteLength;var G=this._totalRange.from+this._receivedLength;this._receivedLength+=M.byteLength,this._onDataArrival&&this._onDataArrival(M,G,this._receivedLength),R.byteLength>=this._bufferLimit&&(a.a.v(this.TAG,"MSStream buffer exceeded max size near ".concat(G+M.byteLength,", reconnecting...")),this._doReconnectIfNeeded())}else this._doReconnectIfNeeded()},I.prototype._doReconnectIfNeeded=function(){if(this._contentLength==null||this._receivedLength<this._contentLength){this._isReconnecting=!0,this._lastTimeBufferSize=0,this._internalAbort();var k={from:this._totalRange.from+this._receivedLength,to:-1};this._internalOpen(this._dataSource,k,!0)}},I.prototype._msrOnLoad=function(k){this._status=l.c.kComplete,this._onComplete&&this._onComplete(this._totalRange.from,this._totalRange.from+this._receivedLength-1)},I.prototype._msrOnError=function(k){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:k.constructor.name+" "+k.type}),!this._onError)throw new u.d(M.msg);this._onError(R,M)}}(l.a),function(){var P=function(I,k){return(P=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(R,M){R.__proto__=M}||function(R,M){for(var G in M)Object.prototype.hasOwnProperty.call(M,G)&&(R[G]=M[G])})(I,k)};return function(I,k){if(typeof k!="function"&&k!==null)throw new TypeError("Class extends value "+String(k)+" is not a constructor or null");function R(){this.constructor=I}P(I,k),I.prototype=k===null?Object.create(k):(R.prototype=k.prototype,new R)}}()),v=function(P){function I(k,R){var M=P.call(this,"xhr-range-loader")||this;return M.TAG="RangeLoader",M._seekHandler=k,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 y(I,P),I.isSupported=function(){try{var k=new XMLHttpRequest;return k.open("GET","https://example.com",!0),k.responseType="arraybuffer",k.responseType==="arraybuffer"}catch(R){return a.a.w("RangeLoader",R.message),!1}},I.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),P.prototype.destroy.call(this)},Object.defineProperty(I.prototype,"currentSpeed",{get:function(){return this._speedSampler.lastSecondKBps},enumerable:!1,configurable:!0}),I.prototype.open=function(k,R){this._dataSource=k,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}))},I.prototype._openSubRange=function(){var k=1024*this._currentChunkSizeKB,R=this._range.from+this._receivedLength,M=R+k;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)},I.prototype._internalOpen=function(k,R){this._lastTimeLoaded=0;var M=k.url;this._config.reuseRedirectedURL&&(this._currentRedirectedURL!=null?M=this._currentRedirectedURL:k.redirectedURL!=null&&(M=k.redirectedURL));var G=this._seekHandler.getConfig(M,R);this._currentRequestURL=G.url;var Y=this._xhr=new XMLHttpRequest;if(Y.open("GET",G.url,!0),Y.responseType="arraybuffer",Y.onreadystatechange=this._onReadyStateChange.bind(this),Y.onprogress=this._onProgress.bind(this),Y.onload=this._onLoad.bind(this),Y.onerror=this._onXhrError.bind(this),k.withCredentials&&(Y.withCredentials=!0),typeof G.headers=="object"){var q=G.headers;for(var X in q)q.hasOwnProperty(X)&&Y.setRequestHeader(X,q[X])}if(typeof this._config.headers=="object"){q=this._config.headers;for(var X in q)q.hasOwnProperty(X)&&Y.setRequestHeader(X,q[X])}Y.send()},I.prototype.abort=function(){this._requestAbort=!0,this._internalAbort(),this._status=l.c.kComplete},I.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)},I.prototype._onReadyStateChange=function(k){var R=k.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})}}},I.prototype._onProgress=function(k){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=k.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 G=k.loaded-this._lastTimeLoaded;this._lastTimeLoaded=k.loaded,this._speedSampler.addBytes(G)}},I.prototype._normalizeSpeed=function(k){var R=this._chunkSizeKBList,M=R.length-1,G=0,Y=0,q=M;if(k<R[0])return R[0];for(;Y<=q;){if((G=Y+Math.floor((q-Y)/2))===M||k>=R[G]&&k<R[G+1])return R[G];R[G]<k?Y=G+1:q=G-1}},I.prototype._onLoad=function(k){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 G=k.target.response,Y=this._range.from+this._receivedLength;this._receivedLength+=G.byteLength;var q=!1;this._contentLength!=null&&this._receivedLength<this._contentLength?this._openSubRange():q=!0,this._onDataArrival&&this._onDataArrival(G,Y,this._receivedLength),q&&(this._status=l.c.kComplete,this._onComplete&&this._onComplete(this._range.from,this._range.from+this._receivedLength-1))}},I.prototype._onXhrError=function(k){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:k.constructor.name+" "+k.type}),!this._onError)throw new u.d(M.msg);this._onError(R,M)},I}(l.a),_=function(){var P=function(I,k){return(P=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(R,M){R.__proto__=M}||function(R,M){for(var G in M)Object.prototype.hasOwnProperty.call(M,G)&&(R[G]=M[G])})(I,k)};return function(I,k){if(typeof k!="function"&&k!==null)throw new TypeError("Class extends value "+String(k)+" is not a constructor or null");function R(){this.constructor=I}P(I,k),I.prototype=k===null?Object.create(k):(R.prototype=k.prototype,new R)}}(),S=function(P){function I(){var k=P.call(this,"websocket-loader")||this;return k.TAG="WebSocketLoader",k._needStash=!0,k._ws=null,k._requestAbort=!1,k._receivedLength=0,k}return _(I,P),I.isSupported=function(){try{return self.WebSocket!==void 0}catch{return!1}},I.prototype.destroy=function(){this._ws&&this.abort(),P.prototype.destroy.call(this)},I.prototype.open=function(k){try{var R=this._ws=new self.WebSocket(k.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(G){this._status=l.c.kError;var M={code:G.code,msg:G.message};if(!this._onError)throw new u.d(M.msg);this._onError(l.b.EXCEPTION,M)}},I.prototype.abort=function(){var k=this._ws;!k||k.readyState!==0&&k.readyState!==1||(this._requestAbort=!0,k.close()),this._ws=null,this._status=l.c.kComplete},I.prototype._onWebSocketOpen=function(k){this._status=l.c.kBuffering},I.prototype._onWebSocketClose=function(k){this._requestAbort!==!0?(this._status=l.c.kComplete,this._onComplete&&this._onComplete(0,this._receivedLength-1)):this._requestAbort=!1},I.prototype._onWebSocketMessage=function(k){var R=this;if(k.data instanceof ArrayBuffer)this._dispatchArrayBuffer(k.data);else if(k.data instanceof Blob){var M=new FileReader;M.onload=function(){R._dispatchArrayBuffer(M.result)},M.readAsArrayBuffer(k.data)}else{this._status=l.c.kError;var G={code:-1,msg:"Unsupported WebSocket message type: "+k.data.constructor.name};if(!this._onError)throw new u.d(G.msg);this._onError(l.b.EXCEPTION,G)}},I.prototype._dispatchArrayBuffer=function(k){var R=k,M=this._receivedLength;this._receivedLength+=R.byteLength,this._onDataArrival&&this._onDataArrival(R,M,this._receivedLength)},I.prototype._onWebSocketError=function(k){this._status=l.c.kError;var R={code:k.code,msg:k.message};if(!this._onError)throw new u.d(R.msg);this._onError(l.b.EXCEPTION,R)},I}(l.a),E=function(){function P(I){this._zeroStart=I||!1}return P.prototype.getConfig=function(I,k){var R={};if(k.from!==0||k.to!==-1){var M=void 0;M=k.to!==-1?"bytes=".concat(k.from.toString(),"-").concat(k.to.toString()):"bytes=".concat(k.from.toString(),"-"),R.Range=M}else this._zeroStart&&(R.Range="bytes=0-");return{url:I,headers:R}},P.prototype.removeURLParameters=function(I){return I},P}(),L=function(){function P(I,k){this._startName=I,this._endName=k}return P.prototype.getConfig=function(I,k){var R=I;if(k.from!==0||k.to!==-1){var M=!0;R.indexOf("?")===-1&&(R+="?",M=!1),M&&(R+="&"),R+="".concat(this._startName,"=").concat(k.from.toString()),k.to!==-1&&(R+="&".concat(this._endName,"=").concat(k.to.toString()))}return{url:R,headers:{}}},P.prototype.removeURLParameters=function(I){var k=I.split("?")[0],R=void 0,M=I.indexOf("?");M!==-1&&(R=I.substring(M+1));var G="";if(R!=null&&R.length>0)for(var Y=R.split("&"),q=0;q<Y.length;q++){var X=Y[q].split("="),Z=q>0;X[0]!==this._startName&&X[0]!==this._endName&&(Z&&(G+="&"),G+=Y[q])}return G.length===0?k:k+"?"+G},P}(),U=function(){function P(I,k,R){this.TAG="IOController",this._config=k,this._extraData=R,this._stashInitialSize=65536,k.stashInitialSize!=null&&k.stashInitialSize>0&&(this._stashInitialSize=k.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,k.enableStashBuffer===!1&&(this._enableStash=!1),this._loader=null,this._loaderClass=null,this._seekHandler=null,this._dataSource=I,this._isWebSocketURL=/wss?:\/\/(.+?)/.test(I.url),this._refTotalLength=I.filesize?I.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 P.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},P.prototype.isWorking=function(){return this._loader&&this._loader.isWorking()&&!this._paused},P.prototype.isPaused=function(){return this._paused},Object.defineProperty(P.prototype,"status",{get:function(){return this._loader.status},enumerable:!1,configurable:!0}),Object.defineProperty(P.prototype,"extraData",{get:function(){return this._extraData},set:function(I){this._extraData=I},enumerable:!1,configurable:!0}),Object.defineProperty(P.prototype,"onDataArrival",{get:function(){return this._onDataArrival},set:function(I){this._onDataArrival=I},enumerable:!1,configurable:!0}),Object.defineProperty(P.prototype,"onSeeked",{get:function(){return this._onSeeked},set:function(I){this._onSeeked=I},enumerable:!1,configurable:!0}),Object.defineProperty(P.prototype,"onError",{get:function(){return this._onError},set:function(I){this._onError=I},enumerable:!1,configurable:!0}),Object.defineProperty(P.prototype,"onComplete",{get:function(){return this._onComplete},set:function(I){this._onComplete=I},enumerable:!1,configurable:!0}),Object.defineProperty(P.prototype,"onRedirect",{get:function(){return this._onRedirect},set:function(I){this._onRedirect=I},enumerable:!1,configurable:!0}),Object.defineProperty(P.prototype,"onRecoveredEarlyEof",{get:function(){return this._onRecoveredEarlyEof},set:function(I){this._onRecoveredEarlyEof=I},enumerable:!1,configurable:!0}),Object.defineProperty(P.prototype,"currentURL",{get:function(){return this._dataSource.url},enumerable:!1,configurable:!0}),Object.defineProperty(P.prototype,"hasRedirect",{get:function(){return this._redirectedURL!=null||this._dataSource.redirectedURL!=null},enumerable:!1,configurable:!0}),Object.defineProperty(P.prototype,"currentRedirectedURL",{get:function(){return this._redirectedURL||this._dataSource.redirectedURL},enumerable:!1,configurable:!0}),Object.defineProperty(P.prototype,"currentSpeed",{get:function(){return this._loaderClass===v?this._loader.currentSpeed:this._speedSampler.lastSecondKBps},enumerable:!1,configurable:!0}),Object.defineProperty(P.prototype,"loaderType",{get:function(){return this._loader.type},enumerable:!1,configurable:!0}),P.prototype._selectSeekHandler=function(){var I=this._config;if(I.seekType==="range")this._seekHandler=new E(this._config.rangeLoadZeroStart);else if(I.seekType==="param"){var k=I.seekParamStart||"bstart",R=I.seekParamEnd||"bend";this._seekHandler=new L(k,R)}else{if(I.seekType!=="custom")throw new u.b("Invalid seekType in config: ".concat(I.seekType));if(typeof I.customSeekHandler!="function")throw new u.b("Custom seekType specified in config but invalid customSeekHandler!");this._seekHandler=new I.customSeekHandler}},P.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(m.isSupported())this._loaderClass=m;else{if(!v.isSupported())throw new u.d("Your browser doesn't support xhr with arraybuffer responseType!");this._loaderClass=v}},P.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)},P.prototype.open=function(I){this._currentRange={from:0,to:-1},I&&(this._currentRange.from=I),this._speedSampler.reset(),I||(this._fullRequestFlag=!0),this._loader.open(this._dataSource,Object.assign({},this._currentRange))},P.prototype.abort=function(){this._loader.abort(),this._paused&&(this._paused=!1,this._resumeFrom=0)},P.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)},P.prototype.resume=function(){if(this._paused){this._paused=!1;var I=this._resumeFrom;this._resumeFrom=0,this._internalSeek(I,!0)}},P.prototype.seek=function(I){this._paused=!1,this._stashUsed=0,this._stashByteStart=0,this._internalSeek(I,!0)},P.prototype._internalSeek=function(I,k){this._loader.isWorking()&&this._loader.abort(),this._flushStashBuffer(k),this._loader.destroy(),this._loader=null;var R={from:I,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()},P.prototype.updateUrl=function(I){if(!I||typeof I!="string"||I.length===0)throw new u.b("Url must be a non-empty string!");this._dataSource.url=I},P.prototype._expandBuffer=function(I){for(var k=this._stashSize;k+1048576<I;)k*=2;if((k+=1048576)!==this._bufferSize){var R=new ArrayBuffer(k);if(this._stashUsed>0){var M=new Uint8Array(this._stashBuffer,0,this._stashUsed);new Uint8Array(R,0,k).set(M,0)}this._stashBuffer=R,this._bufferSize=k}},P.prototype._normalizeSpeed=function(I){var k=this._speedNormalizeList,R=k.length-1,M=0,G=0,Y=R;if(I<k[0])return k[0];for(;G<=Y;){if((M=G+Math.floor((Y-G)/2))===R||I>=k[M]&&I<k[M+1])return k[M];k[M]<I?G=M+1:Y=M-1}},P.prototype._adjustStashSize=function(I){var k=0;(k=this._config.isLive?I/8:I<512?I:I>=512&&I<=1024?Math.floor(1.5*I):2*I)>8192&&(k=8192);var R=1024*k+1048576;this._bufferSize<R&&this._expandBuffer(R),this._stashSize=1024*k},P.prototype._dispatchChunks=function(I,k){return this._currentRange.to=k+I.byteLength-1,this._onDataArrival(I,k)},P.prototype._onURLRedirect=function(I){this._redirectedURL=I,this._onRedirect&&this._onRedirect(I)},P.prototype._onContentLengthKnown=function(I){I&&this._fullRequestFlag&&(this._totalLength=I,this._fullRequestFlag=!1)},P.prototype._onLoaderChunkArrival=function(I,k,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(I.byteLength);var M=this._speedSampler.lastSecondKBps;if(M!==0){var G=this._normalizeSpeed(M);this._speedNormalized!==G&&(this._speedNormalized=G,this._adjustStashSize(G))}if(this._enableStash)if(this._stashUsed===0&&this._stashByteStart===0&&(this._stashByteStart=k),this._stashUsed+I.byteLength<=this._stashSize)(X=new Uint8Array(this._stashBuffer,0,this._stashSize)).set(new Uint8Array(I),this._stashUsed),this._stashUsed+=I.byteLength;else if(X=new Uint8Array(this._stashBuffer,0,this._bufferSize),this._stashUsed>0){var Y=this._stashBuffer.slice(0,this._stashUsed);(Z=this._dispatchChunks(Y,this._stashByteStart))<Y.byteLength?Z>0&&(oe=new Uint8Array(Y,Z),X.set(oe,0),this._stashUsed=oe.byteLength,this._stashByteStart+=Z):(this._stashUsed=0,this._stashByteStart+=Z),this._stashUsed+I.byteLength>this._bufferSize&&(this._expandBuffer(this._stashUsed+I.byteLength),X=new Uint8Array(this._stashBuffer,0,this._bufferSize)),X.set(new Uint8Array(I),this._stashUsed),this._stashUsed+=I.byteLength}else(Z=this._dispatchChunks(I,k))<I.byteLength&&((q=I.byteLength-Z)>this._bufferSize&&(this._expandBuffer(q),X=new Uint8Array(this._stashBuffer,0,this._bufferSize)),X.set(new Uint8Array(I,Z),0),this._stashUsed+=q,this._stashByteStart=k+Z);else if(this._stashUsed===0){var q;(Z=this._dispatchChunks(I,k))<I.byteLength&&((q=I.byteLength-Z)>this._bufferSize&&this._expandBuffer(q),(X=new Uint8Array(this._stashBuffer,0,this._bufferSize)).set(new Uint8Array(I,Z),0),this._stashUsed+=q,this._stashByteStart=k+Z)}else{var X,Z;if(this._stashUsed+I.byteLength>this._bufferSize&&this._expandBuffer(this._stashUsed+I.byteLength),(X=new Uint8Array(this._stashBuffer,0,this._bufferSize)).set(new Uint8Array(I),this._stashUsed),this._stashUsed+=I.byteLength,(Z=this._dispatchChunks(this._stashBuffer.slice(0,this._stashUsed),this._stashByteStart))<this._stashUsed&&Z>0){var oe=new Uint8Array(this._stashBuffer,Z);X.set(oe,0)}this._stashUsed-=Z,this._stashByteStart+=Z}}},P.prototype._flushStashBuffer=function(I){if(this._stashUsed>0){var k=this._stashBuffer.slice(0,this._stashUsed),R=this._dispatchChunks(k,this._stashByteStart),M=k.byteLength-R;if(R<k.byteLength){if(!I){if(R>0){var G=new Uint8Array(this._stashBuffer,0,this._bufferSize),Y=new Uint8Array(k,R);G.set(Y,0),this._stashUsed=Y.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},P.prototype._onLoaderComplete=function(I,k){this._flushStashBuffer(!0),this._onComplete&&this._onComplete(this._extraData)},P.prototype._onLoaderError=function(I,k){switch(a.a.e(this.TAG,"Loader error, code = ".concat(k.code,", msg = ").concat(k.msg)),this._flushStashBuffer(!1),this._isEarlyEofReconnecting&&(this._isEarlyEofReconnecting=!1,I=l.b.UNRECOVERABLE_EARLY_EOF),I){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)))}I=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: "+k.msg);this._onError(I,k)},P}();r.a=U},function(n,r,s){var i=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"&&s(21).polyfill()},a}();i.install(),r.a=i},function(n,r,s){var i=s(9),a=s.n(i),o=s(0),l=s(5),c=s(7),u=s(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,m){this._emitter.addListener(f,m)},h.prototype.off=function(f,m){this._emitter.removeListener(f,m)},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 m=this._mediaSource=this._useManagedMediaSource?new self.ManagedMediaSource:new self.MediaSource;m.addEventListener("sourceopen",this.e.onSourceOpen),m.addEventListener("sourceended",this.e.onSourceEnded),m.addEventListener("sourceclose",this.e.onSourceClose),this._useManagedMediaSource&&(m.addEventListener("startstreaming",this.e.onStartStreaming),m.addEventListener("endstreaming",this.e.onEndStreaming),m.addEventListener("qualitychange",this.e.onQualityChange)),this._mediaElementProxy=f},h.prototype.shutdown=function(){if(this._mediaSource){var f=this._mediaSource;for(var m in this._sourceBuffers){var g=this._pendingSegments[m];g.splice(0,g.length),this._pendingSegments[m]=null,this._pendingRemoveRanges[m]=null,this._lastInitSegments[m]=null;var y=this._sourceBuffers[m];if(y){if(f.readyState!=="closed"){try{f.removeSourceBuffer(y)}catch(v){o.a.e(this.TAG,v.message)}y.removeEventListener("error",this.e.onSourceBufferError),y.removeEventListener("updateend",this.e.onSourceBufferUpdateEnd)}this._mimeTypes[m]=null,this._sourceBuffers[m]=null}}if(f.readyState==="open")try{f.endOfStream()}catch(v){o.a.e(this.TAG,v.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,m){if(m===void 0&&(m=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 g=f,y="".concat(g.container);g.codec&&g.codec.length>0&&(g.codec==="opus"&&l.a.safari&&(g.codec="Opus"),y+=";codecs=".concat(g.codec));var v=!1;if(o.a.v(this.TAG,"Received Initialization Segment, mimeType: "+y),this._lastInitSegments[g.type]=g,y!==this._mimeTypes[g.type]){if(this._mimeTypes[g.type])o.a.v(this.TAG,"Notice: ".concat(g.type," mimeType changed, origin: ").concat(this._mimeTypes[g.type],", target: ").concat(y));else{v=!0;try{var _=this._sourceBuffers[g.type]=this._mediaSource.addSourceBuffer(y);_.addEventListener("error",this.e.onSourceBufferError),_.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[g.type]=y}m||this._pendingSegments[g.type].push(g),v||this._sourceBuffers[g.type]&&!this._sourceBuffers[g.type].updating&&this._doAppendSegments(),l.a.safari&&g.container==="audio/mpeg"&&g.mediaDuration>0&&(this._requireSetMediaDuration=!0,this._pendingMediaDuration=g.mediaDuration/1e3,this._updateMediaSourceDuration())},h.prototype.appendMediaSegment=function(f){var m=f;this._pendingSegments[m.type].push(m),this._config.autoCleanupSourceBuffer&&this._needCleanupSourceBuffer()&&this._doCleanupSourceBuffer();var g=this._sourceBuffers[m.type];!g||g.updating||this._hasPendingRemoveRanges()||this._doAppendSegments()},h.prototype.flush=function(){for(var f in this._sourceBuffers)if(this._sourceBuffers[f]){var m=this._sourceBuffers[f];if(this._mediaSource.readyState==="open")try{m.abort()}catch(E){o.a.e(this.TAG,E.message)}var g=this._pendingSegments[f];if(g.splice(0,g.length),this._mediaSource.readyState!=="closed"){for(var y=0;y<m.buffered.length;y++){var v=m.buffered.start(y),_=m.buffered.end(y);this._pendingRemoveRanges[f].push({start:v,end:_})}if(m.updating||this._doRemoveRanges(),l.a.safari){var S=this._lastInitSegments[f];S&&(this._pendingSegments[f].push(S),m.updating||this._doAppendSegments())}}}},h.prototype.endOfStream=function(){var f=this._mediaSource,m=this._sourceBuffers;f&&f.readyState==="open"?m.video&&m.video.updating||m.audio&&m.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 m in this._sourceBuffers){var g=this._sourceBuffers[m];if(g){var y=g.buffered;if(y.length>=1&&f-y.start(0)>=this._config.autoCleanupMaxBackwardDuration)return!0}}return!1},h.prototype._doCleanupSourceBuffer=function(){var f=this._mediaElementProxy.getCurrentTime();for(var m in this._sourceBuffers){var g=this._sourceBuffers[m];if(g){for(var y=g.buffered,v=!1,_=0;_<y.length;_++){var S=y.start(_),E=y.end(_);if(S<=f&&f<E+3){if(f-S>=this._config.autoCleanupMaxBackwardDuration){v=!0;var L=f-this._config.autoCleanupMinBackwardDuration;this._pendingRemoveRanges[m].push({start:S,end:L})}}else E<f&&(v=!0,this._pendingRemoveRanges[m].push({start:S,end:E}))}v&&!g.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 m=this._mediaSource.duration,g=this._pendingMediaDuration;g>0&&(isNaN(m)||g>m)&&(o.a.v(this.TAG,"Update MediaSource duration from ".concat(m," to ").concat(g)),this._mediaSource.duration=g),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 m=this._sourceBuffers[f],g=this._pendingRemoveRanges[f];g.length&&!m.updating;){var y=g.shift();m.remove(y.start,y.end)}},h.prototype._doAppendSegments=function(){var f=this._pendingSegments;for(var m in f)if(this._sourceBuffers[m]&&!this._sourceBuffers[m].updating&&this._mediaSource.streaming!==!1&&f[m].length>0){var g=f[m].shift();if(typeof g.timestampOffset=="number"&&isFinite(g.timestampOffset)){var y=this._sourceBuffers[m].timestampOffset,v=g.timestampOffset/1e3;Math.abs(y-v)>.1&&(o.a.v(this.TAG,"Update MPEG audio timestampOffset from ".concat(y," to ").concat(v)),this._sourceBuffers[m].timestampOffset=v),delete g.timestampOffset}if(!g.data||g.data.byteLength===0)continue;try{this._sourceBuffers[m].appendBuffer(g.data),this._isBufferFull=!1}catch(_){this._pendingSegments[m].unshift(g),_.code===22?(this._isBufferFull||this._emitter.emit(c.a.BUFFER_FULL),this._isBufferFull=!0):(o.a.e(this.TAG,_.message),this._emitter.emit(c.a.ERROR,{code:_.code,msg:_.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 m=f.shift();this.appendInitSegment(m,!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,s){var i=s(9),a=s.n(i),o=s(18),l=s.n(o),c=s(0),u=s(8),d=s(13),h=s(1),f=(s(19),s(12)),m=function(){function g(y,v){if(this.TAG="Transmuxer",this._emitter=new a.a,v.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:[y,v]}),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(y,v)}else this._controller=new d.a(y,v);if(this._controller){var _=this._controller;_.on(h.a.IO_ERROR,this._onIOError.bind(this)),_.on(h.a.DEMUX_ERROR,this._onDemuxError.bind(this)),_.on(h.a.INIT_SEGMENT,this._onInitSegment.bind(this)),_.on(h.a.MEDIA_SEGMENT,this._onMediaSegment.bind(this)),_.on(h.a.LOADING_COMPLETE,this._onLoadingComplete.bind(this)),_.on(h.a.RECOVERED_EARLY_EOF,this._onRecoveredEarlyEof.bind(this)),_.on(h.a.MEDIA_INFO,this._onMediaInfo.bind(this)),_.on(h.a.METADATA_ARRIVED,this._onMetaDataArrived.bind(this)),_.on(h.a.SCRIPTDATA_ARRIVED,this._onScriptDataArrived.bind(this)),_.on(h.a.TIMED_ID3_METADATA_ARRIVED,this._onTimedID3MetadataArrived.bind(this)),_.on(h.a.SYNCHRONOUS_KLV_METADATA_ARRIVED,this._onSynchronousKLVMetadataArrived.bind(this)),_.on(h.a.ASYNCHRONOUS_KLV_METADATA_ARRIVED,this._onAsynchronousKLVMetadataArrived.bind(this)),_.on(h.a.SMPTE2038_METADATA_ARRIVED,this._onSMPTE2038MetadataArrived.bind(this)),_.on(h.a.SCTE35_METADATA_ARRIVED,this._onSCTE35MetadataArrived.bind(this)),_.on(h.a.PES_PRIVATE_DATA_DESCRIPTOR,this._onPESPrivateDataDescriptor.bind(this)),_.on(h.a.PES_PRIVATE_DATA_ARRIVED,this._onPESPrivateDataArrived.bind(this)),_.on(h.a.STATISTICS_INFO,this._onStatisticsInfo.bind(this)),_.on(h.a.RECOMMEND_SEEKPOINT,this._onRecommendSeekpoint.bind(this))}}return g.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},g.prototype.on=function(y,v){this._emitter.addListener(y,v)},g.prototype.off=function(y,v){this._emitter.removeListener(y,v)},g.prototype.hasWorker=function(){return this._worker!=null},g.prototype.open=function(){this._worker?this._worker.postMessage({cmd:"start"}):this._controller.start()},g.prototype.close=function(){this._worker?this._worker.postMessage({cmd:"stop"}):this._controller.stop()},g.prototype.seek=function(y){this._worker?this._worker.postMessage({cmd:"seek",param:y}):this._controller.seek(y)},g.prototype.pause=function(){this._worker?this._worker.postMessage({cmd:"pause"}):this._controller.pause()},g.prototype.resume=function(){this._worker?this._worker.postMessage({cmd:"resume"}):this._controller.resume()},g.prototype._onInitSegment=function(y,v){var _=this;Promise.resolve().then(function(){_._emitter.emit(h.a.INIT_SEGMENT,y,v)})},g.prototype._onMediaSegment=function(y,v){var _=this;Promise.resolve().then(function(){_._emitter.emit(h.a.MEDIA_SEGMENT,y,v)})},g.prototype._onLoadingComplete=function(){var y=this;Promise.resolve().then(function(){y._emitter.emit(h.a.LOADING_COMPLETE)})},g.prototype._onRecoveredEarlyEof=function(){var y=this;Promise.resolve().then(function(){y._emitter.emit(h.a.RECOVERED_EARLY_EOF)})},g.prototype._onMediaInfo=function(y){var v=this;Promise.resolve().then(function(){v._emitter.emit(h.a.MEDIA_INFO,y)})},g.prototype._onMetaDataArrived=function(y){var v=this;Promise.resolve().then(function(){v._emitter.emit(h.a.METADATA_ARRIVED,y)})},g.prototype._onScriptDataArrived=function(y){var v=this;Promise.resolve().then(function(){v._emitter.emit(h.a.SCRIPTDATA_ARRIVED,y)})},g.prototype._onTimedID3MetadataArrived=function(y){var v=this;Promise.resolve().then(function(){v._emitter.emit(h.a.TIMED_ID3_METADATA_ARRIVED,y)})},g.prototype._onSynchronousKLVMetadataArrived=function(y){var v=this;Promise.resolve().then(function(){v._emitter.emit(h.a.SYNCHRONOUS_KLV_METADATA_ARRIVED,y)})},g.prototype._onAsynchronousKLVMetadataArrived=function(y){var v=this;Promise.resolve().then(function(){v._emitter.emit(h.a.ASYNCHRONOUS_KLV_METADATA_ARRIVED,y)})},g.prototype._onSMPTE2038MetadataArrived=function(y){var v=this;Promise.resolve().then(function(){v._emitter.emit(h.a.SMPTE2038_METADATA_ARRIVED,y)})},g.prototype._onSCTE35MetadataArrived=function(y){var v=this;Promise.resolve().then(function(){v._emitter.emit(h.a.SCTE35_METADATA_ARRIVED,y)})},g.prototype._onPESPrivateDataDescriptor=function(y){var v=this;Promise.resolve().then(function(){v._emitter.emit(h.a.PES_PRIVATE_DATA_DESCRIPTOR,y)})},g.prototype._onPESPrivateDataArrived=function(y){var v=this;Promise.resolve().then(function(){v._emitter.emit(h.a.PES_PRIVATE_DATA_ARRIVED,y)})},g.prototype._onStatisticsInfo=function(y){var v=this;Promise.resolve().then(function(){v._emitter.emit(h.a.STATISTICS_INFO,y)})},g.prototype._onIOError=function(y,v){var _=this;Promise.resolve().then(function(){_._emitter.emit(h.a.IO_ERROR,y,v)})},g.prototype._onDemuxError=function(y,v){var _=this;Promise.resolve().then(function(){_._emitter.emit(h.a.DEMUX_ERROR,y,v)})},g.prototype._onRecommendSeekpoint=function(y){var v=this;Promise.resolve().then(function(){v._emitter.emit(h.a.RECOMMEND_SEEKPOINT,y)})},g.prototype._onLoggingConfigChanged=function(y){this._worker&&this._worker.postMessage({cmd:"logging_config",param:y})},g.prototype._onWorkerMessage=function(y){var v=y.data,_=v.data;if(v.msg==="destroyed"||this._workerDestroying)return this._workerDestroying=!1,this._worker.terminate(),void(this._worker=null);switch(v.msg){case h.a.INIT_SEGMENT:case h.a.MEDIA_SEGMENT:this._emitter.emit(v.msg,_.type,_.data);break;case h.a.LOADING_COMPLETE:case h.a.RECOVERED_EARLY_EOF:this._emitter.emit(v.msg);break;case h.a.MEDIA_INFO:Object.setPrototypeOf(_,f.a.prototype),this._emitter.emit(v.msg,_);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(v.msg,_);break;case h.a.IO_ERROR:case h.a.DEMUX_ERROR:this._emitter.emit(v.msg,_.type,_.info);break;case h.a.RECOMMEND_SEEKPOINT:this._emitter.emit(v.msg,_);break;case"logcat_callback":c.a.emitter.emit("log",_.type,_.logcat)}},g}();r.a=m},function(n,r,s){function i(c){var u={};function d(f){if(u[f])return u[f].exports;var m=u[f]={i:f,l:!1,exports:{}};return c[f].call(m.exports,m,m.exports,d),m.l=!0,m.exports}d.m=c,d.c=u,d.i=function(f){return f},d.d=function(f,m,g){d.o(f,m)||Object.defineProperty(f,m,{configurable:!1,enumerable:!0,get:g})},d.r=function(f){Object.defineProperty(f,"__esModule",{value:!0})},d.n=function(f){var m=f&&f.__esModule?function(){return f.default}:function(){return f};return d.d(m,"a",m),m},d.o=function(f,m){return Object.prototype.hasOwnProperty.call(f,m)},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(),m=f.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/);if(!m)return h;for(var g,y=m[1],v=new RegExp("(\\\\n|\\W)"+a(y)+"\\(\\s*(/\\*.*?\\*/)?\\s*.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)","g");g=v.exec(f);)g[3]!=="dll-reference"&&h[d].push(g[3]);for(v=new RegExp("\\("+a(y)+'\\("(dll-reference\\s([\\.|\\-|\\+|\\w|/|@]+))"\\)\\)\\(\\s*(/\\*.*?\\*/)?\\s*.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)',"g");g=v.exec(f);)c[g[2]]||(h[d].push(g[1]),c[g[2]]=s(g[1]).m),h[g[2]]=h[g[2]]||[],h[g[2]].push(g[4]);for(var _,S=Object.keys(h),E=0;E<S.length;E++)for(var L=0;L<h[S[E]].length;L++)_=h[S[E]][L],isNaN(1*_)||(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:s.m},h=u.all?{main:Object.keys(d.main)}:function(v,_){for(var S={main:[_]},E={main:[]},L={main:{}};l(S);)for(var U=Object.keys(S),P=0;P<U.length;P++){var I=U[P],k=S[I].pop();if(L[I]=L[I]||{},!L[I][k]&&v[I][k]){L[I][k]=!0,E[I]=E[I]||[],E[I].push(k);for(var R=o(v,v[I][k],I),M=Object.keys(R),G=0;G<M.length;G++)S[M[G]]=S[M[G]]||[],S[M[G]]=S[M[G]].concat(R[M[G]])}}return E}(d,c),f="";Object.keys(h).filter(function(v){return v!=="main"}).forEach(function(v){for(var _=0;h[v][_];)_++;h[v].push(_),d[v][_]="(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })",f=f+"var "+v+" = ("+i.toString().replace("ENTRY_MODULE",JSON.stringify(_))+")({"+h[v].map(function(S){return JSON.stringify(S)+": "+d[v][S].toString()}).join(",")+`});
`}),f=f+"new (("+i.toString().replace("ENTRY_MODULE",JSON.stringify(c))+")({"+h.main.map(function(v){return JSON.stringify(v)+": "+d.main[v].toString()}).join(",")+"}))(self);";var m=new self.Blob([f],{type:"text/javascript"});if(u.bare)return m;var g=(self.URL||self.webkitURL||self.mozURL||self.msURL).createObjectURL(m),y=new self.Worker(g);return y.objectURL=g,y}},function(n,r,s){s.r(r),s(0);var i=s(8),a=s(15),o=s(13),l=s(1);r.default=function(c){var u=null,d=(function(q,X){c.postMessage({msg:"logcat_callback",data:{type:q,logcat:X}})}).bind(this);function h(q,X){var Z={msg:l.a.INIT_SEGMENT,data:{type:q,data:X}};c.postMessage(Z,[X.data])}function f(q,X){var Z={msg:l.a.MEDIA_SEGMENT,data:{type:q,data:X}};c.postMessage(Z,[X.data])}function m(){var q={msg:l.a.LOADING_COMPLETE};c.postMessage(q)}function g(){var q={msg:l.a.RECOVERED_EARLY_EOF};c.postMessage(q)}function y(q){var X={msg:l.a.MEDIA_INFO,data:q};c.postMessage(X)}function v(q){var X={msg:l.a.METADATA_ARRIVED,data:q};c.postMessage(X)}function _(q){var X={msg:l.a.SCRIPTDATA_ARRIVED,data:q};c.postMessage(X)}function S(q){var X={msg:l.a.TIMED_ID3_METADATA_ARRIVED,data:q};c.postMessage(X)}function E(q){var X={msg:l.a.SYNCHRONOUS_KLV_METADATA_ARRIVED,data:q};c.postMessage(X)}function L(q){var X={msg:l.a.ASYNCHRONOUS_KLV_METADATA_ARRIVED,data:q};c.postMessage(X)}function U(q){var X={msg:l.a.SMPTE2038_METADATA_ARRIVED,data:q};c.postMessage(X)}function P(q){var X={msg:l.a.SCTE35_METADATA_ARRIVED,data:q};c.postMessage(X)}function I(q){var X={msg:l.a.PES_PRIVATE_DATA_DESCRIPTOR,data:q};c.postMessage(X)}function k(q){var X={msg:l.a.PES_PRIVATE_DATA_ARRIVED,data:q};c.postMessage(X)}function R(q){var X={msg:l.a.STATISTICS_INFO,data:q};c.postMessage(X)}function M(q,X){c.postMessage({msg:l.a.IO_ERROR,data:{type:q,info:X}})}function G(q,X){c.postMessage({msg:l.a.DEMUX_ERROR,data:{type:q,info:X}})}function Y(q){c.postMessage({msg:l.a.RECOMMEND_SEEKPOINT,data:q})}a.a.install(),c.addEventListener("message",function(q){switch(q.data.cmd){case"init":(u=new o.a(q.data.param[0],q.data.param[1])).on(l.a.IO_ERROR,M.bind(this)),u.on(l.a.DEMUX_ERROR,G.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,m.bind(this)),u.on(l.a.RECOVERED_EARLY_EOF,g.bind(this)),u.on(l.a.MEDIA_INFO,y.bind(this)),u.on(l.a.METADATA_ARRIVED,v.bind(this)),u.on(l.a.SCRIPTDATA_ARRIVED,_.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,P.bind(this)),u.on(l.a.PES_PRIVATE_DATA_DESCRIPTOR,I.bind(this)),u.on(l.a.PES_PRIVATE_DATA_ARRIVED,k.bind(this)),u.on(l.a.STATISTICS_INFO,R.bind(this)),u.on(l.a.RECOMMEND_SEEKPOINT,Y.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(q.data.param);break;case"pause":u.pause();break;case"resume":u.resume();break;case"logging_config":var X=q.data.param;i.a.applyConfig(X),X.enableCallback===!0?i.a.addLogListener(d):i.a.removeLogListener(d)}})}},function(n,r,s){n.exports=s(25).default},function(n,r,s){(function(i,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(be){return typeof be=="function"}var c=Array.isArray?Array.isArray:function(be){return Object.prototype.toString.call(be)==="[object Array]"},u=0,d=void 0,h=void 0,f=function(be,Pe){E[u]=be,E[u+1]=Pe,(u+=2)===2&&(h?h(L):R())},m=typeof window<"u"?window:void 0,g=m||{},y=g.MutationObserver||g.WebKitMutationObserver,v=typeof self>"u"&&i!==void 0&&{}.toString.call(i)==="[object process]",_=typeof Uint8ClampedArray<"u"&&typeof importScripts<"u"&&typeof MessageChannel<"u";function S(){var be=setTimeout;return function(){return be(L,1)}}var E=new Array(1e3);function L(){for(var be=0;be<u;be+=2)(0,E[be])(E[be+1]),E[be]=void 0,E[be+1]=void 0;u=0}var U,P,I,k,R=void 0;function M(be,Pe){var Ae=this,we=new this.constructor(q);we[Y]===void 0&&Te(we);var Ue=Ae._state;if(Ue){var Oe=arguments[Ue-1];f(function(){return Q(Ue,we,Oe,Ae._result)})}else K(Ae,we,be,Pe);return we}function G(be){if(be&&typeof be=="object"&&be.constructor===this)return be;var Pe=new this(q);return Z(Pe,be),Pe}v?R=function(){return i.nextTick(L)}:y?(P=0,I=new y(L),k=document.createTextNode(""),I.observe(k,{characterData:!0}),R=function(){k.data=P=++P%2}):_?((U=new MessageChannel).port1.onmessage=L,R=function(){return U.port2.postMessage(0)}):R=m===void 0?function(){try{var be=Function("return this")().require("vertx");return(d=be.runOnLoop||be.runOnContext)!==void 0?function(){d(L)}:S()}catch{return S()}}():S();var Y=Math.random().toString(36).substring(2);function q(){}function X(be,Pe,Ae){Pe.constructor===be.constructor&&Ae===M&&Pe.constructor.resolve===G?function(we,Ue){Ue._state===1?ne(we,Ue._result):Ue._state===2?H(we,Ue._result):K(Ue,void 0,function(Oe){return Z(we,Oe)},function(Oe){return H(we,Oe)})}(be,Pe):Ae===void 0?ne(be,Pe):l(Ae)?function(we,Ue,Oe){f(function(Dt){var en=!1,wn=function(it,nn,mn,On){try{it.call(nn,mn,On)}catch(Cn){return Cn}}(Oe,Ue,function(it){en||(en=!0,Ue!==it?Z(Dt,it):ne(Dt,it))},function(it){en||(en=!0,H(Dt,it))},Dt._label);!en&&wn&&(en=!0,H(Dt,wn))},we)}(be,Pe,Ae):ne(be,Pe)}function Z(be,Pe){if(be===Pe)H(be,new TypeError("You cannot resolve a promise with itself"));else if(Ue=typeof(we=Pe),we===null||Ue!=="object"&&Ue!=="function")ne(be,Pe);else{var Ae=void 0;try{Ae=Pe.then}catch(Oe){return void H(be,Oe)}X(be,Pe,Ae)}var we,Ue}function oe(be){be._onerror&&be._onerror(be._result),J(be)}function ne(be,Pe){be._state===void 0&&(be._result=Pe,be._state=1,be._subscribers.length!==0&&f(J,be))}function H(be,Pe){be._state===void 0&&(be._state=2,be._result=Pe,f(oe,be))}function K(be,Pe,Ae,we){var Ue=be._subscribers,Oe=Ue.length;be._onerror=null,Ue[Oe]=Pe,Ue[Oe+1]=Ae,Ue[Oe+2]=we,Oe===0&&be._state&&f(J,be)}function J(be){var Pe=be._subscribers,Ae=be._state;if(Pe.length!==0){for(var we=void 0,Ue=void 0,Oe=be._result,Dt=0;Dt<Pe.length;Dt+=3)we=Pe[Dt],Ue=Pe[Dt+Ae],we?Q(Ae,we,Ue,Oe):Ue(Oe);be._subscribers.length=0}}function Q(be,Pe,Ae,we){var Ue=l(Ae),Oe=void 0,Dt=void 0,en=!0;if(Ue){try{Oe=Ae(we)}catch(wn){en=!1,Dt=wn}if(Pe===Oe)return void H(Pe,new TypeError("A promises callback cannot return that same promise."))}else Oe=we;Pe._state!==void 0||(Ue&&en?Z(Pe,Oe):en===!1?H(Pe,Dt):be===1?ne(Pe,Oe):be===2&&H(Pe,Oe))}var ve=0;function Te(be){be[Y]=ve++,be._state=void 0,be._result=void 0,be._subscribers=[]}var Ne=function(){function be(Pe,Ae){this._instanceConstructor=Pe,this.promise=new Pe(q),this.promise[Y]||Te(this.promise),c(Ae)?(this.length=Ae.length,this._remaining=Ae.length,this._result=new Array(this.length),this.length===0?ne(this.promise,this._result):(this.length=this.length||0,this._enumerate(Ae),this._remaining===0&&ne(this.promise,this._result))):H(this.promise,new Error("Array Methods must be provided an Array"))}return be.prototype._enumerate=function(Pe){for(var Ae=0;this._state===void 0&&Ae<Pe.length;Ae++)this._eachEntry(Pe[Ae],Ae)},be.prototype._eachEntry=function(Pe,Ae){var we=this._instanceConstructor,Ue=we.resolve;if(Ue===G){var Oe=void 0,Dt=void 0,en=!1;try{Oe=Pe.then}catch(it){en=!0,Dt=it}if(Oe===M&&Pe._state!==void 0)this._settledAt(Pe._state,Ae,Pe._result);else if(typeof Oe!="function")this._remaining--,this._result[Ae]=Pe;else if(we===Ke){var wn=new we(q);en?H(wn,Dt):X(wn,Pe,Oe),this._willSettleAt(wn,Ae)}else this._willSettleAt(new we(function(it){return it(Pe)}),Ae)}else this._willSettleAt(Ue(Pe),Ae)},be.prototype._settledAt=function(Pe,Ae,we){var Ue=this.promise;Ue._state===void 0&&(this._remaining--,Pe===2?H(Ue,we):this._result[Ae]=we),this._remaining===0&&ne(Ue,this._result)},be.prototype._willSettleAt=function(Pe,Ae){var we=this;K(Pe,void 0,function(Ue){return we._settledAt(1,Ae,Ue)},function(Ue){return we._settledAt(2,Ae,Ue)})},be}(),Ke=function(){function be(Pe){this[Y]=ve++,this._result=this._state=void 0,this._subscribers=[],q!==Pe&&(typeof Pe!="function"&&function(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}(),this instanceof be?function(Ae,we){try{we(function(Ue){Z(Ae,Ue)},function(Ue){H(Ae,Ue)})}catch(Ue){H(Ae,Ue)}}(this,Pe):function(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}())}return be.prototype.catch=function(Pe){return this.then(null,Pe)},be.prototype.finally=function(Pe){var Ae=this.constructor;return l(Pe)?this.then(function(we){return Ae.resolve(Pe()).then(function(){return we})},function(we){return Ae.resolve(Pe()).then(function(){throw we})}):this.then(Pe,Pe)},be}();return Ke.prototype.then=M,Ke.all=function(be){return new Ne(this,be).promise},Ke.race=function(be){var Pe=this;return c(be)?new Pe(function(Ae,we){for(var Ue=be.length,Oe=0;Oe<Ue;Oe++)Pe.resolve(be[Oe]).then(Ae,we)}):new Pe(function(Ae,we){return we(new TypeError("You must pass an array to race."))})},Ke.resolve=G,Ke.reject=function(be){var Pe=new this(q);return H(Pe,be),Pe},Ke._setScheduler=function(be){h=be},Ke._setAsap=function(be){f=be},Ke._asap=f,Ke.polyfill=function(){var be=void 0;if(a!==void 0)be=a;else if(typeof self<"u")be=self;else try{be=Function("return this")()}catch{throw new Error("polyfill failed because global object is unavailable in this environment")}var Pe=be.Promise;if(Pe){var Ae=null;try{Ae=Object.prototype.toString.call(Pe.resolve())}catch{}if(Ae==="[object Promise]"&&!Pe.cast)return}be.Promise=Ke},Ke.Promise=Ke,Ke},n.exports=o()}).call(this,s(22),s(23))},function(n,r){var s,i,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(_){if(s===setTimeout)return setTimeout(_,0);if((s===o||!s)&&setTimeout)return s=setTimeout,setTimeout(_,0);try{return s(_,0)}catch{try{return s.call(null,_,0)}catch{return s.call(this,_,0)}}}(function(){try{s=typeof setTimeout=="function"?setTimeout:o}catch{s=o}try{i=typeof clearTimeout=="function"?clearTimeout:l}catch{i=l}})();var u,d=[],h=!1,f=-1;function m(){h&&u&&(h=!1,u.length?d=u.concat(d):f=-1,d.length&&g())}function g(){if(!h){var _=c(m);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(i===clearTimeout)return clearTimeout(E);if((i===l||!i)&&clearTimeout)return i=clearTimeout,clearTimeout(E);try{i(E)}catch{try{return i.call(null,E)}catch{return i.call(this,E)}}}(_)}}function y(_,S){this.fun=_,this.array=S}function v(){}a.nextTick=function(_){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 y(_,S)),d.length!==1||h||c(g)},y.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=v,a.addListener=v,a.once=v,a.off=v,a.removeListener=v,a.removeAllListeners=v,a.emit=v,a.prependListener=v,a.prependOnceListener=v,a.listeners=function(_){return[]},a.binding=function(_){throw new Error("process.binding is not supported")},a.cwd=function(){return"/"},a.chdir=function(_){throw new Error("process.chdir is not supported")},a.umask=function(){return 0}},function(n,r){var s;s=function(){return this}();try{s=s||new Function("return this")()}catch{typeof window=="object"&&(s=window)}n.exports=s},function(n,r,s){s.r(r);var i=s(0),a=s(8),o=s(3),l=s(7),c=s(16),u=s(17),d=s(1),h=s(4),f=s(10);r.default=function(m){var g="PlayerEngineWorker",y=(function(H,K){m.postMessage({msg:"logcat_callback",type:H,logcat:K})}).bind(void 0),v=null,_=null,S=null,E=null,L=!1,U=!1,P=0,I=0,k=!1;function R(){S&&(S.shutdown(),S.destroy(),S=null)}function M(){if(v==null||_==null)throw new o.a("Worker not initialized");if(E)throw new o.a("Transmuxer has been initialized");U||(!_.deferLoadAfterSourceOpen||L?((E=new u.a(v,_)).on(d.a.INIT_SEGMENT,function(H,K){S.appendInitSegment(K)}),E.on(d.a.MEDIA_SEGMENT,function(H,K){S.appendMediaSegment(K),m.postMessage({msg:"buffered_position_changed",buffered_position_milliseconds:K.info.endDts})}),E.on(d.a.LOADING_COMPLETE,function(){S.endOfStream(),m.postMessage({msg:"player_event",event:h.a.LOADING_COMPLETE})}),E.on(d.a.RECOVERED_EARLY_EOF,function(){m.postMessage({msg:"player_event",event:h.a.RECOVERED_EARLY_EOF})}),E.on(d.a.IO_ERROR,function(H,K){m.postMessage({msg:"player_event",event:h.a.ERROR,error_type:f.b.NETWORK_ERROR,error_detail:H,info:K})}),E.on(d.a.DEMUX_ERROR,function(H,K){m.postMessage({msg:"player_event",event:h.a.ERROR,error_type:f.b.MEDIA_ERROR,error_detail:H,info:K})}),E.on(d.a.MEDIA_INFO,function(H){oe(d.a.MEDIA_INFO,H)}),E.on(d.a.STATISTICS_INFO,function(H){oe(d.a.STATISTICS_INFO,H)}),E.on(d.a.RECOMMEND_SEEKPOINT,function(H){(function(K){m.postMessage({msg:"transmuxing_event",event:d.a.RECOMMEND_SEEKPOINT,milliseconds:K})})(H)}),E.on(d.a.METADATA_ARRIVED,function(H){ne(h.a.METADATA_ARRIVED,H)}),E.on(d.a.SCRIPTDATA_ARRIVED,function(H){ne(h.a.SCRIPTDATA_ARRIVED,H)}),E.on(d.a.TIMED_ID3_METADATA_ARRIVED,function(H){ne(h.a.TIMED_ID3_METADATA_ARRIVED,H)}),E.on(d.a.SYNCHRONOUS_KLV_METADATA_ARRIVED,function(H){ne(h.a.SYNCHRONOUS_KLV_METADATA_ARRIVED,H)}),E.on(d.a.ASYNCHRONOUS_KLV_METADATA_ARRIVED,function(H){ne(h.a.ASYNCHRONOUS_KLV_METADATA_ARRIVED,H)}),E.on(d.a.SMPTE2038_METADATA_ARRIVED,function(H){ne(h.a.SMPTE2038_METADATA_ARRIVED,H)}),E.on(d.a.SCTE35_METADATA_ARRIVED,function(H){ne(h.a.SCTE35_METADATA_ARRIVED,H)}),E.on(d.a.PES_PRIVATE_DATA_DESCRIPTOR,function(H){ne(h.a.PES_PRIVATE_DATA_DESCRIPTOR,H)}),E.on(d.a.PES_PRIVATE_DATA_ARRIVED,function(H){ne(h.a.PES_PRIVATE_DATA_ARRIVED,H)}),E.open()):U=!0)}function G(){S&&S.flush(),E&&(E.close(),E.destroy(),E=null)}function Y(){L=!0,U&&(U=!1,M())}function q(){m.postMessage({msg:"mse_event",event:l.a.UPDATE_END})}function X(){i.a.v(g,"MSE SourceBuffer is full, report to main thread"),m.postMessage({msg:"mse_event",event:l.a.BUFFER_FULL})}function Z(H){m.postMessage({msg:"player_event",event:h.a.ERROR,error_type:f.b.MEDIA_ERROR,error_detail:f.b.MEDIA_MSE_ERROR,info:H})}function oe(H,K){m.postMessage({msg:"transmuxing_event",event:H,info:K})}function ne(H,K){m.postMessage({msg:"player_event",event:H,extraData:K})}m.addEventListener("message",function(H){if(!k){var K=H.data;switch(K.cmd){case"logging_config":var J=K;a.a.applyConfig(J.logging_config),J.logging_config.enableCallback===!0?a.a.addLogListener(y):a.a.removeLogListener(y);break;case"init":v=(J=K).media_data_source,_=J.config;break;case"destroy":(function(){E&&G(),S&&R(),k=!0,m.postMessage({msg:"destroyed"})})();break;case"initialize_mse":(function(){i.a.v(g,"Initializing MediaSource in DedicatedWorker"),(S=new c.a(_)).on(l.a.SOURCE_OPEN,Y.bind(this)),S.on(l.a.UPDATE_END,q.bind(this)),S.on(l.a.BUFFER_FULL,X.bind(this)),S.on(l.a.ERROR,Z.bind(this)),S.initialize({getCurrentTime:function(){return P},getReadyState:function(){return I}});var Q=S.getHandle();m.postMessage({msg:"mse_init",handle:Q},[Q])})();break;case"shutdown_mse":R();break;case"load":M();break;case"unload":G();break;case"unbuffered_seek":J=K,S.flush(),E.seek(J.milliseconds);break;case"timeupdate":P=(J=K).current_time;break;case"readystatechange":I=(J=K).ready_state;break;case"pause_transmuxer":E.pause();break;case"resume_transmuxer":E.resume()}}})}},function(n,r,s){s.r(r);var i=s(15),a=s(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 H(){}return H.supportMSEH264Playback=function(){var K=self.MediaSource&&self.MediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),J=self.ManagedMediaSource&&self.ManagedMediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"');return K||J},H.supportMSEH265Playback=function(){var K=self.MediaSource&&self.MediaSource.isTypeSupported('video/mp4; codecs="hvc1.1.6.L93.B0"'),J=self.ManagedMediaSource&&self.ManagedMediaSource.isTypeSupported('video/mp4; codecs="hvc1.1.6.L93.B0"');return K||J},H.supportNetworkStreamIO=function(){var K=new a.a({},l()),J=K.loaderType;return K.destroy(),J=="fetch-stream-loader"||J=="xhr-moz-chunked-loader"},H.getNetworkLoaderTypeName=function(){var K=new a.a({},l()),J=K.loaderType;return K.destroy(),J},H.supportNativeMediaPlayback=function(K){H.videoElement==null&&(H.videoElement=window.document.createElement("video"));var J=H.videoElement.canPlayType(K);return J==="probably"||J=="maybe"},H.getFeatureList=function(){var K={msePlayback:!1,mseLivePlayback:!1,mseH265Playback:!1,networkStreamIO:!1,networkLoaderName:"",nativeMP4H264Playback:!1,nativeMP4H265Playback:!1,nativeWebmVP8Playback:!1,nativeWebmVP9Playback:!1};return K.msePlayback=H.supportMSEH264Playback(),K.networkStreamIO=H.supportNetworkStreamIO(),K.networkLoaderName=H.getNetworkLoaderTypeName(),K.mseLivePlayback=K.msePlayback&&K.networkStreamIO,K.mseH265Playback=H.supportMSEH265Playback(),K.nativeMP4H264Playback=H.supportNativeMediaPlayback('video/mp4; codecs="avc1.42001E, mp4a.40.2"'),K.nativeMP4H265Playback=H.supportNativeMediaPlayback('video/mp4; codecs="hvc1.1.6.L93.B0"'),K.nativeWebmVP8Playback=H.supportNativeMediaPlayback('video/webm; codecs="vp8.0, vorbis"'),K.nativeWebmVP9Playback=H.supportNativeMediaPlayback('video/webm; codecs="vp9"'),K},H}(),u=s(2),d=s(0),h=s(9),f=s.n(h),m=s(16),g=s(4),y=s(17),v=s(7),_=s(10),S=s(3),E=s(1),L=s(5),U=s(11),P=function(){function H(K,J,Q){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=K,this._media_element=J,this._on_unbuffered_seek=Q,this.e={onMediaSeeking:this._onMediaSeeking.bind(this)};var ve=L.a.chrome&&(L.a.version.major<50||L.a.version.major===50&&L.a.version.build<2661);this._always_seek_keyframe=!!(ve||L.a.msedge||L.a.msie),this._always_seek_keyframe&&(this._config.accurateSeek=!1),this._media_element.addEventListener("seeking",this.e.onMediaSeeking)}return H.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},H.prototype.seek=function(K){var J=this._isPositionBuffered(K),Q=!1;if(K<1&&this._media_element.buffered.length>0){var ve=this._media_element.buffered.start(0);(ve<1&&K<ve||L.a.safari)&&(Q=!0,K=L.a.safari?.1:ve)}if(Q)this.directSeek(K);else if(J)if(this._always_seek_keyframe){var Te=this._getNearestKeyframe(Math.floor(1e3*K));Te!=null&&(K=Te.dts/1e3),this.directSeek(K)}else this.directSeek(K);else this._idr_sample_list.clear(),this._on_unbuffered_seek(Math.floor(1e3*K)),this._config.accurateSeek&&this.directSeek(K)},H.prototype.directSeek=function(K){this._request_set_current_time=!0,this._media_element.currentTime=K},H.prototype.appendSyncPoints=function(K){this._idr_sample_list.appendArray(K)},H.prototype._onMediaSeeking=function(K){if(this._request_set_current_time)this._request_set_current_time=!1;else{var J=this._media_element.currentTime,Q=this._media_element.buffered;if(J<1&&Q.length>0){var ve=Q.start(0);if(ve<1&&J<ve||L.a.safari){var Te=L.a.safari?.1:ve;return void this.directSeek(Te)}}if(this._isPositionBuffered(J)){if(this._always_seek_keyframe){var Ne=this._getNearestKeyframe(Math.floor(1e3*J));Ne!=null&&(J=Ne.dts/1e3,this.directSeek(J))}}else this._seek_request_record_clocktime=H._getClockTime(),window.setTimeout(this._pollAndApplyUnbufferedSeek.bind(this),50)}},H.prototype._pollAndApplyUnbufferedSeek=function(){if(this._seek_request_record_clocktime!=null)if(this._seek_request_record_clocktime<=H._getClockTime()-100){var K=this._media_element.currentTime;this._seek_request_record_clocktime=null,this._isPositionBuffered(K)||(this._idr_sample_list.clear(),this._on_unbuffered_seek(Math.floor(1e3*K)),this._config.accurateSeek&&this.directSeek(K))}else window.setTimeout(this._pollAndApplyUnbufferedSeek.bind(this),50)},H.prototype._isPositionBuffered=function(K){for(var J=this._media_element.buffered,Q=0;Q<J.length;Q++){var ve=J.start(Q),Te=J.end(Q);if(K>=ve&&K<Te)return!0}return!1},H.prototype._getNearestKeyframe=function(K){return this._idr_sample_list.getLastSyncPointBeforeDts(K)},H._getClockTime=function(){return self.performance&&self.performance.now?self.performance.now():Date.now()},H}(),I=function(){function H(K,J,Q,ve){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=K,this._media_element=J,this._on_pause_transmuxer=Q,this._on_resume_transmuxer=ve,this.e={onMediaTimeUpdate:this._onMediaTimeUpdate.bind(this)}}return H.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},H.prototype.notifyBufferedPositionChanged=function(K){!this._config.isLive&&this._config.lazyLoad&&(K==null?this._suspendTransmuxerIfNeeded():this._suspendTransmuxerIfBufferedPositionExceeded(K))},H.prototype._onMediaTimeUpdate=function(K){this._paused&&this._resumeTransmuxerIfNeeded()},H.prototype._suspendTransmuxerIfNeeded=function(){for(var K=this._media_element.buffered,J=this._media_element.currentTime,Q=0,ve=0;ve<K.length;ve++){var Te=K.start(ve),Ne=K.end(ve);if(Te<=J&&J<Ne){Q=Ne;break}}Q>0&&this._suspendTransmuxerIfBufferedPositionExceeded(Q)},H.prototype._suspendTransmuxerIfBufferedPositionExceeded=function(K){K>=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))},H.prototype.suspendTransmuxer=function(){this._paused=!0,this._on_pause_transmuxer()},H.prototype._resumeTransmuxerIfNeeded=function(){for(var K=this._media_element.buffered,J=this._media_element.currentTime,Q=this._config.lazyLoadRecoverDuration,ve=!1,Te=0;Te<K.length;Te++){var Ne=K.start(Te),Ke=K.end(Te);if(J>=Ne&&J<Ke){J>=Ke-Q&&(ve=!0);break}}ve&&(d.a.v(this.TAG,"Continue loading from paused position"),this.resumeTransmuxer(),this._media_element.removeEventListener("timeupdate",this.e.onMediaTimeUpdate))},H.prototype.resumeTransmuxer=function(){this._paused=!1,this._on_resume_transmuxer()},H}(),k=function(){function H(K,J){this.TAG="StartupStallJumper",this._media_element=null,this._on_direct_seek=null,this._canplay_received=!1,this.e=null,this._media_element=K,this._on_direct_seek=J,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 H.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},H.prototype._onMediaCanPlay=function(K){this._canplay_received=!0,this._media_element.removeEventListener("canplay",this.e.onMediaCanPlay)},H.prototype._onMediaStalled=function(K){this._detectAndFixStuckPlayback(!0)},H.prototype._onMediaProgress=function(K){this._detectAndFixStuckPlayback()},H.prototype._detectAndFixStuckPlayback=function(K){var J=this._media_element,Q=J.buffered;K||!this._canplay_received||J.readyState<2?Q.length>0&&J.currentTime<Q.start(0)&&(d.a.w(this.TAG,"Playback seems stuck at ".concat(J.currentTime,", seek to ").concat(Q.start(0))),this._on_direct_seek(Q.start(0)),this._media_element.removeEventListener("progress",this.e.onMediaProgress)):this._media_element.removeEventListener("progress",this.e.onMediaProgress)},H}(),R=function(){function H(K,J,Q){this._config=null,this._media_element=null,this._on_direct_seek=null,this._config=K,this._media_element=J,this._on_direct_seek=Q}return H.prototype.destroy=function(){this._on_direct_seek=null,this._media_element=null,this._config=null},H.prototype.notifyBufferedRangeUpdate=function(){this._chaseLiveLatency()},H.prototype._chaseLiveLatency=function(){var K=this._media_element.buffered,J=this._media_element.currentTime,Q=this._media_element.paused;if(this._config.isLive&&this._config.liveBufferLatencyChasing&&K.length!=0&&(this._config.liveBufferLatencyChasingOnPaused||!Q)){var ve=K.end(K.length-1);if(ve>this._config.liveBufferLatencyMaxLatency&&ve-J>this._config.liveBufferLatencyMaxLatency){var Te=ve-this._config.liveBufferLatencyMinRemain;this._on_direct_seek(Te)}}},H}(),M=function(){function H(K,J){this._config=null,this._media_element=null,this.e=null,this._config=K,this._media_element=J,this.e={onMediaTimeUpdate:this._onMediaTimeUpdate.bind(this)},this._media_element.addEventListener("timeupdate",this.e.onMediaTimeUpdate)}return H.prototype.destroy=function(){this._media_element.removeEventListener("timeupdate",this.e.onMediaTimeUpdate),this._media_element=null,this._config=null},H.prototype._onMediaTimeUpdate=function(K){if(this._config.isLive&&this._config.liveSync){var J=this._getCurrentLatency();if(J>this._config.liveSyncMaxLatency){var Q=Math.min(2,Math.max(1,this._config.liveSyncPlaybackRate));this._media_element.playbackRate=Q}else J>this._config.liveSyncTargetLatency||this._media_element.playbackRate!==1&&this._media_element.playbackRate!==0&&(this._media_element.playbackRate=1)}},H.prototype._getCurrentLatency=function(){if(!this._media_element)return 0;var K=this._media_element.buffered,J=this._media_element.currentTime;return K.length==0?0:K.end(K.length-1)-J},H}(),G=function(){function H(K,J){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=K,this._config=l(),typeof J=="object"&&Object.assign(this._config,J),K.isLive===!0&&(this._config.isLive=!0),this.e={onMediaLoadedMetadata:this._onMediaLoadedMetadata.bind(this)}}return H.prototype.destroy=function(){this._emitter.emit(g.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},H.prototype.on=function(K,J){var Q=this;this._emitter.addListener(K,J),K===g.a.MEDIA_INFO&&this._media_info?Promise.resolve().then(function(){return Q._emitter.emit(g.a.MEDIA_INFO,Q.mediaInfo)}):K==g.a.STATISTICS_INFO&&this._statistics_info&&Promise.resolve().then(function(){return Q._emitter.emit(g.a.STATISTICS_INFO,Q.statisticsInfo)})},H.prototype.off=function(K,J){this._emitter.removeListener(K,J)},H.prototype.attachMediaElement=function(K){var J=this;this._media_element=K,K.src="",K.removeAttribute("src"),K.srcObject=null,K.load(),K.addEventListener("loadedmetadata",this.e.onMediaLoadedMetadata),this._mse_controller=new m.a(this._config),this._mse_controller.on(v.a.UPDATE_END,this._onMSEUpdateEnd.bind(this)),this._mse_controller.on(v.a.BUFFER_FULL,this._onMSEBufferFull.bind(this)),this._mse_controller.on(v.a.SOURCE_OPEN,this._onMSESourceOpen.bind(this)),this._mse_controller.on(v.a.ERROR,this._onMSEError.bind(this)),this._mse_controller.on(v.a.START_STREAMING,this._onMSEStartStreaming.bind(this)),this._mse_controller.on(v.a.END_STREAMING,this._onMSEEndStreaming.bind(this)),this._mse_controller.initialize({getCurrentTime:function(){return J._media_element.currentTime},getReadyState:function(){return J._media_element.readyState}}),this._mse_controller.isManagedMediaSource()?(K.disableRemotePlayback=!0,K.srcObject=this._mse_controller.getObject()):K.src=this._mse_controller.getObjectURL()},H.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)},H.prototype.load=function(){var K=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 y.a(this._media_data_source,this._config),this._transmuxer.on(E.a.INIT_SEGMENT,function(J,Q){K._mse_controller.appendInitSegment(Q)}),this._transmuxer.on(E.a.MEDIA_SEGMENT,function(J,Q){K._mse_controller.appendMediaSegment(Q),!K._config.isLive&&J==="video"&&Q.data&&Q.data.byteLength>0&&"info"in Q&&K._seeking_handler.appendSyncPoints(Q.info.syncPoints),K._loading_controller.notifyBufferedPositionChanged(Q.info.endDts/1e3)}),this._transmuxer.on(E.a.LOADING_COMPLETE,function(){K._mse_controller.endOfStream(),K._emitter.emit(g.a.LOADING_COMPLETE)}),this._transmuxer.on(E.a.RECOVERED_EARLY_EOF,function(){K._emitter.emit(g.a.RECOVERED_EARLY_EOF)}),this._transmuxer.on(E.a.IO_ERROR,function(J,Q){K._emitter.emit(g.a.ERROR,_.b.NETWORK_ERROR,J,Q)}),this._transmuxer.on(E.a.DEMUX_ERROR,function(J,Q){K._emitter.emit(g.a.ERROR,_.b.MEDIA_ERROR,J,Q)}),this._transmuxer.on(E.a.MEDIA_INFO,function(J){K._media_info=J,K._emitter.emit(g.a.MEDIA_INFO,Object.assign({},J))}),this._transmuxer.on(E.a.STATISTICS_INFO,function(J){K._statistics_info=K._fillStatisticsInfo(J),K._emitter.emit(g.a.STATISTICS_INFO,Object.assign({},J))}),this._transmuxer.on(E.a.RECOMMEND_SEEKPOINT,function(J){K._media_element&&!K._config.accurateSeek&&K._seeking_handler.directSeek(J/1e3)}),this._transmuxer.on(E.a.METADATA_ARRIVED,function(J){K._emitter.emit(g.a.METADATA_ARRIVED,J)}),this._transmuxer.on(E.a.SCRIPTDATA_ARRIVED,function(J){K._emitter.emit(g.a.SCRIPTDATA_ARRIVED,J)}),this._transmuxer.on(E.a.TIMED_ID3_METADATA_ARRIVED,function(J){K._emitter.emit(g.a.TIMED_ID3_METADATA_ARRIVED,J)}),this._transmuxer.on(E.a.SYNCHRONOUS_KLV_METADATA_ARRIVED,function(J){K._emitter.emit(g.a.SYNCHRONOUS_KLV_METADATA_ARRIVED,J)}),this._transmuxer.on(E.a.ASYNCHRONOUS_KLV_METADATA_ARRIVED,function(J){K._emitter.emit(g.a.ASYNCHRONOUS_KLV_METADATA_ARRIVED,J)}),this._transmuxer.on(E.a.SMPTE2038_METADATA_ARRIVED,function(J){K._emitter.emit(g.a.SMPTE2038_METADATA_ARRIVED,J)}),this._transmuxer.on(E.a.SCTE35_METADATA_ARRIVED,function(J){K._emitter.emit(g.a.SCTE35_METADATA_ARRIVED,J)}),this._transmuxer.on(E.a.PES_PRIVATE_DATA_DESCRIPTOR,function(J){K._emitter.emit(g.a.PES_PRIVATE_DATA_DESCRIPTOR,J)}),this._transmuxer.on(E.a.PES_PRIVATE_DATA_ARRIVED,function(J){K._emitter.emit(g.a.PES_PRIVATE_DATA_ARRIVED,J)}),this._seeking_handler=new P(this._config,this._media_element,this._onRequiredUnbufferedSeek.bind(this)),this._loading_controller=new I(this._config,this._media_element,this._onRequestPauseTransmuxer.bind(this),this._onRequestResumeTransmuxer.bind(this)),this._startup_stall_jumper=new k(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)},H.prototype.unload=function(){var K,J,Q,ve,Te,Ne,Ke,be,Pe;(K=this._media_element)===null||K===void 0||K.pause(),(J=this._live_latency_synchronizer)===null||J===void 0||J.destroy(),this._live_latency_synchronizer=null,(Q=this._live_latency_chaser)===null||Q===void 0||Q.destroy(),this._live_latency_chaser=null,(ve=this._startup_stall_jumper)===null||ve===void 0||ve.destroy(),this._startup_stall_jumper=null,(Te=this._loading_controller)===null||Te===void 0||Te.destroy(),this._loading_controller=null,(Ne=this._seeking_handler)===null||Ne===void 0||Ne.destroy(),this._seeking_handler=null,(Ke=this._mse_controller)===null||Ke===void 0||Ke.flush(),(be=this._transmuxer)===null||be===void 0||be.close(),(Pe=this._transmuxer)===null||Pe===void 0||Pe.destroy(),this._transmuxer=null},H.prototype.play=function(){return this._media_element.play()},H.prototype.pause=function(){this._media_element.pause()},H.prototype.seek=function(K){this._media_element&&this._seeking_handler?this._seeking_handler.seek(K):this._pending_seek_time=K},Object.defineProperty(H.prototype,"mediaInfo",{get:function(){return Object.assign({},this._media_info)},enumerable:!1,configurable:!0}),Object.defineProperty(H.prototype,"statisticsInfo",{get:function(){return Object.assign({},this._statistics_info)},enumerable:!1,configurable:!0}),H.prototype._onMSESourceOpen=function(){this._mse_source_opened=!0,this._has_pending_load&&(this._has_pending_load=!1,this.load())},H.prototype._onMSEUpdateEnd=function(){this._config.isLive&&this._config.liveBufferLatencyChasing&&this._live_latency_chaser&&this._live_latency_chaser.notifyBufferedRangeUpdate(),this._loading_controller.notifyBufferedPositionChanged()},H.prototype._onMSEBufferFull=function(){d.a.v(this.TAG,"MSE SourceBuffer is full, suspend transmuxing task"),this._loading_controller.suspendTransmuxer()},H.prototype._onMSEError=function(K){this._emitter.emit(g.a.ERROR,_.b.MEDIA_ERROR,_.a.MEDIA_MSE_ERROR,K)},H.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()))},H.prototype._onMSEEndStreaming=function(){this._config.isLive||(d.a.v(this.TAG,"Suspend transmuxing task due to ManagedMediaSource onEndStreaming"),this._loading_controller.suspendTransmuxer())},H.prototype._onMediaLoadedMetadata=function(K){this._loaded_metadata_received=!0,this._pending_seek_time!=null&&(this._seeking_handler.seek(this._pending_seek_time),this._pending_seek_time=null)},H.prototype._onRequestDirectSeek=function(K){this._seeking_handler.directSeek(K)},H.prototype._onRequiredUnbufferedSeek=function(K){this._mse_controller.flush(),this._transmuxer.seek(K)},H.prototype._onRequestPauseTransmuxer=function(){this._transmuxer.pause()},H.prototype._onRequestResumeTransmuxer=function(){this._transmuxer.resume()},H.prototype._fillStatisticsInfo=function(K){if(K.playerType="MSEPlayer",!(this._media_element instanceof HTMLVideoElement))return K;var J=!0,Q=0,ve=0;if(this._media_element.getVideoPlaybackQuality){var Te=this._media_element.getVideoPlaybackQuality();Q=Te.totalVideoFrames,ve=Te.droppedVideoFrames}else this._media_element.webkitDecodedFrameCount!=null?(Q=this._media_element.webkitDecodedFrameCount,ve=this._media_element.webkitDroppedFrameCount):J=!1;return J&&(K.decodedFrames=Q,K.droppedFrames=ve),K},H}(),Y=s(18),q=s(8),X=function(){function H(K,J){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=K,this._config=l(),typeof J=="object"&&Object.assign(this._config,J),K.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)},q.a.registerListener(this.e.onLoggingConfigChanged),this._worker=Y(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:q.a.getConfig()})}return H.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))},H.prototype.destroy=function(){this._emitter.emit(g.a.DESTROYING),this.unload(),this.detachMediaElement(),this._worker_destroying=!0,this._worker.postMessage({cmd:"destroy"}),q.a.removeListener(this.e.onLoggingConfigChanged),this.e=null,this._media_data_source=null,this._emitter.removeAllListeners(),this._emitter=null},H.prototype.on=function(K,J){var Q=this;this._emitter.addListener(K,J),K===g.a.MEDIA_INFO&&this._media_info?Promise.resolve().then(function(){return Q._emitter.emit(g.a.MEDIA_INFO,Q.mediaInfo)}):K==g.a.STATISTICS_INFO&&this._statistics_info&&Promise.resolve().then(function(){return Q._emitter.emit(g.a.STATISTICS_INFO,Q.statisticsInfo)})},H.prototype.off=function(K,J){this._emitter.removeListener(K,J)},H.prototype.attachMediaElement=function(K){this._media_element=K,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"})},H.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)},H.prototype.load=function(){this._worker.postMessage({cmd:"load"}),this._seeking_handler=new P(this._config,this._media_element,this._onRequiredUnbufferedSeek.bind(this)),this._loading_controller=new I(this._config,this._media_element,this._onRequestPauseTransmuxer.bind(this),this._onRequestResumeTransmuxer.bind(this)),this._startup_stall_jumper=new k(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)},H.prototype.unload=function(){var K,J,Q,ve,Te,Ne;(K=this._media_element)===null||K===void 0||K.pause(),this._worker.postMessage({cmd:"unload"}),(J=this._live_latency_synchronizer)===null||J===void 0||J.destroy(),this._live_latency_synchronizer=null,(Q=this._live_latency_chaser)===null||Q===void 0||Q.destroy(),this._live_latency_chaser=null,(ve=this._startup_stall_jumper)===null||ve===void 0||ve.destroy(),this._startup_stall_jumper=null,(Te=this._loading_controller)===null||Te===void 0||Te.destroy(),this._loading_controller=null,(Ne=this._seeking_handler)===null||Ne===void 0||Ne.destroy(),this._seeking_handler=null},H.prototype.play=function(){return this._media_element.play()},H.prototype.pause=function(){this._media_element.pause()},H.prototype.seek=function(K){this._media_element&&this._seeking_handler?this._seeking_handler.seek(K):this._pending_seek_time=K},Object.defineProperty(H.prototype,"mediaInfo",{get:function(){return Object.assign({},this._media_info)},enumerable:!1,configurable:!0}),Object.defineProperty(H.prototype,"statisticsInfo",{get:function(){return Object.assign({},this._statistics_info)},enumerable:!1,configurable:!0}),H.prototype._onLoggingConfigChanged=function(K){var J;(J=this._worker)===null||J===void 0||J.postMessage({cmd:"logging_config",logging_config:K})},H.prototype._onMSEUpdateEnd=function(){this._config.isLive&&this._config.liveBufferLatencyChasing&&this._live_latency_chaser&&this._live_latency_chaser.notifyBufferedRangeUpdate(),this._loading_controller.notifyBufferedPositionChanged()},H.prototype._onMSEBufferFull=function(){d.a.v(this.TAG,"MSE SourceBuffer is full, suspend transmuxing task"),this._loading_controller.suspendTransmuxer()},H.prototype._onMediaLoadedMetadata=function(K){this._pending_seek_time!=null&&(this._seeking_handler.seek(this._pending_seek_time),this._pending_seek_time=null)},H.prototype._onRequestDirectSeek=function(K){this._seeking_handler.directSeek(K)},H.prototype._onRequiredUnbufferedSeek=function(K){this._worker.postMessage({cmd:"unbuffered_seek",milliseconds:K})},H.prototype._onRequestPauseTransmuxer=function(){this._worker.postMessage({cmd:"pause_transmuxer"})},H.prototype._onRequestResumeTransmuxer=function(){this._worker.postMessage({cmd:"resume_transmuxer"})},H.prototype._onMediaTimeUpdate=function(K){this._worker.postMessage({cmd:"timeupdate",current_time:K.target.currentTime})},H.prototype._onMediaReadyStateChange=function(K){this._worker.postMessage({cmd:"readystatechange",ready_state:K.target.readyState})},H.prototype._onWorkerMessage=function(K){var J,Q=K.data,ve=Q.msg;if(ve=="destroyed"||this._worker_destroying)return this._worker_destroying=!1,(J=this._worker)===null||J===void 0||J.terminate(),void(this._worker=null);switch(ve){case"mse_init":var Te=Q;"ManagedMediaSource"in self&&!("MediaSource"in self)&&(this._media_element.disableRemotePlayback=!0),this._media_element.srcObject=Te.handle;break;case"mse_event":(Te=Q).event==v.a.UPDATE_END?this._onMSEUpdateEnd():Te.event==v.a.BUFFER_FULL&&this._onMSEBufferFull();break;case"transmuxing_event":if((Te=Q).event==E.a.MEDIA_INFO){var Ne=Q;this._media_info=Ne.info,this._emitter.emit(g.a.MEDIA_INFO,Object.assign({},Ne.info))}else if(Te.event==E.a.STATISTICS_INFO){var Ke=Q;this._statistics_info=this._fillStatisticsInfo(Ke.info),this._emitter.emit(g.a.STATISTICS_INFO,Object.assign({},Ke.info))}else if(Te.event==E.a.RECOMMEND_SEEKPOINT){var be=Q;this._media_element&&!this._config.accurateSeek&&this._seeking_handler.directSeek(be.milliseconds/1e3)}break;case"player_event":if((Te=Q).event==g.a.ERROR){var Pe=Q;this._emitter.emit(g.a.ERROR,Pe.error_type,Pe.error_detail,Pe.info)}else if("extraData"in Te){var Ae=Q;this._emitter.emit(Ae.event,Ae.extraData)}break;case"logcat_callback":Te=Q,d.a.emitter.emit("log",Te.type,Te.logcat);break;case"buffered_position_changed":Te=Q,this._loading_controller.notifyBufferedPositionChanged(Te.buffered_position_milliseconds/1e3)}},H.prototype._fillStatisticsInfo=function(K){if(K.playerType="MSEPlayer",!(this._media_element instanceof HTMLVideoElement))return K;var J=!0,Q=0,ve=0;if(this._media_element.getVideoPlaybackQuality){var Te=this._media_element.getVideoPlaybackQuality();Q=Te.totalVideoFrames,ve=Te.droppedVideoFrames}else this._media_element.webkitDecodedFrameCount!=null?(Q=this._media_element.webkitDecodedFrameCount,ve=this._media_element.webkitDroppedFrameCount):J=!1;return J&&(K.decodedFrames=Q,K.droppedFrames=ve),K},H}(),Z=function(){function H(K,J){this.TAG="MSEPlayer",this._type="MSEPlayer",this._media_element=null,this._player_engine=null;var Q=K.type.toLowerCase();if(Q!=="mse"&&Q!=="mpegts"&&Q!=="m2ts"&&Q!=="flv")throw new S.b("MSEPlayer requires an mpegts/m2ts/flv MediaDataSource input!");if(J&&J.enableWorkerForMSE&&X.isSupported())try{this._player_engine=new X(K,J)}catch{d.a.e(this.TAG,"Error while initializing PlayerEngineDedicatedThread, fallback to PlayerEngineMainThread"),this._player_engine=new G(K,J)}else this._player_engine=new G(K,J)}return H.prototype.destroy=function(){this._player_engine.destroy(),this._player_engine=null,this._media_element=null},H.prototype.on=function(K,J){this._player_engine.on(K,J)},H.prototype.off=function(K,J){this._player_engine.off(K,J)},H.prototype.attachMediaElement=function(K){this._media_element=K,this._player_engine.attachMediaElement(K)},H.prototype.detachMediaElement=function(){this._media_element=null,this._player_engine.detachMediaElement()},H.prototype.load=function(){this._player_engine.load()},H.prototype.unload=function(){this._player_engine.unload()},H.prototype.play=function(){return this._player_engine.play()},H.prototype.pause=function(){this._player_engine.pause()},Object.defineProperty(H.prototype,"type",{get:function(){return this._type},enumerable:!1,configurable:!0}),Object.defineProperty(H.prototype,"buffered",{get:function(){return this._media_element.buffered},enumerable:!1,configurable:!0}),Object.defineProperty(H.prototype,"duration",{get:function(){return this._media_element.duration},enumerable:!1,configurable:!0}),Object.defineProperty(H.prototype,"volume",{get:function(){return this._media_element.volume},set:function(K){this._media_element.volume=K},enumerable:!1,configurable:!0}),Object.defineProperty(H.prototype,"muted",{get:function(){return this._media_element.muted},set:function(K){this._media_element.muted=K},enumerable:!1,configurable:!0}),Object.defineProperty(H.prototype,"currentTime",{get:function(){return this._media_element?this._media_element.currentTime:0},set:function(K){this._player_engine.seek(K)},enumerable:!1,configurable:!0}),Object.defineProperty(H.prototype,"mediaInfo",{get:function(){return this._player_engine.mediaInfo},enumerable:!1,configurable:!0}),Object.defineProperty(H.prototype,"statisticsInfo",{get:function(){return this._player_engine.statisticsInfo},enumerable:!1,configurable:!0}),H}(),oe=function(){function H(K,J){this.TAG="NativePlayer",this._type="NativePlayer",this._emitter=new f.a,this._config=l(),typeof J=="object"&&Object.assign(this._config,J);var Q=K.type.toLowerCase();if(Q==="mse"||Q==="mpegts"||Q==="m2ts"||Q==="flv")throw new S.b("NativePlayer does't support mse/mpegts/m2ts/flv MediaDataSource input!");if(K.hasOwnProperty("segments"))throw new S.b("NativePlayer(".concat(K.type,") doesn't support multipart playback!"));this.e={onvLoadedMetadata:this._onvLoadedMetadata.bind(this)},this._pendingSeekTime=null,this._statisticsReporter=null,this._mediaDataSource=K,this._mediaElement=null}return H.prototype.destroy=function(){this._emitter.emit(g.a.DESTROYING),this._mediaElement&&(this.unload(),this.detachMediaElement()),this.e=null,this._mediaDataSource=null,this._emitter.removeAllListeners(),this._emitter=null},H.prototype.on=function(K,J){var Q=this;K===g.a.MEDIA_INFO?this._mediaElement!=null&&this._mediaElement.readyState!==0&&Promise.resolve().then(function(){Q._emitter.emit(g.a.MEDIA_INFO,Q.mediaInfo)}):K===g.a.STATISTICS_INFO&&this._mediaElement!=null&&this._mediaElement.readyState!==0&&Promise.resolve().then(function(){Q._emitter.emit(g.a.STATISTICS_INFO,Q.statisticsInfo)}),this._emitter.addListener(K,J)},H.prototype.off=function(K,J){this._emitter.removeListener(K,J)},H.prototype.attachMediaElement=function(K){if(this._mediaElement=K,K.addEventListener("loadedmetadata",this.e.onvLoadedMetadata),this._pendingSeekTime!=null)try{K.currentTime=this._pendingSeekTime,this._pendingSeekTime=null}catch{}},H.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)},H.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)},H.prototype.unload=function(){this._mediaElement&&(this._mediaElement.src="",this._mediaElement.removeAttribute("src")),this._statisticsReporter!=null&&(window.clearInterval(this._statisticsReporter),this._statisticsReporter=null)},H.prototype.play=function(){return this._mediaElement.play()},H.prototype.pause=function(){this._mediaElement.pause()},Object.defineProperty(H.prototype,"type",{get:function(){return this._type},enumerable:!1,configurable:!0}),Object.defineProperty(H.prototype,"buffered",{get:function(){return this._mediaElement.buffered},enumerable:!1,configurable:!0}),Object.defineProperty(H.prototype,"duration",{get:function(){return this._mediaElement.duration},enumerable:!1,configurable:!0}),Object.defineProperty(H.prototype,"volume",{get:function(){return this._mediaElement.volume},set:function(K){this._mediaElement.volume=K},enumerable:!1,configurable:!0}),Object.defineProperty(H.prototype,"muted",{get:function(){return this._mediaElement.muted},set:function(K){this._mediaElement.muted=K},enumerable:!1,configurable:!0}),Object.defineProperty(H.prototype,"currentTime",{get:function(){return this._mediaElement?this._mediaElement.currentTime:0},set:function(K){this._mediaElement?this._mediaElement.currentTime=K:this._pendingSeekTime=K},enumerable:!1,configurable:!0}),Object.defineProperty(H.prototype,"mediaInfo",{get:function(){var K={mimeType:(this._mediaElement instanceof HTMLAudioElement?"audio/":"video/")+this._mediaDataSource.type};return this._mediaElement&&(K.duration=Math.floor(1e3*this._mediaElement.duration),this._mediaElement instanceof HTMLVideoElement&&(K.width=this._mediaElement.videoWidth,K.height=this._mediaElement.videoHeight)),K},enumerable:!1,configurable:!0}),Object.defineProperty(H.prototype,"statisticsInfo",{get:function(){var K={playerType:this._type,url:this._mediaDataSource.url};if(!(this._mediaElement instanceof HTMLVideoElement))return K;var J=!0,Q=0,ve=0;if(this._mediaElement.getVideoPlaybackQuality){var Te=this._mediaElement.getVideoPlaybackQuality();Q=Te.totalVideoFrames,ve=Te.droppedVideoFrames}else this._mediaElement.webkitDecodedFrameCount!=null?(Q=this._mediaElement.webkitDecodedFrameCount,ve=this._mediaElement.webkitDroppedFrameCount):J=!1;return J&&(K.decodedFrames=Q,K.droppedFrames=ve),K},enumerable:!1,configurable:!0}),H.prototype._onvLoadedMetadata=function(K){this._pendingSeekTime!=null&&(this._mediaElement.currentTime=this._pendingSeekTime,this._pendingSeekTime=null),this._emitter.emit(g.a.MEDIA_INFO,this.mediaInfo)},H.prototype._reportStatisticsInfo=function(){this._emitter.emit(g.a.STATISTICS_INFO,this.statisticsInfo)},H}();i.a.install();var ne={createPlayer:function(H,K){var J=H;if(J==null||typeof J!="object")throw new S.b("MediaDataSource must be an javascript object!");if(!J.hasOwnProperty("type"))throw new S.b("MediaDataSource must has type field to indicate video file type!");switch(J.type){case"mse":case"mpegts":case"m2ts":case"flv":return new Z(J,K);default:return new oe(J,K)}},isSupported:function(){return c.supportMSEH264Playback()},getFeatureList:function(){return c.getFeatureList()}};ne.BaseLoader=u.a,ne.LoaderStatus=u.c,ne.LoaderErrors=u.b,ne.Events=g.a,ne.ErrorTypes=_.b,ne.ErrorDetails=_.a,ne.MSEPlayer=Z,ne.NativePlayer=oe,ne.LoggingControl=q.a,Object.defineProperty(ne,"version",{enumerable:!0,get:function(){return"1.8.0"}}),r.default=ne}])})})(X4);var Kme=X4.exports;const fO=tv(Kme),Ux=typeof navigator<"u"?navigator.userAgent:"",Hme=()=>typeof window>"u"?"none":typeof window.tizen<"u"||window.webapis&&typeof window.webapis.avplay<"u"||/Tizen/i.test(Ux)&&/SmartTV/i.test(Ux)?"tizen":typeof window.webOS<"u"||typeof window.webOSSystem<"u"||typeof window.PalmSystem<"u"||/Web0S|webOS\.TV/i.test(Ux)?"webos":"none";let Bx=null;const GA=()=>(Bx===null&&(Bx=Hme()),Bx),zme=()=>GA()==="tizen",Q4=()=>GA()==="webos",qme=()=>GA()!=="none",Wme=t=>{if(!t||rs.isNativePlatform()||qme())return t;const e=encodeURIComponent(_i());return`${X3()}?url=${encodeURIComponent(t)}&ua=${e}`},s_=()=>{var e;return typeof window>"u"?null:((e=window.webapis)==null?void 0:e.avplay)??null},Yme=()=>s_()!==null;let _n=null;const J4=t=>{const e=s_();if(!e)return;const n=t.getBoundingClientRect();try{e.setDisplayRect(Math.round(n.left),Math.round(n.top),Math.round(n.width),Math.round(n.height))}catch(r){console.warn("[Tizen AVPlay] setDisplayRect failed",r)}},Z4=()=>{const t=s_();if(t){try{t.stop()}catch(e){console.warn("[Tizen AVPlay] stop failed",e)}try{t.close()}catch(e){console.warn("[Tizen AVPlay] close failed",e)}_n=null}},Xme=(t,e)=>{var r,s;const n=s_();if(!n){(r=e.onError)==null||r.call(e,"AVPlay API not available");return}Z4(),_n=e;try{if(n.open(e.url),e.userAgent)try{n.setStreamingProperty("USER_AGENT",e.userAgent)}catch(i){console.warn("[Tizen AVPlay] setStreamingProperty USER_AGENT failed",i)}try{n.setStreamingProperty("ADAPTIVE_INFO","BITRATES=auto|STARTBITRATE=LOWEST|SKIPBITRATE=LOWEST")}catch(i){console.warn("[Tizen AVPlay] setStreamingProperty ADAPTIVE_INFO failed",i)}n.setDisplayMethod("PLAYER_DISPLAY_MODE_FULL_SCREEN"),J4(t),n.setListener({onbufferingstart:()=>{var i;return(i=_n==null?void 0:_n.onBufferingStart)==null?void 0:i.call(_n)},onbufferingcomplete:()=>{var i;return(i=_n==null?void 0:_n.onBufferingComplete)==null?void 0:i.call(_n)},oncurrentplaytime:i=>{var a;return(a=_n==null?void 0:_n.onTimeUpdate)==null?void 0:a.call(_n,i)},onstreamcompleted:()=>{var i;return(i=_n==null?void 0:_n.onEnded)==null?void 0:i.call(_n)},onerror:i=>{var a;console.error("[Tizen AVPlay] error event:",i),(a=_n==null?void 0:_n.onError)==null||a.call(_n,String(i))}}),n.prepareAsync(()=>{var i;try{n.play()}catch(a){console.error("[Tizen AVPlay] play() threw:",a),(i=e.onError)==null||i.call(e,`play failed: ${String(a)}`)}},i=>{var a;console.error("[Tizen AVPlay] prepareAsync failed:",i),(a=e.onError)==null||a.call(e,`prepare failed: ${String(i)}`)})}catch(i){console.error("[Tizen AVPlay] open/prepare threw:",i),(s=e.onError)==null||s.call(e,`open failed: ${String(i)}`)}},Qme=(t,e={})=>{if(!Q4())return t;const r={mediaTransportType:e.transport&&e.transport!=="auto"?e.transport.toUpperCase():/\.m3u8(\?|$)/i.test(t)?"HLS":/\.ts(\?|$)/i.test(t)||/\/live\//i.test(t)?"MPEG-TS":/\.mpd(\?|$)/i.test(t)?"DASH":"URI",option:{htmlMediaOption:{useUMSMediaInfo:!0},adaptiveStreaming:{apsBitrate:e.adaptiveStreaming===!1?0:1,adaptiveResolution:"auto"},bufferingMinTime:1e3,bufferingMaxTime:6e3,...e.isLive?{liveBuffering:{minTime:4e3,maxTime:12e3}}:{},...e.userAgent?{httpHeader:`User-Agent: ${e.userAgent}`}:{}}};return`${t}|${JSON.stringify(r)}`},eo="video/*",Jme=[[/\.m3u8(\?|$)/i,eo],[/\.ts(\?|$)/i,eo],[/\.mpd(\?|$)/i,eo],[/\.mp4(\?|$)/i,eo],[/\.mkv(\?|$)/i,eo],[/\.webm(\?|$)/i,eo],[/\.avi(\?|$)/i,eo],[/\.mov(\?|$)/i,eo]],Zme=t=>{for(const[e,n]of Jme)if(e.test(t))return n;return eo},ege=(t,e={})=>{const n=t.match(/^(https?):\/\/(.+)$/i);if(!n)return t;const[,r,s]=n,i=e.mime??Zme(t),a=[`scheme=${r}`,"action=android.intent.action.VIEW",`type=${i}`];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://${s}#Intent;${a.join(";")}`},e$=t=>`vlc://${t}`,KA=t=>`vlc-x-callback://x-callback-url/stream?url=${encodeURIComponent(t)}`,tge=t=>`market://details?id=${encodeURIComponent(t)}`,pO=t=>`https://play.google.com/store/apps/details?id=${encodeURIComponent(t)}`,nge=()=>typeof navigator>"u"?!1:/Android/i.test(navigator.userAgent),rge=()=>typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent),t$=(t,e={})=>{if(nge())try{const n=ege(t,e);let r=!1;const s=()=>{typeof document<"u"&&document.hidden&&(r=!0,document.removeEventListener("visibilitychange",s))};return typeof document<"u"&&document.addEventListener("visibilitychange",s),window.setTimeout(()=>{typeof document<"u"&&(document.removeEventListener("visibilitychange",s),!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(rge())try{return window.location.href=KA(t),!0}catch(n){return console.warn("[externalLauncher] iOS launch failed",n),!1}return!1},n$=t=>{try{const e=tge(t);window.setTimeout(()=>{window.location.href=e,window.setTimeout(()=>{typeof document<"u"&&!document.hidden&&(window.location.href=pO(t))},1200)},50)}catch(e){console.warn("[externalLauncher] openPlayStore failed",e),window.location.href=pO(t)}},sge=t=>/\.m3u8(\?|$)/i.test(t)||/\/live\//i.test(t)||/\.ts(\?|$)/i.test(t),i_=({src:t,poster:e,title:n,autoPlay:r=!0,className:s="",isLive:i})=>{const a=C.useRef(null),o=C.useRef(null),l=C.useRef(null),c=C.useRef(null),u=C.useRef(null),[d,h]=C.useState(!1),[f,m]=C.useState("idle"),g=i??sge(t),y=Cm(),v=zme()&&Yme(),_=Q4(),S=oF(),E=C.useCallback(()=>{const P=l.current;if(P)try{P.stopLoad(),P.startLoad()}catch(I){console.warn("[VideoPlayer] restartStream failed:",I)}},[]),L=C.useCallback(async()=>{try{await ol.play({url:t,title:n??"",userAgent:_i(),isLive:g})}catch(P){console.error("[VideoPlayer] native play failed:",P),It.error("Native player failed")}},[t,n,g]),U=C.useCallback(async()=>{h(!0);try{if(y){const P=async R=>await ol.openExternal({url:t,title:n??"",userAgent:_i(),package:R}),I=await P("com.brouken.player");if(I!=null&&I.launched)return;const k=await P("org.videolan.vlc");if(k!=null&&k.launched)return;It.error("Please install ExoPlayer or VLC",{action:{label:"Install",onClick:()=>ol.openPlayStore({package:"com.brouken.player"})},duration:1e4})}else t$(t,{package:"com.brouken.player",title:n??"",userAgent:_i(),onNotInstalled:I=>{It.error("Please install ExoPlayer or VLC",{action:{label:"Install",onClick:()=>n$(I||"com.brouken.player")},duration:1e4})}})||It.message('Tap "Open in player" to launch the stream')}catch(P){console.error("[VideoPlayer] external launch failed:",P),It.error((P==null?void 0:P.message)??"Couldn't open external player")}finally{window.setTimeout(()=>h(!1),900)}},[t,n,y]);if(C.useEffect(()=>{t&&u.current!==t&&(u.current=t,y&&r&&(S==="external"?U():L()))},[t,y,S]),C.useEffect(()=>{if(y||v||S==="external")return;const P=a.current;if(!P||!t)return;const k=(_?Qme(t,{isLive:g,adaptiveStreaming:!0,userAgent:_i()}):null)??Wme(t),R=P.canPlayType("application/vnd.apple.mpegurl")!=="";let M=!1,G=0;P.pause(),P.removeAttribute("src"),P.load();try{P.muted=!1,P.volume=1}catch(X){console.warn("[VideoPlayer] reset mute/volume failed",X)}const Y=()=>{const X=new zs({autoStartLoad:!0,enableWorker:!0,lowLatencyMode:!1,backBufferLength:60,maxBufferLength:60,maxMaxBufferLength:120,maxBufferSize:6e7,liveSyncDuration:g?10:void 0,liveMaxLatencyDuration:g?30:void 0,liveDurationInfinity:g,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});l.current=X,X.loadSource(k),X.attachMedia(P),X.on(zs.Events.MANIFEST_PARSED,()=>{if(g){P.muted=!0;try{X.levels&&X.levels.length>1&&(X.currentLevel=1)}catch(Z){console.warn("[VideoPlayer] set initial level failed",Z)}}r&&P.play().catch(()=>{})}),X.on(zs.Events.ERROR,(Z,oe)=>{if(!M&&oe.fatal)switch(oe.type){case zs.ErrorTypes.NETWORK_ERROR:if(console.warn("[HLS] network error",oe.details),oe.details==="manifestLoadError"||oe.details==="manifestLoadTimeOut"||oe.details==="manifestParsingError"){try{X.destroy()}catch(ne){console.warn("[VideoPlayer] hls.destroy failed (manifest error path)",ne)}l.current=null,q()}else window.setTimeout(()=>{M||E()},1200);break;case zs.ErrorTypes.MEDIA_ERROR:if(console.warn("[HLS] media error → recoverMediaError()",oe.details),G<2){G++;try{X.recoverMediaError()}catch{}}else if(G<4){G++;try{X.swapAudioCodec(),X.recoverMediaError()}catch{}}else{console.error("[HLS] gave up recovering media errors");try{X.destroy()}catch{}l.current=null,g&&q()}break;default:console.error("[HLS] fatal other:",oe.type,oe.details);try{X.destroy()}catch{}l.current=null,g&&q();break}})},q=()=>{if(!fO.isSupported())return;const X=fO.createPlayer({type:"mpegts",isLive:g,url:k},{enableWorker:!0,liveBufferLatencyChasing:!1,lazyLoad:!1,autoCleanupSourceBuffer:!0,stashInitialSize:384});if(c.current=X,X.attachMediaElement(P),X.load(),g&&(P.muted=!0),r){const Z=X.play();Z&&typeof Z.catch=="function"&&Z.catch(()=>{})}};if(g&&zs.isSupported()&&!_)Y();else if(g&&(R||_))P.src=k,P.muted=!0,r&&P.play().catch(()=>{});else{try{P.removeAttribute("crossorigin")}catch{}if(P.src=k,P.muted=!1,r){const X=P.play();X&&typeof X.catch=="function"&&X.catch(Z=>{(Z==null?void 0:Z.name)==="NotAllowedError"&&(P.muted=!0,P.play().catch(()=>{}))})}}return()=>{if(M=!0,l.current){try{l.current.destroy()}catch{}l.current=null}if(c.current){try{c.current.pause(),c.current.unload(),c.current.detachMediaElement(),c.current.destroy()}catch{}c.current=null}try{P.removeAttribute("src"),P.load()}catch{}}},[t,r,g,y,v,_,S]),C.useEffect(()=>{if(!v||S==="external")return;const P=o.current;if(!P||!t)return;m("buffering"),Xme(P,{url:t,userAgent:_i(),isLive:g,onBufferingStart:()=>m("buffering"),onBufferingComplete:()=>m("playing"),onEnded:()=>m("idle"),onError:k=>{console.error("[Tizen AVPlay]",k),m("error")}});const I=new ResizeObserver(()=>{J4(P)});return I.observe(P),()=>{I.disconnect(),Z4(),m("idle")}},[t,v,g,S]),S==="external"){const P=typeof navigator<"u"?navigator.userAgent:"",I=/iPad|iPhone|iPod/.test(P),k=/Android/i.test(P),R=I?KA(t):k?void 0:e$(t);return p.jsx("div",{className:`relative w-full h-full bg-black flex items-center justify-center ${s}`,style:e?{backgroundImage:`url(${e})`,backgroundSize:"cover",backgroundPosition:"center"}:void 0,children:y||k?p.jsxs("button",{onClick: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",children:[d?p.jsx(Pn,{className:"w-5 h-5 animate-spin"}):p.jsx(vo,{className:"w-5 h-5"}),"Open stream"]}):p.jsxs("a",{href:R,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:[p.jsx(vo,{className:"w-5 h-5"}),"Open in VLC"]})})}if(v)return p.jsxs("div",{ref:o,className:`relative w-full h-full bg-black ${s}`,"data-testid":"tizen-avplay-container",children:[p.jsx("object",{type:"application/avplayer",style:{width:"100%",height:"100%"}}),f==="buffering"&&p.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:p.jsx(Pn,{className:"w-10 h-10 animate-spin text-white/80"})}),f==="error"&&p.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/60 text-white text-sm",children:"Stream unavailable. Check your IPTV server."})]});if(y){const P=()=>ol.openExternal({url:t,title:n??"",userAgent:_i(),package:"org.videolan.vlc"}).then(I=>{!(I!=null&&I.launched)&&(I==null?void 0:I.reason)==="not-installed"&&It.error("VLC is not installed",{action:{label:"Install",onClick:()=>ol.openPlayStore({package:"org.videolan.vlc"})},duration:8e3})});return p.jsx("div",{className:`relative w-full h-full bg-black flex items-center justify-center ${s}`,style:e?{backgroundImage:`url(${e})`,backgroundSize:"cover",backgroundPosition:"center"}:void 0,children:p.jsxs("div",{className:"flex flex-col gap-3 items-center",children:[p.jsxs("button",{onClick:L,disabled:d,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:[d?p.jsx(Pn,{className:"w-5 h-5 animate-spin"}):p.jsx(va,{className:"w-5 h-5"}),d?"Opening…":"Play"]}),p.jsxs("button",{onClick:P,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:[p.jsx(vo,{className:"w-3.5 h-3.5"}),"Open in VLC instead"]}),p.jsxs("p",{className:"text-xs text-white/50",children:[Wre()==="ios"?"AVPlayer":"ExoPlayer",n?` · ${n}`:""]})]})})}return p.jsx("video",{ref:a,poster:e,controls:!0,playsInline:!0,className:`w-full h-full bg-black ${s}`})},ige=({src:t,poster:e,title:n,isLive:r,onPrevChannel:s,onNextChannel:i,canGoPrev:a=!0,canGoNext:o=!0})=>{const l=C.useRef(null),[c,u]=C.useState(!1),[d,h]=C.useState(!1),f=C.useCallback(()=>{var v;return((v=l.current)==null?void 0:v.querySelector("video"))??null},[]);C.useEffect(()=>{const v=f();if(!v)return;const _=()=>u(!0),S=()=>u(!1);return v.addEventListener("play",_),v.addEventListener("pause",S),u(!v.paused),()=>{v.removeEventListener("play",_),v.removeEventListener("pause",S)}},[f,t]),C.useEffect(()=>{const v=()=>{h(document.fullscreenElement===l.current)};return document.addEventListener("fullscreenchange",v),()=>document.removeEventListener("fullscreenchange",v)},[]);const m=C.useCallback(()=>{const v=f();v&&(v.paused?v.play():v.pause())},[f]),g=C.useCallback(()=>{const v=l.current;v&&(document.fullscreenElement===v?document.exitFullscreen():v.requestFullscreen&&v.requestFullscreen().catch(()=>{}))},[]),y=C.useCallback(v=>{v.preventDefault(),g()},[g]);return p.jsxs("div",{ref:l,className:"relative w-full h-full bg-black rounded-xl overflow-hidden flex flex-col","data-testid":"inline-preview-player",children:[p.jsx("div",{className:"relative flex-1 min-h-0",onDoubleClick:y,children:p.jsx(i_,{src:t,poster:e,title:n,isLive:r})}),p.jsxs("div",{className:["flex items-center justify-center gap-1 px-3 py-2 bg-gradient-to-t from-black/90 via-black/70 to-transparent",d?"absolute bottom-0 left-0 right-0 z-20 pointer-events-auto":"relative"].join(" "),"data-testid":"inline-preview-controls",children:[p.jsx(Jg,{label:"Previous channel",testId:"inline-prev-channel",disabled:!a||!s,onClick:()=>s==null?void 0:s(),children:p.jsx(q9,{className:"w-5 h-5",fill:"currentColor",strokeWidth:0})}),p.jsx(Jg,{label:c?"Pause":"Play",testId:"inline-play-pause",onClick:m,children:c?p.jsx(E9,{className:"w-6 h-6",fill:"currentColor",strokeWidth:0}):p.jsx(va,{className:"w-6 h-6 ml-0.5",fill:"currentColor",strokeWidth:0})}),p.jsx(Jg,{label:"Next channel",testId:"inline-next-channel",disabled:!o||!i,onClick:()=>i==null?void 0:i(),children:p.jsx(Uj,{className:"w-5 h-5",fill:"currentColor",strokeWidth:0})}),p.jsx(Jg,{label:d?"Exit fullscreen":"Fullscreen",testId:"inline-fullscreen",onClick:g,children:p.jsx(_9,{className:"w-5 h-5",strokeWidth:2.5})})]})]})},Jg=({label:t,testId:e,onClick:n,disabled:r,children:s})=>p.jsx("button",{type:"button",onClick:n,disabled:r,"aria-label":t,title:t,"data-testid":e,className:["min-w-[48px] min-h-[48px] flex items-center justify-center","rounded-full transition-all duration-150","text-primary hover:bg-primary/15 active:scale-95","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",r?"opacity-30 cursor-not-allowed":"cursor-pointer"].join(" "),children:s}),mO="nadiplay.inlinePreview.enabledCache.v1",age=()=>{const[t,e]=C.useState(()=>{try{const n=localStorage.getItem(mO);if(n==="0")return!1;if(n==="1")return!0}catch{}return!0});return C.useEffect(()=>{let n=!1;return P0().then(r=>{if(n)return;const s=r.inline_preview_enabled!==!1;e(s);try{localStorage.setItem(mO,s?"1":"0")}catch{}}).catch(()=>{}),()=>{n=!0}},[]),t},gO=(t,e)=>`nadiplay_fav_${t}_${e}`,HA=(t,e)=>{const[n,r]=C.useState(new Set);C.useEffect(()=>{if(!t)return r(new Set);const a=localStorage.getItem(gO(t,e));r(a?new Set(JSON.parse(a)):new Set)},[t,e]);const s=C.useCallback(a=>{t&&r(o=>{const l=new Set(o);return l.has(a)?l.delete(a):l.add(a),localStorage.setItem(gO(t,e),JSON.stringify([...l])),l})},[t,e]),i=C.useCallback(a=>n.has(a),[n]);return{favorites:n,toggle:s,isFavorite:i}},yO="nadiplay_device_id",oge=()=>{try{const t=localStorage.getItem(yO);if(t)return t;const e="dev-"+Math.random().toString(36).slice(2,10)+"-"+Date.now().toString(36);return localStorage.setItem(yO,e),e}catch{return"dev-anon-"+Date.now().toString(36)}},lge=(t,e={})=>{const{user:n}=ys();C.useEffect(()=>{if(!t||!n||!Pl())return;const r=()=>void Wee({device_id:oge(),channel:e.channel,kind:e.kind??"live"}).catch(()=>{});r();const s=window.setInterval(r,6e4);return()=>window.clearInterval(s)},[t,n==null?void 0:n.id,e.channel,e.kind])},cge=[{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"}],uge=()=>cge[0];var vO;(function(t){t.General="General",t.ParentalGuidance="ParentalGuidance",t.Teen="Teen",t.MatureAudience="MatureAudience"})(vO||(vO={}));var _O;(function(t){t.SizeChanged="bannerAdSizeChanged",t.Loaded="bannerAdLoaded",t.FailedToLoad="bannerAdFailedToLoad",t.Opened="bannerAdOpened",t.Closed="bannerAdClosed",t.AdImpression="bannerAdImpression"})(_O||(_O={}));var Fw;(function(t){t.TOP_CENTER="TOP_CENTER",t.CENTER="CENTER",t.BOTTOM_CENTER="BOTTOM_CENTER"})(Fw||(Fw={}));var $w;(function(t){t.BANNER="BANNER",t.FULL_BANNER="FULL_BANNER",t.LARGE_BANNER="LARGE_BANNER",t.MEDIUM_RECTANGLE="MEDIUM_RECTANGLE",t.LEADERBOARD="LEADERBOARD",t.ADAPTIVE_BANNER="ADAPTIVE_BANNER",t.SMART_BANNER="SMART_BANNER"})($w||($w={}));var bO;(function(t){t.Loaded="interstitialAdLoaded",t.FailedToLoad="interstitialAdFailedToLoad",t.Showed="interstitialAdShowed",t.FailedToShow="interstitialAdFailedToShow",t.Dismissed="interstitialAdDismissed"})(bO||(bO={}));var xO;(function(t){t.Loaded="onRewardedInterstitialAdLoaded",t.FailedToLoad="onRewardedInterstitialAdFailedToLoad",t.Showed="onRewardedInterstitialAdShowed",t.FailedToShow="onRewardedInterstitialAdFailedToShow",t.Dismissed="onRewardedInterstitialAdDismissed",t.Rewarded="onRewardedInterstitialAdReward"})(xO||(xO={}));var SO;(function(t){t.Loaded="onRewardedVideoAdLoaded",t.FailedToLoad="onRewardedVideoAdFailedToLoad",t.Showed="onRewardedVideoAdShowed",t.FailedToShow="onRewardedVideoAdFailedToShow",t.Dismissed="onRewardedVideoAdDismissed",t.Rewarded="onRewardedVideoAdReward"})(SO||(SO={}));var EO;(function(t){t.NOT_REQUIRED="NOT_REQUIRED",t.OBTAINED="OBTAINED",t.REQUIRED="REQUIRED",t.UNKNOWN="UNKNOWN"})(EO||(EO={}));var wO;(function(t){t[t.DISABLED=0]="DISABLED",t[t.EEA=1]="EEA",t[t.NOT_EEA=2]="NOT_EEA",t[t.US=3]="US",t[t.OTHER=4]="OTHER"})(wO||(wO={}));const mo=pu("AdMob",{web:()=>km(()=>import("./web-DC96tBjW.js"),[]).then(t=>new t.AdMobWeb)}),a_=rs.isNativePlatform(),dge=rs.getPlatform()==="android";let ir=null,TO=!1,Z0=!1,Fd=!1;async function hge(t){const e=await fetch(`${t}/api/public/ad-config`,{cache:"no-cache"});if(!e.ok)throw new Error(`ad-config HTTP ${e.status}`);return await e.json()}async function r$(t){if(!a_||!dge)return null;if(ir)return ir;try{ir=await hge(t)}catch(e){return console.warn("[AdMob] Could not load /api/public/ad-config:",e),null}if(!ir.enabled)return console.log("[AdMob] Ads disabled in admin panel."),ir;if(!TO)try{await mo.initialize({initializeForTesting:ir.testing}),TO=!0,mo.addListener("onInterstitialAdLoaded",()=>{Fd=!0}),mo.addListener("onInterstitialAdFailedToLoad",e=>{Fd=!1,console.warn("[AdMob] Interstitial failed to load:",e)}),mo.addListener("onInterstitialAdDismissed",()=>{Fd=!1,s$()}),console.log("[AdMob] Initialised (testing =",ir.testing,")")}catch(e){console.warn("[AdMob] initialize() failed:",e)}return ir}async function fge(t){const e=await r$(t);if(!(e!=null&&e.enabled)||!e.banner_id)return;if(Z0){try{await mo.resumeBanner()}catch{}return}const n={adId:e.banner_id,adSize:$w.ADAPTIVE_BANNER,position:Fw.BOTTOM_CENTER,margin:56,isTesting:e.testing};try{await mo.showBanner(n),Z0=!0}catch(r){console.warn("[AdMob] showBanner failed:",r)}}async function pge(){if(!(!a_||!Z0))try{await mo.hideBanner(),Z0=!1}catch(t){console.warn("[AdMob] hideBanner failed:",t)}}async function s$(t){if(a_&&(!ir&&t&&await r$(t),!(!(ir!=null&&ir.enabled)||!ir.interstitial_id)))try{const e={adId:ir.interstitial_id,isTesting:ir.testing};await mo.prepareInterstitial(e)}catch(e){Fd=!1,console.warn("[AdMob] prepareInterstitial failed:",e)}}async function mge(){if(!a_||!(ir!=null&&ir.enabled)||!Fd)return!1;try{return await mo.showInterstitial(),!0}catch(t){return console.warn("[AdMob] showInterstitial failed:",t),Fd=!1,!1}}function gge(){return(ir==null?void 0:ir.interstitial_every)??0}function AO(){return"https://nadiplayer-edit.preview.emergentagent.com"}function i$(t=!0){C.useEffect(()=>{if(t)return fge(AO()),s$(AO()),()=>{pge()}},[t])}function yge(t){const e=C.useRef(0);C.useEffect(()=>{const n=gge();!n||t<=0||t%n===0&&t!==e.current&&(e.current=t,mge())},[t])}const vge=()=>{const{activeProfile:t}=Li(),{t:e}=wr(),{user:n}=ys(),{data:r=[],isLoading:s,error:i}=Z3(t),a=qv(),{isFavorite:o,toggle:l}=HA(t==null?void 0:t.id,"live"),[c,u]=C.useState(""),[d,h]=C.useState("All"),[f,m]=C.useState(null);lge(!!f,{channel:(f==null?void 0:f.name)||(f==null?void 0:f.id),kind:"live"});const[g,y]=C.useState(!1),[v,_]=C.useState("grid"),[S,E]=C.useState(0);i$(!0),yge(S);const L=oF(),U=Cm(),P=uge(),I=(n==null?void 0:n.role)==="user",k=age(),R=!U&&k?"internal":L,M=C.useMemo(()=>["All",...Array.from(new Set(r.map(Q=>Q.category)))],[r]),G=C.useMemo(()=>r.filter(Q=>{const ve=Q.name.toLowerCase().includes(c.toLowerCase()),Te=d==="All"||Q.category===d,Ne=!g||o(Q.id);return ve&&Te&&Ne}),[r,c,d,g,o]),{data:Y=[]}=ase(t,f==null?void 0:f.id),q=Y.find(Q=>Q.nowPlaying)??Y[0],X=async Q=>{let ve=Q;if(ve.streamUrl.startsWith("stalker-cmd:")&&(t==null?void 0:t.kind)==="stalker"){const Te=ve.streamUrl.slice(12),Ne=It.loading(`Resolving ${ve.name}…`);try{const Ke=await zc.resolveStream(t.portalUrl,t.macAddress,Te);It.dismiss(Ne),ve={...ve,streamUrl:Ke}}catch(Ke){It.error(`Could not resolve stream: ${(Ke==null?void 0:Ke.message)||"error"}`,{id:Ne});return}}if(R==="external"){try{if(U){const Te=await ol.openExternal({url:ve.streamUrl,title:ve.name,userAgent:_i(),package:P.androidPackage});Te!=null&&Te.launched?It.success(e("liveTV.openingInApp",{channel:ve.name,app:P.label})):(Te==null?void 0:Te.reason)==="not-installed"&&Te.package?It.error(`${P.label} is not installed`,{action:{label:"Install",onClick:()=>ol.openPlayStore({package:Te.package})},duration:8e3}):It.error(e("liveTV.couldntOpen",{app:P.label}))}else t$(ve.streamUrl,{package:P.androidPackage,title:ve.name,userAgent:_i(),onNotInstalled:Ne=>{if(!Ne){It.error(`No ${P.label} app handled the stream`);return}It.error(`${P.label} is not installed`,{action:{label:"Install",onClick:()=>n$(Ne)},duration:1e4})}})?It.message(e("liveTV.sentToApp",{app:P.label})):It.message(`Tap "Open in ${P.label}" to launch`)}catch(Te){It.error((Te==null?void 0:Te.message)||e("liveTV.couldntOpen",{app:P.label}))}m(ve);return}m(ve),E(Te=>Te+1)},Z=Q=>{const ve=typeof navigator<"u"?navigator.userAgent:"";if(/iPad|iPhone|iPod/.test(ve))return KA(Q);if(!/Android/i.test(ve))return e$(Q)};if(!t)return p.jsx(au,{title:e("liveTV.title"),children:p.jsx("div",{className:"h-full flex items-center justify-center",children:p.jsxs("div",{className:"glass-card rounded-2xl p-6 text-center max-w-sm",children:[p.jsx("p",{className:"text-foreground text-sm mb-3",children:e("liveTV.noActiveServer")}),I?p.jsx("p",{className:"text-muted-foreground text-xs",children:e("liveTV.contactAdmin")}):p.jsx(e1,{to:"/account",className:"text-primary text-xs underline",children:e("liveTV.addProfile")})]})})});const oe=R==="external"?p.jsxs("div",{className:"glass-card rounded-xl px-3 py-1.5 flex items-center gap-1.5",children:[p.jsx(vo,{className:"w-3 h-3 text-primary"}),p.jsx("span",{className:"text-[10px] text-foreground/80",children:P.label})]}):null,ne={contentVisibility:"auto",containIntrinsicSize:"56px"},H={contentVisibility:"auto",containIntrinsicSize:"160px"},K=()=>p.jsx(Ci,{autoFocus:!0,focusKey:"channel-list",className:"space-y-1",children:G.slice(0,300).map(Q=>p.jsxs(Kl,{focusKey:`ch-${Q.id}`,onEnter:()=>X(Q),onClick:()=>X(Q),subtle:!0,style:ne,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:[p.jsx("div",{className:"w-10 h-7 rounded bg-muted/30 flex items-center justify-center shrink-0 overflow-hidden",children:Q.logoUrl?p.jsx("img",{src:Q.logoUrl,alt:"",loading:"lazy",decoding:"async",className:"w-full h-full object-contain",onError:ve=>ve.currentTarget.style.display="none"}):p.jsx(va,{className:"w-3 h-3 text-muted-foreground"})}),p.jsxs("div",{className:"flex-1 min-w-0",children:[p.jsx("p",{className:"text-foreground text-xs font-medium truncate",children:Q.name}),p.jsx("p",{className:"text-muted-foreground text-[10px] truncate",children:Q.category})]}),p.jsx("button",{onClick:ve=>{ve.stopPropagation(),l(Q.id)},children:p.jsx(Gf,{className:`w-4 h-4 ${o(Q.id)?"text-primary fill-primary":"text-muted-foreground"}`})})]},Q.id))}),J=()=>p.jsx(Ci,{autoFocus:!0,focusKey:"channel-grid",className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 2xl:grid-cols-4 gap-2 auto-rows-max",children:G.slice(0,300).map(Q=>p.jsxs(Kl,{focusKey:`ch-grid-${Q.id}`,onEnter:()=>X(Q),onClick:()=>X(Q),style:H,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:[p.jsx("div",{className:"w-14 h-10 rounded bg-muted/30 flex items-center justify-center overflow-hidden",children:Q.logoUrl?p.jsx("img",{src:Q.logoUrl,alt:"",loading:"lazy",decoding:"async",className:"w-full h-full object-contain",onError:ve=>ve.currentTarget.style.display="none"}):p.jsx(va,{className:"w-4 h-4 text-muted-foreground"})}),p.jsx("p",{className:"text-foreground text-[11px] font-medium text-center line-clamp-2",children:Q.name}),p.jsx("button",{onClick:ve=>{ve.stopPropagation(),l(Q.id)},className:"absolute top-1.5 right-1.5",children:p.jsx(Gf,{className:`w-3.5 h-3.5 ${o(Q.id)?"text-primary fill-primary":"text-muted-foreground"}`})})]},Q.id))});return p.jsx(au,{title:e("liveTV.title"),children:p.jsxs("div",{className:"h-full flex flex-col gap-3",children:[p.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[p.jsxs("div",{className:"glass-card rounded-xl px-3 py-2 flex items-center gap-2 flex-1 min-w-[180px]",children:[p.jsx(c1,{className:"w-4 h-4 text-muted-foreground"}),p.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"})]}),p.jsxs("div",{className:"glass-card rounded-xl px-3 py-2 flex items-center gap-2",children:[p.jsx(_m,{className:"w-4 h-4 text-muted-foreground"}),p.jsx("select",{value:d,onChange:Q=>h(Q.target.value),className:"bg-transparent text-foreground text-xs outline-none",children:M.map(Q=>p.jsx("option",{value:Q,className:"bg-background",children:Q==="All"?e("common.all"):Q},Q))})]}),p.jsxs("button",{onClick:()=>y(Q=>!Q),className:`glass-card rounded-xl px-3 py-2 flex items-center gap-1.5 ${g?"border border-primary/40":""}`,title:e("liveTV.favs"),children:[p.jsx(Gf,{className:`w-3.5 h-3.5 ${g?"text-primary fill-primary":"text-muted-foreground"}`}),p.jsx("span",{className:"text-[11px] text-foreground/80",children:e("liveTV.favs")})]}),p.jsxs("div",{className:"glass-card rounded-xl p-0.5 flex items-center",children:[p.jsx("button",{onClick:()=>_("list"),className:`px-2.5 py-1.5 rounded-lg ${v==="list"?"bg-primary/20 text-primary":"text-muted-foreground"}`,title:e("liveTV.listView"),children:p.jsx(o9,{className:"w-3.5 h-3.5"})}),p.jsx("button",{onClick:()=>_("grid"),className:`px-2.5 py-1.5 rounded-lg ${v==="grid"?"bg-primary/20 text-primary":"text-muted-foreground"}`,title:e("liveTV.gridView"),children:p.jsx(t9,{className:"w-3.5 h-3.5"})})]}),p.jsx("button",{onClick:()=>a(t.id),className:"glass-card rounded-xl p-2",title:e("common.refresh"),children:p.jsx(Oh,{className:"w-3.5 h-3.5 text-muted-foreground hover:text-primary"})}),oe]}),R==="external"?p.jsxs("div",{className:"flex-1 flex flex-col gap-2 min-h-0",children:[f&&p.jsxs("div",{className:"glass-card rounded-xl px-3 py-2 flex flex-col sm:flex-row sm:items-center gap-2",children:[p.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[p.jsx("div",{className:"w-9 h-7 rounded bg-muted/30 flex items-center justify-center overflow-hidden",children:f.logoUrl?p.jsx("img",{src:f.logoUrl,alt:"",className:"w-full h-full object-contain"}):p.jsx(va,{className:"w-3 h-3 text-muted-foreground"})}),p.jsxs("div",{className:"flex-1 min-w-0",children:[p.jsx("p",{className:"text-foreground text-xs font-medium truncate",children:f.name}),p.jsx("p",{className:"text-muted-foreground text-[10px] truncate",children:q!=null&&q.title?e("liveTV.nowPrefix",{title:q.title}):f.category})]})]}),(()=>{const Q=Z(f.streamUrl);return Q?p.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:[p.jsx(vo,{className:"w-3.5 h-3.5"}),"Open in ",P.label]}):p.jsxs("button",{onClick:()=>X(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:[p.jsx(vo,{className:"w-3.5 h-3.5"}),"Open in ",P.label]})})()]}),p.jsxs("div",{className:"flex-1 overflow-y-auto overscroll-contain pr-1 -mr-1 touch-pan-y",children:[s&&p.jsx("div",{className:"flex items-center justify-center py-10",children:p.jsx(Pn,{className:"w-5 h-5 text-primary animate-spin"})}),i&&p.jsx("p",{className:"text-destructive text-xs px-2",children:e("liveTV.failedLoad")}),!s&&G.length===0&&p.jsx("p",{className:"text-muted-foreground text-xs text-center py-6",children:e("liveTV.noChannels")}),v==="list"?K():J()]}),f&&Y.length>0&&p.jsxs("div",{className:"glass-card rounded-xl p-2 max-h-36 overflow-y-auto",children:[p.jsx("p",{className:"text-[10px] text-muted-foreground mb-1 px-1",children:e("liveTV.epgFor",{name:f.name})}),Y.slice(0,6).map((Q,ve)=>p.jsxs("div",{className:`flex items-center gap-2 px-2 py-1 rounded-md ${Q.nowPlaying?"bg-primary/10":""}`,children:[p.jsx("span",{className:"text-[10px] text-muted-foreground w-10 shrink-0",children:Q.start?Q.start.slice(11,16):"--:--"}),p.jsx("span",{className:`text-[11px] truncate ${Q.nowPlaying?"text-primary font-medium":"text-foreground/80"}`,children:Q.title||"—"})]},Q.id+ve))]})]}):p.jsxs("div",{className:"flex-1 flex flex-col landscape:max-md:flex-row md:flex-row gap-3 min-h-0",children:[p.jsx("div",{className:"flex-1 md:flex-none landscape:max-md:flex-1 md:w-[340px] lg:w-[380px] xl:w-[440px] 2xl:w-[500px] md:shrink-0 flex flex-col gap-2 min-h-0 min-w-0 order-2 md:order-1 landscape:max-md:order-1",children:p.jsxs("div",{className:"flex-1 overflow-y-auto overscroll-contain pr-1 -mr-1 touch-pan-y",children:[s&&p.jsx("div",{className:"flex items-center justify-center py-8",children:p.jsx(Pn,{className:"w-5 h-5 text-primary animate-spin"})}),i&&p.jsx("p",{className:"text-destructive text-xs px-2",children:e("liveTV.failedLoad")}),!s&&G.length===0&&p.jsx("p",{className:"text-muted-foreground text-xs text-center py-6",children:e("liveTV.noChannels")}),v==="list"?K():J()]})}),p.jsxs("div",{className:`${f?"flex":"hidden md:flex landscape:max-md:flex"} flex-col items-center justify-start gap-2 py-2 md:py-4 min-w-0 min-h-0 shrink-0 md:flex-1 md:shrink landscape:max-md:flex-1 landscape:max-md:shrink order-1 md:order-2 landscape:max-md:order-2`,children:[p.jsx("div",{className:"w-full max-w-[720px] xl:max-w-[960px] 2xl:max-w-[1280px] aspect-video glass-card rounded-2xl overflow-hidden flex items-center justify-center relative mx-auto max-h-[42vh] md:max-h-none landscape:max-md:max-h-none",children:f?k&&!U?(()=>{const Q=G.findIndex(Ne=>Ne.id===f.id),ve=Q>0?G[Q-1]:G.length>1?G[G.length-1]:void 0,Te=Q>=0&&Q<G.length-1?G[Q+1]:G.length>1?G[0]:void 0;return p.jsx(ige,{src:f.streamUrl,poster:f.logoUrl,title:f.name,isLive:!0,canGoPrev:!!ve,canGoNext:!!Te,onPrevChannel:ve?()=>X(ve):void 0,onNextChannel:Te?()=>X(Te):void 0},f.id)})():p.jsx(i_,{src:f.streamUrl,poster:f.logoUrl,title:f.name,isLive:!0}):p.jsxs("div",{className:"text-center",children:[p.jsx(va,{className:"w-12 h-12 text-primary/50 mx-auto mb-2"}),p.jsx("p",{className:"text-muted-foreground text-sm",children:e("liveTV.selectChannel")})]})}),f&&p.jsxs("div",{className:"text-center",children:[p.jsx("p",{className:"text-foreground text-sm font-medium",children:f.name}),p.jsx("p",{className:"text-muted-foreground text-[10px]",children:q!=null&&q.title?e("liveTV.nowPrefix",{title:q.title}):f.category})]})]})]}),p.jsx("div",{className:"text-muted-foreground text-[10px] tabular-nums","data-testid":"livetv-count",children:G.length===r.length?e("liveTV.channels",{count:r.length}):`${G.length} / ${r.length} ${e("liveTV.channels",{count:r.length}).replace(/^\d+\s*/,"")}`})]})})},_ge=()=>{const{activeProfile:t}=Li(),{t:e}=wr(),{user:n}=ys(),{data:r=[],isLoading:s,error:i}=eF(t),a=qv(),{isFavorite:o,toggle:l}=HA(t==null?void 0:t.id,"movie"),[c,u]=C.useState(""),[d,h]=C.useState("All"),[f,m]=C.useState(null);i$(!!f);const g=["All",...Array.from(new Set(r.map(_=>_.category)))],y=r.filter(_=>{const S=_.name.toLowerCase().includes(c.toLowerCase()),E=d==="All"||_.category===d;return S&&E}),v=(n==null?void 0:n.role)==="user";return t?p.jsxs(au,{title:e("movies.title"),children:[p.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[p.jsxs("div",{className:"flex gap-2",children:[p.jsxs("div",{className:"glass-card rounded-xl px-3 py-2 flex items-center gap-2 w-40",children:[p.jsx(_m,{className:"w-4 h-4 text-muted-foreground"}),p.jsx("select",{value:d,onChange:_=>h(_.target.value),className:"bg-transparent text-foreground text-xs outline-none flex-1",children:g.map(_=>p.jsx("option",{value:_,className:"bg-background",children:_==="All"?e("common.all"):_},_))})]}),p.jsxs("div",{className:"glass-card rounded-xl px-3 py-2 flex items-center gap-2 flex-1",children:[p.jsx(c1,{className:"w-4 h-4 text-muted-foreground"}),p.jsx("input",{type:"text",placeholder:e("movies.searchPlaceholder"),value:c,onChange:_=>u(_.target.value),className:"bg-transparent text-foreground placeholder:text-muted-foreground text-xs outline-none flex-1"})]}),p.jsx("button",{onClick:()=>a(t.id),className:"glass-card rounded-xl px-3 py-2",children:p.jsx(Oh,{className:"w-4 h-4 text-muted-foreground"})})]}),s&&p.jsx("div",{className:"flex items-center justify-center py-12",children:p.jsx(Pn,{className:"w-6 h-6 text-primary animate-spin"})}),i&&p.jsx("p",{className:"text-destructive text-xs",children:e("movies.failedLoad")}),p.jsx(Ci,{autoFocus:!0,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 xl:grid-cols-6 2xl:grid-cols-7 gap-3 pb-2 auto-rows-max",children:y.slice(0,300).map(_=>p.jsxs(Kl,{focusKey:`movie-${_.id}`,onEnter:()=>m(_),onClick:()=>m(_),style:{contentVisibility:"auto",containIntrinsicSize:"auto 360px"},className:"glass-card rounded-xl overflow-hidden cursor-pointer group hover:border-primary/30 transition-all border-transparent flex flex-col",children:[p.jsxs("div",{className:"aspect-[2/3] w-full bg-muted/20 flex items-center justify-center relative overflow-hidden",children:[_.posterUrl?p.jsx("img",{src:_.posterUrl,alt:_.name,loading:"lazy",decoding:"async",className:"w-full h-full object-cover",onError:S=>S.currentTarget.style.display="none"}):p.jsx(va,{className:"w-8 h-8 text-muted-foreground/30 group-hover:text-primary/60 transition-colors"}),p.jsx("button",{onClick:S=>{S.stopPropagation(),l(_.id)},className:"absolute top-2 right-2 z-10",children:p.jsx(Gf,{className:`w-4 h-4 ${o(_.id)?"text-primary fill-primary":"text-muted-foreground/80"}`})}),_.rating&&p.jsxs("span",{className:"absolute top-2 left-2 text-[10px] bg-primary/80 text-primary-foreground px-1.5 py-0.5 rounded",children:["★ ",_.rating]})]}),p.jsxs("div",{className:"p-2.5",children:[p.jsx("p",{className:"text-foreground text-xs font-medium truncate",children:_.name}),p.jsxs("div",{className:"flex items-center justify-between mt-1",children:[p.jsx("span",{className:"text-muted-foreground text-[10px] truncate",children:_.category}),_.year&&p.jsx("span",{className:"text-muted-foreground text-[10px]",children:_.year})]})]})]},_.id))}),!s&&!i&&p.jsx("div",{className:"flex justify-center items-center py-1.5 text-[11px] text-muted-foreground tabular-nums","data-testid":"movies-count",children:y.length===r.length?`${r.length} movies`:`${y.length} / ${r.length} movies`})]}),p.jsx(Lo,{children:f&&p.jsx(gt.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:p.jsxs(gt.div,{initial:{scale:.95},animate:{scale:1},exit:{scale:.95},className:"relative w-full max-w-4xl glass-card rounded-2xl overflow-hidden",children:[p.jsx("button",{onClick:()=>m(null),className:"absolute top-3 right-3 z-10 w-8 h-8 rounded-full glass flex items-center justify-center",children:p.jsx(Na,{className:"w-4 h-4 text-foreground"})}),p.jsx("div",{className:"aspect-video bg-black",children:p.jsx(i_,{src:f.streamUrl,poster:f.posterUrl})}),p.jsxs("div",{className:"p-4",children:[p.jsx("p",{className:"text-foreground text-sm font-medium",children:f.name}),p.jsxs("p",{className:"text-muted-foreground text-xs",children:[f.category," ",f.year&&`• ${f.year}`]})]})]})})})]}):p.jsx(au,{title:e("movies.title"),children:p.jsx("div",{className:"h-full flex items-center justify-center",children:p.jsxs("div",{className:"glass-card rounded-2xl p-6 text-center max-w-sm",children:[p.jsx("p",{className:"text-foreground text-sm mb-3",children:e("movies.noActiveServer")}),v?p.jsx("p",{className:"text-muted-foreground text-xs",children:e("movies.contactAdmin")}):p.jsx(e1,{to:"/account",className:"text-primary text-xs underline",children:e("movies.addProfile")})]})})})},bge=()=>{var U;const{activeProfile:t}=Li(),{t:e}=wr(),{user:n}=ys(),{data:r=[],isLoading:s,error:i}=tF(t),a=qv(),{isFavorite:o,toggle:l}=HA(t==null?void 0:t.id,"series"),[c,u]=C.useState(""),[d,h]=C.useState("All"),[f,m]=C.useState(null),[g,y]=C.useState(null),v=["All",...Array.from(new Set(r.map(P=>P.category)))],_=r.filter(P=>{const I=P.name.toLowerCase().includes(c.toLowerCase()),k=d==="All"||P.category===d;return I&&k}),S=kh({queryKey:["xtream",t==null?void 0:t.id,"series-info",f==null?void 0:f.id],queryFn:()=>fs.getSeriesInfo(t,f.id),enabled:!!f&&!!t}),E=(n==null?void 0:n.role)==="user";if(!t)return p.jsx(au,{title:e("series.title"),children:p.jsx("div",{className:"h-full flex items-center justify-center",children:p.jsxs("div",{className:"glass-card rounded-2xl p-6 text-center max-w-sm",children:[p.jsx("p",{className:"text-foreground text-sm mb-3",children:e("series.noActiveServer")}),E?p.jsx("p",{className:"text-muted-foreground text-xs",children:e("series.contactAdmin")}):p.jsx(e1,{to:"/account",className:"text-primary text-xs underline",children:e("series.addProfile")})]})})});const L=((U=S.data)==null?void 0:U.episodes)??{};return p.jsxs(au,{title:e("series.title"),children:[p.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[p.jsxs("div",{className:"flex gap-2",children:[p.jsxs("div",{className:"glass-card rounded-xl px-3 py-2 flex items-center gap-2 w-40",children:[p.jsx(_m,{className:"w-4 h-4 text-muted-foreground"}),p.jsx("select",{value:d,onChange:P=>h(P.target.value),className:"bg-transparent text-foreground text-xs outline-none flex-1",children:v.map(P=>p.jsx("option",{value:P,className:"bg-background",children:P==="All"?e("common.all"):P},P))})]}),p.jsxs("div",{className:"glass-card rounded-xl px-3 py-2 flex items-center gap-2 flex-1",children:[p.jsx(c1,{className:"w-4 h-4 text-muted-foreground"}),p.jsx("input",{type:"text",placeholder:e("series.searchPlaceholder"),value:c,onChange:P=>u(P.target.value),className:"bg-transparent text-foreground placeholder:text-muted-foreground text-xs outline-none flex-1"})]}),p.jsx("button",{onClick:()=>a(t.id),className:"glass-card rounded-xl px-3 py-2",children:p.jsx(Oh,{className:"w-4 h-4 text-muted-foreground"})})]}),s&&p.jsx("div",{className:"flex items-center justify-center py-12",children:p.jsx(Pn,{className:"w-6 h-6 text-primary animate-spin"})}),i&&p.jsx("p",{className:"text-destructive text-xs",children:e("series.failedLoad")}),p.jsx(Ci,{autoFocus:!0,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 xl:grid-cols-6 2xl:grid-cols-7 gap-3 pb-2 auto-rows-max",children:_.slice(0,300).map(P=>p.jsxs(Kl,{focusKey:`series-${P.id}`,onEnter:()=>m(P),onClick:()=>m(P),style:{contentVisibility:"auto",containIntrinsicSize:"auto 360px"},className:"glass-card rounded-xl overflow-hidden cursor-pointer group hover:border-primary/30 transition-all border-transparent flex flex-col",children:[p.jsxs("div",{className:"aspect-[2/3] w-full bg-muted/20 flex items-center justify-center relative overflow-hidden",children:[P.posterUrl?p.jsx("img",{src:P.posterUrl,alt:P.name,loading:"lazy",decoding:"async",className:"w-full h-full object-cover",onError:I=>I.currentTarget.style.display="none"}):p.jsx(Dh,{className:"w-8 h-8 text-muted-foreground/30 group-hover:text-primary/60 transition-colors"}),p.jsx("button",{onClick:I=>{I.stopPropagation(),l(P.id)},className:"absolute top-2 right-2 z-10",children:p.jsx(Gf,{className:`w-4 h-4 ${o(P.id)?"text-primary fill-primary":"text-muted-foreground/80"}`})}),P.rating&&p.jsxs("span",{className:"absolute top-2 left-2 text-[10px] bg-primary/80 text-primary-foreground px-1.5 py-0.5 rounded",children:["★ ",P.rating]})]}),p.jsxs("div",{className:"p-2.5",children:[p.jsx("p",{className:"text-foreground text-xs font-medium truncate",children:P.name}),p.jsx("span",{className:"text-muted-foreground text-[10px] truncate block",children:P.category})]})]},P.id))}),!s&&!i&&p.jsx("div",{className:"flex justify-center items-center py-1.5 text-[11px] text-muted-foreground tabular-nums","data-testid":"series-count",children:_.length===r.length?`${r.length} series`:`${_.length} / ${r.length} series`})]}),p.jsx(Lo,{children:f&&p.jsx(gt.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:()=>{m(null),y(null)},children:p.jsxs(gt.div,{initial:{scale:.95},animate:{scale:1},exit:{scale:.95},onClick:P=>P.stopPropagation(),className:"relative w-full max-w-4xl max-h-[90vh] glass-card rounded-2xl overflow-hidden flex flex-col",children:[p.jsx("button",{onClick:()=>{m(null),y(null)},className:"absolute top-3 right-3 z-10 w-8 h-8 rounded-full glass flex items-center justify-center",children:p.jsx(Na,{className:"w-4 h-4 text-foreground"})}),g?p.jsx("div",{className:"aspect-video bg-black",children:p.jsx(i_,{src:g})}):p.jsxs("div",{className:"p-5 flex gap-4 border-b border-border",children:[f.posterUrl&&p.jsx("img",{src:f.posterUrl,alt:"",className:"w-24 h-36 object-cover rounded-lg"}),p.jsxs("div",{children:[p.jsx("h2",{className:"text-foreground text-lg font-medium",children:f.name}),p.jsx("p",{className:"text-muted-foreground text-xs mb-1",children:f.category}),f.rating&&p.jsxs("p",{className:"text-primary text-xs",children:["★ ",f.rating]}),f.plot&&p.jsx("p",{className:"text-muted-foreground text-xs mt-2 line-clamp-3",children:f.plot})]})]}),p.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[S.isLoading&&p.jsx("div",{className:"flex justify-center py-6",children:p.jsx(u9,{className:"w-5 h-5 animate-spin text-primary"})}),Object.entries(L).map(([P,I])=>p.jsxs(Ci,{focusKey:`season-${P}`,children:[p.jsx("h3",{className:"text-foreground text-sm font-medium mb-2",children:e("series.season",{n:P})}),p.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:I.map(k=>p.jsxs(wi,{focusKey:`ep-${k.id}`,onEnter:()=>y(fs.buildSeriesEpisodeUrl(t,k.id,k.container_extension||"mp4")),onClick:()=>y(fs.buildSeriesEpisodeUrl(t,k.id,k.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:[p.jsx(va,{className:"w-3 h-3 text-primary shrink-0"}),p.jsxs("span",{className:"text-foreground text-xs truncate",children:[e("series.episodePrefix",{n:k.episode_num}),": ",k.title]})]},k.id))})]},P))]})]})})})]})},xge=5*60*1e3,a$="nadi_update_snoozed_for";function o$(){const[t,e]=C.useState(null),[n,r]=C.useState(!0),[s,i]=C.useState(qc);C.useEffect(()=>{let u=!1;return m5().then(d=>{u||i(d)}),()=>{u=!0}},[]),C.useEffect(()=>{let u=!1;const d=async()=>{var f;try{const m=await g5();u||e(m);try{const g=(f=m==null?void 0:m.flags)==null?void 0:f.player_notice_enabled;typeof g=="boolean"&&localStorage.setItem("nadiplay.playerNotice.enabledCache.v1",g?"1":"0")}catch{}}catch{}finally{u||r(!1)}};d();const h=setInterval(d,xge);return()=>{u=!0,clearInterval(h)}},[]);const a=t==null?void 0:t.update,o=!!(a!=null&&a.enabled),l=o&&!!(a!=null&&a.latest_version)&&bw(a.latest_version,s)>0,c=o&&!!(a!=null&&a.min_supported_version)&&bw(s,a.min_supported_version)<0;return{loading:n,info:t,installedVersion:s,hasUpdate:l,forced:c}}function Sge(t){try{sessionStorage.setItem(a$,t||"")}catch{}}function Ege(t){try{return sessionStorage.getItem(a$)===(t||"")}catch{return!1}}const wge=()=>{const t=lr(),{hasUpdate:e,info:n}=o$(),[r,s]=C.useState(n);C.useEffect(()=>{if(n){s(n);return}let u=!1;return g5().then(d=>{u||s(d)}).catch(()=>{}),()=>{u=!0}},[n]);const i=r==null?void 0:r.creator,a=r==null?void 0:r.support,o=r==null?void 0:r.update,l=a?xue(a.whatsapp_number,a.whatsapp_message):null,c=(o==null?void 0:o.apk_url)||(o==null?void 0:o.play_url)||"";return p.jsxs("div",{className:"glass-card rounded-2xl p-4 space-y-4","data-testid":"account-help-about-card",children:[p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx(Jz,{className:"w-4 h-4 text-primary"}),p.jsx("p",{className:"text-foreground text-sm font-medium",children:"Help & About"})]}),p.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-border/60 bg-background/30 p-3",children:[p.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:p.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"})}),p.jsxs("div",{className:"min-w-0 flex-1",children:[p.jsx("p",{className:"truncate text-sm font-semibold text-foreground",children:"Nadiplayer"}),p.jsxs("p",{className:"text-[11px] text-muted-foreground","data-testid":"account-app-version",children:["Version v",qc,(o==null?void 0:o.latest_version)&&o.latest_version!==qc&&p.jsxs("span",{className:"ml-1 text-muted-foreground/70",children:["(latest v",o.latest_version,")"]})]})]}),e&&p.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:[p.jsx(kv,{className:"h-3 w-3"}),"Update"]})]}),c&&p.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:[p.jsx(o1,{className:"h-3.5 w-3.5"}),e?"Download latest version":"Check downloads"]}),((i==null?void 0:i.name)||(i==null?void 0:i.bio)||(i==null?void 0:i.role))&&p.jsxs("div",{className:"rounded-xl border border-border/60 bg-background/30 p-3","data-testid":"account-creator-card",children:[p.jsx("p",{className:"mb-2 text-[10px] font-medium uppercase tracking-[0.2em] text-muted-foreground",children:"Created by"}),p.jsxs("div",{className:"flex items-start gap-3",children:[p.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:i.avatar_url?p.jsx("img",{src:i.avatar_url,alt:i.name,className:"h-10 w-10 object-cover",onError:u=>{u.currentTarget.style.display="none"}}):p.jsx(Ji,{className:"h-5 w-5 text-primary"})}),p.jsxs("div",{className:"min-w-0 flex-1",children:[i.name&&p.jsx("p",{className:"truncate text-sm font-medium text-foreground","data-testid":"account-creator-name",children:i.name}),i.role&&p.jsx("p",{className:"truncate text-[11px] text-primary/80",children:i.role}),i.bio&&p.jsx("p",{className:"mt-1 whitespace-pre-wrap text-[11px] leading-relaxed text-muted-foreground",children:i.bio})]})]})]}),p.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[p.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:[p.jsx(Ul,{className:"h-3.5 w-3.5 text-primary"}),p.jsx("span",{children:"Privacy Policy"}),p.jsx(vo,{className:"ml-auto h-3 w-3 text-muted-foreground"})]}),(a==null?void 0:a.email)&&p.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:[p.jsx(y9,{className:"h-3.5 w-3.5 text-primary"}),p.jsx("span",{className:"truncate",children:a.email})]})]}),l&&p.jsx(gt.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:p.jsx(Mj,{className:"h-5 w-5"})})]})},Fx="https://nadiplayer-edit.preview.emergentagent.com";function Tge(){const[t,e]=C.useState(null),[n,r]=C.useState(!1),[s,i]=C.useState(""),[a,o]=C.useState(!1),[l,c]=C.useState(!1),{profiles:u,removeProfile:d}=Li();C.useEffect(()=>{try{const m=localStorage.getItem("nadiplay_device");if(!m)return;const g=JSON.parse(m);g&&g.device_id&&e(g)}catch(m){console.warn("[DeviceStatusCard] parse failed",m)}},[]);const h=C.useCallback(async m=>{try{const g=await fetch(`${Fx}/api/device/status/${m}`);if(!g.ok)return;const y=await g.json();r(!!y.paired),i(y.profile_name||"")}catch{}},[]);C.useEffect(()=>{if(!t)return;let m=!1;const g=async()=>{m||await h(t.device_id)};g();const y=setInterval(g,8e3);return()=>{m=!0,clearInterval(y)}},[t,h]);const f=C.useCallback(async()=>{if(t&&confirm(`Unpair this device?

Your IPTV profile will be removed from this device and the PIN will be reset. You'll need to pair again from the web portal.`)){c(!0);try{const m=await fetch(`${Fx}/api/device/unpair/${t.device_id}`,{method:"DELETE"});if(!m.ok)throw new Error(`Unpair failed (${m.status})`);const g=await m.json().catch(()=>({}));try{const v=await fetch(`${Fx}/api/device/config/${t.device_id}`);if(v.ok){const _=await v.json(),S=u.find(E=>E.kind==="xtream"&&E.serverUrl===_.server_url&&E.username===_.username);S&&d(S.id)}}catch{}const y={...t,pin:g.new_pin||t.pin};localStorage.setItem("nadiplay_device",JSON.stringify(y)),e(y),r(!1),i(""),It.success("Device unpaired. A new PIN is ready in the activation screen.")}catch(m){It.error((m==null?void 0:m.message)||"Unpair failed")}finally{c(!1)}}},[t,u,d]);return t?p.jsxs("div",{className:"mt-3 pt-3 border-t border-border/40 space-y-2","data-testid":"device-status-card",children:[p.jsxs("div",{className:"flex items-center justify-between gap-2",children:[p.jsxs("div",{className:"flex items-center gap-2",children:[n?p.jsx(a1,{className:"w-3.5 h-3.5 text-primary"}):p.jsx(kz,{className:"w-3.5 h-3.5 text-muted-foreground"}),p.jsx("span",{className:"text-[11px] text-foreground",children:n?"Paired":"Not paired"}),n&&s?p.jsxs("span",{className:"text-[10px] text-muted-foreground truncate max-w-[40%]",children:["· ",s]}):null]}),n&&p.jsxs("button",{onClick:f,disabled:l,className:"text-[11px] px-3 py-1.5 rounded-lg glass hover:border-destructive/40 text-destructive flex items-center gap-1.5 transition-all disabled:opacity-50","data-testid":"unpair-device-btn",children:[l?p.jsx(Pn,{className:"w-3 h-3 animate-spin"}):p.jsx(G9,{className:"w-3 h-3"}),"Unpair this device"]})]}),p.jsxs("div",{className:"grid grid-cols-2 gap-2 text-[10px]",children:[p.jsxs("div",{className:"glass rounded-lg px-2.5 py-1.5",children:[p.jsx("p",{className:"text-muted-foreground",children:"MAC Address"}),p.jsx("p",{className:"font-mono text-foreground/90 truncate","data-testid":"device-mac",children:t.mac_address||"—"})]}),p.jsxs("div",{className:"glass rounded-lg px-2.5 py-1.5",children:[p.jsx("p",{className:"text-muted-foreground",children:"Device ID"}),p.jsx("p",{className:"font-mono text-foreground/90 truncate","data-testid":"device-id",children:t.device_id})]})]})]}):null}const Age=()=>{const{profiles:t}=Li(),e=tA(),n=e?t.find(l=>l.id===e)??null:null,r=Z3(n),s=eF(n),i=tF(n),[a,o]=C.useState(zI);return C.useEffect(()=>{const l=()=>o(zI());return window.addEventListener("nadiplay-managed-counts-changed",l),window.addEventListener("storage",l),()=>{window.removeEventListener("nadiplay-managed-counts-changed",l),window.removeEventListener("storage",l)}},[]),C.useEffect(()=>{var d,h,f;if(!n)return;const l=(d=r.data)==null?void 0:d.length,c=(h=s.data)==null?void 0:h.length,u=(f=i.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||(rF({channels:l,movies:c,series:u}),o({channels:l,movies:c,series:u,updatedAt:Date.now()}))},[n,r.data,s.data,i.data,a]),e?a:null},Rge=()=>{const{t}=wr(),{profiles:e,activeProfileId:n,setActiveProfileId:r,updateProfile:s,removeProfile:i}=Li(),a=qv(),o=vA(),l=tA(),c=Age(),[u,d]=C.useState(!1),[h,f]=C.useState(null),[m,g]=C.useState({}),[y,v]=C.useState(null),[_,S]=C.useState(_i()),E=lr(),L=R=>{f(R.id),g({name:R.name,serverUrl:R.serverUrl,username:R.username,password:R.password})},U=R=>{s(R,m),f(null),It.success(t("account.profileUpdated"))},P=R=>{a(R),It.success(t("account.playlistReloaded"))},I=async R=>{v(R.id);try{await fs.authenticate(R),It.success(t("account.connectedSuccess",{name:R.name}))}catch(M){It.error(t("account.connectFailed",{name:R.name,error:(M==null?void 0:M.message)??"Failed to connect"}))}finally{v(null)}},k=R=>{confirm(t("account.confirmDelete"))&&(i(R),It.success(t("account.profileRemoved")))};return p.jsxs(au,{title:t("account.title"),children:[p.jsxs("div",{className:"h-full flex flex-col gap-3 max-w-2xl mx-auto w-full",children:[p.jsxs("div",{className:"flex items-center justify-between",children:[p.jsx("p",{className:"text-muted-foreground text-xs",children:t("account.profilesCount",{count:e.length})}),p.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:[p.jsx(_o,{className:"w-4 h-4 text-primary"}),p.jsx("span",{className:"text-foreground text-xs font-medium",children:t("account.addServer")})]})]}),p.jsxs("div",{className:"flex-1 overflow-y-auto space-y-3 pr-1",children:[p.jsxs("div",{className:"glass-card rounded-2xl p-4","data-testid":"device-pairing-section",children:[p.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[p.jsx(wp,{className:"w-4 h-4 text-primary"}),p.jsx("p",{className:"text-foreground text-sm font-medium",children:t("account.devicePairing")})]}),p.jsx("p",{className:"text-muted-foreground text-[11px] mb-3",children:t("account.devicePairingDesc")}),p.jsxs("div",{className:"flex gap-2",children:[p.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:[p.jsx(hE,{className:"w-3.5 h-3.5"})," ",t("account.imOnDevice")]}),p.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:[p.jsx(wp,{className:"w-3.5 h-3.5"})," ",t("account.iHavePin")]})]}),p.jsx(Tge,{})]}),p.jsx(wge,{}),p.jsxs("div",{className:"glass-card rounded-2xl p-4",children:[p.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[p.jsx(hE,{className:"w-4 h-4 text-primary"}),p.jsx("p",{className:"text-foreground text-sm font-medium",children:t("account.playerIdentity")})]}),p.jsx("p",{className:"text-muted-foreground text-[11px] mb-3",children:t("account.playerIdentityDesc")}),p.jsx("div",{className:"flex flex-wrap gap-2",children:q3.map(R=>{const M=_===R.value;return p.jsx("button",{onClick:()=>{Yre(R.value),S(R.value),It.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)})}),p.jsxs("p",{className:"text-muted-foreground text-[10px] mt-2 truncate",children:[t("account.sending"),": ",p.jsx("span",{className:"text-foreground/70",children:_})]})]}),e.length===0&&p.jsxs("div",{className:"glass-card rounded-2xl p-8 text-center",children:[p.jsx(Gc,{className:"w-10 h-10 text-muted-foreground/40 mx-auto mb-3"}),p.jsx("p",{className:"text-foreground text-sm mb-1",children:t("account.noProfiles")}),p.jsx("p",{className:"text-muted-foreground text-xs",children:t("account.noProfilesDesc")})]}),e.map(R=>{const M=R.id===n,G=h===R.id,Y=!!l&&R.id===l;return p.jsxs(gt.div,{layout:!0,"data-testid":Y?"managed-profile-card":"user-profile-card",className:`glass-card rounded-2xl p-4 border ${M?"border-primary/40":"border-transparent"}`,children:[p.jsxs("div",{className:"flex items-start gap-3",children:[p.jsx("div",{className:`w-10 h-10 rounded-full glass flex items-center justify-center shrink-0 ${M?"border border-primary":""}`,children:Y?p.jsx(Ul,{className:`w-5 h-5 ${M?"text-primary":"text-muted-foreground"}`}):p.jsx(Ji,{className:`w-5 h-5 ${M?"text-primary":"text-muted-foreground"}`})}),p.jsx("div",{className:"flex-1 min-w-0 space-y-2",children:G&&!Y?p.jsx(p.Fragment,{children:[{key:"name",label:"profileName"},{key:"serverUrl",label:"serverUrl"},{key:"username",label:"username"},{key:"password",label:"password"}].map(({key:q,label:X})=>p.jsx("input",{value:m[q]??"",onChange:Z=>g({...m,[q]:Z.target.value}),placeholder:t(X==="profileName"?"account.profileName":X==="serverUrl"?"account.serverUrl":X==="username"?"common.username":"common.password"),className:"w-full glass-input rounded-lg px-3 py-2 text-foreground text-xs outline-none"},q))}):Y?p.jsxs(p.Fragment,{children:[p.jsx("p",{className:"text-foreground text-sm font-medium truncate",children:R.name}),p.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-primary",children:[p.jsx(Ul,{className:"w-3 h-3"}),p.jsx("span",{children:"Managed by admin"})]}),p.jsxs("div",{className:"flex flex-wrap gap-3 pt-1","data-testid":"managed-counts",children:[p.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-foreground/80",children:[p.jsx(ri,{className:"w-3 h-3 text-primary"}),p.jsx("span",{className:"tabular-nums",children:(c==null?void 0:c.channels)??"—"}),p.jsx("span",{className:"text-muted-foreground",children:"TV"})]}),p.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-foreground/80",children:[p.jsx(bm,{className:"w-3 h-3 text-primary"}),p.jsx("span",{className:"tabular-nums",children:(c==null?void 0:c.movies)??"—"}),p.jsx("span",{className:"text-muted-foreground",children:"Movies"})]}),p.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-foreground/80",children:[p.jsx(Dh,{className:"w-3 h-3 text-primary"}),p.jsx("span",{className:"tabular-nums",children:(c==null?void 0:c.series)??"—"}),p.jsx("span",{className:"text-muted-foreground",children:"Series"})]})]})]}):p.jsxs(p.Fragment,{children:[p.jsx("p",{className:"text-foreground text-sm font-medium truncate",children:R.name}),p.jsx("p",{className:"text-muted-foreground text-xs truncate",children:R.serverUrl}),p.jsxs("p",{className:"text-muted-foreground text-[10px] truncate",children:[t("account.user"),": ",R.username]})]})}),!Y&&p.jsx("div",{className:"flex flex-col gap-1.5 shrink-0",children:G?p.jsxs(p.Fragment,{children:[p.jsx("button",{onClick:()=>U(R.id),className:"w-8 h-8 rounded-lg glass flex items-center justify-center hover:border-primary/40",children:p.jsx(qi,{className:"w-4 h-4 text-primary"})}),p.jsx("button",{onClick:()=>f(null),className:"w-8 h-8 rounded-lg glass flex items-center justify-center",children:p.jsx(Na,{className:"w-4 h-4 text-muted-foreground"})})]}):p.jsxs(p.Fragment,{children:[p.jsx("button",{onClick:()=>L(R),className:"w-8 h-8 rounded-lg glass flex items-center justify-center hover:border-primary/40",children:p.jsx(T9,{className:"w-3.5 h-3.5 text-muted-foreground"})}),p.jsx("button",{onClick:()=>k(R.id),className:"w-8 h-8 rounded-lg glass flex items-center justify-center hover:border-destructive/40",children:p.jsx(xm,{className:"w-3.5 h-3.5 text-destructive"})})]})})]}),!G&&p.jsxs("div",{className:"flex flex-wrap gap-2 mt-3 pt-3 border-t border-border/40",children:[p.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")}),!Y&&p.jsxs("button",{onClick:()=>I(R),disabled:y===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===R.id?p.jsx(Pn,{className:"w-3 h-3 animate-spin"}):null," ",t("common.test")]}),p.jsxs("button",{onClick:()=>P(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:[p.jsx(Oh,{className:"w-3 h-3"})," ",t("account.reloadPlaylist")]})]})]},R.id)})]})]}),p.jsx(y5,{open:u,onClose:()=>d(!1),onSubmit:async R=>{await o(R)&&d(!1)}})]})};var Cge=Object.defineProperty,ev=Object.getOwnPropertySymbols,l$=Object.prototype.hasOwnProperty,c$=Object.prototype.propertyIsEnumerable,RO=(t,e,n)=>e in t?Cge(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Vw=(t,e)=>{for(var n in e||(e={}))l$.call(e,n)&&RO(t,n,e[n]);if(ev)for(var n of ev(e))c$.call(e,n)&&RO(t,n,e[n]);return t},Gw=(t,e)=>{var n={};for(var r in t)l$.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&ev)for(var r of ev(t))e.indexOf(r)<0&&c$.call(t,r)&&(n[r]=t[r]);return n};/**
 * @license QR Code generator library (TypeScript)
 * Copyright (c) Project Nayuki.
 * SPDX-License-Identifier: MIT
 */var lu;(t=>{const e=class qt{constructor(l,c,u,d){if(this.version=l,this.errorCorrectionLevel=c,this.modules=[],this.isFunction=[],l<qt.MIN_VERSION||l>qt.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 m=0;m<this.size;m++)h.push(!1);for(let m=0;m<this.size;m++)this.modules.push(h.slice()),this.isFunction.push(h.slice());this.drawFunctionPatterns();const f=this.addEccAndInterleave(u);if(this.drawCodewords(f),d==-1){let m=1e9;for(let g=0;g<8;g++){this.applyMask(g),this.drawFormatBits(g);const y=this.getPenaltyScore();y<m&&(d=g,m=y),this.applyMask(g)}}s(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 qt.encodeSegments(u,c)}static encodeBinary(l,c){const u=t.QrSegment.makeBytes(l);return qt.encodeSegments([u],c)}static encodeSegments(l,c,u=1,d=40,h=-1,f=!0){if(!(qt.MIN_VERSION<=u&&u<=d&&d<=qt.MAX_VERSION)||h<-1||h>7)throw new RangeError("Invalid value");let m,g;for(m=u;;m++){const S=qt.getNumDataCodewords(m,c)*8,E=a.getTotalBits(l,m);if(E<=S){g=E;break}if(m>=d)throw new RangeError("Data too long")}for(const S of[qt.Ecc.MEDIUM,qt.Ecc.QUARTILE,qt.Ecc.HIGH])f&&g<=qt.getNumDataCodewords(m,S)*8&&(c=S);let y=[];for(const S of l){n(S.mode.modeBits,4,y),n(S.numChars,S.mode.numCharCountBits(m),y);for(const E of S.getData())y.push(E)}s(y.length==g);const v=qt.getNumDataCodewords(m,c)*8;s(y.length<=v),n(0,Math.min(4,v-y.length),y),n(0,(8-y.length%8)%8,y),s(y.length%8==0);for(let S=236;y.length<v;S^=253)n(S,8,y);let _=[];for(;_.length*8<y.length;)_.push(0);return y.forEach((S,E)=>_[E>>>3]|=S<<7-(E&7)),new qt(m,c,_,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;s(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;s(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,m=c+u;0<=f&&f<this.size&&0<=m&&m<this.size&&this.setFunctionModule(f,m,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!=qt.getNumDataCodewords(c,u))throw new RangeError("Invalid argument");const d=qt.NUM_ERROR_CORRECTION_BLOCKS[u.ordinal][c],h=qt.ECC_CODEWORDS_PER_BLOCK[u.ordinal][c],f=Math.floor(qt.getNumRawDataModules(c)/8),m=d-f%d,g=Math.floor(f/d);let y=[];const v=qt.reedSolomonComputeDivisor(h);for(let S=0,E=0;S<d;S++){let L=l.slice(E,E+g-h+(S<m?0:1));E+=L.length;const U=qt.reedSolomonComputeRemainder(L,v);S<m&&L.push(0),y.push(L.concat(U))}let _=[];for(let S=0;S<y[0].length;S++)y.forEach((E,L)=>{(S!=g-h||L>=m)&&_.push(E[S])});return s(_.length==f),_}drawCodewords(l){if(l.length!=Math.floor(qt.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,g=(u+1&2)==0?this.size-1-d:d;!this.isFunction[g][f]&&c<l.length*8&&(this.modules[g][f]=r(l[c>>>3],7-(c&7)),c++)}}s(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,m=0,g=[0,0,0,0,0,0,0];for(let y=0;y<this.size;y++)this.modules[h][y]==f?(m++,m==5?l+=qt.PENALTY_N1:m>5&&l++):(this.finderPenaltyAddHistory(m,g),f||(l+=this.finderPenaltyCountPatterns(g)*qt.PENALTY_N3),f=this.modules[h][y],m=1);l+=this.finderPenaltyTerminateAndCount(f,m,g)*qt.PENALTY_N3}for(let h=0;h<this.size;h++){let f=!1,m=0,g=[0,0,0,0,0,0,0];for(let y=0;y<this.size;y++)this.modules[y][h]==f?(m++,m==5?l+=qt.PENALTY_N1:m>5&&l++):(this.finderPenaltyAddHistory(m,g),f||(l+=this.finderPenaltyCountPatterns(g)*qt.PENALTY_N3),f=this.modules[y][h],m=1);l+=this.finderPenaltyTerminateAndCount(f,m,g)*qt.PENALTY_N3}for(let h=0;h<this.size-1;h++)for(let f=0;f<this.size-1;f++){const m=this.modules[h][f];m==this.modules[h][f+1]&&m==this.modules[h+1][f]&&m==this.modules[h+1][f+1]&&(l+=qt.PENALTY_N2)}let c=0;for(const h of this.modules)c=h.reduce((f,m)=>f+(m?1:0),c);const u=this.size*this.size,d=Math.ceil(Math.abs(c*20-u*10)/u)-1;return s(0<=d&&d<=9),l+=d*qt.PENALTY_N4,s(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<qt.MIN_VERSION||l>qt.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 s(208<=c&&c<=29648),c}static getNumDataCodewords(l,c){return Math.floor(qt.getNumRawDataModules(l)/8)-qt.ECC_CODEWORDS_PER_BLOCK[c.ordinal][l]*qt.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]=qt.reedSolomonMultiply(c[h],u),h+1<c.length&&(c[h]^=c[h+1]);u=qt.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,m)=>u[m]^=qt.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 s(u>>>8==0),u}finderPenaltyCountPatterns(l){const c=l[1];s(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 s(o){if(!o)throw new Error("Assertion error")}const i=class qn{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 qn(qn.Mode.BYTE,l.length,c)}static makeNumeric(l){if(!qn.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 qn(qn.Mode.NUMERIC,l.length,c)}static makeAlphanumeric(l){if(!qn.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=qn.ALPHANUMERIC_CHARSET.indexOf(l.charAt(u))*45;d+=qn.ALPHANUMERIC_CHARSET.indexOf(l.charAt(u+1)),n(d,11,c)}return u<l.length&&n(qn.ALPHANUMERIC_CHARSET.indexOf(l.charAt(u)),6,c),new qn(qn.Mode.ALPHANUMERIC,l.length,c)}static makeSegments(l){return l==""?[]:qn.isNumeric(l)?[qn.makeNumeric(l)]:qn.isAlphanumeric(l)?[qn.makeAlphanumeric(l)]:[qn.makeBytes(qn.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 qn(qn.Mode.ECI,0,c)}static isNumeric(l){return qn.NUMERIC_REGEX.test(l)}static isAlphanumeric(l){return qn.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}};i.NUMERIC_REGEX=/^[0-9]*$/,i.ALPHANUMERIC_REGEX=/^[A-Z0-9 $%*+.\/:-]*$/,i.ALPHANUMERIC_CHARSET="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";let a=i;t.QrSegment=i})(lu||(lu={}));(t=>{(e=>{const n=class{constructor(s,i){this.ordinal=s,this.formatBits=i}};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={}))})(lu||(lu={}));(t=>{(e=>{const n=class{constructor(s,i){this.modeBits=s,this.numBitsCharCount=i}numCharCountBits(s){return this.numBitsCharCount[Math.floor((s+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={}))})(lu||(lu={}));var xd=lu;/**
 * @license qrcode.react
 * Copyright (c) Paul O'Shannessy
 * SPDX-License-Identifier: ISC
 */var kge={L:xd.QrCode.Ecc.LOW,M:xd.QrCode.Ecc.MEDIUM,Q:xd.QrCode.Ecc.QUARTILE,H:xd.QrCode.Ecc.HIGH},u$=128,d$="L",h$="#FFFFFF",f$="#000000",p$=!1,m$=1,Lge=4,Ige=0,Pge=.1;function g$(t,e=0){const n=[];return t.forEach(function(r,s){let i=null;r.forEach(function(a,o){if(!a&&i!==null){n.push(`M${i+e} ${s+e}h${o-i}v1H${i+e}z`),i=null;return}if(o===r.length-1){if(!a)return;i===null?n.push(`M${o+e},${s+e} h1v1H${o+e}z`):n.push(`M${i+e},${s+e} h${o+1-i}v1H${i+e}z`);return}a&&i===null&&(i=o)})}),n.join("")}function y$(t,e){return t.slice().map((n,r)=>r<e.y||r>=e.y+e.h?n:n.map((s,i)=>i<e.x||i>=e.x+e.w?s:!1))}function Dge(t,e,n,r){if(r==null)return null;const s=t.length+n*2,i=Math.floor(e*Pge),a=s/e,o=(r.width||i)*a,l=(r.height||i)*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 m=Math.floor(c),g=Math.floor(u),y=Math.ceil(o+c-m),v=Math.ceil(l+u-g);h={x:m,y:g,w:y,h:v}}const f=r.crossOrigin;return{x:c,y:u,h:l,w:o,excavation:h,opacity:d,crossOrigin:f}}function Oge(t,e){return e!=null?Math.max(Math.floor(e),0):t?Lge:Ige}function v$({value:t,level:e,minVersion:n,includeMargin:r,marginSize:s,imageSettings:i,size:a,boostLevel:o}){let l=Be.useMemo(()=>{const m=(Array.isArray(t)?t:[t]).reduce((g,y)=>(g.push(...xd.QrSegment.makeSegments(y)),g),[]);return xd.QrCode.encodeSegments(m,kge[e],n,void 0,void 0,o)},[t,e,n,o]);const{cells:c,margin:u,numCells:d,calculatedImageSettings:h}=Be.useMemo(()=>{let f=l.getModules();const m=Oge(r,s),g=f.length+m*2,y=Dge(f,a,m,i);return{cells:f,margin:m,numCells:g,calculatedImageSettings:y}},[l,a,i,r,s]);return{qrcode:l,margin:u,cells:c,numCells:d,calculatedImageSettings:h}}var Nge=function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0}(),Mge=Be.forwardRef(function(e,n){const r=e,{value:s,size:i=u$,level:a=d$,bgColor:o=h$,fgColor:l=f$,includeMargin:c=p$,minVersion:u=m$,boostLevel:d,marginSize:h,imageSettings:f}=r,g=Gw(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:y}=g,v=Gw(g,["style"]),_=f==null?void 0:f.src,S=Be.useRef(null),E=Be.useRef(null),L=Be.useCallback(q=>{S.current=q,typeof n=="function"?n(q):n&&(n.current=q)},[n]),[U,P]=Be.useState(!1),{margin:I,cells:k,numCells:R,calculatedImageSettings:M}=v$({value:s,level:a,minVersion:u,boostLevel:d,includeMargin:c,marginSize:h,imageSettings:f,size:i});Be.useEffect(()=>{if(S.current!=null){const q=S.current,X=q.getContext("2d");if(!X)return;let Z=k;const oe=E.current,ne=M!=null&&oe!==null&&oe.complete&&oe.naturalHeight!==0&&oe.naturalWidth!==0;ne&&M.excavation!=null&&(Z=y$(k,M.excavation));const H=window.devicePixelRatio||1;q.height=q.width=i*H;const K=i/R*H;X.scale(K,K),X.fillStyle=o,X.fillRect(0,0,R,R),X.fillStyle=l,Nge?X.fill(new Path2D(g$(Z,I))):k.forEach(function(J,Q){J.forEach(function(ve,Te){ve&&X.fillRect(Te+I,Q+I,1,1)})}),M&&(X.globalAlpha=M.opacity),ne&&X.drawImage(oe,M.x+I,M.y+I,M.w,M.h)}}),Be.useEffect(()=>{P(!1)},[_]);const G=Vw({height:i,width:i},y);let Y=null;return _!=null&&(Y=Be.createElement("img",{src:_,key:_,style:{display:"none"},onLoad:()=>{P(!0)},ref:E,crossOrigin:M==null?void 0:M.crossOrigin})),Be.createElement(Be.Fragment,null,Be.createElement("canvas",Vw({style:G,height:i,width:i,ref:L,role:"img"},v)),Y)});Mge.displayName="QRCodeCanvas";var _$=Be.forwardRef(function(e,n){const r=e,{value:s,size:i=u$,level:a=d$,bgColor:o=h$,fgColor:l=f$,includeMargin:c=p$,minVersion:u=m$,boostLevel:d,title:h,marginSize:f,imageSettings:m}=r,g=Gw(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:y,cells:v,numCells:_,calculatedImageSettings:S}=v$({value:s,level:a,minVersion:u,boostLevel:d,includeMargin:c,marginSize:f,imageSettings:m,size:i});let E=v,L=null;m!=null&&S!=null&&(S.excavation!=null&&(E=y$(v,S.excavation)),L=Be.createElement("image",{href:m.src,height:S.h,width:S.w,x:S.x+y,y:S.y+y,preserveAspectRatio:"none",opacity:S.opacity,crossOrigin:S.crossOrigin}));const U=g$(E,y);return Be.createElement("svg",Vw({height:i,width:i,viewBox:`0 0 ${_} ${_}`,ref:n,role:"img"},g),!!h&&Be.createElement("title",null,h),Be.createElement("path",{fill:o,d:`M0,0 h${_}v${_}H0z`,shapeRendering:"crispEdges"}),Be.createElement("path",{fill:l,d:U,shapeRendering:"crispEdges"}),L)});_$.displayName="QRCodeSVG";const jge=pu("DeviceIdentity");async function $x(){if(rs.getPlatform()!=="android")return{mac:"",source:"web"};try{return await jge.getMac()}catch(t){return console.warn("[deviceIdentity] native call failed",t),{mac:"",source:"error"}}}const dc="https://nadiplayer-edit.preview.emergentagent.com",Uge="https://nadi.kr/nadiplayer/pair/",Bge=()=>{const[t,e]=C.useState(null),[n,r]=C.useState(!0),[s,i]=C.useState(!1),[a,o]=C.useState(null),l=lr(),{addProfile:c,setActiveProfileId:u}=Li();C.useEffect(()=>{const m=localStorage.getItem("nadiplay_device");if(m)try{const g=JSON.parse(m);e(g),r(!1);return}catch(g){console.warn("[DeviceActivation] parse stored device failed",g)}(async()=>{try{const g=await $x(),y={mac_address:g.mac||"",hardware_id:g.android_id||"",model:g.model||""},v=await fetch(`${dc}/api/device/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(!v.ok)throw new Error("Registration failed");const _=await v.json(),S={device_id:_.device_id,mac_address:_.mac_address,pin:_.pin};if(localStorage.setItem("nadiplay_device",JSON.stringify(S)),e(S),_.paired){i(!0);try{const E=await fetch(`${dc}/api/device/config/${S.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),It.success("Device already paired – loading channels…"),setTimeout(()=>l("/"),1200)}}catch(E){console.warn("[DeviceActivation] auto-load config failed",E)}}}catch(g){It.error(g.message||"Failed to register device")}finally{r(!1)}})()},[]),C.useEffect(()=>{if(!t||s)return;let m=!1,g=0;const y=async()=>{try{const _=await fetch(`${dc}/api/device/status/${t.device_id}`);if(_.status===404){if(g++,g>=3&&!m){localStorage.removeItem("nadiplay_device"),e(null),r(!0);try{const E=await $x(),U=await(await fetch(`${dc}/api/device/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mac_address:E.mac||"",hardware_id:E.android_id||"",model:E.model||""})})).json(),P={device_id:U.device_id,mac_address:U.mac_address,pin:U.pin};localStorage.setItem("nadiplay_device",JSON.stringify(P)),e(P)}catch(E){console.warn("[DeviceActivation] re-register failed",E)}r(!1)}return}if(!_.ok)return;if(g=0,(await _.json()).paired&&!m){i(!0);const E=await fetch(`${dc}/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),It.success("Device paired! Loading channels..."),setTimeout(()=>l("/"),1500)}}}catch(_){console.warn("[DeviceActivation] poll error",_)}},v=setInterval(y,3e3);return y(),()=>{m=!0,clearInterval(v)}},[t,s,c,u,l]);const d=C.useCallback((m,g)=>{navigator.clipboard.writeText(m).then(()=>{o(g),It.success(`${g} copied`),setTimeout(()=>o(null),2e3)})},[]),h=C.useCallback(async()=>{if(t){try{await fetch(`${dc}/api/device/unpair/${t.device_id}`,{method:"DELETE"})}catch(m){console.warn("[DeviceActivation] unpair failed",m)}localStorage.removeItem("nadiplay_device"),e(null),i(!1),r(!0);try{const m=await $x(),y=await(await fetch(`${dc}/api/device/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mac_address:m.mac||"",hardware_id:m.android_id||"",model:m.model||""})})).json(),v={device_id:y.device_id,mac_address:y.mac_address,pin:y.pin};localStorage.setItem("nadiplay_device",JSON.stringify(v)),e(v),It.success("New device code generated")}catch{It.error("Failed to re-register")}finally{r(!1)}}},[t]),f=Uge;return n?p.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:p.jsx(Pn,{className:"w-8 h-8 text-primary animate-spin"})}):s?p.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background px-4",children:p.jsxs(gt.div,{initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1},className:"glass-card rounded-3xl p-10 text-center max-w-md",children:[p.jsx("div",{className:"w-16 h-16 rounded-full bg-primary/20 flex items-center justify-center mx-auto mb-4",children:p.jsx(qi,{className:"w-8 h-8 text-primary"})}),p.jsx("h2",{className:"text-foreground text-xl font-semibold mb-2",children:"Device Paired!"}),p.jsx("p",{className:"text-muted-foreground text-sm",children:"Loading your IPTV profile..."})]})}):p.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-background px-4","data-testid":"device-activation-page",children:[p.jsx("div",{className:"absolute inset-0 bg-cover bg-center bg-no-repeat opacity-30",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),p.jsx("div",{className:"absolute inset-0 bg-background/60"}),p.jsxs(gt.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:[p.jsxs("div",{className:"flex flex-col items-center mb-6",children:[p.jsx("div",{className:"w-14 h-14 rounded-2xl glass flex items-center justify-center mb-3",children:p.jsx(ri,{className:"w-6 h-6 text-primary"})}),p.jsx("h1",{className:"font-display text-2xl tracking-[0.2em] gold-text",children:"NADIPLAYER"}),p.jsx("p",{className:"text-muted-foreground text-xs mt-1",children:"Device Activation"})]}),t&&p.jsxs("div",{className:"space-y-5",children:[p.jsx("div",{className:"flex justify-center",children:p.jsx("div",{className:"bg-white p-3 rounded-2xl",children:p.jsx(_$,{value:`${f}?pin=${t.pin}`,size:160,level:"M","data-testid":"pairing-qr-code"})})}),p.jsxs("p",{className:"text-center text-muted-foreground text-[11px]",children:["Scan this QR code or visit"," ",p.jsx("span",{className:"text-primary break-all",children:f})]}),p.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[p.jsx(CO,{label:"MAC Address",value:t.mac_address,onCopy:()=>d(t.mac_address,"MAC"),isCopied:a==="MAC"}),p.jsx(CO,{label:"Device ID",value:t.device_id,onCopy:()=>d(t.device_id,"Device ID"),isCopied:a==="Device ID"})]}),p.jsxs("div",{className:"glass rounded-2xl p-5 text-center","data-testid":"device-pin-display",children:[p.jsx("p",{className:"text-muted-foreground text-xs mb-2",children:"Your Pairing PIN"}),p.jsx("div",{className:"flex justify-center gap-2",children:t.pin.split("").map((m,g)=>p.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:m},`pin-digit-${g}`))}),p.jsx("p",{className:"text-muted-foreground text-[10px] mt-3",children:"Enter this PIN on the web portal to link your account"})]}),p.jsxs("div",{className:"flex items-center justify-center gap-2 text-muted-foreground",children:[p.jsx(hq,{className:"w-4 h-4 animate-pulse text-primary"}),p.jsx("span",{className:"text-xs",children:"Waiting for pairing..."})]}),p.jsxs("div",{className:"flex gap-3",children:[p.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:[p.jsx(wp,{className:"w-3.5 h-3.5"})," Open Pair Portal"]}),p.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:[p.jsx(Oh,{className:"w-3.5 h-3.5"})," Reset"]})]})]})]})]})},CO=({label:t,value:e,onCopy:n,isCopied:r})=>p.jsxs("div",{className:"flex items-center justify-between glass rounded-xl px-4 py-3",children:[p.jsxs("div",{children:[p.jsx("p",{className:"text-muted-foreground text-[10px]",children:t}),p.jsx("p",{className:"text-foreground text-sm font-mono tracking-wider",children:e})]}),p.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?p.jsx(qi,{className:"w-3.5 h-3.5 text-primary"}):p.jsx(Dz,{className:"w-3.5 h-3.5 text-muted-foreground"})})]}),Fge="https://nadiplayer-edit.preview.emergentagent.com",$ge=()=>{const[t]=t1(),e=lr(),[n,r]=C.useState(t.get("pin")||""),[s,i]=C.useState(""),[a,o]=C.useState(""),[l,c]=C.useState(""),[u,d]=C.useState("My IPTV"),[h,f]=C.useState(!1),[m,g]=C.useState(!1),[y,v]=C.useState("");C.useEffect(()=>{if(!n){const S=document.getElementById("pin-input");S&&S.focus()}},[n]);const _=async S=>{S.preventDefault(),v("");const E=n.replace(/\s/g,"");if(E.length!==6||!/^\d+$/.test(E)){v("PIN must be exactly 6 digits");return}if(!s.trim()){v("Server URL is required");return}if(!a.trim()||!l.trim()){v("Username and password are required");return}f(!0);try{const L=await fetch(`${Fge}/api/device/pair`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pin:E,server_url:s.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})`)}g(!0),It.success("Device paired successfully!")}catch(L){v(L.message||"Pairing failed"),It.error(L.message||"Pairing failed")}finally{f(!1)}};return m?p.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-background px-4",children:[p.jsx("div",{className:"absolute inset-0 bg-cover bg-center bg-no-repeat opacity-30",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),p.jsx("div",{className:"absolute inset-0 bg-background/80"}),p.jsxs(gt.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:[p.jsx("div",{className:"w-16 h-16 rounded-full bg-primary/20 flex items-center justify-center mx-auto mb-4",children:p.jsx(qi,{className:"w-8 h-8 text-primary"})}),p.jsx("h2",{className:"text-foreground text-xl font-semibold mb-2",children:"Paired!"}),p.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."}),p.jsx("button",{onClick:()=>e("/"),className:"text-primary text-xs underline","data-testid":"go-home-btn",children:"Go to Home"})]})]}):p.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-background px-4","data-testid":"pair-portal-page",children:[p.jsx("div",{className:"absolute inset-0 bg-cover bg-center bg-no-repeat opacity-30",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),p.jsx("div",{className:"absolute inset-0 bg-background/60"}),p.jsxs(gt.form,{onSubmit:_,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:[p.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:[p.jsx(Ph,{className:"w-3.5 h-3.5"})," Back"]}),p.jsxs("div",{className:"flex flex-col items-center mb-6",children:[p.jsx("div",{className:"w-14 h-14 rounded-2xl glass flex items-center justify-center mb-3",children:p.jsx(wp,{className:"w-6 h-6 text-primary"})}),p.jsx("h1",{className:"font-display text-2xl tracking-[0.2em] gold-text",children:"PAIR DEVICE"}),p.jsx("p",{className:"text-muted-foreground text-xs mt-1",children:"Enter the PIN shown on your TV"})]}),p.jsxs("div",{className:"mb-5",children:[p.jsx("label",{className:"text-muted-foreground text-[11px] mb-1.5 block",children:"6-Digit PIN"}),p.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"})]}),p.jsxs("div",{className:"space-y-3 mb-5",children:[p.jsx("p",{className:"text-muted-foreground text-[11px]",children:"IPTV Server Credentials"}),p.jsx(Zg,{icon:Vc,placeholder:"Profile Name (e.g. My IPTV)",value:u,onChange:d,testId:"profile-name-input"}),p.jsx(Zg,{icon:Gc,placeholder:"Server URL (http://...)",value:s,onChange:i,testId:"server-url-input"}),p.jsx(Zg,{icon:Ji,placeholder:"Username",value:a,onChange:o,testId:"username-input"}),p.jsx(Zg,{icon:Cv,placeholder:"Password",value:l,onChange:c,type:"password",testId:"password-input"})]}),y&&p.jsx("p",{className:"text-destructive text-xs text-center mb-3","data-testid":"pair-error",children:y}),p.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&&p.jsx(Pn,{className:"w-4 h-4 animate-spin"}),h?"Pairing...":"Pair Device"]}),p.jsx("p",{className:"text-center text-muted-foreground text-[10px] mt-4",children:"Your credentials are sent directly to the device and stored securely."})]})]})},Zg=({icon:t,placeholder:e,value:n,onChange:r,type:s="text",testId:i})=>p.jsxs("div",{className:"flex items-center gap-3 glass-input rounded-xl px-4 py-3",children:[p.jsx(t,{className:"w-4 h-4 text-muted-foreground shrink-0"}),p.jsx("input",{type:s,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":i})]}),mf="https://nadiplayer-edit.preview.emergentagent.com",Vge=()=>{const[t]=t1(),e=lr(),[n,r]=C.useState([]),[s,i]=C.useState(null),[a,o]=C.useState("3m"),[l,c]=C.useState(""),[u,d]=C.useState("stripe"),[h,f]=C.useState(!1),[m,g]=C.useState(""),y=t.get("session_id"),v=t.get("canceled")==="1",_=t.get("paypal")==="1",S=t.get("token")||t.get("order_id"),[E,L]=C.useState(v?"Payment canceled.":""),[U,P]=C.useState(null);C.useEffect(()=>{(async()=>{try{const[M,G]=await Promise.all([fetch(`${mf}/api/payments/plans`).then(Y=>Y.json()),fetch(`${mf}/api/payments/config`).then(Y=>Y.json())]);r(M.plans||[]),i(G)}catch{}})()},[]),C.useEffect(()=>{if(!y)return;let R=0;const M=setInterval(async()=>{R+=1;try{const Y=await(await fetch(`${mf}/api/payments/checkout/status/${y}`)).json();Y.payment_status==="paid"?(clearInterval(M),P({expiry_at:Y.user_expiry_at,amount:(Y.amount_total||0)/100,currency:Y.currency||"usd"}),L(""),It.success("Payment successful!")):Y.status==="expired"||R>30?(clearInterval(M),L("Payment session expired. Please try again.")):L("Payment is being processed…")}catch{R>30&&(clearInterval(M),L("Could not verify payment."))}},2e3);return()=>clearInterval(M)},[y]),C.useEffect(()=>{if(!_||!S)return;(async()=>{L("Capturing PayPal payment…");try{const G=await(await fetch(`${mf}/api/payments/paypal/capture`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({order_id:S})})).json();G.status==="COMPLETED"?(P({expiry_at:G.user_expiry_at,amount:0,currency:"usd"}),L(""),It.success("PayPal payment completed!")):L(`PayPal status: ${G.status}`)}catch(M){L(M.message||"PayPal capture failed")}})()},[_,S]);const I=C.useMemo(()=>n.find(R=>R.id===a),[n,a]),k=async()=>{if(g(""),!l.trim()){g("Please enter your Nadi Player username");return}if(!I){g("Please pick a plan");return}f(!0);try{const R=await fetch(`${mf}/api/payments/checkout/session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({plan_id:I.id,username:l.trim(),origin_url:window.location.origin,provider:u})});if(!R.ok){const G=await R.json().catch(()=>({}));throw new Error(G.detail||`Checkout failed (${R.status})`)}const M=await R.json();if(u==="stripe"&&M.url)window.location.href=M.url;else if(u==="paypal"&&M.approval_url)window.location.href=M.approval_url;else throw new Error("Missing redirect URL")}catch(R){g(R.message||"Checkout failed"),It.error(R.message||"Checkout failed")}finally{f(!1)}};return U?p.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-background px-4","data-testid":"subscription-success-page",children:[p.jsx("div",{className:"absolute inset-0 bg-cover bg-center bg-no-repeat opacity-30",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),p.jsx("div",{className:"absolute inset-0 bg-background/80"}),p.jsxs(gt.div,{initial:{scale:.92,opacity:0},animate:{scale:1,opacity:1},className:"relative z-10 glass-card rounded-3xl p-10 max-w-lg w-full text-center",children:[p.jsx("div",{className:"w-20 h-20 rounded-full bg-primary/20 flex items-center justify-center mx-auto mb-5",children:p.jsx(qi,{className:"w-10 h-10 text-primary"})}),p.jsx("h1",{className:"font-display text-3xl tracking-[0.25em] gold-text mb-2",children:"PAID"}),p.jsx("p",{className:"text-muted-foreground text-sm mb-6",children:"Your Nadi Player subscription has been activated."}),U.expiry_at?p.jsxs("div",{className:"glass-input rounded-xl p-4 mb-6",children:[p.jsx("p",{className:"text-[11px] uppercase tracking-widest text-muted-foreground mb-1",children:"Active until"}),p.jsx("p",{className:"font-mono text-foreground text-sm",children:new Date(U.expiry_at).toLocaleString()})]}):p.jsx("div",{className:"glass-input rounded-xl p-4 mb-6 text-xs text-muted-foreground",children:"Payment recorded. If the username you entered doesn't exist yet, ask the admin to create it and we'll apply the credit to that account on request."}),p.jsxs("div",{className:"flex gap-3",children:[p.jsx("button",{onClick:()=>e("/"),className:"flex-1 py-3 rounded-xl glass-input text-foreground text-sm hover:bg-muted/40 transition","data-testid":"go-home-btn",children:"Go Home"}),p.jsx("button",{onClick:()=>e("/login"),className:"flex-1 py-3 rounded-xl bg-gradient-to-r from-primary/80 to-primary/60 text-primary-foreground text-sm hover:from-primary hover:to-primary/80 transition","data-testid":"login-btn",children:"Login"})]})]})]}):p.jsxs("div",{className:"min-h-screen bg-background px-4 py-10","data-testid":"subscription-page",children:[p.jsx("div",{className:"fixed inset-0 bg-cover bg-center bg-no-repeat opacity-30 pointer-events-none",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),p.jsx("div",{className:"fixed inset-0 bg-background/60 pointer-events-none"}),p.jsxs("div",{className:"relative z-10 max-w-4xl mx-auto",children:[p.jsxs("button",{onClick:()=>e(-1),className:"flex items-center gap-1 text-muted-foreground text-xs mb-6 hover:text-foreground transition","data-testid":"back-btn",children:[p.jsx(Ph,{className:"w-3.5 h-3.5"})," Back"]}),p.jsxs(gt.div,{initial:{opacity:0,y:16},animate:{opacity:1,y:0},className:"text-center mb-10",children:[p.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1 rounded-full glass text-[10px] tracking-widest uppercase text-primary mb-4",children:[p.jsx(kv,{className:"w-3 h-3"})," Subscription"]}),p.jsx("h1",{className:"font-display text-4xl md:text-5xl tracking-[0.2em] gold-text mb-3",children:"NADI PLAYER"}),p.jsx("p",{className:"text-muted-foreground text-sm max-w-xl mx-auto",children:"Pick a plan, pay securely with Stripe or PayPal, and your account is extended automatically — no admin intervention needed."})]}),p.jsx(Lo,{children:(E||v)&&p.jsxs(gt.div,{initial:{opacity:0,y:-8},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},className:`glass-card rounded-2xl p-4 mb-6 flex items-center gap-3 ${v?"text-destructive":"text-primary"}`,"data-testid":"status-banner",children:[v?p.jsx(Rv,{className:"w-5 h-5 shrink-0"}):p.jsx(Pn,{className:"w-5 h-5 animate-spin shrink-0"}),p.jsx("p",{className:"text-sm",children:E||"Payment canceled."})]})}),p.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mb-8",children:n.map((R,M)=>{const G=R.id===a,Y=(R.amount/(R.days/30)).toFixed(2),q=R.id==="12m";return p.jsxs(gt.button,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:M*.05},onClick:()=>o(R.id),className:`relative text-left rounded-2xl p-4 transition-all focusable ${G?"glass-card ring-2 ring-primary shadow-[0_0_40px_hsla(40,80%,55%,0.3)]":"glass hover:ring-1 hover:ring-primary/40"}`,"data-testid":`plan-card-${R.id}`,children:[q&&p.jsx("span",{className:"absolute -top-2 right-3 text-[9px] uppercase tracking-widest bg-primary text-primary-foreground px-2 py-0.5 rounded-full",children:"Best"}),p.jsx("p",{className:"text-[10px] uppercase tracking-widest text-muted-foreground mb-1",children:R.name}),p.jsxs("p",{className:"font-display text-3xl gold-text mb-1",children:["$",R.amount.toFixed(2)]}),p.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["$",Y,"/mo · ",R.days," days"]}),G&&p.jsx("div",{className:"absolute top-3 right-3 w-5 h-5 rounded-full bg-primary flex items-center justify-center",children:p.jsx(qi,{className:"w-3 h-3 text-primary-foreground"})})]},R.id)})}),p.jsxs(gt.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.2},className:"glass-card rounded-3xl p-6 md:p-8",children:[p.jsx("label",{className:"text-muted-foreground text-[11px] mb-1.5 block uppercase tracking-widest",children:"Nadi Player Username"}),p.jsxs("div",{className:"flex items-center gap-3 glass-input rounded-xl px-4 py-3 mb-5",children:[p.jsx(Ji,{className:"w-4 h-4 text-muted-foreground"}),p.jsx("input",{type:"text",placeholder:"your_username",value:l,onChange:R=>c(R.target.value),className:"flex-1 bg-transparent text-foreground placeholder:text-muted-foreground text-sm outline-none",autoComplete:"off","data-testid":"username-input"})]}),p.jsx("label",{className:"text-muted-foreground text-[11px] mb-1.5 block uppercase tracking-widest",children:"Payment Method"}),p.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-6",children:[p.jsxs("button",{onClick:()=>d("stripe"),disabled:!(s!=null&&s.stripe_enabled),className:`py-3 rounded-xl text-sm flex items-center justify-center gap-2 transition disabled:opacity-40 ${u==="stripe"?"bg-gradient-to-r from-primary/80 to-primary/60 text-primary-foreground":"glass-input text-foreground"}`,"data-testid":"provider-stripe-btn",children:[p.jsx(Mz,{className:"w-4 h-4"})," Stripe"]}),p.jsxs("button",{onClick:()=>d("paypal"),disabled:!(s!=null&&s.paypal_enabled),className:`py-3 rounded-xl text-sm flex items-center justify-center gap-2 transition disabled:opacity-40 ${u==="paypal"?"bg-gradient-to-r from-primary/80 to-primary/60 text-primary-foreground":"glass-input text-foreground"}`,"data-testid":"provider-paypal-btn",title:s!=null&&s.paypal_enabled?"":"PayPal not configured on this server",children:[p.jsx("span",{className:"font-bold text-xs",children:"PayPal"}),!(s!=null&&s.paypal_enabled)&&p.jsx("span",{className:"text-[9px] opacity-60",children:"(disabled)"})]})]}),m&&p.jsx("p",{className:"text-destructive text-xs mb-3 text-center","data-testid":"error-msg",children:m}),p.jsxs("button",{onClick:k,disabled:h||!I,className:"w-full py-3.5 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 flex items-center justify-center gap-2 disabled:opacity-60","data-testid":"pay-btn",children:[h&&p.jsx(Pn,{className:"w-4 h-4 animate-spin"}),h?"Preparing checkout…":`Pay $${(I==null?void 0:I.amount.toFixed(2))||"0.00"} with ${u==="stripe"?"Stripe":"PayPal"}`]}),p.jsxs("div",{className:"flex items-center justify-center gap-4 mt-5 text-[10px] text-muted-foreground",children:[p.jsxs("span",{className:"flex items-center gap-1",children:[p.jsx(H9,{className:"w-3 h-3"})," Secure checkout"]}),p.jsxs("span",{className:"flex items-center gap-1",children:[p.jsx(Oj,{className:"w-3 h-3"})," Instant activation"]})]})]}),p.jsx("p",{className:"text-center text-muted-foreground text-[10px] mt-8",children:"By paying you agree to the Nadi Player Terms. Questions? Contact support."})]})]})},Gge=()=>{const t=Qi(),{t:e}=wr();return C.useEffect(()=>{console.error("404 Error: User attempted to access non-existent route:",t.pathname)},[t.pathname]),p.jsx("div",{className:"flex min-h-screen items-center justify-center bg-muted",children:p.jsxs("div",{className:"text-center",children:[p.jsx("h1",{className:"mb-4 text-4xl font-bold",children:e("notFound.title")}),p.jsx("p",{className:"mb-4 text-xl text-muted-foreground",children:e("notFound.message")}),p.jsx("a",{href:"/",className:"text-primary underline hover:text-primary/90",children:e("notFound.goHome")})]})})},Kge="May 4, 2026",Hge=[{n:"1.",title:"Introduction",body:p.jsxs("p",{children:["NadiPlayer (",p.jsx("strong",{children:'"we," "our," or "us"'}),") is a media player application developed by ",p.jsx("strong",{children:"Nadi"}),". We respect your privacy and are committed to protecting any information that may be used to identify your device for the sole purpose of providing our services."]})},{n:"2.",title:"Information Collection and Usage",body:p.jsxs(p.Fragment,{children:[p.jsx("p",{children:"To provide a seamless experience between our web portal and the application, we use specific device identifiers:"}),p.jsxs("ul",{className:"list-disc pl-5 space-y-1.5 mt-2",children:[p.jsxs("li",{children:[p.jsx("strong",{children:"MAC Address and Device ID:"})," As shown in our pairing screen, we display your device's MAC Address and a unique Device ID locally."]}),p.jsxs("li",{children:[p.jsx("strong",{children:"Manual Pairing:"})," We do not transmit this data automatically. The user must manually enter these identifiers and a generated 6-digit PIN on our secure web portal to pair their device and manage playlists."]}),p.jsxs("li",{children:[p.jsx("strong",{children:"Purpose:"})," These identifiers are used strictly for authentication and to link the user's legally owned content/playlists to their specific device."]})]})]})},{n:"3.",title:"Content Responsibility (Disclaimer)",body:p.jsxs("ul",{className:"list-disc pl-5 space-y-1.5",children:[p.jsxs("li",{children:[p.jsx("strong",{children:"Clean Player Policy:"})," NadiPlayer is strictly a media player tool. We do not provide, host, sell, or include any IPTV subscriptions, media content, or playlists."]}),p.jsxs("li",{children:[p.jsx("strong",{children:"User Content:"})," Users are solely responsible for the content they play. NadiPlayer does not have access to, nor do we monitor, the specific streams or files you choose to play."]}),p.jsxs("li",{children:[p.jsx("strong",{children:"Copyright:"})," We do not endorse the streaming of copyright-protected material without permission from the rightful owners."]})]})},{n:"4.",title:"Data Storage and Security",body:p.jsxs("ul",{className:"list-disc pl-5 space-y-1.5",children:[p.jsxs("li",{children:[p.jsx("strong",{children:"Local Storage:"})," All playlists and server credentials provided by the user are stored locally on the device or handled via the pairing secure link."]}),p.jsxs("li",{children:[p.jsx("strong",{children:"Encryption:"})," Data transmitted during the pairing process is encrypted to prevent unauthorized access."]}),p.jsxs("li",{children:[p.jsx("strong",{children:"Third-Party SDKs:"})," NadiPlayer does not include hidden third-party tracking SDKs or intrusive advertising networks."]})]})},{n:"5.",title:"Children's Privacy",body:p.jsx("p",{children:"NadiPlayer does not collect personal information from any user, including children. Our application is a tool for playing user-provided content and is safe for all age groups."})},{n:"6.",title:"Permissions",body:p.jsxs("p",{children:["The app may request access to"," ",p.jsx("strong",{children:'"Photos/Media/Files"'})," or"," ",p.jsx("strong",{children:'"Network Access"'})," solely to play local files or stream content from user-provided URLs."]})},{n:"7.",title:"Contact Information",body:p.jsxs(p.Fragment,{children:[p.jsx("p",{children:"For any privacy-related inquiries, please contact:"}),p.jsxs("ul",{className:"list-none pl-0 space-y-1 mt-2",children:[p.jsxs("li",{children:[p.jsx("strong",{children:"Developer:"})," Nadi"]}),p.jsxs("li",{children:[p.jsx("strong",{children:"Email:"})," ",p.jsx("a",{href:"mailto:nadiplayer@nadi.kr",className:"text-primary underline-offset-2 hover:underline",children:"nadiplayer@nadi.kr"})]}),p.jsxs("li",{children:[p.jsx("strong",{children:"Website:"})," ",p.jsx("a",{href:"https://nadi.kr",target:"_blank",rel:"noreferrer",className:"text-primary underline-offset-2 hover:underline",children:"https://nadi.kr"})]})]})]})}],zge=()=>{const t=lr();return p.jsxs("div",{className:"min-h-screen w-full bg-background","data-testid":"privacy-screen",children:[p.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:[p.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:p.jsx(Ph,{className:"h-4 w-4"})}),p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx(Ul,{className:"h-4 w-4 text-primary"}),p.jsx("span",{className:"text-sm font-semibold tracking-wide text-foreground",children:"Privacy Policy"})]})]}),p.jsx(gt.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:p.jsxs("div",{className:"rounded-2xl border border-border/70 bg-card/70 p-5 shadow-xl backdrop-blur",children:[p.jsx("div",{className:"flex items-start justify-between gap-3 mb-1",children:p.jsx("h1",{className:"text-xl font-bold text-foreground",children:"Privacy Policy for NadiPlayer"})}),p.jsxs("p",{className:"text-[11px] text-muted-foreground tracking-wider uppercase mb-5",children:["Last Updated: ",Kge]}),p.jsx("div",{className:"space-y-5 text-sm text-muted-foreground leading-relaxed","data-testid":"privacy-text",children:Hge.map(e=>p.jsxs("section",{children:[p.jsxs("h2",{className:"text-[13px] font-semibold tracking-wider text-primary uppercase mb-1.5 border-b border-border/40 pb-1",children:[p.jsx("span",{className:"text-muted-foreground mr-2 font-normal",children:e.n}),e.title]}),p.jsx("div",{className:"pt-1 text-foreground/85",children:e.body})]},e.n))}),p.jsx("div",{className:"mt-7 pt-4 border-t border-border/40 text-center text-[11px] text-muted-foreground",children:"© 2026 NadiPlayer — All rights reserved."})]})})]})},Vx=768;function qge(){const[t,e]=C.useState(void 0);return C.useEffect(()=>{const n=window.matchMedia(`(max-width: ${Vx-1}px)`),r=()=>{e(window.innerWidth<Vx)};return n.addEventListener("change",r),e(window.innerWidth<Vx),()=>n.removeEventListener("change",r)},[]),!!t}const Wge=[{key:"home",label:"Home",route:"/",icon:uE},{key:"live",label:"Live TV",route:"/live-tv",icon:ri},{key:"movies",label:"Movies",route:"/movies",icon:bm},{key:"series",label:"Series",route:"/series",icon:Dh},{key:"account",label:"Account",route:"/account",icon:Ji}],Yge=new Set(["/","/live-tv","/movies","/series","/account"]),Xge=()=>{const[t,e]=C.useState(!1);return C.useEffect(()=>{const n=window.matchMedia("(orientation: landscape) and (max-height: 500px)"),r=()=>e(n.matches);return r(),n.addEventListener?n.addEventListener("change",r):n.addListener(r),()=>{n.removeEventListener?n.removeEventListener("change",r):n.removeListener(r)}},[]),t},Qge=()=>{const t=Qi(),e=lr(),n=qge(),r=Xge();if(!Yge.has(t.pathname)||n&&r)return null;const s=n?{paddingBottom:"env(safe-area-inset-bottom, 0px)"}:{paddingBottom:"env(safe-area-inset-bottom, 0px)"};return p.jsx("nav",{className:"fixed bottom-0 left-0 right-0 z-40 border-t border-border/60 bg-background/85 backdrop-blur-xl",style:s,"data-testid":"bottom-nav","data-mobile":n?"1":"0",children:p.jsx(Ci,{focusKey:"bottom-nav",className:n?"flex items-stretch justify-around px-1 py-1":"flex items-stretch justify-around px-1 py-2",children:Wge.map(i=>{const a=t.pathname===i.route,o=i.icon;return p.jsx(wi,{focusKey:`nav-${i.key}`,onEnter:()=>e(i.route),onClick:()=>e(i.route),subtle:!0,"data-testid":`nav-${i.key}`,"aria-label":i.label,className:`flex flex-1 flex-col items-center justify-center rounded-lg transition-colors border-transparent ${n?"py-1":"py-2"} ${a?"text-primary":"text-muted-foreground hover:text-foreground"}`,focusClassName:"!border-primary/50",children:p.jsx(o,{className:`${n?"h-5 w-5":"h-6 w-6"} ${a?"":"opacity-60"}`,strokeWidth:a?2.2:1.6})},i.key)})})})},Kw=pu("App",{web:()=>km(()=>import("./web-SEctF8HS.js"),[]).then(t=>new t.AppWeb)}),Jge=Object.freeze(Object.defineProperty({__proto__:null,App:Kw},Symbol.toStringTag,{value:"Module"}));function b$(){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 Zge(){const t=b$();return t==="webos"||t==="tizen"}function eye(){const t=window.webOS;t!=null&&t.platformBack&&t.platformBack()}function tye(){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 nye=()=>{const t=lr(),e=Qi(),r=["/","/welcome","/login","/admin"].includes(e.pathname),s=i=>{if(r||!i){switch(b$()){case"webos":eye();break;case"tizen":tye();break;case"capacitor":Kw.exitApp();break;default:window.close()}return}t(-1)};return C.useEffect(()=>{if(!Cm())return;let i=null;return(async()=>{const a=await Kw.addListener("backButton",({canGoBack:o})=>{s(o)});i=()=>a.remove()})(),()=>{i&&i()}},[t,e.pathname]),C.useEffect(()=>{if(!Zge())return;const i=o=>{(o.keyCode===10009||o.keyCode===461||o.key==="Escape")&&(o.preventDefault(),o.stopPropagation(),s(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",i,!0),()=>{document.removeEventListener("keydown",i,!0)}},[t,e.pathname]),null},Gx=pu("ApkInstaller");function Kx(){return rs.isNativePlatform()&&rs.getPlatform()==="android"}const rye=()=>{var M,G,Y;const{info:t,hasUpdate:e,forced:n,installedVersion:r}=o$(),{user:s}=ys(),i=Qi(),{t:a}=wr(),o=(s==null?void 0:s.role)==="admin",l=i.pathname.startsWith("/admin")||i.pathname.startsWith("/login"),c=n&&!o&&!l,[u,d]=C.useState(!1),[h,f]=C.useState(!1),[m,g]=C.useState({phase:"idle"}),y=C.useRef(null);if(C.useEffect(()=>{var q;(q=t==null?void 0:t.update)!=null&&q.latest_version&&d(Ege(t.update.latest_version))},[(M=t==null?void 0:t.update)==null?void 0:M.latest_version]),C.useEffect(()=>{if(!(t!=null&&t.update))return;f(!1);const q=t.update.popup_delay_seconds,X=Number.isFinite(q)?Math.max(0,Math.min(600,Number(q))):10,Z=window.setTimeout(()=>f(!0),X*1e3);return()=>window.clearTimeout(Z)},[(G=t==null?void 0:t.update)==null?void 0:G.popup_delay_seconds,(Y=t==null?void 0:t.update)==null?void 0:Y.latest_version]),C.useEffect(()=>{if(!Kx())return;let q=!0;return Gx.addListener("downloadProgress",({loaded:X,total:Z,percent:oe})=>{q&&g(ne=>ne.phase==="downloading"?{phase:"downloading",percent:oe,loaded:X,total:Z}:ne)}).then(X=>{y.current=X}),()=>{var X;q=!1,(X=y.current)==null||X.remove(),y.current=null}},[]),!t||!e||!h||!c&&u)return null;const v=t.update,_=v.apk_url||"",S=v.play_url||"",E=_||S,L=()=>{c||m.phase==="downloading"||m.phase==="installing"||(Sge(v.latest_version),d(!0))},U=q=>{q&&window.open(q,"_blank","noopener,noreferrer")},P=async()=>{if(Kx()&&_){try{g({phase:"downloading",percent:0,loaded:0,total:0});const{path:q}=await Gx.downloadApk({url:_,fileName:`nadiplayer-${v.latest_version}.apk`});g({phase:"installing"});const X=await Gx.installApk({path:q});if(!X.launched&&X.reason==="needs-install-permission"){g({phase:"needs-permission"});return}g({phase:"done"})}catch(q){g({phase:"error",message:q instanceof Error?q.message:"Update failed"})}return}U(E)},I=(()=>{switch(m.phase){case"downloading":return m.percent>=0?a("update.downloadingPercent",{percent:m.percent}):a("update.downloading");case"installing":return a("update.openingInstaller");case"needs-permission":return a("update.allowInstallRetry");case"done":return a("update.installerLaunched");case"error":return a("update.retry");default:return Kx()&&_?a("update.updateNow"):a("update.downloadUpdate")}})(),k=m.phase==="downloading"||m.phase==="installing",R=()=>{if(m.phase!=="downloading")return null;const q=m.percent>=0?Math.max(0,Math.min(100,m.percent)):null;return p.jsx("div",{className:"mt-2 h-1.5 w-full overflow-hidden rounded-full bg-muted","data-testid":"update-popup-progress",children:p.jsx("div",{className:"h-full bg-primary transition-[width] duration-150",style:{width:q===null?"30%":`${q}%`}})})};return p.jsx(Lo,{children:p.jsx(gt.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:q=>{q.target===q.currentTarget&&L()},children:p.jsxs(gt.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:[!c&&!k&&p.jsx("button",{onClick:L,"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":a("update.closeAria"),children:p.jsx(Na,{className:"h-4 w-4"})}),p.jsxs("div",{className:"mb-4 flex items-start gap-3",children:[p.jsx("div",{className:`flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl border ${c?"border-amber-500/50 bg-amber-500/10 text-amber-400":"border-primary/40 bg-primary/10 text-primary"}`,children:c?p.jsx(sq,{className:"h-6 w-6"}):p.jsx(kv,{className:"h-6 w-6"})}),p.jsxs("div",{className:"min-w-0 flex-1",children:[p.jsx("h2",{className:"text-lg font-semibold tracking-tight text-foreground","data-testid":"update-popup-title",children:a(c?"update.titleForced":"update.titleNormal")}),p.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[p.jsxs("span",{"data-testid":"update-popup-current",children:["v",r]}),"  →  ",p.jsxs("span",{className:"font-medium text-foreground","data-testid":"update-popup-latest",children:["v",v.latest_version]})]})]})]}),c&&p.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:a("update.forcedNotice")}),o&&n&&p.jsxs("div",{className:"mb-4 flex items-start 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-admin-preview",children:[p.jsx(Ul,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),p.jsx("span",{children:a("update.adminPreview",{installed:r,min:t.update.min_supported_version})})]}),!o&&l&&n&&p.jsxs("div",{className:"mb-4 flex items-start 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-login-preview",children:[p.jsx(Ul,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),p.jsx("span",{children:a("update.loginPreview")})]}),m.phase==="needs-permission"&&p.jsx("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:a("update.needPermission")}),m.phase==="error"&&p.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:m.message}),m.phase==="done"&&p.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:[p.jsx(a1,{className:"h-4 w-4"}),a("update.installerOpened")]}),v.changelog&&p.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:[p.jsx("p",{className:"mb-1 text-[10px] font-medium uppercase tracking-[0.2em] text-muted-foreground",children:a("update.whatsNew")}),p.jsx("pre",{className:"whitespace-pre-wrap break-words font-sans text-xs leading-relaxed text-foreground/90","data-testid":"update-popup-changelog",children:v.changelog})]}),p.jsxs("div",{className:"flex flex-col gap-2",children:[E?p.jsxs("button",{onClick:P,disabled:k,"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:[m.phase==="downloading"||m.phase==="installing"?p.jsx(Pn,{className:"h-4 w-4 animate-spin"}):p.jsx(o1,{className:"h-4 w-4"}),I]}):p.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:a("update.noUrl")}),R(),S&&_&&p.jsxs("button",{onClick:()=>U(S),disabled:k,"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:[p.jsx(vo,{className:"h-3.5 w-3.5"}),a("update.openInPlayStore")]}),!c&&!k&&p.jsx("button",{onClick:L,"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:a("update.later")})]})]},"update-card")},"update-backdrop")})},x$="nadiplay_lang_chosen";function sye(){try{return localStorage.getItem(x$)==="1"}catch{return!1}}const iye=({onFinish:t})=>{const{i18n:e,t:n}=wr(),[r,s]=C.useState(()=>{const d=Gi.findIndex(h=>h.code===e.language);return d>=0?d:0}),[i,a]=C.useState(1),o=Gi[r];C.useEffect(()=>{e.changeLanguage(o.code)},[o.code,e]);const l=()=>{a(1),s(d=>(d+1)%Gi.length)},c=()=>{a(-1),s(d=>(d-1+Gi.length)%Gi.length)};C.useEffect(()=>{const d=h=>{h.key==="ArrowRight"?(h.preventDefault(),l()):h.key==="ArrowLeft"?(h.preventDefault(),c()):h.key==="Enter"&&(h.preventDefault(),u())};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[]);const u=()=>{try{localStorage.setItem(x$,"1"),localStorage.setItem("nadiplay_lang",o.code)}catch{}t()};return p.jsxs(gt.div,{"data-testid":"first-run-lang-select",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.5,ease:"easeOut"},className:"fixed inset-0 z-[9998] overflow-hidden flex flex-col items-center justify-center px-6",style:{background:"radial-gradient(ellipse at center, hsl(200, 40%, 10%) 0%, hsl(200, 30%, 5%) 55%, #000 100%)"},children:[p.jsx("div",{className:"absolute inset-0 opacity-30 bg-cover bg-center",style:{backgroundImage:"url('/images/nebula-bg.png')"}}),p.jsx("div",{className:"absolute inset-0 bg-background/55"}),[0,1].map(d=>p.jsx(gt.div,{initial:{scale:.4,opacity:0},animate:{scale:2.5,opacity:0},transition:{duration:4,delay:d*1.2,repeat:1/0,ease:"easeOut"},className:"absolute rounded-full pointer-events-none",style:{width:320,height:320,border:"1px solid hsla(40, 80%, 55%, 0.28)",boxShadow:"0 0 50px hsla(40, 80%, 55%, 0.18)"}},d)),p.jsxs(gt.div,{initial:{opacity:0,y:-16},animate:{opacity:1,y:0},transition:{delay:.15,duration:.6},className:"relative z-10 flex flex-col items-center gap-2 mb-8",children:[p.jsxs("div",{className:"flex items-center gap-2 text-primary/90",children:[p.jsx(kv,{className:"w-4 h-4"}),p.jsx("span",{className:"text-[10px] sm:text-xs uppercase tracking-[0.4em]",children:"NADIPLAYER"})]}),p.jsx("h1",{className:"font-display text-2xl sm:text-3xl md:text-4xl gold-text tracking-[0.25em] text-center",style:{textShadow:"0 0 30px hsla(40, 80%, 55%, 0.35)"},children:n("firstRun.title")}),p.jsx("p",{className:"text-muted-foreground text-[11px] sm:text-xs uppercase tracking-[0.3em] text-center max-w-md",children:n("firstRun.subtitle")})]}),p.jsxs("div",{className:"relative z-10 flex items-center justify-center gap-4 sm:gap-8 w-full max-w-2xl",children:[p.jsx("button",{type:"button",onClick:c,"data-testid":"first-run-prev-btn","aria-label":"Previous language",className:"flex items-center justify-center w-12 h-12 sm:w-14 sm:h-14 rounded-full glass border border-primary/30 text-primary hover:bg-primary/15 active:scale-95 transition shrink-0",children:p.jsx(vz,{className:"w-6 h-6"})}),p.jsx("div",{className:"relative flex-1 h-44 sm:h-52 flex items-center justify-center overflow-hidden",children:p.jsx(Lo,{mode:"wait",initial:!1,custom:i,children:p.jsxs(gt.div,{custom:i,initial:d=>({x:d*280,rotate:d*18,opacity:0,scale:.7}),animate:{x:0,rotate:0,opacity:1,scale:1},exit:d=>({x:d*-280,rotate:d*-18,opacity:0,scale:.7}),transition:{type:"spring",stiffness:220,damping:22},className:"absolute flex flex-col items-center gap-3","data-testid":`first-run-flag-${o.code}`,children:[p.jsx("div",{className:"w-32 h-32 sm:w-40 sm:h-40 rounded-3xl glass-card flex items-center justify-center",style:{border:"1px solid hsla(40, 80%, 55%, 0.45)",boxShadow:"0 0 60px hsla(40, 80%, 55%, 0.35), inset 0 0 30px hsla(40, 80%, 55%, 0.08)"},children:p.jsx("span",{className:"text-7xl sm:text-8xl leading-none select-none",style:{filter:"drop-shadow(0 0 20px hsla(40, 80%, 55%, 0.4))"},children:o.flag})}),p.jsxs("div",{className:"text-center",children:[p.jsx("div",{className:"font-display text-xl sm:text-2xl gold-text tracking-[0.2em]",children:o.label}),p.jsx("div",{className:"text-[10px] uppercase tracking-[0.4em] text-muted-foreground mt-1",children:o.code.toUpperCase()})]})]},o.code)})}),p.jsx("button",{type:"button",onClick:l,"data-testid":"first-run-next-btn","aria-label":"Next language",className:"flex items-center justify-center w-12 h-12 sm:w-14 sm:h-14 rounded-full glass border border-primary/30 text-primary hover:bg-primary/15 active:scale-95 transition shrink-0",children:p.jsx(bz,{className:"w-6 h-6"})})]}),p.jsx("div",{className:"relative z-10 flex items-center gap-2 mt-6",children:Gi.map((d,h)=>p.jsx("button",{type:"button",onClick:()=>{a(h>r?1:-1),s(h)},"data-testid":`first-run-dot-${d.code}`,"aria-label":`Select ${d.label}`,className:`h-2 rounded-full transition-all ${h===r?"w-8 bg-primary shadow-[0_0_12px_hsla(40,80%,55%,0.6)]":"w-2 bg-muted-foreground/30 hover:bg-muted-foreground/60"}`},d.code))}),p.jsx(gt.button,{type:"button",onClick:u,"data-testid":"first-run-continue-btn",whileHover:{scale:1.03},whileTap:{scale:.97},className:"relative z-10 mt-10 px-10 py-3 rounded-full bg-primary text-primary-foreground font-semibold tracking-[0.3em] uppercase text-sm shadow-[0_8px_30px_hsla(40,80%,55%,0.4)] hover:brightness-110",children:n("firstRun.continue")}),p.jsx("p",{className:"relative z-10 mt-4 text-[10px] uppercase tracking-[0.3em] text-muted-foreground/70",children:n("firstRun.hint")})]})},aye=typeof window<"u"&&window.location&&window.location.protocol==="file:",oye=aye?vK:yK,lye=new oG,cye="nadiplay_splash_shown",Hu=({children:t})=>{const{user:e,isGuest:n,loading:r}=ys(),s=Qi();return r?null:!e&&!n?p.jsx(p0,{to:"/welcome",replace:!0,state:{from:s.pathname}}):(e==null?void 0:e.role)==="admin"&&s.pathname==="/"?p.jsx(p0,{to:"/admin",replace:!0}):p.jsx(p.Fragment,{children:t})},kO=({children:t})=>{const{user:e,loading:n}=ys();return n?null:e?e.role!=="admin"?p.jsx(p0,{to:"/",replace:!0}):p.jsx(p.Fragment,{children:t}):p.jsx(p0,{to:"/login",replace:!0})},uye=()=>{const{user:t}=ys();return ose(t?{id:t.id,role:t.role}:null),fse(t?{id:t.id,role:t.role}:null),mse(),vse(),p.jsxs(cK,{children:[p.jsx(jr,{path:"/welcome",element:p.jsx(yue,{})}),p.jsx(jr,{path:"/login",element:p.jsx(vue,{})}),p.jsx(jr,{path:"/connect",element:p.jsx(kue,{})}),p.jsx(jr,{path:"/select-profile",element:p.jsx(Hu,{children:p.jsx(Lue,{})})}),p.jsx(jr,{path:"/admin",element:p.jsx(kO,{children:p.jsx(Eue,{})})}),p.jsx(jr,{path:"/admin/broadcast",element:p.jsx(kO,{children:p.jsx(Cue,{})})}),p.jsx(jr,{path:"/",element:p.jsx(Hu,{children:p.jsx(Fue,{})})}),p.jsx(jr,{path:"/live-tv",element:p.jsx(Hu,{children:p.jsx(vge,{})})}),p.jsx(jr,{path:"/movies",element:p.jsx(Hu,{children:p.jsx(_ge,{})})}),p.jsx(jr,{path:"/series",element:p.jsx(Hu,{children:p.jsx(bge,{})})}),p.jsx(jr,{path:"/account",element:p.jsx(Hu,{children:p.jsx(Rge,{})})}),p.jsx(jr,{path:"/activate",element:p.jsx(Bge,{})}),p.jsx(jr,{path:"/pair",element:p.jsx($ge,{})}),p.jsx(jr,{path:"/subscription",element:p.jsx(Vge,{})}),p.jsx(jr,{path:"/privacy",element:p.jsx(zge,{})}),p.jsx(jr,{path:"*",element:p.jsx(Gge,{})})]})},dye=()=>{const[t,e]=C.useState(()=>{if(typeof window>"u")return!1;try{return sessionStorage.getItem(cye)!=="1"}catch{return!0}}),[n,r]=C.useState(()=>typeof window>"u"?!1:!sye());return p.jsx(lG,{client:lye,children:p.jsx(PW,{children:p.jsx(Ple,{children:p.jsxs(lse,{children:[t&&p.jsx(Ree,{onFinish:()=>e(!1)}),!t&&n&&p.jsx(iye,{onFinish:()=>r(!1)}),p.jsx(Yq,{}),p.jsx(ZK,{}),p.jsxs(oye,{children:[p.jsx(nye,{}),p.jsx(uye,{}),p.jsx(Qge,{}),!t&&!n&&p.jsx(rye,{})]})]})})})})};class hye extends Be.Component{constructor(){super(...arguments);qm(this,"state",{error:null});qm(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?p.jsx("div",{className:"min-h-screen flex items-center justify-center p-6 bg-background",children:p.jsxs("div",{className:"glass-card rounded-2xl p-6 max-w-md text-center",children:[p.jsx("p",{className:"text-foreground text-sm font-medium mb-2",children:"Something went wrong rendering this page."}),p.jsx("p",{className:"text-muted-foreground text-[11px] break-all mb-4",children:this.state.error.message}),p.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"}),p.jsx("p",{className:"text-muted-foreground text-[10px] mt-3",children:"(This error is contained — your current stream keeps playing.)"})]})}):this.props.children}}globalThis.__NDP_OWNER__=Object.freeze({author:"Nadifi abdessamad",email:"nadiplayer@nadi.kr",website:"https://nadi.kr",copyright:"(c) 2026 Nadi Player",repo:"https://github.com/ghizlanefit-cell/Nadiplayer-v1.2.5-ads",build:"v1.2.5-ads"});NV.createRoot(document.getElementById("root")).render(p.jsx(hye,{children:p.jsx(dye,{})}));export{EO as A,_3 as W,pu as r};
