@kinxcdn/commerce-player 1.6.4-alpha.5 → 1.6.5-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commerce-player.min.js +2 -2
- package/dist/esm/index.js +3 -3
- package/dist/styles.css +2 -2
- package/package.json +1 -1
|
@@ -32,7 +32,7 @@ var Yn={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24
|
|
|
32
32
|
*
|
|
33
33
|
* This source code is licensed under the ISC license.
|
|
34
34
|
* See the LICENSE file in the root directory of this source tree.
|
|
35
|
-
*/function ci({message:e,duration:t=3e3,visible:r,setVisible:n}){return p.useEffect(()=>{const e=setTimeout(()=>n(!1),t);return()=>clearTimeout(e)},[r]),r?g.createElement("div",{style:{position:"fixed",top:"1rem",left:"50%",transform:"translateX(-50%)",background:"rgba(0,0,0,0.8)",color:"#fff",padding:"0.75rem 1.25rem",borderRadius:"0.375rem",fontSize:"14px",zIndex:9999,boxShadow:"0 2px 10px rgba(0,0,0,0.2)"}},e):null}const di=({shortForm:e,shareUrl:t})=>{const r=null!=t?t:window.location.href,[n,i]=p.useState(!1);return g.createElement(g.Fragment,null,g.createElement("button",{onClick:()=>J(void 0,void 0,void 0,function*(){try{i(!0),Hn.isMobile&&navigator.share&&e?yield navigator.share({title:e.title,url:r}):(e=>{if(void 0!==navigator.clipboard)navigator.clipboard.writeText(e).then(()=>{});else{const t=document.createElement("textarea");t.value=e,document.body.appendChild(t),t.select(),t.setSelectionRange(0,99999);try{document.execCommand("copy")}catch(e){console.error("복사 실패",e)}t.setSelectionRange(0,0),document.body.removeChild(t)}})(r)}catch(e){console.error("Fail to copy on clipboard")}}),className:"cursor-pointer"},g.createElement(ni,{size:22}),g.createElement(ci,{message:"공유 링크 복사 완료",setVisible:i,visible:n})))},hi=({width:e,height:t})=>g.createElement("div",{className:"w-full h-full flex items-center justify-center"},g.createElement("img",{src:"public/images/noImage.svg",alt:"no image",width:e||50,height:t||50})),fi=({product:e,onError:t})=>g.createElement("img",{src:e.thumbPath,alt:e.productName,className:"object-cover p-0 flex-none",style:{height:"80px",width:"80px"},onError:t}),pi=({product:e,hideMoreBtn:t,contentId:r})=>{const{isPreview:n,priceText:i}=cr(),[s,a]=p.useState(!1);return g.createElement("div",{style:{height:"80px"},className:"flex gap-2 items-center w-full",onClick:()=>J(void 0,void 0,void 0,function*(){t&&(window.open(e.linkPath,"_blank"),n||(yield Zt({contentProductId:e.eventProductId,contentId:r,productId:e.productId})))})},e.thumbPath&&!s?g.createElement(fi,{product:e,onError:()=>a(!0)}):g.createElement(hi,null),g.createElement("div",{className:"flex flex-col text-left p-2 w-full justify-center"},e.brand&&g.createElement("span",{className:"break-keep line-clamp-1 text-gray-500",style:{fontSize:"10px"}},e.brand.brandName),g.createElement("div",{className:"text-gray-800 text-ellipsis line-clamp-1 ",style:{fontSize:"12px"}},e.productName),g.createElement("div",{className:"text-red-500 break-keep",style:{fontSize:"12px"}},i?i+" ":"할인가 ",g.createElement("span",{className:"font-semibold break-keep"},$t(e.sellingPrice),"원"))))};function gi(e,t,{checkForDefaultPrevented:r=!0}={}){return function(n){if(e?.(n),!1===r||!n.defaultPrevented)return t?.(n)}}function mi(e,t){if("function"==typeof e)return e(t);null!=e&&(e.current=t)}function vi(...e){return t=>{let r=!1;const n=e.map(e=>{const n=mi(e,t);return r||"function"!=typeof n||(r=!0),n});if(r)return()=>{for(let t=0;t<n.length;t++){const r=n[t];"function"==typeof r?r():mi(e[t],null)}}}}function yi(...e){return p.useCallback(vi(...e),e)}var bi,wi,Ei={exports:{}},Si={};var Ti=(wi||(wi=1,Ei.exports=function(){if(bi)return Si;bi=1;var e=l(),t=Symbol.for("react.element"),r=Symbol.for("react.fragment"),n=Object.prototype.hasOwnProperty,i=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,s={key:!0,ref:!0,__self:!0,__source:!0};function a(e,r,a){var o,l={},u=null,c=null;for(o in void 0!==a&&(u=""+a),void 0!==r.key&&(u=""+r.key),void 0!==r.ref&&(c=r.ref),r)n.call(r,o)&&!s.hasOwnProperty(o)&&(l[o]=r[o]);if(e&&e.defaultProps)for(o in r=e.defaultProps)void 0===l[o]&&(l[o]=r[o]);return{$$typeof:t,type:e,key:u,ref:c,props:l,_owner:i.current}}return Si.Fragment=r,Si.jsx=a,Si.jsxs=a,Si}()),Ei.exports);function xi(...e){const t=e[0];if(1===e.length)return t;const r=()=>{const r=e.map(e=>({useScope:e(),scopeName:e.scopeName}));return function(e){const n=r.reduce((t,{useScope:r,scopeName:n})=>({...t,...r(e)[`__scope${n}`]}),{});return p.useMemo(()=>({[`__scope${t.scopeName}`]:n}),[n])}};return r.scopeName=t.scopeName,r}var ki=globalThis?.document?p.useLayoutEffect:()=>{},Ai=m[" useId ".trim().toString()]||(()=>{}),Ri=0;function Li(e){const[t,r]=p.useState(Ai());return ki(()=>{e||r(e=>e??String(Ri++))},[e]),e||(t?`radix-${t}`:"")}var Ii=m[" useInsertionEffect ".trim().toString()]||ki;function Ci({prop:e,defaultProp:t,onChange:r=()=>{},caller:n}){const[i,s,a]=function({defaultProp:e,onChange:t}){const[r,n]=p.useState(e),i=p.useRef(r),s=p.useRef(t);return Ii(()=>{s.current=t},[t]),p.useEffect(()=>{i.current!==r&&(s.current?.(r),i.current=r)},[r,i]),[r,n,s]}({defaultProp:t,onChange:r}),o=void 0!==e,l=o?e:i;{const t=p.useRef(void 0!==e);p.useEffect(()=>{const e=t.current;if(e!==o){const t=e?"controlled":"uncontrolled",r=o?"controlled":"uncontrolled";console.warn(`${n} is changing from ${t} to ${r}. 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.`)}t.current=o},[o,n])}const u=p.useCallback(t=>{if(o){const r=function(e){return"function"==typeof e}(t)?t(e):t;r!==e&&a.current?.(r)}else s(t)},[o,e,s,a]);return[l,u]}var Pi=x(),Di=t(Pi);function _i(e){const t=Mi(e),r=p.forwardRef((e,r)=>{const{children:n,...i}=e,s=p.Children.toArray(n),a=s.find(Ni);if(a){const e=a.props.children,n=s.map(t=>t===a?p.Children.count(e)>1?p.Children.only(null):p.isValidElement(e)?e.props.children:null:t);return Ti.jsx(t,{...i,ref:r,children:p.isValidElement(e)?p.cloneElement(e,void 0,n):null})}return Ti.jsx(t,{...i,ref:r,children:n})});return r.displayName=`${e}.Slot`,r}function Mi(e){const t=p.forwardRef((e,t)=>{const{children:r,...n}=e;if(p.isValidElement(r)){const e=function(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;if(r)return e.ref;if(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r)return e.props.ref;return e.props.ref||e.ref}(r),i=function(e,t){const r={...t};for(const n in t){const i=e[n],s=t[n];/^on[A-Z]/.test(n)?i&&s?r[n]=(...e)=>{const t=s(...e);return i(...e),t}:i&&(r[n]=i):"style"===n?r[n]={...i,...s}:"className"===n&&(r[n]=[i,s].filter(Boolean).join(" "))}return{...e,...r}}(n,r.props);return r.type!==p.Fragment&&(i.ref=t?vi(t,e):e),p.cloneElement(r,i)}return p.Children.count(r)>1?p.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Oi=Symbol("radix.slottable");function Ni(e){return p.isValidElement(e)&&"function"==typeof e.type&&"__radixId"in e.type&&e.type.__radixId===Oi}var Fi=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,t)=>{const r=_i(`Primitive.${t}`),n=p.forwardRef((e,n)=>{const{asChild:i,...s}=e,a=i?r:t;return"undefined"!=typeof window&&(window[Symbol.for("radix-ui")]=!0),Ti.jsx(a,{...s,ref:n})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function $i(e){const t=p.useRef(e);return p.useEffect(()=>{t.current=e}),p.useMemo(()=>(...e)=>t.current?.(...e),[])}function Bi(e,t=globalThis?.document){const r=$i(e);p.useEffect(()=>{const e=e=>{"Escape"===e.key&&r(e)};return t.addEventListener("keydown",e,{capture:!0}),()=>t.removeEventListener("keydown",e,{capture:!0})},[r,t])}var Ui,zi="dismissableLayer.update",ji="dismissableLayer.pointerDownOutside",Gi="dismissableLayer.focusOutside",Hi=p.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Vi=p.forwardRef((e,t)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:n,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:a,onDismiss:o,...l}=e,u=p.useContext(Hi),[c,d]=p.useState(null),h=c?.ownerDocument??globalThis?.document,[,f]=p.useState({}),g=yi(t,e=>d(e)),m=Array.from(u.layers),[v]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),y=m.indexOf(v),b=c?m.indexOf(c):-1,w=u.layersWithOutsidePointerEventsDisabled.size>0,E=b>=y,S=function(e,t=globalThis?.document){const r=$i(e),n=p.useRef(!1),i=p.useRef(()=>{});return p.useEffect(()=>{const e=e=>{if(e.target&&!n.current){let n=function(){Ki(ji,r,s,{discrete:!0})};const s={originalEvent:e};"touch"===e.pointerType?(t.removeEventListener("click",i.current),i.current=n,t.addEventListener("click",i.current,{once:!0})):n()}else t.removeEventListener("click",i.current);n.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",e)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",e),t.removeEventListener("click",i.current)}},[t,r]),{onPointerDownCapture:()=>n.current=!0}}(e=>{const t=e.target,r=[...u.branches].some(e=>e.contains(t));E&&!r&&(i?.(e),a?.(e),e.defaultPrevented||o?.())},h),T=function(e,t=globalThis?.document){const r=$i(e),n=p.useRef(!1);return p.useEffect(()=>{const e=e=>{if(e.target&&!n.current){Ki(Gi,r,{originalEvent:e},{discrete:!1})}};return t.addEventListener("focusin",e),()=>t.removeEventListener("focusin",e)},[t,r]),{onFocusCapture:()=>n.current=!0,onBlurCapture:()=>n.current=!1}}(e=>{const t=e.target;[...u.branches].some(e=>e.contains(t))||(s?.(e),a?.(e),e.defaultPrevented||o?.())},h);return Bi(e=>{b===u.layers.size-1&&(n?.(e),!e.defaultPrevented&&o&&(e.preventDefault(),o()))},h),p.useEffect(()=>{if(c)return r&&(0===u.layersWithOutsidePointerEventsDisabled.size&&(Ui=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(c)),u.layers.add(c),Wi(),()=>{r&&1===u.layersWithOutsidePointerEventsDisabled.size&&(h.body.style.pointerEvents=Ui)}},[c,h,r,u]),p.useEffect(()=>()=>{c&&(u.layers.delete(c),u.layersWithOutsidePointerEventsDisabled.delete(c),Wi())},[c,u]),p.useEffect(()=>{const e=()=>f({});return document.addEventListener(zi,e),()=>document.removeEventListener(zi,e)},[]),Ti.jsx(Fi.div,{...l,ref:g,style:{pointerEvents:w?E?"auto":"none":void 0,...e.style},onFocusCapture:gi(e.onFocusCapture,T.onFocusCapture),onBlurCapture:gi(e.onBlurCapture,T.onBlurCapture),onPointerDownCapture:gi(e.onPointerDownCapture,S.onPointerDownCapture)})});Vi.displayName="DismissableLayer";function Wi(){const e=new CustomEvent(zi);document.dispatchEvent(e)}function Ki(e,t,r,{discrete:n}){const i=r.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:r});t&&i.addEventListener(e,t,{once:!0}),n?function(e,t){e&&Pi.flushSync(()=>e.dispatchEvent(t))}(i,s):i.dispatchEvent(s)}p.forwardRef((e,t)=>{const r=p.useContext(Hi),n=p.useRef(null),i=yi(t,n);return p.useEffect(()=>{const e=n.current;if(e)return r.branches.add(e),()=>{r.branches.delete(e)}},[r.branches]),Ti.jsx(Fi.div,{...e,ref:i})}).displayName="DismissableLayerBranch";var Yi="focusScope.autoFocusOnMount",qi="focusScope.autoFocusOnUnmount",Xi={bubbles:!1,cancelable:!0},Qi=p.forwardRef((e,t)=>{const{loop:r=!1,trapped:n=!1,onMountAutoFocus:i,onUnmountAutoFocus:s,...a}=e,[o,l]=p.useState(null),u=$i(i),c=$i(s),d=p.useRef(null),h=yi(t,e=>l(e)),f=p.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;p.useEffect(()=>{if(n){let e=function(e){if(f.paused||!o)return;const t=e.target;o.contains(t)?d.current=t:ts(d.current,{select:!0})},t=function(e){if(f.paused||!o)return;const t=e.relatedTarget;null!==t&&(o.contains(t)||ts(d.current,{select:!0}))},r=function(e){if(document.activeElement===document.body)for(const t of e)t.removedNodes.length>0&&ts(o)};document.addEventListener("focusin",e),document.addEventListener("focusout",t);const n=new MutationObserver(r);return o&&n.observe(o,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",e),document.removeEventListener("focusout",t),n.disconnect()}}},[n,o,f.paused]),p.useEffect(()=>{if(o){rs.add(f);const t=document.activeElement;if(!o.contains(t)){const r=new CustomEvent(Yi,Xi);o.addEventListener(Yi,u),o.dispatchEvent(r),r.defaultPrevented||(!function(e,{select:t=!1}={}){const r=document.activeElement;for(const n of e)if(ts(n,{select:t}),document.activeElement!==r)return}((e=Zi(o),e.filter(e=>"A"!==e.tagName)),{select:!0}),document.activeElement===t&&ts(o))}return()=>{o.removeEventListener(Yi,u),setTimeout(()=>{const e=new CustomEvent(qi,Xi);o.addEventListener(qi,c),o.dispatchEvent(e),e.defaultPrevented||ts(t??document.body,{select:!0}),o.removeEventListener(qi,c),rs.remove(f)},0)}}var e},[o,u,c,f]);const g=p.useCallback(e=>{if(!r&&!n)return;if(f.paused)return;const t="Tab"===e.key&&!e.altKey&&!e.ctrlKey&&!e.metaKey,i=document.activeElement;if(t&&i){const t=e.currentTarget,[n,s]=function(e){const t=Zi(e),r=Ji(t,e),n=Ji(t.reverse(),e);return[r,n]}(t);n&&s?e.shiftKey||i!==s?e.shiftKey&&i===n&&(e.preventDefault(),r&&ts(s,{select:!0})):(e.preventDefault(),r&&ts(n,{select:!0})):i===t&&e.preventDefault()}},[r,n,f.paused]);return Ti.jsx(Fi.div,{tabIndex:-1,...a,ref:h,onKeyDown:g})});function Zi(e){const t=[],r=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:e=>{const t="INPUT"===e.tagName&&"hidden"===e.type;return e.disabled||e.hidden||t?NodeFilter.FILTER_SKIP:e.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)t.push(r.currentNode);return t}function Ji(e,t){for(const r of e)if(!es(r,{upTo:t}))return r}function es(e,{upTo:t}){if("hidden"===getComputedStyle(e).visibility)return!0;for(;e;){if(void 0!==t&&e===t)return!1;if("none"===getComputedStyle(e).display)return!0;e=e.parentElement}return!1}function ts(e,{select:t=!1}={}){if(e&&e.focus){const r=document.activeElement;e.focus({preventScroll:!0}),e!==r&&function(e){return e instanceof HTMLInputElement&&"select"in e}(e)&&t&&e.select()}}Qi.displayName="FocusScope";var rs=function(){let e=[];return{add(t){const r=e[0];t!==r&&r?.pause(),e=ns(e,t),e.unshift(t)},remove(t){e=ns(e,t),e[0]?.resume()}}}();function ns(e,t){const r=[...e],n=r.indexOf(t);return-1!==n&&r.splice(n,1),r}var is=p.forwardRef((e,t)=>{const{container:r,...n}=e,[i,s]=p.useState(!1);ki(()=>s(!0),[]);const a=r||i&&globalThis?.document?.body;return a?Di.createPortal(Ti.jsx(Fi.div,{...n,ref:t}),a):null});is.displayName="Portal";var ss=e=>{const{present:t,children:r}=e,n=function(e){const[t,r]=p.useState(),n=p.useRef(null),i=p.useRef(e),s=p.useRef("none"),a=e?"mounted":"unmounted",[o,l]=function(e,t){return p.useReducer((e,r)=>t[e][r]??e,e)}(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return p.useEffect(()=>{const e=as(n.current);s.current="mounted"===o?e:"none"},[o]),ki(()=>{const t=n.current,r=i.current;if(r!==e){const n=s.current,a=as(t);if(e)l("MOUNT");else if("none"===a||"none"===t?.display)l("UNMOUNT");else{l(r&&n!==a?"ANIMATION_OUT":"UNMOUNT")}i.current=e}},[e,l]),ki(()=>{if(t){let e;const r=t.ownerDocument.defaultView??window,a=s=>{const a=as(n.current).includes(s.animationName);if(s.target===t&&a&&(l("ANIMATION_END"),!i.current)){const n=t.style.animationFillMode;t.style.animationFillMode="forwards",e=r.setTimeout(()=>{"forwards"===t.style.animationFillMode&&(t.style.animationFillMode=n)})}},o=e=>{e.target===t&&(s.current=as(n.current))};return t.addEventListener("animationstart",o),t.addEventListener("animationcancel",a),t.addEventListener("animationend",a),()=>{r.clearTimeout(e),t.removeEventListener("animationstart",o),t.removeEventListener("animationcancel",a),t.removeEventListener("animationend",a)}}l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(o),ref:p.useCallback(e=>{n.current=e?getComputedStyle(e):null,r(e)},[])}}(t),i="function"==typeof r?r({present:n.isPresent}):p.Children.only(r),s=yi(n.ref,function(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;if(r)return e.ref;if(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r)return e.props.ref;return e.props.ref||e.ref}(i));return"function"==typeof r||n.isPresent?p.cloneElement(i,{ref:s}):null};function as(e){return e?.animationName||"none"}ss.displayName="Presence";var os=0;function ls(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var us="right-scroll-bar-position",cs="width-before-scroll-bar";function ds(e,t){return"function"==typeof e?e(t):e&&(e.current=t),e}var hs="undefined"!=typeof window?p.useLayoutEffect:p.useEffect,fs=new WeakMap;function ps(e,t){var r,n,i,s=(r=null,n=function(t){return e.forEach(function(e){return ds(e,t)})},(i=p.useState(function(){return{value:r,callback:n,facade:{get current(){return i.value},set current(e){var t=i.value;t!==e&&(i.value=e,i.callback(e,t))}}}})[0]).callback=n,i.facade);return hs(function(){var t=fs.get(s);if(t){var r=new Set(t),n=new Set(e),i=s.current;r.forEach(function(e){n.has(e)||ds(e,null)}),n.forEach(function(e){r.has(e)||ds(e,i)})}fs.set(s,e)},[e]),s}function gs(e){return e}var ms=function(e){var t=e.sideCar,r=Z(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var n=t.read();if(!n)throw new Error("Sidecar medium not found");return p.createElement(n,Q({},r))};ms.isSideCarExport=!0;var vs=function(e){void 0===e&&(e={});var t=function(e,t){void 0===t&&(t=gs);var r=[],n=!1,i={read:function(){if(n)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return r.length?r[r.length-1]:e},useMedium:function(e){var i=t(e,n);return r.push(i),function(){r=r.filter(function(e){return e!==i})}},assignSyncMedium:function(e){for(n=!0;r.length;){var t=r;r=[],t.forEach(e)}r={push:function(t){return e(t)},filter:function(){return r}}},assignMedium:function(e){n=!0;var t=[];if(r.length){var i=r;r=[],i.forEach(e),t=r}var s=function(){var r=t;t=[],r.forEach(e)},a=function(){return Promise.resolve().then(s)};a(),r={push:function(e){t.push(e),a()},filter:function(e){return t=t.filter(e),r}}}};return i}(null);return t.options=Q({async:!0,ssr:!1},e),t}(),ys=function(){},bs=p.forwardRef(function(e,t){var r=p.useRef(null),n=p.useState({onScrollCapture:ys,onWheelCapture:ys,onTouchMoveCapture:ys}),i=n[0],s=n[1],a=e.forwardProps,o=e.children,l=e.className,u=e.removeScrollBar,c=e.enabled,d=e.shards,h=e.sideCar,f=e.noRelative,g=e.noIsolation,m=e.inert,v=e.allowPinchZoom,y=e.as,b=void 0===y?"div":y,w=e.gapMode,E=Z(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),S=h,T=ps([r,t]),x=Q(Q({},E),i);return p.createElement(p.Fragment,null,c&&p.createElement(S,{sideCar:vs,removeScrollBar:u,shards:d,noRelative:f,noIsolation:g,inert:m,setCallbacks:s,allowPinchZoom:!!v,lockRef:r,gapMode:w}),a?p.cloneElement(p.Children.only(o),Q(Q({},x),{ref:T})):p.createElement(b,Q({},x,{className:l,ref:T}),o))});bs.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},bs.classNames={fullWidth:cs,zeroRight:us};function ws(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=function(){if("undefined"!=typeof __webpack_nonce__)return __webpack_nonce__}();return t&&e.setAttribute("nonce",t),e}var Es=function(){var e=0,t=null;return{add:function(r){var n,i;0==e&&(t=ws())&&(i=r,(n=t).styleSheet?n.styleSheet.cssText=i:n.appendChild(document.createTextNode(i)),function(e){(document.head||document.getElementsByTagName("head")[0]).appendChild(e)}(t)),e++},remove:function(){! --e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Ss=function(){var e,t=(e=Es(),function(t,r){p.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&r])});return function(e){var r=e.styles,n=e.dynamic;return t(r,n),null}},Ts={left:0,top:0,right:0,gap:0},xs=function(e){return parseInt(e||"",10)||0},ks=function(e){if(void 0===e&&(e="margin"),"undefined"==typeof window)return Ts;var t=function(e){var t=window.getComputedStyle(document.body),r=t["padding"===e?"paddingLeft":"marginLeft"],n=t["padding"===e?"paddingTop":"marginTop"],i=t["padding"===e?"paddingRight":"marginRight"];return[xs(r),xs(n),xs(i)]}(e),r=document.documentElement.clientWidth,n=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,n-r+t[2]-t[0])}},As=Ss(),Rs="data-scroll-locked",Ls=function(e,t,r,n){var i=e.left,s=e.top,a=e.right,o=e.gap;return void 0===r&&(r="margin"),"\n .".concat("with-scroll-bars-hidden"," {\n overflow: hidden ").concat(n,";\n padding-right: ").concat(o,"px ").concat(n,";\n }\n body[").concat(Rs,"] {\n overflow: hidden ").concat(n,";\n overscroll-behavior: contain;\n ").concat([t&&"position: relative ".concat(n,";"),"margin"===r&&"\n padding-left: ".concat(i,"px;\n padding-top: ").concat(s,"px;\n padding-right: ").concat(a,"px;\n margin-left:0;\n margin-top:0;\n margin-right: ").concat(o,"px ").concat(n,";\n "),"padding"===r&&"padding-right: ".concat(o,"px ").concat(n,";")].filter(Boolean).join(""),"\n }\n \n .").concat(us," {\n right: ").concat(o,"px ").concat(n,";\n }\n \n .").concat(cs," {\n margin-right: ").concat(o,"px ").concat(n,";\n }\n \n .").concat(us," .").concat(us," {\n right: 0 ").concat(n,";\n }\n \n .").concat(cs," .").concat(cs," {\n margin-right: 0 ").concat(n,";\n }\n \n body[").concat(Rs,"] {\n ").concat("--removed-body-scroll-bar-size",": ").concat(o,"px;\n }\n")},Is=function(){var e=parseInt(document.body.getAttribute(Rs)||"0",10);return isFinite(e)?e:0},Cs=function(e){var t=e.noRelative,r=e.noImportant,n=e.gapMode,i=void 0===n?"margin":n;p.useEffect(function(){return document.body.setAttribute(Rs,(Is()+1).toString()),function(){var e=Is()-1;e<=0?document.body.removeAttribute(Rs):document.body.setAttribute(Rs,e.toString())}},[]);var s=p.useMemo(function(){return ks(i)},[i]);return p.createElement(As,{styles:Ls(s,!t,i,r?"":"!important")})},Ps=!1;if("undefined"!=typeof window)try{var Ds=Object.defineProperty({},"passive",{get:function(){return Ps=!0,!0}});window.addEventListener("test",Ds,Ds),window.removeEventListener("test",Ds,Ds)}catch(e){Ps=!1}var _s=!!Ps&&{passive:!1},Ms=function(e,t){if(!(e instanceof Element))return!1;var r=window.getComputedStyle(e);return"hidden"!==r[t]&&!(r.overflowY===r.overflowX&&!function(e){return"TEXTAREA"===e.tagName}(e)&&"visible"===r[t])},Os=function(e,t){var r=t.ownerDocument,n=t;do{if("undefined"!=typeof ShadowRoot&&n instanceof ShadowRoot&&(n=n.host),Ns(e,n)){var i=Fs(e,n);if(i[1]>i[2])return!0}n=n.parentNode}while(n&&n!==r.body);return!1},Ns=function(e,t){return"v"===e?function(e){return Ms(e,"overflowY")}(t):function(e){return Ms(e,"overflowX")}(t)},Fs=function(e,t){return"v"===e?[(r=t).scrollTop,r.scrollHeight,r.clientHeight]:function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]}(t);var r},$s=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Bs=function(e){return[e.deltaX,e.deltaY]},Us=function(e){return e&&"current"in e?e.current:e},zs=function(e){return"\n .block-interactivity-".concat(e," {pointer-events: none;}\n .allow-interactivity-").concat(e," {pointer-events: all;}\n")},js=0,Gs=[];function Hs(e){for(var t=null;null!==e;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var Vs,Ws=(Vs=function(e){var t=p.useRef([]),r=p.useRef([0,0]),n=p.useRef(),i=p.useState(js++)[0],s=p.useState(Ss)[0],a=p.useRef(e);p.useEffect(function(){a.current=e},[e]),p.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var t=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,s=t.length;i<s;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))}([e.lockRef.current],(e.shards||[]).map(Us),!0).filter(Boolean);return t.forEach(function(e){return e.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),t.forEach(function(e){return e.classList.remove("allow-interactivity-".concat(i))})}}},[e.inert,e.lockRef.current,e.shards]);var o=p.useCallback(function(e,t){if("touches"in e&&2===e.touches.length||"wheel"===e.type&&e.ctrlKey)return!a.current.allowPinchZoom;var i,s=$s(e),o=r.current,l="deltaX"in e?e.deltaX:o[0]-s[0],u="deltaY"in e?e.deltaY:o[1]-s[1],c=e.target,d=Math.abs(l)>Math.abs(u)?"h":"v";if("touches"in e&&"h"===d&&"range"===c.type)return!1;var h=Os(d,c);if(!h)return!0;if(h?i=d:(i="v"===d?"h":"v",h=Os(d,c)),!h)return!1;if(!n.current&&"changedTouches"in e&&(l||u)&&(n.current=i),!i)return!0;var f=n.current||i;return function(e,t,r,n,i){var s=function(e,t){return"h"===e&&"rtl"===t?-1:1}(e,window.getComputedStyle(t).direction),a=s*n,o=r.target,l=t.contains(o),u=!1,c=a>0,d=0,h=0;do{if(!o)break;var f=Fs(e,o),p=f[0],g=f[1]-f[2]-s*p;(p||g)&&Ns(e,o)&&(d+=g,h+=p);var m=o.parentNode;o=m&&m.nodeType===Node.DOCUMENT_FRAGMENT_NODE?m.host:m}while(!l&&o!==document.body||l&&(t.contains(o)||t===o));return c&&(Math.abs(d)<1||!i)?u=!0:c||!(Math.abs(h)<1)&&i||(u=!0),u}(f,t,e,"h"===f?l:u,!0)},[]),l=p.useCallback(function(e){var r=e;if(Gs.length&&Gs[Gs.length-1]===s){var n="deltaY"in r?Bs(r):$s(r),i=t.current.filter(function(e){return e.name===r.type&&(e.target===r.target||r.target===e.shadowParent)&&function(e,t){return e[0]===t[0]&&e[1]===t[1]}(e.delta,n)})[0];if(i&&i.should)r.cancelable&&r.preventDefault();else if(!i){var l=(a.current.shards||[]).map(Us).filter(Boolean).filter(function(e){return e.contains(r.target)});(l.length>0?o(r,l[0]):!a.current.noIsolation)&&r.cancelable&&r.preventDefault()}}},[]),u=p.useCallback(function(e,r,n,i){var s={name:e,delta:r,target:n,should:i,shadowParent:Hs(n)};t.current.push(s),setTimeout(function(){t.current=t.current.filter(function(e){return e!==s})},1)},[]),c=p.useCallback(function(e){r.current=$s(e),n.current=void 0},[]),d=p.useCallback(function(t){u(t.type,Bs(t),t.target,o(t,e.lockRef.current))},[]),h=p.useCallback(function(t){u(t.type,$s(t),t.target,o(t,e.lockRef.current))},[]);p.useEffect(function(){return Gs.push(s),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:h}),document.addEventListener("wheel",l,_s),document.addEventListener("touchmove",l,_s),document.addEventListener("touchstart",c,_s),function(){Gs=Gs.filter(function(e){return e!==s}),document.removeEventListener("wheel",l,_s),document.removeEventListener("touchmove",l,_s),document.removeEventListener("touchstart",c,_s)}},[]);var f=e.removeScrollBar,g=e.inert;return p.createElement(p.Fragment,null,g?p.createElement(s,{styles:zs(i)}):null,f?p.createElement(Cs,{noRelative:e.noRelative,gapMode:e.gapMode}):null)},vs.useMedium(Vs),ms),Ks=p.forwardRef(function(e,t){return p.createElement(bs,Q({},e,{ref:t,sideCar:Ws}))});Ks.classNames=bs.classNames;var Ys=new WeakMap,qs=new WeakMap,Xs={},Qs=0,Zs=function(e){return e&&(e.host||Zs(e.parentNode))},Js=function(e,t,r,n){var i=function(e,t){return t.map(function(t){if(e.contains(t))return t;var r=Zs(t);return r&&e.contains(r)?r:(console.error("aria-hidden",t,"in not contained inside",e,". Doing nothing"),null)}).filter(function(e){return Boolean(e)})}(t,Array.isArray(e)?e:[e]);Xs[r]||(Xs[r]=new WeakMap);var s=Xs[r],a=[],o=new Set,l=new Set(i),u=function(e){e&&!o.has(e)&&(o.add(e),u(e.parentNode))};i.forEach(u);var c=function(e){e&&!l.has(e)&&Array.prototype.forEach.call(e.children,function(e){if(o.has(e))c(e);else try{var t=e.getAttribute(n),i=null!==t&&"false"!==t,l=(Ys.get(e)||0)+1,u=(s.get(e)||0)+1;Ys.set(e,l),s.set(e,u),a.push(e),1===l&&i&&qs.set(e,!0),1===u&&e.setAttribute(r,"true"),i||e.setAttribute(n,"true")}catch(t){console.error("aria-hidden: cannot operate on ",e,t)}})};return c(t),o.clear(),Qs++,function(){a.forEach(function(e){var t=Ys.get(e)-1,i=s.get(e)-1;Ys.set(e,t),s.set(e,i),t||(qs.has(e)||e.removeAttribute(n),qs.delete(e)),i||e.removeAttribute(r)}),--Qs||(Ys=new WeakMap,Ys=new WeakMap,qs=new WeakMap,Xs={})}},ea=function(e,t,r){void 0===r&&(r="data-aria-hidden");var n=Array.from(Array.isArray(e)?e:[e]),i=function(e){return"undefined"==typeof document?null:(Array.isArray(e)?e[0]:e).ownerDocument.body}(e);return i?(n.push.apply(n,Array.from(i.querySelectorAll("[aria-live], script"))),Js(n,i,r,"aria-hidden")):function(){return null}},ta="Dialog",[ra,na]=function(e,t=[]){let r=[];const n=()=>{const t=r.map(e=>p.createContext(e));return function(r){const n=r?.[e]||t;return p.useMemo(()=>({[`__scope${e}`]:{...r,[e]:n}}),[r,n])}};return n.scopeName=e,[function(t,n){const i=p.createContext(n),s=r.length;r=[...r,n];const a=t=>{const{scope:r,children:n,...a}=t,o=r?.[e]?.[s]||i,l=p.useMemo(()=>a,Object.values(a));return Ti.jsx(o.Provider,{value:l,children:n})};return a.displayName=t+"Provider",[a,function(r,a){const o=a?.[e]?.[s]||i,l=p.useContext(o);if(l)return l;if(void 0!==n)return n;throw new Error(`\`${r}\` must be used within \`${t}\``)}]},xi(n,...t)]}(ta),[ia,sa]=ra(ta),aa=e=>{const{__scopeDialog:t,children:r,open:n,defaultOpen:i,onOpenChange:s,modal:a=!0}=e,o=p.useRef(null),l=p.useRef(null),[u,c]=Ci({prop:n,defaultProp:i??!1,onChange:s,caller:ta});return Ti.jsx(ia,{scope:t,triggerRef:o,contentRef:l,contentId:Li(),titleId:Li(),descriptionId:Li(),open:u,onOpenChange:c,onOpenToggle:p.useCallback(()=>c(e=>!e),[c]),modal:a,children:r})};aa.displayName=ta;var oa="DialogTrigger",la=p.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,i=sa(oa,r),s=yi(t,i.triggerRef);return Ti.jsx(Fi.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":La(i.open),...n,ref:s,onClick:gi(e.onClick,i.onOpenToggle)})});la.displayName=oa;var ua="DialogPortal",[ca,da]=ra(ua,{forceMount:void 0}),ha=e=>{const{__scopeDialog:t,forceMount:r,children:n,container:i}=e,s=sa(ua,t);return Ti.jsx(ca,{scope:t,forceMount:r,children:p.Children.map(n,e=>Ti.jsx(ss,{present:r||s.open,children:Ti.jsx(is,{asChild:!0,container:i,children:e})}))})};ha.displayName=ua;var fa="DialogOverlay",pa=p.forwardRef((e,t)=>{const r=da(fa,e.__scopeDialog),{forceMount:n=r.forceMount,...i}=e,s=sa(fa,e.__scopeDialog);return s.modal?Ti.jsx(ss,{present:n||s.open,children:Ti.jsx(ma,{...i,ref:t})}):null});pa.displayName=fa;var ga=_i("DialogOverlay.RemoveScroll"),ma=p.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,i=sa(fa,r);return Ti.jsx(Ks,{as:ga,allowPinchZoom:!0,shards:[i.contentRef],children:Ti.jsx(Fi.div,{"data-state":La(i.open),...n,ref:t,style:{pointerEvents:"auto",...n.style}})})}),va="DialogContent",ya=p.forwardRef((e,t)=>{const r=da(va,e.__scopeDialog),{forceMount:n=r.forceMount,...i}=e,s=sa(va,e.__scopeDialog);return Ti.jsx(ss,{present:n||s.open,children:s.modal?Ti.jsx(ba,{...i,ref:t}):Ti.jsx(wa,{...i,ref:t})})});ya.displayName=va;var ba=p.forwardRef((e,t)=>{const r=sa(va,e.__scopeDialog),n=p.useRef(null),i=yi(t,r.contentRef,n);return p.useEffect(()=>{const e=n.current;if(e)return ea(e)},[]),Ti.jsx(Ea,{...e,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:gi(e.onCloseAutoFocus,e=>{e.preventDefault(),r.triggerRef.current?.focus()}),onPointerDownOutside:gi(e.onPointerDownOutside,e=>{const t=e.detail.originalEvent,r=0===t.button&&!0===t.ctrlKey;(2===t.button||r)&&e.preventDefault()}),onFocusOutside:gi(e.onFocusOutside,e=>e.preventDefault())})}),wa=p.forwardRef((e,t)=>{const r=sa(va,e.__scopeDialog),n=p.useRef(!1),i=p.useRef(!1);return Ti.jsx(Ea,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:t=>{e.onCloseAutoFocus?.(t),t.defaultPrevented||(n.current||r.triggerRef.current?.focus(),t.preventDefault()),n.current=!1,i.current=!1},onInteractOutside:t=>{e.onInteractOutside?.(t),t.defaultPrevented||(n.current=!0,"pointerdown"===t.detail.originalEvent.type&&(i.current=!0));const s=t.target,a=r.triggerRef.current?.contains(s);a&&t.preventDefault(),"focusin"===t.detail.originalEvent.type&&i.current&&t.preventDefault()}})}),Ea=p.forwardRef((e,t)=>{const{__scopeDialog:r,trapFocus:n,onOpenAutoFocus:i,onCloseAutoFocus:s,...a}=e,o=sa(va,r),l=p.useRef(null),u=yi(t,l);return p.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??ls()),document.body.insertAdjacentElement("beforeend",e[1]??ls()),os++,()=>{1===os&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),os--}},[]),Ti.jsxs(Ti.Fragment,{children:[Ti.jsx(Qi,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:i,onUnmountAutoFocus:s,children:Ti.jsx(Vi,{role:"dialog",id:o.contentId,"aria-describedby":o.descriptionId,"aria-labelledby":o.titleId,"data-state":La(o.open),...a,ref:u,onDismiss:()=>o.onOpenChange(!1)})}),Ti.jsxs(Ti.Fragment,{children:[Ti.jsx(Da,{titleId:o.titleId}),Ti.jsx(_a,{contentRef:l,descriptionId:o.descriptionId})]})]})}),Sa="DialogTitle",Ta=p.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,i=sa(Sa,r);return Ti.jsx(Fi.h2,{id:i.titleId,...n,ref:t})});Ta.displayName=Sa;var xa="DialogDescription",ka=p.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,i=sa(xa,r);return Ti.jsx(Fi.p,{id:i.descriptionId,...n,ref:t})});ka.displayName=xa;var Aa="DialogClose",Ra=p.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,i=sa(Aa,r);return Ti.jsx(Fi.button,{type:"button",...n,ref:t,onClick:gi(e.onClick,()=>i.onOpenChange(!1))})});function La(e){return e?"open":"closed"}Ra.displayName=Aa;var Ia="DialogTitleWarning",[Ca,Pa]=function(e,t){const r=p.createContext(t),n=e=>{const{children:t,...n}=e,i=p.useMemo(()=>n,Object.values(n));return Ti.jsx(r.Provider,{value:i,children:t})};return n.displayName=e+"Provider",[n,function(n){const i=p.useContext(r);if(i)return i;if(void 0!==t)return t;throw new Error(`\`${n}\` must be used within \`${e}\``)}]}(Ia,{contentName:va,titleName:Sa,docsSlug:"dialog"}),Da=({titleId:e})=>{const t=Pa(Ia),r=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.\n\nIf you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.\n\nFor more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return p.useEffect(()=>{if(e){document.getElementById(e)||console.error(r)}},[r,e]),null},_a=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Pa("DialogDescriptionWarning").contentName}}.`;return p.useEffect(()=>{const n=e.current?.getAttribute("aria-describedby");if(t&&n){document.getElementById(t)||console.warn(r)}},[r,e,t]),null},Ma=aa,Oa=la,Na=ha,Fa=pa,$a=ya,Ba=Ta,Ua=ka,za=Ra;const ja=g.createContext({drawerRef:{current:null},overlayRef:{current:null},onPress:()=>{},onRelease:()=>{},onDrag:()=>{},onNestedDrag:()=>{},onNestedOpenChange:()=>{},onNestedRelease:()=>{},openProp:void 0,dismissible:!1,isOpen:!1,isDragging:!1,keyboardIsOpen:{current:!1},snapPointsOffset:null,snapPoints:null,handleOnly:!1,modal:!1,shouldFade:!1,activeSnapPoint:null,onOpenChange:()=>{},setActiveSnapPoint:()=>{},closeDrawer:()=>{},direction:"bottom",shouldAnimate:{current:!0},shouldScaleBackground:!1,setBackgroundColorOnScale:!0,noBodyStyles:!1,container:null,autoFocus:!1}),Ga=()=>{const e=g.useContext(ja);if(!e)throw new Error("useDrawerContext must be used within a Drawer.Root");return e};function Ha(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function Va(){return Ka(/^iPad/)||Ka(/^Mac/)&&navigator.maxTouchPoints>1}function Wa(){return Ka(/^iPhone/)||Va()}function Ka(e){return"undefined"!=typeof window&&null!=window.navigator?e.test(window.navigator.platform):void 0}!function(e){if("undefined"==typeof document)return;let t=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",t.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}("[data-vaul-drawer]{touch-action:none;will-change:transform;transition:transform .5s cubic-bezier(.32, .72, 0, 1);animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=open]{animation-name:slideFromBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=closed]{animation-name:slideToBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=open]{animation-name:slideFromTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=closed]{animation-name:slideToTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=open]{animation-name:slideFromLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=closed]{animation-name:slideToLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=open]{animation-name:slideFromRight}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=closed]{animation-name:slideToRight}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--initial-transform,100%),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--initial-transform,100%),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-overlay][data-vaul-snap-points=false]{animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-overlay][data-vaul-snap-points=false][data-state=open]{animation-name:fadeIn}[data-vaul-overlay][data-state=closed]{animation-name:fadeOut}[data-vaul-animate=false]{animation:none!important}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:0;transition:opacity .5s cubic-bezier(.32, .72, 0, 1)}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:1}[data-vaul-drawer]:not([data-vaul-custom-container=true])::after{content:'';position:absolute;background:inherit;background-color:inherit}[data-vaul-drawer][data-vaul-drawer-direction=top]::after{top:initial;bottom:100%;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=bottom]::after{top:100%;bottom:initial;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=left]::after{left:initial;right:100%;top:0;bottom:0;width:200%}[data-vaul-drawer][data-vaul-drawer-direction=right]::after{left:100%;right:initial;top:0;bottom:0;width:200%}[data-vaul-overlay][data-vaul-snap-points=true]:not([data-vaul-snap-points-overlay=true]):not(\n[data-state=closed]\n){opacity:0}[data-vaul-overlay][data-vaul-snap-points-overlay=true]{opacity:1}[data-vaul-handle]{display:block;position:relative;opacity:.7;background:#e2e2e4;margin-left:auto;margin-right:auto;height:5px;width:32px;border-radius:1rem;touch-action:pan-y}[data-vaul-handle]:active,[data-vaul-handle]:hover{opacity:1}[data-vaul-handle-hitarea]{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:max(100%,2.75rem);height:max(100%,2.75rem);touch-action:inherit}@media (hover:hover) and (pointer:fine){[data-vaul-drawer]{user-select:none}}@media (pointer:fine){[data-vaul-handle-hitarea]:{width:100%;height:100%}}@keyframes fadeIn{from{opacity:0}to{opacity:1}}@keyframes fadeOut{to{opacity:0}}@keyframes slideFromBottom{from{transform:translate3d(0,var(--initial-transform,100%),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToBottom{to{transform:translate3d(0,var(--initial-transform,100%),0)}}@keyframes slideFromTop{from{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToTop{to{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}}@keyframes slideFromLeft{from{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToLeft{to{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}}@keyframes slideFromRight{from{transform:translate3d(var(--initial-transform,100%),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToRight{to{transform:translate3d(var(--initial-transform,100%),0,0)}}");const Ya="undefined"!=typeof window?p.useLayoutEffect:p.useEffect;function qa(...e){return(...t)=>{for(let r of e)"function"==typeof r&&r(...t)}}const Xa="undefined"!=typeof document&&window.visualViewport;function Qa(e){let t=window.getComputedStyle(e);return/(auto|scroll)/.test(t.overflow+t.overflowX+t.overflowY)}function Za(e){for(Qa(e)&&(e=e.parentElement);e&&!Qa(e);)e=e.parentElement;return e||document.scrollingElement||document.documentElement}const Ja=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);let eo,to=0;function ro(e={}){let{isDisabled:t}=e;Ya(()=>{if(!t)return to++,1===to&&Wa()&&(eo=function(){let e,t=0,r=r=>{e=Za(r.target),e===document.documentElement&&e===document.body||(t=r.changedTouches[0].pageY)},n=r=>{if(!e||e===document.documentElement||e===document.body)return void r.preventDefault();let n=r.changedTouches[0].pageY,i=e.scrollTop,s=e.scrollHeight-e.clientHeight;0!==s&&((i<=0&&n>t||i>=s&&n<t)&&r.preventDefault(),t=n)},i=e=>{let t=e.target;so(t)&&t!==document.activeElement&&(e.preventDefault(),t.style.transform="translateY(-2000px)",t.focus(),requestAnimationFrame(()=>{t.style.transform=""}))},s=e=>{let t=e.target;so(t)&&(t.style.transform="translateY(-2000px)",requestAnimationFrame(()=>{t.style.transform="",Xa&&(Xa.height<window.innerHeight?requestAnimationFrame(()=>{io(t)}):Xa.addEventListener("resize",()=>io(t),{once:!0}))}))},a=()=>{window.scrollTo(0,0)},o=window.pageXOffset,l=window.pageYOffset,u=qa(function(e,t,r){let n=e.style[t];return e.style[t]=r,()=>{e.style[t]=n}}(document.documentElement,"paddingRight",window.innerWidth-document.documentElement.clientWidth+"px"));window.scrollTo(0,0);let c=qa(no(document,"touchstart",r,{passive:!1,capture:!0}),no(document,"touchmove",n,{passive:!1,capture:!0}),no(document,"touchend",i,{passive:!1,capture:!0}),no(document,"focus",s,!0),no(window,"scroll",a));return()=>{u(),c(),window.scrollTo(o,l)}}()),()=>{to--,0===to&&(null==eo||eo())}},[t])}function no(e,t,r,n){return e.addEventListener(t,r,n),()=>{e.removeEventListener(t,r,n)}}function io(e){let t=document.scrollingElement||document.documentElement;for(;e&&e!==t;){let t=Za(e);if(t!==document.documentElement&&t!==document.body&&t!==e){let r=t.getBoundingClientRect().top,n=e.getBoundingClientRect().top;e.getBoundingClientRect().bottom>t.getBoundingClientRect().bottom+24&&(t.scrollTop+=n-r)}e=t.parentElement}}function so(e){return e instanceof HTMLInputElement&&!Ja.has(e.type)||e instanceof HTMLTextAreaElement||e instanceof HTMLElement&&e.isContentEditable}function ao(...e){return p.useCallback(function(...e){return t=>e.forEach(e=>function(e,t){"function"==typeof e?e(t):null!=e&&(e.current=t)}(e,t))}(...e),e)}const oo=new WeakMap;function lo(e,t,r=!1){if(!(e&&e instanceof HTMLElement))return;let n={};Object.entries(t).forEach(([t,r])=>{t.startsWith("--")?e.style.setProperty(t,r):(n[t]=e.style[t],e.style[t]=r)}),r||oo.set(e,n)}const uo=e=>{switch(e){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return e}};function co(e,t){if(!e)return null;const r=window.getComputedStyle(e),n=r.transform||r.webkitTransform||r.mozTransform;let i=n.match(/^matrix3d\((.+)\)$/);return i?parseFloat(i[1].split(", ")[uo(t)?13:12]):(i=n.match(/^matrix\((.+)\)$/),i?parseFloat(i[1].split(", ")[uo(t)?5:4]):null)}function ho(e,t){if(!e)return()=>{};const r=e.style.cssText;return Object.assign(e.style,t),()=>{e.style.cssText=r}}const fo={DURATION:.5,EASE:[.32,.72,0,1]},po=16,go="vaul-dragging";function mo(e){const t=g.useRef(e);return g.useEffect(()=>{t.current=e}),g.useMemo(()=>(...e)=>null==t.current?void 0:t.current.call(t,...e),[])}function vo({prop:e,defaultProp:t,onChange:r=()=>{}}){const[n,i]=function({defaultProp:e,onChange:t}){const r=g.useState(e),[n]=r,i=g.useRef(n),s=mo(t);return g.useEffect(()=>{i.current!==n&&(s(n),i.current=n)},[n,i,s]),r}({defaultProp:t,onChange:r}),s=void 0!==e,a=s?e:n,o=mo(r),l=g.useCallback(t=>{if(s){const r="function"==typeof t?t(e):t;r!==e&&o(r)}else i(t)},[s,e,i,o]);return[a,l]}let yo=null;function bo({open:e,onOpenChange:t,children:r,onDrag:n,onRelease:i,snapPoints:s,shouldScaleBackground:a=!1,setBackgroundColorOnScale:o=!0,closeThreshold:l=.25,scrollLockTimeout:u=100,dismissible:c=!0,handleOnly:d=!1,fadeFromIndex:h=s&&s.length-1,activeSnapPoint:f,setActiveSnapPoint:p,fixed:m,modal:v=!0,onClose:y,nested:b,noBodyStyles:w=!1,direction:E="bottom",defaultOpen:S=!1,disablePreventScroll:T=!0,snapToSequentialPoint:x=!1,preventScrollRestoration:k=!1,repositionInputs:A=!0,onAnimationEnd:R,container:L,autoFocus:I=!1}){var C,P;const[D=!1,_]=vo({defaultProp:S,prop:e,onChange:e=>{null==t||t(e),e||b||ce(),setTimeout(()=>{null==R||R(e)},1e3*fo.DURATION),e&&!v&&"undefined"!=typeof window&&window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"}),e||(document.body.style.pointerEvents="auto")}}),[M,O]=g.useState(!1),[N,F]=g.useState(!1),[$,B]=g.useState(!1),U=g.useRef(null),z=g.useRef(null),j=g.useRef(null),G=g.useRef(null),H=g.useRef(null),V=g.useRef(!1),W=g.useRef(null),K=g.useRef(0),Y=g.useRef(!1),q=g.useRef(!S),X=g.useRef(0),Q=g.useRef(null),Z=g.useRef((null==(C=Q.current)?void 0:C.getBoundingClientRect().height)||0),J=g.useRef((null==(P=Q.current)?void 0:P.getBoundingClientRect().width)||0),ee=g.useRef(0),te=g.useCallback(e=>{s&&e===ae.length-1&&(z.current=new Date)},[]),{activeSnapPoint:re,activeSnapPointIndex:ne,setActiveSnapPoint:ie,onRelease:se,snapPointsOffset:ae,onDrag:oe,shouldFade:le,getPercentageDragged:ue}=function({activeSnapPointProp:e,setActiveSnapPointProp:t,snapPoints:r,drawerRef:n,overlayRef:i,fadeFromIndex:s,onSnapPointChange:a,direction:o="bottom",container:l,snapToSequentialPoint:u}){const[c,d]=vo({prop:e,defaultProp:null==r?void 0:r[0],onChange:t}),[h,f]=g.useState("undefined"!=typeof window?{innerWidth:window.innerWidth,innerHeight:window.innerHeight}:void 0);g.useEffect(()=>{function e(){f({innerWidth:window.innerWidth,innerHeight:window.innerHeight})}return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const p=g.useMemo(()=>c===(null==r?void 0:r[r.length-1])||null,[r,c]),m=g.useMemo(()=>{var e;return null!=(e=null==r?void 0:r.findIndex(e=>e===c))?e:null},[r,c]),v=r&&r.length>0&&(s||0===s)&&!Number.isNaN(s)&&r[s]===c||!r,y=g.useMemo(()=>{const e=l?{width:l.getBoundingClientRect().width,height:l.getBoundingClientRect().height}:"undefined"!=typeof window?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0};var t;return null!=(t=null==r?void 0:r.map(t=>{const r="string"==typeof t;let n=0;if(r&&(n=parseInt(t,10)),uo(o)){const i=r?n:h?t*e.height:0;return h?"bottom"===o?e.height-i:-e.height+i:i}const i=r?n:h?t*e.width:0;return h?"right"===o?e.width-i:-e.width+i:i}))?t:[]},[r,h,l]),b=g.useMemo(()=>null!==m?null==y?void 0:y[m]:null,[y,m]),w=g.useCallback(e=>{var t;const l=null!=(t=null==y?void 0:y.findIndex(t=>t===e))?t:null;a(l),lo(n.current,{transition:`transform ${fo.DURATION}s cubic-bezier(${fo.EASE.join(",")})`,transform:uo(o)?`translate3d(0, ${e}px, 0)`:`translate3d(${e}px, 0, 0)`}),y&&l!==y.length-1&&void 0!==s&&l!==s&&l<s?lo(i.current,{transition:`opacity ${fo.DURATION}s cubic-bezier(${fo.EASE.join(",")})`,opacity:"0"}):lo(i.current,{transition:`opacity ${fo.DURATION}s cubic-bezier(${fo.EASE.join(",")})`,opacity:"1"}),d(null==r?void 0:r[Math.max(l,0)])},[n.current,r,y,s,i,d]);return g.useEffect(()=>{if(c||e){var t;const n=null!=(t=null==r?void 0:r.findIndex(t=>t===e||t===c))?t:-1;y&&-1!==n&&"number"==typeof y[n]&&w(y[n])}},[c,e,r,y,w]),{isLastSnapPoint:p,activeSnapPoint:c,shouldFade:v,getPercentageDragged:function(e,t){if(!r||"number"!=typeof m||!y||void 0===s)return null;const n=m===s-1;if(m>=s&&t)return 0;if(n&&!t)return 1;if(!v&&!n)return null;const i=n?m+1:m-1,a=n?y[i]-y[i-1]:y[i+1]-y[i],o=e/Math.abs(a);return n?1-o:o},setActiveSnapPoint:d,activeSnapPointIndex:m,onRelease:function({draggedDistance:e,closeDrawer:t,velocity:n,dismissible:a}){if(void 0===s)return;const l="bottom"===o||"right"===o?(null!=b?b:0)-e:(null!=b?b:0)+e,c=0===m,d=e>0;if(m===s-1&&lo(i.current,{transition:`opacity ${fo.DURATION}s cubic-bezier(${fo.EASE.join(",")})`}),!u&&n>2&&!d)return void(a?t():w(y[0]));if(!u&&n>2&&d&&y&&r)return void w(y[r.length-1]);const h=null==y?void 0:y.reduce((e,t)=>"number"!=typeof e||"number"!=typeof t?e:Math.abs(t-l)<Math.abs(e-l)?t:e),f=uo(o)?window.innerHeight:window.innerWidth;if(n>.4&&Math.abs(e)<.4*f){const e=d?1:-1;if(e>0&&p&&r)return void w(y[r.length-1]);if(c&&e<0&&a&&t(),null===m)return;return void w(y[m+e])}w(h)},onDrag:function({draggedDistance:e}){if(null===b)return;const t="bottom"===o||"right"===o?b-e:b+e;("bottom"===o||"right"===o)&&t<y[y.length-1]||("top"===o||"left"===o)&&t>y[y.length-1]||lo(n.current,{transform:uo(o)?`translate3d(0, ${t}px, 0)`:`translate3d(${t}px, 0, 0)`})},snapPointsOffset:y}}({snapPoints:s,activeSnapPointProp:f,setActiveSnapPointProp:p,drawerRef:Q,fadeFromIndex:h,overlayRef:U,onSnapPointChange:te,direction:E,container:L,snapToSequentialPoint:x});ro({isDisabled:!D||N||!v||$||!M||!A||!T});const{restorePositionSetting:ce}=function({isOpen:e,modal:t,nested:r,hasBeenOpened:n,preventScrollRestoration:i,noBodyStyles:s}){const[a,o]=g.useState(()=>"undefined"!=typeof window?window.location.href:""),l=g.useRef(0),u=g.useCallback(()=>{if(Ha()&&null===yo&&e&&!s){yo={position:document.body.style.position,top:document.body.style.top,left:document.body.style.left,height:document.body.style.height,right:"unset"};const{scrollX:e,innerHeight:t}=window;document.body.style.setProperty("position","fixed","important"),Object.assign(document.body.style,{top:-l.current+"px",left:-e+"px",right:"0px",height:"auto"}),window.setTimeout(()=>window.requestAnimationFrame(()=>{const e=t-window.innerHeight;e&&l.current>=t&&(document.body.style.top=-(l.current+e)+"px")}),300)}},[e]),c=g.useCallback(()=>{if(Ha()&&null!==yo&&!s){const e=-parseInt(document.body.style.top,10),t=-parseInt(document.body.style.left,10);Object.assign(document.body.style,yo),window.requestAnimationFrame(()=>{i&&a!==window.location.href?o(window.location.href):window.scrollTo(t,e)}),yo=null}},[a]);return g.useEffect(()=>{function e(){l.current=window.scrollY}return e(),window.addEventListener("scroll",e),()=>{window.removeEventListener("scroll",e)}},[]),g.useEffect(()=>{if(t)return()=>{"undefined"!=typeof document&&(document.querySelector("[data-vaul-drawer]")||c())}},[t,c]),g.useEffect(()=>{!r&&n&&(e?(!window.matchMedia("(display-mode: standalone)").matches&&u(),t||window.setTimeout(()=>{c()},500)):c())},[e,n,a,t,r,u,c]),{restorePositionSetting:c}}({isOpen:D,modal:v,nested:null!=b&&b,hasBeenOpened:M,preventScrollRestoration:k,noBodyStyles:w});function de(){return(window.innerWidth-26)/window.innerWidth}function he(e,t){var r;let n=e;const i=null==(r=window.getSelection())?void 0:r.toString(),s=Q.current?co(Q.current,E):null,a=new Date;if("SELECT"===n.tagName)return!1;if(n.hasAttribute("data-vaul-no-drag")||n.closest("[data-vaul-no-drag]"))return!1;if("right"===E||"left"===E)return!0;if(z.current&&a.getTime()-z.current.getTime()<500)return!1;if(null!==s&&("bottom"===E?s>0:s<0))return!0;if(i&&i.length>0)return!1;if(H.current&&a.getTime()-H.current.getTime()<u&&0===s)return H.current=a,!1;if(t)return H.current=a,!1;for(;n;){if(n.scrollHeight>n.clientHeight){if(0!==n.scrollTop)return H.current=new Date,!1;if("dialog"===n.getAttribute("role"))return!0}n=n.parentNode}return!0}function fe(e){!function(){if(!N||!Q.current)return;Q.current.classList.remove(go),V.current=!1,F(!1),G.current=new Date}(),null==y||y(),e||_(!1),setTimeout(()=>{s&&ie(s[0])},1e3*fo.DURATION)}function pe(){if(!Q.current)return;const e=document.querySelector("[data-vaul-drawer-wrapper]"),t=co(Q.current,E);lo(Q.current,{transform:"translate3d(0, 0, 0)",transition:`transform ${fo.DURATION}s cubic-bezier(${fo.EASE.join(",")})`}),lo(U.current,{transition:`opacity ${fo.DURATION}s cubic-bezier(${fo.EASE.join(",")})`,opacity:"1"}),a&&t&&t>0&&D&&lo(e,{borderRadius:"8px",overflow:"hidden",...uo(E)?{transform:`scale(${de()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,transformOrigin:"top"}:{transform:`scale(${de()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,transformOrigin:"left"},transitionProperty:"transform, border-radius",transitionDuration:`${fo.DURATION}s`,transitionTimingFunction:`cubic-bezier(${fo.EASE.join(",")})`},!0)}return g.useEffect(()=>{window.requestAnimationFrame(()=>{q.current=!0})},[]),g.useEffect(()=>{var e;function t(){if(!Q.current||!A)return;if(so(document.activeElement)||Y.current){var e;const t=(null==(e=window.visualViewport)?void 0:e.height)||0,r=window.innerHeight;let n=r-t;const i=Q.current.getBoundingClientRect().height||0,a=i>.8*r;ee.current||(ee.current=i);const o=Q.current.getBoundingClientRect().top;if(Math.abs(X.current-n)>60&&(Y.current=!Y.current),s&&s.length>0&&ae&&ne){n+=ae[ne]||0}if(X.current=n,i>t||Y.current){const e=Q.current.getBoundingClientRect().height;let r=e;e>t&&(r=t-(a?o:26)),Q.current.style.height=m?e-Math.max(n,0)+"px":`${Math.max(r,t-o)}px`}else(function(){const e=navigator.userAgent;return"undefined"!=typeof window&&(/Firefox/.test(e)&&/Mobile/.test(e)||/FxiOS/.test(e))})()||(Q.current.style.height=`${ee.current}px`);s&&s.length>0&&!Y.current?Q.current.style.bottom="0px":Q.current.style.bottom=`${Math.max(n,0)}px`}}return null==(e=window.visualViewport)||e.addEventListener("resize",t),()=>{var e;return null==(e=window.visualViewport)?void 0:e.removeEventListener("resize",t)}},[ne,s,ae]),g.useEffect(()=>(D&&(lo(document.documentElement,{scrollBehavior:"auto"}),z.current=new Date),()=>{!function(e,t){if(!(e&&e instanceof HTMLElement))return;let r=oo.get(e);r&&(e.style[t]=r[t])}(document.documentElement,"scrollBehavior")}),[D]),g.useEffect(()=>{v||window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"})},[v]),g.createElement(Ma,{defaultOpen:S,onOpenChange:e=>{(c||e)&&(e?O(!0):fe(!0),_(e))},open:D},g.createElement(ja.Provider,{value:{activeSnapPoint:re,snapPoints:s,setActiveSnapPoint:ie,drawerRef:Q,overlayRef:U,onOpenChange:t,onPress:function(e){var t,r;(c||s)&&(Q.current&&!Q.current.contains(e.target)||(Z.current=(null==(t=Q.current)?void 0:t.getBoundingClientRect().height)||0,J.current=(null==(r=Q.current)?void 0:r.getBoundingClientRect().width)||0,F(!0),j.current=new Date,Wa()&&window.addEventListener("touchend",()=>V.current=!1,{once:!0}),e.target.setPointerCapture(e.pointerId),K.current=uo(E)?e.pageY:e.pageX))},onRelease:function(e){if(!N||!Q.current)return;Q.current.classList.remove(go),V.current=!1,F(!1),G.current=new Date;const t=co(Q.current,E);if(!e||!he(e.target,!1)||!t||Number.isNaN(t))return;if(null===j.current)return;const r=G.current.getTime()-j.current.getTime(),n=K.current-(uo(E)?e.pageY:e.pageX),a=Math.abs(n)/r;if(a>.05&&(B(!0),setTimeout(()=>{B(!1)},200)),s){return se({draggedDistance:n*("bottom"===E||"right"===E?1:-1),closeDrawer:fe,velocity:a,dismissible:c}),void(null==i||i(e,!0))}if("bottom"===E||"right"===E?n>0:n<0)return pe(),void(null==i||i(e,!0));if(a>.4)return fe(),void(null==i||i(e,!1));var o;const u=Math.min(null!=(o=Q.current.getBoundingClientRect().height)?o:0,window.innerHeight);var d;const h=Math.min(null!=(d=Q.current.getBoundingClientRect().width)?d:0,window.innerWidth),f="left"===E||"right"===E;if(Math.abs(t)>=(f?h:u)*l)return fe(),void(null==i||i(e,!1));null==i||i(e,!0),pe()},onDrag:function(e){if(Q.current&&N){const t="bottom"===E||"right"===E?1:-1,r=(K.current-(uo(E)?e.pageY:e.pageX))*t,i=r>0,o=s&&!c&&!i;if(o&&0===ne)return;const l=Math.abs(r),u=document.querySelector("[data-vaul-drawer-wrapper]");let d=l/("bottom"===E||"top"===E?Z.current:J.current);const f=ue(l,i);if(null!==f&&(d=f),o&&d>=1)return;if(!V.current&&!he(e.target,i))return;if(Q.current.classList.add(go),V.current=!0,lo(Q.current,{transition:"none"}),lo(U.current,{transition:"none"}),s&&oe({draggedDistance:r}),i&&!s){const e=function(e){return 8*(Math.log(e+1)-2)}(r),n=Math.min(-1*e,0)*t;return void lo(Q.current,{transform:uo(E)?`translate3d(0, ${n}px, 0)`:`translate3d(${n}px, 0, 0)`})}const p=1-d;if((le||h&&ne===h-1)&&(null==n||n(e,d),lo(U.current,{opacity:`${p}`,transition:"none"},!0)),u&&U.current&&a){const e=Math.min(de()+d*(1-de()),1),t=8-8*d,r=Math.max(0,14-14*d);lo(u,{borderRadius:`${t}px`,transform:uo(E)?`scale(${e}) translate3d(0, ${r}px, 0)`:`scale(${e}) translate3d(${r}px, 0, 0)`,transition:"none"},!0)}if(!s){const e=l*t;lo(Q.current,{transform:uo(E)?`translate3d(0, ${e}px, 0)`:`translate3d(${e}px, 0, 0)`})}}},dismissible:c,shouldAnimate:q,handleOnly:d,isOpen:D,isDragging:N,shouldFade:le,closeDrawer:fe,onNestedDrag:function(e,t){if(t<0)return;const r=(window.innerWidth-po)/window.innerWidth,n=r+t*(1-r),i=t*po-16;lo(Q.current,{transform:uo(E)?`scale(${n}) translate3d(0, ${i}px, 0)`:`scale(${n}) translate3d(${i}px, 0, 0)`,transition:"none"})},onNestedOpenChange:function(e){const t=e?(window.innerWidth-po)/window.innerWidth:1,r=e?-16:0;W.current&&window.clearTimeout(W.current),lo(Q.current,{transition:`transform ${fo.DURATION}s cubic-bezier(${fo.EASE.join(",")})`,transform:uo(E)?`scale(${t}) translate3d(0, ${r}px, 0)`:`scale(${t}) translate3d(${r}px, 0, 0)`}),!e&&Q.current&&(W.current=setTimeout(()=>{const e=co(Q.current,E);lo(Q.current,{transition:"none",transform:uo(E)?`translate3d(0, ${e}px, 0)`:`translate3d(${e}px, 0, 0)`})},500))},onNestedRelease:function(e,t){const r=uo(E)?window.innerHeight:window.innerWidth,n=t?(r-po)/r:1,i=t?-16:0;t&&lo(Q.current,{transition:`transform ${fo.DURATION}s cubic-bezier(${fo.EASE.join(",")})`,transform:uo(E)?`scale(${n}) translate3d(0, ${i}px, 0)`:`scale(${n}) translate3d(${i}px, 0, 0)`})},keyboardIsOpen:Y,modal:v,snapPointsOffset:ae,activeSnapPointIndex:ne,direction:E,shouldScaleBackground:a,setBackgroundColorOnScale:o,noBodyStyles:w,container:L,autoFocus:I}},r))}const wo=g.forwardRef(function({...e},t){const{overlayRef:r,snapPoints:n,onRelease:i,shouldFade:s,isOpen:a,modal:o,shouldAnimate:l}=Ga(),u=ao(t,r),c=n&&n.length>0;if(!o)return null;const d=g.useCallback(e=>i(e),[i]);return g.createElement(Fa,{onMouseUp:d,ref:u,"data-vaul-overlay":"","data-vaul-snap-points":a&&c?"true":"false","data-vaul-snap-points-overlay":a&&s?"true":"false","data-vaul-animate":(null==l?void 0:l.current)?"true":"false",...e})});wo.displayName="Drawer.Overlay";const Eo=g.forwardRef(function({onPointerDownOutside:e,style:t,onOpenAutoFocus:r,...n},i){const{drawerRef:s,onPress:a,onRelease:o,onDrag:l,keyboardIsOpen:u,snapPointsOffset:c,activeSnapPointIndex:d,modal:h,isOpen:f,direction:m,snapPoints:v,container:y,handleOnly:b,shouldAnimate:w,autoFocus:E}=Ga(),[S,T]=g.useState(!1),x=ao(i,s),k=g.useRef(null),A=g.useRef(null),R=g.useRef(!1),L=v&&v.length>0;!function(){const{direction:e,isOpen:t,shouldScaleBackground:r,setBackgroundColorOnScale:n,noBodyStyles:i}=Ga(),s=g.useRef(null),a=p.useMemo(()=>document.body.style.backgroundColor,[]);function o(){return(window.innerWidth-26)/window.innerWidth}g.useEffect(()=>{if(t&&r){s.current&&clearTimeout(s.current);const t=document.querySelector("[data-vaul-drawer-wrapper]")||document.querySelector("[vaul-drawer-wrapper]");if(!t)return;n&&!i&&ho(document.body,{background:"black"}),ho(t,{transformOrigin:uo(e)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${fo.DURATION}s`,transitionTimingFunction:`cubic-bezier(${fo.EASE.join(",")})`});const r=ho(t,{borderRadius:"8px",overflow:"hidden",...uo(e)?{transform:`scale(${o()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`}:{transform:`scale(${o()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`}});return()=>{r(),s.current=window.setTimeout(()=>{a?document.body.style.background=a:document.body.style.removeProperty("background")},1e3*fo.DURATION)}}},[t,r,a])}();function I(e){k.current=null,R.current=!1,o(e)}return g.useEffect(()=>{L&&window.requestAnimationFrame(()=>{T(!0)})},[]),g.createElement($a,{"data-vaul-drawer-direction":m,"data-vaul-drawer":"","data-vaul-delayed-snap-points":S?"true":"false","data-vaul-snap-points":f&&L?"true":"false","data-vaul-custom-container":y?"true":"false","data-vaul-animate":(null==w?void 0:w.current)?"true":"false",...n,ref:x,style:c&&c.length>0?{"--snap-point-height":`${c[null!=d?d:0]}px`,...t}:t,onPointerDown:e=>{b||(null==n.onPointerDown||n.onPointerDown.call(n,e),k.current={x:e.pageX,y:e.pageY},a(e))},onOpenAutoFocus:e=>{null==r||r(e),E||e.preventDefault()},onPointerDownOutside:t=>{null==e||e(t),h&&!t.defaultPrevented?u.current&&(u.current=!1):t.preventDefault()},onFocusOutside:e=>{h||e.preventDefault()},onPointerMove:e=>{if(A.current=e,b)return;if(null==n.onPointerMove||n.onPointerMove.call(n,e),!k.current)return;const t=e.pageY-k.current.y,r=e.pageX-k.current.x,i="touch"===e.pointerType?10:2,s=((e,t,r=0)=>{if(R.current)return!0;const n=Math.abs(e.y),i=Math.abs(e.x),s=i>n,a=["bottom","right"].includes(t)?1:-1;if("left"===t||"right"===t){if(!(e.x*a<0)&&i>=0&&i<=r)return s}else if(!(e.y*a<0)&&n>=0&&n<=r)return!s;return R.current=!0,!0})({x:r,y:t},m,i);s?l(e):(Math.abs(r)>i||Math.abs(t)>i)&&(k.current=null)},onPointerUp:e=>{null==n.onPointerUp||n.onPointerUp.call(n,e),k.current=null,R.current=!1,o(e)},onPointerOut:e=>{null==n.onPointerOut||n.onPointerOut.call(n,e),I(A.current)},onContextMenu:e=>{null==n.onContextMenu||n.onContextMenu.call(n,e),A.current&&I(A.current)}})});Eo.displayName="Drawer.Content";const So=g.forwardRef(function({preventCycle:e=!1,children:t,...r},n){const{closeDrawer:i,isDragging:s,snapPoints:a,activeSnapPoint:o,setActiveSnapPoint:l,dismissible:u,handleOnly:c,isOpen:d,onPress:h,onDrag:f}=Ga(),p=g.useRef(null),m=g.useRef(!1);function v(){p.current&&window.clearTimeout(p.current),m.current=!1}return g.createElement("div",{onClick:function(){m.current?v():window.setTimeout(()=>{!function(){if(s||e||m.current)return void v();if(v(),!a||0===a.length)return void(u||i());if(o===a[a.length-1]&&u)return void i();const t=a.findIndex(e=>e===o);if(-1===t)return;const r=a[t+1];l(r)}()},120)},onPointerCancel:v,onPointerDown:e=>{c&&h(e),p.current=window.setTimeout(()=>{m.current=!0},250)},onPointerMove:e=>{c&&f(e)},ref:n,"data-vaul-drawer-visible":d?"true":"false","data-vaul-handle":"","aria-hidden":"true",...r},g.createElement("span",{"data-vaul-handle-hitarea":"","aria-hidden":"true"},t))});So.displayName="Drawer.Handle";const To={Root:bo,NestedRoot:function({onDrag:e,onOpenChange:t,open:r,...n}){const{onNestedDrag:i,onNestedOpenChange:s,onNestedRelease:a}=Ga();if(!i)throw new Error("Drawer.NestedRoot must be placed in another drawer");return g.createElement(bo,{nested:!0,open:r,onClose:()=>{s(!1)},onDrag:(t,r)=>{i(t,r),null==e||e(t,r)},onOpenChange:e=>{e&&s(e),null==t||t(e)},onRelease:a,...n})},Content:Eo,Overlay:wo,Trigger:Oa,Portal:function(e){const t=Ga(),{container:r=t.container,...n}=e;return g.createElement(Na,{container:r,...n})},Handle:So,Close:za,Title:Ba,Description:Ua};function xo(e){var t=Z(e,[]);return p.createElement(To.Root,Object.assign({"data-slot":"drawer"},t))}function ko(e){var t=Z(e,[]);return p.createElement(To.Trigger,Object.assign({"data-slot":"drawer-trigger"},t))}function Ao(e){var t=Z(e,[]);return p.createElement(To.Portal,Object.assign({"data-slot":"drawer-portal"},t))}function Ro(e){var{className:t}=e,r=Z(e,["className"]);return p.createElement(To.Overlay,Object.assign({"data-slot":"drawer-overlay",className:Ot("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-[999999] bg-black/50",t)},r))}function Lo(e){var{className:t,children:r}=e,n=Z(e,["className","children"]);return p.createElement(Ao,{"data-slot":"drawer-portal"},p.createElement(Ro,null),p.createElement(To.Content,Object.assign({"data-slot":"drawer-content",className:Ot("group/drawer-content bg-background fixed z-[999999] flex h-auto flex-col","data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b","data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t","data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm","data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm",t)},n),p.createElement("div",{className:"bg-muted mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full group-data-[vaul-drawer-direction=bottom]/drawer-content:block"}),r))}function Io(e){var{className:t}=e,r=Z(e,["className"]);return p.createElement("div",Object.assign({"data-slot":"drawer-header",className:Ot("flex flex-col gap-1.5 p-4",t)},r))}function Co(e){var{className:t}=e,r=Z(e,["className"]);return p.createElement(To.Title,Object.assign({"data-slot":"drawer-title",className:Ot("text-foreground font-semibold",t)},r))}const Po=({children:e,products:t,contentId:r})=>{const{isPreview:n}=cr();return g.createElement(xo,{direction:"right",fadeFromIndex:0,snapPoints:[1]},g.createElement(ko,{className:"w-full"},e),g.createElement(Lo,null,g.createElement(Io,null,g.createElement(Co,null,"상품 목록")),g.createElement("div",{className:"overflow-y-scroll grid-cols-2 grid items-baseline justify-items-center scrollbar-hide"},t.map(e=>e.linkPath?g.createElement("a",{key:e.productId,className:"p-2 text-gray-800 w-full h-full flex flex-col items-center justify-center no-underline",href:e.linkPath,target:"_blank",onClick:()=>J(void 0,void 0,void 0,function*(){n||(yield Zt({contentId:r,contentProductId:e.eventProductId,productId:e.productId}))})},g.createElement(Do,{product:e})):g.createElement(Do,{key:e.productId,product:e})))))},Do=({product:e})=>g.createElement("div",{className:"text-gray-800 w-32"},g.createElement("div",{className:"w-full aspect-square mb-2 border border-[#f4f3f6] rounded "},g.createElement("img",{src:e.thumbPath,alt:e.productName,className:"w-full h-full"})),e.brand&&g.createElement("p",{className:"text-xs text-gray-400 mb-1"},e.brand.brandName),g.createElement("p",{className:"w-full text-[12px] md:text-[15px] mb-1"},e.productName),g.createElement("div",{className:"w-full "},g.createElement("div",{className:"flex"},g.createElement("span",{className:"text-sm text-red-500 mr-2 font-semibold"},e.discount,"%"),g.createElement("span",{className:"font-semibold"},Nt(e.sellingPrice),"원"))));function _o(e){let t,r,{swiper:n,extendParams:i,on:s,emit:a,params:o}=e;n.autoplay={running:!1,paused:!1,timeLeft:0},i({autoplay:{enabled:!1,delay:3e3,waitForTransition:!0,disableOnInteraction:!1,stopOnLastSlide:!1,reverseDirection:!1,pauseOnMouseEnter:!1}});let l,u,c,d,h,f,p,g,m=o&&o.autoplay?o.autoplay.delay:3e3,v=o&&o.autoplay?o.autoplay.delay:3e3,y=(new Date).getTime();function b(e){n&&!n.destroyed&&n.wrapperEl&&e.target===n.wrapperEl&&(n.wrapperEl.removeEventListener("transitionend",b),g||e.detail&&e.detail.bySwiperTouchMove||k())}const w=()=>{if(n.destroyed||!n.autoplay.running)return;n.autoplay.paused?u=!0:u&&(v=l,u=!1);const e=n.autoplay.paused?l:y+v-(new Date).getTime();n.autoplay.timeLeft=e,a("autoplayTimeLeft",e,e/m),r=requestAnimationFrame(()=>{w()})},E=e=>{if(n.destroyed||!n.autoplay.running)return;cancelAnimationFrame(r),w();let i=void 0===e?n.params.autoplay.delay:e;m=n.params.autoplay.delay,v=n.params.autoplay.delay;const s=(()=>{let e;if(e=n.virtual&&n.params.virtual.enabled?n.slides.filter(e=>e.classList.contains("swiper-slide-active"))[0]:n.slides[n.activeIndex],!e)return;return parseInt(e.getAttribute("data-swiper-autoplay"),10)})();!Number.isNaN(s)&&s>0&&void 0===e&&(i=s,m=s,v=s),l=i;const o=n.params.speed,u=()=>{n&&!n.destroyed&&(n.params.autoplay.reverseDirection?!n.isBeginning||n.params.loop||n.params.rewind?(n.slidePrev(o,!0,!0),a("autoplay")):n.params.autoplay.stopOnLastSlide||(n.slideTo(n.slides.length-1,o,!0,!0),a("autoplay")):!n.isEnd||n.params.loop||n.params.rewind?(n.slideNext(o,!0,!0),a("autoplay")):n.params.autoplay.stopOnLastSlide||(n.slideTo(0,o,!0,!0),a("autoplay")),n.params.cssMode&&(y=(new Date).getTime(),requestAnimationFrame(()=>{E()})))};return i>0?(clearTimeout(t),t=setTimeout(()=>{u()},i)):requestAnimationFrame(()=>{u()}),i},S=()=>{y=(new Date).getTime(),n.autoplay.running=!0,E(),a("autoplayStart")},T=()=>{n.autoplay.running=!1,clearTimeout(t),cancelAnimationFrame(r),a("autoplayStop")},x=(e,r)=>{if(n.destroyed||!n.autoplay.running)return;clearTimeout(t),e||(p=!0);const i=()=>{a("autoplayPause"),n.params.autoplay.waitForTransition?n.wrapperEl.addEventListener("transitionend",b):k()};if(n.autoplay.paused=!0,r)return f&&(l=n.params.autoplay.delay),f=!1,void i();const s=l||n.params.autoplay.delay;l=s-((new Date).getTime()-y),n.isEnd&&l<0&&!n.params.loop||(l<0&&(l=0),i())},k=()=>{n.isEnd&&l<0&&!n.params.loop||n.destroyed||!n.autoplay.running||(y=(new Date).getTime(),p?(p=!1,E(l)):E(),n.autoplay.paused=!1,a("autoplayResume"))},A=()=>{if(n.destroyed||!n.autoplay.running)return;const e=yr();"hidden"===e.visibilityState&&(p=!0,x(!0)),"visible"===e.visibilityState&&k()},R=e=>{"mouse"===e.pointerType&&(p=!0,g=!0,n.animating||n.autoplay.paused||x(!0))},L=e=>{"mouse"===e.pointerType&&(g=!1,n.autoplay.paused&&k())};s("init",()=>{n.params.autoplay.enabled&&(n.params.autoplay.pauseOnMouseEnter&&(n.el.addEventListener("pointerenter",R),n.el.addEventListener("pointerleave",L)),yr().addEventListener("visibilitychange",A),S())}),s("destroy",()=>{n.el&&"string"!=typeof n.el&&(n.el.removeEventListener("pointerenter",R),n.el.removeEventListener("pointerleave",L)),yr().removeEventListener("visibilitychange",A),n.autoplay.running&&T()}),s("_freeModeStaticRelease",()=>{(d||p)&&k()}),s("_freeModeNoMomentumRelease",()=>{n.params.autoplay.disableOnInteraction?T():x(!0,!0)}),s("beforeTransitionStart",(e,t,r)=>{!n.destroyed&&n.autoplay.running&&(r||!n.params.autoplay.disableOnInteraction?x(!0,!0):T())}),s("sliderFirstMove",()=>{!n.destroyed&&n.autoplay.running&&(n.params.autoplay.disableOnInteraction?T():(c=!0,d=!1,p=!1,h=setTimeout(()=>{p=!0,d=!0,x(!0)},200)))}),s("touchEnd",()=>{if(!n.destroyed&&n.autoplay.running&&c){if(clearTimeout(h),clearTimeout(t),n.params.autoplay.disableOnInteraction)return d=!1,void(c=!1);d&&n.params.cssMode&&k(),d=!1,c=!1}}),s("slideChange",()=>{!n.destroyed&&n.autoplay.running&&(f=!0)}),Object.assign(n.autoplay,{start:S,stop:T,pause:x,resume:k})}function Mo(e,t){const r=Ir(t);return r!==t&&(r.style.backfaceVisibility="hidden",r.style["-webkit-backface-visibility"]="hidden"),r}function Oo(e){let{swiper:t,duration:r,transformElements:n,allSlides:i}=e;const{activeIndex:s}=t;if(t.params.virtualTranslate&&0!==r){let e,r=!1;e=i?n:n.filter(e=>{const r=e.classList.contains("swiper-slide-transform")?(e=>{if(!e.parentElement)return t.slides.filter(t=>t.shadowRoot&&t.shadowRoot===e.parentNode)[0];return e.parentElement})(e):e;return t.getSlideIndex(r)===s}),e.forEach(e=>{!function(e,t){t&&e.addEventListener("transitionend",function r(n){n.target===e&&(t.call(e,n),e.removeEventListener("transitionend",r))})}(e,()=>{if(r)return;if(!t||t.destroyed)return;r=!0,t.animating=!1;const e=new window.CustomEvent("transitionend",{bubbles:!0,cancelable:!0});t.wrapperEl.dispatchEvent(e)})})}}function No(e,t,r){const n=`swiper-slide-shadow swiper-slide-shadow-${e}`,i=Ir(t);let s=i.querySelector(`.${n.split(" ").join(".")}`);return s||(s=Dr("div",n.split(" ")),i.append(s)),s}function Fo(e){let{swiper:t,extendParams:r,on:n}=e;r({cardsEffect:{slideShadows:!0,rotate:!0,perSlideRotate:2,perSlideOffset:8}});!function(e){const{effect:t,swiper:r,on:n,setTranslate:i,setTransition:s,overwriteParams:a,perspective:o,recreateShadows:l,getEffectParams:u}=e;let c;n("beforeInit",()=>{if(r.params.effect!==t)return;r.classNames.push(`${r.params.containerModifierClass}${t}`),o&&o()&&r.classNames.push(`${r.params.containerModifierClass}3d`);const e=a?a():{};Object.assign(r.params,e),Object.assign(r.originalParams,e)}),n("setTranslate",()=>{r.params.effect===t&&i()}),n("setTransition",(e,n)=>{r.params.effect===t&&s(n)}),n("transitionEnd",()=>{if(r.params.effect===t&&l){if(!u||!u().slideShadows)return;r.slides.forEach(e=>{e.querySelectorAll(".swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left").forEach(e=>e.remove())}),l()}}),n("virtualUpdate",()=>{r.params.effect===t&&(r.slides.length||(c=!0),requestAnimationFrame(()=>{c&&r.slides&&r.slides.length&&(i(),c=!1)}))})}({effect:"cards",swiper:t,on:n,setTranslate:()=>{const{slides:e,activeIndex:r,rtlTranslate:n}=t,i=t.params.cardsEffect,{startTranslate:s,isTouched:a}=t.touchEventsData,o=n?-t.translate:t.translate;for(let l=0;l<e.length;l+=1){const u=e[l],c=u.progress,d=Math.min(Math.max(c,-4),4);let h=u.swiperSlideOffset;t.params.centeredSlides&&!t.params.cssMode&&(t.wrapperEl.style.transform=`translateX(${t.minTranslate()}px)`),t.params.centeredSlides&&t.params.cssMode&&(h-=e[0].swiperSlideOffset);let f=t.params.cssMode?-h-t.translate:-h,p=0;const g=-100*Math.abs(d);let m=1,v=-i.perSlideRotate*d,y=i.perSlideOffset-.75*Math.abs(d);const b=t.virtual&&t.params.virtual.enabled?t.virtual.from+l:l,w=(b===r||b===r-1)&&d>0&&d<1&&(a||t.params.cssMode)&&o<s,E=(b===r||b===r+1)&&d<0&&d>-1&&(a||t.params.cssMode)&&o>s;if(w||E){const e=(1-Math.abs((Math.abs(d)-.5)/.5))**.5;v+=-28*d*e,m+=-.5*e,y+=96*e,p=-25*e*Math.abs(d)+"%"}if(f=d<0?`calc(${f}px ${n?"-":"+"} (${y*Math.abs(d)}%))`:d>0?`calc(${f}px ${n?"-":"+"} (-${y*Math.abs(d)}%))`:`${f}px`,!t.isHorizontal()){const e=p;p=f,f=e}const S=d<0?""+(1+(1-m)*d):""+(1-(1-m)*d),T=`\n translate3d(${f}, ${p}, ${g}px)\n rotateZ(${i.rotate?n?-v:v:0}deg)\n scale(${S})\n `;if(i.slideShadows){let e=u.querySelector(".swiper-slide-shadow");e||(e=No("cards",u)),e&&(e.style.opacity=Math.min(Math.max((Math.abs(d)-.5)/.5,0),1))}u.style.zIndex=-Math.abs(Math.round(c))+e.length;Mo(0,u).style.transform=T}},setTransition:e=>{const r=t.slides.map(e=>Ir(e));r.forEach(t=>{t.style.transitionDuration=`${e}ms`,t.querySelectorAll(".swiper-slide-shadow").forEach(t=>{t.style.transitionDuration=`${e}ms`})}),Oo({swiper:t,duration:e,transformElements:r})},perspective:()=>!0,overwriteParams:()=>({watchSlidesProgress:!0,virtualTranslate:!t.params.cssMode})})}const $o=({products:e,useDrawer:t,contentId:r})=>{const n=p.useMemo(()=>(e=>{if(e.length>=3)return e;const t=[...e];for(;t.length<3;)t.push(...e);return t})(e),[e]),i=1===(null==e?void 0:e.length);return(null==e?void 0:e.length)?g.createElement("div",{className:"w-full",style:{height:"80px"}},i?g.createElement("div",{className:"bg-white overflow-hidden rounded-xl w-full",style:{borderRadius:"10px",height:"80px"}},t?g.createElement(Po,{products:e,contentId:r},g.createElement(pi,{product:e[0],productsLength:e.length,contentId:r})):g.createElement(pi,{product:e[0],productsLength:e.length,hideMoreBtn:!0,contentId:r})):g.createElement(_n,{nested:!0,modules:[Fo,_o],slidesPerView:1.1,effect:"cards",autoplay:!0,loop:!0,grabCursor:!0,cardsEffect:{rotate:!1},className:"w-full",style:{height:"80px"}},n.map((n,i)=>g.createElement(Mn,{key:i+n.productId,className:"bg-white overflow-hidden rounded-xl",style:{borderRadius:"10px",height:"80px"}},t?g.createElement(Po,{products:e,contentId:r},g.createElement(pi,{product:n,productsLength:e.length,contentId:r})):g.createElement(pi,{product:n,productsLength:e.length,hideMoreBtn:!0,contentId:r}))))):null},Bo=({shortForm:e,useDrawer:t,isPopup:r,shareUrl:n,handleClose:i})=>{const[s,a]=p.useState(!Boolean(r)),[o,l]=p.useState(!0),{logo:u,productsInfo:c,thumbPath:d,title:h,media:f,brand:m,shortsId:v}=e;return g.createElement("div",{className:"h-full w-full text-sm overflow-hidden text-white relative"},g.createElement("div",{style:{backgroundImage:"linear-gradient(to bottom, rgba(0,0,0,0.4) 0%, transparent 50%, rgba(0,0,0,0.4) 100%)",padding:"15px"},className:"absolute h-full flex flex-col w-full z-[1] justify-between inset-0 bg-gradient-to-b from-black/40 via-transparent to-black/40"},g.createElement("div",{className:"flex gap-2 justify-between "},g.createElement("div",{className:"max-w-16"},(null==u?void 0:u.thumbPath)?g.createElement("img",{className:"mb-1",src:u.thumbPath,alt:u.logoName,width:100,height:100}):null),g.createElement("div",{className:"justify-self-end flex gap-2"},g.createElement("div",{className:"cursor-pointer text-white ",onClick:()=>{l(e=>!e)}},o?g.createElement(ti,{size:20}):g.createElement(ri,{size:20})),g.createElement("div",{className:"cursor-pointer text-white ",onClick:()=>{a(e=>!e)}},s?g.createElement(si,{size:20}):g.createElement(ii,{size:20})),g.createElement("div",{className:"cursor-pointer text-white ",onClick:i},g.createElement(ai,{size:20})))),g.createElement("div",null,g.createElement("div",{className:"flex justify-between items-end mb-3 gap-3"},g.createElement("div",{className:"w-full"},m&&g.createElement("div",{className:"items-center flex gap-3 mb-2"},g.createElement("div",{className:"w-12 h-12 bg-white rounded-full border overflow-hidden"},g.createElement("img",{src:m.thumbPath,alt:m.brandName,width:100,height:100,className:"object-contain w-full h-full"})),g.createElement("p",{style:{fontSize:"14px",textAlign:"start"}},null==m?void 0:m.brandName)),g.createElement("p",{style:{fontSize:"14px",textAlign:"start"}},h)),g.createElement("div",{className:"flex flex-col items-center",style:{gap:"15px"}},g.createElement(ui,{shortsId:v}),g.createElement("div",{className:"w-[24px] h-[24px] flex items-center justify-center"},g.createElement(di,{shortForm:e,shareUrl:n})))),c&&g.createElement($o,{products:c,useDrawer:t,contentId:e.shortsId}))),g.createElement(oi,{file:Ft(null==f?void 0:f.objectId),thumbnail:`${Gt(d)}`,mute:s,isVertical:(null==f?void 0:f.height)>(null==f?void 0:f.width),play:o}))},Uo=g.memo(({shortform:e,shareUrl:t,handleClose:r})=>g.createElement(g.Fragment,null,g.createElement("div",{onClick:e=>e.stopPropagation(),className:"overflow-hidden",style:{borderRadius:"10px",overflow:"hidden",width:"100%",height:"100%",backgroundRepeat:"no-repeat",backgroundPosition:"center",backgroundSize:"cover",backgroundImage:`url(${Gt(e.thumbPath)})`}},g.createElement(Bo,{handleClose:r,shortForm:e,useDrawer:!1,isPopup:!0,shareUrl:t})))),zo=g.memo(({shortform:e})=>g.createElement("div",{onClick:e=>{e.stopPropagation()},style:{width:"100%",height:"100%",borderRadius:"10px",backgroundRepeat:"no-repeat",backgroundPosition:"center",backgroundSize:"cover",backgroundImage:`url(${e.thumbPath.includes("https")?e.thumbPath:`https://${e.thumbPath}`})`}})),jo=({shortform:e,shareUrl:t,handleClose:r})=>{const{isActive:n}=p.useContext(Pn),i=p.useContext(Dn),s=On().width<430||Hn.isMobile;return g.createElement("div",{className:"flex items-center justify-center w-full h-full select-none",onClick:e=>{r()}},g.createElement("div",{className:"max-h-full flex items-center justify-center",style:{width:"100%",aspectRatio:s?"auto":"9 / 16",height:s?"100dvh":"auto",maxHeight:s?void 0:"90vh",transform:s?void 0:`scale(${n?1:.8})`,transition:"transform 180ms ease"}},n?g.createElement("div",{className:"flex items-center justify-between w-full h-full text-white relative"},g.createElement("div",{className:"cursor-pointer absolute",onClick:e=>{e.stopPropagation(),i.slidePrev()},style:{zIndex:1e5,left:s?"0":"-30px",top:"50%",transform:"translateY(-50%)",width:30,height:30,display:"grid",placeItems:"center",pointerEvents:"auto"}},g.createElement(Qn,{size:28})),g.createElement(Uo,{shortform:e,shareUrl:t,handleClose:r}),g.createElement("div",{className:"cursor-pointer absolute",style:{zIndex:1e5,right:s?"0":"-30px",top:"50%",transform:"translateY(-50%)",width:30,height:30,display:"grid",placeItems:"center",pointerEvents:"auto"},onClick:e=>{e.stopPropagation(),i.slideNext()}},g.createElement(Zn,{size:28}))):g.createElement(zo,{shortform:e})))},{PLAYER_BACK_BASE_URL:Go}=Mt(),Ho=({collection:e,initialShortsId:t,onSlideChange:r,onClosePlayer:n})=>{var i;const s=p.useMemo(()=>Math.max(e.contents.findIndex(e=>e.shortsId===t),0),[e.contents,t]),a=e.contents.length,o=Math.max(a,10),l=null!==(i=On().width)&&void 0!==i?i:0,u=l<430||Hn.isMobile,c=u?1:l>=1200?4:l>=900?3:2,d=p.useMemo(()=>(e=>{const t=[...e];for(;t.length<o;)t.push(...e);return t})(e.contents),[e.contents]),h=p.useRef(null);return g.createElement("div",{style:{minHeight:100,minWidth:300},className:"w-full"},g.createElement(_n,{style:{minHeight:100,overflow:"visible"},initialSlide:s,ref:h,lazyPreloadPrevNext:2,className:"w-full",spaceBetween:u?8:l>=1200?24:l>=900?25:16,slidesPerView:c,grabCursor:!0,centeredSlides:1!==c,onSlideChangeTransitionEnd:t=>{const n=t.realIndex%a;null==r||r(n);const i=e.contents[(n+1)%a];var s;s=Ft(i.media.objectId),Nn||(Nn=document.createElement("video"),Nn.muted=!0,Nn.playsInline=!0,Nn.preload="metadata",Nn.loop=!0,Nn.style.cssText="position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;opacity:0",document.body.appendChild(Nn)),Fn!==s&&(Nn.src=s,Nn.load(),Fn=s)},loop:!0,slideToClickedSlide:!0},d.map((t,r)=>g.createElement(Mn,{key:r},g.createElement(jo,{handleClose:n,shortform:t,shareUrl:`${Go}/collection/${e.colId}?start=${t.shortsId}&layout=5`})))))},Vo=({shortform:e,onThumbnailClick:t,iconSize:r,exposeTitle:n,borderLine:i})=>{const s=p.useMemo(()=>jt(i),[i])?{background:"linear-gradient(#fff,#fff) padding-box, conic-gradient(#f58529,#f77737,#fd1d1d,#833ab4,#c13584,#f58529) border-box",border:"3px solid transparent"}:{background:"#fff",border:"3px solid #fff"};return g.createElement("div",{className:"flex flex-col w-full gap-2",onClick:()=>t(e.shortsId)},g.createElement("div",{className:"rounded-full overflow-hidden cursor-pointer",style:Object.assign({width:r,height:r,padding:4},s)},g.createElement("img",{src:Gt(e.thumbPath),alt:"thumbnail",className:"w-full h-full object-cover block rounded-full"})),n&&g.createElement("span",{style:{width:r},className:"text-black overflow-hidden text-[12px] whitespace-nowrap text-center text-clip cursor-default"},e.title))},Wo=ur(e=>({open:!1,setOpen:t=>e({open:t})})),Ko=({product:e,productLength:t,hideMoreBadge:r=!1,contentId:n,lineClamp:i,showMoreBtn:s=!1,openProductPopup:a})=>{const{isPreview:o}=cr();return g.createElement(g.Fragment,null,g.createElement("div",{className:"product-banner border mbus-border",onClick:()=>J(void 0,void 0,void 0,function*(){r&&(window.open(e.linkPath,"_blank"),o||(yield Zt({contentProductId:e.eventProductId,contentId:n,productId:e.productId})))})},g.createElement("span",{className:"product-banner__clip","aria-hidden":!0},g.createElement("span",{className:"product-banner__sheen"})),g.createElement("div",{className:"relative",style:{width:"40%",minWidth:"40%"}},g.createElement("img",{style:{borderRadius:"0.625rem"},className:"aspect-square rounded-lg object-cover w-full",src:Gt(e.thumbPath),alt:e.productName}),!r&&g.createElement("p",{className:"absolute text-white rounded-lg",style:{backgroundColor:"#797979",top:-10,right:-10,padding:"2px 4px",fontSize:"10px",borderRadius:"0.625rem"}},"+",t)),g.createElement("div",{style:{position:"relative",zIndex:2,minWidth:0,flex:1,paddingRight:24}},g.createElement("p",{style:{display:"-webkit-box",WebkitLineClamp:i||2,WebkitBoxOrient:"vertical",overflow:"hidden",wordBreak:"break-word",fontWeight:600,color:"#494949"}},e.productName)),g.createElement("span",{className:"product-banner__arrow","aria-hidden":!0},"›")),s&&t>1&&g.createElement("div",{onClick:a,className:" flex items-center justify-center border mbus-border cursor-pointer",style:{borderRadius:"0.625rem",padding:"10px",backgroundColor:"#f5f5f5",fontWeight:600}},"+ 더보기 (",t,")"))},Yo=({products:e,iconSize:t,contentId:r,setSelectedProducts:n,showMoreBtn:i,hideMoreBadge:s})=>{const{setOpen:a}=Wo(),o=()=>{n({productsInfo:e,shortsId:r}),a(!0)};return g.createElement(g.Fragment,null,g.createElement("div",{onClick:()=>J(void 0,void 0,void 0,function*(){1===e.length||i||o()}),className:"flex flex-col gap-2 mt-4 text-gray-800",style:{maxWidth:t||"100%",fontSize:13}},g.createElement(Ko,{showMoreBtn:i,lineClamp:2,product:e[0],contentId:r,productLength:e.length,hideMoreBadge:null!=s?s:1===e.length,openProductPopup:o})))},qo=({product:e,maxWidth:t="100%",height:r,cardWidth:n})=>g.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,borderRadius:8,backgroundColor:"#ffffff",color:"#111827",maxWidth:t,height:r,width:"100%",paddingRight:8}},g.createElement("img",{src:Gt(e.thumbPath),alt:e.productName,style:{height:"100%",aspectRatio:"1 / 1",borderRadius:6,objectFit:"cover",flexShrink:0}}),g.createElement("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",justifyContent:"center"}},g.createElement("span",{style:{lineHeight:1.25,overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",fontSize:12}},e.productName),g.createElement("span",{style:{lineHeight:1.25,overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",fontSize:11}},"number"==typeof e.sellingPrice&&e.sellingPrice<e.price?"number"==typeof n&&n>=190?g.createElement(g.Fragment,null,g.createElement("span",{style:{color:"#dc2626",fontWeight:600,marginRight:4}},Nt(e.sellingPrice),"원"),g.createElement("span",{style:{color:"#9ca3af",textDecoration:"line-through"}},Nt(e.price),"원")):g.createElement("span",{style:{color:"#dc2626",fontWeight:600}},Nt(e.sellingPrice),"원"):g.createElement("span",{style:{color:"#dc2626",fontWeight:600}},Nt(e.price),"원")))),Xo=({playUrl:e,poster:t})=>g.createElement("div",{className:"w-full h-full absolute top-0 left-0 z-10 pointer-events-none",style:{backgroundImage:`url(${t})`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat"}},g.createElement("video",{src:e,autoPlay:!0,muted:!0,preload:"auto",playsInline:!0,loop:!0,className:"w-full h-full object-cover"})),Qo=({shortform:e,onThumbnailClick:t,iconSize:r,exposeTitle:n,rounded:i,borderLine:s,titlePosition:a,exposeProductBanner:o,setSelectedProducts:l,iconRatio:u,hoverPlay:c,exposeProductBadge:d})=>{var h;const f=p.useMemo(()=>jt(s),[s]),[m,v]=p.useState(!1),{API_BASE_URL:y}=Mt();return g.createElement("div",{className:"relative"},g.createElement("div",{onMouseEnter:()=>v(!0),onMouseLeave:()=>v(!1),onClick:()=>t(e.shortsId),style:Object.assign({width:r,aspectRatio:u},i&&{borderRadius:"10px"}),className:`cursor-pointer p-[3px] ${i&&"rounded-xl"} ${f&&"bg-insta"} relative overflow-hidden`},m&&c&&g.createElement(Xo,{playUrl:`${y}/direct/${e.media.objectId}`,poster:Gt(e.thumbPath)}),g.createElement("img",{style:Object.assign({},i&&{borderRadius:"10px"}),src:Gt(e.thumbPath),alt:"thumbnail",className:`w-full h-full object-cover ${i&&"rounded-xl"}`}),d&&(null===(h=e.productsInfo)||void 0===h?void 0:h.length)>0&&!(c&&m)&&g.createElement("div",{className:"absolute pointer-events-none flex items-center justify-center z-20",style:{left:2,right:2,bottom:10,height:"20%"}},g.createElement("div",{className:"h-full inline-block",style:{width:"95%"}},g.createElement(qo,{product:e.productsInfo[0],maxWidth:"100%",height:"100%",cardWidth:r})))),n&&!(c&&m&&a===V.INNER)&&g.createElement("p",{style:Object.assign({width:r,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},a===V.INNER&&d?{bottom:"22%"}:{}),className:`my-2 ${a===V.INNER?"absolute bottom-0 left-0 text-white px-2 z-10":""} text-[12px] cursor-default truncate`},e.title),o&&g.createElement(Yo,{setSelectedProducts:l,products:e.productsInfo,iconSize:r,contentId:e.shortsId}))},Zo=e=>{const{iconShape:t,collection:r}=e;return t===j.MANY?g.createElement(Jo,Object.assign({},e)):g.createElement(el,Object.assign({},e,{shortform:r.contents[0]}))},Jo=e=>{const{collection:t}=e,{thumbnailAutoPlay:r}=e,{setCollection:n,nextKey:i,setNextKey:s,isFetching:a,setIsFetching:o}=fr();return g.createElement(_n,{freeMode:!0,slidesPerView:"auto",spaceBetween:12,onReachEnd:()=>J(void 0,void 0,void 0,function*(){var e,r,l;if(t&&!(a||(null!==(e=t.count)&&void 0!==e?e:Number.MAX_SAFE_INTEGER)<=t.contents.length)){o(!0);try{const e=yield tr({collectionId:t.colId,nextKey:i});if(!e||!(null===(r=e.contents)||void 0===r?void 0:r.length))return;s((null===(l=e.contents.at(-1))||void 0===l?void 0:l.shortsId)||"");const a=new Set(t.contents.map(e=>e.shortsId)),o=e.contents.filter(e=>!a.has(e.shortsId));if(!o.length)return;n(Object.assign(Object.assign({},t),{contents:[...t.contents,...o]}))}catch(e){console.error(e)}finally{o(!1)}}}),modules:r?[_o]:[],autoplay:!!r&&{delay:3e3,disableOnInteraction:!1,pauseOnMouseEnter:!0},loop:r||void 0},null==t?void 0:t.contents.map(t=>g.createElement(Mn,{key:t.shortsId,className:"!w-auto"},g.createElement(el,Object.assign({},e,{shortform:t})))))},el=e=>{const{iconForm:t}=e;return t===z.INSTA?g.createElement(Vo,Object.assign({},e)):g.createElement(Qo,Object.assign({},e))};function tl(e,t,{checkForDefaultPrevented:r=!0}={}){return function(n){if(e?.(n),!1===r||!n.defaultPrevented)return t?.(n)}}function rl(e,t){if("function"==typeof e)return e(t);null!=e&&(e.current=t)}function nl(...e){return t=>{let r=!1;const n=e.map(e=>{const n=rl(e,t);return r||"function"!=typeof n||(r=!0),n});if(r)return()=>{for(let t=0;t<n.length;t++){const r=n[t];"function"==typeof r?r():rl(e[t],null)}}}}function il(...e){return p.useCallback(nl(...e),e)}function sl(...e){const t=e[0];if(1===e.length)return t;const r=()=>{const r=e.map(e=>({useScope:e(),scopeName:e.scopeName}));return function(e){const n=r.reduce((t,{useScope:r,scopeName:n})=>({...t,...r(e)[`__scope${n}`]}),{});return p.useMemo(()=>({[`__scope${t.scopeName}`]:n}),[n])}};return r.scopeName=t.scopeName,r}var al=globalThis?.document?p.useLayoutEffect:()=>{},ol=m[" useId ".trim().toString()]||(()=>{}),ll=0;function ul(e){const[t,r]=p.useState(ol());return al(()=>{e||r(e=>e??String(ll++))},[e]),e||(t?`radix-${t}`:"")}var cl=m[" useInsertionEffect ".trim().toString()]||al;function dl({prop:e,defaultProp:t,onChange:r=()=>{},caller:n}){const[i,s,a]=function({defaultProp:e,onChange:t}){const[r,n]=p.useState(e),i=p.useRef(r),s=p.useRef(t);return cl(()=>{s.current=t},[t]),p.useEffect(()=>{i.current!==r&&(s.current?.(r),i.current=r)},[r,i]),[r,n,s]}({defaultProp:t,onChange:r}),o=void 0!==e,l=o?e:i;{const t=p.useRef(void 0!==e);p.useEffect(()=>{const e=t.current;if(e!==o){const t=e?"controlled":"uncontrolled",r=o?"controlled":"uncontrolled";console.warn(`${n} is changing from ${t} to ${r}. 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.`)}t.current=o},[o,n])}const u=p.useCallback(t=>{if(o){const r=function(e){return"function"==typeof e}(t)?t(e):t;r!==e&&a.current?.(r)}else s(t)},[o,e,s,a]);return[l,u]}function hl(e,t,{checkForDefaultPrevented:r=!0}={}){return function(n){if(e?.(n),!1===r||!n.defaultPrevented)return t?.(n)}}function fl(e,t){if("function"==typeof e)return e(t);null!=e&&(e.current=t)}function pl(...e){return t=>{let r=!1;const n=e.map(e=>{const n=fl(e,t);return r||"function"!=typeof n||(r=!0),n});if(r)return()=>{for(let t=0;t<n.length;t++){const r=n[t];"function"==typeof r?r():fl(e[t],null)}}}}function gl(...e){return p.useCallback(pl(...e),e)}function ml(e){const t=p.forwardRef((e,t)=>{const{children:r,...n}=e;if(p.isValidElement(r)){const e=function(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;if(r)return e.ref;if(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r)return e.props.ref;return e.props.ref||e.ref}(r),i=function(e,t){const r={...t};for(const n in t){const i=e[n],s=t[n];/^on[A-Z]/.test(n)?i&&s?r[n]=(...e)=>{const t=s(...e);return i(...e),t}:i&&(r[n]=i):"style"===n?r[n]={...i,...s}:"className"===n&&(r[n]=[i,s].filter(Boolean).join(" "))}return{...e,...r}}(n,r.props);return r.type!==p.Fragment&&(i.ref=t?pl(t,e):e),p.cloneElement(r,i)}return p.Children.count(r)>1?p.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var vl=Symbol("radix.slottable");function yl(e){return p.isValidElement(e)&&"function"==typeof e.type&&"__radixId"in e.type&&e.type.__radixId===vl}var bl=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,t)=>{const r=function(e){const t=ml(e),r=p.forwardRef((e,r)=>{const{children:n,...i}=e,s=p.Children.toArray(n),a=s.find(yl);if(a){const e=a.props.children,n=s.map(t=>t===a?p.Children.count(e)>1?p.Children.only(null):p.isValidElement(e)?e.props.children:null:t);return Ti.jsx(t,{...i,ref:r,children:p.isValidElement(e)?p.cloneElement(e,void 0,n):null})}return Ti.jsx(t,{...i,ref:r,children:n})});return r.displayName=`${e}.Slot`,r}(`Primitive.${t}`),n=p.forwardRef((e,n)=>{const{asChild:i,...s}=e,a=i?r:t;return"undefined"!=typeof window&&(window[Symbol.for("radix-ui")]=!0),Ti.jsx(a,{...s,ref:n})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});var wl,El="dismissableLayer.update",Sl="dismissableLayer.pointerDownOutside",Tl="dismissableLayer.focusOutside",xl=p.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),kl=p.forwardRef((e,t)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:n,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:a,onDismiss:o,...l}=e,u=p.useContext(xl),[c,d]=p.useState(null),h=c?.ownerDocument??globalThis?.document,[,f]=p.useState({}),g=gl(t,e=>d(e)),m=Array.from(u.layers),[v]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),y=m.indexOf(v),b=c?m.indexOf(c):-1,w=u.layersWithOutsidePointerEventsDisabled.size>0,E=b>=y,S=function(e,t=globalThis?.document){const r=$i(e),n=p.useRef(!1),i=p.useRef(()=>{});return p.useEffect(()=>{const e=e=>{if(e.target&&!n.current){let n=function(){Rl(Sl,r,s,{discrete:!0})};const s={originalEvent:e};"touch"===e.pointerType?(t.removeEventListener("click",i.current),i.current=n,t.addEventListener("click",i.current,{once:!0})):n()}else t.removeEventListener("click",i.current);n.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",e)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",e),t.removeEventListener("click",i.current)}},[t,r]),{onPointerDownCapture:()=>n.current=!0}}(e=>{const t=e.target,r=[...u.branches].some(e=>e.contains(t));E&&!r&&(i?.(e),a?.(e),e.defaultPrevented||o?.())},h),T=function(e,t=globalThis?.document){const r=$i(e),n=p.useRef(!1);return p.useEffect(()=>{const e=e=>{if(e.target&&!n.current){Rl(Tl,r,{originalEvent:e},{discrete:!1})}};return t.addEventListener("focusin",e),()=>t.removeEventListener("focusin",e)},[t,r]),{onFocusCapture:()=>n.current=!0,onBlurCapture:()=>n.current=!1}}(e=>{const t=e.target;[...u.branches].some(e=>e.contains(t))||(s?.(e),a?.(e),e.defaultPrevented||o?.())},h);return Bi(e=>{b===u.layers.size-1&&(n?.(e),!e.defaultPrevented&&o&&(e.preventDefault(),o()))},h),p.useEffect(()=>{if(c)return r&&(0===u.layersWithOutsidePointerEventsDisabled.size&&(wl=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(c)),u.layers.add(c),Al(),()=>{r&&1===u.layersWithOutsidePointerEventsDisabled.size&&(h.body.style.pointerEvents=wl)}},[c,h,r,u]),p.useEffect(()=>()=>{c&&(u.layers.delete(c),u.layersWithOutsidePointerEventsDisabled.delete(c),Al())},[c,u]),p.useEffect(()=>{const e=()=>f({});return document.addEventListener(El,e),()=>document.removeEventListener(El,e)},[]),Ti.jsx(bl.div,{...l,ref:g,style:{pointerEvents:w?E?"auto":"none":void 0,...e.style},onFocusCapture:hl(e.onFocusCapture,T.onFocusCapture),onBlurCapture:hl(e.onBlurCapture,T.onBlurCapture),onPointerDownCapture:hl(e.onPointerDownCapture,S.onPointerDownCapture)})});kl.displayName="DismissableLayer";function Al(){const e=new CustomEvent(El);document.dispatchEvent(e)}function Rl(e,t,r,{discrete:n}){const i=r.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:r});t&&i.addEventListener(e,t,{once:!0}),n?function(e,t){e&&Pi.flushSync(()=>e.dispatchEvent(t))}(i,s):i.dispatchEvent(s)}p.forwardRef((e,t)=>{const r=p.useContext(xl),n=p.useRef(null),i=gl(t,n);return p.useEffect(()=>{const e=n.current;if(e)return r.branches.add(e),()=>{r.branches.delete(e)}},[r.branches]),Ti.jsx(bl.div,{...e,ref:i})}).displayName="DismissableLayerBranch";var Ll=e=>{const{present:t,children:r}=e,n=function(e){const[t,r]=p.useState(),n=p.useRef(null),i=p.useRef(e),s=p.useRef("none"),a=e?"mounted":"unmounted",[o,l]=function(e,t){return p.useReducer((e,r)=>t[e][r]??e,e)}(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return p.useEffect(()=>{const e=Il(n.current);s.current="mounted"===o?e:"none"},[o]),al(()=>{const t=n.current,r=i.current;if(r!==e){const n=s.current,a=Il(t);if(e)l("MOUNT");else if("none"===a||"none"===t?.display)l("UNMOUNT");else{l(r&&n!==a?"ANIMATION_OUT":"UNMOUNT")}i.current=e}},[e,l]),al(()=>{if(t){let e;const r=t.ownerDocument.defaultView??window,a=s=>{const a=Il(n.current).includes(s.animationName);if(s.target===t&&a&&(l("ANIMATION_END"),!i.current)){const n=t.style.animationFillMode;t.style.animationFillMode="forwards",e=r.setTimeout(()=>{"forwards"===t.style.animationFillMode&&(t.style.animationFillMode=n)})}},o=e=>{e.target===t&&(s.current=Il(n.current))};return t.addEventListener("animationstart",o),t.addEventListener("animationcancel",a),t.addEventListener("animationend",a),()=>{r.clearTimeout(e),t.removeEventListener("animationstart",o),t.removeEventListener("animationcancel",a),t.removeEventListener("animationend",a)}}l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(o),ref:p.useCallback(e=>{n.current=e?getComputedStyle(e):null,r(e)},[])}}(t),i="function"==typeof r?r({present:n.isPresent}):p.Children.only(r),s=il(n.ref,function(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;if(r)return e.ref;if(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r)return e.props.ref;return e.props.ref||e.ref}(i));return"function"==typeof r||n.isPresent?p.cloneElement(i,{ref:s}):null};function Il(e){return e?.animationName||"none"}function Cl(e){const t=Pl(e),r=p.forwardRef((e,r)=>{const{children:n,...i}=e,s=p.Children.toArray(n),a=s.find(_l);if(a){const e=a.props.children,n=s.map(t=>t===a?p.Children.count(e)>1?p.Children.only(null):p.isValidElement(e)?e.props.children:null:t);return Ti.jsx(t,{...i,ref:r,children:p.isValidElement(e)?p.cloneElement(e,void 0,n):null})}return Ti.jsx(t,{...i,ref:r,children:n})});return r.displayName=`${e}.Slot`,r}function Pl(e){const t=p.forwardRef((e,t)=>{const{children:r,...n}=e;if(p.isValidElement(r)){const e=function(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;if(r)return e.ref;if(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r)return e.props.ref;return e.props.ref||e.ref}(r),i=function(e,t){const r={...t};for(const n in t){const i=e[n],s=t[n];/^on[A-Z]/.test(n)?i&&s?r[n]=(...e)=>{const t=s(...e);return i(...e),t}:i&&(r[n]=i):"style"===n?r[n]={...i,...s}:"className"===n&&(r[n]=[i,s].filter(Boolean).join(" "))}return{...e,...r}}(n,r.props);return r.type!==p.Fragment&&(i.ref=t?nl(t,e):e),p.cloneElement(r,i)}return p.Children.count(r)>1?p.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}Ll.displayName="Presence";var Dl=Symbol("radix.slottable");function _l(e){return p.isValidElement(e)&&"function"==typeof e.type&&"__radixId"in e.type&&e.type.__radixId===Dl}var Ml=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,t)=>{const r=Cl(`Primitive.${t}`),n=p.forwardRef((e,n)=>{const{asChild:i,...s}=e,a=i?r:t;return"undefined"!=typeof window&&(window[Symbol.for("radix-ui")]=!0),Ti.jsx(a,{...s,ref:n})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{}),Ol=0;function Nl(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Fl="Dialog",[$l,Bl]=function(e,t=[]){let r=[];const n=()=>{const t=r.map(e=>p.createContext(e));return function(r){const n=r?.[e]||t;return p.useMemo(()=>({[`__scope${e}`]:{...r,[e]:n}}),[r,n])}};return n.scopeName=e,[function(t,n){const i=p.createContext(n),s=r.length;r=[...r,n];const a=t=>{const{scope:r,children:n,...a}=t,o=r?.[e]?.[s]||i,l=p.useMemo(()=>a,Object.values(a));return Ti.jsx(o.Provider,{value:l,children:n})};return a.displayName=t+"Provider",[a,function(r,a){const o=a?.[e]?.[s]||i,l=p.useContext(o);if(l)return l;if(void 0!==n)return n;throw new Error(`\`${r}\` must be used within \`${t}\``)}]},sl(n,...t)]}(Fl),[Ul,zl]=$l(Fl),jl=e=>{const{__scopeDialog:t,children:r,open:n,defaultOpen:i,onOpenChange:s,modal:a=!0}=e,o=p.useRef(null),l=p.useRef(null),[u,c]=dl({prop:n,defaultProp:i??!1,onChange:s,caller:Fl});return Ti.jsx(Ul,{scope:t,triggerRef:o,contentRef:l,contentId:ul(),titleId:ul(),descriptionId:ul(),open:u,onOpenChange:c,onOpenToggle:p.useCallback(()=>c(e=>!e),[c]),modal:a,children:r})};jl.displayName=Fl;var Gl="DialogTrigger";p.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,i=zl(Gl,r),s=il(t,i.triggerRef);return Ti.jsx(Ml.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":uu(i.open),...n,ref:s,onClick:tl(e.onClick,i.onOpenToggle)})}).displayName=Gl;var Hl="DialogPortal",[Vl,Wl]=$l(Hl,{forceMount:void 0}),Kl=e=>{const{__scopeDialog:t,forceMount:r,children:n,container:i}=e,s=zl(Hl,t);return Ti.jsx(Vl,{scope:t,forceMount:r,children:p.Children.map(n,e=>Ti.jsx(Ll,{present:r||s.open,children:Ti.jsx(is,{asChild:!0,container:i,children:e})}))})};Kl.displayName=Hl;var Yl="DialogOverlay",ql=p.forwardRef((e,t)=>{const r=Wl(Yl,e.__scopeDialog),{forceMount:n=r.forceMount,...i}=e,s=zl(Yl,e.__scopeDialog);return s.modal?Ti.jsx(Ll,{present:n||s.open,children:Ti.jsx(Ql,{...i,ref:t})}):null});ql.displayName=Yl;var Xl=Cl("DialogOverlay.RemoveScroll"),Ql=p.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,i=zl(Yl,r);return Ti.jsx(Ks,{as:Xl,allowPinchZoom:!0,shards:[i.contentRef],children:Ti.jsx(Ml.div,{"data-state":uu(i.open),...n,ref:t,style:{pointerEvents:"auto",...n.style}})})}),Zl="DialogContent",Jl=p.forwardRef((e,t)=>{const r=Wl(Zl,e.__scopeDialog),{forceMount:n=r.forceMount,...i}=e,s=zl(Zl,e.__scopeDialog);return Ti.jsx(Ll,{present:n||s.open,children:s.modal?Ti.jsx(eu,{...i,ref:t}):Ti.jsx(tu,{...i,ref:t})})});Jl.displayName=Zl;var eu=p.forwardRef((e,t)=>{const r=zl(Zl,e.__scopeDialog),n=p.useRef(null),i=il(t,r.contentRef,n);return p.useEffect(()=>{const e=n.current;if(e)return ea(e)},[]),Ti.jsx(ru,{...e,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:tl(e.onCloseAutoFocus,e=>{e.preventDefault(),r.triggerRef.current?.focus()}),onPointerDownOutside:tl(e.onPointerDownOutside,e=>{const t=e.detail.originalEvent,r=0===t.button&&!0===t.ctrlKey;(2===t.button||r)&&e.preventDefault()}),onFocusOutside:tl(e.onFocusOutside,e=>e.preventDefault())})}),tu=p.forwardRef((e,t)=>{const r=zl(Zl,e.__scopeDialog),n=p.useRef(!1),i=p.useRef(!1);return Ti.jsx(ru,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:t=>{e.onCloseAutoFocus?.(t),t.defaultPrevented||(n.current||r.triggerRef.current?.focus(),t.preventDefault()),n.current=!1,i.current=!1},onInteractOutside:t=>{e.onInteractOutside?.(t),t.defaultPrevented||(n.current=!0,"pointerdown"===t.detail.originalEvent.type&&(i.current=!0));const s=t.target,a=r.triggerRef.current?.contains(s);a&&t.preventDefault(),"focusin"===t.detail.originalEvent.type&&i.current&&t.preventDefault()}})}),ru=p.forwardRef((e,t)=>{const{__scopeDialog:r,trapFocus:n,onOpenAutoFocus:i,onCloseAutoFocus:s,...a}=e,o=zl(Zl,r),l=p.useRef(null),u=il(t,l);return p.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Nl()),document.body.insertAdjacentElement("beforeend",e[1]??Nl()),Ol++,()=>{1===Ol&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),Ol--}},[]),Ti.jsxs(Ti.Fragment,{children:[Ti.jsx(Qi,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:i,onUnmountAutoFocus:s,children:Ti.jsx(kl,{role:"dialog",id:o.contentId,"aria-describedby":o.descriptionId,"aria-labelledby":o.titleId,"data-state":uu(o.open),...a,ref:u,onDismiss:()=>o.onOpenChange(!1)})}),Ti.jsxs(Ti.Fragment,{children:[Ti.jsx(fu,{titleId:o.titleId}),Ti.jsx(pu,{contentRef:l,descriptionId:o.descriptionId})]})]})}),nu="DialogTitle",iu=p.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,i=zl(nu,r);return Ti.jsx(Ml.h2,{id:i.titleId,...n,ref:t})});iu.displayName=nu;var su="DialogDescription",au=p.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,i=zl(su,r);return Ti.jsx(Ml.p,{id:i.descriptionId,...n,ref:t})});au.displayName=su;var ou="DialogClose",lu=p.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,i=zl(ou,r);return Ti.jsx(Ml.button,{type:"button",...n,ref:t,onClick:tl(e.onClick,()=>i.onOpenChange(!1))})});function uu(e){return e?"open":"closed"}lu.displayName=ou;var cu="DialogTitleWarning",[du,hu]=function(e,t){const r=p.createContext(t),n=e=>{const{children:t,...n}=e,i=p.useMemo(()=>n,Object.values(n));return Ti.jsx(r.Provider,{value:i,children:t})};return n.displayName=e+"Provider",[n,function(n){const i=p.useContext(r);if(i)return i;if(void 0!==t)return t;throw new Error(`\`${n}\` must be used within \`${e}\``)}]}(cu,{contentName:Zl,titleName:nu,docsSlug:"dialog"}),fu=({titleId:e})=>{const t=hu(cu),r=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.\n\nIf you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.\n\nFor more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return p.useEffect(()=>{if(e){document.getElementById(e)||console.error(r)}},[r,e]),null},pu=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${hu("DialogDescriptionWarning").contentName}}.`;return p.useEffect(()=>{const n=e.current?.getAttribute("aria-describedby");if(t&&n){document.getElementById(t)||console.warn(r)}},[r,e,t]),null},gu=jl,mu=Kl,vu=ql,yu=Jl,bu=iu,wu=lu;function Eu(e){return p.createElement(gu,Object.assign({"data-slot":"dialog"},e))}function Su(e){var t=Z(e,[]);return p.createElement(mu,Object.assign({"data-slot":"dialog-portal"},t))}function Tu(e){var{className:t}=e,r=Z(e,["className"]);return p.createElement(vu,Object.assign({"data-slot":"dialog-overlay",className:Ot("fixed inset-0 z-50 bg-black/50",t)},r))}function xu(e){var{className:t,children:r,showCloseButton:n=!0,container:i}=e,s=Z(e,["className","children","showCloseButton","container"]);return p.createElement(Su,{"data-slot":"dialog-portal",container:i},p.createElement(Tu,null),p.createElement(yu,Object.assign({"data-slot":"dialog-content",style:{left:"50%",top:"50%",transform:"translate(-50%, -50%)",outline:"none"},className:Ot("fixed","z-50 grid w-full max-w-lg sm:mx-0 gap-4 p-6",t)},s),r,n&&p.createElement(wu,{"data-slot":"dialog-close",style:{right:"calc(var(--spacing) * 4)",top:"calc(var(--spacing) * 4)",outline:"none"},className:Ot("absolute right-4 top-4 rounded opacity-70 transition-opacity","hover:opacity-100 focus:outline-none","focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:ring-offset-background","disabled:pointer-events-none"),"aria-label":"Close"},p.createElement(ai,{className:"h-4 w-4 pointer-events-none shrink-0",style:{height:"calc(var(--spacing) * 4)",width:"calc(var(--spacing) * 4)"}}))))}function ku(e){var{className:t}=e,r=Z(e,["className"]);return p.createElement("div",Object.assign({"data-slot":"dialog-header",className:Ot("flex flex-col gap-2 text-left",t)},r))}function Au(e){var{className:t}=e,r=Z(e,["className"]);return p.createElement(bu,Object.assign({"data-slot":"dialog-title",className:Ot("text-lg leading-none font-semibold",t)},r))}function Ru({title:e,children:t,contentClassName:r,hideCloseButton:n=!1,portalContainer:i,description:s}){const{open:a,setOpen:o}=Wo();return g.createElement(Eu,{open:a,onOpenChange:o},g.createElement(xu,{container:i,className:r,showCloseButton:!n},e&&g.createElement(ku,null,g.createElement(Au,{style:{color:"#494949"}},e||""),g.createElement(au,{style:{color:"#5e5e5e",fontSize:"12.5px"}},s||"")),t))}const Lu=({products:e,contentId:t})=>{const r=On().width<430||Hn.isMobile;return g.createElement("div",{onWheel:e=>e.stopPropagation(),onTouchMove:e=>e.stopPropagation(),className:"grid gap-2 "+(r?"grid-cols-1":"grid-cols-2"),style:{fontSize:13}},e.map(r=>g.createElement(Ko,{key:r.productId,product:r,hideMoreBadge:!0,productLength:e.length,contentId:t})))},{PLAYER_BACK_BASE_URL:Iu}=Mt(),Cu=({widgetPlayerOption:e,setCollectionUuid:t,portalContainer:r})=>{const{player:n}=e,[i,s]=p.useState(null),{collection:a}=fr(),{isPreview:o}=cr(),{onSlideChange:l,onCollectionClose:u}=pr(i,s),{setOpen:c,open:d}=Wo();p.useEffect(()=>{d||(i&&(u(),s(null)),h&&f(null))},[d]);const[h,f]=p.useState();return g.createElement(g.Fragment,null,a&&g.createElement(Zo,Object.assign({collection:a},e,{onThumbnailClick:e=>J(void 0,void 0,void 0,function*(){if(n===H.POPUP){const r=Ut(),n=Ut();if(t(n),s(Object.assign(Object.assign({},a.contents.find(t=>t.shortsId===e)),{uuid:r})),c(!0),o)return;yield Promise.all([Xt({contentId:a.colId,uuid:n,type:X.COLLECTION,userId:a.userId,isFirstPlay:!zt(a.colId)}),Xt({contentId:e,uuid:r,type:X.SHORTS,userId:a.userId,isFirstPlay:!zt(e)})])}else{const t=(e=>{switch(e){case H.HORIZONTAL:return W.HORIZONTAL;case H.VERTICAL:return W.VERTICAL;case H.GRID:return W.PRODUCTS;case H.TABLET:return W.TABLET;default:return W.PLATFORM}})(n),r=null==a?void 0:a.contents.findIndex(t=>t.shortsId===e);let i="";r&&r>1&&(i=(null==a?void 0:a.contents[r-1].shortsId)||""),open(`${Iu}/collection/${a.colId}?nextKey=${i}&layout=${t}`)}}),setSelectedProducts:f})),h&&g.createElement(Ru,{portalContainer:r,title:"상품 목록",contentClassName:"bg-white rounded p-4 product-dialog-container",description:"상품 정보를 확인해 보세요"},g.createElement(Lu,{products:h.productsInfo,contentId:h.shortsId})),a&&i&&g.createElement(Ru,{portalContainer:r,hideCloseButton:!0,contentClassName:"w-full max-w-none p-0 mx-0"},g.createElement(Ho,{collection:a,initialShortsId:i.shortsId,onClosePlayer:()=>J(void 0,void 0,void 0,function*(){u(),c(!1)}),onSlideChange:l})))};var Pu,Du={},_u={};function Mu(){if(Pu)return _u;Pu=1;var e=l();function t(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r<arguments.length;r++)t+="&args[]="+encodeURIComponent(arguments[r]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var r=Object.prototype.hasOwnProperty,n=/^[: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]*$/,i={},s={};function a(e){return!!r.call(s,e)||!r.call(i,e)&&(n.test(e)?s[e]=!0:(i[e]=!0,!1))}function o(e,t,r,n,i,s,a){this.acceptsBooleans=2===t||3===t||4===t,this.attributeName=n,this.attributeNamespace=i,this.mustUseProperty=r,this.propertyName=e,this.type=t,this.sanitizeURL=s,this.removeEmptyString=a}var u={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){u[e]=new o(e,0,!1,e,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];u[t]=new o(t,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){u[e]=new o(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){u[e]=new o(e,2,!1,e,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){u[e]=new o(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){u[e]=new o(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){u[e]=new o(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){u[e]=new o(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){u[e]=new o(e,5,!1,e.toLowerCase(),null,!1,!1)});var c=/[\-:]([a-z])/g;function d(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(c,d);u[t]=new o(t,1,!1,e,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(c,d);u[t]=new o(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(c,d);u[t]=new o(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){u[e]=new o(e,1,!1,e.toLowerCase(),null,!1,!1)}),u.xlinkHref=new o("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){u[e]=new o(e,1,!1,e.toLowerCase(),null,!0,!0)});var h={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},f=["Webkit","ms","Moz","O"];Object.keys(h).forEach(function(e){f.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),h[t]=h[e]})});var p=/["'&<>]/;function g(e){if("boolean"==typeof e||"number"==typeof e)return""+e;e=""+e;var t=p.exec(e);if(t){var r,n="",i=0;for(r=t.index;r<e.length;r++){switch(e.charCodeAt(r)){case 34:t=""";break;case 38:t="&";break;case 39:t="'";break;case 60:t="<";break;case 62:t=">";break;default:continue}i!==r&&(n+=e.substring(i,r)),i=r+1,n+=t}e=i!==r?n+e.substring(i,r):n}return e}var m=/([A-Z])/g,v=/^ms-/,y=Array.isArray;function b(e,t){return{insertionMode:e,selectedValue:t}}var w=new Map;function E(e,n,i){if("object"!=typeof i)throw Error(t(62));for(var s in n=!0,i)if(r.call(i,s)){var a=i[s];if(null!=a&&"boolean"!=typeof a&&""!==a){if(0===s.indexOf("--")){var o=g(s);a=g((""+a).trim())}else{o=s;var l=w.get(o);void 0!==l||(l=g(o.replace(m,"-$1").toLowerCase().replace(v,"-ms-")),w.set(o,l)),o=l,a="number"==typeof a?0===a||r.call(h,s)?""+a:a+"px":g((""+a).trim())}n?(n=!1,e.push(' style="',o,":",a)):e.push(";",o,":",a)}}n||e.push('"')}function S(e,t,r,n){switch(r){case"style":return void E(e,t,n);case"defaultValue":case"defaultChecked":case"innerHTML":case"suppressContentEditableWarning":case"suppressHydrationWarning":return}if(!(2<r.length)||"o"!==r[0]&&"O"!==r[0]||"n"!==r[1]&&"N"!==r[1])if(null!==(t=u.hasOwnProperty(r)?u[r]:null)){switch(typeof n){case"function":case"symbol":return;case"boolean":if(!t.acceptsBooleans)return}switch(r=t.attributeName,t.type){case 3:n&&e.push(" ",r,'=""');break;case 4:!0===n?e.push(" ",r,'=""'):!1!==n&&e.push(" ",r,'="',g(n),'"');break;case 5:isNaN(n)||e.push(" ",r,'="',g(n),'"');break;case 6:!isNaN(n)&&1<=n&&e.push(" ",r,'="',g(n),'"');break;default:t.sanitizeURL&&(n=""+n),e.push(" ",r,'="',g(n),'"')}}else if(a(r)){switch(typeof n){case"function":case"symbol":return;case"boolean":if("data-"!==(t=r.toLowerCase().slice(0,5))&&"aria-"!==t)return}e.push(" ",r,'="',g(n),'"')}}function T(e,r,n){if(null!=r){if(null!=n)throw Error(t(60));if("object"!=typeof r||!("__html"in r))throw Error(t(61));null!=(r=r.__html)&&e.push(""+r)}}function x(e,t,n,i){e.push(R(n));var s,a=n=null;for(s in t)if(r.call(t,s)){var o=t[s];if(null!=o)switch(s){case"children":n=o;break;case"dangerouslySetInnerHTML":a=o;break;default:S(e,i,s,o)}}return e.push(">"),T(e,a,n),"string"==typeof n?(e.push(g(n)),null):n}var k=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,A=new Map;function R(e){var r=A.get(e);if(void 0===r){if(!k.test(e))throw Error(t(65,e));r="<"+e,A.set(e,r)}return r}function L(n,i,s,o,l){switch(i){case"select":n.push(R("select"));var u=null,c=null;for(p in s)if(r.call(s,p)){var d=s[p];if(null!=d)switch(p){case"children":u=d;break;case"dangerouslySetInnerHTML":c=d;break;case"defaultValue":case"value":break;default:S(n,o,p,d)}}return n.push(">"),T(n,c,u),u;case"option":c=l.selectedValue,n.push(R("option"));var h=d=null,f=null,p=null;for(u in s)if(r.call(s,u)){var m=s[u];if(null!=m)switch(u){case"children":d=m;break;case"selected":f=m;break;case"dangerouslySetInnerHTML":p=m;break;case"value":h=m;default:S(n,o,u,m)}}if(null!=c)if(s=null!==h?""+h:function(t){var r="";return e.Children.forEach(t,function(e){null!=e&&(r+=e)}),r}(d),y(c)){for(o=0;o<c.length;o++)if(""+c[o]===s){n.push(' selected=""');break}}else""+c===s&&n.push(' selected=""');else f&&n.push(' selected=""');return n.push(">"),T(n,p,d),d;case"textarea":for(d in n.push(R("textarea")),p=c=u=null,s)if(r.call(s,d)&&null!=(h=s[d]))switch(d){case"children":p=h;break;case"value":u=h;break;case"defaultValue":c=h;break;case"dangerouslySetInnerHTML":throw Error(t(91));default:S(n,o,d,h)}if(null===u&&null!==c&&(u=c),n.push(">"),null!=p){if(null!=u)throw Error(t(92));if(y(p)&&1<p.length)throw Error(t(93));u=""+p}return"string"==typeof u&&"\n"===u[0]&&n.push("\n"),null!==u&&n.push(g(""+u)),null;case"input":for(c in n.push(R("input")),h=p=d=u=null,s)if(r.call(s,c)&&null!=(f=s[c]))switch(c){case"children":case"dangerouslySetInnerHTML":throw Error(t(399,"input"));case"defaultChecked":h=f;break;case"defaultValue":d=f;break;case"checked":p=f;break;case"value":u=f;break;default:S(n,o,c,f)}return null!==p?S(n,o,"checked",p):null!==h&&S(n,o,"checked",h),null!==u?S(n,o,"value",u):null!==d&&S(n,o,"value",d),n.push("/>"),null;case"menuitem":for(var v in n.push(R("menuitem")),s)if(r.call(s,v)&&null!=(u=s[v]))switch(v){case"children":case"dangerouslySetInnerHTML":throw Error(t(400));default:S(n,o,v,u)}return n.push(">"),null;case"title":for(m in n.push(R("title")),u=null,s)if(r.call(s,m)&&null!=(c=s[m]))switch(m){case"children":u=c;break;case"dangerouslySetInnerHTML":throw Error(t(434));default:S(n,o,m,c)}return n.push(">"),u;case"listing":case"pre":for(h in n.push(R(i)),c=u=null,s)if(r.call(s,h)&&null!=(d=s[h]))switch(h){case"children":u=d;break;case"dangerouslySetInnerHTML":c=d;break;default:S(n,o,h,d)}if(n.push(">"),null!=c){if(null!=u)throw Error(t(60));if("object"!=typeof c||!("__html"in c))throw Error(t(61));null!=(s=c.__html)&&("string"==typeof s&&0<s.length&&"\n"===s[0]?n.push("\n",s):n.push(""+s))}return"string"==typeof u&&"\n"===u[0]&&n.push("\n"),u;case"area":case"base":case"br":case"col":case"embed":case"hr":case"img":case"keygen":case"link":case"meta":case"param":case"source":case"track":case"wbr":for(var b in n.push(R(i)),s)if(r.call(s,b)&&null!=(u=s[b]))switch(b){case"children":case"dangerouslySetInnerHTML":throw Error(t(399,i));default:S(n,o,b,u)}return n.push("/>"),null;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 x(n,s,i,o);case"html":return 0===l.insertionMode&&n.push("<!DOCTYPE html>"),x(n,s,i,o);default:if(-1===i.indexOf("-")&&"string"!=typeof s.is)return x(n,s,i,o);for(f in n.push(R(i)),c=u=null,s)if(r.call(s,f)&&null!=(d=s[f]))switch(f){case"children":u=d;break;case"dangerouslySetInnerHTML":c=d;break;case"style":E(n,o,d);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":break;default:a(f)&&"function"!=typeof d&&"symbol"!=typeof d&&n.push(" ",f,'="',g(d),'"')}return n.push(">"),T(n,c,u),u}}function I(e,r,n){if(e.push('\x3c!--$?--\x3e<template id="'),null===n)throw Error(t(395));return e.push(n),e.push('"></template>')}var C=/[<\u2028\u2029]/g;function P(e){return JSON.stringify(e).replace(C,function(e){switch(e){case"<":return"\\u003c";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:throw Error("escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React")}})}function D(e,t,r,n){return r.generateStaticMarkup?(e.push(g(t)),!1):(""===t?e=n:(n&&e.push("\x3c!-- --\x3e"),e.push(g(t)),e=!0),e)}var _=Object.assign,M=Symbol.for("react.element"),O=Symbol.for("react.portal"),N=Symbol.for("react.fragment"),F=Symbol.for("react.strict_mode"),$=Symbol.for("react.profiler"),B=Symbol.for("react.provider"),U=Symbol.for("react.context"),z=Symbol.for("react.forward_ref"),j=Symbol.for("react.suspense"),G=Symbol.for("react.suspense_list"),H=Symbol.for("react.memo"),V=Symbol.for("react.lazy"),W=Symbol.for("react.scope"),K=Symbol.for("react.debug_trace_mode"),Y=Symbol.for("react.legacy_hidden"),q=Symbol.for("react.default_value"),X=Symbol.iterator;function Q(e){if(null==e)return null;if("function"==typeof e)return e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case N:return"Fragment";case O:return"Portal";case $:return"Profiler";case F:return"StrictMode";case j:return"Suspense";case G:return"SuspenseList"}if("object"==typeof e)switch(e.$$typeof){case U:return(e.displayName||"Context")+".Consumer";case B:return(e._context.displayName||"Context")+".Provider";case z:var t=e.render;return(e=e.displayName)||(e=""!==(e=t.displayName||t.name||"")?"ForwardRef("+e+")":"ForwardRef"),e;case H:return null!==(t=e.displayName||null)?t:Q(e.type)||"Memo";case V:t=e._payload,e=e._init;try{return Q(e(t))}catch(e){}}return null}var Z={};function J(e,t){if(!(e=e.contextTypes))return Z;var r,n={};for(r in e)n[r]=t[r];return n}var ee=null;function te(e,r){if(e!==r){e.context._currentValue2=e.parentValue,e=e.parent;var n=r.parent;if(null===e){if(null!==n)throw Error(t(401))}else{if(null===n)throw Error(t(401));te(e,n)}r.context._currentValue2=r.value}}function re(e){e.context._currentValue2=e.parentValue,null!==(e=e.parent)&&re(e)}function ne(e){var t=e.parent;null!==t&&ne(t),e.context._currentValue2=e.value}function ie(e,r){if(e.context._currentValue2=e.parentValue,null===(e=e.parent))throw Error(t(402));e.depth===r.depth?te(e,r):ie(e,r)}function se(e,r){var n=r.parent;if(null===n)throw Error(t(402));e.depth===n.depth?te(e,n):se(e,n),r.context._currentValue2=r.value}function ae(e){var t=ee;t!==e&&(null===t?ne(e):null===e?re(t):t.depth===e.depth?te(t,e):t.depth>e.depth?ie(t,e):se(t,e),ee=e)}var oe={isMounted:function(){return!1},enqueueSetState:function(e,t){null!==(e=e._reactInternals).queue&&e.queue.push(t)},enqueueReplaceState:function(e,t){(e=e._reactInternals).replace=!0,e.queue=[t]},enqueueForceUpdate:function(){}};function le(e,t,r,n){var i=void 0!==e.state?e.state:null;e.updater=oe,e.props=r,e.state=i;var s={queue:[],replace:!1};e._reactInternals=s;var a=t.contextType;if(e.context="object"==typeof a&&null!==a?a._currentValue2:n,"function"==typeof(a=t.getDerivedStateFromProps)&&(i=null==(a=a(r,i))?i:_({},i,a),e.state=i),"function"!=typeof t.getDerivedStateFromProps&&"function"!=typeof e.getSnapshotBeforeUpdate&&("function"==typeof e.UNSAFE_componentWillMount||"function"==typeof e.componentWillMount))if(t=e.state,"function"==typeof e.componentWillMount&&e.componentWillMount(),"function"==typeof e.UNSAFE_componentWillMount&&e.UNSAFE_componentWillMount(),t!==e.state&&oe.enqueueReplaceState(e,e.state,null),null!==s.queue&&0<s.queue.length)if(t=s.queue,a=s.replace,s.queue=null,s.replace=!1,a&&1===t.length)e.state=t[0];else{for(s=a?t[0]:e.state,i=!0,a=a?1:0;a<t.length;a++){var o=t[a];null!=(o="function"==typeof o?o.call(e,s,r,n):o)&&(i?(i=!1,s=_({},s,o)):_(s,o))}e.state=s}else s.queue=null}var ue={id:1,overflow:""};function ce(e,t,r){var n=e.id;e=e.overflow;var i=32-de(n)-1;n&=~(1<<i),r+=1;var s=32-de(t)+i;if(30<s){var a=i-i%5;return s=(n&(1<<a)-1).toString(32),n>>=a,i-=a,{id:1<<32-de(t)+i|r<<i|n,overflow:s+e}}return{id:1<<s|r<<i|n,overflow:e}}var de=Math.clz32?Math.clz32:function(e){return e>>>=0,0===e?32:31-(he(e)/fe|0)|0},he=Math.log,fe=Math.LN2;var pe="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},ge=null,me=null,ve=null,ye=null,be=!1,we=!1,Ee=0,Se=null,Te=0;function xe(){if(null===ge)throw Error(t(321));return ge}function ke(){if(0<Te)throw Error(t(312));return{memoizedState:null,queue:null,next:null}}function Ae(){return null===ye?null===ve?(be=!1,ve=ye=ke()):(be=!0,ye=ve):null===ye.next?(be=!1,ye=ye.next=ke()):(be=!0,ye=ye.next),ye}function Re(){me=ge=null,we=!1,ve=null,Te=0,ye=Se=null}function Le(e,t){return"function"==typeof t?t(e):t}function Ie(e,t,r){if(ge=xe(),ye=Ae(),be){var n=ye.queue;if(t=n.dispatch,null!==Se&&void 0!==(r=Se.get(n))){Se.delete(n),n=ye.memoizedState;do{n=e(n,r.action),r=r.next}while(null!==r);return ye.memoizedState=n,[n,t]}return[ye.memoizedState,t]}return e=e===Le?"function"==typeof t?t():t:void 0!==r?r(t):t,ye.memoizedState=e,e=(e=ye.queue={last:null,dispatch:null}).dispatch=Pe.bind(null,ge,e),[ye.memoizedState,e]}function Ce(e,t){if(ge=xe(),t=void 0===t?null:t,null!==(ye=Ae())){var r=ye.memoizedState;if(null!==r&&null!==t){var n=r[1];e:if(null===n)n=!1;else{for(var i=0;i<n.length&&i<t.length;i++)if(!pe(t[i],n[i])){n=!1;break e}n=!0}if(n)return r[0]}}return e=e(),ye.memoizedState=[e,t],e}function Pe(e,r,n){if(25<=Te)throw Error(t(301));if(e===ge)if(we=!0,e={action:n,next:null},null===Se&&(Se=new Map),void 0===(n=Se.get(r)))Se.set(r,e);else{for(r=n;null!==r.next;)r=r.next;r.next=e}}function De(){throw Error(t(394))}function _e(){}var Me={readContext:function(e){return e._currentValue2},useContext:function(e){return xe(),e._currentValue2},useMemo:Ce,useReducer:Ie,useRef:function(e){ge=xe();var t=(ye=Ae()).memoizedState;return null===t?(e={current:e},ye.memoizedState=e):t},useState:function(e){return Ie(Le,e)},useInsertionEffect:_e,useLayoutEffect:function(){},useCallback:function(e,t){return Ce(function(){return e},t)},useImperativeHandle:_e,useEffect:_e,useDebugValue:_e,useDeferredValue:function(e){return xe(),e},useTransition:function(){return xe(),[!1,De]},useId:function(){var e=me.treeContext,r=e.overflow;e=((e=e.id)&~(1<<32-de(e)-1)).toString(32)+r;var n=Oe;if(null===n)throw Error(t(404));return r=Ee++,e=":"+n.idPrefix+"R"+e,0<r&&(e+="H"+r.toString(32)),e+":"},useMutableSource:function(e,t){return xe(),t(e._source)},useSyncExternalStore:function(e,r,n){if(void 0===n)throw Error(t(407));return n()}},Oe=null,Ne=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher;function Fe(e){return console.error(e),null}function $e(){}function Be(e,t,r,n,i,s,a,o){e.allPendingTasks++,null===r?e.pendingRootTasks++:r.pendingTasks++;var l={node:t,ping:function(){var t=e.pingedTasks;t.push(l),1===t.length&&et(e)},blockedBoundary:r,blockedSegment:n,abortSet:i,legacyContext:s,context:a,treeContext:o};return i.add(l),l}function Ue(e,t,r,n,i,s){return{status:0,id:-1,index:t,parentFlushed:!1,chunks:[],children:[],formatContext:n,boundary:r,lastPushedText:i,textEmbedded:s}}function ze(e,t){if(null!=(e=e.onError(t))&&"string"!=typeof e)throw Error('onError returned something with a type other than "string". onError should return a string and may return null or undefined but must not return anything else. It received something of type "'+typeof e+'" instead');return e}function je(e,t){var r=e.onShellError;r(t),(r=e.onFatalError)(t),null!==e.destination?(e.status=2,e.destination.destroy(t)):(e.status=1,e.fatalError=t)}function Ge(e,t,r,n,i){for(ge={},me=t,Ee=0,e=r(n,i);we;)we=!1,Ee=0,Te+=1,ye=null,e=r(n,i);return Re(),e}function He(e,r,n,i){var s=n.render(),a=i.childContextTypes;if(null!=a){var o=r.legacyContext;if("function"!=typeof n.getChildContext)i=o;else{for(var l in n=n.getChildContext())if(!(l in a))throw Error(t(108,Q(i)||"Unknown",l));i=_({},o,n)}r.legacyContext=i,Ke(e,r,s),r.legacyContext=o}else Ke(e,r,s)}function Ve(e,t){if(e&&e.defaultProps){for(var r in t=_({},t),e=e.defaultProps)void 0===t[r]&&(t[r]=e[r]);return t}return t}function We(e,r,n,i,s){if("function"==typeof n)if(n.prototype&&n.prototype.isReactComponent){s=J(n,r.legacyContext);var a=n.contextType;le(a=new n(i,"object"==typeof a&&null!==a?a._currentValue2:s),n,i,s),He(e,r,a,n)}else{s=Ge(e,r,n,i,a=J(n,r.legacyContext));var o=0!==Ee;if("object"==typeof s&&null!==s&&"function"==typeof s.render&&void 0===s.$$typeof)le(s,n,i,a),He(e,r,s,n);else if(o){i=r.treeContext,r.treeContext=ce(i,1,0);try{Ke(e,r,s)}finally{r.treeContext=i}}else Ke(e,r,s)}else{if("string"!=typeof n){switch(n){case Y:case K:case F:case $:case N:case G:return void Ke(e,r,i.children);case W:throw Error(t(343));case j:e:{n=r.blockedBoundary,s=r.blockedSegment,a=i.fallback,i=i.children;var l={id:null,rootSegmentID:-1,parentFlushed:!1,pendingTasks:0,forceClientRender:!1,completedSegments:[],byteSize:0,fallbackAbortableTasks:o=new Set,errorDigest:null},u=Ue(0,s.chunks.length,l,s.formatContext,!1,!1);s.children.push(u),s.lastPushedText=!1;var c=Ue(0,0,null,s.formatContext,!1,!1);c.parentFlushed=!0,r.blockedBoundary=l,r.blockedSegment=c;try{if(qe(e,r,i),e.responseState.generateStaticMarkup||c.lastPushedText&&c.textEmbedded&&c.chunks.push("\x3c!-- --\x3e"),c.status=1,Ze(l,c),0===l.pendingTasks)break e}catch(t){c.status=4,l.forceClientRender=!0,l.errorDigest=ze(e,t)}finally{r.blockedBoundary=n,r.blockedSegment=s}r=Be(e,a,n,u,o,r.legacyContext,r.context,r.treeContext),e.pingedTasks.push(r)}return}if("object"==typeof n&&null!==n)switch(n.$$typeof){case z:if(i=Ge(e,r,n.render,i,s),0!==Ee){n=r.treeContext,r.treeContext=ce(n,1,0);try{Ke(e,r,i)}finally{r.treeContext=n}}else Ke(e,r,i);return;case H:return void We(e,r,n=n.type,i=Ve(n,i),s);case B:if(s=i.children,n=n._context,i=i.value,a=n._currentValue2,n._currentValue2=i,ee=i={parent:o=ee,depth:null===o?0:o.depth+1,context:n,parentValue:a,value:i},r.context=i,Ke(e,r,s),null===(e=ee))throw Error(t(403));return i=e.parentValue,e.context._currentValue2=i===q?e.context._defaultValue:i,e=ee=e.parent,void(r.context=e);case U:return void Ke(e,r,i=(i=i.children)(n._currentValue2));case V:return void We(e,r,n=(s=n._init)(n._payload),i=Ve(n,i),void 0)}throw Error(t(130,null==n?n:typeof n,""))}switch(a=L((s=r.blockedSegment).chunks,n,i,e.responseState,s.formatContext),s.lastPushedText=!1,o=s.formatContext,s.formatContext=function(e,t,r){switch(t){case"select":return b(1,null!=r.value?r.value:r.defaultValue);case"svg":return b(2,null);case"math":return b(3,null);case"foreignObject":return b(1,null);case"table":return b(4,null);case"thead":case"tbody":case"tfoot":return b(5,null);case"colgroup":return b(7,null);case"tr":return b(6,null)}return 4<=e.insertionMode||0===e.insertionMode?b(1,null):e}(o,n,i),qe(e,r,a),s.formatContext=o,n){case"area":case"base":case"br":case"col":case"embed":case"hr":case"img":case"input":case"keygen":case"link":case"meta":case"param":case"source":case"track":case"wbr":break;default:s.chunks.push("</",n,">")}s.lastPushedText=!1}}function Ke(e,r,n){if(r.node=n,"object"==typeof n&&null!==n){switch(n.$$typeof){case M:return void We(e,r,n.type,n.props,n.ref);case O:throw Error(t(257));case V:var i=n._init;return void Ke(e,r,n=i(n._payload))}if(y(n))return void Ye(e,r,n);if(null===n||"object"!=typeof n?i=null:i="function"==typeof(i=X&&n[X]||n["@@iterator"])?i:null,i&&(i=i.call(n))){if(!(n=i.next()).done){var s=[];do{s.push(n.value),n=i.next()}while(!n.done);Ye(e,r,s)}return}throw e=Object.prototype.toString.call(n),Error(t(31,"[object Object]"===e?"object with keys {"+Object.keys(n).join(", ")+"}":e))}"string"==typeof n?(i=r.blockedSegment).lastPushedText=D(r.blockedSegment.chunks,n,e.responseState,i.lastPushedText):"number"==typeof n&&((i=r.blockedSegment).lastPushedText=D(r.blockedSegment.chunks,""+n,e.responseState,i.lastPushedText))}function Ye(e,t,r){for(var n=r.length,i=0;i<n;i++){var s=t.treeContext;t.treeContext=ce(s,n,i);try{qe(e,t,r[i])}finally{t.treeContext=s}}}function qe(e,t,r){var n=t.blockedSegment.formatContext,i=t.legacyContext,s=t.context;try{return Ke(e,t,r)}catch(l){if(Re(),"object"!=typeof l||null===l||"function"!=typeof l.then)throw t.blockedSegment.formatContext=n,t.legacyContext=i,t.context=s,ae(s),l;r=l;var a=t.blockedSegment,o=Ue(0,a.chunks.length,null,a.formatContext,a.lastPushedText,!0);a.children.push(o),a.lastPushedText=!1,e=Be(e,t.node,t.blockedBoundary,o,t.abortSet,t.legacyContext,t.context,t.treeContext).ping,r.then(e,e),t.blockedSegment.formatContext=n,t.legacyContext=i,t.context=s,ae(s)}}function Xe(e){var t=e.blockedBoundary;(e=e.blockedSegment).status=3,Je(this,t,e)}function Qe(e,r,n){var i=e.blockedBoundary;e.blockedSegment.status=3,null===i?(r.allPendingTasks--,2!==r.status&&(r.status=2,null!==r.destination&&r.destination.push(null))):(i.pendingTasks--,i.forceClientRender||(i.forceClientRender=!0,e=void 0===n?Error(t(432)):n,i.errorDigest=r.onError(e),i.parentFlushed&&r.clientRenderedBoundaries.push(i)),i.fallbackAbortableTasks.forEach(function(e){return Qe(e,r,n)}),i.fallbackAbortableTasks.clear(),r.allPendingTasks--,0===r.allPendingTasks&&(i=r.onAllReady)())}function Ze(e,t){if(0===t.chunks.length&&1===t.children.length&&null===t.children[0].boundary){var r=t.children[0];r.id=t.id,r.parentFlushed=!0,1===r.status&&Ze(e,r)}else e.completedSegments.push(t)}function Je(e,r,n){if(null===r){if(n.parentFlushed){if(null!==e.completedRootSegment)throw Error(t(389));e.completedRootSegment=n}e.pendingRootTasks--,0===e.pendingRootTasks&&(e.onShellError=$e,(r=e.onShellReady)())}else r.pendingTasks--,r.forceClientRender||(0===r.pendingTasks?(n.parentFlushed&&1===n.status&&Ze(r,n),r.parentFlushed&&e.completedBoundaries.push(r),r.fallbackAbortableTasks.forEach(Xe,e),r.fallbackAbortableTasks.clear()):n.parentFlushed&&1===n.status&&(Ze(r,n),1===r.completedSegments.length&&r.parentFlushed&&e.partialBoundaries.push(r)));e.allPendingTasks--,0===e.allPendingTasks&&(e=e.onAllReady)()}function et(e){if(2!==e.status){var t=ee,r=Ne.current;Ne.current=Me;var n=Oe;Oe=e.responseState;try{var i,s=e.pingedTasks;for(i=0;i<s.length;i++){var a=s[i],o=e,l=a.blockedSegment;if(0===l.status){ae(a.context);try{Ke(o,a,a.node),o.responseState.generateStaticMarkup||l.lastPushedText&&l.textEmbedded&&l.chunks.push("\x3c!-- --\x3e"),a.abortSet.delete(a),l.status=1,Je(o,a.blockedBoundary,l)}catch(e){if(Re(),"object"==typeof e&&null!==e&&"function"==typeof e.then){var u=a.ping;e.then(u,u)}else{a.abortSet.delete(a),l.status=4;var c=a.blockedBoundary,d=e,h=ze(o,d);if(null===c?je(o,d):(c.pendingTasks--,c.forceClientRender||(c.forceClientRender=!0,c.errorDigest=h,c.parentFlushed&&o.clientRenderedBoundaries.push(c))),o.allPendingTasks--,0===o.allPendingTasks)(0,o.onAllReady)()}}}}s.splice(0,i),null!==e.destination&&at(e,e.destination)}catch(t){ze(e,t),je(e,t)}finally{Oe=n,Ne.current=r,r===Me&&ae(t)}}}function tt(e,r,n){switch(n.parentFlushed=!0,n.status){case 0:var i=n.id=e.nextSegmentId++;return n.lastPushedText=!1,n.textEmbedded=!1,e=e.responseState,r.push('<template id="'),r.push(e.placeholderPrefix),e=i.toString(16),r.push(e),r.push('"></template>');case 1:n.status=2;var s=!0;i=n.chunks;var a=0;n=n.children;for(var o=0;o<n.length;o++){for(s=n[o];a<s.index;a++)r.push(i[a]);s=rt(e,r,s)}for(;a<i.length-1;a++)r.push(i[a]);return a<i.length&&(s=r.push(i[a])),s;default:throw Error(t(390))}}function rt(e,r,n){var i=n.boundary;if(null===i)return tt(e,r,n);if(i.parentFlushed=!0,i.forceClientRender)return e.responseState.generateStaticMarkup||(i=i.errorDigest,r.push("\x3c!--$!--\x3e"),r.push("<template"),i&&(r.push(' data-dgst="'),i=g(i),r.push(i),r.push('"')),r.push("></template>")),tt(e,r,n),e=!!e.responseState.generateStaticMarkup||r.push("\x3c!--/$--\x3e");if(0<i.pendingTasks){i.rootSegmentID=e.nextSegmentId++,0<i.completedSegments.length&&e.partialBoundaries.push(i);var s=e.responseState,a=s.nextSuspenseID++;return s=s.boundaryPrefix+a.toString(16),i=i.id=s,I(r,e.responseState,i),tt(e,r,n),r.push("\x3c!--/$--\x3e")}if(i.byteSize>e.progressiveChunkSize)return i.rootSegmentID=e.nextSegmentId++,e.completedBoundaries.push(i),I(r,e.responseState,i.id),tt(e,r,n),r.push("\x3c!--/$--\x3e");if(e.responseState.generateStaticMarkup||r.push("\x3c!--$--\x3e"),1!==(n=i.completedSegments).length)throw Error(t(391));return rt(e,r,n[0]),e=!!e.responseState.generateStaticMarkup||r.push("\x3c!--/$--\x3e")}function nt(e,r,n){return function(e,r,n,i){switch(n.insertionMode){case 0:case 1:return e.push('<div hidden id="'),e.push(r.segmentPrefix),r=i.toString(16),e.push(r),e.push('">');case 2:return e.push('<svg aria-hidden="true" style="display:none" id="'),e.push(r.segmentPrefix),r=i.toString(16),e.push(r),e.push('">');case 3:return e.push('<math aria-hidden="true" style="display:none" id="'),e.push(r.segmentPrefix),r=i.toString(16),e.push(r),e.push('">');case 4:return e.push('<table hidden id="'),e.push(r.segmentPrefix),r=i.toString(16),e.push(r),e.push('">');case 5:return e.push('<table hidden><tbody id="'),e.push(r.segmentPrefix),r=i.toString(16),e.push(r),e.push('">');case 6:return e.push('<table hidden><tr id="'),e.push(r.segmentPrefix),r=i.toString(16),e.push(r),e.push('">');case 7:return e.push('<table hidden><colgroup id="'),e.push(r.segmentPrefix),r=i.toString(16),e.push(r),e.push('">');default:throw Error(t(397))}}(r,e.responseState,n.formatContext,n.id),rt(e,r,n),function(e,r){switch(r.insertionMode){case 0:case 1:return e.push("</div>");case 2:return e.push("</svg>");case 3:return e.push("</math>");case 4:return e.push("</table>");case 5:return e.push("</tbody></table>");case 6:return e.push("</tr></table>");case 7:return e.push("</colgroup></table>");default:throw Error(t(397))}}(r,n.formatContext)}function it(e,r,n){for(var i=n.completedSegments,s=0;s<i.length;s++)st(e,r,n,i[s]);if(i.length=0,e=e.responseState,i=n.id,n=n.rootSegmentID,r.push(e.startInlineScript),e.sentCompleteBoundaryFunction?r.push('$RC("'):(e.sentCompleteBoundaryFunction=!0,r.push('function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}};$RC("')),null===i)throw Error(t(395));return n=n.toString(16),r.push(i),r.push('","'),r.push(e.segmentPrefix),r.push(n),r.push('")<\/script>')}function st(e,r,n,i){if(2===i.status)return!0;var s=i.id;if(-1===s){if(-1===(i.id=n.rootSegmentID))throw Error(t(392));return nt(e,r,i)}return nt(e,r,i),e=e.responseState,r.push(e.startInlineScript),e.sentCompleteSegmentFunction?r.push('$RS("'):(e.sentCompleteSegmentFunction=!0,r.push('function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};$RS("')),r.push(e.segmentPrefix),s=s.toString(16),r.push(s),r.push('","'),r.push(e.placeholderPrefix),r.push(s),r.push('")<\/script>')}function at(e,r){try{var n=e.completedRootSegment;if(null!==n&&0===e.pendingRootTasks){rt(e,r,n),e.completedRootSegment=null;var i=e.responseState.bootstrapChunks;for(n=0;n<i.length-1;n++)r.push(i[n]);n<i.length&&r.push(i[n])}var s,a=e.clientRenderedBoundaries;for(s=0;s<a.length;s++){var o=a[s];i=r;var l=e.responseState,u=o.id,c=o.errorDigest,d=o.errorMessage,h=o.errorComponentStack;if(i.push(l.startInlineScript),l.sentClientRenderFunction?i.push('$RX("'):(l.sentClientRenderFunction=!0,i.push('function $RX(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())};$RX("')),null===u)throw Error(t(395));if(i.push(u),i.push('"'),c||d||h){i.push(",");var f=P(c||"");i.push(f)}if(d||h){i.push(",");var p=P(d||"");i.push(p)}if(h){i.push(",");var g=P(h);i.push(g)}if(!i.push(")<\/script>"))return e.destination=null,s++,void a.splice(0,s)}a.splice(0,s);var m=e.completedBoundaries;for(s=0;s<m.length;s++)if(!it(e,r,m[s]))return e.destination=null,s++,void m.splice(0,s);m.splice(0,s);var v=e.partialBoundaries;for(s=0;s<v.length;s++){var y=v[s];e:{a=e,o=r;var b=y.completedSegments;for(l=0;l<b.length;l++)if(!st(a,o,y,b[l])){l++,b.splice(0,l);var w=!1;break e}b.splice(0,l),w=!0}if(!w)return e.destination=null,s++,void v.splice(0,s)}v.splice(0,s);var E=e.completedBoundaries;for(s=0;s<E.length;s++)if(!it(e,r,E[s]))return e.destination=null,s++,void E.splice(0,s);E.splice(0,s)}finally{0===e.allPendingTasks&&0===e.pingedTasks.length&&0===e.clientRenderedBoundaries.length&&0===e.completedBoundaries.length&&r.push(null)}}function ot(e,t){try{var r=e.abortableTasks;r.forEach(function(r){return Qe(r,e,t)}),r.clear(),null!==e.destination&&at(e,e.destination)}catch(t){ze(e,t),je(e,t)}}function lt(){}function ut(e,r,n,i){var s=!1,a=null,o="",l={push:function(e){return null!==e&&(o+=e),!0},destroy:function(e){s=!0,a=e}},u=!1;if(e=function(e,t,r,n,i,s,a){var o=[],l=new Set;return(r=Ue(t={destination:null,responseState:t,progressiveChunkSize:void 0===n?12800:n,status:0,fatalError:null,nextSegmentId:0,allPendingTasks:0,pendingRootTasks:0,completedRootSegment:null,abortableTasks:l,pingedTasks:o,clientRenderedBoundaries:[],completedBoundaries:[],partialBoundaries:[],onError:void 0===i?Fe:i,onAllReady:$e,onShellReady:void 0===a?$e:a,onShellError:$e,onFatalError:$e},0,null,r,!1,!1)).parentFlushed=!0,e=Be(t,e,null,r,l,Z,null,ue),o.push(e),t}(e,function(e,t){return{bootstrapChunks:[],startInlineScript:"<script>",placeholderPrefix:(t=void 0===t?"":t)+"P:",segmentPrefix:t+"S:",boundaryPrefix:t+"B:",idPrefix:t,nextSuspenseID:0,sentCompleteSegmentFunction:!1,sentCompleteBoundaryFunction:!1,sentClientRenderFunction:!1,generateStaticMarkup:e}}(n,r?r.identifierPrefix:void 0),{insertionMode:1,selectedValue:null},1/0,lt,0,function(){u=!0}),et(e),ot(e,i),1===e.status)e.status=2,l.destroy(e.fatalError);else if(2!==e.status&&null===e.destination){e.destination=l;try{at(e,l)}catch(t){ze(e,t),je(e,t)}}if(s)throw a;if(!u)throw Error(t(426));return o}return _u.renderToNodeStream=function(){throw Error(t(207))},_u.renderToStaticMarkup=function(e,t){return ut(e,t,!0,'The server used "renderToStaticMarkup" which does not support Suspense. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server')},_u.renderToStaticNodeStream=function(){throw Error(t(208))},_u.renderToString=function(e,t){return ut(e,t,!1,'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server')},_u.version="18.3.1",_u}var Ou,Nu,Fu={};
|
|
35
|
+
*/function ci({message:e,duration:t=3e3,visible:r,setVisible:n}){return p.useEffect(()=>{const e=setTimeout(()=>n(!1),t);return()=>clearTimeout(e)},[r]),r?g.createElement("div",{style:{position:"fixed",top:"1rem",left:"50%",transform:"translateX(-50%)",background:"rgba(0,0,0,0.8)",color:"#fff",padding:"0.75rem 1.25rem",borderRadius:"0.375rem",fontSize:"14px",zIndex:9999,boxShadow:"0 2px 10px rgba(0,0,0,0.2)"}},e):null}const di=({shortForm:e,shareUrl:t})=>{const r=null!=t?t:window.location.href,[n,i]=p.useState(!1);return g.createElement(g.Fragment,null,g.createElement("button",{onClick:()=>J(void 0,void 0,void 0,function*(){try{i(!0),Hn.isMobile&&navigator.share&&e?yield navigator.share({title:e.title,url:r}):(e=>{if(void 0!==navigator.clipboard)navigator.clipboard.writeText(e).then(()=>{});else{const t=document.createElement("textarea");t.value=e,document.body.appendChild(t),t.select(),t.setSelectionRange(0,99999);try{document.execCommand("copy")}catch(e){console.error("복사 실패",e)}t.setSelectionRange(0,0),document.body.removeChild(t)}})(r)}catch(e){console.error("Fail to copy on clipboard")}}),className:"cursor-pointer"},g.createElement(ni,{size:22}),g.createElement(ci,{message:"공유 링크 복사 완료",setVisible:i,visible:n})))},hi=({width:e,height:t})=>g.createElement("div",{className:"w-full h-full flex items-center justify-center"},g.createElement("img",{src:"public/images/noImage.svg",alt:"no image",width:e||50,height:t||50})),fi=({product:e,onError:t})=>g.createElement("img",{src:e.thumbPath,alt:e.productName,className:"object-cover p-0 flex-none",style:{height:"80px",width:"80px"},onError:t}),pi=({product:e,hideMoreBtn:t,contentId:r})=>{const{isPreview:n,priceText:i}=cr(),[s,a]=p.useState(!1);return g.createElement("div",{style:{height:"80px"},className:"flex gap-2 items-center w-full",onClick:()=>J(void 0,void 0,void 0,function*(){t&&(window.open(e.linkPath,"_blank"),n||(yield Zt({contentProductId:e.eventProductId,contentId:r,productId:e.productId})))})},e.thumbPath&&!s?g.createElement(fi,{product:e,onError:()=>a(!0)}):g.createElement(hi,null),g.createElement("div",{className:"flex flex-col text-left p-2 w-full justify-center"},e.brand&&g.createElement("span",{className:"break-keep line-clamp-1 text-gray-500",style:{fontSize:"10px"}},e.brand.brandName),g.createElement("div",{className:"text-gray-800 text-ellipsis line-clamp-1 ",style:{fontSize:"12px"}},e.productName),g.createElement("div",{className:"text-red-500 break-keep",style:{fontSize:"12px"}},i?i+" ":"할인가 ",g.createElement("span",{className:"font-semibold break-keep"},$t(e.sellingPrice),"원"))))};function gi(e,t,{checkForDefaultPrevented:r=!0}={}){return function(n){if(e?.(n),!1===r||!n.defaultPrevented)return t?.(n)}}function mi(e,t){if("function"==typeof e)return e(t);null!=e&&(e.current=t)}function vi(...e){return t=>{let r=!1;const n=e.map(e=>{const n=mi(e,t);return r||"function"!=typeof n||(r=!0),n});if(r)return()=>{for(let t=0;t<n.length;t++){const r=n[t];"function"==typeof r?r():mi(e[t],null)}}}}function yi(...e){return p.useCallback(vi(...e),e)}var bi,wi,Ei={exports:{}},Si={};var Ti=(wi||(wi=1,Ei.exports=function(){if(bi)return Si;bi=1;var e=l(),t=Symbol.for("react.element"),r=Symbol.for("react.fragment"),n=Object.prototype.hasOwnProperty,i=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,s={key:!0,ref:!0,__self:!0,__source:!0};function a(e,r,a){var o,l={},u=null,c=null;for(o in void 0!==a&&(u=""+a),void 0!==r.key&&(u=""+r.key),void 0!==r.ref&&(c=r.ref),r)n.call(r,o)&&!s.hasOwnProperty(o)&&(l[o]=r[o]);if(e&&e.defaultProps)for(o in r=e.defaultProps)void 0===l[o]&&(l[o]=r[o]);return{$$typeof:t,type:e,key:u,ref:c,props:l,_owner:i.current}}return Si.Fragment=r,Si.jsx=a,Si.jsxs=a,Si}()),Ei.exports);function xi(...e){const t=e[0];if(1===e.length)return t;const r=()=>{const r=e.map(e=>({useScope:e(),scopeName:e.scopeName}));return function(e){const n=r.reduce((t,{useScope:r,scopeName:n})=>({...t,...r(e)[`__scope${n}`]}),{});return p.useMemo(()=>({[`__scope${t.scopeName}`]:n}),[n])}};return r.scopeName=t.scopeName,r}var ki=globalThis?.document?p.useLayoutEffect:()=>{},Ai=m[" useId ".trim().toString()]||(()=>{}),Ri=0;function Li(e){const[t,r]=p.useState(Ai());return ki(()=>{e||r(e=>e??String(Ri++))},[e]),e||(t?`radix-${t}`:"")}var Ii=m[" useInsertionEffect ".trim().toString()]||ki;function Ci({prop:e,defaultProp:t,onChange:r=()=>{},caller:n}){const[i,s,a]=function({defaultProp:e,onChange:t}){const[r,n]=p.useState(e),i=p.useRef(r),s=p.useRef(t);return Ii(()=>{s.current=t},[t]),p.useEffect(()=>{i.current!==r&&(s.current?.(r),i.current=r)},[r,i]),[r,n,s]}({defaultProp:t,onChange:r}),o=void 0!==e,l=o?e:i;{const t=p.useRef(void 0!==e);p.useEffect(()=>{const e=t.current;if(e!==o){const t=e?"controlled":"uncontrolled",r=o?"controlled":"uncontrolled";console.warn(`${n} is changing from ${t} to ${r}. 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.`)}t.current=o},[o,n])}const u=p.useCallback(t=>{if(o){const r=function(e){return"function"==typeof e}(t)?t(e):t;r!==e&&a.current?.(r)}else s(t)},[o,e,s,a]);return[l,u]}var Pi=x(),Di=t(Pi);function _i(e){const t=Mi(e),r=p.forwardRef((e,r)=>{const{children:n,...i}=e,s=p.Children.toArray(n),a=s.find(Ni);if(a){const e=a.props.children,n=s.map(t=>t===a?p.Children.count(e)>1?p.Children.only(null):p.isValidElement(e)?e.props.children:null:t);return Ti.jsx(t,{...i,ref:r,children:p.isValidElement(e)?p.cloneElement(e,void 0,n):null})}return Ti.jsx(t,{...i,ref:r,children:n})});return r.displayName=`${e}.Slot`,r}function Mi(e){const t=p.forwardRef((e,t)=>{const{children:r,...n}=e;if(p.isValidElement(r)){const e=function(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;if(r)return e.ref;if(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r)return e.props.ref;return e.props.ref||e.ref}(r),i=function(e,t){const r={...t};for(const n in t){const i=e[n],s=t[n];/^on[A-Z]/.test(n)?i&&s?r[n]=(...e)=>{const t=s(...e);return i(...e),t}:i&&(r[n]=i):"style"===n?r[n]={...i,...s}:"className"===n&&(r[n]=[i,s].filter(Boolean).join(" "))}return{...e,...r}}(n,r.props);return r.type!==p.Fragment&&(i.ref=t?vi(t,e):e),p.cloneElement(r,i)}return p.Children.count(r)>1?p.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Oi=Symbol("radix.slottable");function Ni(e){return p.isValidElement(e)&&"function"==typeof e.type&&"__radixId"in e.type&&e.type.__radixId===Oi}var Fi=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,t)=>{const r=_i(`Primitive.${t}`),n=p.forwardRef((e,n)=>{const{asChild:i,...s}=e,a=i?r:t;return"undefined"!=typeof window&&(window[Symbol.for("radix-ui")]=!0),Ti.jsx(a,{...s,ref:n})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function $i(e){const t=p.useRef(e);return p.useEffect(()=>{t.current=e}),p.useMemo(()=>(...e)=>t.current?.(...e),[])}function Bi(e,t=globalThis?.document){const r=$i(e);p.useEffect(()=>{const e=e=>{"Escape"===e.key&&r(e)};return t.addEventListener("keydown",e,{capture:!0}),()=>t.removeEventListener("keydown",e,{capture:!0})},[r,t])}var Ui,zi="dismissableLayer.update",ji="dismissableLayer.pointerDownOutside",Gi="dismissableLayer.focusOutside",Hi=p.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Vi=p.forwardRef((e,t)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:n,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:a,onDismiss:o,...l}=e,u=p.useContext(Hi),[c,d]=p.useState(null),h=c?.ownerDocument??globalThis?.document,[,f]=p.useState({}),g=yi(t,e=>d(e)),m=Array.from(u.layers),[v]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),y=m.indexOf(v),b=c?m.indexOf(c):-1,w=u.layersWithOutsidePointerEventsDisabled.size>0,E=b>=y,S=function(e,t=globalThis?.document){const r=$i(e),n=p.useRef(!1),i=p.useRef(()=>{});return p.useEffect(()=>{const e=e=>{if(e.target&&!n.current){let n=function(){Ki(ji,r,s,{discrete:!0})};const s={originalEvent:e};"touch"===e.pointerType?(t.removeEventListener("click",i.current),i.current=n,t.addEventListener("click",i.current,{once:!0})):n()}else t.removeEventListener("click",i.current);n.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",e)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",e),t.removeEventListener("click",i.current)}},[t,r]),{onPointerDownCapture:()=>n.current=!0}}(e=>{const t=e.target,r=[...u.branches].some(e=>e.contains(t));E&&!r&&(i?.(e),a?.(e),e.defaultPrevented||o?.())},h),T=function(e,t=globalThis?.document){const r=$i(e),n=p.useRef(!1);return p.useEffect(()=>{const e=e=>{if(e.target&&!n.current){Ki(Gi,r,{originalEvent:e},{discrete:!1})}};return t.addEventListener("focusin",e),()=>t.removeEventListener("focusin",e)},[t,r]),{onFocusCapture:()=>n.current=!0,onBlurCapture:()=>n.current=!1}}(e=>{const t=e.target;[...u.branches].some(e=>e.contains(t))||(s?.(e),a?.(e),e.defaultPrevented||o?.())},h);return Bi(e=>{b===u.layers.size-1&&(n?.(e),!e.defaultPrevented&&o&&(e.preventDefault(),o()))},h),p.useEffect(()=>{if(c)return r&&(0===u.layersWithOutsidePointerEventsDisabled.size&&(Ui=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(c)),u.layers.add(c),Wi(),()=>{r&&1===u.layersWithOutsidePointerEventsDisabled.size&&(h.body.style.pointerEvents=Ui)}},[c,h,r,u]),p.useEffect(()=>()=>{c&&(u.layers.delete(c),u.layersWithOutsidePointerEventsDisabled.delete(c),Wi())},[c,u]),p.useEffect(()=>{const e=()=>f({});return document.addEventListener(zi,e),()=>document.removeEventListener(zi,e)},[]),Ti.jsx(Fi.div,{...l,ref:g,style:{pointerEvents:w?E?"auto":"none":void 0,...e.style},onFocusCapture:gi(e.onFocusCapture,T.onFocusCapture),onBlurCapture:gi(e.onBlurCapture,T.onBlurCapture),onPointerDownCapture:gi(e.onPointerDownCapture,S.onPointerDownCapture)})});Vi.displayName="DismissableLayer";function Wi(){const e=new CustomEvent(zi);document.dispatchEvent(e)}function Ki(e,t,r,{discrete:n}){const i=r.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:r});t&&i.addEventListener(e,t,{once:!0}),n?function(e,t){e&&Pi.flushSync(()=>e.dispatchEvent(t))}(i,s):i.dispatchEvent(s)}p.forwardRef((e,t)=>{const r=p.useContext(Hi),n=p.useRef(null),i=yi(t,n);return p.useEffect(()=>{const e=n.current;if(e)return r.branches.add(e),()=>{r.branches.delete(e)}},[r.branches]),Ti.jsx(Fi.div,{...e,ref:i})}).displayName="DismissableLayerBranch";var Yi="focusScope.autoFocusOnMount",qi="focusScope.autoFocusOnUnmount",Xi={bubbles:!1,cancelable:!0},Qi=p.forwardRef((e,t)=>{const{loop:r=!1,trapped:n=!1,onMountAutoFocus:i,onUnmountAutoFocus:s,...a}=e,[o,l]=p.useState(null),u=$i(i),c=$i(s),d=p.useRef(null),h=yi(t,e=>l(e)),f=p.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;p.useEffect(()=>{if(n){let e=function(e){if(f.paused||!o)return;const t=e.target;o.contains(t)?d.current=t:ts(d.current,{select:!0})},t=function(e){if(f.paused||!o)return;const t=e.relatedTarget;null!==t&&(o.contains(t)||ts(d.current,{select:!0}))},r=function(e){if(document.activeElement===document.body)for(const t of e)t.removedNodes.length>0&&ts(o)};document.addEventListener("focusin",e),document.addEventListener("focusout",t);const n=new MutationObserver(r);return o&&n.observe(o,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",e),document.removeEventListener("focusout",t),n.disconnect()}}},[n,o,f.paused]),p.useEffect(()=>{if(o){rs.add(f);const t=document.activeElement;if(!o.contains(t)){const r=new CustomEvent(Yi,Xi);o.addEventListener(Yi,u),o.dispatchEvent(r),r.defaultPrevented||(!function(e,{select:t=!1}={}){const r=document.activeElement;for(const n of e)if(ts(n,{select:t}),document.activeElement!==r)return}((e=Zi(o),e.filter(e=>"A"!==e.tagName)),{select:!0}),document.activeElement===t&&ts(o))}return()=>{o.removeEventListener(Yi,u),setTimeout(()=>{const e=new CustomEvent(qi,Xi);o.addEventListener(qi,c),o.dispatchEvent(e),e.defaultPrevented||ts(t??document.body,{select:!0}),o.removeEventListener(qi,c),rs.remove(f)},0)}}var e},[o,u,c,f]);const g=p.useCallback(e=>{if(!r&&!n)return;if(f.paused)return;const t="Tab"===e.key&&!e.altKey&&!e.ctrlKey&&!e.metaKey,i=document.activeElement;if(t&&i){const t=e.currentTarget,[n,s]=function(e){const t=Zi(e),r=Ji(t,e),n=Ji(t.reverse(),e);return[r,n]}(t);n&&s?e.shiftKey||i!==s?e.shiftKey&&i===n&&(e.preventDefault(),r&&ts(s,{select:!0})):(e.preventDefault(),r&&ts(n,{select:!0})):i===t&&e.preventDefault()}},[r,n,f.paused]);return Ti.jsx(Fi.div,{tabIndex:-1,...a,ref:h,onKeyDown:g})});function Zi(e){const t=[],r=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:e=>{const t="INPUT"===e.tagName&&"hidden"===e.type;return e.disabled||e.hidden||t?NodeFilter.FILTER_SKIP:e.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)t.push(r.currentNode);return t}function Ji(e,t){for(const r of e)if(!es(r,{upTo:t}))return r}function es(e,{upTo:t}){if("hidden"===getComputedStyle(e).visibility)return!0;for(;e;){if(void 0!==t&&e===t)return!1;if("none"===getComputedStyle(e).display)return!0;e=e.parentElement}return!1}function ts(e,{select:t=!1}={}){if(e&&e.focus){const r=document.activeElement;e.focus({preventScroll:!0}),e!==r&&function(e){return e instanceof HTMLInputElement&&"select"in e}(e)&&t&&e.select()}}Qi.displayName="FocusScope";var rs=function(){let e=[];return{add(t){const r=e[0];t!==r&&r?.pause(),e=ns(e,t),e.unshift(t)},remove(t){e=ns(e,t),e[0]?.resume()}}}();function ns(e,t){const r=[...e],n=r.indexOf(t);return-1!==n&&r.splice(n,1),r}var is=p.forwardRef((e,t)=>{const{container:r,...n}=e,[i,s]=p.useState(!1);ki(()=>s(!0),[]);const a=r||i&&globalThis?.document?.body;return a?Di.createPortal(Ti.jsx(Fi.div,{...n,ref:t}),a):null});is.displayName="Portal";var ss=e=>{const{present:t,children:r}=e,n=function(e){const[t,r]=p.useState(),n=p.useRef(null),i=p.useRef(e),s=p.useRef("none"),a=e?"mounted":"unmounted",[o,l]=function(e,t){return p.useReducer((e,r)=>t[e][r]??e,e)}(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return p.useEffect(()=>{const e=as(n.current);s.current="mounted"===o?e:"none"},[o]),ki(()=>{const t=n.current,r=i.current;if(r!==e){const n=s.current,a=as(t);if(e)l("MOUNT");else if("none"===a||"none"===t?.display)l("UNMOUNT");else{l(r&&n!==a?"ANIMATION_OUT":"UNMOUNT")}i.current=e}},[e,l]),ki(()=>{if(t){let e;const r=t.ownerDocument.defaultView??window,a=s=>{const a=as(n.current).includes(s.animationName);if(s.target===t&&a&&(l("ANIMATION_END"),!i.current)){const n=t.style.animationFillMode;t.style.animationFillMode="forwards",e=r.setTimeout(()=>{"forwards"===t.style.animationFillMode&&(t.style.animationFillMode=n)})}},o=e=>{e.target===t&&(s.current=as(n.current))};return t.addEventListener("animationstart",o),t.addEventListener("animationcancel",a),t.addEventListener("animationend",a),()=>{r.clearTimeout(e),t.removeEventListener("animationstart",o),t.removeEventListener("animationcancel",a),t.removeEventListener("animationend",a)}}l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(o),ref:p.useCallback(e=>{n.current=e?getComputedStyle(e):null,r(e)},[])}}(t),i="function"==typeof r?r({present:n.isPresent}):p.Children.only(r),s=yi(n.ref,function(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;if(r)return e.ref;if(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r)return e.props.ref;return e.props.ref||e.ref}(i));return"function"==typeof r||n.isPresent?p.cloneElement(i,{ref:s}):null};function as(e){return e?.animationName||"none"}ss.displayName="Presence";var os=0;function ls(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var us="right-scroll-bar-position",cs="width-before-scroll-bar";function ds(e,t){return"function"==typeof e?e(t):e&&(e.current=t),e}var hs="undefined"!=typeof window?p.useLayoutEffect:p.useEffect,fs=new WeakMap;function ps(e,t){var r,n,i,s=(r=null,n=function(t){return e.forEach(function(e){return ds(e,t)})},(i=p.useState(function(){return{value:r,callback:n,facade:{get current(){return i.value},set current(e){var t=i.value;t!==e&&(i.value=e,i.callback(e,t))}}}})[0]).callback=n,i.facade);return hs(function(){var t=fs.get(s);if(t){var r=new Set(t),n=new Set(e),i=s.current;r.forEach(function(e){n.has(e)||ds(e,null)}),n.forEach(function(e){r.has(e)||ds(e,i)})}fs.set(s,e)},[e]),s}function gs(e){return e}var ms=function(e){var t=e.sideCar,r=Z(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var n=t.read();if(!n)throw new Error("Sidecar medium not found");return p.createElement(n,Q({},r))};ms.isSideCarExport=!0;var vs=function(e){void 0===e&&(e={});var t=function(e,t){void 0===t&&(t=gs);var r=[],n=!1,i={read:function(){if(n)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return r.length?r[r.length-1]:e},useMedium:function(e){var i=t(e,n);return r.push(i),function(){r=r.filter(function(e){return e!==i})}},assignSyncMedium:function(e){for(n=!0;r.length;){var t=r;r=[],t.forEach(e)}r={push:function(t){return e(t)},filter:function(){return r}}},assignMedium:function(e){n=!0;var t=[];if(r.length){var i=r;r=[],i.forEach(e),t=r}var s=function(){var r=t;t=[],r.forEach(e)},a=function(){return Promise.resolve().then(s)};a(),r={push:function(e){t.push(e),a()},filter:function(e){return t=t.filter(e),r}}}};return i}(null);return t.options=Q({async:!0,ssr:!1},e),t}(),ys=function(){},bs=p.forwardRef(function(e,t){var r=p.useRef(null),n=p.useState({onScrollCapture:ys,onWheelCapture:ys,onTouchMoveCapture:ys}),i=n[0],s=n[1],a=e.forwardProps,o=e.children,l=e.className,u=e.removeScrollBar,c=e.enabled,d=e.shards,h=e.sideCar,f=e.noRelative,g=e.noIsolation,m=e.inert,v=e.allowPinchZoom,y=e.as,b=void 0===y?"div":y,w=e.gapMode,E=Z(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),S=h,T=ps([r,t]),x=Q(Q({},E),i);return p.createElement(p.Fragment,null,c&&p.createElement(S,{sideCar:vs,removeScrollBar:u,shards:d,noRelative:f,noIsolation:g,inert:m,setCallbacks:s,allowPinchZoom:!!v,lockRef:r,gapMode:w}),a?p.cloneElement(p.Children.only(o),Q(Q({},x),{ref:T})):p.createElement(b,Q({},x,{className:l,ref:T}),o))});bs.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},bs.classNames={fullWidth:cs,zeroRight:us};function ws(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=function(){if("undefined"!=typeof __webpack_nonce__)return __webpack_nonce__}();return t&&e.setAttribute("nonce",t),e}var Es=function(){var e=0,t=null;return{add:function(r){var n,i;0==e&&(t=ws())&&(i=r,(n=t).styleSheet?n.styleSheet.cssText=i:n.appendChild(document.createTextNode(i)),function(e){(document.head||document.getElementsByTagName("head")[0]).appendChild(e)}(t)),e++},remove:function(){! --e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Ss=function(){var e,t=(e=Es(),function(t,r){p.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&r])});return function(e){var r=e.styles,n=e.dynamic;return t(r,n),null}},Ts={left:0,top:0,right:0,gap:0},xs=function(e){return parseInt(e||"",10)||0},ks=function(e){if(void 0===e&&(e="margin"),"undefined"==typeof window)return Ts;var t=function(e){var t=window.getComputedStyle(document.body),r=t["padding"===e?"paddingLeft":"marginLeft"],n=t["padding"===e?"paddingTop":"marginTop"],i=t["padding"===e?"paddingRight":"marginRight"];return[xs(r),xs(n),xs(i)]}(e),r=document.documentElement.clientWidth,n=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,n-r+t[2]-t[0])}},As=Ss(),Rs="data-scroll-locked",Ls=function(e,t,r,n){var i=e.left,s=e.top,a=e.right,o=e.gap;return void 0===r&&(r="margin"),"\n .".concat("with-scroll-bars-hidden"," {\n overflow: hidden ").concat(n,";\n padding-right: ").concat(o,"px ").concat(n,";\n }\n body[").concat(Rs,"] {\n overflow: hidden ").concat(n,";\n overscroll-behavior: contain;\n ").concat([t&&"position: relative ".concat(n,";"),"margin"===r&&"\n padding-left: ".concat(i,"px;\n padding-top: ").concat(s,"px;\n padding-right: ").concat(a,"px;\n margin-left:0;\n margin-top:0;\n margin-right: ").concat(o,"px ").concat(n,";\n "),"padding"===r&&"padding-right: ".concat(o,"px ").concat(n,";")].filter(Boolean).join(""),"\n }\n \n .").concat(us," {\n right: ").concat(o,"px ").concat(n,";\n }\n \n .").concat(cs," {\n margin-right: ").concat(o,"px ").concat(n,";\n }\n \n .").concat(us," .").concat(us," {\n right: 0 ").concat(n,";\n }\n \n .").concat(cs," .").concat(cs," {\n margin-right: 0 ").concat(n,";\n }\n \n body[").concat(Rs,"] {\n ").concat("--removed-body-scroll-bar-size",": ").concat(o,"px;\n }\n")},Is=function(){var e=parseInt(document.body.getAttribute(Rs)||"0",10);return isFinite(e)?e:0},Cs=function(e){var t=e.noRelative,r=e.noImportant,n=e.gapMode,i=void 0===n?"margin":n;p.useEffect(function(){return document.body.setAttribute(Rs,(Is()+1).toString()),function(){var e=Is()-1;e<=0?document.body.removeAttribute(Rs):document.body.setAttribute(Rs,e.toString())}},[]);var s=p.useMemo(function(){return ks(i)},[i]);return p.createElement(As,{styles:Ls(s,!t,i,r?"":"!important")})},Ps=!1;if("undefined"!=typeof window)try{var Ds=Object.defineProperty({},"passive",{get:function(){return Ps=!0,!0}});window.addEventListener("test",Ds,Ds),window.removeEventListener("test",Ds,Ds)}catch(e){Ps=!1}var _s=!!Ps&&{passive:!1},Ms=function(e,t){if(!(e instanceof Element))return!1;var r=window.getComputedStyle(e);return"hidden"!==r[t]&&!(r.overflowY===r.overflowX&&!function(e){return"TEXTAREA"===e.tagName}(e)&&"visible"===r[t])},Os=function(e,t){var r=t.ownerDocument,n=t;do{if("undefined"!=typeof ShadowRoot&&n instanceof ShadowRoot&&(n=n.host),Ns(e,n)){var i=Fs(e,n);if(i[1]>i[2])return!0}n=n.parentNode}while(n&&n!==r.body);return!1},Ns=function(e,t){return"v"===e?function(e){return Ms(e,"overflowY")}(t):function(e){return Ms(e,"overflowX")}(t)},Fs=function(e,t){return"v"===e?[(r=t).scrollTop,r.scrollHeight,r.clientHeight]:function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]}(t);var r},$s=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Bs=function(e){return[e.deltaX,e.deltaY]},Us=function(e){return e&&"current"in e?e.current:e},zs=function(e){return"\n .block-interactivity-".concat(e," {pointer-events: none;}\n .allow-interactivity-").concat(e," {pointer-events: all;}\n")},js=0,Gs=[];function Hs(e){for(var t=null;null!==e;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var Vs,Ws=(Vs=function(e){var t=p.useRef([]),r=p.useRef([0,0]),n=p.useRef(),i=p.useState(js++)[0],s=p.useState(Ss)[0],a=p.useRef(e);p.useEffect(function(){a.current=e},[e]),p.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(i));var t=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,s=t.length;i<s;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))}([e.lockRef.current],(e.shards||[]).map(Us),!0).filter(Boolean);return t.forEach(function(e){return e.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),t.forEach(function(e){return e.classList.remove("allow-interactivity-".concat(i))})}}},[e.inert,e.lockRef.current,e.shards]);var o=p.useCallback(function(e,t){if("touches"in e&&2===e.touches.length||"wheel"===e.type&&e.ctrlKey)return!a.current.allowPinchZoom;var i,s=$s(e),o=r.current,l="deltaX"in e?e.deltaX:o[0]-s[0],u="deltaY"in e?e.deltaY:o[1]-s[1],c=e.target,d=Math.abs(l)>Math.abs(u)?"h":"v";if("touches"in e&&"h"===d&&"range"===c.type)return!1;var h=Os(d,c);if(!h)return!0;if(h?i=d:(i="v"===d?"h":"v",h=Os(d,c)),!h)return!1;if(!n.current&&"changedTouches"in e&&(l||u)&&(n.current=i),!i)return!0;var f=n.current||i;return function(e,t,r,n,i){var s=function(e,t){return"h"===e&&"rtl"===t?-1:1}(e,window.getComputedStyle(t).direction),a=s*n,o=r.target,l=t.contains(o),u=!1,c=a>0,d=0,h=0;do{if(!o)break;var f=Fs(e,o),p=f[0],g=f[1]-f[2]-s*p;(p||g)&&Ns(e,o)&&(d+=g,h+=p);var m=o.parentNode;o=m&&m.nodeType===Node.DOCUMENT_FRAGMENT_NODE?m.host:m}while(!l&&o!==document.body||l&&(t.contains(o)||t===o));return c&&(Math.abs(d)<1||!i)?u=!0:c||!(Math.abs(h)<1)&&i||(u=!0),u}(f,t,e,"h"===f?l:u,!0)},[]),l=p.useCallback(function(e){var r=e;if(Gs.length&&Gs[Gs.length-1]===s){var n="deltaY"in r?Bs(r):$s(r),i=t.current.filter(function(e){return e.name===r.type&&(e.target===r.target||r.target===e.shadowParent)&&function(e,t){return e[0]===t[0]&&e[1]===t[1]}(e.delta,n)})[0];if(i&&i.should)r.cancelable&&r.preventDefault();else if(!i){var l=(a.current.shards||[]).map(Us).filter(Boolean).filter(function(e){return e.contains(r.target)});(l.length>0?o(r,l[0]):!a.current.noIsolation)&&r.cancelable&&r.preventDefault()}}},[]),u=p.useCallback(function(e,r,n,i){var s={name:e,delta:r,target:n,should:i,shadowParent:Hs(n)};t.current.push(s),setTimeout(function(){t.current=t.current.filter(function(e){return e!==s})},1)},[]),c=p.useCallback(function(e){r.current=$s(e),n.current=void 0},[]),d=p.useCallback(function(t){u(t.type,Bs(t),t.target,o(t,e.lockRef.current))},[]),h=p.useCallback(function(t){u(t.type,$s(t),t.target,o(t,e.lockRef.current))},[]);p.useEffect(function(){return Gs.push(s),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:h}),document.addEventListener("wheel",l,_s),document.addEventListener("touchmove",l,_s),document.addEventListener("touchstart",c,_s),function(){Gs=Gs.filter(function(e){return e!==s}),document.removeEventListener("wheel",l,_s),document.removeEventListener("touchmove",l,_s),document.removeEventListener("touchstart",c,_s)}},[]);var f=e.removeScrollBar,g=e.inert;return p.createElement(p.Fragment,null,g?p.createElement(s,{styles:zs(i)}):null,f?p.createElement(Cs,{noRelative:e.noRelative,gapMode:e.gapMode}):null)},vs.useMedium(Vs),ms),Ks=p.forwardRef(function(e,t){return p.createElement(bs,Q({},e,{ref:t,sideCar:Ws}))});Ks.classNames=bs.classNames;var Ys=new WeakMap,qs=new WeakMap,Xs={},Qs=0,Zs=function(e){return e&&(e.host||Zs(e.parentNode))},Js=function(e,t,r,n){var i=function(e,t){return t.map(function(t){if(e.contains(t))return t;var r=Zs(t);return r&&e.contains(r)?r:(console.error("aria-hidden",t,"in not contained inside",e,". Doing nothing"),null)}).filter(function(e){return Boolean(e)})}(t,Array.isArray(e)?e:[e]);Xs[r]||(Xs[r]=new WeakMap);var s=Xs[r],a=[],o=new Set,l=new Set(i),u=function(e){e&&!o.has(e)&&(o.add(e),u(e.parentNode))};i.forEach(u);var c=function(e){e&&!l.has(e)&&Array.prototype.forEach.call(e.children,function(e){if(o.has(e))c(e);else try{var t=e.getAttribute(n),i=null!==t&&"false"!==t,l=(Ys.get(e)||0)+1,u=(s.get(e)||0)+1;Ys.set(e,l),s.set(e,u),a.push(e),1===l&&i&&qs.set(e,!0),1===u&&e.setAttribute(r,"true"),i||e.setAttribute(n,"true")}catch(t){console.error("aria-hidden: cannot operate on ",e,t)}})};return c(t),o.clear(),Qs++,function(){a.forEach(function(e){var t=Ys.get(e)-1,i=s.get(e)-1;Ys.set(e,t),s.set(e,i),t||(qs.has(e)||e.removeAttribute(n),qs.delete(e)),i||e.removeAttribute(r)}),--Qs||(Ys=new WeakMap,Ys=new WeakMap,qs=new WeakMap,Xs={})}},ea=function(e,t,r){void 0===r&&(r="data-aria-hidden");var n=Array.from(Array.isArray(e)?e:[e]),i=function(e){return"undefined"==typeof document?null:(Array.isArray(e)?e[0]:e).ownerDocument.body}(e);return i?(n.push.apply(n,Array.from(i.querySelectorAll("[aria-live], script"))),Js(n,i,r,"aria-hidden")):function(){return null}},ta="Dialog",[ra,na]=function(e,t=[]){let r=[];const n=()=>{const t=r.map(e=>p.createContext(e));return function(r){const n=r?.[e]||t;return p.useMemo(()=>({[`__scope${e}`]:{...r,[e]:n}}),[r,n])}};return n.scopeName=e,[function(t,n){const i=p.createContext(n),s=r.length;r=[...r,n];const a=t=>{const{scope:r,children:n,...a}=t,o=r?.[e]?.[s]||i,l=p.useMemo(()=>a,Object.values(a));return Ti.jsx(o.Provider,{value:l,children:n})};return a.displayName=t+"Provider",[a,function(r,a){const o=a?.[e]?.[s]||i,l=p.useContext(o);if(l)return l;if(void 0!==n)return n;throw new Error(`\`${r}\` must be used within \`${t}\``)}]},xi(n,...t)]}(ta),[ia,sa]=ra(ta),aa=e=>{const{__scopeDialog:t,children:r,open:n,defaultOpen:i,onOpenChange:s,modal:a=!0}=e,o=p.useRef(null),l=p.useRef(null),[u,c]=Ci({prop:n,defaultProp:i??!1,onChange:s,caller:ta});return Ti.jsx(ia,{scope:t,triggerRef:o,contentRef:l,contentId:Li(),titleId:Li(),descriptionId:Li(),open:u,onOpenChange:c,onOpenToggle:p.useCallback(()=>c(e=>!e),[c]),modal:a,children:r})};aa.displayName=ta;var oa="DialogTrigger",la=p.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,i=sa(oa,r),s=yi(t,i.triggerRef);return Ti.jsx(Fi.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":La(i.open),...n,ref:s,onClick:gi(e.onClick,i.onOpenToggle)})});la.displayName=oa;var ua="DialogPortal",[ca,da]=ra(ua,{forceMount:void 0}),ha=e=>{const{__scopeDialog:t,forceMount:r,children:n,container:i}=e,s=sa(ua,t);return Ti.jsx(ca,{scope:t,forceMount:r,children:p.Children.map(n,e=>Ti.jsx(ss,{present:r||s.open,children:Ti.jsx(is,{asChild:!0,container:i,children:e})}))})};ha.displayName=ua;var fa="DialogOverlay",pa=p.forwardRef((e,t)=>{const r=da(fa,e.__scopeDialog),{forceMount:n=r.forceMount,...i}=e,s=sa(fa,e.__scopeDialog);return s.modal?Ti.jsx(ss,{present:n||s.open,children:Ti.jsx(ma,{...i,ref:t})}):null});pa.displayName=fa;var ga=_i("DialogOverlay.RemoveScroll"),ma=p.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,i=sa(fa,r);return Ti.jsx(Ks,{as:ga,allowPinchZoom:!0,shards:[i.contentRef],children:Ti.jsx(Fi.div,{"data-state":La(i.open),...n,ref:t,style:{pointerEvents:"auto",...n.style}})})}),va="DialogContent",ya=p.forwardRef((e,t)=>{const r=da(va,e.__scopeDialog),{forceMount:n=r.forceMount,...i}=e,s=sa(va,e.__scopeDialog);return Ti.jsx(ss,{present:n||s.open,children:s.modal?Ti.jsx(ba,{...i,ref:t}):Ti.jsx(wa,{...i,ref:t})})});ya.displayName=va;var ba=p.forwardRef((e,t)=>{const r=sa(va,e.__scopeDialog),n=p.useRef(null),i=yi(t,r.contentRef,n);return p.useEffect(()=>{const e=n.current;if(e)return ea(e)},[]),Ti.jsx(Ea,{...e,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:gi(e.onCloseAutoFocus,e=>{e.preventDefault(),r.triggerRef.current?.focus()}),onPointerDownOutside:gi(e.onPointerDownOutside,e=>{const t=e.detail.originalEvent,r=0===t.button&&!0===t.ctrlKey;(2===t.button||r)&&e.preventDefault()}),onFocusOutside:gi(e.onFocusOutside,e=>e.preventDefault())})}),wa=p.forwardRef((e,t)=>{const r=sa(va,e.__scopeDialog),n=p.useRef(!1),i=p.useRef(!1);return Ti.jsx(Ea,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:t=>{e.onCloseAutoFocus?.(t),t.defaultPrevented||(n.current||r.triggerRef.current?.focus(),t.preventDefault()),n.current=!1,i.current=!1},onInteractOutside:t=>{e.onInteractOutside?.(t),t.defaultPrevented||(n.current=!0,"pointerdown"===t.detail.originalEvent.type&&(i.current=!0));const s=t.target,a=r.triggerRef.current?.contains(s);a&&t.preventDefault(),"focusin"===t.detail.originalEvent.type&&i.current&&t.preventDefault()}})}),Ea=p.forwardRef((e,t)=>{const{__scopeDialog:r,trapFocus:n,onOpenAutoFocus:i,onCloseAutoFocus:s,...a}=e,o=sa(va,r),l=p.useRef(null),u=yi(t,l);return p.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??ls()),document.body.insertAdjacentElement("beforeend",e[1]??ls()),os++,()=>{1===os&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),os--}},[]),Ti.jsxs(Ti.Fragment,{children:[Ti.jsx(Qi,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:i,onUnmountAutoFocus:s,children:Ti.jsx(Vi,{role:"dialog",id:o.contentId,"aria-describedby":o.descriptionId,"aria-labelledby":o.titleId,"data-state":La(o.open),...a,ref:u,onDismiss:()=>o.onOpenChange(!1)})}),Ti.jsxs(Ti.Fragment,{children:[Ti.jsx(Da,{titleId:o.titleId}),Ti.jsx(_a,{contentRef:l,descriptionId:o.descriptionId})]})]})}),Sa="DialogTitle",Ta=p.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,i=sa(Sa,r);return Ti.jsx(Fi.h2,{id:i.titleId,...n,ref:t})});Ta.displayName=Sa;var xa="DialogDescription",ka=p.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,i=sa(xa,r);return Ti.jsx(Fi.p,{id:i.descriptionId,...n,ref:t})});ka.displayName=xa;var Aa="DialogClose",Ra=p.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,i=sa(Aa,r);return Ti.jsx(Fi.button,{type:"button",...n,ref:t,onClick:gi(e.onClick,()=>i.onOpenChange(!1))})});function La(e){return e?"open":"closed"}Ra.displayName=Aa;var Ia="DialogTitleWarning",[Ca,Pa]=function(e,t){const r=p.createContext(t),n=e=>{const{children:t,...n}=e,i=p.useMemo(()=>n,Object.values(n));return Ti.jsx(r.Provider,{value:i,children:t})};return n.displayName=e+"Provider",[n,function(n){const i=p.useContext(r);if(i)return i;if(void 0!==t)return t;throw new Error(`\`${n}\` must be used within \`${e}\``)}]}(Ia,{contentName:va,titleName:Sa,docsSlug:"dialog"}),Da=({titleId:e})=>{const t=Pa(Ia),r=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.\n\nIf you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.\n\nFor more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return p.useEffect(()=>{if(e){document.getElementById(e)||console.error(r)}},[r,e]),null},_a=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Pa("DialogDescriptionWarning").contentName}}.`;return p.useEffect(()=>{const n=e.current?.getAttribute("aria-describedby");if(t&&n){document.getElementById(t)||console.warn(r)}},[r,e,t]),null},Ma=aa,Oa=la,Na=ha,Fa=pa,$a=ya,Ba=Ta,Ua=ka,za=Ra;const ja=g.createContext({drawerRef:{current:null},overlayRef:{current:null},onPress:()=>{},onRelease:()=>{},onDrag:()=>{},onNestedDrag:()=>{},onNestedOpenChange:()=>{},onNestedRelease:()=>{},openProp:void 0,dismissible:!1,isOpen:!1,isDragging:!1,keyboardIsOpen:{current:!1},snapPointsOffset:null,snapPoints:null,handleOnly:!1,modal:!1,shouldFade:!1,activeSnapPoint:null,onOpenChange:()=>{},setActiveSnapPoint:()=>{},closeDrawer:()=>{},direction:"bottom",shouldAnimate:{current:!0},shouldScaleBackground:!1,setBackgroundColorOnScale:!0,noBodyStyles:!1,container:null,autoFocus:!1}),Ga=()=>{const e=g.useContext(ja);if(!e)throw new Error("useDrawerContext must be used within a Drawer.Root");return e};function Ha(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function Va(){return Ka(/^iPad/)||Ka(/^Mac/)&&navigator.maxTouchPoints>1}function Wa(){return Ka(/^iPhone/)||Va()}function Ka(e){return"undefined"!=typeof window&&null!=window.navigator?e.test(window.navigator.platform):void 0}!function(e){if("undefined"==typeof document)return;let t=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",t.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}("[data-vaul-drawer]{touch-action:none;will-change:transform;transition:transform .5s cubic-bezier(.32, .72, 0, 1);animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=open]{animation-name:slideFromBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=bottom][data-state=closed]{animation-name:slideToBottom}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=open]{animation-name:slideFromTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=top][data-state=closed]{animation-name:slideToTop}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=open]{animation-name:slideFromLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=left][data-state=closed]{animation-name:slideToLeft}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=open]{animation-name:slideFromRight}[data-vaul-drawer][data-vaul-snap-points=false][data-vaul-drawer-direction=right][data-state=closed]{animation-name:slideToRight}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--initial-transform,100%),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}[data-vaul-drawer][data-vaul-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--initial-transform,100%),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=top]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=bottom]{transform:translate3d(0,var(--snap-point-height,0),0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=left]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-drawer][data-vaul-delayed-snap-points=true][data-vaul-drawer-direction=right]{transform:translate3d(var(--snap-point-height,0),0,0)}[data-vaul-overlay][data-vaul-snap-points=false]{animation-duration:.5s;animation-timing-function:cubic-bezier(0.32,0.72,0,1)}[data-vaul-overlay][data-vaul-snap-points=false][data-state=open]{animation-name:fadeIn}[data-vaul-overlay][data-state=closed]{animation-name:fadeOut}[data-vaul-animate=false]{animation:none!important}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:0;transition:opacity .5s cubic-bezier(.32, .72, 0, 1)}[data-vaul-overlay][data-vaul-snap-points=true]{opacity:1}[data-vaul-drawer]:not([data-vaul-custom-container=true])::after{content:'';position:absolute;background:inherit;background-color:inherit}[data-vaul-drawer][data-vaul-drawer-direction=top]::after{top:initial;bottom:100%;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=bottom]::after{top:100%;bottom:initial;left:0;right:0;height:200%}[data-vaul-drawer][data-vaul-drawer-direction=left]::after{left:initial;right:100%;top:0;bottom:0;width:200%}[data-vaul-drawer][data-vaul-drawer-direction=right]::after{left:100%;right:initial;top:0;bottom:0;width:200%}[data-vaul-overlay][data-vaul-snap-points=true]:not([data-vaul-snap-points-overlay=true]):not(\n[data-state=closed]\n){opacity:0}[data-vaul-overlay][data-vaul-snap-points-overlay=true]{opacity:1}[data-vaul-handle]{display:block;position:relative;opacity:.7;background:#e2e2e4;margin-left:auto;margin-right:auto;height:5px;width:32px;border-radius:1rem;touch-action:pan-y}[data-vaul-handle]:active,[data-vaul-handle]:hover{opacity:1}[data-vaul-handle-hitarea]{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:max(100%,2.75rem);height:max(100%,2.75rem);touch-action:inherit}@media (hover:hover) and (pointer:fine){[data-vaul-drawer]{user-select:none}}@media (pointer:fine){[data-vaul-handle-hitarea]:{width:100%;height:100%}}@keyframes fadeIn{from{opacity:0}to{opacity:1}}@keyframes fadeOut{to{opacity:0}}@keyframes slideFromBottom{from{transform:translate3d(0,var(--initial-transform,100%),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToBottom{to{transform:translate3d(0,var(--initial-transform,100%),0)}}@keyframes slideFromTop{from{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}to{transform:translate3d(0,0,0)}}@keyframes slideToTop{to{transform:translate3d(0,calc(var(--initial-transform,100%) * -1),0)}}@keyframes slideFromLeft{from{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToLeft{to{transform:translate3d(calc(var(--initial-transform,100%) * -1),0,0)}}@keyframes slideFromRight{from{transform:translate3d(var(--initial-transform,100%),0,0)}to{transform:translate3d(0,0,0)}}@keyframes slideToRight{to{transform:translate3d(var(--initial-transform,100%),0,0)}}");const Ya="undefined"!=typeof window?p.useLayoutEffect:p.useEffect;function qa(...e){return(...t)=>{for(let r of e)"function"==typeof r&&r(...t)}}const Xa="undefined"!=typeof document&&window.visualViewport;function Qa(e){let t=window.getComputedStyle(e);return/(auto|scroll)/.test(t.overflow+t.overflowX+t.overflowY)}function Za(e){for(Qa(e)&&(e=e.parentElement);e&&!Qa(e);)e=e.parentElement;return e||document.scrollingElement||document.documentElement}const Ja=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);let eo,to=0;function ro(e={}){let{isDisabled:t}=e;Ya(()=>{if(!t)return to++,1===to&&Wa()&&(eo=function(){let e,t=0,r=r=>{e=Za(r.target),e===document.documentElement&&e===document.body||(t=r.changedTouches[0].pageY)},n=r=>{if(!e||e===document.documentElement||e===document.body)return void r.preventDefault();let n=r.changedTouches[0].pageY,i=e.scrollTop,s=e.scrollHeight-e.clientHeight;0!==s&&((i<=0&&n>t||i>=s&&n<t)&&r.preventDefault(),t=n)},i=e=>{let t=e.target;so(t)&&t!==document.activeElement&&(e.preventDefault(),t.style.transform="translateY(-2000px)",t.focus(),requestAnimationFrame(()=>{t.style.transform=""}))},s=e=>{let t=e.target;so(t)&&(t.style.transform="translateY(-2000px)",requestAnimationFrame(()=>{t.style.transform="",Xa&&(Xa.height<window.innerHeight?requestAnimationFrame(()=>{io(t)}):Xa.addEventListener("resize",()=>io(t),{once:!0}))}))},a=()=>{window.scrollTo(0,0)},o=window.pageXOffset,l=window.pageYOffset,u=qa(function(e,t,r){let n=e.style[t];return e.style[t]=r,()=>{e.style[t]=n}}(document.documentElement,"paddingRight",window.innerWidth-document.documentElement.clientWidth+"px"));window.scrollTo(0,0);let c=qa(no(document,"touchstart",r,{passive:!1,capture:!0}),no(document,"touchmove",n,{passive:!1,capture:!0}),no(document,"touchend",i,{passive:!1,capture:!0}),no(document,"focus",s,!0),no(window,"scroll",a));return()=>{u(),c(),window.scrollTo(o,l)}}()),()=>{to--,0===to&&(null==eo||eo())}},[t])}function no(e,t,r,n){return e.addEventListener(t,r,n),()=>{e.removeEventListener(t,r,n)}}function io(e){let t=document.scrollingElement||document.documentElement;for(;e&&e!==t;){let t=Za(e);if(t!==document.documentElement&&t!==document.body&&t!==e){let r=t.getBoundingClientRect().top,n=e.getBoundingClientRect().top;e.getBoundingClientRect().bottom>t.getBoundingClientRect().bottom+24&&(t.scrollTop+=n-r)}e=t.parentElement}}function so(e){return e instanceof HTMLInputElement&&!Ja.has(e.type)||e instanceof HTMLTextAreaElement||e instanceof HTMLElement&&e.isContentEditable}function ao(...e){return p.useCallback(function(...e){return t=>e.forEach(e=>function(e,t){"function"==typeof e?e(t):null!=e&&(e.current=t)}(e,t))}(...e),e)}const oo=new WeakMap;function lo(e,t,r=!1){if(!(e&&e instanceof HTMLElement))return;let n={};Object.entries(t).forEach(([t,r])=>{t.startsWith("--")?e.style.setProperty(t,r):(n[t]=e.style[t],e.style[t]=r)}),r||oo.set(e,n)}const uo=e=>{switch(e){case"top":case"bottom":return!0;case"left":case"right":return!1;default:return e}};function co(e,t){if(!e)return null;const r=window.getComputedStyle(e),n=r.transform||r.webkitTransform||r.mozTransform;let i=n.match(/^matrix3d\((.+)\)$/);return i?parseFloat(i[1].split(", ")[uo(t)?13:12]):(i=n.match(/^matrix\((.+)\)$/),i?parseFloat(i[1].split(", ")[uo(t)?5:4]):null)}function ho(e,t){if(!e)return()=>{};const r=e.style.cssText;return Object.assign(e.style,t),()=>{e.style.cssText=r}}const fo={DURATION:.5,EASE:[.32,.72,0,1]},po=16,go="vaul-dragging";function mo(e){const t=g.useRef(e);return g.useEffect(()=>{t.current=e}),g.useMemo(()=>(...e)=>null==t.current?void 0:t.current.call(t,...e),[])}function vo({prop:e,defaultProp:t,onChange:r=()=>{}}){const[n,i]=function({defaultProp:e,onChange:t}){const r=g.useState(e),[n]=r,i=g.useRef(n),s=mo(t);return g.useEffect(()=>{i.current!==n&&(s(n),i.current=n)},[n,i,s]),r}({defaultProp:t,onChange:r}),s=void 0!==e,a=s?e:n,o=mo(r),l=g.useCallback(t=>{if(s){const r="function"==typeof t?t(e):t;r!==e&&o(r)}else i(t)},[s,e,i,o]);return[a,l]}let yo=null;function bo({open:e,onOpenChange:t,children:r,onDrag:n,onRelease:i,snapPoints:s,shouldScaleBackground:a=!1,setBackgroundColorOnScale:o=!0,closeThreshold:l=.25,scrollLockTimeout:u=100,dismissible:c=!0,handleOnly:d=!1,fadeFromIndex:h=s&&s.length-1,activeSnapPoint:f,setActiveSnapPoint:p,fixed:m,modal:v=!0,onClose:y,nested:b,noBodyStyles:w=!1,direction:E="bottom",defaultOpen:S=!1,disablePreventScroll:T=!0,snapToSequentialPoint:x=!1,preventScrollRestoration:k=!1,repositionInputs:A=!0,onAnimationEnd:R,container:L,autoFocus:I=!1}){var C,P;const[D=!1,_]=vo({defaultProp:S,prop:e,onChange:e=>{null==t||t(e),e||b||ce(),setTimeout(()=>{null==R||R(e)},1e3*fo.DURATION),e&&!v&&"undefined"!=typeof window&&window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"}),e||(document.body.style.pointerEvents="auto")}}),[M,O]=g.useState(!1),[N,F]=g.useState(!1),[$,B]=g.useState(!1),U=g.useRef(null),z=g.useRef(null),j=g.useRef(null),G=g.useRef(null),H=g.useRef(null),V=g.useRef(!1),W=g.useRef(null),K=g.useRef(0),Y=g.useRef(!1),q=g.useRef(!S),X=g.useRef(0),Q=g.useRef(null),Z=g.useRef((null==(C=Q.current)?void 0:C.getBoundingClientRect().height)||0),J=g.useRef((null==(P=Q.current)?void 0:P.getBoundingClientRect().width)||0),ee=g.useRef(0),te=g.useCallback(e=>{s&&e===ae.length-1&&(z.current=new Date)},[]),{activeSnapPoint:re,activeSnapPointIndex:ne,setActiveSnapPoint:ie,onRelease:se,snapPointsOffset:ae,onDrag:oe,shouldFade:le,getPercentageDragged:ue}=function({activeSnapPointProp:e,setActiveSnapPointProp:t,snapPoints:r,drawerRef:n,overlayRef:i,fadeFromIndex:s,onSnapPointChange:a,direction:o="bottom",container:l,snapToSequentialPoint:u}){const[c,d]=vo({prop:e,defaultProp:null==r?void 0:r[0],onChange:t}),[h,f]=g.useState("undefined"!=typeof window?{innerWidth:window.innerWidth,innerHeight:window.innerHeight}:void 0);g.useEffect(()=>{function e(){f({innerWidth:window.innerWidth,innerHeight:window.innerHeight})}return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const p=g.useMemo(()=>c===(null==r?void 0:r[r.length-1])||null,[r,c]),m=g.useMemo(()=>{var e;return null!=(e=null==r?void 0:r.findIndex(e=>e===c))?e:null},[r,c]),v=r&&r.length>0&&(s||0===s)&&!Number.isNaN(s)&&r[s]===c||!r,y=g.useMemo(()=>{const e=l?{width:l.getBoundingClientRect().width,height:l.getBoundingClientRect().height}:"undefined"!=typeof window?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0};var t;return null!=(t=null==r?void 0:r.map(t=>{const r="string"==typeof t;let n=0;if(r&&(n=parseInt(t,10)),uo(o)){const i=r?n:h?t*e.height:0;return h?"bottom"===o?e.height-i:-e.height+i:i}const i=r?n:h?t*e.width:0;return h?"right"===o?e.width-i:-e.width+i:i}))?t:[]},[r,h,l]),b=g.useMemo(()=>null!==m?null==y?void 0:y[m]:null,[y,m]),w=g.useCallback(e=>{var t;const l=null!=(t=null==y?void 0:y.findIndex(t=>t===e))?t:null;a(l),lo(n.current,{transition:`transform ${fo.DURATION}s cubic-bezier(${fo.EASE.join(",")})`,transform:uo(o)?`translate3d(0, ${e}px, 0)`:`translate3d(${e}px, 0, 0)`}),y&&l!==y.length-1&&void 0!==s&&l!==s&&l<s?lo(i.current,{transition:`opacity ${fo.DURATION}s cubic-bezier(${fo.EASE.join(",")})`,opacity:"0"}):lo(i.current,{transition:`opacity ${fo.DURATION}s cubic-bezier(${fo.EASE.join(",")})`,opacity:"1"}),d(null==r?void 0:r[Math.max(l,0)])},[n.current,r,y,s,i,d]);return g.useEffect(()=>{if(c||e){var t;const n=null!=(t=null==r?void 0:r.findIndex(t=>t===e||t===c))?t:-1;y&&-1!==n&&"number"==typeof y[n]&&w(y[n])}},[c,e,r,y,w]),{isLastSnapPoint:p,activeSnapPoint:c,shouldFade:v,getPercentageDragged:function(e,t){if(!r||"number"!=typeof m||!y||void 0===s)return null;const n=m===s-1;if(m>=s&&t)return 0;if(n&&!t)return 1;if(!v&&!n)return null;const i=n?m+1:m-1,a=n?y[i]-y[i-1]:y[i+1]-y[i],o=e/Math.abs(a);return n?1-o:o},setActiveSnapPoint:d,activeSnapPointIndex:m,onRelease:function({draggedDistance:e,closeDrawer:t,velocity:n,dismissible:a}){if(void 0===s)return;const l="bottom"===o||"right"===o?(null!=b?b:0)-e:(null!=b?b:0)+e,c=0===m,d=e>0;if(m===s-1&&lo(i.current,{transition:`opacity ${fo.DURATION}s cubic-bezier(${fo.EASE.join(",")})`}),!u&&n>2&&!d)return void(a?t():w(y[0]));if(!u&&n>2&&d&&y&&r)return void w(y[r.length-1]);const h=null==y?void 0:y.reduce((e,t)=>"number"!=typeof e||"number"!=typeof t?e:Math.abs(t-l)<Math.abs(e-l)?t:e),f=uo(o)?window.innerHeight:window.innerWidth;if(n>.4&&Math.abs(e)<.4*f){const e=d?1:-1;if(e>0&&p&&r)return void w(y[r.length-1]);if(c&&e<0&&a&&t(),null===m)return;return void w(y[m+e])}w(h)},onDrag:function({draggedDistance:e}){if(null===b)return;const t="bottom"===o||"right"===o?b-e:b+e;("bottom"===o||"right"===o)&&t<y[y.length-1]||("top"===o||"left"===o)&&t>y[y.length-1]||lo(n.current,{transform:uo(o)?`translate3d(0, ${t}px, 0)`:`translate3d(${t}px, 0, 0)`})},snapPointsOffset:y}}({snapPoints:s,activeSnapPointProp:f,setActiveSnapPointProp:p,drawerRef:Q,fadeFromIndex:h,overlayRef:U,onSnapPointChange:te,direction:E,container:L,snapToSequentialPoint:x});ro({isDisabled:!D||N||!v||$||!M||!A||!T});const{restorePositionSetting:ce}=function({isOpen:e,modal:t,nested:r,hasBeenOpened:n,preventScrollRestoration:i,noBodyStyles:s}){const[a,o]=g.useState(()=>"undefined"!=typeof window?window.location.href:""),l=g.useRef(0),u=g.useCallback(()=>{if(Ha()&&null===yo&&e&&!s){yo={position:document.body.style.position,top:document.body.style.top,left:document.body.style.left,height:document.body.style.height,right:"unset"};const{scrollX:e,innerHeight:t}=window;document.body.style.setProperty("position","fixed","important"),Object.assign(document.body.style,{top:-l.current+"px",left:-e+"px",right:"0px",height:"auto"}),window.setTimeout(()=>window.requestAnimationFrame(()=>{const e=t-window.innerHeight;e&&l.current>=t&&(document.body.style.top=-(l.current+e)+"px")}),300)}},[e]),c=g.useCallback(()=>{if(Ha()&&null!==yo&&!s){const e=-parseInt(document.body.style.top,10),t=-parseInt(document.body.style.left,10);Object.assign(document.body.style,yo),window.requestAnimationFrame(()=>{i&&a!==window.location.href?o(window.location.href):window.scrollTo(t,e)}),yo=null}},[a]);return g.useEffect(()=>{function e(){l.current=window.scrollY}return e(),window.addEventListener("scroll",e),()=>{window.removeEventListener("scroll",e)}},[]),g.useEffect(()=>{if(t)return()=>{"undefined"!=typeof document&&(document.querySelector("[data-vaul-drawer]")||c())}},[t,c]),g.useEffect(()=>{!r&&n&&(e?(!window.matchMedia("(display-mode: standalone)").matches&&u(),t||window.setTimeout(()=>{c()},500)):c())},[e,n,a,t,r,u,c]),{restorePositionSetting:c}}({isOpen:D,modal:v,nested:null!=b&&b,hasBeenOpened:M,preventScrollRestoration:k,noBodyStyles:w});function de(){return(window.innerWidth-26)/window.innerWidth}function he(e,t){var r;let n=e;const i=null==(r=window.getSelection())?void 0:r.toString(),s=Q.current?co(Q.current,E):null,a=new Date;if("SELECT"===n.tagName)return!1;if(n.hasAttribute("data-vaul-no-drag")||n.closest("[data-vaul-no-drag]"))return!1;if("right"===E||"left"===E)return!0;if(z.current&&a.getTime()-z.current.getTime()<500)return!1;if(null!==s&&("bottom"===E?s>0:s<0))return!0;if(i&&i.length>0)return!1;if(H.current&&a.getTime()-H.current.getTime()<u&&0===s)return H.current=a,!1;if(t)return H.current=a,!1;for(;n;){if(n.scrollHeight>n.clientHeight){if(0!==n.scrollTop)return H.current=new Date,!1;if("dialog"===n.getAttribute("role"))return!0}n=n.parentNode}return!0}function fe(e){!function(){if(!N||!Q.current)return;Q.current.classList.remove(go),V.current=!1,F(!1),G.current=new Date}(),null==y||y(),e||_(!1),setTimeout(()=>{s&&ie(s[0])},1e3*fo.DURATION)}function pe(){if(!Q.current)return;const e=document.querySelector("[data-vaul-drawer-wrapper]"),t=co(Q.current,E);lo(Q.current,{transform:"translate3d(0, 0, 0)",transition:`transform ${fo.DURATION}s cubic-bezier(${fo.EASE.join(",")})`}),lo(U.current,{transition:`opacity ${fo.DURATION}s cubic-bezier(${fo.EASE.join(",")})`,opacity:"1"}),a&&t&&t>0&&D&&lo(e,{borderRadius:"8px",overflow:"hidden",...uo(E)?{transform:`scale(${de()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`,transformOrigin:"top"}:{transform:`scale(${de()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`,transformOrigin:"left"},transitionProperty:"transform, border-radius",transitionDuration:`${fo.DURATION}s`,transitionTimingFunction:`cubic-bezier(${fo.EASE.join(",")})`},!0)}return g.useEffect(()=>{window.requestAnimationFrame(()=>{q.current=!0})},[]),g.useEffect(()=>{var e;function t(){if(!Q.current||!A)return;if(so(document.activeElement)||Y.current){var e;const t=(null==(e=window.visualViewport)?void 0:e.height)||0,r=window.innerHeight;let n=r-t;const i=Q.current.getBoundingClientRect().height||0,a=i>.8*r;ee.current||(ee.current=i);const o=Q.current.getBoundingClientRect().top;if(Math.abs(X.current-n)>60&&(Y.current=!Y.current),s&&s.length>0&&ae&&ne){n+=ae[ne]||0}if(X.current=n,i>t||Y.current){const e=Q.current.getBoundingClientRect().height;let r=e;e>t&&(r=t-(a?o:26)),Q.current.style.height=m?e-Math.max(n,0)+"px":`${Math.max(r,t-o)}px`}else(function(){const e=navigator.userAgent;return"undefined"!=typeof window&&(/Firefox/.test(e)&&/Mobile/.test(e)||/FxiOS/.test(e))})()||(Q.current.style.height=`${ee.current}px`);s&&s.length>0&&!Y.current?Q.current.style.bottom="0px":Q.current.style.bottom=`${Math.max(n,0)}px`}}return null==(e=window.visualViewport)||e.addEventListener("resize",t),()=>{var e;return null==(e=window.visualViewport)?void 0:e.removeEventListener("resize",t)}},[ne,s,ae]),g.useEffect(()=>(D&&(lo(document.documentElement,{scrollBehavior:"auto"}),z.current=new Date),()=>{!function(e,t){if(!(e&&e instanceof HTMLElement))return;let r=oo.get(e);r&&(e.style[t]=r[t])}(document.documentElement,"scrollBehavior")}),[D]),g.useEffect(()=>{v||window.requestAnimationFrame(()=>{document.body.style.pointerEvents="auto"})},[v]),g.createElement(Ma,{defaultOpen:S,onOpenChange:e=>{(c||e)&&(e?O(!0):fe(!0),_(e))},open:D},g.createElement(ja.Provider,{value:{activeSnapPoint:re,snapPoints:s,setActiveSnapPoint:ie,drawerRef:Q,overlayRef:U,onOpenChange:t,onPress:function(e){var t,r;(c||s)&&(Q.current&&!Q.current.contains(e.target)||(Z.current=(null==(t=Q.current)?void 0:t.getBoundingClientRect().height)||0,J.current=(null==(r=Q.current)?void 0:r.getBoundingClientRect().width)||0,F(!0),j.current=new Date,Wa()&&window.addEventListener("touchend",()=>V.current=!1,{once:!0}),e.target.setPointerCapture(e.pointerId),K.current=uo(E)?e.pageY:e.pageX))},onRelease:function(e){if(!N||!Q.current)return;Q.current.classList.remove(go),V.current=!1,F(!1),G.current=new Date;const t=co(Q.current,E);if(!e||!he(e.target,!1)||!t||Number.isNaN(t))return;if(null===j.current)return;const r=G.current.getTime()-j.current.getTime(),n=K.current-(uo(E)?e.pageY:e.pageX),a=Math.abs(n)/r;if(a>.05&&(B(!0),setTimeout(()=>{B(!1)},200)),s){return se({draggedDistance:n*("bottom"===E||"right"===E?1:-1),closeDrawer:fe,velocity:a,dismissible:c}),void(null==i||i(e,!0))}if("bottom"===E||"right"===E?n>0:n<0)return pe(),void(null==i||i(e,!0));if(a>.4)return fe(),void(null==i||i(e,!1));var o;const u=Math.min(null!=(o=Q.current.getBoundingClientRect().height)?o:0,window.innerHeight);var d;const h=Math.min(null!=(d=Q.current.getBoundingClientRect().width)?d:0,window.innerWidth),f="left"===E||"right"===E;if(Math.abs(t)>=(f?h:u)*l)return fe(),void(null==i||i(e,!1));null==i||i(e,!0),pe()},onDrag:function(e){if(Q.current&&N){const t="bottom"===E||"right"===E?1:-1,r=(K.current-(uo(E)?e.pageY:e.pageX))*t,i=r>0,o=s&&!c&&!i;if(o&&0===ne)return;const l=Math.abs(r),u=document.querySelector("[data-vaul-drawer-wrapper]");let d=l/("bottom"===E||"top"===E?Z.current:J.current);const f=ue(l,i);if(null!==f&&(d=f),o&&d>=1)return;if(!V.current&&!he(e.target,i))return;if(Q.current.classList.add(go),V.current=!0,lo(Q.current,{transition:"none"}),lo(U.current,{transition:"none"}),s&&oe({draggedDistance:r}),i&&!s){const e=function(e){return 8*(Math.log(e+1)-2)}(r),n=Math.min(-1*e,0)*t;return void lo(Q.current,{transform:uo(E)?`translate3d(0, ${n}px, 0)`:`translate3d(${n}px, 0, 0)`})}const p=1-d;if((le||h&&ne===h-1)&&(null==n||n(e,d),lo(U.current,{opacity:`${p}`,transition:"none"},!0)),u&&U.current&&a){const e=Math.min(de()+d*(1-de()),1),t=8-8*d,r=Math.max(0,14-14*d);lo(u,{borderRadius:`${t}px`,transform:uo(E)?`scale(${e}) translate3d(0, ${r}px, 0)`:`scale(${e}) translate3d(${r}px, 0, 0)`,transition:"none"},!0)}if(!s){const e=l*t;lo(Q.current,{transform:uo(E)?`translate3d(0, ${e}px, 0)`:`translate3d(${e}px, 0, 0)`})}}},dismissible:c,shouldAnimate:q,handleOnly:d,isOpen:D,isDragging:N,shouldFade:le,closeDrawer:fe,onNestedDrag:function(e,t){if(t<0)return;const r=(window.innerWidth-po)/window.innerWidth,n=r+t*(1-r),i=t*po-16;lo(Q.current,{transform:uo(E)?`scale(${n}) translate3d(0, ${i}px, 0)`:`scale(${n}) translate3d(${i}px, 0, 0)`,transition:"none"})},onNestedOpenChange:function(e){const t=e?(window.innerWidth-po)/window.innerWidth:1,r=e?-16:0;W.current&&window.clearTimeout(W.current),lo(Q.current,{transition:`transform ${fo.DURATION}s cubic-bezier(${fo.EASE.join(",")})`,transform:uo(E)?`scale(${t}) translate3d(0, ${r}px, 0)`:`scale(${t}) translate3d(${r}px, 0, 0)`}),!e&&Q.current&&(W.current=setTimeout(()=>{const e=co(Q.current,E);lo(Q.current,{transition:"none",transform:uo(E)?`translate3d(0, ${e}px, 0)`:`translate3d(${e}px, 0, 0)`})},500))},onNestedRelease:function(e,t){const r=uo(E)?window.innerHeight:window.innerWidth,n=t?(r-po)/r:1,i=t?-16:0;t&&lo(Q.current,{transition:`transform ${fo.DURATION}s cubic-bezier(${fo.EASE.join(",")})`,transform:uo(E)?`scale(${n}) translate3d(0, ${i}px, 0)`:`scale(${n}) translate3d(${i}px, 0, 0)`})},keyboardIsOpen:Y,modal:v,snapPointsOffset:ae,activeSnapPointIndex:ne,direction:E,shouldScaleBackground:a,setBackgroundColorOnScale:o,noBodyStyles:w,container:L,autoFocus:I}},r))}const wo=g.forwardRef(function({...e},t){const{overlayRef:r,snapPoints:n,onRelease:i,shouldFade:s,isOpen:a,modal:o,shouldAnimate:l}=Ga(),u=ao(t,r),c=n&&n.length>0;if(!o)return null;const d=g.useCallback(e=>i(e),[i]);return g.createElement(Fa,{onMouseUp:d,ref:u,"data-vaul-overlay":"","data-vaul-snap-points":a&&c?"true":"false","data-vaul-snap-points-overlay":a&&s?"true":"false","data-vaul-animate":(null==l?void 0:l.current)?"true":"false",...e})});wo.displayName="Drawer.Overlay";const Eo=g.forwardRef(function({onPointerDownOutside:e,style:t,onOpenAutoFocus:r,...n},i){const{drawerRef:s,onPress:a,onRelease:o,onDrag:l,keyboardIsOpen:u,snapPointsOffset:c,activeSnapPointIndex:d,modal:h,isOpen:f,direction:m,snapPoints:v,container:y,handleOnly:b,shouldAnimate:w,autoFocus:E}=Ga(),[S,T]=g.useState(!1),x=ao(i,s),k=g.useRef(null),A=g.useRef(null),R=g.useRef(!1),L=v&&v.length>0;!function(){const{direction:e,isOpen:t,shouldScaleBackground:r,setBackgroundColorOnScale:n,noBodyStyles:i}=Ga(),s=g.useRef(null),a=p.useMemo(()=>document.body.style.backgroundColor,[]);function o(){return(window.innerWidth-26)/window.innerWidth}g.useEffect(()=>{if(t&&r){s.current&&clearTimeout(s.current);const t=document.querySelector("[data-vaul-drawer-wrapper]")||document.querySelector("[vaul-drawer-wrapper]");if(!t)return;n&&!i&&ho(document.body,{background:"black"}),ho(t,{transformOrigin:uo(e)?"top":"left",transitionProperty:"transform, border-radius",transitionDuration:`${fo.DURATION}s`,transitionTimingFunction:`cubic-bezier(${fo.EASE.join(",")})`});const r=ho(t,{borderRadius:"8px",overflow:"hidden",...uo(e)?{transform:`scale(${o()}) translate3d(0, calc(env(safe-area-inset-top) + 14px), 0)`}:{transform:`scale(${o()}) translate3d(calc(env(safe-area-inset-top) + 14px), 0, 0)`}});return()=>{r(),s.current=window.setTimeout(()=>{a?document.body.style.background=a:document.body.style.removeProperty("background")},1e3*fo.DURATION)}}},[t,r,a])}();function I(e){k.current=null,R.current=!1,o(e)}return g.useEffect(()=>{L&&window.requestAnimationFrame(()=>{T(!0)})},[]),g.createElement($a,{"data-vaul-drawer-direction":m,"data-vaul-drawer":"","data-vaul-delayed-snap-points":S?"true":"false","data-vaul-snap-points":f&&L?"true":"false","data-vaul-custom-container":y?"true":"false","data-vaul-animate":(null==w?void 0:w.current)?"true":"false",...n,ref:x,style:c&&c.length>0?{"--snap-point-height":`${c[null!=d?d:0]}px`,...t}:t,onPointerDown:e=>{b||(null==n.onPointerDown||n.onPointerDown.call(n,e),k.current={x:e.pageX,y:e.pageY},a(e))},onOpenAutoFocus:e=>{null==r||r(e),E||e.preventDefault()},onPointerDownOutside:t=>{null==e||e(t),h&&!t.defaultPrevented?u.current&&(u.current=!1):t.preventDefault()},onFocusOutside:e=>{h||e.preventDefault()},onPointerMove:e=>{if(A.current=e,b)return;if(null==n.onPointerMove||n.onPointerMove.call(n,e),!k.current)return;const t=e.pageY-k.current.y,r=e.pageX-k.current.x,i="touch"===e.pointerType?10:2,s=((e,t,r=0)=>{if(R.current)return!0;const n=Math.abs(e.y),i=Math.abs(e.x),s=i>n,a=["bottom","right"].includes(t)?1:-1;if("left"===t||"right"===t){if(!(e.x*a<0)&&i>=0&&i<=r)return s}else if(!(e.y*a<0)&&n>=0&&n<=r)return!s;return R.current=!0,!0})({x:r,y:t},m,i);s?l(e):(Math.abs(r)>i||Math.abs(t)>i)&&(k.current=null)},onPointerUp:e=>{null==n.onPointerUp||n.onPointerUp.call(n,e),k.current=null,R.current=!1,o(e)},onPointerOut:e=>{null==n.onPointerOut||n.onPointerOut.call(n,e),I(A.current)},onContextMenu:e=>{null==n.onContextMenu||n.onContextMenu.call(n,e),A.current&&I(A.current)}})});Eo.displayName="Drawer.Content";const So=g.forwardRef(function({preventCycle:e=!1,children:t,...r},n){const{closeDrawer:i,isDragging:s,snapPoints:a,activeSnapPoint:o,setActiveSnapPoint:l,dismissible:u,handleOnly:c,isOpen:d,onPress:h,onDrag:f}=Ga(),p=g.useRef(null),m=g.useRef(!1);function v(){p.current&&window.clearTimeout(p.current),m.current=!1}return g.createElement("div",{onClick:function(){m.current?v():window.setTimeout(()=>{!function(){if(s||e||m.current)return void v();if(v(),!a||0===a.length)return void(u||i());if(o===a[a.length-1]&&u)return void i();const t=a.findIndex(e=>e===o);if(-1===t)return;const r=a[t+1];l(r)}()},120)},onPointerCancel:v,onPointerDown:e=>{c&&h(e),p.current=window.setTimeout(()=>{m.current=!0},250)},onPointerMove:e=>{c&&f(e)},ref:n,"data-vaul-drawer-visible":d?"true":"false","data-vaul-handle":"","aria-hidden":"true",...r},g.createElement("span",{"data-vaul-handle-hitarea":"","aria-hidden":"true"},t))});So.displayName="Drawer.Handle";const To={Root:bo,NestedRoot:function({onDrag:e,onOpenChange:t,open:r,...n}){const{onNestedDrag:i,onNestedOpenChange:s,onNestedRelease:a}=Ga();if(!i)throw new Error("Drawer.NestedRoot must be placed in another drawer");return g.createElement(bo,{nested:!0,open:r,onClose:()=>{s(!1)},onDrag:(t,r)=>{i(t,r),null==e||e(t,r)},onOpenChange:e=>{e&&s(e),null==t||t(e)},onRelease:a,...n})},Content:Eo,Overlay:wo,Trigger:Oa,Portal:function(e){const t=Ga(),{container:r=t.container,...n}=e;return g.createElement(Na,{container:r,...n})},Handle:So,Close:za,Title:Ba,Description:Ua};function xo(e){var t=Z(e,[]);return p.createElement(To.Root,Object.assign({"data-slot":"drawer"},t))}function ko(e){var t=Z(e,[]);return p.createElement(To.Trigger,Object.assign({"data-slot":"drawer-trigger"},t))}function Ao(e){var t=Z(e,[]);return p.createElement(To.Portal,Object.assign({"data-slot":"drawer-portal"},t))}function Ro(e){var{className:t}=e,r=Z(e,["className"]);return p.createElement(To.Overlay,Object.assign({"data-slot":"drawer-overlay",className:Ot("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-[999999] bg-black/50",t)},r))}function Lo(e){var{className:t,children:r}=e,n=Z(e,["className","children"]);return p.createElement(Ao,{"data-slot":"drawer-portal"},p.createElement(Ro,null),p.createElement(To.Content,Object.assign({"data-slot":"drawer-content",className:Ot("group/drawer-content bg-background fixed z-[999999] flex h-auto flex-col","data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b","data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t","data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm","data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm",t)},n),p.createElement("div",{className:"bg-muted mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full group-data-[vaul-drawer-direction=bottom]/drawer-content:block"}),r))}function Io(e){var{className:t}=e,r=Z(e,["className"]);return p.createElement("div",Object.assign({"data-slot":"drawer-header",className:Ot("flex flex-col gap-1.5 p-4",t)},r))}function Co(e){var{className:t}=e,r=Z(e,["className"]);return p.createElement(To.Title,Object.assign({"data-slot":"drawer-title",className:Ot("text-foreground font-semibold",t)},r))}const Po=({children:e,products:t,contentId:r})=>{const{isPreview:n}=cr();return g.createElement(xo,{direction:"right",fadeFromIndex:0,snapPoints:[1]},g.createElement(ko,{className:"w-full"},e),g.createElement(Lo,null,g.createElement(Io,null,g.createElement(Co,null,"상품 목록")),g.createElement("div",{className:"overflow-y-scroll grid-cols-2 grid items-baseline justify-items-center scrollbar-hide"},t.map(e=>e.linkPath?g.createElement("a",{key:e.productId,className:"p-2 text-gray-800 w-full h-full flex flex-col items-center justify-center no-underline",href:e.linkPath,target:"_blank",onClick:()=>J(void 0,void 0,void 0,function*(){n||(yield Zt({contentId:r,contentProductId:e.eventProductId,productId:e.productId}))})},g.createElement(Do,{product:e})):g.createElement(Do,{key:e.productId,product:e})))))},Do=({product:e})=>g.createElement("div",{className:"text-gray-800 w-32"},g.createElement("div",{className:"w-full aspect-square mb-2 border border-[#f4f3f6] rounded "},g.createElement("img",{src:e.thumbPath,alt:e.productName,className:"w-full h-full"})),e.brand&&g.createElement("p",{className:"text-xs text-gray-400 mb-1"},e.brand.brandName),g.createElement("p",{className:"w-full text-[12px] md:text-[15px] mb-1"},e.productName),g.createElement("div",{className:"w-full "},g.createElement("div",{className:"flex"},g.createElement("span",{className:"text-sm text-red-500 mr-2 font-semibold"},e.discount,"%"),g.createElement("span",{className:"font-semibold"},Nt(e.sellingPrice),"원"))));function _o(e){let t,r,{swiper:n,extendParams:i,on:s,emit:a,params:o}=e;n.autoplay={running:!1,paused:!1,timeLeft:0},i({autoplay:{enabled:!1,delay:3e3,waitForTransition:!0,disableOnInteraction:!1,stopOnLastSlide:!1,reverseDirection:!1,pauseOnMouseEnter:!1}});let l,u,c,d,h,f,p,g,m=o&&o.autoplay?o.autoplay.delay:3e3,v=o&&o.autoplay?o.autoplay.delay:3e3,y=(new Date).getTime();function b(e){n&&!n.destroyed&&n.wrapperEl&&e.target===n.wrapperEl&&(n.wrapperEl.removeEventListener("transitionend",b),g||e.detail&&e.detail.bySwiperTouchMove||k())}const w=()=>{if(n.destroyed||!n.autoplay.running)return;n.autoplay.paused?u=!0:u&&(v=l,u=!1);const e=n.autoplay.paused?l:y+v-(new Date).getTime();n.autoplay.timeLeft=e,a("autoplayTimeLeft",e,e/m),r=requestAnimationFrame(()=>{w()})},E=e=>{if(n.destroyed||!n.autoplay.running)return;cancelAnimationFrame(r),w();let i=void 0===e?n.params.autoplay.delay:e;m=n.params.autoplay.delay,v=n.params.autoplay.delay;const s=(()=>{let e;if(e=n.virtual&&n.params.virtual.enabled?n.slides.filter(e=>e.classList.contains("swiper-slide-active"))[0]:n.slides[n.activeIndex],!e)return;return parseInt(e.getAttribute("data-swiper-autoplay"),10)})();!Number.isNaN(s)&&s>0&&void 0===e&&(i=s,m=s,v=s),l=i;const o=n.params.speed,u=()=>{n&&!n.destroyed&&(n.params.autoplay.reverseDirection?!n.isBeginning||n.params.loop||n.params.rewind?(n.slidePrev(o,!0,!0),a("autoplay")):n.params.autoplay.stopOnLastSlide||(n.slideTo(n.slides.length-1,o,!0,!0),a("autoplay")):!n.isEnd||n.params.loop||n.params.rewind?(n.slideNext(o,!0,!0),a("autoplay")):n.params.autoplay.stopOnLastSlide||(n.slideTo(0,o,!0,!0),a("autoplay")),n.params.cssMode&&(y=(new Date).getTime(),requestAnimationFrame(()=>{E()})))};return i>0?(clearTimeout(t),t=setTimeout(()=>{u()},i)):requestAnimationFrame(()=>{u()}),i},S=()=>{y=(new Date).getTime(),n.autoplay.running=!0,E(),a("autoplayStart")},T=()=>{n.autoplay.running=!1,clearTimeout(t),cancelAnimationFrame(r),a("autoplayStop")},x=(e,r)=>{if(n.destroyed||!n.autoplay.running)return;clearTimeout(t),e||(p=!0);const i=()=>{a("autoplayPause"),n.params.autoplay.waitForTransition?n.wrapperEl.addEventListener("transitionend",b):k()};if(n.autoplay.paused=!0,r)return f&&(l=n.params.autoplay.delay),f=!1,void i();const s=l||n.params.autoplay.delay;l=s-((new Date).getTime()-y),n.isEnd&&l<0&&!n.params.loop||(l<0&&(l=0),i())},k=()=>{n.isEnd&&l<0&&!n.params.loop||n.destroyed||!n.autoplay.running||(y=(new Date).getTime(),p?(p=!1,E(l)):E(),n.autoplay.paused=!1,a("autoplayResume"))},A=()=>{if(n.destroyed||!n.autoplay.running)return;const e=yr();"hidden"===e.visibilityState&&(p=!0,x(!0)),"visible"===e.visibilityState&&k()},R=e=>{"mouse"===e.pointerType&&(p=!0,g=!0,n.animating||n.autoplay.paused||x(!0))},L=e=>{"mouse"===e.pointerType&&(g=!1,n.autoplay.paused&&k())};s("init",()=>{n.params.autoplay.enabled&&(n.params.autoplay.pauseOnMouseEnter&&(n.el.addEventListener("pointerenter",R),n.el.addEventListener("pointerleave",L)),yr().addEventListener("visibilitychange",A),S())}),s("destroy",()=>{n.el&&"string"!=typeof n.el&&(n.el.removeEventListener("pointerenter",R),n.el.removeEventListener("pointerleave",L)),yr().removeEventListener("visibilitychange",A),n.autoplay.running&&T()}),s("_freeModeStaticRelease",()=>{(d||p)&&k()}),s("_freeModeNoMomentumRelease",()=>{n.params.autoplay.disableOnInteraction?T():x(!0,!0)}),s("beforeTransitionStart",(e,t,r)=>{!n.destroyed&&n.autoplay.running&&(r||!n.params.autoplay.disableOnInteraction?x(!0,!0):T())}),s("sliderFirstMove",()=>{!n.destroyed&&n.autoplay.running&&(n.params.autoplay.disableOnInteraction?T():(c=!0,d=!1,p=!1,h=setTimeout(()=>{p=!0,d=!0,x(!0)},200)))}),s("touchEnd",()=>{if(!n.destroyed&&n.autoplay.running&&c){if(clearTimeout(h),clearTimeout(t),n.params.autoplay.disableOnInteraction)return d=!1,void(c=!1);d&&n.params.cssMode&&k(),d=!1,c=!1}}),s("slideChange",()=>{!n.destroyed&&n.autoplay.running&&(f=!0)}),Object.assign(n.autoplay,{start:S,stop:T,pause:x,resume:k})}function Mo(e,t){const r=Ir(t);return r!==t&&(r.style.backfaceVisibility="hidden",r.style["-webkit-backface-visibility"]="hidden"),r}function Oo(e){let{swiper:t,duration:r,transformElements:n,allSlides:i}=e;const{activeIndex:s}=t;if(t.params.virtualTranslate&&0!==r){let e,r=!1;e=i?n:n.filter(e=>{const r=e.classList.contains("swiper-slide-transform")?(e=>{if(!e.parentElement)return t.slides.filter(t=>t.shadowRoot&&t.shadowRoot===e.parentNode)[0];return e.parentElement})(e):e;return t.getSlideIndex(r)===s}),e.forEach(e=>{!function(e,t){t&&e.addEventListener("transitionend",function r(n){n.target===e&&(t.call(e,n),e.removeEventListener("transitionend",r))})}(e,()=>{if(r)return;if(!t||t.destroyed)return;r=!0,t.animating=!1;const e=new window.CustomEvent("transitionend",{bubbles:!0,cancelable:!0});t.wrapperEl.dispatchEvent(e)})})}}function No(e,t,r){const n=`swiper-slide-shadow swiper-slide-shadow-${e}`,i=Ir(t);let s=i.querySelector(`.${n.split(" ").join(".")}`);return s||(s=Dr("div",n.split(" ")),i.append(s)),s}function Fo(e){let{swiper:t,extendParams:r,on:n}=e;r({cardsEffect:{slideShadows:!0,rotate:!0,perSlideRotate:2,perSlideOffset:8}});!function(e){const{effect:t,swiper:r,on:n,setTranslate:i,setTransition:s,overwriteParams:a,perspective:o,recreateShadows:l,getEffectParams:u}=e;let c;n("beforeInit",()=>{if(r.params.effect!==t)return;r.classNames.push(`${r.params.containerModifierClass}${t}`),o&&o()&&r.classNames.push(`${r.params.containerModifierClass}3d`);const e=a?a():{};Object.assign(r.params,e),Object.assign(r.originalParams,e)}),n("setTranslate",()=>{r.params.effect===t&&i()}),n("setTransition",(e,n)=>{r.params.effect===t&&s(n)}),n("transitionEnd",()=>{if(r.params.effect===t&&l){if(!u||!u().slideShadows)return;r.slides.forEach(e=>{e.querySelectorAll(".swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left").forEach(e=>e.remove())}),l()}}),n("virtualUpdate",()=>{r.params.effect===t&&(r.slides.length||(c=!0),requestAnimationFrame(()=>{c&&r.slides&&r.slides.length&&(i(),c=!1)}))})}({effect:"cards",swiper:t,on:n,setTranslate:()=>{const{slides:e,activeIndex:r,rtlTranslate:n}=t,i=t.params.cardsEffect,{startTranslate:s,isTouched:a}=t.touchEventsData,o=n?-t.translate:t.translate;for(let l=0;l<e.length;l+=1){const u=e[l],c=u.progress,d=Math.min(Math.max(c,-4),4);let h=u.swiperSlideOffset;t.params.centeredSlides&&!t.params.cssMode&&(t.wrapperEl.style.transform=`translateX(${t.minTranslate()}px)`),t.params.centeredSlides&&t.params.cssMode&&(h-=e[0].swiperSlideOffset);let f=t.params.cssMode?-h-t.translate:-h,p=0;const g=-100*Math.abs(d);let m=1,v=-i.perSlideRotate*d,y=i.perSlideOffset-.75*Math.abs(d);const b=t.virtual&&t.params.virtual.enabled?t.virtual.from+l:l,w=(b===r||b===r-1)&&d>0&&d<1&&(a||t.params.cssMode)&&o<s,E=(b===r||b===r+1)&&d<0&&d>-1&&(a||t.params.cssMode)&&o>s;if(w||E){const e=(1-Math.abs((Math.abs(d)-.5)/.5))**.5;v+=-28*d*e,m+=-.5*e,y+=96*e,p=-25*e*Math.abs(d)+"%"}if(f=d<0?`calc(${f}px ${n?"-":"+"} (${y*Math.abs(d)}%))`:d>0?`calc(${f}px ${n?"-":"+"} (-${y*Math.abs(d)}%))`:`${f}px`,!t.isHorizontal()){const e=p;p=f,f=e}const S=d<0?""+(1+(1-m)*d):""+(1-(1-m)*d),T=`\n translate3d(${f}, ${p}, ${g}px)\n rotateZ(${i.rotate?n?-v:v:0}deg)\n scale(${S})\n `;if(i.slideShadows){let e=u.querySelector(".swiper-slide-shadow");e||(e=No("cards",u)),e&&(e.style.opacity=Math.min(Math.max((Math.abs(d)-.5)/.5,0),1))}u.style.zIndex=-Math.abs(Math.round(c))+e.length;Mo(0,u).style.transform=T}},setTransition:e=>{const r=t.slides.map(e=>Ir(e));r.forEach(t=>{t.style.transitionDuration=`${e}ms`,t.querySelectorAll(".swiper-slide-shadow").forEach(t=>{t.style.transitionDuration=`${e}ms`})}),Oo({swiper:t,duration:e,transformElements:r})},perspective:()=>!0,overwriteParams:()=>({watchSlidesProgress:!0,virtualTranslate:!t.params.cssMode})})}const $o=({products:e,useDrawer:t,contentId:r})=>{const n=p.useMemo(()=>(e=>{if(e.length>=3)return e;const t=[...e];for(;t.length<3;)t.push(...e);return t})(e),[e]),i=1===(null==e?void 0:e.length);return(null==e?void 0:e.length)?g.createElement("div",{className:"w-full",style:{height:"80px"}},i?g.createElement("div",{className:"bg-white overflow-hidden rounded-xl w-full",style:{borderRadius:"10px",height:"80px"}},t?g.createElement(Po,{products:e,contentId:r},g.createElement(pi,{product:e[0],productsLength:e.length,contentId:r})):g.createElement(pi,{product:e[0],productsLength:e.length,hideMoreBtn:!0,contentId:r})):g.createElement(_n,{nested:!0,modules:[Fo,_o],slidesPerView:1.1,effect:"cards",autoplay:!0,loop:!0,grabCursor:!0,cardsEffect:{rotate:!1},className:"w-full",style:{height:"80px"}},n.map((n,i)=>g.createElement(Mn,{key:i+n.productId,className:"bg-white overflow-hidden rounded-xl",style:{borderRadius:"10px",height:"80px"}},t?g.createElement(Po,{products:e,contentId:r},g.createElement(pi,{product:n,productsLength:e.length,contentId:r})):g.createElement(pi,{product:n,productsLength:e.length,hideMoreBtn:!0,contentId:r}))))):null},Bo=({shortForm:e,useDrawer:t,isPopup:r,shareUrl:n,handleClose:i})=>{const[s,a]=p.useState(!Boolean(r)),[o,l]=p.useState(!0),{logo:u,productsInfo:c,thumbPath:d,title:h,media:f,brand:m,shortsId:v}=e;return g.createElement("div",{className:"h-full w-full text-sm overflow-hidden text-white relative"},g.createElement("div",{style:{backgroundImage:"linear-gradient(to bottom, rgba(0,0,0,0.4) 0%, transparent 50%, rgba(0,0,0,0.4) 100%)",padding:"15px"},className:"absolute h-full flex flex-col w-full z-[1] justify-between inset-0 bg-gradient-to-b from-black/40 via-transparent to-black/40"},g.createElement("div",{className:"flex gap-2 justify-between "},g.createElement("div",{className:"max-w-16"},(null==u?void 0:u.thumbPath)?g.createElement("img",{className:"mb-1",src:u.thumbPath,alt:u.logoName,width:100,height:100}):null),g.createElement("div",{className:"justify-self-end flex gap-2"},g.createElement("div",{className:"cursor-pointer text-white ",onClick:()=>{l(e=>!e)}},o?g.createElement(ti,{size:20}):g.createElement(ri,{size:20})),g.createElement("div",{className:"cursor-pointer text-white ",onClick:()=>{a(e=>!e)}},s?g.createElement(si,{size:20}):g.createElement(ii,{size:20})),g.createElement("div",{className:"cursor-pointer text-white ",onClick:i},g.createElement(ai,{size:20})))),g.createElement("div",null,g.createElement("div",{className:"flex justify-between items-end mb-3 gap-3"},g.createElement("div",{className:"w-full"},m&&g.createElement("div",{className:"items-center flex gap-3 mb-2"},g.createElement("div",{className:"w-12 h-12 bg-white rounded-full border overflow-hidden"},g.createElement("img",{src:m.thumbPath,alt:m.brandName,width:100,height:100,className:"object-contain w-full h-full"})),g.createElement("p",{style:{fontSize:"14px",textAlign:"start"}},null==m?void 0:m.brandName)),g.createElement("p",{style:{fontSize:"14px",textAlign:"start"}},h)),g.createElement("div",{className:"flex flex-col items-center",style:{gap:"15px"}},g.createElement(ui,{shortsId:v}),g.createElement("div",{className:"w-[24px] h-[24px] flex items-center justify-center"},g.createElement(di,{shortForm:e,shareUrl:n})))),c&&g.createElement($o,{products:c,useDrawer:t,contentId:e.shortsId}))),g.createElement(oi,{file:Ft(null==f?void 0:f.objectId),thumbnail:`${Gt(d)}`,mute:s,isVertical:(null==f?void 0:f.height)>(null==f?void 0:f.width),play:o}))},Uo=g.memo(({shortform:e,shareUrl:t,handleClose:r})=>g.createElement(g.Fragment,null,g.createElement("div",{onClick:e=>e.stopPropagation(),className:"overflow-hidden",style:{borderRadius:"10px",overflow:"hidden",width:"100%",height:"100%",backgroundRepeat:"no-repeat",backgroundPosition:"center",backgroundSize:"cover",backgroundImage:`url(${Gt(e.thumbPath)})`}},g.createElement(Bo,{handleClose:r,shortForm:e,useDrawer:!1,isPopup:!0,shareUrl:t})))),zo=g.memo(({shortform:e})=>g.createElement("div",{onClick:e=>{e.stopPropagation()},style:{width:"100%",height:"100%",borderRadius:"10px",backgroundRepeat:"no-repeat",backgroundPosition:"center",backgroundSize:"cover",backgroundImage:`url(${e.thumbPath.includes("https")?e.thumbPath:`https://${e.thumbPath}`})`}})),jo=({shortform:e,shareUrl:t,handleClose:r})=>{const{isActive:n}=p.useContext(Pn),i=p.useContext(Dn),s=On().width<430||Hn.isMobile;return g.createElement("div",{className:"flex items-center justify-center w-full h-full select-none",onClick:e=>{r()}},g.createElement("div",{className:"max-h-full flex items-center justify-center",style:{width:"100%",aspectRatio:s?"auto":"9 / 16",height:s?"100dvh":"auto",maxHeight:s?void 0:"90vh",transform:s?void 0:`scale(${n?1:.8})`,transition:"transform 180ms ease"}},n?g.createElement("div",{className:"flex items-center justify-between w-full h-full text-white relative"},g.createElement("div",{className:"cursor-pointer absolute",onClick:e=>{e.stopPropagation(),i.slidePrev()},style:{zIndex:1e5,left:s?"0":"-30px",top:"50%",transform:"translateY(-50%)",width:30,height:30,display:"grid",placeItems:"center",pointerEvents:"auto"}},g.createElement(Qn,{size:28})),g.createElement(Uo,{shortform:e,shareUrl:t,handleClose:r}),g.createElement("div",{className:"cursor-pointer absolute",style:{zIndex:1e5,right:s?"0":"-30px",top:"50%",transform:"translateY(-50%)",width:30,height:30,display:"grid",placeItems:"center",pointerEvents:"auto"},onClick:e=>{e.stopPropagation(),i.slideNext()}},g.createElement(Zn,{size:28}))):g.createElement(zo,{shortform:e})))},{PLAYER_BACK_BASE_URL:Go}=Mt(),Ho=({collection:e,initialShortsId:t,onSlideChange:r,onClosePlayer:n})=>{var i;const s=p.useMemo(()=>Math.max(e.contents.findIndex(e=>e.shortsId===t),0),[e.contents,t]),a=e.contents.length,o=Math.max(a,10),l=null!==(i=On().width)&&void 0!==i?i:0,u=l<430||Hn.isMobile,c=u?1:l>=1200?4:l>=900?3:2,d=p.useMemo(()=>(e=>{const t=[...e];for(;t.length<o;)t.push(...e);return t})(e.contents),[e.contents]),h=p.useRef(null);return g.createElement("div",{style:{minHeight:100,minWidth:300},className:"w-full"},g.createElement(_n,{style:{minHeight:100,overflow:"visible"},initialSlide:s,ref:h,lazyPreloadPrevNext:2,className:"w-full",spaceBetween:u?8:l>=1200?24:l>=900?25:16,slidesPerView:c,grabCursor:!0,centeredSlides:1!==c,onSlideChangeTransitionEnd:t=>{const n=t.realIndex%a;null==r||r(n);const i=e.contents[(n+1)%a];var s;s=Ft(i.media.objectId),Nn||(Nn=document.createElement("video"),Nn.muted=!0,Nn.playsInline=!0,Nn.preload="metadata",Nn.loop=!0,Nn.style.cssText="position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;opacity:0",document.body.appendChild(Nn)),Fn!==s&&(Nn.src=s,Nn.load(),Fn=s)},loop:!0,slideToClickedSlide:!0},d.map((t,r)=>g.createElement(Mn,{key:r},g.createElement(jo,{handleClose:n,shortform:t,shareUrl:`${Go}/collection/${e.colId}?start=${t.shortsId}&layout=5`})))))},Vo=({shortform:e,onThumbnailClick:t,iconSize:r,exposeTitle:n,borderLine:i})=>{const s=p.useMemo(()=>jt(i),[i])?{background:"linear-gradient(#fff,#fff) padding-box, conic-gradient(#f58529,#f77737,#fd1d1d,#833ab4,#c13584,#f58529) border-box",border:"3px solid transparent"}:{background:"#fff",border:"3px solid #fff"};return g.createElement("div",{className:"flex flex-col w-full gap-2",onClick:()=>t(e.shortsId)},g.createElement("div",{className:"rounded-full overflow-hidden cursor-pointer",style:Object.assign({width:r,height:r,padding:4},s)},g.createElement("img",{src:Gt(e.thumbPath),alt:"thumbnail",className:"w-full h-full object-cover block rounded-full"})),n&&g.createElement("span",{style:{width:r},className:"text-black overflow-hidden text-[12px] whitespace-nowrap text-center text-clip cursor-default"},e.title))},Wo=ur(e=>({open:!1,setOpen:t=>e({open:t})})),Ko=({product:e,productLength:t,hideMoreBadge:r=!1,contentId:n,lineClamp:i,showMoreBtn:s=!1,openProductPopup:a})=>{const{isPreview:o}=cr();return g.createElement(g.Fragment,null,g.createElement("div",{className:"product-banner border mbus-border",onClick:()=>J(void 0,void 0,void 0,function*(){r&&(window.open(e.linkPath,"_blank"),o||(yield Zt({contentProductId:e.eventProductId,contentId:n,productId:e.productId})))})},g.createElement("span",{className:"product-banner__clip","aria-hidden":!0},g.createElement("span",{className:"product-banner__sheen"})),g.createElement("div",{className:"relative",style:{width:"40%",minWidth:"40%"}},g.createElement("img",{style:{borderRadius:"0.625rem"},className:"aspect-square rounded-lg object-cover w-full",src:Gt(e.thumbPath),alt:e.productName}),!r&&g.createElement("p",{className:"absolute text-white rounded-lg",style:{backgroundColor:"#797979",top:-10,right:-10,padding:"2px 4px",fontSize:"10px",borderRadius:"0.625rem"}},"+",t)),g.createElement("div",{style:{position:"relative",zIndex:2,minWidth:0,flex:1,paddingRight:24}},g.createElement("p",{style:{display:"-webkit-box",WebkitLineClamp:i||2,WebkitBoxOrient:"vertical",overflow:"hidden",wordBreak:"break-word",fontWeight:600,color:"#494949"}},e.productName)),g.createElement("span",{className:"product-banner__arrow","aria-hidden":!0},"›")),s&&t>1&&g.createElement("div",{onClick:a,className:" flex items-center justify-center border mbus-border cursor-pointer",style:{borderRadius:"0.625rem",padding:"10px",backgroundColor:"#f5f5f5",fontWeight:600}},"+ 더보기 (",t,")"))},Yo=({products:e,iconSize:t,contentId:r,setSelectedProducts:n,showMoreBtn:i,hideMoreBadge:s})=>{const{setOpen:a}=Wo(),o=()=>{n({productsInfo:e,shortsId:r}),a(!0)};return g.createElement(g.Fragment,null,g.createElement("div",{onClick:()=>J(void 0,void 0,void 0,function*(){1===e.length||i||o()}),className:"flex flex-col gap-2 mt-4 text-gray-800",style:{maxWidth:t||"100%",fontSize:13}},g.createElement(Ko,{showMoreBtn:i,lineClamp:2,product:e[0],contentId:r,productLength:e.length,hideMoreBadge:null!=s?s:1===e.length,openProductPopup:o})))},qo=({product:e,maxWidth:t="100%",height:r,cardWidth:n})=>g.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,borderRadius:8,backgroundColor:"#ffffff",color:"#111827",maxWidth:t,height:r,width:"100%",paddingRight:8}},g.createElement("img",{src:Gt(e.thumbPath),alt:e.productName,style:{height:"100%",aspectRatio:"1 / 1",borderRadius:6,objectFit:"cover",flexShrink:0}}),g.createElement("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",justifyContent:"center"}},g.createElement("span",{style:{lineHeight:1.25,overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",fontSize:12}},e.productName),g.createElement("span",{style:{lineHeight:1.25,overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",fontSize:11}},"number"==typeof e.sellingPrice&&e.sellingPrice<e.price?"number"==typeof n&&n>=190?g.createElement(g.Fragment,null,g.createElement("span",{style:{color:"#dc2626",fontWeight:600,marginRight:4}},Nt(e.sellingPrice),"원"),g.createElement("span",{style:{color:"#9ca3af",textDecoration:"line-through"}},Nt(e.price),"원")):g.createElement("span",{style:{color:"#dc2626",fontWeight:600}},Nt(e.sellingPrice),"원"):g.createElement("span",{style:{color:"#dc2626",fontWeight:600}},Nt(e.price),"원")))),Xo=({playUrl:e,poster:t})=>g.createElement("div",{className:"w-full h-full absolute top-0 left-0 z-10 pointer-events-none",style:{backgroundImage:`url(${t})`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat"}},g.createElement("video",{src:e,autoPlay:!0,muted:!0,preload:"auto",playsInline:!0,loop:!0,className:"w-full h-full object-cover"})),Qo=({shortform:e,onThumbnailClick:t,iconSize:r,exposeTitle:n,rounded:i,borderLine:s,titlePosition:a,exposeProductBanner:o,setSelectedProducts:l,iconRatio:u,hoverPlay:c,exposeProductBadge:d})=>{var h;const f=p.useMemo(()=>jt(s),[s]),[m,v]=p.useState(!1),{API_BASE_URL:y}=Mt();return g.createElement("div",{className:"relative"},g.createElement("div",{onMouseEnter:()=>v(!0),onMouseLeave:()=>v(!1),onClick:()=>t(e.shortsId),style:Object.assign({width:r,aspectRatio:u},i&&{borderRadius:"10px"}),className:`cursor-pointer p-[3px] ${i&&"rounded-xl"} ${f&&"bg-insta"} relative overflow-hidden`},m&&c&&g.createElement(Xo,{playUrl:`${y}/direct/${e.media.objectId}`,poster:Gt(e.thumbPath)}),g.createElement("img",{style:Object.assign({},i&&{borderRadius:"10px"}),src:Gt(e.thumbPath),alt:"thumbnail",className:`w-full h-full object-cover ${i&&"rounded-xl"}`}),d&&(null===(h=e.productsInfo)||void 0===h?void 0:h.length)>0&&!(c&&m)&&g.createElement("div",{className:"absolute pointer-events-none flex items-center justify-center z-20",style:{left:2,right:2,bottom:10,height:"20%"}},g.createElement("div",{className:"h-full inline-block",style:{width:"95%"}},g.createElement(qo,{product:e.productsInfo[0],maxWidth:"100%",height:"100%",cardWidth:r})))),n&&!(c&&m&&a===V.INNER)&&g.createElement("p",{style:Object.assign({width:r,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},a===V.INNER&&d?{bottom:"22%"}:{}),className:`my-2 ${a===V.INNER?"absolute bottom-0 left-0 text-white px-2 z-10":""} text-[12px] cursor-default truncate`},e.title),o&&g.createElement(Yo,{setSelectedProducts:l,products:e.productsInfo,iconSize:r,contentId:e.shortsId}))},Zo=e=>{const{iconShape:t,collection:r}=e;return t===j.MANY?g.createElement(Jo,Object.assign({},e)):g.createElement(el,Object.assign({},e,{shortform:r.contents[0]}))},Jo=e=>{const{collection:t}=e,{thumbnailAutoPlay:r}=e,{setCollection:n,nextKey:i,setNextKey:s,isFetching:a,setIsFetching:o}=fr();return g.createElement(_n,{freeMode:!0,slidesPerView:"auto",spaceBetween:12,onReachEnd:()=>J(void 0,void 0,void 0,function*(){var e,r,l;if(t&&!(a||(null!==(e=t.count)&&void 0!==e?e:Number.MAX_SAFE_INTEGER)<=t.contents.length)){o(!0);try{const e=yield tr({collectionId:t.colId,nextKey:i});if(!e||!(null===(r=e.contents)||void 0===r?void 0:r.length))return;s((null===(l=e.contents.at(-1))||void 0===l?void 0:l.shortsId)||"");const a=new Set(t.contents.map(e=>e.shortsId)),o=e.contents.filter(e=>!a.has(e.shortsId));if(!o.length)return;n(Object.assign(Object.assign({},t),{contents:[...t.contents,...o]}))}catch(e){console.error(e)}finally{o(!1)}}}),modules:r?[_o]:[],autoplay:!!r&&{delay:3e3,disableOnInteraction:!1,pauseOnMouseEnter:!0},loop:r||void 0},null==t?void 0:t.contents.map(t=>g.createElement(Mn,{key:t.shortsId,className:"!w-auto"},g.createElement(el,Object.assign({},e,{shortform:t})))))},el=e=>{const{iconForm:t}=e;return t===z.INSTA?g.createElement(Vo,Object.assign({},e)):g.createElement(Qo,Object.assign({},e))};function tl(e,t,{checkForDefaultPrevented:r=!0}={}){return function(n){if(e?.(n),!1===r||!n.defaultPrevented)return t?.(n)}}function rl(e,t){if("function"==typeof e)return e(t);null!=e&&(e.current=t)}function nl(...e){return t=>{let r=!1;const n=e.map(e=>{const n=rl(e,t);return r||"function"!=typeof n||(r=!0),n});if(r)return()=>{for(let t=0;t<n.length;t++){const r=n[t];"function"==typeof r?r():rl(e[t],null)}}}}function il(...e){return p.useCallback(nl(...e),e)}function sl(...e){const t=e[0];if(1===e.length)return t;const r=()=>{const r=e.map(e=>({useScope:e(),scopeName:e.scopeName}));return function(e){const n=r.reduce((t,{useScope:r,scopeName:n})=>({...t,...r(e)[`__scope${n}`]}),{});return p.useMemo(()=>({[`__scope${t.scopeName}`]:n}),[n])}};return r.scopeName=t.scopeName,r}var al=globalThis?.document?p.useLayoutEffect:()=>{},ol=m[" useId ".trim().toString()]||(()=>{}),ll=0;function ul(e){const[t,r]=p.useState(ol());return al(()=>{e||r(e=>e??String(ll++))},[e]),e||(t?`radix-${t}`:"")}var cl=m[" useInsertionEffect ".trim().toString()]||al;function dl({prop:e,defaultProp:t,onChange:r=()=>{},caller:n}){const[i,s,a]=function({defaultProp:e,onChange:t}){const[r,n]=p.useState(e),i=p.useRef(r),s=p.useRef(t);return cl(()=>{s.current=t},[t]),p.useEffect(()=>{i.current!==r&&(s.current?.(r),i.current=r)},[r,i]),[r,n,s]}({defaultProp:t,onChange:r}),o=void 0!==e,l=o?e:i;{const t=p.useRef(void 0!==e);p.useEffect(()=>{const e=t.current;if(e!==o){const t=e?"controlled":"uncontrolled",r=o?"controlled":"uncontrolled";console.warn(`${n} is changing from ${t} to ${r}. 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.`)}t.current=o},[o,n])}const u=p.useCallback(t=>{if(o){const r=function(e){return"function"==typeof e}(t)?t(e):t;r!==e&&a.current?.(r)}else s(t)},[o,e,s,a]);return[l,u]}function hl(e,t,{checkForDefaultPrevented:r=!0}={}){return function(n){if(e?.(n),!1===r||!n.defaultPrevented)return t?.(n)}}function fl(e,t){if("function"==typeof e)return e(t);null!=e&&(e.current=t)}function pl(...e){return t=>{let r=!1;const n=e.map(e=>{const n=fl(e,t);return r||"function"!=typeof n||(r=!0),n});if(r)return()=>{for(let t=0;t<n.length;t++){const r=n[t];"function"==typeof r?r():fl(e[t],null)}}}}function gl(...e){return p.useCallback(pl(...e),e)}function ml(e){const t=p.forwardRef((e,t)=>{const{children:r,...n}=e;if(p.isValidElement(r)){const e=function(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;if(r)return e.ref;if(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r)return e.props.ref;return e.props.ref||e.ref}(r),i=function(e,t){const r={...t};for(const n in t){const i=e[n],s=t[n];/^on[A-Z]/.test(n)?i&&s?r[n]=(...e)=>{const t=s(...e);return i(...e),t}:i&&(r[n]=i):"style"===n?r[n]={...i,...s}:"className"===n&&(r[n]=[i,s].filter(Boolean).join(" "))}return{...e,...r}}(n,r.props);return r.type!==p.Fragment&&(i.ref=t?pl(t,e):e),p.cloneElement(r,i)}return p.Children.count(r)>1?p.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var vl=Symbol("radix.slottable");function yl(e){return p.isValidElement(e)&&"function"==typeof e.type&&"__radixId"in e.type&&e.type.__radixId===vl}var bl=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,t)=>{const r=function(e){const t=ml(e),r=p.forwardRef((e,r)=>{const{children:n,...i}=e,s=p.Children.toArray(n),a=s.find(yl);if(a){const e=a.props.children,n=s.map(t=>t===a?p.Children.count(e)>1?p.Children.only(null):p.isValidElement(e)?e.props.children:null:t);return Ti.jsx(t,{...i,ref:r,children:p.isValidElement(e)?p.cloneElement(e,void 0,n):null})}return Ti.jsx(t,{...i,ref:r,children:n})});return r.displayName=`${e}.Slot`,r}(`Primitive.${t}`),n=p.forwardRef((e,n)=>{const{asChild:i,...s}=e,a=i?r:t;return"undefined"!=typeof window&&(window[Symbol.for("radix-ui")]=!0),Ti.jsx(a,{...s,ref:n})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});var wl,El="dismissableLayer.update",Sl="dismissableLayer.pointerDownOutside",Tl="dismissableLayer.focusOutside",xl=p.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),kl=p.forwardRef((e,t)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:n,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:a,onDismiss:o,...l}=e,u=p.useContext(xl),[c,d]=p.useState(null),h=c?.ownerDocument??globalThis?.document,[,f]=p.useState({}),g=gl(t,e=>d(e)),m=Array.from(u.layers),[v]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),y=m.indexOf(v),b=c?m.indexOf(c):-1,w=u.layersWithOutsidePointerEventsDisabled.size>0,E=b>=y,S=function(e,t=globalThis?.document){const r=$i(e),n=p.useRef(!1),i=p.useRef(()=>{});return p.useEffect(()=>{const e=e=>{if(e.target&&!n.current){let n=function(){Rl(Sl,r,s,{discrete:!0})};const s={originalEvent:e};"touch"===e.pointerType?(t.removeEventListener("click",i.current),i.current=n,t.addEventListener("click",i.current,{once:!0})):n()}else t.removeEventListener("click",i.current);n.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",e)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",e),t.removeEventListener("click",i.current)}},[t,r]),{onPointerDownCapture:()=>n.current=!0}}(e=>{const t=e.target,r=[...u.branches].some(e=>e.contains(t));E&&!r&&(i?.(e),a?.(e),e.defaultPrevented||o?.())},h),T=function(e,t=globalThis?.document){const r=$i(e),n=p.useRef(!1);return p.useEffect(()=>{const e=e=>{if(e.target&&!n.current){Rl(Tl,r,{originalEvent:e},{discrete:!1})}};return t.addEventListener("focusin",e),()=>t.removeEventListener("focusin",e)},[t,r]),{onFocusCapture:()=>n.current=!0,onBlurCapture:()=>n.current=!1}}(e=>{const t=e.target;[...u.branches].some(e=>e.contains(t))||(s?.(e),a?.(e),e.defaultPrevented||o?.())},h);return Bi(e=>{b===u.layers.size-1&&(n?.(e),!e.defaultPrevented&&o&&(e.preventDefault(),o()))},h),p.useEffect(()=>{if(c)return r&&(0===u.layersWithOutsidePointerEventsDisabled.size&&(wl=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(c)),u.layers.add(c),Al(),()=>{r&&1===u.layersWithOutsidePointerEventsDisabled.size&&(h.body.style.pointerEvents=wl)}},[c,h,r,u]),p.useEffect(()=>()=>{c&&(u.layers.delete(c),u.layersWithOutsidePointerEventsDisabled.delete(c),Al())},[c,u]),p.useEffect(()=>{const e=()=>f({});return document.addEventListener(El,e),()=>document.removeEventListener(El,e)},[]),Ti.jsx(bl.div,{...l,ref:g,style:{pointerEvents:w?E?"auto":"none":void 0,...e.style},onFocusCapture:hl(e.onFocusCapture,T.onFocusCapture),onBlurCapture:hl(e.onBlurCapture,T.onBlurCapture),onPointerDownCapture:hl(e.onPointerDownCapture,S.onPointerDownCapture)})});kl.displayName="DismissableLayer";function Al(){const e=new CustomEvent(El);document.dispatchEvent(e)}function Rl(e,t,r,{discrete:n}){const i=r.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:r});t&&i.addEventListener(e,t,{once:!0}),n?function(e,t){e&&Pi.flushSync(()=>e.dispatchEvent(t))}(i,s):i.dispatchEvent(s)}p.forwardRef((e,t)=>{const r=p.useContext(xl),n=p.useRef(null),i=gl(t,n);return p.useEffect(()=>{const e=n.current;if(e)return r.branches.add(e),()=>{r.branches.delete(e)}},[r.branches]),Ti.jsx(bl.div,{...e,ref:i})}).displayName="DismissableLayerBranch";var Ll=e=>{const{present:t,children:r}=e,n=function(e){const[t,r]=p.useState(),n=p.useRef(null),i=p.useRef(e),s=p.useRef("none"),a=e?"mounted":"unmounted",[o,l]=function(e,t){return p.useReducer((e,r)=>t[e][r]??e,e)}(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return p.useEffect(()=>{const e=Il(n.current);s.current="mounted"===o?e:"none"},[o]),al(()=>{const t=n.current,r=i.current;if(r!==e){const n=s.current,a=Il(t);if(e)l("MOUNT");else if("none"===a||"none"===t?.display)l("UNMOUNT");else{l(r&&n!==a?"ANIMATION_OUT":"UNMOUNT")}i.current=e}},[e,l]),al(()=>{if(t){let e;const r=t.ownerDocument.defaultView??window,a=s=>{const a=Il(n.current).includes(s.animationName);if(s.target===t&&a&&(l("ANIMATION_END"),!i.current)){const n=t.style.animationFillMode;t.style.animationFillMode="forwards",e=r.setTimeout(()=>{"forwards"===t.style.animationFillMode&&(t.style.animationFillMode=n)})}},o=e=>{e.target===t&&(s.current=Il(n.current))};return t.addEventListener("animationstart",o),t.addEventListener("animationcancel",a),t.addEventListener("animationend",a),()=>{r.clearTimeout(e),t.removeEventListener("animationstart",o),t.removeEventListener("animationcancel",a),t.removeEventListener("animationend",a)}}l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(o),ref:p.useCallback(e=>{n.current=e?getComputedStyle(e):null,r(e)},[])}}(t),i="function"==typeof r?r({present:n.isPresent}):p.Children.only(r),s=il(n.ref,function(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;if(r)return e.ref;if(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r)return e.props.ref;return e.props.ref||e.ref}(i));return"function"==typeof r||n.isPresent?p.cloneElement(i,{ref:s}):null};function Il(e){return e?.animationName||"none"}function Cl(e){const t=Pl(e),r=p.forwardRef((e,r)=>{const{children:n,...i}=e,s=p.Children.toArray(n),a=s.find(_l);if(a){const e=a.props.children,n=s.map(t=>t===a?p.Children.count(e)>1?p.Children.only(null):p.isValidElement(e)?e.props.children:null:t);return Ti.jsx(t,{...i,ref:r,children:p.isValidElement(e)?p.cloneElement(e,void 0,n):null})}return Ti.jsx(t,{...i,ref:r,children:n})});return r.displayName=`${e}.Slot`,r}function Pl(e){const t=p.forwardRef((e,t)=>{const{children:r,...n}=e;if(p.isValidElement(r)){const e=function(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;if(r)return e.ref;if(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r)return e.props.ref;return e.props.ref||e.ref}(r),i=function(e,t){const r={...t};for(const n in t){const i=e[n],s=t[n];/^on[A-Z]/.test(n)?i&&s?r[n]=(...e)=>{const t=s(...e);return i(...e),t}:i&&(r[n]=i):"style"===n?r[n]={...i,...s}:"className"===n&&(r[n]=[i,s].filter(Boolean).join(" "))}return{...e,...r}}(n,r.props);return r.type!==p.Fragment&&(i.ref=t?nl(t,e):e),p.cloneElement(r,i)}return p.Children.count(r)>1?p.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}Ll.displayName="Presence";var Dl=Symbol("radix.slottable");function _l(e){return p.isValidElement(e)&&"function"==typeof e.type&&"__radixId"in e.type&&e.type.__radixId===Dl}var Ml=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,t)=>{const r=Cl(`Primitive.${t}`),n=p.forwardRef((e,n)=>{const{asChild:i,...s}=e,a=i?r:t;return"undefined"!=typeof window&&(window[Symbol.for("radix-ui")]=!0),Ti.jsx(a,{...s,ref:n})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{}),Ol=0;function Nl(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Fl="Dialog",[$l,Bl]=function(e,t=[]){let r=[];const n=()=>{const t=r.map(e=>p.createContext(e));return function(r){const n=r?.[e]||t;return p.useMemo(()=>({[`__scope${e}`]:{...r,[e]:n}}),[r,n])}};return n.scopeName=e,[function(t,n){const i=p.createContext(n),s=r.length;r=[...r,n];const a=t=>{const{scope:r,children:n,...a}=t,o=r?.[e]?.[s]||i,l=p.useMemo(()=>a,Object.values(a));return Ti.jsx(o.Provider,{value:l,children:n})};return a.displayName=t+"Provider",[a,function(r,a){const o=a?.[e]?.[s]||i,l=p.useContext(o);if(l)return l;if(void 0!==n)return n;throw new Error(`\`${r}\` must be used within \`${t}\``)}]},sl(n,...t)]}(Fl),[Ul,zl]=$l(Fl),jl=e=>{const{__scopeDialog:t,children:r,open:n,defaultOpen:i,onOpenChange:s,modal:a=!0}=e,o=p.useRef(null),l=p.useRef(null),[u,c]=dl({prop:n,defaultProp:i??!1,onChange:s,caller:Fl});return Ti.jsx(Ul,{scope:t,triggerRef:o,contentRef:l,contentId:ul(),titleId:ul(),descriptionId:ul(),open:u,onOpenChange:c,onOpenToggle:p.useCallback(()=>c(e=>!e),[c]),modal:a,children:r})};jl.displayName=Fl;var Gl="DialogTrigger";p.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,i=zl(Gl,r),s=il(t,i.triggerRef);return Ti.jsx(Ml.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":uu(i.open),...n,ref:s,onClick:tl(e.onClick,i.onOpenToggle)})}).displayName=Gl;var Hl="DialogPortal",[Vl,Wl]=$l(Hl,{forceMount:void 0}),Kl=e=>{const{__scopeDialog:t,forceMount:r,children:n,container:i}=e,s=zl(Hl,t);return Ti.jsx(Vl,{scope:t,forceMount:r,children:p.Children.map(n,e=>Ti.jsx(Ll,{present:r||s.open,children:Ti.jsx(is,{asChild:!0,container:i,children:e})}))})};Kl.displayName=Hl;var Yl="DialogOverlay",ql=p.forwardRef((e,t)=>{const r=Wl(Yl,e.__scopeDialog),{forceMount:n=r.forceMount,...i}=e,s=zl(Yl,e.__scopeDialog);return s.modal?Ti.jsx(Ll,{present:n||s.open,children:Ti.jsx(Ql,{...i,ref:t})}):null});ql.displayName=Yl;var Xl=Cl("DialogOverlay.RemoveScroll"),Ql=p.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,i=zl(Yl,r);return Ti.jsx(Ks,{as:Xl,allowPinchZoom:!0,shards:[i.contentRef],children:Ti.jsx(Ml.div,{"data-state":uu(i.open),...n,ref:t,style:{pointerEvents:"auto",...n.style}})})}),Zl="DialogContent",Jl=p.forwardRef((e,t)=>{const r=Wl(Zl,e.__scopeDialog),{forceMount:n=r.forceMount,...i}=e,s=zl(Zl,e.__scopeDialog);return Ti.jsx(Ll,{present:n||s.open,children:s.modal?Ti.jsx(eu,{...i,ref:t}):Ti.jsx(tu,{...i,ref:t})})});Jl.displayName=Zl;var eu=p.forwardRef((e,t)=>{const r=zl(Zl,e.__scopeDialog),n=p.useRef(null),i=il(t,r.contentRef,n);return p.useEffect(()=>{const e=n.current;if(e)return ea(e)},[]),Ti.jsx(ru,{...e,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:tl(e.onCloseAutoFocus,e=>{e.preventDefault(),r.triggerRef.current?.focus()}),onPointerDownOutside:tl(e.onPointerDownOutside,e=>{const t=e.detail.originalEvent,r=0===t.button&&!0===t.ctrlKey;(2===t.button||r)&&e.preventDefault()}),onFocusOutside:tl(e.onFocusOutside,e=>e.preventDefault())})}),tu=p.forwardRef((e,t)=>{const r=zl(Zl,e.__scopeDialog),n=p.useRef(!1),i=p.useRef(!1);return Ti.jsx(ru,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:t=>{e.onCloseAutoFocus?.(t),t.defaultPrevented||(n.current||r.triggerRef.current?.focus(),t.preventDefault()),n.current=!1,i.current=!1},onInteractOutside:t=>{e.onInteractOutside?.(t),t.defaultPrevented||(n.current=!0,"pointerdown"===t.detail.originalEvent.type&&(i.current=!0));const s=t.target,a=r.triggerRef.current?.contains(s);a&&t.preventDefault(),"focusin"===t.detail.originalEvent.type&&i.current&&t.preventDefault()}})}),ru=p.forwardRef((e,t)=>{const{__scopeDialog:r,trapFocus:n,onOpenAutoFocus:i,onCloseAutoFocus:s,...a}=e,o=zl(Zl,r),l=p.useRef(null),u=il(t,l);return p.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Nl()),document.body.insertAdjacentElement("beforeend",e[1]??Nl()),Ol++,()=>{1===Ol&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),Ol--}},[]),Ti.jsxs(Ti.Fragment,{children:[Ti.jsx(Qi,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:i,onUnmountAutoFocus:s,children:Ti.jsx(kl,{role:"dialog",id:o.contentId,"aria-describedby":o.descriptionId,"aria-labelledby":o.titleId,"data-state":uu(o.open),...a,ref:u,onDismiss:()=>o.onOpenChange(!1)})}),Ti.jsxs(Ti.Fragment,{children:[Ti.jsx(fu,{titleId:o.titleId}),Ti.jsx(pu,{contentRef:l,descriptionId:o.descriptionId})]})]})}),nu="DialogTitle",iu=p.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,i=zl(nu,r);return Ti.jsx(Ml.h2,{id:i.titleId,...n,ref:t})});iu.displayName=nu;var su="DialogDescription",au=p.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,i=zl(su,r);return Ti.jsx(Ml.p,{id:i.descriptionId,...n,ref:t})});au.displayName=su;var ou="DialogClose",lu=p.forwardRef((e,t)=>{const{__scopeDialog:r,...n}=e,i=zl(ou,r);return Ti.jsx(Ml.button,{type:"button",...n,ref:t,onClick:tl(e.onClick,()=>i.onOpenChange(!1))})});function uu(e){return e?"open":"closed"}lu.displayName=ou;var cu="DialogTitleWarning",[du,hu]=function(e,t){const r=p.createContext(t),n=e=>{const{children:t,...n}=e,i=p.useMemo(()=>n,Object.values(n));return Ti.jsx(r.Provider,{value:i,children:t})};return n.displayName=e+"Provider",[n,function(n){const i=p.useContext(r);if(i)return i;if(void 0!==t)return t;throw new Error(`\`${n}\` must be used within \`${e}\``)}]}(cu,{contentName:Zl,titleName:nu,docsSlug:"dialog"}),fu=({titleId:e})=>{const t=hu(cu),r=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.\n\nIf you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.\n\nFor more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return p.useEffect(()=>{if(e){document.getElementById(e)||console.error(r)}},[r,e]),null},pu=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${hu("DialogDescriptionWarning").contentName}}.`;return p.useEffect(()=>{const n=e.current?.getAttribute("aria-describedby");if(t&&n){document.getElementById(t)||console.warn(r)}},[r,e,t]),null},gu=jl,mu=Kl,vu=ql,yu=Jl,bu=iu,wu=lu;function Eu(e){return p.createElement(gu,Object.assign({"data-slot":"dialog"},e))}function Su(e){var t=Z(e,[]);return p.createElement(mu,Object.assign({"data-slot":"dialog-portal"},t))}function Tu(e){var{className:t}=e,r=Z(e,["className"]);return p.createElement(vu,Object.assign({"data-slot":"dialog-overlay",className:Ot("fixed inset-0 z-50 bg-black/50",t)},r))}function xu(e){var{className:t,children:r,showCloseButton:n=!0,container:i}=e,s=Z(e,["className","children","showCloseButton","container"]);return p.createElement(Su,{"data-slot":"dialog-portal",container:i},p.createElement(Tu,null),p.createElement(yu,Object.assign({"data-slot":"dialog-content",style:{left:"50%",top:"50%",transform:"translate(-50%, -50%)",outline:"none"},className:Ot("fixed","z-50 grid w-full max-w-lg sm:mx-0 gap-4 p-6",t)},s),r,n&&p.createElement(wu,{"data-slot":"dialog-close",style:{right:"calc(var(--spacing) * 4)",top:"calc(var(--spacing) * 4)",outline:"none"},className:Ot("absolute right-4 top-4 rounded opacity-70 transition-opacity","hover:opacity-100 focus:outline-none","focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:ring-offset-background","disabled:pointer-events-none"),"aria-label":"Close"},p.createElement(ai,{className:"h-4 w-4 pointer-events-none shrink-0",style:{height:"calc(var(--spacing) * 4)",width:"calc(var(--spacing) * 4)"}}))))}function ku(e){var{className:t}=e,r=Z(e,["className"]);return p.createElement("div",Object.assign({"data-slot":"dialog-header",className:Ot("flex flex-col gap-2 text-left",t)},r))}function Au(e){var{className:t}=e,r=Z(e,["className"]);return p.createElement(bu,Object.assign({"data-slot":"dialog-title",className:Ot("text-lg leading-none font-semibold",t)},r))}function Ru({title:e,children:t,contentClassName:r,hideCloseButton:n=!1,portalContainer:i,description:s}){const{open:a,setOpen:o}=Wo();return g.createElement(Eu,{open:a,onOpenChange:o},g.createElement(xu,{container:i,className:r,showCloseButton:!n},e&&g.createElement(ku,null,g.createElement(Au,{style:{color:"#494949"}},e||""),g.createElement(au,{style:{color:"#5e5e5e",fontSize:"12.5px"}},s||"")),t))}const Lu=({products:e,contentId:t})=>{const r=On().width<430||Hn.isMobile;return g.createElement("div",{onWheel:e=>e.stopPropagation(),onTouchMove:e=>e.stopPropagation(),className:"grid gap-2 "+(r?"grid-cols-1":"grid-cols-2"),style:{fontSize:13}},e.map(r=>g.createElement(Ko,{key:r.productId,product:r,hideMoreBadge:!0,productLength:e.length,contentId:t})))},Iu=({widgetPlayerOption:e,setCollectionUuid:t,portalContainer:r})=>{const{PLAYER_BASE_URL:n}=Mt(),{player:i}=e,[s,a]=p.useState(null),{collection:o}=fr(),{isPreview:l}=cr(),{onSlideChange:u,onCollectionClose:c}=pr(s,a),{setOpen:d,open:h}=Wo();p.useEffect(()=>{h||(s&&(c(),a(null)),f&&m(null))},[h]);const[f,m]=p.useState();return g.createElement(g.Fragment,null,o&&g.createElement(Zo,Object.assign({collection:o},e,{onThumbnailClick:e=>J(void 0,void 0,void 0,function*(){if(i===H.POPUP){const r=Ut(),n=Ut();if(t(n),a(Object.assign(Object.assign({},o.contents.find(t=>t.shortsId===e)),{uuid:r})),d(!0),l)return;const i=yield Promise.allSettled([Xt({contentId:o.colId,uuid:n,type:X.COLLECTION,userId:o.userId,isFirstPlay:!zt(o.colId)}),Xt({contentId:e,uuid:r,type:X.SHORTS,userId:o.userId,isFirstPlay:!zt(e)})]);for(const e of i)"rejected"===e.status&&console.error("Error joining statistics:",e.reason)}else{const t=(e=>{switch(e){case H.HORIZONTAL:return W.HORIZONTAL;case H.VERTICAL:return W.VERTICAL;case H.GRID:return W.PRODUCTS;case H.TABLET:return W.TABLET;default:return W.PLATFORM}})(i),r=null==o?void 0:o.contents.findIndex(t=>t.shortsId===e);let s="";r&&(s=(null==o?void 0:o.contents[r-1].shortsId)||"");const a=new URLSearchParams(Object.assign(Object.assign({},s&&{nextKey:s}),{layout:String(t)}));open(`${n}/collection/${o.colId}?${a.toString()}`)}}),setSelectedProducts:m})),f&&g.createElement(Ru,{portalContainer:r,title:"상품 목록",contentClassName:"bg-white rounded p-4 product-dialog-container",description:"상품 정보를 확인해 보세요"},g.createElement(Lu,{products:f.productsInfo,contentId:f.shortsId})),o&&s&&g.createElement(Ru,{portalContainer:r,hideCloseButton:!0,contentClassName:"w-full max-w-none p-0 mx-0"},g.createElement(Ho,{collection:o,initialShortsId:s.shortsId,onClosePlayer:()=>J(void 0,void 0,void 0,function*(){c(),d(!1)}),onSlideChange:u})))};var Cu,Pu={},Du={};function _u(){if(Cu)return Du;Cu=1;var e=l();function t(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r<arguments.length;r++)t+="&args[]="+encodeURIComponent(arguments[r]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var r=Object.prototype.hasOwnProperty,n=/^[: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]*$/,i={},s={};function a(e){return!!r.call(s,e)||!r.call(i,e)&&(n.test(e)?s[e]=!0:(i[e]=!0,!1))}function o(e,t,r,n,i,s,a){this.acceptsBooleans=2===t||3===t||4===t,this.attributeName=n,this.attributeNamespace=i,this.mustUseProperty=r,this.propertyName=e,this.type=t,this.sanitizeURL=s,this.removeEmptyString=a}var u={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){u[e]=new o(e,0,!1,e,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];u[t]=new o(t,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){u[e]=new o(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){u[e]=new o(e,2,!1,e,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){u[e]=new o(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){u[e]=new o(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){u[e]=new o(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){u[e]=new o(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){u[e]=new o(e,5,!1,e.toLowerCase(),null,!1,!1)});var c=/[\-:]([a-z])/g;function d(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(c,d);u[t]=new o(t,1,!1,e,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(c,d);u[t]=new o(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(c,d);u[t]=new o(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){u[e]=new o(e,1,!1,e.toLowerCase(),null,!1,!1)}),u.xlinkHref=new o("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){u[e]=new o(e,1,!1,e.toLowerCase(),null,!0,!0)});var h={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},f=["Webkit","ms","Moz","O"];Object.keys(h).forEach(function(e){f.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),h[t]=h[e]})});var p=/["'&<>]/;function g(e){if("boolean"==typeof e||"number"==typeof e)return""+e;e=""+e;var t=p.exec(e);if(t){var r,n="",i=0;for(r=t.index;r<e.length;r++){switch(e.charCodeAt(r)){case 34:t=""";break;case 38:t="&";break;case 39:t="'";break;case 60:t="<";break;case 62:t=">";break;default:continue}i!==r&&(n+=e.substring(i,r)),i=r+1,n+=t}e=i!==r?n+e.substring(i,r):n}return e}var m=/([A-Z])/g,v=/^ms-/,y=Array.isArray;function b(e,t){return{insertionMode:e,selectedValue:t}}var w=new Map;function E(e,n,i){if("object"!=typeof i)throw Error(t(62));for(var s in n=!0,i)if(r.call(i,s)){var a=i[s];if(null!=a&&"boolean"!=typeof a&&""!==a){if(0===s.indexOf("--")){var o=g(s);a=g((""+a).trim())}else{o=s;var l=w.get(o);void 0!==l||(l=g(o.replace(m,"-$1").toLowerCase().replace(v,"-ms-")),w.set(o,l)),o=l,a="number"==typeof a?0===a||r.call(h,s)?""+a:a+"px":g((""+a).trim())}n?(n=!1,e.push(' style="',o,":",a)):e.push(";",o,":",a)}}n||e.push('"')}function S(e,t,r,n){switch(r){case"style":return void E(e,t,n);case"defaultValue":case"defaultChecked":case"innerHTML":case"suppressContentEditableWarning":case"suppressHydrationWarning":return}if(!(2<r.length)||"o"!==r[0]&&"O"!==r[0]||"n"!==r[1]&&"N"!==r[1])if(null!==(t=u.hasOwnProperty(r)?u[r]:null)){switch(typeof n){case"function":case"symbol":return;case"boolean":if(!t.acceptsBooleans)return}switch(r=t.attributeName,t.type){case 3:n&&e.push(" ",r,'=""');break;case 4:!0===n?e.push(" ",r,'=""'):!1!==n&&e.push(" ",r,'="',g(n),'"');break;case 5:isNaN(n)||e.push(" ",r,'="',g(n),'"');break;case 6:!isNaN(n)&&1<=n&&e.push(" ",r,'="',g(n),'"');break;default:t.sanitizeURL&&(n=""+n),e.push(" ",r,'="',g(n),'"')}}else if(a(r)){switch(typeof n){case"function":case"symbol":return;case"boolean":if("data-"!==(t=r.toLowerCase().slice(0,5))&&"aria-"!==t)return}e.push(" ",r,'="',g(n),'"')}}function T(e,r,n){if(null!=r){if(null!=n)throw Error(t(60));if("object"!=typeof r||!("__html"in r))throw Error(t(61));null!=(r=r.__html)&&e.push(""+r)}}function x(e,t,n,i){e.push(R(n));var s,a=n=null;for(s in t)if(r.call(t,s)){var o=t[s];if(null!=o)switch(s){case"children":n=o;break;case"dangerouslySetInnerHTML":a=o;break;default:S(e,i,s,o)}}return e.push(">"),T(e,a,n),"string"==typeof n?(e.push(g(n)),null):n}var k=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,A=new Map;function R(e){var r=A.get(e);if(void 0===r){if(!k.test(e))throw Error(t(65,e));r="<"+e,A.set(e,r)}return r}function L(n,i,s,o,l){switch(i){case"select":n.push(R("select"));var u=null,c=null;for(p in s)if(r.call(s,p)){var d=s[p];if(null!=d)switch(p){case"children":u=d;break;case"dangerouslySetInnerHTML":c=d;break;case"defaultValue":case"value":break;default:S(n,o,p,d)}}return n.push(">"),T(n,c,u),u;case"option":c=l.selectedValue,n.push(R("option"));var h=d=null,f=null,p=null;for(u in s)if(r.call(s,u)){var m=s[u];if(null!=m)switch(u){case"children":d=m;break;case"selected":f=m;break;case"dangerouslySetInnerHTML":p=m;break;case"value":h=m;default:S(n,o,u,m)}}if(null!=c)if(s=null!==h?""+h:function(t){var r="";return e.Children.forEach(t,function(e){null!=e&&(r+=e)}),r}(d),y(c)){for(o=0;o<c.length;o++)if(""+c[o]===s){n.push(' selected=""');break}}else""+c===s&&n.push(' selected=""');else f&&n.push(' selected=""');return n.push(">"),T(n,p,d),d;case"textarea":for(d in n.push(R("textarea")),p=c=u=null,s)if(r.call(s,d)&&null!=(h=s[d]))switch(d){case"children":p=h;break;case"value":u=h;break;case"defaultValue":c=h;break;case"dangerouslySetInnerHTML":throw Error(t(91));default:S(n,o,d,h)}if(null===u&&null!==c&&(u=c),n.push(">"),null!=p){if(null!=u)throw Error(t(92));if(y(p)&&1<p.length)throw Error(t(93));u=""+p}return"string"==typeof u&&"\n"===u[0]&&n.push("\n"),null!==u&&n.push(g(""+u)),null;case"input":for(c in n.push(R("input")),h=p=d=u=null,s)if(r.call(s,c)&&null!=(f=s[c]))switch(c){case"children":case"dangerouslySetInnerHTML":throw Error(t(399,"input"));case"defaultChecked":h=f;break;case"defaultValue":d=f;break;case"checked":p=f;break;case"value":u=f;break;default:S(n,o,c,f)}return null!==p?S(n,o,"checked",p):null!==h&&S(n,o,"checked",h),null!==u?S(n,o,"value",u):null!==d&&S(n,o,"value",d),n.push("/>"),null;case"menuitem":for(var v in n.push(R("menuitem")),s)if(r.call(s,v)&&null!=(u=s[v]))switch(v){case"children":case"dangerouslySetInnerHTML":throw Error(t(400));default:S(n,o,v,u)}return n.push(">"),null;case"title":for(m in n.push(R("title")),u=null,s)if(r.call(s,m)&&null!=(c=s[m]))switch(m){case"children":u=c;break;case"dangerouslySetInnerHTML":throw Error(t(434));default:S(n,o,m,c)}return n.push(">"),u;case"listing":case"pre":for(h in n.push(R(i)),c=u=null,s)if(r.call(s,h)&&null!=(d=s[h]))switch(h){case"children":u=d;break;case"dangerouslySetInnerHTML":c=d;break;default:S(n,o,h,d)}if(n.push(">"),null!=c){if(null!=u)throw Error(t(60));if("object"!=typeof c||!("__html"in c))throw Error(t(61));null!=(s=c.__html)&&("string"==typeof s&&0<s.length&&"\n"===s[0]?n.push("\n",s):n.push(""+s))}return"string"==typeof u&&"\n"===u[0]&&n.push("\n"),u;case"area":case"base":case"br":case"col":case"embed":case"hr":case"img":case"keygen":case"link":case"meta":case"param":case"source":case"track":case"wbr":for(var b in n.push(R(i)),s)if(r.call(s,b)&&null!=(u=s[b]))switch(b){case"children":case"dangerouslySetInnerHTML":throw Error(t(399,i));default:S(n,o,b,u)}return n.push("/>"),null;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 x(n,s,i,o);case"html":return 0===l.insertionMode&&n.push("<!DOCTYPE html>"),x(n,s,i,o);default:if(-1===i.indexOf("-")&&"string"!=typeof s.is)return x(n,s,i,o);for(f in n.push(R(i)),c=u=null,s)if(r.call(s,f)&&null!=(d=s[f]))switch(f){case"children":u=d;break;case"dangerouslySetInnerHTML":c=d;break;case"style":E(n,o,d);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":break;default:a(f)&&"function"!=typeof d&&"symbol"!=typeof d&&n.push(" ",f,'="',g(d),'"')}return n.push(">"),T(n,c,u),u}}function I(e,r,n){if(e.push('\x3c!--$?--\x3e<template id="'),null===n)throw Error(t(395));return e.push(n),e.push('"></template>')}var C=/[<\u2028\u2029]/g;function P(e){return JSON.stringify(e).replace(C,function(e){switch(e){case"<":return"\\u003c";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:throw Error("escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React")}})}function D(e,t,r,n){return r.generateStaticMarkup?(e.push(g(t)),!1):(""===t?e=n:(n&&e.push("\x3c!-- --\x3e"),e.push(g(t)),e=!0),e)}var _=Object.assign,M=Symbol.for("react.element"),O=Symbol.for("react.portal"),N=Symbol.for("react.fragment"),F=Symbol.for("react.strict_mode"),$=Symbol.for("react.profiler"),B=Symbol.for("react.provider"),U=Symbol.for("react.context"),z=Symbol.for("react.forward_ref"),j=Symbol.for("react.suspense"),G=Symbol.for("react.suspense_list"),H=Symbol.for("react.memo"),V=Symbol.for("react.lazy"),W=Symbol.for("react.scope"),K=Symbol.for("react.debug_trace_mode"),Y=Symbol.for("react.legacy_hidden"),q=Symbol.for("react.default_value"),X=Symbol.iterator;function Q(e){if(null==e)return null;if("function"==typeof e)return e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case N:return"Fragment";case O:return"Portal";case $:return"Profiler";case F:return"StrictMode";case j:return"Suspense";case G:return"SuspenseList"}if("object"==typeof e)switch(e.$$typeof){case U:return(e.displayName||"Context")+".Consumer";case B:return(e._context.displayName||"Context")+".Provider";case z:var t=e.render;return(e=e.displayName)||(e=""!==(e=t.displayName||t.name||"")?"ForwardRef("+e+")":"ForwardRef"),e;case H:return null!==(t=e.displayName||null)?t:Q(e.type)||"Memo";case V:t=e._payload,e=e._init;try{return Q(e(t))}catch(e){}}return null}var Z={};function J(e,t){if(!(e=e.contextTypes))return Z;var r,n={};for(r in e)n[r]=t[r];return n}var ee=null;function te(e,r){if(e!==r){e.context._currentValue2=e.parentValue,e=e.parent;var n=r.parent;if(null===e){if(null!==n)throw Error(t(401))}else{if(null===n)throw Error(t(401));te(e,n)}r.context._currentValue2=r.value}}function re(e){e.context._currentValue2=e.parentValue,null!==(e=e.parent)&&re(e)}function ne(e){var t=e.parent;null!==t&&ne(t),e.context._currentValue2=e.value}function ie(e,r){if(e.context._currentValue2=e.parentValue,null===(e=e.parent))throw Error(t(402));e.depth===r.depth?te(e,r):ie(e,r)}function se(e,r){var n=r.parent;if(null===n)throw Error(t(402));e.depth===n.depth?te(e,n):se(e,n),r.context._currentValue2=r.value}function ae(e){var t=ee;t!==e&&(null===t?ne(e):null===e?re(t):t.depth===e.depth?te(t,e):t.depth>e.depth?ie(t,e):se(t,e),ee=e)}var oe={isMounted:function(){return!1},enqueueSetState:function(e,t){null!==(e=e._reactInternals).queue&&e.queue.push(t)},enqueueReplaceState:function(e,t){(e=e._reactInternals).replace=!0,e.queue=[t]},enqueueForceUpdate:function(){}};function le(e,t,r,n){var i=void 0!==e.state?e.state:null;e.updater=oe,e.props=r,e.state=i;var s={queue:[],replace:!1};e._reactInternals=s;var a=t.contextType;if(e.context="object"==typeof a&&null!==a?a._currentValue2:n,"function"==typeof(a=t.getDerivedStateFromProps)&&(i=null==(a=a(r,i))?i:_({},i,a),e.state=i),"function"!=typeof t.getDerivedStateFromProps&&"function"!=typeof e.getSnapshotBeforeUpdate&&("function"==typeof e.UNSAFE_componentWillMount||"function"==typeof e.componentWillMount))if(t=e.state,"function"==typeof e.componentWillMount&&e.componentWillMount(),"function"==typeof e.UNSAFE_componentWillMount&&e.UNSAFE_componentWillMount(),t!==e.state&&oe.enqueueReplaceState(e,e.state,null),null!==s.queue&&0<s.queue.length)if(t=s.queue,a=s.replace,s.queue=null,s.replace=!1,a&&1===t.length)e.state=t[0];else{for(s=a?t[0]:e.state,i=!0,a=a?1:0;a<t.length;a++){var o=t[a];null!=(o="function"==typeof o?o.call(e,s,r,n):o)&&(i?(i=!1,s=_({},s,o)):_(s,o))}e.state=s}else s.queue=null}var ue={id:1,overflow:""};function ce(e,t,r){var n=e.id;e=e.overflow;var i=32-de(n)-1;n&=~(1<<i),r+=1;var s=32-de(t)+i;if(30<s){var a=i-i%5;return s=(n&(1<<a)-1).toString(32),n>>=a,i-=a,{id:1<<32-de(t)+i|r<<i|n,overflow:s+e}}return{id:1<<s|r<<i|n,overflow:e}}var de=Math.clz32?Math.clz32:function(e){return e>>>=0,0===e?32:31-(he(e)/fe|0)|0},he=Math.log,fe=Math.LN2;var pe="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},ge=null,me=null,ve=null,ye=null,be=!1,we=!1,Ee=0,Se=null,Te=0;function xe(){if(null===ge)throw Error(t(321));return ge}function ke(){if(0<Te)throw Error(t(312));return{memoizedState:null,queue:null,next:null}}function Ae(){return null===ye?null===ve?(be=!1,ve=ye=ke()):(be=!0,ye=ve):null===ye.next?(be=!1,ye=ye.next=ke()):(be=!0,ye=ye.next),ye}function Re(){me=ge=null,we=!1,ve=null,Te=0,ye=Se=null}function Le(e,t){return"function"==typeof t?t(e):t}function Ie(e,t,r){if(ge=xe(),ye=Ae(),be){var n=ye.queue;if(t=n.dispatch,null!==Se&&void 0!==(r=Se.get(n))){Se.delete(n),n=ye.memoizedState;do{n=e(n,r.action),r=r.next}while(null!==r);return ye.memoizedState=n,[n,t]}return[ye.memoizedState,t]}return e=e===Le?"function"==typeof t?t():t:void 0!==r?r(t):t,ye.memoizedState=e,e=(e=ye.queue={last:null,dispatch:null}).dispatch=Pe.bind(null,ge,e),[ye.memoizedState,e]}function Ce(e,t){if(ge=xe(),t=void 0===t?null:t,null!==(ye=Ae())){var r=ye.memoizedState;if(null!==r&&null!==t){var n=r[1];e:if(null===n)n=!1;else{for(var i=0;i<n.length&&i<t.length;i++)if(!pe(t[i],n[i])){n=!1;break e}n=!0}if(n)return r[0]}}return e=e(),ye.memoizedState=[e,t],e}function Pe(e,r,n){if(25<=Te)throw Error(t(301));if(e===ge)if(we=!0,e={action:n,next:null},null===Se&&(Se=new Map),void 0===(n=Se.get(r)))Se.set(r,e);else{for(r=n;null!==r.next;)r=r.next;r.next=e}}function De(){throw Error(t(394))}function _e(){}var Me={readContext:function(e){return e._currentValue2},useContext:function(e){return xe(),e._currentValue2},useMemo:Ce,useReducer:Ie,useRef:function(e){ge=xe();var t=(ye=Ae()).memoizedState;return null===t?(e={current:e},ye.memoizedState=e):t},useState:function(e){return Ie(Le,e)},useInsertionEffect:_e,useLayoutEffect:function(){},useCallback:function(e,t){return Ce(function(){return e},t)},useImperativeHandle:_e,useEffect:_e,useDebugValue:_e,useDeferredValue:function(e){return xe(),e},useTransition:function(){return xe(),[!1,De]},useId:function(){var e=me.treeContext,r=e.overflow;e=((e=e.id)&~(1<<32-de(e)-1)).toString(32)+r;var n=Oe;if(null===n)throw Error(t(404));return r=Ee++,e=":"+n.idPrefix+"R"+e,0<r&&(e+="H"+r.toString(32)),e+":"},useMutableSource:function(e,t){return xe(),t(e._source)},useSyncExternalStore:function(e,r,n){if(void 0===n)throw Error(t(407));return n()}},Oe=null,Ne=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher;function Fe(e){return console.error(e),null}function $e(){}function Be(e,t,r,n,i,s,a,o){e.allPendingTasks++,null===r?e.pendingRootTasks++:r.pendingTasks++;var l={node:t,ping:function(){var t=e.pingedTasks;t.push(l),1===t.length&&et(e)},blockedBoundary:r,blockedSegment:n,abortSet:i,legacyContext:s,context:a,treeContext:o};return i.add(l),l}function Ue(e,t,r,n,i,s){return{status:0,id:-1,index:t,parentFlushed:!1,chunks:[],children:[],formatContext:n,boundary:r,lastPushedText:i,textEmbedded:s}}function ze(e,t){if(null!=(e=e.onError(t))&&"string"!=typeof e)throw Error('onError returned something with a type other than "string". onError should return a string and may return null or undefined but must not return anything else. It received something of type "'+typeof e+'" instead');return e}function je(e,t){var r=e.onShellError;r(t),(r=e.onFatalError)(t),null!==e.destination?(e.status=2,e.destination.destroy(t)):(e.status=1,e.fatalError=t)}function Ge(e,t,r,n,i){for(ge={},me=t,Ee=0,e=r(n,i);we;)we=!1,Ee=0,Te+=1,ye=null,e=r(n,i);return Re(),e}function He(e,r,n,i){var s=n.render(),a=i.childContextTypes;if(null!=a){var o=r.legacyContext;if("function"!=typeof n.getChildContext)i=o;else{for(var l in n=n.getChildContext())if(!(l in a))throw Error(t(108,Q(i)||"Unknown",l));i=_({},o,n)}r.legacyContext=i,Ke(e,r,s),r.legacyContext=o}else Ke(e,r,s)}function Ve(e,t){if(e&&e.defaultProps){for(var r in t=_({},t),e=e.defaultProps)void 0===t[r]&&(t[r]=e[r]);return t}return t}function We(e,r,n,i,s){if("function"==typeof n)if(n.prototype&&n.prototype.isReactComponent){s=J(n,r.legacyContext);var a=n.contextType;le(a=new n(i,"object"==typeof a&&null!==a?a._currentValue2:s),n,i,s),He(e,r,a,n)}else{s=Ge(e,r,n,i,a=J(n,r.legacyContext));var o=0!==Ee;if("object"==typeof s&&null!==s&&"function"==typeof s.render&&void 0===s.$$typeof)le(s,n,i,a),He(e,r,s,n);else if(o){i=r.treeContext,r.treeContext=ce(i,1,0);try{Ke(e,r,s)}finally{r.treeContext=i}}else Ke(e,r,s)}else{if("string"!=typeof n){switch(n){case Y:case K:case F:case $:case N:case G:return void Ke(e,r,i.children);case W:throw Error(t(343));case j:e:{n=r.blockedBoundary,s=r.blockedSegment,a=i.fallback,i=i.children;var l={id:null,rootSegmentID:-1,parentFlushed:!1,pendingTasks:0,forceClientRender:!1,completedSegments:[],byteSize:0,fallbackAbortableTasks:o=new Set,errorDigest:null},u=Ue(0,s.chunks.length,l,s.formatContext,!1,!1);s.children.push(u),s.lastPushedText=!1;var c=Ue(0,0,null,s.formatContext,!1,!1);c.parentFlushed=!0,r.blockedBoundary=l,r.blockedSegment=c;try{if(qe(e,r,i),e.responseState.generateStaticMarkup||c.lastPushedText&&c.textEmbedded&&c.chunks.push("\x3c!-- --\x3e"),c.status=1,Ze(l,c),0===l.pendingTasks)break e}catch(t){c.status=4,l.forceClientRender=!0,l.errorDigest=ze(e,t)}finally{r.blockedBoundary=n,r.blockedSegment=s}r=Be(e,a,n,u,o,r.legacyContext,r.context,r.treeContext),e.pingedTasks.push(r)}return}if("object"==typeof n&&null!==n)switch(n.$$typeof){case z:if(i=Ge(e,r,n.render,i,s),0!==Ee){n=r.treeContext,r.treeContext=ce(n,1,0);try{Ke(e,r,i)}finally{r.treeContext=n}}else Ke(e,r,i);return;case H:return void We(e,r,n=n.type,i=Ve(n,i),s);case B:if(s=i.children,n=n._context,i=i.value,a=n._currentValue2,n._currentValue2=i,ee=i={parent:o=ee,depth:null===o?0:o.depth+1,context:n,parentValue:a,value:i},r.context=i,Ke(e,r,s),null===(e=ee))throw Error(t(403));return i=e.parentValue,e.context._currentValue2=i===q?e.context._defaultValue:i,e=ee=e.parent,void(r.context=e);case U:return void Ke(e,r,i=(i=i.children)(n._currentValue2));case V:return void We(e,r,n=(s=n._init)(n._payload),i=Ve(n,i),void 0)}throw Error(t(130,null==n?n:typeof n,""))}switch(a=L((s=r.blockedSegment).chunks,n,i,e.responseState,s.formatContext),s.lastPushedText=!1,o=s.formatContext,s.formatContext=function(e,t,r){switch(t){case"select":return b(1,null!=r.value?r.value:r.defaultValue);case"svg":return b(2,null);case"math":return b(3,null);case"foreignObject":return b(1,null);case"table":return b(4,null);case"thead":case"tbody":case"tfoot":return b(5,null);case"colgroup":return b(7,null);case"tr":return b(6,null)}return 4<=e.insertionMode||0===e.insertionMode?b(1,null):e}(o,n,i),qe(e,r,a),s.formatContext=o,n){case"area":case"base":case"br":case"col":case"embed":case"hr":case"img":case"input":case"keygen":case"link":case"meta":case"param":case"source":case"track":case"wbr":break;default:s.chunks.push("</",n,">")}s.lastPushedText=!1}}function Ke(e,r,n){if(r.node=n,"object"==typeof n&&null!==n){switch(n.$$typeof){case M:return void We(e,r,n.type,n.props,n.ref);case O:throw Error(t(257));case V:var i=n._init;return void Ke(e,r,n=i(n._payload))}if(y(n))return void Ye(e,r,n);if(null===n||"object"!=typeof n?i=null:i="function"==typeof(i=X&&n[X]||n["@@iterator"])?i:null,i&&(i=i.call(n))){if(!(n=i.next()).done){var s=[];do{s.push(n.value),n=i.next()}while(!n.done);Ye(e,r,s)}return}throw e=Object.prototype.toString.call(n),Error(t(31,"[object Object]"===e?"object with keys {"+Object.keys(n).join(", ")+"}":e))}"string"==typeof n?(i=r.blockedSegment).lastPushedText=D(r.blockedSegment.chunks,n,e.responseState,i.lastPushedText):"number"==typeof n&&((i=r.blockedSegment).lastPushedText=D(r.blockedSegment.chunks,""+n,e.responseState,i.lastPushedText))}function Ye(e,t,r){for(var n=r.length,i=0;i<n;i++){var s=t.treeContext;t.treeContext=ce(s,n,i);try{qe(e,t,r[i])}finally{t.treeContext=s}}}function qe(e,t,r){var n=t.blockedSegment.formatContext,i=t.legacyContext,s=t.context;try{return Ke(e,t,r)}catch(l){if(Re(),"object"!=typeof l||null===l||"function"!=typeof l.then)throw t.blockedSegment.formatContext=n,t.legacyContext=i,t.context=s,ae(s),l;r=l;var a=t.blockedSegment,o=Ue(0,a.chunks.length,null,a.formatContext,a.lastPushedText,!0);a.children.push(o),a.lastPushedText=!1,e=Be(e,t.node,t.blockedBoundary,o,t.abortSet,t.legacyContext,t.context,t.treeContext).ping,r.then(e,e),t.blockedSegment.formatContext=n,t.legacyContext=i,t.context=s,ae(s)}}function Xe(e){var t=e.blockedBoundary;(e=e.blockedSegment).status=3,Je(this,t,e)}function Qe(e,r,n){var i=e.blockedBoundary;e.blockedSegment.status=3,null===i?(r.allPendingTasks--,2!==r.status&&(r.status=2,null!==r.destination&&r.destination.push(null))):(i.pendingTasks--,i.forceClientRender||(i.forceClientRender=!0,e=void 0===n?Error(t(432)):n,i.errorDigest=r.onError(e),i.parentFlushed&&r.clientRenderedBoundaries.push(i)),i.fallbackAbortableTasks.forEach(function(e){return Qe(e,r,n)}),i.fallbackAbortableTasks.clear(),r.allPendingTasks--,0===r.allPendingTasks&&(i=r.onAllReady)())}function Ze(e,t){if(0===t.chunks.length&&1===t.children.length&&null===t.children[0].boundary){var r=t.children[0];r.id=t.id,r.parentFlushed=!0,1===r.status&&Ze(e,r)}else e.completedSegments.push(t)}function Je(e,r,n){if(null===r){if(n.parentFlushed){if(null!==e.completedRootSegment)throw Error(t(389));e.completedRootSegment=n}e.pendingRootTasks--,0===e.pendingRootTasks&&(e.onShellError=$e,(r=e.onShellReady)())}else r.pendingTasks--,r.forceClientRender||(0===r.pendingTasks?(n.parentFlushed&&1===n.status&&Ze(r,n),r.parentFlushed&&e.completedBoundaries.push(r),r.fallbackAbortableTasks.forEach(Xe,e),r.fallbackAbortableTasks.clear()):n.parentFlushed&&1===n.status&&(Ze(r,n),1===r.completedSegments.length&&r.parentFlushed&&e.partialBoundaries.push(r)));e.allPendingTasks--,0===e.allPendingTasks&&(e=e.onAllReady)()}function et(e){if(2!==e.status){var t=ee,r=Ne.current;Ne.current=Me;var n=Oe;Oe=e.responseState;try{var i,s=e.pingedTasks;for(i=0;i<s.length;i++){var a=s[i],o=e,l=a.blockedSegment;if(0===l.status){ae(a.context);try{Ke(o,a,a.node),o.responseState.generateStaticMarkup||l.lastPushedText&&l.textEmbedded&&l.chunks.push("\x3c!-- --\x3e"),a.abortSet.delete(a),l.status=1,Je(o,a.blockedBoundary,l)}catch(e){if(Re(),"object"==typeof e&&null!==e&&"function"==typeof e.then){var u=a.ping;e.then(u,u)}else{a.abortSet.delete(a),l.status=4;var c=a.blockedBoundary,d=e,h=ze(o,d);if(null===c?je(o,d):(c.pendingTasks--,c.forceClientRender||(c.forceClientRender=!0,c.errorDigest=h,c.parentFlushed&&o.clientRenderedBoundaries.push(c))),o.allPendingTasks--,0===o.allPendingTasks)(0,o.onAllReady)()}}}}s.splice(0,i),null!==e.destination&&at(e,e.destination)}catch(t){ze(e,t),je(e,t)}finally{Oe=n,Ne.current=r,r===Me&&ae(t)}}}function tt(e,r,n){switch(n.parentFlushed=!0,n.status){case 0:var i=n.id=e.nextSegmentId++;return n.lastPushedText=!1,n.textEmbedded=!1,e=e.responseState,r.push('<template id="'),r.push(e.placeholderPrefix),e=i.toString(16),r.push(e),r.push('"></template>');case 1:n.status=2;var s=!0;i=n.chunks;var a=0;n=n.children;for(var o=0;o<n.length;o++){for(s=n[o];a<s.index;a++)r.push(i[a]);s=rt(e,r,s)}for(;a<i.length-1;a++)r.push(i[a]);return a<i.length&&(s=r.push(i[a])),s;default:throw Error(t(390))}}function rt(e,r,n){var i=n.boundary;if(null===i)return tt(e,r,n);if(i.parentFlushed=!0,i.forceClientRender)return e.responseState.generateStaticMarkup||(i=i.errorDigest,r.push("\x3c!--$!--\x3e"),r.push("<template"),i&&(r.push(' data-dgst="'),i=g(i),r.push(i),r.push('"')),r.push("></template>")),tt(e,r,n),e=!!e.responseState.generateStaticMarkup||r.push("\x3c!--/$--\x3e");if(0<i.pendingTasks){i.rootSegmentID=e.nextSegmentId++,0<i.completedSegments.length&&e.partialBoundaries.push(i);var s=e.responseState,a=s.nextSuspenseID++;return s=s.boundaryPrefix+a.toString(16),i=i.id=s,I(r,e.responseState,i),tt(e,r,n),r.push("\x3c!--/$--\x3e")}if(i.byteSize>e.progressiveChunkSize)return i.rootSegmentID=e.nextSegmentId++,e.completedBoundaries.push(i),I(r,e.responseState,i.id),tt(e,r,n),r.push("\x3c!--/$--\x3e");if(e.responseState.generateStaticMarkup||r.push("\x3c!--$--\x3e"),1!==(n=i.completedSegments).length)throw Error(t(391));return rt(e,r,n[0]),e=!!e.responseState.generateStaticMarkup||r.push("\x3c!--/$--\x3e")}function nt(e,r,n){return function(e,r,n,i){switch(n.insertionMode){case 0:case 1:return e.push('<div hidden id="'),e.push(r.segmentPrefix),r=i.toString(16),e.push(r),e.push('">');case 2:return e.push('<svg aria-hidden="true" style="display:none" id="'),e.push(r.segmentPrefix),r=i.toString(16),e.push(r),e.push('">');case 3:return e.push('<math aria-hidden="true" style="display:none" id="'),e.push(r.segmentPrefix),r=i.toString(16),e.push(r),e.push('">');case 4:return e.push('<table hidden id="'),e.push(r.segmentPrefix),r=i.toString(16),e.push(r),e.push('">');case 5:return e.push('<table hidden><tbody id="'),e.push(r.segmentPrefix),r=i.toString(16),e.push(r),e.push('">');case 6:return e.push('<table hidden><tr id="'),e.push(r.segmentPrefix),r=i.toString(16),e.push(r),e.push('">');case 7:return e.push('<table hidden><colgroup id="'),e.push(r.segmentPrefix),r=i.toString(16),e.push(r),e.push('">');default:throw Error(t(397))}}(r,e.responseState,n.formatContext,n.id),rt(e,r,n),function(e,r){switch(r.insertionMode){case 0:case 1:return e.push("</div>");case 2:return e.push("</svg>");case 3:return e.push("</math>");case 4:return e.push("</table>");case 5:return e.push("</tbody></table>");case 6:return e.push("</tr></table>");case 7:return e.push("</colgroup></table>");default:throw Error(t(397))}}(r,n.formatContext)}function it(e,r,n){for(var i=n.completedSegments,s=0;s<i.length;s++)st(e,r,n,i[s]);if(i.length=0,e=e.responseState,i=n.id,n=n.rootSegmentID,r.push(e.startInlineScript),e.sentCompleteBoundaryFunction?r.push('$RC("'):(e.sentCompleteBoundaryFunction=!0,r.push('function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}};$RC("')),null===i)throw Error(t(395));return n=n.toString(16),r.push(i),r.push('","'),r.push(e.segmentPrefix),r.push(n),r.push('")<\/script>')}function st(e,r,n,i){if(2===i.status)return!0;var s=i.id;if(-1===s){if(-1===(i.id=n.rootSegmentID))throw Error(t(392));return nt(e,r,i)}return nt(e,r,i),e=e.responseState,r.push(e.startInlineScript),e.sentCompleteSegmentFunction?r.push('$RS("'):(e.sentCompleteSegmentFunction=!0,r.push('function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};$RS("')),r.push(e.segmentPrefix),s=s.toString(16),r.push(s),r.push('","'),r.push(e.placeholderPrefix),r.push(s),r.push('")<\/script>')}function at(e,r){try{var n=e.completedRootSegment;if(null!==n&&0===e.pendingRootTasks){rt(e,r,n),e.completedRootSegment=null;var i=e.responseState.bootstrapChunks;for(n=0;n<i.length-1;n++)r.push(i[n]);n<i.length&&r.push(i[n])}var s,a=e.clientRenderedBoundaries;for(s=0;s<a.length;s++){var o=a[s];i=r;var l=e.responseState,u=o.id,c=o.errorDigest,d=o.errorMessage,h=o.errorComponentStack;if(i.push(l.startInlineScript),l.sentClientRenderFunction?i.push('$RX("'):(l.sentClientRenderFunction=!0,i.push('function $RX(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())};$RX("')),null===u)throw Error(t(395));if(i.push(u),i.push('"'),c||d||h){i.push(",");var f=P(c||"");i.push(f)}if(d||h){i.push(",");var p=P(d||"");i.push(p)}if(h){i.push(",");var g=P(h);i.push(g)}if(!i.push(")<\/script>"))return e.destination=null,s++,void a.splice(0,s)}a.splice(0,s);var m=e.completedBoundaries;for(s=0;s<m.length;s++)if(!it(e,r,m[s]))return e.destination=null,s++,void m.splice(0,s);m.splice(0,s);var v=e.partialBoundaries;for(s=0;s<v.length;s++){var y=v[s];e:{a=e,o=r;var b=y.completedSegments;for(l=0;l<b.length;l++)if(!st(a,o,y,b[l])){l++,b.splice(0,l);var w=!1;break e}b.splice(0,l),w=!0}if(!w)return e.destination=null,s++,void v.splice(0,s)}v.splice(0,s);var E=e.completedBoundaries;for(s=0;s<E.length;s++)if(!it(e,r,E[s]))return e.destination=null,s++,void E.splice(0,s);E.splice(0,s)}finally{0===e.allPendingTasks&&0===e.pingedTasks.length&&0===e.clientRenderedBoundaries.length&&0===e.completedBoundaries.length&&r.push(null)}}function ot(e,t){try{var r=e.abortableTasks;r.forEach(function(r){return Qe(r,e,t)}),r.clear(),null!==e.destination&&at(e,e.destination)}catch(t){ze(e,t),je(e,t)}}function lt(){}function ut(e,r,n,i){var s=!1,a=null,o="",l={push:function(e){return null!==e&&(o+=e),!0},destroy:function(e){s=!0,a=e}},u=!1;if(e=function(e,t,r,n,i,s,a){var o=[],l=new Set;return(r=Ue(t={destination:null,responseState:t,progressiveChunkSize:void 0===n?12800:n,status:0,fatalError:null,nextSegmentId:0,allPendingTasks:0,pendingRootTasks:0,completedRootSegment:null,abortableTasks:l,pingedTasks:o,clientRenderedBoundaries:[],completedBoundaries:[],partialBoundaries:[],onError:void 0===i?Fe:i,onAllReady:$e,onShellReady:void 0===a?$e:a,onShellError:$e,onFatalError:$e},0,null,r,!1,!1)).parentFlushed=!0,e=Be(t,e,null,r,l,Z,null,ue),o.push(e),t}(e,function(e,t){return{bootstrapChunks:[],startInlineScript:"<script>",placeholderPrefix:(t=void 0===t?"":t)+"P:",segmentPrefix:t+"S:",boundaryPrefix:t+"B:",idPrefix:t,nextSuspenseID:0,sentCompleteSegmentFunction:!1,sentCompleteBoundaryFunction:!1,sentClientRenderFunction:!1,generateStaticMarkup:e}}(n,r?r.identifierPrefix:void 0),{insertionMode:1,selectedValue:null},1/0,lt,0,function(){u=!0}),et(e),ot(e,i),1===e.status)e.status=2,l.destroy(e.fatalError);else if(2!==e.status&&null===e.destination){e.destination=l;try{at(e,l)}catch(t){ze(e,t),je(e,t)}}if(s)throw a;if(!u)throw Error(t(426));return o}return Du.renderToNodeStream=function(){throw Error(t(207))},Du.renderToStaticMarkup=function(e,t){return ut(e,t,!0,'The server used "renderToStaticMarkup" which does not support Suspense. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server')},Du.renderToStaticNodeStream=function(){throw Error(t(208))},Du.renderToString=function(e,t){return ut(e,t,!1,'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server')},Du.version="18.3.1",Du}var Mu,Ou,Nu={};
|
|
36
36
|
/**
|
|
37
37
|
* @license React
|
|
38
38
|
* react-dom-server.browser.production.min.js
|
|
@@ -41,4 +41,4 @@ var Yn={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24
|
|
|
41
41
|
*
|
|
42
42
|
* This source code is licensed under the MIT license found in the
|
|
43
43
|
* LICENSE file in the root directory of this source tree.
|
|
44
|
-
*/function $u(){if(Ou)return Fu;Ou=1;var e=l();function t(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r<arguments.length;r++)t+="&args[]="+encodeURIComponent(arguments[r]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var r=null,n=0;function i(e,t){if(0!==t.length)if(512<t.length)0<n&&(e.enqueue(new Uint8Array(r.buffer,0,n)),r=new Uint8Array(512),n=0),e.enqueue(t);else{var i=r.length-n;i<t.length&&(0===i?e.enqueue(r):(r.set(t.subarray(0,i),n),e.enqueue(r),t=t.subarray(i)),r=new Uint8Array(512),n=0),r.set(t,n),n+=t.length}}function s(e,t){return i(e,t),!0}function a(e){r&&0<n&&(e.enqueue(new Uint8Array(r.buffer,0,n)),r=null,n=0)}var o=new TextEncoder;function u(e){return o.encode(e)}function c(e){return o.encode(e)}function d(e,t){"function"==typeof e.error?e.error(t):e.close()}var h=Object.prototype.hasOwnProperty,f=/^[: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]*$/,p={},g={};function m(e){return!!h.call(g,e)||!h.call(p,e)&&(f.test(e)?g[e]=!0:(p[e]=!0,!1))}function v(e,t,r,n,i,s,a){this.acceptsBooleans=2===t||3===t||4===t,this.attributeName=n,this.attributeNamespace=i,this.mustUseProperty=r,this.propertyName=e,this.type=t,this.sanitizeURL=s,this.removeEmptyString=a}var y={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){y[e]=new v(e,0,!1,e,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];y[t]=new v(t,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){y[e]=new v(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){y[e]=new v(e,2,!1,e,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){y[e]=new v(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){y[e]=new v(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){y[e]=new v(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){y[e]=new v(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){y[e]=new v(e,5,!1,e.toLowerCase(),null,!1,!1)});var b=/[\-:]([a-z])/g;function w(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(b,w);y[t]=new v(t,1,!1,e,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(b,w);y[t]=new v(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(b,w);y[t]=new v(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){y[e]=new v(e,1,!1,e.toLowerCase(),null,!1,!1)}),y.xlinkHref=new v("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){y[e]=new v(e,1,!1,e.toLowerCase(),null,!0,!0)});var E={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},S=["Webkit","ms","Moz","O"];Object.keys(E).forEach(function(e){S.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),E[t]=E[e]})});var T=/["'&<>]/;function x(e){if("boolean"==typeof e||"number"==typeof e)return""+e;e=""+e;var t=T.exec(e);if(t){var r,n="",i=0;for(r=t.index;r<e.length;r++){switch(e.charCodeAt(r)){case 34:t=""";break;case 38:t="&";break;case 39:t="'";break;case 60:t="<";break;case 62:t=">";break;default:continue}i!==r&&(n+=e.substring(i,r)),i=r+1,n+=t}e=i!==r?n+e.substring(i,r):n}return e}var k=/([A-Z])/g,A=/^ms-/,R=Array.isArray,L=c("<script>"),I=c("<\/script>"),C=c('<script src="'),P=c('<script type="module" src="'),D=c('" async=""><\/script>'),_=/(<\/|<)(s)(cript)/gi;function M(e,t,r,n){return t+("s"===r?"\\u0073":"\\u0053")+n}function O(e,t){return{insertionMode:e,selectedValue:t}}var N=c("\x3c!-- --\x3e");function F(e,t,r,n){return""===t?n:(n&&e.push(N),e.push(u(x(t))),!0)}var $=new Map,B=c(' style="'),U=c(":"),z=c(";");function j(e,r,n){if("object"!=typeof n)throw Error(t(62));for(var i in r=!0,n)if(h.call(n,i)){var s=n[i];if(null!=s&&"boolean"!=typeof s&&""!==s){if(0===i.indexOf("--")){var a=u(x(i));s=u(x((""+s).trim()))}else{a=i;var o=$.get(a);void 0!==o||(o=c(x(a.replace(k,"-$1").toLowerCase().replace(A,"-ms-"))),$.set(a,o)),a=o,s="number"==typeof s?0===s||h.call(E,i)?u(""+s):u(s+"px"):u(x((""+s).trim()))}r?(r=!1,e.push(B,a,U,s)):e.push(z,a,U,s)}}r||e.push(V)}var G=c(" "),H=c('="'),V=c('"'),W=c('=""');function K(e,t,r,n){switch(r){case"style":return void j(e,t,n);case"defaultValue":case"defaultChecked":case"innerHTML":case"suppressContentEditableWarning":case"suppressHydrationWarning":return}if(!(2<r.length)||"o"!==r[0]&&"O"!==r[0]||"n"!==r[1]&&"N"!==r[1])if(null!==(t=y.hasOwnProperty(r)?y[r]:null)){switch(typeof n){case"function":case"symbol":return;case"boolean":if(!t.acceptsBooleans)return}switch(r=u(t.attributeName),t.type){case 3:n&&e.push(G,r,W);break;case 4:!0===n?e.push(G,r,W):!1!==n&&e.push(G,r,H,u(x(n)),V);break;case 5:isNaN(n)||e.push(G,r,H,u(x(n)),V);break;case 6:!isNaN(n)&&1<=n&&e.push(G,r,H,u(x(n)),V);break;default:t.sanitizeURL&&(n=""+n),e.push(G,r,H,u(x(n)),V)}}else if(m(r)){switch(typeof n){case"function":case"symbol":return;case"boolean":if("data-"!==(t=r.toLowerCase().slice(0,5))&&"aria-"!==t)return}e.push(G,u(r),H,u(x(n)),V)}}var Y=c(">"),q=c("/>");function X(e,r,n){if(null!=r){if(null!=n)throw Error(t(60));if("object"!=typeof r||!("__html"in r))throw Error(t(61));null!=(r=r.__html)&&e.push(u(""+r))}}var Q=c(' selected=""');function Z(e,t,r,n){e.push(re(r));var i,s=r=null;for(i in t)if(h.call(t,i)){var a=t[i];if(null!=a)switch(i){case"children":r=a;break;case"dangerouslySetInnerHTML":s=a;break;default:K(e,n,i,a)}}return e.push(Y),X(e,s,r),"string"==typeof r?(e.push(u(x(r))),null):r}var J=c("\n"),ee=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,te=new Map;function re(e){var r=te.get(e);if(void 0===r){if(!ee.test(e))throw Error(t(65,e));r=c("<"+e),te.set(e,r)}return r}var ne=c("<!DOCTYPE html>");function ie(r,n,i,s,a){switch(n){case"select":r.push(re("select"));var o=null,l=null;for(p in i)if(h.call(i,p)){var c=i[p];if(null!=c)switch(p){case"children":o=c;break;case"dangerouslySetInnerHTML":l=c;break;case"defaultValue":case"value":break;default:K(r,s,p,c)}}return r.push(Y),X(r,l,o),o;case"option":l=a.selectedValue,r.push(re("option"));var d=c=null,f=null,p=null;for(o in i)if(h.call(i,o)){var g=i[o];if(null!=g)switch(o){case"children":c=g;break;case"selected":f=g;break;case"dangerouslySetInnerHTML":p=g;break;case"value":d=g;default:K(r,s,o,g)}}if(null!=l)if(i=null!==d?""+d:function(t){var r="";return e.Children.forEach(t,function(e){null!=e&&(r+=e)}),r}(c),R(l)){for(s=0;s<l.length;s++)if(""+l[s]===i){r.push(Q);break}}else""+l===i&&r.push(Q);else f&&r.push(Q);return r.push(Y),X(r,p,c),c;case"textarea":for(c in r.push(re("textarea")),p=l=o=null,i)if(h.call(i,c)&&null!=(d=i[c]))switch(c){case"children":p=d;break;case"value":o=d;break;case"defaultValue":l=d;break;case"dangerouslySetInnerHTML":throw Error(t(91));default:K(r,s,c,d)}if(null===o&&null!==l&&(o=l),r.push(Y),null!=p){if(null!=o)throw Error(t(92));if(R(p)&&1<p.length)throw Error(t(93));o=""+p}return"string"==typeof o&&"\n"===o[0]&&r.push(J),null!==o&&r.push(u(x(""+o))),null;case"input":for(l in r.push(re("input")),d=p=c=o=null,i)if(h.call(i,l)&&null!=(f=i[l]))switch(l){case"children":case"dangerouslySetInnerHTML":throw Error(t(399,"input"));case"defaultChecked":d=f;break;case"defaultValue":c=f;break;case"checked":p=f;break;case"value":o=f;break;default:K(r,s,l,f)}return null!==p?K(r,s,"checked",p):null!==d&&K(r,s,"checked",d),null!==o?K(r,s,"value",o):null!==c&&K(r,s,"value",c),r.push(q),null;case"menuitem":for(var v in r.push(re("menuitem")),i)if(h.call(i,v)&&null!=(o=i[v]))switch(v){case"children":case"dangerouslySetInnerHTML":throw Error(t(400));default:K(r,s,v,o)}return r.push(Y),null;case"title":for(g in r.push(re("title")),o=null,i)if(h.call(i,g)&&null!=(l=i[g]))switch(g){case"children":o=l;break;case"dangerouslySetInnerHTML":throw Error(t(434));default:K(r,s,g,l)}return r.push(Y),o;case"listing":case"pre":for(d in r.push(re(n)),l=o=null,i)if(h.call(i,d)&&null!=(c=i[d]))switch(d){case"children":o=c;break;case"dangerouslySetInnerHTML":l=c;break;default:K(r,s,d,c)}if(r.push(Y),null!=l){if(null!=o)throw Error(t(60));if("object"!=typeof l||!("__html"in l))throw Error(t(61));null!=(i=l.__html)&&("string"==typeof i&&0<i.length&&"\n"===i[0]?r.push(J,u(i)):r.push(u(""+i)))}return"string"==typeof o&&"\n"===o[0]&&r.push(J),o;case"area":case"base":case"br":case"col":case"embed":case"hr":case"img":case"keygen":case"link":case"meta":case"param":case"source":case"track":case"wbr":for(var y in r.push(re(n)),i)if(h.call(i,y)&&null!=(o=i[y]))switch(y){case"children":case"dangerouslySetInnerHTML":throw Error(t(399,n));default:K(r,s,y,o)}return r.push(q),null;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 Z(r,i,n,s);case"html":return 0===a.insertionMode&&r.push(ne),Z(r,i,n,s);default:if(-1===n.indexOf("-")&&"string"!=typeof i.is)return Z(r,i,n,s);for(f in r.push(re(n)),l=o=null,i)if(h.call(i,f)&&null!=(c=i[f]))switch(f){case"children":o=c;break;case"dangerouslySetInnerHTML":l=c;break;case"style":j(r,s,c);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":break;default:m(f)&&"function"!=typeof c&&"symbol"!=typeof c&&r.push(G,u(f),H,u(x(c)),V)}return r.push(Y),X(r,l,o),o}}var se=c("</"),ae=c(">"),oe=c('<template id="'),le=c('"></template>'),ue=c("\x3c!--$--\x3e"),ce=c('\x3c!--$?--\x3e<template id="'),de=c('"></template>'),he=c("\x3c!--$!--\x3e"),fe=c("\x3c!--/$--\x3e"),pe=c("<template"),ge=c('"'),me=c(' data-dgst="');c(' data-msg="'),c(' data-stck="');var ve=c("></template>");function ye(e,r,n){if(i(e,ce),null===n)throw Error(t(395));return i(e,n),s(e,de)}var be=c('<div hidden id="'),we=c('">'),Ee=c("</div>"),Se=c('<svg aria-hidden="true" style="display:none" id="'),Te=c('">'),xe=c("</svg>"),ke=c('<math aria-hidden="true" style="display:none" id="'),Ae=c('">'),Re=c("</math>"),Le=c('<table hidden id="'),Ie=c('">'),Ce=c("</table>"),Pe=c('<table hidden><tbody id="'),De=c('">'),_e=c("</tbody></table>"),Me=c('<table hidden><tr id="'),Oe=c('">'),Ne=c("</tr></table>"),Fe=c('<table hidden><colgroup id="'),$e=c('">'),Be=c("</colgroup></table>");var Ue=c('function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};$RS("'),ze=c('$RS("'),je=c('","'),Ge=c('")<\/script>'),He=c('function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}};$RC("'),Ve=c('$RC("'),We=c('","'),Ke=c('")<\/script>'),Ye=c('function $RX(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())};$RX("'),qe=c('$RX("'),Xe=c('"'),Qe=c(")<\/script>"),Ze=c(","),Je=/[<\u2028\u2029]/g;function et(e){return JSON.stringify(e).replace(Je,function(e){switch(e){case"<":return"\\u003c";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:throw Error("escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React")}})}var tt=Object.assign,rt=Symbol.for("react.element"),nt=Symbol.for("react.portal"),it=Symbol.for("react.fragment"),st=Symbol.for("react.strict_mode"),at=Symbol.for("react.profiler"),ot=Symbol.for("react.provider"),lt=Symbol.for("react.context"),ut=Symbol.for("react.forward_ref"),ct=Symbol.for("react.suspense"),dt=Symbol.for("react.suspense_list"),ht=Symbol.for("react.memo"),ft=Symbol.for("react.lazy"),pt=Symbol.for("react.scope"),gt=Symbol.for("react.debug_trace_mode"),mt=Symbol.for("react.legacy_hidden"),vt=Symbol.for("react.default_value"),yt=Symbol.iterator;function bt(e){if(null==e)return null;if("function"==typeof e)return e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case it:return"Fragment";case nt:return"Portal";case at:return"Profiler";case st:return"StrictMode";case ct:return"Suspense";case dt:return"SuspenseList"}if("object"==typeof e)switch(e.$$typeof){case lt:return(e.displayName||"Context")+".Consumer";case ot:return(e._context.displayName||"Context")+".Provider";case ut:var t=e.render;return(e=e.displayName)||(e=""!==(e=t.displayName||t.name||"")?"ForwardRef("+e+")":"ForwardRef"),e;case ht:return null!==(t=e.displayName||null)?t:bt(e.type)||"Memo";case ft:t=e._payload,e=e._init;try{return bt(e(t))}catch(e){}}return null}var wt={};function Et(e,t){if(!(e=e.contextTypes))return wt;var r,n={};for(r in e)n[r]=t[r];return n}var St=null;function Tt(e,r){if(e!==r){e.context._currentValue=e.parentValue,e=e.parent;var n=r.parent;if(null===e){if(null!==n)throw Error(t(401))}else{if(null===n)throw Error(t(401));Tt(e,n)}r.context._currentValue=r.value}}function xt(e){e.context._currentValue=e.parentValue,null!==(e=e.parent)&&xt(e)}function kt(e){var t=e.parent;null!==t&&kt(t),e.context._currentValue=e.value}function At(e,r){if(e.context._currentValue=e.parentValue,null===(e=e.parent))throw Error(t(402));e.depth===r.depth?Tt(e,r):At(e,r)}function Rt(e,r){var n=r.parent;if(null===n)throw Error(t(402));e.depth===n.depth?Tt(e,n):Rt(e,n),r.context._currentValue=r.value}function Lt(e){var t=St;t!==e&&(null===t?kt(e):null===e?xt(t):t.depth===e.depth?Tt(t,e):t.depth>e.depth?At(t,e):Rt(t,e),St=e)}var It={isMounted:function(){return!1},enqueueSetState:function(e,t){null!==(e=e._reactInternals).queue&&e.queue.push(t)},enqueueReplaceState:function(e,t){(e=e._reactInternals).replace=!0,e.queue=[t]},enqueueForceUpdate:function(){}};function Ct(e,t,r,n){var i=void 0!==e.state?e.state:null;e.updater=It,e.props=r,e.state=i;var s={queue:[],replace:!1};e._reactInternals=s;var a=t.contextType;if(e.context="object"==typeof a&&null!==a?a._currentValue:n,"function"==typeof(a=t.getDerivedStateFromProps)&&(i=null==(a=a(r,i))?i:tt({},i,a),e.state=i),"function"!=typeof t.getDerivedStateFromProps&&"function"!=typeof e.getSnapshotBeforeUpdate&&("function"==typeof e.UNSAFE_componentWillMount||"function"==typeof e.componentWillMount))if(t=e.state,"function"==typeof e.componentWillMount&&e.componentWillMount(),"function"==typeof e.UNSAFE_componentWillMount&&e.UNSAFE_componentWillMount(),t!==e.state&&It.enqueueReplaceState(e,e.state,null),null!==s.queue&&0<s.queue.length)if(t=s.queue,a=s.replace,s.queue=null,s.replace=!1,a&&1===t.length)e.state=t[0];else{for(s=a?t[0]:e.state,i=!0,a=a?1:0;a<t.length;a++){var o=t[a];null!=(o="function"==typeof o?o.call(e,s,r,n):o)&&(i?(i=!1,s=tt({},s,o)):tt(s,o))}e.state=s}else s.queue=null}var Pt={id:1,overflow:""};function Dt(e,t,r){var n=e.id;e=e.overflow;var i=32-_t(n)-1;n&=~(1<<i),r+=1;var s=32-_t(t)+i;if(30<s){var a=i-i%5;return s=(n&(1<<a)-1).toString(32),n>>=a,i-=a,{id:1<<32-_t(t)+i|r<<i|n,overflow:s+e}}return{id:1<<s|r<<i|n,overflow:e}}var _t=Math.clz32?Math.clz32:function(e){return e>>>=0,0===e?32:31-(Mt(e)/Ot|0)|0},Mt=Math.log,Ot=Math.LN2;var Nt="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},Ft=null,$t=null,Bt=null,Ut=null,zt=!1,jt=!1,Gt=0,Ht=null,Vt=0;function Wt(){if(null===Ft)throw Error(t(321));return Ft}function Kt(){if(0<Vt)throw Error(t(312));return{memoizedState:null,queue:null,next:null}}function Yt(){return null===Ut?null===Bt?(zt=!1,Bt=Ut=Kt()):(zt=!0,Ut=Bt):null===Ut.next?(zt=!1,Ut=Ut.next=Kt()):(zt=!0,Ut=Ut.next),Ut}function qt(){$t=Ft=null,jt=!1,Bt=null,Vt=0,Ut=Ht=null}function Xt(e,t){return"function"==typeof t?t(e):t}function Qt(e,t,r){if(Ft=Wt(),Ut=Yt(),zt){var n=Ut.queue;if(t=n.dispatch,null!==Ht&&void 0!==(r=Ht.get(n))){Ht.delete(n),n=Ut.memoizedState;do{n=e(n,r.action),r=r.next}while(null!==r);return Ut.memoizedState=n,[n,t]}return[Ut.memoizedState,t]}return e=e===Xt?"function"==typeof t?t():t:void 0!==r?r(t):t,Ut.memoizedState=e,e=(e=Ut.queue={last:null,dispatch:null}).dispatch=Jt.bind(null,Ft,e),[Ut.memoizedState,e]}function Zt(e,t){if(Ft=Wt(),t=void 0===t?null:t,null!==(Ut=Yt())){var r=Ut.memoizedState;if(null!==r&&null!==t){var n=r[1];e:if(null===n)n=!1;else{for(var i=0;i<n.length&&i<t.length;i++)if(!Nt(t[i],n[i])){n=!1;break e}n=!0}if(n)return r[0]}}return e=e(),Ut.memoizedState=[e,t],e}function Jt(e,r,n){if(25<=Vt)throw Error(t(301));if(e===Ft)if(jt=!0,e={action:n,next:null},null===Ht&&(Ht=new Map),void 0===(n=Ht.get(r)))Ht.set(r,e);else{for(r=n;null!==r.next;)r=r.next;r.next=e}}function er(){throw Error(t(394))}function tr(){}var rr={readContext:function(e){return e._currentValue},useContext:function(e){return Wt(),e._currentValue},useMemo:Zt,useReducer:Qt,useRef:function(e){Ft=Wt();var t=(Ut=Yt()).memoizedState;return null===t?(e={current:e},Ut.memoizedState=e):t},useState:function(e){return Qt(Xt,e)},useInsertionEffect:tr,useLayoutEffect:function(){},useCallback:function(e,t){return Zt(function(){return e},t)},useImperativeHandle:tr,useEffect:tr,useDebugValue:tr,useDeferredValue:function(e){return Wt(),e},useTransition:function(){return Wt(),[!1,er]},useId:function(){var e=$t.treeContext,r=e.overflow;e=((e=e.id)&~(1<<32-_t(e)-1)).toString(32)+r;var n=nr;if(null===n)throw Error(t(404));return r=Gt++,e=":"+n.idPrefix+"R"+e,0<r&&(e+="H"+r.toString(32)),e+":"},useMutableSource:function(e,t){return Wt(),t(e._source)},useSyncExternalStore:function(e,r,n){if(void 0===n)throw Error(t(407));return n()}},nr=null,ir=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher;function sr(e){return console.error(e),null}function ar(){}function or(e,t,r,n,i,s,a,o){e.allPendingTasks++,null===r?e.pendingRootTasks++:r.pendingTasks++;var l={node:t,ping:function(){var t=e.pingedTasks;t.push(l),1===t.length&&Sr(e)},blockedBoundary:r,blockedSegment:n,abortSet:i,legacyContext:s,context:a,treeContext:o};return i.add(l),l}function lr(e,t,r,n,i,s){return{status:0,id:-1,index:t,parentFlushed:!1,chunks:[],children:[],formatContext:n,boundary:r,lastPushedText:i,textEmbedded:s}}function ur(e,t){if(null!=(e=e.onError(t))&&"string"!=typeof e)throw Error('onError returned something with a type other than "string". onError should return a string and may return null or undefined but must not return anything else. It received something of type "'+typeof e+'" instead');return e}function cr(e,t){var r=e.onShellError;r(t),(r=e.onFatalError)(t),null!==e.destination?(e.status=2,d(e.destination,t)):(e.status=1,e.fatalError=t)}function dr(e,t,r,n,i){for(Ft={},$t=t,Gt=0,e=r(n,i);jt;)jt=!1,Gt=0,Vt+=1,Ut=null,e=r(n,i);return qt(),e}function hr(e,r,n,i){var s=n.render(),a=i.childContextTypes;if(null!=a){var o=r.legacyContext;if("function"!=typeof n.getChildContext)i=o;else{for(var l in n=n.getChildContext())if(!(l in a))throw Error(t(108,bt(i)||"Unknown",l));i=tt({},o,n)}r.legacyContext=i,gr(e,r,s),r.legacyContext=o}else gr(e,r,s)}function fr(e,t){if(e&&e.defaultProps){for(var r in t=tt({},t),e=e.defaultProps)void 0===t[r]&&(t[r]=e[r]);return t}return t}function pr(e,r,n,i,s){if("function"==typeof n)if(n.prototype&&n.prototype.isReactComponent){s=Et(n,r.legacyContext);var a=n.contextType;Ct(a=new n(i,"object"==typeof a&&null!==a?a._currentValue:s),n,i,s),hr(e,r,a,n)}else{s=dr(e,r,n,i,a=Et(n,r.legacyContext));var o=0!==Gt;if("object"==typeof s&&null!==s&&"function"==typeof s.render&&void 0===s.$$typeof)Ct(s,n,i,a),hr(e,r,s,n);else if(o){i=r.treeContext,r.treeContext=Dt(i,1,0);try{gr(e,r,s)}finally{r.treeContext=i}}else gr(e,r,s)}else{if("string"!=typeof n){switch(n){case mt:case gt:case st:case at:case it:case dt:return void gr(e,r,i.children);case pt:throw Error(t(343));case ct:e:{n=r.blockedBoundary,s=r.blockedSegment,a=i.fallback,i=i.children;var l={id:null,rootSegmentID:-1,parentFlushed:!1,pendingTasks:0,forceClientRender:!1,completedSegments:[],byteSize:0,fallbackAbortableTasks:o=new Set,errorDigest:null},c=lr(0,s.chunks.length,l,s.formatContext,!1,!1);s.children.push(c),s.lastPushedText=!1;var d=lr(0,0,null,s.formatContext,!1,!1);d.parentFlushed=!0,r.blockedBoundary=l,r.blockedSegment=d;try{if(vr(e,r,i),d.lastPushedText&&d.textEmbedded&&d.chunks.push(N),d.status=1,wr(l,d),0===l.pendingTasks)break e}catch(t){d.status=4,l.forceClientRender=!0,l.errorDigest=ur(e,t)}finally{r.blockedBoundary=n,r.blockedSegment=s}r=or(e,a,n,c,o,r.legacyContext,r.context,r.treeContext),e.pingedTasks.push(r)}return}if("object"==typeof n&&null!==n)switch(n.$$typeof){case ut:if(i=dr(e,r,n.render,i,s),0!==Gt){n=r.treeContext,r.treeContext=Dt(n,1,0);try{gr(e,r,i)}finally{r.treeContext=n}}else gr(e,r,i);return;case ht:return void pr(e,r,n=n.type,i=fr(n,i),s);case ot:if(s=i.children,n=n._context,i=i.value,a=n._currentValue,n._currentValue=i,St=i={parent:o=St,depth:null===o?0:o.depth+1,context:n,parentValue:a,value:i},r.context=i,gr(e,r,s),null===(e=St))throw Error(t(403));return i=e.parentValue,e.context._currentValue=i===vt?e.context._defaultValue:i,e=St=e.parent,void(r.context=e);case lt:return void gr(e,r,i=(i=i.children)(n._currentValue));case ft:return void pr(e,r,n=(s=n._init)(n._payload),i=fr(n,i),void 0)}throw Error(t(130,null==n?n:typeof n,""))}switch(a=ie((s=r.blockedSegment).chunks,n,i,e.responseState,s.formatContext),s.lastPushedText=!1,o=s.formatContext,s.formatContext=function(e,t,r){switch(t){case"select":return O(1,null!=r.value?r.value:r.defaultValue);case"svg":return O(2,null);case"math":return O(3,null);case"foreignObject":return O(1,null);case"table":return O(4,null);case"thead":case"tbody":case"tfoot":return O(5,null);case"colgroup":return O(7,null);case"tr":return O(6,null)}return 4<=e.insertionMode||0===e.insertionMode?O(1,null):e}(o,n,i),vr(e,r,a),s.formatContext=o,n){case"area":case"base":case"br":case"col":case"embed":case"hr":case"img":case"input":case"keygen":case"link":case"meta":case"param":case"source":case"track":case"wbr":break;default:s.chunks.push(se,u(n),ae)}s.lastPushedText=!1}}function gr(e,r,n){if(r.node=n,"object"==typeof n&&null!==n){switch(n.$$typeof){case rt:return void pr(e,r,n.type,n.props,n.ref);case nt:throw Error(t(257));case ft:var i=n._init;return void gr(e,r,n=i(n._payload))}if(R(n))return void mr(e,r,n);if(null===n||"object"!=typeof n?i=null:i="function"==typeof(i=yt&&n[yt]||n["@@iterator"])?i:null,i&&(i=i.call(n))){if(!(n=i.next()).done){var s=[];do{s.push(n.value),n=i.next()}while(!n.done);mr(e,r,s)}return}throw e=Object.prototype.toString.call(n),Error(t(31,"[object Object]"===e?"object with keys {"+Object.keys(n).join(", ")+"}":e))}"string"==typeof n?(i=r.blockedSegment).lastPushedText=F(r.blockedSegment.chunks,n,e.responseState,i.lastPushedText):"number"==typeof n&&((i=r.blockedSegment).lastPushedText=F(r.blockedSegment.chunks,""+n,e.responseState,i.lastPushedText))}function mr(e,t,r){for(var n=r.length,i=0;i<n;i++){var s=t.treeContext;t.treeContext=Dt(s,n,i);try{vr(e,t,r[i])}finally{t.treeContext=s}}}function vr(e,t,r){var n=t.blockedSegment.formatContext,i=t.legacyContext,s=t.context;try{return gr(e,t,r)}catch(l){if(qt(),"object"!=typeof l||null===l||"function"!=typeof l.then)throw t.blockedSegment.formatContext=n,t.legacyContext=i,t.context=s,Lt(s),l;r=l;var a=t.blockedSegment,o=lr(0,a.chunks.length,null,a.formatContext,a.lastPushedText,!0);a.children.push(o),a.lastPushedText=!1,e=or(e,t.node,t.blockedBoundary,o,t.abortSet,t.legacyContext,t.context,t.treeContext).ping,r.then(e,e),t.blockedSegment.formatContext=n,t.legacyContext=i,t.context=s,Lt(s)}}function yr(e){var t=e.blockedBoundary;(e=e.blockedSegment).status=3,Er(this,t,e)}function br(e,r,n){var i=e.blockedBoundary;e.blockedSegment.status=3,null===i?(r.allPendingTasks--,2!==r.status&&(r.status=2,null!==r.destination&&r.destination.close())):(i.pendingTasks--,i.forceClientRender||(i.forceClientRender=!0,e=void 0===n?Error(t(432)):n,i.errorDigest=r.onError(e),i.parentFlushed&&r.clientRenderedBoundaries.push(i)),i.fallbackAbortableTasks.forEach(function(e){return br(e,r,n)}),i.fallbackAbortableTasks.clear(),r.allPendingTasks--,0===r.allPendingTasks&&(i=r.onAllReady)())}function wr(e,t){if(0===t.chunks.length&&1===t.children.length&&null===t.children[0].boundary){var r=t.children[0];r.id=t.id,r.parentFlushed=!0,1===r.status&&wr(e,r)}else e.completedSegments.push(t)}function Er(e,r,n){if(null===r){if(n.parentFlushed){if(null!==e.completedRootSegment)throw Error(t(389));e.completedRootSegment=n}e.pendingRootTasks--,0===e.pendingRootTasks&&(e.onShellError=ar,(r=e.onShellReady)())}else r.pendingTasks--,r.forceClientRender||(0===r.pendingTasks?(n.parentFlushed&&1===n.status&&wr(r,n),r.parentFlushed&&e.completedBoundaries.push(r),r.fallbackAbortableTasks.forEach(yr,e),r.fallbackAbortableTasks.clear()):n.parentFlushed&&1===n.status&&(wr(r,n),1===r.completedSegments.length&&r.parentFlushed&&e.partialBoundaries.push(r)));e.allPendingTasks--,0===e.allPendingTasks&&(e=e.onAllReady)()}function Sr(e){if(2!==e.status){var t=St,r=ir.current;ir.current=rr;var n=nr;nr=e.responseState;try{var i,s=e.pingedTasks;for(i=0;i<s.length;i++){var a=s[i],o=e,l=a.blockedSegment;if(0===l.status){Lt(a.context);try{gr(o,a,a.node),l.lastPushedText&&l.textEmbedded&&l.chunks.push(N),a.abortSet.delete(a),l.status=1,Er(o,a.blockedBoundary,l)}catch(e){if(qt(),"object"==typeof e&&null!==e&&"function"==typeof e.then){var u=a.ping;e.then(u,u)}else{a.abortSet.delete(a),l.status=4;var c=a.blockedBoundary,d=e,h=ur(o,d);if(null===c?cr(o,d):(c.pendingTasks--,c.forceClientRender||(c.forceClientRender=!0,c.errorDigest=h,c.parentFlushed&&o.clientRenderedBoundaries.push(c))),o.allPendingTasks--,0===o.allPendingTasks)(0,o.onAllReady)()}}}}s.splice(0,i),null!==e.destination&&Lr(e,e.destination)}catch(t){ur(e,t),cr(e,t)}finally{nr=n,ir.current=r,r===rr&&Lt(t)}}}function Tr(e,r,n){switch(n.parentFlushed=!0,n.status){case 0:var a=n.id=e.nextSegmentId++;return n.lastPushedText=!1,n.textEmbedded=!1,e=e.responseState,i(r,oe),i(r,e.placeholderPrefix),i(r,e=u(a.toString(16))),s(r,le);case 1:n.status=2;var o=!0;a=n.chunks;var l=0;n=n.children;for(var c=0;c<n.length;c++){for(o=n[c];l<o.index;l++)i(r,a[l]);o=xr(e,r,o)}for(;l<a.length-1;l++)i(r,a[l]);return l<a.length&&(o=s(r,a[l])),o;default:throw Error(t(390))}}function xr(e,r,n){var a=n.boundary;if(null===a)return Tr(e,r,n);if(a.parentFlushed=!0,a.forceClientRender)a=a.errorDigest,s(r,he),i(r,pe),a&&(i(r,me),i(r,u(x(a))),i(r,ge)),s(r,ve),Tr(e,r,n);else if(0<a.pendingTasks){a.rootSegmentID=e.nextSegmentId++,0<a.completedSegments.length&&e.partialBoundaries.push(a);var o=e.responseState,l=o.nextSuspenseID++;o=c(o.boundaryPrefix+l.toString(16)),a=a.id=o,ye(r,e.responseState,a),Tr(e,r,n)}else if(a.byteSize>e.progressiveChunkSize)a.rootSegmentID=e.nextSegmentId++,e.completedBoundaries.push(a),ye(r,e.responseState,a.id),Tr(e,r,n);else{if(s(r,ue),1!==(n=a.completedSegments).length)throw Error(t(391));xr(e,r,n[0])}return s(r,fe)}function kr(e,r,n){return function(e,r,n,a){switch(n.insertionMode){case 0:case 1:return i(e,be),i(e,r.segmentPrefix),i(e,u(a.toString(16))),s(e,we);case 2:return i(e,Se),i(e,r.segmentPrefix),i(e,u(a.toString(16))),s(e,Te);case 3:return i(e,ke),i(e,r.segmentPrefix),i(e,u(a.toString(16))),s(e,Ae);case 4:return i(e,Le),i(e,r.segmentPrefix),i(e,u(a.toString(16))),s(e,Ie);case 5:return i(e,Pe),i(e,r.segmentPrefix),i(e,u(a.toString(16))),s(e,De);case 6:return i(e,Me),i(e,r.segmentPrefix),i(e,u(a.toString(16))),s(e,Oe);case 7:return i(e,Fe),i(e,r.segmentPrefix),i(e,u(a.toString(16))),s(e,$e);default:throw Error(t(397))}}(r,e.responseState,n.formatContext,n.id),xr(e,r,n),function(e,r){switch(r.insertionMode){case 0:case 1:return s(e,Ee);case 2:return s(e,xe);case 3:return s(e,Re);case 4:return s(e,Ce);case 5:return s(e,_e);case 6:return s(e,Ne);case 7:return s(e,Be);default:throw Error(t(397))}}(r,n.formatContext)}function Ar(e,r,n){for(var a=n.completedSegments,o=0;o<a.length;o++)Rr(e,r,n,a[o]);if(a.length=0,e=e.responseState,a=n.id,n=n.rootSegmentID,i(r,e.startInlineScript),e.sentCompleteBoundaryFunction?i(r,Ve):(e.sentCompleteBoundaryFunction=!0,i(r,He)),null===a)throw Error(t(395));return n=u(n.toString(16)),i(r,a),i(r,We),i(r,e.segmentPrefix),i(r,n),s(r,Ke)}function Rr(e,r,n,a){if(2===a.status)return!0;var o=a.id;if(-1===o){if(-1===(a.id=n.rootSegmentID))throw Error(t(392));return kr(e,r,a)}return kr(e,r,a),i(r,(e=e.responseState).startInlineScript),e.sentCompleteSegmentFunction?i(r,ze):(e.sentCompleteSegmentFunction=!0,i(r,Ue)),i(r,e.segmentPrefix),i(r,o=u(o.toString(16))),i(r,je),i(r,e.placeholderPrefix),i(r,o),s(r,Ge)}function Lr(e,o){r=new Uint8Array(512),n=0;try{var l=e.completedRootSegment;if(null!==l&&0===e.pendingRootTasks){xr(e,o,l),e.completedRootSegment=null;var c=e.responseState.bootstrapChunks;for(l=0;l<c.length-1;l++)i(o,c[l]);l<c.length&&s(o,c[l])}var d,h=e.clientRenderedBoundaries;for(d=0;d<h.length;d++){var f=h[d];c=o;var p=e.responseState,g=f.id,m=f.errorDigest,v=f.errorMessage,y=f.errorComponentStack;if(i(c,p.startInlineScript),p.sentClientRenderFunction?i(c,qe):(p.sentClientRenderFunction=!0,i(c,Ye)),null===g)throw Error(t(395));i(c,g),i(c,Xe),(m||v||y)&&(i(c,Ze),i(c,u(et(m||"")))),(v||y)&&(i(c,Ze),i(c,u(et(v||"")))),y&&(i(c,Ze),i(c,u(et(y)))),s(c,Qe)}h.splice(0,d);var b=e.completedBoundaries;for(d=0;d<b.length;d++)Ar(e,o,b[d]);b.splice(0,d),a(o),r=new Uint8Array(512),n=0;var w=e.partialBoundaries;for(d=0;d<w.length;d++){var E=w[d];e:{h=e,f=o;var S=E.completedSegments;for(p=0;p<S.length;p++)if(!Rr(h,f,E,S[p])){p++,S.splice(0,p);var T=!1;break e}S.splice(0,p),T=!0}if(!T)return e.destination=null,d++,void w.splice(0,d)}w.splice(0,d);var x=e.completedBoundaries;for(d=0;d<x.length;d++)Ar(e,o,x[d]);x.splice(0,d)}finally{a(o),0===e.allPendingTasks&&0===e.pingedTasks.length&&0===e.clientRenderedBoundaries.length&&0===e.completedBoundaries.length&&o.close()}}function Ir(e,t){try{var r=e.abortableTasks;r.forEach(function(r){return br(r,e,t)}),r.clear(),null!==e.destination&&Lr(e,e.destination)}catch(t){ur(e,t),cr(e,t)}}return Fu.renderToReadableStream=function(e,t){return new Promise(function(r,n){var i,s,a=new Promise(function(e,t){s=e,i=t}),o=function(e,t,r,n,i,s,a,o,l){var u=[],c=new Set;return(r=lr(t={destination:null,responseState:t,progressiveChunkSize:void 0===n?12800:n,status:0,fatalError:null,nextSegmentId:0,allPendingTasks:0,pendingRootTasks:0,completedRootSegment:null,abortableTasks:c,pingedTasks:u,clientRenderedBoundaries:[],completedBoundaries:[],partialBoundaries:[],onError:void 0===i?sr:i,onAllReady:void 0===s?ar:s,onShellReady:void 0===a?ar:a,onShellError:void 0===o?ar:o,onFatalError:void 0===l?ar:l},0,null,r,!1,!1)).parentFlushed=!0,e=or(t,e,null,r,c,wt,null,Pt),u.push(e),t}(e,function(e,t,r,n,i){e=void 0===e?"":e,t=void 0===t?L:c('<script nonce="'+x(t)+'">');var s=[];if(void 0!==r&&s.push(t,u((""+r).replace(_,M)),I),void 0!==n)for(r=0;r<n.length;r++)s.push(C,u(x(n[r])),D);if(void 0!==i)for(n=0;n<i.length;n++)s.push(P,u(x(i[n])),D);return{bootstrapChunks:s,startInlineScript:t,placeholderPrefix:c(e+"P:"),segmentPrefix:c(e+"S:"),boundaryPrefix:e+"B:",idPrefix:e,nextSuspenseID:0,sentCompleteSegmentFunction:!1,sentCompleteBoundaryFunction:!1,sentClientRenderFunction:!1}}(t?t.identifierPrefix:void 0,t?t.nonce:void 0,t?t.bootstrapScriptContent:void 0,t?t.bootstrapScripts:void 0,t?t.bootstrapModules:void 0),function(e){return O("http://www.w3.org/2000/svg"===e?2:"http://www.w3.org/1998/Math/MathML"===e?3:0,null)}(t?t.namespaceURI:void 0),t?t.progressiveChunkSize:void 0,t?t.onError:void 0,s,function(){var e=new ReadableStream({type:"bytes",pull:function(e){if(1===o.status)o.status=2,d(e,o.fatalError);else if(2!==o.status&&null===o.destination){o.destination=e;try{Lr(o,e)}catch(e){ur(o,e),cr(o,e)}}},cancel:function(){Ir(o)}},{highWaterMark:0});e.allReady=a,r(e)},function(e){a.catch(function(){}),n(e)},i);if(t&&t.signal){var l=t.signal,h=function(){Ir(o,l.reason),l.removeEventListener("abort",h)};l.addEventListener("abort",h)}Sr(o)})},Fu.version="18.3.1",Fu}var Bu,Uu,zu,ju,Gu,Hu=function(){return Nu||(Nu=1,e=Mu(),t=$u(),Du.version=e.version,Du.renderToString=e.renderToString,Du.renderToStaticMarkup=e.renderToStaticMarkup,Du.renderToNodeStream=e.renderToNodeStream,Du.renderToStaticNodeStream=e.renderToStaticNodeStream,Du.renderToReadableStream=t.renderToReadableStream),Du;var e,t}(),Vu={exports:{}};function Wu(){if(Uu)return Bu;Uu=1;return Bu="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"}function Ku(){if(ju)return zu;ju=1;var e=Wu();function t(){}function r(){}return r.resetWarningCache=t,zu=function(){function n(t,r,n,i,s,a){if(a!==e){var o=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw o.name="Invariant Violation",o}}function i(){return n}n.isRequired=n;var s={array:n,bigint:n,bool:n,func:n,number:n,object:n,string:n,symbol:n,any:n,arrayOf:i,element:n,elementType:n,instanceOf:i,node:n,objectOf:i,oneOf:i,oneOfType:i,shape:i,exact:i,checkPropTypes:r,resetWarningCache:t};return s.PropTypes=s,s}}function Yu(){return Gu||(Gu=1,Vu.exports=Ku()()),Vu.exports}var qu=t(Yu()),Xu="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Qu(e,t){return e(t={exports:{}},t.exports),t.exports}var Zu=Qu(function(e){!function(t){var r=function(e,t,n){if(!l(t)||c(t)||d(t)||h(t)||o(t))return t;var i,s=0,a=0;if(u(t))for(i=[],a=t.length;s<a;s++)i.push(r(e,t[s],n));else for(var f in i={},t)Object.prototype.hasOwnProperty.call(t,f)&&(i[e(f,n)]=r(e,t[f],n));return i},n=function(e){return f(e)?e:(e=e.replace(/[\-_\s]+(.)?/g,function(e,t){return t?t.toUpperCase():""})).substr(0,1).toLowerCase()+e.substr(1)},i=function(e){var t=n(e);return t.substr(0,1).toUpperCase()+t.substr(1)},s=function(e,t){return function(e,t){var r=(t=t||{}).separator||"_",n=t.split||/(?=[A-Z])/;return e.split(n).join(r)}(e,t).toLowerCase()},a=Object.prototype.toString,o=function(e){return"function"==typeof e},l=function(e){return e===Object(e)},u=function(e){return"[object Array]"==a.call(e)},c=function(e){return"[object Date]"==a.call(e)},d=function(e){return"[object RegExp]"==a.call(e)},h=function(e){return"[object Boolean]"==a.call(e)},f=function(e){return(e-=0)==e},p=function(e,t){var r=t&&"process"in t?t.process:t;return"function"!=typeof r?e:function(t,n){return r(t,e,n)}},g={camelize:n,decamelize:s,pascalize:i,depascalize:s,camelizeKeys:function(e,t){return r(p(n,t),e)},decamelizeKeys:function(e,t){return r(p(s,t),e,t)},pascalizeKeys:function(e,t){return r(p(i,t),e)},depascalizeKeys:function(){return this.decamelizeKeys.apply(this,arguments)}};e.exports?e.exports=g:t.humps=g}(Xu)}).decamelize,Ju=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n},ec=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e)){var r=[],n=!0,i=!1,s=void 0;try{for(var a,o=e[Symbol.iterator]();!(n=(a=o.next()).done)&&(r.push(a.value),!t||r.length!==t);n=!0);}catch(e){i=!0,s=e}finally{try{n||null==o.return||o.return()}finally{if(i)throw s}}return r}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Ju(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Ju(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()},tc=Qu(function(e){function t(){return e.exports=t=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},t.apply(this,arguments)}e.exports=t}),rc=function(e,t){if(null==e)return{};var r,n,i=function(e,t){if(null==e)return{};var r,n,i={},s=Object.keys(e);for(n=0;n<s.length;n++)r=s[n],t.indexOf(r)>=0||(i[r]=e[r]);return i}(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(n=0;n<s.length;n++)r=s[n],t.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(i[r]=e[r])}return i},nc=p.createContext(null);function ic(e){var t=e.children,r=void 0===t?"":t,n=rc(e,["children"]);return"string"!=typeof r&&(r=Hu.renderToString(r)),g.createElement("template",tc({},n,{dangerouslySetInnerHTML:{__html:r}}))}function sc(e){var t=e.root,r=e.children;return Pi.createPortal(void 0===r?null:r,t)}ic.propTypes={children:qu.oneOfType([qu.string,qu.node])},sc.propTypes={root:qu.object.isRequired,children:qu.node};var ac=new Map;var oc=function(){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"core",t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(e){return e.children};return new Proxy(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{get:function(r,n){var i=Zu(n,{separator:"-"}),s="".concat(e,"-").concat(i);return ac.has(s)||ac.set(s,function(e){var t=p.forwardRef(function(t,r){var n,i,s=t.mode,a=void 0===s?"open":s,o=t.delegatesFocus,l=void 0!==o&&o,u=t.styleSheets,c=void 0===u?[]:u,d=t.ssr,h=void 0!==d&&d,f=t.children,m=rc(t,["mode","delegatesFocus","styleSheets","ssr","children"]),v=(i=p.useRef((n=r)&&n.current),p.useEffect(function(){n&&(n.current=i.current)},[n]),i),y=p.useState(null),b=ec(y,2),w=b[0],E=b[1],S="node_".concat(a).concat(l);return p.useLayoutEffect(function(){if(v.current)try{if("function"==typeof r&&r(v.current),h){var e=v.current.shadowRoot;return void E(e)}var t=v.current.attachShadow({mode:a,delegatesFocus:l});c.length>0&&(t.adoptedStyleSheets=c),E(t)}catch(e){!function(e){var t=e.error,r=e.styleSheets,n=e.root;if("NotSupportedError"!==t.name)throw t;r.length>0&&(n.adoptedStyleSheets=r)}({error:e,styleSheets:c,root:w})}},[r,v,c]),g.createElement(g.Fragment,null,g.createElement(e.tag,tc({key:S,ref:v},m),(w||h)&&g.createElement(nc.Provider,{value:w},h?g.createElement(ic,{shadowroot:a,shadowrootmode:a},e.render({root:w,ssr:h,children:f})):g.createElement(sc,{root:w},e.render({root:w,ssr:h,children:f})))))});return t.propTypes={mode:qu.oneOf(["open","closed"]),delegatesFocus:qu.bool,styleSheets:qu.arrayOf(qu.instanceOf(globalThis.CSSStyleSheet)),ssr:qu.bool,children:qu.node},t}({tag:i,render:t})),ac.get(s)}})}();const lc='/*! tailwindcss v4.0.12 | MIT License | https://tailwindcss.com */@layer theme, base, components, utilities;@layer theme{:host,:root{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-500:oklch(0.637 0.237 25.331);--color-blue-200:oklch(0.882 0.059 254.128);--color-blue-300:oklch(0.809 0.105 251.813);--color-gray-200:oklch(0.928 0.006 264.531);--color-gray-400:oklch(0.707 0.022 261.325);--color-gray-500:oklch(0.551 0.027 264.364);--color-gray-700:oklch(0.373 0.034 259.733);--color-gray-800:oklch(0.278 0.033 256.848);--color-gray-900:oklch(0.21 0.034 264.665);--color-zinc-700:oklch(0.37 0.013 285.805);--color-black:#000;--color-white:#fff;--spacing:0.25rem;--container-sm:24rem;--container-lg:32rem;--text-xs:0.75rem;--text-xs--line-height:1.33333;--text-sm:0.875rem;--text-sm--line-height:1.42857;--text-lg:1.125rem;--text-lg--line-height:1.55556;--text-xl:1.25rem;--text-xl--line-height:1.4;--font-weight-medium:500;--font-weight-semibold:600;--leading-tight:1.25;--ease-in:cubic-bezier(0.4,0,1,1);--ease-in-out:cubic-bezier(0.4,0,0.2,1);--animate-pulse:pulse 2s cubic-bezier(0.4,0,0.6,1) infinite;--aspect-video:16/9;--default-transition-duration:150ms;--default-transition-timing-function:cubic-bezier(0.4,0,0.2,1);--default-font-family:var(--font-sans);--default-font-feature-settings:var(--font-sans--font-feature-settings);--default-font-variation-settings:var(\n --font-sans--font-variation-settings\n );--default-mono-font-family:var(--font-mono);--default-mono-font-feature-settings:var(\n --font-mono--font-feature-settings\n );--default-mono-font-variation-settings:var(\n --font-mono--font-variation-settings\n );--animate-float:float 2s ease}}@layer base{*,::backdrop,::file-selector-button,:after,:before{border:0 solid;box-sizing:border-box;margin:0;padding:0}:host,html{-webkit-text-size-adjust:100%;font-feature-settings:var(--default-font-feature-settings,normal);-webkit-tap-highlight-color:transparent;font-family:var( --default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji" );font-variation-settings:var( --default-font-variation-settings,normal );line-height:1.5;tab-size:4}body{line-height:inherit}hr{border-top-width:1px;color:inherit;height:0}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-feature-settings:var( --default-mono-font-feature-settings,normal );font-family:var( --default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace );font-size:1em;font-variation-settings:var( --default-mono-font-variation-settings,normal )}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{border-collapse:collapse;border-color:inherit;text-indent:0}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}menu,ol,ul{list-style:none}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{height:auto;max-width:100%}::file-selector-button,button,input,optgroup,select,textarea{font-feature-settings:inherit;background-color:transparent;border-radius:0;color:inherit;font:inherit;font-variation-settings:inherit;letter-spacing:inherit;opacity:1}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{color:color-mix(in oklab,currentColor 50%,transparent);opacity:1}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit,::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-meridiem-field,::-webkit-datetime-edit-millisecond-field,::-webkit-datetime-edit-minute-field,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-second-field,::-webkit-datetime-edit-year-field{padding-block:0}:-moz-ui-invalid{box-shadow:none}::file-selector-button,button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer utilities{.pointer-events-none{pointer-events:none}.visible{visibility:visible}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.inset-0{inset:calc(var(--spacing)*0)}.top-0{top:calc(var(--spacing)*0)}.top-4{top:calc(var(--spacing)*4)}.right-4{right:calc(var(--spacing)*4)}.bottom-0{bottom:calc(var(--spacing)*0)}.left-0{left:calc(var(--spacing)*0)}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\\[1\\]{z-index:1}.z-\\[5\\]{z-index:5}.z-\\[999\\]{z-index:999}.z-\\[999999\\]{z-index:999999}.container{width:100%;@media (width >= 40rem){max-width:40rem}@media (width >= 48rem){max-width:48rem}@media (width >= 64rem){max-width:64rem}@media (width >= 80rem){max-width:80rem}@media (width >= 96rem){max-width:96rem}}.mx-0{margin-inline:calc(var(--spacing)*0)}.mx-10{margin-inline:calc(var(--spacing)*10)}.mx-auto{margin-inline:auto}.my-0{margin-block:calc(var(--spacing)*0)}.my-2{margin-block:calc(var(--spacing)*2)}.my-10{margin-block:calc(var(--spacing)*10)}.mt-2{margin-top:calc(var(--spacing)*2)}.mt-3{margin-top:calc(var(--spacing)*3)}.mt-4{margin-top:calc(var(--spacing)*4)}.mt-auto{margin-top:auto}.mr-2{margin-right:calc(var(--spacing)*2)}.mb-1{margin-bottom:calc(var(--spacing)*1)}.mb-2{margin-bottom:calc(var(--spacing)*2)}.mb-3{margin-bottom:calc(var(--spacing)*3)}.line-clamp-1{-webkit-line-clamp:1}.line-clamp-1,.line-clamp-2{-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.line-clamp-2{-webkit-line-clamp:2}.block{display:block}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.table{display:table}.aspect-\\[9\\/16\\]{aspect-ratio:9/16}.aspect-square{aspect-ratio:1/1}.aspect-video{aspect-ratio:var(--aspect-video)}.size-3{height:calc(var(--spacing)*3);width:calc(var(--spacing)*3)}.size-4{height:calc(var(--spacing)*4);width:calc(var(--spacing)*4)}.h-1{height:calc(var(--spacing)*1)}.h-2{height:calc(var(--spacing)*2)}.h-3\\.5{height:calc(var(--spacing)*3.5)}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-6{height:calc(var(--spacing)*6)}.h-10{height:calc(var(--spacing)*10)}.h-12{height:calc(var(--spacing)*12)}.h-14{height:calc(var(--spacing)*14)}.h-16{height:calc(var(--spacing)*16)}.h-\\[24px\\]{height:24px}.h-\\[60px\\]{height:60px}.h-\\[80\\%\\]{height:80%}.h-\\[100px\\]{height:100px}.h-\\[125px\\]{height:125px}.h-\\[500px\\]{height:500px}.h-\\[600px\\]{height:600px}.h-auto{height:auto}.h-full{height:100%}.max-h-\\[150px\\]{max-height:150px}.max-h-\\[300px\\]{max-height:300px}.max-h-fit{max-height:fit-content}.max-h-full{max-height:100%}.\\!w-auto{width:auto!important}.w-4{width:calc(var(--spacing)*4)}.w-4\\/5{width:80%}.w-12{width:calc(var(--spacing)*12)}.w-14{width:calc(var(--spacing)*14)}.w-16{width:calc(var(--spacing)*16)}.w-32{width:calc(var(--spacing)*32)}.w-36{width:calc(var(--spacing)*36)}.w-\\[24px\\]{width:24px}.w-\\[50px\\]{width:50px}.w-\\[80\\%\\]{width:80%}.w-\\[100px\\]{width:100px}.w-\\[400px\\]{width:400px}.w-\\[500px\\]{width:500px}.w-\\[1024px\\]{width:1024px}.w-full{width:100%}.max-w-16{max-width:calc(var(--spacing)*16)}.max-w-52{max-width:calc(var(--spacing)*52)}.max-w-\\[40\\%\\]{max-width:40%}.max-w-\\[800px\\]{max-width:800px}.max-w-fit{max-width:fit-content}.max-w-full{max-width:100%}.max-w-lg{max-width:var(--container-lg)}.max-w-none{max-width:none}.min-w-0{min-width:calc(var(--spacing)*0)}.min-w-44{min-width:calc(var(--spacing)*44)}.min-w-\\[768px\\]{min-width:768px}.flex-1{flex:1}.flex-\\[2\\]{flex:2}.flex-none{flex:none}.flex-shrink-0,.shrink-0{flex-shrink:0}.grow{flex-grow:1}.border-collapse{border-collapse:collapse}.translate-y-0\\.5{--tw-translate-y:calc(var(--spacing)*0.5);translate:var(--tw-translate-x) var(--tw-translate-y)}.transform{transform:var(--tw-rotate-x) var(--tw-rotate-y) var(--tw-rotate-z) var(--tw-skew-x) var(--tw-skew-y)}.animate-float{animation:var(--animate-float)}.animate-pulse{animation:var(--animate-pulse)}.cursor-default{cursor:default}.cursor-pointer{cursor:pointer}.touch-none{touch-action:none}.resize{resize:both}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.flex-wrap{flex-wrap:wrap}.items-baseline{align-items:baseline}.items-center{align-items:center}.items-end{align-items:flex-end}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.justify-items-center{justify-items:center}.gap-1{gap:calc(var(--spacing)*1)}.gap-1\\.5{gap:calc(var(--spacing)*1.5)}.gap-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}.gap-5{gap:calc(var(--spacing)*5)}.gap-10{gap:calc(var(--spacing)*10)}.self-center{align-self:center}.justify-self-end{justify-self:flex-end}.truncate{text-overflow:ellipsis;white-space:nowrap}.overflow-hidden,.truncate{overflow:hidden}.overflow-scroll{overflow:scroll}.overflow-y-auto{overflow-y:auto}.overflow-y-scroll{overflow-y:scroll}.rounded{border-radius:.25rem}.rounded-full{border-radius:calc(infinity * 1px)}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-xl{border-radius:calc(var(--radius) + 4px)}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-none{--tw-border-style:none;border-style:none}.border-\\[\\#f4f3f6\\]{border-color:#f4f3f6}.bg-\\[\\#0ab060\\]{background-color:#0ab060}.bg-\\[\\#eeeeee\\]{background-color:#eee}.bg-\\[\\#f4f4f4\\]{background-color:#f4f4f4}.bg-\\[rgba\\(0\\,0\\,0\\,\\.3\\)\\]{background-color:rgba(0,0,0,.3)}.bg-background{background-color:var(--background)}.bg-black{background-color:var(--color-black)}.bg-black\\/50{background-color:color-mix(in oklab,var(--color-black) 50%,transparent)}.bg-blue-200{background-color:var(--color-blue-200)}.bg-blue-300{background-color:var(--color-blue-300)}.bg-gray-200{background-color:var(--color-gray-200)}.bg-muted{background-color:var(--muted)}.bg-white{background-color:var(--color-white)}.bg-zinc-700{background-color:var(--color-zinc-700)}.bg-gradient-to-b{--tw-gradient-position:to bottom in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.from-black\\/40{--tw-gradient-from:color-mix(in oklab,var(--color-black) 40%,transparent);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from) var(--tw-gradient-from-position),var(--tw-gradient-to) var(--tw-gradient-to-position))}.via-transparent{--tw-gradient-via:transparent;--tw-gradient-via-stops:var(--tw-gradient-position),var(--tw-gradient-from) var(--tw-gradient-from-position),var(--tw-gradient-via) var(--tw-gradient-via-position),var(--tw-gradient-to) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.to-black\\/40{--tw-gradient-to:color-mix(in oklab,var(--color-black) 40%,transparent);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from) var(--tw-gradient-from-position),var(--tw-gradient-to) var(--tw-gradient-to-position))}.fill-black{fill:var(--color-black)}.fill-red-500{fill:var(--color-red-500)}.fill-white{fill:var(--color-white)}.object-contain{object-fit:contain}.object-cover{object-fit:cover}.object-center{object-position:center}.p-0{padding:calc(var(--spacing)*0)}.p-1{padding:calc(var(--spacing)*1)}.p-2{padding:calc(var(--spacing)*2)}.p-4{padding:calc(var(--spacing)*4)}.p-6{padding:calc(var(--spacing)*6)}.p-10{padding:calc(var(--spacing)*10)}.p-\\[3px\\]{padding:3px}.px-2{padding-inline:calc(var(--spacing)*2)}.px-4{padding-inline:calc(var(--spacing)*4)}.px-\\[24px\\]{padding-inline:24px}.py-2{padding-block:calc(var(--spacing)*2)}.py-4{padding-block:calc(var(--spacing)*4)}.pt-0{padding-top:calc(var(--spacing)*0)}.pr-1{padding-right:calc(var(--spacing)*1)}.pb-4{padding-bottom:calc(var(--spacing)*4)}.pb-10{padding-bottom:calc(var(--spacing)*10)}.text-center{text-align:center}.text-left{text-align:left}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\\[10px\\]{font-size:10px}.text-\\[12px\\]{font-size:12px}.leading-none{--tw-leading:1;line-height:1}.leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.break-keep{word-break:keep-all}.text-clip{text-overflow:clip}.text-ellipsis{text-overflow:ellipsis}.whitespace-nowrap{white-space:nowrap}.text-black{color:var(--color-black)}.text-foreground{color:var(--foreground)}.text-gray-400{color:var(--color-gray-400)}.text-gray-500{color:var(--color-gray-500)}.text-gray-700{color:var(--color-gray-700)}.text-gray-800{color:var(--color-gray-800)}.text-gray-900{color:var(--color-gray-900)}.text-muted-foreground{color:var(--muted-foreground)}.text-red-500{color:var(--color-red-500)}.text-transparent{color:transparent}.text-white{color:var(--color-white)}.line-through{text-decoration-line:line-through}.no-underline{text-decoration-line:none}.opacity-50{opacity:50%}.opacity-70{opacity:70%}.shadow,.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,rgba(0,0,0,.1)),0 1px 2px -1px var(--tw-shadow-color,rgba(0,0,0,.1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-ring\\/30{--tw-ring-color:color-mix(in oklab,var(--ring) 30%,transparent)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.transition{transition-duration:var(--tw-duration,var(--default-transition-duration));transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function))}.transition-\\[color\\,box-shadow\\]{transition-duration:var(--tw-duration,var(--default-transition-duration));transition-property:color,box-shadow;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function))}.transition-all{transition-duration:var(--tw-duration,var(--default-transition-duration));transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function))}.transition-opacity{transition-duration:var(--tw-duration,var(--default-transition-duration));transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function))}.transition-transform{transition-duration:var(--tw-duration,var(--default-transition-duration));transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function))}.duration-200{--tw-duration:200ms;transition-duration:.2s}.ease-in{--tw-ease:var(--ease-in);transition-timing-function:var(--ease-in)}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.outline-none{--tw-outline-style:none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}.duration-200{animation-duration:.2s}.ease-in{animation-timing-function:cubic-bezier(.4,0,1,1)}.ease-in-out{animation-timing-function:cubic-bezier(.4,0,.2,1)}.fade-in{--tw-enter-opacity:0}.group-data-\\[vaul-drawer-direction\\=bottom\\]\\/drawer-content\\:block{&:is(:where(.group\\/drawer-content)[data-vaul-drawer-direction=bottom] *){display:block}}.last\\:border-b-0{&:last-child{border-bottom-style:var(--tw-border-style);border-bottom-width:0}}.hover\\:underline{&:hover{@media (hover:hover){text-decoration-line:underline}}}.hover\\:opacity-100{&:hover{@media (hover:hover){opacity:100%}}}.hover\\:ring-4{&:hover{@media (hover:hover){--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentColor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}}.focus\\:ring-2{&:focus{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentColor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}.focus\\:ring-ring{&:focus{--tw-ring-color:var(--ring)}}.focus\\:ring-offset-2{&:focus{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}}.focus\\:ring-offset-background{&:focus{--tw-ring-offset-color:var(--background)}}.focus\\:outline-none{&:focus{--tw-outline-style:none;outline-style:none}}.focus-visible\\:border-ring{&:focus-visible{border-color:var(--ring)}}.focus-visible\\:ring-4{&:focus-visible{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentColor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}.focus-visible\\:ring-\\[3px\\]{&:focus-visible{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentColor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}.focus-visible\\:ring-ring\\/50{&:focus-visible{--tw-ring-color:color-mix(in oklab,var(--ring) 50%,transparent)}}.focus-visible\\:outline-hidden{&:focus-visible{--tw-outline-style:none;outline-style:none;@media (forced-colors:active){outline:2px solid transparent;outline-offset:2px}}}.disabled\\:pointer-events-none{&:disabled{pointer-events:none}}.disabled\\:opacity-50{&:disabled{opacity:50%}}.data-\\[disabled\\]\\:opacity-50{&[data-disabled]{opacity:50%}}.data-\\[orientation\\=horizontal\\]\\:h-1\\.5{&[data-orientation=horizontal]{height:calc(var(--spacing)*1.5)}}.data-\\[orientation\\=horizontal\\]\\:h-full{&[data-orientation=horizontal]{height:100%}}.data-\\[orientation\\=horizontal\\]\\:w-full{&[data-orientation=horizontal]{width:100%}}.data-\\[orientation\\=vertical\\]\\:h-full{&[data-orientation=vertical]{height:100%}}.data-\\[orientation\\=vertical\\]\\:min-h-44{&[data-orientation=vertical]{min-height:calc(var(--spacing)*44)}}.data-\\[orientation\\=vertical\\]\\:w-1\\.5{&[data-orientation=vertical]{width:calc(var(--spacing)*1.5)}}.data-\\[orientation\\=vertical\\]\\:w-auto{&[data-orientation=vertical]{width:auto}}.data-\\[orientation\\=vertical\\]\\:w-full{&[data-orientation=vertical]{width:100%}}.data-\\[orientation\\=vertical\\]\\:flex-col{&[data-orientation=vertical]{flex-direction:column}}.data-\\[state\\=closed\\]\\:animate-out{&[data-state=closed]{--tw-exit-opacity:initial;--tw-exit-scale:initial;--tw-exit-rotate:initial;--tw-exit-translate-x:initial;--tw-exit-translate-y:initial;animation-duration:.15s;animation-name:exit}}.data-\\[state\\=closed\\]\\:fade-out-0{&[data-state=closed]{--tw-exit-opacity:0}}.data-\\[state\\=open\\]\\:animate-in{&[data-state=open]{--tw-enter-opacity:initial;--tw-enter-scale:initial;--tw-enter-rotate:initial;--tw-enter-translate-x:initial;--tw-enter-translate-y:initial;animation-duration:.15s;animation-name:enter}}.data-\\[state\\=open\\]\\:fade-in-0{&[data-state=open]{--tw-enter-opacity:0}}.data-\\[vaul-drawer-direction\\=bottom\\]\\:inset-x-0{&[data-vaul-drawer-direction=bottom]{inset-inline:calc(var(--spacing)*0)}}.data-\\[vaul-drawer-direction\\=bottom\\]\\:bottom-0{&[data-vaul-drawer-direction=bottom]{bottom:calc(var(--spacing)*0)}}.data-\\[vaul-drawer-direction\\=bottom\\]\\:mt-24{&[data-vaul-drawer-direction=bottom]{margin-top:calc(var(--spacing)*24)}}.data-\\[vaul-drawer-direction\\=bottom\\]\\:max-h-\\[80vh\\]{&[data-vaul-drawer-direction=bottom]{max-height:80vh}}.data-\\[vaul-drawer-direction\\=bottom\\]\\:rounded-t-lg{&[data-vaul-drawer-direction=bottom]{border-top-left-radius:var(--radius);border-top-right-radius:var(--radius)}}.data-\\[vaul-drawer-direction\\=bottom\\]\\:border-t{&[data-vaul-drawer-direction=bottom]{border-top-style:var(--tw-border-style);border-top-width:1px}}.data-\\[vaul-drawer-direction\\=left\\]\\:inset-y-0{&[data-vaul-drawer-direction=left]{inset-block:calc(var(--spacing)*0)}}.data-\\[vaul-drawer-direction\\=left\\]\\:left-0{&[data-vaul-drawer-direction=left]{left:calc(var(--spacing)*0)}}.data-\\[vaul-drawer-direction\\=left\\]\\:w-3\\/4{&[data-vaul-drawer-direction=left]{width:75%}}.data-\\[vaul-drawer-direction\\=left\\]\\:border-r{&[data-vaul-drawer-direction=left]{border-right-style:var(--tw-border-style);border-right-width:1px}}.data-\\[vaul-drawer-direction\\=right\\]\\:inset-y-0{&[data-vaul-drawer-direction=right]{inset-block:calc(var(--spacing)*0)}}.data-\\[vaul-drawer-direction\\=right\\]\\:right-0{&[data-vaul-drawer-direction=right]{right:calc(var(--spacing)*0)}}.data-\\[vaul-drawer-direction\\=right\\]\\:w-3\\/4{&[data-vaul-drawer-direction=right]{width:75%}}.data-\\[vaul-drawer-direction\\=right\\]\\:border-l{&[data-vaul-drawer-direction=right]{border-left-style:var(--tw-border-style);border-left-width:1px}}.data-\\[vaul-drawer-direction\\=top\\]\\:inset-x-0{&[data-vaul-drawer-direction=top]{inset-inline:calc(var(--spacing)*0)}}.data-\\[vaul-drawer-direction\\=top\\]\\:top-0{&[data-vaul-drawer-direction=top]{top:calc(var(--spacing)*0)}}.data-\\[vaul-drawer-direction\\=top\\]\\:mb-24{&[data-vaul-drawer-direction=top]{margin-bottom:calc(var(--spacing)*24)}}.data-\\[vaul-drawer-direction\\=top\\]\\:max-h-\\[80vh\\]{&[data-vaul-drawer-direction=top]{max-height:80vh}}.data-\\[vaul-drawer-direction\\=top\\]\\:rounded-b-lg{&[data-vaul-drawer-direction=top]{border-bottom-left-radius:var(--radius);border-bottom-right-radius:var(--radius)}}.data-\\[vaul-drawer-direction\\=top\\]\\:border-b{&[data-vaul-drawer-direction=top]{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}}.data-\\[vaul-drawer-direction\\=left\\]\\:sm\\:max-w-sm,.sm\\:flex-row,.sm\\:justify-end,.sm\\:mx-0{&[data-vaul-drawer-direction=left]{@media (width >= 40rem){max-width:var(--container-sm)}}}.data-\\[vaul-drawer-direction\\=right\\]\\:sm\\:max-w-sm{&[data-vaul-drawer-direction=right]{@media (width >= 40rem){max-width:var(--container-sm)}}}.\\[\\&\\[data-state\\=open\\]\\>svg\\]\\:rotate-180,.md\\:text-\\[15px\\]{&[data-state=open]>svg{rotate:180deg}}}body{--background:oklch(1 0 0);--foreground:oklch(0.145 0 0);--card:oklch(1 0 0);--card-foreground:oklch(0.145 0 0);--popover:oklch(1 0 0);--popover-foreground:oklch(0.145 0 0);--primary:oklch(0.205 0 0);--primary-foreground:oklch(0.985 0 0);--secondary:oklch(0.97 0 0);--secondary-foreground:oklch(0.205 0 0);--muted:oklch(0.97 0 0);--muted-foreground:oklch(0.556 0 0);--accent:oklch(0.97 0 0);--accent-foreground:oklch(0.205 0 0);--destructive:oklch(0.577 0.245 27.325);--destructive-foreground:oklch(0.577 0.245 27.325);--border:oklch(0.922 0 0);--input:oklch(0.922 0 0);--ring:oklch(0.708 0 0);--chart-1:oklch(0.646 0.222 41.116);--chart-2:oklch(0.6 0.118 184.704);--chart-3:oklch(0.398 0.07 227.392);--chart-4:oklch(0.828 0.189 84.429);--chart-5:oklch(0.769 0.188 70.08);--radius:0.625rem;--sidebar:oklch(0.985 0 0);--sidebar-foreground:oklch(0.145 0 0);--sidebar-primary:oklch(0.205 0 0);--sidebar-primary-foreground:oklch(0.985 0 0);--sidebar-accent:oklch(0.97 0 0);--sidebar-accent-foreground:oklch(0.205 0 0);--sidebar-border:oklch(0.922 0 0);--sidebar-ring:oklch(0.708 0 0);outline:none}.dark{--background:oklch(0.145 0 0);--foreground:oklch(0.985 0 0);--card:oklch(0.145 0 0);--card-foreground:oklch(0.985 0 0);--popover:oklch(0.145 0 0);--popover-foreground:oklch(0.985 0 0);--primary:oklch(0.985 0 0);--primary-foreground:oklch(0.205 0 0);--secondary:oklch(0.269 0 0);--secondary-foreground:oklch(0.985 0 0);--muted:oklch(0.269 0 0);--muted-foreground:oklch(0.708 0 0);--accent:oklch(0.269 0 0);--accent-foreground:oklch(0.985 0 0);--destructive:oklch(0.396 0.141 25.723);--destructive-foreground:oklch(0.637 0.237 25.331);--border:oklch(0.269 0 0);--input:oklch(0.269 0 0);--ring:oklch(0.439 0 0);--chart-1:oklch(0.488 0.243 264.376);--chart-2:oklch(0.696 0.17 162.48);--chart-3:oklch(0.769 0.188 70.08);--chart-4:oklch(0.627 0.265 303.9);--chart-5:oklch(0.645 0.246 16.439);--sidebar:oklch(0.205 0 0);--sidebar-foreground:oklch(0.985 0 0);--sidebar-primary:oklch(0.488 0.243 264.376);--sidebar-primary-foreground:oklch(0.985 0 0);--sidebar-accent:oklch(0.269 0 0);--sidebar-accent-foreground:oklch(0.985 0 0);--sidebar-border:oklch(0.269 0 0);--sidebar-ring:oklch(0.439 0 0)}@layer base{*{border-color:var(--border);outline-color:color-mix(in oklab,var(--ring) 50%,transparent)}body{background-color:var(--background);color:var(--foreground)}}html.overflow-hidden{overflow:hidden}.scrollbar-hide::-webkit-scrollbar{display:none}.scrollbar-hide{-ms-overflow-style:none;scrollbar-width:none}.bg-insta{background-image:linear-gradient(to top right,#facc15,#ec4899,#9333ea)}.product-banner{align-items:center;background:#fff;border-radius:8px;cursor:pointer;display:flex;gap:8px;position:relative}.product-banner__clip{border-radius:inherit;overflow:hidden}.product-banner__clip,.product-banner__sheen{inset:0;pointer-events:none;position:absolute;z-index:1}.product-banner__sheen{background:linear-gradient(270deg,rgba(0,0,0,.1),transparent);transform:translateX(100%);transition:transform .3s ease}.product-banner:hover .product-banner__sheen{transform:translateX(0)}.product-banner__arrow{opacity:0;pointer-events:none;position:absolute;right:8px;top:50%;transform:translate(4px,-50%);transition:transform .3s ease,opacity .3s ease;z-index:2}.product-banner:hover .product-banner__arrow{opacity:1;transform:translateY(-50%)}.product-dialog-container{max-height:70vh;max-width:min(82vw,500px);overflow-y:auto;width:100%}.border{border:1px solid oklch(.922 0 0)}@font-face{font-family:swiper-icons;font-style:normal;font-weight:400;src:url("data:application/font-woff;charset=utf-8;base64, d09GRgABAAAAAAZgABAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAAGRAAAABoAAAAci6qHkUdERUYAAAWgAAAAIwAAACQAYABXR1BPUwAABhQAAAAuAAAANuAY7+xHU1VCAAAFxAAAAFAAAABm2fPczU9TLzIAAAHcAAAASgAAAGBP9V5RY21hcAAAAkQAAACIAAABYt6F0cBjdnQgAAACzAAAAAQAAAAEABEBRGdhc3AAAAWYAAAACAAAAAj//wADZ2x5ZgAAAywAAADMAAAD2MHtryVoZWFkAAABbAAAADAAAAA2E2+eoWhoZWEAAAGcAAAAHwAAACQC9gDzaG10eAAAAigAAAAZAAAArgJkABFsb2NhAAAC0AAAAFoAAABaFQAUGG1heHAAAAG8AAAAHwAAACAAcABAbmFtZQAAA/gAAAE5AAACXvFdBwlwb3N0AAAFNAAAAGIAAACE5s74hXjaY2BkYGAAYpf5Hu/j+W2+MnAzMYDAzaX6QjD6/4//Bxj5GA8AuRwMYGkAPywL13jaY2BkYGA88P8Agx4j+/8fQDYfA1AEBWgDAIB2BOoAeNpjYGRgYNBh4GdgYgABEMnIABJzYNADCQAACWgAsQB42mNgYfzCOIGBlYGB0YcxjYGBwR1Kf2WQZGhhYGBiYGVmgAFGBiQQkOaawtDAoMBQxXjg/wEGPcYDDA4wNUA2CCgwsAAAO4EL6gAAeNpj2M0gyAACqxgGNWBkZ2D4/wMA+xkDdgAAAHjaY2BgYGaAYBkGRgYQiAHyGMF8FgYHIM3DwMHABGQrMOgyWDLEM1T9/w8UBfEMgLzE////P/5//f/V/xv+r4eaAAeMbAxwIUYmIMHEgKYAYjUcsDAwsLKxc3BycfPw8jEQA/gZBASFhEVExcQlJKWkZWTl5BUUlZRVVNXUNTQZBgMAAMR+E+gAEQFEAAAAKgAqACoANAA+AEgAUgBcAGYAcAB6AIQAjgCYAKIArAC2AMAAygDUAN4A6ADyAPwBBgEQARoBJAEuATgBQgFMAVYBYAFqAXQBfgGIAZIBnAGmAbIBzgHsAAB42u2NMQ6CUAyGW568x9AneYYgm4MJbhKFaExIOAVX8ApewSt4Bic4AfeAid3VOBixDxfPYEza5O+Xfi04YADggiUIULCuEJK8VhO4bSvpdnktHI5QCYtdi2sl8ZnXaHlqUrNKzdKcT8cjlq+rwZSvIVczNiezsfnP/uznmfPFBNODM2K7MTQ45YEAZqGP81AmGGcF3iPqOop0r1SPTaTbVkfUe4HXj97wYE+yNwWYxwWu4v1ugWHgo3S1XdZEVqWM7ET0cfnLGxWfkgR42o2PvWrDMBSFj/IHLaF0zKjRgdiVMwScNRAoWUoH78Y2icB/yIY09An6AH2Bdu/UB+yxopYshQiEvnvu0dURgDt8QeC8PDw7Fpji3fEA4z/PEJ6YOB5hKh4dj3EvXhxPqH/SKUY3rJ7srZ4FZnh1PMAtPhwP6fl2PMJMPDgeQ4rY8YT6Gzao0eAEA409DuggmTnFnOcSCiEiLMgxCiTI6Cq5DZUd3Qmp10vO0LaLTd2cjN4fOumlc7lUYbSQcZFkutRG7g6JKZKy0RmdLY680CDnEJ+UMkpFFe1RN7nxdVpXrC4aTtnaurOnYercZg2YVmLN/d/gczfEimrE/fs/bOuq29Zmn8tloORaXgZgGa78yO9/cnXm2BpaGvq25Dv9S4E9+5SIc9PqupJKhYFSSl47+Qcr1mYNAAAAeNptw0cKwkAAAMDZJA8Q7OUJvkLsPfZ6zFVERPy8qHh2YER+3i/BP83vIBLLySsoKimrqKqpa2hp6+jq6RsYGhmbmJqZSy0sraxtbO3sHRydnEMU4uR6yx7JJXveP7WrDycAAAAAAAH//wACeNpjYGRgYOABYhkgZgJCZgZNBkYGLQZtIJsFLMYAAAw3ALgAeNolizEKgDAQBCchRbC2sFER0YD6qVQiBCv/H9ezGI6Z5XBAw8CBK/m5iQQVauVbXLnOrMZv2oLdKFa8Pjuru2hJzGabmOSLzNMzvutpB3N42mNgZGBg4GKQYzBhYMxJLMlj4GBgAYow/P/PAJJhLM6sSoWKfWCAAwDAjgbRAAB42mNgYGBkAIIbCZo5IPrmUn0hGA0AO8EFTQAA")}:root{--swiper-theme-color:#007aff}:host{display:block;margin-left:auto;margin-right:auto;position:relative;z-index:1}.swiper{display:block;list-style:none;margin-left:auto;margin-right:auto;overflow:hidden;padding:0;position:relative;z-index:1}.swiper-vertical>.swiper-wrapper{flex-direction:column}.swiper-wrapper{box-sizing:content-box;display:flex;height:100%;position:relative;transition-property:transform;transition-timing-function:var(--swiper-wrapper-transition-timing-function,initial);width:100%;z-index:1}.swiper-android .swiper-slide,.swiper-ios .swiper-slide,.swiper-wrapper{transform:translateZ(0)}.swiper-horizontal{touch-action:pan-y}.swiper-vertical{touch-action:pan-x}.swiper-slide{display:block;flex-shrink:0;height:100%;position:relative;transition-property:transform;width:100%}.swiper-slide-invisible-blank{visibility:hidden}.swiper-autoheight,.swiper-autoheight .swiper-slide{height:auto}.swiper-autoheight .swiper-wrapper{align-items:flex-start;transition-property:transform,height}.swiper-backface-hidden .swiper-slide{-webkit-backface-visibility:hidden;backface-visibility:hidden;transform:translateZ(0)}.swiper-3d.swiper-css-mode .swiper-wrapper{perspective:1200px}.swiper-3d .swiper-wrapper{transform-style:preserve-3d}.swiper-3d{perspective:1200px}.swiper-3d .swiper-cube-shadow,.swiper-3d .swiper-slide{transform-style:preserve-3d}.swiper-css-mode>.swiper-wrapper{-ms-overflow-style:none;overflow:auto;scrollbar-width:none}.swiper-css-mode>.swiper-wrapper::-webkit-scrollbar{display:none}.swiper-css-mode>.swiper-wrapper>.swiper-slide{scroll-snap-align:start start}.swiper-css-mode.swiper-horizontal>.swiper-wrapper{scroll-snap-type:x mandatory}.swiper-css-mode.swiper-vertical>.swiper-wrapper{scroll-snap-type:y mandatory}.swiper-css-mode.swiper-free-mode>.swiper-wrapper{scroll-snap-type:none}.swiper-css-mode.swiper-free-mode>.swiper-wrapper>.swiper-slide{scroll-snap-align:none}.swiper-css-mode.swiper-centered>.swiper-wrapper:before{content:"";flex-shrink:0;order:9999}.swiper-css-mode.swiper-centered>.swiper-wrapper>.swiper-slide{scroll-snap-align:center center;scroll-snap-stop:always}.swiper-css-mode.swiper-centered.swiper-horizontal>.swiper-wrapper>.swiper-slide:first-child{margin-inline-start:var(--swiper-centered-offset-before)}.swiper-css-mode.swiper-centered.swiper-horizontal>.swiper-wrapper:before{height:100%;min-height:1px;width:var(--swiper-centered-offset-after)}.swiper-css-mode.swiper-centered.swiper-vertical>.swiper-wrapper>.swiper-slide:first-child{margin-block-start:var(--swiper-centered-offset-before)}.swiper-css-mode.swiper-centered.swiper-vertical>.swiper-wrapper:before{height:var(--swiper-centered-offset-after);min-width:1px;width:100%}.swiper-3d .swiper-slide-shadow,.swiper-3d .swiper-slide-shadow-bottom,.swiper-3d .swiper-slide-shadow-left,.swiper-3d .swiper-slide-shadow-right,.swiper-3d .swiper-slide-shadow-top{height:100%;left:0;pointer-events:none;position:absolute;top:0;width:100%;z-index:10}.swiper-3d .swiper-slide-shadow{background:rgba(0,0,0,.15)}.swiper-3d .swiper-slide-shadow-left{background-image:linear-gradient(270deg,rgba(0,0,0,.5),transparent)}.swiper-3d .swiper-slide-shadow-right{background-image:linear-gradient(90deg,rgba(0,0,0,.5),transparent)}.swiper-3d .swiper-slide-shadow-top{background-image:linear-gradient(0deg,rgba(0,0,0,.5),transparent)}.swiper-3d .swiper-slide-shadow-bottom{background-image:linear-gradient(180deg,rgba(0,0,0,.5),transparent)}.swiper-lazy-preloader{border:4px solid var(--swiper-preloader-color,var(--swiper-theme-color));border-radius:50%;border-top:4px solid transparent;box-sizing:border-box;height:42px;left:50%;margin-left:-21px;margin-top:-21px;position:absolute;top:50%;transform-origin:50%;width:42px;z-index:10}.swiper-watch-progress .swiper-slide-visible .swiper-lazy-preloader,.swiper:not(.swiper-watch-progress) .swiper-lazy-preloader{animation:swiper-preloader-spin 1s linear infinite}.swiper-lazy-preloader-white{--swiper-preloader-color:#fff}.swiper-lazy-preloader-black{--swiper-preloader-color:#000}@keyframes swiper-preloader-spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}.swiper.swiper-cards{overflow:visible}.swiper-cards .swiper-slide{-webkit-backface-visibility:hidden;backface-visibility:hidden;overflow:hidden;transform-origin:center bottom}.swiper-grid>.swiper-wrapper{flex-wrap:wrap}.swiper-grid-column>.swiper-wrapper{flex-direction:column;flex-wrap:wrap}@keyframes enter{0%{opacity:var(--tw-enter-opacity,1);transform:translate3d(var(--tw-enter-translate-x,0),var(--tw-enter-translate-y,0),0) scale3d(var(--tw-enter-scale,1),var(--tw-enter-scale,1),var(--tw-enter-scale,1)) rotate(var(--tw-enter-rotate,0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity,1);transform:translate3d(var(--tw-exit-translate-x,0),var(--tw-exit-translate-y,0),0) scale3d(var(--tw-exit-scale,1),var(--tw-exit-scale,1),var(--tw-exit-scale,1)) rotate(var(--tw-exit-rotate,0))}}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-rotate-x{syntax:"*";inherits:false;initial-value:rotateX(0)}@property --tw-rotate-y{syntax:"*";inherits:false;initial-value:rotateY(0)}@property --tw-rotate-z{syntax:"*";inherits:false;initial-value:rotateZ(0)}@property --tw-skew-x{syntax:"*";inherits:false;initial-value:skewX(0)}@property --tw-skew-y{syntax:"*";inherits:false;initial-value:skewY(0)}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-gradient-position{syntax:"*";inherits:false}@property --tw-gradient-from{syntax:"<color>";inherits:false;initial-value:#0000}@property --tw-gradient-via{syntax:"<color>";inherits:false;initial-value:#0000}@property --tw-gradient-to{syntax:"<color>";inherits:false;initial-value:#0000}@property --tw-gradient-stops{syntax:"*";inherits:false}@property --tw-gradient-via-stops{syntax:"*";inherits:false}@property --tw-gradient-from-position{syntax:"<length-percentage>";inherits:false;initial-value:0}@property --tw-gradient-via-position{syntax:"<length-percentage>";inherits:false;initial-value:50%}@property --tw-gradient-to-position{syntax:"<length-percentage>";inherits:false;initial-value:100%}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@keyframes pulse{50%{opacity:.5}}@keyframes float{0%{opacity:1;transform:translateY(0)}to{opacity:0;transform:translateY(-200px)}}',uc=lc.trim().length>0,cc="undefined"!=typeof window&&"adoptedStyleSheets"in Document.prototype&&"undefined"!=typeof CSSStyleSheet&&"replaceSync"in CSSStyleSheet.prototype;let dc=null;function hc(e){return dc||(dc=new CSSStyleSheet,dc.replaceSync(e)),dc}function fc(){return uc?lc:function(){const e=[];for(const t of Array.from(document.styleSheets))try{e.push(Array.from(t.cssRules).map(e=>e.cssText).join("\n"))}catch(e){}return e.join("\n")}()}const pc=({extra:e})=>{const t=fc()+(e?"\n"+e:"");return g.createElement("style",null,t)};function gc(){const[e,t]=g.useState(null),r=p.useRef(null),{open:n,setOpen:i}=Wo();return p.useEffect(()=>{r.current&&(r.current.style.display=n?"block":"none")},[n]),g.useLayoutEffect(()=>{const e=document.createElement("div");e.style.position="fixed",e.style.inset="0",e.style.zIndex="214748348",e.style.display="none",document.body.appendChild(e),r.current=e;const n=e.attachShadow({mode:"open"});!function(e){const t=fc();if(cc)e.adoptedStyleSheets=[hc(t)];else{const r=document.createElement("style");r.textContent=t,e.appendChild(r)}}(n);const i=document.createElement("style");i.innerHTML="\n .product-dialog-container{\n max-height: 70vh;\n overflow-y: auto;\n width: 100%;\n max-width: min(82vw, 500px) !important;\n }\n ",n.appendChild(i);const s=document.createElement("div");return n.appendChild(s),t(s),()=>e.remove()},[]),{container:e,setOpen:i}}const mc=e=>{const{collectionId:t,isPreview:r,priceText:n,container:i}=e,{setIsPreview:s,setPriceText:a}=cr(),{setCollection:o,setNextKey:l,collection:u}=fr();p.useEffect(()=>{n&&a(n);const e=Boolean(r);e&&s(e)},[]),p.useEffect(()=>{J(void 0,void 0,void 0,function*(){var e;const r=yield tr({collectionId:t,size:10});if(!r)return;const{contents:n,count:i}=r;(null==n?void 0:n.length)&&l(null===(e=n.at(-1))||void 0===e?void 0:e.shortsId),o(Object.assign(Object.assign({},r),{count:i}))})},[t]);const c=function(e){var t,r,n,i,s,a,o,l,u,c,d,h;const f=null!==(t=e.iconForm)&&void 0!==t?t:z.INSTA,p={collectionId:e.collectionId,iconForm:f,iconShape:null!==(r=e.iconShape)&&void 0!==r?r:j.MANY,iconSize:null!==(n=e.iconSize)&&void 0!==n?n:120,borderLine:null!==(i=e.borderLine)&&void 0!==i?i:G.DAY,exposeTitle:null===(s=e.exposeTitle)||void 0===s||s,player:null!==(a=e.player)&&void 0!==a?a:H.POPUP,rounded:null===(o=e.rounded)||void 0===o||o,titlePosition:null!==(l=e.titlePosition)&&void 0!==l?l:V.BOTTOM,exposeProductBanner:null!==(u=e.exposeProductBanner)&&void 0!==u&&u,exposeProductBadge:null!==(c=e.exposeProductBadge)&&void 0!==c&&c,priceText:e.priceText||"할인가",hoverPlay:null!==(d=e.hoverPlay)&&void 0!==d&&d,thumbnailAutoPlay:null!==(h=e.thumbnailAutoPlay)&&void 0!==h&&h};return f===z.YOUTUBE?Object.assign(Object.assign({},p),{iconForm:z.YOUTUBE,iconRatio:e.iconRatio||"9/16"}):Object.assign(Object.assign({},p),{iconForm:z.INSTA})}(e),{containerRef:d}=function({collectionId:e,iconSize:t}){const{collection:r,setCollection:n,nextKey:i,setNextKey:s,isFetching:a,setIsFetching:o}=fr(),l=g.useRef(null),[u,c]=g.useState(0);return g.useEffect(()=>{if(!l.current)return;const e=new ResizeObserver(e=>{var t,r,n;const i=null!==(n=null===(r=null===(t=e[0])||void 0===t?void 0:t.contentRect)||void 0===r?void 0:r.width)&&void 0!==n?n:0;c(i)});return e.observe(l.current),()=>e.disconnect()},[]),g.useEffect(()=>{var e;if(!r||!r.contents)return;const l=Math.max(1,t+12),c=Math.ceil((u||0)/l)+4,d=null!==(e=r.count)&&void 0!==e?e:Number.MAX_SAFE_INTEGER,h=Math.min(d,c);if(r.contents.length>=h||a)return;let f=!1;return(()=>{J(this,void 0,void 0,function*(){var e,t,a,l,u;try{o(!0);let c=r,d=i||(null===(e=c.contents.at(-1))||void 0===e?void 0:e.shortsId)||void 0;const p=new Set(c.contents.map(e=>e.shortsId));for(;!f&&c.contents.length<h;){const e=Math.max(6,h-c.contents.length),r=yield tr({collectionId:c.colId,nextKey:d,size:e});if(!r||!(null===(t=r.contents)||void 0===t?void 0:t.length))break;d=null!==(l=null===(a=r.contents.at(-1))||void 0===a?void 0:a.shortsId)&&void 0!==l?l:d;const i=r.contents.filter(e=>!p.has(e.shortsId));if(!i.length)break;if(i.forEach(e=>p.add(e.shortsId)),c=Object.assign(Object.assign({},c),{contents:[...c.contents,...i]}),n(c),s(d||""),c.contents.length>=(null!==(u=c.count)&&void 0!==u?u:Number.MAX_SAFE_INTEGER))break}}finally{o(!1)}})})(),()=>{f=!0}},[null==r?void 0:r.colId,null==r?void 0:r.count,null==r?void 0:r.contents.length,u,t,a,i,n,o,s]),{containerRef:l}}({collectionId:t,iconSize:c.iconSize});return g.createElement(oc.div,null,g.createElement(pc,null),g.createElement("div",{ref:d},g.createElement(Cu,{widgetPlayerOption:c,setCollectionUuid:e=>{o(Object.assign(Object.assign({},u),{uuid:e}))},portalContainer:i})))},vc=({portalContainer:e,aspectRatio:t})=>{var r;const{collection:n,setNextKey:i}=fr(),[s,a]=p.useState(),{setOpen:o,open:l}=Wo();p.useEffect(()=>{l||s&&a(null)},[l]);const u=(null!==(r=On().width)&&void 0!==r?r:0)<430||Hn.isMobile;return g.createElement(g.Fragment,null,g.createElement("div",{className:"grid gap-4",style:{gridTemplateColumns:`repeat(${u?2:5}, 1fr)`}},null==n?void 0:n.contents.map(e=>g.createElement("div",null,g.createElement("div",{className:"overflow-hidden",style:{borderRadius:"0.625rem",aspectRatio:null!=t?t:"9/16"}},g.createElement("video",{loop:!0,className:"w-full h-full object-cover",muted:!0,autoPlay:!0,playsInline:!0,src:Ft(e.media.objectId),poster:Gt(e.thumbPath)})),g.createElement(Yo,{hideMoreBadge:!0,showMoreBtn:!0,products:e.productsInfo,contentId:e.shortsId,setSelectedProducts:a})))),s&&g.createElement(Ru,{portalContainer:e,title:"상품 목록",contentClassName:"bg-white rounded p-4 product-dialog-container",description:"연결된 전체 상품 정보를 확인해 보세요"},g.createElement(Lu,{products:s.productsInfo,contentId:s.shortsId})))},yc=({collectionId:e,aspectRatio:t,container:r,isPreview:n})=>{const{setCollection:i,setNextKey:s}=fr();return p.useEffect(()=>{J(void 0,void 0,void 0,function*(){var t;const r=yield tr({collectionId:e,size:-1});if(!r)return;const{contents:n,count:a}=r;(null==n?void 0:n.length)&&s(null===(t=n.at(-1))||void 0===t?void 0:t.shortsId),i(Object.assign(Object.assign({},r),{count:a}))})},[e]),g.createElement(oc.div,null,g.createElement(pc,null),g.createElement(vc,{portalContainer:r,aspectRatio:t}))},bc=ur(e=>({shortform:null,setShortform:t=>e({shortform:t})}));var wc={exports:{}},Ec={};function Sc(e){var t,r,n="";if("string"==typeof e||"number"==typeof e)n+=e;else if("object"==typeof e)if(Array.isArray(e))for(t=0;t<e.length;t++)e[t]&&(r=Sc(e[t]))&&(n&&(n+=" "),n+=r);else for(t in e)e[t]&&(n&&(n+=" "),n+=t);return n}function Tc(){for(var e,t,r=0,n="";r<arguments.length;)(e=arguments[r++])&&(t=Sc(e))&&(n&&(n+=" "),n+=t);return n}var xc,kc=r(Object.freeze({__proto__:null,clsx:Tc,default:Tc})),Ac={},Rc={};function Lc(){if(xc)return Rc;return xc=1,Object.defineProperty(Rc,"__esModule",{value:!0}),Rc.dontSetMe=function(e,t,r){if(e[t])return new Error("Invalid prop ".concat(t," passed to ").concat(r," - do not set this, set it on the child."))},Rc.findInArray=function(e,t){for(let r=0,n=e.length;r<n;r++)if(t.apply(t,[e[r],r,e]))return e[r]},Rc.int=function(e){return parseInt(e,10)},Rc.isFunction=function(e){return"function"==typeof e||"[object Function]"===Object.prototype.toString.call(e)},Rc.isNum=function(e){return"number"==typeof e&&!isNaN(e)},Rc}var Ic,Cc,Pc={};function Dc(){if(Cc)return Ac;Cc=1,Object.defineProperty(Ac,"__esModule",{value:!0}),Ac.addClassName=a,Ac.addEvent=function(e,t,r,n){if(!e)return;const i={capture:!0,...n};e.addEventListener?e.addEventListener(t,r,i):e.attachEvent?e.attachEvent("on"+t,r):e["on"+t]=r},Ac.addUserSelectStyles=function(e){if(!e)return;let t=e.getElementById("react-draggable-style-el");t||(t=e.createElement("style"),t.type="text/css",t.id="react-draggable-style-el",t.innerHTML=".react-draggable-transparent-selection *::-moz-selection {all: inherit;}\n",t.innerHTML+=".react-draggable-transparent-selection *::selection {all: inherit;}\n",e.getElementsByTagName("head")[0].appendChild(t));e.body&&a(e.body,"react-draggable-transparent-selection")},Ac.createCSSTransform=function(e,r){const n=s(e,r,"px");return{[(0,t.browserPrefixToKey)("transform",t.default)]:n}},Ac.createSVGTransform=function(e,t){return s(e,t,"")},Ac.getTouch=function(t,r){return t.targetTouches&&(0,e.findInArray)(t.targetTouches,e=>r===e.identifier)||t.changedTouches&&(0,e.findInArray)(t.changedTouches,e=>r===e.identifier)},Ac.getTouchIdentifier=function(e){if(e.targetTouches&&e.targetTouches[0])return e.targetTouches[0].identifier;if(e.changedTouches&&e.changedTouches[0])return e.changedTouches[0].identifier},Ac.getTranslation=s,Ac.innerHeight=function(t){let r=t.clientHeight;const n=t.ownerDocument.defaultView.getComputedStyle(t);return r-=(0,e.int)(n.paddingTop),r-=(0,e.int)(n.paddingBottom),r},Ac.innerWidth=function(t){let r=t.clientWidth;const n=t.ownerDocument.defaultView.getComputedStyle(t);return r-=(0,e.int)(n.paddingLeft),r-=(0,e.int)(n.paddingRight),r},Ac.matchesSelector=i,Ac.matchesSelectorAndParentsTo=function(e,t,r){let n=e;do{if(i(n,t))return!0;if(n===r)return!1;n=n.parentNode}while(n);return!1},Ac.offsetXYFromParent=function(e,t,r){const n=t===t.ownerDocument.body?{left:0,top:0}:t.getBoundingClientRect(),i=(e.clientX+t.scrollLeft-n.left)/r,s=(e.clientY+t.scrollTop-n.top)/r;return{x:i,y:s}},Ac.outerHeight=function(t){let r=t.clientHeight;const n=t.ownerDocument.defaultView.getComputedStyle(t);return r+=(0,e.int)(n.borderTopWidth),r+=(0,e.int)(n.borderBottomWidth),r},Ac.outerWidth=function(t){let r=t.clientWidth;const n=t.ownerDocument.defaultView.getComputedStyle(t);return r+=(0,e.int)(n.borderLeftWidth),r+=(0,e.int)(n.borderRightWidth),r},Ac.removeClassName=o,Ac.removeEvent=function(e,t,r,n){if(!e)return;const i={capture:!0,...n};e.removeEventListener?e.removeEventListener(t,r,i):e.detachEvent?e.detachEvent("on"+t,r):e["on"+t]=null},Ac.removeUserSelectStyles=function(e){if(!e)return;try{if(e.body&&o(e.body,"react-draggable-transparent-selection"),e.selection)e.selection.empty();else{const t=(e.defaultView||window).getSelection();t&&"Caret"!==t.type&&t.removeAllRanges()}}catch(e){}};var e=Lc(),t=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=r(t);if(n&&n.has(e))return n.get(e);var i={},s=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var a in e)if("default"!==a&&Object.prototype.hasOwnProperty.call(e,a)){var o=s?Object.getOwnPropertyDescriptor(e,a):null;o&&(o.get||o.set)?Object.defineProperty(i,a,o):i[a]=e[a]}i.default=e,n&&n.set(e,i);return i}(function(){if(Ic)return Pc;Ic=1,Object.defineProperty(Pc,"__esModule",{value:!0}),Pc.browserPrefixToKey=r,Pc.browserPrefixToStyle=function(e,t){return t?"-".concat(t.toLowerCase(),"-").concat(e):e},Pc.default=void 0,Pc.getPrefix=t;const e=["Moz","Webkit","O","ms"];function t(){var t;let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"transform";if("undefined"==typeof window)return"";const i=null===(t=window.document)||void 0===t||null===(t=t.documentElement)||void 0===t?void 0:t.style;if(!i)return"";if(n in i)return"";for(let t=0;t<e.length;t++)if(r(n,e[t])in i)return e[t];return""}function r(e,t){return t?"".concat(t).concat(function(e){let t="",r=!0;for(let n=0;n<e.length;n++)r?(t+=e[n].toUpperCase(),r=!1):"-"===e[n]?r=!0:t+=e[n];return t}(e)):e}return Pc.default=t(),Pc}());function r(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(r=function(e){return e?n:t})(e)}let n="";function i(t,r){return n||(n=(0,e.findInArray)(["matches","webkitMatchesSelector","mozMatchesSelector","msMatchesSelector","oMatchesSelector"],function(r){return(0,e.isFunction)(t[r])})),!!(0,e.isFunction)(t[n])&&t[n](r)}function s(e,t,r){let{x:n,y:i}=e,s="translate(".concat(n).concat(r,",").concat(i).concat(r,")");if(t){const e="".concat("string"==typeof t.x?t.x:t.x+r),n="".concat("string"==typeof t.y?t.y:t.y+r);s="translate(".concat(e,", ").concat(n,")")+s}return s}function a(e,t){e.classList?e.classList.add(t):e.className.match(new RegExp("(?:^|\\s)".concat(t,"(?!\\S)")))||(e.className+=" ".concat(t))}function o(e,t){e.classList?e.classList.remove(t):e.className=e.className.replace(new RegExp("(?:^|\\s)".concat(t,"(?!\\S)"),"g"),"")}return Ac}var _c,Mc={};function Oc(){if(_c)return Mc;_c=1,Object.defineProperty(Mc,"__esModule",{value:!0}),Mc.canDragX=function(e){return"both"===e.props.axis||"x"===e.props.axis},Mc.canDragY=function(e){return"both"===e.props.axis||"y"===e.props.axis},Mc.createCoreData=function(t,n,i){const s=!(0,e.isNum)(t.lastX),a=r(t);return s?{node:a,deltaX:0,deltaY:0,lastX:n,lastY:i,x:n,y:i}:{node:a,deltaX:n-t.lastX,deltaY:i-t.lastY,lastX:t.lastX,lastY:t.lastY,x:n,y:i}},Mc.createDraggableData=function(e,t){const r=e.props.scale;return{node:t.node,x:e.state.x+t.deltaX/r,y:e.state.y+t.deltaY/r,deltaX:t.deltaX/r,deltaY:t.deltaY/r,lastX:e.state.x,lastY:e.state.y}},Mc.getBoundPosition=function(n,i,s){if(!n.props.bounds)return[i,s];let{bounds:a}=n.props;a="string"==typeof a?a:function(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom}}(a);const o=r(n);if("string"==typeof a){const{ownerDocument:r}=o,n=r.defaultView;let i;if(i="parent"===a?o.parentNode:r.querySelector(a),!(i instanceof n.HTMLElement))throw new Error('Bounds selector "'+a+'" could not find an element.');const s=i,l=n.getComputedStyle(o),u=n.getComputedStyle(s);a={left:-o.offsetLeft+(0,e.int)(u.paddingLeft)+(0,e.int)(l.marginLeft),top:-o.offsetTop+(0,e.int)(u.paddingTop)+(0,e.int)(l.marginTop),right:(0,t.innerWidth)(s)-(0,t.outerWidth)(o)-o.offsetLeft+(0,e.int)(u.paddingRight)-(0,e.int)(l.marginRight),bottom:(0,t.innerHeight)(s)-(0,t.outerHeight)(o)-o.offsetTop+(0,e.int)(u.paddingBottom)-(0,e.int)(l.marginBottom)}}(0,e.isNum)(a.right)&&(i=Math.min(i,a.right));(0,e.isNum)(a.bottom)&&(s=Math.min(s,a.bottom));(0,e.isNum)(a.left)&&(i=Math.max(i,a.left));(0,e.isNum)(a.top)&&(s=Math.max(s,a.top));return[i,s]},Mc.getControlPosition=function(e,n,i){const s="number"==typeof n?(0,t.getTouch)(e,n):null;if("number"==typeof n&&!s)return null;const a=r(i),o=i.props.offsetParent||a.offsetParent||a.ownerDocument.body;return(0,t.offsetXYFromParent)(s||e,o,i.props.scale)},Mc.snapToGrid=function(e,t,r){const n=Math.round(t/e[0])*e[0],i=Math.round(r/e[1])*e[1];return[n,i]};var e=Lc(),t=Dc();function r(e){const t=e.findDOMNode();if(!t)throw new Error("<DraggableCore>: Unmounted during event!");return t}return Mc}var Nc,Fc,$c,Bc,Uc={},zc={};function jc(){if(Nc)return zc;return Nc=1,Object.defineProperty(zc,"__esModule",{value:!0}),zc.default=function(){},zc}function Gc(){if(Fc)return Uc;Fc=1,Object.defineProperty(Uc,"__esModule",{value:!0}),Uc.default=void 0;var e=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=u(t);if(r&&r.has(e))return r.get(e);var n={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var a=i?Object.getOwnPropertyDescriptor(e,s):null;a&&(a.get||a.set)?Object.defineProperty(n,s,a):n[s]=e[s]}n.default=e,r&&r.set(e,n);return n}(l()),t=o(Yu()),r=o(x()),n=Dc(),i=Oc(),s=Lc(),a=o(jc());function o(e){return e&&e.__esModule?e:{default:e}}function u(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(u=function(e){return e?r:t})(e)}function c(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}const d={start:"touchstart",move:"touchmove",stop:"touchend"},h={start:"mousedown",move:"mousemove",stop:"mouseup"};let f=h,p=class extends e.Component{constructor(){super(...arguments),c(this,"dragging",!1),c(this,"lastX",NaN),c(this,"lastY",NaN),c(this,"touchIdentifier",null),c(this,"mounted",!1),c(this,"handleDragStart",e=>{if(this.props.onMouseDown(e),!this.props.allowAnyClick&&"number"==typeof e.button&&0!==e.button)return!1;const t=this.findDOMNode();if(!t||!t.ownerDocument||!t.ownerDocument.body)throw new Error("<DraggableCore> not mounted on DragStart!");const{ownerDocument:r}=t;if(this.props.disabled||!(e.target instanceof r.defaultView.Node)||this.props.handle&&!(0,n.matchesSelectorAndParentsTo)(e.target,this.props.handle,t)||this.props.cancel&&(0,n.matchesSelectorAndParentsTo)(e.target,this.props.cancel,t))return;"touchstart"===e.type&&e.preventDefault();const s=(0,n.getTouchIdentifier)(e);this.touchIdentifier=s;const o=(0,i.getControlPosition)(e,s,this);if(null==o)return;const{x:l,y:u}=o,c=(0,i.createCoreData)(this,l,u);(0,a.default)("DraggableCore: handleDragStart: %j",c),(0,a.default)("calling",this.props.onStart);!1!==this.props.onStart(e,c)&&!1!==this.mounted&&(this.props.enableUserSelectHack&&(0,n.addUserSelectStyles)(r),this.dragging=!0,this.lastX=l,this.lastY=u,(0,n.addEvent)(r,f.move,this.handleDrag),(0,n.addEvent)(r,f.stop,this.handleDragStop))}),c(this,"handleDrag",e=>{const t=(0,i.getControlPosition)(e,this.touchIdentifier,this);if(null==t)return;let{x:r,y:n}=t;if(Array.isArray(this.props.grid)){let e=r-this.lastX,t=n-this.lastY;if([e,t]=(0,i.snapToGrid)(this.props.grid,e,t),!e&&!t)return;r=this.lastX+e,n=this.lastY+t}const s=(0,i.createCoreData)(this,r,n);(0,a.default)("DraggableCore: handleDrag: %j",s);if(!1!==this.props.onDrag(e,s)&&!1!==this.mounted)this.lastX=r,this.lastY=n;else try{this.handleDragStop(new MouseEvent("mouseup"))}catch(e){const t=document.createEvent("MouseEvents");t.initMouseEvent("mouseup",!0,!0,window,0,0,0,0,0,!1,!1,!1,!1,0,null),this.handleDragStop(t)}}),c(this,"handleDragStop",e=>{if(!this.dragging)return;const t=(0,i.getControlPosition)(e,this.touchIdentifier,this);if(null==t)return;let{x:r,y:s}=t;if(Array.isArray(this.props.grid)){let e=r-this.lastX||0,t=s-this.lastY||0;[e,t]=(0,i.snapToGrid)(this.props.grid,e,t),r=this.lastX+e,s=this.lastY+t}const o=(0,i.createCoreData)(this,r,s);if(!1===this.props.onStop(e,o)||!1===this.mounted)return!1;const l=this.findDOMNode();l&&this.props.enableUserSelectHack&&(0,n.removeUserSelectStyles)(l.ownerDocument),(0,a.default)("DraggableCore: handleDragStop: %j",o),this.dragging=!1,this.lastX=NaN,this.lastY=NaN,l&&((0,a.default)("DraggableCore: Removing handlers"),(0,n.removeEvent)(l.ownerDocument,f.move,this.handleDrag),(0,n.removeEvent)(l.ownerDocument,f.stop,this.handleDragStop))}),c(this,"onMouseDown",e=>(f=h,this.handleDragStart(e))),c(this,"onMouseUp",e=>(f=h,this.handleDragStop(e))),c(this,"onTouchStart",e=>(f=d,this.handleDragStart(e))),c(this,"onTouchEnd",e=>(f=d,this.handleDragStop(e)))}componentDidMount(){this.mounted=!0;const e=this.findDOMNode();e&&(0,n.addEvent)(e,d.start,this.onTouchStart,{passive:!1})}componentWillUnmount(){this.mounted=!1;const e=this.findDOMNode();if(e){const{ownerDocument:t}=e;(0,n.removeEvent)(t,h.move,this.handleDrag),(0,n.removeEvent)(t,d.move,this.handleDrag),(0,n.removeEvent)(t,h.stop,this.handleDragStop),(0,n.removeEvent)(t,d.stop,this.handleDragStop),(0,n.removeEvent)(e,d.start,this.onTouchStart,{passive:!1}),this.props.enableUserSelectHack&&(0,n.removeUserSelectStyles)(t)}}findDOMNode(){var e,t;return null!==(e=this.props)&&void 0!==e&&e.nodeRef?null===(t=this.props)||void 0===t||null===(t=t.nodeRef)||void 0===t?void 0:t.current:r.default.findDOMNode(this)}render(){return e.cloneElement(e.Children.only(this.props.children),{onMouseDown:this.onMouseDown,onMouseUp:this.onMouseUp,onTouchEnd:this.onTouchEnd})}};return Uc.default=p,c(p,"displayName","DraggableCore"),c(p,"propTypes",{allowAnyClick:t.default.bool,children:t.default.node.isRequired,disabled:t.default.bool,enableUserSelectHack:t.default.bool,offsetParent:function(e,t){if(e[t]&&1!==e[t].nodeType)throw new Error("Draggable's offsetParent must be a DOM Node.")},grid:t.default.arrayOf(t.default.number),handle:t.default.string,cancel:t.default.string,nodeRef:t.default.object,onStart:t.default.func,onDrag:t.default.func,onStop:t.default.func,onMouseDown:t.default.func,scale:t.default.number,className:s.dontSetMe,style:s.dontSetMe,transform:s.dontSetMe}),c(p,"defaultProps",{allowAnyClick:!1,disabled:!1,enableUserSelectHack:!0,onStart:function(){},onDrag:function(){},onStop:function(){},onMouseDown:function(){},scale:1}),Uc}function Hc(){return $c||($c=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"DraggableCore",{enumerable:!0,get:function(){return u.default}}),e.default=void 0;var t=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=h(t);if(r&&r.has(e))return r.get(e);var n={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var a=i?Object.getOwnPropertyDescriptor(e,s):null;a&&(a.get||a.set)?Object.defineProperty(n,s,a):n[s]=e[s]}n.default=e,r&&r.set(e,n);return n}(l()),r=d(Yu()),n=d(x()),i=d(kc),s=Dc(),a=Oc(),o=Lc(),u=d(Gc()),c=d(jc());function d(e){return e&&e.__esModule?e:{default:e}}function h(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(h=function(e){return e?r:t})(e)}function f(){return f=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},f.apply(this,arguments)}function p(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class g extends t.Component{static getDerivedStateFromProps(e,t){let{position:r}=e,{prevPropsPosition:n}=t;return!r||n&&r.x===n.x&&r.y===n.y?null:((0,c.default)("Draggable: getDerivedStateFromProps %j",{position:r,prevPropsPosition:n}),{x:r.x,y:r.y,prevPropsPosition:{...r}})}constructor(e){super(e),p(this,"onDragStart",(e,t)=>{(0,c.default)("Draggable: onDragStart: %j",t);if(!1===this.props.onStart(e,(0,a.createDraggableData)(this,t)))return!1;this.setState({dragging:!0,dragged:!0})}),p(this,"onDrag",(e,t)=>{if(!this.state.dragging)return!1;(0,c.default)("Draggable: onDrag: %j",t);const r=(0,a.createDraggableData)(this,t),n={x:r.x,y:r.y,slackX:0,slackY:0};if(this.props.bounds){const{x:e,y:t}=n;n.x+=this.state.slackX,n.y+=this.state.slackY;const[i,s]=(0,a.getBoundPosition)(this,n.x,n.y);n.x=i,n.y=s,n.slackX=this.state.slackX+(e-n.x),n.slackY=this.state.slackY+(t-n.y),r.x=n.x,r.y=n.y,r.deltaX=n.x-this.state.x,r.deltaY=n.y-this.state.y}if(!1===this.props.onDrag(e,r))return!1;this.setState(n)}),p(this,"onDragStop",(e,t)=>{if(!this.state.dragging)return!1;if(!1===this.props.onStop(e,(0,a.createDraggableData)(this,t)))return!1;(0,c.default)("Draggable: onDragStop: %j",t);const r={dragging:!1,slackX:0,slackY:0};if(Boolean(this.props.position)){const{x:e,y:t}=this.props.position;r.x=e,r.y=t}this.setState(r)}),this.state={dragging:!1,dragged:!1,x:e.position?e.position.x:e.defaultPosition.x,y:e.position?e.position.y:e.defaultPosition.y,prevPropsPosition:{...e.position},slackX:0,slackY:0,isElementSVG:!1},!e.position||e.onDrag||e.onStop||console.warn("A `position` was applied to this <Draggable>, without drag handlers. This will make this component effectively undraggable. Please attach `onDrag` or `onStop` handlers so you can adjust the `position` of this element.")}componentDidMount(){void 0!==window.SVGElement&&this.findDOMNode()instanceof window.SVGElement&&this.setState({isElementSVG:!0})}componentWillUnmount(){this.setState({dragging:!1})}findDOMNode(){var e,t;return null!==(e=null===(t=this.props)||void 0===t||null===(t=t.nodeRef)||void 0===t?void 0:t.current)&&void 0!==e?e:n.default.findDOMNode(this)}render(){const{axis:e,bounds:r,children:n,defaultPosition:o,defaultClassName:l,defaultClassNameDragging:c,defaultClassNameDragged:d,position:h,positionOffset:p,scale:g,...m}=this.props;let v={},y=null;const b=!Boolean(h)||this.state.dragging,w=h||o,E={x:(0,a.canDragX)(this)&&b?this.state.x:w.x,y:(0,a.canDragY)(this)&&b?this.state.y:w.y};this.state.isElementSVG?y=(0,s.createSVGTransform)(E,p):v=(0,s.createCSSTransform)(E,p);const S=(0,i.default)(n.props.className||"",l,{[c]:this.state.dragging,[d]:this.state.dragged});return t.createElement(u.default,f({},m,{onStart:this.onDragStart,onDrag:this.onDrag,onStop:this.onDragStop}),t.cloneElement(t.Children.only(n),{className:S,style:{...n.props.style,...v},transform:y}))}}e.default=g,p(g,"displayName","Draggable"),p(g,"propTypes",{...u.default.propTypes,axis:r.default.oneOf(["both","x","y","none"]),bounds:r.default.oneOfType([r.default.shape({left:r.default.number,right:r.default.number,top:r.default.number,bottom:r.default.number}),r.default.string,r.default.oneOf([!1])]),defaultClassName:r.default.string,defaultClassNameDragging:r.default.string,defaultClassNameDragged:r.default.string,defaultPosition:r.default.shape({x:r.default.number,y:r.default.number}),positionOffset:r.default.shape({x:r.default.oneOfType([r.default.number,r.default.string]),y:r.default.oneOfType([r.default.number,r.default.string])}),position:r.default.shape({x:r.default.number,y:r.default.number}),className:o.dontSetMe,style:o.dontSetMe,transform:o.dontSetMe}),p(g,"defaultProps",{...u.default.defaultProps,axis:"both",bounds:!1,defaultClassName:"react-draggable",defaultClassNameDragging:"react-draggable-dragging",defaultClassNameDragged:"react-draggable-dragged",defaultPosition:{x:0,y:0},scale:1})}(Ec)),Ec}var Vc=function(){if(Bc)return wc.exports;Bc=1;const{default:e,DraggableCore:t}=Hc();return wc.exports=e,wc.exports.default=e,wc.exports.DraggableCore=t,wc.exports}(),Wc=t(Vc),Kc=function(){return Kc=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},Kc.apply(this,arguments)},Yc={width:"100%",height:"10px",top:"0px",left:"0px",cursor:"row-resize"},qc={width:"10px",height:"100%",top:"0px",left:"0px",cursor:"col-resize"},Xc={width:"20px",height:"20px",position:"absolute",zIndex:1},Qc={top:Kc(Kc({},Yc),{top:"-5px"}),right:Kc(Kc({},qc),{left:void 0,right:"-5px"}),bottom:Kc(Kc({},Yc),{top:void 0,bottom:"-5px"}),left:Kc(Kc({},qc),{left:"-5px"}),topRight:Kc(Kc({},Xc),{right:"-10px",top:"-10px",cursor:"ne-resize"}),bottomRight:Kc(Kc({},Xc),{right:"-10px",bottom:"-10px",cursor:"se-resize"}),bottomLeft:Kc(Kc({},Xc),{left:"-10px",bottom:"-10px",cursor:"sw-resize"}),topLeft:Kc(Kc({},Xc),{left:"-10px",top:"-10px",cursor:"nw-resize"})},Zc=p.memo(function(e){var t=e.onResizeStart,r=e.direction,n=e.children,i=e.replaceStyles,s=e.className,a=p.useCallback(function(e){t(e,r)},[t,r]),o=p.useCallback(function(e){t(e,r)},[t,r]),l=p.useMemo(function(){return Kc(Kc({position:"absolute",userSelect:"none"},Qc[r]),null!=i?i:{})},[i,r]);return Ti.jsx("div",{className:s||void 0,style:l,onMouseDown:a,onTouchStart:o,children:n})}),Jc=function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},e(t,r)};return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),ed=function(){return ed=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},ed.apply(this,arguments)},td={width:"auto",height:"auto"},rd=function(e,t,r){return Math.max(Math.min(e,r),t)},nd=function(e,t,r){var n=Math.round(e/t);return n*t+r*(n-1)},id=function(e,t){return new RegExp(e,"i").test(t)},sd=function(e){return Boolean(e.touches&&e.touches.length)},ad=function(e,t,r){void 0===r&&(r=0);var n=t.reduce(function(r,n,i){return Math.abs(n-e)<Math.abs(t[r]-e)?i:r},0),i=Math.abs(t[n]-e);return 0===r||i<r?t[n]:e},od=function(e){return"auto"===(e=e.toString())||e.endsWith("px")||e.endsWith("%")||e.endsWith("vh")||e.endsWith("vw")||e.endsWith("vmax")||e.endsWith("vmin")?e:"".concat(e,"px")},ld=function(e,t,r,n){if(e&&"string"==typeof e){if(e.endsWith("px"))return Number(e.replace("px",""));if(e.endsWith("%"))return t*(Number(e.replace("%",""))/100);if(e.endsWith("vw"))return r*(Number(e.replace("vw",""))/100);if(e.endsWith("vh"))return n*(Number(e.replace("vh",""))/100)}return e},ud=["as","ref","style","className","grid","gridGap","snap","bounds","boundsByDirection","size","defaultSize","minWidth","minHeight","maxWidth","maxHeight","lockAspectRatio","lockAspectRatioExtraWidth","lockAspectRatioExtraHeight","enable","handleStyles","handleClasses","handleWrapperStyle","handleWrapperClass","children","onResizeStart","onResize","onResizeStop","handleComponent","scale","resizeRatio","snapGap"],cd="__resizable_base__",dd=function(e){function t(t){var r,n,i,s,a=e.call(this,t)||this;return a.ratio=1,a.resizable=null,a.parentLeft=0,a.parentTop=0,a.resizableLeft=0,a.resizableRight=0,a.resizableTop=0,a.resizableBottom=0,a.targetLeft=0,a.targetTop=0,a.delta={width:0,height:0},a.appendBase=function(){if(!a.resizable||!a.window)return null;var e=a.parentNode;if(!e)return null;var t=a.window.document.createElement("div");return t.style.width="100%",t.style.height="100%",t.style.position="absolute",t.style.transform="scale(0, 0)",t.style.left="0",t.style.flex="0 0 100%",t.classList?t.classList.add(cd):t.className+=cd,e.appendChild(t),t},a.removeBase=function(e){var t=a.parentNode;t&&t.removeChild(e)},a.state={isResizing:!1,width:null!==(n=null===(r=a.propsSize)||void 0===r?void 0:r.width)&&void 0!==n?n:"auto",height:null!==(s=null===(i=a.propsSize)||void 0===i?void 0:i.height)&&void 0!==s?s:"auto",direction:"right",original:{x:0,y:0,width:0,height:0},backgroundStyle:{height:"100%",width:"100%",backgroundColor:"rgba(0,0,0,0)",cursor:"auto",opacity:0,position:"fixed",zIndex:9999,top:"0",left:"0",bottom:"0",right:"0"},flexBasis:void 0},a.onResizeStart=a.onResizeStart.bind(a),a.onMouseMove=a.onMouseMove.bind(a),a.onMouseUp=a.onMouseUp.bind(a),a}return Jc(t,e),Object.defineProperty(t.prototype,"parentNode",{get:function(){return this.resizable?this.resizable.parentNode:null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"window",{get:function(){return this.resizable&&this.resizable.ownerDocument?this.resizable.ownerDocument.defaultView:null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"propsSize",{get:function(){return this.props.size||this.props.defaultSize||td},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"size",{get:function(){var e=0,t=0;if(this.resizable&&this.window){var r=this.resizable.offsetWidth,n=this.resizable.offsetHeight,i=this.resizable.style.position;"relative"!==i&&(this.resizable.style.position="relative"),e="auto"!==this.resizable.style.width?this.resizable.offsetWidth:r,t="auto"!==this.resizable.style.height?this.resizable.offsetHeight:n,this.resizable.style.position=i}return{width:e,height:t}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"sizeStyle",{get:function(){var e=this,t=this.props.size,r=function(t){var r;if(void 0===e.state[t]||"auto"===e.state[t])return"auto";if(e.propsSize&&e.propsSize[t]&&(null===(r=e.propsSize[t])||void 0===r?void 0:r.toString().endsWith("%"))){if(e.state[t].toString().endsWith("%"))return e.state[t].toString();var n=e.getParentSize(),i=Number(e.state[t].toString().replace("px",""))/n[t]*100;return"".concat(i,"%")}return od(e.state[t])};return{width:t&&void 0!==t.width&&!this.state.isResizing?od(t.width):r("width"),height:t&&void 0!==t.height&&!this.state.isResizing?od(t.height):r("height")}},enumerable:!1,configurable:!0}),t.prototype.getParentSize=function(){if(!this.parentNode)return this.window?{width:this.window.innerWidth,height:this.window.innerHeight}:{width:0,height:0};var e=this.appendBase();if(!e)return{width:0,height:0};var t=!1,r=this.parentNode.style.flexWrap;"wrap"!==r&&(t=!0,this.parentNode.style.flexWrap="wrap"),e.style.position="relative",e.style.minWidth="100%",e.style.minHeight="100%";var n={width:e.offsetWidth,height:e.offsetHeight};return t&&(this.parentNode.style.flexWrap=r),this.removeBase(e),n},t.prototype.bindEvents=function(){this.window&&(this.window.addEventListener("mouseup",this.onMouseUp),this.window.addEventListener("mousemove",this.onMouseMove),this.window.addEventListener("mouseleave",this.onMouseUp),this.window.addEventListener("touchmove",this.onMouseMove,{capture:!0,passive:!1}),this.window.addEventListener("touchend",this.onMouseUp))},t.prototype.unbindEvents=function(){this.window&&(this.window.removeEventListener("mouseup",this.onMouseUp),this.window.removeEventListener("mousemove",this.onMouseMove),this.window.removeEventListener("mouseleave",this.onMouseUp),this.window.removeEventListener("touchmove",this.onMouseMove,!0),this.window.removeEventListener("touchend",this.onMouseUp))},t.prototype.componentDidMount=function(){if(this.resizable&&this.window){var e=this.window.getComputedStyle(this.resizable);this.setState({width:this.state.width||this.size.width,height:this.state.height||this.size.height,flexBasis:"auto"!==e.flexBasis?e.flexBasis:void 0})}},t.prototype.componentWillUnmount=function(){this.window&&this.unbindEvents()},t.prototype.createSizeForCssProperty=function(e,t){var r=this.propsSize&&this.propsSize[t];return"auto"!==this.state[t]||this.state.original[t]!==e||void 0!==r&&"auto"!==r?e:"auto"},t.prototype.calculateNewMaxFromBoundary=function(e,t){var r,n,i=this.props.boundsByDirection,s=this.state.direction,a=i&&id("left",s),o=i&&id("top",s);if("parent"===this.props.bounds){var l=this.parentNode;l&&(r=a?this.resizableRight-this.parentLeft:l.offsetWidth+(this.parentLeft-this.resizableLeft),n=o?this.resizableBottom-this.parentTop:l.offsetHeight+(this.parentTop-this.resizableTop))}else"window"===this.props.bounds?this.window&&(r=a?this.resizableRight:this.window.innerWidth-this.resizableLeft,n=o?this.resizableBottom:this.window.innerHeight-this.resizableTop):this.props.bounds&&(r=a?this.resizableRight-this.targetLeft:this.props.bounds.offsetWidth+(this.targetLeft-this.resizableLeft),n=o?this.resizableBottom-this.targetTop:this.props.bounds.offsetHeight+(this.targetTop-this.resizableTop));return r&&Number.isFinite(r)&&(e=e&&e<r?e:r),n&&Number.isFinite(n)&&(t=t&&t<n?t:n),{maxWidth:e,maxHeight:t}},t.prototype.calculateNewSizeFromDirection=function(e,t){var r,n=this.props.scale||1,i=(r=this.props.resizeRatio||1,Array.isArray(r)?r:[r,r]),s=i[0],a=i[1],o=this.state,l=o.direction,u=o.original,c=this.props,d=c.lockAspectRatio,h=c.lockAspectRatioExtraHeight,f=c.lockAspectRatioExtraWidth,p=u.width,g=u.height,m=h||0,v=f||0;return id("right",l)&&(p=u.width+(e-u.x)*s/n,d&&(g=(p-v)/this.ratio+m)),id("left",l)&&(p=u.width-(e-u.x)*s/n,d&&(g=(p-v)/this.ratio+m)),id("bottom",l)&&(g=u.height+(t-u.y)*a/n,d&&(p=(g-m)*this.ratio+v)),id("top",l)&&(g=u.height-(t-u.y)*a/n,d&&(p=(g-m)*this.ratio+v)),{newWidth:p,newHeight:g}},t.prototype.calculateNewSizeFromAspectRatio=function(e,t,r,n){var i=this.props,s=i.lockAspectRatio,a=i.lockAspectRatioExtraHeight,o=i.lockAspectRatioExtraWidth,l=void 0===n.width?10:n.width,u=void 0===r.width||r.width<0?e:r.width,c=void 0===n.height?10:n.height,d=void 0===r.height||r.height<0?t:r.height,h=a||0,f=o||0;if(s){var p=(c-h)*this.ratio+f,g=(d-h)*this.ratio+f,m=(l-f)/this.ratio+h,v=(u-f)/this.ratio+h,y=Math.max(l,p),b=Math.min(u,g),w=Math.max(c,m),E=Math.min(d,v);e=rd(e,y,b),t=rd(t,w,E)}else e=rd(e,l,u),t=rd(t,c,d);return{newWidth:e,newHeight:t}},t.prototype.setBoundingClientRect=function(){var e=1/(this.props.scale||1);if("parent"===this.props.bounds){var t=this.parentNode;if(t){var r=t.getBoundingClientRect();this.parentLeft=r.left*e,this.parentTop=r.top*e}}if(this.props.bounds&&"string"!=typeof this.props.bounds){var n=this.props.bounds.getBoundingClientRect();this.targetLeft=n.left*e,this.targetTop=n.top*e}if(this.resizable){var i=this.resizable.getBoundingClientRect(),s=i.left,a=i.top,o=i.right,l=i.bottom;this.resizableLeft=s*e,this.resizableRight=o*e,this.resizableTop=a*e,this.resizableBottom=l*e}},t.prototype.onResizeStart=function(e,t){if(this.resizable&&this.window){var r,n=0,i=0;if(e.nativeEvent&&function(e){return Boolean((e.clientX||0===e.clientX)&&(e.clientY||0===e.clientY))}(e.nativeEvent)?(n=e.nativeEvent.clientX,i=e.nativeEvent.clientY):e.nativeEvent&&sd(e.nativeEvent)&&(n=e.nativeEvent.touches[0].clientX,i=e.nativeEvent.touches[0].clientY),this.props.onResizeStart)if(this.resizable)if(!1===this.props.onResizeStart(e,t,this.resizable))return;this.props.size&&(void 0!==this.props.size.height&&this.props.size.height!==this.state.height&&this.setState({height:this.props.size.height}),void 0!==this.props.size.width&&this.props.size.width!==this.state.width&&this.setState({width:this.props.size.width})),this.ratio="number"==typeof this.props.lockAspectRatio?this.props.lockAspectRatio:this.size.width/this.size.height;var s=this.window.getComputedStyle(this.resizable);if("auto"!==s.flexBasis){var a=this.parentNode;if(a){var o=this.window.getComputedStyle(a).flexDirection;this.flexDir=o.startsWith("row")?"row":"column",r=s.flexBasis}}this.setBoundingClientRect(),this.bindEvents();var l={original:{x:n,y:i,width:this.size.width,height:this.size.height},isResizing:!0,backgroundStyle:ed(ed({},this.state.backgroundStyle),{cursor:this.window.getComputedStyle(e.target).cursor||"auto"}),direction:t,flexBasis:r};this.setState(l)}},t.prototype.onMouseMove=function(e){var t=this;if(this.state.isResizing&&this.resizable&&this.window){if(this.window.TouchEvent&&sd(e))try{e.preventDefault(),e.stopPropagation()}catch(e){}var r=this.props,n=r.maxWidth,i=r.maxHeight,s=r.minWidth,a=r.minHeight,o=sd(e)?e.touches[0].clientX:e.clientX,l=sd(e)?e.touches[0].clientY:e.clientY,u=this.state,c=u.direction,d=u.original,h=u.width,f=u.height,p=this.getParentSize(),g=function(e,t,r,n,i,s,a){return n=ld(n,e.width,t,r),i=ld(i,e.height,t,r),s=ld(s,e.width,t,r),a=ld(a,e.height,t,r),{maxWidth:void 0===n?void 0:Number(n),maxHeight:void 0===i?void 0:Number(i),minWidth:void 0===s?void 0:Number(s),minHeight:void 0===a?void 0:Number(a)}}(p,this.window.innerWidth,this.window.innerHeight,n,i,s,a);n=g.maxWidth,i=g.maxHeight,s=g.minWidth,a=g.minHeight;var m=this.calculateNewSizeFromDirection(o,l),v=m.newHeight,y=m.newWidth,b=this.calculateNewMaxFromBoundary(n,i);this.props.snap&&this.props.snap.x&&(y=ad(y,this.props.snap.x,this.props.snapGap)),this.props.snap&&this.props.snap.y&&(v=ad(v,this.props.snap.y,this.props.snapGap));var w=this.calculateNewSizeFromAspectRatio(y,v,{width:b.maxWidth,height:b.maxHeight},{width:s,height:a});if(y=w.newWidth,v=w.newHeight,this.props.grid){var E=nd(y,this.props.grid[0],this.props.gridGap?this.props.gridGap[0]:0),S=nd(v,this.props.grid[1],this.props.gridGap?this.props.gridGap[1]:0),T=this.props.snapGap||0;y=0===T||Math.abs(E-y)<=T?E:y,v=0===T||Math.abs(S-v)<=T?S:v}var x={width:y-d.width,height:v-d.height};if(this.delta=x,h&&"string"==typeof h)if(h.endsWith("%")){var k=y/p.width*100;y="".concat(k,"%")}else if(h.endsWith("vw")){var A=y/this.window.innerWidth*100;y="".concat(A,"vw")}else if(h.endsWith("vh")){var R=y/this.window.innerHeight*100;y="".concat(R,"vh")}if(f&&"string"==typeof f)if(f.endsWith("%")){k=v/p.height*100;v="".concat(k,"%")}else if(f.endsWith("vw")){A=v/this.window.innerWidth*100;v="".concat(A,"vw")}else if(f.endsWith("vh")){R=v/this.window.innerHeight*100;v="".concat(R,"vh")}var L={width:this.createSizeForCssProperty(y,"width"),height:this.createSizeForCssProperty(v,"height")};"row"===this.flexDir?L.flexBasis=L.width:"column"===this.flexDir&&(L.flexBasis=L.height);var I=this.state.width!==L.width,C=this.state.height!==L.height,P=this.state.flexBasis!==L.flexBasis,D=I||C||P;D&&Pi.flushSync(function(){t.setState(L)}),this.props.onResize&&D&&this.props.onResize(e,c,this.resizable,x)}},t.prototype.onMouseUp=function(e){var t,r,n=this.state,i=n.isResizing,s=n.direction;n.original,i&&this.resizable&&(this.props.onResizeStop&&this.props.onResizeStop(e,s,this.resizable,this.delta),this.props.size&&this.setState({width:null!==(t=this.props.size.width)&&void 0!==t?t:"auto",height:null!==(r=this.props.size.height)&&void 0!==r?r:"auto"}),this.unbindEvents(),this.setState({isResizing:!1,backgroundStyle:ed(ed({},this.state.backgroundStyle),{cursor:"auto"})}))},t.prototype.updateSize=function(e){var t,r;this.setState({width:null!==(t=e.width)&&void 0!==t?t:"auto",height:null!==(r=e.height)&&void 0!==r?r:"auto"})},t.prototype.renderResizer=function(){var e=this,t=this.props,r=t.enable,n=t.handleStyles,i=t.handleClasses,s=t.handleWrapperStyle,a=t.handleWrapperClass,o=t.handleComponent;if(!r)return null;var l=Object.keys(r).map(function(t){return!1!==r[t]?Ti.jsx(Zc,{direction:t,onResizeStart:e.onResizeStart,replaceStyles:n&&n[t],className:i&&i[t],children:o&&o[t]?o[t]:null},t):null});return Ti.jsx("div",{className:a,style:s,children:l})},t.prototype.render=function(){var e=this,t=Object.keys(this.props).reduce(function(t,r){return-1!==ud.indexOf(r)||(t[r]=e.props[r]),t},{}),r=ed(ed(ed({position:"relative",userSelect:this.state.isResizing?"none":"auto"},this.props.style),this.sizeStyle),{maxWidth:this.props.maxWidth,maxHeight:this.props.maxHeight,minWidth:this.props.minWidth,minHeight:this.props.minHeight,boxSizing:"border-box",flexShrink:0});this.state.flexBasis&&(r.flexBasis=this.state.flexBasis);var n=this.props.as||"div";return Ti.jsxs(n,ed({style:r,className:this.props.className},t,{ref:function(t){t&&(e.resizable=t)},children:[this.state.isResizing&&Ti.jsx("div",{style:this.state.backgroundStyle}),this.props.children,this.renderResizer()]}))},t.defaultProps={as:"div",onResizeStart:function(){},onResize:function(){},onResizeStop:function(){},enable:{top:!0,right:!0,bottom:!0,left:!0,topRight:!0,bottomRight:!0,bottomLeft:!0,topLeft:!0},style:{},grid:[1,1],gridGap:[0,0],lockAspectRatio:!1,lockAspectRatioExtraWidth:0,lockAspectRatioExtraHeight:0,scale:1,resizeRatio:1,snapGap:0},t}(p.PureComponent),hd=function(e,t){return hd=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},hd(e,t)};var fd=function(){return fd=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},fd.apply(this,arguments)};var pd={width:"auto",height:"auto",display:"inline-block",position:"absolute",top:0,left:0},gd=function(e){function t(t){var r=e.call(this,t)||this;return r.resizingPosition={x:0,y:0},r.offsetFromParent={left:0,top:0},r.resizableElement={current:null},r.originalPosition={x:0,y:0},r.state={resizing:!1,bounds:{top:0,right:0,bottom:0,left:0},maxWidth:t.maxWidth,maxHeight:t.maxHeight},r.onResizeStart=r.onResizeStart.bind(r),r.onResize=r.onResize.bind(r),r.onResizeStop=r.onResizeStop.bind(r),r.onDragStart=r.onDragStart.bind(r),r.onDrag=r.onDrag.bind(r),r.onDragStop=r.onDragStop.bind(r),r.getMaxSizesFromProps=r.getMaxSizesFromProps.bind(r),r}return function(e,t){function r(){this.constructor=e}hd(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}(t,e),t.prototype.componentDidMount=function(){this.updateOffsetFromParent();var e=this.offsetFromParent,t=e.left,r=e.top,n=this.getDraggablePosition(),i=n.x,s=n.y;this.draggable.setState({x:i-t,y:s-r}),this.forceUpdate()},t.prototype.getDraggablePosition=function(){var e=this.draggable.state;return{x:e.x,y:e.y}},t.prototype.getParent=function(){return this.resizable&&this.resizable.parentNode},t.prototype.getParentSize=function(){return this.resizable.getParentSize()},t.prototype.getMaxSizesFromProps=function(){return{maxWidth:void 0===this.props.maxWidth?Number.MAX_SAFE_INTEGER:this.props.maxWidth,maxHeight:void 0===this.props.maxHeight?Number.MAX_SAFE_INTEGER:this.props.maxHeight}},t.prototype.getSelfElement=function(){return this.resizable&&this.resizable.resizable},t.prototype.getOffsetHeight=function(e){var t=this.props.scale;switch(this.props.bounds){case"window":return window.innerHeight/t;case"body":return document.body.offsetHeight/t;default:return e.offsetHeight}},t.prototype.getOffsetWidth=function(e){var t=this.props.scale;switch(this.props.bounds){case"window":return window.innerWidth/t;case"body":return document.body.offsetWidth/t;default:return e.offsetWidth}},t.prototype.onDragStart=function(e,t){this.props.onDragStart&&this.props.onDragStart(e,t);var r=this.getDraggablePosition();if(this.originalPosition=r,this.props.bounds){var n,i=this.getParent(),s=this.props.scale;if("parent"===this.props.bounds)n=i;else{if("body"===this.props.bounds){var a=i.getBoundingClientRect(),o=a.left,l=a.top,u=document.body.getBoundingClientRect(),c=-(o-i.offsetLeft*s-u.left)/s,d=-(l-i.offsetTop*s-u.top)/s,h=(document.body.offsetWidth-this.resizable.size.width*s)/s+c,f=(document.body.offsetHeight-this.resizable.size.height*s)/s+d;return this.setState({bounds:{top:d,right:h,bottom:f,left:c}})}if("window"===this.props.bounds){if(!this.resizable)return;var p=i.getBoundingClientRect(),g=p.left,m=p.top,v=-(g-i.offsetLeft*s)/s,y=-(m-i.offsetTop*s)/s;h=(window.innerWidth-this.resizable.size.width*s)/s+v,f=(window.innerHeight-this.resizable.size.height*s)/s+y;return this.setState({bounds:{top:y,right:h,bottom:f,left:v}})}"string"==typeof this.props.bounds?n=document.querySelector(this.props.bounds):this.props.bounds instanceof HTMLElement&&(n=this.props.bounds)}if(n instanceof HTMLElement&&i instanceof HTMLElement){var b=n.getBoundingClientRect(),w=b.left,E=b.top,S=i.getBoundingClientRect(),T=(w-S.left)/s,x=E-S.top;if(this.resizable){this.updateOffsetFromParent();var k=this.offsetFromParent;this.setState({bounds:{top:x-k.top,right:T+(n.offsetWidth-this.resizable.size.width)-k.left/s,bottom:x+(n.offsetHeight-this.resizable.size.height)-k.top,left:T-k.left/s}})}}}},t.prototype.onDrag=function(e,t){if(this.props.onDrag){var r=this.offsetFromParent,n=r.left,i=r.top;return this.props.dragAxis&&"both"!==this.props.dragAxis?"x"===this.props.dragAxis?this.props.onDrag(e,fd(fd({},t),{x:t.x+n,y:this.originalPosition.y+i,deltaY:0})):"y"===this.props.dragAxis?this.props.onDrag(e,fd(fd({},t),{x:this.originalPosition.x+n,y:t.y+i,deltaX:0})):void 0:this.props.onDrag(e,fd(fd({},t),{x:t.x+n,y:t.y+i}))}},t.prototype.onDragStop=function(e,t){if(this.props.onDragStop){var r=this.offsetFromParent,n=r.left,i=r.top;return this.props.dragAxis&&"both"!==this.props.dragAxis?"x"===this.props.dragAxis?this.props.onDragStop(e,fd(fd({},t),{x:t.x+n,y:this.originalPosition.y+i,deltaY:0})):"y"===this.props.dragAxis?this.props.onDragStop(e,fd(fd({},t),{x:this.originalPosition.x+n,y:t.y+i,deltaX:0})):void 0:this.props.onDragStop(e,fd(fd({},t),{x:t.x+n,y:t.y+i}))}},t.prototype.onResizeStart=function(e,t,r){e.stopPropagation(),this.setState({resizing:!0});var n=this.props.scale,i=this.offsetFromParent,s=this.getDraggablePosition();if(this.resizingPosition={x:s.x+i.left,y:s.y+i.top},this.originalPosition=s,this.props.bounds){var a=this.getParent(),o=void 0;"parent"===this.props.bounds?o=a:"body"===this.props.bounds?o=document.body:"window"===this.props.bounds?o=window:"string"==typeof this.props.bounds?o=document.querySelector(this.props.bounds):this.props.bounds instanceof HTMLElement&&(o=this.props.bounds);var l=this.getSelfElement();if(l instanceof Element&&(o instanceof HTMLElement||o===window)&&a instanceof HTMLElement){var u=this.getMaxSizesFromProps(),c=u.maxWidth,d=u.maxHeight,h=this.getParentSize();if(c&&"string"==typeof c)if(c.endsWith("%")){var f=Number(c.replace("%",""))/100;c=h.width*f}else c.endsWith("px")&&(c=Number(c.replace("px","")));if(d&&"string"==typeof d)if(d.endsWith("%")){f=Number(d.replace("%",""))/100;d=h.height*f}else d.endsWith("px")&&(d=Number(d.replace("px","")));var p=l.getBoundingClientRect(),g=p.left,m=p.top,v="window"===this.props.bounds?{left:0,top:0}:o.getBoundingClientRect(),y=v.left,b=v.top,w=this.getOffsetWidth(o),E=this.getOffsetHeight(o),S=t.toLowerCase().endsWith("left"),T=t.toLowerCase().endsWith("right"),x=t.startsWith("top"),k=t.startsWith("bottom");if((S||x)&&this.resizable){var A=(g-y)/n+this.resizable.size.width;this.setState({maxWidth:A>Number(c)?c:A})}if(T||this.props.lockAspectRatio&&!S&&!x){A=w+(y-g)/n;this.setState({maxWidth:A>Number(c)?c:A})}if((x||S)&&this.resizable){A=(m-b)/n+this.resizable.size.height;this.setState({maxHeight:A>Number(d)?d:A})}if(k||this.props.lockAspectRatio&&!x&&!S){A=E+(b-m)/n;this.setState({maxHeight:A>Number(d)?d:A})}}}else this.setState({maxWidth:this.props.maxWidth,maxHeight:this.props.maxHeight});this.props.onResizeStart&&this.props.onResizeStart(e,t,r)},t.prototype.onResize=function(e,t,r,n){var i=this,s={x:this.originalPosition.x,y:this.originalPosition.y},a=-n.width,o=-n.height;["top","left","topLeft","bottomLeft","topRight"].includes(t)&&("bottomLeft"===t?s.x+=a:("topRight"===t||(s.x+=a),s.y+=o));var l=this.draggable.state;s.x===l.x&&s.y===l.y||Pi.flushSync(function(){i.draggable.setState(s)}),this.updateOffsetFromParent();var u=this.offsetFromParent,c=this.getDraggablePosition().x+u.left,d=this.getDraggablePosition().y+u.top;this.resizingPosition={x:c,y:d},this.props.onResize&&this.props.onResize(e,t,r,n,{x:c,y:d})},t.prototype.onResizeStop=function(e,t,r,n){this.setState({resizing:!1});var i=this.getMaxSizesFromProps(),s=i.maxWidth,a=i.maxHeight;this.setState({maxWidth:s,maxHeight:a}),this.props.onResizeStop&&this.props.onResizeStop(e,t,r,n,this.resizingPosition)},t.prototype.updateSize=function(e){this.resizable&&this.resizable.updateSize({width:e.width,height:e.height})},t.prototype.updatePosition=function(e){this.draggable.setState(e)},t.prototype.updateOffsetFromParent=function(){var e=this.props.scale,t=this.getParent(),r=this.getSelfElement();if(!t||null===r)return{top:0,left:0};var n=t.getBoundingClientRect(),i=n.left,s=n.top,a=r.getBoundingClientRect(),o=this.getDraggablePosition(),l=t.scrollLeft,u=t.scrollTop;this.offsetFromParent={left:a.left-i+l-o.x*e,top:a.top-s+u-o.y*e}},t.prototype.render=function(){var e=this,t=this.props,r=t.disableDragging,n=t.style,i=t.dragHandleClassName,s=t.position,a=t.onMouseDown,o=t.onMouseUp,l=t.dragAxis,u=t.dragGrid,c=t.bounds,d=t.enableUserSelectHack,h=t.cancel,f=t.children;t.onResizeStart,t.onResize,t.onResizeStop,t.onDragStart,t.onDrag,t.onDragStop;var g=t.resizeHandleStyles,m=t.resizeHandleClasses,v=t.resizeHandleComponent,y=t.enableResizing,b=t.resizeGrid,w=t.resizeHandleWrapperClass,E=t.resizeHandleWrapperStyle,S=t.scale,T=t.allowAnyClick,x=t.dragPositionOffset,k=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]])}return r}(t,["disableDragging","style","dragHandleClassName","position","onMouseDown","onMouseUp","dragAxis","dragGrid","bounds","enableUserSelectHack","cancel","children","onResizeStart","onResize","onResizeStop","onDragStart","onDrag","onDragStop","resizeHandleStyles","resizeHandleClasses","resizeHandleComponent","enableResizing","resizeGrid","resizeHandleWrapperClass","resizeHandleWrapperStyle","scale","allowAnyClick","dragPositionOffset"]),A=this.props.default?fd({},this.props.default):void 0;delete k.default;var R,L=r||i?{cursor:"auto"}:{cursor:"move"},I=fd(fd(fd({},pd),L),n),C=this.offsetFromParent,P=C.left,D=C.top;s&&(R={x:s.x-P,y:s.y-D});var _,M=this.state.resizing?void 0:R,O=this.state.resizing?"both":l;return p.createElement(Wc,{ref:function(t){t&&(e.draggable=t)},handle:i?".".concat(i):void 0,defaultPosition:A,onMouseDown:a,onMouseUp:o,onStart:this.onDragStart,onDrag:this.onDrag,onStop:this.onDragStop,axis:O,disabled:r,grid:u,bounds:c?this.state.bounds:void 0,position:M,enableUserSelectHack:d,cancel:h,scale:S,allowAnyClick:T,nodeRef:this.resizableElement,positionOffset:x},p.createElement(dd,fd({},k,{ref:function(t){t&&(e.resizable=t,e.resizableElement.current=t.resizable)},defaultSize:A,size:this.props.size,enable:"boolean"==typeof y?(_=y,{bottom:_,bottomLeft:_,bottomRight:_,left:_,right:_,top:_,topLeft:_,topRight:_}):y,onResizeStart:this.onResizeStart,onResize:this.onResize,onResizeStop:this.onResizeStop,style:I,minWidth:this.props.minWidth,minHeight:this.props.minHeight,maxWidth:this.state.resizing?this.state.maxWidth:this.props.maxWidth,maxHeight:this.state.resizing?this.state.maxHeight:this.props.maxHeight,grid:b,handleWrapperClass:w,handleWrapperStyle:E,lockAspectRatio:this.props.lockAspectRatio,lockAspectRatioExtraWidth:this.props.lockAspectRatioExtraWidth,lockAspectRatioExtraHeight:this.props.lockAspectRatioExtraHeight,handleStyles:g,handleClasses:m,handleComponent:v,scale:this.props.scale}),f))},t.defaultProps={maxWidth:Number.MAX_SAFE_INTEGER,maxHeight:Number.MAX_SAFE_INTEGER,scale:1,onResizeStart:function(){},onResize:function(){},onResizeStop:function(){},onDragStart:function(){},onDrag:function(){},onDragStop:function(){}},t}(p.PureComponent);const md=({shortform:e,mute:t,play:r})=>{const n=Ft(e.media.objectId);return Object.assign({hideProducts:!0},e.playerSettings),g.createElement("div",{className:"relative w-full h-full text-white"},g.createElement(oi,{file:n,mute:t,play:r}))},vd=({shortform:e,setClose:t})=>{const[r,n]=g.useState(!0),[i,s]=p.useState(!0),[a,o]=p.useState(!1),l=g.useRef(null),u=()=>{l.current&&(window.clearTimeout(l.current),l.current=null)},c=(e=1500)=>{u(),l.current=window.setTimeout(()=>o(!1),e)};return p.useEffect(()=>()=>u(),[]),g.createElement("div",{className:"relative w-full h-full",onClick:()=>{o(!0),c(2e3)},onMouseLeave:()=>c(800),onMouseEnter:()=>a&&c(1500)},g.createElement("div",{className:"absolute inset-0 bg-black",style:{zIndex:1,opacity:a?.4:0,transition:"opacity 300ms ease",pointerEvents:a?"auto":"none"}}),g.createElement("div",{className:"absolute inset-0",style:{zIndex:2,opacity:a?1:0,transition:"opacity 300ms ease",pointerEvents:a?"auto":"none"}},g.createElement("div",{className:"absolute text-white flex gap-2",style:{zIndex:3,top:8,right:8}},g.createElement("button",{className:"cursor-pointer",onClick:e=>{e.stopPropagation(),n(e=>!e)},"aria-label":r?"Unmute":"Mute"},r?g.createElement(si,{size:20}):g.createElement(ii,{size:20})),g.createElement("button",{className:"cursor-pointer",onClick:e=>{null==e||e.stopPropagation(),t()},"aria-label":"Close"},g.createElement(ai,{size:20}))),g.createElement("div",{className:"absolute inset-0 flex items-center justify-center",style:{pointerEvents:"none"}},g.createElement("button",{onClick:e=>{null==e||e.stopPropagation(),s(e=>!e)},"aria-label":i?"Pause":"Play",className:"cursor-pointer text-white p-2 ",style:{pointerEvents:"auto"}},i?g.createElement(ti,{size:28}):g.createElement(ri,{size:28})))),g.createElement(md,{shortform:e,mute:r,play:i}))},yd=({shortsId:e,type:t})=>{const{shortform:r}=bc(),[n,i]=p.useState(!1),{playtime:s}=Kt(),a=()=>{if(!r)return;i(!0);const{shortsId:e,uuid:t,userId:n}=r;Qt({contentId:e,uuid:t,type:X.SHORTS,playtime:s,userId:n})};(({shorform:e,playtime:t})=>{p.useEffect(()=>{if(!e)return;const{shortsId:t,shortsUuid:r,userId:n}=e;Xt({contentId:t,uuid:r,type:X.SHORTS,userId:n,isFirstPlay:!zt(t)})},[]);const r=ne();p.useEffect(()=>{if(!e||r)return;const{shortsId:n,uuid:i,userId:s}=e;Qt({contentId:n,uuid:i,type:X.SHORTS,playtime:t,userId:s})},[r])})({shorform:r,playtime:s});const{w:o,h:l,left:u,top:c}=(()=>{const e=window.visualViewport;return e?{w:e.width,h:e.height,left:e.offsetLeft,top:e.offsetTop}:{w:window.innerWidth,h:window.innerHeight,left:0,top:0}})();return r&&!n&&g.createElement(gd,{minWidth:240,lockAspectRatio:9/16,style:{zIndex:99999},default:{width:240,height:427,x:u+o-240-50,y:c+l-427-50},bounds:"window"},"shopping"===t&&r.productsInfo.length>0?g.createElement(Bo,{shortForm:r,handleClose:a}):g.createElement(vd,{shortform:r,setClose:a}))},bd=({eventId:e})=>{const[t,r]=p.useState(!1),{PLAYER_BASE_URL:n}=Mt();if(t)return null;const{w:i,h:s,left:a,top:o}=(()=>{const e=window.visualViewport;return e?{w:e.width,h:e.height,left:e.offsetLeft,top:e.offsetTop}:{w:window.innerWidth,h:window.innerHeight,left:0,top:0}})();return g.createElement(gd,{minWidth:240,lockAspectRatio:9/17.05,style:{zIndex:99999},default:{width:240,height:455,x:a+i-240-50,y:o+s-427-28-50},bounds:"window",dragHandleClassName:"live-floating-drag-handle"},g.createElement("div",{className:"flex flex-col w-full h-full",style:{borderRadius:8,overflow:"hidden",boxShadow:"0 4px 24px rgba(0,0,0,0.4)"}},g.createElement("div",{className:"live-floating-drag-handle flex items-center justify-between",style:{height:28,minHeight:28,background:"#111",cursor:"grab",padding:"0 8px",userSelect:"none"}},g.createElement(Jn,{size:16,color:"#888"}),g.createElement("button",{className:"cursor-pointer",style:{color:"#ccc",lineHeight:0},onClick:()=>r(!0),"aria-label":"Close"},g.createElement(ai,{size:16}))),g.createElement("iframe",{src:`${n}/live/${e}`,style:{flex:1,border:0,display:"block",minHeight:0},allow:"autoplay; fullscreen; picture-in-picture",allowFullScreen:!0,scrolling:"no",referrerPolicy:"no-referrer-when-downgrade"})))};var wd;!function(e){e[e.PLATFORM=1]="PLATFORM",e[e.GRID=2]="GRID",e[e.VERTICAL=3]="VERTICAL",e[e.HORIZONTAL=4]="HORIZONTAL"}(wd||(wd={}));const Ed=ur(e=>({liveWidget:null,setLiveWidget:t=>e({liveWidget:t}),nextKey:"",setNextKey:t=>e({nextKey:t}),isFetching:!1,setIsFetching:t=>e({isFetching:t})})),Sd=({opacity:e=.4,className:t})=>{const r=Math.max(0,Math.min(1,e));return g.createElement("div",{"aria-hidden":!0,role:"presentation",className:`absolute inset-0 pointer-events-none ${null!=t?t:""}`,style:{backgroundColor:`rgba(0,0,0,${r})`,borderRadius:"inherit"}})},Td=({content:e})=>{const{PLAYER_BASE_URL:t}=Mt();return g.createElement("iframe",{src:`${t}/live/${e.eventId}`,className:"w-full h-full block",style:{border:0,display:"block"},allow:"autoplay; fullscreen; picture-in-picture",allowFullScreen:!0,scrolling:"no",referrerPolicy:"no-referrer-when-downgrade"})},xd=(e,t)=>{const[r,n]=g.useState({}),[i,s]=g.useState({primary:20,secondary:12});return g.useEffect(()=>{const r=t.current;if(!r)return;const i=()=>{const t=r.getBoundingClientRect(),i=Math.max(0,Math.floor(t.width)),a=Math.max(0,Math.floor(t.height)),[o,l]=e.includes("/")?e.split("/").map(e=>parseFloat(e)):[1,1],u=l/o;let c,d;i>0&&a>0?(c=i,d=Math.round(c*u),d>a&&(d=a,c=Math.round(d/u)),n({width:c,height:d})):n({});const h="number"==typeof c?c:i,f=Math.max(16,Math.round(.075*h)),p=Math.max(11,Math.round(.042*h));s({primary:f,secondary:p})};if("undefined"!=typeof ResizeObserver){const e=new ResizeObserver(()=>i());return e.observe(r),()=>e.disconnect()}{const e=()=>i();return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)}},[e]),{fontSize:i,boxSize:r}},kd=({content:e,aspectRatio:t="9/16",cursor:r="default",borderRadius:n})=>{var i,s;const{leftTime:a}=(e=>{const{start:t}=e,r=vt().tz("Asia/Seoul").unix(),[n,i]=p.useState(t-r>0?t-r:0);return Wt(()=>{i(n<=0?0:e=>e-1)},1e3),{leftTime:n}})(e),o=null===(s=null===(i=null==e?void 0:e.designInfo)||void 0===i?void 0:i.thumbPath)||void 0===s?void 0:s.preview,l=g.useRef(null),{boxSize:u,fontSize:c}=xd(t,l),{PLAYER_BASE_URL:d}=Mt(),h=Math.floor(Date.now()/1e3),f="number"==typeof e.end&&e.end>0&&e.end<h;return g.createElement("div",{className:"w-full h-full flex items-center justify-center",ref:l},g.createElement("div",{className:"relative rounded overflow-hidden",style:{width:u.width?`${u.width}px`:"100%",height:u.height?`${u.height}px`:"100%",borderRadius:`${null!=n?n:10}px`,backgroundRepeat:"no-repeat",backgroundPosition:"center",backgroundSize:"cover",aspectRatio:u.height?void 0:t,backgroundImage:o?`url(${Gt(o)})`:void 0,backgroundColor:o?void 0:"black"}},1===e.openStatus?g.createElement(g.Fragment,null,g.createElement(Td,{content:e}),g.createElement("a",{href:`${d}/live/${e.eventId}`,target:"_blank",rel:"noopener noreferrer","aria-label":`${e.eventName} 바로가기`,style:{position:"absolute",inset:0,zIndex:30,display:"block",textDecoration:"none",cursor:"pointer",background:"transparent"}})):f?g.createElement(g.Fragment,null,g.createElement(Sd,null),g.createElement("div",{className:"text-white flex flex-col items-center justify-center absolute inset-0",style:{zIndex:10,gap:"12px",userSelect:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none",cursor:r,pointerEvents:"none"}},g.createElement("p",{style:{fontSize:`${c.primary}px`,fontWeight:700}},"다시보기"),g.createElement("p",{style:{fontSize:`${c.secondary}px`}},"라이브가 종료되었습니다"))):g.createElement(g.Fragment,null,g.createElement(Sd,null),g.createElement("div",{className:"text-white flex flex-col items-center justify-center absolute inset-0",style:{zIndex:10,gap:"20px",userSelect:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none",cursor:r,pointerEvents:"none"}},g.createElement("p",{style:{fontSize:`${c.primary}px`}},((e,t)=>{if(e>86400)return vt.unix(t).tz("Asia/Seoul").format("M월 D일 A h시 mm분");const r=vt.duration(e,"seconds");return`${r.hours().toString().padStart(2,"0")}:${r.minutes().toString().padStart(2,"0")}:${r.seconds().toString().padStart(2,"0")}`})(a,e.start)),g.createElement("p",{style:{fontSize:`${c.secondary}px`}},"곧 라이브가 시작됩니다!")))))},Ad=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},Rd=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=Ld},Ld=Number.MAX_SAFE_INTEGER||9007199254740991;let Id=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),Cd=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.UNKNOWN="unknown",e}({}),Pd=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({});var Dd="manifest",_d="level",Md="audioTrack",Od="subtitleTrack",Nd="main",Fd="audio",$d="subtitle";class Bd{constructor(e,t=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_=t,this.totalWeight_=r}sample(e,t){const r=Math.pow(this.alpha_,e);this.estimate_=t*(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 Ud{constructor(e,t,r,n=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 Bd(e),this.fast_=new Bd(t),this.defaultTTFB_=n,this.ttfb_=new Bd(e)}update(e,t){const{slow_:r,fast_:n,ttfb_:i}=this;r.halfLife!==e&&(this.slow_=new Bd(e,r.getEstimate(),r.getTotalWeight())),n.halfLife!==t&&(this.fast_=new Bd(t,n.getEstimate(),n.getTotalWeight())),i.halfLife!==e&&(this.ttfb_=new Bd(e,i.getEstimate(),i.getTotalWeight()))}sample(e,t){const r=(e=Math.max(e,this.minDelayMs_))/1e3,n=8*t/r;this.fast_.sample(r,n),this.slow_.sample(r,n)}sampleTTFB(e){const t=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(t,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 zd(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function jd(){return jd=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},jd.apply(null,arguments)}function Gd(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function Hd(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Gd(Object(r),!0).forEach(function(t){zd(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Gd(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}class Vd{constructor(e,t){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=Wd,this.debug=t.debug.bind(null,r),this.log=t.log.bind(null,r),this.warn=t.warn.bind(null,r),this.info=t.info.bind(null,r),this.error=t.error.bind(null,r)}}const Wd=function(){},Kd={trace:Wd,debug:Wd,log:Wd,warn:Wd,info:Wd,error:Wd};function Yd(){return jd({},Kd)}function qd(e,t,r){return t[e]?t[e].bind(t):function(e,t){const r=self.console[e];return r?r.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):Wd}(e,r)}const Xd=Yd();const Qd=Xd;function Zd(e=!0){if("undefined"==typeof self)return;return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Jd(e,t){const r=Object.keys(e),n=Object.keys(t),i=r.length,s=n.length;return!i||!s||i===s&&!r.some(e=>-1===n.indexOf(e))}function eh(e,t=!1){if("undefined"!=typeof TextDecoder){const r=new TextDecoder("utf-8").decode(e);if(t){const e=r.indexOf("\0");return-1!==e?r.substring(0,e):r}return r.replace(/\0/g,"")}const r=e.length;let n,i,s,a="",o=0;for(;o<r;){if(n=e[o++],0===n&&t)return a;if(0!==n&&3!==n)switch(n>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(n);break;case 12:case 13:i=e[o++],a+=String.fromCharCode((31&n)<<6|63&i);break;case 14:i=e[o++],s=e[o++],a+=String.fromCharCode((15&n)<<12|(63&i)<<6|63&s)}}return a}function th(e){let t="";for(let r=0;r<e.length;r++){let n=e[r].toString(16);n.length<2&&(n="0"+n),t+=n}return t}function rh(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function nh(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ih,sh={exports:{}};var ah,oh,lh,uh,ch,dh=(ih||(ih=1,ah=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,oh=/^(?=([^\/?#]*))\1([^]*)$/,lh=/(?:\/|^)\.(?=\/)/g,uh=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,sh.exports=ch={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.alwaysNormalize)return e;var n=ch.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");return n.path=ch.normalizePath(n.path),ch.buildURLFromParts(n)}var i=ch.parseURL(t);if(!i)throw new Error("Error trying to parse relative URL.");if(i.scheme)return r.alwaysNormalize?(i.path=ch.normalizePath(i.path),ch.buildURLFromParts(i)):t;var s=ch.parseURL(e);if(!s)throw new Error("Error trying to parse base URL.");if(!s.netLoc&&s.path&&"/"!==s.path[0]){var a=oh.exec(s.path);s.netLoc=a[1],s.path=a[2]}s.netLoc&&!s.path&&(s.path="/");var o={scheme:s.scheme,netLoc:i.netLoc,path:null,params:i.params,query:i.query,fragment:i.fragment};if(!i.netLoc&&(o.netLoc=s.netLoc,"/"!==i.path[0]))if(i.path){var l=s.path,u=l.substring(0,l.lastIndexOf("/")+1)+i.path;o.path=ch.normalizePath(u)}else o.path=s.path,i.params||(o.params=s.params,i.query||(o.query=s.query));return null===o.path&&(o.path=r.alwaysNormalize?ch.normalizePath(i.path):i.path),ch.buildURLFromParts(o)},parseURL:function(e){var t=ah.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(lh,"");e.length!==(e=e.replace(uh,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}}),sh.exports);class hh{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 fh="audio",ph="video",gh="audiovideo";class mh{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof e&&(e={url:e}),this.base=e,function(e,t){const r=wh(e,t);r&&(r.enumerable=!0,Object.defineProperty(e,t,r))}(this,"stats")}setByteRange(e,t){const r=e.split("@",2);let n;n=1===r.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(r[1]),this._byteRange=[n,parseInt(r[0])+n]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[fh]:null,[ph]:null,[gh]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new hh),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=dh.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[fh]=null,e[ph]=null,e[gh]=null}}function vh(e){return"initSegment"!==e.sn}class yh extends mh{constructor(e,t){super(t),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],t=this.byteRange[1];if(Ad(e)&&Ad(t))return t-e}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(null==(e=this._decryptdata)||!e.keyId){const e=Object.keys(t);if(1===e.length){const r=this._decryptdata=t[e[0]]||null;r&&(this._decryptdata=r.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const e=Ad(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t;const e=Object.keys(this.levelkeys),r=e.length;if(r>1||1===r&&null!=(t=this.levelkeys[e[0]])&&t.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){Ad(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}get ref(){return vh(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 t=this.levelkeys;if(t){var r;const n=t[e];!n||null!=(r=this._decryptdata)&&r.keyId||(this._decryptdata=n.getDecryptData(this.sn,t))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,r,n,i,s=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,n),o.endDTS=Math.max(o.endDTS,i)):a[e]={startPTS:t,endPTS:r,startDTS:n,endDTS:i,partial:s}}}class bh extends mh{constructor(e,t,r,n,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=t,this.index=n;const s=e.enumeratedString("BYTERANGE");s&&this.setByteRange(s,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 wh(e,t){const r=Object.getPrototypeOf(e);if(r){const e=Object.getOwnPropertyDescriptor(r,t);return e||wh(r,t)}}const Eh=Math.pow(2,32)-1,Sh=[].push,Th={video:1,audio:2,id3:3,text:4};function xh(e){return String.fromCharCode.apply(null,e)}function kh(e,t){const r=e[t]<<8|e[t+1];return r<0?65536+r:r}function Ah(e,t){const r=Lh(e,t);return r<0?4294967296+r:r}function Rh(e,t){let r=Ah(e,t);return r*=Math.pow(2,32),r+=Ah(e,t+4),r}function Lh(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function Ih(e,t){const r=[];if(!t.length)return r;const n=e.byteLength;for(let i=0;i<n;){const s=Ah(e,i),a=s>1?i+s:n;if(xh(e.subarray(i+4,i+8))===t[0])if(1===t.length)r.push(e.subarray(i+8,a));else{const n=Ih(e.subarray(i+8,a),t.slice(1));n.length&&Sh.apply(r,n)}i=a}return r}function Ch(e){const t=[],r=e[0];let n=8;const i=Ah(e,n);n+=4;let s=0,a=0;0===r?(s=Ah(e,n),a=Ah(e,n+4),n+=8):(s=Rh(e,n),a=Rh(e,n+8),n+=16),n+=2;let o=e.length+a;const l=kh(e,n);n+=2;for(let r=0;r<l;r++){let r=n;const s=Ah(e,r);r+=4;const a=2147483647&s;if(1===(2147483648&s)>>>31)return Qd.warn("SIDX has hierarchical references (not supported)"),null;const l=Ah(e,r);r+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/i,start:o,end:o+a-1}}),o+=a,r+=4,n=r}return{earliestPresentationTime:s,timescale:i,version:r,referencesCount:l,references:t}}function Ph(e){const t=[],r=Ih(e,["moov","trak"]);for(let e=0;e<r.length;e++){const n=r[e],i=Ih(n,["tkhd"])[0];if(i){let e=i[0];const r=Ah(i,0===e?12:20),s=Ih(n,["mdia","mdhd"])[0];if(s){e=s[0];const i=Ah(s,0===e?12:20),a=Ih(n,["mdia","hdlr"])[0];if(a){const e=xh(a.subarray(8,12)),s={soun:fh,vide:ph}[e],o=Dh(Ih(n,["mdia","minf","stbl","stsd"])[0]);s?(t[r]={timescale:i,type:s,stsd:o},t[s]=Hd({timescale:i,id:r},o)):t[r]={timescale:i,type:e,stsd:o}}}}}return Ih(e,["moov","mvex","trex"]).forEach(e=>{const r=Ah(e,4),n=t[r];n&&(n.default={duration:Ah(e,12),flags:Ah(e,20)})}),t}function Dh(e){const t=e.subarray(8),r=t.subarray(86),n=xh(t.subarray(4,8));let i,s=n;const a="enca"===n||"encv"===n;if(a){const e=Ih(t,[n])[0];Ih(e.subarray("enca"===n?28:78),["sinf"]).forEach(e=>{const t=Ih(e,["schm"])[0];if(t){const r=xh(t.subarray(4,8));if("cbcs"===r||"cenc"===r){const t=Ih(e,["frma"])[0];t&&(s=xh(t))}}})}const o=s;switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const e=Ih(r,["avcC"])[0];e&&e.length>3&&(s+="."+Oh(e[1])+Oh(e[2])+Oh(e[3]),i=_h("avc1"===o?"dva1":"dvav",r));break}case"mp4a":{const e=Ih(t,[n])[0],r=Ih(e.subarray(28),["esds"])[0];if(r&&r.length>7){let e=4;if(3!==r[e++])break;e=Mh(r,e),e+=2;const t=r[e++];if(128&t&&(e+=2),64&t&&(e+=r[e++]),4!==r[e++])break;e=Mh(r,e);const n=r[e++];if(64!==n)break;if(s+="."+Oh(n),e+=12,5!==r[e++])break;e=Mh(r,e);const i=r[e++];let a=(248&i)>>3;31===a&&(a+=1+((7&i)<<3)+((224&r[e])>>5)),s+="."+a}break}case"hvc1":case"hev1":{const e=Ih(r,["hvcC"])[0];if(e&&e.length>12){const t=e[1],r=["","A","B","C"][t>>6],n=31&t,i=Ah(e,2),a=(32&t)>>5?"H":"L",o=e[12],l=e.subarray(6,12);s+="."+r+n,s+="."+function(e){let t=0;for(let r=0;r<32;r++)t|=(e>>r&1)<<31-r;return t>>>0}(i).toString(16).toUpperCase(),s+="."+a+o;let u="";for(let e=l.length;e--;){const t=l[e];if(t||u){u="."+t.toString(16).toUpperCase()+u}}s+=u}i=_h("hev1"==o?"dvhe":"dvh1",r);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":s=_h(s,r)||s;break;case"vp09":{const e=Ih(r,["vpcC"])[0];if(e&&e.length>6){const t=e[4],r=e[5],n=e[6]>>4&15;s+="."+Nh(t)+"."+Nh(r)+"."+Nh(n)}break}case"av01":{const e=Ih(r,["av1C"])[0];if(e&&e.length>2){const t=e[1]>>>5,n=31&e[1],a=e[2]>>>7?"H":"M",o=(64&e[2])>>6,l=(32&e[2])>>5,u=2===t&&o?l?12:10:o?10:8,c=(16&e[2])>>4,d=(8&e[2])>>3,h=(4&e[2])>>2,f=3&e[2],p=1,g=1,m=1,v=0;s+="."+t+"."+Nh(n)+a+"."+Nh(u)+"."+c+"."+d+h+f+"."+Nh(p)+"."+Nh(g)+"."+Nh(m)+"."+v,i=_h("dav1",r)}break}}return{codec:s,encrypted:a,supplemental:i}}function _h(e,t){const r=Ih(t,["dvvC"]),n=r.length?r[0]:Ih(t,["dvcC"])[0];if(n){const t=n[2]>>1&127,r=n[2]<<5&32|n[3]>>3&31;return e+"."+Nh(t)+"."+Nh(r)}}function Mh(e,t){const r=t+5;for(;128&e[t++]&&t<r;);return t}function Oh(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function Nh(e){return(e<10?"0":"")+e}function Fh(e,t){Ih(e,["moov","trak"]).forEach(e=>{const r=Ih(e,["mdia","minf","stbl","stsd"])[0];if(!r)return;const n=r.subarray(8);let i=Ih(n,["enca"]);const s=i.length>0;s||(i=Ih(n,["encv"])),i.forEach(e=>{Ih(s?e.subarray(28):e.subarray(78),["sinf"]).forEach(e=>{const r=$h(e);r&&t(r,s)})})})}function $h(e){const t=Ih(e,["schm"])[0];if(t){const r=xh(t.subarray(4,8));if("cbcs"===r||"cenc"===r){const t=Ih(e,["schi","tenc"])[0];if(t)return t}}}function Bh(e,t){const r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function Uh(e,t){const r=[],n=t.samples,i=t.timescale,s=t.id;let a=!1;return Ih(n,["moof"]).map(o=>{const l=o.byteOffset-8;Ih(o,["traf"]).map(o=>{const u=Ih(o,["tfdt"]).map(e=>{const t=e[0];let r=Ah(e,4);return 1===t&&(r*=Math.pow(2,32),r+=Ah(e,8)),r/i})[0];return void 0!==u&&(e=u),Ih(o,["tfhd"]).map(u=>{const c=Ah(u,4),d=16777215&Ah(u,0);let h=0;const f=!!(16&d);let p=0;const g=!!(32&d);let m=8;c===s&&(!!(1&d)&&(m+=8),!!(2&d)&&(m+=4),!!(8&d)&&(h=Ah(u,m),m+=4),f&&(p=Ah(u,m),m+=4),g&&(m+=4),"video"===t.type&&(a=zh(t.codec)),Ih(o,["trun"]).map(s=>{const o=s[0],u=16777215&Ah(s,0),c=!!(1&u);let d=0;const f=!!(4&u),g=!!(256&u);let m=0;const v=!!(512&u);let y=0;const b=!!(1024&u),w=!!(2048&u);let E=0;const S=Ah(s,4);let T=8;c&&(d=Ah(s,T),T+=4),f&&(T+=4);let x=d+l;for(let l=0;l<S;l++){if(g?(m=Ah(s,T),T+=4):m=h,v?(y=Ah(s,T),T+=4):y=p,b&&(T+=4),w&&(E=0===o?Ah(s,T):Lh(s,T),T+=4),t.type===ph){let t=0;for(;t<y;){const s=Ah(n,x);if(x+=4,jh(a,n[x])){Gh(n.subarray(x,x+s),a?2:1,e+E/i,r)}x+=s,t+=s+4}}e+=m/i}}))})})}),r}function zh(e){if(!e)return!1;const t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function jh(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6===(31&t)}function Gh(e,t,r,n){const i=Hh(e);let s=0;s+=t;let a=0,o=0,l=0;for(;s<i.length;){a=0;do{if(s>=i.length)break;l=i[s++],a+=l}while(255===l);o=0;do{if(s>=i.length)break;l=i[s++],o+=l}while(255===l);const e=i.length-s;let t=s;if(o<e)s+=o;else if(o>e){Qd.error(`Malformed SEI payload. ${o} is too small, only ${e} bytes left to parse.`);break}if(4===a){if(181===i[t++]){const e=kh(i,t);if(t+=2,49===e){const e=Ah(i,t);if(t+=4,1195456820===e){const e=i[t++];if(3===e){const s=i[t++],o=64&s,l=o?2+3*(31&s):0,u=new Uint8Array(l);if(o){u[0]=s;for(let e=1;e<l;e++)u[e]=i[t++]}n.push({type:e,payloadType:a,pts:r,bytes:u})}}}}}else if(5===a&&o>16){const e=[];for(let r=0;r<16;r++){const n=i[t++].toString(16);e.push(1==n.length?"0"+n:n),3!==r&&5!==r&&7!==r&&9!==r||e.push("-")}const s=o-16,l=new Uint8Array(s);for(let e=0;e<s;e++)l[e]=i[t++];n.push({payloadType:a,pts:r,uuid:e.join(""),userData:eh(l),userDataBytes:l})}}}function Hh(e){const t=e.byteLength,r=[];let n=1;for(;n<t-2;)0===e[n]&&0===e[n+1]&&3===e[n+2]?(r.push(n+2),n+=2):n++;if(0===r.length)return e;const i=t-r.length,s=new Uint8Array(i);let a=0;for(n=0;n<i;a++,n++)a===r[0]&&(a++,r.shift()),s[n]=e[a];return s}function Vh(e,t,r){if(16!==e.byteLength)throw new RangeError("Invalid system id");let n,i,s;n=0,i=new Uint8Array,s=new Uint8Array;const a=new Uint8Array(4);return r.byteLength>0&&new DataView(a.buffer).setUint32(0,r.byteLength,!1),function(e,...t){const r=t.length;let n=8,i=r;for(;i--;)n+=t[i].byteLength;const s=new Uint8Array(n);for(s[0]=n>>24&255,s[1]=n>>16&255,s[2]=n>>8&255,s[3]=255&n,s.set(e,4),i=0,n=8;i<r;i++)s.set(t[i],n),n+=t[i].byteLength;return s}([112,115,115,104],new Uint8Array([0,0,0,0]),e,s,i,a,r)}function Wh(e){const t=e.getUint32(0),r=e.byteOffset,n=e.byteLength;if(n<t)return{offset:r,size:n};if(1886614376!==e.getUint32(4))return{offset:r,size:t};const i=e.getUint32(8)>>>24;if(0!==i&&1!==i)return{offset:r,size:t};const s=e.buffer,a=th(new Uint8Array(s,r+12,16));let o=null,l=null,u=0;if(0===i)u=28;else{const i=e.getUint32(28);if(!i||n<32+16*i)return{offset:r,size:t};o=[];for(let e=0;e<i;e++)o.push(new Uint8Array(s,r+32+16*e,16));u=32+16*i}if(!u)return{offset:r,size:t};const c=e.getUint32(u);return t-32<c?{offset:r,size:t}:(l=new Uint8Array(s,r+u+4,c),{version:i,systemId:a,kids:o,data:l,offset:r,size:t})}const Kh=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Yh={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 qh(e,t){const r=Yh[t];return!!r&&!!r[e.slice(0,4)]}function Xh(e,t,r=!0){return!e.split(",").some(e=>!Qh(e,t,r))}function Qh(e,t,r=!0){var n;const i=Zd(r);return null!=(n=null==i?void 0:i.isTypeSupported(Zh(e,t)))&&n}function Zh(e,t){return`${t}/mp4;codecs=${e}`}function Jh(e){if(e){const t=e.substring(0,4);return Yh.video[t]}return 2}function ef(e){const t=Kh();return e.split(",").reduce((e,r)=>{const n=t&&zh(r)?9:Yh.video[r];return n?(2*n+e)/(e?3:2):(Yh.audio[r]+e)/(e?2:1)},0)}const tf={};const rf=/flac|opus|mp4a\.40\.34/i;function nf(e,t=!0){return e.replace(rf,e=>function(e,t=!0){if(tf[e])return tf[e];const r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let i=0;i<r.length;i++){var n;if(Qh(r[i],"audio",t))return tf[e]=r[i],r[i];if("mp3"===r[i]&&null!=(n=Zd(t))&&n.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t))}function sf(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(af(e,"audio")||af(e,"video")))return e;if(t){const r=t.split(",");if(r.length>1){if(e)for(let t=r.length;t--;)if(r[t].substring(0,4)===e.substring(0,4))return r[t];return r[0]}}return t||e}function af(e,t){return qh(e,t)&&Qh(e,t)}function of(e){if(e.startsWith("av01.")){const t=e.split("."),r=["0","111","01","01","01","0"];for(let e=t.length;e>4&&e<10;e++)t[e]=r[e-4];return t.join(".")}return e}function lf(e){const t=Zd(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function uf(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const cf={supported:!1,smooth:!1,powerEfficient:!1},df={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function hf(e,t){return{supported:!1,configurations:t,decodingInfoResults:[cf],error:e}}function ff(e,t,r,n,i,s){const a=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=null==s?void 0:s.audioCodec,u=null==s?void 0:s.channels,c=u?parseInt(u):l?1/0:2;let d=null;if(null!=o&&o.length)try{d=1===o.length&&o[0]?t.groups[o[0]].channels:o.reduce((e,r)=>{if(r){const n=t.groups[r];if(!n)throw new Error(`Audio track group ${r} not found`);Object.keys(n.channels).forEach(t=>{e[t]=(e[t]||0)+n.channels[t]})}return e},{2:0})}catch(e){return!0}return void 0!==a&&(a.split(",").some(e=>zh(e))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(n,30)||"SDR"!==e.videoRange&&e.videoRange!==r||e.bitrate>Math.max(i,8e6))||!!d&&Ad(c)&&Object.keys(d).some(e=>parseInt(e)>c)}function pf(e,t,r,n={}){const i=e.videoCodec;if(!i&&!e.audioCodec||!r)return Promise.resolve(df);const s=[],a=function(e){var t;const r=null==(t=e.videoCodec)?void 0:t.split(","),n=mf(e),i=e.width||640,s=e.height||480,a=e.frameRate||30,o=e.videoRange.toLowerCase();return r?r.map(e=>{const t={contentType:Zh(of(e),"video"),width:i,height:s,bitrate:n,framerate:a};return"sdr"!==o&&(t.transferFunction=o),t}):[]}(e),o=a.length,l=function(e,t,r){var n;const i=null==(n=e.audioCodec)?void 0:n.split(","),s=mf(e);if(i&&e.audioGroups)return e.audioGroups.reduce((e,n)=>{var a;const o=n?null==(a=t.groups[n])?void 0:a.tracks:null;return o?o.reduce((e,t)=>{if(t.groupId===n){const n=parseFloat(t.channels||"");i.forEach(t=>{const i={contentType:Zh(t,"audio"),bitrate:r?gf(t,s):s};n&&(i.channels=""+n),e.push(i)})}return e},e):e},[]);return[]}(e,t,o>0),u=l.length;for(let e=o||1*u||1;e--;){const t={type:"media-source"};if(o&&(t.video=a[e%o]),u){t.audio=l[e%u];const r=t.audio.bitrate;t.video&&r&&(t.video.bitrate-=r)}s.push(t)}if(i){const e=navigator.userAgent;if(i.split(",").some(e=>zh(e))&&Kh())return Promise.resolve(hf(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${e})`),s))}return Promise.all(s.map(e=>{const t=function(e){let t="";const{audio:r,video:n}=e;if(n){t+=`${uf(n.contentType)}_r${n.height}x${n.width}f${Math.ceil(n.framerate)}${n.transferFunction||"sd"}_${Math.ceil(n.bitrate/1e5)}`}if(r){t+=`${n?"_":""}${uf(r.contentType)}_c${r.channels}`}return t}(e);return n[t]||(n[t]=r.decodingInfo(e))})).then(e=>({supported:!e.some(e=>!e.supported),configurations:s,decodingInfoResults:e})).catch(e=>({supported:!1,configurations:s,decodingInfoResults:[],error:e}))}function gf(e,t){if(t<=1)return 1;let r=128e3;return"ec-3"===e?r=768e3:"ac-3"===e&&(r=64e4),Math.min(t/2,r)}function mf(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}const vf=["NONE","TYPE-0","TYPE-1",null];const yf=["SDR","PQ","HLG"];var bf="",wf="YES",Ef="v2";function Sf(e){const{canSkipUntil:t,canSkipDateRanges:r,age:n}=e;return t&&n<t/2?r?Ef:wf:bf}class Tf{constructor(e,t,r){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=r}addDirectives(e){const t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class xf{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(e=>!!e).map(e=>e.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const r=null==(t=e.supplemental)?void 0:t.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 kf(this._audioGroups,e)}hasSubtitleGroup(e){return kf(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t)if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.push(t)}}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 null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function kf(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function Af(e,t){let r=!1,n=[];if(e&&(r="SDR"!==e,n=[e]),t){n=t.allowedVideoRanges||yf.slice(0);const e="SDR"!==n.join("")&&!t.videoCodec;r=void 0!==t.preferHDR?t.preferHDR:e&&function(){if("function"==typeof matchMedia){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}(),r||(n=["SDR"])}return{preferHDR:r,allowedVideoRanges:n}}const Rf=(e,t)=>JSON.stringify(e,(e=>{const t=new WeakSet;return(r,n)=>{if(e&&(n=e(r,n)),"object"==typeof n&&null!==n){if(t.has(n))return;t.add(n)}return n}})(t));function Lf(e,t){Qd.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function If(e){return e.reduce((e,t)=>{let r=e.groups[t.groupId];r||(r=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(t);const n=t.channels||"2";return r.channels[n]=(r.channels[n]||0)+1,r.hasDefault=r.hasDefault||t.default,r.hasAutoSelect=r.hasAutoSelect||t.autoselect,r.hasDefault&&(e.hasDefaultAudio=!0),r.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Cf(e){if(!e)return e;const{lang:t,assocLang:r,characteristics:n,channels:i,audioCodec:s}=e;return{lang:t,assocLang:r,characteristics:n,channels:i,audioCodec:s}}function Pf(e,t,r){if("attrs"in e){const r=t.indexOf(e);if(-1!==r)return r}for(let n=0;n<t.length;n++){if(Df(e,t[n],r))return n}return-1}function Df(e,t,r){const{groupId:n,name:i,lang:s,assocLang:a,default:o}=e,l=e.forced;return(void 0===n||t.groupId===n)&&(void 0===i||t.name===i)&&(void 0===s||function(e,t="--"){if(e.length===t.length)return e===t;return e.startsWith(t)||t.startsWith(e)}(s,t.lang))&&(void 0===s||t.assocLang===a)&&(void 0===o||t.default===o)&&(void 0===l||t.forced===l)&&(!("characteristics"in e)||function(e,t=""){const r=e.split(","),n=t.split(",");return r.length===n.length&&!r.some(e=>-1===n.indexOf(e))}(e.characteristics||"",t.characteristics))&&(void 0===r||r(e,t))}function _f(e,t){const{audioCodec:r,channels:n}=e;return!(void 0!==r&&(t.audioCodec||"").substring(0,4)!==r.substring(0,4)||void 0!==n&&n!==(t.channels||"2"))}function Mf(e,t,r){for(let n=t;n>-1;n--)if(r(e[n]))return n;for(let n=t+1;n<e.length;n++)if(r(e[n]))return n;return-1}function Of(e,t){var r;return!!e&&e!==(null==(r=t.loadLevelObj)?void 0:r.uri)}const Nf=function(e,t){let r=0,n=e.length-1,i=null,s=null;for(;r<=n;){i=(r+n)/2|0,s=e[i];const a=t(s);if(a>0)r=i+1;else{if(!(a<0))return s;n=i-1}}return null};function Ff(e,t,r=0,n=0,i=.005){let s=null;if(e){s=t[1+e.sn-t[0].sn]||null;const n=e.endDTS-r;n>0&&n<15e-7&&(r+=15e-7),s&&e.level!==s.level&&s.end<=e.end&&(s=t[2+e.sn-t[0].sn]||null)}else 0===r&&0===t[0].start&&(s=t[0]);if(s&&((!e||e.level===s.level)&&0===$f(r,n,s)||function(e,t,r){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){const n=t.tagList.reduce((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e),r);return e.start<=n}return!1}(s,e,Math.min(i,n))))return s;const a=Nf(t,$f.bind(null,r,n));return!a||a===e&&s?s:a}function $f(e=0,t=0,r){if(r.start<=e&&r.start+r.duration>e)return 0;const n=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-n<=e?1:r.start-n>e&&r.start?-1:0}function Bf(e,t,r){const n=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-n>e}function Uf(e,t,r){if(e&&e.startCC<=t&&e.endCC>=t){let n=e.fragments;const{fragmentHint:i}=e;let s;return i&&(n=n.concat(i)),Nf(n,e=>e.cc<t?1:e.cc>t?-1:(s=e,e.end<=r?1:e.start>r?-1:0)),s||null}return null}function zf(e){switch(e.details){case Cd.FRAG_LOAD_TIMEOUT:case Cd.KEY_LOAD_TIMEOUT:case Cd.LEVEL_LOAD_TIMEOUT:case Cd.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function jf(e){return e.details.startsWith("key")}function Gf(e){return jf(e)&&!!e.frag&&!e.frag.decryptdata}function Hf(e,t){const r=zf(t);return e.default[(r?"timeout":"error")+"Retry"]}function Vf(e,t){const r="linear"===e.backoff?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}function Wf(e){return Hd(Hd({},e),{errorRetry:null,timeoutRetry:null})}function Kf(e,t,r,n){if(!e)return!1;const i=null==n?void 0:n.code,s=t<e.maxNumRetry&&(function(e){return Yf(e)||!!e&&(e<400||e>499)}(i)||!!r);return e.shouldRetry?e.shouldRetry(e,t,r,n,s):s}function Yf(e){return 0===e&&!1===navigator.onLine}var qf=0,Xf=2,Qf=3,Zf=5,Jf=0,ep=1,tp=2,rp=4;function np(e){const t={action:qf,flags:Jf};return e&&(t.resolved=!0),t}var ip="NOT_LOADED",sp="APPENDING",ap="PARTIAL",op="OK";class lp{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(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Pd.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Pd.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Pd.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Pd.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Pd.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Pd.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const r=this.activePartLists[t];if(r)for(let t=r.length;t--;){const n=r[t];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,r){const{fragments:n}=this,i=Object.keys(n);for(let s=i.length;s--;){const a=n[i[s]];if((null==a?void 0:a.body.type)===t&&(!r||a.buffered)){const t=a.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,r,n,i){this.timeRanges&&(this.timeRanges[e]=t);const s=(null==n?void 0:n.fragment.sn)||-1;Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;if(s>=a.body.sn)return;if(!a.buffered&&(!a.loaded||i))return void(a.body.type===r&&this.removeFragment(a.body));const o=a.range[e];o&&(0!==o.time.length?o.time.some(e=>{const r=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return r&&this.removeFragment(a.body),r}):this.removeFragment(a.body))})}detectPartialFragments(e){const t=this.timeRanges;if(!t||"initSegment"===e.frag.sn)return;const r=e.frag,n=cp(r),i=this.fragments[n];if(!i||i.buffered&&r.gap)return;const s=!r.relurl;Object.keys(t).forEach(n=>{const a=r.elementaryStreams[n];if(!a)return;const o=t[n],l=s||!0===a.partial;i.range[n]=this.getBufferedTimes(r,e.part,l,o)}),i.loaded=null,Object.keys(i.range).length?(this.bufferedEnd(i,r),up(i)||this.removeParts(r.sn-1,r.type)):this.removeFragment(i.body)}bufferedEnd(e,t){e.buffered=!0;(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const r=this.activePartLists[t];r&&(this.activePartLists[t]=dp(r,t=>t.fragment.sn>=e))}fragBuffered(e,t){const r=cp(e);let n=this.fragments[r];!n&&t&&(n=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),n&&(n.loaded=null,this.bufferedEnd(n,e))}getBufferedTimes(e,t,r,n){const i={time:[],partial:r},s=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||s;for(let e=0;e<n.length;e++){const t=n.start(e)-this.bufferPadding,r=n.end(e)+this.bufferPadding;if(l>=t&&o<=r){i.time.push({startPTS:Math.max(s,n.start(e)),endPTS:Math.min(a,n.end(e))});break}if(s<r&&a>t){const t=Math.max(s,n.start(e)),r=Math.min(a,n.end(e));r>t&&(i.partial=!0,i.time.push({startPTS:t,endPTS:r}))}else if(a<=t)break}return i}getPartialFragment(e){let t,r,n,i=null,s=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const u=o[l];u&&up(u)&&(r=u.body.start-a,n=u.body.end+a,e>=r&&e<=n&&(t=Math.min(e-r,n-e),s<=t&&(i=u.body,s=t)))}),i}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||up(t))}getState(e){const t=cp(e),r=this.fragments[t];return r?r.buffered?up(r)?ap:op:sp:ip}isTimeBuffered(e,t,r){let n,i;for(let s=0;s<r.length;s++){if(n=r.start(s)-this.bufferPadding,i=r.end(s)+this.bufferPadding,e>=n&&t<=i)return!0;if(t<=n)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if("initSegment"===t.frag.sn||t.frag.bitrateTest)return;const r=t.frag,n=t.part?null:t,i=cp(r);this.fragments[i]={body:r,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:r,part:n,timeRanges:i,type:s}=t;if("initSegment"===r.sn)return;const a=r.type;if(n){let e=this.activePartLists[a];e||(this.activePartLists[a]=e=[]),e.push(n)}this.timeRanges=i;const o=i[s];this.detectEvictedFragments(s,o,a,n)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=cp(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,r=Object.keys(t);if(!e)return r.length>0;for(let n=r.length;n--;){const i=t[r[n]];if((null==i?void 0:i.body.type)===e)return!0}return!1}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,r,n,i){n&&!this.hasGaps||Object.keys(this.fragments).forEach(s=>{const a=this.fragments[s];if(!a)return;const o=a.body;o.type!==r||n&&!o.gap||o.start<t&&o.end>e&&(a.buffered||i)&&this.removeFragment(o)})}removeFragment(e){const t=cp(e);e.clearElementaryStreamInfo();const r=this.activePartLists[e.type];if(r){const t=e.sn;this.activePartLists[e.type]=dp(r,e=>e.fragment.sn!==t)}delete this.fragments[t],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 t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach(e=>e.clearElementaryStreamInfo())}}function up(e){var t,r,n;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(r=e.range.audio)&&r.partial||null!=(n=e.range.audiovideo)&&n.partial)}function cp(e){return`${e.type}_${e.level}_${e.sn}`}function dp(e,t){return e.filter(e=>{const r=t(e);return r||e.clearElementaryStreamInfo(),r})}var hp=0,fp=1;class pp{constructor(e,t,r){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=r}decrypt(e,t){switch(this.aesMode){case hp:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case fp:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class gp{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 t=new DataView(e),r=new Uint32Array(4);for(let e=0;e<4;e++)r[e]=t.getUint32(4*e);return r}initTable(){const e=this.sBox,t=this.invSBox,r=this.subMix,n=r[0],i=r[1],s=r[2],a=r[3],o=this.invSubMix,l=o[0],u=o[1],c=o[2],d=o[3],h=new Uint32Array(256);let f=0,p=0,g=0;for(g=0;g<256;g++)h[g]=g<128?g<<1:g<<1^283;for(g=0;g<256;g++){let r=p^p<<1^p<<2^p<<3^p<<4;r=r>>>8^255&r^99,e[f]=r,t[r]=f;const o=h[f],g=h[o],m=h[g];let v=257*h[r]^16843008*r;n[f]=v<<24|v>>>8,i[f]=v<<16|v>>>16,s[f]=v<<8|v>>>24,a[f]=v,v=16843009*m^65537*g^257*o^16843008*f,l[r]=v<<24|v>>>8,u[r]=v<<16|v>>>16,c[r]=v<<8|v>>>24,d[r]=v,f?(f=o^h[h[h[m^o]]],p^=h[h[p]]):f=p=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let r=!0,n=0;for(;n<t.length&&r;)r=t[n]===this.key[n],n++;if(r)return;this.key=t;const i=this.keySize=t.length;if(4!==i&&6!==i&&8!==i)throw new Error("Invalid aes key size="+i);const s=this.ksRows=4*(i+6+1);let a,o;const l=this.keySchedule=new Uint32Array(s),u=this.invKeySchedule=new Uint32Array(s),c=this.sBox,d=this.rcon,h=this.invSubMix,f=h[0],p=h[1],g=h[2],m=h[3];let v,y;for(a=0;a<s;a++)a<i?v=l[a]=t[a]:(y=v,a%i===0?(y=y<<8|y>>>24,y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[255&y],y^=d[a/i|0]<<24):i>6&&a%i===4&&(y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[255&y]),l[a]=v=(l[a-i]^y)>>>0);for(o=0;o<s;o++)a=s-o,y=3&o?l[a]:l[a-4],u[o]=o<4||a<=4?y:f[c[y>>>24]]^p[c[y>>>16&255]]^g[c[y>>>8&255]]^m[c[255&y]],u[o]=u[o]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,r){const n=this.keySize+6,i=this.invKeySchedule,s=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],u=a[2],c=a[3],d=this.uint8ArrayToUint32Array_(r);let h=d[0],f=d[1],p=d[2],g=d[3];const m=new Int32Array(e),v=new Int32Array(m.length);let y,b,w,E,S,T,x,k,A,R,L,I,C,P;const D=this.networkToHostOrderSwap;for(;t<m.length;){for(A=D(m[t]),R=D(m[t+1]),L=D(m[t+2]),I=D(m[t+3]),S=A^i[0],T=I^i[1],x=L^i[2],k=R^i[3],C=4,P=1;P<n;P++)y=o[S>>>24]^l[T>>16&255]^u[x>>8&255]^c[255&k]^i[C],b=o[T>>>24]^l[x>>16&255]^u[k>>8&255]^c[255&S]^i[C+1],w=o[x>>>24]^l[k>>16&255]^u[S>>8&255]^c[255&T]^i[C+2],E=o[k>>>24]^l[S>>16&255]^u[T>>8&255]^c[255&x]^i[C+3],S=y,T=b,x=w,k=E,C+=4;y=s[S>>>24]<<24^s[T>>16&255]<<16^s[x>>8&255]<<8^s[255&k]^i[C],b=s[T>>>24]<<24^s[x>>16&255]<<16^s[k>>8&255]<<8^s[255&S]^i[C+1],w=s[x>>>24]<<24^s[k>>16&255]<<16^s[S>>8&255]<<8^s[255&T]^i[C+2],E=s[k>>>24]<<24^s[S>>16&255]<<16^s[T>>8&255]<<8^s[255&x]^i[C+3],v[t]=D(y^h),v[t+1]=D(E^f),v[t+2]=D(w^p),v[t+3]=D(b^g),h=A,f=R,p=L,g=I,t+=4}return v.buffer}}class mp{constructor(e,t,r){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=r}expandKey(){const e=function(e){switch(e){case hp:return"AES-CBC";case fp:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${e}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}class vp{constructor(e,{removePKCS7Padding:t=!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=t,t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(e){}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:t}=this;if(!e||t)return this.reset(),null;const r=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?function(e){const t=e.byteLength,r=t&&new DataView(e.buffer).getUint8(t-1);return r?e.slice(0,t-r):e}(r):r}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,r,n){return this.useSoftware?new Promise((i,s)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,r,n);const o=this.flush();o?i(o.buffer):s(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,r,n)}softwareDecrypt(e,t,r,n){const{currentIV:i,currentResult:s,remainderData:a}=this;if(n!==hp||16!==t.byteLength)return Qd.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=Bh(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;i&&(r=i);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new gp),l.expandKey(t);const u=s;return this.currentResult=l.decrypt(o.buffer,0,r),this.currentIV=o.slice(-16).buffer,u||null}webCryptoDecrypt(e,t,r,n){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,r,n));this.key=t,this.fastAesKey=new mp(this.subtle,t,n)}return this.fastAesKey.expandKey().then(t=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new pp(this.subtle,new Uint8Array(r),n).decrypt(e.buffer,t)}).catch(i=>(Qd.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(e,t,r,n)))}onWebCryptoError(e,t,r,n){const i=this.enableSoftwareAES;if(i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,r,n);const i=this.flush();if(i)return i.buffer}throw new Error("WebCrypto"+(i?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const r=e.length-e.length%16;return r!==e.length&&(t=e.slice(0,r),this.remainderData=e.slice(r)),t}logOnce(e){this.logEnabled&&(Qd.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const yp=Math.pow(2,17);class bp{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,t){const r=e.url;if(!r)return Promise.reject(new Sp({type:Id.NETWORK_ERROR,details:Cd.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(r?"part list":"url")),networkDetails:null}));this.abort();const n=this.config,i=n.fLoader,s=n.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some(e=>"GAP"===e[0]))return void o(Ep(e));e.gap=!1}const l=this.loader=i?new i(n):new s(n),u=wp(e);e.loader=l;const c=Wf(n.fragLoadPolicy.default),d={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:yp};e.stats=l.stats;const h={onSuccess:(t,r,n,i)=>{this.resetLoader(e,l);let s=t.data;n.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(s.slice(0,16)),s=s.slice(16)),a({frag:e,part:null,payload:s,networkDetails:i})},onError:(t,n,i,s)=>{this.resetLoader(e,l),o(new Sp({type:Id.NETWORK_ERROR,details:Cd.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Hd({url:r,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:i,stats:s}))},onAbort:(t,r,n)=>{this.resetLoader(e,l),o(new Sp({type:Id.NETWORK_ERROR,details:Cd.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:n,stats:t}))},onTimeout:(t,r,n)=>{this.resetLoader(e,l),o(new Sp({type:Id.NETWORK_ERROR,details:Cd.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:n,stats:t}))}};t&&(h.onProgress=(r,n,i,s)=>t({frag:e,part:null,payload:i,networkDetails:s})),l.load(u,d,h)})}loadPart(e,t,r){this.abort();const n=this.config,i=n.fLoader,s=n.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o(Ep(e,t));const l=this.loader=i?new i(n):new s(n),u=wp(e,t);e.loader=l;const c=Wf(n.fragLoadPolicy.default),d={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:yp};t.stats=l.stats,l.load(u,d,{onSuccess:(n,i,s,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const u={frag:e,part:t,payload:n.data,networkDetails:o};r(u),a(u)},onError:(r,n,i,s)=>{this.resetLoader(e,l),o(new Sp({type:Id.NETWORK_ERROR,details:Cd.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Hd({url:u.url,data:void 0},r),error:new Error(`HTTP Error ${r.code} ${r.text}`),networkDetails:i,stats:s}))},onAbort:(r,n,i)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new Sp({type:Id.NETWORK_ERROR,details:Cd.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:i,stats:r}))},onTimeout:(r,n,i)=>{this.resetLoader(e,l),o(new Sp({type:Id.NETWORK_ERROR,details:Cd.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:i,stats:r}))}})})}updateStatsFromPart(e,t){const r=e.stats,n=t.stats,i=n.total;if(r.loaded+=n.loaded,i){const n=Math.round(e.duration/t.duration),s=Math.min(Math.round(r.loaded/i),n),a=(n-s)*Math.round(r.loaded/s);r.total=r.loaded+a}else r.total=Math.max(r.loaded,r.total);const s=r.loading,a=n.loading;s.start?s.first+=a.first-a.start:(s.start=a.start,s.first=a.first),s.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function wp(e,t=null){const r=t||e,n={frag:e,part:t,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},i=r.byteRangeStartOffset,s=r.byteRangeEndOffset;if(Ad(i)&&Ad(s)){var a;let t=i,r=s;if("initSegment"===e.sn&&("AES-128"===(o=null==(a=e.decryptdata)?void 0:a.method)||"AES-256"===o)){const e=s-i;e%16&&(r=s+(16-e%16)),0!==i&&(n.resetIV=!0,t=i-16)}n.rangeStart=t,n.rangeEnd=r}var o;return n}function Ep(e,t){const r=new Error(`GAP ${e.gap?"tag":"attribute"} found`),n={type:Id.MEDIA_ERROR,details:Cd.FRAG_GAP,fatal:!1,frag:e,error:r,networkDetails:null};return t&&(n.part=t),(t||e).stats.aborted=!0,new Sp(n)}class Sp extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Tp extends Vd{constructor(e,t){super(e,t),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&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class xp{constructor(e,t,r,n=0,i=-1,s=!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={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=r,this.size=n,this.part=i,this.partial=s}}const kp={length:0,start:()=>0,end:()=>0};class Ap{static isBuffered(e,t){if(e){const r=Ap.getBuffered(e);for(let e=r.length;e--;)if(t>=r.start(e)&&t<=r.end(e))return!0}return!1}static bufferedRanges(e){if(e){const t=Ap.getBuffered(e);return Ap.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let r=0;r<e.length;r++)t.push({start:e.start(r),end:e.end(r)});return t}static bufferInfo(e,t,r){if(e){const n=Ap.bufferedRanges(e);if(n.length)return Ap.bufferedInfo(n,t,r)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,r){t=Math.max(0,t),e.length>1&&e.sort((e,t)=>e.start-t.start||t.end-e.end);let n=-1,i=[];if(r)for(let s=0;s<e.length;s++){t>=e[s].start&&t<=e[s].end&&(n=s);const a=i.length;if(a){const t=i[a-1].end;e[s].start-t<r?e[s].end>t&&(i[a-1].end=e[s].end):i.push(e[s])}else i.push(e[s])}else i=e;let s,a=0,o=t,l=t;for(let e=0;e<i.length;e++){const u=i[e].start,c=i[e].end;if(-1===n&&t>=u&&t<=c&&(n=e),t+r>=u&&t<c)o=u,l=c,a=l-t;else if(t+r<u){s=u;break}}return{len:a,start:o||0,end:l||0,nextStart:s,buffered:e,bufferedIndex:n}}static getBuffered(e){try{return e.buffered||kp}catch(e){return Qd.log("failed to get media.buffered",e),kp}}}const Rp=/\{\$([a-zA-Z0-9-_]+)\}/g;function Lp(e){return Rp.test(e)}function Ip(e,t){if(null!==e.variableList||e.hasVariableRefs){const r=e.variableList;return t.replace(Rp,t=>{const n=t.substring(2,t.length-1),i=null==r?void 0:r[n];return void 0===i?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${n}"`)),t):i})}return t}function Cp(e,t,r){let n,i,s=e.variableList;if(s||(e.variableList=s={}),"QUERYPARAM"in t){n=t.QUERYPARAM;try{const e=new self.URL(r).searchParams;if(!e.has(n))throw new Error(`"${n}" does not match any query parameter in URI: "${r}"`);i=e.get(n)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else n=t.NAME,i=t.VALUE;n in s?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${n}"`)):s[n]=i||""}function Pp(e,t,r){const n=t.IMPORT;if(r&&n in r){let t=e.variableList;t||(e.variableList=t={}),t[n]=r[n]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${n}"`))}const Dp=/^(\d+)x(\d+)$/,_p=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Mp{constructor(e,t){"string"==typeof e&&(e=Mp.parseAttrList(e,t)),jd(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>"X-"===e.substring(0,2))}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const r=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)r[e]=parseInt(t.slice(2*e,2*e+2),16);return r}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const r=this[e];return r?parseFloat(r):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const r=this[e];return(r?r.split(/[ ,]+/):[]).reduce((e,t)=>(e[t.toLowerCase()]=!0,e),t)}bool(e){return"YES"===this[e]}decimalResolution(e){const t=Dp.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let r;const n={};for(_p.lastIndex=0;null!==(r=_p.exec(e));){const i=r[1].trim();let s=r[2];const a=0===s.indexOf('"')&&s.lastIndexOf('"')===s.length-1;let o=!1;if(a)s=s.slice(1,-1);else switch(i){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(a||o))s=Ip(t,s);else if(!o&&!a)switch(i){case"CLOSED-CAPTIONS":if("NONE"===s)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":Qd.warn(`${e}: attribute ${i} is missing quotes`)}n[i]=s}return n}}function Op(e){return"ID"!==e&&"CLASS"!==e&&"CUE"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function Np(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}class Fp{constructor(e,t,r=0){var n;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=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(n=null==t?void 0:t.tagOrder)?n:r,t){const r=t.attr;for(const t in r)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==r[t]){Qd.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=jd(new Mp({}),r,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=(null==t?void 0:t.endDate)||new Date(this.attr["END-DATE"]);Ad(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return void 0===e?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 null===e||null===e.programDateTime?(Qd.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 t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(Ad(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"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&Ad(this.startDate.getTime())&&(null===this.duration||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)}}class $p{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)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let r=t.decryptdata;return r||(t.setKeyFormat(e.keyFormat),r=t.decryptdata),!!r&&e.matches(r)})}get hasProgramDateTime(){return!!this.fragments.length&&Ad(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;if(e>0){return 1e3*(this.driftEnd-this.driftStart)/e}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&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 null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(-1!==t){for(let r=e.length;r--;)if(e[r].index>t)return e[r].index;return t}}return 0}get lastPartSn(){var e;return null!=(e=this.partList)&&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 Bp(e,t){return e.length===t.length&&!e.some((e,r)=>e!==t[r])}function Up(e,t){return!e&&!t||!(!e||!t)&&Bp(e,t)}function zp(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function jp(e){switch(e){case"AES-128":case"AES-256":return hp;case"AES-256-CTR":return fp;default:throw new Error(`invalid full segment method ${e}`)}}function Gp(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function Hp(e){return Uint8Array.from(unescape(encodeURIComponent(e)),e=>e.charCodeAt(0))}function Vp(e){const t=function(e,t,r){const n=e[t];e[t]=e[r],e[r]=n};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function Wp(e){const t=e.split(":");let r=null;if("data"===t[0]&&2===t.length){const e=t[1].split(";"),n=e[e.length-1].split(",");if(2===n.length){const t="base64"===n[0],i=n[1];t?(e.splice(-1,1),r=Gp(i)):r=function(e){const t=Hp(e).subarray(0,16),r=new Uint8Array(16);return r.set(t,16-t.length),r}(i)}}return r}const Kp="undefined"!=typeof self?self:void 0;var Yp={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},qp="org.w3.clearkey",Xp="com.apple.streamingkeydelivery",Qp="com.microsoft.playready",Zp="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Jp(e){switch(e){case Xp:return Yp.FAIRPLAY;case Qp:return Yp.PLAYREADY;case Zp:return Yp.WIDEVINE;case qp:return Yp.CLEARKEY}}function eg(e){switch(e){case Yp.FAIRPLAY:return Xp;case Yp.PLAYREADY:return Qp;case Yp.WIDEVINE:return Zp;case Yp.CLEARKEY:return qp}}function tg(e){const{drmSystems:t,widevineLicenseUrl:r}=e,n=t?[Yp.FAIRPLAY,Yp.WIDEVINE,Yp.PLAYREADY,Yp.CLEARKEY].filter(e=>!!t[e]):[];return!n[Yp.WIDEVINE]&&r&&n.push(Yp.WIDEVINE),n}const rg=null!=Kp&&null!=(ng=Kp.navigator)&&ng.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var ng;function ig(e){const t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),r=String.fromCharCode.apply(null,Array.from(t)),n=r.substring(r.indexOf("<"),r.length),i=(new DOMParser).parseFromString(n,"text/xml").getElementsByTagName("KID")[0];if(i){const e=i.childNodes[0]?i.childNodes[0].nodeValue:i.getAttribute("VALUE");if(e){const t=Gp(e).subarray(0,16);return Vp(t),t}}return null}let sg={};class ag{static clearKeyUriToKeyIdMap(){sg={}}static setKeyIdForUri(e,t){sg[e]=t}static addKeyIdForUri(e){const t=Object.keys(sg).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,t),sg[e]=r,r}constructor(e,t,r,n=[1],i=null,s){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=t,this.keyFormat=r,this.keyFormatVersions=n,this.iv=i,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!zp(e),null!=s&&s.startsWith("0x")&&(this.keyId=new Uint8Array(rh(s)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Bp(e.keyFormatVersions,this.keyFormatVersions)&&Up(e.iv,this.iv)&&Up(e.keyId,this.keyId)}isSupported(){if(this.method){if(zp(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case Xp:case Zp:case Qp:case qp:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(zp(this.method)){let t=this.iv;t||("number"!=typeof e&&(Qd.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),t=function(e){const t=new Uint8Array(16);for(let r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}(e));return new ag(this.method,this.uri,"identity",this.keyFormatVersions,t)}if(this.keyId){const e=sg[this.uri];if(e&&!Bp(this.keyId,e)&&ag.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const r=Wp(this.uri);if(r)switch(this.keyFormat){case Zp:if(this.pssh=r,!this.keyId){const e=function(e){const t=[];if(e instanceof ArrayBuffer){const r=e.byteLength;let n=0;for(;n+32<r;){const r=Wh(new DataView(e,n));t.push(r),n+=r.size}}return t}(r.buffer);if(e.length){var n;const t=e[0];this.keyId=null!=(n=t.kids)&&n.length?t.kids[0]:null}}this.keyId||(this.keyId=og(t));break;case Qp:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Vh(e,0,r),this.keyId=ig(r);break}default:{let e=r.subarray(0,16);if(16!==e.length){const t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||16!==this.keyId.byteLength){let e;e=function(e){const t=null==e?void 0:e[Zp];if(t)return t.keyId;return null}(t),e||(e=og(t),e||(e=sg[this.uri])),e&&(this.keyId=e,ag.setKeyIdForUri(this.uri,e))}return this}}function og(e){const t=null==e?void 0:e[Qp];if(t){const e=Wp(t.uri);if(e)return ig(e)}return null}const lg=/#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,ug=/#EXT-X-MEDIA:(.*)/g,cg=/^#EXT(?:INF|-X-TARGETDURATION):/m,dg=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),hg=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 fg{static findGroup(e,t){for(let r=0;r<e.length;r++){const n=e[r];if(n.id===t)return n}}static resolve(e,t){return dh.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return cg.test(e)}static parseMasterPlaylist(e,t){const r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Lp(e)},n=[];if(lg.lastIndex=0,!e.startsWith("#EXTM3U"))return r.playlistParsingError=new Error("no EXTM3U delimiter"),r;let i;for(;null!=(i=lg.exec(e));)if(i[1]){var s;const e=new Mp(i[1],r),a=Ip(r,i[2]),o={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:fg.resolve(a,t)},l=e.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),yg(e.CODECS,o);const u=e["SUPPLEMENTAL-CODECS"];u&&(o.supplemental={},yg(u,o.supplemental)),null!=(s=o.unknownCodecs)&&s.length||n.push(o),r.levels.push(o)}else if(i[3]){const e=i[3],n=i[4];switch(e){case"SESSION-DATA":{const e=new Mp(n,r),t=e["DATA-ID"];t&&(null===r.sessionData&&(r.sessionData={}),r.sessionData[t]=e);break}case"SESSION-KEY":{const e=mg(n,t,r);e.encrypted&&e.isSupported()?(null===r.sessionKeys&&(r.sessionKeys=[]),r.sessionKeys.push(e)):Qd.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${n}"`);break}case"DEFINE":Cp(r,new Mp(n,r),t);break;case"CONTENT-STEERING":{const e=new Mp(n,r);r.contentSteering={uri:fg.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":r.startTimeOffset=vg(n)}}const a=n.length>0&&n.length<r.levels.length;return r.levels=a?n:r.levels,0===r.levels.length&&(r.playlistParsingError=new Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(e,t,r){let n;const i={},s=r.levels,a={AUDIO:s.map(e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec})),SUBTITLES:s.map(e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec})),"CLOSED-CAPTIONS":[]};let o=0;for(ug.lastIndex=0;null!==(n=ug.exec(e));){const e=new Mp(n[1],r),s=e.TYPE;if(s){const r=a[s],n=i[s]||[];i[s]=n;const l=e.LANGUAGE,u=e["ASSOC-LANGUAGE"],c=e.CHANNELS,d=e.CHARACTERISTICS,h=e["INSTREAM-ID"],f={attrs:e,bitrate:0,id:o++,groupId:e["GROUP-ID"]||"",name:e.NAME||l||"",type:s,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:l,url:e.URI?fg.resolve(e.URI,t):""};if(u&&(f.assocLang=u),c&&(f.channels=c),d&&(f.characteristics=d),h&&(f.instreamId=h),null!=r&&r.length){const e=fg.findGroup(r,f.groupId)||r[0];bg(f,e,"audioCodec"),bg(f,e,"textCodec")}n.push(f)}}return i}static parseLevelPlaylist(e,t,r,n,i,s){var a;const o={url:t},l=new $p(t),u=l.fragments,c=[];let d,h,f,p,g=null,m=0,v=0,y=0,b=0,w=0,E=null,S=new yh(n,o),T=-1,x=!1,k=null;if(dg.lastIndex=0,l.m3u8=e,l.hasVariableRefs=Lp(e),"#EXTM3U"!==(null==(a=dg.exec(e))?void 0:a[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(d=dg.exec(e));){x&&(x=!1,S=new yh(n,o),S.playlistOffset=y,S.setStart(y),S.sn=m,S.cc=b,w&&(S.bitrate=w),S.level=r,g&&(S.initSegment=g,g.rawProgramDateTime&&(S.rawProgramDateTime=g.rawProgramDateTime,g.rawProgramDateTime=null),k&&(S.setByteRange(k),k=null)));const e=d[1];if(e){S.duration=parseFloat(e);const t=(" "+d[2]).slice(1);S.title=t||null,S.tagList.push(t?["INF",e,t]:["INF",e])}else if(d[3]){if(Ad(S.duration)){S.playlistOffset=y,S.setStart(y),f&&Sg(S,f,l),S.sn=m,S.level=r,S.cc=b,u.push(S);const e=(" "+d[3]).slice(1);S.relurl=Ip(l,e),wg(S,E,c),E=S,y+=S.duration,m++,v=0,x=!0}}else{if(d=d[0].match(hg),!d){Qd.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h<d.length&&void 0===d[h];h++);const e=(" "+d[h]).slice(1),i=(" "+d[h+1]).slice(1),a=d[h+2]?(" "+d[h+2]).slice(1):null;switch(e){case"BYTERANGE":E?S.setByteRange(i,E):S.setByteRange(i);break;case"PROGRAM-DATE-TIME":S.rawProgramDateTime=i,S.tagList.push(["PROGRAM-DATE-TIME",i]),-1===T&&(T=u.length);break;case"PLAYLIST-TYPE":l.type&&Tg(l,e,d),l.type=i.toUpperCase();break;case"MEDIA-SEQUENCE":0!==l.startSN?Tg(l,e,d):u.length>0&&xg(l,e,d),m=l.startSN=parseInt(i);break;case"SKIP":{l.skippedSegments&&Tg(l,e,d);const t=new Mp(i,l),r=t.decimalInteger("SKIPPED-SEGMENTS");if(Ad(r)){l.skippedSegments+=r;for(let e=r;e--;)u.push(null);m+=r}const n=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");n&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(n.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&Tg(l,e,d),l.targetduration=Math.max(parseInt(i),1);break;case"VERSION":null!==l.version&&Tg(l,e,d),l.version=parseInt(i);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||Tg(l,e,d),l.live=!1;break;case"#":(i||a)&&S.tagList.push(a?[i,a]:[i]);break;case"DISCONTINUITY":b++,S.tagList.push(["DIS"]);break;case"GAP":S.gap=!0,S.tagList.push([e]);break;case"BITRATE":S.tagList.push([e,i]),w=1e3*parseInt(i),Ad(w)?S.bitrate=w:w=0;break;case"DATERANGE":{const e=new Mp(i,l),t=new Fp(e,l.dateRanges[e.ID],l.dateRangeTagCount);l.dateRangeTagCount++,t.isValid||l.skippedSegments?l.dateRanges[t.id]=t:Qd.warn(`Ignoring invalid DATERANGE tag: "${i}"`),S.tagList.push(["EXT-X-DATERANGE",i]);break}case"DEFINE":{const e=new Mp(i,l);"IMPORT"in e?Pp(l,e,s):Cp(l,e,t)}break;case"DISCONTINUITY-SEQUENCE":0!==l.startCC?Tg(l,e,d):u.length>0&&xg(l,e,d),l.startCC=b=parseInt(i);break;case"KEY":{const e=mg(i,t,l);if(e.isSupported()){if("NONE"===e.method){f=void 0;break}f||(f={});const t=f[e.keyFormat];null!=t&&t.matches(e)||(t&&(f=jd({},f)),f[e.keyFormat]=e)}else Qd.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${i}"`);break}case"START":l.startTimeOffset=vg(i);break;case"MAP":{const e=new Mp(i,l);if(S.duration){const t=new yh(n,o);Eg(t,e,r,f),g=t,S.initSegment=g,g.rawProgramDateTime&&!S.rawProgramDateTime&&(S.rawProgramDateTime=g.rawProgramDateTime)}else{const t=S.byteRangeEndOffset;if(t){const e=S.byteRangeStartOffset;k=`${t-e}@${e}`}else k=null;Eg(S,e,r,f),g=S,x=!0}g.cc=b;break}case"SERVER-CONTROL":p&&Tg(l,e,d),p=new Mp(i),l.canBlockReload=p.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=p.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&p.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=p.optionalFloat("PART-HOLD-BACK",0),l.holdBack=p.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{l.partTarget&&Tg(l,e,d);const t=new Mp(i);l.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=l.partList;e||(e=l.partList=[]);const t=v>0?e[e.length-1]:void 0,r=v++,n=new Mp(i,l),s=new bh(n,S,o,r,t);e.push(s),S.duration+=s.duration;break}case"PRELOAD-HINT":{const e=new Mp(i,l);l.preloadHint=e;break}case"RENDITION-REPORT":{const e=new Mp(i,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(e);break}default:Qd.warn(`line parsed but not handled: ${d}`)}}}E&&!E.relurl?(u.pop(),y-=E.duration,l.partList&&(l.fragmentHint=E)):l.partList&&(wg(S,E,c),S.cc=b,l.fragmentHint=S,f&&Sg(S,f,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const A=u.length,R=u[0],L=u[A-1];if(y+=l.skippedSegments*l.targetduration,y>0&&A&&L){l.averagetargetduration=y/A;const e=L.sn;l.endSN="initSegment"!==e?e:0,l.live||(L.endList=!0),T>0&&(!function(e,t){let r=e[t];for(let n=t;n--;){const t=e[n];if(!t)return;t.programDateTime=r.programDateTime-1e3*t.duration,r=t}}(u,T),R&&c.unshift(R))}return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,c.length&&l.dateRangeTagCount&&R&&pg(c,l),l.endCC=b,l}}function pg(e,t){let r=e.length;if(!r){if(!t.hasProgramDateTime)return;{const n=t.fragments[t.fragments.length-1];e.push(n),r++}}const n=e[r-1],i=t.live?1/0:t.totalduration,s=Object.keys(t.dateRanges);for(let o=s.length;o--;){const l=t.dateRanges[s[o]],u=l.startDate.getTime();l.tagAnchor=n.ref;for(let n=r;n--;){var a;if((null==(a=e[n])?void 0:a.sn)<t.startSN)break;const r=gg(t,u,e,n,i);if(-1!==r){l.tagAnchor=t.fragments[r].ref;break}}}}function gg(e,t,r,n,i){const s=r[n];if(s){const o=s.programDateTime;if(t>=o||0===n){var a;if(t<=o+1e3*(((null==(a=r[n+1])?void 0:a.start)||i)-s.start)){const i=r[n].sn-e.startSN;if(i<0)return-1;const s=e.fragments;if(s.length>r.length){for(let a=(r[n+1]||s[s.length-1]).sn-e.startSN;a>i;a--){const e=s[a].programDateTime;if(t>=e&&t<e+1e3*s[a].duration)return a}}return i}}}return-1}function mg(e,t,r){var n,i;const s=new Mp(e,r),a=null!=(n=s.METHOD)?n:"",o=s.URI,l=s.hexadecimalInteger("IV"),u=s.KEYFORMATVERSIONS,c=null!=(i=s.KEYFORMAT)?i:"identity";o&&s.IV&&!l&&Qd.error(`Invalid IV: ${s.IV}`);const d=o?fg.resolve(o,t):"",h=(u||"1").split("/").map(Number).filter(Number.isFinite);return new ag(a,d,c,h,l,s.KEYID)}function vg(e){const t=new Mp(e).decimalFloatingPoint("TIME-OFFSET");return Ad(t)?t:null}function yg(e,t){let r=(e||"").split(/[ ,]+/).filter(e=>e);["video","audio","text"].forEach(e=>{const n=r.filter(t=>qh(t,e));n.length&&(t[`${e}Codec`]=n.map(e=>e.split("/")[0]).join(","),r=r.filter(e=>-1===n.indexOf(e)))}),t.unknownCodecs=r}function bg(e,t,r){const n=t[r];n&&(e[r]=n)}function wg(e,t,r){e.rawProgramDateTime?r.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function Eg(e,t,r,n){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=r,e.sn="initSegment",n&&(e.levelkeys=n),e.initSegment=null}function Sg(e,t,r){e.levelkeys=t;const{encryptedFragments:n}=r;n.length&&n[n.length-1].levelkeys===t||!Object.keys(t).some(e=>t[e].isCommonEncryption)||n.push(e)}function Tg(e,t,r){e.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${r[0]})`)}function xg(e,t,r){e.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${r[0]})`)}function kg(e,t){const r=t.startPTS;if(Ad(r)){let n,i=0;t.sn>e.sn?(i=r-e.start,n=e):(i=e.start-r,n=t),n.duration!==i&&n.setDuration(i)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration)}else t.setStart(Math.max(e.start-t.duration,0))}function Ag(e,t,r,n,i,s,a){n-r<=0&&(a.warn("Fragment should have a positive duration",t),n=r+t.duration,s=i+t.duration);let o=r,l=n;const u=t.startPTS,c=t.endPTS;if(Ad(u)){const d=Math.abs(u-r);e&&d>e.totalduration?a.warn(`media timestamps and playlist times differ by ${d}s for level ${t.level} ${e.url}`):Ad(t.deltaPTS)?t.deltaPTS=Math.max(d,t.deltaPTS):t.deltaPTS=d,o=Math.max(r,u),r=Math.min(r,u),i=void 0!==t.startDTS?Math.min(i,t.startDTS):i,l=Math.min(n,c),n=Math.max(n,c),s=void 0!==t.endDTS?Math.max(s,t.endDTS):s}const d=r-t.start;0!==t.start&&t.setStart(r),t.setDuration(n-t.start),t.startPTS=r,t.maxStartPTS=o,t.startDTS=i,t.endPTS=n,t.minEndPTS=l,t.endDTS=s;const h=t.sn;if(!e||h<e.startSN||h>e.endSN)return 0;let f;const p=h-e.startSN,g=e.fragments;for(g[p]=t,f=p;f>0;f--)kg(g[f],g[f-1]);for(f=p;f<g.length-1;f++)kg(g[f],g[f+1]);return e.fragmentHint&&kg(g[g.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,d}function Rg(e,t,r){if(e===t)return;let n=null;const i=e.fragments;for(let e=i.length-1;e>=0;e--){const t=i[e].initSegment;if(t){n=t;break}}let s;e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,r){const n=t.skippedSegments,i=Math.max(e.startSN,t.startSN)-t.startSN,s=(e.fragmentHint?1:0)+(n?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let u=i;u<=s;u++){const i=l[a+u];let s=o[u];if(n&&!s&&i&&(s=t.fragments[u]=i),i&&s){r(i,s,u,o);const n=i.relurl,a=s.relurl;if(n&&Ng(n,a))return void(t.playlistParsingError=Lg(`media sequence mismatch ${s.sn}:`,e,t,i,s));if(i.cc!==s.cc)return void(t.playlistParsingError=Lg(`discontinuity sequence mismatch (${i.cc}!=${s.cc})`,e,t,i,s))}}}(e,t,(e,r,i,a)=>{if((!t.startCC||t.skippedSegments)&&r.cc!==e.cc){const n=e.cc-r.cc;for(let e=i;e<a.length;e++)a[e].cc+=n;t.endCC=a[a.length-1].cc}Ad(e.startPTS)&&Ad(e.endPTS)&&(r.setStart(r.startPTS=e.startPTS),r.startDTS=e.startDTS,r.maxStartPTS=e.maxStartPTS,r.endPTS=e.endPTS,r.endDTS=e.endDTS,r.minEndPTS=e.minEndPTS,r.setDuration(e.endPTS-e.startPTS),r.duration&&(s=r),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(r.elementaryStreams=e.elementaryStreams),r.loader=e.loader,e.hasStats&&(r.stats=e.stats),e.initSegment&&(r.initSegment=e.initSegment,n=e.initSegment)});const a=t.fragments,o=t.fragmentHint?a.concat(t.fragmentHint):a;if(n&&o.forEach(e=>{var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=n)?void 0:t.relurl)||(e.initSegment=n)}),t.skippedSegments){if(t.deltaUpdateFailed=a.some(e=>!e),t.deltaUpdateFailed){r.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)a.shift();t.startSN=a[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,r){const{dateRanges:n,recentlyRemovedDateranges:i}=t,s=jd({},e);i&&i.forEach(e=>{delete s[e]});const a=Object.keys(s).length;if(!a)return n;return Object.keys(n).forEach(e=>{const t=s[e],i=new Fp(n[e].attr,t);i.isValid?(s[e]=i,t||(i.tagOrder+=a)):r.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Rf(n[e].attr)}"`)}),s}(e.dateRanges,t,r));const n=e.fragments.filter(e=>e.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e<o.length;e++)null===o[e].programDateTime&&wg(o[e],o[e-1],n);pg(n,t)}t.endCC=a[a.length-1].cc}if(!t.startCC){var l;const r=Dg(e,t.startSN-1);t.startCC=null!=(l=null==r?void 0:r.cc)?l:a[0].cc}!function(e,t,r){if(e&&t){let n=0;for(let i=0,s=e.length;i<=s;i++){const s=e[i],a=t[i+n];s&&a&&s.index===a.index&&s.fragment.sn===a.fragment.sn?r(s,a):n--}}}(e.partList,t.partList,(e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats}),s?Ag(t,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS,r):Ig(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const u=t.advancedDateTime;if(t.advanced&&u){const e=t.edge;t.driftStart||(t.driftStartTime=u,t.driftStart=e),t.driftEndTime=u,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}function Lg(e,t,r,n,i){return new Error(`${e} ${i.url}\nPlaylist starting @${t.startSN}\n${t.m3u8}\n\nPlaylist starting @${r.startSN}\n${r.m3u8}`)}function Ig(e,t,r=!0){const n=t.startSN+t.skippedSegments-e.startSN,i=e.fragments,s=n>=0;let a=0;if(s&&n<i.length)a=i[n].start;else if(s&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(s&&r)a=e.fragmentStart+n*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;a=e.fragmentStart}Cg(t,a)}function Cg(e,t){if(t){const r=e.fragments;for(let n=e.skippedSegments;n<r.length;n++)r[n].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function Pg(e,t=1/0){let r=1e3*e.targetduration;if(e.updated){const n=e.fragments,i=4;if(n.length&&r*i>t){const e=1e3*n[n.length-1].duration;e<r&&(r=e)}}else r/=2;return Math.round(r)}function Dg(e,t,r){if(!e)return null;let n=e.fragments[t-e.startSN];return n||(n=e.fragmentHint,n&&n.sn===t?n:t<e.startSN&&r&&r.sn===t?r:null)}function _g(e,t,r){return e?Mg(e.partList,t,r):null}function Mg(e,t,r){if(e)for(let n=e.length;n--;){const i=e[n];if(i.index===r&&i.fragment.sn===t)return i}return null}function Og(e){e.forEach((e,t)=>{var r;null==(r=e.details)||r.fragments.forEach(e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function Ng(e,t){return!(e===t||!t)&&Fg(e)!==Fg(t)}function Fg(e){return e.replace(/\?[^?]*$/,"")}function $g(e,t){for(let n=0,i=e.length;n<i;n++){var r;if((null==(r=e[n])?void 0:r.cc)===t)return e[n]}return null}function Bg(e,t){const r=e.start+t;e.startPTS=r,e.setStart(r),e.endPTS=r+e.duration}function Ug(e,t){const r=t.fragments;for(let t=0,n=r.length;t<n;t++)Bg(r[t],e);t.fragmentHint&&Bg(t.fragmentHint,e),t.alignedSliding=!0}function zg(e,t){if(!function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e))return;const r=Math.min(t.endCC,e.endCC),n=$g(t.fragments,r),i=$g(e.fragments,r);if(!n||!i)return;Qd.log(`Aligning playlist at start of dicontinuity sequence ${r}`);Ug(n.start-i.start,e)}function jg(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const r=e.fragments,n=t.fragments;if(!r.length||!n.length)return;let i,s;const a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(i=$g(n,a),s=$g(r,a)),i&&s||(i=n[Math.floor(n.length/2)],s=$g(r,i.cc)||r[Math.floor(r.length/2)]);const o=i.programDateTime,l=s.programDateTime;if(!o||!l)return;Ug((l-o)/1e3-(s.start-i.start),e)}function Gg(e,t,r){Hg(e,t,r),e.addEventListener(t,r)}function Hg(e,t,r){e.removeEventListener(t,r)}const Vg=function(e){let t="";const r=e.length;for(let n=0;n<r;n++)t+=`[${e.start(n).toFixed(3)}-${e.end(n).toFixed(3)}]`;return t},Wg="STOPPED",Kg="IDLE",Yg="KEY_LOADING",qg="FRAG_LOADING",Xg="FRAG_LOADING_WAITING_RETRY",Qg="WAITING_TRACK",Zg="PARSING",Jg="PARSED",em="ENDED",tm="ERROR",rm="WAITING_INIT_PTS",nm="WAITING_LEVEL";class im extends Tp{constructor(e,t,r,n,i){super(n,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Wg,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:e,fragCurrent:t,media:r,mediaBuffer:n,state:i}=this,s=r?r.currentTime:0,a=Ap.bufferInfo(n||r,s,e.maxBufferHole),o=!a.len;if(this.log(`Media seeking to ${Ad(s)?s.toFixed(3):s}, state: ${i}, ${o?"out of":"in"} buffer`),this.state===em)this.resetLoadingState();else if(t){const r=e.maxFragLookUpTolerance,n=t.start-r,i=t.start+t.duration+r;if(o||i<a.start||n>a.end){const e=s>i;(s<n||e)&&(e&&t.loader&&(this.log(`Cancelling fragment load for seek (sn: ${t.sn})`),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(r){this.fragmentTracker.removeFragmentsInRange(s,1/0,this.playlistType,!0);if(s>this.lastCurrentTime&&(this.lastCurrentTime=s),!this.loadingParts){const e=Math.max(a.end,s),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${s.toFixed(2)} with buffer @${e.toFixed(2)}`),this.loadingParts=t)}}this.hls.hasEnoughToStart||(this.log(`Setting ${o?"startPosition":"nextLoadPosition"} to ${s} for seek without enough to start`),this.nextLoadPosition=s,o&&(this.startPosition=s)),o&&this.state===Kg&&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 bp(e.config),this.keyLoader=r,this.fragmentTracker=t,this.config=e.config,this.decrypter=new vp(e.config)}registerListeners(){const{hls:e}=this;e.on(Pd.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Pd.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Pd.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Pd.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Pd.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Pd.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Pd.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Pd.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===Wg)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Wg}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return-1===t&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const r=e.end||0,n=this.config.timelineOffset||0;if(r<=n)return!1;const i=e.buffered;this.config.maxBufferHole&&i&&i.length>1&&(e=Ap.bufferedInfo(i,e.start,0));const s=e.nextStart;if(s&&s>n&&s<t.edge)return!1;if(this.media.currentTime<e.start)return!1;const a=t.partList;if(null!=a&&a.length){const e=a[a.length-1];return Ap.isBuffered(this.media,e.start+e.duration/2)}const o=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;var t;return e?(null==(t=this.getLevelDetails())?void 0:t.appliedTimelineOffset)||e:0}onMediaAttached(e,t){const r=this.media=this.mediaBuffer=t.media;Gg(r,"seeking",this.onMediaSeeking),Gg(r,"ended",this.onMediaEnded);const n=this.config;this.levels&&n.autoStartLoad&&this.state===Wg&&this.startLoad(n.startPosition)}onMediaDetaching(e,t){const r=!!t.transferMedia,n=this.media;if(null!==n){if(n.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Hg(n,"seeking",this.onMediaSeeking),Hg(n,"ended",this.onMediaEnded),this.keyLoader&&!r&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,r)return this.resetLoadingState(),void this.resetTransmuxer();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,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=Wg,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,t,r){this.startFragRequested=!0,this._loadFragForPlayback(e,t,r)}_loadFragForPlayback(e,t,r){this._doFragLoad(e,t,r,e=>{const t=e.frag;if(this.fragContextChanged(t))return this.warn(`${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(e)}).then(e=>{if(!e)return;const t=this.state,r=e.frag;this.fragContextChanged(r)?(t===qg||!this.fragCurrent&&t===Zg)&&(this.fragmentTracker.removeFragment(r),this.state=Kg):("payload"in e&&(this.log(`Loaded ${r.type} sn: ${r.sn} of ${this.playlistLabel()} ${r.level}`),this.hls.trigger(Pd.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))}).catch(t=>{this.state!==Wg&&this.state!==tm&&(this.warn(`Frag error: ${(null==t?void 0:t.message)||t}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:r}=this;if(r.getState(e)===sp){const t=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,t),i=Math.max(e.duration,n?n.len:this.config.maxBufferLength),s=this.backtrackFragment;(1===(s?e.sn-s.sn:0)||this.reduceMaxBufferLength(i,e.duration))&&r.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?r.removeAllFragments():r.hasParts(e.type)&&(r.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),r.getState(e)===ap&&r.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,r=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:r};this.hls.trigger(Pd.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(e=>{const t=null==e?void 0:e.frag;if(!t||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return e}).then(e=>{const{hls:t}=this,{frag:r,payload:n}=e,i=r.decryptdata;if(n&&n.byteLength>0&&null!=i&&i.key&&i.iv&&zp(i.method)){const s=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),i.key.buffer,i.iv.buffer,jp(i.method)).catch(e=>{throw t.trigger(Pd.ERROR,{type:Id.MEDIA_ERROR,details:Cd.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:r}),e}).then(n=>{const i=self.performance.now();return t.trigger(Pd.FRAG_DECRYPTED,{frag:r,payload:n,stats:{tstart:s,tdecrypt:i}}),e.payload=n,this.completeInitSegmentLoad(e)})}return this.completeInitSegmentLoad(e)}).catch(t=>{this.state!==Wg&&this.state!==tm&&(this.warn(t),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const r=e.frag.stats;this.state!==Wg&&(this.state=Kg),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,t){var r,n;const i=e.tracks;if(i&&!t.encrypted&&(null!=(r=i.audio)&&r.encrypted||null!=(n=i.video)&&n.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const e=this.media,r=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${e?"attached mediaKeys: "+e.mediaKeys:"detached"})`);return this.warn(r.message),!e||e.mediaKeys?!1:(this.hls.trigger(Pd.ERROR,{type:Id.KEY_SYSTEM_ERROR,details:Cd.KEY_SYSTEM_NO_KEYS,fatal:!1,error:r,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const r=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${r?Vg(Ap.getBuffered(r)):"(detached)"})`),vh(e)){var n;if(e.type!==$d){const t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return void(this.state=Kg)}const t=null==(n=this.levels)?void 0:n[e.level];null!=t&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=Kg}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:r,part:n,partsLoaded:i}=e,s=!i||0===i.length||i.some(e=>!e),a=new xp(r.level,r.sn,r.stats.chunkCount+1,0,n?n.index:-1,!s);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,r=null,n){var i;this.fragCurrent=e;const s=t.details;if(!this.levels||!s)throw new Error(`frag load aborted, missing level${s?"":" detail"}s`);let a=null;if(!e.encrypted||null!=(i=e.decryptdata)&&i.key)e.encrypted||(a=this.keyLoader.loadClear(e,s.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));else if(this.log(`Loading key for ${e.sn} of [${s.startSN}-${s.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=Yg,this.fragCurrent=e,a=this.keyLoader.load(e).then(e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(Pd.KEY_LOADED,e),this.state===Yg&&(this.state=Kg),e}),this.hls.trigger(Pd.KEY_LOADING,{frag:e}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);const o=this.fragPrevious;if(vh(e)&&(!o||e.sn!==o.sn)){const r=this.shouldLoadParts(t.details,e.end);r!==this.loadingParts&&(this.log(`LL-Part loading ${r?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${e.sn}`),this.loadingParts=r)}if(r=Math.max(e.start,r||0),this.loadingParts&&vh(e)){const i=s.partList;if(i&&n){r>s.fragmentEnd&&s.fragmentHint&&(e=s.fragmentHint);const o=this.getNextPart(i,e,r);if(o>-1){const l=i[o];let u;return e=this.fragCurrent=l.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${l.index} (${o}/${i.length-1}) of ${this.fragInfo(e,!1,l)}) cc: ${e.cc} [${s.startSN}-${s.endSN}], target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=qg,u=a?a.then(r=>!r||this.fragContextChanged(r.frag)?null:this.doFragPartsLoad(e,l,t,n)).catch(e=>this.handleFragLoadError(e)):this.doFragPartsLoad(e,l,t,n).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(Pd.FRAG_LOADING,{frag:e,part:l,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):u}if(!e.url||this.loadedEndOfParts(i,r))return Promise.resolve(null)}}var l;if(vh(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${r.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${null==(l=s.partList)?void 0:l.filter(e=>e.loaded).map(e=>`[${e.start}-${e.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} ${"["+s.startSN+"-"+s.endSN+"]"}, target: ${parseFloat(r.toFixed(3))}`),Ad(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=qg;const u=this.config.progressive&&e.type!==$d;let c;return c=u&&a?a.then(t=>!t||this.fragContextChanged(t.frag)?null:this.fragmentLoader.load(e,n)).catch(e=>this.handleFragLoadError(e)):Promise.all([this.fragmentLoader.load(e,u?n:void 0),a]).then(([e])=>(!u&&n&&n(e),e)).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(Pd.FRAG_LOADING,{frag:e,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(e,t,r,n){return new Promise((i,s)=>{var a;const o=[],l=null==(a=r.details)?void 0:a.partList,u=t=>{this.fragmentLoader.loadPart(e,t,n).then(n=>{o[t.index]=n;const s=n.part;this.hls.trigger(Pd.FRAG_LOADED,n);const a=_g(r.details,e.sn,t.index+1)||Mg(l,e.sn,t.index+1);if(!a)return i({frag:e,part:s,partsLoaded:o});u(a)}).catch(s)};u(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===Cd.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===Id.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(Pd.ERROR,t)}else this.hls.trigger(Pd.ERROR,{type:Id.OTHER_ERROR,details:Cd.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Zg)return void(this.fragCurrent||this.state===Wg||this.state===tm||(this.state=Kg));const{frag:r,part:n,level:i}=t,s=self.performance.now();r.stats.parsing.end=s,n&&(n.stats.parsing.end=s);const a=this.getLevelDetails(),o=a&&r.sn>a.endSN||this.shouldLoadParts(a,r.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${r.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(r,n,i,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var r;const i=e.partList[0];if(i.fragment.type===$d)return!1;if(t>=i.end+((null==(r=e.fragmentHint)?void 0:r.duration)||0)){var n;if((this.hls.hasEnoughToStart?(null==(n=this.media)?void 0:n.currentTime)||this.lastCurrentTime:this.getLoadPosition())>i.start-i.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:r}=this,{level:n,sn:i,part:s}=e;if(null==t||!t[n])return this.warn(`Levels object was unset while buffering fragment ${i} of ${this.playlistLabel()} ${n}. The current chunk will not be buffered.`),null;const a=t[n],o=a.details,l=s>-1?_g(o,i,s):null,u=l?l.fragment:Dg(o,i,r);return u?(r&&r!==u&&(u.stats=r.stats),{frag:u,part:l,level:a}):null}bufferFragmentData(e,t,r,n,i){if(this.state!==Zg)return;const{data1:s,data2:a}=e;let o=s;if(a&&(o=Bh(s,a)),!o.length)return;const l=this.initPTS[t.cc],u=l?-l.baseTime/l.timescale:void 0,c={type:e.type,frag:t,part:r,chunkMeta:n,offset:u,parent:t.type,data:o};if(this.hls.trigger(Pd.BUFFER_APPENDING,c),e.dropped&&e.independent&&!r){if(i)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!Ap.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const r=t.currentTime,n=Ap.bufferInfo(t,r,0),i=e.duration,s=Math.min(2*this.config.maxFragLookUpTolerance,.25*i),a=Math.max(Math.min(e.start-s,n.end-s),r+s);e.start-a>s&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var r;const n=this.getLoadPosition();if(!Ad(n))return null;const i=this.lastCurrentTime>n||null!=(r=this.media)&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,i)}getFwdBufferInfoAtPos(e,t,r,n){const i=Ap.bufferInfo(e,t,n);if(0===i.len&&void 0!==i.nextStart){const s=this.fragmentTracker.getBufferedFrag(t,r);if(s&&(i.nextStart<=s.end||s.gap)){const r=Math.max(Math.min(i.nextStart,s.end)-t,n);return Ap.bufferInfo(e,t,r)}}return i}getMaxBufferLength(e){const{config:t}=this;let r;return r=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(r,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const r=this.config,n=Math.max(Math.min(e-t,r.maxBufferLength),t),i=Math.max(e-3*t,r.maxMaxBufferLength/2,n);return i>=n&&(r.maxMaxBufferLength=i,this.warn(`Reduce max buffer length to ${i}s`),!0)}getAppendedFrag(e,t=Nd){const r=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return r&&"fragment"in r?r.fragment:r}getNextFragment(e,t){const r=t.fragments,n=r.length;if(!n)return null;const{config:i}=this,s=r[0].start,a=i.lowLatencyMode&&!!t.partList;let o=null;if(t.live){const r=i.initialLiveManifestSize;if(n<r)return this.warn(`Not enough fragments to start playback (have: ${n}, need: ${r})`),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<s){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t);const r=this.hls.startPosition,n=this.hls.liveSyncPosition,i=o?(-1!==r&&r>=s?r:n)||o.start:e;this.log(`Setting startPosition to ${i} to match start frag at live edge. mainStart: ${r} liveSyncPosition: ${n} frag.start: ${null==(l=o)?void 0:l.start}`),this.startPosition=this.nextLoadPosition=i}}else e<=s&&(o=r[0]);if(!o){const r=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,r,t)}let u=this.filterReplacedPrimary(o,t);if(!u&&o){const e=o.sn-t.startSN;u=this.filterReplacedPrimary(r[e+1]||null,t)}return this.mapToInitFragWhenRequired(u)}isLoopLoading(e,t){const r=this.fragmentTracker.getState(e);return(r===op||r===ap&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,r,n,i){let s=null;if(e.gap&&(s=this.getNextFragment(this.nextLoadPosition,t),s&&!s.gap&&r.nextStart)){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,n,0);if(null!==e&&r.len+e.len>=i){const e=s.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,s}get primaryPrefetch(){if(sm(this.config)){var e;if(null==(e=this.hls.interstitialsManager)||null==(e=e.playingItem)?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(sm(this.config)&&e.type!==$d){const r=this.hls.interstitialsManager,n=null==r?void 0:r.bufferingItem;if(n){const r=n.event;if(r){if(r.appendInPlace||Math.abs(e.start-n.start)>1||0===n.start)return null}else{if(e.end<=n.start&&!1===(null==t?void 0:t.live))return null;if(e.start>n.end&&n.nextEvent&&(n.nextEvent.appendInPlace||e.start-n.end>1))return null}}const i=null==r?void 0:r.playerQueue;if(i)for(let t=i.length;t--;){const r=i[t].interstitial;if(r.appendInPlace&&e.start>=r.startTime&&e.end<=r.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,r){let n=-1,i=!1,s=!0;for(let a=0,o=e.length;a<o;a++){const o=e[a];if(s=s&&!o.independent,n>-1&&r<o.start)break;const l=o.loaded;l?n=-1:(i||(o.independent||s)&&o.fragment===t)&&(o.fragment!==t&&this.warn(`Need buffer at ${r} but next unloaded part starts at ${o.start}`),n=a),i=l}return n}loadedEndOfParts(e,t){let r;for(let n=e.length;n--;){if(r=e[n],!r.loaded)return!1;if(t>r.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,r=this.fragPrevious;let n=null;if(r){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${r.programDateTime}`),n=function(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!Ad(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(let n=0;n<e.length;++n){const i=e[n];if(Bf(t,r,i))return i}return null}(t,r.endProgramDateTime,this.config.maxFragLookUpTolerance)),!n){const i=r.sn+1;if(i>=e.startSN&&i<=e.endSN){const s=t[i-e.startSN];r.cc===s.cc&&(n=s,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=Uf(e,r.cc,r.end),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(n=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return n}getFragmentAtPosition(e,t,r){const{config:n}=this;let{fragPrevious:i}=this,{fragments:s,endSN:a}=r;const{fragmentHint:o}=r,{maxFragLookUpTolerance:l}=n,u=r.partList,c=!!(this.loadingParts&&null!=u&&u.length&&o);let d;if(c&&!this.bitrateTest&&u[u.length-1].fragment.sn===o.sn&&(s=s.concat(o),a=o.sn),e<t){var h;d=Ff(i,s,e,e<this.lastCurrentTime||e>t-l||null!=(h=this.media)&&h.paused||!this.startFragRequested?0:l)}else d=s[s.length-1];if(d){const e=d.sn-r.startSN,t=this.fragmentTracker.getState(d);if((t===op||t===ap&&d.gap)&&(i=d),i&&d.sn===i.sn&&(!c||u[0].fragment.sn>d.sn||!r.live)){if(d.level===i.level){const t=s[e+1];d=d.sn<a&&this.fragmentTracker.getState(t)!==op?t:null}}}return d}alignPlaylists(e,t,r){const n=e.fragments.length;if(!n)return this.warn("No fragments in live playlist"),0;const i=e.fragmentStart,s=!t,a=e.alignedSliding&&Ad(i);if(s||!a&&!i){!function(e,t){e&&(zg(t,e),t.alignedSliding||jg(t,e),t.alignedSliding||t.skippedSegments||Ig(e,t,!1))}(r,e);const i=e.fragmentStart;return this.log(`Live playlist sliding: ${i.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${n}`),i}return i}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let r=this.startPosition;r<t&&(r=-1);const n=this.timelineOffset;if(-1===r){const i=null!==this.startTimeOffset,s=i?this.startTimeOffset:e.startTimeOffset;null!==s&&Ad(s)?(r=t+s,s<0&&(r+=e.edge),r=Math.min(Math.max(t,r),t+e.totalduration),this.log(`Setting startPosition to ${r} for start time offset ${s} found in ${i?"multivariant":"media"} playlist`),this.startPosition=r):e.live?(r=this.hls.liveSyncPosition||t,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+n}this.nextLoadPosition=r+n}getLoadPosition(){var e;const{media:t}=this;let r=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?r=t.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&vh(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===Xg)||(this.state=Kg)}onFragmentOrKeyLoadError(e,t){var r;if(t.chunkMeta&&!t.frag){const e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}const n=t.frag;if(!n||n.type!==e||!this.levels)return;var i;if(this.fragContextChanged(n))return void this.warn(`Frag load error must match current frag to retry ${n.url} > ${null==(i=this.fragCurrent)?void 0:i.url}`);const s=t.details===Cd.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(n,!0);const a=t.errorAction;if(!a)return void(this.state=tm);const{action:o,flags:l,retryCount:u=0,retryConfig:c}=a,d=!!c,h=d&&o===Zf,f=d&&!a.resolved&&l===ep,p=null==(r=this.hls.latestLevelDetails)?void 0:r.live;if(!h&&f&&vh(n)&&!n.endList&&p&&!Gf(t))this.resetFragmentErrors(e),this.treatAsGap(n),a.resolved=!0;else if((h||f)&&u<c.maxNumRetry){var g;const r=Yf(null==(g=t.response)?void 0:g.code),i=Vf(c,u);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+i,this.state=Xg,a.resolved=!0,r)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(t.reason="offline");this.warn(`Fragment ${n.sn} of ${e} ${n.level} errored with ${t.details}, retrying loading ${u+1}/${c.maxNumRetry} in ${i}ms`)}else if(c){if(this.resetFragmentErrors(e),!(u<c.maxNumRetry))return void this.warn(`${t.details} reached or exceeded max retry (${u})`);s||o===Qf||(a.resolved=!0)}else this.state=o===Xf?nm:tm;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,r=t===1/0;(!t||e>=t||r&&!Yf(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Kg)}reduceLengthAndFlushBuffer(e){if(this.state===Zg||this.state===Jg){const t=e.frag,r=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,r),i=n&&n.len>.5;i&&this.reduceMaxBufferLength(n.len,(null==t?void 0:t.duration)||10);const s=!i;return s&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${r} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),s}return!1}resetFragmentErrors(e){e===Fd&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Wg&&(this.state=Kg)}afterBufferFlushed(e,t,r){if(!e)return;const n=Ap.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,r),this.state===em&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Wg&&(this.state=Kg)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${-1===e.level?"<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,t,r,n){const i=r.details;if(!i)return void this.warn("level.details undefined");if(!Object.keys(e.elementaryStreams).reduce((t,s)=>{const a=e.elementaryStreams[s];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${s} duration reliably (${o})`),t||!1;const l=n?0:Ag(i,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this);return this.hls.trigger(Pd.LEVEL_PTS_UPDATED,{details:i,level:r,drift:l,type:s,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t},!1)){var s;const t=null===(null==(s=this.transmuxer)?void 0:s.error);if((0===r.fragmentError||t&&(r.fragmentError<2||e.endList))&&this.treatAsGap(e,r),t){const t=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(t.message),this.hls.trigger(Pd.ERROR,{type:Id.MEDIA_ERROR,details:Cd.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${r.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Jg,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(Pd.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===Nd?"level":"track"}fragInfo(e,t=!0,r){var n,i;return`${this.playlistLabel()} ${e.level} (${r?"part":"frag"}:[${(null!=(n=t&&!r?e.startPTS:(r||e).start)?n:NaN).toFixed(3)}-${(null!=(i=t&&!r?e.endPTS:(r||e).end)?i:NaN).toFixed(3)}]${r&&"main"===e.type?"INDEPENDENT="+(r.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;null==(e=this.transmuxer)||e.reset()}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function sm(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}class am{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let r;return e.length?(r=1===e.length?e[0]:function(e,t){const r=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){const i=e[t];r.set(i,n),n+=i.length}return r}(e,t),this.reset(),r):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var om,lm={exports:{}};var um=(om||(om=1,function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}function i(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function s(e,t,n,s,a){if("function"!=typeof n)throw new TypeError("The listener must be a function");var o=new i(n,s||e,a),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0===--e._eventsCount?e._events=new n:delete e._events[t]}function o(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),o.prototype.eventNames=function(){var e,n,i=[];if(0===this._eventsCount)return i;for(n in e=this._events)t.call(e,n)&&i.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},o.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,a=new Array(s);i<s;i++)a[i]=n[i].fn;return a},o.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},o.prototype.emit=function(e,t,n,i,s,a){var o=r?r+e:e;if(!this._events[o])return!1;var l,u,c=this._events[o],d=arguments.length;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),d){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,s),!0;case 6:return c.fn.call(c.context,t,n,i,s,a),!0}for(u=1,l=new Array(d-1);u<d;u++)l[u-1]=arguments[u];c.fn.apply(c.context,l)}else{var h,f=c.length;for(u=0;u<f;u++)switch(c[u].once&&this.removeListener(e,c[u].fn,void 0,!0),d){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,t);break;case 3:c[u].fn.call(c[u].context,t,n);break;case 4:c[u].fn.call(c[u].context,t,n,i);break;default:if(!l)for(h=1,l=new Array(d-1);h<d;h++)l[h-1]=arguments[h];c[u].fn.apply(c[u].context,l)}}return!0},o.prototype.on=function(e,t,r){return s(this,e,t,r,!1)},o.prototype.once=function(e,t,r){return s(this,e,t,r,!0)},o.prototype.removeListener=function(e,t,n,i){var s=r?r+e:e;if(!this._events[s])return this;if(!t)return a(this,s),this;var o=this._events[s];if(o.fn)o.fn!==t||i&&!o.once||n&&o.context!==n||a(this,s);else{for(var l=0,u=[],c=o.length;l<c;l++)(o[l].fn!==t||i&&!o[l].once||n&&o[l].context!==n)&&u.push(o[l]);u.length?this._events[s]=1===u.length?u[0]:u:a(this,s)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&a(this,t)):(this._events=new n,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,e.exports=o}(lm)),lm.exports),cm=nh(um);const dm="1.6.15",hm={};function fm(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function pm(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function gm(e,t){let r=0;return r=(127&e[t])<<21,r|=(127&e[t+1])<<14,r|=(127&e[t+2])<<7,r|=127&e[t+3],r}function mm(e,t){const r=t;let n=0;for(;pm(e,t);){n+=10;n+=gm(e,t+6),fm(e,t+10)&&(n+=10),t+=n}if(n>0)return e.subarray(r,r+n)}function vm(e,t){return 255===e[t]&&240==(246&e[t+1])}function ym(e,t){return 1&e[t+1]?7:9}function bm(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function wm(e,t){return t+1<e.length&&vm(e,t)}function Em(e,t){if(wm(e,t)){const r=ym(e,t);if(t+r>=e.length)return!1;const n=bm(e,t);if(n<=r)return!1;const i=t+n;return i===e.length||wm(e,i)}return!1}function Sm(e,t,r,n,i){if(!e.samplerate){const s=function(e,t,r,n){const i=t[r+2],s=i>>2&15;if(s>12){const t=new Error(`invalid ADTS sampling index:${s}`);return void e.emit(Pd.ERROR,Pd.ERROR,{type:Id.MEDIA_ERROR,details:Cd.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message})}const a=1+(i>>6&3),o=t[r+3]>>6&3|(1&i)<<2,l="mp4a.40."+a,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][s];let c=s;5!==a&&29!==a||(c-=3);const d=[a<<3|(14&c)>>1,(1&c)<<7|o<<3];return Qd.log(`manifest codec:${n}, parsed codec:${l}, channels:${o}, rate:${u} (ADTS object type:${a} sampling index:${s})`),{config:d,samplerate:u,channelCount:o,codec:l,parsedCodec:l,manifestCodec:n}}(t,r,n,i);if(!s)return;jd(e,s)}}function Tm(e){return 9216e4/e}function xm(e,t,r,n,i){const s=n+i*Tm(e.samplerate),a=function(e,t){const r=ym(e,t);if(t+r<=e.length){const n=bm(e,t)-r;if(n>0)return{headerLength:r,frameLength:n}}}(t,r);let o;if(a){const{frameLength:n,headerLength:i}=a,l=i+n,u=Math.max(0,r+l-t.length);u?(o=new Uint8Array(l-i),o.set(t.subarray(r+i,t.length),0)):o=t.subarray(r+i,r+l);const c={unit:o,pts:s};return u||e.samples.push(c),{sample:c,length:l,missing:u}}const l=t.length-r;o=new Uint8Array(l),o.set(t.subarray(r,t.length),0);return{sample:{unit:o,pts:s},length:l,missing:-1}}function km(e,t){return pm(e,t)&&gm(e,t+6)+10<=e.length-t}function Am(e,t=0,r=1/0){return function(e,t,r,n){const i=function(e){return e instanceof ArrayBuffer?e:e.buffer}(e);let s=1;"BYTES_PER_ELEMENT"in n&&(s=n.BYTES_PER_ELEMENT);const a=(d=e,d&&d.buffer instanceof ArrayBuffer&&void 0!==d.byteLength&&void 0!==d.byteOffset?e.byteOffset:0),o=(a+e.byteLength)/s,l=(a+t)/s,u=Math.floor(Math.max(0,Math.min(l,o))),c=Math.floor(Math.min(u+Math.max(r,0),o));var d;return new n(i,u,c-u)}(e,t,r,Uint8Array)}function Rm(e){const t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(e.size<2)return;if(3!==e.data[0])return void console.log("Ignore frame with unrecognized character encoding");const r=e.data.subarray(1).indexOf(0);if(-1===r)return;const n=eh(Am(e.data,1,r)),i=e.data[2+r],s=e.data.subarray(3+r).indexOf(0);if(-1===s)return;const a=eh(Am(e.data,3+r,s));let o;return o="--\x3e"===n?eh(Am(e.data,4+r+s)):function(e){return e instanceof ArrayBuffer?e:0==e.byteOffset&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}(e.data.subarray(4+r+s)),t.mimeType=n,t.pictureType=i,t.description=a,t.data=o,t}function Lm(e){return"PRIV"===e.type?function(e){if(e.size<2)return;const t=eh(e.data,!0),r=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:r.buffer}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;let t=1;const r=eh(e.data.subarray(t),!0);t+=r.length+1;const n=eh(e.data.subarray(t));return{key:e.type,info:r,data:n}}const t=eh(e.data);return{key:e.type,info:"",data:t}}(e):"APIC"===e.type?Rm(e):function(e){if(e.size<2)return;if("TXXX"===e.type){let t=1;const r=eh(e.data.subarray(t),!0);t+=r.length+1;const n=eh(e.data.subarray(t));return{key:e.type,info:r,data:n}}const t=eh(e.data.subarray(1));return{key:e.type,info:"",data:t}}(e)}function Im(e){const t=String.fromCharCode(e[0],e[1],e[2],e[3]),r=gm(e,4);return{type:t,size:r,data:e.subarray(10,10+r)}}function Cm(e){let t=0;const r=[];for(;pm(e,t);){const n=gm(e,t+6);e[t+5]>>6&1&&(t+=10),t+=10;const i=t+n;for(;t+10<i;){const n=Im(e.subarray(t)),i=Lm(n);i&&r.push(i),t+=n.size+10}fm(e,t)&&(t+=10)}return r}function Pm(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function Dm(e){if(8===e.data.byteLength){const t=new Uint8Array(e.data),r=1&t[3];let n=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return n/=45,r&&(n+=47721858.84),Math.round(n)}}function _m(e){const t=Cm(e);for(let e=0;e<t.length;e++){const r=t[e];if(Pm(r))return Dm(r)}}let Mm=function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e}({});function Om(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class Nm{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,t,r,n){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,t){return!1}appendFrame(e,t,r){}demux(e,t){this.cachedData&&(e=Bh(this.cachedData,e),this.cachedData=null);let r,n=mm(e,0),i=n?n.length:0;const s=this._audioTrack,a=this._id3Track,o=n?_m(n):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&Ad(o))&&(this.basePTS=Fm(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),n&&n.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:Mm.audioId3,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(e,i)){const t=this.appendFrame(s,e,i);t?(this.frameIndex++,this.lastPTS=t.sample.pts,i+=t.length,r=i):i=l}else km(e,i)?(n=mm(e,i),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:Mm.audioId3,duration:Number.POSITIVE_INFINITY}),i+=n.length,r=i):i++;if(i===l&&r!==l){const t=e.slice(r);this.cachedData?this.cachedData=Bh(this.cachedData,t):this.cachedData=t}}return{audioTrack:s,videoTrack:Om(),id3Track:a,textTrack:Om()}}demuxSampleAes(e,t,r){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Om(),id3Track:this._id3Track,textTrack:Om()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Fm=(e,t,r)=>{if(Ad(e))return 90*e;return 9e4*t+(r?9e4*r.baseTime/r.timescale:0)};let $m=null;const Bm=[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],Um=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],zm=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],jm=[0,1,1,4];function Gm(e,t,r,n,i){if(r+24>t.length)return;const s=Hm(t,r);if(s&&r+s.frameLength<=t.length){const a=n+i*(9e4*s.samplesPerFrame/s.sampleRate),o={unit:t.subarray(r,r+s.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=s.channelCount,e.samplerate=s.sampleRate,e.samples.push(o),{sample:o,length:s.frameLength,missing:0}}}function Hm(e,t){const r=e[t+1]>>3&3,n=e[t+1]>>1&3,i=e[t+2]>>4&15,s=e[t+2]>>2&3;if(1!==r&&0!==i&&15!==i&&3!==s){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*Bm[14*(3===r?3-n:3===n?3:4)+i-1],u=Um[3*(3===r?0:2===r?1:2)+s],c=3===o?1:2,d=zm[r][n],h=jm[n],f=8*d*h,p=Math.floor(d*l/u+a)*h;if(null===$m){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);$m=e?parseInt(e[1]):0}return!!$m&&$m<=87&&2===n&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:u,channelCount:c,frameLength:p,samplesPerFrame:f}}}function Vm(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function Wm(e,t){return t+1<e.length&&Vm(e,t)}function Km(e,t){if(t+1<e.length&&Vm(e,t)){const r=4,n=Hm(e,t);let i=r;null!=n&&n.frameLength&&(i=n.frameLength);const s=t+i;return s===e.length||Wm(e,s)}return!1}const Ym=(e,t)=>{let r=0,n=5;t+=n;const i=new Uint32Array(1),s=new Uint32Array(1),a=new Uint8Array(1);for(;n>0;){a[0]=e[t];const o=Math.min(n,8),l=8-o;s[0]=4278190080>>>24+l<<l,i[0]=(a[0]&s[0])>>l,r=r?r<<o|i[0]:i[0],t+=1,n-=o}return r};class qm extends Nm{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,r,n){super.resetInitSegment(e,t,r,n),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,r){const n=Xm(e,t,r,this.basePTS,this.frameIndex);if(-1!==n){return{sample:e.samples[e.samples.length-1],length:n,missing:0}}}static probe(e){if(!e)return!1;const t=mm(e,0);if(!t)return!1;const r=t.length;return 11===e[r]&&119===e[r+1]&&void 0!==_m(t)&&Ym(e,r)<16}}function Xm(e,t,r,n,i){if(r+8>t.length)return-1;if(11!==t[r]||119!==t[r+1])return-1;const s=t[r+4]>>6;if(s>=3)return-1;const a=[48e3,44100,32e3][s],o=63&t[r+4],l=2*[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][3*o+s];if(r+l>t.length)return-1;const u=t[r+6]>>5;let c=0;2===u?c+=2:(1&u&&1!==u&&(c+=2),4&u&&(c+=2));const d=(t[r+6]<<8|t[r+7])>>12-c&1,h=[2,1,2,3,3,4,4,5][u]+d,f=t[r+5]>>3,p=7&t[r+5],g=new Uint8Array([s<<6|f<<1|p>>2,(3&p)<<6|u<<3|d<<2|o>>4,o<<4&224]),m=n+i*(1536/a*9e4),v=t.subarray(r,r+l);return e.config=g,e.channelCount=h,e.samplerate=a,e.samples.push({unit:v,pts:m}),l}const Qm=/\/emsg[-/]ID3/i;function Zm(e,t){return Ad(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}class Jm{constructor(e,t,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new vp(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,hp)}decryptAacSample(e,t,r){const n=e[t].unit;if(n.length<=16)return;const i=n.subarray(16,n.length-n.length%16),s=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(s).then(i=>{const s=new Uint8Array(i);n.set(s,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,r)}).catch(r)}decryptAacSamples(e,t,r){for(;;t++){if(t>=e.length)return void r();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,r),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t);let n=0;for(let t=32;t<e.length-16;t+=160,n+=16)r.set(e.subarray(t,t+16),n);return r}getAvcDecryptedUnit(e,t){const r=new Uint8Array(t);let n=0;for(let t=32;t<e.length-16;t+=160,n+=16)e.set(r.subarray(n,n+16),t);return e}decryptAvcSample(e,t,r,n,i){const s=Hh(i.data),a=this.getAvcEncryptedData(s);this.decryptBuffer(a.buffer).then(a=>{i.data=this.getAvcDecryptedUnit(s,a),this.decrypter.isSync()||this.decryptAvcSamples(e,t,r+1,n)}).catch(n)}decryptAvcSamples(e,t,r,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,r=0){if(t>=e.length)return void n();const i=e[t].units;for(;!(r>=i.length);r++){const s=i[r];if(!(s.data.length<=48||1!==s.type&&5!==s.type||(this.decryptAvcSample(e,t,r,n,s),this.decrypter.isSync())))return}}}}class ev{constructor(){this.VideoSample=null}createVideoSample(e,t,r){return{key:e,frame:!1,pts:t,dts:r,units:[],length:0}}getLastNalUnit(e){var t;let r,n=this.VideoSample;if(n&&0!==n.units.length||(n=e[e.length-1]),null!=(t=n)&&t.units){const e=n.units;r=e[e.length-1]}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const r=t.samples,n=r.length;if(!n)return void t.dropped++;{const t=r[n-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}}parseNALu(e,t,r){const n=t.byteLength;let i=e.naluState||0;const s=i,a=[];let o,l,u,c=0,d=-1,h=0;for(-1===i&&(d=0,h=this.getNALuType(t,0),i=0,c=1);c<n;)if(o=t[c++],i)if(1!==i)if(o)if(1===o){if(l=c-i-1,d>=0){const e={data:t.subarray(d,l),type:h};a.push(e)}else{const r=this.getLastNalUnit(e.samples);r&&(s&&c<=4-s&&r.state&&(r.data=r.data.subarray(0,r.data.byteLength-s)),l>0&&(r.data=Bh(r.data,t.subarray(0,l)),r.state=0))}c<n?(u=this.getNALuType(t,c),d=c,h=u,i=0):i=-1}else i=0;else i=3;else i=o?0:2;else i=o?0:1;if(d>=0&&i>=0){const e={data:t.subarray(d,n),type:h,state:i};a.push(e)}if(0===a.length){const r=this.getLastNalUnit(e.samples);r&&(r.data=Bh(r.data,t))}return e.naluState=i,a}}class tv{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,t=this.bytesAvailable,r=e.byteLength-t,n=new Uint8Array(4),i=Math.min(4,t);if(0===i)throw new Error("no bytes available");n.set(e.subarray(r,r+i)),this.word=new DataView(n.buffer).getUint32(0),this.bitsAvailable=8*i,this.bytesAvailable-=i}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const r=this.word>>>32-t;if(e>32&&Qd.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?r<<t|this.readBits(t):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 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class rv extends ev{parsePES(e,t,r,n){const i=this.parseNALu(e,r.data,n);let s,a=this.VideoSample,o=!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(n=>{var i,l;switch(n.type){case 1:{let t=!1;s=!0;const i=n.data;if(o&&i.length>4){const e=this.readSliceType(i);2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var u;if(t)null!=(u=a)&&u.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=t;break}case 5:s=!0,null!=(i=a)&&i.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:s=!0,Gh(n.data,1,r.pts,t.samples);break;case 7:{var c,d;s=!0,o=!0;const t=n.data,r=this.readSPS(t);if(!e.sps||e.width!==r.width||e.height!==r.height||(null==(c=e.pixelRatio)?void 0:c[0])!==r.pixelRatio[0]||(null==(d=e.pixelRatio)?void 0:d[1])!==r.pixelRatio[1]){e.width=r.width,e.height=r.height,e.pixelRatio=r.pixelRatio,e.sps=[t];const n=t.subarray(1,4);let i="avc1.";for(let e=0;e<3;e++){let t=n[e].toString(16);t.length<2&&(t="0"+t),i+=t}e.codec=i}break}case 8:s=!0,e.pps=[n.data];break;case 9:s=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;case 12:s=!0;break;default:s=!1}if(a&&s){a.units.push(n)}}),n&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return 31&e[t]}readSliceType(e){const t=new tv(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let r,n=8,i=8;for(let s=0;s<e;s++)0!==i&&(r=t.readEG(),i=(n+r+256)%256),n=0===i?n:i}readSPS(e){const t=new tv(e);let r,n,i,s=0,a=0,o=0,l=0;const u=t.readUByte.bind(t),c=t.readBits.bind(t),d=t.readUEG.bind(t),h=t.readBoolean.bind(t),f=t.skipBits.bind(t),p=t.skipEG.bind(t),g=t.skipUEG.bind(t),m=this.skipScalingList.bind(this);u();const v=u();if(c(5),f(3),u(),g(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const e=d();if(3===e&&f(1),g(),g(),f(1),h())for(n=3!==e?8:12,i=0;i<n;i++)h()&&m(i<6?16:64,t)}g();const y=d();if(0===y)d();else if(1===y)for(f(1),p(),p(),r=d(),i=0;i<r;i++)p();g(),f(1);const b=d(),w=d(),E=c(1);0===E&&f(1),f(1),h()&&(s=d(),a=d(),o=d(),l=d());let S=[1,1];if(h()&&h()){switch(u()){case 1:S=[1,1];break;case 2:S=[12,11];break;case 3:S=[10,11];break;case 4:S=[16,11];break;case 5:S=[40,33];break;case 6:S=[24,11];break;case 7:S=[20,11];break;case 8:S=[32,11];break;case 9:S=[80,33];break;case 10:S=[18,11];break;case 11:S=[15,11];break;case 12:S=[64,33];break;case 13:S=[160,99];break;case 14:S=[4,3];break;case 15:S=[3,2];break;case 16:S=[2,1];break;case 255:S=[u()<<8|u(),u()<<8|u()]}}return{width:Math.ceil(16*(b+1)-2*s-2*a),height:(2-E)*(w+1)*16-(E?2:4)*(o+l),pixelRatio:S}}}class nv extends ev{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,r,n){const i=this.parseNALu(e,r.data,n);let s,a=this.VideoSample,o=!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(n=>{var i,l;switch(n.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,s=!0;break;case 16:case 17:case 18:case 21:var u;if(s=!0,o)null!=(u=a)&&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 19:case 20:s=!0,null!=(i=a)&&i.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:s=!0,Gh(n.data,2,r.pts,t.samples);break;case 32:s=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=jd(e.params,this.readVPS(n.data)),this.initVPS=n.data),e.vps=[n.data];break;case 33:if(s=!0,o=!0,void 0===e.vps||e.vps[0]===this.initVPS||void 0===e.sps||this.matchSPS(e.sps[0],n.data)||(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const t=this.readSPS(n.data);e.width=t.width,e.height=t.height,e.pixelRatio=t.pixelRatio,e.codec=t.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={});for(const r in t.params)e.params[r]=t.params[r]}this.pushParameterSet(e.sps,n.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),a.key=!0;break;case 34:if(s=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];const t=this.readPPS(n.data);for(const r in t)e.params[r]=t[r]}this.pushParameterSet(e.pps,n.data,e.vps)}break;case 35:s=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;default:s=!1}if(a&&s){a.units.push(n)}}),n&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,r){(r&&r[0]===this.initVPS||!r&&!e.length)&&e.push(t)}getNALuType(e,t){return(126&e[t])>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let r=0;for(let n=0;n<e.byteLength;n++)n>=2&&3===e[n]&&0===e[n-1]&&0===e[n-2]||(t[r]=e[n],r++);return new Uint8Array(t.buffer,0,r)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new tv(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);return{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}}readSPS(e){const t=new tv(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const r=t.readBits(3);t.readBoolean();const n=t.readBits(2),i=t.readBoolean(),s=t.readBits(5),a=t.readUByte(),o=t.readUByte(),l=t.readUByte(),u=t.readUByte(),c=t.readUByte(),d=t.readUByte(),h=t.readUByte(),f=t.readUByte(),p=t.readUByte(),g=t.readUByte(),m=t.readUByte(),v=[],y=[];for(let e=0;e<r;e++)v.push(t.readBoolean()),y.push(t.readBoolean());if(r>0)for(let e=r;e<8;e++)t.readBits(2);for(let e=0;e<r;e++)v[e]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[e]&&t.readUByte();t.readUEG();const b=t.readUEG();3==b&&t.skipBits(1);const w=t.readUEG(),E=t.readUEG(),S=t.readBoolean();let T=0,x=0,k=0,A=0;S&&(T+=t.readUEG(),x+=t.readUEG(),k+=t.readUEG(),A+=t.readUEG());const R=t.readUEG(),L=t.readUEG(),I=t.readUEG();for(let e=t.readBoolean()?0:r;e<=r;e++)t.skipUEG(),t.skipUEG(),t.skipUEG();t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.readBoolean()){if(t.readBoolean())for(let e=0;e<4;e++)for(let r=0;r<(3===e?2:6);r++){if(t.readBoolean()){const r=Math.min(64,1<<4+(e<<1));e>1&&t.readEG();for(let e=0;e<r;e++)t.readEG()}else t.readUEG()}}t.readBoolean(),t.readBoolean();t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const C=t.readUEG();let P=0;for(let e=0;e<C;e++){let r=!1;if(0!==e&&(r=t.readBoolean()),r){e===C&&t.readUEG(),t.readBoolean(),t.readUEG();let r=0;for(let e=0;e<=P;e++){const e=t.readBoolean();let n=!1;e||(n=t.readBoolean()),(e||n)&&r++}P=r}else{const e=t.readUEG(),r=t.readUEG();P=e+r;for(let r=0;r<e;r++)t.readUEG(),t.readBoolean();for(let e=0;e<r;e++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const e=t.readUEG();for(let r=0;r<e;r++){for(let e=0;e<I+4;e++)t.readBits(1);t.readBits(1)}}let D=0,_=1,M=1,O=!0,N=1,F=0;t.readBoolean(),t.readBoolean();let $=!1;if(t.readBoolean()){if(t.readBoolean()){const e=t.readUByte();e>0&&e<16?(_=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],M=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):255===e&&(_=t.readBits(16),M=t.readBits(16))}t.readBoolean()&&t.readBoolean();if(t.readBoolean()){t.readBits(3),t.readBoolean();t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())}t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),$=t.readBoolean(),$&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG());if(t.readBoolean()){N=t.readBits(32),F=t.readBits(32);t.readBoolean()&&t.readUEG();if(t.readBoolean()){const e=t.readBoolean(),n=t.readBoolean();let i=!1;(e||n)&&(i=t.readBoolean(),i&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),i&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let s=0;s<=r;s++){O=t.readBoolean();let r=!1;O||t.readBoolean()?t.readEG():r=t.readBoolean();const s=r?1:t.readUEG()+1;if(e)for(let e=0;e<s;e++)t.readUEG(),t.readUEG(),i&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(n)for(let e=0;e<s;e++)t.readUEG(),t.readUEG(),i&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),D=t.readUEG())}let B=w,U=E;if(S){let e=1,t=1;1===b?e=t=2:2==b&&(e=2),B=w-e*x-e*T,U=E-t*A-t*k}const z=n?["A","B","C"][n]:"",j=a<<24|o<<16|l<<8|u;let G=0;for(let e=0;e<32;e++)G=(G|(j>>e&1)<<31-e)>>>0;let H=G.toString(16);1===s&&"2"===H&&(H="6");return{codecString:`hvc1.${z}${s}.${H}.${i?"H":"L"}${m}.B0`,params:{general_tier_flag:i,general_profile_idc:s,general_profile_space:n,general_profile_compatibility_flags:[a,o,l,u],general_constraint_indicator_flags:[c,d,h,f,p,g],general_level_idc:m,bit_depth:R+8,bit_depth_luma_minus8:R,bit_depth_chroma_minus8:L,min_spatial_segmentation_idc:D,chroma_format_idc:b,frame_rate:{fixed:O,fps:F/N}},width:B,height:U,pixelRatio:[_,M]}}readPPS(e){const t=new tv(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2);t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const r=t.readBoolean(),n=t.readBoolean();let i=1;return n&&r?i=0:n?i=3:r&&(i=2),{parallelismType:i}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const iv=188;class sv{constructor(e,t,r,n){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=t,this.typeSupported=r,this.logger=n,this.videoParser=null}static probe(e,t){const r=sv.syncOffset(e);return r>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${r}`),-1!==r}static syncOffset(e){const t=e.length;let r=Math.min(940,t-iv)+1,n=0;for(;n<r;){let i=!1,s=-1,a=0;for(let o=n;o<t;o+=iv){if(71!==e[o]||t-o!==iv&&71!==e[o+iv]){if(a)return-1;break}if(a++,-1===s&&(s=o,0!==s&&(r=Math.min(s+18612,e.length-iv)+1)),i||(i=0===av(e,o)),i&&a>1&&(0===s&&a>2||o+iv>r))return s}n++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:Th[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,r,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=sv.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=sv.createTrack("audio",n),this._id3Track=sv.createTrack("id3"),this._txtTrack=sv.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:r}=this;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,r=!1,n=!1){let i;r||(this.sampleAes=null);const s=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let u=s.pid,c=s.pesData,d=a.pid,h=o.pid,f=a.pesData,p=o.pesData,g=null,m=this.pmtParsed,v=this._pmtId,y=e.length;if(this.remainderData&&(y=(e=Bh(this.remainderData,e)).length,this.remainderData=null),y<iv&&!n)return this.remainderData=e,{audioTrack:a,videoTrack:s,id3Track:o,textTrack:l};const b=Math.max(0,sv.syncOffset(e));y-=(y-b)%iv,y<e.byteLength&&!n&&(this.remainderData=new Uint8Array(e.buffer,y,e.buffer.byteLength-y));let w=0;for(let t=b;t<y;t+=iv)if(71===e[t]){const n=!!(64&e[t+1]),y=av(e,t);let w;if((48&e[t+3])>>4>1){if(w=t+5+e[t+4],w===t+iv)continue}else w=t+4;switch(y){case u:n&&(c&&(i=dv(c,this.logger))&&(this.readyVideoParser(s.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(s,l,i,!1)),c={data:[],size:0}),c&&(c.data.push(e.subarray(w,t+iv)),c.size+=t+iv-w);break;case d:if(n){if(f&&(i=dv(f,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,i);break;case"mp3":this.parseMPEGPES(a,i);break;case"ac3":this.parseAC3PES(a,i)}f={data:[],size:0}}f&&(f.data.push(e.subarray(w,t+iv)),f.size+=t+iv-w);break;case h:n&&(p&&(i=dv(p,this.logger))&&this.parseID3PES(o,i),p={data:[],size:0}),p&&(p.data.push(e.subarray(w,t+iv)),p.size+=t+iv-w);break;case 0:n&&(w+=e[w]+1),v=this._pmtId=ov(e,w);break;case v:{n&&(w+=e[w]+1);const i=lv(e,w,this.typeSupported,r,this.observer,this.logger);u=i.videoPid,u>0&&(s.pid=u,s.segmentCodec=i.segmentVideoCodec),d=i.audioPid,d>0&&(a.pid=d,a.segmentCodec=i.segmentAudioCodec),h=i.id3Pid,h>0&&(o.pid=h),null===g||m||(this.logger.warn(`MPEG-TS PMT found at ${t} after unknown PID '${g}'. Backtracking to sync byte @${b} to parse all TS packets.`),g=null,t=b-188),m=this.pmtParsed=!0;break}case 17:case 8191:break;default:g=y}}else w++;w>0&&uv(this.observer,new Error(`Found ${w} TS packet/s that do not start with 0x47`),void 0,this.logger),s.pesData=c,a.pesData=f,o.pesData=p;const E={audioTrack:a,videoTrack:s,id3Track:o,textTrack:l};return n&&this.extractRemainingSamples(E),E}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:r,id3Track:n,textTrack:i}=e,s=r.pesData,a=t.pesData,o=n.pesData;let l;if(s&&(l=dv(s,this.logger))?(this.readyVideoParser(r.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(r,i,l,!0),r.pesData=null)):r.pesData=s,a&&(l=dv(a,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l)}t.pesData=null}else null!=a&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;o&&(l=dv(o,this.logger))?(this.parseID3PES(n,l),n.pesData=null):n.pesData=o}demuxSampleAes(e,t,r){const n=this.demux(e,r,!0,!this.config.progressive),i=this.sampleAes=new Jm(this.observer,this.config,t);return this.decrypt(n,i)}readyVideoParser(e){null===this.videoParser&&("avc"===e?this.videoParser=new rv:"hevc"===e&&(this.videoParser=new nv))}decrypt(e,t){return new Promise(r=>{const{audioTrack:n,videoTrack:i}=e;n.samples&&"aac"===n.segmentCodec?t.decryptAacSamples(n.samples,0,()=>{i.samples?t.decryptAvcSamples(i.samples,0,0,()=>{r(e)}):r(e)}):i.samples&&t.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,t){let r=0;const n=this.aacOverFlow;let i,s,a,o=t.data;if(n){this.aacOverFlow=null;const t=n.missing,i=n.sample.unit.byteLength;if(-1===t)o=Bh(n.sample.unit,o);else{const s=i-t;n.sample.unit.set(o.subarray(0,t),s),e.samples.push(n.sample),r=n.missing}}for(i=r,s=o.length;i<s-1&&!wm(o,i);i++);if(i!==r){let e;const t=i<s-1;if(e=t?`AAC PES did not start with ADTS header,offset:${i}`:"No ADTS header found in AAC PES",uv(this.observer,new Error(e),t,this.logger),!t)return}if(Sm(e,this.observer,o,i,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!n)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=Tm(e.samplerate);a=n.sample.pts+t}}let l,u=0;for(;i<s;){if(l=xm(e,o,i,a,u),i+=l.length,l.missing){this.aacOverFlow=l;break}for(u++;i<s-1&&!wm(o,i);i++);}}parseMPEGPES(e,t){const r=t.data,n=r.length;let i=0,s=0;const a=t.pts;if(void 0!==a)for(;s<n;)if(Wm(r,s)){const t=Gm(e,r,s,a,i);if(!t)break;s+=t.length,i++}else s++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(e,t){{const r=t.data,n=t.pts;if(void 0===n)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const i=r.length;let s,a=0,o=0;for(;o<i&&(s=Xm(e,r,o,n,a++))>0;)o+=s}}parseID3PES(e,t){if(void 0===t.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const r=jd({},t,{type:this._videoTrack?Mm.emsg:Mm.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}}function av(e,t){return((31&e[t+1])<<8)+e[t+2]}function ov(e,t){return(31&e[t+10])<<8|e[t+11]}function lv(e,t,r,n,i,s){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<o;){const o=av(e,t),l=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!n){cv("ADTS AAC",s);break}case 15:-1===a.audioPid&&(a.audioPid=o);break;case 21:-1===a.id3Pid&&(a.id3Pid=o);break;case 219:if(!n){cv("H.264",s);break}case 27:-1===a.videoPid&&(a.videoPid=o);break;case 3:case 4:r.mpeg||r.mp3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="mp3"):s.log("MPEG audio found, not supported in this browser");break;case 193:if(!n){cv("AC-3",s);break}case 129:r.ac3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="ac3"):s.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===a.audioPid&&l>0){let n=t+5,i=l;for(;i>2;){if(106===e[n])!0!==r.ac3?s.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=o,a.segmentAudioCodec="ac3");const t=e[n+1]+2;n+=t,i-=t}}break;case 194:case 135:return uv(i,new Error("Unsupported EC-3 in M2TS found"),void 0,s),a;case 36:-1===a.videoPid&&(a.videoPid=o,a.segmentVideoCodec="hevc",s.log("HEVC in M2TS found"))}t+=l+5}return a}function uv(e,t,r,n){n.warn(`parsing error: ${t.message}`),e.emit(Pd.ERROR,Pd.ERROR,{type:Id.MEDIA_ERROR,details:Cd.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:t,reason:t.message})}function cv(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function dv(e,t){let r,n,i,s,a,o=0;const l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=Bh(l[0],l[1]),l.splice(1,1);r=l[0];if(1===(r[0]<<16)+(r[1]<<8)+r[2]){if(n=(r[4]<<8)+r[5],n&&n>e.size-6)return null;const u=r[7];192&u&&(s=536870912*(14&r[9])+4194304*(255&r[10])+16384*(254&r[11])+128*(255&r[12])+(254&r[13])/2,64&u?(a=536870912*(14&r[14])+4194304*(255&r[15])+16384*(254&r[16])+128*(255&r[17])+(254&r[18])/2,s-a>54e5&&(t.warn(`${Math.round((s-a)/9e4)}s delta between PTS and DTS, align them`),s=a)):a=s),i=r[8];let c=i+9;if(e.size<=c)return null;e.size-=c;const d=new Uint8Array(e.size);for(let e=0,t=l.length;e<t;e++){r=l[e];let t=r.byteLength;if(c){if(c>t){c-=t;continue}r=r.subarray(c),t-=c,c=0}d.set(r,o),o+=t}return n&&(n-=i+3),{data:d,pts:s,dts:a,len:n}}return null}class hv{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)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(6===t)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(1===t)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(2===t)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(3===t)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])}}}const fv=Math.pow(2,32)-1;class pv{static init(){let e;for(e in pv.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:[]},pv.types)pv.types.hasOwnProperty(e)&&(pv.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=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]);pv.HDLR_TYPES={video:t,audio:r};const n=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]);pv.STTS=pv.STSC=pv.STCO=i,pv.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),pv.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),pv.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),pv.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const s=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);pv.FTYP=pv.box(pv.types.ftyp,s,o,s,a),pv.DINF=pv.box(pv.types.dinf,pv.box(pv.types.dref,n))}static box(e,...t){let r=8,n=t.length;const i=n;for(;n--;)r+=t[n].byteLength;const s=new Uint8Array(r);for(s[0]=r>>24&255,s[1]=r>>16&255,s[2]=r>>8&255,s[3]=255&r,s.set(e,4),n=0,r=8;n<i;n++)s.set(t[n],r),r+=t[n].byteLength;return s}static hdlr(e){return pv.box(pv.types.hdlr,pv.HDLR_TYPES[e])}static mdat(e){return pv.box(pv.types.mdat,e)}static mdhd(e,t){t*=e;const r=Math.floor(t/(fv+1)),n=Math.floor(t%(fv+1));return pv.box(pv.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,255&e,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))}static mdia(e){return pv.box(pv.types.mdia,pv.mdhd(e.timescale||0,e.duration||0),pv.hdlr(e.type),pv.minf(e))}static mfhd(e){return pv.box(pv.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?pv.box(pv.types.minf,pv.box(pv.types.smhd,pv.SMHD),pv.DINF,pv.stbl(e)):pv.box(pv.types.minf,pv.box(pv.types.vmhd,pv.VMHD),pv.DINF,pv.stbl(e))}static moof(e,t,r){return pv.box(pv.types.moof,pv.mfhd(e),pv.traf(r,t))}static moov(e){let t=e.length;const r=[];for(;t--;)r[t]=pv.trak(e[t]);return pv.box.apply(null,[pv.types.moov,pv.mvhd(e[0].timescale||0,e[0].duration||0)].concat(r).concat(pv.mvex(e)))}static mvex(e){let t=e.length;const r=[];for(;t--;)r[t]=pv.trex(e[t]);return pv.box.apply(null,[pv.types.mvex,...r])}static mvhd(e,t){t*=e;const r=Math.floor(t/(fv+1)),n=Math.floor(t%(fv+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,255&e,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n,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 pv.box(pv.types.mvhd,i)}static sdtp(e){const t=e.samples||[],r=new Uint8Array(4+t.length);let n,i;for(n=0;n<t.length;n++)i=t[n].flags,r[n+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return pv.box(pv.types.sdtp,r)}static stbl(e){return pv.box(pv.types.stbl,pv.stsd(e),pv.box(pv.types.stts,pv.STTS),pv.box(pv.types.stsc,pv.STSC),pv.box(pv.types.stsz,pv.STSZ),pv.box(pv.types.stco,pv.STCO))}static avc1(e){let t,r,n,i=[],s=[];for(t=0;t<e.sps.length;t++)r=e.sps[t],n=r.byteLength,i.push(n>>>8&255),i.push(255&n),i=i.concat(Array.prototype.slice.call(r));for(t=0;t<e.pps.length;t++)r=e.pps[t],n=r.byteLength,s.push(n>>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(r));const a=pv.box(pv.types.avcC,new Uint8Array([1,i[3],i[4],i[5],255,224|e.sps.length].concat(i).concat([e.pps.length]).concat(s))),o=e.width,l=e.height,u=e.pixelRatio[0],c=e.pixelRatio[1];return pv.box(pv.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,o>>8&255,255&o,l>>8&255,255&l,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]),a,pv.box(pv.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),pv.box(pv.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,255&u,c>>24,c>>16&255,c>>8&255,255&c])))}static esds(e){const t=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,...t,6,1,2])}static audioStsd(e){const t=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,t>>8&255,255&t,0,0])}static mp4a(e){return pv.box(pv.types.mp4a,pv.audioStsd(e),pv.box(pv.types.esds,pv.esds(e)))}static mp3(e){return pv.box(pv.types[".mp3"],pv.audioStsd(e))}static ac3(e){return pv.box(pv.types["ac-3"],pv.audioStsd(e),pv.box(pv.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if("audio"===e.type){if("aac"===t)return pv.box(pv.types.stsd,pv.STSD,pv.mp4a(e));if("ac3"===t&&e.config)return pv.box(pv.types.stsd,pv.STSD,pv.ac3(e));if("mp3"===t&&"mp3"===e.codec)return pv.box(pv.types.stsd,pv.STSD,pv.mp3(e))}else{if(!e.pps||!e.sps)throw new Error("video track missing pps or sps");if("avc"===t)return pv.box(pv.types.stsd,pv.STSD,pv.avc1(e));if("hevc"===t&&e.vps)return pv.box(pv.types.stsd,pv.STSD,pv.hvc1(e))}throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,r=(e.duration||0)*(e.timescale||0),n=e.width||0,i=e.height||0,s=Math.floor(r/(fv+1)),a=Math.floor(r%(fv+1));return pv.box(pv.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,a>>24,a>>16&255,a>>8&255,255&a,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,n>>8&255,255&n,0,0,i>>8&255,255&i,0,0]))}static traf(e,t){const r=pv.sdtp(e),n=e.id,i=Math.floor(t/(fv+1)),s=Math.floor(t%(fv+1));return pv.box(pv.types.traf,pv.box(pv.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),pv.box(pv.types.tfdt,new Uint8Array([1,0,0,0,i>>24,i>>16&255,i>>8&255,255&i,s>>24,s>>16&255,s>>8&255,255&s])),pv.trun(e,r.length+16+20+8+16+8+8),r)}static trak(e){return e.duration=e.duration||4294967295,pv.box(pv.types.trak,pv.tkhd(e),pv.mdia(e))}static trex(e){const t=e.id;return pv.box(pv.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const r=e.samples||[],n=r.length,i=12+16*n,s=new Uint8Array(i);let a,o,l,u,c,d;for(t+=8+i,s.set(["video"===e.type?1:0,0,15,1,n>>>24&255,n>>>16&255,n>>>8&255,255&n,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),a=0;a<n;a++)o=r[a],l=o.duration,u=o.size,c=o.flags,d=o.cts,s.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,u>>>24&255,u>>>16&255,u>>>8&255,255&u,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,61440&c.degradPrio,15&c.degradPrio,d>>>24&255,d>>>16&255,d>>>8&255,255&d],12+16*a);return pv.box(pv.types.trun,s)}static initSegment(e){pv.types||pv.init();const t=pv.moov(e);return Bh(pv.FTYP,t)}static hvc1(e){const t=e.params,r=[e.vps,e.sps,e.pps],n=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),3|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),r.length]);let i=n.length;for(let e=0;e<r.length;e+=1){i+=3;for(let t=0;t<r[e].length;t+=1)i+=2+r[e][t].length}const s=new Uint8Array(i);s.set(n,0),i=n.length;const a=r.length-1;for(let e=0;e<r.length;e+=1){s.set(new Uint8Array([32+e|(e===a?128:0),0,r[e].length]),i),i+=3;for(let t=0;t<r[e].length;t+=1)s.set(new Uint8Array([r[e][t].length>>8,255&r[e][t].length]),i),i+=2,s.set(r[e][t],i),i+=r[e][t].length}const o=pv.box(pv.types.hvcC,s),l=e.width,u=e.height,c=e.pixelRatio[0],d=e.pixelRatio[1];return pv.box(pv.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,l>>8&255,255&l,u>>8&255,255&u,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,pv.box(pv.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),pv.box(pv.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,d>>24,d>>16&255,d>>8&255,255&d])))}}pv.types=void 0,pv.HDLR_TYPES=void 0,pv.STTS=void 0,pv.STSC=void 0,pv.STCO=void 0,pv.STSZ=void 0,pv.VMHD=void 0,pv.SMHD=void 0,pv.STSD=void 0,pv.FTYP=void 0,pv.DINF=void 0;function gv(e,t,r=1,n=!1){const i=e*t*r;return n?Math.round(i):i}function mv(e,t=!1){return gv(e,1e3,1/9e4,t)}function vv(e){const{baseTime:t,timescale:r,trackId:n}=e;return`${t/r} (${t}/${r}) trackId: ${n}`}let yv,bv=null,wv=null;function Ev(e,t,r,n){return{duration:t,size:r,cts:n,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class Sv extends Vd{constructor(e,t,r,n){if(super("mp4-remuxer",n),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=t,this.typeSupported=r,this.ISGenerated=!1,null===bv){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);bv=e?parseInt(e[1]):0}if(null===wv){const e=navigator.userAgent.match(/Safari\/(\d+)/i);wv=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;t&&e&&e.trackId===t.trackId&&e.baseTime===t.baseTime&&e.timescale===t.timescale||this.log(`Reset initPTS: ${t?vv(t):t} > ${e?vv(e):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 t=!1;const r=e[0].pts,n=e.reduce((e,n)=>{let i=n.pts,s=i-e;return s<-4294967296&&(t=!0,i=Tv(i,r),s=i-e),s>0?e:i},r);return t&&this.debug("PTS rollover detected"),n}remux(e,t,r,n,i,s,a,o){let l,u,c,d,h,f,p=i,g=i;const m=e.pid>-1,v=t.pid>-1,y=t.samples.length,b=e.samples.length>0,w=a&&y>0||y>1;if((!m||b)&&(!v||w)||this.ISGenerated||a){if(this.ISGenerated){var E,S,T,x;const e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||(null==(E=t.pixelRatio)?void 0:E[0])!==(null==(S=e.pixelRatio)?void 0:S[0])||(null==(T=t.pixelRatio)?void 0:T[1])!==(null==(x=e.pixelRatio)?void 0:x[1]))||!e&&w||null===this.nextAudioTs&&b)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,i,s));const r=this.isVideoContiguous;let n,a=-1;if(w&&(a=function(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!r&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){this.warn(`Dropped ${a} out of ${y} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,g+=(t.samples[0].pts-e)/t.inputTimeScale,n=g}else-1===a&&(this.warn(`No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(b&&w){const r=this.getVideoStartPts(t.samples),n=(Tv(e.samples[0].pts,r)-r)/t.inputTimeScale;p+=Math.max(0,n),g+=Math.max(0,-n)}if(b){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(e,t,i,s)),u=this.remuxAudio(e,p,this.isAudioContiguous,s,v||w||o===Fd?g:void 0),w){const n=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(e,t,i,s)),l=this.remuxVideo(t,g,r,n)}}else w&&(l=this.remuxVideo(t,g,r,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=n)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(h=xv(r,i,this._initPTS,this._initDTS)),n.samples.length&&(d=kv(n,i,this._initPTS))),{audio:u,video:l,initSegment:c,independent:f,text:d,id3:h}}computeInitPts(e,t,r,n){const i=Math.round(r*t);let s=Tv(e,i);if(s<i+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(i-s)/t} ${n}`);s<i+t;)s+=8589934592;return s-i}generateIS(e,t,r,n){const i=e.samples,s=t.samples,a=this.typeSupported,o={},l=this._initPTS;let u,c,d,h=!l||n,f="audio/mp4",p=-1;if(h&&(u=c=1/0),e.config&&i.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):pv.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(p=e.id,d=e.inputTimeScale,l&&d===l.timescale?h=!1:u=c=this.computeInitPts(i[0].pts,d,r,"audio"))}if(t.sps&&t.pps&&s.length){if(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:pv.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(p=t.id,d=t.inputTimeScale,l&&d===l.timescale)h=!1;else{const e=this.getVideoStartPts(s),t=Tv(s[0].dts,e),n=this.computeInitPts(t,d,r,"video"),i=this.computeInitPts(e,d,r,"video");c=Math.min(c,n),u=Math.min(u,i)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,h?(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${u/d} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${u/d} (${u}/${d}) trackId: ${p}`),this._initPTS={baseTime:u,timescale:d,trackId:p},this._initDTS={baseTime:c,timescale:d,trackId:p}):u=d=void 0,{tracks:o,initPTS:u,timescale:d,trackId:p}}remuxVideo(e,t,r,n){const i=e.inputTimeScale,s=e.samples,a=[],o=s.length,l=this._initPTS,u=l.baseTime*i/l.timescale;let c,d,h=this.nextVideoTs,f=8,p=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,v=!1;if(!r||null===h){const e=u+t*i,n=s[0].pts-Tv(s[0].dts,s[0].pts);bv&&null!==h&&Math.abs(e-n-(h+u))<15e3?r=!0:h=e-n-u}const y=h+u;for(let e=0;e<o;e++){const t=s[e];t.pts=Tv(t.pts,y),t.dts=Tv(t.dts,y),t.dts<s[e>0?e-1:e].dts&&(v=!0)}v&&s.sort(function(e,t){const r=e.dts-t.dts,n=e.pts-t.pts;return r||n}),c=s[0].dts,d=s[s.length-1].dts;const b=d-c,w=b?Math.round(b/(o-1)):p||e.inputTimeScale/30;if(r){const r=c-y,n=r>w,i=r<-1;if((n||i)&&(n?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${mv(r,!0)} ms (${r}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${mv(-r,!0)} ms (${r}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!i||y>=s[0].pts||bv)){c=y;const e=s[0].pts-r;if(n)s[0].dts=c,s[0].pts=e;else{let t=!0;for(let n=0;n<s.length&&!(s[n].dts>e&&t);n++){const e=s[n].pts;if(s[n].dts-=r,s[n].pts-=r,n<s.length-1){const r=s[n+1].pts;t=r<=s[n].pts==r<=e}}}this.log(`Video: Initial PTS/DTS adjusted: ${mv(e,!0)}/${mv(c,!0)}, delta: ${mv(r,!0)} ms`)}}c=Math.max(0,c);let E=0,S=0,T=c;for(let e=0;e<o;e++){const t=s[e],r=t.units,n=r.length;let i=0;for(let e=0;e<n;e++)i+=r[e].data.length;S+=i,E+=n,t.length=i,t.dts<T?(t.dts=T,T+=w/4|0||1):T=t.dts,g=Math.min(t.pts,g),m=Math.max(t.pts,m)}d=s[o-1].dts;const x=S+4*E+8;let k;try{k=new Uint8Array(x)}catch(e){return void this.observer.emit(Pd.ERROR,Pd.ERROR,{type:Id.MUX_ERROR,details:Cd.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:x,reason:`fail allocating video mdat ${x}`})}const A=new DataView(k.buffer);A.setUint32(0,x),k.set(pv.types.mdat,4);let R=!1,L=Number.POSITIVE_INFINITY,I=Number.POSITIVE_INFINITY,C=Number.NEGATIVE_INFINITY,P=Number.NEGATIVE_INFINITY;for(let e=0;e<o;e++){const t=s[e],r=t.units;let l,c=0;for(let e=0,t=r.length;e<t;e++){const t=r[e],n=t.data,i=t.data.byteLength;A.setUint32(f,i),f+=4,k.set(n,f),f+=i,c+=4+i}if(e<o-1)p=s[e+1].dts-t.dts,l=s[e+1].pts-t.pts;else{const r=this.config,a=e>0?t.dts-s[e-1].dts:w;if(l=e>0?t.pts-s[e-1].pts:w,r.stretchShortVideoTrack&&null!==this.nextAudioTs){const e=Math.floor(r.maxBufferHole*i),s=(n?g+n*i:this.nextAudioTs+u)-t.pts;s>e?(p=s-a,p<0?p=a:R=!0,this.log(`It is approximately ${s/90} ms to the next segment; using duration ${p/90} ms for the last video frame.`)):p=a}else p=a}const d=Math.round(t.pts-t.dts);L=Math.min(L,p),C=Math.max(C,p),I=Math.min(I,l),P=Math.max(P,l),a.push(Ev(t.key,p,c,d))}if(a.length)if(bv){if(bv<70){const e=a[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(wv&&P-I<C-L&&w/C<.025&&0===a[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=c;for(let t=0,r=a.length;t<r;t++){const n=e+a[t].duration,i=e+a[t].cts;if(t<r-1){const e=n+a[t+1].cts;a[t].duration=e-i}else a[t].duration=t?a[t-1].duration:w;a[t].cts=0,e=n}}p=R||!p?w:p;const D=d+p;this.nextVideoTs=h=D-u,this.videoSampleDuration=p,this.isVideoContiguous=!0;const _={data1:pv.moof(e.sequenceNumber++,c,jd(e,{samples:a})),data2:k,startPTS:(g-u)/i,endPTS:(m+p-u)/i,startDTS:(c-u)/i,endDTS:h/i,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,_}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(e,t,r,n,i){const s=e.inputTimeScale,a=s/(e.samplerate?e.samplerate:s),o=this.getSamplesPerFrame(e),l=o*a,u=this._initPTS,c="mp3"===e.segmentCodec&&this.typeSupported.mpeg,d=[],h=void 0!==i;let f=e.samples,p=c?0:8,g=this.nextAudioTs||-1;const m=u.baseTime*s/u.timescale,v=m+t*s;if(this.isAudioContiguous=r=r||f.length&&g>0&&(n&&Math.abs(v-(g+m))<9e3||Math.abs(Tv(f[0].pts,v)-(g+m))<20*l),f.forEach(function(e){e.pts=Tv(e.pts,v)}),!r||g<0){const e=f.length;if(f=f.filter(e=>e.pts>=0),e!==f.length&&this.warn(`Removed ${f.length-e} of ${e} samples (initPTS ${m} / ${s})`),!f.length)return;g=0===i?0:n&&!h?Math.max(0,v-m):f[0].pts-m}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let r=0,n=g+m;r<f.length;r++){const i=f[r],a=i.pts,o=a-n,u=Math.abs(1e3*o/s);if(o<=-t*l&&h)0===r&&(this.warn(`Audio frame @ ${(a/s).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/s)} ms.`),this.nextAudioTs=g=a-m,n=a);else if(o>=t*l&&u<1e4&&h){let t=Math.round(o/l);for(n=a-t*l;n<0&&t&&l;)t--,n+=l;0===r&&(this.nextAudioTs=g=n-m),this.warn(`Injecting ${t} audio frames @ ${((n-m)/s).toFixed(3)}s due to ${Math.round(1e3*o/s)} ms gap.`);for(let s=0;s<t;s++){let t=hv.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);t||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),t=i.unit.subarray()),f.splice(r,0,{unit:t,pts:n}),n+=l,r++}}i.pts=n,n+=l}}let y,b=null,w=null,E=0,S=f.length;for(;S--;)E+=f[S].unit.byteLength;for(let t=0,n=f.length;t<n;t++){const n=f[t],i=n.unit;let s=n.pts;if(null!==w){d[t-1].duration=Math.round((s-w)/a)}else{if(r&&"aac"===e.segmentCodec&&(s=g+m),b=s,!(E>0))return;E+=p;try{y=new Uint8Array(E)}catch(e){return void this.observer.emit(Pd.ERROR,Pd.ERROR,{type:Id.MUX_ERROR,details:Cd.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:E,reason:`fail allocating audio mdat ${E}`})}if(!c){new DataView(y.buffer).setUint32(0,E),y.set(pv.types.mdat,4)}}y.set(i,p);const l=i.byteLength;p+=l,d.push(Ev(!0,o,l,0)),w=s}const T=d.length;if(!T)return;const x=d[d.length-1];g=w-m,this.nextAudioTs=g+a*x.duration;const k=c?new Uint8Array(0):pv.moof(e.sequenceNumber++,b/a,jd({},e,{samples:d}));e.samples=[];const A=(b-m)/s,R=this.nextAudioTs/s,L={data1:k,data2:y,startPTS:A,endPTS:R,startDTS:A,endDTS:R,type:"audio",hasAudio:!0,hasVideo:!1,nb:T};return this.isAudioContiguous=!0,L}}function Tv(e,t){let r;if(null===t)return e;for(r=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=r;return e}function xv(e,t,r,n){const i=e.samples.length;if(!i)return;const s=e.inputTimeScale;for(let a=0;a<i;a++){const i=e.samples[a];i.pts=Tv(i.pts-r.baseTime*s/r.timescale,t*s)/s,i.dts=Tv(i.dts-n.baseTime*s/n.timescale,t*s)/s}const a=e.samples;return e.samples=[],{samples:a}}function kv(e,t,r){const n=e.samples.length;if(!n)return;const i=e.inputTimeScale;for(let s=0;s<n;s++){const n=e.samples[s];n.pts=Tv(n.pts-r.baseTime*i/r.timescale,t*i)/i}e.samples.sort((e,t)=>e.pts-t.pts);const s=e.samples;return e.samples=[],{samples:s}}function Av(e,t,r=!1){return void 0!==(null==e?void 0:e.start)?(e.start+(r?e.duration:0))/e.timescale:t}function Rv(e,t,r){const n=e.codec;if(n&&n.length>4)return n;if(t===fh){if("ec-3"===n||"ac-3"===n||"alac"===n)return n;if("fLaC"===n||"Opus"===n){return nf(n,!1)}return r.warn(`Unhandled audio codec "${n}" in mp4 MAP`),n||"mp4a"}return r.warn(`Unhandled video codec "${n}" in mp4 MAP`),n||"avc1"}try{yv=self.performance.now.bind(self.performance)}catch(e){yv=Date.now}const Lv=[{demux:class{constructor(e,t){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=t}resetTimeStamp(){}resetInitSegment(e,t,r,n){const i=this.videoTrack=Om("video",1),s=this.audioTrack=Om("audio",1),a=this.txtTrack=Om("text",1);if(this.id3Track=Om("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const o=Ph(e);if(o.video){const{id:e,timescale:t,codec:r,supplemental:n}=o.video;i.id=e,i.timescale=a.timescale=t,i.codec=r,i.supplemental=n}if(o.audio){const{id:e,timescale:t,codec:r}=o.audio;s.id=e,s.timescale=t,s.codec=r}a.id=Th.text,i.sampleDuration=0,i.duration=s.duration=n}resetContiguity(){this.remainderData=null}static probe(e){return function(e){const t=e.byteLength;for(let r=0;r<t;){const n=Ah(e,r);if(n>8&&109===e[r+4]&&111===e[r+5]&&111===e[r+6]&&102===e[r+7])return!0;r=n>1?r+n:t}return!1}(e)}demux(e,t){this.timeOffset=t;let r=e;const n=this.videoTrack,i=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=Bh(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},r=Ih(e,["moof"]);if(r.length<2)return t.remainder=e,t;const n=r[r.length-1];return t.valid=e.slice(0,n.byteOffset-8),t.remainder=e.slice(n.byteOffset-8),t}(r);this.remainderData=t.remainder,n.samples=t.valid||new Uint8Array}else n.samples=r;const s=this.extractID3Track(n,t);return i.samples=Uh(t,n),{videoTrack:n,audioTrack:this.audioTrack,id3Track:s,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,r=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(t,this.timeOffset);return r.samples=Uh(e,t),{videoTrack:t,audioTrack:Om(),id3Track:n,textTrack:Om()}}extractID3Track(e,t){const r=this.id3Track;if(e.samples.length){const n=Ih(e.samples,["emsg"]);n&&n.forEach(e=>{const n=function(e){const t=e[0];let r="",n="",i=0,s=0,a=0,o=0,l=0,u=0;if(0===t){for(;"\0"!==xh(e.subarray(u,u+1));)r+=xh(e.subarray(u,u+1)),u+=1;for(r+=xh(e.subarray(u,u+1)),u+=1;"\0"!==xh(e.subarray(u,u+1));)n+=xh(e.subarray(u,u+1)),u+=1;n+=xh(e.subarray(u,u+1)),u+=1,i=Ah(e,12),s=Ah(e,16),o=Ah(e,20),l=Ah(e,24),u=28}else if(1===t){u+=4,i=Ah(e,u),u+=4;const t=Ah(e,u);u+=4;const s=Ah(e,u);for(u+=4,a=2**32*t+s,Rd(a)||(a=Number.MAX_SAFE_INTEGER,Qd.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Ah(e,u),u+=4,l=Ah(e,u),u+=4;"\0"!==xh(e.subarray(u,u+1));)r+=xh(e.subarray(u,u+1)),u+=1;for(r+=xh(e.subarray(u,u+1)),u+=1;"\0"!==xh(e.subarray(u,u+1));)n+=xh(e.subarray(u,u+1)),u+=1;n+=xh(e.subarray(u,u+1)),u+=1}return{schemeIdUri:r,value:n,timeScale:i,presentationTime:a,presentationTimeDelta:s,eventDuration:o,id:l,payload:e.subarray(u,e.byteLength)}}(e);if(Qm.test(n.schemeIdUri)){const e=Zm(n,t);let i=4294967295===n.eventDuration?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;i<=.001&&(i=Number.POSITIVE_INFINITY);const s=n.payload;r.samples.push({data:s,len:s.byteLength,dts:e,pts:e,type:Mm.emsg,duration:i})}else if(this.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const e=Zm(n,t);r.samples.push({data:n.payload,len:n.payload.byteLength,dts:e,pts:e,type:Mm.misbklv,duration:Number.POSITIVE_INFINITY})}})}return r}demuxSampleAes(e,t,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}},remux:class extends Vd{constructor(e,t,r,n){super("passthrough-remuxer",n),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 t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,r,n){this.audioCodec=t,this.videoCodec=r,this.generateInitSegment(e,n),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:r,videoCodec:n}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:i,video:s}=this.initData=Ph(e);if(t)!function(e,t){if(!e||!t)return;const r=t.keyId;r&&t.isCommonEncryption&&Fh(e,(e,t)=>{const n=e.subarray(8,24);n.some(e=>0!==e)||(Qd.log(`[eme] Patching keyId in 'enc${t?"a":"v"}>sinf>>tenc' box: ${th(n)} -> ${th(r)}`),e.set(r,8))})}(e,t);else{const e=i||s;null!=e&&e.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${e.codec}")!`)}i&&(r=Rv(i,fh,this)),s&&(n=Rv(s,ph,this));const a={};i&&s?a.audiovideo={container:"video/mp4",codec:r+","+n,supplemental:s.supplemental,encrypted:s.encrypted,initSegment:e,id:"main"}:i?a.audio={container:"audio/mp4",codec:r,encrypted:i.encrypted,initSegment:e,id:"audio"}:s?a.video={container:"video/mp4",codec:n,supplemental:s.supplemental,encrypted:s.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(e,t,r,n,i,s){var a,o;let{initPTS:l,lastEndTime:u}=this;const c={audio:void 0,video:void 0,text:n,id3:r,initSegment:void 0};Ad(u)||(u=this.lastEndTime=i||0);const d=t.samples;if(!d.length)return c;const h={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(d),f=this.initData),null==(o=f)||!o.length)return this.warn("Failed to generate initSegment."),c;this.emitInitSegment&&(h.tracks=this.initTracks,this.emitInitSegment=!1);const p=function(e,t,r){const n={},i=Ih(e,["moof","traf"]);for(let e=0;e<i.length;e++){const s=i[e],a=Ih(s,["tfhd"])[0],o=Ah(a,4),l=t[o];if(!l)continue;n[o]||(n[o]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const u=n[o],c=Ih(s,["tfdt"])[0];if(c){const e=c[0];let t=Ah(c,4);1===e&&(t===Eh?r.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(t*=Eh+1,t+=Ah(c,8))),Ad(t)&&(!Ad(u.start)||t<u.start)&&(u.start=t)}const d=l.default,h=Ah(a,0)|(null==d?void 0:d.flags);let f=(null==d?void 0:d.duration)||0;8&h&&(f=Ah(a,2&h?12:8));const p=Ih(s,["trun"]);let g=u.start||0,m=0,v=f;for(let e=0;e<p.length;e++){const t=p[e],r=Ah(t,4),n=u.sampleCount;u.sampleCount+=r;const i=1&t[3],s=4&t[3],a=1&t[2],o=2&t[2],l=4&t[2],c=8&t[2];let d=8,h=r;for(i&&(d+=4),s&&r&&(1&t[d+1]||void 0!==u.keyFrameIndex||(u.keyFrameIndex=n),d+=4,a?(v=Ah(t,d),d+=4):v=f,o&&(d+=4),c&&(d+=4),g+=v,m+=v,h--);h--;)a?(v=Ah(t,d),d+=4):v=f,o&&(d+=4),l&&(1&t[d+1]||void 0===u.keyFrameIndex&&(u.keyFrameIndex=u.sampleCount-(h+1),u.keyFrameStart=g),d+=4),c&&(d+=4),g+=v,m+=v;!m&&f&&(m+=f*r)}u.duration+=m}if(!Object.keys(n).some(e=>n[e].duration)){let t=1/0,r=0;const i=Ih(e,["sidx"]);for(let e=0;e<i.length;e++){const n=Ch(i[e]);if(null!=n&&n.references){t=Math.min(t,n.earliestPresentationTime/n.timescale);const e=n.references.reduce((e,t)=>e+t.info.duration||0,0);r=Math.max(r,e+n.earliestPresentationTime/n.timescale)}}r&&Ad(r)&&Object.keys(n).forEach(e=>{n[e].duration||(n[e].duration=r*n[e].timescale-n[e].start)})}return n}(d,f,this),g=f.audio?p[f.audio.id]:null,m=f.video?p[f.video.id]:null,v=Av(m,1/0),y=Av(g,1/0),b=Av(m,0,!0),w=Av(g,0,!0);let E=i,S=0;const T=g&&(!m||!l&&y<v||l&&l.trackId===f.audio.id),x=T?g:m;if(x){const e=x.timescale,t=x.start-i*e,r=T?f.audio.id:f.video.id;E=x.start/e,S=T?w-y:b-v,!s&&l||!function(e,t,r,n){if(null===e)return!0;const i=Math.max(n,1),s=t-e.baseTime/e.timescale;return Math.abs(s-r)>i}(l,E,i,S)&&e===l.timescale||(l&&this.warn(`Timestamps at playlist time: ${s?"":"~"}${i} ${t/e} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${E-i} (${t}/${e}) trackId: ${r}`),l=null,h.initPTS=t,h.timescale=e,h.trackId=r)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${i}`);l?(h.initPTS=l.baseTime,h.timescale=l.timescale,h.trackId=l.trackId):(h.timescale&&void 0!==h.trackId&&void 0!==h.initPTS||(this.warn("Could not set initPTS"),h.initPTS=E,h.timescale=1,h.trackId=-1),this.initPTS=l={baseTime:h.initPTS,timescale:h.timescale,trackId:h.trackId});const k=E-l.baseTime/l.timescale,A=k+S;S>0?this.lastEndTime=A:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const R=!!f.audio,L=!!f.video;let I="";R&&(I+="audio"),L&&(I+="video");const C={data1:d,startPTS:k,startDTS:k,endPTS:A,endDTS:A,type:I,hasAudio:R,hasVideo:L,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};c.audio=R&&!L?C:void 0,c.video=L?C:void 0;const P=null==m?void 0:m.sampleCount;if(P){const e=m.keyFrameIndex,t=-1!==e;C.nb=P,C.dropped=0===e||this.isVideoContiguous?0:t?e:P,C.independent=t,C.firstKeyFrame=e,t&&m.keyFrameStart&&(C.firstKeyFramePTS=(m.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(c.independent=t),this.isVideoContiguous||(this.isVideoContiguous=t),C.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${e}/${P} dropped: ${C.dropped} start: ${C.firstKeyFramePTS||"NA"}`)}return c.initSegment=h,c.id3=xv(r,i,l,l),n.samples.length&&(c.text=kv(n,i,l)),c}}},{demux:sv,remux:Sv},{demux:class extends Nm{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,r,n){super.resetInitSegment(e,t,r,n),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const r=mm(e,0);let n=(null==r?void 0:r.length)||0;if(Km(e,n))return!1;for(let r=e.length;n<r;n++)if(Em(e,n))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&vm(e,t)&&bm(e,t)<=e.length-t}(e,t)}appendFrame(e,t,r){Sm(e,this.observer,t,r,e.manifestCodec);const n=xm(e,t,r,this.basePTS,this.frameIndex);if(n&&0===n.missing)return n}},remux:Sv},{demux:class extends Nm{resetInitSegment(e,t,r,n){super.resetInitSegment(e,t,r,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=mm(e,0);let r=(null==t?void 0:t.length)||0;if(t&&11===e[r]&&119===e[r+1]&&void 0!==_m(t)&&Ym(e,r)<=16)return!1;for(let t=e.length;r<t;r++)if(Km(e,r))return Qd.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return Vm(e,t)&&4<=e.length-t}(e,t)}appendFrame(e,t,r){if(null!==this.basePTS)return Gm(e,t,r,this.basePTS,this.frameIndex)}},remux:Sv}];Lv.splice(2,0,{demux:qm,remux:Sv});class Iv{constructor(e,t,r,n,i,s){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=t,this.config=r,this.id=i,this.logger=s}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,r,n){const i=r.transmuxing;i.executeStart=yv();let s=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:o}=this;n&&(this.currentTransmuxState=n);const{contiguous:l,discontinuity:u,trackSwitch:c,accurateTimeOffset:d,timeOffset:h,initSegmentChange:f}=n||a,{audioCodec:p,videoCodec:g,defaultInitPts:m,duration:v,initSegmentData:y}=o,b=function(e,t){let r=null;e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(r=t);return r}(s,t);if(b&&zp(b.method)){const e=this.getDecrypter(),t=jp(b.method);if(!e.isSync())return this.asyncResult=!0,this.decryptionPromise=e.webCryptoDecrypt(s,b.key.buffer,b.iv.buffer,t).then(e=>{const t=this.push(e,null,r);return this.decryptionPromise=null,t}),this.decryptionPromise;{let n=e.softwareDecrypt(s,b.key.buffer,b.iv.buffer,t);if(r.part>-1){const t=e.flush();n=t?t.buffer:t}if(!n)return i.executeEnd=yv(),Cv(r);s=new Uint8Array(n)}}const w=this.needsProbing(u,c);if(w){const e=this.configureTransmuxer(s);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(Pd.ERROR,Pd.ERROR,{type:Id.MEDIA_ERROR,details:Cd.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),i.executeEnd=yv(),Cv(r)}(u||c||f||w)&&this.resetInitSegment(y,p,g,v,t),(u||f||w)&&this.resetInitialTimestamp(m),l||this.resetContiguity();const E=this.transmux(s,b,h,d,r);this.asyncResult=Pv(E);const S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,i.executeEnd=yv(),E}flush(e){const t=e.transmuxing;t.executeStart=yv();const{decrypter:r,currentTransmuxState:n,decryptionPromise:i}=this;if(i)return this.asyncResult=!0,i.then(()=>this.flush(e));const s=[],{timeOffset:a}=n;if(r){const t=r.flush();t&&s.push(this.push(t.buffer,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l){t.executeEnd=yv();const r=[Cv(e)];return this.asyncResult?Promise.resolve(r):r}const u=o.flush(a);return Pv(u)?(this.asyncResult=!0,u.then(t=>(this.flushRemux(s,t,e),s))):(this.flushRemux(s,u,e),this.asyncResult?Promise.resolve(s):s)}flushRemux(e,t,r){const{audioTrack:n,videoTrack:i,id3Track:s,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${r.sn}${r.part>-1?" part: "+r.part:""} of ${this.id===Nd?"level":"track"} ${r.level}`);const u=this.remuxer.remux(n,i,s,a,l,o,!0,this.id);e.push({remuxResult:u,chunkMeta:r}),r.transmuxing.executeEnd=yv()}resetInitialTimestamp(e){const{demuxer:t,remuxer:r}=this;t&&r&&(t.resetTimeStamp(e),r.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,r,n,i){const{demuxer:s,remuxer:a}=this;s&&a&&(s.resetInitSegment(e,t,r,n),a.resetInitSegment(e,t,r,i))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,r,n,i){let s;return s=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,r,n,i):this.transmuxUnencrypted(e,r,n,i),s}transmuxUnencrypted(e,t,r,n){const{audioTrack:i,videoTrack:s,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(i,s,a,o,t,r,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,r,n,i){return this.demuxer.demuxSampleAes(e,t,r).then(e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,r,n,!1,this.id),chunkMeta:i}))}configureTransmuxer(e){const{config:t,observer:r,typeSupported:n}=this;let i;for(let t=0,r=Lv.length;t<r;t++){var s;if(null!=(s=Lv[t].demux)&&s.probe(e,this.logger)){i=Lv[t];break}}if(!i)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=i.remux,u=i.demux;o&&o instanceof l||(this.remuxer=new l(r,t,n,this.logger)),a&&a instanceof u||(this.demuxer=new u(r,t,n,this.logger),this.probe=u.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new vp(this.config)),e}}const Cv=e=>({remuxResult:{},chunkMeta:e});function Pv(e){return"then"in e&&e.then instanceof Function}class Dv{constructor(e,t,r,n,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=t,this.initSegmentData=r,this.duration=n,this.defaultInitPts=i||null}}class _v{constructor(e,t,r,n,i,s){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=t,this.accurateTimeOffset=r,this.trackSwitch=n,this.timeOffset=i,this.initSegmentChange=s}}let Mv=0;class Ov{constructor(e,t,r,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Mv++,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=e=>{const t=e.data,r=this.hls;if(r&&null!=t&&t.event&&t.instanceNo===this.instanceNo)switch(t.event){case"init":{var n;const e=null==(n=this.workerContext)?void 0:n.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":r.logger[t.data.logType]&&r.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,r.trigger(t.event,t.data)}},this.onWorkerError=e=>{if(!this.hls)return;const t=new Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(Pd.ERROR,{type:Id.OTHER_ERROR,details:Cd.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})};const i=e.config;this.hls=e,this.id=t,this.useWorker=!!i.enableWorker,this.onTransmuxComplete=r,this.onFlush=n;const s=(e,t)=>{(t=t||{}).frag=this.frag||void 0,e===Pd.ERROR&&(t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new cm,this.observer.on(Pd.FRAG_DECRYPTED,s),this.observer.on(Pd.ERROR,s);const a=lf(i.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const r=this.hls.logger;if(i.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{i.workerPath?(r.log(`loading Web Worker ${i.workerPath} for "${t}"`),this.workerContext=function(e){const t=hm[e];if(t)return t.clientCount++,t;const r=new self.URL(e,self.location.href).href,n={worker:new self.Worker(r),scriptURL:r,clientCount:1};return hm[e]=n,n}(i.workerPath)):(r.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){const e=hm[dm];if(e)return e.clientCount++,e;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),r=self.URL.createObjectURL(t),n={worker:new self.Worker(r),objectURL:r,clientCount:1};return hm[dm]=n,n}());const{worker:e}=this.workerContext;e.addEventListener("message",this.onWorkerMessage),e.addEventListener("error",this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:Rf(i)})}catch(n){r.warn(`Error setting up "${t}" Web Worker, fallback to inline`,n),this.terminateWorker(),this.error=null,this.transmuxer=new Iv(this.observer,a,i,"",t,e.logger)}return}}this.transmuxer=new Iv(this.observer,a,i,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Mv++;const t=this.hls.config,r=lf(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:r,id:this.id,config:Rf(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){const t=hm[e||dm];if(t&&1===t.clientCount--){const{worker:r,objectURL:n}=t;delete hm[e||dm],n&&self.URL.revokeObjectURL(n),r.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const e=this.transmuxer;e&&(e.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,t,r,n,i,s,a,o,l,u){var c,d;l.transmuxing.start=self.performance.now();const{instanceNo:h,transmuxer:f}=this,p=s?s.start:i.start,g=i.decryptdata,m=this.frag,v=!(m&&i.cc===m.cc),y=!(m&&l.level===m.level),b=m?l.sn-m.sn:-1,w=this.part?l.part-this.part.index:-1,E=0===b&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),S=!y&&(1===b||0===b&&(1===w||E&&w<=0)),T=self.performance.now();(y||b||0===i.stats.parsing.start)&&(i.stats.parsing.start=T),!s||!w&&S||(s.stats.parsing.start=T);const x=!(m&&(null==(c=i.initSegment)?void 0:c.url)===(null==(d=m.initSegment)?void 0:d.url)),k=new _v(v,S,o,y,p,x);if(!S||v||x){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===Nd?"level":"track"}: ${l.level} id: ${l.id}\n discontinuity: ${v}\n trackSwitch: ${y}\n contiguous: ${S}\n accurateTimeOffset: ${o}\n timeOffset: ${p}\n initSegmentChange: ${x}`);const e=new Dv(r,n,t,a,u);this.configureTransmuxer(e)}if(this.frag=i,this.part=s,this.workerContext)this.workerContext.worker.postMessage({instanceNo:h,cmd:"demux",data:e,decryptdata:g,chunkMeta:l,state:k},e instanceof ArrayBuffer?[e]:[]);else if(f){const t=f.push(e,g,l,k);Pv(t)?t.then(e=>{this.handleTransmuxComplete(e)}).catch(e=>{this.transmuxerError(e,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:r}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(r){const t=r.flush(e);Pv(t)?t.then(t=>{this.handleFlushResult(t,e)}).catch(t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")}):this.handleFlushResult(t,e)}}transmuxerError(e,t,r){this.hls&&(this.error=e,this.hls.trigger(Pd.ERROR,{type:Id.MEDIA_ERROR,details:Cd.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:r}))}handleFlushResult(e,t){e.forEach(e=>{this.handleTransmuxComplete(e)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:r}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):r&&r.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}class Nv extends Vd{constructor(e,t){super(t,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(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,r){const n=null==t?void 0:t.renditionReports;if(n){let i=-1;for(let r=0;r<n.length;r++){const s=n[r];let a;try{a=new self.URL(s.URI,t.url).href}catch(e){this.warn(`Could not construct new URL for Rendition Report: ${e}`),a=s.URI||""}if(a===e){i=r;break}a===e.substring(0,a.length)&&(i=r)}if(-1!==i){const e=n[i],s=parseInt(e["LAST-MSN"])||t.lastPartSn;let a=parseInt(e["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const e=Math.min(t.age-t.partTarget,t.targetduration);a>=0&&e>t.partTarget&&(a+=1)}const o=r&&Sf(r);return new Tf(s,a>=0?a:void 0,o)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}return e}playlistLoaded(e,t,r){const{details:n,stats:i}=t,s=self.performance.now(),a=i.loading.first?Math.max(0,s-i.loading.first):0;n.advancedDateTime=Date.now()-a;const o=this.hls.config.timelineOffset;if(o!==n.appliedTimelineOffset){const e=Math.max(o||0,0);n.appliedTimelineOffset=e,n.fragments.forEach(t=>{t.setStart(t.playlistOffset+e)})}if(n.live||null!=r&&r.live){const o="levelInfo"in t?t.levelInfo:t.track;if(n.reloaded(r),r&&n.fragments.length>0){Rg(r,n,this);const e=n.playlistParsingError;if(e){this.warn(e);const r=this.hls;if(!r.config.ignorePlaylistParsingErrors){var l;const{networkDetails:s}=t;return void r.trigger(Pd.ERROR,{type:Id.NETWORK_ERROR,details:Cd.LEVEL_PARSING_ERROR,fatal:!1,url:n.url,error:e,reason:e.message,level:t.level||void 0,parent:null==(l=n.fragments[0])?void 0:l.type,networkDetails:s,stats:i})}n.playlistParsingError=null}}-1===n.requestScheduled&&(n.requestScheduled=i.loading.start);const u=this.hls.mainForwardBufferInfo,c=u?u.end-u.len:0,d=Pg(n,1e3*(n.edge-c));if(n.requestScheduled+d<s?n.requestScheduled=s:n.requestScheduled+=d,this.log(`live playlist ${e} ${n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:n.updated?"UPDATED":"MISSED"}`),!this.canLoad||!n.live)return;let h,f,p;if(n.canBlockReload&&n.endSN&&n.advanced){const e=this.hls.config.lowLatencyMode,i=n.lastPartSn,a=n.endSN,l=n.lastPartIndex,u=i===a;-1!==l?u?(f=a+1,p=e?0:l):(f=i,p=e?l+1:n.maxPartIndex):f=a+1;const c=n.age,d=c+n.ageHeader;let g=Math.min(d-n.partTarget,1.5*n.targetduration);if(g>0){if(d>3*n.targetduration)this.log(`Playlist last advanced ${c.toFixed(2)}s ago. Omitting segment and part directives.`),f=void 0,p=void 0;else if(null!=r&&r.tuneInGoal&&d-n.partTarget>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${g} with playlist age: ${n.age}`),g=0;else{const e=Math.floor(g/n.targetduration);if(f+=e,void 0!==p){p+=Math.round(g%n.targetduration/n.partTarget)}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${c.toFixed(2)}s goal: ${g} skip sn ${e} to part ${p}`)}n.tuneInGoal=g}if(h=this.getDeliveryDirectives(n,t.deliveryDirectives,f,p),e||!u)return n.requestScheduled=s,void this.loadingPlaylist(o,h)}else(n.canBlockReload||n.canSkipUntil)&&(h=this.getDeliveryDirectives(n,t.deliveryDirectives,f,p));h&&void 0!==f&&n.canBlockReload&&(n.requestScheduled=i.loading.first+Math.max(d-2*a,d/2)),this.scheduleLoading(o,h,n)}else this.clearTimer()}scheduleLoading(e,t,r){const n=r||e.details;if(!n)return void this.loadingPlaylist(e,t);const i=self.performance.now(),s=n.requestScheduled;if(i>=s)return void this.loadingPlaylist(e,t);const a=s-i;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),a)}getDeliveryDirectives(e,t,r,n){let i=Sf(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,n=t.part,i=bf),new Tf(r,n,i)}checkRetry(e){const t=e.details,r=zf(e),n=e.errorAction,{action:i,retryCount:s=0,retryConfig:a}=n||{},o=!!n&&!!a&&(i===Zf||!n.resolved&&i===Xf);if(o){var l;if(s>=a.maxNumRetry)return!1;if(r&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${s+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=Vf(a,s);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),e),this.warn(`Retrying playlist loading ${s+1}/${a.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,n.resolved=!0}return o}}function Fv(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!$v(e[r].attrs,t[r].attrs))return!1;return!0}function $v(e,t,r){const n=e["STABLE-RENDITION-ID"];return n&&!r?n===t["STABLE-RENDITION-ID"]:!(r||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(r=>e[r]!==t[r])}function Bv(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}class Uv{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,r){if(null===this.queues||null===this.tracks)return;const n=this.queues[t];n.push(e),1!==n.length||r||this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const r={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(r,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const r={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(r)}})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const r=null==(t=e[0])?void 0:t.label;"async-blocker"!==r&&"async-blocker-prepend"!==r||(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(null===this.queues)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(null===this.queues||null===this.tracks)return;const t=this.queues[e];if(t.length){const n=t[0];try{n.execute()}catch(t){var r;if(n.onError(t),null===this.queues||null===this.tracks)return;const i=null==(r=this.tracks[e])?void 0:r.buffer;null!=i&&i.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return null===e||null===t?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(e){var t,r;return null!=(t=this.queues)&&t[e]||null!=(r=this.tracks)&&r[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const r=null==(t=this.tracks)?void 0:t[e],n=null==r?void 0:r.buffer;return n?`SourceBuffer${n.updating?" updating":""}${r.ended?" ended":""}${r.ending?" ending":""}`:"none"}listOps(e){var t;return(null==(t=this.queues)?void 0:t[e].map(e=>e.label).join(", "))||""}}const zv=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,jv="HlsJsTrackRemovedError";class Gv extends Error{constructor(e){super(e),this.name=jv}}function Hv(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach(t=>{e.removeChild(t)})}function Vv(e){return"audio"===e?1:0}class Wv{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(Pd.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(Pd.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Pd.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Pd.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Pd.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Pd.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(Pd.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(Pd.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Pd.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Pd.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Pd.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Pd.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const r=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,r.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&Ad(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const e=this.hls.levels;if(e.length){const t=this.hls,r=this.getMaxLevel(e.length-1);r!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${r}: ${e[r].height}p@${e[r].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=r,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const r=t.filter((t,r)=>this.isLevelAllowed(t)&&r<=e);return this.clientRect=null,Wv.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,t={width:0,height:0};if(e){const r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t}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(e){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height)}static getMaxLevelByMediaSize(e,t,r){if(null==e||!e.length)return-1;const n=(e,t)=>!t||(e.width!==t.width||e.height!==t.height);let i=e.length-1;const s=Math.max(t,r);for(let t=0;t<e.length;t+=1){const r=e[t];if((r.width>=s||r.height>=s)&&n(r,e[t+1])){i=t;break}}return i}}const Kv={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Yv={HLS:"h"};class qv{constructor(e,t){Array.isArray(e)&&(e=e.map(e=>e instanceof qv?e:new qv(e))),this.value=e,this.params=t}}function Xv(e,t,r,n){return new Error(`failed to ${e} "${i=t,Array.isArray(i)?JSON.stringify(i):i instanceof Map?"Map{}":i instanceof Set?"Set{}":"object"==typeof i?JSON.stringify(i):String(i)}" as ${r}`,{cause:n});var i}function Qv(e,t,r){return Xv("serialize",e,t,r)}class Zv{constructor(e){this.description=e}}const Jv="Bare Item";function ey(e){if(!1===ArrayBuffer.isView(e))throw Qv(e,"Byte Sequence");return`:${t=e,btoa(String.fromCharCode(...t))}:`;var t}function ty(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw Qv(e,"Integer");return e.toString()}function ry(e,t){if(e<0)return-ry(-e,t);const r=Math.pow(10,t);if(Math.abs(e*r%1-.5)<Number.EPSILON){const t=Math.floor(e*r);return(t%2==0?t:t+1)/r}return Math.round(e*r)/r}function ny(e){const t=ry(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw Qv(e,"Decimal");const r=t.toString();return r.includes(".")?r:`${r}.0`}const iy=/[\x00-\x1f\x7f]+/;function sy(e){const t=(r=e).description||r.toString().slice(7,-1);var r;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw Qv(t,"Token");return t}function ay(e){switch(typeof e){case"number":if(!Ad(e))throw Qv(e,Jv);return Number.isInteger(e)?ty(e):ny(e);case"string":return function(e){if(iy.test(e))throw Qv(e,"String");return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(e);case"symbol":return sy(e);case"boolean":return function(e){if("boolean"!=typeof e)throw Qv(e,"Boolean");return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return`@${ty(e.getTime()/1e3)}`}(e);if(e instanceof Uint8Array)return ey(e);if(e instanceof Zv)return sy(e);default:throw Qv(e,Jv)}}function oy(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw Qv(e,"Key");return e}function ly(e){return null==e?"":Object.entries(e).map(([e,t])=>!0===t?`;${oy(e)}`:`;${oy(e)}=${ay(t)}`).join("")}function uy(e){return e instanceof qv?`${ay(e.value)}${ly(e.params)}`:ay(e)}function cy(e,t={whitespace:!0}){if("object"!=typeof e||null==e)throw Qv(e,"Dict");const r=e instanceof Map?e.entries():Object.entries(e),n=(null==t?void 0:t.whitespace)?" ":"";return Array.from(r).map(([e,t])=>{t instanceof qv==!1&&(t=new qv(t));let r=oy(e);var n;return!0===t.value?r+=ly(t.params):(r+="=",Array.isArray(t.value)?r+=`(${(n=t).value.map(uy).join(" ")})${ly(n.params)}`:r+=uy(t)),r}).join(`,${n}`)}function dy(e,t){return cy(e,t)}const hy="CMCD-Object",fy="CMCD-Request",py="CMCD-Session",gy="CMCD-Status",my={br:hy,ab:hy,d:hy,ot:hy,tb:hy,tpb:hy,lb:hy,tab:hy,lab:hy,url:hy,pb:fy,bl:fy,tbl:fy,dl:fy,ltc:fy,mtp:fy,nor:fy,nrr:fy,rc:fy,sn:fy,sta:fy,su:fy,ttfb:fy,ttfbb:fy,ttlb:fy,cmsdd:fy,cmsds:fy,smrt:fy,df:fy,cs:fy,ts:fy,cid:py,pr:py,sf:py,sid:py,st:py,v:py,msd:py,bs:gy,bsd:gy,cdn:gy,rtp:gy,bg:gy,pt:gy,ec:gy,e:gy},vy=fy;function yy(e,t){const r={};if(!e)return r;const n=Object.keys(e),i=t?(s=t,Object.keys(s).reduce((e,t)=>{var r;return null===(r=s[t])||void 0===r||r.forEach(r=>e[r]=t),e},{})):{};var s;return n.reduce((t,r)=>{var n;const s=my[r]||i[r]||vy;return(null!==(n=t[s])&&void 0!==n?n:t[s]={})[r]=e[r],t},r)}const by="event";const wy=e=>Math.round(e),Ey=(e,t)=>Array.isArray(e)?e.map(e=>Ey(e,t)):e instanceof qv&&"string"==typeof e.value?new qv(Ey(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){const r=new URL(e),n=new URL(t);if(r.origin!==n.origin)return e;const i=r.pathname.split("/").slice(1),s=n.pathname.split("/").slice(1,-1);for(;i[0]===s[0];)i.shift(),s.shift();for(;s.length;)s.shift(),i.unshift("..");return i.join("/")+r.search+r.hash}(e,t.baseUrl)),1===t.version?encodeURIComponent(e):e),Sy=e=>100*wy(e/100),Ty={br:wy,d:wy,bl:Sy,dl:Sy,mtp:Sy,nor:(e,t)=>{let r=e;return t.version>=2&&(e instanceof qv&&"string"==typeof e.value?r=new qv([e]):"string"==typeof e&&(r=[e])),Ey(r,t)},rtp:Sy,tb:wy},xy="request",ky="response",Ay=["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"],Ry=["e"],Ly=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Iy(e){return Ly.test(e)}const Cy=["d","dl","nor","ot","rtp","su"];const Py=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];const Dy=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function _y(e){return Dy.includes(e)||Iy(e)}const My={[ky]:function(e){return Ay.includes(e)||Cy.includes(e)||Py.includes(e)||Iy(e)},[by]:function(e){return Ay.includes(e)||Ry.includes(e)||Iy(e)},[xy]:function(e){return Ay.includes(e)||Cy.includes(e)||Iy(e)}};function Oy(e,t={}){const r={};if(null==e||"object"!=typeof e)return r;const n=t.version||e.v||1,i=t.reportingMode||xy,s=1===n?_y:My[i];let a=Object.keys(e).filter(s);const o=t.filter;"function"==typeof o&&(a=a.filter(o));const l=i===ky||i===by;l&&!a.includes("ts")&&a.push("ts"),n>1&&!a.includes("v")&&a.push("v");const u=jd({},Ty,t.formatters),c={version:n,reportingMode:i,baseUrl:t.baseUrl};return a.sort().forEach(t=>{let i=e[t];const s=u[t];if("function"==typeof s&&(i=s(i,c)),"v"===t){if(1===n)return;i=n}"pr"==t&&1===i||(l&&"ts"===t&&!Ad(i)&&(i=Date.now()),function(e){return"number"==typeof e?Ad(e):null!=e&&""!==e&&!1!==e}(i)&&(function(e){return["ot","sf","st","e","sta"].includes(e)}(t)&&"string"==typeof i&&(i=new Zv(i)),r[t]=i))}),r}function Ny(e,t,r){return jd(e,function(e,t={}){const r={};if(!e)return r;const n=yy(Oy(e,t),null==t?void 0:t.customHeaderMap);return Object.entries(n).reduce((e,[t,r])=>{const n=dy(r,{whitespace:!1});return n&&(e[t]=n),e},r)}(t,r))}function Fy(e,t={}){if(!e)return"";const r=function(e,t={}){return e?dy(Oy(e,t),{whitespace:!1}):""}(e,t);return encodeURIComponent(r)}const $y=/CMCD=[^&#]+/;function By(e,t,r){const n=function(e,t={}){return e?`CMCD=${Fy(e,t)}`:""}(t,r);if(!n)return e;if($y.test(e))return e.replace($y,n);const i=e.includes("?")?"&":"?";return`${e}${i}${n}`}function Uy(e,t,r,n){e&&Object.keys(t).forEach(i=>{const s=e.filter(e=>e.groupId===i).map(e=>{const s=jd({},e);return s.details=void 0,s.attrs=new Mp(s.attrs),s.url=s.attrs.URI=zy(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),s.groupId=s.attrs["GROUP-ID"]=t[i],s.attrs["PATHWAY-ID"]=n,s});e.push(...s)})}function zy(e,t,r,n){const{HOST:i,PARAMS:s,[r]:a}=n;let o;t&&(o=null==a?void 0:a[t],o&&(e=o));const l=new self.URL(e);return i&&!o&&(l.host=i),s&&Object.keys(s).sort().forEach(e=>{e&&l.searchParams.set(e,s[e])}),l.href}class jy extends Vd{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=jy.CDMCleanupPromise?[jy.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=e=>{const{initDataType:t,initData:r}=e,n=`"${e.type}" event: init data type: "${t}"`;if(this.debug(n),null!==r){if(!this.keyFormatPromise){let e=Object.keys(this.keySystemAccessPromises);e.length||(e=tg(this.config));const t=e.map(eg).filter(e=>!!e);this.keyFormatPromise=this.getKeyFormatPromise(t)}this.keyFormatPromise.then(i=>{const s=Jp(i);if("sinf"!==t||s!==Yp.FAIRPLAY)return void this.log(`Ignoring "${e.type}" event with init data type: "${t}" for selected key-system ${s}`);let a;try{const e=xh(new Uint8Array(r)),t=$h(Gp(JSON.parse(e).sinf));if(!t)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(t.subarray(8,24))}catch(e){return void this.warn(`${n} Failed to parse sinf: ${e}`)}const o=th(a),{keyIdToKeySessionPromise:l,mediaKeySessions:u}=this;let c=l[o];for(let e=0;e<u.length;e++){const n=u[e],i=n.decryptdata;if(!i.keyId)continue;const s=th(i.keyId);if(Bp(a,i.keyId)||-1!==i.uri.replace(/-/g,"").indexOf(o)){if(c=l[s],!c)continue;if(i.pssh)break;delete l[s],i.pssh=new Uint8Array(r),i.keyId=a,c=l[o]=c.then(()=>this.generateRequestWithPreferredKeySession(n,t,r,"encrypted-event-key-match")),c.catch(e=>this.handleError(e));break}}c||this.handleError(new Error(`Key ID ${o} not encountered in playlist. Key-system sessions ${u.length}.`))}).catch(e=>this.handleError(e))}},this.onWaitingForKey=e=>{this.log(`"${e.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(Pd.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Pd.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(Pd.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Pd.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(Pd.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(Pd.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Pd.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(Pd.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Pd.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(Pd.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:r}=this.config,n=null==t?void 0:t[e];return n?n.licenseUrl:e===Yp.WIDEVINE&&r?r:void 0}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(void 0===t)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,r=null==t?void 0:t[e];if(r)return r.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,r=(e,t,r)=>!!e&&r.indexOf(e)===t,n=t.map(e=>e.audioCodec).filter(r),i=t.map(e=>e.videoCodec).filter(r);return n.length+i.length===0&&i.push("avc1.42e01e"),new Promise((t,r)=>{const s=e=>{const a=e.shift();this.getMediaKeysPromise(a,n,i).then(e=>t({keySystem:a,mediaKeys:e})).catch(t=>{e.length?s(e):r(t instanceof Vy?t:new Vy({type:Id.KEY_SYSTEM_ERROR,details:Cd.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};s(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:r}=this.config;if("function"!=typeof r){let e=`Configured requestMediaKeySystemAccess is not a function ${r}`;return null===rg&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(e))}return r(e,t)}getMediaKeysPromise(e,t,r){var n;const i=function(e,t,r,n){let i;switch(e){case Yp.FAIRPLAY:i=["cenc","sinf"];break;case Yp.WIDEVINE:case Yp.PLAYREADY:i=["cenc"];break;case Yp.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return function(e,t,r,n){return[{initDataTypes:e,persistentState:n.persistentState||"optional",distinctiveIdentifier:n.distinctiveIdentifier||"optional",sessionTypes:n.sessionTypes||[n.sessionType||"temporary"],audioCapabilities:t.map(e=>({contentType:`audio/mp4; codecs=${e}`,robustness:n.audioRobustness||"",encryptionScheme:n.audioEncryptionScheme||null})),videoCapabilities:r.map(e=>({contentType:`video/mp4; codecs=${e}`,robustness:n.videoRobustness||"",encryptionScheme:n.videoEncryptionScheme||null}))}]}(i,t,r,n)}(e,t,r,this.config.drmSystemOptions||{});let s=this.keySystemAccessPromises[e],a=null==(n=s)?void 0:n.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${Rf(i)}`),a=this.requestMediaKeySystemAccess(e,i);const t=s=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)}),a.then(r=>{this.log(`Access for key-system "${r.keySystem}" obtained`);const n=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const i=t.mediaKeys=r.createMediaKeys().then(r=>(this.log(`Media-keys created for "${e}"`),t.hasMediaKeys=!0,n.then(t=>t?this.setMediaKeysServerCertificate(r,e,t):r)));return i.catch(t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)}),i})}return a.then(()=>s.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:r}){this.log(`Creating key-system session "${t}" keyId: ${th(e.keyId||[])} keyUri: ${e.uri}`);const n=r.createSession(),i={decryptdata:e,keySystem:t,mediaKeys:r,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(i),i}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const r=this.createMediaKeySessionContext(e),n=Gy(t),i="cenc";this.keyIdToKeySessionPromise[n]=this.generateRequestWithPreferredKeySession(r,i,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyId ${th(e.decryptdata.keyId||[])}\n } (data length: ${t.byteLength})`),r.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>eg(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:e,mediaKeys:t})=>this.attemptSetMediaKeys(e,t))}selectKeySystem(e){return new Promise((t,r)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:e})=>{const n=eg(e);n?t(n):r(new Error(`Unable to find format for key-system "${e}"`))}).catch(r)})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=tg(this.config),r=e.map(Jp).filter(e=>!!e&&-1!==t.indexOf(e));return this.selectKeySystem(r)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let r=0;r<t.length;r++){const n=Hy(e,t[r]);if(n)return n}}loadKey(e){const t=e.keyInfo.decryptdata,r=Gy(t),n=this.bannedKeyIds[r];if(n||"internal-error"===this.getKeyStatus(t)){const r=Wy(n||"internal-error",t);return this.handleError(r,e.frag),Promise.reject(r)}const i=`(keyId: ${r} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${i}`);const s=this.keyIdToKeySessionPromise[r];if(!s){const n=this.getKeySystemForKeyPromise(t).then(({keySystem:r,mediaKeys:n})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${i}`),this.attemptSetMediaKeys(r,n).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:r,mediaKeys:n,decryptdata:t}))))).then(e=>{const r=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(e,"cenc",r,"playlist-key")});return n.catch(t=>this.handleError(t,e.frag)),this.keyIdToKeySessionPromise[r]=n,n}return s.catch(r=>{if(r instanceof Vy){const n=Hd({},r.data);"internal-error"===this.getKeyStatus(t)&&(n.decryptdata=t);const i=new Vy(n,r.message);this.handleError(i,e.frag)}}),s}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Vy){t&&(e.data.frag=t);const r=e.data.decryptdata;this.error(`${e.message}${r?` (${th(r.keyId||[])})`:""}`),this.hls.trigger(Pd.ERROR,e.data)}else this.error(e.message),this.hls.trigger(Pd.ERROR,{type:Id.KEY_SYSTEM_ERROR,details:Cd.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=Gy(e),r=this.keyIdToKeySessionPromise[t];if(!r){const t=Jp(e.keyFormat),r=t?[t]:tg(this.config);return this.attemptKeySystemAccess(r)}return r}getKeySystemSelectionPromise(e){if(e.length||(e=tg(this.config)),0===e.length)throw new Vy({type:Id.KEY_SYSTEM_ERROR,details:Cd.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Rf({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const r=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const n=Promise.all(r).then(()=>this.media?this.media.setMediaKeys(t):new Promise((e,r)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return r(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(e).catch(r)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(n),n.then(()=>{this.log(`Media-keys set for "${e}"`),r.push(n),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(e=>-1===r.indexOf(e))})}generateRequestWithPreferredKeySession(e,t,r,n){var i;const s=null==(i=this.config.drmSystems)||null==(i=i[e.keySystem])?void 0:i.generateRequest;if(s)try{const n=s.call(this.hls,t,r,e);if(!n)throw new Error("Invalid response from configured generateRequest filter");t=n.initDataType,r=n.initData?n.initData:null,e.decryptdata.pssh=r?new Uint8Array(r):null}catch(e){if(this.warn(e.message),this.hls&&this.hls.config.debug)throw e}if(null===r)return this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(e);const a=Gy(e.decryptdata),o=e.decryptdata.uri;this.log(`Generating key-session request for "${n}" keyId: ${a} URI: ${o} (init data type: ${t} length: ${r.byteLength})`);const l=new cm,u=e._onmessage=t=>{const r=e.mediaKeysSession;if(!r)return void l.emit("error",new Error("invalid state"));const{messageType:n,message:i}=t;this.log(`"${n}" message event for session "${r.sessionId}" message size: ${i.byteLength}`),"license-request"===n||"license-renewal"===n?this.renewLicense(e,i).catch(e=>{l.eventNames().length?l.emit("error",e):this.handleError(e)}):"license-release"===n?e.keySystem===Yp.FAIRPLAY&&this.updateKeySession(e,Hp("acknowledged")).then(()=>this.removeSession(e)).catch(e=>this.handleError(e)):this.warn(`unhandled media key message type "${n}"`)},c=(e,t)=>{let r;t.keyStatus=e,e.startsWith("usable")?l.emit("resolved"):"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?r=Wy(e,t.decryptdata):"expired"===e?r=new Error(`key expired (keyId: ${a})`):"released"===e?r=new Error("key released"):"status-pending"===e||this.warn(`unhandled key status change "${e}" (keyId: ${a})`),r&&(l.eventNames().length?l.emit("error",r):this.handleError(r))},d=e._onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void l.emit("error",new Error("invalid state"));const r=this.getKeyStatuses(e);if(!Object.keys(r).some(e=>"status-pending"!==r[e]))return;if("expired"===r[a])return this.log(`Expired key ${Rf(r)} in key-session "${e.mediaKeysSession.sessionId}"`),void this.renewKeySession(e);let n=r[a];if(n)c(n,e);else{var i;const t=1e3;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(i=e.keyStatusTimeouts)[a]||(i[a]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const r=this.getKeyStatus(e.decryptdata);if(r&&"status-pending"!==r)return this.log(`No status for keyId ${a} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${r} from other session.`),c(r,e);this.log(`key status for ${a} in key-session "${e.mediaKeysSession.sessionId}" timed out after ${t}ms`),n="internal-error",c(n,e)},t)),this.log(`No status for keyId ${a} (${Rf(r)}).`)}};Gg(e.mediaKeysSession,"message",u),Gg(e.mediaKeysSession,"keystatuseschange",d);const h=new Promise((e,t)=>{l.on("error",t),l.on("resolved",e)});return e.mediaKeysSession.generateRequest(t,r).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${a} URI: ${o}`)}).catch(t=>{throw new Vy({type:Id.KEY_SYSTEM_ERROR,details:Cd.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${t}`)}).then(()=>h).catch(t=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw t}))).then(()=>(l.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((r,n)=>{if("string"==typeof n&&"object"==typeof r){const e=n;n=r,r=e}const i="buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);if(e.keySystem===Yp.PLAYREADY&&16===i.length){const e=th(i);t[e]=r,Vp(i)}const s=th(i);"internal-error"===r&&(this.bannedKeyIds[s]=r),this.log(`key status change "${r}" for keyStatuses keyId: ${s} key-session "${e.mediaKeysSession.sessionId}"`),t[s]=r}),t}fetchServerCertificate(e){const t=this.config,r=new(0,t.loader)(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((i,s)=>{const a={responseType:"arraybuffer",url:n},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(e,t,r,n)=>{i(e.data)},onError:(t,r,i,o)=>{s(new Vy({type:Id.KEY_SYSTEM_ERROR,details:Cd.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:i,response:Hd({url:a.url,data:void 0},t)},`"${e}" certificate request failed (${n}). Status: ${t.code} (${t.text})`))},onTimeout:(t,r,i)=>{s(new Vy({type:Id.KEY_SYSTEM_ERROR,details:Cd.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:i,response:{url:a.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(e,t,r)=>{s(new Error("aborted"))}};r.load(a,l,u)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,r){return new Promise((n,i)=>{e.setServerCertificate(r).then(i=>{this.log(`setServerCertificate ${i?"success":"not supported by CDM"} (${r.byteLength}) on "${t}"`),n(e)}).catch(e=>{i(new Vy({type:Id.KEY_SYSTEM_ERROR,details:Cd.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(t=>this.updateKeySession(e,new Uint8Array(t)).catch(t=>{throw new Vy({type:Id.KEY_SYSTEM_ERROR,details:Cd.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:t,fatal:!1},t.message)}))}unpackPlayReadyKeyMessage(e,t){const r=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!r.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const n=(new DOMParser).parseFromString(r,"application/xml"),i=n.querySelectorAll("HttpHeader");if(i.length>0){let t;for(let r=0,n=i.length;r<n;r++){var s,a;t=i[r];const n=null==(s=t.querySelector("name"))?void 0:s.textContent,o=null==(a=t.querySelector("value"))?void 0:a.textContent;n&&o&&e.setRequestHeader(n,o)}}const o=n.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return Hp(atob(l))}setupLicenseXHR(e,t,r,n){const i=this.config.licenseXhrSetup;return i?Promise.resolve().then(()=>{if(!r.decryptdata)throw new Error("Key removed");return i.call(this.hls,e,t,r,n)}).catch(s=>{if(!r.decryptdata)throw s;return e.open("POST",t,!0),i.call(this.hls,e,t,r,n)}).then(r=>{e.readyState||e.open("POST",t,!0);return{xhr:e,licenseChallenge:r||n}}):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))}requestLicense(e,t){const r=this.config.keyLoadPolicy.default;return new Promise((n,i)=>{const s=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${s}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return i(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let t=a.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);const r=this.config.licenseResponseCallback;if(r)try{t=r.call(this.hls,a,s,e)}catch(e){this.error(e)}n(t)}else{const o=r.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)i(new Vy({type:Id.KEY_SYSTEM_ERROR,details:Cd.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:a,response:{url:s,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${s}). Status: ${a.status} (${a.statusText})`));else{const r=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${r} attempts left`),this.requestLicense(e,t).then(n,i)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,s,e,t).then(({xhr:t,licenseChallenge:r})=>{e.keySystem==Yp.PLAYREADY&&(r=this.unpackPlayReadyKeyMessage(t,r)),t.send(r)}).catch(i)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const r=t.media;this.media=r,Gg(r,"encrypted",this.onMediaEncrypted),Gg(r,"waitingforkey",this.onWaitingForKey);const n=this.mediaResolved;n?n():this.mediaKeys=r.mediaKeys}onMediaDetached(){const e=this.media;e&&(Hg(e,"encrypted",this.onMediaEncrypted),Hg(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const r=this.media,n=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,ag.clearKeyUriToKeyIdMap();const i=n.length;jy.CDMCleanupPromise=Promise.all(n.map(e=>this.removeSession(e)).concat((null==r||null==(e=r.setMediaKeys(null))?void 0:e.catch(e=>{this.log(`Could not clear media keys: ${e}`),this.hls&&this.hls.trigger(Pd.ERROR,{type:Id.OTHER_ERROR,details:Cd.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${e}`)})}))||Promise.resolve())).catch(e=>{this.log(`Could not close sessions and clear media keys: ${e}`),this.hls&&this.hls.trigger(Pd.ERROR,{type:Id.OTHER_ERROR,details:Cd.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${e}`)})}).then(()=>{i&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){const e=t.reduce((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:r,decryptdata:n}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${th((null==n?void 0:n.keyId)||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.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:s}=e;s&&Object.keys(s).forEach(e=>self.clearTimeout(s[e]));const{drmSystemOptions:a}=this.config,o=function(e){var t;return!(!e||"persistent-license"!==e.sessionType&&(null==(t=e.sessionTypes)||!t.some(e=>"persistent-license"===e)))}(a)?new Promise((e,r)=>{self.setTimeout(()=>r(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(e).catch(r)}):Promise.resolve();return o.catch(e=>{this.log(`Could not remove session: ${e}`),this.hls&&this.hls.trigger(Pd.ERROR,{type:Id.OTHER_ERROR,details:Cd.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${e}`)})}).then(()=>t.close()).catch(e=>{this.log(`Could not close session: ${e}`),this.hls&&this.hls.trigger(Pd.ERROR,{type:Id.OTHER_ERROR,details:Cd.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${e}`)})})}return Promise.resolve()}}function Gy(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return th(e.keyId)}function Hy(e,t){return e.keyId&&t.mediaKeysSession.keyStatuses.has(e.keyId)?t.mediaKeysSession.keyStatuses.get(e.keyId):e.matches(t.decryptdata)?t.keyStatus:void 0}jy.CDMCleanupPromise=void 0;class Vy extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function Wy(e,t){const r="output-restricted"===e,n=r?Cd.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:Cd.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Vy({type:Id.KEY_SYSTEM_ERROR,details:n,fatal:!1,decryptdata:t},r?"HDCP level output restricted":`key status changed to "${e}"`)}function Ky(e,t){let r;try{r=new Event("addtrack")}catch(e){r=document.createEvent("Event"),r.initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)}function Yy(e,t){const r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(r){Qd.debug(`[texttrack-utils]: ${r}`);try{const r=new self.TextTrackCue(t.startTime,t.endTime,t.text);r.id=t.id,e.addCue(r)}catch(e){Qd.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===r&&(e.mode=r)}function qy(e,t){const r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues)for(let r=e.cues.length;r--;)t&&e.cues[r].removeEventListener("enter",t),e.removeCue(e.cues[r]);"disabled"===r&&(e.mode=r)}function Xy(e,t,r,n){const i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&e.cues.length>0){const i=function(e,t,r){const n=[],i=function(e,t){if(t<=e[0].startTime)return 0;const r=e.length-1;if(t>e[r].endTime)return-1;let n,i=0,s=r;for(;i<=s;)if(n=Math.floor((s+i)/2),t<e[n].startTime)s=n-1;else{if(!(t>e[n].startTime&&i<r))return n;i=n+1}return e[i].startTime-t<t-e[s].startTime?i:s}(e,t);if(i>-1)for(let s=i,a=e.length;s<a;s++){const i=e[s];if(i.startTime>=t&&i.endTime<=r)n.push(i);else if(i.startTime>r)return n}return n}(e.cues,t,r);for(let t=0;t<i.length;t++)n&&!n(i[t])||e.removeCue(i[t])}"disabled"===i&&(e.mode=i)}function Qy(e){const t=[];for(let r=0;r<e.length;r++){const n=e[r];"subtitles"!==n.kind&&"captions"!==n.kind||!n.label||t.push(e[r])}return t}function Zy(e){let t=5381,r=e.length;for(;r;)t=33*t^e.charCodeAt(--r);return(t>>>0).toString()}const Jy=.025;let eb=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function tb(e,t,r){return`${e.identifier}-${r+1}-${Zy(t)}`}class rb{constructor(e,t){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=t,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,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const r=this.playoutLimit;if(e<=0||isNaN(r))return!1;if(0===r)return!0;return((null==(t=this.assetList[e])?void 0:t.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 t=this.dateRange.tagAnchor;if(t)return nb(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime;return t-nb(t,e)<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=Ad(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return nb(e,t)}return e}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Jy))}set appendInPlace(e){this.appendInPlaceStarted?this.resetOnResume=!e:this.appendInPlaceDisabled=!e}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return t=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?eb.Range:eb.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}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||null!==this.assetListResponse}toString(){return`["${(e=this).identifier}" ${e.cue.pre?"<pre>":e.cue.post?"<post>":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`;var e}}function nb(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<Jy)?t.start:t.start+t.duration}function ib(e,t,r){const n=new self.URL(e,r);return"data:"!==n.protocol&&n.searchParams.set("_HLS_primary_id",t),n}function sb(e,t){for(;null!=(r=e.assetList[++t])&&r.error;)var r;return t}function ab(e){const t=e.timelineStart,r=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+r).toFixed(2)}]`}class ob{constructor(e,t,r,n){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(Pd.PLAYOUT_LIMIT_REACHED,{})};const i=this.hls=new e(t);this.interstitial=r,this.assetItem=n;const s=()=>{this.hasDetails=!0};i.once(Pd.LEVEL_LOADED,s),i.once(Pd.AUDIO_TRACK_LOADED,s),i.once(Pd.SUBTITLE_TRACK_LOADED,s),i.on(Pd.MEDIA_ATTACHING,(e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t;this.interstitial.playoutLimit&&(t.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&i.on(Pd.BUFFER_APPENDED,()=>{const e=this.bufferedEnd;this.reachedPlayout(e)&&(this._bufferedEosTime=e,i.trigger(Pd.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 t=this.assetItem.uri;try{t=ib(t,e.config.primarySessionId||"").href}catch(e){}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if(null!=(t=this.hls)&&t.bufferedToEnd)return!0;if(!e)return!1;const r=Math.min(this._bufferedEosTime||1/0,this.duration),n=this.timelineOffset,i=Ap.bufferInfo(e,n,0);return this.getAssetTime(i.end)>=r-.02}reachedPlayout(e){const t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!(null!=(e=this.hls)&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return(null==(e=this.hls)?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=Ap.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.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 t=this.interstitial.playoutLimit;if(t){const r=t-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(null==(e=this.hls)?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const r=e-t;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 t=this.timelineOffset,r=this.duration;return Math.min(Math.max(0,e-t),r)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var e;this.mediaAttached&&(null!=(e=this.hls)&&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 t;this.loadSource(),null==(t=this.hls)||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()}resumeBuffering(){var e;null==(e=this.hls)||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.hls)||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=e=>delete e.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,r){var n;null==(n=this.hls)||n.on(e,t)}once(e,t,r){var n;null==(n=this.hls)||n.once(e,t)}off(e,t,r){var n;null==(n=this.hls)||n.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${ab(this.assetItem)} ${null==(e=this.hls)?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}class lb extends Vd{constructor(e,t){super("interstitials-sched",t),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,t){return this.events?this.events.reduce((r,n)=>e<=n.startOffset&&t>n.startOffset?(delete n.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,t){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 n=this.items;if(n)for(n[r]||(void 0===t&&(t=e.start),r=this.findItemIndexAtTime(t));r>=0&&null!=(i=n[r])&&i.event;){var i;r--}return r}findItemIndexAtTime(e,t){const r=this.items;if(r)for(let n=0;n<r.length;n++){let i=r[n];if(t&&"primary"!==t&&(i=i[t]),e===i.start||e>i.start&&e<i.end)return n}return-1}findJumpRestrictedIndex(e,t){const r=this.items;if(r)for(let n=e;n<=t&&r[n];n++){const e=r[n].event;if(null!=e&&e.restrictions.jump&&!e.appendInPlace)return n}return-1}findEventIndex(e){const t=this.items;if(t)for(let n=t.length;n--;){var r;if((null==(r=t[n].event)?void 0:r.identifier)===e)return n}return-1}findAssetIndex(e,t){const r=e.assetList,n=r.length;if(n>1)for(let e=0;e<n;e++){const i=r[e];if(!i.error){const r=i.timelineStart;if(t===r||t>r&&(t<r+(i.duration||0)||e===n-1))return e}}return 0}get assetIdAtEnd(){var e;const t=null==(e=this.items)||null==(e=e[this.length-1])?void 0:e.event;if(t){const e=t.assetList,r=e[e.length-1];if(r)return r.identifier}return null}parseInterstitialDateRanges(e,t){const r=e.main.details,{dateRanges:n}=r,i=this.events,s=this.parseDateRanges(n,{url:r.url},t),a=Object.keys(n),o=i?i.filter(e=>!a.includes(e.identifier)):[];s.length&&s.sort((e,t)=>{const r=e.cue.pre,n=e.cue.post,i=t.cue.pre,s=t.cue.post;if(r&&!i)return-1;if(i&&!r)return 1;if(n&&!s)return 1;if(s&&!n)return-1;if(!(r||i||n||s)){const r=e.startTime,n=t.startTime;if(r!==n)return r-n}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=s,o.forEach(e=>{this.removeEvent(e)}),this.updateSchedule(e,o)}updateSchedule(e,t=[],r=!1){const n=this.events||[];if(n.length||t.length||this.length<2){const i=this.items,s=this.parseSchedule(n,e),a=r||t.length||(null==i?void 0:i.length)!==s.length||s.some((e,t)=>Math.abs(e.playout.start-i[t].playout.start)>.005||Math.abs(e.playout.end-i[t].playout.end)>.005);a&&(this.items=s,this.onScheduleUpdate(t,i))}}parseDateRanges(e,t,r){const n=[],i=Object.keys(e);for(let s=0;s<i.length;s++){const a=i[s],o=e[a];if(o.isInterstitial){let e=this.eventMap[a];e?e.setDateRange(o):(e=new rb(o,t),this.eventMap[a]=e,!1===r&&(e.appendInPlace=r)),n.push(e)}}return n}parseSchedule(e,t){const r=[],n=t.main.details,i=n.live?1/0:n.edge;let s=0;if((e=e.filter(e=>!(e.error||e.cue.once&&e.hasPlayed))).length){this.resolveOffsets(e,t);let n=0,o=0;if(e.forEach((t,a)=>{const l=t.cue.pre,u=t.cue.post,c=e[a-1]||null,d=t.appendInPlace,h=u?i:t.startOffset,f=t.duration,p=t.timelineOccupancy===eb.Range?f:0,g=t.resumptionOffset,m=(null==c?void 0:c.startTime)===h,v=h+t.cumulativeDuration;let y=d?v+f:h+g;if(l||!u&&h<=0){const e=o;o+=p,t.timelineStart=v;const n=s;s+=f,r.push({event:t,start:v,end:y,playout:{start:n,end:s},integrated:{start:e,end:o}})}else{if(!(h<=i))return;{if(!m){const i=h-n;if(i>.033){const l=n,u=o;o+=i;const c=s;s+=i;const d={previousEvent:e[a-1]||null,nextEvent:t,start:l,end:l+i,playout:{start:c,end:s},integrated:{start:u,end:o}};r.push(d)}else i>0&&c&&(c.cumulativeDuration+=i,r[r.length-1].end=h)}u&&(y=v),t.timelineStart=v;const i=o;o+=p;const l=s;s+=f,r.push({event:t,start:v,end:y,playout:{start:l,end:s},integrated:{start:i,end:o}})}}const b=t.resumeTime;n=u||b>i?i:b}),n<i){var a;const e=n,t=o,l=i-n;o+=l;const u=s;s+=l,r.push({previousEvent:(null==(a=r[r.length-1])?void 0:a.event)||null,nextEvent:null,start:n,end:e+l,playout:{start:u,end:s},integrated:{start:t,end:o}})}this.setDurations(i,s,o)}else{const e=0;r.push({previousEvent:null,nextEvent:null,start:e,end:i,playout:{start:e,end:i},integrated:{start:e,end:i}}),this.setDurations(i,i,i)}return r}setDurations(e,t,r){this.durations={primary:e,playout:t,integrated:r}}resolveOffsets(e,t){const r=t.main.details,n=r.live?1/0:r.edge;let i=0,s=-1;e.forEach((a,o)=>{const l=a.cue.pre,u=a.cue.post,c=l?0:u?n:a.startTime;this.updateAssetDurations(a);if(s===c?a.cumulativeDuration=i:(i=0,s=c),!u&&a.snapOptions.in&&(a.resumeAnchor=Ff(null,r.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(a,t)||(a.appendInPlace=!1)}if(!a.appendInPlace&&o+1<e.length){e[o+1].startTime-e[o].resumeTime<.033&&(e[o+1].appendInPlace=!1,e[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`))}const d=Ad(a.resumeOffset)?a.resumeOffset:a.duration;i+=d})}primaryCanResumeInPlaceAt(e,t){const r=e.resumeTime,n=e.startTime+e.resumptionOffset;if(Math.abs(r-n)>Jy)return this.log(`"${e.identifier}" resumption ${r} not aligned with estimated timeline end ${n}`),!1;return!Object.keys(t).some(n=>{const i=t[n].details,s=i.edge;if(r>=s)return this.log(`"${e.identifier}" resumption ${r} past ${n} playlist end ${s}`),!1;const a=Ff(null,i.fragments,r);if(!a)return this.log(`"${e.identifier}" resumption ${r} does not align with any fragments in ${n} playlist (${i.fragStart}-${i.fragmentEnd})`),!0;const o="audio"===n?.175:0;return!(Math.abs(a.start-r)<Jy+o||Math.abs(a.end-r)<Jy+o)&&(this.log(`"${e.identifier}" resumption ${r} not aligned with ${n} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let r=0,n=!1,i=!1;for(let s=0;s<e.assetList.length;s++){const a=e.assetList[s],o=t+r;a.startOffset=r,a.timelineStart=o,n||(n=null===a.duration),i||(i=!!a.error);r+=a.error?0:a.duration||0}e.duration=n&&!i?Math.max(r,e.duration):r}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function ub(e){return`[${e.event?'"'+e.event.identifier+'"':"primary"}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}class cb{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const r=e.assetListUrl;let n;try{n=ib(r,this.hls.sessionId,e.baseUrl)}catch(t){const n=this.assignAssetListError(e,Cd.ASSET_LIST_LOAD_ERROR,t,r);return void this.hls.trigger(Pd.ERROR,n)}t&&"data:"!==n.protocol&&n.searchParams.set("_HLS_start_offset",""+t);const i=this.hls.config,s=new(0,i.loader)(i),a={responseType:"json",url:n.href},o=i.interstitialAssetListLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(t,r,n,i)=>{const s=t.data,a=null==s?void 0:s.ASSETS;if(!Array.isArray(a)){const t=this.assignAssetListError(e,Cd.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),n.url,r,i);return void this.hls.trigger(Pd.ERROR,t)}e.assetListResponse=s,this.hls.trigger(Pd.ASSET_LIST_LOADED,{event:e,assetListResponse:s,networkDetails:i})},onError:(t,r,n,i)=>{const s=this.assignAssetListError(e,Cd.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${r.url})`),r.url,i,n);this.hls.trigger(Pd.ERROR,s)},onTimeout:(t,r,n)=>{const i=this.assignAssetListError(e,Cd.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${r.url})`),r.url,t,n);this.hls.trigger(Pd.ERROR,i)}};return s.load(a,l,u),this.hls.trigger(Pd.ASSET_LIST_LOADING,{event:e}),s}assignAssetListError(e,t,r,n,i,s){return e.error=r,{type:Id.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:n,error:r,networkDetails:s,stats:i}}}function db(e){var t;null==e||null==(t=e.play())||t.catch(()=>{})}function hb(e,t){return`[${e}] Advancing timeline position to ${t}`}class fb{constructor(e){this.buffered=void 0;const t=(t,r,n)=>{if((r>>>=0)>n-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${r}) is greater than the maximum bound (${n})`);return e[r][t]};this.buffered={get length(){return e.length},end:r=>t("end",r,e.length),start:r=>t("start",r,e.length)}}}const pb={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},gb=e=>String.fromCharCode(pb[e]||e),mb=15,vb=100,yb={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},bb={17:2,18:4,21:6,22:8,23:10,19:13,20:15},wb={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Eb={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Sb=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Tb{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const r="function"==typeof t?t():t;Qd.log(`${this.time} [${e}] ${r}`)}}}const xb=function(e){const t=[];for(let r=0;r<e.length;r++)t.push(e[r].toString(16));return t};class kb{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 t=["foreground","underline","italics","background","flash"];for(let r=0;r<t.length;r++){const n=t[r];e.hasOwnProperty(n)&&(this[n]=e[n])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!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 Ab{constructor(){this.uchar=" ",this.penState=new kb}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}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 Rb{constructor(e){this.chars=[],this.pos=0,this.currPenState=new kb,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<vb;e++)this.chars.push(new Ab);this.logger=e}equals(e){for(let t=0;t<vb;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<vb;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<vb;t++)if(!this.chars[t].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>vb&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=vb)}moveCursor(e){const t=this.pos+e;if(e>1)for(let e=this.pos+1;e<t+1;e++)this.chars[e].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=gb(e);this.pos>=vb?this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<vb;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let r=0;r<vb;r++){const n=this.chars[r].uchar;" "!==n&&(t=!1),e.push(n)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e);this.chars[this.pos].setPenState(this.currPenState)}}class Lb{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<mb;t++)this.rows.push(new Rb(e));this.logger=e}reset(){for(let e=0;e<mb;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let r=0;r<mb;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t}copy(e){for(let t=0;t<mb;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<mb;t++)if(!this.rows[t].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 = "+Rf(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<mb;e++)this.rows[e].clear();const e=this.currRow+1-this.nrRollUpRows,r=this.lastOutputScreen;if(r){const n=r.rows[e].cueStartTime,i=this.logger.time;if(null!==n&&null!==i&&n<i)for(let n=0;n<this.nrRollUpRows;n++)this.rows[t-this.nrRollUpRows+n+1].copy(r.rows[e+n])}}this.currRow=t;const r=this.rows[this.currRow];if(null!==e.indent){const t=e.indent,n=Math.max(t-1,0);r.setCursor(e.indent),e.color=r.chars[n].penState.foreground}const n={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(n)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+Rf(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let r="",n=-1;for(let r=0;r<mb;r++){const i=this.rows[r].getTextString();i&&(n=r+1,e?t.push("Row "+n+": '"+i+"'"):t.push(i.trim()))}return t.length>0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r}getTextAndFormat(){return this.rows}}class Ib{constructor(e,t,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=t,this.mode=null,this.verbose=0,this.displayedMemory=new Lb(r),this.nonDisplayedMemory=new Lb(r),this.lastOutputScreen=new Lb(r),this.currRollUpRow=this.displayedMemory.rows[14],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[14],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),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(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"),"MODE_TEXT"!==this.mode&&(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"),"MODE_POP-ON"===this.mode){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 t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{const r=Math.floor(e/2)-16,n=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=n[r]}this.logger.log(2,"MIDROW: "+Rf(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,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 Cb{constructor(e,t,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const n=this.logger=new Tb;this.channels=[null,new Ib(e,t,n),new Ib(e+1,r,n)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let e=0;e<t.length;e+=2){const r=127&t[e],n=127&t[e+1];let i=!1,s=null;if(0===r&&0===n)continue;this.logger.log(3,()=>"["+xb([t[e],t[e+1]])+"] -> ("+xb([r,n])+")");const a=this.cmdHistory;if(r>=16&&r<=31){if(Db(r,n,a)){Pb(null,null,a),this.logger.log(3,()=>"Repeated command ("+xb([r,n])+") is dropped");continue}Pb(r,n,this.cmdHistory),i=this.parseCmd(r,n),i||(i=this.parseMidrow(r,n)),i||(i=this.parsePAC(r,n)),i||(i=this.parseBackgroundAttributes(r,n))}else Pb(null,null,a);if(!i&&(s=this.parseChars(r,n),s)){const e=this.currentChannel;if(e&&e>0){this.channels[e].insertChars(s)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}i||s||this.logger.log(2,()=>"Couldn't parse cleaned data "+xb([r,n])+" orig: "+xb([t[e],t[e+1]]))}}parseCmd(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;const r=20===e||21===e||23===e?1:2,n=this.channels[r];return 20===e||21===e||28===e||29===e?32===t?n.ccRCL():33===t?n.ccBS():34===t?n.ccAOF():35===t?n.ccAON():36===t?n.ccDER():37===t?n.ccRU(2):38===t?n.ccRU(3):39===t?n.ccRU(4):40===t?n.ccFON():41===t?n.ccRDC():42===t?n.ccTR():43===t?n.ccRTD():44===t?n.ccEDM():45===t?n.ccCR():46===t?n.ccENM():47===t&&n.ccEOC():n.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let r=0;if((17===e||25===e)&&t>=32&&t<=47){if(r=17===e?1:2,r!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const n=this.channels[r];return!!n&&(n.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+xb([e,t])+")"),!0)}return!1}parsePAC(e,t){let r;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;const n=e<=23?1:2;r=t>=64&&t<=95?1===n?yb[e]:wb[e]:1===n?bb[e]:Eb[e];const i=this.channels[n];return!!i&&(i.setPAC(this.interpretPAC(r,t)),this.currentChannel=n,!0)}interpretPAC(e,t){let r;const n={color:null,italics:!1,indent:null,underline:!1,row:e};return r=t>95?t-96:t-64,n.underline=!(1&~r),r<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(n.italics=!0,n.color="white"):n.indent=4*Math.floor((r-16)/2),n}parseChars(e,t){let r,n=null,i=null;if(e>=25?(r=2,i=e-8):(r=1,i=e),i>=17&&i<=19){let e;e=17===i?t+80:18===i?t+112:t+144,this.logger.log(2,()=>"Special char '"+gb(e)+"' in channel "+r),n=[e]}else e>=32&&e<=127&&(n=0===t?[e]:[e,t]);return n&&this.logger.log(3,()=>"Char codes = "+xb(n).join(",")),n}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;let r;const n={};16===e||24===e?(r=Math.floor((t-32)/2),n.background=Sb[r],t%2==1&&(n.background=n.background+"_semi")):45===t?n.background="transparent":(n.foreground="black",47===t&&(n.underline=!0));const i=e<=23?1:2;return this.channels[i].setBkgData(n),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Pb(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const r=this.channels[t];r&&r.cueSplitAtTime(e)}}}function Pb(e,t,r){r.a=e,r.b=t}function Db(e,t,r){return r.a===e&&r.b===t}var _b=function(){if(null!=Kp&&Kp.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function r(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;const r=t.toLowerCase();return!!~e.indexOf(r)&&r}function n(e){return r(t,e)}function i(e,...t){let r=1;for(;r<arguments.length;r++){const t=arguments[r];for(const r in t)e[r]=t[r]}return e}function s(t,s,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let u="",c=!1,d=t,h=s,f=a,p=null,g="",m=!0,v="auto",y="start",b=50,w="middle",E=50,S="middle";Object.defineProperty(o,"id",i({},l,{get:function(){return u},set:function(e){u=""+e}})),Object.defineProperty(o,"pauseOnExit",i({},l,{get:function(){return c},set:function(e){c=!!e}})),Object.defineProperty(o,"startTime",i({},l,{get:function(){return d},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");d=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",i({},l,{get:function(){return h},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");h=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",i({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",i({},l,{get:function(){return p},set:function(e){p=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",i({},l,{get:function(){return g},set:function(t){const n=function(t){return r(e,t)}(t);if(!1===n)throw new SyntaxError("An invalid or illegal string was specified.");g=n,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",i({},l,{get:function(){return m},set:function(e){m=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",i({},l,{get:function(){return v},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",i({},l,{get:function(){return y},set:function(e){const t=n(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",i({},l,{get:function(){return b},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");b=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",i({},l,{get:function(){return w},set:function(e){const t=n(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");w=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",i({},l,{get:function(){return E},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",i({},l,{get:function(){return S},set:function(e){const t=n(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");S=t,this.hasBeenReset=!0}})),o.displayState=void 0}return s.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},s}();class Mb{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Ob(e){function t(e,t,r,n){return 3600*(0|e)+60*(0|t)+(0|r)+parseFloat(n||0)}const r=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?t(r[2],r[3],0,r[4]):t(r[1],r[2],r[3],r[4]):null}class Nb{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||""===t||(this.values[e]=t)}get(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,r){for(let n=0;n<r.length;++n)if(t===r[n]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const r=parseFloat(t);if(r>=0&&r<=100)return this.set(e,r),!0}return!1}}function Fb(e,t,r,n){const i=n?e.split(n):[e];for(const e in i){if("string"!=typeof i[e])continue;const n=i[e].split(r);if(2!==n.length)continue;t(n[0],n[1])}}const $b=new _b(0,0,""),Bb="middle"===$b.align?"middle":"center";function Ub(e,t,r){const n=e;function i(){const t=Ob(e);if(null===t)throw new Error("Malformed timestamp: "+n);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function s(){e=e.replace(/^\s+/,"")}if(s(),t.startTime=i(),s(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+n);e=e.slice(3),s(),t.endTime=i(),s(),function(e,t){const n=new Nb;Fb(e,function(e,t){let i;switch(e){case"region":for(let i=r.length-1;i>=0;i--)if(r[i].id===t){n.set(e,r[i].region);break}break;case"vertical":n.alt(e,t,["rl","lr"]);break;case"line":i=t.split(","),n.integer(e,i[0]),n.percent(e,i[0])&&n.set("snapToLines",!1),n.alt(e,i[0],["auto"]),2===i.length&&n.alt("lineAlign",i[1],["start",Bb,"end"]);break;case"position":i=t.split(","),n.percent(e,i[0]),2===i.length&&n.alt("positionAlign",i[1],["start",Bb,"end","line-left","line-right","auto"]);break;case"size":n.percent(e,t);break;case"align":n.alt(e,t,["start",Bb,"end","left","right"])}},/:/,/\s/),t.region=n.get("region",null),t.vertical=n.get("vertical","");let i=n.get("line","auto");"auto"===i&&-1===$b.line&&(i=-1),t.line=i,t.lineAlign=n.get("lineAlign","start"),t.snapToLines=n.get("snapToLines",!0),t.size=n.get("size",100),t.align=n.get("align",Bb);let s=n.get("position","auto");"auto"===s&&50===$b.position&&(s="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=s}(e,t)}function zb(e){return e.replace(/<br(?: \/)?>/gi,"\n")}class jb{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Mb,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;function r(){let e=t.buffer,r=0;for(e=zb(e);r<e.length&&"\r"!==e[r]&&"\n"!==e[r];)++r;const n=e.slice(0,r);return"\r"===e[r]&&++r,"\n"===e[r]&&++r,t.buffer=e.slice(r),n}function n(e){Fb(e,function(e,t){},/:/)}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let e="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;e=r();const n=e.match(/^()?WEBVTT([ \t].*)?$/);if(null==n||!n[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let i=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(i?i=!1:e=r(),t.state){case"HEADER":/:/.test(e)?n(e):e||(t.state="ID");continue;case"NOTE":e||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(e)){t.state="NOTE";break}if(!e)continue;if(t.cue=new _b(0,0,""),t.state="CUE",-1===e.indexOf("--\x3e")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Ub(e,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const r=-1!==e.indexOf("--\x3e");if(!e||r&&(i=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=e}continue;case"BADCUE":e||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const Gb=/\r\n|\n\r|\n|\r/g,Hb=function(e,t,r=0){return e.slice(r,r+t.length)===t};function Vb(e,t,r){return Zy(e.toString())+Zy(t.toString())+Zy(r)}function Wb(e,t,r,n,i,s,a){const o=new jb,l=eh(new Uint8Array(e)).trim().replace(Gb,"\n").split("\n"),u=[],c=t?function(e,t=1){return gv(e,9e4,1/t)}(t.baseTime,t.timescale):0;let d,h="00:00.000",f=0,p=0,g=!0;o.oncue=function(e){const s=r[n];let a=r.ccOffset;const o=(f-c)/9e4;if(null!=s&&s.new&&(void 0!==p?a=r.ccOffset=s.start:function(e,t,r){let n=e[t],i=e[n.prevCC];if(!i||!i.new&&n.new)return e.ccOffset=e.presentationOffset=n.start,void(n.new=!1);for(;null!=(s=i)&&s.new;){var s;e.ccOffset+=n.start-i.start,n.new=!1,n=i,i=e[n.prevCC]}e.presentationOffset=r}(r,n,o)),o){if(!t)return void(d=new Error("Missing initPTS for VTT MPEGTS"));a=o-r.presentationOffset}const l=e.endTime-e.startTime,h=Tv(9e4*(e.startTime+a-p),9e4*i)/9e4;e.startTime=Math.max(h,0),e.endTime=Math.max(h+l,0);const g=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(g)),e.id||(e.id=Vb(e.startTime,e.endTime,g)),e.endTime>0&&u.push(e)},o.onparsingerror=function(e){d=e},o.onflush=function(){d?a(d):s(u)},l.forEach(e=>{if(g){if(Hb(e,"X-TIMESTAMP-MAP=")){g=!1,e.slice(16).split(",").forEach(e=>{Hb(e,"LOCAL:")?h=e.slice(6):Hb(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))});try{p=function(e){let t=parseInt(e.slice(-3));const r=parseInt(e.slice(-6,-4)),n=parseInt(e.slice(-9,-7)),i=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(Ad(t)&&Ad(r)&&Ad(n)&&Ad(i)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*r,t+=6e4*n,t+=36e5*i,t}(h)/1e3}catch(e){d=e}return}""===e&&(g=!1)}o.parse(e+"\n")}),o.flush()}const Kb="stpp.ttml.im1t",Yb=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,qb=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Xb={left:"start",center:"center",right:"end",start:"start",end:"end"};function Qb(e,t,r,n){const i=Ih(new Uint8Array(e),["mdat"]);if(0===i.length)return void n(new Error("Could not parse IMSC1 mdat"));const s=i.map(e=>eh(e)),a=function(e,t,r=1,n=!1){return gv(e,t,1/r,n)}(t.baseTime,1,t.timescale);try{s.forEach(e=>r(function(e,t){const r=(new DOMParser).parseFromString(e,"text/xml"),n=r.getElementsByTagName("tt")[0];if(!n)throw new Error("Invalid ttml");const i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},s=Object.keys(i).reduce((e,t)=>(e[t]=n.getAttribute(`ttp:${t}`)||i[t],e),{}),a="preserve"!==n.getAttribute("xml:space"),o=Jb(Zb(n,"styling","style")),l=Jb(Zb(n,"layout","region")),u=Zb(n,"body","[begin]");return[].map.call(u,e=>{const r=ew(e,a);if(!r||!e.hasAttribute("begin"))return null;const n=nw(e.getAttribute("begin"),s),i=nw(e.getAttribute("dur"),s);let u=nw(e.getAttribute("end"),s);if(null===n)throw rw(e);if(null===u){if(null===i)throw rw(e);u=n+i}const c=new _b(n-t,u-t,r);c.id=Vb(c.startTime,c.endTime,c.text);const d=function(e,t,r){const n="http://www.w3.org/ns/ttml#styling";let i=null;const s=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;a&&r.hasOwnProperty(a)&&(i=r[a]);return s.reduce((r,s)=>{const a=tw(t,n,s)||tw(e,n,s)||tw(i,n,s);return a&&(r[s]=a),r},{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),{textAlign:h}=d;if(h){const e=Xb[h];e&&(c.lineAlign=e),c.align=h}return jd(c,d),c}).filter(e=>null!==e)}(e,a)))}catch(e){n(e)}}function Zb(e,t,r){const n=e.getElementsByTagName(t)[0];return n?[].slice.call(n.querySelectorAll(r)):[]}function Jb(e){return e.reduce((e,t)=>{const r=t.getAttribute("xml:id");return r&&(e[r]=t),e},{})}function ew(e,t){return[].slice.call(e.childNodes).reduce((e,r,n)=>{var i;return"br"===r.nodeName&&n?e+"\n":null!=(i=r.childNodes)&&i.length?ew(r,t):t?e+r.textContent.trim().replace(/\s+/g," "):e+r.textContent},"")}function tw(e,t,r){return e&&e.hasAttributeNS(t,r)?e.getAttributeNS(t,r):null}function rw(e){return new Error(`Could not parse ttml timestamp ${e}`)}function nw(e,t){if(!e)return null;let r=Ob(e);return null===r&&(Yb.test(e)?r=function(e,t){const r=Yb.exec(e),n=(0|r[4])+(0|r[5])/t.subFrameRate;return 3600*(0|r[1])+60*(0|r[2])+(0|r[3])+n/t.frameRate}(e,t):qb.test(e)&&(r=function(e,t){const r=qb.exec(e),n=Number(r[1]);switch(r[2]){case"h":return 3600*n;case"m":return 60*n;case"ms":return 1e3*n;case"f":return n/t.frameRate;case"t":return n/t.tickRate}return n}(e,t))),r}class iw{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,r){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}function sw(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function aw(e,t){return!!e&&e.kind===sw(t)&&Bv(t,e)}function ow(e,t,r,n){return Math.min(t,n)-Math.max(e,r)}const lw=/\s/,uw={newCue(e,t,r,n){const i=[];let s,a,o,l,u;const c=self.VTTCue||self.TextTrackCue;for(let h=0;h<n.rows.length;h++)if(s=n.rows[h],o=!0,l=0,u="",!s.isEmpty()){var d;for(let e=0;e<s.chars.length;e++)lw.test(s.chars[e].uchar)&&o?l++:(u+=s.chars[e].uchar,o=!1);s.cueStartTime=t,t===r&&(r+=1e-4),l>=16?l--:l++;const n=zb(u.trim()),f=Vb(t,r,n);null!=e&&null!=(d=e.cues)&&d.getCueById(f)||(a=new c(t,r,n),a.id=f,a.line=h+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),i.push(a))}return e&&i.length&&(i.sort((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line),i.forEach(t=>Yy(e,t))),i}};const cw=/(\d+)-(\d+)\/(\d+)/;class dw{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||hw,this.controller=new self.AbortController,this.stats=new hh}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(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,r){const n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();const i=function(e,t){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(jd({},e.headers))};e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return r}(e,this.controller.signal),s="arraybuffer"===e.responseType,a=s?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=r,this.request=this.fetchSetup(e,i),self.clearTimeout(this.requestTimeout),t.timeout=o&&Ad(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},t.timeout);(Pv(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(r=>{var i;this.response=this.loader=r;const a=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},l-(a-n.loading.start)),!r.ok){const{status:e,statusText:t}=r;throw new fw(t||"fetch, bad network response",e,r)}n.loading.first=a,n.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=cw.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(Ad(e))return e}const r=e.get("Content-Length");if(r)return parseInt(r)}(r.headers)||n.total;const o=null==(i=this.callbacks)?void 0:i.onProgress;return o&&Ad(t.highWaterMark)?this.loadProgressively(r,n,e,t.highWaterMark,o):s?r.arrayBuffer():"json"===e.responseType?r.json():r.text()}).then(r=>{var i,s;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const l=r[a];l&&(n.loaded=n.total=l);const u={url:o.url,data:r,code:o.status},c=null==(i=this.callbacks)?void 0:i.onProgress;c&&!Ad(t.highWaterMark)&&c(n,e,r,o),null==(s=this.callbacks)||s.onSuccess(u,n,e,o)}).catch(t=>{var r;if(self.clearTimeout(this.requestTimeout),n.aborted)return;const i=t&&t.code||0,s=t?t.message:null;null==(r=this.callbacks)||r.onError({code:i,text:s},e,t?t.details:null,n)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,r,n=0,i){const s=new am,a=e.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return s.dataLength&&i(t,r,s.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const l=a.value,u=l.length;return t.loaded+=u,u<n||s.dataLength?(s.push(l),s.dataLength>=n&&i(t,r,s.flush().buffer,e)):i(t,r,l.buffer,e),o()}).catch(()=>Promise.reject());return o()}}function hw(e,t){return new self.Request(e.url,t)}class fw extends Error{constructor(e,t,r){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=r}}const pw=/^age:\s*[\d.]+\s*$/im;class gw{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 hh,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,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,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=t,this.callbacks=r,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const r=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;const i=this.xhrSetup;i?Promise.resolve().then(()=>{if(this.loader===r&&!this.stats.aborted)return i(r,t.url)}).catch(e=>{if(this.loader===r&&!this.stats.aborted)return r.open("GET",t.url,!0),i(r,t.url)}).then(()=>{this.loader!==r||this.stats.aborted||this.openAndSendXhr(r,t,e)}).catch(e=>{var i;null==(i=this.callbacks)||i.onError({code:r.status,text:e.message},t,r,n)}):this.openAndSendXhr(r,t,e)}openAndSendXhr(e,t,r){e.readyState||e.open("GET",t.url,!0);const n=t.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:s}=r.loadPolicy;if(n)for(const t in n)e.setRequestHeader(t,n[t]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),r.timeout=i&&Ad(i)?i:s,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:r}=this;if(!e||!t)return;const n=t.readyState,i=this.config;if(!r.aborted&&n>=2&&(0===r.loading.first&&(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)))),4===n)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const n=t.status,l="text"===t.responseType?t.responseText:null;if(n>=200&&n<300){const i=null!=l?l:t.response;if(null!=i){var s,a;r.loading.end=Math.max(self.performance.now(),r.loading.first);const o="arraybuffer"===t.responseType?i.byteLength:i.length;r.loaded=r.total=o,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first);const l=null==(s=this.callbacks)?void 0:s.onProgress;l&&l(r,e,i,t);const u={url:t.responseURL,data:i,code:n};return void(null==(a=this.callbacks)||a.onSuccess(u,r,e,t))}}const u=i.loadPolicy.errorRetry;var o;if(Kf(u,r.retry,!1,{url:e.url,data:void 0,code:n}))this.retry(u);else Qd.error(`${n} while loading ${e.url}`),null==(o=this.callbacks)||o.onError({code:n,text:t.statusText},e,t,r)}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(Kf(e,this.stats.retry,!0))this.retry(e);else{var t;Qd.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:r}=this;this.retryDelay=Vf(e,r.retry),r.retry++,Qd.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?void 0:t.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 t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&pw.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):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 mw=Hd(Hd({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:6e7,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:gw,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class extends Vd{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=e=>{var t;const{fragCurrent:r,partCurrent:n,hls:i}=this,{autoLevelEnabled:s,media:a}=i;if(!r||!a)return;const o=performance.now(),l=n?n.stats:r.stats,u=n?n.duration:r.duration,c=o-l.loading.start,d=i.minAutoLevel,h=r.level,f=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||h<=d)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!s)return;const p=f>-1&&f!==h,g=!!e||p;if(!g&&(a.paused||!a.playbackRate||!a.readyState))return;const m=i.mainForwardBufferInfo;if(!g&&null===m)return;const v=this.bwEstimator.getEstimateTTFB(),y=Math.abs(a.playbackRate);if(c<=Math.max(v,u/(2*y)*1e3))return;const b=m?m.len/y:0,w=l.loading.first?l.loading.first-l.loading.start:-1,E=l.loaded&&w>-1,S=this.getBwEstimate(),T=i.levels,x=T[h],k=Math.max(l.loaded,Math.round(u*(r.bitrate||x.averageBitrate)/8));let A=E?c-w:c;A<1&&E&&(A=Math.min(c,8*l.loaded/S));const R=E?1e3*l.loaded/A:0,L=v/1e3,I=R?(k-l.loaded)/R:8*k/S+L;if(I<=b)return;const C=R?8*R:S,P=!0===(null==(t=(null==e?void 0:e.details)||this.hls.latestLevelDetails)?void 0:t.live),D=this.hls.config.abrBandWidthUpFactor;let _,M=Number.POSITIVE_INFINITY;for(_=h-1;_>d;_--){const e=T[_].maxBitrate,t=!T[_].details||P;if(M=this.getTimeToLoadFrag(L,C,u*e,t),M<Math.min(b,u+L))break}if(M>=I)return;if(M>10*u)return;E?this.bwEstimator.sample(c-Math.min(v,w),l.loaded):this.bwEstimator.sampleTTFB(c);const O=T[_].maxBitrate;this.getBwEstimate()*D>O&&this.resetEstimator(O);const N=this.findBestLevel(O,d,_,0,b,1,1);N>-1&&(_=N),this.warn(`Fragment ${r.sn}${n?" part "+n.index:""} of level ${h} is loading too slowly;\n Fragment duration: ${r.duration.toFixed(3)}\n Time to underbuffer: ${b.toFixed(3)} s\n Estimated load time for current fragment: ${I.toFixed(3)} s\n Estimated load time for down switch fragment: ${M.toFixed(3)} s\n TTFB estimate: ${0|w} ms\n Current BW estimate: ${Ad(S)?0|S:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${_} @ ${0|O} bps`),i.nextLoadLevel=i.nextAutoLevel=_,this.clearTimer();const F=()=>{if(this.clearTimer(),this.fragCurrent===r&&this.hls.loadLevel===_&&_>0){const e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${_>0?"and switching down":""}\n Fragment duration: ${r.duration.toFixed(3)} s\n Time to underbuffer: ${e.toFixed(3)} s`),r.abortRequests(),this.fragCurrent=this.partCurrent=null,_>d){let t=this.findBestLevel(this.hls.levels[d].bitrate,d,_,0,e,1,1);-1===t&&(t=d),this.hls.nextLoadLevel=this.hls.nextAutoLevel=t,this.resetEstimator(this.hls.levels[t].bitrate)}}};p||I>2*M?F():this.timer=self.setInterval(F,1e3*M),i.trigger(Pd.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,part:n,stats:l})},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 Ud(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Pd.FRAG_LOADING,this.onFragLoading,this),e.on(Pd.FRAG_LOADED,this.onFragLoaded,this),e.on(Pd.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Pd.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Pd.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Pd.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Pd.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(Pd.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Pd.FRAG_LOADING,this.onFragLoading,this),e.off(Pd.FRAG_LOADED,this.onFragLoaded,this),e.off(Pd.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Pd.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Pd.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Pd.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Pd.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(Pd.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){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,t){const r=t.frag;if(!this.ignoreFragment(r)){var n;if(!r.bitrateTest)this.fragCurrent=r,this.partCurrent=null!=(n=t.part)?n:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case Cd.BUFFER_ADD_CODEC_ERROR:case Cd.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Cd.FRAG_LOAD_TIMEOUT:{const e=t.frag,{fragCurrent:r,partCurrent:n}=this;if(e&&r&&e.sn===r.sn&&e.level===r.level){const t=performance.now(),r=n?n.stats:e.stats,i=t-r.loading.start,s=r.loading.first?r.loading.first-r.loading.start:-1;if(r.loaded&&s>-1){const e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(i-Math.min(e,s),r.loaded)}else this.bwEstimator.sampleTTFB(i)}break}}}getTimeToLoadFrag(e,t,r,n){return e+r/t+(n?e+this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const r=this.hls.config,{loading:n}=t.stats,i=n.end-n.first;Ad(i)&&(this.lastLevelLoadSec=i/1e3),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:r}){const n=r?r.stats:t.stats;if(t.type===Nd&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const e=r?r.duration:t.duration,i=this.hls.levels[t.level],s=(i.loaded?i.loaded.bytes:0)+n.loaded,a=(i.loaded?i.loaded.duration:0)+e;i.loaded={bytes:s,duration:a},i.realBitrate=Math.round(8*s/a)}if(t.bitrateTest){const e={stats:n,frag:t,part:r,id:t.type};this.onFragBuffered(Pd.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:r,part:n}=t,i=null!=n&&n.stats.loaded?n.stats:r.stats;if(i.aborted)return;if(this.ignoreFragment(r))return;const s=i.parsing.end-i.loading.start-Math.min(i.loading.first-i.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(s,i.loaded),i.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=s/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==Nd||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,r=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,i=this.findBestLevel(r,t,e,0,n,1,1);if(i>-1)return i;const s=this.hls.firstLevel,a=Math.min(Math.max(s,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${s} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&r&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;const n=t&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,n)&&t[e].loadError<=t[n].loadError)return e}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:r}=this;if(r.levels.length<=1)return r.loadLevel;const{maxAutoLevel:n,config:i,minAutoLevel:s}=r,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let u=i.abrBandWidthFactor,c=i.abrBandWidthUpFactor;if(l){const e=this.findBestLevel(o,s,n,l,0,u,c);if(e>=0)return this.rebufferNotice=-1,e}let d=a?Math.min(a,i.maxStarvationDelay):i.maxStarvationDelay;if(!l){const e=this.bitrateTestDelay;if(e){d=(a?Math.min(a,i.maxLoadingDelay):i.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),u=c=1}}const h=this.findBestLevel(o,s,n,l,d,u,c);if(this.rebufferNotice!==h&&(this.rebufferNotice=h,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${h}`)),h>-1)return h;const f=r.levels[s],p=r.loadLevelObj;return p&&(null==f?void 0:f.bitrate)<p.bitrate?s:r.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const r=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,n=e.mainForwardBufferInfo;return(n?n.len:0)/r}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,r,n,i,s,a){var o;const l=n+i,u=this.lastLoadedFragLevel,c=-1===u?this.hls.firstLevel:u,{fragCurrent:d,partCurrent:h}=this,{levels:f,allAudioTracks:p,loadLevel:g,config:m}=this.hls;if(1===f.length)return 0;const v=f[c],y=!(null==(o=this.hls.latestLevelDetails)||!o.live),b=-1===g||-1===u;let w,E="SDR",S=(null==v?void 0:v.frameRate)||0;const{audioPreference:T,videoPreference:x}=m,k=this.audioTracksByGroup||(this.audioTracksByGroup=If(p));let A=-1;if(b){if(-1!==this.firstSelection)return this.firstSelection;const n=this.codecTiers||(this.codecTiers=function(e,t,r,n){return e.slice(r,n+1).reduce((e,r,n)=>{if(!r.codecSet)return e;const i=r.audioGroups;let s=e[r.codecSet];s||(e[r.codecSet]=s={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:n,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,fragmentError:0}),s.minBitrate=Math.min(s.minBitrate,r.bitrate);const a=Math.min(r.height,r.width);return s.minHeight=Math.min(s.minHeight,a),s.minFramerate=Math.min(s.minFramerate,r.frameRate),s.minIndex=Math.min(s.minIndex,n),s.maxScore=Math.max(s.maxScore,r.score),s.fragmentError+=r.fragmentError,s.videoRanges[r.videoRange]=(s.videoRanges[r.videoRange]||0)+1,i&&i.forEach(e=>{if(!e)return;const r=t.groups[e];r&&(s.hasDefaultAudio=s.hasDefaultAudio||t.hasDefaultAudio?r.hasDefault:r.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(r.channels).forEach(e=>{s.channels[e]=(s.channels[e]||0)+r.channels[e]}))}),e},{})}(f,k,t,r)),i=function(e,t,r,n,i){const s=Object.keys(e),a=null==n?void 0:n.channels,o=null==n?void 0:n.audioCodec,l=null==i?void 0:i.videoCodec,u=a&&2===parseInt(a);let c=!1,d=!1,h=1/0,f=1/0,p=1/0,g=1/0,m=0,v=[];const{preferHDR:y,allowedVideoRanges:b}=Af(t,i);for(let t=s.length;t--;){const r=e[s[t]];c||(c=r.channels[2]>0),h=Math.min(h,r.minHeight),f=Math.min(f,r.minFramerate),p=Math.min(p,r.minBitrate),b.filter(e=>r.videoRanges[e]>0).length>0&&(d=!0)}h=Ad(h)?h:0,f=Ad(f)?f:0;const w=Math.max(1080,h),E=Math.max(30,f);p=Ad(p)?p:r,r=Math.max(p,r),d||(t=void 0);const S=s.length>1;return{codecSet:s.reduce((t,n)=>{const i=e[n];if(n===t)return t;if(v=d?b.filter(e=>i.videoRanges[e]>0):[],S){if(i.minBitrate>r)return Lf(n,`min bitrate of ${i.minBitrate} > current estimate of ${r}`),t;if(!i.hasDefaultAudio)return Lf(n,"no renditions with default or auto-select sound found"),t;if(o&&n.indexOf(o.substring(0,4))%5!=0)return Lf(n,`audio codec preference "${o}" not found`),t;if(a&&!u){if(!i.channels[a])return Lf(n,`no renditions with ${a} channel sound found (channels options: ${Object.keys(i.channels)})`),t}else if((!o||u)&&c&&0===i.channels[2])return Lf(n,"no renditions with stereo sound found"),t;if(i.minHeight>w)return Lf(n,`min resolution of ${i.minHeight} > maximum of ${w}`),t;if(i.minFramerate>E)return Lf(n,`min framerate of ${i.minFramerate} > maximum of ${E}`),t;if(!v.some(e=>i.videoRanges[e]>0))return Lf(n,`no variants with VIDEO-RANGE of ${Rf(v)} found`),t;if(l&&n.indexOf(l.substring(0,4))%5!=0)return Lf(n,`video codec preference "${l}" not found`),t;if(i.maxScore<m)return Lf(n,`max score of ${i.maxScore} < selected max of ${m}`),t}return t&&(ef(n)>=ef(t)||i.fragmentError>e[t].fragmentError)?t:(g=i.minIndex,m=i.maxScore,n)},void 0),videoRanges:v,preferHDR:y,minFramerate:f,minBitrate:p,minIndex:g}}(n,E,e,T,x),{codecSet:s,videoRanges:a,minFramerate:o,minBitrate:l,minIndex:u,preferHDR:c}=i;A=u,w=s,E=c?a[a.length-1]:a[0],S=o,e=Math.max(e,l),this.log(`picked start tier ${Rf(i)}`)}else w=null==v?void 0:v.codecSet,E=null==v?void 0:v.videoRange;const R=h?h.duration:d?d.duration:0,L=this.bwEstimator.getEstimateTTFB()/1e3,I=[];for(let o=r;o>=t;o--){var C;const t=f[o],d=o>c;if(!t)continue;if(m.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){const r=navigator.mediaCapabilities;"function"==typeof(null==r?void 0:r.decodingInfo)&&ff(t,k,E,S,e,T)?(t.supportedPromise=pf(t,k,r,this.supportedCache),t.supportedPromise.then(e=>{if(!this.hls)return;t.supportedResult=e;const r=this.hls.levels,n=r.indexOf(t);e.error?this.warn(`MediaCapabilities decodingInfo error: "${e.error}" for level ${n} ${Rf(e)}`):e.supported?e.decodingInfoResults.some(e=>!1===e.smooth||!1===e.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${n} not smooth or powerEfficient: ${Rf(e)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${n} ${Rf(e)}`),n>-1&&r.length>1&&(this.log(`Removing unsupported level ${n}`),this.hls.removeLevel(n),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(e=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${e}`)})):t.supportedResult=df}if((w&&t.codecSet!==w||E&&t.videoRange!==E||d&&S>t.frameRate||!d&&S>0&&S<t.frameRate||null!=(C=t.supportedResult)&&null!=(C=C.decodingInfoResults)&&C.some(e=>!1===e.smooth))&&(!b||o!==A)){I.push(o);continue}const p=t.details,v=(h?null==p?void 0:p.partTarget:null==p?void 0:p.averagetargetduration)||R;let x;x=d?a*e:s*e;const P=R&&n>=2*R&&0===i?t.averageBitrate:t.maxBitrate,D=this.getTimeToLoadFrag(L,x,P*v,void 0===p);if(x>=P&&(o===u||0===t.loadError&&0===t.fragmentError)&&(D<=L||!Ad(D)||y&&!this.bitrateTestDelay||D<l)){const e=this.forcedAutoLevel;return o===g||-1!==e&&e===g||(I.length&&this.trace(`Skipped level(s) ${I.join(",")} of ${r} max with CODECS and VIDEO-RANGE:"${f[I[0]].codecs}" ${f[I[0]].videoRange}; not compatible with "${w}" ${E}`),this.info(`switch candidate:${c}->${o} adjustedbw(${Math.round(x)})-bitrate=${Math.round(x-P)} ttfb:${L.toFixed(1)} avgDuration:${v.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${D.toFixed(1)} firstSelection:${b} codecSet:${t.codecSet} videoRange:${t.videoRange} hls.loadLevel:${g}`)),b&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:r}=this.hls;return Math.min(Math.max(e,r),t)}},bufferController:class extends Vd{constructor(e,t){var r;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=e=>{var t;this.hls&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{const{media:t,mediaSource:r}=this;e&&this.log("Media source opened"),t&&r&&(r.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(Pd.MEDIA_ATTACHED,{media:t,mediaSource:r}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=(r=Zd(e.config.preferManagedMediaSource),"undefined"!=typeof self&&r===self.ManagedMediaSource),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(Pd.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Pd.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Pd.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Pd.BUFFER_RESET,this.onBufferReset,this),e.on(Pd.BUFFER_APPENDING,this.onBufferAppending,this),e.on(Pd.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Pd.BUFFER_EOS,this.onBufferEos,this),e.on(Pd.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Pd.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Pd.FRAG_PARSED,this.onFragParsed,this),e.on(Pd.FRAG_CHANGED,this.onFragChanged,this),e.on(Pd.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Pd.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Pd.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Pd.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Pd.BUFFER_RESET,this.onBufferReset,this),e.off(Pd.BUFFER_APPENDING,this.onBufferAppending,this),e.off(Pd.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Pd.BUFFER_EOS,this.onBufferEos,this),e.off(Pd.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Pd.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Pd.FRAG_PARSED,this.onFragParsed,this),e.off(Pd.FRAG_CHANGED,this.onFragChanged,this),e.off(Pd.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const r={};if(this.operationQueue){const e=this.isUpdating();e||this.operationQueue.removeBlockers();const t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?" operations in queue":""}${e?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const n=this.transferData;return!this.sourceBufferCount&&n&&n.mediaSource===t?jd(r,n.tracks):this.sourceBuffers.forEach(e=>{const[t]=e;t&&(r[t]=jd({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null}),{media:e,mediaSource:t,tracks:r}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var r;let n=2;(t.audio&&!t.video||!t.altAudio)&&(n=1),this.bufferCodecEventsTotal=n,this.log(`${n} bufferCodec event(s) expected.`),null!=(r=this.transferData)&&r.mediaSource&&this.sourceBufferCount&&n&&this.bufferCreated()}onMediaAttaching(e,t){const r=this.media=t.media;this.transferData=this.overrides=void 0;const n=Zd(this.appendSource);if(n){const e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const i=this.mediaSource=t.mediaSource||new n;if(this.assignMediaSource(i),e)this._objectUrl=r.src,this.attachTransferred();else{const e=this._objectUrl=self.URL.createObjectURL(i);if(this.appendSource)try{r.removeAttribute("src");const t=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||t&&i instanceof t,Hv(r),function(e,t){const r=self.document.createElement("source");r.type="video/mp4",r.src=t,e.appendChild(r)}(r,e),r.load()}catch(t){r.src=e}else r.src=e}r.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,r;this.log(`${(null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${null==(r=e.constructor)?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,t=this.transferData;if(!t||!e)return;const r=this.tracks,n=t.tracks,i=n?Object.keys(n):null,s=i?i.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(n&&i&&s){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${Rf(r,(e,t)=>"initSegment"===e?void 0:t)};\ntransfer tracks: ${Rf(n,(e,t)=>"initSegment"===e?void 0:t)}}`),!Jd(n,r)){t.mediaSource=null,t.tracks=void 0;const i=e.currentTime,s=this.details,a=Math.max(i,(null==s?void 0:s.fragments[0].start)||0);return a-i>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${i} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(n)}"->"${Object.keys(r)}") start time: ${a} currentTime: ${i}`),this.onMediaDetaching(Pd.MEDIA_DETACHING,{}),this.onMediaAttaching(Pd.MEDIA_ATTACHING,t),void(e.currentTime=a))}this.transferData=void 0,i.forEach(e=>{const t=e,r=n[t];if(r){const e=r.buffer;if(e){const n=this.fragmentTracker,i=r.id;if(n.hasFragments(i)||n.hasParts(i)){const r=Ap.getBuffered(e);n.detectEvictedFragments(t,r,i,null,!0)}const s=Vv(t),a=[t,e];this.sourceBuffers[s]=a,e.updating&&this.operationQueue&&this.operationQueue.prependBlocker(t),this.trackSourceBuffer(t,r)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}onMediaDetaching(e,t){const r=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:n,mediaSource:i,_objectUrl:s}=this;if(i){if(this.log("media source "+(r?"transferring":"detaching")),r)this.sourceBuffers.forEach(([e])=>{e&&this.removeBuffer(e)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const e="open"===i.readyState;try{const t=i.sourceBuffers;for(let r=t.length;r--;)e&&t[r].abort(),i.removeSourceBuffer(t[r]);e&&i.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.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}n&&(n.removeEventListener("emptied",this._onMediaEmptied),r||(s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(n.removeAttribute("src"),this.appendSource&&Hv(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(Pd.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const r=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),r)try{var n;null!=(n=this.mediaSource)&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(t){this.warn(`onBufferReset ${e}`,t)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Vv(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Uv(this.tracks)}onBufferCodecs(e,t){var r;const n=this.tracks,i=Object.keys(t);this.log(`BUFFER_CODECS: "${i}" (current SB count ${this.sourceBufferCount})`);const s="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),a=!s&&this.sourceBufferCount&&this.media&&i.some(e=>!n[e]);s||a?this.warn(`Unsupported transition between "${Object.keys(n)}" and "${i}" SourceBuffers`):(i.forEach(e=>{var r,i;const s=t[e],{id:a,codec:o,levelCodec:l,container:u,metadata:c,supplemental:d}=s;let h=n[e];const f=null==(r=this.transferData)||null==(r=r.tracks)?void 0:r[e],p=null!=f&&f.buffer?f:h,g=(null==p?void 0:p.pendingCodec)||(null==p?void 0:p.codec),m=null==p?void 0:p.levelCodec;h||(h=n[e]={buffer:void 0,listeners:[],codec:o,supplemental:d,container:u,levelCodec:l,metadata:c,id:a});const v=sf(g,m),y=null==v?void 0:v.replace(zv,"$1");let b=sf(o,l);const w=null==(i=b)?void 0:i.replace(zv,"$1");b&&v&&y!==w&&("audio"===e.slice(0,5)&&(b=nf(b,this.appendSource)),this.log(`switching codec ${g} to ${b}`),b!==(h.pendingCodec||h.codec)&&(h.pendingCodec=b),h.container=u,this.appendChangeType(e,u,b))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(r=t.audio)?void 0:r.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const r=this.tracks[t];return e[t]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},e},{})}appendChangeType(e,t,r){const n=`${t};codecs=${r}`,i={label:`change-type=${n}`,execute:()=>{const i=this.tracks[e];if(i){const s=i.buffer;null!=s&&s.changeType&&(this.log(`changing ${e} sourceBuffer type to ${n}`),s.changeType(n),i.codec=r,i.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(i,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const r=e.start,n=r+.05*e.duration;if(!0===(null==(t=this.fragmentTracker.getAppendedFrag(r,Nd))?void 0:t.gap))return;const i={label:"block-audio",execute:()=>{var e;const t=this.tracks.video;(this.lastVideoAppendEnd>n||null!=t&&t.buffer&&Ap.isBuffered(t.buffer,n)||!0===(null==(e=this.fragmentTracker.getAppendedFrag(n,Nd))?void 0:e.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:i,frag:e},this.append(i,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:r}=this,{data:n,type:i,parent:s,frag:a,part:o,chunkMeta:l,offset:u}=t,c=l.buffering[i],{sn:d,cc:h}=a,f=self.performance.now();c.start=f;const p=a.stats.buffering,g=o?o.stats.buffering:null;0===p.start&&(p.start=f),g&&0===g.start&&(g.start=f);const m=r.audio;let v=!1;"audio"===i&&"audio/mpeg"===(null==m?void 0:m.container)&&(v=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const y=r.video,b=null==y?void 0:y.buffer;if(b&&"initSegment"!==d){const e=o||a,t=this.blockedAudioAppend;if("audio"!==i||"main"===s||this.blockedAudioAppend||y.ending||y.ended){if("video"===i){const r=e.end;if(t){const e=t.frag.start;(r>e||r<this.lastVideoAppendEnd||Ap.isBuffered(b,e))&&this.unblockAudio()}this.lastVideoAppendEnd=r}}else{const t=e.start+.05*e.duration,r=b.buffered,n=this.currentOp("video");r.length||n?!n&&!Ap.isBuffered(b,t)&&this.lastVideoAppendEnd<t&&this.blockAudio(e):this.blockAudio(e)}}const w=(o||a).start,E={label:`append-${i}`,execute:()=>{var e;c.executeStart=self.performance.now();const t=null==(e=this.tracks[i])?void 0:e.buffer;t&&(v?this.updateTimestampOffset(t,w,.1,i,d,h):void 0!==u&&Ad(u)&&this.updateTimestampOffset(t,u,1e-6,i,d,h)),this.appendExecutor(n,i)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();c.executeEnd=c.end=e,0===p.first&&(p.first=e),g&&0===g.first&&(g.first=e);const t={};this.sourceBuffers.forEach(([e,r])=>{e&&(t[e]=Ap.getBuffered(r))}),this.appendErrors[i]=0,"audio"===i||"video"===i?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(Pd.BUFFER_APPENDED,{type:i,frag:a,part:o,chunkMeta:l,parent:a.type,timeRanges:t})},onError:e=>{var t;const r={type:Id.MEDIA_ERROR,parent:a.type,details:Cd.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:a,part:o,chunkMeta:l,error:e,err:e,fatal:!1},n=null==(t=this.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e)r.details=Cd.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!n)r.errorAction=np(!0);else if(e.name===jv&&0===this.sourceBufferCount)r.errorAction=np(!0);else{const e=++this.appendErrors[i];this.warn(`Failed ${e}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${i}" sourceBuffer (${n||"no media error"})`),(e>=this.hls.config.appendErrorMaxRetry||n)&&(r.fatal=!0)}this.hls.trigger(Pd.ERROR,r)}};this.log(`queuing "${i}" append sn: ${d}${o?" p: "+o.index:""} of ${a.type===Nd?"level":"track"} ${a.level} cc: ${h}`),this.append(E,i,this.isPending(this.tracks[i]))}getFlushOp(e,t,r){return this.log(`queuing "${e}" remove ${t}-${r}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,r)},onStart:()=>{},onComplete:()=>{this.hls.trigger(Pd.BUFFER_FLUSHED,{type:e})},onError:n=>{this.warn(`Failed to remove ${t}-${r} from "${e}" SourceBuffer`,n)}}}onBufferFlushing(e,t){const{type:r,startOffset:n,endOffset:i}=t;r?this.append(this.getFlushOp(r,n,i),r):this.sourceBuffers.forEach(([e])=>{e&&this.append(this.getFlushOp(e,n,i),e)})}onFragParsed(e,t){const{frag:r,part:n}=t,i=[],s=n?n.elementaryStreams:r.elementaryStreams;s[gh]?i.push("audiovideo"):(s[fh]&&i.push("audio"),s[ph]&&i.push("video"));0===i.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${r.type} level: ${r.level} sn: ${r.sn}`),this.blockBuffers(()=>{const e=self.performance.now();r.stats.buffering.end=e,n&&(n.stats.buffering.end=e);const t=n?n.stats:r.stats;this.hls.trigger(Pd.FRAG_BUFFERED,{frag:r,part:n,stats:t,id:r.type})},i).catch(e=>{this.warn(`Fragment buffered callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var r;this.sourceBuffers.forEach(([e])=>{if(e){const r=this.tracks[e];t.type&&t.type!==e||(r.ending=!0,r.ended||(r.ended=!0,this.log(`${e} buffer reached EOS`)))}});const n=!1!==(null==(r=this.overrides)?void 0:r.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t;return e&&!(null!=(t=this.tracks[e])&&t.ended)})?n?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:e}=this;e&&"open"===e.readyState?(this.log("Calling mediaSource.endOfStream()"),e.endOfStream(),this.hls.trigger(Pd.BUFFERED_TO_END,void 0)):e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)})):(this.tracksEnded(),this.hls.trigger(Pd.BUFFERED_TO_END,void 0)):"video"===t.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(null!==e){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===Cd.BUFFER_APPEND_ERROR&&t.frag){var r;const e=null==(r=t.errorAction)?void 0:r.nextAutoLevel;Ad(e)&&e!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:r}=this;if(!r||null===t)return;if(!this.sourceBufferCount)return;const n=e.config,i=r.currentTime,s=t.levelTargetDuration,a=t.live&&null!==n.liveBackBufferLength?n.liveBackBufferLength:n.backBufferLength;if(Ad(a)&&a>=0){const e=Math.max(a,s),t=Math.floor(i/s)*s-e;this.flushBackBuffer(i,s,t)}const o=n.frontBufferFlushThreshold;if(Ad(o)&&o>0){const e=Math.max(n.maxBufferLength,o),t=Math.max(e,s),r=Math.floor(i/s)*s+t;this.flushFrontBuffer(i,s,r)}}flushBackBuffer(e,t,r){this.sourceBuffers.forEach(([e,t])=>{if(t){const i=Ap.getBuffered(t);if(i.length>0&&r>i.start(0)){var n;this.hls.trigger(Pd.BACK_BUFFER_REACHED,{bufferEnd:r});const t=this.tracks[e];if(null!=(n=this.details)&&n.live)this.hls.trigger(Pd.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(null!=t&&t.ended)return void this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);this.hls.trigger(Pd.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:e})}}})}flushFrontBuffer(e,t,r){this.sourceBuffers.forEach(([t,n])=>{if(n){const i=Ap.getBuffered(n),s=i.length;if(s<2)return;const a=i.start(s-1),o=i.end(s-1);if(r>a||e>=a&&e<=o)return;this.hls.trigger(Pd.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:t})}})}getDurationAndRange(){var e;const{details:t,mediaSource:r}=this;if(!t||!this.media||"open"!==(null==r?void 0:r.readyState))return null;const n=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&r.setLiveSeekableRange){const e=Math.max(0,t.fragmentStart);return{duration:1/0,start:e,end:Math.max(e,n)}}return{duration:1/0}}const i=null==(e=this.overrides)?void 0:e.duration;if(i)return Ad(i)?{duration:i}:null;const s=this.media.duration;return n>(Ad(r.duration)?r.duration:0)&&n>s||!Ad(s)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:r}){const n=this.mediaSource;this.media&&n&&"open"===n.readyState&&(n.duration!==e&&(Ad(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),n.duration=e),void 0!==t&&void 0!==r&&(this.log(`MediaSource duration is set to ${n.duration}. Setting seekable range to ${t}-${r}.`),n.setLiveSeekableRange(t,r)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:r}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${Rf(r)}`),this.tracksReady){var n;const e=null==(n=this.transferData)?void 0:n.tracks;e&&Object.keys(e).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,r])=>{if(t){const n=this.tracks[t];e[t]={buffer:r,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}}),this.hls.trigger(Pd.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(Pd.ERROR,{type:Id.MEDIA_ERROR,details:Cd.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:r}=this;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(const i in e){const s=i,a=e[s];if(this.isPending(a)){const e=this.getTrackCodec(a,s),i=`${a.container};codecs=${e}`;a.codec=e,this.log(`creating sourceBuffer(${i})${this.currentOp(s)?" Queued":""} ${Rf(a)}`);try{const e=r.addSourceBuffer(i),n=Vv(s),o=[s,e];t[n]=o,a.buffer=e}catch(e){var n;return this.error(`error while trying to add sourceBuffer: ${e.message}`),this.shiftAndExecuteNext(s),null==(n=this.operationQueue)||n.removeBlockers(),delete this.tracks[s],void this.hls.trigger(Pd.ERROR,{type:Id.MEDIA_ERROR,details:Cd.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:s,mimeType:i,parent:a.id})}this.trackSourceBuffer(s,a)}}this.bufferCreated()}getTrackCodec(e,t){const r=e.supplemental;let n=e.codec;r&&("video"===t||"audiovideo"===t)&&Xh(r,"video")&&(n=function(e,t){const r=[];if(e){const t=e.split(",");for(let e=0;e<t.length;e++)qh(t[e],"video")||r.push(t[e])}return t&&r.push(t),r.join(",")}(n,r));const i=sf(n,e.levelCodec);return i?"audio"===t.slice(0,5)?nf(i,this.appendSource):i:""}trackSourceBuffer(e,t){const r=t.buffer;if(!r)return;const n=this.getTrackCodec(t,e);this.tracks[e]={buffer:r,codec:n,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.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",(e,t)=>{const r=t.removedRanges;null!=r&&r.length&&this.hls.trigger(Pd.BUFFER_FLUSHED,{type:e})})}get mediaSrc(){var e,t;const r=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==r?void 0:r.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if("closed"===(null==(t=this.mediaSource)?void 0:t.readyState))return void this.resetBuffer(e);const r=this.currentOp(e);r&&(r.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var r;const n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(r=this.mediaSource)?void 0:r.readyState}`);this.error(`${n}`,t),this.hls.trigger(Pd.ERROR,{type:Id.MEDIA_ERROR,details:Cd.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});const i=this.currentOp(e);i&&i.onError(n)}updateTimestampOffset(e,t,r,n,i,s){const a=t-e.timestampOffset;Math.abs(a)>=r&&(this.log(`Updating ${n} SourceBuffer timestampOffset to ${t} (sn: ${i} cc: ${s})`),e.timestampOffset=t)}removeExecutor(e,t,r){const{media:n,mediaSource:i}=this,s=this.tracks[e],a=null==s?void 0:s.buffer;if(!n||!i||!a)return this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(e);const o=Ad(n.duration)?n.duration:1/0,l=Ad(i.duration)?i.duration:1/0,u=Math.max(0,t),c=Math.min(r,o,l);c>u&&(!s.ending||s.ended)?(s.ended=!1,this.log(`Removing [${u},${c}] from the ${e} SourceBuffer`),a.remove(u,c)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const r=this.tracks[t],n=null==r?void 0:r.buffer;if(!n)throw new Gv(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);r.ending=!1,r.ended=!1,n.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:r}=this,n=t.map(e=>this.appendBlocker(e));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(t=>{r===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(e=>{var t;const r=null==(t=this.tracks[e])?void 0:t.buffer;r&&!r.updating&&this.shiftAndExecuteNext(e)})}append(e,t,r){this.operationQueue&&this.operationQueue.append(e,t,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,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,r){const n=this.tracks[e];if(!n)return;const i=n.buffer;if(!i)return;const s=r.bind(this,e);n.listeners.push({event:t,listener:s}),i.addEventListener(t,s)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const r=t.buffer;r&&(t.listeners.forEach(e=>{r.removeEventListener(e.event,e.listener)}),t.listeners.length=0)}},capLevelController:Wv,errorController:class extends Vd{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(Pd.ERROR,this.onError,this),e.on(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Pd.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Pd.ERROR,this.onError,this),e.off(Pd.ERROR,this.onErrorOut,this),e.off(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Pd.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===Nd?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,r=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===r?t.loadLevel:r}variantHasKey(e,t){if(e){var r;if(null!=(r=e.details)&&r.hasKey(t))return!0;const n=e.audioGroups;if(n){return this.hls.allAudioTracks.filter(e=>n.indexOf(e.groupId)>=0).some(e=>{var r;return null==(r=e.details)?void 0:r.hasKey(t)})}}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var r;if(t.fatal)return;const n=this.hls,i=t.context;switch(t.details){case Cd.FRAG_LOAD_ERROR:case Cd.FRAG_LOAD_TIMEOUT:case Cd.KEY_LOAD_ERROR:case Cd.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case Cd.FRAG_PARSING_ERROR:if(null!=(r=t.frag)&&r.gap)return void(t.errorAction=np());case Cd.FRAG_GAP:case Cd.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=Xf);case Cd.LEVEL_EMPTY_ERROR:case Cd.LEVEL_PARSING_ERROR:{var s;const e=t.parent===Nd?t.level:n.loadLevel;t.details===Cd.LEVEL_EMPTY_ERROR&&null!=(s=t.context)&&null!=(s=s.levelDetails)&&s.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case Cd.LEVEL_LOAD_ERROR:case Cd.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==i?void 0:i.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.level)));case Cd.AUDIO_TRACK_LOAD_ERROR:case Cd.AUDIO_TRACK_LOAD_TIMEOUT:case Cd.SUBTITLE_LOAD_ERROR:case Cd.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const e=n.loadLevelObj;if(e&&(i.type===Md&&e.hasAudioGroup(i.groupId)||i.type===Od&&e.hasSubtitleGroup(i.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=Xf,void(t.errorAction.flags=ep)}return;case Cd.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:Xf,flags:tp});case Cd.KEY_SYSTEM_SESSION_UPDATE_FAILED:case Cd.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case Cd.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:Xf,flags:rp});case Cd.BUFFER_ADD_CODEC_ERROR:case Cd.REMUX_ALLOC_ERROR:case Cd.BUFFER_APPEND_ERROR:var a;if(!t.errorAction)t.errorAction=this.getLevelSwitchAction(t,null!=(a=t.level)?a:n.loadLevel);return;case Cd.INTERNAL_EXCEPTION:case Cd.BUFFER_APPENDING_ERROR:case Cd.BUFFER_FULL_ERROR:case Cd.LEVEL_SWITCH_ERROR:case Cd.BUFFER_STALLED_ERROR:case Cd.BUFFER_SEEK_OVER_HOLE:case Cd.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=np())}t.type===Id.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=np())}getPlaylistRetryOrSwitchAction(e,t){const r=Hf(this.hls.config.playlistLoadPolicy,e),n=this.playlistError++;if(Kf(r,n,zf(e),e.response))return{action:Zf,flags:Jf,retryConfig:r,retryCount:n};const i=this.getLevelSwitchAction(e,t);return r&&(i.retryConfig=r,i.retryCount=n),i}getFragRetryOrSwitchAction(e){const t=this.hls,r=this.getVariantLevelIndex(e.frag),n=t.levels[r],{fragLoadPolicy:i,keyLoadPolicy:s}=t.config,a=Hf(jf(e)?s:i,e),o=t.levels.reduce((e,t)=>e+t.fragmentError,0);if(n&&(e.details!==Cd.FRAG_GAP&&n.fragmentError++,!Gf(e))){if(Kf(a,o,zf(e),e.response))return{action:Zf,flags:Jf,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(e,r);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){const r=this.hls;null==t&&(t=r.loadLevel);const n=this.hls.levels[t];if(n){var i,s;const t=e.details;n.loadError++,t===Cd.BUFFER_APPEND_ERROR&&n.fragmentError++;let l=-1;const{levels:u,loadLevel:c,minAutoLevel:d,maxAutoLevel:h}=r;r.autoLevelEnabled||r.config.preserveManualLevelOnError||(r.loadLevel=-1);const f=null==(i=e.frag)?void 0:i.type,p=(f===Fd&&t===Cd.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(t===Cd.BUFFER_ADD_CODEC_ERROR||t===Cd.BUFFER_APPEND_ERROR))&&u.some(({audioCodec:e})=>n.audioCodec!==e),g="video"===e.sourceBufferName&&(t===Cd.BUFFER_ADD_CODEC_ERROR||t===Cd.BUFFER_APPEND_ERROR)&&u.some(({codecSet:e,audioCodec:t})=>n.codecSet!==e&&n.audioCodec===t),{type:m,groupId:v}=null!=(s=e.context)?s:{};for(let r=u.length;r--;){const i=(r+c)%u.length;if(i!==c&&i>=d&&i<=h&&0===u[i].loadError){var a,o;const r=u[i];if(t===Cd.FRAG_GAP&&f===Nd&&e.frag){const t=u[i].details;if(t){const r=Ff(e.frag,t.fragments,e.frag.start);if(null!=r&&r.gap)continue}}else{if(m===Md&&r.hasAudioGroup(v)||m===Od&&r.hasSubtitleGroup(v))continue;if(f===Fd&&null!=(a=n.audioGroups)&&a.some(e=>r.hasAudioGroup(e))||f===$d&&null!=(o=n.subtitleGroups)&&o.some(e=>r.hasSubtitleGroup(e))||p&&n.audioCodec===r.audioCodec||g&&n.codecSet===r.codecSet||!p&&n.codecSet!==r.codecSet)continue}l=i;break}}if(l>-1&&r.loadLevel!==l)return e.levelRetry=!0,this.playlistError=0,{action:Xf,flags:Jf,nextAutoLevel:l}}return{action:Xf,flags:ep}}onErrorOut(e,t){var r;switch(null==(r=t.errorAction)?void 0:r.action){case qf:break;case Xf:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===Cd.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,r=e.errorAction;if(!r)return;const{flags:n}=r,i=r.nextAutoLevel;switch(n){case Jf:this.switchLevel(e,i);break;case tp:{const n=this.getVariantLevelIndex(e.frag),i=t.levels[n],s=null==i?void 0:i.attrs["HDCP-LEVEL"];if(r.hdcpLevel=s,"NONE"===s)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(s){t.maxHdcpLevel=vf[vf.indexOf(s)-1],r.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case rp:{const t=e.decryptdata;if(t){const n=this.hls.levels,i=n.length;for(let r=i;r--;){var s,a;if(this.variantHasKey(n[r],t))this.log(`Banned key found in level ${r} (${n[r].bitrate}bps) or audio group "${null==(s=n[r].audioGroups)?void 0:s.join(",")}" (${null==(a=e.frag)?void 0:a.type} fragment) ${th(t.keyId||[])}`),n[r].fragmentError++,n[r].loadError++,this.log(`Removing level ${r} with key error (${e.error})`),this.hls.removeLevel(r)}const o=e.frag;if(this.hls.levels.length<i)r.resolved=!0;else if(o&&o.type!==Nd){const e=o.decryptdata;e&&!t.matches(e)&&(r.resolved=!0)}}break}}r.resolved||this.switchLevel(e,i)}switchLevel(e,t){if(void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===Cd.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName)){const t=uf(e.mimeType),r=this.hls.levels;for(let n=r.length;n--;)r[n][`${e.sourceBufferName}Codec`]===t&&(this.log(`Removing level ${n} for ${e.details} ("${t}" not supported)`),this.hls.removeLevel(n))}}},fpsController:class{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(Pd.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(Pd.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(Pd.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(Pd.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const r=this.hls.config;if(r.capLevelOnFPSDrop){const e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,r){const n=performance.now();if(t){if(this.lastTime){const e=n-this.lastTime,i=r-this.lastDroppedFrames,s=t-this.lastDecodedFrames,a=1e3*i/e,o=this.hls;if(o.trigger(Pd.FPS_DROP,{currentDropped:i,currentDecoded:s,totalDroppedFrames:r}),a>0&&i>o.config.fpsDroppedMonitoringThreshold*s){let e=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(Pd.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=n,this.lastDroppedFrames=r,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},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:rg,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:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},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},{cueHandler:uw,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends im{constructor(e,t,r){super(e,t,r,"subtitle-stream-controller",$d),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(Pd.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Pd.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Pd.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Pd.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Pd.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(Pd.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(Pd.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Pd.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Pd.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Pd.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Pd.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(Pd.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=Kg,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:r,success:n}=t;if(this.fragContextChanged(r)||(vh(r)&&(this.fragPrevious=r),this.state=Kg),!n)return;const i=this.tracksBuffered[this.currentTrackId];if(!i)return;let s;const a=r.start;for(let e=0;e<i.length;e++)if(a>=i[e].start&&a<=i[e].end){s=i[e];break}const o=r.start+r.duration;s?s.end=o:(s={start:a,end:o},i.push(s)),this.fragmentTracker.fragBuffered(r),this.fragBufferedComplete(r,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:r,endOffset:n}=t;if(0===r&&n!==Number.POSITIVE_INFINITY){const e=n-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach(t=>{for(let r=0;r<t.length;)if(t[r].end<=e)t.shift();else{if(!(t[r].start<e))break;t[r].start=e,r++}}),this.fragmentTracker.removeFragmentsInRange(r,e,$d)}}onError(e,t){const r=t.frag;(null==r?void 0:r.type)===$d&&(t.details===Cd.FRAG_GAP&&this.fragmentTracker.fragBuffered(r,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Wg&&(this.state=Kg))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){this.levels&&Fv(this.levels,t)?this.levels=t.map(e=>new xf(e)):(this.tracksBuffered=[],this.levels=t.map(e=>{const t=new xf(e);return this.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,$d),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){var r;if(this.currentTrackId=t.id,null==(r=this.levels)||!r.length||-1===this.currentTrackId)return void this.clearInterval();const n=this.levels[this.currentTrackId];null!=n&&n.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,n&&this.state!==Wg&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var r;const{currentTrackId:n,levels:i}=this,{details:s,id:a}=t;if(!i)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=i[a];if(a>=i.length||!o)return;this.log(`Subtitle track ${a} loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(s.live||null!=(r=o.details)&&r.live){if(s.deltaUpdateFailed)return;const e=this.mainDetails;if(!e)return void(this.startFragRequested=!1);const t=e.fragments[0];var u;if(o.details)l=this.alignPlaylists(s,o.details,null==(u=this.levelLastLoaded)?void 0:u.details),0===l&&t&&(l=t.start,Cg(s,l));else s.hasProgramDateTime&&e.hasProgramDateTime?(jg(s,e),l=s.fragmentStart):t&&(l=t.start,Cg(s,l));e&&!this.startFragRequested&&this.setStartPosition(e,l)}if(o.details=s,this.levelLastLoaded=o,a===n&&(this.hls.trigger(Pd.SUBTITLE_TRACK_UPDATED,{details:s,id:a,groupId:t.groupId}),this.tick(),s.live&&!this.fragCurrent&&this.media&&this.state===Kg)){Ff(null,s.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(e){const{frag:t,payload:r}=e,n=t.decryptdata,i=this.hls;if(!this.fragContextChanged(t)&&r&&r.byteLength>0&&null!=n&&n.key&&n.iv&&zp(n.method)){const e=performance.now();this.decrypter.decrypt(new Uint8Array(r),n.key.buffer,n.iv.buffer,jp(n.method)).catch(e=>{throw i.trigger(Pd.ERROR,{type:Id.MEDIA_ERROR,details:Cd.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e}).then(r=>{const n=performance.now();i.trigger(Pd.FRAG_DECRYPTED,{frag:t,payload:r,stats:{tstart:e,tdecrypt:n}})}).catch(e=>{this.warn(`${e.name}: ${e.message}`),this.state=Kg})}}doTick(){if(this.media){if(this.state===Kg){const{currentTrackId:e,levels:t}=this,r=null==t?void 0:t[e];if(!r||!t.length||!r.details)return;if(this.waitForLive(r))return;const{config:n}=this,i=this.getLoadPosition(),s=Ap.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],i,n.maxBufferHole),{end:a,len:o}=s,l=r.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;const u=l.fragments,c=u.length,d=l.edge;let h=null;const f=this.fragPrevious;if(a<d){const e=n.maxFragLookUpTolerance,t=a>d-e?0:e;h=Ff(f,u,Math.max(u[0].start,a),t),!h&&f&&f.start<u[0].start&&(h=u[0])}else h=u[c-1];if(h=this.filterReplacedPrimary(h,r.details),!h)return;const p=u[h.sn-l.startSN-1];if(p&&p.cc===h.cc&&this.fragmentTracker.getState(p)===ip&&(h=p),this.fragmentTracker.getState(h)===ip){const e=this.mapToInitFragWhenRequired(h);e&&this.loadFragment(e,r,a)}}}else this.state=Kg}loadFragment(e,t,r){vh(e)?super.loadFragment(e,t,r):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new fb(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends Nv{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 e=null;const t=Qy(this.media.textTracks);for(let r=0;r<t.length;r++)if("hidden"===t[r].mode)e=t[r];else if("showing"===t[r].mode){e=t[r];break}const r=this.findTrackForTextTrack(e);this.subtitleTrack!==r&&this.setSubtitleTrack(r)},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(Pd.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Pd.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Pd.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Pd.LEVEL_LOADING,this.onLevelLoading,this),e.on(Pd.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Pd.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Pd.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Pd.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Pd.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Pd.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Pd.LEVEL_LOADING,this.onLevelLoading,this),e.off(Pd.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Pd.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Pd.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.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,t){const r=this.media;if(!r)return;const n=!!t.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,n)return;Qy(r.textTracks).forEach(e=>{qy(e)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:r,groupId:n,details:i}=t,s=this.tracksInGroup[r];if(!s||s.groupId!==n)return void this.warn(`Subtitle track with id:${r} and group:${n} not found in active group ${null==s?void 0:s.groupId}`);const a=s.details;s.details=t.details,this.log(`Subtitle track ${r} "${s.name}" lang:${s.lang} group:${n} loaded [${i.startSN}-${i.endSN}]`),r===this.trackId&&this.playlistLoaded(r,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const r=t.subtitleGroups||null,n=this.groupIds;let i=this.currentTrack;if(!r||(null==n?void 0:n.length)!==(null==r?void 0:r.length)||null!=r&&r.some(e=>-1===(null==n?void 0:n.indexOf(e)))){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter(e=>!r||-1!==r.indexOf(e.groupId));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.subtitlePreference;if(!i&&t){this.selectDefaultTrack=!1;const r=Pf(t,e);if(r>-1)i=e[r];else{const e=Pf(t,this.tracks);i=this.tracks[e]}}let n=this.findTrackId(i);-1===n&&i&&(n=this.findTrackId(null));const s={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${null==r?void 0:r.join(",")}" group-id`),this.hls.trigger(Pd.SUBTITLE_TRACKS_UPDATED,s),-1!==n&&-1===this.trackId&&this.setSubtitleTrack(n)}}findTrackId(e){const t=this.tracksInGroup,r=this.selectDefaultTrack;for(let n=0;n<t.length;n++){const i=t[n];if((!r||i.default)&&(r||e)&&(!e||Df(i,e)))return n}if(e){for(let r=0;r<t.length;r++){const n=t[r];if($v(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return r}for(let r=0;r<t.length;r++){const n=t[r];if($v(e.attrs,n.attrs,["LANGUAGE"]))return r}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let r=0;r<t.length;r++){if(Bv(t[r],e))return r}}return-1}onError(e,t){!t.fatal&&t.context&&(t.context.type!==Od||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}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(-1===e.id)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const r=this.currentTrack;if(r&&Df(e,r))return r;const n=Pf(e,this.tracksInGroup);if(n>-1){const e=this.tracksInGroup[n];return this.setSubtitleTrack(n),e}if(r)return null;{const r=Pf(e,t);if(r>-1)return t[r]}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const r=e.id,n=e.groupId,i=this.getUrlWithDirectives(e.url,t),s=e.details,a=null==s?void 0:s.age;this.log(`Loading subtitle ${r} "${e.name}" lang:${e.lang} group:${n}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&s.live?" age "+a.toFixed(1)+(s.type&&" "+s.type||""):""} ${i}`),this.hls.trigger(Pd.SUBTITLE_TRACK_LOADING,{url:i,id:r,groupId:n,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Qy(e.textTracks),r=this.currentTrack;let n;if(r&&(n=t.filter(e=>Bv(r,e))[0],n||this.warn(`Unable to find subtitle TextTrack with name "${r.name}" and language "${r.lang}"`)),[].slice.call(t).forEach(e=>{"disabled"!==e.mode&&e!==n&&(e.mode="disabled")}),n){const e=this.subtitleDisplay?"showing":"hidden";n.mode!==e&&(n.mode=e)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=e);if(e<-1||e>=t.length||!Ad(e))return void this.warn(`Invalid subtitle track id: ${e}`);this.selectDefaultTrack=!1;const r=this.currentTrack,n=t[e]||null;if(this.trackId=e,this.currentTrack=n,this.toggleTrackModes(),!n)return void this.hls.trigger(Pd.SUBTITLE_TRACK_SWITCH,{id:e});const i=!!n.details&&!n.details.live;if(e===this.trackId&&n===r&&i)return;this.log(`Switching to subtitle-track ${e}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));const{id:s,groupId:a="",name:o,type:l,url:u}=n;this.hls.trigger(Pd.SUBTITLE_TRACK_SWITCH,{id:s,groupId:a,name:o,type:l,url:u});const c=this.switchParams(n.url,null==r?void 0:r.details,n.details);this.loadPlaylist(c)}},timelineController:class{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={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},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(Pd.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Pd.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Pd.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Pd.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Pd.FRAG_LOADING,this.onFragLoading,this),e.on(Pd.FRAG_LOADED,this.onFragLoaded,this),e.on(Pd.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(Pd.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(Pd.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Pd.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(Pd.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(Pd.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Pd.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Pd.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Pd.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Pd.FRAG_LOADING,this.onFragLoading,this),e.off(Pd.FRAG_LOADED,this.onFragLoaded,this),e.off(Pd.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(Pd.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(Pd.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Pd.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(Pd.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new iw(this,"textTrack1"),t=new iw(this,"textTrack2"),r=new iw(this,"textTrack3"),n=new iw(this,"textTrack4");this.cea608Parser1=new Cb(1,e,t),this.cea608Parser2=new Cb(3,r,n)}addCues(e,t,r,n,i){let s=!1;for(let e=i.length;e--;){const n=i[e],a=ow(n[0],n[1],t,r);if(a>=0&&(n[0]=Math.min(n[0],t),n[1]=Math.max(n[1],r),s=!0,a/(r-t)>.5))return}if(s||i.push([t,r]),this.config.renderTextTracksNatively){const i=this.captionsTracks[e];this.Cues.newCue(i,t,r,n)}else{const i=this.Cues.newCue(null,t,r,n);this.hls.trigger(Pd.CUES_PARSED,{type:"captions",cues:i,track:e})}}onInitPtsFound(e,{frag:t,id:r,initPTS:n,timescale:i,trackId:s}){const{unparsedVttFrags:a}=this;r===Nd&&(this.initPTS[t.cc]={baseTime:n,timescale:i,trackId:s}),a.length&&(this.unparsedVttFrags=[],a.forEach(e=>{this.initPTS[e.frag.cc]?this.onFragLoaded(Pd.FRAG_LOADED,e):this.hls.trigger(Pd.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:r}=this;if(r)for(let n=0;n<r.textTracks.length;n++){const i=r.textTracks[n];if(aw(i,{name:e,lang:t,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:t,captionsTracks:r,media:n}=this,{label:i,languageCode:s}=t[e],a=this.getExistingTrack(i,s);if(a)r[e]=a,qy(r[e]),Ky(r[e],n);else{const t=this.createTextTrack("captions",i,s);t&&(t[e]=!0,r[e]=t)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const r={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(Pd.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}createTextTrack(e,t,r){const n=this.media;if(n)return n.addTextTrack(e,t,r)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const r=!!t.transferMedia;if(this.media=null,r)return;const{captionsTracks:n}=this;Object.keys(n).forEach(e=>{qy(n[e]),delete n[e]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},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 t=e.textTracks;if(t)for(let e=0;e<t.length;e++)qy(t[e])}onSubtitleTracksUpdated(e,t){const r=t.subtitleTracks||[],n=r.some(e=>e.textCodec===Kb);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(Fv(this.tracks,r))return void(this.tracks=r);if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){const e=this.media,t=e?Qy(e.textTracks):null;if(this.tracks.forEach((e,r)=>{let n;if(t){let r=null;for(let n=0;n<t.length;n++)if(t[n]&&aw(t[n],e)){r=t[n],t[n]=null;break}r&&(n=r)}if(n)qy(n);else{const t=sw(e);n=this.createTextTrack(t,e.name,e.lang),n&&(n.mode="disabled")}n&&this.textTracks.push(n)}),null!=t&&t.length){const e=t.filter(e=>null!==e).map(e=>e.label);e.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${e.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const e=this.tracks.map(e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}));this.hls.trigger(Pd.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(e=>{const t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;const r=`textTrack${t[1]}`,n=this.captionsProperties[r];n&&(n.label=e.name,e.lang&&(n.languageCode=e.lang),n.media=e)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===Nd){var r,n;const{cea608Parser1:e,cea608Parser2:i,lastSn:s}=this,{cc:a,sn:o}=t.frag,l=null!=(r=null==(n=t.part)?void 0:n.index)?r:-1;e&&i&&(o!==s+1||o===s&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(e.reset(),i.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(e,t){const{frag:r,payload:n}=t;if(r.type===$d)if(n.byteLength){const e=r.decryptdata,i="stats"in t;if(null==e||!e.encrypted||i){const e=this.tracks[r.level],i=this.vttCCs;i[r.cc]||(i[r.cc]={start:r.start,prevCC:this.prevCC,new:!0},this.prevCC=r.cc),e&&e.textCodec===Kb?this._parseIMSC1(r,n):this._parseVTTs(t)}}else this.hls.trigger(Pd.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const r=this.hls;Qb(t,this.initPTS[e.cc],t=>{this._appendCues(t,e.level),r.trigger(Pd.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},t=>{r.logger.log(`Failed to parse IMSC1: ${t}`),r.trigger(Pd.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})})}_parseVTTs(e){var t;const{frag:r,payload:n}=e,{initPTS:i,unparsedVttFrags:s}=this,a=i.length-1;if(!i[r.cc]&&-1===a)return void s.push(e);const o=this.hls;Wb(null!=(t=r.initSegment)&&t.data?Bh(r.initSegment.data,new Uint8Array(n)).buffer:n,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,e=>{this._appendCues(e,r.level),o.trigger(Pd.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})},t=>{const i="Missing initPTS for VTT MPEGTS"===t.message;i?s.push(e):this._fallbackToIMSC1(r,n),o.logger.log(`Failed to parse VTT cue: ${t}`),i&&a>r.cc||o.trigger(Pd.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:t})})}_fallbackToIMSC1(e,t){const r=this.tracks[e.level];r.textCodec||Qb(t,this.initPTS[e.cc],()=>{r.textCodec=Kb,this._parseIMSC1(e,t)},()=>{r.textCodec="wvtt"})}_appendCues(e,t){const r=this.hls;if(this.config.renderTextTracksNatively){const r=this.textTracks[t];if(!r||"disabled"===r.mode)return;e.forEach(e=>Yy(r,e))}else{const n=this.tracks[t];if(!n)return;const i=n.default?"default":"subtitles"+t;r.trigger(Pd.CUES_PARSED,{type:"subtitles",cues:e,track:i})}}onFragDecrypted(e,t){const{frag:r}=t;r.type===$d&&this.onFragLoaded(Pd.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:r,samples:n}=t;if(r.type!==Nd||"NONE"!==this.closedCaptionsForLevel(r))for(let e=0;e<n.length;e++){const t=n[e].bytes;if(t){this.cea608Parser1||this.initCea608Parsers();const r=this.extractCea608Data(t);this.cea608Parser1.addData(n[e].pts,r[0]),this.cea608Parser2.addData(n[e].pts,r[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:r,endOffsetSubtitles:n,type:i}){const{media:s}=this;if(s&&!(s.currentTime<r)){if(!i||"video"===i){const{captionsTracks:e}=this;Object.keys(e).forEach(n=>Xy(e[n],t,r))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==n){const{textTracks:e}=this;Object.keys(e).forEach(r=>Xy(e[r],t,n))}}}extractCea608Data(e){const t=[[],[]],r=31&e[0];let n=2;for(let i=0;i<r;i++){const r=e[n++],i=127&e[n++],s=127&e[n++];if(0===i&&0===s)continue;if(!!(4&r)){const e=3&r;0!==e&&1!==e||(t[e].push(i),t[e].push(s))}}return t}},audioStreamController:class extends im{constructor(e,t,r){super(e,t,r,"audio-stream-controller",Fd),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(Pd.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Pd.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(Pd.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Pd.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Pd.BUFFER_RESET,this.onBufferReset,this),e.on(Pd.BUFFER_CREATED,this.onBufferCreated,this),e.on(Pd.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Pd.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Pd.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Pd.FRAG_LOADING,this.onFragLoading,this),e.on(Pd.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(Pd.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Pd.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(Pd.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Pd.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Pd.BUFFER_RESET,this.onBufferReset,this),e.off(Pd.BUFFER_CREATED,this.onBufferCreated,this),e.off(Pd.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Pd.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Pd.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Pd.FRAG_LOADING,this.onFragLoading,this),e.off(Pd.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:r,initPTS:n,timescale:i,trackId:s}){if(r===Nd){const e=t.cc,r=this.fragCurrent;if(this.initPTS[e]={baseTime:n,timescale:i,trackId:s},this.log(`InitPTS for cc: ${e} found from main: ${n/i} (${n}/${i}) trackId: ${s}`),this.mainAnchor=t,this.state===rm){const r=this.waitingData;(!r&&!this.loadingParts||r&&r.frag.cc!==e)&&this.syncWithAnchor(t,null==r?void 0:r.frag)}else!this.hls.hasEnoughToStart&&r&&r.cc!==e?(r.abortRequests(),this.syncWithAnchor(t,r)):this.state===Kg&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var r;const n=(null==(r=this.mainFragLoading)?void 0:r.frag)||null;if(t&&(null==n?void 0:n.cc)===t.cc)return;const i=(n||e).cc,s=Uf(this.getLevelDetails(),i,this.getLoadPosition());s&&(this.log(`Syncing with main frag at ${s.start} cc ${s.cc}`),this.startFragRequested=!1,this.nextLoadPosition=s.start,this.resetLoadingState(),this.state===Kg&&this.doTickIdle())}startLoad(e,t){if(!this.levels)return this.startPosition=e,void(this.state=Wg);const r=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),r>0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r,this.state=Kg):this.state=Qg,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case Kg:this.doTickIdle();break;case Qg:{const{levels:e,trackId:t}=this,r=null==e?void 0:e[t],n=null==r?void 0:r.details;if(n&&!this.waitForLive(r)){if(this.waitForCdnTuneIn(n))break;this.state=rm}break}case Xg:this.checkRetryDate();break;case rm:{const e=this.waitingData;if(e){const{frag:t,part:r,cache:n,complete:i}=e,s=this.mainAnchor;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.state=qg;const e={frag:t,part:r,payload:n.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(e),i&&super._handleFragmentLoadComplete(e)}else s&&s.cc!==e.frag.cc&&this.syncWithAnchor(s,e.frag)}else this.state=Kg}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:r,media:n,trackId:i}=this,s=t.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!s.startFragPrefetch)||null==r||!r[i])return;const a=r[i],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=Qg,void(this.startFragRequested=!1);const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,fh,Fd));const u=this.getFwdBufferInfo(l,Fd);if(null===u)return;if(!this.switchingTrack&&this._streamEnded(u,o))return t.trigger(Pd.BUFFER_EOS,{type:"audio"}),void(this.state=em);const c=u.len,d=t.maxBufferLength,h=o.fragments,f=h[0].start,p=this.getLoadPosition(),g=this.flushing?p:u.end;if(this.switchingTrack&&n){const e=p;o.PTSKnown&&e<f&&(u.end>f||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=f+.05)}if(c>=d&&!this.switchingTrack&&g<h[h.length-1].start)return;let m=this.getNextFragment(g,o);if(m&&this.isLoopLoading(m,g)&&(m=this.getNextFragmentLoopLoading(m,o,u,Nd,d)),!m)return void(this.bufferFlushed=!0);let v=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&vh(m)&&!m.endList&&(!o.live||!this.loadingParts&&g<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===op&&(this.mainFragLoading=v=null),v&&vh(v))){if(m.start>v.end){const e=this.fragmentTracker.getFragAtPos(g,Nd);e&&e.end>v.end&&(v=e,this.mainFragLoading={frag:e,targetBufferTime:null})}if(m.start>v.end)return}this.loadFragment(m,a,g)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(e=>new xf(e))}onAudioTrackSwitching(e,t){const r=!!t.url;this.trackId=t.id;const{fragCurrent:n}=this;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),r?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==Wg&&(this.setInterval(100),this.state=Kg,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const r=this.cachedTrackLoadedData;r&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(Pd.AUDIO_TRACK_LOADED,r))}onAudioTrackLoaded(e,t){var r;const{levels:n}=this,{details:i,id:s,groupId:a,track:o}=t;if(!n)return void this.warn(`Audio tracks reset while loading track ${s} "${o.name}" of "${a}"`);const l=this.mainDetails;if(!l||i.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==Wg&&(this.state=Qg));this.cachedTrackLoadedData=null,this.log(`Audio track ${s} "${o.name}" of "${a}" loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:""},duration:${i.totalduration}`);const u=n[s];let c=0;if(i.live||null!=(r=u.details)&&r.live){if(this.checkLiveUpdate(i),i.deltaUpdateFailed)return;var d;if(u.details)c=this.alignPlaylists(i,u.details,null==(d=this.levelLastLoaded)?void 0:d.details);i.alignedSliding||(zg(i,l),i.alignedSliding||jg(i,l),c=i.fragmentStart)}u.details=i,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(l,c),this.hls.trigger(Pd.AUDIO_TRACK_UPDATED,{details:i,id:s,groupId:t.groupId}),this.state!==Qg||this.waitForCdnTuneIn(i)||(this.state=Kg),this.tick()}_handleFragmentLoadProgress(e){var t;const r=e.frag,{part:n,payload:i}=e,{config:s,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const u=l.details;if(!u)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(r.start);const c=s.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new Ov(this.hls,Fd,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const h=this.initPTS[r.cc],f=null==(t=r.initSegment)?void 0:t.data;if(void 0!==h){const e=!1,t=n?n.index:-1,s=-1!==t,a=new xp(r.level,r.sn,r.stats.chunkCount,i.byteLength,t,s);d.push(i,f,c,"",r,n,u.totalduration,e,a,h)}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 ${a}`);const{cache:e}=this.waitingData=this.waitingData||{frag:r,part:n,cache:new am,complete:!1};e.push(new Uint8Array(i)),this.state!==Wg&&(this.state=rm)}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const r=t.tracks.audio;r&&(this.mediaBuffer=r.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===Nd&&vh(t.frag)&&(this.mainFragLoading=t,this.state===Kg&&this.tick())}onFragBuffered(e,t){const{frag:r,part:n}=t;if(r.type===Fd)if(this.fragContextChanged(r))this.warn(`Fragment ${r.sn}${n?" p: "+n.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(vh(r)){this.fragPrevious=r;const e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(Pd.AUDIO_TRACK_SWITCHED,Hd({},e)))}this.fragBufferedComplete(r,n),this.media&&this.tick()}else this.audioOnly||r.type!==Nd||r.elementaryStreams.video||r.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(e,t){var r;if(t.fatal)this.state=tm;else switch(t.details){case Cd.FRAG_GAP:case Cd.FRAG_PARSING_ERROR:case Cd.FRAG_DECRYPT_ERROR:case Cd.FRAG_LOAD_ERROR:case Cd.FRAG_LOAD_TIMEOUT:case Cd.KEY_LOAD_ERROR:case Cd.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Fd,t);break;case Cd.AUDIO_TRACK_LOAD_ERROR:case Cd.AUDIO_TRACK_LOAD_TIMEOUT:case Cd.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Qg||(null==(r=t.context)?void 0:r.type)!==Md||(this.state=Kg);break;case Cd.BUFFER_ADD_CODEC_ERROR:case Cd.BUFFER_APPEND_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case Cd.BUFFER_FULL_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case Cd.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==ph&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==ph){this.flushing=!1,this.bufferFlushed=!0,this.state===em&&(this.state=Kg);const e=this.mediaBuffer||this.media;e&&(this.afterBufferFlushed(e,t,Fd),this.tick())}}_handleTransmuxComplete(e){var t;const r="audio",{hls:n}=this,{remuxResult:i,chunkMeta:s}=e,a=this.getCurrentContext(s);if(!a)return void this.resetWhenMissingContext(s);const{frag:o,part:l,level:u}=a,{details:c}=u,{audio:d,text:h,id3:f,initSegment:p}=i;if(!this.fragContextChanged(o)&&c){if(this.state=Zg,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),null!=p&&p.tracks){const e=o.initSegment||o;if(this.unhandledEncryptionError(p,o))return;this._bufferInitSegment(u,p.tracks,e,s),n.trigger(Pd.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:r,tracks:p.tracks})}if(d){const{startPTS:e,endPTS:t,startDTS:r,endDTS:n}=d;l&&(l.elementaryStreams[fh]={startPTS:e,endPTS:t,startDTS:r,endDTS:n}),o.setElementaryStreamInfo(fh,e,t,r,n),this.bufferFragmentData(d,o,l,s)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=jd({id:r,frag:o,details:c},f);n.trigger(Pd.FRAG_PARSING_METADATA,e)}if(h){const e=jd({id:r,frag:o,details:c},h);n.trigger(Pd.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(e,t,r,n){if(this.state!==Zg)return;if(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio)return;const i=t.audio;i.id=Fd;const s=e.audioCodec;this.log(`Init audio buffer, container:${i.container}, codecs[level/parsed]=[${s}/${i.codec}]`),s&&1===s.split(",").length&&(i.levelCodec=s),this.hls.trigger(Pd.BUFFER_CODECS,t);const a=i.initSegment;if(null!=a&&a.byteLength){const e={type:"audio",frag:r,part:null,chunkMeta:n,parent:r.type,data:a};this.hls.trigger(Pd.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,r){const n=this.fragmentTracker.getState(e);var i;if(this.switchingTrack||n===ip||n===ap)if(vh(e))if(null!=(i=t.details)&&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=rm;const r=this.mainDetails;r&&r.fragmentStart!==t.details.fragmentStart&&jg(t.details,r)}else super.loadFragment(e,t,r);else this._loadInitSegment(e,t);else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:r,assocLang:n,characteristics:i,audioCodec:s,channels:a}=this.bufferedTrack;Df({name:t,lang:r,assocLang:n,characteristics:i,audioCodec:s,channels:a},e,_f)||(Of(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:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(Pd.AUDIO_TRACK_SWITCHED,Hd({},e))}},audioTrackController:class extends Nv{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(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Pd.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Pd.LEVEL_LOADING,this.onLevelLoading,this),e.on(Pd.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Pd.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Pd.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Pd.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Pd.LEVEL_LOADING,this.onLevelLoading,this),e.off(Pd.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Pd.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Pd.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,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:r,groupId:n,details:i}=t,s=this.tracksInGroup[r];if(!s||s.groupId!==n)return void this.warn(`Audio track with id:${r} and group:${n} not found in active group ${null==s?void 0:s.groupId}`);const a=s.details;s.details=t.details,this.log(`Audio track ${r} "${s.name}" lang:${s.lang} group:${n} loaded [${i.startSN}-${i.endSN}]`),r===this.trackId&&this.playlistLoaded(r,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const r=t.audioGroups||null,n=this.groupIds;let i=this.currentTrack;if(!r||(null==n?void 0:n.length)!==(null==r?void 0:r.length)||null!=r&&r.some(e=>-1===(null==n?void 0:n.indexOf(e)))){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter(e=>!r||-1!==r.indexOf(e.groupId));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.audioPreference;if(!i&&t){const r=Pf(t,e,_f);if(r>-1)i=e[r];else{const e=Pf(t,this.tracks);i=this.tracks[e]}}let n=this.findTrackId(i);-1===n&&i&&(n=this.findTrackId(null));const a={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${null==r?void 0:r.join(",")}`),this.hls.trigger(Pd.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==n&&-1===o)this.setAudioTrack(n);else if(e.length&&-1===o){var s;const t=new Error(`No audio track selected for current audio group-ID(s): ${null==(s=this.groupIds)?void 0:s.join(",")} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(Pd.ERROR,{type:Id.MEDIA_ERROR,details:Cd.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}}onError(e,t){!t.fatal&&t.context&&(t.context.type!==Md||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}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 t=this.hls;if(t.config.audioPreference=e,e){const r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){const n=this.currentTrack;if(n&&Df(e,n,_f))return n;const i=Pf(e,this.tracksInGroup,_f);if(i>-1){const e=this.tracksInGroup[i];return this.setAudioTrack(i),e}if(n){let n=t.loadLevel;-1===n&&(n=t.firstAutoLevel);const i=function(e,t,r,n,i){const s=t[n],a=t.reduce((e,t,r)=>{const n=t.uri;return(e[n]||(e[n]=[])).push(r),e},{})[s.uri];a.length>1&&(n=Math.max.apply(Math,a));const o=s.videoRange,l=s.frameRate,u=s.codecSet.substring(0,4),c=Mf(t,n,t=>{if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==u)return!1;const n=t.audioGroups,s=r.filter(e=>!n||-1!==n.indexOf(e.groupId));return Pf(e,s,i)>-1});return c>-1?c:Mf(t,n,t=>{const n=t.audioGroups,s=r.filter(e=>!n||-1!==n.indexOf(e.groupId));return Pf(e,s,i)>-1})}(e,t.levels,r,n,_f);if(-1===i)return null;t.nextLoadLevel=i}if(e.channels||e.audioCodec){const t=Pf(e,r);if(t>-1)return r[t]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn(`Invalid audio track id: ${e}`);this.selectDefaultTrack=!1;const r=this.currentTrack,n=t[e],i=n.details&&!n.details.live;if(e===this.trackId&&n===r&&i)return;if(this.log(`Switching to audio-track ${e} "${n.name}" lang:${n.lang} group:${n.groupId} channels:${n.channels}`),this.trackId=e,this.currentTrack=n,this.hls.trigger(Pd.AUDIO_TRACK_SWITCHING,Hd({},n)),i)return;const s=this.switchParams(n.url,null==r?void 0:r.details,n.details);this.loadPlaylist(s)}findTrackId(e){const t=this.tracksInGroup;for(let r=0;r<t.length;r++){const n=t[r];if((!this.selectDefaultTrack||n.default)&&(!e||Df(e,n,_f)))return r}if(e){const{name:r,lang:n,assocLang:i,characteristics:s,audioCodec:a,channels:o}=e;for(let e=0;e<t.length;e++){if(Df({name:r,lang:n,assocLang:i,characteristics:s,audioCodec:a,channels:o},t[e],_f))return e}for(let r=0;r<t.length;r++){const n=t[r];if($v(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return r}for(let r=0;r<t.length;r++){const n=t[r];if($v(e.attrs,n.attrs,["LANGUAGE"]))return r}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&Of(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const r=e.id,n=e.groupId,i=this.getUrlWithDirectives(e.url,t),s=e.details,a=null==s?void 0:s.age;this.log(`Loading audio-track ${r} "${e.name}" lang:${e.lang} group:${n}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&s.live?" age "+a.toFixed(1)+(s.type&&" "+s.type||""):""} ${i}`),this.hls.trigger(Pd.AUDIO_TRACK_LOADING,{url:i,id:r,groupId:n,deliveryDirectives:t||null,track:e})}},emeController:jy,cmcdController:class{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=e=>{try{this.apply(e,{ot:Kv.MANIFEST,su:!this.initialized})}catch(e){this.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{const{frag:t,part:r}=e,n=this.hls.levels[t.level],i=this.getObjectType(t),s={d:1e3*(r||t).duration,ot:i};i!==Kv.VIDEO&&i!==Kv.AUDIO&&i!=Kv.MUXED||(s.br=n.bitrate/1e3,s.tb=this.getTopBandwidth(i)/1e3,s.bl=this.getBufferLength(i));const a=r?this.getNextPart(r):this.getNextFrag(t);null!=a&&a.url&&a.url!==t.url&&(s.nor=a.url),this.apply(e,s)}catch(e){this.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=e;const t=this.config=e.config,{cmcd:r}=t;null!=r&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=r.sessionId||e.sessionId,this.cid=r.contentId,this.useHeaders=!0===r.useHeaders,this.includeKeys=r.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(Pd.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Pd.MEDIA_DETACHED,this.onMediaDetached,this),e.on(Pd.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(Pd.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Pd.MEDIA_DETACHED,this.onMediaDetached,this),e.off(Pd.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,t){this.media=t.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,t){var r,n;this.audioBuffer=null==(r=t.tracks.audio)?void 0:r.buffer,this.videoBuffer=null==(n=t.tracks.video)?void 0:n.buffer}createData(){var e;return{v:1,sf:Yv.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){jd(t,this.createData());const r=t.ot===Kv.INIT||t.ot===Kv.VIDEO||t.ot===Kv.MUXED;this.starved&&r&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);const{includeKeys:n}=this;n&&(t=Object.keys(t).reduce((e,r)=>(n.includes(r)&&(e[r]=t[r]),e),{}));const i={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),Ny(e.headers,t,i)):e.url=By(e.url,t,i)}getNextFrag(e){var t;const r=null==(t=this.hls.levels[e.level])?void 0:t.details;if(r){const t=e.sn-r.startSN;return r.fragments[t+1]}}getNextPart(e){var t;const{index:r,fragment:n}=e,i=null==(t=this.hls.levels[n.level])||null==(t=t.details)?void 0:t.partList;if(i){const{sn:e}=n;for(let t=i.length-1;t>=0;t--){const n=i[t];if(n.index===r&&n.fragment.sn===e)return i[t+1]}}}getObjectType(e){const{type:t}=e;return"subtitle"===t?Kv.TIMED_TEXT:"initSegment"===e.sn?Kv.INIT:"audio"===t?Kv.AUDIO:"main"===t?this.hls.audioTracks.length?Kv.VIDEO:Kv.MUXED:void 0}getTopBandwidth(e){let t,r=0;const n=this.hls;if(e===Kv.AUDIO)t=n.audioTracks;else{const e=n.maxAutoLevel,r=e>-1?e+1:n.levels.length;t=n.levels.slice(0,r)}return t.forEach(e=>{e.bitrate>r&&(r=e.bitrate)}),r>0?r:NaN}getBufferLength(e){const t=this.media,r=e===Kv.AUDIO?this.audioBuffer:this.videoBuffer;if(!r||!t)return NaN;return 1e3*Ap.bufferInfo(r,t.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,r=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new r(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,r,n){t(e),this.loader.load(e,r,n)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,r=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new r(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,r,n){t(e),this.loader.load(e,r,n)}}}},contentSteeringController:class extends Vd{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(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Pd.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Pd.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Pd.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Pd.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Pd.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Pd.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.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=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(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 t=this.levels;t&&(this.levels=t.filter(t=>t!==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,t){const{contentSteering:r}=t;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:r}=t;if((null==r?void 0:r.action)===Xf&&r.flags===ep){const e=this.levels;let n=this._pathwayPriority,i=this.pathwayId;if(t.context){const{groupId:r,pathwayId:n,type:s}=t.context;r&&e?i=this.getPathwayForGroupId(r,s,i):n&&(i=n)}i in this.penalizedPathways||(this.penalizedPathways[i]=performance.now()),!n&&e&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),r.resolved=this.pathwayId!==i),t.details!==Cd.BUFFER_APPEND_ERROR||t.fatal?r.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${i} levels: ${e?e.length:e} priorities: ${Rf(n)} penalized: ${Rf(this.penalizedPathways)}`):r.resolved=!0}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){const r=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${r}"`),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){let t;this._pathwayPriority=e;const r=this.penalizedPathways,n=performance.now();Object.keys(r).forEach(e=>{n-r[e]>3e5&&delete r[e]});for(let n=0;n<e.length;n++){const i=e[n];if(i in r)continue;if(i===this.pathwayId)return;const s=this.hls.nextLoadLevel,a=this.hls.levels[s];if(t=this.getLevelsForPathway(i),t.length>0){this.log(`Setting Pathway to "${i}"`),this.pathwayId=i,Og(t),this.hls.trigger(Pd.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[s];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=s);break}}}getPathwayForGroupId(e,t,r){const n=this.getLevelsForPathway(r).concat(this.levels||[]);for(let r=0;r<n.length;r++)if(t===Md&&n[r].hasAudioGroup(e)||t===Od&&n[r].hasSubtitleGroup(e))return n[r].pathwayId;return r}clonePathways(e){const t=this.levels;if(!t)return;const r={},n={};e.forEach(e=>{const{ID:i,"BASE-ID":s,"URI-REPLACEMENT":a}=e;if(t.some(e=>e.pathwayId===i))return;const o=this.getLevelsForPathway(s).map(e=>{const t=new Mp(e.attrs);t["PATHWAY-ID"]=i;const s=t.AUDIO&&`${t.AUDIO}_clone_${i}`,o=t.SUBTITLES&&`${t.SUBTITLES}_clone_${i}`;s&&(r[t.AUDIO]=s,t.AUDIO=s),o&&(n[t.SUBTITLES]=o,t.SUBTITLES=o);const l=zy(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),u=new xf({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t<e.audioGroups.length;t++)u.addGroupId("audio",`${e.audioGroups[t]}_clone_${i}`);if(e.subtitleGroups)for(let t=1;t<e.subtitleGroups.length;t++)u.addGroupId("text",`${e.subtitleGroups[t]}_clone_${i}`);return u});t.push(...o),Uy(this.audioTracks,r,a,i),Uy(this.subtitleTracks,n,a,i)})}loadSteeringManifest(e){const t=this.hls.config,r=t.loader;let n;this.loader&&this.loader.destroy(),this.loader=new r(t);try{n=new self.URL(e)}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${e}`)}if("data:"!==n.protocol){const e=0|(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate);n.searchParams.set("_HLS_pathway",this.pathwayId),n.searchParams.set("_HLS_throughput",""+e)}const i={responseType:"json",url:n.href},s=t.steeringManifestLoadPolicy.default,a=s.errorRetry||s.timeoutRetry||{},o={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(e,t,r,i)=>{this.log(`Loaded steering manifest: "${n}"`);const s=e.data;if(1!==(null==s?void 0:s.VERSION))return void this.log(`Steering VERSION ${s.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=s.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=s;if(a)try{this.uri=new self.URL(a,n).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||r.url),o&&this.clonePathways(o);const u={steeringManifest:s,url:n.toString()};this.hls.trigger(Pd.STEERING_MANIFEST_LOADED,u),l&&this.updatePathwayPriority(l)},onError:(e,t,r,n)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let i=1e3*this.timeToLoad;if(429===e.code){const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(i=1e3*parseFloat(t))}return void this.log(`Steering manifest ${t.url} rate limited`)}this.scheduleRefresh(this.uri||t.url,i)},onTimeout:(e,t,r)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(i,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var t;const r=null==(t=this.hls)?void 0:t.media;!r||r.ended?this.scheduleRefresh(e,1e3*this.timeToLoad):this.loadSteeringManifest(e)},t)}},interstitialsController:class extends Vd{constructor(e,t){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 e=this.currentTime;if(void 0===e||this.playbackDisabled||!this.schedule)return;const t=e-this.timelinePos;if(Math.abs(t)<1/7056e5)return;const r=t<=-.01;this.timelinePos=e,this.bufferedPos=e;const n=this.playingItem;if(!n)return void this.checkBuffer();if(r){this.schedule.resetErrorsInRange(e,e-t)&&this.updateSchedule(!0)}if(this.checkBuffer(),r&&e<n.start||e>=n.end){var i;const t=this.findItemIndex(n);let s=this.schedule.findItemIndexAtTime(e);if(-1===s&&(s=t+(r?-1:1),this.log(`seeked ${r?"back ":""}to position not covered by schedule ${e} (resolving from ${t} to ${s})`)),!this.isInterstitial(n)&&null!=(i=this.media)&&i.paused&&(this.shouldPlay=!1),!r&&s>t){const e=this.schedule.findJumpRestrictedIndex(t+1,s);if(e>t)return void this.setSchedulePosition(e)}return void this.setSchedulePosition(s)}const s=this.playingAsset;if(!s){if(this.playingLastItem&&this.isInterstitial(n)){const t=n.event.assetList[0];t&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(e,t))}return}const a=s.timelineStart,o=s.duration||0;var l;(r&&e<a||e>=a+o)&&(null!=(l=n.event)&&l.appendInPlace&&(this.clearAssetPlayers(n.event,n),this.flushFrontBuffer(e)),this.setScheduleToAssetAtTime(e,s))},this.onTimeupdate=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled)return;if(!(e>this.timelinePos))return;this.timelinePos=e,e>this.bufferedPos&&this.checkBuffer();const t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}const r=this.playingAsset;if(!r)return;e>=r.timelineStart+(r.duration||0)&&this.setScheduleToAssetAtTime(e,r)},this.onScheduleUpdate=(e,t)=>{const r=this.schedule;if(!r)return;const n=this.playingItem,i=r.events||[],s=r.items||[],a=r.durations,o=e.map(e=>e.identifier),l=!(!i.length&&!o.length);(l||t)&&this.log(`INTERSTITIALS_UPDATED (${i.length}): ${i}\nSchedule: ${s.map(e=>ub(e))} pos: ${this.timelinePos}`),o.length&&this.log(`Removed events ${o}`);let u=null,c=null;n&&(u=this.updateItem(n,this.timelinePos),this.itemsMatch(n,u)?this.playingItem=u:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const d=this.bufferingItem;if(d&&(c=this.updateItem(d,this.bufferedPos),this.itemsMatch(d,c)?this.bufferingItem=c:d.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(d.event,null))),e.forEach(e=>{e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,null)})}),this.playerQueue.forEach(e=>{if(e.interstitial.appendInPlace){const t=e.assetItem.timelineStart,r=e.timelineOffset-t;if(r)try{e.timelineOffset=t}catch(n){Math.abs(r)>Jy&&this.warn(`${n} ("${e.assetId}" ${e.timelineOffset}->${t})`)}}}),l||t){if(this.hls.trigger(Pd.INTERSTITIALS_UPDATED,{events:i.slice(0),schedule:s.slice(0),durations:a,removedIds:o}),this.isInterstitial(n)&&o.includes(n.event.identifier))return this.warn(`Interstitial "${n.event.identifier}" removed while playing`),void this.primaryFallback(n.event);n&&this.trimInPlace(u,n),d&&c!==u&&this.trimInPlace(c,d),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new cb(e),this.schedule=new lb(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(Pd.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Pd.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Pd.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Pd.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Pd.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Pd.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(Pd.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Pd.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(Pd.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(Pd.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(Pd.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Pd.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Pd.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(Pd.MEDIA_ENDED,this.onMediaEnded,this),e.on(Pd.ERROR,this.onError,this),e.on(Pd.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(Pd.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Pd.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Pd.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Pd.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Pd.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Pd.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(Pd.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Pd.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(Pd.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(Pd.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(Pd.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Pd.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Pd.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Pd.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(Pd.MEDIA_ENDED,this.onMediaEnded,this),e.off(Pd.ERROR,this.onError,this),e.off(Pd.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.getBufferingPlayer())||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){Hg(e,"play",this.onPlay),Hg(e,"pause",this.onPause),Hg(e,"seeking",this.onSeeking),Hg(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const r=this.media=t.media;Gg(r,"seeking",this.onSeeking),Gg(r,"timeupdate",this.onTimeupdate),Gg(r,"play",this.onPlay),Gg(r,"pause",this.onPause)}onMediaAttached(e,t){const r=this.effectivePlayingItem,n=this.detachedData;if(this.detachedData=null,null===r)this.checkStart();else if(!n){this.clearScheduleState();const e=this.findItemIndex(r);this.setSchedulePosition(e)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const r=!!t.transferMedia,n=this.media;if(this.media=null,!r&&(n&&this.removeMediaListeners(n),this.detachedData)){const e=this.getBufferingPlayer();e&&(this.log(`Removing schedule state for detachedData and ${e}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,e.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,r=t=>t?e.getAssetPlayer(t.identifier):t,n=(t,n,s,a,o)=>{if(t){let l=t[n].start;const u=t.event;if(u){if("playout"===n||u.timelineOccupancy!==eb.Point){const e=r(s);(null==e?void 0:e.interstitial)===u&&(l+=e.assetItem.startOffset+e[o])}}else{l+=("bufferedPos"===a?i():e[a])-t.start}return l}return 0},i=()=>{const t=e.bufferedPos;return t===Number.MAX_VALUE?s("primary"):Math.max(t,0)},s=t=>{var r,n;return null!=(r=e.primaryDetails)&&r.live?e.primaryDetails.edge:(null==(n=e.schedule)?void 0:n.durations[t])||0},a=(t,i)=>{var s,a;const o=e.effectivePlayingItem;if(null!=o&&null!=(s=o.event)&&s.restrictions.skip||!e.schedule)return;e.log(`seek to ${t} "${i}"`);const l=e.effectivePlayingItem,u=e.schedule.findItemIndexAtTime(t,i),c=null==(a=e.schedule.items)?void 0:a[u],d=e.getBufferingPlayer(),h=null==d?void 0:d.interstitial,f=null==h?void 0:h.appendInPlace,p=l&&e.itemsMatch(l,c);if(l&&(f||p)){const s=r(e.playingAsset),a=(null==s?void 0:s.media)||e.primaryMedia;if(a){const r="primary"===i?a.currentTime:n(l,i,e.playingAsset,"timelinePos","currentTime"),o=t-r,u=(f?r:a.currentTime)+o;if(u>=0&&(!s||f||u<=s.duration))return void(a.currentTime=u)}}if(c){let r=t;if("primary"!==i){const e=t-c[i].start;r=c.start+e}const n=!e.isInterstitial(c);if(e.isInterstitial(l)&&!l.event.appendInPlace||!n&&!c.event.appendInPlace){if(l){const s=e.findItemIndex(l);if(u>s){const t=e.schedule.findJumpRestrictedIndex(s+1,u);if(t>s)return void e.setSchedulePosition(t)}let a=0;if(n)e.timelinePos=r,e.checkBuffer();else{const e=c.event.assetList,r=t-(c[i]||c).start;for(let t=e.length;t--;){const n=e[t];if(n.duration&&r>=n.startOffset&&r<n.startOffset+n.duration){a=t;break}}}e.setSchedulePosition(u,a)}}else{const t=e.media||(f?null==d?void 0:d.media:null);t&&(t.currentTime=r)}}},o=()=>{const r=e.effectivePlayingItem;if(e.isInterstitial(r))return r;const n=t();return e.isInterstitial(n)?n:null},l={get bufferedEnd(){const r=t(),i=e.bufferingItem;var s;return i&&i===r&&(n(i,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-i.playout.start||(null==(s=e.bufferingAsset)?void 0:s.startOffset))||0},get currentTime(){const t=o(),r=e.effectivePlayingItem;return r&&r===t?n(r,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-r.playout.start:0},set currentTime(t){const r=o(),n=e.effectivePlayingItem;n&&n===r&&a(t+n.playout.start,"playout")},get duration(){const e=o();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t;const r=null==(t=o())?void 0:t.event.assetList;return r?r.map(t=>e.getAssetPlayer(t.identifier)):[]},get playingIndex(){var t;const r=null==(t=o())?void 0:t.event;return r&&e.effectivePlayingAsset?r.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var t;return(null==(t=e.schedule)||null==(t=t.events)?void 0:t.slice(0))||[]},get schedule(){var t;return(null==(t=e.schedule)||null==(t=t.items)?void 0:t.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const r=t();return e.findItemIndex(r)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return i()},get currentTime(){const t=e.timelinePos;return t>0?t:0},set currentTime(e){a(e,"primary")},get duration(){return s("primary")},get seekableStart(){var t;return(null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0}},integrated:{get bufferedEnd(){return n(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return n(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){a(e,"integrated")},get duration(){return s("integrated")},get seekableStart(){var t;return((t,r)=>{var n;if(0!==t&&"primary"!==r&&null!=(n=e.schedule)&&n.length){var i;const n=e.schedule.findItemIndexAtTime(t),s=null==(i=e.schedule.items)?void 0:i[n];if(s)return t+(s[r].start-s.start)}return t})((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"integrated")}},skip:()=>{const t=e.effectivePlayingItem,r=null==t?void 0:t.event;if(r&&!r.restrictions.skip){const n=e.findItemIndex(t);if(r.appendInPlace){const e=t.playout.start+t.event.duration;a(e+.001,"playout")}else e.advanceAfterAssetEnded(r,n,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,r=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&r)&&this.findItemIndex(t)===r.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var e,t;if(null===this.mediaSelection)return;const r=this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&!r.event.appendInPlace)return;let n=this.media;!n&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(n=this.primaryMedia);const i=null==(t=n)?void 0:t.currentTime;return void 0!==i&&Ad(i)?i:void 0}get primaryMedia(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}isInterstitial(e){return!(null==e||!e.event)}retreiveMediaSource(e,t){const r=this.getAssetPlayer(e);r&&this.transferMediaFromPlayer(r,t)}transferMediaFromPlayer(e,t){const r=e.interstitial.appendInPlace,n=e.media;if(r&&n===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&n)return void(this.detachedData={media:n});const r=e.transferMedia();this.log(`transfer MediaSource from ${e} ${Rf(r)}`),this.detachedData=r}else t&&n&&(this.shouldPlay||(this.shouldPlay=!n.paused))}transferMediaTo(e,t){var r,n;if(e.media===t)return;let i=null;const s=this.hls,a=e!==s,o=a&&e.interstitial.appendInPlace,l=null==(r=this.detachedData)?void 0:r.mediaSource;let u;if(s.media)o&&(i=s.transferMedia(),this.detachedData=i),u="Primary";else if(l){const e=this.getBufferingPlayer();e?(i=e.transferMedia(),u=`${e}`):u="detached MediaSource"}else u="detached media";if(!i)if(l)i=this.detachedData,this.log(`using detachedData: MediaSource ${Rf(i)}`);else if(!this.detachedData||s.media===t){const e=this.playerQueue;e.length>1&&e.forEach(e=>{if(a&&e.interstitial.appendInPlace!==o){const t=e.interstitial;this.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${t}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}const c=i&&"mediaSource"in i&&"closed"!==(null==(n=i.mediaSource)?void 0:n.readyState),d=c&&i?i:t;this.log(`${c?"transfering MediaSource":"attaching media"} to ${a?e:"Primary"} from ${u} (media.currentTime: ${t.currentTime})`);const h=this.schedule;if(d===i&&h){const t=a&&e.assetId===h.assetIdAtEnd;d.overrides={duration:h.duration,endOfStream:!a||t,cueRemoval:!a}}e.attachMedia(d)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=null==e?void 0:e.events;if(!t||this.playbackDisabled||!this.media)return;-1===this.bufferedPos&&(this.bufferedPos=0);const r=this.timelinePos,n=this.effectivePlayingItem;if(-1===r){const r=this.hls.startPosition;if(this.log(hb("checkStart",r)),this.timelinePos=r,t.length&&t[0].cue.pre){const r=e.findEventIndex(t[0].identifier);this.setSchedulePosition(r)}else if(r>=0||!this.primaryLive){const t=this.timelinePos=r>0?r:0,n=e.findItemIndexAtTime(t);this.setSchedulePosition(n)}}else if(n&&!this.playingItem){const t=e.findItemIndex(n);this.setSchedulePosition(t)}}advanceAssetBuffering(e,t){const r=e.event,n=r.findAssetIndex(t),i=sb(r,n);if(r.isAssetPastPlayoutLimit(i)){if(this.schedule){var s;const t=null==(s=this.schedule.items)?void 0:s[this.findItemIndex(e)+1];t&&this.bufferedToItem(t)}}else this.bufferedToEvent(e,i)}advanceAfterAssetEnded(e,t,r){const n=sb(e,r);if(e.isAssetPastPlayoutLimit(n)){if(this.schedule){const r=this.schedule.items;if(r){const n=t+1;if(n>=r.length)return void this.setSchedulePosition(-1);const i=e.resumeTime;this.timelinePos<i&&(this.log(hb("advanceAfterAssetEnded",i)),this.timelinePos=i,e.appendInPlace&&this.advanceInPlace(i),this.checkBuffer(this.bufferedPos<i)),this.setSchedulePosition(n)}}}else{if(e.appendInPlace){const t=e.assetList[n];t&&this.advanceInPlace(t.timelineStart)}this.setSchedulePosition(t,n)}}setScheduleToAssetAtTime(e,t){const r=this.schedule;if(!r)return;const n=t.parentIdentifier,i=r.getEvent(n);if(i){const t=r.findEventIndex(n),s=r.findAssetIndex(i,e);this.advanceAfterAssetEnded(i,t,s-1)}}setSchedulePosition(e,t){var r;const n=null==(r=this.schedule)?void 0:r.items;if(!n||this.playbackDisabled)return;const i=e>=0?n[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${i?ub(i):i}) pos: ${this.timelinePos}`);const s=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(s)){const r=s.event,u=this.playingAsset,c=null==u?void 0:u.identifier,d=c?this.getAssetPlayer(c):null;if(d&&c&&(!this.eventItemsMatch(s,i)||void 0!==t&&c!==r.assetList[t].identifier)){var o;const t=r.findAssetIndex(u);if(this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${r.assetList.length} ${ab(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(Pd.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:t,event:r,schedule:n.slice(0),scheduleIndex:e,player:d}),s!==this.playingItem)return void(this.itemsMatch(s,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(r,this.findItemIndex(this.playingItem),t));this.retreiveMediaSource(c,i),!d.media||null!=(o=this.detachedData)&&o.mediaSource||d.detachMedia()}if(!this.eventItemsMatch(s,i)&&(this.endedItem=s,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${r} ${ub(s)}`),r.hasPlayed=!0,this.hls.trigger(Pd.INTERSTITIAL_ENDED,{event:r,schedule:n.slice(0),scheduleIndex:e}),r.cue.once)){var l;this.updateSchedule();const e=null==(l=this.schedule)?void 0:l.items;if(i&&e){const r=this.findItemIndex(i);this.advanceSchedule(r,e,t,s,a)}return}}this.advanceSchedule(e,n,t,s,a)}advanceSchedule(e,t,r,n,i){const s=this.schedule;if(!s)return;const a=t[e]||null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(t=>{const r=t.interstitial,n=s.findEventIndex(r.identifier);(n<e||n>e+1)&&this.clearInterstitial(r,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const i=a.event;if(void 0===r){const t=sb(i,(r=s.findAssetIndex(i,this.timelinePos))-1);if(i.isAssetPastPlayoutLimit(t)||i.appendInPlace&&this.timelinePos===a.end)return void this.advanceAfterAssetEnded(i,e,r);r=t}const l=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let u=this.preloadAssets(i,r);if(this.eventItemsMatch(a,l||n)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${ub(a)} ${i.appendInPlace?"append in place":""}`),this.hls.trigger(Pd.INTERSTITIAL_STARTED,{event:i,schedule:t.slice(0),scheduleIndex:e})),!i.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${i}`);if(i.assetListLoader&&(i.assetListLoader.destroy(),i.assetListLoader=void 0),!o)return void this.log(`Waiting for attachMedia to start Interstitial ${i}`);this.waitingItem=this.endedItem=null,this.playingItem=a;const c=i.assetList[r];if(!c)return void this.advanceAfterAssetEnded(i,e,r||0);if(u||(u=this.getAssetPlayer(c.identifier)),null===u||u.destroyed){const e=i.assetList.length;this.warn(`asset ${r+1}/${e} player destroyed ${i}`),u=this.createAssetPlayer(i,c,r),u.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&i.appendInPlace&&this.isAssetBuffered(c))return;this.startAssetPlayer(u,r,t,e,o),this.shouldPlay&&db(u.media)}else a?(this.resumePrimary(a,e,n),this.shouldPlay&&db(this.hls.media)):i&&this.isInterstitial(n)&&(this.endedItem=null,this.playingItem=n,n.event.appendInPlace||this.attachPrimary(s.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}get primaryLive(){var e;return!(null==(e=this.primaryDetails)||!e.live)}resumePrimary(e,t,r){var n,i;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${ub(e)}`),null==(n=this.detachedData)||!n.mediaSource){let r=this.timelinePos;(r<e.start||r>=e.end)&&(r=this.getPrimaryResumption(e,t),this.log(hb("resumePrimary",r)),this.timelinePos=r),this.attachPrimary(r,e)}if(!r)return;const s=null==(i=this.schedule)?void 0:i.items;s&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${ub(e)}`),this.hls.trigger(Pd.INTERSTITIALS_PRIMARY_RESUMED,{schedule:s.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const r=e.start;if(this.primaryLive){const e=this.primaryDetails;if(0===t)return this.hls.startPosition;if(e&&(r<e.fragmentStart||r>e.edge))return this.hls.liveSyncPosition||-1}return r}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);if(null!=t&&t.hls)return t.hls.bufferedToEnd;return Ap.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,r){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const n=this.primaryMedia;if(!n)return;const i=this.hls;i.media?this.checkBuffer():(this.transferMediaTo(i,n),r&&this.startLoadingPrimaryAt(e,r)),r||(this.log(hb("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,r))}startLoadingPrimaryAt(e,t){var r;const n=this.hls;!n.loadingEnabled||!n.media||Math.abs(((null==(r=n.mainForwardBufferInfo)?void 0:r.start)||n.media.currentTime)-e)>.5?n.startLoad(e,t):n.bufferingEnabled||n.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),null==(e=this.schedule)||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(Pd.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(Pd.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(-1===t.level||!this.schedule)return;const r=this.hls.levels[t.level];if(!r.details)return;const n=Hd(Hd({},this.mediaSelection||this.altSelection),{},{main:r});this.mediaSelection=n,this.schedule.parseInterstitialDateRanges(n,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const r=this.hls.audioTracks[t.id],n=this.mediaSelection;if(!n)return void(this.altSelection=Hd(Hd({},this.altSelection),{},{audio:r}));const i=Hd(Hd({},n),{},{audio:r});this.mediaSelection=i}onSubtitleTrackUpdated(e,t){const r=this.hls.subtitleTracks[t.id],n=this.mediaSelection;if(!n)return void(this.altSelection=Hd(Hd({},this.altSelection),{},{subtitles:r}));const i=Hd(Hd({},n),{},{subtitles:r});this.mediaSelection=i}onAudioTrackSwitching(e,t){const r=Cf(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setAudioOption(t)||e.setAudioOption(r)))}onSubtitleTrackSwitch(e,t){const r=Cf(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setSubtitleOption(t)||-1!==t.id&&e.setSubtitleOption(r)))}onBufferCodecs(e,t){const r=t.tracks;r&&(this.requiredTracks=r)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const r=this.playingItem;if(r&&!this.itemsMatch(r,this.bufferingItem)&&!this.isInterstitial(r)){const e=this.timelinePos;this.bufferedPos=e,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let e=0;e<t.length;e++){const n=t[e];if(n.cue.post){var r;const e=this.schedule.findEventIndex(n.identifier),t=null==(r=this.schedule.items)?void 0:r[e];this.isInterstitial(t)&&this.eventItemsMatch(t,this.bufferingItem)&&this.bufferedToItem(t,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}else this.shouldPlay=!1}updateItem(e,t){var r;const n=null==(r=this.schedule)?void 0:r.items;if(e&&n){return n[this.findItemIndex(e,t)]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((t,r)=>{e.event.isAssetPastPlayoutLimit(r)&&this.clearAssetPlayer(t.identifier,null)});const r=e.end+.25,n=Ap.bufferInfo(this.primaryMedia,r,0);if(n.end>r||(n.nextStart||0)>r){this.log(`trim buffered interstitial ${ub(e)} (was ${ub(t)})`);const n=!0;this.attachPrimary(r,null,n),this.flushFrontBuffer(r)}}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var r;return!!t&&(e===t||e.event.identifier===(null==(r=t.event)?void 0:r.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const r=this.mediaSelection;r&&(null==(t=this.schedule)||t.updateSchedule(r,[],e))}checkBuffer(e){var t;const r=null==(t=this.schedule)?void 0:t.items;if(!r)return;const n=Ap.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=n.len<1),this.updateBufferedPos(n.end,r,e)}updateBufferedPos(e,t,r){const n=this.schedule,i=this.bufferingItem;if(this.bufferedPos>e||!n)return;if(1===t.length&&this.itemsMatch(t[0],i))return void(this.bufferedPos=e);const s=this.playingItem,a=this.findItemIndex(s);let o=n.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const r=this.findItemIndex(i),n=Math.min(r+1,t.length-1),s=t[n];if((-1===o&&i&&e>=i.end||null!=(l=s.event)&&l.appendInPlace&&e+.01>=s.start)&&(o=n),this.isInterstitial(i)){const e=i.event;if(n-a>1&&!1===e.appendInPlace)return;if(0===e.assetList.length&&e.assetListLoader)return}if(this.bufferedPos=e,o>r&&o>a)this.bufferedToItem(s);else{const t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&s.start<t.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(s)&&this.preloadAssets(s.event,0)}}else r&&s&&!this.itemsMatch(s,i)&&(o===a?this.bufferedToItem(s):o===a+1&&this.bufferedToItem(t[o]))}assetsBuffered(e,t){return 0!==e.event.assetList.length&&!e.event.assetList.some(e=>{const r=this.getAssetPlayer(e.identifier);return!(null!=r&&r.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,r=this.schedule;if(!this.itemsMatch(e,t)&&r){const{items:n,events:i}=r;if(!n||!i)return t;const s=this.isInterstitial(e),a=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const o=a?a.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${ub(e)}`+(t?` (${o.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(s){const t=r.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((e,r)=>{const n=this.getAssetPlayer(e.identifier);n&&(r===t&&n.loadSource(),n.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(e=>e.pauseBuffering());this.hls.trigger(Pd.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:i.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const r=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==r){this.bufferingAsset=null;const t=this.detachedData;if(t)if(t.mediaSource){const t=!0;this.attachPrimary(e.start,e,t)}else this.preloadPrimary(e);else this.preloadPrimary(e)}}preloadPrimary(e){const t=this.findItemIndex(e),r=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(r)}bufferedToEvent(e,t){const r=e.event,n=0===r.assetList.length&&!r.assetListLoader,i=r.cue.once;if(n||!i){const e=this.preloadAssets(r,t);if(null!=e&&e.interstitial.appendInPlace){const t=this.primaryMedia;t&&this.bufferAssetPlayer(e,t)}}}preloadAssets(e,t){const r=e.assetUrl,n=e.assetList.length,i=0===n&&!e.assetListLoader,s=e.cue.once;if(i){const i=e.timelineStart;if(e.appendInPlace){var a;const t=this.playingItem;this.isInterstitial(t)||(null==t||null==(a=t.nextEvent)?void 0:a.identifier)!==e.identifier||this.flushFrontBuffer(i+.25)}let s,o=0;if(!this.playingItem&&this.primaryLive&&(o=this.hls.startPosition,-1===o&&(o=this.hls.liveSyncPosition||0)),o&&!e.cue.pre&&!e.cue.post){const e=o-i;e>0&&(s=Math.round(1e3*e)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${r?1:n} ${e}${s?` live-start: ${o} start-offset: ${s}`:""}`),r)return this.createAsset(e,0,0,i,e.duration,r);const l=this.assetListLoader.loadAssetList(e,s);l&&(e.assetListLoader=l)}else if(!s&&n){for(let r=t;r<n;r++){const t=e.assetList[r],n=this.getAssetPlayerQueueIndex(t.identifier);-1!==n&&!this.playerQueue[n].destroyed||t.error||this.createAssetPlayer(e,t,r)}const r=e.assetList[t];if(r){const e=this.getAssetPlayer(r.identifier);return e&&e.loadSource(),e}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`);Object.keys(t).forEach(t=>{this.hls.trigger(Pd.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let r=0;r<t.length;r++)if(e===t[r].assetId)return r;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t)for(let r=0;r<e.length;r++)if(e[r].media===t)return e[r];return null}createAsset(e,t,r,n,i,s){const a={parentIdentifier:e.identifier,identifier:tb(e,s,t),duration:i,startOffset:r,timelineStart:n,uri:s};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,r){const n=this.hls,i=n.userConfig;let s=i.videoPreference;const a=n.loadLevelObj||n.levels[n.currentLevel];(s||a)&&(s=jd({},s),a.videoCodec&&(s.videoCodec=a.videoCodec),a.videoRange&&(s.allowedVideoRanges=[a.videoRange]));const o=n.audioTracks[n.audioTrack],l=n.subtitleTracks[n.subtitleTrack];let u=0;if(this.primaryLive||e.appendInPlace){const e=this.timelinePos-t.timelineStart;if(e>1){const r=t.duration;r&&e<r&&(u=e)}}const c=t.identifier,d=Hd(Hd({},i),{},{maxMaxBufferLength:Math.min(180,n.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:c,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:s,audioPreference:o||i.audioPreference,subtitlePreference:l||i.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(d.timelineOffset=t.timelineStart));const h=d.cmcd;null!=h&&h.sessionId&&h.contentId&&(d.cmcd=jd({},h,{contentId:Zy(t.uri)})),this.getAssetPlayer(c)&&this.warn(`Duplicate date range identifier ${e} and asset ${c}`);const f=new ob(this.HlsPlayerClass,d,e,t);this.playerQueue.push(f),e.assetList[r]=t;let p=!0;const g=n=>{if(n.live){var i;const t=new Error(`Interstitials MUST be VOD assets ${e}`),n={fatal:!0,type:Id.OTHER_ERROR,details:Cd.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},s=(null==(i=this.schedule)?void 0:i.findEventIndex(e.identifier))||-1;return void this.handleAssetItemError(n,e,s,r,t.message)}const s=n.edge-n.fragmentStart,a=t.duration;(p||null===a||s>a)&&(p=!1,this.log(`Interstitial asset "${c}" duration change ${a} > ${s}`),t.duration=s,this.updateSchedule())};f.on(Pd.LEVEL_UPDATED,(e,{details:t})=>g(t)),f.on(Pd.LEVEL_PTS_UPDATED,(e,{details:t})=>g(t)),f.on(Pd.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const m=(e,t)=>{const r=this.getAssetPlayer(c);if(r&&t.tracks){r.off(Pd.BUFFER_CODECS,m),r.tracks=t.tracks;const e=this.primaryMedia;this.bufferingAsset===r.assetItem&&e&&!r.media&&this.bufferAssetPlayer(r,e)}};f.on(Pd.BUFFER_CODECS,m);f.on(Pd.BUFFERED_TO_END,()=>{var r;const n=this.getAssetPlayer(c);if(this.log(`buffered to end of asset ${n}`),!n||!this.schedule)return;const i=this.schedule.findEventIndex(e.identifier),s=null==(r=this.schedule.items)?void 0:r[i];this.isInterstitial(s)&&this.advanceAssetBuffering(s,t)});const v=t=>()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;this.shouldPlay=!0;const r=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,r,t)};return f.once(Pd.MEDIA_ENDED,v(r)),f.once(Pd.PLAYOUT_LIMIT_REACHED,v(1/0)),f.on(Pd.ERROR,(t,n)=>{if(!this.schedule)return;const i=this.getAssetPlayer(c);if(n.details===Cd.BUFFER_STALLED_ERROR)return null!=i&&i.appendInPlace?void this.handleInPlaceStall(e):(this.onTimeupdate(),void this.checkBuffer(!0));this.handleAssetItemError(n,e,this.schedule.findEventIndex(e.identifier),r,`Asset player error ${n.error} ${e}`)}),f.on(Pd.DESTROYING,()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;const t=new Error(`Asset player destroyed unexpectedly ${c}`),n={fatal:!0,type:Id.OTHER_ERROR,details:Cd.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(n,e,this.schedule.findEventIndex(e.identifier),r,t.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${ab(t)}`),this.hls.trigger(Pd.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:r,event:e,player:f}),f}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log(`reset asset player "${e}" after error`);const r=this.playerQueue[t];this.transferMediaFromPlayer(r,null),r.resetDetails()}}clearAssetPlayer(e,t){const r=this.getAssetPlayerQueueIndex(e);if(-1!==r){const e=this.playerQueue[r];this.log(`clear ${e} toSegment: ${t?ub(t):t}`),this.transferMediaFromPlayer(e,t),this.playerQueue.splice(r,1),e.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,r,n,i){const{interstitial:s,assetItem:a,assetId:o}=e,l=s.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=a,u&&u.identifier===o||(u&&(this.clearAssetPlayer(u.identifier,r[n]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${ab(a)}`),this.hls.trigger(Pd.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:s,schedule:r.slice(0),scheduleIndex:n,player:e})),this.bufferAssetPlayer(e,i)}bufferAssetPlayer(e,t){var r,n;if(!this.schedule)return;const{interstitial:i,assetItem:s}=e,a=this.schedule.findEventIndex(i.identifier),o=null==(r=this.schedule.items)?void 0:r[a];if(!o)return;e.loadSource(),this.setBufferingItem(o),this.bufferingAsset=s;const l=this.getBufferingPlayer();if(l===e)return;const u=i.appendInPlace;if(u&&!1===(null==l?void 0:l.interstitial.appendInPlace))return;const c=(null==l?void 0:l.tracks)||(null==(n=this.detachedData)?void 0:n.tracks)||this.requiredTracks;if(u&&s!==this.playingAsset){if(!e.tracks)return void this.log(`Waiting for track info before buffering ${e}`);if(c&&!Jd(c,e.tracks)){const t=new Error(`Asset ${ab(s)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(c)}')`),r={fatal:!0,type:Id.OTHER_ERROR,details:Cd.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},n=i.findAssetIndex(s);return void this.handleAssetItemError(r,i,a,n,t.message)}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,r=this.primaryMedia;if(!t||!r)return;const n=r.currentTime,i=t.findAssetIndex(e,n),s=e.assetList[i];if(s){const a=this.getAssetPlayer(s.identifier);if(a){const o=a.currentTime||n-s.timelineStart,l=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+l} in ${a} ${e} (media.currentTime: ${n})`),o&&(l/r.playbackRate<.5||a.bufferedInPlaceToEnd(r))&&a.hls){const r=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,r,i)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,r,n,i){if(e.details===Cd.BUFFER_STALLED_ERROR)return;const s=t.assetList[n]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${s?ab(s):s} ${e.error}`),!this.schedule)return;const a=(null==s?void 0:s.identifier)||"",o=this.getAssetPlayerQueueIndex(a),l=this.playerQueue[o]||null,u=this.schedule.items,c=jd({},e,{fatal:!1,errorAction:np(!0),asset:s,assetListIndex:n,event:t,schedule:u,scheduleIndex:r,player:l});if(this.hls.trigger(Pd.INTERSTITIAL_ASSET_ERROR,c),!e.fatal)return;const d=this.playingAsset,h=this.bufferingAsset,f=new Error(i);if(s&&(this.clearAssetPlayer(a,null),s.error=f),t.assetList.some(e=>!e.error))for(let e=n;e<t.assetList.length;e++)this.resetAssetPlayer(t.assetList[e].identifier);else t.error=f;this.updateSchedule(!0),t.error?this.primaryFallback(t):d&&d.identifier===a?this.advanceAfterAssetEnded(t,r,n):h&&h.identifier===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,h)}primaryFallback(e){const t=e.timelineStart,r=this.effectivePlayingItem;let n=this.timelinePos;if(r){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${n} playing: ${ub(r)} error: ${e.error}`),-1===n&&(n=this.hls.startPosition);const i=this.updateItem(r,n);this.itemsMatch(r,i)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(-1===n)return void this.checkStart();if(!this.schedule)return;const i=this.schedule.findItemIndexAtTime(n);this.setSchedulePosition(i)}onAssetListLoaded(e,t){var r,n;const i=t.event,s=i.identifier,a=t.assetListResponse.ASSETS;if(null==(r=this.schedule)||!r.hasEvent(s))return;const o=i.timelineStart,l=i.duration;let u=0;a.forEach((e,t)=>{const r=parseFloat(e.DURATION);this.createAsset(i,t,u,o+u,r,e.URI),u+=r}),i.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${l}) ${i}`);const c=this.waitingItem,d=(null==c?void 0:c.event.identifier)===s;this.updateSchedule();const h=null==(n=this.bufferingItem)?void 0:n.event;if(d){var f;const e=this.schedule.findEventIndex(s),t=null==(f=this.schedule.items)?void 0:f[e];if(t){if(!this.playingItem&&this.timelinePos>t.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==e)return i.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${i}`),this.log(i.error.message),this.updateSchedule(!0),void this.primaryFallback(i)}this.setBufferingItem(t)}this.setSchedulePosition(e)}else if((null==h?void 0:h.identifier)===s){const e=i.assetList[0];if(e){const t=this.getAssetPlayer(e.identifier);if(h.appendInPlace){const e=this.primaryMedia;t&&e&&this.bufferAssetPlayer(t,e)}else t&&t.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case Cd.ASSET_LIST_PARSING_ERROR:case Cd.ASSET_LIST_LOAD_ERROR:case Cd.ASSET_LIST_LOAD_TIMEOUT:{const e=t.interstitial;e&&(this.updateSchedule(!0),this.primaryFallback(e));break}case Cd.BUFFER_STALLED_ERROR:{const e=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(e)&&e.event.appendInPlace)return void this.handleInPlaceStall(e.event);this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}});function vw(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(vw):Object.keys(e).reduce((t,r)=>(t[r]=vw(e[r]),t),{}):e}function yw(e,t){const r=e.loader;if(r!==dw&&r!==gw)t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1})()&&(e.loader=dw,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class bw extends Tp{constructor(e,t){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 e;null!=(e=this.media)&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var e;this.hls&&(this.ended=(null==(e=this.media)?void 0:e.currentTime)||1,this.hls.trigger(Pd.MEDIA_ENDED,{stalled:!1}))},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(Pd.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Pd.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Pd.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(Pd.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Pd.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Pd.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;const r=this.media=t.media;Gg(r,"playing",this.onMediaPlaying),Gg(r,"waiting",this.onMediaWaiting),Gg(r,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:r}=this;r&&(Hg(r,"playing",this.onMediaPlaying),Hg(r,"waiting",this.onMediaWaiting),Hg(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(null==(e=this.media)||!e.readyState||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var r,n;const i=null==(r=this.hls)?void 0:r.config;if(!i)return;const s=this.media;if(!s)return;const{seeking:a}=s,o=this.seeking&&!a,l=!this.seeking&&a,u=s.paused&&!a||s.ended||0===s.playbackRate;if(this.seeking=a,e!==t)return t&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,i.nudgeOnVideoHole&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(l||o)return void(o&&this.stallResolved(e));if(u)return this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&s.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(Pd.MEDIA_ENDED,{stalled:!1})));if(!Ap.getBuffered(s).length)return void(this.nudgeRetry=0);const c=Ap.bufferInfo(s,e,0),d=c.nextStart||0,h=this.fragmentTracker;if(a&&h&&this.hls){const t=ww(this.hls.inFlightFragments,e),r=c.len>2,n=!d||t||d-e>2&&!h.getPartialFragment(e);if(r||n)return;this.moved=!1}const f=null==(n=this.hls)?void 0:n.latestLevelDetails;if(!this.moved&&null!==this.stalled&&h){if(!(c.len>0)&&!d)return;const t=Math.max(d,c.start||0)-e,r=!(null==f||!f.live)?2*f.targetduration:2,n=Sw(e,h);if(t>0&&(t<=r||n))return void(s.paused||this._trySkipBufferHole(n))}const p=i.detectStallWithCurrentTimeMs,g=self.performance.now(),m=this.waiting;let v=this.stalled;if(null===v){if(!(m>0&&g-m<p))return void(this.stalled=g);v=this.stalled=m}const y=g-v;if(!a&&(y>=p||m)&&this.hls){var b;if("ended"===(null==(b=this.mediaSource)?void 0:b.readyState)&&(null==f||!f.live)&&Math.abs(e-((null==f?void 0:f.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(Pd.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(c),!this.media||!this.hls)return}const w=Ap.bufferInfo(s,e,i.maxBufferHole);this._tryFixBufferStall(w,y,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const r=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(r)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(Pd.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var r;const n=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(r=this.buffered.audio)&&r.length&&n&&n.length>1&&e>n.end(0)){const r=Ap.bufferedInfo(Ap.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const r=Ap.timeRangesToArray(n),i=Ap.bufferedInfo(r,t,0).bufferedIndex;if(i>-1&&i<r.length-1){const t=Ap.bufferedInfo(r,e,0).bufferedIndex,n=r[i].end,s=r[i+1].start;if((-1===t||t>i)&&s-n<1&&e-n<2){const r=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${n} -> ${s} buffered index: ${t}`);this.warn(r.message),this.media.currentTime+=1e-6;let i=Sw(e,this.fragmentTracker);i&&"fragment"in i?i=i.fragment:i||(i=void 0);const a=Ap.bufferInfo(this.media,e,0);this.hls.trigger(Pd.ERROR,{type:Id.MEDIA_ERROR,details:Cd.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:r,reason:r.message,frag:i,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(e,t,r){var n,i;const{fragmentTracker:s,media:a}=this,o=null==(n=this.hls)?void 0:n.config;if(!a||!s||!o)return;const l=null==(i=this.hls)?void 0:i.latestLevelDetails,u=Sw(r,s);if(u||null!=l&&l.live&&r<l.fragmentStart){if(this._trySkipBufferHole(u)||!this.media)return}const c=e.buffered,d=this.adjacentTraversal(e,r);(c&&c.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-r<o.maxBufferHole||d))&&(t>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const r=this.fragmentTracker,n=e.nextStart;if(r&&n){const e=r.getFragAtPos(t,Nd),i=r.getFragAtPos(n,Nd);if(e&&i)return i.sn-e.sn<2}return!1}_reportStall(e){const{hls:t,media:r,stallReported:n,stalled:i}=this;if(!n&&null!==i&&r&&t){this.stallReported=!0;const n=new Error(`Playback stalling at @${r.currentTime} due to low buffer (${Rf(e)})`);this.warn(n.message),t.trigger(Pd.ERROR,{type:Id.MEDIA_ERROR,details:Cd.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len,bufferInfo:e,stalled:{start:i}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:r,media:n}=this,i=null==(t=this.hls)?void 0:t.config;if(!n||!r||!i)return 0;const s=n.currentTime,a=Ap.bufferInfo(n,s,0),o=s<a.start?a.start:a.nextStart;if(o&&this.hls){const t=a.len<=i.maxBufferHole,u=a.len>0&&a.len<1&&n.readyState<3,c=o-s;if(c>0&&(t||u)){if(c>i.maxBufferHole){let t=!1;if(0===s){const e=r.getAppendedFrag(0,Nd);e&&o<e.end&&(t=!0)}if(!t&&e){var l;if(null==(l=this.hls.loadLevelObj)||!l.details)return 0;if(ww(this.hls.inFlightFragments,o))return 0;let t=!1,n=e.end;for(;n<o;){const e=Sw(n,r);if(!e){t=!0;break}n+=e.duration}if(t)return 0}}const t=Math.max(o+.05,s+.1);if(this.warn(`skipping hole, adjusting currentTime from ${s} to ${t}`),this.moved=!0,n.currentTime=t,null==e||!e.gap){const r=new Error(`fragment loaded with buffer holes, seeking from ${s} to ${t}`),n={type:Id.MEDIA_ERROR,details:Cd.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:r,reason:r.message,buffer:a.len,bufferInfo:a};e&&("fragment"in e?n.part=e:n.frag=e),this.hls.trigger(Pd.ERROR,n)}return t}}return 0}_tryNudgeBuffer(e){const{hls:t,media:r,nudgeRetry:n}=this,i=null==t?void 0:t.config;if(!r||!i)return 0;const s=r.currentTime;if(this.nudgeRetry++,n<i.nudgeMaxRetry){const a=s+(n+1)*i.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${s} to ${a}`);this.warn(o.message),r.currentTime=a,t.trigger(Pd.ERROR,{type:Id.MEDIA_ERROR,details:Cd.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{const r=new Error(`Playhead still not moving while enough data buffered @${s} after ${i.nudgeMaxRetry} nudges`);this.error(r.message),t.trigger(Pd.ERROR,{type:Id.MEDIA_ERROR,details:Cd.BUFFER_STALLED_ERROR,error:r,fatal:!0,buffer:e.len,bufferInfo:e})}}}function ww(e,t){const r=Ew(e.main);if(r&&r.start<=t)return r;const n=Ew(e.audio);return n&&n.start<=t?n:null}function Ew(e){if(!e)return null;switch(e.state){case Kg:case Wg:case em:case tm:return null}return e.frag}function Sw(e,t){return t.getAppendedFrag(e,Nd)||t.getPartialFragment(e)}function Tw(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function xw(e,t,r,n,i){let s=new e(t,r,"");try{s.value=n,i&&(s.type=i)}catch(a){s=new e(t,r,Rf(i?Hd({type:i},n):n))}return s}const kw=(()=>{const e=Tw();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Aw{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(Pd.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(Pd.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Pd.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Pd.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Pd.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(Pd.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Pd.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Pd.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(Pd.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Pd.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Pd.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Pd.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(Pd.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Pd.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Pd.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var r;this.media=t.media,!1===(null==(r=t.overrides)?void 0:r.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){var e;const t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null;!!t.transferMedia||(this.id3Track&&(this.removeCues&&qy(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const r=e[t];if("metadata"===r.kind&&"id3"===r.label)return Ky(r,this.media),r}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:r,enableID3MetadataCues:n}=this.hls.config;if(!r&&!n)return;const{samples:i}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const s=Tw();if(s)for(let e=0;e<i.length;e++){const t=i[e].type;if(t===Mm.emsg&&!r||!n)continue;const a=Cm(i[e].data),o=i[e].pts;let l=o+i[e].duration;l>kw&&(l=kw);l-o<=0&&(l=o+.25);for(let e=0;e<a.length;e++){const r=a[e];if(!Pm(r)){this.updateId3CueEnds(o,t);const e=xw(s,o,l,r,t);e&&this.id3Track.addCue(e)}}}}updateId3CueEnds(e,t){var r;const n=null==(r=this.id3Track)?void 0:r.cues;if(n)for(let r=n.length;r--;){const i=n[r];i.type===t&&i.startTime<e&&i.endTime===kw&&(i.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:r,type:n}){const{id3Track:i,hls:s}=this;if(!s)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=s;if(i&&(a||o)){let e;e="audio"===n?e=>e.type===Mm.audioId3&&o:"video"===n?e=>e.type===Mm.emsg&&a:e=>e.type===Mm.audioId3&&o||e.type===Mm.emsg&&a,Xy(i,t,r,e)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:r,timelineOffset:n,enableDateRangeMetadataCues:i,interstitialsController:s}=this.hls.config;if(!i)return;const a=Tw();if(r&&n&&!s){const{fragmentStart:t,fragmentEnd:n}=e;let i=this.assetCue;i?(i.startTime=t,i.endTime=n):a&&(i=this.assetCue=xw(a,t,n,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),i&&(i.id=r,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(i),i.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=e,u=Object.keys(l);let c=this.dateRangeCuesAppended;var d;if(o&&t)if(null!=(d=o.cues)&&d.length){const e=Object.keys(c).filter(e=>!u.includes(e));for(let t=e.length;t--;){var h;const r=e[t],n=null==(h=c[r])?void 0:h.cues;delete c[r],n&&Object.keys(n).forEach(e=>{const t=n[e];if(t){t.removeEventListener("enter",this.onEventCueEnter);try{o.removeCue(t)}catch(e){}}})}}else c=this.dateRangeCuesAppended={};const f=e.fragments[e.fragments.length-1];if(0!==u.length&&Ad(null==f?void 0:f.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let e=0;e<u.length;e++){const t=u[e],r=l[t],n=r.startTime,i=c[t],o=(null==i?void 0:i.cues)||{};let d=(null==i?void 0:i.durationKnown)||!1,h=kw;const{duration:f,endDate:p}=r;if(p&&null!==f)h=n+f,d=!0;else if(r.endOnNext&&!d){const e=u.reduce((e,t)=>{if(t!==r.id){const n=l[t];if(n.class===r.class&&n.startDate>r.startDate&&(!e||r.startDate<e.startDate))return n}return e},null);e&&(h=e.startTime,d=!0)}const g=Object.keys(r.attr);for(let e=0;e<g.length;e++){const l=g[e];if(!Op(l))continue;const u=o[l];if(u)!d||null!=i&&i.durationKnown?Math.abs(u.startTime-n)>.01&&(u.startTime=n,u.endTime=h):u.endTime=h;else if(a){let e=r.attr[l];Np(l)&&(e=rh(e));const i=xw(a,n,h,{key:l,data:e},Mm.dateRange);i&&(i.id=t,this.id3Track.addCue(i),o[l]=i,s&&("X-ASSET-LIST"!==l&&"X-ASSET-URL"!==l||i.addEventListener("enter",this.onEventCueEnter)))}}c[t]={cues:o,dateRange:r,durationKnown:d}}}}}class Rw{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:e}=this,t=this.levelDetails;if(!e||!t)return;this.currentTime=e.currentTime;const r=this.computeLatency();if(null===r)return;this._latency=r;const{lowLatencyMode:n,maxLiveSyncPlaybackRate:i}=this.config;if(!n||1===i||!t.live)return;const s=this.targetLatency;if(null===s)return;const a=r-s;if(a<Math.min(this.maxLatency,s+t.targetduration)&&a>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,i)),r=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,n=Math.min(t,Math.max(1,r));this.changeMediaPlaybackRate(e,n)}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(null===e||null===this.hls)return null;const{holdBack:t,partHoldBack:r,targetduration:n}=e,{liveSyncDuration:i,liveSyncDurationCount:s,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&r||t;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==i?i:s*n);const u=n;return l+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(),t=this.targetLatency;if(null===e||null===t)return null;const r=this.levelDetails;if(null===r)return null;const n=r.edge,i=e-t-this.edgeStalled,s=n-r.totalduration,a=n-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(s,i),a)}get drift(){const e=this.levelDetails;return null===e?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(Pd.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Pd.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Pd.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Pd.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(Pd.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Pd.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Pd.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Pd.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.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:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var r;t.details===Cd.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(r=this.levelDetails)&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var r,n;e.playbackRate!==t&&(null==(r=this.hls)||r.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(n=this.targetLatency)?void 0:n.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}class Lw extends Nv{constructor(e,t){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=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Pd.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Pd.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Pd.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Pd.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Pd.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Pd.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Pd.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Pd.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Pd.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Pd.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.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,t){this.resetLevels()}onManifestLoaded(e,t){const r=this.hls.config.preferManagedMediaSource,n=[],i={},s={};let a=!1,o=!1,l=!1;t.levels.forEach(e=>{const t=e.attrs;let{audioCodec:u,videoCodec:c}=e;u&&(e.audioCodec=u=nf(u,r)||void 0),c&&(c=e.videoCodec=function(e){const t=e.split(",");for(let e=0;e<t.length;e++){const r=t[e].split(".");r.length>2&&"avc1"===r[0]&&(t[e]=`avc1.${parseInt(r[1]).toString(16)}${("000"+parseInt(r[2]).toString(16)).slice(-4)}`)}return t.join(",")}(c));const{width:d,height:h,unknownCodecs:f}=e,p=(null==f?void 0:f.length)||0;if(a||(a=!(!d||!h)),o||(o=!!c),l||(l=!!u),p||u&&!this.isAudioSupported(u)||c&&!this.isVideoSupported(c))return void this.log(`Some or all CODECS not supported "${t.CODECS}"`);const{CODECS:g,"FRAME-RATE":m,"HDCP-LEVEL":v,"PATHWAY-ID":y,RESOLUTION:b,"VIDEO-RANGE":w}=t,E=`${`${y||"."}-`}${e.bitrate}-${b}-${m}-${g}-${w}-${v}`;if(i[E])if(i[E].uri===e.url||e.attrs["PATHWAY-ID"])i[E].addGroupId("audio",t.AUDIO),i[E].addGroupId("text",t.SUBTITLES);else{const t=s[E]+=1;e.attrs["PATHWAY-ID"]=new Array(t+1).join(".");const r=this.createLevel(e);i[E]=r,n.push(r)}else{const t=this.createLevel(e);i[E]=t,s[E]=1,n.push(t)}}),this.filterAndSortMediaOptions(n,t,a,o,l)}createLevel(e){const t=new xf(e),r=e.supplemental;if(null!=r&&r.videoCodec&&!this.isVideoSupported(r.videoCodec)){const e=new Error(`SUPPLEMENTAL-CODECS not supported "${r.videoCodec}"`);this.log(e.message),t.supportedResult=hf(e,[])}return t}isAudioSupported(e){return Xh(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Xh(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,r,n,i){var s;let a=[],o=[],l=e;const u=(null==(s=t.stats)?void 0:s.parsing)||{};if((r||n)&&i&&(l=l.filter(({videoCodec:e,videoRange:t,width:r,height:n})=>{return(!!e||!(!r||!n))&&(!!(i=t)&&yf.indexOf(i)>-1);var i})),0===l.length)return Promise.resolve().then(()=>{if(this.hls){let e="no level with compatible codecs found in manifest",r=e;t.levels.length&&(r=`one or more CODECS in variant not supported: ${Rf(t.levels.map(e=>e.attrs.CODECS).filter((e,t,r)=>r.indexOf(e)===t))}`,this.warn(r),e+=` (${r})`);const n=new Error(e);this.hls.trigger(Pd.ERROR,{type:Id.MEDIA_ERROR,details:Cd.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:n,reason:r})}}),void(u.end=performance.now());t.audioTracks&&(a=t.audioTracks.filter(e=>!e.audioCodec||this.isAudioSupported(e.audioCodec)),Iw(a)),t.subtitles&&(o=t.subtitles,Iw(o));const c=l.slice(0);l.sort((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return yf.indexOf(e.videoRange)-yf.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){const r=Jh(e.videoCodec),n=Jh(t.videoCodec);if(r!==n)return n-r}if(e.uri===t.uri&&e.codecSet!==t.codecSet){const r=ef(e.codecSet),n=ef(t.codecSet);if(r!==n)return n-r}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0});let d=c[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==c.length))for(let e=0;e<c.length;e++)if(c[e].pathwayId===l[0].pathwayId){d=c[e];break}this._levels=l;for(let e=0;e<l.length;e++)if(l[e]===d){var h;this._firstLevel=e;const t=d.bitrate,r=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${t}`),void 0===(null==(h=this.hls.userConfig)?void 0:h.abrEwmaDefaultEstimate)){const e=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);e>r&&r===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}const f=i&&!n,p=this.hls.config,g=!(!p.audioStreamController||!p.audioTrackController),m={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:i,video:n,altAudio:g&&!f&&a.some(e=>!!e.url)};u.end=performance.now(),this.hls.trigger(Pd.MANIFEST_PARSED,m)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const r=new Error("invalid level idx"),n=e<0;if(this.hls.trigger(Pd.ERROR,{type:Id.OTHER_ERROR,details:Cd.LEVEL_SWITCH_ERROR,level:e,fatal:n,error:r,reason:r.message}),n)return;e=Math.min(e,t.length-1)}const r=this.currentLevelIndex,n=this.currentLevel,i=n?n.attrs["PATHWAY-ID"]:void 0,s=t[e],a=s.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=s,r===e&&n&&i===a)return;this.log(`Switching to level ${e} (${s.height?s.height+"p ":""}${s.videoRange?s.videoRange+" ":""}${s.codecSet?s.codecSet+" ":""}@${s.bitrate})${a?" with Pathway "+a:""} from level ${r}${i?" with Pathway "+i:""}`);const o={level:e,attrs:s.attrs,details:s.details,bitrate:s.bitrate,averageBitrate:s.averageBitrate,maxBitrate:s.maxBitrate,realBitrate:s.realBitrate,width:s.width,height:s.height,codecSet:s.codecSet,audioCodec:s.audioCodec,videoCodec:s.videoCodec,audioGroups:s.audioGroups,subtitleGroups:s.subtitleGroups,loaded:s.loaded,loadError:s.loadError,fragmentError:s.fragmentError,name:s.name,id:s.id,uri:s.uri,url:s.url,urlId:0,audioGroupIds:s.audioGroupIds,textGroupIds:s.textGroupIds};this.hls.trigger(Pd.LEVEL_SWITCHING,o);const l=s.details;if(!l||l.live){const e=this.switchParams(s.uri,null==n?void 0:n.details,l);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?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 t=this.steering.pathways(),r=e.filter(e=>-1!==t.indexOf(e));if(e.length<1)return void this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);this.steering.pathwayPriority=r}}onError(e,t){!t.fatal&&t.context&&t.context.type===_d&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&t.type===Nd){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return;const r=this._levels[t.level];null!=r&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0)}}onLevelLoaded(e,t){var r;const{level:n,details:i}=t,s=t.levelInfo;var a;if(!s)return this.warn(`Invalid level index ${n}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(i.deltaUpdateFailed=!0));if(s===this.currentLevel||t.withoutMultiVariant){0===s.fragmentError&&(s.loadError=0);let e=s.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(n,t,e)}else null!=(r=t.deliveryDirectives)&&r.skip&&(i.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const r=this.getUrlWithDirectives(e.uri,t),n=this.currentLevelIndex,i=e.attrs["PATHWAY-ID"],s=e.details,a=null==s?void 0:s.age;this.log(`Loading level index ${n}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${i?" Pathway "+i:""}${a&&s.live?" age "+a.toFixed(1)+(s.type&&" "+s.type||""):""} ${r}`),this.hls.trigger(Pd.LEVEL_LOADING,{url:r,level:n,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(1===this._levels.length)return;const r=this._levels.filter((t,r)=>r!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(e=>e.level=-1)),!1));Og(r),this._levels=r,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const n=r.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(Pd.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:r}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(Pd.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}function Iw(e){const t={};e.forEach(e=>{const r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++})}function Cw(){return self.SourceBuffer||self.WebKitSourceBuffer}function Pw(){if(!Zd())return!1;const e=Cw();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}class Dw extends im{constructor(e,t,r){super(e,t,r,"stream-controller",Nd),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 e=this.media,t=e?e.currentTime:null;if(null===t||!Ad(t))return;if(this.log(`Media seeked to ${t.toFixed(3)}`),!this.getBufferedFrag(t))return;const r=this.getFwdBufferInfoAtPos(e,t,Nd,0);null!==r&&0!==r.len?this.tick():this.warn(`Main forward buffer length at ${t} on "seeked" event ${r?r.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(Pd.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Pd.LEVEL_LOADING,this.onLevelLoading,this),e.on(Pd.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Pd.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(Pd.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Pd.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(Pd.BUFFER_CREATED,this.onBufferCreated,this),e.on(Pd.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Pd.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Pd.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(Pd.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Pd.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Pd.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(Pd.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Pd.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(Pd.BUFFER_CREATED,this.onBufferCreated,this),e.off(Pd.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Pd.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Pd.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:r,hls:n}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=n.startLevel;-1===e&&(n.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=n.firstAutoLevel),n.nextLoadLevel=e,this.level=n.loadLevel,this._hasEnoughToStart=!!t}r>0&&-1===e&&!t&&(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r),this.state=Kg,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=Wg}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case nm:{const{levels:e,level:t}=this,r=null==e?void 0:e[t],n=null==r?void 0:r.details;if(n&&(!n.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(n))break;this.state=Kg;break}if(this.hls.nextLoadLevel!==this.level){this.state=Kg;break}break}case Xg:this.checkRetryDate()}this.state===Kg&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:r,media:n}=this;if(null===t||!n&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const i=this.buffering?e.nextLoadLevel:e.loadLevel;if(null==r||!r[i])return;const s=r[i],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const e={};return 2===this.altAudio&&(e.type="video"),this.hls.trigger(Pd.BUFFER_EOS,e),void(this.state=em)}if(!this.buffering)return;e.loadLevel!==i&&-1===e.manualLevel&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=e.nextLoadLevel=i;const l=s.details;if(!l||this.state===nm||this.waitForLive(s))return this.level=i,this.state=nm,void(this.startFragRequested=!1);const u=a.len,c=this.getMaxBufferLength(s.maxBitrate);if(u>=c)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const d=this.backtrackFragment?this.backtrackFragment.start:a.end;let h=this.getNextFragment(d,l);if(this.couldBacktrack&&!this.fragPrevious&&h&&vh(h)&&this.fragmentTracker.getState(h)!==op){var f;const e=(null!=(f=this.backtrackFragment)?f:h).sn-l.startSN,t=l.fragments[e-1];t&&h.cc===t.cc&&(h=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(h&&this.isLoopLoading(h,d)){if(!h.gap){const e=this.audioOnly&&!this.altAudio?fh:ph,t=(e===ph?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,Nd)}h=this.getNextFragmentLoopLoading(h,l,a,Nd,c)}h&&(!h.initSegment||h.initSegment.data||this.bitrateTest||(h=h.initSegment),this.loadFragment(h,s,d))}loadFragment(e,t,r){const n=this.fragmentTracker.getState(e);n===ip||n===ap?vh(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,t)):super.loadFragment(e,t,r):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,Nd)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(null!=t&&t.readyState){let r;const n=this.getAppendedFrag(t.currentTime);n&&n.start>1&&this.flushMainBuffer(0,n.start-1);const i=this.getLevelDetails();if(null!=i&&i.live){const e=this.getMainFwdBufferInfo();if(!e||e.len<2*i.targetduration)return}if(!t.paused&&e){const t=e[this.hls.nextLoadLevel],n=this.fragLastKbps;r=n&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*n)+1:0}else r=0;const s=this.getBufferedFrag(t.currentTime+r);if(s){const e=this.followingBufferedFrag(s);if(e){this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,r=e.duration,n=Math.max(s.end,t+Math.min(Math.max(r-this.config.maxFragLookUpTolerance,r*(this.couldBacktrack?.5:.125)),r*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(n,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 Yg:case qg:case Xg:case Zg:case Jg:this.state=Kg}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,2===this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const r=t.media;Gg(r,"playing",this.onMediaPlaying),Gg(r,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:r}=this;r&&(Hg(r,"playing",this.onMediaPlaying),Hg(r,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t);!!t.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(Pd.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let r=!1,n=!1;for(let e=0;e<t.levels.length;e++){const i=t.levels[e].audioCodec;i&&(r=r||-1!==i.indexOf("mp4a.40.2"),n=n||-1!==i.indexOf("mp4a.40.5"))}this.audioCodecSwitch=r&&n&&!function(){var e;const t=Cw();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:r}=this;if(!r||this.state!==Kg)return;const n=t.levelInfo;(!n.details||n.details.live&&(this.levelLastLoaded!==n||n.details.expired)||this.waitForCdnTuneIn(n.details))&&(this.state=nm)}onLevelLoaded(e,t){var r;const{levels:n,startFragRequested:i}=this,s=t.level,a=t.details,o=a.totalduration;if(!n)return void this.warn(`Levels were reset while loading level ${s}`);this.log(`Level ${s} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=t.levelInfo,u=this.fragCurrent;!u||this.state!==qg&&this.state!==Xg||u.level!==t.level&&u.loader&&this.abortCurrentFrag();let c=0;if(a.live||null!=(r=l.details)&&r.live){var d;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;c=this.alignPlaylists(a,l.details,null==(d=this.levelLastLoaded)?void 0:d.details)}if(l.details=a,this.levelLastLoaded=l,i||this.setStartPosition(a,c),this.hls.trigger(Pd.LEVEL_UPDATED,{details:a,level:s}),this.state===nm){if(this.waitForCdnTuneIn(a))return;this.state=Kg}i&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:r}=this;if(!r)return;const n=this.hls.liveSyncPosition,i=this.getLoadPosition(),s=e.fragmentStart,a=e.edge,o=i>=s-t.maxFragLookUpTolerance&&i<=a;if(null!==n&&r.duration>n&&(i<n||!o)){const s=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&r.readyState<4||i<a-s)&&(this._hasEnoughToStart||(this.nextLoadPosition=n),r.readyState))if(this.warn(`Playback: ${i.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${n.toFixed(3)}`),"buffered"===this.config.liveSyncMode){var l;const e=Ap.bufferInfo(r,n,0);if(null==(l=e.buffered)||!l.length)return void(r.currentTime=n);if(e.start<=i)return void(r.currentTime=n);const{nextStart:t}=Ap.bufferedInfo(e.buffered,i,0);t&&(r.currentTime=t)}else r.currentTime=n}}_handleFragmentLoadProgress(e){var t;const r=e.frag,{part:n,payload:i}=e,{levels:s}=this;if(!s)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);const a=s[r.level];if(!a)return void this.warn(`Level ${r.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${r.sn} of level ${r.level} after level details were reset`),void this.fragmentTracker.removeFragment(r);const l=a.videoCodec,u=o.PTSKnown||!o.live,c=null==(t=r.initSegment)?void 0:t.data,d=this._getAudioCodec(a),h=this.transmuxer=this.transmuxer||new Ov(this.hls,Nd,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=n?n.index:-1,p=-1!==f,g=new xp(r.level,r.sn,r.stats.chunkCount,i.byteLength,f,p),m=this.initPTS[r.cc];h.push(i,c,d,l,r,n,o.totalduration,u,g,m)}onAudioTrackSwitching(e,t){const r=this.hls,n=0!==this.altAudio;if(Of(t.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 e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(n)return this.altAudio=0,this.fragmentTracker.removeAllFragments(),r.once(Pd.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(Pd.AUDIO_TRACK_SWITCHED,t)}),void r.trigger(Pd.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});r.trigger(Pd.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const r=Of(t.url,this.hls);if(r){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=r?2:0,this.tick()}onBufferCreated(e,t){const r=t.tracks;let n,i,s=!1;for(const e in r){const t=r[e];if("main"===t.id){if(i=e,n=t,"video"===e){const t=r[e];t&&(this.videoBuffer=t.buffer)}}else s=!0}s&&n?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=n.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:r,part:n}=t,i=r.type===Nd;if(i){if(this.fragContextChanged(r))return this.warn(`Fragment ${r.sn}${n?" p: "+n.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Jg&&(this.state=Kg));const e=n?n.stats:r.stats;this.fragLastKbps=Math.round(8*e.total/(e.buffering.end-e.loading.first)),vh(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,n)}const s=this.media;s&&(!this._hasEnoughToStart&&Ap.getBuffered(s).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),i&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var r;if(t.fatal)this.state=tm;else switch(t.details){case Cd.FRAG_GAP:case Cd.FRAG_PARSING_ERROR:case Cd.FRAG_DECRYPT_ERROR:case Cd.FRAG_LOAD_ERROR:case Cd.FRAG_LOAD_TIMEOUT:case Cd.KEY_LOAD_ERROR:case Cd.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Nd,t);break;case Cd.LEVEL_LOAD_ERROR:case Cd.LEVEL_LOAD_TIMEOUT:case Cd.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==nm||(null==(r=t.context)?void 0:r.type)!==_d||(this.state=Kg);break;case Cd.BUFFER_ADD_CODEC_ERROR:case Cd.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case Cd.BUFFER_FULL_ERROR:if("main"!==t.parent)return;if(this.reduceLengthAndFlushBuffer(t)){!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}break;case Cd.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=Kg,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==fh||!this.altAudio){const e=(t===ph?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t,Nd),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let r=this.startPosition;if(r>=0&&t<r){if(e.seeking)return void this.log(`could not seek to ${r}, already seeking at ${t}`);const n=this.timelineOffset;n&&r&&(r+=n);const i=this.getLevelDetails(),s=Ap.getBuffered(e),a=s.length?s.start(0):0,o=a-r,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==i?void 0:i.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),r+=o,this.startPosition=r),t<r&&(this.log(`seek to target start position ${r} from current time ${t} buffer start ${a}`),e.currentTime=r)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(e=>{const{hls:r}=this,n=null==e?void 0:e.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=Kg,this.startFragRequested=!1,this.bitrateTest=!1;const i=n.stats;i.parsing.start=i.parsing.end=i.buffering.start=i.buffering.end=self.performance.now(),r.trigger(Pd.FRAG_LOADED,e),n.bitrateTest=!1}).catch(t=>{this.state!==Wg&&this.state!==tm&&(this.warn(t),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:r}=this,{remuxResult:n,chunkMeta:i}=e,s=this.getCurrentContext(i);if(!s)return void this.resetWhenMissingContext(i);const{frag:a,part:o,level:l}=s,{video:u,text:c,id3:d,initSegment:h}=n,{details:f}=l,p=this.altAudio?void 0:n.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=Zg,h){const e=h.tracks;if(e){const n=a.initSegment||a;if(this.unhandledEncryptionError(h,a))return;this._bufferInitSegment(l,e,n,i),r.trigger(Pd.FRAG_PARSING_INIT_SEGMENT,{frag:n,id:t,tracks:e})}const n=h.initPTS,s=h.timescale,o=this.initPTS[a.cc];if(Ad(n)&&(!o||o.baseTime!==n||o.timescale!==s)){const e=h.trackId;this.initPTS[a.cc]={baseTime:n,timescale:s,trackId:e},r.trigger(Pd.INIT_PTS_FOUND,{frag:a,id:t,initPTS:n,timescale:s,trackId:e})}}if(u&&f){p&&"audiovideo"===u.type&&this.logMuxedErr(a);const e=f.fragments[a.sn-1-f.startSN],t=a.sn===f.startSN,r=!e||a.cc>e.cc;if(!1!==n.independent){const{startPTS:e,endPTS:n,startDTS:s,endDTS:l}=u;if(o)o.elementaryStreams[u.type]={startPTS:e,endPTS:n,startDTS:s,endDTS:l};else if(u.firstKeyFrame&&u.independent&&1===i.id&&!r&&(this.couldBacktrack=!0),u.dropped&&u.independent){const i=this.getMainFwdBufferInfo(),s=(i?i.end:this.getLoadPosition())+this.config.maxBufferHole,o=u.firstKeyFramePTS?u.firstKeyFramePTS:e;if(!t&&s<o-this.config.maxBufferHole&&!r)return void this.backtrack(a);r&&(a.gap=!0),a.setElementaryStreamInfo(u.type,a.start,n,a.start,l,!0)}else t&&e-(f.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(u.type,e,n,s,l),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(u,a,o,i,t||r)}else{if(!t&&!r)return void this.backtrack(a);a.gap=!0}}if(p){const{startPTS:e,endPTS:t,startDTS:r,endDTS:n}=p;o&&(o.elementaryStreams[fh]={startPTS:e,endPTS:t,startDTS:r,endDTS:n}),a.setElementaryStreamInfo(fh,e,t,r,n),this.bufferFragmentData(p,a,o,i)}if(f&&null!=d&&d.samples.length){const e={id:t,frag:a,details:f,samples:d.samples};r.trigger(Pd.FRAG_PARSING_METADATA,e)}if(f&&c){const e={id:t,frag:a,details:f,samples:c.samples};r.trigger(Pd.FRAG_PARSING_USERDATA,e)}}}logMuxedErr(e){this.warn(`${vh(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,r,n){if(this.state!==Zg)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(r));const{audio:i,video:s,audiovideo:a}=t;if(i){const r=e.audioCodec;let n=sf(i.codec,r);"mp4a"===n&&(n="mp4a.40.5");const s=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){n&&(n=-1!==n.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const e=i.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&-1===s.indexOf("firefox")&&(n="mp4a.40.5")}n&&-1!==n.indexOf("mp4a.40.5")&&-1!==s.indexOf("android")&&"audio/mpeg"!==i.container&&(n="mp4a.40.2",this.log(`Android: force audio codec to ${n}`)),r&&r!==n&&this.log(`Swapping manifest audio codec "${r}" for "${n}"`),i.levelCodec=n,i.id=Nd,this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${n||""}/${r||""}/${i.codec}]`),delete t.audiovideo}if(s){s.levelCodec=e.videoCodec,s.id=Nd;const r=s.codec;if(4===(null==r?void 0:r.length))switch(r){case"hvc1":case"hev1":s.codec="hvc1.1.6.L120.90";break;case"av01":s.codec="av01.0.04M.08";break;case"avc1":s.codec="avc1.42e01e"}this.log(`Init video buffer, container:${s.container}, codecs[level/parsed]=[${e.videoCodec||""}/${r}]${s.codec!==r?" parsed-corrected="+s.codec:""}${s.supplemental?" supplemental="+s.supplemental:""}`),delete t.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio);const o=Object.keys(t);if(o.length){if(this.hls.trigger(Pd.BUFFER_CODECS,t),!this.hls)return;o.forEach(e=>{const i=t[e].initSegment;null!=i&&i.byteLength&&this.hls.trigger(Pd.BUFFER_APPENDING,{type:e,data:i,frag:r,part:null,chunkMeta:n,parent:r.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,Nd)}get maxBufferLength(){const{levels:e,level:t}=this,r=null==e?void 0:e[t];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=Kg}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const r=e.currentTime;if(Ap.isBuffered(e,r)?t=this.getAppendedFrag(r):Ap.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t){this.backtrackFragment=null;const e=this.fragPlaying,r=t.level;e&&t.sn===e.sn&&e.level===r||(this.fragPlaying=t,this.hls.trigger(Pd.FRAG_CHANGED,{frag:t}),e&&e.level===r||this.hls.trigger(Pd.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return Ad(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(Ad(t)){const e=this.getLevelDetails(),r=this.currentFrag||(e?Ff(null,e.fragments,t):null);if(r){const e=r.programDateTime;if(null!==e){const n=e+1e3*(t-r.start);return new Date(n)}}}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 _w extends Vd{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const r in this.keyIdToKeyInfo){const n=this.keyIdToKeyInfo[r].loader;if(n){var t;if(e&&e!==(null==(t=n.context)?void 0:t.frag.type))return;n.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=Cd.KEY_LOAD_ERROR,r,n,i){return new Sp({type:Id.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:i,error:r,networkDetails:n})}loadClear(e,t,r){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let n=0,i=t.length;n<i;n++){const s=t[n];if(e.cc<=s.cc&&(!vh(e)||!vh(s)||e.sn<s.sn)||!r&&n==i-1)return this.emeController.selectKeySystemFormat(s).then(e=>{if(!this.emeController)return;s.setKeyFormat(e);const t=Jp(e);return t?this.emeController.getKeySystemAccess([t]):void 0})}if(this.config.requireKeySystemAccessOnStart){const e=tg(this.config);if(e.length)return this.emeController.getKeySystemAccess(e)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var r,n;t&&e.setKeyFormat(t);const i=e.decryptdata;if(!i){const r=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,Cd.KEY_LOAD_ERROR,r))}const s=i.uri;if(!s)return Promise.reject(this.createKeyLoadError(e,Cd.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${s}"`)));const a=Mw(i);let o=this.keyIdToKeyInfo[a];if(null!=(r=o)&&r.decryptdata.key)return i.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if(this.emeController&&null!=(n=o)&&n.keyLoadPromise){switch(this.emeController.getKeyStatus(o.decryptdata)){case"usable":case"usable-in-future":return o.keyLoadPromise.then(t=>{const{keyInfo:r}=t;return i.key=r.decryptdata.key,{frag:e,keyInfo:r}})}}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${i.keyId?" keyId: "+th(i.keyId):""} URI: ${i.uri} from ${e.type} ${e.level}`),o=this.keyIdToKeyInfo[a]={decryptdata:i,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},i.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===i.keyFormat?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,Cd.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(e,t){const r={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var n;if(!e.decryptdata.keyId&&null!=(n=t.initSegment)&&n.data){const r=function(e){const t=[];return Fh(e,e=>t.push(e.subarray(8,24))),t}(t.initSegment.data);if(r.length){let t=r[0];t.some(e=>0!==e)?(this.log(`Using keyId found in init segment ${th(t)}`),ag.setKeyIdForUri(e.decryptdata.uri,t)):(t=ag.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${th(t)}`)),e.decryptdata.keyId=t}}if(!e.decryptdata.keyId&&!vh(t))return Promise.resolve(r);const i=this.emeController.loadKey(r);return(e.keyLoadPromise=i.then(t=>(e.mediaKeySessionContext=t,r))).catch(r=>{throw e.keyLoadPromise=null,"data"in r&&(r.data.frag=t),r})}return Promise.resolve(r)}loadKeyHTTP(e,t){const r=this.config,n=new(0,r.loader)(r);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((i,s)=>{const a={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=r.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(e,t,r,n)=>{const{frag:a,keyInfo:o}=r,l=Mw(o.decryptdata);if(!a.decryptdata||o!==this.keyIdToKeyInfo[l])return s(this.createKeyLoadError(a,Cd.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),n));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,o.loader=null,i({frag:a,keyInfo:o})},onError:(e,r,n,i)=>{this.resetLoader(r),s(this.createKeyLoadError(t,Cd.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),n,Hd({url:a.url,data:void 0},e)))},onTimeout:(e,r,n)=>{this.resetLoader(r),s(this.createKeyLoadError(t,Cd.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),n))},onAbort:(e,r,n)=>{this.resetLoader(r),s(this.createKeyLoadError(t,Cd.INTERNAL_ABORTED,new Error("key loading aborted"),n))}};n.load(a,l,u)})}resetLoader(e){const{frag:t,keyInfo:r,url:n}=e,i=r.loader;t.keyLoader===i&&(t.keyLoader=null,r.loader=null);const s=Mw(r.decryptdata)||n;delete this.keyIdToKeyInfo[s],i&&i.destroy()}}function Mw(e){if(e.keyFormat!==Xp){const t=e.keyId;if(t)return th(t)}return e.uri}function Ow(e){const{type:t}=e;switch(t){case Md:return Fd;case Od:return $d;default:return Nd}}function Nw(e,t){let r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}class Fw{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(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Pd.LEVEL_LOADING,this.onLevelLoading,this),e.on(Pd.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(Pd.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(Pd.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(Pd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Pd.LEVEL_LOADING,this.onLevelLoading,this),e.off(Pd.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(Pd.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(Pd.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,r=t.pLoader,n=t.loader,i=new(r||n)(t);return this.loaders[e.type]=i,i}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:r}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Dd,url:r,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:r,level:n,pathwayId:i,url:s,deliveryDirectives:a,levelInfo:o}=t;this.load({id:r,level:n,pathwayId:i,responseType:"text",type:_d,url:s,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(e,t){const{id:r,groupId:n,url:i,deliveryDirectives:s,track:a}=t;this.load({id:r,groupId:n,level:null,responseType:"text",type:Md,url:i,deliveryDirectives:s,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:r,groupId:n,url:i,deliveryDirectives:s,track:a}=t;this.load({id:r,groupId:n,level:null,responseType:"text",type:Od,url:i,deliveryDirectives:s,levelOrTrack:a})}onLevelsUpdated(e,t){const r=this.loaders[_d];if(r){const e=r.context;e&&!t.levels.some(t=>t===e.levelOrTrack)&&(r.abort(),delete this.loaders[_d])}}load(e){var t;const r=this.hls.config;let n,i=this.getInternalLoader(e);if(i){const t=this.hls.logger,r=i.context;if(r&&r.levelOrTrack===e.levelOrTrack&&(r.url===e.url||r.deliveryDirectives&&!e.deliveryDirectives))return void(r.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${r.url}`));t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}if(n=e.type===Dd?r.manifestLoadPolicy.default:jd({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),Ad(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===_d&&null!==e.level?t=this.hls.levels[e.level].details:e.type===Md&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===Od&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,r=t.targetduration;if(e&&r){const t=1e3*Math.max(3*e,.8*r);n=jd({},n,{maxTimeToFirstByteMs:Math.min(t,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,n.maxTimeToFirstByteMs)})}}}const s=n.errorRetry||n.timeoutRetry||{},a={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:s.maxNumRetry||0,retryDelay:s.retryDelayMs||0,maxRetryDelay:s.maxRetryDelayMs||0},o={onSuccess:(e,t,r,n)=>{const i=this.getInternalLoader(r);this.resetInternalLoader(r.type);const s=e.data;t.parsing.start=performance.now(),fg.isMediaPlaylist(s)||r.type!==Dd?this.handleTrackOrLevelPlaylist(e,t,r,n||null,i):this.handleMasterPlaylist(e,t,r,n)},onError:(e,t,r,n)=>{this.handleNetworkError(t,r,!1,e,n)},onTimeout:(e,t,r)=>{this.handleNetworkError(t,r,!0,void 0,e)}};i.load(e,a,o)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:r}=this.hls;(e||r)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,r,n){const i=this.hls,s=e.data,a=Nw(e,r),o=fg.parseMasterPlaylist(s,a);if(o.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,r,o.playlistParsingError,n,t);const{contentSteering:l,levels:u,sessionData:c,sessionKeys:d,startTimeOffset:h,variableList:f}=o;this.variableList=f,u.forEach(e=>{const{unknownCodecs:t}=e;if(t){const{preferManagedMediaSource:r}=this.hls.config;let{audioCodec:n,videoCodec:i}=e;for(let s=t.length;s--;){const a=t[s];Xh(a,"audio",r)?(e.audioCodec=n=n?`${n},${a}`:a,Yh.audio[n.substring(0,4)]=2,t.splice(s,1)):Xh(a,"video",r)&&(e.videoCodec=i=i?`${i},${a}`:a,Yh.video[i.substring(0,4)]=2,t.splice(s,1))}}});const{AUDIO:p=[],SUBTITLES:g,"CLOSED-CAPTIONS":m}=fg.parseMasterPlaylistMedia(s,a,o);if(p.length){p.some(e=>!e.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"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Mp({}),bitrate:0,url:""}))}i.trigger(Pd.MANIFEST_LOADED,{levels:u,audioTracks:p,subtitles:g,captions:m,contentSteering:l,url:a,stats:t,networkDetails:n,sessionData:c,sessionKeys:d,startTimeOffset:h,variableList:f})}handleTrackOrLevelPlaylist(e,t,r,n,i){const s=this.hls,{id:a,level:o,type:l}=r,u=Nw(e,r),c=Ad(o)?o:Ad(a)?a:0,d=Ow(r),h=fg.parseLevelPlaylist(e.data,u,c,d,0,this.variableList);if(l===Dd){const e={attrs:new Mp({}),bitrate:0,details:h,name:"",url:u};h.requestScheduled=t.loading.start+Pg(h,0),s.trigger(Pd.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:u,stats:t,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=h,this.handlePlaylistLoaded(h,e,t,r,n,i)}handleManifestParsingError(e,t,r,n,i){this.hls.trigger(Pd.ERROR,{type:Id.NETWORK_ERROR,details:Cd.MANIFEST_PARSING_ERROR,fatal:t.type===Dd,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:n,stats:i})}handleNetworkError(e,t,r=!1,n,i){let s=`A network ${r?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${e.type}`;e.type===_d?s+=`: ${e.level} id: ${e.id}`:e.type!==Md&&e.type!==Od||(s+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(s);this.hls.logger.warn(`[playlist-loader]: ${s}`);let o=Cd.UNKNOWN,l=!1;const u=this.getInternalLoader(e);switch(e.type){case Dd:o=r?Cd.MANIFEST_LOAD_TIMEOUT:Cd.MANIFEST_LOAD_ERROR,l=!0;break;case _d:o=r?Cd.LEVEL_LOAD_TIMEOUT:Cd.LEVEL_LOAD_ERROR,l=!1;break;case Md:o=r?Cd.AUDIO_TRACK_LOAD_TIMEOUT:Cd.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case Od:o=r?Cd.SUBTITLE_TRACK_LOAD_TIMEOUT:Cd.SUBTITLE_LOAD_ERROR,l=!1}u&&this.resetInternalLoader(e.type);const c={type:Id.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:u,context:e,error:a,networkDetails:t,stats:i};if(n){const r=(null==t?void 0:t.url)||e.url;c.response=Hd({url:r,data:void 0},n)}this.hls.trigger(Pd.ERROR,c)}handlePlaylistLoaded(e,t,r,n,i,s){const a=this.hls,{type:o,level:l,levelOrTrack:u,id:c,groupId:d,deliveryDirectives:h}=n,f=Nw(t,n),p=Ow(n);let g="number"==typeof n.level&&p===Nd?l:void 0;const m=e.playlistParsingError;if(m){if(this.hls.logger.warn(`${m} ${e.url}`),!a.config.ignorePlaylistParsingErrors)return void a.trigger(Pd.ERROR,{type:Id.NETWORK_ERROR,details:Cd.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:m,reason:m.message,response:t,context:n,level:g,parent:p,networkDetails:i,stats:r});e.playlistParsingError=null}if(!e.fragments.length){const s=e.playlistParsingError=new Error("No Segments found in Playlist");return void a.trigger(Pd.ERROR,{type:Id.NETWORK_ERROR,details:Cd.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:s,reason:s.message,response:t,context:n,level:g,parent:p,networkDetails:i,stats:r})}switch(e.live&&s&&(s.getCacheAge&&(e.ageHeader=s.getCacheAge()||0),s.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case Dd:case _d:if(g)if(u){if(u!==a.levels[g]){const e=a.levels.indexOf(u);e>-1&&(g=e)}}else g=0;a.trigger(Pd.LEVEL_LOADED,{details:e,levelInfo:u||a.levels[0],level:g||0,id:c||0,stats:r,networkDetails:i,deliveryDirectives:h,withoutMultiVariant:o===Dd});break;case Md:a.trigger(Pd.AUDIO_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:d||"",stats:r,networkDetails:i,deliveryDirectives:h});break;case Od:a.trigger(Pd.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:d||"",stats:r,networkDetails:i,deliveryDirectives:h})}}}class $w{static get version(){return dm}static isMSESupported(){return Pw()}static isSupported(){return function(){if(!Pw())return!1;const e=Zd();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>e.isTypeSupported(Zh(t,"video")))||["mp4a.40.2","fLaC"].some(t=>e.isTypeSupported(Zh(t,"audio"))))}()}static getMediaSource(){return Zd()}static get Events(){return Pd}static get MetadataSchema(){return Mm}static get ErrorTypes(){return Id}static get ErrorDetails(){return Cd}static get DefaultConfig(){return $w.defaultConfig?$w.defaultConfig:mw}static set DefaultConfig(e){$w.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 cm,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 t=this.logger=function(e,t,r){const n=Yd();if("object"==typeof console&&!0===e||"object"==typeof e){const i=["debug","log","info","warn","error"];i.forEach(t=>{n[t]=qd(t,e,r)});try{n.log(`Debug logs enabled for "${t}" in hls.js version 1.6.15`)}catch(e){return Yd()}i.forEach(t=>{Xd[t]=qd(t,e)})}else jd(Xd,n);return n}(e.debug||!1,"Hls instance",e.assetPlayerId),r=this.config=function(e,t,r){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const n=vw(e),i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(e=>{const s=`${"level"===e?"playlist":e}LoadPolicy`,a=void 0===t[s],o=[];i.forEach(r=>{const i=`${e}Loading${r}`,l=t[i];if(void 0!==l&&a){o.push(i);const e=n[s].default;switch(t[s]={default:e},r){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}}),o.length&&r.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${s}": ${Rf(t[s])}`)}),Hd(Hd({},n),t)}($w.DefaultConfig,e,t);this.userConfig=e,r.progressive&&yw(r,t);const{abrController:n,bufferController:i,capLevelController:s,errorController:a,fpsController:o}=r,l=new a(this),u=this.abrController=new n(this),c=new lp(this),d=r.interstitialsController,h=d?this.interstitialsController=new d(this,$w):null,f=this.bufferController=new i(this,c),p=this.capLevelController=new s(this),g=new o(this),m=new Fw(this),v=r.contentSteeringController,y=v?new v(this):null,b=this.levelController=new Lw(this,y),w=new Aw(this),E=new _w(this.config,this.logger),S=this.streamController=new Dw(this,c,E),T=this.gapController=new bw(this,c);p.setStreamController(S),g.setStreamController(S);const x=[m,b,S];h&&x.splice(1,0,h),y&&x.splice(1,0,y),this.networkControllers=x;const k=[u,f,T,p,g,w,c];this.audioTrackController=this.createController(r.audioTrackController,x);const A=r.audioStreamController;A&&x.push(this.audioStreamController=new A(this,c,E)),this.subtitleTrackController=this.createController(r.subtitleTrackController,x);const R=r.subtitleStreamController;R&&x.push(this.subtititleStreamController=new R(this,c,E)),this.createController(r.timelineController,k),E.emeController=this.emeController=this.createController(r.emeController,k),this.cmcdController=this.createController(r.cmcdController,k),this.latencyController=this.createController(Rw,k),this.coreComponents=k,x.push(l);const L=l.onErrorOut;"function"==typeof L&&this.on(Pd.ERROR,L,l),this.on(Pd.MANIFEST_LOADED,m.onManifestLoaded,m)}createController(e,t){if(e){const r=new e(this);return t&&t.push(r),r}return null}on(e,t,r=this){this._emitter.on(e,t,r)}once(e,t,r=this){this._emitter.once(e,t,r)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,r=this,n){this._emitter.off(e,t,r,n)}listeners(e){return this._emitter.listeners(e)}emit(e,t,r){return this._emitter.emit(e,t,r)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;const r=e===Pd.ERROR;this.trigger(Pd.ERROR,{type:Id.OTHER_ERROR,details:Cd.INTERNAL_EXCEPTION,fatal:r,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(Pd.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.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 t=new Error(`attachMedia failed: invalid argument (${e})`);return void this.trigger(Pd.ERROR,{type:Id.OTHER_ERROR,details:Cd.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,r=t?e.media:e,n=t?e:{media:r};this._media=r,this.trigger(Pd.MEDIA_ATTACHING,n)}detachMedia(){this.logger.log("detachMedia"),this.trigger(Pd.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(Pd.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,r=this._url,n=this._url=dh.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${n}`),t&&r&&(r!==n||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(Pd.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let r=0;r<this.networkControllers.length&&(this.networkControllers[r].startLoad(e,t),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={[Nd]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[Fd]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[$d]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=function(){try{return crypto.randomUUID()}catch(e){try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){let t=(new Date).getTime();const r="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const r=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==e?r:3&r|8).toString(16)});return r}}}()),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-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}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){(function(e){return vf.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const r=e.length;for(let n=0;n<r;n++)if(e[n].maxBitrate>=t)return n;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:r}=this;let n;if(n=-1===t&&null!=e&&e.length?e.length-1:t,r)for(let t=n;t--;){const n=e[t].attrs["HDCP-LEVEL"];if(n&&n<=r)return t}return n}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 t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.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 t=this.audioTrackController;t&&(t.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 t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.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!(null==(e=this.bufferController)||!e.bufferedToEnd)}get interstitialsManager(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){return pf(e,If(t),navigator.mediaCapabilities)}}$w.defaultConfig=void 0;const Bw=({file:e,startTime:t,poster:r,autoplay:n=!0,active:i=!0,visible:s=!0,muted:a=!0})=>{const o=p.useRef(null),{isReady:l,prewarm:u,setLowestResolution:c,startBufferBasedUpshift:d}=(({file:e,videoRef:t,autoplay:r=!0,startTime:n,enabled:i=!0,onReady:s,onError:a})=>{const o=p.useRef(null),l=p.useRef(null),u=p.useRef(0),c=p.useRef(0),d=p.useRef(!1),h=p.useRef(!1),[f,g]=p.useState("idle"),[m,v]=p.useState(0),[y,b]=p.useState(!1),[w,E]=p.useState([]),[S,T]=p.useState("auto"),x=()=>{null!=l.current&&(clearTimeout(l.current),l.current=null)},k=(e=1e3)=>{if(null!=l.current)return;const t=u.current;if(t>=5)return g("error"),x(),void(null==a||a(new Error("Max retry reached")));const r=Math.min(15e3,e*Math.pow(2,Math.min(t,4)));g("loading"),console.log(`[HLS] schedule retry #${t+1} in ${r}ms`),l.current=window.setTimeout(()=>{l.current=null,u.current+=1,console.log(`[HLS] retryCount => ${u.current}`),v(e=>e+1)},r)};p.useEffect(()=>{u.current=0,c.current=0,h.current=!1,b(!1),v(0),g(e?"loading":"idle"),x()},[e]);const A=p.useCallback(()=>J(void 0,void 0,void 0,function*(){if(e)try{yield fetch(e,{method:"HEAD",mode:"cors",credentials:"omit"})}catch(e){}}),[e]);p.useEffect(()=>{var n;const l=t.current;if(!l||!e||!i)return void(e&&!i&&(h.current=!1,b(!1),g("idle")));let f=()=>{};try{null===(n=o.current)||void 0===n||n.destroy()}catch(e){}if(o.current=null,h.current=!1,b(!1),g("loading"),$w.isSupported()){d.current=!1;const t=new $w({lowLatencyMode:!1,backBufferLength:0,maxBufferLength:2,maxMaxBufferLength:4,maxBufferSize:2e6,maxBufferHole:.5,startFragPrefetch:!0,capLevelToPlayerSize:!0});o.current=t;const n=()=>{const e=(t.levels||[]).map((e,t)=>{const r=e.height,n=e.width,i=e.bitrate,s=e.name;return{id:t,height:r,width:n,bitrate:i,name:s,label:s||(r?`${r}p`:`Level ${t}`)}});E(e);const r=t.currentLevel;T(null==r||r<0?"auto":r)},i=()=>{h.current||(h.current=!0,b(!0),g("ready"),u.current=0,x(),null==s||s(),r&&l.play().catch(()=>{}))};t.on($w.Events.MANIFEST_PARSED,()=>{n(),r||L()}),t.on($w.Events.FRAG_BUFFERED,i),t.on($w.Events.BUFFER_APPENDED,i),t.on($w.Events.LEVEL_SWITCHED,(e,t)=>{const r=null==t?void 0:t.level;T(null==r||r<0?"auto":r)}),t.on($w.Events.ERROR,(e,r)=>{var n,i,s,l,d;const f=500===(null!==(l=null!==(i=null===(n=null==r?void 0:r.response)||void 0===n?void 0:n.code)&&void 0!==i?i:null===(s=null==r?void 0:r.response)||void 0===s?void 0:s.status)&&void 0!==l?l:null===(d=null==r?void 0:r.response)||void 0===d?void 0:d.statusCode);if(r.type!==$w.ErrorTypes.NETWORK_ERROR||r.fatal){if(r.fatal){if(r.type===$w.ErrorTypes.MEDIA_ERROR){if(c.current+=1,c.current<=2){try{t.recoverMediaError()}catch(e){}return void g("loading")}try{t.destroy()}catch(e){}return o.current=null,h.current=!1,b(!1),void k()}if(f){console.warn("[HLS] fatal 500 response - no retry");try{t.destroy()}catch(e){}return o.current=null,h.current=!1,b(!1),x(),g("error"),void(null==a||a(new Error("HTTP 500")))}try{t.destroy()}catch(e){}return o.current=null,h.current=!1,b(!1),void k()}}else{if(f){console.warn("[HLS] 500 response detected - no retry"),g("error");try{t.destroy()}catch(e){}return o.current=null,x(),void(null==a||a(new Error("HTTP 500")))}try{if(u.current>=5){g("error");try{t.destroy()}catch(e){}return o.current=null,void(null==a||a(new Error("Max retry reached")))}u.current+=1,console.log(`[HLS] non-fatal network retry => ${u.current}`),t.startLoad()}catch(e){}}}),t.attachMedia(l),t.loadSource(e),f=()=>{try{t.destroy()}catch(e){}o.current=null}}else if(l.canPlayType("application/vnd.apple.mpegURL")){d.current=!0,l.src!==e&&(l.src=e);const t=()=>{h.current||(h.current=!0,b(!0),g("ready"),u.current=0,x(),null==s||s(),r&&l.play().catch(()=>{}))},n=()=>{if(h.current=!1,b(!1),u.current>=5)return g("error"),void(null==a||a(new Error("Max retry reached")));k()};l.addEventListener("loadedmetadata",t),l.addEventListener("error",n),r&&l.play().catch(()=>{}),f=()=>{l.removeEventListener("loadedmetadata",t),l.removeEventListener("error",n)}}else g("error"),null==a||a(new Error("HLS not supported"));return()=>{f(),x()}},[e,m,r,s,a,t,i]),p.useEffect(()=>{if(!y)return;if(null==n||n<=0)return;const e=t.current;if(e)try{Math.abs(e.currentTime-n)>.5&&(e.currentTime=n)}catch(e){}},[y,n,t]),p.useEffect(()=>{const e=t.current;if(!e)return;const r=()=>g("ready"),n=()=>g("ready"),i=()=>{"error"!==f&&g("loading")},s=()=>g("loading"),o=()=>{g("error"),null==a||a()};return e.addEventListener("playing",r),e.addEventListener("canplay",n),e.addEventListener("waiting",i),e.addEventListener("stalled",s),e.addEventListener("error",o),()=>{e.removeEventListener("playing",r),e.removeEventListener("canplay",n),e.removeEventListener("waiting",i),e.removeEventListener("stalled",s),e.removeEventListener("error",o)}},[f,a,t]);const R=p.useCallback(()=>{const e=o.current;e&&!d.current&&(console.log("Set auto resolution"),e.nextLevel=-1,T("auto"))},[]),L=p.useCallback(()=>{var e,t;const r=o.current;if(!r)return;const n=r.levels||[];if(n.length){let i=0;for(let r=1;r<n.length;r++)(null!==(e=n[r].height)&&void 0!==e?e:99999)<(null!==(t=n[i].height)&&void 0!==t?t:99999)&&(i=r);r.currentLevel=i}},[]),I=p.useCallback((e=2)=>{const r=o.current,n=t.current;if(!r||!n||d.current)return()=>{};let i=!1;const s=()=>{if(!i)if(r.autoLevelEnabled)i=!0;else try{n.buffered.length>0&&n.buffered.end(0)-n.currentTime>=e&&(r.nextLevel=-1,T("auto"),i=!0)}catch(e){}};return r.on($w.Events.FRAG_BUFFERED,s),()=>{r.off($w.Events.FRAG_BUFFERED,s)}},[t]);return{playbackStatus:f,isReady:y,qualities:w,currentLevel:S,isAutoQuality:p.useMemo(()=>"auto"===S,[S]),canSetResolution:!d.current&&$w.isSupported(),setResolution:e=>{const t=o.current;if(!t||d.current)return;if("string"==typeof e&&"auto"===e.toLowerCase())return t.currentLevel=-1,void T("auto");const r="number"==typeof e?e:parseInt(e,10);if(!Number.isFinite(r)){const r=w.find(t=>t.label.toLowerCase()===String(e).toLowerCase());return void(r&&(t.currentLevel=r.id,T(r.id)))}const n=[...w].filter(e=>e.height).sort((e,t)=>(t.height||0)-(e.height||0)),i=n.find(e=>(e.height||0)<=r)||n[n.length-1];i&&(t.currentLevel=i.id,T(i.id))},setAutoResolution:R,prewarm:A,setLowestResolution:L,startBufferBasedUpshift:I}})({file:e,videoRef:o,autoplay:n,startTime:t,enabled:n||i});return p.useEffect(()=>{u()},[u]),g.useEffect(()=>{var e,t;const r=o.current;if(r)if(i)null===(e=r.play)||void 0===e||e.call(r).catch(()=>{});else try{null===(t=r.pause)||void 0===t||t.call(r)}catch(e){}},[i,l]),p.useEffect(()=>{if(!i)return;c();return d(2)},[i,c,d]),g.createElement("video",{ref:o,playsInline:!0,autoPlay:n,muted:a,poster:Gt(r||""),preload:"metadata",className:"w-full h-full object-cover object-center bg-black",style:{opacity:s&&l?1:0,transition:"opacity 200ms ease-in-out"}})},Uw=({view:e})=>g.createElement("div",{className:"absolute",style:{top:8,left:8,borderRadius:"4px",color:"white",overflow:"hidden",fontSize:11}},g.createElement("span",{style:{backgroundColor:"rgba(62,213,69,0.71)",color:"white",padding:4,paddingLeft:9,paddingRight:9,display:"inline-block",lineHeight:1}},"다시보기"),g.createElement("span",{style:{backgroundColor:"rgba(58,58,58,0.52)",color:"white",padding:4,paddingLeft:9,paddingRight:9,display:"inline-block",lineHeight:1}},e," 시청")),zw=({content:e,aspectRatio:t="9/16",cursor:r="default",borderRadius:n,playback:i="hover"})=>{var s,a,o,l,u;const c=g.useRef(null),[d,h]=g.useState(!1),f=g.useRef(null),[p,m]=g.useState(!1),[v,y]=g.useState(!0),[b,w]=g.useState(!1),{boxSize:E}=xd(t,c),S=e.thumbPath||(null===(a=null===(s=null==e?void 0:e.designInfo)||void 0===s?void 0:s.thumbPath)||void 0===a?void 0:a.preview),T=3===e.status,{API_BASE_URL:x,PLAYER_BASE_URL:k}=Mt(),A=`${x}/hls/${null===(o=e.replay)||void 0===o?void 0:o.objectId}`;g.useEffect(()=>{const e=c.current;if(!e)return;const t=new IntersectionObserver(e=>{const t=e[0];w(t.isIntersecting&&t.intersectionRatio>=.5)},{root:null,threshold:[0,.5,1]});return t.observe(e),()=>t.disconnect()},[i]),g.useEffect(()=>{var e;if("undefined"!=typeof window&&window.matchMedia)try{const t=window.matchMedia("(pointer: fine)"),r=()=>y(t.matches);return r(),null===(e=t.addEventListener)||void 0===e||e.call(t,"change",r),()=>{var e;return null===(e=t.removeEventListener)||void 0===e?void 0:e.call(t,"change",r)}}catch(e){}},[i]);const R=()=>{null!=f.current&&(clearTimeout(f.current),f.current=null)},L=()=>{m(!0),R(),h(!1)};g.useEffect(()=>{const e=()=>m(!1);return window.addEventListener("mouseup",e),window.addEventListener("touchend",e),window.addEventListener("pointerup",e),()=>{window.removeEventListener("mouseup",e),window.removeEventListener("touchend",e),window.removeEventListener("pointerup",e)}},[i]);const I="hover"===i&&v,C=Boolean(A&&("autoplay"===i&&b||I&&d));return g.createElement("div",{className:"w-full h-full flex flex-col items-center justify-center",ref:c,onMouseEnter:()=>{"hover"===i&&v&&(p||(R(),f.current=window.setTimeout(()=>{h(!0)},150)))},onMouseLeave:()=>{R(),h(!1)},onMouseDown:L,onTouchStart:L},g.createElement("div",{className:"relative rounded overflow-hidden",style:{width:E.width?`${E.width}px`:"100%",height:E.height?`${E.height}px`:"100%",borderRadius:`${null!=n?n:10}px`,backgroundRepeat:"no-repeat",backgroundPosition:"center",backgroundSize:"cover",aspectRatio:E.height?void 0:t,backgroundImage:S?`url(${Gt(S)})`:void 0,backgroundColor:S?void 0:"black"}},T?g.createElement("iframe",{src:`${k}/live/${e.eventId}`,className:"w-full h-full"}):g.createElement(g.Fragment,null,g.createElement("div",{className:"absolute inset-0 w-full h-full object-cover",style:{pointerEvents:"none"}},g.createElement(Bw,{file:A,poster:S,autoplay:"autoplay"===i,active:"autoplay"===i&&b||I&&d,visible:C,muted:!0})),!C&&g.createElement(Sd,null),g.createElement(Uw,{view:null!==(u=null===(l=e.statistics)||void 0===l?void 0:l.pageView)&&void 0!==u?u:0}))))},jw=e=>{var t,r,n,i;const{content:s,title:a,aspectRatio:o="9/16",card:l,titleFontSize:u}=e,c=null!==(t=null==l?void 0:l.layout)&&void 0!==t?t:"slider",d=null!==(r=null==l?void 0:l.sliderPerView)&&void 0!==r?r:3,h=null!==(n=null==l?void 0:l.gridColumns)&&void 0!==n?n:3,f=null!==(i=null==l?void 0:l.gap)&&void 0!==i?i:12,m=null==l?void 0:l.width,v=m?"auto":d,y=p.useMemo(()=>({fontSize:u?`${u}px`:void 0,fontWeight:600}),[u]),{PLAYER_BASE_URL:b}=Mt();return s&&0!==s.length?g.createElement("div",{className:"flex flex-col w-full",style:{gap:f}},g.createElement("p",{className:"truncate",style:Object.assign(Object.assign({},y),{userSelect:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none",cursor:"default"})},a||("past"===e.liveType?"지난 라이브":"예정된 라이브")),"slider"===c?g.createElement("div",null,g.createElement(_n,{key:`${v}-${null!=m?m:""}-${f}`,slidesPerView:v,spaceBetween:f},s.map(t=>{var r,n;return g.createElement(Mn,{key:t.eventId,style:m?{width:`${m}px`}:void 0},g.createElement("a",{href:`${b}/live/${t.eventId}`,target:"_blank",rel:"noopener noreferrer",className:"flex flex-col",style:{gap:6,textDecoration:"none",cursor:"pointer"}},"past"===e.liveType?g.createElement(zw,{content:t,aspectRatio:o,cursor:"pointer",borderRadius:null==l?void 0:l.borderRadius,playback:e.playback}):g.createElement(kd,{content:t,aspectRatio:o,cursor:"pointer",borderRadius:null==l?void 0:l.borderRadius}),g.createElement("p",{className:"truncate",style:{color:null!==(n=null===(r=e.theme)||void 0===r?void 0:r.textColor)&&void 0!==n?n:"black",fontSize:14,userSelect:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none"}},t.eventName)))}))):g.createElement("div",{style:{overflowY:"auto"}},g.createElement("div",{style:{display:"grid",gridTemplateColumns:m?`repeat(auto-fill, ${m}px)`:`repeat(${h}, minmax(0, 1fr))`,gap:f}},s.map(t=>{var r,n;return g.createElement("a",{key:t.eventId,href:`${b}/live/${t.eventId}`,target:"_blank",rel:"noopener noreferrer",className:"flex flex-col",style:{gap:6,textDecoration:"none",cursor:"pointer"}},"past"===e.liveType?g.createElement(zw,{content:t,aspectRatio:o,cursor:"pointer",borderRadius:null==l?void 0:l.borderRadius,playback:e.playback}):g.createElement(kd,{content:t,aspectRatio:o,cursor:"pointer",borderRadius:null==l?void 0:l.borderRadius}),g.createElement("p",{className:"truncate",style:{color:null!==(n=null===(r=e.theme)||void 0===r?void 0:r.textColor)&&void 0!==n?n:"black",fontSize:14,userSelect:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none"}},t.eventName))})))):null};var Gw;!function(e){e[e.READY=1]="READY",e[e.STREAMING=2]="STREAMING",e[e.PAUSED=3]="PAUSED"}(Gw||(Gw={}));const Hw=({content:e})=>{const t=g.useMemo(()=>vt(e.start).tz("Asia/Seoul").format("M월 D일 A HH:mm"),[e.start]),r=e.eventStatus!==Gw.READY;return g.createElement("div",{className:"flex-1 flex flex-col gap-5 items-center justify-center"},g.createElement("p",{style:{fontWeight:"bold",fontSize:"24px"}},e.eventName),!r&&g.createElement("p",null,t),g.createElement("button",{onClick:()=>{window.open(`https://player.midibus.im/live/${e.eventId}`,"_blank")},className:"rounded bg-black text-white cursor-pointer",style:{width:"70%",padding:"10px"}},"라이브 입장하기"))},Vw=e=>{var t,r;const{content:n,aspectRatio:i="9/16",videoAlign:s}=e,a=null===(t=e.card)||void 0===t?void 0:t.borderRadius,o=null===(r=e.card)||void 0===r?void 0:r.width,{PLAYER_BASE_URL:l}=Mt();return g.createElement("div",{className:"flex w-full h-full items-center justify-center"},"only"===s?g.createElement("a",{className:"w-full h-full",href:`${l}/live/${n.eventId}`,target:"_blank",rel:"noopener noreferrer",style:o?{width:`${o}px`}:void 0},g.createElement(kd,{content:n,aspectRatio:i,borderRadius:a,cursor:"pointer"})):"left"===s?g.createElement(g.Fragment,null,g.createElement("div",{className:"flex-1"},g.createElement("a",{href:`${l}/live/${n.eventId}`,target:"_blank",rel:"noopener noreferrer",style:o?{width:`${o}px`}:void 0},g.createElement(kd,{content:n,aspectRatio:i,borderRadius:a,cursor:"pointer"}))),g.createElement(Hw,{content:n})):g.createElement(g.Fragment,null,g.createElement(Hw,{content:n}),g.createElement("div",{className:"flex-1"},g.createElement("a",{href:`${l}/live/${n.eventId}`,target:"_blank",rel:"noopener noreferrer",style:o?{width:`${o}px`}:void 0},g.createElement(kd,{content:n,aspectRatio:i,borderRadius:a,cursor:"pointer"})))))},Ww=e=>{var t;const{theme:r,titleFontSize:n,title:i}=e;return g.createElement("div",{className:"w-full h-full flex flex-col",style:{color:null!==(t=null==r?void 0:r.textColor)&&void 0!==t?t:"#252525"}},g.createElement("p",{style:Object.assign(Object.assign({},n&&{fontSize:n}),{fontWeight:"bold",color:null==r?void 0:r.textColor,paddingTop:"10px",paddingBottom:"10px",marginBottom:"30px"})},i||("past"===e.liveType?"지난 라이브":"예정된 라이브")),g.createElement("div",{className:"self-center text-center h-full flex flex-col items-center justify-center",style:{minHeight:"200px"}},g.createElement("p",{style:{fontSize:"20px",marginBottom:"10px"}},"past"===e.liveType?"지난 라이브가 없어요.":"예정된 라이브가 없어요."),g.createElement("span",{style:{fontWeight:"lighter"}},"past"===e.liveType?"다른 콘텐츠도 확인해 보세요.":"곧 혜택 가득한 라이브로 찾아올게요!")))};function Kw(e){var{className:t}=e,r=Z(e,["className"]);return p.createElement("div",Object.assign({className:Ot("animate-pulse rounded-md bg-gray-200",t)},r))}const Yw=e=>{var t,r,n,i,s,a,o,l,u;const{card:c,aspectRatio:d="9/16",widgetType:h,layout:f,theme:p}=e,m=null!==(t=null==c?void 0:c.layout)&&void 0!==t?t:"slider",v=null!==(r=null==c?void 0:c.sliderPerView)&&void 0!==r?r:3,y=null!==(n=null==c?void 0:c.gridColumns)&&void 0!==n?n:3,b=null!==(i=null==c?void 0:c.gap)&&void 0!==i?i:12,w=null!==(s=null==c?void 0:c.borderRadius)&&void 0!==s?s:8,E=null!==(a=null==f?void 0:f.paddingTop)&&void 0!==a?a:0,S=null!==(o=null==f?void 0:f.paddingBottom)&&void 0!==o?o:0,T=null!==(l=null==f?void 0:f.paddingLeft)&&void 0!==l?l:0,x=null!==(u=null==f?void 0:f.paddingRight)&&void 0!==u?u:0,k="ONE"===h&&"past"!==e.liveType,A=k?1:(null==c?void 0:c.visibleCount)||6,R=k?1:"slider"===m?v:A;return g.createElement("div",{className:"w-full flex flex-col",style:{gap:b,paddingTop:E,paddingBottom:S,paddingLeft:T,paddingRight:x,backgroundColor:null==p?void 0:p.backgroundColor}},g.createElement(Kw,{className:"h-5 w-36"}),g.createElement("div",{style:k||"scroll"!==m?{display:"flex",gap:b,overflow:"hidden"}:{display:"grid",gridTemplateColumns:`repeat(${y}, minmax(0, 1fr))`,gap:b}},Array.from({length:R}).map((e,t)=>g.createElement("div",{key:t,className:"flex flex-col flex-shrink-0",style:{flex:k||"slider"!==m?void 0:`0 0 calc((100% - ${b*(v-1)}px) / ${v})`,gap:6}},g.createElement(Kw,{style:{aspectRatio:d,borderRadius:w,width:"100%"}}),g.createElement(Kw,{className:"h-3.5 w-4/5"})))))},qw=e=>{var t,r,n,i;const{widgetType:s,theme:a,layout:o}=e,{liveWidget:l}=Ed(),u=null!==(t=null==o?void 0:o.paddingTop)&&void 0!==t?t:0,c=null!==(r=null==o?void 0:o.paddingBottom)&&void 0!==r?r:0,d=null!==(n=null==o?void 0:o.paddingLeft)&&void 0!==n?n:0,h=null!==(i=null==o?void 0:o.paddingRight)&&void 0!==i?i:0;return null===l?g.createElement(Yw,Object.assign({},e)):0===l.length?g.createElement(Ww,Object.assign({},e)):g.createElement("div",{className:"w-full h-full",style:{backgroundColor:null==a?void 0:a.backgroundColor,color:null==a?void 0:a.textColor,paddingTop:u,paddingBottom:c,paddingLeft:d,paddingRight:h}},"ONE"===s&&"past"!==e.liveType?g.createElement(Vw,Object.assign({content:l[0]},e)):g.createElement(jw,Object.assign({content:l},e)))},Xw=U(e=>{const{container:t}=gc();return t?g.createElement(hr,null,g.createElement(mc,Object.assign({},e,{container:t}))):null},{props:{collectionId:"string",iconForm:"string",iconShape:"string",iconSize:"number",borderLine:"string",exposeTitle:"boolean",titlePosition:"string",player:"string",rounded:"boolean",exposeProductBanner:"boolean",exposeProductBadge:"boolean",priceText:"string",iconRatio:"string",hoverPlay:"boolean",thumbnailAutoPlay:"boolean"}}),Qw=U(e=>{const{container:t}=gc();return t?g.createElement(hr,null,g.createElement(yc,Object.assign({},e,{container:t}))):null},{props:{collectionId:"string",aspectRatio:"string"}}),Zw=U(({shortsId:e,type:t,isPreview:r})=>{const{setShortform:n,shortform:i}=bc();return p.useEffect(()=>{if(!e)return;e&&J(void 0,void 0,void 0,function*(){const t=yield rr(e,r);t&&n(Object.assign(Object.assign({},t),{uuid:Ut()}))})},[e]),i?g.createElement(oc.div,{style:{position:"fixed",inset:0,pointerEvents:"none",zIndex:99999}},g.createElement(pc,null),g.createElement("div",{style:{pointerEvents:"auto"}},g.createElement(yd,{shortsId:e,type:t}))):null},{props:{shortsId:"string",type:"string"}}),Jw=U(e=>{const{setLiveWidget:t,liveWidget:r}=Ed(),{userId:n,card:i,includeRepresentative:s,liveType:a}=e;return p.useEffect(()=>{if(!n)return;if(r&&(null==i?void 0:i.visibleCount)&&r.length>Number(i.visibleCount))return void t(r.slice(0,null==i?void 0:i.visibleCount));const o=new AbortController;return J(void 0,void 0,void 0,function*(){const r=yield nr(n,"past"===a?"FINISHED":"UPCOMING",(null==i?void 0:i.visibleCount)||6,s,e.sorting);if(!r||o.signal.aborted)return;t(r);const l=yield Promise.allSettled(r.map(e=>J(void 0,void 0,void 0,function*(){const t=yield((e,t)=>J(void 0,void 0,void 0,function*(){const{STATISTICS_BASE_URL:r}=Mt(),n=`${r}/replay/${e}/${t}/summary`,i=yield fetch(n);if(404!==i.status){if(!i.ok){const e=yield i.text().catch(()=>"");return console.error(`[ReplayStatistics] ${i.status} ${i.statusText} ${e}`),{pageView:0,like:0}}return i.json()}}))(n,e.eventId);return Object.assign(Object.assign({},e),{statistics:t})})));o.signal.aborted||t(l.map((e,t)=>"fulfilled"===e.status?e.value:r[t]))}),()=>o.abort()},[n,null==i?void 0:i.visibleCount,a,e.sorting,s]),g.createElement(oc.div,{className:"w-full h-full"},g.createElement(pc,null),g.createElement(qw,Object.assign({},e)))},{props:{userId:"string",title:"string",titleFontSize:"number",isPreview:"boolean",liveType:"string",widgetType:"string",videoAlign:"string",aspectRatio:"string",playback:"string",includeRepresentative:"boolean",theme:"json",layout:"json",card:"json",sorting:"string"}}),eE=U(({eventId:e})=>e?g.createElement(oc.div,{style:{position:"fixed",inset:0,pointerEvents:"none",zIndex:99999}},g.createElement(pc,null),g.createElement("div",{style:{pointerEvents:"auto"}},g.createElement(bd,{eventId:e}))):null,{props:{eventId:"string"}});customElements.define("mc-widget-player",Xw),customElements.define("mc-collection-showcase",Qw),customElements.define("mc-floating-player",Zw),customElements.define("mc-live-widget",Jw),customElements.define("mc-live-floating-player",eE)});
|
|
44
|
+
*/function Fu(){if(Mu)return Nu;Mu=1;var e=l();function t(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r<arguments.length;r++)t+="&args[]="+encodeURIComponent(arguments[r]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var r=null,n=0;function i(e,t){if(0!==t.length)if(512<t.length)0<n&&(e.enqueue(new Uint8Array(r.buffer,0,n)),r=new Uint8Array(512),n=0),e.enqueue(t);else{var i=r.length-n;i<t.length&&(0===i?e.enqueue(r):(r.set(t.subarray(0,i),n),e.enqueue(r),t=t.subarray(i)),r=new Uint8Array(512),n=0),r.set(t,n),n+=t.length}}function s(e,t){return i(e,t),!0}function a(e){r&&0<n&&(e.enqueue(new Uint8Array(r.buffer,0,n)),r=null,n=0)}var o=new TextEncoder;function u(e){return o.encode(e)}function c(e){return o.encode(e)}function d(e,t){"function"==typeof e.error?e.error(t):e.close()}var h=Object.prototype.hasOwnProperty,f=/^[: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]*$/,p={},g={};function m(e){return!!h.call(g,e)||!h.call(p,e)&&(f.test(e)?g[e]=!0:(p[e]=!0,!1))}function v(e,t,r,n,i,s,a){this.acceptsBooleans=2===t||3===t||4===t,this.attributeName=n,this.attributeNamespace=i,this.mustUseProperty=r,this.propertyName=e,this.type=t,this.sanitizeURL=s,this.removeEmptyString=a}var y={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){y[e]=new v(e,0,!1,e,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];y[t]=new v(t,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){y[e]=new v(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){y[e]=new v(e,2,!1,e,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){y[e]=new v(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){y[e]=new v(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){y[e]=new v(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){y[e]=new v(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){y[e]=new v(e,5,!1,e.toLowerCase(),null,!1,!1)});var b=/[\-:]([a-z])/g;function w(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(b,w);y[t]=new v(t,1,!1,e,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(b,w);y[t]=new v(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(b,w);y[t]=new v(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){y[e]=new v(e,1,!1,e.toLowerCase(),null,!1,!1)}),y.xlinkHref=new v("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){y[e]=new v(e,1,!1,e.toLowerCase(),null,!0,!0)});var E={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},S=["Webkit","ms","Moz","O"];Object.keys(E).forEach(function(e){S.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),E[t]=E[e]})});var T=/["'&<>]/;function x(e){if("boolean"==typeof e||"number"==typeof e)return""+e;e=""+e;var t=T.exec(e);if(t){var r,n="",i=0;for(r=t.index;r<e.length;r++){switch(e.charCodeAt(r)){case 34:t=""";break;case 38:t="&";break;case 39:t="'";break;case 60:t="<";break;case 62:t=">";break;default:continue}i!==r&&(n+=e.substring(i,r)),i=r+1,n+=t}e=i!==r?n+e.substring(i,r):n}return e}var k=/([A-Z])/g,A=/^ms-/,R=Array.isArray,L=c("<script>"),I=c("<\/script>"),C=c('<script src="'),P=c('<script type="module" src="'),D=c('" async=""><\/script>'),_=/(<\/|<)(s)(cript)/gi;function M(e,t,r,n){return t+("s"===r?"\\u0073":"\\u0053")+n}function O(e,t){return{insertionMode:e,selectedValue:t}}var N=c("\x3c!-- --\x3e");function F(e,t,r,n){return""===t?n:(n&&e.push(N),e.push(u(x(t))),!0)}var $=new Map,B=c(' style="'),U=c(":"),z=c(";");function j(e,r,n){if("object"!=typeof n)throw Error(t(62));for(var i in r=!0,n)if(h.call(n,i)){var s=n[i];if(null!=s&&"boolean"!=typeof s&&""!==s){if(0===i.indexOf("--")){var a=u(x(i));s=u(x((""+s).trim()))}else{a=i;var o=$.get(a);void 0!==o||(o=c(x(a.replace(k,"-$1").toLowerCase().replace(A,"-ms-"))),$.set(a,o)),a=o,s="number"==typeof s?0===s||h.call(E,i)?u(""+s):u(s+"px"):u(x((""+s).trim()))}r?(r=!1,e.push(B,a,U,s)):e.push(z,a,U,s)}}r||e.push(V)}var G=c(" "),H=c('="'),V=c('"'),W=c('=""');function K(e,t,r,n){switch(r){case"style":return void j(e,t,n);case"defaultValue":case"defaultChecked":case"innerHTML":case"suppressContentEditableWarning":case"suppressHydrationWarning":return}if(!(2<r.length)||"o"!==r[0]&&"O"!==r[0]||"n"!==r[1]&&"N"!==r[1])if(null!==(t=y.hasOwnProperty(r)?y[r]:null)){switch(typeof n){case"function":case"symbol":return;case"boolean":if(!t.acceptsBooleans)return}switch(r=u(t.attributeName),t.type){case 3:n&&e.push(G,r,W);break;case 4:!0===n?e.push(G,r,W):!1!==n&&e.push(G,r,H,u(x(n)),V);break;case 5:isNaN(n)||e.push(G,r,H,u(x(n)),V);break;case 6:!isNaN(n)&&1<=n&&e.push(G,r,H,u(x(n)),V);break;default:t.sanitizeURL&&(n=""+n),e.push(G,r,H,u(x(n)),V)}}else if(m(r)){switch(typeof n){case"function":case"symbol":return;case"boolean":if("data-"!==(t=r.toLowerCase().slice(0,5))&&"aria-"!==t)return}e.push(G,u(r),H,u(x(n)),V)}}var Y=c(">"),q=c("/>");function X(e,r,n){if(null!=r){if(null!=n)throw Error(t(60));if("object"!=typeof r||!("__html"in r))throw Error(t(61));null!=(r=r.__html)&&e.push(u(""+r))}}var Q=c(' selected=""');function Z(e,t,r,n){e.push(re(r));var i,s=r=null;for(i in t)if(h.call(t,i)){var a=t[i];if(null!=a)switch(i){case"children":r=a;break;case"dangerouslySetInnerHTML":s=a;break;default:K(e,n,i,a)}}return e.push(Y),X(e,s,r),"string"==typeof r?(e.push(u(x(r))),null):r}var J=c("\n"),ee=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,te=new Map;function re(e){var r=te.get(e);if(void 0===r){if(!ee.test(e))throw Error(t(65,e));r=c("<"+e),te.set(e,r)}return r}var ne=c("<!DOCTYPE html>");function ie(r,n,i,s,a){switch(n){case"select":r.push(re("select"));var o=null,l=null;for(p in i)if(h.call(i,p)){var c=i[p];if(null!=c)switch(p){case"children":o=c;break;case"dangerouslySetInnerHTML":l=c;break;case"defaultValue":case"value":break;default:K(r,s,p,c)}}return r.push(Y),X(r,l,o),o;case"option":l=a.selectedValue,r.push(re("option"));var d=c=null,f=null,p=null;for(o in i)if(h.call(i,o)){var g=i[o];if(null!=g)switch(o){case"children":c=g;break;case"selected":f=g;break;case"dangerouslySetInnerHTML":p=g;break;case"value":d=g;default:K(r,s,o,g)}}if(null!=l)if(i=null!==d?""+d:function(t){var r="";return e.Children.forEach(t,function(e){null!=e&&(r+=e)}),r}(c),R(l)){for(s=0;s<l.length;s++)if(""+l[s]===i){r.push(Q);break}}else""+l===i&&r.push(Q);else f&&r.push(Q);return r.push(Y),X(r,p,c),c;case"textarea":for(c in r.push(re("textarea")),p=l=o=null,i)if(h.call(i,c)&&null!=(d=i[c]))switch(c){case"children":p=d;break;case"value":o=d;break;case"defaultValue":l=d;break;case"dangerouslySetInnerHTML":throw Error(t(91));default:K(r,s,c,d)}if(null===o&&null!==l&&(o=l),r.push(Y),null!=p){if(null!=o)throw Error(t(92));if(R(p)&&1<p.length)throw Error(t(93));o=""+p}return"string"==typeof o&&"\n"===o[0]&&r.push(J),null!==o&&r.push(u(x(""+o))),null;case"input":for(l in r.push(re("input")),d=p=c=o=null,i)if(h.call(i,l)&&null!=(f=i[l]))switch(l){case"children":case"dangerouslySetInnerHTML":throw Error(t(399,"input"));case"defaultChecked":d=f;break;case"defaultValue":c=f;break;case"checked":p=f;break;case"value":o=f;break;default:K(r,s,l,f)}return null!==p?K(r,s,"checked",p):null!==d&&K(r,s,"checked",d),null!==o?K(r,s,"value",o):null!==c&&K(r,s,"value",c),r.push(q),null;case"menuitem":for(var v in r.push(re("menuitem")),i)if(h.call(i,v)&&null!=(o=i[v]))switch(v){case"children":case"dangerouslySetInnerHTML":throw Error(t(400));default:K(r,s,v,o)}return r.push(Y),null;case"title":for(g in r.push(re("title")),o=null,i)if(h.call(i,g)&&null!=(l=i[g]))switch(g){case"children":o=l;break;case"dangerouslySetInnerHTML":throw Error(t(434));default:K(r,s,g,l)}return r.push(Y),o;case"listing":case"pre":for(d in r.push(re(n)),l=o=null,i)if(h.call(i,d)&&null!=(c=i[d]))switch(d){case"children":o=c;break;case"dangerouslySetInnerHTML":l=c;break;default:K(r,s,d,c)}if(r.push(Y),null!=l){if(null!=o)throw Error(t(60));if("object"!=typeof l||!("__html"in l))throw Error(t(61));null!=(i=l.__html)&&("string"==typeof i&&0<i.length&&"\n"===i[0]?r.push(J,u(i)):r.push(u(""+i)))}return"string"==typeof o&&"\n"===o[0]&&r.push(J),o;case"area":case"base":case"br":case"col":case"embed":case"hr":case"img":case"keygen":case"link":case"meta":case"param":case"source":case"track":case"wbr":for(var y in r.push(re(n)),i)if(h.call(i,y)&&null!=(o=i[y]))switch(y){case"children":case"dangerouslySetInnerHTML":throw Error(t(399,n));default:K(r,s,y,o)}return r.push(q),null;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 Z(r,i,n,s);case"html":return 0===a.insertionMode&&r.push(ne),Z(r,i,n,s);default:if(-1===n.indexOf("-")&&"string"!=typeof i.is)return Z(r,i,n,s);for(f in r.push(re(n)),l=o=null,i)if(h.call(i,f)&&null!=(c=i[f]))switch(f){case"children":o=c;break;case"dangerouslySetInnerHTML":l=c;break;case"style":j(r,s,c);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":break;default:m(f)&&"function"!=typeof c&&"symbol"!=typeof c&&r.push(G,u(f),H,u(x(c)),V)}return r.push(Y),X(r,l,o),o}}var se=c("</"),ae=c(">"),oe=c('<template id="'),le=c('"></template>'),ue=c("\x3c!--$--\x3e"),ce=c('\x3c!--$?--\x3e<template id="'),de=c('"></template>'),he=c("\x3c!--$!--\x3e"),fe=c("\x3c!--/$--\x3e"),pe=c("<template"),ge=c('"'),me=c(' data-dgst="');c(' data-msg="'),c(' data-stck="');var ve=c("></template>");function ye(e,r,n){if(i(e,ce),null===n)throw Error(t(395));return i(e,n),s(e,de)}var be=c('<div hidden id="'),we=c('">'),Ee=c("</div>"),Se=c('<svg aria-hidden="true" style="display:none" id="'),Te=c('">'),xe=c("</svg>"),ke=c('<math aria-hidden="true" style="display:none" id="'),Ae=c('">'),Re=c("</math>"),Le=c('<table hidden id="'),Ie=c('">'),Ce=c("</table>"),Pe=c('<table hidden><tbody id="'),De=c('">'),_e=c("</tbody></table>"),Me=c('<table hidden><tr id="'),Oe=c('">'),Ne=c("</tr></table>"),Fe=c('<table hidden><colgroup id="'),$e=c('">'),Be=c("</colgroup></table>");var Ue=c('function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};$RS("'),ze=c('$RS("'),je=c('","'),Ge=c('")<\/script>'),He=c('function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}};$RC("'),Ve=c('$RC("'),We=c('","'),Ke=c('")<\/script>'),Ye=c('function $RX(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())};$RX("'),qe=c('$RX("'),Xe=c('"'),Qe=c(")<\/script>"),Ze=c(","),Je=/[<\u2028\u2029]/g;function et(e){return JSON.stringify(e).replace(Je,function(e){switch(e){case"<":return"\\u003c";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:throw Error("escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React")}})}var tt=Object.assign,rt=Symbol.for("react.element"),nt=Symbol.for("react.portal"),it=Symbol.for("react.fragment"),st=Symbol.for("react.strict_mode"),at=Symbol.for("react.profiler"),ot=Symbol.for("react.provider"),lt=Symbol.for("react.context"),ut=Symbol.for("react.forward_ref"),ct=Symbol.for("react.suspense"),dt=Symbol.for("react.suspense_list"),ht=Symbol.for("react.memo"),ft=Symbol.for("react.lazy"),pt=Symbol.for("react.scope"),gt=Symbol.for("react.debug_trace_mode"),mt=Symbol.for("react.legacy_hidden"),vt=Symbol.for("react.default_value"),yt=Symbol.iterator;function bt(e){if(null==e)return null;if("function"==typeof e)return e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case it:return"Fragment";case nt:return"Portal";case at:return"Profiler";case st:return"StrictMode";case ct:return"Suspense";case dt:return"SuspenseList"}if("object"==typeof e)switch(e.$$typeof){case lt:return(e.displayName||"Context")+".Consumer";case ot:return(e._context.displayName||"Context")+".Provider";case ut:var t=e.render;return(e=e.displayName)||(e=""!==(e=t.displayName||t.name||"")?"ForwardRef("+e+")":"ForwardRef"),e;case ht:return null!==(t=e.displayName||null)?t:bt(e.type)||"Memo";case ft:t=e._payload,e=e._init;try{return bt(e(t))}catch(e){}}return null}var wt={};function Et(e,t){if(!(e=e.contextTypes))return wt;var r,n={};for(r in e)n[r]=t[r];return n}var St=null;function Tt(e,r){if(e!==r){e.context._currentValue=e.parentValue,e=e.parent;var n=r.parent;if(null===e){if(null!==n)throw Error(t(401))}else{if(null===n)throw Error(t(401));Tt(e,n)}r.context._currentValue=r.value}}function xt(e){e.context._currentValue=e.parentValue,null!==(e=e.parent)&&xt(e)}function kt(e){var t=e.parent;null!==t&&kt(t),e.context._currentValue=e.value}function At(e,r){if(e.context._currentValue=e.parentValue,null===(e=e.parent))throw Error(t(402));e.depth===r.depth?Tt(e,r):At(e,r)}function Rt(e,r){var n=r.parent;if(null===n)throw Error(t(402));e.depth===n.depth?Tt(e,n):Rt(e,n),r.context._currentValue=r.value}function Lt(e){var t=St;t!==e&&(null===t?kt(e):null===e?xt(t):t.depth===e.depth?Tt(t,e):t.depth>e.depth?At(t,e):Rt(t,e),St=e)}var It={isMounted:function(){return!1},enqueueSetState:function(e,t){null!==(e=e._reactInternals).queue&&e.queue.push(t)},enqueueReplaceState:function(e,t){(e=e._reactInternals).replace=!0,e.queue=[t]},enqueueForceUpdate:function(){}};function Ct(e,t,r,n){var i=void 0!==e.state?e.state:null;e.updater=It,e.props=r,e.state=i;var s={queue:[],replace:!1};e._reactInternals=s;var a=t.contextType;if(e.context="object"==typeof a&&null!==a?a._currentValue:n,"function"==typeof(a=t.getDerivedStateFromProps)&&(i=null==(a=a(r,i))?i:tt({},i,a),e.state=i),"function"!=typeof t.getDerivedStateFromProps&&"function"!=typeof e.getSnapshotBeforeUpdate&&("function"==typeof e.UNSAFE_componentWillMount||"function"==typeof e.componentWillMount))if(t=e.state,"function"==typeof e.componentWillMount&&e.componentWillMount(),"function"==typeof e.UNSAFE_componentWillMount&&e.UNSAFE_componentWillMount(),t!==e.state&&It.enqueueReplaceState(e,e.state,null),null!==s.queue&&0<s.queue.length)if(t=s.queue,a=s.replace,s.queue=null,s.replace=!1,a&&1===t.length)e.state=t[0];else{for(s=a?t[0]:e.state,i=!0,a=a?1:0;a<t.length;a++){var o=t[a];null!=(o="function"==typeof o?o.call(e,s,r,n):o)&&(i?(i=!1,s=tt({},s,o)):tt(s,o))}e.state=s}else s.queue=null}var Pt={id:1,overflow:""};function Dt(e,t,r){var n=e.id;e=e.overflow;var i=32-_t(n)-1;n&=~(1<<i),r+=1;var s=32-_t(t)+i;if(30<s){var a=i-i%5;return s=(n&(1<<a)-1).toString(32),n>>=a,i-=a,{id:1<<32-_t(t)+i|r<<i|n,overflow:s+e}}return{id:1<<s|r<<i|n,overflow:e}}var _t=Math.clz32?Math.clz32:function(e){return e>>>=0,0===e?32:31-(Mt(e)/Ot|0)|0},Mt=Math.log,Ot=Math.LN2;var Nt="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},Ft=null,$t=null,Bt=null,Ut=null,zt=!1,jt=!1,Gt=0,Ht=null,Vt=0;function Wt(){if(null===Ft)throw Error(t(321));return Ft}function Kt(){if(0<Vt)throw Error(t(312));return{memoizedState:null,queue:null,next:null}}function Yt(){return null===Ut?null===Bt?(zt=!1,Bt=Ut=Kt()):(zt=!0,Ut=Bt):null===Ut.next?(zt=!1,Ut=Ut.next=Kt()):(zt=!0,Ut=Ut.next),Ut}function qt(){$t=Ft=null,jt=!1,Bt=null,Vt=0,Ut=Ht=null}function Xt(e,t){return"function"==typeof t?t(e):t}function Qt(e,t,r){if(Ft=Wt(),Ut=Yt(),zt){var n=Ut.queue;if(t=n.dispatch,null!==Ht&&void 0!==(r=Ht.get(n))){Ht.delete(n),n=Ut.memoizedState;do{n=e(n,r.action),r=r.next}while(null!==r);return Ut.memoizedState=n,[n,t]}return[Ut.memoizedState,t]}return e=e===Xt?"function"==typeof t?t():t:void 0!==r?r(t):t,Ut.memoizedState=e,e=(e=Ut.queue={last:null,dispatch:null}).dispatch=Jt.bind(null,Ft,e),[Ut.memoizedState,e]}function Zt(e,t){if(Ft=Wt(),t=void 0===t?null:t,null!==(Ut=Yt())){var r=Ut.memoizedState;if(null!==r&&null!==t){var n=r[1];e:if(null===n)n=!1;else{for(var i=0;i<n.length&&i<t.length;i++)if(!Nt(t[i],n[i])){n=!1;break e}n=!0}if(n)return r[0]}}return e=e(),Ut.memoizedState=[e,t],e}function Jt(e,r,n){if(25<=Vt)throw Error(t(301));if(e===Ft)if(jt=!0,e={action:n,next:null},null===Ht&&(Ht=new Map),void 0===(n=Ht.get(r)))Ht.set(r,e);else{for(r=n;null!==r.next;)r=r.next;r.next=e}}function er(){throw Error(t(394))}function tr(){}var rr={readContext:function(e){return e._currentValue},useContext:function(e){return Wt(),e._currentValue},useMemo:Zt,useReducer:Qt,useRef:function(e){Ft=Wt();var t=(Ut=Yt()).memoizedState;return null===t?(e={current:e},Ut.memoizedState=e):t},useState:function(e){return Qt(Xt,e)},useInsertionEffect:tr,useLayoutEffect:function(){},useCallback:function(e,t){return Zt(function(){return e},t)},useImperativeHandle:tr,useEffect:tr,useDebugValue:tr,useDeferredValue:function(e){return Wt(),e},useTransition:function(){return Wt(),[!1,er]},useId:function(){var e=$t.treeContext,r=e.overflow;e=((e=e.id)&~(1<<32-_t(e)-1)).toString(32)+r;var n=nr;if(null===n)throw Error(t(404));return r=Gt++,e=":"+n.idPrefix+"R"+e,0<r&&(e+="H"+r.toString(32)),e+":"},useMutableSource:function(e,t){return Wt(),t(e._source)},useSyncExternalStore:function(e,r,n){if(void 0===n)throw Error(t(407));return n()}},nr=null,ir=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher;function sr(e){return console.error(e),null}function ar(){}function or(e,t,r,n,i,s,a,o){e.allPendingTasks++,null===r?e.pendingRootTasks++:r.pendingTasks++;var l={node:t,ping:function(){var t=e.pingedTasks;t.push(l),1===t.length&&Sr(e)},blockedBoundary:r,blockedSegment:n,abortSet:i,legacyContext:s,context:a,treeContext:o};return i.add(l),l}function lr(e,t,r,n,i,s){return{status:0,id:-1,index:t,parentFlushed:!1,chunks:[],children:[],formatContext:n,boundary:r,lastPushedText:i,textEmbedded:s}}function ur(e,t){if(null!=(e=e.onError(t))&&"string"!=typeof e)throw Error('onError returned something with a type other than "string". onError should return a string and may return null or undefined but must not return anything else. It received something of type "'+typeof e+'" instead');return e}function cr(e,t){var r=e.onShellError;r(t),(r=e.onFatalError)(t),null!==e.destination?(e.status=2,d(e.destination,t)):(e.status=1,e.fatalError=t)}function dr(e,t,r,n,i){for(Ft={},$t=t,Gt=0,e=r(n,i);jt;)jt=!1,Gt=0,Vt+=1,Ut=null,e=r(n,i);return qt(),e}function hr(e,r,n,i){var s=n.render(),a=i.childContextTypes;if(null!=a){var o=r.legacyContext;if("function"!=typeof n.getChildContext)i=o;else{for(var l in n=n.getChildContext())if(!(l in a))throw Error(t(108,bt(i)||"Unknown",l));i=tt({},o,n)}r.legacyContext=i,gr(e,r,s),r.legacyContext=o}else gr(e,r,s)}function fr(e,t){if(e&&e.defaultProps){for(var r in t=tt({},t),e=e.defaultProps)void 0===t[r]&&(t[r]=e[r]);return t}return t}function pr(e,r,n,i,s){if("function"==typeof n)if(n.prototype&&n.prototype.isReactComponent){s=Et(n,r.legacyContext);var a=n.contextType;Ct(a=new n(i,"object"==typeof a&&null!==a?a._currentValue:s),n,i,s),hr(e,r,a,n)}else{s=dr(e,r,n,i,a=Et(n,r.legacyContext));var o=0!==Gt;if("object"==typeof s&&null!==s&&"function"==typeof s.render&&void 0===s.$$typeof)Ct(s,n,i,a),hr(e,r,s,n);else if(o){i=r.treeContext,r.treeContext=Dt(i,1,0);try{gr(e,r,s)}finally{r.treeContext=i}}else gr(e,r,s)}else{if("string"!=typeof n){switch(n){case mt:case gt:case st:case at:case it:case dt:return void gr(e,r,i.children);case pt:throw Error(t(343));case ct:e:{n=r.blockedBoundary,s=r.blockedSegment,a=i.fallback,i=i.children;var l={id:null,rootSegmentID:-1,parentFlushed:!1,pendingTasks:0,forceClientRender:!1,completedSegments:[],byteSize:0,fallbackAbortableTasks:o=new Set,errorDigest:null},c=lr(0,s.chunks.length,l,s.formatContext,!1,!1);s.children.push(c),s.lastPushedText=!1;var d=lr(0,0,null,s.formatContext,!1,!1);d.parentFlushed=!0,r.blockedBoundary=l,r.blockedSegment=d;try{if(vr(e,r,i),d.lastPushedText&&d.textEmbedded&&d.chunks.push(N),d.status=1,wr(l,d),0===l.pendingTasks)break e}catch(t){d.status=4,l.forceClientRender=!0,l.errorDigest=ur(e,t)}finally{r.blockedBoundary=n,r.blockedSegment=s}r=or(e,a,n,c,o,r.legacyContext,r.context,r.treeContext),e.pingedTasks.push(r)}return}if("object"==typeof n&&null!==n)switch(n.$$typeof){case ut:if(i=dr(e,r,n.render,i,s),0!==Gt){n=r.treeContext,r.treeContext=Dt(n,1,0);try{gr(e,r,i)}finally{r.treeContext=n}}else gr(e,r,i);return;case ht:return void pr(e,r,n=n.type,i=fr(n,i),s);case ot:if(s=i.children,n=n._context,i=i.value,a=n._currentValue,n._currentValue=i,St=i={parent:o=St,depth:null===o?0:o.depth+1,context:n,parentValue:a,value:i},r.context=i,gr(e,r,s),null===(e=St))throw Error(t(403));return i=e.parentValue,e.context._currentValue=i===vt?e.context._defaultValue:i,e=St=e.parent,void(r.context=e);case lt:return void gr(e,r,i=(i=i.children)(n._currentValue));case ft:return void pr(e,r,n=(s=n._init)(n._payload),i=fr(n,i),void 0)}throw Error(t(130,null==n?n:typeof n,""))}switch(a=ie((s=r.blockedSegment).chunks,n,i,e.responseState,s.formatContext),s.lastPushedText=!1,o=s.formatContext,s.formatContext=function(e,t,r){switch(t){case"select":return O(1,null!=r.value?r.value:r.defaultValue);case"svg":return O(2,null);case"math":return O(3,null);case"foreignObject":return O(1,null);case"table":return O(4,null);case"thead":case"tbody":case"tfoot":return O(5,null);case"colgroup":return O(7,null);case"tr":return O(6,null)}return 4<=e.insertionMode||0===e.insertionMode?O(1,null):e}(o,n,i),vr(e,r,a),s.formatContext=o,n){case"area":case"base":case"br":case"col":case"embed":case"hr":case"img":case"input":case"keygen":case"link":case"meta":case"param":case"source":case"track":case"wbr":break;default:s.chunks.push(se,u(n),ae)}s.lastPushedText=!1}}function gr(e,r,n){if(r.node=n,"object"==typeof n&&null!==n){switch(n.$$typeof){case rt:return void pr(e,r,n.type,n.props,n.ref);case nt:throw Error(t(257));case ft:var i=n._init;return void gr(e,r,n=i(n._payload))}if(R(n))return void mr(e,r,n);if(null===n||"object"!=typeof n?i=null:i="function"==typeof(i=yt&&n[yt]||n["@@iterator"])?i:null,i&&(i=i.call(n))){if(!(n=i.next()).done){var s=[];do{s.push(n.value),n=i.next()}while(!n.done);mr(e,r,s)}return}throw e=Object.prototype.toString.call(n),Error(t(31,"[object Object]"===e?"object with keys {"+Object.keys(n).join(", ")+"}":e))}"string"==typeof n?(i=r.blockedSegment).lastPushedText=F(r.blockedSegment.chunks,n,e.responseState,i.lastPushedText):"number"==typeof n&&((i=r.blockedSegment).lastPushedText=F(r.blockedSegment.chunks,""+n,e.responseState,i.lastPushedText))}function mr(e,t,r){for(var n=r.length,i=0;i<n;i++){var s=t.treeContext;t.treeContext=Dt(s,n,i);try{vr(e,t,r[i])}finally{t.treeContext=s}}}function vr(e,t,r){var n=t.blockedSegment.formatContext,i=t.legacyContext,s=t.context;try{return gr(e,t,r)}catch(l){if(qt(),"object"!=typeof l||null===l||"function"!=typeof l.then)throw t.blockedSegment.formatContext=n,t.legacyContext=i,t.context=s,Lt(s),l;r=l;var a=t.blockedSegment,o=lr(0,a.chunks.length,null,a.formatContext,a.lastPushedText,!0);a.children.push(o),a.lastPushedText=!1,e=or(e,t.node,t.blockedBoundary,o,t.abortSet,t.legacyContext,t.context,t.treeContext).ping,r.then(e,e),t.blockedSegment.formatContext=n,t.legacyContext=i,t.context=s,Lt(s)}}function yr(e){var t=e.blockedBoundary;(e=e.blockedSegment).status=3,Er(this,t,e)}function br(e,r,n){var i=e.blockedBoundary;e.blockedSegment.status=3,null===i?(r.allPendingTasks--,2!==r.status&&(r.status=2,null!==r.destination&&r.destination.close())):(i.pendingTasks--,i.forceClientRender||(i.forceClientRender=!0,e=void 0===n?Error(t(432)):n,i.errorDigest=r.onError(e),i.parentFlushed&&r.clientRenderedBoundaries.push(i)),i.fallbackAbortableTasks.forEach(function(e){return br(e,r,n)}),i.fallbackAbortableTasks.clear(),r.allPendingTasks--,0===r.allPendingTasks&&(i=r.onAllReady)())}function wr(e,t){if(0===t.chunks.length&&1===t.children.length&&null===t.children[0].boundary){var r=t.children[0];r.id=t.id,r.parentFlushed=!0,1===r.status&&wr(e,r)}else e.completedSegments.push(t)}function Er(e,r,n){if(null===r){if(n.parentFlushed){if(null!==e.completedRootSegment)throw Error(t(389));e.completedRootSegment=n}e.pendingRootTasks--,0===e.pendingRootTasks&&(e.onShellError=ar,(r=e.onShellReady)())}else r.pendingTasks--,r.forceClientRender||(0===r.pendingTasks?(n.parentFlushed&&1===n.status&&wr(r,n),r.parentFlushed&&e.completedBoundaries.push(r),r.fallbackAbortableTasks.forEach(yr,e),r.fallbackAbortableTasks.clear()):n.parentFlushed&&1===n.status&&(wr(r,n),1===r.completedSegments.length&&r.parentFlushed&&e.partialBoundaries.push(r)));e.allPendingTasks--,0===e.allPendingTasks&&(e=e.onAllReady)()}function Sr(e){if(2!==e.status){var t=St,r=ir.current;ir.current=rr;var n=nr;nr=e.responseState;try{var i,s=e.pingedTasks;for(i=0;i<s.length;i++){var a=s[i],o=e,l=a.blockedSegment;if(0===l.status){Lt(a.context);try{gr(o,a,a.node),l.lastPushedText&&l.textEmbedded&&l.chunks.push(N),a.abortSet.delete(a),l.status=1,Er(o,a.blockedBoundary,l)}catch(e){if(qt(),"object"==typeof e&&null!==e&&"function"==typeof e.then){var u=a.ping;e.then(u,u)}else{a.abortSet.delete(a),l.status=4;var c=a.blockedBoundary,d=e,h=ur(o,d);if(null===c?cr(o,d):(c.pendingTasks--,c.forceClientRender||(c.forceClientRender=!0,c.errorDigest=h,c.parentFlushed&&o.clientRenderedBoundaries.push(c))),o.allPendingTasks--,0===o.allPendingTasks)(0,o.onAllReady)()}}}}s.splice(0,i),null!==e.destination&&Lr(e,e.destination)}catch(t){ur(e,t),cr(e,t)}finally{nr=n,ir.current=r,r===rr&&Lt(t)}}}function Tr(e,r,n){switch(n.parentFlushed=!0,n.status){case 0:var a=n.id=e.nextSegmentId++;return n.lastPushedText=!1,n.textEmbedded=!1,e=e.responseState,i(r,oe),i(r,e.placeholderPrefix),i(r,e=u(a.toString(16))),s(r,le);case 1:n.status=2;var o=!0;a=n.chunks;var l=0;n=n.children;for(var c=0;c<n.length;c++){for(o=n[c];l<o.index;l++)i(r,a[l]);o=xr(e,r,o)}for(;l<a.length-1;l++)i(r,a[l]);return l<a.length&&(o=s(r,a[l])),o;default:throw Error(t(390))}}function xr(e,r,n){var a=n.boundary;if(null===a)return Tr(e,r,n);if(a.parentFlushed=!0,a.forceClientRender)a=a.errorDigest,s(r,he),i(r,pe),a&&(i(r,me),i(r,u(x(a))),i(r,ge)),s(r,ve),Tr(e,r,n);else if(0<a.pendingTasks){a.rootSegmentID=e.nextSegmentId++,0<a.completedSegments.length&&e.partialBoundaries.push(a);var o=e.responseState,l=o.nextSuspenseID++;o=c(o.boundaryPrefix+l.toString(16)),a=a.id=o,ye(r,e.responseState,a),Tr(e,r,n)}else if(a.byteSize>e.progressiveChunkSize)a.rootSegmentID=e.nextSegmentId++,e.completedBoundaries.push(a),ye(r,e.responseState,a.id),Tr(e,r,n);else{if(s(r,ue),1!==(n=a.completedSegments).length)throw Error(t(391));xr(e,r,n[0])}return s(r,fe)}function kr(e,r,n){return function(e,r,n,a){switch(n.insertionMode){case 0:case 1:return i(e,be),i(e,r.segmentPrefix),i(e,u(a.toString(16))),s(e,we);case 2:return i(e,Se),i(e,r.segmentPrefix),i(e,u(a.toString(16))),s(e,Te);case 3:return i(e,ke),i(e,r.segmentPrefix),i(e,u(a.toString(16))),s(e,Ae);case 4:return i(e,Le),i(e,r.segmentPrefix),i(e,u(a.toString(16))),s(e,Ie);case 5:return i(e,Pe),i(e,r.segmentPrefix),i(e,u(a.toString(16))),s(e,De);case 6:return i(e,Me),i(e,r.segmentPrefix),i(e,u(a.toString(16))),s(e,Oe);case 7:return i(e,Fe),i(e,r.segmentPrefix),i(e,u(a.toString(16))),s(e,$e);default:throw Error(t(397))}}(r,e.responseState,n.formatContext,n.id),xr(e,r,n),function(e,r){switch(r.insertionMode){case 0:case 1:return s(e,Ee);case 2:return s(e,xe);case 3:return s(e,Re);case 4:return s(e,Ce);case 5:return s(e,_e);case 6:return s(e,Ne);case 7:return s(e,Be);default:throw Error(t(397))}}(r,n.formatContext)}function Ar(e,r,n){for(var a=n.completedSegments,o=0;o<a.length;o++)Rr(e,r,n,a[o]);if(a.length=0,e=e.responseState,a=n.id,n=n.rootSegmentID,i(r,e.startInlineScript),e.sentCompleteBoundaryFunction?i(r,Ve):(e.sentCompleteBoundaryFunction=!0,i(r,He)),null===a)throw Error(t(395));return n=u(n.toString(16)),i(r,a),i(r,We),i(r,e.segmentPrefix),i(r,n),s(r,Ke)}function Rr(e,r,n,a){if(2===a.status)return!0;var o=a.id;if(-1===o){if(-1===(a.id=n.rootSegmentID))throw Error(t(392));return kr(e,r,a)}return kr(e,r,a),i(r,(e=e.responseState).startInlineScript),e.sentCompleteSegmentFunction?i(r,ze):(e.sentCompleteSegmentFunction=!0,i(r,Ue)),i(r,e.segmentPrefix),i(r,o=u(o.toString(16))),i(r,je),i(r,e.placeholderPrefix),i(r,o),s(r,Ge)}function Lr(e,o){r=new Uint8Array(512),n=0;try{var l=e.completedRootSegment;if(null!==l&&0===e.pendingRootTasks){xr(e,o,l),e.completedRootSegment=null;var c=e.responseState.bootstrapChunks;for(l=0;l<c.length-1;l++)i(o,c[l]);l<c.length&&s(o,c[l])}var d,h=e.clientRenderedBoundaries;for(d=0;d<h.length;d++){var f=h[d];c=o;var p=e.responseState,g=f.id,m=f.errorDigest,v=f.errorMessage,y=f.errorComponentStack;if(i(c,p.startInlineScript),p.sentClientRenderFunction?i(c,qe):(p.sentClientRenderFunction=!0,i(c,Ye)),null===g)throw Error(t(395));i(c,g),i(c,Xe),(m||v||y)&&(i(c,Ze),i(c,u(et(m||"")))),(v||y)&&(i(c,Ze),i(c,u(et(v||"")))),y&&(i(c,Ze),i(c,u(et(y)))),s(c,Qe)}h.splice(0,d);var b=e.completedBoundaries;for(d=0;d<b.length;d++)Ar(e,o,b[d]);b.splice(0,d),a(o),r=new Uint8Array(512),n=0;var w=e.partialBoundaries;for(d=0;d<w.length;d++){var E=w[d];e:{h=e,f=o;var S=E.completedSegments;for(p=0;p<S.length;p++)if(!Rr(h,f,E,S[p])){p++,S.splice(0,p);var T=!1;break e}S.splice(0,p),T=!0}if(!T)return e.destination=null,d++,void w.splice(0,d)}w.splice(0,d);var x=e.completedBoundaries;for(d=0;d<x.length;d++)Ar(e,o,x[d]);x.splice(0,d)}finally{a(o),0===e.allPendingTasks&&0===e.pingedTasks.length&&0===e.clientRenderedBoundaries.length&&0===e.completedBoundaries.length&&o.close()}}function Ir(e,t){try{var r=e.abortableTasks;r.forEach(function(r){return br(r,e,t)}),r.clear(),null!==e.destination&&Lr(e,e.destination)}catch(t){ur(e,t),cr(e,t)}}return Nu.renderToReadableStream=function(e,t){return new Promise(function(r,n){var i,s,a=new Promise(function(e,t){s=e,i=t}),o=function(e,t,r,n,i,s,a,o,l){var u=[],c=new Set;return(r=lr(t={destination:null,responseState:t,progressiveChunkSize:void 0===n?12800:n,status:0,fatalError:null,nextSegmentId:0,allPendingTasks:0,pendingRootTasks:0,completedRootSegment:null,abortableTasks:c,pingedTasks:u,clientRenderedBoundaries:[],completedBoundaries:[],partialBoundaries:[],onError:void 0===i?sr:i,onAllReady:void 0===s?ar:s,onShellReady:void 0===a?ar:a,onShellError:void 0===o?ar:o,onFatalError:void 0===l?ar:l},0,null,r,!1,!1)).parentFlushed=!0,e=or(t,e,null,r,c,wt,null,Pt),u.push(e),t}(e,function(e,t,r,n,i){e=void 0===e?"":e,t=void 0===t?L:c('<script nonce="'+x(t)+'">');var s=[];if(void 0!==r&&s.push(t,u((""+r).replace(_,M)),I),void 0!==n)for(r=0;r<n.length;r++)s.push(C,u(x(n[r])),D);if(void 0!==i)for(n=0;n<i.length;n++)s.push(P,u(x(i[n])),D);return{bootstrapChunks:s,startInlineScript:t,placeholderPrefix:c(e+"P:"),segmentPrefix:c(e+"S:"),boundaryPrefix:e+"B:",idPrefix:e,nextSuspenseID:0,sentCompleteSegmentFunction:!1,sentCompleteBoundaryFunction:!1,sentClientRenderFunction:!1}}(t?t.identifierPrefix:void 0,t?t.nonce:void 0,t?t.bootstrapScriptContent:void 0,t?t.bootstrapScripts:void 0,t?t.bootstrapModules:void 0),function(e){return O("http://www.w3.org/2000/svg"===e?2:"http://www.w3.org/1998/Math/MathML"===e?3:0,null)}(t?t.namespaceURI:void 0),t?t.progressiveChunkSize:void 0,t?t.onError:void 0,s,function(){var e=new ReadableStream({type:"bytes",pull:function(e){if(1===o.status)o.status=2,d(e,o.fatalError);else if(2!==o.status&&null===o.destination){o.destination=e;try{Lr(o,e)}catch(e){ur(o,e),cr(o,e)}}},cancel:function(){Ir(o)}},{highWaterMark:0});e.allReady=a,r(e)},function(e){a.catch(function(){}),n(e)},i);if(t&&t.signal){var l=t.signal,h=function(){Ir(o,l.reason),l.removeEventListener("abort",h)};l.addEventListener("abort",h)}Sr(o)})},Nu.version="18.3.1",Nu}var $u,Bu,Uu,zu,ju,Gu=function(){return Ou||(Ou=1,e=_u(),t=Fu(),Pu.version=e.version,Pu.renderToString=e.renderToString,Pu.renderToStaticMarkup=e.renderToStaticMarkup,Pu.renderToNodeStream=e.renderToNodeStream,Pu.renderToStaticNodeStream=e.renderToStaticNodeStream,Pu.renderToReadableStream=t.renderToReadableStream),Pu;var e,t}(),Hu={exports:{}};function Vu(){if(Bu)return $u;Bu=1;return $u="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"}function Wu(){if(zu)return Uu;zu=1;var e=Vu();function t(){}function r(){}return r.resetWarningCache=t,Uu=function(){function n(t,r,n,i,s,a){if(a!==e){var o=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw o.name="Invariant Violation",o}}function i(){return n}n.isRequired=n;var s={array:n,bigint:n,bool:n,func:n,number:n,object:n,string:n,symbol:n,any:n,arrayOf:i,element:n,elementType:n,instanceOf:i,node:n,objectOf:i,oneOf:i,oneOfType:i,shape:i,exact:i,checkPropTypes:r,resetWarningCache:t};return s.PropTypes=s,s}}function Ku(){return ju||(ju=1,Hu.exports=Wu()()),Hu.exports}var Yu=t(Ku()),qu="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Xu(e,t){return e(t={exports:{}},t.exports),t.exports}var Qu=Xu(function(e){!function(t){var r=function(e,t,n){if(!l(t)||c(t)||d(t)||h(t)||o(t))return t;var i,s=0,a=0;if(u(t))for(i=[],a=t.length;s<a;s++)i.push(r(e,t[s],n));else for(var f in i={},t)Object.prototype.hasOwnProperty.call(t,f)&&(i[e(f,n)]=r(e,t[f],n));return i},n=function(e){return f(e)?e:(e=e.replace(/[\-_\s]+(.)?/g,function(e,t){return t?t.toUpperCase():""})).substr(0,1).toLowerCase()+e.substr(1)},i=function(e){var t=n(e);return t.substr(0,1).toUpperCase()+t.substr(1)},s=function(e,t){return function(e,t){var r=(t=t||{}).separator||"_",n=t.split||/(?=[A-Z])/;return e.split(n).join(r)}(e,t).toLowerCase()},a=Object.prototype.toString,o=function(e){return"function"==typeof e},l=function(e){return e===Object(e)},u=function(e){return"[object Array]"==a.call(e)},c=function(e){return"[object Date]"==a.call(e)},d=function(e){return"[object RegExp]"==a.call(e)},h=function(e){return"[object Boolean]"==a.call(e)},f=function(e){return(e-=0)==e},p=function(e,t){var r=t&&"process"in t?t.process:t;return"function"!=typeof r?e:function(t,n){return r(t,e,n)}},g={camelize:n,decamelize:s,pascalize:i,depascalize:s,camelizeKeys:function(e,t){return r(p(n,t),e)},decamelizeKeys:function(e,t){return r(p(s,t),e,t)},pascalizeKeys:function(e,t){return r(p(i,t),e)},depascalizeKeys:function(){return this.decamelizeKeys.apply(this,arguments)}};e.exports?e.exports=g:t.humps=g}(qu)}).decamelize,Zu=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n},Ju=function(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e)){var r=[],n=!0,i=!1,s=void 0;try{for(var a,o=e[Symbol.iterator]();!(n=(a=o.next()).done)&&(r.push(a.value),!t||r.length!==t);n=!0);}catch(e){i=!0,s=e}finally{try{n||null==o.return||o.return()}finally{if(i)throw s}}return r}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Zu(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Zu(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()},ec=Xu(function(e){function t(){return e.exports=t=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},t.apply(this,arguments)}e.exports=t}),tc=function(e,t){if(null==e)return{};var r,n,i=function(e,t){if(null==e)return{};var r,n,i={},s=Object.keys(e);for(n=0;n<s.length;n++)r=s[n],t.indexOf(r)>=0||(i[r]=e[r]);return i}(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(n=0;n<s.length;n++)r=s[n],t.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(i[r]=e[r])}return i},rc=p.createContext(null);function nc(e){var t=e.children,r=void 0===t?"":t,n=tc(e,["children"]);return"string"!=typeof r&&(r=Gu.renderToString(r)),g.createElement("template",ec({},n,{dangerouslySetInnerHTML:{__html:r}}))}function ic(e){var t=e.root,r=e.children;return Pi.createPortal(void 0===r?null:r,t)}nc.propTypes={children:Yu.oneOfType([Yu.string,Yu.node])},ic.propTypes={root:Yu.object.isRequired,children:Yu.node};var sc=new Map;var ac=function(){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"core",t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(e){return e.children};return new Proxy(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{get:function(r,n){var i=Qu(n,{separator:"-"}),s="".concat(e,"-").concat(i);return sc.has(s)||sc.set(s,function(e){var t=p.forwardRef(function(t,r){var n,i,s=t.mode,a=void 0===s?"open":s,o=t.delegatesFocus,l=void 0!==o&&o,u=t.styleSheets,c=void 0===u?[]:u,d=t.ssr,h=void 0!==d&&d,f=t.children,m=tc(t,["mode","delegatesFocus","styleSheets","ssr","children"]),v=(i=p.useRef((n=r)&&n.current),p.useEffect(function(){n&&(n.current=i.current)},[n]),i),y=p.useState(null),b=Ju(y,2),w=b[0],E=b[1],S="node_".concat(a).concat(l);return p.useLayoutEffect(function(){if(v.current)try{if("function"==typeof r&&r(v.current),h){var e=v.current.shadowRoot;return void E(e)}var t=v.current.attachShadow({mode:a,delegatesFocus:l});c.length>0&&(t.adoptedStyleSheets=c),E(t)}catch(e){!function(e){var t=e.error,r=e.styleSheets,n=e.root;if("NotSupportedError"!==t.name)throw t;r.length>0&&(n.adoptedStyleSheets=r)}({error:e,styleSheets:c,root:w})}},[r,v,c]),g.createElement(g.Fragment,null,g.createElement(e.tag,ec({key:S,ref:v},m),(w||h)&&g.createElement(rc.Provider,{value:w},h?g.createElement(nc,{shadowroot:a,shadowrootmode:a},e.render({root:w,ssr:h,children:f})):g.createElement(ic,{root:w},e.render({root:w,ssr:h,children:f})))))});return t.propTypes={mode:Yu.oneOf(["open","closed"]),delegatesFocus:Yu.bool,styleSheets:Yu.arrayOf(Yu.instanceOf(globalThis.CSSStyleSheet)),ssr:Yu.bool,children:Yu.node},t}({tag:i,render:t})),sc.get(s)}})}();const oc='/*! tailwindcss v4.0.12 | MIT License | https://tailwindcss.com */@layer theme, base, components, utilities;@layer theme{:host,:root{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-500:oklch(0.637 0.237 25.331);--color-blue-200:oklch(0.882 0.059 254.128);--color-blue-300:oklch(0.809 0.105 251.813);--color-gray-200:oklch(0.928 0.006 264.531);--color-gray-400:oklch(0.707 0.022 261.325);--color-gray-500:oklch(0.551 0.027 264.364);--color-gray-700:oklch(0.373 0.034 259.733);--color-gray-800:oklch(0.278 0.033 256.848);--color-gray-900:oklch(0.21 0.034 264.665);--color-zinc-700:oklch(0.37 0.013 285.805);--color-black:#000;--color-white:#fff;--spacing:0.25rem;--container-sm:24rem;--container-lg:32rem;--text-xs:0.75rem;--text-xs--line-height:1.33333;--text-sm:0.875rem;--text-sm--line-height:1.42857;--text-lg:1.125rem;--text-lg--line-height:1.55556;--text-xl:1.25rem;--text-xl--line-height:1.4;--font-weight-medium:500;--font-weight-semibold:600;--leading-tight:1.25;--ease-in:cubic-bezier(0.4,0,1,1);--ease-in-out:cubic-bezier(0.4,0,0.2,1);--animate-pulse:pulse 2s cubic-bezier(0.4,0,0.6,1) infinite;--aspect-video:16/9;--default-transition-duration:150ms;--default-transition-timing-function:cubic-bezier(0.4,0,0.2,1);--default-font-family:var(--font-sans);--default-font-feature-settings:var(--font-sans--font-feature-settings);--default-font-variation-settings:var(\n --font-sans--font-variation-settings\n );--default-mono-font-family:var(--font-mono);--default-mono-font-feature-settings:var(\n --font-mono--font-feature-settings\n );--default-mono-font-variation-settings:var(\n --font-mono--font-variation-settings\n );--animate-float:float 2s ease}}@layer base{*,::backdrop,::file-selector-button,:after,:before{border:0 solid;box-sizing:border-box;margin:0;padding:0}:host,html{-webkit-text-size-adjust:100%;font-feature-settings:var(--default-font-feature-settings,normal);-webkit-tap-highlight-color:transparent;font-family:var( --default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji" );font-variation-settings:var( --default-font-variation-settings,normal );line-height:1.5;tab-size:4}body{line-height:inherit}hr{border-top-width:1px;color:inherit;height:0}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-feature-settings:var( --default-mono-font-feature-settings,normal );font-family:var( --default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace );font-size:1em;font-variation-settings:var( --default-mono-font-variation-settings,normal )}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{border-collapse:collapse;border-color:inherit;text-indent:0}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}menu,ol,ul{list-style:none}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{height:auto;max-width:100%}::file-selector-button,button,input,optgroup,select,textarea{font-feature-settings:inherit;background-color:transparent;border-radius:0;color:inherit;font:inherit;font-variation-settings:inherit;letter-spacing:inherit;opacity:1}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{color:color-mix(in oklab,currentColor 50%,transparent);opacity:1}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit,::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-meridiem-field,::-webkit-datetime-edit-millisecond-field,::-webkit-datetime-edit-minute-field,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-second-field,::-webkit-datetime-edit-year-field{padding-block:0}:-moz-ui-invalid{box-shadow:none}::file-selector-button,button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer utilities{.pointer-events-none{pointer-events:none}.visible{visibility:visible}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.inset-0{inset:calc(var(--spacing)*0)}.top-0{top:calc(var(--spacing)*0)}.top-4{top:calc(var(--spacing)*4)}.right-4{right:calc(var(--spacing)*4)}.bottom-0{bottom:calc(var(--spacing)*0)}.left-0{left:calc(var(--spacing)*0)}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\\[1\\]{z-index:1}.z-\\[5\\]{z-index:5}.z-\\[999\\]{z-index:999}.z-\\[999999\\]{z-index:999999}.container{width:100%;@media (width >= 40rem){max-width:40rem}@media (width >= 48rem){max-width:48rem}@media (width >= 64rem){max-width:64rem}@media (width >= 80rem){max-width:80rem}@media (width >= 96rem){max-width:96rem}}.mx-0{margin-inline:calc(var(--spacing)*0)}.mx-10{margin-inline:calc(var(--spacing)*10)}.mx-auto{margin-inline:auto}.my-0{margin-block:calc(var(--spacing)*0)}.my-2{margin-block:calc(var(--spacing)*2)}.my-10{margin-block:calc(var(--spacing)*10)}.mt-2{margin-top:calc(var(--spacing)*2)}.mt-3{margin-top:calc(var(--spacing)*3)}.mt-4{margin-top:calc(var(--spacing)*4)}.mt-auto{margin-top:auto}.mr-2{margin-right:calc(var(--spacing)*2)}.mb-1{margin-bottom:calc(var(--spacing)*1)}.mb-2{margin-bottom:calc(var(--spacing)*2)}.mb-3{margin-bottom:calc(var(--spacing)*3)}.line-clamp-1{-webkit-line-clamp:1}.line-clamp-1,.line-clamp-2{-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.line-clamp-2{-webkit-line-clamp:2}.block{display:block}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.table{display:table}.aspect-\\[9\\/16\\]{aspect-ratio:9/16}.aspect-square{aspect-ratio:1/1}.aspect-video{aspect-ratio:var(--aspect-video)}.size-3{height:calc(var(--spacing)*3);width:calc(var(--spacing)*3)}.size-4{height:calc(var(--spacing)*4);width:calc(var(--spacing)*4)}.h-1{height:calc(var(--spacing)*1)}.h-2{height:calc(var(--spacing)*2)}.h-3\\.5{height:calc(var(--spacing)*3.5)}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-6{height:calc(var(--spacing)*6)}.h-10{height:calc(var(--spacing)*10)}.h-12{height:calc(var(--spacing)*12)}.h-14{height:calc(var(--spacing)*14)}.h-16{height:calc(var(--spacing)*16)}.h-\\[24px\\]{height:24px}.h-\\[60px\\]{height:60px}.h-\\[80\\%\\]{height:80%}.h-\\[100px\\]{height:100px}.h-\\[125px\\]{height:125px}.h-\\[500px\\]{height:500px}.h-\\[600px\\]{height:600px}.h-auto{height:auto}.h-full{height:100%}.max-h-\\[150px\\]{max-height:150px}.max-h-\\[300px\\]{max-height:300px}.max-h-fit{max-height:fit-content}.max-h-full{max-height:100%}.\\!w-auto{width:auto!important}.w-4{width:calc(var(--spacing)*4)}.w-4\\/5{width:80%}.w-12{width:calc(var(--spacing)*12)}.w-14{width:calc(var(--spacing)*14)}.w-16{width:calc(var(--spacing)*16)}.w-32{width:calc(var(--spacing)*32)}.w-36{width:calc(var(--spacing)*36)}.w-\\[24px\\]{width:24px}.w-\\[50px\\]{width:50px}.w-\\[80\\%\\]{width:80%}.w-\\[100px\\]{width:100px}.w-\\[400px\\]{width:400px}.w-\\[500px\\]{width:500px}.w-\\[1024px\\]{width:1024px}.w-full{width:100%}.max-w-16{max-width:calc(var(--spacing)*16)}.max-w-52{max-width:calc(var(--spacing)*52)}.max-w-\\[40\\%\\]{max-width:40%}.max-w-\\[800px\\]{max-width:800px}.max-w-fit{max-width:fit-content}.max-w-full{max-width:100%}.max-w-lg{max-width:var(--container-lg)}.max-w-none{max-width:none}.min-w-0{min-width:calc(var(--spacing)*0)}.min-w-44{min-width:calc(var(--spacing)*44)}.min-w-\\[768px\\]{min-width:768px}.flex-1{flex:1}.flex-\\[2\\]{flex:2}.flex-none{flex:none}.flex-shrink-0,.shrink-0{flex-shrink:0}.grow{flex-grow:1}.border-collapse{border-collapse:collapse}.translate-y-0\\.5{--tw-translate-y:calc(var(--spacing)*0.5);translate:var(--tw-translate-x) var(--tw-translate-y)}.transform{transform:var(--tw-rotate-x) var(--tw-rotate-y) var(--tw-rotate-z) var(--tw-skew-x) var(--tw-skew-y)}.animate-float{animation:var(--animate-float)}.animate-pulse{animation:var(--animate-pulse)}.cursor-default{cursor:default}.cursor-pointer{cursor:pointer}.touch-none{touch-action:none}.resize{resize:both}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.flex-wrap{flex-wrap:wrap}.items-baseline{align-items:baseline}.items-center{align-items:center}.items-end{align-items:flex-end}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.justify-items-center{justify-items:center}.gap-1{gap:calc(var(--spacing)*1)}.gap-1\\.5{gap:calc(var(--spacing)*1.5)}.gap-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}.gap-5{gap:calc(var(--spacing)*5)}.gap-10{gap:calc(var(--spacing)*10)}.self-center{align-self:center}.justify-self-end{justify-self:flex-end}.truncate{text-overflow:ellipsis;white-space:nowrap}.overflow-hidden,.truncate{overflow:hidden}.overflow-scroll{overflow:scroll}.overflow-y-auto{overflow-y:auto}.overflow-y-scroll{overflow-y:scroll}.rounded{border-radius:.25rem}.rounded-full{border-radius:calc(infinity * 1px)}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-xl{border-radius:calc(var(--radius) + 4px)}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-none{--tw-border-style:none;border-style:none}.border-\\[\\#f4f3f6\\]{border-color:#f4f3f6}.bg-\\[\\#0ab060\\]{background-color:#0ab060}.bg-\\[\\#eeeeee\\]{background-color:#eee}.bg-\\[\\#f4f4f4\\]{background-color:#f4f4f4}.bg-\\[rgba\\(0\\,0\\,0\\,\\.3\\)\\]{background-color:rgba(0,0,0,.3)}.bg-background{background-color:var(--background)}.bg-black{background-color:var(--color-black)}.bg-black\\/50{background-color:color-mix(in oklab,var(--color-black) 50%,transparent)}.bg-blue-200{background-color:var(--color-blue-200)}.bg-blue-300{background-color:var(--color-blue-300)}.bg-gray-200{background-color:var(--color-gray-200)}.bg-muted{background-color:var(--muted)}.bg-white{background-color:var(--color-white)}.bg-zinc-700{background-color:var(--color-zinc-700)}.bg-gradient-to-b{--tw-gradient-position:to bottom in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.from-black\\/40{--tw-gradient-from:color-mix(in oklab,var(--color-black) 40%,transparent);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from) var(--tw-gradient-from-position),var(--tw-gradient-to) var(--tw-gradient-to-position))}.via-transparent{--tw-gradient-via:transparent;--tw-gradient-via-stops:var(--tw-gradient-position),var(--tw-gradient-from) var(--tw-gradient-from-position),var(--tw-gradient-via) var(--tw-gradient-via-position),var(--tw-gradient-to) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.to-black\\/40{--tw-gradient-to:color-mix(in oklab,var(--color-black) 40%,transparent);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from) var(--tw-gradient-from-position),var(--tw-gradient-to) var(--tw-gradient-to-position))}.fill-black{fill:var(--color-black)}.fill-red-500{fill:var(--color-red-500)}.fill-white{fill:var(--color-white)}.object-contain{object-fit:contain}.object-cover{object-fit:cover}.object-center{object-position:center}.p-0{padding:calc(var(--spacing)*0)}.p-1{padding:calc(var(--spacing)*1)}.p-2{padding:calc(var(--spacing)*2)}.p-4{padding:calc(var(--spacing)*4)}.p-6{padding:calc(var(--spacing)*6)}.p-10{padding:calc(var(--spacing)*10)}.p-\\[3px\\]{padding:3px}.px-2{padding-inline:calc(var(--spacing)*2)}.px-4{padding-inline:calc(var(--spacing)*4)}.px-\\[24px\\]{padding-inline:24px}.py-2{padding-block:calc(var(--spacing)*2)}.py-4{padding-block:calc(var(--spacing)*4)}.pt-0{padding-top:calc(var(--spacing)*0)}.pr-1{padding-right:calc(var(--spacing)*1)}.pb-4{padding-bottom:calc(var(--spacing)*4)}.pb-10{padding-bottom:calc(var(--spacing)*10)}.text-center{text-align:center}.text-left{text-align:left}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\\[10px\\]{font-size:10px}.text-\\[12px\\]{font-size:12px}.leading-none{--tw-leading:1;line-height:1}.leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.break-keep{word-break:keep-all}.text-clip{text-overflow:clip}.text-ellipsis{text-overflow:ellipsis}.whitespace-nowrap{white-space:nowrap}.text-black{color:var(--color-black)}.text-foreground{color:var(--foreground)}.text-gray-400{color:var(--color-gray-400)}.text-gray-500{color:var(--color-gray-500)}.text-gray-700{color:var(--color-gray-700)}.text-gray-800{color:var(--color-gray-800)}.text-gray-900{color:var(--color-gray-900)}.text-muted-foreground{color:var(--muted-foreground)}.text-red-500{color:var(--color-red-500)}.text-transparent{color:transparent}.text-white{color:var(--color-white)}.line-through{text-decoration-line:line-through}.no-underline{text-decoration-line:none}.opacity-50{opacity:50%}.opacity-70{opacity:70%}.shadow,.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,rgba(0,0,0,.1)),0 1px 2px -1px var(--tw-shadow-color,rgba(0,0,0,.1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-ring\\/30{--tw-ring-color:color-mix(in oklab,var(--ring) 30%,transparent)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.transition{transition-duration:var(--tw-duration,var(--default-transition-duration));transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function))}.transition-\\[color\\,box-shadow\\]{transition-duration:var(--tw-duration,var(--default-transition-duration));transition-property:color,box-shadow;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function))}.transition-all{transition-duration:var(--tw-duration,var(--default-transition-duration));transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function))}.transition-opacity{transition-duration:var(--tw-duration,var(--default-transition-duration));transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function))}.transition-transform{transition-duration:var(--tw-duration,var(--default-transition-duration));transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function))}.duration-200{--tw-duration:200ms;transition-duration:.2s}.ease-in{--tw-ease:var(--ease-in);transition-timing-function:var(--ease-in)}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.outline-none{--tw-outline-style:none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}.duration-200{animation-duration:.2s}.ease-in{animation-timing-function:cubic-bezier(.4,0,1,1)}.ease-in-out{animation-timing-function:cubic-bezier(.4,0,.2,1)}.fade-in{--tw-enter-opacity:0}.group-data-\\[vaul-drawer-direction\\=bottom\\]\\/drawer-content\\:block{&:is(:where(.group\\/drawer-content)[data-vaul-drawer-direction=bottom] *){display:block}}.last\\:border-b-0{&:last-child{border-bottom-style:var(--tw-border-style);border-bottom-width:0}}.hover\\:underline{&:hover{@media (hover:hover){text-decoration-line:underline}}}.hover\\:opacity-100{&:hover{@media (hover:hover){opacity:100%}}}.hover\\:ring-4{&:hover{@media (hover:hover){--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentColor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}}.focus\\:ring-2{&:focus{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentColor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}.focus\\:ring-ring{&:focus{--tw-ring-color:var(--ring)}}.focus\\:ring-offset-2{&:focus{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}}.focus\\:ring-offset-background{&:focus{--tw-ring-offset-color:var(--background)}}.focus\\:outline-none{&:focus{--tw-outline-style:none;outline-style:none}}.focus-visible\\:border-ring{&:focus-visible{border-color:var(--ring)}}.focus-visible\\:ring-4{&:focus-visible{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentColor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}.focus-visible\\:ring-\\[3px\\]{&:focus-visible{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentColor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}.focus-visible\\:ring-ring\\/50{&:focus-visible{--tw-ring-color:color-mix(in oklab,var(--ring) 50%,transparent)}}.focus-visible\\:outline-hidden{&:focus-visible{--tw-outline-style:none;outline-style:none;@media (forced-colors:active){outline:2px solid transparent;outline-offset:2px}}}.disabled\\:pointer-events-none{&:disabled{pointer-events:none}}.disabled\\:opacity-50{&:disabled{opacity:50%}}.data-\\[disabled\\]\\:opacity-50{&[data-disabled]{opacity:50%}}.data-\\[orientation\\=horizontal\\]\\:h-1\\.5{&[data-orientation=horizontal]{height:calc(var(--spacing)*1.5)}}.data-\\[orientation\\=horizontal\\]\\:h-full{&[data-orientation=horizontal]{height:100%}}.data-\\[orientation\\=horizontal\\]\\:w-full{&[data-orientation=horizontal]{width:100%}}.data-\\[orientation\\=vertical\\]\\:h-full{&[data-orientation=vertical]{height:100%}}.data-\\[orientation\\=vertical\\]\\:min-h-44{&[data-orientation=vertical]{min-height:calc(var(--spacing)*44)}}.data-\\[orientation\\=vertical\\]\\:w-1\\.5{&[data-orientation=vertical]{width:calc(var(--spacing)*1.5)}}.data-\\[orientation\\=vertical\\]\\:w-auto{&[data-orientation=vertical]{width:auto}}.data-\\[orientation\\=vertical\\]\\:w-full{&[data-orientation=vertical]{width:100%}}.data-\\[orientation\\=vertical\\]\\:flex-col{&[data-orientation=vertical]{flex-direction:column}}.data-\\[state\\=closed\\]\\:animate-out{&[data-state=closed]{--tw-exit-opacity:initial;--tw-exit-scale:initial;--tw-exit-rotate:initial;--tw-exit-translate-x:initial;--tw-exit-translate-y:initial;animation-duration:.15s;animation-name:exit}}.data-\\[state\\=closed\\]\\:fade-out-0{&[data-state=closed]{--tw-exit-opacity:0}}.data-\\[state\\=open\\]\\:animate-in{&[data-state=open]{--tw-enter-opacity:initial;--tw-enter-scale:initial;--tw-enter-rotate:initial;--tw-enter-translate-x:initial;--tw-enter-translate-y:initial;animation-duration:.15s;animation-name:enter}}.data-\\[state\\=open\\]\\:fade-in-0{&[data-state=open]{--tw-enter-opacity:0}}.data-\\[vaul-drawer-direction\\=bottom\\]\\:inset-x-0{&[data-vaul-drawer-direction=bottom]{inset-inline:calc(var(--spacing)*0)}}.data-\\[vaul-drawer-direction\\=bottom\\]\\:bottom-0{&[data-vaul-drawer-direction=bottom]{bottom:calc(var(--spacing)*0)}}.data-\\[vaul-drawer-direction\\=bottom\\]\\:mt-24{&[data-vaul-drawer-direction=bottom]{margin-top:calc(var(--spacing)*24)}}.data-\\[vaul-drawer-direction\\=bottom\\]\\:max-h-\\[80vh\\]{&[data-vaul-drawer-direction=bottom]{max-height:80vh}}.data-\\[vaul-drawer-direction\\=bottom\\]\\:rounded-t-lg{&[data-vaul-drawer-direction=bottom]{border-top-left-radius:var(--radius);border-top-right-radius:var(--radius)}}.data-\\[vaul-drawer-direction\\=bottom\\]\\:border-t{&[data-vaul-drawer-direction=bottom]{border-top-style:var(--tw-border-style);border-top-width:1px}}.data-\\[vaul-drawer-direction\\=left\\]\\:inset-y-0{&[data-vaul-drawer-direction=left]{inset-block:calc(var(--spacing)*0)}}.data-\\[vaul-drawer-direction\\=left\\]\\:left-0{&[data-vaul-drawer-direction=left]{left:calc(var(--spacing)*0)}}.data-\\[vaul-drawer-direction\\=left\\]\\:w-3\\/4{&[data-vaul-drawer-direction=left]{width:75%}}.data-\\[vaul-drawer-direction\\=left\\]\\:border-r{&[data-vaul-drawer-direction=left]{border-right-style:var(--tw-border-style);border-right-width:1px}}.data-\\[vaul-drawer-direction\\=right\\]\\:inset-y-0{&[data-vaul-drawer-direction=right]{inset-block:calc(var(--spacing)*0)}}.data-\\[vaul-drawer-direction\\=right\\]\\:right-0{&[data-vaul-drawer-direction=right]{right:calc(var(--spacing)*0)}}.data-\\[vaul-drawer-direction\\=right\\]\\:w-3\\/4{&[data-vaul-drawer-direction=right]{width:75%}}.data-\\[vaul-drawer-direction\\=right\\]\\:border-l{&[data-vaul-drawer-direction=right]{border-left-style:var(--tw-border-style);border-left-width:1px}}.data-\\[vaul-drawer-direction\\=top\\]\\:inset-x-0{&[data-vaul-drawer-direction=top]{inset-inline:calc(var(--spacing)*0)}}.data-\\[vaul-drawer-direction\\=top\\]\\:top-0{&[data-vaul-drawer-direction=top]{top:calc(var(--spacing)*0)}}.data-\\[vaul-drawer-direction\\=top\\]\\:mb-24{&[data-vaul-drawer-direction=top]{margin-bottom:calc(var(--spacing)*24)}}.data-\\[vaul-drawer-direction\\=top\\]\\:max-h-\\[80vh\\]{&[data-vaul-drawer-direction=top]{max-height:80vh}}.data-\\[vaul-drawer-direction\\=top\\]\\:rounded-b-lg{&[data-vaul-drawer-direction=top]{border-bottom-left-radius:var(--radius);border-bottom-right-radius:var(--radius)}}.data-\\[vaul-drawer-direction\\=top\\]\\:border-b{&[data-vaul-drawer-direction=top]{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}}.data-\\[vaul-drawer-direction\\=left\\]\\:sm\\:max-w-sm,.sm\\:flex-row,.sm\\:justify-end,.sm\\:mx-0{&[data-vaul-drawer-direction=left]{@media (width >= 40rem){max-width:var(--container-sm)}}}.data-\\[vaul-drawer-direction\\=right\\]\\:sm\\:max-w-sm{&[data-vaul-drawer-direction=right]{@media (width >= 40rem){max-width:var(--container-sm)}}}.\\[\\&\\[data-state\\=open\\]\\>svg\\]\\:rotate-180,.md\\:text-\\[15px\\]{&[data-state=open]>svg{rotate:180deg}}}body{--background:oklch(1 0 0);--foreground:oklch(0.145 0 0);--card:oklch(1 0 0);--card-foreground:oklch(0.145 0 0);--popover:oklch(1 0 0);--popover-foreground:oklch(0.145 0 0);--primary:oklch(0.205 0 0);--primary-foreground:oklch(0.985 0 0);--secondary:oklch(0.97 0 0);--secondary-foreground:oklch(0.205 0 0);--muted:oklch(0.97 0 0);--muted-foreground:oklch(0.556 0 0);--accent:oklch(0.97 0 0);--accent-foreground:oklch(0.205 0 0);--destructive:oklch(0.577 0.245 27.325);--destructive-foreground:oklch(0.577 0.245 27.325);--border:oklch(0.922 0 0);--input:oklch(0.922 0 0);--ring:oklch(0.708 0 0);--chart-1:oklch(0.646 0.222 41.116);--chart-2:oklch(0.6 0.118 184.704);--chart-3:oklch(0.398 0.07 227.392);--chart-4:oklch(0.828 0.189 84.429);--chart-5:oklch(0.769 0.188 70.08);--radius:0.625rem;--sidebar:oklch(0.985 0 0);--sidebar-foreground:oklch(0.145 0 0);--sidebar-primary:oklch(0.205 0 0);--sidebar-primary-foreground:oklch(0.985 0 0);--sidebar-accent:oklch(0.97 0 0);--sidebar-accent-foreground:oklch(0.205 0 0);--sidebar-border:oklch(0.922 0 0);--sidebar-ring:oklch(0.708 0 0);outline:none}.dark{--background:oklch(0.145 0 0);--foreground:oklch(0.985 0 0);--card:oklch(0.145 0 0);--card-foreground:oklch(0.985 0 0);--popover:oklch(0.145 0 0);--popover-foreground:oklch(0.985 0 0);--primary:oklch(0.985 0 0);--primary-foreground:oklch(0.205 0 0);--secondary:oklch(0.269 0 0);--secondary-foreground:oklch(0.985 0 0);--muted:oklch(0.269 0 0);--muted-foreground:oklch(0.708 0 0);--accent:oklch(0.269 0 0);--accent-foreground:oklch(0.985 0 0);--destructive:oklch(0.396 0.141 25.723);--destructive-foreground:oklch(0.637 0.237 25.331);--border:oklch(0.269 0 0);--input:oklch(0.269 0 0);--ring:oklch(0.439 0 0);--chart-1:oklch(0.488 0.243 264.376);--chart-2:oklch(0.696 0.17 162.48);--chart-3:oklch(0.769 0.188 70.08);--chart-4:oklch(0.627 0.265 303.9);--chart-5:oklch(0.645 0.246 16.439);--sidebar:oklch(0.205 0 0);--sidebar-foreground:oklch(0.985 0 0);--sidebar-primary:oklch(0.488 0.243 264.376);--sidebar-primary-foreground:oklch(0.985 0 0);--sidebar-accent:oklch(0.269 0 0);--sidebar-accent-foreground:oklch(0.985 0 0);--sidebar-border:oklch(0.269 0 0);--sidebar-ring:oklch(0.439 0 0)}@layer base{*{border-color:var(--border);outline-color:color-mix(in oklab,var(--ring) 50%,transparent)}body{background-color:var(--background);color:var(--foreground)}}html.overflow-hidden{overflow:hidden}.scrollbar-hide::-webkit-scrollbar{display:none}.scrollbar-hide{-ms-overflow-style:none;scrollbar-width:none}.bg-insta{background-image:linear-gradient(to top right,#facc15,#ec4899,#9333ea)}.product-banner{align-items:center;background:#fff;border-radius:8px;cursor:pointer;display:flex;gap:8px;position:relative}.product-banner__clip{border-radius:inherit;overflow:hidden}.product-banner__clip,.product-banner__sheen{inset:0;pointer-events:none;position:absolute;z-index:1}.product-banner__sheen{background:linear-gradient(270deg,rgba(0,0,0,.1),transparent);transform:translateX(100%);transition:transform .3s ease}.product-banner:hover .product-banner__sheen{transform:translateX(0)}.product-banner__arrow{opacity:0;pointer-events:none;position:absolute;right:8px;top:50%;transform:translate(4px,-50%);transition:transform .3s ease,opacity .3s ease;z-index:2}.product-banner:hover .product-banner__arrow{opacity:1;transform:translateY(-50%)}.product-dialog-container{max-height:70vh;max-width:min(82vw,500px);overflow-y:auto;width:100%}.border{border:1px solid oklch(.922 0 0)}@font-face{font-family:swiper-icons;font-style:normal;font-weight:400;src:url("data:application/font-woff;charset=utf-8;base64, d09GRgABAAAAAAZgABAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAAGRAAAABoAAAAci6qHkUdERUYAAAWgAAAAIwAAACQAYABXR1BPUwAABhQAAAAuAAAANuAY7+xHU1VCAAAFxAAAAFAAAABm2fPczU9TLzIAAAHcAAAASgAAAGBP9V5RY21hcAAAAkQAAACIAAABYt6F0cBjdnQgAAACzAAAAAQAAAAEABEBRGdhc3AAAAWYAAAACAAAAAj//wADZ2x5ZgAAAywAAADMAAAD2MHtryVoZWFkAAABbAAAADAAAAA2E2+eoWhoZWEAAAGcAAAAHwAAACQC9gDzaG10eAAAAigAAAAZAAAArgJkABFsb2NhAAAC0AAAAFoAAABaFQAUGG1heHAAAAG8AAAAHwAAACAAcABAbmFtZQAAA/gAAAE5AAACXvFdBwlwb3N0AAAFNAAAAGIAAACE5s74hXjaY2BkYGAAYpf5Hu/j+W2+MnAzMYDAzaX6QjD6/4//Bxj5GA8AuRwMYGkAPywL13jaY2BkYGA88P8Agx4j+/8fQDYfA1AEBWgDAIB2BOoAeNpjYGRgYNBh4GdgYgABEMnIABJzYNADCQAACWgAsQB42mNgYfzCOIGBlYGB0YcxjYGBwR1Kf2WQZGhhYGBiYGVmgAFGBiQQkOaawtDAoMBQxXjg/wEGPcYDDA4wNUA2CCgwsAAAO4EL6gAAeNpj2M0gyAACqxgGNWBkZ2D4/wMA+xkDdgAAAHjaY2BgYGaAYBkGRgYQiAHyGMF8FgYHIM3DwMHABGQrMOgyWDLEM1T9/w8UBfEMgLzE////P/5//f/V/xv+r4eaAAeMbAxwIUYmIMHEgKYAYjUcsDAwsLKxc3BycfPw8jEQA/gZBASFhEVExcQlJKWkZWTl5BUUlZRVVNXUNTQZBgMAAMR+E+gAEQFEAAAAKgAqACoANAA+AEgAUgBcAGYAcAB6AIQAjgCYAKIArAC2AMAAygDUAN4A6ADyAPwBBgEQARoBJAEuATgBQgFMAVYBYAFqAXQBfgGIAZIBnAGmAbIBzgHsAAB42u2NMQ6CUAyGW568x9AneYYgm4MJbhKFaExIOAVX8ApewSt4Bic4AfeAid3VOBixDxfPYEza5O+Xfi04YADggiUIULCuEJK8VhO4bSvpdnktHI5QCYtdi2sl8ZnXaHlqUrNKzdKcT8cjlq+rwZSvIVczNiezsfnP/uznmfPFBNODM2K7MTQ45YEAZqGP81AmGGcF3iPqOop0r1SPTaTbVkfUe4HXj97wYE+yNwWYxwWu4v1ugWHgo3S1XdZEVqWM7ET0cfnLGxWfkgR42o2PvWrDMBSFj/IHLaF0zKjRgdiVMwScNRAoWUoH78Y2icB/yIY09An6AH2Bdu/UB+yxopYshQiEvnvu0dURgDt8QeC8PDw7Fpji3fEA4z/PEJ6YOB5hKh4dj3EvXhxPqH/SKUY3rJ7srZ4FZnh1PMAtPhwP6fl2PMJMPDgeQ4rY8YT6Gzao0eAEA409DuggmTnFnOcSCiEiLMgxCiTI6Cq5DZUd3Qmp10vO0LaLTd2cjN4fOumlc7lUYbSQcZFkutRG7g6JKZKy0RmdLY680CDnEJ+UMkpFFe1RN7nxdVpXrC4aTtnaurOnYercZg2YVmLN/d/gczfEimrE/fs/bOuq29Zmn8tloORaXgZgGa78yO9/cnXm2BpaGvq25Dv9S4E9+5SIc9PqupJKhYFSSl47+Qcr1mYNAAAAeNptw0cKwkAAAMDZJA8Q7OUJvkLsPfZ6zFVERPy8qHh2YER+3i/BP83vIBLLySsoKimrqKqpa2hp6+jq6RsYGhmbmJqZSy0sraxtbO3sHRydnEMU4uR6yx7JJXveP7WrDycAAAAAAAH//wACeNpjYGRgYOABYhkgZgJCZgZNBkYGLQZtIJsFLMYAAAw3ALgAeNolizEKgDAQBCchRbC2sFER0YD6qVQiBCv/H9ezGI6Z5XBAw8CBK/m5iQQVauVbXLnOrMZv2oLdKFa8Pjuru2hJzGabmOSLzNMzvutpB3N42mNgZGBg4GKQYzBhYMxJLMlj4GBgAYow/P/PAJJhLM6sSoWKfWCAAwDAjgbRAAB42mNgYGBkAIIbCZo5IPrmUn0hGA0AO8EFTQAA")}:root{--swiper-theme-color:#007aff}:host{display:block;margin-left:auto;margin-right:auto;position:relative;z-index:1}.swiper{display:block;list-style:none;margin-left:auto;margin-right:auto;overflow:hidden;padding:0;position:relative;z-index:1}.swiper-vertical>.swiper-wrapper{flex-direction:column}.swiper-wrapper{box-sizing:content-box;display:flex;height:100%;position:relative;transition-property:transform;transition-timing-function:var(--swiper-wrapper-transition-timing-function,initial);width:100%;z-index:1}.swiper-android .swiper-slide,.swiper-ios .swiper-slide,.swiper-wrapper{transform:translateZ(0)}.swiper-horizontal{touch-action:pan-y}.swiper-vertical{touch-action:pan-x}.swiper-slide{display:block;flex-shrink:0;height:100%;position:relative;transition-property:transform;width:100%}.swiper-slide-invisible-blank{visibility:hidden}.swiper-autoheight,.swiper-autoheight .swiper-slide{height:auto}.swiper-autoheight .swiper-wrapper{align-items:flex-start;transition-property:transform,height}.swiper-backface-hidden .swiper-slide{-webkit-backface-visibility:hidden;backface-visibility:hidden;transform:translateZ(0)}.swiper-3d.swiper-css-mode .swiper-wrapper{perspective:1200px}.swiper-3d .swiper-wrapper{transform-style:preserve-3d}.swiper-3d{perspective:1200px}.swiper-3d .swiper-cube-shadow,.swiper-3d .swiper-slide{transform-style:preserve-3d}.swiper-css-mode>.swiper-wrapper{-ms-overflow-style:none;overflow:auto;scrollbar-width:none}.swiper-css-mode>.swiper-wrapper::-webkit-scrollbar{display:none}.swiper-css-mode>.swiper-wrapper>.swiper-slide{scroll-snap-align:start start}.swiper-css-mode.swiper-horizontal>.swiper-wrapper{scroll-snap-type:x mandatory}.swiper-css-mode.swiper-vertical>.swiper-wrapper{scroll-snap-type:y mandatory}.swiper-css-mode.swiper-free-mode>.swiper-wrapper{scroll-snap-type:none}.swiper-css-mode.swiper-free-mode>.swiper-wrapper>.swiper-slide{scroll-snap-align:none}.swiper-css-mode.swiper-centered>.swiper-wrapper:before{content:"";flex-shrink:0;order:9999}.swiper-css-mode.swiper-centered>.swiper-wrapper>.swiper-slide{scroll-snap-align:center center;scroll-snap-stop:always}.swiper-css-mode.swiper-centered.swiper-horizontal>.swiper-wrapper>.swiper-slide:first-child{margin-inline-start:var(--swiper-centered-offset-before)}.swiper-css-mode.swiper-centered.swiper-horizontal>.swiper-wrapper:before{height:100%;min-height:1px;width:var(--swiper-centered-offset-after)}.swiper-css-mode.swiper-centered.swiper-vertical>.swiper-wrapper>.swiper-slide:first-child{margin-block-start:var(--swiper-centered-offset-before)}.swiper-css-mode.swiper-centered.swiper-vertical>.swiper-wrapper:before{height:var(--swiper-centered-offset-after);min-width:1px;width:100%}.swiper-3d .swiper-slide-shadow,.swiper-3d .swiper-slide-shadow-bottom,.swiper-3d .swiper-slide-shadow-left,.swiper-3d .swiper-slide-shadow-right,.swiper-3d .swiper-slide-shadow-top{height:100%;left:0;pointer-events:none;position:absolute;top:0;width:100%;z-index:10}.swiper-3d .swiper-slide-shadow{background:rgba(0,0,0,.15)}.swiper-3d .swiper-slide-shadow-left{background-image:linear-gradient(270deg,rgba(0,0,0,.5),transparent)}.swiper-3d .swiper-slide-shadow-right{background-image:linear-gradient(90deg,rgba(0,0,0,.5),transparent)}.swiper-3d .swiper-slide-shadow-top{background-image:linear-gradient(0deg,rgba(0,0,0,.5),transparent)}.swiper-3d .swiper-slide-shadow-bottom{background-image:linear-gradient(180deg,rgba(0,0,0,.5),transparent)}.swiper-lazy-preloader{border:4px solid var(--swiper-preloader-color,var(--swiper-theme-color));border-radius:50%;border-top:4px solid transparent;box-sizing:border-box;height:42px;left:50%;margin-left:-21px;margin-top:-21px;position:absolute;top:50%;transform-origin:50%;width:42px;z-index:10}.swiper-watch-progress .swiper-slide-visible .swiper-lazy-preloader,.swiper:not(.swiper-watch-progress) .swiper-lazy-preloader{animation:swiper-preloader-spin 1s linear infinite}.swiper-lazy-preloader-white{--swiper-preloader-color:#fff}.swiper-lazy-preloader-black{--swiper-preloader-color:#000}@keyframes swiper-preloader-spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}.swiper.swiper-cards{overflow:visible}.swiper-cards .swiper-slide{-webkit-backface-visibility:hidden;backface-visibility:hidden;overflow:hidden;transform-origin:center bottom}.swiper-grid>.swiper-wrapper{flex-wrap:wrap}.swiper-grid-column>.swiper-wrapper{flex-direction:column;flex-wrap:wrap}@keyframes enter{0%{opacity:var(--tw-enter-opacity,1);transform:translate3d(var(--tw-enter-translate-x,0),var(--tw-enter-translate-y,0),0) scale3d(var(--tw-enter-scale,1),var(--tw-enter-scale,1),var(--tw-enter-scale,1)) rotate(var(--tw-enter-rotate,0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity,1);transform:translate3d(var(--tw-exit-translate-x,0),var(--tw-exit-translate-y,0),0) scale3d(var(--tw-exit-scale,1),var(--tw-exit-scale,1),var(--tw-exit-scale,1)) rotate(var(--tw-exit-rotate,0))}}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-rotate-x{syntax:"*";inherits:false;initial-value:rotateX(0)}@property --tw-rotate-y{syntax:"*";inherits:false;initial-value:rotateY(0)}@property --tw-rotate-z{syntax:"*";inherits:false;initial-value:rotateZ(0)}@property --tw-skew-x{syntax:"*";inherits:false;initial-value:skewX(0)}@property --tw-skew-y{syntax:"*";inherits:false;initial-value:skewY(0)}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-gradient-position{syntax:"*";inherits:false}@property --tw-gradient-from{syntax:"<color>";inherits:false;initial-value:#0000}@property --tw-gradient-via{syntax:"<color>";inherits:false;initial-value:#0000}@property --tw-gradient-to{syntax:"<color>";inherits:false;initial-value:#0000}@property --tw-gradient-stops{syntax:"*";inherits:false}@property --tw-gradient-via-stops{syntax:"*";inherits:false}@property --tw-gradient-from-position{syntax:"<length-percentage>";inherits:false;initial-value:0}@property --tw-gradient-via-position{syntax:"<length-percentage>";inherits:false;initial-value:50%}@property --tw-gradient-to-position{syntax:"<length-percentage>";inherits:false;initial-value:100%}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@keyframes pulse{50%{opacity:.5}}@keyframes float{0%{opacity:1;transform:translateY(0)}to{opacity:0;transform:translateY(-200px)}}',lc=oc.trim().length>0,uc="undefined"!=typeof window&&"adoptedStyleSheets"in Document.prototype&&"undefined"!=typeof CSSStyleSheet&&"replaceSync"in CSSStyleSheet.prototype;let cc=null;function dc(e){return cc||(cc=new CSSStyleSheet,cc.replaceSync(e)),cc}function hc(){return lc?oc:function(){const e=[];for(const t of Array.from(document.styleSheets))try{e.push(Array.from(t.cssRules).map(e=>e.cssText).join("\n"))}catch(e){}return e.join("\n")}()}const fc=({extra:e})=>{const t=hc()+(e?"\n"+e:"");return g.createElement("style",null,t)};function pc(){const[e,t]=g.useState(null),r=p.useRef(null),{open:n,setOpen:i}=Wo();return p.useEffect(()=>{r.current&&(r.current.style.display=n?"block":"none")},[n]),g.useLayoutEffect(()=>{const e=document.createElement("div");e.style.position="fixed",e.style.inset="0",e.style.zIndex="214748348",e.style.display="none",document.body.appendChild(e),r.current=e;const n=e.attachShadow({mode:"open"});!function(e){const t=hc();if(uc)e.adoptedStyleSheets=[dc(t)];else{const r=document.createElement("style");r.textContent=t,e.appendChild(r)}}(n);const i=document.createElement("style");i.innerHTML="\n .product-dialog-container{\n max-height: 70vh;\n overflow-y: auto;\n width: 100%;\n max-width: min(82vw, 500px) !important;\n }\n ",n.appendChild(i);const s=document.createElement("div");return n.appendChild(s),t(s),()=>e.remove()},[]),{container:e,setOpen:i}}const gc=e=>{const{collectionId:t,isPreview:r,priceText:n,container:i}=e,{setIsPreview:s,setPriceText:a}=cr(),{setCollection:o,setNextKey:l,collection:u}=fr();p.useEffect(()=>{n&&a(n);const e=Boolean(r);e&&s(e)},[]),p.useEffect(()=>{J(void 0,void 0,void 0,function*(){var e;const r=yield tr({collectionId:t,size:10});if(!r)return;const{contents:n,count:i}=r;(null==n?void 0:n.length)&&l(null===(e=n.at(-1))||void 0===e?void 0:e.shortsId),o(Object.assign(Object.assign({},r),{count:i}))})},[t]);const c=function(e){var t,r,n,i,s,a,o,l,u,c,d,h;const f=null!==(t=e.iconForm)&&void 0!==t?t:z.INSTA,p={collectionId:e.collectionId,iconForm:f,iconShape:null!==(r=e.iconShape)&&void 0!==r?r:j.MANY,iconSize:null!==(n=e.iconSize)&&void 0!==n?n:120,borderLine:null!==(i=e.borderLine)&&void 0!==i?i:G.DAY,exposeTitle:null===(s=e.exposeTitle)||void 0===s||s,player:null!==(a=e.player)&&void 0!==a?a:H.POPUP,rounded:null===(o=e.rounded)||void 0===o||o,titlePosition:null!==(l=e.titlePosition)&&void 0!==l?l:V.BOTTOM,exposeProductBanner:null!==(u=e.exposeProductBanner)&&void 0!==u&&u,exposeProductBadge:null!==(c=e.exposeProductBadge)&&void 0!==c&&c,priceText:e.priceText||"할인가",hoverPlay:null!==(d=e.hoverPlay)&&void 0!==d&&d,thumbnailAutoPlay:null!==(h=e.thumbnailAutoPlay)&&void 0!==h&&h};return f===z.YOUTUBE?Object.assign(Object.assign({},p),{iconForm:z.YOUTUBE,iconRatio:e.iconRatio||"9/16"}):Object.assign(Object.assign({},p),{iconForm:z.INSTA})}(e),{containerRef:d}=function({collectionId:e,iconSize:t}){const{collection:r,setCollection:n,nextKey:i,setNextKey:s,isFetching:a,setIsFetching:o}=fr(),l=g.useRef(null),[u,c]=g.useState(0);return g.useEffect(()=>{if(!l.current)return;const e=new ResizeObserver(e=>{var t,r,n;const i=null!==(n=null===(r=null===(t=e[0])||void 0===t?void 0:t.contentRect)||void 0===r?void 0:r.width)&&void 0!==n?n:0;c(i)});return e.observe(l.current),()=>e.disconnect()},[]),g.useEffect(()=>{var e;if(!r||!r.contents)return;const l=Math.max(1,t+12),c=Math.ceil((u||0)/l)+4,d=null!==(e=r.count)&&void 0!==e?e:Number.MAX_SAFE_INTEGER,h=Math.min(d,c);if(r.contents.length>=h||a)return;let f=!1;return(()=>{J(this,void 0,void 0,function*(){var e,t,a,l,u;try{o(!0);let c=r,d=i||(null===(e=c.contents.at(-1))||void 0===e?void 0:e.shortsId)||void 0;const p=new Set(c.contents.map(e=>e.shortsId));for(;!f&&c.contents.length<h;){const e=Math.max(6,h-c.contents.length),r=yield tr({collectionId:c.colId,nextKey:d,size:e});if(!r||!(null===(t=r.contents)||void 0===t?void 0:t.length))break;d=null!==(l=null===(a=r.contents.at(-1))||void 0===a?void 0:a.shortsId)&&void 0!==l?l:d;const i=r.contents.filter(e=>!p.has(e.shortsId));if(!i.length)break;if(i.forEach(e=>p.add(e.shortsId)),c=Object.assign(Object.assign({},c),{contents:[...c.contents,...i]}),n(c),s(d||""),c.contents.length>=(null!==(u=c.count)&&void 0!==u?u:Number.MAX_SAFE_INTEGER))break}}finally{o(!1)}})})(),()=>{f=!0}},[null==r?void 0:r.colId,null==r?void 0:r.count,null==r?void 0:r.contents.length,u,t,a,i,n,o,s]),{containerRef:l}}({collectionId:t,iconSize:c.iconSize});return g.createElement(ac.div,null,g.createElement(fc,null),g.createElement("div",{ref:d},g.createElement(Iu,{widgetPlayerOption:c,setCollectionUuid:e=>{o(Object.assign(Object.assign({},u),{uuid:e}))},portalContainer:i})))},mc=({portalContainer:e,aspectRatio:t})=>{var r;const{collection:n,setNextKey:i}=fr(),[s,a]=p.useState(),{setOpen:o,open:l}=Wo();p.useEffect(()=>{l||s&&a(null)},[l]);const u=(null!==(r=On().width)&&void 0!==r?r:0)<430||Hn.isMobile;return g.createElement(g.Fragment,null,g.createElement("div",{className:"grid gap-4",style:{gridTemplateColumns:`repeat(${u?2:5}, 1fr)`}},null==n?void 0:n.contents.map(e=>g.createElement("div",null,g.createElement("div",{className:"overflow-hidden",style:{borderRadius:"0.625rem",aspectRatio:null!=t?t:"9/16"}},g.createElement("video",{loop:!0,className:"w-full h-full object-cover",muted:!0,autoPlay:!0,playsInline:!0,src:Ft(e.media.objectId),poster:Gt(e.thumbPath)})),g.createElement(Yo,{hideMoreBadge:!0,showMoreBtn:!0,products:e.productsInfo,contentId:e.shortsId,setSelectedProducts:a})))),s&&g.createElement(Ru,{portalContainer:e,title:"상품 목록",contentClassName:"bg-white rounded p-4 product-dialog-container",description:"연결된 전체 상품 정보를 확인해 보세요"},g.createElement(Lu,{products:s.productsInfo,contentId:s.shortsId})))},vc=({collectionId:e,aspectRatio:t,container:r,isPreview:n})=>{const{setCollection:i,setNextKey:s}=fr();return p.useEffect(()=>{J(void 0,void 0,void 0,function*(){var t;const r=yield tr({collectionId:e,size:-1});if(!r)return;const{contents:n,count:a}=r;(null==n?void 0:n.length)&&s(null===(t=n.at(-1))||void 0===t?void 0:t.shortsId),i(Object.assign(Object.assign({},r),{count:a}))})},[e]),g.createElement(ac.div,null,g.createElement(fc,null),g.createElement(mc,{portalContainer:r,aspectRatio:t}))},yc=ur(e=>({shortform:null,setShortform:t=>e({shortform:t})}));var bc={exports:{}},wc={};function Ec(e){var t,r,n="";if("string"==typeof e||"number"==typeof e)n+=e;else if("object"==typeof e)if(Array.isArray(e))for(t=0;t<e.length;t++)e[t]&&(r=Ec(e[t]))&&(n&&(n+=" "),n+=r);else for(t in e)e[t]&&(n&&(n+=" "),n+=t);return n}function Sc(){for(var e,t,r=0,n="";r<arguments.length;)(e=arguments[r++])&&(t=Ec(e))&&(n&&(n+=" "),n+=t);return n}var Tc,xc=r(Object.freeze({__proto__:null,clsx:Sc,default:Sc})),kc={},Ac={};function Rc(){if(Tc)return Ac;return Tc=1,Object.defineProperty(Ac,"__esModule",{value:!0}),Ac.dontSetMe=function(e,t,r){if(e[t])return new Error("Invalid prop ".concat(t," passed to ").concat(r," - do not set this, set it on the child."))},Ac.findInArray=function(e,t){for(let r=0,n=e.length;r<n;r++)if(t.apply(t,[e[r],r,e]))return e[r]},Ac.int=function(e){return parseInt(e,10)},Ac.isFunction=function(e){return"function"==typeof e||"[object Function]"===Object.prototype.toString.call(e)},Ac.isNum=function(e){return"number"==typeof e&&!isNaN(e)},Ac}var Lc,Ic,Cc={};function Pc(){if(Ic)return kc;Ic=1,Object.defineProperty(kc,"__esModule",{value:!0}),kc.addClassName=a,kc.addEvent=function(e,t,r,n){if(!e)return;const i={capture:!0,...n};e.addEventListener?e.addEventListener(t,r,i):e.attachEvent?e.attachEvent("on"+t,r):e["on"+t]=r},kc.addUserSelectStyles=function(e){if(!e)return;let t=e.getElementById("react-draggable-style-el");t||(t=e.createElement("style"),t.type="text/css",t.id="react-draggable-style-el",t.innerHTML=".react-draggable-transparent-selection *::-moz-selection {all: inherit;}\n",t.innerHTML+=".react-draggable-transparent-selection *::selection {all: inherit;}\n",e.getElementsByTagName("head")[0].appendChild(t));e.body&&a(e.body,"react-draggable-transparent-selection")},kc.createCSSTransform=function(e,r){const n=s(e,r,"px");return{[(0,t.browserPrefixToKey)("transform",t.default)]:n}},kc.createSVGTransform=function(e,t){return s(e,t,"")},kc.getTouch=function(t,r){return t.targetTouches&&(0,e.findInArray)(t.targetTouches,e=>r===e.identifier)||t.changedTouches&&(0,e.findInArray)(t.changedTouches,e=>r===e.identifier)},kc.getTouchIdentifier=function(e){if(e.targetTouches&&e.targetTouches[0])return e.targetTouches[0].identifier;if(e.changedTouches&&e.changedTouches[0])return e.changedTouches[0].identifier},kc.getTranslation=s,kc.innerHeight=function(t){let r=t.clientHeight;const n=t.ownerDocument.defaultView.getComputedStyle(t);return r-=(0,e.int)(n.paddingTop),r-=(0,e.int)(n.paddingBottom),r},kc.innerWidth=function(t){let r=t.clientWidth;const n=t.ownerDocument.defaultView.getComputedStyle(t);return r-=(0,e.int)(n.paddingLeft),r-=(0,e.int)(n.paddingRight),r},kc.matchesSelector=i,kc.matchesSelectorAndParentsTo=function(e,t,r){let n=e;do{if(i(n,t))return!0;if(n===r)return!1;n=n.parentNode}while(n);return!1},kc.offsetXYFromParent=function(e,t,r){const n=t===t.ownerDocument.body?{left:0,top:0}:t.getBoundingClientRect(),i=(e.clientX+t.scrollLeft-n.left)/r,s=(e.clientY+t.scrollTop-n.top)/r;return{x:i,y:s}},kc.outerHeight=function(t){let r=t.clientHeight;const n=t.ownerDocument.defaultView.getComputedStyle(t);return r+=(0,e.int)(n.borderTopWidth),r+=(0,e.int)(n.borderBottomWidth),r},kc.outerWidth=function(t){let r=t.clientWidth;const n=t.ownerDocument.defaultView.getComputedStyle(t);return r+=(0,e.int)(n.borderLeftWidth),r+=(0,e.int)(n.borderRightWidth),r},kc.removeClassName=o,kc.removeEvent=function(e,t,r,n){if(!e)return;const i={capture:!0,...n};e.removeEventListener?e.removeEventListener(t,r,i):e.detachEvent?e.detachEvent("on"+t,r):e["on"+t]=null},kc.removeUserSelectStyles=function(e){if(!e)return;try{if(e.body&&o(e.body,"react-draggable-transparent-selection"),e.selection)e.selection.empty();else{const t=(e.defaultView||window).getSelection();t&&"Caret"!==t.type&&t.removeAllRanges()}}catch(e){}};var e=Rc(),t=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=r(t);if(n&&n.has(e))return n.get(e);var i={},s=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var a in e)if("default"!==a&&Object.prototype.hasOwnProperty.call(e,a)){var o=s?Object.getOwnPropertyDescriptor(e,a):null;o&&(o.get||o.set)?Object.defineProperty(i,a,o):i[a]=e[a]}i.default=e,n&&n.set(e,i);return i}(function(){if(Lc)return Cc;Lc=1,Object.defineProperty(Cc,"__esModule",{value:!0}),Cc.browserPrefixToKey=r,Cc.browserPrefixToStyle=function(e,t){return t?"-".concat(t.toLowerCase(),"-").concat(e):e},Cc.default=void 0,Cc.getPrefix=t;const e=["Moz","Webkit","O","ms"];function t(){var t;let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"transform";if("undefined"==typeof window)return"";const i=null===(t=window.document)||void 0===t||null===(t=t.documentElement)||void 0===t?void 0:t.style;if(!i)return"";if(n in i)return"";for(let t=0;t<e.length;t++)if(r(n,e[t])in i)return e[t];return""}function r(e,t){return t?"".concat(t).concat(function(e){let t="",r=!0;for(let n=0;n<e.length;n++)r?(t+=e[n].toUpperCase(),r=!1):"-"===e[n]?r=!0:t+=e[n];return t}(e)):e}return Cc.default=t(),Cc}());function r(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(r=function(e){return e?n:t})(e)}let n="";function i(t,r){return n||(n=(0,e.findInArray)(["matches","webkitMatchesSelector","mozMatchesSelector","msMatchesSelector","oMatchesSelector"],function(r){return(0,e.isFunction)(t[r])})),!!(0,e.isFunction)(t[n])&&t[n](r)}function s(e,t,r){let{x:n,y:i}=e,s="translate(".concat(n).concat(r,",").concat(i).concat(r,")");if(t){const e="".concat("string"==typeof t.x?t.x:t.x+r),n="".concat("string"==typeof t.y?t.y:t.y+r);s="translate(".concat(e,", ").concat(n,")")+s}return s}function a(e,t){e.classList?e.classList.add(t):e.className.match(new RegExp("(?:^|\\s)".concat(t,"(?!\\S)")))||(e.className+=" ".concat(t))}function o(e,t){e.classList?e.classList.remove(t):e.className=e.className.replace(new RegExp("(?:^|\\s)".concat(t,"(?!\\S)"),"g"),"")}return kc}var Dc,_c={};function Mc(){if(Dc)return _c;Dc=1,Object.defineProperty(_c,"__esModule",{value:!0}),_c.canDragX=function(e){return"both"===e.props.axis||"x"===e.props.axis},_c.canDragY=function(e){return"both"===e.props.axis||"y"===e.props.axis},_c.createCoreData=function(t,n,i){const s=!(0,e.isNum)(t.lastX),a=r(t);return s?{node:a,deltaX:0,deltaY:0,lastX:n,lastY:i,x:n,y:i}:{node:a,deltaX:n-t.lastX,deltaY:i-t.lastY,lastX:t.lastX,lastY:t.lastY,x:n,y:i}},_c.createDraggableData=function(e,t){const r=e.props.scale;return{node:t.node,x:e.state.x+t.deltaX/r,y:e.state.y+t.deltaY/r,deltaX:t.deltaX/r,deltaY:t.deltaY/r,lastX:e.state.x,lastY:e.state.y}},_c.getBoundPosition=function(n,i,s){if(!n.props.bounds)return[i,s];let{bounds:a}=n.props;a="string"==typeof a?a:function(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom}}(a);const o=r(n);if("string"==typeof a){const{ownerDocument:r}=o,n=r.defaultView;let i;if(i="parent"===a?o.parentNode:r.querySelector(a),!(i instanceof n.HTMLElement))throw new Error('Bounds selector "'+a+'" could not find an element.');const s=i,l=n.getComputedStyle(o),u=n.getComputedStyle(s);a={left:-o.offsetLeft+(0,e.int)(u.paddingLeft)+(0,e.int)(l.marginLeft),top:-o.offsetTop+(0,e.int)(u.paddingTop)+(0,e.int)(l.marginTop),right:(0,t.innerWidth)(s)-(0,t.outerWidth)(o)-o.offsetLeft+(0,e.int)(u.paddingRight)-(0,e.int)(l.marginRight),bottom:(0,t.innerHeight)(s)-(0,t.outerHeight)(o)-o.offsetTop+(0,e.int)(u.paddingBottom)-(0,e.int)(l.marginBottom)}}(0,e.isNum)(a.right)&&(i=Math.min(i,a.right));(0,e.isNum)(a.bottom)&&(s=Math.min(s,a.bottom));(0,e.isNum)(a.left)&&(i=Math.max(i,a.left));(0,e.isNum)(a.top)&&(s=Math.max(s,a.top));return[i,s]},_c.getControlPosition=function(e,n,i){const s="number"==typeof n?(0,t.getTouch)(e,n):null;if("number"==typeof n&&!s)return null;const a=r(i),o=i.props.offsetParent||a.offsetParent||a.ownerDocument.body;return(0,t.offsetXYFromParent)(s||e,o,i.props.scale)},_c.snapToGrid=function(e,t,r){const n=Math.round(t/e[0])*e[0],i=Math.round(r/e[1])*e[1];return[n,i]};var e=Rc(),t=Pc();function r(e){const t=e.findDOMNode();if(!t)throw new Error("<DraggableCore>: Unmounted during event!");return t}return _c}var Oc,Nc,Fc,$c,Bc={},Uc={};function zc(){if(Oc)return Uc;return Oc=1,Object.defineProperty(Uc,"__esModule",{value:!0}),Uc.default=function(){},Uc}function jc(){if(Nc)return Bc;Nc=1,Object.defineProperty(Bc,"__esModule",{value:!0}),Bc.default=void 0;var e=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=u(t);if(r&&r.has(e))return r.get(e);var n={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var a=i?Object.getOwnPropertyDescriptor(e,s):null;a&&(a.get||a.set)?Object.defineProperty(n,s,a):n[s]=e[s]}n.default=e,r&&r.set(e,n);return n}(l()),t=o(Ku()),r=o(x()),n=Pc(),i=Mc(),s=Rc(),a=o(zc());function o(e){return e&&e.__esModule?e:{default:e}}function u(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(u=function(e){return e?r:t})(e)}function c(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}const d={start:"touchstart",move:"touchmove",stop:"touchend"},h={start:"mousedown",move:"mousemove",stop:"mouseup"};let f=h,p=class extends e.Component{constructor(){super(...arguments),c(this,"dragging",!1),c(this,"lastX",NaN),c(this,"lastY",NaN),c(this,"touchIdentifier",null),c(this,"mounted",!1),c(this,"handleDragStart",e=>{if(this.props.onMouseDown(e),!this.props.allowAnyClick&&"number"==typeof e.button&&0!==e.button)return!1;const t=this.findDOMNode();if(!t||!t.ownerDocument||!t.ownerDocument.body)throw new Error("<DraggableCore> not mounted on DragStart!");const{ownerDocument:r}=t;if(this.props.disabled||!(e.target instanceof r.defaultView.Node)||this.props.handle&&!(0,n.matchesSelectorAndParentsTo)(e.target,this.props.handle,t)||this.props.cancel&&(0,n.matchesSelectorAndParentsTo)(e.target,this.props.cancel,t))return;"touchstart"===e.type&&e.preventDefault();const s=(0,n.getTouchIdentifier)(e);this.touchIdentifier=s;const o=(0,i.getControlPosition)(e,s,this);if(null==o)return;const{x:l,y:u}=o,c=(0,i.createCoreData)(this,l,u);(0,a.default)("DraggableCore: handleDragStart: %j",c),(0,a.default)("calling",this.props.onStart);!1!==this.props.onStart(e,c)&&!1!==this.mounted&&(this.props.enableUserSelectHack&&(0,n.addUserSelectStyles)(r),this.dragging=!0,this.lastX=l,this.lastY=u,(0,n.addEvent)(r,f.move,this.handleDrag),(0,n.addEvent)(r,f.stop,this.handleDragStop))}),c(this,"handleDrag",e=>{const t=(0,i.getControlPosition)(e,this.touchIdentifier,this);if(null==t)return;let{x:r,y:n}=t;if(Array.isArray(this.props.grid)){let e=r-this.lastX,t=n-this.lastY;if([e,t]=(0,i.snapToGrid)(this.props.grid,e,t),!e&&!t)return;r=this.lastX+e,n=this.lastY+t}const s=(0,i.createCoreData)(this,r,n);(0,a.default)("DraggableCore: handleDrag: %j",s);if(!1!==this.props.onDrag(e,s)&&!1!==this.mounted)this.lastX=r,this.lastY=n;else try{this.handleDragStop(new MouseEvent("mouseup"))}catch(e){const t=document.createEvent("MouseEvents");t.initMouseEvent("mouseup",!0,!0,window,0,0,0,0,0,!1,!1,!1,!1,0,null),this.handleDragStop(t)}}),c(this,"handleDragStop",e=>{if(!this.dragging)return;const t=(0,i.getControlPosition)(e,this.touchIdentifier,this);if(null==t)return;let{x:r,y:s}=t;if(Array.isArray(this.props.grid)){let e=r-this.lastX||0,t=s-this.lastY||0;[e,t]=(0,i.snapToGrid)(this.props.grid,e,t),r=this.lastX+e,s=this.lastY+t}const o=(0,i.createCoreData)(this,r,s);if(!1===this.props.onStop(e,o)||!1===this.mounted)return!1;const l=this.findDOMNode();l&&this.props.enableUserSelectHack&&(0,n.removeUserSelectStyles)(l.ownerDocument),(0,a.default)("DraggableCore: handleDragStop: %j",o),this.dragging=!1,this.lastX=NaN,this.lastY=NaN,l&&((0,a.default)("DraggableCore: Removing handlers"),(0,n.removeEvent)(l.ownerDocument,f.move,this.handleDrag),(0,n.removeEvent)(l.ownerDocument,f.stop,this.handleDragStop))}),c(this,"onMouseDown",e=>(f=h,this.handleDragStart(e))),c(this,"onMouseUp",e=>(f=h,this.handleDragStop(e))),c(this,"onTouchStart",e=>(f=d,this.handleDragStart(e))),c(this,"onTouchEnd",e=>(f=d,this.handleDragStop(e)))}componentDidMount(){this.mounted=!0;const e=this.findDOMNode();e&&(0,n.addEvent)(e,d.start,this.onTouchStart,{passive:!1})}componentWillUnmount(){this.mounted=!1;const e=this.findDOMNode();if(e){const{ownerDocument:t}=e;(0,n.removeEvent)(t,h.move,this.handleDrag),(0,n.removeEvent)(t,d.move,this.handleDrag),(0,n.removeEvent)(t,h.stop,this.handleDragStop),(0,n.removeEvent)(t,d.stop,this.handleDragStop),(0,n.removeEvent)(e,d.start,this.onTouchStart,{passive:!1}),this.props.enableUserSelectHack&&(0,n.removeUserSelectStyles)(t)}}findDOMNode(){var e,t;return null!==(e=this.props)&&void 0!==e&&e.nodeRef?null===(t=this.props)||void 0===t||null===(t=t.nodeRef)||void 0===t?void 0:t.current:r.default.findDOMNode(this)}render(){return e.cloneElement(e.Children.only(this.props.children),{onMouseDown:this.onMouseDown,onMouseUp:this.onMouseUp,onTouchEnd:this.onTouchEnd})}};return Bc.default=p,c(p,"displayName","DraggableCore"),c(p,"propTypes",{allowAnyClick:t.default.bool,children:t.default.node.isRequired,disabled:t.default.bool,enableUserSelectHack:t.default.bool,offsetParent:function(e,t){if(e[t]&&1!==e[t].nodeType)throw new Error("Draggable's offsetParent must be a DOM Node.")},grid:t.default.arrayOf(t.default.number),handle:t.default.string,cancel:t.default.string,nodeRef:t.default.object,onStart:t.default.func,onDrag:t.default.func,onStop:t.default.func,onMouseDown:t.default.func,scale:t.default.number,className:s.dontSetMe,style:s.dontSetMe,transform:s.dontSetMe}),c(p,"defaultProps",{allowAnyClick:!1,disabled:!1,enableUserSelectHack:!0,onStart:function(){},onDrag:function(){},onStop:function(){},onMouseDown:function(){},scale:1}),Bc}function Gc(){return Fc||(Fc=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"DraggableCore",{enumerable:!0,get:function(){return u.default}}),e.default=void 0;var t=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=h(t);if(r&&r.has(e))return r.get(e);var n={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var a=i?Object.getOwnPropertyDescriptor(e,s):null;a&&(a.get||a.set)?Object.defineProperty(n,s,a):n[s]=e[s]}n.default=e,r&&r.set(e,n);return n}(l()),r=d(Ku()),n=d(x()),i=d(xc),s=Pc(),a=Mc(),o=Rc(),u=d(jc()),c=d(zc());function d(e){return e&&e.__esModule?e:{default:e}}function h(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(h=function(e){return e?r:t})(e)}function f(){return f=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},f.apply(this,arguments)}function p(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class g extends t.Component{static getDerivedStateFromProps(e,t){let{position:r}=e,{prevPropsPosition:n}=t;return!r||n&&r.x===n.x&&r.y===n.y?null:((0,c.default)("Draggable: getDerivedStateFromProps %j",{position:r,prevPropsPosition:n}),{x:r.x,y:r.y,prevPropsPosition:{...r}})}constructor(e){super(e),p(this,"onDragStart",(e,t)=>{(0,c.default)("Draggable: onDragStart: %j",t);if(!1===this.props.onStart(e,(0,a.createDraggableData)(this,t)))return!1;this.setState({dragging:!0,dragged:!0})}),p(this,"onDrag",(e,t)=>{if(!this.state.dragging)return!1;(0,c.default)("Draggable: onDrag: %j",t);const r=(0,a.createDraggableData)(this,t),n={x:r.x,y:r.y,slackX:0,slackY:0};if(this.props.bounds){const{x:e,y:t}=n;n.x+=this.state.slackX,n.y+=this.state.slackY;const[i,s]=(0,a.getBoundPosition)(this,n.x,n.y);n.x=i,n.y=s,n.slackX=this.state.slackX+(e-n.x),n.slackY=this.state.slackY+(t-n.y),r.x=n.x,r.y=n.y,r.deltaX=n.x-this.state.x,r.deltaY=n.y-this.state.y}if(!1===this.props.onDrag(e,r))return!1;this.setState(n)}),p(this,"onDragStop",(e,t)=>{if(!this.state.dragging)return!1;if(!1===this.props.onStop(e,(0,a.createDraggableData)(this,t)))return!1;(0,c.default)("Draggable: onDragStop: %j",t);const r={dragging:!1,slackX:0,slackY:0};if(Boolean(this.props.position)){const{x:e,y:t}=this.props.position;r.x=e,r.y=t}this.setState(r)}),this.state={dragging:!1,dragged:!1,x:e.position?e.position.x:e.defaultPosition.x,y:e.position?e.position.y:e.defaultPosition.y,prevPropsPosition:{...e.position},slackX:0,slackY:0,isElementSVG:!1},!e.position||e.onDrag||e.onStop||console.warn("A `position` was applied to this <Draggable>, without drag handlers. This will make this component effectively undraggable. Please attach `onDrag` or `onStop` handlers so you can adjust the `position` of this element.")}componentDidMount(){void 0!==window.SVGElement&&this.findDOMNode()instanceof window.SVGElement&&this.setState({isElementSVG:!0})}componentWillUnmount(){this.setState({dragging:!1})}findDOMNode(){var e,t;return null!==(e=null===(t=this.props)||void 0===t||null===(t=t.nodeRef)||void 0===t?void 0:t.current)&&void 0!==e?e:n.default.findDOMNode(this)}render(){const{axis:e,bounds:r,children:n,defaultPosition:o,defaultClassName:l,defaultClassNameDragging:c,defaultClassNameDragged:d,position:h,positionOffset:p,scale:g,...m}=this.props;let v={},y=null;const b=!Boolean(h)||this.state.dragging,w=h||o,E={x:(0,a.canDragX)(this)&&b?this.state.x:w.x,y:(0,a.canDragY)(this)&&b?this.state.y:w.y};this.state.isElementSVG?y=(0,s.createSVGTransform)(E,p):v=(0,s.createCSSTransform)(E,p);const S=(0,i.default)(n.props.className||"",l,{[c]:this.state.dragging,[d]:this.state.dragged});return t.createElement(u.default,f({},m,{onStart:this.onDragStart,onDrag:this.onDrag,onStop:this.onDragStop}),t.cloneElement(t.Children.only(n),{className:S,style:{...n.props.style,...v},transform:y}))}}e.default=g,p(g,"displayName","Draggable"),p(g,"propTypes",{...u.default.propTypes,axis:r.default.oneOf(["both","x","y","none"]),bounds:r.default.oneOfType([r.default.shape({left:r.default.number,right:r.default.number,top:r.default.number,bottom:r.default.number}),r.default.string,r.default.oneOf([!1])]),defaultClassName:r.default.string,defaultClassNameDragging:r.default.string,defaultClassNameDragged:r.default.string,defaultPosition:r.default.shape({x:r.default.number,y:r.default.number}),positionOffset:r.default.shape({x:r.default.oneOfType([r.default.number,r.default.string]),y:r.default.oneOfType([r.default.number,r.default.string])}),position:r.default.shape({x:r.default.number,y:r.default.number}),className:o.dontSetMe,style:o.dontSetMe,transform:o.dontSetMe}),p(g,"defaultProps",{...u.default.defaultProps,axis:"both",bounds:!1,defaultClassName:"react-draggable",defaultClassNameDragging:"react-draggable-dragging",defaultClassNameDragged:"react-draggable-dragged",defaultPosition:{x:0,y:0},scale:1})}(wc)),wc}var Hc=function(){if($c)return bc.exports;$c=1;const{default:e,DraggableCore:t}=Gc();return bc.exports=e,bc.exports.default=e,bc.exports.DraggableCore=t,bc.exports}(),Vc=t(Hc),Wc=function(){return Wc=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},Wc.apply(this,arguments)},Kc={width:"100%",height:"10px",top:"0px",left:"0px",cursor:"row-resize"},Yc={width:"10px",height:"100%",top:"0px",left:"0px",cursor:"col-resize"},qc={width:"20px",height:"20px",position:"absolute",zIndex:1},Xc={top:Wc(Wc({},Kc),{top:"-5px"}),right:Wc(Wc({},Yc),{left:void 0,right:"-5px"}),bottom:Wc(Wc({},Kc),{top:void 0,bottom:"-5px"}),left:Wc(Wc({},Yc),{left:"-5px"}),topRight:Wc(Wc({},qc),{right:"-10px",top:"-10px",cursor:"ne-resize"}),bottomRight:Wc(Wc({},qc),{right:"-10px",bottom:"-10px",cursor:"se-resize"}),bottomLeft:Wc(Wc({},qc),{left:"-10px",bottom:"-10px",cursor:"sw-resize"}),topLeft:Wc(Wc({},qc),{left:"-10px",top:"-10px",cursor:"nw-resize"})},Qc=p.memo(function(e){var t=e.onResizeStart,r=e.direction,n=e.children,i=e.replaceStyles,s=e.className,a=p.useCallback(function(e){t(e,r)},[t,r]),o=p.useCallback(function(e){t(e,r)},[t,r]),l=p.useMemo(function(){return Wc(Wc({position:"absolute",userSelect:"none"},Xc[r]),null!=i?i:{})},[i,r]);return Ti.jsx("div",{className:s||void 0,style:l,onMouseDown:a,onTouchStart:o,children:n})}),Zc=function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},e(t,r)};return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),Jc=function(){return Jc=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},Jc.apply(this,arguments)},ed={width:"auto",height:"auto"},td=function(e,t,r){return Math.max(Math.min(e,r),t)},rd=function(e,t,r){var n=Math.round(e/t);return n*t+r*(n-1)},nd=function(e,t){return new RegExp(e,"i").test(t)},id=function(e){return Boolean(e.touches&&e.touches.length)},sd=function(e,t,r){void 0===r&&(r=0);var n=t.reduce(function(r,n,i){return Math.abs(n-e)<Math.abs(t[r]-e)?i:r},0),i=Math.abs(t[n]-e);return 0===r||i<r?t[n]:e},ad=function(e){return"auto"===(e=e.toString())||e.endsWith("px")||e.endsWith("%")||e.endsWith("vh")||e.endsWith("vw")||e.endsWith("vmax")||e.endsWith("vmin")?e:"".concat(e,"px")},od=function(e,t,r,n){if(e&&"string"==typeof e){if(e.endsWith("px"))return Number(e.replace("px",""));if(e.endsWith("%"))return t*(Number(e.replace("%",""))/100);if(e.endsWith("vw"))return r*(Number(e.replace("vw",""))/100);if(e.endsWith("vh"))return n*(Number(e.replace("vh",""))/100)}return e},ld=["as","ref","style","className","grid","gridGap","snap","bounds","boundsByDirection","size","defaultSize","minWidth","minHeight","maxWidth","maxHeight","lockAspectRatio","lockAspectRatioExtraWidth","lockAspectRatioExtraHeight","enable","handleStyles","handleClasses","handleWrapperStyle","handleWrapperClass","children","onResizeStart","onResize","onResizeStop","handleComponent","scale","resizeRatio","snapGap"],ud="__resizable_base__",cd=function(e){function t(t){var r,n,i,s,a=e.call(this,t)||this;return a.ratio=1,a.resizable=null,a.parentLeft=0,a.parentTop=0,a.resizableLeft=0,a.resizableRight=0,a.resizableTop=0,a.resizableBottom=0,a.targetLeft=0,a.targetTop=0,a.delta={width:0,height:0},a.appendBase=function(){if(!a.resizable||!a.window)return null;var e=a.parentNode;if(!e)return null;var t=a.window.document.createElement("div");return t.style.width="100%",t.style.height="100%",t.style.position="absolute",t.style.transform="scale(0, 0)",t.style.left="0",t.style.flex="0 0 100%",t.classList?t.classList.add(ud):t.className+=ud,e.appendChild(t),t},a.removeBase=function(e){var t=a.parentNode;t&&t.removeChild(e)},a.state={isResizing:!1,width:null!==(n=null===(r=a.propsSize)||void 0===r?void 0:r.width)&&void 0!==n?n:"auto",height:null!==(s=null===(i=a.propsSize)||void 0===i?void 0:i.height)&&void 0!==s?s:"auto",direction:"right",original:{x:0,y:0,width:0,height:0},backgroundStyle:{height:"100%",width:"100%",backgroundColor:"rgba(0,0,0,0)",cursor:"auto",opacity:0,position:"fixed",zIndex:9999,top:"0",left:"0",bottom:"0",right:"0"},flexBasis:void 0},a.onResizeStart=a.onResizeStart.bind(a),a.onMouseMove=a.onMouseMove.bind(a),a.onMouseUp=a.onMouseUp.bind(a),a}return Zc(t,e),Object.defineProperty(t.prototype,"parentNode",{get:function(){return this.resizable?this.resizable.parentNode:null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"window",{get:function(){return this.resizable&&this.resizable.ownerDocument?this.resizable.ownerDocument.defaultView:null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"propsSize",{get:function(){return this.props.size||this.props.defaultSize||ed},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"size",{get:function(){var e=0,t=0;if(this.resizable&&this.window){var r=this.resizable.offsetWidth,n=this.resizable.offsetHeight,i=this.resizable.style.position;"relative"!==i&&(this.resizable.style.position="relative"),e="auto"!==this.resizable.style.width?this.resizable.offsetWidth:r,t="auto"!==this.resizable.style.height?this.resizable.offsetHeight:n,this.resizable.style.position=i}return{width:e,height:t}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"sizeStyle",{get:function(){var e=this,t=this.props.size,r=function(t){var r;if(void 0===e.state[t]||"auto"===e.state[t])return"auto";if(e.propsSize&&e.propsSize[t]&&(null===(r=e.propsSize[t])||void 0===r?void 0:r.toString().endsWith("%"))){if(e.state[t].toString().endsWith("%"))return e.state[t].toString();var n=e.getParentSize(),i=Number(e.state[t].toString().replace("px",""))/n[t]*100;return"".concat(i,"%")}return ad(e.state[t])};return{width:t&&void 0!==t.width&&!this.state.isResizing?ad(t.width):r("width"),height:t&&void 0!==t.height&&!this.state.isResizing?ad(t.height):r("height")}},enumerable:!1,configurable:!0}),t.prototype.getParentSize=function(){if(!this.parentNode)return this.window?{width:this.window.innerWidth,height:this.window.innerHeight}:{width:0,height:0};var e=this.appendBase();if(!e)return{width:0,height:0};var t=!1,r=this.parentNode.style.flexWrap;"wrap"!==r&&(t=!0,this.parentNode.style.flexWrap="wrap"),e.style.position="relative",e.style.minWidth="100%",e.style.minHeight="100%";var n={width:e.offsetWidth,height:e.offsetHeight};return t&&(this.parentNode.style.flexWrap=r),this.removeBase(e),n},t.prototype.bindEvents=function(){this.window&&(this.window.addEventListener("mouseup",this.onMouseUp),this.window.addEventListener("mousemove",this.onMouseMove),this.window.addEventListener("mouseleave",this.onMouseUp),this.window.addEventListener("touchmove",this.onMouseMove,{capture:!0,passive:!1}),this.window.addEventListener("touchend",this.onMouseUp))},t.prototype.unbindEvents=function(){this.window&&(this.window.removeEventListener("mouseup",this.onMouseUp),this.window.removeEventListener("mousemove",this.onMouseMove),this.window.removeEventListener("mouseleave",this.onMouseUp),this.window.removeEventListener("touchmove",this.onMouseMove,!0),this.window.removeEventListener("touchend",this.onMouseUp))},t.prototype.componentDidMount=function(){if(this.resizable&&this.window){var e=this.window.getComputedStyle(this.resizable);this.setState({width:this.state.width||this.size.width,height:this.state.height||this.size.height,flexBasis:"auto"!==e.flexBasis?e.flexBasis:void 0})}},t.prototype.componentWillUnmount=function(){this.window&&this.unbindEvents()},t.prototype.createSizeForCssProperty=function(e,t){var r=this.propsSize&&this.propsSize[t];return"auto"!==this.state[t]||this.state.original[t]!==e||void 0!==r&&"auto"!==r?e:"auto"},t.prototype.calculateNewMaxFromBoundary=function(e,t){var r,n,i=this.props.boundsByDirection,s=this.state.direction,a=i&&nd("left",s),o=i&&nd("top",s);if("parent"===this.props.bounds){var l=this.parentNode;l&&(r=a?this.resizableRight-this.parentLeft:l.offsetWidth+(this.parentLeft-this.resizableLeft),n=o?this.resizableBottom-this.parentTop:l.offsetHeight+(this.parentTop-this.resizableTop))}else"window"===this.props.bounds?this.window&&(r=a?this.resizableRight:this.window.innerWidth-this.resizableLeft,n=o?this.resizableBottom:this.window.innerHeight-this.resizableTop):this.props.bounds&&(r=a?this.resizableRight-this.targetLeft:this.props.bounds.offsetWidth+(this.targetLeft-this.resizableLeft),n=o?this.resizableBottom-this.targetTop:this.props.bounds.offsetHeight+(this.targetTop-this.resizableTop));return r&&Number.isFinite(r)&&(e=e&&e<r?e:r),n&&Number.isFinite(n)&&(t=t&&t<n?t:n),{maxWidth:e,maxHeight:t}},t.prototype.calculateNewSizeFromDirection=function(e,t){var r,n=this.props.scale||1,i=(r=this.props.resizeRatio||1,Array.isArray(r)?r:[r,r]),s=i[0],a=i[1],o=this.state,l=o.direction,u=o.original,c=this.props,d=c.lockAspectRatio,h=c.lockAspectRatioExtraHeight,f=c.lockAspectRatioExtraWidth,p=u.width,g=u.height,m=h||0,v=f||0;return nd("right",l)&&(p=u.width+(e-u.x)*s/n,d&&(g=(p-v)/this.ratio+m)),nd("left",l)&&(p=u.width-(e-u.x)*s/n,d&&(g=(p-v)/this.ratio+m)),nd("bottom",l)&&(g=u.height+(t-u.y)*a/n,d&&(p=(g-m)*this.ratio+v)),nd("top",l)&&(g=u.height-(t-u.y)*a/n,d&&(p=(g-m)*this.ratio+v)),{newWidth:p,newHeight:g}},t.prototype.calculateNewSizeFromAspectRatio=function(e,t,r,n){var i=this.props,s=i.lockAspectRatio,a=i.lockAspectRatioExtraHeight,o=i.lockAspectRatioExtraWidth,l=void 0===n.width?10:n.width,u=void 0===r.width||r.width<0?e:r.width,c=void 0===n.height?10:n.height,d=void 0===r.height||r.height<0?t:r.height,h=a||0,f=o||0;if(s){var p=(c-h)*this.ratio+f,g=(d-h)*this.ratio+f,m=(l-f)/this.ratio+h,v=(u-f)/this.ratio+h,y=Math.max(l,p),b=Math.min(u,g),w=Math.max(c,m),E=Math.min(d,v);e=td(e,y,b),t=td(t,w,E)}else e=td(e,l,u),t=td(t,c,d);return{newWidth:e,newHeight:t}},t.prototype.setBoundingClientRect=function(){var e=1/(this.props.scale||1);if("parent"===this.props.bounds){var t=this.parentNode;if(t){var r=t.getBoundingClientRect();this.parentLeft=r.left*e,this.parentTop=r.top*e}}if(this.props.bounds&&"string"!=typeof this.props.bounds){var n=this.props.bounds.getBoundingClientRect();this.targetLeft=n.left*e,this.targetTop=n.top*e}if(this.resizable){var i=this.resizable.getBoundingClientRect(),s=i.left,a=i.top,o=i.right,l=i.bottom;this.resizableLeft=s*e,this.resizableRight=o*e,this.resizableTop=a*e,this.resizableBottom=l*e}},t.prototype.onResizeStart=function(e,t){if(this.resizable&&this.window){var r,n=0,i=0;if(e.nativeEvent&&function(e){return Boolean((e.clientX||0===e.clientX)&&(e.clientY||0===e.clientY))}(e.nativeEvent)?(n=e.nativeEvent.clientX,i=e.nativeEvent.clientY):e.nativeEvent&&id(e.nativeEvent)&&(n=e.nativeEvent.touches[0].clientX,i=e.nativeEvent.touches[0].clientY),this.props.onResizeStart)if(this.resizable)if(!1===this.props.onResizeStart(e,t,this.resizable))return;this.props.size&&(void 0!==this.props.size.height&&this.props.size.height!==this.state.height&&this.setState({height:this.props.size.height}),void 0!==this.props.size.width&&this.props.size.width!==this.state.width&&this.setState({width:this.props.size.width})),this.ratio="number"==typeof this.props.lockAspectRatio?this.props.lockAspectRatio:this.size.width/this.size.height;var s=this.window.getComputedStyle(this.resizable);if("auto"!==s.flexBasis){var a=this.parentNode;if(a){var o=this.window.getComputedStyle(a).flexDirection;this.flexDir=o.startsWith("row")?"row":"column",r=s.flexBasis}}this.setBoundingClientRect(),this.bindEvents();var l={original:{x:n,y:i,width:this.size.width,height:this.size.height},isResizing:!0,backgroundStyle:Jc(Jc({},this.state.backgroundStyle),{cursor:this.window.getComputedStyle(e.target).cursor||"auto"}),direction:t,flexBasis:r};this.setState(l)}},t.prototype.onMouseMove=function(e){var t=this;if(this.state.isResizing&&this.resizable&&this.window){if(this.window.TouchEvent&&id(e))try{e.preventDefault(),e.stopPropagation()}catch(e){}var r=this.props,n=r.maxWidth,i=r.maxHeight,s=r.minWidth,a=r.minHeight,o=id(e)?e.touches[0].clientX:e.clientX,l=id(e)?e.touches[0].clientY:e.clientY,u=this.state,c=u.direction,d=u.original,h=u.width,f=u.height,p=this.getParentSize(),g=function(e,t,r,n,i,s,a){return n=od(n,e.width,t,r),i=od(i,e.height,t,r),s=od(s,e.width,t,r),a=od(a,e.height,t,r),{maxWidth:void 0===n?void 0:Number(n),maxHeight:void 0===i?void 0:Number(i),minWidth:void 0===s?void 0:Number(s),minHeight:void 0===a?void 0:Number(a)}}(p,this.window.innerWidth,this.window.innerHeight,n,i,s,a);n=g.maxWidth,i=g.maxHeight,s=g.minWidth,a=g.minHeight;var m=this.calculateNewSizeFromDirection(o,l),v=m.newHeight,y=m.newWidth,b=this.calculateNewMaxFromBoundary(n,i);this.props.snap&&this.props.snap.x&&(y=sd(y,this.props.snap.x,this.props.snapGap)),this.props.snap&&this.props.snap.y&&(v=sd(v,this.props.snap.y,this.props.snapGap));var w=this.calculateNewSizeFromAspectRatio(y,v,{width:b.maxWidth,height:b.maxHeight},{width:s,height:a});if(y=w.newWidth,v=w.newHeight,this.props.grid){var E=rd(y,this.props.grid[0],this.props.gridGap?this.props.gridGap[0]:0),S=rd(v,this.props.grid[1],this.props.gridGap?this.props.gridGap[1]:0),T=this.props.snapGap||0;y=0===T||Math.abs(E-y)<=T?E:y,v=0===T||Math.abs(S-v)<=T?S:v}var x={width:y-d.width,height:v-d.height};if(this.delta=x,h&&"string"==typeof h)if(h.endsWith("%")){var k=y/p.width*100;y="".concat(k,"%")}else if(h.endsWith("vw")){var A=y/this.window.innerWidth*100;y="".concat(A,"vw")}else if(h.endsWith("vh")){var R=y/this.window.innerHeight*100;y="".concat(R,"vh")}if(f&&"string"==typeof f)if(f.endsWith("%")){k=v/p.height*100;v="".concat(k,"%")}else if(f.endsWith("vw")){A=v/this.window.innerWidth*100;v="".concat(A,"vw")}else if(f.endsWith("vh")){R=v/this.window.innerHeight*100;v="".concat(R,"vh")}var L={width:this.createSizeForCssProperty(y,"width"),height:this.createSizeForCssProperty(v,"height")};"row"===this.flexDir?L.flexBasis=L.width:"column"===this.flexDir&&(L.flexBasis=L.height);var I=this.state.width!==L.width,C=this.state.height!==L.height,P=this.state.flexBasis!==L.flexBasis,D=I||C||P;D&&Pi.flushSync(function(){t.setState(L)}),this.props.onResize&&D&&this.props.onResize(e,c,this.resizable,x)}},t.prototype.onMouseUp=function(e){var t,r,n=this.state,i=n.isResizing,s=n.direction;n.original,i&&this.resizable&&(this.props.onResizeStop&&this.props.onResizeStop(e,s,this.resizable,this.delta),this.props.size&&this.setState({width:null!==(t=this.props.size.width)&&void 0!==t?t:"auto",height:null!==(r=this.props.size.height)&&void 0!==r?r:"auto"}),this.unbindEvents(),this.setState({isResizing:!1,backgroundStyle:Jc(Jc({},this.state.backgroundStyle),{cursor:"auto"})}))},t.prototype.updateSize=function(e){var t,r;this.setState({width:null!==(t=e.width)&&void 0!==t?t:"auto",height:null!==(r=e.height)&&void 0!==r?r:"auto"})},t.prototype.renderResizer=function(){var e=this,t=this.props,r=t.enable,n=t.handleStyles,i=t.handleClasses,s=t.handleWrapperStyle,a=t.handleWrapperClass,o=t.handleComponent;if(!r)return null;var l=Object.keys(r).map(function(t){return!1!==r[t]?Ti.jsx(Qc,{direction:t,onResizeStart:e.onResizeStart,replaceStyles:n&&n[t],className:i&&i[t],children:o&&o[t]?o[t]:null},t):null});return Ti.jsx("div",{className:a,style:s,children:l})},t.prototype.render=function(){var e=this,t=Object.keys(this.props).reduce(function(t,r){return-1!==ld.indexOf(r)||(t[r]=e.props[r]),t},{}),r=Jc(Jc(Jc({position:"relative",userSelect:this.state.isResizing?"none":"auto"},this.props.style),this.sizeStyle),{maxWidth:this.props.maxWidth,maxHeight:this.props.maxHeight,minWidth:this.props.minWidth,minHeight:this.props.minHeight,boxSizing:"border-box",flexShrink:0});this.state.flexBasis&&(r.flexBasis=this.state.flexBasis);var n=this.props.as||"div";return Ti.jsxs(n,Jc({style:r,className:this.props.className},t,{ref:function(t){t&&(e.resizable=t)},children:[this.state.isResizing&&Ti.jsx("div",{style:this.state.backgroundStyle}),this.props.children,this.renderResizer()]}))},t.defaultProps={as:"div",onResizeStart:function(){},onResize:function(){},onResizeStop:function(){},enable:{top:!0,right:!0,bottom:!0,left:!0,topRight:!0,bottomRight:!0,bottomLeft:!0,topLeft:!0},style:{},grid:[1,1],gridGap:[0,0],lockAspectRatio:!1,lockAspectRatioExtraWidth:0,lockAspectRatioExtraHeight:0,scale:1,resizeRatio:1,snapGap:0},t}(p.PureComponent),dd=function(e,t){return dd=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},dd(e,t)};var hd=function(){return hd=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},hd.apply(this,arguments)};var fd={width:"auto",height:"auto",display:"inline-block",position:"absolute",top:0,left:0},pd=function(e){function t(t){var r=e.call(this,t)||this;return r.resizingPosition={x:0,y:0},r.offsetFromParent={left:0,top:0},r.resizableElement={current:null},r.originalPosition={x:0,y:0},r.state={resizing:!1,bounds:{top:0,right:0,bottom:0,left:0},maxWidth:t.maxWidth,maxHeight:t.maxHeight},r.onResizeStart=r.onResizeStart.bind(r),r.onResize=r.onResize.bind(r),r.onResizeStop=r.onResizeStop.bind(r),r.onDragStart=r.onDragStart.bind(r),r.onDrag=r.onDrag.bind(r),r.onDragStop=r.onDragStop.bind(r),r.getMaxSizesFromProps=r.getMaxSizesFromProps.bind(r),r}return function(e,t){function r(){this.constructor=e}dd(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}(t,e),t.prototype.componentDidMount=function(){this.updateOffsetFromParent();var e=this.offsetFromParent,t=e.left,r=e.top,n=this.getDraggablePosition(),i=n.x,s=n.y;this.draggable.setState({x:i-t,y:s-r}),this.forceUpdate()},t.prototype.getDraggablePosition=function(){var e=this.draggable.state;return{x:e.x,y:e.y}},t.prototype.getParent=function(){return this.resizable&&this.resizable.parentNode},t.prototype.getParentSize=function(){return this.resizable.getParentSize()},t.prototype.getMaxSizesFromProps=function(){return{maxWidth:void 0===this.props.maxWidth?Number.MAX_SAFE_INTEGER:this.props.maxWidth,maxHeight:void 0===this.props.maxHeight?Number.MAX_SAFE_INTEGER:this.props.maxHeight}},t.prototype.getSelfElement=function(){return this.resizable&&this.resizable.resizable},t.prototype.getOffsetHeight=function(e){var t=this.props.scale;switch(this.props.bounds){case"window":return window.innerHeight/t;case"body":return document.body.offsetHeight/t;default:return e.offsetHeight}},t.prototype.getOffsetWidth=function(e){var t=this.props.scale;switch(this.props.bounds){case"window":return window.innerWidth/t;case"body":return document.body.offsetWidth/t;default:return e.offsetWidth}},t.prototype.onDragStart=function(e,t){this.props.onDragStart&&this.props.onDragStart(e,t);var r=this.getDraggablePosition();if(this.originalPosition=r,this.props.bounds){var n,i=this.getParent(),s=this.props.scale;if("parent"===this.props.bounds)n=i;else{if("body"===this.props.bounds){var a=i.getBoundingClientRect(),o=a.left,l=a.top,u=document.body.getBoundingClientRect(),c=-(o-i.offsetLeft*s-u.left)/s,d=-(l-i.offsetTop*s-u.top)/s,h=(document.body.offsetWidth-this.resizable.size.width*s)/s+c,f=(document.body.offsetHeight-this.resizable.size.height*s)/s+d;return this.setState({bounds:{top:d,right:h,bottom:f,left:c}})}if("window"===this.props.bounds){if(!this.resizable)return;var p=i.getBoundingClientRect(),g=p.left,m=p.top,v=-(g-i.offsetLeft*s)/s,y=-(m-i.offsetTop*s)/s;h=(window.innerWidth-this.resizable.size.width*s)/s+v,f=(window.innerHeight-this.resizable.size.height*s)/s+y;return this.setState({bounds:{top:y,right:h,bottom:f,left:v}})}"string"==typeof this.props.bounds?n=document.querySelector(this.props.bounds):this.props.bounds instanceof HTMLElement&&(n=this.props.bounds)}if(n instanceof HTMLElement&&i instanceof HTMLElement){var b=n.getBoundingClientRect(),w=b.left,E=b.top,S=i.getBoundingClientRect(),T=(w-S.left)/s,x=E-S.top;if(this.resizable){this.updateOffsetFromParent();var k=this.offsetFromParent;this.setState({bounds:{top:x-k.top,right:T+(n.offsetWidth-this.resizable.size.width)-k.left/s,bottom:x+(n.offsetHeight-this.resizable.size.height)-k.top,left:T-k.left/s}})}}}},t.prototype.onDrag=function(e,t){if(this.props.onDrag){var r=this.offsetFromParent,n=r.left,i=r.top;return this.props.dragAxis&&"both"!==this.props.dragAxis?"x"===this.props.dragAxis?this.props.onDrag(e,hd(hd({},t),{x:t.x+n,y:this.originalPosition.y+i,deltaY:0})):"y"===this.props.dragAxis?this.props.onDrag(e,hd(hd({},t),{x:this.originalPosition.x+n,y:t.y+i,deltaX:0})):void 0:this.props.onDrag(e,hd(hd({},t),{x:t.x+n,y:t.y+i}))}},t.prototype.onDragStop=function(e,t){if(this.props.onDragStop){var r=this.offsetFromParent,n=r.left,i=r.top;return this.props.dragAxis&&"both"!==this.props.dragAxis?"x"===this.props.dragAxis?this.props.onDragStop(e,hd(hd({},t),{x:t.x+n,y:this.originalPosition.y+i,deltaY:0})):"y"===this.props.dragAxis?this.props.onDragStop(e,hd(hd({},t),{x:this.originalPosition.x+n,y:t.y+i,deltaX:0})):void 0:this.props.onDragStop(e,hd(hd({},t),{x:t.x+n,y:t.y+i}))}},t.prototype.onResizeStart=function(e,t,r){e.stopPropagation(),this.setState({resizing:!0});var n=this.props.scale,i=this.offsetFromParent,s=this.getDraggablePosition();if(this.resizingPosition={x:s.x+i.left,y:s.y+i.top},this.originalPosition=s,this.props.bounds){var a=this.getParent(),o=void 0;"parent"===this.props.bounds?o=a:"body"===this.props.bounds?o=document.body:"window"===this.props.bounds?o=window:"string"==typeof this.props.bounds?o=document.querySelector(this.props.bounds):this.props.bounds instanceof HTMLElement&&(o=this.props.bounds);var l=this.getSelfElement();if(l instanceof Element&&(o instanceof HTMLElement||o===window)&&a instanceof HTMLElement){var u=this.getMaxSizesFromProps(),c=u.maxWidth,d=u.maxHeight,h=this.getParentSize();if(c&&"string"==typeof c)if(c.endsWith("%")){var f=Number(c.replace("%",""))/100;c=h.width*f}else c.endsWith("px")&&(c=Number(c.replace("px","")));if(d&&"string"==typeof d)if(d.endsWith("%")){f=Number(d.replace("%",""))/100;d=h.height*f}else d.endsWith("px")&&(d=Number(d.replace("px","")));var p=l.getBoundingClientRect(),g=p.left,m=p.top,v="window"===this.props.bounds?{left:0,top:0}:o.getBoundingClientRect(),y=v.left,b=v.top,w=this.getOffsetWidth(o),E=this.getOffsetHeight(o),S=t.toLowerCase().endsWith("left"),T=t.toLowerCase().endsWith("right"),x=t.startsWith("top"),k=t.startsWith("bottom");if((S||x)&&this.resizable){var A=(g-y)/n+this.resizable.size.width;this.setState({maxWidth:A>Number(c)?c:A})}if(T||this.props.lockAspectRatio&&!S&&!x){A=w+(y-g)/n;this.setState({maxWidth:A>Number(c)?c:A})}if((x||S)&&this.resizable){A=(m-b)/n+this.resizable.size.height;this.setState({maxHeight:A>Number(d)?d:A})}if(k||this.props.lockAspectRatio&&!x&&!S){A=E+(b-m)/n;this.setState({maxHeight:A>Number(d)?d:A})}}}else this.setState({maxWidth:this.props.maxWidth,maxHeight:this.props.maxHeight});this.props.onResizeStart&&this.props.onResizeStart(e,t,r)},t.prototype.onResize=function(e,t,r,n){var i=this,s={x:this.originalPosition.x,y:this.originalPosition.y},a=-n.width,o=-n.height;["top","left","topLeft","bottomLeft","topRight"].includes(t)&&("bottomLeft"===t?s.x+=a:("topRight"===t||(s.x+=a),s.y+=o));var l=this.draggable.state;s.x===l.x&&s.y===l.y||Pi.flushSync(function(){i.draggable.setState(s)}),this.updateOffsetFromParent();var u=this.offsetFromParent,c=this.getDraggablePosition().x+u.left,d=this.getDraggablePosition().y+u.top;this.resizingPosition={x:c,y:d},this.props.onResize&&this.props.onResize(e,t,r,n,{x:c,y:d})},t.prototype.onResizeStop=function(e,t,r,n){this.setState({resizing:!1});var i=this.getMaxSizesFromProps(),s=i.maxWidth,a=i.maxHeight;this.setState({maxWidth:s,maxHeight:a}),this.props.onResizeStop&&this.props.onResizeStop(e,t,r,n,this.resizingPosition)},t.prototype.updateSize=function(e){this.resizable&&this.resizable.updateSize({width:e.width,height:e.height})},t.prototype.updatePosition=function(e){this.draggable.setState(e)},t.prototype.updateOffsetFromParent=function(){var e=this.props.scale,t=this.getParent(),r=this.getSelfElement();if(!t||null===r)return{top:0,left:0};var n=t.getBoundingClientRect(),i=n.left,s=n.top,a=r.getBoundingClientRect(),o=this.getDraggablePosition(),l=t.scrollLeft,u=t.scrollTop;this.offsetFromParent={left:a.left-i+l-o.x*e,top:a.top-s+u-o.y*e}},t.prototype.render=function(){var e=this,t=this.props,r=t.disableDragging,n=t.style,i=t.dragHandleClassName,s=t.position,a=t.onMouseDown,o=t.onMouseUp,l=t.dragAxis,u=t.dragGrid,c=t.bounds,d=t.enableUserSelectHack,h=t.cancel,f=t.children;t.onResizeStart,t.onResize,t.onResizeStop,t.onDragStart,t.onDrag,t.onDragStop;var g=t.resizeHandleStyles,m=t.resizeHandleClasses,v=t.resizeHandleComponent,y=t.enableResizing,b=t.resizeGrid,w=t.resizeHandleWrapperClass,E=t.resizeHandleWrapperStyle,S=t.scale,T=t.allowAnyClick,x=t.dragPositionOffset,k=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]])}return r}(t,["disableDragging","style","dragHandleClassName","position","onMouseDown","onMouseUp","dragAxis","dragGrid","bounds","enableUserSelectHack","cancel","children","onResizeStart","onResize","onResizeStop","onDragStart","onDrag","onDragStop","resizeHandleStyles","resizeHandleClasses","resizeHandleComponent","enableResizing","resizeGrid","resizeHandleWrapperClass","resizeHandleWrapperStyle","scale","allowAnyClick","dragPositionOffset"]),A=this.props.default?hd({},this.props.default):void 0;delete k.default;var R,L=r||i?{cursor:"auto"}:{cursor:"move"},I=hd(hd(hd({},fd),L),n),C=this.offsetFromParent,P=C.left,D=C.top;s&&(R={x:s.x-P,y:s.y-D});var _,M=this.state.resizing?void 0:R,O=this.state.resizing?"both":l;return p.createElement(Vc,{ref:function(t){t&&(e.draggable=t)},handle:i?".".concat(i):void 0,defaultPosition:A,onMouseDown:a,onMouseUp:o,onStart:this.onDragStart,onDrag:this.onDrag,onStop:this.onDragStop,axis:O,disabled:r,grid:u,bounds:c?this.state.bounds:void 0,position:M,enableUserSelectHack:d,cancel:h,scale:S,allowAnyClick:T,nodeRef:this.resizableElement,positionOffset:x},p.createElement(cd,hd({},k,{ref:function(t){t&&(e.resizable=t,e.resizableElement.current=t.resizable)},defaultSize:A,size:this.props.size,enable:"boolean"==typeof y?(_=y,{bottom:_,bottomLeft:_,bottomRight:_,left:_,right:_,top:_,topLeft:_,topRight:_}):y,onResizeStart:this.onResizeStart,onResize:this.onResize,onResizeStop:this.onResizeStop,style:I,minWidth:this.props.minWidth,minHeight:this.props.minHeight,maxWidth:this.state.resizing?this.state.maxWidth:this.props.maxWidth,maxHeight:this.state.resizing?this.state.maxHeight:this.props.maxHeight,grid:b,handleWrapperClass:w,handleWrapperStyle:E,lockAspectRatio:this.props.lockAspectRatio,lockAspectRatioExtraWidth:this.props.lockAspectRatioExtraWidth,lockAspectRatioExtraHeight:this.props.lockAspectRatioExtraHeight,handleStyles:g,handleClasses:m,handleComponent:v,scale:this.props.scale}),f))},t.defaultProps={maxWidth:Number.MAX_SAFE_INTEGER,maxHeight:Number.MAX_SAFE_INTEGER,scale:1,onResizeStart:function(){},onResize:function(){},onResizeStop:function(){},onDragStart:function(){},onDrag:function(){},onDragStop:function(){}},t}(p.PureComponent);const gd=({shortform:e,mute:t,play:r})=>{const n=Ft(e.media.objectId);return Object.assign({hideProducts:!0},e.playerSettings),g.createElement("div",{className:"relative w-full h-full text-white"},g.createElement(oi,{file:n,mute:t,play:r}))},md=({shortform:e,setClose:t})=>{const[r,n]=g.useState(!0),[i,s]=p.useState(!0),[a,o]=p.useState(!1),l=g.useRef(null),u=()=>{l.current&&(window.clearTimeout(l.current),l.current=null)},c=(e=1500)=>{u(),l.current=window.setTimeout(()=>o(!1),e)};return p.useEffect(()=>()=>u(),[]),g.createElement("div",{className:"relative w-full h-full",onClick:()=>{o(!0),c(2e3)},onMouseLeave:()=>c(800),onMouseEnter:()=>a&&c(1500)},g.createElement("div",{className:"absolute inset-0 bg-black",style:{zIndex:1,opacity:a?.4:0,transition:"opacity 300ms ease",pointerEvents:a?"auto":"none"}}),g.createElement("div",{className:"absolute inset-0",style:{zIndex:2,opacity:a?1:0,transition:"opacity 300ms ease",pointerEvents:a?"auto":"none"}},g.createElement("div",{className:"absolute text-white flex gap-2",style:{zIndex:3,top:8,right:8}},g.createElement("button",{className:"cursor-pointer",onClick:e=>{e.stopPropagation(),n(e=>!e)},"aria-label":r?"Unmute":"Mute"},r?g.createElement(si,{size:20}):g.createElement(ii,{size:20})),g.createElement("button",{className:"cursor-pointer",onClick:e=>{null==e||e.stopPropagation(),t()},"aria-label":"Close"},g.createElement(ai,{size:20}))),g.createElement("div",{className:"absolute inset-0 flex items-center justify-center",style:{pointerEvents:"none"}},g.createElement("button",{onClick:e=>{null==e||e.stopPropagation(),s(e=>!e)},"aria-label":i?"Pause":"Play",className:"cursor-pointer text-white p-2 ",style:{pointerEvents:"auto"}},i?g.createElement(ti,{size:28}):g.createElement(ri,{size:28})))),g.createElement(gd,{shortform:e,mute:r,play:i}))},vd=({shortsId:e,type:t})=>{const{shortform:r}=yc(),[n,i]=p.useState(!1),{playtime:s}=Kt(),a=()=>{if(!r)return;i(!0);const{shortsId:e,uuid:t,userId:n}=r;Qt({contentId:e,uuid:t,type:X.SHORTS,playtime:s,userId:n})};(({shorform:e,playtime:t})=>{p.useEffect(()=>{if(!e)return;const{shortsId:t,shortsUuid:r,userId:n}=e;Xt({contentId:t,uuid:r,type:X.SHORTS,userId:n,isFirstPlay:!zt(t)})},[]);const r=ne();p.useEffect(()=>{if(!e||r)return;const{shortsId:n,uuid:i,userId:s}=e;Qt({contentId:n,uuid:i,type:X.SHORTS,playtime:t,userId:s})},[r])})({shorform:r,playtime:s});const{w:o,h:l,left:u,top:c}=(()=>{const e=window.visualViewport;return e?{w:e.width,h:e.height,left:e.offsetLeft,top:e.offsetTop}:{w:window.innerWidth,h:window.innerHeight,left:0,top:0}})();return r&&!n&&g.createElement(pd,{minWidth:240,lockAspectRatio:9/16,style:{zIndex:99999},default:{width:240,height:427,x:u+o-240-50,y:c+l-427-50},bounds:"window"},"shopping"===t&&r.productsInfo.length>0?g.createElement(Bo,{shortForm:r,handleClose:a}):g.createElement(md,{shortform:r,setClose:a}))},yd=({eventId:e})=>{const[t,r]=p.useState(!1),{PLAYER_BASE_URL:n}=Mt();if(t)return null;const{w:i,h:s,left:a,top:o}=(()=>{const e=window.visualViewport;return e?{w:e.width,h:e.height,left:e.offsetLeft,top:e.offsetTop}:{w:window.innerWidth,h:window.innerHeight,left:0,top:0}})();return g.createElement(pd,{minWidth:240,lockAspectRatio:9/17.05,style:{zIndex:99999},default:{width:240,height:455,x:a+i-240-50,y:o+s-427-28-50},bounds:"window",dragHandleClassName:"live-floating-drag-handle"},g.createElement("div",{className:"flex flex-col w-full h-full",style:{borderRadius:8,overflow:"hidden",boxShadow:"0 4px 24px rgba(0,0,0,0.4)"}},g.createElement("div",{className:"live-floating-drag-handle flex items-center justify-between",style:{height:28,minHeight:28,background:"#111",cursor:"grab",padding:"0 8px",userSelect:"none"}},g.createElement(Jn,{size:16,color:"#888"}),g.createElement("button",{className:"cursor-pointer",style:{color:"#ccc",lineHeight:0},onClick:()=>r(!0),"aria-label":"Close"},g.createElement(ai,{size:16}))),g.createElement("iframe",{src:`${n}/live/${e}`,style:{flex:1,border:0,display:"block",minHeight:0},allow:"autoplay; fullscreen; picture-in-picture",allowFullScreen:!0,scrolling:"no",referrerPolicy:"no-referrer-when-downgrade"})))};var bd;!function(e){e[e.PLATFORM=1]="PLATFORM",e[e.GRID=2]="GRID",e[e.VERTICAL=3]="VERTICAL",e[e.HORIZONTAL=4]="HORIZONTAL"}(bd||(bd={}));const wd=ur(e=>({liveWidget:null,setLiveWidget:t=>e({liveWidget:t}),nextKey:"",setNextKey:t=>e({nextKey:t}),isFetching:!1,setIsFetching:t=>e({isFetching:t})})),Ed=({opacity:e=.4,className:t})=>{const r=Math.max(0,Math.min(1,e));return g.createElement("div",{"aria-hidden":!0,role:"presentation",className:`absolute inset-0 pointer-events-none ${null!=t?t:""}`,style:{backgroundColor:`rgba(0,0,0,${r})`,borderRadius:"inherit"}})},Sd=({content:e})=>{const{PLAYER_BASE_URL:t}=Mt();return g.createElement("iframe",{src:`${t}/live/${e.eventId}`,className:"w-full h-full block",style:{border:0,display:"block"},allow:"autoplay; fullscreen; picture-in-picture",allowFullScreen:!0,scrolling:"no",referrerPolicy:"no-referrer-when-downgrade"})},Td=(e,t)=>{const[r,n]=g.useState({}),[i,s]=g.useState({primary:20,secondary:12});return g.useEffect(()=>{const r=t.current;if(!r)return;const i=()=>{const t=r.getBoundingClientRect(),i=Math.max(0,Math.floor(t.width)),a=Math.max(0,Math.floor(t.height)),[o,l]=e.includes("/")?e.split("/").map(e=>parseFloat(e)):[1,1],u=l/o;let c,d;i>0&&a>0?(c=i,d=Math.round(c*u),d>a&&(d=a,c=Math.round(d/u)),n({width:c,height:d})):n({});const h="number"==typeof c?c:i,f=Math.max(16,Math.round(.075*h)),p=Math.max(11,Math.round(.042*h));s({primary:f,secondary:p})};if("undefined"!=typeof ResizeObserver){const e=new ResizeObserver(()=>i());return e.observe(r),()=>e.disconnect()}{const e=()=>i();return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)}},[e]),{fontSize:i,boxSize:r}},xd=({content:e,aspectRatio:t="9/16",cursor:r="default",borderRadius:n})=>{var i,s;const{leftTime:a}=(e=>{const{start:t}=e,r=vt().tz("Asia/Seoul").unix(),[n,i]=p.useState(t-r>0?t-r:0);return Wt(()=>{i(n<=0?0:e=>e-1)},1e3),{leftTime:n}})(e),o=null===(s=null===(i=null==e?void 0:e.designInfo)||void 0===i?void 0:i.thumbPath)||void 0===s?void 0:s.preview,l=g.useRef(null),{boxSize:u,fontSize:c}=Td(t,l),{PLAYER_BASE_URL:d}=Mt(),h=Math.floor(Date.now()/1e3),f="number"==typeof e.end&&e.end>0&&e.end<h;return g.createElement("div",{className:"w-full h-full flex items-center justify-center",ref:l},g.createElement("div",{className:"relative rounded overflow-hidden",style:{width:u.width?`${u.width}px`:"100%",height:u.height?`${u.height}px`:"100%",borderRadius:`${null!=n?n:10}px`,backgroundRepeat:"no-repeat",backgroundPosition:"center",backgroundSize:"cover",aspectRatio:u.height?void 0:t,backgroundImage:o?`url(${Gt(o)})`:void 0,backgroundColor:o?void 0:"black"}},1===e.openStatus?g.createElement(g.Fragment,null,g.createElement(Sd,{content:e}),g.createElement("a",{href:`${d}/live/${e.eventId}`,target:"_blank",rel:"noopener noreferrer","aria-label":`${e.eventName} 바로가기`,style:{position:"absolute",inset:0,zIndex:30,display:"block",textDecoration:"none",cursor:"pointer",background:"transparent"}})):f?g.createElement(g.Fragment,null,g.createElement(Ed,null),g.createElement("div",{className:"text-white flex flex-col items-center justify-center absolute inset-0",style:{zIndex:10,gap:"12px",userSelect:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none",cursor:r,pointerEvents:"none"}},g.createElement("p",{style:{fontSize:`${c.primary}px`,fontWeight:700}},"다시보기"),g.createElement("p",{style:{fontSize:`${c.secondary}px`}},"라이브가 종료되었습니다"))):g.createElement(g.Fragment,null,g.createElement(Ed,null),g.createElement("div",{className:"text-white flex flex-col items-center justify-center absolute inset-0",style:{zIndex:10,gap:"20px",userSelect:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none",cursor:r,pointerEvents:"none"}},g.createElement("p",{style:{fontSize:`${c.primary}px`}},((e,t)=>{if(e>86400)return vt.unix(t).tz("Asia/Seoul").format("M월 D일 A h시 mm분");const r=vt.duration(e,"seconds");return`${r.hours().toString().padStart(2,"0")}:${r.minutes().toString().padStart(2,"0")}:${r.seconds().toString().padStart(2,"0")}`})(a,e.start)),g.createElement("p",{style:{fontSize:`${c.secondary}px`}},"곧 라이브가 시작됩니다!")))))},kd=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},Ad=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=Rd},Rd=Number.MAX_SAFE_INTEGER||9007199254740991;let Ld=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),Id=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.UNKNOWN="unknown",e}({}),Cd=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({});var Pd="manifest",Dd="level",_d="audioTrack",Md="subtitleTrack",Od="main",Nd="audio",Fd="subtitle";class $d{constructor(e,t=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_=t,this.totalWeight_=r}sample(e,t){const r=Math.pow(this.alpha_,e);this.estimate_=t*(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 Bd{constructor(e,t,r,n=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 $d(e),this.fast_=new $d(t),this.defaultTTFB_=n,this.ttfb_=new $d(e)}update(e,t){const{slow_:r,fast_:n,ttfb_:i}=this;r.halfLife!==e&&(this.slow_=new $d(e,r.getEstimate(),r.getTotalWeight())),n.halfLife!==t&&(this.fast_=new $d(t,n.getEstimate(),n.getTotalWeight())),i.halfLife!==e&&(this.ttfb_=new $d(e,i.getEstimate(),i.getTotalWeight()))}sample(e,t){const r=(e=Math.max(e,this.minDelayMs_))/1e3,n=8*t/r;this.fast_.sample(r,n),this.slow_.sample(r,n)}sampleTTFB(e){const t=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(t,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 Ud(e,t,r){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function zd(){return zd=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},zd.apply(null,arguments)}function jd(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function Gd(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?jd(Object(r),!0).forEach(function(t){Ud(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):jd(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}class Hd{constructor(e,t){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=Vd,this.debug=t.debug.bind(null,r),this.log=t.log.bind(null,r),this.warn=t.warn.bind(null,r),this.info=t.info.bind(null,r),this.error=t.error.bind(null,r)}}const Vd=function(){},Wd={trace:Vd,debug:Vd,log:Vd,warn:Vd,info:Vd,error:Vd};function Kd(){return zd({},Wd)}function Yd(e,t,r){return t[e]?t[e].bind(t):function(e,t){const r=self.console[e];return r?r.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):Vd}(e,r)}const qd=Kd();const Xd=qd;function Qd(e=!0){if("undefined"==typeof self)return;return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Zd(e,t){const r=Object.keys(e),n=Object.keys(t),i=r.length,s=n.length;return!i||!s||i===s&&!r.some(e=>-1===n.indexOf(e))}function Jd(e,t=!1){if("undefined"!=typeof TextDecoder){const r=new TextDecoder("utf-8").decode(e);if(t){const e=r.indexOf("\0");return-1!==e?r.substring(0,e):r}return r.replace(/\0/g,"")}const r=e.length;let n,i,s,a="",o=0;for(;o<r;){if(n=e[o++],0===n&&t)return a;if(0!==n&&3!==n)switch(n>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(n);break;case 12:case 13:i=e[o++],a+=String.fromCharCode((31&n)<<6|63&i);break;case 14:i=e[o++],s=e[o++],a+=String.fromCharCode((15&n)<<12|(63&i)<<6|63&s)}}return a}function eh(e){let t="";for(let r=0;r<e.length;r++){let n=e[r].toString(16);n.length<2&&(n="0"+n),t+=n}return t}function th(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function rh(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var nh,ih={exports:{}};var sh,ah,oh,lh,uh,ch=(nh||(nh=1,sh=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,ah=/^(?=([^\/?#]*))\1([^]*)$/,oh=/(?:\/|^)\.(?=\/)/g,lh=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,ih.exports=uh={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.alwaysNormalize)return e;var n=uh.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");return n.path=uh.normalizePath(n.path),uh.buildURLFromParts(n)}var i=uh.parseURL(t);if(!i)throw new Error("Error trying to parse relative URL.");if(i.scheme)return r.alwaysNormalize?(i.path=uh.normalizePath(i.path),uh.buildURLFromParts(i)):t;var s=uh.parseURL(e);if(!s)throw new Error("Error trying to parse base URL.");if(!s.netLoc&&s.path&&"/"!==s.path[0]){var a=ah.exec(s.path);s.netLoc=a[1],s.path=a[2]}s.netLoc&&!s.path&&(s.path="/");var o={scheme:s.scheme,netLoc:i.netLoc,path:null,params:i.params,query:i.query,fragment:i.fragment};if(!i.netLoc&&(o.netLoc=s.netLoc,"/"!==i.path[0]))if(i.path){var l=s.path,u=l.substring(0,l.lastIndexOf("/")+1)+i.path;o.path=uh.normalizePath(u)}else o.path=s.path,i.params||(o.params=s.params,i.query||(o.query=s.query));return null===o.path&&(o.path=r.alwaysNormalize?uh.normalizePath(i.path):i.path),uh.buildURLFromParts(o)},parseURL:function(e){var t=sh.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(oh,"");e.length!==(e=e.replace(lh,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}}),ih.exports);class dh{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 hh="audio",fh="video",ph="audiovideo";class gh{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof e&&(e={url:e}),this.base=e,function(e,t){const r=bh(e,t);r&&(r.enumerable=!0,Object.defineProperty(e,t,r))}(this,"stats")}setByteRange(e,t){const r=e.split("@",2);let n;n=1===r.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(r[1]),this._byteRange=[n,parseInt(r[0])+n]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[hh]:null,[fh]:null,[ph]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new dh),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=ch.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[hh]=null,e[fh]=null,e[ph]=null}}function mh(e){return"initSegment"!==e.sn}class vh extends gh{constructor(e,t){super(t),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],t=this.byteRange[1];if(kd(e)&&kd(t))return t-e}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(null==(e=this._decryptdata)||!e.keyId){const e=Object.keys(t);if(1===e.length){const r=this._decryptdata=t[e[0]]||null;r&&(this._decryptdata=r.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const e=kd(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t;const e=Object.keys(this.levelkeys),r=e.length;if(r>1||1===r&&null!=(t=this.levelkeys[e[0]])&&t.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){kd(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}get ref(){return mh(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 t=this.levelkeys;if(t){var r;const n=t[e];!n||null!=(r=this._decryptdata)&&r.keyId||(this._decryptdata=n.getDecryptData(this.sn,t))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,r,n,i,s=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,n),o.endDTS=Math.max(o.endDTS,i)):a[e]={startPTS:t,endPTS:r,startDTS:n,endDTS:i,partial:s}}}class yh extends gh{constructor(e,t,r,n,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=t,this.index=n;const s=e.enumeratedString("BYTERANGE");s&&this.setByteRange(s,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 bh(e,t){const r=Object.getPrototypeOf(e);if(r){const e=Object.getOwnPropertyDescriptor(r,t);return e||bh(r,t)}}const wh=Math.pow(2,32)-1,Eh=[].push,Sh={video:1,audio:2,id3:3,text:4};function Th(e){return String.fromCharCode.apply(null,e)}function xh(e,t){const r=e[t]<<8|e[t+1];return r<0?65536+r:r}function kh(e,t){const r=Rh(e,t);return r<0?4294967296+r:r}function Ah(e,t){let r=kh(e,t);return r*=Math.pow(2,32),r+=kh(e,t+4),r}function Rh(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function Lh(e,t){const r=[];if(!t.length)return r;const n=e.byteLength;for(let i=0;i<n;){const s=kh(e,i),a=s>1?i+s:n;if(Th(e.subarray(i+4,i+8))===t[0])if(1===t.length)r.push(e.subarray(i+8,a));else{const n=Lh(e.subarray(i+8,a),t.slice(1));n.length&&Eh.apply(r,n)}i=a}return r}function Ih(e){const t=[],r=e[0];let n=8;const i=kh(e,n);n+=4;let s=0,a=0;0===r?(s=kh(e,n),a=kh(e,n+4),n+=8):(s=Ah(e,n),a=Ah(e,n+8),n+=16),n+=2;let o=e.length+a;const l=xh(e,n);n+=2;for(let r=0;r<l;r++){let r=n;const s=kh(e,r);r+=4;const a=2147483647&s;if(1===(2147483648&s)>>>31)return Xd.warn("SIDX has hierarchical references (not supported)"),null;const l=kh(e,r);r+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/i,start:o,end:o+a-1}}),o+=a,r+=4,n=r}return{earliestPresentationTime:s,timescale:i,version:r,referencesCount:l,references:t}}function Ch(e){const t=[],r=Lh(e,["moov","trak"]);for(let e=0;e<r.length;e++){const n=r[e],i=Lh(n,["tkhd"])[0];if(i){let e=i[0];const r=kh(i,0===e?12:20),s=Lh(n,["mdia","mdhd"])[0];if(s){e=s[0];const i=kh(s,0===e?12:20),a=Lh(n,["mdia","hdlr"])[0];if(a){const e=Th(a.subarray(8,12)),s={soun:hh,vide:fh}[e],o=Ph(Lh(n,["mdia","minf","stbl","stsd"])[0]);s?(t[r]={timescale:i,type:s,stsd:o},t[s]=Gd({timescale:i,id:r},o)):t[r]={timescale:i,type:e,stsd:o}}}}}return Lh(e,["moov","mvex","trex"]).forEach(e=>{const r=kh(e,4),n=t[r];n&&(n.default={duration:kh(e,12),flags:kh(e,20)})}),t}function Ph(e){const t=e.subarray(8),r=t.subarray(86),n=Th(t.subarray(4,8));let i,s=n;const a="enca"===n||"encv"===n;if(a){const e=Lh(t,[n])[0];Lh(e.subarray("enca"===n?28:78),["sinf"]).forEach(e=>{const t=Lh(e,["schm"])[0];if(t){const r=Th(t.subarray(4,8));if("cbcs"===r||"cenc"===r){const t=Lh(e,["frma"])[0];t&&(s=Th(t))}}})}const o=s;switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const e=Lh(r,["avcC"])[0];e&&e.length>3&&(s+="."+Mh(e[1])+Mh(e[2])+Mh(e[3]),i=Dh("avc1"===o?"dva1":"dvav",r));break}case"mp4a":{const e=Lh(t,[n])[0],r=Lh(e.subarray(28),["esds"])[0];if(r&&r.length>7){let e=4;if(3!==r[e++])break;e=_h(r,e),e+=2;const t=r[e++];if(128&t&&(e+=2),64&t&&(e+=r[e++]),4!==r[e++])break;e=_h(r,e);const n=r[e++];if(64!==n)break;if(s+="."+Mh(n),e+=12,5!==r[e++])break;e=_h(r,e);const i=r[e++];let a=(248&i)>>3;31===a&&(a+=1+((7&i)<<3)+((224&r[e])>>5)),s+="."+a}break}case"hvc1":case"hev1":{const e=Lh(r,["hvcC"])[0];if(e&&e.length>12){const t=e[1],r=["","A","B","C"][t>>6],n=31&t,i=kh(e,2),a=(32&t)>>5?"H":"L",o=e[12],l=e.subarray(6,12);s+="."+r+n,s+="."+function(e){let t=0;for(let r=0;r<32;r++)t|=(e>>r&1)<<31-r;return t>>>0}(i).toString(16).toUpperCase(),s+="."+a+o;let u="";for(let e=l.length;e--;){const t=l[e];if(t||u){u="."+t.toString(16).toUpperCase()+u}}s+=u}i=Dh("hev1"==o?"dvhe":"dvh1",r);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":s=Dh(s,r)||s;break;case"vp09":{const e=Lh(r,["vpcC"])[0];if(e&&e.length>6){const t=e[4],r=e[5],n=e[6]>>4&15;s+="."+Oh(t)+"."+Oh(r)+"."+Oh(n)}break}case"av01":{const e=Lh(r,["av1C"])[0];if(e&&e.length>2){const t=e[1]>>>5,n=31&e[1],a=e[2]>>>7?"H":"M",o=(64&e[2])>>6,l=(32&e[2])>>5,u=2===t&&o?l?12:10:o?10:8,c=(16&e[2])>>4,d=(8&e[2])>>3,h=(4&e[2])>>2,f=3&e[2],p=1,g=1,m=1,v=0;s+="."+t+"."+Oh(n)+a+"."+Oh(u)+"."+c+"."+d+h+f+"."+Oh(p)+"."+Oh(g)+"."+Oh(m)+"."+v,i=Dh("dav1",r)}break}}return{codec:s,encrypted:a,supplemental:i}}function Dh(e,t){const r=Lh(t,["dvvC"]),n=r.length?r[0]:Lh(t,["dvcC"])[0];if(n){const t=n[2]>>1&127,r=n[2]<<5&32|n[3]>>3&31;return e+"."+Oh(t)+"."+Oh(r)}}function _h(e,t){const r=t+5;for(;128&e[t++]&&t<r;);return t}function Mh(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function Oh(e){return(e<10?"0":"")+e}function Nh(e,t){Lh(e,["moov","trak"]).forEach(e=>{const r=Lh(e,["mdia","minf","stbl","stsd"])[0];if(!r)return;const n=r.subarray(8);let i=Lh(n,["enca"]);const s=i.length>0;s||(i=Lh(n,["encv"])),i.forEach(e=>{Lh(s?e.subarray(28):e.subarray(78),["sinf"]).forEach(e=>{const r=Fh(e);r&&t(r,s)})})})}function Fh(e){const t=Lh(e,["schm"])[0];if(t){const r=Th(t.subarray(4,8));if("cbcs"===r||"cenc"===r){const t=Lh(e,["schi","tenc"])[0];if(t)return t}}}function $h(e,t){const r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function Bh(e,t){const r=[],n=t.samples,i=t.timescale,s=t.id;let a=!1;return Lh(n,["moof"]).map(o=>{const l=o.byteOffset-8;Lh(o,["traf"]).map(o=>{const u=Lh(o,["tfdt"]).map(e=>{const t=e[0];let r=kh(e,4);return 1===t&&(r*=Math.pow(2,32),r+=kh(e,8)),r/i})[0];return void 0!==u&&(e=u),Lh(o,["tfhd"]).map(u=>{const c=kh(u,4),d=16777215&kh(u,0);let h=0;const f=!!(16&d);let p=0;const g=!!(32&d);let m=8;c===s&&(!!(1&d)&&(m+=8),!!(2&d)&&(m+=4),!!(8&d)&&(h=kh(u,m),m+=4),f&&(p=kh(u,m),m+=4),g&&(m+=4),"video"===t.type&&(a=Uh(t.codec)),Lh(o,["trun"]).map(s=>{const o=s[0],u=16777215&kh(s,0),c=!!(1&u);let d=0;const f=!!(4&u),g=!!(256&u);let m=0;const v=!!(512&u);let y=0;const b=!!(1024&u),w=!!(2048&u);let E=0;const S=kh(s,4);let T=8;c&&(d=kh(s,T),T+=4),f&&(T+=4);let x=d+l;for(let l=0;l<S;l++){if(g?(m=kh(s,T),T+=4):m=h,v?(y=kh(s,T),T+=4):y=p,b&&(T+=4),w&&(E=0===o?kh(s,T):Rh(s,T),T+=4),t.type===fh){let t=0;for(;t<y;){const s=kh(n,x);if(x+=4,zh(a,n[x])){jh(n.subarray(x,x+s),a?2:1,e+E/i,r)}x+=s,t+=s+4}}e+=m/i}}))})})}),r}function Uh(e){if(!e)return!1;const t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function zh(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6===(31&t)}function jh(e,t,r,n){const i=Gh(e);let s=0;s+=t;let a=0,o=0,l=0;for(;s<i.length;){a=0;do{if(s>=i.length)break;l=i[s++],a+=l}while(255===l);o=0;do{if(s>=i.length)break;l=i[s++],o+=l}while(255===l);const e=i.length-s;let t=s;if(o<e)s+=o;else if(o>e){Xd.error(`Malformed SEI payload. ${o} is too small, only ${e} bytes left to parse.`);break}if(4===a){if(181===i[t++]){const e=xh(i,t);if(t+=2,49===e){const e=kh(i,t);if(t+=4,1195456820===e){const e=i[t++];if(3===e){const s=i[t++],o=64&s,l=o?2+3*(31&s):0,u=new Uint8Array(l);if(o){u[0]=s;for(let e=1;e<l;e++)u[e]=i[t++]}n.push({type:e,payloadType:a,pts:r,bytes:u})}}}}}else if(5===a&&o>16){const e=[];for(let r=0;r<16;r++){const n=i[t++].toString(16);e.push(1==n.length?"0"+n:n),3!==r&&5!==r&&7!==r&&9!==r||e.push("-")}const s=o-16,l=new Uint8Array(s);for(let e=0;e<s;e++)l[e]=i[t++];n.push({payloadType:a,pts:r,uuid:e.join(""),userData:Jd(l),userDataBytes:l})}}}function Gh(e){const t=e.byteLength,r=[];let n=1;for(;n<t-2;)0===e[n]&&0===e[n+1]&&3===e[n+2]?(r.push(n+2),n+=2):n++;if(0===r.length)return e;const i=t-r.length,s=new Uint8Array(i);let a=0;for(n=0;n<i;a++,n++)a===r[0]&&(a++,r.shift()),s[n]=e[a];return s}function Hh(e,t,r){if(16!==e.byteLength)throw new RangeError("Invalid system id");let n,i,s;n=0,i=new Uint8Array,s=new Uint8Array;const a=new Uint8Array(4);return r.byteLength>0&&new DataView(a.buffer).setUint32(0,r.byteLength,!1),function(e,...t){const r=t.length;let n=8,i=r;for(;i--;)n+=t[i].byteLength;const s=new Uint8Array(n);for(s[0]=n>>24&255,s[1]=n>>16&255,s[2]=n>>8&255,s[3]=255&n,s.set(e,4),i=0,n=8;i<r;i++)s.set(t[i],n),n+=t[i].byteLength;return s}([112,115,115,104],new Uint8Array([0,0,0,0]),e,s,i,a,r)}function Vh(e){const t=e.getUint32(0),r=e.byteOffset,n=e.byteLength;if(n<t)return{offset:r,size:n};if(1886614376!==e.getUint32(4))return{offset:r,size:t};const i=e.getUint32(8)>>>24;if(0!==i&&1!==i)return{offset:r,size:t};const s=e.buffer,a=eh(new Uint8Array(s,r+12,16));let o=null,l=null,u=0;if(0===i)u=28;else{const i=e.getUint32(28);if(!i||n<32+16*i)return{offset:r,size:t};o=[];for(let e=0;e<i;e++)o.push(new Uint8Array(s,r+32+16*e,16));u=32+16*i}if(!u)return{offset:r,size:t};const c=e.getUint32(u);return t-32<c?{offset:r,size:t}:(l=new Uint8Array(s,r+u+4,c),{version:i,systemId:a,kids:o,data:l,offset:r,size:t})}const Wh=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Kh={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 Yh(e,t){const r=Kh[t];return!!r&&!!r[e.slice(0,4)]}function qh(e,t,r=!0){return!e.split(",").some(e=>!Xh(e,t,r))}function Xh(e,t,r=!0){var n;const i=Qd(r);return null!=(n=null==i?void 0:i.isTypeSupported(Qh(e,t)))&&n}function Qh(e,t){return`${t}/mp4;codecs=${e}`}function Zh(e){if(e){const t=e.substring(0,4);return Kh.video[t]}return 2}function Jh(e){const t=Wh();return e.split(",").reduce((e,r)=>{const n=t&&Uh(r)?9:Kh.video[r];return n?(2*n+e)/(e?3:2):(Kh.audio[r]+e)/(e?2:1)},0)}const ef={};const tf=/flac|opus|mp4a\.40\.34/i;function rf(e,t=!0){return e.replace(tf,e=>function(e,t=!0){if(ef[e])return ef[e];const r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let i=0;i<r.length;i++){var n;if(Xh(r[i],"audio",t))return ef[e]=r[i],r[i];if("mp3"===r[i]&&null!=(n=Qd(t))&&n.isTypeSupported("audio/mpeg"))return""}return e}(e.toLowerCase(),t))}function nf(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(sf(e,"audio")||sf(e,"video")))return e;if(t){const r=t.split(",");if(r.length>1){if(e)for(let t=r.length;t--;)if(r[t].substring(0,4)===e.substring(0,4))return r[t];return r[0]}}return t||e}function sf(e,t){return Yh(e,t)&&Xh(e,t)}function af(e){if(e.startsWith("av01.")){const t=e.split("."),r=["0","111","01","01","01","0"];for(let e=t.length;e>4&&e<10;e++)t[e]=r[e-4];return t.join(".")}return e}function of(e){const t=Qd(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function lf(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const uf={supported:!1,smooth:!1,powerEfficient:!1},cf={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function df(e,t){return{supported:!1,configurations:t,decodingInfoResults:[uf],error:e}}function hf(e,t,r,n,i,s){const a=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=null==s?void 0:s.audioCodec,u=null==s?void 0:s.channels,c=u?parseInt(u):l?1/0:2;let d=null;if(null!=o&&o.length)try{d=1===o.length&&o[0]?t.groups[o[0]].channels:o.reduce((e,r)=>{if(r){const n=t.groups[r];if(!n)throw new Error(`Audio track group ${r} not found`);Object.keys(n.channels).forEach(t=>{e[t]=(e[t]||0)+n.channels[t]})}return e},{2:0})}catch(e){return!0}return void 0!==a&&(a.split(",").some(e=>Uh(e))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(n,30)||"SDR"!==e.videoRange&&e.videoRange!==r||e.bitrate>Math.max(i,8e6))||!!d&&kd(c)&&Object.keys(d).some(e=>parseInt(e)>c)}function ff(e,t,r,n={}){const i=e.videoCodec;if(!i&&!e.audioCodec||!r)return Promise.resolve(cf);const s=[],a=function(e){var t;const r=null==(t=e.videoCodec)?void 0:t.split(","),n=gf(e),i=e.width||640,s=e.height||480,a=e.frameRate||30,o=e.videoRange.toLowerCase();return r?r.map(e=>{const t={contentType:Qh(af(e),"video"),width:i,height:s,bitrate:n,framerate:a};return"sdr"!==o&&(t.transferFunction=o),t}):[]}(e),o=a.length,l=function(e,t,r){var n;const i=null==(n=e.audioCodec)?void 0:n.split(","),s=gf(e);if(i&&e.audioGroups)return e.audioGroups.reduce((e,n)=>{var a;const o=n?null==(a=t.groups[n])?void 0:a.tracks:null;return o?o.reduce((e,t)=>{if(t.groupId===n){const n=parseFloat(t.channels||"");i.forEach(t=>{const i={contentType:Qh(t,"audio"),bitrate:r?pf(t,s):s};n&&(i.channels=""+n),e.push(i)})}return e},e):e},[]);return[]}(e,t,o>0),u=l.length;for(let e=o||1*u||1;e--;){const t={type:"media-source"};if(o&&(t.video=a[e%o]),u){t.audio=l[e%u];const r=t.audio.bitrate;t.video&&r&&(t.video.bitrate-=r)}s.push(t)}if(i){const e=navigator.userAgent;if(i.split(",").some(e=>Uh(e))&&Wh())return Promise.resolve(df(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${e})`),s))}return Promise.all(s.map(e=>{const t=function(e){let t="";const{audio:r,video:n}=e;if(n){t+=`${lf(n.contentType)}_r${n.height}x${n.width}f${Math.ceil(n.framerate)}${n.transferFunction||"sd"}_${Math.ceil(n.bitrate/1e5)}`}if(r){t+=`${n?"_":""}${lf(r.contentType)}_c${r.channels}`}return t}(e);return n[t]||(n[t]=r.decodingInfo(e))})).then(e=>({supported:!e.some(e=>!e.supported),configurations:s,decodingInfoResults:e})).catch(e=>({supported:!1,configurations:s,decodingInfoResults:[],error:e}))}function pf(e,t){if(t<=1)return 1;let r=128e3;return"ec-3"===e?r=768e3:"ac-3"===e&&(r=64e4),Math.min(t/2,r)}function gf(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}const mf=["NONE","TYPE-0","TYPE-1",null];const vf=["SDR","PQ","HLG"];var yf="",bf="YES",wf="v2";function Ef(e){const{canSkipUntil:t,canSkipDateRanges:r,age:n}=e;return t&&n<t/2?r?wf:bf:yf}class Sf{constructor(e,t,r){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=r}addDirectives(e){const t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class Tf{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(e=>!!e).map(e=>e.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const r=null==(t=e.supplemental)?void 0:t.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 xf(this._audioGroups,e)}hasSubtitleGroup(e){return xf(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t)if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.push(t)}}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 null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function xf(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function kf(e,t){let r=!1,n=[];if(e&&(r="SDR"!==e,n=[e]),t){n=t.allowedVideoRanges||vf.slice(0);const e="SDR"!==n.join("")&&!t.videoCodec;r=void 0!==t.preferHDR?t.preferHDR:e&&function(){if("function"==typeof matchMedia){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}(),r||(n=["SDR"])}return{preferHDR:r,allowedVideoRanges:n}}const Af=(e,t)=>JSON.stringify(e,(e=>{const t=new WeakSet;return(r,n)=>{if(e&&(n=e(r,n)),"object"==typeof n&&null!==n){if(t.has(n))return;t.add(n)}return n}})(t));function Rf(e,t){Xd.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function Lf(e){return e.reduce((e,t)=>{let r=e.groups[t.groupId];r||(r=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(t);const n=t.channels||"2";return r.channels[n]=(r.channels[n]||0)+1,r.hasDefault=r.hasDefault||t.default,r.hasAutoSelect=r.hasAutoSelect||t.autoselect,r.hasDefault&&(e.hasDefaultAudio=!0),r.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function If(e){if(!e)return e;const{lang:t,assocLang:r,characteristics:n,channels:i,audioCodec:s}=e;return{lang:t,assocLang:r,characteristics:n,channels:i,audioCodec:s}}function Cf(e,t,r){if("attrs"in e){const r=t.indexOf(e);if(-1!==r)return r}for(let n=0;n<t.length;n++){if(Pf(e,t[n],r))return n}return-1}function Pf(e,t,r){const{groupId:n,name:i,lang:s,assocLang:a,default:o}=e,l=e.forced;return(void 0===n||t.groupId===n)&&(void 0===i||t.name===i)&&(void 0===s||function(e,t="--"){if(e.length===t.length)return e===t;return e.startsWith(t)||t.startsWith(e)}(s,t.lang))&&(void 0===s||t.assocLang===a)&&(void 0===o||t.default===o)&&(void 0===l||t.forced===l)&&(!("characteristics"in e)||function(e,t=""){const r=e.split(","),n=t.split(",");return r.length===n.length&&!r.some(e=>-1===n.indexOf(e))}(e.characteristics||"",t.characteristics))&&(void 0===r||r(e,t))}function Df(e,t){const{audioCodec:r,channels:n}=e;return!(void 0!==r&&(t.audioCodec||"").substring(0,4)!==r.substring(0,4)||void 0!==n&&n!==(t.channels||"2"))}function _f(e,t,r){for(let n=t;n>-1;n--)if(r(e[n]))return n;for(let n=t+1;n<e.length;n++)if(r(e[n]))return n;return-1}function Mf(e,t){var r;return!!e&&e!==(null==(r=t.loadLevelObj)?void 0:r.uri)}const Of=function(e,t){let r=0,n=e.length-1,i=null,s=null;for(;r<=n;){i=(r+n)/2|0,s=e[i];const a=t(s);if(a>0)r=i+1;else{if(!(a<0))return s;n=i-1}}return null};function Nf(e,t,r=0,n=0,i=.005){let s=null;if(e){s=t[1+e.sn-t[0].sn]||null;const n=e.endDTS-r;n>0&&n<15e-7&&(r+=15e-7),s&&e.level!==s.level&&s.end<=e.end&&(s=t[2+e.sn-t[0].sn]||null)}else 0===r&&0===t[0].start&&(s=t[0]);if(s&&((!e||e.level===s.level)&&0===Ff(r,n,s)||function(e,t,r){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){const n=t.tagList.reduce((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e),r);return e.start<=n}return!1}(s,e,Math.min(i,n))))return s;const a=Of(t,Ff.bind(null,r,n));return!a||a===e&&s?s:a}function Ff(e=0,t=0,r){if(r.start<=e&&r.start+r.duration>e)return 0;const n=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-n<=e?1:r.start-n>e&&r.start?-1:0}function $f(e,t,r){const n=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-n>e}function Bf(e,t,r){if(e&&e.startCC<=t&&e.endCC>=t){let n=e.fragments;const{fragmentHint:i}=e;let s;return i&&(n=n.concat(i)),Of(n,e=>e.cc<t?1:e.cc>t?-1:(s=e,e.end<=r?1:e.start>r?-1:0)),s||null}return null}function Uf(e){switch(e.details){case Id.FRAG_LOAD_TIMEOUT:case Id.KEY_LOAD_TIMEOUT:case Id.LEVEL_LOAD_TIMEOUT:case Id.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function zf(e){return e.details.startsWith("key")}function jf(e){return zf(e)&&!!e.frag&&!e.frag.decryptdata}function Gf(e,t){const r=Uf(t);return e.default[(r?"timeout":"error")+"Retry"]}function Hf(e,t){const r="linear"===e.backoff?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}function Vf(e){return Gd(Gd({},e),{errorRetry:null,timeoutRetry:null})}function Wf(e,t,r,n){if(!e)return!1;const i=null==n?void 0:n.code,s=t<e.maxNumRetry&&(function(e){return Kf(e)||!!e&&(e<400||e>499)}(i)||!!r);return e.shouldRetry?e.shouldRetry(e,t,r,n,s):s}function Kf(e){return 0===e&&!1===navigator.onLine}var Yf=0,qf=2,Xf=3,Qf=5,Zf=0,Jf=1,ep=2,tp=4;function rp(e){const t={action:Yf,flags:Zf};return e&&(t.resolved=!0),t}var np="NOT_LOADED",ip="APPENDING",sp="PARTIAL",ap="OK";class op{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(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Cd.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Cd.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Cd.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Cd.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Cd.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Cd.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const r=this.activePartLists[t];if(r)for(let t=r.length;t--;){const n=r[t];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,r){const{fragments:n}=this,i=Object.keys(n);for(let s=i.length;s--;){const a=n[i[s]];if((null==a?void 0:a.body.type)===t&&(!r||a.buffered)){const t=a.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,r,n,i){this.timeRanges&&(this.timeRanges[e]=t);const s=(null==n?void 0:n.fragment.sn)||-1;Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;if(s>=a.body.sn)return;if(!a.buffered&&(!a.loaded||i))return void(a.body.type===r&&this.removeFragment(a.body));const o=a.range[e];o&&(0!==o.time.length?o.time.some(e=>{const r=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return r&&this.removeFragment(a.body),r}):this.removeFragment(a.body))})}detectPartialFragments(e){const t=this.timeRanges;if(!t||"initSegment"===e.frag.sn)return;const r=e.frag,n=up(r),i=this.fragments[n];if(!i||i.buffered&&r.gap)return;const s=!r.relurl;Object.keys(t).forEach(n=>{const a=r.elementaryStreams[n];if(!a)return;const o=t[n],l=s||!0===a.partial;i.range[n]=this.getBufferedTimes(r,e.part,l,o)}),i.loaded=null,Object.keys(i.range).length?(this.bufferedEnd(i,r),lp(i)||this.removeParts(r.sn-1,r.type)):this.removeFragment(i.body)}bufferedEnd(e,t){e.buffered=!0;(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const r=this.activePartLists[t];r&&(this.activePartLists[t]=cp(r,t=>t.fragment.sn>=e))}fragBuffered(e,t){const r=up(e);let n=this.fragments[r];!n&&t&&(n=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),n&&(n.loaded=null,this.bufferedEnd(n,e))}getBufferedTimes(e,t,r,n){const i={time:[],partial:r},s=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||s;for(let e=0;e<n.length;e++){const t=n.start(e)-this.bufferPadding,r=n.end(e)+this.bufferPadding;if(l>=t&&o<=r){i.time.push({startPTS:Math.max(s,n.start(e)),endPTS:Math.min(a,n.end(e))});break}if(s<r&&a>t){const t=Math.max(s,n.start(e)),r=Math.min(a,n.end(e));r>t&&(i.partial=!0,i.time.push({startPTS:t,endPTS:r}))}else if(a<=t)break}return i}getPartialFragment(e){let t,r,n,i=null,s=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const u=o[l];u&&lp(u)&&(r=u.body.start-a,n=u.body.end+a,e>=r&&e<=n&&(t=Math.min(e-r,n-e),s<=t&&(i=u.body,s=t)))}),i}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||lp(t))}getState(e){const t=up(e),r=this.fragments[t];return r?r.buffered?lp(r)?sp:ap:ip:np}isTimeBuffered(e,t,r){let n,i;for(let s=0;s<r.length;s++){if(n=r.start(s)-this.bufferPadding,i=r.end(s)+this.bufferPadding,e>=n&&t<=i)return!0;if(t<=n)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if("initSegment"===t.frag.sn||t.frag.bitrateTest)return;const r=t.frag,n=t.part?null:t,i=up(r);this.fragments[i]={body:r,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:r,part:n,timeRanges:i,type:s}=t;if("initSegment"===r.sn)return;const a=r.type;if(n){let e=this.activePartLists[a];e||(this.activePartLists[a]=e=[]),e.push(n)}this.timeRanges=i;const o=i[s];this.detectEvictedFragments(s,o,a,n)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=up(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,r=Object.keys(t);if(!e)return r.length>0;for(let n=r.length;n--;){const i=t[r[n]];if((null==i?void 0:i.body.type)===e)return!0}return!1}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,r,n,i){n&&!this.hasGaps||Object.keys(this.fragments).forEach(s=>{const a=this.fragments[s];if(!a)return;const o=a.body;o.type!==r||n&&!o.gap||o.start<t&&o.end>e&&(a.buffered||i)&&this.removeFragment(o)})}removeFragment(e){const t=up(e);e.clearElementaryStreamInfo();const r=this.activePartLists[e.type];if(r){const t=e.sn;this.activePartLists[e.type]=cp(r,e=>e.fragment.sn!==t)}delete this.fragments[t],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 t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach(e=>e.clearElementaryStreamInfo())}}function lp(e){var t,r,n;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(r=e.range.audio)&&r.partial||null!=(n=e.range.audiovideo)&&n.partial)}function up(e){return`${e.type}_${e.level}_${e.sn}`}function cp(e,t){return e.filter(e=>{const r=t(e);return r||e.clearElementaryStreamInfo(),r})}var dp=0,hp=1;class fp{constructor(e,t,r){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=r}decrypt(e,t){switch(this.aesMode){case dp:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case hp:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class pp{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 t=new DataView(e),r=new Uint32Array(4);for(let e=0;e<4;e++)r[e]=t.getUint32(4*e);return r}initTable(){const e=this.sBox,t=this.invSBox,r=this.subMix,n=r[0],i=r[1],s=r[2],a=r[3],o=this.invSubMix,l=o[0],u=o[1],c=o[2],d=o[3],h=new Uint32Array(256);let f=0,p=0,g=0;for(g=0;g<256;g++)h[g]=g<128?g<<1:g<<1^283;for(g=0;g<256;g++){let r=p^p<<1^p<<2^p<<3^p<<4;r=r>>>8^255&r^99,e[f]=r,t[r]=f;const o=h[f],g=h[o],m=h[g];let v=257*h[r]^16843008*r;n[f]=v<<24|v>>>8,i[f]=v<<16|v>>>16,s[f]=v<<8|v>>>24,a[f]=v,v=16843009*m^65537*g^257*o^16843008*f,l[r]=v<<24|v>>>8,u[r]=v<<16|v>>>16,c[r]=v<<8|v>>>24,d[r]=v,f?(f=o^h[h[h[m^o]]],p^=h[h[p]]):f=p=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let r=!0,n=0;for(;n<t.length&&r;)r=t[n]===this.key[n],n++;if(r)return;this.key=t;const i=this.keySize=t.length;if(4!==i&&6!==i&&8!==i)throw new Error("Invalid aes key size="+i);const s=this.ksRows=4*(i+6+1);let a,o;const l=this.keySchedule=new Uint32Array(s),u=this.invKeySchedule=new Uint32Array(s),c=this.sBox,d=this.rcon,h=this.invSubMix,f=h[0],p=h[1],g=h[2],m=h[3];let v,y;for(a=0;a<s;a++)a<i?v=l[a]=t[a]:(y=v,a%i===0?(y=y<<8|y>>>24,y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[255&y],y^=d[a/i|0]<<24):i>6&&a%i===4&&(y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[255&y]),l[a]=v=(l[a-i]^y)>>>0);for(o=0;o<s;o++)a=s-o,y=3&o?l[a]:l[a-4],u[o]=o<4||a<=4?y:f[c[y>>>24]]^p[c[y>>>16&255]]^g[c[y>>>8&255]]^m[c[255&y]],u[o]=u[o]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,r){const n=this.keySize+6,i=this.invKeySchedule,s=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],u=a[2],c=a[3],d=this.uint8ArrayToUint32Array_(r);let h=d[0],f=d[1],p=d[2],g=d[3];const m=new Int32Array(e),v=new Int32Array(m.length);let y,b,w,E,S,T,x,k,A,R,L,I,C,P;const D=this.networkToHostOrderSwap;for(;t<m.length;){for(A=D(m[t]),R=D(m[t+1]),L=D(m[t+2]),I=D(m[t+3]),S=A^i[0],T=I^i[1],x=L^i[2],k=R^i[3],C=4,P=1;P<n;P++)y=o[S>>>24]^l[T>>16&255]^u[x>>8&255]^c[255&k]^i[C],b=o[T>>>24]^l[x>>16&255]^u[k>>8&255]^c[255&S]^i[C+1],w=o[x>>>24]^l[k>>16&255]^u[S>>8&255]^c[255&T]^i[C+2],E=o[k>>>24]^l[S>>16&255]^u[T>>8&255]^c[255&x]^i[C+3],S=y,T=b,x=w,k=E,C+=4;y=s[S>>>24]<<24^s[T>>16&255]<<16^s[x>>8&255]<<8^s[255&k]^i[C],b=s[T>>>24]<<24^s[x>>16&255]<<16^s[k>>8&255]<<8^s[255&S]^i[C+1],w=s[x>>>24]<<24^s[k>>16&255]<<16^s[S>>8&255]<<8^s[255&T]^i[C+2],E=s[k>>>24]<<24^s[S>>16&255]<<16^s[T>>8&255]<<8^s[255&x]^i[C+3],v[t]=D(y^h),v[t+1]=D(E^f),v[t+2]=D(w^p),v[t+3]=D(b^g),h=A,f=R,p=L,g=I,t+=4}return v.buffer}}class gp{constructor(e,t,r){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=r}expandKey(){const e=function(e){switch(e){case dp:return"AES-CBC";case hp:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${e}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}class mp{constructor(e,{removePKCS7Padding:t=!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=t,t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(e){}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:t}=this;if(!e||t)return this.reset(),null;const r=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?function(e){const t=e.byteLength,r=t&&new DataView(e.buffer).getUint8(t-1);return r?e.slice(0,t-r):e}(r):r}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,r,n){return this.useSoftware?new Promise((i,s)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,r,n);const o=this.flush();o?i(o.buffer):s(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,r,n)}softwareDecrypt(e,t,r,n){const{currentIV:i,currentResult:s,remainderData:a}=this;if(n!==dp||16!==t.byteLength)return Xd.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=$h(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;i&&(r=i);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new pp),l.expandKey(t);const u=s;return this.currentResult=l.decrypt(o.buffer,0,r),this.currentIV=o.slice(-16).buffer,u||null}webCryptoDecrypt(e,t,r,n){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,r,n));this.key=t,this.fastAesKey=new gp(this.subtle,t,n)}return this.fastAesKey.expandKey().then(t=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new fp(this.subtle,new Uint8Array(r),n).decrypt(e.buffer,t)}).catch(i=>(Xd.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(e,t,r,n)))}onWebCryptoError(e,t,r,n){const i=this.enableSoftwareAES;if(i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,r,n);const i=this.flush();if(i)return i.buffer}throw new Error("WebCrypto"+(i?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const r=e.length-e.length%16;return r!==e.length&&(t=e.slice(0,r),this.remainderData=e.slice(r)),t}logOnce(e){this.logEnabled&&(Xd.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const vp=Math.pow(2,17);class yp{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,t){const r=e.url;if(!r)return Promise.reject(new Ep({type:Ld.NETWORK_ERROR,details:Id.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(r?"part list":"url")),networkDetails:null}));this.abort();const n=this.config,i=n.fLoader,s=n.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some(e=>"GAP"===e[0]))return void o(wp(e));e.gap=!1}const l=this.loader=i?new i(n):new s(n),u=bp(e);e.loader=l;const c=Vf(n.fragLoadPolicy.default),d={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:vp};e.stats=l.stats;const h={onSuccess:(t,r,n,i)=>{this.resetLoader(e,l);let s=t.data;n.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(s.slice(0,16)),s=s.slice(16)),a({frag:e,part:null,payload:s,networkDetails:i})},onError:(t,n,i,s)=>{this.resetLoader(e,l),o(new Ep({type:Ld.NETWORK_ERROR,details:Id.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Gd({url:r,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:i,stats:s}))},onAbort:(t,r,n)=>{this.resetLoader(e,l),o(new Ep({type:Ld.NETWORK_ERROR,details:Id.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:n,stats:t}))},onTimeout:(t,r,n)=>{this.resetLoader(e,l),o(new Ep({type:Ld.NETWORK_ERROR,details:Id.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:n,stats:t}))}};t&&(h.onProgress=(r,n,i,s)=>t({frag:e,part:null,payload:i,networkDetails:s})),l.load(u,d,h)})}loadPart(e,t,r){this.abort();const n=this.config,i=n.fLoader,s=n.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o(wp(e,t));const l=this.loader=i?new i(n):new s(n),u=bp(e,t);e.loader=l;const c=Vf(n.fragLoadPolicy.default),d={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:vp};t.stats=l.stats,l.load(u,d,{onSuccess:(n,i,s,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const u={frag:e,part:t,payload:n.data,networkDetails:o};r(u),a(u)},onError:(r,n,i,s)=>{this.resetLoader(e,l),o(new Ep({type:Ld.NETWORK_ERROR,details:Id.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Gd({url:u.url,data:void 0},r),error:new Error(`HTTP Error ${r.code} ${r.text}`),networkDetails:i,stats:s}))},onAbort:(r,n,i)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new Ep({type:Ld.NETWORK_ERROR,details:Id.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:i,stats:r}))},onTimeout:(r,n,i)=>{this.resetLoader(e,l),o(new Ep({type:Ld.NETWORK_ERROR,details:Id.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:i,stats:r}))}})})}updateStatsFromPart(e,t){const r=e.stats,n=t.stats,i=n.total;if(r.loaded+=n.loaded,i){const n=Math.round(e.duration/t.duration),s=Math.min(Math.round(r.loaded/i),n),a=(n-s)*Math.round(r.loaded/s);r.total=r.loaded+a}else r.total=Math.max(r.loaded,r.total);const s=r.loading,a=n.loading;s.start?s.first+=a.first-a.start:(s.start=a.start,s.first=a.first),s.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function bp(e,t=null){const r=t||e,n={frag:e,part:t,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},i=r.byteRangeStartOffset,s=r.byteRangeEndOffset;if(kd(i)&&kd(s)){var a;let t=i,r=s;if("initSegment"===e.sn&&("AES-128"===(o=null==(a=e.decryptdata)?void 0:a.method)||"AES-256"===o)){const e=s-i;e%16&&(r=s+(16-e%16)),0!==i&&(n.resetIV=!0,t=i-16)}n.rangeStart=t,n.rangeEnd=r}var o;return n}function wp(e,t){const r=new Error(`GAP ${e.gap?"tag":"attribute"} found`),n={type:Ld.MEDIA_ERROR,details:Id.FRAG_GAP,fatal:!1,frag:e,error:r,networkDetails:null};return t&&(n.part=t),(t||e).stats.aborted=!0,new Ep(n)}class Ep extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Sp extends Hd{constructor(e,t){super(e,t),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&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Tp{constructor(e,t,r,n=0,i=-1,s=!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={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=r,this.size=n,this.part=i,this.partial=s}}const xp={length:0,start:()=>0,end:()=>0};class kp{static isBuffered(e,t){if(e){const r=kp.getBuffered(e);for(let e=r.length;e--;)if(t>=r.start(e)&&t<=r.end(e))return!0}return!1}static bufferedRanges(e){if(e){const t=kp.getBuffered(e);return kp.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let r=0;r<e.length;r++)t.push({start:e.start(r),end:e.end(r)});return t}static bufferInfo(e,t,r){if(e){const n=kp.bufferedRanges(e);if(n.length)return kp.bufferedInfo(n,t,r)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,r){t=Math.max(0,t),e.length>1&&e.sort((e,t)=>e.start-t.start||t.end-e.end);let n=-1,i=[];if(r)for(let s=0;s<e.length;s++){t>=e[s].start&&t<=e[s].end&&(n=s);const a=i.length;if(a){const t=i[a-1].end;e[s].start-t<r?e[s].end>t&&(i[a-1].end=e[s].end):i.push(e[s])}else i.push(e[s])}else i=e;let s,a=0,o=t,l=t;for(let e=0;e<i.length;e++){const u=i[e].start,c=i[e].end;if(-1===n&&t>=u&&t<=c&&(n=e),t+r>=u&&t<c)o=u,l=c,a=l-t;else if(t+r<u){s=u;break}}return{len:a,start:o||0,end:l||0,nextStart:s,buffered:e,bufferedIndex:n}}static getBuffered(e){try{return e.buffered||xp}catch(e){return Xd.log("failed to get media.buffered",e),xp}}}const Ap=/\{\$([a-zA-Z0-9-_]+)\}/g;function Rp(e){return Ap.test(e)}function Lp(e,t){if(null!==e.variableList||e.hasVariableRefs){const r=e.variableList;return t.replace(Ap,t=>{const n=t.substring(2,t.length-1),i=null==r?void 0:r[n];return void 0===i?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${n}"`)),t):i})}return t}function Ip(e,t,r){let n,i,s=e.variableList;if(s||(e.variableList=s={}),"QUERYPARAM"in t){n=t.QUERYPARAM;try{const e=new self.URL(r).searchParams;if(!e.has(n))throw new Error(`"${n}" does not match any query parameter in URI: "${r}"`);i=e.get(n)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else n=t.NAME,i=t.VALUE;n in s?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${n}"`)):s[n]=i||""}function Cp(e,t,r){const n=t.IMPORT;if(r&&n in r){let t=e.variableList;t||(e.variableList=t={}),t[n]=r[n]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${n}"`))}const Pp=/^(\d+)x(\d+)$/,Dp=/(.+?)=(".*?"|.*?)(?:,|$)/g;class _p{constructor(e,t){"string"==typeof e&&(e=_p.parseAttrList(e,t)),zd(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>"X-"===e.substring(0,2))}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const r=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)r[e]=parseInt(t.slice(2*e,2*e+2),16);return r}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const r=this[e];return r?parseFloat(r):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const r=this[e];return(r?r.split(/[ ,]+/):[]).reduce((e,t)=>(e[t.toLowerCase()]=!0,e),t)}bool(e){return"YES"===this[e]}decimalResolution(e){const t=Pp.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let r;const n={};for(Dp.lastIndex=0;null!==(r=Dp.exec(e));){const i=r[1].trim();let s=r[2];const a=0===s.indexOf('"')&&s.lastIndexOf('"')===s.length-1;let o=!1;if(a)s=s.slice(1,-1);else switch(i){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(a||o))s=Lp(t,s);else if(!o&&!a)switch(i){case"CLOSED-CAPTIONS":if("NONE"===s)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":Xd.warn(`${e}: attribute ${i} is missing quotes`)}n[i]=s}return n}}function Mp(e){return"ID"!==e&&"CLASS"!==e&&"CUE"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function Op(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}class Np{constructor(e,t,r=0){var n;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=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(n=null==t?void 0:t.tagOrder)?n:r,t){const r=t.attr;for(const t in r)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==r[t]){Xd.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=zd(new _p({}),r,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=(null==t?void 0:t.endDate)||new Date(this.attr["END-DATE"]);kd(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return void 0===e?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 null===e||null===e.programDateTime?(Xd.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 t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(kd(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"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&kd(this.startDate.getTime())&&(null===this.duration||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)}}class Fp{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)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let r=t.decryptdata;return r||(t.setKeyFormat(e.keyFormat),r=t.decryptdata),!!r&&e.matches(r)})}get hasProgramDateTime(){return!!this.fragments.length&&kd(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;if(e>0){return 1e3*(this.driftEnd-this.driftStart)/e}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&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 null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(-1!==t){for(let r=e.length;r--;)if(e[r].index>t)return e[r].index;return t}}return 0}get lastPartSn(){var e;return null!=(e=this.partList)&&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 $p(e,t){return e.length===t.length&&!e.some((e,r)=>e!==t[r])}function Bp(e,t){return!e&&!t||!(!e||!t)&&$p(e,t)}function Up(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function zp(e){switch(e){case"AES-128":case"AES-256":return dp;case"AES-256-CTR":return hp;default:throw new Error(`invalid full segment method ${e}`)}}function jp(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function Gp(e){return Uint8Array.from(unescape(encodeURIComponent(e)),e=>e.charCodeAt(0))}function Hp(e){const t=function(e,t,r){const n=e[t];e[t]=e[r],e[r]=n};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function Vp(e){const t=e.split(":");let r=null;if("data"===t[0]&&2===t.length){const e=t[1].split(";"),n=e[e.length-1].split(",");if(2===n.length){const t="base64"===n[0],i=n[1];t?(e.splice(-1,1),r=jp(i)):r=function(e){const t=Gp(e).subarray(0,16),r=new Uint8Array(16);return r.set(t,16-t.length),r}(i)}}return r}const Wp="undefined"!=typeof self?self:void 0;var Kp={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Yp="org.w3.clearkey",qp="com.apple.streamingkeydelivery",Xp="com.microsoft.playready",Qp="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Zp(e){switch(e){case qp:return Kp.FAIRPLAY;case Xp:return Kp.PLAYREADY;case Qp:return Kp.WIDEVINE;case Yp:return Kp.CLEARKEY}}function Jp(e){switch(e){case Kp.FAIRPLAY:return qp;case Kp.PLAYREADY:return Xp;case Kp.WIDEVINE:return Qp;case Kp.CLEARKEY:return Yp}}function eg(e){const{drmSystems:t,widevineLicenseUrl:r}=e,n=t?[Kp.FAIRPLAY,Kp.WIDEVINE,Kp.PLAYREADY,Kp.CLEARKEY].filter(e=>!!t[e]):[];return!n[Kp.WIDEVINE]&&r&&n.push(Kp.WIDEVINE),n}const tg=null!=Wp&&null!=(rg=Wp.navigator)&&rg.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var rg;function ng(e){const t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),r=String.fromCharCode.apply(null,Array.from(t)),n=r.substring(r.indexOf("<"),r.length),i=(new DOMParser).parseFromString(n,"text/xml").getElementsByTagName("KID")[0];if(i){const e=i.childNodes[0]?i.childNodes[0].nodeValue:i.getAttribute("VALUE");if(e){const t=jp(e).subarray(0,16);return Hp(t),t}}return null}let ig={};class sg{static clearKeyUriToKeyIdMap(){ig={}}static setKeyIdForUri(e,t){ig[e]=t}static addKeyIdForUri(e){const t=Object.keys(ig).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,t),ig[e]=r,r}constructor(e,t,r,n=[1],i=null,s){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=t,this.keyFormat=r,this.keyFormatVersions=n,this.iv=i,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!Up(e),null!=s&&s.startsWith("0x")&&(this.keyId=new Uint8Array(th(s)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&$p(e.keyFormatVersions,this.keyFormatVersions)&&Bp(e.iv,this.iv)&&Bp(e.keyId,this.keyId)}isSupported(){if(this.method){if(Up(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case qp:case Qp:case Xp:case Yp:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(Up(this.method)){let t=this.iv;t||("number"!=typeof e&&(Xd.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),t=function(e){const t=new Uint8Array(16);for(let r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}(e));return new sg(this.method,this.uri,"identity",this.keyFormatVersions,t)}if(this.keyId){const e=ig[this.uri];if(e&&!$p(this.keyId,e)&&sg.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const r=Vp(this.uri);if(r)switch(this.keyFormat){case Qp:if(this.pssh=r,!this.keyId){const e=function(e){const t=[];if(e instanceof ArrayBuffer){const r=e.byteLength;let n=0;for(;n+32<r;){const r=Vh(new DataView(e,n));t.push(r),n+=r.size}}return t}(r.buffer);if(e.length){var n;const t=e[0];this.keyId=null!=(n=t.kids)&&n.length?t.kids[0]:null}}this.keyId||(this.keyId=ag(t));break;case Xp:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Hh(e,0,r),this.keyId=ng(r);break}default:{let e=r.subarray(0,16);if(16!==e.length){const t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||16!==this.keyId.byteLength){let e;e=function(e){const t=null==e?void 0:e[Qp];if(t)return t.keyId;return null}(t),e||(e=ag(t),e||(e=ig[this.uri])),e&&(this.keyId=e,sg.setKeyIdForUri(this.uri,e))}return this}}function ag(e){const t=null==e?void 0:e[Xp];if(t){const e=Vp(t.uri);if(e)return ng(e)}return null}const og=/#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,lg=/#EXT-X-MEDIA:(.*)/g,ug=/^#EXT(?:INF|-X-TARGETDURATION):/m,cg=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),dg=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 hg{static findGroup(e,t){for(let r=0;r<e.length;r++){const n=e[r];if(n.id===t)return n}}static resolve(e,t){return ch.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return ug.test(e)}static parseMasterPlaylist(e,t){const r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Rp(e)},n=[];if(og.lastIndex=0,!e.startsWith("#EXTM3U"))return r.playlistParsingError=new Error("no EXTM3U delimiter"),r;let i;for(;null!=(i=og.exec(e));)if(i[1]){var s;const e=new _p(i[1],r),a=Lp(r,i[2]),o={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:hg.resolve(a,t)},l=e.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),vg(e.CODECS,o);const u=e["SUPPLEMENTAL-CODECS"];u&&(o.supplemental={},vg(u,o.supplemental)),null!=(s=o.unknownCodecs)&&s.length||n.push(o),r.levels.push(o)}else if(i[3]){const e=i[3],n=i[4];switch(e){case"SESSION-DATA":{const e=new _p(n,r),t=e["DATA-ID"];t&&(null===r.sessionData&&(r.sessionData={}),r.sessionData[t]=e);break}case"SESSION-KEY":{const e=gg(n,t,r);e.encrypted&&e.isSupported()?(null===r.sessionKeys&&(r.sessionKeys=[]),r.sessionKeys.push(e)):Xd.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${n}"`);break}case"DEFINE":Ip(r,new _p(n,r),t);break;case"CONTENT-STEERING":{const e=new _p(n,r);r.contentSteering={uri:hg.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":r.startTimeOffset=mg(n)}}const a=n.length>0&&n.length<r.levels.length;return r.levels=a?n:r.levels,0===r.levels.length&&(r.playlistParsingError=new Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(e,t,r){let n;const i={},s=r.levels,a={AUDIO:s.map(e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec})),SUBTITLES:s.map(e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec})),"CLOSED-CAPTIONS":[]};let o=0;for(lg.lastIndex=0;null!==(n=lg.exec(e));){const e=new _p(n[1],r),s=e.TYPE;if(s){const r=a[s],n=i[s]||[];i[s]=n;const l=e.LANGUAGE,u=e["ASSOC-LANGUAGE"],c=e.CHANNELS,d=e.CHARACTERISTICS,h=e["INSTREAM-ID"],f={attrs:e,bitrate:0,id:o++,groupId:e["GROUP-ID"]||"",name:e.NAME||l||"",type:s,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:l,url:e.URI?hg.resolve(e.URI,t):""};if(u&&(f.assocLang=u),c&&(f.channels=c),d&&(f.characteristics=d),h&&(f.instreamId=h),null!=r&&r.length){const e=hg.findGroup(r,f.groupId)||r[0];yg(f,e,"audioCodec"),yg(f,e,"textCodec")}n.push(f)}}return i}static parseLevelPlaylist(e,t,r,n,i,s){var a;const o={url:t},l=new Fp(t),u=l.fragments,c=[];let d,h,f,p,g=null,m=0,v=0,y=0,b=0,w=0,E=null,S=new vh(n,o),T=-1,x=!1,k=null;if(cg.lastIndex=0,l.m3u8=e,l.hasVariableRefs=Rp(e),"#EXTM3U"!==(null==(a=cg.exec(e))?void 0:a[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(d=cg.exec(e));){x&&(x=!1,S=new vh(n,o),S.playlistOffset=y,S.setStart(y),S.sn=m,S.cc=b,w&&(S.bitrate=w),S.level=r,g&&(S.initSegment=g,g.rawProgramDateTime&&(S.rawProgramDateTime=g.rawProgramDateTime,g.rawProgramDateTime=null),k&&(S.setByteRange(k),k=null)));const e=d[1];if(e){S.duration=parseFloat(e);const t=(" "+d[2]).slice(1);S.title=t||null,S.tagList.push(t?["INF",e,t]:["INF",e])}else if(d[3]){if(kd(S.duration)){S.playlistOffset=y,S.setStart(y),f&&Eg(S,f,l),S.sn=m,S.level=r,S.cc=b,u.push(S);const e=(" "+d[3]).slice(1);S.relurl=Lp(l,e),bg(S,E,c),E=S,y+=S.duration,m++,v=0,x=!0}}else{if(d=d[0].match(dg),!d){Xd.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h<d.length&&void 0===d[h];h++);const e=(" "+d[h]).slice(1),i=(" "+d[h+1]).slice(1),a=d[h+2]?(" "+d[h+2]).slice(1):null;switch(e){case"BYTERANGE":E?S.setByteRange(i,E):S.setByteRange(i);break;case"PROGRAM-DATE-TIME":S.rawProgramDateTime=i,S.tagList.push(["PROGRAM-DATE-TIME",i]),-1===T&&(T=u.length);break;case"PLAYLIST-TYPE":l.type&&Sg(l,e,d),l.type=i.toUpperCase();break;case"MEDIA-SEQUENCE":0!==l.startSN?Sg(l,e,d):u.length>0&&Tg(l,e,d),m=l.startSN=parseInt(i);break;case"SKIP":{l.skippedSegments&&Sg(l,e,d);const t=new _p(i,l),r=t.decimalInteger("SKIPPED-SEGMENTS");if(kd(r)){l.skippedSegments+=r;for(let e=r;e--;)u.push(null);m+=r}const n=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");n&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(n.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&Sg(l,e,d),l.targetduration=Math.max(parseInt(i),1);break;case"VERSION":null!==l.version&&Sg(l,e,d),l.version=parseInt(i);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||Sg(l,e,d),l.live=!1;break;case"#":(i||a)&&S.tagList.push(a?[i,a]:[i]);break;case"DISCONTINUITY":b++,S.tagList.push(["DIS"]);break;case"GAP":S.gap=!0,S.tagList.push([e]);break;case"BITRATE":S.tagList.push([e,i]),w=1e3*parseInt(i),kd(w)?S.bitrate=w:w=0;break;case"DATERANGE":{const e=new _p(i,l),t=new Np(e,l.dateRanges[e.ID],l.dateRangeTagCount);l.dateRangeTagCount++,t.isValid||l.skippedSegments?l.dateRanges[t.id]=t:Xd.warn(`Ignoring invalid DATERANGE tag: "${i}"`),S.tagList.push(["EXT-X-DATERANGE",i]);break}case"DEFINE":{const e=new _p(i,l);"IMPORT"in e?Cp(l,e,s):Ip(l,e,t)}break;case"DISCONTINUITY-SEQUENCE":0!==l.startCC?Sg(l,e,d):u.length>0&&Tg(l,e,d),l.startCC=b=parseInt(i);break;case"KEY":{const e=gg(i,t,l);if(e.isSupported()){if("NONE"===e.method){f=void 0;break}f||(f={});const t=f[e.keyFormat];null!=t&&t.matches(e)||(t&&(f=zd({},f)),f[e.keyFormat]=e)}else Xd.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${i}"`);break}case"START":l.startTimeOffset=mg(i);break;case"MAP":{const e=new _p(i,l);if(S.duration){const t=new vh(n,o);wg(t,e,r,f),g=t,S.initSegment=g,g.rawProgramDateTime&&!S.rawProgramDateTime&&(S.rawProgramDateTime=g.rawProgramDateTime)}else{const t=S.byteRangeEndOffset;if(t){const e=S.byteRangeStartOffset;k=`${t-e}@${e}`}else k=null;wg(S,e,r,f),g=S,x=!0}g.cc=b;break}case"SERVER-CONTROL":p&&Sg(l,e,d),p=new _p(i),l.canBlockReload=p.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=p.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&p.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=p.optionalFloat("PART-HOLD-BACK",0),l.holdBack=p.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{l.partTarget&&Sg(l,e,d);const t=new _p(i);l.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=l.partList;e||(e=l.partList=[]);const t=v>0?e[e.length-1]:void 0,r=v++,n=new _p(i,l),s=new yh(n,S,o,r,t);e.push(s),S.duration+=s.duration;break}case"PRELOAD-HINT":{const e=new _p(i,l);l.preloadHint=e;break}case"RENDITION-REPORT":{const e=new _p(i,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(e);break}default:Xd.warn(`line parsed but not handled: ${d}`)}}}E&&!E.relurl?(u.pop(),y-=E.duration,l.partList&&(l.fragmentHint=E)):l.partList&&(bg(S,E,c),S.cc=b,l.fragmentHint=S,f&&Eg(S,f,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const A=u.length,R=u[0],L=u[A-1];if(y+=l.skippedSegments*l.targetduration,y>0&&A&&L){l.averagetargetduration=y/A;const e=L.sn;l.endSN="initSegment"!==e?e:0,l.live||(L.endList=!0),T>0&&(!function(e,t){let r=e[t];for(let n=t;n--;){const t=e[n];if(!t)return;t.programDateTime=r.programDateTime-1e3*t.duration,r=t}}(u,T),R&&c.unshift(R))}return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,c.length&&l.dateRangeTagCount&&R&&fg(c,l),l.endCC=b,l}}function fg(e,t){let r=e.length;if(!r){if(!t.hasProgramDateTime)return;{const n=t.fragments[t.fragments.length-1];e.push(n),r++}}const n=e[r-1],i=t.live?1/0:t.totalduration,s=Object.keys(t.dateRanges);for(let o=s.length;o--;){const l=t.dateRanges[s[o]],u=l.startDate.getTime();l.tagAnchor=n.ref;for(let n=r;n--;){var a;if((null==(a=e[n])?void 0:a.sn)<t.startSN)break;const r=pg(t,u,e,n,i);if(-1!==r){l.tagAnchor=t.fragments[r].ref;break}}}}function pg(e,t,r,n,i){const s=r[n];if(s){const o=s.programDateTime;if(t>=o||0===n){var a;if(t<=o+1e3*(((null==(a=r[n+1])?void 0:a.start)||i)-s.start)){const i=r[n].sn-e.startSN;if(i<0)return-1;const s=e.fragments;if(s.length>r.length){for(let a=(r[n+1]||s[s.length-1]).sn-e.startSN;a>i;a--){const e=s[a].programDateTime;if(t>=e&&t<e+1e3*s[a].duration)return a}}return i}}}return-1}function gg(e,t,r){var n,i;const s=new _p(e,r),a=null!=(n=s.METHOD)?n:"",o=s.URI,l=s.hexadecimalInteger("IV"),u=s.KEYFORMATVERSIONS,c=null!=(i=s.KEYFORMAT)?i:"identity";o&&s.IV&&!l&&Xd.error(`Invalid IV: ${s.IV}`);const d=o?hg.resolve(o,t):"",h=(u||"1").split("/").map(Number).filter(Number.isFinite);return new sg(a,d,c,h,l,s.KEYID)}function mg(e){const t=new _p(e).decimalFloatingPoint("TIME-OFFSET");return kd(t)?t:null}function vg(e,t){let r=(e||"").split(/[ ,]+/).filter(e=>e);["video","audio","text"].forEach(e=>{const n=r.filter(t=>Yh(t,e));n.length&&(t[`${e}Codec`]=n.map(e=>e.split("/")[0]).join(","),r=r.filter(e=>-1===n.indexOf(e)))}),t.unknownCodecs=r}function yg(e,t,r){const n=t[r];n&&(e[r]=n)}function bg(e,t,r){e.rawProgramDateTime?r.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function wg(e,t,r,n){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=r,e.sn="initSegment",n&&(e.levelkeys=n),e.initSegment=null}function Eg(e,t,r){e.levelkeys=t;const{encryptedFragments:n}=r;n.length&&n[n.length-1].levelkeys===t||!Object.keys(t).some(e=>t[e].isCommonEncryption)||n.push(e)}function Sg(e,t,r){e.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${r[0]})`)}function Tg(e,t,r){e.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${r[0]})`)}function xg(e,t){const r=t.startPTS;if(kd(r)){let n,i=0;t.sn>e.sn?(i=r-e.start,n=e):(i=e.start-r,n=t),n.duration!==i&&n.setDuration(i)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration)}else t.setStart(Math.max(e.start-t.duration,0))}function kg(e,t,r,n,i,s,a){n-r<=0&&(a.warn("Fragment should have a positive duration",t),n=r+t.duration,s=i+t.duration);let o=r,l=n;const u=t.startPTS,c=t.endPTS;if(kd(u)){const d=Math.abs(u-r);e&&d>e.totalduration?a.warn(`media timestamps and playlist times differ by ${d}s for level ${t.level} ${e.url}`):kd(t.deltaPTS)?t.deltaPTS=Math.max(d,t.deltaPTS):t.deltaPTS=d,o=Math.max(r,u),r=Math.min(r,u),i=void 0!==t.startDTS?Math.min(i,t.startDTS):i,l=Math.min(n,c),n=Math.max(n,c),s=void 0!==t.endDTS?Math.max(s,t.endDTS):s}const d=r-t.start;0!==t.start&&t.setStart(r),t.setDuration(n-t.start),t.startPTS=r,t.maxStartPTS=o,t.startDTS=i,t.endPTS=n,t.minEndPTS=l,t.endDTS=s;const h=t.sn;if(!e||h<e.startSN||h>e.endSN)return 0;let f;const p=h-e.startSN,g=e.fragments;for(g[p]=t,f=p;f>0;f--)xg(g[f],g[f-1]);for(f=p;f<g.length-1;f++)xg(g[f],g[f+1]);return e.fragmentHint&&xg(g[g.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,d}function Ag(e,t,r){if(e===t)return;let n=null;const i=e.fragments;for(let e=i.length-1;e>=0;e--){const t=i[e].initSegment;if(t){n=t;break}}let s;e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,r){const n=t.skippedSegments,i=Math.max(e.startSN,t.startSN)-t.startSN,s=(e.fragmentHint?1:0)+(n?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let u=i;u<=s;u++){const i=l[a+u];let s=o[u];if(n&&!s&&i&&(s=t.fragments[u]=i),i&&s){r(i,s,u,o);const n=i.relurl,a=s.relurl;if(n&&Og(n,a))return void(t.playlistParsingError=Rg(`media sequence mismatch ${s.sn}:`,e,t,i,s));if(i.cc!==s.cc)return void(t.playlistParsingError=Rg(`discontinuity sequence mismatch (${i.cc}!=${s.cc})`,e,t,i,s))}}}(e,t,(e,r,i,a)=>{if((!t.startCC||t.skippedSegments)&&r.cc!==e.cc){const n=e.cc-r.cc;for(let e=i;e<a.length;e++)a[e].cc+=n;t.endCC=a[a.length-1].cc}kd(e.startPTS)&&kd(e.endPTS)&&(r.setStart(r.startPTS=e.startPTS),r.startDTS=e.startDTS,r.maxStartPTS=e.maxStartPTS,r.endPTS=e.endPTS,r.endDTS=e.endDTS,r.minEndPTS=e.minEndPTS,r.setDuration(e.endPTS-e.startPTS),r.duration&&(s=r),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(r.elementaryStreams=e.elementaryStreams),r.loader=e.loader,e.hasStats&&(r.stats=e.stats),e.initSegment&&(r.initSegment=e.initSegment,n=e.initSegment)});const a=t.fragments,o=t.fragmentHint?a.concat(t.fragmentHint):a;if(n&&o.forEach(e=>{var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=n)?void 0:t.relurl)||(e.initSegment=n)}),t.skippedSegments){if(t.deltaUpdateFailed=a.some(e=>!e),t.deltaUpdateFailed){r.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)a.shift();t.startSN=a[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,r){const{dateRanges:n,recentlyRemovedDateranges:i}=t,s=zd({},e);i&&i.forEach(e=>{delete s[e]});const a=Object.keys(s).length;if(!a)return n;return Object.keys(n).forEach(e=>{const t=s[e],i=new Np(n[e].attr,t);i.isValid?(s[e]=i,t||(i.tagOrder+=a)):r.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Af(n[e].attr)}"`)}),s}(e.dateRanges,t,r));const n=e.fragments.filter(e=>e.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e<o.length;e++)null===o[e].programDateTime&&bg(o[e],o[e-1],n);fg(n,t)}t.endCC=a[a.length-1].cc}if(!t.startCC){var l;const r=Pg(e,t.startSN-1);t.startCC=null!=(l=null==r?void 0:r.cc)?l:a[0].cc}!function(e,t,r){if(e&&t){let n=0;for(let i=0,s=e.length;i<=s;i++){const s=e[i],a=t[i+n];s&&a&&s.index===a.index&&s.fragment.sn===a.fragment.sn?r(s,a):n--}}}(e.partList,t.partList,(e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats}),s?kg(t,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS,r):Lg(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const u=t.advancedDateTime;if(t.advanced&&u){const e=t.edge;t.driftStart||(t.driftStartTime=u,t.driftStart=e),t.driftEndTime=u,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}function Rg(e,t,r,n,i){return new Error(`${e} ${i.url}\nPlaylist starting @${t.startSN}\n${t.m3u8}\n\nPlaylist starting @${r.startSN}\n${r.m3u8}`)}function Lg(e,t,r=!0){const n=t.startSN+t.skippedSegments-e.startSN,i=e.fragments,s=n>=0;let a=0;if(s&&n<i.length)a=i[n].start;else if(s&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(s&&r)a=e.fragmentStart+n*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;a=e.fragmentStart}Ig(t,a)}function Ig(e,t){if(t){const r=e.fragments;for(let n=e.skippedSegments;n<r.length;n++)r[n].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function Cg(e,t=1/0){let r=1e3*e.targetduration;if(e.updated){const n=e.fragments,i=4;if(n.length&&r*i>t){const e=1e3*n[n.length-1].duration;e<r&&(r=e)}}else r/=2;return Math.round(r)}function Pg(e,t,r){if(!e)return null;let n=e.fragments[t-e.startSN];return n||(n=e.fragmentHint,n&&n.sn===t?n:t<e.startSN&&r&&r.sn===t?r:null)}function Dg(e,t,r){return e?_g(e.partList,t,r):null}function _g(e,t,r){if(e)for(let n=e.length;n--;){const i=e[n];if(i.index===r&&i.fragment.sn===t)return i}return null}function Mg(e){e.forEach((e,t)=>{var r;null==(r=e.details)||r.fragments.forEach(e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function Og(e,t){return!(e===t||!t)&&Ng(e)!==Ng(t)}function Ng(e){return e.replace(/\?[^?]*$/,"")}function Fg(e,t){for(let n=0,i=e.length;n<i;n++){var r;if((null==(r=e[n])?void 0:r.cc)===t)return e[n]}return null}function $g(e,t){const r=e.start+t;e.startPTS=r,e.setStart(r),e.endPTS=r+e.duration}function Bg(e,t){const r=t.fragments;for(let t=0,n=r.length;t<n;t++)$g(r[t],e);t.fragmentHint&&$g(t.fragmentHint,e),t.alignedSliding=!0}function Ug(e,t){if(!function(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}(t,e))return;const r=Math.min(t.endCC,e.endCC),n=Fg(t.fragments,r),i=Fg(e.fragments,r);if(!n||!i)return;Xd.log(`Aligning playlist at start of dicontinuity sequence ${r}`);Bg(n.start-i.start,e)}function zg(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const r=e.fragments,n=t.fragments;if(!r.length||!n.length)return;let i,s;const a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(i=Fg(n,a),s=Fg(r,a)),i&&s||(i=n[Math.floor(n.length/2)],s=Fg(r,i.cc)||r[Math.floor(r.length/2)]);const o=i.programDateTime,l=s.programDateTime;if(!o||!l)return;Bg((l-o)/1e3-(s.start-i.start),e)}function jg(e,t,r){Gg(e,t,r),e.addEventListener(t,r)}function Gg(e,t,r){e.removeEventListener(t,r)}const Hg=function(e){let t="";const r=e.length;for(let n=0;n<r;n++)t+=`[${e.start(n).toFixed(3)}-${e.end(n).toFixed(3)}]`;return t},Vg="STOPPED",Wg="IDLE",Kg="KEY_LOADING",Yg="FRAG_LOADING",qg="FRAG_LOADING_WAITING_RETRY",Xg="WAITING_TRACK",Qg="PARSING",Zg="PARSED",Jg="ENDED",em="ERROR",tm="WAITING_INIT_PTS",rm="WAITING_LEVEL";class nm extends Sp{constructor(e,t,r,n,i){super(n,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Vg,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:e,fragCurrent:t,media:r,mediaBuffer:n,state:i}=this,s=r?r.currentTime:0,a=kp.bufferInfo(n||r,s,e.maxBufferHole),o=!a.len;if(this.log(`Media seeking to ${kd(s)?s.toFixed(3):s}, state: ${i}, ${o?"out of":"in"} buffer`),this.state===Jg)this.resetLoadingState();else if(t){const r=e.maxFragLookUpTolerance,n=t.start-r,i=t.start+t.duration+r;if(o||i<a.start||n>a.end){const e=s>i;(s<n||e)&&(e&&t.loader&&(this.log(`Cancelling fragment load for seek (sn: ${t.sn})`),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(r){this.fragmentTracker.removeFragmentsInRange(s,1/0,this.playlistType,!0);if(s>this.lastCurrentTime&&(this.lastCurrentTime=s),!this.loadingParts){const e=Math.max(a.end,s),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${s.toFixed(2)} with buffer @${e.toFixed(2)}`),this.loadingParts=t)}}this.hls.hasEnoughToStart||(this.log(`Setting ${o?"startPosition":"nextLoadPosition"} to ${s} for seek without enough to start`),this.nextLoadPosition=s,o&&(this.startPosition=s)),o&&this.state===Wg&&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 yp(e.config),this.keyLoader=r,this.fragmentTracker=t,this.config=e.config,this.decrypter=new mp(e.config)}registerListeners(){const{hls:e}=this;e.on(Cd.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Cd.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Cd.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Cd.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Cd.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Cd.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Cd.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Cd.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===Vg)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Vg}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return-1===t&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const r=e.end||0,n=this.config.timelineOffset||0;if(r<=n)return!1;const i=e.buffered;this.config.maxBufferHole&&i&&i.length>1&&(e=kp.bufferedInfo(i,e.start,0));const s=e.nextStart;if(s&&s>n&&s<t.edge)return!1;if(this.media.currentTime<e.start)return!1;const a=t.partList;if(null!=a&&a.length){const e=a[a.length-1];return kp.isBuffered(this.media,e.start+e.duration/2)}const o=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;var t;return e?(null==(t=this.getLevelDetails())?void 0:t.appliedTimelineOffset)||e:0}onMediaAttached(e,t){const r=this.media=this.mediaBuffer=t.media;jg(r,"seeking",this.onMediaSeeking),jg(r,"ended",this.onMediaEnded);const n=this.config;this.levels&&n.autoStartLoad&&this.state===Vg&&this.startLoad(n.startPosition)}onMediaDetaching(e,t){const r=!!t.transferMedia,n=this.media;if(null!==n){if(n.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Gg(n,"seeking",this.onMediaSeeking),Gg(n,"ended",this.onMediaEnded),this.keyLoader&&!r&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,r)return this.resetLoadingState(),void this.resetTransmuxer();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,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=Vg,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,t,r){this.startFragRequested=!0,this._loadFragForPlayback(e,t,r)}_loadFragForPlayback(e,t,r){this._doFragLoad(e,t,r,e=>{const t=e.frag;if(this.fragContextChanged(t))return this.warn(`${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(e)}).then(e=>{if(!e)return;const t=this.state,r=e.frag;this.fragContextChanged(r)?(t===Yg||!this.fragCurrent&&t===Qg)&&(this.fragmentTracker.removeFragment(r),this.state=Wg):("payload"in e&&(this.log(`Loaded ${r.type} sn: ${r.sn} of ${this.playlistLabel()} ${r.level}`),this.hls.trigger(Cd.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))}).catch(t=>{this.state!==Vg&&this.state!==em&&(this.warn(`Frag error: ${(null==t?void 0:t.message)||t}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:r}=this;if(r.getState(e)===ip){const t=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,t),i=Math.max(e.duration,n?n.len:this.config.maxBufferLength),s=this.backtrackFragment;(1===(s?e.sn-s.sn:0)||this.reduceMaxBufferLength(i,e.duration))&&r.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?r.removeAllFragments():r.hasParts(e.type)&&(r.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),r.getState(e)===sp&&r.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,r=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:r};this.hls.trigger(Cd.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(e=>{const t=null==e?void 0:e.frag;if(!t||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return e}).then(e=>{const{hls:t}=this,{frag:r,payload:n}=e,i=r.decryptdata;if(n&&n.byteLength>0&&null!=i&&i.key&&i.iv&&Up(i.method)){const s=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),i.key.buffer,i.iv.buffer,zp(i.method)).catch(e=>{throw t.trigger(Cd.ERROR,{type:Ld.MEDIA_ERROR,details:Id.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:r}),e}).then(n=>{const i=self.performance.now();return t.trigger(Cd.FRAG_DECRYPTED,{frag:r,payload:n,stats:{tstart:s,tdecrypt:i}}),e.payload=n,this.completeInitSegmentLoad(e)})}return this.completeInitSegmentLoad(e)}).catch(t=>{this.state!==Vg&&this.state!==em&&(this.warn(t),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const r=e.frag.stats;this.state!==Vg&&(this.state=Wg),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,t){var r,n;const i=e.tracks;if(i&&!t.encrypted&&(null!=(r=i.audio)&&r.encrypted||null!=(n=i.video)&&n.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const e=this.media,r=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${e?"attached mediaKeys: "+e.mediaKeys:"detached"})`);return this.warn(r.message),!e||e.mediaKeys?!1:(this.hls.trigger(Cd.ERROR,{type:Ld.KEY_SYSTEM_ERROR,details:Id.KEY_SYSTEM_NO_KEYS,fatal:!1,error:r,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const r=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${r?Hg(kp.getBuffered(r)):"(detached)"})`),mh(e)){var n;if(e.type!==Fd){const t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return void(this.state=Wg)}const t=null==(n=this.levels)?void 0:n[e.level];null!=t&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=Wg}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:r,part:n,partsLoaded:i}=e,s=!i||0===i.length||i.some(e=>!e),a=new Tp(r.level,r.sn,r.stats.chunkCount+1,0,n?n.index:-1,!s);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,r=null,n){var i;this.fragCurrent=e;const s=t.details;if(!this.levels||!s)throw new Error(`frag load aborted, missing level${s?"":" detail"}s`);let a=null;if(!e.encrypted||null!=(i=e.decryptdata)&&i.key)e.encrypted||(a=this.keyLoader.loadClear(e,s.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));else if(this.log(`Loading key for ${e.sn} of [${s.startSN}-${s.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=Kg,this.fragCurrent=e,a=this.keyLoader.load(e).then(e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(Cd.KEY_LOADED,e),this.state===Kg&&(this.state=Wg),e}),this.hls.trigger(Cd.KEY_LOADING,{frag:e}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);const o=this.fragPrevious;if(mh(e)&&(!o||e.sn!==o.sn)){const r=this.shouldLoadParts(t.details,e.end);r!==this.loadingParts&&(this.log(`LL-Part loading ${r?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${e.sn}`),this.loadingParts=r)}if(r=Math.max(e.start,r||0),this.loadingParts&&mh(e)){const i=s.partList;if(i&&n){r>s.fragmentEnd&&s.fragmentHint&&(e=s.fragmentHint);const o=this.getNextPart(i,e,r);if(o>-1){const l=i[o];let u;return e=this.fragCurrent=l.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${l.index} (${o}/${i.length-1}) of ${this.fragInfo(e,!1,l)}) cc: ${e.cc} [${s.startSN}-${s.endSN}], target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=Yg,u=a?a.then(r=>!r||this.fragContextChanged(r.frag)?null:this.doFragPartsLoad(e,l,t,n)).catch(e=>this.handleFragLoadError(e)):this.doFragPartsLoad(e,l,t,n).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(Cd.FRAG_LOADING,{frag:e,part:l,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):u}if(!e.url||this.loadedEndOfParts(i,r))return Promise.resolve(null)}}var l;if(mh(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${r.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${null==(l=s.partList)?void 0:l.filter(e=>e.loaded).map(e=>`[${e.start}-${e.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} ${"["+s.startSN+"-"+s.endSN+"]"}, target: ${parseFloat(r.toFixed(3))}`),kd(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Yg;const u=this.config.progressive&&e.type!==Fd;let c;return c=u&&a?a.then(t=>!t||this.fragContextChanged(t.frag)?null:this.fragmentLoader.load(e,n)).catch(e=>this.handleFragLoadError(e)):Promise.all([this.fragmentLoader.load(e,u?n:void 0),a]).then(([e])=>(!u&&n&&n(e),e)).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(Cd.FRAG_LOADING,{frag:e,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(e,t,r,n){return new Promise((i,s)=>{var a;const o=[],l=null==(a=r.details)?void 0:a.partList,u=t=>{this.fragmentLoader.loadPart(e,t,n).then(n=>{o[t.index]=n;const s=n.part;this.hls.trigger(Cd.FRAG_LOADED,n);const a=Dg(r.details,e.sn,t.index+1)||_g(l,e.sn,t.index+1);if(!a)return i({frag:e,part:s,partsLoaded:o});u(a)}).catch(s)};u(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===Id.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===Ld.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(Cd.ERROR,t)}else this.hls.trigger(Cd.ERROR,{type:Ld.OTHER_ERROR,details:Id.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Qg)return void(this.fragCurrent||this.state===Vg||this.state===em||(this.state=Wg));const{frag:r,part:n,level:i}=t,s=self.performance.now();r.stats.parsing.end=s,n&&(n.stats.parsing.end=s);const a=this.getLevelDetails(),o=a&&r.sn>a.endSN||this.shouldLoadParts(a,r.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${r.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(r,n,i,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var r;const i=e.partList[0];if(i.fragment.type===Fd)return!1;if(t>=i.end+((null==(r=e.fragmentHint)?void 0:r.duration)||0)){var n;if((this.hls.hasEnoughToStart?(null==(n=this.media)?void 0:n.currentTime)||this.lastCurrentTime:this.getLoadPosition())>i.start-i.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:r}=this,{level:n,sn:i,part:s}=e;if(null==t||!t[n])return this.warn(`Levels object was unset while buffering fragment ${i} of ${this.playlistLabel()} ${n}. The current chunk will not be buffered.`),null;const a=t[n],o=a.details,l=s>-1?Dg(o,i,s):null,u=l?l.fragment:Pg(o,i,r);return u?(r&&r!==u&&(u.stats=r.stats),{frag:u,part:l,level:a}):null}bufferFragmentData(e,t,r,n,i){if(this.state!==Qg)return;const{data1:s,data2:a}=e;let o=s;if(a&&(o=$h(s,a)),!o.length)return;const l=this.initPTS[t.cc],u=l?-l.baseTime/l.timescale:void 0,c={type:e.type,frag:t,part:r,chunkMeta:n,offset:u,parent:t.type,data:o};if(this.hls.trigger(Cd.BUFFER_APPENDING,c),e.dropped&&e.independent&&!r){if(i)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!kp.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const r=t.currentTime,n=kp.bufferInfo(t,r,0),i=e.duration,s=Math.min(2*this.config.maxFragLookUpTolerance,.25*i),a=Math.max(Math.min(e.start-s,n.end-s),r+s);e.start-a>s&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var r;const n=this.getLoadPosition();if(!kd(n))return null;const i=this.lastCurrentTime>n||null!=(r=this.media)&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,i)}getFwdBufferInfoAtPos(e,t,r,n){const i=kp.bufferInfo(e,t,n);if(0===i.len&&void 0!==i.nextStart){const s=this.fragmentTracker.getBufferedFrag(t,r);if(s&&(i.nextStart<=s.end||s.gap)){const r=Math.max(Math.min(i.nextStart,s.end)-t,n);return kp.bufferInfo(e,t,r)}}return i}getMaxBufferLength(e){const{config:t}=this;let r;return r=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(r,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const r=this.config,n=Math.max(Math.min(e-t,r.maxBufferLength),t),i=Math.max(e-3*t,r.maxMaxBufferLength/2,n);return i>=n&&(r.maxMaxBufferLength=i,this.warn(`Reduce max buffer length to ${i}s`),!0)}getAppendedFrag(e,t=Od){const r=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return r&&"fragment"in r?r.fragment:r}getNextFragment(e,t){const r=t.fragments,n=r.length;if(!n)return null;const{config:i}=this,s=r[0].start,a=i.lowLatencyMode&&!!t.partList;let o=null;if(t.live){const r=i.initialLiveManifestSize;if(n<r)return this.warn(`Not enough fragments to start playback (have: ${n}, need: ${r})`),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<s){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t);const r=this.hls.startPosition,n=this.hls.liveSyncPosition,i=o?(-1!==r&&r>=s?r:n)||o.start:e;this.log(`Setting startPosition to ${i} to match start frag at live edge. mainStart: ${r} liveSyncPosition: ${n} frag.start: ${null==(l=o)?void 0:l.start}`),this.startPosition=this.nextLoadPosition=i}}else e<=s&&(o=r[0]);if(!o){const r=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,r,t)}let u=this.filterReplacedPrimary(o,t);if(!u&&o){const e=o.sn-t.startSN;u=this.filterReplacedPrimary(r[e+1]||null,t)}return this.mapToInitFragWhenRequired(u)}isLoopLoading(e,t){const r=this.fragmentTracker.getState(e);return(r===ap||r===sp&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,r,n,i){let s=null;if(e.gap&&(s=this.getNextFragment(this.nextLoadPosition,t),s&&!s.gap&&r.nextStart)){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,n,0);if(null!==e&&r.len+e.len>=i){const e=s.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,s}get primaryPrefetch(){if(im(this.config)){var e;if(null==(e=this.hls.interstitialsManager)||null==(e=e.playingItem)?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(im(this.config)&&e.type!==Fd){const r=this.hls.interstitialsManager,n=null==r?void 0:r.bufferingItem;if(n){const r=n.event;if(r){if(r.appendInPlace||Math.abs(e.start-n.start)>1||0===n.start)return null}else{if(e.end<=n.start&&!1===(null==t?void 0:t.live))return null;if(e.start>n.end&&n.nextEvent&&(n.nextEvent.appendInPlace||e.start-n.end>1))return null}}const i=null==r?void 0:r.playerQueue;if(i)for(let t=i.length;t--;){const r=i[t].interstitial;if(r.appendInPlace&&e.start>=r.startTime&&e.end<=r.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,r){let n=-1,i=!1,s=!0;for(let a=0,o=e.length;a<o;a++){const o=e[a];if(s=s&&!o.independent,n>-1&&r<o.start)break;const l=o.loaded;l?n=-1:(i||(o.independent||s)&&o.fragment===t)&&(o.fragment!==t&&this.warn(`Need buffer at ${r} but next unloaded part starts at ${o.start}`),n=a),i=l}return n}loadedEndOfParts(e,t){let r;for(let n=e.length;n--;){if(r=e[n],!r.loaded)return!1;if(t>r.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,r=this.fragPrevious;let n=null;if(r){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${r.programDateTime}`),n=function(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!kd(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(let n=0;n<e.length;++n){const i=e[n];if($f(t,r,i))return i}return null}(t,r.endProgramDateTime,this.config.maxFragLookUpTolerance)),!n){const i=r.sn+1;if(i>=e.startSN&&i<=e.endSN){const s=t[i-e.startSN];r.cc===s.cc&&(n=s,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=Bf(e,r.cc,r.end),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(n=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return n}getFragmentAtPosition(e,t,r){const{config:n}=this;let{fragPrevious:i}=this,{fragments:s,endSN:a}=r;const{fragmentHint:o}=r,{maxFragLookUpTolerance:l}=n,u=r.partList,c=!!(this.loadingParts&&null!=u&&u.length&&o);let d;if(c&&!this.bitrateTest&&u[u.length-1].fragment.sn===o.sn&&(s=s.concat(o),a=o.sn),e<t){var h;d=Nf(i,s,e,e<this.lastCurrentTime||e>t-l||null!=(h=this.media)&&h.paused||!this.startFragRequested?0:l)}else d=s[s.length-1];if(d){const e=d.sn-r.startSN,t=this.fragmentTracker.getState(d);if((t===ap||t===sp&&d.gap)&&(i=d),i&&d.sn===i.sn&&(!c||u[0].fragment.sn>d.sn||!r.live)){if(d.level===i.level){const t=s[e+1];d=d.sn<a&&this.fragmentTracker.getState(t)!==ap?t:null}}}return d}alignPlaylists(e,t,r){const n=e.fragments.length;if(!n)return this.warn("No fragments in live playlist"),0;const i=e.fragmentStart,s=!t,a=e.alignedSliding&&kd(i);if(s||!a&&!i){!function(e,t){e&&(Ug(t,e),t.alignedSliding||zg(t,e),t.alignedSliding||t.skippedSegments||Lg(e,t,!1))}(r,e);const i=e.fragmentStart;return this.log(`Live playlist sliding: ${i.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${n}`),i}return i}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let r=this.startPosition;r<t&&(r=-1);const n=this.timelineOffset;if(-1===r){const i=null!==this.startTimeOffset,s=i?this.startTimeOffset:e.startTimeOffset;null!==s&&kd(s)?(r=t+s,s<0&&(r+=e.edge),r=Math.min(Math.max(t,r),t+e.totalduration),this.log(`Setting startPosition to ${r} for start time offset ${s} found in ${i?"multivariant":"media"} playlist`),this.startPosition=r):e.live?(r=this.hls.liveSyncPosition||t,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+n}this.nextLoadPosition=r+n}getLoadPosition(){var e;const{media:t}=this;let r=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?r=t.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&mh(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===qg)||(this.state=Wg)}onFragmentOrKeyLoadError(e,t){var r;if(t.chunkMeta&&!t.frag){const e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}const n=t.frag;if(!n||n.type!==e||!this.levels)return;var i;if(this.fragContextChanged(n))return void this.warn(`Frag load error must match current frag to retry ${n.url} > ${null==(i=this.fragCurrent)?void 0:i.url}`);const s=t.details===Id.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(n,!0);const a=t.errorAction;if(!a)return void(this.state=em);const{action:o,flags:l,retryCount:u=0,retryConfig:c}=a,d=!!c,h=d&&o===Qf,f=d&&!a.resolved&&l===Jf,p=null==(r=this.hls.latestLevelDetails)?void 0:r.live;if(!h&&f&&mh(n)&&!n.endList&&p&&!jf(t))this.resetFragmentErrors(e),this.treatAsGap(n),a.resolved=!0;else if((h||f)&&u<c.maxNumRetry){var g;const r=Kf(null==(g=t.response)?void 0:g.code),i=Hf(c,u);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+i,this.state=qg,a.resolved=!0,r)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(t.reason="offline");this.warn(`Fragment ${n.sn} of ${e} ${n.level} errored with ${t.details}, retrying loading ${u+1}/${c.maxNumRetry} in ${i}ms`)}else if(c){if(this.resetFragmentErrors(e),!(u<c.maxNumRetry))return void this.warn(`${t.details} reached or exceeded max retry (${u})`);s||o===Xf||(a.resolved=!0)}else this.state=o===qf?rm:em;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,r=t===1/0;(!t||e>=t||r&&!Kf(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Wg)}reduceLengthAndFlushBuffer(e){if(this.state===Qg||this.state===Zg){const t=e.frag,r=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,r),i=n&&n.len>.5;i&&this.reduceMaxBufferLength(n.len,(null==t?void 0:t.duration)||10);const s=!i;return s&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${r} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),s}return!1}resetFragmentErrors(e){e===Nd&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Vg&&(this.state=Wg)}afterBufferFlushed(e,t,r){if(!e)return;const n=kp.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,r),this.state===Jg&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Vg&&(this.state=Wg)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${-1===e.level?"<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,t,r,n){const i=r.details;if(!i)return void this.warn("level.details undefined");if(!Object.keys(e.elementaryStreams).reduce((t,s)=>{const a=e.elementaryStreams[s];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${s} duration reliably (${o})`),t||!1;const l=n?0:kg(i,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this);return this.hls.trigger(Cd.LEVEL_PTS_UPDATED,{details:i,level:r,drift:l,type:s,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t},!1)){var s;const t=null===(null==(s=this.transmuxer)?void 0:s.error);if((0===r.fragmentError||t&&(r.fragmentError<2||e.endList))&&this.treatAsGap(e,r),t){const t=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(t.message),this.hls.trigger(Cd.ERROR,{type:Ld.MEDIA_ERROR,details:Id.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${r.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Zg,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(Cd.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===Od?"level":"track"}fragInfo(e,t=!0,r){var n,i;return`${this.playlistLabel()} ${e.level} (${r?"part":"frag"}:[${(null!=(n=t&&!r?e.startPTS:(r||e).start)?n:NaN).toFixed(3)}-${(null!=(i=t&&!r?e.endPTS:(r||e).end)?i:NaN).toFixed(3)}]${r&&"main"===e.type?"INDEPENDENT="+(r.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;null==(e=this.transmuxer)||e.reset()}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function im(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}class sm{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let r;return e.length?(r=1===e.length?e[0]:function(e,t){const r=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){const i=e[t];r.set(i,n),n+=i.length}return r}(e,t),this.reset(),r):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var am,om={exports:{}};var lm=(am||(am=1,function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}function i(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function s(e,t,n,s,a){if("function"!=typeof n)throw new TypeError("The listener must be a function");var o=new i(n,s||e,a),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0===--e._eventsCount?e._events=new n:delete e._events[t]}function o(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),o.prototype.eventNames=function(){var e,n,i=[];if(0===this._eventsCount)return i;for(n in e=this._events)t.call(e,n)&&i.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},o.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,a=new Array(s);i<s;i++)a[i]=n[i].fn;return a},o.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},o.prototype.emit=function(e,t,n,i,s,a){var o=r?r+e:e;if(!this._events[o])return!1;var l,u,c=this._events[o],d=arguments.length;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),d){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,s),!0;case 6:return c.fn.call(c.context,t,n,i,s,a),!0}for(u=1,l=new Array(d-1);u<d;u++)l[u-1]=arguments[u];c.fn.apply(c.context,l)}else{var h,f=c.length;for(u=0;u<f;u++)switch(c[u].once&&this.removeListener(e,c[u].fn,void 0,!0),d){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,t);break;case 3:c[u].fn.call(c[u].context,t,n);break;case 4:c[u].fn.call(c[u].context,t,n,i);break;default:if(!l)for(h=1,l=new Array(d-1);h<d;h++)l[h-1]=arguments[h];c[u].fn.apply(c[u].context,l)}}return!0},o.prototype.on=function(e,t,r){return s(this,e,t,r,!1)},o.prototype.once=function(e,t,r){return s(this,e,t,r,!0)},o.prototype.removeListener=function(e,t,n,i){var s=r?r+e:e;if(!this._events[s])return this;if(!t)return a(this,s),this;var o=this._events[s];if(o.fn)o.fn!==t||i&&!o.once||n&&o.context!==n||a(this,s);else{for(var l=0,u=[],c=o.length;l<c;l++)(o[l].fn!==t||i&&!o[l].once||n&&o[l].context!==n)&&u.push(o[l]);u.length?this._events[s]=1===u.length?u[0]:u:a(this,s)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&a(this,t)):(this._events=new n,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,e.exports=o}(om)),om.exports),um=rh(lm);const cm="1.6.15",dm={};function hm(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function fm(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function pm(e,t){let r=0;return r=(127&e[t])<<21,r|=(127&e[t+1])<<14,r|=(127&e[t+2])<<7,r|=127&e[t+3],r}function gm(e,t){const r=t;let n=0;for(;fm(e,t);){n+=10;n+=pm(e,t+6),hm(e,t+10)&&(n+=10),t+=n}if(n>0)return e.subarray(r,r+n)}function mm(e,t){return 255===e[t]&&240==(246&e[t+1])}function vm(e,t){return 1&e[t+1]?7:9}function ym(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function bm(e,t){return t+1<e.length&&mm(e,t)}function wm(e,t){if(bm(e,t)){const r=vm(e,t);if(t+r>=e.length)return!1;const n=ym(e,t);if(n<=r)return!1;const i=t+n;return i===e.length||bm(e,i)}return!1}function Em(e,t,r,n,i){if(!e.samplerate){const s=function(e,t,r,n){const i=t[r+2],s=i>>2&15;if(s>12){const t=new Error(`invalid ADTS sampling index:${s}`);return void e.emit(Cd.ERROR,Cd.ERROR,{type:Ld.MEDIA_ERROR,details:Id.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message})}const a=1+(i>>6&3),o=t[r+3]>>6&3|(1&i)<<2,l="mp4a.40."+a,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][s];let c=s;5!==a&&29!==a||(c-=3);const d=[a<<3|(14&c)>>1,(1&c)<<7|o<<3];return Xd.log(`manifest codec:${n}, parsed codec:${l}, channels:${o}, rate:${u} (ADTS object type:${a} sampling index:${s})`),{config:d,samplerate:u,channelCount:o,codec:l,parsedCodec:l,manifestCodec:n}}(t,r,n,i);if(!s)return;zd(e,s)}}function Sm(e){return 9216e4/e}function Tm(e,t,r,n,i){const s=n+i*Sm(e.samplerate),a=function(e,t){const r=vm(e,t);if(t+r<=e.length){const n=ym(e,t)-r;if(n>0)return{headerLength:r,frameLength:n}}}(t,r);let o;if(a){const{frameLength:n,headerLength:i}=a,l=i+n,u=Math.max(0,r+l-t.length);u?(o=new Uint8Array(l-i),o.set(t.subarray(r+i,t.length),0)):o=t.subarray(r+i,r+l);const c={unit:o,pts:s};return u||e.samples.push(c),{sample:c,length:l,missing:u}}const l=t.length-r;o=new Uint8Array(l),o.set(t.subarray(r,t.length),0);return{sample:{unit:o,pts:s},length:l,missing:-1}}function xm(e,t){return fm(e,t)&&pm(e,t+6)+10<=e.length-t}function km(e,t=0,r=1/0){return function(e,t,r,n){const i=function(e){return e instanceof ArrayBuffer?e:e.buffer}(e);let s=1;"BYTES_PER_ELEMENT"in n&&(s=n.BYTES_PER_ELEMENT);const a=(d=e,d&&d.buffer instanceof ArrayBuffer&&void 0!==d.byteLength&&void 0!==d.byteOffset?e.byteOffset:0),o=(a+e.byteLength)/s,l=(a+t)/s,u=Math.floor(Math.max(0,Math.min(l,o))),c=Math.floor(Math.min(u+Math.max(r,0),o));var d;return new n(i,u,c-u)}(e,t,r,Uint8Array)}function Am(e){const t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(e.size<2)return;if(3!==e.data[0])return void console.log("Ignore frame with unrecognized character encoding");const r=e.data.subarray(1).indexOf(0);if(-1===r)return;const n=Jd(km(e.data,1,r)),i=e.data[2+r],s=e.data.subarray(3+r).indexOf(0);if(-1===s)return;const a=Jd(km(e.data,3+r,s));let o;return o="--\x3e"===n?Jd(km(e.data,4+r+s)):function(e){return e instanceof ArrayBuffer?e:0==e.byteOffset&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}(e.data.subarray(4+r+s)),t.mimeType=n,t.pictureType=i,t.description=a,t.data=o,t}function Rm(e){return"PRIV"===e.type?function(e){if(e.size<2)return;const t=Jd(e.data,!0),r=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:r.buffer}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;let t=1;const r=Jd(e.data.subarray(t),!0);t+=r.length+1;const n=Jd(e.data.subarray(t));return{key:e.type,info:r,data:n}}const t=Jd(e.data);return{key:e.type,info:"",data:t}}(e):"APIC"===e.type?Am(e):function(e){if(e.size<2)return;if("TXXX"===e.type){let t=1;const r=Jd(e.data.subarray(t),!0);t+=r.length+1;const n=Jd(e.data.subarray(t));return{key:e.type,info:r,data:n}}const t=Jd(e.data.subarray(1));return{key:e.type,info:"",data:t}}(e)}function Lm(e){const t=String.fromCharCode(e[0],e[1],e[2],e[3]),r=pm(e,4);return{type:t,size:r,data:e.subarray(10,10+r)}}function Im(e){let t=0;const r=[];for(;fm(e,t);){const n=pm(e,t+6);e[t+5]>>6&1&&(t+=10),t+=10;const i=t+n;for(;t+10<i;){const n=Lm(e.subarray(t)),i=Rm(n);i&&r.push(i),t+=n.size+10}hm(e,t)&&(t+=10)}return r}function Cm(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function Pm(e){if(8===e.data.byteLength){const t=new Uint8Array(e.data),r=1&t[3];let n=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return n/=45,r&&(n+=47721858.84),Math.round(n)}}function Dm(e){const t=Im(e);for(let e=0;e<t.length;e++){const r=t[e];if(Cm(r))return Pm(r)}}let _m=function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e}({});function Mm(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class Om{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,t,r,n){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,t){return!1}appendFrame(e,t,r){}demux(e,t){this.cachedData&&(e=$h(this.cachedData,e),this.cachedData=null);let r,n=gm(e,0),i=n?n.length:0;const s=this._audioTrack,a=this._id3Track,o=n?Dm(n):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&kd(o))&&(this.basePTS=Nm(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),n&&n.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:_m.audioId3,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(e,i)){const t=this.appendFrame(s,e,i);t?(this.frameIndex++,this.lastPTS=t.sample.pts,i+=t.length,r=i):i=l}else xm(e,i)?(n=gm(e,i),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:_m.audioId3,duration:Number.POSITIVE_INFINITY}),i+=n.length,r=i):i++;if(i===l&&r!==l){const t=e.slice(r);this.cachedData?this.cachedData=$h(this.cachedData,t):this.cachedData=t}}return{audioTrack:s,videoTrack:Mm(),id3Track:a,textTrack:Mm()}}demuxSampleAes(e,t,r){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Mm(),id3Track:this._id3Track,textTrack:Mm()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Nm=(e,t,r)=>{if(kd(e))return 90*e;return 9e4*t+(r?9e4*r.baseTime/r.timescale:0)};let Fm=null;const $m=[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],Bm=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Um=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],zm=[0,1,1,4];function jm(e,t,r,n,i){if(r+24>t.length)return;const s=Gm(t,r);if(s&&r+s.frameLength<=t.length){const a=n+i*(9e4*s.samplesPerFrame/s.sampleRate),o={unit:t.subarray(r,r+s.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=s.channelCount,e.samplerate=s.sampleRate,e.samples.push(o),{sample:o,length:s.frameLength,missing:0}}}function Gm(e,t){const r=e[t+1]>>3&3,n=e[t+1]>>1&3,i=e[t+2]>>4&15,s=e[t+2]>>2&3;if(1!==r&&0!==i&&15!==i&&3!==s){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*$m[14*(3===r?3-n:3===n?3:4)+i-1],u=Bm[3*(3===r?0:2===r?1:2)+s],c=3===o?1:2,d=Um[r][n],h=zm[n],f=8*d*h,p=Math.floor(d*l/u+a)*h;if(null===Fm){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Fm=e?parseInt(e[1]):0}return!!Fm&&Fm<=87&&2===n&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:u,channelCount:c,frameLength:p,samplesPerFrame:f}}}function Hm(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function Vm(e,t){return t+1<e.length&&Hm(e,t)}function Wm(e,t){if(t+1<e.length&&Hm(e,t)){const r=4,n=Gm(e,t);let i=r;null!=n&&n.frameLength&&(i=n.frameLength);const s=t+i;return s===e.length||Vm(e,s)}return!1}const Km=(e,t)=>{let r=0,n=5;t+=n;const i=new Uint32Array(1),s=new Uint32Array(1),a=new Uint8Array(1);for(;n>0;){a[0]=e[t];const o=Math.min(n,8),l=8-o;s[0]=4278190080>>>24+l<<l,i[0]=(a[0]&s[0])>>l,r=r?r<<o|i[0]:i[0],t+=1,n-=o}return r};class Ym extends Om{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,r,n){super.resetInitSegment(e,t,r,n),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,r){const n=qm(e,t,r,this.basePTS,this.frameIndex);if(-1!==n){return{sample:e.samples[e.samples.length-1],length:n,missing:0}}}static probe(e){if(!e)return!1;const t=gm(e,0);if(!t)return!1;const r=t.length;return 11===e[r]&&119===e[r+1]&&void 0!==Dm(t)&&Km(e,r)<16}}function qm(e,t,r,n,i){if(r+8>t.length)return-1;if(11!==t[r]||119!==t[r+1])return-1;const s=t[r+4]>>6;if(s>=3)return-1;const a=[48e3,44100,32e3][s],o=63&t[r+4],l=2*[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][3*o+s];if(r+l>t.length)return-1;const u=t[r+6]>>5;let c=0;2===u?c+=2:(1&u&&1!==u&&(c+=2),4&u&&(c+=2));const d=(t[r+6]<<8|t[r+7])>>12-c&1,h=[2,1,2,3,3,4,4,5][u]+d,f=t[r+5]>>3,p=7&t[r+5],g=new Uint8Array([s<<6|f<<1|p>>2,(3&p)<<6|u<<3|d<<2|o>>4,o<<4&224]),m=n+i*(1536/a*9e4),v=t.subarray(r,r+l);return e.config=g,e.channelCount=h,e.samplerate=a,e.samples.push({unit:v,pts:m}),l}const Xm=/\/emsg[-/]ID3/i;function Qm(e,t){return kd(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}class Zm{constructor(e,t,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new mp(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,dp)}decryptAacSample(e,t,r){const n=e[t].unit;if(n.length<=16)return;const i=n.subarray(16,n.length-n.length%16),s=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(s).then(i=>{const s=new Uint8Array(i);n.set(s,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,r)}).catch(r)}decryptAacSamples(e,t,r){for(;;t++){if(t>=e.length)return void r();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,r),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t);let n=0;for(let t=32;t<e.length-16;t+=160,n+=16)r.set(e.subarray(t,t+16),n);return r}getAvcDecryptedUnit(e,t){const r=new Uint8Array(t);let n=0;for(let t=32;t<e.length-16;t+=160,n+=16)e.set(r.subarray(n,n+16),t);return e}decryptAvcSample(e,t,r,n,i){const s=Gh(i.data),a=this.getAvcEncryptedData(s);this.decryptBuffer(a.buffer).then(a=>{i.data=this.getAvcDecryptedUnit(s,a),this.decrypter.isSync()||this.decryptAvcSamples(e,t,r+1,n)}).catch(n)}decryptAvcSamples(e,t,r,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,r=0){if(t>=e.length)return void n();const i=e[t].units;for(;!(r>=i.length);r++){const s=i[r];if(!(s.data.length<=48||1!==s.type&&5!==s.type||(this.decryptAvcSample(e,t,r,n,s),this.decrypter.isSync())))return}}}}class Jm{constructor(){this.VideoSample=null}createVideoSample(e,t,r){return{key:e,frame:!1,pts:t,dts:r,units:[],length:0}}getLastNalUnit(e){var t;let r,n=this.VideoSample;if(n&&0!==n.units.length||(n=e[e.length-1]),null!=(t=n)&&t.units){const e=n.units;r=e[e.length-1]}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const r=t.samples,n=r.length;if(!n)return void t.dropped++;{const t=r[n-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}}parseNALu(e,t,r){const n=t.byteLength;let i=e.naluState||0;const s=i,a=[];let o,l,u,c=0,d=-1,h=0;for(-1===i&&(d=0,h=this.getNALuType(t,0),i=0,c=1);c<n;)if(o=t[c++],i)if(1!==i)if(o)if(1===o){if(l=c-i-1,d>=0){const e={data:t.subarray(d,l),type:h};a.push(e)}else{const r=this.getLastNalUnit(e.samples);r&&(s&&c<=4-s&&r.state&&(r.data=r.data.subarray(0,r.data.byteLength-s)),l>0&&(r.data=$h(r.data,t.subarray(0,l)),r.state=0))}c<n?(u=this.getNALuType(t,c),d=c,h=u,i=0):i=-1}else i=0;else i=3;else i=o?0:2;else i=o?0:1;if(d>=0&&i>=0){const e={data:t.subarray(d,n),type:h,state:i};a.push(e)}if(0===a.length){const r=this.getLastNalUnit(e.samples);r&&(r.data=$h(r.data,t))}return e.naluState=i,a}}class ev{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,t=this.bytesAvailable,r=e.byteLength-t,n=new Uint8Array(4),i=Math.min(4,t);if(0===i)throw new Error("no bytes available");n.set(e.subarray(r,r+i)),this.word=new DataView(n.buffer).getUint32(0),this.bitsAvailable=8*i,this.bytesAvailable-=i}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const r=this.word>>>32-t;if(e>32&&Xd.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?r<<t|this.readBits(t):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 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class tv extends Jm{parsePES(e,t,r,n){const i=this.parseNALu(e,r.data,n);let s,a=this.VideoSample,o=!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(n=>{var i,l;switch(n.type){case 1:{let t=!1;s=!0;const i=n.data;if(o&&i.length>4){const e=this.readSliceType(i);2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var u;if(t)null!=(u=a)&&u.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=t;break}case 5:s=!0,null!=(i=a)&&i.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:s=!0,jh(n.data,1,r.pts,t.samples);break;case 7:{var c,d;s=!0,o=!0;const t=n.data,r=this.readSPS(t);if(!e.sps||e.width!==r.width||e.height!==r.height||(null==(c=e.pixelRatio)?void 0:c[0])!==r.pixelRatio[0]||(null==(d=e.pixelRatio)?void 0:d[1])!==r.pixelRatio[1]){e.width=r.width,e.height=r.height,e.pixelRatio=r.pixelRatio,e.sps=[t];const n=t.subarray(1,4);let i="avc1.";for(let e=0;e<3;e++){let t=n[e].toString(16);t.length<2&&(t="0"+t),i+=t}e.codec=i}break}case 8:s=!0,e.pps=[n.data];break;case 9:s=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;case 12:s=!0;break;default:s=!1}if(a&&s){a.units.push(n)}}),n&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return 31&e[t]}readSliceType(e){const t=new ev(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let r,n=8,i=8;for(let s=0;s<e;s++)0!==i&&(r=t.readEG(),i=(n+r+256)%256),n=0===i?n:i}readSPS(e){const t=new ev(e);let r,n,i,s=0,a=0,o=0,l=0;const u=t.readUByte.bind(t),c=t.readBits.bind(t),d=t.readUEG.bind(t),h=t.readBoolean.bind(t),f=t.skipBits.bind(t),p=t.skipEG.bind(t),g=t.skipUEG.bind(t),m=this.skipScalingList.bind(this);u();const v=u();if(c(5),f(3),u(),g(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const e=d();if(3===e&&f(1),g(),g(),f(1),h())for(n=3!==e?8:12,i=0;i<n;i++)h()&&m(i<6?16:64,t)}g();const y=d();if(0===y)d();else if(1===y)for(f(1),p(),p(),r=d(),i=0;i<r;i++)p();g(),f(1);const b=d(),w=d(),E=c(1);0===E&&f(1),f(1),h()&&(s=d(),a=d(),o=d(),l=d());let S=[1,1];if(h()&&h()){switch(u()){case 1:S=[1,1];break;case 2:S=[12,11];break;case 3:S=[10,11];break;case 4:S=[16,11];break;case 5:S=[40,33];break;case 6:S=[24,11];break;case 7:S=[20,11];break;case 8:S=[32,11];break;case 9:S=[80,33];break;case 10:S=[18,11];break;case 11:S=[15,11];break;case 12:S=[64,33];break;case 13:S=[160,99];break;case 14:S=[4,3];break;case 15:S=[3,2];break;case 16:S=[2,1];break;case 255:S=[u()<<8|u(),u()<<8|u()]}}return{width:Math.ceil(16*(b+1)-2*s-2*a),height:(2-E)*(w+1)*16-(E?2:4)*(o+l),pixelRatio:S}}}class rv extends Jm{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,r,n){const i=this.parseNALu(e,r.data,n);let s,a=this.VideoSample,o=!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(n=>{var i,l;switch(n.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,s=!0;break;case 16:case 17:case 18:case 21:var u;if(s=!0,o)null!=(u=a)&&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 19:case 20:s=!0,null!=(i=a)&&i.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:s=!0,jh(n.data,2,r.pts,t.samples);break;case 32:s=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=zd(e.params,this.readVPS(n.data)),this.initVPS=n.data),e.vps=[n.data];break;case 33:if(s=!0,o=!0,void 0===e.vps||e.vps[0]===this.initVPS||void 0===e.sps||this.matchSPS(e.sps[0],n.data)||(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const t=this.readSPS(n.data);e.width=t.width,e.height=t.height,e.pixelRatio=t.pixelRatio,e.codec=t.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={});for(const r in t.params)e.params[r]=t.params[r]}this.pushParameterSet(e.sps,n.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),a.key=!0;break;case 34:if(s=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];const t=this.readPPS(n.data);for(const r in t)e.params[r]=t[r]}this.pushParameterSet(e.pps,n.data,e.vps)}break;case 35:s=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;default:s=!1}if(a&&s){a.units.push(n)}}),n&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,r){(r&&r[0]===this.initVPS||!r&&!e.length)&&e.push(t)}getNALuType(e,t){return(126&e[t])>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let r=0;for(let n=0;n<e.byteLength;n++)n>=2&&3===e[n]&&0===e[n-1]&&0===e[n-2]||(t[r]=e[n],r++);return new Uint8Array(t.buffer,0,r)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new ev(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);return{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}}readSPS(e){const t=new ev(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const r=t.readBits(3);t.readBoolean();const n=t.readBits(2),i=t.readBoolean(),s=t.readBits(5),a=t.readUByte(),o=t.readUByte(),l=t.readUByte(),u=t.readUByte(),c=t.readUByte(),d=t.readUByte(),h=t.readUByte(),f=t.readUByte(),p=t.readUByte(),g=t.readUByte(),m=t.readUByte(),v=[],y=[];for(let e=0;e<r;e++)v.push(t.readBoolean()),y.push(t.readBoolean());if(r>0)for(let e=r;e<8;e++)t.readBits(2);for(let e=0;e<r;e++)v[e]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[e]&&t.readUByte();t.readUEG();const b=t.readUEG();3==b&&t.skipBits(1);const w=t.readUEG(),E=t.readUEG(),S=t.readBoolean();let T=0,x=0,k=0,A=0;S&&(T+=t.readUEG(),x+=t.readUEG(),k+=t.readUEG(),A+=t.readUEG());const R=t.readUEG(),L=t.readUEG(),I=t.readUEG();for(let e=t.readBoolean()?0:r;e<=r;e++)t.skipUEG(),t.skipUEG(),t.skipUEG();t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.readBoolean()){if(t.readBoolean())for(let e=0;e<4;e++)for(let r=0;r<(3===e?2:6);r++){if(t.readBoolean()){const r=Math.min(64,1<<4+(e<<1));e>1&&t.readEG();for(let e=0;e<r;e++)t.readEG()}else t.readUEG()}}t.readBoolean(),t.readBoolean();t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const C=t.readUEG();let P=0;for(let e=0;e<C;e++){let r=!1;if(0!==e&&(r=t.readBoolean()),r){e===C&&t.readUEG(),t.readBoolean(),t.readUEG();let r=0;for(let e=0;e<=P;e++){const e=t.readBoolean();let n=!1;e||(n=t.readBoolean()),(e||n)&&r++}P=r}else{const e=t.readUEG(),r=t.readUEG();P=e+r;for(let r=0;r<e;r++)t.readUEG(),t.readBoolean();for(let e=0;e<r;e++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const e=t.readUEG();for(let r=0;r<e;r++){for(let e=0;e<I+4;e++)t.readBits(1);t.readBits(1)}}let D=0,_=1,M=1,O=!0,N=1,F=0;t.readBoolean(),t.readBoolean();let $=!1;if(t.readBoolean()){if(t.readBoolean()){const e=t.readUByte();e>0&&e<16?(_=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],M=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):255===e&&(_=t.readBits(16),M=t.readBits(16))}t.readBoolean()&&t.readBoolean();if(t.readBoolean()){t.readBits(3),t.readBoolean();t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())}t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),$=t.readBoolean(),$&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG());if(t.readBoolean()){N=t.readBits(32),F=t.readBits(32);t.readBoolean()&&t.readUEG();if(t.readBoolean()){const e=t.readBoolean(),n=t.readBoolean();let i=!1;(e||n)&&(i=t.readBoolean(),i&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),i&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let s=0;s<=r;s++){O=t.readBoolean();let r=!1;O||t.readBoolean()?t.readEG():r=t.readBoolean();const s=r?1:t.readUEG()+1;if(e)for(let e=0;e<s;e++)t.readUEG(),t.readUEG(),i&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(n)for(let e=0;e<s;e++)t.readUEG(),t.readUEG(),i&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),D=t.readUEG())}let B=w,U=E;if(S){let e=1,t=1;1===b?e=t=2:2==b&&(e=2),B=w-e*x-e*T,U=E-t*A-t*k}const z=n?["A","B","C"][n]:"",j=a<<24|o<<16|l<<8|u;let G=0;for(let e=0;e<32;e++)G=(G|(j>>e&1)<<31-e)>>>0;let H=G.toString(16);1===s&&"2"===H&&(H="6");return{codecString:`hvc1.${z}${s}.${H}.${i?"H":"L"}${m}.B0`,params:{general_tier_flag:i,general_profile_idc:s,general_profile_space:n,general_profile_compatibility_flags:[a,o,l,u],general_constraint_indicator_flags:[c,d,h,f,p,g],general_level_idc:m,bit_depth:R+8,bit_depth_luma_minus8:R,bit_depth_chroma_minus8:L,min_spatial_segmentation_idc:D,chroma_format_idc:b,frame_rate:{fixed:O,fps:F/N}},width:B,height:U,pixelRatio:[_,M]}}readPPS(e){const t=new ev(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2);t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const r=t.readBoolean(),n=t.readBoolean();let i=1;return n&&r?i=0:n?i=3:r&&(i=2),{parallelismType:i}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const nv=188;class iv{constructor(e,t,r,n){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=t,this.typeSupported=r,this.logger=n,this.videoParser=null}static probe(e,t){const r=iv.syncOffset(e);return r>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${r}`),-1!==r}static syncOffset(e){const t=e.length;let r=Math.min(940,t-nv)+1,n=0;for(;n<r;){let i=!1,s=-1,a=0;for(let o=n;o<t;o+=nv){if(71!==e[o]||t-o!==nv&&71!==e[o+nv]){if(a)return-1;break}if(a++,-1===s&&(s=o,0!==s&&(r=Math.min(s+18612,e.length-nv)+1)),i||(i=0===sv(e,o)),i&&a>1&&(0===s&&a>2||o+nv>r))return s}n++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:Sh[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,r,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=iv.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=iv.createTrack("audio",n),this._id3Track=iv.createTrack("id3"),this._txtTrack=iv.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:r}=this;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,r=!1,n=!1){let i;r||(this.sampleAes=null);const s=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let u=s.pid,c=s.pesData,d=a.pid,h=o.pid,f=a.pesData,p=o.pesData,g=null,m=this.pmtParsed,v=this._pmtId,y=e.length;if(this.remainderData&&(y=(e=$h(this.remainderData,e)).length,this.remainderData=null),y<nv&&!n)return this.remainderData=e,{audioTrack:a,videoTrack:s,id3Track:o,textTrack:l};const b=Math.max(0,iv.syncOffset(e));y-=(y-b)%nv,y<e.byteLength&&!n&&(this.remainderData=new Uint8Array(e.buffer,y,e.buffer.byteLength-y));let w=0;for(let t=b;t<y;t+=nv)if(71===e[t]){const n=!!(64&e[t+1]),y=sv(e,t);let w;if((48&e[t+3])>>4>1){if(w=t+5+e[t+4],w===t+nv)continue}else w=t+4;switch(y){case u:n&&(c&&(i=cv(c,this.logger))&&(this.readyVideoParser(s.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(s,l,i,!1)),c={data:[],size:0}),c&&(c.data.push(e.subarray(w,t+nv)),c.size+=t+nv-w);break;case d:if(n){if(f&&(i=cv(f,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,i);break;case"mp3":this.parseMPEGPES(a,i);break;case"ac3":this.parseAC3PES(a,i)}f={data:[],size:0}}f&&(f.data.push(e.subarray(w,t+nv)),f.size+=t+nv-w);break;case h:n&&(p&&(i=cv(p,this.logger))&&this.parseID3PES(o,i),p={data:[],size:0}),p&&(p.data.push(e.subarray(w,t+nv)),p.size+=t+nv-w);break;case 0:n&&(w+=e[w]+1),v=this._pmtId=av(e,w);break;case v:{n&&(w+=e[w]+1);const i=ov(e,w,this.typeSupported,r,this.observer,this.logger);u=i.videoPid,u>0&&(s.pid=u,s.segmentCodec=i.segmentVideoCodec),d=i.audioPid,d>0&&(a.pid=d,a.segmentCodec=i.segmentAudioCodec),h=i.id3Pid,h>0&&(o.pid=h),null===g||m||(this.logger.warn(`MPEG-TS PMT found at ${t} after unknown PID '${g}'. Backtracking to sync byte @${b} to parse all TS packets.`),g=null,t=b-188),m=this.pmtParsed=!0;break}case 17:case 8191:break;default:g=y}}else w++;w>0&&lv(this.observer,new Error(`Found ${w} TS packet/s that do not start with 0x47`),void 0,this.logger),s.pesData=c,a.pesData=f,o.pesData=p;const E={audioTrack:a,videoTrack:s,id3Track:o,textTrack:l};return n&&this.extractRemainingSamples(E),E}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:r,id3Track:n,textTrack:i}=e,s=r.pesData,a=t.pesData,o=n.pesData;let l;if(s&&(l=cv(s,this.logger))?(this.readyVideoParser(r.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(r,i,l,!0),r.pesData=null)):r.pesData=s,a&&(l=cv(a,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l)}t.pesData=null}else null!=a&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;o&&(l=cv(o,this.logger))?(this.parseID3PES(n,l),n.pesData=null):n.pesData=o}demuxSampleAes(e,t,r){const n=this.demux(e,r,!0,!this.config.progressive),i=this.sampleAes=new Zm(this.observer,this.config,t);return this.decrypt(n,i)}readyVideoParser(e){null===this.videoParser&&("avc"===e?this.videoParser=new tv:"hevc"===e&&(this.videoParser=new rv))}decrypt(e,t){return new Promise(r=>{const{audioTrack:n,videoTrack:i}=e;n.samples&&"aac"===n.segmentCodec?t.decryptAacSamples(n.samples,0,()=>{i.samples?t.decryptAvcSamples(i.samples,0,0,()=>{r(e)}):r(e)}):i.samples&&t.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,t){let r=0;const n=this.aacOverFlow;let i,s,a,o=t.data;if(n){this.aacOverFlow=null;const t=n.missing,i=n.sample.unit.byteLength;if(-1===t)o=$h(n.sample.unit,o);else{const s=i-t;n.sample.unit.set(o.subarray(0,t),s),e.samples.push(n.sample),r=n.missing}}for(i=r,s=o.length;i<s-1&&!bm(o,i);i++);if(i!==r){let e;const t=i<s-1;if(e=t?`AAC PES did not start with ADTS header,offset:${i}`:"No ADTS header found in AAC PES",lv(this.observer,new Error(e),t,this.logger),!t)return}if(Em(e,this.observer,o,i,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!n)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=Sm(e.samplerate);a=n.sample.pts+t}}let l,u=0;for(;i<s;){if(l=Tm(e,o,i,a,u),i+=l.length,l.missing){this.aacOverFlow=l;break}for(u++;i<s-1&&!bm(o,i);i++);}}parseMPEGPES(e,t){const r=t.data,n=r.length;let i=0,s=0;const a=t.pts;if(void 0!==a)for(;s<n;)if(Vm(r,s)){const t=jm(e,r,s,a,i);if(!t)break;s+=t.length,i++}else s++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(e,t){{const r=t.data,n=t.pts;if(void 0===n)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const i=r.length;let s,a=0,o=0;for(;o<i&&(s=qm(e,r,o,n,a++))>0;)o+=s}}parseID3PES(e,t){if(void 0===t.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const r=zd({},t,{type:this._videoTrack?_m.emsg:_m.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}}function sv(e,t){return((31&e[t+1])<<8)+e[t+2]}function av(e,t){return(31&e[t+10])<<8|e[t+11]}function ov(e,t,r,n,i,s){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<o;){const o=sv(e,t),l=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!n){uv("ADTS AAC",s);break}case 15:-1===a.audioPid&&(a.audioPid=o);break;case 21:-1===a.id3Pid&&(a.id3Pid=o);break;case 219:if(!n){uv("H.264",s);break}case 27:-1===a.videoPid&&(a.videoPid=o);break;case 3:case 4:r.mpeg||r.mp3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="mp3"):s.log("MPEG audio found, not supported in this browser");break;case 193:if(!n){uv("AC-3",s);break}case 129:r.ac3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="ac3"):s.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===a.audioPid&&l>0){let n=t+5,i=l;for(;i>2;){if(106===e[n])!0!==r.ac3?s.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=o,a.segmentAudioCodec="ac3");const t=e[n+1]+2;n+=t,i-=t}}break;case 194:case 135:return lv(i,new Error("Unsupported EC-3 in M2TS found"),void 0,s),a;case 36:-1===a.videoPid&&(a.videoPid=o,a.segmentVideoCodec="hevc",s.log("HEVC in M2TS found"))}t+=l+5}return a}function lv(e,t,r,n){n.warn(`parsing error: ${t.message}`),e.emit(Cd.ERROR,Cd.ERROR,{type:Ld.MEDIA_ERROR,details:Id.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:t,reason:t.message})}function uv(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function cv(e,t){let r,n,i,s,a,o=0;const l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=$h(l[0],l[1]),l.splice(1,1);r=l[0];if(1===(r[0]<<16)+(r[1]<<8)+r[2]){if(n=(r[4]<<8)+r[5],n&&n>e.size-6)return null;const u=r[7];192&u&&(s=536870912*(14&r[9])+4194304*(255&r[10])+16384*(254&r[11])+128*(255&r[12])+(254&r[13])/2,64&u?(a=536870912*(14&r[14])+4194304*(255&r[15])+16384*(254&r[16])+128*(255&r[17])+(254&r[18])/2,s-a>54e5&&(t.warn(`${Math.round((s-a)/9e4)}s delta between PTS and DTS, align them`),s=a)):a=s),i=r[8];let c=i+9;if(e.size<=c)return null;e.size-=c;const d=new Uint8Array(e.size);for(let e=0,t=l.length;e<t;e++){r=l[e];let t=r.byteLength;if(c){if(c>t){c-=t;continue}r=r.subarray(c),t-=c,c=0}d.set(r,o),o+=t}return n&&(n-=i+3),{data:d,pts:s,dts:a,len:n}}return null}class dv{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)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(6===t)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(1===t)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(2===t)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(3===t)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])}}}const hv=Math.pow(2,32)-1;class fv{static init(){let e;for(e in fv.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:[]},fv.types)fv.types.hasOwnProperty(e)&&(fv.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=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]);fv.HDLR_TYPES={video:t,audio:r};const n=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]);fv.STTS=fv.STSC=fv.STCO=i,fv.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),fv.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),fv.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),fv.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const s=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);fv.FTYP=fv.box(fv.types.ftyp,s,o,s,a),fv.DINF=fv.box(fv.types.dinf,fv.box(fv.types.dref,n))}static box(e,...t){let r=8,n=t.length;const i=n;for(;n--;)r+=t[n].byteLength;const s=new Uint8Array(r);for(s[0]=r>>24&255,s[1]=r>>16&255,s[2]=r>>8&255,s[3]=255&r,s.set(e,4),n=0,r=8;n<i;n++)s.set(t[n],r),r+=t[n].byteLength;return s}static hdlr(e){return fv.box(fv.types.hdlr,fv.HDLR_TYPES[e])}static mdat(e){return fv.box(fv.types.mdat,e)}static mdhd(e,t){t*=e;const r=Math.floor(t/(hv+1)),n=Math.floor(t%(hv+1));return fv.box(fv.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,255&e,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))}static mdia(e){return fv.box(fv.types.mdia,fv.mdhd(e.timescale||0,e.duration||0),fv.hdlr(e.type),fv.minf(e))}static mfhd(e){return fv.box(fv.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?fv.box(fv.types.minf,fv.box(fv.types.smhd,fv.SMHD),fv.DINF,fv.stbl(e)):fv.box(fv.types.minf,fv.box(fv.types.vmhd,fv.VMHD),fv.DINF,fv.stbl(e))}static moof(e,t,r){return fv.box(fv.types.moof,fv.mfhd(e),fv.traf(r,t))}static moov(e){let t=e.length;const r=[];for(;t--;)r[t]=fv.trak(e[t]);return fv.box.apply(null,[fv.types.moov,fv.mvhd(e[0].timescale||0,e[0].duration||0)].concat(r).concat(fv.mvex(e)))}static mvex(e){let t=e.length;const r=[];for(;t--;)r[t]=fv.trex(e[t]);return fv.box.apply(null,[fv.types.mvex,...r])}static mvhd(e,t){t*=e;const r=Math.floor(t/(hv+1)),n=Math.floor(t%(hv+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,255&e,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n,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 fv.box(fv.types.mvhd,i)}static sdtp(e){const t=e.samples||[],r=new Uint8Array(4+t.length);let n,i;for(n=0;n<t.length;n++)i=t[n].flags,r[n+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return fv.box(fv.types.sdtp,r)}static stbl(e){return fv.box(fv.types.stbl,fv.stsd(e),fv.box(fv.types.stts,fv.STTS),fv.box(fv.types.stsc,fv.STSC),fv.box(fv.types.stsz,fv.STSZ),fv.box(fv.types.stco,fv.STCO))}static avc1(e){let t,r,n,i=[],s=[];for(t=0;t<e.sps.length;t++)r=e.sps[t],n=r.byteLength,i.push(n>>>8&255),i.push(255&n),i=i.concat(Array.prototype.slice.call(r));for(t=0;t<e.pps.length;t++)r=e.pps[t],n=r.byteLength,s.push(n>>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(r));const a=fv.box(fv.types.avcC,new Uint8Array([1,i[3],i[4],i[5],255,224|e.sps.length].concat(i).concat([e.pps.length]).concat(s))),o=e.width,l=e.height,u=e.pixelRatio[0],c=e.pixelRatio[1];return fv.box(fv.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,o>>8&255,255&o,l>>8&255,255&l,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]),a,fv.box(fv.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),fv.box(fv.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,255&u,c>>24,c>>16&255,c>>8&255,255&c])))}static esds(e){const t=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,...t,6,1,2])}static audioStsd(e){const t=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,t>>8&255,255&t,0,0])}static mp4a(e){return fv.box(fv.types.mp4a,fv.audioStsd(e),fv.box(fv.types.esds,fv.esds(e)))}static mp3(e){return fv.box(fv.types[".mp3"],fv.audioStsd(e))}static ac3(e){return fv.box(fv.types["ac-3"],fv.audioStsd(e),fv.box(fv.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if("audio"===e.type){if("aac"===t)return fv.box(fv.types.stsd,fv.STSD,fv.mp4a(e));if("ac3"===t&&e.config)return fv.box(fv.types.stsd,fv.STSD,fv.ac3(e));if("mp3"===t&&"mp3"===e.codec)return fv.box(fv.types.stsd,fv.STSD,fv.mp3(e))}else{if(!e.pps||!e.sps)throw new Error("video track missing pps or sps");if("avc"===t)return fv.box(fv.types.stsd,fv.STSD,fv.avc1(e));if("hevc"===t&&e.vps)return fv.box(fv.types.stsd,fv.STSD,fv.hvc1(e))}throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,r=(e.duration||0)*(e.timescale||0),n=e.width||0,i=e.height||0,s=Math.floor(r/(hv+1)),a=Math.floor(r%(hv+1));return fv.box(fv.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,a>>24,a>>16&255,a>>8&255,255&a,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,n>>8&255,255&n,0,0,i>>8&255,255&i,0,0]))}static traf(e,t){const r=fv.sdtp(e),n=e.id,i=Math.floor(t/(hv+1)),s=Math.floor(t%(hv+1));return fv.box(fv.types.traf,fv.box(fv.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),fv.box(fv.types.tfdt,new Uint8Array([1,0,0,0,i>>24,i>>16&255,i>>8&255,255&i,s>>24,s>>16&255,s>>8&255,255&s])),fv.trun(e,r.length+16+20+8+16+8+8),r)}static trak(e){return e.duration=e.duration||4294967295,fv.box(fv.types.trak,fv.tkhd(e),fv.mdia(e))}static trex(e){const t=e.id;return fv.box(fv.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const r=e.samples||[],n=r.length,i=12+16*n,s=new Uint8Array(i);let a,o,l,u,c,d;for(t+=8+i,s.set(["video"===e.type?1:0,0,15,1,n>>>24&255,n>>>16&255,n>>>8&255,255&n,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),a=0;a<n;a++)o=r[a],l=o.duration,u=o.size,c=o.flags,d=o.cts,s.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,u>>>24&255,u>>>16&255,u>>>8&255,255&u,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,61440&c.degradPrio,15&c.degradPrio,d>>>24&255,d>>>16&255,d>>>8&255,255&d],12+16*a);return fv.box(fv.types.trun,s)}static initSegment(e){fv.types||fv.init();const t=fv.moov(e);return $h(fv.FTYP,t)}static hvc1(e){const t=e.params,r=[e.vps,e.sps,e.pps],n=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),3|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),r.length]);let i=n.length;for(let e=0;e<r.length;e+=1){i+=3;for(let t=0;t<r[e].length;t+=1)i+=2+r[e][t].length}const s=new Uint8Array(i);s.set(n,0),i=n.length;const a=r.length-1;for(let e=0;e<r.length;e+=1){s.set(new Uint8Array([32+e|(e===a?128:0),0,r[e].length]),i),i+=3;for(let t=0;t<r[e].length;t+=1)s.set(new Uint8Array([r[e][t].length>>8,255&r[e][t].length]),i),i+=2,s.set(r[e][t],i),i+=r[e][t].length}const o=fv.box(fv.types.hvcC,s),l=e.width,u=e.height,c=e.pixelRatio[0],d=e.pixelRatio[1];return fv.box(fv.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,l>>8&255,255&l,u>>8&255,255&u,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,fv.box(fv.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),fv.box(fv.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,d>>24,d>>16&255,d>>8&255,255&d])))}}fv.types=void 0,fv.HDLR_TYPES=void 0,fv.STTS=void 0,fv.STSC=void 0,fv.STCO=void 0,fv.STSZ=void 0,fv.VMHD=void 0,fv.SMHD=void 0,fv.STSD=void 0,fv.FTYP=void 0,fv.DINF=void 0;function pv(e,t,r=1,n=!1){const i=e*t*r;return n?Math.round(i):i}function gv(e,t=!1){return pv(e,1e3,1/9e4,t)}function mv(e){const{baseTime:t,timescale:r,trackId:n}=e;return`${t/r} (${t}/${r}) trackId: ${n}`}let vv,yv=null,bv=null;function wv(e,t,r,n){return{duration:t,size:r,cts:n,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class Ev extends Hd{constructor(e,t,r,n){if(super("mp4-remuxer",n),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=t,this.typeSupported=r,this.ISGenerated=!1,null===yv){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);yv=e?parseInt(e[1]):0}if(null===bv){const e=navigator.userAgent.match(/Safari\/(\d+)/i);bv=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;t&&e&&e.trackId===t.trackId&&e.baseTime===t.baseTime&&e.timescale===t.timescale||this.log(`Reset initPTS: ${t?mv(t):t} > ${e?mv(e):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 t=!1;const r=e[0].pts,n=e.reduce((e,n)=>{let i=n.pts,s=i-e;return s<-4294967296&&(t=!0,i=Sv(i,r),s=i-e),s>0?e:i},r);return t&&this.debug("PTS rollover detected"),n}remux(e,t,r,n,i,s,a,o){let l,u,c,d,h,f,p=i,g=i;const m=e.pid>-1,v=t.pid>-1,y=t.samples.length,b=e.samples.length>0,w=a&&y>0||y>1;if((!m||b)&&(!v||w)||this.ISGenerated||a){if(this.ISGenerated){var E,S,T,x;const e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||(null==(E=t.pixelRatio)?void 0:E[0])!==(null==(S=e.pixelRatio)?void 0:S[0])||(null==(T=t.pixelRatio)?void 0:T[1])!==(null==(x=e.pixelRatio)?void 0:x[1]))||!e&&w||null===this.nextAudioTs&&b)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,i,s));const r=this.isVideoContiguous;let n,a=-1;if(w&&(a=function(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!r&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){this.warn(`Dropped ${a} out of ${y} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,g+=(t.samples[0].pts-e)/t.inputTimeScale,n=g}else-1===a&&(this.warn(`No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(b&&w){const r=this.getVideoStartPts(t.samples),n=(Sv(e.samples[0].pts,r)-r)/t.inputTimeScale;p+=Math.max(0,n),g+=Math.max(0,-n)}if(b){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(e,t,i,s)),u=this.remuxAudio(e,p,this.isAudioContiguous,s,v||w||o===Nd?g:void 0),w){const n=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(e,t,i,s)),l=this.remuxVideo(t,g,r,n)}}else w&&(l=this.remuxVideo(t,g,r,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=n)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(h=Tv(r,i,this._initPTS,this._initDTS)),n.samples.length&&(d=xv(n,i,this._initPTS))),{audio:u,video:l,initSegment:c,independent:f,text:d,id3:h}}computeInitPts(e,t,r,n){const i=Math.round(r*t);let s=Sv(e,i);if(s<i+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(i-s)/t} ${n}`);s<i+t;)s+=8589934592;return s-i}generateIS(e,t,r,n){const i=e.samples,s=t.samples,a=this.typeSupported,o={},l=this._initPTS;let u,c,d,h=!l||n,f="audio/mp4",p=-1;if(h&&(u=c=1/0),e.config&&i.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):fv.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(p=e.id,d=e.inputTimeScale,l&&d===l.timescale?h=!1:u=c=this.computeInitPts(i[0].pts,d,r,"audio"))}if(t.sps&&t.pps&&s.length){if(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:fv.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(p=t.id,d=t.inputTimeScale,l&&d===l.timescale)h=!1;else{const e=this.getVideoStartPts(s),t=Sv(s[0].dts,e),n=this.computeInitPts(t,d,r,"video"),i=this.computeInitPts(e,d,r,"video");c=Math.min(c,n),u=Math.min(u,i)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,h?(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${u/d} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${u/d} (${u}/${d}) trackId: ${p}`),this._initPTS={baseTime:u,timescale:d,trackId:p},this._initDTS={baseTime:c,timescale:d,trackId:p}):u=d=void 0,{tracks:o,initPTS:u,timescale:d,trackId:p}}remuxVideo(e,t,r,n){const i=e.inputTimeScale,s=e.samples,a=[],o=s.length,l=this._initPTS,u=l.baseTime*i/l.timescale;let c,d,h=this.nextVideoTs,f=8,p=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,v=!1;if(!r||null===h){const e=u+t*i,n=s[0].pts-Sv(s[0].dts,s[0].pts);yv&&null!==h&&Math.abs(e-n-(h+u))<15e3?r=!0:h=e-n-u}const y=h+u;for(let e=0;e<o;e++){const t=s[e];t.pts=Sv(t.pts,y),t.dts=Sv(t.dts,y),t.dts<s[e>0?e-1:e].dts&&(v=!0)}v&&s.sort(function(e,t){const r=e.dts-t.dts,n=e.pts-t.pts;return r||n}),c=s[0].dts,d=s[s.length-1].dts;const b=d-c,w=b?Math.round(b/(o-1)):p||e.inputTimeScale/30;if(r){const r=c-y,n=r>w,i=r<-1;if((n||i)&&(n?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${gv(r,!0)} ms (${r}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${gv(-r,!0)} ms (${r}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!i||y>=s[0].pts||yv)){c=y;const e=s[0].pts-r;if(n)s[0].dts=c,s[0].pts=e;else{let t=!0;for(let n=0;n<s.length&&!(s[n].dts>e&&t);n++){const e=s[n].pts;if(s[n].dts-=r,s[n].pts-=r,n<s.length-1){const r=s[n+1].pts;t=r<=s[n].pts==r<=e}}}this.log(`Video: Initial PTS/DTS adjusted: ${gv(e,!0)}/${gv(c,!0)}, delta: ${gv(r,!0)} ms`)}}c=Math.max(0,c);let E=0,S=0,T=c;for(let e=0;e<o;e++){const t=s[e],r=t.units,n=r.length;let i=0;for(let e=0;e<n;e++)i+=r[e].data.length;S+=i,E+=n,t.length=i,t.dts<T?(t.dts=T,T+=w/4|0||1):T=t.dts,g=Math.min(t.pts,g),m=Math.max(t.pts,m)}d=s[o-1].dts;const x=S+4*E+8;let k;try{k=new Uint8Array(x)}catch(e){return void this.observer.emit(Cd.ERROR,Cd.ERROR,{type:Ld.MUX_ERROR,details:Id.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:x,reason:`fail allocating video mdat ${x}`})}const A=new DataView(k.buffer);A.setUint32(0,x),k.set(fv.types.mdat,4);let R=!1,L=Number.POSITIVE_INFINITY,I=Number.POSITIVE_INFINITY,C=Number.NEGATIVE_INFINITY,P=Number.NEGATIVE_INFINITY;for(let e=0;e<o;e++){const t=s[e],r=t.units;let l,c=0;for(let e=0,t=r.length;e<t;e++){const t=r[e],n=t.data,i=t.data.byteLength;A.setUint32(f,i),f+=4,k.set(n,f),f+=i,c+=4+i}if(e<o-1)p=s[e+1].dts-t.dts,l=s[e+1].pts-t.pts;else{const r=this.config,a=e>0?t.dts-s[e-1].dts:w;if(l=e>0?t.pts-s[e-1].pts:w,r.stretchShortVideoTrack&&null!==this.nextAudioTs){const e=Math.floor(r.maxBufferHole*i),s=(n?g+n*i:this.nextAudioTs+u)-t.pts;s>e?(p=s-a,p<0?p=a:R=!0,this.log(`It is approximately ${s/90} ms to the next segment; using duration ${p/90} ms for the last video frame.`)):p=a}else p=a}const d=Math.round(t.pts-t.dts);L=Math.min(L,p),C=Math.max(C,p),I=Math.min(I,l),P=Math.max(P,l),a.push(wv(t.key,p,c,d))}if(a.length)if(yv){if(yv<70){const e=a[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(bv&&P-I<C-L&&w/C<.025&&0===a[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=c;for(let t=0,r=a.length;t<r;t++){const n=e+a[t].duration,i=e+a[t].cts;if(t<r-1){const e=n+a[t+1].cts;a[t].duration=e-i}else a[t].duration=t?a[t-1].duration:w;a[t].cts=0,e=n}}p=R||!p?w:p;const D=d+p;this.nextVideoTs=h=D-u,this.videoSampleDuration=p,this.isVideoContiguous=!0;const _={data1:fv.moof(e.sequenceNumber++,c,zd(e,{samples:a})),data2:k,startPTS:(g-u)/i,endPTS:(m+p-u)/i,startDTS:(c-u)/i,endDTS:h/i,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,_}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(e,t,r,n,i){const s=e.inputTimeScale,a=s/(e.samplerate?e.samplerate:s),o=this.getSamplesPerFrame(e),l=o*a,u=this._initPTS,c="mp3"===e.segmentCodec&&this.typeSupported.mpeg,d=[],h=void 0!==i;let f=e.samples,p=c?0:8,g=this.nextAudioTs||-1;const m=u.baseTime*s/u.timescale,v=m+t*s;if(this.isAudioContiguous=r=r||f.length&&g>0&&(n&&Math.abs(v-(g+m))<9e3||Math.abs(Sv(f[0].pts,v)-(g+m))<20*l),f.forEach(function(e){e.pts=Sv(e.pts,v)}),!r||g<0){const e=f.length;if(f=f.filter(e=>e.pts>=0),e!==f.length&&this.warn(`Removed ${f.length-e} of ${e} samples (initPTS ${m} / ${s})`),!f.length)return;g=0===i?0:n&&!h?Math.max(0,v-m):f[0].pts-m}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let r=0,n=g+m;r<f.length;r++){const i=f[r],a=i.pts,o=a-n,u=Math.abs(1e3*o/s);if(o<=-t*l&&h)0===r&&(this.warn(`Audio frame @ ${(a/s).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/s)} ms.`),this.nextAudioTs=g=a-m,n=a);else if(o>=t*l&&u<1e4&&h){let t=Math.round(o/l);for(n=a-t*l;n<0&&t&&l;)t--,n+=l;0===r&&(this.nextAudioTs=g=n-m),this.warn(`Injecting ${t} audio frames @ ${((n-m)/s).toFixed(3)}s due to ${Math.round(1e3*o/s)} ms gap.`);for(let s=0;s<t;s++){let t=dv.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);t||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),t=i.unit.subarray()),f.splice(r,0,{unit:t,pts:n}),n+=l,r++}}i.pts=n,n+=l}}let y,b=null,w=null,E=0,S=f.length;for(;S--;)E+=f[S].unit.byteLength;for(let t=0,n=f.length;t<n;t++){const n=f[t],i=n.unit;let s=n.pts;if(null!==w){d[t-1].duration=Math.round((s-w)/a)}else{if(r&&"aac"===e.segmentCodec&&(s=g+m),b=s,!(E>0))return;E+=p;try{y=new Uint8Array(E)}catch(e){return void this.observer.emit(Cd.ERROR,Cd.ERROR,{type:Ld.MUX_ERROR,details:Id.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:E,reason:`fail allocating audio mdat ${E}`})}if(!c){new DataView(y.buffer).setUint32(0,E),y.set(fv.types.mdat,4)}}y.set(i,p);const l=i.byteLength;p+=l,d.push(wv(!0,o,l,0)),w=s}const T=d.length;if(!T)return;const x=d[d.length-1];g=w-m,this.nextAudioTs=g+a*x.duration;const k=c?new Uint8Array(0):fv.moof(e.sequenceNumber++,b/a,zd({},e,{samples:d}));e.samples=[];const A=(b-m)/s,R=this.nextAudioTs/s,L={data1:k,data2:y,startPTS:A,endPTS:R,startDTS:A,endDTS:R,type:"audio",hasAudio:!0,hasVideo:!1,nb:T};return this.isAudioContiguous=!0,L}}function Sv(e,t){let r;if(null===t)return e;for(r=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=r;return e}function Tv(e,t,r,n){const i=e.samples.length;if(!i)return;const s=e.inputTimeScale;for(let a=0;a<i;a++){const i=e.samples[a];i.pts=Sv(i.pts-r.baseTime*s/r.timescale,t*s)/s,i.dts=Sv(i.dts-n.baseTime*s/n.timescale,t*s)/s}const a=e.samples;return e.samples=[],{samples:a}}function xv(e,t,r){const n=e.samples.length;if(!n)return;const i=e.inputTimeScale;for(let s=0;s<n;s++){const n=e.samples[s];n.pts=Sv(n.pts-r.baseTime*i/r.timescale,t*i)/i}e.samples.sort((e,t)=>e.pts-t.pts);const s=e.samples;return e.samples=[],{samples:s}}function kv(e,t,r=!1){return void 0!==(null==e?void 0:e.start)?(e.start+(r?e.duration:0))/e.timescale:t}function Av(e,t,r){const n=e.codec;if(n&&n.length>4)return n;if(t===hh){if("ec-3"===n||"ac-3"===n||"alac"===n)return n;if("fLaC"===n||"Opus"===n){return rf(n,!1)}return r.warn(`Unhandled audio codec "${n}" in mp4 MAP`),n||"mp4a"}return r.warn(`Unhandled video codec "${n}" in mp4 MAP`),n||"avc1"}try{vv=self.performance.now.bind(self.performance)}catch(e){vv=Date.now}const Rv=[{demux:class{constructor(e,t){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=t}resetTimeStamp(){}resetInitSegment(e,t,r,n){const i=this.videoTrack=Mm("video",1),s=this.audioTrack=Mm("audio",1),a=this.txtTrack=Mm("text",1);if(this.id3Track=Mm("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const o=Ch(e);if(o.video){const{id:e,timescale:t,codec:r,supplemental:n}=o.video;i.id=e,i.timescale=a.timescale=t,i.codec=r,i.supplemental=n}if(o.audio){const{id:e,timescale:t,codec:r}=o.audio;s.id=e,s.timescale=t,s.codec=r}a.id=Sh.text,i.sampleDuration=0,i.duration=s.duration=n}resetContiguity(){this.remainderData=null}static probe(e){return function(e){const t=e.byteLength;for(let r=0;r<t;){const n=kh(e,r);if(n>8&&109===e[r+4]&&111===e[r+5]&&111===e[r+6]&&102===e[r+7])return!0;r=n>1?r+n:t}return!1}(e)}demux(e,t){this.timeOffset=t;let r=e;const n=this.videoTrack,i=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=$h(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},r=Lh(e,["moof"]);if(r.length<2)return t.remainder=e,t;const n=r[r.length-1];return t.valid=e.slice(0,n.byteOffset-8),t.remainder=e.slice(n.byteOffset-8),t}(r);this.remainderData=t.remainder,n.samples=t.valid||new Uint8Array}else n.samples=r;const s=this.extractID3Track(n,t);return i.samples=Bh(t,n),{videoTrack:n,audioTrack:this.audioTrack,id3Track:s,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,r=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(t,this.timeOffset);return r.samples=Bh(e,t),{videoTrack:t,audioTrack:Mm(),id3Track:n,textTrack:Mm()}}extractID3Track(e,t){const r=this.id3Track;if(e.samples.length){const n=Lh(e.samples,["emsg"]);n&&n.forEach(e=>{const n=function(e){const t=e[0];let r="",n="",i=0,s=0,a=0,o=0,l=0,u=0;if(0===t){for(;"\0"!==Th(e.subarray(u,u+1));)r+=Th(e.subarray(u,u+1)),u+=1;for(r+=Th(e.subarray(u,u+1)),u+=1;"\0"!==Th(e.subarray(u,u+1));)n+=Th(e.subarray(u,u+1)),u+=1;n+=Th(e.subarray(u,u+1)),u+=1,i=kh(e,12),s=kh(e,16),o=kh(e,20),l=kh(e,24),u=28}else if(1===t){u+=4,i=kh(e,u),u+=4;const t=kh(e,u);u+=4;const s=kh(e,u);for(u+=4,a=2**32*t+s,Ad(a)||(a=Number.MAX_SAFE_INTEGER,Xd.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=kh(e,u),u+=4,l=kh(e,u),u+=4;"\0"!==Th(e.subarray(u,u+1));)r+=Th(e.subarray(u,u+1)),u+=1;for(r+=Th(e.subarray(u,u+1)),u+=1;"\0"!==Th(e.subarray(u,u+1));)n+=Th(e.subarray(u,u+1)),u+=1;n+=Th(e.subarray(u,u+1)),u+=1}return{schemeIdUri:r,value:n,timeScale:i,presentationTime:a,presentationTimeDelta:s,eventDuration:o,id:l,payload:e.subarray(u,e.byteLength)}}(e);if(Xm.test(n.schemeIdUri)){const e=Qm(n,t);let i=4294967295===n.eventDuration?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;i<=.001&&(i=Number.POSITIVE_INFINITY);const s=n.payload;r.samples.push({data:s,len:s.byteLength,dts:e,pts:e,type:_m.emsg,duration:i})}else if(this.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const e=Qm(n,t);r.samples.push({data:n.payload,len:n.payload.byteLength,dts:e,pts:e,type:_m.misbklv,duration:Number.POSITIVE_INFINITY})}})}return r}demuxSampleAes(e,t,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}},remux:class extends Hd{constructor(e,t,r,n){super("passthrough-remuxer",n),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 t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,r,n){this.audioCodec=t,this.videoCodec=r,this.generateInitSegment(e,n),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:r,videoCodec:n}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:i,video:s}=this.initData=Ch(e);if(t)!function(e,t){if(!e||!t)return;const r=t.keyId;r&&t.isCommonEncryption&&Nh(e,(e,t)=>{const n=e.subarray(8,24);n.some(e=>0!==e)||(Xd.log(`[eme] Patching keyId in 'enc${t?"a":"v"}>sinf>>tenc' box: ${eh(n)} -> ${eh(r)}`),e.set(r,8))})}(e,t);else{const e=i||s;null!=e&&e.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${e.codec}")!`)}i&&(r=Av(i,hh,this)),s&&(n=Av(s,fh,this));const a={};i&&s?a.audiovideo={container:"video/mp4",codec:r+","+n,supplemental:s.supplemental,encrypted:s.encrypted,initSegment:e,id:"main"}:i?a.audio={container:"audio/mp4",codec:r,encrypted:i.encrypted,initSegment:e,id:"audio"}:s?a.video={container:"video/mp4",codec:n,supplemental:s.supplemental,encrypted:s.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(e,t,r,n,i,s){var a,o;let{initPTS:l,lastEndTime:u}=this;const c={audio:void 0,video:void 0,text:n,id3:r,initSegment:void 0};kd(u)||(u=this.lastEndTime=i||0);const d=t.samples;if(!d.length)return c;const h={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(d),f=this.initData),null==(o=f)||!o.length)return this.warn("Failed to generate initSegment."),c;this.emitInitSegment&&(h.tracks=this.initTracks,this.emitInitSegment=!1);const p=function(e,t,r){const n={},i=Lh(e,["moof","traf"]);for(let e=0;e<i.length;e++){const s=i[e],a=Lh(s,["tfhd"])[0],o=kh(a,4),l=t[o];if(!l)continue;n[o]||(n[o]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const u=n[o],c=Lh(s,["tfdt"])[0];if(c){const e=c[0];let t=kh(c,4);1===e&&(t===wh?r.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(t*=wh+1,t+=kh(c,8))),kd(t)&&(!kd(u.start)||t<u.start)&&(u.start=t)}const d=l.default,h=kh(a,0)|(null==d?void 0:d.flags);let f=(null==d?void 0:d.duration)||0;8&h&&(f=kh(a,2&h?12:8));const p=Lh(s,["trun"]);let g=u.start||0,m=0,v=f;for(let e=0;e<p.length;e++){const t=p[e],r=kh(t,4),n=u.sampleCount;u.sampleCount+=r;const i=1&t[3],s=4&t[3],a=1&t[2],o=2&t[2],l=4&t[2],c=8&t[2];let d=8,h=r;for(i&&(d+=4),s&&r&&(1&t[d+1]||void 0!==u.keyFrameIndex||(u.keyFrameIndex=n),d+=4,a?(v=kh(t,d),d+=4):v=f,o&&(d+=4),c&&(d+=4),g+=v,m+=v,h--);h--;)a?(v=kh(t,d),d+=4):v=f,o&&(d+=4),l&&(1&t[d+1]||void 0===u.keyFrameIndex&&(u.keyFrameIndex=u.sampleCount-(h+1),u.keyFrameStart=g),d+=4),c&&(d+=4),g+=v,m+=v;!m&&f&&(m+=f*r)}u.duration+=m}if(!Object.keys(n).some(e=>n[e].duration)){let t=1/0,r=0;const i=Lh(e,["sidx"]);for(let e=0;e<i.length;e++){const n=Ih(i[e]);if(null!=n&&n.references){t=Math.min(t,n.earliestPresentationTime/n.timescale);const e=n.references.reduce((e,t)=>e+t.info.duration||0,0);r=Math.max(r,e+n.earliestPresentationTime/n.timescale)}}r&&kd(r)&&Object.keys(n).forEach(e=>{n[e].duration||(n[e].duration=r*n[e].timescale-n[e].start)})}return n}(d,f,this),g=f.audio?p[f.audio.id]:null,m=f.video?p[f.video.id]:null,v=kv(m,1/0),y=kv(g,1/0),b=kv(m,0,!0),w=kv(g,0,!0);let E=i,S=0;const T=g&&(!m||!l&&y<v||l&&l.trackId===f.audio.id),x=T?g:m;if(x){const e=x.timescale,t=x.start-i*e,r=T?f.audio.id:f.video.id;E=x.start/e,S=T?w-y:b-v,!s&&l||!function(e,t,r,n){if(null===e)return!0;const i=Math.max(n,1),s=t-e.baseTime/e.timescale;return Math.abs(s-r)>i}(l,E,i,S)&&e===l.timescale||(l&&this.warn(`Timestamps at playlist time: ${s?"":"~"}${i} ${t/e} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${E-i} (${t}/${e}) trackId: ${r}`),l=null,h.initPTS=t,h.timescale=e,h.trackId=r)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${i}`);l?(h.initPTS=l.baseTime,h.timescale=l.timescale,h.trackId=l.trackId):(h.timescale&&void 0!==h.trackId&&void 0!==h.initPTS||(this.warn("Could not set initPTS"),h.initPTS=E,h.timescale=1,h.trackId=-1),this.initPTS=l={baseTime:h.initPTS,timescale:h.timescale,trackId:h.trackId});const k=E-l.baseTime/l.timescale,A=k+S;S>0?this.lastEndTime=A:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const R=!!f.audio,L=!!f.video;let I="";R&&(I+="audio"),L&&(I+="video");const C={data1:d,startPTS:k,startDTS:k,endPTS:A,endDTS:A,type:I,hasAudio:R,hasVideo:L,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};c.audio=R&&!L?C:void 0,c.video=L?C:void 0;const P=null==m?void 0:m.sampleCount;if(P){const e=m.keyFrameIndex,t=-1!==e;C.nb=P,C.dropped=0===e||this.isVideoContiguous?0:t?e:P,C.independent=t,C.firstKeyFrame=e,t&&m.keyFrameStart&&(C.firstKeyFramePTS=(m.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(c.independent=t),this.isVideoContiguous||(this.isVideoContiguous=t),C.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${e}/${P} dropped: ${C.dropped} start: ${C.firstKeyFramePTS||"NA"}`)}return c.initSegment=h,c.id3=Tv(r,i,l,l),n.samples.length&&(c.text=xv(n,i,l)),c}}},{demux:iv,remux:Ev},{demux:class extends Om{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,r,n){super.resetInitSegment(e,t,r,n),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const r=gm(e,0);let n=(null==r?void 0:r.length)||0;if(Wm(e,n))return!1;for(let r=e.length;n<r;n++)if(wm(e,n))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&mm(e,t)&&ym(e,t)<=e.length-t}(e,t)}appendFrame(e,t,r){Em(e,this.observer,t,r,e.manifestCodec);const n=Tm(e,t,r,this.basePTS,this.frameIndex);if(n&&0===n.missing)return n}},remux:Ev},{demux:class extends Om{resetInitSegment(e,t,r,n){super.resetInitSegment(e,t,r,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=gm(e,0);let r=(null==t?void 0:t.length)||0;if(t&&11===e[r]&&119===e[r+1]&&void 0!==Dm(t)&&Km(e,r)<=16)return!1;for(let t=e.length;r<t;r++)if(Wm(e,r))return Xd.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return Hm(e,t)&&4<=e.length-t}(e,t)}appendFrame(e,t,r){if(null!==this.basePTS)return jm(e,t,r,this.basePTS,this.frameIndex)}},remux:Ev}];Rv.splice(2,0,{demux:Ym,remux:Ev});class Lv{constructor(e,t,r,n,i,s){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=t,this.config=r,this.id=i,this.logger=s}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,r,n){const i=r.transmuxing;i.executeStart=vv();let s=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:o}=this;n&&(this.currentTransmuxState=n);const{contiguous:l,discontinuity:u,trackSwitch:c,accurateTimeOffset:d,timeOffset:h,initSegmentChange:f}=n||a,{audioCodec:p,videoCodec:g,defaultInitPts:m,duration:v,initSegmentData:y}=o,b=function(e,t){let r=null;e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(r=t);return r}(s,t);if(b&&Up(b.method)){const e=this.getDecrypter(),t=zp(b.method);if(!e.isSync())return this.asyncResult=!0,this.decryptionPromise=e.webCryptoDecrypt(s,b.key.buffer,b.iv.buffer,t).then(e=>{const t=this.push(e,null,r);return this.decryptionPromise=null,t}),this.decryptionPromise;{let n=e.softwareDecrypt(s,b.key.buffer,b.iv.buffer,t);if(r.part>-1){const t=e.flush();n=t?t.buffer:t}if(!n)return i.executeEnd=vv(),Iv(r);s=new Uint8Array(n)}}const w=this.needsProbing(u,c);if(w){const e=this.configureTransmuxer(s);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(Cd.ERROR,Cd.ERROR,{type:Ld.MEDIA_ERROR,details:Id.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),i.executeEnd=vv(),Iv(r)}(u||c||f||w)&&this.resetInitSegment(y,p,g,v,t),(u||f||w)&&this.resetInitialTimestamp(m),l||this.resetContiguity();const E=this.transmux(s,b,h,d,r);this.asyncResult=Cv(E);const S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,i.executeEnd=vv(),E}flush(e){const t=e.transmuxing;t.executeStart=vv();const{decrypter:r,currentTransmuxState:n,decryptionPromise:i}=this;if(i)return this.asyncResult=!0,i.then(()=>this.flush(e));const s=[],{timeOffset:a}=n;if(r){const t=r.flush();t&&s.push(this.push(t.buffer,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l){t.executeEnd=vv();const r=[Iv(e)];return this.asyncResult?Promise.resolve(r):r}const u=o.flush(a);return Cv(u)?(this.asyncResult=!0,u.then(t=>(this.flushRemux(s,t,e),s))):(this.flushRemux(s,u,e),this.asyncResult?Promise.resolve(s):s)}flushRemux(e,t,r){const{audioTrack:n,videoTrack:i,id3Track:s,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${r.sn}${r.part>-1?" part: "+r.part:""} of ${this.id===Od?"level":"track"} ${r.level}`);const u=this.remuxer.remux(n,i,s,a,l,o,!0,this.id);e.push({remuxResult:u,chunkMeta:r}),r.transmuxing.executeEnd=vv()}resetInitialTimestamp(e){const{demuxer:t,remuxer:r}=this;t&&r&&(t.resetTimeStamp(e),r.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,r,n,i){const{demuxer:s,remuxer:a}=this;s&&a&&(s.resetInitSegment(e,t,r,n),a.resetInitSegment(e,t,r,i))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,r,n,i){let s;return s=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,r,n,i):this.transmuxUnencrypted(e,r,n,i),s}transmuxUnencrypted(e,t,r,n){const{audioTrack:i,videoTrack:s,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(i,s,a,o,t,r,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,r,n,i){return this.demuxer.demuxSampleAes(e,t,r).then(e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,r,n,!1,this.id),chunkMeta:i}))}configureTransmuxer(e){const{config:t,observer:r,typeSupported:n}=this;let i;for(let t=0,r=Rv.length;t<r;t++){var s;if(null!=(s=Rv[t].demux)&&s.probe(e,this.logger)){i=Rv[t];break}}if(!i)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=i.remux,u=i.demux;o&&o instanceof l||(this.remuxer=new l(r,t,n,this.logger)),a&&a instanceof u||(this.demuxer=new u(r,t,n,this.logger),this.probe=u.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new mp(this.config)),e}}const Iv=e=>({remuxResult:{},chunkMeta:e});function Cv(e){return"then"in e&&e.then instanceof Function}class Pv{constructor(e,t,r,n,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=t,this.initSegmentData=r,this.duration=n,this.defaultInitPts=i||null}}class Dv{constructor(e,t,r,n,i,s){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=t,this.accurateTimeOffset=r,this.trackSwitch=n,this.timeOffset=i,this.initSegmentChange=s}}let _v=0;class Mv{constructor(e,t,r,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=_v++,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=e=>{const t=e.data,r=this.hls;if(r&&null!=t&&t.event&&t.instanceNo===this.instanceNo)switch(t.event){case"init":{var n;const e=null==(n=this.workerContext)?void 0:n.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":r.logger[t.data.logType]&&r.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,r.trigger(t.event,t.data)}},this.onWorkerError=e=>{if(!this.hls)return;const t=new Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(Cd.ERROR,{type:Ld.OTHER_ERROR,details:Id.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})};const i=e.config;this.hls=e,this.id=t,this.useWorker=!!i.enableWorker,this.onTransmuxComplete=r,this.onFlush=n;const s=(e,t)=>{(t=t||{}).frag=this.frag||void 0,e===Cd.ERROR&&(t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new um,this.observer.on(Cd.FRAG_DECRYPTED,s),this.observer.on(Cd.ERROR,s);const a=of(i.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const r=this.hls.logger;if(i.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{i.workerPath?(r.log(`loading Web Worker ${i.workerPath} for "${t}"`),this.workerContext=function(e){const t=dm[e];if(t)return t.clientCount++,t;const r=new self.URL(e,self.location.href).href,n={worker:new self.Worker(r),scriptURL:r,clientCount:1};return dm[e]=n,n}(i.workerPath)):(r.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){const e=dm[cm];if(e)return e.clientCount++,e;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),r=self.URL.createObjectURL(t),n={worker:new self.Worker(r),objectURL:r,clientCount:1};return dm[cm]=n,n}());const{worker:e}=this.workerContext;e.addEventListener("message",this.onWorkerMessage),e.addEventListener("error",this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:Af(i)})}catch(n){r.warn(`Error setting up "${t}" Web Worker, fallback to inline`,n),this.terminateWorker(),this.error=null,this.transmuxer=new Lv(this.observer,a,i,"",t,e.logger)}return}}this.transmuxer=new Lv(this.observer,a,i,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=_v++;const t=this.hls.config,r=of(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:r,id:this.id,config:Af(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){const t=dm[e||cm];if(t&&1===t.clientCount--){const{worker:r,objectURL:n}=t;delete dm[e||cm],n&&self.URL.revokeObjectURL(n),r.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const e=this.transmuxer;e&&(e.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,t,r,n,i,s,a,o,l,u){var c,d;l.transmuxing.start=self.performance.now();const{instanceNo:h,transmuxer:f}=this,p=s?s.start:i.start,g=i.decryptdata,m=this.frag,v=!(m&&i.cc===m.cc),y=!(m&&l.level===m.level),b=m?l.sn-m.sn:-1,w=this.part?l.part-this.part.index:-1,E=0===b&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),S=!y&&(1===b||0===b&&(1===w||E&&w<=0)),T=self.performance.now();(y||b||0===i.stats.parsing.start)&&(i.stats.parsing.start=T),!s||!w&&S||(s.stats.parsing.start=T);const x=!(m&&(null==(c=i.initSegment)?void 0:c.url)===(null==(d=m.initSegment)?void 0:d.url)),k=new Dv(v,S,o,y,p,x);if(!S||v||x){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===Od?"level":"track"}: ${l.level} id: ${l.id}\n discontinuity: ${v}\n trackSwitch: ${y}\n contiguous: ${S}\n accurateTimeOffset: ${o}\n timeOffset: ${p}\n initSegmentChange: ${x}`);const e=new Pv(r,n,t,a,u);this.configureTransmuxer(e)}if(this.frag=i,this.part=s,this.workerContext)this.workerContext.worker.postMessage({instanceNo:h,cmd:"demux",data:e,decryptdata:g,chunkMeta:l,state:k},e instanceof ArrayBuffer?[e]:[]);else if(f){const t=f.push(e,g,l,k);Cv(t)?t.then(e=>{this.handleTransmuxComplete(e)}).catch(e=>{this.transmuxerError(e,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:r}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(r){const t=r.flush(e);Cv(t)?t.then(t=>{this.handleFlushResult(t,e)}).catch(t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")}):this.handleFlushResult(t,e)}}transmuxerError(e,t,r){this.hls&&(this.error=e,this.hls.trigger(Cd.ERROR,{type:Ld.MEDIA_ERROR,details:Id.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:r}))}handleFlushResult(e,t){e.forEach(e=>{this.handleTransmuxComplete(e)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:r}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):r&&r.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}class Ov extends Hd{constructor(e,t){super(t,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(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,r){const n=null==t?void 0:t.renditionReports;if(n){let i=-1;for(let r=0;r<n.length;r++){const s=n[r];let a;try{a=new self.URL(s.URI,t.url).href}catch(e){this.warn(`Could not construct new URL for Rendition Report: ${e}`),a=s.URI||""}if(a===e){i=r;break}a===e.substring(0,a.length)&&(i=r)}if(-1!==i){const e=n[i],s=parseInt(e["LAST-MSN"])||t.lastPartSn;let a=parseInt(e["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const e=Math.min(t.age-t.partTarget,t.targetduration);a>=0&&e>t.partTarget&&(a+=1)}const o=r&&Ef(r);return new Sf(s,a>=0?a:void 0,o)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}return e}playlistLoaded(e,t,r){const{details:n,stats:i}=t,s=self.performance.now(),a=i.loading.first?Math.max(0,s-i.loading.first):0;n.advancedDateTime=Date.now()-a;const o=this.hls.config.timelineOffset;if(o!==n.appliedTimelineOffset){const e=Math.max(o||0,0);n.appliedTimelineOffset=e,n.fragments.forEach(t=>{t.setStart(t.playlistOffset+e)})}if(n.live||null!=r&&r.live){const o="levelInfo"in t?t.levelInfo:t.track;if(n.reloaded(r),r&&n.fragments.length>0){Ag(r,n,this);const e=n.playlistParsingError;if(e){this.warn(e);const r=this.hls;if(!r.config.ignorePlaylistParsingErrors){var l;const{networkDetails:s}=t;return void r.trigger(Cd.ERROR,{type:Ld.NETWORK_ERROR,details:Id.LEVEL_PARSING_ERROR,fatal:!1,url:n.url,error:e,reason:e.message,level:t.level||void 0,parent:null==(l=n.fragments[0])?void 0:l.type,networkDetails:s,stats:i})}n.playlistParsingError=null}}-1===n.requestScheduled&&(n.requestScheduled=i.loading.start);const u=this.hls.mainForwardBufferInfo,c=u?u.end-u.len:0,d=Cg(n,1e3*(n.edge-c));if(n.requestScheduled+d<s?n.requestScheduled=s:n.requestScheduled+=d,this.log(`live playlist ${e} ${n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:n.updated?"UPDATED":"MISSED"}`),!this.canLoad||!n.live)return;let h,f,p;if(n.canBlockReload&&n.endSN&&n.advanced){const e=this.hls.config.lowLatencyMode,i=n.lastPartSn,a=n.endSN,l=n.lastPartIndex,u=i===a;-1!==l?u?(f=a+1,p=e?0:l):(f=i,p=e?l+1:n.maxPartIndex):f=a+1;const c=n.age,d=c+n.ageHeader;let g=Math.min(d-n.partTarget,1.5*n.targetduration);if(g>0){if(d>3*n.targetduration)this.log(`Playlist last advanced ${c.toFixed(2)}s ago. Omitting segment and part directives.`),f=void 0,p=void 0;else if(null!=r&&r.tuneInGoal&&d-n.partTarget>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${g} with playlist age: ${n.age}`),g=0;else{const e=Math.floor(g/n.targetduration);if(f+=e,void 0!==p){p+=Math.round(g%n.targetduration/n.partTarget)}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${c.toFixed(2)}s goal: ${g} skip sn ${e} to part ${p}`)}n.tuneInGoal=g}if(h=this.getDeliveryDirectives(n,t.deliveryDirectives,f,p),e||!u)return n.requestScheduled=s,void this.loadingPlaylist(o,h)}else(n.canBlockReload||n.canSkipUntil)&&(h=this.getDeliveryDirectives(n,t.deliveryDirectives,f,p));h&&void 0!==f&&n.canBlockReload&&(n.requestScheduled=i.loading.first+Math.max(d-2*a,d/2)),this.scheduleLoading(o,h,n)}else this.clearTimer()}scheduleLoading(e,t,r){const n=r||e.details;if(!n)return void this.loadingPlaylist(e,t);const i=self.performance.now(),s=n.requestScheduled;if(i>=s)return void this.loadingPlaylist(e,t);const a=s-i;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),a)}getDeliveryDirectives(e,t,r,n){let i=Ef(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,n=t.part,i=yf),new Sf(r,n,i)}checkRetry(e){const t=e.details,r=Uf(e),n=e.errorAction,{action:i,retryCount:s=0,retryConfig:a}=n||{},o=!!n&&!!a&&(i===Qf||!n.resolved&&i===qf);if(o){var l;if(s>=a.maxNumRetry)return!1;if(r&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${s+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=Hf(a,s);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),e),this.warn(`Retrying playlist loading ${s+1}/${a.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,n.resolved=!0}return o}}function Nv(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Fv(e[r].attrs,t[r].attrs))return!1;return!0}function Fv(e,t,r){const n=e["STABLE-RENDITION-ID"];return n&&!r?n===t["STABLE-RENDITION-ID"]:!(r||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(r=>e[r]!==t[r])}function $v(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}class Bv{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,r){if(null===this.queues||null===this.tracks)return;const n=this.queues[t];n.push(e),1!==n.length||r||this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const r={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(r,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const r={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(r)}})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const r=null==(t=e[0])?void 0:t.label;"async-blocker"!==r&&"async-blocker-prepend"!==r||(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(null===this.queues)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(null===this.queues||null===this.tracks)return;const t=this.queues[e];if(t.length){const n=t[0];try{n.execute()}catch(t){var r;if(n.onError(t),null===this.queues||null===this.tracks)return;const i=null==(r=this.tracks[e])?void 0:r.buffer;null!=i&&i.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return null===e||null===t?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(e){var t,r;return null!=(t=this.queues)&&t[e]||null!=(r=this.tracks)&&r[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const r=null==(t=this.tracks)?void 0:t[e],n=null==r?void 0:r.buffer;return n?`SourceBuffer${n.updating?" updating":""}${r.ended?" ended":""}${r.ending?" ending":""}`:"none"}listOps(e){var t;return(null==(t=this.queues)?void 0:t[e].map(e=>e.label).join(", "))||""}}const Uv=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,zv="HlsJsTrackRemovedError";class jv extends Error{constructor(e){super(e),this.name=zv}}function Gv(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach(t=>{e.removeChild(t)})}function Hv(e){return"audio"===e?1:0}class Vv{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(Cd.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(Cd.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Cd.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Cd.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Cd.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Cd.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(Cd.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(Cd.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Cd.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Cd.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Cd.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Cd.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const r=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,r.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&kd(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const e=this.hls.levels;if(e.length){const t=this.hls,r=this.getMaxLevel(e.length-1);r!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${r}: ${e[r].height}p@${e[r].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=r,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const r=t.filter((t,r)=>this.isLevelAllowed(t)&&r<=e);return this.clientRect=null,Vv.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,t={width:0,height:0};if(e){const r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t}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(e){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height)}static getMaxLevelByMediaSize(e,t,r){if(null==e||!e.length)return-1;const n=(e,t)=>!t||(e.width!==t.width||e.height!==t.height);let i=e.length-1;const s=Math.max(t,r);for(let t=0;t<e.length;t+=1){const r=e[t];if((r.width>=s||r.height>=s)&&n(r,e[t+1])){i=t;break}}return i}}const Wv={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Kv={HLS:"h"};class Yv{constructor(e,t){Array.isArray(e)&&(e=e.map(e=>e instanceof Yv?e:new Yv(e))),this.value=e,this.params=t}}function qv(e,t,r,n){return new Error(`failed to ${e} "${i=t,Array.isArray(i)?JSON.stringify(i):i instanceof Map?"Map{}":i instanceof Set?"Set{}":"object"==typeof i?JSON.stringify(i):String(i)}" as ${r}`,{cause:n});var i}function Xv(e,t,r){return qv("serialize",e,t,r)}class Qv{constructor(e){this.description=e}}const Zv="Bare Item";function Jv(e){if(!1===ArrayBuffer.isView(e))throw Xv(e,"Byte Sequence");return`:${t=e,btoa(String.fromCharCode(...t))}:`;var t}function ey(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw Xv(e,"Integer");return e.toString()}function ty(e,t){if(e<0)return-ty(-e,t);const r=Math.pow(10,t);if(Math.abs(e*r%1-.5)<Number.EPSILON){const t=Math.floor(e*r);return(t%2==0?t:t+1)/r}return Math.round(e*r)/r}function ry(e){const t=ty(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw Xv(e,"Decimal");const r=t.toString();return r.includes(".")?r:`${r}.0`}const ny=/[\x00-\x1f\x7f]+/;function iy(e){const t=(r=e).description||r.toString().slice(7,-1);var r;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw Xv(t,"Token");return t}function sy(e){switch(typeof e){case"number":if(!kd(e))throw Xv(e,Zv);return Number.isInteger(e)?ey(e):ry(e);case"string":return function(e){if(ny.test(e))throw Xv(e,"String");return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(e);case"symbol":return iy(e);case"boolean":return function(e){if("boolean"!=typeof e)throw Xv(e,"Boolean");return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return`@${ey(e.getTime()/1e3)}`}(e);if(e instanceof Uint8Array)return Jv(e);if(e instanceof Qv)return iy(e);default:throw Xv(e,Zv)}}function ay(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw Xv(e,"Key");return e}function oy(e){return null==e?"":Object.entries(e).map(([e,t])=>!0===t?`;${ay(e)}`:`;${ay(e)}=${sy(t)}`).join("")}function ly(e){return e instanceof Yv?`${sy(e.value)}${oy(e.params)}`:sy(e)}function uy(e,t={whitespace:!0}){if("object"!=typeof e||null==e)throw Xv(e,"Dict");const r=e instanceof Map?e.entries():Object.entries(e),n=(null==t?void 0:t.whitespace)?" ":"";return Array.from(r).map(([e,t])=>{t instanceof Yv==!1&&(t=new Yv(t));let r=ay(e);var n;return!0===t.value?r+=oy(t.params):(r+="=",Array.isArray(t.value)?r+=`(${(n=t).value.map(ly).join(" ")})${oy(n.params)}`:r+=ly(t)),r}).join(`,${n}`)}function cy(e,t){return uy(e,t)}const dy="CMCD-Object",hy="CMCD-Request",fy="CMCD-Session",py="CMCD-Status",gy={br:dy,ab:dy,d:dy,ot:dy,tb:dy,tpb:dy,lb:dy,tab:dy,lab:dy,url:dy,pb:hy,bl:hy,tbl:hy,dl:hy,ltc:hy,mtp:hy,nor:hy,nrr:hy,rc:hy,sn:hy,sta:hy,su:hy,ttfb:hy,ttfbb:hy,ttlb:hy,cmsdd:hy,cmsds:hy,smrt:hy,df:hy,cs:hy,ts:hy,cid:fy,pr:fy,sf:fy,sid:fy,st:fy,v:fy,msd:fy,bs:py,bsd:py,cdn:py,rtp:py,bg:py,pt:py,ec:py,e:py},my=hy;function vy(e,t){const r={};if(!e)return r;const n=Object.keys(e),i=t?(s=t,Object.keys(s).reduce((e,t)=>{var r;return null===(r=s[t])||void 0===r||r.forEach(r=>e[r]=t),e},{})):{};var s;return n.reduce((t,r)=>{var n;const s=gy[r]||i[r]||my;return(null!==(n=t[s])&&void 0!==n?n:t[s]={})[r]=e[r],t},r)}const yy="event";const by=e=>Math.round(e),wy=(e,t)=>Array.isArray(e)?e.map(e=>wy(e,t)):e instanceof Yv&&"string"==typeof e.value?new Yv(wy(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){const r=new URL(e),n=new URL(t);if(r.origin!==n.origin)return e;const i=r.pathname.split("/").slice(1),s=n.pathname.split("/").slice(1,-1);for(;i[0]===s[0];)i.shift(),s.shift();for(;s.length;)s.shift(),i.unshift("..");return i.join("/")+r.search+r.hash}(e,t.baseUrl)),1===t.version?encodeURIComponent(e):e),Ey=e=>100*by(e/100),Sy={br:by,d:by,bl:Ey,dl:Ey,mtp:Ey,nor:(e,t)=>{let r=e;return t.version>=2&&(e instanceof Yv&&"string"==typeof e.value?r=new Yv([e]):"string"==typeof e&&(r=[e])),wy(r,t)},rtp:Ey,tb:by},Ty="request",xy="response",ky=["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"],Ay=["e"],Ry=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Ly(e){return Ry.test(e)}const Iy=["d","dl","nor","ot","rtp","su"];const Cy=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];const Py=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function Dy(e){return Py.includes(e)||Ly(e)}const _y={[xy]:function(e){return ky.includes(e)||Iy.includes(e)||Cy.includes(e)||Ly(e)},[yy]:function(e){return ky.includes(e)||Ay.includes(e)||Ly(e)},[Ty]:function(e){return ky.includes(e)||Iy.includes(e)||Ly(e)}};function My(e,t={}){const r={};if(null==e||"object"!=typeof e)return r;const n=t.version||e.v||1,i=t.reportingMode||Ty,s=1===n?Dy:_y[i];let a=Object.keys(e).filter(s);const o=t.filter;"function"==typeof o&&(a=a.filter(o));const l=i===xy||i===yy;l&&!a.includes("ts")&&a.push("ts"),n>1&&!a.includes("v")&&a.push("v");const u=zd({},Sy,t.formatters),c={version:n,reportingMode:i,baseUrl:t.baseUrl};return a.sort().forEach(t=>{let i=e[t];const s=u[t];if("function"==typeof s&&(i=s(i,c)),"v"===t){if(1===n)return;i=n}"pr"==t&&1===i||(l&&"ts"===t&&!kd(i)&&(i=Date.now()),function(e){return"number"==typeof e?kd(e):null!=e&&""!==e&&!1!==e}(i)&&(function(e){return["ot","sf","st","e","sta"].includes(e)}(t)&&"string"==typeof i&&(i=new Qv(i)),r[t]=i))}),r}function Oy(e,t,r){return zd(e,function(e,t={}){const r={};if(!e)return r;const n=vy(My(e,t),null==t?void 0:t.customHeaderMap);return Object.entries(n).reduce((e,[t,r])=>{const n=cy(r,{whitespace:!1});return n&&(e[t]=n),e},r)}(t,r))}function Ny(e,t={}){if(!e)return"";const r=function(e,t={}){return e?cy(My(e,t),{whitespace:!1}):""}(e,t);return encodeURIComponent(r)}const Fy=/CMCD=[^&#]+/;function $y(e,t,r){const n=function(e,t={}){return e?`CMCD=${Ny(e,t)}`:""}(t,r);if(!n)return e;if(Fy.test(e))return e.replace(Fy,n);const i=e.includes("?")?"&":"?";return`${e}${i}${n}`}function By(e,t,r,n){e&&Object.keys(t).forEach(i=>{const s=e.filter(e=>e.groupId===i).map(e=>{const s=zd({},e);return s.details=void 0,s.attrs=new _p(s.attrs),s.url=s.attrs.URI=Uy(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),s.groupId=s.attrs["GROUP-ID"]=t[i],s.attrs["PATHWAY-ID"]=n,s});e.push(...s)})}function Uy(e,t,r,n){const{HOST:i,PARAMS:s,[r]:a}=n;let o;t&&(o=null==a?void 0:a[t],o&&(e=o));const l=new self.URL(e);return i&&!o&&(l.host=i),s&&Object.keys(s).sort().forEach(e=>{e&&l.searchParams.set(e,s[e])}),l.href}class zy extends Hd{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=zy.CDMCleanupPromise?[zy.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=e=>{const{initDataType:t,initData:r}=e,n=`"${e.type}" event: init data type: "${t}"`;if(this.debug(n),null!==r){if(!this.keyFormatPromise){let e=Object.keys(this.keySystemAccessPromises);e.length||(e=eg(this.config));const t=e.map(Jp).filter(e=>!!e);this.keyFormatPromise=this.getKeyFormatPromise(t)}this.keyFormatPromise.then(i=>{const s=Zp(i);if("sinf"!==t||s!==Kp.FAIRPLAY)return void this.log(`Ignoring "${e.type}" event with init data type: "${t}" for selected key-system ${s}`);let a;try{const e=Th(new Uint8Array(r)),t=Fh(jp(JSON.parse(e).sinf));if(!t)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(t.subarray(8,24))}catch(e){return void this.warn(`${n} Failed to parse sinf: ${e}`)}const o=eh(a),{keyIdToKeySessionPromise:l,mediaKeySessions:u}=this;let c=l[o];for(let e=0;e<u.length;e++){const n=u[e],i=n.decryptdata;if(!i.keyId)continue;const s=eh(i.keyId);if($p(a,i.keyId)||-1!==i.uri.replace(/-/g,"").indexOf(o)){if(c=l[s],!c)continue;if(i.pssh)break;delete l[s],i.pssh=new Uint8Array(r),i.keyId=a,c=l[o]=c.then(()=>this.generateRequestWithPreferredKeySession(n,t,r,"encrypted-event-key-match")),c.catch(e=>this.handleError(e));break}}c||this.handleError(new Error(`Key ID ${o} not encountered in playlist. Key-system sessions ${u.length}.`))}).catch(e=>this.handleError(e))}},this.onWaitingForKey=e=>{this.log(`"${e.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(Cd.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Cd.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(Cd.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Cd.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(Cd.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(Cd.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Cd.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(Cd.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Cd.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(Cd.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:r}=this.config,n=null==t?void 0:t[e];return n?n.licenseUrl:e===Kp.WIDEVINE&&r?r:void 0}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(void 0===t)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,r=null==t?void 0:t[e];if(r)return r.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,r=(e,t,r)=>!!e&&r.indexOf(e)===t,n=t.map(e=>e.audioCodec).filter(r),i=t.map(e=>e.videoCodec).filter(r);return n.length+i.length===0&&i.push("avc1.42e01e"),new Promise((t,r)=>{const s=e=>{const a=e.shift();this.getMediaKeysPromise(a,n,i).then(e=>t({keySystem:a,mediaKeys:e})).catch(t=>{e.length?s(e):r(t instanceof Hy?t:new Hy({type:Ld.KEY_SYSTEM_ERROR,details:Id.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};s(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:r}=this.config;if("function"!=typeof r){let e=`Configured requestMediaKeySystemAccess is not a function ${r}`;return null===tg&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(e))}return r(e,t)}getMediaKeysPromise(e,t,r){var n;const i=function(e,t,r,n){let i;switch(e){case Kp.FAIRPLAY:i=["cenc","sinf"];break;case Kp.WIDEVINE:case Kp.PLAYREADY:i=["cenc"];break;case Kp.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return function(e,t,r,n){return[{initDataTypes:e,persistentState:n.persistentState||"optional",distinctiveIdentifier:n.distinctiveIdentifier||"optional",sessionTypes:n.sessionTypes||[n.sessionType||"temporary"],audioCapabilities:t.map(e=>({contentType:`audio/mp4; codecs=${e}`,robustness:n.audioRobustness||"",encryptionScheme:n.audioEncryptionScheme||null})),videoCapabilities:r.map(e=>({contentType:`video/mp4; codecs=${e}`,robustness:n.videoRobustness||"",encryptionScheme:n.videoEncryptionScheme||null}))}]}(i,t,r,n)}(e,t,r,this.config.drmSystemOptions||{});let s=this.keySystemAccessPromises[e],a=null==(n=s)?void 0:n.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${Af(i)}`),a=this.requestMediaKeySystemAccess(e,i);const t=s=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)}),a.then(r=>{this.log(`Access for key-system "${r.keySystem}" obtained`);const n=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const i=t.mediaKeys=r.createMediaKeys().then(r=>(this.log(`Media-keys created for "${e}"`),t.hasMediaKeys=!0,n.then(t=>t?this.setMediaKeysServerCertificate(r,e,t):r)));return i.catch(t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)}),i})}return a.then(()=>s.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:r}){this.log(`Creating key-system session "${t}" keyId: ${eh(e.keyId||[])} keyUri: ${e.uri}`);const n=r.createSession(),i={decryptdata:e,keySystem:t,mediaKeys:r,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(i),i}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const r=this.createMediaKeySessionContext(e),n=jy(t),i="cenc";this.keyIdToKeySessionPromise[n]=this.generateRequestWithPreferredKeySession(r,i,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyId ${eh(e.decryptdata.keyId||[])}\n } (data length: ${t.byteLength})`),r.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>Jp(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:e,mediaKeys:t})=>this.attemptSetMediaKeys(e,t))}selectKeySystem(e){return new Promise((t,r)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:e})=>{const n=Jp(e);n?t(n):r(new Error(`Unable to find format for key-system "${e}"`))}).catch(r)})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=eg(this.config),r=e.map(Zp).filter(e=>!!e&&-1!==t.indexOf(e));return this.selectKeySystem(r)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let r=0;r<t.length;r++){const n=Gy(e,t[r]);if(n)return n}}loadKey(e){const t=e.keyInfo.decryptdata,r=jy(t),n=this.bannedKeyIds[r];if(n||"internal-error"===this.getKeyStatus(t)){const r=Vy(n||"internal-error",t);return this.handleError(r,e.frag),Promise.reject(r)}const i=`(keyId: ${r} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${i}`);const s=this.keyIdToKeySessionPromise[r];if(!s){const n=this.getKeySystemForKeyPromise(t).then(({keySystem:r,mediaKeys:n})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${i}`),this.attemptSetMediaKeys(r,n).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:r,mediaKeys:n,decryptdata:t}))))).then(e=>{const r=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(e,"cenc",r,"playlist-key")});return n.catch(t=>this.handleError(t,e.frag)),this.keyIdToKeySessionPromise[r]=n,n}return s.catch(r=>{if(r instanceof Hy){const n=Gd({},r.data);"internal-error"===this.getKeyStatus(t)&&(n.decryptdata=t);const i=new Hy(n,r.message);this.handleError(i,e.frag)}}),s}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Hy){t&&(e.data.frag=t);const r=e.data.decryptdata;this.error(`${e.message}${r?` (${eh(r.keyId||[])})`:""}`),this.hls.trigger(Cd.ERROR,e.data)}else this.error(e.message),this.hls.trigger(Cd.ERROR,{type:Ld.KEY_SYSTEM_ERROR,details:Id.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=jy(e),r=this.keyIdToKeySessionPromise[t];if(!r){const t=Zp(e.keyFormat),r=t?[t]:eg(this.config);return this.attemptKeySystemAccess(r)}return r}getKeySystemSelectionPromise(e){if(e.length||(e=eg(this.config)),0===e.length)throw new Hy({type:Ld.KEY_SYSTEM_ERROR,details:Id.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Af({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const r=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const n=Promise.all(r).then(()=>this.media?this.media.setMediaKeys(t):new Promise((e,r)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return r(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(e).catch(r)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(n),n.then(()=>{this.log(`Media-keys set for "${e}"`),r.push(n),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(e=>-1===r.indexOf(e))})}generateRequestWithPreferredKeySession(e,t,r,n){var i;const s=null==(i=this.config.drmSystems)||null==(i=i[e.keySystem])?void 0:i.generateRequest;if(s)try{const n=s.call(this.hls,t,r,e);if(!n)throw new Error("Invalid response from configured generateRequest filter");t=n.initDataType,r=n.initData?n.initData:null,e.decryptdata.pssh=r?new Uint8Array(r):null}catch(e){if(this.warn(e.message),this.hls&&this.hls.config.debug)throw e}if(null===r)return this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(e);const a=jy(e.decryptdata),o=e.decryptdata.uri;this.log(`Generating key-session request for "${n}" keyId: ${a} URI: ${o} (init data type: ${t} length: ${r.byteLength})`);const l=new um,u=e._onmessage=t=>{const r=e.mediaKeysSession;if(!r)return void l.emit("error",new Error("invalid state"));const{messageType:n,message:i}=t;this.log(`"${n}" message event for session "${r.sessionId}" message size: ${i.byteLength}`),"license-request"===n||"license-renewal"===n?this.renewLicense(e,i).catch(e=>{l.eventNames().length?l.emit("error",e):this.handleError(e)}):"license-release"===n?e.keySystem===Kp.FAIRPLAY&&this.updateKeySession(e,Gp("acknowledged")).then(()=>this.removeSession(e)).catch(e=>this.handleError(e)):this.warn(`unhandled media key message type "${n}"`)},c=(e,t)=>{let r;t.keyStatus=e,e.startsWith("usable")?l.emit("resolved"):"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?r=Vy(e,t.decryptdata):"expired"===e?r=new Error(`key expired (keyId: ${a})`):"released"===e?r=new Error("key released"):"status-pending"===e||this.warn(`unhandled key status change "${e}" (keyId: ${a})`),r&&(l.eventNames().length?l.emit("error",r):this.handleError(r))},d=e._onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void l.emit("error",new Error("invalid state"));const r=this.getKeyStatuses(e);if(!Object.keys(r).some(e=>"status-pending"!==r[e]))return;if("expired"===r[a])return this.log(`Expired key ${Af(r)} in key-session "${e.mediaKeysSession.sessionId}"`),void this.renewKeySession(e);let n=r[a];if(n)c(n,e);else{var i;const t=1e3;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(i=e.keyStatusTimeouts)[a]||(i[a]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const r=this.getKeyStatus(e.decryptdata);if(r&&"status-pending"!==r)return this.log(`No status for keyId ${a} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${r} from other session.`),c(r,e);this.log(`key status for ${a} in key-session "${e.mediaKeysSession.sessionId}" timed out after ${t}ms`),n="internal-error",c(n,e)},t)),this.log(`No status for keyId ${a} (${Af(r)}).`)}};jg(e.mediaKeysSession,"message",u),jg(e.mediaKeysSession,"keystatuseschange",d);const h=new Promise((e,t)=>{l.on("error",t),l.on("resolved",e)});return e.mediaKeysSession.generateRequest(t,r).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${a} URI: ${o}`)}).catch(t=>{throw new Hy({type:Ld.KEY_SYSTEM_ERROR,details:Id.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${t}`)}).then(()=>h).catch(t=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw t}))).then(()=>(l.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((r,n)=>{if("string"==typeof n&&"object"==typeof r){const e=n;n=r,r=e}const i="buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);if(e.keySystem===Kp.PLAYREADY&&16===i.length){const e=eh(i);t[e]=r,Hp(i)}const s=eh(i);"internal-error"===r&&(this.bannedKeyIds[s]=r),this.log(`key status change "${r}" for keyStatuses keyId: ${s} key-session "${e.mediaKeysSession.sessionId}"`),t[s]=r}),t}fetchServerCertificate(e){const t=this.config,r=new(0,t.loader)(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((i,s)=>{const a={responseType:"arraybuffer",url:n},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(e,t,r,n)=>{i(e.data)},onError:(t,r,i,o)=>{s(new Hy({type:Ld.KEY_SYSTEM_ERROR,details:Id.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:i,response:Gd({url:a.url,data:void 0},t)},`"${e}" certificate request failed (${n}). Status: ${t.code} (${t.text})`))},onTimeout:(t,r,i)=>{s(new Hy({type:Ld.KEY_SYSTEM_ERROR,details:Id.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:i,response:{url:a.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(e,t,r)=>{s(new Error("aborted"))}};r.load(a,l,u)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,r){return new Promise((n,i)=>{e.setServerCertificate(r).then(i=>{this.log(`setServerCertificate ${i?"success":"not supported by CDM"} (${r.byteLength}) on "${t}"`),n(e)}).catch(e=>{i(new Hy({type:Ld.KEY_SYSTEM_ERROR,details:Id.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(t=>this.updateKeySession(e,new Uint8Array(t)).catch(t=>{throw new Hy({type:Ld.KEY_SYSTEM_ERROR,details:Id.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:t,fatal:!1},t.message)}))}unpackPlayReadyKeyMessage(e,t){const r=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!r.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const n=(new DOMParser).parseFromString(r,"application/xml"),i=n.querySelectorAll("HttpHeader");if(i.length>0){let t;for(let r=0,n=i.length;r<n;r++){var s,a;t=i[r];const n=null==(s=t.querySelector("name"))?void 0:s.textContent,o=null==(a=t.querySelector("value"))?void 0:a.textContent;n&&o&&e.setRequestHeader(n,o)}}const o=n.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return Gp(atob(l))}setupLicenseXHR(e,t,r,n){const i=this.config.licenseXhrSetup;return i?Promise.resolve().then(()=>{if(!r.decryptdata)throw new Error("Key removed");return i.call(this.hls,e,t,r,n)}).catch(s=>{if(!r.decryptdata)throw s;return e.open("POST",t,!0),i.call(this.hls,e,t,r,n)}).then(r=>{e.readyState||e.open("POST",t,!0);return{xhr:e,licenseChallenge:r||n}}):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))}requestLicense(e,t){const r=this.config.keyLoadPolicy.default;return new Promise((n,i)=>{const s=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${s}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return i(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let t=a.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);const r=this.config.licenseResponseCallback;if(r)try{t=r.call(this.hls,a,s,e)}catch(e){this.error(e)}n(t)}else{const o=r.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)i(new Hy({type:Ld.KEY_SYSTEM_ERROR,details:Id.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:a,response:{url:s,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${s}). Status: ${a.status} (${a.statusText})`));else{const r=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${r} attempts left`),this.requestLicense(e,t).then(n,i)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,s,e,t).then(({xhr:t,licenseChallenge:r})=>{e.keySystem==Kp.PLAYREADY&&(r=this.unpackPlayReadyKeyMessage(t,r)),t.send(r)}).catch(i)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const r=t.media;this.media=r,jg(r,"encrypted",this.onMediaEncrypted),jg(r,"waitingforkey",this.onWaitingForKey);const n=this.mediaResolved;n?n():this.mediaKeys=r.mediaKeys}onMediaDetached(){const e=this.media;e&&(Gg(e,"encrypted",this.onMediaEncrypted),Gg(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const r=this.media,n=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,sg.clearKeyUriToKeyIdMap();const i=n.length;zy.CDMCleanupPromise=Promise.all(n.map(e=>this.removeSession(e)).concat((null==r||null==(e=r.setMediaKeys(null))?void 0:e.catch(e=>{this.log(`Could not clear media keys: ${e}`),this.hls&&this.hls.trigger(Cd.ERROR,{type:Ld.OTHER_ERROR,details:Id.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${e}`)})}))||Promise.resolve())).catch(e=>{this.log(`Could not close sessions and clear media keys: ${e}`),this.hls&&this.hls.trigger(Cd.ERROR,{type:Ld.OTHER_ERROR,details:Id.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${e}`)})}).then(()=>{i&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){const e=t.reduce((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:r,decryptdata:n}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${eh((null==n?void 0:n.keyId)||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.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:s}=e;s&&Object.keys(s).forEach(e=>self.clearTimeout(s[e]));const{drmSystemOptions:a}=this.config,o=function(e){var t;return!(!e||"persistent-license"!==e.sessionType&&(null==(t=e.sessionTypes)||!t.some(e=>"persistent-license"===e)))}(a)?new Promise((e,r)=>{self.setTimeout(()=>r(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(e).catch(r)}):Promise.resolve();return o.catch(e=>{this.log(`Could not remove session: ${e}`),this.hls&&this.hls.trigger(Cd.ERROR,{type:Ld.OTHER_ERROR,details:Id.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${e}`)})}).then(()=>t.close()).catch(e=>{this.log(`Could not close session: ${e}`),this.hls&&this.hls.trigger(Cd.ERROR,{type:Ld.OTHER_ERROR,details:Id.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${e}`)})})}return Promise.resolve()}}function jy(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return eh(e.keyId)}function Gy(e,t){return e.keyId&&t.mediaKeysSession.keyStatuses.has(e.keyId)?t.mediaKeysSession.keyStatuses.get(e.keyId):e.matches(t.decryptdata)?t.keyStatus:void 0}zy.CDMCleanupPromise=void 0;class Hy extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function Vy(e,t){const r="output-restricted"===e,n=r?Id.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:Id.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Hy({type:Ld.KEY_SYSTEM_ERROR,details:n,fatal:!1,decryptdata:t},r?"HDCP level output restricted":`key status changed to "${e}"`)}function Wy(e,t){let r;try{r=new Event("addtrack")}catch(e){r=document.createEvent("Event"),r.initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)}function Ky(e,t){const r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(r){Xd.debug(`[texttrack-utils]: ${r}`);try{const r=new self.TextTrackCue(t.startTime,t.endTime,t.text);r.id=t.id,e.addCue(r)}catch(e){Xd.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===r&&(e.mode=r)}function Yy(e,t){const r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues)for(let r=e.cues.length;r--;)t&&e.cues[r].removeEventListener("enter",t),e.removeCue(e.cues[r]);"disabled"===r&&(e.mode=r)}function qy(e,t,r,n){const i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&e.cues.length>0){const i=function(e,t,r){const n=[],i=function(e,t){if(t<=e[0].startTime)return 0;const r=e.length-1;if(t>e[r].endTime)return-1;let n,i=0,s=r;for(;i<=s;)if(n=Math.floor((s+i)/2),t<e[n].startTime)s=n-1;else{if(!(t>e[n].startTime&&i<r))return n;i=n+1}return e[i].startTime-t<t-e[s].startTime?i:s}(e,t);if(i>-1)for(let s=i,a=e.length;s<a;s++){const i=e[s];if(i.startTime>=t&&i.endTime<=r)n.push(i);else if(i.startTime>r)return n}return n}(e.cues,t,r);for(let t=0;t<i.length;t++)n&&!n(i[t])||e.removeCue(i[t])}"disabled"===i&&(e.mode=i)}function Xy(e){const t=[];for(let r=0;r<e.length;r++){const n=e[r];"subtitles"!==n.kind&&"captions"!==n.kind||!n.label||t.push(e[r])}return t}function Qy(e){let t=5381,r=e.length;for(;r;)t=33*t^e.charCodeAt(--r);return(t>>>0).toString()}const Zy=.025;let Jy=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function eb(e,t,r){return`${e.identifier}-${r+1}-${Qy(t)}`}class tb{constructor(e,t){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=t,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,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const r=this.playoutLimit;if(e<=0||isNaN(r))return!1;if(0===r)return!0;return((null==(t=this.assetList[e])?void 0:t.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 t=this.dateRange.tagAnchor;if(t)return rb(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime;return t-rb(t,e)<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=kd(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return rb(e,t)}return e}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Zy))}set appendInPlace(e){this.appendInPlaceStarted?this.resetOnResume=!e:this.appendInPlaceDisabled=!e}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return t=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?Jy.Range:Jy.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}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||null!==this.assetListResponse}toString(){return`["${(e=this).identifier}" ${e.cue.pre?"<pre>":e.cue.post?"<post>":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`;var e}}function rb(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<Zy)?t.start:t.start+t.duration}function nb(e,t,r){const n=new self.URL(e,r);return"data:"!==n.protocol&&n.searchParams.set("_HLS_primary_id",t),n}function ib(e,t){for(;null!=(r=e.assetList[++t])&&r.error;)var r;return t}function sb(e){const t=e.timelineStart,r=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+r).toFixed(2)}]`}class ab{constructor(e,t,r,n){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(Cd.PLAYOUT_LIMIT_REACHED,{})};const i=this.hls=new e(t);this.interstitial=r,this.assetItem=n;const s=()=>{this.hasDetails=!0};i.once(Cd.LEVEL_LOADED,s),i.once(Cd.AUDIO_TRACK_LOADED,s),i.once(Cd.SUBTITLE_TRACK_LOADED,s),i.on(Cd.MEDIA_ATTACHING,(e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t;this.interstitial.playoutLimit&&(t.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&i.on(Cd.BUFFER_APPENDED,()=>{const e=this.bufferedEnd;this.reachedPlayout(e)&&(this._bufferedEosTime=e,i.trigger(Cd.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 t=this.assetItem.uri;try{t=nb(t,e.config.primarySessionId||"").href}catch(e){}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if(null!=(t=this.hls)&&t.bufferedToEnd)return!0;if(!e)return!1;const r=Math.min(this._bufferedEosTime||1/0,this.duration),n=this.timelineOffset,i=kp.bufferInfo(e,n,0);return this.getAssetTime(i.end)>=r-.02}reachedPlayout(e){const t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!(null!=(e=this.hls)&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return(null==(e=this.hls)?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=kp.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.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 t=this.interstitial.playoutLimit;if(t){const r=t-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(null==(e=this.hls)?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const r=e-t;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 t=this.timelineOffset,r=this.duration;return Math.min(Math.max(0,e-t),r)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var e;this.mediaAttached&&(null!=(e=this.hls)&&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 t;this.loadSource(),null==(t=this.hls)||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()}resumeBuffering(){var e;null==(e=this.hls)||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.hls)||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=e=>delete e.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,r){var n;null==(n=this.hls)||n.on(e,t)}once(e,t,r){var n;null==(n=this.hls)||n.once(e,t)}off(e,t,r){var n;null==(n=this.hls)||n.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${sb(this.assetItem)} ${null==(e=this.hls)?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}class ob extends Hd{constructor(e,t){super("interstitials-sched",t),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,t){return this.events?this.events.reduce((r,n)=>e<=n.startOffset&&t>n.startOffset?(delete n.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,t){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 n=this.items;if(n)for(n[r]||(void 0===t&&(t=e.start),r=this.findItemIndexAtTime(t));r>=0&&null!=(i=n[r])&&i.event;){var i;r--}return r}findItemIndexAtTime(e,t){const r=this.items;if(r)for(let n=0;n<r.length;n++){let i=r[n];if(t&&"primary"!==t&&(i=i[t]),e===i.start||e>i.start&&e<i.end)return n}return-1}findJumpRestrictedIndex(e,t){const r=this.items;if(r)for(let n=e;n<=t&&r[n];n++){const e=r[n].event;if(null!=e&&e.restrictions.jump&&!e.appendInPlace)return n}return-1}findEventIndex(e){const t=this.items;if(t)for(let n=t.length;n--;){var r;if((null==(r=t[n].event)?void 0:r.identifier)===e)return n}return-1}findAssetIndex(e,t){const r=e.assetList,n=r.length;if(n>1)for(let e=0;e<n;e++){const i=r[e];if(!i.error){const r=i.timelineStart;if(t===r||t>r&&(t<r+(i.duration||0)||e===n-1))return e}}return 0}get assetIdAtEnd(){var e;const t=null==(e=this.items)||null==(e=e[this.length-1])?void 0:e.event;if(t){const e=t.assetList,r=e[e.length-1];if(r)return r.identifier}return null}parseInterstitialDateRanges(e,t){const r=e.main.details,{dateRanges:n}=r,i=this.events,s=this.parseDateRanges(n,{url:r.url},t),a=Object.keys(n),o=i?i.filter(e=>!a.includes(e.identifier)):[];s.length&&s.sort((e,t)=>{const r=e.cue.pre,n=e.cue.post,i=t.cue.pre,s=t.cue.post;if(r&&!i)return-1;if(i&&!r)return 1;if(n&&!s)return 1;if(s&&!n)return-1;if(!(r||i||n||s)){const r=e.startTime,n=t.startTime;if(r!==n)return r-n}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=s,o.forEach(e=>{this.removeEvent(e)}),this.updateSchedule(e,o)}updateSchedule(e,t=[],r=!1){const n=this.events||[];if(n.length||t.length||this.length<2){const i=this.items,s=this.parseSchedule(n,e),a=r||t.length||(null==i?void 0:i.length)!==s.length||s.some((e,t)=>Math.abs(e.playout.start-i[t].playout.start)>.005||Math.abs(e.playout.end-i[t].playout.end)>.005);a&&(this.items=s,this.onScheduleUpdate(t,i))}}parseDateRanges(e,t,r){const n=[],i=Object.keys(e);for(let s=0;s<i.length;s++){const a=i[s],o=e[a];if(o.isInterstitial){let e=this.eventMap[a];e?e.setDateRange(o):(e=new tb(o,t),this.eventMap[a]=e,!1===r&&(e.appendInPlace=r)),n.push(e)}}return n}parseSchedule(e,t){const r=[],n=t.main.details,i=n.live?1/0:n.edge;let s=0;if((e=e.filter(e=>!(e.error||e.cue.once&&e.hasPlayed))).length){this.resolveOffsets(e,t);let n=0,o=0;if(e.forEach((t,a)=>{const l=t.cue.pre,u=t.cue.post,c=e[a-1]||null,d=t.appendInPlace,h=u?i:t.startOffset,f=t.duration,p=t.timelineOccupancy===Jy.Range?f:0,g=t.resumptionOffset,m=(null==c?void 0:c.startTime)===h,v=h+t.cumulativeDuration;let y=d?v+f:h+g;if(l||!u&&h<=0){const e=o;o+=p,t.timelineStart=v;const n=s;s+=f,r.push({event:t,start:v,end:y,playout:{start:n,end:s},integrated:{start:e,end:o}})}else{if(!(h<=i))return;{if(!m){const i=h-n;if(i>.033){const l=n,u=o;o+=i;const c=s;s+=i;const d={previousEvent:e[a-1]||null,nextEvent:t,start:l,end:l+i,playout:{start:c,end:s},integrated:{start:u,end:o}};r.push(d)}else i>0&&c&&(c.cumulativeDuration+=i,r[r.length-1].end=h)}u&&(y=v),t.timelineStart=v;const i=o;o+=p;const l=s;s+=f,r.push({event:t,start:v,end:y,playout:{start:l,end:s},integrated:{start:i,end:o}})}}const b=t.resumeTime;n=u||b>i?i:b}),n<i){var a;const e=n,t=o,l=i-n;o+=l;const u=s;s+=l,r.push({previousEvent:(null==(a=r[r.length-1])?void 0:a.event)||null,nextEvent:null,start:n,end:e+l,playout:{start:u,end:s},integrated:{start:t,end:o}})}this.setDurations(i,s,o)}else{const e=0;r.push({previousEvent:null,nextEvent:null,start:e,end:i,playout:{start:e,end:i},integrated:{start:e,end:i}}),this.setDurations(i,i,i)}return r}setDurations(e,t,r){this.durations={primary:e,playout:t,integrated:r}}resolveOffsets(e,t){const r=t.main.details,n=r.live?1/0:r.edge;let i=0,s=-1;e.forEach((a,o)=>{const l=a.cue.pre,u=a.cue.post,c=l?0:u?n:a.startTime;this.updateAssetDurations(a);if(s===c?a.cumulativeDuration=i:(i=0,s=c),!u&&a.snapOptions.in&&(a.resumeAnchor=Nf(null,r.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(a,t)||(a.appendInPlace=!1)}if(!a.appendInPlace&&o+1<e.length){e[o+1].startTime-e[o].resumeTime<.033&&(e[o+1].appendInPlace=!1,e[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`))}const d=kd(a.resumeOffset)?a.resumeOffset:a.duration;i+=d})}primaryCanResumeInPlaceAt(e,t){const r=e.resumeTime,n=e.startTime+e.resumptionOffset;if(Math.abs(r-n)>Zy)return this.log(`"${e.identifier}" resumption ${r} not aligned with estimated timeline end ${n}`),!1;return!Object.keys(t).some(n=>{const i=t[n].details,s=i.edge;if(r>=s)return this.log(`"${e.identifier}" resumption ${r} past ${n} playlist end ${s}`),!1;const a=Nf(null,i.fragments,r);if(!a)return this.log(`"${e.identifier}" resumption ${r} does not align with any fragments in ${n} playlist (${i.fragStart}-${i.fragmentEnd})`),!0;const o="audio"===n?.175:0;return!(Math.abs(a.start-r)<Zy+o||Math.abs(a.end-r)<Zy+o)&&(this.log(`"${e.identifier}" resumption ${r} not aligned with ${n} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let r=0,n=!1,i=!1;for(let s=0;s<e.assetList.length;s++){const a=e.assetList[s],o=t+r;a.startOffset=r,a.timelineStart=o,n||(n=null===a.duration),i||(i=!!a.error);r+=a.error?0:a.duration||0}e.duration=n&&!i?Math.max(r,e.duration):r}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function lb(e){return`[${e.event?'"'+e.event.identifier+'"':"primary"}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}class ub{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const r=e.assetListUrl;let n;try{n=nb(r,this.hls.sessionId,e.baseUrl)}catch(t){const n=this.assignAssetListError(e,Id.ASSET_LIST_LOAD_ERROR,t,r);return void this.hls.trigger(Cd.ERROR,n)}t&&"data:"!==n.protocol&&n.searchParams.set("_HLS_start_offset",""+t);const i=this.hls.config,s=new(0,i.loader)(i),a={responseType:"json",url:n.href},o=i.interstitialAssetListLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(t,r,n,i)=>{const s=t.data,a=null==s?void 0:s.ASSETS;if(!Array.isArray(a)){const t=this.assignAssetListError(e,Id.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),n.url,r,i);return void this.hls.trigger(Cd.ERROR,t)}e.assetListResponse=s,this.hls.trigger(Cd.ASSET_LIST_LOADED,{event:e,assetListResponse:s,networkDetails:i})},onError:(t,r,n,i)=>{const s=this.assignAssetListError(e,Id.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${r.url})`),r.url,i,n);this.hls.trigger(Cd.ERROR,s)},onTimeout:(t,r,n)=>{const i=this.assignAssetListError(e,Id.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${r.url})`),r.url,t,n);this.hls.trigger(Cd.ERROR,i)}};return s.load(a,l,u),this.hls.trigger(Cd.ASSET_LIST_LOADING,{event:e}),s}assignAssetListError(e,t,r,n,i,s){return e.error=r,{type:Ld.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:n,error:r,networkDetails:s,stats:i}}}function cb(e){var t;null==e||null==(t=e.play())||t.catch(()=>{})}function db(e,t){return`[${e}] Advancing timeline position to ${t}`}class hb{constructor(e){this.buffered=void 0;const t=(t,r,n)=>{if((r>>>=0)>n-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${r}) is greater than the maximum bound (${n})`);return e[r][t]};this.buffered={get length(){return e.length},end:r=>t("end",r,e.length),start:r=>t("start",r,e.length)}}}const fb={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},pb=e=>String.fromCharCode(fb[e]||e),gb=15,mb=100,vb={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},yb={17:2,18:4,21:6,22:8,23:10,19:13,20:15},bb={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},wb={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Eb=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Sb{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const r="function"==typeof t?t():t;Xd.log(`${this.time} [${e}] ${r}`)}}}const Tb=function(e){const t=[];for(let r=0;r<e.length;r++)t.push(e[r].toString(16));return t};class xb{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 t=["foreground","underline","italics","background","flash"];for(let r=0;r<t.length;r++){const n=t[r];e.hasOwnProperty(n)&&(this[n]=e[n])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!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 kb{constructor(){this.uchar=" ",this.penState=new xb}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}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 Ab{constructor(e){this.chars=[],this.pos=0,this.currPenState=new xb,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<mb;e++)this.chars.push(new kb);this.logger=e}equals(e){for(let t=0;t<mb;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<mb;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<mb;t++)if(!this.chars[t].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>mb&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=mb)}moveCursor(e){const t=this.pos+e;if(e>1)for(let e=this.pos+1;e<t+1;e++)this.chars[e].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=pb(e);this.pos>=mb?this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<mb;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let r=0;r<mb;r++){const n=this.chars[r].uchar;" "!==n&&(t=!1),e.push(n)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e);this.chars[this.pos].setPenState(this.currPenState)}}class Rb{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<gb;t++)this.rows.push(new Ab(e));this.logger=e}reset(){for(let e=0;e<gb;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let r=0;r<gb;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t}copy(e){for(let t=0;t<gb;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<gb;t++)if(!this.rows[t].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 = "+Af(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<gb;e++)this.rows[e].clear();const e=this.currRow+1-this.nrRollUpRows,r=this.lastOutputScreen;if(r){const n=r.rows[e].cueStartTime,i=this.logger.time;if(null!==n&&null!==i&&n<i)for(let n=0;n<this.nrRollUpRows;n++)this.rows[t-this.nrRollUpRows+n+1].copy(r.rows[e+n])}}this.currRow=t;const r=this.rows[this.currRow];if(null!==e.indent){const t=e.indent,n=Math.max(t-1,0);r.setCursor(e.indent),e.color=r.chars[n].penState.foreground}const n={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(n)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+Af(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let r="",n=-1;for(let r=0;r<gb;r++){const i=this.rows[r].getTextString();i&&(n=r+1,e?t.push("Row "+n+": '"+i+"'"):t.push(i.trim()))}return t.length>0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r}getTextAndFormat(){return this.rows}}class Lb{constructor(e,t,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=t,this.mode=null,this.verbose=0,this.displayedMemory=new Rb(r),this.nonDisplayedMemory=new Rb(r),this.lastOutputScreen=new Rb(r),this.currRollUpRow=this.displayedMemory.rows[14],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[14],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),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(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"),"MODE_TEXT"!==this.mode&&(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"),"MODE_POP-ON"===this.mode){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 t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{const r=Math.floor(e/2)-16,n=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=n[r]}this.logger.log(2,"MIDROW: "+Af(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,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 Ib{constructor(e,t,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const n=this.logger=new Sb;this.channels=[null,new Lb(e,t,n),new Lb(e+1,r,n)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let e=0;e<t.length;e+=2){const r=127&t[e],n=127&t[e+1];let i=!1,s=null;if(0===r&&0===n)continue;this.logger.log(3,()=>"["+Tb([t[e],t[e+1]])+"] -> ("+Tb([r,n])+")");const a=this.cmdHistory;if(r>=16&&r<=31){if(Pb(r,n,a)){Cb(null,null,a),this.logger.log(3,()=>"Repeated command ("+Tb([r,n])+") is dropped");continue}Cb(r,n,this.cmdHistory),i=this.parseCmd(r,n),i||(i=this.parseMidrow(r,n)),i||(i=this.parsePAC(r,n)),i||(i=this.parseBackgroundAttributes(r,n))}else Cb(null,null,a);if(!i&&(s=this.parseChars(r,n),s)){const e=this.currentChannel;if(e&&e>0){this.channels[e].insertChars(s)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}i||s||this.logger.log(2,()=>"Couldn't parse cleaned data "+Tb([r,n])+" orig: "+Tb([t[e],t[e+1]]))}}parseCmd(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;const r=20===e||21===e||23===e?1:2,n=this.channels[r];return 20===e||21===e||28===e||29===e?32===t?n.ccRCL():33===t?n.ccBS():34===t?n.ccAOF():35===t?n.ccAON():36===t?n.ccDER():37===t?n.ccRU(2):38===t?n.ccRU(3):39===t?n.ccRU(4):40===t?n.ccFON():41===t?n.ccRDC():42===t?n.ccTR():43===t?n.ccRTD():44===t?n.ccEDM():45===t?n.ccCR():46===t?n.ccENM():47===t&&n.ccEOC():n.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let r=0;if((17===e||25===e)&&t>=32&&t<=47){if(r=17===e?1:2,r!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const n=this.channels[r];return!!n&&(n.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Tb([e,t])+")"),!0)}return!1}parsePAC(e,t){let r;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;const n=e<=23?1:2;r=t>=64&&t<=95?1===n?vb[e]:bb[e]:1===n?yb[e]:wb[e];const i=this.channels[n];return!!i&&(i.setPAC(this.interpretPAC(r,t)),this.currentChannel=n,!0)}interpretPAC(e,t){let r;const n={color:null,italics:!1,indent:null,underline:!1,row:e};return r=t>95?t-96:t-64,n.underline=!(1&~r),r<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(n.italics=!0,n.color="white"):n.indent=4*Math.floor((r-16)/2),n}parseChars(e,t){let r,n=null,i=null;if(e>=25?(r=2,i=e-8):(r=1,i=e),i>=17&&i<=19){let e;e=17===i?t+80:18===i?t+112:t+144,this.logger.log(2,()=>"Special char '"+pb(e)+"' in channel "+r),n=[e]}else e>=32&&e<=127&&(n=0===t?[e]:[e,t]);return n&&this.logger.log(3,()=>"Char codes = "+Tb(n).join(",")),n}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;let r;const n={};16===e||24===e?(r=Math.floor((t-32)/2),n.background=Eb[r],t%2==1&&(n.background=n.background+"_semi")):45===t?n.background="transparent":(n.foreground="black",47===t&&(n.underline=!0));const i=e<=23?1:2;return this.channels[i].setBkgData(n),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Cb(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const r=this.channels[t];r&&r.cueSplitAtTime(e)}}}function Cb(e,t,r){r.a=e,r.b=t}function Pb(e,t,r){return r.a===e&&r.b===t}var Db=function(){if(null!=Wp&&Wp.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function r(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;const r=t.toLowerCase();return!!~e.indexOf(r)&&r}function n(e){return r(t,e)}function i(e,...t){let r=1;for(;r<arguments.length;r++){const t=arguments[r];for(const r in t)e[r]=t[r]}return e}function s(t,s,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let u="",c=!1,d=t,h=s,f=a,p=null,g="",m=!0,v="auto",y="start",b=50,w="middle",E=50,S="middle";Object.defineProperty(o,"id",i({},l,{get:function(){return u},set:function(e){u=""+e}})),Object.defineProperty(o,"pauseOnExit",i({},l,{get:function(){return c},set:function(e){c=!!e}})),Object.defineProperty(o,"startTime",i({},l,{get:function(){return d},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");d=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",i({},l,{get:function(){return h},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");h=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",i({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",i({},l,{get:function(){return p},set:function(e){p=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",i({},l,{get:function(){return g},set:function(t){const n=function(t){return r(e,t)}(t);if(!1===n)throw new SyntaxError("An invalid or illegal string was specified.");g=n,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",i({},l,{get:function(){return m},set:function(e){m=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",i({},l,{get:function(){return v},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",i({},l,{get:function(){return y},set:function(e){const t=n(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",i({},l,{get:function(){return b},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");b=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",i({},l,{get:function(){return w},set:function(e){const t=n(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");w=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",i({},l,{get:function(){return E},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",i({},l,{get:function(){return S},set:function(e){const t=n(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");S=t,this.hasBeenReset=!0}})),o.displayState=void 0}return s.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},s}();class _b{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Mb(e){function t(e,t,r,n){return 3600*(0|e)+60*(0|t)+(0|r)+parseFloat(n||0)}const r=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?t(r[2],r[3],0,r[4]):t(r[1],r[2],r[3],r[4]):null}class Ob{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||""===t||(this.values[e]=t)}get(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,r){for(let n=0;n<r.length;++n)if(t===r[n]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const r=parseFloat(t);if(r>=0&&r<=100)return this.set(e,r),!0}return!1}}function Nb(e,t,r,n){const i=n?e.split(n):[e];for(const e in i){if("string"!=typeof i[e])continue;const n=i[e].split(r);if(2!==n.length)continue;t(n[0],n[1])}}const Fb=new Db(0,0,""),$b="middle"===Fb.align?"middle":"center";function Bb(e,t,r){const n=e;function i(){const t=Mb(e);if(null===t)throw new Error("Malformed timestamp: "+n);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function s(){e=e.replace(/^\s+/,"")}if(s(),t.startTime=i(),s(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+n);e=e.slice(3),s(),t.endTime=i(),s(),function(e,t){const n=new Ob;Nb(e,function(e,t){let i;switch(e){case"region":for(let i=r.length-1;i>=0;i--)if(r[i].id===t){n.set(e,r[i].region);break}break;case"vertical":n.alt(e,t,["rl","lr"]);break;case"line":i=t.split(","),n.integer(e,i[0]),n.percent(e,i[0])&&n.set("snapToLines",!1),n.alt(e,i[0],["auto"]),2===i.length&&n.alt("lineAlign",i[1],["start",$b,"end"]);break;case"position":i=t.split(","),n.percent(e,i[0]),2===i.length&&n.alt("positionAlign",i[1],["start",$b,"end","line-left","line-right","auto"]);break;case"size":n.percent(e,t);break;case"align":n.alt(e,t,["start",$b,"end","left","right"])}},/:/,/\s/),t.region=n.get("region",null),t.vertical=n.get("vertical","");let i=n.get("line","auto");"auto"===i&&-1===Fb.line&&(i=-1),t.line=i,t.lineAlign=n.get("lineAlign","start"),t.snapToLines=n.get("snapToLines",!0),t.size=n.get("size",100),t.align=n.get("align",$b);let s=n.get("position","auto");"auto"===s&&50===Fb.position&&(s="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=s}(e,t)}function Ub(e){return e.replace(/<br(?: \/)?>/gi,"\n")}class zb{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new _b,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;function r(){let e=t.buffer,r=0;for(e=Ub(e);r<e.length&&"\r"!==e[r]&&"\n"!==e[r];)++r;const n=e.slice(0,r);return"\r"===e[r]&&++r,"\n"===e[r]&&++r,t.buffer=e.slice(r),n}function n(e){Nb(e,function(e,t){},/:/)}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let e="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;e=r();const n=e.match(/^()?WEBVTT([ \t].*)?$/);if(null==n||!n[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let i=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(i?i=!1:e=r(),t.state){case"HEADER":/:/.test(e)?n(e):e||(t.state="ID");continue;case"NOTE":e||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(e)){t.state="NOTE";break}if(!e)continue;if(t.cue=new Db(0,0,""),t.state="CUE",-1===e.indexOf("--\x3e")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Bb(e,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const r=-1!==e.indexOf("--\x3e");if(!e||r&&(i=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=e}continue;case"BADCUE":e||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const jb=/\r\n|\n\r|\n|\r/g,Gb=function(e,t,r=0){return e.slice(r,r+t.length)===t};function Hb(e,t,r){return Qy(e.toString())+Qy(t.toString())+Qy(r)}function Vb(e,t,r,n,i,s,a){const o=new zb,l=Jd(new Uint8Array(e)).trim().replace(jb,"\n").split("\n"),u=[],c=t?function(e,t=1){return pv(e,9e4,1/t)}(t.baseTime,t.timescale):0;let d,h="00:00.000",f=0,p=0,g=!0;o.oncue=function(e){const s=r[n];let a=r.ccOffset;const o=(f-c)/9e4;if(null!=s&&s.new&&(void 0!==p?a=r.ccOffset=s.start:function(e,t,r){let n=e[t],i=e[n.prevCC];if(!i||!i.new&&n.new)return e.ccOffset=e.presentationOffset=n.start,void(n.new=!1);for(;null!=(s=i)&&s.new;){var s;e.ccOffset+=n.start-i.start,n.new=!1,n=i,i=e[n.prevCC]}e.presentationOffset=r}(r,n,o)),o){if(!t)return void(d=new Error("Missing initPTS for VTT MPEGTS"));a=o-r.presentationOffset}const l=e.endTime-e.startTime,h=Sv(9e4*(e.startTime+a-p),9e4*i)/9e4;e.startTime=Math.max(h,0),e.endTime=Math.max(h+l,0);const g=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(g)),e.id||(e.id=Hb(e.startTime,e.endTime,g)),e.endTime>0&&u.push(e)},o.onparsingerror=function(e){d=e},o.onflush=function(){d?a(d):s(u)},l.forEach(e=>{if(g){if(Gb(e,"X-TIMESTAMP-MAP=")){g=!1,e.slice(16).split(",").forEach(e=>{Gb(e,"LOCAL:")?h=e.slice(6):Gb(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))});try{p=function(e){let t=parseInt(e.slice(-3));const r=parseInt(e.slice(-6,-4)),n=parseInt(e.slice(-9,-7)),i=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(kd(t)&&kd(r)&&kd(n)&&kd(i)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*r,t+=6e4*n,t+=36e5*i,t}(h)/1e3}catch(e){d=e}return}""===e&&(g=!1)}o.parse(e+"\n")}),o.flush()}const Wb="stpp.ttml.im1t",Kb=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Yb=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,qb={left:"start",center:"center",right:"end",start:"start",end:"end"};function Xb(e,t,r,n){const i=Lh(new Uint8Array(e),["mdat"]);if(0===i.length)return void n(new Error("Could not parse IMSC1 mdat"));const s=i.map(e=>Jd(e)),a=function(e,t,r=1,n=!1){return pv(e,t,1/r,n)}(t.baseTime,1,t.timescale);try{s.forEach(e=>r(function(e,t){const r=(new DOMParser).parseFromString(e,"text/xml"),n=r.getElementsByTagName("tt")[0];if(!n)throw new Error("Invalid ttml");const i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},s=Object.keys(i).reduce((e,t)=>(e[t]=n.getAttribute(`ttp:${t}`)||i[t],e),{}),a="preserve"!==n.getAttribute("xml:space"),o=Zb(Qb(n,"styling","style")),l=Zb(Qb(n,"layout","region")),u=Qb(n,"body","[begin]");return[].map.call(u,e=>{const r=Jb(e,a);if(!r||!e.hasAttribute("begin"))return null;const n=rw(e.getAttribute("begin"),s),i=rw(e.getAttribute("dur"),s);let u=rw(e.getAttribute("end"),s);if(null===n)throw tw(e);if(null===u){if(null===i)throw tw(e);u=n+i}const c=new Db(n-t,u-t,r);c.id=Hb(c.startTime,c.endTime,c.text);const d=function(e,t,r){const n="http://www.w3.org/ns/ttml#styling";let i=null;const s=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;a&&r.hasOwnProperty(a)&&(i=r[a]);return s.reduce((r,s)=>{const a=ew(t,n,s)||ew(e,n,s)||ew(i,n,s);return a&&(r[s]=a),r},{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),{textAlign:h}=d;if(h){const e=qb[h];e&&(c.lineAlign=e),c.align=h}return zd(c,d),c}).filter(e=>null!==e)}(e,a)))}catch(e){n(e)}}function Qb(e,t,r){const n=e.getElementsByTagName(t)[0];return n?[].slice.call(n.querySelectorAll(r)):[]}function Zb(e){return e.reduce((e,t)=>{const r=t.getAttribute("xml:id");return r&&(e[r]=t),e},{})}function Jb(e,t){return[].slice.call(e.childNodes).reduce((e,r,n)=>{var i;return"br"===r.nodeName&&n?e+"\n":null!=(i=r.childNodes)&&i.length?Jb(r,t):t?e+r.textContent.trim().replace(/\s+/g," "):e+r.textContent},"")}function ew(e,t,r){return e&&e.hasAttributeNS(t,r)?e.getAttributeNS(t,r):null}function tw(e){return new Error(`Could not parse ttml timestamp ${e}`)}function rw(e,t){if(!e)return null;let r=Mb(e);return null===r&&(Kb.test(e)?r=function(e,t){const r=Kb.exec(e),n=(0|r[4])+(0|r[5])/t.subFrameRate;return 3600*(0|r[1])+60*(0|r[2])+(0|r[3])+n/t.frameRate}(e,t):Yb.test(e)&&(r=function(e,t){const r=Yb.exec(e),n=Number(r[1]);switch(r[2]){case"h":return 3600*n;case"m":return 60*n;case"ms":return 1e3*n;case"f":return n/t.frameRate;case"t":return n/t.tickRate}return n}(e,t))),r}class nw{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,r){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}function iw(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function sw(e,t){return!!e&&e.kind===iw(t)&&$v(t,e)}function aw(e,t,r,n){return Math.min(t,n)-Math.max(e,r)}const ow=/\s/,lw={newCue(e,t,r,n){const i=[];let s,a,o,l,u;const c=self.VTTCue||self.TextTrackCue;for(let h=0;h<n.rows.length;h++)if(s=n.rows[h],o=!0,l=0,u="",!s.isEmpty()){var d;for(let e=0;e<s.chars.length;e++)ow.test(s.chars[e].uchar)&&o?l++:(u+=s.chars[e].uchar,o=!1);s.cueStartTime=t,t===r&&(r+=1e-4),l>=16?l--:l++;const n=Ub(u.trim()),f=Hb(t,r,n);null!=e&&null!=(d=e.cues)&&d.getCueById(f)||(a=new c(t,r,n),a.id=f,a.line=h+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),i.push(a))}return e&&i.length&&(i.sort((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line),i.forEach(t=>Ky(e,t))),i}};const uw=/(\d+)-(\d+)\/(\d+)/;class cw{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||dw,this.controller=new self.AbortController,this.stats=new dh}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(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,r){const n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();const i=function(e,t){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(zd({},e.headers))};e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return r}(e,this.controller.signal),s="arraybuffer"===e.responseType,a=s?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=r,this.request=this.fetchSetup(e,i),self.clearTimeout(this.requestTimeout),t.timeout=o&&kd(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},t.timeout);(Cv(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(r=>{var i;this.response=this.loader=r;const a=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},l-(a-n.loading.start)),!r.ok){const{status:e,statusText:t}=r;throw new hw(t||"fetch, bad network response",e,r)}n.loading.first=a,n.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=uw.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(kd(e))return e}const r=e.get("Content-Length");if(r)return parseInt(r)}(r.headers)||n.total;const o=null==(i=this.callbacks)?void 0:i.onProgress;return o&&kd(t.highWaterMark)?this.loadProgressively(r,n,e,t.highWaterMark,o):s?r.arrayBuffer():"json"===e.responseType?r.json():r.text()}).then(r=>{var i,s;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const l=r[a];l&&(n.loaded=n.total=l);const u={url:o.url,data:r,code:o.status},c=null==(i=this.callbacks)?void 0:i.onProgress;c&&!kd(t.highWaterMark)&&c(n,e,r,o),null==(s=this.callbacks)||s.onSuccess(u,n,e,o)}).catch(t=>{var r;if(self.clearTimeout(this.requestTimeout),n.aborted)return;const i=t&&t.code||0,s=t?t.message:null;null==(r=this.callbacks)||r.onError({code:i,text:s},e,t?t.details:null,n)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,r,n=0,i){const s=new sm,a=e.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return s.dataLength&&i(t,r,s.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const l=a.value,u=l.length;return t.loaded+=u,u<n||s.dataLength?(s.push(l),s.dataLength>=n&&i(t,r,s.flush().buffer,e)):i(t,r,l.buffer,e),o()}).catch(()=>Promise.reject());return o()}}function dw(e,t){return new self.Request(e.url,t)}class hw extends Error{constructor(e,t,r){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=r}}const fw=/^age:\s*[\d.]+\s*$/im;class pw{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 dh,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,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,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=t,this.callbacks=r,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const r=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;const i=this.xhrSetup;i?Promise.resolve().then(()=>{if(this.loader===r&&!this.stats.aborted)return i(r,t.url)}).catch(e=>{if(this.loader===r&&!this.stats.aborted)return r.open("GET",t.url,!0),i(r,t.url)}).then(()=>{this.loader!==r||this.stats.aborted||this.openAndSendXhr(r,t,e)}).catch(e=>{var i;null==(i=this.callbacks)||i.onError({code:r.status,text:e.message},t,r,n)}):this.openAndSendXhr(r,t,e)}openAndSendXhr(e,t,r){e.readyState||e.open("GET",t.url,!0);const n=t.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:s}=r.loadPolicy;if(n)for(const t in n)e.setRequestHeader(t,n[t]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),r.timeout=i&&kd(i)?i:s,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:r}=this;if(!e||!t)return;const n=t.readyState,i=this.config;if(!r.aborted&&n>=2&&(0===r.loading.first&&(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)))),4===n)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const n=t.status,l="text"===t.responseType?t.responseText:null;if(n>=200&&n<300){const i=null!=l?l:t.response;if(null!=i){var s,a;r.loading.end=Math.max(self.performance.now(),r.loading.first);const o="arraybuffer"===t.responseType?i.byteLength:i.length;r.loaded=r.total=o,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first);const l=null==(s=this.callbacks)?void 0:s.onProgress;l&&l(r,e,i,t);const u={url:t.responseURL,data:i,code:n};return void(null==(a=this.callbacks)||a.onSuccess(u,r,e,t))}}const u=i.loadPolicy.errorRetry;var o;if(Wf(u,r.retry,!1,{url:e.url,data:void 0,code:n}))this.retry(u);else Xd.error(`${n} while loading ${e.url}`),null==(o=this.callbacks)||o.onError({code:n,text:t.statusText},e,t,r)}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(Wf(e,this.stats.retry,!0))this.retry(e);else{var t;Xd.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:r}=this;this.retryDelay=Hf(e,r.retry),r.retry++,Xd.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?void 0:t.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 t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&fw.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):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 gw=Gd(Gd({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:6e7,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:pw,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class extends Hd{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=e=>{var t;const{fragCurrent:r,partCurrent:n,hls:i}=this,{autoLevelEnabled:s,media:a}=i;if(!r||!a)return;const o=performance.now(),l=n?n.stats:r.stats,u=n?n.duration:r.duration,c=o-l.loading.start,d=i.minAutoLevel,h=r.level,f=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||h<=d)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!s)return;const p=f>-1&&f!==h,g=!!e||p;if(!g&&(a.paused||!a.playbackRate||!a.readyState))return;const m=i.mainForwardBufferInfo;if(!g&&null===m)return;const v=this.bwEstimator.getEstimateTTFB(),y=Math.abs(a.playbackRate);if(c<=Math.max(v,u/(2*y)*1e3))return;const b=m?m.len/y:0,w=l.loading.first?l.loading.first-l.loading.start:-1,E=l.loaded&&w>-1,S=this.getBwEstimate(),T=i.levels,x=T[h],k=Math.max(l.loaded,Math.round(u*(r.bitrate||x.averageBitrate)/8));let A=E?c-w:c;A<1&&E&&(A=Math.min(c,8*l.loaded/S));const R=E?1e3*l.loaded/A:0,L=v/1e3,I=R?(k-l.loaded)/R:8*k/S+L;if(I<=b)return;const C=R?8*R:S,P=!0===(null==(t=(null==e?void 0:e.details)||this.hls.latestLevelDetails)?void 0:t.live),D=this.hls.config.abrBandWidthUpFactor;let _,M=Number.POSITIVE_INFINITY;for(_=h-1;_>d;_--){const e=T[_].maxBitrate,t=!T[_].details||P;if(M=this.getTimeToLoadFrag(L,C,u*e,t),M<Math.min(b,u+L))break}if(M>=I)return;if(M>10*u)return;E?this.bwEstimator.sample(c-Math.min(v,w),l.loaded):this.bwEstimator.sampleTTFB(c);const O=T[_].maxBitrate;this.getBwEstimate()*D>O&&this.resetEstimator(O);const N=this.findBestLevel(O,d,_,0,b,1,1);N>-1&&(_=N),this.warn(`Fragment ${r.sn}${n?" part "+n.index:""} of level ${h} is loading too slowly;\n Fragment duration: ${r.duration.toFixed(3)}\n Time to underbuffer: ${b.toFixed(3)} s\n Estimated load time for current fragment: ${I.toFixed(3)} s\n Estimated load time for down switch fragment: ${M.toFixed(3)} s\n TTFB estimate: ${0|w} ms\n Current BW estimate: ${kd(S)?0|S:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${_} @ ${0|O} bps`),i.nextLoadLevel=i.nextAutoLevel=_,this.clearTimer();const F=()=>{if(this.clearTimer(),this.fragCurrent===r&&this.hls.loadLevel===_&&_>0){const e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${_>0?"and switching down":""}\n Fragment duration: ${r.duration.toFixed(3)} s\n Time to underbuffer: ${e.toFixed(3)} s`),r.abortRequests(),this.fragCurrent=this.partCurrent=null,_>d){let t=this.findBestLevel(this.hls.levels[d].bitrate,d,_,0,e,1,1);-1===t&&(t=d),this.hls.nextLoadLevel=this.hls.nextAutoLevel=t,this.resetEstimator(this.hls.levels[t].bitrate)}}};p||I>2*M?F():this.timer=self.setInterval(F,1e3*M),i.trigger(Cd.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,part:n,stats:l})},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 Bd(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Cd.FRAG_LOADING,this.onFragLoading,this),e.on(Cd.FRAG_LOADED,this.onFragLoaded,this),e.on(Cd.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Cd.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Cd.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Cd.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Cd.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(Cd.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Cd.FRAG_LOADING,this.onFragLoading,this),e.off(Cd.FRAG_LOADED,this.onFragLoaded,this),e.off(Cd.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Cd.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Cd.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Cd.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Cd.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(Cd.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){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,t){const r=t.frag;if(!this.ignoreFragment(r)){var n;if(!r.bitrateTest)this.fragCurrent=r,this.partCurrent=null!=(n=t.part)?n:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case Id.BUFFER_ADD_CODEC_ERROR:case Id.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Id.FRAG_LOAD_TIMEOUT:{const e=t.frag,{fragCurrent:r,partCurrent:n}=this;if(e&&r&&e.sn===r.sn&&e.level===r.level){const t=performance.now(),r=n?n.stats:e.stats,i=t-r.loading.start,s=r.loading.first?r.loading.first-r.loading.start:-1;if(r.loaded&&s>-1){const e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(i-Math.min(e,s),r.loaded)}else this.bwEstimator.sampleTTFB(i)}break}}}getTimeToLoadFrag(e,t,r,n){return e+r/t+(n?e+this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const r=this.hls.config,{loading:n}=t.stats,i=n.end-n.first;kd(i)&&(this.lastLevelLoadSec=i/1e3),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:r}){const n=r?r.stats:t.stats;if(t.type===Od&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const e=r?r.duration:t.duration,i=this.hls.levels[t.level],s=(i.loaded?i.loaded.bytes:0)+n.loaded,a=(i.loaded?i.loaded.duration:0)+e;i.loaded={bytes:s,duration:a},i.realBitrate=Math.round(8*s/a)}if(t.bitrateTest){const e={stats:n,frag:t,part:r,id:t.type};this.onFragBuffered(Cd.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:r,part:n}=t,i=null!=n&&n.stats.loaded?n.stats:r.stats;if(i.aborted)return;if(this.ignoreFragment(r))return;const s=i.parsing.end-i.loading.start-Math.min(i.loading.first-i.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(s,i.loaded),i.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=s/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==Od||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,r=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,i=this.findBestLevel(r,t,e,0,n,1,1);if(i>-1)return i;const s=this.hls.firstLevel,a=Math.min(Math.max(s,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${s} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&r&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;const n=t&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,n)&&t[e].loadError<=t[n].loadError)return e}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:r}=this;if(r.levels.length<=1)return r.loadLevel;const{maxAutoLevel:n,config:i,minAutoLevel:s}=r,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let u=i.abrBandWidthFactor,c=i.abrBandWidthUpFactor;if(l){const e=this.findBestLevel(o,s,n,l,0,u,c);if(e>=0)return this.rebufferNotice=-1,e}let d=a?Math.min(a,i.maxStarvationDelay):i.maxStarvationDelay;if(!l){const e=this.bitrateTestDelay;if(e){d=(a?Math.min(a,i.maxLoadingDelay):i.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),u=c=1}}const h=this.findBestLevel(o,s,n,l,d,u,c);if(this.rebufferNotice!==h&&(this.rebufferNotice=h,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${h}`)),h>-1)return h;const f=r.levels[s],p=r.loadLevelObj;return p&&(null==f?void 0:f.bitrate)<p.bitrate?s:r.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const r=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,n=e.mainForwardBufferInfo;return(n?n.len:0)/r}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,r,n,i,s,a){var o;const l=n+i,u=this.lastLoadedFragLevel,c=-1===u?this.hls.firstLevel:u,{fragCurrent:d,partCurrent:h}=this,{levels:f,allAudioTracks:p,loadLevel:g,config:m}=this.hls;if(1===f.length)return 0;const v=f[c],y=!(null==(o=this.hls.latestLevelDetails)||!o.live),b=-1===g||-1===u;let w,E="SDR",S=(null==v?void 0:v.frameRate)||0;const{audioPreference:T,videoPreference:x}=m,k=this.audioTracksByGroup||(this.audioTracksByGroup=Lf(p));let A=-1;if(b){if(-1!==this.firstSelection)return this.firstSelection;const n=this.codecTiers||(this.codecTiers=function(e,t,r,n){return e.slice(r,n+1).reduce((e,r,n)=>{if(!r.codecSet)return e;const i=r.audioGroups;let s=e[r.codecSet];s||(e[r.codecSet]=s={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:n,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,fragmentError:0}),s.minBitrate=Math.min(s.minBitrate,r.bitrate);const a=Math.min(r.height,r.width);return s.minHeight=Math.min(s.minHeight,a),s.minFramerate=Math.min(s.minFramerate,r.frameRate),s.minIndex=Math.min(s.minIndex,n),s.maxScore=Math.max(s.maxScore,r.score),s.fragmentError+=r.fragmentError,s.videoRanges[r.videoRange]=(s.videoRanges[r.videoRange]||0)+1,i&&i.forEach(e=>{if(!e)return;const r=t.groups[e];r&&(s.hasDefaultAudio=s.hasDefaultAudio||t.hasDefaultAudio?r.hasDefault:r.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(r.channels).forEach(e=>{s.channels[e]=(s.channels[e]||0)+r.channels[e]}))}),e},{})}(f,k,t,r)),i=function(e,t,r,n,i){const s=Object.keys(e),a=null==n?void 0:n.channels,o=null==n?void 0:n.audioCodec,l=null==i?void 0:i.videoCodec,u=a&&2===parseInt(a);let c=!1,d=!1,h=1/0,f=1/0,p=1/0,g=1/0,m=0,v=[];const{preferHDR:y,allowedVideoRanges:b}=kf(t,i);for(let t=s.length;t--;){const r=e[s[t]];c||(c=r.channels[2]>0),h=Math.min(h,r.minHeight),f=Math.min(f,r.minFramerate),p=Math.min(p,r.minBitrate),b.filter(e=>r.videoRanges[e]>0).length>0&&(d=!0)}h=kd(h)?h:0,f=kd(f)?f:0;const w=Math.max(1080,h),E=Math.max(30,f);p=kd(p)?p:r,r=Math.max(p,r),d||(t=void 0);const S=s.length>1;return{codecSet:s.reduce((t,n)=>{const i=e[n];if(n===t)return t;if(v=d?b.filter(e=>i.videoRanges[e]>0):[],S){if(i.minBitrate>r)return Rf(n,`min bitrate of ${i.minBitrate} > current estimate of ${r}`),t;if(!i.hasDefaultAudio)return Rf(n,"no renditions with default or auto-select sound found"),t;if(o&&n.indexOf(o.substring(0,4))%5!=0)return Rf(n,`audio codec preference "${o}" not found`),t;if(a&&!u){if(!i.channels[a])return Rf(n,`no renditions with ${a} channel sound found (channels options: ${Object.keys(i.channels)})`),t}else if((!o||u)&&c&&0===i.channels[2])return Rf(n,"no renditions with stereo sound found"),t;if(i.minHeight>w)return Rf(n,`min resolution of ${i.minHeight} > maximum of ${w}`),t;if(i.minFramerate>E)return Rf(n,`min framerate of ${i.minFramerate} > maximum of ${E}`),t;if(!v.some(e=>i.videoRanges[e]>0))return Rf(n,`no variants with VIDEO-RANGE of ${Af(v)} found`),t;if(l&&n.indexOf(l.substring(0,4))%5!=0)return Rf(n,`video codec preference "${l}" not found`),t;if(i.maxScore<m)return Rf(n,`max score of ${i.maxScore} < selected max of ${m}`),t}return t&&(Jh(n)>=Jh(t)||i.fragmentError>e[t].fragmentError)?t:(g=i.minIndex,m=i.maxScore,n)},void 0),videoRanges:v,preferHDR:y,minFramerate:f,minBitrate:p,minIndex:g}}(n,E,e,T,x),{codecSet:s,videoRanges:a,minFramerate:o,minBitrate:l,minIndex:u,preferHDR:c}=i;A=u,w=s,E=c?a[a.length-1]:a[0],S=o,e=Math.max(e,l),this.log(`picked start tier ${Af(i)}`)}else w=null==v?void 0:v.codecSet,E=null==v?void 0:v.videoRange;const R=h?h.duration:d?d.duration:0,L=this.bwEstimator.getEstimateTTFB()/1e3,I=[];for(let o=r;o>=t;o--){var C;const t=f[o],d=o>c;if(!t)continue;if(m.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){const r=navigator.mediaCapabilities;"function"==typeof(null==r?void 0:r.decodingInfo)&&hf(t,k,E,S,e,T)?(t.supportedPromise=ff(t,k,r,this.supportedCache),t.supportedPromise.then(e=>{if(!this.hls)return;t.supportedResult=e;const r=this.hls.levels,n=r.indexOf(t);e.error?this.warn(`MediaCapabilities decodingInfo error: "${e.error}" for level ${n} ${Af(e)}`):e.supported?e.decodingInfoResults.some(e=>!1===e.smooth||!1===e.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${n} not smooth or powerEfficient: ${Af(e)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${n} ${Af(e)}`),n>-1&&r.length>1&&(this.log(`Removing unsupported level ${n}`),this.hls.removeLevel(n),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(e=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${e}`)})):t.supportedResult=cf}if((w&&t.codecSet!==w||E&&t.videoRange!==E||d&&S>t.frameRate||!d&&S>0&&S<t.frameRate||null!=(C=t.supportedResult)&&null!=(C=C.decodingInfoResults)&&C.some(e=>!1===e.smooth))&&(!b||o!==A)){I.push(o);continue}const p=t.details,v=(h?null==p?void 0:p.partTarget:null==p?void 0:p.averagetargetduration)||R;let x;x=d?a*e:s*e;const P=R&&n>=2*R&&0===i?t.averageBitrate:t.maxBitrate,D=this.getTimeToLoadFrag(L,x,P*v,void 0===p);if(x>=P&&(o===u||0===t.loadError&&0===t.fragmentError)&&(D<=L||!kd(D)||y&&!this.bitrateTestDelay||D<l)){const e=this.forcedAutoLevel;return o===g||-1!==e&&e===g||(I.length&&this.trace(`Skipped level(s) ${I.join(",")} of ${r} max with CODECS and VIDEO-RANGE:"${f[I[0]].codecs}" ${f[I[0]].videoRange}; not compatible with "${w}" ${E}`),this.info(`switch candidate:${c}->${o} adjustedbw(${Math.round(x)})-bitrate=${Math.round(x-P)} ttfb:${L.toFixed(1)} avgDuration:${v.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${D.toFixed(1)} firstSelection:${b} codecSet:${t.codecSet} videoRange:${t.videoRange} hls.loadLevel:${g}`)),b&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:r}=this.hls;return Math.min(Math.max(e,r),t)}},bufferController:class extends Hd{constructor(e,t){var r;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=e=>{var t;this.hls&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{const{media:t,mediaSource:r}=this;e&&this.log("Media source opened"),t&&r&&(r.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(Cd.MEDIA_ATTACHED,{media:t,mediaSource:r}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=(r=Qd(e.config.preferManagedMediaSource),"undefined"!=typeof self&&r===self.ManagedMediaSource),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(Cd.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Cd.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Cd.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Cd.BUFFER_RESET,this.onBufferReset,this),e.on(Cd.BUFFER_APPENDING,this.onBufferAppending,this),e.on(Cd.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Cd.BUFFER_EOS,this.onBufferEos,this),e.on(Cd.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Cd.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Cd.FRAG_PARSED,this.onFragParsed,this),e.on(Cd.FRAG_CHANGED,this.onFragChanged,this),e.on(Cd.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Cd.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Cd.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Cd.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Cd.BUFFER_RESET,this.onBufferReset,this),e.off(Cd.BUFFER_APPENDING,this.onBufferAppending,this),e.off(Cd.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Cd.BUFFER_EOS,this.onBufferEos,this),e.off(Cd.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Cd.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Cd.FRAG_PARSED,this.onFragParsed,this),e.off(Cd.FRAG_CHANGED,this.onFragChanged,this),e.off(Cd.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const r={};if(this.operationQueue){const e=this.isUpdating();e||this.operationQueue.removeBlockers();const t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?" operations in queue":""}${e?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const n=this.transferData;return!this.sourceBufferCount&&n&&n.mediaSource===t?zd(r,n.tracks):this.sourceBuffers.forEach(e=>{const[t]=e;t&&(r[t]=zd({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null}),{media:e,mediaSource:t,tracks:r}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var r;let n=2;(t.audio&&!t.video||!t.altAudio)&&(n=1),this.bufferCodecEventsTotal=n,this.log(`${n} bufferCodec event(s) expected.`),null!=(r=this.transferData)&&r.mediaSource&&this.sourceBufferCount&&n&&this.bufferCreated()}onMediaAttaching(e,t){const r=this.media=t.media;this.transferData=this.overrides=void 0;const n=Qd(this.appendSource);if(n){const e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const i=this.mediaSource=t.mediaSource||new n;if(this.assignMediaSource(i),e)this._objectUrl=r.src,this.attachTransferred();else{const e=this._objectUrl=self.URL.createObjectURL(i);if(this.appendSource)try{r.removeAttribute("src");const t=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||t&&i instanceof t,Gv(r),function(e,t){const r=self.document.createElement("source");r.type="video/mp4",r.src=t,e.appendChild(r)}(r,e),r.load()}catch(t){r.src=e}else r.src=e}r.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,r;this.log(`${(null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${null==(r=e.constructor)?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,t=this.transferData;if(!t||!e)return;const r=this.tracks,n=t.tracks,i=n?Object.keys(n):null,s=i?i.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(n&&i&&s){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${Af(r,(e,t)=>"initSegment"===e?void 0:t)};\ntransfer tracks: ${Af(n,(e,t)=>"initSegment"===e?void 0:t)}}`),!Zd(n,r)){t.mediaSource=null,t.tracks=void 0;const i=e.currentTime,s=this.details,a=Math.max(i,(null==s?void 0:s.fragments[0].start)||0);return a-i>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${i} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(n)}"->"${Object.keys(r)}") start time: ${a} currentTime: ${i}`),this.onMediaDetaching(Cd.MEDIA_DETACHING,{}),this.onMediaAttaching(Cd.MEDIA_ATTACHING,t),void(e.currentTime=a))}this.transferData=void 0,i.forEach(e=>{const t=e,r=n[t];if(r){const e=r.buffer;if(e){const n=this.fragmentTracker,i=r.id;if(n.hasFragments(i)||n.hasParts(i)){const r=kp.getBuffered(e);n.detectEvictedFragments(t,r,i,null,!0)}const s=Hv(t),a=[t,e];this.sourceBuffers[s]=a,e.updating&&this.operationQueue&&this.operationQueue.prependBlocker(t),this.trackSourceBuffer(t,r)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}onMediaDetaching(e,t){const r=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:n,mediaSource:i,_objectUrl:s}=this;if(i){if(this.log("media source "+(r?"transferring":"detaching")),r)this.sourceBuffers.forEach(([e])=>{e&&this.removeBuffer(e)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const e="open"===i.readyState;try{const t=i.sourceBuffers;for(let r=t.length;r--;)e&&t[r].abort(),i.removeSourceBuffer(t[r]);e&&i.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.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}n&&(n.removeEventListener("emptied",this._onMediaEmptied),r||(s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(n.removeAttribute("src"),this.appendSource&&Gv(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(Cd.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const r=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),r)try{var n;null!=(n=this.mediaSource)&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(t){this.warn(`onBufferReset ${e}`,t)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Hv(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Bv(this.tracks)}onBufferCodecs(e,t){var r;const n=this.tracks,i=Object.keys(t);this.log(`BUFFER_CODECS: "${i}" (current SB count ${this.sourceBufferCount})`);const s="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),a=!s&&this.sourceBufferCount&&this.media&&i.some(e=>!n[e]);s||a?this.warn(`Unsupported transition between "${Object.keys(n)}" and "${i}" SourceBuffers`):(i.forEach(e=>{var r,i;const s=t[e],{id:a,codec:o,levelCodec:l,container:u,metadata:c,supplemental:d}=s;let h=n[e];const f=null==(r=this.transferData)||null==(r=r.tracks)?void 0:r[e],p=null!=f&&f.buffer?f:h,g=(null==p?void 0:p.pendingCodec)||(null==p?void 0:p.codec),m=null==p?void 0:p.levelCodec;h||(h=n[e]={buffer:void 0,listeners:[],codec:o,supplemental:d,container:u,levelCodec:l,metadata:c,id:a});const v=nf(g,m),y=null==v?void 0:v.replace(Uv,"$1");let b=nf(o,l);const w=null==(i=b)?void 0:i.replace(Uv,"$1");b&&v&&y!==w&&("audio"===e.slice(0,5)&&(b=rf(b,this.appendSource)),this.log(`switching codec ${g} to ${b}`),b!==(h.pendingCodec||h.codec)&&(h.pendingCodec=b),h.container=u,this.appendChangeType(e,u,b))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(r=t.audio)?void 0:r.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const r=this.tracks[t];return e[t]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},e},{})}appendChangeType(e,t,r){const n=`${t};codecs=${r}`,i={label:`change-type=${n}`,execute:()=>{const i=this.tracks[e];if(i){const s=i.buffer;null!=s&&s.changeType&&(this.log(`changing ${e} sourceBuffer type to ${n}`),s.changeType(n),i.codec=r,i.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(i,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const r=e.start,n=r+.05*e.duration;if(!0===(null==(t=this.fragmentTracker.getAppendedFrag(r,Od))?void 0:t.gap))return;const i={label:"block-audio",execute:()=>{var e;const t=this.tracks.video;(this.lastVideoAppendEnd>n||null!=t&&t.buffer&&kp.isBuffered(t.buffer,n)||!0===(null==(e=this.fragmentTracker.getAppendedFrag(n,Od))?void 0:e.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:i,frag:e},this.append(i,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:r}=this,{data:n,type:i,parent:s,frag:a,part:o,chunkMeta:l,offset:u}=t,c=l.buffering[i],{sn:d,cc:h}=a,f=self.performance.now();c.start=f;const p=a.stats.buffering,g=o?o.stats.buffering:null;0===p.start&&(p.start=f),g&&0===g.start&&(g.start=f);const m=r.audio;let v=!1;"audio"===i&&"audio/mpeg"===(null==m?void 0:m.container)&&(v=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const y=r.video,b=null==y?void 0:y.buffer;if(b&&"initSegment"!==d){const e=o||a,t=this.blockedAudioAppend;if("audio"!==i||"main"===s||this.blockedAudioAppend||y.ending||y.ended){if("video"===i){const r=e.end;if(t){const e=t.frag.start;(r>e||r<this.lastVideoAppendEnd||kp.isBuffered(b,e))&&this.unblockAudio()}this.lastVideoAppendEnd=r}}else{const t=e.start+.05*e.duration,r=b.buffered,n=this.currentOp("video");r.length||n?!n&&!kp.isBuffered(b,t)&&this.lastVideoAppendEnd<t&&this.blockAudio(e):this.blockAudio(e)}}const w=(o||a).start,E={label:`append-${i}`,execute:()=>{var e;c.executeStart=self.performance.now();const t=null==(e=this.tracks[i])?void 0:e.buffer;t&&(v?this.updateTimestampOffset(t,w,.1,i,d,h):void 0!==u&&kd(u)&&this.updateTimestampOffset(t,u,1e-6,i,d,h)),this.appendExecutor(n,i)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();c.executeEnd=c.end=e,0===p.first&&(p.first=e),g&&0===g.first&&(g.first=e);const t={};this.sourceBuffers.forEach(([e,r])=>{e&&(t[e]=kp.getBuffered(r))}),this.appendErrors[i]=0,"audio"===i||"video"===i?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(Cd.BUFFER_APPENDED,{type:i,frag:a,part:o,chunkMeta:l,parent:a.type,timeRanges:t})},onError:e=>{var t;const r={type:Ld.MEDIA_ERROR,parent:a.type,details:Id.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:a,part:o,chunkMeta:l,error:e,err:e,fatal:!1},n=null==(t=this.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e)r.details=Id.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!n)r.errorAction=rp(!0);else if(e.name===zv&&0===this.sourceBufferCount)r.errorAction=rp(!0);else{const e=++this.appendErrors[i];this.warn(`Failed ${e}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${i}" sourceBuffer (${n||"no media error"})`),(e>=this.hls.config.appendErrorMaxRetry||n)&&(r.fatal=!0)}this.hls.trigger(Cd.ERROR,r)}};this.log(`queuing "${i}" append sn: ${d}${o?" p: "+o.index:""} of ${a.type===Od?"level":"track"} ${a.level} cc: ${h}`),this.append(E,i,this.isPending(this.tracks[i]))}getFlushOp(e,t,r){return this.log(`queuing "${e}" remove ${t}-${r}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,r)},onStart:()=>{},onComplete:()=>{this.hls.trigger(Cd.BUFFER_FLUSHED,{type:e})},onError:n=>{this.warn(`Failed to remove ${t}-${r} from "${e}" SourceBuffer`,n)}}}onBufferFlushing(e,t){const{type:r,startOffset:n,endOffset:i}=t;r?this.append(this.getFlushOp(r,n,i),r):this.sourceBuffers.forEach(([e])=>{e&&this.append(this.getFlushOp(e,n,i),e)})}onFragParsed(e,t){const{frag:r,part:n}=t,i=[],s=n?n.elementaryStreams:r.elementaryStreams;s[ph]?i.push("audiovideo"):(s[hh]&&i.push("audio"),s[fh]&&i.push("video"));0===i.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${r.type} level: ${r.level} sn: ${r.sn}`),this.blockBuffers(()=>{const e=self.performance.now();r.stats.buffering.end=e,n&&(n.stats.buffering.end=e);const t=n?n.stats:r.stats;this.hls.trigger(Cd.FRAG_BUFFERED,{frag:r,part:n,stats:t,id:r.type})},i).catch(e=>{this.warn(`Fragment buffered callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var r;this.sourceBuffers.forEach(([e])=>{if(e){const r=this.tracks[e];t.type&&t.type!==e||(r.ending=!0,r.ended||(r.ended=!0,this.log(`${e} buffer reached EOS`)))}});const n=!1!==(null==(r=this.overrides)?void 0:r.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t;return e&&!(null!=(t=this.tracks[e])&&t.ended)})?n?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:e}=this;e&&"open"===e.readyState?(this.log("Calling mediaSource.endOfStream()"),e.endOfStream(),this.hls.trigger(Cd.BUFFERED_TO_END,void 0)):e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)})):(this.tracksEnded(),this.hls.trigger(Cd.BUFFERED_TO_END,void 0)):"video"===t.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(null!==e){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===Id.BUFFER_APPEND_ERROR&&t.frag){var r;const e=null==(r=t.errorAction)?void 0:r.nextAutoLevel;kd(e)&&e!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:r}=this;if(!r||null===t)return;if(!this.sourceBufferCount)return;const n=e.config,i=r.currentTime,s=t.levelTargetDuration,a=t.live&&null!==n.liveBackBufferLength?n.liveBackBufferLength:n.backBufferLength;if(kd(a)&&a>=0){const e=Math.max(a,s),t=Math.floor(i/s)*s-e;this.flushBackBuffer(i,s,t)}const o=n.frontBufferFlushThreshold;if(kd(o)&&o>0){const e=Math.max(n.maxBufferLength,o),t=Math.max(e,s),r=Math.floor(i/s)*s+t;this.flushFrontBuffer(i,s,r)}}flushBackBuffer(e,t,r){this.sourceBuffers.forEach(([e,t])=>{if(t){const i=kp.getBuffered(t);if(i.length>0&&r>i.start(0)){var n;this.hls.trigger(Cd.BACK_BUFFER_REACHED,{bufferEnd:r});const t=this.tracks[e];if(null!=(n=this.details)&&n.live)this.hls.trigger(Cd.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(null!=t&&t.ended)return void this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);this.hls.trigger(Cd.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:e})}}})}flushFrontBuffer(e,t,r){this.sourceBuffers.forEach(([t,n])=>{if(n){const i=kp.getBuffered(n),s=i.length;if(s<2)return;const a=i.start(s-1),o=i.end(s-1);if(r>a||e>=a&&e<=o)return;this.hls.trigger(Cd.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:t})}})}getDurationAndRange(){var e;const{details:t,mediaSource:r}=this;if(!t||!this.media||"open"!==(null==r?void 0:r.readyState))return null;const n=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&r.setLiveSeekableRange){const e=Math.max(0,t.fragmentStart);return{duration:1/0,start:e,end:Math.max(e,n)}}return{duration:1/0}}const i=null==(e=this.overrides)?void 0:e.duration;if(i)return kd(i)?{duration:i}:null;const s=this.media.duration;return n>(kd(r.duration)?r.duration:0)&&n>s||!kd(s)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:r}){const n=this.mediaSource;this.media&&n&&"open"===n.readyState&&(n.duration!==e&&(kd(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),n.duration=e),void 0!==t&&void 0!==r&&(this.log(`MediaSource duration is set to ${n.duration}. Setting seekable range to ${t}-${r}.`),n.setLiveSeekableRange(t,r)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:r}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${Af(r)}`),this.tracksReady){var n;const e=null==(n=this.transferData)?void 0:n.tracks;e&&Object.keys(e).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,r])=>{if(t){const n=this.tracks[t];e[t]={buffer:r,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}}),this.hls.trigger(Cd.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(Cd.ERROR,{type:Ld.MEDIA_ERROR,details:Id.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:r}=this;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(const i in e){const s=i,a=e[s];if(this.isPending(a)){const e=this.getTrackCodec(a,s),i=`${a.container};codecs=${e}`;a.codec=e,this.log(`creating sourceBuffer(${i})${this.currentOp(s)?" Queued":""} ${Af(a)}`);try{const e=r.addSourceBuffer(i),n=Hv(s),o=[s,e];t[n]=o,a.buffer=e}catch(e){var n;return this.error(`error while trying to add sourceBuffer: ${e.message}`),this.shiftAndExecuteNext(s),null==(n=this.operationQueue)||n.removeBlockers(),delete this.tracks[s],void this.hls.trigger(Cd.ERROR,{type:Ld.MEDIA_ERROR,details:Id.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:s,mimeType:i,parent:a.id})}this.trackSourceBuffer(s,a)}}this.bufferCreated()}getTrackCodec(e,t){const r=e.supplemental;let n=e.codec;r&&("video"===t||"audiovideo"===t)&&qh(r,"video")&&(n=function(e,t){const r=[];if(e){const t=e.split(",");for(let e=0;e<t.length;e++)Yh(t[e],"video")||r.push(t[e])}return t&&r.push(t),r.join(",")}(n,r));const i=nf(n,e.levelCodec);return i?"audio"===t.slice(0,5)?rf(i,this.appendSource):i:""}trackSourceBuffer(e,t){const r=t.buffer;if(!r)return;const n=this.getTrackCodec(t,e);this.tracks[e]={buffer:r,codec:n,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.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",(e,t)=>{const r=t.removedRanges;null!=r&&r.length&&this.hls.trigger(Cd.BUFFER_FLUSHED,{type:e})})}get mediaSrc(){var e,t;const r=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==r?void 0:r.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if("closed"===(null==(t=this.mediaSource)?void 0:t.readyState))return void this.resetBuffer(e);const r=this.currentOp(e);r&&(r.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var r;const n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(r=this.mediaSource)?void 0:r.readyState}`);this.error(`${n}`,t),this.hls.trigger(Cd.ERROR,{type:Ld.MEDIA_ERROR,details:Id.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});const i=this.currentOp(e);i&&i.onError(n)}updateTimestampOffset(e,t,r,n,i,s){const a=t-e.timestampOffset;Math.abs(a)>=r&&(this.log(`Updating ${n} SourceBuffer timestampOffset to ${t} (sn: ${i} cc: ${s})`),e.timestampOffset=t)}removeExecutor(e,t,r){const{media:n,mediaSource:i}=this,s=this.tracks[e],a=null==s?void 0:s.buffer;if(!n||!i||!a)return this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(e);const o=kd(n.duration)?n.duration:1/0,l=kd(i.duration)?i.duration:1/0,u=Math.max(0,t),c=Math.min(r,o,l);c>u&&(!s.ending||s.ended)?(s.ended=!1,this.log(`Removing [${u},${c}] from the ${e} SourceBuffer`),a.remove(u,c)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const r=this.tracks[t],n=null==r?void 0:r.buffer;if(!n)throw new jv(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);r.ending=!1,r.ended=!1,n.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:r}=this,n=t.map(e=>this.appendBlocker(e));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(t=>{r===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(e=>{var t;const r=null==(t=this.tracks[e])?void 0:t.buffer;r&&!r.updating&&this.shiftAndExecuteNext(e)})}append(e,t,r){this.operationQueue&&this.operationQueue.append(e,t,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,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,r){const n=this.tracks[e];if(!n)return;const i=n.buffer;if(!i)return;const s=r.bind(this,e);n.listeners.push({event:t,listener:s}),i.addEventListener(t,s)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const r=t.buffer;r&&(t.listeners.forEach(e=>{r.removeEventListener(e.event,e.listener)}),t.listeners.length=0)}},capLevelController:Vv,errorController:class extends Hd{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(Cd.ERROR,this.onError,this),e.on(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Cd.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Cd.ERROR,this.onError,this),e.off(Cd.ERROR,this.onErrorOut,this),e.off(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Cd.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===Od?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,r=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===r?t.loadLevel:r}variantHasKey(e,t){if(e){var r;if(null!=(r=e.details)&&r.hasKey(t))return!0;const n=e.audioGroups;if(n){return this.hls.allAudioTracks.filter(e=>n.indexOf(e.groupId)>=0).some(e=>{var r;return null==(r=e.details)?void 0:r.hasKey(t)})}}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var r;if(t.fatal)return;const n=this.hls,i=t.context;switch(t.details){case Id.FRAG_LOAD_ERROR:case Id.FRAG_LOAD_TIMEOUT:case Id.KEY_LOAD_ERROR:case Id.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case Id.FRAG_PARSING_ERROR:if(null!=(r=t.frag)&&r.gap)return void(t.errorAction=rp());case Id.FRAG_GAP:case Id.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=qf);case Id.LEVEL_EMPTY_ERROR:case Id.LEVEL_PARSING_ERROR:{var s;const e=t.parent===Od?t.level:n.loadLevel;t.details===Id.LEVEL_EMPTY_ERROR&&null!=(s=t.context)&&null!=(s=s.levelDetails)&&s.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case Id.LEVEL_LOAD_ERROR:case Id.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==i?void 0:i.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.level)));case Id.AUDIO_TRACK_LOAD_ERROR:case Id.AUDIO_TRACK_LOAD_TIMEOUT:case Id.SUBTITLE_LOAD_ERROR:case Id.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const e=n.loadLevelObj;if(e&&(i.type===_d&&e.hasAudioGroup(i.groupId)||i.type===Md&&e.hasSubtitleGroup(i.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=qf,void(t.errorAction.flags=Jf)}return;case Id.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:qf,flags:ep});case Id.KEY_SYSTEM_SESSION_UPDATE_FAILED:case Id.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case Id.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:qf,flags:tp});case Id.BUFFER_ADD_CODEC_ERROR:case Id.REMUX_ALLOC_ERROR:case Id.BUFFER_APPEND_ERROR:var a;if(!t.errorAction)t.errorAction=this.getLevelSwitchAction(t,null!=(a=t.level)?a:n.loadLevel);return;case Id.INTERNAL_EXCEPTION:case Id.BUFFER_APPENDING_ERROR:case Id.BUFFER_FULL_ERROR:case Id.LEVEL_SWITCH_ERROR:case Id.BUFFER_STALLED_ERROR:case Id.BUFFER_SEEK_OVER_HOLE:case Id.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=rp())}t.type===Ld.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=rp())}getPlaylistRetryOrSwitchAction(e,t){const r=Gf(this.hls.config.playlistLoadPolicy,e),n=this.playlistError++;if(Wf(r,n,Uf(e),e.response))return{action:Qf,flags:Zf,retryConfig:r,retryCount:n};const i=this.getLevelSwitchAction(e,t);return r&&(i.retryConfig=r,i.retryCount=n),i}getFragRetryOrSwitchAction(e){const t=this.hls,r=this.getVariantLevelIndex(e.frag),n=t.levels[r],{fragLoadPolicy:i,keyLoadPolicy:s}=t.config,a=Gf(zf(e)?s:i,e),o=t.levels.reduce((e,t)=>e+t.fragmentError,0);if(n&&(e.details!==Id.FRAG_GAP&&n.fragmentError++,!jf(e))){if(Wf(a,o,Uf(e),e.response))return{action:Qf,flags:Zf,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(e,r);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){const r=this.hls;null==t&&(t=r.loadLevel);const n=this.hls.levels[t];if(n){var i,s;const t=e.details;n.loadError++,t===Id.BUFFER_APPEND_ERROR&&n.fragmentError++;let l=-1;const{levels:u,loadLevel:c,minAutoLevel:d,maxAutoLevel:h}=r;r.autoLevelEnabled||r.config.preserveManualLevelOnError||(r.loadLevel=-1);const f=null==(i=e.frag)?void 0:i.type,p=(f===Nd&&t===Id.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(t===Id.BUFFER_ADD_CODEC_ERROR||t===Id.BUFFER_APPEND_ERROR))&&u.some(({audioCodec:e})=>n.audioCodec!==e),g="video"===e.sourceBufferName&&(t===Id.BUFFER_ADD_CODEC_ERROR||t===Id.BUFFER_APPEND_ERROR)&&u.some(({codecSet:e,audioCodec:t})=>n.codecSet!==e&&n.audioCodec===t),{type:m,groupId:v}=null!=(s=e.context)?s:{};for(let r=u.length;r--;){const i=(r+c)%u.length;if(i!==c&&i>=d&&i<=h&&0===u[i].loadError){var a,o;const r=u[i];if(t===Id.FRAG_GAP&&f===Od&&e.frag){const t=u[i].details;if(t){const r=Nf(e.frag,t.fragments,e.frag.start);if(null!=r&&r.gap)continue}}else{if(m===_d&&r.hasAudioGroup(v)||m===Md&&r.hasSubtitleGroup(v))continue;if(f===Nd&&null!=(a=n.audioGroups)&&a.some(e=>r.hasAudioGroup(e))||f===Fd&&null!=(o=n.subtitleGroups)&&o.some(e=>r.hasSubtitleGroup(e))||p&&n.audioCodec===r.audioCodec||g&&n.codecSet===r.codecSet||!p&&n.codecSet!==r.codecSet)continue}l=i;break}}if(l>-1&&r.loadLevel!==l)return e.levelRetry=!0,this.playlistError=0,{action:qf,flags:Zf,nextAutoLevel:l}}return{action:qf,flags:Jf}}onErrorOut(e,t){var r;switch(null==(r=t.errorAction)?void 0:r.action){case Yf:break;case qf:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===Id.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,r=e.errorAction;if(!r)return;const{flags:n}=r,i=r.nextAutoLevel;switch(n){case Zf:this.switchLevel(e,i);break;case ep:{const n=this.getVariantLevelIndex(e.frag),i=t.levels[n],s=null==i?void 0:i.attrs["HDCP-LEVEL"];if(r.hdcpLevel=s,"NONE"===s)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(s){t.maxHdcpLevel=mf[mf.indexOf(s)-1],r.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case tp:{const t=e.decryptdata;if(t){const n=this.hls.levels,i=n.length;for(let r=i;r--;){var s,a;if(this.variantHasKey(n[r],t))this.log(`Banned key found in level ${r} (${n[r].bitrate}bps) or audio group "${null==(s=n[r].audioGroups)?void 0:s.join(",")}" (${null==(a=e.frag)?void 0:a.type} fragment) ${eh(t.keyId||[])}`),n[r].fragmentError++,n[r].loadError++,this.log(`Removing level ${r} with key error (${e.error})`),this.hls.removeLevel(r)}const o=e.frag;if(this.hls.levels.length<i)r.resolved=!0;else if(o&&o.type!==Od){const e=o.decryptdata;e&&!t.matches(e)&&(r.resolved=!0)}}break}}r.resolved||this.switchLevel(e,i)}switchLevel(e,t){if(void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===Id.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName)){const t=lf(e.mimeType),r=this.hls.levels;for(let n=r.length;n--;)r[n][`${e.sourceBufferName}Codec`]===t&&(this.log(`Removing level ${n} for ${e.details} ("${t}" not supported)`),this.hls.removeLevel(n))}}},fpsController:class{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(Cd.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(Cd.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(Cd.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(Cd.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const r=this.hls.config;if(r.capLevelOnFPSDrop){const e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,r){const n=performance.now();if(t){if(this.lastTime){const e=n-this.lastTime,i=r-this.lastDroppedFrames,s=t-this.lastDecodedFrames,a=1e3*i/e,o=this.hls;if(o.trigger(Cd.FPS_DROP,{currentDropped:i,currentDecoded:s,totalDroppedFrames:r}),a>0&&i>o.config.fpsDroppedMonitoringThreshold*s){let e=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(Cd.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=n,this.lastDroppedFrames=r,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},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:tg,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:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},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},{cueHandler:lw,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends nm{constructor(e,t,r){super(e,t,r,"subtitle-stream-controller",Fd),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(Cd.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Cd.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Cd.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Cd.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Cd.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(Cd.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(Cd.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Cd.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Cd.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Cd.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Cd.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(Cd.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=Wg,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:r,success:n}=t;if(this.fragContextChanged(r)||(mh(r)&&(this.fragPrevious=r),this.state=Wg),!n)return;const i=this.tracksBuffered[this.currentTrackId];if(!i)return;let s;const a=r.start;for(let e=0;e<i.length;e++)if(a>=i[e].start&&a<=i[e].end){s=i[e];break}const o=r.start+r.duration;s?s.end=o:(s={start:a,end:o},i.push(s)),this.fragmentTracker.fragBuffered(r),this.fragBufferedComplete(r,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:r,endOffset:n}=t;if(0===r&&n!==Number.POSITIVE_INFINITY){const e=n-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach(t=>{for(let r=0;r<t.length;)if(t[r].end<=e)t.shift();else{if(!(t[r].start<e))break;t[r].start=e,r++}}),this.fragmentTracker.removeFragmentsInRange(r,e,Fd)}}onError(e,t){const r=t.frag;(null==r?void 0:r.type)===Fd&&(t.details===Id.FRAG_GAP&&this.fragmentTracker.fragBuffered(r,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Vg&&(this.state=Wg))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){this.levels&&Nv(this.levels,t)?this.levels=t.map(e=>new Tf(e)):(this.tracksBuffered=[],this.levels=t.map(e=>{const t=new Tf(e);return this.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Fd),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){var r;if(this.currentTrackId=t.id,null==(r=this.levels)||!r.length||-1===this.currentTrackId)return void this.clearInterval();const n=this.levels[this.currentTrackId];null!=n&&n.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,n&&this.state!==Vg&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var r;const{currentTrackId:n,levels:i}=this,{details:s,id:a}=t;if(!i)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=i[a];if(a>=i.length||!o)return;this.log(`Subtitle track ${a} loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(s.live||null!=(r=o.details)&&r.live){if(s.deltaUpdateFailed)return;const e=this.mainDetails;if(!e)return void(this.startFragRequested=!1);const t=e.fragments[0];var u;if(o.details)l=this.alignPlaylists(s,o.details,null==(u=this.levelLastLoaded)?void 0:u.details),0===l&&t&&(l=t.start,Ig(s,l));else s.hasProgramDateTime&&e.hasProgramDateTime?(zg(s,e),l=s.fragmentStart):t&&(l=t.start,Ig(s,l));e&&!this.startFragRequested&&this.setStartPosition(e,l)}if(o.details=s,this.levelLastLoaded=o,a===n&&(this.hls.trigger(Cd.SUBTITLE_TRACK_UPDATED,{details:s,id:a,groupId:t.groupId}),this.tick(),s.live&&!this.fragCurrent&&this.media&&this.state===Wg)){Nf(null,s.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(e){const{frag:t,payload:r}=e,n=t.decryptdata,i=this.hls;if(!this.fragContextChanged(t)&&r&&r.byteLength>0&&null!=n&&n.key&&n.iv&&Up(n.method)){const e=performance.now();this.decrypter.decrypt(new Uint8Array(r),n.key.buffer,n.iv.buffer,zp(n.method)).catch(e=>{throw i.trigger(Cd.ERROR,{type:Ld.MEDIA_ERROR,details:Id.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e}).then(r=>{const n=performance.now();i.trigger(Cd.FRAG_DECRYPTED,{frag:t,payload:r,stats:{tstart:e,tdecrypt:n}})}).catch(e=>{this.warn(`${e.name}: ${e.message}`),this.state=Wg})}}doTick(){if(this.media){if(this.state===Wg){const{currentTrackId:e,levels:t}=this,r=null==t?void 0:t[e];if(!r||!t.length||!r.details)return;if(this.waitForLive(r))return;const{config:n}=this,i=this.getLoadPosition(),s=kp.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],i,n.maxBufferHole),{end:a,len:o}=s,l=r.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;const u=l.fragments,c=u.length,d=l.edge;let h=null;const f=this.fragPrevious;if(a<d){const e=n.maxFragLookUpTolerance,t=a>d-e?0:e;h=Nf(f,u,Math.max(u[0].start,a),t),!h&&f&&f.start<u[0].start&&(h=u[0])}else h=u[c-1];if(h=this.filterReplacedPrimary(h,r.details),!h)return;const p=u[h.sn-l.startSN-1];if(p&&p.cc===h.cc&&this.fragmentTracker.getState(p)===np&&(h=p),this.fragmentTracker.getState(h)===np){const e=this.mapToInitFragWhenRequired(h);e&&this.loadFragment(e,r,a)}}}else this.state=Wg}loadFragment(e,t,r){mh(e)?super.loadFragment(e,t,r):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new hb(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends Ov{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 e=null;const t=Xy(this.media.textTracks);for(let r=0;r<t.length;r++)if("hidden"===t[r].mode)e=t[r];else if("showing"===t[r].mode){e=t[r];break}const r=this.findTrackForTextTrack(e);this.subtitleTrack!==r&&this.setSubtitleTrack(r)},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(Cd.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Cd.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Cd.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Cd.LEVEL_LOADING,this.onLevelLoading,this),e.on(Cd.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Cd.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Cd.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Cd.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Cd.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Cd.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Cd.LEVEL_LOADING,this.onLevelLoading,this),e.off(Cd.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Cd.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Cd.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.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,t){const r=this.media;if(!r)return;const n=!!t.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,n)return;Xy(r.textTracks).forEach(e=>{Yy(e)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:r,groupId:n,details:i}=t,s=this.tracksInGroup[r];if(!s||s.groupId!==n)return void this.warn(`Subtitle track with id:${r} and group:${n} not found in active group ${null==s?void 0:s.groupId}`);const a=s.details;s.details=t.details,this.log(`Subtitle track ${r} "${s.name}" lang:${s.lang} group:${n} loaded [${i.startSN}-${i.endSN}]`),r===this.trackId&&this.playlistLoaded(r,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const r=t.subtitleGroups||null,n=this.groupIds;let i=this.currentTrack;if(!r||(null==n?void 0:n.length)!==(null==r?void 0:r.length)||null!=r&&r.some(e=>-1===(null==n?void 0:n.indexOf(e)))){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter(e=>!r||-1!==r.indexOf(e.groupId));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.subtitlePreference;if(!i&&t){this.selectDefaultTrack=!1;const r=Cf(t,e);if(r>-1)i=e[r];else{const e=Cf(t,this.tracks);i=this.tracks[e]}}let n=this.findTrackId(i);-1===n&&i&&(n=this.findTrackId(null));const s={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${null==r?void 0:r.join(",")}" group-id`),this.hls.trigger(Cd.SUBTITLE_TRACKS_UPDATED,s),-1!==n&&-1===this.trackId&&this.setSubtitleTrack(n)}}findTrackId(e){const t=this.tracksInGroup,r=this.selectDefaultTrack;for(let n=0;n<t.length;n++){const i=t[n];if((!r||i.default)&&(r||e)&&(!e||Pf(i,e)))return n}if(e){for(let r=0;r<t.length;r++){const n=t[r];if(Fv(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return r}for(let r=0;r<t.length;r++){const n=t[r];if(Fv(e.attrs,n.attrs,["LANGUAGE"]))return r}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let r=0;r<t.length;r++){if($v(t[r],e))return r}}return-1}onError(e,t){!t.fatal&&t.context&&(t.context.type!==Md||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}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(-1===e.id)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const r=this.currentTrack;if(r&&Pf(e,r))return r;const n=Cf(e,this.tracksInGroup);if(n>-1){const e=this.tracksInGroup[n];return this.setSubtitleTrack(n),e}if(r)return null;{const r=Cf(e,t);if(r>-1)return t[r]}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const r=e.id,n=e.groupId,i=this.getUrlWithDirectives(e.url,t),s=e.details,a=null==s?void 0:s.age;this.log(`Loading subtitle ${r} "${e.name}" lang:${e.lang} group:${n}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&s.live?" age "+a.toFixed(1)+(s.type&&" "+s.type||""):""} ${i}`),this.hls.trigger(Cd.SUBTITLE_TRACK_LOADING,{url:i,id:r,groupId:n,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Xy(e.textTracks),r=this.currentTrack;let n;if(r&&(n=t.filter(e=>$v(r,e))[0],n||this.warn(`Unable to find subtitle TextTrack with name "${r.name}" and language "${r.lang}"`)),[].slice.call(t).forEach(e=>{"disabled"!==e.mode&&e!==n&&(e.mode="disabled")}),n){const e=this.subtitleDisplay?"showing":"hidden";n.mode!==e&&(n.mode=e)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=e);if(e<-1||e>=t.length||!kd(e))return void this.warn(`Invalid subtitle track id: ${e}`);this.selectDefaultTrack=!1;const r=this.currentTrack,n=t[e]||null;if(this.trackId=e,this.currentTrack=n,this.toggleTrackModes(),!n)return void this.hls.trigger(Cd.SUBTITLE_TRACK_SWITCH,{id:e});const i=!!n.details&&!n.details.live;if(e===this.trackId&&n===r&&i)return;this.log(`Switching to subtitle-track ${e}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));const{id:s,groupId:a="",name:o,type:l,url:u}=n;this.hls.trigger(Cd.SUBTITLE_TRACK_SWITCH,{id:s,groupId:a,name:o,type:l,url:u});const c=this.switchParams(n.url,null==r?void 0:r.details,n.details);this.loadPlaylist(c)}},timelineController:class{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={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},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(Cd.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Cd.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Cd.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Cd.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Cd.FRAG_LOADING,this.onFragLoading,this),e.on(Cd.FRAG_LOADED,this.onFragLoaded,this),e.on(Cd.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(Cd.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(Cd.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Cd.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(Cd.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(Cd.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Cd.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Cd.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Cd.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Cd.FRAG_LOADING,this.onFragLoading,this),e.off(Cd.FRAG_LOADED,this.onFragLoaded,this),e.off(Cd.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(Cd.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(Cd.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Cd.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(Cd.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new nw(this,"textTrack1"),t=new nw(this,"textTrack2"),r=new nw(this,"textTrack3"),n=new nw(this,"textTrack4");this.cea608Parser1=new Ib(1,e,t),this.cea608Parser2=new Ib(3,r,n)}addCues(e,t,r,n,i){let s=!1;for(let e=i.length;e--;){const n=i[e],a=aw(n[0],n[1],t,r);if(a>=0&&(n[0]=Math.min(n[0],t),n[1]=Math.max(n[1],r),s=!0,a/(r-t)>.5))return}if(s||i.push([t,r]),this.config.renderTextTracksNatively){const i=this.captionsTracks[e];this.Cues.newCue(i,t,r,n)}else{const i=this.Cues.newCue(null,t,r,n);this.hls.trigger(Cd.CUES_PARSED,{type:"captions",cues:i,track:e})}}onInitPtsFound(e,{frag:t,id:r,initPTS:n,timescale:i,trackId:s}){const{unparsedVttFrags:a}=this;r===Od&&(this.initPTS[t.cc]={baseTime:n,timescale:i,trackId:s}),a.length&&(this.unparsedVttFrags=[],a.forEach(e=>{this.initPTS[e.frag.cc]?this.onFragLoaded(Cd.FRAG_LOADED,e):this.hls.trigger(Cd.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:r}=this;if(r)for(let n=0;n<r.textTracks.length;n++){const i=r.textTracks[n];if(sw(i,{name:e,lang:t,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:t,captionsTracks:r,media:n}=this,{label:i,languageCode:s}=t[e],a=this.getExistingTrack(i,s);if(a)r[e]=a,Yy(r[e]),Wy(r[e],n);else{const t=this.createTextTrack("captions",i,s);t&&(t[e]=!0,r[e]=t)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const r={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(Cd.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}createTextTrack(e,t,r){const n=this.media;if(n)return n.addTextTrack(e,t,r)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const r=!!t.transferMedia;if(this.media=null,r)return;const{captionsTracks:n}=this;Object.keys(n).forEach(e=>{Yy(n[e]),delete n[e]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},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 t=e.textTracks;if(t)for(let e=0;e<t.length;e++)Yy(t[e])}onSubtitleTracksUpdated(e,t){const r=t.subtitleTracks||[],n=r.some(e=>e.textCodec===Wb);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(Nv(this.tracks,r))return void(this.tracks=r);if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){const e=this.media,t=e?Xy(e.textTracks):null;if(this.tracks.forEach((e,r)=>{let n;if(t){let r=null;for(let n=0;n<t.length;n++)if(t[n]&&sw(t[n],e)){r=t[n],t[n]=null;break}r&&(n=r)}if(n)Yy(n);else{const t=iw(e);n=this.createTextTrack(t,e.name,e.lang),n&&(n.mode="disabled")}n&&this.textTracks.push(n)}),null!=t&&t.length){const e=t.filter(e=>null!==e).map(e=>e.label);e.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${e.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const e=this.tracks.map(e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}));this.hls.trigger(Cd.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(e=>{const t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;const r=`textTrack${t[1]}`,n=this.captionsProperties[r];n&&(n.label=e.name,e.lang&&(n.languageCode=e.lang),n.media=e)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===Od){var r,n;const{cea608Parser1:e,cea608Parser2:i,lastSn:s}=this,{cc:a,sn:o}=t.frag,l=null!=(r=null==(n=t.part)?void 0:n.index)?r:-1;e&&i&&(o!==s+1||o===s&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(e.reset(),i.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(e,t){const{frag:r,payload:n}=t;if(r.type===Fd)if(n.byteLength){const e=r.decryptdata,i="stats"in t;if(null==e||!e.encrypted||i){const e=this.tracks[r.level],i=this.vttCCs;i[r.cc]||(i[r.cc]={start:r.start,prevCC:this.prevCC,new:!0},this.prevCC=r.cc),e&&e.textCodec===Wb?this._parseIMSC1(r,n):this._parseVTTs(t)}}else this.hls.trigger(Cd.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const r=this.hls;Xb(t,this.initPTS[e.cc],t=>{this._appendCues(t,e.level),r.trigger(Cd.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},t=>{r.logger.log(`Failed to parse IMSC1: ${t}`),r.trigger(Cd.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})})}_parseVTTs(e){var t;const{frag:r,payload:n}=e,{initPTS:i,unparsedVttFrags:s}=this,a=i.length-1;if(!i[r.cc]&&-1===a)return void s.push(e);const o=this.hls;Vb(null!=(t=r.initSegment)&&t.data?$h(r.initSegment.data,new Uint8Array(n)).buffer:n,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,e=>{this._appendCues(e,r.level),o.trigger(Cd.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})},t=>{const i="Missing initPTS for VTT MPEGTS"===t.message;i?s.push(e):this._fallbackToIMSC1(r,n),o.logger.log(`Failed to parse VTT cue: ${t}`),i&&a>r.cc||o.trigger(Cd.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:t})})}_fallbackToIMSC1(e,t){const r=this.tracks[e.level];r.textCodec||Xb(t,this.initPTS[e.cc],()=>{r.textCodec=Wb,this._parseIMSC1(e,t)},()=>{r.textCodec="wvtt"})}_appendCues(e,t){const r=this.hls;if(this.config.renderTextTracksNatively){const r=this.textTracks[t];if(!r||"disabled"===r.mode)return;e.forEach(e=>Ky(r,e))}else{const n=this.tracks[t];if(!n)return;const i=n.default?"default":"subtitles"+t;r.trigger(Cd.CUES_PARSED,{type:"subtitles",cues:e,track:i})}}onFragDecrypted(e,t){const{frag:r}=t;r.type===Fd&&this.onFragLoaded(Cd.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:r,samples:n}=t;if(r.type!==Od||"NONE"!==this.closedCaptionsForLevel(r))for(let e=0;e<n.length;e++){const t=n[e].bytes;if(t){this.cea608Parser1||this.initCea608Parsers();const r=this.extractCea608Data(t);this.cea608Parser1.addData(n[e].pts,r[0]),this.cea608Parser2.addData(n[e].pts,r[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:r,endOffsetSubtitles:n,type:i}){const{media:s}=this;if(s&&!(s.currentTime<r)){if(!i||"video"===i){const{captionsTracks:e}=this;Object.keys(e).forEach(n=>qy(e[n],t,r))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==n){const{textTracks:e}=this;Object.keys(e).forEach(r=>qy(e[r],t,n))}}}extractCea608Data(e){const t=[[],[]],r=31&e[0];let n=2;for(let i=0;i<r;i++){const r=e[n++],i=127&e[n++],s=127&e[n++];if(0===i&&0===s)continue;if(!!(4&r)){const e=3&r;0!==e&&1!==e||(t[e].push(i),t[e].push(s))}}return t}},audioStreamController:class extends nm{constructor(e,t,r){super(e,t,r,"audio-stream-controller",Nd),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(Cd.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Cd.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(Cd.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Cd.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Cd.BUFFER_RESET,this.onBufferReset,this),e.on(Cd.BUFFER_CREATED,this.onBufferCreated,this),e.on(Cd.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Cd.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Cd.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Cd.FRAG_LOADING,this.onFragLoading,this),e.on(Cd.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(Cd.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Cd.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(Cd.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Cd.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Cd.BUFFER_RESET,this.onBufferReset,this),e.off(Cd.BUFFER_CREATED,this.onBufferCreated,this),e.off(Cd.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Cd.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Cd.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Cd.FRAG_LOADING,this.onFragLoading,this),e.off(Cd.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:r,initPTS:n,timescale:i,trackId:s}){if(r===Od){const e=t.cc,r=this.fragCurrent;if(this.initPTS[e]={baseTime:n,timescale:i,trackId:s},this.log(`InitPTS for cc: ${e} found from main: ${n/i} (${n}/${i}) trackId: ${s}`),this.mainAnchor=t,this.state===tm){const r=this.waitingData;(!r&&!this.loadingParts||r&&r.frag.cc!==e)&&this.syncWithAnchor(t,null==r?void 0:r.frag)}else!this.hls.hasEnoughToStart&&r&&r.cc!==e?(r.abortRequests(),this.syncWithAnchor(t,r)):this.state===Wg&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var r;const n=(null==(r=this.mainFragLoading)?void 0:r.frag)||null;if(t&&(null==n?void 0:n.cc)===t.cc)return;const i=(n||e).cc,s=Bf(this.getLevelDetails(),i,this.getLoadPosition());s&&(this.log(`Syncing with main frag at ${s.start} cc ${s.cc}`),this.startFragRequested=!1,this.nextLoadPosition=s.start,this.resetLoadingState(),this.state===Wg&&this.doTickIdle())}startLoad(e,t){if(!this.levels)return this.startPosition=e,void(this.state=Vg);const r=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),r>0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r,this.state=Wg):this.state=Xg,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case Wg:this.doTickIdle();break;case Xg:{const{levels:e,trackId:t}=this,r=null==e?void 0:e[t],n=null==r?void 0:r.details;if(n&&!this.waitForLive(r)){if(this.waitForCdnTuneIn(n))break;this.state=tm}break}case qg:this.checkRetryDate();break;case tm:{const e=this.waitingData;if(e){const{frag:t,part:r,cache:n,complete:i}=e,s=this.mainAnchor;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.state=Yg;const e={frag:t,part:r,payload:n.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(e),i&&super._handleFragmentLoadComplete(e)}else s&&s.cc!==e.frag.cc&&this.syncWithAnchor(s,e.frag)}else this.state=Wg}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:r,media:n,trackId:i}=this,s=t.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!s.startFragPrefetch)||null==r||!r[i])return;const a=r[i],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=Xg,void(this.startFragRequested=!1);const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,hh,Nd));const u=this.getFwdBufferInfo(l,Nd);if(null===u)return;if(!this.switchingTrack&&this._streamEnded(u,o))return t.trigger(Cd.BUFFER_EOS,{type:"audio"}),void(this.state=Jg);const c=u.len,d=t.maxBufferLength,h=o.fragments,f=h[0].start,p=this.getLoadPosition(),g=this.flushing?p:u.end;if(this.switchingTrack&&n){const e=p;o.PTSKnown&&e<f&&(u.end>f||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=f+.05)}if(c>=d&&!this.switchingTrack&&g<h[h.length-1].start)return;let m=this.getNextFragment(g,o);if(m&&this.isLoopLoading(m,g)&&(m=this.getNextFragmentLoopLoading(m,o,u,Od,d)),!m)return void(this.bufferFlushed=!0);let v=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&mh(m)&&!m.endList&&(!o.live||!this.loadingParts&&g<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===ap&&(this.mainFragLoading=v=null),v&&mh(v))){if(m.start>v.end){const e=this.fragmentTracker.getFragAtPos(g,Od);e&&e.end>v.end&&(v=e,this.mainFragLoading={frag:e,targetBufferTime:null})}if(m.start>v.end)return}this.loadFragment(m,a,g)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(e=>new Tf(e))}onAudioTrackSwitching(e,t){const r=!!t.url;this.trackId=t.id;const{fragCurrent:n}=this;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),r?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==Vg&&(this.setInterval(100),this.state=Wg,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const r=this.cachedTrackLoadedData;r&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(Cd.AUDIO_TRACK_LOADED,r))}onAudioTrackLoaded(e,t){var r;const{levels:n}=this,{details:i,id:s,groupId:a,track:o}=t;if(!n)return void this.warn(`Audio tracks reset while loading track ${s} "${o.name}" of "${a}"`);const l=this.mainDetails;if(!l||i.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==Vg&&(this.state=Xg));this.cachedTrackLoadedData=null,this.log(`Audio track ${s} "${o.name}" of "${a}" loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:""},duration:${i.totalduration}`);const u=n[s];let c=0;if(i.live||null!=(r=u.details)&&r.live){if(this.checkLiveUpdate(i),i.deltaUpdateFailed)return;var d;if(u.details)c=this.alignPlaylists(i,u.details,null==(d=this.levelLastLoaded)?void 0:d.details);i.alignedSliding||(Ug(i,l),i.alignedSliding||zg(i,l),c=i.fragmentStart)}u.details=i,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(l,c),this.hls.trigger(Cd.AUDIO_TRACK_UPDATED,{details:i,id:s,groupId:t.groupId}),this.state!==Xg||this.waitForCdnTuneIn(i)||(this.state=Wg),this.tick()}_handleFragmentLoadProgress(e){var t;const r=e.frag,{part:n,payload:i}=e,{config:s,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const u=l.details;if(!u)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(r.start);const c=s.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new Mv(this.hls,Nd,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const h=this.initPTS[r.cc],f=null==(t=r.initSegment)?void 0:t.data;if(void 0!==h){const e=!1,t=n?n.index:-1,s=-1!==t,a=new Tp(r.level,r.sn,r.stats.chunkCount,i.byteLength,t,s);d.push(i,f,c,"",r,n,u.totalduration,e,a,h)}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 ${a}`);const{cache:e}=this.waitingData=this.waitingData||{frag:r,part:n,cache:new sm,complete:!1};e.push(new Uint8Array(i)),this.state!==Vg&&(this.state=tm)}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const r=t.tracks.audio;r&&(this.mediaBuffer=r.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===Od&&mh(t.frag)&&(this.mainFragLoading=t,this.state===Wg&&this.tick())}onFragBuffered(e,t){const{frag:r,part:n}=t;if(r.type===Nd)if(this.fragContextChanged(r))this.warn(`Fragment ${r.sn}${n?" p: "+n.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(mh(r)){this.fragPrevious=r;const e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(Cd.AUDIO_TRACK_SWITCHED,Gd({},e)))}this.fragBufferedComplete(r,n),this.media&&this.tick()}else this.audioOnly||r.type!==Od||r.elementaryStreams.video||r.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(e,t){var r;if(t.fatal)this.state=em;else switch(t.details){case Id.FRAG_GAP:case Id.FRAG_PARSING_ERROR:case Id.FRAG_DECRYPT_ERROR:case Id.FRAG_LOAD_ERROR:case Id.FRAG_LOAD_TIMEOUT:case Id.KEY_LOAD_ERROR:case Id.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Nd,t);break;case Id.AUDIO_TRACK_LOAD_ERROR:case Id.AUDIO_TRACK_LOAD_TIMEOUT:case Id.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Xg||(null==(r=t.context)?void 0:r.type)!==_d||(this.state=Wg);break;case Id.BUFFER_ADD_CODEC_ERROR:case Id.BUFFER_APPEND_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case Id.BUFFER_FULL_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case Id.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==fh&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==fh){this.flushing=!1,this.bufferFlushed=!0,this.state===Jg&&(this.state=Wg);const e=this.mediaBuffer||this.media;e&&(this.afterBufferFlushed(e,t,Nd),this.tick())}}_handleTransmuxComplete(e){var t;const r="audio",{hls:n}=this,{remuxResult:i,chunkMeta:s}=e,a=this.getCurrentContext(s);if(!a)return void this.resetWhenMissingContext(s);const{frag:o,part:l,level:u}=a,{details:c}=u,{audio:d,text:h,id3:f,initSegment:p}=i;if(!this.fragContextChanged(o)&&c){if(this.state=Qg,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),null!=p&&p.tracks){const e=o.initSegment||o;if(this.unhandledEncryptionError(p,o))return;this._bufferInitSegment(u,p.tracks,e,s),n.trigger(Cd.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:r,tracks:p.tracks})}if(d){const{startPTS:e,endPTS:t,startDTS:r,endDTS:n}=d;l&&(l.elementaryStreams[hh]={startPTS:e,endPTS:t,startDTS:r,endDTS:n}),o.setElementaryStreamInfo(hh,e,t,r,n),this.bufferFragmentData(d,o,l,s)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=zd({id:r,frag:o,details:c},f);n.trigger(Cd.FRAG_PARSING_METADATA,e)}if(h){const e=zd({id:r,frag:o,details:c},h);n.trigger(Cd.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(e,t,r,n){if(this.state!==Qg)return;if(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio)return;const i=t.audio;i.id=Nd;const s=e.audioCodec;this.log(`Init audio buffer, container:${i.container}, codecs[level/parsed]=[${s}/${i.codec}]`),s&&1===s.split(",").length&&(i.levelCodec=s),this.hls.trigger(Cd.BUFFER_CODECS,t);const a=i.initSegment;if(null!=a&&a.byteLength){const e={type:"audio",frag:r,part:null,chunkMeta:n,parent:r.type,data:a};this.hls.trigger(Cd.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,r){const n=this.fragmentTracker.getState(e);var i;if(this.switchingTrack||n===np||n===sp)if(mh(e))if(null!=(i=t.details)&&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=tm;const r=this.mainDetails;r&&r.fragmentStart!==t.details.fragmentStart&&zg(t.details,r)}else super.loadFragment(e,t,r);else this._loadInitSegment(e,t);else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:r,assocLang:n,characteristics:i,audioCodec:s,channels:a}=this.bufferedTrack;Pf({name:t,lang:r,assocLang:n,characteristics:i,audioCodec:s,channels:a},e,Df)||(Mf(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:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(Cd.AUDIO_TRACK_SWITCHED,Gd({},e))}},audioTrackController:class extends Ov{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(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Cd.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Cd.LEVEL_LOADING,this.onLevelLoading,this),e.on(Cd.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Cd.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Cd.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Cd.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Cd.LEVEL_LOADING,this.onLevelLoading,this),e.off(Cd.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Cd.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Cd.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,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:r,groupId:n,details:i}=t,s=this.tracksInGroup[r];if(!s||s.groupId!==n)return void this.warn(`Audio track with id:${r} and group:${n} not found in active group ${null==s?void 0:s.groupId}`);const a=s.details;s.details=t.details,this.log(`Audio track ${r} "${s.name}" lang:${s.lang} group:${n} loaded [${i.startSN}-${i.endSN}]`),r===this.trackId&&this.playlistLoaded(r,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const r=t.audioGroups||null,n=this.groupIds;let i=this.currentTrack;if(!r||(null==n?void 0:n.length)!==(null==r?void 0:r.length)||null!=r&&r.some(e=>-1===(null==n?void 0:n.indexOf(e)))){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter(e=>!r||-1!==r.indexOf(e.groupId));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.audioPreference;if(!i&&t){const r=Cf(t,e,Df);if(r>-1)i=e[r];else{const e=Cf(t,this.tracks);i=this.tracks[e]}}let n=this.findTrackId(i);-1===n&&i&&(n=this.findTrackId(null));const a={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${null==r?void 0:r.join(",")}`),this.hls.trigger(Cd.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==n&&-1===o)this.setAudioTrack(n);else if(e.length&&-1===o){var s;const t=new Error(`No audio track selected for current audio group-ID(s): ${null==(s=this.groupIds)?void 0:s.join(",")} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(Cd.ERROR,{type:Ld.MEDIA_ERROR,details:Id.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}}onError(e,t){!t.fatal&&t.context&&(t.context.type!==_d||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}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 t=this.hls;if(t.config.audioPreference=e,e){const r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){const n=this.currentTrack;if(n&&Pf(e,n,Df))return n;const i=Cf(e,this.tracksInGroup,Df);if(i>-1){const e=this.tracksInGroup[i];return this.setAudioTrack(i),e}if(n){let n=t.loadLevel;-1===n&&(n=t.firstAutoLevel);const i=function(e,t,r,n,i){const s=t[n],a=t.reduce((e,t,r)=>{const n=t.uri;return(e[n]||(e[n]=[])).push(r),e},{})[s.uri];a.length>1&&(n=Math.max.apply(Math,a));const o=s.videoRange,l=s.frameRate,u=s.codecSet.substring(0,4),c=_f(t,n,t=>{if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==u)return!1;const n=t.audioGroups,s=r.filter(e=>!n||-1!==n.indexOf(e.groupId));return Cf(e,s,i)>-1});return c>-1?c:_f(t,n,t=>{const n=t.audioGroups,s=r.filter(e=>!n||-1!==n.indexOf(e.groupId));return Cf(e,s,i)>-1})}(e,t.levels,r,n,Df);if(-1===i)return null;t.nextLoadLevel=i}if(e.channels||e.audioCodec){const t=Cf(e,r);if(t>-1)return r[t]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn(`Invalid audio track id: ${e}`);this.selectDefaultTrack=!1;const r=this.currentTrack,n=t[e],i=n.details&&!n.details.live;if(e===this.trackId&&n===r&&i)return;if(this.log(`Switching to audio-track ${e} "${n.name}" lang:${n.lang} group:${n.groupId} channels:${n.channels}`),this.trackId=e,this.currentTrack=n,this.hls.trigger(Cd.AUDIO_TRACK_SWITCHING,Gd({},n)),i)return;const s=this.switchParams(n.url,null==r?void 0:r.details,n.details);this.loadPlaylist(s)}findTrackId(e){const t=this.tracksInGroup;for(let r=0;r<t.length;r++){const n=t[r];if((!this.selectDefaultTrack||n.default)&&(!e||Pf(e,n,Df)))return r}if(e){const{name:r,lang:n,assocLang:i,characteristics:s,audioCodec:a,channels:o}=e;for(let e=0;e<t.length;e++){if(Pf({name:r,lang:n,assocLang:i,characteristics:s,audioCodec:a,channels:o},t[e],Df))return e}for(let r=0;r<t.length;r++){const n=t[r];if(Fv(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return r}for(let r=0;r<t.length;r++){const n=t[r];if(Fv(e.attrs,n.attrs,["LANGUAGE"]))return r}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&Mf(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const r=e.id,n=e.groupId,i=this.getUrlWithDirectives(e.url,t),s=e.details,a=null==s?void 0:s.age;this.log(`Loading audio-track ${r} "${e.name}" lang:${e.lang} group:${n}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&s.live?" age "+a.toFixed(1)+(s.type&&" "+s.type||""):""} ${i}`),this.hls.trigger(Cd.AUDIO_TRACK_LOADING,{url:i,id:r,groupId:n,deliveryDirectives:t||null,track:e})}},emeController:zy,cmcdController:class{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=e=>{try{this.apply(e,{ot:Wv.MANIFEST,su:!this.initialized})}catch(e){this.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{const{frag:t,part:r}=e,n=this.hls.levels[t.level],i=this.getObjectType(t),s={d:1e3*(r||t).duration,ot:i};i!==Wv.VIDEO&&i!==Wv.AUDIO&&i!=Wv.MUXED||(s.br=n.bitrate/1e3,s.tb=this.getTopBandwidth(i)/1e3,s.bl=this.getBufferLength(i));const a=r?this.getNextPart(r):this.getNextFrag(t);null!=a&&a.url&&a.url!==t.url&&(s.nor=a.url),this.apply(e,s)}catch(e){this.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=e;const t=this.config=e.config,{cmcd:r}=t;null!=r&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=r.sessionId||e.sessionId,this.cid=r.contentId,this.useHeaders=!0===r.useHeaders,this.includeKeys=r.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(Cd.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Cd.MEDIA_DETACHED,this.onMediaDetached,this),e.on(Cd.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(Cd.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Cd.MEDIA_DETACHED,this.onMediaDetached,this),e.off(Cd.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,t){this.media=t.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,t){var r,n;this.audioBuffer=null==(r=t.tracks.audio)?void 0:r.buffer,this.videoBuffer=null==(n=t.tracks.video)?void 0:n.buffer}createData(){var e;return{v:1,sf:Kv.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){zd(t,this.createData());const r=t.ot===Wv.INIT||t.ot===Wv.VIDEO||t.ot===Wv.MUXED;this.starved&&r&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);const{includeKeys:n}=this;n&&(t=Object.keys(t).reduce((e,r)=>(n.includes(r)&&(e[r]=t[r]),e),{}));const i={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),Oy(e.headers,t,i)):e.url=$y(e.url,t,i)}getNextFrag(e){var t;const r=null==(t=this.hls.levels[e.level])?void 0:t.details;if(r){const t=e.sn-r.startSN;return r.fragments[t+1]}}getNextPart(e){var t;const{index:r,fragment:n}=e,i=null==(t=this.hls.levels[n.level])||null==(t=t.details)?void 0:t.partList;if(i){const{sn:e}=n;for(let t=i.length-1;t>=0;t--){const n=i[t];if(n.index===r&&n.fragment.sn===e)return i[t+1]}}}getObjectType(e){const{type:t}=e;return"subtitle"===t?Wv.TIMED_TEXT:"initSegment"===e.sn?Wv.INIT:"audio"===t?Wv.AUDIO:"main"===t?this.hls.audioTracks.length?Wv.VIDEO:Wv.MUXED:void 0}getTopBandwidth(e){let t,r=0;const n=this.hls;if(e===Wv.AUDIO)t=n.audioTracks;else{const e=n.maxAutoLevel,r=e>-1?e+1:n.levels.length;t=n.levels.slice(0,r)}return t.forEach(e=>{e.bitrate>r&&(r=e.bitrate)}),r>0?r:NaN}getBufferLength(e){const t=this.media,r=e===Wv.AUDIO?this.audioBuffer:this.videoBuffer;if(!r||!t)return NaN;return 1e3*kp.bufferInfo(r,t.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,r=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new r(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,r,n){t(e),this.loader.load(e,r,n)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,r=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new r(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,r,n){t(e),this.loader.load(e,r,n)}}}},contentSteeringController:class extends Hd{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(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Cd.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Cd.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Cd.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Cd.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Cd.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Cd.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.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=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(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 t=this.levels;t&&(this.levels=t.filter(t=>t!==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,t){const{contentSteering:r}=t;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:r}=t;if((null==r?void 0:r.action)===qf&&r.flags===Jf){const e=this.levels;let n=this._pathwayPriority,i=this.pathwayId;if(t.context){const{groupId:r,pathwayId:n,type:s}=t.context;r&&e?i=this.getPathwayForGroupId(r,s,i):n&&(i=n)}i in this.penalizedPathways||(this.penalizedPathways[i]=performance.now()),!n&&e&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),r.resolved=this.pathwayId!==i),t.details!==Id.BUFFER_APPEND_ERROR||t.fatal?r.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${i} levels: ${e?e.length:e} priorities: ${Af(n)} penalized: ${Af(this.penalizedPathways)}`):r.resolved=!0}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){const r=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${r}"`),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){let t;this._pathwayPriority=e;const r=this.penalizedPathways,n=performance.now();Object.keys(r).forEach(e=>{n-r[e]>3e5&&delete r[e]});for(let n=0;n<e.length;n++){const i=e[n];if(i in r)continue;if(i===this.pathwayId)return;const s=this.hls.nextLoadLevel,a=this.hls.levels[s];if(t=this.getLevelsForPathway(i),t.length>0){this.log(`Setting Pathway to "${i}"`),this.pathwayId=i,Mg(t),this.hls.trigger(Cd.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[s];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=s);break}}}getPathwayForGroupId(e,t,r){const n=this.getLevelsForPathway(r).concat(this.levels||[]);for(let r=0;r<n.length;r++)if(t===_d&&n[r].hasAudioGroup(e)||t===Md&&n[r].hasSubtitleGroup(e))return n[r].pathwayId;return r}clonePathways(e){const t=this.levels;if(!t)return;const r={},n={};e.forEach(e=>{const{ID:i,"BASE-ID":s,"URI-REPLACEMENT":a}=e;if(t.some(e=>e.pathwayId===i))return;const o=this.getLevelsForPathway(s).map(e=>{const t=new _p(e.attrs);t["PATHWAY-ID"]=i;const s=t.AUDIO&&`${t.AUDIO}_clone_${i}`,o=t.SUBTITLES&&`${t.SUBTITLES}_clone_${i}`;s&&(r[t.AUDIO]=s,t.AUDIO=s),o&&(n[t.SUBTITLES]=o,t.SUBTITLES=o);const l=Uy(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),u=new Tf({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t<e.audioGroups.length;t++)u.addGroupId("audio",`${e.audioGroups[t]}_clone_${i}`);if(e.subtitleGroups)for(let t=1;t<e.subtitleGroups.length;t++)u.addGroupId("text",`${e.subtitleGroups[t]}_clone_${i}`);return u});t.push(...o),By(this.audioTracks,r,a,i),By(this.subtitleTracks,n,a,i)})}loadSteeringManifest(e){const t=this.hls.config,r=t.loader;let n;this.loader&&this.loader.destroy(),this.loader=new r(t);try{n=new self.URL(e)}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${e}`)}if("data:"!==n.protocol){const e=0|(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate);n.searchParams.set("_HLS_pathway",this.pathwayId),n.searchParams.set("_HLS_throughput",""+e)}const i={responseType:"json",url:n.href},s=t.steeringManifestLoadPolicy.default,a=s.errorRetry||s.timeoutRetry||{},o={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(e,t,r,i)=>{this.log(`Loaded steering manifest: "${n}"`);const s=e.data;if(1!==(null==s?void 0:s.VERSION))return void this.log(`Steering VERSION ${s.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=s.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=s;if(a)try{this.uri=new self.URL(a,n).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||r.url),o&&this.clonePathways(o);const u={steeringManifest:s,url:n.toString()};this.hls.trigger(Cd.STEERING_MANIFEST_LOADED,u),l&&this.updatePathwayPriority(l)},onError:(e,t,r,n)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let i=1e3*this.timeToLoad;if(429===e.code){const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(i=1e3*parseFloat(t))}return void this.log(`Steering manifest ${t.url} rate limited`)}this.scheduleRefresh(this.uri||t.url,i)},onTimeout:(e,t,r)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(i,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var t;const r=null==(t=this.hls)?void 0:t.media;!r||r.ended?this.scheduleRefresh(e,1e3*this.timeToLoad):this.loadSteeringManifest(e)},t)}},interstitialsController:class extends Hd{constructor(e,t){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 e=this.currentTime;if(void 0===e||this.playbackDisabled||!this.schedule)return;const t=e-this.timelinePos;if(Math.abs(t)<1/7056e5)return;const r=t<=-.01;this.timelinePos=e,this.bufferedPos=e;const n=this.playingItem;if(!n)return void this.checkBuffer();if(r){this.schedule.resetErrorsInRange(e,e-t)&&this.updateSchedule(!0)}if(this.checkBuffer(),r&&e<n.start||e>=n.end){var i;const t=this.findItemIndex(n);let s=this.schedule.findItemIndexAtTime(e);if(-1===s&&(s=t+(r?-1:1),this.log(`seeked ${r?"back ":""}to position not covered by schedule ${e} (resolving from ${t} to ${s})`)),!this.isInterstitial(n)&&null!=(i=this.media)&&i.paused&&(this.shouldPlay=!1),!r&&s>t){const e=this.schedule.findJumpRestrictedIndex(t+1,s);if(e>t)return void this.setSchedulePosition(e)}return void this.setSchedulePosition(s)}const s=this.playingAsset;if(!s){if(this.playingLastItem&&this.isInterstitial(n)){const t=n.event.assetList[0];t&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(e,t))}return}const a=s.timelineStart,o=s.duration||0;var l;(r&&e<a||e>=a+o)&&(null!=(l=n.event)&&l.appendInPlace&&(this.clearAssetPlayers(n.event,n),this.flushFrontBuffer(e)),this.setScheduleToAssetAtTime(e,s))},this.onTimeupdate=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled)return;if(!(e>this.timelinePos))return;this.timelinePos=e,e>this.bufferedPos&&this.checkBuffer();const t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}const r=this.playingAsset;if(!r)return;e>=r.timelineStart+(r.duration||0)&&this.setScheduleToAssetAtTime(e,r)},this.onScheduleUpdate=(e,t)=>{const r=this.schedule;if(!r)return;const n=this.playingItem,i=r.events||[],s=r.items||[],a=r.durations,o=e.map(e=>e.identifier),l=!(!i.length&&!o.length);(l||t)&&this.log(`INTERSTITIALS_UPDATED (${i.length}): ${i}\nSchedule: ${s.map(e=>lb(e))} pos: ${this.timelinePos}`),o.length&&this.log(`Removed events ${o}`);let u=null,c=null;n&&(u=this.updateItem(n,this.timelinePos),this.itemsMatch(n,u)?this.playingItem=u:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const d=this.bufferingItem;if(d&&(c=this.updateItem(d,this.bufferedPos),this.itemsMatch(d,c)?this.bufferingItem=c:d.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(d.event,null))),e.forEach(e=>{e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,null)})}),this.playerQueue.forEach(e=>{if(e.interstitial.appendInPlace){const t=e.assetItem.timelineStart,r=e.timelineOffset-t;if(r)try{e.timelineOffset=t}catch(n){Math.abs(r)>Zy&&this.warn(`${n} ("${e.assetId}" ${e.timelineOffset}->${t})`)}}}),l||t){if(this.hls.trigger(Cd.INTERSTITIALS_UPDATED,{events:i.slice(0),schedule:s.slice(0),durations:a,removedIds:o}),this.isInterstitial(n)&&o.includes(n.event.identifier))return this.warn(`Interstitial "${n.event.identifier}" removed while playing`),void this.primaryFallback(n.event);n&&this.trimInPlace(u,n),d&&c!==u&&this.trimInPlace(c,d),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new ub(e),this.schedule=new ob(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(Cd.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Cd.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Cd.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Cd.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Cd.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Cd.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(Cd.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Cd.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(Cd.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(Cd.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(Cd.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Cd.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Cd.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(Cd.MEDIA_ENDED,this.onMediaEnded,this),e.on(Cd.ERROR,this.onError,this),e.on(Cd.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(Cd.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Cd.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Cd.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Cd.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Cd.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Cd.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(Cd.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Cd.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(Cd.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(Cd.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(Cd.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Cd.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Cd.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Cd.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(Cd.MEDIA_ENDED,this.onMediaEnded,this),e.off(Cd.ERROR,this.onError,this),e.off(Cd.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.getBufferingPlayer())||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){Gg(e,"play",this.onPlay),Gg(e,"pause",this.onPause),Gg(e,"seeking",this.onSeeking),Gg(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const r=this.media=t.media;jg(r,"seeking",this.onSeeking),jg(r,"timeupdate",this.onTimeupdate),jg(r,"play",this.onPlay),jg(r,"pause",this.onPause)}onMediaAttached(e,t){const r=this.effectivePlayingItem,n=this.detachedData;if(this.detachedData=null,null===r)this.checkStart();else if(!n){this.clearScheduleState();const e=this.findItemIndex(r);this.setSchedulePosition(e)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const r=!!t.transferMedia,n=this.media;if(this.media=null,!r&&(n&&this.removeMediaListeners(n),this.detachedData)){const e=this.getBufferingPlayer();e&&(this.log(`Removing schedule state for detachedData and ${e}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,e.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,r=t=>t?e.getAssetPlayer(t.identifier):t,n=(t,n,s,a,o)=>{if(t){let l=t[n].start;const u=t.event;if(u){if("playout"===n||u.timelineOccupancy!==Jy.Point){const e=r(s);(null==e?void 0:e.interstitial)===u&&(l+=e.assetItem.startOffset+e[o])}}else{l+=("bufferedPos"===a?i():e[a])-t.start}return l}return 0},i=()=>{const t=e.bufferedPos;return t===Number.MAX_VALUE?s("primary"):Math.max(t,0)},s=t=>{var r,n;return null!=(r=e.primaryDetails)&&r.live?e.primaryDetails.edge:(null==(n=e.schedule)?void 0:n.durations[t])||0},a=(t,i)=>{var s,a;const o=e.effectivePlayingItem;if(null!=o&&null!=(s=o.event)&&s.restrictions.skip||!e.schedule)return;e.log(`seek to ${t} "${i}"`);const l=e.effectivePlayingItem,u=e.schedule.findItemIndexAtTime(t,i),c=null==(a=e.schedule.items)?void 0:a[u],d=e.getBufferingPlayer(),h=null==d?void 0:d.interstitial,f=null==h?void 0:h.appendInPlace,p=l&&e.itemsMatch(l,c);if(l&&(f||p)){const s=r(e.playingAsset),a=(null==s?void 0:s.media)||e.primaryMedia;if(a){const r="primary"===i?a.currentTime:n(l,i,e.playingAsset,"timelinePos","currentTime"),o=t-r,u=(f?r:a.currentTime)+o;if(u>=0&&(!s||f||u<=s.duration))return void(a.currentTime=u)}}if(c){let r=t;if("primary"!==i){const e=t-c[i].start;r=c.start+e}const n=!e.isInterstitial(c);if(e.isInterstitial(l)&&!l.event.appendInPlace||!n&&!c.event.appendInPlace){if(l){const s=e.findItemIndex(l);if(u>s){const t=e.schedule.findJumpRestrictedIndex(s+1,u);if(t>s)return void e.setSchedulePosition(t)}let a=0;if(n)e.timelinePos=r,e.checkBuffer();else{const e=c.event.assetList,r=t-(c[i]||c).start;for(let t=e.length;t--;){const n=e[t];if(n.duration&&r>=n.startOffset&&r<n.startOffset+n.duration){a=t;break}}}e.setSchedulePosition(u,a)}}else{const t=e.media||(f?null==d?void 0:d.media:null);t&&(t.currentTime=r)}}},o=()=>{const r=e.effectivePlayingItem;if(e.isInterstitial(r))return r;const n=t();return e.isInterstitial(n)?n:null},l={get bufferedEnd(){const r=t(),i=e.bufferingItem;var s;return i&&i===r&&(n(i,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-i.playout.start||(null==(s=e.bufferingAsset)?void 0:s.startOffset))||0},get currentTime(){const t=o(),r=e.effectivePlayingItem;return r&&r===t?n(r,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-r.playout.start:0},set currentTime(t){const r=o(),n=e.effectivePlayingItem;n&&n===r&&a(t+n.playout.start,"playout")},get duration(){const e=o();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t;const r=null==(t=o())?void 0:t.event.assetList;return r?r.map(t=>e.getAssetPlayer(t.identifier)):[]},get playingIndex(){var t;const r=null==(t=o())?void 0:t.event;return r&&e.effectivePlayingAsset?r.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var t;return(null==(t=e.schedule)||null==(t=t.events)?void 0:t.slice(0))||[]},get schedule(){var t;return(null==(t=e.schedule)||null==(t=t.items)?void 0:t.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const r=t();return e.findItemIndex(r)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return i()},get currentTime(){const t=e.timelinePos;return t>0?t:0},set currentTime(e){a(e,"primary")},get duration(){return s("primary")},get seekableStart(){var t;return(null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0}},integrated:{get bufferedEnd(){return n(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return n(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){a(e,"integrated")},get duration(){return s("integrated")},get seekableStart(){var t;return((t,r)=>{var n;if(0!==t&&"primary"!==r&&null!=(n=e.schedule)&&n.length){var i;const n=e.schedule.findItemIndexAtTime(t),s=null==(i=e.schedule.items)?void 0:i[n];if(s)return t+(s[r].start-s.start)}return t})((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"integrated")}},skip:()=>{const t=e.effectivePlayingItem,r=null==t?void 0:t.event;if(r&&!r.restrictions.skip){const n=e.findItemIndex(t);if(r.appendInPlace){const e=t.playout.start+t.event.duration;a(e+.001,"playout")}else e.advanceAfterAssetEnded(r,n,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,r=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&r)&&this.findItemIndex(t)===r.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var e,t;if(null===this.mediaSelection)return;const r=this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&!r.event.appendInPlace)return;let n=this.media;!n&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(n=this.primaryMedia);const i=null==(t=n)?void 0:t.currentTime;return void 0!==i&&kd(i)?i:void 0}get primaryMedia(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}isInterstitial(e){return!(null==e||!e.event)}retreiveMediaSource(e,t){const r=this.getAssetPlayer(e);r&&this.transferMediaFromPlayer(r,t)}transferMediaFromPlayer(e,t){const r=e.interstitial.appendInPlace,n=e.media;if(r&&n===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&n)return void(this.detachedData={media:n});const r=e.transferMedia();this.log(`transfer MediaSource from ${e} ${Af(r)}`),this.detachedData=r}else t&&n&&(this.shouldPlay||(this.shouldPlay=!n.paused))}transferMediaTo(e,t){var r,n;if(e.media===t)return;let i=null;const s=this.hls,a=e!==s,o=a&&e.interstitial.appendInPlace,l=null==(r=this.detachedData)?void 0:r.mediaSource;let u;if(s.media)o&&(i=s.transferMedia(),this.detachedData=i),u="Primary";else if(l){const e=this.getBufferingPlayer();e?(i=e.transferMedia(),u=`${e}`):u="detached MediaSource"}else u="detached media";if(!i)if(l)i=this.detachedData,this.log(`using detachedData: MediaSource ${Af(i)}`);else if(!this.detachedData||s.media===t){const e=this.playerQueue;e.length>1&&e.forEach(e=>{if(a&&e.interstitial.appendInPlace!==o){const t=e.interstitial;this.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${t}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}const c=i&&"mediaSource"in i&&"closed"!==(null==(n=i.mediaSource)?void 0:n.readyState),d=c&&i?i:t;this.log(`${c?"transfering MediaSource":"attaching media"} to ${a?e:"Primary"} from ${u} (media.currentTime: ${t.currentTime})`);const h=this.schedule;if(d===i&&h){const t=a&&e.assetId===h.assetIdAtEnd;d.overrides={duration:h.duration,endOfStream:!a||t,cueRemoval:!a}}e.attachMedia(d)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=null==e?void 0:e.events;if(!t||this.playbackDisabled||!this.media)return;-1===this.bufferedPos&&(this.bufferedPos=0);const r=this.timelinePos,n=this.effectivePlayingItem;if(-1===r){const r=this.hls.startPosition;if(this.log(db("checkStart",r)),this.timelinePos=r,t.length&&t[0].cue.pre){const r=e.findEventIndex(t[0].identifier);this.setSchedulePosition(r)}else if(r>=0||!this.primaryLive){const t=this.timelinePos=r>0?r:0,n=e.findItemIndexAtTime(t);this.setSchedulePosition(n)}}else if(n&&!this.playingItem){const t=e.findItemIndex(n);this.setSchedulePosition(t)}}advanceAssetBuffering(e,t){const r=e.event,n=r.findAssetIndex(t),i=ib(r,n);if(r.isAssetPastPlayoutLimit(i)){if(this.schedule){var s;const t=null==(s=this.schedule.items)?void 0:s[this.findItemIndex(e)+1];t&&this.bufferedToItem(t)}}else this.bufferedToEvent(e,i)}advanceAfterAssetEnded(e,t,r){const n=ib(e,r);if(e.isAssetPastPlayoutLimit(n)){if(this.schedule){const r=this.schedule.items;if(r){const n=t+1;if(n>=r.length)return void this.setSchedulePosition(-1);const i=e.resumeTime;this.timelinePos<i&&(this.log(db("advanceAfterAssetEnded",i)),this.timelinePos=i,e.appendInPlace&&this.advanceInPlace(i),this.checkBuffer(this.bufferedPos<i)),this.setSchedulePosition(n)}}}else{if(e.appendInPlace){const t=e.assetList[n];t&&this.advanceInPlace(t.timelineStart)}this.setSchedulePosition(t,n)}}setScheduleToAssetAtTime(e,t){const r=this.schedule;if(!r)return;const n=t.parentIdentifier,i=r.getEvent(n);if(i){const t=r.findEventIndex(n),s=r.findAssetIndex(i,e);this.advanceAfterAssetEnded(i,t,s-1)}}setSchedulePosition(e,t){var r;const n=null==(r=this.schedule)?void 0:r.items;if(!n||this.playbackDisabled)return;const i=e>=0?n[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${i?lb(i):i}) pos: ${this.timelinePos}`);const s=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(s)){const r=s.event,u=this.playingAsset,c=null==u?void 0:u.identifier,d=c?this.getAssetPlayer(c):null;if(d&&c&&(!this.eventItemsMatch(s,i)||void 0!==t&&c!==r.assetList[t].identifier)){var o;const t=r.findAssetIndex(u);if(this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${r.assetList.length} ${sb(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(Cd.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:t,event:r,schedule:n.slice(0),scheduleIndex:e,player:d}),s!==this.playingItem)return void(this.itemsMatch(s,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(r,this.findItemIndex(this.playingItem),t));this.retreiveMediaSource(c,i),!d.media||null!=(o=this.detachedData)&&o.mediaSource||d.detachMedia()}if(!this.eventItemsMatch(s,i)&&(this.endedItem=s,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${r} ${lb(s)}`),r.hasPlayed=!0,this.hls.trigger(Cd.INTERSTITIAL_ENDED,{event:r,schedule:n.slice(0),scheduleIndex:e}),r.cue.once)){var l;this.updateSchedule();const e=null==(l=this.schedule)?void 0:l.items;if(i&&e){const r=this.findItemIndex(i);this.advanceSchedule(r,e,t,s,a)}return}}this.advanceSchedule(e,n,t,s,a)}advanceSchedule(e,t,r,n,i){const s=this.schedule;if(!s)return;const a=t[e]||null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(t=>{const r=t.interstitial,n=s.findEventIndex(r.identifier);(n<e||n>e+1)&&this.clearInterstitial(r,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const i=a.event;if(void 0===r){const t=ib(i,(r=s.findAssetIndex(i,this.timelinePos))-1);if(i.isAssetPastPlayoutLimit(t)||i.appendInPlace&&this.timelinePos===a.end)return void this.advanceAfterAssetEnded(i,e,r);r=t}const l=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let u=this.preloadAssets(i,r);if(this.eventItemsMatch(a,l||n)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${lb(a)} ${i.appendInPlace?"append in place":""}`),this.hls.trigger(Cd.INTERSTITIAL_STARTED,{event:i,schedule:t.slice(0),scheduleIndex:e})),!i.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${i}`);if(i.assetListLoader&&(i.assetListLoader.destroy(),i.assetListLoader=void 0),!o)return void this.log(`Waiting for attachMedia to start Interstitial ${i}`);this.waitingItem=this.endedItem=null,this.playingItem=a;const c=i.assetList[r];if(!c)return void this.advanceAfterAssetEnded(i,e,r||0);if(u||(u=this.getAssetPlayer(c.identifier)),null===u||u.destroyed){const e=i.assetList.length;this.warn(`asset ${r+1}/${e} player destroyed ${i}`),u=this.createAssetPlayer(i,c,r),u.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&i.appendInPlace&&this.isAssetBuffered(c))return;this.startAssetPlayer(u,r,t,e,o),this.shouldPlay&&cb(u.media)}else a?(this.resumePrimary(a,e,n),this.shouldPlay&&cb(this.hls.media)):i&&this.isInterstitial(n)&&(this.endedItem=null,this.playingItem=n,n.event.appendInPlace||this.attachPrimary(s.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}get primaryLive(){var e;return!(null==(e=this.primaryDetails)||!e.live)}resumePrimary(e,t,r){var n,i;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${lb(e)}`),null==(n=this.detachedData)||!n.mediaSource){let r=this.timelinePos;(r<e.start||r>=e.end)&&(r=this.getPrimaryResumption(e,t),this.log(db("resumePrimary",r)),this.timelinePos=r),this.attachPrimary(r,e)}if(!r)return;const s=null==(i=this.schedule)?void 0:i.items;s&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${lb(e)}`),this.hls.trigger(Cd.INTERSTITIALS_PRIMARY_RESUMED,{schedule:s.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const r=e.start;if(this.primaryLive){const e=this.primaryDetails;if(0===t)return this.hls.startPosition;if(e&&(r<e.fragmentStart||r>e.edge))return this.hls.liveSyncPosition||-1}return r}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);if(null!=t&&t.hls)return t.hls.bufferedToEnd;return kp.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,r){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const n=this.primaryMedia;if(!n)return;const i=this.hls;i.media?this.checkBuffer():(this.transferMediaTo(i,n),r&&this.startLoadingPrimaryAt(e,r)),r||(this.log(db("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,r))}startLoadingPrimaryAt(e,t){var r;const n=this.hls;!n.loadingEnabled||!n.media||Math.abs(((null==(r=n.mainForwardBufferInfo)?void 0:r.start)||n.media.currentTime)-e)>.5?n.startLoad(e,t):n.bufferingEnabled||n.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),null==(e=this.schedule)||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(Cd.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(Cd.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(-1===t.level||!this.schedule)return;const r=this.hls.levels[t.level];if(!r.details)return;const n=Gd(Gd({},this.mediaSelection||this.altSelection),{},{main:r});this.mediaSelection=n,this.schedule.parseInterstitialDateRanges(n,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const r=this.hls.audioTracks[t.id],n=this.mediaSelection;if(!n)return void(this.altSelection=Gd(Gd({},this.altSelection),{},{audio:r}));const i=Gd(Gd({},n),{},{audio:r});this.mediaSelection=i}onSubtitleTrackUpdated(e,t){const r=this.hls.subtitleTracks[t.id],n=this.mediaSelection;if(!n)return void(this.altSelection=Gd(Gd({},this.altSelection),{},{subtitles:r}));const i=Gd(Gd({},n),{},{subtitles:r});this.mediaSelection=i}onAudioTrackSwitching(e,t){const r=If(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setAudioOption(t)||e.setAudioOption(r)))}onSubtitleTrackSwitch(e,t){const r=If(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setSubtitleOption(t)||-1!==t.id&&e.setSubtitleOption(r)))}onBufferCodecs(e,t){const r=t.tracks;r&&(this.requiredTracks=r)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const r=this.playingItem;if(r&&!this.itemsMatch(r,this.bufferingItem)&&!this.isInterstitial(r)){const e=this.timelinePos;this.bufferedPos=e,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let e=0;e<t.length;e++){const n=t[e];if(n.cue.post){var r;const e=this.schedule.findEventIndex(n.identifier),t=null==(r=this.schedule.items)?void 0:r[e];this.isInterstitial(t)&&this.eventItemsMatch(t,this.bufferingItem)&&this.bufferedToItem(t,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}else this.shouldPlay=!1}updateItem(e,t){var r;const n=null==(r=this.schedule)?void 0:r.items;if(e&&n){return n[this.findItemIndex(e,t)]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((t,r)=>{e.event.isAssetPastPlayoutLimit(r)&&this.clearAssetPlayer(t.identifier,null)});const r=e.end+.25,n=kp.bufferInfo(this.primaryMedia,r,0);if(n.end>r||(n.nextStart||0)>r){this.log(`trim buffered interstitial ${lb(e)} (was ${lb(t)})`);const n=!0;this.attachPrimary(r,null,n),this.flushFrontBuffer(r)}}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var r;return!!t&&(e===t||e.event.identifier===(null==(r=t.event)?void 0:r.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const r=this.mediaSelection;r&&(null==(t=this.schedule)||t.updateSchedule(r,[],e))}checkBuffer(e){var t;const r=null==(t=this.schedule)?void 0:t.items;if(!r)return;const n=kp.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=n.len<1),this.updateBufferedPos(n.end,r,e)}updateBufferedPos(e,t,r){const n=this.schedule,i=this.bufferingItem;if(this.bufferedPos>e||!n)return;if(1===t.length&&this.itemsMatch(t[0],i))return void(this.bufferedPos=e);const s=this.playingItem,a=this.findItemIndex(s);let o=n.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const r=this.findItemIndex(i),n=Math.min(r+1,t.length-1),s=t[n];if((-1===o&&i&&e>=i.end||null!=(l=s.event)&&l.appendInPlace&&e+.01>=s.start)&&(o=n),this.isInterstitial(i)){const e=i.event;if(n-a>1&&!1===e.appendInPlace)return;if(0===e.assetList.length&&e.assetListLoader)return}if(this.bufferedPos=e,o>r&&o>a)this.bufferedToItem(s);else{const t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&s.start<t.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(s)&&this.preloadAssets(s.event,0)}}else r&&s&&!this.itemsMatch(s,i)&&(o===a?this.bufferedToItem(s):o===a+1&&this.bufferedToItem(t[o]))}assetsBuffered(e,t){return 0!==e.event.assetList.length&&!e.event.assetList.some(e=>{const r=this.getAssetPlayer(e.identifier);return!(null!=r&&r.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,r=this.schedule;if(!this.itemsMatch(e,t)&&r){const{items:n,events:i}=r;if(!n||!i)return t;const s=this.isInterstitial(e),a=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const o=a?a.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${lb(e)}`+(t?` (${o.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(s){const t=r.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((e,r)=>{const n=this.getAssetPlayer(e.identifier);n&&(r===t&&n.loadSource(),n.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(e=>e.pauseBuffering());this.hls.trigger(Cd.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:i.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const r=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==r){this.bufferingAsset=null;const t=this.detachedData;if(t)if(t.mediaSource){const t=!0;this.attachPrimary(e.start,e,t)}else this.preloadPrimary(e);else this.preloadPrimary(e)}}preloadPrimary(e){const t=this.findItemIndex(e),r=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(r)}bufferedToEvent(e,t){const r=e.event,n=0===r.assetList.length&&!r.assetListLoader,i=r.cue.once;if(n||!i){const e=this.preloadAssets(r,t);if(null!=e&&e.interstitial.appendInPlace){const t=this.primaryMedia;t&&this.bufferAssetPlayer(e,t)}}}preloadAssets(e,t){const r=e.assetUrl,n=e.assetList.length,i=0===n&&!e.assetListLoader,s=e.cue.once;if(i){const i=e.timelineStart;if(e.appendInPlace){var a;const t=this.playingItem;this.isInterstitial(t)||(null==t||null==(a=t.nextEvent)?void 0:a.identifier)!==e.identifier||this.flushFrontBuffer(i+.25)}let s,o=0;if(!this.playingItem&&this.primaryLive&&(o=this.hls.startPosition,-1===o&&(o=this.hls.liveSyncPosition||0)),o&&!e.cue.pre&&!e.cue.post){const e=o-i;e>0&&(s=Math.round(1e3*e)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${r?1:n} ${e}${s?` live-start: ${o} start-offset: ${s}`:""}`),r)return this.createAsset(e,0,0,i,e.duration,r);const l=this.assetListLoader.loadAssetList(e,s);l&&(e.assetListLoader=l)}else if(!s&&n){for(let r=t;r<n;r++){const t=e.assetList[r],n=this.getAssetPlayerQueueIndex(t.identifier);-1!==n&&!this.playerQueue[n].destroyed||t.error||this.createAssetPlayer(e,t,r)}const r=e.assetList[t];if(r){const e=this.getAssetPlayer(r.identifier);return e&&e.loadSource(),e}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`);Object.keys(t).forEach(t=>{this.hls.trigger(Cd.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let r=0;r<t.length;r++)if(e===t[r].assetId)return r;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t)for(let r=0;r<e.length;r++)if(e[r].media===t)return e[r];return null}createAsset(e,t,r,n,i,s){const a={parentIdentifier:e.identifier,identifier:eb(e,s,t),duration:i,startOffset:r,timelineStart:n,uri:s};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,r){const n=this.hls,i=n.userConfig;let s=i.videoPreference;const a=n.loadLevelObj||n.levels[n.currentLevel];(s||a)&&(s=zd({},s),a.videoCodec&&(s.videoCodec=a.videoCodec),a.videoRange&&(s.allowedVideoRanges=[a.videoRange]));const o=n.audioTracks[n.audioTrack],l=n.subtitleTracks[n.subtitleTrack];let u=0;if(this.primaryLive||e.appendInPlace){const e=this.timelinePos-t.timelineStart;if(e>1){const r=t.duration;r&&e<r&&(u=e)}}const c=t.identifier,d=Gd(Gd({},i),{},{maxMaxBufferLength:Math.min(180,n.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:c,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:s,audioPreference:o||i.audioPreference,subtitlePreference:l||i.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(d.timelineOffset=t.timelineStart));const h=d.cmcd;null!=h&&h.sessionId&&h.contentId&&(d.cmcd=zd({},h,{contentId:Qy(t.uri)})),this.getAssetPlayer(c)&&this.warn(`Duplicate date range identifier ${e} and asset ${c}`);const f=new ab(this.HlsPlayerClass,d,e,t);this.playerQueue.push(f),e.assetList[r]=t;let p=!0;const g=n=>{if(n.live){var i;const t=new Error(`Interstitials MUST be VOD assets ${e}`),n={fatal:!0,type:Ld.OTHER_ERROR,details:Id.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},s=(null==(i=this.schedule)?void 0:i.findEventIndex(e.identifier))||-1;return void this.handleAssetItemError(n,e,s,r,t.message)}const s=n.edge-n.fragmentStart,a=t.duration;(p||null===a||s>a)&&(p=!1,this.log(`Interstitial asset "${c}" duration change ${a} > ${s}`),t.duration=s,this.updateSchedule())};f.on(Cd.LEVEL_UPDATED,(e,{details:t})=>g(t)),f.on(Cd.LEVEL_PTS_UPDATED,(e,{details:t})=>g(t)),f.on(Cd.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const m=(e,t)=>{const r=this.getAssetPlayer(c);if(r&&t.tracks){r.off(Cd.BUFFER_CODECS,m),r.tracks=t.tracks;const e=this.primaryMedia;this.bufferingAsset===r.assetItem&&e&&!r.media&&this.bufferAssetPlayer(r,e)}};f.on(Cd.BUFFER_CODECS,m);f.on(Cd.BUFFERED_TO_END,()=>{var r;const n=this.getAssetPlayer(c);if(this.log(`buffered to end of asset ${n}`),!n||!this.schedule)return;const i=this.schedule.findEventIndex(e.identifier),s=null==(r=this.schedule.items)?void 0:r[i];this.isInterstitial(s)&&this.advanceAssetBuffering(s,t)});const v=t=>()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;this.shouldPlay=!0;const r=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,r,t)};return f.once(Cd.MEDIA_ENDED,v(r)),f.once(Cd.PLAYOUT_LIMIT_REACHED,v(1/0)),f.on(Cd.ERROR,(t,n)=>{if(!this.schedule)return;const i=this.getAssetPlayer(c);if(n.details===Id.BUFFER_STALLED_ERROR)return null!=i&&i.appendInPlace?void this.handleInPlaceStall(e):(this.onTimeupdate(),void this.checkBuffer(!0));this.handleAssetItemError(n,e,this.schedule.findEventIndex(e.identifier),r,`Asset player error ${n.error} ${e}`)}),f.on(Cd.DESTROYING,()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;const t=new Error(`Asset player destroyed unexpectedly ${c}`),n={fatal:!0,type:Ld.OTHER_ERROR,details:Id.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(n,e,this.schedule.findEventIndex(e.identifier),r,t.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${sb(t)}`),this.hls.trigger(Cd.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:r,event:e,player:f}),f}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log(`reset asset player "${e}" after error`);const r=this.playerQueue[t];this.transferMediaFromPlayer(r,null),r.resetDetails()}}clearAssetPlayer(e,t){const r=this.getAssetPlayerQueueIndex(e);if(-1!==r){const e=this.playerQueue[r];this.log(`clear ${e} toSegment: ${t?lb(t):t}`),this.transferMediaFromPlayer(e,t),this.playerQueue.splice(r,1),e.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,r,n,i){const{interstitial:s,assetItem:a,assetId:o}=e,l=s.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=a,u&&u.identifier===o||(u&&(this.clearAssetPlayer(u.identifier,r[n]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${sb(a)}`),this.hls.trigger(Cd.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:s,schedule:r.slice(0),scheduleIndex:n,player:e})),this.bufferAssetPlayer(e,i)}bufferAssetPlayer(e,t){var r,n;if(!this.schedule)return;const{interstitial:i,assetItem:s}=e,a=this.schedule.findEventIndex(i.identifier),o=null==(r=this.schedule.items)?void 0:r[a];if(!o)return;e.loadSource(),this.setBufferingItem(o),this.bufferingAsset=s;const l=this.getBufferingPlayer();if(l===e)return;const u=i.appendInPlace;if(u&&!1===(null==l?void 0:l.interstitial.appendInPlace))return;const c=(null==l?void 0:l.tracks)||(null==(n=this.detachedData)?void 0:n.tracks)||this.requiredTracks;if(u&&s!==this.playingAsset){if(!e.tracks)return void this.log(`Waiting for track info before buffering ${e}`);if(c&&!Zd(c,e.tracks)){const t=new Error(`Asset ${sb(s)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(c)}')`),r={fatal:!0,type:Ld.OTHER_ERROR,details:Id.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},n=i.findAssetIndex(s);return void this.handleAssetItemError(r,i,a,n,t.message)}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,r=this.primaryMedia;if(!t||!r)return;const n=r.currentTime,i=t.findAssetIndex(e,n),s=e.assetList[i];if(s){const a=this.getAssetPlayer(s.identifier);if(a){const o=a.currentTime||n-s.timelineStart,l=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+l} in ${a} ${e} (media.currentTime: ${n})`),o&&(l/r.playbackRate<.5||a.bufferedInPlaceToEnd(r))&&a.hls){const r=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,r,i)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,r,n,i){if(e.details===Id.BUFFER_STALLED_ERROR)return;const s=t.assetList[n]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${s?sb(s):s} ${e.error}`),!this.schedule)return;const a=(null==s?void 0:s.identifier)||"",o=this.getAssetPlayerQueueIndex(a),l=this.playerQueue[o]||null,u=this.schedule.items,c=zd({},e,{fatal:!1,errorAction:rp(!0),asset:s,assetListIndex:n,event:t,schedule:u,scheduleIndex:r,player:l});if(this.hls.trigger(Cd.INTERSTITIAL_ASSET_ERROR,c),!e.fatal)return;const d=this.playingAsset,h=this.bufferingAsset,f=new Error(i);if(s&&(this.clearAssetPlayer(a,null),s.error=f),t.assetList.some(e=>!e.error))for(let e=n;e<t.assetList.length;e++)this.resetAssetPlayer(t.assetList[e].identifier);else t.error=f;this.updateSchedule(!0),t.error?this.primaryFallback(t):d&&d.identifier===a?this.advanceAfterAssetEnded(t,r,n):h&&h.identifier===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,h)}primaryFallback(e){const t=e.timelineStart,r=this.effectivePlayingItem;let n=this.timelinePos;if(r){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${n} playing: ${lb(r)} error: ${e.error}`),-1===n&&(n=this.hls.startPosition);const i=this.updateItem(r,n);this.itemsMatch(r,i)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(-1===n)return void this.checkStart();if(!this.schedule)return;const i=this.schedule.findItemIndexAtTime(n);this.setSchedulePosition(i)}onAssetListLoaded(e,t){var r,n;const i=t.event,s=i.identifier,a=t.assetListResponse.ASSETS;if(null==(r=this.schedule)||!r.hasEvent(s))return;const o=i.timelineStart,l=i.duration;let u=0;a.forEach((e,t)=>{const r=parseFloat(e.DURATION);this.createAsset(i,t,u,o+u,r,e.URI),u+=r}),i.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${l}) ${i}`);const c=this.waitingItem,d=(null==c?void 0:c.event.identifier)===s;this.updateSchedule();const h=null==(n=this.bufferingItem)?void 0:n.event;if(d){var f;const e=this.schedule.findEventIndex(s),t=null==(f=this.schedule.items)?void 0:f[e];if(t){if(!this.playingItem&&this.timelinePos>t.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==e)return i.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${i}`),this.log(i.error.message),this.updateSchedule(!0),void this.primaryFallback(i)}this.setBufferingItem(t)}this.setSchedulePosition(e)}else if((null==h?void 0:h.identifier)===s){const e=i.assetList[0];if(e){const t=this.getAssetPlayer(e.identifier);if(h.appendInPlace){const e=this.primaryMedia;t&&e&&this.bufferAssetPlayer(t,e)}else t&&t.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case Id.ASSET_LIST_PARSING_ERROR:case Id.ASSET_LIST_LOAD_ERROR:case Id.ASSET_LIST_LOAD_TIMEOUT:{const e=t.interstitial;e&&(this.updateSchedule(!0),this.primaryFallback(e));break}case Id.BUFFER_STALLED_ERROR:{const e=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(e)&&e.event.appendInPlace)return void this.handleInPlaceStall(e.event);this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}});function mw(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(mw):Object.keys(e).reduce((t,r)=>(t[r]=mw(e[r]),t),{}):e}function vw(e,t){const r=e.loader;if(r!==cw&&r!==pw)t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1})()&&(e.loader=cw,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class yw extends Sp{constructor(e,t){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 e;null!=(e=this.media)&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var e;this.hls&&(this.ended=(null==(e=this.media)?void 0:e.currentTime)||1,this.hls.trigger(Cd.MEDIA_ENDED,{stalled:!1}))},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(Cd.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Cd.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Cd.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(Cd.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Cd.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Cd.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;const r=this.media=t.media;jg(r,"playing",this.onMediaPlaying),jg(r,"waiting",this.onMediaWaiting),jg(r,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:r}=this;r&&(Gg(r,"playing",this.onMediaPlaying),Gg(r,"waiting",this.onMediaWaiting),Gg(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(null==(e=this.media)||!e.readyState||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var r,n;const i=null==(r=this.hls)?void 0:r.config;if(!i)return;const s=this.media;if(!s)return;const{seeking:a}=s,o=this.seeking&&!a,l=!this.seeking&&a,u=s.paused&&!a||s.ended||0===s.playbackRate;if(this.seeking=a,e!==t)return t&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,i.nudgeOnVideoHole&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(l||o)return void(o&&this.stallResolved(e));if(u)return this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&s.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(Cd.MEDIA_ENDED,{stalled:!1})));if(!kp.getBuffered(s).length)return void(this.nudgeRetry=0);const c=kp.bufferInfo(s,e,0),d=c.nextStart||0,h=this.fragmentTracker;if(a&&h&&this.hls){const t=bw(this.hls.inFlightFragments,e),r=c.len>2,n=!d||t||d-e>2&&!h.getPartialFragment(e);if(r||n)return;this.moved=!1}const f=null==(n=this.hls)?void 0:n.latestLevelDetails;if(!this.moved&&null!==this.stalled&&h){if(!(c.len>0)&&!d)return;const t=Math.max(d,c.start||0)-e,r=!(null==f||!f.live)?2*f.targetduration:2,n=Ew(e,h);if(t>0&&(t<=r||n))return void(s.paused||this._trySkipBufferHole(n))}const p=i.detectStallWithCurrentTimeMs,g=self.performance.now(),m=this.waiting;let v=this.stalled;if(null===v){if(!(m>0&&g-m<p))return void(this.stalled=g);v=this.stalled=m}const y=g-v;if(!a&&(y>=p||m)&&this.hls){var b;if("ended"===(null==(b=this.mediaSource)?void 0:b.readyState)&&(null==f||!f.live)&&Math.abs(e-((null==f?void 0:f.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(Cd.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(c),!this.media||!this.hls)return}const w=kp.bufferInfo(s,e,i.maxBufferHole);this._tryFixBufferStall(w,y,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const r=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(r)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(Cd.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var r;const n=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(r=this.buffered.audio)&&r.length&&n&&n.length>1&&e>n.end(0)){const r=kp.bufferedInfo(kp.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const r=kp.timeRangesToArray(n),i=kp.bufferedInfo(r,t,0).bufferedIndex;if(i>-1&&i<r.length-1){const t=kp.bufferedInfo(r,e,0).bufferedIndex,n=r[i].end,s=r[i+1].start;if((-1===t||t>i)&&s-n<1&&e-n<2){const r=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${n} -> ${s} buffered index: ${t}`);this.warn(r.message),this.media.currentTime+=1e-6;let i=Ew(e,this.fragmentTracker);i&&"fragment"in i?i=i.fragment:i||(i=void 0);const a=kp.bufferInfo(this.media,e,0);this.hls.trigger(Cd.ERROR,{type:Ld.MEDIA_ERROR,details:Id.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:r,reason:r.message,frag:i,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(e,t,r){var n,i;const{fragmentTracker:s,media:a}=this,o=null==(n=this.hls)?void 0:n.config;if(!a||!s||!o)return;const l=null==(i=this.hls)?void 0:i.latestLevelDetails,u=Ew(r,s);if(u||null!=l&&l.live&&r<l.fragmentStart){if(this._trySkipBufferHole(u)||!this.media)return}const c=e.buffered,d=this.adjacentTraversal(e,r);(c&&c.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-r<o.maxBufferHole||d))&&(t>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const r=this.fragmentTracker,n=e.nextStart;if(r&&n){const e=r.getFragAtPos(t,Od),i=r.getFragAtPos(n,Od);if(e&&i)return i.sn-e.sn<2}return!1}_reportStall(e){const{hls:t,media:r,stallReported:n,stalled:i}=this;if(!n&&null!==i&&r&&t){this.stallReported=!0;const n=new Error(`Playback stalling at @${r.currentTime} due to low buffer (${Af(e)})`);this.warn(n.message),t.trigger(Cd.ERROR,{type:Ld.MEDIA_ERROR,details:Id.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len,bufferInfo:e,stalled:{start:i}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:r,media:n}=this,i=null==(t=this.hls)?void 0:t.config;if(!n||!r||!i)return 0;const s=n.currentTime,a=kp.bufferInfo(n,s,0),o=s<a.start?a.start:a.nextStart;if(o&&this.hls){const t=a.len<=i.maxBufferHole,u=a.len>0&&a.len<1&&n.readyState<3,c=o-s;if(c>0&&(t||u)){if(c>i.maxBufferHole){let t=!1;if(0===s){const e=r.getAppendedFrag(0,Od);e&&o<e.end&&(t=!0)}if(!t&&e){var l;if(null==(l=this.hls.loadLevelObj)||!l.details)return 0;if(bw(this.hls.inFlightFragments,o))return 0;let t=!1,n=e.end;for(;n<o;){const e=Ew(n,r);if(!e){t=!0;break}n+=e.duration}if(t)return 0}}const t=Math.max(o+.05,s+.1);if(this.warn(`skipping hole, adjusting currentTime from ${s} to ${t}`),this.moved=!0,n.currentTime=t,null==e||!e.gap){const r=new Error(`fragment loaded with buffer holes, seeking from ${s} to ${t}`),n={type:Ld.MEDIA_ERROR,details:Id.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:r,reason:r.message,buffer:a.len,bufferInfo:a};e&&("fragment"in e?n.part=e:n.frag=e),this.hls.trigger(Cd.ERROR,n)}return t}}return 0}_tryNudgeBuffer(e){const{hls:t,media:r,nudgeRetry:n}=this,i=null==t?void 0:t.config;if(!r||!i)return 0;const s=r.currentTime;if(this.nudgeRetry++,n<i.nudgeMaxRetry){const a=s+(n+1)*i.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${s} to ${a}`);this.warn(o.message),r.currentTime=a,t.trigger(Cd.ERROR,{type:Ld.MEDIA_ERROR,details:Id.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{const r=new Error(`Playhead still not moving while enough data buffered @${s} after ${i.nudgeMaxRetry} nudges`);this.error(r.message),t.trigger(Cd.ERROR,{type:Ld.MEDIA_ERROR,details:Id.BUFFER_STALLED_ERROR,error:r,fatal:!0,buffer:e.len,bufferInfo:e})}}}function bw(e,t){const r=ww(e.main);if(r&&r.start<=t)return r;const n=ww(e.audio);return n&&n.start<=t?n:null}function ww(e){if(!e)return null;switch(e.state){case Wg:case Vg:case Jg:case em:return null}return e.frag}function Ew(e,t){return t.getAppendedFrag(e,Od)||t.getPartialFragment(e)}function Sw(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Tw(e,t,r,n,i){let s=new e(t,r,"");try{s.value=n,i&&(s.type=i)}catch(a){s=new e(t,r,Af(i?Gd({type:i},n):n))}return s}const xw=(()=>{const e=Sw();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class kw{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(Cd.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(Cd.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Cd.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Cd.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Cd.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(Cd.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Cd.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Cd.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(Cd.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Cd.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Cd.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Cd.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(Cd.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Cd.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Cd.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var r;this.media=t.media,!1===(null==(r=t.overrides)?void 0:r.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){var e;const t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null;!!t.transferMedia||(this.id3Track&&(this.removeCues&&Yy(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const r=e[t];if("metadata"===r.kind&&"id3"===r.label)return Wy(r,this.media),r}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:r,enableID3MetadataCues:n}=this.hls.config;if(!r&&!n)return;const{samples:i}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const s=Sw();if(s)for(let e=0;e<i.length;e++){const t=i[e].type;if(t===_m.emsg&&!r||!n)continue;const a=Im(i[e].data),o=i[e].pts;let l=o+i[e].duration;l>xw&&(l=xw);l-o<=0&&(l=o+.25);for(let e=0;e<a.length;e++){const r=a[e];if(!Cm(r)){this.updateId3CueEnds(o,t);const e=Tw(s,o,l,r,t);e&&this.id3Track.addCue(e)}}}}updateId3CueEnds(e,t){var r;const n=null==(r=this.id3Track)?void 0:r.cues;if(n)for(let r=n.length;r--;){const i=n[r];i.type===t&&i.startTime<e&&i.endTime===xw&&(i.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:r,type:n}){const{id3Track:i,hls:s}=this;if(!s)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=s;if(i&&(a||o)){let e;e="audio"===n?e=>e.type===_m.audioId3&&o:"video"===n?e=>e.type===_m.emsg&&a:e=>e.type===_m.audioId3&&o||e.type===_m.emsg&&a,qy(i,t,r,e)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:r,timelineOffset:n,enableDateRangeMetadataCues:i,interstitialsController:s}=this.hls.config;if(!i)return;const a=Sw();if(r&&n&&!s){const{fragmentStart:t,fragmentEnd:n}=e;let i=this.assetCue;i?(i.startTime=t,i.endTime=n):a&&(i=this.assetCue=Tw(a,t,n,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),i&&(i.id=r,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(i),i.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=e,u=Object.keys(l);let c=this.dateRangeCuesAppended;var d;if(o&&t)if(null!=(d=o.cues)&&d.length){const e=Object.keys(c).filter(e=>!u.includes(e));for(let t=e.length;t--;){var h;const r=e[t],n=null==(h=c[r])?void 0:h.cues;delete c[r],n&&Object.keys(n).forEach(e=>{const t=n[e];if(t){t.removeEventListener("enter",this.onEventCueEnter);try{o.removeCue(t)}catch(e){}}})}}else c=this.dateRangeCuesAppended={};const f=e.fragments[e.fragments.length-1];if(0!==u.length&&kd(null==f?void 0:f.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let e=0;e<u.length;e++){const t=u[e],r=l[t],n=r.startTime,i=c[t],o=(null==i?void 0:i.cues)||{};let d=(null==i?void 0:i.durationKnown)||!1,h=xw;const{duration:f,endDate:p}=r;if(p&&null!==f)h=n+f,d=!0;else if(r.endOnNext&&!d){const e=u.reduce((e,t)=>{if(t!==r.id){const n=l[t];if(n.class===r.class&&n.startDate>r.startDate&&(!e||r.startDate<e.startDate))return n}return e},null);e&&(h=e.startTime,d=!0)}const g=Object.keys(r.attr);for(let e=0;e<g.length;e++){const l=g[e];if(!Mp(l))continue;const u=o[l];if(u)!d||null!=i&&i.durationKnown?Math.abs(u.startTime-n)>.01&&(u.startTime=n,u.endTime=h):u.endTime=h;else if(a){let e=r.attr[l];Op(l)&&(e=th(e));const i=Tw(a,n,h,{key:l,data:e},_m.dateRange);i&&(i.id=t,this.id3Track.addCue(i),o[l]=i,s&&("X-ASSET-LIST"!==l&&"X-ASSET-URL"!==l||i.addEventListener("enter",this.onEventCueEnter)))}}c[t]={cues:o,dateRange:r,durationKnown:d}}}}}class Aw{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:e}=this,t=this.levelDetails;if(!e||!t)return;this.currentTime=e.currentTime;const r=this.computeLatency();if(null===r)return;this._latency=r;const{lowLatencyMode:n,maxLiveSyncPlaybackRate:i}=this.config;if(!n||1===i||!t.live)return;const s=this.targetLatency;if(null===s)return;const a=r-s;if(a<Math.min(this.maxLatency,s+t.targetduration)&&a>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,i)),r=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,n=Math.min(t,Math.max(1,r));this.changeMediaPlaybackRate(e,n)}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(null===e||null===this.hls)return null;const{holdBack:t,partHoldBack:r,targetduration:n}=e,{liveSyncDuration:i,liveSyncDurationCount:s,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&r||t;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==i?i:s*n);const u=n;return l+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(),t=this.targetLatency;if(null===e||null===t)return null;const r=this.levelDetails;if(null===r)return null;const n=r.edge,i=e-t-this.edgeStalled,s=n-r.totalduration,a=n-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(s,i),a)}get drift(){const e=this.levelDetails;return null===e?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(Cd.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Cd.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Cd.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Cd.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(Cd.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Cd.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Cd.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Cd.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.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:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var r;t.details===Id.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(r=this.levelDetails)&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var r,n;e.playbackRate!==t&&(null==(r=this.hls)||r.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(n=this.targetLatency)?void 0:n.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}class Rw extends Ov{constructor(e,t){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=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Cd.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Cd.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Cd.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Cd.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Cd.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Cd.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Cd.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Cd.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Cd.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Cd.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.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,t){this.resetLevels()}onManifestLoaded(e,t){const r=this.hls.config.preferManagedMediaSource,n=[],i={},s={};let a=!1,o=!1,l=!1;t.levels.forEach(e=>{const t=e.attrs;let{audioCodec:u,videoCodec:c}=e;u&&(e.audioCodec=u=rf(u,r)||void 0),c&&(c=e.videoCodec=function(e){const t=e.split(",");for(let e=0;e<t.length;e++){const r=t[e].split(".");r.length>2&&"avc1"===r[0]&&(t[e]=`avc1.${parseInt(r[1]).toString(16)}${("000"+parseInt(r[2]).toString(16)).slice(-4)}`)}return t.join(",")}(c));const{width:d,height:h,unknownCodecs:f}=e,p=(null==f?void 0:f.length)||0;if(a||(a=!(!d||!h)),o||(o=!!c),l||(l=!!u),p||u&&!this.isAudioSupported(u)||c&&!this.isVideoSupported(c))return void this.log(`Some or all CODECS not supported "${t.CODECS}"`);const{CODECS:g,"FRAME-RATE":m,"HDCP-LEVEL":v,"PATHWAY-ID":y,RESOLUTION:b,"VIDEO-RANGE":w}=t,E=`${`${y||"."}-`}${e.bitrate}-${b}-${m}-${g}-${w}-${v}`;if(i[E])if(i[E].uri===e.url||e.attrs["PATHWAY-ID"])i[E].addGroupId("audio",t.AUDIO),i[E].addGroupId("text",t.SUBTITLES);else{const t=s[E]+=1;e.attrs["PATHWAY-ID"]=new Array(t+1).join(".");const r=this.createLevel(e);i[E]=r,n.push(r)}else{const t=this.createLevel(e);i[E]=t,s[E]=1,n.push(t)}}),this.filterAndSortMediaOptions(n,t,a,o,l)}createLevel(e){const t=new Tf(e),r=e.supplemental;if(null!=r&&r.videoCodec&&!this.isVideoSupported(r.videoCodec)){const e=new Error(`SUPPLEMENTAL-CODECS not supported "${r.videoCodec}"`);this.log(e.message),t.supportedResult=df(e,[])}return t}isAudioSupported(e){return qh(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return qh(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,r,n,i){var s;let a=[],o=[],l=e;const u=(null==(s=t.stats)?void 0:s.parsing)||{};if((r||n)&&i&&(l=l.filter(({videoCodec:e,videoRange:t,width:r,height:n})=>{return(!!e||!(!r||!n))&&(!!(i=t)&&vf.indexOf(i)>-1);var i})),0===l.length)return Promise.resolve().then(()=>{if(this.hls){let e="no level with compatible codecs found in manifest",r=e;t.levels.length&&(r=`one or more CODECS in variant not supported: ${Af(t.levels.map(e=>e.attrs.CODECS).filter((e,t,r)=>r.indexOf(e)===t))}`,this.warn(r),e+=` (${r})`);const n=new Error(e);this.hls.trigger(Cd.ERROR,{type:Ld.MEDIA_ERROR,details:Id.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:n,reason:r})}}),void(u.end=performance.now());t.audioTracks&&(a=t.audioTracks.filter(e=>!e.audioCodec||this.isAudioSupported(e.audioCodec)),Lw(a)),t.subtitles&&(o=t.subtitles,Lw(o));const c=l.slice(0);l.sort((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return vf.indexOf(e.videoRange)-vf.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){const r=Zh(e.videoCodec),n=Zh(t.videoCodec);if(r!==n)return n-r}if(e.uri===t.uri&&e.codecSet!==t.codecSet){const r=Jh(e.codecSet),n=Jh(t.codecSet);if(r!==n)return n-r}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0});let d=c[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==c.length))for(let e=0;e<c.length;e++)if(c[e].pathwayId===l[0].pathwayId){d=c[e];break}this._levels=l;for(let e=0;e<l.length;e++)if(l[e]===d){var h;this._firstLevel=e;const t=d.bitrate,r=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${t}`),void 0===(null==(h=this.hls.userConfig)?void 0:h.abrEwmaDefaultEstimate)){const e=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);e>r&&r===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}const f=i&&!n,p=this.hls.config,g=!(!p.audioStreamController||!p.audioTrackController),m={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:i,video:n,altAudio:g&&!f&&a.some(e=>!!e.url)};u.end=performance.now(),this.hls.trigger(Cd.MANIFEST_PARSED,m)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const r=new Error("invalid level idx"),n=e<0;if(this.hls.trigger(Cd.ERROR,{type:Ld.OTHER_ERROR,details:Id.LEVEL_SWITCH_ERROR,level:e,fatal:n,error:r,reason:r.message}),n)return;e=Math.min(e,t.length-1)}const r=this.currentLevelIndex,n=this.currentLevel,i=n?n.attrs["PATHWAY-ID"]:void 0,s=t[e],a=s.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=s,r===e&&n&&i===a)return;this.log(`Switching to level ${e} (${s.height?s.height+"p ":""}${s.videoRange?s.videoRange+" ":""}${s.codecSet?s.codecSet+" ":""}@${s.bitrate})${a?" with Pathway "+a:""} from level ${r}${i?" with Pathway "+i:""}`);const o={level:e,attrs:s.attrs,details:s.details,bitrate:s.bitrate,averageBitrate:s.averageBitrate,maxBitrate:s.maxBitrate,realBitrate:s.realBitrate,width:s.width,height:s.height,codecSet:s.codecSet,audioCodec:s.audioCodec,videoCodec:s.videoCodec,audioGroups:s.audioGroups,subtitleGroups:s.subtitleGroups,loaded:s.loaded,loadError:s.loadError,fragmentError:s.fragmentError,name:s.name,id:s.id,uri:s.uri,url:s.url,urlId:0,audioGroupIds:s.audioGroupIds,textGroupIds:s.textGroupIds};this.hls.trigger(Cd.LEVEL_SWITCHING,o);const l=s.details;if(!l||l.live){const e=this.switchParams(s.uri,null==n?void 0:n.details,l);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?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 t=this.steering.pathways(),r=e.filter(e=>-1!==t.indexOf(e));if(e.length<1)return void this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);this.steering.pathwayPriority=r}}onError(e,t){!t.fatal&&t.context&&t.context.type===Dd&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&t.type===Od){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return;const r=this._levels[t.level];null!=r&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0)}}onLevelLoaded(e,t){var r;const{level:n,details:i}=t,s=t.levelInfo;var a;if(!s)return this.warn(`Invalid level index ${n}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(i.deltaUpdateFailed=!0));if(s===this.currentLevel||t.withoutMultiVariant){0===s.fragmentError&&(s.loadError=0);let e=s.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(n,t,e)}else null!=(r=t.deliveryDirectives)&&r.skip&&(i.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const r=this.getUrlWithDirectives(e.uri,t),n=this.currentLevelIndex,i=e.attrs["PATHWAY-ID"],s=e.details,a=null==s?void 0:s.age;this.log(`Loading level index ${n}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${i?" Pathway "+i:""}${a&&s.live?" age "+a.toFixed(1)+(s.type&&" "+s.type||""):""} ${r}`),this.hls.trigger(Cd.LEVEL_LOADING,{url:r,level:n,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(1===this._levels.length)return;const r=this._levels.filter((t,r)=>r!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(e=>e.level=-1)),!1));Mg(r),this._levels=r,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const n=r.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(Cd.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:r}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(Cd.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}function Lw(e){const t={};e.forEach(e=>{const r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++})}function Iw(){return self.SourceBuffer||self.WebKitSourceBuffer}function Cw(){if(!Qd())return!1;const e=Iw();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}class Pw extends nm{constructor(e,t,r){super(e,t,r,"stream-controller",Od),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 e=this.media,t=e?e.currentTime:null;if(null===t||!kd(t))return;if(this.log(`Media seeked to ${t.toFixed(3)}`),!this.getBufferedFrag(t))return;const r=this.getFwdBufferInfoAtPos(e,t,Od,0);null!==r&&0!==r.len?this.tick():this.warn(`Main forward buffer length at ${t} on "seeked" event ${r?r.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(Cd.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Cd.LEVEL_LOADING,this.onLevelLoading,this),e.on(Cd.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Cd.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(Cd.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Cd.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(Cd.BUFFER_CREATED,this.onBufferCreated,this),e.on(Cd.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Cd.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Cd.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(Cd.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Cd.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Cd.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(Cd.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Cd.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(Cd.BUFFER_CREATED,this.onBufferCreated,this),e.off(Cd.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Cd.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Cd.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:r,hls:n}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=n.startLevel;-1===e&&(n.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=n.firstAutoLevel),n.nextLoadLevel=e,this.level=n.loadLevel,this._hasEnoughToStart=!!t}r>0&&-1===e&&!t&&(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r),this.state=Wg,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=Vg}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case rm:{const{levels:e,level:t}=this,r=null==e?void 0:e[t],n=null==r?void 0:r.details;if(n&&(!n.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(n))break;this.state=Wg;break}if(this.hls.nextLoadLevel!==this.level){this.state=Wg;break}break}case qg:this.checkRetryDate()}this.state===Wg&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:r,media:n}=this;if(null===t||!n&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const i=this.buffering?e.nextLoadLevel:e.loadLevel;if(null==r||!r[i])return;const s=r[i],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const e={};return 2===this.altAudio&&(e.type="video"),this.hls.trigger(Cd.BUFFER_EOS,e),void(this.state=Jg)}if(!this.buffering)return;e.loadLevel!==i&&-1===e.manualLevel&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=e.nextLoadLevel=i;const l=s.details;if(!l||this.state===rm||this.waitForLive(s))return this.level=i,this.state=rm,void(this.startFragRequested=!1);const u=a.len,c=this.getMaxBufferLength(s.maxBitrate);if(u>=c)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const d=this.backtrackFragment?this.backtrackFragment.start:a.end;let h=this.getNextFragment(d,l);if(this.couldBacktrack&&!this.fragPrevious&&h&&mh(h)&&this.fragmentTracker.getState(h)!==ap){var f;const e=(null!=(f=this.backtrackFragment)?f:h).sn-l.startSN,t=l.fragments[e-1];t&&h.cc===t.cc&&(h=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(h&&this.isLoopLoading(h,d)){if(!h.gap){const e=this.audioOnly&&!this.altAudio?hh:fh,t=(e===fh?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,Od)}h=this.getNextFragmentLoopLoading(h,l,a,Od,c)}h&&(!h.initSegment||h.initSegment.data||this.bitrateTest||(h=h.initSegment),this.loadFragment(h,s,d))}loadFragment(e,t,r){const n=this.fragmentTracker.getState(e);n===np||n===sp?mh(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,t)):super.loadFragment(e,t,r):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,Od)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(null!=t&&t.readyState){let r;const n=this.getAppendedFrag(t.currentTime);n&&n.start>1&&this.flushMainBuffer(0,n.start-1);const i=this.getLevelDetails();if(null!=i&&i.live){const e=this.getMainFwdBufferInfo();if(!e||e.len<2*i.targetduration)return}if(!t.paused&&e){const t=e[this.hls.nextLoadLevel],n=this.fragLastKbps;r=n&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*n)+1:0}else r=0;const s=this.getBufferedFrag(t.currentTime+r);if(s){const e=this.followingBufferedFrag(s);if(e){this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,r=e.duration,n=Math.max(s.end,t+Math.min(Math.max(r-this.config.maxFragLookUpTolerance,r*(this.couldBacktrack?.5:.125)),r*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(n,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 Kg:case Yg:case qg:case Qg:case Zg:this.state=Wg}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,2===this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const r=t.media;jg(r,"playing",this.onMediaPlaying),jg(r,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:r}=this;r&&(Gg(r,"playing",this.onMediaPlaying),Gg(r,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t);!!t.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(Cd.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let r=!1,n=!1;for(let e=0;e<t.levels.length;e++){const i=t.levels[e].audioCodec;i&&(r=r||-1!==i.indexOf("mp4a.40.2"),n=n||-1!==i.indexOf("mp4a.40.5"))}this.audioCodecSwitch=r&&n&&!function(){var e;const t=Iw();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:r}=this;if(!r||this.state!==Wg)return;const n=t.levelInfo;(!n.details||n.details.live&&(this.levelLastLoaded!==n||n.details.expired)||this.waitForCdnTuneIn(n.details))&&(this.state=rm)}onLevelLoaded(e,t){var r;const{levels:n,startFragRequested:i}=this,s=t.level,a=t.details,o=a.totalduration;if(!n)return void this.warn(`Levels were reset while loading level ${s}`);this.log(`Level ${s} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=t.levelInfo,u=this.fragCurrent;!u||this.state!==Yg&&this.state!==qg||u.level!==t.level&&u.loader&&this.abortCurrentFrag();let c=0;if(a.live||null!=(r=l.details)&&r.live){var d;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;c=this.alignPlaylists(a,l.details,null==(d=this.levelLastLoaded)?void 0:d.details)}if(l.details=a,this.levelLastLoaded=l,i||this.setStartPosition(a,c),this.hls.trigger(Cd.LEVEL_UPDATED,{details:a,level:s}),this.state===rm){if(this.waitForCdnTuneIn(a))return;this.state=Wg}i&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:r}=this;if(!r)return;const n=this.hls.liveSyncPosition,i=this.getLoadPosition(),s=e.fragmentStart,a=e.edge,o=i>=s-t.maxFragLookUpTolerance&&i<=a;if(null!==n&&r.duration>n&&(i<n||!o)){const s=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&r.readyState<4||i<a-s)&&(this._hasEnoughToStart||(this.nextLoadPosition=n),r.readyState))if(this.warn(`Playback: ${i.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${n.toFixed(3)}`),"buffered"===this.config.liveSyncMode){var l;const e=kp.bufferInfo(r,n,0);if(null==(l=e.buffered)||!l.length)return void(r.currentTime=n);if(e.start<=i)return void(r.currentTime=n);const{nextStart:t}=kp.bufferedInfo(e.buffered,i,0);t&&(r.currentTime=t)}else r.currentTime=n}}_handleFragmentLoadProgress(e){var t;const r=e.frag,{part:n,payload:i}=e,{levels:s}=this;if(!s)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);const a=s[r.level];if(!a)return void this.warn(`Level ${r.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${r.sn} of level ${r.level} after level details were reset`),void this.fragmentTracker.removeFragment(r);const l=a.videoCodec,u=o.PTSKnown||!o.live,c=null==(t=r.initSegment)?void 0:t.data,d=this._getAudioCodec(a),h=this.transmuxer=this.transmuxer||new Mv(this.hls,Od,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=n?n.index:-1,p=-1!==f,g=new Tp(r.level,r.sn,r.stats.chunkCount,i.byteLength,f,p),m=this.initPTS[r.cc];h.push(i,c,d,l,r,n,o.totalduration,u,g,m)}onAudioTrackSwitching(e,t){const r=this.hls,n=0!==this.altAudio;if(Mf(t.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 e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(n)return this.altAudio=0,this.fragmentTracker.removeAllFragments(),r.once(Cd.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(Cd.AUDIO_TRACK_SWITCHED,t)}),void r.trigger(Cd.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});r.trigger(Cd.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const r=Mf(t.url,this.hls);if(r){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=r?2:0,this.tick()}onBufferCreated(e,t){const r=t.tracks;let n,i,s=!1;for(const e in r){const t=r[e];if("main"===t.id){if(i=e,n=t,"video"===e){const t=r[e];t&&(this.videoBuffer=t.buffer)}}else s=!0}s&&n?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=n.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:r,part:n}=t,i=r.type===Od;if(i){if(this.fragContextChanged(r))return this.warn(`Fragment ${r.sn}${n?" p: "+n.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Zg&&(this.state=Wg));const e=n?n.stats:r.stats;this.fragLastKbps=Math.round(8*e.total/(e.buffering.end-e.loading.first)),mh(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,n)}const s=this.media;s&&(!this._hasEnoughToStart&&kp.getBuffered(s).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),i&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var r;if(t.fatal)this.state=em;else switch(t.details){case Id.FRAG_GAP:case Id.FRAG_PARSING_ERROR:case Id.FRAG_DECRYPT_ERROR:case Id.FRAG_LOAD_ERROR:case Id.FRAG_LOAD_TIMEOUT:case Id.KEY_LOAD_ERROR:case Id.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Od,t);break;case Id.LEVEL_LOAD_ERROR:case Id.LEVEL_LOAD_TIMEOUT:case Id.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==rm||(null==(r=t.context)?void 0:r.type)!==Dd||(this.state=Wg);break;case Id.BUFFER_ADD_CODEC_ERROR:case Id.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case Id.BUFFER_FULL_ERROR:if("main"!==t.parent)return;if(this.reduceLengthAndFlushBuffer(t)){!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}break;case Id.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=Wg,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==hh||!this.altAudio){const e=(t===fh?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t,Od),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let r=this.startPosition;if(r>=0&&t<r){if(e.seeking)return void this.log(`could not seek to ${r}, already seeking at ${t}`);const n=this.timelineOffset;n&&r&&(r+=n);const i=this.getLevelDetails(),s=kp.getBuffered(e),a=s.length?s.start(0):0,o=a-r,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==i?void 0:i.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),r+=o,this.startPosition=r),t<r&&(this.log(`seek to target start position ${r} from current time ${t} buffer start ${a}`),e.currentTime=r)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(e=>{const{hls:r}=this,n=null==e?void 0:e.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=Wg,this.startFragRequested=!1,this.bitrateTest=!1;const i=n.stats;i.parsing.start=i.parsing.end=i.buffering.start=i.buffering.end=self.performance.now(),r.trigger(Cd.FRAG_LOADED,e),n.bitrateTest=!1}).catch(t=>{this.state!==Vg&&this.state!==em&&(this.warn(t),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:r}=this,{remuxResult:n,chunkMeta:i}=e,s=this.getCurrentContext(i);if(!s)return void this.resetWhenMissingContext(i);const{frag:a,part:o,level:l}=s,{video:u,text:c,id3:d,initSegment:h}=n,{details:f}=l,p=this.altAudio?void 0:n.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=Qg,h){const e=h.tracks;if(e){const n=a.initSegment||a;if(this.unhandledEncryptionError(h,a))return;this._bufferInitSegment(l,e,n,i),r.trigger(Cd.FRAG_PARSING_INIT_SEGMENT,{frag:n,id:t,tracks:e})}const n=h.initPTS,s=h.timescale,o=this.initPTS[a.cc];if(kd(n)&&(!o||o.baseTime!==n||o.timescale!==s)){const e=h.trackId;this.initPTS[a.cc]={baseTime:n,timescale:s,trackId:e},r.trigger(Cd.INIT_PTS_FOUND,{frag:a,id:t,initPTS:n,timescale:s,trackId:e})}}if(u&&f){p&&"audiovideo"===u.type&&this.logMuxedErr(a);const e=f.fragments[a.sn-1-f.startSN],t=a.sn===f.startSN,r=!e||a.cc>e.cc;if(!1!==n.independent){const{startPTS:e,endPTS:n,startDTS:s,endDTS:l}=u;if(o)o.elementaryStreams[u.type]={startPTS:e,endPTS:n,startDTS:s,endDTS:l};else if(u.firstKeyFrame&&u.independent&&1===i.id&&!r&&(this.couldBacktrack=!0),u.dropped&&u.independent){const i=this.getMainFwdBufferInfo(),s=(i?i.end:this.getLoadPosition())+this.config.maxBufferHole,o=u.firstKeyFramePTS?u.firstKeyFramePTS:e;if(!t&&s<o-this.config.maxBufferHole&&!r)return void this.backtrack(a);r&&(a.gap=!0),a.setElementaryStreamInfo(u.type,a.start,n,a.start,l,!0)}else t&&e-(f.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(u.type,e,n,s,l),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(u,a,o,i,t||r)}else{if(!t&&!r)return void this.backtrack(a);a.gap=!0}}if(p){const{startPTS:e,endPTS:t,startDTS:r,endDTS:n}=p;o&&(o.elementaryStreams[hh]={startPTS:e,endPTS:t,startDTS:r,endDTS:n}),a.setElementaryStreamInfo(hh,e,t,r,n),this.bufferFragmentData(p,a,o,i)}if(f&&null!=d&&d.samples.length){const e={id:t,frag:a,details:f,samples:d.samples};r.trigger(Cd.FRAG_PARSING_METADATA,e)}if(f&&c){const e={id:t,frag:a,details:f,samples:c.samples};r.trigger(Cd.FRAG_PARSING_USERDATA,e)}}}logMuxedErr(e){this.warn(`${mh(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,r,n){if(this.state!==Qg)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(r));const{audio:i,video:s,audiovideo:a}=t;if(i){const r=e.audioCodec;let n=nf(i.codec,r);"mp4a"===n&&(n="mp4a.40.5");const s=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){n&&(n=-1!==n.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const e=i.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&-1===s.indexOf("firefox")&&(n="mp4a.40.5")}n&&-1!==n.indexOf("mp4a.40.5")&&-1!==s.indexOf("android")&&"audio/mpeg"!==i.container&&(n="mp4a.40.2",this.log(`Android: force audio codec to ${n}`)),r&&r!==n&&this.log(`Swapping manifest audio codec "${r}" for "${n}"`),i.levelCodec=n,i.id=Od,this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${n||""}/${r||""}/${i.codec}]`),delete t.audiovideo}if(s){s.levelCodec=e.videoCodec,s.id=Od;const r=s.codec;if(4===(null==r?void 0:r.length))switch(r){case"hvc1":case"hev1":s.codec="hvc1.1.6.L120.90";break;case"av01":s.codec="av01.0.04M.08";break;case"avc1":s.codec="avc1.42e01e"}this.log(`Init video buffer, container:${s.container}, codecs[level/parsed]=[${e.videoCodec||""}/${r}]${s.codec!==r?" parsed-corrected="+s.codec:""}${s.supplemental?" supplemental="+s.supplemental:""}`),delete t.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio);const o=Object.keys(t);if(o.length){if(this.hls.trigger(Cd.BUFFER_CODECS,t),!this.hls)return;o.forEach(e=>{const i=t[e].initSegment;null!=i&&i.byteLength&&this.hls.trigger(Cd.BUFFER_APPENDING,{type:e,data:i,frag:r,part:null,chunkMeta:n,parent:r.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,Od)}get maxBufferLength(){const{levels:e,level:t}=this,r=null==e?void 0:e[t];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=Wg}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const r=e.currentTime;if(kp.isBuffered(e,r)?t=this.getAppendedFrag(r):kp.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t){this.backtrackFragment=null;const e=this.fragPlaying,r=t.level;e&&t.sn===e.sn&&e.level===r||(this.fragPlaying=t,this.hls.trigger(Cd.FRAG_CHANGED,{frag:t}),e&&e.level===r||this.hls.trigger(Cd.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return kd(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(kd(t)){const e=this.getLevelDetails(),r=this.currentFrag||(e?Nf(null,e.fragments,t):null);if(r){const e=r.programDateTime;if(null!==e){const n=e+1e3*(t-r.start);return new Date(n)}}}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 Dw extends Hd{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const r in this.keyIdToKeyInfo){const n=this.keyIdToKeyInfo[r].loader;if(n){var t;if(e&&e!==(null==(t=n.context)?void 0:t.frag.type))return;n.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=Id.KEY_LOAD_ERROR,r,n,i){return new Ep({type:Ld.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:i,error:r,networkDetails:n})}loadClear(e,t,r){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let n=0,i=t.length;n<i;n++){const s=t[n];if(e.cc<=s.cc&&(!mh(e)||!mh(s)||e.sn<s.sn)||!r&&n==i-1)return this.emeController.selectKeySystemFormat(s).then(e=>{if(!this.emeController)return;s.setKeyFormat(e);const t=Zp(e);return t?this.emeController.getKeySystemAccess([t]):void 0})}if(this.config.requireKeySystemAccessOnStart){const e=eg(this.config);if(e.length)return this.emeController.getKeySystemAccess(e)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var r,n;t&&e.setKeyFormat(t);const i=e.decryptdata;if(!i){const r=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,Id.KEY_LOAD_ERROR,r))}const s=i.uri;if(!s)return Promise.reject(this.createKeyLoadError(e,Id.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${s}"`)));const a=_w(i);let o=this.keyIdToKeyInfo[a];if(null!=(r=o)&&r.decryptdata.key)return i.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if(this.emeController&&null!=(n=o)&&n.keyLoadPromise){switch(this.emeController.getKeyStatus(o.decryptdata)){case"usable":case"usable-in-future":return o.keyLoadPromise.then(t=>{const{keyInfo:r}=t;return i.key=r.decryptdata.key,{frag:e,keyInfo:r}})}}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${i.keyId?" keyId: "+eh(i.keyId):""} URI: ${i.uri} from ${e.type} ${e.level}`),o=this.keyIdToKeyInfo[a]={decryptdata:i,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},i.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===i.keyFormat?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,Id.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(e,t){const r={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var n;if(!e.decryptdata.keyId&&null!=(n=t.initSegment)&&n.data){const r=function(e){const t=[];return Nh(e,e=>t.push(e.subarray(8,24))),t}(t.initSegment.data);if(r.length){let t=r[0];t.some(e=>0!==e)?(this.log(`Using keyId found in init segment ${eh(t)}`),sg.setKeyIdForUri(e.decryptdata.uri,t)):(t=sg.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${eh(t)}`)),e.decryptdata.keyId=t}}if(!e.decryptdata.keyId&&!mh(t))return Promise.resolve(r);const i=this.emeController.loadKey(r);return(e.keyLoadPromise=i.then(t=>(e.mediaKeySessionContext=t,r))).catch(r=>{throw e.keyLoadPromise=null,"data"in r&&(r.data.frag=t),r})}return Promise.resolve(r)}loadKeyHTTP(e,t){const r=this.config,n=new(0,r.loader)(r);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((i,s)=>{const a={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=r.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(e,t,r,n)=>{const{frag:a,keyInfo:o}=r,l=_w(o.decryptdata);if(!a.decryptdata||o!==this.keyIdToKeyInfo[l])return s(this.createKeyLoadError(a,Id.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),n));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,o.loader=null,i({frag:a,keyInfo:o})},onError:(e,r,n,i)=>{this.resetLoader(r),s(this.createKeyLoadError(t,Id.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),n,Gd({url:a.url,data:void 0},e)))},onTimeout:(e,r,n)=>{this.resetLoader(r),s(this.createKeyLoadError(t,Id.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),n))},onAbort:(e,r,n)=>{this.resetLoader(r),s(this.createKeyLoadError(t,Id.INTERNAL_ABORTED,new Error("key loading aborted"),n))}};n.load(a,l,u)})}resetLoader(e){const{frag:t,keyInfo:r,url:n}=e,i=r.loader;t.keyLoader===i&&(t.keyLoader=null,r.loader=null);const s=_w(r.decryptdata)||n;delete this.keyIdToKeyInfo[s],i&&i.destroy()}}function _w(e){if(e.keyFormat!==qp){const t=e.keyId;if(t)return eh(t)}return e.uri}function Mw(e){const{type:t}=e;switch(t){case _d:return Nd;case Md:return Fd;default:return Od}}function Ow(e,t){let r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}class Nw{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(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Cd.LEVEL_LOADING,this.onLevelLoading,this),e.on(Cd.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(Cd.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(Cd.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(Cd.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Cd.LEVEL_LOADING,this.onLevelLoading,this),e.off(Cd.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(Cd.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(Cd.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,r=t.pLoader,n=t.loader,i=new(r||n)(t);return this.loaders[e.type]=i,i}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:r}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Pd,url:r,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:r,level:n,pathwayId:i,url:s,deliveryDirectives:a,levelInfo:o}=t;this.load({id:r,level:n,pathwayId:i,responseType:"text",type:Dd,url:s,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(e,t){const{id:r,groupId:n,url:i,deliveryDirectives:s,track:a}=t;this.load({id:r,groupId:n,level:null,responseType:"text",type:_d,url:i,deliveryDirectives:s,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:r,groupId:n,url:i,deliveryDirectives:s,track:a}=t;this.load({id:r,groupId:n,level:null,responseType:"text",type:Md,url:i,deliveryDirectives:s,levelOrTrack:a})}onLevelsUpdated(e,t){const r=this.loaders[Dd];if(r){const e=r.context;e&&!t.levels.some(t=>t===e.levelOrTrack)&&(r.abort(),delete this.loaders[Dd])}}load(e){var t;const r=this.hls.config;let n,i=this.getInternalLoader(e);if(i){const t=this.hls.logger,r=i.context;if(r&&r.levelOrTrack===e.levelOrTrack&&(r.url===e.url||r.deliveryDirectives&&!e.deliveryDirectives))return void(r.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${r.url}`));t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}if(n=e.type===Pd?r.manifestLoadPolicy.default:zd({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),kd(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===Dd&&null!==e.level?t=this.hls.levels[e.level].details:e.type===_d&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===Md&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,r=t.targetduration;if(e&&r){const t=1e3*Math.max(3*e,.8*r);n=zd({},n,{maxTimeToFirstByteMs:Math.min(t,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,n.maxTimeToFirstByteMs)})}}}const s=n.errorRetry||n.timeoutRetry||{},a={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:s.maxNumRetry||0,retryDelay:s.retryDelayMs||0,maxRetryDelay:s.maxRetryDelayMs||0},o={onSuccess:(e,t,r,n)=>{const i=this.getInternalLoader(r);this.resetInternalLoader(r.type);const s=e.data;t.parsing.start=performance.now(),hg.isMediaPlaylist(s)||r.type!==Pd?this.handleTrackOrLevelPlaylist(e,t,r,n||null,i):this.handleMasterPlaylist(e,t,r,n)},onError:(e,t,r,n)=>{this.handleNetworkError(t,r,!1,e,n)},onTimeout:(e,t,r)=>{this.handleNetworkError(t,r,!0,void 0,e)}};i.load(e,a,o)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:r}=this.hls;(e||r)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,r,n){const i=this.hls,s=e.data,a=Ow(e,r),o=hg.parseMasterPlaylist(s,a);if(o.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,r,o.playlistParsingError,n,t);const{contentSteering:l,levels:u,sessionData:c,sessionKeys:d,startTimeOffset:h,variableList:f}=o;this.variableList=f,u.forEach(e=>{const{unknownCodecs:t}=e;if(t){const{preferManagedMediaSource:r}=this.hls.config;let{audioCodec:n,videoCodec:i}=e;for(let s=t.length;s--;){const a=t[s];qh(a,"audio",r)?(e.audioCodec=n=n?`${n},${a}`:a,Kh.audio[n.substring(0,4)]=2,t.splice(s,1)):qh(a,"video",r)&&(e.videoCodec=i=i?`${i},${a}`:a,Kh.video[i.substring(0,4)]=2,t.splice(s,1))}}});const{AUDIO:p=[],SUBTITLES:g,"CLOSED-CAPTIONS":m}=hg.parseMasterPlaylistMedia(s,a,o);if(p.length){p.some(e=>!e.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"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new _p({}),bitrate:0,url:""}))}i.trigger(Cd.MANIFEST_LOADED,{levels:u,audioTracks:p,subtitles:g,captions:m,contentSteering:l,url:a,stats:t,networkDetails:n,sessionData:c,sessionKeys:d,startTimeOffset:h,variableList:f})}handleTrackOrLevelPlaylist(e,t,r,n,i){const s=this.hls,{id:a,level:o,type:l}=r,u=Ow(e,r),c=kd(o)?o:kd(a)?a:0,d=Mw(r),h=hg.parseLevelPlaylist(e.data,u,c,d,0,this.variableList);if(l===Pd){const e={attrs:new _p({}),bitrate:0,details:h,name:"",url:u};h.requestScheduled=t.loading.start+Cg(h,0),s.trigger(Cd.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:u,stats:t,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=h,this.handlePlaylistLoaded(h,e,t,r,n,i)}handleManifestParsingError(e,t,r,n,i){this.hls.trigger(Cd.ERROR,{type:Ld.NETWORK_ERROR,details:Id.MANIFEST_PARSING_ERROR,fatal:t.type===Pd,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:n,stats:i})}handleNetworkError(e,t,r=!1,n,i){let s=`A network ${r?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${e.type}`;e.type===Dd?s+=`: ${e.level} id: ${e.id}`:e.type!==_d&&e.type!==Md||(s+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(s);this.hls.logger.warn(`[playlist-loader]: ${s}`);let o=Id.UNKNOWN,l=!1;const u=this.getInternalLoader(e);switch(e.type){case Pd:o=r?Id.MANIFEST_LOAD_TIMEOUT:Id.MANIFEST_LOAD_ERROR,l=!0;break;case Dd:o=r?Id.LEVEL_LOAD_TIMEOUT:Id.LEVEL_LOAD_ERROR,l=!1;break;case _d:o=r?Id.AUDIO_TRACK_LOAD_TIMEOUT:Id.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case Md:o=r?Id.SUBTITLE_TRACK_LOAD_TIMEOUT:Id.SUBTITLE_LOAD_ERROR,l=!1}u&&this.resetInternalLoader(e.type);const c={type:Ld.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:u,context:e,error:a,networkDetails:t,stats:i};if(n){const r=(null==t?void 0:t.url)||e.url;c.response=Gd({url:r,data:void 0},n)}this.hls.trigger(Cd.ERROR,c)}handlePlaylistLoaded(e,t,r,n,i,s){const a=this.hls,{type:o,level:l,levelOrTrack:u,id:c,groupId:d,deliveryDirectives:h}=n,f=Ow(t,n),p=Mw(n);let g="number"==typeof n.level&&p===Od?l:void 0;const m=e.playlistParsingError;if(m){if(this.hls.logger.warn(`${m} ${e.url}`),!a.config.ignorePlaylistParsingErrors)return void a.trigger(Cd.ERROR,{type:Ld.NETWORK_ERROR,details:Id.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:m,reason:m.message,response:t,context:n,level:g,parent:p,networkDetails:i,stats:r});e.playlistParsingError=null}if(!e.fragments.length){const s=e.playlistParsingError=new Error("No Segments found in Playlist");return void a.trigger(Cd.ERROR,{type:Ld.NETWORK_ERROR,details:Id.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:s,reason:s.message,response:t,context:n,level:g,parent:p,networkDetails:i,stats:r})}switch(e.live&&s&&(s.getCacheAge&&(e.ageHeader=s.getCacheAge()||0),s.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case Pd:case Dd:if(g)if(u){if(u!==a.levels[g]){const e=a.levels.indexOf(u);e>-1&&(g=e)}}else g=0;a.trigger(Cd.LEVEL_LOADED,{details:e,levelInfo:u||a.levels[0],level:g||0,id:c||0,stats:r,networkDetails:i,deliveryDirectives:h,withoutMultiVariant:o===Pd});break;case _d:a.trigger(Cd.AUDIO_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:d||"",stats:r,networkDetails:i,deliveryDirectives:h});break;case Md:a.trigger(Cd.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:d||"",stats:r,networkDetails:i,deliveryDirectives:h})}}}class Fw{static get version(){return cm}static isMSESupported(){return Cw()}static isSupported(){return function(){if(!Cw())return!1;const e=Qd();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>e.isTypeSupported(Qh(t,"video")))||["mp4a.40.2","fLaC"].some(t=>e.isTypeSupported(Qh(t,"audio"))))}()}static getMediaSource(){return Qd()}static get Events(){return Cd}static get MetadataSchema(){return _m}static get ErrorTypes(){return Ld}static get ErrorDetails(){return Id}static get DefaultConfig(){return Fw.defaultConfig?Fw.defaultConfig:gw}static set DefaultConfig(e){Fw.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 um,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 t=this.logger=function(e,t,r){const n=Kd();if("object"==typeof console&&!0===e||"object"==typeof e){const i=["debug","log","info","warn","error"];i.forEach(t=>{n[t]=Yd(t,e,r)});try{n.log(`Debug logs enabled for "${t}" in hls.js version 1.6.15`)}catch(e){return Kd()}i.forEach(t=>{qd[t]=Yd(t,e)})}else zd(qd,n);return n}(e.debug||!1,"Hls instance",e.assetPlayerId),r=this.config=function(e,t,r){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const n=mw(e),i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(e=>{const s=`${"level"===e?"playlist":e}LoadPolicy`,a=void 0===t[s],o=[];i.forEach(r=>{const i=`${e}Loading${r}`,l=t[i];if(void 0!==l&&a){o.push(i);const e=n[s].default;switch(t[s]={default:e},r){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}}),o.length&&r.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${s}": ${Af(t[s])}`)}),Gd(Gd({},n),t)}(Fw.DefaultConfig,e,t);this.userConfig=e,r.progressive&&vw(r,t);const{abrController:n,bufferController:i,capLevelController:s,errorController:a,fpsController:o}=r,l=new a(this),u=this.abrController=new n(this),c=new op(this),d=r.interstitialsController,h=d?this.interstitialsController=new d(this,Fw):null,f=this.bufferController=new i(this,c),p=this.capLevelController=new s(this),g=new o(this),m=new Nw(this),v=r.contentSteeringController,y=v?new v(this):null,b=this.levelController=new Rw(this,y),w=new kw(this),E=new Dw(this.config,this.logger),S=this.streamController=new Pw(this,c,E),T=this.gapController=new yw(this,c);p.setStreamController(S),g.setStreamController(S);const x=[m,b,S];h&&x.splice(1,0,h),y&&x.splice(1,0,y),this.networkControllers=x;const k=[u,f,T,p,g,w,c];this.audioTrackController=this.createController(r.audioTrackController,x);const A=r.audioStreamController;A&&x.push(this.audioStreamController=new A(this,c,E)),this.subtitleTrackController=this.createController(r.subtitleTrackController,x);const R=r.subtitleStreamController;R&&x.push(this.subtititleStreamController=new R(this,c,E)),this.createController(r.timelineController,k),E.emeController=this.emeController=this.createController(r.emeController,k),this.cmcdController=this.createController(r.cmcdController,k),this.latencyController=this.createController(Aw,k),this.coreComponents=k,x.push(l);const L=l.onErrorOut;"function"==typeof L&&this.on(Cd.ERROR,L,l),this.on(Cd.MANIFEST_LOADED,m.onManifestLoaded,m)}createController(e,t){if(e){const r=new e(this);return t&&t.push(r),r}return null}on(e,t,r=this){this._emitter.on(e,t,r)}once(e,t,r=this){this._emitter.once(e,t,r)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,r=this,n){this._emitter.off(e,t,r,n)}listeners(e){return this._emitter.listeners(e)}emit(e,t,r){return this._emitter.emit(e,t,r)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;const r=e===Cd.ERROR;this.trigger(Cd.ERROR,{type:Ld.OTHER_ERROR,details:Id.INTERNAL_EXCEPTION,fatal:r,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(Cd.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.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 t=new Error(`attachMedia failed: invalid argument (${e})`);return void this.trigger(Cd.ERROR,{type:Ld.OTHER_ERROR,details:Id.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,r=t?e.media:e,n=t?e:{media:r};this._media=r,this.trigger(Cd.MEDIA_ATTACHING,n)}detachMedia(){this.logger.log("detachMedia"),this.trigger(Cd.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(Cd.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,r=this._url,n=this._url=ch.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${n}`),t&&r&&(r!==n||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(Cd.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let r=0;r<this.networkControllers.length&&(this.networkControllers[r].startLoad(e,t),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={[Od]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[Nd]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[Fd]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=function(){try{return crypto.randomUUID()}catch(e){try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){let t=(new Date).getTime();const r="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const r=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==e?r:3&r|8).toString(16)});return r}}}()),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-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}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){(function(e){return mf.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const r=e.length;for(let n=0;n<r;n++)if(e[n].maxBitrate>=t)return n;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:r}=this;let n;if(n=-1===t&&null!=e&&e.length?e.length-1:t,r)for(let t=n;t--;){const n=e[t].attrs["HDCP-LEVEL"];if(n&&n<=r)return t}return n}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 t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.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 t=this.audioTrackController;t&&(t.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 t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.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!(null==(e=this.bufferController)||!e.bufferedToEnd)}get interstitialsManager(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){return ff(e,Lf(t),navigator.mediaCapabilities)}}Fw.defaultConfig=void 0;const $w=({file:e,startTime:t,poster:r,autoplay:n=!0,active:i=!0,visible:s=!0,muted:a=!0})=>{const o=p.useRef(null),{isReady:l,prewarm:u,setLowestResolution:c,startBufferBasedUpshift:d}=(({file:e,videoRef:t,autoplay:r=!0,startTime:n,enabled:i=!0,onReady:s,onError:a})=>{const o=p.useRef(null),l=p.useRef(null),u=p.useRef(0),c=p.useRef(0),d=p.useRef(!1),h=p.useRef(!1),[f,g]=p.useState("idle"),[m,v]=p.useState(0),[y,b]=p.useState(!1),[w,E]=p.useState([]),[S,T]=p.useState("auto"),x=()=>{null!=l.current&&(clearTimeout(l.current),l.current=null)},k=(e=1e3)=>{if(null!=l.current)return;const t=u.current;if(t>=5)return g("error"),x(),void(null==a||a(new Error("Max retry reached")));const r=Math.min(15e3,e*Math.pow(2,Math.min(t,4)));g("loading"),console.log(`[HLS] schedule retry #${t+1} in ${r}ms`),l.current=window.setTimeout(()=>{l.current=null,u.current+=1,console.log(`[HLS] retryCount => ${u.current}`),v(e=>e+1)},r)};p.useEffect(()=>{u.current=0,c.current=0,h.current=!1,b(!1),v(0),g(e?"loading":"idle"),x()},[e]);const A=p.useCallback(()=>J(void 0,void 0,void 0,function*(){if(e)try{yield fetch(e,{method:"HEAD",mode:"cors",credentials:"omit"})}catch(e){}}),[e]);p.useEffect(()=>{var n;const l=t.current;if(!l||!e||!i)return void(e&&!i&&(h.current=!1,b(!1),g("idle")));let f=()=>{};try{null===(n=o.current)||void 0===n||n.destroy()}catch(e){}if(o.current=null,h.current=!1,b(!1),g("loading"),Fw.isSupported()){d.current=!1;const t=new Fw({lowLatencyMode:!1,backBufferLength:0,maxBufferLength:2,maxMaxBufferLength:4,maxBufferSize:2e6,maxBufferHole:.5,startFragPrefetch:!0,capLevelToPlayerSize:!0});o.current=t;const n=()=>{const e=(t.levels||[]).map((e,t)=>{const r=e.height,n=e.width,i=e.bitrate,s=e.name;return{id:t,height:r,width:n,bitrate:i,name:s,label:s||(r?`${r}p`:`Level ${t}`)}});E(e);const r=t.currentLevel;T(null==r||r<0?"auto":r)},i=()=>{h.current||(h.current=!0,b(!0),g("ready"),u.current=0,x(),null==s||s(),r&&l.play().catch(()=>{}))};t.on(Fw.Events.MANIFEST_PARSED,()=>{n(),r||L()}),t.on(Fw.Events.FRAG_BUFFERED,i),t.on(Fw.Events.BUFFER_APPENDED,i),t.on(Fw.Events.LEVEL_SWITCHED,(e,t)=>{const r=null==t?void 0:t.level;T(null==r||r<0?"auto":r)}),t.on(Fw.Events.ERROR,(e,r)=>{var n,i,s,l,d;const f=500===(null!==(l=null!==(i=null===(n=null==r?void 0:r.response)||void 0===n?void 0:n.code)&&void 0!==i?i:null===(s=null==r?void 0:r.response)||void 0===s?void 0:s.status)&&void 0!==l?l:null===(d=null==r?void 0:r.response)||void 0===d?void 0:d.statusCode);if(r.type!==Fw.ErrorTypes.NETWORK_ERROR||r.fatal){if(r.fatal){if(r.type===Fw.ErrorTypes.MEDIA_ERROR){if(c.current+=1,c.current<=2){try{t.recoverMediaError()}catch(e){}return void g("loading")}try{t.destroy()}catch(e){}return o.current=null,h.current=!1,b(!1),void k()}if(f){console.warn("[HLS] fatal 500 response - no retry");try{t.destroy()}catch(e){}return o.current=null,h.current=!1,b(!1),x(),g("error"),void(null==a||a(new Error("HTTP 500")))}try{t.destroy()}catch(e){}return o.current=null,h.current=!1,b(!1),void k()}}else{if(f){console.warn("[HLS] 500 response detected - no retry"),g("error");try{t.destroy()}catch(e){}return o.current=null,x(),void(null==a||a(new Error("HTTP 500")))}try{if(u.current>=5){g("error");try{t.destroy()}catch(e){}return o.current=null,void(null==a||a(new Error("Max retry reached")))}u.current+=1,console.log(`[HLS] non-fatal network retry => ${u.current}`),t.startLoad()}catch(e){}}}),t.attachMedia(l),t.loadSource(e),f=()=>{try{t.destroy()}catch(e){}o.current=null}}else if(l.canPlayType("application/vnd.apple.mpegURL")){d.current=!0,l.src!==e&&(l.src=e);const t=()=>{h.current||(h.current=!0,b(!0),g("ready"),u.current=0,x(),null==s||s(),r&&l.play().catch(()=>{}))},n=()=>{if(h.current=!1,b(!1),u.current>=5)return g("error"),void(null==a||a(new Error("Max retry reached")));k()};l.addEventListener("loadedmetadata",t),l.addEventListener("error",n),r&&l.play().catch(()=>{}),f=()=>{l.removeEventListener("loadedmetadata",t),l.removeEventListener("error",n)}}else g("error"),null==a||a(new Error("HLS not supported"));return()=>{f(),x()}},[e,m,r,s,a,t,i]),p.useEffect(()=>{if(!y)return;if(null==n||n<=0)return;const e=t.current;if(e)try{Math.abs(e.currentTime-n)>.5&&(e.currentTime=n)}catch(e){}},[y,n,t]),p.useEffect(()=>{const e=t.current;if(!e)return;const r=()=>g("ready"),n=()=>g("ready"),i=()=>{"error"!==f&&g("loading")},s=()=>g("loading"),o=()=>{g("error"),null==a||a()};return e.addEventListener("playing",r),e.addEventListener("canplay",n),e.addEventListener("waiting",i),e.addEventListener("stalled",s),e.addEventListener("error",o),()=>{e.removeEventListener("playing",r),e.removeEventListener("canplay",n),e.removeEventListener("waiting",i),e.removeEventListener("stalled",s),e.removeEventListener("error",o)}},[f,a,t]);const R=p.useCallback(()=>{const e=o.current;e&&!d.current&&(console.log("Set auto resolution"),e.nextLevel=-1,T("auto"))},[]),L=p.useCallback(()=>{var e,t;const r=o.current;if(!r)return;const n=r.levels||[];if(n.length){let i=0;for(let r=1;r<n.length;r++)(null!==(e=n[r].height)&&void 0!==e?e:99999)<(null!==(t=n[i].height)&&void 0!==t?t:99999)&&(i=r);r.currentLevel=i}},[]),I=p.useCallback((e=2)=>{const r=o.current,n=t.current;if(!r||!n||d.current)return()=>{};let i=!1;const s=()=>{if(!i)if(r.autoLevelEnabled)i=!0;else try{n.buffered.length>0&&n.buffered.end(0)-n.currentTime>=e&&(r.nextLevel=-1,T("auto"),i=!0)}catch(e){}};return r.on(Fw.Events.FRAG_BUFFERED,s),()=>{r.off(Fw.Events.FRAG_BUFFERED,s)}},[t]);return{playbackStatus:f,isReady:y,qualities:w,currentLevel:S,isAutoQuality:p.useMemo(()=>"auto"===S,[S]),canSetResolution:!d.current&&Fw.isSupported(),setResolution:e=>{const t=o.current;if(!t||d.current)return;if("string"==typeof e&&"auto"===e.toLowerCase())return t.currentLevel=-1,void T("auto");const r="number"==typeof e?e:parseInt(e,10);if(!Number.isFinite(r)){const r=w.find(t=>t.label.toLowerCase()===String(e).toLowerCase());return void(r&&(t.currentLevel=r.id,T(r.id)))}const n=[...w].filter(e=>e.height).sort((e,t)=>(t.height||0)-(e.height||0)),i=n.find(e=>(e.height||0)<=r)||n[n.length-1];i&&(t.currentLevel=i.id,T(i.id))},setAutoResolution:R,prewarm:A,setLowestResolution:L,startBufferBasedUpshift:I}})({file:e,videoRef:o,autoplay:n,startTime:t,enabled:n||i});return p.useEffect(()=>{u()},[u]),g.useEffect(()=>{var e,t;const r=o.current;if(r)if(i)null===(e=r.play)||void 0===e||e.call(r).catch(()=>{});else try{null===(t=r.pause)||void 0===t||t.call(r)}catch(e){}},[i,l]),p.useEffect(()=>{if(!i)return;c();return d(2)},[i,c,d]),g.createElement("video",{ref:o,playsInline:!0,autoPlay:n,muted:a,poster:Gt(r||""),preload:"metadata",className:"w-full h-full object-cover object-center bg-black",style:{opacity:s&&l?1:0,transition:"opacity 200ms ease-in-out"}})},Bw=({view:e})=>g.createElement("div",{className:"absolute",style:{top:8,left:8,borderRadius:"4px",color:"white",overflow:"hidden",fontSize:11}},g.createElement("span",{style:{backgroundColor:"rgba(62,213,69,0.71)",color:"white",padding:4,paddingLeft:9,paddingRight:9,display:"inline-block",lineHeight:1}},"다시보기"),g.createElement("span",{style:{backgroundColor:"rgba(58,58,58,0.52)",color:"white",padding:4,paddingLeft:9,paddingRight:9,display:"inline-block",lineHeight:1}},e," 시청")),Uw=({content:e,aspectRatio:t="9/16",cursor:r="default",borderRadius:n,playback:i="hover"})=>{var s,a,o,l,u;const c=g.useRef(null),[d,h]=g.useState(!1),f=g.useRef(null),[p,m]=g.useState(!1),[v,y]=g.useState(!0),[b,w]=g.useState(!1),{boxSize:E}=Td(t,c),S=e.thumbPath||(null===(a=null===(s=null==e?void 0:e.designInfo)||void 0===s?void 0:s.thumbPath)||void 0===a?void 0:a.preview),T=3===e.status,{API_BASE_URL:x,PLAYER_BASE_URL:k}=Mt(),A=`${x}/hls/${null===(o=e.replay)||void 0===o?void 0:o.objectId}`;g.useEffect(()=>{const e=c.current;if(!e)return;const t=new IntersectionObserver(e=>{const t=e[0];w(t.isIntersecting&&t.intersectionRatio>=.5)},{root:null,threshold:[0,.5,1]});return t.observe(e),()=>t.disconnect()},[i]),g.useEffect(()=>{var e;if("undefined"!=typeof window&&window.matchMedia)try{const t=window.matchMedia("(pointer: fine)"),r=()=>y(t.matches);return r(),null===(e=t.addEventListener)||void 0===e||e.call(t,"change",r),()=>{var e;return null===(e=t.removeEventListener)||void 0===e?void 0:e.call(t,"change",r)}}catch(e){}},[i]);const R=()=>{null!=f.current&&(clearTimeout(f.current),f.current=null)},L=()=>{m(!0),R(),h(!1)};g.useEffect(()=>{const e=()=>m(!1);return window.addEventListener("mouseup",e),window.addEventListener("touchend",e),window.addEventListener("pointerup",e),()=>{window.removeEventListener("mouseup",e),window.removeEventListener("touchend",e),window.removeEventListener("pointerup",e)}},[i]);const I="hover"===i&&v,C=Boolean(A&&("autoplay"===i&&b||I&&d));return g.createElement("div",{className:"w-full h-full flex flex-col items-center justify-center",ref:c,onMouseEnter:()=>{"hover"===i&&v&&(p||(R(),f.current=window.setTimeout(()=>{h(!0)},150)))},onMouseLeave:()=>{R(),h(!1)},onMouseDown:L,onTouchStart:L},g.createElement("div",{className:"relative rounded overflow-hidden",style:{width:E.width?`${E.width}px`:"100%",height:E.height?`${E.height}px`:"100%",borderRadius:`${null!=n?n:10}px`,backgroundRepeat:"no-repeat",backgroundPosition:"center",backgroundSize:"cover",aspectRatio:E.height?void 0:t,backgroundImage:S?`url(${Gt(S)})`:void 0,backgroundColor:S?void 0:"black"}},T?g.createElement("iframe",{src:`${k}/live/${e.eventId}`,className:"w-full h-full"}):g.createElement(g.Fragment,null,g.createElement("div",{className:"absolute inset-0 w-full h-full object-cover",style:{pointerEvents:"none"}},g.createElement($w,{file:A,poster:S,autoplay:"autoplay"===i,active:"autoplay"===i&&b||I&&d,visible:C,muted:!0})),!C&&g.createElement(Ed,null),g.createElement(Bw,{view:null!==(u=null===(l=e.statistics)||void 0===l?void 0:l.pageView)&&void 0!==u?u:0}))))},zw=e=>{var t,r,n,i;const{content:s,title:a,aspectRatio:o="9/16",card:l,titleFontSize:u}=e,c=null!==(t=null==l?void 0:l.layout)&&void 0!==t?t:"slider",d=null!==(r=null==l?void 0:l.sliderPerView)&&void 0!==r?r:3,h=null!==(n=null==l?void 0:l.gridColumns)&&void 0!==n?n:3,f=null!==(i=null==l?void 0:l.gap)&&void 0!==i?i:12,m=null==l?void 0:l.width,v=m?"auto":d,y=p.useMemo(()=>({fontSize:u?`${u}px`:void 0,fontWeight:600}),[u]),{PLAYER_BASE_URL:b}=Mt();return s&&0!==s.length?g.createElement("div",{className:"flex flex-col w-full",style:{gap:f}},g.createElement("p",{className:"truncate",style:Object.assign(Object.assign({},y),{userSelect:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none",cursor:"default"})},a||("past"===e.liveType?"지난 라이브":"예정된 라이브")),"slider"===c?g.createElement("div",null,g.createElement(_n,{key:`${v}-${null!=m?m:""}-${f}`,slidesPerView:v,spaceBetween:f},s.map(t=>{var r,n;return g.createElement(Mn,{key:t.eventId,style:m?{width:`${m}px`}:void 0},g.createElement("a",{href:`${b}/live/${t.eventId}`,target:"_blank",rel:"noopener noreferrer",className:"flex flex-col",style:{gap:6,textDecoration:"none",cursor:"pointer"}},"past"===e.liveType?g.createElement(Uw,{content:t,aspectRatio:o,cursor:"pointer",borderRadius:null==l?void 0:l.borderRadius,playback:e.playback}):g.createElement(xd,{content:t,aspectRatio:o,cursor:"pointer",borderRadius:null==l?void 0:l.borderRadius}),g.createElement("p",{className:"truncate",style:{color:null!==(n=null===(r=e.theme)||void 0===r?void 0:r.textColor)&&void 0!==n?n:"black",fontSize:14,userSelect:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none"}},t.eventName)))}))):g.createElement("div",{style:{overflowY:"auto"}},g.createElement("div",{style:{display:"grid",gridTemplateColumns:m?`repeat(auto-fill, ${m}px)`:`repeat(${h}, minmax(0, 1fr))`,gap:f}},s.map(t=>{var r,n;return g.createElement("a",{key:t.eventId,href:`${b}/live/${t.eventId}`,target:"_blank",rel:"noopener noreferrer",className:"flex flex-col",style:{gap:6,textDecoration:"none",cursor:"pointer"}},"past"===e.liveType?g.createElement(Uw,{content:t,aspectRatio:o,cursor:"pointer",borderRadius:null==l?void 0:l.borderRadius,playback:e.playback}):g.createElement(xd,{content:t,aspectRatio:o,cursor:"pointer",borderRadius:null==l?void 0:l.borderRadius}),g.createElement("p",{className:"truncate",style:{color:null!==(n=null===(r=e.theme)||void 0===r?void 0:r.textColor)&&void 0!==n?n:"black",fontSize:14,userSelect:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none"}},t.eventName))})))):null};var jw;!function(e){e[e.READY=1]="READY",e[e.STREAMING=2]="STREAMING",e[e.PAUSED=3]="PAUSED"}(jw||(jw={}));const Gw=({content:e})=>{const t=g.useMemo(()=>vt(e.start).tz("Asia/Seoul").format("M월 D일 A HH:mm"),[e.start]),r=e.eventStatus!==jw.READY;return g.createElement("div",{className:"flex-1 flex flex-col gap-5 items-center justify-center"},g.createElement("p",{style:{fontWeight:"bold",fontSize:"24px"}},e.eventName),!r&&g.createElement("p",null,t),g.createElement("button",{onClick:()=>{window.open(`https://player.midibus.im/live/${e.eventId}`,"_blank")},className:"rounded bg-black text-white cursor-pointer",style:{width:"70%",padding:"10px"}},"라이브 입장하기"))},Hw=e=>{var t,r;const{content:n,aspectRatio:i="9/16",videoAlign:s}=e,a=null===(t=e.card)||void 0===t?void 0:t.borderRadius,o=null===(r=e.card)||void 0===r?void 0:r.width,{PLAYER_BASE_URL:l}=Mt();return g.createElement("div",{className:"flex w-full h-full items-center justify-center"},"only"===s?g.createElement("a",{className:"w-full h-full",href:`${l}/live/${n.eventId}`,target:"_blank",rel:"noopener noreferrer",style:o?{width:`${o}px`}:void 0},g.createElement(xd,{content:n,aspectRatio:i,borderRadius:a,cursor:"pointer"})):"left"===s?g.createElement(g.Fragment,null,g.createElement("div",{className:"flex-1"},g.createElement("a",{href:`${l}/live/${n.eventId}`,target:"_blank",rel:"noopener noreferrer",style:o?{width:`${o}px`}:void 0},g.createElement(xd,{content:n,aspectRatio:i,borderRadius:a,cursor:"pointer"}))),g.createElement(Gw,{content:n})):g.createElement(g.Fragment,null,g.createElement(Gw,{content:n}),g.createElement("div",{className:"flex-1"},g.createElement("a",{href:`${l}/live/${n.eventId}`,target:"_blank",rel:"noopener noreferrer",style:o?{width:`${o}px`}:void 0},g.createElement(xd,{content:n,aspectRatio:i,borderRadius:a,cursor:"pointer"})))))},Vw=e=>{var t;const{theme:r,titleFontSize:n,title:i}=e;return g.createElement("div",{className:"w-full h-full flex flex-col",style:{color:null!==(t=null==r?void 0:r.textColor)&&void 0!==t?t:"#252525"}},g.createElement("p",{style:Object.assign(Object.assign({},n&&{fontSize:n}),{fontWeight:"bold",color:null==r?void 0:r.textColor,paddingTop:"10px",paddingBottom:"10px",marginBottom:"30px"})},i||("past"===e.liveType?"지난 라이브":"예정된 라이브")),g.createElement("div",{className:"self-center text-center h-full flex flex-col items-center justify-center",style:{minHeight:"200px"}},g.createElement("p",{style:{fontSize:"20px",marginBottom:"10px"}},"past"===e.liveType?"지난 라이브가 없어요.":"예정된 라이브가 없어요."),g.createElement("span",{style:{fontWeight:"lighter"}},"past"===e.liveType?"다른 콘텐츠도 확인해 보세요.":"곧 혜택 가득한 라이브로 찾아올게요!")))};function Ww(e){var{className:t}=e,r=Z(e,["className"]);return p.createElement("div",Object.assign({className:Ot("animate-pulse rounded-md bg-gray-200",t)},r))}const Kw=e=>{var t,r,n,i,s,a,o,l,u;const{card:c,aspectRatio:d="9/16",widgetType:h,layout:f,theme:p}=e,m=null!==(t=null==c?void 0:c.layout)&&void 0!==t?t:"slider",v=null!==(r=null==c?void 0:c.sliderPerView)&&void 0!==r?r:3,y=null!==(n=null==c?void 0:c.gridColumns)&&void 0!==n?n:3,b=null!==(i=null==c?void 0:c.gap)&&void 0!==i?i:12,w=null!==(s=null==c?void 0:c.borderRadius)&&void 0!==s?s:8,E=null!==(a=null==f?void 0:f.paddingTop)&&void 0!==a?a:0,S=null!==(o=null==f?void 0:f.paddingBottom)&&void 0!==o?o:0,T=null!==(l=null==f?void 0:f.paddingLeft)&&void 0!==l?l:0,x=null!==(u=null==f?void 0:f.paddingRight)&&void 0!==u?u:0,k="ONE"===h&&"past"!==e.liveType,A=k?1:(null==c?void 0:c.visibleCount)||6,R=k?1:"slider"===m?v:A;return g.createElement("div",{className:"w-full flex flex-col",style:{gap:b,paddingTop:E,paddingBottom:S,paddingLeft:T,paddingRight:x,backgroundColor:null==p?void 0:p.backgroundColor}},g.createElement(Ww,{className:"h-5 w-36"}),g.createElement("div",{style:k||"scroll"!==m?{display:"flex",gap:b,overflow:"hidden"}:{display:"grid",gridTemplateColumns:`repeat(${y}, minmax(0, 1fr))`,gap:b}},Array.from({length:R}).map((e,t)=>g.createElement("div",{key:t,className:"flex flex-col flex-shrink-0",style:{flex:k||"slider"!==m?void 0:`0 0 calc((100% - ${b*(v-1)}px) / ${v})`,gap:6}},g.createElement(Ww,{style:{aspectRatio:d,borderRadius:w,width:"100%"}}),g.createElement(Ww,{className:"h-3.5 w-4/5"})))))},Yw=e=>{var t,r,n,i;const{widgetType:s,theme:a,layout:o}=e,{liveWidget:l}=wd(),u=null!==(t=null==o?void 0:o.paddingTop)&&void 0!==t?t:0,c=null!==(r=null==o?void 0:o.paddingBottom)&&void 0!==r?r:0,d=null!==(n=null==o?void 0:o.paddingLeft)&&void 0!==n?n:0,h=null!==(i=null==o?void 0:o.paddingRight)&&void 0!==i?i:0;return null===l?g.createElement(Kw,Object.assign({},e)):0===l.length?g.createElement(Vw,Object.assign({},e)):g.createElement("div",{className:"w-full h-full",style:{backgroundColor:null==a?void 0:a.backgroundColor,color:null==a?void 0:a.textColor,paddingTop:u,paddingBottom:c,paddingLeft:d,paddingRight:h}},"ONE"===s&&"past"!==e.liveType?g.createElement(Hw,Object.assign({content:l[0]},e)):g.createElement(zw,Object.assign({content:l},e)))},qw=U(e=>{const{container:t}=pc();return t?g.createElement(hr,null,g.createElement(gc,Object.assign({},e,{container:t}))):null},{props:{collectionId:"string",iconForm:"string",iconShape:"string",iconSize:"number",borderLine:"string",exposeTitle:"boolean",titlePosition:"string",player:"string",rounded:"boolean",exposeProductBanner:"boolean",exposeProductBadge:"boolean",priceText:"string",iconRatio:"string",hoverPlay:"boolean",thumbnailAutoPlay:"boolean"}}),Xw=U(e=>{const{container:t}=pc();return t?g.createElement(hr,null,g.createElement(vc,Object.assign({},e,{container:t}))):null},{props:{collectionId:"string",aspectRatio:"string"}}),Qw=U(({shortsId:e,type:t,isPreview:r})=>{const{setShortform:n,shortform:i}=yc();return p.useEffect(()=>{if(!e)return;e&&J(void 0,void 0,void 0,function*(){const t=yield rr(e,r);t&&n(Object.assign(Object.assign({},t),{uuid:Ut()}))})},[e]),i?g.createElement(ac.div,{style:{position:"fixed",inset:0,pointerEvents:"none",zIndex:99999}},g.createElement(fc,null),g.createElement("div",{style:{pointerEvents:"auto"}},g.createElement(vd,{shortsId:e,type:t}))):null},{props:{shortsId:"string",type:"string"}}),Zw=U(e=>{const{setLiveWidget:t,liveWidget:r}=wd(),{userId:n,card:i,includeRepresentative:s,liveType:a}=e;return p.useEffect(()=>{if(!n)return;if(r&&(null==i?void 0:i.visibleCount)&&r.length>Number(i.visibleCount))return void t(r.slice(0,null==i?void 0:i.visibleCount));const o=new AbortController;return J(void 0,void 0,void 0,function*(){const r=yield nr(n,"past"===a?"FINISHED":"UPCOMING",(null==i?void 0:i.visibleCount)||6,s,e.sorting);if(!r||o.signal.aborted)return;t(r);const l=yield Promise.allSettled(r.map(e=>J(void 0,void 0,void 0,function*(){const t=yield((e,t)=>J(void 0,void 0,void 0,function*(){const{STATISTICS_BASE_URL:r}=Mt(),n=`${r}/replay/${e}/${t}/summary`,i=yield fetch(n);if(404!==i.status){if(!i.ok){const e=yield i.text().catch(()=>"");return console.error(`[ReplayStatistics] ${i.status} ${i.statusText} ${e}`),{pageView:0,like:0}}return i.json()}}))(n,e.eventId);return Object.assign(Object.assign({},e),{statistics:t})})));o.signal.aborted||t(l.map((e,t)=>"fulfilled"===e.status?e.value:r[t]))}),()=>o.abort()},[n,null==i?void 0:i.visibleCount,a,e.sorting,s]),g.createElement(ac.div,{className:"w-full h-full"},g.createElement(fc,null),g.createElement(Yw,Object.assign({},e)))},{props:{userId:"string",title:"string",titleFontSize:"number",isPreview:"boolean",liveType:"string",widgetType:"string",videoAlign:"string",aspectRatio:"string",playback:"string",includeRepresentative:"boolean",theme:"json",layout:"json",card:"json",sorting:"string"}}),Jw=U(({eventId:e})=>e?g.createElement(ac.div,{style:{position:"fixed",inset:0,pointerEvents:"none",zIndex:99999}},g.createElement(fc,null),g.createElement("div",{style:{pointerEvents:"auto"}},g.createElement(yd,{eventId:e}))):null,{props:{eventId:"string"}});customElements.define("mc-widget-player",qw),customElements.define("mc-collection-showcase",Xw),customElements.define("mc-floating-player",Qw),customElements.define("mc-live-widget",Zw),customElements.define("mc-live-floating-player",Jw)});
|