@camstack/addon-admin-ui 0.1.46 → 0.1.47

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.
Files changed (49) hide show
  1. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs-CRKSbdgN.js → __mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs-CawbgE5L.js} +1 -1
  2. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs_commonjs-proxy-BGPfTw3V.js → __mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs_commonjs-proxy-GKALXIcl.js} +1 -1
  3. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.mjs-jPpiOa0I.js → __mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.mjs-JVZxVBTk.js} +1 -1
  4. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.mjs_commonjs-proxy-DYNYuSL7.js → __mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.mjs_commonjs-proxy-fDAP1KhM.js} +1 -1
  5. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare__react__loadShare__.mjs-ij0ODm-n.js → __mfe_internal__admin_ui_host__loadShare__react__loadShare__.mjs-hk6goaRc.js} +1 -1
  6. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare__react__loadShare__.mjs_commonjs-proxy-C4Ko8zXp.js → __mfe_internal__admin_ui_host__loadShare__react__loadShare__.mjs_commonjs-proxy-CKOygvIQ.js} +1 -1
  7. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.mjs-Cf5gSqc_.js → __mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.mjs-DGvrhOC3.js} +1 -1
  8. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-CYaX3FDr.js → __mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-DG9hE2tk.js} +1 -1
  9. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs-rHwdrynu.js → __mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs-ByazpYAv.js} +1 -1
  10. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs_commonjs-proxy-DRDS6j-Y.js → __mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs_commonjs-proxy-CxaW4xr1.js} +1 -1
  11. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare__react_mf_2_konva__loadShare__.mjs-cUuqcEcL.js → __mfe_internal__admin_ui_host__loadShare__react_mf_2_konva__loadShare__.mjs-BLBZm4ju.js} +1 -1
  12. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare__react_mf_2_konva__loadShare__.mjs_commonjs-proxy-CzMP41OH.js → __mfe_internal__admin_ui_host__loadShare__react_mf_2_konva__loadShare__.mjs_commonjs-proxy-LyTotJxo.js} +1 -1
  13. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-DNAkeUTZ.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-C3ppGtyE.js} +1 -1
  14. package/dist/assets/{devices-DaqavVOg.js → devices-DmCyuEuQ.js} +1 -1
  15. package/dist/assets/{hostInit-ByQycOVJ.js → hostInit-BhyqZ3AI.js} +1 -1
  16. package/dist/assets/index-BH5Ezf7x.js +1 -0
  17. package/dist/assets/index-BPRNeJ5M.js +126 -0
  18. package/dist/assets/index-BViRW9IB.js +1 -0
  19. package/dist/assets/index-BpGkKz46.js +1 -0
  20. package/dist/assets/index-C2d2NdfQ.css +1 -0
  21. package/dist/assets/index-C9MS3ovr.js +1 -0
  22. package/dist/assets/index-CAZNi1Jm.js +1 -0
  23. package/dist/assets/index-CDGj60rb.js +190 -0
  24. package/dist/assets/index-DBG7Fygw.js +1 -0
  25. package/dist/assets/index-DeFTFjpg.js +1514 -0
  26. package/dist/assets/{index-BpC2rqYA.js → index-DuP0eN9F.js} +1 -1
  27. package/dist/assets/index-na_oszC9.js +1 -0
  28. package/dist/assets/method-access-map-BCPBTC0g.js +1 -0
  29. package/dist/assets/{remoteEntry-iRKuVHUX.js → remoteEntry-0I-ik-5b.js} +1 -1
  30. package/dist/assets/{schemas-BdJePqbR.js → schemas-DSjJ1TGP.js} +4 -4
  31. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-QVZxTxLo.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-ChhI9HQF.js} +2 -2
  32. package/dist/index.html +31 -11
  33. package/dist/mf-entry-bootstrap-0.js +2 -2
  34. package/dist/server/addon.js +3332 -564
  35. package/dist/server/addon.js.map +1 -1
  36. package/dist/sw.js +1 -1
  37. package/package.json +2 -1
  38. package/dist/assets/index-B6kubsZI.js +0 -151
  39. package/dist/assets/index-BI1a6Whs.js +0 -1
  40. package/dist/assets/index-BVNg3Krt.js +0 -1185
  41. package/dist/assets/index-BbwPCEeT.js +0 -1
  42. package/dist/assets/index-CukoHCyD.js +0 -1
  43. package/dist/assets/index-Cyva9RmE.js +0 -1
  44. package/dist/assets/index-DLnW8nGB.css +0 -1
  45. package/dist/assets/index-DNydUTOB.js +0 -1
  46. package/dist/assets/index-DVLRgczW.js +0 -1
  47. package/dist/assets/index-PXbclFuZ.js +0 -87
  48. package/dist/assets/index-QqQmcu5i.js +0 -1
  49. package/dist/assets/method-access-map-DjDdPRYC.js +0 -1
@@ -0,0 +1,126 @@
1
+ import{e as _,h as q,c as ae,f as oe,d as ct,b as hr,i as ne,n as It,R as dt,m as fr,o as Gf,q as Uy,k as Is,g as mc,p as _u,a as Hf}from"./__mfe_internal__admin_ui_host__loadShare__react__loadShare__.mjs-hk6goaRc.js";import{c as u,d as v,e as Ie,a as Vf}from"./__mfe_internal__admin_ui_host__loadShare__react_mf_1_jsx_mf_2_runtime__loadShare__.mjs-C_6K4VBY.js";import{b as Ys,a as jf}from"./__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.mjs-DGvrhOC3.js";import{b as Gy,a as Kf}from"./__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs-ByazpYAv.js";import{n as ts,m as gc,h as Hy,o as Vy,p as jy,_ as zf}from"./__mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs-CawbgE5L.js";import{c as Wf,s as Qf,B as Ky,F as zy,n as Wy,_ as qf}from"./__mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_client__loadShare__.mjs-DIkg6-MH.js";import{a as Qy,_ as Yf}from"./__mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.mjs-JVZxVBTk.js";import{a as rn,b as qy,c as Ga,d as Wn,e as Ji,_ as Xf,f as Zf,g as Jf,h as Yy}from"./__mfe_internal__admin_ui_host__loadShare__react_mf_2_konva__loadShare__.mjs-BLBZm4ju.js";import{_ as ep}from"./__mfe_internal__admin_ui_host__loadShare__konva__loadShare__.mjs-g85Oidc0.js";import{D as te,b as Ft,a as Le,e as Xy,R as Zy,d as Jy,f as e0,g as t0,c as r0,S as n0,E as s0}from"./index-BViRW9IB.js";import{K as i0,T as Ou,f as a0,E as Ee,A as o0}from"./method-access-map-BCPBTC0g.js";import{c as l0}from"./devices-DmCyuEuQ.js";import{a as vc,o as c0,b as Ha,s as nn,n as Fu}from"./schemas-DSjJ1TGP.js";import"./__mfe_internal__admin_ui_host__loadShare__react__loadShare__.mjs_commonjs-proxy-CKOygvIQ.js";import"./__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-DG9hE2tk.js";var tp={frigate:"#3b82f6",scrypted:"#a855f7",reolink:"#06b6d4",homeAssistant:"#22d3ee",rtsp:"#78716c"},u0={primary:"#f59e42",primaryForeground:"#0c0a09",background:"#0c0a09",backgroundElevated:"#1c1917",surface:"#1c1917",surfaceHover:"#292524",border:"#292524",borderSubtle:"#1c1917",foreground:"#fafaf9",foregroundMuted:"#a8a29e",foregroundSubtle:"#78716c",foregroundDisabled:"#57534e",success:"#4ade80",warning:"#fbbf24",danger:"#f87171",info:"#60a5fa",provider:tp},d0={primary:"#e67e22",primaryForeground:"#ffffff",background:"#fafaf9",backgroundElevated:"#ffffff",surface:"#f5f5f4",surfaceHover:"#e7e5e4",border:"#d6d3d1",borderSubtle:"#e7e5e4",foreground:"#1c1917",foregroundMuted:"#57534e",foregroundSubtle:"#78716c",foregroundDisabled:"#a8a29e",success:"#16a34a",warning:"#d97706",danger:"#dc2626",info:"#2563eb",provider:tp},$u={colors:{dark:u0,light:d0},spacing:{xs:2,sm:4,md:8,lg:12,xl:16,"2xl":24,"3xl":32},radius:{sm:4,md:6,lg:8,xl:12},typography:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',sizes:{xs:{fontSize:10,lineHeight:14},sm:{fontSize:11,lineHeight:16},base:{fontSize:12,lineHeight:18},lg:{fontSize:13,lineHeight:18},xl:{fontSize:14,lineHeight:20},"2xl":{fontSize:16,lineHeight:22},"3xl":{fontSize:20,lineHeight:28}},weights:{regular:400,medium:500,semibold:600,bold:700}},table:{rowHeight:28,headerHeight:24,cellPaddingX:8,cellPaddingY:6},sidebar:{width:176,itemHeight:28,iconSize:14}};function rp(e,t){const r={...e};for(const n in t){const s=t[n],i=e[n];s!==void 0&&typeof s=="object"&&s!==null&&!Array.isArray(s)&&typeof i=="object"&&i!==null?r[n]=rp(i,s):s!==void 0&&(r[n]=s)}return r}function xO(e){return e?rp(structuredClone($u),e):structuredClone($u)}function np(e){return e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}function h0(e){return`--color-${np(e)}`}function Bu(e){const t=[];for(const[r,n]of Object.entries(e))r!=="provider"&&t.push(` ${h0(r)}: ${n};`);return t.join(`
2
+ `)}function f0(e){const t=[];for(const[r,n]of Object.entries(e))t.push(` --color-provider-${np(r)}: ${n};`);return t.join(`
3
+ `)}function p0(e){const t=[];for(const[r,n]of Object.entries(e))t.push(` --spacing-${r}: ${n}px;`);return t.join(`
4
+ `)}function m0(e){const t=[];for(const[r,n]of Object.entries(e))t.push(` --radius-${r}: ${n}px;`);return t.join(`
5
+ `)}function SO(e){const t=Bu(e.colors.dark),r=Bu(e.colors.light);return`@theme {
6
+ ${f0(e.colors.dark.provider)}
7
+ ${p0(e.spacing)}
8
+ ${m0(e.radius)}
9
+ }
10
+
11
+ .dark {
12
+ ${t}
13
+ }
14
+
15
+ .light {
16
+ ${r}
17
+ }
18
+
19
+ @media (prefers-color-scheme: dark) {
20
+ :root {
21
+ ${t.replace(/^ {2}/gm," ")}
22
+ }
23
+ }
24
+
25
+ @media (prefers-color-scheme: light) {
26
+ :root {
27
+ ${r.replace(/^ {2}/gm," ")}
28
+ }
29
+ }
30
+ `}var sp=hr(null),Va=["dark","light","system"];function ip(){return typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function g0(e,t){if(typeof window>"u")return t;const r=localStorage.getItem(e);return r==="dark"||r==="light"||r==="system"?r:t}function Uu(e){return e==="system"?ip():e}function Gu({children:e,defaultMode:t="system",storageKey:r="camstack-theme-mode"}){const[n,s]=_(()=>g0(r,t)),[i,a]=_(()=>Uu(n)),l=q(d=>{s(d),a(Uu(d)),typeof window<"u"&&localStorage.setItem(r,d)},[r]),o=q(()=>{l(Va[(Va.indexOf(n)+1)%Va.length]??"dark")},[n,l]);ae(()=>{if(typeof document>"u")return;const d=document.documentElement;d.classList.remove("dark","light"),d.classList.add(i)},[n,i]),ae(()=>{if(typeof window>"u"||n!=="system")return;const d=window.matchMedia("(prefers-color-scheme: dark)"),h=()=>{a(ip())};return d.addEventListener("change",h),()=>d.removeEventListener("change",h)},[n]);const c=oe(()=>({mode:n,resolvedMode:i,setMode:l,toggleMode:o}),[n,i,l,o]);return u(sp.Provider,{value:c,children:e})}function v0(){const e=ct(sp);if(!e)throw new Error("useThemeMode must be used within a ThemeProvider");return e}var ja={};function ap(e){var t,r,n="";if(typeof e=="string"||typeof e=="number")n+=e;else if(typeof e=="object")if(Array.isArray(e)){var s=e.length;for(t=0;t<s;t++)e[t]&&(r=ap(e[t]))&&(n&&(n+=" "),n+=r)}else for(r in e)e[r]&&(n&&(n+=" "),n+=r);return n}function op(){for(var e,t,r=0,n="",s=arguments.length;r<s;r++)(e=arguments[r])&&(t=ap(e))&&(n&&(n+=" "),n+=t);return n}var b0=(e,t)=>{const r=new Array(e.length+t.length);for(let n=0;n<e.length;n++)r[n]=e[n];for(let n=0;n<t.length;n++)r[e.length+n]=t[n];return r},y0=(e,t)=>({classGroupId:e,validator:t}),lp=(e=new Map,t=null,r)=>({nextPart:e,validators:t,classGroupId:r}),ea="-",Hu=[],x0="arbitrary..",S0=e=>{const t=w0(e),{conflictingClassGroups:r,conflictingClassGroupModifiers:n}=e;return{getClassGroupId:a=>{if(a.startsWith("[")&&a.endsWith("]"))return E0(a);const l=a.split(ea);return cp(l,l[0]===""&&l.length>1?1:0,t)},getConflictingClassGroupIds:(a,l)=>{if(l){const o=n[a],c=r[a];return o?c?b0(c,o):o:c||Hu}return r[a]||Hu}}},cp=(e,t,r)=>{if(e.length-t===0)return r.classGroupId;const n=e[t],s=r.nextPart.get(n);if(s){const o=cp(e,t+1,s);if(o)return o}const i=r.validators;if(i===null)return;const a=t===0?e.join(ea):e.slice(t).join(ea),l=i.length;for(let o=0;o<l;o++){const c=i[o];if(c.validator(a))return c.classGroupId}},E0=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),r=t.indexOf(":"),n=t.slice(0,r);return n?x0+n:void 0})(),w0=e=>{const{theme:t,classGroups:r}=e;return k0(r,t)},k0=(e,t)=>{const r=lp();for(const n in e){const s=e[n];bc(s,r,n,t)}return r},bc=(e,t,r,n)=>{const s=e.length;for(let i=0;i<s;i++){const a=e[i];T0(a,t,r,n)}},T0=(e,t,r,n)=>{if(typeof e=="string"){A0(e,t,r);return}if(typeof e=="function"){C0(e,t,r,n);return}N0(e,t,r,n)},A0=(e,t,r)=>{const n=e===""?t:up(t,e);n.classGroupId=r},C0=(e,t,r,n)=>{if(L0(e)){bc(e(n),t,r,n);return}t.validators===null&&(t.validators=[]),t.validators.push(y0(r,e))},N0=(e,t,r,n)=>{const s=Object.entries(e),i=s.length;for(let a=0;a<i;a++){const[l,o]=s[a];bc(o,up(t,l),r,n)}},up=(e,t)=>{let r=e;const n=t.split(ea),s=n.length;for(let i=0;i<s;i++){const a=n[i];let l=r.nextPart.get(a);l||(l=lp(),r.nextPart.set(a,l)),r=l}return r},L0=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,I0=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,r=Object.create(null),n=Object.create(null);const s=(i,a)=>{r[i]=a,t++,t>e&&(t=0,n=r,r=Object.create(null))};return{get(i){let a=r[i];if(a!==void 0)return a;if((a=n[i])!==void 0)return s(i,a),a},set(i,a){i in r?r[i]=a:s(i,a)}}},il="!",Vu=":",R0=[],ju=(e,t,r,n,s)=>({modifiers:e,hasImportantModifier:t,baseClassName:r,maybePostfixModifierPosition:n,isExternal:s}),M0=e=>{const{prefix:t,experimentalParseClassName:r}=e;let n=s=>{const i=[];let a=0,l=0,o=0,c;const d=s.length;for(let g=0;g<d;g++){const b=s[g];if(a===0&&l===0){if(b===Vu){i.push(s.slice(o,g)),o=g+1;continue}if(b==="/"){c=g;continue}}b==="["?a++:b==="]"?a--:b==="("?l++:b===")"&&l--}const h=i.length===0?s:s.slice(o);let f=h,p=!1;h.endsWith(il)?(f=h.slice(0,-1),p=!0):h.startsWith(il)&&(f=h.slice(1),p=!0);const m=c&&c>o?c-o:void 0;return ju(i,p,f,m)};if(t){const s=t+Vu,i=n;n=a=>a.startsWith(s)?i(a.slice(s.length)):ju(R0,!1,a,void 0,!0)}if(r){const s=n;n=i=>r({className:i,parseClassName:s})}return n},P0=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((r,n)=>{t.set(r,1e6+n)}),r=>{const n=[];let s=[];for(let i=0;i<r.length;i++){const a=r[i],l=a[0]==="[",o=t.has(a);l||o?(s.length>0&&(s.sort(),n.push(...s),s=[]),n.push(a)):s.push(a)}return s.length>0&&(s.sort(),n.push(...s)),n}},D0=e=>({cache:I0(e.cacheSize),parseClassName:M0(e),sortModifiers:P0(e),...S0(e)}),_0=/\s+/,O0=(e,t)=>{const{parseClassName:r,getClassGroupId:n,getConflictingClassGroupIds:s,sortModifiers:i}=t,a=[],l=e.trim().split(_0);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{isExternal:h,modifiers:f,hasImportantModifier:p,baseClassName:m,maybePostfixModifierPosition:g}=r(d);if(h){o=d+(o.length>0?" "+o:o);continue}let b=!!g,y=n(b?m.substring(0,g):m);if(!y){if(!b){o=d+(o.length>0?" "+o:o);continue}if(y=n(m),!y){o=d+(o.length>0?" "+o:o);continue}b=!1}const S=f.length===0?"":f.length===1?f[0]:i(f).join(":"),E=p?S+il:S,k=E+y;if(a.indexOf(k)>-1)continue;a.push(k);const T=s(y,b);for(let A=0;A<T.length;++A){const N=T[A];a.push(E+N)}o=d+(o.length>0?" "+o:o)}return o},F0=(...e)=>{let t=0,r,n,s="";for(;t<e.length;)(r=e[t++])&&(n=dp(r))&&(s&&(s+=" "),s+=n);return s},dp=e=>{if(typeof e=="string")return e;let t,r="";for(let n=0;n<e.length;n++)e[n]&&(t=dp(e[n]))&&(r&&(r+=" "),r+=t);return r},$0=(e,...t)=>{let r,n,s,i;const a=o=>(r=D0(t.reduce((c,d)=>d(c),e())),n=r.cache.get,s=r.cache.set,i=l,l(o)),l=o=>{const c=n(o);if(c)return c;const d=O0(o,r);return s(o,d),d};return i=a,(...o)=>i(F0(...o))},B0=[],pt=e=>{const t=r=>r[e]||B0;return t.isThemeGetter=!0,t},hp=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,fp=/^\((?:(\w[\w-]*):)?(.+)\)$/i,U0=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,G0=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,H0=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,V0=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,j0=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,K0=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Mr=e=>U0.test(e),Me=e=>!!e&&!Number.isNaN(Number(e)),Pr=e=>!!e&&Number.isInteger(Number(e)),Ka=e=>e.endsWith("%")&&Me(e.slice(0,-1)),vr=e=>G0.test(e),pp=()=>!0,z0=e=>H0.test(e)&&!V0.test(e),yc=()=>!1,W0=e=>j0.test(e),Q0=e=>K0.test(e),q0=e=>!pe(e)&&!ve(e),Y0=e=>Kr(e,vp,yc),pe=e=>hp.test(e),Xr=e=>Kr(e,bp,z0),Ku=e=>Kr(e,s1,Me),X0=e=>Kr(e,xp,pp),Z0=e=>Kr(e,yp,yc),zu=e=>Kr(e,mp,yc),J0=e=>Kr(e,gp,Q0),ti=e=>Kr(e,Sp,W0),ve=e=>fp.test(e),as=e=>mn(e,bp),e1=e=>mn(e,yp),Wu=e=>mn(e,mp),t1=e=>mn(e,vp),r1=e=>mn(e,gp),ri=e=>mn(e,Sp,!0),n1=e=>mn(e,xp,!0),Kr=(e,t,r)=>{const n=hp.exec(e);return n?n[1]?t(n[1]):r(n[2]):!1},mn=(e,t,r=!1)=>{const n=fp.exec(e);return n?n[1]?t(n[1]):r:!1},mp=e=>e==="position"||e==="percentage",gp=e=>e==="image"||e==="url",vp=e=>e==="length"||e==="size"||e==="bg-size",bp=e=>e==="length",s1=e=>e==="number",yp=e=>e==="family-name",xp=e=>e==="number"||e==="weight",Sp=e=>e==="shadow",i1=()=>{const e=pt("color"),t=pt("font"),r=pt("text"),n=pt("font-weight"),s=pt("tracking"),i=pt("leading"),a=pt("breakpoint"),l=pt("container"),o=pt("spacing"),c=pt("radius"),d=pt("shadow"),h=pt("inset-shadow"),f=pt("text-shadow"),p=pt("drop-shadow"),m=pt("blur"),g=pt("perspective"),b=pt("aspect"),y=pt("ease"),S=pt("animate"),E=()=>["auto","avoid","all","avoid-page","page","left","right","column"],k=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],T=()=>[...k(),ve,pe],A=()=>["auto","hidden","clip","visible","scroll"],N=()=>["auto","contain","none"],C=()=>[ve,pe,o],M=()=>[Mr,"full","auto",...C()],P=()=>[Pr,"none","subgrid",ve,pe],D=()=>["auto",{span:["full",Pr,ve,pe]},Pr,ve,pe],$=()=>[Pr,"auto",ve,pe],B=()=>["auto","min","max","fr",ve,pe],j=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],U=()=>["start","end","center","stretch","center-safe","end-safe"],F=()=>["auto",...C()],Y=()=>[Mr,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...C()],I=()=>[Mr,"screen","full","dvw","lvw","svw","min","max","fit",...C()],R=()=>[Mr,"screen","full","lh","dvh","lvh","svh","min","max","fit",...C()],O=()=>[e,ve,pe],K=()=>[...k(),Wu,zu,{position:[ve,pe]}],W=()=>["no-repeat",{repeat:["","x","y","space","round"]}],J=()=>["auto","cover","contain",t1,Y0,{size:[ve,pe]}],Q=()=>[Ka,as,Xr],ee=()=>["","none","full",c,ve,pe],ie=()=>["",Me,as,Xr],se=()=>["solid","dashed","dotted","double"],be=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ye=()=>[Me,Ka,Wu,zu],ue=()=>["","none",m,ve,pe],we=()=>["none",Me,ve,pe],le=()=>["none",Me,ve,pe],Z=()=>[Me,ve,pe],ce=()=>[Mr,"full",...C()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[vr],breakpoint:[vr],color:[pp],container:[vr],"drop-shadow":[vr],ease:["in","out","in-out"],font:[q0],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[vr],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[vr],shadow:[vr],spacing:["px",Me],text:[vr],"text-shadow":[vr],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Mr,pe,ve,b]}],container:["container"],columns:[{columns:[Me,pe,ve,l]}],"break-after":[{"break-after":E()}],"break-before":[{"break-before":E()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:T()}],overflow:[{overflow:A()}],"overflow-x":[{"overflow-x":A()}],"overflow-y":[{"overflow-y":A()}],overscroll:[{overscroll:N()}],"overscroll-x":[{"overscroll-x":N()}],"overscroll-y":[{"overscroll-y":N()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:M()}],"inset-x":[{"inset-x":M()}],"inset-y":[{"inset-y":M()}],start:[{"inset-s":M(),start:M()}],end:[{"inset-e":M(),end:M()}],"inset-bs":[{"inset-bs":M()}],"inset-be":[{"inset-be":M()}],top:[{top:M()}],right:[{right:M()}],bottom:[{bottom:M()}],left:[{left:M()}],visibility:["visible","invisible","collapse"],z:[{z:[Pr,"auto",ve,pe]}],basis:[{basis:[Mr,"full","auto",l,...C()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Me,Mr,"auto","initial","none",pe]}],grow:[{grow:["",Me,ve,pe]}],shrink:[{shrink:["",Me,ve,pe]}],order:[{order:[Pr,"first","last","none",ve,pe]}],"grid-cols":[{"grid-cols":P()}],"col-start-end":[{col:D()}],"col-start":[{"col-start":$()}],"col-end":[{"col-end":$()}],"grid-rows":[{"grid-rows":P()}],"row-start-end":[{row:D()}],"row-start":[{"row-start":$()}],"row-end":[{"row-end":$()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":B()}],"auto-rows":[{"auto-rows":B()}],gap:[{gap:C()}],"gap-x":[{"gap-x":C()}],"gap-y":[{"gap-y":C()}],"justify-content":[{justify:[...j(),"normal"]}],"justify-items":[{"justify-items":[...U(),"normal"]}],"justify-self":[{"justify-self":["auto",...U()]}],"align-content":[{content:["normal",...j()]}],"align-items":[{items:[...U(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...U(),{baseline:["","last"]}]}],"place-content":[{"place-content":j()}],"place-items":[{"place-items":[...U(),"baseline"]}],"place-self":[{"place-self":["auto",...U()]}],p:[{p:C()}],px:[{px:C()}],py:[{py:C()}],ps:[{ps:C()}],pe:[{pe:C()}],pbs:[{pbs:C()}],pbe:[{pbe:C()}],pt:[{pt:C()}],pr:[{pr:C()}],pb:[{pb:C()}],pl:[{pl:C()}],m:[{m:F()}],mx:[{mx:F()}],my:[{my:F()}],ms:[{ms:F()}],me:[{me:F()}],mbs:[{mbs:F()}],mbe:[{mbe:F()}],mt:[{mt:F()}],mr:[{mr:F()}],mb:[{mb:F()}],ml:[{ml:F()}],"space-x":[{"space-x":C()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":C()}],"space-y-reverse":["space-y-reverse"],size:[{size:Y()}],"inline-size":[{inline:["auto",...I()]}],"min-inline-size":[{"min-inline":["auto",...I()]}],"max-inline-size":[{"max-inline":["none",...I()]}],"block-size":[{block:["auto",...R()]}],"min-block-size":[{"min-block":["auto",...R()]}],"max-block-size":[{"max-block":["none",...R()]}],w:[{w:[l,"screen",...Y()]}],"min-w":[{"min-w":[l,"screen","none",...Y()]}],"max-w":[{"max-w":[l,"screen","none","prose",{screen:[a]},...Y()]}],h:[{h:["screen","lh",...Y()]}],"min-h":[{"min-h":["screen","lh","none",...Y()]}],"max-h":[{"max-h":["screen","lh",...Y()]}],"font-size":[{text:["base",r,as,Xr]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[n,n1,X0]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Ka,pe]}],"font-family":[{font:[e1,Z0,t]}],"font-features":[{"font-features":[pe]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[s,ve,pe]}],"line-clamp":[{"line-clamp":[Me,"none",ve,Ku]}],leading:[{leading:[i,...C()]}],"list-image":[{"list-image":["none",ve,pe]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",ve,pe]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:O()}],"text-color":[{text:O()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...se(),"wavy"]}],"text-decoration-thickness":[{decoration:[Me,"from-font","auto",ve,Xr]}],"text-decoration-color":[{decoration:O()}],"underline-offset":[{"underline-offset":[Me,"auto",ve,pe]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:C()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",ve,pe]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",ve,pe]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:K()}],"bg-repeat":[{bg:W()}],"bg-size":[{bg:J()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Pr,ve,pe],radial:["",ve,pe],conic:[Pr,ve,pe]},r1,J0]}],"bg-color":[{bg:O()}],"gradient-from-pos":[{from:Q()}],"gradient-via-pos":[{via:Q()}],"gradient-to-pos":[{to:Q()}],"gradient-from":[{from:O()}],"gradient-via":[{via:O()}],"gradient-to":[{to:O()}],rounded:[{rounded:ee()}],"rounded-s":[{"rounded-s":ee()}],"rounded-e":[{"rounded-e":ee()}],"rounded-t":[{"rounded-t":ee()}],"rounded-r":[{"rounded-r":ee()}],"rounded-b":[{"rounded-b":ee()}],"rounded-l":[{"rounded-l":ee()}],"rounded-ss":[{"rounded-ss":ee()}],"rounded-se":[{"rounded-se":ee()}],"rounded-ee":[{"rounded-ee":ee()}],"rounded-es":[{"rounded-es":ee()}],"rounded-tl":[{"rounded-tl":ee()}],"rounded-tr":[{"rounded-tr":ee()}],"rounded-br":[{"rounded-br":ee()}],"rounded-bl":[{"rounded-bl":ee()}],"border-w":[{border:ie()}],"border-w-x":[{"border-x":ie()}],"border-w-y":[{"border-y":ie()}],"border-w-s":[{"border-s":ie()}],"border-w-e":[{"border-e":ie()}],"border-w-bs":[{"border-bs":ie()}],"border-w-be":[{"border-be":ie()}],"border-w-t":[{"border-t":ie()}],"border-w-r":[{"border-r":ie()}],"border-w-b":[{"border-b":ie()}],"border-w-l":[{"border-l":ie()}],"divide-x":[{"divide-x":ie()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":ie()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...se(),"hidden","none"]}],"divide-style":[{divide:[...se(),"hidden","none"]}],"border-color":[{border:O()}],"border-color-x":[{"border-x":O()}],"border-color-y":[{"border-y":O()}],"border-color-s":[{"border-s":O()}],"border-color-e":[{"border-e":O()}],"border-color-bs":[{"border-bs":O()}],"border-color-be":[{"border-be":O()}],"border-color-t":[{"border-t":O()}],"border-color-r":[{"border-r":O()}],"border-color-b":[{"border-b":O()}],"border-color-l":[{"border-l":O()}],"divide-color":[{divide:O()}],"outline-style":[{outline:[...se(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Me,ve,pe]}],"outline-w":[{outline:["",Me,as,Xr]}],"outline-color":[{outline:O()}],shadow:[{shadow:["","none",d,ri,ti]}],"shadow-color":[{shadow:O()}],"inset-shadow":[{"inset-shadow":["none",h,ri,ti]}],"inset-shadow-color":[{"inset-shadow":O()}],"ring-w":[{ring:ie()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:O()}],"ring-offset-w":[{"ring-offset":[Me,Xr]}],"ring-offset-color":[{"ring-offset":O()}],"inset-ring-w":[{"inset-ring":ie()}],"inset-ring-color":[{"inset-ring":O()}],"text-shadow":[{"text-shadow":["none",f,ri,ti]}],"text-shadow-color":[{"text-shadow":O()}],opacity:[{opacity:[Me,ve,pe]}],"mix-blend":[{"mix-blend":[...be(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":be()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Me]}],"mask-image-linear-from-pos":[{"mask-linear-from":ye()}],"mask-image-linear-to-pos":[{"mask-linear-to":ye()}],"mask-image-linear-from-color":[{"mask-linear-from":O()}],"mask-image-linear-to-color":[{"mask-linear-to":O()}],"mask-image-t-from-pos":[{"mask-t-from":ye()}],"mask-image-t-to-pos":[{"mask-t-to":ye()}],"mask-image-t-from-color":[{"mask-t-from":O()}],"mask-image-t-to-color":[{"mask-t-to":O()}],"mask-image-r-from-pos":[{"mask-r-from":ye()}],"mask-image-r-to-pos":[{"mask-r-to":ye()}],"mask-image-r-from-color":[{"mask-r-from":O()}],"mask-image-r-to-color":[{"mask-r-to":O()}],"mask-image-b-from-pos":[{"mask-b-from":ye()}],"mask-image-b-to-pos":[{"mask-b-to":ye()}],"mask-image-b-from-color":[{"mask-b-from":O()}],"mask-image-b-to-color":[{"mask-b-to":O()}],"mask-image-l-from-pos":[{"mask-l-from":ye()}],"mask-image-l-to-pos":[{"mask-l-to":ye()}],"mask-image-l-from-color":[{"mask-l-from":O()}],"mask-image-l-to-color":[{"mask-l-to":O()}],"mask-image-x-from-pos":[{"mask-x-from":ye()}],"mask-image-x-to-pos":[{"mask-x-to":ye()}],"mask-image-x-from-color":[{"mask-x-from":O()}],"mask-image-x-to-color":[{"mask-x-to":O()}],"mask-image-y-from-pos":[{"mask-y-from":ye()}],"mask-image-y-to-pos":[{"mask-y-to":ye()}],"mask-image-y-from-color":[{"mask-y-from":O()}],"mask-image-y-to-color":[{"mask-y-to":O()}],"mask-image-radial":[{"mask-radial":[ve,pe]}],"mask-image-radial-from-pos":[{"mask-radial-from":ye()}],"mask-image-radial-to-pos":[{"mask-radial-to":ye()}],"mask-image-radial-from-color":[{"mask-radial-from":O()}],"mask-image-radial-to-color":[{"mask-radial-to":O()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":k()}],"mask-image-conic-pos":[{"mask-conic":[Me]}],"mask-image-conic-from-pos":[{"mask-conic-from":ye()}],"mask-image-conic-to-pos":[{"mask-conic-to":ye()}],"mask-image-conic-from-color":[{"mask-conic-from":O()}],"mask-image-conic-to-color":[{"mask-conic-to":O()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:K()}],"mask-repeat":[{mask:W()}],"mask-size":[{mask:J()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",ve,pe]}],filter:[{filter:["","none",ve,pe]}],blur:[{blur:ue()}],brightness:[{brightness:[Me,ve,pe]}],contrast:[{contrast:[Me,ve,pe]}],"drop-shadow":[{"drop-shadow":["","none",p,ri,ti]}],"drop-shadow-color":[{"drop-shadow":O()}],grayscale:[{grayscale:["",Me,ve,pe]}],"hue-rotate":[{"hue-rotate":[Me,ve,pe]}],invert:[{invert:["",Me,ve,pe]}],saturate:[{saturate:[Me,ve,pe]}],sepia:[{sepia:["",Me,ve,pe]}],"backdrop-filter":[{"backdrop-filter":["","none",ve,pe]}],"backdrop-blur":[{"backdrop-blur":ue()}],"backdrop-brightness":[{"backdrop-brightness":[Me,ve,pe]}],"backdrop-contrast":[{"backdrop-contrast":[Me,ve,pe]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Me,ve,pe]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Me,ve,pe]}],"backdrop-invert":[{"backdrop-invert":["",Me,ve,pe]}],"backdrop-opacity":[{"backdrop-opacity":[Me,ve,pe]}],"backdrop-saturate":[{"backdrop-saturate":[Me,ve,pe]}],"backdrop-sepia":[{"backdrop-sepia":["",Me,ve,pe]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":C()}],"border-spacing-x":[{"border-spacing-x":C()}],"border-spacing-y":[{"border-spacing-y":C()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",ve,pe]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Me,"initial",ve,pe]}],ease:[{ease:["linear","initial",y,ve,pe]}],delay:[{delay:[Me,ve,pe]}],animate:[{animate:["none",S,ve,pe]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[g,ve,pe]}],"perspective-origin":[{"perspective-origin":T()}],rotate:[{rotate:we()}],"rotate-x":[{"rotate-x":we()}],"rotate-y":[{"rotate-y":we()}],"rotate-z":[{"rotate-z":we()}],scale:[{scale:le()}],"scale-x":[{"scale-x":le()}],"scale-y":[{"scale-y":le()}],"scale-z":[{"scale-z":le()}],"scale-3d":["scale-3d"],skew:[{skew:Z()}],"skew-x":[{"skew-x":Z()}],"skew-y":[{"skew-y":Z()}],transform:[{transform:[ve,pe,"","none","gpu","cpu"]}],"transform-origin":[{origin:T()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:ce()}],"translate-x":[{"translate-x":ce()}],"translate-y":[{"translate-y":ce()}],"translate-z":[{"translate-z":ce()}],"translate-none":["translate-none"],accent:[{accent:O()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:O()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",ve,pe]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":C()}],"scroll-mx":[{"scroll-mx":C()}],"scroll-my":[{"scroll-my":C()}],"scroll-ms":[{"scroll-ms":C()}],"scroll-me":[{"scroll-me":C()}],"scroll-mbs":[{"scroll-mbs":C()}],"scroll-mbe":[{"scroll-mbe":C()}],"scroll-mt":[{"scroll-mt":C()}],"scroll-mr":[{"scroll-mr":C()}],"scroll-mb":[{"scroll-mb":C()}],"scroll-ml":[{"scroll-ml":C()}],"scroll-p":[{"scroll-p":C()}],"scroll-px":[{"scroll-px":C()}],"scroll-py":[{"scroll-py":C()}],"scroll-ps":[{"scroll-ps":C()}],"scroll-pe":[{"scroll-pe":C()}],"scroll-pbs":[{"scroll-pbs":C()}],"scroll-pbe":[{"scroll-pbe":C()}],"scroll-pt":[{"scroll-pt":C()}],"scroll-pr":[{"scroll-pr":C()}],"scroll-pb":[{"scroll-pb":C()}],"scroll-pl":[{"scroll-pl":C()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",ve,pe]}],fill:[{fill:["none",...O()]}],"stroke-w":[{stroke:[Me,as,Xr,Ku]}],stroke:[{stroke:["none",...O()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},a1=$0(i1);function L(...e){return a1(op(e))}var Ep=1e3,wp=60*Ep,al=60*wp,Qu=24*al,o1=30*Ep;function kp(e){if(e==null||e<=0)return null;const t=Date.now()-e;return t<o1?"just now":t<al?`${String(Math.floor(t/wp))}m ago`:t<Qu?`${String(Math.floor(t/al))}h ago`:`${String(Math.floor(t/Qu))}d ago`}var l1=/^(\d{4})-(\d{2})-(\d{2})/,c1=/^(\d{2}):(\d{2})(?::(\d{2}))?$/;function u1(e,t){const r=l1.exec(e);if(r===null)return e;const n=Number(r[1]),s=Number(r[2]),i=Number(r[3]),a=new Date(n,s-1,i);if(Number.isNaN(a.getTime()))return e;try{return a.toLocaleDateString(t)}catch{return e}}function d1(e,t){const r=c1.exec(e);if(r===null)return e;const n=new Date(1970,0,1,Number(r[1]),Number(r[2]),r[3]!==void 0?Number(r[3]):0);if(Number.isNaN(n.getTime()))return e;try{return n.toLocaleTimeString(t,{hour:"2-digit",minute:"2-digit"})}catch{return e}}function h1(e,t){const r=e.includes("T")?e:e.replace(" ","T"),n=new Date(r);if(Number.isNaN(n.getTime()))return e;try{return n.toLocaleString(t,{dateStyle:"medium",timeStyle:"short"})}catch{return e}}function xc(e,t,r){return e===""?e:t==="date"?u1(e,r):t==="time"?d1(e,r):h1(e,r)}function f1(e){if(e==null||typeof e!="object")return null;const t=Reflect.get(e,"data");if(t!=null&&typeof t=="object"){const r=Reflect.get(t,"capRouteReason");if(typeof r=="string")return r}return null}function ta(e){const t=f1(e);return t!==null?t==="no-provider"||t==="node-offline":(e instanceof Error?e.message:String(e)).includes("provider not available")}var EO="rounded-lg border border-border bg-surface overflow-hidden",wO="border-b border-border px-3 sm:px-4 py-1.5 sm:py-2",kO="p-2 sm:p-3 lg:p-4",TO="space-y-3 sm:space-y-4",AO="gap-2 sm:gap-3",CO="px-3 sm:px-4 py-1.5 sm:py-2",NO="grid grid-cols-2 sm:grid-cols-2 lg:grid-cols-4",LO="grid grid-cols-1 lg:grid-cols-2",IO="flex flex-col-reverse md:flex-row",RO="w-full md:w-44 lg:w-52 md:flex-shrink-0 border-b md:border-b-0 md:border-l border-border",MO="text-[10px] sm:text-[11px] font-semibold text-foreground uppercase tracking-wider",PO="text-[11px] sm:text-xs text-foreground",kr="text-[10px] text-foreground-subtle",DO="text-[11px] sm:text-xs font-medium text-foreground",_O="text-base sm:text-lg font-semibold leading-tight text-foreground",OO="inline-flex items-center justify-center gap-1 rounded border border-border bg-surface px-1.5 py-0.5 sm:px-2 sm:py-1 text-[10px] sm:text-[11px] font-medium text-foreground hover:bg-surface-hover transition-colors disabled:opacity-40",FO="inline-flex items-center justify-center gap-1 rounded border border-primary/40 bg-primary/15 px-1.5 py-0.5 sm:px-2 sm:py-1 text-[10px] sm:text-[11px] font-medium text-primary hover:bg-primary/25 transition-colors disabled:opacity-40",$O="inline-flex items-center justify-center gap-1 rounded border border-danger/40 bg-danger/10 px-1.5 py-0.5 sm:px-2 sm:py-1 text-[10px] sm:text-[11px] font-medium text-danger hover:bg-danger/20 transition-colors disabled:opacity-40",BO="inline-flex items-center justify-center gap-1 rounded border border-warning/40 bg-warning/10 px-1.5 py-0.5 sm:px-2 sm:py-1 text-[10px] sm:text-[11px] font-medium text-warning hover:bg-warning/20 transition-colors disabled:opacity-40",UO="w-full rounded border border-border bg-background px-1.5 py-0.5 sm:px-2 sm:py-1 text-[11px] sm:text-xs text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none",GO="inline-flex items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-medium transition-colors",HO="border-primary/50 bg-primary/15 text-primary",VO="border-border bg-surface text-foreground-subtle hover:bg-surface-hover";function p1(e,t){for(const r of e.slots)for(const n of r.addons)if(n.id===t)return n;return null}function m1(e,t){return e.models.find(r=>r.id===t)??null}function g1(e,t){return e.models.find(r=>!!r.formats[t])??null}function v1(e,t){const r=new Set((t.configSchema??[]).map(s=>s.key)),n={};for(const[s,i]of Object.entries(e))r.has(s)&&(n[s]=i);return n}function jO(e){const{source:t,target:r,catalog:n,addonIds:s}=e,i=[];for(const a of s){const l=t.defaults[a];if(!l){i.push({addonId:a,outcome:"skip",modelId:null,reason:"no source entry",patch:null});continue}const o=p1(n,a);if(!o){i.push({addonId:a,outcome:"skip",modelId:null,reason:"addon not in target catalog",patch:null});continue}const c=m1(o,l.modelId),d=c!==null&&!!c.formats[r.engine.format];let h,f;if(d)h=l.modelId,f="exact";else{const m=g1(o,r.engine.format);if(!m){i.push({addonId:a,outcome:"skip",modelId:null,reason:"no compatible model for target format",patch:null});continue}h=m.id,f="mapped"}const p={enabled:l.enabled,modelId:h,settings:v1(l.settings,o)};i.push({addonId:a,outcome:f,modelId:h,patch:p})}return i}var qu={idle:{label:"Idle",textColor:"text-foreground-subtle",badgeClass:"border-border bg-surface-hover text-foreground-subtle",dotClass:"bg-gray-400",icon:"PowerOff"},active:{label:"Active",textColor:"text-success",badgeClass:"border-success/40 bg-success/10 text-success",dotClass:"bg-red-500 animate-pulse",icon:"Activity"},watching:{label:"Watching",textColor:"text-foreground-subtle",badgeClass:"border-border bg-surface-hover text-foreground-subtle",dotClass:"bg-emerald-500",icon:"Eye"},"load-shed":{label:"Load-Shed",textColor:"text-amber-500",badgeClass:"border-amber-500/40 bg-amber-500/10 text-amber-500",dotClass:"bg-amber-500",icon:"AlertTriangle"},paused:{label:"Paused",textColor:"text-gray-400",badgeClass:"border-gray-500/40 bg-gray-500/10 text-gray-400",dotClass:"bg-gray-400",icon:"PauseCircle"}};function Tp(e){return qu[e]??qu.watching}function Nr(e,t){if(typeof globalThis>"u")return hr(t);const r=globalThis.__camstackSharedContexts,n=r??new Map;r||(globalThis.__camstackSharedContexts=n);const s=n.get(e);if(s)return s;const i=hr(t);return n.set(e,i),i}var b1="FEDERATION_DEBUG",ol=(function(e){return e[e.UNKNOWN=1]="UNKNOWN",e[e.CALCULATED=2]="CALCULATED",e[e.NO_USE=0]="NO_USE",e})({}),Ap=!0;function y1(){return Ap}function x1(){try{if(y1()&&window.localStorage)return!!localStorage.getItem(b1)}catch{return!1}return!1}function ll(){return typeof process<"u"&&ja&&ja.FEDERATION_DEBUG?!!ja.FEDERATION_DEBUG:typeof FEDERATION_DEBUG<"u"&&FEDERATION_DEBUG?!0:x1()}var S1="[ Federation Runtime ]",Cp=function(...e){return e.length?e.reduce((t,r)=>r?t?`${t}:${r}`:r:t,""):""},cl=(e,t)=>{if("getPublicPath"in e){let r;return e.getPublicPath.startsWith("function")?r=new Function("return "+e.getPublicPath)()():r=new Function(e.getPublicPath)(),`${r}${t}`}else return"publicPath"in e?`${e.publicPath}${t}`:(console.warn("Cannot get resource URL. If in debug mode, please ignore.",e,t),"")},Np=e=>{console.warn(`${S1}: ${e}`)};function Lp(e){try{return JSON.stringify(e,null,2)}catch{return""}}var za=(e,t)=>{if(!e)return t;const n=(s=>{if(s===".")return"";if(s.startsWith("./"))return s.replace("./","");if(s.startsWith("/")){const i=s.slice(1);return i.endsWith("/")?i.slice(0,-1):i}return s})(e);return n?n.endsWith("/")?`${n}${t}`:`${n}/${t}`:t};function E1(e){return e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/")}function w1(e,t={}){const{remotes:r={},overrides:n={},version:s}=t;let i;const a=()=>"publicPath"in e.metaData?(e.metaData.publicPath==="auto"||e.metaData.publicPath==="")&&s?E1(s):e.metaData.publicPath:e.metaData.getPublicPath,l=Object.keys(n);let o={};Object.keys(r).length||(o=e.remotes?.reduce((S,E)=>{let k;const T=E.federationContainerName;return l.includes(T)?k=n[T]:"version"in E?k=E.version:k=E.entry,S[T]={matchedVersion:k},S},{})||{}),Object.keys(r).forEach(S=>o[S]={matchedVersion:l.includes(S)?n[S]:r[S]});const{remoteEntry:{path:c,name:d,type:h},types:f={path:"",name:"",zip:"",api:""},buildInfo:{buildVersion:p},globalName:m,ssrRemoteEntry:g}=e.metaData,{exposes:b}=e;let y={version:s||"",buildVersion:p,globalName:m,remoteEntry:za(c,d),remoteEntryType:h,remoteTypes:za(f.path,f.name),remoteTypesZip:f.zip||"",remoteTypesAPI:f.api||"",remotesInfo:o,shared:e?.shared.map(S=>({assets:S.assets,sharedName:S.name,version:S.version,usedExports:S.referenceExports||[]})),modules:b?.map(S=>({moduleName:S.name,modulePath:S.path,assets:S.assets}))};if("publicPath"in e.metaData?(i={...y,publicPath:a()},typeof e.metaData.ssrPublicPath=="string"&&(i.ssrPublicPath=e.metaData.ssrPublicPath)):i={...y,getPublicPath:a()},g){const S=za(g.path,g.name);i.ssrRemoteEntry=S,i.ssrRemoteEntryType=g.type||"commonjs-module"}return i}function Ip(e){return!!("remoteEntry"in e&&e.remoteEntry.includes(".json"))}var k1="[ Module Federation ]",os=console,T1=["logger.ts","logger.js","captureStackTrace","Logger.emit","Logger.log","Logger.info","Logger.warn","Logger.error","Logger.debug"];function A1(){try{const e=new Error().stack;if(!e)return;const[,...t]=e.split(`
31
+ `),r=t.filter(n=>!T1.some(s=>n.includes(s)));return r.length?`Stack trace:
32
+ ${r.slice(0,5).join(`
33
+ `)}`:void 0}catch{return}}var Rp=class{constructor(e,t=os){this.prefix=e,this.delegate=t??os}setPrefix(e){this.prefix=e}setDelegate(e){this.delegate=e??os}emit(e,t){const r=this.delegate,n=ll()?A1():void 0,s=n?[...t,n]:t,i=(()=>{switch(e){case"log":return["log","info"];case"info":return["info","log"];case"warn":return["warn","info","log"];case"error":return["error","warn","log"];default:return["debug","log"]}})();for(const a of i){const l=r[a];if(typeof l=="function"){l.call(r,this.prefix,...s);return}}for(const a of i){const l=os[a];if(typeof l=="function"){l.call(os,this.prefix,...s);return}}}log(...e){this.emit("log",e)}warn(...e){this.emit("warn",e)}error(...e){this.emit("error",e)}success(...e){this.emit("info",e)}info(...e){this.emit("info",e)}ready(...e){this.emit("info",e)}debug(...e){ll()&&this.emit("debug",e)}};function C1(e){return new Rp(e)}function N1(e){const t=new Rp(e);return Object.defineProperty(t,"__mf_infrastructure_logger__",{value:!0,enumerable:!1,configurable:!1}),t}N1(k1);async function Mp(e,t){try{return await e()}catch(r){Np(r);return}}function ul(e,t){const r=/^(https?:)?\/\//i;return e.replace(r,"").replace(/\/$/,"")===t.replace(r,"").replace(/\/$/,"")}function Pp(e){let t=null,r=!0,n=2e4,s;const i=document.getElementsByTagName("script");for(let c=0;c<i.length;c++){const d=i[c],h=d.getAttribute("src");if(h&&ul(h,e.url)){t=d,r=!1;break}}if(!t){const c=e.attrs;t=document.createElement("script"),t.type=c?.type==="module"?"module":"text/javascript";let d;e.createScriptHook&&(d=e.createScriptHook(e.url,e.attrs),d instanceof HTMLScriptElement?t=d:typeof d=="object"&&("script"in d&&d.script&&(t=d.script),"timeout"in d&&d.timeout&&(n=d.timeout))),t.src||(t.src=e.url),c&&!d&&Object.keys(c).forEach(h=>{t&&(h==="async"||h==="defer"?t[h]=c[h]:t.getAttribute(h)||t.setAttribute(h,c[h]))})}let a=null;const l=typeof window<"u"?c=>{if(c.filename&&ul(c.filename,e.url)){const d=new Error(`ScriptExecutionError: Script "${e.url}" loaded but threw a runtime error during execution: ${c.message} (${c.filename}:${c.lineno}:${c.colno})`);d.name="ScriptExecutionError",a=d}}:null;l&&window.addEventListener("error",l);const o=async(c,d)=>{clearTimeout(s),l&&window.removeEventListener("error",l);const h=()=>{if(d?.type==="error"){const f=new Error(d?.isTimeout?`ScriptNetworkError: Script "${e.url}" timed out.`:`ScriptNetworkError: Failed to load script "${e.url}" - the script URL is unreachable or the server returned an error (network failure, 404, CORS, etc.)`);f.name="ScriptNetworkError",e?.onErrorCallback&&e?.onErrorCallback(f)}else a?e?.onErrorCallback&&e?.onErrorCallback(a):e?.cb&&e?.cb()};if(t&&(t.onerror=null,t.onload=null,Mp(()=>{const{needDeleteScript:f=!0}=e;f&&t?.parentNode&&t.parentNode.removeChild(t)}),c&&typeof c=="function")){const f=c(d);if(f instanceof Promise){const p=await f;return h(),p}return h(),f}h()};return t.onerror=o.bind(null,t.onerror),t.onload=o.bind(null,t.onload),s=setTimeout(()=>{o(null,{type:"error",isTimeout:!0})},n),{script:t,needAttach:r}}function Wa(e){let t=null,r=!0;const n=document.getElementsByTagName("link");for(let i=0;i<n.length;i++){const a=n[i],l=a.getAttribute("href"),o=a.getAttribute("rel");if(l&&ul(l,e.url)&&o===e.attrs.rel){t=a,r=!1;break}}if(!t){t=document.createElement("link"),t.setAttribute("href",e.url);let i;const a=e.attrs;e.createLinkHook&&(i=e.createLinkHook(e.url,a),i instanceof HTMLLinkElement&&(t=i)),a&&!i&&Object.keys(a).forEach(l=>{t&&!t.getAttribute(l)&&t.setAttribute(l,a[l])})}const s=(i,a)=>{const l=()=>{a?.type==="error"?e?.onErrorCallback&&e?.onErrorCallback(a):e?.cb&&e?.cb()};if(t&&(t.onerror=null,t.onload=null,Mp(()=>{const{needDeleteLink:o=!0}=e;o&&t?.parentNode&&t.parentNode.removeChild(t)}),i)){const o=i(a);return l(),o}l()};return t.onerror=s.bind(null,t.onerror),t.onload=s.bind(null,t.onload),{link:t,needAttach:r}}function L1(e,t){const{attrs:r={},createScriptHook:n}=t;return new Promise((s,i)=>{const{script:a,needAttach:l}=Pp({url:e,cb:s,onErrorCallback:i,attrs:{fetchpriority:"high",...r},createScriptHook:n,needDeleteScript:!0});l&&document.head.appendChild(a)})}var I1=e=>`View the docs to see how to solve: https://module-federation.io/guide/troubleshooting/${e.split("-")[0].toLowerCase()}#${e.toLowerCase()}`,Dp=(e,t,r,n)=>{const s=[`${[t[e]]} #${e}`];return r&&s.push(`args: ${JSON.stringify(r)}`),s.push(I1(e)),n&&s.push(`Original Error Message:
34
+ ${n}`),s.join(`
35
+ `)};function R1(e,t,r,n,s,i){return n(Dp(e,t,r,s))}var on="[ Federation Runtime ]",dl=C1(on);function $t(e,t,r,n,s){e||(r!==void 0?it(t,r,n,void 0):it(t))}function it(e,t,r,n,s){if(t!==void 0)return R1(e,t,r??{},a=>{throw new Error(`${on}: ${a}`)},n);const i=e;throw i instanceof Error?(i.message.startsWith(on)||(i.message=`${on}: ${i.message}`),i):new Error(`${on}: ${i}`)}function Sc(e){e instanceof Error&&(e.message.startsWith(on)||(e.message=`${on}: ${e.message}`)),dl.warn(e)}function M1(e,t){return e.findIndex(r=>r===t)===-1&&e.push(t),e}function Rs(e){return"version"in e&&e.version?`${e.name}:${e.version}`:"entry"in e&&e.entry?`${e.name}:${e.entry}`:`${e.name}`}function Ec(e){return typeof e.entry<"u"}function _p(e){return!e.entry.includes(".json")}function wc(e){return e&&typeof e=="object"}var P1=Object.prototype.toString;function D1(e){return P1.call(e)==="[object Object]"}function Op(e){return Array.isArray(e)?e:[e]}function Fp(e){const t={url:"",type:"global",globalName:""};return"remoteEntry"in e?{url:e.remoteEntry,type:e.remoteEntryType,globalName:e.globalName}:t}var _1=(e,t)=>{let r;return e.endsWith("/")?r=e.slice(0,-1):r=e,t.startsWith(".")&&(t=t.slice(1)),r=r+t,r},ht=typeof globalThis=="object"?globalThis:window,er=(()=>{try{return document.defaultView}catch{return ht}})(),Ms=er;function Mi(e,t,r){Object.defineProperty(e,t,{value:r,configurable:!1,writable:!0})}function Pi(e,t){return Object.hasOwnProperty.call(e,t)}Pi(ht,"__GLOBAL_LOADING_REMOTE_ENTRY__")||Mi(ht,"__GLOBAL_LOADING_REMOTE_ENTRY__",{});var Dn=ht.__GLOBAL_LOADING_REMOTE_ENTRY__;function $p(e){Pi(e,"__VMOK__")&&!Pi(e,"__FEDERATION__")&&Mi(e,"__FEDERATION__",e.__VMOK__),Pi(e,"__FEDERATION__")||(Mi(e,"__FEDERATION__",{__GLOBAL_PLUGIN__:[],__INSTANCES__:[],moduleInfo:{},__SHARE__:{},__MANIFEST_LOADING__:{},__PRELOADED_MAP__:new Map}),Mi(e,"__VMOK__",e.__FEDERATION__)),e.__FEDERATION__.__GLOBAL_PLUGIN__??=[],e.__FEDERATION__.__INSTANCES__??=[],e.__FEDERATION__.moduleInfo??={},e.__FEDERATION__.__SHARE__??={},e.__FEDERATION__.__MANIFEST_LOADING__??={},e.__FEDERATION__.__PRELOADED_MAP__??=new Map}$p(ht);$p(er);function O1(e){ht.__FEDERATION__.__INSTANCES__.push(e)}function F1(){return ht.__FEDERATION__.__DEBUG_CONSTRUCTOR__}function $1(e,t=ll()){t&&(ht.__FEDERATION__.__DEBUG_CONSTRUCTOR__=e,ht.__FEDERATION__.__DEBUG_CONSTRUCTOR_VERSION__="2.4.0")}function Qn(e,t){if(typeof t=="string"){if(e[t])return{value:e[t],key:t};{const r=Object.keys(e);for(const n of r){const[s,i]=n.split(":"),a=`${s}:${t}`,l=e[a];if(l)return{value:l,key:a}}return{value:void 0,key:t}}}else it(`getInfoWithoutType: "key" must be a string, got ${typeof t} (${JSON.stringify(t)}).`)}var Yu=()=>er.__FEDERATION__.moduleInfo,B1=(e,t)=>{const r=Qn(t,Rs(e)).value;if(r&&!r.version&&"version"in e&&e.version&&(r.version=e.version),r)return r;if("version"in e&&e.version){const{version:n,...s}=e,i=Rs(s),a=Qn(er.__FEDERATION__.moduleInfo,i).value;if(a?.version===n)return a}},Di=e=>B1(e,er.__FEDERATION__.moduleInfo),Xu=(e,t)=>{const r=Rs(e);return er.__FEDERATION__.moduleInfo[r]=t,er.__FEDERATION__.moduleInfo},U1=e=>(er.__FEDERATION__.moduleInfo={...er.__FEDERATION__.moduleInfo,...e},()=>{const t=Object.keys(e);for(const r of t)delete er.__FEDERATION__.moduleInfo[r]}),Bp=(e,t)=>{const r=t||`__FEDERATION_${e}:custom__`;return{remoteEntryKey:r,entryExports:ht[r]}},G1=()=>er.__FEDERATION__.__GLOBAL_PLUGIN__,H1=e=>ht.__FEDERATION__.__PRELOADED_MAP__.get(e),V1=e=>ht.__FEDERATION__.__PRELOADED_MAP__.set(e,!0),Zu="[0-9A-Za-z-]+",kc=`(?:\\+(${Zu}(?:\\.${Zu})*))`,ys="0|[1-9]\\d*",_i="[0-9]+",Up="\\d*[a-zA-Z-][a-zA-Z0-9-]*",Ju=`(?:${_i}|${Up})`,j1=`(?:-?(${Ju}(?:\\.${Ju})*))`,ed=`(?:${ys}|${Up})`,Gp=`(?:-(${ed}(?:\\.${ed})*))`,Qa=`${ys}|x|X|\\*`,qn=`[v=\\s]*(${Qa})(?:\\.(${Qa})(?:\\.(${Qa})(?:${Gp})?${kc}?)?)?`,K1=`^\\s*(${qn})\\s+-\\s+(${qn})\\s*$`,z1=`[v=\\s]*${`(${_i})\\.(${_i})\\.(${_i})`}${j1}?${kc}?`,Tc="((?:<|>)?=?)",W1=`(\\s*)${Tc}\\s*(${z1}|${qn})`,Hp="(?:~>?)",Q1=`(\\s*)${Hp}\\s+`,Vp="(?:\\^)",q1=`(\\s*)${Vp}\\s+`,Y1="(<|>)?=?\\s*\\*",X1=`^${Vp}${qn}$`,Z1=`v?${`(${ys})\\.(${ys})\\.(${ys})`}${Gp}?${kc}?`,J1=`^${Hp}${qn}$`,ex=`^${Tc}\\s*${qn}$`,tx=`^${Tc}\\s*(${Z1})$|^$`,rx="^\\s*>=\\s*0.0.0\\s*$";function mr(e){return new RegExp(e)}function Nt(e){return!e||e.toLowerCase()==="x"||e==="*"}function jp(...e){return t=>e.reduce((r,n)=>n(r),t)}function td(e){return e.match(mr(tx))}function rd(e,t,r,n){const s=`${e}.${t}.${r}`;return n?`${s}-${n}`:s}function nx(e){return e.replace(mr(K1),(t,r,n,s,i,a,l,o,c,d,h,f)=>(Nt(n)?r="":Nt(s)?r=`>=${n}.0.0`:Nt(i)?r=`>=${n}.${s}.0`:r=`>=${r}`,Nt(c)?o="":Nt(d)?o=`<${Number(c)+1}.0.0-0`:Nt(h)?o=`<${c}.${Number(d)+1}.0-0`:f?o=`<=${c}.${d}.${h}-${f}`:o=`<=${o}`,`${r} ${o}`.trim()))}function sx(e){return e.replace(mr(W1),"$1$2$3")}function ix(e){return e.replace(mr(Q1),"$1~")}function ax(e){return e.replace(mr(q1),"$1^")}function ox(e){return e.trim().split(/\s+/).map(t=>t.replace(mr(X1),(r,n,s,i,a)=>Nt(n)?"":Nt(s)?`>=${n}.0.0 <${Number(n)+1}.0.0-0`:Nt(i)?n==="0"?`>=${n}.${s}.0 <${n}.${Number(s)+1}.0-0`:`>=${n}.${s}.0 <${Number(n)+1}.0.0-0`:a?n==="0"?s==="0"?`>=${n}.${s}.${i}-${a} <${n}.${s}.${Number(i)+1}-0`:`>=${n}.${s}.${i}-${a} <${n}.${Number(s)+1}.0-0`:`>=${n}.${s}.${i}-${a} <${Number(n)+1}.0.0-0`:n==="0"?s==="0"?`>=${n}.${s}.${i} <${n}.${s}.${Number(i)+1}-0`:`>=${n}.${s}.${i} <${n}.${Number(s)+1}.0-0`:`>=${n}.${s}.${i} <${Number(n)+1}.0.0-0`)).join(" ")}function lx(e){return e.trim().split(/\s+/).map(t=>t.replace(mr(J1),(r,n,s,i,a)=>Nt(n)?"":Nt(s)?`>=${n}.0.0 <${Number(n)+1}.0.0-0`:Nt(i)?`>=${n}.${s}.0 <${n}.${Number(s)+1}.0-0`:a?`>=${n}.${s}.${i}-${a} <${n}.${Number(s)+1}.0-0`:`>=${n}.${s}.${i} <${n}.${Number(s)+1}.0-0`)).join(" ")}function cx(e){return e.split(/\s+/).map(t=>t.trim().replace(mr(ex),(r,n,s,i,a,l)=>{const o=Nt(s),c=o||Nt(i),d=c||Nt(a);return n==="="&&d&&(n=""),l="",o?n===">"||n==="<"?"<0.0.0-0":"*":n&&d?(c&&(i=0),a=0,n===">"?(n=">=",c?(s=Number(s)+1,i=0,a=0):(i=Number(i)+1,a=0)):n==="<="&&(n="<",c?s=Number(s)+1:i=Number(i)+1),n==="<"&&(l="-0"),`${n+s}.${i}.${a}${l}`):c?`>=${s}.0.0${l} <${Number(s)+1}.0.0-0`:d?`>=${s}.${i}.0${l} <${s}.${Number(i)+1}.0-0`:r})).join(" ")}function ux(e){return e.trim().replace(mr(Y1),"")}function dx(e){return e.trim().replace(mr(rx),"")}function Oi(e,t){return e=Number(e)||e,t=Number(t)||t,e>t?1:e===t?0:-1}function hx(e,t){const{preRelease:r}=e,{preRelease:n}=t;if(r===void 0&&n)return 1;if(r&&n===void 0)return-1;if(r===void 0&&n===void 0)return 0;for(let s=0,i=r.length;s<=i;s++){const a=r[s],l=n[s];if(a!==l)return a===void 0&&l===void 0?0:a?l?Oi(a,l):-1:1}return 0}function ni(e,t){return Oi(e.major,t.major)||Oi(e.minor,t.minor)||Oi(e.patch,t.patch)||hx(e,t)}function qa(e,t){return e.version===t.version}function fx(e,t){switch(e.operator){case"":case"=":return qa(e,t);case">":return ni(e,t)<0;case">=":return qa(e,t)||ni(e,t)<0;case"<":return ni(e,t)>0;case"<=":return qa(e,t)||ni(e,t)>0;case void 0:return!0;default:return!1}}function px(e){return jp(ox,lx,cx,ux)(e)}function mx(e){return jp(nx,sx,ix,ax)(e.trim()).split(/\s+/).join(" ")}function fs(e,t){if(!e)return!1;const r=td(e);if(!r)return!1;const[,n,,s,i,a,l]=r,o={operator:n,version:rd(s,i,a,l),major:s,minor:i,patch:a,preRelease:l?.split(".")},c=t.split("||");for(const d of c){const h=d.trim();if(!h||h==="*"||h==="x")return!0;try{const f=mx(h);if(!f.trim())return!0;const p=f.split(" ").map(b=>px(b)).join(" ");if(!p.trim())return!0;const m=p.split(/\s+/).map(b=>dx(b)).filter(Boolean);if(m.length===0)continue;let g=!0;for(const b of m){const y=td(b);if(!y){g=!1;break}const[,S,,E,k,T,A]=y;if(!fx({operator:S,version:rd(E,k,T,A),major:E,minor:k,patch:T,preRelease:A?.split(".")},o)){g=!1;break}}if(g)return!0}catch(f){console.error(`[semver] Error processing range part "${h}":`,f);continue}}return!1}var Aa="default",gx="global";function vx(e,t,r,n){let s;return"get"in e?s=e.get:"lib"in e?s=()=>Promise.resolve(e.lib):s=()=>Promise.resolve(()=>{it(`Cannot get shared "${r}" from "${t}": neither "get" nor "lib" is provided in the share config.`)}),e.shareConfig?.eager&&e.treeShaking?.mode&&it(`Invalid shared config for "${r}" from "${t}": cannot use both "eager: true" and "treeShaking.mode" simultaneously. Choose one strategy.`),{deps:[],useIn:[],from:t,loading:null,...e,shareConfig:{requiredVersion:`^${e.version}`,singleton:!1,eager:!1,strictVersion:!1,...e.shareConfig},get:s,loaded:e?.loaded||"lib"in e?!0:void 0,version:e.version??"0",scope:Array.isArray(e.scope)?e.scope:[e.scope??"default"],strategy:(e.strategy??n)||"version-first",treeShaking:e.treeShaking?{...e.treeShaking,mode:e.treeShaking.mode??"server-calc",status:e.treeShaking.status??ol.UNKNOWN,useIn:[]}:void 0}}function Kp(e,t){const r=t.shared||{},n=t.name,s=Object.keys(r).reduce((a,l)=>{const o=Op(r[l]);return a[l]=a[l]||[],o.forEach(c=>{a[l].push(vx(c,n,l,t.shareStrategy))}),a},{}),i={...e.shared};return Object.keys(s).forEach(a=>{i[a]?s[a].forEach(l=>{i[a].find(o=>o.version===l.version)||i[a].push(l)}):i[a]=s[a]}),{allShareInfos:i,newShareInfos:s}}function Ps(e,t){if(!e)return!1;const{status:r,mode:n}=e;return r===ol.NO_USE?!1:r===ol.CALCULATED?!0:n==="runtime-infer"?t?yx(e,t):!0:!1}function ln(e,t){const r=n=>{if(!Number.isNaN(Number(n))){const s=n.split(".");let i=n;for(let a=0;a<3-s.length;a++)i+=".0";return i}return n};return!!fs(r(e),`<=${r(t)}`)}var Ds=(e,t)=>{const r=t||function(n,s){return ln(n,s)};return Object.keys(e).reduce((n,s)=>!n||r(n,s)||n==="0"?s:n,0)},ra=e=>!!e.loaded||typeof e.lib=="function",bx=e=>!!e.loading,yx=(e,t)=>{if(!e||!t)return!1;const{usedExports:r}=e;return r?!!t.every(n=>r.includes(n)):!1};function xx(e,t,r,n){const s=e[t][r];let i="",a=Ps(n);const l=function(o,c){return a?s[o].treeShaking?s[c].treeShaking?!ra(s[o].treeShaking)&&ln(o,c):!1:!0:!ra(s[o])&&ln(o,c)};if(a){if(i=Ds(e[t][r],l),i)return{version:i,useTreesShaking:a};a=!1}return{version:Ds(e[t][r],l),useTreesShaking:a}}var xn=e=>ra(e)||bx(e);function Sx(e,t,r,n){const s=e[t][r];let i="",a=Ps(n);const l=function(o,c){if(a){if(!s[o].treeShaking)return!0;if(!s[c].treeShaking)return!1;if(xn(s[c].treeShaking))return xn(s[o].treeShaking)?!!ln(o,c):!0;if(xn(s[o].treeShaking))return!1}return xn(s[c])?xn(s[o])?!!ln(o,c):!0:xn(s[o])?!1:ln(o,c)};if(a){if(i=Ds(e[t][r],l),i)return{version:i,useTreesShaking:a};a=!1}return{version:Ds(e[t][r],l),useTreesShaking:a}}function Ex(e){return e==="loaded-first"?Sx:xx}function Fi(e,t,r,n){if(!e)return;const{shareConfig:s,scope:i=Aa,strategy:a,treeShaking:l}=r,o=Array.isArray(i)?i:[i];for(const c of o)if(s&&e[c]&&e[c][t]){const{requiredVersion:d}=s,{version:h,useTreesShaking:f}=Ex(a)(e,c,t,l),p=()=>{const g=e[c][t][h];if(s.singleton){if(typeof d=="string"&&!fs(h,d)){const b=`Version ${h} from ${h&&g.from} of shared singleton module ${t} does not satisfy the requirement of ${r.from} which needs ${d})`;s.strictVersion?it(b):Sc(b)}return{shared:g,useTreesShaking:f}}else{if(d===!1||d==="*")return{shared:g,useTreesShaking:f};if(fs(h,d))return{shared:g,useTreesShaking:f};const b=Ps(l);if(b){for(const[y,S]of Object.entries(e[c][t]))if(Ps(S.treeShaking,l?.usedExports)&&fs(y,d))return{shared:S,useTreesShaking:b}}for(const[y,S]of Object.entries(e[c][t]))if(fs(y,d))return{shared:S,useTreesShaking:!1}}},m={shareScopeMap:e,scope:c,pkgName:t,version:h,GlobalFederation:Ms.__FEDERATION__,shareInfo:r,resolver:p};return(n.emit(m)||m).resolver()}}function zp(){return Ms.__FEDERATION__.__SHARE__}function nd(e){const{pkgName:t,extraOptions:r,shareInfos:n}=e,s=o=>{if(!o)return;const c={};return o.forEach(h=>{c[h.version]=h}),c[Ds(c,function(h,f){return!ra(c[h])&&ln(h,f)})]},i=r?.resolver??s,a=o=>o!==null&&typeof o=="object"&&!Array.isArray(o),l=(...o)=>{const c={};for(const d of o)if(d)for(const[h,f]of Object.entries(d)){const p=c[h];a(p)&&a(f)?c[h]=l(p,f):f!==void 0&&(c[h]=f)}return c};return l(i(n[t]),r?.customShareInfo)}var Sn=(e,t)=>{e.useIn||(e.useIn=[]),M1(e.useIn,t)};function si(e,t){return t&&e.treeShaking?e.treeShaking:e}function wx(e,t){for(const r of e){const n=t.startsWith(r.name);let s=t.replace(r.name,"");if(n){if(s.startsWith("/")){const l=r.name;return s=`.${s}`,{pkgNameOrAlias:l,expose:s,remote:r}}else if(s==="")return{pkgNameOrAlias:r.name,expose:".",remote:r}}const i=r.alias&&t.startsWith(r.alias);let a=r.alias&&t.replace(r.alias,"");if(r.alias&&i){if(a&&a.startsWith("/")){const l=r.alias;return a=`.${a}`,{pkgNameOrAlias:l,expose:a,remote:r}}else if(a==="")return{pkgNameOrAlias:r.alias,expose:".",remote:r}}}}function kx(e,t){for(const r of e)if(t===r.name||r.alias&&t===r.alias)return r}var Wp="RUNTIME-001",Qp="RUNTIME-002",qp="RUNTIME-003",Yp="RUNTIME-004",Xp="RUNTIME-005",hl="RUNTIME-006",Zp="RUNTIME-007",Jp="RUNTIME-008",Ac="RUNTIME-009",em="RUNTIME-010",tm="RUNTIME-011",Tx="RUNTIME-012",Ut={[Wp]:"Failed to get remoteEntry exports.",[Qp]:'The remote entry interface does not contain "init"',[qp]:"Failed to get manifest.",[Yp]:"Failed to locate remote.",[Xp]:"Invalid loadShareSync function call from bundler runtime",[hl]:"Invalid loadShareSync function call from runtime",[Zp]:"Failed to get remote snapshot.",[Jp]:"Failed to load script resources.",[Ac]:"Please call createInstance first.",[em]:'The name option cannot be changed after initialization. If you want to create a new instance with a different name, please use "createInstance" api.',[tm]:"The remoteEntry URL is missing from the remote snapshot.",[Tx]:'The getter for the shared module is not a function. This may be caused by setting "shared.import: false" without the host providing the corresponding lib.'};({...Ut});var rm=".then(callbacks[0]).catch(callbacks[1])";async function Ax({entry:e,remoteEntryExports:t}){return new Promise((r,n)=>{try{t?r(t):typeof FEDERATION_ALLOW_NEW_FUNCTION<"u"?new Function("callbacks",`import("${e}")${rm}`)([r,n]):import(e).then(r).catch(n)}catch(s){it(`Failed to load ESM entry from "${e}". ${s instanceof Error?s.message:String(s)}`)}})}async function Cx({entry:e,remoteEntryExports:t}){return new Promise((r,n)=>{try{t?r(t):typeof __system_context__>"u"?System.import(e).then(r).catch(n):new Function("callbacks",`System.import("${e}")${rm}`)([r,n])}catch(s){it(`Failed to load SystemJS entry from "${e}". ${s instanceof Error?s.message:String(s)}`)}})}function Nx(e,t,r){const{remoteEntryKey:n,entryExports:s}=Bp(e,t);return s||it(Wp,Ut,{remoteName:e,remoteEntryUrl:r,remoteEntryKey:n}),s}async function Lx({name:e,globalName:t,entry:r,remoteInfo:n,loaderHook:s,getEntryUrl:i}){const{entryExports:a}=Bp(e,t);if(a)return a;const l=i?i(r):r;return L1(l,{attrs:{},createScriptHook:(o,c)=>{const d=s.lifecycle.createScript.emit({url:o,attrs:c,remoteInfo:n});if(d&&(d instanceof HTMLScriptElement||"script"in d||"timeout"in d))return d}}).then(()=>Nx(e,t,r),o=>{const c=o instanceof Error?o.message:String(o);it(Jp,Ut,{remoteName:e,resourceUrl:l},c)})}async function Ix({remoteInfo:e,remoteEntryExports:t,loaderHook:r,getEntryUrl:n}){const{entry:s,entryGlobalName:i,name:a,type:l}=e;switch(l){case"esm":case"module":return Ax({entry:s,remoteEntryExports:t});case"system":return Cx({entry:s,remoteEntryExports:t});default:return Lx({entry:s,globalName:i,name:a,remoteInfo:e,loaderHook:r,getEntryUrl:n})}}function fl(e){const{entry:t,name:r}=e;return Cp(r,t)}async function na(e){const{origin:t,remoteEntryExports:r,remoteInfo:n,getEntryUrl:s,_inErrorHandling:i=!1}=e,a=fl(n);if(r)return r;if(!Dn[a]){const l=t.remoteHandler.hooks.lifecycle.loadEntry,o=t.loaderHook;Dn[a]=l.emit({loaderHook:o,remoteInfo:n,remoteEntryExports:r}).then(c=>c||Ix({remoteInfo:n,remoteEntryExports:r,loaderHook:o,getEntryUrl:s})).catch(async c=>{const d=fl(n),h=c instanceof Error&&c.message.includes("ScriptExecutionError");if(c instanceof Error&&c.message.includes("RUNTIME-008")&&!h&&!i){const f=m=>na({...m,_inErrorHandling:!0}),p=await t.loaderHook.lifecycle.loadEntryError.emit({getRemoteEntry:f,origin:t,remoteInfo:n,remoteEntryExports:r,globalLoading:Dn,uniqueKey:d});if(p)return p}throw c})}return Dn[a]}function sa(e){return{...e,entry:"entry"in e?e.entry:"",type:e.type||"global",entryGlobalName:e.entryGlobalName||e.name,shareScope:e.shareScope||"default"}}function Rx(){return typeof FEDERATION_BUILD_IDENTIFIER<"u"?FEDERATION_BUILD_IDENTIFIER:""}function Mx(e,t){const r=G1(),n=[t.hooks,t.remoteHandler.hooks,t.sharedHandler.hooks,t.snapshotHandler.hooks,t.loaderHook,t.bridgeHook];return r.length>0&&r.forEach(s=>{e?.find(i=>i.name!==s.name)&&e.push(s)}),e&&e.length>0&&e.forEach(s=>{n.forEach(i=>{i.applyPlugin(s,t)})}),e}function Px(e){return{name:e.name,alias:e.alias,entry:"entry"in e?e.entry:void 0,version:"version"in e?e.version:void 0,type:e.type,entryGlobalName:e.entryGlobalName,shareScope:e.shareScope}}function Yn(e){const t={};for(const[r,n]of Object.entries(e.shared)){const s=n[0];s&&(t[r]={version:s.version,singleton:s.shareConfig?.singleton,requiredVersion:s.shareConfig?.requiredVersion===!1?!1:s.shareConfig?.requiredVersion,eager:s.eager,strictVersion:s.shareConfig?.strictVersion})}return{project:{name:e.name,mfRole:e.remotes?.length>0?"host":"unknown"},mfConfig:{name:e.name,remotes:e.remotes?.map(Px)??[],shared:t}}}function nm(e){return{resourceCategory:"sync",share:!0,depsRemote:!0,...e}}function Dx(e,t){return t.map(r=>{const n=kx(e,r.nameOrAlias);return $t(n,`Unable to preload ${r.nameOrAlias} as it is not included in ${!n&&Lp({remoteInfo:n,remotes:e})}`),{remote:n,preloadConfig:nm(r)}})}function _x(e){return e?e.map(t=>t==="."?t:t.startsWith("./")?t.replace("./",""):t):[]}function sm(e,t,r,n=!0){const{cssAssets:s,jsAssetsWithoutEntry:i,entryAssets:a}=r;if(t.options.inBrowser){if(a.forEach(l=>{const{moduleInfo:o}=l,c=t.moduleCache.get(e.name);na(c?{origin:t,remoteInfo:o,remoteEntryExports:c.remoteEntryExports}:{origin:t,remoteInfo:o,remoteEntryExports:void 0})}),n){const l={rel:"preload",as:"style"};s.forEach(o=>{const{link:c,needAttach:d}=Wa({url:o,cb:()=>{},attrs:l,createLinkHook:(h,f)=>{const p=t.loaderHook.lifecycle.createLink.emit({url:h,attrs:f,remoteInfo:e});if(p instanceof HTMLLinkElement)return p}});d&&document.head.appendChild(c)})}else{const l={rel:"stylesheet",type:"text/css"};s.forEach(o=>{const{link:c,needAttach:d}=Wa({url:o,cb:()=>{},attrs:l,createLinkHook:(h,f)=>{const p=t.loaderHook.lifecycle.createLink.emit({url:h,attrs:f,remoteInfo:e});if(p instanceof HTMLLinkElement)return p},needDeleteLink:!1});d&&document.head.appendChild(c)})}if(n){const l={rel:"preload",as:"script"};i.forEach(o=>{const{link:c,needAttach:d}=Wa({url:o,cb:()=>{},attrs:l,createLinkHook:(h,f)=>{const p=t.loaderHook.lifecycle.createLink.emit({url:h,attrs:f,remoteInfo:e});if(p instanceof HTMLLinkElement)return p}});d&&document.head.appendChild(c)})}else{const l={fetchpriority:"high",type:e?.type==="module"?"module":"text/javascript"};i.forEach(o=>{const{script:c,needAttach:d}=Pp({url:o,cb:()=>{},attrs:l,createScriptHook:(h,f)=>{const p=t.loaderHook.lifecycle.createScript.emit({url:h,attrs:f,remoteInfo:e});if(p instanceof HTMLScriptElement)return p},needDeleteScript:!0});d&&document.head.appendChild(c)})}}}function Ox(e,t,r){const n=t,s=Array.isArray(e.shareScope)?e.shareScope:[e.shareScope];s.length||s.push("default"),s.forEach(a=>{n[a]||(n[a]={})});const i={version:e.version||"",shareScopeKeys:Array.isArray(e.shareScope)?s:e.shareScope||"default"};return Object.defineProperty(i,"shareScopeMap",{value:n,enumerable:!1}),{remoteEntryInitOptions:i,shareScope:n[s[0]],initScope:r??[]}}var im=class{constructor({remoteInfo:e,host:t}){this.inited=!1,this.initing=!1,this.lib=void 0,this.remoteInfo=e,this.host=t}async getEntry(){if(this.remoteEntryExports)return this.remoteEntryExports;const e=await na({origin:this.host,remoteInfo:this.remoteInfo,remoteEntryExports:this.remoteEntryExports});return $t(e,`remoteEntryExports is undefined
36
+ ${Lp(this.remoteInfo)}`),this.remoteEntryExports=e,this.remoteEntryExports}async init(e,t,r){const n=await this.getEntry();if(this.inited)return n;if(this.initPromise)return await this.initPromise,n;this.initing=!0,this.initPromise=(async()=>{const{remoteEntryInitOptions:s,shareScope:i,initScope:a}=Ox(this.remoteInfo,this.host.shareScopeMap,r),l=await this.host.hooks.lifecycle.beforeInitContainer.emit({shareScope:i,remoteEntryInitOptions:s,initScope:a,remoteInfo:this.remoteInfo,origin:this.host});typeof n?.init>"u"&&it(Qp,Ut,{hostName:this.host.name,remoteName:this.remoteInfo.name,remoteEntryUrl:this.remoteInfo.entry,remoteEntryKey:this.remoteInfo.entryGlobalName},void 0,Yn(this.host.options)),await n.init(l.shareScope,l.initScope,l.remoteEntryInitOptions),await this.host.hooks.lifecycle.initContainer.emit({...l,id:e,remoteSnapshot:t,remoteEntryExports:n}),this.inited=!0})();try{await this.initPromise}finally{this.initing=!1,this.initPromise=void 0}return n}async get(e,t,r,n){const{loadFactory:s=!0}=r||{loadFactory:!0},i=await this.init(e,n);this.lib=i;let a;a=await this.host.loaderHook.lifecycle.getModuleFactory.emit({remoteEntryExports:i,expose:t,moduleInfo:this.remoteInfo}),a||(a=await i.get(t)),$t(a,`${Rs(this.remoteInfo)} remote don't export ${t}.`);const l=_1(this.remoteInfo.name,t),o=this.wraperFactory(a,l);return s?await o():o}wraperFactory(e,t){function r(n,s){n&&typeof n=="object"&&Object.isExtensible(n)&&!Object.getOwnPropertyDescriptor(n,Symbol.for("mf_module_id"))&&Object.defineProperty(n,Symbol.for("mf_module_id"),{value:s,enumerable:!1})}return e instanceof Promise?async()=>{const n=await e();return r(n,t),n}:()=>{const n=e();return r(n,t),n}}},jt=class{constructor(e){this.type="",this.listeners=new Set,e&&(this.type=e)}on(e){typeof e=="function"&&this.listeners.add(e)}once(e){const t=this;this.on(function r(...n){return t.remove(r),e.apply(null,n)})}emit(...e){let t;return this.listeners.size>0&&this.listeners.forEach(r=>{t=r(...e)}),t}remove(e){this.listeners.delete(e)}removeAll(){this.listeners.clear()}},Zt=class extends jt{emit(...e){let t;const r=Array.from(this.listeners);if(r.length>0){let n=0;const s=i=>i===!1?!1:n<r.length?Promise.resolve(r[n++].apply(null,e)).then(s):i;t=s()}return Promise.resolve(t)}};function am(e,t){if(!wc(t))return!1;if(e!==t){for(const r in e)if(!(r in t))return!1}return!0}var Bn=class extends jt{constructor(e){super(),this.onerror=it,this.type=e}emit(e){wc(e)||it(`The data for the "${this.type}" hook should be an object.`);for(const t of this.listeners)try{const r=t(e);if(am(e,r))e=r;else{this.onerror(`A plugin returned an unacceptable value for the "${this.type}" type.`);break}}catch(r){Sc(r),this.onerror(r)}return e}},Ur=class extends jt{constructor(e){super(),this.onerror=it,this.type=e}emit(e){wc(e)||it(`The response data for the "${this.type}" hook must be an object.`);const t=Array.from(this.listeners);if(t.length>0){let r=0;const n=i=>(Sc(i),this.onerror(i),e),s=i=>{if(am(e,i)){if(e=i,r<t.length)try{return Promise.resolve(t[r++](e)).then(s,n)}catch(a){return n(a)}}else this.onerror(`A plugin returned an incorrect value for the "${this.type}" type.`);return e};return Promise.resolve(s(e))}return Promise.resolve(e)}},Un=class{constructor(e){this.registerPlugins={},this.lifecycle=e,this.lifecycleKeys=Object.keys(e)}applyPlugin(e,t){$t(D1(e),"Plugin configuration is invalid.");const r=e.name;$t(r,"A name must be provided by the plugin."),this.registerPlugins[r]||(this.registerPlugins[r]=e,e.apply?.(t),Object.keys(this.lifecycle).forEach(n=>{const s=e[n];s&&this.lifecycle[n].on(s)}))}removePlugin(e){$t(e,"A name is required.");const t=this.registerPlugins[e];$t(t,`The plugin "${e}" is not registered.`),Object.keys(t).forEach(r=>{r!=="name"&&this.lifecycle[r].remove(t[r])})}};function om(e,t){const r=Fp(t);r.url||it(tm,Ut,{remoteName:e.name});let n=cl(t,r.url);e.type=r.type,e.entryGlobalName=r.globalName,e.entry=n,e.version=t.version,e.buildVersion=t.buildVersion}function Fx(){return{name:"snapshot-plugin",async afterResolve(e){const{remote:t,pkgNameOrAlias:r,expose:n,origin:s,remoteInfo:i,id:a}=e;if(!Ec(t)||!_p(t)){const{remoteSnapshot:l,globalSnapshot:o}=await s.snapshotHandler.loadRemoteSnapshotInfo({moduleInfo:t,id:a});om(i,l);const c={remote:t,preloadConfig:{nameOrAlias:r,exposes:[n],resourceCategory:"sync",share:!1,depsRemote:!1}},d=await s.remoteHandler.hooks.lifecycle.generatePreloadAssets.emit({origin:s,preloadOptions:c,remoteInfo:i,remote:t,remoteSnapshot:l,globalSnapshot:o});return d&&sm(i,s,d,!1),{...e,remoteSnapshot:l}}return e}}}function $x(e){const t=e.split(":");return t.length===1?{name:t[0],version:void 0}:t.length===2?{name:t[0],version:t[1]}:{name:t[1],version:t[2]}}function lm(e,t,r,n,s={},i){const{value:a}=Qn(e,Rs(t)),l=i||a;if(l&&!Ip(l)&&(r(l,t,n),l.remotesInfo)){const o=Object.keys(l.remotesInfo);for(const c of o){if(s[c])continue;s[c]=!0;const d=$x(c),h=l.remotesInfo[c];lm(e,{name:d.name,version:h.matchedVersion},r,!1,s,void 0)}}}var Ya=(e,t)=>document.querySelector(`${e}[${e==="link"?"href":"src"}="${t}"]`);function Bx(e,t,r,n,s){const i=[],a=[],l=[],o=new Set,c=new Set,{options:d}=e,{preloadConfig:h}=t,{depsRemote:f}=h;if(lm(n,r,(m,g,b)=>{let y;if(b)y=h;else if(Array.isArray(f)){const A=f.find(N=>N.nameOrAlias===g.name||N.nameOrAlias===g.alias);if(!A)return;y=nm(A)}else if(f===!0)y=h;else return;const S=cl(m,Fp(m).url);S&&l.push({name:g.name,moduleInfo:{name:g.name,entry:S,type:"remoteEntryType"in m?m.remoteEntryType:"global",entryGlobalName:"globalName"in m?m.globalName:g.name,shareScope:"",version:"version"in m?m.version:void 0},url:S});let E="modules"in m?m.modules:[];const k=_x(y.exposes);k.length&&"modules"in m&&(E=m?.modules?.reduce((A,N)=>(k?.indexOf(N.moduleName)!==-1&&A.push(N),A),[]));function T(A){const N=A.map(C=>cl(m,C));return y.filter?N.filter(y.filter):N}if(E){const A=E.length;for(let N=0;N<A;N++){const C=E[N],M=`${g.name}/${C.moduleName}`;e.remoteHandler.hooks.lifecycle.handlePreloadModule.emit({id:C.moduleName==="."?g.name:M,name:g.name,remoteSnapshot:m,preloadConfig:y,remote:g,origin:e}),!H1(M)&&(y.resourceCategory==="all"?(i.push(...T(C.assets.css.async)),i.push(...T(C.assets.css.sync)),a.push(...T(C.assets.js.async)),a.push(...T(C.assets.js.sync))):y.resourceCategory==="sync"&&(i.push(...T(C.assets.css.sync)),a.push(...T(C.assets.js.sync))),V1(M))}}},!0,{},s),s.shared&&s.shared.length>0){const m=(g,b)=>{const{shared:y}=Fi(e.shareScopeMap,b.sharedName,g,e.sharedHandler.hooks.lifecycle.resolveShare)||{};y&&typeof y.lib=="function"&&(b.assets.js.sync.forEach(S=>{o.add(S)}),b.assets.css.sync.forEach(S=>{c.add(S)}))};s.shared.forEach(g=>{const b=d.shared?.[g.sharedName];if(!b)return;const y=g.version?b.find(S=>S.version===g.version):b;y&&Op(y).forEach(S=>{m(S,g)})})}const p=a.filter(m=>!o.has(m)&&!Ya("script",m));return{cssAssets:i.filter(m=>!c.has(m)&&!Ya("link",m)),jsAssetsWithoutEntry:p,entryAssets:l.filter(m=>!Ya("script",m.url))}}var Ux=function(){return{name:"generate-preload-assets-plugin",async generatePreloadAssets(e){const{origin:t,preloadOptions:r,remoteInfo:n,remote:s,globalSnapshot:i,remoteSnapshot:a}=e;return Ec(s)&&_p(s)?{cssAssets:[],jsAssetsWithoutEntry:[],entryAssets:[{name:s.name,url:s.entry,moduleInfo:{name:n.name,entry:s.entry,type:n.type||"global",entryGlobalName:"",shareScope:""}}]}:(om(n,a),Bx(t,r,n,i,a))}}};function cm(e,t){const r=Di({name:t.name,version:t.options.version}),n=r&&"remotesInfo"in r&&r.remotesInfo&&Qn(r.remotesInfo,e.name).value;return n&&n.matchedVersion?{hostGlobalSnapshot:r,globalSnapshot:Yu(),remoteSnapshot:Di({name:e.name,version:n.matchedVersion})}:{hostGlobalSnapshot:void 0,globalSnapshot:Yu(),remoteSnapshot:Di({name:e.name,version:"version"in e?e.version:void 0})}}var Gx=class{constructor(e){this.loadingHostSnapshot=null,this.manifestCache=new Map,this.hooks=new Un({beforeLoadRemoteSnapshot:new Zt("beforeLoadRemoteSnapshot"),loadSnapshot:new Ur("loadGlobalSnapshot"),loadRemoteSnapshot:new Ur("loadRemoteSnapshot"),afterLoadSnapshot:new Ur("afterLoadSnapshot")}),this.manifestLoading=Ms.__FEDERATION__.__MANIFEST_LOADING__,this.HostInstance=e,this.loaderHook=e.loaderHook}async loadRemoteSnapshotInfo({moduleInfo:e,id:t,expose:r}){const{options:n}=this.HostInstance;await this.hooks.lifecycle.beforeLoadRemoteSnapshot.emit({options:n,moduleInfo:e});let s=Di({name:this.HostInstance.options.name,version:this.HostInstance.options.version});s||(s={version:this.HostInstance.options.version||"",remoteEntry:"",remotesInfo:{}},U1({[this.HostInstance.options.name]:s})),s&&"remotesInfo"in s&&!Qn(s.remotesInfo,e.name).value&&("version"in e||"entry"in e)&&(s.remotesInfo={...s?.remotesInfo,[e.name]:{matchedVersion:"version"in e?e.version:e.entry}});const{hostGlobalSnapshot:i,remoteSnapshot:a,globalSnapshot:l}=this.getGlobalRemoteInfo(e),{remoteSnapshot:o,globalSnapshot:c}=await this.hooks.lifecycle.loadSnapshot.emit({options:n,moduleInfo:e,hostGlobalSnapshot:i,remoteSnapshot:a,globalSnapshot:l});let d,h;if(o)if(Ip(o)){const f=o.remoteEntry,p=await this.getManifestJson(f,e,{}),m=Xu({...e,entry:f},p);d=p,h=m}else{const{remoteSnapshot:f}=await this.hooks.lifecycle.loadRemoteSnapshot.emit({options:this.HostInstance.options,moduleInfo:e,remoteSnapshot:o,from:"global"});d=f,h=c}else if(Ec(e)){const f=await this.getManifestJson(e.entry,e,{}),p=Xu(e,f),{remoteSnapshot:m}=await this.hooks.lifecycle.loadRemoteSnapshot.emit({options:this.HostInstance.options,moduleInfo:e,remoteSnapshot:f,from:"global"});d=m,h=p}else it(Zp,Ut,{remoteName:e.name,remoteVersion:e.version,hostName:this.HostInstance.options.name,globalSnapshot:JSON.stringify(c)},void 0,Yn(this.HostInstance.options));return await this.hooks.lifecycle.afterLoadSnapshot.emit({id:t,host:this.HostInstance,options:n,moduleInfo:e,remoteSnapshot:d}),{remoteSnapshot:d,globalSnapshot:h}}getGlobalRemoteInfo(e){return cm(e,this.HostInstance)}async getManifestJson(e,t,r){const n=async()=>{let i=this.manifestCache.get(e);if(i)return i;try{let a=await this.loaderHook.lifecycle.fetch.emit(e,{},sa(t));(!a||!(a instanceof Response))&&(a=await fetch(e,{})),i=await a.json()}catch(a){i=await this.HostInstance.remoteHandler.hooks.lifecycle.errorLoadRemote.emit({id:e,error:a,from:"runtime",lifecycle:"afterResolve",origin:this.HostInstance}),i||(delete this.manifestLoading[e],it(qp,Ut,{manifestUrl:e,moduleName:t.name,hostName:this.HostInstance.options.name},`${a}`,Yn(this.HostInstance.options)))}return $t(i.metaData&&i.exposes&&i.shared,`"${e}" is not a valid federation manifest for remote "${t.name}". Missing required fields: ${[!i.metaData&&"metaData",!i.exposes&&"exposes",!i.shared&&"shared"].filter(Boolean).join(", ")}.`),this.manifestCache.set(e,i),i},s=async()=>{const i=await n(),a=w1(i,{version:e}),{remoteSnapshot:l}=await this.hooks.lifecycle.loadRemoteSnapshot.emit({options:this.HostInstance.options,moduleInfo:t,manifestJson:i,remoteSnapshot:a,manifestUrl:e,from:"manifest"});return l};return this.manifestLoading[e]||(this.manifestLoading[e]=s().then(i=>i)),this.manifestLoading[e]}},Hx=class{constructor(e){this.hooks=new Un({beforeRegisterShare:new Bn("beforeRegisterShare"),afterResolve:new Ur("afterResolve"),beforeLoadShare:new Ur("beforeLoadShare"),loadShare:new Zt,resolveShare:new Bn("resolveShare"),initContainerShareScopeMap:new Bn("initContainerShareScopeMap")}),this.host=e,this.shareScopeMap={},this.initTokens={},this._setGlobalShareScopeMap(e.options)}registerShared(e,t){const{newShareInfos:r,allShareInfos:n}=Kp(e,t);return Object.keys(r).forEach(s=>{r[s].forEach(i=>{i.scope.forEach(a=>{this.hooks.lifecycle.beforeRegisterShare.emit({origin:this.host,pkgName:s,shared:i}),this.shareScopeMap[a]?.[s]||this.setShared({pkgName:s,lib:i.lib,get:i.get,loaded:i.loaded||!!i.lib,shared:i,from:t.name})})})}),{newShareInfos:r,allShareInfos:n}}async loadShare(e,t){const{host:r}=this,n=nd({pkgName:e,extraOptions:t,shareInfos:r.options.shared});n?.scope&&await Promise.all(n.scope.map(async l=>{await Promise.all(this.initializeSharing(l,{strategy:n.strategy}))}));const{shareInfo:s}=await this.hooks.lifecycle.beforeLoadShare.emit({pkgName:e,shareInfo:n,shared:r.options.shared,origin:r});$t(s,`Cannot find shared "${e}" in host "${r.options.name}". Ensure the shared config for "${e}" is declared in the federation plugin options and the host has been initialized before loading shares.`);const{shared:i,useTreesShaking:a}=Fi(this.shareScopeMap,e,s,this.hooks.lifecycle.resolveShare)||{};if(i){const l=si(i,a);if(l.lib)return Sn(l,r.options.name),l.lib;if(l.loading&&!l.loaded){const o=await l.loading;return l.loaded=!0,l.lib||(l.lib=o),Sn(l,r.options.name),o}else{const c=(async()=>{const d=await l.get();return Sn(l,r.options.name),l.loaded=!0,l.lib=d,d})();return this.setShared({pkgName:e,loaded:!1,shared:i,from:r.options.name,lib:null,loading:c,treeShaking:a?l:void 0}),c}}else{if(t?.customShareInfo)return!1;const l=Ps(s.treeShaking),o=si(s,l),d=(async()=>{const h=await o.get();o.lib=h,o.loaded=!0,Sn(o,r.options.name);const{shared:f,useTreesShaking:p}=Fi(this.shareScopeMap,e,s,this.hooks.lifecycle.resolveShare)||{};if(f){const m=si(f,p);m.lib=h,m.loaded=!0,f.from=s.from}return h})();return this.setShared({pkgName:e,loaded:!1,shared:s,from:r.options.name,lib:null,loading:d,treeShaking:l?o:void 0}),d}}initializeSharing(e=Aa,t){const{host:r}=this,n=t?.from,s=t?.strategy;let i=t?.initScope;const a=[];if(n!=="build"){const{initTokens:f}=this;i||(i=[]);let p=f[e];if(p||(p=f[e]={from:this.host.name}),i.indexOf(p)>=0)return a;i.push(p)}const l=this.shareScopeMap,o=r.options.name;l[e]||(l[e]={});const c=l[e],d=(f,p)=>{const{version:m,eager:g}=p;c[f]=c[f]||{};const b=c[f],y=b[m]&&si(b[m]),S=!!(y&&("eager"in y&&y.eager||"shareConfig"in y&&y.shareConfig?.eager));(!y||y.strategy!=="loaded-first"&&!y.loaded&&(!g!=!S?g:o>b[m].from))&&(b[m]=p)},h=async f=>{const{module:p}=await r.remoteHandler.getRemoteModuleAndOptions({id:f});let m;try{m=await p.getEntry()}catch(g){if(m=await r.remoteHandler.hooks.lifecycle.errorLoadRemote.emit({id:f,error:g,from:"runtime",lifecycle:"beforeLoadShare",origin:r}),!m)return}finally{m?.init&&!p.initing&&(p.remoteEntryExports=m,await p.init(void 0,void 0,i))}};return Object.keys(r.options.shared).forEach(f=>{r.options.shared[f].forEach(p=>{p.scope.includes(e)&&d(f,p)})}),(r.options.shareStrategy==="version-first"||s==="version-first")&&r.options.remotes.forEach(f=>{f.shareScope===e&&a.push(h(f.name))}),a}loadShareSync(e,t){const{host:r}=this,n=nd({pkgName:e,extraOptions:t,shareInfos:r.options.shared});n?.scope&&n.scope.forEach(a=>{this.initializeSharing(a,{strategy:n.strategy})});const{shared:s,useTreesShaking:i}=Fi(this.shareScopeMap,e,n,this.hooks.lifecycle.resolveShare)||{};if(s){if(typeof s.lib=="function")return Sn(s,r.options.name),s.loaded||(s.loaded=!0,s.from===r.options.name&&(n.loaded=!0)),s.lib;if(typeof s.get=="function"){const a=s.get();if(!(a instanceof Promise))return Sn(s,r.options.name),this.setShared({pkgName:e,loaded:!0,from:r.options.name,lib:a,shared:s}),a}}if(n.lib)return n.loaded||(n.loaded=!0),n.lib;if(n.get){const a=n.get();return a instanceof Promise&&it(t?.from==="build"?Xp:hl,Ut,{hostName:r.options.name,sharedPkgName:e},void 0,Yn(r.options)),n.lib=a,this.setShared({pkgName:e,loaded:!0,from:r.options.name,lib:n.lib,shared:n}),n.lib}it(hl,Ut,{hostName:r.options.name,sharedPkgName:e},void 0,Yn(r.options))}initShareScopeMap(e,t,r={}){const{host:n}=this;this.shareScopeMap[e]=t,this.hooks.lifecycle.initContainerShareScopeMap.emit({shareScope:t,options:n.options,origin:n,scopeName:e,hostShareScopeMap:r.hostShareScopeMap})}setShared({pkgName:e,shared:t,from:r,lib:n,loading:s,loaded:i,get:a,treeShaking:l}){const{version:o,scope:c="default",...d}=t,h=Array.isArray(c)?c:[c],f=p=>{const m=(b,y,S)=>{S&&!b[y]&&(b[y]=S)},g=l?p.treeShaking:p;m(g,"loaded",i),m(g,"loading",s),m(g,"get",a)};h.forEach(p=>{this.shareScopeMap[p]||(this.shareScopeMap[p]={}),this.shareScopeMap[p][e]||(this.shareScopeMap[p][e]={}),this.shareScopeMap[p][e][o]||(this.shareScopeMap[p][e][o]={version:o,scope:[p],...d,lib:n});const m=this.shareScopeMap[p][e][o];f(m),r&&m.from!==r&&(m.from=r)})}_setGlobalShareScopeMap(e){const t=zp(),r=e.id||e.name;r&&!t[r]&&(t[r]=this.shareScopeMap)}},Vx=class{constructor(e){this.hooks=new Un({beforeRegisterRemote:new Bn("beforeRegisterRemote"),registerRemote:new Bn("registerRemote"),beforeRequest:new Ur("beforeRequest"),onLoad:new Zt("onLoad"),handlePreloadModule:new jt("handlePreloadModule"),errorLoadRemote:new Zt("errorLoadRemote"),beforePreloadRemote:new Zt("beforePreloadRemote"),generatePreloadAssets:new Zt("generatePreloadAssets"),afterPreloadRemote:new Zt,loadEntry:new Zt}),this.host=e,this.idToRemoteMap={}}formatAndRegisterRemote(e,t){return(t.remotes||[]).reduce((r,n)=>(this.registerRemote(n,r,{force:!1}),r),e.remotes)}setIdToRemoteMap(e,t){const{remote:r,expose:n}=t,{name:s,alias:i}=r;if(this.idToRemoteMap[e]={name:r.name,expose:n},i&&e.startsWith(s)){const a=e.replace(s,i);this.idToRemoteMap[a]={name:r.name,expose:n};return}if(i&&e.startsWith(i)){const a=e.replace(i,s);this.idToRemoteMap[a]={name:r.name,expose:n}}}async loadRemote(e,t){const{host:r}=this;try{const{loadFactory:n=!0}=t||{loadFactory:!0},{module:s,moduleOptions:i,remoteMatchInfo:a}=await this.getRemoteModuleAndOptions({id:e}),{pkgNameOrAlias:l,remote:o,expose:c,id:d,remoteSnapshot:h}=a,f=await s.get(d,c,t,h),p=await this.hooks.lifecycle.onLoad.emit({id:d,pkgNameOrAlias:l,expose:c,exposeModule:n?f:void 0,exposeModuleFactory:n?void 0:f,remote:o,options:i,moduleInstance:s,origin:r});return this.setIdToRemoteMap(e,a),typeof p=="function"?p:f}catch(n){const{from:s="runtime"}=t||{from:"runtime"},i=await this.hooks.lifecycle.errorLoadRemote.emit({id:e,error:n,from:s,lifecycle:"onLoad",origin:r});if(!i)throw n;return i}}async preloadRemote(e){const{host:t}=this;await this.hooks.lifecycle.beforePreloadRemote.emit({preloadOps:e,options:t.options,origin:t});const r=Dx(t.options.remotes,e);await Promise.all(r.map(async n=>{const{remote:s}=n,i=sa(s),{globalSnapshot:a,remoteSnapshot:l}=await t.snapshotHandler.loadRemoteSnapshotInfo({moduleInfo:s}),o=await this.hooks.lifecycle.generatePreloadAssets.emit({origin:t,preloadOptions:n,remote:s,remoteInfo:i,globalSnapshot:a,remoteSnapshot:l});o&&sm(i,t,o)}))}registerRemotes(e,t){const{host:r}=this;e.forEach(n=>{this.registerRemote(n,r.options.remotes,{force:t?.force})})}async getRemoteModuleAndOptions(e){const{host:t}=this,{id:r}=e;let n;try{n=await this.hooks.lifecycle.beforeRequest.emit({id:r,options:t.options,origin:t})}catch(p){if(n=await this.hooks.lifecycle.errorLoadRemote.emit({id:r,options:t.options,origin:t,from:"runtime",error:p,lifecycle:"beforeRequest"}),!n)throw p}const{id:s}=n,i=wx(t.options.remotes,s);i||it(Yp,Ut,{hostName:t.options.name,requestId:s},void 0,Yn(t.options));const{remote:a}=i,l=sa(a),o=await t.sharedHandler.hooks.lifecycle.afterResolve.emit({id:s,...i,options:t.options,origin:t,remoteInfo:l}),{remote:c,expose:d}=o;$t(c&&d,`The 'beforeRequest' hook was executed, but it failed to return the correct 'remote' and 'expose' values while loading ${s}.`);let h=t.moduleCache.get(c.name);const f={host:t,remoteInfo:l};return h||(h=new im(f),t.moduleCache.set(c.name,h)),{module:h,moduleOptions:f,remoteMatchInfo:o}}registerRemote(e,t,r){const{host:n}=this,s=()=>{if(e.alias){const a=t.find(l=>e.alias&&(l.name.startsWith(e.alias)||l.alias?.startsWith(e.alias)));$t(!a,`The alias ${e.alias} of remote ${e.name} is not allowed to be the prefix of ${a&&a.name} name or alias`)}"entry"in e&&typeof window<"u"&&!e.entry.startsWith("http")&&(e.entry=new URL(e.entry,window.location.origin).href),e.shareScope||(e.shareScope=Aa),e.type||(e.type=gx)};this.hooks.lifecycle.beforeRegisterRemote.emit({remote:e,origin:n});const i=t.find(a=>a.name===e.name);if(!i)s(),t.push(e),this.hooks.lifecycle.registerRemote.emit({remote:e,origin:n});else{const a=[`The remote "${e.name}" is already registered.`,"Please note that overriding it may cause unexpected errors."];r?.force&&(this.removeRemote(i),s(),t.push(e),this.hooks.lifecycle.registerRemote.emit({remote:e,origin:n}),Np(a.join(" ")))}}removeRemote(e){try{const{host:t}=this,{name:r}=e,n=t.options.remotes.findIndex(i=>i.name===r);n!==-1&&t.options.remotes.splice(n,1);const s=t.moduleCache.get(e.name);if(s){const i=s.remoteInfo,a=i.entryGlobalName;ht[a]&&(Object.getOwnPropertyDescriptor(ht,a)?.configurable?delete ht[a]:ht[a]=void 0);const l=fl(s.remoteInfo);Dn[l]&&delete Dn[l],t.snapshotHandler.manifestCache.delete(i.entry);let o=i.buildVersion?Cp(i.name,i.buildVersion):i.name;const c=ht.__FEDERATION__.__INSTANCES__.findIndex(h=>i.buildVersion?h.options.id===o:h.name===o);if(c!==-1){const h=ht.__FEDERATION__.__INSTANCES__[c];o=h.options.id||o;const f=zp();let p=!0;const m=[];Object.keys(f).forEach(g=>{const b=f[g];b&&Object.keys(b).forEach(y=>{const S=b[y];S&&Object.keys(S).forEach(E=>{const k=S[E];k&&Object.keys(k).forEach(T=>{const A=k[T];A&&typeof A=="object"&&A.from===i.name&&(A.loaded||A.loading?(A.useIn=A.useIn.filter(N=>N!==i.name),A.useIn.length?p=!1:m.push([g,y,E,T])):m.push([g,y,E,T]))})})})}),p&&(h.shareScopeMap={},delete f[o]),m.forEach(([g,b,y,S])=>{delete f[g]?.[b]?.[y]?.[S]}),ht.__FEDERATION__.__INSTANCES__.splice(c,1)}const{hostGlobalSnapshot:d}=cm(e,t);if(d){const h=d&&"remotesInfo"in d&&d.remotesInfo&&Qn(d.remotesInfo,e.name).key;h&&(delete d.remotesInfo[h],Ms.__FEDERATION__.__MANIFEST_LOADING__[h]&&delete Ms.__FEDERATION__.__MANIFEST_LOADING__[h])}t.moduleCache.delete(e.name)}}catch(t){dl.error(`removeRemote failed: ${t instanceof Error?t.message:String(t)}`)}}},jx=typeof FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN=="boolean"?!FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN:!0,um=class{constructor(e){this.hooks=new Un({beforeInit:new Bn("beforeInit"),init:new jt,beforeInitContainer:new Ur("beforeInitContainer"),initContainer:new Ur("initContainer")}),this.version="2.4.0",this.moduleCache=new Map,this.loaderHook=new Un({getModuleInfo:new jt,createScript:new jt,createLink:new jt,fetch:new Zt,loadEntryError:new Zt,getModuleFactory:new Zt}),this.bridgeHook=new Un({beforeBridgeRender:new jt,afterBridgeRender:new jt,beforeBridgeDestroy:new jt,afterBridgeDestroy:new jt});const t=jx?[Fx(),Ux()]:[],r={id:Rx(),name:e.name,plugins:t,remotes:[],shared:{},inBrowser:Ap};this.name=e.name,this.options=r,this.snapshotHandler=new Gx(this),this.sharedHandler=new Hx(this),this.remoteHandler=new Vx(this),this.shareScopeMap=this.sharedHandler.shareScopeMap,this.registerPlugins([...r.plugins,...e.plugins||[]]),this.options=this.formatOptions(r,e)}initOptions(e){e.name&&e.name!==this.options.name&&it(Dp(em,Ut)),this.registerPlugins(e.plugins);const t=this.formatOptions(this.options,e);return this.options=t,t}async loadShare(e,t){return this.sharedHandler.loadShare(e,t)}loadShareSync(e,t){return this.sharedHandler.loadShareSync(e,t)}initializeSharing(e=Aa,t){return this.sharedHandler.initializeSharing(e,t)}initRawContainer(e,t,r){const n=sa({name:e,entry:t}),s=new im({host:this,remoteInfo:n});return s.remoteEntryExports=r,this.moduleCache.set(e,s),s}async loadRemote(e,t){return this.remoteHandler.loadRemote(e,t)}async preloadRemote(e){return this.remoteHandler.preloadRemote(e)}initShareScopeMap(e,t,r={}){this.sharedHandler.initShareScopeMap(e,t,r)}formatOptions(e,t){const{allShareInfos:r}=Kp(e,t),{userOptions:n,options:s}=this.hooks.lifecycle.beforeInit.emit({origin:this,userOptions:t,options:e,shareInfo:r}),i=this.remoteHandler.formatAndRegisterRemote(s,n),{allShareInfos:a}=this.sharedHandler.registerShared(s,n),l=[...s.plugins];n.plugins&&n.plugins.forEach(c=>{l.includes(c)||l.push(c)});const o={...e,...t,plugins:l,remotes:i,shared:a,id:n.id||e.id};return this.hooks.lifecycle.init.emit({origin:this,options:o}),o}registerPlugins(e){const t=Mx(e,this);this.options.plugins=this.options.plugins.reduce((r,n)=>(n&&r&&!r.find(s=>s.name===n.name)&&r.push(n),r),t||[])}registerRemotes(e,t){return this.remoteHandler.registerRemotes(e,t)}registerShared(e){this.sharedHandler.registerShared(this.options,{...this.options,shared:e})}};function Kx(){return typeof FEDERATION_BUILD_IDENTIFIER<"u"?FEDERATION_BUILD_IDENTIFIER:""}function zx(e,t){const r=Kx();return ht.__FEDERATION__.__INSTANCES__.find(n=>!!(r&&n.options.id===r||n.options.name===e&&!n.options.version&&!t||n.options.name===e&&t&&n.options.version===t))}function Wx(e){const t=new(F1()||um)({id:`${e.name}@${e.version||Date.now()}`,...e});return O1(t),t}var Jt=null;function Qx(e){const t=zx(e.name,e.version),r={...e,id:e.id||""};return t?(t.initOptions(r),Jt||(Jt=t),t):(Jt=Wx(r),Jt)}function qx(...e){return $t(Jt,Ac,Ut),Jt.loadRemote.apply(Jt,e)}function Yx(...e){return $t(Jt,Ac,Ut),Jt.registerRemotes.apply(Jt,e)}function Xx(){return Jt}$1(um);function Gn(e){const t=(typeof globalThis<"u"?globalThis:void 0)?.[e];return t&&typeof t=="object"?t:{}}var Zx={singleton:!0,requiredVersion:!1,eager:!0},Vt=e=>({version:"0.0.0",scope:"default",lib:e,shareConfig:Zx}),sd="__mf_module_cache__";function Jx(){const e=globalThis,t=e[sd];if(t&&typeof t=="object"){const n=t;return n.share??={},n.remote??={},n}const r={share:{},remote:{}};return e[sd]=r,r}function eS(){const e=Jx();e.share.react??=Hf,e.share["react-dom"]??=jf,e.share["react-dom/client"]??=Kf,e.share["react/jsx-runtime"]??=Vf,e.share["@tanstack/react-query"]??=zf,e.share["@trpc/client"]??=qf,e.share["@trpc/react-query"]??=Yf,e.share["react-konva"]??=Xf,e.share.konva??=ep,e.share["@camstack/ui-library"]??=Gn("__camstackUiLibrary"),e.share["@camstack/sdk"]??=Gn("__camstackSdk"),e.share["@camstack/types"]??=Gn("__camstackTypes")}function tS(){eS(),Xx()===null&&Qx({name:"admin_ui_host",remotes:[],shared:{react:Vt(()=>Hf),"react-dom":Vt(()=>jf),"react-dom/client":Vt(()=>Kf),"react/jsx-runtime":Vt(()=>Vf),"@tanstack/react-query":Vt(()=>zf),"@trpc/client":Vt(()=>qf),"@trpc/react-query":Vt(()=>Yf),"react-konva":Vt(()=>Xf),konva:Vt(()=>ep),"@camstack/ui-library":Vt(()=>Gn("__camstackUiLibrary")),"@camstack/sdk":Vt(()=>Gn("__camstackSdk")),"@camstack/types":Vt(()=>Gn("__camstackTypes"))}})}/**
37
+ * @license lucide-react v0.576.0 - ISC
38
+ *
39
+ * This source code is licensed under the ISC license.
40
+ * See the LICENSE file in the root directory of this source tree.
41
+ */var dm=(...e)=>e.filter((t,r,n)=>!!t&&t.trim()!==""&&n.indexOf(t)===r).join(" ").trim();/**
42
+ * @license lucide-react v0.576.0 - ISC
43
+ *
44
+ * This source code is licensed under the ISC license.
45
+ * See the LICENSE file in the root directory of this source tree.
46
+ */var rS=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
47
+ * @license lucide-react v0.576.0 - ISC
48
+ *
49
+ * This source code is licensed under the ISC license.
50
+ * See the LICENSE file in the root directory of this source tree.
51
+ */var nS=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,r,n)=>n?n.toUpperCase():r.toLowerCase());/**
52
+ * @license lucide-react v0.576.0 - ISC
53
+ *
54
+ * This source code is licensed under the ISC license.
55
+ * See the LICENSE file in the root directory of this source tree.
56
+ */var id=e=>{const t=nS(e);return t.charAt(0).toUpperCase()+t.slice(1)};/**
57
+ * @license lucide-react v0.576.0 - ISC
58
+ *
59
+ * This source code is licensed under the ISC license.
60
+ * See the LICENSE file in the root directory of this source tree.
61
+ */var sS={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
62
+ * @license lucide-react v0.576.0 - ISC
63
+ *
64
+ * This source code is licensed under the ISC license.
65
+ * See the LICENSE file in the root directory of this source tree.
66
+ */var iS=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1};/**
67
+ * @license lucide-react v0.576.0 - ISC
68
+ *
69
+ * This source code is licensed under the ISC license.
70
+ * See the LICENSE file in the root directory of this source tree.
71
+ */var aS=It(({color:e="currentColor",size:t=24,strokeWidth:r=2,absoluteStrokeWidth:n,className:s="",children:i,iconNode:a,...l},o)=>Is("svg",{ref:o,...sS,width:t,height:t,stroke:e,strokeWidth:n?Number(r)*24/Number(t):r,className:dm("lucide",s),...!i&&!iS(l)&&{"aria-hidden":"true"},...l},[...a.map(([c,d])=>Is(c,d)),...Array.isArray(i)?i:[i]]));/**
72
+ * @license lucide-react v0.576.0 - ISC
73
+ *
74
+ * This source code is licensed under the ISC license.
75
+ * See the LICENSE file in the root directory of this source tree.
76
+ */var V=(e,t)=>{const r=It(({className:n,...s},i)=>Is(aS,{ref:i,iconNode:t,className:dm(`lucide-${rS(id(e))}`,`lucide-${e}`,n),...s}));return r.displayName=id(e),r},ur=V("activity",[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]]),oS=V("alarm-smoke",[["path",{d:"M11 21c0-2.5 2-2.5 2-5",key:"1sicvv"}],["path",{d:"M16 21c0-2.5 2-2.5 2-5",key:"1o3eny"}],["path",{d:"m19 8-.8 3a1.25 1.25 0 0 1-1.2 1H7a1.25 1.25 0 0 1-1.2-1L5 8",key:"1bvca4"}],["path",{d:"M21 3a1 1 0 0 1 1 1v2a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V4a1 1 0 0 1 1-1z",key:"x3qr1j"}],["path",{d:"M6 21c0-2.5 2-2.5 2-5",key:"i3w1gp"}]]),ad=V("arrow-down-to-line",[["path",{d:"M12 17V3",key:"1cwfxf"}],["path",{d:"m6 11 6 6 6-6",key:"12ii2o"}],["path",{d:"M19 21H5",key:"150jfl"}]]),lS=V("arrow-down",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]),cS=V("arrow-left",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]),uS=V("arrow-right",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]),dS=V("arrow-up-to-line",[["path",{d:"M5 3h14",key:"7usisc"}],["path",{d:"m18 13-6-6-6 6",key:"1kf1n9"}],["path",{d:"M12 7v14",key:"1akyts"}]]),hS=V("arrow-up",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]),fS=V("bath",[["path",{d:"M10 4 8 6",key:"1rru8s"}],["path",{d:"M17 19v2",key:"ts1sot"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"M7 19v2",key:"12npes"}],["path",{d:"M9 5 7.621 3.621A2.121 2.121 0 0 0 4 5v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5",key:"14ym8i"}]]),hm=V("battery-full",[["path",{d:"M10 10v4",key:"1mb2ec"}],["path",{d:"M14 10v4",key:"1nt88p"}],["path",{d:"M22 14v-4",key:"14q9d5"}],["path",{d:"M6 10v4",key:"1n77qd"}],["rect",{x:"2",y:"6",width:"16",height:"12",rx:"2",key:"13zb55"}]]),pS=V("battery-low",[["path",{d:"M22 14v-4",key:"14q9d5"}],["path",{d:"M6 14v-4",key:"14a6bd"}],["rect",{x:"2",y:"6",width:"16",height:"12",rx:"2",key:"13zb55"}]]),Cc=V("battery-medium",[["path",{d:"M10 14v-4",key:"suye4c"}],["path",{d:"M22 14v-4",key:"14q9d5"}],["path",{d:"M6 14v-4",key:"14a6bd"}],["rect",{x:"2",y:"6",width:"16",height:"12",rx:"2",key:"13zb55"}]]),fm=V("battery-warning",[["path",{d:"M10 17h.01",key:"nbq80n"}],["path",{d:"M10 7v6",key:"nne03l"}],["path",{d:"M14 6h2a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2",key:"1m83kb"}],["path",{d:"M22 14v-4",key:"14q9d5"}],["path",{d:"M6 18H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h2",key:"h8lgfh"}]]),mS=V("battery",[["path",{d:"M 22 14 L 22 10",key:"nqc4tb"}],["rect",{x:"2",y:"6",width:"16",height:"12",rx:"2",key:"13zb55"}]]),gS=V("bell-ring",[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M22 8c0-2.3-.8-4.3-2-6",key:"5bb3ad"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}],["path",{d:"M4 2C2.8 3.7 2 5.7 2 8",key:"tap9e0"}]]),_s=V("bell",[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]]),vS=V("blinds",[["path",{d:"M3 3h18",key:"o7r712"}],["path",{d:"M20 7H8",key:"gd2fo2"}],["path",{d:"M20 11H8",key:"1ynp89"}],["path",{d:"M10 19h10",key:"19hjk5"}],["path",{d:"M8 15h12",key:"1yqzne"}],["path",{d:"M4 3v14",key:"fggqzn"}],["circle",{cx:"4",cy:"19",r:"2",key:"p3m9r0"}]]),bS=V("bot",[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]]),pl=V("box",[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]]),yS=V("bug",[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]]),pm=V("camera",[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z",key:"18u6gg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]),xS=V("cast",[["path",{d:"M2 8V6a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-6",key:"3zrzxg"}],["path",{d:"M2 12a9 9 0 0 1 8 8",key:"g6cvee"}],["path",{d:"M2 16a5 5 0 0 1 4 4",key:"1y1dii"}],["line",{x1:"2",x2:"2.01",y1:"20",y2:"20",key:"xu2jvo"}]]),Lr=V("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]),yt=V("chevron-down",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]),SS=V("chevron-left",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),nr=V("chevron-right",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),dn=V("chevron-up",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]),ES=V("chevrons-down-up",[["path",{d:"m7 20 5-5 5 5",key:"13a0gw"}],["path",{d:"m7 4 5 5 5-5",key:"1kwcof"}]]),wS=V("chevrons-up-down",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]),rs=V("circle-alert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]),kS=V("circle-check-big",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]),TS=V("circle-check",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]),mm=V("circle-dot",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]),AS=V("circle-pause",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"10",x2:"10",y1:"15",y2:"9",key:"c1nkhi"}],["line",{x1:"14",x2:"14",y1:"15",y2:"9",key:"h65svq"}]]),CS=V("circle-plus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]),gm=V("circle-question-mark",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]),NS=V("circle-x",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]),ml=V("clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]]),LS=V("cloud-fog",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"M16 17H7",key:"pygtm1"}],["path",{d:"M17 21H9",key:"1u2q02"}]]),IS=V("cloud-lightning",[["path",{d:"M6 16.326A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 .5 8.973",key:"1cez44"}],["path",{d:"m13 12-3 5h4l-3 5",key:"1t22er"}]]),RS=V("cloud-rain",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"M16 14v6",key:"1j4efv"}],["path",{d:"M8 14v6",key:"17c4r9"}],["path",{d:"M12 16v6",key:"c8a4gj"}]]),od=V("cloud-snow",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"M8 15h.01",key:"a7atzg"}],["path",{d:"M8 19h.01",key:"puxtts"}],["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M12 21h.01",key:"h35vbk"}],["path",{d:"M16 15h.01",key:"rnfrdf"}],["path",{d:"M16 19h.01",key:"1vcnzz"}]]),vm=V("cloud-sun",[["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}],["path",{d:"M15.947 12.65a4 4 0 0 0-5.925-4.128",key:"dpwdj0"}],["path",{d:"M13 22H7a5 5 0 1 1 4.9-6H13a3 3 0 0 1 0 6Z",key:"s09mg5"}]]),MS=V("cloud",[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]]),PS=V("copy-plus",[["line",{x1:"15",x2:"15",y1:"12",y2:"18",key:"1p7wdc"}],["line",{x1:"12",x2:"18",y1:"15",y2:"15",key:"1nscbv"}],["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]),zr=V("copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]),DS=V("cpu",[["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M17 20v2",key:"1rnc9c"}],["path",{d:"M17 2v2",key:"11trls"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M2 17h2",key:"7oei6x"}],["path",{d:"M2 7h2",key:"asdhe0"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"M20 17h2",key:"1fpfkl"}],["path",{d:"M20 7h2",key:"1o8tra"}],["path",{d:"M7 20v2",key:"4gnj0m"}],["path",{d:"M7 2v2",key:"1i4yhu"}],["rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",key:"1vbyd7"}],["rect",{x:"8",y:"8",width:"8",height:"8",rx:"1",key:"z9xiuo"}]]),Nc=V("crosshair",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"22",x2:"18",y1:"12",y2:"12",key:"l9bcsi"}],["line",{x1:"6",x2:"2",y1:"12",y2:"12",key:"13hhkx"}],["line",{x1:"12",x2:"12",y1:"6",y2:"2",key:"10w3f3"}],["line",{x1:"12",x2:"12",y1:"22",y2:"18",key:"15g9kq"}]]),_S=V("database",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]]),OS=V("door-closed",[["path",{d:"M10 12h.01",key:"1kxr2c"}],["path",{d:"M18 20V6a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v14",key:"36qu9e"}],["path",{d:"M2 20h20",key:"owomy5"}]]),Os=V("door-open",[["path",{d:"M11 20H2",key:"nlcfvz"}],["path",{d:"M11 4.562v16.157a1 1 0 0 0 1.242.97L19 20V5.562a2 2 0 0 0-1.515-1.94l-4-1A2 2 0 0 0 11 4.561z",key:"au4z13"}],["path",{d:"M11 4H8a2 2 0 0 0-2 2v14",key:"74r1mk"}],["path",{d:"M14 12h.01",key:"1jfl7z"}],["path",{d:"M22 20h-3",key:"vhrsz"}]]),Fs=V("download",[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]]),bm=V("droplet",[["path",{d:"M12 22a7 7 0 0 0 7-7c0-2-1-3.9-3-5.5s-3.5-4-4-6.5c-.5 2.5-2 4.9-4 6.5C6 11.1 5 13 5 15a7 7 0 0 0 7 7z",key:"c7niix"}]]),Lc=V("droplets",[["path",{d:"M7 16.3c2.2 0 4-1.83 4-4.05 0-1.16-.57-2.26-1.71-3.19S7.29 6.75 7 5.3c-.29 1.45-1.14 2.84-2.29 3.76S3 11.1 3 12.25c0 2.22 1.8 4.05 4 4.05z",key:"1ptgy4"}],["path",{d:"M12.56 6.6A10.97 10.97 0 0 0 14 3.02c.5 2.5 2 4.9 4 6.5s3 3.5 3 5.5a6.98 6.98 0 0 1-11.91 4.97",key:"1sl1rz"}]]),FS=V("ellipsis-vertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]),ym=V("external-link",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]),Ca=V("eye-off",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]),Xs=V("eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),gl=V("fan",[["path",{d:"M10.827 16.379a6.082 6.082 0 0 1-8.618-7.002l5.412 1.45a6.082 6.082 0 0 1 7.002-8.618l-1.45 5.412a6.082 6.082 0 0 1 8.618 7.002l-5.412-1.45a6.082 6.082 0 0 1-7.002 8.618l1.45-5.412Z",key:"484a7f"}],["path",{d:"M12 12v.01",key:"u5ubse"}]]),xm=V("film",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 3v18",key:"bbkbws"}],["path",{d:"M3 7.5h4",key:"zfgn84"}],["path",{d:"M3 12h18",key:"1i2n21"}],["path",{d:"M3 16.5h4",key:"1230mu"}],["path",{d:"M17 3v18",key:"in4fa5"}],["path",{d:"M17 7.5h4",key:"myr1c1"}],["path",{d:"M17 16.5h4",key:"go4c1d"}]]),$S=V("flame",[["path",{d:"M12 3q1 4 4 6.5t3 5.5a1 1 0 0 1-14 0 5 5 0 0 1 1-3 1 1 0 0 0 5 0c0-2-1.5-3-1.5-5q0-2 2.5-4",key:"1slcih"}]]),BS=V("flashlight",[["path",{d:"M12 13v1",key:"176q98"}],["path",{d:"M17 2a1 1 0 0 1 1 1v4a3 3 0 0 1-.6 1.8l-.6.8A4 4 0 0 0 16 12v8a2 2 0 0 1-2 2H10a2 2 0 0 1-2-2v-8a4 4 0 0 0-.8-2.4l-.6-.8A3 3 0 0 1 6 7V3a1 1 0 0 1 1-1z",key:"17vh7j"}],["path",{d:"M6 6h12",key:"n6hhss"}]]),US=V("flask-conical",[["path",{d:"M14 2v6a2 2 0 0 0 .245.96l5.51 10.08A2 2 0 0 1 18 22H6a2 2 0 0 1-1.755-2.96l5.51-10.08A2 2 0 0 0 10 8V2",key:"18mbvz"}],["path",{d:"M6.453 15h11.094",key:"3shlmq"}],["path",{d:"M8.5 2h7",key:"csnxdl"}]]),GS=V("footprints",[["path",{d:"M4 16v-2.38C4 11.5 2.97 10.5 3 8c.03-2.72 1.49-6 4.5-6C9.37 2 10 3.8 10 5.5c0 3.11-2 5.66-2 8.68V16a2 2 0 1 1-4 0Z",key:"1dudjm"}],["path",{d:"M20 20v-2.38c0-2.12 1.03-3.12 1-5.62-.03-2.72-1.49-6-4.5-6C14.63 6 14 7.8 14 9.5c0 3.11 2 5.66 2 8.68V20a2 2 0 1 0 4 0Z",key:"l2t8xc"}],["path",{d:"M16 17h4",key:"1dejxt"}],["path",{d:"M4 13h4",key:"1bwh8b"}]]),Sm=V("funnel",[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]]),HS=V("gamepad-2",[["line",{x1:"6",x2:"10",y1:"11",y2:"11",key:"1gktln"}],["line",{x1:"8",x2:"8",y1:"9",y2:"13",key:"qnk9ow"}],["line",{x1:"15",x2:"15.01",y1:"12",y2:"12",key:"krot7o"}],["line",{x1:"18",x2:"18.01",y1:"10",y2:"10",key:"1lcuu1"}],["path",{d:"M17.32 5H6.68a4 4 0 0 0-3.978 3.59c-.006.052-.01.101-.017.152C2.604 9.416 2 14.456 2 16a3 3 0 0 0 3 3c1 0 1.5-.5 2-1l1.414-1.414A2 2 0 0 1 9.828 16h4.344a2 2 0 0 1 1.414.586L17 18c.5.5 1 1 2 1a3 3 0 0 0 3-3c0-1.545-.604-6.584-.685-7.258-.007-.05-.011-.1-.017-.151A4 4 0 0 0 17.32 5z",key:"mfqc10"}]]),xs=V("gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]),VS=V("grid-2x2",[["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M3 12h18",key:"1i2n21"}],["rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",key:"h1oib"}]]),jS=V("grip-horizontal",[["circle",{cx:"12",cy:"9",r:"1",key:"124mty"}],["circle",{cx:"19",cy:"9",r:"1",key:"1ruzo2"}],["circle",{cx:"5",cy:"9",r:"1",key:"1a8b28"}],["circle",{cx:"12",cy:"15",r:"1",key:"1e56xg"}],["circle",{cx:"19",cy:"15",r:"1",key:"1a92ep"}],["circle",{cx:"5",cy:"15",r:"1",key:"5r1jwy"}]]),KS=V("hard-drive",[["path",{d:"M10 16h.01",key:"1bzywj"}],["path",{d:"M2.212 11.577a2 2 0 0 0-.212.896V18a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-5.527a2 2 0 0 0-.212-.896L18.55 5.11A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"18tbho"}],["path",{d:"M21.946 12.013H2.054",key:"zqlbp7"}],["path",{d:"M6 16h.01",key:"1pmjb7"}]]),zS=V("hash",[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]]),WS=V("hexagon",[["path",{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z",key:"yt0hxn"}]]),ns=V("house",[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]]),Em=V("image-off",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M10.41 10.41a2 2 0 1 1-2.83-2.83",key:"1bzlo9"}],["line",{x1:"13.5",x2:"6",y1:"13.5",y2:"21",key:"1q0aeu"}],["line",{x1:"18",x2:"21",y1:"12",y2:"15",key:"5mozeu"}],["path",{d:"M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59",key:"mmje98"}],["path",{d:"M21 15V5a2 2 0 0 0-2-2H9",key:"43el77"}]]),wm=V("image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]),QS=V("inbox",[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]]),qS=V("info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]),YS=V("layout-grid",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]]),Ic=V("lightbulb",[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]]),km=V("list-checks",[["path",{d:"M13 5h8",key:"a7qcls"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 19h8",key:"c3s6r1"}],["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}]]),XS=V("list",[["path",{d:"M3 5h.01",key:"18ugdj"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 19h.01",key:"noohij"}],["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 19h13",key:"m83p4d"}]]),vt=V("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]),ZS=V("locate-fixed",[["line",{x1:"2",x2:"5",y1:"12",y2:"12",key:"bvdh0s"}],["line",{x1:"19",x2:"22",y1:"12",y2:"12",key:"1tbv5k"}],["line",{x1:"12",x2:"12",y1:"2",y2:"5",key:"11lu5j"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}],["circle",{cx:"12",cy:"12",r:"7",key:"fim9np"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),vl=V("lock-open",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 9.9-1",key:"1mm8w8"}]]),Rc=V("lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]),JS=V("mail",[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]]),eE=V("map-pin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]),ld=V("maximize-2",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]]),tE=V("megaphone",[["path",{d:"M11 6a13 13 0 0 0 8.4-2.8A1 1 0 0 1 21 4v12a1 1 0 0 1-1.6.8A13 13 0 0 0 11 14H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2z",key:"q8bfy3"}],["path",{d:"M6 14a12 12 0 0 0 2.4 7.2 2 2 0 0 0 3.2-2.4A8 8 0 0 1 10 14",key:"1853fq"}],["path",{d:"M8 6v8",key:"15ugcq"}]]),rE=V("menu",[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]]),nE=V("message-square",[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]]),Tm=V("mic",[["path",{d:"M12 19v3",key:"npa21l"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3",key:"s6n7sd"}]]),cd=V("minimize-2",[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]]),Am=V("minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]),sE=V("monitor-play",[["path",{d:"M15.033 9.44a.647.647 0 0 1 0 1.12l-4.065 2.352a.645.645 0 0 1-.968-.56V7.648a.645.645 0 0 1 .967-.56z",key:"vbtd3f"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",key:"x3v2xh"}]]),Na=V("moon",[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]]),Cm=V("mouse-pointer-click",[["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"M9.037 9.69a.498.498 0 0 1 .653-.653l11 4.5a.5.5 0 0 1-.074.949l-4.349 1.041a1 1 0 0 0-.74.739l-1.04 4.35a.5.5 0 0 1-.95.074z",key:"s0h3yz"}]]),iE=V("move",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m19 9 3 3-3 3",key:"1mg7y2"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]]),aE=V("music",[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]]),oE=V("navigation",[["polygon",{points:"3 11 22 2 13 21 11 13 3 11",key:"1ltx0t"}]]),Nm=V("network",[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]]),Zs=V("pause",[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]]),lE=V("pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]),cE=V("pipette",[["path",{d:"m12 9-8.414 8.414A2 2 0 0 0 3 18.828v1.344a2 2 0 0 1-.586 1.414A2 2 0 0 1 3.828 21h1.344a2 2 0 0 0 1.414-.586L15 12",key:"1y3wsu"}],["path",{d:"m18 9 .4.4a1 1 0 1 1-3 3l-3.8-3.8a1 1 0 1 1 3-3l.4.4 3.4-3.4a1 1 0 1 1 3 3z",key:"110lr1"}],["path",{d:"m2 22 .414-.414",key:"jhxm08"}]]),Ar=V("play",[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]]),gn=V("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]),uE=V("plug",[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]]),dE=V("power-off",[["path",{d:"M18.36 6.64A9 9 0 0 1 20.77 15",key:"dxknvb"}],["path",{d:"M6.16 6.16a9 9 0 1 0 12.68 12.68",key:"1x7qb5"}],["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]),La=V("power",[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]]),hE=V("qr-code",[["rect",{width:"5",height:"5",x:"3",y:"3",rx:"1",key:"1tu5fj"}],["rect",{width:"5",height:"5",x:"16",y:"3",rx:"1",key:"1v8r4q"}],["rect",{width:"5",height:"5",x:"3",y:"16",rx:"1",key:"1x03jg"}],["path",{d:"M21 16h-3a2 2 0 0 0-2 2v3",key:"177gqh"}],["path",{d:"M21 21v.01",key:"ents32"}],["path",{d:"M12 7v3a2 2 0 0 1-2 2H7",key:"8crl2c"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M12 3h.01",key:"n36tog"}],["path",{d:"M12 16v.01",key:"133mhm"}],["path",{d:"M16 12h1",key:"1slzba"}],["path",{d:"M21 12v.01",key:"1lwtk9"}],["path",{d:"M12 21v-1",key:"1880an"}]]),fE=V("radar",[["path",{d:"M19.07 4.93A10 10 0 0 0 6.99 3.34",key:"z3du51"}],["path",{d:"M4 6h.01",key:"oypzma"}],["path",{d:"M2.29 9.62A10 10 0 1 0 21.31 8.35",key:"qzzz0"}],["path",{d:"M16.24 7.76A6 6 0 1 0 8.23 16.67",key:"1yjesh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M17.99 11.66A6 6 0 0 1 15.77 16.67",key:"1u2y91"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"m13.41 10.59 5.66-5.66",key:"mhq4k0"}]]),Lm=V("radio",[["path",{d:"M16.247 7.761a6 6 0 0 1 0 8.478",key:"1fwjs5"}],["path",{d:"M19.075 4.933a10 10 0 0 1 0 14.134",key:"ehdyv1"}],["path",{d:"M4.925 19.067a10 10 0 0 1 0-14.134",key:"1q22gi"}],["path",{d:"M7.753 16.239a6 6 0 0 1 0-8.478",key:"r2q7qm"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]),vn=V("refresh-cw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]),bl=V("rotate-ccw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]),yl=V("rotate-cw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]),Im=V("save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]),pE=V("scan",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}]]),Rm=V("scroll-text",[["path",{d:"M15 12h-5",key:"r7krc0"}],["path",{d:"M15 8h-5",key:"1khuty"}],["path",{d:"M19 17V5a2 2 0 0 0-2-2H4",key:"zz82l3"}],["path",{d:"M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3",key:"1ph1d7"}]]),Xn=V("search",[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]),mE=V("server",[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]]),gE=V("settings",[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),xl=V("share-2",[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]]),Mc=V("shield-alert",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]),vE=V("shield-check",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]),bE=V("shield-off",[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5 5a1 1 0 0 0-1 1v7c0 5 3.5 7.5 7.67 8.94a1 1 0 0 0 .67.01c2.35-.82 4.48-1.97 5.9-3.71",key:"1jlk70"}],["path",{d:"M9.309 3.652A12.252 12.252 0 0 0 11.24 2.28a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1v7a9.784 9.784 0 0 1-.08 1.264",key:"18rp1v"}]]),Mm=V("shield",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]]),yE=V("ship",[["path",{d:"M12 10.189V14",key:"1p8cqu"}],["path",{d:"M12 2v3",key:"qbqxhf"}],["path",{d:"M19 13V7a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2v6",key:"qpkstq"}],["path",{d:"M19.38 20A11.6 11.6 0 0 0 21 14l-8.188-3.639a2 2 0 0 0-1.624 0L3 14a11.6 11.6 0 0 0 2.81 7.76",key:"7tigtc"}],["path",{d:"M2 21c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1s1.2 1 2.5 1c2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"1924j5"}]]),Pm=V("siren",[["path",{d:"M7 18v-6a5 5 0 1 1 10 0v6",key:"pcx96s"}],["path",{d:"M5 21a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-1a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2z",key:"1b4s83"}],["path",{d:"M21 12h1",key:"jtio3y"}],["path",{d:"M18.5 4.5 18 5",key:"g5sp9y"}],["path",{d:"M2 12h1",key:"1uaihz"}],["path",{d:"M12 2v1",key:"11qlp1"}],["path",{d:"m4.929 4.929.707.707",key:"1i51kw"}],["path",{d:"M12 12v6",key:"3ahymv"}]]),xE=V("skip-back",[["path",{d:"M17.971 4.285A2 2 0 0 1 21 6v12a2 2 0 0 1-3.029 1.715l-9.997-5.998a2 2 0 0 1-.003-3.432z",key:"15892j"}],["path",{d:"M3 20V4",key:"1ptbpl"}]]),SE=V("skip-forward",[["path",{d:"M21 4v16",key:"7j8fe9"}],["path",{d:"M6.029 4.285A2 2 0 0 0 3 6v12a2 2 0 0 0 3.029 1.715l9.997-5.998a2 2 0 0 0 .003-3.432z",key:"zs4d6"}]]),Pc=V("sliders-horizontal",[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]]),EE=V("smartphone",[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]]),Cr=V("square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]),wE=V("star",[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]]),Dc=V("sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]),kE=V("table-2",[["path",{d:"M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18",key:"gugj83"}]]),ud=V("target",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]),_c=V("thermometer",[["path",{d:"M14 4v10.54a4 4 0 1 1-4 0V4a2 2 0 0 1 4 0Z",key:"17jzev"}]]),Sl=V("toggle-left",[["circle",{cx:"9",cy:"12",r:"3",key:"u3jwor"}],["rect",{width:"20",height:"14",x:"2",y:"5",rx:"7",key:"g7kal2"}]]),TE=V("tractor",[["path",{d:"m10 11 11 .9a1 1 0 0 1 .8 1.1l-.665 4.158a1 1 0 0 1-.988.842H20",key:"she1j9"}],["path",{d:"M16 18h-5",key:"bq60fd"}],["path",{d:"M18 5a1 1 0 0 0-1 1v5.573",key:"1kv8ia"}],["path",{d:"M3 4h8.129a1 1 0 0 1 .99.863L13 11.246",key:"1q1ert"}],["path",{d:"M4 11V4",key:"9ft8pt"}],["path",{d:"M7 15h.01",key:"k5ht0j"}],["path",{d:"M8 10.1V4",key:"1jgyzo"}],["circle",{cx:"18",cy:"18",r:"2",key:"1emm8v"}],["circle",{cx:"7",cy:"15",r:"5",key:"ddtuc"}]]),zt=V("trash-2",[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]]),AE=V("trending-up",[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]]),CE=V("trending-down",[["path",{d:"M16 17h6v-6",key:"t6n2it"}],["path",{d:"m22 17-8.5-8.5-5 5L2 7",key:"x473p"}]]),ss=V("triangle-alert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]),NE=V("type",[["path",{d:"M12 4v16",key:"1654pz"}],["path",{d:"M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2",key:"e0r10z"}],["path",{d:"M9 20h6",key:"s66wpe"}]]),LE=V("unlink-2",[["path",{d:"M15 7h2a5 5 0 0 1 0 10h-2m-6 0H7A5 5 0 0 1 7 7h2",key:"1re2ne"}]]),Dm=V("upload",[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]]),IE=V("vibrate",[["path",{d:"m2 8 2 2-2 2 2 2-2 2",key:"sv1b1"}],["path",{d:"m22 8-2 2 2 2-2 2 2 2",key:"101i4y"}],["rect",{width:"8",height:"14",x:"8",y:"5",rx:"1",key:"1oyrl4"}]]),Oc=V("volume-2",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]]),RE=V("volume-x",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]]),ME=V("waves",[["path",{d:"M2 6c.6.5 1.2 1 2.5 1C7 7 7 5 9.5 5c2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"knzxuh"}],["path",{d:"M2 12c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"2jd2cc"}],["path",{d:"M2 18c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"rd2r6e"}]]),_m=V("wifi-off",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}],["path",{d:"M5 12.859a10 10 0 0 1 5.17-2.69",key:"1dl1wf"}],["path",{d:"M19 12.859a10 10 0 0 0-2.007-1.523",key:"4k23kn"}],["path",{d:"M2 8.82a15 15 0 0 1 4.177-2.643",key:"1grhjp"}],["path",{d:"M22 8.82a15 15 0 0 0-11.288-3.764",key:"z3jwby"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]),Fc=V("wifi",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M2 8.82a15 15 0 0 1 20 0",key:"dnpr2z"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]]),ia=V("wind",[["path",{d:"M12.8 19.6A2 2 0 1 0 14 16H2",key:"148xed"}],["path",{d:"M17.5 8a2.5 2.5 0 1 1 2 4H2",key:"1u4tom"}],["path",{d:"M9.8 4.4A2 2 0 1 1 11 8H2",key:"75valh"}]]),PE=V("workflow",[["rect",{width:"8",height:"8",x:"3",y:"3",rx:"2",key:"by2w9f"}],["path",{d:"M7 11v4a2 2 0 0 0 2 2h4",key:"xkn7yn"}],["rect",{width:"8",height:"8",x:"13",y:"13",rx:"2",key:"1cgmvn"}]]),DE=V("wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]]),bt=V("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),$r=V("zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]),Om=V("zoom-in",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]),Fm=V("zoom-out",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]),KO={frigate:yE,scrypted:Mm,reolink:Lm,homeAssistant:ns,rtsp:xS},zO={online:TS,offline:NS,degraded:rs,unknown:gm},dd=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,hd=op,bn=(e,t)=>r=>{var n;if(t?.variants==null)return hd(e,r?.class,r?.className);const{variants:s,defaultVariants:i}=t,a=Object.keys(s).map(o=>{const c=r?.[o],d=i?.[o];if(c===null)return null;const h=dd(c)||dd(d);return s[o][h]}),l=r&&Object.entries(r).reduce((o,c)=>{let[d,h]=c;return h===void 0||(o[d]=h),o},{});return hd(e,a,t==null||(n=t.compoundVariants)===null||n===void 0?void 0:n.reduce((o,c)=>{let{class:d,className:h,...f}=c;return Object.entries(f).every(p=>{let[m,g]=p;return Array.isArray(g)?g.includes({...i,...l}[m]):{...i,...l}[m]===g})?[...o,d,h]:o},[]),r?.class,r?.className)},_E=bn("inline-flex items-center justify-center rounded-md font-medium transition-colors cursor-pointer disabled:opacity-50 disabled:pointer-events-none",{variants:{variant:{primary:"bg-primary text-primary-foreground hover:bg-primary/90",secondary:"bg-surface text-foreground hover:bg-surface-hover",ghost:"hover:bg-surface-hover text-foreground-muted",danger:"bg-danger text-white hover:bg-danger/90",outline:"border border-border bg-transparent hover:bg-surface-hover"},size:{sm:"h-7 px-2.5 text-xs gap-1.5",md:"h-8 px-3 text-sm gap-2",lg:"h-9 px-4 text-sm gap-2"}},defaultVariants:{variant:"primary",size:"sm"}}),tr=It(({className:e,variant:t,size:r,...n},s)=>u("button",{ref:s,className:L(_E({variant:t,size:r}),e),...n}));tr.displayName="Button";var OE=bn("inline-flex items-center justify-center rounded-md font-medium transition-colors cursor-pointer disabled:opacity-50 disabled:pointer-events-none",{variants:{variant:{primary:"bg-primary text-primary-foreground hover:bg-primary/90",secondary:"bg-surface text-foreground hover:bg-surface-hover",ghost:"hover:bg-surface-hover text-foreground-muted",danger:"bg-danger text-white hover:bg-danger/90",outline:"border border-border bg-transparent hover:bg-surface-hover"},size:{sm:"h-7 w-7",md:"h-8 w-8",lg:"h-9 w-9"}},defaultVariants:{variant:"primary",size:"sm"}}),$m=It(({className:e,variant:t,size:r,icon:n,...s},i)=>u("button",{ref:i,className:L(OE({variant:t,size:r}),e),...s,children:u(n,{className:"h-4 w-4"})}));$m.displayName="IconButton";var FE=bn("inline-flex items-center rounded-full text-xs font-medium px-2 py-0.5",{variants:{variant:{default:"bg-surface-hover text-foreground",success:"bg-success/15 text-success",warning:"bg-warning/15 text-warning",danger:"bg-danger/15 text-danger",info:"bg-info/15 text-info"},styleVariant:{solid:"",outline:"border bg-transparent"}},defaultVariants:{variant:"default",styleVariant:"solid"}}),Hn=It(({className:e,variant:t,style:r,...n},s)=>u("span",{ref:s,className:L(FE({variant:t,styleVariant:r}),e),...n}));Hn.displayName="Badge";var $E=bn("rounded-lg p-3",{variants:{variant:{flat:"bg-surface",bordered:"bg-surface border border-border"}},defaultVariants:{variant:"bordered"}}),Bm=It(({className:e,variant:t,...r},n)=>u("div",{ref:n,className:L($E({variant:t}),e),...r}));Bm.displayName="Card";function BE({expanded:e,onExpandedChange:t,header:r,children:n,dimmed:s=!1,hideChevron:i=!1,className:a}){return v("div",{className:L("rounded-lg border border-border bg-surface overflow-hidden",s&&"opacity-[0.45]",a),children:[v("div",{role:"button",tabIndex:0,className:"flex items-center gap-2.5 px-3 py-2.5 cursor-pointer select-none",onClick:()=>t(!e),onKeyDown:l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),t(!e))},children:[!i&&u("span",{className:"text-foreground-subtle shrink-0",children:e?u(yt,{className:"h-4 w-4"}):u(nr,{className:"h-4 w-4"})}),r]}),e&&n&&u("div",{className:"border-t border-border px-3 py-3",children:n})]})}var Um=It(({className:e,...t},r)=>u("label",{ref:r,className:L("text-[10px] uppercase tracking-wider text-foreground-muted font-medium",e),...t}));Um.displayName="Label";var UE=bn("",{variants:{orientation:{horizontal:"h-px w-full bg-border-subtle",vertical:"w-px h-full bg-border-subtle"}},defaultVariants:{orientation:"horizontal"}}),Gm=It(({className:e,orientation:t,...r},n)=>u("div",{ref:n,role:"separator",className:L(UE({orientation:t}),e),...r}));Gm.displayName="Separator";var GE=It(({className:e,...t},r)=>u("div",{ref:r,className:L("animate-pulse bg-surface-hover rounded-md h-4 w-full",e),...t}));GE.displayName="Skeleton";var fd=bn("h-7 w-full px-2.5 text-xs bg-surface border rounded-md text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary transition-colors",{variants:{state:{default:"border-border",error:"border-danger"}},defaultVariants:{state:"default"}}),El=It(({className:e,state:t,leftSlot:r,rightSlot:n,...s},i)=>r||n?v("div",{className:"relative flex items-center w-full",children:[r&&u("div",{className:"absolute left-2.5 flex items-center pointer-events-none",children:r}),u("input",{ref:i,className:L(fd({state:t}),r?"pl-7":"",n?"pr-7":"",e),...s}),n&&u("div",{className:"absolute right-2.5 flex items-center pointer-events-none",children:n})]}):u("input",{ref:i,className:L(fd({state:t}),e),...s}));El.displayName="Input";var aa=It(({className:e,options:t,...r},n)=>v("div",{className:"relative w-full",children:[u("select",{ref:n,className:L("h-7 w-full px-2.5 text-xs bg-surface border border-border rounded-md text-foreground appearance-none pr-7 focus:outline-none focus:ring-1 focus:ring-primary",e),...r,children:t.map(s=>u("option",{value:s.value,children:s.label},s.value))}),u("div",{className:"absolute right-2 top-1/2 -translate-y-1/2 pointer-events-none text-foreground-muted",children:u(yt,{className:"h-3.5 w-3.5"})})]}));aa.displayName="Select";var HE=It(({className:e,...t},r)=>u("input",{ref:r,type:"checkbox",className:L("w-3.5 h-3.5 rounded-sm border border-border accent-primary",e),...t}));HE.displayName="Checkbox";var VE=It(({className:e,checked:t,onCheckedChange:r,label:n,...s},i)=>v("button",{ref:i,role:"switch","aria-checked":t,type:"button",onClick:()=>r(!t),className:L("inline-flex items-center gap-2",e),...s,children:[u("span",{className:L("w-8 h-4 rounded-full transition-colors",t?"bg-primary":"bg-surface-hover"),children:u("span",{className:L("block w-3.5 h-3.5 rounded-full bg-white transition-transform",t?"translate-x-4":"translate-x-0.5")})}),n&&u("span",{className:"text-xs text-foreground",children:n})]}));VE.displayName="Switch";var Hm=hr(null);function Vm(){const e=ct(Hm);if(!e)throw new Error("Dialog compound components must be used within <Dialog>");return e}function $c({children:e,open:t,onOpenChange:r}){const[n,s]=_(!1),i=t??n,a=fr(),l=q(o=>{r?.(o),t===void 0&&s(o)},[t,r]);return u(Hm.Provider,{value:{open:i,setOpen:l,contentId:a},children:e})}function WO({children:e,...t}){const{setOpen:r}=Vm();return u("button",{type:"button",onClick:()=>r(!0),...t,children:e})}var jE=bn("fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 m-0 w-[calc(100vw-2rem)] bg-background-elevated border border-border rounded-lg p-4 backdrop:bg-black/50 backdrop:backdrop-blur-sm max-h-[calc(100dvh-2rem)] overflow-y-auto",{variants:{width:{sm:"max-w-sm",md:"max-w-md",lg:"max-w-lg"}},defaultVariants:{width:"md"}}),Ia=It(({className:e,width:t,children:r,...n},s)=>{const{open:i,setOpen:a,contentId:l}=Vm(),o=ne(null),c=s??o;ae(()=>{const h=c.current;h&&(i&&!h.open&&h.showModal(),!i&&h.open&&h.close())},[i,c]);const d=h=>{h.target===h.currentTarget&&a(!1)};return u("dialog",{ref:c,id:l,className:L(jE({width:t}),e),onClick:d,onClose:()=>a(!1),...n,children:r})});Ia.displayName="DialogContent";function Bc({className:e,...t}){return u("div",{className:L("flex flex-col gap-1 mb-3",e),...t})}function Uc({className:e,...t}){return u("div",{className:L("flex justify-end gap-2 mt-4",e),...t})}function Gc({className:e,...t}){return u("h2",{className:L("text-sm font-semibold text-foreground",e),...t})}function Hc({className:e,...t}){return u("p",{className:L("text-xs text-foreground-muted",e),...t})}var jm=hr(null);function Vc(){const e=ct(jm);if(!e)throw new Error("Dropdown compound components must be used within <Dropdown>");return e}function QO({children:e}){const[t,r]=_(!1),n=fr(),s=fr(),i=ne(null);return u(jm.Provider,{value:{open:t,setOpen:r,triggerId:n,contentId:s,triggerRef:i},children:u("div",{className:"relative inline-block",children:e})})}function qO({children:e,...t}){const{open:r,setOpen:n,triggerId:s,contentId:i,triggerRef:a}=Vc();return u("button",{type:"button",ref:a,id:s,"aria-haspopup":"menu","aria-expanded":r,"aria-controls":r?i:void 0,onClick:()=>n(!r),...t,children:e})}function YO({className:e,children:t,align:r="start",offset:n=4,...s}){const{open:i,setOpen:a,contentId:l,triggerId:o,triggerRef:c}=Vc(),d=ne(null),[h,f]=_(null);return Gf(()=>{if(!i){f(null);return}const p=()=>{const m=c.current;if(!m)return;const g=m.getBoundingClientRect(),b=r==="end"?g.right:g.left;f({top:g.bottom+n,left:b,minWidth:g.width})};return p(),window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),()=>{window.removeEventListener("resize",p),window.removeEventListener("scroll",p,!0)}},[i,r,n,c]),ae(()=>{if(!i)return;const p=g=>{const b=d.current,y=c.current;b&&!b.contains(g.target)&&!y?.contains(g.target)&&a(!1)},m=g=>{g.key==="Escape"&&a(!1)};return document.addEventListener("mousedown",p),document.addEventListener("keydown",m),()=>{document.removeEventListener("mousedown",p),document.removeEventListener("keydown",m)}},[i,a,c]),!i||!h||typeof document>"u"?null:Ys(u("div",{ref:d,id:l,role:"menu","aria-labelledby":o,style:{position:"fixed",top:h.top,...r==="end"?{right:window.innerWidth-h.left}:{left:h.left},minWidth:h.minWidth},className:L("z-50 bg-background-elevated border border-border rounded-md shadow-lg py-1 min-w-[160px]",e),...s,children:t}),document.body)}function XO({className:e,icon:t,variant:r="default",children:n,onClick:s,...i}){const{setOpen:a}=Vc(),l=q(o=>{s?.(o),a(!1)},[s,a]);return v("button",{type:"button",role:"menuitem",className:L("h-7 text-xs px-2 w-full text-left flex items-center gap-2",r==="danger"?"text-danger hover:bg-danger/10":"text-foreground hover:bg-surface-hover",e),onClick:l,...i,children:[t&&u(t,{size:14}),n]})}var Km=hr(null);function zm(){const e=ct(Km);if(!e)throw new Error("Tooltip compound components must be used within <Tooltip>");return e}function KE({children:e,className:t}){const[r,n]=_(!1),s=ne(null),i=fr(),a=()=>{s.current=setTimeout(()=>n(!0),300)},l=()=>{s.current&&clearTimeout(s.current),n(!1)};return u(Km.Provider,{value:{open:r,show:a,hide:l,tooltipId:i},children:u("div",{className:L("relative",t??"inline-block"),children:e})})}function zE({children:e,...t}){const{show:r,hide:n,tooltipId:s,open:i}=zm();return u("div",{onMouseEnter:r,onMouseLeave:n,onFocus:r,onBlur:n,"aria-describedby":i?s:void 0,...t,children:e})}function WE({className:e,children:t,...r}){const{open:n,tooltipId:s}=zm();return u("div",{id:s,role:"tooltip",className:L("absolute bottom-full left-1/2 -translate-x-1/2 mb-2 bg-foreground text-background text-xs px-2 py-1 rounded-md shadow-md whitespace-nowrap pointer-events-none transition-opacity duration-150",n?"opacity-100":"opacity-0",e),...r,children:t})}var pd="(max-width: 767px)",md="(min-width: 768px) and (max-width: 1023px)";function Wm(e){return t=>{const r=window.matchMedia(e);return r.addEventListener("change",t),()=>r.removeEventListener("change",t)}}function Qm(e){return()=>window.matchMedia(e).matches}function qm(){return!1}function Ra(){return mc(Wm(pd),Qm(pd),qm)}function ZO(){return mc(Wm(md),Qm(md),qm)}function Ym({open:e,onClose:t,title:r,children:n,className:s}){return ae(()=>{if(!e)return;const i=a=>{a.key==="Escape"&&t()};return document.addEventListener("keydown",i),document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",i),document.body.style.overflow=""}},[e,t]),v(Ie,{children:[u("div",{className:L("fixed inset-0 z-40 bg-black/50 transition-opacity duration-200",e?"opacity-100":"pointer-events-none opacity-0"),onClick:t,"aria-hidden":"true"}),v("div",{role:"dialog","aria-modal":"true",className:L("fixed inset-x-0 bottom-0 z-50 flex flex-col bg-background-elevated border-t border-border rounded-t-xl shadow-2xl transition-transform duration-200 ease-out","max-h-[80dvh]",e?"translate-y-0":"translate-y-full",s),children:[u("div",{className:"flex justify-center pt-2 pb-1",children:u("div",{className:"h-1 w-8 rounded-full bg-foreground-subtle/30"})}),r&&v("div",{className:"flex items-center justify-between px-4 pb-2",children:[u("span",{className:"text-sm font-medium text-foreground",children:r}),u("button",{onClick:t,className:"p-1 rounded-md hover:bg-surface-hover text-foreground-muted transition-colors",children:u(bt,{className:"h-4 w-4"})})]}),u("div",{className:"flex-1 overflow-y-auto px-4 pb-4",children:n})]})]})}var Xm=hr(null);function Zm(){const e=ct(Xm);if(!e)throw new Error("Popover compound components must be used within <Popover>");return e}function QE({children:e,open:t,onOpenChange:r}){const[n,s]=_(!1),i=t??n,a=fr(),l=fr(),o=q(c=>{r?.(c),t===void 0&&s(c)},[t,r]);return u(Xm.Provider,{value:{open:i,setOpen:o,triggerId:a,contentId:l},children:u("div",{className:"relative inline-block",children:e})})}function qE({children:e,...t}){const{open:r,setOpen:n,triggerId:s,contentId:i}=Zm();return u("button",{type:"button",id:s,"aria-haspopup":"dialog","aria-expanded":r,"aria-controls":r?i:void 0,onClick:()=>n(!r),...t,children:e})}function YE({className:e,children:t,...r}){const{open:n,setOpen:s,contentId:i,triggerId:a}=Zm(),l=Ra(),o=ne(null);return ae(()=>{if(!n||l)return;const c=h=>{const f=o.current,p=document.getElementById(a);f&&!f.contains(h.target)&&!p?.contains(h.target)&&s(!1)},d=h=>{h.key==="Escape"&&s(!1)};return document.addEventListener("mousedown",c),document.addEventListener("keydown",d),()=>{document.removeEventListener("mousedown",c),document.removeEventListener("keydown",d)}},[n,s,a,l]),n?l?u(Ym,{open:n,onClose:()=>s(!1),children:t}):u("div",{ref:o,id:i,role:"dialog","aria-labelledby":a,className:L("absolute left-0 top-full z-50 mt-1 bg-background-elevated border border-border rounded-lg shadow-lg p-3",e),...r,children:t}):null}var Jm=hr(null);function eg(){const e=ct(Jm);if(!e)throw new Error("Tabs compound components must be used within <Tabs>");return e}function JO({value:e,onValueChange:t,defaultValue:r="",className:n,...s}){const[i,a]=_(r),l=e??i,o=q(c=>{t?.(c),e===void 0&&a(c)},[e,t]);return u(Jm.Provider,{value:{value:l,setValue:o},children:u("div",{className:n,...s})})}function e3({className:e,...t}){return u("div",{role:"tablist",className:L("flex flex-row border-b border-border-subtle",e),...t})}function t3({value:e,className:t,...r}){const{value:n,setValue:s}=eg(),i=e===n;return u("button",{type:"button",role:"tab","aria-selected":i,"aria-controls":`tabpanel-${e}`,tabIndex:i?0:-1,className:L("h-7 text-xs px-3 transition-colors",i?"border-b-2 border-primary text-foreground font-medium":"text-foreground-muted hover:text-foreground",t),onClick:()=>s(e),...r})}function r3({value:e,className:t,...r}){const{value:n}=eg();return e!==n?null:u("div",{role:"tabpanel",id:`tabpanel-${e}`,className:L("pt-3",t),...r})}var tg=It(({className:e,...t},r)=>u("div",{ref:r,className:L("overflow-auto [&::-webkit-scrollbar]:w-1 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-thumb]:bg-surface-hover [&::-webkit-scrollbar-thumb]:rounded-full",e),...t}));tg.displayName="ScrollArea";function n3({title:e,onClose:t,children:r,defaultWidth:n=360,defaultHeight:s=280,minWidth:i=280,minHeight:a=160,offsetIndex:l=0,className:o}){const[c,d]=_({x:80+l*30,y:80+l*30}),[h,f]=_({w:n,h:s}),[p,m]=_(!1),g=ne(!1),b=ne(!1),y=ne({x:0,y:0}),S=Ra(),E=q(T=>{T.preventDefault(),g.current=!0,y.current={x:T.clientX-c.x,y:T.clientY-c.y}},[c]),k=q(T=>{T.preventDefault(),T.stopPropagation(),b.current=!0,y.current={x:T.clientX,y:T.clientY}},[]);return ae(()=>{const T=N=>{if(g.current&&d({x:N.clientX-y.current.x,y:N.clientY-y.current.y}),b.current){const C=N.clientX-y.current.x,M=N.clientY-y.current.y;y.current={x:N.clientX,y:N.clientY},f(P=>({w:Math.max(i,P.w+C),h:Math.max(a,P.h+M)}))}},A=()=>{g.current=!1,b.current=!1};return window.addEventListener("mousemove",T),window.addEventListener("mouseup",A),()=>{window.removeEventListener("mousemove",T),window.removeEventListener("mouseup",A)}},[i,a]),S?v("div",{className:L("fixed inset-x-0 bottom-0 z-50 rounded-t-xl border-t border-border bg-background-elevated shadow-2xl flex flex-col overflow-hidden",o),style:{maxHeight:"60dvh"},children:[v("div",{className:"flex items-center justify-between gap-2 px-3 py-2 border-b border-border shrink-0 bg-surface",children:[u("span",{className:"text-[11px] font-medium truncate",children:e}),v("div",{className:"flex items-center gap-1 shrink-0",children:[u("button",{onClick:()=>m(!p),className:"p-0.5 rounded hover:bg-surface-hover text-foreground-muted transition-colors",children:p?u(ld,{size:12}):u(cd,{size:12})}),u("button",{onClick:t,className:"p-0.5 rounded hover:bg-danger/20 text-foreground-muted hover:text-danger transition-colors",children:u(bt,{size:12})})]})]}),!p&&u("div",{className:"flex-1 min-h-0 overflow-y-auto",children:r})]}):v("div",{className:L("fixed z-50 rounded-lg border border-border bg-background-elevated shadow-2xl flex flex-col overflow-hidden",o),style:{left:c.x,top:c.y,width:p?280:h.w,height:p?"auto":h.h},children:[v("div",{onMouseDown:E,className:"flex items-center justify-between gap-2 px-3 py-2 border-b border-border cursor-move select-none shrink-0 bg-surface",children:[v("div",{className:"flex items-center gap-2 min-w-0",children:[u(jS,{size:12,className:"text-foreground-subtle shrink-0"}),u("span",{className:"text-[11px] font-medium truncate",children:e})]}),v("div",{className:"flex items-center gap-1 shrink-0",children:[u("button",{onClick:()=>m(!p),className:"p-0.5 rounded hover:bg-surface-hover text-foreground-muted transition-colors",title:p?"Restore":"Minimize",children:p?u(ld,{size:12}):u(cd,{size:12})}),u("button",{onClick:t,className:"p-0.5 rounded hover:bg-danger/20 text-foreground-muted hover:text-danger transition-colors",title:"Close",children:u(bt,{size:12})})]})]}),!p&&v("div",{className:"flex-1 min-h-0 overflow-y-auto relative",children:[r,u("div",{onMouseDown:k,className:"absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize",style:{background:"linear-gradient(135deg, transparent 50%, var(--color-foreground-subtle) 50%)",opacity:.4}})]})]})}function XE({open:e,onClose:t,children:r,className:n,width:s="w-64"}){const i=ne(null);return ae(()=>{if(!e)return;const a=l=>{l.key==="Escape"&&t()};return document.addEventListener("keydown",a),document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",a),document.body.style.overflow=""}},[e,t]),v(Ie,{children:[u("div",{className:L("fixed inset-0 z-40 bg-black/50 backdrop-blur-sm transition-opacity duration-200",e?"opacity-100":"pointer-events-none opacity-0"),onClick:t,"aria-hidden":"true"}),u("div",{ref:i,role:"dialog","aria-modal":"true",className:L("fixed inset-y-0 left-0 z-50 flex flex-col bg-surface border-r border-border shadow-2xl transition-transform duration-200 ease-out pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]",s,e?"translate-x-0":"-translate-x-full",n),children:r})]})}function s3({items:e,className:t}){return u("nav",{className:`hidden md:flex items-center gap-1 text-[11px] text-foreground-subtle ${t??""}`,children:e.map((r,n)=>{const s=n===e.length-1,i=!s&&(r.onClick||r.href);return v(dt.Fragment,{children:[n>0&&u(nr,{className:"h-3 w-3 flex-shrink-0"}),i?r.onClick?u("button",{type:"button",onClick:r.onClick,className:"hover:text-foreground transition-colors",children:r.label}):u("a",{href:r.href,className:"hover:text-foreground transition-colors",children:r.label}):u("span",{className:s?"text-foreground font-medium":"",children:r.label})]},n)})})}var gd={left:"text-left",right:"text-right",center:"text-center"};function i3({columns:e,rows:t,rowKey:r,onRowClick:n,minWidthPx:s=480,emptyMessage:i,className:a,bordered:l=!0,rowClassName:o}){return t.length===0&&i?u("div",{className:`rounded-lg ${l?"border border-border":""} bg-surface px-3 py-4 text-xs text-foreground-subtle text-center ${a??""}`,children:i}):t.length===0?null:u("div",{className:`rounded-lg ${l?"border border-border":""} bg-surface overflow-x-auto ${a??""}`,children:v("table",{className:"w-full text-xs",style:{minWidth:`${s}px`},children:[u("thead",{className:"bg-surface",children:u("tr",{children:e.map(c=>{const d=c.align??"left",h=c.nowrap??!0;return u("th",{className:["px-3 py-2 text-foreground-subtle font-medium bg-surface border-b border-border",gd[d],h?"whitespace-nowrap":"",c.width??""].filter(Boolean).join(" "),children:c.headerRender?c.headerRender():c.header},c.key)})})}),u("tbody",{children:t.map((c,d)=>{const h=r?r(c,d):d,f=o?.(c,d)??"",p=n!==void 0;return u("tr",{onClick:p?()=>n(c,d):void 0,className:[p?"cursor-pointer hover:bg-primary/5":"hover:bg-primary/5",f].filter(Boolean).join(" "),children:e.map(m=>{const g=m.align??"left",b=m.nowrap??!1;return u("td",{className:["px-3 py-2 text-foreground border-b border-border",gd[g],b?"whitespace-nowrap":""].filter(Boolean).join(" "),children:m.render(c,d)},m.key)})},h)})})]})})}function a3({open:e,onClose:t,title:r,subtitle:n,footer:s,children:i,widthClass:a="w-[360px]"}){return ae(()=>{if(!e)return;const l=o=>{o.key==="Escape"&&t()};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[e,t]),e?v("aside",{className:L("absolute top-0 right-0 bottom-0 z-20 flex flex-col","bg-surface border-l border-border shadow-xl",a),role:"dialog","aria-modal":"false",children:[v("header",{className:"flex items-start justify-between gap-2 px-4 py-3 border-b border-border",children:[v("div",{className:"min-w-0",children:[u("div",{className:"text-sm font-semibold text-foreground truncate",children:r}),n!==void 0&&u("div",{className:"text-[11px] text-foreground-subtle mt-0.5 truncate",children:n})]}),u("button",{type:"button",onClick:t,className:"p-1 rounded hover:bg-muted text-foreground-subtle hover:text-foreground","aria-label":"Close panel",children:u(bt,{className:"w-4 h-4"})})]}),u("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3",children:i}),s!==void 0&&u("footer",{className:"flex items-center gap-2 justify-end px-4 py-3 border-t border-border",children:s})]}):null}var ZE={inherit:"bg-muted",on:"bg-emerald-500",off:"bg-orange-500",na:"bg-gray-300 opacity-50"};function rg({node:e,depth:t,selectedAddonId:r,onSelect:n,agentDots:s}){const i=e.addonId===r,a=s?.[e.addonId]??[];return v("div",{children:[v("button",{type:"button",onClick:()=>n(e.addonId),className:L("w-full flex items-center justify-between gap-2 text-left px-3 py-1.5 text-xs","border-l-2",i?"bg-accent border-primary text-foreground font-medium":"border-transparent hover:bg-muted/40 text-foreground"),style:{paddingLeft:`${12+t*14}px`},children:[u("span",{className:"truncate",children:e.addonName}),a.length>0&&u("span",{className:"flex items-center gap-1 shrink-0",children:a.map(l=>u("span",{title:`${l.agentNodeId}: ${l.state}`,className:L("w-2 h-2 rounded-full",ZE[l.state])},l.agentNodeId))})]}),e.children.map(l=>u(rg,{node:l,depth:t+1,selectedAddonId:r,onSelect:n,agentDots:s},l.addonId))]})}function o3({tree:e,selectedAddonId:t,onSelect:r,agentDots:n,className:s}){return u("div",{className:L("flex flex-col py-2",s),children:e.map(i=>u(rg,{node:i,depth:0,selectedAddonId:t,onSelect:r,agentDots:n},i.addonId))})}function l3(e){const t=[],r=[],n=new Map;for(const i of e.slots)for(const a of i.addons){const l={addonId:a.id,addonName:a.name,slot:a.slot,inputClasses:a.inputClasses,outputClasses:a.outputClasses,children:[]};a.slot==="audio-classifier"?t.push(l):(r.push(l),n.set(a.id,l))}const s=[];for(const i of r){if(i.inputClasses.length===0){s.push(i);continue}const a=r.find(l=>l.addonId!==i.addonId&&l.outputClasses.some(o=>i.inputClasses.includes(o)));a&&a.children.push(i)}return[...s,...t]}function JE(e){return e?e.models.map(t=>({id:t.id,name:t.name})):[]}function Xa({step:e,schema:t,allSchemas:r,depth:n=0,onChange:s,onDelete:i,readOnly:a=!1,toggleMode:l="simple",overrideState:o=null,onOverrideChange:c,inheritedEnabled:d,hideModelAndSettings:h=!1}){const[f,p]=_(!1),m=JE(t);if(m.length>0&&!m.some(b=>b.id===e.modelId)&&!a){const b=(t?.defaultModelId?m.find(y=>y.id===t.defaultModelId):null)??m[0];b&&b.id!==e.modelId&&queueMicrotask(()=>s({...e,modelId:b.id}))}const g=v(Ie,{children:[v("div",{className:"flex-1 min-w-0",children:[u("span",{className:"text-[10px] uppercase tracking-wider font-medium text-foreground-subtle/60 block leading-none",children:e.slot}),u("span",{className:"text-sm font-semibold text-foreground truncate block leading-tight",children:e.addonName}),v("div",{className:"flex items-center gap-1 mt-0.5 flex-wrap",children:[e.inputClasses.map(b=>u("span",{className:"text-[9px] uppercase font-semibold tracking-wide px-1.5 py-0.5 rounded bg-blue-500/12 text-blue-400",children:b},b)),e.inputClasses.length>0&&e.outputClasses.length>0&&u("span",{className:"text-foreground-subtle/40 text-[10px]",children:"→"}),e.outputClasses.map(b=>u("span",{className:"text-[9px] uppercase font-semibold tracking-wide px-1.5 py-0.5 rounded bg-green-500/12 text-green-400",children:b},b))]})]}),!a&&l==="simple"&&u("button",{onClick:b=>{b.stopPropagation(),s({...e,enabled:!e.enabled})},className:L("relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors",e.enabled?"bg-success":"bg-foreground-subtle/30"),children:u("span",{className:L("inline-block h-4 w-4 rounded-full bg-white shadow transition-transform",e.enabled?"translate-x-6":"translate-x-1")})}),!a&&l==="threeState"&&c&&v("div",{className:"flex items-center gap-0.5 rounded-md border border-border p-0.5",onClick:b=>b.stopPropagation(),children:[u(Za,{label:"Inherit",active:o===null,variant:"inherit",subtext:d===void 0?void 0:d?"on":"off",onClick:()=>c(null)}),u(Za,{label:"On",active:o===!0,variant:"on",onClick:()=>c(!0)}),u(Za,{label:"Off",active:o===!1,variant:"off",onClick:()=>c(!1)})]})]});return u(BE,{expanded:f,onExpandedChange:p,dimmed:!e.enabled,header:g,children:h?u("p",{className:"text-[11px] text-foreground-subtle",children:"Model and detection settings are managed per agent — open the Pipeline page for this camera's agent to edit them."}):v("div",{className:"space-y-3",children:[u(wl,{label:"Model",value:e.modelId,disabled:a,options:m.map(b=>({value:b.id,label:b.name})),onChange:b=>s({...e,modelId:b})}),e.slot==="audio-classifier"&&e.engine&&u(wl,{label:"Runtime",value:`${e.engine.runtime}/${e.engine.backend}`,disabled:a,options:[{value:"node/cpu",label:"Node.js — ONNX CPU"},{value:"node/coreml",label:"Node.js — Apple SoundAnalysis (macOS)"},{value:"python/cpu",label:"Python — ONNX CPU"}],onChange:b=>{const[y,S]=b.split("/");s({...e,engine:{runtime:y,backend:S,format:S==="coreml"?"coreml":"onnx"}})}}),t?.configSchema?.map(b=>u(jc,{field:b,allFields:t.configSchema??[],step:e,disabled:a,onChange:s},b.key))]})})}function wl({label:e,value:t,options:r,disabled:n,onChange:s}){return v("div",{children:[u("label",{className:"block text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-1.5",children:e}),v("select",{value:t,onChange:i=>s(i.target.value),disabled:n,className:"w-full rounded-lg border border-border bg-surface px-3 py-2 text-xs text-foreground focus:outline-none focus:border-primary/50",children:[r.length===0&&u("option",{value:t,children:t||"default"}),r.map(i=>u("option",{value:i.value,disabled:i.disabled,children:i.label},i.value))]})]})}function ew({label:e,description:t,value:r,options:n,disabled:s,onChange:i}){function a(l){s||i(r.includes(l)?r.filter(o=>o!==l):[...r,l])}return v("div",{children:[u("label",{className:"block text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-1",children:e}),t&&u("p",{className:"text-[10px] text-foreground-subtle/60 mb-1.5",children:t}),u("div",{className:"flex flex-wrap gap-1.5",children:n.map(l=>u("button",{type:"button",disabled:s,onClick:()=>a(l.value),className:L("text-[10px] font-medium px-2 py-1 rounded-md border transition-colors",r.includes(l.value)?"bg-primary/20 text-primary border-primary/40":"bg-surface text-foreground-subtle border-border hover:border-primary/30",s&&"opacity-50 cursor-not-allowed"),children:l.label},l.value))})]})}function tw(e,t,r){const n=t.settings?.[e];if(n!==void 0)return n;const s=r.find(i=>"key"in i&&i.key===e);return s&&"default"in s?s.default:void 0}function jc({field:e,allFields:t,step:r,disabled:n,onChange:s}){const i=e.type!=="separator"&&e.type!=="info"?e.showWhen:void 0;if(i){const{field:l,equals:o,notEquals:c,in:d,notIn:h}=i,f=tw(l,r,t);if(o!==void 0&&f!==o||c!==void 0&&f===c||d!==void 0&&!d.includes(f)||h!==void 0&&h.includes(f))return null}function a(l){s({...r,settings:{...r.settings,[e.key]:l}})}if(e.type==="select"){const l=r.settings?.[e.key],o=typeof l=="string"?l:e.default??"";return u(wl,{label:e.label,value:o,disabled:n||e.disabled,options:e.options,onChange:a})}if(e.type==="multiselect"){const l=r.settings?.[e.key],o=Array.isArray(l)?l:Array.isArray(e.default)?e.default:[];return u(ew,{label:e.label,description:e.description,value:o,options:e.options,disabled:n||e.disabled,onChange:a})}if(e.type==="slider"||e.type==="number"){const l=r.settings?.[e.key],o=typeof e.default=="number"?e.default:e.min??0,c=typeof l=="number"?l:o,d=e.min??0,h=e.max??1,f=e.step??.01,p=e.type==="slider"?e.showValue:!0,m="unit"in e?e.unit:void 0,g=e.type==="slider"?e.displayScale:void 0,b=g?c/g:c;return v("div",{children:[v("div",{className:"flex items-center justify-between mb-1",children:[u("span",{className:"text-[10px] font-medium text-foreground-subtle uppercase tracking-wide",children:e.label}),p&&v("span",{className:"text-xs font-medium text-foreground tabular-nums",children:[typeof b=="number"?b.toFixed(2).replace(/\.?0+$/,""):b,m?` ${m}`:""]})]}),e.description&&u("p",{className:"text-[10px] text-foreground-subtle/60 mb-1.5",children:e.description}),u("input",{type:"range",min:d,max:h,step:f,value:c,disabled:n||e.disabled,onChange:y=>a(Number(y.target.value)),className:"w-full accent-primary h-1.5"})]})}if(e.type==="boolean"){const l=r.settings?.[e.key];return v("label",{className:"flex items-center gap-2",children:[u("input",{type:"checkbox",checked:typeof l=="boolean"?l:e.default===!0,disabled:n||e.disabled,onChange:o=>a(o.target.checked),className:"h-3.5 w-3.5 accent-primary"}),u("span",{className:"text-[10px] font-medium text-foreground-subtle uppercase tracking-wide",children:e.label})]})}if(e.type==="text"||e.type==="password"||e.type==="textarea"){const l=r.settings?.[e.key],o=typeof l=="string"?l:e.default??"",c=e.type==="password"?"password":"text";return v("div",{children:[u("label",{className:"block text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-1.5",children:e.label}),e.type==="textarea"?u("textarea",{value:o,disabled:n||e.disabled,placeholder:e.placeholder,onChange:d=>a(d.target.value),rows:3,className:"w-full rounded-lg border border-border bg-surface px-3 py-2 text-xs text-foreground focus:outline-none focus:border-primary/50 resize-y"}):u("input",{type:c,value:o,disabled:n||e.disabled,placeholder:e.placeholder,onChange:d=>a(d.target.value),className:"w-full rounded-lg border border-border bg-surface px-3 py-2 text-xs text-foreground focus:outline-none focus:border-primary/50"})]})}return e.type==="separator"?u("div",{className:"border-t border-border my-2"}):e.type==="info"?u("div",{className:"rounded-md border border-border bg-surface px-2 py-1.5 text-[10px] text-foreground-subtle",children:e.content}):null}function Za({label:e,active:t,variant:r,subtext:n,onClick:s}){return v("button",{type:"button",onClick:s,className:L("px-2 py-1 text-[10px] font-medium rounded transition-colors",t?r==="on"?"bg-green-500/20 text-green-400":r==="off"?"bg-red-500/20 text-red-400":"bg-primary/20 text-primary":"text-foreground-subtle hover:bg-surface-hover"),children:[e,n&&t&&v("span",{className:"ml-1 opacity-60",children:["(",n,")"]})]})}function ng(e,t){return{addonId:e.id,addonName:e.name,slot:e.slot,inputClasses:[...e.inputClasses],outputClasses:[...e.outputClasses],enabled:t.enabled,modelId:t.modelId,children:[],settings:{...t.settings}}}function rw(e,t,r){return r?{enabled:r.enabled??t.enabled,modelId:r.modelId??t.modelId,settings:r.settings??t.settings}:t}function nw({addon:e,agentDefault:t,modelsForFormat:r,onChangeAgentConfig:n}){const s=i=>{n?.({...t,...i})};return v("div",{className:"space-y-4 text-xs",children:[v("label",{className:"flex items-center gap-2",children:[u("input",{type:"checkbox",checked:t.enabled,onChange:i=>s({enabled:i.target.checked})}),v("span",{children:["Enabled on this agent (",e.name,")"]})]}),v("div",{children:[u("div",{className:"text-[10px] uppercase tracking-widest text-foreground-subtle mb-1",children:"Model"}),u("select",{className:"w-full bg-surface border border-border rounded px-2 py-1 text-xs",value:t.modelId,onChange:i=>s({modelId:i.target.value}),children:r.map(i=>u("option",{value:i.id,children:i.name},i.id))})]}),(e.configSchema?.length??0)>0&&v("div",{className:"pt-2 border-t border-border/50 space-y-3",children:[u("div",{className:"text-[10px] uppercase tracking-widest text-foreground-subtle",children:"Settings"}),e.configSchema?.map(i=>u(jc,{field:i,allFields:e.configSchema??[],step:ng(e,t),disabled:!1,onChange:a=>s({settings:{...a.settings}})},i.key))]})]})}function sw({addon:e,agentDefault:t,agentNodeId:r,currentPatch:n,modelsForFormat:s,onChangePatch:i}){const a=rw("device",t,n),l=p=>{const m=p.enabled!==void 0||p.modelId!==void 0||p.settings!==void 0;i?.(m?p:null)},o=p=>{const{enabled:m,...g}=n??{};l(p==="inherit"?g:{...g,enabled:p==="on"})},c=p=>{const{modelId:m,...g}=n??{};l(p===void 0?g:{...g,modelId:p})},d=p=>{const{settings:m,...g}=n??{};l(p===void 0?g:{...g,settings:p})},h=n?.enabled===void 0?"inherit":n.enabled?"on":"off",f=n?.modelId!==void 0;return v("div",{className:"space-y-4 text-xs",children:[v("div",{className:"flex items-center gap-1",children:[["inherit","on","off"].map(p=>u("button",{type:"button",onClick:()=>o(p),className:L("px-3 py-1 border border-border rounded text-xs capitalize",h===p?"bg-primary text-primary-foreground border-primary":"bg-surface text-foreground hover:bg-muted"),children:p},p)),v("span",{className:"ml-2 text-[10px] text-foreground-subtle",children:["agent default: ",u("span",{className:"font-semibold",children:t.enabled?"on":"off"})]})]}),v("div",{children:[v("div",{className:"flex items-center justify-between mb-1",children:[u("div",{className:"text-[10px] uppercase tracking-widest text-foreground-subtle",children:"Model"}),f?u("button",{type:"button",className:"text-[10px] text-foreground-subtle hover:text-foreground",onClick:()=>c(void 0),children:"Clear"}):u("button",{type:"button",className:"text-[10px] text-primary hover:underline",onClick:()=>c(t.modelId),children:"Override"})]}),u("select",{disabled:!f,className:"w-full bg-surface border border-border rounded px-2 py-1 text-xs disabled:opacity-50",value:f?n?.modelId??t.modelId:t.modelId,onChange:p=>c(p.target.value),children:s.map(p=>u("option",{value:p.id,children:p.name},p.id))}),!f&&v("div",{className:"text-[10px] text-foreground-subtle mt-1",children:["inherits from ",r]})]}),(e.configSchema?.length??0)>0&&(()=>{const p=n?.settings!==void 0;return v("div",{className:"pt-2 border-t border-border/50 space-y-3",children:[v("div",{className:"flex items-center justify-between",children:[u("div",{className:"text-[10px] uppercase tracking-widest text-foreground-subtle",children:"Settings"}),p?u("button",{type:"button",className:"text-[10px] text-foreground-subtle hover:text-foreground",onClick:()=>d(void 0),children:"Clear"}):u("button",{type:"button",className:"text-[10px] text-primary hover:underline",onClick:()=>d({...t.settings}),children:"Override"})]}),e.configSchema?.map(m=>u(jc,{field:m,allFields:e.configSchema??[],step:ng(e,a),disabled:!p,onChange:g=>d({...g.settings})},m.key)),!p&&v("div",{className:"text-[10px] text-foreground-subtle",children:["inherits from ",r]})]})})(),v("div",{className:"rounded bg-muted/40 px-3 py-2 text-[11px] text-foreground-subtle",children:[u("div",{className:"font-semibold text-foreground mb-0.5",children:"Effective config preview"}),v("div",{className:"font-mono truncate",children:[e.id," · model: ",a.modelId," · ",a.enabled?"on":"off"]})]})]})}function c3(e){const{mode:t,addon:r,agentDefault:n,agentNodeId:s,currentPatch:i,onChangeAgentConfig:a,onChangePatch:l,engineFormat:o}=e,c=oe(()=>r.models.filter(d=>!!d.formats[o]),[r.models,o]);return t==="agent"?u(nw,{addon:r,agentDefault:n,modelsForFormat:c,onChangeAgentConfig:a}):u(sw,{addon:r,agentDefault:n,agentNodeId:s,currentPatch:i,modelsForFormat:c,onChangePatch:l})}function iw(e){const t=[],r=(n,s)=>{for(const i of n)t.push({node:i,depth:s}),r(i.children,s+1)};return r(e,0),t}var vd={detector:{label:"detector",className:"text-emerald-500"},cropper:{label:"cropper",className:"text-blue-500"},classifier:{label:"classifier",className:"text-violet-500"},refiner:{label:"refiner",className:"text-amber-500"},"audio-classifier":{label:"audio classifier",className:"text-pink-500"}};function aw({slot:e}){const t=vd[e]??vd.classifier;return u("span",{className:L("text-[9px] font-semibold uppercase tracking-widest leading-none",t.className),children:t.label})}var bd="inline-flex items-center rounded bg-muted px-1.5 py-px text-[9px] font-medium text-foreground-subtle";function ow({inputs:e,outputs:t}){return e.length===0&&t.length===0?null:v("span",{className:"inline-flex items-center gap-1 flex-wrap",children:[e.map(r=>u("span",{className:L(bd,"bg-blue-500/10 text-blue-500"),children:r},`in-${r}`)),e.length>0&&t.length>0&&u("span",{className:"text-foreground-subtle/60 text-[9px]",children:"→"}),t.map(r=>u("span",{className:L(bd,"bg-emerald-500/10 text-emerald-500"),children:r},`out-${r}`))]})}function lw({enabled:e,onChange:t,disabled:r}){return u("button",{type:"button",role:"switch","aria-checked":e,disabled:r,onClick:n=>{n.stopPropagation(),t(!e)},className:L("relative inline-flex h-3.5 w-7 shrink-0 items-center rounded-full transition-colors",e?"bg-emerald-500":"bg-foreground-subtle/30",r?"opacity-50 cursor-not-allowed":"cursor-pointer"),title:e?"Click to disable":"Click to enable",children:u("span",{className:L("inline-block h-3 w-3 rounded-full bg-white shadow transition-transform",e?"translate-x-3.5":"translate-x-0.5")})})}function cw(e){return e.kind==="enabled"?v("span",{className:"inline-flex items-center gap-1",children:[u("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-500 shrink-0"}),u("span",{className:"font-mono text-foreground",children:e.modelId})]}):e.kind==="disabled"?v("span",{className:"inline-flex items-center gap-1 text-foreground-subtle",children:[u("span",{className:"h-1.5 w-1.5 rounded-full border border-foreground-subtle/60 shrink-0"}),"off"]}):v("span",{className:"inline-flex items-center gap-1 text-foreground-subtle/70",children:[u("span",{className:"h-1.5 w-1.5 rounded-full bg-muted shrink-0"}),"n/a"]})}function uw({node:e,depth:t,agents:r,getCellState:n,onCellClick:s,selectedCell:i,toggleProps:a}){return v(Ie,{children:[v("div",{className:"sticky left-0 z-10 bg-surface px-3 py-2 border-b border-border text-xs flex items-start gap-2",style:{paddingLeft:`${12+t*14}px`},children:[v("div",{className:"flex flex-col gap-1 min-w-0 flex-1",children:[u(aw,{slot:e.slot}),v("div",{className:"flex items-center gap-2 flex-wrap",children:[u("span",{className:"font-semibold truncate",children:e.addonName}),u(ow,{inputs:e.inputClasses,outputs:e.outputClasses})]})]}),a&&u("span",{className:"pl-2 pt-0.5 shrink-0",children:u(lw,{enabled:a.enabled,onChange:a.onChange,disabled:a.disabled})})]}),r.map(l=>{const o=n(e.addonId,l.agentNodeId),c=i?.addonId===e.addonId&&i.agentNodeId===l.agentNodeId;return u("button",{type:"button",onClick:()=>s(e.addonId,l.agentNodeId),className:L("text-left px-3 py-1.5 border-b border-l border-border text-xs hover:bg-muted/40",o.kind==="enabled"&&"bg-emerald-500/5",o.kind==="na"&&"bg-muted/30",c&&"ring-2 ring-primary ring-inset"),children:cw(o)},l.agentNodeId)})]})}function u3({tree:e,agents:t,getCellState:r,onCellClick:n,selectedCell:s,onToggleEnabled:i}){const a=oe(()=>iw(e),[e]),l=`minmax(320px, 1fr) repeat(${t.length}, minmax(160px, 220px))`,o=i!==void 0&&t.length===1,c=t[0]?.agentNodeId;return u("div",{className:"overflow-auto border border-border rounded",children:v("div",{className:"grid",style:{gridTemplateColumns:l},children:[u("div",{className:"sticky top-0 left-0 z-20 bg-muted/60 px-3 py-2 text-[10px] uppercase tracking-widest text-foreground-subtle border-b border-border",children:"Step"}),t.map(d=>v("div",{className:"sticky top-0 z-10 bg-muted/60 px-3 py-2 border-b border-l border-border",children:[u("div",{className:"text-xs font-semibold text-foreground",children:d.agentNodeId}),u("div",{className:"text-[10px] text-foreground-subtle truncate",children:d.engineLabel})]},d.agentNodeId)),a.map(({node:d,depth:h})=>{const f=o&&c!==void 0?r(d.addonId,c):null;return u(uw,{node:d,depth:h,agents:t,getCellState:r,onCellClick:n,selectedCell:s,toggleProps:o&&f!==null?{enabled:f.kind==="enabled",onChange:p=>i?.(d.addonId,p),disabled:f.kind==="na"}:void 0},d.addonId)})]})})}var sg=typeof globalThis<"u"?globalThis.__camstackTrpcReact:void 0,x=sg??Qy();typeof globalThis<"u"&&!sg&&(globalThis.__camstackTrpcReact=x);var Kc=Nr("camstack:system",null);function dw({system:e,children:t}){return u(Kc.Provider,{value:e,children:t})}function Gt(){const e=ct(Kc);if(!e)throw new Error("useSystem(): no <SystemProvider> in tree");return e}function d3(){return ct(Kc)}function Ma(e,t){const r=Gt(),n=ne(t);n.current=t;const[s,i]=_(r.connectionVersion);ae(()=>r.subscribeConnectionEvents((a,l)=>{a==="connected"&&i(l)}),[r]),ae(()=>r.subscribeEvent(e,a=>{n.current(a)}),[r,e,s])}function kl(e){const t=ne(e);return t.current=e,t}function ig(e,t){const[r,n]=_(null),s=kl(t);return Ma(e,i=>{const a=i.data,l=s.current;l&&!l(a)||n(a)}),r}function h3(e,t,r){const[n,s]=_(()=>new Map),i=kl(t),a=kl(r);return Ma(e,l=>{const o=l.data,c=a.current;if(c&&!c(o))return;const d=i.current(o);s(h=>{const f=new Map(h);return f.set(d,o),f})}),{map:n,values:oe(()=>Array.from(n.values()),[n])}}function zc(){const{data:e,isLoading:t}=x.nodes.topology.useQuery(void 0,{staleTime:6e4}),r=ig("cluster.topology-snapshot")?.nodes??e;return{nodes:oe(()=>{const n=[];for(const s of r??[])n.push({id:String(s.id??""),name:String(s.name??s.id??""),shortName:s.isHub?"HUB":String(s.name??s.id??""),isHub:!!s.isHub,isOnline:!!s.isOnline,localIps:s.localIps??[],addons:(s.addons??[]).map(i=>({addonId:i.id,capabilities:i.capabilities}))});return n.sort((s,i)=>s.isHub!==i.isHub?s.isHub?-1:1:s.name.localeCompare(i.name)),n},[r]),isLoading:t}}function f3({selectedNodeId:e,onSelect:t,label:r="Node",hideIcon:n=!1,alwaysShow:s=!1}){const{nodes:i}=zc();return!s&&i.length<=1?null:v("div",{className:"flex items-center gap-1.5",children:[!n&&u(mE,{className:"h-3.5 w-3.5 text-foreground-subtle"}),r&&u("span",{className:"text-[10px] uppercase tracking-wider text-foreground-subtle",children:r}),u("div",{className:"flex rounded-md border border-border overflow-hidden text-[11px] font-medium",children:i.map((a,l)=>{const o=e===a.id;return u("button",{type:"button",onClick:()=>t(a.id),disabled:!a.isOnline,title:a.isOnline?a.name:`${a.name} (offline)`,className:L("px-2.5 py-1 transition-colors",o?"bg-primary/15 text-primary":"bg-transparent text-foreground-subtle hover:bg-surface-hover hover:text-foreground",l>0&&"border-l border-border",!a.isOnline&&"opacity-50 cursor-not-allowed"),children:a.shortName},a.id)})})]})}var hw={online:{colorClass:"bg-success",label:"Online"},offline:{colorClass:"bg-danger",label:"Offline"},degraded:{colorClass:"bg-warning",label:"Degraded"},unknown:{colorClass:"bg-foreground-subtle",label:"Unknown"}};function p3({status:e,showDot:t=!0,showLabel:r=!0,size:n="sm",className:s}){const i=hw[e];return v("span",{className:L("inline-flex items-center gap-1.5",n==="sm"?"text-xs":"text-sm",s),children:[t&&u("span",{className:L("h-1.5 w-1.5 shrink-0 rounded-full",i.colorClass),"aria-hidden":"true"}),r&&u("span",{className:"text-foreground",children:i.label})]})}var fw={frigate:{colorClass:"bg-provider-frigate",label:"Frigate"},scrypted:{colorClass:"bg-provider-scrypted",label:"Scrypted"},reolink:{colorClass:"bg-provider-reolink",label:"Reolink"},homeAssistant:{colorClass:"bg-provider-homeAssistant",label:"Home Assistant"},rtsp:{colorClass:"bg-provider-rtsp",label:"RTSP"}};function m3({provider:e,showLabel:t=!0,className:r}){const n=fw[e];return v("span",{className:L("inline-flex items-center gap-1.5 text-xs",r),children:[u("span",{className:L("h-1.5 w-1.5 shrink-0 rounded-sm",n.colorClass),"aria-hidden":"true"}),t&&u("span",{className:"text-foreground",children:n.label})]})}var pw={success:"bg-emerald-400 text-emerald-950",warning:"bg-amber-400 text-amber-950",danger:"bg-red-400 text-red-950",info:"bg-blue-400 text-blue-950",neutral:"bg-foreground-subtle/20 text-foreground"};function mw({children:e,variant:t="neutral",mono:r,className:n}){return u("span",{className:L("inline-flex items-center rounded-md px-2 py-0.5 text-[11px] font-bold leading-tight",r&&"font-mono",pw[t],n),children:e})}function g3({version:e,preRelease:t,className:r}){return u(mw,{variant:t??/-(alpha|beta|rc|dev|canary|next)/i.test(e)?"warning":"success",mono:!0,className:r,children:e})}function v3({label:e,description:t,error:r,required:n,children:s,orientation:i="vertical",className:a}){const l=i==="horizontal";return v("div",{className:L("flex gap-2",l?"flex-row items-center justify-between":"flex-col",a),children:[v("div",{className:L(l?"flex-1":""),children:[v(Um,{children:[e,n&&u("span",{className:"text-danger ml-0.5",children:"*"})]}),t&&u("p",{className:"text-foreground-subtle text-xs mt-0.5",children:t})]}),u("div",{className:L(l?"shrink-0":""),children:s}),r&&u("p",{className:"text-danger text-xs",children:r})]})}function b3({title:e,subtitle:t,actions:r,className:n}){return v("div",{className:L("flex flex-col gap-2 mb-3 sm:flex-row sm:items-center sm:justify-between",n),children:[v("div",{children:[u("h1",{className:"text-sm font-semibold text-foreground",children:e}),t&&u("p",{className:"text-foreground-subtle text-xs",children:t})]}),r&&u("div",{className:"flex items-center gap-2 flex-wrap",children:r})]})}function ag({icon:e,title:t,description:r,action:n,className:s}){return v("div",{className:L("flex flex-col items-center justify-center gap-3 py-12",s),children:[e&&u(e,{className:"h-12 w-12 text-foreground-subtle","aria-hidden":"true"}),v("div",{className:"flex flex-col items-center gap-1 text-center",children:[u("p",{className:"text-foreground-muted text-sm font-medium",children:t}),r&&u("p",{className:"text-foreground-subtle text-xs max-w-xs",children:r})]}),n&&u("div",{className:"mt-1",children:n})]})}var gw={danger:{box:"border-danger/40 bg-danger/10",icon:"text-danger",title:"text-danger",message:"text-danger"},warning:{box:"border-amber-500/40 bg-amber-500/10",icon:"text-amber-600 dark:text-amber-400",title:"text-amber-700 dark:text-amber-300",message:"text-amber-700 dark:text-amber-300"}};function oa({message:e,title:t,onRetry:r,action:n,variant:s="danger",className:i}){const a=gw[s],l=s==="warning"?ss:rs;return v("div",{role:"alert",className:L("flex items-start gap-2.5 rounded border px-3 py-2.5",a.box,i),children:[u(l,{className:L("h-4 w-4 mt-0.5 shrink-0",a.icon),"aria-hidden":"true"}),v("div",{className:"flex-1 min-w-0",children:[t&&u("p",{className:L("text-xs font-semibold",a.title),children:t}),u("div",{className:L("text-xs break-words",a.message,t?"mt-0.5":""),children:e})]}),n??(r&&v("button",{type:"button",onClick:r,className:L("shrink-0 inline-flex items-center gap-1 rounded px-2 py-1 text-[11px] font-medium","border border-current/30 hover:bg-current/10 transition-colors",a.message),children:[u(vn,{className:"h-3 w-3","aria-hidden":"true"}),"Retry"]}))]})}var og=Nr("camstack:confirm-dialog",null);function is(){const e=ct(og);if(!e)throw new Error("useConfirm must be used within ConfirmDialogProvider");return e.confirm}function y3({children:e}){const[t,r]=_(null),n=q(o=>new Promise(c=>{r({...o,resolve:c})}),[]),s=()=>{t?.resolve(!0),r(null)},i=()=>{t?.resolve(!1),r(null)},a={danger:{icon:"text-red-400",button:"bg-red-500 hover:bg-red-600 text-white"},warning:{icon:"text-orange-400",button:"bg-orange-500 hover:bg-orange-600 text-white"},default:{icon:"text-primary",button:"bg-primary hover:bg-primary/90 text-white"}},l=t?a[t.variant??"default"]:a.default;return v(og.Provider,{value:{confirm:n},children:[e,t&&v("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[u("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm",onClick:i}),v("div",{className:"relative z-10 w-full max-w-sm mx-4 rounded-xl border border-border bg-surface shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-150",onClick:o=>o.stopPropagation(),children:[v("div",{className:"px-5 pt-5 pb-4",children:[u("h3",{className:"text-sm font-semibold text-foreground",children:t.title}),u("p",{className:"mt-2 text-xs text-foreground-subtle leading-relaxed",children:t.message})]}),v("div",{className:"flex justify-end gap-2 px-5 py-3 border-t border-border bg-surface-hover/30",children:[u("button",{type:"button",onClick:i,className:"px-3 py-1.5 text-xs font-medium rounded-md border border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",children:t.cancelLabel??"Cancel"}),u("button",{type:"button",onClick:s,className:`px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${l.button}`,children:t.confirmLabel??"Confirm"})]})]})]})]})}function x3({value:e,label:t,trend:r,className:n}){return v(Bm,{className:L("flex flex-col gap-1",n),children:[v("div",{className:"flex items-baseline gap-2",children:[u("span",{className:"text-2xl font-semibold text-foreground",children:e}),r&&v("span",{className:L("inline-flex items-center gap-0.5 text-xs font-medium",r.direction==="up"?"text-success":"text-danger"),children:[r.direction==="up"?u(AE,{className:"h-3 w-3"}):u(CE,{className:"h-3 w-3"}),r.value,"%"]})]}),u("span",{className:"text-xs text-foreground-muted",children:t})]})}function S3({items:e,className:t}){return u("dl",{className:L("flex flex-col",t),children:e.map(r=>v("div",{className:"flex items-center h-7",children:[u("dt",{className:"text-foreground-subtle text-xs w-1/3 shrink-0",children:r.key}),u("dd",{className:"text-foreground text-xs",children:r.value})]},r.key))})}function E3({children:e,maxHeight:t=300,className:r}){const[n,s]=_(!1),i=q(()=>{navigator.clipboard.writeText(e).then(()=>{s(!0),setTimeout(()=>s(!1),2e3)})},[e]);return v("div",{className:L("relative group",r),children:[u(tg,{style:{maxHeight:t},children:u("pre",{className:"font-mono text-xs bg-surface p-3 rounded-md border border-border-subtle",children:u("code",{children:e})})}),u("div",{className:"absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity",children:u($m,{icon:n?Lr:zr,"aria-label":"Copy code",variant:"ghost",size:"sm",onClick:i})})]})}function w3({filters:e,values:t,onChange:r,className:n}){const s=Ra(),[i,a]=_(!1),l=(c,d)=>{r({...t,[c]:d})},o=Object.values(t).filter(c=>c!==void 0&&c!=="").length;if(s){const c=e.find(h=>h.type==="search"),d=e.some(h=>h.type!=="search");return v("div",{className:L("flex items-center gap-2",n),children:[c&&u(El,{placeholder:c.placeholder??"Search...",value:t[c.key]??"",onChange:h=>l(c.key,h.target.value),leftSlot:u(Xn,{className:"h-3 w-3 text-foreground-subtle"}),className:"flex-1"}),d&&v(Ie,{children:[v("button",{onClick:()=>a(!0),className:"flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-xs text-foreground-muted hover:bg-surface-hover transition-colors shrink-0",children:[u(Pc,{className:"h-3.5 w-3.5"}),"Filters",o>0&&u(Hn,{variant:"info",className:"ml-1 text-[10px] px-1 py-0",children:o})]}),u(Ym,{open:i,onClose:()=>a(!1),title:"Filters",children:u("div",{className:"flex flex-col gap-3",children:e.filter(h=>h.type!=="search").map(h=>{switch(h.type){case"select":return v("div",{children:[u("label",{className:"text-xs text-foreground-muted mb-1 block",children:h.label}),u(aa,{options:h.options,value:t[h.key]??"",onChange:f=>l(h.key,f.target.value),className:"w-full"})]},h.key);case"badge-toggle":return u("div",{className:"flex items-center gap-1 flex-wrap",children:h.options.map(f=>{const p=t[h.key]===f.value;return u("button",{type:"button",onClick:()=>l(h.key,p?void 0:f.value),children:u(Hn,{variant:p?"info":"default",className:"cursor-pointer",children:f.label})},f.value)})},h.key);default:return null}})})})]})]})}return u("div",{className:L("flex items-center gap-2 flex-wrap",n),children:e.map(c=>{switch(c.type){case"search":return u(El,{placeholder:c.placeholder??"Search...",value:t[c.key]??"",onChange:d=>l(c.key,d.target.value),leftSlot:u(Xn,{className:"h-3 w-3 text-foreground-subtle"}),className:"w-48"},c.key);case"select":return u(aa,{options:c.options,value:t[c.key]??"",onChange:d=>l(c.key,d.target.value),className:"w-36"},c.key);case"badge-toggle":return u("div",{className:"flex items-center gap-1",children:c.options.map(d=>{const h=t[c.key]===d.value;return u("button",{type:"button",onClick:()=>l(c.key,h?void 0:d.value),children:u(Hn,{variant:h?"info":"default",className:"cursor-pointer",children:d.label})},d.value)})},c.key);default:return null}})})}function yd({label:e,icon:t,href:r,badge:n,active:s=!1,className:i}){return v("a",{href:r,className:L("flex items-center gap-2 h-7 px-2 text-[11px] transition-colors",s?"border-l-2 border-primary bg-primary/[0.08] text-foreground rounded-r-md":"text-foreground-subtle hover:bg-surface-hover rounded-md",i),children:[u(t,{className:"h-3.5 w-3.5 shrink-0"}),u("span",{className:"truncate flex-1",children:e}),n!==void 0&&u(Hn,{className:"ml-auto text-[10px] px-1.5 py-0",children:n})]})}function xd({logo:e,sections:t,footer:r,onNavigate:n,className:s}){return v("nav",{className:L("bg-surface border-r border-border h-full flex flex-col",s),children:[e&&u("div",{className:"px-3 py-2 shrink-0",children:e}),u("div",{className:"flex-1 overflow-auto px-1 py-1",children:t.map((i,a)=>v("div",{className:L(a>0?"mt-3":""),children:[i.label&&u("span",{className:"text-[10px] text-foreground-disabled uppercase tracking-wider px-2 mb-1 block",children:i.label}),u("div",{className:"flex flex-col gap-0.5",onClick:n,children:i.items.map(l=>u(yd,{...l},l.href))})]},a))}),r&&r.length>0&&v("div",{className:"shrink-0 px-1 pb-1",children:[u(Gm,{className:"mb-1"}),u("div",{className:"flex flex-col gap-0.5",onClick:n,children:r.map(i=>u(yd,{...i},i.href))})]})]})}function k3({sidebar:e,header:t,mobileLogo:r,mobileActions:n,children:s,className:i}){const a=Ra(),[l,o]=_(!1);return v("div",{className:L("flex h-screen",i),children:[!a&&u(xd,{...e,className:L("w-44",e.className)}),a&&u(XE,{open:l,onClose:()=>o(!1),width:"w-64",children:u(xd,{...e,onNavigate:()=>o(!1),className:"w-full border-r-0"})}),v("div",{className:"flex flex-1 flex-col min-w-0",children:[a&&v("header",{className:"flex items-center h-12 border-b border-border px-3 shrink-0 bg-surface/80 backdrop-blur-sm",children:[u("button",{onClick:()=>o(!0),className:"p-1.5 -ml-1.5 rounded-md hover:bg-surface-hover text-foreground-muted transition-colors","aria-label":"Open menu",children:u(rE,{className:"h-5 w-5"})}),r&&u("div",{className:"flex-1 flex justify-center",children:r}),n&&u("div",{className:"shrink-0",children:n})]}),!a&&t&&v("header",{className:"flex items-center h-10 border-b border-border px-4 shrink-0",children:[t.breadcrumbs&&t.breadcrumbs.length>0&&u("nav",{className:"flex items-center gap-1 text-xs flex-1 min-w-0",children:t.breadcrumbs.map((c,d)=>{const h=d===t.breadcrumbs.length-1;return v("span",{className:"flex items-center gap-1",children:[d>0&&u(nr,{className:"h-3 w-3 text-foreground-subtle shrink-0"}),c.href&&!h?u("a",{href:c.href,className:"text-foreground-subtle hover:text-foreground transition-colors truncate",children:c.label}):u("span",{className:"text-foreground truncate",children:c.label})]},d)})}),t.actions&&u("div",{className:"flex items-center gap-2 ml-auto shrink-0",children:t.actions})]}),u("main",{className:"flex-1 overflow-auto p-4",children:s})]})]})}var vw={online:"bg-success",offline:"bg-danger",warning:"bg-warning",unknown:"bg-foreground-subtle"};function T3({title:e,subtitle:t,status:r,selected:n,onClick:s,badges:i,actions:a,offlineAction:l,className:o}){const c=r==="offline";return v("div",{onClick:s,className:L("w-full rounded-lg border p-3 text-left transition-colors",s&&"cursor-pointer",n?"border-primary bg-primary/10":"border-border bg-surface hover:bg-surface-hover",c&&!n&&"opacity-50",o),children:[v("div",{className:"flex items-center justify-between mb-2",children:[u("span",{className:"text-sm font-medium truncate",children:e}),r&&u("span",{className:L("h-2 w-2 rounded-full shrink-0",vw[r])})]}),t&&u("div",{className:"text-[11px] text-foreground-muted",children:t}),i&&i.length>0&&u("div",{className:"flex flex-wrap gap-1 mt-2",children:i.map((d,h)=>{const f=L("rounded px-1.5 py-0.5 text-[10px] flex items-center gap-0.5",n?"bg-primary/20":"bg-surface-hover",d.onClick&&"hover:opacity-80 transition-opacity cursor-pointer");return d.onClick?v("button",{onClick:p=>{p.stopPropagation(),d.onClick()},className:f,children:[d.icon,d.label]},h):v("span",{className:f,children:[d.icon,d.label]},h)})}),!c&&a&&a.length>0&&u("div",{className:"flex items-center gap-0.5 mt-2 -mb-1",children:a.map((d,h)=>u("button",{onClick:f=>{f.stopPropagation(),d.onClick()},className:"p-1 rounded hover:bg-surface-hover text-foreground-subtle hover:text-foreground transition-colors",title:d.label,"aria-label":d.label,children:d.icon},h))}),c&&l&&u("div",{className:"mt-2",onClick:d=>d.stopPropagation(),children:l})]})}function A3({children:e,minCardWidth:t=220,gap:r=3,className:n}){return u("div",{className:L("p-4 overflow-y-auto flex-1 content-start",n),style:{display:"grid",gridTemplateColumns:`repeat(auto-fill, minmax(${t}px, 1fr))`,gap:`${r*4}px`},children:e})}var bw="capability.binding-changed";function Qt(e,t){const[r,n]=_(null);return ae(()=>{if(t===null){n(null);return}let s=!1;const i=async()=>{try{const l=await e.deviceManager.getBindings.query({deviceId:t});s||n(l)}catch{s||n(l=>l)}};i();const a=e.live?.onEvent.subscribe({category:bw},{onData:l=>{const o=l.data?.source;if(!o){i();return}o.type==="device"&&o.id===t&&i()}});return()=>{s=!0,a?.unsubscribe()}},[e,t]),oe(()=>r?r0(e,r):null,[e,r])}function Tr(e){const t=q(n=>e?e.subscribe(()=>n()):()=>{},[e]),r=q(()=>e?.value,[e]);return mc(t,r,r)}function yw(e,t,r){const n=Qt(e,t);return Tr(n?r(n.state):void 0)}function _e(e){const t=Qt(e.trpc,e.deviceId),r=Tr(t!==null?e.slice(t):void 0),n=t!==null?e.cap(t):void 0,s=Tr(t!==null?t.state.deviceStatus:void 0),i=s?.online??!0,a=i?null:s?.lastChangedAt??null;return{dev:t,cap:n,slice:r,available:(e.requireFeature===void 0||(e.deviceFeatures??[]).includes(e.requireFeature))&&n!==void 0&&r!==void 0&&i,online:i,offlineSince:a}}var $s={[te.Camera]:{icon:pm,label:"Camera"},[te.Hub]:{icon:Nm,label:"Hub"},[te.Light]:{icon:Ic,label:"Light"},[te.Siren]:{icon:Pm,label:"Siren"},[te.Switch]:{icon:Sl,label:"Switch"},[te.Sensor]:{icon:ur,label:"Sensor"},[te.Thermostat]:{icon:_c,label:"Thermostat"},[te.Button]:{icon:mm,label:"Button"},[te.EventEmitter]:{icon:$r,label:"Event Emitter"},[te.Update]:{icon:vn,label:"Update"},[te.Generic]:{icon:pl,label:"Generic"},[te.Notifier]:{icon:_s,label:"Notifier"},[te.Script]:{icon:Rm,label:"Script"},[te.Automation]:{icon:PE,label:"Automation"},[te.Lock]:{icon:Rc,label:"Lock"},[te.Cover]:{icon:vS,label:"Cover"},[te.Valve]:{icon:cE,label:"Valve"},[te.Humidifier]:{icon:ME,label:"Humidifier"},[te.WaterHeater]:{icon:fS,label:"Water heater"},[te.Fan]:{icon:gl,label:"Fan"},[te.MediaPlayer]:{icon:sE,label:"Media player"},[te.AlarmPanel]:{icon:Mc,label:"Alarm panel"},[te.Control]:{icon:Pc,label:"Control"},[te.Presence]:{icon:eE,label:"Presence"},[te.Weather]:{icon:vm,label:"Weather"},[te.Vacuum]:{icon:bS,label:"Vacuum"},[te.LawnMower]:{icon:TE,label:"Lawn mower"},[te.Container]:{icon:pl,label:"Container"},[te.Image]:{icon:wm,label:"Image"}},Tl={[Le.Siren]:{icon:Pm,label:"Siren"},[Le.Floodlight]:{icon:Ic,label:"Floodlight"},[Le.Spotlight]:{icon:BS,label:"Spotlight"},[Le.PirSensor]:{icon:fE,label:"PIR sensor"},[Le.Chime]:{icon:_s,label:"Chime"},[Le.Autotrack]:{icon:Nc,label:"Auto-track"},[Le.Nightvision]:{icon:Na,label:"Night vision"},[Le.PrivacyMask]:{icon:Ca,label:"Privacy mask"},[Le.Doorbell]:{icon:OS,label:"Doorbell"},[Le.BinaryHelper]:{icon:Sl,label:"Binary helper"},[Le.MotionSensor]:{icon:GS,label:"Motion sensor"},[Le.ContactSensor]:{icon:Os,label:"Contact sensor"},[Le.LeakSensor]:{icon:bm,label:"Leak sensor"},[Le.SmokeSensor]:{icon:oS,label:"Smoke sensor"},[Le.COSensor]:{icon:ia,label:"CO sensor"},[Le.GasSensor]:{icon:$S,label:"Gas sensor"},[Le.TamperSensor]:{icon:Mc,label:"Tamper sensor"},[Le.VibrationSensor]:{icon:IE,label:"Vibration sensor"},[Le.ConnectivitySensor]:{icon:Fc,label:"Connectivity"},[Le.SoundSensor]:{icon:Oc,label:"Sound sensor"},[Le.BinarySensor]:{icon:Sl,label:"Binary sensor"},[Le.TemperatureSensor]:{icon:_c,label:"Temperature"},[Le.HumiditySensor]:{icon:Lc,label:"Humidity"},[Le.AmbientLightSensor]:{icon:Dc,label:"Ambient light"},[Le.PressureSensor]:{icon:xs,label:"Pressure"},[Le.PowerSensor]:{icon:$r,label:"Power"},[Le.EnergySensor]:{icon:$r,label:"Energy"},[Le.VoltageSensor]:{icon:$r,label:"Voltage"},[Le.CurrentSensor]:{icon:$r,label:"Current"},[Le.AirQualitySensor]:{icon:ia,label:"Air quality"},[Le.BatterySensor]:{icon:xs,label:"Battery"},[Le.NumericSensor]:{icon:zS,label:"Numeric sensor"},[Le.EnumSensor]:{icon:XS,label:"Enum sensor"},[Le.DateTimeSensor]:{icon:ml,label:"Date / time"},[Le.GenericSensor]:{icon:xs,label:"Sensor"},[Le.NumericControl]:{icon:Pc,label:"Numeric control"},[Le.SelectControl]:{icon:km,label:"Select control"},[Le.TextControl]:{icon:NE,label:"Text control"},[Le.DateTimeControl]:{icon:ml,label:"Date / time control"},[Le.MobilePushNotifier]:{icon:EE,label:"Mobile push"},[Le.MessagingNotifier]:{icon:nE,label:"Messaging"},[Le.EmailNotifier]:{icon:JS,label:"Email"},[Le.GenericNotifier]:{icon:_s,label:"Notifier"}},xw=new Set(Object.values(te)),Sw=new Set(Object.values(Le));function Ew(e){return xw.has(e)}function ww(e){return Sw.has(e)}function C3(e){return $s[e]}function N3(e){return Tl[e]}function Wc(e){return Ew(e)?$s[e]:$s[te.Generic]}function kw(e){return ww(e)?Tl[e]:Tl[Le.GenericSensor]}var Tw=Object.values(te).map(e=>({id:e,label:$s[e].label,icon:$s[e].icon}));function Aw(){return Tw}var Sd=["lock","climate","light","fan","cover","switch","sensor"];function Cw(e,t){if(t!==void 0){const r=e.find(n=>n.entityId===t);if(r!==void 0)return r}return[...e].sort((r,n)=>Ed(r.type)-Ed(n.type))[0]??null}function Ed(e){const t=Sd.indexOf(e);return t===-1?Sd.length:t}function Qc(e){return e.sourceInfo?.id??e.stableId}function Nw(e){return{id:e.id,entityId:Qc(e),type:e.type}}function Lw(e,t){if(t==null)return;const r=e.find(n=>n.id===t);return r===void 0?void 0:Qc(r)}function Js(e,t,r){return Cw(e.map(Nw),r!=null&&r!==""?r:Lw(e,t))}function L3(e){return e.parentDeviceId===null?"top-level":e.role?"accessory":"adopted"}var Iw={minimal:{showIntegrationIcon:!1,showParentBadge:!1,showSnapshot:!1,showBattery:!1,showStableId:!1,showId:!1,showSwitchToggle:!0,showChildrenAccordion:!1},compact:{showIntegrationIcon:!0,showParentBadge:!0,showSnapshot:!0,showBattery:!0,showStableId:!1,showId:!1,showSwitchToggle:!0,showChildrenAccordion:!0},expanded:{showIntegrationIcon:!1,showParentBadge:!0,showSnapshot:!0,showBattery:!0,showStableId:!0,showId:!0,showSwitchToggle:!0,showChildrenAccordion:!0}};function Rw(e){const t=Iw[e.variant??"compact"];return{showIntegrationIcon:e.showIntegrationIcon??t.showIntegrationIcon,showParentBadge:e.showParentBadge??t.showParentBadge,showSnapshot:e.showSnapshot??t.showSnapshot,showBattery:e.showBattery??t.showBattery,showStableId:e.showStableId??t.showStableId,showId:e.showId??t.showId,showSwitchToggle:e.showSwitchToggle??t.showSwitchToggle,showChildrenAccordion:e.showChildrenAccordion??t.showChildrenAccordion}}function lg(e){return e.role?kw(e.role).icon:Wc(e.type).icon}var cg={"native-snapshot":wm,"two-way-audio":Tm,"pan-tilt-zoom":Nc,"ptz-autotrack":ZS,"doorbell-button":Os,"motion-trigger":ur,"battery-operated":mS,rebootable:yl},ug={"native-snapshot":"Native snapshot","two-way-audio":"Two-way audio","pan-tilt-zoom":"Pan-Tilt-Zoom","ptz-autotrack":"PTZ autotrack","doorbell-button":"Doorbell button","motion-trigger":"Motion trigger","battery-operated":"Battery operated",rebootable:"Rebootable"},Mw={"native-snapshot":"snapshot",rebootable:"reboot","pan-tilt-zoom":"ptz","ptz-autotrack":"ptz-autotrack","two-way-audio":"intercom","motion-trigger":"motion-trigger"},dg=new Set(["camera","hub","nvr"]);function Pw(e){return!dg.has(e.type.toLowerCase())}function wd(e){return e.role?!0:!dg.has(e.type.toLowerCase())}function hg(e){return(e.features??[]).includes("motion-trigger")}function Dw(e,t){if(e.type!==te.Container)return e.online;const r=t??[];if(r.length===0)return e.online;const n=Js(r,e.linkDeviceId,e.primaryChildEntityId);if(n===null)return e.online;const s=r.find(i=>i.id===n.id);return s===void 0?e.online:s.online}function fg(e,t){if(e.type!==te.Container)return e.type;const r=t??[];if(r.length===0)return e.type;const n=Js(r,e.linkDeviceId,e.primaryChildEntityId);if(n===null)return e.type;const s=r.find(i=>i.id===n.id);return s===void 0?e.type:s.type}function _w(e,t){if(e.type!==te.Container)return e;const r=t??[];if(r.length===0)return e;const n=Js(r,e.linkDeviceId,e.primaryChildEntityId);return n===null?e:r.find(s=>s.id===n.id)??e}function Ow(e){if(e.length<=24)return e;const t=e.lastIndexOf(":");if(t>=0&&t<e.length-4)return e.slice(t+1);const r=e.split("-");if(r.length>2){const n=r.slice(-2).join("-");if(n.length>=6)return n}return`…${e.slice(-18)}`}function kd({trpc:e,accessoryChildren:t,adoptedChildren:r,onNavigate:n}){return v("div",{className:"border-t border-border-subtle/50",children:[r.length>0&&u(Td,{trpc:e,label:"Adopted devices",rows:r,onNavigate:n}),t.length>0&&u(Td,{trpc:e,label:"Accessories",rows:t,onNavigate:n})]})}function Td({trpc:e,label:t,rows:r,onNavigate:n}){return v("div",{children:[u("div",{className:"px-3 pt-1.5 pb-1 text-[9px] font-semibold uppercase tracking-wide text-foreground-subtle",children:t}),u("ul",{children:r.map(s=>u(Fw,{trpc:e,child:s,onNavigate:n},s.id))})]})}function Fw({trpc:e,child:t,onNavigate:r}){const n=!t.disabled,s=n&&Pw(t),i=n&&hg(t);return u("li",{children:v("div",{onClick:a=>{a.stopPropagation(),r(t.id)},className:"w-full flex items-center gap-2 px-3 py-1.5 text-left hover:bg-surface-hover transition-colors cursor-pointer",children:[u(lg(t),{className:"h-3 w-3 text-foreground-subtle flex-shrink-0"}),u("span",{className:"text-[10.5px] text-foreground flex-1 truncate",children:t.name}),i&&u(Bw,{trpc:e,deviceId:t.id,features:t.features}),s&&u($w,{trpc:e,deviceId:t.id}),u("span",{className:L("h-1.5 w-1.5 rounded-full flex-shrink-0",t.online?"bg-success":"bg-foreground-subtle/40"),title:t.online?"Online":"Offline"})]})})}function $w({trpc:e,deviceId:t}){const{dev:r,cap:n,slice:s,available:i}=_e({trpc:e,deviceId:t,cap:h=>h.switch,slice:h=>h.state.switch}),[a,l]=_(!1);if(r!==null&&!n)return null;const o=s?.on===!0,c={transform:o?"translateX(14px)":"translateX(2px)"},d=async h=>{if(h.stopPropagation(),!(a||!i||!n)){l(!0);try{await n.setState({on:!o})}finally{l(!1)}}};return u("button",{type:"button",onClick:h=>{d(h)},disabled:a||!i,className:L("relative inline-flex h-4 w-7 items-center rounded-full border transition-colors flex-shrink-0",o?"bg-success/30 border-success/50":"bg-surface-hover border-border",a&&"opacity-60",!i&&"opacity-40 cursor-not-allowed"),title:i?o?"Turn off":"Turn on":"Awaiting state…","aria-pressed":o,children:u("span",{className:L("absolute h-3 w-3 rounded-full transition-all",o?"bg-success":"bg-foreground-subtle"),style:c})})}function Bw({trpc:e,deviceId:t,features:r}){const{dev:n,cap:s,slice:i,available:a}=_e({trpc:e,deviceId:t,cap:h=>h.motionTrigger,slice:h=>h.state.motionTrigger,requireFeature:"motion-trigger",deviceFeatures:r}),[l,o]=_(!1);if(n!==null&&!s)return null;const c=i?.enabled===!0,d=async h=>{if(h.stopPropagation(),!(l||!a||!s)){o(!0);try{await s.setMotionTrigger({enabled:!c})}finally{o(!1)}}};return u("button",{type:"button",onClick:h=>{d(h)},disabled:l||!a,className:L("inline-flex h-4 w-4 items-center justify-center rounded transition-colors flex-shrink-0",c?"text-primary bg-primary/10":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover",(l||!a)&&"opacity-50"),title:a?c?"Motion-trigger: on (click to disable)":"Motion-trigger: off (click to enable)":"Awaiting state…","aria-pressed":c,children:u(ur,{className:"h-2.5 w-2.5"})})}var Uw=[],pg=hr(null);function Ad({value:e,children:t}){return u(pg.Provider,{value:e,children:t})}function qc(e){return ct(pg)?.get(e)??Uw}var Cd={up:{pan:0,tilt:1},down:{pan:0,tilt:-1},left:{pan:-1,tilt:0},right:{pan:1,tilt:0},"up-left":{pan:-1,tilt:1},"up-right":{pan:1,tilt:1},"down-left":{pan:-1,tilt:-1},"down-right":{pan:1,tilt:-1}};function mg(e,t,r){const n=r?.defaultSpeed??.5,s=r?.pulseMs??250,i=r?.enabled??!0,a=Qt(e,i?t:null)?.ptz,[l,o]=_([]),[c,d]=_(null),[h,f]=_(!1),[p,m]=_(null),g=q(async()=>{if(!(!i||!a))try{o(await a.getPresets({}))}catch(S){if(ta(S))return;m(S instanceof Error?S.message:String(S))}},[a,i]),b=q(async()=>{if(!(!i||!a))try{d(await a.getOptions({}))}catch(S){if(ta(S))return;m(S instanceof Error?S.message:String(S))}},[a,i]);ae(()=>{g(),b()},[g,b]);const y=q(async S=>{if(!(!i||!a)){m(null),f(!0);try{return await S()}catch(E){m(E instanceof Error?E.message:String(E));return}finally{f(!1)}}},[i,a]);return{move:q(async(S,E)=>{if(!a)return;const k=Cd[S],T=E??n;await y(async()=>{await a.move({pan:k.pan,tilt:k.tilt,speed:T}),await new Promise(A=>setTimeout(A,s)),await a.stop({})})},[a,n,s,y]),startContinuous:q(async(S,E)=>{if(!a)return;const k=Cd[S],T=E??n;await y(()=>a.continuousMove({pan:k.pan,tilt:k.tilt,speed:T}))},[a,n,y]),stopContinuous:q(async()=>{a&&await y(()=>a.stop({}))},[a,y]),zoom:q(async(S,E)=>{if(!a)return;const k=S==="in"?1:-1,T=E??n;await y(async()=>{await a.move({zoom:k,speed:T}),await new Promise(A=>setTimeout(A,s)),await a.stop({})})},[a,n,s,y]),goHome:q(async()=>{a&&await y(()=>a.goHome({}))},[a,y]),goToPreset:q(async S=>{a&&await y(()=>a.goToPreset({presetId:S}))},[a,y]),savePreset:q(async S=>{if(a)return y(async()=>{const E=new Set(l.map(A=>Number(A.id)).filter(A=>Number.isInteger(A)&&A>=0));let k=0;for(;E.has(k);)k+=1;const T=String(k);return await a.savePreset({presetId:T,name:S}),await g(),T})},[a,l,g,y]),deletePreset:q(async S=>{a&&await y(async()=>{await a.deletePreset({presetId:S}),await g()})},[a,g,y]),presets:l,refreshPresets:g,options:c,busy:h,error:p}}function ii({direction:e,icon:t,disabled:r,className:n,variant:s,onMove:i,onStart:a,onStop:l}){const[o,c]=_(null),[d,h]=_(!1),f=q(y=>{if(r)return;y.currentTarget.setPointerCapture(y.pointerId),c(Date.now()),h(!1);const S=setTimeout(()=>{h(!0),a(e)},250);y.currentTarget.dataset.timer=String(S)},[e,r,a]),p=q(y=>{const S=Number(y.currentTarget.dataset.timer);S&&clearTimeout(S),y.currentTarget.dataset.timer="",d?l():o!==null&&i(e),c(null),h(!1)},[d,e,i,l,o]),m=q(y=>{const S=Number(y.currentTarget.dataset.timer);S&&clearTimeout(S),y.currentTarget.dataset.timer="",d&&l(),c(null),h(!1)},[d,l]),g=s==="panel"?"h-9 w-9":"h-7 w-7",b=s==="panel"?"h-4 w-4":"h-3.5 w-3.5";return u("button",{type:"button",disabled:r,onPointerDown:f,onPointerUp:p,onPointerCancel:m,className:L("flex items-center justify-center rounded transition-colors disabled:opacity-40",s==="panel"?"text-foreground hover:bg-surface-hover active:bg-surface-hover/80":"text-white hover:bg-white/15 active:bg-white/25",g,n),title:e,children:u(t,{className:b})})}function gg({controls:e,mode:t="overlay",showPresets:r,showZoom:n=!0,showHome:s=!0,className:i}){const{move:a,startContinuous:l,stopContinuous:o,zoom:c,goHome:d,goToPreset:h,savePreset:f,deletePreset:p,presets:m,options:g,busy:b,error:y}=e,S=is(),[E,k]=_(!1),[T,A]=_(""),N=(r??m.length>0)&&m.length>0,C=t==="panel",M=C&&(g?.supportsPresets??!1),P=g?.maxPresets!==void 0&&m.length>=g.maxPresets,D=q(async()=>{const R=T.trim();!R||b||P||await f(R)!==void 0&&A("")},[T,b,P,f]),$=q(async(R,O)=>{await S({title:"Delete preset",message:`Delete PTZ preset "${O}"? This removes it from the camera.`,confirmLabel:"Delete",variant:"danger"})&&await p(R)},[S,p]),B=C?"flex flex-col items-stretch gap-2 w-full h-full p-3":"pointer-events-auto absolute top-3 right-3 z-10 flex flex-col items-end gap-2",j=L(C?"flex items-center gap-3 rounded-lg p-2":"flex items-center gap-2 rounded-lg border border-white/30 bg-zinc-900/90 backdrop-blur-md p-2 shadow-lg shadow-black/40",b&&"ring-1 ring-primary/40"),U=C?"h-9 w-9":"h-7 w-7",F=C?"h-4 w-4":"h-3.5 w-3.5",Y=C?"text-foreground hover:bg-surface-hover":"text-white hover:bg-white/15",I=C?"h-12 w-px bg-border mx-1":"h-12 w-px bg-white/15 mx-1";return v("div",{className:L(B,i),children:[y&&v("div",{className:"rounded bg-danger/90 px-2 py-1 text-[10px] font-medium text-white shadow-lg max-w-[200px] self-center",children:["PTZ: ",y]}),v("div",{className:L(j,C&&"justify-center"),children:[v("div",{className:"grid grid-cols-3 gap-0.5",children:[u("span",{"aria-hidden":!0,className:C?"h-9 w-9":"h-7 w-7"}),u(ii,{direction:"up",icon:hS,variant:t,onMove:a,onStart:l,onStop:o}),u("span",{"aria-hidden":!0,className:C?"h-9 w-9":"h-7 w-7"}),u(ii,{direction:"left",icon:cS,variant:t,onMove:a,onStart:l,onStop:o}),u("span",{"aria-hidden":!0,className:C?"h-9 w-9":"h-7 w-7"}),u(ii,{direction:"right",icon:uS,variant:t,onMove:a,onStart:l,onStop:o}),u("span",{"aria-hidden":!0,className:C?"h-9 w-9":"h-7 w-7"}),u(ii,{direction:"down",icon:lS,variant:t,onMove:a,onStart:l,onStop:o}),u("span",{"aria-hidden":!0,className:C?"h-9 w-9":"h-7 w-7"})]}),(n||s)&&u("div",{className:I}),v("div",{className:"flex flex-col gap-0.5",children:[n&&v(Ie,{children:[u("button",{type:"button",onClick:()=>c("in"),disabled:b,title:"Zoom in",className:L("flex items-center justify-center rounded disabled:opacity-40",U,Y),children:u(Om,{className:F})}),u("button",{type:"button",onClick:()=>c("out"),disabled:b,title:"Zoom out",className:L("flex items-center justify-center rounded disabled:opacity-40",U,Y),children:u(Fm,{className:F})})]}),s&&u("button",{type:"button",onClick:()=>d(),disabled:b,title:"Go home",className:L("flex items-center justify-center rounded disabled:opacity-40",U,Y),children:u(ns,{className:F})})]}),N&&v("div",{className:"relative",children:[v("button",{type:"button",onClick:()=>k(R=>!R),disabled:b,className:L("flex items-center gap-1 rounded px-2 text-[10px] disabled:opacity-40",C?"h-9 text-foreground hover:bg-surface-hover":"h-7 text-white hover:bg-white/15"),title:"Presets",children:["Presets",u(yt,{className:L("h-3 w-3 transition-transform",E&&"rotate-180")})]}),E&&u("div",{className:L("absolute right-0 top-full mt-1 min-w-[140px] rounded-lg shadow-xl py-1 z-20",C?"bg-surface border border-border":"border border-white/30 bg-zinc-900/95 backdrop-blur-md"),children:m.map(R=>v("div",{className:L("group flex items-center",C?"hover:bg-surface-hover":"hover:bg-white/15"),children:[u("button",{type:"button",onClick:()=>{h(R.id),k(!1)},disabled:b,className:L("flex-1 px-3 py-1.5 text-left text-[10px] disabled:opacity-40",C?"text-foreground":"text-white"),children:R.name||R.id}),M&&u("button",{type:"button",onClick:()=>void $(R.id,R.name||R.id),disabled:b,title:`Delete preset ${R.name||R.id}`,className:L("mr-1 flex h-5 w-5 shrink-0 items-center justify-center rounded","text-foreground-subtle hover:bg-danger/15 hover:text-danger disabled:opacity-40"),children:u(bt,{className:"h-3 w-3"})})]},R.id))})]})]}),M&&v("div",{className:"flex flex-col gap-1 rounded-lg border border-border p-2",children:[v("div",{className:"flex items-center gap-2",children:[u("input",{type:"text",value:T,onChange:R=>A(R.target.value),onKeyDown:R=>{R.key==="Enter"&&D()},disabled:b||P,placeholder:"New preset name",maxLength:64,className:L("min-w-0 flex-1 rounded border border-border bg-surface px-2 py-1 text-[11px] text-foreground","placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary/50","disabled:opacity-40")}),v("button",{type:"button",onClick:()=>void D(),disabled:b||P||T.trim().length===0,title:P?`Camera preset limit reached (${g?.maxPresets})`:"Save current position as a new preset",className:L("flex h-7 shrink-0 items-center gap-1 rounded px-2 text-[10px] font-medium","bg-primary/15 text-primary hover:bg-primary/25 disabled:opacity-40"),children:[u(gn,{className:"h-3 w-3"}),"Save current position"]})]}),P&&v("span",{className:"text-[10px] text-foreground-subtle",children:["Camera preset limit reached (",g?.maxPresets,"). Delete a preset to add a new one."]})]})]})}var Gw="fill",Hw="right",Vw="center";function la({align:e,children:t,className:r,...n}){return e==="fit"?u("div",{...n,className:L("inline-flex items-center",r),children:t}):u("div",{...n,className:L("w-[140px] shrink-0 flex items-center gap-1.5",e==="center"?"justify-center":"justify-end",e==="fill"?"[&>*:last-child]:w-full":"",r),children:t})}function I3({value:e,unit:t}){return v("span",{className:"text-sm text-foreground",children:[e,t?u("span",{"data-unit":!0,className:"ml-0.5 text-[11px] text-foreground-subtle",children:t}):null]})}function vg({value:e,unit:t,onDelta:r}){return v("div",{className:"flex h-8 w-full overflow-hidden rounded-lg border border-border bg-surface",children:[u("button",{type:"button","aria-label":"Decrement",className:"w-9 shrink-0 bg-surface-hover text-base text-foreground",onClick:()=>r(-1),children:"−"}),v("span",{className:"flex flex-1 items-center justify-center gap-0.5 border-x border-border/60 text-sm",children:[e,t?u("span",{"data-unit":!0,className:"text-[11px] text-foreground-subtle",children:t}):null]}),u("button",{type:"button","aria-label":"Increment",className:"w-9 shrink-0 bg-surface-hover text-base text-foreground",onClick:()=>r(1),children:"+"})]})}function jw({on:e,targetLabel:t,onConfirm:r}){const n=ne(null),s=ne(!1);return v("div",{className:L("relative h-12 w-full rounded-full border flex items-center",e?"bg-emerald-50 border-emerald-200 pl-4":"bg-amber-50 border-amber-200 justify-end pr-4"),children:[u("span",{className:"text-xs font-semibold opacity-60",children:t}),u("span",{"data-testid":"slide-thumb",className:"absolute top-1 left-1 h-10 w-14 rounded-[19px] bg-surface shadow flex items-center justify-center",onPointerDown:i=>{i.currentTarget.setPointerCapture?.(i.pointerId),n.current=i.clientX,s.current=!1},onPointerMove:i=>{n.current!==null&&Math.abs(i.clientX-n.current)>40&&(s.current=!0)},onPointerUp:()=>{s.current&&r(),s.current=!1,n.current=null},onPointerCancel:()=>{s.current=!1,n.current=null}})]})}var Kw=2,Nd=270,zw=315;function Ww(e){const t=(e-135+360)%360;return t>Nd?t<=zw?1:0:t/Nd}function $i({fraction:e,color:t,knobTopPx:r,onDragFraction:n}){const s=-135+e*270,i=ne(null),[a,l]=_(!1),o=n!==void 0,c=r??Kw,d=p=>{n!==void 0&&(p.preventDefault(),p.stopPropagation(),p.currentTarget.setPointerCapture?.(p.pointerId),l(!0))},h=p=>{if(n===void 0||!a)return;const m=i.current;if(m===null)return;const g=m.getBoundingClientRect(),b=g.left+g.width/2,y=g.top+g.height/2;n(Ww(Math.atan2(p.clientY-y,p.clientX-b)*180/Math.PI))},f=p=>{n!==void 0&&(p.currentTarget.releasePointerCapture?.(p.pointerId),l(!1))};return u("div",{ref:i,className:"absolute inset-0",style:{transform:`rotate(${s}deg)`},children:u("div",{className:L("absolute left-1/2 h-5 w-5 -translate-x-1/2 rounded-full bg-white shadow",o&&(a?"cursor-grabbing":"cursor-grab")),style:{top:c,border:`3px solid ${t}`},...o?{onPointerDown:d,onPointerMove:h,onPointerUp:f,onPointerCancel:f}:{}})})}function Al({fraction:e,color:t}){return v("div",{className:"relative h-2 w-full rounded-full bg-border",children:[u("div",{className:"absolute left-0 top-0 h-2 rounded-full",style:{width:`${e*100}%`,background:t??"var(--color-primary)"}}),u("div",{className:"absolute -top-1 h-4 w-4 rounded-full bg-white shadow",style:{left:`calc(${e*100}% - 8px)`}})]})}function Qw({trpc:e,deviceId:t}){const r=Qt(e,t),n=r!==null?r.button:void 0;if(n===void 0)return null;const s=()=>{n.press({deviceId:t})};return v("button",{type:"button","aria-label":"Press",title:"Press",onClick:i=>{i.stopPropagation(),s()},className:L("inline-flex h-5 items-center gap-1 rounded px-1.5 text-xs","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"),children:[u(Cm,{className:"h-3 w-3"}),u("span",{children:"Press"})]})}function qw({trpc:e,deviceId:t}){const r=Qt(e,t),n=r!==null?r.button:void 0;return n===void 0?null:v("div",{className:"flex flex-col items-center justify-center gap-4 rounded-lg border border-border bg-surface p-6",children:[u("button",{type:"button","aria-label":"Press button",onClick:()=>{n.press({deviceId:t})},className:L("inline-flex h-14 w-14 items-center justify-center rounded-full","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors","shadow-md"),children:u(Cm,{className:"h-6 w-6"})}),u("span",{className:"text-sm font-medium text-foreground",children:"Press"})]})}var Yw=4e3;function Ld(e){if(e!==void 0)return e!==null&&typeof e=="object"&&"lastChangedAt"in e&&typeof e.lastChangedAt=="number"?e.lastChangedAt:e}function Ze(e,t){const r=t?.enabled!==!1,n=t?.timeoutMs??Yw,[s,i]=_(void 0),a=ne(void 0),l=ne(void 0),o=ne(!1),c=ne(void 0),d=q(()=>{c.current!==void 0&&(clearTimeout(c.current),c.current=void 0),a.current=void 0,o.current=!1,l.current=void 0,i(void 0)},[]);ae(()=>{if(!r||!o.current)return;const f=Ld(e),p=l.current;f!==void 0&&f!==p&&d()}),ae(()=>()=>{c.current!==void 0&&clearTimeout(c.current)},[]);const h=q(f=>{if(!r)return;c.current!==void 0&&(clearTimeout(c.current),c.current=void 0);const p=a.current??e;if(p!==void 0){const m={...p,...f};a.current=m,i(m)}l.current=Ld(e),o.current=!0,c.current=setTimeout(d,n)},[r,e,d,n]);return r?{display:s!==void 0?s:e,applyOptimistic:h}:{display:e,applyOptimistic:()=>{}}}function Pa(e){switch(e){case"opening":return{up:"accent",stop:"neutral",down:"neutral"};case"closing":return{up:"neutral",stop:"neutral",down:"accent"};case"open":return{up:"filled",stop:"neutral",down:"neutral"};case"closed":return{up:"neutral",stop:"neutral",down:"filled"};default:return{up:"neutral",stop:"neutral",down:"neutral"}}}function Xw(e){switch(e){case"accent":return"bg-primary text-primary-foreground";case"filled":return"bg-primary/15 text-primary";case"neutral":return""}}function Ja({label:e,busy:t,variant:r,onClick:n,children:s}){return u("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:i=>{i.stopPropagation(),n()},className:L("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",Xw(r),t&&"opacity-40 cursor-not-allowed"),children:s})}function Zw({trpc:e,deviceId:t,optimistic:r}){const{cap:n,slice:s,available:i}=_e({trpc:e,deviceId:t,cap:h=>h.cover,slice:h=>h.state.cover}),{display:a,applyOptimistic:l}=Ze(s,{enabled:r??!0});if(n===void 0)return null;const o=Pa(a?.state),c=!i,d=(h,f)=>{c||!h||(f!==void 0&&l(f),h({}))};return v("div",{className:"inline-flex items-center gap-1",children:[u(Ja,{label:"Open",busy:c,variant:o.up,onClick:()=>d(n?.open,{state:"opening"}),children:u(dn,{className:"h-3.5 w-3.5"})}),u(Ja,{label:"Stop",busy:c,variant:o.stop,onClick:()=>d(n?.stop,{state:"stopped"}),children:u(Cr,{className:"h-3 w-3"})}),u(Ja,{label:"Close",busy:c,variant:o.down,onClick:()=>d(n?.close,{state:"closing"}),children:u(yt,{className:"h-3.5 w-3.5"})}),a!==void 0&&a.position!==null&&v("span",{className:"tabular-nums text-xs text-foreground-subtle ml-1",children:[a.position,"%"]})]})}function eo({label:e,busy:t,variant:r,onClick:n,children:s}){return u("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:i=>{i.stopPropagation(),n()},className:L("inline-flex h-10 w-10 items-center justify-center rounded-md text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",r==="accent"&&"bg-primary text-primary-foreground hover:bg-primary/90",r==="filled"&&"bg-primary/15 text-primary",t&&"opacity-40 cursor-not-allowed"),children:s})}function bg(){return v(Ie,{children:[u("div",{"aria-hidden":"true",className:"absolute inset-y-0 left-1/2 w-px -translate-x-px bg-white/60"}),u("div",{"aria-hidden":"true",className:"absolute inset-x-0 top-1/2 h-px -translate-y-px bg-white/60"})]})}function Jw({position:e,interactive:t,onSetPosition:r}){const n=(1-e/100)*100,s=ne(null),i=ne(!1),a=ne(null),l=f=>{const p=s.current;if(p===null)return e;const m=p.getBoundingClientRect();if(m.height<=0)return e;const g=(f-m.top)/m.height,b=Math.round(100-g*100);return Math.min(100,Math.max(0,b))},o=f=>{if(r===void 0)return;const p=l(f);a.current!==p&&(a.current=p,r(p))},c=f=>{t&&(f.stopPropagation(),f.preventDefault(),i.current=!0,a.current=null,f.currentTarget.setPointerCapture(f.pointerId),o(f.clientY))},d=f=>{!t||!i.current||(f.stopPropagation(),o(f.clientY))},h=f=>{!t||!i.current||(f.stopPropagation(),i.current=!1,a.current=null,f.currentTarget.hasPointerCapture(f.pointerId)&&f.currentTarget.releasePointerCapture(f.pointerId))};return v("div",{ref:s,"data-testid":"cover-window",...t?{"aria-label":"Drag to set position",role:"slider","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":e}:{"aria-hidden":"true"},onPointerDown:t?c:void 0,onPointerMove:t?d:void 0,onPointerUp:t?h:void 0,onPointerCancel:t?h:void 0,className:L("relative w-28 h-36 rounded border-2 border-amber-700/60 bg-gradient-to-b from-sky-200 to-sky-50 overflow-hidden flex-shrink-0",t&&"cursor-ns-resize touch-none select-none"),style:{boxShadow:"inset 0 0 0 2px rgba(255,255,255,.5)"},children:[u(bg,{}),u("div",{className:"absolute inset-x-0 top-0 transition-all duration-200",style:{height:`${n}%`,background:"repeating-linear-gradient(#c9cdd2, #c9cdd2 6px, #b7bcc2 6px, #b7bcc2 8px)",borderBottom:n>0?"1px solid #9aa":"none"}}),v("div",{"data-testid":"cover-lever",className:L("absolute inset-x-0 h-4 flex items-center justify-center gap-1 z-10 transition-all duration-200",t&&"cursor-grab active:cursor-grabbing"),style:{top:`calc(${n}% - 8px)`},children:[u("div",{className:"absolute -inset-x-1.5 h-full rounded-lg bg-slate-600 shadow-md"}),u("span",{className:"h-1 w-1 rounded-full bg-white/70 relative z-10","aria-hidden":"true"}),u("span",{className:"h-1 w-1 rounded-full bg-white/70 relative z-10","aria-hidden":"true"}),u("span",{className:"h-1 w-1 rounded-full bg-white/70 relative z-10","aria-hidden":"true"}),v("span",{"data-testid":"cover-position-pct",className:"absolute left-full ml-2 text-xs font-semibold text-foreground tabular-nums whitespace-nowrap",children:[e,"%"]})]})]})}function ek({isOpen:e}){return v("div",{"data-testid":"cover-window","aria-hidden":"true",className:"relative w-28 h-36 rounded border-2 border-amber-700/60 bg-gradient-to-b from-sky-200 to-sky-50 overflow-hidden flex-shrink-0",style:{boxShadow:"inset 0 0 0 2px rgba(255,255,255,.5)"},children:[u(bg,{}),!e&&u("div",{className:"absolute inset-0",style:{background:"repeating-linear-gradient(#c9cdd2, #c9cdd2 6px, #b7bcc2 6px, #b7bcc2 8px)"}})]})}function tk({trpc:e,deviceId:t,features:r,optimistic:n}){const{cap:s,slice:i,available:a}=_e({trpc:e,deviceId:t,cap:S=>S.cover,slice:S=>S.state.cover}),{display:l,applyOptimistic:o}=Ze(i,{enabled:n??!0});if(s===void 0)return null;const c=!a,d=(r??[]).includes(Ft.CoverPositionable),h=(r??[]).includes(Ft.CoverTilt),f=Pa(l?.state),p=l?.position??null,m=p!==null,g=l?.state==="open"||l?.state==="opening",b=(S,E)=>{c||!S||(E!==void 0&&o(E),S({}))},y=S=>{c||(o({position:S}),s?.setPosition({position:S}))};return v("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:[v("div",{className:"flex items-center gap-6",children:[m?u(Jw,{position:p,interactive:d,onSetPosition:d?y:void 0}):u(ek,{isOpen:g}),v("div",{className:"flex flex-col gap-3 flex-1",children:[m&&v("div",{className:"flex items-baseline gap-1",children:[u("span",{className:"text-3xl font-semibold tabular-nums text-foreground",children:p}),u("span",{className:"text-base text-foreground-subtle",children:"%"}),u("span",{className:"text-xs text-foreground-subtle ml-1",children:"open"})]}),!m&&u("div",{className:"flex items-baseline gap-1",children:u("span",{className:"text-3xl font-semibold capitalize text-foreground",children:l?.state??"—"})}),v("div",{className:"flex items-center gap-2",children:[u(eo,{label:"Open",busy:c,variant:f.up,onClick:()=>b(s?.open,{state:"opening"}),children:u(dn,{className:"h-5 w-5"})}),u(eo,{label:"Stop",busy:c,variant:f.stop,onClick:()=>b(s?.stop,{state:"stopped"}),children:u(Cr,{className:"h-4 w-4"})}),u(eo,{label:"Close",busy:c,variant:f.down,onClick:()=>b(s?.close,{state:"closing"}),children:u(yt,{className:"h-5 w-5"})})]})]})]}),d&&v("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[u("span",{className:"w-12 shrink-0",children:"Position"}),u("input",{"aria-label":"Position",type:"range",min:0,max:100,step:1,value:p??0,disabled:c,className:"flex-1",onChange:S=>{y(Number(S.target.value))}}),v("span",{className:"w-8 text-right tabular-nums",children:[p??"—","%"]})]}),!d&&p!==null&&v("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[u("span",{className:"w-12 shrink-0",children:"Position"}),u("input",{"aria-label":"Position",type:"range",min:0,max:100,step:1,value:p,disabled:!0,readOnly:!0,className:"flex-1 opacity-60"}),v("span",{className:"w-8 text-right tabular-nums",children:[p,"%"]})]}),h&&v("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[u("span",{className:"w-12 shrink-0",children:"Tilt"}),u("input",{"aria-label":"Tilt position",type:"range",min:0,max:100,step:1,value:l?.tiltPosition??0,disabled:c,className:"flex-1",onChange:S=>{const E=Number(S.target.value);o({tiltPosition:E}),c||s?.setTiltPosition({tiltPosition:E})}}),v("span",{className:"w-8 text-right tabular-nums",children:[l?.tiltPosition??"—","%"]})]})]})}function rk(e){return u("span",{className:"text-foreground-subtle text-xs select-none","aria-hidden":"true",children:"—"})}function yg(e){return u("div",{className:"rounded border border-border bg-surface-subtle px-3 py-2 text-xs text-foreground-subtle",children:"Controls coming soon"})}var R3=x.accessories.setChildHidden.useMutation,M3=x.accessories.getStatus.useQuery,P3=x.addonPages.listPages.useQuery,nk=x.addons.list.useQuery,D3=x.addons.getLogs.useQuery,_3=x.addons.listPackages.useQuery,O3=x.addons.installPackage.useMutation,F3=x.addons.installFromWorkspace.useMutation,$3=x.addons.isWorkspaceAvailable.useQuery,B3=x.addons.listWorkspacePackages.useQuery,U3=x.addons.uninstallPackage.useMutation,G3=x.addons.reloadPackages.useMutation,H3=x.addons.searchAvailable.useQuery,V3=x.addons.listUpdates.useQuery,j3=x.addons.updatePackage.useMutation,K3=x.addons.rollbackPackage.useMutation,z3=x.addons.forceRefresh.useMutation,W3=x.addons.restartServer.useMutation,Q3=x.addons.getLastRestart.useQuery,q3=x.addons.listFrameworkPackages.useQuery,Y3=x.addons.listCapabilityProviders.useQuery,X3=x.addons.setCapabilityProviderEnabled.useMutation,Z3=x.addons.updateFrameworkPackage.useMutation,J3=x.addons.startBulkUpdate.useMutation,e4=x.addons.getBulkUpdateState.useQuery,t4=x.addons.cancelBulkUpdate.useMutation,r4=x.addons.listActiveBulkUpdates.useQuery,n4=x.addons.getVersions.useQuery,s4=x.addons.restartAddon.useMutation,i4=x.addons.retryLoad.useMutation,a4=x.addons.getAutoUpdateSettings.useQuery,o4=x.addons.setAutoUpdateSettings.useMutation,l4=x.addons.getAddonAutoUpdate.useQuery,c4=x.addons.setAddonAutoUpdate.useMutation,u4=x.addons.applyAutoUpdateToAll.useMutation,d4=x.addons.custom.useMutation,h4=x.addons.onAddonLogs.useSubscription,f4=x.addonSettings.getGlobalSettings.useQuery,p4=x.addonSettings.updateGlobalSettings.useMutation,m4=x.addonSettings.getDeviceSettings.useQuery,g4=x.addonSettings.updateDeviceSettings.useMutation,sk=x.addonWidgets.listWidgets.useQuery,v4=x.airQualitySensor.getStatus.useQuery,b4=x.alarmPanel.arm.useMutation,y4=x.alarmPanel.disarm.useMutation,x4=x.alarmPanel.trigger.useMutation,S4=x.alarmPanel.getStatus.useQuery,E4=x.alerts.emit.useMutation,w4=x.alerts.update.useMutation,k4=x.alerts.list.useQuery,T4=x.alerts.getUnreadCount.useQuery,A4=x.alerts.markRead.useMutation,C4=x.alerts.markAllRead.useMutation,N4=x.alerts.dismiss.useMutation,L4=x.ambientLightSensor.getStatus.useQuery,I4=x.audioAnalysis.resolveDeviceSettings.useQuery,R4=x.audioAnalysis.getDeviceSettingsContribution.useQuery,M4=x.audioAnalysis.getDeviceLiveContribution.useQuery,P4=x.audioAnalysis.applyDeviceSettingsPatch.useMutation,D4=x.audioAnalyzer.analyseChunk.useMutation,_4=x.audioAnalyzer.classify.useQuery,O4=x.audioAnalyzer.isReady.useQuery,F4=x.audioAnalyzer.dispose.useMutation,$4=x.audioAnalyzer.reprobeAudioEngine.useMutation,B4=x.audioCodec.listSupportedCodecs.useQuery,U4=x.audioCodec.canHandle.useQuery,G4=x.audioCodec.createDecodeSession.useMutation,H4=x.audioCodec.createEncodeSession.useMutation,V4=x.audioCodec.closeSession.useMutation,j4=x.audioCodec.pushEncodedFrame.useMutation,K4=x.audioCodec.pullPcm.useQuery,z4=x.audioCodec.pushPcm.useMutation,W4=x.audioCodec.pullEncoded.useQuery,Q4=x.audioCodec.flushEncode.useMutation,q4=x.audioCodec.listActiveSessions.useQuery,Y4=x.audioMetrics.getCurrentSnapshot.useQuery,X4=x.audioMetrics.getHistory.useQuery,Z4=x.automationControl.enable.useMutation,J4=x.automationControl.disable.useMutation,eF=x.automationControl.trigger.useMutation,tF=x.automationControl.getStatus.useQuery,rF=x.backup.listDestinations.useQuery,nF=x.backup.trigger.useMutation,sF=x.backup.list.useQuery,iF=x.backup.listLocations.useQuery,aF=x.backup.getEntries.useQuery,oF=x.backup.restore.useMutation,lF=x.backup.delete.useMutation,cF=x.backup.listArchives.useQuery,uF=x.backup.upsertDestinationPolicy.useMutation,dF=x.backup.previewSchedule.useQuery,hF=x.battery.wakeForStream.useMutation,fF=x.battery.getStatus.useQuery,pF=x.binary.getStatus.useQuery,mF=x.brightness.setBrightness.useMutation,gF=x.brightness.getStatus.useQuery,vF=x.broker.list.useQuery,bF=x.broker.get.useQuery,yF=x.broker.listProviders.useQuery,xF=x.broker.add.useMutation,SF=x.broker.remove.useMutation,EF=x.broker.testConnection.useMutation,wF=x.broker.getSettings.useQuery,kF=x.broker.setSettings.useMutation,TF=x.broker.getBrokerConfig.useQuery,AF=x.broker.getSettingsSchema.useQuery,CF=x.broker.testSettings.useMutation,NF=x.broker.publish.useMutation,LF=x.broker.subscribe.useMutation,IF=x.broker.unsubscribe.useMutation,RF=x.broker.getState.useQuery,MF=x.broker.getStatus.useQuery,PF=x.button.press.useMutation,DF=x.cameraCredentials.getCredentials.useQuery,_F=x.cameraCredentials.getStatus.useQuery,OF=x.cameraPipelineConfig.getDeviceSettingsContribution.useQuery,FF=x.cameraPipelineConfig.getDeviceLiveContribution.useQuery,$F=x.cameraPipelineConfig.applyDeviceSettingsPatch.useMutation,BF=x.cameraStreams.getCameraStreams.useQuery,UF=x.cameraStreams.getBrokerStreams.useQuery,ik=x.cameraStreams.getRtspEntries.useQuery,GF=x.cameraStreams.getProfileRtspEntries.useQuery,HF=x.cameraStreams.pickStream.useQuery,VF=x.carbonMonoxide.getStatus.useQuery,jF=x.climateControl.setMode.useMutation,KF=x.climateControl.setFanMode.useMutation,zF=x.climateControl.setPreset.useMutation,WF=x.climateControl.setTarget.useMutation,QF=x.climateControl.setTargetRange.useMutation,qF=x.climateControl.setTargetHumidity.useMutation,YF=x.climateControl.getStatus.useQuery,XF=x.color.setColor.useMutation,ZF=x.color.getStatus.useQuery,JF=x.connectivity.getStatus.useQuery,e$=x.consumables.reset.useMutation,t$=x.consumables.getStatus.useQuery,r$=x.contact.getStatus.useQuery,n$=x.control.setValue.useMutation,s$=x.control.getStatus.useQuery,i$=x.cover.open.useMutation,a$=x.cover.close.useMutation,o$=x.cover.stop.useMutation,l$=x.cover.setPosition.useMutation,c$=x.cover.setTiltPosition.useMutation,u$=x.cover.getStatus.useQuery,d$=x.decoder.supportsCodec.useQuery,h$=x.decoder.getInfo.useQuery,f$=x.decoder.createSession.useQuery,p$=x.decoder.destroySession.useQuery,m$=x.decoder.pushPacket.useQuery,g$=x.decoder.openStream.useQuery,v$=x.decoder.pullFrames.useQuery,b$=x.decoder.pullHandles.useQuery,y$=x.decoder.getFrame.useQuery,x$=x.decoder.getShmStats.useQuery,S$=x.decoder.updateConfig.useQuery,E$=x.decoder.getStats.useQuery,w$=x.decoder.listActiveSessions.useQuery,k$=x.decoder.reprobeHwaccel.useMutation,T$=x.detectionPipeline.getDeviceSettingsContribution.useQuery,A$=x.detectionPipeline.getDeviceLiveContribution.useQuery,C$=x.detectionPipeline.applyDeviceSettingsPatch.useMutation,N$=x.deviceAdoption.listCandidateFilters.useQuery,L$=x.deviceAdoption.listCandidates.useQuery,I$=x.deviceAdoption.getCandidate.useQuery,R$=x.deviceAdoption.refresh.useMutation,M$=x.deviceAdoption.adopt.useMutation,P$=x.deviceAdoption.release.useMutation,D$=x.deviceAdoption.resync.useMutation,_$=x.deviceAdoption.getStatus.useQuery,O$=x.deviceDiscovery.listDiscovered.useQuery,F$=x.deviceDiscovery.refreshDiscovery.useMutation,$$=x.deviceDiscovery.adoptDevice.useMutation,B$=x.deviceDiscovery.releaseDevice.useMutation,U$=x.deviceDiscovery.getStatus.useQuery,ak=x.deviceExport.getStatus.useQuery,ok=x.deviceExport.listSupportedDeviceKinds.useQuery,lk=x.deviceExport.listExposedDevices.useQuery,ck=x.deviceExport.exposeDevice.useMutation,uk=x.deviceExport.unexposeDevice.useMutation,G$=x.deviceExport.getDeviceSettingsContribution.useQuery,H$=x.deviceExport.getDeviceLiveContribution.useQuery,V$=x.deviceExport.applyDeviceSettingsPatch.useMutation,j$=x.deviceManager.allocateDeviceId.useMutation,K$=x.deviceManager.registerDevice.useMutation,z$=x.deviceManager.removeDevice.useMutation,W$=x.deviceManager.persistConfig.useMutation,Q$=x.deviceManager.loadConfig.useQuery,q$=x.deviceManager.loadRuntimeState.useQuery,Y$=x.deviceManager.loadMeta.useQuery,X$=x.deviceManager.setName.useMutation,Z$=x.deviceManager.setLocation.useMutation,J$=x.deviceManager.setType.useMutation,eB=x.deviceManager.setIntegrationId.useMutation,tB=x.deviceManager.setLinkDeviceId.useMutation,rB=x.deviceManager.setPrimaryChildEntityId.useMutation,nB=x.deviceManager.setChildLayout.useMutation,sB=x.deviceManager.setDeviceLinks.useMutation,iB=x.deviceManager.getWireableFields.useQuery,aB=x.deviceManager.setRole.useMutation,oB=x.deviceManager.applyInitialMeta.useMutation,lB=x.deviceManager.setMetadata.useMutation,cB=x.deviceManager.listLocations.useQuery,uB=x.deviceManager.addLocation.useMutation,dB=x.deviceManager.removeLocation.useMutation,hB=x.deviceManager.setDisabled.useMutation,fB=x.deviceManager.listPersistedByAddon.useQuery,xg=x.deviceManager.listAll.useQuery,Sg=x.deviceManager.getDevice.useQuery,pB=x.deviceManager.getChildren.useQuery,mB=x.deviceManager.getStreamSources.useQuery,gB=x.deviceManager.getConfigSchema.useQuery,vB=x.deviceManager.getSettingsSchema.useQuery,bB=x.deviceManager.updateConfig.useMutation,yB=x.deviceManager.enable.useMutation,xB=x.deviceManager.disable.useMutation,SB=x.deviceManager.remove.useMutation,EB=x.deviceManager.removeByIntegration.useMutation,wB=x.deviceManager.getStreamProfileMap.useQuery,kB=x.deviceManager.setStreamProfileMap.useMutation,TB=x.deviceManager.probeStreams.useMutation,AB=x.deviceManager.getBindings.useQuery,CB=x.deviceManager.getAllBindings.useQuery,NB=x.deviceManager.setWrapperActive.useMutation,LB=x.deviceManager.listWrappersForCap.useQuery,IB=x.deviceManager.listBindableCapsForDeviceType.useQuery,RB=x.deviceManager.getDeviceSettingsAggregate.useQuery,MB=x.deviceManager.getDeviceLiveInfoAggregate.useQuery,PB=x.deviceManager.getDeviceAggregate.useQuery,DB=x.deviceManager.runDeviceAction.useMutation,_B=x.deviceManager.updateDeviceField.useMutation,OB=x.deviceManager.updateDeviceFieldsBatch.useMutation,FB=x.deviceManager.discoverDevices.useMutation,$B=x.deviceManager.adoptDevice.useMutation,BB=x.deviceManager.getCreationSchema.useQuery,UB=x.deviceManager.createDevice.useMutation,GB=x.deviceManager.testCreationField.useMutation,HB=x.deviceManager.adoptionListCandidates.useQuery,VB=x.deviceManager.adoptionRefresh.useMutation,jB=x.deviceManager.adoptionAdopt.useMutation,KB=x.deviceManager.adoptionRelease.useMutation,zB=x.deviceManager.testField.useMutation,WB=x.deviceManager.getDeviceStatusAggregate.useQuery,QB=x.deviceOps.getStreamSources.useQuery,qB=x.deviceOps.getConfigEntries.useQuery,YB=x.deviceOps.setConfig.useMutation,XB=x.deviceOps.runAction.useMutation,ZB=x.deviceOps.removeDevice.useMutation,JB=x.deviceOps.getSettingsSchema.useQuery,eU=x.deviceOps.getRawState.useQuery,tU=x.deviceProvider.start.useMutation,rU=x.deviceProvider.stop.useMutation,nU=x.deviceProvider.getStatus.useQuery,sU=x.deviceProvider.getDevices.useQuery,iU=x.deviceProvider.supportsDiscovery.useQuery,aU=x.deviceProvider.discoverDevices.useMutation,oU=x.deviceProvider.adoptDiscoveredDevice.useMutation,lU=x.deviceProvider.supportsManualCreation.useQuery,cU=x.deviceProvider.getChildCreationSchema.useQuery,uU=x.deviceProvider.createDevice.useMutation,dU=x.deviceProvider.testCreationField.useMutation,hU=x.deviceState.getSnapshot.useQuery,fU=x.deviceState.getCapSlice.useQuery,pU=x.deviceState.getAllSnapshots.useQuery,mU=x.deviceState.setCapSlice.useMutation,gU=x.deviceStatus.getStatus.useQuery,vU=x.doorbell.getStatus.useQuery,bU=x.enumSensor.getStatus.useQuery,yU=x.eventEmitter.getStatus.useQuery,xU=x.events.getEvents.useQuery,SU=x.events.getEventThumbnail.useQuery,EU=x.events.getEventClipUrl.useQuery,wU=x.fanControl.setPercentage.useMutation,kU=x.fanControl.setPreset.useMutation,TU=x.fanControl.setDirection.useMutation,AU=x.fanControl.setOscillating.useMutation,CU=x.fanControl.getStatus.useQuery,NU=x.featureProbe.getStatus.useQuery,LU=x.flood.getStatus.useQuery,IU=x.gas.getStatus.useQuery,RU=x.humidifier.setOn.useMutation,MU=x.humidifier.setTargetHumidity.useMutation,PU=x.humidifier.setMode.useMutation,DU=x.humidifier.getStatus.useQuery,_U=x.humiditySensor.getStatus.useQuery,OU=x.image.getStatus.useQuery,FU=x.integrations.list.useQuery,$U=x.integrations.get.useQuery,BU=x.integrations.getByAddonId.useQuery,UU=x.integrations.create.useMutation,GU=x.integrations.update.useMutation,HU=x.integrations.delete.useMutation,VU=x.integrations.getSettings.useQuery,jU=x.integrations.setSettings.useMutation,KU=x.integrations.getAvailableTypes.useQuery,zU=x.integrations.testConnection.useMutation,WU=x.intercom.startSession.useMutation,QU=x.intercom.handleAnswer.useMutation,qU=x.intercom.stopSession.useMutation,YU=x.intercom.startTalkSession.useMutation,XU=x.intercom.pushTalkAudio.useMutation,ZU=x.intercom.endTalkSession.useMutation,JU=x.intercom.getStatus.useQuery,e6=x.lawnMowerControl.startMowing.useMutation,t6=x.lawnMowerControl.pause.useMutation,r6=x.lawnMowerControl.dock.useMutation,n6=x.lawnMowerControl.getStatus.useQuery,s6=x.localNetwork.list.useQuery,i6=x.localNetwork.getPreferred.useQuery,a6=x.localNetwork.getConnectionEndpoints.useQuery,o6=x.localNetwork.getAllowedAddresses.useQuery,l6=x.localNetwork.setAllowedAddresses.useMutation,c6=x.localNetwork.resetAllowlistToBestMatch.useMutation,u6=x.lockControl.lock.useMutation,d6=x.lockControl.unlock.useMutation,h6=x.lockControl.open.useMutation,f6=x.lockControl.getStatus.useQuery,p6=x.mediaPlayer.play.useMutation,m6=x.mediaPlayer.pause.useMutation,g6=x.mediaPlayer.stop.useMutation,v6=x.mediaPlayer.next.useMutation,b6=x.mediaPlayer.previous.useMutation,y6=x.mediaPlayer.seek.useMutation,x6=x.mediaPlayer.setVolume.useMutation,S6=x.mediaPlayer.setMute.useMutation,E6=x.mediaPlayer.setShuffle.useMutation,w6=x.mediaPlayer.setRepeat.useMutation,k6=x.mediaPlayer.selectSource.useMutation,T6=x.mediaPlayer.playMedia.useMutation,A6=x.mediaPlayer.getStatus.useQuery,C6=x.meshNetwork.getStatus.useQuery,N6=x.meshNetwork.join.useMutation,L6=x.meshNetwork.startLogin.useMutation,I6=x.meshNetwork.leave.useMutation,R6=x.meshNetwork.logout.useMutation,M6=x.meshNetwork.listPeers.useQuery,P6=x.meshNetwork.testConnection.useMutation,D6=x.metricsProvider.collectSnapshot.useQuery,_6=x.metricsProvider.getCached.useQuery,O6=x.metricsProvider.getCurrent.useQuery,F6=x.metricsProvider.getDiskSpace.useQuery,$6=x.metricsProvider.getGpuInfo.useQuery,B6=x.metricsProvider.getCpuTemperature.useQuery,U6=x.metricsProvider.getProcessStats.useQuery,G6=x.metricsProvider.listAddonInstances.useQuery,H6=x.metricsProvider.getAddonStats.useQuery,V6=x.metricsProvider.listNodeProcesses.useQuery,j6=x.metricsProvider.killProcess.useMutation,K6=x.motion.isDetected.useQuery,z6=x.motion.getStatus.useQuery,W6=x.motionDetection.analyze.useMutation,Q6=x.motionDetection.removeCamera.useMutation,q6=x.motionDetection.reset.useMutation,Y6=x.motionDetection.getDeviceSettingsContribution.useQuery,X6=x.motionDetection.getDeviceLiveContribution.useQuery,Z6=x.motionDetection.applyDeviceSettingsPatch.useMutation,J6=x.motionTrigger.setMotionTrigger.useMutation,e8=x.motionTrigger.getStatus.useQuery,t8=x.motionZones.getOptions.useQuery,r8=x.motionZones.setZone.useMutation,n8=x.motionZones.getStatus.useQuery,s8=x.mqttBroker.listBrokers.useQuery,i8=x.mqttBroker.getBrokerConfig.useQuery,a8=x.mqttBroker.addBroker.useMutation,o8=x.mqttBroker.removeBroker.useMutation,l8=x.mqttBroker.testConnection.useMutation,c8=x.mqttBroker.startEmbeddedBroker.useMutation,u8=x.mqttBroker.stopEmbeddedBroker.useMutation,d8=x.mqttBroker.getStatus.useQuery,h8=x.nativeObjectDetection.setEnabled.useMutation,f8=x.nativeObjectDetection.getStatus.useQuery,p8=x.networkAccess.start.useMutation,m8=x.networkAccess.stop.useMutation,g8=x.networkAccess.getEndpoint.useQuery,v8=x.networkAccess.getStatus.useQuery,b8=x.networkAccess.listEndpoints.useQuery,y8=x.networkQuality.getDeviceStats.useQuery,x8=x.networkQuality.getAllStats.useQuery,S8=x.networkQuality.reportClientStats.useMutation,E8=x.nodes.topology.useQuery,w8=x.nodes.deployAddon.useMutation,k8=x.nodes.undeployAddon.useMutation,T8=x.nodes.restartAddon.useMutation,A8=x.nodes.restartProcess.useMutation,C8=x.nodes.restartNode.useMutation,N8=x.nodes.shutdownNode.useMutation,L8=x.nodes.renameNode.useMutation,I8=x.nodes.clusterAddonStatus.useQuery,R8=x.nodes.getCapUsageGraph.useQuery,M8=x.nodes.getNodeAddons.useQuery,P8=x.nodes.setProcessLogLevel.useMutation,D8=x.nodes.executeQuery.useMutation,_8=x.notificationOutput.send.useMutation,O8=x.notificationOutput.sendTest.useMutation,F8=x.notifier.send.useMutation,$8=x.notifier.cancel.useMutation,B8=x.notifier.getStatus.useQuery,U8=x.numericSensor.getStatus.useQuery,G8=x.osd.setOverlay.useMutation,H8=x.osd.getStatus.useQuery,V8=x.pipelineAnalytics.getActiveTracks.useQuery,j8=x.pipelineAnalytics.getTrack.useQuery,K8=x.pipelineAnalytics.listTracks.useQuery,z8=x.pipelineAnalytics.clearTracks.useMutation,dk=x.pipelineAnalytics.getMotionEvents.useQuery,hk=x.pipelineAnalytics.getObjectEvents.useQuery,fk=x.pipelineAnalytics.getAudioEvents.useQuery,pk=x.pipelineAnalytics.getEventDensity.useQuery,W8=x.pipelineAnalytics.pruneEventsBefore.useMutation,Q8=x.pipelineAnalytics.getEventMedia.useQuery,q8=x.pipelineAnalytics.getTrackMedia.useQuery,Y8=x.pipelineAnalytics.getDeviceSettingsContribution.useQuery,X8=x.pipelineAnalytics.getDeviceLiveContribution.useQuery,Z8=x.pipelineAnalytics.applyDeviceSettingsPatch.useMutation,J8=x.pipelineExecutor.getAvailableEngines.useQuery,eG=x.pipelineExecutor.getSelectedEngine.useQuery,tG=x.pipelineExecutor.getDefaultSteps.useQuery,rG=x.pipelineExecutor.reprobeEngine.useMutation,nG=x.pipelineExecutor.getVideoPipelineSteps.useQuery,sG=x.pipelineExecutor.setVideoPipelineSteps.useMutation,iG=x.pipelineExecutor.getSchema.useQuery,aG=x.pipelineExecutor.getGlobalSteps.useQuery,oG=x.pipelineExecutor.getGlobalPipelineConfig.useQuery,lG=x.pipelineExecutor.getOrchestratorConfigSchema.useQuery,cG=x.pipelineExecutor.listTemplates.useQuery,uG=x.pipelineExecutor.saveTemplate.useMutation,dG=x.pipelineExecutor.updateTemplate.useMutation,hG=x.pipelineExecutor.deleteTemplate.useMutation,fG=x.pipelineExecutor.getCapabilities.useQuery,pG=x.pipelineExecutor.getAddonModels.useQuery,mG=x.pipelineExecutor.downloadModel.useMutation,gG=x.pipelineExecutor.deleteModel.useMutation,vG=x.pipelineExecutor.detect.useQuery,bG=x.pipelineExecutor.runPipeline.useMutation,yG=x.pipelineExecutor.runPipelineBatch.useMutation,xG=x.pipelineExecutor.cacheFrameInPool.useMutation,SG=x.pipelineExecutor.inferCached.useMutation,EG=x.pipelineExecutor.uncacheFrame.useMutation,wG=x.pipelineExecutor.getEffectiveTuning.useQuery,kG=x.pipelineExecutor.listLoadedEngines.useQuery,TG=x.pipelineExecutor.spinEngine.useMutation,AG=x.pipelineExecutor.killEngine.useMutation,CG=x.pipelineExecutor.listReferenceImages.useQuery,NG=x.pipelineExecutor.getReferenceImage.useQuery,LG=x.pipelineExecutor.getReferenceAudioFiles.useQuery,IG=x.pipelineExecutor.getReferenceAudio.useQuery,RG=x.pipelineExecutor.getAudioCapabilities.useQuery,MG=x.pipelineExecutor.runAudioTest.useMutation,PG=x.pipelineExecutor.getDetectionConfigSchema.useQuery,DG=x.pipelineOrchestrator.assignPipeline.useMutation,_G=x.pipelineOrchestrator.unassignPipeline.useMutation,OG=x.pipelineOrchestrator.rebalance.useMutation,FG=x.pipelineOrchestrator.getPipelineAssignments.useQuery,$G=x.pipelineOrchestrator.getPipelineAssignment.useQuery,BG=x.pipelineOrchestrator.getAgentLoad.useQuery,UG=x.pipelineOrchestrator.getGlobalMetrics.useQuery,GG=x.pipelineOrchestrator.getCameraMetrics.useQuery,HG=x.pipelineOrchestrator.getCapabilityBindings.useQuery,VG=x.pipelineOrchestrator.setCapabilityBinding.useMutation,jG=x.pipelineOrchestrator.assignDecoder.useMutation,KG=x.pipelineOrchestrator.unassignDecoder.useMutation,zG=x.pipelineOrchestrator.getDecoderAssignments.useQuery,WG=x.pipelineOrchestrator.assignAudio.useMutation,QG=x.pipelineOrchestrator.unassignAudio.useMutation,qG=x.pipelineOrchestrator.getAudioAssignment.useQuery,YG=x.pipelineOrchestrator.getAudioNodeLoad.useQuery,XG=x.pipelineOrchestrator.getAudioAssignments.useQuery,ZG=x.pipelineOrchestrator.getDecoderAssignment.useQuery,JG=x.pipelineOrchestrator.getAgentSettings.useQuery,e9=x.pipelineOrchestrator.listAgentSettings.useQuery,t9=x.pipelineOrchestrator.setAgentAddonDefaults.useMutation,r9=x.pipelineOrchestrator.removeAgentSettings.useMutation,n9=x.pipelineOrchestrator.getCameraSettings.useQuery,s9=x.pipelineOrchestrator.setCameraStepToggle.useMutation,i9=x.pipelineOrchestrator.getCameraStepOverrides.useQuery,a9=x.pipelineOrchestrator.setCameraStepOverride.useMutation,o9=x.pipelineOrchestrator.setCameraPipelineForAgent.useMutation,l9=x.pipelineOrchestrator.resolvePipeline.useQuery,c9=x.pipelineOrchestrator.listTemplates.useQuery,u9=x.pipelineOrchestrator.saveTemplate.useMutation,d9=x.pipelineOrchestrator.updateTemplate.useMutation,h9=x.pipelineOrchestrator.deleteTemplate.useMutation,f9=x.pipelineOrchestrator.getDeviceSettingsContribution.useQuery,p9=x.pipelineOrchestrator.getDeviceLiveContribution.useQuery,m9=x.pipelineOrchestrator.applyDeviceSettingsPatch.useMutation,g9=x.pipelineRunner.attachCamera.useMutation,v9=x.pipelineRunner.detachCamera.useMutation,b9=x.pipelineRunner.reportMotion.useMutation,y9=x.pipelineRunner.getLocalLoad.useQuery,x9=x.pipelineRunner.getLocalMetrics.useQuery,S9=x.pipelineRunner.getCameraMetrics.useQuery,E9=x.pipelineRunner.getAllCameraMetrics.useQuery,w9=x.pipelineRunner.getLocalCameras.useQuery,k9=x.powerMeter.getStatus.useQuery,T9=x.presence.getStatus.useQuery,A9=x.pressureSensor.getStatus.useQuery,C9=x.privacyMask.getOptions.useQuery,N9=x.privacyMask.setMask.useMutation,L9=x.privacyMask.getStatus.useQuery,I9=x.ptz.move.useMutation,R9=x.ptz.continuousMove.useMutation,M9=x.ptz.stop.useMutation,P9=x.ptz.getPresets.useQuery,D9=x.ptz.goToPreset.useMutation,_9=x.ptz.savePreset.useMutation,O9=x.ptz.deletePreset.useMutation,F9=x.ptz.getOptions.useQuery,$9=x.ptz.goHome.useMutation,B9=x.ptz.getPosition.useQuery,U9=x.ptz.setAutofocus.useMutation,G9=x.ptz.getStatus.useQuery,mk=x.ptzAutotrack.getStatus.useQuery,gk=x.ptzAutotrack.setEnabled.useMutation,H9=x.ptzAutotrack.getSettings.useQuery,vk=x.ptzAutotrack.setSettings.useMutation,V9=x.reboot.reboot.useMutation,Eg=x.recording.getAvailability.useQuery,j9=x.recording.getPlaybackManifest.useQuery,K9=x.recording.getStorageUsage.useQuery,bk=x.recording.getDeviceConfig.useQuery,yk=x.recording.setDeviceConfig.useMutation,xk=x.recording.rescanStorage.useMutation,z9=x.recording.pruneFootage.useMutation,Sk=x.recording.getStatus.useQuery,W9=x.recording.getDeviceSettingsContribution.useQuery,Q9=x.recording.getDeviceLiveContribution.useQuery,q9=x.recording.applyDeviceSettingsPatch.useMutation,Y9=x.scriptRunner.run.useMutation,X9=x.scriptRunner.stop.useMutation,Z9=x.scriptRunner.getStatus.useQuery,J9=x.settingsStore.get.useQuery,e7=x.settingsStore.set.useMutation,t7=x.settingsStore.query.useQuery,r7=x.settingsStore.insert.useMutation,n7=x.settingsStore.update.useMutation,s7=x.settingsStore.delete.useMutation,i7=x.settingsStore.count.useQuery,a7=x.settingsStore.histogram.useQuery,o7=x.settingsStore.isEmpty.useQuery,l7=x.settingsStore.declareCollection.useMutation,c7=x.smoke.getStatus.useQuery,u7=x.snapshot.getSnapshot.useQuery,d7=x.snapshot.invalidateCache.useMutation,h7=x.snapshot.getStatus.useQuery,f7=x.snapshot.getDeviceSettingsContribution.useQuery,p7=x.snapshot.getDeviceLiveContribution.useQuery,m7=x.snapshot.applyDeviceSettingsPatch.useMutation,g7=x.snapshotProvider.supportsDevice.useQuery,v7=x.snapshotProvider.getSnapshot.useQuery,b7=x.storage.resolve.useQuery,y7=x.storage.write.useMutation,x7=x.storage.read.useQuery,S7=x.storage.exists.useQuery,E7=x.storage.list.useQuery,w7=x.storage.delete.useMutation,k7=x.storage.getAvailableSpace.useQuery,T7=x.storage.beginUpload.useMutation,A7=x.storage.writeChunk.useMutation,C7=x.storage.finalizeUpload.useMutation,N7=x.storage.abortUpload.useMutation,L7=x.storage.beginDownload.useMutation,I7=x.storage.readChunk.useQuery,R7=x.storage.endDownload.useMutation,M7=x.storage.listLocations.useQuery,P7=x.storage.getDefaultLocation.useQuery,D7=x.storage.listLocationDeclarations.useQuery,_7=x.storage.upsertLocation.useMutation,O7=x.storage.deleteLocation.useMutation,F7=x.storage.testLocation.useQuery,$7=x.storage.listProviders.useQuery,B7=x.storage.testConfig.useQuery,U7=x.streamBroker.publishCameraStream.useMutation,G7=x.streamBroker.retractCameraStream.useMutation,H7=x.streamBroker.assignProfile.useMutation,V7=x.streamBroker.unassignProfile.useMutation,j7=x.streamBroker.listAllCameraStreams.useQuery,K7=x.streamBroker.listAllProfileSlots.useQuery,z7=x.streamBroker.getBrokerStats.useQuery,W7=x.streamBroker.listClients.useQuery,Q7=x.streamBroker.killClient.useMutation,q7=x.streamBroker.restartProfile.useMutation,Y7=x.streamBroker.getStreamUrl.useQuery,X7=x.streamBroker.getStreamWithCodec.useMutation,Z7=x.streamBroker.releaseStreamWithCodec.useMutation,J7=x.streamBroker.subscribeAudioChunks.useMutation,eH=x.streamBroker.pullAudioChunks.useQuery,tH=x.streamBroker.unsubscribeAudioChunks.useMutation,rH=x.streamBroker.subscribeFrames.useMutation,nH=x.streamBroker.pullFrameHandles.useQuery,sH=x.streamBroker.unsubscribeFrames.useMutation,iH=x.streamBroker.setPreBufferDuration.useMutation,aH=x.streamBroker.getPreBufferInfo.useQuery,oH=x.streamBroker.getRtspPort.useQuery,lH=x.streamBroker.getAllRtspEntries.useQuery,cH=x.streamBroker.getRtspEntry.useQuery,uH=x.streamBroker.regenerateRtspToken.useMutation,dH=x.streamBroker.setRtspEnabled.useMutation,hH=x.streamBroker.isRtspEnabled.useQuery,fH=x.streamBroker.getDeviceSettingsContribution.useQuery,pH=x.streamBroker.getDeviceLiveContribution.useQuery,mH=x.streamBroker.applyDeviceSettingsPatch.useMutation,gH=x.streamCatalog.getCatalog.useQuery,vH=x.streamParams.getOptions.useQuery,bH=x.streamParams.setProfile.useMutation,yH=x.streamParams.getConfigSchema.useQuery,xH=x.streamParams.getStatus.useQuery,SH=x.switch.setState.useMutation,EH=x.switch.getStatus.useQuery,wH=x.system.info.useQuery,kH=x.system.health.useQuery,TH=x.system.featureFlags.useQuery,AH=x.system.networkAddresses.useQuery,CH=x.system.getRetentionConfig.useQuery,NH=x.system.setRetentionConfig.useMutation,LH=x.system.forceRetentionCleanup.useMutation,IH=x.tamper.getStatus.useQuery,RH=x.temperatureSensor.getStatus.useQuery,MH=x.toast.onToast.useSubscription,PH=x.turnProvider.getTurnServers.useQuery,DH=x.update.installUpdate.useMutation,_H=x.update.getStatus.useQuery,OH=x.userManagement.listUsers.useQuery,FH=x.userManagement.createUser.useMutation,$H=x.userManagement.updateUser.useMutation,BH=x.userManagement.deleteUser.useMutation,UH=x.userManagement.resetPassword.useMutation,GH=x.userManagement.setUserScopes.useMutation,HH=x.userManagement.validateCredentials.useMutation,VH=x.userManagement.listApiKeys.useQuery,jH=x.userManagement.createApiKey.useMutation,KH=x.userManagement.revokeApiKey.useMutation,zH=x.userManagement.validateApiKey.useMutation,WH=x.userManagement.createScopedToken.useMutation,QH=x.userManagement.revokeScopedToken.useMutation,qH=x.userManagement.validateScopedToken.useQuery,YH=x.userManagement.listScopedTokens.useQuery,XH=x.userManagement.setupTotp.useMutation,ZH=x.userManagement.confirmTotp.useMutation,JH=x.userManagement.disableTotp.useMutation,eV=x.userManagement.getTotpStatus.useQuery,tV=x.userManagement.verifyTotp.useMutation,rV=x.userManagement.oauthIssueCode.useMutation,nV=x.userManagement.oauthExchangeCode.useMutation,sV=x.userManagement.oauthRefresh.useMutation,iV=x.userManagement.oauthVerifyAccessToken.useQuery,aV=x.userManagement.listOauthSessions.useQuery,oV=x.userManagement.revokeOauthSession.useMutation,lV=x.vacuumControl.start.useMutation,cV=x.vacuumControl.pause.useMutation,uV=x.vacuumControl.stop.useMutation,dV=x.vacuumControl.returnToBase.useMutation,hV=x.vacuumControl.locate.useMutation,fV=x.vacuumControl.setFanSpeed.useMutation,pV=x.vacuumControl.getStatus.useQuery,mV=x.valve.open.useMutation,gV=x.valve.close.useMutation,vV=x.valve.stop.useMutation,bV=x.valve.setPosition.useMutation,yV=x.valve.getStatus.useQuery,xV=x.vibration.getStatus.useQuery,SV=x.waterHeater.setTargetTemp.useMutation,EV=x.waterHeater.setOperationMode.useMutation,wV=x.waterHeater.setAway.useMutation,kV=x.waterHeater.getStatus.useQuery,TV=x.weather.getStatus.useQuery,AV=x.webrtcSession.listStreams.useQuery,CV=x.webrtcSession.createSession.useMutation,NV=x.webrtcSession.handleOffer.useMutation,LV=x.webrtcSession.handleAnswer.useMutation,IV=x.webrtcSession.addIceCandidate.useMutation,RV=x.webrtcSession.getIceCandidates.useQuery,MV=x.webrtcSession.closeSession.useMutation,PV=x.webrtcSession.hasAdaptiveBitrate.useQuery,DV=x.webrtcSession.getSessionState.useQuery,_V=x.zoneAnalytics.getCurrentSnapshot.useQuery,OV=x.zoneAnalytics.getZoneHistory.useQuery,FV=x.zoneAnalytics.getCameraHistory.useQuery,$V=x.zoneAnalytics.getUnzonedHistory.useQuery,BV=x.zoneRules.listRules.useQuery,UV=x.zoneRules.setRules.useMutation,GV=x.zones.listZones.useQuery,HV=x.zones.addZone.useMutation,VV=x.zones.removeZone.useMutation,jV=x.zones.updateZone.useMutation;function Ss(e,t){return t!==void 0?e.toFixed(t):Number.isInteger(e)?String(e):e.toFixed(1)}var wg={kind:"binary",field:"on",onLabel:"Low",offLabel:"Normal"};function kg(e){return e==="battery-sensor"}function Tg(e,t){if(!Cg(e))return!1;const r=e[t];if(typeof r!="number")return!1;const n=e.lastFetchedAt;return!(r===0&&n===0)}var Ag={"temperature-sensor":{kind:"numeric",field:"celsius",canonicalUnit:"°C",getSliceHandle:e=>e.temperatureSensor},"humidity-sensor":{kind:"numeric",field:"percent",canonicalUnit:"%",getSliceHandle:e=>e.humiditySensor},"ambient-light-sensor":{kind:"numeric",field:"lux",canonicalUnit:"lx",getSliceHandle:e=>e.ambientLightSensor},"pressure-sensor":{kind:"numeric",field:"hpa",canonicalUnit:"hPa",getSliceHandle:e=>e.pressureSensor},"numeric-sensor":{kind:"numeric",field:"value",getSliceHandle:e=>e.numericSensor},"power-sensor":{kind:"numeric",field:"watts",canonicalUnit:"W",getSliceHandle:e=>e.powerMeter},"energy-sensor":{kind:"numeric",field:"kwhTotal",canonicalUnit:"kWh",getSliceHandle:e=>e.powerMeter},"voltage-sensor":{kind:"numeric",field:"volts",canonicalUnit:"V",getSliceHandle:e=>e.powerMeter},"current-sensor":{kind:"numeric",field:"amps",canonicalUnit:"A",getSliceHandle:e=>e.powerMeter},"battery-sensor":{kind:"numeric",field:"value",canonicalUnit:"%",getSliceHandle:e=>e.numericSensor},"generic-sensor":{kind:"numeric",field:"value",getSliceHandle:e=>e.numericSensor},"motion-sensor":{kind:"binary",field:"detected",onLabel:"Detected",offLabel:"Clear",getSliceHandle:e=>e.motion},"pir-sensor":{kind:"binary",field:"detected",onLabel:"Detected",offLabel:"Clear",getSliceHandle:e=>e.motion},"contact-sensor":{kind:"binary",field:"entryOpen",onLabel:"Open",offLabel:"Closed",getSliceHandle:e=>e.contact},"smoke-sensor":{kind:"binary",field:"detected",onLabel:"Smoke!",offLabel:"Clear",getSliceHandle:e=>e.smoke},"leak-sensor":{kind:"binary",field:"flooded",onLabel:"Leak!",offLabel:"Dry",getSliceHandle:e=>e.flood},"co-sensor":{kind:"binary",field:"detected",onLabel:"CO!",offLabel:"Clear",getSliceHandle:e=>e.carbonMonoxide},"binary-sensor":{kind:"binary",field:"on",onLabel:"On",offLabel:"Off",getSliceHandle:e=>e.binary},presence:{kind:"presence",getSliceHandle:e=>e.presence},"enum-sensor":{kind:"string",getSliceHandle:e=>e.enumSensor},"datetime-sensor":{kind:"datetime",format:"datetime",getSliceHandle:e=>e.enumSensor}};function Cg(e){return typeof e=="object"&&e!==null}function Ek(e){return typeof e=="object"&&e!==null}function wk(e){return typeof e=="object"&&e!==null&&"state"in e&&typeof e.state=="string"}function Es(e){return typeof e=="object"&&e!==null&&"value"in e&&typeof e.value=="string"}function Ng(e){if(typeof e!="object"||e===null)return;const t=e.format;if(t==="date"||t==="time"||t==="datetime")return t}function kk(e){return e==="home"?"Home":e==="not_home"?"Away":e.charAt(0).toUpperCase()+e.slice(1)}function Yc({trpc:e,device:t}){const r=t.role!=null?Ag[t.role]:void 0,n=kg(t.role),s=Qt(e,t.id),i=Tr(s!==null&&r!==void 0?r.getSliceHandle(s.state):void 0),a=Tr(s!==null&&r?.kind==="numeric"?s.state.enumSensor:void 0),l=Tr(s!==null&&n?s.state.binary:void 0),o=n&&r?.kind==="numeric"&&!Tg(i,r.field)&&l!==void 0,c=o?wg:r,d=o?l:i;if(c===void 0||d===void 0)return null;if(c.kind==="numeric"){if(!Cg(d))return null;const f=d[c.field];if(typeof f!="number")return null;const p=d.lastFetchedAt,m=f===0&&p===0;if(m&&Es(a)&&a.value!=="")return u("span",{className:L("inline-flex items-baseline text-xs text-foreground"),children:a.value});if(m)return null;const g=d,b=(typeof g.unit=="string"?g.unit:void 0)??c.canonicalUnit??"",y=Ss(f,typeof g.precision=="number"?g.precision:void 0);return v("span",{className:L("inline-flex items-baseline gap-0.5 tabular-nums text-xs text-foreground"),children:[u("span",{children:y}),b&&u("span",{className:"text-foreground-subtle",children:b})]})}if(c.kind==="binary"){if(!Ek(d))return null;const p=!!d[c.field],m=p?c.onLabel:c.offLabel;return u("span",{className:L("inline-flex items-center rounded px-1.5 py-0.5 text-xs font-medium",p?"bg-warning/15 text-warning":"bg-surface-subtle text-foreground-subtle"),children:m})}if(c.kind==="string")return!Es(d)||d.value===""?null:u("span",{className:L("inline-flex items-baseline text-xs text-foreground"),children:d.value});if(c.kind==="datetime"){if(!Es(d)||d.value==="")return null;const f=Ng(d)??c.format,p=xc(d.value,f);return u("span",{className:L("inline-flex items-baseline text-xs text-foreground"),children:p})}if(!wk(d))return null;const h=kk(d.state);return u("span",{className:L("inline-flex items-center rounded px-1.5 py-0.5 text-xs font-medium",d.state==="home"?"bg-success/15 text-success":"bg-surface-subtle text-foreground-subtle"),children:h})}function Tk(e){return{id:e.id,stableId:e.stableId,addonId:e.addonId,type:e.type,name:e.name,online:e.online,disabled:e.disabled,parentDeviceId:e.parentDeviceId,role:e.role??void 0,features:e.features}}function Ak({trpc:e,deviceId:t}){const{data:r}=Sg({deviceId:t},{staleTime:6e4});return r===void 0?null:u(Yc,{trpc:e,device:Tk(r)})}function Ck(e){return typeof e=="object"&&e!==null}function Nk(e){return typeof e=="object"&&e!==null}function Lk(e){return typeof e=="object"&&e!==null&&"state"in e&&typeof e.state=="string"}function Ik(e){return e==="home"?"Home":e==="not_home"?"Away":e.charAt(0).toUpperCase()+e.slice(1)}var Rk={low:"bg-danger",medium:"bg-warning",high:"bg-success"};function Mk(e){return e<=20?"low":e<=50?"medium":"high"}function Pk({percent:e}){const t=Math.min(100,Math.max(0,e)),r=Mk(t);return u("div",{"data-testid":"battery-bar","data-band":r,className:"h-2 w-24 overflow-hidden rounded-full bg-border",children:u("div",{className:L("h-full rounded-full transition-all",Rk[r]),style:{width:`${t}%`}})})}function Dk({trpc:e,device:t}){const r=t.role!=null?Ag[t.role]:void 0,n=kg(t.role),s=Qt(e,t.id),i=Tr(s!==null&&r!==void 0?r.getSliceHandle(s.state):void 0),a=Tr(s!==null&&n?s.state.binary:void 0),l=n&&r?.kind==="numeric"&&!Tg(i,r.field)&&a!==void 0,o=l?wg:r,c=l?a:i;if(o===void 0||c===void 0)return v("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4 min-h-[96px]",children:[u("span",{className:"text-sm text-foreground-subtle",children:t.name}),u("span",{className:"text-xs text-foreground-subtle italic",children:"Awaiting state…"})]});if(o.kind==="numeric"){if(!Ck(c))return null;const h=c[o.field];if(typeof h!="number")return null;const f=c,p=(typeof f.unit=="string"?f.unit:void 0)??o.canonicalUnit??"";return v("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4",children:[v("div",{className:"flex items-baseline gap-1",children:[u("span",{className:"text-3xl font-semibold tabular-nums text-foreground",children:Ss(h,typeof f.precision=="number"?f.precision:void 0)}),p&&u("span",{className:"text-base text-foreground-subtle",children:p})]}),n&&u(Pk,{percent:h}),u("span",{className:"text-sm text-foreground-subtle",children:t.name})]})}if(o.kind==="binary"){if(!Nk(c))return null;const f=!!c[o.field],p=f?o.onLabel:o.offLabel;return v("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4",children:[u("span",{className:L("inline-flex items-center rounded px-3 py-1.5 text-lg font-semibold",f?"bg-warning/15 text-warning":"bg-surface-subtle text-foreground-subtle"),children:p}),u("span",{className:"text-sm text-foreground-subtle",children:t.name})]})}if(o.kind==="datetime"){if(!Es(c))return null;if(c.value==="")return v("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4 min-h-[96px]",children:[u("span",{className:"text-sm text-foreground-subtle",children:t.name}),u("span",{className:"text-xs text-foreground-subtle italic",children:"Awaiting state…"})]});const h=Ng(c)??o.format;return v("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4",children:[u("span",{className:"text-3xl font-semibold tabular-nums text-foreground",children:xc(c.value,h)}),u("span",{className:"text-sm text-foreground-subtle",children:t.name})]})}if(o.kind==="string")return!Es(c)||c.value===""?null:v("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4",children:[u("span",{className:"text-xl font-semibold text-foreground",children:c.value}),u("span",{className:"text-sm text-foreground-subtle",children:t.name})]});if(!Lk(c))return null;const d=Ik(c.state);return v("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4",children:[u("span",{className:L("inline-flex items-center rounded px-3 py-1.5 text-lg font-semibold",c.state==="home"?"bg-success/15 text-success":"bg-surface-subtle text-foreground-subtle"),children:d}),u("span",{className:"text-sm text-foreground-subtle",children:t.name})]})}function _k({trpc:e,deviceId:t}){const{data:r}=Sg({deviceId:t},{staleTime:6e4});return r===void 0?null:u(Dk,{trpc:e,device:r})}function Lg(e){return e===void 0||e.inProgress?!1:e.availableVersion!==null&&e.currentVersion!==null&&e.availableVersion!==e.currentVersion}function Ig(e,t){return _e({trpc:e,deviceId:t,cap:r=>r.update,slice:r=>r.state.update})}function Ok({trpc:e,deviceId:t}){const{cap:r,slice:n}=Ig(e,t);return r===void 0?null:n?.inProgress?v("span",{className:"inline-flex items-center gap-1 text-xs text-foreground-subtle",children:[u(vt,{className:"h-3.5 w-3.5 animate-spin"}),"Updating…"]}):Lg(n)?v("span",{className:"inline-flex items-center gap-1 rounded bg-warning/15 px-1.5 py-0.5 text-[10px] font-medium text-warning",children:[u(Fs,{className:"h-3 w-3"}),"Update"]}):v("span",{className:"inline-flex items-center gap-1 text-[10px] text-foreground-subtle",children:[u(Lr,{className:"h-3 w-3 text-success"}),n?.currentVersion??"Up to date"]})}function Fk({trpc:e,deviceId:t}){const{cap:r,slice:n,available:s}=Ig(e,t);if(r===void 0)return null;const i=n?.inProgress===!0,a=Lg(n),l=n?.currentVersion??"—",o=()=>{!s||r===void 0||!a||r.installUpdate({})};return v("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4",children:[v("div",{className:"flex items-baseline gap-1.5",children:[u("span",{className:"text-3xl font-semibold tabular-nums text-foreground",children:l}),a&&n?.availableVersion!=null&&v(Ie,{children:[u("span",{className:"text-base text-foreground-subtle",children:"→"}),u("span",{className:"text-base font-medium text-warning tabular-nums",children:n.availableVersion})]})]}),i?v("span",{className:"inline-flex items-center gap-1.5 rounded px-3 py-1.5 text-sm font-medium text-foreground-subtle",children:[u(vt,{className:"h-4 w-4 animate-spin"}),"Installing…"]}):a?v("button",{type:"button",onClick:c=>{c.stopPropagation(),o()},disabled:!s,className:"inline-flex items-center gap-1.5 rounded-lg bg-primary px-4 py-1.5 text-sm font-medium text-primary-foreground shadow-sm transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[u(Fs,{className:"h-4 w-4"}),"Install update"]}):v("span",{className:"inline-flex items-center gap-1.5 rounded bg-success/15 px-3 py-1 text-sm font-medium text-success",children:[u(Lr,{className:"h-4 w-4"}),"Up to date"]}),n?.state!=null&&n.state!==""&&u("span",{className:"text-[10px] text-foreground-subtle",children:n.state})]})}function $k(e){switch(e){case"cleaning":return{label:"Cleaning",tone:"text-primary"};case"paused":return{label:"Paused",tone:"text-warning"};case"returning":return{label:"Returning",tone:"text-primary"};case"docked":return{label:"Docked",tone:"text-success"};case"idle":return{label:"Idle",tone:"text-foreground-subtle"};case"error":return{label:"Error",tone:"text-destructive"};case void 0:return{label:"Unknown",tone:"text-foreground-subtle"}}}function Rg(e,t){return _e({trpc:e,deviceId:t,cap:r=>r.vacuumControl,slice:r=>r.state.vacuumControl})}function to({label:e,busy:t,active:r,onClick:n,children:s}){return u("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:i=>{i.stopPropagation(),n()},className:L("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",r&&"bg-primary text-primary-foreground",t&&"opacity-40 cursor-not-allowed"),children:s})}function Bk(e){switch(e){case"cleaning":return{glow:"bg-primary/15",accent:"text-primary",docked:!1,active:!0};case"returning":return{glow:"bg-primary/10",accent:"text-primary",docked:!1,active:!0};case"docked":return{glow:"bg-success/10",accent:"text-success",docked:!0,active:!1};case"paused":return{glow:"bg-warning/10",accent:"text-warning",docked:!1,active:!1};case"error":return{glow:"bg-destructive/10",accent:"text-destructive",docked:!1,active:!1};case"idle":return{glow:"bg-transparent",accent:"text-foreground-subtle",docked:!1,active:!1};case void 0:return{glow:"bg-transparent",accent:"text-foreground-subtle",docked:!1,active:!1}}}function Uk({state:e}){const t=Bk(e);return v("div",{"aria-hidden":"true",className:"relative w-28 h-36 rounded border-2 border-border bg-gradient-to-b from-surface-hover to-surface overflow-hidden flex-shrink-0",style:{boxShadow:"inset 0 0 0 2px rgba(255,255,255,.06)"},children:[u("div",{className:L("absolute inset-0 transition-colors duration-300",t.glow)}),u("div",{className:L("absolute inset-0 flex items-center justify-center",t.accent),children:v("svg",{viewBox:"0 0 100 100",className:"w-20 h-20",fill:"none",children:[t.docked&&u("rect",{x:"34",y:"80",width:"32",height:"8",rx:"2",fill:"currentColor",opacity:"0.35"}),t.active&&u("circle",{cx:"50",cy:"50",r:"44",stroke:"currentColor",strokeWidth:"2",opacity:"0.4",className:"animate-ping",style:{transformOrigin:"center"}}),u("circle",{cx:"50",cy:"50",r:"34",fill:"currentColor",fillOpacity:"0.12",stroke:"currentColor",strokeWidth:"2.5"}),u("path",{d:"M 24 42 A 34 34 0 0 1 76 42",stroke:"currentColor",strokeWidth:"3",opacity:"0.55",strokeLinecap:"round"}),u("circle",{cx:"50",cy:"50",r:"9",fill:"currentColor",fillOpacity:"0.25",stroke:"currentColor",strokeWidth:"2"}),u("circle",{cx:"50",cy:"50",r:"3",fill:"currentColor"})]})})]})}function Mg({level:e}){return v("span",{className:"inline-flex items-center gap-0.5 tabular-nums text-xs text-foreground-subtle",children:[u(Cc,{className:"h-3.5 w-3.5"}),e,"%"]})}function Gk(e){switch(e){case"cleanWater":return!0;case"detergent":return!0;case"dirtyWater":return!1;case"dustBin":return!1;default:return e}}function Hk(e,t){const r=Gk(e);return t.level!==null?r?t.level<=15?"warning":"ok":t.level>=85?"warning":"ok":t.status!==null?r?t.status==="low"?"warning":"ok":t.status==="full"?"warning":"ok":"ok"}function Vk(e){switch(e){case"cleanWater":return{label:"Clean water",icon:u(bm,{className:"h-3.5 w-3.5"})};case"dirtyWater":return{label:"Dirty water",icon:u(Lc,{className:"h-3.5 w-3.5"})};case"detergent":return{label:"Detergent",icon:u(US,{className:"h-3.5 w-3.5"})};case"dustBin":return{label:"Dust bin",icon:u(zt,{className:"h-3.5 w-3.5"})};default:return e}}function jk({kind:e,tank:t}){if(t===null)return null;const r=Vk(e),n=Hk(e,t)==="warning";return t.level!==null?v("div",{className:"flex items-center gap-2 text-xs",children:[v("span",{className:L("inline-flex items-center gap-1 w-24 shrink-0",n?"text-warning":"text-foreground-subtle"),children:[r.icon,r.label]}),u("span",{className:"relative h-1.5 flex-1 overflow-hidden rounded-full bg-surface-hover",children:u("span",{className:L("absolute inset-y-0 left-0 rounded-full transition-all",n?"bg-warning":"bg-primary"),style:{width:`${t.level}%`}})}),v("span",{className:L("tabular-nums w-9 text-right",n?"text-warning":"text-foreground-subtle"),children:[t.level,"%"]})]}):t.status!==null?v("div",{className:"flex items-center gap-2 text-xs",children:[v("span",{className:L("inline-flex items-center gap-1 w-24 shrink-0",n?"text-warning":"text-foreground-subtle"),children:[r.icon,r.label]}),u("span",{className:L("inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium",n?"bg-warning/15 text-warning":"bg-primary/15 text-foreground-subtle"),children:t.status})]}):null}function Kk({cleanWater:e,dirtyWater:t,detergent:r,dustBin:n}){const s=[["cleanWater",e],["dirtyWater",t],["detergent",r],["dustBin",n]];return s.some(([,i])=>i!==null&&(i.level!==null||i.status!==null))?u("div",{className:"grid grid-cols-1 gap-x-6 gap-y-2 rounded-md border border-border bg-surface-hover/40 p-3 sm:grid-cols-2",children:s.map(([i,a])=>u(jk,{kind:i,tank:a},i))}):null}function zk({trpc:e,deviceId:t}){const{cap:r,slice:n,available:s}=Rg(e,t);if(r===void 0)return null;const i=!s,a=n?.state,l=a==="cleaning",o=c=>{i||c===void 0||c({})};return v("div",{className:"inline-flex items-center gap-1",children:[u(to,{label:"Start",busy:i,active:l,onClick:()=>o(r.start),children:u(Ar,{className:"h-3 w-3"})}),u(to,{label:"Pause",busy:i,active:a==="paused",onClick:()=>o(r.pause),children:u(Zs,{className:"h-3 w-3"})}),u(to,{label:"Return to base",busy:i,active:a==="returning",onClick:()=>o(r.returnToBase),children:u(ns,{className:"h-3.5 w-3.5"})}),n?.batteryLevel!=null&&u("span",{className:"ml-1",children:u(Mg,{level:n.batteryLevel})})]})}function ls({label:e,busy:t,active:r,onClick:n,children:s}){return u("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:i=>{i.stopPropagation(),n()},className:L("inline-flex h-10 w-10 items-center justify-center rounded-md text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",r&&"bg-primary text-primary-foreground hover:bg-primary/90",t&&"opacity-40 cursor-not-allowed"),children:s})}function Wk({trpc:e,deviceId:t}){const{cap:r,slice:n,available:s}=Rg(e,t);if(r===void 0)return null;const i=!s,a=n?.state,l=$k(a),o=n?.availableFanSpeeds??[],c=h=>{i||h===void 0||h({})},d=h=>{i||h===""||r.setFanSpeed({speed:h})};return v("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:[v("div",{className:"flex items-center gap-6",children:[u(Uk,{state:a}),v("div",{className:"flex flex-col gap-3 flex-1",children:[v("div",{className:"flex items-center justify-between",children:[u("span",{className:L("text-3xl font-semibold",l.tone),children:l.label}),n?.batteryLevel!=null&&u(Mg,{level:n.batteryLevel})]}),v("div",{className:"flex items-center gap-2",children:[u(ls,{label:"Start",busy:i,active:a==="cleaning",onClick:()=>c(r.start),children:u(Ar,{className:"h-5 w-5"})}),u(ls,{label:"Pause",busy:i,active:a==="paused",onClick:()=>c(r.pause),children:u(Zs,{className:"h-5 w-5"})}),u(ls,{label:"Stop",busy:i,active:!1,onClick:()=>c(r.stop),children:u(Cr,{className:"h-4 w-4"})}),u(ls,{label:"Return to base",busy:i,active:a==="returning",onClick:()=>c(r.returnToBase),children:u(ns,{className:"h-5 w-5"})}),u(ls,{label:"Locate",busy:i,active:!1,onClick:()=>c(r.locate),children:u(tE,{className:"h-5 w-5"})})]})]})]}),o.length>0&&v("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[u("span",{className:"w-16 shrink-0",children:"Fan speed"}),v("select",{"aria-label":"Fan speed",value:n?.fanSpeed??"",disabled:i,onChange:h=>{d(h.target.value)},onClick:h=>{h.stopPropagation()},className:"flex-1 rounded border border-border bg-surface px-2 py-1 text-foreground disabled:opacity-50",children:[n?.fanSpeed==null&&u("option",{value:"",children:"—"}),o.map(h=>u("option",{value:h,children:h},h))]})]}),u(Kk,{cleanWater:n?.cleanWater??null,dirtyWater:n?.dirtyWater??null,detergent:n?.detergent??null,dustBin:n?.dustBin??null})]})}function Qk(e){switch(e){case"mowing":return{label:"Mowing",tone:"text-primary"};case"paused":return{label:"Paused",tone:"text-warning"};case"docked":return{label:"Docked",tone:"text-success"};case"idle":return{label:"Idle",tone:"text-foreground-subtle"};case"error":return{label:"Error",tone:"text-destructive"};case void 0:return{label:"Unknown",tone:"text-foreground-subtle"}}}function Pg(e,t){return _e({trpc:e,deviceId:t,cap:r=>r.lawnMowerControl,slice:r=>r.state.lawnMowerControl})}function qk(e){switch(e){case"mowing":return{glow:"bg-primary/15",accent:"text-primary",docked:!1,active:!0};case"docked":return{glow:"bg-success/10",accent:"text-success",docked:!0,active:!1};case"paused":return{glow:"bg-warning/10",accent:"text-warning",docked:!1,active:!1};case"error":return{glow:"bg-destructive/10",accent:"text-destructive",docked:!1,active:!1};case"idle":return{glow:"bg-transparent",accent:"text-foreground-subtle",docked:!1,active:!1};case void 0:return{glow:"bg-transparent",accent:"text-foreground-subtle",docked:!1,active:!1}}}function Yk({activity:e}){const t=qk(e);return v("div",{"aria-hidden":"true",className:"relative w-28 h-36 rounded border-2 border-border bg-gradient-to-b from-emerald-700/40 to-emerald-900/30 overflow-hidden flex-shrink-0",style:{boxShadow:"inset 0 0 0 2px rgba(255,255,255,.06)"},children:[u("div",{className:L("absolute inset-0 transition-colors duration-300",t.glow)}),u("div",{className:L("absolute inset-0 flex items-center justify-center",t.accent),children:v("svg",{viewBox:"0 0 100 100",className:"w-20 h-20",fill:"none",children:[t.docked&&u("rect",{x:"30",y:"78",width:"40",height:"9",rx:"2",fill:"currentColor",opacity:"0.35"}),t.active&&v("g",{stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",opacity:"0.5",children:[u("line",{x1:"18",y1:"36",x2:"10",y2:"36",className:"animate-pulse"}),u("line",{x1:"18",y1:"50",x2:"6",y2:"50",className:"animate-pulse"}),u("line",{x1:"18",y1:"64",x2:"10",y2:"64",className:"animate-pulse"})]}),u("rect",{x:"28",y:"34",width:"44",height:"34",rx:"8",fill:"currentColor",fillOpacity:"0.14",stroke:"currentColor",strokeWidth:"2.5"}),u("line",{x1:"34",y1:"60",x2:"66",y2:"60",stroke:"currentColor",strokeWidth:"2",opacity:"0.5"}),u("circle",{cx:"50",cy:"48",r:"5",stroke:"currentColor",strokeWidth:"2",opacity:"0.6"}),u("circle",{cx:"34",cy:"68",r:"6",fill:"currentColor",fillOpacity:"0.3",stroke:"currentColor",strokeWidth:"2"}),u("circle",{cx:"66",cy:"68",r:"6",fill:"currentColor",fillOpacity:"0.3",stroke:"currentColor",strokeWidth:"2"})]})})]})}function Dg({level:e}){return v("span",{className:"inline-flex items-center gap-0.5 tabular-nums text-xs text-foreground-subtle",children:[u(Cc,{className:"h-3.5 w-3.5"}),e,"%"]})}function ro({label:e,busy:t,active:r,onClick:n,children:s}){return u("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:i=>{i.stopPropagation(),n()},className:L("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",r&&"bg-primary text-primary-foreground",t&&"opacity-40 cursor-not-allowed"),children:s})}function Xk({trpc:e,deviceId:t}){const{cap:r,slice:n,available:s}=Pg(e,t);if(r===void 0)return null;const i=!s,a=n?.activity,l=o=>{i||o===void 0||o({})};return v("div",{className:"inline-flex items-center gap-1",children:[u(ro,{label:"Mow",busy:i,active:a==="mowing",onClick:()=>l(r.startMowing),children:u(Ar,{className:"h-3 w-3"})}),u(ro,{label:"Pause",busy:i,active:a==="paused",onClick:()=>l(r.pause),children:u(Zs,{className:"h-3 w-3"})}),u(ro,{label:"Dock",busy:i,active:a==="docked",onClick:()=>l(r.dock),children:u(ns,{className:"h-3.5 w-3.5"})}),n?.batteryLevel!=null&&u("span",{className:"ml-1",children:u(Dg,{level:n.batteryLevel})})]})}function no({label:e,busy:t,active:r,onClick:n,children:s}){return u("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:i=>{i.stopPropagation(),n()},className:L("inline-flex h-10 w-10 items-center justify-center rounded-md text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",r&&"bg-primary text-primary-foreground hover:bg-primary/90",t&&"opacity-40 cursor-not-allowed"),children:s})}function Zk({trpc:e,deviceId:t}){const{cap:r,slice:n,available:s}=Pg(e,t);if(r===void 0)return null;const i=!s,a=n?.activity,l=Qk(a),o=c=>{i||c===void 0||c({})};return u("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:v("div",{className:"flex items-center gap-6",children:[u(Yk,{activity:a}),v("div",{className:"flex flex-col gap-3 flex-1",children:[v("div",{className:"flex items-center justify-between",children:[u("span",{className:L("text-3xl font-semibold",l.tone),children:l.label}),n?.batteryLevel!=null&&u(Dg,{level:n.batteryLevel})]}),v("div",{className:"flex items-center gap-2",children:[u(no,{label:"Start mowing",busy:i,active:a==="mowing",onClick:()=>o(r.startMowing),children:u(Ar,{className:"h-5 w-5"})}),u(no,{label:"Pause",busy:i,active:a==="paused",onClick:()=>o(r.pause),children:u(Zs,{className:"h-5 w-5"})}),u(no,{label:"Dock",busy:i,active:a==="docked",onClick:()=>o(r.dock),children:u(ns,{className:"h-5 w-5"})})]})]})]})})}function Jk(e){switch(e){case"open":return{label:"Open",tone:"text-primary"};case"opening":return{label:"Opening",tone:"text-primary"};case"closing":return{label:"Closing",tone:"text-warning"};case"closed":return{label:"Closed",tone:"text-foreground-subtle"};case"stopped":return{label:"Stopped",tone:"text-warning"};case void 0:return{label:"Unknown",tone:"text-foreground-subtle"}}}function _g(e,t){return _e({trpc:e,deviceId:t,cap:r=>r.valve,slice:r=>r.state.valve})}function Og(e){switch(e){case"accent":return"bg-primary text-primary-foreground";case"filled":return"bg-primary/15 text-primary";case"neutral":return""}}function so({label:e,busy:t,variant:r,onClick:n,children:s}){return u("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:i=>{i.stopPropagation(),n()},className:L("inline-flex h-5 w-5 items-center justify-center rounded text-xs text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",Og(r),t&&"opacity-40 cursor-not-allowed"),children:s})}function eT({trpc:e,deviceId:t,optimistic:r}){const{cap:n,slice:s,available:i}=_g(e,t),{display:a,applyOptimistic:l}=Ze(s,{enabled:r??!0});if(n===void 0)return null;const o=!i,c=Pa(a?.state),d=(h,f)=>{o||!h||(f!==void 0&&l(f),h({}))};return v("div",{className:"inline-flex items-center gap-1",children:[u(so,{label:"Open",busy:o,variant:c.up,onClick:()=>d(n.open,{state:"opening"}),children:u(dn,{className:"h-3.5 w-3.5"})}),u(so,{label:"Stop",busy:o,variant:c.stop,onClick:()=>d(n.stop,{state:"stopped"}),children:u(Cr,{className:"h-3 w-3"})}),u(so,{label:"Close",busy:o,variant:c.down,onClick:()=>d(n.close,{state:"closing"}),children:u(yt,{className:"h-3.5 w-3.5"})}),a!==void 0&&a.position!==null&&v("span",{className:"tabular-nums text-xs text-foreground-subtle ml-1",children:[a.position,"%"]})]})}function tT(e){switch(e){case"open":return{glow:"bg-primary/15",accent:"text-primary",flowing:!0,active:!1};case"opening":return{glow:"bg-primary/10",accent:"text-primary",flowing:!0,active:!0};case"closing":return{glow:"bg-warning/10",accent:"text-warning",flowing:!1,active:!0};case"closed":return{glow:"bg-transparent",accent:"text-foreground-subtle",flowing:!1,active:!1};case"stopped":return{glow:"bg-warning/10",accent:"text-warning",flowing:!1,active:!1};case void 0:return{glow:"bg-transparent",accent:"text-foreground-subtle",flowing:!1,active:!1}}}function rT(e){switch(e){case"open":return 0;case"opening":return 0;case"closed":return 1;case"closing":return 1;case"stopped":return 1;case void 0:return 1}}function nT({state:e,position:t,interactive:r,onSetPosition:n}){const s=tT(e),i=t!==null?1-t/100:rT(e),a=41+i*8,l=-90*(1-i),o=ne(null),c=ne(!1),d=ne(null),h=b=>{const y=t??0,S=o.current;if(S===null)return y;const E=S.getBoundingClientRect();if(E.height<=0)return y;const k=(b-E.top)/E.height,T=Math.round(100-k*100);return Math.min(100,Math.max(0,T))},f=b=>{if(n===void 0)return;const y=h(b);d.current!==y&&(d.current=y,n(y))},p=b=>{r&&(b.stopPropagation(),b.preventDefault(),c.current=!0,d.current=null,b.currentTarget.setPointerCapture(b.pointerId),f(b.clientY))},m=b=>{!r||!c.current||(b.stopPropagation(),f(b.clientY))},g=b=>{!r||!c.current||(b.stopPropagation(),c.current=!1,d.current=null,b.currentTarget.hasPointerCapture(b.pointerId)&&b.currentTarget.releasePointerCapture(b.pointerId))};return v("div",{ref:o,"data-testid":"valve-graphic",...r?{"aria-label":"Drag to set position",role:"slider","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":t??0}:{"aria-hidden":"true"},onPointerDown:r?p:void 0,onPointerMove:r?m:void 0,onPointerUp:r?g:void 0,onPointerCancel:r?g:void 0,className:L("relative w-28 h-36 rounded border-2 border-border bg-gradient-to-b from-surface-hover to-surface overflow-hidden flex-shrink-0",r&&"cursor-ns-resize touch-none select-none"),style:{boxShadow:"inset 0 0 0 2px rgba(255,255,255,.06)"},children:[u("div",{className:L("absolute inset-0 transition-colors duration-300",s.glow)}),u("div",{className:L("absolute inset-0 flex items-center justify-center",s.accent),"aria-hidden":"true",children:v("svg",{viewBox:"0 0 100 100",className:"w-24 h-28",fill:"none",children:[u("rect",{x:"40",y:"4",width:"20",height:"92",rx:"3",fill:"currentColor",fillOpacity:"0.06",stroke:"currentColor",strokeWidth:"2.5"}),s.flowing&&u("line",{x1:"50",y1:"8",x2:"50",y2:"92",stroke:"currentColor",strokeWidth:"4",strokeLinecap:"round",strokeDasharray:"4 8",opacity:"0.5",className:"animate-pulse"}),s.active&&u("circle",{cx:"50",cy:"50",r:"22",stroke:"currentColor",strokeWidth:"2",opacity:"0.4",className:"animate-ping",style:{transformOrigin:"center"}}),u("circle",{cx:"50",cy:"50",r:"17",fill:"currentColor",fillOpacity:"0.12",stroke:"currentColor",strokeWidth:"2.5"}),u("rect",{x:"43",y:a,width:"14",height:"6",rx:"1.5",fill:"currentColor",fillOpacity:"0.55",className:"transition-all duration-200"}),u("line",{x1:"50",y1:"33",x2:"50",y2:"22",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round"}),u("g",{style:{transform:`rotate(${l}deg)`,transformOrigin:"50px 20px",transition:"transform 200ms"},children:u("rect",{x:"34",y:"17",width:"32",height:"6",rx:"3",fill:"currentColor",fillOpacity:"0.7"})})]})})]})}function io({label:e,busy:t,variant:r,onClick:n,children:s}){return u("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:i=>{i.stopPropagation(),n()},className:L("inline-flex h-10 w-10 items-center justify-center rounded-md text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",Og(r),t&&"opacity-40 cursor-not-allowed"),children:s})}function sT({trpc:e,deviceId:t,features:r,optimistic:n}){const{cap:s,slice:i,available:a}=_g(e,t),{display:l,applyOptimistic:o}=Ze(i,{enabled:n??!0});if(s===void 0)return null;const c=!a,d=(r??[]).includes(Ft.ValvePositionable),h=Pa(l?.state),f=Jk(l?.state),p=l?.position??null,m=p!==null,g=(y,S)=>{c||!y||(S!==void 0&&o(S),y({}))},b=y=>{c||(o({position:y}),s.setPosition({position:y}))};return v("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:[v("div",{className:"flex items-center gap-6",children:[u(nT,{state:l?.state,position:p,interactive:d&&m,onSetPosition:d&&m?b:void 0}),v("div",{className:"flex flex-col gap-3 flex-1",children:[m&&v("div",{className:"flex items-baseline gap-1",children:[u("span",{className:"text-3xl font-semibold tabular-nums text-foreground",children:p}),u("span",{className:"text-base text-foreground-subtle",children:"%"}),u("span",{className:"text-xs text-foreground-subtle ml-1",children:"open"})]}),!m&&u("div",{className:"flex items-baseline gap-1",children:u("span",{className:L("text-3xl font-semibold",f.tone),children:f.label})}),v("div",{className:"flex items-center gap-2",children:[u(io,{label:"Open",busy:c,variant:h.up,onClick:()=>g(s.open,{state:"opening"}),children:u(dn,{className:"h-5 w-5"})}),u(io,{label:"Stop",busy:c,variant:h.stop,onClick:()=>g(s.stop,{state:"stopped"}),children:u(Cr,{className:"h-4 w-4"})}),u(io,{label:"Close",busy:c,variant:h.down,onClick:()=>g(s.close,{state:"closing"}),children:u(yt,{className:"h-5 w-5"})})]})]})]}),d&&v("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[u("span",{className:"w-12 shrink-0",children:"Position"}),u("input",{"aria-label":"Position",type:"range",min:0,max:100,step:1,value:p??0,disabled:c,className:"flex-1",onChange:y=>{b(Number(y.target.value))}}),v("span",{className:"w-8 text-right tabular-nums",children:[p??"—","%"]})]}),!d&&m&&v("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[u("span",{className:"w-12 shrink-0",children:"Position"}),u("input",{"aria-label":"Position",type:"range",min:0,max:100,step:1,value:p,disabled:!0,readOnly:!0,className:"flex-1 opacity-60"}),v("span",{className:"w-8 text-right tabular-nums",children:[p,"%"]})]})]})}function iT(e,t){switch(t){case"humidifying":return{glow:"bg-primary/15",accent:"text-primary",misting:!0};case"drying":return{glow:"bg-warning/10",accent:"text-warning",misting:!1};case"idle":return{glow:"bg-transparent",accent:"text-foreground-subtle",misting:!1};case"off":return{glow:"bg-transparent",accent:"text-foreground-subtle",misting:!1};default:return e?{glow:"bg-primary/10",accent:"text-primary",misting:!0}:{glow:"bg-transparent",accent:"text-foreground-subtle",misting:!1}}}function Fg(e,t){return _e({trpc:e,deviceId:t,cap:r=>r.humidifier,slice:r=>r.state.humidifier})}function aT({trpc:e,deviceId:t,optimistic:r}){const{cap:n,slice:s,available:i}=Fg(e,t),{display:a,applyOptimistic:l}=Ze(s,{enabled:r??!0});if(n===void 0)return null;const o=!i,c=a?.on??!1,d=()=>{o||(l({on:!c}),n.setOn({on:!c}))};return v("div",{className:"inline-flex items-center gap-2",children:[u("button",{type:"button","aria-label":c?"Turn off":"Turn on",title:c?"Turn off":"Turn on",disabled:o,onClick:h=>{h.stopPropagation(),d()},className:L("inline-flex h-5 w-5 items-center justify-center rounded text-xs transition-colors",c?"bg-primary text-primary-foreground":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover",o&&"opacity-40 cursor-not-allowed"),children:u(La,{className:"h-3.5 w-3.5"})}),a!==void 0&&a.targetHumidity!==null&&v("span",{className:"tabular-nums text-xs text-foreground-subtle",children:[a.currentHumidity!==null&&v(Ie,{children:[a.currentHumidity,"%",u("span",{className:"mx-0.5",children:"→"})]}),a.targetHumidity,"%"]})]})}function oT({fillPct:e,tint:t}){const r=82-Math.min(100,Math.max(0,e))/100*56,n=`humidifier-droplet-clip-${fr()}`;return v("div",{"data-testid":"humidifier-graphic","aria-hidden":"true",className:"relative w-28 h-36 rounded border-2 border-border bg-gradient-to-b from-surface-hover to-surface overflow-hidden flex-shrink-0",style:{boxShadow:"inset 0 0 0 2px rgba(255,255,255,.06)"},children:[u("div",{className:L("absolute inset-0 transition-colors duration-300",t.glow)}),u("div",{className:L("absolute inset-0 flex items-center justify-center",t.accent),children:v("svg",{viewBox:"0 0 100 100",className:"w-24 h-28",fill:"none",children:[u("defs",{children:u("clipPath",{id:n,children:u("path",{d:"M50 26 C50 26 30 52 30 66 a20 20 0 0 0 40 0 C70 52 50 26 50 26 Z"})})}),t.misting&&v("g",{className:"animate-pulse",opacity:"0.55",children:[u("line",{x1:"42",y1:"20",x2:"42",y2:"8",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeDasharray:"3 5"}),u("line",{x1:"50",y1:"18",x2:"50",y2:"4",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeDasharray:"3 5"}),u("line",{x1:"58",y1:"20",x2:"58",y2:"8",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeDasharray:"3 5"})]}),u("path",{d:"M50 26 C50 26 30 52 30 66 a20 20 0 0 0 40 0 C70 52 50 26 50 26 Z",fill:"currentColor",fillOpacity:"0.08",stroke:"currentColor",strokeWidth:"2.5"}),u("g",{clipPath:`url(#${n})`,children:u("rect",{x:"28",y:r,width:"44",height:"60",fill:"currentColor",fillOpacity:"0.4",className:"transition-all duration-300"})}),u("circle",{cx:"43",cy:"56",r:"3",fill:"currentColor",fillOpacity:"0.5"})]})})]})}function lT({trpc:e,deviceId:t,optimistic:r}){const{cap:n,slice:s,available:i}=Fg(e,t),{display:a,applyOptimistic:l}=Ze(s,{enabled:r??!0});if(n===void 0||a===void 0)return null;const o=!i,c=iT(a.on,a.action),d=a.minHumidity??0,h=a.maxHumidity??100,f=a.targetHumidity,p=a.currentHumidity,m=p??f??0,g=()=>{o||(l({on:!a.on}),n.setOn({on:!a.on}))},b=y=>{o||(l({targetHumidity:y}),n.setTargetHumidity({humidity:y}))};return v("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:[v("div",{className:"flex items-center gap-6",children:[u(oT,{fillPct:m,tint:c}),v("div",{className:"flex flex-col gap-3 flex-1",children:[v("div",{className:"flex items-baseline gap-1",children:[u("span",{className:"text-3xl font-semibold tabular-nums text-foreground",children:f!==null?f:"—"}),u("span",{className:"text-base text-foreground-subtle",children:"%"}),u("span",{className:"text-xs text-foreground-subtle ml-1",children:"target"})]}),v("div",{className:"text-xs text-foreground-subtle tabular-nums",children:["Current: ",p!==null?`${p}%`:"—",a.action!==null&&v("span",{className:"ml-2 capitalize",children:["· ",a.action]})]}),v("button",{type:"button","aria-label":a.on?"Turn off":"Turn on",disabled:o,onClick:y=>{y.stopPropagation(),g()},className:L("inline-flex w-fit items-center gap-2 rounded-md px-3 py-1.5 text-sm transition-colors",a.on?"bg-primary text-primary-foreground":"border border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover",o&&"opacity-40 cursor-not-allowed"),children:[u(La,{className:"h-4 w-4"}),a.on?"On":"Off"]})]})]}),v("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[u("span",{className:"w-12 shrink-0",children:"Target"}),u("input",{"aria-label":"Target humidity",type:"range",min:d,max:h,step:1,value:f??d,disabled:o,className:"flex-1",onChange:y=>{b(Number(y.target.value))}}),v("span",{className:"w-8 text-right tabular-nums",children:[f??"—","%"]})]}),a.availableModes.length>0&&u("select",{"aria-label":"Mode",value:a.mode??"",disabled:o,onChange:y=>{y.stopPropagation();const S=a.availableModes.find(E=>E===y.target.value);!o&&S!==void 0&&(l({mode:S}),n.setMode({mode:S}))},className:L("w-full rounded border border-border bg-surface px-3 py-1.5 text-sm",o&&"opacity-40 cursor-not-allowed"),children:a.availableModes.map(y=>u("option",{value:y,children:y},y))})]})}function cT(e){switch(e){case"heating":return{glow:"bg-warning/10",accent:"text-warning",heating:!0};case"idle":return{glow:"bg-primary/10",accent:"text-primary",heating:!1};case"off":return{glow:"bg-transparent",accent:"text-foreground-subtle",heating:!1}}}function uT(e,t,r){return e===null||e==="off"?"off":t!==null&&r!==null&&t<r?"heating":"idle"}function $g(e,t){return _e({trpc:e,deviceId:t,cap:r=>r.waterHeater,slice:r=>r.state.waterHeater})}function dT({trpc:e,deviceId:t,optimistic:r}){const{cap:n,slice:s}=$g(e,t),{display:i}=Ze(s,{enabled:r??!0});return n===void 0||i===void 0?null:v("div",{className:"inline-flex items-center gap-1.5 text-xs text-foreground-subtle",children:[v("span",{className:"tabular-nums",children:[i.currentTemp!==null&&v(Ie,{children:[i.currentTemp,"°",u("span",{className:"mx-0.5",children:"→"})]}),i.targetTemp!==null?`${i.targetTemp}°`:"—"]}),i.operationMode!==null&&v("span",{className:"capitalize text-foreground-subtle/80",children:["· ",i.operationMode.replace(/_/g," ")]})]})}function hT({fillPct:e,tint:t}){const r=86-Math.min(100,Math.max(0,e))/100*68,n=`water-heater-tank-clip-${fr()}`;return v("div",{"data-testid":"water-heater-graphic","aria-hidden":"true",className:"relative w-28 h-36 rounded border-2 border-border bg-gradient-to-b from-surface-hover to-surface overflow-hidden flex-shrink-0",style:{boxShadow:"inset 0 0 0 2px rgba(255,255,255,.06)"},children:[u("div",{className:L("absolute inset-0 transition-colors duration-300",t.glow)}),u("div",{className:L("absolute inset-0 flex items-center justify-center",t.accent),children:v("svg",{viewBox:"0 0 100 100",className:"w-24 h-28",fill:"none",children:[u("defs",{children:u("clipPath",{id:n,children:u("rect",{x:"30",y:"18",width:"40",height:"68",rx:"14"})})}),u("g",{clipPath:`url(#${n})`,children:u("rect",{x:"28",y:r,width:"44",height:"72",fill:"currentColor",fillOpacity:"0.32",className:"transition-all duration-300"})}),u("rect",{x:"30",y:"18",width:"40",height:"68",rx:"14",fill:"currentColor",fillOpacity:"0.06",stroke:"currentColor",strokeWidth:"2.5"}),u("line",{x1:"50",y1:"18",x2:"50",y2:"8",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round"}),u("rect",{x:"40",y:"6",width:"20",height:"5",rx:"2",fill:"currentColor",fillOpacity:"0.6"}),u("g",{className:t.heating?"animate-pulse":void 0,opacity:t.heating?.9:.35,children:u("path",{d:"M38 74 q4 -6 8 0 q4 6 8 0 q4 -6 8 0",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",fill:"none"})}),u("circle",{cx:"62",cy:"34",r:"3.5",stroke:"currentColor",strokeWidth:"2",fill:t.heating?"currentColor":"none",fillOpacity:"0.6"})]})})]})}function fT({trpc:e,deviceId:t,optimistic:r}){const{cap:n,slice:s,available:i}=$g(e,t),{display:a,applyOptimistic:l}=Ze(s,{enabled:r??!0});if(n===void 0||a===void 0)return null;const o=!i,c=uT(a.operationMode,a.currentTemp,a.targetTemp),d=cT(c),h=a.currentTemp,f=a.targetTemp,p=a.minTemp,m=a.maxTemp,g=h!==null&&f!==null&&f>0?Math.min(100,h/f*100):h!==null&&m!==null&&m>0?Math.min(100,h/m*100):50,b=E=>{let k=E;return p!==null&&(k=Math.max(p,k)),m!==null&&(k=Math.min(m,k)),k},y=E=>{if(o||f===null)return;const k=b(f+E);l({targetTemp:k}),n.setTargetTemp({temp:k})},S=()=>{o||a.away===null||(l({away:!a.away}),n.setAway({on:!a.away}))};return v("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:[v("div",{className:"flex items-center gap-6",children:[u(hT,{fillPct:g,tint:d}),v("div",{className:"flex flex-col gap-3 flex-1",children:[v("div",{className:"flex items-baseline gap-1",children:[u("span",{className:"text-3xl font-semibold tabular-nums text-foreground",children:h!==null?h:"—"}),u("span",{className:"text-base text-foreground-subtle",children:"°"})]}),v("div",{className:"text-xs text-foreground-subtle tabular-nums",children:["Target: ",f!==null?`${f}°`:"—",v("span",{className:"ml-2 capitalize",children:["· ",c]})]}),f!==null&&u("div",{className:"w-[180px]",children:u(vg,{value:f,unit:"°",onDelta:y})})]})]}),a.availableModes.length>0&&u("select",{"aria-label":"Operation mode",value:a.operationMode??"",disabled:o,onChange:E=>{E.stopPropagation();const k=a.availableModes.find(T=>T===E.target.value);!o&&k!==void 0&&(l({operationMode:k}),n.setOperationMode({mode:k}))},className:L("w-full rounded border border-border bg-surface px-3 py-1.5 text-sm",o&&"opacity-40 cursor-not-allowed"),children:a.availableModes.map(E=>u("option",{value:E,children:E},E))}),a.away!==null&&v("button",{type:"button","aria-label":a.away?"Disable away mode":"Enable away mode",disabled:o,onClick:E=>{E.stopPropagation(),S()},className:L("inline-flex w-fit items-center gap-2 rounded-md px-3 py-1.5 text-sm transition-colors",a.away?"bg-primary text-primary-foreground":"border border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover",o&&"opacity-40 cursor-not-allowed"),children:[u(La,{className:"h-4 w-4"}),"Away ",a.away?"on":"off"]})]})}function Bg(e){switch(e){case"sunny":return{label:"Sunny",glyph:"sun"};case"clear-night":return{label:"Clear night",glyph:"clear-night"};case"partlycloudy":return{label:"Partly cloudy",glyph:"partly-cloudy"};case"cloudy":return{label:"Cloudy",glyph:"cloudy"};case"rainy":return{label:"Rainy",glyph:"rain"};case"pouring":return{label:"Pouring",glyph:"rain"};case"snowy":return{label:"Snowy",glyph:"snow"};case"snowy-rainy":return{label:"Sleet",glyph:"snow"};case"lightning":return{label:"Lightning",glyph:"lightning"};case"lightning-rainy":return{label:"Thunderstorm",glyph:"lightning"};case"fog":return{label:"Fog",glyph:"fog"};case"windy":return{label:"Windy",glyph:"wind"};case"windy-variant":return{label:"Windy",glyph:"wind"};case"hail":return{label:"Hail",glyph:"hail"};case"exceptional":return{label:"Exceptional",glyph:"cloudy"};case null:return{label:"Unknown",glyph:"cloudy"};default:return{label:e,glyph:"cloudy"}}}function Ug(e){switch(e){case"sunny":return{glow:"bg-warning/15",accent:"text-warning"};case"clear-night":return{glow:"bg-primary/10",accent:"text-primary"};case"partlycloudy":return{glow:"bg-warning/10",accent:"text-warning"};case"cloudy":return{glow:"bg-transparent",accent:"text-foreground-subtle"};case"rainy":case"pouring":return{glow:"bg-primary/15",accent:"text-primary"};case"snowy":case"snowy-rainy":return{glow:"bg-primary/10",accent:"text-primary"};case"lightning":case"lightning-rainy":return{glow:"bg-warning/20",accent:"text-warning"};case"fog":return{glow:"bg-transparent",accent:"text-foreground-subtle"};case"windy":case"windy-variant":return{glow:"bg-transparent",accent:"text-foreground-subtle"};case"hail":return{glow:"bg-primary/10",accent:"text-primary"};default:return{glow:"bg-transparent",accent:"text-foreground-subtle"}}}function pT(e){const t="h-4 w-4";switch(e){case"sun":return u(Dc,{className:t});case"clear-night":return u(Na,{className:t});case"partly-cloudy":return u(vm,{className:t});case"cloudy":return u(MS,{className:t});case"rain":return u(RS,{className:t});case"snow":return u(od,{className:t});case"lightning":return u(IS,{className:t});case"fog":return u(LS,{className:t});case"wind":return u(ia,{className:t});case"hail":return u(od,{className:t});default:return null}}function Gg(e,t){return _e({trpc:e,deviceId:t,cap:r=>r.weather,slice:r=>r.state.weather})}function mT(e,t){return e===null?"—":`${Math.round(e)}${t??"°"}`}function gT({trpc:e,deviceId:t}){const{slice:r}=Gg(e,t);if(r===void 0)return null;const n=Bg(r.condition);return v("div",{className:"inline-flex items-center gap-1.5 text-xs text-foreground-subtle",children:[u("span",{className:L("inline-flex",Ug(r.condition).accent),title:n.label,"aria-label":n.label,children:pT(n.glyph)}),u("span",{className:"tabular-nums",children:mT(r.temperature,r.temperatureUnit)})]})}function vT({glyph:e,tint:t}){const r=fr();return v("div",{"data-testid":"weather-scene","aria-hidden":"true",className:"relative w-28 h-36 rounded border-2 border-border bg-gradient-to-b from-surface-hover to-surface overflow-hidden flex-shrink-0",style:{boxShadow:"inset 0 0 0 2px rgba(255,255,255,.06)"},children:[u("div",{className:L("absolute inset-0 transition-colors duration-300",t.glow)}),u("div",{className:L("absolute inset-0 flex items-center justify-center",t.accent),children:u("svg",{viewBox:"0 0 100 100",className:"w-24 h-28",fill:"none","data-glyph":e,children:bT(e,r)})})]})}function Zr({cx:e,cy:t,scale:r=1}){return u("g",{transform:`translate(${e} ${t}) scale(${r})`,children:u("path",{d:"M-22 8 a13 13 0 0 1 4 -25 a16 16 0 0 1 30 4 a11 11 0 0 1 -2 21 Z",fill:"currentColor",fillOpacity:"0.12",stroke:"currentColor",strokeWidth:"2.5",strokeLinejoin:"round"})})}function bT(e,t){switch(e){case"sun":return v("g",{children:[u("circle",{cx:"50",cy:"48",r:"16",fill:"currentColor",fillOpacity:"0.18",stroke:"currentColor",strokeWidth:"2.5"}),u("g",{stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",children:[0,45,90,135,180,225,270,315].map(r=>{const n=r*Math.PI/180;return u("line",{x1:50+Math.cos(n)*22,y1:48+Math.sin(n)*22,x2:50+Math.cos(n)*30,y2:48+Math.sin(n)*30},`${t}-ray-${r}`)})})]});case"clear-night":return v("g",{children:[u("path",{d:"M62 30 a22 22 0 1 0 8 38 a18 18 0 0 1 -8 -38 Z",fill:"currentColor",fillOpacity:"0.18",stroke:"currentColor",strokeWidth:"2.5"}),u("circle",{cx:"34",cy:"32",r:"1.6",fill:"currentColor"}),u("circle",{cx:"28",cy:"48",r:"1.2",fill:"currentColor"}),u("circle",{cx:"40",cy:"62",r:"1.4",fill:"currentColor"})]});case"partly-cloudy":return v("g",{children:[u("circle",{cx:"38",cy:"38",r:"12",fill:"currentColor",fillOpacity:"0.18",stroke:"currentColor",strokeWidth:"2.5"}),u("g",{stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",children:[200,240,300].map(r=>{const n=r*Math.PI/180;return u("line",{x1:38+Math.cos(n)*16,y1:38+Math.sin(n)*16,x2:38+Math.cos(n)*22,y2:38+Math.sin(n)*22},`${t}-pcray-${r}`)})}),u(Zr,{cx:58,cy:60})]});case"cloudy":return v("g",{children:[u(Zr,{cx:40,cy:44,scale:.9}),u(Zr,{cx:62,cy:58})]});case"rain":return v("g",{children:[u(Zr,{cx:50,cy:42}),v("g",{className:"animate-pulse",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",opacity:"0.7",children:[u("line",{x1:"38",y1:"62",x2:"34",y2:"78"}),u("line",{x1:"50",y1:"62",x2:"46",y2:"80"}),u("line",{x1:"62",y1:"62",x2:"58",y2:"78"})]})]});case"snow":return v("g",{children:[u(Zr,{cx:50,cy:42}),v("g",{fill:"currentColor",opacity:"0.8",className:"animate-pulse",children:[u("circle",{cx:"38",cy:"70",r:"2.5"}),u("circle",{cx:"50",cy:"76",r:"2.5"}),u("circle",{cx:"62",cy:"70",r:"2.5"})]})]});case"lightning":return v("g",{children:[u(Zr,{cx:50,cy:40}),u("path",{d:"M52 58 L42 74 L50 74 L46 88 L62 68 L53 68 L58 58 Z",fill:"currentColor",fillOpacity:"0.85",className:"animate-pulse"})]});case"fog":return v("g",{stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",opacity:"0.6",children:[u("line",{x1:"26",y1:"40",x2:"74",y2:"40"}),u("line",{x1:"30",y1:"52",x2:"70",y2:"52"}),u("line",{x1:"24",y1:"64",x2:"68",y2:"64"}),u("line",{x1:"32",y1:"76",x2:"76",y2:"76"})]});case"wind":return v("g",{stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",fill:"none",opacity:"0.75",children:[u("path",{d:"M22 42 H60 a7 7 0 1 0 -7 -7"}),u("path",{d:"M22 56 H72 a7 7 0 1 1 -7 7"}),u("path",{d:"M22 70 H52 a6 6 0 1 0 -6 -6"})]});case"hail":return v("g",{children:[u(Zr,{cx:50,cy:42}),v("g",{fill:"currentColor",opacity:"0.85",className:"animate-pulse",children:[u("circle",{cx:"40",cy:"70",r:"3"}),u("circle",{cx:"52",cy:"78",r:"3"}),u("circle",{cx:"62",cy:"68",r:"3"})]})]});default:return null}}function ao({icon:e,label:t,value:r}){return v("div",{className:"flex items-center gap-1.5 text-xs text-foreground-subtle",title:t,children:[u("span",{className:"inline-flex text-foreground-subtle","aria-hidden":"true",children:e}),u("span",{className:"tabular-nums text-foreground",children:r})]})}function yT({trpc:e,deviceId:t}){const{slice:r}=Gg(e,t);if(r===void 0)return null;const n=Bg(r.condition),s=Ug(r.condition),i=r.temperatureUnit??"°";return u("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:v("div",{className:"flex items-center gap-6",children:[u(vT,{glyph:n.glyph,tint:s}),v("div",{className:"flex flex-col gap-3 flex-1",children:[v("div",{className:"flex items-baseline gap-1",children:[u("span",{className:"text-3xl font-semibold tabular-nums text-foreground",children:r.temperature!==null?Math.round(r.temperature):"—"}),u("span",{className:"text-base text-foreground-subtle",children:i}),u("span",{className:"text-xs text-foreground-subtle ml-2 capitalize",children:n.label})]}),v("div",{className:"flex flex-col gap-1.5",children:[r.humidity!==null&&u(ao,{icon:u(Lc,{className:"h-3.5 w-3.5"}),label:"Humidity",value:`${Math.round(r.humidity)}%`}),r.windSpeed!==null&&u(ao,{icon:r.windBearing!==null?u(oE,{className:"h-3.5 w-3.5",style:{transform:`rotate(${r.windBearing}deg)`}}):u(ia,{className:"h-3.5 w-3.5"}),label:"Wind",value:`${Math.round(r.windSpeed)} ${r.windSpeedUnit??""}`.trim()}),r.pressure!==null&&u(ao,{icon:u(xs,{className:"h-3.5 w-3.5"}),label:"Pressure",value:`${Math.round(r.pressure)} ${r.pressureUnit??""}`.trim()})]})]})]})})}var xT=288,ST=196,ET="h-7 w-7 rounded",oo=8,Id=8;function Hg({src:e,alt:t,caption:r,placeholder:n="No image",thumbClassName:s=ET,expandedWidth:i=xT,expandedHeight:a=ST}){const l=ne(null),[o,c]=_(null),[d,h]=_(!1);ae(()=>{h(!1)},[e]);const f=e!==null&&!d,p=e??void 0,m=q(()=>{const b=l.current;if(!b)return;const y=b.getBoundingClientRect(),S=y.top,E=window.innerHeight-y.bottom,k=S<a+oo&&E>S?y.bottom+oo:y.top-a-oo,T=y.right-i;c({top:k,left:Math.max(Id,Math.min(T,window.innerWidth-i-Id))})},[i,a]),g=q(()=>c(null),[]);return v(Ie,{children:[u("button",{ref:l,type:"button",onClick:b=>b.stopPropagation(),onMouseEnter:m,onMouseLeave:g,onFocus:m,onBlur:g,"aria-label":t,className:`flex flex-shrink-0 items-center justify-center overflow-hidden border border-border bg-background text-foreground-subtle transition-colors hover:bg-surface-hover ${s}`,children:f?u("img",{src:p,alt:"",onError:()=>h(!0),className:"h-full w-full object-cover"}):u(Em,{className:"h-3.5 w-3.5","aria-hidden":"true"})}),o&&Ys(v("div",{"aria-hidden":"true",style:{position:"fixed",top:o.top,left:o.left,width:i,pointerEvents:"none"},className:"z-[9999] overflow-hidden rounded-lg border border-border bg-surface shadow-lg shadow-black/30",children:[u("div",{className:"flex h-40 items-center justify-center bg-background",children:f?u("img",{src:p,alt:t,className:"h-full w-full object-cover"}):u("span",{className:"text-xs text-foreground-subtle",children:n})}),u("div",{className:"px-3 py-2",children:u("p",{className:"truncate text-xs font-semibold text-foreground",children:r??t})})]}),document.body)]})}function Vg(e,t){return _e({trpc:e,deviceId:t,cap:r=>r.image,slice:r=>r.state.image})}function wT({trpc:e,deviceId:t}){const{slice:r}=Vg(e,t);return r===void 0?null:u(Hg,{src:r.url,alt:"Image",placeholder:"No image",thumbClassName:"h-7 w-7 rounded"})}function kT({trpc:e,deviceId:t,deviceName:r}){const{slice:n}=Vg(e,t),[s,i]=_(!1);return ae(()=>{i(!1)},[n?.url??null]),n===void 0?null:u("div",{className:"flex flex-col items-stretch gap-3 rounded-lg border border-border bg-surface p-4",children:u("div",{className:"flex w-full items-center justify-center overflow-hidden rounded border-2 border-border bg-gradient-to-b from-surface-hover to-surface",children:n.url!==null&&!s?u("img",{src:n.url,alt:r??"Image",onError:()=>i(!0),className:"max-h-72 w-full object-contain"}):v("div",{"data-testid":"image-placeholder",className:"flex h-48 w-full flex-col items-center justify-center gap-2 text-foreground-subtle",children:[u(Em,{className:"h-8 w-8","aria-hidden":"true"}),u("span",{className:"text-xs",children:"No image"})]})})})}function Xc({trpc:e,deviceId:t,optimistic:r}){const{cap:n,slice:s,available:i}=_e({trpc:e,deviceId:t,cap:m=>m.switch,slice:m=>m.state.switch}),{display:a,applyOptimistic:l}=Ze(s,{enabled:r??!0}),[o,c]=_(!1);if(a===void 0)return null;const d=a.on===!0,h=o||!i,f={transform:d?"translateX(14px)":"translateX(2px)"},p=async()=>{if(h||!n)return;const m=!d;l({on:m}),c(!0);try{await n.setState({on:m})}finally{c(!1)}};return u("button",{type:"button","aria-pressed":d,title:d?"Turn off":"Turn on",disabled:h,onClick:m=>{m.stopPropagation(),p()},className:L("relative inline-flex h-4 w-7 items-center rounded-full border transition-colors flex-shrink-0",d?"bg-success/30 border-success/50":"bg-surface-hover border-border",h&&"opacity-60"),children:u("span",{className:L("absolute h-3 w-3 rounded-full transition-all",d?"bg-success":"bg-foreground-subtle"),style:f})})}function TT(e){return e instanceof Error?e.message:String(e)}function AT({trpc:e,deviceId:t,layout:r,optimistic:n,features:s}){const{cap:i,slice:a,available:l}=_e({trpc:e,deviceId:t,cap:F=>F.lockControl,slice:F=>F.state.lockControl}),{display:o,applyOptimistic:c}=Ze(a,{enabled:n??!0}),[d,h]=_(null),[f,p]=_(!1),[m,g]=_(null);if(o===void 0)return null;const b=o.state==="locked"||o.state==="locking",y=!l||o.state==="jammed",S=s?.includes(Ft.LockOpen)===!0,E=r==="compact",k=()=>{c({state:"locking"}),i?.lock({})},T=()=>{c({state:"unlocking"}),i?.unlock({})},A=()=>{i?.open({})},N=()=>{if(!y){if(!b){k();return}if(E){g(null),h("unlock");return}T()}},C=()=>{if(!y){if(E){g(null),h("open");return}A()}},M=()=>{f||h(null)},P=async()=>{if(!(f||d===null)){g(null),p(!0);try{d==="unlock"?(c({state:"unlocking"}),await i?.unlock({})):await i?.open({}),h(null)}catch(F){g(TT(F))}finally{p(!1)}}},D=b?"Unlock":"Lock",$=d==="open"?"Open door?":"Unlock device?",B=d==="open"?"This will release the latch and open the door.":"This will unlock the device.",j=d==="open"?"Confirm open":"Confirm unlock",U=d==="open"?u(Os,{className:"h-4 w-4 text-amber-400"}):u(vl,{className:"h-4 w-4 text-amber-400"});return v("div",{className:L("inline-flex items-center",r==="full"?"gap-2":"gap-1"),children:[v("button",{type:"button","aria-label":D,title:o.state==="jammed"?"Jammed":D,disabled:y,onClick:F=>{F.stopPropagation(),N()},className:L("inline-flex items-center justify-center rounded transition-colors",r==="full"?"h-7 gap-1.5 px-2 text-xs":"h-5 w-5",b?"text-success":"text-warning",y&&"opacity-40 cursor-not-allowed","hover:bg-surface-hover"),children:[b?u(Rc,{className:"h-3.5 w-3.5"}):u(vl,{className:"h-3.5 w-3.5"}),r==="full"&&u("span",{children:o.state})]}),S&&v("button",{type:"button","aria-label":"Open door",title:"Open door",disabled:y,onClick:F=>{F.stopPropagation(),C()},className:L("inline-flex items-center justify-center rounded transition-colors",r==="full"?"h-7 gap-1.5 px-2 text-xs":"h-5 w-5","text-foreground-muted",y&&"opacity-40 cursor-not-allowed","hover:bg-surface-hover"),children:[u(Os,{className:"h-3.5 w-3.5"}),r==="full"&&u("span",{children:"Open"})]}),E&&u($c,{open:d!==null,onOpenChange:F=>{F||M()},children:v(Ia,{width:"sm",onClick:F=>F.stopPropagation(),children:[v(Bc,{children:[v(Gc,{className:"flex items-center gap-2",children:[U,$]}),u(Hc,{children:B})]}),m!==null&&u("div",{className:"mt-2 px-3 py-2 rounded border border-danger/40 bg-danger/10 text-xs text-danger",children:m}),v(Uc,{children:[u(tr,{type:"button",variant:"ghost",size:"sm",disabled:f,onClick:()=>M(),children:"Cancel"}),v(tr,{type:"button",variant:"danger",size:"sm","aria-label":j,disabled:f,onClick:()=>{P()},children:[f&&u(vt,{className:"h-3.5 w-3.5 animate-spin"}),j]})]})]})})]})}function CT({trpc:e,deviceId:t,layout:r,optimistic:n}){const{cap:s,slice:i,available:a}=_e({trpc:e,deviceId:t,cap:d=>d.brightness,slice:d=>d.state.brightness}),{display:l,applyOptimistic:o}=Ze(i,{enabled:n??!0});if(l===void 0)return null;const c=!a;return v("label",{className:L("flex items-center gap-2 text-xs text-foreground-subtle",r==="compact"&&"min-w-[140px]"),children:[u("input",{"aria-label":"Brightness",type:"range",min:0,max:100,step:1,value:l.percentage,disabled:c,onChange:d=>{const h=Number(d.target.value);o({percentage:h}),c||s?.setBrightness({percentage:h})}}),v("span",{className:"tabular-nums w-8 text-right",children:[l.percentage,"%"]})]})}function NT({trpc:e,deviceId:t,features:r,layout:n,optimistic:s}){const{cap:i,slice:a,available:l}=_e({trpc:e,deviceId:t,cap:g=>g.fanControl,slice:g=>g.state.fanControl}),{display:o,applyOptimistic:c}=Ze(a,{enabled:s??!0});if(o===void 0)return null;const d=!l,h=r??[],f=h.includes("fan-speed"),p=h.includes("fan-preset"),m=a?.percentageStep!=null&&a.percentageStep>0?a.percentageStep:1;return v("div",{className:L("inline-flex items-center gap-2",n==="full"&&"flex-col items-stretch"),children:[f&&v("div",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[u("input",{"aria-label":"Fan speed",type:"range",min:0,max:100,step:m,value:o.percentage??0,disabled:d,onChange:g=>{const b=Number(g.target.value),y=Math.min(100,Math.max(0,Math.round(b/m)*m));c({percentage:y}),d||i?.setPercentage({percentage:y})}}),v("span",{className:"tabular-nums w-8 text-right",children:[o.percentage??"—","%"]})]}),p&&o.availablePresets.length>0&&u("div",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:v("select",{"aria-label":"Fan preset",value:o.preset,disabled:d,onChange:g=>{const b=g.target.value;!d&&b&&(c({preset:b}),i?.setPreset({preset:b}))},className:"bg-surface border border-border rounded px-1 py-0.5",children:[u("option",{value:"",disabled:!0,children:"—"}),o.availablePresets.map(g=>u("option",{value:g,children:g},g))]})})]})}var jg={heat:"border-amber-400 bg-amber-50 dark:bg-amber-950",cool:"border-blue-400 bg-blue-50 dark:bg-blue-950",auto:"border-purple-400 bg-purple-50 dark:bg-purple-950",heat_cool:"border-fuchsia-400 bg-fuchsia-50 dark:bg-fuchsia-950",fan_only:"border-slate-400 bg-slate-50 dark:bg-slate-950",dry:"border-cyan-400 bg-cyan-50 dark:bg-cyan-950",off:"border-zinc-300 bg-zinc-50 dark:bg-zinc-900"},LT={heat:"text-amber-600 dark:text-amber-400",cool:"text-blue-600 dark:text-blue-400",auto:"text-purple-600 dark:text-purple-400",heat_cool:"text-fuchsia-600 dark:text-fuchsia-400",fan_only:"text-slate-600 dark:text-slate-400",dry:"text-cyan-600 dark:text-cyan-400",off:"text-foreground"},IT={heat:"bg-amber-400 text-amber-950",cool:"bg-blue-400 text-blue-950",auto:"bg-purple-400 text-purple-950",heat_cool:"bg-fuchsia-400 text-fuchsia-950",fan_only:"bg-slate-400 text-slate-950",dry:"bg-cyan-400 text-cyan-950",off:"bg-zinc-300 text-zinc-700"};function RT({trpc:e,deviceId:t,features:r,layout:n,optimistic:s}){const{cap:i,slice:a,available:l}=_e({trpc:e,deviceId:t,cap:p=>p.climateControl,slice:p=>p.state.climateControl}),{display:o,applyOptimistic:c}=Ze(a,{enabled:s??!0});if(i===void 0||o===void 0)return null;const d=!l;if(n==="compact")return v("div",{"data-mode":o.mode,className:"inline-flex items-center gap-1",children:[u("span",{className:L("text-xs tabular-nums font-medium",LT[o.mode]),children:o.target!==null?v(Ie,{children:[o.target,"°",o.currentTemp!==null&&v("span",{className:"text-foreground-subtle font-normal",children:[" (",o.currentTemp,"°)"]})]}):o.currentTemp!==null?v("span",{className:"text-foreground-subtle",children:[o.currentTemp,"°"]}):null}),o.target!==null&&v(Ie,{children:[u("button",{type:"button","aria-label":"Decrease target",disabled:d,onClick:p=>{if(p.stopPropagation(),!d&&o.target!==null){const m=o.target-1;c({target:m}),i.setTarget({target:m})}},className:L("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs",d&&"opacity-40 cursor-not-allowed"),children:"−"}),u("button",{type:"button","aria-label":"Increase target",disabled:d,onClick:p=>{if(p.stopPropagation(),!d&&o.target!==null){const m=o.target+1;c({target:m}),i.setTarget({target:m})}},className:L("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs",d&&"opacity-40 cursor-not-allowed"),children:"+"})]}),u("select",{"aria-label":"Mode",value:o.mode,disabled:d,onChange:p=>{p.stopPropagation();const m=p.target.value;d||(c({mode:m}),i.setMode({mode:m}))},className:L("bg-transparent px-0.5 text-xs text-foreground-subtle hover:text-foreground cursor-pointer",d&&"opacity-40 cursor-not-allowed"),children:o.availableModes.map(p=>u("option",{value:p,children:p},p))})]});const h=o.mode==="heat_cool"||o.targetLow!==null&&o.targetHigh!==null,f=!h&&o.target!==null;return v("div",{"data-mode":o.mode,className:L("inline-flex items-center gap-2 rounded border px-2 py-1 transition-colors",jg[o.mode],"flex-col items-stretch gap-3"),children:[v("div",{className:"inline-flex items-center gap-1 text-xs tabular-nums",children:[o.currentTemp!==null&&v("span",{className:"text-foreground-subtle",children:[o.currentTemp,"°"]}),f&&v(Ie,{children:[u("span",{className:"text-foreground-subtle",children:"→"}),v("span",{className:"font-medium",children:[o.target,"°"]}),u("button",{type:"button","aria-label":"Decrease target",disabled:d,onClick:p=>{if(p.stopPropagation(),!d&&o.target!==null){const m=o.target-1;c({target:m}),i.setTarget({target:m})}},className:L("inline-flex h-4 w-4 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",d&&"opacity-40 cursor-not-allowed"),children:"−"}),u("button",{type:"button","aria-label":"Increase target",disabled:d,onClick:p=>{if(p.stopPropagation(),!d&&o.target!==null){const m=o.target+1;c({target:m}),i.setTarget({target:m})}},className:L("inline-flex h-4 w-4 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",d&&"opacity-40 cursor-not-allowed"),children:"+"})]})]}),u("div",{className:"inline-flex items-center gap-0.5 rounded bg-surface-subtle p-0.5",children:o.availableModes.map(p=>u("button",{type:"button","aria-label":p,disabled:d,onClick:m=>{m.stopPropagation(),d||(c({mode:p}),i.setMode({mode:p}))},className:L("rounded px-1.5 py-0.5 text-xs transition-colors",p===o.mode?IT[p]:"text-foreground-subtle hover:text-foreground hover:bg-surface-hover",d&&"opacity-40 cursor-not-allowed"),children:p},p))}),h&&v("div",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[v("label",{className:"flex items-center gap-1",children:[u("span",{children:"Low"}),u("input",{"aria-label":"Target low",type:"number",step:.5,value:o.targetLow??"",disabled:d,onChange:p=>{if(!d){const m=Number(p.target.value),g=o.targetHigh??m;c({targetLow:m}),i.setTargetRange({targetLow:m,targetHigh:g})}},className:"w-14 rounded border border-border bg-surface px-1 py-0.5 tabular-nums"})]}),v("label",{className:"flex items-center gap-1",children:[u("span",{children:"High"}),u("input",{"aria-label":"Target high",type:"number",step:.5,value:o.targetHigh??"",disabled:d,onChange:p=>{if(!d){const m=Number(p.target.value),g=o.targetLow??m;c({targetHigh:m}),i.setTargetRange({targetLow:g,targetHigh:m})}},className:"w-14 rounded border border-border bg-surface px-1 py-0.5 tabular-nums"})]})]}),o.availableFanModes.length>0&&v("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[u("span",{children:"Fan"}),v("select",{"aria-label":"Fan mode",value:o.fanMode,disabled:d,onChange:p=>{const m=p.target.value;!d&&m&&(c({fanMode:m}),i.setFanMode({fanMode:m}))},className:"rounded border border-border bg-surface px-1 py-0.5",children:[u("option",{value:"",disabled:!0,children:"—"}),o.availableFanModes.map(p=>u("option",{value:p,children:p},p))]})]}),o.availablePresets.length>0&&v("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[u("span",{children:"Preset"}),v("select",{"aria-label":"Preset",value:o.preset,disabled:d,onChange:p=>{const m=p.target.value;!d&&m&&(c({preset:m}),i.setPreset({preset:m}))},className:"rounded border border-border bg-surface px-1 py-0.5",children:[u("option",{value:"",disabled:!0,children:"—"}),o.availablePresets.map(p=>u("option",{value:p,children:p},p))]})]}),o.targetHumidity!==null&&v("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[u("span",{children:"Humidity"}),u("input",{"aria-label":"Target humidity",type:"range",min:0,max:100,step:1,value:o.targetHumidity,disabled:d,onChange:p=>{const m=Number(p.target.value);c({targetHumidity:m}),d||i.setTargetHumidity({targetHumidity:m})}}),v("span",{className:"tabular-nums w-8 text-right",children:[o.targetHumidity,"%"]})]})]})}var MT={playing:"border-green-400 bg-green-50 dark:bg-green-950",paused:"border-amber-400 bg-amber-50 dark:bg-amber-950",buffering:"border-blue-400 bg-blue-50 dark:bg-blue-950",on:"border-slate-400 bg-slate-50 dark:bg-slate-950",idle:"border-slate-400 bg-slate-50 dark:bg-slate-950",off:"border-zinc-300 bg-zinc-50 dark:bg-zinc-900",standby:"border-zinc-300 bg-zinc-50 dark:bg-zinc-900"},PT={playing:"bg-green-500",paused:"bg-amber-400",buffering:"bg-blue-400",on:"bg-slate-400",idle:"bg-slate-400",off:"bg-zinc-300",standby:"bg-zinc-300"},Kg=["off","all","one"];function DT(e){return Kg.includes(e)}var _T={off:"Off",all:"All",one:"One"};function OT(e){return e==="playing"||e==="buffering"?"pause":"play"}function FT({trpc:e,deviceId:t,features:r,layout:n,optimistic:s}){const{cap:i,slice:a,available:l}=_e({trpc:e,deviceId:t,cap:f=>f.mediaPlayer,slice:f=>f.state.mediaPlayer}),{display:o,applyOptimistic:c}=Ze(a,{enabled:s??!0});if(o===void 0)return null;const d=!l,h=OT(o.state);return v("div",{"data-state":o.state,className:L("inline-flex items-center gap-2 rounded border px-2 py-1 transition-colors",MT[o.state],n==="full"&&"flex-col items-stretch gap-3"),children:[v("div",{className:"inline-flex items-center gap-2",children:[u("span",{role:"status","aria-label":o.state,className:L("inline-block h-2 w-2 rounded-full flex-shrink-0",PT[o.state])}),u("button",{type:"button","aria-label":h==="play"?"Play":"Pause",disabled:d,onClick:f=>{f.stopPropagation(),!d&&(h==="play"?(c({state:"playing"}),i?.play({})):(c({state:"paused"}),i?.pause({})))},className:L("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs",d&&"opacity-40 cursor-not-allowed"),children:h==="play"?"▶":"⏸"})]}),n==="full"&&v(Ie,{children:[v("div",{className:"inline-flex items-center gap-1",children:[u("button",{type:"button","aria-label":"Previous",disabled:d,onClick:f=>{f.stopPropagation(),d||i?.previous({})},className:L("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs",d&&"opacity-40 cursor-not-allowed"),children:"⏮"}),u("button",{type:"button","aria-label":"Next",disabled:d,onClick:f=>{f.stopPropagation(),d||i?.next({})},className:L("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs",d&&"opacity-40 cursor-not-allowed"),children:"⏭"})]}),o.volumeLevel!==null&&v("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[u("span",{children:"Vol"}),u("input",{"aria-label":"Volume",type:"range",min:0,max:100,step:1,value:o.volumeLevel,disabled:d,onChange:f=>{const p=Number(f.target.value);c({volumeLevel:p}),d||i?.setVolume({volumeLevel:p})}}),v("span",{className:"tabular-nums w-8 text-right",children:[o.volumeLevel,"%"]})]}),o.isMuted!==null&&u("button",{type:"button","aria-label":o.isMuted?"Unmute":"Mute",disabled:d,onClick:f=>{if(f.stopPropagation(),!d&&o.isMuted!==null){const p=!o.isMuted;c({isMuted:p}),i?.setMute({muted:p})}},className:L("inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs transition-colors",o.isMuted?"bg-amber-400 text-amber-950":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover",d&&"opacity-40 cursor-not-allowed"),children:o.isMuted?"🔇":"🔊"}),o.availableSources.length>0&&v("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[u("span",{children:"Source"}),v("select",{"aria-label":"Source",value:o.source,disabled:d,onChange:f=>{const p=f.target.value;!d&&p&&(c({source:p}),i?.selectSource({source:p}))},className:"rounded border border-border bg-surface px-1 py-0.5",children:[u("option",{value:"",disabled:!0,children:"—"}),o.availableSources.map(f=>u("option",{value:f,children:f},f))]})]}),o.shuffle!==null&&u("button",{type:"button","aria-label":"Shuffle",disabled:d,onClick:f=>{if(f.stopPropagation(),!d&&o.shuffle!==null){const p=!o.shuffle;c({shuffle:p}),i?.setShuffle({shuffle:p})}},className:L("inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs transition-colors",o.shuffle?"bg-green-400 text-green-950":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover",d&&"opacity-40 cursor-not-allowed"),children:"⇌ Shuffle"}),o.repeat!==null&&v("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[u("span",{children:"Repeat"}),u("select",{"aria-label":"Repeat",value:o.repeat,disabled:d,onChange:f=>{const p=f.target.value;!d&&DT(p)&&(c({repeat:p}),i?.setRepeat({repeat:p}))},className:"rounded border border-border bg-surface px-1 py-0.5",children:Kg.map(f=>u("option",{value:f,children:_T[f]},f))})]})]})]})}function $T(e){return e.slice(0,10)}function BT(e){return e.slice(0,5)}function UT(e){return(e.includes("T")?e:e.replace(" ","T")).slice(0,16)}function GT({value:e,busy:t,onCommit:r,unit:n,min:s,max:i,step:a,precision:l}){const[o,c]=_(Ss(e,l)),d=Number(o),h=o!==""&&!Number.isNaN(d),f=a??1,p=g=>{let b=g;return s!==void 0&&(b=Math.max(s,b)),i!==void 0&&(b=Math.min(i,b)),b},m=()=>{!t&&h&&r(p(d))};return v("div",{className:"inline-flex items-center gap-1",children:[u("button",{type:"button","aria-label":"Decrement",disabled:t,onClick:g=>{if(g.stopPropagation(),!t){const b=p(e-f);c(Ss(b,l)),r(b)}},className:L("inline-flex h-5 w-5 items-center justify-center rounded border border-border bg-surface text-xs transition-colors hover:bg-surface-hover",t&&"opacity-40 cursor-not-allowed"),children:"−"}),u("input",{"aria-label":"Numeric value",type:"number",disabled:t,value:o,onChange:g=>{c(g.target.value);const b=Number(g.target.value);g.target.value!==""&&!Number.isNaN(b)&&(t||r(p(b)))},onBlur:m,onKeyDown:g=>{g.key==="Enter"&&m()},className:L("w-16 rounded border border-border bg-surface px-1 py-0.5 text-xs tabular-nums text-center",t&&"opacity-40 cursor-not-allowed")}),n!==void 0&&u("span",{className:"text-foreground-subtle text-xs",children:n}),u("button",{type:"button","aria-label":"Increment",disabled:t,onClick:g=>{if(g.stopPropagation(),!t){const b=p(e+f);c(Ss(b,l)),r(b)}},className:L("inline-flex h-5 w-5 items-center justify-center rounded border border-border bg-surface text-xs transition-colors hover:bg-surface-hover",t&&"opacity-40 cursor-not-allowed"),children:"+"})]})}function HT({value:e,busy:t,onCommit:r}){const[n,s]=_(e);return u("input",{type:"text",disabled:t,value:n,onChange:i=>s(i.target.value),onBlur:()=>{t||r(n)},onKeyDown:i=>{i.key==="Enter"&&!t&&r(n)},className:L("rounded border border-border bg-surface px-2 py-0.5 text-xs",t&&"opacity-40 cursor-not-allowed")})}function VT({slice:e,busy:t,setValueFn:r,layout:n}){switch(e.kind){case"numeric":return u(GT,{value:typeof e.value=="number"?e.value:Number(e.value),busy:t,onCommit:s=>{r({control:{kind:"numeric",value:s}})},unit:e.unit,min:e.min,max:e.max,step:e.step,precision:e.precision});case"select":return u("select",{"aria-label":"Control value",disabled:t,value:String(e.value),onChange:s=>{s.stopPropagation(),t||r({control:{kind:"select",value:s.target.value}})},className:L("w-full max-w-full min-w-0 truncate rounded border border-border bg-surface px-1 py-0.5 text-xs",t&&"opacity-40 cursor-not-allowed"),children:e.options.map(s=>u("option",{value:s,children:s},s))});case"text":return u(HT,{value:String(e.value),busy:t,onCommit:s=>{r({control:{kind:"text",value:s}})}});case"datetime":{const s=String(e.value),i=e.format??"datetime";return n==="compact"?s===""?u("span",{"aria-label":"Control value",className:"text-xs text-foreground-subtle",children:"—"}):u("span",{"aria-label":"Control value",className:"text-xs text-foreground",children:xc(s,i)}):u("input",{type:i==="date"?"date":i==="time"?"time":"datetime-local","aria-label":"Control value",disabled:t,value:i==="date"?$T(s):i==="time"?BT(s):UT(s),onChange:a=>{a.stopPropagation(),t||r({control:{kind:"datetime",value:a.target.value}})},className:L("rounded border border-border bg-surface px-1 py-0.5 text-xs",t&&"opacity-40 cursor-not-allowed")})}default:return null}}function zg({trpc:e,deviceId:t,features:r,layout:n,optimistic:s}){const{cap:i,slice:a,available:l}=_e({trpc:e,deviceId:t,cap:f=>f.control,slice:f=>f.state.control}),{display:o,applyOptimistic:c}=Ze(a,{enabled:s??!0});if(o===void 0)return null;const d=!l,h=f=>{!d&&i&&(c({value:f.control.value}),i.setValue(f))};return u("div",{"data-kind":o.kind,className:"inline-flex min-w-0 max-w-full items-center gap-1 rounded border border-border px-2 py-1 transition-colors",children:u(VT,{slice:o,busy:d,setValueFn:h,layout:n})})}var jT=5,KT=35;function lo(e,t,r){return Math.min(1,Math.max(0,(e-t)/(r-t)))}function co(e,t,r){return Math.round(t+e*(r-t))}var wr=176,ca=76,Bi=2*Math.PI*ca,cs=Bi*(270/360),uo=wr/2-ca-10;function Rd(e){const t=wr/2,r=wr/2,n=Bi-cs,s=e.mode==="band"?(()=>{const i=e.band.from*cs,a=Math.max(0,(e.band.to-e.band.from)*cs);return{dasharray:`${a} ${Bi-a}`,dashoffset:-i}})():(()=>{const i=e.fraction*cs;return{dasharray:`${i} ${Bi-i}`,dashoffset:void 0}})();return v("svg",{width:wr,height:wr,viewBox:`0 0 ${wr} ${wr}`,"aria-hidden":"true",className:"absolute inset-0",style:{transform:"rotate(135deg)"},children:[u("circle",{cx:t,cy:r,r:ca,fill:"none",stroke:"var(--color-border)",strokeWidth:12,strokeDasharray:`${cs} ${n}`,strokeLinecap:"round"}),u("circle",{cx:t,cy:r,r:ca,fill:"none",stroke:e.color,strokeWidth:12,strokeDasharray:s.dasharray,...s.dashoffset!==void 0?{strokeDashoffset:s.dashoffset}:{},strokeLinecap:"round"})]})}var zT={heat:"#f59e0b",cool:"#60a5fa",auto:"#c084fc",heat_cool:"#e879f9",fan_only:"#94a3b8",dry:"#22d3ee",off:"#d4d4d8"};function WT({trpc:e,deviceId:t,features:r,optimistic:n}){const{cap:s,slice:i,available:a}=_e({trpc:e,deviceId:t,cap:y=>y.climateControl,slice:y=>y.state.climateControl}),{display:l,applyOptimistic:o}=Ze(i,{enabled:n??!0});if(s===void 0||l===void 0)return null;const c=!a,d=zT[l.mode],h=l.mode==="heat_cool"||l.targetLow!==null&&l.targetHigh!==null,f=jT,p=KT,m=!h&&l.target!==null?lo(l.target,f,p):0,g=h&&l.targetLow!==null?lo(l.targetLow,f,p):0,b=h&&l.targetHigh!==null?lo(l.targetHigh,f,p):0;return v("div",{"data-mode":l.mode,className:L("flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4 transition-colors",jg[l.mode]),children:[v("div",{className:"flex flex-col items-center gap-3",children:[v("div",{className:"relative",style:{width:wr,height:wr},children:[h?u(Rd,{mode:"band",band:{from:g,to:b},color:d}):u(Rd,{mode:"fill",fraction:m,color:d}),h?v(Ie,{children:[u("div",{"data-testid":"arc-knob",children:u($i,{fraction:g,color:d,knobTopPx:uo,onDragFraction:y=>{if(c||l.targetHigh===null)return;const S=Math.min(co(y,f,p),l.targetHigh);o({targetLow:S}),s.setTargetRange({targetLow:S,targetHigh:l.targetHigh})}})}),u("div",{"data-testid":"arc-knob",children:u($i,{fraction:b,color:d,knobTopPx:uo,onDragFraction:y=>{if(c||l.targetLow===null)return;const S=Math.max(co(y,f,p),l.targetLow);o({targetHigh:S}),s.setTargetRange({targetLow:l.targetLow,targetHigh:S})}})})]}):u("div",{"data-testid":"arc-knob",children:u($i,{fraction:m,color:d,knobTopPx:uo,onDragFraction:y=>{if(c)return;const S=co(y,f,p);o({target:S}),s.setTarget({target:S})}})}),v("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-0.5 pointer-events-none",children:[v("div",{"data-testid":"current-temp",className:"text-4xl font-bold tabular-nums text-foreground leading-none",children:[l.currentTemp!==null?l.currentTemp:"—",u("span",{className:"text-lg text-foreground-subtle font-normal ml-0.5",children:"°"})]}),!h&&l.target!==null&&v("div",{className:"text-xs font-semibold",style:{color:d},children:["set ",l.target,"°"]}),h&&l.targetLow!==null&&l.targetHigh!==null&&v("div",{className:"text-xs font-semibold",style:{color:d},children:[l.targetLow,"° – ",l.targetHigh,"°"]})]})]}),!h&&l.target!==null&&u("div",{className:"w-[200px]",children:u(vg,{value:`${l.target}°`,onDelta:y=>{if(c||l.target===null)return;const S=l.target+y;o({target:S}),s.setTarget({target:S})}})})]}),u("select",{"aria-label":"Mode",value:l.mode,disabled:c,onChange:y=>{y.stopPropagation();const S=y.target.value;!c&&S&&(o({mode:l.availableModes.find(E=>E===S)??l.mode}),s.setMode({mode:l.availableModes.find(E=>E===S)??l.mode}))},className:L("w-full rounded border border-border bg-surface px-3 py-1.5 text-sm",c&&"opacity-40 cursor-not-allowed"),children:l.availableModes.map(y=>u("option",{value:y,children:y},y))})]})}function QT(e){return e==="locked"||e==="locking"}function Wg(e){return e==="jammed"}var qT={locked:{colorClass:"border-success/30 bg-success/10 text-success",icon:"locked"},locking:{colorClass:"border-success/30 bg-success/10 text-success",icon:"locked"},unlocked:{colorClass:"border-warning/30 bg-warning/10 text-warning",icon:"open"},unlocking:{colorClass:"border-warning/30 bg-warning/10 text-warning",icon:"open"},jammed:{colorClass:"border-danger/30 bg-danger/10 text-danger",icon:"locked"}};function YT({state:e}){const t=qT[e];return u("div",{"data-testid":"lock-glyph","data-state":e,className:L("flex h-16 w-16 items-center justify-center rounded-full border-2",t.colorClass),children:t.icon==="locked"?u(Rc,{className:"h-8 w-8","aria-hidden":"true"}):u(vl,{className:"h-8 w-8","aria-hidden":"true"})})}function XT({state:e}){return u("span",{className:L("text-sm font-medium capitalize",Wg(e)?"text-danger":"text-foreground-muted"),children:e})}function ZT({busy:e,onOpen:t}){return v("button",{type:"button","aria-label":"Open (unlatch)",title:"Open (unlatch)",disabled:e,onClick:r=>{r.stopPropagation(),t()},className:L("inline-flex items-center gap-1.5 rounded-md border border-border px-3 py-1.5 text-xs font-medium","text-foreground-muted hover:bg-surface-hover transition-colors",e&&"opacity-40 cursor-not-allowed"),children:[u(Os,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Open"]})}function JT({trpc:e,deviceId:t,features:r,optimistic:n}){const{cap:s,slice:i,available:a}=_e({trpc:e,deviceId:t,cap:g=>g.lockControl,slice:g=>g.state.lockControl}),{display:l,applyOptimistic:o}=Ze(i,{enabled:n??!0});if(s===void 0||l===void 0)return null;const c=QT(l.state),d=Wg(l.state)||!a,h=r?.includes(Ft.LockOpen)===!0,f=()=>{d||(c?(o({state:"unlocking"}),s.unlock({})):(o({state:"locking"}),s.lock({})))},p=()=>{d||s.open({})},m=c?"Unlock":"Lock";return v("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:[v("div",{className:"flex flex-col items-center gap-2",children:[u(YT,{state:l.state}),u(XT,{state:l.state})]}),u("div",{className:L(d&&"pointer-events-none opacity-40"),children:u(jw,{on:c,targetLabel:m,onConfirm:f})}),h&&u("div",{className:"flex justify-center",children:u(ZT,{busy:d,onOpen:p})})]})}var xr=150,Ui=64,eA=xr/2,Cl=2*Math.PI*Ui,ho=Cl*(270/360);function Qg({fraction:e,color:t,children:r,onDragFraction:n}){const s=Math.min(1,Math.max(0,e)),i=xr/2,a=xr/2,l=Cl-ho,o=s*ho;return v("div",{className:"relative",style:{width:xr,height:xr},children:[v("svg",{width:xr,height:xr,viewBox:`0 0 ${xr} ${xr}`,"aria-hidden":"true",className:"absolute inset-0",style:{transform:"rotate(135deg)"},children:[u("circle",{cx:i,cy:a,r:Ui,fill:"none",stroke:"var(--color-border)",strokeWidth:11,strokeDasharray:`${ho} ${l}`,strokeLinecap:"round"}),u("circle",{cx:i,cy:a,r:Ui,fill:"none",stroke:t,strokeWidth:11,strokeDasharray:`${o} ${Cl-o}`,strokeLinecap:"round"})]}),u("div",{"data-testid":"arc-knob",children:u($i,{fraction:s,color:t,knobTopPx:eA-Ui-10,...n!==void 0?{onDragFraction:n}:{}})}),u("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-0.5 pointer-events-none",children:r})]})}function Zc({on:e,busy:t,onToggle:r}){const n={transform:e?"translateX(30px)":"translateX(3px)"};return u("button",{type:"button","aria-pressed":e,title:e?"Turn off":"Turn on",disabled:t,onClick:s=>{s.stopPropagation(),r()},className:L("relative inline-flex h-8 w-16 items-center rounded-full border transition-colors flex-shrink-0",e?"bg-success/30 border-success/50":"bg-surface-hover border-border",t&&"opacity-60 cursor-not-allowed"),children:u("span",{className:L("absolute h-6 w-6 rounded-full transition-all",e?"bg-success":"bg-foreground-subtle"),style:n})})}var Nl=500,qg=150,tA="linear-gradient(90deg, #9ec9ff, #ffffff, #ffb24d)";function rA(e,t,r){return Math.min(1,Math.max(0,(e-t)/(r-t)))}function nA(e){return rA(e,qg,Nl)}var sA="#f4b740",iA="#d4d4d8";function aA({trpc:e,deviceId:t,features:r,optimistic:n}){const s=_e({trpc:e,deviceId:t,cap:k=>k.switch,slice:k=>k.state.switch}),i=_e({trpc:e,deviceId:t,cap:k=>k.brightness,slice:k=>k.state.brightness}),a=_e({trpc:e,deviceId:t,cap:k=>k.color,slice:k=>k.state.color}),l=Ze(s.slice,{enabled:n??!0}),o=Ze(i.slice,{enabled:n??!0}),c=Ze(a.slice,{enabled:n??!0});if(s.cap===void 0||l.display===void 0)return null;const d=l.display.on===!0,h=!s.available,f=o.display?.percentage??0,p=!i.available,m=d?f/100:0,g=d?sA:iA,b=(r?.includes(Ft.LightColorMired)??!1)&&a.cap!==void 0,y=c.display?.mireds,S=!a.available,E=()=>{if(h)return;const k=!d;l.applyOptimistic({on:k}),s.cap?.setState({on:k})};return v("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:[v("div",{className:"flex flex-col items-center gap-3",children:[v(Qg,{fraction:m,color:g,children:[v("div",{"data-testid":"brightness-readout",className:"text-3xl font-bold tabular-nums text-foreground leading-none",children:[f,u("span",{className:"text-base text-foreground-subtle font-normal ml-0.5",children:"%"})]}),u(Ic,{className:"h-5 w-5 text-foreground-subtle","aria-hidden":"true"})]}),i.cap!==void 0&&v("label",{className:"flex w-full items-center gap-2 text-xs text-foreground-subtle",children:[u("span",{className:"w-16",children:"Brightness"}),u("input",{"aria-label":"Brightness",type:"range",min:0,max:100,step:1,className:"flex-1",value:f,disabled:p||!d,onChange:k=>{const T=Number(k.target.value);o.applyOptimistic({percentage:T}),p||i.cap?.setBrightness({percentage:T})}}),v("span",{className:"tabular-nums w-9 text-right",children:[f,"%"]})]})]}),v("div",{className:"flex items-center justify-between",children:[u("span",{className:"text-sm font-medium text-foreground-muted",children:d?"On":"Off"}),u(Zc,{on:d,busy:h,onToggle:E})]}),b&&v("div",{className:"flex items-center gap-2","data-testid":"color-temp-strip",children:[u(_c,{className:"h-4 w-4 text-foreground-subtle","aria-hidden":"true"}),v("label",{className:"flex-1",children:[u("span",{className:"sr-only",children:"Colour temperature"}),u("input",{"aria-label":"Colour temperature",type:"range",min:qg,max:Nl,step:1,className:"w-full",value:y??Nl,disabled:S||!d,onChange:k=>{const T=Number(k.target.value);c.applyOptimistic({mode:"mired",mireds:T}),S||a.cap?.setColor({color:{mode:"mired",mireds:T}})}}),u("div",{className:"pointer-events-none mt-1",children:u(Al,{fraction:y!==void 0?nA(y):.5,color:tA})})]})]})]})}var oA="#3aa6a0",lA="#d4d4d8";function cA({trpc:e,deviceId:t,features:r,optimistic:n}){const s=_e({trpc:e,deviceId:t,cap:C=>C.switch,slice:C=>C.state.switch}),i=_e({trpc:e,deviceId:t,cap:C=>C.fanControl,slice:C=>C.state.fanControl}),a=Ze(s.slice,{enabled:n??!0}),l=Ze(i.slice,{enabled:n??!0});if(s.cap===void 0||a.display===void 0)return null;const o=a.display.on===!0,c=!s.available,d=l.display?.percentage??0,h=!i.available,f=o?d/100:0,p=o?oA:lA,m=r?.includes(Ft.FanSpeed)??!1,g=(r?.includes(Ft.FanOscillating)??!1)&&i.cap!==void 0,b=l.display?.availablePresets??[],y=(r?.includes(Ft.FanPreset)??!1)&&i.cap!==void 0&&b.length>0,S=l.display?.preset??"",E=l.display?.oscillating===!0,k=()=>{if(c)return;const C=!o;a.applyOptimistic({on:C}),s.cap?.setState({on:C})},T=()=>{if(h)return;const C=!E;l.applyOptimistic({oscillating:C}),i.cap?.setOscillating({oscillating:C})},A=C=>{if(h)return;const M=l.display;if(M===void 0)return;const P=M.percentageStep!==void 0&&M.percentageStep>0?M.percentageStep:1,D=Math.min(100,Math.max(0,Math.round(C*100/P)*P));l.applyOptimistic({percentage:D}),i.cap?.setPercentage({percentage:D})},N=C=>{h||C===""||(l.applyOptimistic({preset:C}),i.cap?.setPreset({preset:C}))};return v("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:[u("div",{className:"flex flex-col items-center gap-3",children:m?v(Qg,{fraction:f,color:p,onDragFraction:A,children:[v("div",{"data-testid":"speed-readout",className:"text-3xl font-bold tabular-nums text-foreground leading-none",children:[d,u("span",{className:"text-base text-foreground-subtle font-normal ml-0.5",children:"%"})]}),u(gl,{className:"h-5 w-5 text-foreground-subtle","aria-hidden":"true"})]}):u("div",{"data-testid":"fan-onoff-icon",className:"flex h-[150px] w-[150px] items-center justify-center",children:u(gl,{className:"h-16 w-16",style:{color:p},"aria-hidden":"true"})})}),y&&u("div",{className:"flex justify-center",children:v("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[u("span",{children:"Preset"}),v("select",{"aria-label":"Fan preset",value:S,disabled:h,onChange:C=>{C.stopPropagation(),N(C.target.value)},className:L("bg-surface border border-border rounded px-1 py-0.5",h&&"opacity-40 cursor-not-allowed"),children:[u("option",{value:"",disabled:!0,children:"—"}),b.map(C=>u("option",{value:C,children:C},C))]})]})}),v("div",{className:"flex items-center justify-between gap-2",children:[g?v("button",{type:"button","aria-label":"Oscillate","aria-pressed":E,disabled:h,onClick:C=>{C.stopPropagation(),T()},className:L("inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs font-medium transition-colors",E?"border-success/50 bg-success/10 text-success":"border-border text-foreground-muted hover:bg-surface-hover",h&&"opacity-40 cursor-not-allowed"),children:[u(vn,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Oscillate"]}):u("span",{className:"text-sm font-medium text-foreground-muted",children:o?"On":"Off"}),u(Zc,{on:o,busy:c,onToggle:k})]})]})}function uA({trpc:e,deviceId:t,optimistic:r}){const{cap:n,slice:s,available:i}=_e({trpc:e,deviceId:t,cap:h=>h.switch,slice:h=>h.state.switch}),{display:a,applyOptimistic:l}=Ze(s,{enabled:r??!0});if(n===void 0||a===void 0)return null;const o=a.on===!0,c=!i,d=()=>{if(c)return;const h=!o;l({on:h}),n.setState({on:h})};return v("div",{className:"flex flex-col items-center gap-4 rounded-lg border border-border bg-surface p-6",children:[u("div",{"data-testid":"switch-glyph","data-state":o?"on":"off",className:L("flex h-16 w-16 items-center justify-center rounded-full border-2 transition-colors",o?"border-success/30 bg-success/10 text-success":"border-border bg-surface-subtle text-foreground-subtle"),children:u(La,{className:"h-8 w-8","aria-hidden":"true"})}),u("span",{className:"text-sm font-medium text-foreground-muted",children:o?"On":"Off"}),u(Zc,{on:o,busy:c,onToggle:d})]})}function dA(e){return e==="playing"||e==="buffering"?"pause":"play"}function hA(e,t){return e===null||t===null||t<=0?0:Math.min(1,Math.max(0,e/t))}function Md(e){if(e===null)return"--:--";const t=Math.floor(e/1e3);return`${Math.floor(t/60)}:${(t%60).toString().padStart(2,"0")}`}function fA({title:e,subtitle:t}){return v("div",{className:"flex flex-col items-center gap-1 text-center",children:[u(aE,{className:"h-6 w-6 text-foreground-subtle","aria-hidden":"true"}),u("span",{className:"text-base font-semibold text-foreground line-clamp-1",children:e??"Nothing playing"}),t&&u("span",{className:"text-xs text-foreground-subtle line-clamp-1",children:t})]})}function fo({label:e,busy:t,onPress:r,children:n,primary:s}){return u("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:i=>{i.stopPropagation(),t||r()},className:L("inline-flex items-center justify-center rounded-full transition-colors",s?"h-12 w-12 bg-primary text-primary-foreground hover:bg-primary/90 shadow-md":"h-10 w-10 text-foreground-muted hover:bg-surface-hover",t&&"opacity-40 cursor-not-allowed"),children:n})}function pA({trpc:e,deviceId:t,features:r,optimistic:n}){const{cap:s,slice:i,available:a}=_e({trpc:e,deviceId:t,cap:E=>E.mediaPlayer,slice:E=>E.state.mediaPlayer}),{display:l,applyOptimistic:o}=Ze(i,{enabled:n??!0});if(s===void 0||l===void 0)return null;const c=!a,d=dA(l.state),h=(r?.includes(Ft.MediaPlayerSeek)??!1)&&l.durationMs!==null&&l.durationMs>0,f=r?.includes(Ft.MediaPlayerNext)??!1,p=r?.includes(Ft.MediaPlayerPrevious)??!1,m=(r?.includes(Ft.MediaPlayerVolume)??!1)&&l.volumeLevel!==null,g=()=>{c||(d==="play"?(o({state:"playing"}),s.play({})):(o({state:"paused"}),s.pause({})))},b=l.currentMedia?.artist??l.currentMedia?.album??null,y=hA(l.positionMs,l.durationMs),S=l.volumeLevel??0;return v("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-6",children:[u(fA,{title:l.currentMedia?.title??null,subtitle:b}),h&&v("div",{"data-testid":"media-seek",className:"flex flex-col gap-1",children:[v("label",{className:"relative block",children:[u("span",{className:"sr-only",children:"Seek"}),u("input",{"aria-label":"Seek",type:"range",min:0,max:l.durationMs??0,step:1e3,className:"absolute inset-0 h-4 w-full cursor-pointer opacity-0",value:l.positionMs??0,disabled:c,onChange:E=>{if(c)return;const k=Number(E.target.value);o({positionMs:k}),s.seek({positionMs:k})}}),u("div",{className:"pointer-events-none",children:u(Al,{fraction:y})})]}),v("div",{className:"flex justify-between text-[11px] tabular-nums text-foreground-subtle",children:[u("span",{children:Md(l.positionMs)}),u("span",{children:Md(l.durationMs)})]})]}),v("div",{className:"flex items-center justify-center gap-4",children:[p&&u(fo,{label:"Previous",busy:c,onPress:()=>void s.previous({}),children:u(xE,{className:"h-5 w-5","aria-hidden":"true"})}),u(fo,{label:d==="play"?"Play":"Pause",busy:c,onPress:g,primary:!0,children:d==="play"?u(Ar,{className:"h-6 w-6","aria-hidden":"true"}):u(Zs,{className:"h-6 w-6","aria-hidden":"true"})}),f&&u(fo,{label:"Next",busy:c,onPress:()=>void s.next({}),children:u(SE,{className:"h-5 w-5","aria-hidden":"true"})})]}),m&&v("div",{"data-testid":"media-volume",className:"flex items-center gap-2",children:[u("button",{type:"button","aria-label":l.isMuted===!0?"Unmute":"Mute",title:l.isMuted===!0?"Unmute":"Mute",disabled:c,onClick:E=>{if(E.stopPropagation(),c||l.isMuted===null)return;const k=!l.isMuted;o({isMuted:k}),s.setMute({muted:k})},className:L("inline-flex h-7 w-7 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",c&&"opacity-40 cursor-not-allowed"),children:l.isMuted===!0?u(RE,{className:"h-4 w-4","aria-hidden":"true"}):u(Oc,{className:"h-4 w-4","aria-hidden":"true"})}),v("label",{className:"relative block flex-1",children:[u("span",{className:"sr-only",children:"Volume"}),u("input",{"aria-label":"Volume",type:"range",min:0,max:100,step:1,className:"absolute inset-0 h-4 w-full cursor-pointer opacity-0",value:S,disabled:c,onChange:E=>{if(c)return;const k=Number(E.target.value);o({volumeLevel:k}),s.setVolume({volumeLevel:k})}}),u("div",{className:"pointer-events-none",children:u(Al,{fraction:S/100})})]}),v("span",{className:"w-9 text-right text-[11px] tabular-nums text-foreground-subtle",children:[S,"%"]})]})]})}var mA={disarmed:{label:"Disarmed",colorClass:"border-border bg-surface-subtle text-foreground-subtle",icon:"disarmed"},armed_home:{label:"Armed Home",colorClass:"border-success/30 bg-success/10 text-success",icon:"armed"},armed_away:{label:"Armed Away",colorClass:"border-success/30 bg-success/10 text-success",icon:"armed"},armed_night:{label:"Armed Night",colorClass:"border-success/30 bg-success/10 text-success",icon:"armed"},armed_vacation:{label:"Armed Vacation",colorClass:"border-success/30 bg-success/10 text-success",icon:"armed"},armed_custom_bypass:{label:"Armed (Bypass)",colorClass:"border-success/30 bg-success/10 text-success",icon:"armed"},arming:{label:"Arming…",colorClass:"border-warning/30 bg-warning/10 text-warning",icon:"pending"},disarming:{label:"Disarming…",colorClass:"border-warning/30 bg-warning/10 text-warning",icon:"pending"},pending:{label:"Pending",colorClass:"border-warning/30 bg-warning/10 text-warning",icon:"pending"},triggered:{label:"Triggered",colorClass:"border-danger/30 bg-danger/10 text-danger",icon:"triggered"}},gA={home:"Home",away:"Away",night:"Night",vacation:"Vacation",custom_bypass:"Bypass"};function vA(e){return e.startsWith("armed_")}function bA(e){return e==="arming"||e==="disarming"}function yA({icon:e}){return e==="disarmed"?u(bE,{className:"h-8 w-8","aria-hidden":"true"}):e==="triggered"?u(Mc,{className:"h-8 w-8","aria-hidden":"true"}):e==="pending"?u(Mm,{className:"h-8 w-8","aria-hidden":"true"}):u(vE,{className:"h-8 w-8","aria-hidden":"true"})}function Pd({label:e,active:t,busy:r,onSelect:n}){return u("button",{type:"button","aria-label":e,"aria-pressed":t,disabled:r,onClick:s=>{s.stopPropagation(),r||n()},className:L("flex-1 rounded-md px-3 py-2 text-sm font-medium transition-colors",t?"bg-primary text-primary-foreground shadow-sm":"text-foreground-muted hover:bg-surface-hover",r&&"opacity-40 cursor-not-allowed"),children:e})}function Yg({state:e,availableModes:t,busy:r,onDisarm:n,onArm:s}){const i=vA(e),a=bA(e);return v("div",{className:"flex items-stretch gap-1 rounded-lg border border-border bg-surface-subtle p-1",children:[u(Pd,{label:"Disarm",active:!i&&!a,busy:r,onSelect:n}),t.map(l=>u(Pd,{label:gA[l],active:!a&&e===`armed_${l}`,busy:r,onSelect:()=>s(l)},l))]})}function Xg(e,t,r){const{cap:n,slice:s,available:i}=_e({trpc:e,deviceId:t,cap:h=>h.alarmPanel,slice:h=>h.state.alarmPanel}),{display:a,applyOptimistic:l}=Ze(s,{enabled:r??!0}),o=!i;return{display:a,capPresent:n!==void 0,busy:o,handleDisarm:()=>{n===void 0||o||(l({state:"disarming"}),n.disarm({}))},handleArm:h=>{n===void 0||o||(l({state:"arming"}),n.arm({mode:h}))}}}function xA({trpc:e,deviceId:t,optimistic:r}){const{display:n,capPresent:s,busy:i,handleDisarm:a,handleArm:l}=Xg(e,t,r);return!s||n===void 0?null:u(Yg,{state:n.state,availableModes:n.availableModes,busy:i,onDisarm:a,onArm:l})}function SA({trpc:e,deviceId:t,optimistic:r}){const{display:n,capPresent:s,busy:i,handleDisarm:a,handleArm:l}=Xg(e,t,r);if(!s||n===void 0)return null;const o=mA[n.state];return v("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-6",children:[v("div",{className:"flex flex-col items-center gap-2",children:[u("div",{"data-testid":"alarm-state","data-state":n.state,className:L("flex h-16 w-16 items-center justify-center rounded-full border-2",o.colorClass),children:u(yA,{icon:o.icon})}),u("span",{className:"text-sm font-medium text-foreground-muted",children:o.label})]}),u(Yg,{state:n.state,availableModes:n.availableModes,busy:i,onDisarm:a,onArm:l})]})}function EA({children:e}){return u("div",{className:"flex flex-col items-stretch gap-3 rounded-lg border border-border bg-surface p-4",children:e})}function Zg(e,t){const{cap:r}=_e({trpc:e,deviceId:t,cap:n=>n.switch,slice:n=>n.state.switch});return r!==void 0}function wA({trpc:e,deviceId:t,features:r,optimistic:n}){return Zg(e,t)?u(Xc,{trpc:e,deviceId:t,features:r,layout:"compact",optimistic:n}):null}function kA(e,t){const{cap:r}=_e({trpc:e,deviceId:t,cap:n=>n.lockControl,slice:n=>n.state.lockControl});return r!==void 0}function TA({trpc:e,deviceId:t,features:r,optimistic:n}){return kA(e,t)?u(AT,{trpc:e,deviceId:t,features:r,layout:"compact",optimistic:n}):null}function AA({trpc:e,deviceId:t,features:r,optimistic:n}){return Zg(e,t)?v("div",{className:"inline-flex items-center gap-2",children:[u(Xc,{trpc:e,deviceId:t,features:r,layout:"compact",optimistic:n}),u(CT,{trpc:e,deviceId:t,features:r,layout:"compact",optimistic:n})]}):null}function CA(e,t){const{cap:r}=_e({trpc:e,deviceId:t,cap:n=>n.fanControl,slice:n=>n.state.fanControl});return r!==void 0}function NA({trpc:e,deviceId:t,features:r,optimistic:n}){return CA(e,t)?v("div",{className:"inline-flex items-center gap-2",children:[u(Xc,{trpc:e,deviceId:t,features:r,layout:"compact",optimistic:n}),u(NT,{trpc:e,deviceId:t,features:r,layout:"compact",optimistic:n})]}):null}function LA(e,t){const{cap:r}=_e({trpc:e,deviceId:t,cap:n=>n.climateControl,slice:n=>n.state.climateControl});return r!==void 0}function IA({trpc:e,deviceId:t,features:r,optimistic:n}){return LA(e,t)?u(RT,{trpc:e,deviceId:t,features:r,layout:"compact",optimistic:n}):null}function RA(e,t){const{cap:r}=_e({trpc:e,deviceId:t,cap:n=>n.mediaPlayer,slice:n=>n.state.mediaPlayer});return r!==void 0}function MA({trpc:e,deviceId:t,features:r,optimistic:n}){return RA(e,t)?u(FT,{trpc:e,deviceId:t,features:r,layout:"compact",optimistic:n}):null}function Jg(e,t){const{cap:r}=_e({trpc:e,deviceId:t,cap:n=>n.control,slice:n=>n.state.control});return r!==void 0}function PA({trpc:e,deviceId:t,features:r,optimistic:n}){return Jg(e,t)?u(zg,{trpc:e,deviceId:t,features:r,layout:"compact",optimistic:n}):null}function DA({trpc:e,deviceId:t,features:r,optimistic:n}){return Jg(e,t)?u(EA,{children:u(zg,{trpc:e,deviceId:t,features:r,layout:"full",optimistic:n})}):null}var _A={InlineControl:Zw,HeroCard:tk},Dr={InlineControl:rk,HeroCard:yg},Dd={InlineControl:Ak,HeroCard:_k},OA={InlineControl:Ok,HeroCard:Fk},_d={InlineControl:wA,HeroCard:uA},FA={InlineControl:TA,HeroCard:JT},$A={InlineControl:AA,HeroCard:aA},BA={InlineControl:NA,HeroCard:cA},UA={InlineControl:IA,HeroCard:WT},GA={InlineControl:MA,HeroCard:pA},HA={InlineControl:xA,HeroCard:SA},VA={InlineControl:PA,HeroCard:DA},jA={InlineControl:zk,HeroCard:Wk},KA={InlineControl:Xk,HeroCard:Zk},zA={InlineControl:eT,HeroCard:sT},WA={InlineControl:aT,HeroCard:lT},QA={InlineControl:dT,HeroCard:fT},qA={InlineControl:gT,HeroCard:yT},YA={InlineControl:wT,HeroCard:kT},XA={[te.Cover]:_A,[te.Valve]:zA,[te.Humidifier]:WA,[te.WaterHeater]:QA,[te.Camera]:Dr,[te.Hub]:Dr,[te.Switch]:_d,[te.Siren]:_d,[te.Light]:$A,[te.Fan]:BA,[te.Sensor]:Dd,[te.Thermostat]:UA,[te.Button]:{InlineControl:Qw,HeroCard:qw},[te.EventEmitter]:Dr,[te.Update]:OA,[te.Generic]:Dr,[te.Notifier]:Dr,[te.Script]:Dr,[te.Automation]:Dr,[te.Lock]:FA,[te.MediaPlayer]:GA,[te.AlarmPanel]:HA,[te.Control]:VA,[te.Presence]:Dd,[te.Weather]:qA,[te.Vacuum]:jA,[te.LawnMower]:KA,[te.Container]:Dr,[te.Image]:YA},ZA={[te.Cover]:!0,[te.Valve]:!0,[te.Thermostat]:!0,[te.Control]:!0,[te.Button]:!0,[te.MediaPlayer]:!0,[te.AlarmPanel]:!0,[te.Lock]:!1,[te.Vacuum]:!1,[te.LawnMower]:!1,[te.Humidifier]:!1,[te.Switch]:!1,[te.Siren]:!1,[te.Light]:!1,[te.Fan]:!1,[te.WaterHeater]:!1,[te.Sensor]:!1,[te.Presence]:!1,[te.EventEmitter]:!1,[te.Notifier]:!1,[te.Script]:!1,[te.Automation]:!1,[te.Camera]:!1,[te.Hub]:!1,[te.Update]:!1,[te.Generic]:!1,[te.Weather]:!1,[te.Container]:!1,[te.Image]:!1},ev=new Set(Object.values(te));function Jc(e){return ev.has(e)?XA[e]:null}function ua(e,t){return t==="table"?"fit":ev.has(e)&&ZA[e]?Gw:t==="center"?Vw:Hw}function JA(e){return e instanceof Error?e.message:String(e)}function eC({trpc:e,deviceId:t,deviceName:r}){const{dev:n,cap:s}=_e({trpc:e,deviceId:t,cap:p=>p.reboot,slice:()=>{}}),[i,a]=_(!1),[l,o]=_(!1),[c,d]=_(null);if(n===null||s===void 0||s===null)return null;const h=p=>{p.stopPropagation(),d(null),a(!0)},f=async()=>{if(!l){d(null),o(!0);try{await s.reboot({}),a(!1)}catch(p){d(JA(p))}finally{o(!1)}}};return v(Ie,{children:[u("button",{type:"button",onClick:h,className:L("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors flex-shrink-0",i&&"bg-surface-hover text-foreground"),title:"Reboot device","aria-label":"Reboot device","aria-haspopup":"dialog","aria-expanded":i,children:u(yl,{className:"h-3 w-3"})}),u($c,{open:i,onOpenChange:p=>{l||a(p)},children:v(Ia,{width:"sm",onClick:p=>p.stopPropagation(),children:[v(Bc,{children:[v(Gc,{className:"flex items-center gap-2",children:[u(yl,{className:"h-4 w-4 text-amber-400"}),"Reboot device?"]}),v(Hc,{children:["This will restart ",r,". It may be unavailable for a moment."]})]}),c!==null&&u("div",{className:"mt-2 px-3 py-2 rounded border border-danger/40 bg-danger/10 text-xs text-danger",children:c}),v(Uc,{children:[u(tr,{type:"button",variant:"ghost",size:"sm",disabled:l,onClick:()=>{l||a(!1)},children:"Cancel"}),v(tr,{type:"button",variant:"danger",size:"sm",disabled:l,onClick:()=>{f()},children:[l&&u(vt,{className:"h-3.5 w-3.5 animate-spin"}),"Reboot"]})]})]})})]})}var tv=new Set([te.Sensor,te.Presence]);function Ll({trpc:e,device:t,controlPlacement:r}){const n=qc(t.id),s=r??"right";if(t.disabled)return null;if(t.type===te.Container){const h=Js(n,t.linkDeviceId,t.primaryChildEntityId),f=h===null?void 0:n.find(p=>p.id===h.id);return f===void 0?null:u(tC,{trpc:e,child:f,placement:s})}const i=tv.has(t.type),a=(i?null:Jc(t.type))?.InlineControl??null,l=ua(t.type,s),o=hg(t),c=(t.features??[]).includes("rebootable"),d=(t.features??[]).includes("pan-tilt-zoom");return v(Ie,{children:[i&&v(la,{align:ua(t.type,s),children:[o&&u(po,{trpc:e,deviceId:t.id,features:t.features}),u(Yc,{trpc:e,device:t})]}),a!==null&&v(la,{align:l,onClick:h=>h.stopPropagation(),children:[o&&u(po,{trpc:e,deviceId:t.id,features:t.features}),u(a,{trpc:e,deviceId:t.id,features:t.features})]}),!i&&a===null&&o&&u(po,{trpc:e,deviceId:t.id,features:t.features}),d&&u(sC,{trpc:e,deviceId:t.id}),c&&u(eC,{trpc:e,deviceId:t.id,deviceName:t.name})]})}function tC({trpc:e,child:t,placement:r}){if(tv.has(t.type))return u(la,{align:ua(t.type,r),children:u(Yc,{trpc:e,device:t})});const n=Jc(t.type)?.InlineControl??null;return n===null?null:u(la,{align:ua(t.type,r),onClick:s=>s.stopPropagation(),children:u(n,{trpc:e,deviceId:t.id,features:t.features})})}function po({trpc:e,deviceId:t,features:r}){const{dev:n,cap:s,slice:i,available:a}=_e({trpc:e,deviceId:t,cap:h=>h.motionTrigger,slice:h=>h.state.motionTrigger,requireFeature:"motion-trigger",deviceFeatures:r}),[l,o]=_(!1);if(n!==null&&!s)return null;const c=i?.enabled===!0,d=async h=>{if(h.stopPropagation(),!(l||!a||!s)){o(!0);try{await s.setMotionTrigger({enabled:!c})}finally{o(!1)}}};return u("button",{type:"button",onClick:h=>{d(h)},disabled:l||!a,className:L("inline-flex h-4 w-4 items-center justify-center rounded transition-colors flex-shrink-0",c?"text-primary bg-primary/10":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover",(l||!a)&&"opacity-50"),title:a?c?"Motion-trigger: on (click to disable)":"Motion-trigger: off (click to enable)":"Awaiting state…","aria-pressed":c,children:u(ur,{className:"h-2.5 w-2.5"})})}var rC=4,nC=300;function sC({trpc:e,deviceId:t}){const r=ne(null),n=ne(null),[s,i]=_(null),a=s!==null,l=mg(e,t,{enabled:a}),o=()=>i(null),c=()=>{const h=r.current;if(!h)return;const f=h.getBoundingClientRect(),p=8,m=Math.min(nC,window.innerWidth-p*2),g=Math.max(p,Math.min(f.right-m,window.innerWidth-m-p)),b=f.bottom+rC;i({top:b,left:g,width:m,maxHeight:Math.max(160,window.innerHeight-b-p)})};return ae(()=>{if(!a)return;const h=p=>{const m=r.current,g=n.current,b=p.target;b!==null&&(m&&m.contains(b)||g&&g.contains(b)||o())},f=p=>{p.key==="Escape"&&(p.stopPropagation(),o())};return document.addEventListener("mousedown",h),document.addEventListener("touchstart",h),document.addEventListener("keydown",f),()=>{document.removeEventListener("mousedown",h),document.removeEventListener("touchstart",h),document.removeEventListener("keydown",f)}},[a]),v(Ie,{children:[u("button",{ref:r,type:"button",onClick:h=>{h.stopPropagation(),a?o():c()},className:L("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors flex-shrink-0",a&&"bg-surface-hover text-foreground"),title:"PTZ controls","aria-label":"PTZ controls","aria-haspopup":"dialog","aria-expanded":a,children:u(HS,{className:"h-3 w-3"})}),s&&Ys(u("div",{ref:n,style:{position:"fixed",top:s.top,left:s.left,width:s.width,maxHeight:s.maxHeight},className:"z-[9999] overflow-y-auto rounded-lg border border-border bg-surface shadow-lg shadow-black/30",onClick:h=>h.stopPropagation(),children:u(gg,{mode:"panel",controls:l})}),document.body)]})}function iC({icon:e,label:t,onClick:r,danger:n=!1}){return u("button",{type:"button","aria-label":t,title:t,onClick:r,className:L("inline-flex h-6 w-6 items-center justify-center rounded transition-colors flex-shrink-0",n?"text-danger hover:bg-danger/10":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover"),children:u(e,{className:"h-3.5 w-3.5"})})}function aC({device:e,onDelete:t}){const r=is(),n=async()=>{await r({title:"Delete device?",message:`This will remove "${e.name.trim()!==""?e.name:`#${String(e.id)}`}" and all its settings. This action cannot be undone.`,confirmLabel:"Delete",variant:"danger"})&&t(e)};return u("span",{onClick:s=>s.stopPropagation(),children:u(iC,{icon:zt,label:"Delete device",danger:!0,onClick:()=>{n()}})})}var oC=Object.freeze([]);function lC(e){return e==="native"?"native":"enhanced"}function cC(e){return e.map(t=>({kind:"marker",feature:t}))}function uC(e,t){const r=new Map,n=t.entries??[];for(const i of n)r.set(i.capName,i);const s=[];for(const i of e){const a=Mw[i];if(a===void 0){s.push({kind:"marker",feature:i});continue}const l=r.get(a);l&&s.push({kind:lC(l.kind),feature:i,capName:a})}return s}function dC(e,t,r){const[n,s]=_(null),[i,a]=_(!1),[l,o]=_(!0);return ae(()=>{if(t===null){s(null),a(!1),o(!1);return}let c=!1;o(!0),a(!1);const d=async()=>{try{const f=await e.deviceManager.getBindings.query({deviceId:t});if(c)return;s(f),o(!1)}catch{if(c)return;a(!0),o(!1)}};d();const h=e.live?.onEvent.subscribe({category:"capability.binding-changed"},{onData:f=>{const p=f.data?.source;if(!p){d();return}p.type==="device"&&p.id===t&&d()}});return()=>{c=!0,h?.unsubscribe()}},[e,t]),r.length===0?{loading:l,resolved:oC}:l||i||!n?{loading:l,resolved:cC(r)}:{loading:!1,resolved:uC(r,n)}}var hC=[];function Il({trpc:e,device:t,flags:r,accessoryCount:n,adoptedCount:s,showFeatureRow:i=!1}){const a=n+s,l=r.showChildrenAccordion&&a>0,o=t.features??hC,c=i&&o.length>0,{resolved:d}=dC(e,c?t.id:null,o),h=c&&d.length>0;return!l&&!h?null:v("div",{className:"flex items-center gap-1.5 flex-nowrap whitespace-nowrap min-w-0",children:[l&&u(fC,{accessoryCount:n,adoptedCount:s}),h&&u(pC,{resolved:d})]})}function fC({accessoryCount:e,adoptedCount:t}){const r=e+t;return r===0?null:v("span",{className:"text-[9px] font-medium text-foreground-subtle bg-surface-elevated/60 rounded px-1.5 py-0.5 flex-shrink-0",title:t>0&&e>0?`${String(t)} adopted · ${String(e)} accessor${e===1?"y":"ies"}`:t>0?`${String(t)} adopted`:`${String(e)} accessor${e===1?"y":"ies"}`,children:["+",r]})}var rv=240,Od=200;function pC({resolved:e}){const t=ne(null),[r,n]=_(null);return v("span",{ref:t,className:"relative inline-flex items-center gap-1 cursor-help",onMouseEnter:()=>{const a=t.current;if(!a)return;const l=a.getBoundingClientRect();n({top:window.innerHeight-l.bottom>=Od?l.bottom+4:l.top-Od-4,left:Math.max(8,Math.min(l.left,window.innerWidth-rv-8))})},onMouseLeave:()=>n(null),children:[e.map(a=>{const l=cg[a.feature];return l?u("span",{className:"inline-flex items-center justify-center h-4 w-4 rounded bg-surface-elevated/60 text-foreground-subtle",title:ug[a.feature]??a.feature,children:u(l,{className:"h-2.5 w-2.5"})},a.feature):null}),r&&Ys(u(mC,{resolved:e,position:r}),document.body)]})}function mC({resolved:e,position:t}){return v("div",{style:{position:"fixed",top:t.top,left:t.left,width:rv,pointerEvents:"none"},className:"z-[9999] rounded-md border border-border bg-surface shadow-lg shadow-black/30 p-2",children:[u("h5",{className:"text-[9px] font-semibold uppercase tracking-wider text-foreground-subtle mb-1.5",children:"Features"}),u("ul",{className:"space-y-0.5",children:e.map(r=>u(gC,{entry:r},r.feature))})]})}function gC({entry:e}){const t=cg[e.feature],r=ug[e.feature]??e.feature;return v("li",{className:"flex items-center justify-between gap-2 text-[10px]",children:[v("span",{className:"flex items-center gap-1.5 text-foreground",children:[t&&u(t,{className:"h-3 w-3 text-foreground-subtle"}),u("span",{children:r})]}),u(vC,{kind:e.kind})]})}function vC({kind:e}){return e==="marker"?u("span",{className:"text-[8.5px] px-1 rounded text-foreground-subtle",title:"Informational marker (no cap registered)",children:"marker"}):u("span",{className:L("text-[8.5px] px-1 rounded",e==="native"?"bg-success/15 text-success":"bg-primary/15 text-primary"),children:e})}var Fd={horizontal:"h-3.5 w-3.5",stacked:"h-4 w-4 mt-0.5"};function Rl({device:e,variant:t,flags:r,parent:n,integrationIcon:s,hasChildren:i,expanded:a,onToggleExpand:l,onNavigateToParent:o,stacked:c=!1}){const d=lg(_w(e,qc(e.id))),h=c?Fd.stacked:Fd.horizontal;return v("div",{className:L(c?"flex items-start gap-2 w-full min-w-0":"flex items-center gap-2 flex-1 min-w-0"),children:[r.showChildrenAccordion&&i?u("button",{type:"button","data-testid":"chevron-slot",onClick:f=>{f.stopPropagation(),l()},className:L("flex items-center justify-center text-foreground-subtle hover:text-foreground transition-colors flex-shrink-0",h),"aria-label":a?"Collapse children":"Expand children","aria-expanded":a,children:a?u(yt,{className:"h-3 w-3"}):u(nr,{className:"h-3 w-3"})}):r.showChildrenAccordion?u("span",{"data-testid":"chevron-slot",className:L("flex-shrink-0",h)}):null,u(d,{className:L("text-foreground-subtle flex-shrink-0",c?"h-4 w-4 mt-0.5":t==="minimal"?"h-3 w-3":"h-3.5 w-3.5")}),v("div",{className:"flex-1 min-w-0",children:[v("div",{className:L("min-w-0",c?"flex flex-col gap-1":"flex items-center gap-1.5"),children:[r.showIntegrationIcon&&s&&u("span",{className:"flex-shrink-0",children:s}),u("span",{className:L("font-semibold text-foreground",c?"text-[13px] leading-snug line-clamp-2 break-words":L("truncate",t==="minimal"?"text-[10.5px]":"text-[11px]")),title:e.name,children:e.name})]}),(r.showId||r.showStableId)&&v("div",{className:"mt-0.5 flex items-center gap-1 text-[9px] text-foreground-subtle font-mono truncate",title:r.showStableId?`stableId: ${e.stableId}`:void 0,children:[r.showId&&v("span",{className:"flex-shrink-0 tabular-nums",children:["#",String(e.id)]}),r.showId&&r.showStableId&&u("span",{className:"flex-shrink-0 opacity-50",children:"·"}),r.showStableId&&u("span",{className:"truncate",children:Ow(e.stableId)})]}),r.showParentBadge&&n&&v("button",{type:"button",onClick:f=>{f.stopPropagation(),o(n.id)},className:"mt-0.5 inline-flex max-w-full items-center gap-1 text-[9px] text-foreground-subtle hover:text-primary transition-colors",title:`Open parent: ${n.name} (#${String(n.id)})`,children:[u(Nm,{className:"h-2.5 w-2.5 shrink-0"}),v("span",{className:"truncate",children:["Under: ",n.name]})]})]})]})}function bC(e,t){return yw(e,t,r=>r.battery)??null}function yC(e,t){const r=Qt(e,t),n=ne(!1),{data:s,isLoading:i,isFetching:a,refetch:l}=gc({queryKey:["device",t,"snapshot"],queryFn:()=>{if(!r)throw new Error("useDeviceSnapshotImage: device proxy not ready");const d=n.current;return n.current=!1,r.snapshot?.getSnapshot({force:d})??null},enabled:r!==null&&t!==null,staleTime:1e4,gcTime:1440*60*1e3,refetchOnWindowFocus:!1,refetchOnReconnect:!1,retry:!1}),o=s?`data:${s.contentType};base64,${s.base64}`:null;function c(){n.current=!0,l()}return{src:o,loading:i||a,refresh:c}}var xC=50;function SC(e){return e<=10?fm:e<=30?pS:e<=70?Cc:hm}function EC(e,t){return t!=="none"?"text-emerald-400":e<=10?"text-rose-400":e<=30?"text-amber-400":"text-foreground-subtle"}function wC({status:e,variant:t="compact",className:r}){if(!e)return null;if(e.binary===!0){const l=e.percentage<xC,o=l?fm:hm;return v("span",{className:L("inline-flex items-center gap-1 text-[10px] font-medium",l?"text-rose-400":"text-foreground-subtle",r),title:`Battery: ${l?"low":"normal"}`,children:[u(o,{className:"h-3.5 w-3.5"}),u("span",{children:l?"Low":"Normal"})]})}const n=SC(e.percentage),s=EC(e.percentage,e.charging),i=e.charging==="solar"?Dc:e.charging==="dc"?uE:null,a=e.sleeping;return v("span",{className:L("inline-flex items-center gap-1 text-[10px] font-medium",s,r),title:`Battery: ${Math.round(e.percentage)}%`+(e.charging!=="none"?` · charging (${e.charging})`:"")+(e.sleeping?" · sleeping":""),children:[u(n,{className:"h-3.5 w-3.5"}),v("span",{children:[Math.round(e.percentage),"%"]}),i&&u(i,{className:"h-3 w-3"}),a&&u(Na,{className:"h-3 w-3 text-blue-300"}),t==="full"&&e.charging!=="none"&&u("span",{className:"text-foreground-subtle",children:e.charging})]})}function Ml({trpc:e,device:t,status:r,enabled:n,showStatusPills:s=!1}){const i=yC(e,n&&t.online?t.id:null),a=(t.features??[]).includes("battery-operated"),l=s&&a&&!t.disabled,o=bC(e,l?t.id:null);if(!n&&!l)return null;const c=r==="offline"||r==="disabled",d=r==="offline"?"Offline — no snapshot":r==="disabled"?"Disabled":"No snapshot yet";return v("span",{className:"inline-flex items-center gap-1.5 flex-nowrap whitespace-nowrap",children:[l&&o&&u(wC,{status:o}),n&&u(Hg,{src:c?null:i.src,alt:t.name,placeholder:d,thumbClassName:"h-7 w-7 rounded"})]})}function kC(e,t){if(e==="disabled")return"Disabled";if(e==="online")return"Online";const r=kp(t);return r===null?"Offline":`Offline · last seen ${r}`}function Pl({status:e,lastChangedAt:t}){return u("span",{className:L("h-1.5 w-1.5 rounded-full flex-shrink-0",e==="disabled"?"bg-warning":e==="online"?"bg-success":"bg-danger"),title:kC(e,t)})}var KV=["name","icon","type","manufacturer","features","previewActions"],TC={devices:["name","icon","type","manufacturer","features","previewActions"],"integration-detail":["name","manufacturer","features","previewActions"]};function AC(e){return TC[e]}var zV={name:0,previewActions:1,icon:2,features:3,type:4,manufacturer:5},Vn={name:"",previewActions:"",icon:"",features:"hidden md:table-cell",type:"hidden lg:table-cell",manufacturer:"hidden xl:table-cell"},eu="manufacturer",nv="model";function sv(e){if(typeof e=="string"){const t=e.trim();return t===""?null:t}return typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean"?String(e):null}function Bs(e,t){return e==null?null:sv(e[t])}function CC(e){const t=Bs(e.metadata,eu),r=Bs(e.metadata,nv);return t!==null&&r!==null?`${t} · ${r}`:t??r??null}function NC(e){if(e==null)return[];const t=[];for(const r of Object.keys(e)){const n=sv(e[r]);n!==null&&t.push({key:r,value:n})}return t}function $d(e){return Bs(e.metadata,eu)!==null}function Bd(e){return(Bs(e.metadata,eu)??"").toLowerCase()}function Ud(e){return(Bs(e.metadata,nv)??"").toLowerCase()}function LC(e,t){const r=Bd(e).localeCompare(Bd(t));return r!==0?r:Ud(e).localeCompare(Ud(t))}function IC({device:e}){const t=CC(e),r=NC(e.metadata);if(t===null&&r.length===0)return u("span",{className:"text-xs text-foreground-subtle/60",children:"—"});const n=t??"—";return r.length===0?u("span",{className:"block truncate text-xs text-foreground-subtle",children:n}):v(KE,{className:"block w-full min-w-0",children:[u(zE,{className:"block w-full min-w-0",children:u("span",{className:"block truncate text-xs text-foreground-subtle",children:n})}),u(WE,{className:"whitespace-normal text-left max-w-xs",children:u("dl",{className:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5",children:r.map(s=>v("div",{className:"contents",children:[u("dt",{className:"font-medium opacity-70",children:s.key}),u("dd",{className:"break-words",children:s.value})]},s.key))})})]})}function WV({title:e,count:t,children:r,defaultOpen:n=!0}){const[s,i]=_(n);return v("div",{className:"rounded-md border border-border-subtle/50",children:[v("button",{type:"button",onClick:()=>i(a=>!a),className:L("w-full flex items-center gap-1.5 px-2 py-1.5 text-left transition-colors","hover:bg-surface-hover"),"aria-expanded":s,children:[s?u(yt,{className:"h-3 w-3 text-foreground-subtle flex-shrink-0"}):u(nr,{className:"h-3 w-3 text-foreground-subtle flex-shrink-0"}),u("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle flex-1 truncate",children:e}),u("span",{className:"text-[10px] font-medium text-foreground-subtle/70 tabular-nums",children:t})]}),s&&u("div",{className:"space-y-1 px-1 pb-1.5",children:r})]})}var RC="Disabled";function MC(e,t,r){const n=t.filter(c=>c.disabled!==!0),s=PC(t.filter(c=>c.disabled===!0));if(r===void 0||r.length===0)return{sections:[],ungrouped:n,disabledSection:s};const i=new Map;for(const c of n)i.set(c.stableId,c);const a=[],l=new Map,o=new Set;for(const c of r){const d=`${e}-${c.childKey}`,h=i.get(d);if(h===void 0)continue;let f=l.get(c.section);f===void 0&&(f={title:c.section,entries:[],collapsed:!1},l.set(c.section,f),a.push(c.section)),f.entries.push({child:h,order:c.order??Number.MAX_SAFE_INTEGER}),c.collapsed===!0&&(f.collapsed=!0),o.add(h.id)}return{sections:a.map(c=>{const d=l.get(c),h=[...d===void 0?[]:d.entries].sort((p,m)=>p.order!==m.order?p.order-m.order:p.child.name.localeCompare(m.child.name)),f=d===void 0?!0:!d.collapsed;return{title:c,children:h.map(p=>p.child),defaultOpen:f}}),ungrouped:n.filter(c=>!o.has(c.id)),disabledSection:s}}function PC(e){if(e.length!==0)return{title:RC,children:[...e].sort((t,r)=>t.name.localeCompare(r.name)),defaultOpen:!1,muted:!0}}function tu(e){const{trpc:t,device:r,parent:n,integrationIcon:s,onNavigate:i,className:a,renderRowAction:l,onDelete:o,selection:c}=e,d=Rw(e),h=e.variant??"compact",f=e.view??"card",p=!r.disabled,m=r.isCamera??r.type.toLowerCase()==="camera",g=e.children??[],b=g.filter(wd),y=g.filter(B=>!wd(B)),S=g.length>0,[E,k]=_(!1),T=e.expanded??E,A=e.onToggleExpand??(()=>k(B=>!B)),N=B=>{i?.(B)},C=e.rowClickSelects===!0&&c!==void 0,M=()=>{if(C&&c!==void 0){c.onToggle();return}N(r.id)},P=e.indentLevel??(e.isAccessoryRow?2:0),D=Dw(r,g),$=p?D?"online":"offline":"disabled";return f==="table"?u(_C,{trpc:t,device:r,variant:h,flags:d,parent:n??null,integrationIcon:s??null,accessoryCount:b.length,adoptedCount:y.length,hasChildren:S,expanded:T,onToggleExpand:A,onRowClick:M,rowSelects:C,rowSelected:c?.selected??!1,onNavigate:N,displayStatus:$,isCamera:m,showSnapshot:d.showSnapshot&&m,isAccessoryRow:e.isAccessoryRow??!1,indentLevel:P,className:a,renderRowAction:l??null,onDelete:o??null,selection:c,showTypeCell:e.showTypeCell??!0,showManufacturerCell:e.showManufacturerCell??!0,showFeaturesCell:e.showFeaturesCell??!0}):h==="minimal"?v("div",{className:L("rounded-lg border border-border bg-surface transition-colors",!p&&"opacity-60",a),children:[v("div",{"data-testid":"device-card-body",onClick:M,...C?{role:"button","aria-pressed":c?.selected??!1,tabIndex:0,onKeyDown:B=>{(B.key==="Enter"||B.key===" ")&&(B.preventDefault(),M())}}:{},className:L("flex items-center gap-2 cursor-pointer hover:border-foreground-subtle/30 w-full px-2.5 py-1.5",c?.selected&&"bg-primary/10"),children:[c&&u("input",{type:"checkbox",checked:c.selected,onChange:c.onToggle,onClick:B=>B.stopPropagation(),"aria-label":`Select ${r.name}`,className:"flex-shrink-0"}),u(Rl,{device:r,variant:h,flags:d,parent:n??null,integrationIcon:s??null,hasChildren:S,expanded:T,onToggleExpand:A,onNavigateToParent:N}),u(Il,{trpc:t,device:r,flags:d,accessoryCount:b.length,adoptedCount:y.length,showFeatureRow:!1}),u(Ml,{trpc:t,device:r,status:$,enabled:d.showSnapshot&&m,showStatusPills:!0}),u(Ll,{trpc:t,device:r,flags:d,controlPlacement:"right"}),l&&u("span",{onClick:B=>B.stopPropagation(),children:l(r)}),u(Pl,{status:$})]}),T&&S&&u(kd,{trpc:t,accessoryChildren:b,adoptedChildren:y,onNavigate:N})]}):v("div",{className:L("group rounded-xl border border-border bg-surface transition-colors","hover:border-foreground-subtle/30",!p&&"opacity-60",a),children:[v("div",{"data-testid":"device-card-body",onClick:M,...C?{role:"button","aria-pressed":c?.selected??!1,tabIndex:0,onKeyDown:B=>{(B.key==="Enter"||B.key===" ")&&(B.preventDefault(),M())}}:{},className:L("flex flex-col gap-2 cursor-pointer w-full p-3 rounded-xl",c?.selected&&"bg-primary/10"),children:[v("div",{className:"flex items-start justify-between gap-2",children:[c&&u("input",{type:"checkbox",checked:c.selected,onChange:c.onToggle,onClick:B=>B.stopPropagation(),"aria-label":`Select ${r.name}`,className:"flex-shrink-0 mt-0.5"}),u(Rl,{device:r,variant:h,flags:d,parent:n??null,integrationIcon:s??null,hasChildren:S,expanded:T,onToggleExpand:A,onNavigateToParent:N,stacked:!0}),u(Pl,{status:$})]}),u(Il,{trpc:t,device:r,flags:d,accessoryCount:b.length,adoptedCount:y.length,showFeatureRow:!1}),v("div",{className:"flex items-center justify-end gap-1.5",children:[u(Ml,{trpc:t,device:r,status:$,enabled:d.showSnapshot&&m,showStatusPills:!0}),u(Ll,{trpc:t,device:r,flags:d,controlPlacement:"right"}),l&&u("span",{onClick:B=>B.stopPropagation(),children:l(r)})]})]}),T&&S&&u(kd,{trpc:t,accessoryChildren:b,adoptedChildren:y,onNavigate:N})]})}var DC={0:"pl-2",1:"pl-6",2:"pl-8"};function _C(e){const{trpc:t,device:r,variant:n,flags:s,parent:i,integrationIcon:a,accessoryCount:l,adoptedCount:o,hasChildren:c,expanded:d,onToggleExpand:h,onNavigate:f,onRowClick:p,rowSelects:m,rowSelected:g,displayStatus:b,isCamera:y,showSnapshot:S,isAccessoryRow:E,indentLevel:k,className:T,renderRowAction:A,onDelete:N,selection:C,showTypeCell:M,showManufacturerCell:P,showFeaturesCell:D}=e,$=qc(r.id);return v("tr",{onClick:p,...m?{role:"button","aria-pressed":g,tabIndex:0,onKeyDown:B=>{(B.key==="Enter"||B.key===" ")&&(B.preventDefault(),p())}}:{},className:L("group cursor-pointer hover:bg-surface-hover transition-colors",!c&&"border-b border-border-subtle/40",E&&"bg-foreground-subtle/[0.03]",g&&"bg-primary/10",T),children:[u("td",{className:L("sticky left-0 z-[1] py-1.5 align-middle pr-2 transition-colors",g?"bg-primary/10 group-hover:bg-surface-hover":E?"bg-surface-subtle group-hover:bg-surface-hover":"bg-surface group-hover:bg-surface-hover","w-64 max-w-[16rem] min-w-0 overflow-hidden",DC[k]),children:v("div",{className:"flex items-center gap-1.5",children:[C&&u("input",{type:"checkbox",checked:C.selected,onChange:C.onToggle,onClick:B=>B.stopPropagation(),"aria-label":`Select ${r.name}`,className:"flex-shrink-0"}),u(Rl,{device:r,variant:n,flags:s,parent:i,integrationIcon:a,hasChildren:c,expanded:d,onToggleExpand:h,onNavigateToParent:f})]})}),M&&u("td",{className:L(Vn.type,"px-2 py-1.5 align-middle text-[10px] text-foreground-subtle whitespace-nowrap"),children:fg(r,$)}),P&&u("td",{className:L(Vn.manufacturer,"px-2 py-1.5 align-middle w-40 max-w-[10rem] min-w-0 overflow-hidden"),children:u(IC,{device:r})}),D&&u("td",{className:L(Vn.features,"px-2 py-1.5 align-middle"),children:u(Il,{trpc:t,device:r,flags:s,accessoryCount:l,adoptedCount:o,showFeatureRow:!0})}),u("td",{className:"px-2 py-1.5 align-middle text-right whitespace-nowrap",children:v("span",{className:"inline-flex items-center justify-end gap-1.5",children:[u(Ll,{trpc:t,device:r,flags:s,controlPlacement:"table"}),u(Ml,{trpc:t,device:r,status:b,enabled:S&&y,showStatusPills:!0}),A&&u("span",{onClick:B=>B.stopPropagation(),children:A(r)}),N&&u(aC,{device:r,onDelete:N}),u(Pl,{status:b})]})})]})}function Gd({selectedIds:e,onClear:t,remove:r,disable:n,enable:s}){const[i,a]=_(!1);if(e.size===0)return null;const l=[...e],o=l.length,c=()=>{for(const g of l)n({deviceId:g});t()},d=()=>{for(const g of l)s({deviceId:g});t()},h=()=>{a(!0)},f=()=>{for(const g of l)r({deviceId:g});a(!1),t()},p=()=>{a(!1)},m=()=>{a(!1),t()};return v("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg border border-border bg-surface-hover",children:[v("span",{className:"text-xs font-medium text-foreground-subtle shrink-0",children:[o," selected"]}),u("div",{className:"h-3.5 w-px bg-border shrink-0","aria-hidden":"true"}),v("div",{className:"flex items-center gap-1.5 flex-wrap",children:[u("button",{type:"button",onClick:c,className:L("inline-flex items-center h-6 px-2.5 rounded-md border text-[10.5px] font-medium transition-colors","border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface"),children:"Disable"}),u("button",{type:"button",onClick:d,className:L("inline-flex items-center h-6 px-2.5 rounded-md border text-[10.5px] font-medium transition-colors","border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface"),children:"Enable"}),i?v(Ie,{children:[v("button",{type:"button",onClick:f,className:L("inline-flex items-center h-6 px-2.5 rounded-md border text-[10.5px] font-medium transition-colors","border-red-500/50 bg-red-500/10 text-red-400 hover:bg-red-500/20"),children:["Confirm delete ",o,"?"]}),u("button",{type:"button",onClick:p,className:L("inline-flex items-center h-6 px-2.5 rounded-md border text-[10.5px] font-medium transition-colors","border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface"),children:"Cancel"})]}):u("button",{type:"button",onClick:h,className:L("inline-flex items-center h-6 px-2.5 rounded-md border text-[10.5px] font-medium transition-colors","border-red-500/40 bg-red-500/10 text-red-400 hover:bg-red-500/20"),children:"Delete"}),u("button",{type:"button",onClick:m,className:L("inline-flex items-center h-6 px-2.5 rounded-md border text-[10.5px] font-medium transition-colors","border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface"),children:"Clear"})]})]})}function OC(e){const[t,r]=_(!1),n=ne(null),s=e.selectedIds.size;return ae(()=>{if(!t)return;const i=l=>{const o=l.target instanceof Node?l.target:null;o&&n.current&&!n.current.contains(o)&&r(!1)},a=l=>{l.key==="Escape"&&r(!1)};return document.addEventListener("mousedown",i),document.addEventListener("touchstart",i),document.addEventListener("keydown",a),()=>{document.removeEventListener("mousedown",i),document.removeEventListener("touchstart",i),document.removeEventListener("keydown",a)}},[t]),s===0?null:v(Ie,{children:[u("div",{className:"hidden sm:block",children:u(Gd,{...e})}),v("div",{ref:n,"data-testid":"batch-actions-compact",className:"relative sm:hidden",children:[v("button",{type:"button",onClick:()=>r(i=>!i),"aria-haspopup":"menu","aria-expanded":t,className:"inline-flex items-center gap-1.5 h-7 px-2.5 rounded-full border border-primary/40 bg-primary/15 text-[10.5px] font-medium text-primary",children:[v("span",{children:["Actions · ",String(s)]}),u(yt,{className:`h-3 w-3 transition-transform ${t?"rotate-180":""}`})]}),t&&u("div",{role:"menu",className:"absolute left-0 top-full mt-1 z-30 rounded-lg border border-border bg-surface shadow-md",children:u(Gd,{...e})})]})]})}function iv(e,t){const[r,n]=_(e);return ae(()=>{const s=setTimeout(()=>n(e),t);return()=>clearTimeout(s)},[e,t]),r}var av=[25,50,100,200],ov="camstack.device-list.pageSize";function ru(e){return av.includes(e)}function FC(e){return ru(e)?e:50}function $C(e){if(typeof window>"u")return e;try{const t=window.localStorage.getItem(ov);if(t===null)return e;const r=Number.parseInt(t,10);return Number.isFinite(r)&&ru(r)?r:e}catch{return e}}function BC(e){if(!(typeof window>"u"))try{window.localStorage.setItem(ov,String(e))}catch{}}function UC(e){const t=FC(e),[r,n]=_(()=>$C(t));return[r,q(s=>{ru(s)&&(n(s),BC(s))},[])]}function GC(e){const t=new Map;for(const r of e)t.set(r.id,r);return e.filter(r=>{if(r.parentDeviceId===null||r.parentDeviceId===void 0)return!0;const n=t.get(r.parentDeviceId);return n?lv.has(n.type.toLowerCase()):!0})}var lv=new Set(["hub","nvr"]);function HC(e){const t=new Map;for(const s of e)t.set(s.id,s);const r=[],n=new Map;for(const s of e){const i=s.parentDeviceId;if(i==null){r.push(s);continue}const a=t.get(i);if(!a){r.push(s);continue}const l=s.role!==null&&s.role!==void 0;if(lv.has(a.type)&&!l){r.push(s);continue}const o=n.get(i);o?o.push(s):n.set(i,[s])}return{topLevel:r,accessoriesByParent:n}}function Hd(e){return e.toLowerCase().replace(/[-_\s]+/g,"")}function ps(e,t){const r=Hd(e);return r===""?!0:Hd(t).includes(r)}var Vd=2;function VC(e,t){if(t<=1)return[{kind:"page",n:1}];if(t<=7){const i=[];for(let a=1;a<=t;a++)i.push({kind:"page",n:a});return i}const r=[],n=Math.max(2,e-Vd),s=Math.min(t-1,e+Vd);r.push({kind:"page",n:1}),n>2&&r.push({kind:"ellipsis",side:"left"});for(let i=n;i<=s;i++)r.push({kind:"page",n:i});return s<t-1&&r.push({kind:"ellipsis",side:"right"}),r.push({kind:"page",n:t}),r}function Dl({currentPage:e,totalItems:t,pageSize:r,onPageChange:n,itemNoun:s="devices"}){if(t<=r)return null;const i=Math.ceil(t/r),a=(e-1)*r+1,l=Math.min(e*r,t),o=VC(e,i);return v("div",{className:"flex items-center justify-between gap-4 flex-wrap pt-2 text-[11px] text-foreground-subtle",children:[v("span",{children:["Showing ",a,"–",l," of ",t," ",s]}),v("span",{className:"inline-flex items-center gap-1",children:[u("button",{type:"button","aria-label":"Previous page",disabled:e===1,onClick:()=>n(e-1),className:L("inline-flex items-center justify-center h-7 w-7 rounded border border-border bg-surface text-foreground-subtle","hover:text-foreground hover:bg-surface-hover transition-colors","disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-surface"),children:u(SS,{className:"h-3 w-3"})}),o.map((c,d)=>c.kind==="ellipsis"?u("span",{className:"px-1 text-foreground-subtle/60 select-none",children:"…"},`e-${d}`):u("button",{type:"button",onClick:()=>n(c.n),className:L("inline-flex items-center justify-center h-7 min-w-7 px-1.5 rounded border text-[10.5px] font-medium transition-colors",c.n===e?"border-primary/40 bg-primary/10 text-primary":"border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface-hover"),children:c.n},`p-${c.n}`)),u("button",{type:"button","aria-label":"Next page",disabled:e===i,onClick:()=>n(e+1),className:L("inline-flex items-center justify-center h-7 w-7 rounded border border-border bg-surface text-foreground-subtle","hover:text-foreground hover:bg-surface-hover transition-colors","disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-surface"),children:u(nr,{className:"h-3 w-3"})})]})]})}function jC({label:e,options:t,selected:r,onChange:n}){const[s,i]=_(!1),a=ne(null);ae(()=>{if(!s)return;const d=f=>{const p=f.target instanceof Node?f.target:null;p&&a.current&&!a.current.contains(p)&&i(!1)},h=f=>{f.key==="Escape"&&i(!1)};return document.addEventListener("mousedown",d),document.addEventListener("touchstart",d),document.addEventListener("keydown",h),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("touchstart",d),document.removeEventListener("keydown",h)}},[s]);const l=new Set(r),o=r.length,c=d=>{const h=new Set(l);h.has(d)?h.delete(d):h.add(d),n(t.filter(f=>h.has(f.id)).map(f=>f.id))};return v("div",{ref:a,className:"relative",children:[v("button",{type:"button",onClick:()=>i(d=>!d),"aria-haspopup":"listbox","aria-expanded":s,className:`inline-flex items-center gap-1.5 h-7 px-2.5 rounded-full border text-[10.5px] font-medium transition-colors ${o>0?"border-primary/40 bg-primary/15 text-primary":"border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface-hover"}`,children:[v("span",{children:[e,o>0?` · ${String(o)}`:""]}),u(yt,{className:`h-3 w-3 transition-transform ${s?"rotate-180":""}`})]}),s&&v("div",{role:"listbox",className:"absolute left-0 top-full mt-1 z-30 min-w-[180px] max-h-72 overflow-y-auto rounded-lg border border-border bg-surface shadow-xl py-1",children:[o>0&&u("button",{type:"button",onClick:()=>n([]),className:"flex w-full items-center px-3 py-1.5 text-left text-[10.5px] text-foreground-subtle hover:bg-surface-hover hover:text-foreground",children:"Clear selection"}),t.map(d=>{const h=l.has(d.id),f=d.icon;return v("button",{type:"button",role:"option","aria-selected":h,onClick:()=>c(d.id),className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-[10.5px] text-foreground hover:bg-surface-hover",children:[u("span",{className:`flex h-3.5 w-3.5 items-center justify-center rounded border shrink-0 ${h?"border-primary bg-primary":"border-border"}`,children:h&&u(Lr,{className:"h-2.5 w-2.5 text-primary-foreground"})}),f&&u(f,{className:"h-3.5 w-3.5 shrink-0 text-foreground-subtle"}),u("span",{className:"truncate",children:d.label})]},d.id)})]})]})}function cv({label:e,options:t,selected:r,onChange:n}){const s=ne(null),[i,a]=_(null);ae(()=>{const d=s.current;if(!d||typeof ResizeObserver>"u")return;const h=new ResizeObserver(f=>{const p=f[0];p&&a(p.contentRect.width)});return h.observe(d),()=>h.disconnect()},[]);const l=new Set(r),o=d=>{const h=new Set(l);h.has(d)?h.delete(d):h.add(d),n(t.filter(f=>h.has(f.id)).map(f=>f.id))},c=56+t.length*88;return u("div",{ref:s,className:"min-w-0 flex-1",children:i!==null&&i>=c?v("div",{className:"flex items-center gap-1.5 flex-wrap",children:[u("span",{className:"text-[10px] font-medium uppercase tracking-wider text-foreground-subtle",children:e}),t.map(d=>{const h=l.has(d.id),f=d.icon;return v("button",{type:"button",onClick:()=>o(d.id),"aria-pressed":h,className:`inline-flex items-center gap-1 h-7 px-2.5 rounded-full border text-[10.5px] font-medium transition-colors ${h?"border-primary/40 bg-primary/15 text-primary":"border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface-hover"}`,children:[f&&u(f,{className:"h-3 w-3 shrink-0"}),d.label]},d.id)})]}):u(jC,{label:e,options:t,selected:r,onChange:n})})}function KC({view:e,onViewChange:t,hideView:r=!1,typeOptions:n,selectedTypes:s,onTypesChange:i,addons:a,selectedAddons:l,onAddonsChange:o,hideAddons:c=!1}){return v("div",{className:"flex items-center gap-2 flex-wrap",children:[!r&&e!==void 0&&t!==void 0&&v("span",{className:"inline-flex border border-border rounded-md overflow-hidden",children:[u("button",{type:"button",onClick:()=>t("cards"),className:L("inline-flex items-center justify-center h-7 w-8 transition-colors",e==="cards"?"bg-primary/10 text-primary":"bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface-hover"),"aria-label":"Cards view",children:u(YS,{className:"h-3.5 w-3.5"})}),u("button",{type:"button",onClick:()=>t("table"),className:L("inline-flex items-center justify-center h-7 w-8 border-l border-border transition-colors",e==="table"?"bg-primary/10 text-primary":"bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface-hover"),"aria-label":"Table view",children:u(kE,{className:"h-3.5 w-3.5"})})]}),n&&n.length>0&&u(cv,{label:"Type",options:n,selected:s,onChange:i}),!c&&a&&a.length>0&&u(zC,{addons:a,selected:l,onChange:o})]})}function zC({addons:e,selected:t,onChange:r}){const[n,s]=_(!1),i=ne(null);ae(()=>{if(!n)return;const c=h=>{const f=h.target;f&&i.current&&!i.current.contains(f)&&s(!1)},d=h=>{h.key==="Escape"&&s(!1)};return document.addEventListener("mousedown",c),document.addEventListener("touchstart",c),document.addEventListener("keydown",d),()=>{document.removeEventListener("mousedown",c),document.removeEventListener("touchstart",c),document.removeEventListener("keydown",d)}},[n]);const a=new Set(t),l=t.length,o=c=>{const d=new Set(a);d.has(c)?d.delete(c):d.add(c),r(e.filter(h=>d.has(h.id)).map(h=>h.id))};return v("div",{ref:i,className:"relative",children:[v("button",{type:"button",onClick:()=>s(c=>!c),className:L("inline-flex items-center gap-1.5 h-7 px-2.5 rounded-full border text-[10.5px] font-medium transition-colors",l>0?"border-primary/40 bg-primary/15 text-primary":"border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface-hover"),"aria-haspopup":"listbox","aria-expanded":n,children:[v("span",{children:["Integration",l>0?` · ${String(l)}`:""]}),u(yt,{className:L("h-3 w-3 transition-transform",n&&"rotate-180")})]}),n&&v("div",{role:"listbox",className:"absolute left-0 top-full mt-1 z-30 min-w-[180px] max-h-72 overflow-y-auto rounded-lg border border-border bg-surface shadow-xl py-1",children:[l>0&&u("button",{type:"button",onClick:()=>r([]),className:"flex w-full items-center px-3 py-1.5 text-left text-[10.5px] text-foreground-subtle hover:bg-surface-hover hover:text-foreground",children:"Clear selection"}),e.map(c=>{const d=a.has(c.id);return v("button",{type:"button",role:"option","aria-selected":d,onClick:()=>o(c.id),className:L("flex w-full items-center gap-2 px-3 py-1.5 text-left text-[10.5px] transition-colors",d?"text-primary":"text-foreground hover:bg-surface-hover"),children:[u("span",{className:L("flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded border",d?"border-primary bg-primary/20":"border-border"),children:d&&u(Lr,{className:"h-2.5 w-2.5"})}),c.icon&&u("span",{className:"inline-flex items-center",children:c.icon}),u("span",{className:"truncate",children:c.name})]},c.id)})]})]})}function WC({variant:e,onClearFilters:t}){return v("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[u(QS,{className:"h-8 w-8 text-foreground-subtle/40 mb-3"}),u("p",{className:"text-sm font-medium text-foreground-subtle",children:e==="filtered"?"No devices match the current filters":"No devices yet"}),e==="filtered"&&t&&u("button",{type:"button",onClick:t,className:"mt-2 text-[11px] text-primary hover:underline",children:"Clear filters"})]})}function jd(e){return e?e.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}function cr(e,t){if(e==="root")return t==="addons"?"addon":t==="types"?"type":t;switch(t){case"view":return"deviceView";case"page":return"devicePage";case"types":return"deviceType";case"q":return"deviceQ";case"addons":return"deviceAddon"}}function Kd(e){try{const t=localStorage.getItem(`camstack:${e}:lastFilters`);if(!t)return{};const r=JSON.parse(t);return typeof r!="object"||r===null?{}:r}catch{return{}}}function QC(e,t){try{localStorage.setItem(`camstack:${e}:lastFilters`,JSON.stringify(t))}catch{}}function zd(e,t,r){const n=new URLSearchParams(window.location.search),s=n.get(cr(e,"view")),i=s==="cards"||s==="table"?s:r.view??t,a=n.get(cr(e,"page")),l=a?parseInt(a,10):1;return{view:i,page:Number.isFinite(l)&&l>=1?l:1,addons:jd(n.get(cr(e,"addons"))??r.addon??null),types:jd(n.get(cr(e,"types"))??r.type??null),q:n.get(cr(e,"q"))??r.q??""}}function qC(e,t,r){const n=new URLSearchParams(window.location.search),s=(l,o)=>{o===null||o===""?n.delete(l):n.set(l,o)};s(cr(e,"view"),t.view===r?null:t.view),s(cr(e,"page"),t.page===1?null:String(t.page)),s(cr(e,"addons"),t.addons.length>0?t.addons.join(","):null),s(cr(e,"types"),t.types.length>0?t.types.join(","):null),s(cr(e,"q"),t.q||null);const i=n.toString(),a=i?`${window.location.pathname}?${i}`:window.location.pathname;window.history.replaceState(null,"",a)}function YC(e){const{scope:t,defaultView:r,lsKey:n}=e,[s,i]=_(()=>zd(t,r,Kd(n))),a=ne(s);a.current=s,ae(()=>{const o=()=>{const c=zd(t,r,Kd(n));a.current=c,i(c)};return window.addEventListener("popstate",o),()=>window.removeEventListener("popstate",o)},[t,r,n]);const l=q(o=>{const c=o(a.current);a.current=c,i(c),qC(t,c,r),QC(n,{view:c.view,addon:c.addons.length>0?c.addons.join(","):null,type:c.types.length>0?c.types.join(","):null,q:c.q})},[t,r,n]);return{state:s,setView:q(o=>l(c=>({...c,view:o})),[l]),setPage:q(o=>l(c=>({...c,page:o})),[l]),setAddons:q(o=>l(c=>({...c,addons:o,page:1})),[l]),setTypes:q(o=>l(c=>({...c,types:o,page:1})),[l]),setQ:q(o=>l(c=>({...c,q:o,page:1})),[l]),clearFilters:q(()=>l(o=>({...o,addons:[],types:[],q:"",page:1})),[l])}}function XC({rows:e,accessoriesByParent:t,trpc:r,resolveIntegrationIcon:n,resolveParent:s,onNavigate:i,renderRowAction:a,selectable:l,rowClickSelects:o,activeSelected:c,onToggleSelection:d}){return u("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3 items-stretch",children:e.map(h=>{const f=t.get(h.id)??[],p=l?{selected:c.has(h.id),onToggle:()=>d(h.id)}:void 0;return u(tu,{trpc:r,device:h,view:"card",integrationIcon:n?.(h.addonId)??null,parent:h.parentDeviceId!==null?s?.(h.parentDeviceId)??null:null,children:f,onNavigate:i??void 0,renderRowAction:a??void 0,selection:p,rowClickSelects:o},h.id)})})}function mo({columnId:e,label:t,sort:r,onSort:n}){const s=r!==null&&r.columnId===e;return v("button",{type:"button",onClick:()=>n(e),className:"group/sort inline-flex items-center gap-0.5 uppercase tracking-wider hover:text-foreground transition-colors",children:[u("span",{children:t}),s?r.dir==="asc"?u(dn,{className:"h-3 w-3 flex-shrink-0"}):u(yt,{className:"h-3 w-3 flex-shrink-0"}):u(dn,{className:L("h-3 w-3 flex-shrink-0 opacity-0 transition-opacity","group-hover/sort:opacity-30")})]})}function go(e,t){return e===null||e.columnId!==t?"none":e.dir==="asc"?"ascending":"descending"}var ZC=new Set(["hub","nvr"]);function JC(e,t){return e.parentDeviceId===null||t===null?0:ZC.has(t.toLowerCase())?1:0}function e2({rows:e,accessoriesByParent:t,autoExpandedParents:r,devices:n,visibleColumns:s,trpc:i,resolveIntegrationIcon:a,resolveParent:l,onNavigate:o,renderRowAction:c,onDeleteDevice:d,selectable:h,rowClickSelects:f,activeSelected:p,onToggleSelection:m,sort:g,onSort:b}){const y=s.includes("type"),S=s.includes("features"),E=s.includes("manufacturer"),k=s.includes("icon"),T=oe(()=>{const A=new Map;for(const N of n)A.set(N.id,N.type);return A},[n]);return u("div",{className:"rounded-lg border border-border bg-surface overflow-x-auto",children:v("table",{className:"w-full border-collapse",children:[u("thead",{children:v("tr",{className:"border-b border-border",children:[u("th",{"aria-sort":go(g,"name"),className:"sticky left-0 z-[1] bg-surface text-left px-2 py-2 text-[9.5px] font-medium uppercase tracking-wider text-foreground-subtle w-64 max-w-[16rem]",children:u(mo,{columnId:"name",label:"Name",sort:g,onSort:b})}),y&&u("th",{"aria-sort":go(g,"type"),className:L(Vn.type,"text-left px-2 py-2 text-[9.5px] font-medium uppercase tracking-wider text-foreground-subtle w-24"),children:u(mo,{columnId:"type",label:"Type",sort:g,onSort:b})}),E&&u("th",{"aria-sort":go(g,"manufacturer"),className:L(Vn.manufacturer,"text-left px-2 py-2 text-[9.5px] font-medium uppercase tracking-wider text-foreground-subtle w-40"),children:u(mo,{columnId:"manufacturer",label:"Hardware",sort:g,onSort:b})}),S&&u("th",{className:L(Vn.features,"text-left px-2 py-2 text-[9.5px] font-medium uppercase tracking-wider text-foreground-subtle w-32"),children:"Features"}),u("th",{className:"text-right px-2 py-2 text-[9.5px] font-medium uppercase tracking-wider text-foreground-subtle w-32",children:"Preview"})]})}),u("tbody",{children:e.map(A=>{const N=t.get(A.id)??[],C=N.length>0,M=r.has(A.id),P=A.parentDeviceId!==null?l?.(A.parentDeviceId)??null:null,D=A.parentDeviceId!==null?T.get(A.parentDeviceId)??null:null,$=h?{selected:p.has(A.id),onToggle:()=>m(A.id)}:void 0;return u(t2,{parent:A,accessories:N,hasAccessories:C,forceExpanded:M,trpc:i,integrationIcon:k?a?.(A.addonId)??null:null,showType:y,showManufacturer:E,showFeatures:S,parentRowParent:P,indentLevel:JC(A,D),onNavigate:o??null,renderRowAction:c??null,onDeleteDevice:d,selection:$,rowClickSelects:f},A.id)})})]})})}function t2({parent:e,accessories:t,hasAccessories:r,forceExpanded:n,trpc:s,integrationIcon:i,showType:a,showManufacturer:l,showFeatures:o,parentRowParent:c,indentLevel:d,onNavigate:h,renderRowAction:f,onDeleteDevice:p,selection:m,rowClickSelects:g}){const[b,y]=_(n),S=ne(n);ae(()=>{S.current!==n&&(y(n),S.current=n)},[n]);const E=()=>y(D=>!D),k=r&&b,T=oe(()=>MC(e.stableId,t,e.childLayout),[e.stableId,e.childLayout,t]),[A,N]=_(()=>{const D=T.sections.filter($=>!$.defaultOpen).map($=>$.title);return T.disabledSection!==void 0&&!T.disabledSection.defaultOpen&&D.push(T.disabledSection.title),new Set(D)}),C=D=>N($=>{const B=new Set($);return B.has(D)?B.delete(D):B.add(D),B}),M=2+(a?1:0)+(l?1:0)+(o?1:0),P=T.disabledSection;return v(Ie,{children:[u(tu,{trpc:s,device:e,view:"table",integrationIcon:i,parent:c,children:t,onNavigate:h??void 0,showChildrenAccordion:!0,expanded:b,onToggleExpand:E,indentLevel:d,renderRowAction:f??void 0,onDelete:p??void 0,selection:m,rowClickSelects:g,showTypeCell:a,showManufacturerCell:l,showFeaturesCell:o}),k&&T.ungrouped.map(D=>u(uv,{trpc:s,accessory:D,showType:a,showManufacturer:l,showFeatures:o,onNavigate:h},D.id)),k&&T.sections.map(D=>{const $=!A.has(D.title);return u(Wd,{title:D.title,count:D.children.length,open:$,colSpan:M,onToggle:()=>C(D.title),rows:D.children,trpc:s,showType:a,showManufacturer:l,showFeatures:o,onNavigate:h},D.title)}),k&&P!==void 0&&u(Wd,{title:P.title,count:P.children.length,open:!A.has(P.title),colSpan:M,onToggle:()=>C(P.title),rows:P.children,trpc:s,showType:a,showManufacturer:l,showFeatures:o,onNavigate:h,muted:!0},P.title)]})}function uv({trpc:e,accessory:t,showType:r,showManufacturer:n,showFeatures:s,onNavigate:i,muted:a}){return u(tu,{trpc:e,device:t,view:"table",integrationIcon:null,parent:null,isAccessoryRow:!0,showChildrenAccordion:!1,onNavigate:i??void 0,showTypeCell:r,showManufacturerCell:n,showFeaturesCell:s,className:a===!0?"opacity-60":void 0})}function Wd({title:e,count:t,open:r,colSpan:n,onToggle:s,rows:i,trpc:a,showType:l,showManufacturer:o,showFeatures:c,onNavigate:d,muted:h}){return v(Ie,{children:[u("tr",{className:L("border-b border-border-subtle/40 bg-surface",h===!0&&"opacity-60"),children:u("td",{colSpan:n,className:"p-0",children:v("button",{type:"button",onClick:s,className:"w-full flex items-center gap-1.5 pl-8 pr-2 py-1 text-left hover:bg-surface-hover transition-colors","aria-expanded":r,children:[r?u(yt,{className:"h-3 w-3 text-foreground-subtle flex-shrink-0"}):u(nr,{className:"h-3 w-3 text-foreground-subtle flex-shrink-0"}),u("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle flex-1 truncate",children:e}),u("span",{className:"text-[10px] font-medium text-foreground-subtle/70 tabular-nums",children:t})]})})}),r&&i.map(f=>u(uv,{trpc:a,accessory:f,showType:l,showManufacturer:o,showFeatures:c,onNavigate:d,muted:h},f.id))]})}function Qd(e){return Wc(e.type).label.toLowerCase()}function qd(e){return e.name.toLowerCase()}function r2(e){return e==="name"?(t,r)=>qd(t).localeCompare(qd(r)):e==="type"?(t,r)=>Qd(t).localeCompare(Qd(r)):LC}function n2(e,t){return e===null||e.columnId!==t?{columnId:t,dir:"asc"}:e.dir==="asc"?{columnId:t,dir:"desc"}:null}function s2(e,t){if(t===null)return[...e];const r=r2(t.columnId),n=t.dir==="asc"?1:-1;return[...e].sort((s,i)=>{if(t.columnId==="manufacturer"){const a=$d(s);if(a!==$d(i))return a?-1:1}return n*r(s,i)})}var i2={cards:24,table:50};function a2(e){const{devices:t,trpc:r,context:n="devices",defaultView:s="table",filters:i,forceAddon:a,resolveIntegrationIcon:l,resolveParent:o,onNavigate:c,pageSize:d=i2,urlScope:h="root",lsKey:f=h==="root"?"devices":"integrations:nested",renderRowAction:p,onDeleteDevice:m,selectable:g=!1,selectedIds:b,onSelectionChange:y,batchActions:S}=e,[E,k]=_(!1),[T,A]=_(new Set),N=b??T,C=Ue=>{const Ge=new Set(N);Ge.has(Ue)?Ge.delete(Ue):Ge.add(Ue),b===void 0&&A(Ge),y?.(Ge)},M=()=>{b===void 0?A(new Set):y?.(new Set)},P=()=>{M(),k(!1)},D=g||S!==void 0&&E,$=S!==void 0&&E,B=oe(()=>AC(n),[n]),[j,U]=_(null),F=Ue=>U(Ge=>n2(Ge,Ue)),Y=i?.typeOptions,I=oe(()=>Y??Aw(),[Y]),R=YC({scope:h,defaultView:s,lsKey:f}),O=R.state.view,[K,W]=UC(d.table),J=O==="cards"?d.cards:K,[Q,ee]=_(R.state.q),ie=iv(Q,300);ae(()=>{ie!==R.state.q&&R.setQ(ie)},[ie]);const se=oe(()=>a!==void 0?[a]:R.state.addons,[a,R.state.addons]),be=oe(()=>{const Ue=new Map;for(const Ge of t){if(Ge.parentDeviceId===null||Ge.parentDeviceId===void 0)continue;const tt=Ue.get(Ge.parentDeviceId);tt?tt.push(Ge):Ue.set(Ge.parentDeviceId,[Ge])}return Ue},[t]),ye=oe(()=>{const Ue=R.state.q,Ge=se.length>0?new Set(se):null,tt=R.state.types.length>0?new Set(R.state.types):null;return t.filter(We=>!(Ge&&!Ge.has(We.addonId)||tt&&!tt.has(fg(We,be.get(We.id)))||Ue.trim()!==""&&!ps(Ue,We.name)&&!ps(Ue,We.stableId)))},[t,be,se,R.state.types,R.state.q]),ue=oe(()=>HC(ye),[ye]),we=oe(()=>s2(ue.topLevel,j),[ue.topLevel,j]),le=oe(()=>{if(R.state.q.trim()==="")return new Set;const Ue=R.state.q,Ge=new Set;for(const[tt,We]of ue.accessoriesByParent.entries())We.some(Ht=>ps(Ue,Ht.name)||ps(Ue,Ht.stableId))&&Ge.add(tt);return Ge},[ue.accessoriesByParent,R.state.q]),Z=ue.topLevel.length,ce=Math.max(1,Math.ceil(Z/J)),Ae=Math.min(R.state.page,ce),Re=(Ae-1)*J,He=we.slice(Re,Re+J);ae(()=>{Ae!==R.state.page&&R.setPage(Ae)},[Ae]),o2();const ut=se.length>0||R.state.types.length>0||R.state.q!=="",St=Z===0;return v("div",{className:"flex flex-col gap-3",children:[v("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[u(KC,{view:O,onViewChange:R.setView,typeOptions:I,selectedTypes:R.state.types,onTypesChange:R.setTypes,addons:i?.addons,selectedAddons:R.state.addons,onAddonsChange:R.setAddons,hideAddons:a!==void 0}),v("div",{className:"flex items-center gap-2",children:[S!==void 0&&(E?v("button",{type:"button",onClick:P,className:"inline-flex items-center gap-1.5 h-7 px-2.5 rounded-md border border-border bg-surface text-[11px] font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",children:[u(bt,{className:"h-3 w-3"}),"Done"]}):v("button",{type:"button",onClick:()=>k(!0),className:"inline-flex items-center gap-1.5 h-7 px-2.5 rounded-md border border-border bg-surface text-[11px] font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",children:[u(km,{className:"h-3 w-3"}),"Select"]})),v("div",{className:"relative",children:[u(Xn,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3 w-3 text-foreground-subtle pointer-events-none"}),u("input",{type:"text",value:Q,onChange:Ue=>ee(Ue.target.value),placeholder:"Search by name or stableId","aria-label":"Search devices by name or stableId",className:"h-7 pl-7 pr-2.5 rounded-md border border-border bg-surface text-[11px] text-foreground placeholder:text-foreground-subtle/60 focus:outline-none focus:ring-1 focus:ring-primary/40 w-56"})]})]})]}),S!==void 0&&E&&u(OC,{selectedIds:N,onClear:M,remove:S.remove,disable:S.disable,enable:S.enable}),St?u(WC,{variant:ut?"filtered":"nofilter",onClearFilters:ut?R.clearFilters:void 0}):O==="cards"?u(Ad,{value:ue.accessoriesByParent,children:u(XC,{rows:He,accessoriesByParent:ue.accessoriesByParent,trpc:r,resolveIntegrationIcon:l??null,resolveParent:o??null,onNavigate:c??null,renderRowAction:p??null,selectable:D,rowClickSelects:$,activeSelected:N,onToggleSelection:C})}):u(Ad,{value:ue.accessoriesByParent,children:u(e2,{rows:He,accessoriesByParent:ue.accessoriesByParent,autoExpandedParents:le,visibleColumns:B,sort:j,onSort:F,devices:ye,trpc:r,resolveIntegrationIcon:l??null,resolveParent:o??null,onNavigate:c??null,renderRowAction:p??null,onDeleteDevice:m??null,selectable:D,rowClickSelects:$,activeSelected:N,onToggleSelection:C})}),!St&&O==="table"&&v("div",{className:"flex items-center justify-between gap-4 flex-wrap pt-2 text-[11px] text-foreground-subtle",children:[v("div",{className:"inline-flex items-center gap-2",children:[Z<=K&&v("span",{children:[Z," ",Z===1?"device":"devices"]}),v("div",{className:"inline-flex items-center gap-1.5",children:[u("span",{"aria-hidden":"true",children:"Per page"}),u("select",{"aria-label":"Devices per page",value:K,onChange:Ue=>{W(Number.parseInt(Ue.target.value,10))},className:"h-7 px-1.5 rounded-md border border-border bg-surface text-[11px] text-foreground focus:outline-none focus:ring-1 focus:ring-primary/40",children:av.map(Ue=>u("option",{value:Ue,children:Ue},Ue))})]})]}),u(Dl,{currentPage:Ae,totalItems:Z,pageSize:J,onPageChange:R.setPage})]}),!St&&O==="cards"&&u(Dl,{currentPage:Ae,totalItems:Z,pageSize:J,onPageChange:R.setPage}),a===void 0&&ut&&Z>0&&v("p",{className:"text-[11px] text-foreground-subtle",children:["Showing ",Z," of ",GC(t).length," devices",se.length>0&&v(Ie,{children:[" ","· filtered by"," ",u("strong",{className:"text-primary",children:se.map(Ue=>i?.addons?.find(Ge=>Ge.id===Ue)?.name??Ue).join(", ")})]})]})]})}function o2(){ts()}function l2(e){const{items:t,getKey:r,getSearchText:n,renderItem:s,getFilterType:i,mapFilterOption:a,filterOptions:l,filterLabel:o="Type",columns:c,renderExpanded:d,isExpanded:h,rowClassName:f,onRowClick:p,isLoading:m=!1,searchPlaceholder:g="Search",emptyLabel:b="No items found.",pageSize:y=100,toolbar:S}=e,[E,k]=_(""),T=iv(E,300),[A,N]=_([]),[C,M]=_(1);ae(()=>{M(1)},[T,A]);const P=oe(()=>{if(!i)return[];if(l)return l;const I=new Set;for(const R of t){const O=i(R);O!==null&&O!==""&&I.add(O)}return[...I].sort().map(R=>{const O=a?.(R);return{id:R,label:O?.label??R,...O?.icon?{icon:O.icon}:{}}})},[t,i,a,l]),D=oe(()=>new Set(A),[A]),$=oe(()=>{const I=T;return t.filter(R=>{if(D.size>0&&i){const O=i(R);if(O===null||!D.has(O))return!1}return!(I.trim()!==""&&!ps(I,n(R)))})},[t,T,n,D,i]),B=$.length,j=Math.max(1,Math.ceil(B/y)),U=Math.min(C,j),F=(U-1)*y,Y=$.slice(F,F+y);return ae(()=>{U!==C&&M(U)},[U,C]),v("div",{className:"flex flex-col gap-3 h-full min-h-0",children:[v("div",{className:"flex items-center justify-between gap-3 flex-wrap shrink-0",children:[i&&P.length>0?u(cv,{label:o,options:P,selected:A,onChange:N}):u("span",{}),v("div",{className:"flex items-center gap-2",children:[v("div",{className:"relative",children:[u(Xn,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3 w-3 text-foreground-subtle pointer-events-none"}),u("input",{type:"text",value:E,onChange:I=>k(I.target.value),placeholder:g,"aria-label":g,className:"h-7 pl-7 pr-2.5 rounded-md border border-border bg-surface text-[11px] text-foreground placeholder:text-foreground-subtle/60 focus:outline-none focus:ring-1 focus:ring-primary/40 w-56"})]}),S]})]}),u("div",{className:"flex-1 min-h-0 overflow-y-auto",children:m&&B===0?u("div",{className:"flex items-center justify-center py-12 text-xs text-foreground-subtle",children:"Loading…"}):B===0?u("div",{className:"flex items-center justify-center py-12 text-xs text-foreground-subtle",children:b}):c?u("div",{className:"rounded-lg border border-border bg-surface overflow-x-auto",children:v("table",{className:"w-full border-collapse",children:[u("thead",{children:u("tr",{className:"border-b border-border",children:c.map(I=>u("th",{className:`text-left px-2 py-2 text-[9.5px] font-medium uppercase tracking-wider text-foreground-subtle ${I.headerClassName??""}`,children:I.header},I.key))})}),u("tbody",{children:Y.map(I=>v(_u,{children:[u("tr",{className:`border-b border-border/60 ${p?"cursor-pointer hover:bg-surface-hover transition-colors":""} ${f?.(I)??""}`,...p?{onClick:()=>p(I),role:"button",tabIndex:0,onKeyDown:R=>{(R.key==="Enter"||R.key===" ")&&(R.preventDefault(),p(I))}}:{},children:c.map(R=>u("td",{className:`px-2 py-2 align-middle ${R.cellClassName??""}`,children:R.cell(I)},R.key))}),d&&h?.(I)&&u("tr",{className:"border-b border-border/60 bg-surface/40",children:u("td",{colSpan:c.length,className:"px-2 pb-2 pt-0",children:d(I)})})]},r(I)))})]})}):u("div",{className:"space-y-1.5",children:Y.map(I=>u(_u,{children:s?.(I)},r(I)))})}),u("div",{className:"shrink-0",children:u(Dl,{currentPage:U,totalItems:B,pageSize:y,onPageChange:M})})]})}function c2(e){return"mode"in e&&e.mode==="generic"?u(l2,{...e}):u(a2,{...e})}function QV({trpc:e,deviceId:t,features:r,layout:n}){const{cap:s,slice:i,available:a}=_e({trpc:e,deviceId:t,cap:h=>h.cover,slice:h=>h.state.cover});if(i===void 0)return null;const l=(r??[]).includes("cover-positionable"),o=!a,c=i.position,d=h=>{o||!h||h({})};return v("div",{className:L("inline-flex items-center gap-1",n==="full"&&"flex-col items-stretch gap-2"),children:[v("div",{className:"inline-flex items-center gap-1",children:[u(vo,{label:"Open",busy:o,onClick:()=>d(s?.open),children:u(dn,{className:"h-3.5 w-3.5"})}),u(vo,{label:"Stop",busy:o,onClick:()=>d(s?.stop),children:u(Cr,{className:"h-3 w-3"})}),u(vo,{label:"Close",busy:o,onClick:()=>d(s?.close),children:u(yt,{className:"h-3.5 w-3.5"})})]}),l&&n==="full"&&v("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[u("span",{children:"Position"}),u("input",{"aria-label":"Position",type:"range",min:0,max:100,step:1,value:c??0,disabled:o,onChange:h=>{o||s?.setPosition({position:Number(h.target.value)})}}),v("span",{className:"tabular-nums w-8 text-right",children:[c??"—","%"]})]})]})}function vo({label:e,busy:t,onClick:r,children:n}){return u("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:s=>{s.stopPropagation(),r()},className:L("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",t&&"opacity-40 cursor-not-allowed"),children:n})}var qV=["cover","lock-control","switch","brightness","fan-control","climate-control","media-player","control"],u2=240,d2=6;function YV({icon:e,title:t,children:r}){const n=ne(null),s=ne(null),[i,a]=_(null),l=i!==null,o=()=>a(null),c=()=>{const d=n.current;if(!d)return;const h=d.getBoundingClientRect(),f=8,p=Math.min(u2,window.innerWidth-f*2),m=Math.max(f,Math.min(h.right-p,window.innerWidth-p-f));a({top:h.bottom+d2,left:m,width:p})};return ae(()=>{if(!l)return;const d=f=>{const p=f.target;s.current?.contains(p)||n.current?.contains(p)||o()},h=f=>{f.key==="Escape"&&o()};return document.addEventListener("mousedown",d),document.addEventListener("touchstart",d),document.addEventListener("keydown",h),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("touchstart",d),document.removeEventListener("keydown",h)}},[l]),v(Ie,{children:[u("button",{ref:n,type:"button",title:t,"aria-label":t,"aria-haspopup":"dialog","aria-expanded":l,onClick:d=>{d.stopPropagation(),l?o():c()},className:L("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors flex-shrink-0",l&&"bg-surface-hover text-foreground"),children:u(e,{className:"h-3 w-3"})}),i&&Ys(u("div",{ref:s,style:{position:"fixed",top:i.top,left:i.left,width:i.width},className:"z-[9999] rounded-lg border border-border bg-surface shadow-lg shadow-black/30 p-2",onClick:d=>d.stopPropagation(),children:r}),document.body)]})}function XV({lastChangedAt:e,className:t}){const r=kp(e);return v("span",{title:r===null?"Unavailable":`Unavailable · last seen ${r}`,className:L("inline-flex items-center gap-1 rounded-full px-2 py-0.5","bg-surface-hover text-foreground-subtle text-[10px] font-medium","border border-border",t),children:[u(_m,{className:"h-3 w-3 flex-shrink-0","aria-hidden":"true"}),u("span",{children:"Unavailable"}),r!==null?u("span",{className:"text-foreground-subtle/70",children:`· last seen ${r}`}):null]})}function ZV({trpc:e,children:t,linkDeviceId:r,primaryChildEntityId:n,onSetPrimary:s}){const i=Js(t,r,n),a=i===null?void 0:t.find(o=>o.id===i.id);if(a===void 0)return u("div",{className:"flex h-full w-full items-center justify-center p-4 text-[11px] italic text-foreground-subtle",children:"No child entities to display."});const l=Jc(a.type)?.HeroCard??yg;return v("div",{className:"flex h-full w-full flex-col items-stretch gap-3 p-3 sm:p-4",children:[t.length>1&&u(h2,{childrenList:t,selectedId:a.id,onSetPrimary:s}),u(l,{trpc:e,deviceId:a.id,features:a.features})]})}function h2({childrenList:e,selectedId:t,onSetPrimary:r}){return v("label",{className:"flex items-center justify-end gap-1.5 self-end text-[11px] text-foreground-subtle",children:[u("span",{children:"primary child:"}),u("select",{value:t,onChange:n=>{const s=Number(n.target.value);if(!Number.isFinite(s)||s===t)return;const i=e.find(a=>a.id===s);i!==void 0&&r(Qc(i))},className:"rounded-md border border-border bg-surface px-1.5 py-0.5 text-[11px] text-foreground",children:e.map(n=>v("option",{value:n.id,children:[n.name," (",n.type,")"]},n.id))})]})}function JV({options:e,value:t,onChange:r}){return u("div",{className:"flex flex-wrap gap-2",children:e.map(n=>{const s=n.id===t;return v("button",{onClick:()=>n.available&&r(n.id),disabled:!n.available,className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-xs font-medium transition-all ${s?"border-primary/40 bg-primary/10 text-primary":n.available?"border-border bg-surface text-foreground-subtle hover:bg-surface-hover hover:text-foreground":"border-border/40 bg-surface/40 text-foreground-subtle/40 cursor-not-allowed"}`,children:[u(DS,{className:"h-3.5 w-3.5 shrink-0"}),n.label,n.isBest&&v("span",{className:"inline-flex items-center gap-0.5 rounded-full bg-amber-500/15 px-1.5 py-0.5 text-[10px] font-semibold text-amber-400",children:[u(wE,{className:"h-2.5 w-2.5"}),"Best"]}),n.platformScore!=null&&v("span",{className:"text-[10px] text-foreground-subtle/60",children:["(",n.platformScore,")"]}),u("span",{className:`h-1.5 w-1.5 rounded-full ${n.available?"bg-success":"bg-danger"}`})]},n.id)})})}function f2(e,t){const r=new Set(t.slots.flatMap(a=>a.addons.map(l=>l.id))),n=[];function s(a){if(!r.has(a.addonId))return n.push(`Addon "${a.addonId}" is no longer available — step removed`),null;const l=t.slots.flatMap(d=>d.addons).find(d=>d.id===a.addonId);let o=a.modelId;if(l&&!l.models.some(d=>d.id===o)){const d=l.defaultModelId;n.push(`Model "${o}" not available for ${a.addonId} — using "${d}"`),o=d}const c=a.children.map(d=>s(d)).filter(d=>d!==null);return{...a,modelId:o,children:c}}const i=e.map(a=>s(a)).filter(a=>a!==null);return{valid:n.length===0,steps:i,warnings:n}}function p2(e){const t=new Map;for(const r of e.slots)for(const n of r.addons)t.set(n.id,n);return t}function bo(e){return{addonId:e.id,addonName:e.name,slot:e.slot,inputClasses:[...e.inputClasses],outputClasses:[...e.outputClasses],enabled:!0,modelId:e.defaultModelId,children:[]}}function yo({addon:e,onClick:t}){return u("button",{type:"button",onClick:t,className:"w-full rounded-lg border border-dashed border-border/60 px-3 py-2.5 text-left transition-all hover:border-primary/30 hover:bg-surface/60 group",children:v("div",{className:"flex items-center gap-3",children:[u(CS,{className:"h-[18px] w-[18px] text-foreground-subtle/30 group-hover:text-primary/60 shrink-0"}),v("div",{className:"flex-1 min-w-0",children:[u("span",{className:"text-[13px] font-medium text-foreground-subtle/50 group-hover:text-foreground-subtle block truncate",children:e.name}),v("div",{className:"flex items-center gap-1 mt-0.5 flex-wrap",children:[e.inputClasses.map(r=>u("span",{className:"text-[9px] uppercase font-semibold tracking-wide px-1.5 py-0.5 rounded bg-blue-500/8 text-blue-400/50",children:r},r)),e.inputClasses.length>0&&e.outputClasses.length>0&&u("span",{className:"text-foreground-subtle/25 text-[10px]",children:"→"}),e.outputClasses.map(r=>u("span",{className:"text-[9px] uppercase font-semibold tracking-wide px-1.5 py-0.5 rounded bg-green-500/8 text-green-400/50",children:r},r))]})]})]})})}function ej({schema:e,steps:t,onChange:r,templates:n,selectedTemplateId:s,onSelectTemplate:i,onSaveTemplate:a,onUpdateTemplate:l,onDeleteTemplate:o,readOnly:c=!1,excludeAddons:d=[],hideTemplates:h=!1,showOnlyEnabled:f=!1,showSlotLabels:p=!1,toggleMode:m="simple",overrides:g={},onOverrideChange:b,inheritedEnabledByAddon:y={},hideModelAndSettings:S=!1}){const E=K=>({toggleMode:m,hideModelAndSettings:S,...m==="threeState"?{overrideState:g[K]!==void 0?g[K]:null,onOverrideChange:b?W=>b(K,W):void 0,inheritedEnabled:y[K]}:{}}),k=oe(()=>new Set(d),[d]),T=oe(()=>p2(e),[e]),[A,N]=_([]),C=s?JSON.stringify(t)!==JSON.stringify(n.find(K=>K.id===s)?.steps):!1;function M(K){const W=K.target.value||null;if(W){const J=n.find(Q=>Q.id===W);J&&N([...f2(J.steps,e).warnings])}else N([]);i(W)}function P(){s&&l(s,t)}function D(){const K=window.prompt("Template name:");K?.trim()&&a(K.trim(),t)}function $(){if(!s)return;const K=n.find(W=>W.id===s);K&&window.confirm(`Delete template "${K.name}"?`)&&o(s)}function B(K){r(t.map(W=>W.addonId!==K.addonId?W:j(K)))}function j(K){const W=K.children.some(J=>J.enabled||J.children.some(Q=>Q.enabled));return{...K,enabled:K.enabled||W,children:K.children.map(J=>{const Q=J.children.some(ee=>ee.enabled);return{...J,enabled:J.enabled||Q}})}}function U(K,W){const J=bo(W);r(t.map(Q=>Q.addonId!==K?Q:{...Q,children:[...Q.children,J]}))}function F(K){const W=new Set;for(const J of K){W.add(J.addonId);for(const ee of J.children)W.add(ee.addonId);const Q=F(J.children);for(const ee of Q)W.add(ee)}return W}const Y=F(t);function I(K){const W=T.get(K.addonId);if(!W)return[];const J=e.slots.find(se=>se.id===W.slot)?.parentSlot==null,Q=W.childSlots,ee=new Set(K.children.map(se=>se.addonId)),ie=[];for(const se of e.slots)if(Q.includes(se.id))for(const be of se.addons){if(ee.has(be.id)||k.has(be.id))continue;const ye=be.inputClasses.length===0;ye&&!J||(ye||be.inputClasses.some(ue=>K.outputClasses.includes(ue)))&&ie.push(be)}return ie}function R(K){const W=f?{...K,children:K.children.filter(Q=>Q.enabled).map(Q=>({...Q,children:Q.children.filter(ee=>ee.enabled)}))}:K,J=f?[]:I(W);return v("div",{className:"space-y-1.5",children:[u(Xa,{step:W,schema:T.get(W.addonId)??null,allSchemas:T,onChange:B,onDelete:c?void 0:Q=>r(t.filter(ee=>ee.addonId!==Q)),readOnly:c,...E(W.addonId)}),(W.children.length>0||J.length>0)&&v("div",{className:"ml-4 pl-3 border-l border-border/60 space-y-1.5",children:[p&&u("span",{className:"text-[10px] font-semibold uppercase tracking-widest text-foreground-subtle/40",children:"Slot: Cropper / Classifier"}),W.children.map(Q=>{const ee=I(Q);return v("div",{className:"space-y-1.5",children:[u(Xa,{step:Q,schema:T.get(Q.addonId)??null,allSchemas:T,depth:1,onChange:ie=>{B({...W,children:W.children.map(se=>se.addonId===ie.addonId?ie:se)})},onDelete:c?void 0:ie=>{B({...W,children:W.children.filter(se=>se.addonId!==ie)})},readOnly:c,...E(Q.addonId)}),(Q.children.length>0||ee.length>0)&&v("div",{className:"ml-4 pl-3 border-l border-border/40 space-y-1.5",children:[p&&u("span",{className:"text-[10px] font-semibold uppercase tracking-widest text-foreground-subtle/30",children:"Slot: Recognizer"}),Q.children.map(ie=>u(Xa,{step:ie,schema:T.get(ie.addonId)??null,allSchemas:T,depth:2,onChange:se=>{B({...W,children:W.children.map(be=>be.addonId===Q.addonId?{...be,children:be.children.map(ye=>ye.addonId===se.addonId?se:ye)}:be)})},onDelete:c?void 0:se=>{B({...W,children:W.children.map(be=>be.addonId===Q.addonId?{...be,children:be.children.filter(ye=>ye.addonId!==se)}:be)})},readOnly:c,...E(ie.addonId)},ie.addonId)),!c&&ee.map(ie=>u(yo,{addon:ie,onClick:()=>{const se=bo(ie);B({...W,children:W.children.map(be=>be.addonId===Q.addonId?{...be,children:[...be.children,se]}:be)})}},ie.id))]})]},Q.addonId)}),!c&&J.map(Q=>u(yo,{addon:Q,onClick:()=>U(W.addonId,Q)},Q.id))]})]},W.addonId)}const O=e.slots.filter(K=>K.parentSlot===null).sort((K,W)=>K.priority-W.priority);return v("div",{className:"space-y-4",children:[!h&&u("div",{className:"rounded-lg border border-border bg-surface p-3",children:v("div",{className:"flex items-center gap-2",children:[u("div",{className:"relative flex-1 min-w-0",children:v("select",{value:s??"",onChange:M,className:"w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground focus:outline-none focus:border-primary/50",children:[u("option",{value:"",children:"No template"}),n.map(K=>u("option",{value:K.id,children:K.name},K.id))]})}),C&&u("span",{className:"h-1.5 w-1.5 rounded-full bg-amber-500 shrink-0"}),u("button",{onClick:P,disabled:!s||c,title:"Save",className:L("p-2 rounded-lg border border-border transition-colors",s&&!c?"text-foreground-subtle hover:bg-surface-hover":"text-foreground-subtle/30 cursor-not-allowed"),children:u(Im,{className:"h-4 w-4"})}),u("button",{onClick:D,disabled:c,title:"Save As",className:L("p-2 rounded-lg border border-border transition-colors",c?"text-foreground-subtle/30 cursor-not-allowed":"text-foreground-subtle hover:bg-surface-hover"),children:u(PS,{className:"h-4 w-4"})}),u("button",{onClick:$,disabled:!s||c,title:"Delete",className:L("p-2 rounded-lg border border-border transition-colors",s&&!c?"text-foreground-subtle hover:text-danger":"text-foreground-subtle/30 cursor-not-allowed"),children:u(zt,{className:"h-4 w-4"})})]})}),A.length>0&&v("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/5 p-3 text-xs text-amber-400 space-y-1",children:[v("div",{className:"flex items-center justify-between",children:[u("span",{className:"font-medium",children:"Template loaded with warnings:"}),u("button",{onClick:()=>N([]),className:"text-amber-400/60 hover:text-amber-400",children:u(bt,{className:"h-3.5 w-3.5"})})]}),A.map((K,W)=>v("div",{children:["• ",K]},W))]}),O.map(K=>{const W=t.filter(se=>se.slot===K.id&&!k.has(se.addonId)),J=f?W.filter(se=>se.enabled):W,Q=f?[]:K.addons.filter(se=>!Y.has(se.id)&&!k.has(se.id)),ee=new Map,ie=[];for(const se of J)se.group?(ee.has(se.group)||ee.set(se.group,[]),ee.get(se.group).push(se)):ie.push(se);return v("div",{className:"space-y-2",children:[p&&v("span",{className:"text-[10px] font-semibold uppercase tracking-widest text-foreground-subtle/50",children:["Slot: ",K.label]}),ie.map(se=>R(se)),[...ee.entries()].map(([se,be])=>v("div",{className:"space-y-2 rounded-lg border border-border/40 p-2",children:[u("span",{className:"text-[10px] font-semibold uppercase tracking-widest text-foreground-subtle/50 px-1",children:se}),be.map(ye=>R(ye))]},se)),!c&&Q.map(se=>u(yo,{addon:se,onClick:()=>{r([...t,bo(se)])}},se.id))]},K.id)})]})}var ai={person:"#3b82f6",vehicle:"#f59e0b",animal:"#22c55e",face:"#a855f7",plate:"#ec4899",bird:"#14b8a6",dog:"#84cc16",cat:"#f97316",car:"#f59e0b",truck:"#d97706",bus:"#b45309",motorcycle:"#eab308",bicycle:"#ca8a04",motion:"#facc15"},Yd=["#ef4444","#8b5cf6","#06b6d4","#f97316","#10b981","#6366f1","#e11d48","#0891b2","#7c3aed","#059669"],tj="#f59e42";function Kt(e,t){if(t?.[e])return t[e];if(t?.[e.toLowerCase()])return t[e.toLowerCase()];if(ai[e])return ai[e];if(ai[e.toLowerCase()])return ai[e.toLowerCase()];let r=0;for(let n=0;n<e.length;n++)r=r*31+(e.codePointAt(n)??0)>>>0;return Yd[r%Yd.length]??"#f59e42"}function rj({src:e,imageWidth:t,imageHeight:r,detections:n=[],classColors:s,aspectRatio:i,className:a,placeholder:l,showConfidence:o=!0,minConfidence:c=0,borderWidth:d=2}){function h(y){return Kt(y,s)}const f=i??(t&&r?`${t}/${r}`:"16/9"),p=n.filter(y=>y.score>=c),m=p.filter(y=>y.kind==="first-level"),g=p.filter(y=>y.kind==="detail"),b=v2(g,y=>y.parentId??"");return u("div",{className:L("rounded-lg border border-border bg-surface overflow-hidden relative",a),style:{aspectRatio:f},children:e?v(Ie,{children:[u("img",{src:e,className:"absolute inset-0 w-full h-full object-fill",alt:""}),p.map((y,S)=>y.debug?.mask&&y.debug.maskWidth&&y.debug.maskHeight?u(m2,{mask:y.debug.mask,maskWidth:y.debug.maskWidth,maskHeight:y.debug.maskHeight,bbox:y.bbox,imageWidth:t,imageHeight:r,color:h(y.macroClass)},`mask-${S}`):null),m.map(y=>{const S=b.get(y.id)??[];return u(Xd,{detection:y,imageWidth:t,imageHeight:r,color:h(y.macroClass),showConfidence:o,borderWidth:y.debug?.mask?1:d,children:S.map(E=>u(g2,{child:E,parentBbox:y.bbox,color:h(E.macroClass),showConfidence:o},`child-${E.id}`))},`det-${y.id}`)}),g.filter(y=>!y.parentId||!m.some(S=>S.id===y.parentId)).map(y=>u(Xd,{detection:y,imageWidth:t,imageHeight:r,color:h(y.macroClass),showConfidence:o,borderWidth:d},`orphan-${y.id}`))]}):u("div",{className:"w-full h-full flex items-center justify-center text-foreground-subtle text-sm",children:l??"No image loaded"})})}function Xd({detection:e,imageWidth:t,imageHeight:r,color:n,showConfidence:s,borderWidth:i,children:a}){const{x:l,y:o,width:c,height:d}=e.bbox,h=v("div",{className:"absolute left-0 flex flex-col items-start gap-px",style:{bottom:"100%",marginBottom:"2px"},children:[v("span",{className:"text-[10px] px-1 rounded-sm whitespace-nowrap text-white",style:{backgroundColor:n},children:[e.macroClass,s&&` ${(e.score*100).toFixed(0)}%`]}),e.labels.map((f,p)=>v("span",{className:"text-[9px] font-semibold px-1 rounded-sm whitespace-nowrap text-white",style:{backgroundColor:Kt(f.label)},children:[f.label," ",(f.score*100).toFixed(0),"%"]},`${e.id}-lbl-${p}`))]});return v("div",{className:"absolute rounded-sm",style:{left:`${l/t*100}%`,top:`${o/r*100}%`,width:`${c/t*100}%`,height:`${d/r*100}%`,borderWidth:`${i}px`,borderStyle:"solid",borderColor:n},children:[h,a]})}function m2({mask:e,maskWidth:t,maskHeight:r,bbox:n,imageWidth:s,imageHeight:i,color:a}){const l=ne(null);return ae(()=>{const o=l.current;if(!o)return;const c=o.getContext("2d");if(!c)return;const d=atob(e),h=new Uint8Array(d.length);for(let y=0;y<d.length;y++)h[y]=d.charCodeAt(y);const f=parseInt(a.slice(1,3),16),p=parseInt(a.slice(3,5),16),m=parseInt(a.slice(5,7),16);o.width=t,o.height=r;const g=c.createImageData(t,r),b=t*r;for(let y=0;y<b;y++){const S=y<h.length?h[y]:0,E=y*4;S>0&&(g.data[E]=f,g.data[E+1]=p,g.data[E+2]=m,g.data[E+3]=120)}c.putImageData(g,0,0)},[e,t,r,a]),u("canvas",{ref:l,className:"absolute pointer-events-none",style:{left:`${n.x/s*100}%`,top:`${n.y/i*100}%`,width:`${n.width/s*100}%`,height:`${n.height/i*100}%`,imageRendering:"pixelated"}})}function g2({child:e,parentBbox:t,color:r,showConfidence:n}){if(t.width<=0||t.height<=0)return null;const s=(e.bbox.x-t.x)/t.width*100,i=(e.bbox.y-t.y)/t.height*100,a=e.bbox.width/t.width*100,l=e.bbox.height/t.height*100;return u("div",{className:"absolute rounded-sm",style:{left:`${Math.max(0,s)}%`,top:`${Math.max(0,i)}%`,width:`${Math.min(100,a)}%`,height:`${Math.min(100,l)}%`,borderWidth:"1px",borderStyle:"solid",borderColor:r},children:v("div",{className:"absolute left-0 flex flex-col items-start gap-px",style:{bottom:"100%",marginBottom:"1px"},children:[v("span",{className:"text-[9px] px-0.5 rounded-sm whitespace-nowrap text-white",style:{backgroundColor:r},children:[e.macroClass,n&&` ${(e.score*100).toFixed(0)}%`]}),e.labels.map((o,c)=>v("span",{className:"text-[8px] font-semibold px-0.5 rounded-sm whitespace-nowrap text-white",style:{backgroundColor:Kt(o.label)},children:[o.label," ",(o.score*100).toFixed(0),"%"]},`${e.id}-lbl-${c}`))]})})}function v2(e,t){const r=new Map;for(const n of e){const s=t(n),i=r.get(s)??[];i.push(n),r.set(s,i)}return r}function nj({detections:e,classColors:t,className:r,hiddenKeys:n,onToggleVisibility:s}){const i=t;if(e.length===0)return u("div",{className:"text-sm text-foreground-subtle italic text-center py-4",children:"No detections"});const a=e.filter(d=>d.kind==="first-level"),l=e.filter(d=>d.kind==="detail"),o=new Map;for(const d of l){if(!d.parentId)continue;const h=o.get(d.parentId)??[];h.push(d),o.set(d.parentId,h)}const c=l.filter(d=>!d.parentId||!a.some(h=>h.id===d.parentId));return v("div",{className:r,children:[v("div",{className:"text-xs font-medium text-foreground-subtle uppercase tracking-wide mb-2",children:["Detections (",e.length,")"]}),v("div",{className:"space-y-2",children:[a.map(d=>u(Zd,{detection:d,children_:o.get(d.id)??[],colors:i,hiddenKeys:n,onToggleVisibility:s},d.id)),c.map(d=>u(Zd,{detection:d,children_:[],colors:i,hiddenKeys:n,onToggleVisibility:s},d.id))]})]})}function Zd({detection:e,children_:t,colors:r,hiddenKeys:n,onToggleVisibility:s}){const i=Kt(e.macroClass,r),a=!n?.has(e.id),l=e.debug?.mask,o=e.debug?.maskWidth,c=e.debug?.maskHeight,d=e.debug?.alternateLabels;return v("div",{className:`rounded-md border border-border bg-surface p-3 space-y-1 ${a?"":"opacity-40"}`,children:[v("div",{className:"flex justify-between items-center",children:[v("div",{className:"flex items-center gap-2",children:[s&&u("input",{type:"checkbox",checked:a,onChange:()=>s(e.id,!a),className:"h-3.5 w-3.5 rounded border-border accent-primary cursor-pointer shrink-0"}),u("span",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:i}}),u("span",{className:"text-sm font-medium text-foreground",children:e.macroClass}),e.kind==="detail"&&u("span",{className:"text-[9px] font-mono px-1 py-0.5 rounded bg-primary/10 text-primary",children:"detail"}),l&&o&&c&&v("span",{className:"text-[9px] font-mono px-1 py-0.5 rounded bg-primary/10 text-primary",children:["mask ",o,"x",c]})]}),u(x2,{confidence:e.score})]}),v("div",{className:"text-[10px] text-foreground-subtle font-mono",children:["bbox: [",Math.round(e.bbox.x),", ",Math.round(e.bbox.y),","," ",Math.round(e.bbox.x+e.bbox.width),","," ",Math.round(e.bbox.y+e.bbox.height),"]"]}),e.labels.length>0&&u("div",{className:"flex flex-wrap gap-1 mt-1",children:e.labels.map((h,f)=>v("span",{className:"inline-flex items-center gap-1 text-[10px] font-medium px-1.5 py-0.5 rounded-full",style:{backgroundColor:Kt(h.label,r)+"20",color:Kt(h.label,r)},children:[h.label,v("span",{className:"opacity-60",children:[(h.score*100).toFixed(0),"%"]}),h.detectionId&&v("span",{className:"opacity-40 text-[8px]",children:["→ ",h.detectionId]})]},f))}),d&&Object.keys(d).length>0&&u(y2,{alternateLabels:d,colors:r}),t.length>0&&u(b2,{items:t,colors:r,hiddenKeys:n,onToggleVisibility:s})]})}function b2({items:e,colors:t,hiddenKeys:r,onToggleVisibility:n}){return u("div",{className:"ml-4 mt-1.5 space-y-1.5 border-l-2 border-border pl-3",children:e.map(s=>{const i=Kt(s.macroClass,t),a=!r?.has(s.id),l=s.debug?.mask,o=s.debug?.maskWidth,c=s.debug?.maskHeight;return v("div",{className:`text-xs space-y-0.5 ${a?"":"opacity-40"}`,children:[v("div",{className:"flex items-center gap-1.5",children:[n&&u("input",{type:"checkbox",checked:a,onChange:()=>n(s.id,!a),className:"h-3 w-3 rounded border-border accent-primary cursor-pointer shrink-0"}),u("span",{className:"h-1.5 w-1.5 rounded-full shrink-0",style:{backgroundColor:i}}),u("span",{className:"font-medium",style:{color:i},children:s.macroClass}),v("span",{className:"text-foreground-subtle",children:[(s.score*100).toFixed(0),"%"]}),l&&o&&c&&v("span",{className:"text-[9px] font-mono px-1 py-0.5 rounded bg-primary/10 text-primary",children:["mask ",o,"x",c]})]}),s.labels.length>0&&u("div",{className:"flex flex-wrap gap-1 ml-5 mt-0.5",children:s.labels.map((d,h)=>v("span",{className:"inline-flex items-center gap-0.5 text-[9px] font-medium px-1 py-0.5 rounded-full",style:{backgroundColor:Kt(d.label,t)+"20",color:Kt(d.label,t)},children:[d.label," ",v("span",{className:"opacity-60",children:[(d.score*100).toFixed(0),"%"]})]},h))})]},s.id)})})}function y2({alternateLabels:e,colors:t}){const[r,n]=_(!1),s=Object.keys(e);return v("div",{className:"mt-1",children:[v("button",{onClick:()=>n(i=>!i),className:"text-[9px] text-foreground-subtle hover:text-foreground transition-colors flex items-center gap-1",children:[u("span",{className:`transition-transform ${r?"rotate-90":""}`,children:"▶"}),"Alternates (",s.length," source",s.length!==1?"s":"",")"]}),r&&u("div",{className:"mt-1 ml-3 space-y-1.5",children:s.map(i=>{const a=e[i];return!a||a.length===0?null:v("div",{children:[u("div",{className:"text-[9px] font-medium text-foreground-subtle mb-0.5",children:i}),u("div",{className:"flex flex-wrap gap-1",children:a.map((l,o)=>v("span",{className:"inline-flex items-center gap-0.5 text-[9px] px-1 py-0.5 rounded-full",style:{backgroundColor:Kt(i,t)+"10",color:Kt(i,t),opacity:Math.max(.4,l.score)},children:[l.label,v("span",{className:"opacity-60",children:[(l.score*100).toFixed(1),"%"]})]},o))})]},i)})})]})}function x2({confidence:e}){return v("span",{className:`text-xs font-medium px-2 py-0.5 rounded-full ${e>=.8?"bg-success/10 text-success":e>=.5?"bg-warning/10 text-warning":"bg-danger/10 text-danger"}`,children:[(e*100).toFixed(1),"%"]})}function sj({timings:e,totalMs:t,className:r}){const n=Object.entries(e);return n.length===0&&t===void 0?null:v("div",{className:`rounded-lg border border-border bg-surface p-3 space-y-2 ${r??""}`,children:[u("div",{className:"text-xs font-medium text-foreground-subtle uppercase tracking-wide",children:"Timings"}),v("div",{className:"space-y-1 text-xs",children:[n.map(([s,i])=>v("div",{className:"flex justify-between",children:[u("span",{className:"text-foreground-subtle",children:s}),v("span",{className:"font-mono text-foreground",children:[i.toFixed(1),"ms"]})]},s)),t!==void 0&&v("div",{className:"flex justify-between pt-1 border-t border-border font-medium text-foreground",children:[u("span",{children:"Total"}),v("span",{className:"font-mono",children:[t.toFixed(1),"ms"]})]})]})]})}function ij({images:e,selectedFilename:t,uploadedName:r,onSelect:n,onUpload:s,className:i,accept:a="image/*",uploadLabel:l="Upload..."}){const o=()=>{const c=document.createElement("input");c.type="file",c.accept=a,c.onchange=()=>{const d=c.files?.[0];if(!d)return;const h=new FileReader;h.onload=()=>{const f=h.result,p=f.split(",")[1];p&&s(p,d.name,f)},h.readAsDataURL(d)},c.click()};return v("div",{className:`flex flex-wrap items-center gap-2 ${i??""}`,children:[e.map(c=>u("button",{onClick:()=>n(c.filename),className:`px-3 py-1.5 text-xs rounded-md border transition-colors ${t===c.filename?"bg-primary text-primary-foreground border-primary":"bg-surface border-border text-foreground hover:border-primary/50"}`,children:c.id??c.filename.replace(/\.[^.]+$/,"")},c.filename)),u("button",{onClick:o,className:"px-3 py-1.5 text-xs rounded-md border border-border bg-surface text-foreground hover:bg-surface-hover transition-colors",children:l}),r&&u("span",{className:"text-xs text-foreground-subtle",children:r})]})}var oi="w-full px-3 py-2 text-sm rounded-md border border-border bg-surface text-foreground focus:outline-none focus:ring-2 focus:ring-primary/50";function aj({runtime:e,backend:t,modelId:r,agentId:n="hub",runtimes:s,backends:i,models:a,agents:l=[],onRuntimeChange:o,onBackendChange:c,onModelChange:d,onAgentChange:h,layout:f="grid",className:p,showAgent:m=!1}){return v("div",{className:`${f==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4":f==="horizontal"?"flex flex-wrap items-end gap-4":"space-y-3"} ${p??""}`,children:[m&&l.length>0&&v("label",{className:"space-y-1",children:[u("span",{className:"text-xs font-medium text-foreground-subtle",children:"Agent"}),u("select",{value:n,onChange:g=>h?.(g.target.value),className:oi,children:l.map(g=>v("option",{value:g.id,children:[g.name," (",g.status,")"]},g.id))})]}),v("label",{className:"space-y-1",children:[u("span",{className:"text-xs font-medium text-foreground-subtle",children:"Runtime"}),u("select",{value:e,onChange:g=>o(g.target.value),className:oi,children:s.map(g=>v("option",{value:g.value,disabled:!g.available,children:[g.label,g.available?"":" (unavailable)"]},g.value))})]}),v("label",{className:"space-y-1",children:[u("span",{className:"text-xs font-medium text-foreground-subtle",children:"Backend"}),u("select",{value:t,onChange:g=>c(g.target.value),className:oi,children:i.map(g=>v("option",{value:g.id,disabled:!g.available,children:[g.label,g.available?"":" (unavailable)"]},g.id))})]}),v("label",{className:"space-y-1",children:[u("span",{className:"text-xs font-medium text-foreground-subtle",children:"Model"}),u("select",{value:r,onChange:g=>d(g.target.value),className:oi,children:a.length===0?u("option",{value:"",children:"No compatible models"}):a.map(g=>v("option",{value:g.id,children:[g.name,g.downloaded?" ✓":""]},g.id))})]})]})}var S2=class{constructor(){this.keyToValue=new Map,this.valueToKey=new Map}set(e,t){this.keyToValue.set(e,t),this.valueToKey.set(t,e)}getByKey(e){return this.keyToValue.get(e)}getByValue(e){return this.valueToKey.get(e)}clear(){this.keyToValue.clear(),this.valueToKey.clear()}},dv=class{constructor(e){this.generateIdentifier=e,this.kv=new S2}register(e,t){this.kv.getByValue(e)||(t||(t=this.generateIdentifier(e)),this.kv.set(t,e))}clear(){this.kv.clear()}getIdentifier(e){return this.kv.getByValue(e)}getValue(e){return this.kv.getByKey(e)}},E2=class extends dv{constructor(){super(e=>e.name),this.classToAllowedProps=new Map}register(e,t){typeof t=="object"?(t.allowProps&&this.classToAllowedProps.set(e,t.allowProps),super.register(e,t.identifier)):super.register(e,t)}getAllowedProps(e){return this.classToAllowedProps.get(e)}};function w2(e){if("values"in Object)return Object.values(e);const t=[];for(const r in e)e.hasOwnProperty(r)&&t.push(e[r]);return t}function k2(e,t){const r=w2(e);if("find"in r)return r.find(t);const n=r;for(let s=0;s<n.length;s++){const i=n[s];if(t(i))return i}}function Zn(e,t){Object.entries(e).forEach(([r,n])=>t(n,r))}function Gi(e,t){return e.indexOf(t)!==-1}function Jd(e,t){for(let r=0;r<e.length;r++){const n=e[r];if(t(n))return n}}var T2=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return k2(this.transfomers,t=>t.isApplicable(e))}findByName(e){return this.transfomers[e]}},A2=e=>Object.prototype.toString.call(e).slice(8,-1),hv=e=>typeof e>"u",C2=e=>e===null,Us=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,_l=e=>Us(e)&&Object.keys(e).length===0,Gr=e=>Array.isArray(e),N2=e=>typeof e=="string",L2=e=>typeof e=="number"&&!isNaN(e),I2=e=>typeof e=="boolean",R2=e=>e instanceof RegExp,Gs=e=>e instanceof Map,Hs=e=>e instanceof Set,fv=e=>A2(e)==="Symbol",M2=e=>e instanceof Date&&!isNaN(e.valueOf()),pv=e=>e instanceof Error,eh=e=>typeof e=="number"&&isNaN(e),P2=e=>I2(e)||C2(e)||hv(e)||L2(e)||N2(e)||fv(e),D2=e=>typeof e=="bigint",_2=e=>e===1/0||e===-1/0,O2=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),F2=e=>e instanceof URL,Ol=e=>e.replace(/\\/g,"\\\\").replace(/\./g,"\\."),xo=e=>e.map(String).map(Ol).join("."),ws=(e,t)=>{const r=[];let n="";for(let i=0;i<e.length;i++){let a=e.charAt(i);if(!t&&a==="\\"){const l=e.charAt(i+1);if(l==="\\"){n+="\\",i++;continue}else if(l!==".")throw Error("invalid path")}if(a==="\\"&&e.charAt(i+1)==="."){n+=".",i++;continue}if(a==="."){r.push(n),n="";continue}n+=a}const s=n;return r.push(s),r};function sr(e,t,r,n){return{isApplicable:e,annotation:t,transform:r,untransform:n}}var mv=[sr(hv,"undefined",()=>null,()=>{}),sr(D2,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):(console.error("Please add a BigInt polyfill."),e)),sr(M2,"Date",e=>e.toISOString(),e=>new Date(e)),sr(pv,"Error",(e,t)=>{const r={name:e.name,message:e.message};return"cause"in e&&(r.cause=e.cause),t.allowedErrorProps.forEach(n=>{r[n]=e[n]}),r},(e,t)=>{const r=new Error(e.message,{cause:e.cause});return r.name=e.name,r.stack=e.stack,t.allowedErrorProps.forEach(n=>{r[n]=e[n]}),r}),sr(R2,"regexp",e=>""+e,e=>{const t=e.slice(1,e.lastIndexOf("/")),r=e.slice(e.lastIndexOf("/")+1);return new RegExp(t,r)}),sr(Hs,"set",e=>[...e.values()],e=>new Set(e)),sr(Gs,"map",e=>[...e.entries()],e=>new Map(e)),sr(e=>eh(e)||_2(e),"number",e=>eh(e)?"NaN":e>0?"Infinity":"-Infinity",Number),sr(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),sr(F2,"URL",e=>e.toString(),e=>new URL(e))];function Da(e,t,r,n){return{isApplicable:e,annotation:t,transform:r,untransform:n}}var gv=Da((e,t)=>fv(e)?!!t.symbolRegistry.getIdentifier(e):!1,(e,t)=>["symbol",t.symbolRegistry.getIdentifier(e)],e=>e.description,(e,t,r)=>{const n=r.symbolRegistry.getValue(t[1]);if(!n)throw new Error("Trying to deserialize unknown symbol");return n}),$2=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,t)=>(e[t.name]=t,e),{}),vv=Da(O2,e=>["typed-array",e.constructor.name],e=>[...e],(e,t)=>{const r=$2[t[1]];if(!r)throw new Error("Trying to deserialize unknown typed array");return new r(e)});function bv(e,t){return e?.constructor?!!t.classRegistry.getIdentifier(e.constructor):!1}var yv=Da(bv,(e,t)=>["class",t.classRegistry.getIdentifier(e.constructor)],(e,t)=>{const r=t.classRegistry.getAllowedProps(e.constructor);if(!r)return{...e};const n={};return r.forEach(s=>{n[s]=e[s]}),n},(e,t,r)=>{const n=r.classRegistry.getValue(t[1]);if(!n)throw new Error(`Trying to deserialize unknown class '${t[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);return Object.assign(Object.create(n.prototype),e)}),xv=Da((e,t)=>!!t.customTransformerRegistry.findApplicable(e),(e,t)=>["custom",t.customTransformerRegistry.findApplicable(e).name],(e,t)=>t.customTransformerRegistry.findApplicable(e).serialize(e),(e,t,r)=>{const n=r.customTransformerRegistry.findByName(t[1]);if(!n)throw new Error("Trying to deserialize unknown custom value");return n.deserialize(e)}),B2=[yv,gv,xv,vv],th=(e,t)=>{const r=Jd(B2,s=>s.isApplicable(e,t));if(r)return{value:r.transform(e,t),type:r.annotation(e,t)};const n=Jd(mv,s=>s.isApplicable(e,t));if(n)return{value:n.transform(e,t),type:n.annotation}},Sv={};mv.forEach(e=>{Sv[e.annotation]=e});var U2=(e,t,r)=>{if(Gr(t))switch(t[0]){case"symbol":return gv.untransform(e,t,r);case"class":return yv.untransform(e,t,r);case"custom":return xv.untransform(e,t,r);case"typed-array":return vv.untransform(e,t,r);default:throw new Error("Unknown transformation: "+t)}else{const n=Sv[t];if(!n)throw new Error("Unknown transformation: "+t);return n.untransform(e,r)}},_n=(e,t)=>{if(t>e.size)throw new Error("index out of bounds");const r=e.keys();for(;t>0;)r.next(),t--;return r.next().value};function Ev(e){if(Gi(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(Gi(e,"prototype"))throw new Error("prototype is not allowed as a property");if(Gi(e,"constructor"))throw new Error("constructor is not allowed as a property")}var G2=(e,t)=>{Ev(t);for(let r=0;r<t.length;r++){const n=t[r];if(Hs(e))e=_n(e,+n);else if(Gs(e)){const s=+n,i=+t[++r]==0?"key":"value",a=_n(e,s);switch(i){case"key":e=a;break;case"value":e=e.get(a);break}}else e=e[n]}return e},Fl=(e,t,r)=>{if(Ev(t),t.length===0)return r(e);let n=e;for(let i=0;i<t.length-1;i++){const a=t[i];if(Gr(n)){const l=+a;n=n[l]}else if(Us(n))n=n[a];else if(Hs(n)){const l=+a;n=_n(n,l)}else if(Gs(n)){if(i===t.length-2)break;const l=+a,o=+t[++i]==0?"key":"value",c=_n(n,l);switch(o){case"key":n=c;break;case"value":n=n.get(c);break}}}const s=t[t.length-1];if(Gr(n)?n[+s]=r(n[+s]):Us(n)&&(n[s]=r(n[s])),Hs(n)){const i=_n(n,+s),a=r(i);i!==a&&(n.delete(i),n.add(a))}if(Gs(n)){const i=+t[t.length-2],a=_n(n,i);switch(+s==0?"key":"value"){case"key":{const l=r(a);n.set(l,n.get(a)),l!==a&&n.delete(a);break}case"value":n.set(a,r(n.get(a)));break}}return e},wv=e=>e<1;function $l(e,t,r,n=[]){if(!e)return;const s=wv(r);if(!Gr(e)){Zn(e,(l,o)=>$l(l,t,r,[...n,...ws(o,s)]));return}const[i,a]=e;a&&Zn(a,(l,o)=>{$l(l,t,r,[...n,...ws(o,s)])}),t(i,n)}function H2(e,t,r,n){return $l(t,(s,i)=>{e=Fl(e,i,a=>U2(a,s,n))},r),e}function V2(e,t,r){const n=wv(r);function s(i,a){const l=G2(e,ws(a,n));i.map(o=>ws(o,n)).forEach(o=>{e=Fl(e,o,()=>l)})}if(Gr(t)){const[i,a]=t;i.forEach(l=>{e=Fl(e,ws(l,n),()=>e)}),a&&Zn(a,s)}else Zn(t,s);return e}var j2=(e,t)=>Us(e)||Gr(e)||Gs(e)||Hs(e)||pv(e)||bv(e,t);function K2(e,t,r){const n=r.get(e);n?n.push(t):r.set(e,[t])}function z2(e,t){const r={};let n;return e.forEach(s=>{if(s.length<=1)return;t||(s=s.map(l=>l.map(String)).sort((l,o)=>l.length-o.length));const[i,...a]=s;i.length===0?n=a.map(xo):r[xo(i)]=a.map(xo)}),n?_l(r)?[n]:[n,r]:_l(r)?void 0:r}var kv=(e,t,r,n,s=[],i=[],a=new Map)=>{const l=P2(e);if(!l){K2(e,s,t);const p=a.get(e);if(p)return n?{transformedValue:null}:p}if(!j2(e,r)){const p=th(e,r),m=p?{transformedValue:p.value,annotations:[p.type]}:{transformedValue:e};return l||a.set(e,m),m}if(Gi(i,e))return{transformedValue:null};const o=th(e,r),c=o?.value??e,d=Gr(c)?[]:{},h={};Zn(c,(p,m)=>{if(m==="__proto__"||m==="constructor"||m==="prototype")throw new Error(`Detected property ${m}. This is a prototype pollution risk, please remove it from your object.`);const g=kv(p,t,r,n,[...s,m],[...i,e],a);d[m]=g.transformedValue,Gr(g.annotations)?h[Ol(m)]=g.annotations:Us(g.annotations)&&Zn(g.annotations,(b,y)=>{h[Ol(m)+"."+y]=b})});const f=_l(h)?{transformedValue:d,annotations:o?[o.type]:void 0}:{transformedValue:d,annotations:o?[o.type,h]:h};return l||a.set(e,f),f};function Tv(e){return Object.prototype.toString.call(e).slice(8,-1)}function rh(e){return Tv(e)==="Array"}function W2(e){if(Tv(e)!=="Object")return!1;const t=Object.getPrototypeOf(e);return!!t&&t.constructor===Object&&t===Object.prototype}function Q2(e,t,r,n,s){const i={}.propertyIsEnumerable.call(n,t)?"enumerable":"nonenumerable";i==="enumerable"&&(e[t]=r),s&&i==="nonenumerable"&&Object.defineProperty(e,t,{value:r,enumerable:!1,writable:!0,configurable:!0})}function Bl(e,t={}){if(rh(e))return e.map(s=>Bl(s,t));if(!W2(e))return e;const r=Object.getOwnPropertyNames(e),n=Object.getOwnPropertySymbols(e);return[...r,...n].reduce((s,i)=>{if(i==="__proto__"||rh(t.props)&&!t.props.includes(i))return s;const a=e[i];return Q2(s,i,Bl(a,t),e,t.nonenumerable),s},{})}var Be=class{constructor({dedupe:e=!1}={}){this.classRegistry=new E2,this.symbolRegistry=new dv(t=>t.description??""),this.customTransformerRegistry=new T2,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const t=new Map,r=kv(e,t,this,this.dedupe),n={json:r.transformedValue};r.annotations&&(n.meta={...n.meta,values:r.annotations});const s=z2(t,this.dedupe);return s&&(n.meta={...n.meta,referentialEqualities:s}),n.meta&&(n.meta.v=1),n}deserialize(e,t){const{json:r,meta:n}=e;let s=t?.inPlace?r:Bl(r);return n?.values&&(s=H2(s,n.values,n.v??0,this)),n?.referentialEqualities&&(s=V2(s,n.referentialEqualities,n.v??0)),s}stringify(e){return JSON.stringify(this.serialize(e))}parse(e){return this.deserialize(JSON.parse(e),{inPlace:!0})}registerClass(e,t){this.classRegistry.register(e,t)}registerSymbol(e,t){this.symbolRegistry.register(e,t)}registerCustom(e,t){this.customTransformerRegistry.register({name:t,...e})}allowErrorProps(...e){this.allowedErrorProps.push(...e)}};Be.defaultInstance=new Be;Be.serialize=Be.defaultInstance.serialize.bind(Be.defaultInstance);Be.deserialize=Be.defaultInstance.deserialize.bind(Be.defaultInstance);Be.stringify=Be.defaultInstance.stringify.bind(Be.defaultInstance);Be.parse=Be.defaultInstance.parse.bind(Be.defaultInstance);Be.registerClass=Be.defaultInstance.registerClass.bind(Be.defaultInstance);Be.registerSymbol=Be.defaultInstance.registerSymbol.bind(Be.defaultInstance);Be.registerCustom=Be.defaultInstance.registerCustom.bind(Be.defaultInstance);Be.allowErrorProps=Be.defaultInstance.allowErrorProps.bind(Be.defaultInstance);Be.serialize;Be.deserialize;Be.stringify;Be.parse;Be.registerClass;Be.registerCustom;Be.registerSymbol;Be.allowErrorProps;function q2({className:e}){return v("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e,children:[u("path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}),u("circle",{cx:"12",cy:"12",r:"3"})]})}function Y2({className:e}){return v("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e,children:[u("path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"}),u("path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242"}),u("path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"}),u("path",{d:"m2 2 20 20"})]})}function X2({className:e}){return u("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e,children:u("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})})}function Z2({onLogin:e,serverUrl:t,logoSrc:r,error:n,className:s}){const[i,a]=_(""),[l,o]=_(""),[c,d]=_(!1),[h,f]=_(!1),[p,m]=_(null),g=n??p,b=async y=>{if(y.preventDefault(),!h){m(null),f(!0);try{await e(i,l)}catch(S){m(S instanceof Error?S.message:"Login failed. Please try again.")}finally{f(!1)}}};return u("div",{className:L("flex min-h-screen items-center justify-center bg-background p-4",s),children:v("div",{className:"w-full max-w-sm",children:[r&&u("div",{className:"flex justify-center mb-8",children:u("img",{src:r,alt:"Logo",className:"h-12"})}),t&&u("p",{className:"mb-4 text-center text-xs text-foreground-subtle truncate",children:t}),v("form",{onSubmit:b,className:"space-y-4 rounded-xl border border-border bg-surface p-6 shadow-xl shadow-black/10",children:[g&&u("div",{className:"rounded-md bg-danger/10 border border-danger/20 px-3 py-2 text-xs text-danger",children:g}),v("div",{className:"space-y-1.5",children:[u("label",{className:"text-xs font-medium text-foreground-subtle",children:"Username"}),u("input",{type:"text",value:i,onChange:y=>a(y.target.value),autoComplete:"username",required:!0,className:"w-full rounded-lg border border-border bg-background px-3 py-2.5 text-sm text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary"})]}),v("div",{className:"space-y-1.5",children:[u("label",{className:"text-xs font-medium text-foreground-subtle",children:"Password"}),v("div",{className:"relative",children:[u("input",{type:c?"text":"password",value:l,onChange:y=>o(y.target.value),autoComplete:"current-password",required:!0,className:"w-full rounded-lg border border-border bg-background px-3 py-2.5 pr-10 text-sm text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary"}),u("button",{type:"button",onClick:()=>d(y=>!y),className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-foreground-subtle hover:text-foreground",tabIndex:-1,children:c?u(Y2,{className:"h-4 w-4"}):u(q2,{className:"h-4 w-4"})})]})]}),v("button",{type:"submit",disabled:h,className:"w-full rounded-lg bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-2",children:[h&&u(X2,{className:"h-4 w-4 animate-spin"}),h?"Logging in...":"Log in"]})]})]})})}var Ul="camstack_dev_token",Av=hr(null);function oj(){const e=ct(Av);if(!e)throw new Error("useDevShell must be used within a DevShell");return e}function J2(){return typeof window>"u"?null:localStorage.getItem(Ul)}function eN({className:e}){return v("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e,children:[u("circle",{cx:"12",cy:"12",r:"4"}),u("path",{d:"M12 2v2"}),u("path",{d:"M12 20v2"}),u("path",{d:"m4.93 4.93 1.41 1.41"}),u("path",{d:"m17.66 17.66 1.41 1.41"}),u("path",{d:"M2 12h2"}),u("path",{d:"M20 12h2"}),u("path",{d:"m6.34 17.66-1.41 1.41"}),u("path",{d:"m19.07 4.93-1.41 1.41"})]})}function tN({className:e}){return u("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e,children:u("path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"})})}function rN({children:e,serverUrl:t,title:r,token:n,onLogout:s}){const i=v0(),a=oe(()=>[Ky({condition:f=>f.type==="subscription",true:zy({client:Wy({url:t.replace(/^http/,"ws")+"/trpc",connectionParams:()=>({token:n})}),transformer:Be}),false:Qf({url:`${t}/trpc`,transformer:Be,headers:()=>({authorization:`Bearer ${n}`})})})],[t,n]),l=oe(()=>Wf({links:a}),[a]),o=oe(()=>x.createClient({links:a}),[a]),c=oe(()=>l0({serverUrl:t,token:n}),[t,n]);ae(()=>(c.init().catch(()=>{}),()=>{c.close()}),[c]);const d=oe(()=>new Vy,[]),h=oe(()=>({trpc:l,token:n,logout:s}),[l,n,s]);return u(dw,{system:c,children:u(x.Provider,{client:o,queryClient:d,children:u(jy,{client:d,children:u(Av.Provider,{value:h,children:v("div",{className:"min-h-screen bg-background text-foreground",children:[v("div",{className:"flex items-center justify-between border-b border-border bg-surface px-4 py-2",children:[v("div",{className:"flex items-center gap-2",children:[u("span",{className:"rounded bg-warning/20 px-2 py-0.5 text-xs font-bold text-warning",children:"DEV MODE"}),r&&u("span",{className:"text-sm font-medium text-foreground",children:r}),u("span",{className:"text-xs text-foreground-subtle",children:t})]}),v("div",{className:"flex items-center gap-2",children:[v("button",{type:"button",onClick:i.toggleMode,className:"flex items-center gap-1.5 rounded-md px-2 py-1 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",title:`Theme: ${i.mode}`,children:[i.resolvedMode==="dark"?u(eN,{className:"h-3.5 w-3.5"}):u(tN,{className:"h-3.5 w-3.5"}),i.mode==="dark"?"Dark":i.mode==="light"?"Light":"System"]}),u("button",{type:"button",onClick:s,className:"rounded-md px-2.5 py-1 text-xs font-medium text-danger hover:bg-danger/10 transition-colors",children:"Logout"})]})]}),u("div",{className:"p-4",children:e({trpc:l,theme:i})})]})})})})})}function nN({children:e,serverUrl:t="https://localhost:4443",title:r}){const[n,s]=_(J2),i=q(async(l,o)=>{const c=await Wf({links:[Qf({url:`${t}/trpc`,transformer:Be})]}).auth.login.mutate({username:l,password:o});if(!c.token)throw new Error("No token returned");localStorage.setItem(Ul,c.token),s(c.token)},[t]),a=q(()=>{localStorage.removeItem(Ul),s(null)},[]);return n?u(Gu,{children:u(rN,{serverUrl:t,title:r,token:n,onLogout:a,children:e})}):u(Gu,{children:u(Z2,{onLogin:i,serverUrl:t})})}function lj(e,t={}){const{serverUrl:r="https://localhost:4443",title:n,rootId:s="root"}=t,i=document.getElementById(s);if(!i){console.error(`[mountAddonPage] Element #${s} not found`);return}Gy(i).render(Is(nN,{serverUrl:r,title:n,children:({trpc:a,theme:l})=>Is(e,{trpc:a,theme:{isDark:l.resolvedMode==="dark"},navigate:o=>{console.log("[dev] navigate:",o)}})}))}var Cv=Nr("camstack:custom-field-renderers",{});function cj({renderers:e,children:t}){return u(Cv.Provider,{value:e,children:t})}function sN(e){return ct(Cv)[e]??null}var nu=Nr("camstack:device-context",null);function uj({deviceId:e,device:t,children:r}){const n={deviceId:e,device:t??null};return u(nu.Provider,{value:n,children:r})}function iN(){return ct(nu)?.deviceId??null}function dj(){return ct(nu)?.device??null}var Nv=Nr("camstack:widget-registry",null),da=new Map,li=new Map,nh=new Set;function su(e,t){return`${e}::${t}`}function aN(e){if(!e||typeof e!="object")return!1;const t=e.default;return t!==null&&typeof t=="object"}function oN(e){if(!e||typeof e!="object")return typeof e;const t=e,r=Object.getPrototypeOf(t),n=r&&typeof r=="object"?r.constructor?.name:void 0;return{ownKeys:Object.keys(t),allKeys:Object.getOwnPropertyNames(t),proto:typeof n=="string"?n:void 0}}async function Lv(e,t,r){const n=su(e,t),s=da.get(n);if(s)return s;const i=li.get(n);if(i)return i;nh.has(e)||(tS(),Yx([{name:e,entry:r,type:"module"}],{force:!1}),nh.add(e));const a=qx(`${e}/${t.startsWith("./")?t.slice(2):t}`).then(l=>{if(!aN(l)){const c=oN(l);throw new Error(`Remote ${e} (${r}) does not expose a default record on '${t}'. Got: ${JSON.stringify(c)}`)}const o=l.default;return da.set(n,o),li.delete(n),o}).catch(l=>{throw li.delete(n),l});return li.set(n,a),a}function Gl(e,t){return da.get(su(e,t))}var lN=3e4,cN=2e3;function hj({children:e}){const t=ts(),r=ne(Date.now()),{data:n}=sk(void 0,{staleTime:0,refetchOnMount:"always",refetchInterval:o=>{const c=o.state.data;return c&&c.length>0||Date.now()-r.current>=lN?!1:cN}});Ma("addon.widget-ready",()=>{t.invalidateQueries({queryKey:[["addonWidgets","listWidgets"]]})});const[s,i]=_(0),a=oe(()=>n??[],[n]);ae(()=>{if(a.length===0)return;let o=!1;const c=new Set;for(const d of a){const h=su(d.remote.remoteName,d.remote.exposedModule);if(c.has(h)||(c.add(h),da.has(h)))continue;const f=d.bundleUrl;Lv(d.remote.remoteName,d.remote.exposedModule,f).then(()=>{o||i(p=>p+1)}).catch(p=>{const m=p instanceof Error?p.message:String(p);(typeof globalThis<"u"?globalThis.console:void 0)?.error?.("[WidgetRegistry] Failed to load widget remote",{remoteName:d.remote.remoteName,exposedModule:d.remote.exposedModule,entryUrl:f,reason:m})})}return()=>{o=!0}},[a]);const l=oe(()=>{const o=new Map,c=new Map;for(const h of a)o.set(`${h.addonId}/${h.stableId}`,h),c.set(h.remote.remoteName,h.bundleUrl);const d=(h,f)=>({widgetId:h,addonId:f.addonId,stableId:f.stableId,tab:f.tab,subTab:f.subTab,label:f.label,order:f.order,kind:f.kind,remote:f.remote,description:f.description,icon:f.icon,bundleUrl:f.bundleUrl,hosts:f.hosts,requires:f.requires,defaultSize:f.defaultSize,allowedSizes:f.allowedSizes,defaultColumns:f.defaultColumns,defaultRows:f.defaultRows});return{resolve:h=>{const f=o.get(h);if(!f)return;const p=Gl(f.remote.remoteName,f.remote.exposedModule);if(!p)return null;const m=p[f.remote.componentKey??f.stableId];if(m)return m},metadata:h=>{const f=o.get(h);if(f)return d(h,f)},listAll:()=>{const h=[];for(const[f,p]of o)h.push(d(f,p));return h},entryUrlFor:h=>c.get(h)}},[a,s]);return u(Nv.Provider,{value:l,children:e})}function fj(e){return iu().resolve(e)}function uN(e){return iu().metadata(e)}function pj(){return iu().listAll()}function dN(e,t){const r=Iv(),n=t??r?.entryUrlFor(e.remoteName),[s,i]=_(0),[a,l]=_(!1);return ae(()=>{if(!n||(l(!1),Gl(e.remoteName,e.exposedModule)))return;let o=!1;return Lv(e.remoteName,e.exposedModule,n).then(()=>{o||i(c=>c+1)}).catch(c=>{const d=c instanceof Error?c.message:String(c);(typeof globalThis<"u"?globalThis.console:void 0)?.error?.("[WidgetRegistry] Failed to load remote component",{remoteName:e.remoteName,exposedModule:e.exposedModule,entryUrl:n,reason:d}),o||l(!0)}),()=>{o=!0}},[e.remoteName,e.exposedModule,n]),oe(()=>{if(!n||a)return;const o=Gl(e.remoteName,e.exposedModule);if(!o)return null;const c=e.componentKey;return c===void 0?Object.values(o)[0]??void 0:o[c]??void 0},[e.remoteName,e.exposedModule,e.componentKey,n,s,a])}function iu(){const e=Iv();if(!e)throw new Error("useWidgetRegistry(): no <WidgetRegistryProvider> in tree");return e}function Iv(){return hN(Nv)}function hN(e){return ct(e)}function Hr({title:e,icon:t,headerRight:r,collapsible:n=!1,defaultOpen:s=!0,bodyClassName:i="p-3",children:a}){const[l,o]=_(s),c=!n||l,d=v(Ie,{children:[v("span",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-foreground",children:[t,e]}),n?l?u(yt,{className:"h-3.5 w-3.5 text-foreground-subtle"}):u(nr,{className:"h-3.5 w-3.5 text-foreground-subtle"}):r]}),h=`px-4 py-2 flex items-center justify-between ${c?"border-b border-border":""}`;return v("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[n?u("button",{type:"button",onClick:()=>o(f=>!f),className:`w-full text-left ${h}`,children:d}):u("div",{className:h,children:d}),c?u("div",{className:i,children:a}):null]})}function So({label:e,icon:t,children:r,footer:n}){return v("div",{className:"rounded-md border border-border/60 bg-background/40 px-3 py-2",children:[v("div",{className:"mb-1 flex items-center gap-1.5 text-[11px] uppercase tracking-wider text-foreground-subtle",children:[t,e]}),u("div",{className:"text-sm font-medium text-foreground",children:r}),n?u("div",{className:"mt-0.5 text-[10px] text-foreground-subtle",children:n}):null]})}function fN({deviceId:e}){const t=Qt(Gt().trpcClient,e),[r,n]=_(null),[s,i]=_(!1);ae(()=>{if(!t)return;let l=!1;return(async()=>{try{const o=await t.ptz?.getStatus({});if(l||!o)return;n(o.autofocus)}catch{}})(),()=>{l=!0}},[t]);const a=q(async()=>{if(!(!t?.ptz||r===null)){i(!0);try{const l=!r;await t.ptz.setAutofocus({enabled:l}),n(l)}catch(l){console.error("ptz.setAutofocus failed",l)}finally{i(!1)}}},[t,r]);return r===null?null:v("div",{className:"flex items-center justify-between border-t border-border/40 mt-2 pt-2",children:[u("span",{className:"text-[10.5px] font-semibold text-foreground",children:"Autofocus"}),v("button",{type:"button",onClick:()=>void a(),disabled:s,"aria-pressed":r,className:`flex items-center gap-1.5 rounded-md px-2 py-1 text-[10px] font-medium transition-colors ${r?"bg-success/15 text-success hover:bg-success/25":"bg-surface-elevated/40 text-foreground-subtle hover:bg-surface-hover hover:text-foreground"} disabled:opacity-50`,children:[u("span",{className:`h-1.5 w-1.5 rounded-full ${r?"bg-success":"bg-foreground-subtle/40"}`}),r?"On":"Off"]})]})}function pN({deviceId:e}){const t=Gt(),r=Number.isFinite(e),n=mg(t.trpcClient,r?e:0,{enabled:r});if(!r)return v("div",{className:"flex items-center justify-center h-full text-[11px] text-foreground-subtle italic",children:["Device #",e," not loaded."]});const s=n.options?.hasAutofocus===!0;return v(Hr,{title:"PTZ",icon:u(iE,{className:"h-3.5 w-3.5 text-foreground-subtle"}),bodyClassName:"p-3 flex flex-col overflow-y-auto",children:[u(gg,{controls:n,mode:"panel"}),s&&u(fN,{deviceId:e})]})}var mN=15;function gN(e){return e.status==="replace"||e.level!==null&&e.level<=mN}function vN(e){try{return new Date(e).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}catch{return""}}function bN({item:e,busy:t,canReset:r,onReset:n}){const s=gN(e),i=s?"bg-warning":"bg-success";return v("div",{className:`flex flex-col gap-1.5 rounded-md border p-3 ${s?"border-warning/40 bg-warning/5":"border-border/40 bg-surface-elevated/30"}`,children:[v("div",{className:"flex items-center justify-between gap-2",children:[u("span",{className:`text-xs font-semibold ${s?"text-warning":"text-foreground"}`,children:e.label}),e.resettable&&u("button",{type:"button",onClick:()=>n(e.key),disabled:t||!r,className:"rounded-md border border-border bg-surface px-2 py-0.5 text-[10px] font-medium text-foreground-subtle hover:bg-surface-hover disabled:opacity-40 transition-colors",children:"Replaced"})]}),e.level!==null?v("div",{className:"flex items-center gap-2",children:[u("div",{className:"h-1.5 flex-1 overflow-hidden rounded-full bg-surface-elevated/60",children:u("div",{className:`h-full rounded-full ${i} transition-all`,style:{width:`${Math.max(0,Math.min(100,e.level))}%`}})}),v("span",{className:"text-[10px] font-medium tabular-nums text-foreground-subtle",children:[Math.round(e.level),"%"]})]}):e.status!==null?u("span",{className:`inline-flex w-fit items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-medium ${e.status==="replace"?"bg-warning/15 text-warning":"bg-success/15 text-success"}`,children:e.status==="replace"?"Replace":"OK"}):u("span",{className:"text-[10px] text-foreground-subtle",children:"—"}),e.lastResetAt!==null&&v("span",{className:"text-[10px] text-foreground-subtle",children:["Replaced ",vN(e.lastResetAt)]})]})}function yN({deviceId:e}){const t=Gt(),r=Number.isFinite(e),{cap:n,slice:s,available:i}=_e({trpc:t.trpcClient,deviceId:r?e:null,cap:d=>d.consumables,slice:d=>d.state.consumables}),[a,l]=_(null),o=q(async d=>{if(n){l(d);try{await n.reset({key:d})}catch(h){console.error("consumables.reset failed",h)}finally{l(null)}}},[n]),c=s?.items??[];return u(Hr,{title:"Consumables",icon:u(xs,{className:"h-3.5 w-3.5 text-foreground-subtle"}),bodyClassName:"p-3 overflow-y-auto",children:c.length===0?u("p",{className:"text-[11px] text-foreground-subtle italic leading-relaxed",children:"No consumables reported."}):u("div",{className:"flex flex-col gap-2",children:c.map(d=>u(bN,{item:d,busy:a===d.key,canReset:i,onReset:h=>void o(h)},d.key))})})}function xN(e){const t=ts(),r=mk({deviceId:e??0},{enabled:e!==null&&Number.isFinite(e),refetchInterval:5e3,retry:1}),n=gk({onSuccess:()=>{t.invalidateQueries({queryKey:[["ptzAutotrack"]]})}}),s=vk({onSuccess:()=>{t.invalidateQueries({queryKey:[["ptzAutotrack"]]})}}),i=q(async o=>{e!==null&&await n.mutateAsync({deviceId:e,enabled:o})},[e,n]),a=q(async o=>{e!==null&&await s.mutateAsync({deviceId:e,settings:o})},[e,s]),l=r.error?r.error.message:n.error?n.error.message:s.error?s.error.message:null;return{status:r.data??null,isLoading:r.isLoading,isPending:n.isPending||s.isPending,error:l,setEnabled:i,setSettings:a}}function SN({deviceId:e}){const{status:t,isLoading:r,isPending:n,error:s,setEnabled:i,setSettings:a}=xN(Number.isFinite(e)?e:null),[l,o]=_({targetType:"",stopDelaySeconds:30,disappearDelaySeconds:15}),[c,d]=_(!1);ae(()=>{if(c)return;const f=t?.currentSettings;f&&o({targetType:f.targetType,stopDelaySeconds:f.stopDelaySeconds,disappearDelaySeconds:f.disappearDelaySeconds})},[t,c]);const h=u(Nc,{className:"h-3.5 w-3.5 text-foreground-subtle"});return r&&!t?u(Hr,{title:"Autotrack",icon:h,children:v("div",{className:"flex items-center gap-2 text-[10.5px] text-foreground-subtle",children:[u(vt,{className:"h-3 w-3 animate-spin"}),"Loading autotrack…"]})}):v(Hr,{title:"Autotrack",icon:h,headerRight:v("button",{type:"button",onClick:()=>{i(!(t?.enabled??!1))},disabled:n,className:`flex items-center gap-1.5 rounded-md px-2 py-1 text-[10px] font-medium transition-colors ${t?.enabled?"bg-success/15 text-success hover:bg-success/25":"bg-surface-elevated/40 text-foreground-subtle hover:bg-surface-hover hover:text-foreground"} disabled:opacity-50`,"aria-pressed":t?.enabled??!1,children:[u("span",{className:`h-1.5 w-1.5 rounded-full ${t?.enabled?"bg-success":"bg-foreground-subtle/40"}`}),t?.enabled?"Enabled":"Disabled"]}),bodyClassName:"p-3 space-y-2",children:[s&&v("div",{className:"flex items-start gap-1.5 rounded-md border border-danger/30 bg-danger/5 px-2 py-1.5 text-[10px] text-danger",children:[u(rs,{className:"h-3 w-3 flex-shrink-0 mt-0.5"}),u("span",{className:"leading-snug break-words",children:s})]}),v("div",{className:"grid grid-cols-2 gap-2 px-2",children:[(t?.supportedTargetTypes?.length??0)>0&&v("label",{className:"col-span-2 flex flex-col gap-1",children:[u("span",{className:"text-[10px] font-medium text-foreground-subtle",children:"Target type"}),u("select",{value:l.targetType,onFocus:()=>d(!0),onChange:f=>o(p=>({...p,targetType:f.target.value})),onBlur:()=>{d(!1);const f=t?.currentSettings?.targetType??"";l.targetType!==f&&a({targetType:l.targetType})},disabled:n,className:"rounded-md border border-border bg-surface px-2 py-1 text-[11px] text-foreground focus:border-primary focus:outline-none disabled:opacity-50",children:(t?.supportedTargetTypes??[]).map(f=>u("option",{value:f.value,children:f.label},f.value))})]}),v("label",{className:"flex flex-col gap-1",children:[u("span",{className:"text-[10px] font-medium text-foreground-subtle",children:"Stop delay (s)"}),u("input",{type:"number",min:0,max:300,value:l.stopDelaySeconds,onFocus:()=>d(!0),onChange:f=>o(p=>({...p,stopDelaySeconds:Number(f.target.value)||0})),onBlur:()=>{d(!1);const f=t?.currentSettings?.stopDelaySeconds??30;l.stopDelaySeconds!==f&&a({stopDelaySeconds:l.stopDelaySeconds})},disabled:n,className:"rounded-md border border-border bg-surface px-2 py-1 text-[11px] text-foreground focus:border-primary focus:outline-none disabled:opacity-50"})]}),v("label",{className:"flex flex-col gap-1",children:[u("span",{className:"text-[10px] font-medium text-foreground-subtle",children:"Disappear delay (s)"}),u("input",{type:"number",min:0,max:300,value:l.disappearDelaySeconds,onFocus:()=>d(!0),onChange:f=>o(p=>({...p,disappearDelaySeconds:Number(f.target.value)||0})),onBlur:()=>{d(!1);const f=t?.currentSettings?.disappearDelaySeconds??15;l.disappearDelaySeconds!==f&&a({disappearDelaySeconds:l.disappearDelaySeconds})},disabled:n,className:"rounded-md border border-border bg-surface px-2 py-1 text-[11px] text-foreground focus:border-primary focus:outline-none disabled:opacity-50"})]})]}),u("p",{className:"px-2 text-[9.5px] text-foreground-subtle leading-snug italic",children:"Settings save on blur. Vendor support varies — Reolink honours all three; Hikvision honours target type + stop delay only (disappear delay is accepted but ignored at firmware push)."})]})}var au=Nr("camstack:player-overlays-state",null),ou=Nr("camstack:player-overlays-actions",null);function mj({children:e}){const[t,r]=_(()=>new Map),[n,s]=_(()=>new Map),i=q(h=>{r(f=>{const p=new Map(f);return p.set(h.id,h),p})},[]),a=q(h=>{r(f=>{if(!f.has(h))return f;const p=new Map(f);return p.delete(h),p})},[]),l=q(h=>{s(f=>{const p=new Map(f);return p.set(h.id,h),p})},[]),o=q(h=>{s(f=>{if(!f.has(h))return f;const p=new Map(f);return p.delete(h),p})},[]),c=oe(()=>({layers:t,buttons:n}),[t,n]),d=oe(()=>({setLayer:i,removeLayer:a,setButton:l,removeButton:o}),[i,a,l,o]);return u(au.Provider,{value:c,children:u(ou.Provider,{value:d,children:e})})}function gj(){const e=ct(au);return oe(()=>e?[...e.layers.values()].sort((t,r)=>t.order-r.order):[],[e])}function EN(){const e=ct(au);return oe(()=>e?[...e.buttons.values()].sort((t,r)=>t.order-r.order):[],[e])}function Rv(e){const t=ct(ou);ae(()=>{if(!(!t||!e))return t.setLayer(e),()=>t.removeLayer(e.id)},[t,e])}function vj(e){const t=ct(ou);ae(()=>{if(!(!t||!e))return t.setButton(e),()=>t.removeButton(e.id)},[t,e])}var Mv={rect:"#ef4444",polygon:"#3b82f6",grid:"#6366f1",line:"#f59e0b"},Pv="33",lu="66",ci="#6366f1",En=3,sh=2,wN=12,Eo=16,wo=9;function ks(e,t,r){return{x:e.x*t,y:e.y*r}}function Hl(e,t,r){return{x:e.x/t,y:e.y/r}}function Dv(e,t,r){return e.flatMap(n=>[n.x*t,n.y*r])}function On(e){return!Number.isFinite(e)||e<0?0:e>1?1:e}function kN(e){return e.color??Mv[e.shape.kind]}function TN(e,t){const r=e[t],n=e[(t+1)%e.length];if(!r||!n)return[...e];const s={x:(r.x+n.x)/2,y:(r.y+n.y)/2};return[...e.slice(0,t+1),s,...e.slice(t+1)]}function AN(e,t){return e.length!==t.length?!1:e.every((r,n)=>{const s=t[n];return Math.abs(r.x-s.x)<1e-6&&Math.abs(r.y-s.y)<1e-6})}function CN(e){return e.kind==="polygon"||e.kind==="line"}function NN({items:e,selectedId:t,onSelect:r,onShapeChange:n,onDrawComplete:s,drawingKind:i,supportedShapes:a,transparent:l=!1,backdrop:o,polygonVertices:c,grid:d}){const h=ne(null),[f,p]=_({w:800,h:450}),[m,g]=_([]),[b,y]=_(null),[S,E]=_(null),[k,T]=_(null),A=i!==null&&a.includes(i);ae(()=>{if(!k)return;const I=e.find(R=>R.id===k.itemId);if(!I||!CN(I.shape)){T(null);return}AN(I.shape.points,k.points)&&T(null)},[e,k]),ae(()=>{const I=h.current;if(!I)return;const R=new ResizeObserver(O=>{const K=O[0];if(!K)return;const{width:W,height:J}=K.contentRect;p(l?{w:W,h:J}:{w:W,h:W*9/16})});return R.observe(I),()=>R.disconnect()},[l]),ae(()=>{!A&&b!==null&&y(null)},[A,b]);const N=q(I=>{s(I),g([])},[s]),C=q(I=>{if(!A||i===null){r(null);return}const R=I.target.getStage();if(!R)return;const O=R.getPointerPosition();if(!O)return;const K=Hl(O,f.w,f.h);if(i==="rect"){const W=On(K.x),J=On(K.y);N({kind:"rect",x:W,y:J,width:Math.min(.2,1-W),height:Math.min(.2,1-J)});return}if(i==="grid"){const W=d?.width??Eo,J=d?.height??wo;N({kind:"grid",gridWidth:W,gridHeight:J,cells:Array.from({length:W*J},()=>!1)});return}if(i==="line"){if(m.length===0){g([K]);return}N({kind:"line",points:[...m,K]});return}if(i==="polygon"){if(m.length===0){g([K]);return}if(m.length>=En){const W=ks(m[0],f.w,f.h);if(Math.hypot(O.x-W.x,O.y-W.y)<wN){N({kind:"polygon",points:m});return}}g(W=>[...W,K])}},[A,i,m,f,d,N,r]),M=q(I=>{!A||i!=="polygon"||m.length<En||(I.cancelBubble=!0,N({kind:"polygon",points:m}))},[A,i,m,N]),P=ne(null),D=ne(null);ae(()=>()=>{P.current!==null&&cancelAnimationFrame(P.current)},[]);const $=q(I=>{if(!A)return;const R=I.target.getStage();R&&(D.current=R.getPointerPosition()??null,P.current===null&&(P.current=requestAnimationFrame(()=>{P.current=null,y(D.current)})))},[A]),B=ne(!1),j=ne(!0),U=ne(new Set),F=q((I,R,O,K)=>{const W=R.gridWidth*R.gridHeight;if(O<0||O>=W||R.cells[O]===K)return;const J=[...R.cells];for(;J.length<W;)J.push(!1);J.length=W,J[O]=K,n(I,{...R,cells:J})},[n]),Y=[];if(!l){for(let I=1;I<Eo;I++){const R=f.w/Eo*I;Y.push(u(rn,{points:[R,0,R,f.h],stroke:"#ffffff",strokeWidth:.5,opacity:.08},`gv-${I}`))}for(let I=1;I<wo;I++){const R=f.h/wo*I;Y.push(u(rn,{points:[0,R,f.w,R],stroke:"#ffffff",strokeWidth:.5,opacity:.08},`gh-${I}`))}}return v("div",{ref:h,className:l?"absolute inset-0":"relative w-full bg-zinc-900 rounded-lg overflow-hidden",style:{cursor:A?"crosshair":"default"},children:[o&&!l?u("div",{className:"absolute inset-0 pointer-events-none [&>*]:w-full [&>*]:h-full [&>img]:object-cover [&>video]:object-cover",style:{width:f.w,height:f.h},children:o}):null,v(qy,{width:f.w,height:f.h,onClick:C,onDblClick:M,onMouseMove:$,children:[v(Ga,{listening:!1,children:[u(rn,{points:[0,0,f.w,0,f.w,f.h,0,f.h,0,0],stroke:"transparent",strokeWidth:0}),Y]}),u(Ga,{children:e.map(I=>{const R=I.id===t,O=I.enabled===!1,K=kN(I),W=R&&!A&&!O;if(I.shape.kind==="rect")return u(IN,{item:I,shape:I.shape,color:K,selected:R,dimmed:O,editable:W,isDrawing:A,size:f,onSelect:r,onShapeChange:n},I.id);if(I.shape.kind==="grid")return u(RN,{item:I,shape:I.shape,color:K,dimmed:O,editable:W,size:f,onSelect:r,paintingRef:B,paintValueRef:j,paintedRef:U,paintCell:F},I.id);const J=I.shape.kind==="line",Q=J?sh:Math.max(En,c?.min??En),ee=J?sh:c?.max,ie=k&&k.itemId===I.id?k.points:I.shape.points;return u(MN,{item:I,shape:I.shape,color:K,selected:R,dimmed:O,editable:W,isLine:J,isDrawing:A,size:f,effectivePoints:ie,minVertices:Q,maxVertices:ee,isDragging:S===I.id,onSelect:r,onShapeChange:n,setDragOverride:T,setDraggingItemId:E},I.id)})}),u(Ga,{listening:!1,children:A&&m.length>0&&v(Wn,{children:[i==="polygon"&&m.length>=2&&u(rn,{points:Dv(m,f.w,f.h),stroke:ci,strokeWidth:1.5,dash:[6,3],opacity:.8}),i==="line"&&m.length===1&&b&&u(rn,{points:[m[0].x*f.w,m[0].y*f.h,b.x,b.y],stroke:Mv.line,strokeWidth:1.5,dash:[6,3],opacity:.7}),i==="polygon"&&b&&m.length>=1&&u(rn,{points:[m[m.length-1].x*f.w,m[m.length-1].y*f.h,b.x,b.y],stroke:ci,strokeWidth:1,dash:[4,4],opacity:.5}),m.map((I,R)=>{const O=ks(I,f.w,f.h),K=R===0&&i==="polygon"&&m.length>=En;return u(Ji,{x:O.x,y:O.y,radius:K?7:4,fill:K?ci:"#ffffff",stroke:ci,strokeWidth:1.5,opacity:.9},R)})]})})]}),A?u("div",{className:"px-3 py-1.5 bg-zinc-800/80 text-[11px] text-zinc-400 border-t border-zinc-700",children:i==="line"?"Click to set the start point, click again to complete the line":i==="rect"?"Click to drop a rectangle, then drag the corner to resize":i==="grid"?"Click to add the grid, then paint cells":m.length<En?"Click to add points (min 3). Double-click or click the first point to close.":"Continue adding points. Double-click or click the first point to close."}):null]})}var ui=.02;function LN(e,t){return Math.abs(e.x-t.x)<1e-6&&Math.abs(e.y-t.y)<1e-6&&Math.abs(e.width-t.width)<1e-6&&Math.abs(e.height-t.height)<1e-6}function IN({item:e,shape:t,color:r,selected:n,dimmed:s,editable:i,isDrawing:a,size:l,onSelect:o,onShapeChange:c}){const[d,h]=_(null),f={x:t.x,y:t.y,width:t.width,height:t.height};ae(()=>{d&&LN(f,d)&&h(null)},[t.x,t.y,t.width,t.height,d]);const p=d??f,m=p.x*l.w,g=p.y*l.h,b=p.width*l.w,y=p.height*l.h,S=s?.35:n?1:.85,E=C=>{h(C),c(e.id,{kind:"rect",x:C.x,y:C.y,width:C.width,height:C.height})},k=C=>({x:Math.max(-m,Math.min(l.w-(m+b),C.x)),y:Math.max(-g,Math.min(l.h-(g+y),C.y))}),T=C=>{const M=C.target,P=M.x()/l.w,D=M.y()/l.h;if(M.position({x:0,y:0}),P===0&&D===0)return;const $=Math.min(Math.max(0,p.x+P),Math.max(0,1-p.width)),B=Math.min(Math.max(0,p.y+D),Math.max(0,1-p.height));E({...p,x:$,y:B})},A=C=>{const M=C.target,P=On(M.x()/l.w-p.x),D=On(M.y()/l.h-p.y);h({...p,width:Math.max(ui,Math.min(P,1-p.x)),height:Math.max(ui,Math.min(D,1-p.y))})},N=C=>{const M=C.target,P=On(M.x()/l.w-p.x),D=On(M.y()/l.h-p.y);E({...p,width:Math.max(ui,Math.min(P,1-p.x)),height:Math.max(ui,Math.min(D,1-p.y))})};return u(Wn,{onClick:C=>{C.cancelBubble=!0,a||o(e.id)},children:v(Wn,{draggable:i,dragBoundFunc:i?k:void 0,onDragEnd:i?T:void 0,onMouseEnter:C=>{if(!i)return;const M=C.target.getStage();M&&(M.container().style.cursor="move")},onMouseLeave:C=>{if(!i)return;const M=C.target.getStage();M&&(M.container().style.cursor=a?"crosshair":"default")},children:[u(Zf,{x:m,y:g,width:b,height:y,fill:r+(n?lu:Pv),stroke:r,strokeWidth:n?2.5:1.5,opacity:S}),e.label?u(Jf,{x:m,y:g-16,text:e.label,fontSize:12,fill:r,stroke:"#000000",strokeWidth:3,fillAfterStrokeEnabled:!0,fontStyle:"bold",listening:!1}):null,i?u(Ji,{x:m+b,y:g+y,radius:6,fill:r,stroke:"#ffffff",strokeWidth:1.5,draggable:!0,dragBoundFunc:C=>({x:Math.min(l.w,Math.max(m,C.x)),y:Math.min(l.h,Math.max(g,C.y))}),onDragStart:C=>{C.cancelBubble=!0},onDragMove:A,onDragEnd:N,onMouseEnter:C=>{const M=C.target.getStage();M&&(M.container().style.cursor="nwse-resize")},onMouseLeave:C=>{const M=C.target.getStage();M&&(M.container().style.cursor="default")}}):null]})})}function RN({item:e,shape:t,color:r,dimmed:n,editable:s,size:i,onSelect:a,paintingRef:l,paintValueRef:o,paintedRef:c,paintCell:d}){const{gridWidth:h,gridHeight:f,cells:p}=t,m=i.w/h,g=i.h/f,b=h*f,y=n?.3:1,S=T=>{if(!s){a(e.id);return}const A=p[T]!==!0;l.current=!0,o.current=A,c.current=new Set([T]),d(e.id,t,T,A)},E=T=>{!l.current||!s||c.current.has(T)||(c.current.add(T),d(e.id,t,T,o.current))},k=()=>{l.current&&(l.current=!1,c.current=new Set)};return u(Wn,{opacity:y,onMouseUp:k,onMouseLeave:k,children:Array.from({length:b},(T,A)=>{const N=A%h,C=Math.floor(A/h),M=p[A]===!0;return u(Zf,{x:N*m,y:C*g,width:m,height:g,fill:M?r+lu:"#ffffff10",stroke:M?r:"#ffffff40",strokeWidth:.5,onMouseDown:P=>{P.cancelBubble=!0,S(A)},onMouseEnter:()=>E(A)},A)})})}function MN({item:e,shape:t,color:r,selected:n,dimmed:s,editable:i,isLine:a,isDrawing:l,size:o,effectivePoints:c,minVertices:d,maxVertices:h,isDragging:f,onSelect:p,onShapeChange:m,setDragOverride:g,setDraggingItemId:b}){const y=Dv(c,o.w,o.h),S=s?.35:n?1:a?.8:.85,E=j=>a?{kind:"line",points:[...j]}:{kind:"polygon",points:[...j]},k=c.map(j=>j.x*o.w),T=c.map(j=>j.y*o.h),A=k.length>0?Math.min(...k):0,N=k.length>0?Math.max(...k):0,C=T.length>0?Math.min(...T):0,M=T.length>0?Math.max(...T):0,P=j=>({x:Math.max(-A,Math.min(o.w-N,j.x)),y:Math.max(-C,Math.min(o.h-M,j.y))}),D=j=>{const U=j.target,F=U.x()/o.w,Y=U.y()/o.h;if(U.position({x:0,y:0}),b(null),F===0&&Y===0)return;const I=t.points.map(R=>({x:R.x+F,y:R.y+Y}));g({itemId:e.id,points:I}),m(e.id,E(I))},$=!a&&c.length>d,B=!a&&(h===void 0||c.length<h);return v(Wn,{onClick:j=>{j.cancelBubble=!0,l||p(e.id)},children:[v(Wn,{draggable:i,dragBoundFunc:i?P:void 0,onDragStart:i?()=>b(e.id):void 0,onDragEnd:i?D:void 0,onMouseEnter:j=>{if(!i)return;const U=j.target.getStage();U&&(U.container().style.cursor="move")},onMouseLeave:j=>{if(!i)return;const U=j.target.getStage();U&&(U.container().style.cursor=l?"crosshair":"default")},children:[a?u(Yy,{points:y,stroke:r,strokeWidth:n?3:2,fill:r,pointerLength:10,pointerWidth:8,opacity:S}):u(rn,{points:y,closed:!0,fill:r+(n?lu:Pv),stroke:r,strokeWidth:n?2.5:1.5,opacity:S}),e.label&&c.length>0?(()=>{const j=ks({x:c.reduce((F,Y)=>F+Y.x,0)/c.length,y:c.reduce((F,Y)=>F+Y.y,0)/c.length},o.w,o.h),U=Math.max(40,e.label.length*11*.62);return u(Jf,{x:j.x-U/2,y:j.y-7,width:U,align:"center",text:e.label,fontSize:12,fill:r,stroke:"#000000",strokeWidth:3,fillAfterStrokeEnabled:!0,fontStyle:"bold",listening:!1})})():null]}),i&&!f&&c.map((j,U)=>{const F=ks(j,o.w,o.h);return u(Ji,{x:F.x,y:F.y,radius:5,fill:r,stroke:"#ffffff",strokeWidth:1.5,draggable:!0,onDragMove:Y=>{const I=Hl({x:Y.target.x(),y:Y.target.y()},o.w,o.h);g(R=>{const O=R&&R.itemId===e.id?R.points:t.points;return{itemId:e.id,points:O.map((K,W)=>W===U?I:K)}})},onDragEnd:Y=>{const I=Hl({x:Y.target.x(),y:Y.target.y()},o.w,o.h),R=t.points.map((O,K)=>K===U?I:O);g({itemId:e.id,points:R}),m(e.id,E(R))},onContextMenu:Y=>{Y.evt.preventDefault(),Y.cancelBubble=!0,$&&m(e.id,E(t.points.filter((I,R)=>R!==U)))}},`pt-${U}`)}),i&&!f&&B&&c.length>=2&&c.map((j,U)=>{const F=c[(U+1)%c.length],Y=ks({x:(j.x+F.x)/2,y:(j.y+F.y)/2},o.w,o.h);return u(Ji,{x:Y.x,y:Y.y,radius:4,fill:"#ffffff",stroke:r,strokeWidth:1.5,opacity:.6,onMouseEnter:I=>{const R=I.target;R.to({radius:6,opacity:1,duration:.1});const O=R.getStage();O&&(O.container().style.cursor="copy")},onMouseLeave:I=>{const R=I.target;R.to({radius:4,opacity:.6,duration:.1});const O=R.getStage();O&&(O.container().style.cursor=l?"crosshair":"default")},onClick:I=>{I.cancelBubble=!0,m(e.id,E(TN(t.points,U)))}},`mid-${U}`)})]})}var _v=Uy(NN),PN=110,DN="motion-zones",ko=0,_N=[1,2,3],To=1,us="rounded-md border border-border bg-surface px-2 py-1 text-[11px] font-medium text-foreground-subtle hover:bg-surface-hover disabled:opacity-40 transition-colors",Ao="rounded-md border border-primary/50 bg-primary/15 px-2.5 py-1 text-[11px] font-medium text-primary hover:bg-primary/25 disabled:opacity-40 transition-colors";function ih(e,t,r){const n=t*r,s=new Array(n);for(let i=0;i<n;i+=1)s[i]=e[i]===!0;return s}function ON(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function Br(e,t){return Math.ceil(e/t)}function ha(e,t,r){return Math.min(r-1,Math.floor((e+.5)/t*r))}function di(e,t,r,n){const s=Br(t,n),i=Br(r,n),a=new Array(s*i).fill(!1);for(let l=0;l<r;l+=1){const o=ha(l,r,i);for(let c=0;c<t;c+=1)e[l*t+c]===!0&&(a[o*s+ha(c,t,s)]=!0)}return a}function Co(e,t,r,n){const s=Br(t,n),i=Br(r,n),a=new Array(t*r).fill(!1);for(let l=0;l<r;l+=1){const o=ha(l,r,i);for(let c=0;c<t;c+=1)a[l*t+c]=e[o*s+ha(c,t,s)]===!0}return a}function FN({deviceId:e}){const t=Qt(Gt().trpcClient,e),[r,n]=_(null),[s,i]=_(!1),[a,l]=_(null),[o,c]=_(null),[d,h]=_(To),[f,p]=_(!1),[m,g]=_(!1),b=ne(!1);ae(()=>{if(!t)return;let I=!1;return b.current=!1,n(null),i(!1),l(null),c(null),h(To),g(!1),(async()=>{try{const R=await t.motionZones?.getOptions({});if(I)return;if(!R)throw new Error("device proxy not ready");if(n(R),b.current)return;const O=await t.motionZones?.getStatus({});if(I)return;if(!O)throw new Error("device proxy not ready");b.current=!0;const K=O.regions.find(J=>J.shape.kind==="grid"),W=ih(K?K.shape.cells:[],R.grid.width,R.grid.height);c(W),l(di(W,R.grid.width,R.grid.height,To))}catch(R){if(I)return;ta(R)?i(!0):console.error("Motion Zones load failed",R)}})(),()=>{I=!0}},[t]);const y=r?r.grid.width:0,S=r?r.grid.height:0,E=Br(y,d),k=Br(S,d),T=oe(()=>a&&r?Co(a,y,S,d):null,[a,r,y,S,d]),A=oe(()=>T!==null&&o!==null&&!ON(T,o),[T,o]),N=oe(()=>T?T.reduce((I,R)=>R?I+1:I,0):0,[T]),C=y*S,M=E*k,P=q(I=>{M>0&&l(new Array(M).fill(I))},[M]),D=q(()=>{l(I=>I&&I.map(R=>!R))},[]),$=q(()=>{o&&r&&l(di(o,y,S,d))},[o,r,y,S,d]),B=q(I=>{I===d||!r||l(R=>{if(!R)return h(I),R;const O=di(Co(R,y,S,d),y,S,I);return h(I),O})},[d,r,y,S]),j=oe(()=>r&&a?[{id:ko,shape:{kind:"grid",gridWidth:E,gridHeight:k,cells:[...a]}}]:[],[r,a,E,k]),U=q((I,R)=>{R.kind==="grid"&&l(R.cells)},[]),F=q(async()=>{if(!(!t||!a||!r)){p(!0);try{const I=Co(a,r.grid.width,r.grid.height,d),R={kind:"grid",gridWidth:r.grid.width,gridHeight:r.grid.height,cells:I};await t.motionZones?.setZone({patch:{regions:[{id:ko,enabled:!0,shape:R}]}});const O=await t.motionZones?.getStatus({});if(O){const K=O.regions.find(J=>J.shape.kind==="grid"),W=ih(K?K.shape.cells:[],r.grid.width,r.grid.height);c(W),l(di(W,r.grid.width,r.grid.height,d))}}catch(I){console.error("Motion Zones save failed",I)}finally{p(!1)}}},[t,a,r,d]);Rv(oe(()=>m&&!s&&r&&a?{id:DN,order:PN,node:u(_v,{transparent:!0,items:j,supportedShapes:["grid"],grid:{width:E,height:k},selectedId:ko,onSelect:()=>{},onShapeChange:U,onDrawComplete:()=>{},drawingKind:null})}:null,[m,s,r,a,j,U,E,k]));const Y=!s&&r!==null&&a!==null;return t?u(Hr,{title:"Motion Zones",icon:u(VS,{className:"h-3.5 w-3.5 text-foreground-subtle"}),children:u("div",{className:"flex flex-col gap-3",children:s?u("p",{className:`${kr} leading-relaxed`,children:"This camera doesn't expose an on-board motion zones grid."}):Y?v(Ie,{children:[v("p",{className:`${kr} leading-relaxed`,children:["Toggle ",u("strong",{className:"text-foreground",children:"Edit grid"})," to paint the region directly on the live frame, then ",u("strong",{className:"text-foreground",children:"Save"})," to push the mask to the camera. Pick a bigger ",u("strong",{className:"text-foreground",children:"Cell size"})," ","for quicker, broad-stroke painting — it's resampled to the camera's native"," ",r.grid.width,"×",r.grid.height," grid on save (×1 is the finest)."]}),v("div",{className:"flex items-center gap-2 flex-wrap",children:[u("button",{type:"button",onClick:()=>g(I=>!I),disabled:f,"aria-pressed":m,className:m?Ao:us,children:m?"Done editing":"Edit grid"}),u("button",{type:"button",onClick:()=>P(!0),disabled:f,className:us,children:"All on"}),u("button",{type:"button",onClick:()=>P(!1),disabled:f,className:us,children:"All off"}),u("button",{type:"button",onClick:D,disabled:f,className:us,children:"Invert"}),v("div",{className:"flex items-center gap-1 ml-1",role:"group","aria-label":"Cell size",children:[u("span",{className:`${kr} mr-0.5`,children:"Cell size"}),_N.map(I=>v("button",{type:"button",onClick:()=>B(I),disabled:f,"aria-pressed":d===I,title:I===1?`Camera grid ${y}×${S} (finest)`:`${Br(y,I)}×${Br(S,I)} painting grid · cells ×${I} bigger`,className:d===I?Ao:us,children:["×",I]},I))]}),v("span",{className:`${kr} ml-1 tabular-nums`,children:[N," / ",C," cells · ",r.grid.width,"×",r.grid.height,d!==1?` · paint ${E}×${k}`:""]}),u("span",{className:"flex-1"}),u("button",{type:"button",onClick:$,disabled:f||!A,className:"rounded-md border border-border bg-surface px-2 py-1 text-[11px] text-foreground-subtle hover:bg-surface-hover disabled:opacity-40 transition-colors",children:"Revert"}),u("button",{type:"button",onClick:()=>void F(),disabled:f||!A,className:Ao,children:f?"Saving…":"Save"})]})]}):u("p",{className:`${kr} leading-relaxed`,children:"Loading the camera's grid…"})})}):null}var $N=120,BN="privacy-mask",hi="rounded-md border border-border bg-surface px-2 py-1 text-[11px] font-medium text-foreground-subtle hover:bg-surface-hover disabled:opacity-40 transition-colors",ds="rounded-md border border-primary/50 bg-primary/15 px-2.5 py-1 text-[11px] font-medium text-primary hover:bg-primary/25 disabled:opacity-40 transition-colors";function ah(e){return e.kind==="rect"||e.kind==="polygon"?e:null}function UN(e){const t=new Set(e.map(n=>n.id));let r=0;for(;t.has(r);)r+=1;return r}function GN(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(JSON.stringify(e[r])!==JSON.stringify(t[r]))return!1;return!0}function HN({deviceId:e}){const t=Qt(Gt().trpcClient,e),[r,n]=_(null),[s,i]=_(!1),[a,l]=_(null),[o,c]=_(null),[d,h]=_(!1),[f,p]=_(!1),[m,g]=_(null),[b,y]=_(null),S=ne(!1);ae(()=>{if(!t)return;let Q=!1;return S.current=!1,n(null),i(!1),l(null),c(null),p(!1),g(null),y(null),(async()=>{try{const ee=await t.privacyMask?.getOptions({});if(Q)return;if(!ee)throw new Error("device proxy not ready");if(n(ee),S.current)return;const ie=await t.privacyMask?.getStatus({});if(Q)return;if(!ie)throw new Error("device proxy not ready");S.current=!0;const se={enabled:ie.enabled,regions:ie.regions};c(se),l(se)}catch(ee){if(Q)return;ta(ee)?i(!0):console.error("Privacy Mask load failed",ee)}})(),()=>{Q=!0}},[t]);const E=oe(()=>a!==null&&o!==null&&(a.enabled!==o.enabled||!GN(a.regions,o.regions)),[a,o]),k=a?a.regions.length:0,T=r?r.maxRegions:0,A=ne(0);ae(()=>{A.current=T},[T]);const N=T>0&&k>=T,C=q(()=>{l(Q=>Q&&{...Q,enabled:!Q.enabled})},[]),M=q(Q=>{g(typeof Q=="number"?Q:null)},[]),P=oe(()=>a?a.regions.map(Q=>({id:Q.id,shape:Q.shape,enabled:Q.enabled,label:`Zone ${String(Q.id)}`})):[],[a]),D=q((Q,ee)=>{const ie=ah(ee);ie&&l(se=>se&&{...se,regions:se.regions.map(be=>be.id===Q?{...be,shape:ie}:be)})},[]),$=q(Q=>{const ee=ah(Q);ee&&(y(null),l(ie=>{if(!ie)return ie;const se=A.current;if(se>0&&ie.regions.length>=se)return ie;const be=UN(ie.regions),ye={id:be,enabled:!0,shape:ee};return g(be),{...ie,regions:[...ie.regions,ye]}}))},[]),B=q(Q=>{p(!0),g(null),y(Q)},[]),j=q(Q=>{p(!0),y(null),g(Q)},[]),U=q(Q=>{g(ee=>ee===Q?null:ee),l(ee=>ee&&{...ee,regions:ee.regions.filter(ie=>ie.id!==Q)})},[]),F=q(()=>{y(null),g(null),o&&l({enabled:o.enabled,regions:o.regions})},[o]),Y=q(async()=>{if(!(!t||!a)){h(!0);try{await t.privacyMask?.setMask({patch:{enabled:a.enabled,regions:[...a.regions]}});const Q=await t.privacyMask?.getStatus({});if(Q){const ee={enabled:Q.enabled,regions:Q.regions};c(ee),l(ee)}}catch(Q){console.error("Privacy Mask save failed",Q)}finally{h(!1)}}},[t,a]),I=q(()=>{p(Q=>(Q&&(y(null),g(null)),!Q))},[]),R=r?.supportedShapes??[];Rv(oe(()=>f&&!s&&r&&a?{id:BN,order:$N,node:u(_v,{transparent:!0,items:P,supportedShapes:R,polygonVertices:r.polygonVertices,selectedId:m,onSelect:M,onShapeChange:D,onDrawComplete:$,drawingKind:b})}:null,[f,s,r,a,P,R,m,M,D,$,b]));const O=r?.supportedShapes.includes("rect")??!1,K=r?.supportedShapes.includes("polygon")??!1,W=r!==null&&(r.maxRegions<=0||r.supportedShapes.length===0),J=!s&&!W&&r!==null&&a!==null;return t?u(Hr,{title:"Privacy Mask",icon:u(Ca,{className:"h-3.5 w-3.5 text-foreground-subtle"}),children:u("div",{className:"flex flex-col gap-3",children:s||W?u("p",{className:`${kr} leading-relaxed`,children:"This camera doesn't support an on-board privacy mask."}):J?v(Ie,{children:[v("p",{className:`${kr} leading-relaxed`,children:["Toggle ",u("strong",{className:"text-foreground",children:"Edit mask"})," to draw blanked-out zones on the live frame, then ",u("strong",{className:"text-foreground",children:"Save"})," to push them to the camera. Drag a rectangle to move, its corner to resize; drag polygon vertices, click an edge midpoint to add one, or right-click a vertex to remove it."]}),v("div",{className:"flex items-center gap-2 flex-wrap",children:[u("button",{type:"button",onClick:I,disabled:d,"aria-pressed":f,className:f?ds:hi,children:f?"Done editing":"Edit mask"}),u("button",{type:"button",onClick:C,disabled:d,"aria-pressed":a.enabled,className:a.enabled?ds:hi,children:a.enabled?"Mask on":"Mask off"}),O&&u("button",{type:"button",onClick:()=>B("rect"),disabled:d||N,"aria-pressed":b==="rect",className:b==="rect"?ds:hi,title:N?"Maximum zones reached":"Add a rectangle zone",children:"+ Rect"}),K&&u("button",{type:"button",onClick:()=>B("polygon"),disabled:d||N,"aria-pressed":b==="polygon",className:b==="polygon"?ds:hi,title:N?"Maximum zones reached":"Add a polygon zone",children:"+ Polygon"}),v("span",{className:`${kr} ml-1 tabular-nums`,children:[k," / ",T," zones"]}),u("span",{className:"flex-1"}),u("button",{type:"button",onClick:F,disabled:d||!E,className:"rounded-md border border-border bg-surface px-2 py-1 text-[11px] text-foreground-subtle hover:bg-surface-hover disabled:opacity-40 transition-colors",children:"Revert"}),u("button",{type:"button",onClick:()=>void Y(),disabled:d||!E,className:ds,children:d?"Saving…":"Save"})]}),k>0?u("div",{className:"flex flex-col gap-1",children:a.regions.map(Q=>{const ee=m===Q.id,ie=Q.shape.kind==="polygon"?WS:Cr;return v("div",{className:`flex items-center gap-2 rounded-md border px-2 py-1 transition-colors ${ee?"border-primary/50 bg-primary/10":"border-border bg-surface"}`,children:[v("button",{type:"button",onClick:()=>j(Q.id),disabled:d,className:"flex flex-1 items-center gap-2 text-left text-[11px] font-medium text-foreground-subtle hover:text-foreground disabled:opacity-40 transition-colors",children:[u(ie,{className:"h-3.5 w-3.5 shrink-0"}),v("span",{children:["Zone ",Q.id]}),u("span",{className:"text-foreground-faint capitalize",children:Q.shape.kind})]}),u("button",{type:"button",onClick:()=>U(Q.id),disabled:d,"aria-label":`Delete zone ${String(Q.id)}`,title:"Delete zone",className:"inline-flex h-6 w-6 items-center justify-center rounded border border-border bg-surface text-foreground-subtle hover:border-red-400/40 hover:bg-red-500/10 hover:text-red-400 disabled:opacity-40 transition-colors",children:u(zt,{className:"h-3.5 w-3.5"})})]},Q.id)})}):null]}):u("p",{className:`${kr} leading-relaxed`,children:"Loading the camera's privacy mask…"})})}):null}function VN(){return{schedule:{kind:"always"},mode:"continuous",preBufferSec:0,postBufferSec:0,resetTimeoutOnNewEvent:!0}}function jN(e){return e==="onMotion"||e==="onAudioThreshold"}function Jr(e,t,r){return e.map((n,s)=>s===t?{...n,...r}:n)}function KN(e,t){return e.filter((r,n)=>n!==t)}var zN=[{d:0,label:"S"},{d:1,label:"M"},{d:2,label:"T"},{d:3,label:"W"},{d:4,label:"T"},{d:5,label:"F"},{d:6,label:"S"}];function WN(e){return e==="onMotion"||e==="onAudioThreshold"?e:"continuous"}function QN(e,t){return t==="onAudioThreshold"?{mode:t,thresholdDbfs:e.thresholdDbfs??-30}:t==="onMotion"?{mode:t,thresholdDbfs:void 0}:{mode:t,preBufferSec:0,postBufferSec:0,thresholdDbfs:void 0}}function qN({schedule:e,onChange:t}){const r=n=>{const s=e.days??[0,1,2,3,4,5,6],i=s.includes(n)?s.filter(a=>a!==n):[...s,n].sort((a,l)=>a-l);t({...e,days:i})};return v("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[u("input",{type:"time",value:e.start,onChange:n=>t({...e,start:n.target.value}),className:"rounded-md border border-border bg-background px-2 py-1 text-xs"}),u("span",{children:"–"}),u("input",{type:"time",value:e.end,onChange:n=>t({...e,end:n.target.value}),className:"rounded-md border border-border bg-background px-2 py-1 text-xs"}),u("div",{className:"flex gap-1",children:zN.map(({d:n,label:s})=>u("button",{type:"button",onClick:()=>r(n),className:`h-6 w-6 rounded text-[10px] ${!e.days||e.days.includes(n)?"bg-primary text-primary-foreground":"bg-surface-hover text-foreground-subtle"}`,children:s},n))})]})}function YN({rules:e,onChange:t}){return v("div",{className:"space-y-2",children:[e.length===0?u("p",{className:"text-xs text-foreground-subtle",children:"No rules — recording is continuous (always) when enabled."}):null,e.map((r,n)=>v("div",{className:"space-y-2 rounded-lg border border-border bg-surface p-3",children:[v("div",{className:"flex items-center justify-between gap-2",children:[v("select",{className:"rounded-md border border-border bg-background px-2 py-1 text-xs",value:r.schedule.kind,onChange:s=>{t(Jr(e,n,{schedule:s.target.value==="timeOfDay"?{kind:"timeOfDay",start:"00:00",end:"23:59"}:{kind:"always"}}))},children:[u("option",{value:"always",children:"Always"}),u("option",{value:"timeOfDay",children:"Time of day"})]}),u("button",{type:"button",onClick:()=>t(KN(e,n)),className:"text-foreground-subtle hover:text-red-500",children:u(bt,{className:"h-4 w-4"})})]}),r.schedule.kind==="timeOfDay"?u(qN,{schedule:r.schedule,onChange:s=>t(Jr(e,n,{schedule:s}))}):null,v("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[v("select",{className:"rounded-md border border-border bg-background px-2 py-1 text-xs",value:r.mode,onChange:s=>t(Jr(e,n,QN(r,WN(s.target.value)))),children:[u("option",{value:"continuous",children:"Continuous"}),u("option",{value:"onMotion",children:"On motion"}),u("option",{value:"onAudioThreshold",children:"On audio"})]}),jN(r.mode)?v(Ie,{children:[v("label",{className:"flex items-center gap-1",children:["pre",u("input",{type:"number",min:0,value:r.preBufferSec,onChange:s=>t(Jr(e,n,{preBufferSec:Number(s.target.value)})),className:"w-14 rounded-md border border-border bg-background px-1 py-1 text-xs"}),"s"]}),v("label",{className:"flex items-center gap-1",children:["post",u("input",{type:"number",min:0,value:r.postBufferSec,onChange:s=>t(Jr(e,n,{postBufferSec:Number(s.target.value)})),className:"w-14 rounded-md border border-border bg-background px-1 py-1 text-xs"}),"s"]}),v("label",{className:"flex items-center gap-1",children:[u("input",{type:"checkbox",checked:r.resetTimeoutOnNewEvent,onChange:s=>t(Jr(e,n,{resetTimeoutOnNewEvent:s.target.checked}))}),"reset"]})]}):null,r.mode==="onAudioThreshold"?v("label",{className:"flex items-center gap-1",children:["thr",u("input",{type:"number",value:r.thresholdDbfs??-30,onChange:s=>t(Jr(e,n,{thresholdDbfs:Number(s.target.value)})),className:"w-16 rounded-md border border-border bg-background px-1 py-1 text-xs"}),"dBFS"]}):null]})]},n)),v("button",{type:"button",onClick:()=>t([...e,VN()]),className:"flex items-center gap-1 rounded-md border border-dashed border-border px-3 py-1.5 text-xs text-foreground-subtle hover:border-primary hover:text-foreground",children:[u(gn,{className:"h-3.5 w-3.5"})," Add rule"]})]})}var XN=["high","mid","low"];function ZN({initial:e,saving:t,onSave:r}){const[n,s]=_(e),i=n.retention??{},a=o=>s({...n,retention:{...i,...o}}),l=o=>o===""?void 0:Number(o);return v("div",{className:"space-y-4",children:[v("label",{className:"flex items-center gap-2 text-xs",children:[u("input",{type:"checkbox",checked:n.enabled,onChange:o=>s({...n,enabled:o.target.checked})}),"Record this camera"]}),v("div",{className:"flex flex-wrap items-center gap-4 text-xs",children:[v("div",{className:"flex items-center gap-2",children:[u("span",{className:"text-foreground-subtle",children:"Profiles:"}),XN.map(o=>u("button",{type:"button",onClick:()=>{const c=n.profiles??[],d=c.includes(o)?c.filter(h=>h!==o):[...c,o];s({...n,profiles:d.length?d:void 0})},className:`rounded px-2 py-1 ${(n.profiles??[]).includes(o)?"bg-primary text-primary-foreground":"bg-surface-hover text-foreground-subtle"}`,children:o},o))]}),v("label",{className:"flex items-center gap-1",children:["Segment",u("input",{type:"number",min:1,value:n.segmentSeconds??"",placeholder:"default",onChange:o=>s({...n,segmentSeconds:l(o.target.value)}),className:"w-16 rounded-md border border-border bg-background px-1 py-1 text-xs"}),"s"]})]}),v("div",{children:[u("div",{className:"mb-1.5 text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle",children:"Rules"}),u(YN,{rules:n.rules??[],onChange:o=>s({...n,rules:o})})]}),v("div",{children:[u("div",{className:"mb-1.5 text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle",children:"Retention (empty = node default)"}),v("div",{className:"flex flex-wrap items-center gap-3 text-xs",children:[v("label",{className:"flex items-center gap-1",children:["Max age",u("input",{type:"number",min:0,value:i.maxAgeDays??"",placeholder:"14",onChange:o=>a({maxAgeDays:l(o.target.value)}),className:"w-16 rounded-md border border-border bg-background px-1 py-1 text-xs"}),"days"]}),v("label",{className:"flex items-center gap-1",children:["Max size",u("input",{type:"number",min:0,value:i.maxSizeGb??"",placeholder:"∞",onChange:o=>a({maxSizeGb:l(o.target.value)}),className:"w-16 rounded-md border border-border bg-background px-1 py-1 text-xs"}),"GB"]})]})]}),u("div",{className:"flex justify-end",children:v("button",{type:"button",disabled:t,onClick:()=>r(n),className:"flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground disabled:opacity-60",children:[t?u(vt,{className:"h-3.5 w-3.5 animate-spin"}):u(Im,{className:"h-3.5 w-3.5"})," Save"]})})]})}var Ov=Nr("camstack:vod-playback",{request:null,play:()=>{},clear:()=>{}});function bj({children:e}){const[t,r]=_(null),n=oe(()=>({request:t,play:s=>r(s),clear:()=>r(null)}),[t]);return u(Ov.Provider,{value:n,children:e})}function JN(){return ct(Ov)}function eL(e){const t=e.filter(n=>n.endMs>n.startMs).map(n=>({startMs:n.startMs,endMs:n.endMs})).sort((n,s)=>n.startMs-s.startMs),r=[];for(const n of t){const s=r[r.length-1];s&&n.startMs<=s.endMs?n.endMs>s.endMs&&(r[r.length-1]={startMs:s.startMs,endMs:n.endMs}):r.push(n)}return r}function tL(e){if(!Number.isFinite(e)||e<0)return"—";if(e<1024)return`${Math.round(e)} B`;const t=["KB","MB","GB","TB","PB"];let r=e/1024,n="KB";for(const s of t){if(n=s,r<1024)break;r/=1024}return`${r>=100?Math.round(r).toString():r.toFixed(1)} ${n}`}var rL=["object","motion","audio"];function nL(e,t,r){const n=[];for(const s of e){const i={motion:s.motion,object:s.object,audio:s.audio},a=i.motion+i.object+i.audio;if(a===0)continue;const l=Math.floor((s.bucketStart-t)/r);let o=null,c=-1;for(const d of rL)i[d]>c&&(c=i[d],o=d);n.push({index:l,startMs:s.bucketStart,endMs:s.bucketStart+r,counts:i,total:a,dominant:o})}return n.sort((s,i)=>s.index-i.index)}function sL(e,t){return e<t.startMs?t.startMs-e:e>t.endMs?e-t.endMs:0}function iL(e,t){if(t.length===0)return null;const r=t.find(i=>e>=i.startMs&&e<=i.endMs);if(r)return{fromMs:e,toMs:r.endMs};let n=null,s=1/0;for(const i of t){const a=sL(e,i);a<s&&(s=a,n=i)}return n?{fromMs:n.startMs,toMs:n.endMs}:null}function cn(e,t,r){const n=r-t;if(n<=0)return 0;const s=(e-t)/n*100;return s<0?0:s>100?100:s}function No(e,t){const r=new Date(e.getFullYear(),e.getMonth(),e.getDate(),0,0,0,0).getTime(),n=new Date(e.getFullYear(),e.getMonth(),e.getDate()+1,0,0,0,0).getTime();return{fromMs:r,toMs:Math.max(r,Math.min(n,t))}}var wn=[24*36e5,12*36e5,6*36e5,36e5,15*6e4];function oh(e,t,r,n){if(r>=t.toMs-t.fromMs)return t;let s=n-r/2,i=n+r/2;return s<t.fromMs&&(s=t.fromMs,i=s+r),i>t.toMs&&(i=t.toMs,s=i-r),{fromMs:s,toMs:i}}function aL(e,t,r){const n=e.toMs-e.fromMs;let s=e.fromMs+r,i=e.toMs+r;return s<t.fromMs&&(s=t.fromMs,i=s+n),i>t.toMs&&(i=t.toMs,s=i-n),{fromMs:s,toMs:i}}var Lo=[15*6e4,5*6e4,6e4,3e4,15e3,5e3];function oL(e){const t=e/100;for(const r of Lo)if(r<=t)return r;return Lo[Lo.length-1]??5e3}function lL(e,t,r){const n=[];for(let s=0;s<r;s++){const i=e+s/(r-1)*(t-e),a=cn(i,e,t),l=new Date(i).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"});n.push({pct:a,label:l})}return n}function cL({windowFrom:e,windowTo:t,spans:r,playheadMs:n,onSeek:s}){const[i,a]=_(null),l=f=>{const p=f.currentTarget.getBoundingClientRect();if(p.width<=0)return null;const m=(f.clientX-p.left)/p.width;return e+Math.min(1,Math.max(0,m))*(t-e)},o=f=>{const p=l(f);p!==null&&s(p)},c=f=>{const p=l(f);if(p===null)return;const m=f.currentTarget.getBoundingClientRect();a({xPct:m.width>0?(f.clientX-m.left)/m.width*100:0,ms:p})},d=()=>{a(null)},h=i!==null?new Date(i.ms).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"}):null;return v("div",{className:"relative",children:[v("div",{"data-testid":"coverage-track",onClick:o,onMouseMove:c,onMouseLeave:d,className:"relative h-5 cursor-pointer overflow-hidden rounded bg-background/40",role:"group","aria-label":"Recorded coverage timeline",children:[r.map(f=>{const p=cn(f.startMs,e,t),m=cn(f.endMs,e,t);return u("div",{"data-testid":"coverage-fascia",className:"absolute inset-y-0 bg-gradient-to-b from-primary to-primary/80",style:{left:`${p}%`,width:`${Math.max(.5,m-p)}%`}},`${f.startMs}-${f.endMs}`)}),n!==null?u("div",{"data-testid":"coverage-playhead",className:"absolute inset-y-[-2px] w-0.5 bg-amber-500 shadow-[0_0_6px] shadow-amber-500",style:{left:`${cn(n,e,t)}%`}}):null]}),i!==null&&h!==null?u("div",{"data-testid":"coverage-hover-tooltip",className:"pointer-events-none absolute top-full z-10 mt-0.5 -translate-x-1/2 rounded bg-popover px-1.5 py-0.5 text-[9px] text-popover-foreground shadow",style:{left:`${i.xPct}%`},children:h}):null]})}var uL={motion:"bg-emerald-500",object:"bg-violet-500",audio:"bg-orange-500"};function dL({windowFrom:e,windowTo:t,buckets:r,selectedIndex:n,onSelectBucket:s}){const i=r.reduce((o,c)=>Math.max(o,c.total),0),a=r[0],l=a?cn(a.endMs,e,t)-cn(a.startMs,e,t):0;return u("div",{className:"relative h-6 rounded bg-background/40",children:r.map(o=>{if(o.total===0||o.dominant===null)return null;const c=i>0?Math.max(15,o.total/i*100):0,d=cn(o.startMs,e,t),h=o.index===n;return u("button",{type:"button","data-testid":"heatmap-bar",title:`${new Date(o.startMs).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})} · motion ${o.counts.motion} · object ${o.counts.object}`,onClick:()=>s(o.index),className:`absolute bottom-0 rounded-t-sm transition-opacity ${uL[o.dominant]} ${h?"opacity-100 ring-1 ring-amber-400":"opacity-80 hover:opacity-100"}`,style:{left:`${d}%`,width:`${Math.max(.6,l)}%`,height:`${c}%`}},o.index)})})}function hL({mediaUrl:e,kind:t}){const[r,n]=_(!1);return e&&!r?u("img",{src:e,alt:"",className:"h-full w-full object-cover",loading:"lazy",onError:()=>n(!0)}):u("div",{className:"flex h-full w-full items-center justify-center text-white/30",children:u(Fv,{kind:t,large:!0})})}function Fv({kind:e,large:t=!1}){const r=t?"h-7 w-7":"h-3.5 w-3.5 text-foreground-subtle";return e==="object"?u(pl,{className:r}):e==="audio"?u(Oc,{className:r}):u(ur,{className:r})}var fL=["motion","object","audio"];function pL(e){return new Date(e).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}function mL({clips:e,loading:t,busyKey:r,onPlay:n,enabledKinds:s,onToggleKind:i,hasMore:a,onLoadMore:l}){const o=u("div",{className:"flex items-center gap-3 pb-1",children:fL.map(c=>v("label",{className:"flex cursor-pointer items-center gap-1 text-xs text-foreground-subtle select-none",children:[u("input",{type:"checkbox",checked:s.has(c),onChange:()=>i(c),className:"h-3.5 w-3.5 accent-primary"}),c]},c))});return t&&e.length===0?v("div",{className:"space-y-2",children:[o,u("div",{className:"px-1 py-2 text-xs text-foreground-subtle",children:"Loading events…"})]}):e.length===0?v("div",{className:"space-y-2",children:[o,u("div",{className:"px-1 py-2 text-xs text-foreground-subtle",children:"No events in this window."})]}):v("div",{className:"space-y-2",children:[o,t?u("div",{className:"px-1 text-[10px] text-foreground-subtle",children:"Loading events…"}):null,u("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-3",children:e.map(c=>{const d=`event:${c.id}`;return v("button",{type:"button",disabled:r!==null,onClick:()=>n(c),className:"group overflow-hidden rounded-lg border border-border text-left transition-colors hover:border-primary disabled:opacity-60",children:[v("div",{className:"relative aspect-video bg-black/90",children:[u(hL,{mediaUrl:c.mediaUrl,kind:c.kind}),u("div",{className:"absolute inset-0 flex items-center justify-center bg-black/0 transition-colors group-hover:bg-black/30",children:r===d?u(vt,{className:"h-6 w-6 animate-spin text-white"}):u(Ar,{className:"h-6 w-6 text-white opacity-0 transition-opacity group-hover:opacity-100"})})]}),v("div",{className:"flex items-center gap-1.5 bg-surface px-2 py-1.5",children:[u(Fv,{kind:c.kind}),v("div",{className:"min-w-0 flex-1",children:[u("div",{className:"truncate text-xs font-medium text-foreground",children:c.label}),u("div",{className:"text-[10px] text-foreground-subtle",children:pL(c.timestamp)})]})]})]},d)})}),e.length>0?v("div",{className:"flex items-center gap-2 pt-1 text-[11px] text-foreground-subtle",children:[v("span",{children:["(",e.length," shown)"]}),a?u("button",{type:"button",onClick:l,className:"rounded px-2 py-0.5 text-[11px] font-medium text-primary hover:underline",children:"Load more"}):null]}):null]})}function lh(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}function gL(e){const t=e.split("-"),r=t[0]!==void 0?parseInt(t[0],10):NaN,n=t[1]!==void 0?parseInt(t[1],10):NaN,s=t[2]!==void 0?parseInt(t[2],10):NaN;return isNaN(r)||isNaN(n)||isNaN(s)?null:new Date(r,n-1,s)}function vL({day:e,onDayChange:t,view:r,dayBounds:n,onViewChange:s}){const i=p=>{const m=gL(p.target.value);m!==null&&t(m)},a=r.toMs-r.fromMs,l=(()=>{let p=0,m=1/0;for(let g=0;g<wn.length;g++){const b=wn[g];if(b===void 0)continue;const y=Math.abs(b-a);y<m&&(m=y,p=g)}return p})(),o=(r.fromMs+r.toMs)/2,c=()=>{const p=wn[Math.min(l+1,wn.length-1)];p!==void 0&&s(oh(r,n,p,o))},d=()=>{const p=wn[Math.max(l-1,0)];p!==void 0&&s(oh(r,n,p,o))},h=l<wn.length-1,f=l>0;return v("div",{className:"flex items-center gap-2",children:[u("input",{type:"date",value:lh(e),max:lh(new Date),onChange:i,className:"rounded border border-border bg-background px-2 py-0.5 text-[11px] text-foreground focus:outline-none focus:ring-1 focus:ring-primary","aria-label":"Select recording day"}),v("div",{className:"ml-auto flex items-center gap-1",children:[u("button",{type:"button",onClick:d,disabled:!f,title:"Zoom out","aria-label":"Zoom out",className:"rounded p-1 text-foreground-subtle transition-colors hover:bg-background/60 hover:text-foreground disabled:cursor-not-allowed disabled:opacity-40",children:u(Fm,{size:13})}),u("button",{type:"button",onClick:c,disabled:!h,title:"Zoom in","aria-label":"Zoom in",className:"rounded p-1 text-foreground-subtle transition-colors hover:bg-background/60 hover:text-foreground disabled:cursor-not-allowed disabled:opacity-40",children:u(Om,{size:13})})]}),u("span",{className:"text-[9px] text-foreground-subtle",children:bL(a)})]})}function bL(e){const t=e/36e5;if(t>=24)return"24h";if(t>=1)return`${Math.round(t)}h`;const r=e/6e4;return`${Math.round(r)}m`}var yL=["motion","object","audio"],Io=60,xL=18e3/100,SL=5e3,EL=1e4,wL=[];function kL({deviceId:e}){const t=Gt(),r=JN(),[n,s]=_(null),[i,a]=_(null),[l,o]=_(null),[c,d]=_(null),[h,f]=_(()=>new Set(yL)),p=q(Z=>{f(ce=>{const Ae=new Set(ce);return Ae.has(Z)?Ae.delete(Z):Ae.add(Z),Ae})},[]),[m,g]=_(Io),b=q(()=>{g(Z=>Z+Io)},[]);ae(()=>{g(Io)},[n]);const[y,S]=_(()=>new Date),[E,k]=_(()=>No(new Date,Date.now())),T=oe(()=>No(y,Date.now()),[y]),A=q(Z=>{S(Z),k(No(Z,Date.now())),s(null)},[]),N=q(Z=>{k(Z),s(null)},[]),C=ne(null),M=q(Z=>{const ce=Math.abs(Z.deltaX)>Math.abs(Z.deltaY)?Z.deltaX:Z.shiftKey?Z.deltaY:0;if(ce===0)return;Z.preventDefault();const Ae=ce*xL;k(Re=>aL(Re,T,Ae))},[T]),P=oL(E.toMs-E.fromMs),D=Eg({deviceId:e,fromMs:E.fromMs,toMs:E.toMs}),$=pk({deviceId:e,since:E.fromMs,until:E.toMs,bucketMs:P}),B=D.data?.ranges??wL,j=oe(()=>eL(B),[B]),U=oe(()=>nL($.data??[],E.fromMs,P),[$.data,E.fromMs,P]),F=n!==null?U.find(Z=>Z.index===n):void 0,Y=F!==void 0,I=F?.startMs??0,R=F?Math.min(F.endMs,E.toMs):0,O=hk({deviceId:e,since:I,until:R,limit:m,projection:"slim"},{enabled:Y&&h.has("object")}),K=dk({deviceId:e,since:I,until:R,limit:m,projection:"slim"},{enabled:Y&&h.has("motion")}),W=fk({deviceId:e,since:I,until:R,limit:m,projection:"slim"},{enabled:Y&&h.has("audio")}),J=oe(()=>{if(!F)return[];const Z=[];if(h.has("object"))for(const ce of O.data??[])Z.push({id:ce.id,timestamp:ce.timestamp,kind:"object",label:ce.label??ce.className,mediaUrl:ce.mediaUrl});if(h.has("motion"))for(const ce of K.data??[])Z.push({id:ce.id,timestamp:ce.timestamp,kind:"motion",label:`Motion (${ce.regionCount})`,mediaUrl:ce.mediaUrl});if(h.has("audio"))for(const ce of W.data??[])Z.push({id:ce.id,timestamp:ce.timestamp,kind:"audio",label:ce.classification?.className??"Audio",mediaUrl:ce.mediaUrl});return Z.sort((ce,Ae)=>Ae.timestamp-ce.timestamp)},[F,h,O.data,K.data,W.data]),Q=oe(()=>!!(h.has("object")&&(O.data?.length??0)===m||h.has("motion")&&(K.data?.length??0)===m||h.has("audio")&&(W.data?.length??0)===m),[h,O.data,K.data,W.data,m]),ee=q(async(Z,ce,Ae,Re,He)=>{o(Z),d(null);try{const ut=await t.trpcClient.recording.getPlaybackManifest.query({deviceId:e,fromMs:ce,toMs:Ae});ut?.playbackUrl?(a(He),r.play({url:ut.playbackUrl,label:Re})):d("No playable footage for this selection.")}catch{d("Could not load this recording.")}finally{o(null)}},[t,e,r]),ie=q(Z=>{const ce=iL(Z,j);if(!ce)return;const Ae=`Recording · ${new Date(ce.fromMs).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`;ee(`seek:${ce.fromMs}`,ce.fromMs,ce.toMs,Ae,ce.fromMs)},[j,ee]),se=q(Z=>{const ce=`${Z.label} · ${new Date(Z.timestamp).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}`;ee(`event:${Z.id}`,Z.timestamp-SL,Z.timestamp+EL,ce,Z.timestamp)},[ee]),be=q(Z=>{s(ce=>ce===Z?null:Z)},[]),ye=D.isLoading,ue=$.isLoading,we=(O.isLoading||K.isLoading||W.isLoading)&&Y,le=oe(()=>lL(E.fromMs,E.toMs,5),[E.fromMs,E.toMs]);return v("div",{className:"space-y-3",children:[D.isError?u(oa,{variant:"warning",message:"Recorder unavailable — the recording service may not be running for this node."}):null,c?u(oa,{variant:"warning",message:c}):null,u(vL,{day:y,onDayChange:A,view:E,dayBounds:T,onViewChange:N}),v("div",{ref:C,onWheel:M,className:"space-y-1",children:[v("div",{className:"space-y-1",children:[u("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle",children:"Recorded"}),ye?u("div",{className:"h-5 animate-pulse rounded bg-background/40"}):j.length===0?u(ag,{icon:xm,title:"No recordings for this window."}):u(cL,{windowFrom:E.fromMs,windowTo:E.toMs,spans:j,playheadMs:i,onSeek:ie})]}),v("div",{className:"space-y-1",children:[u("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle",children:"Events · density"}),ue?u("div",{className:"h-6 animate-pulse rounded bg-background/40"}):u(dL,{windowFrom:E.fromMs,windowTo:E.toMs,buckets:U,selectedIndex:n,onSelectBucket:be})]}),u("div",{className:"relative h-3",children:le.map(Z=>u("span",{className:"absolute -translate-x-1/2 text-[9px] text-foreground-subtle",style:{left:`${Z.pct}%`},children:Z.label},Z.pct))})]}),F?u(mL,{clips:J,loading:we,busyKey:l,onPlay:se,enabledKinds:h,onToggleKind:p,hasMore:Q,onLoadMore:b}):u("p",{className:"text-[11px] text-foreground-subtle",children:"Click the coverage bar to play from any point, or a density bar to browse that window's events."})]})}var TL=1440*60*1e3;function AL(e){const t=Math.round(e/1e3),r=Math.floor(t/3600),n=Math.floor(t%3600/60),s=t%60;return r>0?`${r}h ${n}m`:n>0?`${n}m ${s}s`:`${s}s`}function CL({deviceId:e}){const t=ts(),r=Sk({deviceId:e}),n=bk({deviceId:e}),s=yk(),i=xk(),a=y=>{s.mutate({deviceId:e,config:y},{onSuccess:()=>{n.refetch(),r.refetch()}})},l=q(()=>{i.mutate({deviceId:e},{onSuccess:()=>{t.invalidateQueries({queryKey:[["recording"]]})}})},[e,t,i]),o=oe(()=>Date.now(),[]),c=Eg({deviceId:e,fromMs:o-TL,toMs:o}),d=r.data?Zy.safeParse(r.data):null,h=d?.success?d.data:null,f=n.data?Jy.safeParse(n.data):null,p=f?.success?f.data:null,m=c.data?.ranges??[],g=m.reduce((y,S)=>y+Math.max(0,S.endMs-S.startMs),0),b=h?.enabled===!0&&h.activeMode==="continuous";return v("div",{className:"space-y-3",children:[u(Hr,{title:"Settings",icon:u(gE,{className:"h-3.5 w-3.5 text-foreground-subtle"}),collapsible:!0,defaultOpen:!1,children:p?u(ZN,{initial:p,saving:s.isPending,onSave:a},JSON.stringify(p)):u("div",{className:"px-1 py-2 text-xs text-foreground-subtle",children:"Loading settings…"})}),u(Hr,{title:"Recording",icon:u(xm,{className:"h-3.5 w-3.5 text-foreground-subtle"}),headerRight:v("span",{className:"flex items-center gap-2",children:[b?v("span",{className:"flex items-center gap-1.5 text-[10px] text-emerald-500",children:[u(Lm,{className:"h-3 w-3"})," Recording"]}):null,u("button",{type:"button",onClick:l,disabled:i.isPending,"aria-label":"Rescan storage",className:"flex items-center rounded p-0.5 text-foreground-subtle transition-colors hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",children:u(vn,{className:`h-3.5 w-3.5 ${i.isPending?"animate-spin":""}`})})]}),children:v("div",{className:"space-y-3",children:[v("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-3",children:[u(So,{label:"Status",icon:u(mm,{className:`h-3.5 w-3.5 ${b?"text-emerald-500":""}`}),footer:h?.nodeId?`node: ${h.nodeId}`:void 0,children:r.isLoading?"…":b?"Recording (continuous)":"Idle"}),u(So,{label:"Storage",icon:u(KS,{className:"h-3.5 w-3.5"}),children:h?tL(h.storageBytes):"—"}),u(So,{label:"Recorded (24h)",icon:u(ml,{className:"h-3.5 w-3.5"}),footer:`${m.length} segment range${m.length===1?"":"s"}`,children:c.isLoading?"…":AL(g)})]}),r.isError?u(oa,{variant:"warning",message:"Recorder unavailable — the recording service may not be running for this node."}):null,u(kL,{deviceId:e}),u("p",{className:"text-[11px] text-foreground-subtle",children:"Recordings play in the main player above — switch back to live from there."})]})})]})}var NL={"host/motion-zones-grid":FN,"host/privacy-mask-grid":HN,"host/ptz-panel":pN,"host/consumables-panel":yN,"host/ptz-autotrack":SN,"host/recording-panel":CL};function LL(e){const{widgetId:t,deviceId:r}=e,n=NL[t];return n!==void 0?r===void 0?u(Ts,{widgetId:t,reason:"missing-device-context"}):u(n,{deviceId:r}):u(IL,{...e})}function IL(e){const{widgetId:t}=e,r=uN(t);return r===void 0?u(Ts,{widgetId:t,reason:"unknown"}):u(RL,{...e,metadata:r})}function RL(e){const{widgetId:t,host:r="device-tab",config:n,deviceId:s,integrationId:i,instanceId:a,size:l,columns:o,rows:c,metadata:d}=e,h=dN(d.remote,d.bundleUrl),f=oe(()=>a??t,[a,t]);return h===null?u(ML,{}):h===void 0?u(Ts,{widgetId:t,reason:"missing-export"}):d.requires.deviceContext&&s===void 0?u(Ts,{widgetId:t,reason:"missing-device-context"}):d.requires.integrationContext&&i===void 0?u(Ts,{widgetId:t,reason:"missing-integration-context"}):u(h,{instanceId:f,host:r,config:n,deviceId:s,integrationId:i,size:l,columns:o,rows:c})}function ML(){return v("div",{className:"rounded-lg border border-border bg-surface/40 p-4 animate-pulse",children:[u("div",{className:"h-3 w-24 bg-foreground-subtle/20 rounded mb-2"}),u("div",{className:"h-2 w-full bg-foreground-subtle/10 rounded mb-1"}),u("div",{className:"h-2 w-3/4 bg-foreground-subtle/10 rounded"})]})}function Ts({widgetId:e,reason:t}){return u("div",{className:"rounded-lg border border-warning/30 bg-warning/10 px-3 py-2 text-xs text-warning",children:t==="unknown"?`Widget "${e}" not registered`:t==="missing-export"?`Widget "${e}" bundle does not export this stableId`:t==="missing-device-context"?`Widget "${e}" requires a deviceId`:`Widget "${e}" requires an integrationId`})}var PL=Object.defineProperty,fa=Object.getOwnPropertySymbols,$v=Object.prototype.hasOwnProperty,Bv=Object.prototype.propertyIsEnumerable,ch=(e,t,r)=>t in e?PL(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Vl=(e,t)=>{for(var r in t||(t={}))$v.call(t,r)&&ch(e,r,t[r]);if(fa)for(var r of fa(t))Bv.call(t,r)&&ch(e,r,t[r]);return e},jl=(e,t)=>{var r={};for(var n in e)$v.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&fa)for(var n of fa(e))t.indexOf(n)<0&&Bv.call(e,n)&&(r[n]=e[n]);return r};/**
77
+ * @license QR Code generator library (TypeScript)
78
+ * Copyright (c) Project Nayuki.
79
+ * SPDX-License-Identifier: MIT
80
+ */var hn;(e=>{const t=class $e{constructor(o,c,d,h){if(this.version=o,this.errorCorrectionLevel=c,this.modules=[],this.isFunction=[],o<$e.MIN_VERSION||o>$e.MAX_VERSION)throw new RangeError("Version value out of range");if(h<-1||h>7)throw new RangeError("Mask value out of range");this.size=o*4+17;let f=[];for(let m=0;m<this.size;m++)f.push(!1);for(let m=0;m<this.size;m++)this.modules.push(f.slice()),this.isFunction.push(f.slice());this.drawFunctionPatterns();const p=this.addEccAndInterleave(d);if(this.drawCodewords(p),h==-1){let m=1e9;for(let g=0;g<8;g++){this.applyMask(g),this.drawFormatBits(g);const b=this.getPenaltyScore();b<m&&(h=g,m=b),this.applyMask(g)}}s(0<=h&&h<=7),this.mask=h,this.applyMask(h),this.drawFormatBits(h),this.isFunction=[]}static encodeText(o,c){const d=e.QrSegment.makeSegments(o);return $e.encodeSegments(d,c)}static encodeBinary(o,c){const d=e.QrSegment.makeBytes(o);return $e.encodeSegments([d],c)}static encodeSegments(o,c,d=1,h=40,f=-1,p=!0){if(!($e.MIN_VERSION<=d&&d<=h&&h<=$e.MAX_VERSION)||f<-1||f>7)throw new RangeError("Invalid value");let m,g;for(m=d;;m++){const E=$e.getNumDataCodewords(m,c)*8,k=a.getTotalBits(o,m);if(k<=E){g=k;break}if(m>=h)throw new RangeError("Data too long")}for(const E of[$e.Ecc.MEDIUM,$e.Ecc.QUARTILE,$e.Ecc.HIGH])p&&g<=$e.getNumDataCodewords(m,E)*8&&(c=E);let b=[];for(const E of o){r(E.mode.modeBits,4,b),r(E.numChars,E.mode.numCharCountBits(m),b);for(const k of E.getData())b.push(k)}s(b.length==g);const y=$e.getNumDataCodewords(m,c)*8;s(b.length<=y),r(0,Math.min(4,y-b.length),b),r(0,(8-b.length%8)%8,b),s(b.length%8==0);for(let E=236;b.length<y;E^=253)r(E,8,b);let S=[];for(;S.length*8<b.length;)S.push(0);return b.forEach((E,k)=>S[k>>>3]|=E<<7-(k&7)),new $e(m,c,S,f)}getModule(o,c){return 0<=o&&o<this.size&&0<=c&&c<this.size&&this.modules[c][o]}getModules(){return this.modules}drawFunctionPatterns(){for(let d=0;d<this.size;d++)this.setFunctionModule(6,d,d%2==0),this.setFunctionModule(d,6,d%2==0);this.drawFinderPattern(3,3),this.drawFinderPattern(this.size-4,3),this.drawFinderPattern(3,this.size-4);const o=this.getAlignmentPatternPositions(),c=o.length;for(let d=0;d<c;d++)for(let h=0;h<c;h++)d==0&&h==0||d==0&&h==c-1||d==c-1&&h==0||this.drawAlignmentPattern(o[d],o[h]);this.drawFormatBits(0),this.drawVersion()}drawFormatBits(o){const c=this.errorCorrectionLevel.formatBits<<3|o;let d=c;for(let f=0;f<10;f++)d=d<<1^(d>>>9)*1335;const h=(c<<10|d)^21522;s(h>>>15==0);for(let f=0;f<=5;f++)this.setFunctionModule(8,f,n(h,f));this.setFunctionModule(8,7,n(h,6)),this.setFunctionModule(8,8,n(h,7)),this.setFunctionModule(7,8,n(h,8));for(let f=9;f<15;f++)this.setFunctionModule(14-f,8,n(h,f));for(let f=0;f<8;f++)this.setFunctionModule(this.size-1-f,8,n(h,f));for(let f=8;f<15;f++)this.setFunctionModule(8,this.size-15+f,n(h,f));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let o=this.version;for(let d=0;d<12;d++)o=o<<1^(o>>>11)*7973;const c=this.version<<12|o;s(c>>>18==0);for(let d=0;d<18;d++){const h=n(c,d),f=this.size-11+d%3,p=Math.floor(d/3);this.setFunctionModule(f,p,h),this.setFunctionModule(p,f,h)}}drawFinderPattern(o,c){for(let d=-4;d<=4;d++)for(let h=-4;h<=4;h++){const f=Math.max(Math.abs(h),Math.abs(d)),p=o+h,m=c+d;0<=p&&p<this.size&&0<=m&&m<this.size&&this.setFunctionModule(p,m,f!=2&&f!=4)}}drawAlignmentPattern(o,c){for(let d=-2;d<=2;d++)for(let h=-2;h<=2;h++)this.setFunctionModule(o+h,c+d,Math.max(Math.abs(h),Math.abs(d))!=1)}setFunctionModule(o,c,d){this.modules[c][o]=d,this.isFunction[c][o]=!0}addEccAndInterleave(o){const c=this.version,d=this.errorCorrectionLevel;if(o.length!=$e.getNumDataCodewords(c,d))throw new RangeError("Invalid argument");const h=$e.NUM_ERROR_CORRECTION_BLOCKS[d.ordinal][c],f=$e.ECC_CODEWORDS_PER_BLOCK[d.ordinal][c],p=Math.floor($e.getNumRawDataModules(c)/8),m=h-p%h,g=Math.floor(p/h);let b=[];const y=$e.reedSolomonComputeDivisor(f);for(let E=0,k=0;E<h;E++){let T=o.slice(k,k+g-f+(E<m?0:1));k+=T.length;const A=$e.reedSolomonComputeRemainder(T,y);E<m&&T.push(0),b.push(T.concat(A))}let S=[];for(let E=0;E<b[0].length;E++)b.forEach((k,T)=>{(E!=g-f||T>=m)&&S.push(k[E])});return s(S.length==p),S}drawCodewords(o){if(o.length!=Math.floor($e.getNumRawDataModules(this.version)/8))throw new RangeError("Invalid argument");let c=0;for(let d=this.size-1;d>=1;d-=2){d==6&&(d=5);for(let h=0;h<this.size;h++)for(let f=0;f<2;f++){const p=d-f,m=(d+1&2)==0?this.size-1-h:h;!this.isFunction[m][p]&&c<o.length*8&&(this.modules[m][p]=n(o[c>>>3],7-(c&7)),c++)}}s(c==o.length*8)}applyMask(o){if(o<0||o>7)throw new RangeError("Mask value out of range");for(let c=0;c<this.size;c++)for(let d=0;d<this.size;d++){let h;switch(o){case 0:h=(d+c)%2==0;break;case 1:h=c%2==0;break;case 2:h=d%3==0;break;case 3:h=(d+c)%3==0;break;case 4:h=(Math.floor(d/3)+Math.floor(c/2))%2==0;break;case 5:h=d*c%2+d*c%3==0;break;case 6:h=(d*c%2+d*c%3)%2==0;break;case 7:h=((d+c)%2+d*c%3)%2==0;break;default:throw new Error("Unreachable")}!this.isFunction[c][d]&&h&&(this.modules[c][d]=!this.modules[c][d])}}getPenaltyScore(){let o=0;for(let f=0;f<this.size;f++){let p=!1,m=0,g=[0,0,0,0,0,0,0];for(let b=0;b<this.size;b++)this.modules[f][b]==p?(m++,m==5?o+=$e.PENALTY_N1:m>5&&o++):(this.finderPenaltyAddHistory(m,g),p||(o+=this.finderPenaltyCountPatterns(g)*$e.PENALTY_N3),p=this.modules[f][b],m=1);o+=this.finderPenaltyTerminateAndCount(p,m,g)*$e.PENALTY_N3}for(let f=0;f<this.size;f++){let p=!1,m=0,g=[0,0,0,0,0,0,0];for(let b=0;b<this.size;b++)this.modules[b][f]==p?(m++,m==5?o+=$e.PENALTY_N1:m>5&&o++):(this.finderPenaltyAddHistory(m,g),p||(o+=this.finderPenaltyCountPatterns(g)*$e.PENALTY_N3),p=this.modules[b][f],m=1);o+=this.finderPenaltyTerminateAndCount(p,m,g)*$e.PENALTY_N3}for(let f=0;f<this.size-1;f++)for(let p=0;p<this.size-1;p++){const m=this.modules[f][p];m==this.modules[f][p+1]&&m==this.modules[f+1][p]&&m==this.modules[f+1][p+1]&&(o+=$e.PENALTY_N2)}let c=0;for(const f of this.modules)c=f.reduce((p,m)=>p+(m?1:0),c);const d=this.size*this.size,h=Math.ceil(Math.abs(c*20-d*10)/d)-1;return s(0<=h&&h<=9),o+=h*$e.PENALTY_N4,s(0<=o&&o<=2568888),o}getAlignmentPatternPositions(){if(this.version==1)return[];{const o=Math.floor(this.version/7)+2,c=this.version==32?26:Math.ceil((this.version*4+4)/(o*2-2))*2;let d=[6];for(let h=this.size-7;d.length<o;h-=c)d.splice(1,0,h);return d}}static getNumRawDataModules(o){if(o<$e.MIN_VERSION||o>$e.MAX_VERSION)throw new RangeError("Version number out of range");let c=(16*o+128)*o+64;if(o>=2){const d=Math.floor(o/7)+2;c-=(25*d-10)*d-55,o>=7&&(c-=36)}return s(208<=c&&c<=29648),c}static getNumDataCodewords(o,c){return Math.floor($e.getNumRawDataModules(o)/8)-$e.ECC_CODEWORDS_PER_BLOCK[c.ordinal][o]*$e.NUM_ERROR_CORRECTION_BLOCKS[c.ordinal][o]}static reedSolomonComputeDivisor(o){if(o<1||o>255)throw new RangeError("Degree out of range");let c=[];for(let h=0;h<o-1;h++)c.push(0);c.push(1);let d=1;for(let h=0;h<o;h++){for(let f=0;f<c.length;f++)c[f]=$e.reedSolomonMultiply(c[f],d),f+1<c.length&&(c[f]^=c[f+1]);d=$e.reedSolomonMultiply(d,2)}return c}static reedSolomonComputeRemainder(o,c){let d=c.map(h=>0);for(const h of o){const f=h^d.shift();d.push(0),c.forEach((p,m)=>d[m]^=$e.reedSolomonMultiply(p,f))}return d}static reedSolomonMultiply(o,c){if(o>>>8||c>>>8)throw new RangeError("Byte out of range");let d=0;for(let h=7;h>=0;h--)d=d<<1^(d>>>7)*285,d^=(c>>>h&1)*o;return s(d>>>8==0),d}finderPenaltyCountPatterns(o){const c=o[1];s(c<=this.size*3);const d=c>0&&o[2]==c&&o[3]==c*3&&o[4]==c&&o[5]==c;return(d&&o[0]>=c*4&&o[6]>=c?1:0)+(d&&o[6]>=c*4&&o[0]>=c?1:0)}finderPenaltyTerminateAndCount(o,c,d){return o&&(this.finderPenaltyAddHistory(c,d),c=0),c+=this.size,this.finderPenaltyAddHistory(c,d),this.finderPenaltyCountPatterns(d)}finderPenaltyAddHistory(o,c){c[0]==0&&(o+=this.size),c.pop(),c.unshift(o)}};t.MIN_VERSION=1,t.MAX_VERSION=40,t.PENALTY_N1=3,t.PENALTY_N2=3,t.PENALTY_N3=40,t.PENALTY_N4=10,t.ECC_CODEWORDS_PER_BLOCK=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],t.NUM_ERROR_CORRECTION_BLOCKS=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],e.QrCode=t;function r(l,o,c){if(o<0||o>31||l>>>o)throw new RangeError("Value out of range");for(let d=o-1;d>=0;d--)c.push(l>>>d&1)}function n(l,o){return(l>>>o&1)!=0}function s(l){if(!l)throw new Error("Assertion error")}const i=class nt{constructor(o,c,d){if(this.mode=o,this.numChars=c,this.bitData=d,c<0)throw new RangeError("Invalid argument");this.bitData=d.slice()}static makeBytes(o){let c=[];for(const d of o)r(d,8,c);return new nt(nt.Mode.BYTE,o.length,c)}static makeNumeric(o){if(!nt.isNumeric(o))throw new RangeError("String contains non-numeric characters");let c=[];for(let d=0;d<o.length;){const h=Math.min(o.length-d,3);r(parseInt(o.substring(d,d+h),10),h*3+1,c),d+=h}return new nt(nt.Mode.NUMERIC,o.length,c)}static makeAlphanumeric(o){if(!nt.isAlphanumeric(o))throw new RangeError("String contains unencodable characters in alphanumeric mode");let c=[],d;for(d=0;d+2<=o.length;d+=2){let h=nt.ALPHANUMERIC_CHARSET.indexOf(o.charAt(d))*45;h+=nt.ALPHANUMERIC_CHARSET.indexOf(o.charAt(d+1)),r(h,11,c)}return d<o.length&&r(nt.ALPHANUMERIC_CHARSET.indexOf(o.charAt(d)),6,c),new nt(nt.Mode.ALPHANUMERIC,o.length,c)}static makeSegments(o){return o==""?[]:nt.isNumeric(o)?[nt.makeNumeric(o)]:nt.isAlphanumeric(o)?[nt.makeAlphanumeric(o)]:[nt.makeBytes(nt.toUtf8ByteArray(o))]}static makeEci(o){let c=[];if(o<0)throw new RangeError("ECI assignment value out of range");if(o<128)r(o,8,c);else if(o<16384)r(2,2,c),r(o,14,c);else if(o<1e6)r(6,3,c),r(o,21,c);else throw new RangeError("ECI assignment value out of range");return new nt(nt.Mode.ECI,0,c)}static isNumeric(o){return nt.NUMERIC_REGEX.test(o)}static isAlphanumeric(o){return nt.ALPHANUMERIC_REGEX.test(o)}getData(){return this.bitData.slice()}static getTotalBits(o,c){let d=0;for(const h of o){const f=h.mode.numCharCountBits(c);if(h.numChars>=1<<f)return 1/0;d+=4+f+h.bitData.length}return d}static toUtf8ByteArray(o){o=encodeURI(o);let c=[];for(let d=0;d<o.length;d++)o.charAt(d)!="%"?c.push(o.charCodeAt(d)):(c.push(parseInt(o.substring(d+1,d+3),16)),d+=2);return c}};i.NUMERIC_REGEX=/^[0-9]*$/,i.ALPHANUMERIC_REGEX=/^[A-Z0-9 $%*+.\/:-]*$/,i.ALPHANUMERIC_CHARSET="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";let a=i;e.QrSegment=i})(hn||(hn={}));(e=>{(t=>{const r=class{constructor(s,i){this.ordinal=s,this.formatBits=i}};r.LOW=new r(0,1),r.MEDIUM=new r(1,0),r.QUARTILE=new r(2,3),r.HIGH=new r(3,2),t.Ecc=r})(e.QrCode||(e.QrCode={}))})(hn||(hn={}));(e=>{(t=>{const r=class{constructor(s,i){this.modeBits=s,this.numBitsCharCount=i}numCharCountBits(s){return this.numBitsCharCount[Math.floor((s+7)/17)]}};r.NUMERIC=new r(1,[10,12,14]),r.ALPHANUMERIC=new r(2,[9,11,13]),r.BYTE=new r(4,[8,16,16]),r.KANJI=new r(8,[8,10,12]),r.ECI=new r(7,[0,0,0]),t.Mode=r})(e.QrSegment||(e.QrSegment={}))})(hn||(hn={}));var Fn=hn;/**
81
+ * @license qrcode.react
82
+ * Copyright (c) Paul O'Shannessy
83
+ * SPDX-License-Identifier: ISC
84
+ */var DL={L:Fn.QrCode.Ecc.LOW,M:Fn.QrCode.Ecc.MEDIUM,Q:Fn.QrCode.Ecc.QUARTILE,H:Fn.QrCode.Ecc.HIGH},Uv=128,Gv="L",Hv="#FFFFFF",Vv="#000000",jv=!1,Kv=1,_L=4,OL=0,FL=.1;function zv(e,t=0){const r=[];return e.forEach(function(n,s){let i=null;n.forEach(function(a,l){if(!a&&i!==null){r.push(`M${i+t} ${s+t}h${l-i}v1H${i+t}z`),i=null;return}if(l===n.length-1){if(!a)return;i===null?r.push(`M${l+t},${s+t} h1v1H${l+t}z`):r.push(`M${i+t},${s+t} h${l+1-i}v1H${i+t}z`);return}a&&i===null&&(i=l)})}),r.join("")}function Wv(e,t){return e.slice().map((r,n)=>n<t.y||n>=t.y+t.h?r:r.map((s,i)=>i<t.x||i>=t.x+t.w?s:!1))}function $L(e,t,r,n){if(n==null)return null;const s=e.length+r*2,i=Math.floor(t*FL),a=s/t,l=(n.width||i)*a,o=(n.height||i)*a,c=n.x==null?e.length/2-l/2:n.x*a,d=n.y==null?e.length/2-o/2:n.y*a,h=n.opacity==null?1:n.opacity;let f=null;if(n.excavate){let m=Math.floor(c),g=Math.floor(d);f={x:m,y:g,w:Math.ceil(l+c-m),h:Math.ceil(o+d-g)}}const p=n.crossOrigin;return{x:c,y:d,h:o,w:l,excavation:f,opacity:h,crossOrigin:p}}function BL(e,t){return t!=null?Math.max(Math.floor(t),0):e?_L:OL}function Qv({value:e,level:t,minVersion:r,includeMargin:n,marginSize:s,imageSettings:i,size:a,boostLevel:l}){let o=dt.useMemo(()=>{const p=(Array.isArray(e)?e:[e]).reduce((m,g)=>(m.push(...Fn.QrSegment.makeSegments(g)),m),[]);return Fn.QrCode.encodeSegments(p,DL[t],r,void 0,void 0,l)},[e,t,r,l]);const{cells:c,margin:d,numCells:h,calculatedImageSettings:f}=dt.useMemo(()=>{let p=o.getModules();const m=BL(n,s);return{cells:p,margin:m,numCells:p.length+m*2,calculatedImageSettings:$L(p,a,m,i)}},[o,a,i,n,s]);return{qrcode:o,margin:d,cells:c,numCells:h,calculatedImageSettings:f}}var UL=(function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0})(),GL=dt.forwardRef(function(t,r){const n=t,{value:s,size:i=Uv,level:a=Gv,bgColor:l=Hv,fgColor:o=Vv,includeMargin:c=jv,minVersion:d=Kv,boostLevel:h,marginSize:f,imageSettings:p}=n,m=jl(n,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:g}=m,b=jl(m,["style"]),y=p?.src,S=dt.useRef(null),E=dt.useRef(null),k=dt.useCallback(B=>{S.current=B,typeof r=="function"?r(B):r&&(r.current=B)},[r]),[T,A]=dt.useState(!1),{margin:N,cells:C,numCells:M,calculatedImageSettings:P}=Qv({value:s,level:a,minVersion:d,boostLevel:h,includeMargin:c,marginSize:f,imageSettings:p,size:i});dt.useEffect(()=>{if(S.current!=null){const B=S.current,j=B.getContext("2d");if(!j)return;let U=C;const F=E.current,Y=P!=null&&F!==null&&F.complete&&F.naturalHeight!==0&&F.naturalWidth!==0;Y&&P.excavation!=null&&(U=Wv(C,P.excavation));const I=window.devicePixelRatio||1;B.height=B.width=i*I;const R=i/M*I;j.scale(R,R),j.fillStyle=l,j.fillRect(0,0,M,M),j.fillStyle=o,UL?j.fill(new Path2D(zv(U,N))):C.forEach(function(O,K){O.forEach(function(W,J){W&&j.fillRect(J+N,K+N,1,1)})}),P&&(j.globalAlpha=P.opacity),Y&&j.drawImage(F,P.x+N,P.y+N,P.w,P.h)}}),dt.useEffect(()=>{A(!1)},[y]);const D=Vl({height:i,width:i},g);let $=null;return y!=null&&($=dt.createElement("img",{src:y,key:y,style:{display:"none"},onLoad:()=>{A(!0)},ref:E,crossOrigin:P?.crossOrigin})),dt.createElement(dt.Fragment,null,dt.createElement("canvas",Vl({style:D,height:i,width:i,ref:k,role:"img"},b)),$)});GL.displayName="QRCodeCanvas";var qv=dt.forwardRef(function(t,r){const n=t,{value:s,size:i=Uv,level:a=Gv,bgColor:l=Hv,fgColor:o=Vv,includeMargin:c=jv,minVersion:d=Kv,boostLevel:h,title:f,marginSize:p,imageSettings:m}=n,g=jl(n,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:b,cells:y,numCells:S,calculatedImageSettings:E}=Qv({value:s,level:a,minVersion:d,boostLevel:h,includeMargin:c,marginSize:p,imageSettings:m,size:i});let k=y,T=null;m!=null&&E!=null&&(E.excavation!=null&&(k=Wv(y,E.excavation)),T=dt.createElement("image",{href:m.src,height:E.h,width:E.w,x:E.x+b,y:E.y+b,preserveAspectRatio:"none",opacity:E.opacity,crossOrigin:E.crossOrigin}));const A=zv(k,b);return dt.createElement("svg",Vl({height:i,width:i,viewBox:`0 0 ${S} ${S}`,ref:r,role:"img"},g),!!f&&dt.createElement("title",null,f),dt.createElement("path",{fill:l,d:`M0,0 h${S}v${S}H0z`,shapeRendering:"crispEdges"}),dt.createElement("path",{fill:o,d:A,shapeRendering:"crispEdges"}),T)});qv.displayName="QRCodeSVG";var HL=192;function Yv({value:e,size:t=HL,className:r,alt:n}){const s=e.trim();return s.length===0?null:u("div",{className:L("inline-flex rounded-md bg-white p-2",r),children:u(qv,{value:s,size:t,marginSize:1,title:n??"QR code"})})}var VL="w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none disabled:opacity-50 disabled:cursor-not-allowed";function jL({value:e,onChange:t,disabled:r}){const n=[];for(const s of Ou)n.includes(s.region)||n.push(s.region);return v("select",{className:VL,value:e,disabled:r,onChange:s=>t(s.target.value),children:[!a0(e)&&u("option",{value:"",children:"— Select timezone —"}),n.map(s=>u("optgroup",{label:s,children:Ou.filter(i=>i.region===s).map(i=>u("option",{value:i.id,children:i.label},i.id))},s))]})}var Wr="w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none disabled:opacity-50 disabled:cursor-not-allowed",_a="block text-[11px] font-medium text-foreground mb-1 break-words",KL="text-[10px] text-foreground-subtle mt-0.5 break-words";function Je({label:e,description:t,required:r,span:n,children:s,translationFn:i}){const a=n===2?"col-span-1 @[480px]:col-span-2":n===3?"col-span-1 @[480px]:col-span-2 @[880px]:col-span-3":n===4?"col-span-1 @[480px]:col-span-2 @[1140px]:col-span-4":"col-span-1",l=rr(e,i),o=rr(t,i),c=l!==void 0&&l!=="";return v("div",{className:`${a} min-w-0`,children:[c&&v("label",{className:_a,children:[l,r&&u("span",{className:"text-danger ml-0.5",children:"*"})]}),s,o&&u("p",{className:KL,children:o})]})}function zL({field:e,value:t,onChange:r,disabled:n,translationFn:s}){return u(Je,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:u("input",{type:e.inputType??"text",className:Wr,value:t==null?"":String(t),placeholder:e.placeholder,maxLength:e.maxLength,pattern:e.pattern,disabled:n||e.disabled,onChange:i=>r(i.target.value)})})}function WL({field:e,value:t,onChange:r,disabled:n,translationFn:s}){const[i,a]=_(t==null?"":String(t)),l=ne(!1);ae(()=>{l.current||a(t==null?"":String(t))},[t]);const o=c=>{if(a(c),c===""||c==="-"){r(void 0);return}const d=Number(c);Number.isNaN(d)||r(d)};return u(Je,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:v("div",{className:"flex items-center gap-1",children:[u("input",{type:"number",className:Wr,value:i,placeholder:e.placeholder,min:e.min,max:e.max,step:e.step,disabled:n||e.disabled,onFocus:()=>{l.current=!0},onBlur:()=>{l.current=!1},onChange:c=>o(c.target.value)}),e.unit&&u("span",{className:"text-xs text-foreground-subtle whitespace-nowrap",children:e.unit})]})})}function QL({field:e,value:t,onChange:r,disabled:n,translationFn:s}){const i=!!t,a=n||e.disabled;return e.style==="checkbox"?u(Je,{label:void 0,description:e.description,required:e.required,span:e.span,translationFn:s,children:v("label",{className:"flex items-center gap-2 cursor-pointer select-none",children:[u("input",{type:"checkbox",className:"h-3.5 w-3.5 rounded border-border accent-primary",checked:i,disabled:a,onChange:l=>r(l.target.checked)}),u("span",{className:"text-xs font-medium text-foreground",children:rr(e.label,s)}),e.required&&u("span",{className:"text-danger",children:"*"})]})}):u(Je,{label:void 0,description:e.description,required:e.required,span:e.span,translationFn:s,children:v("div",{className:"flex items-center justify-between",children:[v("span",{className:_a+" mb-0",children:[rr(e.label,s),e.required&&u("span",{className:"text-danger ml-0.5",children:"*"})]}),u("button",{type:"button",role:"switch","aria-checked":i,disabled:a,onClick:()=>!a&&r(!i),className:["relative inline-flex h-4 w-8 shrink-0 items-center rounded-full transition-colors duration-150",i?"bg-primary":"bg-foreground-subtle/30",a?"opacity-50 cursor-not-allowed":"cursor-pointer"].join(" "),children:u("span",{className:["inline-block h-3 w-3 rounded-full bg-white shadow transition-transform duration-150",i?"translate-x-4":"translate-x-0.5"].join(" ")})})]})})}function qL({field:e,value:t,onChange:r,disabled:n,translationFn:s}){const i=e.options.some(a=>a.value==="");return u(Je,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:v("select",{className:Wr,value:t==null?"":String(t),disabled:n||e.disabled,onChange:a=>r(a.target.value),children:[!e.required&&!i&&u("option",{value:"",children:"— Select —"}),e.options.map(a=>u("option",{value:a.value,children:a.label},a.value))]})})}function YL({field:e,value:t,onChange:r,disabled:n,translationFn:s}){return u(Je,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:u(jL,{value:typeof t=="string"?t:"",onChange:r,disabled:n||e.disabled})})}function XL({field:e,value:t,onChange:r,disabled:n,translationFn:s}){return u(Je,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:u("input",{type:"datetime-local",className:Wr,value:typeof t=="string"?t:"",placeholder:e.placeholder,disabled:n||e.disabled,onChange:i=>r(i.target.value)})})}function ZL({field:e,value:t,onChange:r,disabled:n,translationFn:s}){const i=Array.isArray(t)?t:[],a=l=>{if(i.includes(l))r(i.filter(o=>o!==l));else{if(e.maxItems!==void 0&&i.length>=e.maxItems)return;r([...i,l])}};return u(Je,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:u("div",{className:"flex flex-wrap gap-2",children:e.options.map(l=>{const o=i.includes(l.value);return v("label",{className:["flex items-center gap-1.5 rounded-md border px-2 py-1 text-xs cursor-pointer select-none transition-colors",o?"border-primary bg-primary/10 text-primary":"border-border bg-background text-foreground hover:bg-surface",n||e.disabled?"opacity-50 cursor-not-allowed":""].join(" "),children:[u("input",{type:"checkbox",className:"sr-only",checked:o,disabled:n||e.disabled,onChange:()=>a(l.value)}),l.label]},l.value)})})})}function JL({field:e,value:t,onChange:r,disabled:n,translationFn:s}){const[i,a]=_(!1),l=e.showToggle!==!1;return u(Je,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:v("div",{className:"relative",children:[u("input",{type:i?"text":"password",className:Wr+(l?" pr-9":""),value:t==null?"":String(t),placeholder:e.placeholder,disabled:n||e.disabled,onChange:o=>r(o.target.value)}),l&&u("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 text-foreground-subtle hover:text-foreground",tabIndex:-1,onClick:()=>a(o=>!o),children:i?u(Ca,{className:"h-3.5 w-3.5"}):u(Xs,{className:"h-3.5 w-3.5"})})]})})}function eI({field:e,value:t,onChange:r,disabled:n,translationFn:s}){return u(Je,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:u("textarea",{className:Wr+" resize-y min-h-[60px]",value:t==null?"":String(t),placeholder:e.placeholder,rows:e.rows??3,maxLength:e.maxLength,disabled:n||e.disabled,onChange:i=>r(i.target.value)})})}function tI({field:e,value:t,onChange:r,disabled:n,translationFn:s}){const i=t==null,a=e.nullable===!0,l=i?e.default??e.min:Number(t),o=e.showValue!==!1,c=e.nullLabel??"Auto",d=n||e.disabled,h=e.displayScale??1,f=e.min/h,p=e.max/h,m=l/h,g=(e.step??1)/h;if(a&&i)return u(Je,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:v("button",{className:"w-full rounded-lg border border-dashed border-border px-3 py-2 text-xs text-foreground-subtle hover:border-primary/40 hover:text-primary transition-colors text-left",disabled:d,onClick:()=>r(e.default??e.min),children:[c," — click to set manually"]})});const b=e.showStepper===!0&&o,y=E=>{const k=l+E*(e.step??1),T=Math.min(e.max,Math.max(e.min,k));T!==l&&r(T)},S="flex h-6 w-6 shrink-0 items-center justify-center rounded border border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:cursor-not-allowed disabled:opacity-40";return u(Je,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:v("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-2",children:[v("div",{className:"flex min-w-0 flex-1 basis-[160px] items-center gap-2",children:[u("span",{className:"text-[10px] text-foreground-subtle tabular-nums shrink-0",children:f}),u("input",{type:"range",className:"min-w-0 flex-1 h-1 accent-primary cursor-pointer disabled:opacity-50",min:f,max:p,step:g,value:m,disabled:d,onChange:E=>r(Number(E.target.value)*h)}),u("span",{className:"text-[10px] text-foreground-subtle tabular-nums shrink-0",children:p})]}),(o||a||e.unit)&&v("div",{className:"flex shrink-0 items-center gap-2",children:[b&&u("button",{type:"button",className:S,disabled:d||l<=e.min,onClick:()=>y(-1),title:`Decrease by ${e.step??1}`,"aria-label":"Decrement",children:u(Am,{className:"h-3 w-3"})}),o&&u("input",{type:"number",className:"w-16 rounded border border-border bg-surface px-1.5 py-0.5 text-xs text-center text-foreground tabular-nums focus:outline-none focus:ring-1 focus:ring-primary",min:f,max:p,step:g,value:m,disabled:d,onChange:E=>{if(E.target.value===""){r(a?null:e.min);return}const k=Number(E.target.value)*h,T=e.step??1,A=k-e.min,N=e.min+Math.round(A/T)*T;r(Math.min(e.max,Math.max(e.min,N)))}}),b&&u("button",{type:"button",className:S,disabled:d||l>=e.max,onClick:()=>y(1),title:`Increase by ${e.step??1}`,"aria-label":"Increment",children:u(gn,{className:"h-3 w-3"})}),e.unit&&u("span",{className:"text-[10px] text-foreground-subtle",children:e.unit}),a&&u("button",{className:"text-[10px] text-foreground-subtle hover:text-primary transition-colors",title:`Reset to ${c}`,disabled:d,onClick:()=>r(null),children:c})]})]})})}function rI({field:e,value:t,onChange:r,disabled:n,translationFn:s}){const i=Array.isArray(t)?t:[],[a,l]=_(""),o=ne(null),c=q(p=>{const m=p.trim();!m||i.includes(m)||e.maxTags!==void 0&&i.length>=e.maxTags||(r([...i,m]),l(""))},[i,e.maxTags,r]),d=p=>r(i.filter(m=>m!==p)),h=p=>{p.key==="Enter"||p.key===","?(p.preventDefault(),c(a)):p.key==="Backspace"&&a===""&&i.length>0&&d(i[i.length-1])},f=n||e.disabled;return u(Je,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:v("div",{className:["flex flex-wrap gap-1.5 rounded-md border border-border bg-background px-2 py-1.5 min-h-[38px] cursor-text","focus-within:border-primary focus-within:ring-1 focus-within:ring-primary/30",f?"opacity-50 cursor-not-allowed":""].join(" "),onClick:()=>!f&&o.current?.focus(),children:[i.map(p=>v("span",{className:"inline-flex items-center gap-1 rounded-md bg-primary/10 px-1.5 py-0.5 text-xs text-primary",children:[p,!f&&u("button",{type:"button",onClick:()=>d(p),className:"hover:text-danger",children:u(bt,{className:"h-2.5 w-2.5"})})]},p)),u("input",{ref:o,type:"text",className:"flex-1 min-w-[80px] bg-transparent text-sm text-foreground outline-none placeholder:text-foreground-disabled",value:a,placeholder:i.length===0?e.placeholder??"Add tags…":"",disabled:f,list:`tags-suggestions-${e.key}`,onChange:p=>l(p.target.value),onKeyDown:h,onBlur:()=>{a.trim()&&c(a)}}),e.suggestions&&u("datalist",{id:`tags-suggestions-${e.key}`,children:e.suggestions.map(p=>u("option",{value:p},p))})]})})}function nI({field:e,value:t,onChange:r,disabled:n,translationFn:s}){const{nodes:i}=zc(),a=typeof t=="string"?t:"",l=e.showOffline?i:i.filter(o=>o.isOnline);return u(Je,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:v("select",{className:"w-full px-3 py-2 text-sm bg-background border border-border rounded-lg text-foreground focus:outline-none focus:border-primary/50 disabled:opacity-50",value:a,onChange:o=>r(o.target.value),disabled:n,children:[u("option",{value:"",children:"Select node…"}),l.map(o=>v("option",{value:o.id,disabled:!o.isOnline,children:[o.shortName,o.isOnline?"":" (offline)"]},o.id))]})})}function sI({field:e,value:t,onChange:r,disabled:n,translationFn:s}){const{nodes:i}=zc(),a=new Set(Array.isArray(t)?t.map(String):[]),l=e.showOffline?i:i.filter(c=>c.isOnline),o=c=>{const d=new Set(a);d.has(c)?d.delete(c):d.add(c),r([...d])};return u(Je,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:u("div",{className:"flex flex-wrap gap-1.5",children:l.map(c=>{const d=a.has(c.id);return u("button",{type:"button",onClick:()=>o(c.id),disabled:n||!c.isOnline,className:`px-2.5 py-1 text-xs font-medium rounded-md border transition-colors ${d?"border-primary bg-primary/10 text-primary":"border-border bg-surface text-foreground-subtle hover:bg-surface-hover"} ${c.isOnline?"":"opacity-50 cursor-not-allowed"}`,children:c.shortName},c.id)})})})}function iI({field:e,value:t,onChange:r,disabled:n,translationFn:s}){const i=t==null?"#000000":String(t);return v(Je,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:[v("div",{className:"flex items-center gap-2",children:[u("input",{type:"color",className:"h-9 w-9 rounded-md border border-border bg-background cursor-pointer p-0.5 disabled:opacity-50",value:i,disabled:n||e.disabled,onChange:a=>r(a.target.value)}),u("input",{type:"text",className:Wr+" flex-1 font-mono",value:i,placeholder:"#000000",disabled:n||e.disabled,onChange:a=>r(a.target.value)})]}),e.presets&&e.presets.length>0&&u("div",{className:"flex gap-1.5 mt-1.5",children:e.presets.map(a=>u("button",{type:"button",className:"h-5 w-5 rounded-md border border-border hover:scale-110 transition-transform disabled:opacity-50",style:{backgroundColor:a},disabled:n||e.disabled,title:a,onClick:()=>r(a)},a))})]})}function aI({field:e,value:t,onChange:r,disabled:n,translationFn:s,onTestField:i,onAction:a,externalProbe:l}){const[o,c]=_("idle"),[d,h]=_(null),f=l?.status??o,p=l?.result??d,m=!!i||!!a,g=q(async()=>{if(m){c("probing"),h(null);try{const S=i?await i(e.key,t):await a("test-probe",e.key,t),E=S&&typeof S=="object"?S:{status:"error",error:"Probe handler returned no result"};h(E),c(E.status==="ok"?"ok":"error")}catch(S){h({status:"error",error:S instanceof Error?S.message:String(S)}),c("error")}}},[i,a,e.key,t,m]),b=f==="probing"?"border-primary/40 bg-primary/10 text-primary":f==="ok"?"border-success/40 bg-success/10 text-success hover:bg-success/15":f==="error"?"border-danger/40 bg-danger/10 text-danger hover:bg-danger/15":"border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover",y=f==="probing"?u(vt,{className:"h-3 w-3 animate-spin"}):f==="ok"?u(kS,{className:"h-3 w-3"}):f==="error"?u(rs,{className:"h-3 w-3"}):u(Fc,{className:"h-3 w-3"});return v(Je,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:[v("div",{className:"@container flex items-center gap-2",style:{containerType:"inline-size"},children:[v("button",{type:"button",onClick:g,title:"Test",disabled:e.disabled||f==="probing"||!m||!t,className:`flex-shrink-0 inline-flex items-center gap-1.5 rounded-md border px-2 py-2 text-xs font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed @[280px]:px-3 ${b}`,children:[y,u("span",{className:"hidden @[280px]:inline",children:"Test"})]}),u("input",{type:e.inputType??"url",className:Wr+" flex-1 min-w-0",value:t==null?"":String(t),placeholder:e.placeholder,disabled:n||e.disabled,onChange:S=>{r(S.target.value),o!=="idle"&&(c("idle"),h(null))}})]}),f==="ok"&&p?.labels&&p.labels.length>0&&u("div",{className:"flex flex-wrap gap-1 mt-1.5",children:p.labels.map((S,E)=>u("span",{className:"text-xs bg-success/10 text-success rounded px-2 py-0.5 font-mono",children:S},E))}),f==="error"&&p?.error&&u("p",{className:"text-xs text-danger mt-1 truncate",title:p.error,children:p.error})]})}function oI({field:e,values:t,onChange:r,disabled:n,translationFn:s,onTestField:i}){const[a,l]=_(e.defaultCollapsed??!1),o=e.style==="accordion";return u("div",{className:`${e.span===2?"col-span-2":e.span===3?"col-span-3":e.span===4?"col-span-4":"col-span-1"} min-w-0`,children:v("div",{className:"@container rounded-lg border border-border bg-surface/50 overflow-hidden",style:{containerType:"inline-size"},children:[v("div",{className:["px-3 py-2 flex items-center justify-between min-w-0",o?"cursor-pointer hover:bg-surface":""].join(" "),onClick:o?()=>l(c=>!c):void 0,children:[u("span",{className:"text-xs font-semibold text-foreground min-w-0 break-words",children:rr(e.label,s)}),o&&u("span",{className:"text-foreground-subtle text-xs shrink-0 ml-2",children:a?"▸":"▾"})]}),!a&&u("div",{className:"px-3 pb-3 grid grid-cols-1 @[480px]:grid-cols-2 gap-x-4 gap-y-3",children:e.fields.map(c=>u(ei,{field:c,values:t,onChange:r,disabled:n,translationFn:s,onTestField:i},c.key))})]})})}function lI({field:e,values:t,onChange:r,disabled:n,translationFn:s,onTestField:i,onAction:a}){const[l,o]=_(e.tabs[0]?.id??""),c=e.span===2?"col-span-2":e.span===3?"col-span-3":e.span===4?"col-span-4":"col-span-1";return e.tabs.length===0?null:v("div",{className:`${c} min-w-0`,children:[e.label&&u("div",{className:_a,children:rr(e.label,s)}),v("div",{className:"@container rounded-lg border border-border-subtle bg-surface-hover/40 overflow-hidden",style:{containerType:"inline-size"},children:[u("div",{className:"flex flex-wrap gap-1 p-1.5 border-b border-border-subtle bg-surface/40",role:"tablist",children:e.tabs.map(d=>{const h=d.id===l;return v("button",{type:"button",role:"tab","aria-selected":h,onClick:()=>o(d.id),className:`inline-flex items-center gap-1.5 whitespace-nowrap rounded-md px-2.5 py-1 text-[11px] transition-colors ${h?"bg-primary text-primary-foreground font-medium shadow-sm":"bg-transparent text-foreground-subtle hover:bg-surface hover:text-foreground"}`,children:[u("span",{children:rr(d.label,s)}),d.badge&&u("span",{className:`text-[9px] px-1 py-0.5 rounded-full font-medium ${h?"bg-primary-foreground/20 text-primary-foreground":"bg-primary/10 text-primary"}`,children:d.badge})]},d.id)})}),e.tabs.map(d=>d.id!==l?null:u("div",{role:"tabpanel",className:"px-3 pb-3 pt-2 grid grid-cols-1 @[480px]:grid-cols-2 gap-x-4 gap-y-3",children:d.fields.map((h,f)=>{const p="key"in h&&typeof h.key=="string"?h.key:`__${d.id}__${f}`;return u(ei,{field:h,values:t,onChange:r,disabled:n,translationFn:s,onTestField:i,onAction:a},p)})},d.id))]})]})}function cI({span:e}){return u("div",{className:e===2?"col-span-2":e===3?"col-span-3":e===4?"col-span-4":"col-span-full",children:u("hr",{className:"border-border"})})}var uh={info:{border:"border-info",bg:"bg-info/5",text:"text-info"},warning:{border:"border-warning",bg:"bg-warning/5",text:"text-warning"},success:{border:"border-success",bg:"bg-success/5",text:"text-success"},danger:{border:"border-danger",bg:"bg-danger/5",text:"text-danger"}};function uI(e){if(typeof window>"u"||typeof DOMParser>"u")return"";const t=new Set(["A","UL","OL","LI","STRONG","EM","CODE","BR","P","SPAN"]),r=new DOMParser().parseFromString(`<div>${e}</div>`,"text/html"),n=r.body.firstElementChild;if(!n)return"";const s=i=>{const a=Array.from(i.children);for(const l of a){if(!t.has(l.tagName)){const c=r.createTextNode(l.textContent??"");l.replaceWith(c);continue}const o=l.tagName==="A"?new Set(["href"]):new Set;for(const c of Array.from(l.attributes))o.has(c.name)||l.removeAttribute(c.name);if(l.tagName==="A"){const c=l.getAttribute("href")??"";!/^https?:\/\//i.test(c)&&!c.startsWith("mailto:")?l.removeAttribute("href"):(l.setAttribute("target","_blank"),l.setAttribute("rel","noopener noreferrer"))}s(l)}};return s(n),n.innerHTML}function dI({field:e}){const t=uh[e.variant??"info"]??uh.info,r=e.format==="html";return u("div",{className:"col-span-full",children:v("div",{className:`rounded-md border-l-4 px-3 py-2.5 ${t.border} ${t.bg}`,children:[e.label&&u("p",{className:`text-xs font-semibold mb-0.5 ${t.text}`,children:e.label}),r?u("div",{className:"text-xs text-foreground-subtle leading-relaxed info-html-content",dangerouslySetInnerHTML:{__html:uI(e.content)}}):u("p",{className:"text-xs text-foreground-subtle leading-relaxed whitespace-pre-line",children:e.content})]})})}function hI({field:e}){const t=e.value;if(!t||t.length===0)return null;const r=e.size??192,n=e.alt??e.label;return u("div",{className:"col-span-full",children:v("div",{className:"rounded-md border border-foreground-subtle/20 px-3 py-3 bg-background-subtle/40 flex flex-col items-start gap-2",children:[e.label&&u("p",{className:"text-xs font-semibold text-foreground",children:e.label}),e.caption&&u("p",{className:"text-xs text-foreground-subtle leading-relaxed",children:e.caption}),u(Yv,{value:t,size:r,alt:n})]})})}var dh={ok:"bg-success",warn:"bg-amber-500",danger:"bg-danger",idle:"bg-foreground-subtle/40",unknown:"bg-foreground-subtle/40"};function fI(e){if(!Number.isFinite(e)||e<0)return"—";if(e<1e3)return`${e}ms`;const t=Math.round(e/1e3);if(t<60)return`${t}s`;const r=Math.floor(t/60),n=t%60;return n===0?`${r}m`:`${r}m ${n}s`}function pI(e){return!Number.isFinite(e)||e<=0?"—":new Date(e).toLocaleTimeString()}function mI({kind:e,value:t}){return t==null||t===""?u("span",{className:"text-foreground-subtle/60",children:"—"}):e==="monospace"?u("span",{className:"font-mono text-[11px]",children:String(t)}):e==="status"?v("span",{className:"inline-flex items-center gap-1.5",children:[u("span",{className:`inline-block h-1.5 w-1.5 rounded-full ${dh[String(t).toLowerCase()]??dh.unknown}`}),u("span",{children:String(t)})]}):e==="duration"&&typeof t=="number"?u("span",{className:"font-mono text-[11px]",children:fI(t)}):e==="timestamp"&&typeof t=="number"?u("span",{className:"font-mono text-[11px]",children:pI(t)}):u("span",{children:String(t)})}function gI({field:e}){const t=e.value??[],r=e.description;return v("div",{className:"col-span-full",children:[e.label&&u("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle mb-1",children:e.label}),r&&u("p",{className:"text-xs text-foreground-subtle mb-2",children:r}),t.length===0?u("div",{className:"rounded-md border border-border bg-surface-subtle px-3 py-2 text-xs text-foreground-subtle",children:e.emptyMessage??"No entries"}):u("div",{className:"rounded-md border border-border overflow-hidden",children:v("table",{className:"w-full text-xs",children:[u("thead",{className:"bg-surface-subtle border-b border-border",children:u("tr",{children:e.columns.map(n=>u("th",{className:"px-3 py-1.5 text-left font-medium text-foreground-subtle",style:n.width?{width:n.width}:void 0,children:n.label},n.key))})}),u("tbody",{className:"divide-y divide-border",children:t.map((n,s)=>u("tr",{className:"hover:bg-surface-hover/40",children:e.columns.map(i=>u("td",{className:"px-3 py-1.5 align-top text-foreground",children:u(mI,{kind:i.kind,value:n[i.key]})},i.key))},s))})]})})]})}function vI({field:e,value:t,onChange:r,disabled:n,translationFn:s,onTestField:i,onAction:a}){const l=Array.isArray(t)?t:[],o=e.minRows??0,c=e.maxRows??Number.POSITIVE_INFINITY,d=(b,y,S)=>{const E=l.slice();E[b]={...E[b]??{},[y]:S},r(E)},h=b=>{l.length<=o||r(l.filter((y,S)=>S!==b))},f=()=>{if(l.length>=c)return;const b=e.defaultItem??{};r([...l,{...b}])},p=(b,y)=>e.rowTitleTemplate?e.rowTitleTemplate.replace(/\{(\w+)\}/g,(S,E)=>{const k=b[E];return k==null||k===""?"—":String(k)}):`Row ${y+1}`,m=l.length>o,g=l.length<c;return v("div",{className:"col-span-full space-y-2",children:[v("div",{className:"space-y-0.5",children:[e.label&&u("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle",children:rr(e.label,s)}),e.description&&u("p",{className:"text-[11px] text-foreground-subtle",children:rr(e.description,s)})]}),l.length===0?u("div",{className:"rounded-md border border-dashed border-border bg-background px-3 py-3 text-center text-[11px] text-foreground-subtle",children:e.emptyMessage??"No entries"}):u("div",{className:"space-y-2",children:l.map((b,y)=>v("div",{className:"rounded-md border border-border bg-background",children:[v("div",{className:"flex items-center justify-between border-b border-border px-3 py-1.5",children:[u("span",{className:"text-xs font-medium text-foreground",children:p(b,y)}),v("button",{type:"button",onClick:()=>h(y),disabled:n||!m,className:"inline-flex items-center gap-1 rounded px-2 py-0.5 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-30 disabled:cursor-not-allowed",title:m?"Remove this row":`At least ${o} row(s) required`,children:[u(Am,{className:"h-3 w-3"}),"Remove"]})]}),u("div",{className:"grid grid-cols-1 @[480px]:grid-cols-2 gap-x-3 gap-y-2 p-3",children:e.itemFields.map(S=>u(ei,{field:S,values:b,onChange:(E,k)=>d(y,E,k),disabled:n,translationFn:s,onTestField:i,allFields:e.itemFields,onAction:a},S.key))})]},y))}),v("div",{children:[v("button",{type:"button",onClick:f,disabled:n||!g,className:"inline-flex items-center gap-1 rounded border border-border bg-surface px-3 py-1 text-[11px] font-medium text-foreground hover:border-primary/40 hover:bg-primary/5 disabled:opacity-30 disabled:cursor-not-allowed",children:[u(gn,{className:"h-3 w-3"}),e.addLabel??"Add"]}),!g&&Number.isFinite(c)&&v("span",{className:"ml-2 text-[10px] text-foreground-subtle",children:["(limit: ",c,")"]})]})]})}function bI({field:e,disabled:t,onAction:r}){const[n,s]=_(!1),i=is(),a=async()=>{if(!(e.confirmMessage&&!await i({title:e.label,message:e.confirmMessage,confirmLabel:e.buttonLabel,variant:e.variant==="danger"?"danger":"default"}))&&r){s(!0);try{await r(e.action,e.key)}finally{s(!1)}}},l={default:"border border-border text-foreground hover:bg-surface-hover",primary:"bg-primary text-primary-foreground hover:bg-primary/90",danger:"bg-danger text-white hover:bg-danger/90"};return u(Je,{label:e.label,description:e.description,required:e.required,span:e.span,children:u("button",{onClick:a,disabled:t||n,className:`inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-colors disabled:opacity-50 ${l[e.variant??"default"]??l.default}`,children:n?"Processing...":e.buttonLabel})})}function cu(e,t){const r={...e.paramsStatic??{}};if(e.paramsFromForm)for(const[n,s]of Object.entries(e.paramsFromForm)){const i=t[s];i!=null&&i!==""&&(r[n]=i)}return r}function yI({field:e,value:t,values:r,onChange:n,disabled:s,onAction:i}){const[a,l]=_(!1),[o,c]=_(null),[d,h]=_(null),f=cu(e,r),p=Object.keys(e.paramsFromForm??{}).some(y=>f[y]===void 0);ae(()=>{if(!i||p){h(null),c(null);return}let y=!1;return l(!0),c(null),i(e.action,e.key,f).then(S=>{if(y)return;const E=S;let k=[];if(Array.isArray(E))k=E;else if(E&&typeof E=="object")for(const T of Object.keys(E)){const A=E[T];if(Array.isArray(A)){k=A;break}}h(k)}).catch(S=>{y||(c(S instanceof Error?S.message:String(S)),h([]))}).finally(()=>{y||l(!1)}),()=>{y=!0}},[(e.refreshOn??Object.values(e.paramsFromForm??{})).map(y=>`${y}=${JSON.stringify(r[y])}`).join("|"),i,e.action,e.key]);const m=e.mapOption.value,g=e.mapOption.label,b=e.mapOption.description;return u(Je,{label:e.label,description:e.description,required:e.required,span:e.span,children:p?u("div",{className:"text-[11px] text-foreground-subtle italic",children:e.emptyParamsMessage??"Fill the prerequisite fields above first."}):a?v("div",{className:"flex items-center gap-2 text-[11px] text-foreground-subtle",children:[u(vt,{className:"h-3 w-3 animate-spin"})," Loading options…"]}):o?u("div",{className:"text-[11px] text-danger",children:o}):d&&d.length===0?u("div",{className:"text-[11px] text-foreground-subtle italic",children:e.emptyResultsMessage??"No options returned."}):(()=>{const y=(d??[]).some(S=>{const E=S[m];return E===""||E===void 0});return v("select",{className:"w-full rounded-md border border-border bg-surface px-2 py-1.5 text-xs text-foreground",value:typeof t=="string"?t:"",disabled:s,onChange:S=>n(S.target.value),children:[!y&&u("option",{value:"",children:"— Select —"}),(d??[]).map((S,E)=>{const k=S[m],T=S[g],A=b?S[b]:void 0,N=typeof k=="string"&&k!==""?k:`row-${E}`;return v("option",{value:typeof k=="string"?k:String(k??""),children:[typeof T=="string"?T:String(T??N),A!==void 0?` (${String(A)})`:""]},N)})]})})()})}function xI({field:e,values:t,disabled:r,onAction:n}){const[s,i]=_(!1),[a,l]=_(null),o=is(),c=async()=>{if(e.confirmMessage&&!await o({title:e.label,message:e.confirmMessage,confirmLabel:e.buttonLabel,variant:e.variant==="danger"?"danger":"default"})||!n)return;const h=cu(e,t);i(!0),l(null);try{const f=await n(e.action,e.key,h),p=typeof f=="object"&&f!==null?f:null;l({kind:"ok",text:e.successMessage?e.successMessage.replace(/\{(\w+)\}/g,(m,g)=>{const b=p?.[g];return b===void 0?"":String(b)}):"Done."})}catch(f){l({kind:"error",text:f instanceof Error?f.message:String(f)})}finally{i(!1)}},d={default:"border border-border text-foreground hover:bg-surface-hover",primary:"bg-primary text-primary-foreground hover:bg-primary/90",danger:"bg-danger text-white hover:bg-danger/90"};return u(Je,{label:e.label,description:e.description,required:e.required,span:e.span,children:v("div",{className:"flex flex-col gap-1.5",children:[u("button",{onClick:c,disabled:r||s,className:`inline-flex w-fit items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-colors disabled:opacity-50 ${d[e.variant??"default"]??d.default}`,children:s?"Working…":e.buttonLabel}),a&&u("div",{className:`text-[11px] ${a.kind==="ok"?"text-emerald-700 dark:text-emerald-300":"text-danger"}`,children:a.text})]})})}function SI({field:e,values:t,disabled:r,onAction:n}){const[s,i]=_(!1),[a,l]=_(null),o=is(),c=async()=>{if(e.confirmMessage&&!await o({title:e.label,message:e.confirmMessage,confirmLabel:e.buttonLabel,variant:e.variant==="danger"?"danger":"default"})||!n)return;const h=cu(e,t);i(!0),l(null);try{const f=await n("device-custom-action",e.action,h),p=typeof f=="object"&&f!==null?f:null;l({kind:"ok",text:e.successMessage?e.successMessage.replace(/\{(\w+)\}/g,(m,g)=>{const b=p?.[g];return b===void 0?"":String(b)}):"Done."})}catch(f){l({kind:"error",text:f instanceof Error?f.message:String(f)})}finally{i(!1)}},d={default:"border border-border text-foreground hover:bg-surface-hover",primary:"bg-primary text-primary-foreground hover:bg-primary/90",danger:"bg-danger text-white hover:bg-danger/90"};return u(Je,{label:e.label,description:e.description,required:e.required,span:e.span,children:v("div",{className:"flex flex-col gap-1.5",children:[u("button",{onClick:c,disabled:r||s,className:`inline-flex w-fit items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-colors disabled:opacity-50 ${d[e.variant??"default"]??d.default}`,children:s?"Working…":e.buttonLabel}),a&&u("div",{className:`text-[11px] ${a.kind==="ok"?"text-emerald-700 dark:text-emerald-300":"text-danger"}`,children:a.text})]})})}function EI({field:e}){const t=iN();return u(Je,{label:void 0,description:void 0,span:e.span,children:u(LL,{widgetId:e.widgetId,host:"device-tab",config:e.widgetConfig,deviceId:t??void 0,instanceId:e.key})})}function wI(e,t){if(e==null)return"—";if(typeof e=="boolean")return e?"yes":"no";if(typeof e=="number"){const r=Number.isInteger(e)?String(e):e.toFixed(2);return t?`${r} ${t}`:r}return typeof e=="string"?e:JSON.stringify(e)}function kI({field:e,values:t,onAction:r,translationFn:n}){const s="key"in e?e.key:void 0;if(!s)return null;const i=t[s],a=i!==void 0?i:"default"in e?e.default:void 0,l=wI(a,"unit"in e?e.unit:void 0),o="label"in e?e.label:void 0,c="description"in e?e.description:void 0,d="span"in e?e.span:void 0,h="actions"in e?e.actions??[]:[];return u(Je,{label:o,description:c,span:d,translationFn:n,children:v("div",{className:"flex items-stretch gap-1",children:[u("div",{className:"flex-1 rounded-md border border-border bg-surface-alt px-2.5 py-1.5 text-xs text-foreground font-mono break-all",children:l}),h.length>0&&u("div",{className:"flex items-center gap-1",children:h.map(f=>u(AI,{action:f,fieldKey:s,value:a,onAction:r},f.action))})]})})}function TI({name:e}){const t="h-3.5 w-3.5";switch(e){case"copy":return u(zr,{className:t});case"refresh-cw":return u(vn,{className:t});case"external-link":return u(ym,{className:t});case"trash-2":return u(zt,{className:t});case"download":return u(Fs,{className:t});case"upload":return u(Dm,{className:t});default:return u(DE,{className:t})}}function AI({action:e,fieldKey:t,value:r,onAction:n}){const s=is(),[i,a]=_(!1),l=e.variant==="danger"?"text-danger hover:bg-danger/10 border-danger/30":e.variant==="primary"?"text-primary hover:bg-primary/10 border-primary/30":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover border-border";return u("button",{type:"button",onClick:async()=>{if(!(e.confirmMessage&&!await s({title:e.tooltip,message:e.confirmMessage,variant:e.variant==="danger"?"danger":"default"}))){if(e.action==="copy-value"){try{await navigator.clipboard.writeText(typeof r=="string"?r:String(r))}catch{}return}if(n){a(!0);try{await n(e.action,t)}finally{a(!1)}}}},disabled:i,title:e.tooltip,className:`inline-flex items-center justify-center rounded-md border px-2 py-1.5 transition-colors disabled:opacity-50 ${l}`,children:u(TI,{name:e.icon})})}function CI(e){return"multiple"in e&&e.multiple!=null}function NI({field:e,values:t,onChange:r,disabled:n,translationFn:s,onTestField:i,externalProbe:a,allFields:l,onAction:o}){const c=e.multiple,d=c.min,h=c.max,f=t[e.key],p=[...Array.isArray(f)?f:f!=null?[f]:[]],m=c.itemDefault!==void 0?c.itemDefault:"default"in e&&e.default!==void 0?e.default:"";for(;p.length<d;)p.push(m);const g=k=>r(e.key,[...k]),b=(k,T)=>{const A=[...p];A[k]=T,g(A)},y=()=>{p.length>=h||g([...p,m])},S=k=>{p.length<=d||g(p.filter((T,A)=>A!==k))},E=()=>{const{multiple:k,...T}=e;return{...T,...{label:void 0,description:void 0,required:!1}}};return u(Je,{label:e.label,description:e.description,required:d>0?e.required:!1,span:e.span,translationFn:s,children:v("div",{className:"space-y-2",children:[p.map((k,T)=>{const A=c.itemLabel?.replace("${n}",String(T+1));return v("div",{className:"space-y-1",children:[A&&u("div",{className:_a,children:A}),v("div",{className:"flex items-center gap-2",children:[u("div",{className:"flex-1 min-w-0",children:u(ei,{field:E(),values:{...t,[e.key]:k},onChange:(N,C)=>b(T,C),disabled:n,translationFn:s,onTestField:i,onAction:o,allFields:l})}),p.length>d&&u("button",{type:"button",onClick:()=>S(T),disabled:n,title:"Remove",className:"flex-shrink-0 inline-flex items-center justify-center rounded-md border border-border p-1.5 text-foreground-subtle hover:text-danger hover:border-danger/50 transition-colors disabled:opacity-40",children:u(zt,{className:"h-3.5 w-3.5"})})]})]},T)}),v("div",{className:"flex items-center justify-between pt-1",children:[p.length<h?v("button",{type:"button",onClick:y,disabled:n,className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-40",children:[u(gn,{className:"h-3 w-3"}),c.addLabel??"Add"]}):u("span",{}),v("span",{className:"text-[10px] text-foreground-subtle tabular-nums",children:[p.length,"/",h]})]})]})})}function LI(e,t,r){if(!("showWhen"in e)||!e.showWhen)return!0;const n=e.showWhen,s=t[n.field],i=r?.find(o=>"key"in o&&o.key===n.field),a=i&&"default"in i?i.default:void 0,l=s!==void 0?s:a;return n.equals!==void 0?l===n.equals:n.notEquals!==void 0?l!==n.notEquals:n.in!==void 0?n.in.includes(l):n.notIn!==void 0?!n.notIn.includes(l):n.includes!==void 0?Array.isArray(l)&&l.includes(n.includes):n.notIncludes!==void 0?!Array.isArray(l)||!l.includes(n.notIncludes):!0}function ei({field:e,values:t,onChange:r,disabled:n,translationFn:s,onTestField:i,externalProbe:a,allFields:l,onAction:o}){if(CI(e))return u(NI,{field:e,values:t,onChange:r,disabled:n,translationFn:s,onTestField:i,externalProbe:a,allFields:l,onAction:o});if("readonlyField"in e&&e.readonlyField===!0)return u(kI,{field:e,values:t,onAction:o,translationFn:s});if(!LI(e,t,l))return null;const c=t[e.key],d=c!==void 0?c:"default"in e?e.default:void 0,h=p=>r(e.key,p),f=sN(e.type);switch(e.type){case"text":return u(zL,{field:e,value:d,onChange:h,disabled:n,translationFn:s});case"number":return u(WL,{field:e,value:d,onChange:h,disabled:n,translationFn:s});case"boolean":return u(QL,{field:e,value:d,onChange:h,disabled:n,translationFn:s});case"select":return u(qL,{field:e,value:d,onChange:h,disabled:n,translationFn:s});case"multiselect":return u(ZL,{field:e,value:d,onChange:h,disabled:n,translationFn:s});case"timezone":return u(YL,{field:e,value:d,onChange:h,disabled:n,translationFn:s});case"datetime":return u(XL,{field:e,value:d,onChange:h,disabled:n,translationFn:s});case"password":return u(JL,{field:e,value:d,onChange:h,disabled:n,translationFn:s});case"textarea":return u(eI,{field:e,value:d,onChange:h,disabled:n,translationFn:s});case"slider":return u(tI,{field:e,value:d,onChange:h,disabled:n,translationFn:s});case"tags":return u(rI,{field:e,value:d,onChange:h,disabled:n,translationFn:s});case"color":return u(iI,{field:e,value:d,onChange:h,disabled:n,translationFn:s});case"node-select":return u(nI,{field:e,value:d,onChange:h,disabled:n,translationFn:s});case"node-multiselect":return u(sI,{field:e,value:d,onChange:h,disabled:n,translationFn:s});case"probe":return u(aI,{field:e,value:d,onChange:h,disabled:n,translationFn:s,onTestField:i,onAction:o,externalProbe:a});case"group":return u(oI,{field:e,values:t,onChange:r,disabled:n,translationFn:s,onTestField:i});case"sub-tabs":return u(lI,{field:e,values:t,onChange:r,disabled:n,translationFn:s,onTestField:i,onAction:o});case"separator":return u(cI,{});case"info":return u(dI,{field:e});case"qr-code":return u(hI,{field:e});case"object-array":return u(gI,{field:e});case"editable-array":return u(vI,{field:e,value:d,onChange:h,disabled:n,translationFn:s,onTestField:i,onAction:o});case"button":return u(bI,{field:e,disabled:n,onAction:o});case"addon-action-select":return u(yI,{field:e,value:d,values:t,onChange:h,disabled:n,onAction:o});case"addon-action-button":return u(xI,{field:e,values:t,disabled:n,onAction:o});case"device-action-button":return u(SI,{field:e,values:t,disabled:n,onAction:o});case"widget":return u(EI,{field:e});default:return f?u(f,{field:e,value:d,onChange:h,disabled:n}):null}}function II(e){return/^[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)+$/.test(e)}function rr(e,t){if(e!==void 0)return t&&II(e)?t(e):e}function RI({section:e,values:t,onChange:r,disabled:n,translationFn:s,onTestField:i,probeResults:a}){const[l,o]=_(e.defaultCollapsed??!1),c=e.style==="accordion",d=e.columns??2,h=d===1?"grid-cols-1":d===3?"grid-cols-1 @[480px]:grid-cols-2 @[880px]:grid-cols-3":d===4?"grid-cols-1 @[480px]:grid-cols-2 @[1140px]:grid-cols-4":"grid-cols-1 @[480px]:grid-cols-2";return v("div",{className:"@container rounded-lg border border-border bg-surface p-3",style:{containerType:"inline-size"},children:[v("div",{className:["flex items-center justify-between mb-2",c?"cursor-pointer":""].join(" "),onClick:c?()=>o(f=>!f):void 0,children:[v("div",{children:[u("h3",{className:"text-[11px] font-semibold text-foreground-subtle uppercase tracking-wider",children:rr(e.title,s)}),e.description&&u("p",{className:"text-[10px] text-foreground-subtle mt-0.5",children:rr(e.description,s)})]}),c&&u("span",{className:"text-foreground-subtle text-xs ml-2",children:l?"▸":"▾"})]}),!l&&u("div",{className:`grid ${h} gap-x-3 gap-y-2.5`,children:e.fields.map(f=>u(ei,{field:f,values:t,onChange:r,disabled:n,translationFn:s,onTestField:i,externalProbe:a?.[f.key]},f.key))})]})}function MI({schema:e,values:t,onChange:r,disabled:n,translationFn:s,onTestField:i,probeResults:a,onClearProbe:l}){const o=(c,d)=>{r({...t,[c]:d}),l?.(c)};return u("div",{className:"space-y-4",children:e.sections.map(c=>u(RI,{section:c,values:t,onChange:o,disabled:n,translationFn:s,onTestField:i,probeResults:a},c.id))})}var PI=({open:e})=>u("svg",{className:`h-3 w-3 transition-transform ${e?"rotate-90":""}`,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:u("polyline",{points:"9 18 15 12 9 6"})});function hh(e){const t={};if(!e)return t;for(const r of e.sections)for(const n of r.fields){if(n.type==="separator"||n.type==="info"||n.type==="button"||n.type==="group")continue;const s=n.key;t[s]=n.value}return t}function DI(e){return{...e,sections:e.sections.map(t=>({...t,fields:t.fields.map(r=>{if(r.type==="separator"||r.type==="info"||r.type==="button"||r.type==="group")return r;const{value:n,...s}=r;return s})}))}}function Sj({trpc:e,addonId:t,nodeId:r,title:n,disabled:s,onAfterChange:i,refreshToken:a,collapsible:l,defaultOpen:o,mode:c,onOverrideChange:d}){const h=c??"persist",[f,p]=_(null),[m,g]=_(!0),[b,y]=_(null),[S,E]=_(!1),[k,T]=_(o??!1),[A,N]=_({}),[C,M]=_(null);ae(()=>{M(null),N({})},[e,t,r,a,h]),ae(()=>{let U=!1;g(!0),y(null);const F=h==="override"&&Object.keys(A).length>0?A:void 0;return e.addonSettings.getGlobalSettings.query({addonId:t,nodeId:r,...F?{overlay:F}:{}}).then(Y=>{U||(p(Y),F||M(hh(Y)),g(!1))}).catch(Y=>{U||(y(Y instanceof Error?Y.message:String(Y)),g(!1))}),()=>{U=!0}},[e,t,r,a,h,JSON.stringify(A)]);const P=oe(()=>hh(f),[f]),D=oe(()=>f?DI(f):null,[f]),$=async U=>{if(h==="override"){const Y=C??P,I={};for(const O of Object.keys(U))U[O]!==Y[O]&&(I[O]=U[O]);const R={...Y,...I};N(I),d?.(I,R);return}const F={};for(const Y of Object.keys(U))U[Y]!==P[Y]&&(F[Y]=U[Y]);if(Object.keys(F).length!==0){E(!0);try{await e.addonSettings.updateGlobalSettings.mutate({addonId:t,nodeId:r,patch:F}),p(await e.addonSettings.getGlobalSettings.query({addonId:t,nodeId:r})),i?.()}catch(Y){y(Y instanceof Error?Y.message:String(Y))}finally{E(!1)}}};if(m)return v("div",{className:"text-xs text-foreground-subtle animate-pulse",children:["Loading ",n??t,"…"]});if(b)return v("div",{className:"text-xs text-red-400",children:[n??t,": ",b]});if(!f||!D)return v("div",{className:"text-xs text-foreground-subtle",children:[n??t," not available on ",r,"."]});const B=h==="override"?{...P,...A}:P,j=v(Ie,{children:[h==="override"?u("div",{className:"mb-2 text-[11px] text-foreground-subtle",children:"Benchmark override — applies to this run only. The addon's saved settings are not changed."}):null,u(MI,{schema:D,values:B,onChange:$,disabled:s===!0||S})]});return l===!0?v("section",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[v("button",{type:"button",onClick:()=>T(U=>!U),className:"w-full px-4 py-2 flex items-center gap-2 hover:bg-surface-hover text-left","aria-expanded":k,children:[u(PI,{open:k}),u("h3",{className:"text-xs font-semibold text-foreground uppercase tracking-wide flex-1",children:n??t}),u("span",{className:"text-[10px] text-foreground-subtle",children:k?"hide":"edit"})]}),k?u("div",{className:"border-t border-border px-4 py-3",children:j}):null]}):n?v("section",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[u("div",{className:"border-b border-border px-4 py-2",children:u("h3",{className:"text-xs font-semibold text-foreground uppercase tracking-wide",children:n})}),u("div",{className:"px-4 py-3",children:j})]}):u("div",{children:j})}function _I({detections:{motion:e,motionRaw:t,detection:r,phase:n},showMotionZones:s=!0,showMotionRaw:i=!0,showDetections:a=!0,showPhaseIndicator:l=!0}){const o=s&&e&&e.zones.length>0,c=i&&t&&t.boxes.length>0,d=a&&r&&r.detections.length>0;return!o&&!c&&!d&&!l?null:v("div",{className:"absolute inset-0 pointer-events-none z-10",children:[l&&u(OI,{phase:n}),c&&u(FI,{raw:t}),o&&u($I,{motion:e}),d&&u(BI,{detections:r.detections,frameWidth:r.frameWidth,frameHeight:r.frameHeight})]})}function OI({phase:e}){const t=Tp(e);return v("div",{className:"absolute top-2 left-2 flex items-center gap-1.5 px-2 py-1 rounded-md bg-black/60 backdrop-blur-sm",children:[u("span",{className:`w-2 h-2 rounded-full ${t.dotClass}`}),u("span",{className:"text-[10px] font-semibold text-white uppercase tracking-wider",children:t.label})]})}function FI({raw:e}){return e.frameWidth===0||e.frameHeight===0?null:u(Ie,{children:e.boxes.map((t,r)=>{const[n,s,i,a]=t.bbox,l=n/e.frameWidth*100,o=s/e.frameHeight*100,c=(i-n)/e.frameWidth*100,d=(a-s)/e.frameHeight*100,h=Math.max(.05,Math.min(.25,t.changeScore*.3));return u("div",{className:"absolute rounded-sm",style:{left:`${l}%`,top:`${o}%`,width:`${c}%`,height:`${d}%`,backgroundColor:`rgba(239, 68, 68, ${h})`}},`mr-${r}`)})})}function $I({motion:e}){return e.frameWidth===0||e.frameHeight===0?null:u(Ie,{children:e.zones.filter(t=>t.w*t.h/(e.frameWidth*e.frameHeight)<.9).map((t,r)=>{const n=Math.max(.15,Math.min(.5,t.intensity/255));return u("div",{className:"absolute rounded-sm",style:{left:`${t.x/e.frameWidth*100}%`,top:`${t.y/e.frameHeight*100}%`,width:`${t.w/e.frameWidth*100}%`,height:`${t.h/e.frameHeight*100}%`,border:`1px solid rgba(250, 204, 21, ${n})`,backgroundColor:`rgba(250, 204, 21, ${n*.15})`}},`mz-${r}`)})})}function BI({detections:e,frameWidth:t,frameHeight:r}){return t===0||r===0?null:u(Ie,{children:e.map(n=>{const{x:s,y:i,width:a,height:l}=n.bbox,o=s/t*100,c=i/r*100,d=a/t*100,h=l/r*100,f=Kt(n.macroClass),p=[`${n.macroClass} ${(n.score*100).toFixed(0)}%`];for(const m of n.labels)p.push(m.label);return u("div",{className:"absolute border-2 rounded-sm",style:{left:`${o}%`,top:`${c}%`,width:`${d}%`,height:`${h}%`,borderColor:f},children:u("div",{className:"absolute -top-4 left-0 px-1 py-0.5 text-[9px] font-bold text-white rounded-sm whitespace-nowrap",style:{backgroundColor:f},children:p.join(" | ")})},`det-${n.id}`)})})}function UI(){return typeof window>"u"?!1:window.matchMedia("(hover: none) and (pointer: coarse)").matches||typeof navigator<"u"&&navigator.maxTouchPoints>0||"ontouchstart"in window}function GI(e){const t={};if(typeof window<"u"){if(e){const n=e.getBoundingClientRect();n.width>0&&n.height>0&&(t.viewportWidth=Math.round(n.width),t.viewportHeight=Math.round(n.height))}t.viewportWidth===void 0&&(t.viewportWidth=window.innerWidth,t.viewportHeight=window.innerHeight),t.devicePixelRatio=window.devicePixelRatio||1;const r=navigator.connection;r?.downlink&&r.downlink>0&&(t.downlinkMbps=r.downlink)}return t}var HI=1500,VI=15e3,jI=40;function KI({serverUrl:e,streamKey:t,label:r,autoPlay:n=!0,muted:s=!0,showControls:i=!0,className:a="",onStateChange:l,onError:o,overlay:c,createSession:d,sendAnswer:h,handleOffer:f,getIceServers:p,addIceCandidate:m,getIceCandidates:g,closeSession:b,getSessionState:y,reoffer:S,posterUrl:E,hintsOverride:k}){const T=ne(null),A=ne(null),N=ne(null),C=ne(new Set),M=ne(null),P=ne(null),D=ne(0),$=ne(!0),B=ne(null),j=ne(null),U=ne(0),F=ne(!1),Y=ne(async()=>{}),[I,R]=_("idle"),[O,K]=_(""),[W,J]=_(s),[Q,ee]=_(!1),[ie,se]=_(!1),be=UI(),[ye,ue]=_(!0),we=ne(null),le=ne(!1);(h||d)&&(le.current=!0);const Z=le.current,ce=ne(!1);f&&(ce.current=!0);const Ae=ce.current,Re=q(re=>{R(re),l?.(re)},[l]),He=q(()=>{if(M.current?.abort(),M.current=null,P.current&&(clearTimeout(P.current),P.current=null),j.current&&(clearTimeout(j.current),j.current=null),B.current=null,F.current=!1,U.current=0,N.current&&(N.current.close(),N.current=null),b&&C.current.size>0){for(const re of C.current)b(re).catch(()=>{});C.current.clear()}T.current&&(T.current.srcObject=null)},[b]),ut=1e3,St=q(re=>{if(!y||!S)return;j.current&&(clearTimeout(j.current),j.current=null);const Se=async()=>{if($.current&&B.current===re){if(!F.current)try{const{pendingRenegotiation:ge}=await y(re);if($.current&&B.current===re&&ge&&ge.epoch>U.current&&!F.current){U.current=ge.epoch,await Y.current(re,ge.target);return}}catch{}!$.current||B.current!==re||(j.current=setTimeout(()=>{Se()},ut))}};j.current=setTimeout(()=>{Se()},ut)},[y,S]),Ue=q(async()=>{if(!$.current||!d||!h)return;He(),Re("connecting");const re=new AbortController;M.current=re;try{const{sessionId:Se,sdpOffer:ge,iceServers:rt}=await d({...GI(A.current),...k});if(C.current.add(Se),!$.current||re.signal.aborted){b?.(Se).catch(()=>{}),C.current.delete(Se);return}const de=new RTCPeerConnection({iceServers:[...rt??[],{urls:"stun:stun.l.google.com:19302"}]});N.current=de;const Oe=new MediaStream;de.ontrack=Ye=>{console.debug("[WebRTC] ontrack",Ye.track.kind,Ye.track.readyState),Oe.addTrack(Ye.track),T.current&&(T.current.srcObject=Oe,T.current.play().catch(()=>{}))},de.oniceconnectionstatechange=()=>{if(!$.current)return;const Ye=de.iceConnectionState;console.debug("[WebRTC] ICE state:",Ye),Ye==="connected"||Ye==="completed"?(D.current=0,Re("playing"),T.current?.paused&&(console.debug("[WebRTC] video was paused at ICE connected — calling play()"),T.current.play().catch(()=>{}))):(Ye==="failed"||Ye==="disconnected"||Ye==="closed")&&(Re("disconnected"),At())},de.onicecandidateerror=Ye=>{console.debug("[WebRTC] ICE candidate error:",Ye)},console.debug("[WebRTC] Setting remote description (server offer)..."),await de.setRemoteDescription({type:"offer",sdp:ge});const ft=await de.createAnswer();if(await de.setLocalDescription(ft),console.debug("[WebRTC] Local description set, waiting for ICE gathering..."),await fh(de),!$.current)return;const Ct=(de.localDescription?.sdp??"").split(`
85
+ `).filter(Ye=>Ye.startsWith("a=candidate:")).length;console.debug("[WebRTC] Sending answer to server",{localCandidates:Ct,sessionId:Se.slice(0,8)}),await h(Se,de.localDescription?.sdp??""),console.debug("[WebRTC] Answer sent successfully");const qr=de,Xe=()=>{const Ye=qr.connectionState;if(Ye==="closed"||Ye==="failed")return;const Ir=T.current;Ir&&Ir.readyState===0&&console.log(`[WebRTC] no video data yet (ice=${qr.iceConnectionState})`)};setTimeout(Xe,3e3),setTimeout(Xe,8e3)}catch(Se){if(!$.current)return;const ge=Se instanceof Error?Se.message:String(Se);K(ge),Re("error"),o?.(ge),At()}},[e,t,d,h,He,Re,o,k]),Ge=q(async()=>{if($.current){He(),Re("connecting");try{const re=new RTCPeerConnection({iceServers:[{urls:"stun:stun.l.google.com:19302"}]});N.current=re,re.addTransceiver("video",{direction:"recvonly"}),re.addTransceiver("audio",{direction:"recvonly"});const Se=new MediaStream;re.ontrack=ft=>{Se.addTrack(ft.track),T.current&&(T.current.srcObject=Se,T.current.play().catch(()=>{}))},re.oniceconnectionstatechange=()=>{if(!$.current)return;const ft=re.iceConnectionState;ft==="connected"||ft==="completed"?(D.current=0,Re("playing"),T.current?.paused&&T.current.play().catch(()=>{})):(ft==="failed"||ft==="disconnected"||ft==="closed")&&(Re("disconnected"),At())};const ge=await re.createOffer();if(await re.setLocalDescription(ge),await fh(re),!$.current)return;const rt=`${e}/api/webrtc?src=${encodeURIComponent(t)}`,de=await fetch(rt,{method:"POST",headers:{"Content-Type":"application/sdp"},body:re.localDescription?.sdp??""});if(!de.ok)throw new Error(`WHEP ${de.status}: ${de.statusText}`);const Oe=await de.text();await re.setRemoteDescription({type:"answer",sdp:Oe})}catch(re){if(!$.current)return;const Se=re instanceof Error?re.message:String(re);K(Se),Re("error"),o?.(Se),At()}}},[e,t,He,Re,o]),tt=q(async()=>{if(!$.current||!f)return;He(),Re("connecting");const re=new AbortController;M.current=re;try{const Se=await p?.();if(!$.current||re.signal.aborted)return;const ge=new RTCPeerConnection({iceServers:[...Se??[],{urls:"stun:stun.l.google.com:19302"}]});N.current=ge;const rt=new MediaStream;ge.ontrack=Xe=>{console.debug("[WebRTC] ontrack (client-offer)",Xe.track.kind,Xe.track.readyState),rt.addTrack(Xe.track),T.current&&(T.current.srcObject=rt,T.current.play().catch(()=>{}))},ge.oniceconnectionstatechange=()=>{if(!$.current)return;const Xe=ge.iceConnectionState;console.debug("[WebRTC] ICE state (client-offer):",Xe),Xe==="connected"||Xe==="completed"?(D.current=0,Re("playing"),T.current?.paused&&T.current.play().catch(()=>{})):(Xe==="failed"||Xe==="disconnected"||Xe==="closed")&&(Re("disconnected"),At())};let de=null;const Oe=[];ge.onicecandidate=Xe=>{if(!Xe.candidate)return;const Ye=Xe.candidate.toJSON();de&&m?m(de,Ye).catch(()=>{}):Oe.push(Ye)},ge.addTransceiver("video",{direction:"recvonly"}),ge.addTransceiver("audio",{direction:"recvonly"});const ft=await ge.createOffer();if(await ge.setLocalDescription(ft),!$.current||re.signal.aborted)return;const{sessionId:Ct,sdpAnswer:qr}=await f(ge.localDescription?.sdp??ft.sdp??"");if(de=Ct,C.current.add(Ct),B.current=Ct,!$.current||re.signal.aborted){b?.(Ct).catch(()=>{}),C.current.delete(Ct);return}if(m)for(const Xe of Oe)m(Ct,Xe).catch(()=>{});if(Oe.length=0,await ge.setRemoteDescription({type:"answer",sdp:qr}),console.debug("[WebRTC] Client-offer answer set (trickle)",{sessionId:Ct.slice(0,8)}),g){const Xe=new Set,Ye=Date.now(),Ir=async()=>{if(!(!$.current||re.signal.aborted||N.current!==ge)){try{const{candidates:Rr,done:Ba}=await g(Ct);for(const Yr of Rr){const yn=Yr.candidate??"";yn&&!Xe.has(yn)&&(Xe.add(yn),ge.addIceCandidate(new RTCIceCandidate(Yr)).catch(()=>{}))}const at=ge.iceConnectionState;if(Ba||Date.now()-Ye>1e4||at==="connected"||at==="completed")return}catch{}setTimeout(()=>{Ir()},200)}};Ir()}St(Ct)}catch(Se){if(!$.current)return;const ge=Se instanceof Error?Se.message:String(Se);K(ge),Re("error"),o?.(ge),At()}},[f,p,m,g,b,He,Re,o,St]);Y.current=q(async(re,Se)=>{const ge=S;if(!$.current||!ge)return;const rt=N.current;F.current=!0;try{const de=await p?.();if(!$.current)return;const Oe=new RTCPeerConnection({iceServers:[...de??[],{urls:"stun:stun.l.google.com:19302"}]}),ft=new MediaStream;let Ct=!1;const qr=()=>{Ct||!$.current||(Ct=!0,N.current=Oe,T.current&&(T.current.srcObject=ft,T.current.play().catch(()=>{})),rt&&rt!==Oe&&rt.close())};Oe.ontrack=at=>{console.debug("[WebRTC] ontrack (reoffer)",at.track.kind,at.track.readyState),ft.addTrack(at.track),qr()},Oe.oniceconnectionstatechange=()=>{if(!$.current)return;const at=Oe.iceConnectionState;console.debug("[WebRTC] ICE state (reoffer):",at),at==="connected"||at==="completed"?(D.current=0,qr(),Re("playing"),T.current?.paused&&T.current.play().catch(()=>{})):(at==="failed"||at==="closed")&&(!Ct&&at==="failed"&&Oe.close(),Re("disconnected"),At())};let Xe=null;const Ye=[];Oe.onicecandidate=at=>{if(!at.candidate)return;const Yr=at.candidate.toJSON();Xe&&m?m(Xe,Yr).catch(()=>{}):Ye.push(Yr)},Oe.addTransceiver("video",{direction:"recvonly"}),Oe.addTransceiver("audio",{direction:"recvonly"});const Ir=await Oe.createOffer();if(await Oe.setLocalDescription(Ir),!$.current){Oe.close();return}const{sessionId:Rr,sdpAnswer:Ba}=await ge(re,Oe.localDescription?.sdp??Ir.sdp??"",Se);if(!$.current){Oe.close();return}if(Xe=Rr,C.current.add(Rr),B.current=Rr,m)for(const at of Ye)m(Rr,at).catch(()=>{});if(Ye.length=0,await Oe.setRemoteDescription({type:"answer",sdp:Ba}),g){const at=new Set,Yr=Date.now(),yn=async()=>{if($.current&&!(Oe.connectionState==="closed"||Oe.signalingState==="closed")){try{const{candidates:$y,done:By}=await g(Rr);for(const Du of $y){const Ua=Du.candidate??"";Ua&&!at.has(Ua)&&(at.add(Ua),Oe.addIceCandidate(new RTCIceCandidate(Du)).catch(()=>{}))}const Pu=Oe.iceConnectionState;if(By||Date.now()-Yr>1e4||Pu==="connected"||Pu==="completed")return}catch{}setTimeout(()=>{yn()},200)}};yn()}St(Rr)}catch(de){console.debug("[WebRTC] reoffer failed; keeping last frame, re-arming poll",de instanceof Error?de.message:String(de)),St(re)}finally{F.current=!1}},[S,p,m,g,Re,St]);const We=Ae?tt:Z?Ue:Ge,Ht=ne(()=>{});Ht.current=We;const At=q(()=>{if(!$.current||D.current>=jI)return;const re=D.current;D.current+=1;const Se=Math.min(VI,HI*2**re),ge=Math.round(Se*(.8+Math.random()*.4));P.current=setTimeout(()=>{$.current&&Ht.current()},ge)},[]);ae(()=>($.current=!0,D.current=0,n&&We(),()=>{$.current=!1,He()}),[e,t]);const gr=ne(!1);ae(()=>{if(n){if(Ae){if(!f)return}else if(Z){if(!d||!h)return}else return;gr.current||N.current||(gr.current=!0,We())}},[n,Ae,Z,f,d,h,We]);const Qr=()=>{D.current=0,We()},H=()=>{T.current&&(T.current.muted=!T.current.muted,J(T.current.muted))},me=async()=>{if(A.current)try{if(document.fullscreenElement){await document.exitFullscreen();return}if(A.current.requestFullscreen){await A.current.requestFullscreen();return}const re=T.current;re?.webkitEnterFullscreen&&re.webkitEnterFullscreen()}catch(re){console.warn(`Fullscreen toggle failed: ${re instanceof Error?re.message:re}`)}},ke=async()=>{const re=T.current;if(re)try{if(typeof re.webkitSetPresentationMode=="function"){re.webkitSetPresentationMode(re.webkitPresentationMode==="picture-in-picture"?"inline":"picture-in-picture");return}document.pictureInPictureElement?await document.exitPictureInPicture():await re.requestPictureInPicture()}catch(Se){console.warn(`PiP toggle failed: ${Se instanceof Error?Se.message:String(Se)}`)}},Ne=()=>{if(!T.current)return;const re=document.createElement("canvas");re.width=T.current.videoWidth||1280,re.height=T.current.videoHeight||720;const Se=re.getContext("2d");if(!Se)return;Se.drawImage(T.current,0,0);const ge=document.createElement("a");ge.download=`${t.replace(/[/:]/g,"-")}-${Date.now()}.jpg`,ge.href=re.toDataURL("image/jpeg",.92),ge.click()};ae(()=>{const re=()=>ee(!!document.fullscreenElement);document.addEventListener("fullscreenchange",re);const Se=T.current;return Se?.addEventListener("webkitbeginfullscreen",re),Se?.addEventListener("webkitendfullscreen",re),()=>{document.removeEventListener("fullscreenchange",re),Se?.removeEventListener("webkitbeginfullscreen",re),Se?.removeEventListener("webkitendfullscreen",re)}},[]),ae(()=>{const re=T.current,Se=typeof document<"u"&&document.pictureInPictureEnabled===!0,ge=re!==null&&typeof re.webkitSetPresentationMode=="function";se(Se||ge)},[]);const Ve=()=>{be||(ue(!0),we.current&&clearTimeout(we.current),we.current=setTimeout(()=>ue(!1),3e3))},Te=()=>{ue(re=>!re),we.current&&clearTimeout(we.current)};return v("div",{ref:A,className:`relative isolate bg-black overflow-hidden group ${a}`,onMouseMove:Ve,onMouseEnter:Ve,onTouchStart:Te,children:[u("video",{ref:T,autoPlay:n,muted:W,playsInline:!0,...E?{poster:E}:{},className:"w-full h-full object-contain relative z-0"}),r&&I==="playing"&&u("div",{className:"absolute top-2 left-2 z-10 transform-gpu px-2 py-0.5 rounded bg-black/60 text-[10px] text-white font-medium",children:r}),c,I==="connecting"&&v("div",{className:"absolute inset-0 z-10 transform-gpu flex flex-col items-center justify-center bg-black/70 gap-2",children:[u("svg",{className:"h-6 w-6 text-white/60 animate-spin",viewBox:"0 0 24 24",fill:"none",children:u("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeDasharray:"32",strokeDashoffset:"32",className:"animate-[dash_1.5s_ease-in-out_infinite]"})}),u("span",{className:"text-xs text-white/60",children:"Connecting…"})]}),(I==="error"||I==="disconnected")&&v("div",{className:"absolute inset-0 z-10 transform-gpu flex flex-col items-center justify-center bg-black/70 gap-2",children:[u("svg",{className:"h-6 w-6 text-red-400",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:u("path",{d:"M1 1l5.5 5.5M23 23l-5.5-5.5M8.11 15.89a8 8 0 0110.78-10.78M3.64 3.64A12 12 0 0020.36 20.36",strokeLinecap:"round"})}),u("span",{className:"text-xs text-red-400 text-center px-4",children:I==="error"?O||"Connection failed":"Disconnected"}),u("button",{onClick:Qr,className:"mt-1 inline-flex items-center gap-1.5 rounded px-3 py-1 text-xs bg-white/10 text-white hover:bg-white/20 transition-colors",children:"Reconnect"})]}),i&&I!=="idle"&&I!=="error"&&v("div",{className:`absolute bottom-0 inset-x-0 z-20 transform-gpu flex items-center justify-between px-3 py-1.5 bg-gradient-to-t from-black/80 to-transparent transition-opacity duration-200 ${be||ye?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none"}`,children:[u("div",{className:"flex items-center gap-1",children:u(fi,{onClick:H,title:W?"Unmute":"Mute",children:W?v("svg",{className:"h-3.5 w-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[u("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),u("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),u("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]}):v("svg",{className:"h-3.5 w-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[u("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),u("path",{d:"M19.07 4.93a10 10 0 010 14.14M15.54 8.46a5 5 0 010 7.07"})]})})}),v("div",{className:"flex items-center gap-1",children:[u(fi,{onClick:Ne,title:"Take snapshot",children:v("svg",{className:"h-3.5 w-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[u("path",{d:"M23 19a2 2 0 01-2 2H3a2 2 0 01-2-2V8a2 2 0 012-2h4l2-3h6l2 3h4a2 2 0 012 2z"}),u("circle",{cx:"12",cy:"13",r:"4"})]})}),ie&&u(fi,{onClick:ke,title:"Picture-in-Picture",children:v("svg",{className:"h-3.5 w-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u("path",{d:"M21 9V6a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2h4"}),u("rect",{width:"10",height:"7",x:"12",y:"13",rx:"2"})]})}),u(fi,{onClick:me,title:Q?"Exit fullscreen":"Fullscreen",children:Q?u("svg",{className:"h-3.5 w-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:u("path",{d:"M8 3v3a2 2 0 01-2 2H3m18 0h-3a2 2 0 01-2-2V3m0 18v-3a2 2 0 012-2h3M3 16h3a2 2 0 012 2v3"})}):u("svg",{className:"h-3.5 w-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:u("path",{d:"M8 3H5a2 2 0 00-2 2v3m18 0V5a2 2 0 00-2-2h-3m0 18h3a2 2 0 002-2v-3M3 16v3a2 2 0 002 2h3"})})})]})]})]})}function fi({onClick:e,title:t,children:r}){return u("button",{onClick:e,title:t,className:"rounded-full p-1.5 min-w-[44px] min-h-[44px] flex items-center justify-center text-white/80 hover:text-white hover:bg-white/20 active:bg-white/30 transition-colors",children:r})}async function fh(e){if(e.iceGatheringState!=="complete")return new Promise(t=>{let r=!1,n;const s=()=>{r||(r=!0,n&&clearInterval(n),e.removeEventListener("icegatheringstatechange",i),t())},i=()=>{e.iceGatheringState==="complete"&&s()};e.addEventListener("icegatheringstatechange",i);const a=Date.now();n=setInterval(()=>{const l=e.localDescription?.sdp??"";/ typ host/.test(l)&&Date.now()-a>=600&&s()},100),setTimeout(s,2500)})}var he=Number.isFinite||function(e){return typeof e=="number"&&isFinite(e)},zI=Number.isSafeInteger||function(e){return typeof e=="number"&&Math.abs(e)<=WI},WI=Number.MAX_SAFE_INTEGER||9007199254740991,xe=(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})({}),G=(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})({}),w=(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})({}),Fe={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},fe={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},kn=class{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_}},QI=class{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 kn(e),this.fast_=new kn(t),this.defaultTTFB_=n,this.ttfb_=new kn(e)}update(e,t){const{slow_:r,fast_:n,ttfb_:s}=this;r.halfLife!==e&&(this.slow_=new kn(e,r.getEstimate(),r.getTotalWeight())),n.halfLife!==t&&(this.fast_=new kn(t,n.getEstimate(),n.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new kn(e,s.getEstimate(),s.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const r=8*t,n=e/1e3,s=r/n;this.fast_.sample(n,s),this.slow_.sample(n,s)}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 qI(e,t,r){return(t=XI(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ze(){return ze=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},ze.apply(null,arguments)}function ph(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function je(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?ph(Object(r),!0).forEach(function(n){qI(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ph(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function YI(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function XI(e){var t=YI(e,"string");return typeof t=="symbol"?t:t+""}var qt=class{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=Fr,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)}},Fr=function(){},ZI={trace:Fr,debug:Fr,log:Fr,warn:Fr,info:Fr,error:Fr};function Kl(){return ze({},ZI)}function JI(e,t){const r=self.console[e];return r?r.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):Fr}function mh(e,t,r){return t[e]?t[e].bind(t):JI(e,r)}var zl=Kl();function eR(e,t,r){const n=Kl();if(typeof console=="object"&&e===!0||typeof e=="object"){const s=["debug","log","info","warn","error"];s.forEach(i=>{n[i]=mh(i,e,r)});try{n.log(`Debug logs enabled for "${t}" in hls.js version 1.6.16`)}catch{return Kl()}s.forEach(i=>{zl[i]=mh(i,e)})}else ze(zl,n);return n}var Ke=zl;function Vr(e=!0){if(!(typeof self>"u"))return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function tR(e){return typeof self<"u"&&e===self.ManagedMediaSource}function Xv(e,t){const r=Object.keys(e),n=Object.keys(t),s=r.length,i=n.length;return!s||!i||s===i&&!r.some(a=>n.indexOf(a)===-1)}function Bt(e,t=!1){if(typeof TextDecoder<"u"){const o=new TextDecoder("utf-8").decode(e);if(t){const c=o.indexOf("\0");return c!==-1?o.substring(0,c):o}return o.replace(/\0/g,"")}const r=e.length;let n,s,i,a="",l=0;for(;l<r;){if(n=e[l++],n===0&&t)return a;if(n===0||n===3)continue;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:s=e[l++],a+=String.fromCharCode((n&31)<<6|s&63);break;case 14:s=e[l++],i=e[l++],a+=String.fromCharCode((n&15)<<12|(s&63)<<6|(i&63)<<0);break}}return a}function wt(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 Zv(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function rR(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ro={exports:{}},gh;function nR(){return gh||(gh=1,(function(e,t){(function(r){var n=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,l={buildAbsoluteURL:function(o,c,d){if(d=d||{},o=o.trim(),c=c.trim(),!c){if(!d.alwaysNormalize)return o;var h=l.parseURL(o);if(!h)throw new Error("Error trying to parse base URL.");return h.path=l.normalizePath(h.path),l.buildURLFromParts(h)}var f=l.parseURL(c);if(!f)throw new Error("Error trying to parse relative URL.");if(f.scheme)return d.alwaysNormalize?(f.path=l.normalizePath(f.path),l.buildURLFromParts(f)):c;var p=l.parseURL(o);if(!p)throw new Error("Error trying to parse base URL.");if(!p.netLoc&&p.path&&p.path[0]!=="/"){var m=s.exec(p.path);p.netLoc=m[1],p.path=m[2]}p.netLoc&&!p.path&&(p.path="/");var g={scheme:p.scheme,netLoc:f.netLoc,path:null,params:f.params,query:f.query,fragment:f.fragment};if(!f.netLoc&&(g.netLoc=p.netLoc,f.path[0]!=="/"))if(!f.path)g.path=p.path,f.params||(g.params=p.params,f.query||(g.query=p.query));else{var b=p.path,y=b.substring(0,b.lastIndexOf("/")+1)+f.path;g.path=l.normalizePath(y)}return g.path===null&&(g.path=d.alwaysNormalize?l.normalizePath(f.path):f.path),l.buildURLFromParts(g)},parseURL:function(o){var c=n.exec(o);return c?{scheme:c[1]||"",netLoc:c[2]||"",path:c[3]||"",params:c[4]||"",query:c[5]||"",fragment:c[6]||""}:null},normalizePath:function(o){for(o=o.split("").reverse().join("").replace(i,"");o.length!==(o=o.replace(a,"")).length;);return o.split("").reverse().join("")},buildURLFromParts:function(o){return o.scheme+o.netLoc+o.path+o.params+o.query+o.fragment}};e.exports=l})()})(Ro)),Ro.exports}var uu=nR(),du=class{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}}},Qe={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},Jv=class{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,iR(this,"stats")}setByteRange(e,t){const r=e.split("@",2);let n;r.length===1?n=t?.byteRangeEndOffset||0:n=parseInt(r[1]),this._byteRange=[n,parseInt(r[0])+n]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[Qe.AUDIO]:null,[Qe.VIDEO]:null,[Qe.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new du),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=uu.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[Qe.AUDIO]=null,e[Qe.VIDEO]=null,e[Qe.AUDIOVIDEO]=null}};function lt(e){return e.sn!=="initSegment"}var Mo=class extends Jv{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(he(e)&&he(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const r=Object.keys(t);if(r.length===1){const n=this._decryptdata=t[r[0]]||null;n&&(this._decryptdata=n.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=he(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const r=Object.keys(this.levelkeys),n=r.length;if(n>1||n===1&&(t=this.levelkeys[r[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!he(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return lt(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&&!((r=this._decryptdata)!=null&&r.keyId)&&(this._decryptdata=n.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,r,n,s,i=!1){const{elementaryStreams:a}=this,l=a[e];if(!l){a[e]={startPTS:t,endPTS:r,startDTS:n,endDTS:s,partial:i};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,r),l.startDTS=Math.min(l.startDTS,n),l.endDTS=Math.max(l.endDTS,s)}},sR=class extends Jv{constructor(e,t,r,n,s){super(r),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=n;const i=e.enumeratedString("BYTERANGE");i&&this.setByteRange(i,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}};function eb(e,t){const r=Object.getPrototypeOf(e);if(r){const n=Object.getOwnPropertyDescriptor(r,t);return n||eb(r,t)}}function iR(e,t){const r=eb(e,t);r&&(r.enumerable=!0,Object.defineProperty(e,t,r))}var vh=Math.pow(2,32)-1,aR=[].push,tb={video:1,audio:2,id3:3,text:4};function mt(e){return String.fromCharCode.apply(null,e)}function rb(e,t){const r=e[t]<<8|e[t+1];return r<0?65536+r:r}function Ce(e,t){const r=nb(e,t);return r<0?4294967296+r:r}function bh(e,t){let r=Ce(e,t);return r*=Math.pow(2,32),r+=Ce(e,t+4),r}function nb(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function oR(e){const t=e.byteLength;for(let r=0;r<t;){const n=Ce(e,r);if(n>8&&e[r+4]===109&&e[r+5]===111&&e[r+6]===111&&e[r+7]===102)return!0;r=n>1?r+n:t}return!1}function Pe(e,t){const r=[];if(!t.length)return r;const n=e.byteLength;for(let s=0;s<n;){const i=Ce(e,s),a=mt(e.subarray(s+4,s+8)),l=i>1?s+i:n;if(a===t[0])if(t.length===1)r.push(e.subarray(s+8,l));else{const o=Pe(e.subarray(s+8,l),t.slice(1));o.length&&aR.apply(r,o)}s=l}return r}function lR(e){const t=[],r=e[0];let n=8;const s=Ce(e,n);n+=4;let i=0,a=0;r===0?(i=Ce(e,n),a=Ce(e,n+4),n+=8):(i=bh(e,n),a=bh(e,n+8),n+=16),n+=2;let l=e.length+a;const o=rb(e,n);n+=2;for(let c=0;c<o;c++){let d=n;const h=Ce(e,d);d+=4;const f=h&2147483647;if((h&2147483648)>>>31===1)return Ke.warn("SIDX has hierarchical references (not supported)"),null;const p=Ce(e,d);d+=4,t.push({referenceSize:f,subsegmentDuration:p,info:{duration:p/s,start:l,end:l+f-1}}),l+=f,d+=4,n=d}return{earliestPresentationTime:i,timescale:s,version:r,referencesCount:o,references:t}}function sb(e){const t=[],r=Pe(e,["moov","trak"]);for(let n=0;n<r.length;n++){const s=r[n],i=Pe(s,["tkhd"])[0];if(i){let a=i[0];const l=Ce(i,a===0?12:20),o=Pe(s,["mdia","mdhd"])[0];if(o){a=o[0];const c=Ce(o,a===0?12:20),d=Pe(s,["mdia","hdlr"])[0];if(d){const h=mt(d.subarray(8,12)),f={soun:Qe.AUDIO,vide:Qe.VIDEO}[h],p=Pe(s,["mdia","minf","stbl","stsd"])[0],m=cR(p);f?(t[l]={timescale:c,type:f,stsd:m},t[f]=je({timescale:c,id:l},m)):t[l]={timescale:c,type:h,stsd:m}}}}}return Pe(e,["moov","mvex","trex"]).forEach(n=>{const s=t[Ce(n,4)];s&&(s.default={duration:Ce(n,12),flags:Ce(n,20)})}),t}function cR(e){const t=e.subarray(8),r=t.subarray(86),n=mt(t.subarray(4,8));let s=n,i;const a=n==="enca"||n==="encv";a&&Pe(Pe(t,[n])[0].subarray(n==="enca"?28:78),["sinf"]).forEach(o=>{const c=Pe(o,["schm"])[0];if(c){const d=mt(c.subarray(4,8));if(d==="cbcs"||d==="cenc"){const h=Pe(o,["frma"])[0];h&&(s=mt(h))}}});const l=s;switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const o=Pe(r,["avcC"])[0];o&&o.length>3&&(s+="."+mi(o[1])+mi(o[2])+mi(o[3]),i=pi(l==="avc1"?"dva1":"dvav",r));break}case"mp4a":{const o=Pe(t,[n])[0],c=Pe(o.subarray(28),["esds"])[0];if(c&&c.length>7){let d=4;if(c[d++]!==3)break;d=Po(c,d),d+=2;const h=c[d++];if(h&128&&(d+=2),h&64&&(d+=c[d++]),c[d++]!==4)break;d=Po(c,d);const f=c[d++];if(f===64)s+="."+mi(f);else break;if(d+=12,c[d++]!==5)break;d=Po(c,d);const p=c[d++];let m=(p&248)>>3;m===31&&(m+=1+((p&7)<<3)+((c[d]&224)>>5)),s+="."+m}break}case"hvc1":case"hev1":{const o=Pe(r,["hvcC"])[0];if(o&&o.length>12){const c=o[1],d=["","A","B","C"][c>>6],h=c&31,f=Ce(o,2),p=(c&32)>>5?"H":"L",m=o[12],g=o.subarray(6,12);s+="."+d+h,s+="."+uR(f).toString(16).toUpperCase(),s+="."+p+m;let b="";for(let y=g.length;y--;){const S=g[y];(S||b)&&(b="."+S.toString(16).toUpperCase()+b)}s+=b}i=pi(l=="hev1"?"dvhe":"dvh1",r);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":s=pi(s,r)||s;break;case"vp09":{const o=Pe(r,["vpcC"])[0];if(o&&o.length>6){const c=o[4],d=o[5],h=o[6]>>4&15;s+="."+or(c)+"."+or(d)+"."+or(h)}break}case"av01":{const o=Pe(r,["av1C"])[0];if(o&&o.length>2){const c=o[1]>>>5,d=o[1]&31,h=o[2]>>>7?"H":"M",f=(o[2]&64)>>6,p=(o[2]&32)>>5,m=c===2&&f?p?12:10:f?10:8,g=(o[2]&16)>>4,b=(o[2]&8)>>3,y=(o[2]&4)>>2,S=o[2]&3;s+="."+c+"."+or(d)+h+"."+or(m)+"."+g+"."+b+y+S+"."+or(1)+"."+or(1)+"."+or(1)+".0",i=pi("dav1",r)}break}}return{codec:s,encrypted:a,supplemental:i}}function pi(e,t){const r=Pe(t,["dvvC"]),n=r.length?r[0]:Pe(t,["dvcC"])[0];if(n){const s=n[2]>>1&127,i=n[2]<<5&32|n[3]>>3&31;return e+"."+or(s)+"."+or(i)}}function uR(e){let t=0;for(let r=0;r<32;r++)t|=(e>>r&1)<<31-r;return t>>>0}function Po(e,t){const r=t+5;for(;e[t++]&128&&t<r;);return t}function mi(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function or(e){return(e<10?"0":"")+e}function dR(e,t){if(!e||!t)return;const r=t.keyId;r&&t.isCommonEncryption&&ib(e,(n,s)=>{const i=n.subarray(8,24);i.some(a=>a!==0)||(Ke.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${wt(i)} -> ${wt(r)}`),n.set(r,8))})}function hR(e){const t=[];return ib(e,r=>t.push(r.subarray(8,24))),t}function ib(e,t){Pe(e,["moov","trak"]).forEach(r=>{const n=Pe(r,["mdia","minf","stbl","stsd"])[0];if(!n)return;const s=n.subarray(8);let i=Pe(s,["enca"]);const a=i.length>0;a||(i=Pe(s,["encv"])),i.forEach(l=>{Pe(a?l.subarray(28):l.subarray(78),["sinf"]).forEach(o=>{const c=ab(o);c&&t(c,a)})})})}function ab(e){const t=Pe(e,["schm"])[0];if(t){const r=mt(t.subarray(4,8));if(r==="cbcs"||r==="cenc"){const n=Pe(e,["schi","tenc"])[0];if(n)return n}}}function fR(e,t,r){const n={},s=Pe(e,["moof","traf"]);for(let i=0;i<s.length;i++){const a=s[i],l=Pe(a,["tfhd"])[0],o=Ce(l,4),c=t[o];if(!c)continue;n[o]||(n[o]={start:NaN,duration:0,sampleCount:0,timescale:c.timescale,type:c.type});const d=n[o],h=Pe(a,["tfdt"])[0];if(h){const E=h[0];let k=Ce(h,4);E===1&&(k===vh?r.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(k*=vh+1,k+=Ce(h,8))),he(k)&&(!he(d.start)||k<d.start)&&(d.start=k)}const f=c.default,p=Ce(l,0)|f?.flags;let m=f?.duration||0;p&8&&(p&2?m=Ce(l,12):m=Ce(l,8));const g=Pe(a,["trun"]);let b=d.start||0,y=0,S=m;for(let E=0;E<g.length;E++){const k=g[E],T=Ce(k,4),A=d.sampleCount;d.sampleCount+=T;const N=k[3]&1,C=k[3]&4,M=k[2]&1,P=k[2]&2,D=k[2]&4,$=k[2]&8;let B=8,j=T;for(N&&(B+=4),C&&T&&(!(k[B+1]&1)&&d.keyFrameIndex===void 0&&(d.keyFrameIndex=A),B+=4,M?(S=Ce(k,B),B+=4):S=m,P&&(B+=4),$&&(B+=4),b+=S,y+=S,j--);j--;)M?(S=Ce(k,B),B+=4):S=m,P&&(B+=4),D&&(k[B+1]&1||d.keyFrameIndex===void 0&&(d.keyFrameIndex=d.sampleCount-(j+1),d.keyFrameStart=b),B+=4),$&&(B+=4),b+=S,y+=S;!y&&m&&(y+=m*T)}d.duration+=y}if(!Object.keys(n).some(i=>n[i].duration)){let i=1/0,a=0;const l=Pe(e,["sidx"]);for(let o=0;o<l.length;o++){const c=lR(l[o]);if(c!=null&&c.references){i=Math.min(i,c.earliestPresentationTime/c.timescale);const d=c.references.reduce((h,f)=>h+f.info.duration||0,0);a=Math.max(a,d+c.earliestPresentationTime/c.timescale)}}a&&he(a)&&Object.keys(n).forEach(o=>{n[o].duration||(n[o].duration=a*n[o].timescale-n[o].start)})}return n}function pR(e){const t={valid:null,remainder:null},r=Pe(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}function Wt(e,t){const r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function yh(e,t){const r=[],n=t.samples,s=t.timescale,i=t.id;let a=!1;return Pe(n,["moof"]).map(l=>{const o=l.byteOffset-8;Pe(l,["traf"]).map(c=>{const d=Pe(c,["tfdt"]).map(h=>{const f=h[0];let p=Ce(h,4);return f===1&&(p*=Math.pow(2,32),p+=Ce(h,8)),p/s})[0];return d!==void 0&&(e=d),Pe(c,["tfhd"]).map(h=>{const f=Ce(h,4),p=Ce(h,0)&16777215,m=(p&1)!==0,g=(p&2)!==0,b=(p&8)!==0;let y=0;const S=(p&16)!==0;let E=0;const k=(p&32)!==0;let T=8;f===i&&(m&&(T+=8),g&&(T+=4),b&&(y=Ce(h,T),T+=4),S&&(E=Ce(h,T),T+=4),k&&(T+=4),t.type==="video"&&(a=Oa(t.codec)),Pe(c,["trun"]).map(A=>{const N=A[0],C=Ce(A,0)&16777215,M=(C&1)!==0;let P=0;const D=(C&4)!==0,$=(C&256)!==0;let B=0;const j=(C&512)!==0;let U=0;const F=(C&1024)!==0,Y=(C&2048)!==0;let I=0;const R=Ce(A,4);let O=8;M&&(P=Ce(A,O),O+=4),D&&(O+=4);let K=P+o;for(let W=0;W<R;W++){if($?(B=Ce(A,O),O+=4):B=y,j?(U=Ce(A,O),O+=4):U=E,F&&(O+=4),Y&&(N===0?I=Ce(A,O):I=nb(A,O),O+=4),t.type===Qe.VIDEO){let J=0;for(;J<U;){const Q=Ce(n,K);K+=4,mR(a,n[K])&&hu(n.subarray(K,K+Q),a?2:1,e+I/s,r),K+=Q,J+=Q+4}}e+=B/s}}))})})}),r}function Oa(e){if(!e)return!1;const t=e.substring(0,4);return t==="hvc1"||t==="hev1"||t==="dvh1"||t==="dvhe"}function mR(e,t){if(e){const r=t>>1&63;return r===39||r===40}else return(t&31)===6}function hu(e,t,r,n){const s=ob(e);let i=0;i+=t;let a=0,l=0,o=0;for(;i<s.length;){a=0;do{if(i>=s.length)break;o=s[i++],a+=o}while(o===255);l=0;do{if(i>=s.length)break;o=s[i++],l+=o}while(o===255);const c=s.length-i;let d=i;if(l<c)i+=l;else if(l>c){Ke.error(`Malformed SEI payload. ${l} is too small, only ${c} bytes left to parse.`);break}if(a===4){if(s[d++]===181){const h=rb(s,d);if(d+=2,h===49){const f=Ce(s,d);if(d+=4,f===1195456820){const p=s[d++];if(p===3){const m=s[d++],g=31&m,b=64&m,y=b?2+g*3:0,S=new Uint8Array(y);if(b){S[0]=m;for(let E=1;E<y;E++)S[E]=s[d++]}n.push({type:p,payloadType:a,pts:r,bytes:S})}}}}}else if(a===5&&l>16){const h=[];for(let m=0;m<16;m++){const g=s[d++].toString(16);h.push(g.length==1?"0"+g:g),(m===3||m===5||m===7||m===9)&&h.push("-")}const f=l-16,p=new Uint8Array(f);for(let m=0;m<f;m++)p[m]=s[d++];n.push({payloadType:a,pts:r,uuid:h.join(""),userData:Bt(p),userDataBytes:p})}}}function ob(e){const t=e.byteLength,r=[];let n=1;for(;n<t-2;)e[n]===0&&e[n+1]===0&&e[n+2]===3?(r.push(n+2),n+=2):n++;if(r.length===0)return e;const s=t-r.length,i=new Uint8Array(s);let a=0;for(n=0;n<s;a++,n++)a===r[0]&&(a++,r.shift()),i[n]=e[a];return i}function gR(e){const t=e[0];let r="",n="",s=0,i=0,a=0,l=0,o=0,c=0;if(t===0){for(;mt(e.subarray(c,c+1))!=="\0";)r+=mt(e.subarray(c,c+1)),c+=1;for(r+=mt(e.subarray(c,c+1)),c+=1;mt(e.subarray(c,c+1))!=="\0";)n+=mt(e.subarray(c,c+1)),c+=1;n+=mt(e.subarray(c,c+1)),c+=1,s=Ce(e,12),i=Ce(e,16),l=Ce(e,20),o=Ce(e,24),c=28}else if(t===1){c+=4,s=Ce(e,c),c+=4;const h=Ce(e,c);c+=4;const f=Ce(e,c);for(c+=4,a=2**32*h+f,zI(a)||(a=Number.MAX_SAFE_INTEGER,Ke.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),l=Ce(e,c),c+=4,o=Ce(e,c),c+=4;mt(e.subarray(c,c+1))!=="\0";)r+=mt(e.subarray(c,c+1)),c+=1;for(r+=mt(e.subarray(c,c+1)),c+=1;mt(e.subarray(c,c+1))!=="\0";)n+=mt(e.subarray(c,c+1)),c+=1;n+=mt(e.subarray(c,c+1)),c+=1}const d=e.subarray(c,e.byteLength);return{schemeIdUri:r,value:n,timeScale:s,presentationTime:a,presentationTimeDelta:i,eventDuration:l,id:o,payload:d}}function vR(e,...t){const r=t.length;let n=8,s=r;for(;s--;)n+=t[s].byteLength;const i=new Uint8Array(n);for(i[0]=n>>24&255,i[1]=n>>16&255,i[2]=n>>8&255,i[3]=n&255,i.set(e,4),s=0,n=8;s<r;s++)i.set(t[s],n),n+=t[s].byteLength;return i}function bR(e,t,r){if(e.byteLength!==16)throw new RangeError("Invalid system id");let n,s;n=0,s=new Uint8Array;let i;n>0?(i=new Uint8Array(4),t.length>0&&new DataView(i.buffer).setUint32(0,t.length,!1)):i=new Uint8Array;const a=new Uint8Array(4);return r.byteLength>0&&new DataView(a.buffer).setUint32(0,r.byteLength,!1),vR([112,115,115,104],new Uint8Array([n,0,0,0]),e,i,s,a,r)}function yR(e){const t=[];if(e instanceof ArrayBuffer){const r=e.byteLength;let n=0;for(;n+32<r;){const s=xR(new DataView(e,n));t.push(s),n+=s.size}}return t}function xR(e){const t=e.getUint32(0),r=e.byteOffset,n=e.byteLength;if(n<t)return{offset:r,size:n};if(e.getUint32(4)!==1886614376)return{offset:r,size:t};const s=e.getUint32(8)>>>24;if(s!==0&&s!==1)return{offset:r,size:t};const i=e.buffer,a=wt(new Uint8Array(i,r+12,16));let l=null,o=null,c=0;if(s===0)c=28;else{const h=e.getUint32(28);if(!h||n<32+h*16)return{offset:r,size:t};l=[];for(let f=0;f<h;f++)l.push(new Uint8Array(i,r+32+f*16,16));c=32+h*16}if(!c)return{offset:r,size:t};const d=e.getUint32(c);return t-32<d?{offset:r,size:t}:(o=new Uint8Array(i,r+c+4,d),{version:s,systemId:a,kids:l,data:o,offset:r,size:t})}var lb=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Jn={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 fu(e,t){const r=Jn[t];return!!r&&!!r[e.slice(0,4)]}function Vs(e,t,r=!0){return!e.split(",").some(n=>!pu(n,t,r))}function pu(e,t,r=!0){var n;const s=Vr(r);return(n=s?.isTypeSupported(js(e,t)))!=null?n:!1}function js(e,t){return`${t}/mp4;codecs=${e}`}function xh(e){if(e){const t=e.substring(0,4);return Jn.video[t]}return 2}function pa(e){const t=lb();return e.split(",").reduce((r,n)=>{const s=t&&Oa(n)?9:Jn.video[n];return s?(s*2+r)/(r?3:2):(Jn.audio[n]+r)/(r?2:1)},0)}var Do={};function SR(e,t=!0){if(Do[e])return Do[e];const r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let s=0;s<r.length;s++){var n;if(pu(r[s],"audio",t))return Do[e]=r[s],r[s];if(r[s]==="mp3"&&(n=Vr(t))!=null&&n.isTypeSupported("audio/mpeg"))return""}return e}var ER=/flac|opus|mp4a\.40\.34/i;function ma(e,t=!0){return e.replace(ER,r=>SR(r.toLowerCase(),t))}function wR(e,t){const r=[];if(e){const n=e.split(",");for(let s=0;s<n.length;s++)fu(n[s],"video")||r.push(n[s])}return t&&r.push(t),r.join(",")}function Hi(e,t){if(e&&(e.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e)!==-1)&&(Sh(e,"audio")||Sh(e,"video")))return e;if(t){const r=t.split(",");if(r.length>1){if(e){for(let n=r.length;n--;)if(r[n].substring(0,4)===e.substring(0,4))return r[n]}return r[0]}}return t||e}function Sh(e,t){return fu(e,t)&&pu(e,t)}function kR(e){const t=e.split(",");for(let r=0;r<t.length;r++){const n=t[r].split(".");n.length>2&&n[0]==="avc1"&&(t[r]=`avc1.${parseInt(n[1]).toString(16)}${("000"+parseInt(n[2]).toString(16)).slice(-4)}`)}return t.join(",")}function TR(e){if(e.startsWith("av01.")){const t=e.split("."),r=["0","111","01","01","01","0"];for(let n=t.length;n>4&&n<10;n++)t[n]=r[n-4];return t.join(".")}return e}function Eh(e){const t=Vr(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 Wl(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var AR={supported:!0,powerEfficient:!0,smooth:!0},CR={supported:!1,smooth:!1,powerEfficient:!1},cb={supported:!0,configurations:[],decodingInfoResults:[AR]};function ub(e,t){return{supported:!1,configurations:t,decodingInfoResults:[CR],error:e}}function NR(e,t,r,n,s,i){const a=e.videoCodec,l=e.audioCodec?e.audioGroups:null,o=i?.audioCodec,c=i?.channels,d=c?parseInt(c):o?1/0:2;let h=null;if(l!=null&&l.length)try{l.length===1&&l[0]?h=t.groups[l[0]].channels:h=l.reduce((f,p)=>{if(p){const m=t.groups[p];if(!m)throw new Error(`Audio track group ${p} not found`);Object.keys(m.channels).forEach(g=>{f[g]=(f[g]||0)+m.channels[g]})}return f},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(f=>Oa(f))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(n,30)||e.videoRange!=="SDR"&&e.videoRange!==r||e.bitrate>Math.max(s,8e6))||!!h&&he(d)&&Object.keys(h).some(f=>parseInt(f)>d)}function db(e,t,r,n={}){const s=e.videoCodec;if(!s&&!e.audioCodec||!r)return Promise.resolve(cb);const i=[],a=LR(e),l=a.length,o=IR(e,t,l>0),c=o.length;for(let d=l||1*c||1;d--;){const h={type:"media-source"};if(l&&(h.video=a[d%l]),c){h.audio=o[d%c];const f=h.audio.bitrate;h.video&&f&&(h.video.bitrate-=f)}i.push(h)}if(s){const d=navigator.userAgent;if(s.split(",").some(h=>Oa(h))&&lb())return Promise.resolve(ub(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${d})`),i))}return Promise.all(i.map(d=>{const h=MR(d);return n[h]||(n[h]=r.decodingInfo(d))})).then(d=>({supported:!d.some(h=>!h.supported),configurations:i,decodingInfoResults:d})).catch(d=>({supported:!1,configurations:i,decodingInfoResults:[],error:d}))}function LR(e){var t;const r=(t=e.videoCodec)==null?void 0:t.split(","),n=hb(e),s=e.width||640,i=e.height||480,a=e.frameRate||30,l=e.videoRange.toLowerCase();return r?r.map(o=>{const c={contentType:js(TR(o),"video"),width:s,height:i,bitrate:n,framerate:a};return l!=="sdr"&&(c.transferFunction=l),c}):[]}function IR(e,t,r){var n;const s=(n=e.audioCodec)==null?void 0:n.split(","),i=hb(e);return s&&e.audioGroups?e.audioGroups.reduce((a,l)=>{var o;const c=l?(o=t.groups[l])==null?void 0:o.tracks:null;return c?c.reduce((d,h)=>{if(h.groupId===l){const f=parseFloat(h.channels||"");s.forEach(p=>{const m={contentType:js(p,"audio"),bitrate:r?RR(p,i):i};f&&(m.channels=""+f),d.push(m)})}return d},a):a},[]):[]}function RR(e,t){if(t<=1)return 1;let r=128e3;return e==="ec-3"?r=768e3:e==="ac-3"&&(r=64e4),Math.min(t/2,r)}function hb(e){return Math.ceil(Math.max(e.bitrate*.9,e.averageBitrate)/1e3)*1e3||1}function MR(e){let t="";const{audio:r,video:n}=e;if(n){const s=Wl(n.contentType);t+=`${s}_r${n.height}x${n.width}f${Math.ceil(n.framerate)}${n.transferFunction||"sd"}_${Math.ceil(n.bitrate/1e5)}`}if(r){const s=Wl(r.contentType);t+=`${n?"_":""}${s}_c${r.channels}`}return t}var Ql=["NONE","TYPE-0","TYPE-1",null];function PR(e){return Ql.indexOf(e)>-1}var ga=["SDR","PQ","HLG"];function DR(e){return!!e&&ga.indexOf(e)>-1}var Vi={No:"",Yes:"YES",v2:"v2"};function wh(e){const{canSkipUntil:t,canSkipDateRanges:r,age:n}=e,s=n<t/2;return t&&s?r?Vi.v2:Vi.Yes:Vi.No}var kh=class{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 this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}},Ks=class{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(r=>!!r).map(r=>r.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const r=(t=e.supplemental)==null?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 Th(this._audioGroups,e)}hasSubtitleGroup(e){return Th(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let r=this._audioGroups;r||(r=this._audioGroups=[]),r.indexOf(t)===-1&&r.push(t)}else if(e==="text"){let r=this._subtitleGroups;r||(r=this._subtitleGroups=[]),r.indexOf(t)===-1&&r.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(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}};function Th(e,t){return!t||!e?!1:e.indexOf(t)!==-1}function _R(){if(typeof matchMedia=="function"){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return e.matches===!0}return!1}function OR(e,t){let r=!1,n=[];if(e&&(r=e!=="SDR",n=[e]),t){n=t.allowedVideoRanges||ga.slice(0);const s=n.join("")!=="SDR"&&!t.videoCodec;r=t.preferHDR!==void 0?t.preferHDR:s&&_R(),r||(n=["SDR"])}return{preferHDR:r,allowedVideoRanges:n}}var FR=e=>{const t=new WeakSet;return(r,n)=>{if(e&&(n=e(r,n)),typeof n=="object"&&n!==null){if(t.has(n))return;t.add(n)}return n}},qe=(e,t)=>JSON.stringify(e,FR(t));function $R(e,t,r,n,s){const i=Object.keys(e),a=n?.channels,l=n?.audioCodec,o=s?.videoCodec,c=a&&parseInt(a)===2;let d=!1,h=!1,f=1/0,p=1/0,m=1/0,g=1/0,b=0,y=[];const{preferHDR:S,allowedVideoRanges:E}=OR(t,s);for(let N=i.length;N--;){const C=e[i[N]];d||(d=C.channels[2]>0),f=Math.min(f,C.minHeight),p=Math.min(p,C.minFramerate),m=Math.min(m,C.minBitrate),E.filter(M=>C.videoRanges[M]>0).length>0&&(h=!0)}f=he(f)?f:0,p=he(p)?p:0;const k=Math.max(1080,f),T=Math.max(30,p);m=he(m)?m:r,r=Math.max(m,r),h||(t=void 0);const A=i.length>1;return{codecSet:i.reduce((N,C)=>{const M=e[C];if(C===N)return N;if(y=h?E.filter(P=>M.videoRanges[P]>0):[],A){if(M.minBitrate>r)return ir(C,`min bitrate of ${M.minBitrate} > current estimate of ${r}`),N;if(!M.hasDefaultAudio)return ir(C,"no renditions with default or auto-select sound found"),N;if(l&&C.indexOf(l.substring(0,4))%5!==0)return ir(C,`audio codec preference "${l}" not found`),N;if(a&&!c){if(!M.channels[a])return ir(C,`no renditions with ${a} channel sound found (channels options: ${Object.keys(M.channels)})`),N}else if((!l||c)&&d&&M.channels[2]===0)return ir(C,"no renditions with stereo sound found"),N;if(M.minHeight>k)return ir(C,`min resolution of ${M.minHeight} > maximum of ${k}`),N;if(M.minFramerate>T)return ir(C,`min framerate of ${M.minFramerate} > maximum of ${T}`),N;if(!y.some(P=>M.videoRanges[P]>0))return ir(C,`no variants with VIDEO-RANGE of ${qe(y)} found`),N;if(o&&C.indexOf(o.substring(0,4))%5!==0)return ir(C,`video codec preference "${o}" not found`),N;if(M.maxScore<b)return ir(C,`max score of ${M.maxScore} < selected max of ${b}`),N}return N&&(pa(C)>=pa(N)||M.fragmentError>e[N].fragmentError)?N:(g=M.minIndex,b=M.maxScore,C)},void 0),videoRanges:y,preferHDR:S,minFramerate:p,minBitrate:m,minIndex:g}}function ir(e,t){Ke.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function fb(e){return e.reduce((t,r)=>{let n=t.groups[r.groupId];n||(n=t.groups[r.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),n.tracks.push(r);const s=r.channels||"2";return n.channels[s]=(n.channels[s]||0)+1,n.hasDefault=n.hasDefault||r.default,n.hasAutoSelect=n.hasAutoSelect||r.autoselect,n.hasDefault&&(t.hasDefaultAudio=!0),n.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function BR(e,t,r,n){return e.slice(r,n+1).reduce((s,i,a)=>{if(!i.codecSet)return s;const l=i.audioGroups;let o=s[i.codecSet];o||(s[i.codecSet]=o={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!l,fragmentError:0}),o.minBitrate=Math.min(o.minBitrate,i.bitrate);const c=Math.min(i.height,i.width);return o.minHeight=Math.min(o.minHeight,c),o.minFramerate=Math.min(o.minFramerate,i.frameRate),o.minIndex=Math.min(o.minIndex,a),o.maxScore=Math.max(o.maxScore,i.score),o.fragmentError+=i.fragmentError,o.videoRanges[i.videoRange]=(o.videoRanges[i.videoRange]||0)+1,l&&l.forEach(d=>{if(!d)return;const h=t.groups[d];h&&(o.hasDefaultAudio=o.hasDefaultAudio||t.hasDefaultAudio?h.hasDefault:h.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(h.channels).forEach(f=>{o.channels[f]=(o.channels[f]||0)+h.channels[f]}))}),s},{})}function Ah(e){if(!e)return e;const{lang:t,assocLang:r,characteristics:n,channels:s,audioCodec:i}=e;return{lang:t,assocLang:r,characteristics:n,channels:s,audioCodec:i}}function dr(e,t,r){if("attrs"in e){const n=t.indexOf(e);if(n!==-1)return n}for(let n=0;n<t.length;n++){const s=t[n];if(un(e,s,r))return n}return-1}function un(e,t,r){const{groupId:n,name:s,lang:i,assocLang:a,default:l}=e,o=e.forced;return(n===void 0||t.groupId===n)&&(s===void 0||t.name===s)&&(i===void 0||UR(i,t.lang))&&(i===void 0||t.assocLang===a)&&(l===void 0||t.default===l)&&(o===void 0||t.forced===o)&&(!("characteristics"in e)||GR(e.characteristics||"",t.characteristics))&&(r===void 0||r(e,t))}function UR(e,t="--"){return e.length===t.length?e===t:e.startsWith(t)||t.startsWith(e)}function GR(e,t=""){const r=e.split(","),n=t.split(",");return r.length===n.length&&!r.some(s=>n.indexOf(s)===-1)}function sn(e,t){const{audioCodec:r,channels:n}=e;return(r===void 0||(t.audioCodec||"").substring(0,4)===r.substring(0,4))&&(n===void 0||n===(t.channels||"2"))}function HR(e,t,r,n,s){const i=t[n],a=t.reduce((h,f,p)=>{const m=f.uri;return(h[m]||(h[m]=[])).push(p),h},{})[i.uri];a.length>1&&(n=Math.max.apply(Math,a));const l=i.videoRange,o=i.frameRate,c=i.codecSet.substring(0,4),d=Ch(t,n,h=>{if(h.videoRange!==l||h.frameRate!==o||h.codecSet.substring(0,4)!==c)return!1;const f=h.audioGroups;return dr(e,r.filter(p=>!f||f.indexOf(p.groupId)!==-1),s)>-1});return d>-1?d:Ch(t,n,h=>{const f=h.audioGroups;return dr(e,r.filter(p=>!f||f.indexOf(p.groupId)!==-1),s)>-1})}function Ch(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 va(e,t){var r;return!!e&&e!==((r=t.loadLevelObj)==null?void 0:r.uri)}var VR=class extends qt{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=t=>{var r;const{fragCurrent:n,partCurrent:s,hls:i}=this,{autoLevelEnabled:a,media:l}=i;if(!n||!l)return;const o=performance.now(),c=s?s.stats:n.stats,d=s?s.duration:n.duration,h=o-c.loading.start,f=i.minAutoLevel,p=n.level,m=this._nextAutoLevel;if(c.aborted||c.loaded&&c.loaded===c.total||p<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!a)return;const g=m>-1&&m!==p,b=!!t||g;if(!b&&(l.paused||!l.playbackRate||!l.readyState))return;const y=i.mainForwardBufferInfo;if(!b&&y===null)return;const S=this.bwEstimator.getEstimateTTFB(),E=Math.abs(l.playbackRate);if(h<=Math.max(S,1e3*(d/(E*2))))return;const k=y?y.len/E:0,T=c.loading.first?c.loading.first-c.loading.start:-1,A=c.loaded&&T>-1,N=this.getBwEstimate(),C=i.levels,M=C[p],P=Math.max(c.loaded,Math.round(d*(n.bitrate||M.averageBitrate)/8));let D=A?h-T:h;D<1&&A&&(D=Math.min(h,c.loaded*8/N));const $=A?c.loaded*1e3/D:0,B=S/1e3,j=$?(P-c.loaded)/$:P*8/N+B;if(j<=k)return;const U=$?$*8:N,F=((r=t?.details||this.hls.latestLevelDetails)==null?void 0:r.live)===!0,Y=this.hls.config.abrBandWidthUpFactor;let I=Number.POSITIVE_INFINITY,R;for(R=p-1;R>f;R--){const J=C[R].maxBitrate,Q=!C[R].details||F;if(I=this.getTimeToLoadFrag(B,U,d*J,Q),I<Math.min(k,d+B))break}if(I>=j||I>d*10)return;A?this.bwEstimator.sample(h-Math.min(S,T),c.loaded):this.bwEstimator.sampleTTFB(h);const O=C[R].maxBitrate;this.getBwEstimate()*Y>O&&this.resetEstimator(O);const K=this.findBestLevel(O,f,R,0,k,1,1);K>-1&&(R=K),this.warn(`Fragment ${n.sn}${s?" part "+s.index:""} of level ${p} is loading too slowly;
86
+ Fragment duration: ${n.duration.toFixed(3)}
87
+ Time to underbuffer: ${k.toFixed(3)} s
88
+ Estimated load time for current fragment: ${j.toFixed(3)} s
89
+ Estimated load time for down switch fragment: ${I.toFixed(3)} s
90
+ TTFB estimate: ${T|0} ms
91
+ Current BW estimate: ${he(N)?N|0:"Unknown"} bps
92
+ New BW estimate: ${this.getBwEstimate()|0} bps
93
+ Switching to level ${R} @ ${O|0} bps`),i.nextLoadLevel=i.nextAutoLevel=R,this.clearTimer();const W=()=>{if(this.clearTimer(),this.fragCurrent===n&&this.hls.loadLevel===R&&R>0){const J=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${R>0?"and switching down":""}
94
+ Fragment duration: ${n.duration.toFixed(3)} s
95
+ Time to underbuffer: ${J.toFixed(3)} s`),n.abortRequests(),this.fragCurrent=this.partCurrent=null,R>f){let Q=this.findBestLevel(this.hls.levels[f].bitrate,f,R,0,J,1,1);Q===-1&&(Q=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=Q,this.resetEstimator(this.hls.levels[Q].bitrate)}}};g||j>I*2?W():this.timer=self.setInterval(W,I*1e3),i.trigger(w.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:s,stats:c})},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 QI(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.FRAG_LOADING,this.onFragLoading,this),e.on(w.FRAG_LOADED,this.onFragLoaded,this),e.on(w.FRAG_BUFFERED,this.onFragBuffered,this),e.on(w.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(w.LEVEL_LOADED,this.onLevelLoaded,this),e.on(w.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(w.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(w.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.FRAG_LOADING,this.onFragLoading,this),e.off(w.FRAG_LOADED,this.onFragLoaded,this),e.off(w.FRAG_BUFFERED,this.onFragBuffered,this),e.off(w.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(w.LEVEL_LOADED,this.onLevelLoaded,this),e.off(w.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(w.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(w.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)){if(!r.bitrateTest){var n;this.fragCurrent=r,this.partCurrent=(n=t.part)!=null?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 G.BUFFER_ADD_CODEC_ERROR:case G.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case G.FRAG_LOAD_TIMEOUT:{const r=t.frag,{fragCurrent:n,partCurrent:s}=this;if(r&&n&&r.sn===n.sn&&r.level===n.level){const i=performance.now(),a=s?s.stats:r.stats,l=i-a.loading.start,o=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&o>-1){const c=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(c,o),a.loaded)}else this.bwEstimator.sampleTTFB(l)}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,s=n.end-n.first;he(s)&&(this.lastLevelLoadSec=s/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===fe.MAIN&&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 s=r?r.duration:t.duration,i=this.hls.levels[t.level],a=(i.loaded?i.loaded.bytes:0)+n.loaded,l=(i.loaded?i.loaded.duration:0)+s;i.loaded={bytes:a,duration:l},i.realBitrate=Math.round(8*a/l)}if(t.bitrateTest){const s={stats:n,frag:t,part:r,id:t.type};this.onFragBuffered(w.FRAG_BUFFERED,s),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:r,part:n}=t,s=n!=null&&n.stats.loaded?n.stats:r.stats;if(s.aborted||this.ignoreFragment(r))return;const i=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(i,s.loaded),s.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=i/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==fe.MAIN||e.sn==="initSegment"}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,s=this.findBestLevel(r,t,e,0,n,1,1);if(s>-1)return s;const i=this.hls.firstLevel,a=Math.min(Math.max(i,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${i} 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(e!==-1&&(!t||!r||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const n=t&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const s=this.hls.levels;if(s.length>Math.max(e,n)&&s[e].loadError<=s[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:s,minAutoLevel:i}=r,a=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),o=this.getStarvationDelay();let c=s.abrBandWidthFactor,d=s.abrBandWidthUpFactor;if(o){const g=this.findBestLevel(l,i,n,o,0,c,d);if(g>=0)return this.rebufferNotice=-1,g}let h=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!o){const g=this.bitrateTestDelay;g&&(h=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-g,this.info(`bitrate test took ${Math.round(1e3*g)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),c=d=1)}const f=this.findBestLevel(l,i,n,o,h,c,d);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${o?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const p=r.levels[i],m=r.loadLevelObj;return m&&p?.bitrate<m.bitrate?i:r.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const r=t&&t.playbackRate!==0?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,s,i,a){var l;const o=n+s,c=this.lastLoadedFragLevel,d=c===-1?this.hls.firstLevel:c,{fragCurrent:h,partCurrent:f}=this,{levels:p,allAudioTracks:m,loadLevel:g,config:b}=this.hls;if(p.length===1)return 0;const y=p[d],S=!!((l=this.hls.latestLevelDetails)!=null&&l.live),E=g===-1||c===-1;let k,T="SDR",A=y?.frameRate||0;const{audioPreference:N,videoPreference:C}=b,M=this.audioTracksByGroup||(this.audioTracksByGroup=fb(m));let P=-1;if(E){if(this.firstSelection!==-1)return this.firstSelection;const U=$R(this.codecTiers||(this.codecTiers=BR(p,M,t,r)),T,e,N,C),{codecSet:F,videoRanges:Y,minFramerate:I,minBitrate:R,minIndex:O,preferHDR:K}=U;P=O,k=F,T=K?Y[Y.length-1]:Y[0],A=I,e=Math.max(e,R),this.log(`picked start tier ${qe(U)}`)}else k=y?.codecSet,T=y?.videoRange;const D=f?f.duration:h?h.duration:0,$=this.bwEstimator.getEstimateTTFB()/1e3,B=[];for(let U=r;U>=t;U--){var j;const F=p[U],Y=U>d;if(!F)continue;if(b.useMediaCapabilities&&!F.supportedResult&&!F.supportedPromise){const J=navigator.mediaCapabilities;typeof J?.decodingInfo=="function"&&NR(F,M,T,A,e,N)?(F.supportedPromise=db(F,M,J,this.supportedCache),F.supportedPromise.then(Q=>{if(!this.hls)return;F.supportedResult=Q;const ee=this.hls.levels,ie=ee.indexOf(F);Q.error?this.warn(`MediaCapabilities decodingInfo error: "${Q.error}" for level ${ie} ${qe(Q)}`):Q.supported?Q.decodingInfoResults.some(se=>se.smooth===!1||se.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${ie} not smooth or powerEfficient: ${qe(Q)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${ie} ${qe(Q)}`),ie>-1&&ee.length>1&&(this.log(`Removing unsupported level ${ie}`),this.hls.removeLevel(ie),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Q=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Q}`)})):F.supportedResult=cb}if((k&&F.codecSet!==k||T&&F.videoRange!==T||Y&&A>F.frameRate||!Y&&A>0&&A<F.frameRate||(j=F.supportedResult)!=null&&(j=j.decodingInfoResults)!=null&&j.some(J=>J.smooth===!1))&&(!E||U!==P)){B.push(U);continue}const I=F.details,R=(f?I?.partTarget:I?.averagetargetduration)||D;let O;Y?O=a*e:O=i*e;const K=D&&n>=D*2&&s===0?F.averageBitrate:F.maxBitrate,W=this.getTimeToLoadFrag($,O,K*R,I===void 0);if(O>=K&&(U===c||F.loadError===0&&F.fragmentError===0)&&(W<=$||!he(W)||S&&!this.bitrateTestDelay||W<o)){const J=this.forcedAutoLevel;return U!==g&&(J===-1||J!==g)&&(B.length&&this.trace(`Skipped level(s) ${B.join(",")} of ${r} max with CODECS and VIDEO-RANGE:"${p[B[0]].codecs}" ${p[B[0]].videoRange}; not compatible with "${k}" ${T}`),this.info(`switch candidate:${d}->${U} adjustedbw(${Math.round(O)})-bitrate=${Math.round(O-K)} ttfb:${$.toFixed(1)} avgDuration:${R.toFixed(1)} maxFetchDuration:${o.toFixed(1)} fetchDuration:${W.toFixed(1)} firstSelection:${E} codecSet:${F.codecSet} videoRange:${F.videoRange} hls.loadLevel:${g}`)),E&&(this.firstSelection=U),U}}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)}},pb={search:function(e,t){let r=0,n=e.length-1,s=null,i=null;for(;r<=n;){s=(r+n)/2|0,i=e[s];const a=t(i);if(a>0)r=s+1;else if(a<0)n=s-1;else return i}return null}};function jR(e,t,r){if(t===null||!Array.isArray(e)||!e.length||!he(t)||t<(e[0].programDateTime||0)||t>=(e[e.length-1].endProgramDateTime||0))return null;for(let n=0;n<e.length;++n){const s=e[n];if(zR(t,r,s))return s}return null}function fn(e,t,r=0,n=0,s=.005){let i=null;if(e){i=t[1+e.sn-t[0].sn]||null;const l=e.endDTS-r;l>0&&l<15e-7&&(r+=15e-7),i&&e.level!==i.level&&i.end<=e.end&&(i=t[2+e.sn-t[0].sn]||null)}else r===0&&t[0].start===0&&(i=t[0]);if(i&&((!e||e.level===i.level)&&Nh(r,n,i)===0||KR(i,e,Math.min(s,n))))return i;const a=pb.search(t,Nh.bind(null,r,n));return a&&(a!==e||!i)?a:i}function KR(e,t,r){if(t&&t.start===0&&t.level<e.level&&(t.endPTS||0)>0){const n=t.tagList.reduce((s,i)=>(i[0]==="INF"&&(s+=parseFloat(i[1])),s),r);return e.start<=n}return!1}function Nh(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 zR(e,t,r){const n=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0))*1e3;return(r.endProgramDateTime||0)-n>e}function mb(e,t,r){if(e&&e.startCC<=t&&e.endCC>=t){let n=e.fragments;const{fragmentHint:s}=e;s&&(n=n.concat(s));let i;return pb.search(n,a=>a.cc<t?1:a.cc>t?-1:(i=a,a.end<=r?1:a.start>r?-1:0)),i||null}return null}function ba(e){switch(e.details){case G.FRAG_LOAD_TIMEOUT:case G.KEY_LOAD_TIMEOUT:case G.LEVEL_LOAD_TIMEOUT:case G.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function gb(e){return e.details.startsWith("key")}function vb(e){return gb(e)&&!!e.frag&&!e.frag.decryptdata}function Lh(e,t){const r=ba(t);return e.default[`${r?"timeout":"error"}Retry`]}function mu(e,t){const r=e.backoff==="linear"?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}function Ih(e){return je(je({},e),{errorRetry:null,timeoutRetry:null})}function ya(e,t,r,n){if(!e)return!1;const s=n?.code,i=t<e.maxNumRetry&&(WR(s)||!!r);return e.shouldRetry?e.shouldRetry(e,t,r,n,i):i}function WR(e){return ql(e)||!!e&&(e<400||e>499)}function ql(e){return e===0&&navigator.onLine===!1}var Et={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Dt={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4},QR=class extends qt{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(w.ERROR,this.onError,this),e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(w.ERROR,this.onError,this),e.off(w.ERROR,this.onErrorOut,this),e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===fe.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,r=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||r===-1?t.loadLevel:r}variantHasKey(e,t){if(e){var r;if((r=e.details)!=null&&r.hasKey(t))return!0;const n=e.audioGroups;if(n)return this.hls.allAudioTracks.filter(s=>n.indexOf(s.groupId)>=0).some(s=>{var i;return(i=s.details)==null?void 0:i.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,s=t.context;switch(t.details){case G.FRAG_LOAD_ERROR:case G.FRAG_LOAD_TIMEOUT:case G.KEY_LOAD_ERROR:case G.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case G.FRAG_PARSING_ERROR:if((r=t.frag)!=null&&r.gap){t.errorAction=jn();return}case G.FRAG_GAP:case G.FRAG_DECRYPT_ERROR:t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Et.SendAlternateToPenaltyBox;return;case G.LEVEL_EMPTY_ERROR:case G.LEVEL_PARSING_ERROR:{var i;const l=t.parent===fe.MAIN?t.level:n.loadLevel;t.details===G.LEVEL_EMPTY_ERROR&&((i=t.context)!=null&&(i=i.levelDetails)!=null&&i.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,l):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,l))}return;case G.LEVEL_LOAD_ERROR:case G.LEVEL_LOAD_TIMEOUT:typeof s?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.level));return;case G.AUDIO_TRACK_LOAD_ERROR:case G.AUDIO_TRACK_LOAD_TIMEOUT:case G.SUBTITLE_LOAD_ERROR:case G.SUBTITLE_TRACK_LOAD_TIMEOUT:if(s){const l=n.loadLevelObj;if(l&&(s.type===Fe.AUDIO_TRACK&&l.hasAudioGroup(s.groupId)||s.type===Fe.SUBTITLE_TRACK&&l.hasSubtitleGroup(s.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=Et.SendAlternateToPenaltyBox,t.errorAction.flags=Dt.MoveAllAlternatesMatchingHost;return}}return;case G.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Et.SendAlternateToPenaltyBox,flags:Dt.MoveAllAlternatesMatchingHDCP};return;case G.KEY_SYSTEM_SESSION_UPDATE_FAILED:case G.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case G.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Et.SendAlternateToPenaltyBox,flags:Dt.MoveAllAlternatesMatchingKey};return;case G.BUFFER_ADD_CODEC_ERROR:case G.REMUX_ALLOC_ERROR:case G.BUFFER_APPEND_ERROR:if(!t.errorAction){var a;t.errorAction=this.getLevelSwitchAction(t,(a=t.level)!=null?a:n.loadLevel)}return;case G.INTERNAL_EXCEPTION:case G.BUFFER_APPENDING_ERROR:case G.BUFFER_FULL_ERROR:case G.LEVEL_SWITCH_ERROR:case G.BUFFER_STALLED_ERROR:case G.BUFFER_SEEK_OVER_HOLE:case G.BUFFER_NUDGE_ON_STALL:t.errorAction=jn();return}t.type===xe.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=jn())}getPlaylistRetryOrSwitchAction(e,t){const r=this.hls,n=Lh(r.config.playlistLoadPolicy,e),s=this.playlistError++;if(ya(n,s,ba(e),e.response))return{action:Et.RetryRequest,flags:Dt.None,retryConfig:n,retryCount:s};const i=this.getLevelSwitchAction(e,t);return n&&(i.retryConfig=n,i.retryCount=s),i}getFragRetryOrSwitchAction(e){const t=this.hls,r=this.getVariantLevelIndex(e.frag),n=t.levels[r],{fragLoadPolicy:s,keyLoadPolicy:i}=t.config,a=Lh(gb(e)?i:s,e),l=t.levels.reduce((c,d)=>c+d.fragmentError,0);if(n&&(e.details!==G.FRAG_GAP&&n.fragmentError++,!vb(e)&&ya(a,l,ba(e),e.response)))return{action:Et.RetryRequest,flags:Dt.None,retryConfig:a,retryCount:l};const o=this.getLevelSwitchAction(e,r);return a&&(o.retryConfig=a,o.retryCount=l),o}getLevelSwitchAction(e,t){const r=this.hls;t==null&&(t=r.loadLevel);const n=this.hls.levels[t];if(n){var s,i;const o=e.details;n.loadError++,o===G.BUFFER_APPEND_ERROR&&n.fragmentError++;let c=-1;const{levels:d,loadLevel:h,minAutoLevel:f,maxAutoLevel:p}=r;!r.autoLevelEnabled&&!r.config.preserveManualLevelOnError&&(r.loadLevel=-1);const m=(s=e.frag)==null?void 0:s.type,g=(m===fe.AUDIO&&o===G.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(o===G.BUFFER_ADD_CODEC_ERROR||o===G.BUFFER_APPEND_ERROR))&&d.some(({audioCodec:E})=>n.audioCodec!==E),b=e.sourceBufferName==="video"&&(o===G.BUFFER_ADD_CODEC_ERROR||o===G.BUFFER_APPEND_ERROR)&&d.some(({codecSet:E,audioCodec:k})=>n.codecSet!==E&&n.audioCodec===k),{type:y,groupId:S}=(i=e.context)!=null?i:{};for(let E=d.length;E--;){const k=(E+h)%d.length;if(k!==h&&k>=f&&k<=p&&d[k].loadError===0){var a,l;const T=d[k];if(o===G.FRAG_GAP&&m===fe.MAIN&&e.frag){const A=d[k].details;if(A){const N=fn(e.frag,A.fragments,e.frag.start);if(N!=null&&N.gap)continue}}else{if(y===Fe.AUDIO_TRACK&&T.hasAudioGroup(S)||y===Fe.SUBTITLE_TRACK&&T.hasSubtitleGroup(S))continue;if(m===fe.AUDIO&&(a=n.audioGroups)!=null&&a.some(A=>T.hasAudioGroup(A))||m===fe.SUBTITLE&&(l=n.subtitleGroups)!=null&&l.some(A=>T.hasSubtitleGroup(A))||g&&n.audioCodec===T.audioCodec||b&&n.codecSet===T.codecSet||!g&&n.codecSet!==T.codecSet)continue}c=k;break}}if(c>-1&&r.loadLevel!==c)return e.levelRetry=!0,this.playlistError=0,{action:Et.SendAlternateToPenaltyBox,flags:Dt.None,nextAutoLevel:c}}return{action:Et.SendAlternateToPenaltyBox,flags:Dt.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var r;switch((r=t.errorAction)==null?void 0:r.action){case Et.DoNothing:break;case Et.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==G.FRAG_GAP?t.fatal=!0:/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());break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,r=e.errorAction;if(!r)return;const{flags:n}=r,s=r.nextAutoLevel;switch(n){case Dt.None:this.switchLevel(e,s);break;case Dt.MoveAllAlternatesMatchingHDCP:{const l=this.getVariantLevelIndex(e.frag),o=t.levels[l],c=o?.attrs["HDCP-LEVEL"];if(r.hdcpLevel=c,c==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(c){t.maxHdcpLevel=Ql[Ql.indexOf(c)-1],r.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Dt.MoveAllAlternatesMatchingKey:{const l=e.decryptdata;if(l){const o=this.hls.levels,c=o.length;for(let h=c;h--;)if(this.variantHasKey(o[h],l)){var i,a;this.log(`Banned key found in level ${h} (${o[h].bitrate}bps) or audio group "${(i=o[h].audioGroups)==null?void 0:i.join(",")}" (${(a=e.frag)==null?void 0:a.type} fragment) ${wt(l.keyId||[])}`),o[h].fragmentError++,o[h].loadError++,this.log(`Removing level ${h} with key error (${e.error})`),this.hls.removeLevel(h)}const d=e.frag;if(this.hls.levels.length<c)r.resolved=!0;else if(d&&d.type!==fe.MAIN){const h=d.decryptdata;h&&!l.matches(h)&&(r.resolved=!0)}}break}}r.resolved||this.switchLevel(e,s)}switchLevel(e,t){if(t!==void 0&&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===G.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const r=Wl(e.mimeType),n=this.hls.levels;for(let s=n.length;s--;)n[s][`${e.sourceBufferName}Codec`]===r&&(this.log(`Removing level ${s} for ${e.details} ("${r}" not supported)`),this.hls.removeLevel(s))}}};function jn(e){const t={action:Et.DoNothing,flags:Dt.None};return e&&(t.resolved=!0),t}var gt={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},qR=class{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(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.BUFFER_APPENDED,this.onBufferAppended,this),e.on(w.FRAG_BUFFERED,this.onFragBuffered,this),e.on(w.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.BUFFER_APPENDED,this.onBufferAppended,this),e.off(w.FRAG_BUFFERED,this.onFragBuffered,this),e.off(w.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 n=r.length;n--;){const s=r[n];if(!s)break;if(s.start<=e&&e<=s.end&&s.loaded)return s}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,r){const{fragments:n}=this,s=Object.keys(n);for(let i=s.length;i--;){const a=n[s[i]];if(a?.body.type===t&&(!r||a.buffered)){const l=a.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,r,n,s){this.timeRanges&&(this.timeRanges[e]=t);const i=n?.fragment.sn||-1;Object.keys(this.fragments).forEach(a=>{const l=this.fragments[a];if(!l||i>=l.body.sn)return;if(!l.buffered&&(!l.loaded||s)){l.body.type===r&&this.removeFragment(l.body);return}const o=l.range[e];if(o){if(o.time.length===0){this.removeFragment(l.body);return}o.time.some(c=>{const d=!this.isTimeBuffered(c.startPTS,c.endPTS,t);return d&&this.removeFragment(l.body),d})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const r=e.frag,n=Tn(r),s=this.fragments[n];if(!s||s.buffered&&r.gap)return;const i=!r.relurl;Object.keys(t).forEach(a=>{const l=r.elementaryStreams[a];if(!l)return;const o=t[a],c=i||l.partial===!0;s.range[a]=this.getBufferedTimes(r,e.part,c,o)}),s.loaded=null,Object.keys(s.range).length?(this.bufferedEnd(s,r),gi(s)||this.removeParts(r.sn-1,r.type)):this.removeFragment(s.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]=Rh(r,n=>n.fragment.sn>=e))}fragBuffered(e,t){const r=Tn(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 s={time:[],partial:r},i=e.start,a=e.end,l=e.minEndPTS||a,o=e.maxStartPTS||i;for(let c=0;c<n.length;c++){const d=n.start(c)-this.bufferPadding,h=n.end(c)+this.bufferPadding;if(o>=d&&l<=h){s.time.push({startPTS:Math.max(i,n.start(c)),endPTS:Math.min(a,n.end(c))});break}else if(i<h&&a>d){const f=Math.max(i,n.start(c)),p=Math.min(a,n.end(c));p>f&&(s.partial=!0,s.time.push({startPTS:f,endPTS:p}))}else if(a<=d)break}return s}getPartialFragment(e){let t=null,r,n,s,i=0;const{bufferPadding:a,fragments:l}=this;return Object.keys(l).forEach(o=>{const c=l[o];c&&gi(c)&&(n=c.body.start-a,s=c.body.end+a,e>=n&&e<=s&&(r=Math.min(e-n,s-e),i<=r&&(t=c.body,i=r)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||gi(t))}getState(e){const t=Tn(e),r=this.fragments[t];return r?r.buffered?gi(r)?gt.PARTIAL:gt.OK:gt.APPENDING:gt.NOT_LOADED}isTimeBuffered(e,t,r){let n,s;for(let i=0;i<r.length;i++){if(n=r.start(i)-this.bufferPadding,s=r.end(i)+this.bufferPadding,e>=n&&t<=s)return!0;if(t<=n)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const r=t.frag,n=t.part?null:t,s=Tn(r);this.fragments[s]={body:r,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:r,part:n,timeRanges:s,type:i}=t;if(r.sn==="initSegment")return;const a=r.type;if(n){let o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(n)}this.timeRanges=s;const l=s[i];this.detectEvictedFragments(i,l,a,n)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Tn(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 s=t[r[n]];if(s?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,r,n,s){n&&!this.hasGaps||Object.keys(this.fragments).forEach(i=>{const a=this.fragments[i];if(!a)return;const l=a.body;l.type!==r||n&&!l.gap||l.start<t&&l.end>e&&(a.buffered||s)&&this.removeFragment(l)})}removeFragment(e){const t=Tn(e);e.clearElementaryStreamInfo();const r=this.activePartLists[e.type];if(r){const n=e.sn;this.activePartLists[e.type]=Rh(r,s=>s.fragment.sn!==n)}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=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(r=>r.clearElementaryStreamInfo())}};function gi(e){var t,r,n;return e.buffered&&!!(e.body.gap||(t=e.range.video)!=null&&t.partial||(r=e.range.audio)!=null&&r.partial||(n=e.range.audiovideo)!=null&&n.partial)}function Tn(e){return`${e.type}_${e.level}_${e.sn}`}function Rh(e,t){return e.filter(r=>{const n=t(r);return n||r.clearElementaryStreamInfo(),n})}var jr={cbc:0,ctr:1},YR=class{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 jr.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case jr.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}};function XR(e){const t=e.byteLength,r=t&&new DataView(e.buffer).getUint8(t-1);return r?e.slice(0,t-r):e}var ZR=class{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 n=0;n<4;n++)r[n]=t.getUint32(n*4);return r}initTable(){const e=this.sBox,t=this.invSBox,r=this.subMix,n=r[0],s=r[1],i=r[2],a=r[3],l=this.invSubMix,o=l[0],c=l[1],d=l[2],h=l[3],f=new Uint32Array(256);let p=0,m=0,g=0;for(g=0;g<256;g++)g<128?f[g]=g<<1:f[g]=g<<1^283;for(g=0;g<256;g++){let b=m^m<<1^m<<2^m<<3^m<<4;b=b>>>8^b&255^99,e[p]=b,t[b]=p;const y=f[p],S=f[y],E=f[S];let k=f[b]*257^b*16843008;n[p]=k<<24|k>>>8,s[p]=k<<16|k>>>16,i[p]=k<<8|k>>>24,a[p]=k,k=E*16843009^S*65537^y*257^p*16843008,o[b]=k<<24|k>>>8,c[b]=k<<16|k>>>16,d[b]=k<<8|k>>>24,h[b]=k,p?(p=y^f[f[f[E^y]]],m^=f[f[m]]):p=m=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 s=this.keySize=t.length;if(s!==4&&s!==6&&s!==8)throw new Error("Invalid aes key size="+s);const i=this.ksRows=(s+6+1)*4;let a,l;const o=this.keySchedule=new Uint32Array(i),c=this.invKeySchedule=new Uint32Array(i),d=this.sBox,h=this.rcon,f=this.invSubMix,p=f[0],m=f[1],g=f[2],b=f[3];let y,S;for(a=0;a<i;a++){if(a<s){y=o[a]=t[a];continue}S=y,a%s===0?(S=S<<8|S>>>24,S=d[S>>>24]<<24|d[S>>>16&255]<<16|d[S>>>8&255]<<8|d[S&255],S^=h[a/s|0]<<24):s>6&&a%s===4&&(S=d[S>>>24]<<24|d[S>>>16&255]<<16|d[S>>>8&255]<<8|d[S&255]),o[a]=y=(o[a-s]^S)>>>0}for(l=0;l<i;l++)a=i-l,l&3?S=o[a]:S=o[a-4],l<4||a<=4?c[l]=S:c[l]=p[d[S>>>24]]^m[d[S>>>16&255]]^g[d[S>>>8&255]]^b[d[S&255]],c[l]=c[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,r){const n=this.keySize+6,s=this.invKeySchedule,i=this.invSBox,a=this.invSubMix,l=a[0],o=a[1],c=a[2],d=a[3],h=this.uint8ArrayToUint32Array_(r);let f=h[0],p=h[1],m=h[2],g=h[3];const b=new Int32Array(e),y=new Int32Array(b.length);let S,E,k,T,A,N,C,M,P,D,$,B,j,U;const F=this.networkToHostOrderSwap;for(;t<b.length;){for(P=F(b[t]),D=F(b[t+1]),$=F(b[t+2]),B=F(b[t+3]),A=P^s[0],N=B^s[1],C=$^s[2],M=D^s[3],j=4,U=1;U<n;U++)S=l[A>>>24]^o[N>>16&255]^c[C>>8&255]^d[M&255]^s[j],E=l[N>>>24]^o[C>>16&255]^c[M>>8&255]^d[A&255]^s[j+1],k=l[C>>>24]^o[M>>16&255]^c[A>>8&255]^d[N&255]^s[j+2],T=l[M>>>24]^o[A>>16&255]^c[N>>8&255]^d[C&255]^s[j+3],A=S,N=E,C=k,M=T,j=j+4;S=i[A>>>24]<<24^i[N>>16&255]<<16^i[C>>8&255]<<8^i[M&255]^s[j],E=i[N>>>24]<<24^i[C>>16&255]<<16^i[M>>8&255]<<8^i[A&255]^s[j+1],k=i[C>>>24]<<24^i[M>>16&255]<<16^i[A>>8&255]<<8^i[N&255]^s[j+2],T=i[M>>>24]<<24^i[A>>16&255]<<16^i[N>>8&255]<<8^i[C&255]^s[j+3],y[t]=F(S^f),y[t+1]=F(T^p),y[t+2]=F(k^m),y[t+3]=F(E^g),f=P,p=D,m=$,g=B,t=t+4}return y.buffer}},JR=class{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=eM(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}};function eM(e){switch(e){case jr.cbc:return"AES-CBC";case jr.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${e}`)}}var tM=16,gu=class{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 r=self.crypto;r&&(this.subtle=r.subtle||r.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const r=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?XR(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((s,i)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,r,n);const l=this.flush();l?s(l.buffer):i(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,r,n)}softwareDecrypt(e,t,r,n){const{currentIV:s,currentResult:i,remainderData:a}=this;if(n!==jr.cbc||t.byteLength!==16)return Ke.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=Wt(a,e),this.remainderData=null);const l=this.getValidChunk(e);if(!l.length)return null;s&&(r=s);let o=this.softwareDecrypter;o||(o=this.softwareDecrypter=new ZR),o.expandKey(t);const c=i;return this.currentResult=o.decrypt(l.buffer,0,r),this.currentIV=l.slice(-16).buffer,c||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 JR(this.subtle,t,n)}return this.fastAesKey.expandKey().then(s=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new YR(this.subtle,new Uint8Array(r),n).decrypt(e.buffer,s)):Promise.reject(new Error("web crypto not initialized"))).catch(s=>(Ke.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${s.name}: ${s.message}`),this.onWebCryptoError(e,t,r,n)))}onWebCryptoError(e,t,r,n){const s=this.enableSoftwareAES;if(s){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"+(s?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const r=e.length-e.length%tM;return r!==e.length&&(t=e.slice(0,r),this.remainderData=e.slice(r)),t}logOnce(e){this.logEnabled&&(Ke.log(`[decrypter]: ${e}`),this.logEnabled=!1)}},Mh=Math.pow(2,17),rM=class{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 Sr({type:xe.NETWORK_ERROR,details:G.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,s=n.fLoader,i=n.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(p=>p[0]==="GAP")){l(Dh(e));return}else e.gap=!1;const o=this.loader=s?new s(n):new i(n),c=Ph(e);e.loader=o;const d=Ih(n.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Mh};e.stats=o.stats;const f={onSuccess:(p,m,g,b)=>{this.resetLoader(e,o);let y=p.data;g.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(y.slice(0,16)),y=y.slice(16)),a({frag:e,part:null,payload:y,networkDetails:b})},onError:(p,m,g,b)=>{this.resetLoader(e,o),l(new Sr({type:xe.NETWORK_ERROR,details:G.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:je({url:r,data:void 0},p),error:new Error(`HTTP Error ${p.code} ${p.text}`),networkDetails:g,stats:b}))},onAbort:(p,m,g)=>{this.resetLoader(e,o),l(new Sr({type:xe.NETWORK_ERROR,details:G.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:g,stats:p}))},onTimeout:(p,m,g)=>{this.resetLoader(e,o),l(new Sr({type:xe.NETWORK_ERROR,details:G.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:g,stats:p}))}};t&&(f.onProgress=(p,m,g,b)=>t({frag:e,part:null,payload:g,networkDetails:b})),o.load(c,h,f)})}loadPart(e,t,r){this.abort();const n=this.config,s=n.fLoader,i=n.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(Dh(e,t));return}const o=this.loader=s?new s(n):new i(n),c=Ph(e,t);e.loader=o;const d=Ih(n.fragLoadPolicy.default),h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Mh};t.stats=o.stats,o.load(c,h,{onSuccess:(f,p,m,g)=>{this.resetLoader(e,o),this.updateStatsFromPart(e,t);const b={frag:e,part:t,payload:f.data,networkDetails:g};r(b),a(b)},onError:(f,p,m,g)=>{this.resetLoader(e,o),l(new Sr({type:xe.NETWORK_ERROR,details:G.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:je({url:c.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:m,stats:g}))},onAbort:(f,p,m)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,o),l(new Sr({type:xe.NETWORK_ERROR,details:G.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:m,stats:f}))},onTimeout:(f,p,m)=>{this.resetLoader(e,o),l(new Sr({type:xe.NETWORK_ERROR,details:G.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:m,stats:f}))}})})}updateStatsFromPart(e,t){const r=e.stats,n=t.stats,s=n.total;if(r.loaded+=n.loaded,s){const l=Math.round(e.duration/t.duration),o=Math.min(Math.round(r.loaded/s),l),c=(l-o)*Math.round(r.loaded/o);r.total=r.loaded+c}else r.total=Math.max(r.loaded,r.total);const i=r.loading,a=n.loading;i.start?i.first+=a.first-a.start:(i.start=a.start,i.first=a.first),i.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}};function Ph(e,t=null){const r=t||e,n={frag:e,part:t,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},s=r.byteRangeStartOffset,i=r.byteRangeEndOffset;if(he(s)&&he(i)){var a;let l=s,o=i;if(e.sn==="initSegment"&&nM((a=e.decryptdata)==null?void 0:a.method)){const c=i-s;c%16&&(o=i+(16-c%16)),s!==0&&(n.resetIV=!0,l=s-16)}n.rangeStart=l,n.rangeEnd=o}return n}function Dh(e,t){const r=new Error(`GAP ${e.gap?"tag":"attribute"} found`),n={type:xe.MEDIA_ERROR,details:G.FRAG_GAP,fatal:!1,frag:e,error:r,networkDetails:null};return t&&(n.part=t),(t||e).stats.aborted=!0,new Sr(n)}function nM(e){return e==="AES-128"||e==="AES-256"}var Sr=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},bb=class extends qt{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?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}},vu=class{constructor(e,t,r,n=0,s=-1,i=!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=vi(),this.buffering={audio:vi(),video:vi(),audiovideo:vi()},this.level=e,this.sn=t,this.id=r,this.size=n,this.part=s,this.partial=i}};function vi(){return{start:0,executeStart:0,executeEnd:0,end:0}}var _h={length:0,start:()=>0,end:()=>0},De=class In{static isBuffered(t,r){if(t){const n=In.getBuffered(t);for(let s=n.length;s--;)if(r>=n.start(s)&&r<=n.end(s))return!0}return!1}static bufferedRanges(t){if(t){const r=In.getBuffered(t);return In.timeRangesToArray(r)}return[]}static timeRangesToArray(t){const r=[];for(let n=0;n<t.length;n++)r.push({start:t.start(n),end:t.end(n)});return r}static bufferInfo(t,r,n){if(t){const s=In.bufferedRanges(t);if(s.length)return In.bufferedInfo(s,r,n)}return{len:0,start:r,end:r,bufferedIndex:-1}}static bufferedInfo(t,r,n){r=Math.max(0,r),t.length>1&&t.sort((d,h)=>d.start-h.start||h.end-d.end);let s=-1,i=[];if(n)for(let d=0;d<t.length;d++){r>=t[d].start&&r<=t[d].end&&(s=d);const h=i.length;if(h){const f=i[h-1].end;t[d].start-f<n?t[d].end>f&&(i[h-1].end=t[d].end):i.push(t[d])}else i.push(t[d])}else i=t;let a=0,l,o=r,c=r;for(let d=0;d<i.length;d++){const h=i[d].start,f=i[d].end;if(s===-1&&r>=h&&r<=f&&(s=d),r+n>=h&&r<f)o=h,c=f,a=c-r;else if(r+n<h){l=h;break}}return{len:a,start:o||0,end:c||0,nextStart:l,buffered:t,bufferedIndex:s}}static getBuffered(t){try{return t.buffered||_h}catch(r){return Ke.log("failed to get media.buffered",r),_h}}},yb=/\{\$([a-zA-Z0-9-_]+)\}/g;function Oh(e){return yb.test(e)}function Yl(e,t){if(e.variableList!==null||e.hasVariableRefs){const r=e.variableList;return t.replace(yb,n=>{const s=n.substring(2,n.length-1),i=r?.[s];return i===void 0?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),n):i})}return t}function Fh(e,t,r){let n=e.variableList;n||(e.variableList=n={});let s,i;if("QUERYPARAM"in t){s=t.QUERYPARAM;try{const a=new self.URL(r).searchParams;if(a.has(s))i=a.get(s);else throw new Error(`"${s}" does not match any query parameter in URI: "${r}"`)}catch(a){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else s=t.NAME,i=t.VALUE;s in n?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):n[s]=i||""}function sM(e,t,r){const n=t.IMPORT;if(r&&n in r){let s=e.variableList;s||(e.variableList=s={}),s[n]=r[n]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${n}"`))}var iM=/^(\d+)x(\d+)$/,$h=/(.+?)=(".*?"|.*?)(?:,|$)/g,ot=class xb{constructor(t,r){typeof t=="string"&&(t=xb.parseAttrList(t,r)),ze(this,t)}get clientAttrs(){return Object.keys(this).filter(t=>t.substring(0,2)==="X-")}decimalInteger(t){const r=parseInt(this[t],10);return r>Number.MAX_SAFE_INTEGER?1/0:r}hexadecimalInteger(t){if(this[t]){let r=(this[t]||"0x").slice(2);r=(r.length&1?"0":"")+r;const n=new Uint8Array(r.length/2);for(let s=0;s<r.length/2;s++)n[s]=parseInt(r.slice(s*2,s*2+2),16);return n}return null}hexadecimalIntegerAsNumber(t){const r=parseInt(this[t],16);return r>Number.MAX_SAFE_INTEGER?1/0:r}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,r){const n=this[t];return n?parseFloat(n):r}enumeratedString(t){return this[t]}enumeratedStringList(t,r){const n=this[t];return(n?n.split(/[ ,]+/):[]).reduce((s,i)=>(s[i.toLowerCase()]=!0,s),r)}bool(t){return this[t]==="YES"}decimalResolution(t){const r=iM.exec(this[t]);if(r!==null)return{width:parseInt(r[1],10),height:parseInt(r[2],10)}}static parseAttrList(t,r){let n;const s={};for($h.lastIndex=0;(n=$h.exec(t))!==null;){const a=n[1].trim();let l=n[2];const o=l.indexOf('"')===0&&l.lastIndexOf('"')===l.length-1;let c=!1;if(o)l=l.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":c=!0}if(r&&(o||c))l=Yl(r,l);else if(!c&&!o)switch(a){case"CLOSED-CAPTIONS":if(l==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Ke.warn(`${t}: attribute ${a} is missing quotes`)}s[a]=l}return s}},aM="com.apple.hls.interstitial";function oM(e){return e!=="ID"&&e!=="CLASS"&&e!=="CUE"&&e!=="START-DATE"&&e!=="DURATION"&&e!=="END-DATE"&&e!=="END-ON-NEXT"}function lM(e){return e==="SCTE35-OUT"||e==="SCTE35-IN"||e==="SCTE35-CMD"}var Sb=class{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=t?.tagAnchor||null,this.tagOrder=(n=t?.tagOrder)!=null?n:r,t){const s=t.attr;for(const i in s)if(Object.prototype.hasOwnProperty.call(e,i)&&e[i]!==s[i]){Ke.warn(`DATERANGE tag attribute: "${i}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=i;break}e=ze(new ot({}),s,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 s=t?.endDate||new Date(this.attr["END-DATE"]);he(s.getTime())&&(this._endDate=s)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(Ke.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 t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(he(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===aM}get isValid(){return!!this.id&&!this._badValueForSameId&&he(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}},cM=10,uM=class{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const 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||t===0&&r>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let r=t.decryptdata;return r||(t.setKeyFormat(e.keyFormat),r=t.decryptdata),!!r&&e.matches(r)})}get hasProgramDateTime(){return this.fragments.length?he(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||cM}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let r=e.length;r--;)if(e[r].index>t)return e[r].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}};function xa(e,t){return e.length===t.length?!e.some((r,n)=>r!==t[n]):!1}function Bh(e,t){return!e&&!t?!0:!e||!t?!1:xa(e,t)}function Kn(e){return e==="AES-128"||e==="AES-256"||e==="AES-256-CTR"}function bu(e){switch(e){case"AES-128":case"AES-256":return jr.cbc;case"AES-256-CTR":return jr.ctr;default:throw new Error(`invalid full segment method ${e}`)}}function yu(e){return Uint8Array.from(atob(e),t=>t.charCodeAt(0))}function Xl(e){return Uint8Array.from(unescape(encodeURIComponent(e)),t=>t.charCodeAt(0))}function dM(e){const t=Xl(e).subarray(0,16),r=new Uint8Array(16);return r.set(t,16-t.length),r}function Eb(e){const t=function(n,s,i){const a=n[s];n[s]=n[i],n[i]=a};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function wb(e){const t=e.split(":");let r=null;if(t[0]==="data"&&t.length===2){const n=t[1].split(";"),s=n[n.length-1].split(",");if(s.length===2){const i=s[0]==="base64",a=s[1];i?(n.splice(-1,1),r=yu(a)):r=dM(a)}}return r}var Sa=typeof self<"u"?self:void 0,et={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},kt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function ji(e){switch(e){case kt.FAIRPLAY:return et.FAIRPLAY;case kt.PLAYREADY:return et.PLAYREADY;case kt.WIDEVINE:return et.WIDEVINE;case kt.CLEARKEY:return et.CLEARKEY}}function _o(e){switch(e){case et.FAIRPLAY:return kt.FAIRPLAY;case et.PLAYREADY:return kt.PLAYREADY;case et.WIDEVINE:return kt.WIDEVINE;case et.CLEARKEY:return kt.CLEARKEY}}function ms(e){const{drmSystems:t,widevineLicenseUrl:r}=e,n=t?[et.FAIRPLAY,et.WIDEVINE,et.PLAYREADY,et.CLEARKEY].filter(s=>!!t[s]):[];return!n[et.WIDEVINE]&&r&&n.push(et.WIDEVINE),n}var kb=(function(e){return Sa!=null&&(e=Sa.navigator)!=null&&e.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function hM(e,t,r,n){let s;switch(e){case et.FAIRPLAY:s=["cenc","sinf"];break;case et.WIDEVINE:case et.PLAYREADY:s=["cenc"];break;case et.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return fM(s,t,r,n)}function fM(e,t,r,n){return[{initDataTypes:e,persistentState:n.persistentState||"optional",distinctiveIdentifier:n.distinctiveIdentifier||"optional",sessionTypes:n.sessionTypes||[n.sessionType||"temporary"],audioCapabilities:t.map(s=>({contentType:`audio/mp4; codecs=${s}`,robustness:n.audioRobustness||"",encryptionScheme:n.audioEncryptionScheme||null})),videoCapabilities:r.map(s=>({contentType:`video/mp4; codecs=${s}`,robustness:n.videoRobustness||"",encryptionScheme:n.videoEncryptionScheme||null}))}]}function pM(e){var t;return!!e&&(e.sessionType==="persistent-license"||!!((t=e.sessionTypes)!=null&&t.some(r=>r==="persistent-license")))}function Tb(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),s=new DOMParser().parseFromString(n,"text/xml").getElementsByTagName("KID")[0];if(s){const i=s.childNodes[0]?s.childNodes[0].nodeValue:s.getAttribute("VALUE");if(i){const a=yu(i).subarray(0,16);return Eb(a),a}}return null}var An={},Ea=class Ki{static clearKeyUriToKeyIdMap(){An={}}static setKeyIdForUri(t,r){An[t]=r}static addKeyIdForUri(t){const r=Object.keys(An).length%Number.MAX_SAFE_INTEGER,n=new Uint8Array(16);return new DataView(n.buffer,12,4).setUint32(0,r),An[t]=n,n}constructor(t,r,n,s=[1],i=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=r,this.keyFormat=n,this.keyFormatVersions=s,this.iv=i,this.encrypted=t?t!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Kn(t),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(Zv(a)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&xa(t.keyFormatVersions,this.keyFormatVersions)&&Bh(t.iv,this.iv)&&Bh(t.keyId,this.keyId)}isSupported(){if(this.method){if(Kn(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case kt.FAIRPLAY:case kt.WIDEVINE:case kt.PLAYREADY:case kt.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(t,r){if(!this.encrypted||!this.uri)return null;if(Kn(this.method)){let i=this.iv;return i||(typeof t!="number"&&(Ke.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),i=gM(t)),new Ki(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.keyId){const i=An[this.uri];if(i&&!xa(this.keyId,i)&&Ki.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const n=wb(this.uri);if(n)switch(this.keyFormat){case kt.WIDEVINE:if(this.pssh=n,!this.keyId){const i=yR(n.buffer);if(i.length){var s;const a=i[0];this.keyId=(s=a.kids)!=null&&s.length?a.kids[0]:null}}this.keyId||(this.keyId=Uh(r));break;case kt.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=bR(i,null,n),this.keyId=Tb(n);break}default:{let i=n.subarray(0,16);if(i.length!==16){const a=new Uint8Array(16);a.set(i,16-i.length),i=a}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i;i=mM(r),i||(i=Uh(r),i||(i=An[this.uri])),i&&(this.keyId=i,Ki.setKeyIdForUri(this.uri,i))}return this}};function mM(e){const t=e?.[kt.WIDEVINE];return t?t.keyId:null}function Uh(e){const t=e?.[kt.PLAYREADY];if(t){const r=wb(t.uri);if(r)return Tb(r)}return null}function gM(e){const t=new Uint8Array(16);for(let r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}var Gh=/#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,Hh=/#EXT-X-MEDIA:(.*)/g,vM=/^#EXT(?:INF|-X-TARGETDURATION):/m,Oo=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),bM=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("|")),gs=class vs{static findGroup(t,r){for(let n=0;n<t.length;n++){const s=t[n];if(s.id===r)return s}}static resolve(t,r){return uu.buildAbsoluteURL(r,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return vM.test(t)}static parseMasterPlaylist(t,r){const n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Oh(t)},s=[];if(Gh.lastIndex=0,!t.startsWith("#EXTM3U"))return n.playlistParsingError=new Error("no EXTM3U delimiter"),n;let i;for(;(i=Gh.exec(t))!=null;)if(i[1]){var a;const l=new ot(i[1],n),o=Yl(n,i[2]),c={attrs:l,bitrate:l.decimalInteger("BANDWIDTH")||l.decimalInteger("AVERAGE-BANDWIDTH"),name:l.NAME,url:vs.resolve(o,r)},d=l.decimalResolution("RESOLUTION");d&&(c.width=d.width,c.height=d.height),Kh(l.CODECS,c);const h=l["SUPPLEMENTAL-CODECS"];h&&(c.supplemental={},Kh(h,c.supplemental)),(a=c.unknownCodecs)!=null&&a.length||s.push(c),n.levels.push(c)}else if(i[3]){const l=i[3],o=i[4];switch(l){case"SESSION-DATA":{const c=new ot(o,n),d=c["DATA-ID"];d&&(n.sessionData===null&&(n.sessionData={}),n.sessionData[d]=c);break}case"SESSION-KEY":{const c=Vh(o,r,n);c.encrypted&&c.isSupported()?(n.sessionKeys===null&&(n.sessionKeys=[]),n.sessionKeys.push(c)):Ke.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${o}"`);break}case"DEFINE":Fh(n,new ot(o,n),r);break;case"CONTENT-STEERING":{const c=new ot(o,n);n.contentSteering={uri:vs.resolve(c["SERVER-URI"],r),pathwayId:c["PATHWAY-ID"]||"."};break}case"START":n.startTimeOffset=jh(o);break}}return n.levels=s.length>0&&s.length<n.levels.length?s:n.levels,n.levels.length===0&&(n.playlistParsingError=new Error("no levels found in manifest")),n}static parseMasterPlaylistMedia(t,r,n){let s;const i={},a=n.levels,l={AUDIO:a.map(c=>({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:a.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]};let o=0;for(Hh.lastIndex=0;(s=Hh.exec(t))!==null;){const c=new ot(s[1],n),d=c.TYPE;if(d){const h=l[d],f=i[d]||[];i[d]=f;const p=c.LANGUAGE,m=c["ASSOC-LANGUAGE"],g=c.CHANNELS,b=c.CHARACTERISTICS,y=c["INSTREAM-ID"],S={attrs:c,bitrate:0,id:o++,groupId:c["GROUP-ID"]||"",name:c.NAME||p||"",type:d,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:p,url:c.URI?vs.resolve(c.URI,r):""};if(m&&(S.assocLang=m),g&&(S.channels=g),b&&(S.characteristics=b),y&&(S.instreamId=y),h!=null&&h.length){const E=vs.findGroup(h,S.groupId)||h[0];zh(S,E,"audioCodec"),zh(S,E,"textCodec")}f.push(S)}}return i}static parseLevelPlaylist(t,r,n,s,i,a){var l;const o={url:r},c=new uM(r),d=c.fragments,h=[];let f=null,p=0,m=0,g=0,b=0,y=0,S=null,E=new Mo(s,o),k,T,A,N=-1,C=!1,M=null,P;if(Oo.lastIndex=0,c.m3u8=t,c.hasVariableRefs=Oh(t),((l=Oo.exec(t))==null?void 0:l[0])!=="#EXTM3U")return c.playlistParsingError=new Error("Missing format identifier #EXTM3U"),c;for(;(k=Oo.exec(t))!==null;){C&&(C=!1,E=new Mo(s,o),E.playlistOffset=g,E.setStart(g),E.sn=p,E.cc=b,y&&(E.bitrate=y),E.level=n,f&&(E.initSegment=f,f.rawProgramDateTime&&(E.rawProgramDateTime=f.rawProgramDateTime,f.rawProgramDateTime=null),M&&(E.setByteRange(M),M=null)));const j=k[1];if(j){E.duration=parseFloat(j);const U=(" "+k[2]).slice(1);E.title=U||null,E.tagList.push(U?["INF",j,U]:["INF",j])}else if(k[3]){if(he(E.duration)){E.playlistOffset=g,E.setStart(g),A&&Qh(E,A,c),E.sn=p,E.level=n,E.cc=b,d.push(E);const U=(" "+k[3]).slice(1);E.relurl=Yl(c,U),Zl(E,S,h),S=E,g+=E.duration,p++,m=0,C=!0}}else{if(k=k[0].match(bM),!k){Ke.warn("No matches on slow regex match for level playlist!");continue}for(T=1;T<k.length&&k[T]===void 0;T++);const U=(" "+k[T]).slice(1),F=(" "+k[T+1]).slice(1),Y=k[T+2]?(" "+k[T+2]).slice(1):null;switch(U){case"BYTERANGE":S?E.setByteRange(F,S):E.setByteRange(F);break;case"PROGRAM-DATE-TIME":E.rawProgramDateTime=F,E.tagList.push(["PROGRAM-DATE-TIME",F]),N===-1&&(N=d.length);break;case"PLAYLIST-TYPE":c.type&&br(c,U,k),c.type=F.toUpperCase();break;case"MEDIA-SEQUENCE":c.startSN!==0?br(c,U,k):d.length>0&&qh(c,U,k),p=c.startSN=parseInt(F);break;case"SKIP":{c.skippedSegments&&br(c,U,k);const I=new ot(F,c),R=I.decimalInteger("SKIPPED-SEGMENTS");if(he(R)){c.skippedSegments+=R;for(let K=R;K--;)d.push(null);p+=R}const O=I.enumeratedString("RECENTLY-REMOVED-DATERANGES");O&&(c.recentlyRemovedDateranges=(c.recentlyRemovedDateranges||[]).concat(O.split(" ")));break}case"TARGETDURATION":c.targetduration!==0&&br(c,U,k),c.targetduration=Math.max(parseInt(F),1);break;case"VERSION":c.version!==null&&br(c,U,k),c.version=parseInt(F);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":c.live||br(c,U,k),c.live=!1;break;case"#":(F||Y)&&E.tagList.push(Y?[F,Y]:[F]);break;case"DISCONTINUITY":b++,E.tagList.push(["DIS"]);break;case"GAP":E.gap=!0,E.tagList.push([U]);break;case"BITRATE":E.tagList.push([U,F]),y=parseInt(F)*1e3,he(y)?E.bitrate=y:y=0;break;case"DATERANGE":{const I=new ot(F,c),R=new Sb(I,c.dateRanges[I.ID],c.dateRangeTagCount);c.dateRangeTagCount++,R.isValid||c.skippedSegments?c.dateRanges[R.id]=R:Ke.warn(`Ignoring invalid DATERANGE tag: "${F}"`),E.tagList.push(["EXT-X-DATERANGE",F]);break}case"DEFINE":{const I=new ot(F,c);"IMPORT"in I?sM(c,I,a):Fh(c,I,r)}break;case"DISCONTINUITY-SEQUENCE":c.startCC!==0?br(c,U,k):d.length>0&&qh(c,U,k),c.startCC=b=parseInt(F);break;case"KEY":{const I=Vh(F,r,c);if(I.isSupported()){if(I.method==="NONE"){A=void 0;break}A||(A={});const R=A[I.keyFormat];R!=null&&R.matches(I)||(R&&(A=ze({},A)),A[I.keyFormat]=I)}else Ke.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${F}"`);break}case"START":c.startTimeOffset=jh(F);break;case"MAP":{const I=new ot(F,c);if(E.duration){const R=new Mo(s,o);Wh(R,I,n,A),f=R,E.initSegment=f,f.rawProgramDateTime&&!E.rawProgramDateTime&&(E.rawProgramDateTime=f.rawProgramDateTime)}else{const R=E.byteRangeEndOffset;if(R){const O=E.byteRangeStartOffset;M=`${R-O}@${O}`}else M=null;Wh(E,I,n,A),f=E,C=!0}f.cc=b;break}case"SERVER-CONTROL":P&&br(c,U,k),P=new ot(F),c.canBlockReload=P.bool("CAN-BLOCK-RELOAD"),c.canSkipUntil=P.optionalFloat("CAN-SKIP-UNTIL",0),c.canSkipDateRanges=c.canSkipUntil>0&&P.bool("CAN-SKIP-DATERANGES"),c.partHoldBack=P.optionalFloat("PART-HOLD-BACK",0),c.holdBack=P.optionalFloat("HOLD-BACK",0);break;case"PART-INF":c.partTarget&&br(c,U,k),c.partTarget=new ot(F).decimalFloatingPoint("PART-TARGET");break;case"PART":{let I=c.partList;I||(I=c.partList=[]);const R=m>0?I[I.length-1]:void 0,O=m++,K=new sR(new ot(F,c),E,o,O,R);I.push(K),E.duration+=K.duration;break}case"PRELOAD-HINT":c.preloadHint=new ot(F,c);break;case"RENDITION-REPORT":{const I=new ot(F,c);c.renditionReports=c.renditionReports||[],c.renditionReports.push(I);break}default:Ke.warn(`line parsed but not handled: ${k}`);break}}}S&&!S.relurl?(d.pop(),g-=S.duration,c.partList&&(c.fragmentHint=S)):c.partList&&(Zl(E,S,h),E.cc=b,c.fragmentHint=E,A&&Qh(E,A,c)),c.targetduration||(c.playlistParsingError=new Error("Missing Target Duration"));const D=d.length,$=d[0],B=d[D-1];if(g+=c.skippedSegments*c.targetduration,g>0&&D&&B){c.averagetargetduration=g/D;const j=B.sn;c.endSN=j!=="initSegment"?j:0,c.live||(B.endList=!0),N>0&&(xM(d,N),$&&h.unshift($))}return c.fragmentHint&&(g+=c.fragmentHint.duration),c.totalduration=g,h.length&&c.dateRangeTagCount&&$&&Ab(h,c),c.endCC=b,c}};function Ab(e,t){let r=e.length;if(!r)if(t.hasProgramDateTime){const l=t.fragments[t.fragments.length-1];e.push(l),r++}else return;const n=e[r-1],s=t.live?1/0:t.totalduration,i=Object.keys(t.dateRanges);for(let l=i.length;l--;){const o=t.dateRanges[i[l]],c=o.startDate.getTime();o.tagAnchor=n.ref;for(let d=r;d--;){var a;if(((a=e[d])==null?void 0:a.sn)<t.startSN)break;const h=yM(t,c,e,d,s);if(h!==-1){o.tagAnchor=t.fragments[h].ref;break}}}}function yM(e,t,r,n,s){const i=r[n];if(i){const l=i.programDateTime;if(t>=l||n===0){var a;if(t<=l+((((a=r[n+1])==null?void 0:a.start)||s)-i.start)*1e3){const o=r[n].sn-e.startSN;if(o<0)return-1;const c=e.fragments;if(c.length>r.length){const d=(r[n+1]||c[c.length-1]).sn-e.startSN;for(let h=d;h>o;h--){const f=c[h].programDateTime;if(t>=f&&t<f+c[h].duration*1e3)return h}}return o}}}return-1}function Vh(e,t,r){var n,s;const i=new ot(e,r),a=(n=i.METHOD)!=null?n:"",l=i.URI,o=i.hexadecimalInteger("IV"),c=i.KEYFORMATVERSIONS,d=(s=i.KEYFORMAT)!=null?s:"identity";return l&&i.IV&&!o&&Ke.error(`Invalid IV: ${i.IV}`),new Ea(a,l?gs.resolve(l,t):"",d,(c||"1").split("/").map(Number).filter(Number.isFinite),o,i.KEYID)}function jh(e){const t=new ot(e).decimalFloatingPoint("TIME-OFFSET");return he(t)?t:null}function Kh(e,t){let r=(e||"").split(/[ ,]+/).filter(n=>n);["video","audio","text"].forEach(n=>{const s=r.filter(i=>fu(i,n));s.length&&(t[`${n}Codec`]=s.map(i=>i.split("/")[0]).join(","),r=r.filter(i=>s.indexOf(i)===-1))}),t.unknownCodecs=r}function zh(e,t,r){const n=t[r];n&&(e[r]=n)}function xM(e,t){let r=e[t];for(let n=t;n--;){const s=e[n];if(!s)return;s.programDateTime=r.programDateTime-s.duration*1e3,r=s}}function Zl(e,t,r){e.rawProgramDateTime?r.push(e):t!=null&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function Wh(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 Qh(e,t,r){e.levelkeys=t;const{encryptedFragments:n}=r;(!n.length||n[n.length-1].levelkeys!==t)&&Object.keys(t).some(s=>t[s].isCommonEncryption)&&n.push(e)}function br(e,t,r){e.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${r[0]})`)}function qh(e,t,r){e.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${r[0]})`)}function Fo(e,t){const r=t.startPTS;if(he(r)){let n=0,s;t.sn>e.sn?(n=r-e.start,s=e):(n=e.start-r,s=t),s.duration!==n&&s.setDuration(n)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration):t.setStart(Math.max(e.start-t.duration,0))}function Cb(e,t,r,n,s,i,a){n-r<=0&&(a.warn("Fragment should have a positive duration",t),n=r+t.duration,i=s+t.duration);let l=r,o=n;const c=t.startPTS,d=t.endPTS;if(he(c)){const b=Math.abs(c-r);e&&b>e.totalduration?a.warn(`media timestamps and playlist times differ by ${b}s for level ${t.level} ${e.url}`):he(t.deltaPTS)?t.deltaPTS=Math.max(b,t.deltaPTS):t.deltaPTS=b,l=Math.max(r,c),r=Math.min(r,c),s=t.startDTS!==void 0?Math.min(s,t.startDTS):s,o=Math.min(n,d),n=Math.max(n,d),i=t.endDTS!==void 0?Math.max(i,t.endDTS):i}const h=r-t.start;t.start!==0&&t.setStart(r),t.setDuration(n-t.start),t.startPTS=r,t.maxStartPTS=l,t.startDTS=s,t.endPTS=n,t.minEndPTS=o,t.endDTS=i;const f=t.sn;if(!e||f<e.startSN||f>e.endSN)return 0;let p;const m=f-e.startSN,g=e.fragments;for(g[m]=t,p=m;p>0;p--)Fo(g[p],g[p-1]);for(p=m;p<g.length-1;p++)Fo(g[p],g[p+1]);return e.fragmentHint&&Fo(g[g.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,h}function SM(e,t,r){if(e===t)return;let n=null;const s=e.fragments;for(let d=s.length-1;d>=0;d--){const h=s[d].initSegment;if(h){n=h;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;let i;kM(e,t,(d,h,f,p)=>{if((!t.startCC||t.skippedSegments)&&h.cc!==d.cc){const m=d.cc-h.cc;for(let g=f;g<p.length;g++)p[g].cc+=m;t.endCC=p[p.length-1].cc}he(d.startPTS)&&he(d.endPTS)&&(h.setStart(h.startPTS=d.startPTS),h.startDTS=d.startDTS,h.maxStartPTS=d.maxStartPTS,h.endPTS=d.endPTS,h.endDTS=d.endDTS,h.minEndPTS=d.minEndPTS,h.setDuration(d.endPTS-d.startPTS),h.duration&&(i=h),t.PTSKnown=t.alignedSliding=!0),d.hasStreams&&(h.elementaryStreams=d.elementaryStreams),h.loader=d.loader,d.hasStats&&(h.stats=d.stats),d.initSegment&&(h.initSegment=d.initSegment,n=d.initSegment)});const a=t.fragments,l=t.fragmentHint?a.concat(t.fragmentHint):a;if(n&&l.forEach(d=>{var h;d&&(!d.initSegment||d.initSegment.relurl===((h=n)==null?void 0:h.relurl))&&(d.initSegment=n)}),t.skippedSegments){if(t.deltaUpdateFailed=a.some(d=>!d),t.deltaUpdateFailed){r.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let d=t.skippedSegments;d--;)a.shift();t.startSN=a[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=EM(e.dateRanges,t,r));const d=e.fragments.filter(h=>h.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let h=1;h<l.length;h++)l[h].programDateTime===null&&Zl(l[h],l[h-1],d);Ab(d,t)}t.endCC=a[a.length-1].cc}if(!t.startCC){var o;const d=Ib(e,t.startSN-1);t.startCC=(o=d?.cc)!=null?o:a[0].cc}wM(e.partList,t.partList,(d,h)=>{h.elementaryStreams=d.elementaryStreams,h.stats=d.stats}),i?Cb(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,r):Nb(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const c=t.advancedDateTime;if(t.advanced&&c){const d=t.edge;t.driftStart||(t.driftStartTime=c,t.driftStart=d),t.driftEndTime=c,t.driftEnd=d}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;t.requestScheduled===-1&&(t.requestScheduled=e.requestScheduled)}function EM(e,t,r){const{dateRanges:n,recentlyRemovedDateranges:s}=t,i=ze({},e);s&&s.forEach(l=>{delete i[l]});const a=Object.keys(i).length;return a?(Object.keys(n).forEach(l=>{const o=i[l],c=new Sb(n[l].attr,o);c.isValid?(i[l]=c,o||(c.tagOrder+=a)):r.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${qe(n[l].attr)}"`)}),i):n}function wM(e,t,r){if(e&&t){let n=0;for(let s=0,i=e.length;s<=i;s++){const a=e[s],l=t[s+n];a&&l&&a.index===l.index&&a.fragment.sn===l.fragment.sn?r(a,l):n--}}}function kM(e,t,r){const n=t.skippedSegments,s=Math.max(e.startSN,t.startSN)-t.startSN,i=(e.fragmentHint?1:0)+(n?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let c=s;c<=i;c++){const d=o[a+c];let h=l[c];if(n&&!h&&d&&(h=t.fragments[c]=d),d&&h){r(d,h,c,l);const f=d.relurl,p=h.relurl;if(f&&TM(f,p)){t.playlistParsingError=Yh(`media sequence mismatch ${h.sn}:`,e,t,d,h);return}else if(d.cc!==h.cc){t.playlistParsingError=Yh(`discontinuity sequence mismatch (${d.cc}!=${h.cc})`,e,t,d,h);return}}}}function Yh(e,t,r,n,s){return new Error(`${e} ${s.url}
96
+ Playlist starting @${t.startSN}
97
+ ${t.m3u8}
98
+
99
+ Playlist starting @${r.startSN}
100
+ ${r.m3u8}`)}function Nb(e,t,r=!0){const n=t.startSN+t.skippedSegments-e.startSN,s=e.fragments,i=n>=0;let a=0;if(i&&n<s.length)a=s[n].start;else if(i&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(i&&r)a=e.fragmentStart+n*t.levelTargetDuration;else if(!t.skippedSegments&&t.fragmentStart===0)a=e.fragmentStart;else return;Jl(t,a)}function Jl(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 Lb(e,t=1/0){let r=1e3*e.targetduration;if(e.updated){const n=e.fragments;if(n.length&&r*4>t){const s=n[n.length-1].duration*1e3;s<r&&(r=s)}}else r/=2;return Math.round(r)}function Ib(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 Xh(e,t,r){return e?Rb(e.partList,t,r):null}function Rb(e,t,r){if(e)for(let n=e.length;n--;){const s=e[n];if(s.index===r&&s.fragment.sn===t)return s}return null}function Mb(e){e.forEach((t,r)=>{var n;(n=t.details)==null||n.fragments.forEach(s=>{s.level=r,s.initSegment&&(s.initSegment.level=r)})})}function TM(e,t){return e!==t&&t?Zh(e)!==Zh(t):!1}function Zh(e){return e.replace(/\?[^?]*$/,"")}function As(e,t){for(let n=0,s=e.length;n<s;n++){var r;if(((r=e[n])==null?void 0:r.cc)===t)return e[n]}return null}function AM(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}function Jh(e,t){const r=e.start+t;e.startPTS=r,e.setStart(r),e.endPTS=r+e.duration}function Pb(e,t){const r=t.fragments;for(let n=0,s=r.length;n<s;n++)Jh(r[n],e);t.fragmentHint&&Jh(t.fragmentHint,e),t.alignedSliding=!0}function CM(e,t){e&&(Db(t,e),t.alignedSliding||wa(t,e),!t.alignedSliding&&!t.skippedSegments&&Nb(e,t,!1))}function Db(e,t){if(!AM(t,e))return;const r=Math.min(t.endCC,e.endCC),n=As(t.fragments,r),s=As(e.fragments,r);!n||!s||(Ke.log(`Aligning playlist at start of dicontinuity sequence ${r}`),Pb(n.start-s.start,e))}function wa(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const r=e.fragments,n=t.fragments;if(!r.length||!n.length)return;let s,i;const a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(s=As(n,a),i=As(r,a)),(!s||!i)&&(s=n[Math.floor(n.length/2)],i=As(r,s.cc)||r[Math.floor(r.length/2)]);const l=s.programDateTime,o=i.programDateTime;!l||!o||Pb((o-l)/1e3-(i.start-s.start),e)}function Lt(e,t,r){Mt(e,t,r),e.addEventListener(t,r)}function Mt(e,t,r){e.removeEventListener(t,r)}var NM={toString: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}},X={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},xu=class extends bb{constructor(e,t,r,n,s){super(n,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=X.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:i,fragCurrent:a,media:l,mediaBuffer:o,state:c}=this,d=l?l.currentTime:0,h=De.bufferInfo(o||l,d,i.maxBufferHole),f=!h.len;if(this.log(`Media seeking to ${he(d)?d.toFixed(3):d}, state: ${c}, ${f?"out of":"in"} buffer`),this.state===X.ENDED)this.resetLoadingState();else if(a){const p=i.maxFragLookUpTolerance,m=a.start-p,g=a.start+a.duration+p;if(f||g<h.start||m>h.end){const b=d>g;(d<m||b)&&(b&&a.loader&&(this.log(`Cancelling fragment load for seek (sn: ${a.sn})`),a.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(l&&(this.fragmentTracker.removeFragmentsInRange(d,1/0,this.playlistType,!0),d>this.lastCurrentTime&&(this.lastCurrentTime=d),!this.loadingParts)){const p=Math.max(h.end,d),m=this.shouldLoadParts(this.getLevelDetails(),p);m&&(this.log(`LL-Part loading ON after seeking to ${d.toFixed(2)} with buffer @${p.toFixed(2)}`),this.loadingParts=m)}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${d} for seek without enough to start`),this.nextLoadPosition=d,f&&(this.startPosition=d)),f&&this.state===X.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=s,this.hls=e,this.fragmentLoader=new rM(e.config),this.keyLoader=r,this.fragmentTracker=t,this.config=e.config,this.decrypter=new gu(e.config)}registerListeners(){const{hls:e}=this;e.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(w.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(w.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===X.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=X.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&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 s=e.buffered;this.config.maxBufferHole&&s&&s.length>1&&(e=De.bufferedInfo(s,e.start,0));const i=e.nextStart;if(i&&i>n&&i<t.edge||this.media.currentTime<e.start)return!1;const a=t.partList;if(a!=null&&a.length){const o=a[a.length-1];return De.isBuffered(this.media,o.start+o.duration/2)}const l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const r=this.media=this.mediaBuffer=t.media;Lt(r,"seeking",this.onMediaSeeking),Lt(r,"ended",this.onMediaEnded);const n=this.config;this.levels&&n.autoStartLoad&&this.state===X.STOPPED&&this.startLoad(n.startPosition)}onMediaDetaching(e,t){const r=!!t.transferMedia,n=this.media;if(n!==null){if(n.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Mt(n,"seeking",this.onMediaSeeking),Mt(n,"ended",this.onMediaEnded),this.keyLoader&&!r&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,r){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,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=X.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,r){this.startFragRequested=!0,this._loadFragForPlayback(e,t,r)}_loadFragForPlayback(e,t,r){const n=s=>{const i=s.frag;if(this.fragContextChanged(i)){this.warn(`${i.type} sn: ${i.sn}${s.part?" part: "+s.part.index:""} of ${this.fragInfo(i,!1,s.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(i);return}i.stats.chunkCount++,this._handleFragmentLoadProgress(s)};this._doFragLoad(e,t,r,n).then(s=>{if(!s)return;const i=this.state,a=s.frag;if(this.fragContextChanged(a)){(i===X.FRAG_LOADING||!this.fragCurrent&&i===X.PARSING)&&(this.fragmentTracker.removeFragment(a),this.state=X.IDLE);return}"payload"in s&&(this.log(`Loaded ${a.type} sn: ${a.sn} of ${this.playlistLabel()} ${a.level}`),this.hls.trigger(w.FRAG_LOADED,s)),this._handleFragmentLoadComplete(s)}).catch(s=>{this.state===X.STOPPED||this.state===X.ERROR||(this.warn(`Frag error: ${s?.message||s}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:r}=this;if(r.getState(e)===gt.APPENDING){const n=e.type,s=this.getFwdBufferInfo(this.mediaBuffer,n),i=Math.max(e.duration,s?s.len:this.config.maxBufferLength),a=this.backtrackFragment;((a?e.sn-a.sn:0)===1||this.reduceMaxBufferLength(i,e.duration))&&r.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?r.removeAllFragments():r.hasParts(e.type)&&(r.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),r.getState(e)===gt.PARTIAL&&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 t?.live&&t.type!=="EVENT"&&(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(w.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(r=>{const n=r?.frag;if(!n||this.fragContextChanged(n)||!this.levels)throw new Error("init load aborted");return r}).then(r=>{const{hls:n}=this,{frag:s,payload:i}=r,a=s.decryptdata;if(i&&i.byteLength>0&&a!=null&&a.key&&a.iv&&Kn(a.method)){const l=self.performance.now();return this.decrypter.decrypt(new Uint8Array(i),a.key.buffer,a.iv.buffer,bu(a.method)).catch(o=>{throw n.trigger(w.ERROR,{type:xe.MEDIA_ERROR,details:G.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:s}),o}).then(o=>{const c=self.performance.now();return n.trigger(w.FRAG_DECRYPTED,{frag:s,payload:o,stats:{tstart:l,tdecrypt:c}}),r.payload=o,this.completeInitSegmentLoad(r)})}return this.completeInitSegmentLoad(r)}).catch(r=>{this.state===X.STOPPED||this.state===X.ERROR||(this.warn(r),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!==X.STOPPED&&(this.state=X.IDLE),e.frag.data=new Uint8Array(e.payload),r.parsing.start=r.buffering.start=self.performance.now(),r.parsing.end=r.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var r,n;const s=e.tracks;if(s&&!t.encrypted&&((r=s.audio)!=null&&r.encrypted||(n=s.video)!=null&&n.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const i=this.media,a=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${i?"attached mediaKeys: "+i.mediaKeys:"detached"})`);return this.warn(a.message),!i||i.mediaKeys?!1:(this.hls.trigger(w.ERROR,{type:xe.KEY_SYSTEM_ERROR,details:G.KEY_SYSTEM_NO_KEYS,fatal:!1,error:a,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?NM.toString(De.getBuffered(r)):"(detached)"})`),lt(e)){var n;if(e.type!==fe.SUBTITLE){const i=e.elementaryStreams;if(!Object.keys(i).some(a=>!!i[a])){this.state=X.IDLE;return}}const s=(n=this.levels)==null?void 0:n[e.level];s!=null&&s.fragmentError&&(this.log(`Resetting level fragment error count of ${s.fragmentError} on frag buffered`),s.fragmentError=0)}this.state=X.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:r,part:n,partsLoaded:s}=e,i=!s||s.length===0||s.some(l=>!l),a=new vu(r.level,r.sn,r.stats.chunkCount+1,0,n?n.index:-1,!i);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,r=null,n){var s;this.fragCurrent=e;const i=t.details;if(!this.levels||!i)throw new Error(`frag load aborted, missing level${i?"":" detail"}s`);let a=null;if(e.encrypted&&!((s=e.decryptdata)!=null&&s.key)){if(this.log(`Loading key for ${e.sn} of [${i.startSN}-${i.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=X.KEY_LOADING,this.fragCurrent=e,a=this.keyLoader.load(e).then(h=>{if(!this.fragContextChanged(h.frag))return this.hls.trigger(w.KEY_LOADED,h),this.state===X.KEY_LOADING&&(this.state=X.IDLE),h}),this.hls.trigger(w.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(a=this.keyLoader.loadClear(e,i.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));const l=this.fragPrevious;if(lt(e)&&(!l||e.sn!==l.sn)){const h=this.shouldLoadParts(t.details,e.end);h!==this.loadingParts&&(this.log(`LL-Part loading ${h?"ON":"OFF"} loading sn ${l?.sn}->${e.sn}`),this.loadingParts=h)}if(r=Math.max(e.start,r||0),this.loadingParts&&lt(e)){const h=i.partList;if(h&&n){r>i.fragmentEnd&&i.fragmentHint&&(e=i.fragmentHint);const f=this.getNextPart(h,e,r);if(f>-1){const p=h[f];e=this.fragCurrent=p.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${p.index} (${f}/${h.length-1}) of ${this.fragInfo(e,!1,p)}) cc: ${e.cc} [${i.startSN}-${i.endSN}], target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=p.start+p.duration,this.state=X.FRAG_LOADING;let m;return a?m=a.then(g=>!g||this.fragContextChanged(g.frag)?null:this.doFragPartsLoad(e,p,t,n)).catch(g=>this.handleFragLoadError(g)):m=this.doFragPartsLoad(e,p,t,n).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(w.FRAG_LOADING,{frag:e,part:p,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):m}else if(!e.url||this.loadedEndOfParts(h,r))return Promise.resolve(null)}}if(lt(e)&&this.loadingParts){var o;this.log(`LL-Part loading OFF after next part miss @${r.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(o=i.partList)==null?void 0:o.filter(h=>h.loaded).map(h=>`[${h.start}-${h.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+i.startSN+"-"+i.endSN+"]"}, target: ${parseFloat(r.toFixed(3))}`),he(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=X.FRAG_LOADING;const c=this.config.progressive&&e.type!==fe.SUBTITLE;let d;return c&&a?d=a.then(h=>!h||this.fragContextChanged(h.frag)?null:this.fragmentLoader.load(e,n)).catch(h=>this.handleFragLoadError(h)):d=Promise.all([this.fragmentLoader.load(e,c?n:void 0),a]).then(([h])=>(!c&&n&&n(h),h)).catch(h=>this.handleFragLoadError(h)),this.hls.trigger(w.FRAG_LOADING,{frag:e,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):d}doFragPartsLoad(e,t,r,n){return new Promise((s,i)=>{var a;const l=[],o=(a=r.details)==null?void 0:a.partList,c=d=>{this.fragmentLoader.loadPart(e,d,n).then(h=>{l[d.index]=h;const f=h.part;this.hls.trigger(w.FRAG_LOADED,h);const p=Xh(r.details,e.sn,d.index+1)||Rb(o,e.sn,d.index+1);if(p)c(p);else return s({frag:e,part:f,partsLoaded:l})}).catch(i)};c(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===G.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===xe.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(w.ERROR,t)}else this.hls.trigger(w.ERROR,{type:xe.OTHER_ERROR,details:G.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==X.PARSING){!this.fragCurrent&&this.state!==X.STOPPED&&this.state!==X.ERROR&&(this.state=X.IDLE);return}const{frag:r,part:n,level:s}=t,i=self.performance.now();r.stats.parsing.end=i,n&&(n.stats.parsing.end=i);const a=this.getLevelDetails(),l=a&&r.sn>a.endSN||this.shouldLoadParts(a,r.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${r.end.toFixed(2)}`),this.loadingParts=l),this.updateLevelTiming(r,n,s,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var r;const s=e.partList[0];if(s.fragment.type===fe.SUBTITLE)return!1;if(t>=s.end+(((r=e.fragmentHint)==null?void 0:r.duration)||0)){var n;if((this.hls.hasEnoughToStart?((n=this.media)==null?void 0:n.currentTime)||this.lastCurrentTime:this.getLoadPosition())>s.start-s.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:r}=this,{level:n,sn:s,part:i}=e;if(!(t!=null&&t[n]))return this.warn(`Levels object was unset while buffering fragment ${s} of ${this.playlistLabel()} ${n}. The current chunk will not be buffered.`),null;const a=t[n],l=a.details,o=i>-1?Xh(l,s,i):null,c=o?o.fragment:Ib(l,s,r);return c?(r&&r!==c&&(c.stats=r.stats),{frag:c,part:o,level:a}):null}bufferFragmentData(e,t,r,n,s){if(this.state!==X.PARSING)return;const{data1:i,data2:a}=e;let l=i;if(a&&(l=Wt(i,a)),!l.length)return;const o=this.initPTS[t.cc],c=o?-o.baseTime/o.timescale:void 0,d={type:e.type,frag:t,part:r,chunkMeta:n,offset:c,parent:t.type,data:l};if(this.hls.trigger(w.BUFFER_APPENDING,d),e.dropped&&e.independent&&!r){if(s)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!De.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const r=t.currentTime,n=De.bufferInfo(t,r,0),s=e.duration,i=Math.min(this.config.maxFragLookUpTolerance*2,s*.25),a=Math.max(Math.min(e.start-i,n.end-i),r+i);e.start-a>i&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var r;const n=this.getLoadPosition();if(!he(n))return null;const s=this.lastCurrentTime>n||(r=this.media)!=null&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,s)}getFwdBufferInfoAtPos(e,t,r,n){const s=De.bufferInfo(e,t,n);if(s.len===0&&s.nextStart!==void 0){const i=this.fragmentTracker.getBufferedFrag(t,r);if(i&&(s.nextStart<=i.end||i.gap)){const a=Math.max(Math.min(s.nextStart,i.end)-t,n);return De.bufferInfo(e,t,a)}}return s}getMaxBufferLength(e){const{config:t}=this;let r;return e?r=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):r=t.maxBufferLength,Math.min(r,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,r){const n=e.nextStart;if(n&&r.start>n){const s=e.buffered;if(s){let i=e.len;const a=e.bufferedIndex;for(let l=s.length-1;l>a;l--)s[l].start<r.start&&(i+=s[l].end-s[l].start);return i>=t}}return!1}reduceMaxBufferLength(e,t){const r=this.config,n=Math.max(Math.min(e-t,r.maxBufferLength),t),s=Math.max(e-t*3,r.maxMaxBufferLength/2,n);return s>=n?(r.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0):!1}getAppendedFrag(e,t=fe.MAIN){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:s}=this,i=t.fragmentStart,a=s.lowLatencyMode&&!!t.partList;let l=null;if(t.live){const d=s.initialLiveManifestSize;if(n<d)return this.warn(`Not enough fragments to start playback (have: ${n}, need: ${d})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<i){var o;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),l=this.getInitialLiveFragment(t);const h=this.config.startPosition,f=this.hls.startPosition,p=this.hls.liveSyncPosition,m=((o=l)==null?void 0:o.start)||0;let g,b;f!==-1&&f>=i?(g=f,b=f===h?"config":"next load start"):p!==null?(g=p,b="live edge"):(g=e,b="buffer pos"),g<m&&(g=m,b="live frag start"),g<i&&(g=i,b="playlist start"),(this.startPosition!=g||this.nextLoadPosition!=g)&&(this.log(`Setting startPosition to ${g.toFixed(3)} ${f===-1?"":`(from ${h}) `}based on ${b}. live edge: ${p} live frag start: ${m.toFixed(3)} playlist start: ${i.toFixed(3)} buffer pos: ${e}`),this.startPosition=this.nextLoadPosition=g)}}else e<=i&&(l=r[0]);if(!l){const d=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,d,t)}let c=this.filterReplacedPrimary(l,t);if(!c&&l){const d=l.sn-t.startSN;c=this.filterReplacedPrimary(r[d+1]||null,t)}return this.mapToInitFragWhenRequired(c)}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;const r=this.fragmentTracker.getState(e);return r===gt.OK||r===gt.PARTIAL&&!!e.gap}getNextFragmentLoopLoading(e,t,r,n,s){let i=null;if(e.gap&&(i=this.getNextFragment(this.nextLoadPosition,t),i&&!i.gap&&r.nextStart)){const a=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,n,0);if(a!==null&&r.len+a.len>=s){const l=i.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,i}get primaryPrefetch(){if(ef(this.config)){var e;if(!((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null)&&e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(ef(this.config)&&e.type!==fe.SUBTITLE){const r=this.hls.interstitialsManager,n=r?.bufferingItem;if(n){const i=n.event;if(i){if(i.appendInPlace||Math.abs(e.start-n.start)>1||n.start===0)return null}else if(e.end<=n.start&&t?.live===!1||e.start>n.end&&n.nextEvent&&(n.nextEvent.appendInPlace||e.start-n.end>1))return null}const s=r?.playerQueue;if(s)for(let i=s.length;i--;){const a=s[i].interstitial;if(a.appendInPlace&&e.start>=a.startTime&&e.end<=a.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,r){let n=-1,s=!1,i=!0;for(let a=0,l=e.length;a<l;a++){const o=e[a];if(i=i&&!o.independent,n>-1&&r<o.start)break;const c=o.loaded;c?n=-1:(s||(o.independent||i)&&o.fragment===t)&&(o.fragment!==t&&this.warn(`Need buffer at ${r} but next unloaded part starts at ${o.start}`),n=a),s=c}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&&(n=jR(t,r.endProgramDateTime,this.config.maxFragLookUpTolerance),n&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${r.programDateTime}`)),!n){const s=r.sn+1;if(s>=e.startSN&&s<=e.endSN){const i=t[s-e.startSN];r.cc===i.cc&&(n=i,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=mb(e,r.cc,r.end),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const s=this.hls.liveSyncPosition;s!==null&&(n=this.getFragmentAtPosition(s,this.bitrateTest?e.fragmentEnd:e.edge,e))}return n}getFragmentAtPosition(e,t,r){const{config:n}=this;let{fragPrevious:s}=this,{fragments:i,endSN:a}=r;const{fragmentHint:l}=r,{maxFragLookUpTolerance:o}=n,c=r.partList,d=!!(this.loadingParts&&c!=null&&c.length&&l);d&&!this.bitrateTest&&c[c.length-1].fragment.sn===l.sn&&(i=i.concat(l),a=l.sn);let h;if(e<t){var f;const p=e<this.lastCurrentTime||e>t-o||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:o;h=fn(s,i,e,p)}else h=i[i.length-1];if(h){const p=h.sn-r.startSN,m=this.fragmentTracker.getState(h);if((m===gt.OK||m===gt.PARTIAL&&h.gap)&&(s=h),s&&h.sn===s.sn&&(!d||c[0].fragment.sn>h.sn||!r.live)&&h.level===s.level){const g=i[p+1];h.sn<a&&this.fragmentTracker.getState(g)!==gt.OK?h=g:h=null}}return h}alignPlaylists(e,t,r){const n=e.fragments.length;if(!n)return this.warn("No fragments in live playlist"),0;const s=e.fragmentStart,i=!t,a=e.alignedSliding&&he(s);if(i||!a&&!s){CM(r,e);const l=e.fragmentStart;return this.log(`Live playlist sliding: ${l.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${n}`),l}return s}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let r=this.startPosition;r<t&&(r=-1);const n=this.timelineOffset;if(r===-1){const s=this.startTimeOffset!==null,i=s?this.startTimeOffset:e.startTimeOffset;i!==null&&he(i)?(r=t+i,i<0&&(r+=e.edge),r=Math.min(Math.max(t,r),t+e.totalduration),this.log(`Setting startPosition to ${r} for start time offset ${i} found in ${s?"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(e=this.hls)!=null&&e.hasEnoughToStart&&t?r=t.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&lt(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!==X.FRAG_LOADING_WAITING_RETRY)&&(this.state=X.IDLE)}onFragmentOrKeyLoadError(e,t){var r;if(t.chunkMeta&&!t.frag){const b=this.getCurrentContext(t.chunkMeta);b&&(t.frag=b.frag)}const n=t.frag;if(!n||n.type!==e||!this.levels)return;if(this.fragContextChanged(n)){var s;this.warn(`Frag load error must match current frag to retry ${n.url} > ${(s=this.fragCurrent)==null?void 0:s.url}`);return}const i=t.details===G.FRAG_GAP;i&&this.fragmentTracker.fragBuffered(n,!0);const a=t.errorAction;if(!a){this.state=X.ERROR;return}const{action:l,flags:o,retryCount:c=0,retryConfig:d}=a,h=!!d,f=h&&l===Et.RetryRequest,p=h&&!a.resolved&&o===Dt.MoveAllAlternatesMatchingHost,m=(r=this.hls.latestLevelDetails)==null?void 0:r.live;if(!f&&p&&lt(n)&&!n.endList&&m&&!vb(t))this.resetFragmentErrors(e),this.treatAsGap(n),a.resolved=!0;else if((f||p)&&c<d.maxNumRetry){var g;const b=ql((g=t.response)==null?void 0:g.code),y=mu(d,c);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+y,this.state=X.FRAG_LOADING_WAITING_RETRY,a.resolved=!0,b){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${n.sn} of ${e} ${n.level} errored with ${t.details}, retrying loading ${c+1}/${d.maxNumRetry} in ${y}ms`)}else if(d)if(this.resetFragmentErrors(e),c<d.maxNumRetry)!i&&l!==Et.RemoveAlternatePermanently&&(a.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${c})`);return}else l===Et.SendAlternateToPenaltyBox?this.state=X.WAITING_LEVEL:this.state=X.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,r=t===1/0;(!t||e>=t||r&&!ql(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=X.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===X.PARSING||this.state===X.PARSED){const t=e.frag,r=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,r),s=n&&n.len>.5;s&&this.reduceMaxBufferLength(n.len,t?.duration||10);const i=!s;return i&&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(),i}return!1}resetFragmentErrors(e){e===fe.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==X.STOPPED&&(this.state=X.IDLE)}afterBufferFlushed(e,t,r){if(!e)return;const n=De.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,r),this.state===X.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==X.STOPPED&&(this.state=X.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;t!=null&&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()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,r,n){const s=r.details;if(!s){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((a,l)=>{const o=e.elementaryStreams[l];if(o){const c=o.endPTS-o.startPTS;if(c<=0)return this.warn(`Could not parse fragment ${e.sn} ${l} duration reliably (${c})`),a||!1;const d=n?0:Cb(s,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS,this);return this.hls.trigger(w.LEVEL_PTS_UPDATED,{details:s,level:r,drift:d,type:l,frag:e,start:o.startPTS,end:o.endPTS}),!0}return a},!1)){var i;const a=((i=this.transmuxer)==null?void 0:i.error)===null;if((r.fragmentError===0||a&&(r.fragmentError<2||e.endList))&&this.treatAsGap(e,r),a){const l=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(w.ERROR,{type:xe.MEDIA_ERROR,details:G.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${r.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=X.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(w.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===fe.MAIN?"level":"track"}fragInfo(e,t=!0,r){var n,s;return`${this.playlistLabel()} ${e.level} (${r?"part":"frag"}:[${((n=t&&!r?e.startPTS:(r||e).start)!=null?n:NaN).toFixed(3)}-${((s=t&&!r?e.endPTS:(r||e).end)!=null?s:NaN).toFixed(3)}]${r&&e.type==="main"?"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;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}};function ef(e){return!!e.interstitialsController&&e.enableInterstitialPlayback!==!1}var _b=class{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;if(e.length)e.length===1?r=e[0]:r=LM(e,t);else return new Uint8Array(0);return this.reset(),r}reset(){this.chunks.length=0,this.dataLength=0}};function LM(e,t){const r=new Uint8Array(t);let n=0;for(let s=0;s<e.length;s++){const i=e[s];r.set(i,n),n+=i.length}return r}var $o={exports:{}},tf;function IM(){return tf||(tf=1,(function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(r=!1));function s(o,c,d){this.fn=o,this.context=c,this.once=d||!1}function i(o,c,d,h,f){if(typeof d!="function")throw new TypeError("The listener must be a function");var p=new s(d,h||o,f),m=r?r+c:c;return o._events[m]?o._events[m].fn?o._events[m]=[o._events[m],p]:o._events[m].push(p):(o._events[m]=p,o._eventsCount++),o}function a(o,c){--o._eventsCount===0?o._events=new n:delete o._events[c]}function l(){this._events=new n,this._eventsCount=0}l.prototype.eventNames=function(){var c=[],d,h;if(this._eventsCount===0)return c;for(h in d=this._events)t.call(d,h)&&c.push(r?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(d)):c},l.prototype.listeners=function(c){var d=r?r+c:c,h=this._events[d];if(!h)return[];if(h.fn)return[h.fn];for(var f=0,p=h.length,m=new Array(p);f<p;f++)m[f]=h[f].fn;return m},l.prototype.listenerCount=function(c){var d=r?r+c:c,h=this._events[d];return h?h.fn?1:h.length:0},l.prototype.emit=function(c,d,h,f,p,m){var g=r?r+c:c;if(!this._events[g])return!1;var b=this._events[g],y=arguments.length,S,E;if(b.fn){switch(b.once&&this.removeListener(c,b.fn,void 0,!0),y){case 1:return b.fn.call(b.context),!0;case 2:return b.fn.call(b.context,d),!0;case 3:return b.fn.call(b.context,d,h),!0;case 4:return b.fn.call(b.context,d,h,f),!0;case 5:return b.fn.call(b.context,d,h,f,p),!0;case 6:return b.fn.call(b.context,d,h,f,p,m),!0}for(E=1,S=new Array(y-1);E<y;E++)S[E-1]=arguments[E];b.fn.apply(b.context,S)}else{var k=b.length,T;for(E=0;E<k;E++)switch(b[E].once&&this.removeListener(c,b[E].fn,void 0,!0),y){case 1:b[E].fn.call(b[E].context);break;case 2:b[E].fn.call(b[E].context,d);break;case 3:b[E].fn.call(b[E].context,d,h);break;case 4:b[E].fn.call(b[E].context,d,h,f);break;default:if(!S)for(T=1,S=new Array(y-1);T<y;T++)S[T-1]=arguments[T];b[E].fn.apply(b[E].context,S)}}return!0},l.prototype.on=function(c,d,h){return i(this,c,d,h,!1)},l.prototype.once=function(c,d,h){return i(this,c,d,h,!0)},l.prototype.removeListener=function(c,d,h,f){var p=r?r+c:c;if(!this._events[p])return this;if(!d)return a(this,p),this;var m=this._events[p];if(m.fn)m.fn===d&&(!f||m.once)&&(!h||m.context===h)&&a(this,p);else{for(var g=0,b=[],y=m.length;g<y;g++)(m[g].fn!==d||f&&!m[g].once||h&&m[g].context!==h)&&b.push(m[g]);b.length?this._events[p]=b.length===1?b[0]:b:a(this,p)}return this},l.prototype.removeAllListeners=function(c){var d;return c?(d=r?r+c:c,this._events[d]&&a(this,d)):(this._events=new n,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=r,l.EventEmitter=l,e.exports=l})($o)),$o.exports}var Su=rR(IM()),zs="1.6.16",es={};function RM(){return typeof __HLS_WORKER_BUNDLE__=="function"}function MM(){const e=es[zs];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 es[zs]=n,n}function PM(e){const t=es[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 es[e]=n,n}function DM(e){const t=es[e||zs];if(t&&t.clientCount--===1){const{worker:r,objectURL:n}=t;delete es[e||zs],n&&self.URL.revokeObjectURL(n),r.terminate()}}function Ob(e,t){return t+10<=e.length&&e[t]===51&&e[t+1]===68&&e[t+2]===73&&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 Eu(e,t){return t+10<=e.length&&e[t]===73&&e[t+1]===68&&e[t+2]===51&&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 Fa(e,t){let r=0;return r=(e[t]&127)<<21,r|=(e[t+1]&127)<<14,r|=(e[t+2]&127)<<7,r|=e[t+3]&127,r}function Ws(e,t){const r=t;let n=0;for(;Eu(e,t);){n+=10;const s=Fa(e,t+6);n+=s,Ob(e,t+10)&&(n+=10),t+=n}if(n>0)return e.subarray(r,r+n)}function _M(e,t,r,n){const s=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],i=t[r+2],a=i>>2&15;if(a>12){const p=new Error(`invalid ADTS sampling index:${a}`);e.emit(w.ERROR,w.ERROR,{type:xe.MEDIA_ERROR,details:G.FRAG_PARSING_ERROR,fatal:!0,error:p,reason:p.message});return}const l=(i>>6&3)+1,o=t[r+3]>>6&3|(i&1)<<2,c="mp4a.40."+l,d=s[a];let h=a;(l===5||l===29)&&(h-=3);const f=[l<<3|(h&14)>>1,(h&1)<<7|o<<3];return Ke.log(`manifest codec:${n}, parsed codec:${c}, channels:${o}, rate:${d} (ADTS object type:${l} sampling index:${a})`),{config:f,samplerate:d,channelCount:o,codec:c,parsedCodec:c,manifestCodec:n}}function Fb(e,t){return e[t]===255&&(e[t+1]&246)===240}function $b(e,t){return e[t+1]&1?7:9}function wu(e,t){return(e[t+3]&3)<<11|e[t+4]<<3|(e[t+5]&224)>>>5}function OM(e,t){return t+5<e.length}function ka(e,t){return t+1<e.length&&Fb(e,t)}function FM(e,t){return OM(e,t)&&Fb(e,t)&&wu(e,t)<=e.length-t}function $M(e,t){if(ka(e,t)){const r=$b(e,t);if(t+r>=e.length)return!1;const n=wu(e,t);if(n<=r)return!1;const s=t+n;return s===e.length||ka(e,s)}return!1}function Bb(e,t,r,n,s){if(!e.samplerate){const i=_M(t,r,n,s);if(!i)return;ze(e,i)}}function Ub(e){return 1024*9e4/e}function BM(e,t){const r=$b(e,t);if(t+r<=e.length){const n=wu(e,t)-r;if(n>0)return{headerLength:r,frameLength:n}}}function Gb(e,t,r,n,s){const i=n+s*Ub(e.samplerate),a=BM(t,r);let l;if(a){const{frameLength:c,headerLength:d}=a,h=d+c,f=Math.max(0,r+h-t.length);f?(l=new Uint8Array(h-d),l.set(t.subarray(r+d,t.length),0)):l=t.subarray(r+d,r+h);const p={unit:l,pts:i};return f||e.samples.push(p),{sample:p,length:h,missing:f}}const o=t.length-r;return l=new Uint8Array(o),l.set(t.subarray(r,t.length),0),{sample:{unit:l,pts:i},length:o,missing:-1}}function UM(e,t){return Eu(e,t)&&Fa(e,t+6)+10<=e.length-t}function GM(e){return e instanceof ArrayBuffer?e:e.byteOffset==0&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}function Bo(e,t=0,r=1/0){return HM(e,t,r,Uint8Array)}function HM(e,t,r,n){const s=VM(e);let i=1;"BYTES_PER_ELEMENT"in n&&(i=n.BYTES_PER_ELEMENT);const a=jM(e)?e.byteOffset:0,l=(a+e.byteLength)/i,o=(a+t)/i,c=Math.floor(Math.max(0,Math.min(o,l)));return new n(s,c,Math.floor(Math.min(c+Math.max(r,0),l))-c)}function VM(e){return e instanceof ArrayBuffer?e:e.buffer}function jM(e){return e&&e.buffer instanceof ArrayBuffer&&e.byteLength!==void 0&&e.byteOffset!==void 0}function KM(e){const t={key:e.type,description:"",data:"",mimeType:null,pictureType:null},r=3;if(e.size<2)return;if(e.data[0]!==r){console.log("Ignore frame with unrecognized character encoding");return}const n=e.data.subarray(1).indexOf(0);if(n===-1)return;const s=Bt(Bo(e.data,1,n)),i=e.data[2+n],a=e.data.subarray(3+n).indexOf(0);if(a===-1)return;const l=Bt(Bo(e.data,3+n,a));let o;return s==="-->"?o=Bt(Bo(e.data,4+n+a)):o=GM(e.data.subarray(4+n+a)),t.mimeType=s,t.pictureType=i,t.description=l,t.data=o,t}function zM(e){if(e.size<2)return;const t=Bt(e.data,!0),r=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:r.buffer}}function WM(e){if(e.size<2)return;if(e.type==="TXXX"){let r=1;const n=Bt(e.data.subarray(r),!0);r+=n.length+1;const s=Bt(e.data.subarray(r));return{key:e.type,info:n,data:s}}const t=Bt(e.data.subarray(1));return{key:e.type,info:"",data:t}}function QM(e){if(e.type==="WXXX"){if(e.size<2)return;let r=1;const n=Bt(e.data.subarray(r),!0);r+=n.length+1;const s=Bt(e.data.subarray(r));return{key:e.type,info:n,data:s}}const t=Bt(e.data);return{key:e.type,info:"",data:t}}function qM(e){return e.type==="PRIV"?zM(e):e.type[0]==="W"?QM(e):e.type==="APIC"?KM(e):WM(e)}function YM(e){const t=String.fromCharCode(e[0],e[1],e[2],e[3]),r=Fa(e,4),n=10;return{type:t,size:r,data:e.subarray(n,n+r)}}var bi=10,XM=10;function Hb(e){let t=0;const r=[];for(;Eu(e,t);){const n=Fa(e,t+6);e[t+5]>>6&1&&(t+=bi),t+=bi;const s=t+n;for(;t+XM<s;){const i=YM(e.subarray(t)),a=qM(i);a&&r.push(a),t+=i.size+bi}Ob(e,t)&&(t+=bi)}return r}function Vb(e){return e&&e.key==="PRIV"&&e.info==="com.apple.streaming.transportStreamTimestamp"}function ZM(e){if(e.data.byteLength===8){const t=new Uint8Array(e.data),r=t[3]&1;let n=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return n/=45,r&&(n+=4772185884e-2),Math.round(n)}}function ku(e){const t=Hb(e);for(let r=0;r<t.length;r++){const n=t[r];if(Vb(n))return ZM(n)}}var Ot=(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 lr(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}var Tu=class{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=Wt(this.cachedData,e),this.cachedData=null);let r=Ws(e,0),n=r?r.length:0,s;const i=this._audioTrack,a=this._id3Track,l=r?ku(r):void 0,o=e.length;for((this.basePTS===null||this.frameIndex===0&&he(l))&&(this.basePTS=JM(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),r&&r.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Ot.audioId3,duration:Number.POSITIVE_INFINITY});n<o;){if(this.canParse(e,n)){const c=this.appendFrame(i,e,n);c?(this.frameIndex++,this.lastPTS=c.sample.pts,n+=c.length,s=n):n=o}else UM(e,n)?(r=Ws(e,n),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Ot.audioId3,duration:Number.POSITIVE_INFINITY}),n+=r.length,s=n):n++;if(n===o&&s!==o){const c=e.slice(s);this.cachedData?this.cachedData=Wt(this.cachedData,c):this.cachedData=c}}return{audioTrack:i,videoTrack:lr(),id3Track:a,textTrack:lr()}}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:lr(),id3Track:this._id3Track,textTrack:lr()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},JM=(e,t,r)=>{if(he(e))return e*90;const n=r?r.baseTime*9e4/r.timescale:0;return t*9e4+n},yi=null,eP=[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],tP=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],rP=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],nP=[0,1,1,4];function jb(e,t,r,n,s){if(r+24>t.length)return;const i=Kb(t,r);if(i&&r+i.frameLength<=t.length){const a=n+s*(i.samplesPerFrame*9e4/i.sampleRate),l={unit:t.subarray(r,r+i.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=i.channelCount,e.samplerate=i.sampleRate,e.samples.push(l),{sample:l,length:i.frameLength,missing:0}}}function Kb(e,t){const r=e[t+1]>>3&3,n=e[t+1]>>1&3,s=e[t+2]>>4&15,i=e[t+2]>>2&3;if(r!==1&&s!==0&&s!==15&&i!==3){const a=e[t+2]>>1&1,l=e[t+3]>>6,o=eP[(r===3?3-n:n===3?3:4)*14+s-1]*1e3,c=tP[(r===3?0:r===2?1:2)*3+i],d=l===3?1:2,h=rP[r][n],f=nP[n],p=h*8*f,m=Math.floor(h*o/c+a)*f;if(yi===null){const g=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);yi=g?parseInt(g[1]):0}return yi&&yi<=87&&n===2&&o>=224e3&&l===0&&(e[t+3]=e[t+3]|128),{sampleRate:c,channelCount:d,frameLength:m,samplesPerFrame:p}}}function Au(e,t){return e[t]===255&&(e[t+1]&224)===224&&(e[t+1]&6)!==0}function zb(e,t){return t+1<e.length&&Au(e,t)}function sP(e,t){return Au(e,t)&&4<=e.length-t}function Wb(e,t){if(t+1<e.length&&Au(e,t)){const n=Kb(e,t);let s=4;n!=null&&n.frameLength&&(s=n.frameLength);const i=t+s;return i===e.length||zb(e,i)}return!1}var iP=class extends Tu{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=Ws(e,0);let n=r?.length||0;if(Wb(e,n))return!1;for(let s=e.length;n<s;n++)if($M(e,n))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return FM(e,t)}appendFrame(e,t,r){Bb(e,this.observer,t,r,e.manifestCodec);const n=Gb(e,t,r,this.basePTS,this.frameIndex);if(n&&n.missing===0)return n}},Qb=(e,t)=>{let r=0,n=5;t+=n;const s=new Uint32Array(1),i=new Uint32Array(1),a=new Uint8Array(1);for(;n>0;){a[0]=e[t];const l=Math.min(n,8),o=8-l;i[0]=4278190080>>>24+o<<o,s[0]=(a[0]&i[0])>>o,r=r?r<<l|s[0]:s[0],t+=1,n-=l}return r},aP=class extends Tu{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=qb(e,t,r,this.basePTS,this.frameIndex);if(n!==-1)return{sample:e.samples[e.samples.length-1],length:n,missing:0}}static probe(e){if(!e)return!1;const t=Ws(e,0);if(!t)return!1;const r=t.length;return e[r]===11&&e[r+1]===119&&ku(t)!==void 0&&Qb(e,r)<16}};function qb(e,t,r,n,s){if(r+8>t.length||t[r]!==11||t[r+1]!==119)return-1;const i=t[r+4]>>6;if(i>=3)return-1;const a=[48e3,44100,32e3][i],l=t[r+4]&63,o=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+i]*2;if(r+o>t.length)return-1;const c=t[r+6]>>5;let d=0;c===2?d+=2:(c&1&&c!==1&&(d+=2),c&4&&(d+=2));const h=(t[r+6]<<8|t[r+7])>>12-d&1,f=[2,1,2,3,3,4,4,5][c]+h,p=t[r+5]>>3,m=t[r+5]&7,g=new Uint8Array([i<<6|p<<1|m>>2,(m&3)<<6|c<<3|h<<2|l>>4,l<<4&224]),b=n+s*(1536/a*9e4),y=t.subarray(r,r+o);return e.config=g,e.channelCount=f,e.samplerate=a,e.samples.push({unit:y,pts:b}),o}var oP=class extends Tu{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=Ws(e,0);let r=t?.length||0;if(t&&e[r]===11&&e[r+1]===119&&ku(t)!==void 0&&Qb(e,r)<=16)return!1;for(let n=e.length;r<n;r++)if(Wb(e,r))return Ke.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return sP(e,t)}appendFrame(e,t,r){if(this.basePTS!==null)return jb(e,t,r,this.basePTS,this.frameIndex)}},lP=/\/emsg[-/]ID3/i,cP=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 s=this.videoTrack=lr("video",1),i=this.audioTrack=lr("audio",1),a=this.txtTrack=lr("text",1);if(this.id3Track=lr("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=sb(e);if(l.video){const{id:o,timescale:c,codec:d,supplemental:h}=l.video;s.id=o,s.timescale=a.timescale=c,s.codec=d,s.supplemental=h}if(l.audio){const{id:o,timescale:c,codec:d}=l.audio;i.id=o,i.timescale=c,i.codec=d}a.id=tb.text,s.sampleDuration=0,s.duration=i.duration=n}resetContiguity(){this.remainderData=null}static probe(e){return oR(e)}demux(e,t){this.timeOffset=t;let r=e;const n=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=Wt(this.remainderData,e));const a=pR(r);this.remainderData=a.remainder,n.samples=a.valid||new Uint8Array}else n.samples=r;const i=this.extractID3Track(n,t);return s.samples=yh(t,n),{videoTrack:n,audioTrack:this.audioTrack,id3Track:i,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=yh(e,t),{videoTrack:t,audioTrack:lr(),id3Track:n,textTrack:lr()}}extractID3Track(e,t){const r=this.id3Track;if(e.samples.length){const n=Pe(e.samples,["emsg"]);n&&n.forEach(s=>{const i=gR(s);if(lP.test(i.schemeIdUri)){const a=rf(i,t);let l=i.eventDuration===4294967295?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const o=i.payload;r.samples.push({data:o,len:o.byteLength,dts:a,pts:a,type:Ot.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata&&i.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const a=rf(i,t);r.samples.push({data:i.payload,len:i.payload.byteLength,dts:a,pts:a,type:Ot.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}};function rf(e,t){return he(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var uP=class{constructor(e,t,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new gu(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,jr.cbc)}decryptAacSample(e,t,r){const n=e[t].unit;if(n.length<=16)return;const s=n.subarray(16,n.length-n.length%16),i=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(i).then(a=>{const l=new Uint8Array(a);n.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,r)}).catch(r)}decryptAacSamples(e,t,r){for(;;t++){if(t>=e.length){r();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,r),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,r=new Int8Array(t);let n=0;for(let s=32;s<e.length-16;s+=160,n+=16)r.set(e.subarray(s,s+16),n);return r}getAvcDecryptedUnit(e,t){const r=new Uint8Array(t);let n=0;for(let s=32;s<e.length-16;s+=160,n+=16)e.set(r.subarray(n,n+16),s);return e}decryptAvcSample(e,t,r,n,s){const i=ob(s.data),a=this.getAvcEncryptedData(i);this.decryptBuffer(a.buffer).then(l=>{s.data=this.getAvcDecryptedUnit(i,l),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){n();return}const s=e[t].units;for(;!(r>=s.length);r++){const i=s[r];if(!(i.data.length<=48||i.type!==1&&i.type!==5)&&(this.decryptAvcSample(e,t,r,n,i),!this.decrypter.isSync()))return}}}},Yb=class{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=this.VideoSample,n;if((!r||r.units.length===0)&&(r=e[e.length-1]),(t=r)!=null&&t.units){const s=r.units;n=s[s.length-1]}return n}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const r=t.samples,n=r.length;if(n){const s=r[n-1];e.pts=s.pts,e.dts=s.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,r){const n=t.byteLength;let s=e.naluState||0;const i=s,a=[];let l=0,o,c,d,h=-1,f=0;for(s===-1&&(h=0,f=this.getNALuType(t,0),s=0,l=1);l<n;){if(o=t[l++],!s){s=o?0:1;continue}if(s===1){s=o?0:2;continue}if(!o)s=3;else if(o===1){if(c=l-s-1,h>=0){const p={data:t.subarray(h,c),type:f};a.push(p)}else{const p=this.getLastNalUnit(e.samples);p&&(i&&l<=4-i&&p.state&&(p.data=p.data.subarray(0,p.data.byteLength-i)),c>0&&(p.data=Wt(p.data,t.subarray(0,c)),p.state=0))}l<n?(d=this.getNALuType(t,l),h=l,f=d,s=0):s=-1}else s=0}if(h>=0&&s>=0){const p={data:t.subarray(h,n),type:f,state:s};a.push(p)}if(a.length===0){const p=this.getLastNalUnit(e.samples);p&&(p.data=Wt(p.data,t))}return e.naluState=s,a}},Cs=class{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),s=Math.min(4,t);if(s===0)throw new Error("no bytes available");n.set(e.subarray(r,r+s)),this.word=new DataView(n.buffer).getUint32(0),this.bitsAvailable=s*8,this.bytesAvailable-=s}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>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&&Ke.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");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)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}},dP=class extends Yb{parsePES(e,t,r,n){const s=this.parseNALu(e,r.data,n);let i=this.VideoSample,a,l=!1;r.data=null,i&&s.length&&!e.audFound&&(this.pushAccessUnit(i,e),i=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),s.forEach(o=>{var c,d;switch(o.type){case 1:{let m=!1;a=!0;const g=o.data;if(l&&g.length>4){const b=this.readSliceType(g);(b===2||b===4||b===7||b===9)&&(m=!0)}if(m){var h;(h=i)!=null&&h.frame&&!i.key&&(this.pushAccessUnit(i,e),i=this.VideoSample=null)}i||(i=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),i.frame=!0,i.key=m;break}case 5:a=!0,(c=i)!=null&&c.frame&&!i.key&&(this.pushAccessUnit(i,e),i=this.VideoSample=null),i||(i=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),i.key=!0,i.frame=!0;break;case 6:a=!0,hu(o.data,1,r.pts,t.samples);break;case 7:{var f,p;a=!0,l=!0;const m=o.data,g=this.readSPS(m);if(!e.sps||e.width!==g.width||e.height!==g.height||((f=e.pixelRatio)==null?void 0:f[0])!==g.pixelRatio[0]||((p=e.pixelRatio)==null?void 0:p[1])!==g.pixelRatio[1]){e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.sps=[m];const b=m.subarray(1,4);let y="avc1.";for(let S=0;S<3;S++){let E=b[S].toString(16);E.length<2&&(E="0"+E),y+=E}e.codec=y}break}case 8:a=!0,e.pps=[o.data];break;case 9:a=!0,e.audFound=!0,(d=i)!=null&&d.frame&&(this.pushAccessUnit(i,e),i=null),i||(i=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;case 12:a=!0;break;default:a=!1;break}i&&a&&i.units.push(o)}),n&&i&&(this.pushAccessUnit(i,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Cs(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let r=8,n=8,s;for(let i=0;i<e;i++)n!==0&&(s=t.readEG(),n=(r+s+256)%256),r=n===0?r:n}readSPS(e){const t=new Cs(e);let r=0,n=0,s=0,i=0,a,l,o;const c=t.readUByte.bind(t),d=t.readBits.bind(t),h=t.readUEG.bind(t),f=t.readBoolean.bind(t),p=t.skipBits.bind(t),m=t.skipEG.bind(t),g=t.skipUEG.bind(t),b=this.skipScalingList.bind(this);c();const y=c();if(d(5),p(3),c(),g(),y===100||y===110||y===122||y===244||y===44||y===83||y===86||y===118||y===128){const N=h();if(N===3&&p(1),g(),g(),p(1),f())for(l=N!==3?8:12,o=0;o<l;o++)f()&&(o<6?b(16,t):b(64,t))}g();const S=h();if(S===0)h();else if(S===1)for(p(1),m(),m(),a=h(),o=0;o<a;o++)m();g(),p(1);const E=h(),k=h(),T=d(1);T===0&&p(1),p(1),f()&&(r=h(),n=h(),s=h(),i=h());let A=[1,1];if(f()&&f())switch(c()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:A=[c()<<8|c(),c()<<8|c()];break}return{width:Math.ceil((E+1)*16-r*2-n*2),height:(2-T)*(k+1)*16-(T?2:4)*(s+i),pixelRatio:A}}},hP=class extends Yb{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,r,n){const s=this.parseNALu(e,r.data,n);let i=this.VideoSample,a,l=!1;r.data=null,i&&s.length&&!e.audFound&&(this.pushAccessUnit(i,e),i=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),s.forEach(o=>{var c,d;switch(o.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:i||(i=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),i.frame=!0,a=!0;break;case 16:case 17:case 18:case 21:if(a=!0,l){var h;(h=i)!=null&&h.frame&&!i.key&&(this.pushAccessUnit(i,e),i=this.VideoSample=null)}i||(i=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),i.key=!0,i.frame=!0;break;case 19:case 20:a=!0,(c=i)!=null&&c.frame&&!i.key&&(this.pushAccessUnit(i,e),i=this.VideoSample=null),i||(i=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),i.key=!0,i.frame=!0;break;case 39:a=!0,hu(o.data,2,r.pts,t.samples);break;case 32:a=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=ze(e.params,this.readVPS(o.data)),this.initVPS=o.data),e.vps=[o.data];break;case 33:if(a=!0,l=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],o.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const f=this.readSPS(o.data);e.width=f.width,e.height=f.height,e.pixelRatio=f.pixelRatio,e.codec=f.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const p in f.params)e.params[p]=f.params[p]}this.pushParameterSet(e.sps,o.data,e.vps),i||(i=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),i.key=!0;break;case 34:if(a=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const f=this.readPPS(o.data);for(const p in f)e.params[p]=f[p]}this.pushParameterSet(e.pps,o.data,e.vps)}break;case 35:a=!0,e.audFound=!0,(d=i)!=null&&d.frame&&(this.pushAccessUnit(i,e),i=null),i||(i=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;default:a=!1;break}i&&a&&i.units.push(o)}),n&&i&&(this.pushAccessUnit(i,e),this.VideoSample=null)}pushParameterSet(e,t,r){(r&&r[0]===this.initVPS||!r&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let r=0;for(let n=0;n<e.byteLength;n++)n>=2&&e[n]===3&&e[n-1]===0&&e[n-2]===0||(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 Cs(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const r=t.readBits(3),n=t.readBoolean();return{numTemporalLayers:r+1,temporalIdNested:n}}readSPS(e){const t=new Cs(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const r=t.readBits(3);t.readBoolean();const n=t.readBits(2),s=t.readBoolean(),i=t.readBits(5),a=t.readUByte(),l=t.readUByte(),o=t.readUByte(),c=t.readUByte(),d=t.readUByte(),h=t.readUByte(),f=t.readUByte(),p=t.readUByte(),m=t.readUByte(),g=t.readUByte(),b=t.readUByte(),y=[],S=[];for(let ue=0;ue<r;ue++)y.push(t.readBoolean()),S.push(t.readBoolean());if(r>0)for(let ue=r;ue<8;ue++)t.readBits(2);for(let ue=0;ue<r;ue++)y[ue]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),S[ue]&&t.readUByte();t.readUEG();const E=t.readUEG();E==3&&t.skipBits(1);const k=t.readUEG(),T=t.readUEG(),A=t.readBoolean();let N=0,C=0,M=0,P=0;A&&(N+=t.readUEG(),C+=t.readUEG(),M+=t.readUEG(),P+=t.readUEG());const D=t.readUEG(),$=t.readUEG(),B=t.readUEG(),j=t.readBoolean();for(let ue=j?0:r;ue<=r;ue++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let ue=0;ue<4;ue++)for(let we=0;we<(ue===3?2:6);we++)if(!t.readBoolean())t.readUEG();else{const le=Math.min(64,1<<4+(ue<<1));ue>1&&t.readEG();for(let Z=0;Z<le;Z++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const U=t.readUEG();let F=0;for(let ue=0;ue<U;ue++){let we=!1;if(ue!==0&&(we=t.readBoolean()),we){ue===U&&t.readUEG(),t.readBoolean(),t.readUEG();let le=0;for(let Z=0;Z<=F;Z++){const ce=t.readBoolean();let Ae=!1;ce||(Ae=t.readBoolean()),(ce||Ae)&&le++}F=le}else{const le=t.readUEG(),Z=t.readUEG();F=le+Z;for(let ce=0;ce<le;ce++)t.readUEG(),t.readBoolean();for(let ce=0;ce<Z;ce++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const ue=t.readUEG();for(let we=0;we<ue;we++){for(let le=0;le<B+4;le++)t.readBits(1);t.readBits(1)}}let Y=0,I=1,R=1,O=!0,K=1,W=0;t.readBoolean(),t.readBoolean();let J=!1;if(t.readBoolean()){if(t.readBoolean()){const ue=t.readUByte(),we=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],le=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];ue>0&&ue<16?(I=we[ue-1],R=le[ue-1]):ue===255&&(I=t.readBits(16),R=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),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(),J=t.readBoolean(),J&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(K=t.readBits(32),W=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const ue=t.readBoolean(),we=t.readBoolean();let le=!1;(ue||we)&&(le=t.readBoolean(),le&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),le&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Z=0;Z<=r;Z++){O=t.readBoolean();const ce=O||t.readBoolean();let Ae=!1;ce?t.readEG():Ae=t.readBoolean();const Re=Ae?1:t.readUEG()+1;if(ue)for(let He=0;He<Re;He++)t.readUEG(),t.readUEG(),le&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(we)for(let He=0;He<Re;He++)t.readUEG(),t.readUEG(),le&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),Y=t.readUEG())}let Q=k,ee=T;if(A){let ue=1,we=1;E===1?ue=we=2:E==2&&(ue=2),Q=k-ue*C-ue*N,ee=T-we*P-we*M}const ie=n?["A","B","C"][n]:"",se=a<<24|l<<16|o<<8|c;let be=0;for(let ue=0;ue<32;ue++)be=(be|(se>>ue&1)<<31-ue)>>>0;let ye=be.toString(16);return i===1&&ye==="2"&&(ye="6"),{codecString:`hvc1.${ie}${i}.${ye}.${s?"H":"L"}${b}.B0`,params:{general_tier_flag:s,general_profile_idc:i,general_profile_space:n,general_profile_compatibility_flags:[a,l,o,c],general_constraint_indicator_flags:[d,h,f,p,m,g],general_level_idc:b,bit_depth:D+8,bit_depth_luma_minus8:D,bit_depth_chroma_minus8:$,min_spatial_segmentation_idc:Y,chroma_format_idc:E,frame_rate:{fixed:O,fps:W/K}},width:Q,height:ee,pixelRatio:[I,R]}}readPPS(e){const t=new Cs(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 s=1;return n&&r?s=0:n?s=3:r&&(s=2),{parallelismType:s}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}},xt=188,fP=class an{constructor(t,r,n,s){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=r,this.typeSupported=n,this.logger=s,this.videoParser=null}static probe(t,r){const n=an.syncOffset(t);return n>0&&r.warn(`MPEG2-TS detected but first sync word found @ offset ${n}`),n!==-1}static syncOffset(t){const r=t.length;let n=Math.min(xt*5,r-xt)+1,s=0;for(;s<n;){let i=!1,a=-1,l=0;for(let o=s;o<r;o+=xt)if(t[o]===71&&(r-o===xt||t[o+xt]===71)){if(l++,a===-1&&(a=o,a!==0&&(n=Math.min(a+xt*99,t.length-xt)+1)),i||(i=ec(t,o)===0),i&&l>1&&(a===0&&l>2||o+xt>n))return a}else{if(l)return-1;break}s++}return-1}static createTrack(t,r){return{container:t==="video"||t==="audio"?"video/mp2t":void 0,type:t,id:tb[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:t==="audio"?r:void 0}}resetInitSegment(t,r,n,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=an.createTrack("video"),this._videoTrack.duration=s,this._audioTrack=an.createTrack("audio",s),this._id3Track=an.createTrack("id3"),this._txtTrack=an.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=n}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:r,_id3Track:n}=this;t&&(t.pesData=null),r&&(r.pesData=null),n&&(n.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,r,n=!1,s=!1){n||(this.sampleAes=null);let i;const a=this._videoTrack,l=this._audioTrack,o=this._id3Track,c=this._txtTrack;let d=a.pid,h=a.pesData,f=l.pid,p=o.pid,m=l.pesData,g=o.pesData,b=null,y=this.pmtParsed,S=this._pmtId,E=t.length;if(this.remainderData&&(t=Wt(this.remainderData,t),E=t.length,this.remainderData=null),E<xt&&!s)return this.remainderData=t,{audioTrack:l,videoTrack:a,id3Track:o,textTrack:c};const k=Math.max(0,an.syncOffset(t));E-=(E-k)%xt,E<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,E,t.buffer.byteLength-E));let T=0;for(let N=k;N<E;N+=xt)if(t[N]===71){const C=!!(t[N+1]&64),M=ec(t,N),P=(t[N+3]&48)>>4;let D;if(P>1){if(D=N+5+t[N+4],D===N+xt)continue}else D=N+4;switch(M){case d:C&&(h&&(i=Cn(h,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,c,i,!1)),h={data:[],size:0}),h&&(h.data.push(t.subarray(D,N+xt)),h.size+=N+xt-D);break;case f:if(C){if(m&&(i=Cn(m,this.logger)))switch(l.segmentCodec){case"aac":this.parseAACPES(l,i);break;case"mp3":this.parseMPEGPES(l,i);break;case"ac3":this.parseAC3PES(l,i);break}m={data:[],size:0}}m&&(m.data.push(t.subarray(D,N+xt)),m.size+=N+xt-D);break;case p:C&&(g&&(i=Cn(g,this.logger))&&this.parseID3PES(o,i),g={data:[],size:0}),g&&(g.data.push(t.subarray(D,N+xt)),g.size+=N+xt-D);break;case 0:C&&(D+=t[D]+1),S=this._pmtId=pP(t,D);break;case S:{C&&(D+=t[D]+1);const $=mP(t,D,this.typeSupported,n,this.observer,this.logger);d=$.videoPid,d>0&&(a.pid=d,a.segmentCodec=$.segmentVideoCodec),f=$.audioPid,f>0&&(l.pid=f,l.segmentCodec=$.segmentAudioCodec),p=$.id3Pid,p>0&&(o.pid=p),b!==null&&!y&&(this.logger.warn(`MPEG-TS PMT found at ${N} after unknown PID '${b}'. Backtracking to sync byte @${k} to parse all TS packets.`),b=null,N=k-188),y=this.pmtParsed=!0;break}case 17:case 8191:break;default:b=M;break}}else T++;T>0&&tc(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=h,l.pesData=m,o.pesData=g;const A={audioTrack:l,videoTrack:a,id3Track:o,textTrack:c};return s&&this.extractRemainingSamples(A),A}flush(){const{remainderData:t}=this;this.remainderData=null;let r;return t?r=this.demux(t,-1,!1,!0):r={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(r),this.sampleAes?this.decrypt(r,this.sampleAes):r}extractRemainingSamples(t){const{audioTrack:r,videoTrack:n,id3Track:s,textTrack:i}=t,a=n.pesData,l=r.pesData,o=s.pesData;let c;if(a&&(c=Cn(a,this.logger))?(this.readyVideoParser(n.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(n,i,c,!0),n.pesData=null)):n.pesData=a,l&&(c=Cn(l,this.logger))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,c);break;case"mp3":this.parseMPEGPES(r,c);break;case"ac3":this.parseAC3PES(r,c);break}r.pesData=null}else l!=null&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=l;o&&(c=Cn(o,this.logger))?(this.parseID3PES(s,c),s.pesData=null):s.pesData=o}demuxSampleAes(t,r,n){const s=this.demux(t,n,!0,!this.config.progressive),i=this.sampleAes=new uP(this.observer,this.config,r);return this.decrypt(s,i)}readyVideoParser(t){this.videoParser===null&&(t==="avc"?this.videoParser=new dP:t==="hevc"&&(this.videoParser=new hP))}decrypt(t,r){return new Promise(n=>{const{audioTrack:s,videoTrack:i}=t;s.samples&&s.segmentCodec==="aac"?r.decryptAacSamples(s.samples,0,()=>{i.samples?r.decryptAvcSamples(i.samples,0,0,()=>{n(t)}):n(t)}):i.samples&&r.decryptAvcSamples(i.samples,0,0,()=>{n(t)})})}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(t,r){let n=0;const s=this.aacOverFlow;let i=r.data;if(s){this.aacOverFlow=null;const h=s.missing,f=s.sample.unit.byteLength;if(h===-1)i=Wt(s.sample.unit,i);else{const p=f-h;s.sample.unit.set(i.subarray(0,h),p),t.samples.push(s.sample),n=s.missing}}let a,l;for(a=n,l=i.length;a<l-1&&!ka(i,a);a++);if(a!==n){let h;const f=a<l-1;if(f?h=`AAC PES did not start with ADTS header,offset:${a}`:h="No ADTS header found in AAC PES",tc(this.observer,new Error(h),f,this.logger),!f)return}Bb(t,this.observer,i,a,this.audioCodec);let o;if(r.pts!==void 0)o=r.pts;else if(s){const h=Ub(t.samplerate);o=s.sample.pts+h}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let c=0,d;for(;a<l;)if(d=Gb(t,i,a,o,c),a+=d.length,d.missing){this.aacOverFlow=d;break}else for(c++;a<l-1&&!ka(i,a);a++);}parseMPEGPES(t,r){const n=r.data,s=n.length;let i=0,a=0;const l=r.pts;if(l===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<s;)if(zb(n,a)){const o=jb(t,n,a,l,i);if(o)a+=o.length,i++;else break}else a++}parseAC3PES(t,r){{const n=r.data,s=r.pts;if(s===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const i=n.length;let a=0,l=0,o;for(;l<i&&(o=qb(t,n,l,s,a++))>0;)l+=o}}parseID3PES(t,r){if(r.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const n=ze({},r,{type:this._videoTrack?Ot.emsg:Ot.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(n)}};function ec(e,t){return((e[t+1]&31)<<8)+e[t+2]}function pP(e,t){return(e[t+10]&31)<<8|e[t+11]}function mP(e,t,r,n,s,i){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},l=(e[t+1]&15)<<8|e[t+2],o=t+3+l-4,c=(e[t+10]&15)<<8|e[t+11];for(t+=12+c;t<o;){const d=ec(e,t),h=(e[t+3]&15)<<8|e[t+4];switch(e[t]){case 207:if(!n){Uo("ADTS AAC",i);break}case 15:a.audioPid===-1&&(a.audioPid=d);break;case 21:a.id3Pid===-1&&(a.id3Pid=d);break;case 219:if(!n){Uo("H.264",i);break}case 27:a.videoPid===-1&&(a.videoPid=d);break;case 3:case 4:!r.mpeg&&!r.mp3?i.log("MPEG audio found, not supported in this browser"):a.audioPid===-1&&(a.audioPid=d,a.segmentAudioCodec="mp3");break;case 193:if(!n){Uo("AC-3",i);break}case 129:r.ac3?a.audioPid===-1&&(a.audioPid=d,a.segmentAudioCodec="ac3"):i.log("AC-3 audio found, not supported in this browser");break;case 6:if(a.audioPid===-1&&h>0){let f=t+5,p=h;for(;p>2;){switch(e[f]){case 106:r.ac3!==!0?i.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=d,a.segmentAudioCodec="ac3");break}const m=e[f+1]+2;f+=m,p-=m}}break;case 194:case 135:return tc(s,new Error("Unsupported EC-3 in M2TS found"),void 0,i),a;case 36:a.videoPid===-1&&(a.videoPid=d,a.segmentVideoCodec="hevc",i.log("HEVC in M2TS found"));break}t+=h+5}return a}function tc(e,t,r,n){n.warn(`parsing error: ${t.message}`),e.emit(w.ERROR,w.ERROR,{type:xe.MEDIA_ERROR,details:G.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:t,reason:t.message})}function Uo(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function Cn(e,t){let r=0,n,s,i,a,l;const o=e.data;if(!e||e.size===0)return null;for(;o[0].length<19&&o.length>1;)o[0]=Wt(o[0],o[1]),o.splice(1,1);if(n=o[0],(n[0]<<16)+(n[1]<<8)+n[2]===1){if(s=(n[4]<<8)+n[5],s&&s>e.size-6)return null;const c=n[7];c&192&&(a=(n[9]&14)*536870912+(n[10]&255)*4194304+(n[11]&254)*16384+(n[12]&255)*128+(n[13]&254)/2,c&64?(l=(n[14]&14)*536870912+(n[15]&255)*4194304+(n[16]&254)*16384+(n[17]&255)*128+(n[18]&254)/2,a-l>60*9e4&&(t.warn(`${Math.round((a-l)/9e4)}s delta between PTS and DTS, align them`),a=l)):l=a),i=n[8];let d=i+9;if(e.size<=d)return null;e.size-=d;const h=new Uint8Array(e.size);for(let f=0,p=o.length;f<p;f++){n=o[f];let m=n.byteLength;if(d)if(d>m){d-=m;continue}else n=n.subarray(d),m-=d,d=0;h.set(n,r),r+=m}return s&&(s-=i+3),{data:h,pts:a,dts:l,len:s}}return null}var gP=class{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}},_r=Math.pow(2,32)-1,Tt=class z{static init(){z.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let t;for(t in z.types)z.types.hasOwnProperty(t)&&(z.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);z.HDLR_TYPES={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])};const r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]);z.STTS=z.STSC=z.STCO=new Uint8Array([0,0,0,0,0,0,0,0]),z.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),z.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),z.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),z.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),s=new Uint8Array([97,118,99,49]),i=new Uint8Array([0,0,0,1]);z.FTYP=z.box(z.types.ftyp,n,i,n,s),z.DINF=z.box(z.types.dinf,z.box(z.types.dref,r))}static box(t,...r){let n=8,s=r.length;const i=s;for(;s--;)n+=r[s].byteLength;const a=new Uint8Array(n);for(a[0]=n>>24&255,a[1]=n>>16&255,a[2]=n>>8&255,a[3]=n&255,a.set(t,4),s=0,n=8;s<i;s++)a.set(r[s],n),n+=r[s].byteLength;return a}static hdlr(t){return z.box(z.types.hdlr,z.HDLR_TYPES[t])}static mdat(t){return z.box(z.types.mdat,t)}static mdhd(t,r){r*=t;const n=Math.floor(r/(_r+1)),s=Math.floor(r%(_r+1));return z.box(z.types.mdhd,new Uint8Array([1,0,0,0,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,t&255,n>>24,n>>16&255,n>>8&255,n&255,s>>24,s>>16&255,s>>8&255,s&255,85,196,0,0]))}static mdia(t){return z.box(z.types.mdia,z.mdhd(t.timescale||0,t.duration||0),z.hdlr(t.type),z.minf(t))}static mfhd(t){return z.box(z.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255]))}static minf(t){return t.type==="audio"?z.box(z.types.minf,z.box(z.types.smhd,z.SMHD),z.DINF,z.stbl(t)):z.box(z.types.minf,z.box(z.types.vmhd,z.VMHD),z.DINF,z.stbl(t))}static moof(t,r,n){return z.box(z.types.moof,z.mfhd(t),z.traf(n,r))}static moov(t){let r=t.length;const n=[];for(;r--;)n[r]=z.trak(t[r]);return z.box.apply(null,[z.types.moov,z.mvhd(t[0].timescale||0,t[0].duration||0)].concat(n).concat(z.mvex(t)))}static mvex(t){let r=t.length;const n=[];for(;r--;)n[r]=z.trex(t[r]);return z.box.apply(null,[z.types.mvex,...n])}static mvhd(t,r){r*=t;const n=Math.floor(r/(_r+1)),s=Math.floor(r%(_r+1)),i=new Uint8Array([1,0,0,0,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,t&255,n>>24,n>>16&255,n>>8&255,n&255,s>>24,s>>16&255,s>>8&255,s&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return z.box(z.types.mvhd,i)}static sdtp(t){const r=t.samples||[],n=new Uint8Array(4+r.length);let s,i;for(s=0;s<r.length;s++)i=r[s].flags,n[s+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return z.box(z.types.sdtp,n)}static stbl(t){return z.box(z.types.stbl,z.stsd(t),z.box(z.types.stts,z.STTS),z.box(z.types.stsc,z.STSC),z.box(z.types.stsz,z.STSZ),z.box(z.types.stco,z.STCO))}static avc1(t){let r=[],n=[],s,i,a;for(s=0;s<t.sps.length;s++)i=t.sps[s],a=i.byteLength,r.push(a>>>8&255),r.push(a&255),r=r.concat(Array.prototype.slice.call(i));for(s=0;s<t.pps.length;s++)i=t.pps[s],a=i.byteLength,n.push(a>>>8&255),n.push(a&255),n=n.concat(Array.prototype.slice.call(i));const l=z.box(z.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|t.sps.length].concat(r).concat([t.pps.length]).concat(n))),o=t.width,c=t.height,d=t.pixelRatio[0],h=t.pixelRatio[1];return z.box(z.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,o&255,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),l,z.box(z.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),z.box(z.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,h>>24,h>>16&255,h>>8&255,h&255])))}static esds(t){const r=t.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,...r,6,1,2])}static audioStsd(t){const r=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,r>>8&255,r&255,0,0])}static mp4a(t){return z.box(z.types.mp4a,z.audioStsd(t),z.box(z.types.esds,z.esds(t)))}static mp3(t){return z.box(z.types[".mp3"],z.audioStsd(t))}static ac3(t){return z.box(z.types["ac-3"],z.audioStsd(t),z.box(z.types.dac3,t.config))}static stsd(t){const{segmentCodec:r}=t;if(t.type==="audio"){if(r==="aac")return z.box(z.types.stsd,z.STSD,z.mp4a(t));if(r==="ac3"&&t.config)return z.box(z.types.stsd,z.STSD,z.ac3(t));if(r==="mp3"&&t.codec==="mp3")return z.box(z.types.stsd,z.STSD,z.mp3(t))}else if(t.pps&&t.sps){if(r==="avc")return z.box(z.types.stsd,z.STSD,z.avc1(t));if(r==="hevc"&&t.vps)return z.box(z.types.stsd,z.STSD,z.hvc1(t))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${t.type} segment codec (${r}/${t.codec})`)}static tkhd(t){const r=t.id,n=(t.duration||0)*(t.timescale||0),s=t.width||0,i=t.height||0,a=Math.floor(n/(_r+1)),l=Math.floor(n%(_r+1));return z.box(z.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,r&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,l>>24,l>>16&255,l>>8&255,l&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,s>>8&255,s&255,0,0,i>>8&255,i&255,0,0]))}static traf(t,r){const n=z.sdtp(t),s=t.id,i=Math.floor(r/(_r+1)),a=Math.floor(r%(_r+1));return z.box(z.types.traf,z.box(z.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),z.box(z.types.tfdt,new Uint8Array([1,0,0,0,i>>24,i>>16&255,i>>8&255,i&255,a>>24,a>>16&255,a>>8&255,a&255])),z.trun(t,n.length+16+20+8+16+8+8),n)}static trak(t){return t.duration=t.duration||4294967295,z.box(z.types.trak,z.tkhd(t),z.mdia(t))}static trex(t){const r=t.id;return z.box(z.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,r){const n=t.samples||[],s=n.length,i=12+16*s,a=new Uint8Array(i);let l,o,c,d,h,f;for(r+=8+i,a.set([t.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255],0),l=0;l<s;l++)o=n[l],c=o.duration,d=o.size,h=o.flags,f=o.cts,a.set([c>>>24&255,c>>>16&255,c>>>8&255,c&255,d>>>24&255,d>>>16&255,d>>>8&255,d&255,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,h.degradPrio&61440,h.degradPrio&15,f>>>24&255,f>>>16&255,f>>>8&255,f&255],12+16*l);return z.box(z.types.trun,a)}static initSegment(t){z.types||z.init();const r=z.moov(t);return Wt(z.FTYP,r)}static hvc1(t){const r=t.params,n=[t.vps,t.sps,t.pps],s=new Uint8Array([1,r.general_profile_space<<6|(r.general_tier_flag?32:0)|r.general_profile_idc,r.general_profile_compatibility_flags[0],r.general_profile_compatibility_flags[1],r.general_profile_compatibility_flags[2],r.general_profile_compatibility_flags[3],r.general_constraint_indicator_flags[0],r.general_constraint_indicator_flags[1],r.general_constraint_indicator_flags[2],r.general_constraint_indicator_flags[3],r.general_constraint_indicator_flags[4],r.general_constraint_indicator_flags[5],r.general_level_idc,240|r.min_spatial_segmentation_idc>>8,255&r.min_spatial_segmentation_idc,252|r.parallelismType,252|r.chroma_format_idc,248|r.bit_depth_luma_minus8,248|r.bit_depth_chroma_minus8,0,parseInt(r.frame_rate.fps),3|r.temporal_id_nested<<2|r.num_temporal_layers<<3|(r.frame_rate.fixed?64:0),n.length]);let i=s.length;for(let p=0;p<n.length;p+=1){i+=3;for(let m=0;m<n[p].length;m+=1)i+=2+n[p][m].length}const a=new Uint8Array(i);a.set(s,0),i=s.length;const l=n.length-1;for(let p=0;p<n.length;p+=1){a.set(new Uint8Array([32+p|(p===l?128:0),0,n[p].length]),i),i+=3;for(let m=0;m<n[p].length;m+=1)a.set(new Uint8Array([n[p][m].length>>8,n[p][m].length&255]),i),i+=2,a.set(n[p][m],i),i+=n[p][m].length}const o=z.box(z.types.hvcC,a),c=t.width,d=t.height,h=t.pixelRatio[0],f=t.pixelRatio[1];return z.box(z.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,c>>8&255,c&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,z.box(z.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),z.box(z.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,f>>24,f>>16&255,f>>8&255,f&255])))}};Tt.types=void 0;Tt.HDLR_TYPES=void 0;Tt.STTS=void 0;Tt.STSC=void 0;Tt.STCO=void 0;Tt.STSZ=void 0;Tt.VMHD=void 0;Tt.SMHD=void 0;Tt.STSD=void 0;Tt.FTYP=void 0;Tt.DINF=void 0;var Xb=9e4;function Cu(e,t,r=1,n=!1){const s=e*t*r;return n?Math.round(s):s}function vP(e,t,r=1,n=!1){return Cu(e,t,1/r,n)}function hs(e,t=!1){return Cu(e,1e3,1/Xb,t)}function bP(e,t=1){return Cu(e,Xb,1/t)}function nf(e){const{baseTime:t,timescale:r,trackId:n}=e;return`${t/r} (${t}/${r}) trackId: ${n}`}var yP=10*1e3,xP=1024,SP=1152,EP=1536,Nn=null,Go=null;function sf(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}}}var zi=class extends qt{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,Nn===null){const s=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Nn=s?parseInt(s[1]):0}if(Go===null){const s=navigator.userAgent.match(/Safari\/(\d+)/i);Go=s?parseInt(s[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&&nf(t)} > ${e&&nf(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((s,i)=>{let a=i.pts,l=a-s;return l<-4294967296&&(t=!0,a=_t(a,r),l=a-s),l>0?s:a},r);return t&&this.debug("PTS rollover detected"),n}remux(e,t,r,n,s,i,a,l){let o,c,d,h,f,p,m=s,g=s;const b=e.pid>-1,y=t.pid>-1,S=t.samples.length,E=e.samples.length>0,k=a&&S>0||S>1;if((!b||E)&&(!y||k)||this.ISGenerated||a){if(this.ISGenerated){var T,A,N,C;const $=this.videoTrackConfig;($&&(t.width!==$.width||t.height!==$.height||((T=t.pixelRatio)==null?void 0:T[0])!==((A=$.pixelRatio)==null?void 0:A[0])||((N=t.pixelRatio)==null?void 0:N[1])!==((C=$.pixelRatio)==null?void 0:C[1]))||!$&&k||this.nextAudioTs===null&&E)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,s,i));const M=this.isVideoContiguous;let P=-1,D;if(k&&(P=wP(t.samples),!M&&this.config.forceKeyFrameOnDiscontinuity))if(p=!0,P>0){this.warn(`Dropped ${P} out of ${S} video samples due to a missing keyframe`);const $=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(P),t.dropped+=P,g+=(t.samples[0].pts-$)/t.inputTimeScale,D=g}else P===-1&&(this.warn(`No keyframe found out of ${S} video samples`),p=!1);if(this.ISGenerated){if(E&&k){const $=this.getVideoStartPts(t.samples),B=(_t(e.samples[0].pts,$)-$)/t.inputTimeScale;m+=Math.max(0,B),g+=Math.max(0,-B)}if(E){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(e,t,s,i)),c=this.remuxAudio(e,m,this.isAudioContiguous,i,y||k||l===fe.AUDIO?g:void 0),k){const $=c?c.endPTS-c.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(e,t,s,i)),o=this.remuxVideo(t,g,M,$)}}else k&&(o=this.remuxVideo(t,g,M,0));o&&(o.firstKeyFrame=P,o.independent=P!==-1,o.firstKeyFramePTS=D)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(f=Zb(r,s,this._initPTS,this._initDTS)),n.samples.length&&(h=Jb(n,s,this._initPTS))),{audio:c,video:o,initSegment:d,independent:p,text:h,id3:f}}computeInitPts(e,t,r,n){const s=Math.round(r*t);let i=_t(e,s);if(i<s+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(s-i)/t} ${n}`);i<s+t;)i+=8589934592;return i-s}generateIS(e,t,r,n){const s=e.samples,i=t.samples,a=this.typeSupported,l={},o=this._initPTS;let c=!o||n,d="audio/mp4",h,f,p,m=-1;if(c&&(h=f=1/0),e.config&&s.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(d="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}l.audio={id:"audio",container:d,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&a.mpeg?new Uint8Array(0):Tt.initSegment([e]),metadata:{channelCount:e.channelCount}},c&&(m=e.id,p=e.inputTimeScale,!o||p!==o.timescale?h=f=this.computeInitPts(s[0].pts,p,r,"audio"):c=!1)}if(t.sps&&t.pps&&i.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Tt.initSegment([t]),metadata:{width:t.width,height:t.height}},c)if(m=t.id,p=t.inputTimeScale,!o||p!==o.timescale){const g=this.getVideoStartPts(i),b=_t(i[0].dts,g),y=this.computeInitPts(b,p,r,"video"),S=this.computeInitPts(g,p,r,"video");f=Math.min(f,y),h=Math.min(h,S)}else c=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,c?(o&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${h/p} != initPTS: ${o.baseTime/o.timescale} (${o.baseTime}/${o.timescale}) trackId: ${o.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${h/p} (${h}/${p}) trackId: ${m}`),this._initPTS={baseTime:h,timescale:p,trackId:m},this._initDTS={baseTime:f,timescale:p,trackId:m}):h=p=void 0,{tracks:l,initPTS:h,timescale:p,trackId:m}}remuxVideo(e,t,r,n){const s=e.inputTimeScale,i=e.samples,a=[],l=i.length,o=this._initPTS,c=o.baseTime*s/o.timescale;let d=this.nextVideoTs,h=8,f=this.videoSampleDuration,p,m,g=Number.POSITIVE_INFINITY,b=Number.NEGATIVE_INFINITY,y=!1;if(!r||d===null){const I=c+t*s,R=i[0].pts-_t(i[0].dts,i[0].pts);Nn&&d!==null&&Math.abs(I-R-(d+c))<15e3?r=!0:d=I-R-c}const S=d+c;for(let I=0;I<l;I++){const R=i[I];R.pts=_t(R.pts,S),R.dts=_t(R.dts,S),R.dts<i[I>0?I-1:I].dts&&(y=!0)}y&&i.sort(function(I,R){const O=I.dts-R.dts,K=I.pts-R.pts;return O||K}),p=i[0].dts,m=i[i.length-1].dts;const E=m-p,k=E?Math.round(E/(l-1)):f||e.inputTimeScale/30;if(r){const I=p-S,R=I>k,O=I<-1;if((R||O)&&(R?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${hs(I,!0)} ms (${I}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${hs(-I,!0)} ms (${I}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!O||S>=i[0].pts||Nn)){p=S;const K=i[0].pts-I;if(R)i[0].dts=p,i[0].pts=K;else{let W=!0;for(let J=0;J<i.length&&!(i[J].dts>K&&W);J++){const Q=i[J].pts;if(i[J].dts-=I,i[J].pts-=I,J<i.length-1){const ee=i[J+1].pts;W=ee<=i[J].pts==ee<=Q}}}this.log(`Video: Initial PTS/DTS adjusted: ${hs(K,!0)}/${hs(p,!0)}, delta: ${hs(I,!0)} ms`)}}p=Math.max(0,p);let T=0,A=0,N=p;for(let I=0;I<l;I++){const R=i[I],O=R.units,K=O.length;let W=0;for(let J=0;J<K;J++)W+=O[J].data.length;A+=W,T+=K,R.length=W,R.dts<N?(R.dts=N,N+=k/4|0||1):N=R.dts,g=Math.min(R.pts,g),b=Math.max(R.pts,b)}m=i[l-1].dts;const C=A+4*T+8;let M;try{M=new Uint8Array(C)}catch(I){this.observer.emit(w.ERROR,w.ERROR,{type:xe.MUX_ERROR,details:G.REMUX_ALLOC_ERROR,fatal:!1,error:I,bytes:C,reason:`fail allocating video mdat ${C}`});return}const P=new DataView(M.buffer);P.setUint32(0,C),M.set(Tt.types.mdat,4);let D=!1,$=Number.POSITIVE_INFINITY,B=Number.POSITIVE_INFINITY,j=Number.NEGATIVE_INFINITY,U=Number.NEGATIVE_INFINITY;for(let I=0;I<l;I++){const R=i[I],O=R.units;let K=0;for(let Q=0,ee=O.length;Q<ee;Q++){const ie=O[Q],se=ie.data,be=ie.data.byteLength;P.setUint32(h,be),h+=4,M.set(se,h),h+=be,K+=4+be}let W;if(I<l-1)f=i[I+1].dts-R.dts,W=i[I+1].pts-R.pts;else{const Q=this.config,ee=I>0?R.dts-i[I-1].dts:k;if(W=I>0?R.pts-i[I-1].pts:k,Q.stretchShortVideoTrack&&this.nextAudioTs!==null){const ie=Math.floor(Q.maxBufferHole*s),se=(n?g+n*s:this.nextAudioTs+c)-R.pts;se>ie?(f=se-ee,f<0?f=ee:D=!0,this.log(`It is approximately ${se/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=ee}else f=ee}const J=Math.round(R.pts-R.dts);$=Math.min($,f),j=Math.max(j,f),B=Math.min(B,W),U=Math.max(U,W),a.push(sf(R.key,f,K,J))}if(a.length){if(Nn){if(Nn<70){const I=a[0].flags;I.dependsOn=2,I.isNonSync=0}}else if(Go&&U-B<j-$&&k/j<.025&&a[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let I=p;for(let R=0,O=a.length;R<O;R++){const K=I+a[R].duration,W=I+a[R].cts;if(R<O-1){const J=K+a[R+1].cts;a[R].duration=J-W}else a[R].duration=R?a[R-1].duration:k;a[R].cts=0,I=K}}}f=D||!f?k:f;const F=m+f;this.nextVideoTs=d=F-c,this.videoSampleDuration=f,this.isVideoContiguous=!0;const Y={data1:Tt.moof(e.sequenceNumber++,p,ze(e,{samples:a})),data2:M,startPTS:(g-c)/s,endPTS:(b+f-c)/s,startDTS:(p-c)/s,endDTS:d/s,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Y}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return SP;case"ac3":return EP;default:return xP}}remuxAudio(e,t,r,n,s){const i=e.inputTimeScale,a=i/(e.samplerate?e.samplerate:i),l=this.getSamplesPerFrame(e),o=l*a,c=this._initPTS,d=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,h=[],f=s!==void 0;let p=e.samples,m=d?0:8,g=this.nextAudioTs||-1;const b=c.baseTime*i/c.timescale,y=b+t*i;if(this.isAudioContiguous=r=r||p.length&&g>0&&(n&&Math.abs(y-(g+b))<9e3||Math.abs(_t(p[0].pts,y)-(g+b))<20*o),p.forEach(function(B){B.pts=_t(B.pts,y)}),!r||g<0){const B=p.length;if(p=p.filter(j=>j.pts>=0),B!==p.length&&this.warn(`Removed ${p.length-B} of ${B} samples (initPTS ${b} / ${i})`),!p.length)return;s===0?g=0:n&&!f?g=Math.max(0,y-b):g=p[0].pts-b}if(e.segmentCodec==="aac"){const B=this.config.maxAudioFramesDrift;for(let j=0,U=g+b;j<p.length;j++){const F=p[j],Y=F.pts,I=Y-U,R=Math.abs(1e3*I/i);if(I<=-B*o&&f)j===0&&(this.warn(`Audio frame @ ${(Y/i).toFixed(3)}s overlaps marker by ${Math.round(1e3*I/i)} ms.`),this.nextAudioTs=g=Y-b,U=Y);else if(I>=B*o&&R<yP&&f){let O=Math.round(I/o);for(U=Y-O*o;U<0&&O&&o;)O--,U+=o;j===0&&(this.nextAudioTs=g=U-b),this.warn(`Injecting ${O} audio frames @ ${((U-b)/i).toFixed(3)}s due to ${Math.round(1e3*I/i)} ms gap.`);for(let K=0;K<O;K++){let W=gP.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);W||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),W=F.unit.subarray()),p.splice(j,0,{unit:W,pts:U}),U+=o,j++}}F.pts=U,U+=o}}let S=null,E=null,k,T=0,A=p.length;for(;A--;)T+=p[A].unit.byteLength;for(let B=0,j=p.length;B<j;B++){const U=p[B],F=U.unit;let Y=U.pts;if(E!==null){const R=h[B-1];R.duration=Math.round((Y-E)/a)}else if(r&&e.segmentCodec==="aac"&&(Y=g+b),S=Y,T>0){T+=m;try{k=new Uint8Array(T)}catch(R){this.observer.emit(w.ERROR,w.ERROR,{type:xe.MUX_ERROR,details:G.REMUX_ALLOC_ERROR,fatal:!1,error:R,bytes:T,reason:`fail allocating audio mdat ${T}`});return}d||(new DataView(k.buffer).setUint32(0,T),k.set(Tt.types.mdat,4))}else return;k.set(F,m);const I=F.byteLength;m+=I,h.push(sf(!0,l,I,0)),E=Y}const N=h.length;if(!N)return;const C=h[h.length-1];g=E-b,this.nextAudioTs=g+a*C.duration;const M=d?new Uint8Array(0):Tt.moof(e.sequenceNumber++,S/a,ze({},e,{samples:h}));e.samples=[];const P=(S-b)/i,D=this.nextAudioTs/i,$={data1:M,data2:k,startPTS:P,endPTS:D,startDTS:P,endDTS:D,type:"audio",hasAudio:!0,hasVideo:!1,nb:N};return this.isAudioContiguous=!0,$}};function _t(e,t){let r;if(t===null)return e;for(t<e?r=-8589934592:r=8589934592;Math.abs(e-t)>4294967296;)e+=r;return e}function wP(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}function Zb(e,t,r,n){const s=e.samples.length;if(!s)return;const i=e.inputTimeScale;for(let l=0;l<s;l++){const o=e.samples[l];o.pts=_t(o.pts-r.baseTime*i/r.timescale,t*i)/i,o.dts=_t(o.dts-n.baseTime*i/n.timescale,t*i)/i}const a=e.samples;return e.samples=[],{samples:a}}function Jb(e,t,r){const n=e.samples.length;if(!n)return;const s=e.inputTimeScale;for(let a=0;a<n;a++){const l=e.samples[a];l.pts=_t(l.pts-r.baseTime*s/r.timescale,t*s)/s}e.samples.sort((a,l)=>a.pts-l.pts);const i=e.samples;return e.samples=[],{samples:i}}var kP=class extends qt{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(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:s,video:i}=this.initData=sb(e);if(t)dR(e,t);else{const l=s||i;l!=null&&l.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${l.codec}")!`)}s&&(r=af(s,Qe.AUDIO,this)),i&&(n=af(i,Qe.VIDEO,this));const a={};s&&i?a.audiovideo={container:"video/mp4",codec:r+","+n,supplemental:i.supplemental,encrypted:i.encrypted,initSegment:e,id:"main"}:s?a.audio={container:"audio/mp4",codec:r,encrypted:s.encrypted,initSegment:e,id:"audio"}:i?a.video={container:"video/mp4",codec:n,supplemental:i.supplemental,encrypted:i.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(e,t,r,n,s,i){var a,l;let{initPTS:o,lastEndTime:c}=this;const d={audio:void 0,video:void 0,text:n,id3:r,initSegment:void 0};he(c)||(c=this.lastEndTime=s||0);const h=t.samples;if(!h.length)return d;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let p=this.initData;if((a=p)!=null&&a.length||(this.generateInitSegment(h),p=this.initData),!((l=p)!=null&&l.length))return this.warn("Failed to generate initSegment."),d;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const m=fR(h,p,this),g=p.audio?m[p.audio.id]:null,b=p.video?m[p.video.id]:null,y=xi(b,1/0),S=xi(g,1/0),E=xi(b,0,!0),k=xi(g,0,!0);let T=s,A=0;const N=g&&(!b||!o&&S<y||o&&o.trackId===p.audio.id),C=N?g:b;if(C){const Y=C.timescale,I=C.start-s*Y,R=N?p.audio.id:p.video.id;T=C.start/Y,A=N?k-S:E-y,(i||!o)&&(TP(o,T,s,A)||Y!==o.timescale)&&(o&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${I/Y} != initPTS: ${o.baseTime/o.timescale} (${o.baseTime}/${o.timescale}) trackId: ${o.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${T-s} (${I}/${Y}) trackId: ${R}`),o=null,f.initPTS=I,f.timescale=Y,f.trackId=R)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${s}`);o?(f.initPTS=o.baseTime,f.timescale=o.timescale,f.trackId=o.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=T,f.timescale=1,f.trackId=-1),this.initPTS=o={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});const M=T-o.baseTime/o.timescale,P=M+A;A>0?this.lastEndTime=P:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const D=!!p.audio,$=!!p.video;let B="";D&&(B+="audio"),$&&(B+="video");const j=(p.audio?p.audio.encrypted:!1)||(p.video?p.video.encrypted:!1),U={data1:h,startPTS:M,startDTS:M,endPTS:P,endDTS:P,type:B,hasAudio:D,hasVideo:$,nb:1,dropped:0,encrypted:j};d.audio=D&&!$?U:void 0,d.video=$?U:void 0;const F=b?.sampleCount;if(F){const Y=b.keyFrameIndex,I=Y!==-1;U.nb=F,U.dropped=Y===0||this.isVideoContiguous?0:I?Y:F,U.independent=I,U.firstKeyFrame=Y,I&&b.keyFrameStart&&(U.firstKeyFramePTS=(b.keyFrameStart-o.baseTime)/o.timescale),this.isVideoContiguous||(d.independent=I),this.isVideoContiguous||(this.isVideoContiguous=I),U.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${Y}/${F} dropped: ${U.dropped} start: ${U.firstKeyFramePTS||"NA"}`)}return d.initSegment=f,d.id3=Zb(r,s,o,o),n.samples.length&&(d.text=Jb(n,s,o)),d}};function xi(e,t,r=!1){return e?.start!==void 0?(e.start+(r?e.duration:0))/e.timescale:t}function TP(e,t,r,n){if(e===null)return!0;const s=Math.max(n,1),i=t-e.baseTime/e.timescale;return Math.abs(i-r)>s}function af(e,t,r){const n=e.codec;return n&&n.length>4?n:t===Qe.AUDIO?n==="ec-3"||n==="ac-3"||n==="alac"?n:n==="fLaC"||n==="Opus"?ma(n,!1):(r.warn(`Unhandled audio codec "${n}" in mp4 MAP`),n||"mp4a"):(r.warn(`Unhandled video codec "${n}" in mp4 MAP`),n||"avc1")}var Er;try{Er=self.performance.now.bind(self.performance)}catch{Er=Date.now}var Wi=[{demux:cP,remux:kP},{demux:fP,remux:zi},{demux:iP,remux:zi},{demux:oP,remux:zi}];Wi.splice(2,0,{demux:aP,remux:zi});var of=class{constructor(e,t,r,n,s,i){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=s,this.logger=i}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,r,n){const s=r.transmuxing;s.executeStart=Er();let i=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:l}=this;n&&(this.currentTransmuxState=n);const{contiguous:o,discontinuity:c,trackSwitch:d,accurateTimeOffset:h,timeOffset:f,initSegmentChange:p}=n||a,{audioCodec:m,videoCodec:g,defaultInitPts:b,duration:y,initSegmentData:S}=l,E=AP(i,t);if(E&&Kn(E.method)){const N=this.getDecrypter(),C=bu(E.method);if(N.isSync()){let M=N.softwareDecrypt(i,E.key.buffer,E.iv.buffer,C);if(r.part>-1){const P=N.flush();M=P&&P.buffer}if(!M)return s.executeEnd=Er(),Ho(r);i=new Uint8Array(M)}else return this.asyncResult=!0,this.decryptionPromise=N.webCryptoDecrypt(i,E.key.buffer,E.iv.buffer,C).then(M=>{const P=this.push(M,null,r);return this.decryptionPromise=null,P}),this.decryptionPromise}const k=this.needsProbing(c,d);if(k){const N=this.configureTransmuxer(i);if(N)return this.logger.warn(`[transmuxer] ${N.message}`),this.observer.emit(w.ERROR,w.ERROR,{type:xe.MEDIA_ERROR,details:G.FRAG_PARSING_ERROR,fatal:!1,error:N,reason:N.message}),s.executeEnd=Er(),Ho(r)}(c||d||p||k)&&this.resetInitSegment(S,m,g,y,t),(c||p||k)&&this.resetInitialTimestamp(b),o||this.resetContiguity();const T=this.transmux(i,E,f,h,r);this.asyncResult=Qs(T);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,s.executeEnd=Er(),T}flush(e){const t=e.transmuxing;t.executeStart=Er();const{decrypter:r,currentTransmuxState:n,decryptionPromise:s}=this;if(s)return this.asyncResult=!0,s.then(()=>this.flush(e));const i=[],{timeOffset:a}=n;if(r){const d=r.flush();d&&i.push(this.push(d.buffer,null,e))}const{demuxer:l,remuxer:o}=this;if(!l||!o){t.executeEnd=Er();const d=[Ho(e)];return this.asyncResult?Promise.resolve(d):d}const c=l.flush(a);return Qs(c)?(this.asyncResult=!0,c.then(d=>(this.flushRemux(i,d,e),i))):(this.flushRemux(i,c,e),this.asyncResult?Promise.resolve(i):i)}flushRemux(e,t,r){const{audioTrack:n,videoTrack:s,id3Track:i,textTrack:a}=t,{accurateTimeOffset:l,timeOffset:o}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${r.sn}${r.part>-1?" part: "+r.part:""} of ${this.id===fe.MAIN?"level":"track"} ${r.level}`);const c=this.remuxer.remux(n,s,i,a,o,l,!0,this.id);e.push({remuxResult:c,chunkMeta:r}),r.transmuxing.executeEnd=Er()}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,s){const{demuxer:i,remuxer:a}=this;!i||!a||(i.resetInitSegment(e,t,r,n),a.resetInitSegment(e,t,r,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,r,n,s){let i;return t&&t.method==="SAMPLE-AES"?i=this.transmuxSampleAes(e,t,r,n,s):i=this.transmuxUnencrypted(e,r,n,s),i}transmuxUnencrypted(e,t,r,n){const{audioTrack:s,videoTrack:i,id3Track:a,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,i,a,l,t,r,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,r,n,s){return this.demuxer.demuxSampleAes(e,t,r).then(i=>({remuxResult:this.remuxer.remux(i.audioTrack,i.videoTrack,i.id3Track,i.textTrack,r,n,!1,this.id),chunkMeta:s}))}configureTransmuxer(e){const{config:t,observer:r,typeSupported:n}=this;let s;for(let d=0,h=Wi.length;d<h;d++){var i;if((i=Wi[d].demux)!=null&&i.probe(e,this.logger)){s=Wi[d];break}}if(!s)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,l=this.remuxer,o=s.remux,c=s.demux;(!l||!(l instanceof o))&&(this.remuxer=new o(r,t,n,this.logger)),(!a||!(a instanceof c))&&(this.demuxer=new c(r,t,n,this.logger),this.probe=c.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new gu(this.config)),e}};function AP(e,t){let r=null;return e.byteLength>0&&t?.key!=null&&t.iv!==null&&t.method!=null&&(r=t),r}var Ho=e=>({remuxResult:{},chunkMeta:e});function Qs(e){return"then"in e&&e.then instanceof Function}var CP=class{constructor(e,t,r,n,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=r,this.duration=n,this.defaultInitPts=s||null}},NP=class{constructor(e,t,r,n,s,i){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=s,this.initSegmentChange=i}},lf=0,ey=class{constructor(e,t,r,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=lf++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=l=>{const o=l.data,c=this.hls;if(!(!c||!(o!=null&&o.event)||o.instanceNo!==this.instanceNo))switch(o.event){case"init":{var d;const h=(d=this.workerContext)==null?void 0:d.objectURL;h&&self.URL.revokeObjectURL(h);break}case"transmuxComplete":this.handleTransmuxComplete(o.data);break;case"flush":this.onFlush(o.data);break;case"workerLog":c.logger[o.data.logType]&&c.logger[o.data.logType](o.data.message);break;default:o.data=o.data||{},o.data.frag=this.frag,o.data.part=this.part,o.data.id=this.id,c.trigger(o.event,o.data);break}},this.onWorkerError=l=>{if(!this.hls)return;const o=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(w.ERROR,{type:xe.OTHER_ERROR,details:G.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:o})};const s=e.config;this.hls=e,this.id=t,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=r,this.onFlush=n;const i=(l,o)=>{o=o||{},o.frag=this.frag||void 0,l===w.ERROR&&(o=o,o.parent=this.id,o.part=this.part,this.error=o.error),this.hls.trigger(l,o)};this.observer=new Su,this.observer.on(w.FRAG_DECRYPTED,i),this.observer.on(w.ERROR,i);const a=Eh(s.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const l=this.hls.logger;if(s.workerPath||RM()){try{s.workerPath?(l.log(`loading Web Worker ${s.workerPath} for "${t}"`),this.workerContext=PM(s.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=MM());const{worker:o}=this.workerContext;o.addEventListener("message",this.onWorkerMessage),o.addEventListener("error",this.onWorkerError),o.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:qe(s)})}catch(o){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,o),this.terminateWorker(),this.error=null,this.transmuxer=new of(this.observer,a,s,"",t,e.logger)}return}}this.transmuxer=new of(this.observer,a,s,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=lf++;const t=this.hls.config,r=Eh(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:r,id:this.id,config:qe(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),DM(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.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,s,i,a,l,o,c){var d,h;o.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:p}=this,m=i?i.start:s.start,g=s.decryptdata,b=this.frag,y=!(b&&s.cc===b.cc),S=!(b&&o.level===b.level),E=b?o.sn-b.sn:-1,k=this.part?o.part-this.part.index:-1,T=E===0&&o.id>1&&o.id===b?.stats.chunkCount,A=!S&&(E===1||E===0&&(k===1||T&&k<=0)),N=self.performance.now();(S||E||s.stats.parsing.start===0)&&(s.stats.parsing.start=N),i&&(k||!A)&&(i.stats.parsing.start=N);const C=!(b&&((d=s.initSegment)==null?void 0:d.url)===((h=b.initSegment)==null?void 0:h.url)),M=new NP(y,A,l,S,m,C);if(!A||y||C){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${s.type} sn: ${o.sn}${o.part>-1?" part: "+o.part:""} ${this.id===fe.MAIN?"level":"track"}: ${o.level} id: ${o.id}
101
+ discontinuity: ${y}
102
+ trackSwitch: ${S}
103
+ contiguous: ${A}
104
+ accurateTimeOffset: ${l}
105
+ timeOffset: ${m}
106
+ initSegmentChange: ${C}`);const P=new CP(r,n,t,a,c);this.configureTransmuxer(P)}if(this.frag=s,this.part=i,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:g,chunkMeta:o,state:M},e instanceof ArrayBuffer?[e]:[]);else if(p){const P=p.push(e,g,o,M);Qs(P)?P.then(D=>{this.handleTransmuxComplete(D)}).catch(D=>{this.transmuxerError(D,o,"transmuxer-interface push error")}):this.handleTransmuxComplete(P)}}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 n=r.flush(e);Qs(n)?n.then(s=>{this.handleFlushResult(s,e)}).catch(s=>{this.transmuxerError(s,e,"transmuxer-interface flush error")}):this.handleFlushResult(n,e)}}transmuxerError(e,t,r){this.hls&&(this.error=e,this.hls.trigger(w.ERROR,{type:xe.MEDIA_ERROR,details:G.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(r=>{this.handleTransmuxComplete(r)}),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)}},cf=100,LP=class extends xu{constructor(e,t,r){super(e,t,r,"audio-stream-controller",fe.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(w.LEVEL_LOADED,this.onLevelLoaded,this),e.on(w.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(w.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(w.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(w.BUFFER_RESET,this.onBufferReset,this),e.on(w.BUFFER_CREATED,this.onBufferCreated,this),e.on(w.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(w.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(w.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(w.FRAG_LOADING,this.onFragLoading,this),e.on(w.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(w.LEVEL_LOADED,this.onLevelLoaded,this),e.off(w.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(w.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(w.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(w.BUFFER_RESET,this.onBufferReset,this),e.off(w.BUFFER_CREATED,this.onBufferCreated,this),e.off(w.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(w.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(w.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(w.FRAG_LOADING,this.onFragLoading,this),e.off(w.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:r,initPTS:n,timescale:s,trackId:i}){if(r===fe.MAIN){const a=t.cc,l=this.fragCurrent;if(this.initPTS[a]={baseTime:n,timescale:s,trackId:i},this.log(`InitPTS for cc: ${a} found from main: ${n/s} (${n}/${s}) trackId: ${i}`),this.mainAnchor=t,this.state===X.WAITING_INIT_PTS){const o=this.waitingData;(!o&&!this.loadingParts||o&&o.frag.cc!==a)&&this.syncWithAnchor(t,o?.frag)}else!this.hls.hasEnoughToStart&&l&&l.cc!==a?(l.abortRequests(),this.syncWithAnchor(t,l)):this.state===X.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var r;const n=((r=this.mainFragLoading)==null?void 0:r.frag)||null;if(t&&n?.cc===t.cc)return;const s=(n||e).cc,i=mb(this.getLevelDetails(),s,this.getLoadPosition());i&&(this.log(`Syncing with main frag at ${i.start} cc ${i.cc}`),this.startFragRequested=!1,this.nextLoadPosition=i.start,this.resetLoadingState(),this.state===X.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=X.STOPPED;return}const r=this.lastCurrentTime;this.stopLoad(),this.setInterval(cf),r>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r,this.state=X.IDLE):this.state=X.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case X.IDLE:this.doTickIdle();break;case X.WAITING_TRACK:{const{levels:e,trackId:t}=this,r=e?.[t],n=r?.details;if(n&&!this.waitForLive(r)){if(this.waitForCdnTuneIn(n))break;this.state=X.WAITING_INIT_PTS}break}case X.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case X.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:r,cache:n,complete:s}=e,i=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=X.FRAG_LOADING;const a={frag:t,part:r,payload:n.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(a),s&&super._handleFragmentLoadComplete(a)}else i&&i.cc!==e.frag.cc&&this.syncWithAnchor(i,e.frag)}else this.state=X.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:r,media:n,trackId:s}=this,i=t.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!i.startFragPrefetch)||!(r!=null&&r[s]))return;const a=r[s],l=a.details;if(!l||this.waitForLive(a)||this.waitForCdnTuneIn(l)){this.state=X.WAITING_TRACK,this.startFragRequested=!1;return}const o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,Qe.AUDIO,fe.AUDIO));const c=this.getFwdBufferInfo(o,fe.AUDIO);if(c===null)return;if(!this.switchingTrack&&this._streamEnded(c,l)){t.trigger(w.BUFFER_EOS,{type:"audio"}),this.state=X.ENDED;return}const d=c.len,h=t.maxBufferLength,f=l.fragments,p=f[0].start,m=this.getLoadPosition(),g=this.flushing?m:c.end;if(this.switchingTrack&&n){const S=m;l.PTSKnown&&S<p&&(c.end>p||c.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=p+.05)}if(d>=h&&!this.switchingTrack&&g<f[f.length-1].start)return;let b=this.getNextFragment(g,l);if(b&&this.isLoopLoading(b,g)&&(b=this.getNextFragmentLoopLoading(b,l,c,fe.MAIN,h)),!b){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(c,h,b))return;let y=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&lt(b)&&!b.endList&&(!l.live||!this.loadingParts&&g<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===gt.OK&&(this.mainFragLoading=y=null),y&&lt(y))){if(b.start>y.end){const S=this.fragmentTracker.getFragAtPos(g,fe.MAIN);S&&S.end>y.end&&(y=S,this.mainFragLoading={frag:S,targetBufferTime:null})}if(b.start>y.end)return}this.loadFragment(b,a,g)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(r=>new Ks(r))}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!==X.STOPPED&&(this.setInterval(cf),this.state=X.IDLE,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(w.AUDIO_TRACK_LOADED,r))}onAudioTrackLoaded(e,t){var r;const{levels:n}=this,{details:s,id:i,groupId:a,track:l}=t;if(!n){this.warn(`Audio tracks reset while loading track ${i} "${l.name}" of "${a}"`);return}const o=this.mainDetails;if(!o||s.endCC>o.endCC||o.expired){this.cachedTrackLoadedData=t,this.state!==X.STOPPED&&(this.state=X.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${i} "${l.name}" of "${a}" loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);const c=n[i];let d=0;if(s.live||(r=c.details)!=null&&r.live){if(this.checkLiveUpdate(s),s.deltaUpdateFailed)return;if(c.details){var h;d=this.alignPlaylists(s,c.details,(h=this.levelLastLoaded)==null?void 0:h.details)}s.alignedSliding||(Db(s,o),s.alignedSliding||wa(s,o),d=s.fragmentStart)}c.details=s,this.levelLastLoaded=c,this.startFragRequested||this.setStartPosition(o,d),this.hls.trigger(w.AUDIO_TRACK_UPDATED,{details:s,id:i,groupId:t.groupId}),this.state===X.WAITING_TRACK&&!this.waitForCdnTuneIn(s)&&(this.state=X.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const r=e.frag,{part:n,payload:s}=e,{config:i,trackId:a,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);return}const o=l[a];if(!o){this.warn("Audio track is undefined on fragment load progress");return}const c=o.details;if(!c){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(r.start);return}const d=i.defaultAudioCodec||o.audioCodec||"mp4a.40.2";let h=this.transmuxer;h||(h=this.transmuxer=new ey(this.hls,fe.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[r.cc],p=(t=r.initSegment)==null?void 0:t.data;if(f!==void 0){const g=n?n.index:-1,b=g!==-1,y=new vu(r.level,r.sn,r.stats.chunkCount,s.byteLength,g,b);h.push(s,p,d,"",r,n,c.totalduration,!1,y,f)}else{this.log(`Unknown video PTS for cc ${r.cc}, waiting for video PTS before demuxing audio frag ${r.sn} of [${c.startSN} ,${c.endSN}],track ${a}`);const{cache:m}=this.waitingData=this.waitingData||{frag:r,part:n,cache:new _b,complete:!1};m.push(new Uint8Array(s)),this.state!==X.STOPPED&&(this.state=X.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}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===fe.MAIN&&lt(t.frag)&&(this.mainFragLoading=t,this.state===X.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:r,part:n}=t;if(r.type!==fe.AUDIO){!this.audioOnly&&r.type===fe.MAIN&&!r.elementaryStreams.video&&!r.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}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"}`);return}if(lt(r)){this.fragPrevious=r;const s=this.switchingTrack;s&&(this.bufferedTrack=s,this.switchingTrack=null,this.hls.trigger(w.AUDIO_TRACK_SWITCHED,je({},s)))}this.fragBufferedComplete(r,n),this.media&&this.tick()}onError(e,t){var r;if(t.fatal){this.state=X.ERROR;return}switch(t.details){case G.FRAG_GAP:case G.FRAG_PARSING_ERROR:case G.FRAG_DECRYPT_ERROR:case G.FRAG_LOAD_ERROR:case G.FRAG_LOAD_TIMEOUT:case G.KEY_LOAD_ERROR:case G.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(fe.AUDIO,t);break;case G.AUDIO_TRACK_LOAD_ERROR:case G.AUDIO_TRACK_LOAD_TIMEOUT:case G.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===X.WAITING_TRACK&&((r=t.context)==null?void 0:r.type)===Fe.AUDIO_TRACK&&(this.state=X.IDLE);break;case G.BUFFER_ADD_CODEC_ERROR:case G.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case G.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case G.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==Qe.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==Qe.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===X.ENDED&&(this.state=X.IDLE);const r=this.mediaBuffer||this.media;r&&(this.afterBufferFlushed(r,t,fe.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const r="audio",{hls:n}=this,{remuxResult:s,chunkMeta:i}=e,a=this.getCurrentContext(i);if(!a){this.resetWhenMissingContext(i);return}const{frag:l,part:o,level:c}=a,{details:d}=c,{audio:h,text:f,id3:p,initSegment:m}=s;if(this.fragContextChanged(l)||!d){this.fragmentTracker.removeFragment(l);return}if(this.state=X.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),m!=null&&m.tracks){const g=l.initSegment||l;if(this.unhandledEncryptionError(m,l))return;this._bufferInitSegment(c,m.tracks,g,i),n.trigger(w.FRAG_PARSING_INIT_SEGMENT,{frag:g,id:r,tracks:m.tracks})}if(h){const{startPTS:g,endPTS:b,startDTS:y,endDTS:S}=h;o&&(o.elementaryStreams[Qe.AUDIO]={startPTS:g,endPTS:b,startDTS:y,endDTS:S}),l.setElementaryStreamInfo(Qe.AUDIO,g,b,y,S),this.bufferFragmentData(h,l,o,i)}if(p!=null&&(t=p.samples)!=null&&t.length){const g=ze({id:r,frag:l,details:d},p);n.trigger(w.FRAG_PARSING_METADATA,g)}if(f){const g=ze({id:r,frag:l,details:d},f);n.trigger(w.FRAG_PARSING_USERDATA,g)}}_bufferInitSegment(e,t,r,n){if(this.state!==X.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const s=t.audio;s.id=fe.AUDIO;const i=e.audioCodec;this.log(`Init audio buffer, container:${s.container}, codecs[level/parsed]=[${i}/${s.codec}]`),i&&i.split(",").length===1&&(s.levelCodec=i),this.hls.trigger(w.BUFFER_CODECS,t);const a=s.initSegment;if(a!=null&&a.byteLength){const l={type:"audio",frag:r,part:null,chunkMeta:n,parent:r.type,data:a};this.hls.trigger(w.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,r){const n=this.fragmentTracker.getState(e);if(this.switchingTrack||n===gt.NOT_LOADED||n===gt.PARTIAL){var s;if(!lt(e))this._loadInitSegment(e,t);else if((s=t.details)!=null&&s.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=X.WAITING_INIT_PTS;const i=this.mainDetails;i&&i.fragmentStart!==t.details.fragmentStart&&wa(t.details,i)}else super.loadFragment(e,t,r)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:r,assocLang:n,characteristics:s,audioCodec:i,channels:a}=this.bufferedTrack;un({name:t,lang:r,assocLang:n,characteristics:s,audioCodec:i,channels:a},e,sn)||(va(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(w.AUDIO_TRACK_SWITCHED,je({},e))}},Nu=class extends qt{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(){this.timer!==-1&&(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=t?.renditionReports;if(n){let s=-1;for(let i=0;i<n.length;i++){const a=n[i];let l;try{l=new self.URL(a.URI,t.url).href}catch(o){this.warn(`Could not construct new URL for Rendition Report: ${o}`),l=a.URI||""}if(l===e){s=i;break}else l===e.substring(0,l.length)&&(s=i)}if(s!==-1){const i=n[s],a=parseInt(i["LAST-MSN"])||t.lastPartSn;let l=parseInt(i["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const c=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&c>t.partTarget&&(l+=1)}const o=r&&wh(r);return new kh(a,l>=0?l: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(r){this.warn(`Could not construct new URL with HLS Delivery Directives: ${r}`)}return e}playlistLoaded(e,t,r){const{details:n,stats:s}=t,i=self.performance.now(),a=s.loading.first?Math.max(0,i-s.loading.first):0;n.advancedDateTime=Date.now()-a;const l=this.hls.config.timelineOffset;if(l!==n.appliedTimelineOffset){const c=Math.max(l||0,0);n.appliedTimelineOffset=c,n.fragments.forEach(d=>{d.setStart(d.playlistOffset+c)})}if(n.live||r!=null&&r.live){const c="levelInfo"in t?t.levelInfo:t.track;if(n.reloaded(r),r&&n.fragments.length>0){SM(r,n,this);const b=n.playlistParsingError;if(b){this.warn(b);const y=this.hls;if(!y.config.ignorePlaylistParsingErrors){var o;const{networkDetails:S}=t;y.trigger(w.ERROR,{type:xe.NETWORK_ERROR,details:G.LEVEL_PARSING_ERROR,fatal:!1,url:n.url,error:b,reason:b.message,level:t.level||void 0,parent:(o=n.fragments[0])==null?void 0:o.type,networkDetails:S,stats:s});return}n.playlistParsingError=null}}n.requestScheduled===-1&&(n.requestScheduled=s.loading.start);const d=this.hls.mainForwardBufferInfo,h=d?d.end-d.len:0,f=Lb(n,(n.edge-h)*1e3);if(n.requestScheduled+f<i?n.requestScheduled=i:n.requestScheduled+=f,this.log(`live playlist ${e} ${n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:n.updated?"UPDATED":"MISSED"}`),!this.canLoad||!n.live)return;let p,m,g;if(n.canBlockReload&&n.endSN&&n.advanced){const b=this.hls.config.lowLatencyMode,y=n.lastPartSn,S=n.endSN,E=n.lastPartIndex,k=E!==-1,T=y===S;k?T?(m=S+1,g=b?0:E):(m=y,g=b?E+1:n.maxPartIndex):m=S+1;const A=n.age,N=A+n.ageHeader;let C=Math.min(N-n.partTarget,n.targetduration*1.5);if(C>0){if(N>n.targetduration*3)this.log(`Playlist last advanced ${A.toFixed(2)}s ago. Omitting segment and part directives.`),m=void 0,g=void 0;else if(r!=null&&r.tuneInGoal&&N-n.partTarget>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${C} with playlist age: ${n.age}`),C=0;else{const M=Math.floor(C/n.targetduration);if(m+=M,g!==void 0){const P=Math.round(C%n.targetduration/n.partTarget);g+=P}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${A.toFixed(2)}s goal: ${C} skip sn ${M} to part ${g}`)}n.tuneInGoal=C}if(p=this.getDeliveryDirectives(n,t.deliveryDirectives,m,g),b||!T){n.requestScheduled=i,this.loadingPlaylist(c,p);return}}else(n.canBlockReload||n.canSkipUntil)&&(p=this.getDeliveryDirectives(n,t.deliveryDirectives,m,g));p&&m!==void 0&&n.canBlockReload&&(n.requestScheduled=s.loading.first+Math.max(f-a*2,f/2)),this.scheduleLoading(c,p,n)}else this.clearTimer()}scheduleLoading(e,t,r){const n=r||e.details;if(!n){this.loadingPlaylist(e,t);return}const s=self.performance.now(),i=n.requestScheduled;if(s>=i){this.loadingPlaylist(e,t);return}const a=i-s;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 s=wh(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,n=t.part,s=Vi.No),new kh(r,n,s)}checkRetry(e){const t=e.details,r=ba(e),n=e.errorAction,{action:s,retryCount:i=0,retryConfig:a}=n||{},l=!!n&&!!a&&(s===Et.RetryRequest||!n.resolved&&s===Et.SendAlternateToPenaltyBox);if(l){var o;if(i>=a.maxNumRetry)return!1;if(r&&(o=e.context)!=null&&o.deliveryDirectives)this.warn(`Retrying playlist loading ${i+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const c=mu(a,i);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),c),this.warn(`Retrying playlist loading ${i+1}/${a.maxNumRetry} after "${t}" in ${c}ms`)}e.levelRetry=!0,n.resolved=!0}return l}};function ty(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!qs(e[r].attrs,t[r].attrs))return!1;return!0}function qs(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(s=>e[s]!==t[s])}function rc(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}var IP=class extends Nu{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(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.MANIFEST_PARSED,this.onManifestParsed,this),e.on(w.LEVEL_LOADING,this.onLevelLoading,this),e.on(w.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(w.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(w.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.MANIFEST_PARSED,this.onManifestParsed,this),e.off(w.LEVEL_LOADING,this.onLevelLoading,this),e.off(w.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(w.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(w.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:s}=t,i=this.tracksInGroup[r];if(!i||i.groupId!==n){this.warn(`Audio track with id:${r} and group:${n} not found in active group ${i?.groupId}`);return}const a=i.details;i.details=t.details,this.log(`Audio track ${r} "${i.name}" lang:${i.lang} group:${n} loaded [${s.startSN}-${s.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 s=this.currentTrack;if(!r||n?.length!==r?.length||r!=null&&r.some(a=>n?.indexOf(a)===-1)){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(h=>!r||r.indexOf(h.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(h=>h.default)&&(this.selectDefaultTrack=!1),a.forEach((h,f)=>{h.id=f});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const l=this.hls.config.audioPreference;if(!s&&l){const h=dr(l,a,sn);if(h>-1)s=a[h];else{const f=dr(l,this.tracks);s=this.tracks[f]}}let o=this.findTrackId(s);o===-1&&s&&(o=this.findTrackId(null));const c={audioTracks:a};this.log(`Updating audio tracks, ${a.length} track(s) found in group(s): ${r?.join(",")}`),this.hls.trigger(w.AUDIO_TRACKS_UPDATED,c);const d=this.trackId;if(o!==-1&&d===-1)this.setAudioTrack(o);else if(a.length&&d===-1){var i;const h=new Error(`No audio track selected for current audio group-ID(s): ${(i=this.groupIds)==null?void 0:i.join(",")} track count: ${a.length}`);this.warn(h.message),this.hls.trigger(w.ERROR,{type:xe.MEDIA_ERROR,details:G.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:h})}}}onError(e,t){t.fatal||!t.context||t.context.type===Fe.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&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&&un(e,n,sn))return n;const s=dr(e,this.tracksInGroup,sn);if(s>-1){const i=this.tracksInGroup[s];return this.setAudioTrack(s),i}else if(n){let i=t.loadLevel;i===-1&&(i=t.firstAutoLevel);const a=HR(e,t.levels,r,i,sn);if(a===-1)return null;t.nextLoadLevel=a}if(e.channels||e.audioCodec){const i=dr(e,r);if(i>-1)return r[i]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const r=this.currentTrack,n=t[e],s=n.details&&!n.details.live;if(e===this.trackId&&n===r&&s||(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(w.AUDIO_TRACK_SWITCHING,je({},n)),s))return;const i=this.switchParams(n.url,r?.details,n.details);this.loadPlaylist(i)}findTrackId(e){const t=this.tracksInGroup;for(let r=0;r<t.length;r++){const n=t[r];if(!(this.selectDefaultTrack&&!n.default)&&(!e||un(e,n,sn)))return r}if(e){const{name:r,lang:n,assocLang:s,characteristics:i,audioCodec:a,channels:l}=e;for(let o=0;o<t.length;o++){const c=t[o];if(un({name:r,lang:n,assocLang:s,characteristics:i,audioCodec:a,channels:l},c,sn))return o}for(let o=0;o<t.length;o++){const c=t[o];if(qs(e.attrs,c.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return o}for(let o=0;o<t.length;o++){const c=t[o];if(qs(e.attrs,c.attrs,["LANGUAGE"]))return o}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&va(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const r=e.id,n=e.groupId,s=this.getUrlWithDirectives(e.url,t),i=e.details,a=i?.age;this.log(`Loading audio-track ${r} "${e.name}" lang:${e.lang} group:${n}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${a&&i.live?" age "+a.toFixed(1)+(i.type&&" "+i.type||""):""} ${s}`),this.hls.trigger(w.AUDIO_TRACK_LOADING,{url:s,id:r,groupId:n,deliveryDirectives:t||null,track:e})}},RP=class{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(this.queues===null||this.tracks===null)return;const n=this.queues[t];n.push(e),n.length===1&&!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(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const r=(t=e[0])==null?void 0:t.label;(r==="async-blocker"||r==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){this.queues!==null&&this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const n=t[0];try{n.execute()}catch(s){var r;if(n.onError(s),this.queues===null||this.tracks===null)return;const i=(r=this.tracks[e])==null?void 0:r.buffer;i!=null&&i.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
107
+ ${this.list("video")}
108
+ ${this.list("audio")}
109
+ ${this.list("audiovideo")}}`}list(e){var t,r;return(t=this.queues)!=null&&t[e]||(r=this.tracks)!=null&&r[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const r=(t=this.tracks)==null?void 0:t[e],n=r?.buffer;return n?`SourceBuffer${n.updating?" updating":""}${r.ended?" ended":""}${r.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(r=>r.label).join(", "))||""}},uf=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,ry="HlsJsTrackRemovedError",MP=class extends Error{constructor(e){super(e),this.name=ry}},PP=class extends qt{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=r=>{var n;this.hls&&((n=this.mediaSource)==null?void 0:n.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=r=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=r=>{const{media:n,mediaSource:s}=this;r&&this.log("Media source opened"),!(!n||!s)&&(s.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(w.MEDIA_ATTACHED,{media:n,mediaSource:s}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:r,_objectUrl:n}=this;r!==n&&this.error(`Media element src was set while attaching MediaSource (${n} > ${r})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=tR(Vr(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(w.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.MANIFEST_PARSED,this.onManifestParsed,this),e.on(w.BUFFER_RESET,this.onBufferReset,this),e.on(w.BUFFER_APPENDING,this.onBufferAppending,this),e.on(w.BUFFER_CODECS,this.onBufferCodecs,this),e.on(w.BUFFER_EOS,this.onBufferEos,this),e.on(w.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(w.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(w.FRAG_PARSED,this.onFragParsed,this),e.on(w.FRAG_CHANGED,this.onFragChanged,this),e.on(w.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(w.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.MANIFEST_PARSED,this.onManifestParsed,this),e.off(w.BUFFER_RESET,this.onBufferReset,this),e.off(w.BUFFER_APPENDING,this.onBufferAppending,this),e.off(w.BUFFER_CODECS,this.onBufferCodecs,this),e.off(w.BUFFER_EOS,this.onBufferEos,this),e.off(w.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(w.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(w.FRAG_PARSED,this.onFragParsed,this),e.off(w.FRAG_CHANGED,this.onFragChanged,this),e.off(w.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const r={};if(this.operationQueue){const s=this.isUpdating();s||this.operationQueue.removeBlockers();const i=this.isQueued();(s||i)&&this.warn(`Transfering MediaSource with${i?" operations in queue":""}${s?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const n=this.transferData;return!this.sourceBufferCount&&n&&n.mediaSource===t?ze(r,n.tracks):this.sourceBuffers.forEach(s=>{const[i]=s;i&&(r[i]=ze({},this.tracks[i]),this.removeBuffer(i)),s[0]=s[1]=null}),{media:e,mediaSource:t,tracks:r}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var r;let n=2;(t.audio&&!t.video||!t.altAudio)&&(n=1),this.bufferCodecEventsTotal=n,this.log(`${n} bufferCodec event(s) expected.`),(r=this.transferData)!=null&&r.mediaSource&&this.sourceBufferCount&&n&&this.bufferCreated()}onMediaAttaching(e,t){const r=this.media=t.media;this.transferData=this.overrides=void 0;const n=Vr(this.appendSource);if(n){const s=!!t.mediaSource;(s||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const i=this.mediaSource=t.mediaSource||new n;if(this.assignMediaSource(i),s)this._objectUrl=r.src,this.attachTransferred();else{const a=this._objectUrl=self.URL.createObjectURL(i);if(this.appendSource)try{r.removeAttribute("src");const l=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||l&&i instanceof l,df(r),DP(r,a),r.load()}catch{r.src=a}else r.src=a}r.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,r;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(r=e.constructor)==null?void 0:r.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const r=this.tracks,n=t.tracks,s=n?Object.keys(n):null,i=s?s.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(n&&s&&i){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
110
+ required tracks: ${qe(r,(l,o)=>l==="initSegment"?void 0:o)};
111
+ transfer tracks: ${qe(n,(l,o)=>l==="initSegment"?void 0:o)}}`),!Xv(n,r)){t.mediaSource=null,t.tracks=void 0;const l=e.currentTime,o=this.details,c=Math.max(l,o?.fragments[0].start||0);if(c-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${c}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(n)}"->"${Object.keys(r)}") start time: ${c} currentTime: ${l}`),this.onMediaDetaching(w.MEDIA_DETACHING,{}),this.onMediaAttaching(w.MEDIA_ATTACHING,t),e.currentTime=c;return}this.transferData=void 0,s.forEach(l=>{const o=l,c=n[o];if(c){const d=c.buffer;if(d){const h=this.fragmentTracker,f=c.id;if(h.hasFragments(f)||h.hasParts(f)){const g=De.getBuffered(d);h.detectEvictedFragments(o,g,f,null,!0)}const p=Vo(o),m=[o,d];this.sourceBuffers[p]=m,d.updating&&this.operationQueue&&this.operationQueue.prependBlocker(o),this.trackSourceBuffer(o,c)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const r=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:n,mediaSource:s,_objectUrl:i}=this;if(s){if(this.log(`media source ${r?"transferring":"detaching"}`),r)this.sourceBuffers.forEach(([a])=>{a&&this.removeBuffer(a)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const a=s.readyState==="open";try{const l=s.sourceBuffers;for(let o=l.length;o--;)a&&l[o].abort(),s.removeSourceBuffer(l[o]);a&&s.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}s.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("sourceended",this._onMediaSourceEnded),s.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(s.removeEventListener("startstreaming",this._onStartStreaming),s.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(n.removeEventListener("emptied",this._onMediaEmptied),r||(i&&self.URL.revokeObjectURL(i),this.mediaSrc===i?(n.removeAttribute("src"),this.appendSource&&df(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(w.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const r=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),r)try{var n;(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(s){this.warn(`onBufferReset ${e}`,s)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Vo(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new RP(this.tracks)}onBufferCodecs(e,t){var r;const n=this.tracks,s=Object.keys(t);this.log(`BUFFER_CODECS: "${s}" (current SB count ${this.sourceBufferCount})`);const i="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),a=!i&&this.sourceBufferCount&&this.media&&s.some(l=>!n[l]);if(i||a){this.warn(`Unsupported transition between "${Object.keys(n)}" and "${s}" SourceBuffers`);return}s.forEach(l=>{var o,c;const{id:d,codec:h,levelCodec:f,container:p,metadata:m,supplemental:g}=t[l];let b=n[l];const y=(o=this.transferData)==null||(o=o.tracks)==null?void 0:o[l],S=y!=null&&y.buffer?y:b,E=S?.pendingCodec||S?.codec,k=S?.levelCodec;b||(b=n[l]={buffer:void 0,listeners:[],codec:h,supplemental:g,container:p,levelCodec:f,metadata:m,id:d});const T=Hi(E,k),A=T?.replace(uf,"$1");let N=Hi(h,f);const C=(c=N)==null?void 0:c.replace(uf,"$1");N&&T&&A!==C&&(l.slice(0,5)==="audio"&&(N=ma(N,this.appendSource)),this.log(`switching codec ${E} to ${N}`),N!==(b.pendingCodec||b.codec)&&(b.pendingCodec=N),b.container=p,this.appendChangeType(l,p,N))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((r=t.audio)==null?void 0:r.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,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}`,s={label:`change-type=${n}`,execute:()=>{const i=this.tracks[e];if(i){const a=i.buffer;a!=null&&a.changeType&&(this.log(`changing ${e} sourceBuffer type to ${n}`),a.changeType(n),i.codec=r,i.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:i=>{this.warn(`Failed to change ${e} SourceBuffer type`,i)}};this.append(s,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const r=e.start,n=r+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(r,fe.MAIN))==null?void 0:t.gap)===!0)return;const s={label:"block-audio",execute:()=>{var i;const a=this.tracks.video;(this.lastVideoAppendEnd>n||a!=null&&a.buffer&&De.isBuffered(a.buffer,n)||((i=this.fragmentTracker.getAppendedFrag(n,fe.MAIN))==null?void 0:i.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:i=>{this.warn("Error executing block-audio operation",i)}};this.blockedAudioAppend={op:s,frag:e},this.append(s,"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:s,parent:i,frag:a,part:l,chunkMeta:o,offset:c}=t,d=o.buffering[s],{sn:h,cc:f}=a,p=self.performance.now();d.start=p;const m=a.stats.buffering,g=l?l.stats.buffering:null;m.start===0&&(m.start=p),g&&g.start===0&&(g.start=p);const b=r.audio;let y=!1;s==="audio"&&b?.container==="audio/mpeg"&&(y=!this.lastMpegAudioChunk||o.id===1||this.lastMpegAudioChunk.sn!==o.sn,this.lastMpegAudioChunk=o);const S=r.video,E=S?.buffer;if(E&&h!=="initSegment"){const A=l||a,N=this.blockedAudioAppend;if(s==="audio"&&i!=="main"&&!this.blockedAudioAppend&&!(S.ending||S.ended)){const C=A.start+A.duration*.05,M=E.buffered,P=this.currentOp("video");!M.length&&!P?this.blockAudio(A):!P&&!De.isBuffered(E,C)&&this.lastVideoAppendEnd<C&&this.blockAudio(A)}else if(s==="video"){const C=A.end;if(N){const M=N.frag.start;(C>M||C<this.lastVideoAppendEnd||De.isBuffered(E,M))&&this.unblockAudio()}this.lastVideoAppendEnd=C}}const k=(l||a).start,T={label:`append-${s}`,execute:()=>{var A;d.executeStart=self.performance.now();const N=(A=this.tracks[s])==null?void 0:A.buffer;N&&(y?this.updateTimestampOffset(N,k,.1,s,h,f):c!==void 0&&he(c)&&this.updateTimestampOffset(N,c,1e-6,s,h,f)),this.appendExecutor(n,s)},onStart:()=>{},onComplete:()=>{const A=self.performance.now();d.executeEnd=d.end=A,m.first===0&&(m.first=A),g&&g.first===0&&(g.first=A);const N={};this.sourceBuffers.forEach(([C,M])=>{C&&(N[C]=De.getBuffered(M))}),this.appendErrors[s]=0,s==="audio"||s==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(w.BUFFER_APPENDED,{type:s,frag:a,part:l,chunkMeta:o,parent:a.type,timeRanges:N})},onError:A=>{var N;const C={type:xe.MEDIA_ERROR,parent:a.type,details:G.BUFFER_APPEND_ERROR,sourceBufferName:s,frag:a,part:l,chunkMeta:o,error:A,err:A,fatal:!1},M=(N=this.media)==null?void 0:N.error;if(A.code===DOMException.QUOTA_EXCEEDED_ERR||A.name=="QuotaExceededError"||"quota"in A)C.details=G.BUFFER_FULL_ERROR;else if(A.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!M)C.errorAction=jn(!0);else if(A.name===ry&&this.sourceBufferCount===0)C.errorAction=jn(!0);else{const P=++this.appendErrors[s];this.warn(`Failed ${P}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${s}" sourceBuffer (${M||"no media error"})`),(P>=this.hls.config.appendErrorMaxRetry||M)&&(C.fatal=!0)}this.hls.trigger(w.ERROR,C)}};this.log(`queuing "${s}" append sn: ${h}${l?" p: "+l.index:""} of ${a.type===fe.MAIN?"level":"track"} ${a.level} cc: ${f}`),this.append(T,s,this.isPending(this.tracks[s]))}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(w.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:s}=t;r?this.append(this.getFlushOp(r,n,s),r):this.sourceBuffers.forEach(([i])=>{i&&this.append(this.getFlushOp(i,n,s),i)})}onFragParsed(e,t){const{frag:r,part:n}=t,s=[],i=n?n.elementaryStreams:r.elementaryStreams;i[Qe.AUDIOVIDEO]?s.push("audiovideo"):(i[Qe.AUDIO]&&s.push("audio"),i[Qe.VIDEO]&&s.push("video"));const a=()=>{const l=self.performance.now();r.stats.buffering.end=l,n&&(n.stats.buffering.end=l);const o=n?n.stats:r.stats;this.hls.trigger(w.FRAG_BUFFERED,{frag:r,part:n,stats:o,id:r.type})};s.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${r.type} level: ${r.level} sn: ${r.sn}`),this.blockBuffers(a,s).catch(l=>{this.warn(`Fragment buffered callback ${l}`),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(([s])=>{if(s){const i=this.tracks[s];(!t.type||t.type===s)&&(i.ending=!0,i.ended||(i.ended=!0,this.log(`${s} buffer reached EOS`)))}});const n=((r=this.overrides)==null?void 0:r.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([s])=>{var i;return s&&!((i=this.tracks[s])!=null&&i.ended)})?n?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:s}=this;if(!s||s.readyState!=="open"){s&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${s.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),s.endOfStream(),this.hls.trigger(w.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(w.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){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===G.BUFFER_APPEND_ERROR&&t.frag){var r;const n=(r=t.errorAction)==null?void 0:r.nextAutoLevel;he(n)&&n!==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||t===null||!this.sourceBufferCount)return;const n=e.config,s=r.currentTime,i=t.levelTargetDuration,a=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(he(a)&&a>=0){const o=Math.max(a,i),c=Math.floor(s/i)*i-o;this.flushBackBuffer(s,i,c)}const l=n.frontBufferFlushThreshold;if(he(l)&&l>0){const o=Math.max(n.maxBufferLength,l),c=Math.max(o,i),d=Math.floor(s/i)*i+c;this.flushFrontBuffer(s,i,d)}}flushBackBuffer(e,t,r){this.sourceBuffers.forEach(([n,s])=>{if(s){const a=De.getBuffered(s);if(a.length>0&&r>a.start(0)){var i;this.hls.trigger(w.BACK_BUFFER_REACHED,{bufferEnd:r});const l=this.tracks[n];if((i=this.details)!=null&&i.live)this.hls.trigger(w.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(l!=null&&l.ended){this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(w.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:n})}}})}flushFrontBuffer(e,t,r){this.sourceBuffers.forEach(([n,s])=>{if(s){const i=De.getBuffered(s),a=i.length;if(a<2)return;const l=i.start(a-1),o=i.end(a-1);if(r>l||e>=l&&e<=o)return;this.hls.trigger(w.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:n})}})}getDurationAndRange(){var e;const{details:t,mediaSource:r}=this;if(!t||!this.media||r?.readyState!=="open")return null;const n=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&r.setLiveSeekableRange){const a=Math.max(0,t.fragmentStart);return{duration:1/0,start:a,end:Math.max(a,n)}}return{duration:1/0}}const s=(e=this.overrides)==null?void 0:e.duration;if(s)return he(s)?{duration:s}:null;const i=this.media.duration;return n>(he(r.duration)?r.duration:0)&&n>i||!he(i)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:r}){const n=this.mediaSource;!this.media||!n||n.readyState!=="open"||(n.duration!==e&&(he(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),n.duration=e),t!==void 0&&r!==void 0&&(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}) ${qe(r)}`),this.tracksReady){var n;const s=(n=this.transferData)==null?void 0:n.tracks;s&&Object.keys(s).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(w.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(w.ERROR,{type:xe.MEDIA_ERROR,details:G.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 s in e){const i=s,a=e[i];if(this.isPending(a)){const l=this.getTrackCodec(a,i),o=`${a.container};codecs=${l}`;a.codec=l,this.log(`creating sourceBuffer(${o})${this.currentOp(i)?" Queued":""} ${qe(a)}`);try{const c=r.addSourceBuffer(o),d=Vo(i);t[d]=[i,c],a.buffer=c}catch(c){var n;this.error(`error while trying to add sourceBuffer: ${c.message}`),this.shiftAndExecuteNext(i),(n=this.operationQueue)==null||n.removeBlockers(),delete this.tracks[i],this.hls.trigger(w.ERROR,{type:xe.MEDIA_ERROR,details:G.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:c,sourceBufferName:i,mimeType:o,parent:a.id});return}this.trackSourceBuffer(i,a)}}this.bufferCreated()}getTrackCodec(e,t){const r=e.supplemental;let n=e.codec;r&&(t==="video"||t==="audiovideo")&&Vs(r,"video")&&(n=wR(n,r));const s=Hi(n,e.levelCodec);return s?t.slice(0,5)==="audio"?ma(s,this.appendSource):s:""}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",(s,i)=>{const a=i.removedRanges;a!=null&&a.length&&this.hls.trigger(w.BUFFER_FLUSHED,{type:s})})}get mediaSrc(){var e,t;const r=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return r?.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}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: ${(r=this.mediaSource)==null?void 0:r.readyState}`);this.error(`${n}`,t),this.hls.trigger(w.ERROR,{type:xe.MEDIA_ERROR,details:G.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});const s=this.currentOp(e);s&&s.onError(n)}updateTimestampOffset(e,t,r,n,s,i){const a=t-e.timestampOffset;Math.abs(a)>=r&&(this.log(`Updating ${n} SourceBuffer timestampOffset to ${t} (sn: ${s} cc: ${i})`),e.timestampOffset=t)}removeExecutor(e,t,r){const{media:n,mediaSource:s}=this,i=this.tracks[e],a=i?.buffer;if(!n||!s||!a){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const l=he(n.duration)?n.duration:1/0,o=he(s.duration)?s.duration:1/0,c=Math.max(0,t),d=Math.min(r,l,o);d>c&&(!i.ending||i.ended)?(i.ended=!1,this.log(`Removing [${c},${d}] from the ${e} SourceBuffer`),a.remove(c,d)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const r=this.tracks[t],n=r?.buffer;if(!n)throw new MP(`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(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}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(s=>this.appendBlocker(s));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(s=>{r===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var r;const n=(r=this.tracks[t])==null?void 0:r.buffer;!n||n.updating||this.shiftAndExecuteNext(t)})}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 s=n.buffer;if(!s)return;const i=r.bind(this,e);n.listeners.push({event:t,listener:i}),s.addEventListener(t,i)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const r=t.buffer;r&&(t.listeners.forEach(n=>{r.removeEventListener(n.event,n.listener)}),t.listeners.length=0)}};function df(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach(r=>{e.removeChild(r)})}function DP(e,t){const r=self.document.createElement("source");r.type="video/mp4",r.src=t,e.appendChild(r)}function Vo(e){return e==="audio"?1:0}var _P=class ny{constructor(t){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=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(w.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(w.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(w.MANIFEST_PARSED,this.onManifestParsed,this),t.on(w.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(w.BUFFER_CODECS,this.onBufferCodecs,this),t.on(w.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(w.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(w.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(w.MANIFEST_PARSED,this.onManifestParsed,this),t.off(w.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(w.BUFFER_CODECS,this.onBufferCodecs,this),t.off(w.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,r){const n=this.hls.levels[r.droppedLevel];this.isLevelAllowed(n)&&this.restrictedLevels.push({bitrate:n.bitrate,height:n.height,width:n.width})}onMediaAttaching(t,r){this.media=r.media instanceof HTMLVideoElement?r.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,r){const n=this.hls;this.restrictedLevels=[],this.firstLevel=r.firstLevel,n.config.capLevelToPlayerSize&&r.video&&this.startCapping()}onLevelsUpdated(t,r){this.timer&&he(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,r){this.hls.config.capLevelToPlayerSize&&r.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const t=this.hls.levels;if(t.length){const r=this.hls,n=this.getMaxLevel(t.length-1);n!==this.autoLevelCapping&&r.logger.log(`Setting autoLevelCapping to ${n}: ${t[n].height}p@${t[n].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),r.autoLevelCapping=n,r.autoLevelEnabled&&r.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=r.autoLevelCapping}}}getMaxLevel(t){const r=this.hls.levels;if(!r.length)return-1;const n=r.filter((s,i)=>this.isLevelAllowed(s)&&i<=t);return this.clientRect=null,ny.getMaxLevelByMediaSize(n,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 t=this.media,r={width:0,height:0};if(t){const n=t.getBoundingClientRect();r.width=n.width,r.height=n.height,!r.width&&!r.height&&(r.width=n.right-n.left||t.width||0,r.height=n.bottom-n.top||t.height||0)}return this.clientRect=r,r}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch{}return Math.min(t,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(t){return!this.restrictedLevels.some(r=>t.bitrate===r.bitrate&&t.width===r.width&&t.height===r.height)}static getMaxLevelByMediaSize(t,r,n){if(!(t!=null&&t.length))return-1;const s=(l,o)=>o?l.width!==o.width||l.height!==o.height:!0;let i=t.length-1;const a=Math.max(r,n);for(let l=0;l<t.length;l+=1){const o=t[l];if((o.width>=a||o.height>=a)&&s(o,t[l+1])){i=l;break}}return i}},Rt={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},OP={HLS:"h"},pn=class nc{constructor(t,r){Array.isArray(t)&&(t=t.map(n=>n instanceof nc?n:new nc(n))),this.value=t,this.params=r}},FP="Dict";function $P(e){return Array.isArray(e)?JSON.stringify(e):e instanceof Map?"Map{}":e instanceof Set?"Set{}":typeof e=="object"?JSON.stringify(e):String(e)}function BP(e,t,r,n){return new Error(`failed to ${e} "${$P(t)}" as ${r}`,{cause:n})}function pr(e,t,r){return BP("serialize",e,t,r)}var sy=class{constructor(e){this.description=e}},hf="Bare Item",UP="Boolean";function GP(e){if(typeof e!="boolean")throw pr(e,UP);return e?"?1":"?0"}function HP(e){return btoa(String.fromCharCode(...e))}var VP="Byte Sequence";function jP(e){if(ArrayBuffer.isView(e)===!1)throw pr(e,VP);return`:${HP(e)}:`}var KP="Integer";function zP(e){return e<-999999999999999||999999999999999<e}function iy(e){if(zP(e))throw pr(e,KP);return e.toString()}function WP(e){return`@${iy(e.getTime()/1e3)}`}function ay(e,t){if(e<0)return-ay(-e,t);const r=Math.pow(10,t);if(Math.abs(e*r%1-.5)<Number.EPSILON){const n=Math.floor(e*r);return(n%2===0?n:n+1)/r}else return Math.round(e*r)/r}var QP="Decimal";function qP(e){const t=ay(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw pr(e,QP);const r=t.toString();return r.includes(".")?r:`${r}.0`}var YP="String",XP=/[\x00-\x1f\x7f]+/;function ZP(e){if(XP.test(e))throw pr(e,YP);return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function JP(e){return e.description||e.toString().slice(7,-1)}var eD="Token";function ff(e){const t=JP(e);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw pr(t,eD);return t}function sc(e){switch(typeof e){case"number":if(!he(e))throw pr(e,hf);return Number.isInteger(e)?iy(e):qP(e);case"string":return ZP(e);case"symbol":return ff(e);case"boolean":return GP(e);case"object":if(e instanceof Date)return WP(e);if(e instanceof Uint8Array)return jP(e);if(e instanceof sy)return ff(e);default:throw pr(e,hf)}}var tD="Key";function ic(e){if(/^[a-z*][a-z0-9\-_.*]*$/.test(e)===!1)throw pr(e,tD);return e}function Lu(e){return e==null?"":Object.entries(e).map(([t,r])=>r===!0?`;${ic(t)}`:`;${ic(t)}=${sc(r)}`).join("")}function oy(e){return e instanceof pn?`${sc(e.value)}${Lu(e.params)}`:sc(e)}function rD(e){return`(${e.value.map(oy).join(" ")})${Lu(e.params)}`}function nD(e,t={whitespace:!0}){if(typeof e!="object"||e==null)throw pr(e,FP);const r=e instanceof Map?e.entries():Object.entries(e),n=t?.whitespace?" ":"";return Array.from(r).map(([s,i])=>{i instanceof pn||(i=new pn(i));let a=ic(s);return i.value===!0?a+=Lu(i.params):(a+="=",Array.isArray(i.value)?a+=rD(i):a+=oy(i)),a}).join(`,${n}`)}function ly(e,t){return nD(e,t)}var ar="CMCD-Object",st="CMCD-Request",en="CMCD-Session",Or="CMCD-Status",sD={br:ar,ab:ar,d:ar,ot:ar,tb:ar,tpb:ar,lb:ar,tab:ar,lab:ar,url:ar,pb:st,bl:st,tbl:st,dl:st,ltc:st,mtp:st,nor:st,nrr:st,rc:st,sn:st,sta:st,su:st,ttfb:st,ttfbb:st,ttlb:st,cmsdd:st,cmsds:st,smrt:st,df:st,cs:st,ts:st,cid:en,pr:en,sf:en,sid:en,st:en,v:en,msd:en,bs:Or,bsd:Or,cdn:Or,rtp:Or,bg:Or,pt:Or,ec:Or,e:Or},iD={REQUEST:st};function aD(e){return Object.keys(e).reduce((t,r)=>{var n;return(n=e[r])===null||n===void 0||n.forEach(s=>t[s]=r),t},{})}function oD(e,t){const r={};if(!e)return r;const n=Object.keys(e),s=t?aD(t):{};return n.reduce((i,a)=>{var l;const o=sD[a]||s[a]||iD.REQUEST,c=(l=i[o])!==null&&l!==void 0?l:i[o]={};return c[a]=e[a],i},r)}function lD(e){return["ot","sf","st","e","sta"].includes(e)}function cD(e){return typeof e=="number"?he(e):e!=null&&e!==""&&e!==!1}var cy="event";function uD(e,t){const r=new URL(e),n=new URL(t);if(r.origin!==n.origin)return e;const s=r.pathname.split("/").slice(1),i=n.pathname.split("/").slice(1,-1);for(;s[0]===i[0];)s.shift(),i.shift();for(;i.length;)i.shift(),s.unshift("..");return s.join("/")+r.search+r.hash}var Qi=e=>Math.round(e),ac=(e,t)=>Array.isArray(e)?e.map(r=>ac(r,t)):e instanceof pn&&typeof e.value=="string"?new pn(ac(e.value,t),e.params):(t.baseUrl&&(e=uD(e,t.baseUrl)),t.version===1?encodeURIComponent(e):e),Si=e=>Qi(e/100)*100,dD=(e,t)=>{let r=e;return t.version>=2&&(e instanceof pn&&typeof e.value=="string"?r=new pn([e]):typeof e=="string"&&(r=[e])),ac(r,t)},hD={br:Qi,d:Qi,bl:Si,dl:Si,mtp:Si,nor:dD,rtp:Si,tb:Qi},uy="request",dy="response",Iu=["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"],fD=["e"],pD=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function $a(e){return pD.test(e)}function mD(e){return Iu.includes(e)||fD.includes(e)||$a(e)}var hy=["d","dl","nor","ot","rtp","su"];function gD(e){return Iu.includes(e)||hy.includes(e)||$a(e)}var vD=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function bD(e){return Iu.includes(e)||hy.includes(e)||vD.includes(e)||$a(e)}var yD=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function xD(e){return yD.includes(e)||$a(e)}var SD={[dy]:bD,[cy]:mD,[uy]:gD};function fy(e,t={}){const r={};if(e==null||typeof e!="object")return r;const n=t.version||e.v||1,s=t.reportingMode||uy,i=n===1?xD:SD[s];let a=Object.keys(e).filter(i);const l=t.filter;typeof l=="function"&&(a=a.filter(l));const o=s===dy||s===cy;o&&!a.includes("ts")&&a.push("ts"),n>1&&!a.includes("v")&&a.push("v");const c=ze({},hD,t.formatters),d={version:n,reportingMode:s,baseUrl:t.baseUrl};return a.sort().forEach(h=>{let f=e[h];const p=c[h];if(typeof p=="function"&&(f=p(f,d)),h==="v"){if(n===1)return;f=n}h=="pr"&&f===1||(o&&h==="ts"&&!he(f)&&(f=Date.now()),cD(f)&&(lD(h)&&typeof f=="string"&&(f=new sy(f)),r[h]=f))}),r}function ED(e,t={}){const r={};if(!e)return r;const n=oD(fy(e,t),t?.customHeaderMap);return Object.entries(n).reduce((s,[i,a])=>{const l=ly(a,{whitespace:!1});return l&&(s[i]=l),s},r)}function wD(e,t,r){return ze(e,ED(t,r))}var kD="CMCD";function TD(e,t={}){return e?ly(fy(e,t),{whitespace:!1}):""}function AD(e,t={}){if(!e)return"";const r=TD(e,t);return encodeURIComponent(r)}function CD(e,t={}){return e?`${kD}=${AD(e,t)}`:""}var pf=/CMCD=[^&#]+/;function ND(e,t,r){const n=CD(t,r);return n?pf.test(e)?e.replace(pf,n):`${e}${e.includes("?")?"&":"?"}${n}`:e}var LD=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=n=>{try{this.apply(n,{ot:Rt.MANIFEST,su:!this.initialized})}catch(s){this.hls.logger.warn("Could not generate manifest CMCD data.",s)}},this.applyFragmentData=n=>{try{const{frag:s,part:i}=n,a=this.hls.levels[s.level],l=this.getObjectType(s),o={d:(i||s).duration*1e3,ot:l};(l===Rt.VIDEO||l===Rt.AUDIO||l==Rt.MUXED)&&(o.br=a.bitrate/1e3,o.tb=this.getTopBandwidth(l)/1e3,o.bl=this.getBufferLength(l));const c=i?this.getNextPart(i):this.getNextFrag(s);c!=null&&c.url&&c.url!==s.url&&(o.nor=c.url),this.apply(n,o)}catch(s){this.hls.logger.warn("Could not generate segment CMCD data.",s)}},this.hls=e;const t=this.config=e.config,{cmcd:r}=t;r!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=r.sessionId||e.sessionId,this.cid=r.contentId,this.useHeaders=r.useHeaders===!0,this.includeKeys=r.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(w.MEDIA_DETACHED,this.onMediaDetached,this),e.on(w.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(w.MEDIA_DETACHED,this.onMediaDetached,this),e.off(w.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=(r=t.tracks.audio)==null?void 0:r.buffer,this.videoBuffer=(n=t.tracks.video)==null?void 0:n.buffer}createData(){var e;return{v:1,sf:OP.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){ze(t,this.createData());const r=t.ot===Rt.INIT||t.ot===Rt.VIDEO||t.ot===Rt.MUXED;this.starved&&r&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:n}=this;n&&(t=Object.keys(t).reduce((i,a)=>(n.includes(a)&&(i[a]=t[a]),i),{}));const s={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),wD(e.headers,t,s)):e.url=ND(e.url,t,s)}getNextFrag(e){var t;const r=(t=this.hls.levels[e.level])==null?void 0:t.details;if(r){const n=e.sn-r.startSN;return r.fragments[n+1]}}getNextPart(e){var t;const{index:r,fragment:n}=e,s=(t=this.hls.levels[n.level])==null||(t=t.details)==null?void 0:t.partList;if(s){const{sn:i}=n;for(let a=s.length-1;a>=0;a--){const l=s[a];if(l.index===r&&l.fragment.sn===i)return s[a+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Rt.TIMED_TEXT;if(e.sn==="initSegment")return Rt.INIT;if(t==="audio")return Rt.AUDIO;if(t==="main")return this.hls.audioTracks.length?Rt.VIDEO:Rt.MUXED}getTopBandwidth(e){let t=0,r;const n=this.hls;if(e===Rt.AUDIO)r=n.audioTracks;else{const s=n.maxAutoLevel,i=s>-1?s+1:n.levels.length;r=n.levels.slice(0,i)}return r.forEach(s=>{s.bitrate>t&&(t=s.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,r=e===Rt.AUDIO?this.audioBuffer:this.videoBuffer;return!r||!t?NaN:De.bufferInfo(r,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,r=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new r(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,i,a){t(s),this.loader.load(s,i,a)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,r=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new r(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,i,a){t(s),this.loader.load(s,i,a)}}}},ID=3e5,RD=class extends qt{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(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(w.MANIFEST_PARSED,this.onManifestParsed,this),e.on(w.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(w.MANIFEST_PARSED,this.onManifestParsed,this),e.off(w.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&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=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(r=>r!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:r}=t;r!==null&&(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(r?.action===Et.SendAlternateToPenaltyBox&&r.flags===Dt.MoveAllAlternatesMatchingHost){const n=this.levels;let s=this._pathwayPriority,i=this.pathwayId;if(t.context){const{groupId:a,pathwayId:l,type:o}=t.context;a&&n?i=this.getPathwayForGroupId(a,o,i):l&&(i=l)}i in this.penalizedPathways||(this.penalizedPathways[i]=performance.now()),!s&&n&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),r.resolved=this.pathwayId!==i),t.details===G.BUFFER_APPEND_ERROR&&!t.fatal?r.resolved=!0:r.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${i} levels: ${n&&n.length} priorities: ${qe(s)} penalized: ${qe(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){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 this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const r=this.penalizedPathways,n=performance.now();Object.keys(r).forEach(s=>{n-r[s]>ID&&delete r[s]});for(let s=0;s<e.length;s++){const i=e[s];if(i in r)continue;if(i===this.pathwayId)return;const a=this.hls.nextLoadLevel,l=this.hls.levels[a];if(t=this.getLevelsForPathway(i),t.length>0){this.log(`Setting Pathway to "${i}"`),this.pathwayId=i,Mb(t),this.hls.trigger(w.LEVELS_UPDATED,{levels:t});const o=this.hls.levels[a];l&&o&&this.levels&&(o.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&o.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${o.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(e,t,r){const n=this.getLevelsForPathway(r).concat(this.levels||[]);for(let s=0;s<n.length;s++)if(t===Fe.AUDIO_TRACK&&n[s].hasAudioGroup(e)||t===Fe.SUBTITLE_TRACK&&n[s].hasSubtitleGroup(e))return n[s].pathwayId;return r}clonePathways(e){const t=this.levels;if(!t)return;const r={},n={};e.forEach(s=>{const{ID:i,"BASE-ID":a,"URI-REPLACEMENT":l}=s;if(t.some(c=>c.pathwayId===i))return;const o=this.getLevelsForPathway(a).map(c=>{const d=new ot(c.attrs);d["PATHWAY-ID"]=i;const h=d.AUDIO&&`${d.AUDIO}_clone_${i}`,f=d.SUBTITLES&&`${d.SUBTITLES}_clone_${i}`;h&&(r[d.AUDIO]=h,d.AUDIO=h),f&&(n[d.SUBTITLES]=f,d.SUBTITLES=f);const p=py(c.uri,d["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),m=new Ks({attrs:d,audioCodec:c.audioCodec,bitrate:c.bitrate,height:c.height,name:c.name,url:p,videoCodec:c.videoCodec,width:c.width});if(c.audioGroups)for(let g=1;g<c.audioGroups.length;g++)m.addGroupId("audio",`${c.audioGroups[g]}_clone_${i}`);if(c.subtitleGroups)for(let g=1;g<c.subtitleGroups.length;g++)m.addGroupId("text",`${c.subtitleGroups[g]}_clone_${i}`);return m});t.push(...o),mf(this.audioTracks,r,l,i),mf(this.subtitleTracks,n,l,i)})}loadSteeringManifest(e){const t=this.hls.config,r=t.loader;this.loader&&this.loader.destroy(),this.loader=new r(t);let n;try{n=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(n.protocol!=="data:"){const c=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;n.searchParams.set("_HLS_pathway",this.pathwayId),n.searchParams.set("_HLS_throughput",""+c)}const s={responseType:"json",url:n.href},i=t.steeringManifestLoadPolicy.default,a=i.errorRetry||i.timeoutRetry||{},l={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},o={onSuccess:(c,d,h,f)=>{this.log(`Loaded steering manifest: "${n}"`);const p=c.data;if(p?.VERSION!==1){this.log(`Steering VERSION ${p.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=p.TTL;const{"RELOAD-URI":m,"PATHWAY-CLONES":g,"PATHWAY-PRIORITY":b}=p;if(m)try{this.uri=new self.URL(m,n).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${m}`);return}this.scheduleRefresh(this.uri||h.url),g&&this.clonePathways(g);const y={steeringManifest:p,url:n.toString()};this.hls.trigger(w.STEERING_MANIFEST_LOADED,y),b&&this.updatePathwayPriority(b)},onError:(c,d,h,f)=>{if(this.log(`Error loading steering manifest: ${c.code} ${c.text} (${d.url})`),this.stopLoad(),c.code===410){this.enabled=!1,this.log(`Steering manifest ${d.url} no longer available`);return}let p=this.timeToLoad*1e3;if(c.code===429){const m=this.loader;if(typeof m?.getResponseHeader=="function"){const g=m.getResponseHeader("Retry-After");g&&(p=parseFloat(g)*1e3)}this.log(`Steering manifest ${d.url} rate limited`);return}this.scheduleRefresh(this.uri||d.url,p)},onTimeout:(c,d,h)=>{this.log(`Timeout loading steering manifest (${d.url})`),this.scheduleRefresh(this.uri||d.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(s,l,o)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var r;const n=(r=this.hls)==null?void 0:r.media;if(n&&!n.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}};function mf(e,t,r,n){e&&Object.keys(t).forEach(s=>{const i=e.filter(a=>a.groupId===s).map(a=>{const l=ze({},a);return l.details=void 0,l.attrs=new ot(l.attrs),l.url=l.attrs.URI=py(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),l.groupId=l.attrs["GROUP-ID"]=t[s],l.attrs["PATHWAY-ID"]=n,l});e.push(...i)})}function py(e,t,r,n){const{HOST:s,PARAMS:i,[r]:a}=n;let l;t&&(l=a?.[t],l&&(e=l));const o=new self.URL(e);return s&&!l&&(o.host=s),i&&Object.keys(i).sort().forEach(c=>{c&&o.searchParams.set(c,i[c])}),o.href}var my=class qi extends qt{constructor(t){super("eme",t.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=qi.CDMCleanupPromise?[qi.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=r=>{const{initDataType:n,initData:s}=r,i=`"${r.type}" event: init data type: "${n}"`;if(this.debug(i),s!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=ms(this.config));const l=a.map(_o).filter(o=>!!o);this.keyFormatPromise=this.getKeyFormatPromise(l)}this.keyFormatPromise.then(a=>{const l=ji(a);if(n!=="sinf"||l!==et.FAIRPLAY){this.log(`Ignoring "${r.type}" event with init data type: "${n}" for selected key-system ${l}`);return}let o;try{const p=mt(new Uint8Array(s)),m=ab(yu(JSON.parse(p).sinf));if(!m)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");o=new Uint8Array(m.subarray(8,24))}catch(p){this.warn(`${i} Failed to parse sinf: ${p}`);return}const c=wt(o),{keyIdToKeySessionPromise:d,mediaKeySessions:h}=this;let f=d[c];for(let p=0;p<h.length;p++){const m=h[p],g=m.decryptdata;if(!g.keyId)continue;const b=wt(g.keyId);if(xa(o,g.keyId)||g.uri.replace(/-/g,"").indexOf(c)!==-1){if(f=d[b],!f)continue;if(g.pssh)break;delete d[b],g.pssh=new Uint8Array(s),g.keyId=o,f=d[c]=f.then(()=>this.generateRequestWithPreferredKeySession(m,n,s,"encrypted-event-key-match")),f.catch(y=>this.handleError(y));break}}f||this.handleError(new Error(`Key ID ${c} not encountered in playlist. Key-system sessions ${h.length}.`))}).catch(a=>this.handleError(a))}},this.onWaitingForKey=r=>{this.log(`"${r.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(w.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(w.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(w.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(w.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(w.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(w.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(w.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(w.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(t){const{drmSystems:r,widevineLicenseUrl:n}=this.config,s=r?.[t];if(s)return s.licenseUrl;if(t===et.WIDEVINE&&n)return n}getLicenseServerUrlOrThrow(t){const r=this.getLicenseServerUrl(t);if(r===void 0)throw new Error(`no license server URL configured for key-system "${t}"`);return r}getServerCertificateUrl(t){const{drmSystems:r}=this.config,n=r?.[t];if(n)return n.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const r=this.hls.levels,n=(a,l,o)=>!!a&&o.indexOf(a)===l,s=r.map(a=>a.audioCodec).filter(n),i=r.map(a=>a.videoCodec).filter(n);return s.length+i.length===0&&i.push("avc1.42e01e"),new Promise((a,l)=>{const o=c=>{const d=c.shift();this.getMediaKeysPromise(d,s,i).then(h=>a({keySystem:d,mediaKeys:h})).catch(h=>{c.length?o(c):h instanceof Pt?l(h):l(new Pt({type:xe.KEY_SYSTEM_ERROR,details:G.KEY_SYSTEM_NO_ACCESS,error:h,fatal:!0},h.message))})};o(t)})}requestMediaKeySystemAccess(t,r){const{requestMediaKeySystemAccessFunc:n}=this.config;if(typeof n!="function"){let s=`Configured requestMediaKeySystemAccess is not a function ${n}`;return kb===null&&self.location.protocol==="http:"&&(s=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(s))}return n(t,r)}getMediaKeysPromise(t,r,n){var s;const i=hM(t,r,n,this.config.drmSystemOptions||{});let a=this.keySystemAccessPromises[t],l=(s=a)==null?void 0:s.keySystemAccess;if(!l){this.log(`Requesting encrypted media "${t}" key-system access with config: ${qe(i)}`),l=this.requestMediaKeySystemAccess(t,i);const o=a=this.keySystemAccessPromises[t]={keySystemAccess:l};return l.catch(c=>{this.log(`Failed to obtain access to key-system "${t}": ${c}`)}),l.then(c=>{this.log(`Access for key-system "${c.keySystem}" obtained`);const d=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const h=o.mediaKeys=c.createMediaKeys().then(f=>(this.log(`Media-keys created for "${t}"`),o.hasMediaKeys=!0,d.then(p=>p?this.setMediaKeysServerCertificate(f,t,p):f)));return h.catch(f=>{this.error(`Failed to create media-keys for "${t}"}: ${f}`)}),h})}return l.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:r,mediaKeys:n}){this.log(`Creating key-system session "${r}" keyId: ${wt(t.keyId||[])} keyUri: ${t.uri}`);const s={decryptdata:t,keySystem:r,mediaKeys:n,mediaKeysSession:n.createSession(),keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(t){const r=t.decryptdata;if(r.pssh){const n=this.createMediaKeySessionContext(t),s=Ei(r),i="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(n,i,r.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}updateKeySession(t,r){const n=t.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyId ${wt(t.decryptdata.keyId||[])}
112
+ } (data length: ${r.byteLength})`),n.update(r)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>_o(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:r,mediaKeys:n})=>this.attemptSetMediaKeys(r,n))}selectKeySystem(t){return new Promise((r,n)=>{this.getKeySystemSelectionPromise(t).then(({keySystem:s})=>{const i=_o(s);i?r(i):n(new Error(`Unable to find format for key-system "${s}"`))}).catch(n)})}selectKeySystemFormat(t){const r=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${r.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(r)),this.keyFormatPromise}getKeyFormatPromise(t){const r=ms(this.config),n=t.map(ji).filter(s=>!!s&&r.indexOf(s)!==-1);return this.selectKeySystem(n)}getKeyStatus(t){const{mediaKeySessions:r}=this;for(let n=0;n<r.length;n++){const s=MD(t,r[n]);if(s)return s}}loadKey(t){const r=t.keyInfo.decryptdata,n=Ei(r),s=this.bannedKeyIds[n];if(s||this.getKeyStatus(r)==="internal-error"){const l=gf(s||"internal-error",r);return this.handleError(l,t.frag),Promise.reject(l)}const i=`(keyId: ${n} format: "${r.keyFormat}" method: ${r.method} uri: ${r.uri})`;this.log(`Starting session for key ${i}`);const a=this.keyIdToKeySessionPromise[n];if(!a){const l=this.getKeySystemForKeyPromise(r).then(({keySystem:o,mediaKeys:c})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${i}`),this.attemptSetMediaKeys(o,c).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:o,mediaKeys:c,decryptdata:r}))))).then(o=>{const c="cenc",d=r.pssh?r.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(o,c,d,"playlist-key")});return l.catch(o=>this.handleError(o,t.frag)),this.keyIdToKeySessionPromise[n]=l,l}return a.catch(l=>{if(l instanceof Pt){const o=je({},l.data);this.getKeyStatus(r)==="internal-error"&&(o.decryptdata=r);const c=new Pt(o,l.message);this.handleError(c,t.frag)}}),a}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,r){if(this.hls)if(t instanceof Pt){r&&(t.data.frag=r);const n=t.data.decryptdata;this.error(`${t.message}${n?` (${wt(n.keyId||[])})`:""}`),this.hls.trigger(w.ERROR,t.data)}else this.error(t.message),this.hls.trigger(w.ERROR,{type:xe.KEY_SYSTEM_ERROR,details:G.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const r=Ei(t),n=this.keyIdToKeySessionPromise[r];if(!n){const s=ji(t.keyFormat),i=s?[s]:ms(this.config);return this.attemptKeySystemAccess(i)}return n}getKeySystemSelectionPromise(t){if(t.length||(t=ms(this.config)),t.length===0)throw new Pt({type:xe.KEY_SYSTEM_ERROR,details:G.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${qe({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,r){if(this.mediaResolved=void 0,this.mediaKeys===r)return Promise.resolve();const n=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const s=Promise.all(n).then(()=>this.media?this.media.setMediaKeys(r):new Promise((i,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=r,this.media.setMediaKeys(r).then(i).catch(a)}}));return this.mediaKeys=r,this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${t}"`),n.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(i=>n.indexOf(i)===-1)})}generateRequestWithPreferredKeySession(t,r,n,s){var i;const a=(i=this.config.drmSystems)==null||(i=i[t.keySystem])==null?void 0:i.generateRequest;if(a)try{const m=a.call(this.hls,r,n,t);if(!m)throw new Error("Invalid response from configured generateRequest filter");r=m.initDataType,n=m.initData?m.initData:null,t.decryptdata.pssh=n?new Uint8Array(n):null}catch(m){if(this.warn(m.message),this.hls&&this.hls.config.debug)throw m}if(n===null)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(t);const l=Ei(t.decryptdata),o=t.decryptdata.uri;this.log(`Generating key-session request for "${s}" keyId: ${l} URI: ${o} (init data type: ${r} length: ${n.byteLength})`);const c=new Su,d=t._onmessage=m=>{const g=t.mediaKeysSession;if(!g){c.emit("error",new Error("invalid state"));return}const{messageType:b,message:y}=m;this.log(`"${b}" message event for session "${g.sessionId}" message size: ${y.byteLength}`),b==="license-request"||b==="license-renewal"?this.renewLicense(t,y).catch(S=>{c.eventNames().length?c.emit("error",S):this.handleError(S)}):b==="license-release"?t.keySystem===et.FAIRPLAY&&this.updateKeySession(t,Xl("acknowledged")).then(()=>this.removeSession(t)).catch(S=>this.handleError(S)):this.warn(`unhandled media key message type "${b}"`)},h=(m,g)=>{g.keyStatus=m;let b;m.startsWith("usable")?c.emit("resolved"):m==="internal-error"||m==="output-restricted"||m==="output-downscaled"?b=gf(m,g.decryptdata):m==="expired"?b=new Error(`key expired (keyId: ${l})`):m==="released"?b=new Error("key released"):m==="status-pending"||this.warn(`unhandled key status change "${m}" (keyId: ${l})`),b&&(c.eventNames().length?c.emit("error",b):this.handleError(b))},f=t._onkeystatuseschange=m=>{if(!t.mediaKeysSession){c.emit("error",new Error("invalid state"));return}const g=this.getKeyStatuses(t);if(!Object.keys(g).some(S=>g[S]!=="status-pending"))return;if(g[l]==="expired"){this.log(`Expired key ${qe(g)} in key-session "${t.mediaKeysSession.sessionId}"`),this.renewKeySession(t);return}let b=g[l];if(b)h(b,t);else{var y;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(y=t.keyStatusTimeouts)[l]||(y[l]=self.setTimeout(()=>{if(!t.mediaKeysSession||!this.mediaKeys)return;const E=this.getKeyStatus(t.decryptdata);if(E&&E!=="status-pending")return this.log(`No status for keyId ${l} in key-session "${t.mediaKeysSession.sessionId}". Using session key-status ${E} from other session.`),h(E,t);this.log(`key status for ${l} in key-session "${t.mediaKeysSession.sessionId}" timed out after 1000ms`),b="internal-error",h(b,t)},1e3)),this.log(`No status for keyId ${l} (${qe(g)}).`)}};Lt(t.mediaKeysSession,"message",d),Lt(t.mediaKeysSession,"keystatuseschange",f);const p=new Promise((m,g)=>{c.on("error",g),c.on("resolved",m)});return t.mediaKeysSession.generateRequest(r,n).then(()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${l} URI: ${o}`)}).catch(m=>{throw new Pt({type:xe.KEY_SYSTEM_ERROR,details:G.KEY_SYSTEM_NO_SESSION,error:m,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${m}`)}).then(()=>p).catch(m=>(c.removeAllListeners(),this.removeSession(t).then(()=>{throw m}))).then(()=>(c.removeAllListeners(),t))}getKeyStatuses(t){const r={};return t.mediaKeysSession.keyStatuses.forEach((n,s)=>{if(typeof s=="string"&&typeof n=="object"){const l=s;s=n,n=l}const i="buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s);if(t.keySystem===et.PLAYREADY&&i.length===16){const l=wt(i);r[l]=n,Eb(i)}const a=wt(i);n==="internal-error"&&(this.bannedKeyIds[a]=n),this.log(`key status change "${n}" for keyStatuses keyId: ${a} key-session "${t.mediaKeysSession.sessionId}"`),r[a]=n}),r}fetchServerCertificate(t){const r=this.config,n=r.loader,s=new n(r),i=this.getServerCertificateUrl(t);return i?(this.log(`Fetching server certificate for "${t}"`),new Promise((a,l)=>{const o={responseType:"arraybuffer",url:i},c=r.certLoadPolicy.default,d={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};s.load(o,d,{onSuccess:(h,f,p,m)=>{a(h.data)},onError:(h,f,p,m)=>{l(new Pt({type:xe.KEY_SYSTEM_ERROR,details:G.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:p,response:je({url:o.url,data:void 0},h)},`"${t}" certificate request failed (${i}). Status: ${h.code} (${h.text})`))},onTimeout:(h,f,p)=>{l(new Pt({type:xe.KEY_SYSTEM_ERROR,details:G.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:p,response:{url:o.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(h,f,p)=>{l(new Error("aborted"))}})})):Promise.resolve()}setMediaKeysServerCertificate(t,r,n){return new Promise((s,i)=>{t.setServerCertificate(n).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${n.byteLength}) on "${r}"`),s(t)}).catch(a=>{i(new Pt({type:xe.KEY_SYSTEM_ERROR,details:G.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(t,r){return this.requestLicense(t,new Uint8Array(r)).then(n=>this.updateKeySession(t,new Uint8Array(n)).catch(s=>{throw new Pt({type:xe.KEY_SYSTEM_ERROR,details:G.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t.decryptdata,error:s,fatal:!1},s.message)}))}unpackPlayReadyKeyMessage(t,r){const n=String.fromCharCode.apply(null,new Uint16Array(r.buffer));if(!n.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),r;const s=new DOMParser().parseFromString(n,"application/xml"),i=s.querySelectorAll("HttpHeader");if(i.length>0){let d;for(let h=0,f=i.length;h<f;h++){var a,l;d=i[h];const p=(a=d.querySelector("name"))==null?void 0:a.textContent,m=(l=d.querySelector("value"))==null?void 0:l.textContent;p&&m&&t.setRequestHeader(p,m)}}const o=s.querySelector("Challenge"),c=o?.textContent;if(!c)throw new Error("Cannot find <Challenge> in key message");return Xl(atob(c))}setupLicenseXHR(t,r,n,s){const i=this.config.licenseXhrSetup;return i?Promise.resolve().then(()=>{if(!n.decryptdata)throw new Error("Key removed");return i.call(this.hls,t,r,n,s)}).catch(a=>{if(!n.decryptdata)throw a;return t.open("POST",r,!0),i.call(this.hls,t,r,n,s)}).then(a=>(t.readyState||t.open("POST",r,!0),{xhr:t,licenseChallenge:a||s})):(t.open("POST",r,!0),Promise.resolve({xhr:t,licenseChallenge:s}))}requestLicense(t,r){const n=this.config.keyLoadPolicy.default;return new Promise((s,i)=>{const a=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${a}`);const l=new XMLHttpRequest;l.responseType="arraybuffer",l.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return i(new Error("invalid state"));if(l.readyState===4)if(l.status===200){this._requestLicenseFailureCount=0;let o=l.response;this.log(`License received ${o instanceof ArrayBuffer?o.byteLength:o}`);const c=this.config.licenseResponseCallback;if(c)try{o=c.call(this.hls,l,a,t)}catch(d){this.error(d)}s(o)}else{const o=n.errorRetry,c=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||l.status>=400&&l.status<500)i(new Pt({type:xe.KEY_SYSTEM_ERROR,details:G.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t.decryptdata,fatal:!0,networkDetails:l,response:{url:a,data:void 0,code:l.status,text:l.statusText}},`License Request XHR failed (${a}). Status: ${l.status} (${l.statusText})`));else{const d=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${d} attempts left`),this.requestLicense(t,r).then(s,i)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=l,this.setupLicenseXHR(l,a,t,r).then(({xhr:o,licenseChallenge:c})=>{t.keySystem==et.PLAYREADY&&(c=this.unpackPlayReadyKeyMessage(o,c)),o.send(c)}).catch(i)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,r){if(!this.config.emeEnabled)return;const n=r.media;this.media=n,Lt(n,"encrypted",this.onMediaEncrypted),Lt(n,"waitingforkey",this.onWaitingForKey);const s=this.mediaResolved;s?s():this.mediaKeys=n.mediaKeys}onMediaDetached(){const t=this.media;t&&(Mt(t,"encrypted",this.onMediaEncrypted),Mt(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const r=this.mediaResolved;if(r&&r(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const n=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Ea.clearKeyUriToKeyIdMap();const i=s.length;qi.CDMCleanupPromise=Promise.all(s.map(a=>this.removeSession(a)).concat((n==null||(t=n.setMediaKeys(null))==null?void 0:t.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(w.ERROR,{type:xe.OTHER_ERROR,details:G.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(w.ERROR,{type:xe.OTHER_ERROR,details:G.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{i&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(t,{sessionKeys:r}){if(!(!r||!this.config.emeEnabled)&&!this.keyFormatPromise){const n=r.reduce((s,i)=>(s.indexOf(i.keyFormat)===-1&&s.push(i.keyFormat),s),[]);this.log(`Selecting key-system from session-keys ${n.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(n)}}removeSession(t){const{mediaKeysSession:r,licenseXhr:n,decryptdata:s}=t;if(r){this.log(`Remove licenses and keys and close session "${r.sessionId}" keyId: ${wt(s?.keyId||[])}`),t._onmessage&&(r.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(r.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),n&&n.readyState!==XMLHttpRequest.DONE&&n.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(t);i>-1&&this.mediaKeySessions.splice(i,1);const{keyStatusTimeouts:a}=t;a&&Object.keys(a).forEach(o=>self.clearTimeout(a[o]));const{drmSystemOptions:l}=this.config;return(pM(l)?new Promise((o,c)=>{self.setTimeout(()=>c(new Error("MediaKeySession.remove() timeout")),8e3),r.remove().then(o).catch(c)}):Promise.resolve()).catch(o=>{this.log(`Could not remove session: ${o}`),this.hls&&this.hls.trigger(w.ERROR,{type:xe.OTHER_ERROR,details:G.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${o}`)})}).then(()=>r.close()).catch(o=>{this.log(`Could not close session: ${o}`),this.hls&&this.hls.trigger(w.ERROR,{type:xe.OTHER_ERROR,details:G.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${o}`)})})}return Promise.resolve()}};my.CDMCleanupPromise=void 0;function Ei(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return wt(e.keyId)}function MD(e,t){if(e.keyId&&t.mediaKeysSession.keyStatuses.has(e.keyId))return t.mediaKeysSession.keyStatuses.get(e.keyId);if(e.matches(t.decryptdata))return t.keyStatus}var Pt=class 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 gf(e,t){const r=e==="output-restricted",n=r?G.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:G.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Pt({type:xe.KEY_SYSTEM_ERROR,details:n,fatal:!1,decryptdata:t},r?"HDCP level output restricted":`key status changed to "${e}"`)}var PD=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(w.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(w.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(w.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(w.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 n=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=n,n&&typeof n.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,r){const n=performance.now();if(t){if(this.lastTime){const s=n-this.lastTime,i=r-this.lastDroppedFrames,a=t-this.lastDecodedFrames,l=1e3*i/s,o=this.hls;if(o.trigger(w.FPS_DROP,{currentDropped:i,currentDecoded:a,totalDroppedFrames:r}),l>0&&i>o.config.fpsDroppedMonitoringThreshold*a){let c=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+c),c>0&&(o.autoLevelCapping===-1||o.autoLevelCapping>=c)&&(c=c-1,o.trigger(w.FPS_DROP_LEVEL_CAPPING,{level:c,droppedLevel:o.currentLevel}),o.autoLevelCapping=c,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)}};function gy(e,t){let r;try{r=new Event("addtrack")}catch{r=document.createEvent("Event"),r.initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)}function vy(e,t){const r=e.mode;if(r==="disabled"&&(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(n){Ke.debug(`[texttrack-utils]: ${n}`);try{const s=new self.TextTrackCue(t.startTime,t.endTime,t.text);s.id=t.id,e.addCue(s)}catch(s){Ke.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${s}`)}}r==="disabled"&&(e.mode=r)}function $n(e,t){const r=e.mode;if(r==="disabled"&&(e.mode="hidden"),e.cues)for(let n=e.cues.length;n--;)t&&e.cues[n].removeEventListener("enter",t),e.removeCue(e.cues[n]);r==="disabled"&&(e.mode=r)}function oc(e,t,r,n){const s=e.mode;if(s==="disabled"&&(e.mode="hidden"),e.cues&&e.cues.length>0){const i=_D(e.cues,t,r);for(let a=0;a<i.length;a++)(!n||n(i[a]))&&e.removeCue(i[a])}s==="disabled"&&(e.mode=s)}function DD(e,t){if(t<=e[0].startTime)return 0;const r=e.length-1;if(t>e[r].endTime)return-1;let n=0,s=r,i;for(;n<=s;)if(i=Math.floor((s+n)/2),t<e[i].startTime)s=i-1;else if(t>e[i].startTime&&n<r)n=i+1;else return i;return e[n].startTime-t<t-e[s].startTime?n:s}function _D(e,t,r){const n=[],s=DD(e,t);if(s>-1)for(let i=s,a=e.length;i<a;i++){const l=e[i];if(l.startTime>=t&&l.endTime<=r)n.push(l);else if(l.startTime>r)return n}return n}function Yi(e){const t=[];for(let r=0;r<e.length;r++){const n=e[r];(n.kind==="subtitles"||n.kind==="captions")&&n.label&&t.push(e[r])}return t}var OD=class extends Nu{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 t=null;const r=Yi(this.media.textTracks);for(let s=0;s<r.length;s++)if(r[s].mode==="hidden")t=r[s];else if(r[s].mode==="showing"){t=r[s];break}const n=this.findTrackForTextTrack(t);this.subtitleTrack!==n&&this.setSubtitleTrack(n)},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(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.MANIFEST_PARSED,this.onManifestParsed,this),e.on(w.LEVEL_LOADING,this.onLevelLoading,this),e.on(w.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(w.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(w.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.MANIFEST_PARSED,this.onManifestParsed,this),e.off(w.LEVEL_LOADING,this.onLevelLoading,this),e.off(w.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(w.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(w.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;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&&Yi(r.textTracks).forEach(s=>{$n(s)})}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:s}=t,i=this.tracksInGroup[r];if(!i||i.groupId!==n){this.warn(`Subtitle track with id:${r} and group:${n} not found in active group ${i?.groupId}`);return}const a=i.details;i.details=t.details,this.log(`Subtitle track ${r} "${i.name}" lang:${i.lang} group:${n} loaded [${s.startSN}-${s.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 s=this.currentTrack;if(!r||n?.length!==r?.length||r!=null&&r.some(i=>n?.indexOf(i)===-1)){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const i=this.tracks.filter(c=>!r||r.indexOf(c.groupId)!==-1);if(i.length)this.selectDefaultTrack&&!i.some(c=>c.default)&&(this.selectDefaultTrack=!1),i.forEach((c,d)=>{c.id=d});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=i;const a=this.hls.config.subtitlePreference;if(!s&&a){this.selectDefaultTrack=!1;const c=dr(a,i);if(c>-1)s=i[c];else{const d=dr(a,this.tracks);s=this.tracks[d]}}let l=this.findTrackId(s);l===-1&&s&&(l=this.findTrackId(null));const o={subtitleTracks:i};this.log(`Updating subtitle tracks, ${i.length} track(s) found in "${r?.join(",")}" group-id`),this.hls.trigger(w.SUBTITLE_TRACKS_UPDATED,o),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}}findTrackId(e){const t=this.tracksInGroup,r=this.selectDefaultTrack;for(let n=0;n<t.length;n++){const s=t[n];if(!(r&&!s.default||!r&&!e)&&(!e||un(s,e)))return n}if(e){for(let n=0;n<t.length;n++){const s=t[n];if(qs(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return n}for(let n=0;n<t.length;n++){const s=t[n];if(qs(e.attrs,s.attrs,["LANGUAGE"]))return n}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let r=0;r<t.length;r++){const n=t[r];if(rc(n,e))return r}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===Fe.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&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(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const r=this.currentTrack;if(r&&un(e,r))return r;const n=dr(e,this.tracksInGroup);if(n>-1){const s=this.tracksInGroup[n];return this.setSubtitleTrack(n),s}else{if(r)return null;{const s=dr(e,t);if(s>-1)return t[s]}}}}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,s=this.getUrlWithDirectives(e.url,t),i=e.details,a=i?.age;this.log(`Loading subtitle ${r} "${e.name}" lang:${e.lang} group:${n}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${a&&i.live?" age "+a.toFixed(1)+(i.type&&" "+i.type||""):""} ${s}`),this.hls.trigger(w.SUBTITLE_TRACK_LOADING,{url:s,id:r,groupId:n,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Yi(e.textTracks),r=this.currentTrack;let n;if(r&&(n=t.filter(s=>rc(r,s))[0],n||this.warn(`Unable to find subtitle TextTrack with name "${r.name}" and language "${r.lang}"`)),[].slice.call(t).forEach(s=>{s.mode!=="disabled"&&s!==n&&(s.mode="disabled")}),n){const s=this.subtitleDisplay?"showing":"hidden";n.mode!==s&&(n.mode=s)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!he(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const r=this.currentTrack,n=t[e]||null;if(this.trackId=e,this.currentTrack=n,this.toggleTrackModes(),!n){this.hls.trigger(w.SUBTITLE_TRACK_SWITCH,{id:e});return}const s=!!n.details&&!n.details.live;if(e===this.trackId&&n===r&&s)return;this.log(`Switching to subtitle-track ${e}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));const{id:i,groupId:a="",name:l,type:o,url:c}=n;this.hls.trigger(w.SUBTITLE_TRACK_SWITCH,{id:i,groupId:a,name:l,type:o,url:c});const d=this.switchParams(n.url,r?.details,n.details);this.loadPlaylist(d)}};function FD(){try{return crypto.randomUUID()}catch{try{const t=URL.createObjectURL(new Blob),r=t.toString();return URL.revokeObjectURL(t),r.slice(r.lastIndexOf("/")+1)}catch{let r=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const s=(r+Math.random()*16)%16|0;return r=Math.floor(r/16),(n=="x"?s:s&3|8).toString(16)})}}}function Ns(e){let t=5381,r=e.length;for(;r;)t=t*33^e.charCodeAt(--r);return(t>>>0).toString()}var zn=.025,Ta=(function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e})({});function $D(e,t,r){return`${e.identifier}-${r+1}-${Ns(t)}`}var BD=class{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,(e=this.assetListLoader)==null||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;return e<=0||isNaN(r)?!1:r===0?!0:(((t=this.assetList[e])==null?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 jo(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime;return t-jo(t,e)<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=he(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 jo(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<zn))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=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 this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?Ta.Range:Ta.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return UD(this)}};function jo(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<zn)?t.start:t.start+t.duration}function by(e,t,r){const n=new self.URL(e,r);return n.protocol!=="data:"&&n.searchParams.set("_HLS_primary_id",t),n}function Ko(e,t){for(;(r=e.assetList[++t])!=null&&r.error;)var r;return t}function UD(e){return`["${e.identifier}" ${e.cue.pre?"<pre>":e.cue.post?"<post>":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`}function Rn(e){const t=e.timelineStart,r=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+r).toFixed(2)}]`}var GD=class{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(w.PLAYOUT_LIMIT_REACHED,{})};const s=this.hls=new e(t);this.interstitial=r,this.assetItem=n;const i=()=>{this.hasDetails=!0};s.once(w.LEVEL_LOADED,i),s.once(w.AUDIO_TRACK_LOADED,i),s.once(w.SUBTITLE_TRACK_LOADED,i),s.on(w.MEDIA_ATTACHING,(a,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&s.on(w.BUFFER_APPENDED,()=>{const o=this.bufferedEnd;this.reachedPlayout(o)&&(this._bufferedEosTime=o,s.trigger(w.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=by(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const r=Math.min(this._bufferedEosTime||1/0,this.duration),n=this.timelineOffset,s=De.bufferInfo(e,n,0);return this.getAssetTime(s.end)>=r-.02}reachedPlayout(e){const t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=De.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((e=this.hls)==null?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(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=r=>delete r.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,r){var n;(n=this.hls)==null||n.on(e,t)}once(e,t,r){var n;(n=this.hls)==null||n.once(e,t)}off(e,t,r){var n;(n=this.hls)==null||n.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${Rn(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}},vf=.033,HD=class extends qt{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]||(t===void 0&&(t=e.start),r=this.findItemIndexAtTime(t));r>=0&&(s=n[r])!=null&&s.event;){var s;r--}return r}findItemIndexAtTime(e,t){const r=this.items;if(r)for(let n=0;n<r.length;n++){let s=r[n];if(t&&t!=="primary"&&(s=s[t]),e===s.start||e>s.start&&e<s.end)return n}return-1}findJumpRestrictedIndex(e,t){const r=this.items;if(r)for(let n=e;n<=t&&r[n];n++){const s=r[n].event;if(s!=null&&s.restrictions.jump&&!s.appendInPlace)return n}return-1}findEventIndex(e){const t=this.items;if(t)for(let n=t.length;n--;){var r;if(((r=t[n].event)==null?void 0:r.identifier)===e)return n}return-1}findAssetIndex(e,t){const r=e.assetList,n=r.length;if(n>1)for(let s=0;s<n;s++){const i=r[s];if(!i.error){const a=i.timelineStart;if(t===a||t>a&&(t<a+(i.duration||0)||s===n-1))return s}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const r=t.assetList,n=r[r.length-1];if(n)return n.identifier}return null}parseInterstitialDateRanges(e,t){const r=e.main.details,{dateRanges:n}=r,s=this.events,i=this.parseDateRanges(n,{url:r.url},t),a=Object.keys(n),l=s?s.filter(o=>!a.includes(o.identifier)):[];i.length&&i.sort((o,c)=>{const d=o.cue.pre,h=o.cue.post,f=c.cue.pre,p=c.cue.post;if(d&&!f)return-1;if(f&&!d||h&&!p)return 1;if(p&&!h)return-1;if(!d&&!f&&!h&&!p){const m=o.startTime,g=c.startTime;if(m!==g)return m-g}return o.dateRange.tagOrder-c.dateRange.tagOrder}),this.events=i,l.forEach(o=>{this.removeEvent(o)}),this.updateSchedule(e,l)}updateSchedule(e,t=[],r=!1){const n=this.events||[];if(n.length||t.length||this.length<2){const s=this.items,i=this.parseSchedule(n,e);(r||t.length||s?.length!==i.length||i.some((a,l)=>Math.abs(a.playout.start-s[l].playout.start)>.005||Math.abs(a.playout.end-s[l].playout.end)>.005))&&(this.items=i,this.onScheduleUpdate(t,s))}}parseDateRanges(e,t,r){const n=[],s=Object.keys(e);for(let i=0;i<s.length;i++){const a=s[i],l=e[a];if(l.isInterstitial){let o=this.eventMap[a];o?o.setDateRange(l):(o=new BD(l,t),this.eventMap[a]=o,r===!1&&(o.appendInPlace=r)),n.push(o)}}return n}parseSchedule(e,t){const r=[],n=t.main.details,s=n.live?1/0:n.edge;let i=0;if(e=e.filter(l=>!l.error&&!(l.cue.once&&l.hasPlayed)),e.length){this.resolveOffsets(e,t);let l=0,o=0;if(e.forEach((c,d)=>{const h=c.cue.pre,f=c.cue.post,p=e[d-1]||null,m=c.appendInPlace,g=f?s:c.startOffset,b=c.duration,y=c.timelineOccupancy===Ta.Range?b:0,S=c.resumptionOffset,E=p?.startTime===g,k=g+c.cumulativeDuration;let T=m?k+b:g+S;if(h||!f&&g<=0){const N=o;o+=y,c.timelineStart=k;const C=i;i+=b,r.push({event:c,start:k,end:T,playout:{start:C,end:i},integrated:{start:N,end:o}})}else if(g<=s){if(!E){const M=g-l;if(M>vf){const P=l,D=o;o+=M;const $=i;i+=M;const B={previousEvent:e[d-1]||null,nextEvent:c,start:P,end:P+M,playout:{start:$,end:i},integrated:{start:D,end:o}};r.push(B)}else M>0&&p&&(p.cumulativeDuration+=M,r[r.length-1].end=g)}f&&(T=k),c.timelineStart=k;const N=o;o+=y;const C=i;i+=b,r.push({event:c,start:k,end:T,playout:{start:C,end:i},integrated:{start:N,end:o}})}else return;const A=c.resumeTime;f||A>s?l=s:l=A}),l<s){var a;const c=l,d=o,h=s-l;o+=h;const f=i;i+=h,r.push({previousEvent:((a=r[r.length-1])==null?void 0:a.event)||null,nextEvent:null,start:l,end:c+h,playout:{start:f,end:i},integrated:{start:d,end:o}})}this.setDurations(s,i,o)}else r.push({previousEvent:null,nextEvent:null,start:0,end:s,playout:{start:0,end:s},integrated:{start:0,end:s}}),this.setDurations(s,s,s);return r}setDurations(e,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 s=0,i=-1;e.forEach((a,l)=>{const o=a.cue.pre,c=a.cue.post,d=o?0:c?n:a.startTime;this.updateAssetDurations(a),i===d?a.cumulativeDuration=s:(s=0,i=d),!c&&a.snapOptions.in&&(a.resumeAnchor=fn(null,r.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(a,t)||(a.appendInPlace=!1)),!a.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<vf&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`));const h=he(a.resumeOffset)?a.resumeOffset:a.duration;s+=h})}primaryCanResumeInPlaceAt(e,t){const r=e.resumeTime,n=e.startTime+e.resumptionOffset;return Math.abs(r-n)>zn?(this.log(`"${e.identifier}" resumption ${r} not aligned with estimated timeline end ${n}`),!1):!Object.keys(t).some(s=>{const i=t[s].details,a=i.edge;if(r>=a)return this.log(`"${e.identifier}" resumption ${r} past ${s} playlist end ${a}`),!1;const l=fn(null,i.fragments,r);if(!l)return this.log(`"${e.identifier}" resumption ${r} does not align with any fragments in ${s} playlist (${i.fragStart}-${i.fragmentEnd})`),!0;const o=s==="audio"?.175:0;return Math.abs(l.start-r)<zn+o||Math.abs(l.end-r)<zn+o?!1:(this.log(`"${e.identifier}" resumption ${r} not aligned with ${s} fragment bounds (${l.start}-${l.end} sn: ${l.sn} cc: ${l.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let r=0,n=!1,s=!1;for(let i=0;i<e.assetList.length;i++){const a=e.assetList[i],l=t+r;a.startOffset=r,a.timelineStart=l,n||(n=a.duration===null),s||(s=!!a.error);const o=a.error?0:a.duration||0;r+=o}n&&!s?e.duration=Math.max(r,e.duration):e.duration=r}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}};function Yt(e){return`[${e.event?'"'+e.event.identifier+'"':"primary"}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}var VD=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const r=e.assetListUrl;let n;try{n=by(r,this.hls.sessionId,e.baseUrl)}catch(d){const h=this.assignAssetListError(e,G.ASSET_LIST_LOAD_ERROR,d,r);this.hls.trigger(w.ERROR,h);return}t&&n.protocol!=="data:"&&n.searchParams.set("_HLS_start_offset",""+t);const s=this.hls.config,i=s.loader,a=new i(s),l={responseType:"json",url:n.href},o=s.interstitialAssetListLoadPolicy.default,c={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};return a.load(l,c,{onSuccess:(d,h,f,p)=>{const m=d.data,g=m?.ASSETS;if(!Array.isArray(g)){const b=this.assignAssetListError(e,G.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),f.url,h,p);this.hls.trigger(w.ERROR,b);return}e.assetListResponse=m,this.hls.trigger(w.ASSET_LIST_LOADED,{event:e,assetListResponse:m,networkDetails:p})},onError:(d,h,f,p)=>{const m=this.assignAssetListError(e,G.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${d.code} ${d.text} (${h.url})`),h.url,p,f);this.hls.trigger(w.ERROR,m)},onTimeout:(d,h,f)=>{const p=this.assignAssetListError(e,G.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${h.url})`),h.url,d,f);this.hls.trigger(w.ERROR,p)}}),this.hls.trigger(w.ASSET_LIST_LOADING,{event:e}),a}assignAssetListError(e,t,r,n,s,i){return e.error=r,{type:xe.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:n,error:r,networkDetails:i,stats:s}}};function bf(e){var t;e==null||(t=e.play())==null||t.catch(()=>{})}function Ln(e,t){return`[${e}] Advancing timeline position to ${t}`}var jD=class extends qt{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 r=this.currentTime;if(r===void 0||this.playbackDisabled||!this.schedule)return;const n=r-this.timelinePos;if(Math.abs(n)<1/7056e5)return;const s=n<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=r,this.bufferedPos=r;const i=this.playingItem;if(!i){this.checkBuffer();return}if(s&&this.schedule.resetErrorsInRange(r,r-n)&&this.updateSchedule(!0),this.checkBuffer(),s&&r<i.start||r>=i.end){var a;const h=this.findItemIndex(i);let f=this.schedule.findItemIndexAtTime(r);if(f===-1&&(f=h+(s?-1:1),this.log(`seeked ${s?"back ":""}to position not covered by schedule ${r} (resolving from ${h} to ${f})`)),!this.isInterstitial(i)&&(a=this.media)!=null&&a.paused&&(this.shouldPlay=!1),!s&&f>h){const p=this.schedule.findJumpRestrictedIndex(h+1,f);if(p>h){this.setSchedulePosition(p);return}}this.setSchedulePosition(f);return}const l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(i)){const h=i.event.assetList[0];h&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(r,h))}return}const o=l.timelineStart,c=l.duration||0;if(s&&r<o||r>=o+c){var d;(d=i.event)!=null&&d.appendInPlace&&(this.clearAssetPlayers(i.event,i),this.flushFrontBuffer(r)),this.setScheduleToAssetAtTime(r,l)}},this.onTimeupdate=()=>{const r=this.currentTime;if(r===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),r>this.timelinePos)this.timelinePos=r,r>this.bufferedPos&&this.checkBuffer();else return;const n=this.playingItem;if(!n||this.playingLastItem)return;if(r>=n.end){this.timelinePos=n.end;const i=this.findItemIndex(n);this.setSchedulePosition(i+1)}const s=this.playingAsset;s&&r>=s.timelineStart+(s.duration||0)&&this.setScheduleToAssetAtTime(r,s)},this.onScheduleUpdate=(r,n)=>{const s=this.schedule;if(!s)return;const i=this.playingItem,a=s.events||[],l=s.items||[],o=s.durations,c=r.map(m=>m.identifier),d=!!(a.length||c.length);(d||n)&&this.log(`INTERSTITIALS_UPDATED (${a.length}): ${a}
113
+ Schedule: ${l.map(m=>Yt(m))} pos: ${this.timelinePos}`),c.length&&this.log(`Removed events ${c}`);let h=null,f=null;i&&(h=this.updateItem(i,this.timelinePos),this.itemsMatch(i,h)?this.playingItem=h:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const p=this.bufferingItem;if(p&&(f=this.updateItem(p,this.bufferedPos),this.itemsMatch(p,f)?this.bufferingItem=f:p.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(p.event,null))),r.forEach(m=>{m.assetList.forEach(g=>{this.clearAssetPlayer(g.identifier,null)})}),this.playerQueue.forEach(m=>{if(m.interstitial.appendInPlace){const g=m.assetItem.timelineStart,b=m.timelineOffset-g;if(b)try{m.timelineOffset=g}catch(y){Math.abs(b)>zn&&this.warn(`${y} ("${m.assetId}" ${m.timelineOffset}->${g})`)}}}),d||n){if(this.hls.trigger(w.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:l.slice(0),durations:o,removedIds:c}),this.isInterstitial(i)&&c.includes(i.event.identifier)){this.warn(`Interstitial "${i.event.identifier}" removed while playing`),this.primaryFallback(i.event);return}i&&this.trimInPlace(h,i),p&&f!==h&&this.trimInPlace(f,p),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new VD(e),this.schedule=new HD(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(w.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(w.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(w.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(w.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(w.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(w.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(w.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(w.BUFFER_APPENDED,this.onBufferAppended,this),e.on(w.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(w.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(w.MEDIA_ENDED,this.onMediaEnded,this),e.on(w.ERROR,this.onError,this),e.on(w.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(w.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(w.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(w.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(w.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(w.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(w.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(w.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(w.BUFFER_CODECS,this.onBufferCodecs,this),e.off(w.BUFFER_APPENDED,this.onBufferAppended,this),e.off(w.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(w.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(w.MEDIA_ENDED,this.onMediaEnded,this),e.off(w.ERROR,this.onError,this),e.off(w.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){Mt(e,"play",this.onPlay),Mt(e,"pause",this.onPause),Mt(e,"seeking",this.onSeeking),Mt(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const r=this.media=t.media;Lt(r,"seeking",this.onSeeking),Lt(r,"timeupdate",this.onTimeupdate),Lt(r,"play",this.onPlay),Lt(r,"pause",this.onPause)}onMediaAttached(e,t){const r=this.effectivePlayingItem,n=this.detachedData;if(this.detachedData=null,r===null)this.checkStart();else if(!n){this.clearScheduleState();const s=this.findItemIndex(r);this.setSchedulePosition(s)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const r=!!t.transferMedia,n=this.media;if(this.media=null,!r&&(n&&this.removeMediaListeners(n),this.detachedData)){const s=this.getBufferingPlayer();s&&(this.log(`Removing schedule state for detachedData and ${s}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,s.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,r=d=>d&&e.getAssetPlayer(d.identifier),n=(d,h,f,p,m)=>{if(d){let g=d[h].start;const b=d.event;if(b){if(h==="playout"||b.timelineOccupancy!==Ta.Point){const y=r(f);y?.interstitial===b&&(g+=y.assetItem.startOffset+y[m])}}else{const y=p==="bufferedPos"?i():e[p];g+=y-d.start}return g}return 0},s=(d,h)=>{var f;if(d!==0&&h!=="primary"&&(f=e.schedule)!=null&&f.length){var p;const m=e.schedule.findItemIndexAtTime(d),g=(p=e.schedule.items)==null?void 0:p[m];if(g)return d+(g[h].start-g.start)}return d},i=()=>{const d=e.bufferedPos;return d===Number.MAX_VALUE?a("primary"):Math.max(d,0)},a=d=>{var h,f;return(h=e.primaryDetails)!=null&&h.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[d])||0},l=(d,h)=>{var f,p;const m=e.effectivePlayingItem;if(m!=null&&(f=m.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${d} "${h}"`);const g=e.effectivePlayingItem,b=e.schedule.findItemIndexAtTime(d,h),y=(p=e.schedule.items)==null?void 0:p[b],S=e.getBufferingPlayer(),E=S?.interstitial,k=E?.appendInPlace,T=g&&e.itemsMatch(g,y);if(g&&(k||T)){const A=r(e.playingAsset),N=A?.media||e.primaryMedia;if(N){const C=h==="primary"?N.currentTime:n(g,h,e.playingAsset,"timelinePos","currentTime"),M=d-C,P=(k?C:N.currentTime)+M;if(P>=0&&(!A||k||P<=A.duration)){N.currentTime=P;return}}}if(y){let A=d;if(h!=="primary"){const C=d-y[h].start;A=y.start+C}const N=!e.isInterstitial(y);if((!e.isInterstitial(g)||g.event.appendInPlace)&&(N||y.event.appendInPlace)){const C=e.media||(k?S?.media:null);C&&(C.currentTime=A)}else if(g){const C=e.findItemIndex(g);if(b>C){const P=e.schedule.findJumpRestrictedIndex(C+1,b);if(P>C){e.setSchedulePosition(P);return}}let M=0;if(N)e.timelinePos=A,e.checkBuffer();else{const P=y.event.assetList,D=d-(y[h]||y).start;for(let $=P.length;$--;){const B=P[$];if(B.duration&&D>=B.startOffset&&D<B.startOffset+B.duration){M=$;break}}}e.setSchedulePosition(b,M)}}},o=()=>{const d=e.effectivePlayingItem;if(e.isInterstitial(d))return d;const h=t();return e.isInterstitial(h)?h:null},c={get bufferedEnd(){const d=t(),h=e.bufferingItem;if(h&&h===d){var f;return n(h,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-h.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){const d=o(),h=e.effectivePlayingItem;return h&&h===d?n(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(d){const h=o(),f=e.effectivePlayingItem;f&&f===h&&l(d+f.playout.start,"playout")},get duration(){const d=o();return d?d.playout.end-d.playout.start:0},get assetPlayers(){var d;const h=(d=o())==null?void 0:d.event.assetList;return h?h.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var d;const h=(d=o())==null?void 0:d.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var d;return((d=e.schedule)==null||(d=d.events)==null?void 0:d.slice(0))||[]},get schedule(){var d;return((d=e.schedule)==null||(d=d.items)==null?void 0:d.slice(0))||[]},get interstitialPlayer(){return o()?c:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const d=t();return e.findItemIndex(d)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const d=e.effectivePlayingItem;return e.findItemIndex(d)},primary:{get bufferedEnd(){return i()},get currentTime(){const d=e.timelinePos;return d>0?d:0},set currentTime(d){l(d,"primary")},get duration(){return a("primary")},get seekableStart(){var d;return((d=e.primaryDetails)==null?void 0:d.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(d){l(d,"integrated")},get duration(){return a("integrated")},get seekableStart(){var d;return s(((d=e.primaryDetails)==null?void 0:d.fragmentStart)||0,"integrated")}},skip:()=>{const d=e.effectivePlayingItem,h=d?.event;if(h&&!h.restrictions.skip){const f=e.findItemIndex(d);h.appendInPlace?l(d.playout.start+d.event.duration+.001,"playout"):e.advanceAfterAssetEnded(h,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,r=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!r?!1:this.findItemIndex(t)===r.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const r=this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&!r.event.appendInPlace)return;let n=this.media;!n&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(n=this.primaryMedia);const s=(t=n)==null?void 0:t.currentTime;if(!(s===void 0||!he(s)))return s}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,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){this.detachedData={media:n};return}const s=e.transferMedia();this.log(`transfer MediaSource from ${e} ${qe(s)}`),this.detachedData=s}else t&&n&&(this.shouldPlay||(this.shouldPlay=!n.paused))}transferMediaTo(e,t){var r,n;if(e.media===t)return;let s=null;const i=this.hls,a=e!==i,l=a&&e.interstitial.appendInPlace,o=(r=this.detachedData)==null?void 0:r.mediaSource;let c;if(i.media)l&&(s=i.transferMedia(),this.detachedData=s),c="Primary";else if(o){const p=this.getBufferingPlayer();p?(s=p.transferMedia(),c=`${p}`):c="detached MediaSource"}else c="detached media";if(!s){if(o)s=this.detachedData,this.log(`using detachedData: MediaSource ${qe(s)}`);else if(!this.detachedData||i.media===t){const p=this.playerQueue;p.length>1&&p.forEach(m=>{if(a&&m.interstitial.appendInPlace!==l){const g=m.interstitial;this.clearInterstitial(m.interstitial,null),g.appendInPlace=!1,g.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${g}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const d=s&&"mediaSource"in s&&((n=s.mediaSource)==null?void 0:n.readyState)!=="closed",h=d&&s?s:t;this.log(`${d?"transfering MediaSource":"attaching media"} to ${a?e:"Primary"} from ${c} (media.currentTime: ${t.currentTime})`);const f=this.schedule;if(h===s&&f){const p=a&&e.assetId===f.assetIdAtEnd;h.overrides={duration:f.duration,endOfStream:!a||p,cueRemoval:!a}}e.attachMedia(h)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e?.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const r=this.timelinePos,n=this.effectivePlayingItem;if(r===-1){const s=this.hls.startPosition;if(this.timelinePos=s,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(Ln("checkStart (preroll)",s));const i=e.findEventIndex(t[0].identifier);this.setSchedulePosition(i)}else if(s>=0||!this.primaryLive){this.log(Ln("checkStart",s));const i=this.timelinePos=s>0?s:0,a=e.findItemIndexAtTime(i);this.setSchedulePosition(a)}else this.hls.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(n&&!this.playingItem){this.log(Ln("checkStart (playing item)",n.start));const s=e.findItemIndex(n);this.setSchedulePosition(s)}}advanceAssetBuffering(e,t){const r=e.event,n=Ko(r,r.findAssetIndex(t));if(!r.isAssetPastPlayoutLimit(n))this.bufferedToEvent(e,n);else if(this.schedule){var s;const i=(s=this.schedule.items)==null?void 0:s[this.findItemIndex(e)+1];i&&this.bufferedToItem(i)}}advanceAfterAssetEnded(e,t,r){const n=Ko(e,r);if(e.isAssetPastPlayoutLimit(n)){if(this.schedule){const s=this.schedule.items;if(s){const i=t+1;if(i>=s.length){this.setSchedulePosition(-1);return}const a=e.resumeTime;this.timelinePos<a&&(this.log(Ln("advanceAfterAssetEnded",a)),this.timelinePos=a,e.appendInPlace&&this.advanceInPlace(a),this.checkBuffer(this.bufferedPos<a)),this.setSchedulePosition(i)}}}else{if(e.appendInPlace){const s=e.assetList[n];s&&this.advanceInPlace(s.timelineStart)}this.setSchedulePosition(t,n)}}setScheduleToAssetAtTime(e,t){const r=this.schedule;if(!r)return;const n=t.parentIdentifier,s=r.getEvent(n);if(s){const i=r.findEventIndex(n),a=r.findAssetIndex(s,e);this.advanceAfterAssetEnded(s,i,a-1)}}setSchedulePosition(e,t){var r;const n=(r=this.schedule)==null?void 0:r.items;if(!n||this.playbackDisabled)return;const s=e>=0?n[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${s&&Yt(s)}) pos: ${this.timelinePos}`);const i=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(i)){const c=i.event,d=this.playingAsset,h=d?.identifier,f=h?this.getAssetPlayer(h):null;if(f&&h&&(!this.eventItemsMatch(i,s)||t!==void 0&&h!==c.assetList[t].identifier)){var l;const p=c.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${p+1}/${c.assetList.length} ${Rn(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(w.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:p,event:c,schedule:n.slice(0),scheduleIndex:e,player:f}),i!==this.playingItem){this.itemsMatch(i,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(c,this.findItemIndex(this.playingItem),p);return}this.retreiveMediaSource(h,s),f.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(i,s)&&(this.endedItem=i,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${c} ${Yt(i)}`),c.hasPlayed=!0,this.hls.trigger(w.INTERSTITIAL_ENDED,{event:c,schedule:n.slice(0),scheduleIndex:e}),c.cue.once)){var o;this.updateSchedule();const p=(o=this.schedule)==null?void 0:o.items;if(s&&p){const m=this.findItemIndex(s);this.advanceSchedule(m,p,t,i,a)}return}}this.advanceSchedule(e,n,t,i,a)}advanceSchedule(e,t,r,n,s){const i=this.schedule;if(!i)return;const a=t[e]||null,l=this.primaryMedia,o=this.playerQueue;if(o.length&&o.forEach(c=>{const d=c.interstitial,h=i.findEventIndex(d.identifier);(h<e||h>e+1)&&this.clearInterstitial(d,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const c=a.event;if(r===void 0){r=i.findAssetIndex(c,this.timelinePos);const p=Ko(c,r-1);if(c.isAssetPastPlayoutLimit(p)||c.appendInPlace&&this.timelinePos===a.end){this.advanceAfterAssetEnded(c,e,r);return}r=p}const d=this.waitingItem;this.assetsBuffered(a,l)||this.setBufferingItem(a);let h=this.preloadAssets(c,r);if(this.eventItemsMatch(a,d||n)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${Yt(a)} ${c.appendInPlace?"append in place":""}`),this.hls.trigger(w.INTERSTITIAL_STARTED,{event:c,schedule:t.slice(0),scheduleIndex:e})),!c.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${c}`);return}if(c.assetListLoader&&(c.assetListLoader.destroy(),c.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${c}`);return}this.waitingItem=this.endedItem=null,this.playingItem=a;const f=c.assetList[r];if(!f){this.advanceAfterAssetEnded(c,e,r||0);return}if(h||(h=this.getAssetPlayer(f.identifier)),h===null||h.destroyed){const p=c.assetList.length;this.warn(`asset ${r+1}/${p} player destroyed ${c}`),h=this.createAssetPlayer(c,f,r),h.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&c.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(h,r,t,e,l),this.shouldPlay&&bf(h.media)}else a?(this.resumePrimary(a,e,n),this.shouldPlay&&bf(this.hls.media)):s&&this.isInterstitial(n)&&(this.endedItem=null,this.playingItem=n,n.event.appendInPlace||this.attachPrimary(i.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,r){var n,s;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Yt(e)}`),!((n=this.detachedData)!=null&&n.mediaSource)){let a=this.timelinePos;(a<e.start||a>=e.end)&&(a=this.getPrimaryResumption(e,t),this.log(Ln("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)}if(!r)return;const i=(s=this.schedule)==null?void 0:s.items;i&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Yt(e)}`),this.hls.trigger(w.INTERSTITIALS_PRIMARY_RESUMED,{schedule:i.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const r=e.start;if(this.primaryLive){const n=this.primaryDetails;if(t===0)return this.hls.startPosition;if(n&&(r<n.fragmentStart||r>n.edge))return this.hls.liveSyncPosition||-1}return r}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:De.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 s=this.hls;s.media?this.checkBuffer():(this.transferMediaTo(s,n),r&&this.startLoadingPrimaryAt(e,r)),r||(this.log(Ln("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,r))}startLoadingPrimaryAt(e,t){var r;const n=this.hls;!n.loadingEnabled||!n.media||Math.abs((((r=n.mainForwardBufferInfo)==null?void 0:r.start)||n.media.currentTime)-e)>.5?n.startLoad(e,t):n.bufferingEnabled||n.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(w.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(w.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const r=this.hls.levels[t.level];if(!r.details)return;const n=je(je({},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){this.altSelection=je(je({},this.altSelection),{},{audio:r});return}const s=je(je({},n),{},{audio:r});this.mediaSelection=s}onSubtitleTrackUpdated(e,t){const r=this.hls.subtitleTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=je(je({},this.altSelection),{},{subtitles:r});return}const s=je(je({},n),{},{subtitles:r});this.mediaSelection=s}onAudioTrackSwitching(e,t){const r=Ah(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setAudioOption(t)||n.setAudioOption(r)))}onSubtitleTrackSwitch(e,t){const r=Ah(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setSubtitleOption(t)||t.id!==-1&&n.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 n=this.timelinePos;this.bufferedPos=n,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let n=0;n<t.length;n++){const s=t[n];if(s.cue.post){var r;const i=this.schedule.findEventIndex(s.identifier),a=(r=this.schedule.items)==null?void 0:r[i];this.isInterstitial(a)&&this.eventItemsMatch(a,this.bufferingItem)&&this.bufferedToItem(a,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const r=this.findItemIndex(t);this.setSchedulePosition(r+1)}else this.shouldPlay=!1}updateItem(e,t){var r;const n=(r=this.schedule)==null?void 0:r.items;return e&&n&&n[this.findItemIndex(e,t)]||null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((s,i)=>{e.event.isAssetPastPlayoutLimit(i)&&this.clearAssetPlayer(s.identifier,null)});const r=e.end+.25,n=De.bufferInfo(this.primaryMedia,r,0);(n.end>r||(n.nextStart||0)>r)&&(this.log(`trim buffered interstitial ${Yt(e)} (was ${Yt(t)})`),this.attachPrimary(r,null,!0),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===((r=t.event)==null?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&&((t=this.schedule)==null||t.updateSchedule(r,[],e))}checkBuffer(e){var t;const r=(t=this.schedule)==null?void 0:t.items;if(!r)return;const n=De.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,s=this.bufferingItem;if(this.bufferedPos>e||!n)return;if(t.length===1&&this.itemsMatch(t[0],s)){this.bufferedPos=e;return}const i=this.playingItem,a=this.findItemIndex(i);let l=n.findItemIndexAtTime(e);if(this.bufferedPos<e){var o;const c=this.findItemIndex(s),d=Math.min(c+1,t.length-1),h=t[d];if((l===-1&&s&&e>=s.end||(o=h.event)!=null&&o.appendInPlace&&e+.01>=h.start)&&(l=d),this.isInterstitial(s)){const f=s.event;if(d-a>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,l>c&&l>a)this.bufferedToItem(h);else{const f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&h.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(h)&&this.preloadAssets(h.event,0)}}else r&&i&&!this.itemsMatch(i,s)&&(l===a?this.bufferedToItem(i):l===a+1&&this.bufferedToItem(t[l]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(r=>{const n=this.getAssetPlayer(r.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,r=this.schedule;if(!this.itemsMatch(e,t)&&r){const{items:n,events:s}=r;if(!n||!s)return t;const i=this.isInterstitial(e),a=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const l=a?a.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Yt(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(i){const o=r.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((c,d)=>{const h=this.getAssetPlayer(c.identifier);h&&(d===o&&h.loadSource(),h.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(o=>o.pauseBuffering());this.hls.trigger(w.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:s.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(r!==null){this.bufferingAsset=null;const n=this.detachedData;n?n.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):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=r.assetList.length===0&&!r.assetListLoader,s=r.cue.once;if(n||!s){const i=this.preloadAssets(r,t);if(i!=null&&i.interstitial.appendInPlace){const a=this.primaryMedia;a&&this.bufferAssetPlayer(i,a)}}}preloadAssets(e,t){const r=e.assetUrl,n=e.assetList.length,s=n===0&&!e.assetListLoader,i=e.cue.once;if(s){const l=e.timelineStart;if(e.appendInPlace){var a;const h=this.playingItem;!this.isInterstitial(h)&&(h==null||(a=h.nextEvent)==null?void 0:a.identifier)===e.identifier&&this.flushFrontBuffer(l+.25)}let o,c=0;if(!this.playingItem&&this.primaryLive&&(c=this.hls.startPosition,c===-1&&(c=this.hls.liveSyncPosition||0)),c&&!(e.cue.pre||e.cue.post)){const h=c-l;h>0&&(o=Math.round(h*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${r?1:n} ${e}${o?` live-start: ${c} start-offset: ${o}`:""}`),r)return this.createAsset(e,0,0,l,e.duration,r);const d=this.assetListLoader.loadAssetList(e,o);d&&(e.assetListLoader=d)}else if(!i&&n){for(let o=t;o<n;o++){const c=e.assetList[o],d=this.getAssetPlayerQueueIndex(c.identifier);(d===-1||this.playerQueue[d].destroyed)&&!c.error&&this.createAssetPlayer(e,c,o)}const l=e.assetList[t];if(l){const o=this.getAssetPlayer(l.identifier);return o&&o.loadSource(),o}}return null}flushFrontBuffer(e){const t=this.requiredTracks;t&&(this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(r=>{this.hls.trigger(w.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:r})}))}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,s,i){const a={parentIdentifier:e.identifier,identifier:$D(e,i,t),duration:s,startOffset:r,timelineStart:n,uri:i};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,r){const n=this.hls,s=n.userConfig;let i=s.videoPreference;const a=n.loadLevelObj||n.levels[n.currentLevel];(i||a)&&(i=ze({},i),a.videoCodec&&(i.videoCodec=a.videoCodec),a.videoRange&&(i.allowedVideoRanges=[a.videoRange]));const l=n.audioTracks[n.audioTrack],o=n.subtitleTracks[n.subtitleTrack];let c=0;if(this.primaryLive||e.appendInPlace){const E=this.timelinePos-t.timelineStart;if(E>1){const k=t.duration;k&&E<k&&(c=E)}}const d=t.identifier,h=je(je({},s),{},{maxMaxBufferLength:Math.min(180,n.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:d,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:c,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:i,audioPreference:l||s.audioPreference,subtitlePreference:o||s.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(h.timelineOffset=t.timelineStart));const f=h.cmcd;f!=null&&f.sessionId&&f.contentId&&(h.cmcd=ze({},f,{contentId:Ns(t.uri)})),this.getAssetPlayer(d)&&this.warn(`Duplicate date range identifier ${e} and asset ${d}`);const p=new GD(this.HlsPlayerClass,h,e,t);this.playerQueue.push(p),e.assetList[r]=t;let m=!0;const g=E=>{if(E.live){var k;const N=new Error(`Interstitials MUST be VOD assets ${e}`),C={fatal:!0,type:xe.OTHER_ERROR,details:G.INTERSTITIAL_ASSET_ITEM_ERROR,error:N},M=((k=this.schedule)==null?void 0:k.findEventIndex(e.identifier))||-1;this.handleAssetItemError(C,e,M,r,N.message);return}const T=E.edge-E.fragmentStart,A=t.duration;(m||A===null||T>A)&&(m=!1,this.log(`Interstitial asset "${d}" duration change ${A} > ${T}`),t.duration=T,this.updateSchedule())};p.on(w.LEVEL_UPDATED,(E,{details:k})=>g(k)),p.on(w.LEVEL_PTS_UPDATED,(E,{details:k})=>g(k)),p.on(w.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const b=(E,k)=>{const T=this.getAssetPlayer(d);if(T&&k.tracks){T.off(w.BUFFER_CODECS,b),T.tracks=k.tracks;const A=this.primaryMedia;this.bufferingAsset===T.assetItem&&A&&!T.media&&this.bufferAssetPlayer(T,A)}};p.on(w.BUFFER_CODECS,b);const y=()=>{var E;const k=this.getAssetPlayer(d);if(this.log(`buffered to end of asset ${k}`),!k||!this.schedule)return;const T=this.schedule.findEventIndex(e.identifier),A=(E=this.schedule.items)==null?void 0:E[T];this.isInterstitial(A)&&this.advanceAssetBuffering(A,t)};p.on(w.BUFFERED_TO_END,y);const S=E=>()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;this.shouldPlay=!0;const k=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,k,E)};return p.once(w.MEDIA_ENDED,S(r)),p.once(w.PLAYOUT_LIMIT_REACHED,S(1/0)),p.on(w.ERROR,(E,k)=>{if(!this.schedule)return;const T=this.getAssetPlayer(d);if(k.details===G.BUFFER_STALLED_ERROR){if(T!=null&&T.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(k,e,this.schedule.findEventIndex(e.identifier),r,`Asset player error ${k.error} ${e}`)}),p.on(w.DESTROYING,()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;const E=new Error(`Asset player destroyed unexpectedly ${d}`),k={fatal:!0,type:xe.OTHER_ERROR,details:G.INTERSTITIAL_ASSET_ITEM_ERROR,error:E};this.handleAssetItemError(k,e,this.schedule.findEventIndex(e.identifier),r,E.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Rn(t)}`),this.hls.trigger(w.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:r,event:e,player:p}),p}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(r=>{this.clearAssetPlayer(r.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){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(r!==-1){const n=this.playerQueue[r];this.log(`clear ${n} toSegment: ${t&&Yt(t)}`),this.transferMediaFromPlayer(n,t),this.playerQueue.splice(r,1),n.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,r,n,s){const{interstitial:i,assetItem:a,assetId:l}=e,o=i.assetList.length,c=this.playingAsset;this.endedAsset=null,this.playingAsset=a,(!c||c.identifier!==l)&&(c&&(this.clearAssetPlayer(c.identifier,r[n]),delete c.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${o} ${Rn(a)}`),this.hls.trigger(w.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:i,schedule:r.slice(0),scheduleIndex:n,player:e})),this.bufferAssetPlayer(e,s)}bufferAssetPlayer(e,t){var r,n;if(!this.schedule)return;const{interstitial:s,assetItem:i}=e,a=this.schedule.findEventIndex(s.identifier),l=(r=this.schedule.items)==null?void 0:r[a];if(!l)return;e.loadSource(),this.setBufferingItem(l),this.bufferingAsset=i;const o=this.getBufferingPlayer();if(o===e)return;const c=s.appendInPlace;if(c&&o?.interstitial.appendInPlace===!1)return;const d=o?.tracks||((n=this.detachedData)==null?void 0:n.tracks)||this.requiredTracks;if(c&&i!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(d&&!Xv(d,e.tracks)){const h=new Error(`Asset ${Rn(i)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(d)}')`),f={fatal:!0,type:xe.OTHER_ERROR,details:G.INTERSTITIAL_ASSET_ITEM_ERROR,error:h},p=s.findAssetIndex(i);this.handleAssetItemError(f,s,a,p,h.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,r=this.primaryMedia;if(!t||!r)return;const n=r.currentTime,s=t.findAssetIndex(e,n),i=e.assetList[s];if(i){const a=this.getAssetPlayer(i.identifier);if(a){const l=a.currentTime||n-i.timelineStart,o=a.duration-l;if(this.warn(`Stalled at ${l} of ${l+o} in ${a} ${e} (media.currentTime: ${n})`),l&&(o/r.playbackRate<.5||a.bufferedInPlaceToEnd(r))&&a.hls){const c=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,c,s)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,r,n,s){if(e.details===G.BUFFER_STALLED_ERROR)return;const i=t.assetList[n]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${i&&Rn(i)} ${e.error}`),!this.schedule)return;const a=i?.identifier||"",l=this.getAssetPlayerQueueIndex(a),o=this.playerQueue[l]||null,c=this.schedule.items,d=ze({},e,{fatal:!1,errorAction:jn(!0),asset:i,assetListIndex:n,event:t,schedule:c,scheduleIndex:r,player:o});if(this.hls.trigger(w.INTERSTITIAL_ASSET_ERROR,d),!e.fatal)return;const h=this.playingAsset,f=this.bufferingAsset,p=new Error(s);if(i&&(this.clearAssetPlayer(a,null),i.error=p),!t.assetList.some(m=>!m.error))t.error=p;else for(let m=n;m<t.assetList.length;m++)this.resetAssetPlayer(t.assetList[m].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):h&&h.identifier===a?this.advanceAfterAssetEnded(t,r,n):f&&f.identifier===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}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: ${Yt(r)} error: ${e.error}`),n===-1&&(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(n===-1){this.checkStart();return}if(!this.schedule)return;const s=this.schedule.findItemIndexAtTime(n);this.setSchedulePosition(s)}onAssetListLoaded(e,t){var r,n;const s=t.event,i=s.identifier,a=t.assetListResponse.ASSETS;if(!((r=this.schedule)!=null&&r.hasEvent(i)))return;const l=s.timelineStart,o=s.duration;let c=0;a.forEach((m,g)=>{const b=parseFloat(m.DURATION);this.createAsset(s,g,c,l+c,b,m.URI),c+=b}),s.duration=c,this.log(`Loaded asset-list with duration: ${c} (was: ${o}) ${s}`);const d=this.waitingItem,h=d?.event.identifier===i;this.updateSchedule();const f=(n=this.bufferingItem)==null?void 0:n.event;if(h){var p;const m=this.schedule.findEventIndex(i),g=(p=this.schedule.items)==null?void 0:p[m];if(g){if(!this.playingItem&&this.timelinePos>g.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==m){s.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${s}`),this.log(s.error.message),this.updateSchedule(!0),this.primaryFallback(s);return}this.setBufferingItem(g)}this.setSchedulePosition(m)}else if(f?.identifier===i){const m=s.assetList[0];if(m){const g=this.getAssetPlayer(m.identifier);if(f.appendInPlace){const b=this.primaryMedia;g&&b&&this.bufferAssetPlayer(g,b)}else g&&g.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case G.ASSET_LIST_PARSING_ERROR:case G.ASSET_LIST_LOAD_ERROR:case G.ASSET_LIST_LOAD_TIMEOUT:{const r=t.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break}case G.BUFFER_STALLED_ERROR:{const r=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&r.event.appendInPlace){this.handleInPlaceStall(r.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},yf=500,KD=class extends xu{constructor(e,t,r){super(e,t,r,"subtitle-stream-controller",fe.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(w.LEVEL_LOADED,this.onLevelLoaded,this),e.on(w.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(w.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(w.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(w.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(w.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(w.LEVEL_LOADED,this.onLevelLoaded,this),e.off(w.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(w.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(w.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(w.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(w.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=X.IDLE,this.setInterval(yf),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)||(lt(r)&&(this.fragPrevious=r),this.state=X.IDLE),!n)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let i;const a=r.start;for(let o=0;o<s.length;o++)if(a>=s[o].start&&a<=s[o].end){i=s[o];break}const l=r.start+r.duration;i?i.end=l:(i={start:a,end:l},s.push(i)),this.fragmentTracker.fragBuffered(r),this.fragBufferedComplete(r,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:r,endOffset:n}=t;if(r===0&&n!==Number.POSITIVE_INFINITY){const s=n-1;if(s<=0)return;t.endOffsetSubtitles=Math.max(0,s),this.tracksBuffered.forEach(i=>{for(let a=0;a<i.length;){if(i[a].end<=s){i.shift();continue}else if(i[a].start<s)i[a].start=s;else break;a++}}),this.fragmentTracker.removeFragmentsInRange(r,s,fe.SUBTITLE)}}onError(e,t){const r=t.frag;r?.type===fe.SUBTITLE&&(t.details===G.FRAG_GAP&&this.fragmentTracker.fragBuffered(r,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==X.STOPPED&&(this.state=X.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&ty(this.levels,t)){this.levels=t.map(r=>new Ks(r));return}this.tracksBuffered=[],this.levels=t.map(r=>{const n=new Ks(r);return this.tracksBuffered[n.id]=[],n}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,fe.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var r;if(this.currentTrackId=t.id,!((r=this.levels)!=null&&r.length)||this.currentTrackId===-1){this.clearInterval();return}const n=this.levels[this.currentTrackId];n!=null&&n.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,n&&this.state!==X.STOPPED&&this.setInterval(yf)}onSubtitleTrackLoaded(e,t){var r;const{currentTrackId:n,levels:s}=this,{details:i,id:a}=t;if(!s){this.warn(`Subtitle tracks were reset while loading level ${a}`);return}const l=s[a];if(a>=s.length||!l)return;this.log(`Subtitle track ${a} loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:""},duration:${i.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let o=0;if(i.live||(r=l.details)!=null&&r.live){if(i.deltaUpdateFailed)return;const d=this.mainDetails;if(!d){this.startFragRequested=!1;return}const h=d.fragments[0];if(!l.details)i.hasProgramDateTime&&d.hasProgramDateTime?(wa(i,d),o=i.fragmentStart):h&&(o=h.start,Jl(i,o));else{var c;o=this.alignPlaylists(i,l.details,(c=this.levelLastLoaded)==null?void 0:c.details),o===0&&h&&(o=h.start,Jl(i,o))}d&&!this.startFragRequested&&this.setStartPosition(d,o)}l.details=i,this.levelLastLoaded=l,a===n&&(this.hls.trigger(w.SUBTITLE_TRACK_UPDATED,{details:i,id:a,groupId:t.groupId}),this.tick(),i.live&&!this.fragCurrent&&this.media&&this.state===X.IDLE&&(fn(null,i.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:r}=e,n=t.decryptdata,s=this.hls;if(!this.fragContextChanged(t)&&r&&r.byteLength>0&&n!=null&&n.key&&n.iv&&Kn(n.method)){const i=performance.now();this.decrypter.decrypt(new Uint8Array(r),n.key.buffer,n.iv.buffer,bu(n.method)).catch(a=>{throw s.trigger(w.ERROR,{type:xe.MEDIA_ERROR,details:G.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:t}),a}).then(a=>{const l=performance.now();s.trigger(w.FRAG_DECRYPTED,{frag:t,payload:a,stats:{tstart:i,tdecrypt:l}})}).catch(a=>{this.warn(`${a.name}: ${a.message}`),this.state=X.IDLE})}}doTick(){if(!this.media){this.state=X.IDLE;return}if(this.state===X.IDLE){const{currentTrackId:e,levels:t}=this,r=t?.[e];if(!r||!t.length||!r.details||this.waitForLive(r))return;const{config:n}=this,s=this.getLoadPosition(),{end:i,len:a}=De.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,n.maxBufferHole),l=r.details;if(a>this.hls.maxBufferLength+l.levelTargetDuration)return;const o=l.fragments,c=o.length,d=l.edge;let h=null;const f=this.fragPrevious;if(i<d){const m=n.maxFragLookUpTolerance,g=i>d-m?0:m;h=fn(f,o,Math.max(o[0].start,i),g),!h&&f&&f.start<o[0].start&&(h=o[0])}else h=o[c-1];if(h=this.filterReplacedPrimary(h,r.details),!h)return;const p=o[h.sn-l.startSN-1];if(p&&p.cc===h.cc&&this.fragmentTracker.getState(p)===gt.NOT_LOADED&&(h=p),this.fragmentTracker.getState(h)===gt.NOT_LOADED){const m=this.mapToInitFragWhenRequired(h);m&&this.loadFragment(m,r,i)}}}loadFragment(e,t,r){lt(e)?super.loadFragment(e,t,r):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new zD(this.tracksBuffered[this.currentTrackId]||[])}},zD=class{constructor(e){this.buffered=void 0;const t=(r,n,s)=>{if(n=n>>>0,n>s-1)throw new DOMException(`Failed to execute '${r}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${s})`);return e[n][r]};this.buffered={get length(){return e.length},end(r){return t("end",r,e.length)},start(r){return t("start",r,e.length)}}}},WD={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},yy=e=>String.fromCharCode(WD[e]||e),Xt=15,yr=100,QD={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},qD={17:2,18:4,21:6,22:8,23:10,19:13,20:15},YD={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},XD={25:2,26:4,29:6,30:8,31:10,27:13,28:15},ZD=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],JD=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const r=typeof t=="function"?t():t;Ke.log(`${this.time} [${e}] ${r}`)}}},tn=function(t){const r=[];for(let n=0;n<t.length;n++)r.push(t[n].toString(16));return r},xy=class{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 this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},e_=class{constructor(){this.uchar=" ",this.penState=new xy}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()}},t_=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new xy,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<yr;t++)this.chars.push(new e_);this.logger=e}equals(e){for(let t=0;t<yr;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<yr;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<yr;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>yr&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=yr)}moveCursor(e){const t=this.pos+e;if(e>1)for(let r=this.pos+1;r<t+1;r++)this.chars[r].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=yy(e);if(this.pos>=yr){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<yr;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<yr;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)}},zo=class{constructor(e){this.rows=[],this.currRow=Xt-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Xt;t++)this.rows.push(new t_(e));this.logger=e}reset(){for(let e=0;e<Xt;e++)this.rows[e].clear();this.currRow=Xt-1}equals(e){let t=!0;for(let r=0;r<Xt;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t}copy(e){for(let t=0;t<Xt;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<Xt;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 = "+qe(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let a=0;a<Xt;a++)this.rows[a].clear();const s=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){const a=i.rows[s].cueStartTime,l=this.logger.time;if(a!==null&&l!==null&&a<l)for(let o=0;o<this.nrRollUpRows;o++)this.rows[t-this.nrRollUpRows+o+1].copy(i.rows[s+o])}}this.currRow=t;const r=this.rows[this.currRow];if(e.indent!==null){const s=e.indent,i=Math.max(s-1,0);r.setCursor(e.indent),e.color=r.chars[i].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 = "+qe(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,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 s=0;s<Xt;s++){const i=this.rows[s].getTextString();i&&(n=s+1,e?t.push("Row "+n+": '"+i+"'"):t.push(i.trim()))}return t.length>0&&(e?r="["+t.join(" | ")+"]":r=t.join(`
114
+ `)),r}getTextAndFormat(){return this.rows}},xf=class{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 zo(r),this.nonDisplayedMemory=new zo(r),this.lastOutputScreen=new zo(r),this.currRollUpRow=this.displayedMemory.rows[Xt-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Xt-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let r=0;r<e.length;r++)this.writeScreen.insertChar(e[r]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};t.underline=e%2===1,t.italics=e>=46,t.italics?t.foreground="white":t.foreground=["white","green","blue","cyan","red","yellow","magenta"][Math.floor(e/2)-16],this.logger.log(2,"MIDROW: "+qe(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t: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.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))}},Sf=class{constructor(e,t,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=n_(),this.logger=void 0;const n=this.logger=new JD;this.channels=[null,new xf(e,t,n),new xf(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 r=0;r<t.length;r+=2){const n=t[r]&127,s=t[r+1]&127;let i=!1,a=null;if(n===0&&s===0)continue;this.logger.log(3,()=>"["+tn([t[r],t[r+1]])+"] -> ("+tn([n,s])+")");const l=this.cmdHistory;if(n>=16&&n<=31){if(r_(n,s,l)){wi(null,null,l),this.logger.log(3,()=>"Repeated command ("+tn([n,s])+") is dropped");continue}wi(n,s,this.cmdHistory),i=this.parseCmd(n,s),i||(i=this.parseMidrow(n,s)),i||(i=this.parsePAC(n,s)),i||(i=this.parseBackgroundAttributes(n,s))}else wi(null,null,l);if(!i&&(a=this.parseChars(n,s),a)){const o=this.currentChannel;o&&o>0?this.channels[o].insertChars(a):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!i&&!a&&this.logger.log(2,()=>"Couldn't parse cleaned data "+tn([n,s])+" orig: "+tn([t[r],t[r+1]]))}}parseCmd(e,t){if(!((e===20||e===28||e===21||e===29)&&t>=32&&t<=47||(e===23||e===31)&&t>=33&&t<=35))return!1;const r=e===20||e===21||e===23?1:2,n=this.channels[r];return e===20||e===21||e===28||e===29?t===32?n.ccRCL():t===33?n.ccBS():t===34?n.ccAOF():t===35?n.ccAON():t===36?n.ccDER():t===37?n.ccRU(2):t===38?n.ccRU(3):t===39?n.ccRU(4):t===40?n.ccFON():t===41?n.ccRDC():t===42?n.ccTR():t===43?n.ccRTD():t===44?n.ccEDM():t===45?n.ccCR():t===46?n.ccENM():t===47&&n.ccEOC():n.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let r=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?r=1:r=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 ("+tn([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let r;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(e===16||e===24)&&t>=64&&t<=95))return!1;const n=e<=23?1:2;t>=64&&t<=95?r=n===1?QD[e]:YD[e]:r=n===1?qD[e]:XD[e];const s=this.channels[n];return s?(s.setPAC(this.interpretPAC(r,t)),this.currentChannel=n,!0):!1}interpretPAC(e,t){let r;const n={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?r=t-96:r=t-64,n.underline=(r&1)===1,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=Math.floor((r-16)/2)*4,n}parseChars(e,t){let r,n=null,s=null;if(e>=25?(r=2,s=e-8):(r=1,s=e),s>=17&&s<=19){let i;s===17?i=t+80:s===18?i=t+112:i=t+144,this.logger.log(2,()=>"Special char '"+yy(i)+"' in channel "+r),n=[i]}else e>=32&&e<=127&&(n=t===0?[e]:[e,t]);return n&&this.logger.log(3,()=>"Char codes = "+tn(n).join(",")),n}parseBackgroundAttributes(e,t){if(!((e===16||e===24)&&t>=32&&t<=47||(e===23||e===31)&&t>=45&&t<=47))return!1;let r;const n={};e===16||e===24?(r=Math.floor((t-32)/2),n.background=ZD[r],t%2===1&&(n.background=n.background+"_semi")):t===45?n.background="transparent":(n.foreground="black",t===47&&(n.underline=!0));const s=e<=23?1:2;return this.channels[s].setBkgData(n),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}wi(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 wi(e,t,r){r.a=e,r.b=t}function r_(e,t,r){return r.a===e&&r.b===t}function n_(){return{a:null,b:null}}var Ru=(function(){if(Sa!=null&&Sa.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function r(l,o){if(typeof o!="string"||!Array.isArray(l))return!1;const c=o.toLowerCase();return~l.indexOf(c)?c:!1}function n(l){return r(e,l)}function s(l){return r(t,l)}function i(l,...o){let c=1;for(;c<arguments.length;c++){const d=arguments[c];for(const h in d)l[h]=d[h]}return l}function a(l,o,c){const d=this,h={enumerable:!0};d.hasBeenReset=!1;let f="",p=!1,m=l,g=o,b=c,y=null,S="",E=!0,k="auto",T="start",A=50,N="middle",C=50,M="middle";Object.defineProperty(d,"id",i({},h,{get:function(){return f},set:function(P){f=""+P}})),Object.defineProperty(d,"pauseOnExit",i({},h,{get:function(){return p},set:function(P){p=!!P}})),Object.defineProperty(d,"startTime",i({},h,{get:function(){return m},set:function(P){if(typeof P!="number")throw new TypeError("Start time must be set to a number.");m=P,this.hasBeenReset=!0}})),Object.defineProperty(d,"endTime",i({},h,{get:function(){return g},set:function(P){if(typeof P!="number")throw new TypeError("End time must be set to a number.");g=P,this.hasBeenReset=!0}})),Object.defineProperty(d,"text",i({},h,{get:function(){return b},set:function(P){b=""+P,this.hasBeenReset=!0}})),Object.defineProperty(d,"region",i({},h,{get:function(){return y},set:function(P){y=P,this.hasBeenReset=!0}})),Object.defineProperty(d,"vertical",i({},h,{get:function(){return S},set:function(P){const D=n(P);if(D===!1)throw new SyntaxError("An invalid or illegal string was specified.");S=D,this.hasBeenReset=!0}})),Object.defineProperty(d,"snapToLines",i({},h,{get:function(){return E},set:function(P){E=!!P,this.hasBeenReset=!0}})),Object.defineProperty(d,"line",i({},h,{get:function(){return k},set:function(P){if(typeof P!="number"&&P!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");k=P,this.hasBeenReset=!0}})),Object.defineProperty(d,"lineAlign",i({},h,{get:function(){return T},set:function(P){const D=s(P);if(!D)throw new SyntaxError("An invalid or illegal string was specified.");T=D,this.hasBeenReset=!0}})),Object.defineProperty(d,"position",i({},h,{get:function(){return A},set:function(P){if(P<0||P>100)throw new Error("Position must be between 0 and 100.");A=P,this.hasBeenReset=!0}})),Object.defineProperty(d,"positionAlign",i({},h,{get:function(){return N},set:function(P){const D=s(P);if(!D)throw new SyntaxError("An invalid or illegal string was specified.");N=D,this.hasBeenReset=!0}})),Object.defineProperty(d,"size",i({},h,{get:function(){return C},set:function(P){if(P<0||P>100)throw new Error("Size must be between 0 and 100.");C=P,this.hasBeenReset=!0}})),Object.defineProperty(d,"align",i({},h,{get:function(){return M},set:function(P){const D=s(P);if(!D)throw new SyntaxError("An invalid or illegal string was specified.");M=D,this.hasBeenReset=!0}})),d.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a})(),s_=class{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}};function Sy(e){function t(n,s,i,a){return(n|0)*3600+(s|0)*60+(i|0)+parseFloat(a||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}var i_=class{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 Ey(e,t,r,n){const s=n?e.split(n):[e];for(const i in s){if(typeof s[i]!="string")continue;const a=s[i].split(r);if(a.length!==2)continue;const l=a[0],o=a[1];t(l,o)}}var lc=new Ru(0,0,""),ki=lc.align==="middle"?"middle":"center";function a_(e,t,r){const n=e;function s(){const l=Sy(e);if(l===null)throw new Error("Malformed timestamp: "+n);return e=e.replace(/^[^\sa-zA-Z-]+/,""),l}function i(l,o){const c=new i_;Ey(l,function(f,p){let m;switch(f){case"region":for(let g=r.length-1;g>=0;g--)if(r[g].id===p){c.set(f,r[g].region);break}break;case"vertical":c.alt(f,p,["rl","lr"]);break;case"line":m=p.split(","),c.integer(f,m[0]),c.percent(f,m[0])&&c.set("snapToLines",!1),c.alt(f,m[0],["auto"]),m.length===2&&c.alt("lineAlign",m[1],["start",ki,"end"]);break;case"position":m=p.split(","),c.percent(f,m[0]),m.length===2&&c.alt("positionAlign",m[1],["start",ki,"end","line-left","line-right","auto"]);break;case"size":c.percent(f,p);break;case"align":c.alt(f,p,["start",ki,"end","left","right"]);break}},/:/,/\s/),o.region=c.get("region",null),o.vertical=c.get("vertical","");let d=c.get("line","auto");d==="auto"&&lc.line===-1&&(d=-1),o.line=d,o.lineAlign=c.get("lineAlign","start"),o.snapToLines=c.get("snapToLines",!0),o.size=c.get("size",100),o.align=c.get("align",ki);let h=c.get("position","auto");h==="auto"&&lc.position===50&&(h=o.align==="start"||o.align==="left"?0:o.align==="end"||o.align==="right"?100:50),o.position=h}function a(){e=e.replace(/^\s+/,"")}if(a(),t.startTime=s(),a(),e.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+n);e=e.slice(3),a(),t.endTime=s(),a(),i(e,t)}function wy(e){return e.replace(/<br(?: \/)?>/gi,`
115
+ `)}var o_=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new s_,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function r(){let s=t.buffer,i=0;for(s=wy(s);i<s.length&&s[i]!=="\r"&&s[i]!==`
116
+ `;)++i;const a=s.slice(0,i);return s[i]==="\r"&&++i,s[i]===`
117
+ `&&++i,t.buffer=s.slice(i),a}function n(s){Ey(s,function(i,a){},/:/)}try{let s="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;s=r();const a=s.match(/^()?WEBVTT([ \t].*)?$/);if(!(a!=null&&a[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:s=r(),t.state){case"HEADER":/:/.test(s)?n(s):s||(t.state="ID");continue;case"NOTE":s||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(s)){t.state="NOTE";break}if(!s)continue;if(t.cue=new Ru(0,0,""),t.state="CUE",s.indexOf("-->")===-1){t.cue.id=s;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{a_(s,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const a=s.indexOf("-->")!==-1;if(!s||a&&(i=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
118
+ `),t.cue.text+=s}continue;case"BADCUE":s||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
119
+
120
+ `,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}},l_=/\r\n|\n\r|\n|\r/g,Wo=function(t,r,n=0){return t.slice(n,n+r.length)===r},c_=function(t){let r=parseInt(t.slice(-3));const n=parseInt(t.slice(-6,-4)),s=parseInt(t.slice(-9,-7)),i=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!he(r)||!he(n)||!he(s)||!he(i))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return r+=1e3*n,r+=60*1e3*s,r+=3600*1e3*i,r};function Mu(e,t,r){return Ns(e.toString())+Ns(t.toString())+Ns(r)}var u_=function(t,r,n){let s=t[r],i=t[s.prevCC];if(!i||!i.new&&s.new){t.ccOffset=t.presentationOffset=s.start,s.new=!1;return}for(;(a=i)!=null&&a.new;){var a;t.ccOffset+=s.start-i.start,s.new=!1,s=i,i=t[s.prevCC]}t.presentationOffset=n};function d_(e,t,r,n,s,i,a){const l=new o_,o=Bt(new Uint8Array(e)).trim().replace(l_,`
121
+ `).split(`
122
+ `),c=[],d=t?bP(t.baseTime,t.timescale):0;let h="00:00.000",f=0,p=0,m,g=!0;l.oncue=function(b){const y=r[n];let S=r.ccOffset;const E=(f-d)/9e4;if(y!=null&&y.new&&(p!==void 0?S=r.ccOffset=y.start:u_(r,n,E)),E){if(!t){m=new Error("Missing initPTS for VTT MPEGTS");return}S=E-r.presentationOffset}const k=b.endTime-b.startTime,T=_t((b.startTime+S-p)*9e4,s*9e4)/9e4;b.startTime=Math.max(T,0),b.endTime=Math.max(T+k,0);const A=b.text.trim();b.text=decodeURIComponent(encodeURIComponent(A)),b.id||(b.id=Mu(b.startTime,b.endTime,A)),b.endTime>0&&c.push(b)},l.onparsingerror=function(b){m=b},l.onflush=function(){if(m){a(m);return}i(c)},o.forEach(b=>{if(g)if(Wo(b,"X-TIMESTAMP-MAP=")){g=!1,b.slice(16).split(",").forEach(y=>{Wo(y,"LOCAL:")?h=y.slice(6):Wo(y,"MPEGTS:")&&(f=parseInt(y.slice(7)))});try{p=c_(h)/1e3}catch(y){m=y}return}else b===""&&(g=!1);l.parse(b+`
123
+ `)}),l.flush()}var Qo="stpp.ttml.im1t",ky=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Ty=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,h_={left:"start",center:"center",right:"end",start:"start",end:"end"};function Ef(e,t,r,n){const s=Pe(new Uint8Array(e),["mdat"]);if(s.length===0){n(new Error("Could not parse IMSC1 mdat"));return}const i=s.map(l=>Bt(l)),a=vP(t.baseTime,1,t.timescale);try{i.forEach(l=>r(f_(l,a)))}catch(l){n(l)}}function f_(e,t){const r=new DOMParser().parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");const n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},s=Object.keys(n).reduce((c,d)=>(c[d]=r.getAttribute(`ttp:${d}`)||n[d],c),{}),i=r.getAttribute("xml:space")!=="preserve",a=wf(qo(r,"styling","style")),l=wf(qo(r,"layout","region")),o=qo(r,"body","[begin]");return[].map.call(o,c=>{const d=Ay(c,i);if(!d||!c.hasAttribute("begin"))return null;const h=Xo(c.getAttribute("begin"),s),f=Xo(c.getAttribute("dur"),s);let p=Xo(c.getAttribute("end"),s);if(h===null)throw kf(c);if(p===null){if(f===null)throw kf(c);p=h+f}const m=new Ru(h-t,p-t,d);m.id=Mu(m.startTime,m.endTime,m.text);const g=l[c.getAttribute("region")],b=a[c.getAttribute("style")],y=p_(g,b,a),{textAlign:S}=y;if(S){const E=h_[S];E&&(m.lineAlign=E),m.align=S}return ze(m,y),m}).filter(c=>c!==null)}function qo(e,t,r){const n=e.getElementsByTagName(t)[0];return n?[].slice.call(n.querySelectorAll(r)):[]}function wf(e){return e.reduce((t,r)=>{const n=r.getAttribute("xml:id");return n&&(t[n]=r),t},{})}function Ay(e,t){return[].slice.call(e.childNodes).reduce((r,n,s)=>{var i;return n.nodeName==="br"&&s?r+`
124
+ `:(i=n.childNodes)!=null&&i.length?Ay(n,t):t?r+n.textContent.trim().replace(/\s+/g," "):r+n.textContent},"")}function p_(e,t,r){const n="http://www.w3.org/ns/ttml#styling";let s=null;const i=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=e!=null&&e.hasAttribute("style")?e.getAttribute("style"):null;return a&&r.hasOwnProperty(a)&&(s=r[a]),i.reduce((l,o)=>{const c=Yo(t,n,o)||Yo(e,n,o)||Yo(s,n,o);return c&&(l[o]=c),l},{})}function Yo(e,t,r){return e&&e.hasAttributeNS(t,r)?e.getAttributeNS(t,r):null}function kf(e){return new Error(`Could not parse ttml timestamp ${e}`)}function Xo(e,t){if(!e)return null;let r=Sy(e);return r===null&&(ky.test(e)?r=m_(e,t):Ty.test(e)&&(r=g_(e,t))),r}function m_(e,t){const r=ky.exec(e),n=(r[4]|0)+(r[5]|0)/t.subFrameRate;return(r[1]|0)*3600+(r[2]|0)*60+(r[3]|0)+n/t.frameRate}function g_(e,t){const r=Ty.exec(e),n=Number(r[1]);switch(r[2]){case"h":return n*3600;case"m":return n*60;case"ms":return n*1e3;case"f":return n/t.frameRate;case"t":return n/t.tickRate}return n}var Ti=class{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(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,r){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},v_=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=Af(),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(w.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(w.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(w.FRAG_LOADING,this.onFragLoading,this),e.on(w.FRAG_LOADED,this.onFragLoaded,this),e.on(w.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(w.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(w.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(w.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(w.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(w.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(w.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(w.FRAG_LOADING,this.onFragLoading,this),e.off(w.FRAG_LOADED,this.onFragLoaded,this),e.off(w.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(w.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(w.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(w.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(w.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new Ti(this,"textTrack1"),t=new Ti(this,"textTrack2"),r=new Ti(this,"textTrack3"),n=new Ti(this,"textTrack4");this.cea608Parser1=new Sf(1,e,t),this.cea608Parser2=new Sf(3,r,n)}addCues(e,t,r,n,s){let i=!1;for(let a=s.length;a--;){const l=s[a],o=b_(l[0],l[1],t,r);if(o>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],r),i=!0,o/(r-t)>.5))return}if(i||s.push([t,r]),this.config.renderTextTracksNatively){const a=this.captionsTracks[e];this.Cues.newCue(a,t,r,n)}else{const a=this.Cues.newCue(null,t,r,n);this.hls.trigger(w.CUES_PARSED,{type:"captions",cues:a,track:e})}}onInitPtsFound(e,{frag:t,id:r,initPTS:n,timescale:s,trackId:i}){const{unparsedVttFrags:a}=this;r===fe.MAIN&&(this.initPTS[t.cc]={baseTime:n,timescale:s,trackId:i}),a.length&&(this.unparsedVttFrags=[],a.forEach(l=>{this.initPTS[l.frag.cc]?this.onFragLoaded(w.FRAG_LOADED,l):this.hls.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:l.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 s=r.textTracks[n];if(Tf(s,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return s}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:r,media:n}=this,{label:s,languageCode:i}=t[e],a=this.getExistingTrack(s,i);if(a)r[e]=a,$n(r[e]),gy(r[e],n);else{const l=this.createTextTrack("captions",s,i);l&&(l[e]=!0,r[e]=l)}}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:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(w.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(s=>{$n(n[s]),delete n[s]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Af(),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 r=0;r<t.length;r++)$n(t[r])}onSubtitleTracksUpdated(e,t){const r=t.subtitleTracks||[],n=r.some(s=>s.textCodec===Qo);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(ty(this.tracks,r)){this.tracks=r;return}if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){const s=this.media,i=s?Yi(s.textTracks):null;if(this.tracks.forEach((a,l)=>{let o;if(i){let c=null;for(let d=0;d<i.length;d++)if(i[d]&&Tf(i[d],a)){c=i[d],i[d]=null;break}c&&(o=c)}if(o)$n(o);else{const c=Cy(a);o=this.createTextTrack(c,a.name,a.lang),o&&(o.mode="disabled")}o&&this.textTracks.push(o)}),i!=null&&i.length){const a=i.filter(l=>l!==null).map(l=>l.label);a.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${a.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const s=this.tracks.map(i=>({label:i.name,kind:i.type.toLowerCase(),default:i.default,subtitleTrack:i}));this.hls.trigger(w.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:s})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(r=>{const n=/(?:CC|SERVICE)([1-4])/.exec(r.instreamId);if(!n)return;const s=`textTrack${n[1]}`,i=this.captionsProperties[s];i&&(i.label=r.name,r.lang&&(i.languageCode=r.lang),i.media=r)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===fe.MAIN){var r,n;const{cea608Parser1:s,cea608Parser2:i,lastSn:a}=this,{cc:l,sn:o}=t.frag,c=(r=(n=t.part)==null?void 0:n.index)!=null?r:-1;s&&i&&(o!==a+1||o===a&&c!==this.lastPartIndex+1||l!==this.lastCc)&&(s.reset(),i.reset()),this.lastCc=l,this.lastSn=o,this.lastPartIndex=c}}onFragLoaded(e,t){const{frag:r,payload:n}=t;if(r.type===fe.SUBTITLE)if(n.byteLength){const s=r.decryptdata,i="stats"in t;if(s==null||!s.encrypted||i){const a=this.tracks[r.level],l=this.vttCCs;l[r.cc]||(l[r.cc]={start:r.start,prevCC:this.prevCC,new:!0},this.prevCC=r.cc),a&&a.textCodec===Qo?this._parseIMSC1(r,n):this._parseVTTs(t)}}else this.hls.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const r=this.hls;Ef(t,this.initPTS[e.cc],n=>{this._appendCues(n,e.level),r.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},n=>{r.logger.log(`Failed to parse IMSC1: ${n}`),r.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:n})})}_parseVTTs(e){var t;const{frag:r,payload:n}=e,{initPTS:s,unparsedVttFrags:i}=this,a=s.length-1;if(!s[r.cc]&&a===-1){i.push(e);return}const l=this.hls;d_((t=r.initSegment)!=null&&t.data?Wt(r.initSegment.data,new Uint8Array(n)).buffer:n,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,o=>{this._appendCues(o,r.level),l.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})},o=>{const c=o.message==="Missing initPTS for VTT MPEGTS";c?i.push(e):this._fallbackToIMSC1(r,n),l.logger.log(`Failed to parse VTT cue: ${o}`),!(c&&a>r.cc)&&l.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:o})})}_fallbackToIMSC1(e,t){const r=this.tracks[e.level];r.textCodec||Ef(t,this.initPTS[e.cc],()=>{r.textCodec=Qo,this._parseIMSC1(e,t)},()=>{r.textCodec="wvtt"})}_appendCues(e,t){const r=this.hls;if(this.config.renderTextTracksNatively){const n=this.textTracks[t];if(!n||n.mode==="disabled")return;e.forEach(s=>vy(n,s))}else{const n=this.tracks[t];if(!n)return;const s=n.default?"default":"subtitles"+t;r.trigger(w.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,t){const{frag:r}=t;r.type===fe.SUBTITLE&&this.onFragLoaded(w.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===fe.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let s=0;s<n.length;s++){const i=n[s].bytes;if(i){this.cea608Parser1||this.initCea608Parsers();const a=this.extractCea608Data(i);this.cea608Parser1.addData(n[s].pts,a[0]),this.cea608Parser2.addData(n[s].pts,a[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:r,endOffsetSubtitles:n,type:s}){const{media:i}=this;if(!(!i||i.currentTime<r)){if(!s||s==="video"){const{captionsTracks:a}=this;Object.keys(a).forEach(l=>oc(a[l],t,r))}if(this.config.renderTextTracksNatively&&t===0&&n!==void 0){const{textTracks:a}=this;Object.keys(a).forEach(l=>oc(a[l],t,n))}}}extractCea608Data(e){const t=[[],[]],r=e[0]&31;let n=2;for(let s=0;s<r;s++){const i=e[n++],a=127&e[n++],l=127&e[n++];if(!(a===0&&l===0)&&(4&i)!==0){const o=3&i;(o===0||o===1)&&(t[o].push(a),t[o].push(l))}}return t}};function Cy(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function Tf(e,t){return!!e&&e.kind===Cy(t)&&rc(t,e)}function b_(e,t,r,n){return Math.min(t,n)-Math.max(e,r)}function Af(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var y_=/\s/,x_={newCue(e,t,r,n){const s=[];let i,a,l,o,c;const d=self.VTTCue||self.TextTrackCue;for(let f=0;f<n.rows.length;f++)if(i=n.rows[f],l=!0,o=0,c="",!i.isEmpty()){var h;for(let g=0;g<i.chars.length;g++)y_.test(i.chars[g].uchar)&&l?o++:(c+=i.chars[g].uchar,l=!1);i.cueStartTime=t,t===r&&(r+=1e-4),o>=16?o--:o++;const p=wy(c.trim()),m=Mu(t,r,p);e!=null&&(h=e.cues)!=null&&h.getCueById(m)||(a=new d(t,r,p),a.id=m,a.line=f+1,a.align="left",a.position=10+Math.min(80,Math.floor(o*8/32)*10),s.push(a))}return e&&s.length&&(s.sort((f,p)=>f.line==="auto"||p.line==="auto"?0:f.line>8&&p.line>8?p.line-f.line:f.line-p.line),s.forEach(f=>vy(e,f))),s}};function S_(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var E_=/(\d+)-(\d+)\/(\d+)/,Cf=class{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||A_,this.controller=new self.AbortController,this.stats=new du}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,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 s=w_(e,this.controller.signal),i=e.responseType==="arraybuffer",a=i?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:o}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=r,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=l&&he(l)?l:o,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},t.timeout),(Qs(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(c=>{var d;this.response=this.loader=c;const h=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=o,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},o-(h-n.loading.start)),!c.ok){const{status:p,statusText:m}=c;throw new C_(m||"fetch, bad network response",p,c)}n.loading.first=h,n.total=T_(c.headers)||n.total;const f=(d=this.callbacks)==null?void 0:d.onProgress;return f&&he(t.highWaterMark)?this.loadProgressively(c,n,e,t.highWaterMark,f):i?c.arrayBuffer():e.responseType==="json"?c.json():c.text()}).then(c=>{var d,h;const f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const p=c[a];p&&(n.loaded=n.total=p);const m={url:f.url,data:c,code:f.status},g=(d=this.callbacks)==null?void 0:d.onProgress;g&&!he(t.highWaterMark)&&g(n,e,c,f),(h=this.callbacks)==null||h.onSuccess(m,n,e,f)}).catch(c=>{var d;if(self.clearTimeout(this.requestTimeout),n.aborted)return;const h=c&&c.code||0,f=c?c.message:null;(d=this.callbacks)==null||d.onError({code:h,text:f},e,c?c.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,s){const i=new _b,a=e.body.getReader(),l=()=>a.read().then(o=>{if(o.done)return i.dataLength&&s(t,r,i.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const c=o.value,d=c.length;return t.loaded+=d,d<n||i.dataLength?(i.push(c),i.dataLength>=n&&s(t,r,i.flush().buffer,e)):s(t,r,c.buffer,e),l()}).catch(()=>Promise.reject());return l()}};function w_(e,t){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(ze({},e.headers))};return e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),r}function k_(e){const t=E_.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}function T_(e){const t=e.get("Content-Range");if(t){const n=k_(t);if(he(n))return n}const r=e.get("Content-Length");if(r)return parseInt(r)}function A_(e,t){return new self.Request(e.url,t)}var C_=class extends Error{constructor(e,t,r){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=r}},N_=/^age:\s*[\d.]+\s*$/im,Ny=class{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 du,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,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 s=this.xhrSetup;s?Promise.resolve().then(()=>{if(!(this.loader!==r||this.stats.aborted))return s(r,t.url)}).catch(i=>{if(!(this.loader!==r||this.stats.aborted))return r.open("GET",t.url,!0),s(r,t.url)}).then(()=>{this.loader!==r||this.stats.aborted||this.openAndSendXhr(r,t,e)}).catch(i=>{var a;(a=this.callbacks)==null||a.onError({code:r.status,text:i.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:s,maxLoadTimeMs:i}=r.loadPolicy;if(n)for(const a in n)e.setRequestHeader(a,n[a]);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=s&&he(s)?s:i,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,s=this.config;if(!r.aborted&&n>=2&&(r.loading.first===0&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),n===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const o=t.status,c=t.responseType==="text"?t.responseText:null;if(o>=200&&o<300){const f=c??t.response;if(f!=null){var i,a;r.loading.end=Math.max(self.performance.now(),r.loading.first),r.loaded=r.total=t.responseType==="arraybuffer"?f.byteLength:f.length,r.bwEstimate=r.total*8e3/(r.loading.end-r.loading.first);const p=(i=this.callbacks)==null?void 0:i.onProgress;p&&p(r,e,f,t);const m={url:t.responseURL,data:f,code:o};(a=this.callbacks)==null||a.onSuccess(m,r,e,t);return}}const d=s.loadPolicy.errorRetry,h=r.retry;if(ya(d,h,!1,{url:e.url,data:void 0,code:o}))this.retry(d);else{var l;Ke.error(`${o} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:o,text:t.statusText},e,t,r)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(ya(e,t,!0))this.retry(e);else{var r;Ke.warn(`timeout while loading ${(r=this.context)==null?void 0:r.url}`);const n=this.callbacks;n&&(this.abortInternal(),n.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:r}=this;this.retryDelay=mu(e,r.retry),r.retry++,Ke.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${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&&N_.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}},L_=je(je({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:Ny,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:VR,bufferController:PP,capLevelController:_P,errorController:QR,fpsController:PD,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:kb,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},I_()),{},{subtitleStreamController:KD,subtitleTrackController:OD,timelineController:v_,audioStreamController:LP,audioTrackController:IP,emeController:my,cmcdController:LD,contentSteeringController:RD,interstitialsController:jD});function I_(){return{cueHandler:x_,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function R_(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(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const n=cc(e),s=["manifest","level","frag"],i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return s.forEach(a=>{const l=`${a==="level"?"playlist":a}LoadPolicy`,o=t[l]===void 0,c=[];i.forEach(d=>{const h=`${a}Loading${d}`,f=t[h];if(f!==void 0&&o){c.push(h);const p=n[l].default;switch(t[l]={default:p},d){case"TimeOut":p.maxLoadTimeMs=f,p.maxTimeToFirstByteMs=f;break;case"MaxRetry":p.errorRetry.maxNumRetry=f,p.timeoutRetry.maxNumRetry=f;break;case"RetryDelay":p.errorRetry.retryDelayMs=f,p.timeoutRetry.retryDelayMs=f;break;case"MaxRetryTimeout":p.errorRetry.maxRetryDelayMs=f,p.timeoutRetry.maxRetryDelayMs=f;break}}}),c.length&&r.warn(`hls.js config: "${c.join('", "')}" setting(s) are deprecated, use "${l}": ${qe(t[l])}`)}),je(je({},n),t)}function cc(e){return e&&typeof e=="object"?Array.isArray(e)?e.map(cc):Object.keys(e).reduce((t,r)=>(t[r]=cc(e[r]),t),{}):e}function M_(e,t){const r=e.loader;r!==Cf&&r!==Ny?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):S_()&&(e.loader=Cf,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}var Xi=2,P_=.1,D_=.05,__=100,O_=class extends bb{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 r;(r=this.media)!=null&&r.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var r;this.ended=((r=this.media)==null?void 0:r.currentTime)||1,this.hls.trigger(w.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(w.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(w.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(__),this.mediaSource=t.mediaSource;const r=this.media=t.media;Lt(r,"playing",this.onMediaPlaying),Lt(r,"waiting",this.onMediaWaiting),Lt(r,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:r}=this;r&&(Mt(r,"playing",this.onMediaPlaying),Mt(r,"waiting",this.onMediaWaiting),Mt(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(!((e=this.media)!=null&&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 s=(r=this.hls)==null?void 0:r.config;if(!s)return;const i=this.media;if(!i)return;const{seeking:a}=i,l=this.seeking&&!a,o=!this.seeking&&a,c=i.paused&&!a||i.ended||i.playbackRate===0;if(this.seeking=a,e!==t){t&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,s.nudgeOnVideoHole&&!c&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(o||l){l&&this.stallResolved(e);return}if(c){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&i.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(w.MEDIA_ENDED,{stalled:!1}));return}if(!De.getBuffered(i).length){this.nudgeRetry=0;return}const d=De.bufferInfo(i,e,0),h=d.nextStart||0,f=this.fragmentTracker;if(a&&f&&this.hls){const T=Nf(this.hls.inFlightFragments,e),A=d.len>Xi,N=!h||T||h-e>Xi&&!f.getPartialFragment(e);if(A||N)return;this.moved=!1}const p=(n=this.hls)==null?void 0:n.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(d.len>0)&&!h)return;const T=Math.max(h,d.start||0)-e,A=p!=null&&p.live?p.targetduration*2:Xi,N=Ai(e,f);if(T>0&&(T<=A||N)){i.paused||this._trySkipBufferHole(N);return}}const m=s.detectStallWithCurrentTimeMs,g=self.performance.now(),b=this.waiting;let y=this.stalled;if(y===null)if(b>0&&g-b<m)y=this.stalled=b;else{this.stalled=g;return}const S=g-y;if(!a&&(S>=m||b)&&this.hls){var E;if(((E=this.mediaSource)==null?void 0:E.readyState)==="ended"&&!(p!=null&&p.live)&&Math.abs(e-(p?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(w.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(d),!this.media||!this.hls)return}const k=De.bufferInfo(i,e,s.maxBufferHole);this._tryFixBufferStall(k,S,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(w.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var r;const n=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(r=this.buffered.audio)!=null&&r.length&&n&&n.length>1&&e>n.end(0)){const s=De.bufferedInfo(De.timeRangesToArray(this.buffered.audio),e,0);if(s.len>1&&t>=s.start){const i=De.timeRangesToArray(n),a=De.bufferedInfo(i,t,0).bufferedIndex;if(a>-1&&a<i.length-1){const l=De.bufferedInfo(i,e,0).bufferedIndex,o=i[a].end,c=i[a+1].start;if((l===-1||l>a)&&c-o<1&&e-o<2){const d=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${o} -> ${c} buffered index: ${l}`);this.warn(d.message),this.media.currentTime+=1e-6;let h=Ai(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);const f=De.bufferInfo(this.media,e,0);this.hls.trigger(w.ERROR,{type:xe.MEDIA_ERROR,details:G.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:h,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,r){var n,s;const{fragmentTracker:i,media:a}=this,l=(n=this.hls)==null?void 0:n.config;if(!a||!i||!l)return;const o=(s=this.hls)==null?void 0:s.latestLevelDetails,c=Ai(r,i);if((c||o!=null&&o.live&&r<o.fragmentStart)&&(this._trySkipBufferHole(c)||!this.media))return;const d=e.buffered,h=this.adjacentTraversal(e,r);(d&&d.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-r<l.maxBufferHole||h))&&(t>l.highBufferWatchdogPeriod*1e3||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 s=r.getFragAtPos(t,fe.MAIN),i=r.getFragAtPos(n,fe.MAIN);if(s&&i)return i.sn-s.sn<2}return!1}_reportStall(e){const{hls:t,media:r,stallReported:n,stalled:s}=this;if(!n&&s!==null&&r&&t){this.stallReported=!0;const i=new Error(`Playback stalling at @${r.currentTime} due to low buffer (${qe(e)})`);this.warn(i.message),t.trigger(w.ERROR,{type:xe.MEDIA_ERROR,details:G.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:e.len,bufferInfo:e,stalled:{start:s}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:r,media:n}=this,s=(t=this.hls)==null?void 0:t.config;if(!n||!r||!s)return 0;const i=n.currentTime,a=De.bufferInfo(n,i,0),l=i<a.start?a.start:a.nextStart;if(l&&this.hls){const c=a.len<=s.maxBufferHole,d=a.len>0&&a.len<1&&n.readyState<3,h=l-i;if(h>0&&(c||d)){if(h>s.maxBufferHole){let p=!1;if(i===0){const m=r.getAppendedFrag(0,fe.MAIN);m&&l<m.end&&(p=!0)}if(!p&&e){var o;if(!((o=this.hls.loadLevelObj)!=null&&o.details)||Nf(this.hls.inFlightFragments,l))return 0;let m=!1,g=e.end;for(;g<l;){const b=Ai(g,r);if(b)g+=b.duration;else{m=!0;break}}if(m)return 0}}const f=Math.max(l+D_,i+P_);if(this.warn(`skipping hole, adjusting currentTime from ${i} to ${f}`),this.moved=!0,n.currentTime=f,!(e!=null&&e.gap)){const p=new Error(`fragment loaded with buffer holes, seeking from ${i} to ${f}`),m={type:xe.MEDIA_ERROR,details:G.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:p,reason:p.message,buffer:a.len,bufferInfo:a};e&&("fragment"in e?m.part=e:m.frag=e),this.hls.trigger(w.ERROR,m)}return f}}return 0}_tryNudgeBuffer(e){const{hls:t,media:r,nudgeRetry:n}=this,s=t?.config;if(!r||!s)return 0;const i=r.currentTime;if(this.nudgeRetry++,n<s.nudgeMaxRetry){const a=i+(n+1)*s.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${i} to ${a}`);this.warn(l.message),r.currentTime=a,t.trigger(w.ERROR,{type:xe.MEDIA_ERROR,details:G.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:e.len,bufferInfo:e})}else{const a=new Error(`Playhead still not moving while enough data buffered @${i} after ${s.nudgeMaxRetry} nudges`);this.error(a.message),t.trigger(w.ERROR,{type:xe.MEDIA_ERROR,details:G.BUFFER_STALLED_ERROR,error:a,fatal:!0,buffer:e.len,bufferInfo:e})}}};function Nf(e,t){const r=Lf(e.main);if(r&&r.start<=t)return r;const n=Lf(e.audio);return n&&n.start<=t?n:null}function Lf(e){if(!e)return null;switch(e.state){case X.IDLE:case X.STOPPED:case X.ENDED:case X.ERROR:return null}return e.frag}function Ai(e,t){return t.getAppendedFrag(e,fe.MAIN)||t.getPartialFragment(e)}var F_=.25;function uc(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Zo(e,t,r,n,s){let i=new e(t,r,"");try{i.value=n,s&&(i.type=s)}catch{i=new e(t,r,qe(s?je({type:s},n):n))}return i}var Ci=(()=>{const e=uc();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),$_=class{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(w.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(w.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(w.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(w.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(w.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(w.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(w.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(w.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(w.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var r;this.media=t.media,((r=t.overrides)==null?void 0:r.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&$n(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(r.kind==="metadata"&&r.label==="id3")return gy(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:s}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const i=uc();if(i)for(let a=0;a<s.length;a++){const l=s[a].type;if(l===Ot.emsg&&!r||!n)continue;const o=Hb(s[a].data),c=s[a].pts;let d=c+s[a].duration;d>Ci&&(d=Ci),d-c<=0&&(d=c+F_);for(let h=0;h<o.length;h++){const f=o[h];if(!Vb(f)){this.updateId3CueEnds(c,l);const p=Zo(i,c,d,f,l);p&&this.id3Track.addCue(p)}}}}updateId3CueEnds(e,t){var r;const n=(r=this.id3Track)==null?void 0:r.cues;if(n)for(let s=n.length;s--;){const i=n[s];i.type===t&&i.startTime<e&&i.endTime===Ci&&(i.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:r,type:n}){const{id3Track:s,hls:i}=this;if(!i)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:l}}=i;if(s&&(a||l)){let o;n==="audio"?o=c=>c.type===Ot.audioId3&&l:n==="video"?o=c=>c.type===Ot.emsg&&a:o=c=>c.type===Ot.audioId3&&l||c.type===Ot.emsg&&a,oc(s,t,r,o)}}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:s,interstitialsController:i}=this.hls.config;if(!s)return;const a=uc();if(r&&n&&!i){const{fragmentStart:m,fragmentEnd:g}=e;let b=this.assetCue;b?(b.startTime=m,b.endTime=g):a&&(b=this.assetCue=Zo(a,m,g,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),b&&(b.id=r,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(b),b.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:l}=this,{dateRanges:o}=e,c=Object.keys(o);let d=this.dateRangeCuesAppended;if(l&&t){var h;if((h=l.cues)!=null&&h.length){const m=Object.keys(d).filter(g=>!c.includes(g));for(let g=m.length;g--;){var f;const b=m[g],y=(f=d[b])==null?void 0:f.cues;delete d[b],y&&Object.keys(y).forEach(S=>{const E=y[S];if(E){E.removeEventListener("enter",this.onEventCueEnter);try{l.removeCue(E)}catch{}}})}}else d=this.dateRangeCuesAppended={}}const p=e.fragments[e.fragments.length-1];if(!(c.length===0||!he(p?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let m=0;m<c.length;m++){const g=c[m],b=o[g],y=b.startTime,S=d[g],E=S?.cues||{};let k=S?.durationKnown||!1,T=Ci;const{duration:A,endDate:N}=b;if(N&&A!==null)T=y+A,k=!0;else if(b.endOnNext&&!k){const M=c.reduce((P,D)=>{if(D!==b.id){const $=o[D];if($.class===b.class&&$.startDate>b.startDate&&(!P||b.startDate<P.startDate))return $}return P},null);M&&(T=M.startTime,k=!0)}const C=Object.keys(b.attr);for(let M=0;M<C.length;M++){const P=C[M];if(!oM(P))continue;const D=E[P];if(D)k&&!(S!=null&&S.durationKnown)?D.endTime=T:Math.abs(D.startTime-y)>.01&&(D.startTime=y,D.endTime=T);else if(a){let $=b.attr[P];lM(P)&&($=Zv($));const B=Zo(a,y,T,{key:P,data:$},Ot.dateRange);B&&(B.id=g,this.id3Track.addCue(B),E[P]=B,i&&(P==="X-ASSET-LIST"||P==="X-ASSET-URL")&&B.addEventListener("enter",this.onEventCueEnter))}}d[g]={cues:E,dateRange:b,durationKnown:k}}}}},B_=class{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:t}=this,r=this.levelDetails;if(!t||!r)return;this.currentTime=t.currentTime;const n=this.computeLatency();if(n===null)return;this._latency=n;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:i}=this.config;if(!s||i===1||!r.live)return;const a=this.targetLatency;if(a===null)return;const l=n-a;if(l<Math.min(this.maxLatency,a+r.targetduration)&&l>.05&&this.forwardBufferLength>1){const o=Math.min(2,Math.max(1,i)),c=Math.round(2/(1+Math.exp(-.75*l-this.edgeStalled))*20)/20,d=Math.min(o,Math.max(1,c));this.changeMediaPlaybackRate(t,d)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:r,targetduration:n}=e,{liveSyncDuration:s,liveSyncDurationCount:i,lowLatencyMode:a}=this.config,l=this.hls.userConfig;let o=a&&r||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||o===0)&&(o=s!==void 0?s:i*n);const c=n;return o+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,c)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const r=this.levelDetails;if(r===null)return null;const n=r.edge,s=e-t-this.edgeStalled,i=n-r.totalduration,a=n-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(i,s),a)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;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(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(w.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(w.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===G.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(r=this.levelDetails)!=null&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var r,n;e.playbackRate!==t&&((r=this.hls)==null||r.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(n=this.targetLatency)==null?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 e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}},U_=class extends Nu{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(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(w.LEVEL_LOADED,this.onLevelLoaded,this),e.on(w.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(w.FRAG_BUFFERED,this.onFragBuffered,this),e.on(w.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(w.LEVEL_LOADED,this.onLevelLoaded,this),e.off(w.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(w.FRAG_BUFFERED,this.onFragBuffered,this),e.off(w.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=[],s={},i={};let a=!1,l=!1,o=!1;t.levels.forEach(c=>{const d=c.attrs;let{audioCodec:h,videoCodec:f}=c;h&&(c.audioCodec=h=ma(h,r)||void 0),f&&(f=c.videoCodec=kR(f));const{width:p,height:m,unknownCodecs:g}=c,b=g?.length||0;if(a||(a=!!(p&&m)),l||(l=!!f),o||(o=!!h),b||h&&!this.isAudioSupported(h)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${d.CODECS}"`);return}const{CODECS:y,"FRAME-RATE":S,"HDCP-LEVEL":E,"PATHWAY-ID":k,RESOLUTION:T,"VIDEO-RANGE":A}=d,N=`${`${k||"."}-`}${c.bitrate}-${T}-${S}-${y}-${A}-${E}`;if(s[N])if(s[N].uri!==c.url&&!c.attrs["PATHWAY-ID"]){const C=i[N]+=1;c.attrs["PATHWAY-ID"]=new Array(C+1).join(".");const M=this.createLevel(c);s[N]=M,n.push(M)}else s[N].addGroupId("audio",d.AUDIO),s[N].addGroupId("text",d.SUBTITLES);else{const C=this.createLevel(c);s[N]=C,i[N]=1,n.push(C)}}),this.filterAndSortMediaOptions(n,t,a,l,o)}createLevel(e){const t=new Ks(e),r=e.supplemental;if(r!=null&&r.videoCodec&&!this.isVideoSupported(r.videoCodec)){const n=new Error(`SUPPLEMENTAL-CODECS not supported "${r.videoCodec}"`);this.log(n.message),t.supportedResult=ub(n,[])}return t}isAudioSupported(e){return Vs(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Vs(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,r,n,s){var i;let a=[],l=[],o=e;const c=((i=t.stats)==null?void 0:i.parsing)||{};if((r||n)&&s&&(o=o.filter(({videoCodec:y,videoRange:S,width:E,height:k})=>(!!y||!!(E&&k))&&DR(S))),o.length===0){Promise.resolve().then(()=>{if(this.hls){let y="no level with compatible codecs found in manifest",S=y;t.levels.length&&(S=`one or more CODECS in variant not supported: ${qe(t.levels.map(k=>k.attrs.CODECS).filter((k,T,A)=>A.indexOf(k)===T))}`,this.warn(S),y+=` (${S})`);const E=new Error(y);this.hls.trigger(w.ERROR,{type:xe.MEDIA_ERROR,details:G.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:E,reason:S})}}),c.end=performance.now();return}t.audioTracks&&(a=t.audioTracks.filter(y=>!y.audioCodec||this.isAudioSupported(y.audioCodec)),If(a)),t.subtitles&&(l=t.subtitles,If(l));const d=o.slice(0);o.sort((y,S)=>{if(y.attrs["HDCP-LEVEL"]!==S.attrs["HDCP-LEVEL"])return(y.attrs["HDCP-LEVEL"]||"")>(S.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&y.height!==S.height)return y.height-S.height;if(y.frameRate!==S.frameRate)return y.frameRate-S.frameRate;if(y.videoRange!==S.videoRange)return ga.indexOf(y.videoRange)-ga.indexOf(S.videoRange);if(y.videoCodec!==S.videoCodec){const E=xh(y.videoCodec),k=xh(S.videoCodec);if(E!==k)return k-E}if(y.uri===S.uri&&y.codecSet!==S.codecSet){const E=pa(y.codecSet),k=pa(S.codecSet);if(E!==k)return k-E}return y.averageBitrate!==S.averageBitrate?y.averageBitrate-S.averageBitrate:0});let h=d[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==d.length)){for(let y=0;y<d.length;y++)if(d[y].pathwayId===o[0].pathwayId){h=d[y];break}}this._levels=o;for(let y=0;y<o.length;y++)if(o[y]===h){var f;this._firstLevel=y;const S=h.bitrate,E=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${o.length} level(s) found, first bitrate: ${S}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){const k=Math.min(S,this.hls.config.abrEwmaDefaultEstimateMax);k>E&&E===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=k)}break}const p=s&&!n,m=this.hls.config,g=!!(m.audioStreamController&&m.audioTrackController),b={levels:o,audioTracks:a,subtitleTracks:l,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:s,video:n,altAudio:g&&!p&&a.some(y=>!!y.url)};c.end=performance.now(),this.hls.trigger(w.MANIFEST_PARSED,b)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const c=new Error("invalid level idx"),d=e<0;if(this.hls.trigger(w.ERROR,{type:xe.OTHER_ERROR,details:G.LEVEL_SWITCH_ERROR,level:e,fatal:d,error:c,reason:c.message}),d)return;e=Math.min(e,t.length-1)}const r=this.currentLevelIndex,n=this.currentLevel,s=n?n.attrs["PATHWAY-ID"]:void 0,i=t[e],a=i.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=i,r===e&&n&&s===a)return;this.log(`Switching to level ${e} (${i.height?i.height+"p ":""}${i.videoRange?i.videoRange+" ":""}${i.codecSet?i.codecSet+" ":""}@${i.bitrate})${a?" with Pathway "+a:""} from level ${r}${s?" with Pathway "+s:""}`);const l={level:e,attrs:i.attrs,details:i.details,bitrate:i.bitrate,averageBitrate:i.averageBitrate,maxBitrate:i.maxBitrate,realBitrate:i.realBitrate,width:i.width,height:i.height,codecSet:i.codecSet,audioCodec:i.audioCodec,videoCodec:i.videoCodec,audioGroups:i.audioGroups,subtitleGroups:i.subtitleGroups,loaded:i.loaded,loadError:i.loadError,fragmentError:i.fragmentError,name:i.name,id:i.id,uri:i.uri,url:i.url,urlId:0,audioGroupIds:i.audioGroupIds,textGroupIds:i.textGroupIds};this.hls.trigger(w.LEVEL_SWITCHING,l);const o=i.details;if(!o||o.live){const c=this.switchParams(i.uri,n?.details,o);this.loadPlaylist(c)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),r=e.filter(n=>t.indexOf(n)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=r}}onError(e,t){t.fatal||!t.context||t.context.type===Fe.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===fe.MAIN){const r=t.elementaryStreams;if(!Object.keys(r).some(s=>!!r[s]))return;const n=this._levels[t.level];n!=null&&n.loadError&&(this.log(`Resetting level error count of ${n.loadError} on frag buffered`),n.loadError=0)}}onLevelLoaded(e,t){var r;const{level:n,details:s}=t,i=t.levelInfo;if(!i){var a;this.warn(`Invalid level index ${n}`),(a=t.deliveryDirectives)!=null&&a.skip&&(s.deltaUpdateFailed=!0);return}if(i===this.currentLevel||t.withoutMultiVariant){i.fragmentError===0&&(i.loadError=0);let l=i.details;l===t.details&&l.advanced&&(l=void 0),this.playlistLoaded(n,t,l)}else(r=t.deliveryDirectives)!=null&&r.skip&&(s.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,s=e.attrs["PATHWAY-ID"],i=e.details,a=i?.age;this.log(`Loading level index ${n}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${s?" Pathway "+s:""}${a&&i.live?" age "+a.toFixed(1)+(i.type&&" "+i.type||""):""} ${r}`),this.hls.trigger(w.LEVEL_LOADING,{url:r,level:n,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const r=this._levels.filter((s,i)=>i!==e?!0:(this.steering&&this.steering.removeLevel(s),s===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,s.details&&s.details.fragments.forEach(a=>a.level=-1)),!1));Mb(r),this._levels=r,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&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(w.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(w.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}};function If(e){const t={};e.forEach(r=>{const n=r.groupId||"";r.id=t[n]=t[n]||0,t[n]++})}function Ly(){return self.SourceBuffer||self.WebKitSourceBuffer}function Iy(){if(!Vr())return!1;const e=Ly();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function G_(){if(!Iy())return!1;const e=Vr();return typeof e?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>e.isTypeSupported(js(t,"video")))||["mp4a.40.2","fLaC"].some(t=>e.isTypeSupported(js(t,"audio"))))}function H_(){var e;const t=Ly();return typeof(t==null||(e=t.prototype)==null?void 0:e.changeType)=="function"}var V_=100,j_=class extends xu{constructor(e,t,r){super(e,t,r,"stream-controller",fe.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const n=this.media,s=n?n.currentTime:null;if(s===null||!he(s)||(this.log(`Media seeked to ${s.toFixed(3)}`),!this.getBufferedFrag(s)))return;const i=this.getFwdBufferInfoAtPos(n,s,fe.MAIN,0);if(i===null||i.len===0){this.warn(`Main forward buffer length at ${s} on "seeked" event ${i?i.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(w.MANIFEST_PARSED,this.onManifestParsed,this),e.on(w.LEVEL_LOADING,this.onLevelLoading,this),e.on(w.LEVEL_LOADED,this.onLevelLoaded,this),e.on(w.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(w.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(w.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(w.BUFFER_CREATED,this.onBufferCreated,this),e.on(w.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(w.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(w.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(w.MANIFEST_PARSED,this.onManifestParsed,this),e.off(w.LEVEL_LOADED,this.onLevelLoaded,this),e.off(w.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(w.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(w.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(w.BUFFER_CREATED,this.onBufferCreated,this),e.off(w.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(w.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(w.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(V_),this.level=-1,!this.startFragRequested){let s=n.startLevel;s===-1&&(n.config.testBandwidth&&this.levels.length>1?(s=0,this.bitrateTest=!0):s=n.firstAutoLevel),n.nextLoadLevel=s,this.level=n.loadLevel,this._hasEnoughToStart=!!t}r>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r),this.state=X.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=X.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case X.WAITING_LEVEL:{const{levels:e,level:t}=this,r=e?.[t],n=r?.details;if(n&&(!n.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(n))break;this.state=X.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=X.IDLE;break}break}case X.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===X.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:r,media:n}=this;if(t===null||!n&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const s=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(r!=null&&r[s]))return;const i=r[s],a=this.getMainFwdBufferInfo();if(a===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(a,l)){const m={};this.altAudio===2&&(m.type="video"),this.hls.trigger(w.BUFFER_EOS,m),this.state=X.ENDED;return}if(!this.buffering)return;e.loadLevel!==s&&e.manualLevel===-1&&this.log(`Adapting to level ${s} from level ${this.level}`),this.level=e.nextLoadLevel=s;const o=i.details;if(!o||this.state===X.WAITING_LEVEL||this.waitForLive(i)){this.level=s,this.state=X.WAITING_LEVEL,this.startFragRequested=!1;return}const c=a.len,d=this.getMaxBufferLength(i.maxBitrate);if(c>=d)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:a.end;let f=this.getNextFragment(h,o);if(this.couldBacktrack&&!this.fragPrevious&&f&&lt(f)&&this.fragmentTracker.getState(f)!==gt.OK){var p;const m=((p=this.backtrackFragment)!=null?p:f).sn-o.startSN,g=o.fragments[m-1];g&&f.cc===g.cc&&(f=g,this.fragmentTracker.removeFragment(g))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){const m=this.audioOnly&&!this.altAudio?Qe.AUDIO:Qe.VIDEO,g=(m===Qe.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;g&&this.afterBufferFlushed(g,m,fe.MAIN)}f=this.getNextFragmentLoopLoading(f,o,a,fe.MAIN,d)}f&&(this.exceedsMaxBuffer(a,d,f)||(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,i,h)))}loadFragment(e,t,r){const n=this.fragmentTracker.getState(e);n===gt.NOT_LOADED||n===gt.PARTIAL?lt(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,fe.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==0){var e;(((e=this.getLevelDetails())==null?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let r;const n=this.getAppendedFrag(t.currentTime);n&&n.start>1&&this.flushMainBuffer(0,n.start-1);const s=this.getLevelDetails();if(s!=null&&s.live){const a=this.getMainFwdBufferInfo();if(!a||a.len<s.targetduration*2)return}if(!t.paused&&e){const a=e[this.hls.nextLoadLevel],l=this.fragLastKbps;l&&this.fragCurrent?r=this.fragCurrent.duration*a.maxBitrate/(1e3*l)+1:r=0}else r=0;const i=this.getBufferedFrag(t.currentTime+r);if(i){const a=this.followingBufferedFrag(i);if(a){this.abortCurrentFrag();const l=a.maxStartPTS?a.maxStartPTS:a.start,o=a.duration,c=Math.max(i.end,l+Math.min(Math.max(o-this.config.maxFragLookUpTolerance,o*(this.couldBacktrack?.5:.125)),o*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(c,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 X.KEY_LOADING:case X.FRAG_LOADING:case X.FRAG_LOADING_WAITING_RETRY:case X.PARSING:case X.PARSED:this.state=X.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const r=t.media;Lt(r,"playing",this.onMediaPlaying),Lt(r,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:r}=this;r&&(Mt(r,"playing",this.onMediaPlaying),Mt(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(w.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 s=0;s<t.levels.length;s++){const i=t.levels[s].audioCodec;i&&(r=r||i.indexOf("mp4a.40.2")!==-1,n=n||i.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=r&&n&&!H_(),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!==X.IDLE)return;const n=t.levelInfo;(!n.details||n.details.live&&(this.levelLastLoaded!==n||n.details.expired)||this.waitForCdnTuneIn(n.details))&&(this.state=X.WAITING_LEVEL)}onLevelLoaded(e,t){var r;const{levels:n,startFragRequested:s}=this,i=t.level,a=t.details,l=a.totalduration;if(!n){this.warn(`Levels were reset while loading level ${i}`);return}this.log(`Level ${i} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${l}`);const o=t.levelInfo,c=this.fragCurrent;c&&(this.state===X.FRAG_LOADING||this.state===X.FRAG_LOADING_WAITING_RETRY)&&c.level!==t.level&&c.loader&&this.abortCurrentFrag();let d=0;if(a.live||(r=o.details)!=null&&r.live){var h;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;d=this.alignPlaylists(a,o.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(o.details=a,this.levelLastLoaded=o,s||this.setStartPosition(a,d),this.hls.trigger(w.LEVEL_UPDATED,{details:a,level:i}),this.state===X.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=X.IDLE}s&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:r}=this;if(!r)return;const n=this.hls.liveSyncPosition,s=this.getLoadPosition(),i=e.fragmentStart,a=e.edge,l=s>=i-t.maxFragLookUpTolerance&&s<=a;if(n!==null&&r.duration>n&&(s<n||!l)){const c=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&r.readyState<4||s<a-c)&&(this._hasEnoughToStart||(this.nextLoadPosition=n),r.readyState))if(this.warn(`Playback: ${s.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${n.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var o;const d=De.bufferInfo(r,n,0);if(!((o=d.buffered)!=null&&o.length)){r.currentTime=n;return}if(d.start<=s){r.currentTime=n;return}const{nextStart:h}=De.bufferedInfo(d.buffered,s,0);h&&(r.currentTime=h)}else r.currentTime=n}}_handleFragmentLoadProgress(e){var t;const r=e.frag,{part:n,payload:s}=e,{levels:i}=this;if(!i){this.warn(`Levels were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);return}const a=i[r.level];if(!a){this.warn(`Level ${r.level} not found on progress`);return}const l=a.details;if(!l){this.warn(`Dropping fragment ${r.sn} of level ${r.level} after level details were reset`),this.fragmentTracker.removeFragment(r);return}const o=a.videoCodec,c=l.PTSKnown||!l.live,d=(t=r.initSegment)==null?void 0:t.data,h=this._getAudioCodec(a),f=this.transmuxer=this.transmuxer||new ey(this.hls,fe.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),p=n?n.index:-1,m=p!==-1,g=new vu(r.level,r.sn,r.stats.chunkCount,s.byteLength,p,m),b=this.initPTS[r.cc];f.push(s,d,h,o,r,n,l.totalduration,c,g,b)}onAudioTrackSwitching(e,t){const r=this.hls,n=this.altAudio!==0;if(va(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 s=this.fragCurrent;s&&(this.log("Switching to main audio track, cancel main fragment load"),s.abortRequests(),this.fragmentTracker.removeFragment(s)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(n){this.altAudio=0,this.fragmentTracker.removeAllFragments(),r.once(w.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(w.AUDIO_TRACK_SWITCHED,t)}),r.trigger(w.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}r.trigger(w.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const r=va(t.url,this.hls);if(r){const n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=r?2:0,this.tick()}onBufferCreated(e,t){const r=t.tracks;let n,s,i=!1;for(const a in r){const l=r[a];if(l.id==="main"){if(s=a,n=l,a==="video"){const o=r[a];o&&(this.videoBuffer=o.buffer)}}else i=!0}i&&n?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=n.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:r,part:n}=t,s=r.type===fe.MAIN;if(s){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}`),this.state===X.PARSED&&(this.state=X.IDLE);return}const a=n?n.stats:r.stats;this.fragLastKbps=Math.round(8*a.total/(a.buffering.end-a.loading.first)),lt(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,n)}const i=this.media;i&&(!this._hasEnoughToStart&&De.getBuffered(i).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),s&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var r;if(t.fatal){this.state=X.ERROR;return}switch(t.details){case G.FRAG_GAP:case G.FRAG_PARSING_ERROR:case G.FRAG_DECRYPT_ERROR:case G.FRAG_LOAD_ERROR:case G.FRAG_LOAD_TIMEOUT:case G.KEY_LOAD_ERROR:case G.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(fe.MAIN,t);break;case G.LEVEL_LOAD_ERROR:case G.LEVEL_LOAD_TIMEOUT:case G.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===X.WAITING_LEVEL&&((r=t.context)==null?void 0:r.type)===Fe.LEVEL&&(this.state=X.IDLE);break;case G.BUFFER_ADD_CODEC_ERROR:case G.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case G.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case G.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=X.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Qe.AUDIO||!this.altAudio){const r=(t===Qe.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,t,fe.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&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){this.log(`could not seek to ${r}, already seeking at ${t}`);return}const n=this.timelineOffset;n&&r&&(r+=n);const s=this.getLevelDetails(),i=De.getBuffered(e),a=i.length?i.start(0):0,l=a-r,o=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<o||this.loadingParts&&l<2*(s?.partTarget||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),r+=l,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.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(r=>{const{hls:n}=this,s=r?.frag;if(!s||this.fragContextChanged(s))return;t.fragmentError=0,this.state=X.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const i=s.stats;i.parsing.start=i.parsing.end=i.buffering.start=i.buffering.end=self.performance.now(),n.trigger(w.FRAG_LOADED,r),s.bitrateTest=!1}).catch(r=>{this.state===X.STOPPED||this.state===X.ERROR||(this.warn(r),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:r}=this,{remuxResult:n,chunkMeta:s}=e,i=this.getCurrentContext(s);if(!i){this.resetWhenMissingContext(s);return}const{frag:a,part:l,level:o}=i,{video:c,text:d,id3:h,initSegment:f}=n,{details:p}=o,m=this.altAudio?void 0:n.audio;if(this.fragContextChanged(a)){this.fragmentTracker.removeFragment(a);return}if(this.state=X.PARSING,f){const g=f.tracks;if(g){const E=a.initSegment||a;if(this.unhandledEncryptionError(f,a))return;this._bufferInitSegment(o,g,E,s),r.trigger(w.FRAG_PARSING_INIT_SEGMENT,{frag:E,id:t,tracks:g})}const b=f.initPTS,y=f.timescale,S=this.initPTS[a.cc];if(he(b)&&(!S||S.baseTime!==b||S.timescale!==y)){const E=f.trackId;this.initPTS[a.cc]={baseTime:b,timescale:y,trackId:E},r.trigger(w.INIT_PTS_FOUND,{frag:a,id:t,initPTS:b,timescale:y,trackId:E})}}if(c&&p){m&&c.type==="audiovideo"&&this.logMuxedErr(a);const g=p.fragments[a.sn-1-p.startSN],b=a.sn===p.startSN,y=!g||a.cc>g.cc;if(n.independent!==!1){const{startPTS:S,endPTS:E,startDTS:k,endDTS:T}=c;if(l)l.elementaryStreams[c.type]={startPTS:S,endPTS:E,startDTS:k,endDTS:T};else if(c.firstKeyFrame&&c.independent&&s.id===1&&!y&&(this.couldBacktrack=!0),c.dropped&&c.independent){const A=this.getMainFwdBufferInfo(),N=(A?A.end:this.getLoadPosition())+this.config.maxBufferHole,C=c.firstKeyFramePTS?c.firstKeyFramePTS:S;if(!b&&N<C-this.config.maxBufferHole&&!y){this.backtrack(a);return}else y&&(a.gap=!0);a.setElementaryStreamInfo(c.type,a.start,E,a.start,T,!0)}else b&&S-(p.appliedTimelineOffset||0)>Xi&&(a.gap=!0);a.setElementaryStreamInfo(c.type,S,E,k,T),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(c,a,l,s,b||y)}else if(b||y)a.gap=!0;else{this.backtrack(a);return}}if(m){const{startPTS:g,endPTS:b,startDTS:y,endDTS:S}=m;l&&(l.elementaryStreams[Qe.AUDIO]={startPTS:g,endPTS:b,startDTS:y,endDTS:S}),a.setElementaryStreamInfo(Qe.AUDIO,g,b,y,S),this.bufferFragmentData(m,a,l,s)}if(p&&h!=null&&h.samples.length){const g={id:t,frag:a,details:p,samples:h.samples};r.trigger(w.FRAG_PARSING_METADATA,g)}if(p&&d){const g={id:t,frag:a,details:p,samples:d.samples};r.trigger(w.FRAG_PARSING_USERDATA,g)}}logMuxedErr(e){this.warn(`${lt(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,r,n){if(this.state!==X.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(r));const{audio:s,video:i,audiovideo:a}=t;if(s){const o=e.audioCodec;let c=Hi(s.codec,o);c==="mp4a"&&(c="mp4a.40.5");const d=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){c&&(c.indexOf("mp4a.40.5")!==-1?c="mp4a.40.2":c="mp4a.40.5");const h=s.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&d.indexOf("firefox")===-1&&(c="mp4a.40.5")}c&&c.indexOf("mp4a.40.5")!==-1&&d.indexOf("android")!==-1&&s.container!=="audio/mpeg"&&(c="mp4a.40.2",this.log(`Android: force audio codec to ${c}`)),o&&o!==c&&this.log(`Swapping manifest audio codec "${o}" for "${c}"`),s.levelCodec=c,s.id=fe.MAIN,this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${c||""}/${o||""}/${s.codec}]`),delete t.audiovideo}if(i){i.levelCodec=e.videoCodec,i.id=fe.MAIN;const o=i.codec;if(o?.length===4)switch(o){case"hvc1":case"hev1":i.codec="hvc1.1.6.L120.90";break;case"av01":i.codec="av01.0.04M.08";break;case"avc1":i.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${i.container}, codecs[level/parsed]=[${e.videoCodec||""}/${o}]${i.codec!==o?" parsed-corrected="+i.codec:""}${i.supplemental?" supplemental="+i.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 l=Object.keys(t);if(l.length){if(this.hls.trigger(w.BUFFER_CODECS,t),!this.hls)return;l.forEach(o=>{const c=t[o].initSegment;c!=null&&c.byteLength&&this.hls.trigger(w.BUFFER_APPENDING,{type:o,data:c,frag:r,part:null,chunkMeta:n,parent:r.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,fe.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,r=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=X.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const r=e.currentTime;if(De.isBuffered(e,r)?t=this.getAppendedFrag(r):De.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t){this.backtrackFragment=null;const n=this.fragPlaying,s=t.level;(!n||t.sn!==n.sn||n.level!==s)&&(this.fragPlaying=t,this.hls.trigger(w.FRAG_CHANGED,{frag:t}),(!n||n.level!==s)&&this.hls.trigger(w.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return he(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(he(t)){const r=this.getLevelDetails(),n=this.currentFrag||(r?fn(null,r.fragments,t):null);if(n){const s=n.programDateTime;if(s!==null){const i=s+(t-n.start)*1e3;return new Date(i)}}}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}},K_=class extends qt{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!==((t=n.context)==null?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=G.KEY_LOAD_ERROR,r,n,s){return new Sr({type:xe.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,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,s=t.length;n<s;n++){const i=t[n];if(e.cc<=i.cc&&(!lt(e)||!lt(i)||e.sn<i.sn)||!r&&n==s-1)return this.emeController.selectKeySystemFormat(i).then(a=>{if(!this.emeController)return;i.setKeyFormat(a);const l=ji(a);if(l)return this.emeController.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){const n=ms(this.config);if(n.length)return this.emeController.getKeySystemAccess(n)}}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 s=e.decryptdata;if(!s){const o=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,G.KEY_LOAD_ERROR,o))}const i=s.uri;if(!i)return Promise.reject(this.createKeyLoadError(e,G.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${i}"`)));const a=Jo(s);let l=this.keyIdToKeyInfo[a];if((r=l)!=null&&r.decryptdata.key)return s.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&(n=l)!=null&&n.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then(o=>{const{keyInfo:c}=o;return s.key=c.decryptdata.key,{frag:e,keyInfo:c}})}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${s.keyId?" keyId: "+wt(s.keyId):""} URI: ${s.uri} from ${e.type} ${e.level}`),l=this.keyIdToKeyInfo[a]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return s.keyFormat==="identity"?this.loadKeyHTTP(l,e):this.loadKeyEME(l,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,G.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e,t){const r={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var n;if(!e.decryptdata.keyId&&(n=t.initSegment)!=null&&n.data){const s=hR(t.initSegment.data);if(s.length){let i=s[0];i.some(a=>a!==0)?(this.log(`Using keyId found in init segment ${wt(i)}`),Ea.setKeyIdForUri(e.decryptdata.uri,i)):(i=Ea.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${wt(i)}`)),e.decryptdata.keyId=i}}return!e.decryptdata.keyId&&!lt(t)?Promise.resolve(r):(e.keyLoadPromise=this.emeController.loadKey(r).then(s=>(e.mediaKeySessionContext=s,r))).catch(s=>{throw e.keyLoadPromise=null,"data"in s&&(s.data.frag=t),s})}return Promise.resolve(r)}loadKeyHTTP(e,t){const r=this.config,n=r.loader,s=new n(r);return t.keyLoader=e.loader=s,e.keyLoadPromise=new Promise((i,a)=>{const l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=r.keyLoadPolicy.default,c={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};s.load(l,c,{onSuccess:(d,h,f,p)=>{const{frag:m,keyInfo:g}=f,b=Jo(g.decryptdata);if(!m.decryptdata||g!==this.keyIdToKeyInfo[b])return a(this.createKeyLoadError(m,G.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));g.decryptdata.key=m.decryptdata.key=new Uint8Array(d.data),m.keyLoader=null,g.loader=null,i({frag:m,keyInfo:g})},onError:(d,h,f,p)=>{this.resetLoader(h),a(this.createKeyLoadError(t,G.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),f,je({url:l.url,data:void 0},d)))},onTimeout:(d,h,f)=>{this.resetLoader(h),a(this.createKeyLoadError(t,G.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),f))},onAbort:(d,h,f)=>{this.resetLoader(h),a(this.createKeyLoadError(t,G.INTERNAL_ABORTED,new Error("key loading aborted"),f))}})})}resetLoader(e){const{frag:t,keyInfo:r,url:n}=e,s=r.loader;t.keyLoader===s&&(t.keyLoader=null,r.loader=null);const i=Jo(r.decryptdata)||n;delete this.keyIdToKeyInfo[i],s&&s.destroy()}};function Jo(e){if(e.keyFormat!==kt.FAIRPLAY){const t=e.keyId;if(t)return wt(t)}return e.uri}function Rf(e){const{type:t}=e;switch(t){case Fe.AUDIO_TRACK:return fe.AUDIO;case Fe.SUBTITLE_TRACK:return fe.SUBTITLE;default:return fe.MAIN}}function el(e,t){let r=e.url;return(r===void 0||r.indexOf("data:")===0)&&(r=t.url),r}var z_=class{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(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.LEVEL_LOADING,this.onLevelLoading,this),e.on(w.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(w.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(w.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.LEVEL_LOADING,this.onLevelLoading,this),e.off(w.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(w.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(w.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,r=t.pLoader,n=t.loader,s=new(r||n)(t);return this.loaders[e.type]=s,s}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:Fe.MANIFEST,url:r,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:r,level:n,pathwayId:s,url:i,deliveryDirectives:a,levelInfo:l}=t;this.load({id:r,level:n,pathwayId:s,responseType:"text",type:Fe.LEVEL,url:i,deliveryDirectives:a,levelOrTrack:l})}onAudioTrackLoading(e,t){const{id:r,groupId:n,url:s,deliveryDirectives:i,track:a}=t;this.load({id:r,groupId:n,level:null,responseType:"text",type:Fe.AUDIO_TRACK,url:s,deliveryDirectives:i,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:r,groupId:n,url:s,deliveryDirectives:i,track:a}=t;this.load({id:r,groupId:n,level:null,responseType:"text",type:Fe.SUBTITLE_TRACK,url:s,deliveryDirectives:i,levelOrTrack:a})}onLevelsUpdated(e,t){const r=this.loaders[Fe.LEVEL];if(r){const n=r.context;n&&!t.levels.some(s=>s===n.levelOrTrack)&&(r.abort(),delete this.loaders[Fe.LEVEL])}}load(e){var t;const r=this.hls.config;let n=this.getInternalLoader(e);if(n){const l=this.hls.logger,o=n.context;if(o&&o.levelOrTrack===e.levelOrTrack&&(o.url===e.url||o.deliveryDirectives&&!e.deliveryDirectives)){o.url===e.url?l.log(`[playlist-loader]: ignore ${e.url} ongoing request`):l.log(`[playlist-loader]: ignore ${e.url} in favor of ${o.url}`);return}l.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}let s;if(e.type===Fe.MANIFEST?s=r.manifestLoadPolicy.default:s=ze({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),he((t=e.deliveryDirectives)==null?void 0:t.part)){let l;if(e.type===Fe.LEVEL&&e.level!==null?l=this.hls.levels[e.level].details:e.type===Fe.AUDIO_TRACK&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===Fe.SUBTITLE_TRACK&&e.id!==null&&(l=this.hls.subtitleTracks[e.id].details),l){const o=l.partTarget,c=l.targetduration;if(o&&c){const d=Math.max(o*3,c*.8)*1e3;s=ze({},s,{maxTimeToFirstByteMs:Math.min(d,s.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,s.maxTimeToFirstByteMs)})}}}const i=s.errorRetry||s.timeoutRetry||{},a={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:i.maxNumRetry||0,retryDelay:i.retryDelayMs||0,maxRetryDelay:i.maxRetryDelayMs||0};n.load(e,a,{onSuccess:(l,o,c,d)=>{const h=this.getInternalLoader(c);this.resetInternalLoader(c.type);const f=l.data;o.parsing.start=performance.now(),gs.isMediaPlaylist(f)||c.type!==Fe.MANIFEST?this.handleTrackOrLevelPlaylist(l,o,c,d||null,h):this.handleMasterPlaylist(l,o,c,d)},onError:(l,o,c,d)=>{this.handleNetworkError(o,c,!1,l,d)},onTimeout:(l,o,c)=>{this.handleNetworkError(o,c,!0,void 0,l)}})}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 s=this.hls,i=e.data,a=el(e,r),l=gs.parseMasterPlaylist(i,a);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,r,l.playlistParsingError,n,t);return}const{contentSteering:o,levels:c,sessionData:d,sessionKeys:h,startTimeOffset:f,variableList:p}=l;this.variableList=p,c.forEach(y=>{const{unknownCodecs:S}=y;if(S){const{preferManagedMediaSource:E}=this.hls.config;let{audioCodec:k,videoCodec:T}=y;for(let A=S.length;A--;){const N=S[A];Vs(N,"audio",E)?(y.audioCodec=k=k?`${k},${N}`:N,Jn.audio[k.substring(0,4)]=2,S.splice(A,1)):Vs(N,"video",E)&&(y.videoCodec=T=T?`${T},${N}`:N,Jn.video[T.substring(0,4)]=2,S.splice(A,1))}}});const{AUDIO:m=[],SUBTITLES:g,"CLOSED-CAPTIONS":b}=gs.parseMasterPlaylistMedia(i,a,l);m.length&&!m.some(y=>!y.url)&&c[0].audioCodec&&!c[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ot({}),bitrate:0,url:""})),s.trigger(w.MANIFEST_LOADED,{levels:c,audioTracks:m,subtitles:g,captions:b,contentSteering:o,url:a,stats:t,networkDetails:n,sessionData:d,sessionKeys:h,startTimeOffset:f,variableList:p})}handleTrackOrLevelPlaylist(e,t,r,n,s){const i=this.hls,{id:a,level:l,type:o}=r,c=el(e,r),d=he(l)?l:he(a)?a:0,h=Rf(r),f=gs.parseLevelPlaylist(e.data,c,d,h,0,this.variableList);if(o===Fe.MANIFEST){const p={attrs:new ot({}),bitrate:0,details:f,name:"",url:c};f.requestScheduled=t.loading.start+Lb(f,0),i.trigger(w.MANIFEST_LOADED,{levels:[p],audioTracks:[],url:c,stats:t,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=f,this.handlePlaylistLoaded(f,e,t,r,n,s)}handleManifestParsingError(e,t,r,n,s){this.hls.trigger(w.ERROR,{type:xe.NETWORK_ERROR,details:G.MANIFEST_PARSING_ERROR,fatal:t.type===Fe.MANIFEST,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:n,stats:s})}handleNetworkError(e,t,r=!1,n,s){let i=`A network ${r?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${e.type}`;e.type===Fe.LEVEL?i+=`: ${e.level} id: ${e.id}`:(e.type===Fe.AUDIO_TRACK||e.type===Fe.SUBTITLE_TRACK)&&(i+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(i);this.hls.logger.warn(`[playlist-loader]: ${i}`);let l=G.UNKNOWN,o=!1;const c=this.getInternalLoader(e);switch(e.type){case Fe.MANIFEST:l=r?G.MANIFEST_LOAD_TIMEOUT:G.MANIFEST_LOAD_ERROR,o=!0;break;case Fe.LEVEL:l=r?G.LEVEL_LOAD_TIMEOUT:G.LEVEL_LOAD_ERROR,o=!1;break;case Fe.AUDIO_TRACK:l=r?G.AUDIO_TRACK_LOAD_TIMEOUT:G.AUDIO_TRACK_LOAD_ERROR,o=!1;break;case Fe.SUBTITLE_TRACK:l=r?G.SUBTITLE_TRACK_LOAD_TIMEOUT:G.SUBTITLE_LOAD_ERROR,o=!1;break}c&&this.resetInternalLoader(e.type);const d={type:xe.NETWORK_ERROR,details:l,fatal:o,url:e.url,loader:c,context:e,error:a,networkDetails:t,stats:s};n&&(d.response=je({url:t?.url||e.url,data:void 0},n)),this.hls.trigger(w.ERROR,d)}handlePlaylistLoaded(e,t,r,n,s,i){const a=this.hls,{type:l,level:o,levelOrTrack:c,id:d,groupId:h,deliveryDirectives:f}=n,p=el(t,n),m=Rf(n);let g=typeof n.level=="number"&&m===fe.MAIN?o:void 0;const b=e.playlistParsingError;if(b){if(this.hls.logger.warn(`${b} ${e.url}`),!a.config.ignorePlaylistParsingErrors){a.trigger(w.ERROR,{type:xe.NETWORK_ERROR,details:G.LEVEL_PARSING_ERROR,fatal:!1,url:p,error:b,reason:b.message,response:t,context:n,level:g,parent:m,networkDetails:s,stats:r});return}e.playlistParsingError=null}if(!e.fragments.length){const y=e.playlistParsingError=new Error("No Segments found in Playlist");a.trigger(w.ERROR,{type:xe.NETWORK_ERROR,details:G.LEVEL_EMPTY_ERROR,fatal:!1,url:p,error:y,reason:y.message,response:t,context:n,level:g,parent:m,networkDetails:s,stats:r});return}switch(e.live&&i&&(i.getCacheAge&&(e.ageHeader=i.getCacheAge()||0),(!i.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case Fe.MANIFEST:case Fe.LEVEL:if(g){if(!c)g=0;else if(c!==a.levels[g]){const y=a.levels.indexOf(c);y>-1&&(g=y)}}a.trigger(w.LEVEL_LOADED,{details:e,levelInfo:c||a.levels[0],level:g||0,id:d||0,stats:r,networkDetails:s,deliveryDirectives:f,withoutMultiVariant:l===Fe.MANIFEST});break;case Fe.AUDIO_TRACK:a.trigger(w.AUDIO_TRACK_LOADED,{details:e,track:c,id:d||0,groupId:h||"",stats:r,networkDetails:s,deliveryDirectives:f});break;case Fe.SUBTITLE_TRACK:a.trigger(w.SUBTITLE_TRACK_LOADED,{details:e,track:c,id:d||0,groupId:h||"",stats:r,networkDetails:s,deliveryDirectives:f});break}}},bs=class Mn{static get version(){return zs}static isMSESupported(){return Iy()}static isSupported(){return G_()}static getMediaSource(){return Vr()}static get Events(){return w}static get MetadataSchema(){return Ot}static get ErrorTypes(){return xe}static get ErrorDetails(){return G}static get DefaultConfig(){return Mn.defaultConfig?Mn.defaultConfig:L_}static set DefaultConfig(t){Mn.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Su,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 r=this.logger=eR(t.debug||!1,"Hls instance",t.assetPlayerId),n=this.config=R_(Mn.DefaultConfig,t,r);this.userConfig=t,n.progressive&&M_(n,r);const{abrController:s,bufferController:i,capLevelController:a,errorController:l,fpsController:o}=n,c=new l(this),d=this.abrController=new s(this),h=new qR(this),f=n.interstitialsController,p=f?this.interstitialsController=new f(this,Mn):null,m=this.bufferController=new i(this,h),g=this.capLevelController=new a(this),b=new o(this),y=new z_(this),S=n.contentSteeringController,E=S?new S(this):null,k=this.levelController=new U_(this,E),T=new $_(this),A=new K_(this.config,this.logger),N=this.streamController=new j_(this,h,A),C=this.gapController=new O_(this,h);g.setStreamController(N),b.setStreamController(N);const M=[y,k,N];p&&M.splice(1,0,p),E&&M.splice(1,0,E),this.networkControllers=M;const P=[d,m,C,g,b,T,h];this.audioTrackController=this.createController(n.audioTrackController,M);const D=n.audioStreamController;D&&M.push(this.audioStreamController=new D(this,h,A)),this.subtitleTrackController=this.createController(n.subtitleTrackController,M);const $=n.subtitleStreamController;$&&M.push(this.subtititleStreamController=new $(this,h,A)),this.createController(n.timelineController,P),A.emeController=this.emeController=this.createController(n.emeController,P),this.cmcdController=this.createController(n.cmcdController,P),this.latencyController=this.createController(B_,P),this.coreComponents=P,M.push(c);const B=c.onErrorOut;typeof B=="function"&&this.on(w.ERROR,B,c),this.on(w.MANIFEST_LOADED,y.onManifestLoaded,y)}createController(t,r){if(t){const n=new t(this);return r&&r.push(n),n}return null}on(t,r,n=this){this._emitter.on(t,r,n)}once(t,r,n=this){this._emitter.once(t,r,n)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,r,n=this,s){this._emitter.off(t,r,n,s)}listeners(t){return this._emitter.listeners(t)}emit(t,r,n){return this._emitter.emit(t,r,n)}trigger(t,r){if(this.config.debug)return this.emit(t,t,r);try{return this.emit(t,t,r)}catch(n){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+n.message+'". Here is a stacktrace:',n),!this.triggeringException){this.triggeringException=!0;const s=t===w.ERROR;this.trigger(w.ERROR,{type:xe.OTHER_ERROR,details:G.INTERNAL_EXCEPTION,fatal:s,event:t,error:n}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(w.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(r=>r.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(r=>r.destroy()),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const i=new Error(`attachMedia failed: invalid argument (${t})`);this.trigger(w.ERROR,{type:xe.OTHER_ERROR,details:G.ATTACH_MEDIA_ERROR,fatal:!0,error:i});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const r="media"in t,n=r?t.media:t,s=r?t:{media:n};this._media=n,this.trigger(w.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia"),this.trigger(w.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(w.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const r=this.media,n=this._url,s=this._url=uu.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${s}`),r&&n&&(n!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(r)),this.trigger(w.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,r){this.logger.log(`startLoad(${t+(r?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let n=0;n<this.networkControllers.length&&(this.networkControllers[n].startLoad(t,r),!(!this.started||!this.networkControllers));n++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!(this.started||!this.networkControllers));t++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(t=>{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[fe.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[fe.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[fe.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,r=t?.currentTime;this.detachMedia(),t&&(this.attachMedia(t),r&&this.startLoad(r))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=FD()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return t===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),t!==-1&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const r=!!t;r!==this.config.capLevelToPlayerSize&&(r?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=r)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){PR(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:r}}=this;if(!t)return 0;const n=t.length;for(let s=0;s<n;s++)if(t[s].maxBitrate>=r)return s;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:r,maxHdcpLevel:n}=this;let s;if(r===-1&&t!=null&&t.length?s=t.length-1:s=r,n)for(let i=s;i--;){const a=t[i].attrs["HDCP-LEVEL"];if(a&&a<=n)return i}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var r;return((r=this.audioTrackController)==null?void 0:r.setAudioOption(t))||null}setSubtitleOption(t){var r;return((r=this.subtitleTrackController)==null?void 0:r.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const r=this.audioTrackController;r&&(r.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const r=this.subtitleTrackController;r&&(r.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return t?t.subtitleDisplay:!1}set subtitleDisplay(t){const r=this.subtitleTrackController;r&&(r.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}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(t){this.latencyController.targetLatency=t}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(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!!((t=this.bufferController)!=null&&t.bufferedToEnd)}get interstitialsManager(){var t;return((t=this.interstitialsController)==null?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,r=this.allAudioTracks){return db(t,fb(r),navigator.mediaCapabilities)}};bs.defaultConfig=void 0;function W_(e,t){return e.name!==void 0&&e.name.length>0?e.name:e.height!==void 0&&e.height>0?`${e.height}p`:e.bitrate!==void 0&&e.bitrate>0?`${Math.round(e.bitrate/1e3)} kbps`:`Level ${t+1}`}function Q_(e){return[{value:-1,label:"Auto"},...e.map((t,r)=>({value:r,label:W_(t,r)}))]}function q_(e){return{height:e.height>0?e.height:void 0,bitrate:e.bitrate>0?e.bitrate:void 0,name:e.name.length>0?e.name:void 0}}function Y_({url:e,authToken:t,posterUrl:r,autoPlay:n=!0,className:s,onQualityOptions:i,selectedLevel:a=-1}){const l=ne(null),o=ne(null),[c,d]=_(null),[h,f]=_(!0);return ae(()=>{const p=l.current;if(!p||!e)return;d(null),f(!0),i?.([]);const m=()=>f(!1);if(p.addEventListener("playing",m),bs.isSupported()){const g=new bs({enableWorker:!0,lowLatencyMode:!1,xhrSetup:b=>{b.withCredentials=!0,t&&b.setRequestHeader("Authorization",`Bearer ${t}`)}});return o.current=g,g.loadSource(e),g.attachMedia(p),g.on(bs.Events.MANIFEST_PARSED,(b,y)=>{const S=y.levels.map(q_);i?.(S.length>1?Q_(S):[]),n&&p.play().catch(()=>{})}),g.on(bs.Events.ERROR,(b,y)=>{y.fatal&&(f(!1),d(`Playback error (${y.type}).`))}),()=>{p.removeEventListener("playing",m),o.current=null,g.destroy()}}if(p.canPlayType("application/vnd.apple.mpegurl")){p.src=e;const g=()=>{n&&p.play().catch(()=>{})};return p.addEventListener("loadedmetadata",g),p.addEventListener("error",()=>d("Could not load this recording.")),()=>{p.removeEventListener("loadedmetadata",g),p.removeEventListener("playing",m),p.removeAttribute("src"),p.load()}}return f(!1),d("HLS playback is not supported in this browser."),()=>p.removeEventListener("playing",m)},[e,t,n,i]),ae(()=>{const p=o.current;p!==null&&(p.currentLevel=a)},[a]),v("div",{className:`relative h-full w-full bg-black ${s??""}`,children:[u("video",{ref:l,controls:!0,playsInline:!0,className:"h-full w-full",...r?{poster:r}:{}}),h&&!c?u("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:u("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-white/20 border-t-white/60"})}):null,c?u("div",{className:"absolute inset-0 flex items-center justify-center px-4 text-center text-sm text-amber-400",children:c}):null]})}function X_(e){return e==="streaming"?"bg-emerald-500":e==="connecting"?"bg-amber-500":e==="error"?"bg-rose-500":"bg-zinc-500"}function Z_(e){const t=Math.floor(e/1e3);return t<60?`${t}s`:t<3600?`${Math.floor(t/60)}m`:`${Math.floor(t/3600)}h${Math.floor(t%3600/60)}m`}function dc({className:e}){return u("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u("polygon",{points:"5 3 19 12 5 21 5 3"})})}function J_({className:e}){return u("svg",{className:e,viewBox:"0 0 24 24",fill:"currentColor",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1"})})}function e5({className:e}){return v("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),u("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),u("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),u("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]})}function t5({className:e}){return v("svg",{className:e,viewBox:"0 0 24 24",fill:"currentColor",children:[u("circle",{cx:"5",cy:"12",r:"2"}),u("circle",{cx:"12",cy:"12",r:"2"}),u("circle",{cx:"19",cy:"12",r:"2"})]})}function tl({label:e,active:t,onClick:r}){return v("button",{type:"button",onClick:r,className:"w-full flex items-center justify-between gap-3 px-3 py-1.5 text-[11px] text-foreground hover:bg-surface-hover transition-colors",children:[u("span",{children:e}),u("span",{className:`inline-block h-3 w-5 rounded-full transition-colors ${t?"bg-primary":"bg-foreground-subtle/30"} relative`,children:u("span",{className:`absolute top-0.5 h-2 w-2 rounded-full bg-white transition-all ${t?"left-2.5":"left-0.5"}`})})]})}function r5({className:e}){return v("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u("circle",{cx:"12",cy:"12",r:"2",fill:"currentColor"}),u("path",{d:"M16.24 7.76a6 6 0 0 1 0 8.49M7.76 16.24a6 6 0 0 1 0-8.49M19.07 4.93a10 10 0 0 1 0 14.14M4.93 19.07a10 10 0 0 1 0-14.14"})]})}function Ry({className:e}){return v("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u("polyline",{points:"23 4 23 10 17 10"}),u("polyline",{points:"1 20 1 14 7 14"}),u("path",{d:"M3.51 9a9 9 0 0114.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0020.49 15"})]})}function n5({className:e}){return v("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u("line",{x1:"2",y1:"2",x2:"22",y2:"22"}),u("path",{d:"M10.41 10.41a2 2 0 11-2.83-2.83"}),u("line",{x1:"13.5",y1:"13.5",x2:"6",y2:"21"}),u("path",{d:"M18 12l-1.5-1.5"}),u("path",{d:"M21 15V5a2 2 0 00-2-2H5"}),u("path",{d:"M21 21H5a2 2 0 01-2-2V11"})]})}function kj({serverUrl:e,createSession:t,sendAnswer:r,handleOffer:n,getIceServers:s,addIceCandidate:i,getIceCandidates:a,closeSession:l,getSessionState:o,playbackUrl:c,playbackAuthToken:d,onExitPlayback:h,posterUrl:f,streams:p,activeStreamId:m,onStreamChange:g,deviceName:b,phase:y,pipelineMetrics:S,detections:E,defaultShowDetections:k=!0,defaultShowMotion:T=!1,streamStats:A,autoPlay:N=!1,showPlayStop:C=!1,snapshotSrc:M,snapshotLoading:P=!1,onRefreshSnapshot:D,showStreamStats:$=!1,children:B,extraOverlay:j,ptzAvailable:U=!1,ptzShown:F=!1,ptzOverlay:Y,onPtzToggle:I,intercomAvailable:R=!1,intercomShown:O=!1,onIntercomToggle:K,chromeless:W=!1,className:J}){const Q=EN(),[ee,ie]=_(N),[se,be]=_(k),[ye,ue]=_(T),[we,le]=_(null),[Z,ce]=_([]),[Ae,Re]=_(-1),[He,ut]=_(!1),St=ne(null);ae(()=>{if(!He)return;function de(Oe){St.current&&!St.current.contains(Oe.target)&&ut(!1)}return document.addEventListener("mousedown",de),()=>document.removeEventListener("mousedown",de)},[He]),ae(()=>{Re(-1)},[c]);const Ue=q(de=>{ce(de)},[]),Ge=m??we??p?.[0]?.id??"",tt=p?.find(de=>de.id===Ge)??p?.[0],We=tt?.inputFps!=null?{status:tt.status??"unknown",inputFps:tt.inputFps,bitrateKbps:tt.bitrateKbps??0}:null,Ht=de=>{le(de),g?.(de),ee&&C&&(ie(!1),setTimeout(()=>ie(!0),50))},At=oe(()=>{const de=tt?.target;if(!(!de||!t))return Oe=>t(de,Oe)},[t,tt]),gr=oe(()=>{const de=tt?.target;if(!(!de||!n))return(Oe,ft)=>n(de,Oe,ft)},[n,tt]),Qr=oe(()=>{if(n)return(de,Oe,ft)=>n(ft,Oe,de)},[n]),H=p,me=()=>ie(!0),ke=()=>ie(!1),Ne=S?.phase??y,Ve=Ne==="active",Te=!!E,re=Te&&(se||ye),Se=U&&F&&!!Y,ge=!!c,rt=ge||(C?ee:!0);return v("div",{className:`overflow-hidden ${W?"":"rounded-xl border border-border bg-surface"} ${J??""}`,children:[v("div",{className:"flex flex-wrap items-center justify-between gap-2 px-3 py-2 border-b border-border",children:[v("div",{className:"flex items-center gap-2 min-w-0",children:[(A??We)&&u("span",{className:`shrink-0 w-2 h-2 rounded-full ${X_((A??We).status)}`}),b&&u("span",{className:"text-xs font-medium text-foreground truncate",children:b}),!ge&&H&&H.length>1&&v("div",{className:"relative",children:[u("select",{"data-testid":"stream-profile-select",value:Ge,onChange:de=>Ht(de.target.value),className:"appearance-none cursor-pointer rounded-md border border-border bg-surface-hover hover:bg-surface text-foreground text-[11px] font-medium pl-2 pr-6 py-1 focus:outline-none focus:ring-1 focus:ring-primary transition-colors",children:H.map(de=>u("option",{value:de.id,children:de.label},de.id))}),u("span",{className:"pointer-events-none absolute right-1.5 top-1/2 -translate-y-1/2 text-foreground-subtle",children:u("svg",{className:"h-2.5 w-2.5",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u("polyline",{points:"3 4.5 6 7.5 9 4.5"})})})]}),ge&&Z.length>1&&v("div",{className:"relative",children:[u("select",{"data-testid":"vod-quality-select",value:Ae,onChange:de=>Re(Number(de.target.value)),className:"appearance-none cursor-pointer rounded-md border border-border bg-surface-hover hover:bg-surface text-foreground text-[11px] font-medium pl-2 pr-6 py-1 focus:outline-none focus:ring-1 focus:ring-primary transition-colors",children:Z.map(de=>u("option",{value:de.value,children:de.label},de.value))}),u("span",{className:"pointer-events-none absolute right-1.5 top-1/2 -translate-y-1/2 text-foreground-subtle",children:u("svg",{className:"h-2.5 w-2.5",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:u("polyline",{points:"3 4.5 6 7.5 9 4.5"})})})]})]}),v("div",{className:"flex items-center gap-1.5 shrink-0 ml-auto",children:[R&&!ge&&v("button",{"data-testid":"stream-intercom-toggle","data-intercom-shown":O?"true":"false",onClick:K,className:`inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-colors ${O?"bg-primary/15 text-primary":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover"}`,title:O?"Close intercom":"Open intercom",children:[u(e5,{className:"h-3 w-3"}),u("span",{className:"hidden xl:inline",children:"Intercom"})]}),Q.map(de=>{const Oe=de.tone==="primary"?"bg-primary text-primary-foreground":"bg-primary/15 text-primary";return v("button",{type:"button","data-toolbar-button-id":de.id,"data-toolbar-button-active":de.active?"true":"false",onClick:de.onClick,disabled:de.disabled,className:`inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-colors disabled:opacity-50 ${de.active?Oe:"text-foreground-subtle hover:text-foreground hover:bg-surface-hover"}`,title:de.title??de.label,children:[de.icon,u("span",{className:"hidden xl:inline",children:de.label})]},de.id)}),C&&v("button",{"data-testid":"stream-play-toggle","data-stream-playing":rt?"true":"false","data-vod":ge?"true":"false",onClick:ge?h:rt?ke:me,className:`inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-colors ${ge?"bg-primary/10 text-primary hover:bg-primary/20":rt?"bg-danger/10 text-danger hover:bg-danger/20":"bg-primary/10 text-primary hover:bg-primary/20"}`,title:ge?"Return to live":rt?"Stop stream":"Start stream",children:[ge?u(r5,{className:"h-3 w-3"}):rt?u(J_,{className:"h-3 w-3"}):u(dc,{className:"h-3 w-3"}),u("span",{className:"hidden xl:inline",children:ge?"Live":rt?"Stop":"Play"})]}),D&&!ge&&v("button",{"data-testid":"stream-snapshot-refresh",onClick:D,disabled:P,className:"inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50",title:"Force snapshot refresh",children:[u(Ry,{className:`h-3 w-3 ${P?"animate-spin":""}`}),u("span",{className:"hidden xl:inline",children:"Snapshot"})]}),(Te||U||S||Ne||A||We&&We.inputFps>0)&&v("div",{ref:St,className:"relative",children:[u("button",{onClick:()=>ut(de=>!de),title:"More controls",className:"inline-flex items-center justify-center rounded-md p-1 text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",children:u(t5,{className:"h-3.5 w-3.5"})}),He&&v("div",{className:"absolute right-0 top-full mt-1 z-30 min-w-[200px] rounded-lg border border-border bg-surface shadow-xl py-1.5",children:[$&&A&&v("div",{className:"px-3 py-1.5 text-[10px] text-foreground-subtle border-b border-border-subtle",children:[v("div",{className:"flex justify-between gap-3",children:[u("span",{children:"Input"}),v("span",{className:"tabular-nums text-foreground",children:[A.inputFps.toFixed(1)," fps"]})]}),v("div",{className:"flex justify-between gap-3",children:[u("span",{children:"Decode"}),v("span",{className:"tabular-nums text-foreground",children:[A.decodeFps.toFixed(1)," fps"]})]}),v("div",{className:"flex justify-between gap-3",children:[u("span",{children:"Uptime"}),u("span",{className:"tabular-nums text-foreground",children:Z_(A.uptimeMs)})]})]}),!$&&We&&We.inputFps>0&&v("div",{className:"px-3 py-1.5 text-[10px] text-foreground-subtle border-b border-border-subtle",children:[v("div",{className:"flex justify-between gap-3",children:[u("span",{children:"Input"}),v("span",{className:"tabular-nums text-foreground",children:[We.inputFps.toFixed(1)," fps"]})]}),We.bitrateKbps>0&&v("div",{className:"flex justify-between gap-3",children:[u("span",{children:"Bitrate"}),v("span",{className:"tabular-nums text-foreground",children:[We.bitrateKbps," kbps"]})]})]}),(S||Te&&Ne)&&v("div",{className:"px-3 py-1.5 text-[10px] text-foreground-subtle border-b border-border-subtle",children:[v("div",{className:"flex justify-between gap-3 items-center",children:[u("span",{children:"Phase"}),v("span",{className:`flex items-center gap-1 font-semibold uppercase tracking-wider ${Ve?"text-red-400":"text-emerald-400"}`,children:[u("span",{className:`w-1.5 h-1.5 rounded-full ${Ve?"bg-red-500 animate-pulse":"bg-emerald-500"}`}),Ve?"Active":"Watching"]})]}),S&&S.detectionFps>0&&v("div",{className:"flex justify-between gap-3",children:[u("span",{children:"Detection"}),v("span",{className:"tabular-nums text-foreground",children:[S.detectionFps.toFixed(1)," det/s"]})]}),S&&S.avgInferenceMs>0&&v("div",{className:"flex justify-between gap-3",children:[u("span",{children:"Inference"}),v("span",{className:"tabular-nums text-foreground",children:[S.avgInferenceMs.toFixed(0)," ms"]})]})]}),Te&&v(Ie,{children:[u(tl,{label:"Show detections",active:se,onClick:()=>be(de=>!de)}),u(tl,{label:"Show motion",active:ye,onClick:()=>ue(de=>!de)})]}),U&&u(tl,{label:"PTZ controls",active:F,onClick:()=>{I?.(),ut(!1)}})]})]})]})]}),c?v("div",{className:"aspect-video relative",children:[u(Y_,{url:c,authToken:d??null,onQualityOptions:Ue,selectedLevel:Ae,...f?{posterUrl:f}:{}}),j||Se?v(Ie,{children:[j,Se&&Y]}):null]}):rt&&e?u("div",{className:"aspect-video relative",children:u(KI,{serverUrl:e,streamKey:Ge,autoPlay:!0,className:"w-full h-full",createSession:At,sendAnswer:r,handleOffer:gr,reoffer:Qr,getSessionState:o,getIceServers:s,addIceCandidate:i,getIceCandidates:a,closeSession:l,...f?{posterUrl:f}:{},overlay:re||j||Se?v(Ie,{children:[re&&u(_I,{detections:E,showPhaseIndicator:!1,showMotionZones:ye,showMotionRaw:ye,showDetections:se}),j,Se&&Y]}):void 0},Ge)}):u(s5,{src:M??null,isLoading:P,onPlay:me,onRetry:D,extraOverlay:j||Se?v(Ie,{children:[j,Se&&Y]}):null,suppressPlayHover:!!j||Se}),B]})}function s5({src:e,isLoading:t,onPlay:r,onRetry:n,extraOverlay:s,suppressPlayHover:i=!1}){return e?v("div",{className:"relative w-full aspect-video bg-black/90 flex items-center justify-center",children:[u("img",{src:e,alt:"Camera snapshot",className:"w-full h-full object-contain"}),!i&&u("button",{onClick:r,className:"absolute inset-0 flex items-center justify-center bg-black/30 opacity-0 hover:opacity-100 transition-opacity cursor-pointer",children:u("div",{className:"h-14 w-14 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center",children:u(dc,{className:"h-7 w-7 text-white ml-0.5"})})}),s]}):t?u("div",{className:"relative w-full aspect-video bg-black/90 flex items-center justify-center",children:u("div",{className:"h-8 w-8 border-2 border-white/20 border-t-white/60 rounded-full animate-spin"})}):u("div",{className:"relative w-full aspect-video bg-black/90 flex items-center justify-center",children:v("div",{className:"flex flex-col items-center gap-2 text-white/40",children:[u(n5,{className:"h-8 w-8"}),u("span",{className:"text-xs",children:"No snapshot available"}),v("div",{className:"flex items-center gap-2 mt-1",children:[n&&v("button",{onClick:n,className:"inline-flex items-center gap-1.5 rounded-md border border-white/20 px-3 py-1.5 text-xs font-medium text-white/60 hover:text-white hover:border-white/40 transition-colors",children:[u(Ry,{className:"h-3 w-3"}),"Retry"]}),v("button",{onClick:r,className:"inline-flex items-center gap-1.5 rounded-md bg-primary/80 px-3 py-1.5 text-xs font-medium text-white hover:bg-primary transition-colors",children:[u(dc,{className:"h-3 w-3"}),"Play Live"]})]})]})})}var Mf={value:"auto",label:"Auto (best available)"};function i5(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Tj({deviceId:e,value:t,onChange:r,disabled:n,label:s,className:i}){const a=fr(),l=ik({deviceId:e},{refetchOnWindowFocus:!1}),[o,c]=_([Mf]);ae(()=>{if(!l.data)return;const f=`${e}/`,p=[Mf];for(const m of l.data){if(!m.enabled)continue;const g=m.brokerId.startsWith(f)?m.brokerId.slice(f.length):m.brokerId;p.push({value:g,label:i5(g)})}c(p)},[l.data,e]);const d=s??"Preferred stream",h=l.isLoading?"Loading available streams…":l.isError?"Could not load streams — only Auto available.":o.length===1?"No enabled streams found — only Auto available.":null;return v("div",{className:i,children:[u("label",{id:a,className:"text-xs font-medium text-foreground-muted block mb-1",children:d}),u(aa,{"aria-labelledby":a,options:o,value:t,disabled:n,onChange:f=>r(f.target.value)}),h!==null&&u("p",{className:"text-foreground-subtle text-[10px] mt-1",children:h})]})}var a5=2e3;function o5({value:e,label:t,className:r,disabled:n}){const[s,i]=_(!1),a=q(()=>{e&&navigator.clipboard.writeText(e).then(()=>{i(!0),setTimeout(()=>i(!1),a5)})},[e]);return v(tr,{size:"sm",variant:"ghost",type:"button",disabled:n||e.length===0,onClick:a,className:L(r),"aria-label":s?"Copied":`Copy ${t??"value"}`,children:[s?u(Lr,{className:"h-3.5 w-3.5 text-success"}):u(zr,{className:"h-3.5 w-3.5"}),t?u("span",{className:"ml-1",children:s?"Copied":t}):null]})}var l5=vc(s0),c5=c0({id:Fu(),stableId:nn(),addonId:nn(),type:nn(),name:nn(),online:Ha(),disabled:Ha(),parentDeviceId:Fu().nullable(),role:nn().nullable().optional(),features:vc(nn()).optional(),isCamera:Ha().optional(),sourceInfo:n0.optional()}),u5=vc(nn()),Pf=1e4;function d5(e){return e==="linked"?"success":e==="error"?"danger":"warning"}function h5(e){return e==="linked"?"Linked":e==="unlinked"?"Unlinked":e==="error"?"Error":e}function f5({field:e}){const[t,r]=_(!1),n=e.secret===!0,s=n&&!t?"•".repeat(Math.min(e.value.length,24)):e.value;return v("div",{className:"flex items-center gap-2 py-1.5",children:[u("span",{className:"text-[11px] text-foreground-subtle w-32 shrink-0",children:e.label}),u("span",{className:"flex-1 min-w-0 truncate font-mono text-xs text-foreground",children:s||"—"}),n&&u(tr,{size:"sm",variant:"ghost",type:"button","aria-label":t?"Hide value":"Reveal value",onClick:()=>r(i=>!i),children:t?u(Ca,{className:"h-3.5 w-3.5"}):u(Xs,{className:"h-3.5 w-3.5"})}),u(o5,{value:e.value,label:e.label})]})}function p5({setup:e}){const t=e.fields??[];return v("div",{className:"border-b border-border bg-surface-hover/10",children:[v("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border",children:[u(hE,{className:"h-3.5 w-3.5 text-foreground-subtle shrink-0"}),u("span",{className:"text-[11px] font-semibold text-foreground-subtle uppercase tracking-wide",children:"Setup"})]}),v("div",{className:"flex flex-col gap-3 p-4 sm:flex-row sm:items-start",children:[e.qr&&u("div",{className:"shrink-0",children:u(Yv,{value:e.qr,alt:"Pairing QR code"})}),v("div",{className:"flex-1 min-w-0",children:[e.note&&u("p",{className:"text-xs text-foreground-muted whitespace-pre-line mb-2",children:e.note}),t.length>0&&u("div",{className:"divide-y divide-border-subtle",children:t.map(r=>u(f5,{field:r},r.label))})]})]})]})}function m5({addonId:e,deviceId:t,exposed:r,busy:n,onExpose:s,onUnexpose:i}){return u(tr,{size:"sm",variant:r?"ghost":"primary",disabled:n,onClick:l=>{l.stopPropagation(),!n&&(r?i(t):s(t))},title:r?`Stop exposing to "${e}"`:`Expose to "${e}"`,children:r?v(Ie,{children:[u(LE,{className:"mr-1 h-3.5 w-3.5"}),"Exposed"]}):v(Ie,{children:[u(xl,{className:"mr-1 h-3.5 w-3.5"}),"Expose"]})})}function Aj({addonId:e,trpc:t,onOpenDevice:r}){const n=ts(),s=ak({nodeId:"hub",addonId:e},{refetchInterval:Pf,retry:!1}),i=lk({nodeId:"hub",addonId:e},{refetchInterval:Pf,retry:!1}),a=ok({nodeId:"hub",addonId:e},{retry:!1}),l=xg({},{refetchInterval:5e3}),o=q(()=>{n.invalidateQueries({queryKey:[["deviceExport"]]})},[n]),c=ck({onSuccess:o}),d=uk({onSuccess:o}),h=oe(()=>{const D=Xy.safeParse(s.data);return D.success?D.data:null},[s.data]),f=oe(()=>{const D=l5.safeParse(i.data);return D.success?D.data:[]},[i.data]),p=oe(()=>new Set(f.map(D=>D.deviceId)),[f]),m=oe(()=>{const D=u5.safeParse(a.data);return new Set(D.success?D.data:[])},[a.data]),g=oe(()=>[...m].sort(),[m]),b=oe(()=>g.map(D=>{const $=Wc(D);return{id:D,label:$.label,icon:$.icon}}),[g]),y=oe(()=>{const D=l.data;if(!Array.isArray(D))return[];const $=[];for(const B of D){const j=c5.safeParse(B);j.success&&m.has(j.data.type)&&$.push(j.data)}return $},[l.data,m]),S=h?.linkState??"unlinked",E=s.isLoading||i.isLoading||a.isLoading||l.isLoading,k=h?.exposedDeviceCount??p.size,T=c.isPending||d.isPending,A=q(D=>{c.mutate({deviceId:D,nodeId:"hub",addonId:e})},[c,e]),N=q(D=>{d.mutate({deviceId:D,nodeId:"hub",addonId:e})},[d,e]),C=q(D=>{const $=String(D.id);return u(m5,{addonId:e,deviceId:$,exposed:p.has($),busy:T,onExpose:A,onUnexpose:N})},[e,p,T,A,N]),M=q(D=>r?.(String(D)),[r]),P=g.length>0;return v("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[v("div",{className:"flex items-center justify-between gap-3 px-4 py-2.5 border-b border-border bg-surface-hover/20",children:[v("div",{className:"flex items-center gap-2 min-w-0",children:[u(xl,{className:"h-3.5 w-3.5 text-foreground-subtle shrink-0"}),u("span",{className:"text-[11px] font-semibold text-foreground-subtle uppercase tracking-wide",children:"Exported devices"}),u(Hn,{variant:d5(S),children:h5(S)}),v("span",{className:"text-[11px] text-foreground-subtle",children:[k," exposed"]})]}),E&&u(vt,{className:"h-3.5 w-3.5 animate-spin text-foreground-subtle"})]}),h?.error&&u("div",{className:"px-4 py-3 border-b border-border",children:u(oa,{message:h.error})}),h?.setup&&u(p5,{setup:h.setup}),u("div",{className:"p-3",children:P&&y.length>0?u(c2,{devices:y,trpc:t,defaultView:"table",filters:{typeOptions:b},urlScope:"nested",lsKey:`device-export:${e}`,onNavigate:r?M:void 0,renderRowAction:C}):u(ag,{icon:xl,title:"No exportable devices",description:P?`No devices of the supported kinds (${g.join(", ")}) are available to expose to "${e}".`:`"${e}" reports no exportable device kinds yet.`})})]})}function Cj({samples:e,sampleRate:t=16e3,height:r=96,className:n="",color:s="#3b82f6",bgColor:i="transparent"}){const a=ne(null),l=ne(null),o=q(()=>{const d=a.current,h=l.current;if(!d||!h||!e||e.length===0)return;const f=h.clientWidth;if(f===0)return;const p=window.devicePixelRatio||1;d.width=f*p,d.height=r*p,d.style.width=`${f}px`,d.style.height=`${r}px`;const m=d.getContext("2d");if(!m)return;m.scale(p,p),i!=="transparent"?(m.fillStyle=i,m.fillRect(0,0,f,r)):m.clearRect(0,0,f,r);const g=e.length/f,b=r/2;m.fillStyle=s,m.globalAlpha=.7;for(let y=0;y<f;y++){const S=Math.floor(y*g),E=Math.min(Math.floor((y+1)*g),e.length);let k=0,T=0;for(let M=S;M<E;M++){const P=e[M];P<k&&(k=P),P>T&&(T=P)}const A=b-T*b,N=b-k*b,C=Math.max(1,N-A);m.fillRect(y,A,1,C)}m.globalAlpha=1,m.strokeStyle=s,m.globalAlpha=.2,m.lineWidth=1,m.beginPath(),m.moveTo(0,b),m.lineTo(f,b),m.stroke(),m.globalAlpha=1},[e,r,s,i]);ae(()=>{o()},[o]),ae(()=>{const d=new ResizeObserver(()=>o()),h=l.current;return h&&d.observe(h),()=>d.disconnect()},[o]);const c=((e&&t?Math.round(e.length/t*1e3):0)/1e3).toFixed(1);return v("div",{ref:l,className:`relative ${n}`,children:[u("canvas",{ref:a,className:"w-full rounded-md"}),e&&e.length>0&&v("div",{className:"absolute bottom-1 right-2 text-[10px] text-foreground-subtle/60 font-mono",children:[c,"s · ",t/1e3,"kHz · ",e.length.toLocaleString()," samples"]})]})}function Nj({currentDbfs:e,durationSec:t=30,maxSamples:r=120,height:n=64,className:s="",color:i="#10b981",clipColor:a="#ef4444",clipThreshold:l=-6,minDbfs:o=-96}){const c=ne(null),d=ne(null),[h,f]=_([]);ae(()=>{e!==null&&f(g=>{const b=[...g,{dbfs:e,timestamp:Date.now()}];return b.length>r?b.slice(-r):b})},[e,r]);const p=q(()=>{const g=c.current,b=d.current;if(!g||!b)return;const y=b.clientWidth;if(y===0)return;const S=window.devicePixelRatio||1;g.width=y*S,g.height=n*S,g.style.width=`${y}px`,g.style.height=`${n}px`;const E=g.getContext("2d");if(!E||(E.scale(S,S),E.clearRect(0,0,y,n),h.length===0))return;const k=h[h.length-1].timestamp,T=t*1e3,A=k-T,N=h.filter(D=>D.timestamp>=A);if(N.length===0)return;const C=Math.max(1,Math.floor(y/(t*2))),M=Math.abs(o);for(const D of N){const $=D.timestamp-A,B=Math.floor($/T*y),j=(Math.max(o,Math.min(0,D.dbfs))-o)/M,U=Math.max(1,j*n);E.fillStyle=D.dbfs>=l?a:i,E.globalAlpha=.8,E.fillRect(B,n-U,C,U)}E.globalAlpha=1;const P=n-(l-o)/M*n;E.strokeStyle=a,E.globalAlpha=.25,E.lineWidth=1,E.setLineDash([4,4]),E.beginPath(),E.moveTo(0,P),E.lineTo(y,P),E.stroke(),E.setLineDash([]),E.globalAlpha=1},[h,t,n,i,a,l,o]);ae(()=>{p()},[p]),ae(()=>{const g=new ResizeObserver(()=>p()),b=d.current;return b&&g.observe(b),()=>g.disconnect()},[p]);const m=h.length>0?h[h.length-1].dbfs:null;return v("div",{ref:d,className:`relative ${s}`,children:[u("canvas",{ref:c,className:"w-full rounded-md"}),v("div",{className:"absolute top-1 left-2 text-[9px] text-foreground-subtle/50 font-mono",children:[t,"s"]}),m!==null&&v("div",{className:"absolute bottom-1 right-2 text-[9px] text-foreground-subtle/50 font-mono",children:[m.toFixed(1)," dBFS · ",h.length," samples"]})]})}function g5(e){return e>=.8?"bg-emerald-500":e>=.5?"bg-amber-500":e>=.3?"bg-orange-500":"bg-zinc-500"}function v5(e){return e>=.8?"text-emerald-400":e>=.5?"text-amber-400":e>=.3?"text-orange-400":"text-zinc-400"}function Lj({classifications:e,processing:t=!1,inferenceMs:r,maxItems:n=10,className:s=""}){const i=e.slice(0,n),a=i.length>0?i[0].score:1;return t?u("div",{className:`rounded-xl border border-border bg-surface p-4 text-center ${s}`,children:u("div",{className:"text-sm text-foreground-subtle animate-pulse",children:"Classifying audio..."})}):i.length===0?u("div",{className:`rounded-xl border border-border bg-surface p-4 text-center ${s}`,children:u("div",{className:"text-xs text-foreground-subtle",children:"No classifications yet"})}):v("div",{className:`rounded-xl border border-border bg-surface overflow-hidden ${s}`,children:[v("div",{className:"px-3 py-2 border-b border-border flex items-center justify-between",children:[u("h3",{className:"text-xs font-medium text-foreground",children:"Audio Classifications"}),v("div",{className:"flex items-center gap-3 text-[10px] text-foreground-subtle",children:[i.length<e.length&&v("span",{children:["showing ",i.length," of ",e.length]}),r!==void 0&&v("span",{className:"font-mono",children:[r.toFixed(1),"ms"]})]})]}),u("div",{className:"divide-y divide-border/50",children:i.map((l,o)=>{const c=a>0?l.score/a*100:0;return v("div",{className:"px-3 py-1.5 flex items-center gap-3 hover:bg-surface-hover/30",children:[u("span",{className:"text-[10px] text-foreground-subtle w-5 text-right font-mono",children:o+1}),u("span",{className:"text-xs font-medium text-foreground min-w-[120px]",children:l.className}),u("div",{className:"flex-1 h-2 rounded-full bg-zinc-800 overflow-hidden",children:u("div",{className:`h-full rounded-full transition-all duration-300 ${g5(l.score)}`,style:{width:`${c}%`}})}),v("span",{className:`text-xs font-mono font-semibold w-14 text-right ${v5(l.score)}`,children:[(l.score*100).toFixed(1),"%"]})]},`${l.className}-${o}`)})})]})}function Ij({data:e,label:t="Response",className:r=""}){const[n,s]=_(!1);if(!e)return null;const i=JSON.stringify(e,null,2);return v("div",{className:`rounded-xl border border-border bg-surface overflow-hidden ${r}`,children:[v("div",{className:"px-3 py-2 border-b border-border flex items-center justify-between cursor-pointer select-none hover:bg-surface-hover/30",onClick:()=>s(a=>!a),children:[v("div",{className:"flex items-center gap-2",children:[u("span",{className:"text-[10px] text-foreground-subtle",children:n?"▼":"▶"}),u("h3",{className:"text-xs font-medium text-foreground",children:t})]}),u("span",{className:"text-[10px] text-foreground-subtle font-mono",children:i.length>1e3?`${(i.length/1024).toFixed(1)} KB`:`${i.length} bytes`})]}),n&&u("div",{className:"max-h-80 overflow-y-auto overflow-x-auto",children:u("pre",{className:"p-3 text-[10px] leading-4 font-mono text-foreground-subtle whitespace-pre",children:i})})]})}var b5={Activity:ur,Eye:Xs,AlertTriangle:ss,PauseCircle:AS,PowerOff:dE};function Rj({phase:e,...t}){const r=b5[Tp(e).icon];return u(r,{...t})}function Ls(e){const[t,r]=_([]),n=q(i=>{r(a=>{const l=[...a,i];return l.length>e?l.slice(-e):l})},[e]),s=q(()=>{r([])},[]);return oe(()=>({entries:t,append:n,reset:s}),[t,n,s])}function y5(e,t=40){return e.scrollHeight-e.scrollTop-e.clientHeight<=t}function Df(e){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e)}catch{return String(e)}}var _f={error:{icon:rs,color:"text-red-400"},warn:{icon:ss,color:"text-amber-400"},info:{icon:qS,color:"text-blue-400"},debug:{icon:yS,color:"text-gray-500"}},Of={debug:0,info:1,warn:2,error:3},x5=["all","debug","info","warn","error"],S5=500;function E5(e,t){return t?(Of[e]??0)>=(Of[t]??0):!0}function My({agentId:e,addonId:t,deviceId:r,containerDeviceId:n,integrationId:s,requestId:i,level:a,maxHeight:l="max-h-96",showScope:o=!1,showFilters:c=!0,limit:d=100,liveBuffer:h,onClose:f,className:p}){const[m,g]=_(""),[b,y]=_(""),[S,E]=_(a),k=e,T=t??(m||void 0),A=r??(b?Number(b):void 0),N=s,C=i,M=oe(()=>{const H={};return k&&(H.agentId=k),T&&(H.addonId=T),n!==void 0&&Number.isFinite(n)?H.containerDeviceId=n:A!==void 0&&Number.isFinite(A)&&(H.deviceId=A),N&&(H.integrationId=N),C&&(H.requestId=C),Object.keys(H).length>0?H:void 0},[k,T,A,n,N,C]),P=Ls(S5),D=h??P,$=D.entries,[B,j]=_(0),[U,F]=_(!0),Y=ne(!1),[I,R]=_(!1),[O,K]=_(!1),[W,J]=_(new Set),[Q,ee]=_(""),ie=ne(null),se=`${k??""}:${T??""}:${String(A??"")}:${String(n??"")}:${N??""}:${C??""}`,be=ne(se);ae(()=>{be.current!==se&&(be.current=se,D.reset(),j(0),J(new Set),R(!1))},[se,D]);const{data:ye,isLoading:ue}=x.logs.query.useQuery({...M?{tags:M}:{},limit:d},{staleTime:3e4});x.logs.subscribe.useSubscription({...M?{tags:M}:{}},{onData:H=>{D.append(H)}});const we=oe(()=>{const H=(ye??[]).map(Te=>({timestamp:Te.timestamp,level:Te.level,message:Te.message,scope:Te.scope,tags:Te.tags,meta:Te.meta})),me=new Map;for(const Te of H)me.set(`${Te.timestamp}|${Te.level}|${Te.scope??""}|${Te.message}`,Te);for(const Te of $)me.set(`${Te.timestamp}|${Te.level}|${Te.scope??""}|${Te.message}`,Te);const ke=[...me.values()].sort((Te,re)=>new Date(Te.timestamp).getTime()-new Date(re.timestamp).getTime()),Ne=(B>0?ke.filter(Te=>new Date(Te.timestamp).getTime()>B):ke).filter(Te=>E5(Te.level,S)),Ve=Q.trim().toLowerCase();return Ve?Ne.filter(Te=>{if(Te.message.toLowerCase().includes(Ve)||Te.scope&&Te.scope.toLowerCase().includes(Ve))return!0;if(Te.tags){for(const re of Object.values(Te.tags))if(re!==void 0&&String(re).toLowerCase().includes(Ve))return!0}if(Te.meta){for(const re of Object.values(Te.meta))if(re!=null&&Df(re).toLowerCase().includes(Ve))return!0}return!1}):Ne},[ye,$,S,B,Q]),le=q(H=>{const me=ie.current;me&&(Y.current=!0,me.scrollTo({top:me.scrollHeight,...H?{behavior:H}:{}}))},[]),[Z,ce]=_(!1),Ae=ne(we.length);Gf(()=>{const H=we.length>Ae.current;Ae.current=we.length,H&&(U?le():ce(!0))},[we.length,U,le]),ae(()=>{U&&Z&&ce(!1)},[U,Z]);const Re=q(()=>{F(!0),le("smooth")},[le]),He=q(()=>{if(Y.current){Y.current=!1;return}const H=ie.current;if(!H)return;const me=y5(H,40);F(ke=>ke===me?ke:me)},[]),ut=oe(()=>we.filter(H=>H.tags&&Object.keys(H.tags).length>0||H.meta&&Object.keys(H.meta).length>0).map(H=>`${H.timestamp}|${H.level}|${H.scope??""}|${H.message}`),[we]),St=q(()=>{R(H=>(H&&J(new Set),!H))},[]),Ue=q(()=>{const H=we.map(me=>{const ke=new Date(me.timestamp).toLocaleTimeString(),Ne=me.tags?" "+Object.entries(me.tags).filter(([,Ve])=>Ve).map(([Ve,Te])=>`${Ve}=${Te}`).join(" "):"";return`${ke} [${me.level.toUpperCase()}]${me.scope?` [${me.scope}]`:""}${Ne} ${me.message}`});navigator.clipboard.writeText(H.join(`
125
+ `)).then(()=>{K(!0),setTimeout(()=>K(!1),1500)})},[we]),Ge=x.logs.clear.useMutation(),tt=q(()=>{j(Date.now()),D.reset(),Ge.mutate({...M?{tags:M}:{}})},[D,Ge,M]),We=q(H=>{J(me=>{const ke=new Set(me);return ke.has(H)?ke.delete(H):ke.add(H),ke})},[]),[Ht,At]=_(null),gr=q((H,me)=>{const ke=new Date(H.timestamp).toISOString(),Ne=H.tags?" "+Object.entries(H.tags).filter(([,re])=>re).map(([re,Se])=>`${re}=${Se}`).join(" "):"",Ve=H.meta&&Object.keys(H.meta).length>0?` meta=${JSON.stringify(H.meta)}`:"",Te=`${ke} [${H.level.toUpperCase()}]${H.scope?` [${H.scope}]`:""}${Ne} ${H.message}${Ve}`;navigator.clipboard.writeText(Te).then(()=>{At(me),setTimeout(()=>At(re=>re===me?null:re),1200)})},[]),Qr=q(H=>`${H.timestamp}|${H.level}|${H.scope??""}|${H.message}`,[]);return v("div",{className:L("h-full min-h-0 flex flex-col",p),onClick:H=>H.stopPropagation(),children:[v("div",{className:"flex items-center justify-between px-3 py-1.5 bg-surface-hover/30 gap-2 shrink-0",children:[v("div",{className:"flex items-center gap-2 flex-wrap",children:[u("span",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle font-medium",children:"Logs"}),k&&u(rl,{label:"agent",value:k}),T&&u(rl,{label:"addon",value:T}),A!==void 0&&u(rl,{label:"device",value:`#${A}`}),u("div",{className:"flex rounded border border-border overflow-hidden text-[9px]",children:x5.map(H=>v("button",{type:"button",onClick:()=>E(H==="all"?void 0:H),className:L("px-1.5 py-0.5 capitalize transition-colors",H==="all"&&!S||S===H?"bg-primary/10 text-primary":"text-foreground-subtle hover:bg-surface-hover",H!=="all"&&"border-l border-border"),children:[H,H!=="all"?"+":""]},H))}),u(Ni,{icon:ad,label:U?"Following":"Paused",active:U,onClick:()=>{U?F(!1):Re()}}),u(Ni,{icon:I?ES:wS,label:I?"Collapse":"Expand",active:I,onClick:St,disabled:ut.length===0}),u(Ni,{icon:zr,label:O?"Copied!":"Copy",onClick:Ue,disabled:we.length===0}),u(Ni,{icon:zt,label:"Clear",onClick:tt}),v("div",{className:"relative",children:[u("input",{type:"text",value:Q,onChange:H=>ee(H.target.value),placeholder:"Search…",className:"w-32 pl-1.5 pr-5 py-0.5 rounded border border-border bg-background text-foreground text-[10px] focus:outline-none focus:border-primary/50"}),Q&&u("button",{type:"button",onClick:()=>ee(""),className:"absolute right-1 top-1/2 -translate-y-1/2 text-foreground-subtle hover:text-foreground",title:"Clear search",children:u(bt,{className:"h-2.5 w-2.5"})})]}),$.length>0&&v("span",{className:"text-[9px] text-emerald-400 font-medium",children:["+",$.length," live"]})]}),f&&u("button",{type:"button",onClick:f,className:"text-foreground-subtle hover:text-foreground",children:u(bt,{className:"h-3.5 w-3.5"})})]}),c&&(!t||!r)&&v("div",{className:"flex items-center gap-2 px-3 py-1 border-b border-border/50 bg-surface/50 text-[10px]",children:[!t&&v("label",{className:"flex items-center gap-1",children:[u("span",{className:"text-foreground-subtle",children:"Addon:"}),u("input",{type:"text",value:m,onChange:H=>g(H.target.value),placeholder:"all",className:"w-28 px-1.5 py-0.5 rounded border border-border bg-background text-foreground text-[10px] focus:outline-none focus:border-primary/50"})]}),!r&&v("label",{className:"flex items-center gap-1",children:[u("span",{className:"text-foreground-subtle",children:"Device:"}),u("input",{type:"text",inputMode:"numeric",value:b,onChange:H=>y(H.target.value),placeholder:"all",className:"w-16 px-1.5 py-0.5 rounded border border-border bg-background text-foreground text-[10px] focus:outline-none focus:border-primary/50"})]})]}),v("div",{className:"relative flex-1 min-h-0 flex flex-col",children:[!U&&Z&&v("button",{type:"button",onClick:Re,className:"absolute bottom-2 left-1/2 -translate-x-1/2 z-10 inline-flex items-center gap-1 px-2 py-1 rounded-full border border-primary/40 bg-primary/15 text-primary text-[10px] font-medium shadow-md backdrop-blur-sm hover:bg-primary/25 transition-colors",title:"Jump to the newest log line and resume following",children:[u(ad,{className:"h-3 w-3"}),"Jump to latest"]}),v("div",{ref:ie,onScroll:He,className:L("flex-1 min-h-0 overflow-auto font-mono text-[10px]",l),children:[ue&&v("div",{className:"flex items-center justify-center gap-2 py-6 text-foreground-subtle",children:[u(vt,{className:"h-3.5 w-3.5 animate-spin"}),"Loading logs..."]}),!ue&&we.length===0&&u("div",{className:"py-4 text-center text-foreground-subtle",children:"No logs found"}),we.length>0&&u("table",{className:"w-full",children:u("tbody",{children:we.map(H=>{const me=_f[H.level]??_f.info,ke=me.icon,Ne=Qr(H),Ve=I||W.has(Ne),Te=H.tags&&Object.keys(H.tags).length>0,re=H.meta&&Object.keys(H.meta).length>0,Se=Te||re;return v("tr",{className:L("hover:bg-surface-hover/30 border-b border-border/30",Se&&"cursor-pointer"),onClick:Se?()=>We(Ne):void 0,children:[u("td",{className:"px-2 py-1 text-foreground-subtle whitespace-nowrap align-top w-[70px]",children:new Date(H.timestamp).toLocaleTimeString()}),u("td",{className:L("px-1 py-1 align-top w-5",me.color),children:u(ke,{className:"h-3 w-3"})}),o&&u("td",{className:"px-2 py-1 text-foreground-subtle align-top truncate max-w-[120px]",title:H.scope,children:H.scope?.replace(/^addon:/,"")??""}),u("td",{className:"px-2 py-1 text-foreground break-all",children:v("div",{className:"flex items-start gap-1",children:[Se&&(Ve?u(yt,{className:"h-3 w-3 text-foreground-subtle shrink-0 mt-0.5"}):u(nr,{className:"h-3 w-3 text-foreground-subtle shrink-0 mt-0.5"})),v("div",{className:"flex-1 min-w-0",children:[H.message,Ve&&Se&&v("div",{className:"mt-0.5 pl-3 text-[9px] leading-snug",children:[re&&Object.entries(H.meta).filter(([,ge])=>ge!==void 0&&ge!=="").map(([ge,rt])=>v("div",{className:"break-all",children:[u("span",{className:"text-amber-400/80",children:ge}),u("span",{className:"text-foreground-subtle",children:"="}),u("span",{className:"text-foreground",children:Df(rt)})]},`m-${ge}`)),Te&&Object.entries(H.tags).filter(([,ge])=>ge!==void 0).map(([ge,rt])=>v("div",{className:"break-all",children:[u("span",{className:"text-primary/70",children:ge}),u("span",{className:"text-foreground-subtle",children:"="}),u("span",{className:"text-foreground",children:rt})]},`t-${ge}`))]})]})]})}),u("td",{className:"px-1 py-1 align-top w-5",children:u(w5,{copied:Ht===Ne,onCopy:()=>gr(H,Ne)})})]},Ne)})})})]})]})]})}function Mj({position:e="bottom",className:t,...r}){return u("div",{className:L(e==="bottom"?"absolute bottom-0 left-0 right-0 z-10 border-t border-border bg-surface/95 backdrop-blur-sm":"absolute inset-x-2 bottom-2 z-10 rounded-lg border border-border bg-surface/95 backdrop-blur-sm shadow-xl",t),children:u(My,{maxHeight:"max-h-48",...r})})}function rl({label:e,value:t}){return v("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium",children:[e,": ",t]})}function w5({copied:e,onCopy:t}){return u("button",{type:"button",title:"Copy this row",onClick:r=>{r.stopPropagation(),t()},className:L("rounded p-0.5 transition-colors",e?"text-emerald-400":"text-foreground-subtle/60 hover:text-foreground hover:bg-surface-hover"),children:e?u(Lr,{className:"h-3 w-3"}):u(zr,{className:"h-3 w-3"})})}function Ni({icon:e,label:t,onClick:r,disabled:n,active:s}){return v("button",{type:"button",onClick:r,disabled:n,className:L("inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border transition-colors",s?"border-amber-500/30 bg-amber-500/10 text-amber-400":"border-border text-foreground-subtle hover:text-foreground",n&&"opacity-40 cursor-not-allowed"),children:[u(e,{className:"h-2.5 w-2.5"}),t]})}function k5(e,t,r,n){if(n!==void 0&&(e.source.deviceId??(e.source.type==="device"&&typeof e.source.id=="number"?e.source.id:void 0))!==n||r!==void 0&&(e.source.addonId??(e.source.type==="addon"&&typeof e.source.id=="string"?e.source.id:void 0))!==r)return!1;if(t!==void 0){const s=e.source.nodeId;if(!s||s!==t&&!s.startsWith(`${t}/`))return!1}return!0}var T5={[Ee.AddonStarted]:{icon:Ar,color:"bg-emerald-500/15 text-emerald-400 border-emerald-500/30",label:"Started"},[Ee.AddonInstalled]:{icon:Fs,color:"bg-emerald-500/15 text-emerald-400 border-emerald-500/30",label:"Installed"},[Ee.AddonRestarted]:{icon:vn,color:"bg-blue-500/15 text-blue-400 border-blue-500/30",label:"Restarted"},[Ee.AddonUpdated]:{icon:Dm,color:"bg-blue-500/15 text-blue-400 border-blue-500/30",label:"Updated"},[Ee.AddonStopped]:{icon:Cr,color:"bg-foreground-subtle/10 text-foreground-subtle border-border",label:"Stopped"},[Ee.AddonUninstalled]:{icon:zt,color:"bg-foreground-subtle/10 text-foreground-subtle border-border",label:"Uninstalled"},[Ee.AddonCrashed]:{icon:rs,color:"bg-red-500/15 text-red-400 border-red-500/30",label:"Crashed"},[Ee.AddonError]:{icon:ss,color:"bg-red-500/15 text-red-400 border-red-500/30",label:"Error"},[Ee.DetectionPhaseTransition]:{icon:ur,color:"bg-violet-500/15 text-violet-400 border-violet-500/30",label:"Phase"},[Ee.DetectionResult]:{icon:pE,color:"bg-purple-500/15 text-purple-400 border-purple-500/30",label:"Detection"},[Ee.DetectionEvent]:{icon:Xs,color:"bg-blue-500/15 text-blue-400 border-blue-500/30",label:"Event"},[Ee.DetectionCameraNative]:{icon:ud,color:"bg-cyan-500/15 text-cyan-400 border-cyan-500/30",label:"Camera AI"},[Ee.ProviderMotion]:{icon:$r,color:"bg-orange-500/15 text-orange-400 border-orange-500/30",label:"Motion"},[Ee.MotionOnMotionChanged]:{icon:$r,color:"bg-orange-500/15 text-orange-400 border-orange-500/30",label:"Motion"},[Ee.MotionAnalysis]:{icon:ur,color:"bg-orange-500/10 text-orange-300 border-orange-500/20",label:"Motion analysis"},[Ee.MotionZonesRaw]:{icon:ur,color:"bg-orange-500/10 text-orange-300 border-orange-500/20",label:"Motion zones"},[Ee.ProviderDetection]:{icon:ud,color:"bg-cyan-500/15 text-cyan-400 border-cyan-500/30",label:"Provider Det"},[Ee.PipelineAudioInferenceResult]:{icon:Tm,color:"bg-pink-500/15 text-pink-400 border-pink-500/30",label:"Audio"},[Ee.AgentOnline]:{icon:Ar,color:"bg-emerald-500/15 text-emerald-400 border-emerald-500/30",label:"Agent Online"},[Ee.AgentOffline]:{icon:Cr,color:"bg-red-500/15 text-red-400 border-red-500/30",label:"Agent Offline"},[Ee.DeviceRegistered]:{icon:Fs,color:"bg-emerald-500/15 text-emerald-400 border-emerald-500/30",label:"Registered"},[Ee.DeviceUnregistered]:{icon:zt,color:"bg-red-500/15 text-red-400 border-red-500/30",label:"Unregistered"},[Ee.DeviceStateChanged]:{icon:ur,color:"bg-foreground-subtle/10 text-foreground-subtle border-border",label:"State"},[Ee.EventEmitted]:{icon:$r,color:"bg-amber-500/15 text-amber-400 border-amber-500/30",label:"Event"}};function hc(e,t){const r=T5[e]??{icon:Ar,color:"bg-foreground-subtle/10 text-foreground-subtle border-border",label:e.split(".").pop()??e};if(e===Ee.DeviceStateChanged&&t&&typeof t.capName=="string"){const n=t.capName;return{...r,label:n}}return r}var Pn=Object.freeze([...new Set(Object.values(Ee))].sort()),A5=Object.freeze([Ee.PipelineCameraMetricsSnapshot,Ee.PipelineRunnerLoadSnapshot,Ee.PipelineEngineMetricsSnapshot,Ee.PipelineInferenceResult,Ee.PipelineTrace,Ee.PipelineProgress,Ee.StreamBrokerMetricsSnapshot,Ee.MetricsNodeResourcesSnapshot,Ee.MetricsNodeProcessesSnapshot,Ee.ClusterTopologySnapshot,Ee.MotionAnalysis,Ee.MotionZonesRaw,Ee.DetectionResult,Ee.PipelineAudioInferenceResult,Ee.PlatformProbePhase,Ee.BenchmarkProgress,Ee.ModelDownloadProgress]),C5=new Set(A5),N5=Object.freeze(Pn.filter(e=>!C5.has(e)));function Zi(e,t){if(e===Ee.DetectionPhaseTransition){const s=t.to,i=t.from,a=typeof t.source=="string"?t.source:null,l=typeof t.cooldownMs=="number"?t.cooldownMs:null,o=a?` (${a}${l?`, ${Math.round(l/1e3)}s cooldown`:""})`:"";return s==="active"?`Motion detected — phase active${o}`:s==="watching"?`Cooldown expired — phase watching${o}`:`Phase: ${String(i)} → ${String(s)}${o}`}if(e===Ee.DetectionResult){const s=t.frame?.detections??[];if(s.length===0)return null;const i=new Map;for(const a of s){const l=a,o=l.class??l.macroClass,c=typeof o=="string"?o:"";c&&i.set(c,(i.get(c)??0)+1)}return[...i.entries()].map(([a,l])=>l>1?`${a} ×${l}`:a).join(", ")}if(e===Ee.PipelineAudioInferenceResult){const s=t.frame?.detections??[];return s.length===0?null:s.map(i=>{const a=i,l=a.macroClass??a.class??a.label,o=typeof l=="string"?l:"",c=a.score;return c?`${o} (${Math.round(c*100)}%)`:o}).filter(Boolean).join(", ")}if(e===Ee.DetectionEvent){const s=t.label??t.class,i=t.score??t.confidence,a=[];return typeof s=="string"&&a.push(s),typeof i=="number"&&a.push(`${Math.round(i*100)}%`),a.length>0?a.join(" — "):null}if(e===Ee.ProviderMotion)return t.active===!0?"motion start":"motion stop";if(e===Ee.DeviceStateChanged){const s=t.slice;if(s&&typeof s=="object"){const i=Object.keys(s).filter(a=>a!=="lastFetchedAt"&&a!=="ts");if(i.length>0)return i.slice(0,4).join(", ")+(i.length>4?"…":"")}return null}if(e===Ee.EventEmitted)return(typeof t.eventType=="string"?t.eventType:null)??null;if(e===Ee.MotionOnMotionChanged){const s=t.detected,i=typeof t.source=="string"?t.source:null,a=s===!0?"motion start":s===!1?"motion stop":"motion";return i?`${a} (${i})`:a}if(e===Ee.ProviderDetection||e===Ee.DetectionCameraNative){const s=t.detections??[];if(!Array.isArray(s)||s.length===0)return(typeof t.class=="string"?t.class:null)??null;const i=new Map;for(const a of s){const l=a,o=l.class??l.macroClass,c=typeof o=="string"?o:"";c&&i.set(c,(i.get(c)??0)+1)}return[...i.entries()].map(([a,l])=>l>1?`${a} ×${l}`:a).join(", ")}const r=t.addonId,n=t.error;return n||(r?`addon: ${r}`:null)}function L5(e){const t=e.category;return t===Ee.DetectionResult||t===Ee.PipelineAudioInferenceResult?Zi(t,e.data)!==null:!0}var I5=300;function Py({agentId:e,addonId:t,deviceId:r,defaultCategories:n,categories:s,category:i,maxHeight:a="max-h-96",limit:l=50,showCategoryFilter:o=!0,showFilters:c=!1,liveBuffer:d,onClose:h,className:f}){const p=oe(()=>n??s??N5,[n,s]),m=oe(()=>[...p].sort().join(","),[p]),[g,b]=_(()=>new Set(p)),y=ne(m);ae(()=>{y.current!==m&&(y.current=m,b(new Set(p)))},[m,p]);const S=Ls(I5),E=d??S,k=E.entries,[T,A]=_(!0),[N,C]=_(new Set),[M,P]=_(""),[D,$]=_(!1),[B,j]=_(""),[U,F]=_(0),Y=ne(null),I=ne(null),R=`${e??""}:${t??""}:${String(r??"")}:${i??""}`,O=ne(R);ae(()=>{O.current!==R&&(O.current=R,E.reset(),C(new Set),F(0))},[R,E]),ae(()=>{if(!D)return;const H=me=>{const ke=I.current;ke&&me.target instanceof Node&&!ke.contains(me.target)&&$(!1)};return document.addEventListener("mousedown",H),()=>{document.removeEventListener("mousedown",H)}},[D]);const K=oe(()=>{const H={};return e&&(H.agentId=e),t&&(H.addonId=t),r!==void 0&&(H.deviceId=r),i&&(H.category=i),H},[e,t,r,i]),W=oe(()=>[...g].sort(),[g]),J=oe(()=>{const H={...K,limit:l};return W.length>0&&W.length<Pn.length&&(H.category=W),H},[K,l,oe(()=>W.join(","),[W]),W]),{data:Q,isLoading:ee}=x.systemEvents.getRecent.useQuery(J,{staleTime:3e4}),ie=ne(g);ae(()=>{ie.current=g},[g]);const se=K;x.systemEvents.subscribe.useSubscription(se,{onData:H=>{const me=H;me?.id&&k5(me,e,t,r)&&ie.current.has(me.category)&&E.append(me)}});const be=ne(k.length);ae(()=>{const H=Y.current;if(!H){be.current=k.length;return}const me=be.current;if(be.current=k.length,!(k.length<=me)){if(T&&H.scrollTop<=8)H.scrollTo({top:0});else if(!T&&H.scrollTop>0){const ke=H.firstElementChild?.firstElementChild,Ne=ke instanceof HTMLElement?ke.offsetHeight:28;H.scrollTop+=Ne*(k.length-me)}}},[k.length,T]);const ye=oe(()=>{const H=new Map;for(const Ne of Q??[])H.set(Ne.id,Ne);for(const Ne of k)H.set(Ne.id,Ne);let me=[...H.values()].filter(Ne=>g.has(Ne.category)).filter(L5);U>0&&(me=me.filter(Ne=>new Date(Ne.timestamp).getTime()>U));const ke=M.trim().toLowerCase();return ke&&(me=me.filter(Ne=>{if(Ne.category.toLowerCase().includes(ke)||hc(Ne.category,Ne.data).label.toLowerCase().includes(ke))return!0;const Ve=Zi(Ne.category,Ne.data);if(Ve&&Ve.toLowerCase().includes(ke))return!0;try{if(new Date(Ne.timestamp).toLocaleTimeString().toLowerCase().includes(ke))return!0}catch{}try{if(JSON.stringify(Ne.data).toLowerCase().includes(ke)||JSON.stringify(Ne.source).toLowerCase().includes(ke))return!0}catch{}return!1})),me.sort((Ne,Ve)=>new Date(Ve.timestamp).getTime()-new Date(Ne.timestamp).getTime())},[Q,k,g,M,U]),ue=q(H=>{C(me=>{const ke=new Set(me);return ke.has(H)?ke.delete(H):ke.add(H),ke})},[]),we=q(H=>{b(me=>{const ke=new Set(me);return ke.has(H)?ke.delete(H):ke.add(H),ke})},[]),le=q(()=>{b(new Set(p)),P(""),F(0)},[p]),Z=q(()=>{F(Date.now()),E.reset()},[E]),[ce,Ae]=_(!1),[Re,He]=_(null),ut=q(H=>{const me=new Date(H.timestamp).toISOString(),ke=Zi(H.category,H.data)??"",Ne=ke?` ${ke}`:"";return`${me} [${H.category}]${Ne} data=${JSON.stringify(H.data)}`},[]),St=q(()=>{const H=ye.map(ut);navigator.clipboard.writeText(H.join(`
126
+ `)).then(()=>{Ae(!0),setTimeout(()=>Ae(!1),1500)})},[ye,ut]),Ue=q(H=>{navigator.clipboard.writeText(ut(H)).then(()=>{He(H.id),setTimeout(()=>He(me=>me===H.id?null:me),1200)})},[ut]),Ge=q(()=>{b(new Set(Pn))},[]),tt=q(()=>{b(new Set)},[]),We=oe(()=>{const H=B.trim().toLowerCase();return H?Pn.filter(me=>me.toLowerCase().includes(H)):Pn},[B]),Ht=Pn.length,At=g.size,gr=At===Ht,Qr=gr?"All":`${At}/${Ht}`;return v("div",{className:L("h-full min-h-0 flex flex-col",f),onClick:H=>H.stopPropagation(),children:[v("div",{className:"flex items-center justify-between px-3 py-1.5 bg-surface-hover/30 gap-2 shrink-0",children:[v("div",{className:"flex items-center gap-2 flex-wrap",children:[u("span",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle font-medium",children:"Events"}),e&&u(Li,{label:"agent",value:e}),t&&u(Li,{label:"addon",value:t}),r!==void 0&&u(Li,{label:"device",value:`#${r}`}),i&&u(Li,{label:"category",value:i}),v("button",{type:"button",onClick:()=>{A(H=>!H),!T&&Y.current&&Y.current.scrollTo({top:0,behavior:"smooth"})},className:L("inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border transition-colors",T?"border-border text-foreground-subtle hover:text-foreground":"border-amber-500/30 bg-amber-500/10 text-amber-400"),children:[u(dS,{className:"h-2.5 w-2.5"}),T?"Auto":"Paused"]}),o&&v("div",{className:"relative",ref:I,children:[v("button",{type:"button",onClick:()=>$(H=>!H),className:L("inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border transition-colors",gr?"border-border text-foreground-subtle hover:text-foreground":"border-violet-500/30 bg-violet-500/10 text-violet-400"),title:"Pick events to track",children:[u(Sm,{className:"h-2.5 w-2.5"}),"Filter (",Qr,")"]}),D&&u(R5,{search:B,onSearchChange:j,categories:We,active:g,onToggle:we,onSelectAll:Ge,onSelectNone:tt,onResetDefaults:le})]}),v("button",{type:"button",onClick:le,className:"inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground transition-colors",title:"Reset filters to defaults",children:[u(bl,{className:"h-2.5 w-2.5"}),"Reset"]}),v("button",{type:"button",onClick:Z,className:"inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground transition-colors",title:"Clear visible entries",children:[u(zt,{className:"h-2.5 w-2.5"}),"Clear"]}),v("button",{type:"button",onClick:St,disabled:ye.length===0,className:L("inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border transition-colors",ce?"border-emerald-500/30 bg-emerald-500/10 text-emerald-400":"border-border text-foreground-subtle hover:text-foreground",ye.length===0&&"opacity-40 cursor-not-allowed"),title:"Copy all visible events",children:[u(zr,{className:"h-2.5 w-2.5"}),ce?"Copied!":"Copy"]}),v("div",{className:"relative",children:[u("input",{type:"text",value:M,onChange:H=>P(H.target.value),placeholder:"Search…",className:"w-32 pl-1.5 pr-5 py-0.5 rounded border border-border bg-background text-foreground text-[10px] focus:outline-none focus:border-primary/50"}),M&&u("button",{type:"button",onClick:()=>P(""),className:"absolute right-1 top-1/2 -translate-y-1/2 text-foreground-subtle hover:text-foreground",title:"Clear search",children:u(bt,{className:"h-2.5 w-2.5"})})]}),k.length>0&&v("span",{className:"text-[9px] text-emerald-400 font-medium",children:["+",k.length," live"]})]}),h&&u("button",{type:"button",onClick:h,className:"text-foreground-subtle hover:text-foreground",children:u(bt,{className:"h-3.5 w-3.5"})})]}),v("div",{ref:Y,className:L("flex-1 min-h-0 overflow-auto text-[10px]",a),children:[ee&&v("div",{className:"flex items-center justify-center gap-2 py-6 text-foreground-subtle",children:[u(vt,{className:"h-3.5 w-3.5 animate-spin"}),"Loading events..."]}),!ee&&ye.length===0&&u("div",{className:"py-4 text-center text-foreground-subtle",children:"No events found"}),ye.length>0&&u("div",{className:"divide-y divide-border/30",children:ye.map(H=>{const me=hc(H.category,H.data),ke=me.icon,Ne=Zi(H.category,H.data),Ve=N.has(H.id);return v("div",{className:"flex items-start gap-2 px-3 py-1.5 hover:bg-surface-hover/30 cursor-pointer",onClick:()=>ue(H.id),children:[u("span",{className:"text-foreground-subtle whitespace-nowrap w-[70px] shrink-0 pt-0.5",children:new Date(H.timestamp).toLocaleTimeString()}),u(M5,{copied:Re===H.id,onCopy:()=>Ue(H)}),v("div",{className:"flex-1 min-w-0",children:[v("div",{className:"flex items-center gap-1.5",children:[Ve?u(yt,{className:"h-3 w-3 text-foreground-subtle shrink-0"}):u(nr,{className:"h-3 w-3 text-foreground-subtle shrink-0"}),v("span",{className:L("inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[9px] font-medium",me.color),children:[u(ke,{className:"h-2.5 w-2.5"}),me.label]}),H.source.nodeId&&H.source.nodeId!=="hub"&&u("span",{className:"text-[9px] px-1 py-0.5 rounded bg-foreground-subtle/10 text-foreground-subtle font-mono",children:H.source.nodeId})]}),Ne&&u("p",{className:"text-foreground-subtle text-[10px] mt-0.5 ml-5",children:Ne}),Ve&&v("div",{className:"mt-1 ml-5 text-[9px] bg-surface rounded px-2 py-1.5 space-y-0.5 font-mono overflow-x-auto",children:[v("div",{children:[u("span",{className:"text-primary/70",children:"source"}),u("span",{className:"text-foreground-subtle",children:": "}),u("span",{className:"text-foreground",children:JSON.stringify(H.source)})]}),v("div",{children:[u("span",{className:"text-primary/70",children:"category"}),u("span",{className:"text-foreground-subtle",children:": "}),u("span",{className:"text-foreground",children:H.category})]}),Object.entries(H.data).map(([Te,re])=>v("div",{children:[u("span",{className:"text-primary/70",children:Te}),u("span",{className:"text-foreground-subtle",children:": "}),u("span",{className:"text-foreground break-all",children:typeof re=="object"?JSON.stringify(re):String(re)})]},Te))]})]})]},H.id)})})]})]})}function R5({search:e,onSearchChange:t,categories:r,active:n,onToggle:s,onSelectAll:i,onSelectNone:a,onResetDefaults:l}){return v("div",{className:"absolute z-20 top-full mt-1 left-0 w-72 max-h-80 rounded-md border border-border bg-surface shadow-lg flex flex-col",onClick:o=>o.stopPropagation(),children:[v("div",{className:"flex items-center gap-1 px-2 py-1.5 border-b border-border/50",children:[u(Xn,{className:"h-3 w-3 text-foreground-subtle"}),u("input",{type:"text",value:e,onChange:o=>t(o.target.value),placeholder:"Filter categories…",className:"flex-1 bg-transparent text-[10px] focus:outline-none text-foreground placeholder:text-foreground-subtle",autoFocus:!0}),e&&u("button",{type:"button",onClick:()=>t(""),className:"text-foreground-subtle hover:text-foreground",children:u(bt,{className:"h-2.5 w-2.5"})})]}),v("div",{className:"flex items-center gap-1 px-2 py-1 border-b border-border/50 text-[9px]",children:[u("button",{type:"button",onClick:i,className:"px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground",children:"All"}),u("button",{type:"button",onClick:a,className:"px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground",children:"None"}),u("button",{type:"button",onClick:l,className:"px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground",children:"Defaults"})]}),v("div",{className:"overflow-y-auto flex-1",children:[r.length===0&&u("div",{className:"text-[10px] text-foreground-subtle italic px-2 py-3 text-center",children:"No matches"}),r.map(o=>{const c=n.has(o),d=hc(o),h=d.icon;return v("button",{type:"button",onClick:()=>s(o),className:"w-full flex items-center gap-2 px-2 py-1 text-left hover:bg-surface-hover/40 text-[10px]",children:[u("input",{type:"checkbox",readOnly:!0,checked:c,className:"accent-violet-500"}),v("span",{className:L("inline-flex items-center gap-1 rounded-full border px-1.5 py-0.5 text-[9px] font-medium shrink-0",d.color),children:[u(h,{className:"h-2.5 w-2.5"}),d.label]}),u("span",{className:"text-foreground-subtle font-mono truncate",children:o})]},o)})]})]})}function Pj({position:e="bottom",className:t,...r}){return u("div",{className:L(e==="bottom"?"absolute bottom-0 left-0 right-0 z-10 border-t border-border bg-surface/95 backdrop-blur-sm":"absolute inset-x-2 bottom-2 z-10 rounded-lg border border-border bg-surface/95 backdrop-blur-sm shadow-xl",t),children:u(Py,{maxHeight:"max-h-48",...r})})}function Li({label:e,value:t}){return v("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium",children:[e,": ",t]})}function M5({copied:e,onCopy:t}){return u("button",{type:"button",title:"Copy this event",onClick:r=>{r.stopPropagation(),t()},className:L("rounded p-0.5 transition-colors mt-0.5",e?"text-emerald-400":"text-foreground-subtle/60 hover:text-foreground hover:bg-surface-hover"),children:e?u(Lr,{className:"h-3 w-3"}):u(zr,{className:"h-3 w-3"})})}function Dj({deviceId:e,className:t="",onOpenChild:r}){const n=x.useUtils(),s=x.deviceDiscovery.listDiscovered.useQuery({deviceId:e},{refetchInterval:1e4,retry:!1}),i=x.deviceDiscovery.getStatus.useQuery({deviceId:e},{refetchInterval:1e4,retry:!1}),a=x.deviceDiscovery.refreshDiscovery.useMutation({onSuccess:()=>{n.deviceDiscovery.listDiscovered.invalidate({deviceId:e}),n.deviceDiscovery.getStatus.invalidate({deviceId:e})}}),l=x.deviceDiscovery.adoptDevice.useMutation({onSuccess:()=>{n.deviceDiscovery.listDiscovered.invalidate({deviceId:e})}}),o=x.deviceDiscovery.releaseDevice.useMutation({onSuccess:()=>{n.deviceDiscovery.listDiscovered.invalidate({deviceId:e})}}),[c,d]=_(null),{available:h,adopted:f}=oe(()=>{const E=s.data??[],k=A=>typeof A.metadata.rtspChannel=="number"?A.metadata.rtspChannel:Number.POSITIVE_INFINITY,T=(A,N)=>{const C=k(A),M=k(N);return C!==M?C-M:A.name.localeCompare(N.name)};return{available:E.filter(A=>!A.alreadyAdopted).sort(T),adopted:E.filter(A=>A.alreadyAdopted).sort(T)}},[s.data]),p=i.data,m=p?.lastError??null,g=p?.lastDiscoveryAt??null;async function b(){await a.mutateAsync({deviceId:e}).catch(()=>{})}async function y(E){d(E.childNativeId);try{await l.mutateAsync({deviceId:e,childNativeId:E.childNativeId})}finally{d(null)}}async function S(E){if(E.adoptedDeviceId!=null){d(E.childNativeId);try{await o.mutateAsync({deviceId:e,childDeviceId:E.adoptedDeviceId})}finally{d(null)}}}return v("div",{className:`rounded-xl border border-border bg-surface ${t}`,children:[v("div",{className:"flex items-start justify-between gap-2 border-b border-border px-3 py-2 sm:px-5 sm:py-3",children:[v("div",{className:"min-w-0",children:[u("h3",{className:"text-sm font-semibold text-foreground",children:"Discovered devices"}),v("p",{className:"text-[11px] text-foreground-subtle",children:["Channels behind this hub. Click ",u("span",{className:"font-medium",children:"Add"})," to promote a channel to a managed device, or ",u("span",{className:"font-medium",children:"Remove"})," to detach."]})]}),v("button",{type:"button",onClick:b,disabled:a.isPending,className:"inline-flex items-center gap-1.5 rounded-lg border border-border px-2 py-1.5 sm:px-3 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50 shrink-0",children:[a.isPending?u(vt,{className:"h-3.5 w-3.5 animate-spin"}):u(vn,{className:"h-3.5 w-3.5"}),u("span",{className:"hidden sm:inline",children:"Refresh"})]})]}),m?v("div",{className:"flex items-start gap-2 border-b border-border bg-destructive/10 px-5 py-2 text-[11px] text-destructive",children:[u(ss,{className:"h-3.5 w-3.5 mt-0.5 shrink-0"}),v("span",{children:["Last refresh failed: ",m]})]}):null,s.isLoading?u("div",{className:"flex items-center justify-center py-8 text-foreground-subtle",children:u(vt,{className:"h-5 w-5 animate-spin"})}):h.length===0&&f.length===0?u("div",{className:"px-5 py-8 text-center text-xs text-foreground-subtle",children:"No channels reported by the hub yet. Click Refresh to enumerate."}):v(Ie,{children:[h.length>0?u(Ff,{title:"Available to add",count:h.length,tone:"primary",children:h.map(E=>u($f,{child:E,busy:c===E.childNativeId,onAdopt:y,onRelease:S,onOpenChild:r},E.childNativeId))}):null,f.length>0?u(Ff,{title:"Already adopted",count:f.length,tone:"muted",children:f.map(E=>u($f,{child:E,busy:c===E.childNativeId,onAdopt:y,onRelease:S,onOpenChild:r},E.childNativeId))}):null]}),g!=null?v("div",{className:"border-t border-border px-5 py-2 text-[10px] text-foreground-subtle",children:["Last refreshed ",new Date(g).toLocaleString()]}):null]})}function Ff({title:e,count:t,tone:r,children:n}){return v("div",{className:"border-t border-border",children:[v("div",{className:`flex items-center justify-between border-b px-3 sm:px-5 py-1.5 text-[10px] uppercase tracking-wider ${r==="primary"?"bg-primary/5 text-primary border-primary/30":"bg-surface text-foreground-subtle border-border"}`,children:[u("span",{className:"font-semibold",children:e}),u("span",{className:"font-mono",children:t})]}),u("div",{className:"divide-y divide-border",children:n})]})}function $f({child:e,busy:t,onAdopt:r,onRelease:n,onOpenChild:s}){return v("div",{className:"flex flex-wrap items-center justify-between gap-2 px-3 py-2 sm:px-5 sm:py-3 sm:flex-nowrap sm:gap-3",children:[v("div",{className:"min-w-0 flex-1",children:[v("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[u(P5,{status:e.status}),u("span",{className:"truncate text-sm font-medium text-foreground",children:e.name}),e.metadata.isDoorbell?u("span",{className:"rounded bg-surface-hover px-1.5 py-0.5 text-[9px] uppercase tracking-wide text-foreground-subtle",children:"Doorbell"}):null,e.metadata.isBattery?u("span",{className:"rounded bg-surface-hover px-1.5 py-0.5 text-[9px] uppercase tracking-wide text-foreground-subtle",children:"Battery"}):null,e.metadata.isMultifocal?u("span",{className:"rounded bg-surface-hover px-1.5 py-0.5 text-[9px] uppercase tracking-wide text-foreground-subtle",children:"Multifocal"}):null]}),v("div",{className:"mt-1 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[11px] text-foreground-subtle",children:[typeof e.metadata.rtspChannel=="number"?v("span",{children:["ch ",u("span",{className:"font-mono",children:e.metadata.rtspChannel})]}):null,e.metadata.model?u("span",{className:"truncate max-w-[160px]",children:e.metadata.model}):null,e.metadata.uid?v("span",{className:"font-mono truncate max-w-[140px]",children:[e.metadata.uid.slice(0,12),"…"]}):null]})]}),e.alreadyAdopted?v("div",{className:"flex items-center gap-2",children:[s&&e.adoptedDeviceId!==null?v("button",{type:"button",onClick:()=>s(e.adoptedDeviceId),className:"inline-flex items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-xs text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",title:"Open device detail",children:[u(ym,{className:"h-3.5 w-3.5"}),"Open"]}):null,v("button",{type:"button",onClick:()=>{n(e)},disabled:t,className:"inline-flex items-center gap-1.5 rounded-lg border border-destructive/30 px-3 py-1.5 text-xs text-destructive hover:bg-destructive/10 transition-colors disabled:opacity-50",children:[t?u(vt,{className:"h-3.5 w-3.5 animate-spin"}):u(zt,{className:"h-3.5 w-3.5"}),"Remove"]})]}):v("button",{type:"button",onClick:()=>{r(e)},disabled:t,className:"inline-flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground shadow-sm disabled:opacity-50",children:[t?u(vt,{className:"h-3.5 w-3.5 animate-spin"}):u(gn,{className:"h-3.5 w-3.5"}),"Add"]})]})}function P5({status:e}){switch(e){case"online":return v("span",{className:"inline-flex items-center gap-1 rounded-full border border-emerald-500/40 bg-emerald-500/10 px-2 py-0.5 text-[10px] font-medium text-emerald-500",children:[u(Fc,{className:"h-2.5 w-2.5"})," online"]});case"sleeping":return v("span",{className:"inline-flex items-center gap-1 rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-[10px] font-medium text-amber-500",children:[u(Na,{className:"h-2.5 w-2.5"})," sleeping"]});case"offline":return v("span",{className:"inline-flex items-center gap-1 rounded-full border border-destructive/40 bg-destructive/10 px-2 py-0.5 text-[10px] font-medium text-destructive",children:[u(_m,{className:"h-2.5 w-2.5"})," offline"]});default:return v("span",{className:"inline-flex items-center gap-1 rounded-full border border-border bg-surface px-2 py-0.5 text-[10px] font-medium text-foreground-subtle",children:[u(gm,{className:"h-2.5 w-2.5"})," unknown"]})}}function D5(e,t){if(!e||typeof e!="object")return null;const r=e;if(r.category!==Ee.DeviceStateChanged)return null;const n=r.data;return!n||typeof n!="object"||n.deviceId!==t||typeof n.capName!="string"||!n.slice||typeof n.slice!="object"?null:{capName:n.capName,slice:n.slice}}function _5(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function O5(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.source!="string"?!1:!!t.data&&typeof t.data=="object"&&!Array.isArray(t.data)}function F5(e,t){const r=new Map;for(const[n,s]of Object.entries(e)){const i=s&&typeof s=="object"&&!Array.isArray(s)?s:{value:s};r.set(n,{slice:i,updatedAt:t})}return r}var $5=Object.freeze([...new Set(o0.filter(e=>e.scope==="device").map(e=>e.name))].sort()),B5=1;function U5({deviceId:e,defaultCaps:t,maxHeight:r="max-h-96",onClose:n,className:s}){const[i,a]=_(oe(()=>new Set(t??[]),[t])),[l,o]=_(""),[c,d]=_(!1),[h,f]=_(""),[p,m]=_("normalized"),g=ne(null),[b,y]=_(new Map),[S,E]=_(new Map),[,k]=_(0),T=ne(e);ae(()=>{T.current!==e&&(T.current=e,y(new Map),E(new Map))},[e]);const{data:A,isLoading:N}=x.deviceState.getAllSnapshots.useQuery({},{staleTime:3e4}),C=ne(!1);ae(()=>{if(C.current||!_5(A))return;const le=A[String(e)];if(C.current=!0,!le)return;const Z=Date.now();y(ce=>{const Ae=new Map(ce);for(const[Re,He]of Object.entries(le))Ae.has(Re)||Ae.set(Re,{slice:He,updatedAt:Z});return Ae})},[A,e]),ae(()=>{C.current=!1},[e]);const M=q((le,Z)=>{y(ce=>{const Ae=new Map(ce);return Ae.set(le,{slice:Z,updatedAt:Date.now()}),Ae})},[]),P=Qt(Gt().trpcClient,e)?.deviceOps?.getRawState,D=gc({queryKey:["device-raw-state",e],queryFn:()=>P({deviceId:e}),enabled:P!=null,staleTime:6e4}),$=O5(D.data)?D.data:null,B=D.isFetched&&!D.isError&&$!=null;ae(()=>{p==="raw"&&!B&&m("normalized")},[p,B]);const j=oe(()=>$?F5($.data,D.dataUpdatedAt||Date.now()):new Map,[$,D.dataUpdatedAt]);ae(()=>{const le=setInterval(()=>k(Z=>Z+1),5e3);return()=>clearInterval(le)},[]);const U=oe(()=>{const le=new Set($5);for(const Z of b.keys())le.add(Z);return[...le].sort()},[b]),F=oe(()=>{const le=l.trim().toLowerCase();return[...b.keys()].sort().filter(Z=>i.size>0&&!i.has(Z)?!1:!le||Z.toLowerCase().includes(le)?!0:pc(b.get(Z)?.slice??{},le))},[b,i,l]),Y=q(le=>{a(Z=>{const ce=new Set(Z);return ce.has(le)?ce.delete(le):ce.add(le),ce})},[]),I=q(()=>{a(new Set(t??[])),o("")},[t]),R=q(()=>{a(new Set(U))},[U]),O=q(()=>{a(new Set)},[]),K=q((le,Z)=>{E(ce=>{const Ae=new Map(ce);return Ae.set(le,!Z),Ae})},[]),W=q((le,Z)=>{const ce=S.get(le);return ce!==void 0?ce:Z<B5},[S]),[J,Q]=_(!1),ee=q(()=>{const le={};for(const Z of F){const ce=b.get(Z);ce&&(le[Z]=ce.slice)}navigator.clipboard.writeText(JSON.stringify(le,null,2)).then(()=>{Q(!0),setTimeout(()=>Q(!1),1500)})},[F,b]),ie=oe(()=>{const le=h.trim().toLowerCase();return le?U.filter(Z=>Z.toLowerCase().includes(le)):U},[h,U]),se=U.length,be=i.size,ye=be===0||be===se,ue=ye?"All":`${be}/${se}`;ae(()=>{if(!c)return;const le=Z=>{const ce=g.current;ce&&!ce.contains(Z.target)&&d(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[c]);const we=l.trim().toLowerCase();return v("div",{className:L("h-full min-h-0 flex flex-col",s),onClick:le=>le.stopPropagation(),children:[v("div",{className:"flex items-center justify-between px-3 py-1.5 bg-surface-hover/30 gap-2 shrink-0",children:[v("div",{className:"flex items-center gap-2 flex-wrap",children:[u("span",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle font-medium",children:"State"}),u(z5,{label:"device",value:`#${e}`}),B&&u(G5,{mode:p,onChange:m}),p==="normalized"&&v(Ie,{children:[v("div",{className:"relative",ref:g,children:[v("button",{type:"button",onClick:()=>d(le=>!le),className:L("inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border transition-colors",ye?"border-border text-foreground-subtle hover:text-foreground":"border-violet-500/30 bg-violet-500/10 text-violet-400"),title:"Pick caps to show",children:[u(Sm,{className:"h-2.5 w-2.5"}),"Filter (",ue,")"]}),c&&u(W5,{search:h,onSearchChange:f,caps:ie,active:i,onToggle:Y,onSelectAll:R,onSelectNone:O,onResetDefaults:I})]}),v("button",{type:"button",onClick:I,className:"inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground transition-colors",title:"Reset filters",children:[u(bl,{className:"h-2.5 w-2.5"}),"Reset"]}),v("button",{type:"button",onClick:ee,disabled:F.length===0,className:L("inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border transition-colors",J?"border-emerald-500/30 bg-emerald-500/10 text-emerald-400":"border-border text-foreground-subtle hover:text-foreground",F.length===0&&"opacity-40 cursor-not-allowed"),title:"Copy visible state as JSON",children:[u(zr,{className:"h-2.5 w-2.5"}),J?"Copied!":"Copy"]}),v("div",{className:"relative",children:[u("input",{type:"text",value:l,onChange:le=>o(le.target.value),placeholder:"Search…",className:"w-32 pl-1.5 pr-5 py-0.5 rounded border border-border bg-background text-foreground text-[10px] focus:outline-none focus:border-primary/50"}),l&&u("button",{type:"button",onClick:()=>o(""),className:"absolute right-1 top-1/2 -translate-y-1/2 text-foreground-subtle hover:text-foreground",title:"Clear search",children:u(bt,{className:"h-2.5 w-2.5"})})]}),v("span",{className:"text-[9px] text-emerald-400 font-medium inline-flex items-center gap-1",children:[u("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-400 animate-pulse"}),"live"]})]}),p==="raw"&&$&&v(Ie,{children:[v("span",{className:"inline-flex items-center gap-1 rounded-full border border-sky-500/30 bg-sky-500/15 text-sky-400 px-2 py-0.5 text-[9px] font-medium font-sans",children:["source: ",$.source]}),v("button",{type:"button",onClick:()=>D.refetch(),disabled:D.isFetching,className:L("inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground transition-colors",D.isFetching&&"opacity-60 cursor-wait"),title:"Re-read raw upstream state",children:[u(bl,{className:L("h-2.5 w-2.5",D.isFetching&&"animate-spin")}),"Refresh"]})]})]}),p==="normalized"&&u(H5,{deviceId:e,onPatch:M}),n&&u("button",{type:"button",onClick:n,className:"text-foreground-subtle hover:text-foreground",children:u(bt,{className:"h-3.5 w-3.5"})})]}),u("div",{className:L("flex-1 min-h-0 overflow-auto text-[10px] font-mono",r),children:p==="raw"?j.size===0?u("div",{className:"py-4 text-center text-foreground-subtle font-sans",children:"No raw state"}):u("div",{className:"py-1",children:[...j.entries()].map(([le,Z])=>u(Bf,{capName:le,slice:Z.slice,updatedAt:Z.updatedAt,searchNeedle:"",isPathOpen:W,onToggle:K},le))}):v(Ie,{children:[N&&b.size===0&&v("div",{className:"flex items-center justify-center gap-2 py-6 text-foreground-subtle font-sans",children:[u(vt,{className:"h-3.5 w-3.5 animate-spin"}),"Loading device state..."]}),!N&&b.size===0&&u("div",{className:"py-4 text-center text-foreground-subtle font-sans",children:"No runtime state"}),!N&&b.size>0&&F.length===0&&u("div",{className:"py-4 text-center text-foreground-subtle font-sans",children:"No caps match the filter"}),F.length>0&&u("div",{className:"py-1",children:F.map(le=>{const Z=b.get(le);return Z?u(Bf,{capName:le,slice:Z.slice,updatedAt:Z.updatedAt,searchNeedle:we,isPathOpen:W,onToggle:K},le):null})})]})})]})}function G5({mode:e,onChange:t}){return u("div",{className:"inline-flex items-center rounded border border-border overflow-hidden",children:[{value:"normalized",label:"Normalized"},{value:"raw",label:"Raw"}].map(r=>u("button",{type:"button",onClick:()=>t(r.value),className:L("text-[9px] px-1.5 py-0.5 transition-colors",e===r.value?"bg-violet-500/15 text-violet-400":"text-foreground-subtle hover:text-foreground"),children:r.label},r.value))})}function H5({deviceId:e,onPatch:t}){return x.systemEvents.subscribe.useSubscription({deviceId:e,category:Ee.DeviceStateChanged},{onData:r=>{const n=D5(r,e);n&&t(n.capName,n.slice)}}),null}function Bf({capName:e,slice:t,updatedAt:r,searchNeedle:n,isPathOpen:s,onToggle:i}){const a=e,l=s(a,0),o=Object.entries(t);return v("div",{children:[v("div",{className:"flex items-center gap-1.5 px-3 py-1 hover:bg-surface-hover/30 cursor-pointer select-none",onClick:()=>i(a,l),children:[u(Oy,{open:l,hasChildren:o.length>0}),u("span",{className:"inline-flex items-center gap-1 rounded-full border border-violet-500/30 bg-violet-500/15 text-violet-400 px-2 py-0.5 text-[9px] font-medium font-sans",children:e}),v("span",{className:"text-[9px] text-foreground-subtle font-sans",children:[o.length," ",o.length===1?"key":"keys"]}),v("span",{className:"ml-auto text-[9px] text-foreground-subtle/70 font-sans tabular-nums",children:["updated ",K5(r)]})]}),l&&u("div",{children:o.length===0?u(_y,{depth:1,label:"empty slice"}):o.map(([c,d])=>u(Dy,{path:`${a}.${c}`,nodeKey:c,value:d,depth:1,searchNeedle:n,isPathOpen:s,onToggle:i},c))})]})}function Dy({path:e,nodeKey:t,value:r,depth:n,searchNeedle:s,isPathOpen:i,onToggle:a}){const l=V5(r),o={paddingLeft:`${12+n*14}px`};if(!l)return v("div",{className:"flex items-start gap-1 px-3 py-0.5",style:o,children:[u("span",{className:L("shrink-0",nl(t,s,"text-primary/70")),children:t}),u("span",{className:"text-foreground-subtle",children:":"}),u("span",{className:L("break-all",nl(fc(r),s,j5(r))),children:fc(r)})]});const c=i(e,n);return v("div",{children:[v("div",{className:"flex items-center gap-1 px-3 py-0.5 hover:bg-surface-hover/30 cursor-pointer select-none",style:o,onClick:()=>a(e,c),children:[u(Oy,{open:c,hasChildren:l.entries.length>0}),u("span",{className:nl(t,s,"text-primary/70"),children:t}),u("span",{className:"text-foreground-subtle/70 text-[9px]",children:l.summary})]}),c&&(l.entries.length===0?u(_y,{depth:n+1,label:l.kind==="array"?"empty array":"empty object"}):l.entries.map(([d,h])=>u(Dy,{path:`${e}.${d}`,nodeKey:d,value:h,depth:n+1,searchNeedle:s,isPathOpen:i,onToggle:a},d)))]})}function _y({depth:e,label:t}){return u("div",{className:"px-3 py-0.5 text-foreground-subtle/60 italic",style:{paddingLeft:`${12+e*14}px`},children:t})}function Oy({open:e,hasChildren:t}){return t?e?u(yt,{className:"h-3 w-3 text-foreground-subtle shrink-0"}):u(nr,{className:"h-3 w-3 text-foreground-subtle shrink-0"}):u("span",{className:"inline-block w-3 shrink-0"})}function V5(e){if(Array.isArray(e))return{kind:"array",entries:e.map((t,r)=>[String(r),t]),summary:`[${e.length}]`};if(e&&typeof e=="object"){const t=Object.entries(e);return{kind:"object",entries:t,summary:`{${t.length}}`}}return null}function fc(e){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function j5(e){return e==null?"text-foreground-subtle/60":typeof e=="number"?"text-amber-400":typeof e=="boolean"?e?"text-emerald-400":"text-rose-400":"text-foreground"}function nl(e,t,r){return t&&e.toLowerCase().includes(t)?L(r,"bg-violet-500/20 rounded px-0.5"):r}function pc(e,t){if(Array.isArray(e))return e.some(r=>pc(r,t));if(e&&typeof e=="object"){for(const[r,n]of Object.entries(e))if(r.toLowerCase().includes(t)||pc(n,t))return!0;return!1}return fc(e).toLowerCase().includes(t)}function K5(e){const t=Date.now()-e;if(t<5e3)return"just now";const r=Math.floor(t/1e3);if(r<60)return`${r}s ago`;const n=Math.floor(r/60);return n<60?`${n}m ago`:`${Math.floor(n/60)}h ago`}function z5({label:e,value:t}){return v("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium font-sans",children:[e,": ",t]})}function W5({search:e,onSearchChange:t,caps:r,active:n,onToggle:s,onSelectAll:i,onSelectNone:a,onResetDefaults:l}){return v("div",{className:"absolute z-20 top-full mt-1 left-0 w-72 max-h-80 rounded-md border border-border bg-surface shadow-lg flex flex-col font-sans",onClick:o=>o.stopPropagation(),children:[v("div",{className:"flex items-center gap-1 px-2 py-1.5 border-b border-border/50",children:[u(Xn,{className:"h-3 w-3 text-foreground-subtle"}),u("input",{type:"text",value:e,onChange:o=>t(o.target.value),placeholder:"Filter caps…",className:"flex-1 bg-transparent text-[10px] focus:outline-none text-foreground placeholder:text-foreground-subtle",autoFocus:!0}),e&&u("button",{type:"button",onClick:()=>t(""),className:"text-foreground-subtle hover:text-foreground",children:u(bt,{className:"h-2.5 w-2.5"})})]}),v("div",{className:"flex items-center gap-1 px-2 py-1 border-b border-border/50 text-[9px]",children:[u("button",{type:"button",onClick:i,className:"px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground",children:"All"}),u("button",{type:"button",onClick:a,className:"px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground",children:"None"}),u("button",{type:"button",onClick:l,className:"px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground",children:"Defaults"})]}),v("div",{className:"overflow-y-auto flex-1",children:[r.length===0&&u("div",{className:"text-[10px] text-foreground-subtle italic px-2 py-3 text-center",children:"No matches"}),r.map(o=>v("button",{type:"button",onClick:()=>s(o),className:"w-full flex items-center gap-2 px-2 py-1 text-left hover:bg-surface-hover/40 text-[10px]",children:[u("input",{type:"checkbox",readOnly:!0,checked:n.has(o),className:"accent-violet-500"}),u("span",{className:"inline-flex items-center gap-1 rounded-full border border-violet-500/30 bg-violet-500/15 text-violet-400 px-1.5 py-0.5 text-[9px] font-medium shrink-0",children:o})]},o))]})]})}var sl=500,Q5=[{id:"logs",label:"Logs",icon:Rm},{id:"events",label:"Events",icon:_s},{id:"state",label:"State",icon:_S}];function _j({deviceId:e,containerDeviceId:t,defaultEventCategories:r,defaultStateCaps:n,initialTab:s="events",className:i,maxHeight:a="max-h-96"}){const[l,o]=_(s),c=Ls(sl),d=Ls(sl),h=Ls(sl),f=c.reset,p=d.reset,m=h.reset;return ae(()=>{f(),p(),m()},[e,f,p,m]),v("div",{className:L("flex flex-col h-full min-h-0",i),children:[u("div",{className:"flex items-center gap-1 mb-2 shrink-0",children:Q5.map(({id:g,label:b,icon:y})=>v("button",{type:"button",onClick:()=>o(g),className:L("inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[11px] font-medium transition-colors",l===g?"bg-primary/15 text-primary border border-primary/30":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover border border-transparent"),children:[u(y,{className:"h-3.5 w-3.5"}),b]},g))}),v("div",{className:"flex-1 min-h-0 overflow-hidden",children:[l==="logs"&&u(My,{...t!==void 0?{containerDeviceId:t}:{deviceId:e},maxHeight:a,showFilters:!1,liveBuffer:c}),l==="events"&&u(Py,{deviceId:e,defaultCategories:r,maxHeight:a,showCategoryFilter:!0,liveBuffer:d}),l==="state"&&u(U5,{deviceId:e,defaultCaps:n,maxHeight:a,liveBuffer:h})]})]})}function Oj({label:e,icon:t,title:r="Confirm action",description:n,confirmLabel:s,triggerVariant:i="outline",confirmVariant:a="danger",size:l="sm",disabled:o,className:c,action:d,onSuccess:h}){const[f,p]=_(!1),[m,g]=_(!1),[b,y]=_(null),S=async()=>{y(null),g(!0);try{const E=await d();h?.(E),p(!1)}catch(E){y(E instanceof Error?E.message:String(E))}finally{g(!1)}};return v(Ie,{children:[v(tr,{type:"button",variant:i,size:l,disabled:o,onClick:()=>{y(null),p(!0)},className:c,children:[t&&u(t,{className:"h-3.5 w-3.5"}),e]}),u($c,{open:f,onOpenChange:E=>!m&&p(E),children:v(Ia,{children:[v(Bc,{children:[v(Gc,{className:"flex items-center gap-2",children:[u(ss,{className:"h-4 w-4 text-amber-400"}),r]}),typeof n=="string"?u(Hc,{children:n}):n]}),b&&u("div",{className:L("mt-2 px-3 py-2 rounded border border-danger/40 bg-danger/10","text-xs text-danger"),children:b}),v(Uc,{children:[u(tr,{type:"button",variant:"ghost",size:l,disabled:m,onClick:()=>p(!1),children:"Cancel"}),v(tr,{type:"button",variant:a,size:l,disabled:m,onClick:()=>{S()},children:[m&&u(vt,{className:"h-3.5 w-3.5 animate-spin"}),s??e]})]})]})})]})}function q5(e,t){const r=document.createElement("a");r.href=t,r.download=e,document.body.appendChild(r),r.click(),document.body.removeChild(r)}function Fj({trpc:e,deviceId:t,deviceName:r,size:n="sm",className:s}){const[i,a]=_(!1),[l,o]=_(!1),[c,d]=_(null),h=r.replace(/[^a-zA-Z0-9_.-]+/g,"_"),f=q(async T=>{a(!0),d(null),o(!1);try{const A=await e.snapshot.getSnapshot.query({deviceId:t,force:!0});if(!A)throw new Error("No snapshot available");const N=`data:${A.contentType};base64,${A.base64}`;if(T==="copy")try{await navigator.clipboard.writeText(N)}catch{throw new Error("Clipboard unavailable")}else{const C=A.contentType.includes("png")?"png":"jpg";q5(`${h}-${new Date().toISOString().replace(/[:.]/g,"-")}.${C}`,N)}o(!0),setTimeout(()=>o(!1),1500)}catch(A){d(A instanceof Error?A.message:String(A))}finally{a(!1)}},[e,t,h]),p=n==="md"?"h-9 px-3 text-sm gap-2":"h-7 px-2.5 text-[11px] gap-1.5",[m,g]=_(null),[b,y]=_(!1),S=()=>{y(!1),g(setTimeout(()=>{y(!0),f("copy")},600))},E=()=>{m&&(clearTimeout(m),g(null)),b||f("download")},k=()=>{m&&(clearTimeout(m),g(null))};return v("button",{type:"button",title:"Click to download · long-press to copy",disabled:i,onPointerDown:S,onPointerUp:E,onPointerLeave:k,onPointerCancel:k,className:L("inline-flex items-center justify-center rounded-lg font-medium border border-border","text-foreground-subtle hover:text-foreground hover:bg-surface-hover","disabled:opacity-50 transition-colors",p,c&&"border-danger/40 text-danger",s),children:[i?u(vt,{className:"h-3.5 w-3.5 animate-spin"}):l?u(Lr,{className:"h-3.5 w-3.5 text-success"}):u(pm,{className:"h-3.5 w-3.5"}),"Snapshot"]})}function Y5(e){const t=Date.now()-e;return t<6e4?"just now":t<36e5?`${Math.floor(t/6e4)}m ago`:t<864e5?`${Math.floor(t/36e5)}h ago`:`${Math.floor(t/864e5)}d ago`}function $j({history:e,limit:t=5,latestIsFresh:r,className:n}){if(e.length===0)return null;const s=r?gS:_s,i=e.slice(0,t);return v("div",{className:L("rounded-lg border border-border bg-surface px-3 py-2",n),children:[v("div",{className:"flex items-center gap-2 mb-2",children:[u(s,{className:L("h-4 w-4 text-amber-400",r&&"animate-pulse")}),u("span",{className:"text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle",children:"Recent presses"}),u("span",{className:"ml-auto rounded-full bg-foreground-subtle/10 px-1.5 py-0.5 text-[10px] font-medium text-foreground-subtle border border-border",children:e.length})]}),u("ul",{className:"space-y-1",children:i.map(a=>v("li",{className:"flex items-center justify-between text-[11px]",title:new Date(a.timestamp).toLocaleString(),children:[u("span",{className:"text-foreground",children:Y5(a.timestamp)}),u("span",{className:"text-foreground-subtle font-mono text-[10px]",children:new Date(a.timestamp).toLocaleTimeString()})]},`${a.deviceId}-${a.timestamp}`))})]})}function Bj({items:e,header:t,triggerClassName:r,title:n="More actions"}){const[s,i]=_(!1),a=e.filter(l=>!l.hidden);return a.length===0?null:v(QE,{open:s,onOpenChange:i,children:[u(qE,{title:n,className:L("inline-flex items-center justify-center rounded-lg p-2","text-foreground-subtle hover:text-foreground hover:bg-surface-hover","border border-transparent transition-colors",r),children:u(FS,{className:"h-4 w-4"})}),v(YE,{className:"left-auto right-0 mt-1 min-w-[200px] p-1",children:[t&&u("div",{className:"px-2 py-1 text-[10px] uppercase tracking-wider text-foreground-subtle",children:t}),u("ul",{className:"space-y-0.5",children:a.map((l,o)=>v("li",{children:[l.separatorBefore&&o>0&&u("div",{className:"my-1 h-px bg-border"}),v("button",{type:"button",disabled:l.disabled,onClick:()=>{l.disabled||(l.onClick(),i(!1))},className:L("flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left text-[12px]","transition-colors disabled:opacity-40 disabled:cursor-not-allowed",l.danger?"text-foreground hover:bg-danger/10 hover:text-danger":"text-foreground hover:bg-surface-hover"),children:[l.icon&&u(l.icon,{className:L("h-3.5 w-3.5 shrink-0 mt-0.5",l.danger&&"text-danger/80")}),v("span",{className:"flex-1 min-w-0",children:[u("span",{className:"block leading-tight",children:l.label}),l.description&&u("span",{className:"block mt-0.5 text-[10px] text-foreground-subtle leading-tight",children:l.description})]})]})]},l.id))})]})]})}var X5=[{value:"view",label:"View",icon:Xs,hint:"Read-only — queries + subscriptions"},{value:"create",label:"Create",icon:lE,hint:"Mutations that create or update"},{value:"delete",label:"Delete",icon:zt,hint:"Destructive ops (delete/revoke/reset/…)"}],Z5=["device","system"];function J5(){return{type:"capability",target:"",access:["view"]}}function eO(e){if(e==null)return[];const t=new Set;for(const r of e)if(r.type==="device")for(const n of r.targets)t.add(n);return[...t]}function tO(e,t,r,n){let s;switch(e){case"addon":s=r;break;case"capability":s=n;break;case"category":s=Z5.map(a=>({value:a,label:a}));break}if(t==null)return s;const i=new Set(t.filter(a=>a.type!=="device"&&a.type===e).map(a=>a.target));return s.filter(a=>i.has(a.value))}function rO(e,t){if(t==null)return["view","create","delete"];const r=t.filter(s=>s.type!==e.type?!1:s.type==="device"&&e.type==="device"?s.targets.some(i=>e.targets.includes(i)):s.type!=="device"&&e.type!=="device"?s.target===e.target:!1);if(r.length===0)return[];const n=new Set;for(const s of r)for(const i of s.access)n.add(i);return[...n]}function Uj({value:e,onChange:t,clampToParent:r,emptyHint:n}){const{data:s}=nk(),{data:i}=xg({}),a=oe(()=>(s??[]).map(m=>({value:m.manifest.id,label:m.manifest.id})).sort((m,g)=>m.label.localeCompare(g.label)),[s]),l=oe(()=>[...i0].sort().map(m=>({value:m,label:m})),[]),o=oe(()=>(i??[]).map(m=>({value:String(m.id),label:`${m.name} (#${m.id} · ${m.addonId})`})).sort((m,g)=>m.label.localeCompare(g.label)),[i]),c=oe(()=>r==null?null:eO(r),[r]),d=(m,g)=>{const b=[...g];switch(m){case"category":return{type:"category",target:"device",access:b};case"capability":return{type:"capability",target:"",access:b};case"addon":return{type:"addon",target:"",access:b};case"device":return{type:"device",targets:[],access:b}}},h=(m,g)=>{t(e.map((b,y)=>{if(y!==m)return b;if(g.type!==void 0&&g.type!==b.type)return d(g.type,g.access??b.access);const S=[...g.access??b.access];return b.type==="device"?{type:"device",targets:[...g.targets??b.targets],access:S}:b.type==="category"?{type:"category",target:g.target??b.target,access:S}:b.type==="capability"?{type:"capability",target:g.target??b.target,access:S}:{type:"addon",target:g.target??b.target,access:S}}))},f=m=>{t(e.filter((g,b)=>b!==m))},p=()=>{t([...e,J5()])};return v("div",{className:"space-y-2",children:[e.length===0&&n&&u("div",{className:"text-[10px] text-foreground-subtle italic px-2 py-2",children:n}),e.map((m,g)=>{const b=rO(m,r);return v("div",{className:"flex flex-wrap items-start gap-1.5 rounded border border-border bg-surface px-2 py-1.5",children:[v("select",{value:m.type,onChange:y=>h(g,{type:y.target.value}),className:"rounded border border-border bg-background px-2 py-1 text-[11px] focus:outline-none focus:ring-1 focus:ring-primary",children:[u("option",{value:"category",children:"category"}),u("option",{value:"capability",children:"capability"}),u("option",{value:"addon",children:"addon"}),u("option",{value:"device",children:"device"})]}),m.type==="device"?u(nO,{value:m.targets,choices:o,clampToParent:c,onChange:y=>h(g,{targets:y})}):v("select",{value:m.target,onChange:y=>h(g,{target:y.target.value}),className:"flex-1 min-w-[160px] rounded border border-border bg-background px-2 py-1 text-[11px] font-mono focus:outline-none focus:ring-1 focus:ring-primary",children:[v("option",{value:"",children:["— pick ",m.type," —"]}),tO(m.type,r,a,l).map(y=>u("option",{value:y.value,children:y.label},y.value))]}),u("div",{className:"flex items-center gap-1",children:X5.map(({value:y,label:S,icon:E,hint:k})=>{const T=m.access.includes(y),A=r!=null&&!b.includes(y)&&!T;return v("label",{title:A?`${k} — not granted by your scope`:k,className:`inline-flex items-center gap-1 rounded px-1.5 py-1 text-[10px] cursor-pointer transition-colors ${T?"bg-primary/15 text-primary font-medium":"text-foreground-subtle hover:bg-foreground-subtle/10"} ${A?"opacity-40 cursor-not-allowed":""}`,children:[u("input",{type:"checkbox",checked:T,disabled:A,onChange:N=>{const C=new Set(m.access);N.target.checked?C.add(y):C.delete(y),h(g,{access:[...C]})},className:"sr-only"}),u(E,{className:"h-3 w-3"}),S]},y)})}),u("button",{type:"button",onClick:()=>f(g),className:"rounded p-1 text-foreground-subtle hover:bg-danger/10 hover:text-danger transition-colors",title:"Remove scope",children:u(bt,{className:"h-3 w-3"})})]},g)}),v("button",{type:"button",onClick:p,className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-foreground-subtle hover:text-foreground hover:bg-foreground-subtle/10 transition-colors",children:[u(gn,{className:"h-3 w-3"}),"Add scope"]})]})}function nO({value:e,choices:t,clampToParent:r,onChange:n}){const[s,i]=_(""),a=oe(()=>{const d=r==null?t:t.filter(f=>r.includes(f.value)),h=new Set(e);return d.filter(f=>!h.has(f.value))},[t,r,e]),l=d=>t.find(h=>h.value===d)?.label??`#${d}`,o=d=>{d&&(n([...e,d]),i(""))},c=d=>{n(e.filter(h=>h!==d))};return v("div",{className:"flex-1 min-w-[160px] flex flex-wrap items-center gap-1",children:[e.length===0&&u("span",{className:"text-[10px] text-foreground-subtle italic px-1",children:"no devices selected"}),e.map(d=>v("span",{className:"inline-flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-mono text-primary",children:[l(d),u("button",{type:"button",onClick:()=>c(d),className:"hover:text-danger transition-colors",title:"Remove device",children:u(bt,{className:"h-2.5 w-2.5"})})]},d)),a.length>0&&v("select",{value:s,onChange:d=>o(d.target.value),className:"rounded border border-border bg-background px-1.5 py-0.5 text-[10px] focus:outline-none focus:ring-1 focus:ring-primary",children:[u("option",{value:"",children:"+ add device…"}),a.map(d=>u("option",{value:d.value,children:d.label},d.value))]})]})}function Gj(e){for(const t of e){if(t.type==="device"){if(t.targets.length===0)return"Scope device: pick at least one device"}else if(t.target.trim().length===0)return`Scope ${t.type}: pick a target`;if(t.access.length===0){const r=t.type==="device"?`[${t.targets.join(",")}]`:t.target;return`Scope ${t.type}:${r}: pick at least one access`}}return null}var Fy=Nr("camstack:zone-editing",null);function Hj({children:e}){const[t,r]=_(!1),[n,s]=_(null),[i,a]=_(null),[l,o]=_(null),c=q(S=>{r(S),S||(s(null),a(null),o(null))},[]),d=q(S=>{s(S)},[]),h=q(S=>{a(S)},[]),f=q(S=>{r(!0),a(null),s(S),o(null)},[]),p=q(()=>{r(!1),s(null),a(null),o(null)},[]),m=q(S=>{a(S.id),o(S)},[]),g=q(S=>{o(E=>E===null?E:{...E,...S})},[]),b=q(()=>{o(null)},[]),y=oe(()=>({editing:t,drawingKind:n,selectedZoneId:i,editingDraft:l,setEditing:c,setDrawingKind:d,setSelectedZoneId:h,startDrawing:f,exitEditing:p,enterDraft:m,updateDraft:g,discardDraft:b}),[t,n,i,l,c,d,h,f,p,m,g,b]);return u(Fy.Provider,{value:y,children:e})}function Vj(){return ct(Fy)}var Uf=500,sO=800;function Ii(e,t,r){try{const n=e.live;if(!n)return null;const s=n.onEvent;return!s||typeof s.subscribe!="function"?null:s.subscribe({category:t},{onData:r})}catch{return null}}function Ri(e,t){return e?.id===t}function jj(e,t){const[r,n]=_(null),[s,i]=_(null),[a,l]=_(null),[o,c]=_("watching"),d=ne(void 0),h=ne(void 0),f=ne(void 0);return ae(()=>{if(t===null)return;const p=Ii(e,"detection.motion-analysis",m=>{const g=m;if(!Ri(g?.source,t))return;const b=g.data;!b?.regions||b.regions.length===0||(n({zones:b.regions.map(y=>({...y.bbox,intensity:y.intensity})),frameWidth:b.frameWidth,frameHeight:b.frameHeight}),d.current&&clearTimeout(d.current),d.current=setTimeout(()=>n(null),Uf))});return()=>{p?.unsubscribe(),d.current&&clearTimeout(d.current)}},[e,t]),ae(()=>{if(t===null)return;const p=Ii(e,"detection.motion-zones-raw",m=>{const g=m;if(!Ri(g?.source,t))return;const b=g.data;b?.zones&&(i({boxes:b.zones.map(y=>({bbox:y.bbox,changeScore:y.changeScore})),frameWidth:b.frameSize?.width??0,frameHeight:b.frameSize?.height??0,motionScore:b.zones.length>0?b.zones.reduce((y,S)=>y+S.changeScore,0)/b.zones.length:0}),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>i(null),Uf))});return()=>{p?.unsubscribe(),h.current&&clearTimeout(h.current)}},[e,t]),ae(()=>{if(t===null)return;const p=Ii(e,"detection.result",m=>{const g=m;if(!Ri(g?.source,t))return;const b=g.data?.frame;b?.detections?.length&&(l({detections:b.detections,frameWidth:b.width,frameHeight:b.height}),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>l(null),sO))});return()=>{p?.unsubscribe(),f.current&&clearTimeout(f.current)}},[e,t]),ae(()=>{if(t===null)return;const p=Ii(e,"detection.phase-transition",m=>{const g=m;Ri(g?.source,t)&&g.data?.to&&c(g.data.to)});return()=>{p?.unsubscribe()}},[e,t]),{motion:r,motionRaw:s,detection:a,phase:o}}function Kj(e,t,r=5e3){const[n,s]=_([]);ae(()=>{if(t===null)return;let p=!1;const m=()=>{e.webrtcSession.listStreams.query({deviceId:t}).then(b=>{p||s(b)}).catch(()=>{})};m();const g=setInterval(m,r);return()=>{p=!0,clearInterval(g)}},[e,t,r]);const[i,a]=_(null);ae(()=>{if(t===null)return;let p=!1;return e.pipelineOrchestrator&&e.pipelineOrchestrator.getCameraMetrics.query({deviceId:t}).then(m=>{p||!m||a({phase:m.phase,detectionFps:m.actualFps,avgInferenceMs:m.avgInferenceTimeMs,droppedFrames:m.droppedFrames})}).catch(()=>{}),()=>{p=!0}},[e,t]),Ma("pipeline.camera-metrics-snapshot",p=>{if(t===null)return;const m=p.data;m.deviceId!==t||!m.metrics||a({phase:m.metrics.phase,detectionFps:m.metrics.actualFps,avgInferenceMs:m.metrics.avgInferenceTimeMs,droppedFrames:m.metrics.droppedFrames})});const{streams:l,hasWebrtc:o}=oe(()=>t===null||n.length===0?{streams:[],hasWebrtc:!1}:{streams:n.map(p=>({id:p.id,label:p.label,target:p.target,status:p.status,inputFps:p.inputFps,decodeFps:p.decodeFps,bitrateKbps:p.bitrateKbps})),hasWebrtc:!0},[t,n]),c=q(async()=>{if(e.turnProvider)try{return(await e.turnProvider.getTurnServers.query()).map(p=>({urls:typeof p.urls=="string"?p.urls:[...p.urls],...p.username!==void 0?{username:p.username}:{},...p.credential!==void 0?{credential:p.credential}:{}}))}catch{return}},[e]),d=q(async(p,m)=>{if(t===null)throw new Error("No device selected");const g=await e.webrtcSession.createSession.mutate({deviceId:t,target:p,hints:m}),b=await c();return{sessionId:g.sessionId,sdpOffer:g.sdpOffer,...b?{iceServers:b}:{}}},[e,t,c]),h=q(async(p,m,g)=>{if(t===null)throw new Error("No device selected");return e.webrtcSession.handleOffer.mutate({deviceId:t,target:p,sdpOffer:m,...g!==void 0?{sessionId:g}:{}})},[e,t]),f=q(async(p,m)=>{if(t===null)throw new Error("No device selected");await e.webrtcSession.handleAnswer.mutate({deviceId:t,sessionId:p,sdpAnswer:m})},[e,t]);return{streams:l,hasWebrtc:o,pipelineMetrics:i,createSession:d,handleOffer:h,getIceServers:c,addIceCandidate:q(async(p,m)=>{t!==null&&await e.webrtcSession.addIceCandidate.mutate({deviceId:t,sessionId:p,candidate:m.candidate??"",sdpMid:m.sdpMid??null,sdpMLineIndex:m.sdpMLineIndex??null}).catch(()=>{})},[e,t]),getIceCandidates:q(async p=>t===null?{candidates:[],done:!0}:e.webrtcSession.getIceCandidates.query({deviceId:t,sessionId:p}),[e,t]),sendAnswer:f,closeSession:q(async p=>{t!==null&&await e.webrtcSession.closeSession.mutate({deviceId:t,sessionId:p}).catch(()=>{})},[e,t]),getSessionState:q(async p=>{if(t===null)return{pendingRenegotiation:null};try{return await e.webrtcSession.getSessionState.query({deviceId:t,sessionId:p})}catch{return{pendingRenegotiation:null}}},[e,t])}}function zj(e){const t=e?.deviceId??null,r=e?.historyLimit??20,n=ig("doorbell.onPressed",t!==null?a=>a.deviceId===t:void 0),[s,i]=_([]);return ae(()=>{n&&i(a=>{if(a.length>0&&a[0].deviceId===n.deviceId&&a[0].timestamp===n.timestamp)return a;const l=[n,...a];return l.length>r?l.slice(0,r):l})},[n,r]),{latest:n??null,history:s}}function Wj(e){const t=Gt(),r=oe(()=>e?JSON.stringify(e):"",[e]),[n,s]=_(()=>t.listDevices(e));return ae(()=>{const i=()=>{s(t.listDevices(e))};i();let a=null,l=null;try{a=t.onDeviceAdded(i),l=t.onDeviceRemoved(i)}catch{}const o=t.subscribeConnectionEvents(c=>{c==="connected"&&i()});return()=>{a?.(),l?.(),o()}},[t,e,r]),n}function Qj(e){const t=Gt(),[r,n]=_(()=>e===null?null:t.getDevice(e));return ae(()=>{if(e===null){n(null);return}const s=()=>{n(t.getDevice(e))};s();let i=null,a=null;try{i=t.onDeviceAdded(s),a=t.onDeviceRemoved(s)}catch{}const l=t.subscribeConnectionEvents(o=>{o==="connected"&&s()});return()=>{i?.(),a?.(),l()}},[t,e]),r}function qj(e,t,r){const n=Gt();return gc({queryKey:e,queryFn:()=>t(n)(),...r})}function Yj(e,t){const r=Gt();return Hy({mutationFn:n=>e(r)(n),...t})}function Xj(e,t){const r=Gt(),n=ts(),[s,i]=_(r.connectionVersion);ae(()=>r.subscribeConnectionEvents((o,c)=>{o==="connected"&&i(c)}),[r]);const a=t.join("|"),l=JSON.stringify(e);ae(()=>{const o=[],c=()=>{const d=JSON.parse(l),h=d.length===1&&Array.isArray(d[0])?d:[d];n.invalidateQueries({queryKey:h})};c();for(const d of a.split("|"))if(d)try{o.push(r.subscribeEvent(d,c))}catch{}return()=>{for(const d of o)d()}},[r,n,a,l,s])}function Zj(e,t,r){const n=ne(null),s=ne(null);(n.current===null||s.current!==e)&&(n.current=e0(e),s.current=e);const i=ne(void 0),a=ne(null),l=a.current;return t===null?(i.current=void 0,a.current=null):(i.current===void 0||l===null||l.source!==n.current||l.deviceId!==t||l.capName!==r)&&(i.current=t0(n.current,t,r),a.current={source:n.current,deviceId:t,capName:r}),Tr(i.current)}export{Sj as AddonGlobalSettingsForm,c3 as AgentStepEditor,SA as AlarmHeroCard,xA as AlarmPanelInlineControl,k3 as AppShell,$i as ArcKnob,Lj as AudioClassificationList,Nj as AudioLevelWaveform,Cj as AudioWaveform,SN as AutotrackSection,OO as BTN_COMPACT,$O as BTN_COMPACT_DANGER,FO as BTN_COMPACT_PRIMARY,BO as BTN_COMPACT_WARNING,Hn as Badge,wC as BatteryBadge,Ym as BottomSheet,s3 as Breadcrumb,CT as BrightnessPanel,tr as Button,Qw as ButtonControl,qw as ButtonHeroCard,Vw as CENTER,HO as CHIP_ACTIVE,GO as CHIP_BASE,VO as CHIP_INACTIVE,ai as CLASS_COLORS,Vn as COLUMN_BREAKPOINT_CLASS,zV as COLUMN_PRIORITY,qV as CONTROL_CAP_NAMES,ZA as CONTROL_FILLS,KI as CameraStreamPlayer,Bm as Card,HE as Checkbox,WV as ChildSectionAccordion,RT as ClimatePanel,E3 as CodeBlock,BE as CollapsibleCard,MI as ConfigFormBuilder,ei as ConfigFormField,jc as ConfigSchemaField,Oj as ConfirmActionButton,y3 as ConfirmDialogProvider,yN as ConsumablesPanel,Ad as ContainerChildrenProvider,ZV as ContainerPrimaryHero,la as ControlColumn,DA as ControlHeroCard,PA as ControlInlineControl,zg as ControlPanel,o5 as CopyButton,tk as CoverHeroCard,Zw as CoverInlineControl,QV as CoverPanel,cj as CustomFieldRenderersProvider,tj as DEFAULT_COLOR,KV as DEVICE_COLUMNS,ov as DEVICE_LIST_PAGE_SIZE_KEY,av as DEVICE_LIST_PAGE_SIZE_OPTIONS,Tl as DEVICE_ROLE_META,XA as DEVICE_TYPE_CONTROL,$s as DEVICE_TYPE_META,i3 as DataTable,rj as DetectionCanvas,_I as DetectionOverlay,nj as DetectionResultTree,nN as DevShell,_j as DeviceActivityPanel,Gd as DeviceBatchToolbar,T3 as DeviceCard,uj as DeviceContextProvider,Aj as DeviceExportPanel,A3 as DeviceGrid,tu as DeviceItem,c2 as DeviceList,$c as Dialog,Ia as DialogContent,Hc as DialogDescription,Uc as DialogFooter,Bc as DialogHeader,Gc as DialogTitle,WO as DialogTrigger,Dj as DiscoveryPanel,$j as DoorbellRecentPanel,QO as Dropdown,YO as DropdownContent,XO as DropdownItem,qO as DropdownTrigger,yg as DummyHeroCard,rk as DummyInline,ag as EmptyState,oa as ErrorBox,Py as EventStream,Gw as FILL,cA as FanHeroCard,NA as FanInlineControl,NT as FanPanel,w3 as FilterBar,Pj as FloatingEventStream,Mj as FloatingLogStream,n3 as FloatingPanel,v3 as FormField,AO as GRID_GAP,LO as GRID_PAIRED,NO as GRID_QUICK_STATS,Al as GripTrack,NL as HOST_WIDGETS,Y_ as HlsVideo,Hg as HoverZoomImage,lT as HumidifierHeroCard,aT as HumidifierInlineControl,UO as INPUT_COMPACT,iC as IconAction,$m as IconButton,kT as ImageHeroCard,wT as ImageInlineControl,ij as ImageSelector,aj as InferenceConfigSelector,El as Input,Bj as KebabMenu,S3 as KeyValueList,CO as LIST_ROW,Um as Label,Zk as LawnMowerHeroCard,Xk as LawnMowerInlineControl,aA as LightHeroCard,AA as LightInlineControl,JT as LockHeroCard,TA as LockInlineControl,AT as LockPanel,My as LogStream,Z2 as LoginForm,jg as MODE_COLOR,_v as MaskShapeCanvas,pA as MediaPlayerHeroCard,MA as MediaPlayerInlineControl,FT as MediaPlayerPanel,XE as MobileDrawer,FN as MotionZonesSettings,sI as NodeMultiSelectField,f3 as NodePicker,nI as NodeSelectField,XV as OfflineBadge,qu as PHASE_CONFIG,Sd as PRIORITY,gg as PTZOverlay,b3 as PageHeader,Rj as PhaseIcon,ej as PipelineBuilder,JV as PipelineRuntimeSelector,Xa as PipelineStep,u3 as PipelineTreeMatrix,mj as PlayerOverlaysProvider,QE as Popover,YE as PopoverContent,YV as PopoverRowAction,qE as PopoverTrigger,m3 as ProviderBadge,pN as PtzPanel,Yv as QrCode,Hw as RIGHT,Ag as ROLE_DESCRIPTOR,Qg as RadialGauge,CL as RecordingPanel,Ij as ResponseLog,kO as SECTION_BODY,EO as SECTION_CARD,wO as SECTION_HEADER,IO as SPLIT_PANEL_OUTER,RO as SPLIT_PANEL_SIDE,TO as STACK_GAP,MT as STATE_COLOR,Uj as ScopePicker,tg as ScrollArea,aa as Select,mw as SemanticBadge,_k as SensorHeroCard,Ak as SensorInlineControl,Yc as SensorValueAtom,Gm as Separator,xd as Sidebar,yd as SidebarItem,GE as Skeleton,a3 as SlideOverPanel,jw as SlideToggle,Fj as SnapshotButton,x3 as StatCard,U5 as StateValuesStream,p3 as StatusBadge,sj as StepTimings,o3 as StepTreeMaster,vg as Stepper,Tj as StreamBrokerSelector,kj as StreamPanel,VE as Switch,uA as SwitchHeroCard,wA as SwitchInlineControl,Xc as SwitchPanel,dw as SystemProvider,PO as TEXT_FIELD_LABEL,kr as TEXT_HINT,_O as TEXT_METRIC,MO as TEXT_SECTION_LABEL,DO as TEXT_VALUE,Ou as TIMEZONES,JO as Tabs,r3 as TabsContent,e3 as TabsList,t3 as TabsTrigger,Zc as TapToggle,Gu as ThemeProvider,WT as ThermostatHeroCard,IA as ThermostatInlineControl,jL as TimezoneSelector,KE as Tooltip,WE as TooltipContent,zE as TooltipTrigger,Wk as VacuumHeroCard,zk as VacuumInlineControl,I3 as ValueReadout,sT as ValveHeroCard,eT as ValveInlineControl,g3 as VersionBadge,bj as VodPlaybackProvider,fT as WaterHeaterHeroCard,dT as WaterHeaterInlineControl,yT as WeatherHeroCard,gT as WeatherInlineControl,So as WidgetMetricCard,Hr as WidgetPanel,hj as WidgetRegistryProvider,LL as WidgetSlot,Hj as ZoneEditingProvider,Aw as allDeviceTypeFilterOptions,l3 as buildStepTreeFromSchema,Qc as childEntityId,L as cn,AC as columnsForContext,Nw as containerChildToRef,GC as countableDevices,Pa as coverHighlight,Nr as createSharedContext,xO as createTheme,u0 as darkColors,$u as defaultTheme,L3 as deriveDeviceKind,N3 as deviceRoleMeta,kw as deviceRoleMetaOf,C3 as deviceTypeMeta,Wc as deviceTypeMetaOf,tS as ensureMfHostInit,a0 as findTimezone,xc as formatControlDateTime,kp as formatLastSeen,ps as fuzzyMatch,Kt as getClassColor,Tp as getPhaseVisual,MC as groupChildrenByLayout,CC as hardwareLabel,iT as humidifierTint,ta as isAbsentProvider,LI as isFieldVisible,Qk as lawnMowerActivityMeta,d0 as lightColors,Lv as loadRemoteBundle,NC as metadataEntries,Bs as metadataString,jO as mirror,lj as mountAddonPage,n2 as nextSort,Hd as normalizeForSearch,Lw as overrideEntityIdFromLink,KO as providerIcons,Js as resolveContainerPrimary,ua as resolveControlAlign,Jc as resolveDeviceControl,Cw as resolvePrimaryChild,s2 as sortRows,zO as statusIcons,Hk as tankAlert,SO as themeToCss,x as trpc,M3 as useAccessoriesGetStatus,R3 as useAccessoriesSetChildHidden,P3 as useAddonPagesListPages,m4 as useAddonSettingsGetDeviceSettings,f4 as useAddonSettingsGetGlobalSettings,g4 as useAddonSettingsUpdateDeviceSettings,p4 as useAddonSettingsUpdateGlobalSettings,sk as useAddonWidgetsListWidgets,u4 as useAddonsApplyAutoUpdateToAll,t4 as useAddonsCancelBulkUpdate,d4 as useAddonsCustom,z3 as useAddonsForceRefresh,l4 as useAddonsGetAddonAutoUpdate,a4 as useAddonsGetAutoUpdateSettings,e4 as useAddonsGetBulkUpdateState,Q3 as useAddonsGetLastRestart,D3 as useAddonsGetLogs,n4 as useAddonsGetVersions,F3 as useAddonsInstallFromWorkspace,O3 as useAddonsInstallPackage,$3 as useAddonsIsWorkspaceAvailable,nk as useAddonsList,r4 as useAddonsListActiveBulkUpdates,Y3 as useAddonsListCapabilityProviders,q3 as useAddonsListFrameworkPackages,_3 as useAddonsListPackages,V3 as useAddonsListUpdates,B3 as useAddonsListWorkspacePackages,h4 as useAddonsOnAddonLogs,G3 as useAddonsReloadPackages,s4 as useAddonsRestartAddon,W3 as useAddonsRestartServer,i4 as useAddonsRetryLoad,K3 as useAddonsRollbackPackage,H3 as useAddonsSearchAvailable,c4 as useAddonsSetAddonAutoUpdate,o4 as useAddonsSetAutoUpdateSettings,X3 as useAddonsSetCapabilityProviderEnabled,J3 as useAddonsStartBulkUpdate,U3 as useAddonsUninstallPackage,Z3 as useAddonsUpdateFrameworkPackage,j3 as useAddonsUpdatePackage,v4 as useAirQualitySensorGetStatus,b4 as useAlarmPanelArm,y4 as useAlarmPanelDisarm,S4 as useAlarmPanelGetStatus,x4 as useAlarmPanelTrigger,N4 as useAlertsDismiss,E4 as useAlertsEmit,T4 as useAlertsGetUnreadCount,k4 as useAlertsList,C4 as useAlertsMarkAllRead,A4 as useAlertsMarkRead,w4 as useAlertsUpdate,pj as useAllWidgets,L4 as useAmbientLightSensorGetStatus,P4 as useAudioAnalysisApplyDeviceSettingsPatch,M4 as useAudioAnalysisGetDeviceLiveContribution,R4 as useAudioAnalysisGetDeviceSettingsContribution,I4 as useAudioAnalysisResolveDeviceSettings,D4 as useAudioAnalyzerAnalyseChunk,_4 as useAudioAnalyzerClassify,F4 as useAudioAnalyzerDispose,O4 as useAudioAnalyzerIsReady,$4 as useAudioAnalyzerReprobeAudioEngine,U4 as useAudioCodecCanHandle,V4 as useAudioCodecCloseSession,G4 as useAudioCodecCreateDecodeSession,H4 as useAudioCodecCreateEncodeSession,Q4 as useAudioCodecFlushEncode,q4 as useAudioCodecListActiveSessions,B4 as useAudioCodecListSupportedCodecs,W4 as useAudioCodecPullEncoded,K4 as useAudioCodecPullPcm,j4 as useAudioCodecPushEncodedFrame,z4 as useAudioCodecPushPcm,Y4 as useAudioMetricsGetCurrentSnapshot,X4 as useAudioMetricsGetHistory,J4 as useAutomationControlDisable,Z4 as useAutomationControlEnable,tF as useAutomationControlGetStatus,eF as useAutomationControlTrigger,lF as useBackupDelete,aF as useBackupGetEntries,sF as useBackupList,cF as useBackupListArchives,rF as useBackupListDestinations,iF as useBackupListLocations,dF as useBackupPreviewSchedule,oF as useBackupRestore,nF as useBackupTrigger,uF as useBackupUpsertDestinationPolicy,fF as useBatteryGetStatus,hF as useBatteryWakeForStream,pF as useBinaryGetStatus,gF as useBrightnessGetStatus,mF as useBrightnessSetBrightness,xF as useBrokerAdd,bF as useBrokerGet,TF as useBrokerGetBrokerConfig,wF as useBrokerGetSettings,AF as useBrokerGetSettingsSchema,RF as useBrokerGetState,MF as useBrokerGetStatus,vF as useBrokerList,yF as useBrokerListProviders,NF as useBrokerPublish,SF as useBrokerRemove,kF as useBrokerSetSettings,LF as useBrokerSubscribe,EF as useBrokerTestConnection,CF as useBrokerTestSettings,IF as useBrokerUnsubscribe,PF as useButtonPress,DF as useCameraCredentialsGetCredentials,_F as useCameraCredentialsGetStatus,$F as useCameraPipelineConfigApplyDeviceSettingsPatch,FF as useCameraPipelineConfigGetDeviceLiveContribution,OF as useCameraPipelineConfigGetDeviceSettingsContribution,UF as useCameraStreamsGetBrokerStreams,BF as useCameraStreamsGetCameraStreams,GF as useCameraStreamsGetProfileRtspEntries,ik as useCameraStreamsGetRtspEntries,HF as useCameraStreamsPickStream,VF as useCarbonMonoxideGetStatus,YF as useClimateControlGetStatus,KF as useClimateControlSetFanMode,jF as useClimateControlSetMode,zF as useClimateControlSetPreset,WF as useClimateControlSetTarget,qF as useClimateControlSetTargetHumidity,QF as useClimateControlSetTargetRange,zc as useClusterNodes,ZF as useColorGetStatus,XF as useColorSetColor,is as useConfirm,JF as useConnectivityGetStatus,t$ as useConsumablesGetStatus,e$ as useConsumablesReset,r$ as useContactGetStatus,qc as useContainerChildren,s$ as useControlGetStatus,n$ as useControlSetValue,a$ as useCoverClose,u$ as useCoverGetStatus,i$ as useCoverOpen,l$ as useCoverSetPosition,c$ as useCoverSetTiltPosition,o$ as useCoverStop,sN as useCustomFieldRenderer,iv as useDebouncedString,f$ as useDecoderCreateSession,p$ as useDecoderDestroySession,y$ as useDecoderGetFrame,h$ as useDecoderGetInfo,x$ as useDecoderGetShmStats,E$ as useDecoderGetStats,w$ as useDecoderListActiveSessions,g$ as useDecoderOpenStream,v$ as useDecoderPullFrames,b$ as useDecoderPullHandles,m$ as useDecoderPushPacket,k$ as useDecoderReprobeHwaccel,d$ as useDecoderSupportsCodec,S$ as useDecoderUpdateConfig,C$ as useDetectionPipelineApplyDeviceSettingsPatch,A$ as useDetectionPipelineGetDeviceLiveContribution,T$ as useDetectionPipelineGetDeviceSettingsContribution,oj as useDevShell,Qj as useDevice,M$ as useDeviceAdoptionAdopt,I$ as useDeviceAdoptionGetCandidate,_$ as useDeviceAdoptionGetStatus,N$ as useDeviceAdoptionListCandidateFilters,L$ as useDeviceAdoptionListCandidates,R$ as useDeviceAdoptionRefresh,P$ as useDeviceAdoptionRelease,D$ as useDeviceAdoptionResync,xN as useDeviceAutotrack,bC as useDeviceBattery,Zj as useDeviceCapSlice,_e as useDeviceCapability,jj as useDeviceDetections,$$ as useDeviceDiscoveryAdoptDevice,U$ as useDeviceDiscoveryGetStatus,O$ as useDeviceDiscoveryListDiscovered,F$ as useDeviceDiscoveryRefreshDiscovery,B$ as useDeviceDiscoveryReleaseDevice,V$ as useDeviceExportApplyDeviceSettingsPatch,ck as useDeviceExportExposeDevice,H$ as useDeviceExportGetDeviceLiveContribution,G$ as useDeviceExportGetDeviceSettingsContribution,ak as useDeviceExportGetStatus,lk as useDeviceExportListExposedDevices,ok as useDeviceExportListSupportedDeviceKinds,uk as useDeviceExportUnexposeDevice,iN as useDeviceId,UC as useDeviceListPageSize,uB as useDeviceManagerAddLocation,$B as useDeviceManagerAdoptDevice,jB as useDeviceManagerAdoptionAdopt,HB as useDeviceManagerAdoptionListCandidates,VB as useDeviceManagerAdoptionRefresh,KB as useDeviceManagerAdoptionRelease,j$ as useDeviceManagerAllocateDeviceId,oB as useDeviceManagerApplyInitialMeta,UB as useDeviceManagerCreateDevice,xB as useDeviceManagerDisable,FB as useDeviceManagerDiscoverDevices,yB as useDeviceManagerEnable,CB as useDeviceManagerGetAllBindings,AB as useDeviceManagerGetBindings,pB as useDeviceManagerGetChildren,gB as useDeviceManagerGetConfigSchema,BB as useDeviceManagerGetCreationSchema,Sg as useDeviceManagerGetDevice,PB as useDeviceManagerGetDeviceAggregate,MB as useDeviceManagerGetDeviceLiveInfoAggregate,RB as useDeviceManagerGetDeviceSettingsAggregate,WB as useDeviceManagerGetDeviceStatusAggregate,vB as useDeviceManagerGetSettingsSchema,wB as useDeviceManagerGetStreamProfileMap,mB as useDeviceManagerGetStreamSources,iB as useDeviceManagerGetWireableFields,xg as useDeviceManagerListAll,IB as useDeviceManagerListBindableCapsForDeviceType,cB as useDeviceManagerListLocations,fB as useDeviceManagerListPersistedByAddon,LB as useDeviceManagerListWrappersForCap,Q$ as useDeviceManagerLoadConfig,Y$ as useDeviceManagerLoadMeta,q$ as useDeviceManagerLoadRuntimeState,W$ as useDeviceManagerPersistConfig,TB as useDeviceManagerProbeStreams,K$ as useDeviceManagerRegisterDevice,SB as useDeviceManagerRemove,EB as useDeviceManagerRemoveByIntegration,z$ as useDeviceManagerRemoveDevice,dB as useDeviceManagerRemoveLocation,DB as useDeviceManagerRunDeviceAction,nB as useDeviceManagerSetChildLayout,sB as useDeviceManagerSetDeviceLinks,hB as useDeviceManagerSetDisabled,eB as useDeviceManagerSetIntegrationId,tB as useDeviceManagerSetLinkDeviceId,Z$ as useDeviceManagerSetLocation,lB as useDeviceManagerSetMetadata,X$ as useDeviceManagerSetName,rB as useDeviceManagerSetPrimaryChildEntityId,aB as useDeviceManagerSetRole,kB as useDeviceManagerSetStreamProfileMap,J$ as useDeviceManagerSetType,NB as useDeviceManagerSetWrapperActive,GB as useDeviceManagerTestCreationField,zB as useDeviceManagerTestField,bB as useDeviceManagerUpdateConfig,_B as useDeviceManagerUpdateDeviceField,OB as useDeviceManagerUpdateDeviceFieldsBatch,qB as useDeviceOpsGetConfigEntries,eU as useDeviceOpsGetRawState,JB as useDeviceOpsGetSettingsSchema,QB as useDeviceOpsGetStreamSources,ZB as useDeviceOpsRemoveDevice,XB as useDeviceOpsRunAction,YB as useDeviceOpsSetConfig,oU as useDeviceProviderAdoptDiscoveredDevice,uU as useDeviceProviderCreateDevice,aU as useDeviceProviderDiscoverDevices,cU as useDeviceProviderGetChildCreationSchema,sU as useDeviceProviderGetDevices,nU as useDeviceProviderGetStatus,tU as useDeviceProviderStart,rU as useDeviceProviderStop,iU as useDeviceProviderSupportsDiscovery,lU as useDeviceProviderSupportsManualCreation,dU as useDeviceProviderTestCreationField,Qt as useDeviceProxy,dj as useDeviceSnapshot,yC as useDeviceSnapshotImage,yw as useDeviceState,pU as useDeviceStateGetAllSnapshots,fU as useDeviceStateGetCapSlice,hU as useDeviceStateGetSnapshot,mU as useDeviceStateSetCapSlice,Tr as useDeviceStateSlice,gU as useDeviceStatusGetStatus,Kj as useDeviceWebrtc,Wj as useDevices,zj as useDoorbellEvents,vU as useDoorbellGetStatus,bU as useEnumSensorGetStatus,yU as useEventEmitterGetStatus,Xj as useEventInvalidation,ig as useEventStreamLatest,h3 as useEventStreamMap,EU as useEventsGetEventClipUrl,SU as useEventsGetEventThumbnail,xU as useEventsGetEvents,CU as useFanControlGetStatus,TU as useFanControlSetDirection,AU as useFanControlSetOscillating,wU as useFanControlSetPercentage,kU as useFanControlSetPreset,NU as useFeatureProbeGetStatus,LU as useFloodGetStatus,IU as useGasGetStatus,DU as useHumidifierGetStatus,PU as useHumidifierSetMode,RU as useHumidifierSetOn,MU as useHumidifierSetTargetHumidity,_U as useHumiditySensorGetStatus,OU as useImageGetStatus,UU as useIntegrationsCreate,HU as useIntegrationsDelete,$U as useIntegrationsGet,KU as useIntegrationsGetAvailableTypes,BU as useIntegrationsGetByAddonId,VU as useIntegrationsGetSettings,FU as useIntegrationsList,jU as useIntegrationsSetSettings,zU as useIntegrationsTestConnection,GU as useIntegrationsUpdate,ZU as useIntercomEndTalkSession,JU as useIntercomGetStatus,QU as useIntercomHandleAnswer,XU as useIntercomPushTalkAudio,WU as useIntercomStartSession,YU as useIntercomStartTalkSession,qU as useIntercomStopSession,ZO as useIsMidWidth,Ra as useIsMobile,r6 as useLawnMowerControlDock,n6 as useLawnMowerControlGetStatus,t6 as useLawnMowerControlPause,e6 as useLawnMowerControlStartMowing,Ls as useLiveBuffer,Ma as useLiveEvent,o6 as useLocalNetworkGetAllowedAddresses,a6 as useLocalNetworkGetConnectionEndpoints,i6 as useLocalNetworkGetPreferred,s6 as useLocalNetworkList,c6 as useLocalNetworkResetAllowlistToBestMatch,l6 as useLocalNetworkSetAllowedAddresses,f6 as useLockControlGetStatus,u6 as useLockControlLock,h6 as useLockControlOpen,d6 as useLockControlUnlock,A6 as useMediaPlayerGetStatus,v6 as useMediaPlayerNext,m6 as useMediaPlayerPause,p6 as useMediaPlayerPlay,T6 as useMediaPlayerPlayMedia,b6 as useMediaPlayerPrevious,y6 as useMediaPlayerSeek,k6 as useMediaPlayerSelectSource,S6 as useMediaPlayerSetMute,w6 as useMediaPlayerSetRepeat,E6 as useMediaPlayerSetShuffle,x6 as useMediaPlayerSetVolume,g6 as useMediaPlayerStop,C6 as useMeshNetworkGetStatus,N6 as useMeshNetworkJoin,I6 as useMeshNetworkLeave,M6 as useMeshNetworkListPeers,R6 as useMeshNetworkLogout,L6 as useMeshNetworkStartLogin,P6 as useMeshNetworkTestConnection,D6 as useMetricsProviderCollectSnapshot,H6 as useMetricsProviderGetAddonStats,_6 as useMetricsProviderGetCached,B6 as useMetricsProviderGetCpuTemperature,O6 as useMetricsProviderGetCurrent,F6 as useMetricsProviderGetDiskSpace,$6 as useMetricsProviderGetGpuInfo,U6 as useMetricsProviderGetProcessStats,j6 as useMetricsProviderKillProcess,G6 as useMetricsProviderListAddonInstances,V6 as useMetricsProviderListNodeProcesses,W6 as useMotionDetectionAnalyze,Z6 as useMotionDetectionApplyDeviceSettingsPatch,X6 as useMotionDetectionGetDeviceLiveContribution,Y6 as useMotionDetectionGetDeviceSettingsContribution,Q6 as useMotionDetectionRemoveCamera,q6 as useMotionDetectionReset,z6 as useMotionGetStatus,K6 as useMotionIsDetected,e8 as useMotionTriggerGetStatus,J6 as useMotionTriggerSetMotionTrigger,t8 as useMotionZonesGetOptions,n8 as useMotionZonesGetStatus,r8 as useMotionZonesSetZone,a8 as useMqttBrokerAddBroker,i8 as useMqttBrokerGetBrokerConfig,d8 as useMqttBrokerGetStatus,s8 as useMqttBrokerListBrokers,o8 as useMqttBrokerRemoveBroker,c8 as useMqttBrokerStartEmbeddedBroker,u8 as useMqttBrokerStopEmbeddedBroker,l8 as useMqttBrokerTestConnection,f8 as useNativeObjectDetectionGetStatus,h8 as useNativeObjectDetectionSetEnabled,g8 as useNetworkAccessGetEndpoint,v8 as useNetworkAccessGetStatus,b8 as useNetworkAccessListEndpoints,p8 as useNetworkAccessStart,m8 as useNetworkAccessStop,x8 as useNetworkQualityGetAllStats,y8 as useNetworkQualityGetDeviceStats,S8 as useNetworkQualityReportClientStats,I8 as useNodesClusterAddonStatus,w8 as useNodesDeployAddon,D8 as useNodesExecuteQuery,R8 as useNodesGetCapUsageGraph,M8 as useNodesGetNodeAddons,L8 as useNodesRenameNode,T8 as useNodesRestartAddon,C8 as useNodesRestartNode,A8 as useNodesRestartProcess,P8 as useNodesSetProcessLogLevel,N8 as useNodesShutdownNode,E8 as useNodesTopology,k8 as useNodesUndeployAddon,_8 as useNotificationOutputSend,O8 as useNotificationOutputSendTest,$8 as useNotifierCancel,B8 as useNotifierGetStatus,F8 as useNotifierSend,U8 as useNumericSensorGetStatus,Ze as useOptimisticSlice,d3 as useOptionalSystem,Iv as useOptionalWidgetRegistry,H8 as useOsdGetStatus,G8 as useOsdSetOverlay,mg as usePTZ,Z8 as usePipelineAnalyticsApplyDeviceSettingsPatch,z8 as usePipelineAnalyticsClearTracks,V8 as usePipelineAnalyticsGetActiveTracks,fk as usePipelineAnalyticsGetAudioEvents,X8 as usePipelineAnalyticsGetDeviceLiveContribution,Y8 as usePipelineAnalyticsGetDeviceSettingsContribution,pk as usePipelineAnalyticsGetEventDensity,Q8 as usePipelineAnalyticsGetEventMedia,dk as usePipelineAnalyticsGetMotionEvents,hk as usePipelineAnalyticsGetObjectEvents,j8 as usePipelineAnalyticsGetTrack,q8 as usePipelineAnalyticsGetTrackMedia,K8 as usePipelineAnalyticsListTracks,W8 as usePipelineAnalyticsPruneEventsBefore,xG as usePipelineExecutorCacheFrameInPool,gG as usePipelineExecutorDeleteModel,hG as usePipelineExecutorDeleteTemplate,vG as usePipelineExecutorDetect,mG as usePipelineExecutorDownloadModel,pG as usePipelineExecutorGetAddonModels,RG as usePipelineExecutorGetAudioCapabilities,J8 as usePipelineExecutorGetAvailableEngines,fG as usePipelineExecutorGetCapabilities,tG as usePipelineExecutorGetDefaultSteps,PG as usePipelineExecutorGetDetectionConfigSchema,wG as usePipelineExecutorGetEffectiveTuning,oG as usePipelineExecutorGetGlobalPipelineConfig,aG as usePipelineExecutorGetGlobalSteps,lG as usePipelineExecutorGetOrchestratorConfigSchema,IG as usePipelineExecutorGetReferenceAudio,LG as usePipelineExecutorGetReferenceAudioFiles,NG as usePipelineExecutorGetReferenceImage,iG as usePipelineExecutorGetSchema,eG as usePipelineExecutorGetSelectedEngine,nG as usePipelineExecutorGetVideoPipelineSteps,SG as usePipelineExecutorInferCached,AG as usePipelineExecutorKillEngine,kG as usePipelineExecutorListLoadedEngines,CG as usePipelineExecutorListReferenceImages,cG as usePipelineExecutorListTemplates,rG as usePipelineExecutorReprobeEngine,MG as usePipelineExecutorRunAudioTest,bG as usePipelineExecutorRunPipeline,yG as usePipelineExecutorRunPipelineBatch,uG as usePipelineExecutorSaveTemplate,sG as usePipelineExecutorSetVideoPipelineSteps,TG as usePipelineExecutorSpinEngine,EG as usePipelineExecutorUncacheFrame,dG as usePipelineExecutorUpdateTemplate,m9 as usePipelineOrchestratorApplyDeviceSettingsPatch,WG as usePipelineOrchestratorAssignAudio,jG as usePipelineOrchestratorAssignDecoder,DG as usePipelineOrchestratorAssignPipeline,h9 as usePipelineOrchestratorDeleteTemplate,BG as usePipelineOrchestratorGetAgentLoad,JG as usePipelineOrchestratorGetAgentSettings,qG as usePipelineOrchestratorGetAudioAssignment,XG as usePipelineOrchestratorGetAudioAssignments,YG as usePipelineOrchestratorGetAudioNodeLoad,GG as usePipelineOrchestratorGetCameraMetrics,n9 as usePipelineOrchestratorGetCameraSettings,i9 as usePipelineOrchestratorGetCameraStepOverrides,HG as usePipelineOrchestratorGetCapabilityBindings,ZG as usePipelineOrchestratorGetDecoderAssignment,zG as usePipelineOrchestratorGetDecoderAssignments,p9 as usePipelineOrchestratorGetDeviceLiveContribution,f9 as usePipelineOrchestratorGetDeviceSettingsContribution,UG as usePipelineOrchestratorGetGlobalMetrics,$G as usePipelineOrchestratorGetPipelineAssignment,FG as usePipelineOrchestratorGetPipelineAssignments,e9 as usePipelineOrchestratorListAgentSettings,c9 as usePipelineOrchestratorListTemplates,OG as usePipelineOrchestratorRebalance,r9 as usePipelineOrchestratorRemoveAgentSettings,l9 as usePipelineOrchestratorResolvePipeline,u9 as usePipelineOrchestratorSaveTemplate,t9 as usePipelineOrchestratorSetAgentAddonDefaults,o9 as usePipelineOrchestratorSetCameraPipelineForAgent,a9 as usePipelineOrchestratorSetCameraStepOverride,s9 as usePipelineOrchestratorSetCameraStepToggle,VG as usePipelineOrchestratorSetCapabilityBinding,QG as usePipelineOrchestratorUnassignAudio,KG as usePipelineOrchestratorUnassignDecoder,_G as usePipelineOrchestratorUnassignPipeline,d9 as usePipelineOrchestratorUpdateTemplate,g9 as usePipelineRunnerAttachCamera,v9 as usePipelineRunnerDetachCamera,E9 as usePipelineRunnerGetAllCameraMetrics,S9 as usePipelineRunnerGetCameraMetrics,w9 as usePipelineRunnerGetLocalCameras,y9 as usePipelineRunnerGetLocalLoad,x9 as usePipelineRunnerGetLocalMetrics,b9 as usePipelineRunnerReportMotion,Rv as usePlayerOverlayLayer,gj as usePlayerOverlayLayers,vj as usePlayerToolbarButton,EN as usePlayerToolbarButtons,k9 as usePowerMeterGetStatus,T9 as usePresenceGetStatus,A9 as usePressureSensorGetStatus,C9 as usePrivacyMaskGetOptions,L9 as usePrivacyMaskGetStatus,N9 as usePrivacyMaskSetMask,H9 as usePtzAutotrackGetSettings,mk as usePtzAutotrackGetStatus,gk as usePtzAutotrackSetEnabled,vk as usePtzAutotrackSetSettings,R9 as usePtzContinuousMove,O9 as usePtzDeletePreset,F9 as usePtzGetOptions,B9 as usePtzGetPosition,P9 as usePtzGetPresets,G9 as usePtzGetStatus,$9 as usePtzGoHome,D9 as usePtzGoToPreset,I9 as usePtzMove,_9 as usePtzSavePreset,U9 as usePtzSetAutofocus,M9 as usePtzStop,V9 as useRebootReboot,q9 as useRecordingApplyDeviceSettingsPatch,Eg as useRecordingGetAvailability,bk as useRecordingGetDeviceConfig,Q9 as useRecordingGetDeviceLiveContribution,W9 as useRecordingGetDeviceSettingsContribution,j9 as useRecordingGetPlaybackManifest,Sk as useRecordingGetStatus,K9 as useRecordingGetStorageUsage,z9 as useRecordingPruneFootage,xk as useRecordingRescanStorage,yk as useRecordingSetDeviceConfig,dN as useRemoteComponent,Z9 as useScriptRunnerGetStatus,Y9 as useScriptRunnerRun,X9 as useScriptRunnerStop,i7 as useSettingsStoreCount,l7 as useSettingsStoreDeclareCollection,s7 as useSettingsStoreDelete,J9 as useSettingsStoreGet,a7 as useSettingsStoreHistogram,r7 as useSettingsStoreInsert,o7 as useSettingsStoreIsEmpty,t7 as useSettingsStoreQuery,e7 as useSettingsStoreSet,n7 as useSettingsStoreUpdate,c7 as useSmokeGetStatus,m7 as useSnapshotApplyDeviceSettingsPatch,p7 as useSnapshotGetDeviceLiveContribution,f7 as useSnapshotGetDeviceSettingsContribution,u7 as useSnapshotGetSnapshot,h7 as useSnapshotGetStatus,d7 as useSnapshotInvalidateCache,v7 as useSnapshotProviderGetSnapshot,g7 as useSnapshotProviderSupportsDevice,N7 as useStorageAbortUpload,L7 as useStorageBeginDownload,T7 as useStorageBeginUpload,w7 as useStorageDelete,O7 as useStorageDeleteLocation,R7 as useStorageEndDownload,S7 as useStorageExists,C7 as useStorageFinalizeUpload,k7 as useStorageGetAvailableSpace,P7 as useStorageGetDefaultLocation,E7 as useStorageList,D7 as useStorageListLocationDeclarations,M7 as useStorageListLocations,$7 as useStorageListProviders,x7 as useStorageRead,I7 as useStorageReadChunk,b7 as useStorageResolve,B7 as useStorageTestConfig,F7 as useStorageTestLocation,_7 as useStorageUpsertLocation,y7 as useStorageWrite,A7 as useStorageWriteChunk,mH as useStreamBrokerApplyDeviceSettingsPatch,H7 as useStreamBrokerAssignProfile,lH as useStreamBrokerGetAllRtspEntries,z7 as useStreamBrokerGetBrokerStats,pH as useStreamBrokerGetDeviceLiveContribution,fH as useStreamBrokerGetDeviceSettingsContribution,aH as useStreamBrokerGetPreBufferInfo,cH as useStreamBrokerGetRtspEntry,oH as useStreamBrokerGetRtspPort,Y7 as useStreamBrokerGetStreamUrl,X7 as useStreamBrokerGetStreamWithCodec,hH as useStreamBrokerIsRtspEnabled,Q7 as useStreamBrokerKillClient,j7 as useStreamBrokerListAllCameraStreams,K7 as useStreamBrokerListAllProfileSlots,W7 as useStreamBrokerListClients,U7 as useStreamBrokerPublishCameraStream,eH as useStreamBrokerPullAudioChunks,nH as useStreamBrokerPullFrameHandles,uH as useStreamBrokerRegenerateRtspToken,Z7 as useStreamBrokerReleaseStreamWithCodec,q7 as useStreamBrokerRestartProfile,G7 as useStreamBrokerRetractCameraStream,iH as useStreamBrokerSetPreBufferDuration,dH as useStreamBrokerSetRtspEnabled,J7 as useStreamBrokerSubscribeAudioChunks,rH as useStreamBrokerSubscribeFrames,V7 as useStreamBrokerUnassignProfile,tH as useStreamBrokerUnsubscribeAudioChunks,sH as useStreamBrokerUnsubscribeFrames,gH as useStreamCatalogGetCatalog,yH as useStreamParamsGetConfigSchema,vH as useStreamParamsGetOptions,xH as useStreamParamsGetStatus,bH as useStreamParamsSetProfile,EH as useSwitchGetStatus,SH as useSwitchSetState,Gt as useSystem,TH as useSystemFeatureFlags,LH as useSystemForceRetentionCleanup,CH as useSystemGetRetentionConfig,kH as useSystemHealth,wH as useSystemInfo,Yj as useSystemMutation,AH as useSystemNetworkAddresses,qj as useSystemQuery,NH as useSystemSetRetentionConfig,IH as useTamperGetStatus,RH as useTemperatureSensorGetStatus,v0 as useThemeMode,MH as useToastOnToast,PH as useTurnProviderGetTurnServers,_H as useUpdateGetStatus,DH as useUpdateInstallUpdate,ZH as useUserManagementConfirmTotp,jH as useUserManagementCreateApiKey,WH as useUserManagementCreateScopedToken,FH as useUserManagementCreateUser,BH as useUserManagementDeleteUser,JH as useUserManagementDisableTotp,eV as useUserManagementGetTotpStatus,VH as useUserManagementListApiKeys,aV as useUserManagementListOauthSessions,YH as useUserManagementListScopedTokens,OH as useUserManagementListUsers,nV as useUserManagementOauthExchangeCode,rV as useUserManagementOauthIssueCode,sV as useUserManagementOauthRefresh,iV as useUserManagementOauthVerifyAccessToken,UH as useUserManagementResetPassword,KH as useUserManagementRevokeApiKey,oV as useUserManagementRevokeOauthSession,QH as useUserManagementRevokeScopedToken,GH as useUserManagementSetUserScopes,XH as useUserManagementSetupTotp,$H as useUserManagementUpdateUser,zH as useUserManagementValidateApiKey,HH as useUserManagementValidateCredentials,qH as useUserManagementValidateScopedToken,tV as useUserManagementVerifyTotp,pV as useVacuumControlGetStatus,hV as useVacuumControlLocate,cV as useVacuumControlPause,dV as useVacuumControlReturnToBase,fV as useVacuumControlSetFanSpeed,lV as useVacuumControlStart,uV as useVacuumControlStop,gV as useValveClose,yV as useValveGetStatus,mV as useValveOpen,bV as useValveSetPosition,vV as useValveStop,xV as useVibrationGetStatus,JN as useVodPlayback,kV as useWaterHeaterGetStatus,wV as useWaterHeaterSetAway,EV as useWaterHeaterSetOperationMode,SV as useWaterHeaterSetTargetTemp,TV as useWeatherGetStatus,IV as useWebrtcSessionAddIceCandidate,MV as useWebrtcSessionCloseSession,CV as useWebrtcSessionCreateSession,RV as useWebrtcSessionGetIceCandidates,DV as useWebrtcSessionGetSessionState,LV as useWebrtcSessionHandleAnswer,NV as useWebrtcSessionHandleOffer,PV as useWebrtcSessionHasAdaptiveBitrate,AV as useWebrtcSessionListStreams,fj as useWidget,uN as useWidgetMetadata,iu as useWidgetRegistry,FV as useZoneAnalyticsGetCameraHistory,_V as useZoneAnalyticsGetCurrentSnapshot,$V as useZoneAnalyticsGetUnzonedHistory,OV as useZoneAnalyticsGetZoneHistory,Vj as useZoneEditing,BV as useZoneRulesListRules,UV as useZoneRulesSetRules,HV as useZonesAddZone,GV as useZonesListZones,VV as useZonesRemoveZone,jV as useZonesUpdateZone,$k as vacuumStateMeta,Gj as validateScopes,Jk as valveStateMeta,uT as waterHeaterPhase,cT as waterHeaterTint,Bg as weatherConditionMeta,Ug as weatherTint};