@nicorp/nui 0.11.2 → 0.11.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,7 +1,7 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),B=require("react"),ro=require("@radix-ui/react-slot"),Bi=require("@radix-ui/react-label"),Oi=require("@radix-ui/react-separator"),Hi=require("@radix-ui/react-avatar"),Gi=require("@radix-ui/react-checkbox"),P=require("lucide-react"),qi=require("@radix-ui/react-switch"),Wi=require("@radix-ui/react-select"),Ui=require("@radix-ui/react-radio-group"),Ki=require("@radix-ui/react-slider"),Xi=require("@radix-ui/react-toggle"),Yi=require("@radix-ui/react-toggle-group"),_e=require("date-fns"),Zi=require("@radix-ui/react-popover"),Ji=require("@radix-ui/react-aspect-ratio"),Qi=require("@radix-ui/react-collapsible"),el=require("@radix-ui/react-scroll-area"),tl=require("@radix-ui/react-tabs"),rl=require("@radix-ui/react-accordion"),nl=require("@radix-ui/react-dialog"),ol=require("@radix-ui/react-dropdown-menu"),sl=require("@radix-ui/react-tooltip"),$e=require("cmdk"),al=require("@radix-ui/react-alert-dialog"),il=require("@radix-ui/react-progress"),qr=require("react-dom"),ll=require("@radix-ui/react-navigation-menu"),cl=require("@radix-ui/react-context-menu"),dl=require("@radix-ui/react-hover-card"),Wr=require("recharts");function xe(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,o.get?o:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const f=xe(B),no=xe(Bi),oo=xe(Oi),Rt=xe(Hi),Lr=xe(Gi),Tr=xe(qi),ye=xe(Wi),$t=xe(Ui),Et=xe(Ki),so=xe(Xi),dr=xe(Yi),Bt=xe(Zi),ul=xe(Ji),Ur=xe(Qi),xt=xe(el),wt=xe(tl),vt=xe(rl),ge=xe(nl),pe=xe(ol),Wt=xe(sl),Ae=xe(al),Er=xe(il),Be=xe(ll),he=xe(cl),ur=xe(dl);function ao(e){var t,r,o="";if(typeof e=="string"||typeof e=="number")o+=e;else if(typeof e=="object")if(Array.isArray(e)){var s=e.length;for(t=0;t<s;t++)e[t]&&(r=ao(e[t]))&&(o&&(o+=" "),o+=r)}else for(r in e)e[r]&&(o&&(o+=" "),o+=r);return o}function io(){for(var e,t,r=0,o="",s=arguments.length;r<s;r++)(e=arguments[r])&&(t=ao(e))&&(o&&(o+=" "),o+=t);return o}const ml=(e,t)=>{const r=new Array(e.length+t.length);for(let o=0;o<e.length;o++)r[o]=e[o];for(let o=0;o<t.length;o++)r[e.length+o]=t[o];return r},fl=(e,t)=>({classGroupId:e,validator:t}),lo=(e=new Map,t=null,r)=>({nextPart:e,validators:t,classGroupId:r}),ar="-",Tn=[],gl="arbitrary..",pl=e=>{const t=xl(e),{conflictingClassGroups:r,conflictingClassGroupModifiers:o}=e;return{getClassGroupId:i=>{if(i.startsWith("[")&&i.endsWith("]"))return hl(i);const l=i.split(ar),d=l[0]===""&&l.length>1?1:0;return co(l,d,t)},getConflictingClassGroupIds:(i,l)=>{if(l){const d=o[i],c=r[i];return d?c?ml(c,d):d:c||Tn}return r[i]||Tn}}},co=(e,t,r)=>{if(e.length-t===0)return r.classGroupId;const s=e[t],a=r.nextPart.get(s);if(a){const c=co(e,t+1,a);if(c)return c}const i=r.validators;if(i===null)return;const l=t===0?e.join(ar):e.slice(t).join(ar),d=i.length;for(let c=0;c<d;c++){const p=i[c];if(p.validator(l))return p.classGroupId}},hl=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),r=t.indexOf(":"),o=t.slice(0,r);return o?gl+o:void 0})(),xl=e=>{const{theme:t,classGroups:r}=e;return vl(r,t)},vl=(e,t)=>{const r=lo();for(const o in e){const s=e[o];Kr(s,r,o,t)}return r},Kr=(e,t,r,o)=>{const s=e.length;for(let a=0;a<s;a++){const i=e[a];bl(i,t,r,o)}},bl=(e,t,r,o)=>{if(typeof e=="string"){wl(e,t,r);return}if(typeof e=="function"){yl(e,t,r,o);return}jl(e,t,r,o)},wl=(e,t,r)=>{const o=e===""?t:uo(t,e);o.classGroupId=r},yl=(e,t,r,o)=>{if(Nl(e)){Kr(e(o),t,r,o);return}t.validators===null&&(t.validators=[]),t.validators.push(fl(r,e))},jl=(e,t,r,o)=>{const s=Object.entries(e),a=s.length;for(let i=0;i<a;i++){const[l,d]=s[i];Kr(d,uo(t,l),r,o)}},uo=(e,t)=>{let r=e;const o=t.split(ar),s=o.length;for(let a=0;a<s;a++){const i=o[a];let l=r.nextPart.get(i);l||(l=lo(),r.nextPart.set(i,l)),r=l}return r},Nl=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,kl=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,r=Object.create(null),o=Object.create(null);const s=(a,i)=>{r[a]=i,t++,t>e&&(t=0,o=r,r=Object.create(null))};return{get(a){let i=r[a];if(i!==void 0)return i;if((i=o[a])!==void 0)return s(a,i),i},set(a,i){a in r?r[a]=i:s(a,i)}}},Dr="!",En=":",Cl=[],Dn=(e,t,r,o,s)=>({modifiers:e,hasImportantModifier:t,baseClassName:r,maybePostfixModifierPosition:o,isExternal:s}),Sl=e=>{const{prefix:t,experimentalParseClassName:r}=e;let o=s=>{const a=[];let i=0,l=0,d=0,c;const p=s.length;for(let x=0;x<p;x++){const y=s[x];if(i===0&&l===0){if(y===En){a.push(s.slice(d,x)),d=x+1;continue}if(y==="/"){c=x;continue}}y==="["?i++:y==="]"?i--:y==="("?l++:y===")"&&l--}const u=a.length===0?s:s.slice(d);let m=u,g=!1;u.endsWith(Dr)?(m=u.slice(0,-1),g=!0):u.startsWith(Dr)&&(m=u.slice(1),g=!0);const h=c&&c>d?c-d:void 0;return Dn(a,g,m,h)};if(t){const s=t+En,a=o;o=i=>i.startsWith(s)?a(i.slice(s.length)):Dn(Cl,!1,i,void 0,!0)}if(r){const s=o;o=a=>r({className:a,parseClassName:s})}return o},Rl=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((r,o)=>{t.set(r,1e6+o)}),r=>{const o=[];let s=[];for(let a=0;a<r.length;a++){const i=r[a],l=i[0]==="[",d=t.has(i);l||d?(s.length>0&&(s.sort(),o.push(...s),s=[]),o.push(i)):s.push(i)}return s.length>0&&(s.sort(),o.push(...s)),o}},_l=e=>({cache:kl(e.cacheSize),parseClassName:Sl(e),sortModifiers:Rl(e),...pl(e)}),Ml=/\s+/,Pl=(e,t)=>{const{parseClassName:r,getClassGroupId:o,getConflictingClassGroupIds:s,sortModifiers:a}=t,i=[],l=e.trim().split(Ml);let d="";for(let c=l.length-1;c>=0;c-=1){const p=l[c],{isExternal:u,modifiers:m,hasImportantModifier:g,baseClassName:h,maybePostfixModifierPosition:x}=r(p);if(u){d=p+(d.length>0?" "+d:d);continue}let y=!!x,b=o(y?h.substring(0,x):h);if(!b){if(!y){d=p+(d.length>0?" "+d:d);continue}if(b=o(h),!b){d=p+(d.length>0?" "+d:d);continue}y=!1}const w=m.length===0?"":m.length===1?m[0]:a(m).join(":"),j=g?w+Dr:w,M=j+b;if(i.indexOf(M)>-1)continue;i.push(M);const R=s(b,y);for(let _=0;_<R.length;++_){const C=R[_];i.push(j+C)}d=p+(d.length>0?" "+d:d)}return d},Il=(...e)=>{let t=0,r,o,s="";for(;t<e.length;)(r=e[t++])&&(o=mo(r))&&(s&&(s+=" "),s+=o);return s},mo=e=>{if(typeof e=="string")return e;let t,r="";for(let o=0;o<e.length;o++)e[o]&&(t=mo(e[o]))&&(r&&(r+=" "),r+=t);return r},Ll=(e,...t)=>{let r,o,s,a;const i=d=>{const c=t.reduce((p,u)=>u(p),e());return r=_l(c),o=r.cache.get,s=r.cache.set,a=l,l(d)},l=d=>{const c=o(d);if(c)return c;const p=Pl(d,r);return s(d,p),p};return a=i,(...d)=>a(Il(...d))},Tl=[],Se=e=>{const t=r=>r[e]||Tl;return t.isThemeGetter=!0,t},fo=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,go=/^\((?:(\w[\w-]*):)?(.+)\)$/i,El=/^\d+\/\d+$/,Dl=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Al=/\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$/,Fl=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Vl=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,zl=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,St=e=>El.test(e),de=e=>!!e&&!Number.isNaN(Number(e)),ct=e=>!!e&&Number.isInteger(Number(e)),yr=e=>e.endsWith("%")&&de(e.slice(0,-1)),tt=e=>Dl.test(e),$l=()=>!0,Bl=e=>Al.test(e)&&!Fl.test(e),po=()=>!1,Ol=e=>Vl.test(e),Hl=e=>zl.test(e),Gl=e=>!J(e)&&!Q(e),ql=e=>_t(e,vo,po),J=e=>fo.test(e),pt=e=>_t(e,bo,Bl),jr=e=>_t(e,Yl,de),An=e=>_t(e,ho,po),Wl=e=>_t(e,xo,Hl),Jt=e=>_t(e,wo,Ol),Q=e=>go.test(e),Lt=e=>Mt(e,bo),Ul=e=>Mt(e,Zl),Fn=e=>Mt(e,ho),Kl=e=>Mt(e,vo),Xl=e=>Mt(e,xo),Qt=e=>Mt(e,wo,!0),_t=(e,t,r)=>{const o=fo.exec(e);return o?o[1]?t(o[1]):r(o[2]):!1},Mt=(e,t,r=!1)=>{const o=go.exec(e);return o?o[1]?t(o[1]):r:!1},ho=e=>e==="position"||e==="percentage",xo=e=>e==="image"||e==="url",vo=e=>e==="length"||e==="size"||e==="bg-size",bo=e=>e==="length",Yl=e=>e==="number",Zl=e=>e==="family-name",wo=e=>e==="shadow",Jl=()=>{const e=Se("color"),t=Se("font"),r=Se("text"),o=Se("font-weight"),s=Se("tracking"),a=Se("leading"),i=Se("breakpoint"),l=Se("container"),d=Se("spacing"),c=Se("radius"),p=Se("shadow"),u=Se("inset-shadow"),m=Se("text-shadow"),g=Se("drop-shadow"),h=Se("blur"),x=Se("perspective"),y=Se("aspect"),b=Se("ease"),w=Se("animate"),j=()=>["auto","avoid","all","avoid-page","page","left","right","column"],M=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],R=()=>[...M(),Q,J],_=()=>["auto","hidden","clip","visible","scroll"],C=()=>["auto","contain","none"],S=()=>[Q,J,d],T=()=>[St,"full","auto",...S()],L=()=>[ct,"none","subgrid",Q,J],V=()=>["auto",{span:["full",ct,Q,J]},ct,Q,J],O=()=>[ct,"auto",Q,J],$=()=>["auto","min","max","fr",Q,J],k=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],z=()=>["start","end","center","stretch","center-safe","end-safe"],A=()=>["auto",...S()],E=()=>[St,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...S()],N=()=>[e,Q,J],W=()=>[...M(),Fn,An,{position:[Q,J]}],q=()=>["no-repeat",{repeat:["","x","y","space","round"]}],G=()=>["auto","cover","contain",Kl,ql,{size:[Q,J]}],Z=()=>[yr,Lt,pt],I=()=>["","none","full",c,Q,J],F=()=>["",de,Lt,pt],U=()=>["solid","dashed","dotted","double"],ee=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],X=()=>[de,yr,Fn,An],Y=()=>["","none",h,Q,J],ae=()=>["none",de,Q,J],te=()=>["none",de,Q,J],ie=()=>[de,Q,J],K=()=>[St,"full",...S()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[tt],breakpoint:[tt],color:[$l],container:[tt],"drop-shadow":[tt],ease:["in","out","in-out"],font:[Gl],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[tt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[tt],shadow:[tt],spacing:["px",de],text:[tt],"text-shadow":[tt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",St,J,Q,y]}],container:["container"],columns:[{columns:[de,J,Q,l]}],"break-after":[{"break-after":j()}],"break-before":[{"break-before":j()}],"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:R()}],overflow:[{overflow:_()}],"overflow-x":[{"overflow-x":_()}],"overflow-y":[{"overflow-y":_()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:T()}],"inset-x":[{"inset-x":T()}],"inset-y":[{"inset-y":T()}],start:[{start:T()}],end:[{end:T()}],top:[{top:T()}],right:[{right:T()}],bottom:[{bottom:T()}],left:[{left:T()}],visibility:["visible","invisible","collapse"],z:[{z:[ct,"auto",Q,J]}],basis:[{basis:[St,"full","auto",l,...S()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[de,St,"auto","initial","none",J]}],grow:[{grow:["",de,Q,J]}],shrink:[{shrink:["",de,Q,J]}],order:[{order:[ct,"first","last","none",Q,J]}],"grid-cols":[{"grid-cols":L()}],"col-start-end":[{col:V()}],"col-start":[{"col-start":O()}],"col-end":[{"col-end":O()}],"grid-rows":[{"grid-rows":L()}],"row-start-end":[{row:V()}],"row-start":[{"row-start":O()}],"row-end":[{"row-end":O()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":$()}],"auto-rows":[{"auto-rows":$()}],gap:[{gap:S()}],"gap-x":[{"gap-x":S()}],"gap-y":[{"gap-y":S()}],"justify-content":[{justify:[...k(),"normal"]}],"justify-items":[{"justify-items":[...z(),"normal"]}],"justify-self":[{"justify-self":["auto",...z()]}],"align-content":[{content:["normal",...k()]}],"align-items":[{items:[...z(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...z(),{baseline:["","last"]}]}],"place-content":[{"place-content":k()}],"place-items":[{"place-items":[...z(),"baseline"]}],"place-self":[{"place-self":["auto",...z()]}],p:[{p:S()}],px:[{px:S()}],py:[{py:S()}],ps:[{ps:S()}],pe:[{pe:S()}],pt:[{pt:S()}],pr:[{pr:S()}],pb:[{pb:S()}],pl:[{pl:S()}],m:[{m:A()}],mx:[{mx:A()}],my:[{my:A()}],ms:[{ms:A()}],me:[{me:A()}],mt:[{mt:A()}],mr:[{mr:A()}],mb:[{mb:A()}],ml:[{ml:A()}],"space-x":[{"space-x":S()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":S()}],"space-y-reverse":["space-y-reverse"],size:[{size:E()}],w:[{w:[l,"screen",...E()]}],"min-w":[{"min-w":[l,"screen","none",...E()]}],"max-w":[{"max-w":[l,"screen","none","prose",{screen:[i]},...E()]}],h:[{h:["screen","lh",...E()]}],"min-h":[{"min-h":["screen","lh","none",...E()]}],"max-h":[{"max-h":["screen","lh",...E()]}],"font-size":[{text:["base",r,Lt,pt]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[o,Q,jr]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",yr,J]}],"font-family":[{font:[Ul,J,t]}],"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,Q,J]}],"line-clamp":[{"line-clamp":[de,"none",Q,jr]}],leading:[{leading:[a,...S()]}],"list-image":[{"list-image":["none",Q,J]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Q,J]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:N()}],"text-color":[{text:N()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...U(),"wavy"]}],"text-decoration-thickness":[{decoration:[de,"from-font","auto",Q,pt]}],"text-decoration-color":[{decoration:N()}],"underline-offset":[{"underline-offset":[de,"auto",Q,J]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:S()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Q,J]}],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",Q,J]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:W()}],"bg-repeat":[{bg:q()}],"bg-size":[{bg:G()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},ct,Q,J],radial:["",Q,J],conic:[ct,Q,J]},Xl,Wl]}],"bg-color":[{bg:N()}],"gradient-from-pos":[{from:Z()}],"gradient-via-pos":[{via:Z()}],"gradient-to-pos":[{to:Z()}],"gradient-from":[{from:N()}],"gradient-via":[{via:N()}],"gradient-to":[{to:N()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"border-w":[{border:F()}],"border-w-x":[{"border-x":F()}],"border-w-y":[{"border-y":F()}],"border-w-s":[{"border-s":F()}],"border-w-e":[{"border-e":F()}],"border-w-t":[{"border-t":F()}],"border-w-r":[{"border-r":F()}],"border-w-b":[{"border-b":F()}],"border-w-l":[{"border-l":F()}],"divide-x":[{"divide-x":F()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":F()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...U(),"hidden","none"]}],"divide-style":[{divide:[...U(),"hidden","none"]}],"border-color":[{border:N()}],"border-color-x":[{"border-x":N()}],"border-color-y":[{"border-y":N()}],"border-color-s":[{"border-s":N()}],"border-color-e":[{"border-e":N()}],"border-color-t":[{"border-t":N()}],"border-color-r":[{"border-r":N()}],"border-color-b":[{"border-b":N()}],"border-color-l":[{"border-l":N()}],"divide-color":[{divide:N()}],"outline-style":[{outline:[...U(),"none","hidden"]}],"outline-offset":[{"outline-offset":[de,Q,J]}],"outline-w":[{outline:["",de,Lt,pt]}],"outline-color":[{outline:N()}],shadow:[{shadow:["","none",p,Qt,Jt]}],"shadow-color":[{shadow:N()}],"inset-shadow":[{"inset-shadow":["none",u,Qt,Jt]}],"inset-shadow-color":[{"inset-shadow":N()}],"ring-w":[{ring:F()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:N()}],"ring-offset-w":[{"ring-offset":[de,pt]}],"ring-offset-color":[{"ring-offset":N()}],"inset-ring-w":[{"inset-ring":F()}],"inset-ring-color":[{"inset-ring":N()}],"text-shadow":[{"text-shadow":["none",m,Qt,Jt]}],"text-shadow-color":[{"text-shadow":N()}],opacity:[{opacity:[de,Q,J]}],"mix-blend":[{"mix-blend":[...ee(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ee()}],"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":[de]}],"mask-image-linear-from-pos":[{"mask-linear-from":X()}],"mask-image-linear-to-pos":[{"mask-linear-to":X()}],"mask-image-linear-from-color":[{"mask-linear-from":N()}],"mask-image-linear-to-color":[{"mask-linear-to":N()}],"mask-image-t-from-pos":[{"mask-t-from":X()}],"mask-image-t-to-pos":[{"mask-t-to":X()}],"mask-image-t-from-color":[{"mask-t-from":N()}],"mask-image-t-to-color":[{"mask-t-to":N()}],"mask-image-r-from-pos":[{"mask-r-from":X()}],"mask-image-r-to-pos":[{"mask-r-to":X()}],"mask-image-r-from-color":[{"mask-r-from":N()}],"mask-image-r-to-color":[{"mask-r-to":N()}],"mask-image-b-from-pos":[{"mask-b-from":X()}],"mask-image-b-to-pos":[{"mask-b-to":X()}],"mask-image-b-from-color":[{"mask-b-from":N()}],"mask-image-b-to-color":[{"mask-b-to":N()}],"mask-image-l-from-pos":[{"mask-l-from":X()}],"mask-image-l-to-pos":[{"mask-l-to":X()}],"mask-image-l-from-color":[{"mask-l-from":N()}],"mask-image-l-to-color":[{"mask-l-to":N()}],"mask-image-x-from-pos":[{"mask-x-from":X()}],"mask-image-x-to-pos":[{"mask-x-to":X()}],"mask-image-x-from-color":[{"mask-x-from":N()}],"mask-image-x-to-color":[{"mask-x-to":N()}],"mask-image-y-from-pos":[{"mask-y-from":X()}],"mask-image-y-to-pos":[{"mask-y-to":X()}],"mask-image-y-from-color":[{"mask-y-from":N()}],"mask-image-y-to-color":[{"mask-y-to":N()}],"mask-image-radial":[{"mask-radial":[Q,J]}],"mask-image-radial-from-pos":[{"mask-radial-from":X()}],"mask-image-radial-to-pos":[{"mask-radial-to":X()}],"mask-image-radial-from-color":[{"mask-radial-from":N()}],"mask-image-radial-to-color":[{"mask-radial-to":N()}],"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":M()}],"mask-image-conic-pos":[{"mask-conic":[de]}],"mask-image-conic-from-pos":[{"mask-conic-from":X()}],"mask-image-conic-to-pos":[{"mask-conic-to":X()}],"mask-image-conic-from-color":[{"mask-conic-from":N()}],"mask-image-conic-to-color":[{"mask-conic-to":N()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:W()}],"mask-repeat":[{mask:q()}],"mask-size":[{mask:G()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Q,J]}],filter:[{filter:["","none",Q,J]}],blur:[{blur:Y()}],brightness:[{brightness:[de,Q,J]}],contrast:[{contrast:[de,Q,J]}],"drop-shadow":[{"drop-shadow":["","none",g,Qt,Jt]}],"drop-shadow-color":[{"drop-shadow":N()}],grayscale:[{grayscale:["",de,Q,J]}],"hue-rotate":[{"hue-rotate":[de,Q,J]}],invert:[{invert:["",de,Q,J]}],saturate:[{saturate:[de,Q,J]}],sepia:[{sepia:["",de,Q,J]}],"backdrop-filter":[{"backdrop-filter":["","none",Q,J]}],"backdrop-blur":[{"backdrop-blur":Y()}],"backdrop-brightness":[{"backdrop-brightness":[de,Q,J]}],"backdrop-contrast":[{"backdrop-contrast":[de,Q,J]}],"backdrop-grayscale":[{"backdrop-grayscale":["",de,Q,J]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[de,Q,J]}],"backdrop-invert":[{"backdrop-invert":["",de,Q,J]}],"backdrop-opacity":[{"backdrop-opacity":[de,Q,J]}],"backdrop-saturate":[{"backdrop-saturate":[de,Q,J]}],"backdrop-sepia":[{"backdrop-sepia":["",de,Q,J]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":S()}],"border-spacing-x":[{"border-spacing-x":S()}],"border-spacing-y":[{"border-spacing-y":S()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Q,J]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[de,"initial",Q,J]}],ease:[{ease:["linear","initial",b,Q,J]}],delay:[{delay:[de,Q,J]}],animate:[{animate:["none",w,Q,J]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[x,Q,J]}],"perspective-origin":[{"perspective-origin":R()}],rotate:[{rotate:ae()}],"rotate-x":[{"rotate-x":ae()}],"rotate-y":[{"rotate-y":ae()}],"rotate-z":[{"rotate-z":ae()}],scale:[{scale:te()}],"scale-x":[{"scale-x":te()}],"scale-y":[{"scale-y":te()}],"scale-z":[{"scale-z":te()}],"scale-3d":["scale-3d"],skew:[{skew:ie()}],"skew-x":[{"skew-x":ie()}],"skew-y":[{"skew-y":ie()}],transform:[{transform:[Q,J,"","none","gpu","cpu"]}],"transform-origin":[{origin:R()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:K()}],"translate-x":[{"translate-x":K()}],"translate-y":[{"translate-y":K()}],"translate-z":[{"translate-z":K()}],"translate-none":["translate-none"],accent:[{accent:N()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:N()}],"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",Q,J]}],"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":S()}],"scroll-mx":[{"scroll-mx":S()}],"scroll-my":[{"scroll-my":S()}],"scroll-ms":[{"scroll-ms":S()}],"scroll-me":[{"scroll-me":S()}],"scroll-mt":[{"scroll-mt":S()}],"scroll-mr":[{"scroll-mr":S()}],"scroll-mb":[{"scroll-mb":S()}],"scroll-ml":[{"scroll-ml":S()}],"scroll-p":[{"scroll-p":S()}],"scroll-px":[{"scroll-px":S()}],"scroll-py":[{"scroll-py":S()}],"scroll-ps":[{"scroll-ps":S()}],"scroll-pe":[{"scroll-pe":S()}],"scroll-pt":[{"scroll-pt":S()}],"scroll-pr":[{"scroll-pr":S()}],"scroll-pb":[{"scroll-pb":S()}],"scroll-pl":[{"scroll-pl":S()}],"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",Q,J]}],fill:[{fill:["none",...N()]}],"stroke-w":[{stroke:[de,Lt,pt,jr]}],stroke:[{stroke:["none",...N()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],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-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},Ql=Ll(Jl);function v(...e){return Ql(io(e))}function Ke(e){const t=Math.floor(e/3600),r=Math.floor(e%3600/60),o=Math.floor(e%60);return t>0?`${t}:${r.toString().padStart(2,"0")}:${o.toString().padStart(2,"0")}`:`${r}:${o.toString().padStart(2,"0")}`}const Vn=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,zn=io,Le=(e,t)=>r=>{var o;if((t==null?void 0:t.variants)==null)return zn(e,r==null?void 0:r.class,r==null?void 0:r.className);const{variants:s,defaultVariants:a}=t,i=Object.keys(s).map(c=>{const p=r==null?void 0:r[c],u=a==null?void 0:a[c];if(p===null)return null;const m=Vn(p)||Vn(u);return s[c][m]}),l=r&&Object.entries(r).reduce((c,p)=>{let[u,m]=p;return m===void 0||(c[u]=m),c},{}),d=t==null||(o=t.compoundVariants)===null||o===void 0?void 0:o.reduce((c,p)=>{let{class:u,className:m,...g}=p;return Object.entries(g).every(h=>{let[x,y]=h;return Array.isArray(y)?y.includes({...a,...l}[x]):{...a,...l}[x]===y})?[...c,u,m]:c},[]);return zn(e,i,d,r==null?void 0:r.class,r==null?void 0:r.className)},Ut=Le("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline",brand:"bg-gradient-to-r from-violet-600 to-indigo-600 text-white hover:from-violet-500 hover:to-indigo-500 shadow-lg shadow-violet-500/25 hover:shadow-violet-500/40 hover:scale-[1.02] active:scale-[0.98]",glow:"bg-primary text-primary-foreground shadow-[0_0_20px_rgba(139,92,246,0.5)] hover:shadow-[0_0_30px_rgba(139,92,246,0.7)] hover:scale-[1.02] active:scale-[0.98]"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",xl:"h-12 rounded-lg px-10 text-base",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),ke=f.forwardRef(({className:e,variant:t,size:r,asChild:o=!1,...s},a)=>{const i=o?ro.Slot:"button";return n.jsx(i,{className:v(Ut({variant:t,size:r,className:e})),ref:a,...s})});ke.displayName="Button";const yo=Le("flex w-full rounded-lg text-sm transition-all duration-200 file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",{variants:{variant:{default:"h-10 border border-input bg-background px-3 py-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",filled:"h-10 border-0 bg-muted/50 px-3 py-2 focus-visible:outline-none focus-visible:bg-muted focus-visible:ring-2 focus-visible:ring-ring",glow:"h-10 border border-input bg-background px-3 py-2 ring-offset-background focus-visible:outline-none focus-visible:border-violet-500/50 focus-visible:ring-2 focus-visible:ring-violet-500/30 focus-visible:shadow-[0_0_15px_rgba(139,92,246,0.3)]",ghost:"h-10 border-0 bg-transparent px-3 py-2 focus-visible:outline-none focus-visible:bg-muted/30"},inputSize:{default:"h-10",sm:"h-9 text-xs",lg:"h-12 text-base"}},defaultVariants:{variant:"default",inputSize:"default"}}),mt=f.forwardRef(({className:e,type:t,variant:r,inputSize:o,...s},a)=>n.jsx("input",{type:t,className:v(yo({variant:r,inputSize:o}),e),ref:a,...s}));mt.displayName="Input";const jo=f.forwardRef(({className:e,...t},r)=>n.jsx("textarea",{className:v("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,...t}));jo.displayName="Textarea";const ec=Le("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),mr=f.forwardRef(({className:e,...t},r)=>n.jsx(no.Root,{ref:r,className:v(ec(),e),...t}));mr.displayName=no.Root.displayName;const No=Le("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function Xr({className:e,variant:t,...r}){return n.jsx("div",{className:v(No({variant:t}),e),...r})}const ko=f.forwardRef(({className:e,orientation:t="horizontal",...r},o)=>n.jsx(oo.Root,{ref:o,decorative:!0,orientation:t,className:v("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));ko.displayName=oo.Root.displayName;const Co=f.forwardRef(({className:e,...t},r)=>n.jsx(Rt.Root,{ref:r,className:v("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));Co.displayName=Rt.Root.displayName;const So=f.forwardRef(({className:e,...t},r)=>n.jsx(Rt.Image,{ref:r,className:v("aspect-square h-full w-full",e),...t}));So.displayName=Rt.Image.displayName;const Ro=f.forwardRef(({className:e,...t},r)=>n.jsx(Rt.Fallback,{ref:r,className:v("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));Ro.displayName=Rt.Fallback.displayName;const _o=f.forwardRef(({className:e,...t},r)=>n.jsx(Lr.Root,{ref:r,className:v("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",e),...t,children:n.jsx(Lr.Indicator,{className:v("flex items-center justify-center text-current"),children:n.jsx(P.Check,{className:"h-4 w-4"})})}));_o.displayName=Lr.Root.displayName;const Mo=f.forwardRef(({className:e,...t},r)=>n.jsx(Tr.Root,{className:v("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:r,children:n.jsx(Tr.Thumb,{className:v("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));Mo.displayName=Tr.Root.displayName;const tc=ye.Root,rc=ye.Group,nc=ye.Value,Po=f.forwardRef(({className:e,children:t,...r},o)=>n.jsxs(ye.Trigger,{ref:o,className:v("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...r,children:[t,n.jsx(ye.Icon,{asChild:!0,children:n.jsx(P.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));Po.displayName=ye.Trigger.displayName;const Yr=f.forwardRef(({className:e,...t},r)=>n.jsx(ye.ScrollUpButton,{ref:r,className:v("flex cursor-default items-center justify-center py-1",e),...t,children:n.jsx(P.ChevronUp,{className:"h-4 w-4"})}));Yr.displayName=ye.ScrollUpButton.displayName;const Zr=f.forwardRef(({className:e,...t},r)=>n.jsx(ye.ScrollDownButton,{ref:r,className:v("flex cursor-default items-center justify-center py-1",e),...t,children:n.jsx(P.ChevronDown,{className:"h-4 w-4"})}));Zr.displayName=ye.ScrollDownButton.displayName;const Io=f.forwardRef(({className:e,children:t,position:r="popper",...o},s)=>n.jsx(ye.Portal,{children:n.jsxs(ye.Content,{ref:s,className:v("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",r==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:r,...o,children:[n.jsx(Yr,{}),n.jsx(ye.Viewport,{className:v("p-1",r==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),n.jsx(Zr,{})]})}));Io.displayName=ye.Content.displayName;const Lo=f.forwardRef(({className:e,...t},r)=>n.jsx(ye.Label,{ref:r,className:v("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));Lo.displayName=ye.Label.displayName;const To=f.forwardRef(({className:e,children:t,...r},o)=>n.jsxs(ye.Item,{ref:o,className:v("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...r,children:[n.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:n.jsx(ye.ItemIndicator,{children:n.jsx(P.Check,{className:"h-4 w-4"})})}),n.jsx(ye.ItemText,{children:t})]}));To.displayName=ye.Item.displayName;const Eo=f.forwardRef(({className:e,...t},r)=>n.jsx(ye.Separator,{ref:r,className:v("-mx-1 my-1 h-px bg-muted",e),...t}));Eo.displayName=ye.Separator.displayName;const Do=f.forwardRef(({className:e,...t},r)=>n.jsx($t.Root,{className:v("grid gap-2",e),...t,ref:r}));Do.displayName=$t.Root.displayName;const Ao=f.forwardRef(({className:e,...t},r)=>n.jsx($t.Item,{ref:r,className:v("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:n.jsx($t.Indicator,{className:"flex items-center justify-center",children:n.jsx(P.Circle,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Ao.displayName=$t.Item.displayName;const Fo=f.forwardRef(({className:e,...t},r)=>n.jsxs(Et.Root,{ref:r,className:v("relative flex w-full touch-none select-none items-center",e),...t,children:[n.jsx(Et.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:n.jsx(Et.Range,{className:"absolute h-full bg-primary"})}),n.jsx(Et.Thumb,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));Fo.displayName=Et.Root.displayName;const Jr=Le("inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground"},size:{default:"h-10 px-3",sm:"h-9 px-2.5",lg:"h-11 px-5"}},defaultVariants:{variant:"default",size:"default"}}),Vo=f.forwardRef(({className:e,variant:t,size:r,...o},s)=>n.jsx(so.Root,{ref:s,className:v(Jr({variant:t,size:r,className:e})),...o}));Vo.displayName=so.Root.displayName;const zo=f.forwardRef(({className:e,variant:t,size:r,children:o,...s},a)=>n.jsx(dr.Root,{ref:a,className:v("flex items-center justify-center gap-1",e),...s,children:n.jsx($o.Provider,{value:{variant:t,size:r},children:o})}));zo.displayName=dr.Root.displayName;const $o=f.createContext({size:"default",variant:"default"}),Bo=f.forwardRef(({className:e,children:t,variant:r,size:o,...s},a)=>{const i=f.useContext($o);return n.jsx(dr.Item,{ref:a,className:v(Jr({variant:i.variant||r,size:i.size||o}),e),...s,children:t})});Bo.displayName=dr.Item.displayName;function Qr({selected:e,onSelect:t,className:r,disabled:o}){const[s,a]=f.useState(()=>e?_e.startOfMonth(e):_e.startOfMonth(new Date)),i=_e.startOfMonth(s),l=_e.endOfMonth(s),d=_e.startOfWeek(i,{weekStartsOn:1}),c=_e.endOfWeek(l,{weekStartsOn:1}),p=_e.eachDayOfInterval({start:d,end:c}),u=["Mo","Tu","We","Th","Fr","Sa","Su"],m=()=>{a(_e.subMonths(s,1))},g=()=>{a(_e.addMonths(s,1))},h=x=>{o!=null&&o(x)||t==null||t(_e.isSameDay(x,e||new Date(0))?void 0:x)};return n.jsxs("div",{className:v("p-4 bg-card rounded-xl border shadow-sm w-[320px]",r),children:[n.jsxs("div",{className:"flex items-center justify-between mb-4",children:[n.jsx(ke,{variant:"ghost",size:"icon",onClick:m,className:"h-8 w-8 rounded-full hover:bg-accent",children:n.jsx(P.ChevronLeft,{className:"h-4 w-4"})}),n.jsx("h2",{className:"text-base font-semibold",children:_e.format(s,"MMMM yyyy")}),n.jsx(ke,{variant:"ghost",size:"icon",onClick:g,className:"h-8 w-8 rounded-full hover:bg-accent",children:n.jsx(P.ChevronRight,{className:"h-4 w-4"})})]}),n.jsx("div",{className:"grid grid-cols-7 gap-1 mb-2",children:u.map(x=>n.jsx("div",{className:"h-8 flex items-center justify-center text-xs font-medium text-muted-foreground",children:x},x))}),n.jsx("div",{className:"grid grid-cols-7 gap-1",children:p.map((x,y)=>{const b=_e.isSameMonth(x,s),w=e&&_e.isSameDay(x,e),j=_e.isToday(x),M=o==null?void 0:o(x);return n.jsx("button",{onClick:()=>h(x),disabled:M,className:v("h-10 w-10 rounded-lg text-sm font-medium transition-all duration-150","flex items-center justify-center","hover:bg-accent focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1",!b&&"text-muted-foreground/40",b&&!w&&"text-foreground hover:text-foreground",w&&"bg-primary text-primary-foreground hover:bg-primary/90 shadow-md",j&&!w&&"bg-accent text-accent-foreground font-bold",M&&"opacity-30 cursor-not-allowed hover:bg-transparent"),children:_e.format(x,"d")},y)})}),n.jsxs("div",{className:"mt-4 pt-3 border-t flex justify-between items-center",children:[n.jsx(ke,{variant:"ghost",size:"sm",onClick:()=>{const x=new Date;a(_e.startOfMonth(x)),t==null||t(x)},className:"text-xs",children:"Today"}),e&&n.jsx("span",{className:"text-xs text-muted-foreground",children:_e.format(e,"MMM d, yyyy")})]})]})}Qr.displayName="Calendar";const Pt=Bt.Root,It=Bt.Trigger,yt=f.forwardRef(({className:e,align:t="center",sideOffset:r=4,...o},s)=>n.jsx(Bt.Portal,{children:n.jsx(Bt.Content,{ref:s,align:t,sideOffset:r,className:v("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...o})}));yt.displayName=Bt.Content.displayName;const Ot={chatInput_placeholder:"Type a message...",chatInput_attachFile:"Attach file",chatInput_stopGenerating:"Stop generating",chatInput_sendMessage:"Send message",conversationList_newChat:"New Chat",conversationList_searchPlaceholder:"Search conversations...",conversationList_noResults:"No conversations found",conversationList_empty:"No conversations yet",conversationList_today:"Today",conversationList_yesterday:"Yesterday",conversationList_previous7Days:"Previous 7 days",conversationList_older:"Older",conversationList_rename:"Rename",conversationList_delete:"Delete",chatHeader_online:"Online",chatHeader_offline:"Offline",chatHeader_typing:"Typing...",chatHeader_back:"Back",chatHeader_clearConversation:"Clear conversation",chatHeader_settings:"Settings",reasoning_title:"Reasoning",reasoning_thinking:"Thinking",reasoning_thoughtFor:"Thought for {duration}",toolCall_calling:"Calling {name}...",toolCall_failed:"{name} — failed",toolCall_arguments:"Arguments",toolCall_result:"Result",toolCall_error:"Error",messageActions_copy:"Copy",messageActions_retry:"Retry",messageActions_edit:"Edit",messageActions_like:"Like",messageActions_dislike:"Dislike",messageActions_share:"Share",messageActions_copied:"Copied!",followUp_freeTextPlaceholder:"Or type your answer...",followUp_send:"Send",sourceCitation_sources:"Sources",aiLoading_thinking:"Thinking",filePreview_remove:"Remove {name}",modelSelector_placeholder:"Select model",modelSelector_searchPlaceholder:"Search models...",modelSelector_noResults:"No models found",common_close:"Close",common_search:"Search",common_noResults:"No results found.",common_previous:"Previous",common_next:"Next",common_more:"More",common_copyCode:"Copy code",combobox_placeholder:"Select option...",combobox_searchPlaceholder:"Search...",combobox_empty:"No results found.",multiselect_placeholder:"Select options...",multiselect_searchPlaceholder:"Search...",multiselect_empty:"No results found.",multiselect_selected:"{count} selected",datePicker_placeholder:"Pick a date",dataTable_searchPlaceholder:"Search...",dataTable_noResults:"No results.",dataTable_pageOf:"Page {page} of {total}",dataTable_previous:"Previous",dataTable_next:"Next",fileUpload_dragDrop:"Drag & drop files here, or click to select",fileUpload_maxSize:"Max file size: {size}",tagInput_placeholder:"Add tag...",pagination_previous:"Previous",pagination_next:"Next",pagination_morePages:"More pages",pagination_goToPrevious:"Go to previous page",pagination_goToNext:"Go to next page",modeToggle_toggleTheme:"Toggle theme",modeToggle_light:"Light",modeToggle_dark:"Dark",modeToggle_system:"System",modeToggle_colorTheme:"Color theme",carousel_previousSlide:"Previous slide",carousel_nextSlide:"Next slide",breadcrumb_more:"More",audioPlayer_play:"Play",audioPlayer_pause:"Pause",audioPlayer_mute:"Mute",audioPlayer_unmute:"Unmute",audioPlayer_seek:"Seek",audioPlayer_volume:"Volume",audioPlayer_error:"Audio failed to load",audioPlayer_loading:"Loading...",audioRecorder_startRecording:"Start recording",audioRecorder_stopRecording:"Stop recording",audioRecorder_pauseRecording:"Pause recording",audioRecorder_resumeRecording:"Resume recording",audioRecorder_reRecord:"Re-record",audioRecorder_microphoneAccess:"Microphone access required",audioRecorder_error:"Recording failed",audioRecorder_permissionDenied:"Microphone access denied",audioWaveform_label:"Audio waveform",audioWaveform_error:"Failed to load audio waveform",audioPlaylist_shuffle:"Shuffle",audioPlaylist_repeatOff:"Repeat off",audioPlaylist_repeatAll:"Repeat all",audioPlaylist_repeatOne:"Repeat one",audioPlaylist_previousTrack:"Previous track",audioPlaylist_nextTrack:"Next track",audioPlaylist_trackOf:"Track {current} of {total}",audioPlaylist_empty:"No tracks in playlist",videoPlayer_play:"Play",videoPlayer_pause:"Pause",videoPlayer_mute:"Mute",videoPlayer_unmute:"Unmute",videoPlayer_seek:"Seek",videoPlayer_volume:"Volume",videoPlayer_fullscreen:"Fullscreen",videoPlayer_exitFullscreen:"Exit fullscreen",videoPlayer_pictureInPicture:"Picture in picture",videoPlayer_playbackSpeed:"Playback speed",videoPlayer_subtitles:"Subtitles",videoPlayer_subtitlesOff:"Off",videoPlayer_label:"Video player",videoPlayer_loading:"Loading...",videoPlayer_error:"Video failed to load",videoRecorder_startCamera:"Start camera",videoRecorder_shareScreen:"Share screen",videoRecorder_startRecording:"Start recording",videoRecorder_stopRecording:"Stop recording",videoRecorder_pauseRecording:"Pause recording",videoRecorder_resumeRecording:"Resume recording",videoRecorder_reRecord:"Re-record",videoRecorder_cameraPreview:"Camera preview",videoRecorder_screenPreview:"Screen preview",videoRecorder_error:"Recording failed",videoRecorder_permissionDenied:"Camera access denied",videoThumbnail_play:"Play video: {title}",videoGallery_label:"Video gallery",image_loading:"Loading image",image_zoomIn:"Zoom in",image_failedToLoad:"Image failed to load",lightbox_label:"Image viewer",lightbox_zoomIn:"Zoom in",lightbox_zoomOut:"Zoom out",lightbox_imageOf:"{current} of {total}",lightbox_download:"Download",imageCropper_label:"Image crop area",imageCropper_crop:"Crop",imageCropper_reset:"Reset",imageCropper_cropFailed:"Failed to create cropped image",imageCompare_slider:"Image comparison slider",imageCompare_before:"Before",imageCompare_after:"After"},Oo={chatInput_placeholder:"Введите сообщение...",chatInput_attachFile:"Прикрепить файл",chatInput_stopGenerating:"Остановить генерацию",chatInput_sendMessage:"Отправить сообщение",conversationList_newChat:"Новый чат",conversationList_searchPlaceholder:"Поиск диалогов...",conversationList_noResults:"Диалоги не найдены",conversationList_empty:"Нет диалогов",conversationList_today:"Сегодня",conversationList_yesterday:"Вчера",conversationList_previous7Days:"Последние 7 дней",conversationList_older:"Ранее",conversationList_rename:"Переименовать",conversationList_delete:"Удалить",chatHeader_online:"Онлайн",chatHeader_offline:"Не в сети",chatHeader_typing:"Печатает...",chatHeader_back:"Назад",chatHeader_clearConversation:"Очистить диалог",chatHeader_settings:"Настройки",reasoning_title:"Рассуждение",reasoning_thinking:"Думаю",reasoning_thoughtFor:"Думал {duration}",toolCall_calling:"Вызываю {name}...",toolCall_failed:"{name} — ошибка",toolCall_arguments:"Аргументы",toolCall_result:"Результат",toolCall_error:"Ошибка",messageActions_copy:"Копировать",messageActions_retry:"Повторить",messageActions_edit:"Редактировать",messageActions_like:"Нравится",messageActions_dislike:"Не нравится",messageActions_share:"Поделиться",messageActions_copied:"Скопировано!",followUp_freeTextPlaceholder:"Или введите свой ответ...",followUp_send:"Отправить",sourceCitation_sources:"Источники",aiLoading_thinking:"Думаю",filePreview_remove:"Удалить {name}",modelSelector_placeholder:"Выберите модель",modelSelector_searchPlaceholder:"Поиск моделей...",modelSelector_noResults:"Модели не найдены",common_close:"Закрыть",common_search:"Поиск",common_noResults:"Ничего не найдено.",common_previous:"Назад",common_next:"Далее",common_more:"Ещё",common_copyCode:"Копировать код",combobox_placeholder:"Выберите...",combobox_searchPlaceholder:"Поиск...",combobox_empty:"Ничего не найдено.",multiselect_placeholder:"Выберите...",multiselect_searchPlaceholder:"Поиск...",multiselect_empty:"Ничего не найдено.",multiselect_selected:"{count} выбрано",datePicker_placeholder:"Выберите дату",dataTable_searchPlaceholder:"Поиск...",dataTable_noResults:"Нет результатов.",dataTable_pageOf:"Страница {page} из {total}",dataTable_previous:"Назад",dataTable_next:"Далее",fileUpload_dragDrop:"Перетащите файлы сюда или нажмите для выбора",fileUpload_maxSize:"Макс. размер файла: {size}",tagInput_placeholder:"Добавить тег...",pagination_previous:"Назад",pagination_next:"Далее",pagination_morePages:"Ещё страницы",pagination_goToPrevious:"Предыдущая страница",pagination_goToNext:"Следующая страница",modeToggle_toggleTheme:"Сменить тему",modeToggle_light:"Светлая",modeToggle_dark:"Тёмная",modeToggle_system:"Системная",modeToggle_colorTheme:"Цветовая тема",carousel_previousSlide:"Предыдущий слайд",carousel_nextSlide:"Следующий слайд",breadcrumb_more:"Ещё",audioPlayer_play:"Воспроизвести",audioPlayer_pause:"Пауза",audioPlayer_mute:"Выключить звук",audioPlayer_unmute:"Включить звук",audioPlayer_seek:"Перемотка",audioPlayer_volume:"Громкость",audioPlayer_error:"Не удалось загрузить аудио",audioPlayer_loading:"Загрузка...",audioRecorder_startRecording:"Начать запись",audioRecorder_stopRecording:"Остановить запись",audioRecorder_pauseRecording:"Приостановить запись",audioRecorder_resumeRecording:"Продолжить запись",audioRecorder_reRecord:"Перезаписать",audioRecorder_microphoneAccess:"Требуется доступ к микрофону",audioRecorder_error:"Ошибка записи",audioRecorder_permissionDenied:"Нет доступа к микрофону",audioWaveform_label:"Звуковая волна",audioWaveform_error:"Не удалось загрузить звуковую волну",audioPlaylist_shuffle:"Перемешать",audioPlaylist_repeatOff:"Повтор выключен",audioPlaylist_repeatAll:"Повторять все",audioPlaylist_repeatOne:"Повторять одну",audioPlaylist_previousTrack:"Предыдущий трек",audioPlaylist_nextTrack:"Следующий трек",audioPlaylist_trackOf:"Трек {current} из {total}",audioPlaylist_empty:"Нет треков в плейлисте",videoPlayer_play:"Воспроизвести",videoPlayer_pause:"Пауза",videoPlayer_mute:"Выключить звук",videoPlayer_unmute:"Включить звук",videoPlayer_seek:"Перемотка",videoPlayer_volume:"Громкость",videoPlayer_fullscreen:"Полный экран",videoPlayer_exitFullscreen:"Выйти из полного экрана",videoPlayer_pictureInPicture:"Картинка в картинке",videoPlayer_playbackSpeed:"Скорость воспроизведения",videoPlayer_subtitles:"Субтитры",videoPlayer_subtitlesOff:"Выключены",videoPlayer_label:"Видеоплеер",videoPlayer_loading:"Загрузка...",videoPlayer_error:"Не удалось загрузить видео",videoRecorder_startCamera:"Включить камеру",videoRecorder_shareScreen:"Поделиться экраном",videoRecorder_startRecording:"Начать запись",videoRecorder_stopRecording:"Остановить запись",videoRecorder_pauseRecording:"Приостановить запись",videoRecorder_resumeRecording:"Продолжить запись",videoRecorder_reRecord:"Перезаписать",videoRecorder_cameraPreview:"Предпросмотр камеры",videoRecorder_screenPreview:"Предпросмотр экрана",videoRecorder_error:"Ошибка записи",videoRecorder_permissionDenied:"Нет доступа к камере",videoThumbnail_play:"Воспроизвести видео: {title}",videoGallery_label:"Галерея видео",image_loading:"Загрузка изображения",image_zoomIn:"Увеличить",image_failedToLoad:"Не удалось загрузить изображение",lightbox_label:"Просмотр изображений",lightbox_zoomIn:"Увеличить",lightbox_zoomOut:"Уменьшить",lightbox_imageOf:"{current} из {total}",lightbox_download:"Скачать",imageCropper_label:"Область обрезки",imageCropper_crop:"Обрезать",imageCropper_reset:"Сбросить",imageCropper_cropFailed:"Не удалось создать обрезанное изображение",imageCompare_slider:"Сравнение изображений",imageCompare_before:"До",imageCompare_after:"После"};function $n(e,t){if(!e)return;const r=t.split(".");let o=e;for(const s of r){if(o===void 0||typeof o=="string")return;o=o[s]}return typeof o=="string"?o:void 0}function sr(e,t){if(!t)return e;let r=e;for(const[o,s]of Object.entries(t))r=r.replaceAll(`{${o}}`,String(s));return r}const oc={en:Ot,ru:Oo},Ho=f.createContext(Ot),Go=f.createContext({lang:"en",messages:{}});function qo({locale:e="en",messages:t,children:r}){const o=typeof e=="string"?e:"en",s=f.useMemo(()=>typeof e=="string"?oc[e]??Ot:{...Ot,...e},[e]),a=f.useMemo(()=>({lang:o,messages:t??{}}),[o,t]);return n.jsx(Go.Provider,{value:a,children:n.jsx(Ho.Provider,{value:s,children:r})})}function ce(){return f.useContext(Ho)}function sc(){const{lang:e,messages:t}=f.useContext(Go);return{t:f.useCallback((o,s)=>{const a=$n(t[e],o);if(a!==void 0)return sr(a,s);if(e!=="en"){const i=$n(t.en,o);if(i!==void 0)return sr(i,s)}return sr(o,s)},[e,t]),lang:e}}function ze(e,t){return sr(e,t)}function ac({value:e,onChange:t,placeholder:r,disabled:o,className:s}){const a=ce(),i=r??a.datePicker_placeholder,[l,d]=f.useState(!1);return n.jsxs(Pt,{open:l,onOpenChange:d,children:[n.jsx(It,{asChild:!0,children:n.jsxs(ke,{variant:"outline",disabled:o,className:v("w-full justify-start text-left font-normal",!e&&"text-muted-foreground",s),children:[n.jsx(P.CalendarIcon,{className:"mr-2 h-4 w-4"}),e?_e.format(e,"PPP"):n.jsx("span",{children:i})]})}),n.jsx(yt,{className:"w-auto p-0",align:"start",children:n.jsx(Qr,{selected:e,onSelect:c=>{t==null||t(c),d(!1)}})})]})}function ic({value:e={hours:12,minutes:0},onChange:t,is24Hour:r=!1,disabled:o,className:s}){const[a,i]=f.useState(!1),[l,d]=f.useState(e.hours>=12?"PM":"AM"),c=r?e.hours:e.hours===0?12:e.hours>12?e.hours-12:e.hours,p=()=>{const y=c.toString().padStart(2,"0"),b=e.minutes.toString().padStart(2,"0");return r?`${y}:${b}`:`${y}:${b} ${l}`},u=y=>{let b=y;r||(l==="PM"&&y!==12&&(b+=12),l==="AM"&&y===12&&(b=0)),t==null||t({...e,hours:b})},m=y=>{t==null||t({...e,minutes:y})},g=y=>{d(y);let b=e.hours;y==="PM"&&e.hours<12&&(b+=12),y==="AM"&&e.hours>=12&&(b-=12),t==null||t({...e,hours:b})},h=r?Array.from({length:24},(y,b)=>b):Array.from({length:12},(y,b)=>b+1),x=Array.from({length:12},(y,b)=>b*5);return n.jsxs(Pt,{open:a,onOpenChange:i,children:[n.jsx(It,{asChild:!0,children:n.jsxs(ke,{variant:"outline",disabled:o,className:v("w-full justify-start font-normal",s),children:[n.jsx(P.Clock,{className:"mr-2 h-4 w-4"}),p()]})}),n.jsx(yt,{className:"w-auto p-2",align:"start",children:n.jsxs("div",{className:"flex gap-1",children:[n.jsx("div",{className:"h-32 w-12 overflow-y-auto rounded border bg-muted/30",children:h.map(y=>n.jsx("button",{onClick:()=>u(y),className:v("w-full py-1 text-sm font-medium transition-colors","hover:bg-accent",c===y&&"bg-primary text-primary-foreground hover:bg-primary/90"),children:y.toString().padStart(2,"0")},y))}),n.jsx("div",{className:"flex items-center text-muted-foreground font-bold",children:":"}),n.jsx("div",{className:"h-32 w-12 overflow-y-auto rounded border bg-muted/30",children:x.map(y=>n.jsx("button",{onClick:()=>m(y),className:v("w-full py-1 text-sm font-medium transition-colors","hover:bg-accent",e.minutes===y&&"bg-primary text-primary-foreground hover:bg-primary/90"),children:y.toString().padStart(2,"0")},y))}),!r&&n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("button",{onClick:()=>g("AM"),className:v("px-2 py-1 text-xs font-medium rounded border transition-colors flex-1","hover:bg-accent",l==="AM"&&"bg-primary text-primary-foreground border-primary"),children:"AM"}),n.jsx("button",{onClick:()=>g("PM"),className:v("px-2 py-1 text-xs font-medium rounded border transition-colors flex-1","hover:bg-accent",l==="PM"&&"bg-primary text-primary-foreground border-primary"),children:"PM"})]})]})})]})}function lc({value:e=0,onChange:t,min:r=-1/0,max:o=1/0,step:s=1,disabled:a,className:i}){const l=()=>{const p=Math.min(e+s,o);t==null||t(p)},d=()=>{const p=Math.max(e-s,r);t==null||t(p)},c=p=>{const u=parseFloat(p.target.value);if(!isNaN(u)){const m=Math.min(Math.max(u,r),o);t==null||t(m)}};return n.jsxs("div",{className:v("flex items-center gap-2",i),children:[n.jsx(ke,{type:"button",variant:"outline",size:"icon",onClick:d,disabled:a||e<=r,className:"h-9 w-9",children:n.jsx(P.Minus,{className:"h-4 w-4"})}),n.jsx(mt,{type:"number",value:e,onChange:c,disabled:a,className:"w-20 text-center [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",min:r,max:o,step:s}),n.jsx(ke,{type:"button",variant:"outline",size:"icon",onClick:l,disabled:a||e>=o,className:"h-9 w-9",children:n.jsx(P.Plus,{className:"h-4 w-4"})})]})}function cc({values:e=[],onChange:t,placeholder:r,disabled:o,className:s,maxTags:a}){const i=ce(),l=r??i.tagInput_placeholder,[d,c]=f.useState(""),p=f.useRef(null),u=g=>{if(g.key==="Enter"&&d.trim()){if(g.preventDefault(),a&&e.length>=a)return;e.includes(d.trim())||t==null||t([...e,d.trim()]),c("")}else g.key==="Backspace"&&!d&&e.length>0&&(t==null||t(e.slice(0,-1)))},m=g=>{t==null||t(e.filter(h=>h!==g))};return n.jsxs("div",{className:v("flex flex-wrap gap-2 rounded-md border border-input bg-background px-3 py-2 focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2",o&&"opacity-50 cursor-not-allowed",s),onClick:()=>{var g;return(g=p.current)==null?void 0:g.focus()},children:[e.map(g=>n.jsxs(Xr,{variant:"secondary",className:"gap-1",children:[g,!o&&n.jsx("button",{type:"button",onClick:h=>{h.stopPropagation(),m(g)},className:"ml-1 rounded-full outline-none hover:bg-muted",children:n.jsx(P.X,{className:"h-3 w-3"})})]},g)),n.jsx("input",{ref:p,type:"text",value:d,onChange:g=>c(g.target.value),onKeyDown:u,placeholder:e.length===0?l:"",disabled:o||(a?e.length>=a:!1),className:"flex-1 min-w-[120px] bg-transparent outline-none placeholder:text-muted-foreground text-sm"})]})}function dc({options:e,value:t,onChange:r,placeholder:o,searchPlaceholder:s,emptyText:a,disabled:i,className:l}){const d=ce(),c=o??d.combobox_placeholder,p=s??d.combobox_searchPlaceholder,u=a??d.combobox_empty,[m,g]=f.useState(!1),[h,x]=f.useState(""),y=e.filter(w=>w.label.toLowerCase().includes(h.toLowerCase())),b=e.find(w=>w.value===t);return n.jsxs(Pt,{open:m,onOpenChange:g,children:[n.jsx(It,{asChild:!0,children:n.jsxs(ke,{variant:"outline",role:"combobox","aria-expanded":m,disabled:i,className:v("w-full justify-between font-normal",!t&&"text-muted-foreground",l),children:[b?b.label:c,n.jsx(P.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),n.jsxs(yt,{className:"w-full p-0",align:"start",children:[n.jsx("div",{className:"p-2 border-b",children:n.jsx(mt,{placeholder:p,value:h,onChange:w=>x(w.target.value),className:"h-8"})}),n.jsx("div",{className:"max-h-60 overflow-auto p-1",children:y.length===0?n.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:u}):y.map(w=>n.jsxs("button",{onClick:()=>{r==null||r(w.value===t?"":w.value),g(!1),x("")},className:v("relative flex w-full cursor-pointer select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none hover:bg-accent hover:text-accent-foreground",t===w.value&&"bg-accent"),children:[n.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:t===w.value&&n.jsx(P.Check,{className:"h-4 w-4"})}),w.label]},w.value))})]})]})}function uc({options:e,value:t=[],onChange:r,placeholder:o,searchPlaceholder:s,emptyText:a,disabled:i,className:l,maxDisplay:d=3}){const c=ce(),p=o??c.multiselect_placeholder,u=s??c.multiselect_searchPlaceholder,m=a??c.multiselect_empty,[g,h]=f.useState(!1),[x,y]=f.useState(""),b=e.filter(_=>_.label.toLowerCase().includes(x.toLowerCase())),w=e.filter(_=>t.includes(_.value)),j=_=>{const C=t.includes(_)?t.filter(S=>S!==_):[...t,_];r==null||r(C)},M=(_,C)=>{C.stopPropagation(),r==null||r(t.filter(S=>S!==_))},R=()=>t.length===0?p:t.length<=d?w.map(_=>_.label).join(", "):ze(c.multiselect_selected,{count:t.length});return n.jsxs(Pt,{open:g,onOpenChange:h,children:[n.jsx(It,{asChild:!0,children:n.jsxs(ke,{variant:"outline",role:"combobox","aria-expanded":g,disabled:i,className:v("w-full justify-between font-normal",t.length===0&&"text-muted-foreground",l),children:[n.jsx("span",{className:"truncate",children:R()}),n.jsx(P.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),n.jsxs(yt,{className:"w-full p-0",align:"start",children:[n.jsx("div",{className:"p-2 border-b",children:n.jsx(mt,{placeholder:u,value:x,onChange:_=>y(_.target.value),className:"h-8"})}),t.length>0&&n.jsx("div",{className:"flex flex-wrap gap-1 p-2 border-b",children:w.map(_=>n.jsxs(Xr,{variant:"secondary",className:"pr-1",children:[_.label,n.jsx("button",{onClick:C=>M(_.value,C),className:"ml-1 rounded-full hover:bg-muted",children:n.jsx(P.X,{className:"h-3 w-3"})})]},_.value))}),n.jsx("div",{className:"max-h-60 overflow-auto p-1",children:b.length===0?n.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:m}):b.map(_=>{const C=t.includes(_.value);return n.jsxs("button",{onClick:()=>j(_.value),className:v("relative flex w-full cursor-pointer select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none hover:bg-accent hover:text-accent-foreground",C&&"bg-accent"),children:[n.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:C&&n.jsx(P.Check,{className:"h-4 w-4"})}),_.label]},_.value)})})]})]})}function mc({length:e=6,value:t="",onChange:r,onComplete:o,disabled:s,className:a}){const i=f.useRef([]),l=(p,u)=>{var h;if(!/^\d*$/.test(u))return;const m=t.split("");m[p]=u;const g=m.join("").slice(0,e);r==null||r(g),u&&p<e-1&&((h=i.current[p+1])==null||h.focus()),g.length===e&&(o==null||o(g))},d=(p,u)=>{var m;u.key==="Backspace"&&!t[p]&&p>0&&((m=i.current[p-1])==null||m.focus())},c=p=>{var m;p.preventDefault();const u=p.clipboardData.getData("text").replace(/\D/g,"").slice(0,e);r==null||r(u),u.length===e&&(o==null||o(u)),(m=i.current[Math.min(u.length,e-1)])==null||m.focus()};return n.jsx("div",{className:v("flex gap-2",a),children:Array.from({length:e}).map((p,u)=>n.jsx("input",{ref:m=>{i.current[u]=m},type:"text",inputMode:"numeric",maxLength:1,value:t[u]||"",onChange:m=>l(u,m.target.value),onKeyDown:m=>d(u,m),onPaste:c,disabled:s,className:v("h-12 w-12 rounded-lg border border-input bg-background text-center text-lg font-semibold","focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2","disabled:opacity-50 disabled:cursor-not-allowed")},u))})}function fc({accept:e,maxSize:t,multiple:r=!1,onUpload:o,disabled:s,className:a}){const[i,l]=f.useState([]),[d,c]=f.useState(!1),p=f.useRef(null),u=ce(),m=w=>{if(!w)return;const j=Array.from(w).filter(R=>!(t&&R.size>t)),M=r?[...i,...j]:j.slice(0,1);l(M),o==null||o(M)},g=w=>{w.preventDefault(),c(!1),s||m(w.dataTransfer.files)},h=w=>{w.preventDefault(),s||c(!0)},x=()=>{c(!1)},y=w=>{const j=i.filter((M,R)=>R!==w);l(j),o==null||o(j)},b=w=>w<1024?w+" B":w<1024*1024?(w/1024).toFixed(1)+" KB":(w/(1024*1024)).toFixed(1)+" MB";return n.jsxs("div",{className:v("space-y-4",a),children:[n.jsxs("div",{onClick:()=>{var w;return!s&&((w=p.current)==null?void 0:w.click())},onDrop:g,onDragOver:h,onDragLeave:x,className:v("border-2 border-dashed rounded-lg p-8 text-center transition-colors cursor-pointer",d?"border-primary bg-primary/5":"border-muted-foreground/25",s&&"opacity-50 cursor-not-allowed","hover:border-primary/50"),children:[n.jsx(P.Upload,{className:"h-10 w-10 mx-auto mb-4 text-muted-foreground"}),n.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:u.fileUpload_dragDrop}),t&&n.jsx("p",{className:"text-xs text-muted-foreground",children:ze(u.fileUpload_maxSize,{size:b(t)})}),n.jsx("input",{ref:p,type:"file",accept:e,multiple:r,onChange:w=>m(w.target.files),disabled:s,className:"hidden"})]}),i.length>0&&n.jsx("div",{className:"space-y-2",children:i.map((w,j)=>n.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-muted/50",children:[n.jsx(P.FileIcon,{className:"h-8 w-8 text-muted-foreground"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-sm font-medium truncate",children:w.name}),n.jsx("p",{className:"text-xs text-muted-foreground",children:b(w.size)})]}),n.jsx(ke,{type:"button",variant:"ghost",size:"icon",onClick:()=>y(j),className:"h-8 w-8",children:n.jsx(P.X,{className:"h-4 w-4"})})]},j))})]})}const gc=["#ef4444","#f97316","#eab308","#22c55e","#14b8a6","#3b82f6","#8b5cf6","#ec4899","#000000","#ffffff"];function er(e){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);if(!t)return{h:0,s:100,l:50};let r=parseInt(t[1],16)/255,o=parseInt(t[2],16)/255,s=parseInt(t[3],16)/255;const a=Math.max(r,o,s),i=Math.min(r,o,s);let l=0,d=0;const c=(a+i)/2;if(a!==i){const p=a-i;switch(d=c>.5?p/(2-a-i):p/(a+i),a){case r:l=((o-s)/p+(o<s?6:0))/6;break;case o:l=((s-r)/p+2)/6;break;case s:l=((r-o)/p+4)/6;break}}return{h:Math.round(l*360),s:Math.round(d*100),l:Math.round(c*100)}}function pc(e,t,r){t/=100,r/=100;const o=t*Math.min(r,1-r),s=a=>{const i=(a+e/30)%12,l=r-o*Math.max(Math.min(i-3,9-i,1),-1);return Math.round(255*l).toString(16).padStart(2,"0")};return`#${s(0)}${s(8)}${s(4)}`}function hc({value:e="#3b82f6",onChange:t,disabled:r,className:o}){const[s,a]=f.useState(!1),[i,l]=f.useState(()=>er(e)),[d,c]=f.useState(e),p=f.useRef(null);f.useEffect(()=>{l(er(e)),c(e)},[e]);const u=h=>{l(h);const x=pc(h.h,h.s,h.l);c(x),t==null||t(x)},m=h=>{if(!p.current)return;const x=p.current.getBoundingClientRect(),y=Math.max(0,Math.min(1,(h.clientX-x.left)/x.width)),b=Math.max(0,Math.min(1,(h.clientY-x.top)/x.height));u({...i,s:Math.round(y*100),l:Math.round((1-b)*100)})},g=h=>{if(c(h),/^#[0-9A-Fa-f]{6}$/.test(h)){const x=er(h);l(x),t==null||t(h)}};return n.jsxs(Pt,{open:s,onOpenChange:a,children:[n.jsx(It,{asChild:!0,children:n.jsxs(ke,{variant:"outline",disabled:r,className:v("w-full justify-start gap-2",o),children:[n.jsx("div",{className:"h-5 w-5 rounded border shadow-sm",style:{backgroundColor:e}}),n.jsx("span",{className:"font-mono text-sm",children:e})]})}),n.jsx(yt,{className:"w-72 p-3",align:"start",children:n.jsxs("div",{className:"space-y-3",children:[n.jsx("div",{ref:p,onClick:m,className:"relative h-40 rounded-lg cursor-crosshair overflow-hidden border",style:{background:`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("react/jsx-runtime"),Q=require("react"),lc=require("@radix-ui/react-slot"),wg=require("@radix-ui/react-label"),Rg=require("@radix-ui/react-separator"),Ag=require("@radix-ui/react-avatar"),Ig=require("@radix-ui/react-checkbox"),W=require("lucide-react"),Lg=require("@radix-ui/react-switch"),Cg=require("@radix-ui/react-select"),_g=require("@radix-ui/react-radio-group"),kg=require("@radix-ui/react-slider"),Dg=require("@radix-ui/react-toggle"),Pg=require("@radix-ui/react-toggle-group"),ot=require("date-fns"),Ng=require("@radix-ui/react-popover"),Mg=require("@radix-ui/react-aspect-ratio"),Fg=require("@radix-ui/react-collapsible"),Og=require("@radix-ui/react-scroll-area"),jg=require("@radix-ui/react-tabs"),Bg=require("@radix-ui/react-accordion"),$g=require("@radix-ui/react-dialog"),Ug=require("@radix-ui/react-dropdown-menu"),Gg=require("@radix-ui/react-tooltip"),St=require("cmdk"),Vg=require("@radix-ui/react-alert-dialog"),Hg=require("@radix-ui/react-progress"),lo=require("react-dom"),Kg=require("@radix-ui/react-navigation-menu"),zg=require("@radix-ui/react-context-menu"),Wg=require("@radix-ui/react-hover-card"),co=require("recharts");function Be(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const s=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const E=Be(Q),cc=Be(wg),dc=Be(Rg),nr=Be(Ag),_i=Be(Ig),ki=Be(Lg),We=Be(Cg),wr=Be(_g),gr=Be(kg),uc=Be(Dg),Mn=Be(Pg),Rr=Be(Ng),Yg=Be(Mg),uo=Be(Fg),Ps=Be(Og),js=Be(jg),Ms=Be(Bg),Fe=Be($g),Oe=Be(Ug),Or=Be(Gg),gt=Be(Vg),Di=Be(Hg),Et=Be(Kg),je=Be(zg),Fn=Be(Wg);function fc(r){var e,t,s="";if(typeof r=="string"||typeof r=="number")s+=r;else if(typeof r=="object")if(Array.isArray(r)){var n=r.length;for(e=0;e<n;e++)r[e]&&(t=fc(r[e]))&&(s&&(s+=" "),s+=t)}else for(t in r)r[t]&&(s&&(s+=" "),s+=t);return s}function hc(){for(var r,e,t=0,s="",n=arguments.length;t<n;t++)(r=arguments[t])&&(e=fc(r))&&(s&&(s+=" "),s+=e);return s}const qg=(r,e)=>{const t=new Array(r.length+e.length);for(let s=0;s<r.length;s++)t[s]=r[s];for(let s=0;s<e.length;s++)t[r.length+s]=e[s];return t},Xg=(r,e)=>({classGroupId:r,validator:e}),gc=(r=new Map,e=null,t)=>({nextPart:r,validators:e,classGroupId:t}),bn="-",Sa=[],Qg="arbitrary..",Zg=r=>{const e=em(r),{conflictingClassGroups:t,conflictingClassGroupModifiers:s}=r;return{getClassGroupId:o=>{if(o.startsWith("[")&&o.endsWith("]"))return Jg(o);const a=o.split(bn),c=a[0]===""&&a.length>1?1:0;return mc(a,c,e)},getConflictingClassGroupIds:(o,a)=>{if(a){const c=s[o],l=t[o];return c?l?qg(l,c):c:l||Sa}return t[o]||Sa}}},mc=(r,e,t)=>{if(r.length-e===0)return t.classGroupId;const n=r[e],i=t.nextPart.get(n);if(i){const l=mc(r,e+1,i);if(l)return l}const o=t.validators;if(o===null)return;const a=e===0?r.join(bn):r.slice(e).join(bn),c=o.length;for(let l=0;l<c;l++){const d=o[l];if(d.validator(a))return d.classGroupId}},Jg=r=>r.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const e=r.slice(1,-1),t=e.indexOf(":"),s=e.slice(0,t);return s?Qg+s:void 0})(),em=r=>{const{theme:e,classGroups:t}=r;return tm(t,e)},tm=(r,e)=>{const t=gc();for(const s in r){const n=r[s];fo(n,t,s,e)}return t},fo=(r,e,t,s)=>{const n=r.length;for(let i=0;i<n;i++){const o=r[i];sm(o,e,t,s)}},sm=(r,e,t,s)=>{if(typeof r=="string"){rm(r,e,t);return}if(typeof r=="function"){nm(r,e,t,s);return}im(r,e,t,s)},rm=(r,e,t)=>{const s=r===""?e:pc(e,r);s.classGroupId=t},nm=(r,e,t,s)=>{if(om(r)){fo(r(s),e,t,s);return}e.validators===null&&(e.validators=[]),e.validators.push(Xg(t,r))},im=(r,e,t,s)=>{const n=Object.entries(r),i=n.length;for(let o=0;o<i;o++){const[a,c]=n[o];fo(c,pc(e,a),t,s)}},pc=(r,e)=>{let t=r;const s=e.split(bn),n=s.length;for(let i=0;i<n;i++){const o=s[i];let a=t.nextPart.get(o);a||(a=gc(),t.nextPart.set(o,a)),t=a}return t},om=r=>"isThemeGetter"in r&&r.isThemeGetter===!0,am=r=>{if(r<1)return{get:()=>{},set:()=>{}};let e=0,t=Object.create(null),s=Object.create(null);const n=(i,o)=>{t[i]=o,e++,e>r&&(e=0,s=t,t=Object.create(null))};return{get(i){let o=t[i];if(o!==void 0)return o;if((o=s[i])!==void 0)return n(i,o),o},set(i,o){i in t?t[i]=o:n(i,o)}}},Pi="!",Ea=":",lm=[],Ta=(r,e,t,s,n)=>({modifiers:r,hasImportantModifier:e,baseClassName:t,maybePostfixModifierPosition:s,isExternal:n}),cm=r=>{const{prefix:e,experimentalParseClassName:t}=r;let s=n=>{const i=[];let o=0,a=0,c=0,l;const d=n.length;for(let p=0;p<d;p++){const x=n[p];if(o===0&&a===0){if(x===Ea){i.push(n.slice(c,p)),c=p+1;continue}if(x==="/"){l=p;continue}}x==="["?o++:x==="]"?o--:x==="("?a++:x===")"&&a--}const u=i.length===0?n:n.slice(c);let h=u,g=!1;u.endsWith(Pi)?(h=u.slice(0,-1),g=!0):u.startsWith(Pi)&&(h=u.slice(1),g=!0);const m=l&&l>c?l-c:void 0;return Ta(i,g,h,m)};if(e){const n=e+Ea,i=s;s=o=>o.startsWith(n)?i(o.slice(n.length)):Ta(lm,!1,o,void 0,!0)}if(t){const n=s;s=i=>t({className:i,parseClassName:n})}return s},dm=r=>{const e=new Map;return r.orderSensitiveModifiers.forEach((t,s)=>{e.set(t,1e6+s)}),t=>{const s=[];let n=[];for(let i=0;i<t.length;i++){const o=t[i],a=o[0]==="[",c=e.has(o);a||c?(n.length>0&&(n.sort(),s.push(...n),n=[]),s.push(o)):n.push(o)}return n.length>0&&(n.sort(),s.push(...n)),s}},um=r=>({cache:am(r.cacheSize),parseClassName:cm(r),sortModifiers:dm(r),...Zg(r)}),fm=/\s+/,hm=(r,e)=>{const{parseClassName:t,getClassGroupId:s,getConflictingClassGroupIds:n,sortModifiers:i}=e,o=[],a=r.trim().split(fm);let c="";for(let l=a.length-1;l>=0;l-=1){const d=a[l],{isExternal:u,modifiers:h,hasImportantModifier:g,baseClassName:m,maybePostfixModifierPosition:p}=t(d);if(u){c=d+(c.length>0?" "+c:c);continue}let x=!!p,v=s(x?m.substring(0,p):m);if(!v){if(!x){c=d+(c.length>0?" "+c:c);continue}if(v=s(m),!v){c=d+(c.length>0?" "+c:c);continue}x=!1}const y=h.length===0?"":h.length===1?h[0]:i(h).join(":"),b=g?y+Pi:y,T=b+v;if(o.indexOf(T)>-1)continue;o.push(T);const R=n(v,x);for(let _=0;_<R.length;++_){const w=R[_];o.push(b+w)}c=d+(c.length>0?" "+c:c)}return c},gm=(...r)=>{let e=0,t,s,n="";for(;e<r.length;)(t=r[e++])&&(s=xc(t))&&(n&&(n+=" "),n+=s);return n},xc=r=>{if(typeof r=="string")return r;let e,t="";for(let s=0;s<r.length;s++)r[s]&&(e=xc(r[s]))&&(t&&(t+=" "),t+=e);return t},mm=(r,...e)=>{let t,s,n,i;const o=c=>{const l=e.reduce((d,u)=>u(d),r());return t=um(l),s=t.cache.get,n=t.cache.set,i=a,a(c)},a=c=>{const l=s(c);if(l)return l;const d=hm(c,t);return n(c,d),d};return i=o,(...c)=>i(gm(...c))},pm=[],tt=r=>{const e=t=>t[r]||pm;return e.isThemeGetter=!0,e},vc=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,yc=/^\((?:(\w[\w-]*):)?(.+)\)$/i,xm=/^\d+\/\d+$/,vm=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,ym=/\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$/,bm=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Sm=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Em=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Hs=r=>xm.test(r),Se=r=>!!r&&!Number.isNaN(Number(r)),gs=r=>!!r&&Number.isInteger(Number(r)),qn=r=>r.endsWith("%")&&Se(r.slice(0,-1)),os=r=>vm.test(r),Tm=()=>!0,wm=r=>ym.test(r)&&!bm.test(r),bc=()=>!1,Rm=r=>Sm.test(r),Am=r=>Em.test(r),Im=r=>!ae(r)&&!le(r),Lm=r=>ir(r,Tc,bc),ae=r=>vc.test(r),Ls=r=>ir(r,wc,wm),Xn=r=>ir(r,Pm,Se),wa=r=>ir(r,Sc,bc),Cm=r=>ir(r,Ec,Am),Gr=r=>ir(r,Rc,Rm),le=r=>yc.test(r),ur=r=>or(r,wc),_m=r=>or(r,Nm),Ra=r=>or(r,Sc),km=r=>or(r,Tc),Dm=r=>or(r,Ec),Vr=r=>or(r,Rc,!0),ir=(r,e,t)=>{const s=vc.exec(r);return s?s[1]?e(s[1]):t(s[2]):!1},or=(r,e,t=!1)=>{const s=yc.exec(r);return s?s[1]?e(s[1]):t:!1},Sc=r=>r==="position"||r==="percentage",Ec=r=>r==="image"||r==="url",Tc=r=>r==="length"||r==="size"||r==="bg-size",wc=r=>r==="length",Pm=r=>r==="number",Nm=r=>r==="family-name",Rc=r=>r==="shadow",Mm=()=>{const r=tt("color"),e=tt("font"),t=tt("text"),s=tt("font-weight"),n=tt("tracking"),i=tt("leading"),o=tt("breakpoint"),a=tt("container"),c=tt("spacing"),l=tt("radius"),d=tt("shadow"),u=tt("inset-shadow"),h=tt("text-shadow"),g=tt("drop-shadow"),m=tt("blur"),p=tt("perspective"),x=tt("aspect"),v=tt("ease"),y=tt("animate"),b=()=>["auto","avoid","all","avoid-page","page","left","right","column"],T=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],R=()=>[...T(),le,ae],_=()=>["auto","hidden","clip","visible","scroll"],w=()=>["auto","contain","none"],A=()=>[le,ae,c],C=()=>[Hs,"full","auto",...A()],L=()=>[gs,"none","subgrid",le,ae],P=()=>["auto",{span:["full",gs,le,ae]},gs,le,ae],M=()=>[gs,"auto",le,ae],j=()=>["auto","min","max","fr",le,ae],D=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],$=()=>["start","end","center","stretch","center-safe","end-safe"],N=()=>["auto",...A()],F=()=>[Hs,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...A()],k=()=>[r,le,ae],z=()=>[...T(),Ra,wa,{position:[le,ae]}],Y=()=>["no-repeat",{repeat:["","x","y","space","round"]}],U=()=>["auto","cover","contain",km,Lm,{size:[le,ae]}],K=()=>[qn,ur,Ls],G=()=>["","none","full",l,le,ae],H=()=>["",Se,ur,Ls],q=()=>["solid","dashed","dotted","double"],J=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ee=()=>[Se,qn,Ra,wa],te=()=>["","none",m,le,ae],de=()=>["none",Se,le,ae],ie=()=>["none",Se,le,ae],ue=()=>[Se,le,ae],re=()=>[Hs,"full",...A()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[os],breakpoint:[os],color:[Tm],container:[os],"drop-shadow":[os],ease:["in","out","in-out"],font:[Im],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[os],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[os],shadow:[os],spacing:["px",Se],text:[os],"text-shadow":[os],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Hs,ae,le,x]}],container:["container"],columns:[{columns:[Se,ae,le,a]}],"break-after":[{"break-after":b()}],"break-before":[{"break-before":b()}],"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:R()}],overflow:[{overflow:_()}],"overflow-x":[{"overflow-x":_()}],"overflow-y":[{"overflow-y":_()}],overscroll:[{overscroll:w()}],"overscroll-x":[{"overscroll-x":w()}],"overscroll-y":[{"overscroll-y":w()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:C()}],"inset-x":[{"inset-x":C()}],"inset-y":[{"inset-y":C()}],start:[{start:C()}],end:[{end:C()}],top:[{top:C()}],right:[{right:C()}],bottom:[{bottom:C()}],left:[{left:C()}],visibility:["visible","invisible","collapse"],z:[{z:[gs,"auto",le,ae]}],basis:[{basis:[Hs,"full","auto",a,...A()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Se,Hs,"auto","initial","none",ae]}],grow:[{grow:["",Se,le,ae]}],shrink:[{shrink:["",Se,le,ae]}],order:[{order:[gs,"first","last","none",le,ae]}],"grid-cols":[{"grid-cols":L()}],"col-start-end":[{col:P()}],"col-start":[{"col-start":M()}],"col-end":[{"col-end":M()}],"grid-rows":[{"grid-rows":L()}],"row-start-end":[{row:P()}],"row-start":[{"row-start":M()}],"row-end":[{"row-end":M()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":j()}],"auto-rows":[{"auto-rows":j()}],gap:[{gap:A()}],"gap-x":[{"gap-x":A()}],"gap-y":[{"gap-y":A()}],"justify-content":[{justify:[...D(),"normal"]}],"justify-items":[{"justify-items":[...$(),"normal"]}],"justify-self":[{"justify-self":["auto",...$()]}],"align-content":[{content:["normal",...D()]}],"align-items":[{items:[...$(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...$(),{baseline:["","last"]}]}],"place-content":[{"place-content":D()}],"place-items":[{"place-items":[...$(),"baseline"]}],"place-self":[{"place-self":["auto",...$()]}],p:[{p:A()}],px:[{px:A()}],py:[{py:A()}],ps:[{ps:A()}],pe:[{pe:A()}],pt:[{pt:A()}],pr:[{pr:A()}],pb:[{pb:A()}],pl:[{pl:A()}],m:[{m:N()}],mx:[{mx:N()}],my:[{my:N()}],ms:[{ms:N()}],me:[{me:N()}],mt:[{mt:N()}],mr:[{mr:N()}],mb:[{mb:N()}],ml:[{ml:N()}],"space-x":[{"space-x":A()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":A()}],"space-y-reverse":["space-y-reverse"],size:[{size:F()}],w:[{w:[a,"screen",...F()]}],"min-w":[{"min-w":[a,"screen","none",...F()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[o]},...F()]}],h:[{h:["screen","lh",...F()]}],"min-h":[{"min-h":["screen","lh","none",...F()]}],"max-h":[{"max-h":["screen","lh",...F()]}],"font-size":[{text:["base",t,ur,Ls]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[s,le,Xn]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",qn,ae]}],"font-family":[{font:[_m,ae,e]}],"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:[n,le,ae]}],"line-clamp":[{"line-clamp":[Se,"none",le,Xn]}],leading:[{leading:[i,...A()]}],"list-image":[{"list-image":["none",le,ae]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",le,ae]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:k()}],"text-color":[{text:k()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...q(),"wavy"]}],"text-decoration-thickness":[{decoration:[Se,"from-font","auto",le,Ls]}],"text-decoration-color":[{decoration:k()}],"underline-offset":[{"underline-offset":[Se,"auto",le,ae]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:A()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",le,ae]}],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",le,ae]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:z()}],"bg-repeat":[{bg:Y()}],"bg-size":[{bg:U()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},gs,le,ae],radial:["",le,ae],conic:[gs,le,ae]},Dm,Cm]}],"bg-color":[{bg:k()}],"gradient-from-pos":[{from:K()}],"gradient-via-pos":[{via:K()}],"gradient-to-pos":[{to:K()}],"gradient-from":[{from:k()}],"gradient-via":[{via:k()}],"gradient-to":[{to:k()}],rounded:[{rounded:G()}],"rounded-s":[{"rounded-s":G()}],"rounded-e":[{"rounded-e":G()}],"rounded-t":[{"rounded-t":G()}],"rounded-r":[{"rounded-r":G()}],"rounded-b":[{"rounded-b":G()}],"rounded-l":[{"rounded-l":G()}],"rounded-ss":[{"rounded-ss":G()}],"rounded-se":[{"rounded-se":G()}],"rounded-ee":[{"rounded-ee":G()}],"rounded-es":[{"rounded-es":G()}],"rounded-tl":[{"rounded-tl":G()}],"rounded-tr":[{"rounded-tr":G()}],"rounded-br":[{"rounded-br":G()}],"rounded-bl":[{"rounded-bl":G()}],"border-w":[{border:H()}],"border-w-x":[{"border-x":H()}],"border-w-y":[{"border-y":H()}],"border-w-s":[{"border-s":H()}],"border-w-e":[{"border-e":H()}],"border-w-t":[{"border-t":H()}],"border-w-r":[{"border-r":H()}],"border-w-b":[{"border-b":H()}],"border-w-l":[{"border-l":H()}],"divide-x":[{"divide-x":H()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":H()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...q(),"hidden","none"]}],"divide-style":[{divide:[...q(),"hidden","none"]}],"border-color":[{border:k()}],"border-color-x":[{"border-x":k()}],"border-color-y":[{"border-y":k()}],"border-color-s":[{"border-s":k()}],"border-color-e":[{"border-e":k()}],"border-color-t":[{"border-t":k()}],"border-color-r":[{"border-r":k()}],"border-color-b":[{"border-b":k()}],"border-color-l":[{"border-l":k()}],"divide-color":[{divide:k()}],"outline-style":[{outline:[...q(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Se,le,ae]}],"outline-w":[{outline:["",Se,ur,Ls]}],"outline-color":[{outline:k()}],shadow:[{shadow:["","none",d,Vr,Gr]}],"shadow-color":[{shadow:k()}],"inset-shadow":[{"inset-shadow":["none",u,Vr,Gr]}],"inset-shadow-color":[{"inset-shadow":k()}],"ring-w":[{ring:H()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:k()}],"ring-offset-w":[{"ring-offset":[Se,Ls]}],"ring-offset-color":[{"ring-offset":k()}],"inset-ring-w":[{"inset-ring":H()}],"inset-ring-color":[{"inset-ring":k()}],"text-shadow":[{"text-shadow":["none",h,Vr,Gr]}],"text-shadow-color":[{"text-shadow":k()}],opacity:[{opacity:[Se,le,ae]}],"mix-blend":[{"mix-blend":[...J(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":J()}],"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":[Se]}],"mask-image-linear-from-pos":[{"mask-linear-from":ee()}],"mask-image-linear-to-pos":[{"mask-linear-to":ee()}],"mask-image-linear-from-color":[{"mask-linear-from":k()}],"mask-image-linear-to-color":[{"mask-linear-to":k()}],"mask-image-t-from-pos":[{"mask-t-from":ee()}],"mask-image-t-to-pos":[{"mask-t-to":ee()}],"mask-image-t-from-color":[{"mask-t-from":k()}],"mask-image-t-to-color":[{"mask-t-to":k()}],"mask-image-r-from-pos":[{"mask-r-from":ee()}],"mask-image-r-to-pos":[{"mask-r-to":ee()}],"mask-image-r-from-color":[{"mask-r-from":k()}],"mask-image-r-to-color":[{"mask-r-to":k()}],"mask-image-b-from-pos":[{"mask-b-from":ee()}],"mask-image-b-to-pos":[{"mask-b-to":ee()}],"mask-image-b-from-color":[{"mask-b-from":k()}],"mask-image-b-to-color":[{"mask-b-to":k()}],"mask-image-l-from-pos":[{"mask-l-from":ee()}],"mask-image-l-to-pos":[{"mask-l-to":ee()}],"mask-image-l-from-color":[{"mask-l-from":k()}],"mask-image-l-to-color":[{"mask-l-to":k()}],"mask-image-x-from-pos":[{"mask-x-from":ee()}],"mask-image-x-to-pos":[{"mask-x-to":ee()}],"mask-image-x-from-color":[{"mask-x-from":k()}],"mask-image-x-to-color":[{"mask-x-to":k()}],"mask-image-y-from-pos":[{"mask-y-from":ee()}],"mask-image-y-to-pos":[{"mask-y-to":ee()}],"mask-image-y-from-color":[{"mask-y-from":k()}],"mask-image-y-to-color":[{"mask-y-to":k()}],"mask-image-radial":[{"mask-radial":[le,ae]}],"mask-image-radial-from-pos":[{"mask-radial-from":ee()}],"mask-image-radial-to-pos":[{"mask-radial-to":ee()}],"mask-image-radial-from-color":[{"mask-radial-from":k()}],"mask-image-radial-to-color":[{"mask-radial-to":k()}],"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":T()}],"mask-image-conic-pos":[{"mask-conic":[Se]}],"mask-image-conic-from-pos":[{"mask-conic-from":ee()}],"mask-image-conic-to-pos":[{"mask-conic-to":ee()}],"mask-image-conic-from-color":[{"mask-conic-from":k()}],"mask-image-conic-to-color":[{"mask-conic-to":k()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:z()}],"mask-repeat":[{mask:Y()}],"mask-size":[{mask:U()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",le,ae]}],filter:[{filter:["","none",le,ae]}],blur:[{blur:te()}],brightness:[{brightness:[Se,le,ae]}],contrast:[{contrast:[Se,le,ae]}],"drop-shadow":[{"drop-shadow":["","none",g,Vr,Gr]}],"drop-shadow-color":[{"drop-shadow":k()}],grayscale:[{grayscale:["",Se,le,ae]}],"hue-rotate":[{"hue-rotate":[Se,le,ae]}],invert:[{invert:["",Se,le,ae]}],saturate:[{saturate:[Se,le,ae]}],sepia:[{sepia:["",Se,le,ae]}],"backdrop-filter":[{"backdrop-filter":["","none",le,ae]}],"backdrop-blur":[{"backdrop-blur":te()}],"backdrop-brightness":[{"backdrop-brightness":[Se,le,ae]}],"backdrop-contrast":[{"backdrop-contrast":[Se,le,ae]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Se,le,ae]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Se,le,ae]}],"backdrop-invert":[{"backdrop-invert":["",Se,le,ae]}],"backdrop-opacity":[{"backdrop-opacity":[Se,le,ae]}],"backdrop-saturate":[{"backdrop-saturate":[Se,le,ae]}],"backdrop-sepia":[{"backdrop-sepia":["",Se,le,ae]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":A()}],"border-spacing-x":[{"border-spacing-x":A()}],"border-spacing-y":[{"border-spacing-y":A()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",le,ae]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Se,"initial",le,ae]}],ease:[{ease:["linear","initial",v,le,ae]}],delay:[{delay:[Se,le,ae]}],animate:[{animate:["none",y,le,ae]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[p,le,ae]}],"perspective-origin":[{"perspective-origin":R()}],rotate:[{rotate:de()}],"rotate-x":[{"rotate-x":de()}],"rotate-y":[{"rotate-y":de()}],"rotate-z":[{"rotate-z":de()}],scale:[{scale:ie()}],"scale-x":[{"scale-x":ie()}],"scale-y":[{"scale-y":ie()}],"scale-z":[{"scale-z":ie()}],"scale-3d":["scale-3d"],skew:[{skew:ue()}],"skew-x":[{"skew-x":ue()}],"skew-y":[{"skew-y":ue()}],transform:[{transform:[le,ae,"","none","gpu","cpu"]}],"transform-origin":[{origin:R()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:re()}],"translate-x":[{"translate-x":re()}],"translate-y":[{"translate-y":re()}],"translate-z":[{"translate-z":re()}],"translate-none":["translate-none"],accent:[{accent:k()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:k()}],"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",le,ae]}],"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":A()}],"scroll-mx":[{"scroll-mx":A()}],"scroll-my":[{"scroll-my":A()}],"scroll-ms":[{"scroll-ms":A()}],"scroll-me":[{"scroll-me":A()}],"scroll-mt":[{"scroll-mt":A()}],"scroll-mr":[{"scroll-mr":A()}],"scroll-mb":[{"scroll-mb":A()}],"scroll-ml":[{"scroll-ml":A()}],"scroll-p":[{"scroll-p":A()}],"scroll-px":[{"scroll-px":A()}],"scroll-py":[{"scroll-py":A()}],"scroll-ps":[{"scroll-ps":A()}],"scroll-pe":[{"scroll-pe":A()}],"scroll-pt":[{"scroll-pt":A()}],"scroll-pr":[{"scroll-pr":A()}],"scroll-pb":[{"scroll-pb":A()}],"scroll-pl":[{"scroll-pl":A()}],"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",le,ae]}],fill:[{fill:["none",...k()]}],"stroke-w":[{stroke:[Se,ur,Ls,Xn]}],stroke:[{stroke:["none",...k()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],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-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},Fm=mm(Mm);function I(...r){return Fm(hc(r))}function Dt(r){const e=Math.floor(r/3600),t=Math.floor(r%3600/60),s=Math.floor(r%60);return e>0?`${e}:${t.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}`:`${t}:${s.toString().padStart(2,"0")}`}const Aa=r=>typeof r=="boolean"?`${r}`:r===0?"0":r,Ia=hc,ft=(r,e)=>t=>{var s;if((e==null?void 0:e.variants)==null)return Ia(r,t==null?void 0:t.class,t==null?void 0:t.className);const{variants:n,defaultVariants:i}=e,o=Object.keys(n).map(l=>{const d=t==null?void 0:t[l],u=i==null?void 0:i[l];if(d===null)return null;const h=Aa(d)||Aa(u);return n[l][h]}),a=t&&Object.entries(t).reduce((l,d)=>{let[u,h]=d;return h===void 0||(l[u]=h),l},{}),c=e==null||(s=e.compoundVariants)===null||s===void 0?void 0:s.reduce((l,d)=>{let{class:u,className:h,...g}=d;return Object.entries(g).every(m=>{let[p,x]=m;return Array.isArray(x)?x.includes({...i,...a}[p]):{...i,...a}[p]===x})?[...l,u,h]:l},[]);return Ia(r,o,c,t==null?void 0:t.class,t==null?void 0:t.className)},jr=ft("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline",brand:"bg-gradient-to-r from-violet-600 to-indigo-600 text-white hover:from-violet-500 hover:to-indigo-500 shadow-lg shadow-violet-500/25 hover:shadow-violet-500/40 hover:scale-[1.02] active:scale-[0.98]",glow:"bg-primary text-primary-foreground shadow-[0_0_20px_rgba(139,92,246,0.5)] hover:shadow-[0_0_30px_rgba(139,92,246,0.7)] hover:scale-[1.02] active:scale-[0.98]"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",xl:"h-12 rounded-lg px-10 text-base",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),Ze=E.forwardRef(({className:r,variant:e,size:t,asChild:s=!1,...n},i)=>{const o=s?lc.Slot:"button";return f.jsx(o,{className:I(jr({variant:e,size:t,className:r})),ref:i,...n})});Ze.displayName="Button";const Ac=ft("flex w-full rounded-lg text-sm transition-all duration-200 file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",{variants:{variant:{default:"h-10 border border-input bg-background px-3 py-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",filled:"h-10 border-0 bg-muted/50 px-3 py-2 focus-visible:outline-none focus-visible:bg-muted focus-visible:ring-2 focus-visible:ring-ring",glow:"h-10 border border-input bg-background px-3 py-2 ring-offset-background focus-visible:outline-none focus-visible:border-violet-500/50 focus-visible:ring-2 focus-visible:ring-violet-500/30 focus-visible:shadow-[0_0_15px_rgba(139,92,246,0.3)]",ghost:"h-10 border-0 bg-transparent px-3 py-2 focus-visible:outline-none focus-visible:bg-muted/30"},inputSize:{default:"h-10",sm:"h-9 text-xs",lg:"h-12 text-base"}},defaultVariants:{variant:"default",inputSize:"default"}}),ws=E.forwardRef(({className:r,type:e,variant:t,inputSize:s,...n},i)=>f.jsx("input",{type:e,className:I(Ac({variant:t,inputSize:s}),r),ref:i,...n}));ws.displayName="Input";const Ic=E.forwardRef(({className:r,...e},t)=>f.jsx("textarea",{className:I("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",r),ref:t,...e}));Ic.displayName="Textarea";const Om=ft("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),On=E.forwardRef(({className:r,...e},t)=>f.jsx(cc.Root,{ref:t,className:I(Om(),r),...e}));On.displayName=cc.Root.displayName;const Lc=ft("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function ho({className:r,variant:e,...t}){return f.jsx("div",{className:I(Lc({variant:e}),r),...t})}const Cc=E.forwardRef(({className:r,orientation:e="horizontal",...t},s)=>f.jsx(dc.Root,{ref:s,decorative:!0,orientation:e,className:I("shrink-0 bg-border",e==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",r),...t}));Cc.displayName=dc.Root.displayName;const _c=E.forwardRef(({className:r,...e},t)=>f.jsx(nr.Root,{ref:t,className:I("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",r),...e}));_c.displayName=nr.Root.displayName;const kc=E.forwardRef(({className:r,...e},t)=>f.jsx(nr.Image,{ref:t,className:I("aspect-square h-full w-full",r),...e}));kc.displayName=nr.Image.displayName;const Dc=E.forwardRef(({className:r,...e},t)=>f.jsx(nr.Fallback,{ref:t,className:I("flex h-full w-full items-center justify-center rounded-full bg-muted",r),...e}));Dc.displayName=nr.Fallback.displayName;const Pc=E.forwardRef(({className:r,...e},t)=>f.jsx(_i.Root,{ref:t,className:I("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",r),...e,children:f.jsx(_i.Indicator,{className:I("flex items-center justify-center text-current"),children:f.jsx(W.Check,{className:"h-4 w-4"})})}));Pc.displayName=_i.Root.displayName;const Nc=E.forwardRef(({className:r,...e},t)=>f.jsx(ki.Root,{className:I("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",r),...e,ref:t,children:f.jsx(ki.Thumb,{className:I("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));Nc.displayName=ki.Root.displayName;const jm=We.Root,Bm=We.Group,$m=We.Value,Mc=E.forwardRef(({className:r,children:e,...t},s)=>f.jsxs(We.Trigger,{ref:s,className:I("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",r),...t,children:[e,f.jsx(We.Icon,{asChild:!0,children:f.jsx(W.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));Mc.displayName=We.Trigger.displayName;const go=E.forwardRef(({className:r,...e},t)=>f.jsx(We.ScrollUpButton,{ref:t,className:I("flex cursor-default items-center justify-center py-1",r),...e,children:f.jsx(W.ChevronUp,{className:"h-4 w-4"})}));go.displayName=We.ScrollUpButton.displayName;const mo=E.forwardRef(({className:r,...e},t)=>f.jsx(We.ScrollDownButton,{ref:t,className:I("flex cursor-default items-center justify-center py-1",r),...e,children:f.jsx(W.ChevronDown,{className:"h-4 w-4"})}));mo.displayName=We.ScrollDownButton.displayName;const Fc=E.forwardRef(({className:r,children:e,position:t="popper",...s},n)=>f.jsx(We.Portal,{children:f.jsxs(We.Content,{ref:n,className:I("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",r),position:t,...s,children:[f.jsx(go,{}),f.jsx(We.Viewport,{className:I("p-1",t==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:e}),f.jsx(mo,{})]})}));Fc.displayName=We.Content.displayName;const Oc=E.forwardRef(({className:r,...e},t)=>f.jsx(We.Label,{ref:t,className:I("py-1.5 pl-8 pr-2 text-sm font-semibold",r),...e}));Oc.displayName=We.Label.displayName;const jc=E.forwardRef(({className:r,children:e,...t},s)=>f.jsxs(We.Item,{ref:s,className:I("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",r),...t,children:[f.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:f.jsx(We.ItemIndicator,{children:f.jsx(W.Check,{className:"h-4 w-4"})})}),f.jsx(We.ItemText,{children:e})]}));jc.displayName=We.Item.displayName;const Bc=E.forwardRef(({className:r,...e},t)=>f.jsx(We.Separator,{ref:t,className:I("-mx-1 my-1 h-px bg-muted",r),...e}));Bc.displayName=We.Separator.displayName;const $c=E.forwardRef(({className:r,...e},t)=>f.jsx(wr.Root,{className:I("grid gap-2",r),...e,ref:t}));$c.displayName=wr.Root.displayName;const Uc=E.forwardRef(({className:r,...e},t)=>f.jsx(wr.Item,{ref:t,className:I("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",r),...e,children:f.jsx(wr.Indicator,{className:"flex items-center justify-center",children:f.jsx(W.Circle,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Uc.displayName=wr.Item.displayName;const Gc=E.forwardRef(({className:r,...e},t)=>f.jsxs(gr.Root,{ref:t,className:I("relative flex w-full touch-none select-none items-center",r),...e,children:[f.jsx(gr.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:f.jsx(gr.Range,{className:"absolute h-full bg-primary"})}),f.jsx(gr.Thumb,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));Gc.displayName=gr.Root.displayName;const po=ft("inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground"},size:{default:"h-10 px-3",sm:"h-9 px-2.5",lg:"h-11 px-5"}},defaultVariants:{variant:"default",size:"default"}}),Vc=E.forwardRef(({className:r,variant:e,size:t,...s},n)=>f.jsx(uc.Root,{ref:n,className:I(po({variant:e,size:t,className:r})),...s}));Vc.displayName=uc.Root.displayName;const Hc=E.forwardRef(({className:r,variant:e,size:t,children:s,...n},i)=>f.jsx(Mn.Root,{ref:i,className:I("flex items-center justify-center gap-1",r),...n,children:f.jsx(Kc.Provider,{value:{variant:e,size:t},children:s})}));Hc.displayName=Mn.Root.displayName;const Kc=E.createContext({size:"default",variant:"default"}),zc=E.forwardRef(({className:r,children:e,variant:t,size:s,...n},i)=>{const o=E.useContext(Kc);return f.jsx(Mn.Item,{ref:i,className:I(po({variant:o.variant||t,size:o.size||s}),r),...n,children:e})});zc.displayName=Mn.Item.displayName;function xo({selected:r,onSelect:e,className:t,disabled:s}){const[n,i]=E.useState(()=>r?ot.startOfMonth(r):ot.startOfMonth(new Date)),o=ot.startOfMonth(n),a=ot.endOfMonth(n),c=ot.startOfWeek(o,{weekStartsOn:1}),l=ot.endOfWeek(a,{weekStartsOn:1}),d=ot.eachDayOfInterval({start:c,end:l}),u=["Mo","Tu","We","Th","Fr","Sa","Su"],h=()=>{i(ot.subMonths(n,1))},g=()=>{i(ot.addMonths(n,1))},m=p=>{s!=null&&s(p)||e==null||e(ot.isSameDay(p,r||new Date(0))?void 0:p)};return f.jsxs("div",{className:I("p-4 bg-card rounded-xl border shadow-sm w-[320px]",t),children:[f.jsxs("div",{className:"flex items-center justify-between mb-4",children:[f.jsx(Ze,{variant:"ghost",size:"icon",onClick:h,className:"h-8 w-8 rounded-full hover:bg-accent",children:f.jsx(W.ChevronLeft,{className:"h-4 w-4"})}),f.jsx("h2",{className:"text-base font-semibold",children:ot.format(n,"MMMM yyyy")}),f.jsx(Ze,{variant:"ghost",size:"icon",onClick:g,className:"h-8 w-8 rounded-full hover:bg-accent",children:f.jsx(W.ChevronRight,{className:"h-4 w-4"})})]}),f.jsx("div",{className:"grid grid-cols-7 gap-1 mb-2",children:u.map(p=>f.jsx("div",{className:"h-8 flex items-center justify-center text-xs font-medium text-muted-foreground",children:p},p))}),f.jsx("div",{className:"grid grid-cols-7 gap-1",children:d.map((p,x)=>{const v=ot.isSameMonth(p,n),y=r&&ot.isSameDay(p,r),b=ot.isToday(p),T=s==null?void 0:s(p);return f.jsx("button",{onClick:()=>m(p),disabled:T,className:I("h-10 w-10 rounded-lg text-sm font-medium transition-all duration-150","flex items-center justify-center","hover:bg-accent focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1",!v&&"text-muted-foreground/40",v&&!y&&"text-foreground hover:text-foreground",y&&"bg-primary text-primary-foreground hover:bg-primary/90 shadow-md",b&&!y&&"bg-accent text-accent-foreground font-bold",T&&"opacity-30 cursor-not-allowed hover:bg-transparent"),children:ot.format(p,"d")},x)})}),f.jsxs("div",{className:"mt-4 pt-3 border-t flex justify-between items-center",children:[f.jsx(Ze,{variant:"ghost",size:"sm",onClick:()=>{const p=new Date;i(ot.startOfMonth(p)),e==null||e(p)},className:"text-xs",children:"Today"}),r&&f.jsx("span",{className:"text-xs text-muted-foreground",children:ot.format(r,"MMM d, yyyy")})]})]})}xo.displayName="Calendar";const ar=Rr.Root,lr=Rr.Trigger,Bs=E.forwardRef(({className:r,align:e="center",sideOffset:t=4,...s},n)=>f.jsx(Rr.Portal,{children:f.jsx(Rr.Content,{ref:n,align:e,sideOffset:t,className:I("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",r),...s})}));Bs.displayName=Rr.Content.displayName;const Ar={chatInput_placeholder:"Type a message...",chatInput_attachFile:"Attach file",chatInput_stopGenerating:"Stop generating",chatInput_sendMessage:"Send message",conversationList_newChat:"New Chat",conversationList_searchPlaceholder:"Search conversations...",conversationList_noResults:"No conversations found",conversationList_empty:"No conversations yet",conversationList_today:"Today",conversationList_yesterday:"Yesterday",conversationList_previous7Days:"Previous 7 days",conversationList_older:"Older",conversationList_rename:"Rename",conversationList_delete:"Delete",chatHeader_online:"Online",chatHeader_offline:"Offline",chatHeader_typing:"Typing...",chatHeader_back:"Back",chatHeader_clearConversation:"Clear conversation",chatHeader_settings:"Settings",reasoning_title:"Reasoning",reasoning_thinking:"Thinking",reasoning_thoughtFor:"Thought for {duration}",toolCall_calling:"Calling {name}...",toolCall_failed:"{name} — failed",toolCall_arguments:"Arguments",toolCall_result:"Result",toolCall_error:"Error",messageActions_copy:"Copy",messageActions_retry:"Retry",messageActions_edit:"Edit",messageActions_like:"Like",messageActions_dislike:"Dislike",messageActions_share:"Share",messageActions_copied:"Copied!",followUp_freeTextPlaceholder:"Or type your answer...",followUp_send:"Send",sourceCitation_sources:"Sources",aiLoading_thinking:"Thinking",filePreview_remove:"Remove {name}",modelSelector_placeholder:"Select model",modelSelector_searchPlaceholder:"Search models...",modelSelector_noResults:"No models found",common_close:"Close",common_search:"Search",common_noResults:"No results found.",common_previous:"Previous",common_next:"Next",common_more:"More",common_copyCode:"Copy code",combobox_placeholder:"Select option...",combobox_searchPlaceholder:"Search...",combobox_empty:"No results found.",multiselect_placeholder:"Select options...",multiselect_searchPlaceholder:"Search...",multiselect_empty:"No results found.",multiselect_selected:"{count} selected",datePicker_placeholder:"Pick a date",dataTable_searchPlaceholder:"Search...",dataTable_noResults:"No results.",dataTable_pageOf:"Page {page} of {total}",dataTable_previous:"Previous",dataTable_next:"Next",fileUpload_dragDrop:"Drag & drop files here, or click to select",fileUpload_maxSize:"Max file size: {size}",tagInput_placeholder:"Add tag...",pagination_previous:"Previous",pagination_next:"Next",pagination_morePages:"More pages",pagination_goToPrevious:"Go to previous page",pagination_goToNext:"Go to next page",modeToggle_toggleTheme:"Toggle theme",modeToggle_light:"Light",modeToggle_dark:"Dark",modeToggle_system:"System",modeToggle_colorTheme:"Color theme",carousel_previousSlide:"Previous slide",carousel_nextSlide:"Next slide",breadcrumb_more:"More",audioPlayer_play:"Play",audioPlayer_pause:"Pause",audioPlayer_mute:"Mute",audioPlayer_unmute:"Unmute",audioPlayer_seek:"Seek",audioPlayer_volume:"Volume",audioPlayer_error:"Audio failed to load",audioPlayer_loading:"Loading...",audioRecorder_startRecording:"Start recording",audioRecorder_stopRecording:"Stop recording",audioRecorder_pauseRecording:"Pause recording",audioRecorder_resumeRecording:"Resume recording",audioRecorder_reRecord:"Re-record",audioRecorder_microphoneAccess:"Microphone access required",audioRecorder_error:"Recording failed",audioRecorder_permissionDenied:"Microphone access denied",audioWaveform_label:"Audio waveform",audioWaveform_error:"Failed to load audio waveform",audioPlaylist_shuffle:"Shuffle",audioPlaylist_repeatOff:"Repeat off",audioPlaylist_repeatAll:"Repeat all",audioPlaylist_repeatOne:"Repeat one",audioPlaylist_previousTrack:"Previous track",audioPlaylist_nextTrack:"Next track",audioPlaylist_trackOf:"Track {current} of {total}",audioPlaylist_empty:"No tracks in playlist",videoPlayer_play:"Play",videoPlayer_pause:"Pause",videoPlayer_mute:"Mute",videoPlayer_unmute:"Unmute",videoPlayer_seek:"Seek",videoPlayer_volume:"Volume",videoPlayer_fullscreen:"Fullscreen",videoPlayer_exitFullscreen:"Exit fullscreen",videoPlayer_pictureInPicture:"Picture in picture",videoPlayer_playbackSpeed:"Playback speed",videoPlayer_subtitles:"Subtitles",videoPlayer_subtitlesOff:"Off",videoPlayer_label:"Video player",videoPlayer_loading:"Loading...",videoPlayer_error:"Video failed to load",videoPlayer_chapter:"Chapter",videoPlayer_skipForward:"Skip forward",videoPlayer_skipBackward:"Skip backward",videoPlayer_live:"LIVE",videoRecorder_startCamera:"Start camera",videoRecorder_shareScreen:"Share screen",videoRecorder_startRecording:"Start recording",videoRecorder_stopRecording:"Stop recording",videoRecorder_pauseRecording:"Pause recording",videoRecorder_resumeRecording:"Resume recording",videoRecorder_reRecord:"Re-record",videoRecorder_cameraPreview:"Camera preview",videoRecorder_screenPreview:"Screen preview",videoRecorder_error:"Recording failed",videoRecorder_permissionDenied:"Camera access denied",videoThumbnail_play:"Play video: {title}",videoGallery_label:"Video gallery",image_loading:"Loading image",image_zoomIn:"Zoom in",image_failedToLoad:"Image failed to load",lightbox_label:"Image viewer",lightbox_zoomIn:"Zoom in",lightbox_zoomOut:"Zoom out",lightbox_imageOf:"{current} of {total}",lightbox_download:"Download",imageCropper_label:"Image crop area",imageCropper_crop:"Crop",imageCropper_reset:"Reset",imageCropper_cropFailed:"Failed to create cropped image",imageCompare_slider:"Image comparison slider",imageCompare_before:"Before",imageCompare_after:"After"},Wc={chatInput_placeholder:"Введите сообщение...",chatInput_attachFile:"Прикрепить файл",chatInput_stopGenerating:"Остановить генерацию",chatInput_sendMessage:"Отправить сообщение",conversationList_newChat:"Новый чат",conversationList_searchPlaceholder:"Поиск диалогов...",conversationList_noResults:"Диалоги не найдены",conversationList_empty:"Нет диалогов",conversationList_today:"Сегодня",conversationList_yesterday:"Вчера",conversationList_previous7Days:"Последние 7 дней",conversationList_older:"Ранее",conversationList_rename:"Переименовать",conversationList_delete:"Удалить",chatHeader_online:"Онлайн",chatHeader_offline:"Не в сети",chatHeader_typing:"Печатает...",chatHeader_back:"Назад",chatHeader_clearConversation:"Очистить диалог",chatHeader_settings:"Настройки",reasoning_title:"Рассуждение",reasoning_thinking:"Думаю",reasoning_thoughtFor:"Думал {duration}",toolCall_calling:"Вызываю {name}...",toolCall_failed:"{name} — ошибка",toolCall_arguments:"Аргументы",toolCall_result:"Результат",toolCall_error:"Ошибка",messageActions_copy:"Копировать",messageActions_retry:"Повторить",messageActions_edit:"Редактировать",messageActions_like:"Нравится",messageActions_dislike:"Не нравится",messageActions_share:"Поделиться",messageActions_copied:"Скопировано!",followUp_freeTextPlaceholder:"Или введите свой ответ...",followUp_send:"Отправить",sourceCitation_sources:"Источники",aiLoading_thinking:"Думаю",filePreview_remove:"Удалить {name}",modelSelector_placeholder:"Выберите модель",modelSelector_searchPlaceholder:"Поиск моделей...",modelSelector_noResults:"Модели не найдены",common_close:"Закрыть",common_search:"Поиск",common_noResults:"Ничего не найдено.",common_previous:"Назад",common_next:"Далее",common_more:"Ещё",common_copyCode:"Копировать код",combobox_placeholder:"Выберите...",combobox_searchPlaceholder:"Поиск...",combobox_empty:"Ничего не найдено.",multiselect_placeholder:"Выберите...",multiselect_searchPlaceholder:"Поиск...",multiselect_empty:"Ничего не найдено.",multiselect_selected:"{count} выбрано",datePicker_placeholder:"Выберите дату",dataTable_searchPlaceholder:"Поиск...",dataTable_noResults:"Нет результатов.",dataTable_pageOf:"Страница {page} из {total}",dataTable_previous:"Назад",dataTable_next:"Далее",fileUpload_dragDrop:"Перетащите файлы сюда или нажмите для выбора",fileUpload_maxSize:"Макс. размер файла: {size}",tagInput_placeholder:"Добавить тег...",pagination_previous:"Назад",pagination_next:"Далее",pagination_morePages:"Ещё страницы",pagination_goToPrevious:"Предыдущая страница",pagination_goToNext:"Следующая страница",modeToggle_toggleTheme:"Сменить тему",modeToggle_light:"Светлая",modeToggle_dark:"Тёмная",modeToggle_system:"Системная",modeToggle_colorTheme:"Цветовая тема",carousel_previousSlide:"Предыдущий слайд",carousel_nextSlide:"Следующий слайд",breadcrumb_more:"Ещё",audioPlayer_play:"Воспроизвести",audioPlayer_pause:"Пауза",audioPlayer_mute:"Выключить звук",audioPlayer_unmute:"Включить звук",audioPlayer_seek:"Перемотка",audioPlayer_volume:"Громкость",audioPlayer_error:"Не удалось загрузить аудио",audioPlayer_loading:"Загрузка...",audioRecorder_startRecording:"Начать запись",audioRecorder_stopRecording:"Остановить запись",audioRecorder_pauseRecording:"Приостановить запись",audioRecorder_resumeRecording:"Продолжить запись",audioRecorder_reRecord:"Перезаписать",audioRecorder_microphoneAccess:"Требуется доступ к микрофону",audioRecorder_error:"Ошибка записи",audioRecorder_permissionDenied:"Нет доступа к микрофону",audioWaveform_label:"Звуковая волна",audioWaveform_error:"Не удалось загрузить звуковую волну",audioPlaylist_shuffle:"Перемешать",audioPlaylist_repeatOff:"Повтор выключен",audioPlaylist_repeatAll:"Повторять все",audioPlaylist_repeatOne:"Повторять одну",audioPlaylist_previousTrack:"Предыдущий трек",audioPlaylist_nextTrack:"Следующий трек",audioPlaylist_trackOf:"Трек {current} из {total}",audioPlaylist_empty:"Нет треков в плейлисте",videoPlayer_play:"Воспроизвести",videoPlayer_pause:"Пауза",videoPlayer_mute:"Выключить звук",videoPlayer_unmute:"Включить звук",videoPlayer_seek:"Перемотка",videoPlayer_volume:"Громкость",videoPlayer_fullscreen:"Полный экран",videoPlayer_exitFullscreen:"Выйти из полного экрана",videoPlayer_pictureInPicture:"Картинка в картинке",videoPlayer_playbackSpeed:"Скорость воспроизведения",videoPlayer_subtitles:"Субтитры",videoPlayer_subtitlesOff:"Выключены",videoPlayer_label:"Видеоплеер",videoPlayer_loading:"Загрузка...",videoPlayer_error:"Не удалось загрузить видео",videoPlayer_chapter:"Глава",videoPlayer_skipForward:"Вперёд",videoPlayer_skipBackward:"Назад",videoPlayer_live:"LIVE",videoRecorder_startCamera:"Включить камеру",videoRecorder_shareScreen:"Поделиться экраном",videoRecorder_startRecording:"Начать запись",videoRecorder_stopRecording:"Остановить запись",videoRecorder_pauseRecording:"Приостановить запись",videoRecorder_resumeRecording:"Продолжить запись",videoRecorder_reRecord:"Перезаписать",videoRecorder_cameraPreview:"Предпросмотр камеры",videoRecorder_screenPreview:"Предпросмотр экрана",videoRecorder_error:"Ошибка записи",videoRecorder_permissionDenied:"Нет доступа к камере",videoThumbnail_play:"Воспроизвести видео: {title}",videoGallery_label:"Галерея видео",image_loading:"Загрузка изображения",image_zoomIn:"Увеличить",image_failedToLoad:"Не удалось загрузить изображение",lightbox_label:"Просмотр изображений",lightbox_zoomIn:"Увеличить",lightbox_zoomOut:"Уменьшить",lightbox_imageOf:"{current} из {total}",lightbox_download:"Скачать",imageCropper_label:"Область обрезки",imageCropper_crop:"Обрезать",imageCropper_reset:"Сбросить",imageCropper_cropFailed:"Не удалось создать обрезанное изображение",imageCompare_slider:"Сравнение изображений",imageCompare_before:"До",imageCompare_after:"После"};function La(r,e){if(!r)return;const t=e.split(".");let s=r;for(const n of t){if(s===void 0||typeof s=="string")return;s=s[n]}return typeof s=="string"?s:void 0}function un(r,e){if(!e)return r;let t=r;for(const[s,n]of Object.entries(e))t=t.replaceAll(`{${s}}`,String(n));return t}const Um={en:Ar,ru:Wc},Yc=E.createContext(Ar),qc=E.createContext({lang:"en",messages:{}});function Xc({locale:r="en",messages:e,children:t}){const s=typeof r=="string"?r:"en",n=E.useMemo(()=>typeof r=="string"?Um[r]??Ar:{...Ar,...r},[r]),i=E.useMemo(()=>({lang:s,messages:e??{}}),[s,e]);return f.jsx(qc.Provider,{value:i,children:f.jsx(Yc.Provider,{value:n,children:t})})}function ye(){return E.useContext(Yc)}function Gm(){const{lang:r,messages:e}=E.useContext(qc);return{t:E.useCallback((s,n)=>{const i=La(e[r],s);if(i!==void 0)return un(i,n);if(r!=="en"){const o=La(e.en,s);if(o!==void 0)return un(o,n)}return un(s,n)},[r,e]),lang:r}}function bt(r,e){return un(r,e)}function Vm({value:r,onChange:e,placeholder:t,disabled:s,className:n}){const i=ye(),o=t??i.datePicker_placeholder,[a,c]=E.useState(!1);return f.jsxs(ar,{open:a,onOpenChange:c,children:[f.jsx(lr,{asChild:!0,children:f.jsxs(Ze,{variant:"outline",disabled:s,className:I("w-full justify-start text-left font-normal",!r&&"text-muted-foreground",n),children:[f.jsx(W.CalendarIcon,{className:"mr-2 h-4 w-4"}),r?ot.format(r,"PPP"):f.jsx("span",{children:o})]})}),f.jsx(Bs,{className:"w-auto p-0",align:"start",children:f.jsx(xo,{selected:r,onSelect:l=>{e==null||e(l),c(!1)}})})]})}function Hm({value:r={hours:12,minutes:0},onChange:e,is24Hour:t=!1,disabled:s,className:n}){const[i,o]=E.useState(!1),[a,c]=E.useState(r.hours>=12?"PM":"AM"),l=t?r.hours:r.hours===0?12:r.hours>12?r.hours-12:r.hours,d=()=>{const x=l.toString().padStart(2,"0"),v=r.minutes.toString().padStart(2,"0");return t?`${x}:${v}`:`${x}:${v} ${a}`},u=x=>{let v=x;t||(a==="PM"&&x!==12&&(v+=12),a==="AM"&&x===12&&(v=0)),e==null||e({...r,hours:v})},h=x=>{e==null||e({...r,minutes:x})},g=x=>{c(x);let v=r.hours;x==="PM"&&r.hours<12&&(v+=12),x==="AM"&&r.hours>=12&&(v-=12),e==null||e({...r,hours:v})},m=t?Array.from({length:24},(x,v)=>v):Array.from({length:12},(x,v)=>v+1),p=Array.from({length:12},(x,v)=>v*5);return f.jsxs(ar,{open:i,onOpenChange:o,children:[f.jsx(lr,{asChild:!0,children:f.jsxs(Ze,{variant:"outline",disabled:s,className:I("w-full justify-start font-normal",n),children:[f.jsx(W.Clock,{className:"mr-2 h-4 w-4"}),d()]})}),f.jsx(Bs,{className:"w-auto p-2",align:"start",children:f.jsxs("div",{className:"flex gap-1",children:[f.jsx("div",{className:"h-32 w-12 overflow-y-auto rounded border bg-muted/30",children:m.map(x=>f.jsx("button",{onClick:()=>u(x),className:I("w-full py-1 text-sm font-medium transition-colors","hover:bg-accent",l===x&&"bg-primary text-primary-foreground hover:bg-primary/90"),children:x.toString().padStart(2,"0")},x))}),f.jsx("div",{className:"flex items-center text-muted-foreground font-bold",children:":"}),f.jsx("div",{className:"h-32 w-12 overflow-y-auto rounded border bg-muted/30",children:p.map(x=>f.jsx("button",{onClick:()=>h(x),className:I("w-full py-1 text-sm font-medium transition-colors","hover:bg-accent",r.minutes===x&&"bg-primary text-primary-foreground hover:bg-primary/90"),children:x.toString().padStart(2,"0")},x))}),!t&&f.jsxs("div",{className:"flex flex-col gap-1",children:[f.jsx("button",{onClick:()=>g("AM"),className:I("px-2 py-1 text-xs font-medium rounded border transition-colors flex-1","hover:bg-accent",a==="AM"&&"bg-primary text-primary-foreground border-primary"),children:"AM"}),f.jsx("button",{onClick:()=>g("PM"),className:I("px-2 py-1 text-xs font-medium rounded border transition-colors flex-1","hover:bg-accent",a==="PM"&&"bg-primary text-primary-foreground border-primary"),children:"PM"})]})]})})]})}function Km({value:r=0,onChange:e,min:t=-1/0,max:s=1/0,step:n=1,disabled:i,className:o}){const a=()=>{const d=Math.min(r+n,s);e==null||e(d)},c=()=>{const d=Math.max(r-n,t);e==null||e(d)},l=d=>{const u=parseFloat(d.target.value);if(!isNaN(u)){const h=Math.min(Math.max(u,t),s);e==null||e(h)}};return f.jsxs("div",{className:I("flex items-center gap-2",o),children:[f.jsx(Ze,{type:"button",variant:"outline",size:"icon",onClick:c,disabled:i||r<=t,className:"h-9 w-9",children:f.jsx(W.Minus,{className:"h-4 w-4"})}),f.jsx(ws,{type:"number",value:r,onChange:l,disabled:i,className:"w-20 text-center [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",min:t,max:s,step:n}),f.jsx(Ze,{type:"button",variant:"outline",size:"icon",onClick:a,disabled:i||r>=s,className:"h-9 w-9",children:f.jsx(W.Plus,{className:"h-4 w-4"})})]})}function zm({values:r=[],onChange:e,placeholder:t,disabled:s,className:n,maxTags:i}){const o=ye(),a=t??o.tagInput_placeholder,[c,l]=E.useState(""),d=E.useRef(null),u=g=>{if(g.key==="Enter"&&c.trim()){if(g.preventDefault(),i&&r.length>=i)return;r.includes(c.trim())||e==null||e([...r,c.trim()]),l("")}else g.key==="Backspace"&&!c&&r.length>0&&(e==null||e(r.slice(0,-1)))},h=g=>{e==null||e(r.filter(m=>m!==g))};return f.jsxs("div",{className:I("flex flex-wrap gap-2 rounded-md border border-input bg-background px-3 py-2 focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2",s&&"opacity-50 cursor-not-allowed",n),onClick:()=>{var g;return(g=d.current)==null?void 0:g.focus()},children:[r.map(g=>f.jsxs(ho,{variant:"secondary",className:"gap-1",children:[g,!s&&f.jsx("button",{type:"button",onClick:m=>{m.stopPropagation(),h(g)},className:"ml-1 rounded-full outline-none hover:bg-muted",children:f.jsx(W.X,{className:"h-3 w-3"})})]},g)),f.jsx("input",{ref:d,type:"text",value:c,onChange:g=>l(g.target.value),onKeyDown:u,placeholder:r.length===0?a:"",disabled:s||(i?r.length>=i:!1),className:"flex-1 min-w-[120px] bg-transparent outline-none placeholder:text-muted-foreground text-sm"})]})}function Wm({options:r,value:e,onChange:t,placeholder:s,searchPlaceholder:n,emptyText:i,disabled:o,className:a}){const c=ye(),l=s??c.combobox_placeholder,d=n??c.combobox_searchPlaceholder,u=i??c.combobox_empty,[h,g]=E.useState(!1),[m,p]=E.useState(""),x=r.filter(y=>y.label.toLowerCase().includes(m.toLowerCase())),v=r.find(y=>y.value===e);return f.jsxs(ar,{open:h,onOpenChange:g,children:[f.jsx(lr,{asChild:!0,children:f.jsxs(Ze,{variant:"outline",role:"combobox","aria-expanded":h,disabled:o,className:I("w-full justify-between font-normal",!e&&"text-muted-foreground",a),children:[v?v.label:l,f.jsx(W.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),f.jsxs(Bs,{className:"w-full p-0",align:"start",children:[f.jsx("div",{className:"p-2 border-b",children:f.jsx(ws,{placeholder:d,value:m,onChange:y=>p(y.target.value),className:"h-8"})}),f.jsx("div",{className:"max-h-60 overflow-auto p-1",children:x.length===0?f.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:u}):x.map(y=>f.jsxs("button",{onClick:()=>{t==null||t(y.value===e?"":y.value),g(!1),p("")},className:I("relative flex w-full cursor-pointer select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none hover:bg-accent hover:text-accent-foreground",e===y.value&&"bg-accent"),children:[f.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e===y.value&&f.jsx(W.Check,{className:"h-4 w-4"})}),y.label]},y.value))})]})]})}function Ym({options:r,value:e=[],onChange:t,placeholder:s,searchPlaceholder:n,emptyText:i,disabled:o,className:a,maxDisplay:c=3}){const l=ye(),d=s??l.multiselect_placeholder,u=n??l.multiselect_searchPlaceholder,h=i??l.multiselect_empty,[g,m]=E.useState(!1),[p,x]=E.useState(""),v=r.filter(_=>_.label.toLowerCase().includes(p.toLowerCase())),y=r.filter(_=>e.includes(_.value)),b=_=>{const w=e.includes(_)?e.filter(A=>A!==_):[...e,_];t==null||t(w)},T=(_,w)=>{w.stopPropagation(),t==null||t(e.filter(A=>A!==_))},R=()=>e.length===0?d:e.length<=c?y.map(_=>_.label).join(", "):bt(l.multiselect_selected,{count:e.length});return f.jsxs(ar,{open:g,onOpenChange:m,children:[f.jsx(lr,{asChild:!0,children:f.jsxs(Ze,{variant:"outline",role:"combobox","aria-expanded":g,disabled:o,className:I("w-full justify-between font-normal",e.length===0&&"text-muted-foreground",a),children:[f.jsx("span",{className:"truncate",children:R()}),f.jsx(W.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),f.jsxs(Bs,{className:"w-full p-0",align:"start",children:[f.jsx("div",{className:"p-2 border-b",children:f.jsx(ws,{placeholder:u,value:p,onChange:_=>x(_.target.value),className:"h-8"})}),e.length>0&&f.jsx("div",{className:"flex flex-wrap gap-1 p-2 border-b",children:y.map(_=>f.jsxs(ho,{variant:"secondary",className:"pr-1",children:[_.label,f.jsx("button",{onClick:w=>T(_.value,w),className:"ml-1 rounded-full hover:bg-muted",children:f.jsx(W.X,{className:"h-3 w-3"})})]},_.value))}),f.jsx("div",{className:"max-h-60 overflow-auto p-1",children:v.length===0?f.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:h}):v.map(_=>{const w=e.includes(_.value);return f.jsxs("button",{onClick:()=>b(_.value),className:I("relative flex w-full cursor-pointer select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none hover:bg-accent hover:text-accent-foreground",w&&"bg-accent"),children:[f.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:w&&f.jsx(W.Check,{className:"h-4 w-4"})}),_.label]},_.value)})})]})]})}function qm({length:r=6,value:e="",onChange:t,onComplete:s,disabled:n,className:i}){const o=E.useRef([]),a=(d,u)=>{var m;if(!/^\d*$/.test(u))return;const h=e.split("");h[d]=u;const g=h.join("").slice(0,r);t==null||t(g),u&&d<r-1&&((m=o.current[d+1])==null||m.focus()),g.length===r&&(s==null||s(g))},c=(d,u)=>{var h;u.key==="Backspace"&&!e[d]&&d>0&&((h=o.current[d-1])==null||h.focus())},l=d=>{var h;d.preventDefault();const u=d.clipboardData.getData("text").replace(/\D/g,"").slice(0,r);t==null||t(u),u.length===r&&(s==null||s(u)),(h=o.current[Math.min(u.length,r-1)])==null||h.focus()};return f.jsx("div",{className:I("flex gap-2",i),children:Array.from({length:r}).map((d,u)=>f.jsx("input",{ref:h=>{o.current[u]=h},type:"text",inputMode:"numeric",maxLength:1,value:e[u]||"",onChange:h=>a(u,h.target.value),onKeyDown:h=>c(u,h),onPaste:l,disabled:n,className:I("h-12 w-12 rounded-lg border border-input bg-background text-center text-lg font-semibold","focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2","disabled:opacity-50 disabled:cursor-not-allowed")},u))})}function Xm({accept:r,maxSize:e,multiple:t=!1,onUpload:s,disabled:n,className:i}){const[o,a]=E.useState([]),[c,l]=E.useState(!1),d=E.useRef(null),u=ye(),h=y=>{if(!y)return;const b=Array.from(y).filter(R=>!(e&&R.size>e)),T=t?[...o,...b]:b.slice(0,1);a(T),s==null||s(T)},g=y=>{y.preventDefault(),l(!1),n||h(y.dataTransfer.files)},m=y=>{y.preventDefault(),n||l(!0)},p=()=>{l(!1)},x=y=>{const b=o.filter((T,R)=>R!==y);a(b),s==null||s(b)},v=y=>y<1024?y+" B":y<1024*1024?(y/1024).toFixed(1)+" KB":(y/(1024*1024)).toFixed(1)+" MB";return f.jsxs("div",{className:I("space-y-4",i),children:[f.jsxs("div",{onClick:()=>{var y;return!n&&((y=d.current)==null?void 0:y.click())},onDrop:g,onDragOver:m,onDragLeave:p,className:I("border-2 border-dashed rounded-lg p-8 text-center transition-colors cursor-pointer",c?"border-primary bg-primary/5":"border-muted-foreground/25",n&&"opacity-50 cursor-not-allowed","hover:border-primary/50"),children:[f.jsx(W.Upload,{className:"h-10 w-10 mx-auto mb-4 text-muted-foreground"}),f.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:u.fileUpload_dragDrop}),e&&f.jsx("p",{className:"text-xs text-muted-foreground",children:bt(u.fileUpload_maxSize,{size:v(e)})}),f.jsx("input",{ref:d,type:"file",accept:r,multiple:t,onChange:y=>h(y.target.files),disabled:n,className:"hidden"})]}),o.length>0&&f.jsx("div",{className:"space-y-2",children:o.map((y,b)=>f.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-muted/50",children:[f.jsx(W.FileIcon,{className:"h-8 w-8 text-muted-foreground"}),f.jsxs("div",{className:"flex-1 min-w-0",children:[f.jsx("p",{className:"text-sm font-medium truncate",children:y.name}),f.jsx("p",{className:"text-xs text-muted-foreground",children:v(y.size)})]}),f.jsx(Ze,{type:"button",variant:"ghost",size:"icon",onClick:()=>x(b),className:"h-8 w-8",children:f.jsx(W.X,{className:"h-4 w-4"})})]},b))})]})}const Qm=["#ef4444","#f97316","#eab308","#22c55e","#14b8a6","#3b82f6","#8b5cf6","#ec4899","#000000","#ffffff"];function Hr(r){const e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(r);if(!e)return{h:0,s:100,l:50};let t=parseInt(e[1],16)/255,s=parseInt(e[2],16)/255,n=parseInt(e[3],16)/255;const i=Math.max(t,s,n),o=Math.min(t,s,n);let a=0,c=0;const l=(i+o)/2;if(i!==o){const d=i-o;switch(c=l>.5?d/(2-i-o):d/(i+o),i){case t:a=((s-n)/d+(s<n?6:0))/6;break;case s:a=((n-t)/d+2)/6;break;case n:a=((t-s)/d+4)/6;break}}return{h:Math.round(a*360),s:Math.round(c*100),l:Math.round(l*100)}}function Zm(r,e,t){e/=100,t/=100;const s=e*Math.min(t,1-t),n=i=>{const o=(i+r/30)%12,a=t-s*Math.max(Math.min(o-3,9-o,1),-1);return Math.round(255*a).toString(16).padStart(2,"0")};return`#${n(0)}${n(8)}${n(4)}`}function Jm({value:r="#3b82f6",onChange:e,disabled:t,className:s}){const[n,i]=E.useState(!1),[o,a]=E.useState(()=>Hr(r)),[c,l]=E.useState(r),d=E.useRef(null);E.useEffect(()=>{a(Hr(r)),l(r)},[r]);const u=m=>{a(m);const p=Zm(m.h,m.s,m.l);l(p),e==null||e(p)},h=m=>{if(!d.current)return;const p=d.current.getBoundingClientRect(),x=Math.max(0,Math.min(1,(m.clientX-p.left)/p.width)),v=Math.max(0,Math.min(1,(m.clientY-p.top)/p.height));u({...o,s:Math.round(x*100),l:Math.round((1-v)*100)})},g=m=>{if(l(m),/^#[0-9A-Fa-f]{6}$/.test(m)){const p=Hr(m);a(p),e==null||e(m)}};return f.jsxs(ar,{open:n,onOpenChange:i,children:[f.jsx(lr,{asChild:!0,children:f.jsxs(Ze,{variant:"outline",disabled:t,className:I("w-full justify-start gap-2",s),children:[f.jsx("div",{className:"h-5 w-5 rounded border shadow-sm",style:{backgroundColor:r}}),f.jsx("span",{className:"font-mono text-sm",children:r})]})}),f.jsx(Bs,{className:"w-72 p-3",align:"start",children:f.jsxs("div",{className:"space-y-3",children:[f.jsx("div",{ref:d,onClick:h,className:"relative h-40 rounded-lg cursor-crosshair overflow-hidden border",style:{background:`
2
2
  linear-gradient(to top, #000 0%, transparent 100%),
3
- linear-gradient(to right, #fff 0%, hsl(${i.h}, 100%, 50%) 100%)
4
- `},children:n.jsx("div",{className:"absolute w-4 h-4 rounded-full border-2 border-white shadow-md transform -translate-x-1/2 -translate-y-1/2 pointer-events-none",style:{left:`${i.s}%`,top:`${100-i.l}%`,backgroundColor:e}})}),n.jsxs("div",{className:"space-y-1",children:[n.jsx(mr,{className:"text-xs",children:"Hue"}),n.jsx("input",{type:"range",min:0,max:360,value:i.h,onChange:h=>u({...i,h:parseInt(h.target.value)}),className:"w-full h-3 rounded-lg appearance-none cursor-pointer",style:{background:`linear-gradient(to right,
3
+ linear-gradient(to right, #fff 0%, hsl(${o.h}, 100%, 50%) 100%)
4
+ `},children:f.jsx("div",{className:"absolute w-4 h-4 rounded-full border-2 border-white shadow-md transform -translate-x-1/2 -translate-y-1/2 pointer-events-none",style:{left:`${o.s}%`,top:`${100-o.l}%`,backgroundColor:r}})}),f.jsxs("div",{className:"space-y-1",children:[f.jsx(On,{className:"text-xs",children:"Hue"}),f.jsx("input",{type:"range",min:0,max:360,value:o.h,onChange:m=>u({...o,h:parseInt(m.target.value)}),className:"w-full h-3 rounded-lg appearance-none cursor-pointer",style:{background:`linear-gradient(to right,
5
5
  hsl(0, 100%, 50%),
6
6
  hsl(60, 100%, 50%),
7
7
  hsl(120, 100%, 50%),
@@ -9,7 +9,7 @@
9
9
  hsl(240, 100%, 50%),
10
10
  hsl(300, 100%, 50%),
11
11
  hsl(360, 100%, 50%)
12
- )`}})]}),n.jsxs("div",{className:"flex gap-2 items-center",children:[n.jsx("div",{className:"h-9 w-9 rounded-md border flex-shrink-0 shadow-inner",style:{backgroundColor:e}}),n.jsx(mt,{value:d,onChange:h=>g(h.target.value),placeholder:"#000000",className:"font-mono text-sm"})]}),n.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:gc.map(h=>n.jsx("button",{onClick:()=>{t==null||t(h),l(er(h)),c(h)},className:v("h-7 w-7 rounded-md border-2 transition-transform hover:scale-110",e===h?"border-primary ring-2 ring-ring":"border-transparent"),style:{backgroundColor:h}},h))})]})})]})}const Wo=f.forwardRef(({className:e,as:t="div",...r},o)=>n.jsx(t,{ref:o,className:v(e),...r}));Wo.displayName="Box";const Uo=f.forwardRef(({className:e,direction:t,wrap:r,justify:o,align:s,gap:a,style:i,...l},d)=>n.jsx("div",{ref:d,className:v("flex",t&&`flex-${t}`,r&&`flex-${r}`,o&&`justify-${o}`,s&&`items-${s}`,typeof a=="number"&&`gap-${a}`,e),style:{...typeof a=="string"?{gap:a}:{},...i},...l}));Uo.displayName="Flex";const Ko=f.forwardRef(({className:e,spacing:t=4,align:r,style:o,...s},a)=>n.jsx("div",{ref:a,className:v("flex flex-col",typeof t=="number"&&`gap-${t}`,r&&`items-${r}`,e),style:{...typeof t=="string"?{gap:t}:{},...o},...s}));Ko.displayName="VStack";const Xo=f.forwardRef(({className:e,spacing:t=4,align:r="center",style:o,...s},a)=>n.jsx("div",{ref:a,className:v("flex flex-row",typeof t=="number"&&`gap-${t}`,r&&`items-${r}`,e),style:{...typeof t=="string"?{gap:t}:{},...o},...s}));Xo.displayName="HStack";const Yo=f.forwardRef(({className:e,cols:t=1,gap:r=4,style:o,...s},a)=>{const i=typeof t=="number"?`grid-cols-${t}`:[t.sm&&`sm:grid-cols-${t.sm}`,t.md&&`md:grid-cols-${t.md}`,t.lg&&`lg:grid-cols-${t.lg}`,t.xl&&`xl:grid-cols-${t.xl}`].filter(Boolean).join(" ");return n.jsx("div",{ref:a,className:v("grid",i,typeof r=="number"&&`gap-${r}`,e),style:{...typeof r=="string"?{gap:r}:{},...o},...s})});Yo.displayName="Grid";const xc={sm:"max-w-screen-sm",md:"max-w-screen-md",lg:"max-w-screen-lg",xl:"max-w-screen-xl","2xl":"max-w-screen-2xl",full:"max-w-full"},Zo=f.forwardRef(({className:e,maxWidth:t="lg",centered:r=!0,...o},s)=>n.jsx("div",{ref:s,className:v("w-full px-4",xc[t],r&&"mx-auto",e),...o}));Zo.displayName="Container";const vc=ul.Root,bc=Ur.Root,wc=Ur.CollapsibleTrigger,Jo=f.forwardRef(({className:e,children:t,...r},o)=>n.jsx(Ur.CollapsibleContent,{ref:o,className:v("overflow-hidden transition-all duration-300 ease-in-out","data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down",e),...r,children:n.jsx("div",{className:"pb-2",children:t})}));Jo.displayName="CollapsibleContent";const Qo=Le("rounded-xl text-card-foreground transition-all duration-300",{variants:{variant:{default:"border bg-card shadow-sm",elevated:"border border-white/10 bg-gradient-to-br from-card/80 to-card/40 backdrop-blur-xl shadow-2xl shadow-black/20",glass:"border border-white/10 bg-white/5 backdrop-blur-xl shadow-xl",ghost:"bg-transparent"}},defaultVariants:{variant:"default"}}),en=f.forwardRef(({className:e,variant:t,...r},o)=>n.jsx("div",{ref:o,className:v(Qo({variant:t}),e),...r}));en.displayName="Card";const tn=f.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:v("flex flex-col space-y-1.5 p-6",e),...t}));tn.displayName="CardHeader";const rn=f.forwardRef(({className:e,...t},r)=>n.jsx("h3",{ref:r,className:v("text-2xl font-semibold leading-none tracking-tight",e),...t}));rn.displayName="CardTitle";const es=f.forwardRef(({className:e,...t},r)=>n.jsx("p",{ref:r,className:v("text-sm text-muted-foreground",e),...t}));es.displayName="CardDescription";const nn=f.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:v("p-6 pt-0",e),...t}));nn.displayName="CardContent";const ts=f.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:v("flex items-center p-6 pt-0",e),...t}));ts.displayName="CardFooter";const on=f.forwardRef(({className:e,...t},r)=>n.jsx("div",{className:"relative w-full overflow-auto",children:n.jsx("table",{ref:r,className:v("w-full caption-bottom text-sm",e),...t})}));on.displayName="Table";const sn=f.forwardRef(({className:e,...t},r)=>n.jsx("thead",{ref:r,className:v("[&_tr]:border-b",e),...t}));sn.displayName="TableHeader";const an=f.forwardRef(({className:e,...t},r)=>n.jsx("tbody",{ref:r,className:v("[&_tr:last-child]:border-0",e),...t}));an.displayName="TableBody";const rs=f.forwardRef(({className:e,...t},r)=>n.jsx("tfoot",{ref:r,className:v("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",e),...t}));rs.displayName="TableFooter";const At=f.forwardRef(({className:e,...t},r)=>n.jsx("tr",{ref:r,className:v("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",e),...t}));At.displayName="TableRow";const ln=f.forwardRef(({className:e,...t},r)=>n.jsx("th",{ref:r,className:v("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",e),...t}));ln.displayName="TableHead";const ir=f.forwardRef(({className:e,...t},r)=>n.jsx("td",{ref:r,className:v("p-4 align-middle [&:has([role=checkbox])]:pr-0",e),...t}));ir.displayName="TableCell";const ns=f.forwardRef(({className:e,...t},r)=>n.jsx("caption",{ref:r,className:v("mt-4 text-sm text-muted-foreground",e),...t}));ns.displayName="TableCaption";const fr=f.forwardRef(({className:e,children:t,orientation:r="vertical",...o},s)=>n.jsxs(xt.Root,{ref:s,className:v("relative overflow-hidden",e),...o,children:[n.jsx(xt.Viewport,{className:"h-full w-full rounded-[inherit]",children:t}),(r==="vertical"||r==="both")&&n.jsx(lr,{orientation:"vertical"}),(r==="horizontal"||r==="both")&&n.jsx(lr,{orientation:"horizontal"}),n.jsx(xt.Corner,{})]}));fr.displayName=xt.Root.displayName;const lr=f.forwardRef(({className:e,orientation:t="vertical",...r},o)=>n.jsx(xt.ScrollAreaScrollbar,{ref:o,orientation:t,className:v("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...r,children:n.jsx(xt.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));lr.displayName=xt.ScrollAreaScrollbar.displayName;const yc=wt.Root,os=f.forwardRef(({className:e,...t},r)=>n.jsx(wt.List,{ref:r,className:v("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",e),...t}));os.displayName=wt.List.displayName;const ss=f.forwardRef(({className:e,...t},r)=>n.jsx(wt.Trigger,{ref:r,className:v("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",e),...t}));ss.displayName=wt.Trigger.displayName;const as=f.forwardRef(({className:e,...t},r)=>n.jsx(wt.Content,{ref:r,className:v("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),...t}));as.displayName=wt.Content.displayName;const jc=vt.Root,is=f.forwardRef(({className:e,...t},r)=>n.jsx(vt.Item,{ref:r,className:v("border-b",e),...t}));is.displayName="AccordionItem";const ls=f.forwardRef(({className:e,children:t,...r},o)=>n.jsx(vt.Header,{className:"flex",children:n.jsxs(vt.Trigger,{ref:o,className:v("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...r,children:[t,n.jsx(P.ChevronDown,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));ls.displayName=vt.Trigger.displayName;const cs=f.forwardRef(({className:e,children:t,...r},o)=>n.jsx(vt.Content,{ref:o,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...r,children:n.jsx("div",{className:v("pb-4 pt-0",e),children:t})}));cs.displayName=vt.Content.displayName;const ds=ge.Root,Nc=ge.Trigger,us=ge.Portal,kc=ge.Close,cn=f.forwardRef(({className:e,...t},r)=>n.jsx(ge.Overlay,{ref:r,className:v("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));cn.displayName=ge.Overlay.displayName;const dn=f.forwardRef(({className:e,children:t,...r},o)=>{const s=ce();return n.jsxs(us,{children:[n.jsx(cn,{}),n.jsxs(ge.Content,{ref:o,className:v("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...r,children:[t,n.jsxs(ge.Close,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[n.jsx(P.X,{className:"h-4 w-4"}),n.jsx("span",{className:"sr-only",children:s.common_close})]})]})]})});dn.displayName=ge.Content.displayName;const ms=({className:e,...t})=>n.jsx("div",{className:v("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});ms.displayName="DialogHeader";const fs=({className:e,...t})=>n.jsx("div",{className:v("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});fs.displayName="DialogFooter";const gs=f.forwardRef(({className:e,...t},r)=>n.jsx(ge.Title,{ref:r,className:v("text-lg font-semibold leading-none tracking-tight",e),...t}));gs.displayName=ge.Title.displayName;const ps=f.forwardRef(({className:e,...t},r)=>n.jsx(ge.Description,{ref:r,className:v("text-sm text-muted-foreground",e),...t}));ps.displayName=ge.Description.displayName;const hs=ge.Root,xs=ge.Trigger,vs=ge.Close,bs=ge.Portal,un=f.forwardRef(({className:e,...t},r)=>n.jsx(ge.Overlay,{className:v("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:r}));un.displayName=ge.Overlay.displayName;const Cc=Le("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),mn=f.forwardRef(({side:e="right",className:t,children:r,...o},s)=>{const a=ce();return n.jsxs(bs,{children:[n.jsx(un,{}),n.jsxs(ge.Content,{ref:s,className:v(Cc({side:e}),t),...o,children:[r,n.jsxs(ge.Close,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[n.jsx(P.X,{className:"h-4 w-4"}),n.jsx("span",{className:"sr-only",children:a.common_close})]})]})]})});mn.displayName=ge.Content.displayName;const fn=({className:e,...t})=>n.jsx("div",{className:v("flex flex-col space-y-2 text-center sm:text-left",e),...t});fn.displayName="SheetHeader";const gn=({className:e,...t})=>n.jsx("div",{className:v("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});gn.displayName="SheetFooter";const pn=f.forwardRef(({className:e,...t},r)=>n.jsx(ge.Title,{ref:r,className:v("text-lg font-semibold text-foreground",e),...t}));pn.displayName=ge.Title.displayName;const hn=f.forwardRef(({className:e,...t},r)=>n.jsx(ge.Description,{ref:r,className:v("text-sm text-muted-foreground",e),...t}));hn.displayName=ge.Description.displayName;const ws=pe.Root,ys=pe.Trigger,Sc=pe.Group,Rc=pe.Portal,_c=pe.Sub,Mc=pe.RadioGroup,js=f.forwardRef(({className:e,inset:t,children:r,...o},s)=>n.jsxs(pe.SubTrigger,{ref:s,className:v("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",t&&"pl-8",e),...o,children:[r,n.jsx(P.ChevronRight,{className:"ml-auto h-4 w-4"})]}));js.displayName=pe.SubTrigger.displayName;const Ns=f.forwardRef(({className:e,...t},r)=>n.jsx(pe.SubContent,{ref:r,className:v("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));Ns.displayName=pe.SubContent.displayName;const xn=f.forwardRef(({className:e,sideOffset:t=4,...r},o)=>n.jsx(pe.Portal,{children:n.jsx(pe.Content,{ref:o,sideOffset:t,className:v("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));xn.displayName=pe.Content.displayName;const Ft=f.forwardRef(({className:e,inset:t,...r},o)=>n.jsx(pe.Item,{ref:o,className:v("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r}));Ft.displayName=pe.Item.displayName;const ks=f.forwardRef(({className:e,children:t,checked:r,...o},s)=>n.jsxs(pe.CheckboxItem,{ref:s,className:v("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:r,...o,children:[n.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:n.jsx(pe.ItemIndicator,{children:n.jsx(P.Check,{className:"h-4 w-4"})})}),t]}));ks.displayName=pe.CheckboxItem.displayName;const Cs=f.forwardRef(({className:e,children:t,...r},o)=>n.jsxs(pe.RadioItem,{ref:o,className:v("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...r,children:[n.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:n.jsx(pe.ItemIndicator,{children:n.jsx(P.Circle,{className:"h-2 w-2 fill-current"})})}),t]}));Cs.displayName=pe.RadioItem.displayName;const Ss=f.forwardRef(({className:e,inset:t,...r},o)=>n.jsx(pe.Label,{ref:o,className:v("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...r}));Ss.displayName=pe.Label.displayName;const Rs=f.forwardRef(({className:e,...t},r)=>n.jsx(pe.Separator,{ref:r,className:v("-mx-1 my-1 h-px bg-muted",e),...t}));Rs.displayName=pe.Separator.displayName;const _s=({className:e,...t})=>n.jsx("span",{className:v("ml-auto text-xs tracking-widest opacity-60",e),...t});_s.displayName="DropdownMenuShortcut";const Pc=Wt.Provider,Ic=Wt.Root,Lc=Wt.Trigger,Ms=f.forwardRef(({className:e,sideOffset:t=4,...r},o)=>n.jsx(Wt.Content,{ref:o,sideOffset:t,className:v("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r}));Ms.displayName=Wt.Content.displayName;const vn=f.forwardRef(({className:e,...t},r)=>n.jsx($e.Command,{ref:r,className:v("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t}));vn.displayName=$e.Command.displayName;const Tc=({children:e,...t})=>n.jsx(ds,{...t,children:n.jsx(dn,{className:"overflow-hidden p-0 shadow-lg",children:n.jsx(vn,{className:"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:e})})}),Ps=f.forwardRef(({className:e,...t},r)=>n.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[n.jsx(P.Search,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),n.jsx($e.Command.Input,{ref:r,className:v("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));Ps.displayName=$e.Command.Input.displayName;const Is=f.forwardRef(({className:e,...t},r)=>n.jsx($e.Command.List,{ref:r,className:v("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}));Is.displayName=$e.Command.List.displayName;const Ls=f.forwardRef((e,t)=>n.jsx($e.Command.Empty,{ref:t,className:"py-6 text-center text-sm",...e}));Ls.displayName=$e.Command.Empty.displayName;const Ts=f.forwardRef(({className:e,...t},r)=>n.jsx($e.Command.Group,{ref:r,className:v("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t}));Ts.displayName=$e.Command.Group.displayName;const Es=f.forwardRef(({className:e,...t},r)=>n.jsx($e.Command.Separator,{ref:r,className:v("-mx-1 h-px bg-border",e),...t}));Es.displayName=$e.Command.Separator.displayName;const Ds=f.forwardRef(({className:e,...t},r)=>n.jsx($e.Command.Item,{ref:r,className:v("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected='true']:text-accent-foreground data-[disabled=true]:opacity-50",e),...t}));Ds.displayName=$e.Command.Item.displayName;const As=({className:e,...t})=>n.jsx("span",{className:v("ml-auto text-xs tracking-widest text-muted-foreground",e),...t});As.displayName="CommandShortcut";const Ec=Le("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),Fs=f.forwardRef(({className:e,variant:t,...r},o)=>n.jsx("div",{ref:o,role:"alert",className:v(Ec({variant:t}),e),...r}));Fs.displayName="Alert";const Vs=f.forwardRef(({className:e,...t},r)=>n.jsx("h5",{ref:r,className:v("mb-1 font-medium leading-none tracking-tight",e),...t}));Vs.displayName="AlertTitle";const zs=f.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:v("text-sm [&_p]:leading-relaxed",e),...t}));zs.displayName="AlertDescription";const Dc=Ae.Root,Ac=Ae.Trigger,$s=Ae.Portal,bn=f.forwardRef(({className:e,...t},r)=>n.jsx(Ae.Overlay,{className:v("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:r}));bn.displayName=Ae.Overlay.displayName;const Bs=f.forwardRef(({className:e,...t},r)=>n.jsxs($s,{children:[n.jsx(bn,{}),n.jsx(Ae.Content,{ref:r,className:v("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));Bs.displayName=Ae.Content.displayName;const Os=({className:e,...t})=>n.jsx("div",{className:v("flex flex-col space-y-2 text-center sm:text-left",e),...t});Os.displayName="AlertDialogHeader";const Hs=({className:e,...t})=>n.jsx("div",{className:v("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});Hs.displayName="AlertDialogFooter";const Gs=f.forwardRef(({className:e,...t},r)=>n.jsx(Ae.Title,{ref:r,className:v("text-lg font-semibold",e),...t}));Gs.displayName=Ae.Title.displayName;const qs=f.forwardRef(({className:e,...t},r)=>n.jsx(Ae.Description,{ref:r,className:v("text-sm text-muted-foreground",e),...t}));qs.displayName=Ae.Description.displayName;const Ws=f.forwardRef(({className:e,...t},r)=>n.jsx(Ae.Action,{ref:r,className:v(Ut(),e),...t}));Ws.displayName=Ae.Action.displayName;const Us=f.forwardRef(({className:e,...t},r)=>n.jsx(Ae.Cancel,{ref:r,className:v(Ut({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));Us.displayName=Ae.Cancel.displayName;const Ks=f.forwardRef(({className:e,value:t,...r},o)=>n.jsx(Er.Root,{ref:o,className:v("relative h-4 w-full overflow-hidden rounded-full bg-secondary",e),...r,children:n.jsx(Er.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));Ks.displayName=Er.Root.displayName;function Fc({className:e,...t}){return n.jsx("div",{className:v("animate-pulse rounded-md bg-muted",e),...t})}function Vc(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",t.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}const zc=e=>{switch(e){case"success":return Oc;case"info":return Gc;case"warning":return Hc;case"error":return qc;default:return null}},$c=Array(12).fill(0),Bc=({visible:e,className:t})=>B.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},B.createElement("div",{className:"sonner-spinner"},$c.map((r,o)=>B.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${o}`})))),Oc=B.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},B.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),Hc=B.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},B.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),Gc=B.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},B.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),qc=B.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},B.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),Wc=B.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},B.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),B.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),Uc=()=>{const[e,t]=B.useState(document.hidden);return B.useEffect(()=>{const r=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",r),()=>window.removeEventListener("visibilitychange",r)},[]),e};let Ar=1;class Kc{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const r=this.subscribers.indexOf(t);this.subscribers.splice(r,1)}),this.publish=t=>{this.subscribers.forEach(r=>r(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var r;const{message:o,...s}=t,a=typeof(t==null?void 0:t.id)=="number"||((r=t.id)==null?void 0:r.length)>0?t.id:Ar++,i=this.toasts.find(d=>d.id===a),l=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(a)&&this.dismissedToasts.delete(a),i?this.toasts=this.toasts.map(d=>d.id===a?(this.publish({...d,...t,id:a,title:o}),{...d,...t,id:a,dismissible:l,title:o}):d):this.addToast({title:o,...s,dismissible:l,id:a}),a},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(r=>r({id:t,dismiss:!0})))):this.toasts.forEach(r=>{this.subscribers.forEach(o=>o({id:r.id,dismiss:!0}))}),t),this.message=(t,r)=>this.create({...r,message:t}),this.error=(t,r)=>this.create({...r,message:t,type:"error"}),this.success=(t,r)=>this.create({...r,type:"success",message:t}),this.info=(t,r)=>this.create({...r,type:"info",message:t}),this.warning=(t,r)=>this.create({...r,type:"warning",message:t}),this.loading=(t,r)=>this.create({...r,type:"loading",message:t}),this.promise=(t,r)=>{if(!r)return;let o;r.loading!==void 0&&(o=this.create({...r,promise:t,type:"loading",message:r.loading,description:typeof r.description!="function"?r.description:void 0}));const s=Promise.resolve(t instanceof Function?t():t);let a=o!==void 0,i;const l=s.then(async c=>{if(i=["resolve",c],B.isValidElement(c))a=!1,this.create({id:o,type:"default",message:c});else if(Yc(c)&&!c.ok){a=!1;const u=typeof r.error=="function"?await r.error(`HTTP error! status: ${c.status}`):r.error,m=typeof r.description=="function"?await r.description(`HTTP error! status: ${c.status}`):r.description,h=typeof u=="object"&&!B.isValidElement(u)?u:{message:u};this.create({id:o,type:"error",description:m,...h})}else if(c instanceof Error){a=!1;const u=typeof r.error=="function"?await r.error(c):r.error,m=typeof r.description=="function"?await r.description(c):r.description,h=typeof u=="object"&&!B.isValidElement(u)?u:{message:u};this.create({id:o,type:"error",description:m,...h})}else if(r.success!==void 0){a=!1;const u=typeof r.success=="function"?await r.success(c):r.success,m=typeof r.description=="function"?await r.description(c):r.description,h=typeof u=="object"&&!B.isValidElement(u)?u:{message:u};this.create({id:o,type:"success",description:m,...h})}}).catch(async c=>{if(i=["reject",c],r.error!==void 0){a=!1;const p=typeof r.error=="function"?await r.error(c):r.error,u=typeof r.description=="function"?await r.description(c):r.description,g=typeof p=="object"&&!B.isValidElement(p)?p:{message:p};this.create({id:o,type:"error",description:u,...g})}}).finally(()=>{a&&(this.dismiss(o),o=void 0),r.finally==null||r.finally.call(r)}),d=()=>new Promise((c,p)=>l.then(()=>i[0]==="reject"?p(i[1]):c(i[1])).catch(p));return typeof o!="string"&&typeof o!="number"?{unwrap:d}:Object.assign(o,{unwrap:d})},this.custom=(t,r)=>{const o=(r==null?void 0:r.id)||Ar++;return this.create({jsx:t(o),id:o,...r}),o},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const Ve=new Kc,Xc=(e,t)=>{const r=(t==null?void 0:t.id)||Ar++;return Ve.addToast({title:e,...t,id:r}),r},Yc=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",Zc=Xc,Jc=()=>Ve.toasts,Qc=()=>Ve.getActiveToasts(),ed=Object.assign(Zc,{success:Ve.success,info:Ve.info,warning:Ve.warning,error:Ve.error,custom:Ve.custom,message:Ve.message,promise:Ve.promise,dismiss:Ve.dismiss,loading:Ve.loading},{getHistory:Jc,getToasts:Qc});Vc("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function tr(e){return e.label!==void 0}const td=3,rd="24px",nd="16px",Bn=4e3,od=356,sd=14,ad=45,id=200;function Je(...e){return e.filter(Boolean).join(" ")}function ld(e){const[t,r]=e.split("-"),o=[];return t&&o.push(t),r&&o.push(r),o}const cd=e=>{var t,r,o,s,a,i,l,d,c;const{invert:p,toast:u,unstyled:m,interacting:g,setHeights:h,visibleToasts:x,heights:y,index:b,toasts:w,expanded:j,removeToast:M,defaultRichColors:R,closeButton:_,style:C,cancelButtonStyle:S,actionButtonStyle:T,className:L="",descriptionClassName:V="",duration:O,position:$,gap:k,expandByDefault:z,classNames:A,icons:E,closeButtonAriaLabel:N="Close toast"}=e,[W,q]=B.useState(null),[G,Z]=B.useState(null),[I,F]=B.useState(!1),[U,ee]=B.useState(!1),[X,Y]=B.useState(!1),[ae,te]=B.useState(!1),[ie,K]=B.useState(!1),[H,ne]=B.useState(0),[me,ve]=B.useState(0),fe=B.useRef(u.duration||O||Bn),Re=B.useRef(null),ue=B.useRef(null),Fe=b===0,He=b+1<=x,Ne=u.type,Te=u.dismissible!==!1,nt=u.className||"",jt=u.descriptionClassName||"",ot=B.useMemo(()=>y.findIndex(le=>le.toastId===u.id)||0,[y,u.id]),st=B.useMemo(()=>{var le;return(le=u.closeButton)!=null?le:_},[u.closeButton,_]),Nt=B.useMemo(()=>u.duration||O||Bn,[u.duration,O]),Ze=B.useRef(0),Ee=B.useRef(0),Qe=B.useRef(0),Ge=B.useRef(null),[at,kt]=$.split("-"),Ct=B.useMemo(()=>y.reduce((le,je,Ce)=>Ce>=ot?le:le+je.height,0),[y,ot]),D=Uc(),re=u.invert||p,we=Ne==="loading";Ee.current=B.useMemo(()=>ot*k+Ct,[ot,Ct]),B.useEffect(()=>{fe.current=Nt},[Nt]),B.useEffect(()=>{F(!0)},[]),B.useEffect(()=>{const le=ue.current;if(le){const je=le.getBoundingClientRect().height;return ve(je),h(Ce=>[{toastId:u.id,height:je,position:u.position},...Ce]),()=>h(Ce=>Ce.filter(De=>De.toastId!==u.id))}},[h,u.id]),B.useLayoutEffect(()=>{if(!I)return;const le=ue.current,je=le.style.height;le.style.height="auto";const Ce=le.getBoundingClientRect().height;le.style.height=je,ve(Ce),h(De=>De.find(Me=>Me.toastId===u.id)?De.map(Me=>Me.toastId===u.id?{...Me,height:Ce}:Me):[{toastId:u.id,height:Ce,position:u.position},...De])},[I,u.title,u.description,h,u.id,u.jsx,u.action,u.cancel]);const Pe=B.useCallback(()=>{ee(!0),ne(Ee.current),h(le=>le.filter(je=>je.toastId!==u.id)),setTimeout(()=>{M(u)},id)},[u,M,h,Ee]);B.useEffect(()=>{if(u.promise&&Ne==="loading"||u.duration===1/0||u.type==="loading")return;let le;return j||g||D?(()=>{if(Qe.current<Ze.current){const De=new Date().getTime()-Ze.current;fe.current=fe.current-De}Qe.current=new Date().getTime()})():(()=>{fe.current!==1/0&&(Ze.current=new Date().getTime(),le=setTimeout(()=>{u.onAutoClose==null||u.onAutoClose.call(u,u),Pe()},fe.current))})(),()=>clearTimeout(le)},[j,g,u,Ne,D,Pe]),B.useEffect(()=>{u.delete&&(Pe(),u.onDismiss==null||u.onDismiss.call(u,u))},[Pe,u.delete]);function et(){var le;if(E!=null&&E.loading){var je;return B.createElement("div",{className:Je(A==null?void 0:A.loader,u==null||(je=u.classNames)==null?void 0:je.loader,"sonner-loader"),"data-visible":Ne==="loading"},E.loading)}return B.createElement(Bc,{className:Je(A==null?void 0:A.loader,u==null||(le=u.classNames)==null?void 0:le.loader),visible:Ne==="loading"})}const ft=u.icon||(E==null?void 0:E[Ne])||zc(Ne);var it,lt;return B.createElement("li",{tabIndex:0,ref:ue,className:Je(L,nt,A==null?void 0:A.toast,u==null||(t=u.classNames)==null?void 0:t.toast,A==null?void 0:A.default,A==null?void 0:A[Ne],u==null||(r=u.classNames)==null?void 0:r[Ne]),"data-sonner-toast":"","data-rich-colors":(it=u.richColors)!=null?it:R,"data-styled":!(u.jsx||u.unstyled||m),"data-mounted":I,"data-promise":!!u.promise,"data-swiped":ie,"data-removed":U,"data-visible":He,"data-y-position":at,"data-x-position":kt,"data-index":b,"data-front":Fe,"data-swiping":X,"data-dismissible":Te,"data-type":Ne,"data-invert":re,"data-swipe-out":ae,"data-swipe-direction":G,"data-expanded":!!(j||z&&I),"data-testid":u.testId,style:{"--index":b,"--toasts-before":b,"--z-index":w.length-b,"--offset":`${U?H:Ee.current}px`,"--initial-height":z?"auto":`${me}px`,...C,...u.style},onDragEnd:()=>{Y(!1),q(null),Ge.current=null},onPointerDown:le=>{le.button!==2&&(we||!Te||(Re.current=new Date,ne(Ee.current),le.target.setPointerCapture(le.pointerId),le.target.tagName!=="BUTTON"&&(Y(!0),Ge.current={x:le.clientX,y:le.clientY})))},onPointerUp:()=>{var le,je,Ce;if(ae||!Te)return;Ge.current=null;const De=Number(((le=ue.current)==null?void 0:le.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Yt=Number(((je=ue.current)==null?void 0:je.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Me=new Date().getTime()-((Ce=Re.current)==null?void 0:Ce.getTime()),qe=W==="x"?De:Yt,Zt=Math.abs(qe)/Me;if(Math.abs(qe)>=ad||Zt>.11){ne(Ee.current),u.onDismiss==null||u.onDismiss.call(u,u),Z(W==="x"?De>0?"right":"left":Yt>0?"down":"up"),Pe(),te(!0);return}else{var We,Ue;(We=ue.current)==null||We.style.setProperty("--swipe-amount-x","0px"),(Ue=ue.current)==null||Ue.style.setProperty("--swipe-amount-y","0px")}K(!1),Y(!1),q(null)},onPointerMove:le=>{var je,Ce,De;if(!Ge.current||!Te||((je=window.getSelection())==null?void 0:je.toString().length)>0)return;const Me=le.clientY-Ge.current.y,qe=le.clientX-Ge.current.x;var Zt;const We=(Zt=e.swipeDirections)!=null?Zt:ld($);!W&&(Math.abs(qe)>1||Math.abs(Me)>1)&&q(Math.abs(qe)>Math.abs(Me)?"x":"y");let Ue={x:0,y:0};const Ln=gt=>1/(1.5+Math.abs(gt)/20);if(W==="y"){if(We.includes("top")||We.includes("bottom"))if(We.includes("top")&&Me<0||We.includes("bottom")&&Me>0)Ue.y=Me;else{const gt=Me*Ln(Me);Ue.y=Math.abs(gt)<Math.abs(Me)?gt:Me}}else if(W==="x"&&(We.includes("left")||We.includes("right")))if(We.includes("left")&&qe<0||We.includes("right")&&qe>0)Ue.x=qe;else{const gt=qe*Ln(qe);Ue.x=Math.abs(gt)<Math.abs(qe)?gt:qe}(Math.abs(Ue.x)>0||Math.abs(Ue.y)>0)&&K(!0),(Ce=ue.current)==null||Ce.style.setProperty("--swipe-amount-x",`${Ue.x}px`),(De=ue.current)==null||De.style.setProperty("--swipe-amount-y",`${Ue.y}px`)}},st&&!u.jsx&&Ne!=="loading"?B.createElement("button",{"aria-label":N,"data-disabled":we,"data-close-button":!0,onClick:we||!Te?()=>{}:()=>{Pe(),u.onDismiss==null||u.onDismiss.call(u,u)},className:Je(A==null?void 0:A.closeButton,u==null||(o=u.classNames)==null?void 0:o.closeButton)},(lt=E==null?void 0:E.close)!=null?lt:Wc):null,(Ne||u.icon||u.promise)&&u.icon!==null&&((E==null?void 0:E[Ne])!==null||u.icon)?B.createElement("div",{"data-icon":"",className:Je(A==null?void 0:A.icon,u==null||(s=u.classNames)==null?void 0:s.icon)},u.promise||u.type==="loading"&&!u.icon?u.icon||et():null,u.type!=="loading"?ft:null):null,B.createElement("div",{"data-content":"",className:Je(A==null?void 0:A.content,u==null||(a=u.classNames)==null?void 0:a.content)},B.createElement("div",{"data-title":"",className:Je(A==null?void 0:A.title,u==null||(i=u.classNames)==null?void 0:i.title)},u.jsx?u.jsx:typeof u.title=="function"?u.title():u.title),u.description?B.createElement("div",{"data-description":"",className:Je(V,jt,A==null?void 0:A.description,u==null||(l=u.classNames)==null?void 0:l.description)},typeof u.description=="function"?u.description():u.description):null),B.isValidElement(u.cancel)?u.cancel:u.cancel&&tr(u.cancel)?B.createElement("button",{"data-button":!0,"data-cancel":!0,style:u.cancelButtonStyle||S,onClick:le=>{tr(u.cancel)&&Te&&(u.cancel.onClick==null||u.cancel.onClick.call(u.cancel,le),Pe())},className:Je(A==null?void 0:A.cancelButton,u==null||(d=u.classNames)==null?void 0:d.cancelButton)},u.cancel.label):null,B.isValidElement(u.action)?u.action:u.action&&tr(u.action)?B.createElement("button",{"data-button":!0,"data-action":!0,style:u.actionButtonStyle||T,onClick:le=>{tr(u.action)&&(u.action.onClick==null||u.action.onClick.call(u.action,le),!le.defaultPrevented&&Pe())},className:Je(A==null?void 0:A.actionButton,u==null||(c=u.classNames)==null?void 0:c.actionButton)},u.action.label):null)};function On(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function dd(e,t){const r={};return[e,t].forEach((o,s)=>{const a=s===1,i=a?"--mobile-offset":"--offset",l=a?nd:rd;function d(c){["top","right","bottom","left"].forEach(p=>{r[`${i}-${p}`]=typeof c=="number"?`${c}px`:c})}typeof o=="number"||typeof o=="string"?d(o):typeof o=="object"?["top","right","bottom","left"].forEach(c=>{o[c]===void 0?r[`${i}-${c}`]=l:r[`${i}-${c}`]=typeof o[c]=="number"?`${o[c]}px`:o[c]}):d(l)}),r}const ud=B.forwardRef(function(t,r){const{id:o,invert:s,position:a="bottom-right",hotkey:i=["altKey","KeyT"],expand:l,closeButton:d,className:c,offset:p,mobileOffset:u,theme:m="light",richColors:g,duration:h,style:x,visibleToasts:y=td,toastOptions:b,dir:w=On(),gap:j=sd,icons:M,containerAriaLabel:R="Notifications"}=t,[_,C]=B.useState([]),S=B.useMemo(()=>o?_.filter(I=>I.toasterId===o):_.filter(I=>!I.toasterId),[_,o]),T=B.useMemo(()=>Array.from(new Set([a].concat(S.filter(I=>I.position).map(I=>I.position)))),[S,a]),[L,V]=B.useState([]),[O,$]=B.useState(!1),[k,z]=B.useState(!1),[A,E]=B.useState(m!=="system"?m:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),N=B.useRef(null),W=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),q=B.useRef(null),G=B.useRef(!1),Z=B.useCallback(I=>{C(F=>{var U;return(U=F.find(ee=>ee.id===I.id))!=null&&U.delete||Ve.dismiss(I.id),F.filter(({id:ee})=>ee!==I.id)})},[]);return B.useEffect(()=>Ve.subscribe(I=>{if(I.dismiss){requestAnimationFrame(()=>{C(F=>F.map(U=>U.id===I.id?{...U,delete:!0}:U))});return}setTimeout(()=>{qr.flushSync(()=>{C(F=>{const U=F.findIndex(ee=>ee.id===I.id);return U!==-1?[...F.slice(0,U),{...F[U],...I},...F.slice(U+1)]:[I,...F]})})})}),[_]),B.useEffect(()=>{if(m!=="system"){E(m);return}if(m==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?E("dark"):E("light")),typeof window>"u")return;const I=window.matchMedia("(prefers-color-scheme: dark)");try{I.addEventListener("change",({matches:F})=>{E(F?"dark":"light")})}catch{I.addListener(({matches:U})=>{try{E(U?"dark":"light")}catch(ee){console.error(ee)}})}},[m]),B.useEffect(()=>{_.length<=1&&$(!1)},[_]),B.useEffect(()=>{const I=F=>{var U;if(i.every(Y=>F[Y]||F.code===Y)){var X;$(!0),(X=N.current)==null||X.focus()}F.code==="Escape"&&(document.activeElement===N.current||(U=N.current)!=null&&U.contains(document.activeElement))&&$(!1)};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[i]),B.useEffect(()=>{if(N.current)return()=>{q.current&&(q.current.focus({preventScroll:!0}),q.current=null,G.current=!1)}},[N.current]),B.createElement("section",{ref:r,"aria-label":`${R} ${W}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},T.map((I,F)=>{var U;const[ee,X]=I.split("-");return S.length?B.createElement("ol",{key:I,dir:w==="auto"?On():w,tabIndex:-1,ref:N,className:c,"data-sonner-toaster":!0,"data-sonner-theme":A,"data-y-position":ee,"data-x-position":X,style:{"--front-toast-height":`${((U=L[0])==null?void 0:U.height)||0}px`,"--width":`${od}px`,"--gap":`${j}px`,...x,...dd(p,u)},onBlur:Y=>{G.current&&!Y.currentTarget.contains(Y.relatedTarget)&&(G.current=!1,q.current&&(q.current.focus({preventScroll:!0}),q.current=null))},onFocus:Y=>{Y.target instanceof HTMLElement&&Y.target.dataset.dismissible==="false"||G.current||(G.current=!0,q.current=Y.relatedTarget)},onMouseEnter:()=>$(!0),onMouseMove:()=>$(!0),onMouseLeave:()=>{k||$(!1)},onDragEnd:()=>$(!1),onPointerDown:Y=>{Y.target instanceof HTMLElement&&Y.target.dataset.dismissible==="false"||z(!0)},onPointerUp:()=>z(!1)},S.filter(Y=>!Y.position&&F===0||Y.position===I).map((Y,ae)=>{var te,ie;return B.createElement(cd,{key:Y.id,icons:M,index:ae,toast:Y,defaultRichColors:g,duration:(te=b==null?void 0:b.duration)!=null?te:h,className:b==null?void 0:b.className,descriptionClassName:b==null?void 0:b.descriptionClassName,invert:s,visibleToasts:y,closeButton:(ie=b==null?void 0:b.closeButton)!=null?ie:d,interacting:k,position:I,style:b==null?void 0:b.style,unstyled:b==null?void 0:b.unstyled,classNames:b==null?void 0:b.classNames,cancelButtonStyle:b==null?void 0:b.cancelButtonStyle,actionButtonStyle:b==null?void 0:b.actionButtonStyle,closeButtonAriaLabel:b==null?void 0:b.closeButtonAriaLabel,removeToast:Z,toasts:S.filter(K=>K.position==Y.position),heights:L.filter(K=>K.position==Y.position),setHeights:V,expandByDefault:l,gap:j,expanded:O,swipeDirections:t.swipeDirections})})):null}))}),Nr=["light","dark","system"];function md(){return typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function Hn(e){return e==="system"?md():e}function fd(e){if(typeof document>"u")return()=>{};const t=document.createElement("style");return e&&t.setAttribute("nonce",e),t.appendChild(document.createTextNode("*, *::before, *::after { transition: none !important; animation: none !important; }")),document.head.appendChild(t),window.getComputedStyle(document.body),()=>{window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>{document.head.removeChild(t)})})}}function gd(e,t){const r=document.documentElement;t==="class"?(r.classList.remove("light","dark"),r.classList.add(e)):r.setAttribute("data-theme",e)}const Xs=B.createContext(void 0);function pd({children:e,defaultTheme:t="system",storageKey:r="nui-theme",attribute:o="class",enableSystem:s=!0,disableTransitionOnChange:a=!1,forcedTheme:i,nonce:l}){const[d,c]=B.useState(()=>{if(typeof window>"u")return t;const b=localStorage.getItem(r);return b&&Nr.includes(b)?b:t}),[p,u]=B.useState(()=>Hn(i??d)),m=B.useRef(d);m.current=d;const g=B.useCallback(()=>{const b=i??m.current,w=Hn(b);u(w);let j;a&&(j=fd(l)),gd(w,o),j==null||j()},[i,o,a,l]);B.useEffect(()=>{g()},[d,i,g]),B.useEffect(()=>{if(!s)return;const b=window.matchMedia("(prefers-color-scheme: dark)"),w=()=>{(i??m.current)==="system"&&g()};return b.addEventListener("change",w),()=>b.removeEventListener("change",w)},[s,i,g]),B.useEffect(()=>{const b=w=>{if(w.key===r&&w.newValue){const j=w.newValue;Nr.includes(j)&&c(j)}};return window.addEventListener("storage",b),()=>window.removeEventListener("storage",b)},[r]);const h=B.useCallback(b=>{!s&&b==="system"||(localStorage.setItem(r,b),c(b))},[r,s]),x=B.useMemo(()=>s?Nr:["light","dark"],[s]),y=B.useMemo(()=>({theme:i??d,resolvedTheme:p,setTheme:h,themes:x}),[i,d,p,h,x]);return n.jsx(Xs.Provider,{value:y,children:e})}function gr(){const e=B.useContext(Xs);if(e===void 0)throw new Error("useTheme must be used within a <ThemeProvider>");return e}const hd=({theme:e,...t})=>{let r=e;try{const{resolvedTheme:o}=gr();e||(r=o)}catch{r||(r="system")}return n.jsx(ud,{theme:r,className:"toaster group",toastOptions:{classNames:{toast:"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground"}},...t})};function xd({icon:e,title:t,description:r,action:o,className:s}){return n.jsxs("div",{className:v("flex flex-col items-center justify-center py-12 px-4 text-center",s),children:[e&&n.jsx("div",{className:"mb-4 text-muted-foreground",children:e}),n.jsx("h3",{className:"text-lg font-semibold",children:t}),r&&n.jsx("p",{className:"mt-1 text-sm text-muted-foreground max-w-sm",children:r}),o&&n.jsx("div",{className:"mt-4",children:o})]})}const Ys=f.forwardRef(({...e},t)=>n.jsx("nav",{ref:t,"aria-label":"breadcrumb",...e}));Ys.displayName="Breadcrumb";const Zs=f.forwardRef(({className:e,...t},r)=>n.jsx("ol",{ref:r,className:v("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",e),...t}));Zs.displayName="BreadcrumbList";const Js=f.forwardRef(({className:e,...t},r)=>n.jsx("li",{ref:r,className:v("inline-flex items-center gap-1.5",e),...t}));Js.displayName="BreadcrumbItem";const Qs=f.forwardRef(({asChild:e,className:t,...r},o)=>{const s=e?ro.Slot:"a";return n.jsx(s,{ref:o,className:v("transition-colors hover:text-foreground",t),...r})});Qs.displayName="BreadcrumbLink";const ea=f.forwardRef(({className:e,...t},r)=>n.jsx("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:v("font-normal text-foreground",e),...t}));ea.displayName="BreadcrumbPage";const ta=({children:e,className:t,...r})=>n.jsx("li",{role:"presentation","aria-hidden":"true",className:v("[&>svg]:w-3.5 [&>svg]:h-3.5",t),...r,children:e??n.jsx(P.ChevronRight,{})});ta.displayName="BreadcrumbSeparator";const ra=({className:e,...t})=>{const r=ce();return n.jsxs("span",{role:"presentation","aria-hidden":"true",className:v("flex h-9 w-9 items-center justify-center",e),...t,children:[n.jsx("span",{className:"h-4 w-4",children:"..."}),n.jsx("span",{className:"sr-only",children:r.breadcrumb_more})]})};ra.displayName="BreadcrumbEllipsis";const na=({className:e,...t})=>n.jsx("nav",{role:"navigation","aria-label":"pagination",className:v("mx-auto flex w-full justify-center",e),...t});na.displayName="Pagination";const oa=f.forwardRef(({className:e,...t},r)=>n.jsx("ul",{ref:r,className:v("flex flex-row items-center gap-1",e),...t}));oa.displayName="PaginationContent";const sa=f.forwardRef(({className:e,...t},r)=>n.jsx("li",{ref:r,className:v("",e),...t}));sa.displayName="PaginationItem";const pr=({className:e,isActive:t,size:r="icon",...o})=>n.jsx("a",{"aria-current":t?"page":void 0,className:v(Ut({variant:t?"outline":"ghost",size:r}),e),...o});pr.displayName="PaginationLink";const aa=({className:e,...t})=>{const r=ce();return n.jsxs(pr,{"aria-label":r.pagination_goToPrevious,size:"default",className:v("gap-1 pl-2.5",e),...t,children:[n.jsx(P.ChevronLeft,{className:"h-4 w-4"}),n.jsx("span",{children:r.pagination_previous})]})};aa.displayName="PaginationPrevious";const ia=({className:e,...t})=>{const r=ce();return n.jsxs(pr,{"aria-label":r.pagination_goToNext,size:"default",className:v("gap-1 pr-2.5",e),...t,children:[n.jsx("span",{children:r.pagination_next}),n.jsx(P.ChevronRight,{className:"h-4 w-4"})]})};ia.displayName="PaginationNext";const la=({className:e,...t})=>{const r=ce();return n.jsxs("span",{"aria-hidden":!0,className:v("flex h-9 w-9 items-center justify-center",e),...t,children:[n.jsx(P.MoreHorizontal,{className:"h-4 w-4"}),n.jsx("span",{className:"sr-only",children:r.pagination_morePages})]})};la.displayName="PaginationEllipsis";function vd({steps:e,activeStep:t,orientation:r="horizontal",className:o}){return n.jsx("div",{className:v("flex",r==="vertical"?"flex-col":"flex-row items-center",o),children:e.map((s,a)=>{const i=a<t,l=a===t,d=a===e.length-1;return n.jsxs(f.Fragment,{children:[n.jsxs("div",{className:v("flex items-center",r==="vertical"&&"flex-row"),children:[n.jsx("div",{className:v("flex h-10 w-10 items-center justify-center rounded-full border-2 font-semibold transition-colors",i&&"border-primary bg-primary text-primary-foreground",l&&"border-primary text-primary",!i&&!l&&"border-muted-foreground/30 text-muted-foreground"),children:i?n.jsx(P.Check,{className:"h-5 w-5"}):a+1}),n.jsxs("div",{className:v("ml-3",r==="horizontal"&&"hidden sm:block"),children:[n.jsx("p",{className:v("text-sm font-medium",l&&"text-foreground",!l&&"text-muted-foreground"),children:s.title}),s.description&&n.jsx("p",{className:"text-xs text-muted-foreground",children:s.description})]})]}),!d&&n.jsx("div",{className:v("flex-1",r==="horizontal"?"mx-4 h-0.5 min-w-[3rem]":"ml-5 my-2 w-0.5 min-h-[2rem]",i?"bg-primary":"bg-muted-foreground/30")})]},a)})})}const ca=f.forwardRef(({className:e,children:t,...r},o)=>n.jsxs(Be.Root,{ref:o,className:v("relative z-10 flex max-w-max flex-1 items-center justify-center",e),...r,children:[t,n.jsx(wn,{})]}));ca.displayName=Be.Root.displayName;const da=f.forwardRef(({className:e,...t},r)=>n.jsx(Be.List,{ref:r,className:v("group flex flex-1 list-none items-center justify-center space-x-1",e),...t}));da.displayName=Be.List.displayName;const bd=Be.Item,ua=Le("group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50"),ma=f.forwardRef(({className:e,children:t,...r},o)=>n.jsxs(Be.Trigger,{ref:o,className:v(ua(),"group",e),...r,children:[t," ",n.jsx(P.ChevronDown,{className:"relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180","aria-hidden":"true"})]}));ma.displayName=Be.Trigger.displayName;const fa=f.forwardRef(({className:e,...t},r)=>n.jsx(Be.Content,{ref:r,className:v("left-0 top-0 w-full data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 md:absolute md:w-auto",e),...t}));fa.displayName=Be.Content.displayName;const wd=Be.Link,wn=f.forwardRef(({className:e,...t},r)=>n.jsx("div",{className:v("absolute left-0 top-full flex justify-center"),children:n.jsx(Be.Viewport,{className:v("origin-top-center relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 md:w-[var(--radix-navigation-menu-viewport-width)]",e),ref:r,...t})}));wn.displayName=Be.Viewport.displayName;const ga=f.forwardRef(({className:e,...t},r)=>n.jsx(Be.Indicator,{ref:r,className:v("top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in",e),...t,children:n.jsx("div",{className:"relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md"})}));ga.displayName=Be.Indicator.displayName;const yd=he.Root,jd=he.Trigger,Nd=he.Group,kd=he.Portal,Cd=he.Sub,Sd=he.RadioGroup,pa=f.forwardRef(({className:e,inset:t,children:r,...o},s)=>n.jsxs(he.SubTrigger,{ref:s,className:v("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",t&&"pl-8",e),...o,children:[r,n.jsx(P.ChevronRight,{className:"ml-auto h-4 w-4"})]}));pa.displayName=he.SubTrigger.displayName;const ha=f.forwardRef(({className:e,...t},r)=>n.jsx(he.SubContent,{ref:r,className:v("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));ha.displayName=he.SubContent.displayName;const xa=f.forwardRef(({className:e,...t},r)=>n.jsx(he.Portal,{children:n.jsx(he.Content,{ref:r,className:v("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t})}));xa.displayName=he.Content.displayName;const va=f.forwardRef(({className:e,inset:t,...r},o)=>n.jsx(he.Item,{ref:o,className:v("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r}));va.displayName=he.Item.displayName;const ba=f.forwardRef(({className:e,children:t,checked:r,...o},s)=>n.jsxs(he.CheckboxItem,{ref:s,className:v("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:r,...o,children:[n.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:n.jsx(he.ItemIndicator,{children:n.jsx(P.Check,{className:"h-4 w-4"})})}),t]}));ba.displayName=he.CheckboxItem.displayName;const wa=f.forwardRef(({className:e,children:t,...r},o)=>n.jsxs(he.RadioItem,{ref:o,className:v("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...r,children:[n.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:n.jsx(he.ItemIndicator,{children:n.jsx(P.Circle,{className:"h-2 w-2 fill-current"})})}),t]}));wa.displayName=he.RadioItem.displayName;const ya=f.forwardRef(({className:e,inset:t,...r},o)=>n.jsx(he.Label,{ref:o,className:v("px-2 py-1.5 text-sm font-semibold text-foreground",t&&"pl-8",e),...r}));ya.displayName=he.Label.displayName;const ja=f.forwardRef(({className:e,...t},r)=>n.jsx(he.Separator,{ref:r,className:v("-mx-1 my-1 h-px bg-border",e),...t}));ja.displayName=he.Separator.displayName;const Na=({className:e,...t})=>n.jsx("span",{className:v("ml-auto text-xs tracking-widest text-muted-foreground",e),...t});Na.displayName="ContextMenuShortcut";const Rd=ur.Root,_d=ur.Trigger,ka=f.forwardRef(({className:e,align:t="center",sideOffset:r=4,...o},s)=>n.jsx(ur.Content,{ref:s,align:t,sideOffset:r,className:v("z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...o}));ka.displayName=ur.Content.displayName;function Md(e){return Object.prototype.toString.call(e)==="[object Object]"}function Gn(e){return Md(e)||Array.isArray(e)}function Pd(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}function yn(e,t){const r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;const s=JSON.stringify(Object.keys(e.breakpoints||{})),a=JSON.stringify(Object.keys(t.breakpoints||{}));return s!==a?!1:r.every(i=>{const l=e[i],d=t[i];return typeof l=="function"?`${l}`==`${d}`:!Gn(l)||!Gn(d)?l===d:yn(l,d)})}function qn(e){return e.concat().sort((t,r)=>t.name>r.name?1:-1).map(t=>t.options)}function Id(e,t){if(e.length!==t.length)return!1;const r=qn(e),o=qn(t);return r.every((s,a)=>{const i=o[a];return yn(s,i)})}function jn(e){return typeof e=="number"}function Fr(e){return typeof e=="string"}function hr(e){return typeof e=="boolean"}function Wn(e){return Object.prototype.toString.call(e)==="[object Object]"}function be(e){return Math.abs(e)}function Nn(e){return Math.sign(e)}function Vt(e,t){return be(e-t)}function Ld(e,t){if(e===0||t===0||be(e)<=be(t))return 0;const r=Vt(be(e),be(t));return be(r/e)}function Td(e){return Math.round(e*100)/100}function Ht(e){return Gt(e).map(Number)}function Xe(e){return e[Kt(e)]}function Kt(e){return Math.max(0,e.length-1)}function kn(e,t){return t===Kt(e)}function Un(e,t=0){return Array.from(Array(e),(r,o)=>t+o)}function Gt(e){return Object.keys(e)}function Ca(e,t){return[e,t].reduce((r,o)=>(Gt(o).forEach(s=>{const a=r[s],i=o[s],l=Wn(a)&&Wn(i);r[s]=l?Ca(a,i):i}),r),{})}function Vr(e,t){return typeof t.MouseEvent<"u"&&e instanceof t.MouseEvent}function Ed(e,t){const r={start:o,center:s,end:a};function o(){return 0}function s(d){return a(d)/2}function a(d){return t-d}function i(d,c){return Fr(e)?r[e](d):e(t,d,c)}return{measure:i}}function qt(){let e=[];function t(s,a,i,l={passive:!0}){let d;if("addEventListener"in s)s.addEventListener(a,i,l),d=()=>s.removeEventListener(a,i,l);else{const c=s;c.addListener(i),d=()=>c.removeListener(i)}return e.push(d),o}function r(){e=e.filter(s=>s())}const o={add:t,clear:r};return o}function Dd(e,t,r,o){const s=qt(),a=1e3/60;let i=null,l=0,d=0;function c(){s.add(e,"visibilitychange",()=>{e.hidden&&h()})}function p(){g(),s.clear()}function u(y){if(!d)return;i||(i=y,r(),r());const b=y-i;for(i=y,l+=b;l>=a;)r(),l-=a;const w=l/a;o(w),d&&(d=t.requestAnimationFrame(u))}function m(){d||(d=t.requestAnimationFrame(u))}function g(){t.cancelAnimationFrame(d),i=null,l=0,d=0}function h(){i=null,l=0}return{init:c,destroy:p,start:m,stop:g,update:r,render:o}}function Ad(e,t){const r=t==="rtl",o=e==="y",s=o?"y":"x",a=o?"x":"y",i=!o&&r?-1:1,l=p(),d=u();function c(h){const{height:x,width:y}=h;return o?x:y}function p(){return o?"top":r?"right":"left"}function u(){return o?"bottom":r?"left":"right"}function m(h){return h*i}return{scroll:s,cross:a,startEdge:l,endEdge:d,measureSize:c,direction:m}}function bt(e=0,t=0){const r=be(e-t);function o(c){return c<e}function s(c){return c>t}function a(c){return o(c)||s(c)}function i(c){return a(c)?o(c)?e:t:c}function l(c){return r?c-r*Math.ceil((c-t)/r):c}return{length:r,max:t,min:e,constrain:i,reachedAny:a,reachedMax:s,reachedMin:o,removeOffset:l}}function Sa(e,t,r){const{constrain:o}=bt(0,e),s=e+1;let a=i(t);function i(m){return r?be((s+m)%s):o(m)}function l(){return a}function d(m){return a=i(m),u}function c(m){return p().set(l()+m)}function p(){return Sa(e,l(),r)}const u={get:l,set:d,add:c,clone:p};return u}function Fd(e,t,r,o,s,a,i,l,d,c,p,u,m,g,h,x,y,b,w){const{cross:j,direction:M}=e,R=["INPUT","SELECT","TEXTAREA"],_={passive:!1},C=qt(),S=qt(),T=bt(50,225).constrain(g.measure(20)),L={mouse:300,touch:400},V={mouse:500,touch:600},O=h?43:25;let $=!1,k=0,z=0,A=!1,E=!1,N=!1,W=!1;function q(K){if(!w)return;function H(me){(hr(w)||w(K,me))&&ee(me)}const ne=t;C.add(ne,"dragstart",me=>me.preventDefault(),_).add(ne,"touchmove",()=>{},_).add(ne,"touchend",()=>{}).add(ne,"touchstart",H).add(ne,"mousedown",H).add(ne,"touchcancel",Y).add(ne,"contextmenu",Y).add(ne,"click",ae,!0)}function G(){C.clear(),S.clear()}function Z(){const K=W?r:t;S.add(K,"touchmove",X,_).add(K,"touchend",Y).add(K,"mousemove",X,_).add(K,"mouseup",Y)}function I(K){const H=K.nodeName||"";return R.includes(H)}function F(){return(h?V:L)[W?"mouse":"touch"]}function U(K,H){const ne=u.add(Nn(K)*-1),me=p.byDistance(K,!h).distance;return h||be(K)<T?me:y&&H?me*.5:p.byIndex(ne.get(),0).distance}function ee(K){const H=Vr(K,o);W=H,N=h&&H&&!K.buttons&&$,$=Vt(s.get(),i.get())>=2,!(H&&K.button!==0)&&(I(K.target)||(A=!0,a.pointerDown(K),c.useFriction(0).useDuration(0),s.set(i),Z(),k=a.readPoint(K),z=a.readPoint(K,j),m.emit("pointerDown")))}function X(K){if(!Vr(K,o)&&K.touches.length>=2)return Y(K);const ne=a.readPoint(K),me=a.readPoint(K,j),ve=Vt(ne,k),fe=Vt(me,z);if(!E&&!W&&(!K.cancelable||(E=ve>fe,!E)))return Y(K);const Re=a.pointerMove(K);ve>x&&(N=!0),c.useFriction(.3).useDuration(.75),l.start(),s.add(M(Re)),K.preventDefault()}function Y(K){const ne=p.byDistance(0,!1).index!==u.get(),me=a.pointerUp(K)*F(),ve=U(M(me),ne),fe=Ld(me,ve),Re=O-10*fe,ue=b+fe/50;E=!1,A=!1,S.clear(),c.useDuration(Re).useFriction(ue),d.distance(ve,!h),W=!1,m.emit("pointerUp")}function ae(K){N&&(K.stopPropagation(),K.preventDefault(),N=!1)}function te(){return A}return{init:q,destroy:G,pointerDown:te}}function Vd(e,t){let o,s;function a(u){return u.timeStamp}function i(u,m){const h=`client${(m||e.scroll)==="x"?"X":"Y"}`;return(Vr(u,t)?u:u.touches[0])[h]}function l(u){return o=u,s=u,i(u)}function d(u){const m=i(u)-i(s),g=a(u)-a(o)>170;return s=u,g&&(o=u),m}function c(u){if(!o||!s)return 0;const m=i(s)-i(o),g=a(u)-a(o),h=a(u)-a(s)>170,x=m/g;return g&&!h&&be(x)>.1?x:0}return{pointerDown:l,pointerMove:d,pointerUp:c,readPoint:i}}function zd(){function e(r){const{offsetTop:o,offsetLeft:s,offsetWidth:a,offsetHeight:i}=r;return{top:o,right:s+a,bottom:o+i,left:s,width:a,height:i}}return{measure:e}}function $d(e){function t(o){return e*(o/100)}return{measure:t}}function Bd(e,t,r,o,s,a,i){const l=[e].concat(o);let d,c,p=[],u=!1;function m(y){return s.measureSize(i.measure(y))}function g(y){if(!a)return;c=m(e),p=o.map(m);function b(w){for(const j of w){if(u)return;const M=j.target===e,R=o.indexOf(j.target),_=M?c:p[R],C=m(M?e:o[R]);if(be(C-_)>=.5){y.reInit(),t.emit("resize");break}}}d=new ResizeObserver(w=>{(hr(a)||a(y,w))&&b(w)}),r.requestAnimationFrame(()=>{l.forEach(w=>d.observe(w))})}function h(){u=!0,d&&d.disconnect()}return{init:g,destroy:h}}function Od(e,t,r,o,s,a){let i=0,l=0,d=s,c=a,p=e.get(),u=0;function m(){const _=o.get()-e.get(),C=!d;let S=0;return C?(i=0,r.set(o),e.set(o),S=_):(r.set(e),i+=_/d,i*=c,p+=i,e.add(i),S=p-u),l=Nn(S),u=p,R}function g(){const _=o.get()-t.get();return be(_)<.001}function h(){return d}function x(){return l}function y(){return i}function b(){return j(s)}function w(){return M(a)}function j(_){return d=_,R}function M(_){return c=_,R}const R={direction:x,duration:h,velocity:y,seek:m,settled:g,useBaseFriction:w,useBaseDuration:b,useFriction:M,useDuration:j};return R}function Hd(e,t,r,o,s){const a=s.measure(10),i=s.measure(50),l=bt(.1,.99);let d=!1;function c(){return!(d||!e.reachedAny(r.get())||!e.reachedAny(t.get()))}function p(g){if(!c())return;const h=e.reachedMin(t.get())?"min":"max",x=be(e[h]-t.get()),y=r.get()-t.get(),b=l.constrain(x/i);r.subtract(y*b),!g&&be(y)<a&&(r.set(e.constrain(r.get())),o.useDuration(25).useBaseFriction())}function u(g){d=!g}return{shouldConstrain:c,constrain:p,toggleActive:u}}function Gd(e,t,r,o,s){const a=bt(-t+e,0),i=u(),l=p(),d=m();function c(h,x){return Vt(h,x)<=1}function p(){const h=i[0],x=Xe(i),y=i.lastIndexOf(h),b=i.indexOf(x)+1;return bt(y,b)}function u(){return r.map((h,x)=>{const{min:y,max:b}=a,w=a.constrain(h),j=!x,M=kn(r,x);return j?b:M||c(y,w)?y:c(b,w)?b:w}).map(h=>parseFloat(h.toFixed(3)))}function m(){if(t<=e+s)return[a.max];if(o==="keepSnaps")return i;const{min:h,max:x}=l;return i.slice(h,x)}return{snapsContained:d,scrollContainLimit:l}}function qd(e,t,r){const o=t[0],s=r?o-e:Xe(t);return{limit:bt(s,o)}}function Wd(e,t,r,o){const a=t.min+.1,i=t.max+.1,{reachedMin:l,reachedMax:d}=bt(a,i);function c(m){return m===1?d(r.get()):m===-1?l(r.get()):!1}function p(m){if(!c(m))return;const g=e*(m*-1);o.forEach(h=>h.add(g))}return{loop:p}}function Ud(e){const{max:t,length:r}=e;function o(a){const i=a-t;return r?i/-r:0}return{get:o}}function Kd(e,t,r,o,s){const{startEdge:a,endEdge:i}=e,{groupSlides:l}=s,d=u().map(t.measure),c=m(),p=g();function u(){return l(o).map(x=>Xe(x)[i]-x[0][a]).map(be)}function m(){return o.map(x=>r[a]-x[a]).map(x=>-be(x))}function g(){return l(c).map(x=>x[0]).map((x,y)=>x+d[y])}return{snaps:c,snapsAligned:p}}function Xd(e,t,r,o,s,a){const{groupSlides:i}=s,{min:l,max:d}=o,c=p();function p(){const m=i(a),g=!e||t==="keepSnaps";return r.length===1?[a]:g?m:m.slice(l,d).map((h,x,y)=>{const b=!x,w=kn(y,x);if(b){const j=Xe(y[0])+1;return Un(j)}if(w){const j=Kt(a)-Xe(y)[0]+1;return Un(j,Xe(y)[0])}return h})}return{slideRegistry:c}}function Yd(e,t,r,o,s){const{reachedAny:a,removeOffset:i,constrain:l}=o;function d(h){return h.concat().sort((x,y)=>be(x)-be(y))[0]}function c(h){const x=e?i(h):l(h),y=t.map((w,j)=>({diff:p(w-x,0),index:j})).sort((w,j)=>be(w.diff)-be(j.diff)),{index:b}=y[0];return{index:b,distance:x}}function p(h,x){const y=[h,h+r,h-r];if(!e)return h;if(!x)return d(y);const b=y.filter(w=>Nn(w)===x);return b.length?d(b):Xe(y)-r}function u(h,x){const y=t[h]-s.get(),b=p(y,x);return{index:h,distance:b}}function m(h,x){const y=s.get()+h,{index:b,distance:w}=c(y),j=!e&&a(y);if(!x||j)return{index:b,distance:h};const M=t[b]-w,R=h+p(M,0);return{index:b,distance:R}}return{byDistance:m,byIndex:u,shortcut:p}}function Zd(e,t,r,o,s,a,i){function l(u){const m=u.distance,g=u.index!==t.get();a.add(m),m&&(o.duration()?e.start():(e.update(),e.render(1),e.update())),g&&(r.set(t.get()),t.set(u.index),i.emit("select"))}function d(u,m){const g=s.byDistance(u,m);l(g)}function c(u,m){const g=t.clone().set(u),h=s.byIndex(g.get(),m);l(h)}return{distance:d,index:c}}function Jd(e,t,r,o,s,a,i,l){const d={passive:!0,capture:!0};let c=0;function p(g){if(!l)return;function h(x){if(new Date().getTime()-c>10)return;i.emit("slideFocusStart"),e.scrollLeft=0;const w=r.findIndex(j=>j.includes(x));jn(w)&&(s.useDuration(0),o.index(w,0),i.emit("slideFocus"))}a.add(document,"keydown",u,!1),t.forEach((x,y)=>{a.add(x,"focus",b=>{(hr(l)||l(g,b))&&h(y)},d)})}function u(g){g.code==="Tab"&&(c=new Date().getTime())}return{init:p}}function Dt(e){let t=e;function r(){return t}function o(d){t=i(d)}function s(d){t+=i(d)}function a(d){t-=i(d)}function i(d){return jn(d)?d:d.get()}return{get:r,set:o,add:s,subtract:a}}function Ra(e,t){const r=e.scroll==="x"?i:l,o=t.style;let s=null,a=!1;function i(m){return`translate3d(${m}px,0px,0px)`}function l(m){return`translate3d(0px,${m}px,0px)`}function d(m){if(a)return;const g=Td(e.direction(m));g!==s&&(o.transform=r(g),s=g)}function c(m){a=!m}function p(){a||(o.transform="",t.getAttribute("style")||t.removeAttribute("style"))}return{clear:p,to:d,toggleActive:c}}function Qd(e,t,r,o,s,a,i,l,d){const p=Ht(s),u=Ht(s).reverse(),m=b().concat(w());function g(C,S){return C.reduce((T,L)=>T-s[L],S)}function h(C,S){return C.reduce((T,L)=>g(T,S)>0?T.concat([L]):T,[])}function x(C){return a.map((S,T)=>({start:S-o[T]+.5+C,end:S+t-.5+C}))}function y(C,S,T){const L=x(S);return C.map(V=>{const O=T?0:-r,$=T?r:0,k=T?"end":"start",z=L[V][k];return{index:V,loopPoint:z,slideLocation:Dt(-1),translate:Ra(e,d[V]),target:()=>l.get()>z?O:$}})}function b(){const C=i[0],S=h(u,C);return y(S,r,!1)}function w(){const C=t-i[0]-1,S=h(p,C);return y(S,-r,!0)}function j(){return m.every(({index:C})=>{const S=p.filter(T=>T!==C);return g(S,t)<=.1})}function M(){m.forEach(C=>{const{target:S,translate:T,slideLocation:L}=C,V=S();V!==L.get()&&(T.to(V),L.set(V))})}function R(){m.forEach(C=>C.translate.clear())}return{canLoop:j,clear:R,loop:M,loopPoints:m}}function eu(e,t,r){let o,s=!1;function a(d){if(!r)return;function c(p){for(const u of p)if(u.type==="childList"){d.reInit(),t.emit("slidesChanged");break}}o=new MutationObserver(p=>{s||(hr(r)||r(d,p))&&c(p)}),o.observe(e,{childList:!0})}function i(){o&&o.disconnect(),s=!0}return{init:a,destroy:i}}function tu(e,t,r,o){const s={};let a=null,i=null,l,d=!1;function c(){l=new IntersectionObserver(h=>{d||(h.forEach(x=>{const y=t.indexOf(x.target);s[y]=x}),a=null,i=null,r.emit("slidesInView"))},{root:e.parentElement,threshold:o}),t.forEach(h=>l.observe(h))}function p(){l&&l.disconnect(),d=!0}function u(h){return Gt(s).reduce((x,y)=>{const b=parseInt(y),{isIntersecting:w}=s[b];return(h&&w||!h&&!w)&&x.push(b),x},[])}function m(h=!0){if(h&&a)return a;if(!h&&i)return i;const x=u(h);return h&&(a=x),h||(i=x),x}return{init:c,destroy:p,get:m}}function ru(e,t,r,o,s,a){const{measureSize:i,startEdge:l,endEdge:d}=e,c=r[0]&&s,p=h(),u=x(),m=r.map(i),g=y();function h(){if(!c)return 0;const w=r[0];return be(t[l]-w[l])}function x(){if(!c)return 0;const w=a.getComputedStyle(Xe(o));return parseFloat(w.getPropertyValue(`margin-${d}`))}function y(){return r.map((w,j,M)=>{const R=!j,_=kn(M,j);return R?m[j]+p:_?m[j]+u:M[j+1][l]-w[l]}).map(be)}return{slideSizes:m,slideSizesWithGaps:g,startGap:p,endGap:u}}function nu(e,t,r,o,s,a,i,l,d){const{startEdge:c,endEdge:p,direction:u}=e,m=jn(r);function g(b,w){return Ht(b).filter(j=>j%w===0).map(j=>b.slice(j,j+w))}function h(b){return b.length?Ht(b).reduce((w,j,M)=>{const R=Xe(w)||0,_=R===0,C=j===Kt(b),S=s[c]-a[R][c],T=s[c]-a[j][p],L=!o&&_?u(i):0,V=!o&&C?u(l):0,O=be(T-V-(S+L));return M&&O>t+d&&w.push(j),C&&w.push(b.length),w},[]).map((w,j,M)=>{const R=Math.max(M[j-1]||0);return b.slice(R,w)}):[]}function x(b){return m?g(b,r):h(b)}return{groupSlides:x}}function ou(e,t,r,o,s,a,i){const{align:l,axis:d,direction:c,startIndex:p,loop:u,duration:m,dragFree:g,dragThreshold:h,inViewThreshold:x,slidesToScroll:y,skipSnaps:b,containScroll:w,watchResize:j,watchSlides:M,watchDrag:R,watchFocus:_}=a,C=2,S=zd(),T=S.measure(t),L=r.map(S.measure),V=Ad(d,c),O=V.measureSize(T),$=$d(O),k=Ed(l,O),z=!u&&!!w,A=u||!!w,{slideSizes:E,slideSizesWithGaps:N,startGap:W,endGap:q}=ru(V,T,L,r,A,s),G=nu(V,O,y,u,T,L,W,q,C),{snaps:Z,snapsAligned:I}=Kd(V,k,T,L,G),F=-Xe(Z)+Xe(N),{snapsContained:U,scrollContainLimit:ee}=Gd(O,F,I,w,C),X=z?U:I,{limit:Y}=qd(F,X,u),ae=Sa(Kt(X),p,u),te=ae.clone(),ie=Ht(r),K=({dragHandler:Ee,scrollBody:Qe,scrollBounds:Ge,options:{loop:at}})=>{at||Ge.constrain(Ee.pointerDown()),Qe.seek()},H=({scrollBody:Ee,translate:Qe,location:Ge,offsetLocation:at,previousLocation:kt,scrollLooper:Ct,slideLooper:D,dragHandler:re,animation:we,eventHandler:Pe,scrollBounds:et,options:{loop:ft}},it)=>{const lt=Ee.settled(),le=!et.shouldConstrain(),je=ft?lt:lt&&le,Ce=je&&!re.pointerDown();Ce&&we.stop();const De=Ge.get()*it+kt.get()*(1-it);at.set(De),ft&&(Ct.loop(Ee.direction()),D.loop()),Qe.to(at.get()),Ce&&Pe.emit("settle"),je||Pe.emit("scroll")},ne=Dd(o,s,()=>K(Ze),Ee=>H(Ze,Ee)),me=.68,ve=X[ae.get()],fe=Dt(ve),Re=Dt(ve),ue=Dt(ve),Fe=Dt(ve),He=Od(fe,ue,Re,Fe,m,me),Ne=Yd(u,X,F,Y,Fe),Te=Zd(ne,ae,te,He,Ne,Fe,i),nt=Ud(Y),jt=qt(),ot=tu(t,r,i,x),{slideRegistry:st}=Xd(z,w,X,ee,G,ie),Nt=Jd(e,r,st,Te,He,jt,i,_),Ze={ownerDocument:o,ownerWindow:s,eventHandler:i,containerRect:T,slideRects:L,animation:ne,axis:V,dragHandler:Fd(V,e,o,s,Fe,Vd(V,s),fe,ne,Te,He,Ne,ae,i,$,g,h,b,me,R),eventStore:jt,percentOfView:$,index:ae,indexPrevious:te,limit:Y,location:fe,offsetLocation:ue,previousLocation:Re,options:a,resizeHandler:Bd(t,i,s,r,V,j,S),scrollBody:He,scrollBounds:Hd(Y,ue,Fe,He,$),scrollLooper:Wd(F,Y,ue,[fe,ue,Re,Fe]),scrollProgress:nt,scrollSnapList:X.map(nt.get),scrollSnaps:X,scrollTarget:Ne,scrollTo:Te,slideLooper:Qd(V,O,F,E,N,Z,X,ue,r),slideFocus:Nt,slidesHandler:eu(t,i,M),slidesInView:ot,slideIndexes:ie,slideRegistry:st,slidesToScroll:G,target:Fe,translate:Ra(V,t)};return Ze}function su(){let e={},t;function r(c){t=c}function o(c){return e[c]||[]}function s(c){return o(c).forEach(p=>p(t,c)),d}function a(c,p){return e[c]=o(c).concat([p]),d}function i(c,p){return e[c]=o(c).filter(u=>u!==p),d}function l(){e={}}const d={init:r,emit:s,off:i,on:a,clear:l};return d}const au={align:"center",axis:"x",container:null,slides:null,containScroll:"trimSnaps",direction:"ltr",slidesToScroll:1,inViewThreshold:0,breakpoints:{},dragFree:!1,dragThreshold:10,loop:!1,skipSnaps:!1,duration:25,startIndex:0,active:!0,watchDrag:!0,watchResize:!0,watchSlides:!0,watchFocus:!0};function iu(e){function t(a,i){return Ca(a,i||{})}function r(a){const i=a.breakpoints||{},l=Gt(i).filter(d=>e.matchMedia(d).matches).map(d=>i[d]).reduce((d,c)=>t(d,c),{});return t(a,l)}function o(a){return a.map(i=>Gt(i.breakpoints||{})).reduce((i,l)=>i.concat(l),[]).map(e.matchMedia)}return{mergeOptions:t,optionsAtMedia:r,optionsMediaQueries:o}}function lu(e){let t=[];function r(a,i){return t=i.filter(({options:l})=>e.optionsAtMedia(l).active!==!1),t.forEach(l=>l.init(a,e)),i.reduce((l,d)=>Object.assign(l,{[d.name]:d}),{})}function o(){t=t.filter(a=>a.destroy())}return{init:r,destroy:o}}function cr(e,t,r){const o=e.ownerDocument,s=o.defaultView,a=iu(s),i=lu(a),l=qt(),d=su(),{mergeOptions:c,optionsAtMedia:p,optionsMediaQueries:u}=a,{on:m,off:g,emit:h}=d,x=V;let y=!1,b,w=c(au,cr.globalOptions),j=c(w),M=[],R,_,C;function S(){const{container:ie,slides:K}=j;_=(Fr(ie)?e.querySelector(ie):ie)||e.children[0];const ne=Fr(K)?_.querySelectorAll(K):K;C=[].slice.call(ne||_.children)}function T(ie){const K=ou(e,_,C,o,s,ie,d);if(ie.loop&&!K.slideLooper.canLoop()){const H=Object.assign({},ie,{loop:!1});return T(H)}return K}function L(ie,K){y||(w=c(w,ie),j=p(w),M=K||M,S(),b=T(j),u([w,...M.map(({options:H})=>H)]).forEach(H=>l.add(H,"change",V)),j.active&&(b.translate.to(b.location.get()),b.animation.init(),b.slidesInView.init(),b.slideFocus.init(te),b.eventHandler.init(te),b.resizeHandler.init(te),b.slidesHandler.init(te),b.options.loop&&b.slideLooper.loop(),_.offsetParent&&C.length&&b.dragHandler.init(te),R=i.init(te,M)))}function V(ie,K){const H=G();O(),L(c({startIndex:H},ie),K),d.emit("reInit")}function O(){b.dragHandler.destroy(),b.eventStore.clear(),b.translate.clear(),b.slideLooper.clear(),b.resizeHandler.destroy(),b.slidesHandler.destroy(),b.slidesInView.destroy(),b.animation.destroy(),i.destroy(),l.clear()}function $(){y||(y=!0,l.clear(),O(),d.emit("destroy"),d.clear())}function k(ie,K,H){!j.active||y||(b.scrollBody.useBaseFriction().useDuration(K===!0?0:j.duration),b.scrollTo.index(ie,H||0))}function z(ie){const K=b.index.add(1).get();k(K,ie,-1)}function A(ie){const K=b.index.add(-1).get();k(K,ie,1)}function E(){return b.index.add(1).get()!==G()}function N(){return b.index.add(-1).get()!==G()}function W(){return b.scrollSnapList}function q(){return b.scrollProgress.get(b.offsetLocation.get())}function G(){return b.index.get()}function Z(){return b.indexPrevious.get()}function I(){return b.slidesInView.get()}function F(){return b.slidesInView.get(!1)}function U(){return R}function ee(){return b}function X(){return e}function Y(){return _}function ae(){return C}const te={canScrollNext:E,canScrollPrev:N,containerNode:Y,internalEngine:ee,destroy:$,off:g,on:m,emit:h,plugins:U,previousScrollSnap:Z,reInit:x,rootNode:X,scrollNext:z,scrollPrev:A,scrollProgress:q,scrollSnapList:W,scrollTo:k,selectedScrollSnap:G,slideNodes:ae,slidesInView:I,slidesNotInView:F};return L(t,r),setTimeout(()=>d.emit("init"),0),te}cr.globalOptions=void 0;function Cn(e={},t=[]){const r=B.useRef(e),o=B.useRef(t),[s,a]=B.useState(),[i,l]=B.useState(),d=B.useCallback(()=>{s&&s.reInit(r.current,o.current)},[s]);return B.useEffect(()=>{yn(r.current,e)||(r.current=e,d())},[e,d]),B.useEffect(()=>{Id(o.current,t)||(o.current=t,d())},[t,d]),B.useEffect(()=>{if(Pd()&&i){cr.globalOptions=Cn.globalOptions;const c=cr(i,r.current,o.current);return a(c),()=>c.destroy()}else a(void 0)},[i,a]),[l,s]}Cn.globalOptions=void 0;const _a=f.createContext(null);function xr(){const e=f.useContext(_a);if(!e)throw new Error("useCarousel must be used within a <Carousel />");return e}const Ma=f.forwardRef(({orientation:e="horizontal",opts:t,setApi:r,plugins:o,className:s,children:a,...i},l)=>{const[d,c]=Cn({...t,axis:e==="horizontal"?"x":"y"},o),[p,u]=f.useState(!1),[m,g]=f.useState(!1),h=f.useCallback(w=>{w&&(u(w.canScrollPrev()),g(w.canScrollNext()))},[]),x=f.useCallback(()=>{c==null||c.scrollPrev()},[c]),y=f.useCallback(()=>{c==null||c.scrollNext()},[c]),b=f.useCallback(w=>{w.key==="ArrowLeft"?(w.preventDefault(),x()):w.key==="ArrowRight"&&(w.preventDefault(),y())},[x,y]);return f.useEffect(()=>{!c||!r||r(c)},[c,r]),f.useEffect(()=>{if(c)return h(c),c.on("reInit",h),c.on("select",h),()=>{c==null||c.off("select",h)}},[c,h]),n.jsx(_a.Provider,{value:{carouselRef:d,api:c,opts:t,orientation:e,scrollPrev:x,scrollNext:y,canScrollPrev:p,canScrollNext:m},children:n.jsx("div",{ref:l,onKeyDownCapture:b,className:v("relative",s),role:"region","aria-roledescription":"carousel",...i,children:a})})});Ma.displayName="Carousel";const Pa=f.forwardRef(({className:e,...t},r)=>{const{carouselRef:o,orientation:s}=xr();return n.jsx("div",{ref:o,className:"overflow-hidden",children:n.jsx("div",{ref:r,className:v("flex",s==="horizontal"?"-ml-4":"-mt-4 flex-col",e),...t})})});Pa.displayName="CarouselContent";const Ia=f.forwardRef(({className:e,...t},r)=>{const{orientation:o}=xr();return n.jsx("div",{ref:r,role:"group","aria-roledescription":"slide",className:v("min-w-0 shrink-0 grow-0 basis-full",o==="horizontal"?"pl-4":"pt-4",e),...t})});Ia.displayName="CarouselItem";const La=f.forwardRef(({className:e,variant:t="outline",size:r="icon",...o},s)=>{const{orientation:a,scrollPrev:i,canScrollPrev:l}=xr(),d=ce();return n.jsxs(ke,{ref:s,variant:t,size:r,className:v("absolute h-8 w-8 rounded-full",a==="horizontal"?"-left-12 top-1/2 -translate-y-1/2":"-top-12 left-1/2 -translate-x-1/2 rotate-90",e),disabled:!l,onClick:i,...o,children:[n.jsx(P.ChevronLeft,{className:"h-4 w-4"}),n.jsx("span",{className:"sr-only",children:d.carousel_previousSlide})]})});La.displayName="CarouselPrevious";const Ta=f.forwardRef(({className:e,variant:t="outline",size:r="icon",...o},s)=>{const{orientation:a,scrollNext:i,canScrollNext:l}=xr(),d=ce();return n.jsxs(ke,{ref:s,variant:t,size:r,className:v("absolute h-8 w-8 rounded-full",a==="horizontal"?"-right-12 top-1/2 -translate-y-1/2":"-bottom-12 left-1/2 -translate-x-1/2 rotate-90",e),disabled:!l,onClick:i,...o,children:[n.jsx(P.ChevronRight,{className:"h-4 w-4"}),n.jsx("span",{className:"sr-only",children:d.carousel_nextSlide})]})});Ta.displayName="CarouselNext";/**
12
+ )`}})]}),f.jsxs("div",{className:"flex gap-2 items-center",children:[f.jsx("div",{className:"h-9 w-9 rounded-md border flex-shrink-0 shadow-inner",style:{backgroundColor:r}}),f.jsx(ws,{value:c,onChange:m=>g(m.target.value),placeholder:"#000000",className:"font-mono text-sm"})]}),f.jsx("div",{className:"grid grid-cols-5 gap-1.5",children:Qm.map(m=>f.jsx("button",{onClick:()=>{e==null||e(m),a(Hr(m)),l(m)},className:I("h-7 w-7 rounded-md border-2 transition-transform hover:scale-110",r===m?"border-primary ring-2 ring-ring":"border-transparent"),style:{backgroundColor:m}},m))})]})})]})}const Qc=E.forwardRef(({className:r,as:e="div",...t},s)=>f.jsx(e,{ref:s,className:I(r),...t}));Qc.displayName="Box";const Zc=E.forwardRef(({className:r,direction:e,wrap:t,justify:s,align:n,gap:i,style:o,...a},c)=>f.jsx("div",{ref:c,className:I("flex",e&&`flex-${e}`,t&&`flex-${t}`,s&&`justify-${s}`,n&&`items-${n}`,typeof i=="number"&&`gap-${i}`,r),style:{...typeof i=="string"?{gap:i}:{},...o},...a}));Zc.displayName="Flex";const Jc=E.forwardRef(({className:r,spacing:e=4,align:t,style:s,...n},i)=>f.jsx("div",{ref:i,className:I("flex flex-col",typeof e=="number"&&`gap-${e}`,t&&`items-${t}`,r),style:{...typeof e=="string"?{gap:e}:{},...s},...n}));Jc.displayName="VStack";const ed=E.forwardRef(({className:r,spacing:e=4,align:t="center",style:s,...n},i)=>f.jsx("div",{ref:i,className:I("flex flex-row",typeof e=="number"&&`gap-${e}`,t&&`items-${t}`,r),style:{...typeof e=="string"?{gap:e}:{},...s},...n}));ed.displayName="HStack";const td=E.forwardRef(({className:r,cols:e=1,gap:t=4,style:s,...n},i)=>{const o=typeof e=="number"?`grid-cols-${e}`:[e.sm&&`sm:grid-cols-${e.sm}`,e.md&&`md:grid-cols-${e.md}`,e.lg&&`lg:grid-cols-${e.lg}`,e.xl&&`xl:grid-cols-${e.xl}`].filter(Boolean).join(" ");return f.jsx("div",{ref:i,className:I("grid",o,typeof t=="number"&&`gap-${t}`,r),style:{...typeof t=="string"?{gap:t}:{},...s},...n})});td.displayName="Grid";const ep={sm:"max-w-screen-sm",md:"max-w-screen-md",lg:"max-w-screen-lg",xl:"max-w-screen-xl","2xl":"max-w-screen-2xl",full:"max-w-full"},sd=E.forwardRef(({className:r,maxWidth:e="lg",centered:t=!0,...s},n)=>f.jsx("div",{ref:n,className:I("w-full px-4",ep[e],t&&"mx-auto",r),...s}));sd.displayName="Container";const tp=Yg.Root,sp=uo.Root,rp=uo.CollapsibleTrigger,rd=E.forwardRef(({className:r,children:e,...t},s)=>f.jsx(uo.CollapsibleContent,{ref:s,className:I("overflow-hidden transition-all duration-300 ease-in-out","data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down",r),...t,children:f.jsx("div",{className:"pb-2",children:e})}));rd.displayName="CollapsibleContent";const nd=ft("rounded-xl text-card-foreground transition-all duration-300",{variants:{variant:{default:"border bg-card shadow-sm",elevated:"border border-white/10 bg-gradient-to-br from-card/80 to-card/40 backdrop-blur-xl shadow-2xl shadow-black/20",glass:"border border-white/10 bg-white/5 backdrop-blur-xl shadow-xl",ghost:"bg-transparent"}},defaultVariants:{variant:"default"}}),vo=E.forwardRef(({className:r,variant:e,...t},s)=>f.jsx("div",{ref:s,className:I(nd({variant:e}),r),...t}));vo.displayName="Card";const yo=E.forwardRef(({className:r,...e},t)=>f.jsx("div",{ref:t,className:I("flex flex-col space-y-1.5 p-6",r),...e}));yo.displayName="CardHeader";const bo=E.forwardRef(({className:r,...e},t)=>f.jsx("h3",{ref:t,className:I("text-2xl font-semibold leading-none tracking-tight",r),...e}));bo.displayName="CardTitle";const id=E.forwardRef(({className:r,...e},t)=>f.jsx("p",{ref:t,className:I("text-sm text-muted-foreground",r),...e}));id.displayName="CardDescription";const So=E.forwardRef(({className:r,...e},t)=>f.jsx("div",{ref:t,className:I("p-6 pt-0",r),...e}));So.displayName="CardContent";const od=E.forwardRef(({className:r,...e},t)=>f.jsx("div",{ref:t,className:I("flex items-center p-6 pt-0",r),...e}));od.displayName="CardFooter";const Eo=E.forwardRef(({className:r,...e},t)=>f.jsx("div",{className:"relative w-full overflow-auto",children:f.jsx("table",{ref:t,className:I("w-full caption-bottom text-sm",r),...e})}));Eo.displayName="Table";const To=E.forwardRef(({className:r,...e},t)=>f.jsx("thead",{ref:t,className:I("[&_tr]:border-b",r),...e}));To.displayName="TableHeader";const wo=E.forwardRef(({className:r,...e},t)=>f.jsx("tbody",{ref:t,className:I("[&_tr:last-child]:border-0",r),...e}));wo.displayName="TableBody";const ad=E.forwardRef(({className:r,...e},t)=>f.jsx("tfoot",{ref:t,className:I("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",r),...e}));ad.displayName="TableFooter";const xr=E.forwardRef(({className:r,...e},t)=>f.jsx("tr",{ref:t,className:I("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",r),...e}));xr.displayName="TableRow";const Ro=E.forwardRef(({className:r,...e},t)=>f.jsx("th",{ref:t,className:I("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",r),...e}));Ro.displayName="TableHead";const Sn=E.forwardRef(({className:r,...e},t)=>f.jsx("td",{ref:t,className:I("p-4 align-middle [&:has([role=checkbox])]:pr-0",r),...e}));Sn.displayName="TableCell";const ld=E.forwardRef(({className:r,...e},t)=>f.jsx("caption",{ref:t,className:I("mt-4 text-sm text-muted-foreground",r),...e}));ld.displayName="TableCaption";const jn=E.forwardRef(({className:r,children:e,orientation:t="vertical",...s},n)=>f.jsxs(Ps.Root,{ref:n,className:I("relative overflow-hidden",r),...s,children:[f.jsx(Ps.Viewport,{className:"h-full w-full rounded-[inherit]",children:e}),(t==="vertical"||t==="both")&&f.jsx(En,{orientation:"vertical"}),(t==="horizontal"||t==="both")&&f.jsx(En,{orientation:"horizontal"}),f.jsx(Ps.Corner,{})]}));jn.displayName=Ps.Root.displayName;const En=E.forwardRef(({className:r,orientation:e="vertical",...t},s)=>f.jsx(Ps.ScrollAreaScrollbar,{ref:s,orientation:e,className:I("flex touch-none select-none transition-colors",e==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",e==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",r),...t,children:f.jsx(Ps.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));En.displayName=Ps.ScrollAreaScrollbar.displayName;const np=js.Root,cd=E.forwardRef(({className:r,...e},t)=>f.jsx(js.List,{ref:t,className:I("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",r),...e}));cd.displayName=js.List.displayName;const dd=E.forwardRef(({className:r,...e},t)=>f.jsx(js.Trigger,{ref:t,className:I("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",r),...e}));dd.displayName=js.Trigger.displayName;const ud=E.forwardRef(({className:r,...e},t)=>f.jsx(js.Content,{ref:t,className:I("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",r),...e}));ud.displayName=js.Content.displayName;const ip=Ms.Root,fd=E.forwardRef(({className:r,...e},t)=>f.jsx(Ms.Item,{ref:t,className:I("border-b",r),...e}));fd.displayName="AccordionItem";const hd=E.forwardRef(({className:r,children:e,...t},s)=>f.jsx(Ms.Header,{className:"flex",children:f.jsxs(Ms.Trigger,{ref:s,className:I("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",r),...t,children:[e,f.jsx(W.ChevronDown,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));hd.displayName=Ms.Trigger.displayName;const gd=E.forwardRef(({className:r,children:e,...t},s)=>f.jsx(Ms.Content,{ref:s,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...t,children:f.jsx("div",{className:I("pb-4 pt-0",r),children:e})}));gd.displayName=Ms.Content.displayName;const md=Fe.Root,op=Fe.Trigger,pd=Fe.Portal,ap=Fe.Close,Ao=E.forwardRef(({className:r,...e},t)=>f.jsx(Fe.Overlay,{ref:t,className:I("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",r),...e}));Ao.displayName=Fe.Overlay.displayName;const Io=E.forwardRef(({className:r,children:e,...t},s)=>{const n=ye();return f.jsxs(pd,{children:[f.jsx(Ao,{}),f.jsxs(Fe.Content,{ref:s,className:I("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",r),...t,children:[e,f.jsxs(Fe.Close,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[f.jsx(W.X,{className:"h-4 w-4"}),f.jsx("span",{className:"sr-only",children:n.common_close})]})]})]})});Io.displayName=Fe.Content.displayName;const xd=({className:r,...e})=>f.jsx("div",{className:I("flex flex-col space-y-1.5 text-center sm:text-left",r),...e});xd.displayName="DialogHeader";const vd=({className:r,...e})=>f.jsx("div",{className:I("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",r),...e});vd.displayName="DialogFooter";const yd=E.forwardRef(({className:r,...e},t)=>f.jsx(Fe.Title,{ref:t,className:I("text-lg font-semibold leading-none tracking-tight",r),...e}));yd.displayName=Fe.Title.displayName;const bd=E.forwardRef(({className:r,...e},t)=>f.jsx(Fe.Description,{ref:t,className:I("text-sm text-muted-foreground",r),...e}));bd.displayName=Fe.Description.displayName;const Sd=Fe.Root,Ed=Fe.Trigger,Td=Fe.Close,wd=Fe.Portal,Lo=E.forwardRef(({className:r,...e},t)=>f.jsx(Fe.Overlay,{className:I("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",r),...e,ref:t}));Lo.displayName=Fe.Overlay.displayName;const lp=ft("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),Co=E.forwardRef(({side:r="right",className:e,children:t,...s},n)=>{const i=ye();return f.jsxs(wd,{children:[f.jsx(Lo,{}),f.jsxs(Fe.Content,{ref:n,className:I(lp({side:r}),e),...s,children:[t,f.jsxs(Fe.Close,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[f.jsx(W.X,{className:"h-4 w-4"}),f.jsx("span",{className:"sr-only",children:i.common_close})]})]})]})});Co.displayName=Fe.Content.displayName;const _o=({className:r,...e})=>f.jsx("div",{className:I("flex flex-col space-y-2 text-center sm:text-left",r),...e});_o.displayName="SheetHeader";const ko=({className:r,...e})=>f.jsx("div",{className:I("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",r),...e});ko.displayName="SheetFooter";const Do=E.forwardRef(({className:r,...e},t)=>f.jsx(Fe.Title,{ref:t,className:I("text-lg font-semibold text-foreground",r),...e}));Do.displayName=Fe.Title.displayName;const Po=E.forwardRef(({className:r,...e},t)=>f.jsx(Fe.Description,{ref:t,className:I("text-sm text-muted-foreground",r),...e}));Po.displayName=Fe.Description.displayName;const Rd=Oe.Root,Ad=Oe.Trigger,cp=Oe.Group,dp=Oe.Portal,up=Oe.Sub,fp=Oe.RadioGroup,Id=E.forwardRef(({className:r,inset:e,children:t,...s},n)=>f.jsxs(Oe.SubTrigger,{ref:n,className:I("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",e&&"pl-8",r),...s,children:[t,f.jsx(W.ChevronRight,{className:"ml-auto h-4 w-4"})]}));Id.displayName=Oe.SubTrigger.displayName;const Ld=E.forwardRef(({className:r,...e},t)=>f.jsx(Oe.SubContent,{ref:t,className:I("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",r),...e}));Ld.displayName=Oe.SubContent.displayName;const No=E.forwardRef(({className:r,sideOffset:e=4,...t},s)=>f.jsx(Oe.Portal,{children:f.jsx(Oe.Content,{ref:s,sideOffset:e,className:I("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",r),...t})}));No.displayName=Oe.Content.displayName;const vr=E.forwardRef(({className:r,inset:e,...t},s)=>f.jsx(Oe.Item,{ref:s,className:I("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e&&"pl-8",r),...t}));vr.displayName=Oe.Item.displayName;const Cd=E.forwardRef(({className:r,children:e,checked:t,...s},n)=>f.jsxs(Oe.CheckboxItem,{ref:n,className:I("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",r),checked:t,...s,children:[f.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:f.jsx(Oe.ItemIndicator,{children:f.jsx(W.Check,{className:"h-4 w-4"})})}),e]}));Cd.displayName=Oe.CheckboxItem.displayName;const _d=E.forwardRef(({className:r,children:e,...t},s)=>f.jsxs(Oe.RadioItem,{ref:s,className:I("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",r),...t,children:[f.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:f.jsx(Oe.ItemIndicator,{children:f.jsx(W.Circle,{className:"h-2 w-2 fill-current"})})}),e]}));_d.displayName=Oe.RadioItem.displayName;const kd=E.forwardRef(({className:r,inset:e,...t},s)=>f.jsx(Oe.Label,{ref:s,className:I("px-2 py-1.5 text-sm font-semibold",e&&"pl-8",r),...t}));kd.displayName=Oe.Label.displayName;const Dd=E.forwardRef(({className:r,...e},t)=>f.jsx(Oe.Separator,{ref:t,className:I("-mx-1 my-1 h-px bg-muted",r),...e}));Dd.displayName=Oe.Separator.displayName;const Pd=({className:r,...e})=>f.jsx("span",{className:I("ml-auto text-xs tracking-widest opacity-60",r),...e});Pd.displayName="DropdownMenuShortcut";const hp=Or.Provider,gp=Or.Root,mp=Or.Trigger,Nd=E.forwardRef(({className:r,sideOffset:e=4,...t},s)=>f.jsx(Or.Content,{ref:s,sideOffset:e,className:I("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",r),...t}));Nd.displayName=Or.Content.displayName;const Mo=E.forwardRef(({className:r,...e},t)=>f.jsx(St.Command,{ref:t,className:I("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",r),...e}));Mo.displayName=St.Command.displayName;const pp=({children:r,...e})=>f.jsx(md,{...e,children:f.jsx(Io,{className:"overflow-hidden p-0 shadow-lg",children:f.jsx(Mo,{className:"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:r})})}),Md=E.forwardRef(({className:r,...e},t)=>f.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[f.jsx(W.Search,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),f.jsx(St.Command.Input,{ref:t,className:I("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",r),...e})]}));Md.displayName=St.Command.Input.displayName;const Fd=E.forwardRef(({className:r,...e},t)=>f.jsx(St.Command.List,{ref:t,className:I("max-h-[300px] overflow-y-auto overflow-x-hidden",r),...e}));Fd.displayName=St.Command.List.displayName;const Od=E.forwardRef((r,e)=>f.jsx(St.Command.Empty,{ref:e,className:"py-6 text-center text-sm",...r}));Od.displayName=St.Command.Empty.displayName;const jd=E.forwardRef(({className:r,...e},t)=>f.jsx(St.Command.Group,{ref:t,className:I("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",r),...e}));jd.displayName=St.Command.Group.displayName;const Bd=E.forwardRef(({className:r,...e},t)=>f.jsx(St.Command.Separator,{ref:t,className:I("-mx-1 h-px bg-border",r),...e}));Bd.displayName=St.Command.Separator.displayName;const $d=E.forwardRef(({className:r,...e},t)=>f.jsx(St.Command.Item,{ref:t,className:I("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected='true']:text-accent-foreground data-[disabled=true]:opacity-50",r),...e}));$d.displayName=St.Command.Item.displayName;const Ud=({className:r,...e})=>f.jsx("span",{className:I("ml-auto text-xs tracking-widest text-muted-foreground",r),...e});Ud.displayName="CommandShortcut";const xp=ft("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),Gd=E.forwardRef(({className:r,variant:e,...t},s)=>f.jsx("div",{ref:s,role:"alert",className:I(xp({variant:e}),r),...t}));Gd.displayName="Alert";const Vd=E.forwardRef(({className:r,...e},t)=>f.jsx("h5",{ref:t,className:I("mb-1 font-medium leading-none tracking-tight",r),...e}));Vd.displayName="AlertTitle";const Hd=E.forwardRef(({className:r,...e},t)=>f.jsx("div",{ref:t,className:I("text-sm [&_p]:leading-relaxed",r),...e}));Hd.displayName="AlertDescription";const vp=gt.Root,yp=gt.Trigger,Kd=gt.Portal,Fo=E.forwardRef(({className:r,...e},t)=>f.jsx(gt.Overlay,{className:I("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",r),...e,ref:t}));Fo.displayName=gt.Overlay.displayName;const zd=E.forwardRef(({className:r,...e},t)=>f.jsxs(Kd,{children:[f.jsx(Fo,{}),f.jsx(gt.Content,{ref:t,className:I("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",r),...e})]}));zd.displayName=gt.Content.displayName;const Wd=({className:r,...e})=>f.jsx("div",{className:I("flex flex-col space-y-2 text-center sm:text-left",r),...e});Wd.displayName="AlertDialogHeader";const Yd=({className:r,...e})=>f.jsx("div",{className:I("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",r),...e});Yd.displayName="AlertDialogFooter";const qd=E.forwardRef(({className:r,...e},t)=>f.jsx(gt.Title,{ref:t,className:I("text-lg font-semibold",r),...e}));qd.displayName=gt.Title.displayName;const Xd=E.forwardRef(({className:r,...e},t)=>f.jsx(gt.Description,{ref:t,className:I("text-sm text-muted-foreground",r),...e}));Xd.displayName=gt.Description.displayName;const Qd=E.forwardRef(({className:r,...e},t)=>f.jsx(gt.Action,{ref:t,className:I(jr(),r),...e}));Qd.displayName=gt.Action.displayName;const Zd=E.forwardRef(({className:r,...e},t)=>f.jsx(gt.Cancel,{ref:t,className:I(jr({variant:"outline"}),"mt-2 sm:mt-0",r),...e}));Zd.displayName=gt.Cancel.displayName;const Jd=E.forwardRef(({className:r,value:e,...t},s)=>f.jsx(Di.Root,{ref:s,className:I("relative h-4 w-full overflow-hidden rounded-full bg-secondary",r),...t,children:f.jsx(Di.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(e||0)}%)`}})}));Jd.displayName=Di.Root.displayName;function bp({className:r,...e}){return f.jsx("div",{className:I("animate-pulse rounded-md bg-muted",r),...e})}function Sp(r){if(typeof document>"u")return;let e=document.head||document.getElementsByTagName("head")[0],t=document.createElement("style");t.type="text/css",e.appendChild(t),t.styleSheet?t.styleSheet.cssText=r:t.appendChild(document.createTextNode(r))}const Ep=r=>{switch(r){case"success":return Rp;case"info":return Ip;case"warning":return Ap;case"error":return Lp;default:return null}},Tp=Array(12).fill(0),wp=({visible:r,className:e})=>Q.createElement("div",{className:["sonner-loading-wrapper",e].filter(Boolean).join(" "),"data-visible":r},Q.createElement("div",{className:"sonner-spinner"},Tp.map((t,s)=>Q.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${s}`})))),Rp=Q.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Q.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),Ap=Q.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},Q.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),Ip=Q.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Q.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),Lp=Q.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Q.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),Cp=Q.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},Q.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),Q.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),_p=()=>{const[r,e]=Q.useState(document.hidden);return Q.useEffect(()=>{const t=()=>{e(document.hidden)};return document.addEventListener("visibilitychange",t),()=>window.removeEventListener("visibilitychange",t)},[]),r};let Ni=1;class kp{constructor(){this.subscribe=e=>(this.subscribers.push(e),()=>{const t=this.subscribers.indexOf(e);this.subscribers.splice(t,1)}),this.publish=e=>{this.subscribers.forEach(t=>t(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e]},this.create=e=>{var t;const{message:s,...n}=e,i=typeof(e==null?void 0:e.id)=="number"||((t=e.id)==null?void 0:t.length)>0?e.id:Ni++,o=this.toasts.find(c=>c.id===i),a=e.dismissible===void 0?!0:e.dismissible;return this.dismissedToasts.has(i)&&this.dismissedToasts.delete(i),o?this.toasts=this.toasts.map(c=>c.id===i?(this.publish({...c,...e,id:i,title:s}),{...c,...e,id:i,dismissible:a,title:s}):c):this.addToast({title:s,...n,dismissible:a,id:i}),i},this.dismiss=e=>(e?(this.dismissedToasts.add(e),requestAnimationFrame(()=>this.subscribers.forEach(t=>t({id:e,dismiss:!0})))):this.toasts.forEach(t=>{this.subscribers.forEach(s=>s({id:t.id,dismiss:!0}))}),e),this.message=(e,t)=>this.create({...t,message:e}),this.error=(e,t)=>this.create({...t,message:e,type:"error"}),this.success=(e,t)=>this.create({...t,type:"success",message:e}),this.info=(e,t)=>this.create({...t,type:"info",message:e}),this.warning=(e,t)=>this.create({...t,type:"warning",message:e}),this.loading=(e,t)=>this.create({...t,type:"loading",message:e}),this.promise=(e,t)=>{if(!t)return;let s;t.loading!==void 0&&(s=this.create({...t,promise:e,type:"loading",message:t.loading,description:typeof t.description!="function"?t.description:void 0}));const n=Promise.resolve(e instanceof Function?e():e);let i=s!==void 0,o;const a=n.then(async l=>{if(o=["resolve",l],Q.isValidElement(l))i=!1,this.create({id:s,type:"default",message:l});else if(Pp(l)&&!l.ok){i=!1;const u=typeof t.error=="function"?await t.error(`HTTP error! status: ${l.status}`):t.error,h=typeof t.description=="function"?await t.description(`HTTP error! status: ${l.status}`):t.description,m=typeof u=="object"&&!Q.isValidElement(u)?u:{message:u};this.create({id:s,type:"error",description:h,...m})}else if(l instanceof Error){i=!1;const u=typeof t.error=="function"?await t.error(l):t.error,h=typeof t.description=="function"?await t.description(l):t.description,m=typeof u=="object"&&!Q.isValidElement(u)?u:{message:u};this.create({id:s,type:"error",description:h,...m})}else if(t.success!==void 0){i=!1;const u=typeof t.success=="function"?await t.success(l):t.success,h=typeof t.description=="function"?await t.description(l):t.description,m=typeof u=="object"&&!Q.isValidElement(u)?u:{message:u};this.create({id:s,type:"success",description:h,...m})}}).catch(async l=>{if(o=["reject",l],t.error!==void 0){i=!1;const d=typeof t.error=="function"?await t.error(l):t.error,u=typeof t.description=="function"?await t.description(l):t.description,g=typeof d=="object"&&!Q.isValidElement(d)?d:{message:d};this.create({id:s,type:"error",description:u,...g})}}).finally(()=>{i&&(this.dismiss(s),s=void 0),t.finally==null||t.finally.call(t)}),c=()=>new Promise((l,d)=>a.then(()=>o[0]==="reject"?d(o[1]):l(o[1])).catch(d));return typeof s!="string"&&typeof s!="number"?{unwrap:c}:Object.assign(s,{unwrap:c})},this.custom=(e,t)=>{const s=(t==null?void 0:t.id)||Ni++;return this.create({jsx:e(s),id:s,...t}),s},this.getActiveToasts=()=>this.toasts.filter(e=>!this.dismissedToasts.has(e.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const vt=new kp,Dp=(r,e)=>{const t=(e==null?void 0:e.id)||Ni++;return vt.addToast({title:r,...e,id:t}),t},Pp=r=>r&&typeof r=="object"&&"ok"in r&&typeof r.ok=="boolean"&&"status"in r&&typeof r.status=="number",Np=Dp,Mp=()=>vt.toasts,Fp=()=>vt.getActiveToasts(),Op=Object.assign(Np,{success:vt.success,info:vt.info,warning:vt.warning,error:vt.error,custom:vt.custom,message:vt.message,promise:vt.promise,dismiss:vt.dismiss,loading:vt.loading},{getHistory:Mp,getToasts:Fp});Sp("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function Kr(r){return r.label!==void 0}const jp=3,Bp="24px",$p="16px",Ca=4e3,Up=356,Gp=14,Vp=45,Hp=200;function qt(...r){return r.filter(Boolean).join(" ")}function Kp(r){const[e,t]=r.split("-"),s=[];return e&&s.push(e),t&&s.push(t),s}const zp=r=>{var e,t,s,n,i,o,a,c,l;const{invert:d,toast:u,unstyled:h,interacting:g,setHeights:m,visibleToasts:p,heights:x,index:v,toasts:y,expanded:b,removeToast:T,defaultRichColors:R,closeButton:_,style:w,cancelButtonStyle:A,actionButtonStyle:C,className:L="",descriptionClassName:P="",duration:M,position:j,gap:D,expandByDefault:$,classNames:N,icons:F,closeButtonAriaLabel:k="Close toast"}=r,[z,Y]=Q.useState(null),[U,K]=Q.useState(null),[G,H]=Q.useState(!1),[q,J]=Q.useState(!1),[ee,te]=Q.useState(!1),[de,ie]=Q.useState(!1),[ue,re]=Q.useState(!1),[Z,fe]=Q.useState(0),[Re,he]=Q.useState(0),be=Q.useRef(u.duration||M||Ca),Ae=Q.useRef(null),Ie=Q.useRef(null),Me=v===0,$e=v+1<=p,Le=u.type,at=u.dismissible!==!1,Ge=u.className||"",Mt=u.descriptionClassName||"",Je=Q.useMemo(()=>x.findIndex(xe=>xe.toastId===u.id)||0,[x,u.id]),Tt=Q.useMemo(()=>{var xe;return(xe=u.closeButton)!=null?xe:_},[u.closeButton,_]),Ft=Q.useMemo(()=>u.duration||M||Ca,[u.duration,M]),wt=Q.useRef(0),we=Q.useRef(0),mt=Q.useRef(0),Ot=Q.useRef(null),[Xe,Rs]=j.split("-"),$s=Q.useMemo(()=>x.reduce((xe,Ue,Ye)=>Ye>=Je?xe:xe+Ue.height,0),[x,Je]),fs=_p(),As=u.invert||d,ns=Le==="loading";we.current=Q.useMemo(()=>Je*D+$s,[Je,$s]),Q.useEffect(()=>{be.current=Ft},[Ft]),Q.useEffect(()=>{H(!0)},[]),Q.useEffect(()=>{const xe=Ie.current;if(xe){const Ue=xe.getBoundingClientRect().height;return he(Ue),m(Ye=>[{toastId:u.id,height:Ue,position:u.position},...Ye]),()=>m(Ye=>Ye.filter(nt=>nt.toastId!==u.id))}},[m,u.id]),Q.useLayoutEffect(()=>{if(!G)return;const xe=Ie.current,Ue=xe.style.height;xe.style.height="auto";const Ye=xe.getBoundingClientRect().height;xe.style.height=Ue,he(Ye),m(nt=>nt.find(et=>et.toastId===u.id)?nt.map(et=>et.toastId===u.id?{...et,height:Ye}:et):[{toastId:u.id,height:Ye,position:u.position},...nt])},[G,u.title,u.description,m,u.id,u.jsx,u.action,u.cancel]);const Rt=Q.useCallback(()=>{J(!0),fe(we.current),m(xe=>xe.filter(Ue=>Ue.toastId!==u.id)),setTimeout(()=>{T(u)},Hp)},[u,T,m,we]);Q.useEffect(()=>{if(u.promise&&Le==="loading"||u.duration===1/0||u.type==="loading")return;let xe;return b||g||fs?(()=>{if(mt.current<wt.current){const nt=new Date().getTime()-wt.current;be.current=be.current-nt}mt.current=new Date().getTime()})():(()=>{be.current!==1/0&&(wt.current=new Date().getTime(),xe=setTimeout(()=>{u.onAutoClose==null||u.onAutoClose.call(u,u),Rt()},be.current))})(),()=>clearTimeout(xe)},[b,g,u,Le,fs,Rt]),Q.useEffect(()=>{u.delete&&(Rt(),u.onDismiss==null||u.onDismiss.call(u,u))},[Rt,u.delete]);function cr(){var xe;if(F!=null&&F.loading){var Ue;return Q.createElement("div",{className:qt(N==null?void 0:N.loader,u==null||(Ue=u.classNames)==null?void 0:Ue.loader,"sonner-loader"),"data-visible":Le==="loading"},F.loading)}return Q.createElement(wp,{className:qt(N==null?void 0:N.loader,u==null||(xe=u.classNames)==null?void 0:xe.loader),visible:Le==="loading"})}const Us=u.icon||(F==null?void 0:F[Le])||Ep(Le);var Is,Yt;return Q.createElement("li",{tabIndex:0,ref:Ie,className:qt(L,Ge,N==null?void 0:N.toast,u==null||(e=u.classNames)==null?void 0:e.toast,N==null?void 0:N.default,N==null?void 0:N[Le],u==null||(t=u.classNames)==null?void 0:t[Le]),"data-sonner-toast":"","data-rich-colors":(Is=u.richColors)!=null?Is:R,"data-styled":!(u.jsx||u.unstyled||h),"data-mounted":G,"data-promise":!!u.promise,"data-swiped":ue,"data-removed":q,"data-visible":$e,"data-y-position":Xe,"data-x-position":Rs,"data-index":v,"data-front":Me,"data-swiping":ee,"data-dismissible":at,"data-type":Le,"data-invert":As,"data-swipe-out":de,"data-swipe-direction":U,"data-expanded":!!(b||$&&G),"data-testid":u.testId,style:{"--index":v,"--toasts-before":v,"--z-index":y.length-v,"--offset":`${q?Z:we.current}px`,"--initial-height":$?"auto":`${Re}px`,...w,...u.style},onDragEnd:()=>{te(!1),Y(null),Ot.current=null},onPointerDown:xe=>{xe.button!==2&&(ns||!at||(Ae.current=new Date,fe(we.current),xe.target.setPointerCapture(xe.pointerId),xe.target.tagName!=="BUTTON"&&(te(!0),Ot.current={x:xe.clientX,y:xe.clientY})))},onPointerUp:()=>{var xe,Ue,Ye;if(de||!at)return;Ot.current=null;const nt=Number(((xe=Ie.current)==null?void 0:xe.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Gt=Number(((Ue=Ie.current)==null?void 0:Ue.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),et=new Date().getTime()-((Ye=Ae.current)==null?void 0:Ye.getTime()),pt=z==="x"?nt:Gt,Gs=Math.abs(pt)/et;if(Math.abs(pt)>=Vp||Gs>.11){fe(we.current),u.onDismiss==null||u.onDismiss.call(u,u),K(z==="x"?nt>0?"right":"left":Gt>0?"down":"up"),Rt(),ie(!0);return}else{var At,It;(At=Ie.current)==null||At.style.setProperty("--swipe-amount-x","0px"),(It=Ie.current)==null||It.style.setProperty("--swipe-amount-y","0px")}re(!1),te(!1),Y(null)},onPointerMove:xe=>{var Ue,Ye,nt;if(!Ot.current||!at||((Ue=window.getSelection())==null?void 0:Ue.toString().length)>0)return;const et=xe.clientY-Ot.current.y,pt=xe.clientX-Ot.current.x;var Gs;const At=(Gs=r.swipeDirections)!=null?Gs:Kp(j);!z&&(Math.abs(pt)>1||Math.abs(et)>1)&&Y(Math.abs(pt)>Math.abs(et)?"x":"y");let It={x:0,y:0};const dr=is=>1/(1.5+Math.abs(is)/20);if(z==="y"){if(At.includes("top")||At.includes("bottom"))if(At.includes("top")&&et<0||At.includes("bottom")&&et>0)It.y=et;else{const is=et*dr(et);It.y=Math.abs(is)<Math.abs(et)?is:et}}else if(z==="x"&&(At.includes("left")||At.includes("right")))if(At.includes("left")&&pt<0||At.includes("right")&&pt>0)It.x=pt;else{const is=pt*dr(pt);It.x=Math.abs(is)<Math.abs(pt)?is:pt}(Math.abs(It.x)>0||Math.abs(It.y)>0)&&re(!0),(Ye=Ie.current)==null||Ye.style.setProperty("--swipe-amount-x",`${It.x}px`),(nt=Ie.current)==null||nt.style.setProperty("--swipe-amount-y",`${It.y}px`)}},Tt&&!u.jsx&&Le!=="loading"?Q.createElement("button",{"aria-label":k,"data-disabled":ns,"data-close-button":!0,onClick:ns||!at?()=>{}:()=>{Rt(),u.onDismiss==null||u.onDismiss.call(u,u)},className:qt(N==null?void 0:N.closeButton,u==null||(s=u.classNames)==null?void 0:s.closeButton)},(Yt=F==null?void 0:F.close)!=null?Yt:Cp):null,(Le||u.icon||u.promise)&&u.icon!==null&&((F==null?void 0:F[Le])!==null||u.icon)?Q.createElement("div",{"data-icon":"",className:qt(N==null?void 0:N.icon,u==null||(n=u.classNames)==null?void 0:n.icon)},u.promise||u.type==="loading"&&!u.icon?u.icon||cr():null,u.type!=="loading"?Us:null):null,Q.createElement("div",{"data-content":"",className:qt(N==null?void 0:N.content,u==null||(i=u.classNames)==null?void 0:i.content)},Q.createElement("div",{"data-title":"",className:qt(N==null?void 0:N.title,u==null||(o=u.classNames)==null?void 0:o.title)},u.jsx?u.jsx:typeof u.title=="function"?u.title():u.title),u.description?Q.createElement("div",{"data-description":"",className:qt(P,Mt,N==null?void 0:N.description,u==null||(a=u.classNames)==null?void 0:a.description)},typeof u.description=="function"?u.description():u.description):null),Q.isValidElement(u.cancel)?u.cancel:u.cancel&&Kr(u.cancel)?Q.createElement("button",{"data-button":!0,"data-cancel":!0,style:u.cancelButtonStyle||A,onClick:xe=>{Kr(u.cancel)&&at&&(u.cancel.onClick==null||u.cancel.onClick.call(u.cancel,xe),Rt())},className:qt(N==null?void 0:N.cancelButton,u==null||(c=u.classNames)==null?void 0:c.cancelButton)},u.cancel.label):null,Q.isValidElement(u.action)?u.action:u.action&&Kr(u.action)?Q.createElement("button",{"data-button":!0,"data-action":!0,style:u.actionButtonStyle||C,onClick:xe=>{Kr(u.action)&&(u.action.onClick==null||u.action.onClick.call(u.action,xe),!xe.defaultPrevented&&Rt())},className:qt(N==null?void 0:N.actionButton,u==null||(l=u.classNames)==null?void 0:l.actionButton)},u.action.label):null)};function _a(){if(typeof window>"u"||typeof document>"u")return"ltr";const r=document.documentElement.getAttribute("dir");return r==="auto"||!r?window.getComputedStyle(document.documentElement).direction:r}function Wp(r,e){const t={};return[r,e].forEach((s,n)=>{const i=n===1,o=i?"--mobile-offset":"--offset",a=i?$p:Bp;function c(l){["top","right","bottom","left"].forEach(d=>{t[`${o}-${d}`]=typeof l=="number"?`${l}px`:l})}typeof s=="number"||typeof s=="string"?c(s):typeof s=="object"?["top","right","bottom","left"].forEach(l=>{s[l]===void 0?t[`${o}-${l}`]=a:t[`${o}-${l}`]=typeof s[l]=="number"?`${s[l]}px`:s[l]}):c(a)}),t}const Yp=Q.forwardRef(function(e,t){const{id:s,invert:n,position:i="bottom-right",hotkey:o=["altKey","KeyT"],expand:a,closeButton:c,className:l,offset:d,mobileOffset:u,theme:h="light",richColors:g,duration:m,style:p,visibleToasts:x=jp,toastOptions:v,dir:y=_a(),gap:b=Gp,icons:T,containerAriaLabel:R="Notifications"}=e,[_,w]=Q.useState([]),A=Q.useMemo(()=>s?_.filter(G=>G.toasterId===s):_.filter(G=>!G.toasterId),[_,s]),C=Q.useMemo(()=>Array.from(new Set([i].concat(A.filter(G=>G.position).map(G=>G.position)))),[A,i]),[L,P]=Q.useState([]),[M,j]=Q.useState(!1),[D,$]=Q.useState(!1),[N,F]=Q.useState(h!=="system"?h:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),k=Q.useRef(null),z=o.join("+").replace(/Key/g,"").replace(/Digit/g,""),Y=Q.useRef(null),U=Q.useRef(!1),K=Q.useCallback(G=>{w(H=>{var q;return(q=H.find(J=>J.id===G.id))!=null&&q.delete||vt.dismiss(G.id),H.filter(({id:J})=>J!==G.id)})},[]);return Q.useEffect(()=>vt.subscribe(G=>{if(G.dismiss){requestAnimationFrame(()=>{w(H=>H.map(q=>q.id===G.id?{...q,delete:!0}:q))});return}setTimeout(()=>{lo.flushSync(()=>{w(H=>{const q=H.findIndex(J=>J.id===G.id);return q!==-1?[...H.slice(0,q),{...H[q],...G},...H.slice(q+1)]:[G,...H]})})})}),[_]),Q.useEffect(()=>{if(h!=="system"){F(h);return}if(h==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?F("dark"):F("light")),typeof window>"u")return;const G=window.matchMedia("(prefers-color-scheme: dark)");try{G.addEventListener("change",({matches:H})=>{F(H?"dark":"light")})}catch{G.addListener(({matches:q})=>{try{F(q?"dark":"light")}catch(J){console.error(J)}})}},[h]),Q.useEffect(()=>{_.length<=1&&j(!1)},[_]),Q.useEffect(()=>{const G=H=>{var q;if(o.every(te=>H[te]||H.code===te)){var ee;j(!0),(ee=k.current)==null||ee.focus()}H.code==="Escape"&&(document.activeElement===k.current||(q=k.current)!=null&&q.contains(document.activeElement))&&j(!1)};return document.addEventListener("keydown",G),()=>document.removeEventListener("keydown",G)},[o]),Q.useEffect(()=>{if(k.current)return()=>{Y.current&&(Y.current.focus({preventScroll:!0}),Y.current=null,U.current=!1)}},[k.current]),Q.createElement("section",{ref:t,"aria-label":`${R} ${z}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},C.map((G,H)=>{var q;const[J,ee]=G.split("-");return A.length?Q.createElement("ol",{key:G,dir:y==="auto"?_a():y,tabIndex:-1,ref:k,className:l,"data-sonner-toaster":!0,"data-sonner-theme":N,"data-y-position":J,"data-x-position":ee,style:{"--front-toast-height":`${((q=L[0])==null?void 0:q.height)||0}px`,"--width":`${Up}px`,"--gap":`${b}px`,...p,...Wp(d,u)},onBlur:te=>{U.current&&!te.currentTarget.contains(te.relatedTarget)&&(U.current=!1,Y.current&&(Y.current.focus({preventScroll:!0}),Y.current=null))},onFocus:te=>{te.target instanceof HTMLElement&&te.target.dataset.dismissible==="false"||U.current||(U.current=!0,Y.current=te.relatedTarget)},onMouseEnter:()=>j(!0),onMouseMove:()=>j(!0),onMouseLeave:()=>{D||j(!1)},onDragEnd:()=>j(!1),onPointerDown:te=>{te.target instanceof HTMLElement&&te.target.dataset.dismissible==="false"||$(!0)},onPointerUp:()=>$(!1)},A.filter(te=>!te.position&&H===0||te.position===G).map((te,de)=>{var ie,ue;return Q.createElement(zp,{key:te.id,icons:T,index:de,toast:te,defaultRichColors:g,duration:(ie=v==null?void 0:v.duration)!=null?ie:m,className:v==null?void 0:v.className,descriptionClassName:v==null?void 0:v.descriptionClassName,invert:n,visibleToasts:x,closeButton:(ue=v==null?void 0:v.closeButton)!=null?ue:c,interacting:D,position:G,style:v==null?void 0:v.style,unstyled:v==null?void 0:v.unstyled,classNames:v==null?void 0:v.classNames,cancelButtonStyle:v==null?void 0:v.cancelButtonStyle,actionButtonStyle:v==null?void 0:v.actionButtonStyle,closeButtonAriaLabel:v==null?void 0:v.closeButtonAriaLabel,removeToast:K,toasts:A.filter(re=>re.position==te.position),heights:L.filter(re=>re.position==te.position),setHeights:P,expandByDefault:a,gap:b,expanded:M,swipeDirections:e.swipeDirections})})):null}))}),Qn=["light","dark","system"];function qp(){return typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function ka(r){return r==="system"?qp():r}function Xp(r){if(typeof document>"u")return()=>{};const e=document.createElement("style");return r&&e.setAttribute("nonce",r),e.appendChild(document.createTextNode("*, *::before, *::after { transition: none !important; animation: none !important; }")),document.head.appendChild(e),window.getComputedStyle(document.body),()=>{window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>{document.head.removeChild(e)})})}}function Qp(r,e){const t=document.documentElement;e==="class"?(t.classList.remove("light","dark"),t.classList.add(r)):t.setAttribute("data-theme",r)}const eu=Q.createContext(void 0);function Zp({children:r,defaultTheme:e="system",storageKey:t="nui-theme",attribute:s="class",enableSystem:n=!0,disableTransitionOnChange:i=!1,forcedTheme:o,nonce:a}){const[c,l]=Q.useState(()=>{if(typeof window>"u")return e;const v=localStorage.getItem(t);return v&&Qn.includes(v)?v:e}),[d,u]=Q.useState(()=>ka(o??c)),h=Q.useRef(c);h.current=c;const g=Q.useCallback(()=>{const v=o??h.current,y=ka(v);u(y);let b;i&&(b=Xp(a)),Qp(y,s),b==null||b()},[o,s,i,a]);Q.useEffect(()=>{g()},[c,o,g]),Q.useEffect(()=>{if(!n)return;const v=window.matchMedia("(prefers-color-scheme: dark)"),y=()=>{(o??h.current)==="system"&&g()};return v.addEventListener("change",y),()=>v.removeEventListener("change",y)},[n,o,g]),Q.useEffect(()=>{const v=y=>{if(y.key===t&&y.newValue){const b=y.newValue;Qn.includes(b)&&l(b)}};return window.addEventListener("storage",v),()=>window.removeEventListener("storage",v)},[t]);const m=Q.useCallback(v=>{!n&&v==="system"||(localStorage.setItem(t,v),l(v))},[t,n]),p=Q.useMemo(()=>n?Qn:["light","dark"],[n]),x=Q.useMemo(()=>({theme:o??c,resolvedTheme:d,setTheme:m,themes:p}),[o,c,d,m,p]);return f.jsx(eu.Provider,{value:x,children:r})}function Bn(){const r=Q.useContext(eu);if(r===void 0)throw new Error("useTheme must be used within a <ThemeProvider>");return r}const Jp=({theme:r,...e})=>{let t=r;try{const{resolvedTheme:s}=Bn();r||(t=s)}catch{t||(t="system")}return f.jsx(Yp,{theme:t,className:"toaster group",toastOptions:{classNames:{toast:"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground"}},...e})};function e0({icon:r,title:e,description:t,action:s,className:n}){return f.jsxs("div",{className:I("flex flex-col items-center justify-center py-12 px-4 text-center",n),children:[r&&f.jsx("div",{className:"mb-4 text-muted-foreground",children:r}),f.jsx("h3",{className:"text-lg font-semibold",children:e}),t&&f.jsx("p",{className:"mt-1 text-sm text-muted-foreground max-w-sm",children:t}),s&&f.jsx("div",{className:"mt-4",children:s})]})}const tu=E.forwardRef(({...r},e)=>f.jsx("nav",{ref:e,"aria-label":"breadcrumb",...r}));tu.displayName="Breadcrumb";const su=E.forwardRef(({className:r,...e},t)=>f.jsx("ol",{ref:t,className:I("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",r),...e}));su.displayName="BreadcrumbList";const ru=E.forwardRef(({className:r,...e},t)=>f.jsx("li",{ref:t,className:I("inline-flex items-center gap-1.5",r),...e}));ru.displayName="BreadcrumbItem";const nu=E.forwardRef(({asChild:r,className:e,...t},s)=>{const n=r?lc.Slot:"a";return f.jsx(n,{ref:s,className:I("transition-colors hover:text-foreground",e),...t})});nu.displayName="BreadcrumbLink";const iu=E.forwardRef(({className:r,...e},t)=>f.jsx("span",{ref:t,role:"link","aria-disabled":"true","aria-current":"page",className:I("font-normal text-foreground",r),...e}));iu.displayName="BreadcrumbPage";const ou=({children:r,className:e,...t})=>f.jsx("li",{role:"presentation","aria-hidden":"true",className:I("[&>svg]:w-3.5 [&>svg]:h-3.5",e),...t,children:r??f.jsx(W.ChevronRight,{})});ou.displayName="BreadcrumbSeparator";const au=({className:r,...e})=>{const t=ye();return f.jsxs("span",{role:"presentation","aria-hidden":"true",className:I("flex h-9 w-9 items-center justify-center",r),...e,children:[f.jsx("span",{className:"h-4 w-4",children:"..."}),f.jsx("span",{className:"sr-only",children:t.breadcrumb_more})]})};au.displayName="BreadcrumbEllipsis";const lu=({className:r,...e})=>f.jsx("nav",{role:"navigation","aria-label":"pagination",className:I("mx-auto flex w-full justify-center",r),...e});lu.displayName="Pagination";const cu=E.forwardRef(({className:r,...e},t)=>f.jsx("ul",{ref:t,className:I("flex flex-row items-center gap-1",r),...e}));cu.displayName="PaginationContent";const du=E.forwardRef(({className:r,...e},t)=>f.jsx("li",{ref:t,className:I("",r),...e}));du.displayName="PaginationItem";const $n=({className:r,isActive:e,size:t="icon",...s})=>f.jsx("a",{"aria-current":e?"page":void 0,className:I(jr({variant:e?"outline":"ghost",size:t}),r),...s});$n.displayName="PaginationLink";const uu=({className:r,...e})=>{const t=ye();return f.jsxs($n,{"aria-label":t.pagination_goToPrevious,size:"default",className:I("gap-1 pl-2.5",r),...e,children:[f.jsx(W.ChevronLeft,{className:"h-4 w-4"}),f.jsx("span",{children:t.pagination_previous})]})};uu.displayName="PaginationPrevious";const fu=({className:r,...e})=>{const t=ye();return f.jsxs($n,{"aria-label":t.pagination_goToNext,size:"default",className:I("gap-1 pr-2.5",r),...e,children:[f.jsx("span",{children:t.pagination_next}),f.jsx(W.ChevronRight,{className:"h-4 w-4"})]})};fu.displayName="PaginationNext";const hu=({className:r,...e})=>{const t=ye();return f.jsxs("span",{"aria-hidden":!0,className:I("flex h-9 w-9 items-center justify-center",r),...e,children:[f.jsx(W.MoreHorizontal,{className:"h-4 w-4"}),f.jsx("span",{className:"sr-only",children:t.pagination_morePages})]})};hu.displayName="PaginationEllipsis";function t0({steps:r,activeStep:e,orientation:t="horizontal",className:s}){return f.jsx("div",{className:I("flex",t==="vertical"?"flex-col":"flex-row items-center",s),children:r.map((n,i)=>{const o=i<e,a=i===e,c=i===r.length-1;return f.jsxs(E.Fragment,{children:[f.jsxs("div",{className:I("flex items-center",t==="vertical"&&"flex-row"),children:[f.jsx("div",{className:I("flex h-10 w-10 items-center justify-center rounded-full border-2 font-semibold transition-colors",o&&"border-primary bg-primary text-primary-foreground",a&&"border-primary text-primary",!o&&!a&&"border-muted-foreground/30 text-muted-foreground"),children:o?f.jsx(W.Check,{className:"h-5 w-5"}):i+1}),f.jsxs("div",{className:I("ml-3",t==="horizontal"&&"hidden sm:block"),children:[f.jsx("p",{className:I("text-sm font-medium",a&&"text-foreground",!a&&"text-muted-foreground"),children:n.title}),n.description&&f.jsx("p",{className:"text-xs text-muted-foreground",children:n.description})]})]}),!c&&f.jsx("div",{className:I("flex-1",t==="horizontal"?"mx-4 h-0.5 min-w-[3rem]":"ml-5 my-2 w-0.5 min-h-[2rem]",o?"bg-primary":"bg-muted-foreground/30")})]},i)})})}const gu=E.forwardRef(({className:r,children:e,...t},s)=>f.jsxs(Et.Root,{ref:s,className:I("relative z-10 flex max-w-max flex-1 items-center justify-center",r),...t,children:[e,f.jsx(Oo,{})]}));gu.displayName=Et.Root.displayName;const mu=E.forwardRef(({className:r,...e},t)=>f.jsx(Et.List,{ref:t,className:I("group flex flex-1 list-none items-center justify-center space-x-1",r),...e}));mu.displayName=Et.List.displayName;const s0=Et.Item,pu=ft("group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50"),xu=E.forwardRef(({className:r,children:e,...t},s)=>f.jsxs(Et.Trigger,{ref:s,className:I(pu(),"group",r),...t,children:[e," ",f.jsx(W.ChevronDown,{className:"relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180","aria-hidden":"true"})]}));xu.displayName=Et.Trigger.displayName;const vu=E.forwardRef(({className:r,...e},t)=>f.jsx(Et.Content,{ref:t,className:I("left-0 top-0 w-full data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 md:absolute md:w-auto",r),...e}));vu.displayName=Et.Content.displayName;const r0=Et.Link,Oo=E.forwardRef(({className:r,...e},t)=>f.jsx("div",{className:I("absolute left-0 top-full flex justify-center"),children:f.jsx(Et.Viewport,{className:I("origin-top-center relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 md:w-[var(--radix-navigation-menu-viewport-width)]",r),ref:t,...e})}));Oo.displayName=Et.Viewport.displayName;const yu=E.forwardRef(({className:r,...e},t)=>f.jsx(Et.Indicator,{ref:t,className:I("top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in",r),...e,children:f.jsx("div",{className:"relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md"})}));yu.displayName=Et.Indicator.displayName;const n0=je.Root,i0=je.Trigger,o0=je.Group,a0=je.Portal,l0=je.Sub,c0=je.RadioGroup,bu=E.forwardRef(({className:r,inset:e,children:t,...s},n)=>f.jsxs(je.SubTrigger,{ref:n,className:I("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",e&&"pl-8",r),...s,children:[t,f.jsx(W.ChevronRight,{className:"ml-auto h-4 w-4"})]}));bu.displayName=je.SubTrigger.displayName;const Su=E.forwardRef(({className:r,...e},t)=>f.jsx(je.SubContent,{ref:t,className:I("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",r),...e}));Su.displayName=je.SubContent.displayName;const Eu=E.forwardRef(({className:r,...e},t)=>f.jsx(je.Portal,{children:f.jsx(je.Content,{ref:t,className:I("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",r),...e})}));Eu.displayName=je.Content.displayName;const Tu=E.forwardRef(({className:r,inset:e,...t},s)=>f.jsx(je.Item,{ref:s,className:I("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e&&"pl-8",r),...t}));Tu.displayName=je.Item.displayName;const wu=E.forwardRef(({className:r,children:e,checked:t,...s},n)=>f.jsxs(je.CheckboxItem,{ref:n,className:I("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",r),checked:t,...s,children:[f.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:f.jsx(je.ItemIndicator,{children:f.jsx(W.Check,{className:"h-4 w-4"})})}),e]}));wu.displayName=je.CheckboxItem.displayName;const Ru=E.forwardRef(({className:r,children:e,...t},s)=>f.jsxs(je.RadioItem,{ref:s,className:I("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",r),...t,children:[f.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:f.jsx(je.ItemIndicator,{children:f.jsx(W.Circle,{className:"h-2 w-2 fill-current"})})}),e]}));Ru.displayName=je.RadioItem.displayName;const Au=E.forwardRef(({className:r,inset:e,...t},s)=>f.jsx(je.Label,{ref:s,className:I("px-2 py-1.5 text-sm font-semibold text-foreground",e&&"pl-8",r),...t}));Au.displayName=je.Label.displayName;const Iu=E.forwardRef(({className:r,...e},t)=>f.jsx(je.Separator,{ref:t,className:I("-mx-1 my-1 h-px bg-border",r),...e}));Iu.displayName=je.Separator.displayName;const Lu=({className:r,...e})=>f.jsx("span",{className:I("ml-auto text-xs tracking-widest text-muted-foreground",r),...e});Lu.displayName="ContextMenuShortcut";const d0=Fn.Root,u0=Fn.Trigger,Cu=E.forwardRef(({className:r,align:e="center",sideOffset:t=4,...s},n)=>f.jsx(Fn.Content,{ref:n,align:e,sideOffset:t,className:I("z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",r),...s}));Cu.displayName=Fn.Content.displayName;function f0(r){return Object.prototype.toString.call(r)==="[object Object]"}function Da(r){return f0(r)||Array.isArray(r)}function h0(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}function jo(r,e){const t=Object.keys(r),s=Object.keys(e);if(t.length!==s.length)return!1;const n=JSON.stringify(Object.keys(r.breakpoints||{})),i=JSON.stringify(Object.keys(e.breakpoints||{}));return n!==i?!1:t.every(o=>{const a=r[o],c=e[o];return typeof a=="function"?`${a}`==`${c}`:!Da(a)||!Da(c)?a===c:jo(a,c)})}function Pa(r){return r.concat().sort((e,t)=>e.name>t.name?1:-1).map(e=>e.options)}function g0(r,e){if(r.length!==e.length)return!1;const t=Pa(r),s=Pa(e);return t.every((n,i)=>{const o=s[i];return jo(n,o)})}function Bo(r){return typeof r=="number"}function Mi(r){return typeof r=="string"}function Un(r){return typeof r=="boolean"}function Na(r){return Object.prototype.toString.call(r)==="[object Object]"}function Ke(r){return Math.abs(r)}function $o(r){return Math.sign(r)}function yr(r,e){return Ke(r-e)}function m0(r,e){if(r===0||e===0||Ke(r)<=Ke(e))return 0;const t=yr(Ke(r),Ke(e));return Ke(t/r)}function p0(r){return Math.round(r*100)/100}function Ir(r){return Lr(r).map(Number)}function zt(r){return r[Br(r)]}function Br(r){return Math.max(0,r.length-1)}function Uo(r,e){return e===Br(r)}function Ma(r,e=0){return Array.from(Array(r),(t,s)=>e+s)}function Lr(r){return Object.keys(r)}function _u(r,e){return[r,e].reduce((t,s)=>(Lr(s).forEach(n=>{const i=t[n],o=s[n],a=Na(i)&&Na(o);t[n]=a?_u(i,o):o}),t),{})}function Fi(r,e){return typeof e.MouseEvent<"u"&&r instanceof e.MouseEvent}function x0(r,e){const t={start:s,center:n,end:i};function s(){return 0}function n(c){return i(c)/2}function i(c){return e-c}function o(c,l){return Mi(r)?t[r](c):r(e,c,l)}return{measure:o}}function Cr(){let r=[];function e(n,i,o,a={passive:!0}){let c;if("addEventListener"in n)n.addEventListener(i,o,a),c=()=>n.removeEventListener(i,o,a);else{const l=n;l.addListener(o),c=()=>l.removeListener(o)}return r.push(c),s}function t(){r=r.filter(n=>n())}const s={add:e,clear:t};return s}function v0(r,e,t,s){const n=Cr(),i=1e3/60;let o=null,a=0,c=0;function l(){n.add(r,"visibilitychange",()=>{r.hidden&&m()})}function d(){g(),n.clear()}function u(x){if(!c)return;o||(o=x,t(),t());const v=x-o;for(o=x,a+=v;a>=i;)t(),a-=i;const y=a/i;s(y),c&&(c=e.requestAnimationFrame(u))}function h(){c||(c=e.requestAnimationFrame(u))}function g(){e.cancelAnimationFrame(c),o=null,a=0,c=0}function m(){o=null,a=0}return{init:l,destroy:d,start:h,stop:g,update:t,render:s}}function y0(r,e){const t=e==="rtl",s=r==="y",n=s?"y":"x",i=s?"x":"y",o=!s&&t?-1:1,a=d(),c=u();function l(m){const{height:p,width:x}=m;return s?p:x}function d(){return s?"top":t?"right":"left"}function u(){return s?"bottom":t?"left":"right"}function h(m){return m*o}return{scroll:n,cross:i,startEdge:a,endEdge:c,measureSize:l,direction:h}}function Fs(r=0,e=0){const t=Ke(r-e);function s(l){return l<r}function n(l){return l>e}function i(l){return s(l)||n(l)}function o(l){return i(l)?s(l)?r:e:l}function a(l){return t?l-t*Math.ceil((l-e)/t):l}return{length:t,max:e,min:r,constrain:o,reachedAny:i,reachedMax:n,reachedMin:s,removeOffset:a}}function ku(r,e,t){const{constrain:s}=Fs(0,r),n=r+1;let i=o(e);function o(h){return t?Ke((n+h)%n):s(h)}function a(){return i}function c(h){return i=o(h),u}function l(h){return d().set(a()+h)}function d(){return ku(r,a(),t)}const u={get:a,set:c,add:l,clone:d};return u}function b0(r,e,t,s,n,i,o,a,c,l,d,u,h,g,m,p,x,v,y){const{cross:b,direction:T}=r,R=["INPUT","SELECT","TEXTAREA"],_={passive:!1},w=Cr(),A=Cr(),C=Fs(50,225).constrain(g.measure(20)),L={mouse:300,touch:400},P={mouse:500,touch:600},M=m?43:25;let j=!1,D=0,$=0,N=!1,F=!1,k=!1,z=!1;function Y(re){if(!y)return;function Z(Re){(Un(y)||y(re,Re))&&J(Re)}const fe=e;w.add(fe,"dragstart",Re=>Re.preventDefault(),_).add(fe,"touchmove",()=>{},_).add(fe,"touchend",()=>{}).add(fe,"touchstart",Z).add(fe,"mousedown",Z).add(fe,"touchcancel",te).add(fe,"contextmenu",te).add(fe,"click",de,!0)}function U(){w.clear(),A.clear()}function K(){const re=z?t:e;A.add(re,"touchmove",ee,_).add(re,"touchend",te).add(re,"mousemove",ee,_).add(re,"mouseup",te)}function G(re){const Z=re.nodeName||"";return R.includes(Z)}function H(){return(m?P:L)[z?"mouse":"touch"]}function q(re,Z){const fe=u.add($o(re)*-1),Re=d.byDistance(re,!m).distance;return m||Ke(re)<C?Re:x&&Z?Re*.5:d.byIndex(fe.get(),0).distance}function J(re){const Z=Fi(re,s);z=Z,k=m&&Z&&!re.buttons&&j,j=yr(n.get(),o.get())>=2,!(Z&&re.button!==0)&&(G(re.target)||(N=!0,i.pointerDown(re),l.useFriction(0).useDuration(0),n.set(o),K(),D=i.readPoint(re),$=i.readPoint(re,b),h.emit("pointerDown")))}function ee(re){if(!Fi(re,s)&&re.touches.length>=2)return te(re);const fe=i.readPoint(re),Re=i.readPoint(re,b),he=yr(fe,D),be=yr(Re,$);if(!F&&!z&&(!re.cancelable||(F=he>be,!F)))return te(re);const Ae=i.pointerMove(re);he>p&&(k=!0),l.useFriction(.3).useDuration(.75),a.start(),n.add(T(Ae)),re.preventDefault()}function te(re){const fe=d.byDistance(0,!1).index!==u.get(),Re=i.pointerUp(re)*H(),he=q(T(Re),fe),be=m0(Re,he),Ae=M-10*be,Ie=v+be/50;F=!1,N=!1,A.clear(),l.useDuration(Ae).useFriction(Ie),c.distance(he,!m),z=!1,h.emit("pointerUp")}function de(re){k&&(re.stopPropagation(),re.preventDefault(),k=!1)}function ie(){return N}return{init:Y,destroy:U,pointerDown:ie}}function S0(r,e){let s,n;function i(u){return u.timeStamp}function o(u,h){const m=`client${(h||r.scroll)==="x"?"X":"Y"}`;return(Fi(u,e)?u:u.touches[0])[m]}function a(u){return s=u,n=u,o(u)}function c(u){const h=o(u)-o(n),g=i(u)-i(s)>170;return n=u,g&&(s=u),h}function l(u){if(!s||!n)return 0;const h=o(n)-o(s),g=i(u)-i(s),m=i(u)-i(n)>170,p=h/g;return g&&!m&&Ke(p)>.1?p:0}return{pointerDown:a,pointerMove:c,pointerUp:l,readPoint:o}}function E0(){function r(t){const{offsetTop:s,offsetLeft:n,offsetWidth:i,offsetHeight:o}=t;return{top:s,right:n+i,bottom:s+o,left:n,width:i,height:o}}return{measure:r}}function T0(r){function e(s){return r*(s/100)}return{measure:e}}function w0(r,e,t,s,n,i,o){const a=[r].concat(s);let c,l,d=[],u=!1;function h(x){return n.measureSize(o.measure(x))}function g(x){if(!i)return;l=h(r),d=s.map(h);function v(y){for(const b of y){if(u)return;const T=b.target===r,R=s.indexOf(b.target),_=T?l:d[R],w=h(T?r:s[R]);if(Ke(w-_)>=.5){x.reInit(),e.emit("resize");break}}}c=new ResizeObserver(y=>{(Un(i)||i(x,y))&&v(y)}),t.requestAnimationFrame(()=>{a.forEach(y=>c.observe(y))})}function m(){u=!0,c&&c.disconnect()}return{init:g,destroy:m}}function R0(r,e,t,s,n,i){let o=0,a=0,c=n,l=i,d=r.get(),u=0;function h(){const _=s.get()-r.get(),w=!c;let A=0;return w?(o=0,t.set(s),r.set(s),A=_):(t.set(r),o+=_/c,o*=l,d+=o,r.add(o),A=d-u),a=$o(A),u=d,R}function g(){const _=s.get()-e.get();return Ke(_)<.001}function m(){return c}function p(){return a}function x(){return o}function v(){return b(n)}function y(){return T(i)}function b(_){return c=_,R}function T(_){return l=_,R}const R={direction:p,duration:m,velocity:x,seek:h,settled:g,useBaseFriction:y,useBaseDuration:v,useFriction:T,useDuration:b};return R}function A0(r,e,t,s,n){const i=n.measure(10),o=n.measure(50),a=Fs(.1,.99);let c=!1;function l(){return!(c||!r.reachedAny(t.get())||!r.reachedAny(e.get()))}function d(g){if(!l())return;const m=r.reachedMin(e.get())?"min":"max",p=Ke(r[m]-e.get()),x=t.get()-e.get(),v=a.constrain(p/o);t.subtract(x*v),!g&&Ke(x)<i&&(t.set(r.constrain(t.get())),s.useDuration(25).useBaseFriction())}function u(g){c=!g}return{shouldConstrain:l,constrain:d,toggleActive:u}}function I0(r,e,t,s,n){const i=Fs(-e+r,0),o=u(),a=d(),c=h();function l(m,p){return yr(m,p)<=1}function d(){const m=o[0],p=zt(o),x=o.lastIndexOf(m),v=o.indexOf(p)+1;return Fs(x,v)}function u(){return t.map((m,p)=>{const{min:x,max:v}=i,y=i.constrain(m),b=!p,T=Uo(t,p);return b?v:T||l(x,y)?x:l(v,y)?v:y}).map(m=>parseFloat(m.toFixed(3)))}function h(){if(e<=r+n)return[i.max];if(s==="keepSnaps")return o;const{min:m,max:p}=a;return o.slice(m,p)}return{snapsContained:c,scrollContainLimit:a}}function L0(r,e,t){const s=e[0],n=t?s-r:zt(e);return{limit:Fs(n,s)}}function C0(r,e,t,s){const i=e.min+.1,o=e.max+.1,{reachedMin:a,reachedMax:c}=Fs(i,o);function l(h){return h===1?c(t.get()):h===-1?a(t.get()):!1}function d(h){if(!l(h))return;const g=r*(h*-1);s.forEach(m=>m.add(g))}return{loop:d}}function _0(r){const{max:e,length:t}=r;function s(i){const o=i-e;return t?o/-t:0}return{get:s}}function k0(r,e,t,s,n){const{startEdge:i,endEdge:o}=r,{groupSlides:a}=n,c=u().map(e.measure),l=h(),d=g();function u(){return a(s).map(p=>zt(p)[o]-p[0][i]).map(Ke)}function h(){return s.map(p=>t[i]-p[i]).map(p=>-Ke(p))}function g(){return a(l).map(p=>p[0]).map((p,x)=>p+c[x])}return{snaps:l,snapsAligned:d}}function D0(r,e,t,s,n,i){const{groupSlides:o}=n,{min:a,max:c}=s,l=d();function d(){const h=o(i),g=!r||e==="keepSnaps";return t.length===1?[i]:g?h:h.slice(a,c).map((m,p,x)=>{const v=!p,y=Uo(x,p);if(v){const b=zt(x[0])+1;return Ma(b)}if(y){const b=Br(i)-zt(x)[0]+1;return Ma(b,zt(x)[0])}return m})}return{slideRegistry:l}}function P0(r,e,t,s,n){const{reachedAny:i,removeOffset:o,constrain:a}=s;function c(m){return m.concat().sort((p,x)=>Ke(p)-Ke(x))[0]}function l(m){const p=r?o(m):a(m),x=e.map((y,b)=>({diff:d(y-p,0),index:b})).sort((y,b)=>Ke(y.diff)-Ke(b.diff)),{index:v}=x[0];return{index:v,distance:p}}function d(m,p){const x=[m,m+t,m-t];if(!r)return m;if(!p)return c(x);const v=x.filter(y=>$o(y)===p);return v.length?c(v):zt(x)-t}function u(m,p){const x=e[m]-n.get(),v=d(x,p);return{index:m,distance:v}}function h(m,p){const x=n.get()+m,{index:v,distance:y}=l(x),b=!r&&i(x);if(!p||b)return{index:v,distance:m};const T=e[v]-y,R=m+d(T,0);return{index:v,distance:R}}return{byDistance:h,byIndex:u,shortcut:d}}function N0(r,e,t,s,n,i,o){function a(u){const h=u.distance,g=u.index!==e.get();i.add(h),h&&(s.duration()?r.start():(r.update(),r.render(1),r.update())),g&&(t.set(e.get()),e.set(u.index),o.emit("select"))}function c(u,h){const g=n.byDistance(u,h);a(g)}function l(u,h){const g=e.clone().set(u),m=n.byIndex(g.get(),h);a(m)}return{distance:c,index:l}}function M0(r,e,t,s,n,i,o,a){const c={passive:!0,capture:!0};let l=0;function d(g){if(!a)return;function m(p){if(new Date().getTime()-l>10)return;o.emit("slideFocusStart"),r.scrollLeft=0;const y=t.findIndex(b=>b.includes(p));Bo(y)&&(n.useDuration(0),s.index(y,0),o.emit("slideFocus"))}i.add(document,"keydown",u,!1),e.forEach((p,x)=>{i.add(p,"focus",v=>{(Un(a)||a(g,v))&&m(x)},c)})}function u(g){g.code==="Tab"&&(l=new Date().getTime())}return{init:d}}function mr(r){let e=r;function t(){return e}function s(c){e=o(c)}function n(c){e+=o(c)}function i(c){e-=o(c)}function o(c){return Bo(c)?c:c.get()}return{get:t,set:s,add:n,subtract:i}}function Du(r,e){const t=r.scroll==="x"?o:a,s=e.style;let n=null,i=!1;function o(h){return`translate3d(${h}px,0px,0px)`}function a(h){return`translate3d(0px,${h}px,0px)`}function c(h){if(i)return;const g=p0(r.direction(h));g!==n&&(s.transform=t(g),n=g)}function l(h){i=!h}function d(){i||(s.transform="",e.getAttribute("style")||e.removeAttribute("style"))}return{clear:d,to:c,toggleActive:l}}function F0(r,e,t,s,n,i,o,a,c){const d=Ir(n),u=Ir(n).reverse(),h=v().concat(y());function g(w,A){return w.reduce((C,L)=>C-n[L],A)}function m(w,A){return w.reduce((C,L)=>g(C,A)>0?C.concat([L]):C,[])}function p(w){return i.map((A,C)=>({start:A-s[C]+.5+w,end:A+e-.5+w}))}function x(w,A,C){const L=p(A);return w.map(P=>{const M=C?0:-t,j=C?t:0,D=C?"end":"start",$=L[P][D];return{index:P,loopPoint:$,slideLocation:mr(-1),translate:Du(r,c[P]),target:()=>a.get()>$?M:j}})}function v(){const w=o[0],A=m(u,w);return x(A,t,!1)}function y(){const w=e-o[0]-1,A=m(d,w);return x(A,-t,!0)}function b(){return h.every(({index:w})=>{const A=d.filter(C=>C!==w);return g(A,e)<=.1})}function T(){h.forEach(w=>{const{target:A,translate:C,slideLocation:L}=w,P=A();P!==L.get()&&(C.to(P),L.set(P))})}function R(){h.forEach(w=>w.translate.clear())}return{canLoop:b,clear:R,loop:T,loopPoints:h}}function O0(r,e,t){let s,n=!1;function i(c){if(!t)return;function l(d){for(const u of d)if(u.type==="childList"){c.reInit(),e.emit("slidesChanged");break}}s=new MutationObserver(d=>{n||(Un(t)||t(c,d))&&l(d)}),s.observe(r,{childList:!0})}function o(){s&&s.disconnect(),n=!0}return{init:i,destroy:o}}function j0(r,e,t,s){const n={};let i=null,o=null,a,c=!1;function l(){a=new IntersectionObserver(m=>{c||(m.forEach(p=>{const x=e.indexOf(p.target);n[x]=p}),i=null,o=null,t.emit("slidesInView"))},{root:r.parentElement,threshold:s}),e.forEach(m=>a.observe(m))}function d(){a&&a.disconnect(),c=!0}function u(m){return Lr(n).reduce((p,x)=>{const v=parseInt(x),{isIntersecting:y}=n[v];return(m&&y||!m&&!y)&&p.push(v),p},[])}function h(m=!0){if(m&&i)return i;if(!m&&o)return o;const p=u(m);return m&&(i=p),m||(o=p),p}return{init:l,destroy:d,get:h}}function B0(r,e,t,s,n,i){const{measureSize:o,startEdge:a,endEdge:c}=r,l=t[0]&&n,d=m(),u=p(),h=t.map(o),g=x();function m(){if(!l)return 0;const y=t[0];return Ke(e[a]-y[a])}function p(){if(!l)return 0;const y=i.getComputedStyle(zt(s));return parseFloat(y.getPropertyValue(`margin-${c}`))}function x(){return t.map((y,b,T)=>{const R=!b,_=Uo(T,b);return R?h[b]+d:_?h[b]+u:T[b+1][a]-y[a]}).map(Ke)}return{slideSizes:h,slideSizesWithGaps:g,startGap:d,endGap:u}}function $0(r,e,t,s,n,i,o,a,c){const{startEdge:l,endEdge:d,direction:u}=r,h=Bo(t);function g(v,y){return Ir(v).filter(b=>b%y===0).map(b=>v.slice(b,b+y))}function m(v){return v.length?Ir(v).reduce((y,b,T)=>{const R=zt(y)||0,_=R===0,w=b===Br(v),A=n[l]-i[R][l],C=n[l]-i[b][d],L=!s&&_?u(o):0,P=!s&&w?u(a):0,M=Ke(C-P-(A+L));return T&&M>e+c&&y.push(b),w&&y.push(v.length),y},[]).map((y,b,T)=>{const R=Math.max(T[b-1]||0);return v.slice(R,y)}):[]}function p(v){return h?g(v,t):m(v)}return{groupSlides:p}}function U0(r,e,t,s,n,i,o){const{align:a,axis:c,direction:l,startIndex:d,loop:u,duration:h,dragFree:g,dragThreshold:m,inViewThreshold:p,slidesToScroll:x,skipSnaps:v,containScroll:y,watchResize:b,watchSlides:T,watchDrag:R,watchFocus:_}=i,w=2,A=E0(),C=A.measure(e),L=t.map(A.measure),P=y0(c,l),M=P.measureSize(C),j=T0(M),D=x0(a,M),$=!u&&!!y,N=u||!!y,{slideSizes:F,slideSizesWithGaps:k,startGap:z,endGap:Y}=B0(P,C,L,t,N,n),U=$0(P,M,x,u,C,L,z,Y,w),{snaps:K,snapsAligned:G}=k0(P,D,C,L,U),H=-zt(K)+zt(k),{snapsContained:q,scrollContainLimit:J}=I0(M,H,G,y,w),ee=$?q:G,{limit:te}=L0(H,ee,u),de=ku(Br(ee),d,u),ie=de.clone(),ue=Ir(t),re=({dragHandler:we,scrollBody:mt,scrollBounds:Ot,options:{loop:Xe}})=>{Xe||Ot.constrain(we.pointerDown()),mt.seek()},Z=({scrollBody:we,translate:mt,location:Ot,offsetLocation:Xe,previousLocation:Rs,scrollLooper:$s,slideLooper:fs,dragHandler:As,animation:ns,eventHandler:Rt,scrollBounds:cr,options:{loop:Us}},Is)=>{const Yt=we.settled(),xe=!cr.shouldConstrain(),Ue=Us?Yt:Yt&&xe,Ye=Ue&&!As.pointerDown();Ye&&ns.stop();const nt=Ot.get()*Is+Rs.get()*(1-Is);Xe.set(nt),Us&&($s.loop(we.direction()),fs.loop()),mt.to(Xe.get()),Ye&&Rt.emit("settle"),Ue||Rt.emit("scroll")},fe=v0(s,n,()=>re(wt),we=>Z(wt,we)),Re=.68,he=ee[de.get()],be=mr(he),Ae=mr(he),Ie=mr(he),Me=mr(he),$e=R0(be,Ie,Ae,Me,h,Re),Le=P0(u,ee,H,te,Me),at=N0(fe,de,ie,$e,Le,Me,o),Ge=_0(te),Mt=Cr(),Je=j0(e,t,o,p),{slideRegistry:Tt}=D0($,y,ee,J,U,ue),Ft=M0(r,t,Tt,at,$e,Mt,o,_),wt={ownerDocument:s,ownerWindow:n,eventHandler:o,containerRect:C,slideRects:L,animation:fe,axis:P,dragHandler:b0(P,r,s,n,Me,S0(P,n),be,fe,at,$e,Le,de,o,j,g,m,v,Re,R),eventStore:Mt,percentOfView:j,index:de,indexPrevious:ie,limit:te,location:be,offsetLocation:Ie,previousLocation:Ae,options:i,resizeHandler:w0(e,o,n,t,P,b,A),scrollBody:$e,scrollBounds:A0(te,Ie,Me,$e,j),scrollLooper:C0(H,te,Ie,[be,Ie,Ae,Me]),scrollProgress:Ge,scrollSnapList:ee.map(Ge.get),scrollSnaps:ee,scrollTarget:Le,scrollTo:at,slideLooper:F0(P,M,H,F,k,K,ee,Ie,t),slideFocus:Ft,slidesHandler:O0(e,o,T),slidesInView:Je,slideIndexes:ue,slideRegistry:Tt,slidesToScroll:U,target:Me,translate:Du(P,e)};return wt}function G0(){let r={},e;function t(l){e=l}function s(l){return r[l]||[]}function n(l){return s(l).forEach(d=>d(e,l)),c}function i(l,d){return r[l]=s(l).concat([d]),c}function o(l,d){return r[l]=s(l).filter(u=>u!==d),c}function a(){r={}}const c={init:t,emit:n,off:o,on:i,clear:a};return c}const V0={align:"center",axis:"x",container:null,slides:null,containScroll:"trimSnaps",direction:"ltr",slidesToScroll:1,inViewThreshold:0,breakpoints:{},dragFree:!1,dragThreshold:10,loop:!1,skipSnaps:!1,duration:25,startIndex:0,active:!0,watchDrag:!0,watchResize:!0,watchSlides:!0,watchFocus:!0};function H0(r){function e(i,o){return _u(i,o||{})}function t(i){const o=i.breakpoints||{},a=Lr(o).filter(c=>r.matchMedia(c).matches).map(c=>o[c]).reduce((c,l)=>e(c,l),{});return e(i,a)}function s(i){return i.map(o=>Lr(o.breakpoints||{})).reduce((o,a)=>o.concat(a),[]).map(r.matchMedia)}return{mergeOptions:e,optionsAtMedia:t,optionsMediaQueries:s}}function K0(r){let e=[];function t(i,o){return e=o.filter(({options:a})=>r.optionsAtMedia(a).active!==!1),e.forEach(a=>a.init(i,r)),o.reduce((a,c)=>Object.assign(a,{[c.name]:c}),{})}function s(){e=e.filter(i=>i.destroy())}return{init:t,destroy:s}}function Tn(r,e,t){const s=r.ownerDocument,n=s.defaultView,i=H0(n),o=K0(i),a=Cr(),c=G0(),{mergeOptions:l,optionsAtMedia:d,optionsMediaQueries:u}=i,{on:h,off:g,emit:m}=c,p=P;let x=!1,v,y=l(V0,Tn.globalOptions),b=l(y),T=[],R,_,w;function A(){const{container:ue,slides:re}=b;_=(Mi(ue)?r.querySelector(ue):ue)||r.children[0];const fe=Mi(re)?_.querySelectorAll(re):re;w=[].slice.call(fe||_.children)}function C(ue){const re=U0(r,_,w,s,n,ue,c);if(ue.loop&&!re.slideLooper.canLoop()){const Z=Object.assign({},ue,{loop:!1});return C(Z)}return re}function L(ue,re){x||(y=l(y,ue),b=d(y),T=re||T,A(),v=C(b),u([y,...T.map(({options:Z})=>Z)]).forEach(Z=>a.add(Z,"change",P)),b.active&&(v.translate.to(v.location.get()),v.animation.init(),v.slidesInView.init(),v.slideFocus.init(ie),v.eventHandler.init(ie),v.resizeHandler.init(ie),v.slidesHandler.init(ie),v.options.loop&&v.slideLooper.loop(),_.offsetParent&&w.length&&v.dragHandler.init(ie),R=o.init(ie,T)))}function P(ue,re){const Z=U();M(),L(l({startIndex:Z},ue),re),c.emit("reInit")}function M(){v.dragHandler.destroy(),v.eventStore.clear(),v.translate.clear(),v.slideLooper.clear(),v.resizeHandler.destroy(),v.slidesHandler.destroy(),v.slidesInView.destroy(),v.animation.destroy(),o.destroy(),a.clear()}function j(){x||(x=!0,a.clear(),M(),c.emit("destroy"),c.clear())}function D(ue,re,Z){!b.active||x||(v.scrollBody.useBaseFriction().useDuration(re===!0?0:b.duration),v.scrollTo.index(ue,Z||0))}function $(ue){const re=v.index.add(1).get();D(re,ue,-1)}function N(ue){const re=v.index.add(-1).get();D(re,ue,1)}function F(){return v.index.add(1).get()!==U()}function k(){return v.index.add(-1).get()!==U()}function z(){return v.scrollSnapList}function Y(){return v.scrollProgress.get(v.offsetLocation.get())}function U(){return v.index.get()}function K(){return v.indexPrevious.get()}function G(){return v.slidesInView.get()}function H(){return v.slidesInView.get(!1)}function q(){return R}function J(){return v}function ee(){return r}function te(){return _}function de(){return w}const ie={canScrollNext:F,canScrollPrev:k,containerNode:te,internalEngine:J,destroy:j,off:g,on:h,emit:m,plugins:q,previousScrollSnap:K,reInit:p,rootNode:ee,scrollNext:$,scrollPrev:N,scrollProgress:Y,scrollSnapList:z,scrollTo:D,selectedScrollSnap:U,slideNodes:de,slidesInView:G,slidesNotInView:H};return L(e,t),setTimeout(()=>c.emit("init"),0),ie}Tn.globalOptions=void 0;function Go(r={},e=[]){const t=Q.useRef(r),s=Q.useRef(e),[n,i]=Q.useState(),[o,a]=Q.useState(),c=Q.useCallback(()=>{n&&n.reInit(t.current,s.current)},[n]);return Q.useEffect(()=>{jo(t.current,r)||(t.current=r,c())},[r,c]),Q.useEffect(()=>{g0(s.current,e)||(s.current=e,c())},[e,c]),Q.useEffect(()=>{if(h0()&&o){Tn.globalOptions=Go.globalOptions;const l=Tn(o,t.current,s.current);return i(l),()=>l.destroy()}else i(void 0)},[o,i]),[a,n]}Go.globalOptions=void 0;const Pu=E.createContext(null);function Gn(){const r=E.useContext(Pu);if(!r)throw new Error("useCarousel must be used within a <Carousel />");return r}const Nu=E.forwardRef(({orientation:r="horizontal",opts:e,setApi:t,plugins:s,className:n,children:i,...o},a)=>{const[c,l]=Go({...e,axis:r==="horizontal"?"x":"y"},s),[d,u]=E.useState(!1),[h,g]=E.useState(!1),m=E.useCallback(y=>{y&&(u(y.canScrollPrev()),g(y.canScrollNext()))},[]),p=E.useCallback(()=>{l==null||l.scrollPrev()},[l]),x=E.useCallback(()=>{l==null||l.scrollNext()},[l]),v=E.useCallback(y=>{y.key==="ArrowLeft"?(y.preventDefault(),p()):y.key==="ArrowRight"&&(y.preventDefault(),x())},[p,x]);return E.useEffect(()=>{!l||!t||t(l)},[l,t]),E.useEffect(()=>{if(l)return m(l),l.on("reInit",m),l.on("select",m),()=>{l==null||l.off("select",m)}},[l,m]),f.jsx(Pu.Provider,{value:{carouselRef:c,api:l,opts:e,orientation:r,scrollPrev:p,scrollNext:x,canScrollPrev:d,canScrollNext:h},children:f.jsx("div",{ref:a,onKeyDownCapture:v,className:I("relative",n),role:"region","aria-roledescription":"carousel",...o,children:i})})});Nu.displayName="Carousel";const Mu=E.forwardRef(({className:r,...e},t)=>{const{carouselRef:s,orientation:n}=Gn();return f.jsx("div",{ref:s,className:"overflow-hidden",children:f.jsx("div",{ref:t,className:I("flex",n==="horizontal"?"-ml-4":"-mt-4 flex-col",r),...e})})});Mu.displayName="CarouselContent";const Fu=E.forwardRef(({className:r,...e},t)=>{const{orientation:s}=Gn();return f.jsx("div",{ref:t,role:"group","aria-roledescription":"slide",className:I("min-w-0 shrink-0 grow-0 basis-full",s==="horizontal"?"pl-4":"pt-4",r),...e})});Fu.displayName="CarouselItem";const Ou=E.forwardRef(({className:r,variant:e="outline",size:t="icon",...s},n)=>{const{orientation:i,scrollPrev:o,canScrollPrev:a}=Gn(),c=ye();return f.jsxs(Ze,{ref:n,variant:e,size:t,className:I("absolute h-8 w-8 rounded-full",i==="horizontal"?"-left-12 top-1/2 -translate-y-1/2":"-top-12 left-1/2 -translate-x-1/2 rotate-90",r),disabled:!a,onClick:o,...s,children:[f.jsx(W.ChevronLeft,{className:"h-4 w-4"}),f.jsx("span",{className:"sr-only",children:c.carousel_previousSlide})]})});Ou.displayName="CarouselPrevious";const ju=E.forwardRef(({className:r,variant:e="outline",size:t="icon",...s},n)=>{const{orientation:i,scrollNext:o,canScrollNext:a}=Gn(),c=ye();return f.jsxs(Ze,{ref:n,variant:e,size:t,className:I("absolute h-8 w-8 rounded-full",i==="horizontal"?"-right-12 top-1/2 -translate-y-1/2":"-bottom-12 left-1/2 -translate-x-1/2 rotate-90",r),disabled:!a,onClick:o,...s,children:[f.jsx(W.ChevronRight,{className:"h-4 w-4"}),f.jsx("span",{className:"sr-only",children:c.carousel_nextSlide})]})});ju.displayName="CarouselNext";/**
13
13
  * table-core
14
14
  *
15
15
  * Copyright (c) TanStack
@@ -18,10 +18,10 @@
18
18
  * LICENSE.md file in the root directory of this source tree.
19
19
  *
20
20
  * @license MIT
21
- */function dt(e,t){return typeof e=="function"?e(t):e}function Oe(e,t){return r=>{t.setState(o=>({...o,[e]:dt(r,o[e])}))}}function vr(e){return e instanceof Function}function cu(e){return Array.isArray(e)&&e.every(t=>typeof t=="number")}function du(e,t){const r=[],o=s=>{s.forEach(a=>{r.push(a);const i=t(a);i!=null&&i.length&&o(i)})};return o(e),r}function oe(e,t,r){let o=[],s;return a=>{let i;r.key&&r.debug&&(i=Date.now());const l=e(a);if(!(l.length!==o.length||l.some((p,u)=>o[u]!==p)))return s;o=l;let c;if(r.key&&r.debug&&(c=Date.now()),s=t(...l),r==null||r.onChange==null||r.onChange(s),r.key&&r.debug&&r!=null&&r.debug()){const p=Math.round((Date.now()-i)*100)/100,u=Math.round((Date.now()-c)*100)/100,m=u/16,g=(h,x)=>{for(h=String(h);h.length<x;)h=" "+h;return h};console.info(`%c⏱ ${g(u,5)} /${g(p,5)} ms`,`
21
+ */function ys(r,e){return typeof r=="function"?r(e):r}function Nt(r,e){return t=>{e.setState(s=>({...s,[r]:ys(t,s[r])}))}}function Vn(r){return r instanceof Function}function z0(r){return Array.isArray(r)&&r.every(e=>typeof e=="number")}function W0(r,e){const t=[],s=n=>{n.forEach(i=>{t.push(i);const o=e(i);o!=null&&o.length&&s(o)})};return s(r),t}function ge(r,e,t){let s=[],n;return i=>{let o;t.key&&t.debug&&(o=Date.now());const a=r(i);if(!(a.length!==s.length||a.some((d,u)=>s[u]!==d)))return n;s=a;let l;if(t.key&&t.debug&&(l=Date.now()),n=e(...a),t==null||t.onChange==null||t.onChange(n),t.key&&t.debug&&t!=null&&t.debug()){const d=Math.round((Date.now()-o)*100)/100,u=Math.round((Date.now()-l)*100)/100,h=u/16,g=(m,p)=>{for(m=String(m);m.length<p;)m=" "+m;return m};console.info(`%c⏱ ${g(u,5)} /${g(d,5)} ms`,`
22
22
  font-size: .6rem;
23
23
  font-weight: bold;
24
- color: hsl(${Math.max(0,Math.min(120-120*m,120))}deg 100% 31%);`,r==null?void 0:r.key)}return s}}function se(e,t,r,o){return{debug:()=>{var s;return(s=e==null?void 0:e.debugAll)!=null?s:e[t]},key:process.env.NODE_ENV==="development"&&r,onChange:o}}function uu(e,t,r,o){const s=()=>{var i;return(i=a.getValue())!=null?i:e.options.renderFallbackValue},a={id:`${t.id}_${r.id}`,row:t,column:r,getValue:()=>t.getValue(o),renderValue:s,getContext:oe(()=>[e,r,t,a],(i,l,d,c)=>({table:i,column:l,row:d,cell:c,getValue:c.getValue,renderValue:c.renderValue}),se(e.options,"debugCells","cell.getContext"))};return e._features.forEach(i=>{i.createCell==null||i.createCell(a,r,t,e)},{}),a}function mu(e,t,r,o){var s,a;const l={...e._getDefaultColumnDef(),...t},d=l.accessorKey;let c=(s=(a=l.id)!=null?a:d?typeof String.prototype.replaceAll=="function"?d.replaceAll(".","_"):d.replace(/\./g,"_"):void 0)!=null?s:typeof l.header=="string"?l.header:void 0,p;if(l.accessorFn?p=l.accessorFn:d&&(d.includes(".")?p=m=>{let g=m;for(const x of d.split(".")){var h;g=(h=g)==null?void 0:h[x],process.env.NODE_ENV!=="production"&&g===void 0&&console.warn(`"${x}" in deeply nested key "${d}" returned undefined.`)}return g}:p=m=>m[l.accessorKey]),!c)throw process.env.NODE_ENV!=="production"?new Error(l.accessorFn?"Columns require an id when using an accessorFn":"Columns require an id when using a non-string header"):new Error;let u={id:`${String(c)}`,accessorFn:p,parent:o,depth:r,columnDef:l,columns:[],getFlatColumns:oe(()=>[!0],()=>{var m;return[u,...(m=u.columns)==null?void 0:m.flatMap(g=>g.getFlatColumns())]},se(e.options,"debugColumns","column.getFlatColumns")),getLeafColumns:oe(()=>[e._getOrderColumnsFn()],m=>{var g;if((g=u.columns)!=null&&g.length){let h=u.columns.flatMap(x=>x.getLeafColumns());return m(h)}return[u]},se(e.options,"debugColumns","column.getLeafColumns"))};for(const m of e._features)m.createColumn==null||m.createColumn(u,e);return u}const Ie="debugHeaders";function Kn(e,t,r){var o;let a={id:(o=r.id)!=null?o:t.id,column:t,index:r.index,isPlaceholder:!!r.isPlaceholder,placeholderId:r.placeholderId,depth:r.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const i=[],l=d=>{d.subHeaders&&d.subHeaders.length&&d.subHeaders.map(l),i.push(d)};return l(a),i},getContext:()=>({table:e,header:a,column:t})};return e._features.forEach(i=>{i.createHeader==null||i.createHeader(a,e)}),a}const fu={createTable:e=>{e.getHeaderGroups=oe(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,r,o,s)=>{var a,i;const l=(a=o==null?void 0:o.map(u=>r.find(m=>m.id===u)).filter(Boolean))!=null?a:[],d=(i=s==null?void 0:s.map(u=>r.find(m=>m.id===u)).filter(Boolean))!=null?i:[],c=r.filter(u=>!(o!=null&&o.includes(u.id))&&!(s!=null&&s.includes(u.id)));return rr(t,[...l,...c,...d],e)},se(e.options,Ie,"getHeaderGroups")),e.getCenterHeaderGroups=oe(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,r,o,s)=>(r=r.filter(a=>!(o!=null&&o.includes(a.id))&&!(s!=null&&s.includes(a.id))),rr(t,r,e,"center")),se(e.options,Ie,"getCenterHeaderGroups")),e.getLeftHeaderGroups=oe(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.left],(t,r,o)=>{var s;const a=(s=o==null?void 0:o.map(i=>r.find(l=>l.id===i)).filter(Boolean))!=null?s:[];return rr(t,a,e,"left")},se(e.options,Ie,"getLeftHeaderGroups")),e.getRightHeaderGroups=oe(()=>[e.getAllColumns(),e.getVisibleLeafColumns(),e.getState().columnPinning.right],(t,r,o)=>{var s;const a=(s=o==null?void 0:o.map(i=>r.find(l=>l.id===i)).filter(Boolean))!=null?s:[];return rr(t,a,e,"right")},se(e.options,Ie,"getRightHeaderGroups")),e.getFooterGroups=oe(()=>[e.getHeaderGroups()],t=>[...t].reverse(),se(e.options,Ie,"getFooterGroups")),e.getLeftFooterGroups=oe(()=>[e.getLeftHeaderGroups()],t=>[...t].reverse(),se(e.options,Ie,"getLeftFooterGroups")),e.getCenterFooterGroups=oe(()=>[e.getCenterHeaderGroups()],t=>[...t].reverse(),se(e.options,Ie,"getCenterFooterGroups")),e.getRightFooterGroups=oe(()=>[e.getRightHeaderGroups()],t=>[...t].reverse(),se(e.options,Ie,"getRightFooterGroups")),e.getFlatHeaders=oe(()=>[e.getHeaderGroups()],t=>t.map(r=>r.headers).flat(),se(e.options,Ie,"getFlatHeaders")),e.getLeftFlatHeaders=oe(()=>[e.getLeftHeaderGroups()],t=>t.map(r=>r.headers).flat(),se(e.options,Ie,"getLeftFlatHeaders")),e.getCenterFlatHeaders=oe(()=>[e.getCenterHeaderGroups()],t=>t.map(r=>r.headers).flat(),se(e.options,Ie,"getCenterFlatHeaders")),e.getRightFlatHeaders=oe(()=>[e.getRightHeaderGroups()],t=>t.map(r=>r.headers).flat(),se(e.options,Ie,"getRightFlatHeaders")),e.getCenterLeafHeaders=oe(()=>[e.getCenterFlatHeaders()],t=>t.filter(r=>{var o;return!((o=r.subHeaders)!=null&&o.length)}),se(e.options,Ie,"getCenterLeafHeaders")),e.getLeftLeafHeaders=oe(()=>[e.getLeftFlatHeaders()],t=>t.filter(r=>{var o;return!((o=r.subHeaders)!=null&&o.length)}),se(e.options,Ie,"getLeftLeafHeaders")),e.getRightLeafHeaders=oe(()=>[e.getRightFlatHeaders()],t=>t.filter(r=>{var o;return!((o=r.subHeaders)!=null&&o.length)}),se(e.options,Ie,"getRightLeafHeaders")),e.getLeafHeaders=oe(()=>[e.getLeftHeaderGroups(),e.getCenterHeaderGroups(),e.getRightHeaderGroups()],(t,r,o)=>{var s,a,i,l,d,c;return[...(s=(a=t[0])==null?void 0:a.headers)!=null?s:[],...(i=(l=r[0])==null?void 0:l.headers)!=null?i:[],...(d=(c=o[0])==null?void 0:c.headers)!=null?d:[]].map(p=>p.getLeafHeaders()).flat()},se(e.options,Ie,"getLeafHeaders"))}};function rr(e,t,r,o){var s,a;let i=0;const l=function(m,g){g===void 0&&(g=1),i=Math.max(i,g),m.filter(h=>h.getIsVisible()).forEach(h=>{var x;(x=h.columns)!=null&&x.length&&l(h.columns,g+1)},0)};l(e);let d=[];const c=(m,g)=>{const h={depth:g,id:[o,`${g}`].filter(Boolean).join("_"),headers:[]},x=[];m.forEach(y=>{const b=[...x].reverse()[0],w=y.column.depth===h.depth;let j,M=!1;if(w&&y.column.parent?j=y.column.parent:(j=y.column,M=!0),b&&(b==null?void 0:b.column)===j)b.subHeaders.push(y);else{const R=Kn(r,j,{id:[o,g,j.id,y==null?void 0:y.id].filter(Boolean).join("_"),isPlaceholder:M,placeholderId:M?`${x.filter(_=>_.column===j).length}`:void 0,depth:g,index:x.length});R.subHeaders.push(y),x.push(R)}h.headers.push(y),y.headerGroup=h}),d.push(h),g>0&&c(x,g-1)},p=t.map((m,g)=>Kn(r,m,{depth:i,index:g}));c(p,i-1),d.reverse();const u=m=>m.filter(h=>h.column.getIsVisible()).map(h=>{let x=0,y=0,b=[0];h.subHeaders&&h.subHeaders.length?(b=[],u(h.subHeaders).forEach(j=>{let{colSpan:M,rowSpan:R}=j;x+=M,b.push(R)})):x=1;const w=Math.min(...b);return y=y+w,h.colSpan=x,h.rowSpan=y,{colSpan:x,rowSpan:y}});return u((s=(a=d[0])==null?void 0:a.headers)!=null?s:[]),d}const Sn=(e,t,r,o,s,a,i)=>{let l={id:t,index:o,original:r,depth:s,parentId:i,_valuesCache:{},_uniqueValuesCache:{},getValue:d=>{if(l._valuesCache.hasOwnProperty(d))return l._valuesCache[d];const c=e.getColumn(d);if(c!=null&&c.accessorFn)return l._valuesCache[d]=c.accessorFn(l.original,o),l._valuesCache[d]},getUniqueValues:d=>{if(l._uniqueValuesCache.hasOwnProperty(d))return l._uniqueValuesCache[d];const c=e.getColumn(d);if(c!=null&&c.accessorFn)return c.columnDef.getUniqueValues?(l._uniqueValuesCache[d]=c.columnDef.getUniqueValues(l.original,o),l._uniqueValuesCache[d]):(l._uniqueValuesCache[d]=[l.getValue(d)],l._uniqueValuesCache[d])},renderValue:d=>{var c;return(c=l.getValue(d))!=null?c:e.options.renderFallbackValue},subRows:[],getLeafRows:()=>du(l.subRows,d=>d.subRows),getParentRow:()=>l.parentId?e.getRow(l.parentId,!0):void 0,getParentRows:()=>{let d=[],c=l;for(;;){const p=c.getParentRow();if(!p)break;d.push(p),c=p}return d.reverse()},getAllCells:oe(()=>[e.getAllLeafColumns()],d=>d.map(c=>uu(e,l,c,c.id)),se(e.options,"debugRows","getAllCells")),_getAllCellsByColumnId:oe(()=>[l.getAllCells()],d=>d.reduce((c,p)=>(c[p.column.id]=p,c),{}),se(e.options,"debugRows","getAllCellsByColumnId"))};for(let d=0;d<e._features.length;d++){const c=e._features[d];c==null||c.createRow==null||c.createRow(l,e)}return l},gu={createColumn:(e,t)=>{e._getFacetedRowModel=t.options.getFacetedRowModel&&t.options.getFacetedRowModel(t,e.id),e.getFacetedRowModel=()=>e._getFacetedRowModel?e._getFacetedRowModel():t.getPreFilteredRowModel(),e._getFacetedUniqueValues=t.options.getFacetedUniqueValues&&t.options.getFacetedUniqueValues(t,e.id),e.getFacetedUniqueValues=()=>e._getFacetedUniqueValues?e._getFacetedUniqueValues():new Map,e._getFacetedMinMaxValues=t.options.getFacetedMinMaxValues&&t.options.getFacetedMinMaxValues(t,e.id),e.getFacetedMinMaxValues=()=>{if(e._getFacetedMinMaxValues)return e._getFacetedMinMaxValues()}}},Ea=(e,t,r)=>{var o,s;const a=r==null||(o=r.toString())==null?void 0:o.toLowerCase();return!!(!((s=e.getValue(t))==null||(s=s.toString())==null||(s=s.toLowerCase())==null)&&s.includes(a))};Ea.autoRemove=e=>Ye(e);const Da=(e,t,r)=>{var o;return!!(!((o=e.getValue(t))==null||(o=o.toString())==null)&&o.includes(r))};Da.autoRemove=e=>Ye(e);const Aa=(e,t,r)=>{var o;return((o=e.getValue(t))==null||(o=o.toString())==null?void 0:o.toLowerCase())===(r==null?void 0:r.toLowerCase())};Aa.autoRemove=e=>Ye(e);const Fa=(e,t,r)=>{var o;return(o=e.getValue(t))==null?void 0:o.includes(r)};Fa.autoRemove=e=>Ye(e);const Va=(e,t,r)=>!r.some(o=>{var s;return!((s=e.getValue(t))!=null&&s.includes(o))});Va.autoRemove=e=>Ye(e)||!(e!=null&&e.length);const za=(e,t,r)=>r.some(o=>{var s;return(s=e.getValue(t))==null?void 0:s.includes(o)});za.autoRemove=e=>Ye(e)||!(e!=null&&e.length);const $a=(e,t,r)=>e.getValue(t)===r;$a.autoRemove=e=>Ye(e);const Ba=(e,t,r)=>e.getValue(t)==r;Ba.autoRemove=e=>Ye(e);const Rn=(e,t,r)=>{let[o,s]=r;const a=e.getValue(t);return a>=o&&a<=s};Rn.resolveFilterValue=e=>{let[t,r]=e,o=typeof t!="number"?parseFloat(t):t,s=typeof r!="number"?parseFloat(r):r,a=t===null||Number.isNaN(o)?-1/0:o,i=r===null||Number.isNaN(s)?1/0:s;if(a>i){const l=a;a=i,i=l}return[a,i]};Rn.autoRemove=e=>Ye(e)||Ye(e[0])&&Ye(e[1]);const rt={includesString:Ea,includesStringSensitive:Da,equalsString:Aa,arrIncludes:Fa,arrIncludesAll:Va,arrIncludesSome:za,equals:$a,weakEquals:Ba,inNumberRange:Rn};function Ye(e){return e==null||e===""}const pu={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:e=>({columnFilters:[],...e}),getDefaultOptions:e=>({onColumnFiltersChange:Oe("columnFilters",e),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(e,t)=>{e.getAutoFilterFn=()=>{const r=t.getCoreRowModel().flatRows[0],o=r==null?void 0:r.getValue(e.id);return typeof o=="string"?rt.includesString:typeof o=="number"?rt.inNumberRange:typeof o=="boolean"||o!==null&&typeof o=="object"?rt.equals:Array.isArray(o)?rt.arrIncludes:rt.weakEquals},e.getFilterFn=()=>{var r,o;return vr(e.columnDef.filterFn)?e.columnDef.filterFn:e.columnDef.filterFn==="auto"?e.getAutoFilterFn():(r=(o=t.options.filterFns)==null?void 0:o[e.columnDef.filterFn])!=null?r:rt[e.columnDef.filterFn]},e.getCanFilter=()=>{var r,o,s;return((r=e.columnDef.enableColumnFilter)!=null?r:!0)&&((o=t.options.enableColumnFilters)!=null?o:!0)&&((s=t.options.enableFilters)!=null?s:!0)&&!!e.accessorFn},e.getIsFiltered=()=>e.getFilterIndex()>-1,e.getFilterValue=()=>{var r;return(r=t.getState().columnFilters)==null||(r=r.find(o=>o.id===e.id))==null?void 0:r.value},e.getFilterIndex=()=>{var r,o;return(r=(o=t.getState().columnFilters)==null?void 0:o.findIndex(s=>s.id===e.id))!=null?r:-1},e.setFilterValue=r=>{t.setColumnFilters(o=>{const s=e.getFilterFn(),a=o==null?void 0:o.find(p=>p.id===e.id),i=dt(r,a?a.value:void 0);if(Xn(s,i,e)){var l;return(l=o==null?void 0:o.filter(p=>p.id!==e.id))!=null?l:[]}const d={id:e.id,value:i};if(a){var c;return(c=o==null?void 0:o.map(p=>p.id===e.id?d:p))!=null?c:[]}return o!=null&&o.length?[...o,d]:[d]})}},createRow:(e,t)=>{e.columnFilters={},e.columnFiltersMeta={}},createTable:e=>{e.setColumnFilters=t=>{const r=e.getAllLeafColumns(),o=s=>{var a;return(a=dt(t,s))==null?void 0:a.filter(i=>{const l=r.find(d=>d.id===i.id);if(l){const d=l.getFilterFn();if(Xn(d,i.value,l))return!1}return!0})};e.options.onColumnFiltersChange==null||e.options.onColumnFiltersChange(o)},e.resetColumnFilters=t=>{var r,o;e.setColumnFilters(t?[]:(r=(o=e.initialState)==null?void 0:o.columnFilters)!=null?r:[])},e.getPreFilteredRowModel=()=>e.getCoreRowModel(),e.getFilteredRowModel=()=>(!e._getFilteredRowModel&&e.options.getFilteredRowModel&&(e._getFilteredRowModel=e.options.getFilteredRowModel(e)),e.options.manualFiltering||!e._getFilteredRowModel?e.getPreFilteredRowModel():e._getFilteredRowModel())}};function Xn(e,t,r){return(e&&e.autoRemove?e.autoRemove(t,r):!1)||typeof t>"u"||typeof t=="string"&&!t}const hu=(e,t,r)=>r.reduce((o,s)=>{const a=s.getValue(e);return o+(typeof a=="number"?a:0)},0),xu=(e,t,r)=>{let o;return r.forEach(s=>{const a=s.getValue(e);a!=null&&(o>a||o===void 0&&a>=a)&&(o=a)}),o},vu=(e,t,r)=>{let o;return r.forEach(s=>{const a=s.getValue(e);a!=null&&(o<a||o===void 0&&a>=a)&&(o=a)}),o},bu=(e,t,r)=>{let o,s;return r.forEach(a=>{const i=a.getValue(e);i!=null&&(o===void 0?i>=i&&(o=s=i):(o>i&&(o=i),s<i&&(s=i)))}),[o,s]},wu=(e,t)=>{let r=0,o=0;if(t.forEach(s=>{let a=s.getValue(e);a!=null&&(a=+a)>=a&&(++r,o+=a)}),r)return o/r},yu=(e,t)=>{if(!t.length)return;const r=t.map(a=>a.getValue(e));if(!cu(r))return;if(r.length===1)return r[0];const o=Math.floor(r.length/2),s=r.sort((a,i)=>a-i);return r.length%2!==0?s[o]:(s[o-1]+s[o])/2},ju=(e,t)=>Array.from(new Set(t.map(r=>r.getValue(e))).values()),Nu=(e,t)=>new Set(t.map(r=>r.getValue(e))).size,ku=(e,t)=>t.length,kr={sum:hu,min:xu,max:vu,extent:bu,mean:wu,median:yu,unique:ju,uniqueCount:Nu,count:ku},Cu={getDefaultColumnDef:()=>({aggregatedCell:e=>{var t,r;return(t=(r=e.getValue())==null||r.toString==null?void 0:r.toString())!=null?t:null},aggregationFn:"auto"}),getInitialState:e=>({grouping:[],...e}),getDefaultOptions:e=>({onGroupingChange:Oe("grouping",e),groupedColumnMode:"reorder"}),createColumn:(e,t)=>{e.toggleGrouping=()=>{t.setGrouping(r=>r!=null&&r.includes(e.id)?r.filter(o=>o!==e.id):[...r??[],e.id])},e.getCanGroup=()=>{var r,o;return((r=e.columnDef.enableGrouping)!=null?r:!0)&&((o=t.options.enableGrouping)!=null?o:!0)&&(!!e.accessorFn||!!e.columnDef.getGroupingValue)},e.getIsGrouped=()=>{var r;return(r=t.getState().grouping)==null?void 0:r.includes(e.id)},e.getGroupedIndex=()=>{var r;return(r=t.getState().grouping)==null?void 0:r.indexOf(e.id)},e.getToggleGroupingHandler=()=>{const r=e.getCanGroup();return()=>{r&&e.toggleGrouping()}},e.getAutoAggregationFn=()=>{const r=t.getCoreRowModel().flatRows[0],o=r==null?void 0:r.getValue(e.id);if(typeof o=="number")return kr.sum;if(Object.prototype.toString.call(o)==="[object Date]")return kr.extent},e.getAggregationFn=()=>{var r,o;if(!e)throw new Error;return vr(e.columnDef.aggregationFn)?e.columnDef.aggregationFn:e.columnDef.aggregationFn==="auto"?e.getAutoAggregationFn():(r=(o=t.options.aggregationFns)==null?void 0:o[e.columnDef.aggregationFn])!=null?r:kr[e.columnDef.aggregationFn]}},createTable:e=>{e.setGrouping=t=>e.options.onGroupingChange==null?void 0:e.options.onGroupingChange(t),e.resetGrouping=t=>{var r,o;e.setGrouping(t?[]:(r=(o=e.initialState)==null?void 0:o.grouping)!=null?r:[])},e.getPreGroupedRowModel=()=>e.getFilteredRowModel(),e.getGroupedRowModel=()=>(!e._getGroupedRowModel&&e.options.getGroupedRowModel&&(e._getGroupedRowModel=e.options.getGroupedRowModel(e)),e.options.manualGrouping||!e._getGroupedRowModel?e.getPreGroupedRowModel():e._getGroupedRowModel())},createRow:(e,t)=>{e.getIsGrouped=()=>!!e.groupingColumnId,e.getGroupingValue=r=>{if(e._groupingValuesCache.hasOwnProperty(r))return e._groupingValuesCache[r];const o=t.getColumn(r);return o!=null&&o.columnDef.getGroupingValue?(e._groupingValuesCache[r]=o.columnDef.getGroupingValue(e.original),e._groupingValuesCache[r]):e.getValue(r)},e._groupingValuesCache={}},createCell:(e,t,r,o)=>{e.getIsGrouped=()=>t.getIsGrouped()&&t.id===r.groupingColumnId,e.getIsPlaceholder=()=>!e.getIsGrouped()&&t.getIsGrouped(),e.getIsAggregated=()=>{var s;return!e.getIsGrouped()&&!e.getIsPlaceholder()&&!!((s=r.subRows)!=null&&s.length)}}};function Su(e,t,r){if(!(t!=null&&t.length)||!r)return e;const o=e.filter(a=>!t.includes(a.id));return r==="remove"?o:[...t.map(a=>e.find(i=>i.id===a)).filter(Boolean),...o]}const Ru={getInitialState:e=>({columnOrder:[],...e}),getDefaultOptions:e=>({onColumnOrderChange:Oe("columnOrder",e)}),createColumn:(e,t)=>{e.getIndex=oe(r=>[zt(t,r)],r=>r.findIndex(o=>o.id===e.id),se(t.options,"debugColumns","getIndex")),e.getIsFirstColumn=r=>{var o;return((o=zt(t,r)[0])==null?void 0:o.id)===e.id},e.getIsLastColumn=r=>{var o;const s=zt(t,r);return((o=s[s.length-1])==null?void 0:o.id)===e.id}},createTable:e=>{e.setColumnOrder=t=>e.options.onColumnOrderChange==null?void 0:e.options.onColumnOrderChange(t),e.resetColumnOrder=t=>{var r;e.setColumnOrder(t?[]:(r=e.initialState.columnOrder)!=null?r:[])},e._getOrderColumnsFn=oe(()=>[e.getState().columnOrder,e.getState().grouping,e.options.groupedColumnMode],(t,r,o)=>s=>{let a=[];if(!(t!=null&&t.length))a=s;else{const i=[...t],l=[...s];for(;l.length&&i.length;){const d=i.shift(),c=l.findIndex(p=>p.id===d);c>-1&&a.push(l.splice(c,1)[0])}a=[...a,...l]}return Su(a,r,o)},se(e.options,"debugTable","_getOrderColumnsFn"))}},Cr=()=>({left:[],right:[]}),_u={getInitialState:e=>({columnPinning:Cr(),...e}),getDefaultOptions:e=>({onColumnPinningChange:Oe("columnPinning",e)}),createColumn:(e,t)=>{e.pin=r=>{const o=e.getLeafColumns().map(s=>s.id).filter(Boolean);t.setColumnPinning(s=>{var a,i;if(r==="right"){var l,d;return{left:((l=s==null?void 0:s.left)!=null?l:[]).filter(u=>!(o!=null&&o.includes(u))),right:[...((d=s==null?void 0:s.right)!=null?d:[]).filter(u=>!(o!=null&&o.includes(u))),...o]}}if(r==="left"){var c,p;return{left:[...((c=s==null?void 0:s.left)!=null?c:[]).filter(u=>!(o!=null&&o.includes(u))),...o],right:((p=s==null?void 0:s.right)!=null?p:[]).filter(u=>!(o!=null&&o.includes(u)))}}return{left:((a=s==null?void 0:s.left)!=null?a:[]).filter(u=>!(o!=null&&o.includes(u))),right:((i=s==null?void 0:s.right)!=null?i:[]).filter(u=>!(o!=null&&o.includes(u)))}})},e.getCanPin=()=>e.getLeafColumns().some(o=>{var s,a,i;return((s=o.columnDef.enablePinning)!=null?s:!0)&&((a=(i=t.options.enableColumnPinning)!=null?i:t.options.enablePinning)!=null?a:!0)}),e.getIsPinned=()=>{const r=e.getLeafColumns().map(l=>l.id),{left:o,right:s}=t.getState().columnPinning,a=r.some(l=>o==null?void 0:o.includes(l)),i=r.some(l=>s==null?void 0:s.includes(l));return a?"left":i?"right":!1},e.getPinnedIndex=()=>{var r,o;const s=e.getIsPinned();return s?(r=(o=t.getState().columnPinning)==null||(o=o[s])==null?void 0:o.indexOf(e.id))!=null?r:-1:0}},createRow:(e,t)=>{e.getCenterVisibleCells=oe(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left,t.getState().columnPinning.right],(r,o,s)=>{const a=[...o??[],...s??[]];return r.filter(i=>!a.includes(i.column.id))},se(t.options,"debugRows","getCenterVisibleCells")),e.getLeftVisibleCells=oe(()=>[e._getAllVisibleCells(),t.getState().columnPinning.left],(r,o)=>(o??[]).map(a=>r.find(i=>i.column.id===a)).filter(Boolean).map(a=>({...a,position:"left"})),se(t.options,"debugRows","getLeftVisibleCells")),e.getRightVisibleCells=oe(()=>[e._getAllVisibleCells(),t.getState().columnPinning.right],(r,o)=>(o??[]).map(a=>r.find(i=>i.column.id===a)).filter(Boolean).map(a=>({...a,position:"right"})),se(t.options,"debugRows","getRightVisibleCells"))},createTable:e=>{e.setColumnPinning=t=>e.options.onColumnPinningChange==null?void 0:e.options.onColumnPinningChange(t),e.resetColumnPinning=t=>{var r,o;return e.setColumnPinning(t?Cr():(r=(o=e.initialState)==null?void 0:o.columnPinning)!=null?r:Cr())},e.getIsSomeColumnsPinned=t=>{var r;const o=e.getState().columnPinning;if(!t){var s,a;return!!((s=o.left)!=null&&s.length||(a=o.right)!=null&&a.length)}return!!((r=o[t])!=null&&r.length)},e.getLeftLeafColumns=oe(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left],(t,r)=>(r??[]).map(o=>t.find(s=>s.id===o)).filter(Boolean),se(e.options,"debugColumns","getLeftLeafColumns")),e.getRightLeafColumns=oe(()=>[e.getAllLeafColumns(),e.getState().columnPinning.right],(t,r)=>(r??[]).map(o=>t.find(s=>s.id===o)).filter(Boolean),se(e.options,"debugColumns","getRightLeafColumns")),e.getCenterLeafColumns=oe(()=>[e.getAllLeafColumns(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,r,o)=>{const s=[...r??[],...o??[]];return t.filter(a=>!s.includes(a.id))},se(e.options,"debugColumns","getCenterLeafColumns"))}};function Mu(e){return e||(typeof document<"u"?document:null)}const nr={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},Sr=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),Pu={getDefaultColumnDef:()=>nr,getInitialState:e=>({columnSizing:{},columnSizingInfo:Sr(),...e}),getDefaultOptions:e=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:Oe("columnSizing",e),onColumnSizingInfoChange:Oe("columnSizingInfo",e)}),createColumn:(e,t)=>{e.getSize=()=>{var r,o,s;const a=t.getState().columnSizing[e.id];return Math.min(Math.max((r=e.columnDef.minSize)!=null?r:nr.minSize,(o=a??e.columnDef.size)!=null?o:nr.size),(s=e.columnDef.maxSize)!=null?s:nr.maxSize)},e.getStart=oe(r=>[r,zt(t,r),t.getState().columnSizing],(r,o)=>o.slice(0,e.getIndex(r)).reduce((s,a)=>s+a.getSize(),0),se(t.options,"debugColumns","getStart")),e.getAfter=oe(r=>[r,zt(t,r),t.getState().columnSizing],(r,o)=>o.slice(e.getIndex(r)+1).reduce((s,a)=>s+a.getSize(),0),se(t.options,"debugColumns","getAfter")),e.resetSize=()=>{t.setColumnSizing(r=>{let{[e.id]:o,...s}=r;return s})},e.getCanResize=()=>{var r,o;return((r=e.columnDef.enableResizing)!=null?r:!0)&&((o=t.options.enableColumnResizing)!=null?o:!0)},e.getIsResizing=()=>t.getState().columnSizingInfo.isResizingColumn===e.id},createHeader:(e,t)=>{e.getSize=()=>{let r=0;const o=s=>{if(s.subHeaders.length)s.subHeaders.forEach(o);else{var a;r+=(a=s.column.getSize())!=null?a:0}};return o(e),r},e.getStart=()=>{if(e.index>0){const r=e.headerGroup.headers[e.index-1];return r.getStart()+r.getSize()}return 0},e.getResizeHandler=r=>{const o=t.getColumn(e.column.id),s=o==null?void 0:o.getCanResize();return a=>{if(!o||!s||(a.persist==null||a.persist(),Rr(a)&&a.touches&&a.touches.length>1))return;const i=e.getSize(),l=e?e.getLeafHeaders().map(b=>[b.column.id,b.column.getSize()]):[[o.id,o.getSize()]],d=Rr(a)?Math.round(a.touches[0].clientX):a.clientX,c={},p=(b,w)=>{typeof w=="number"&&(t.setColumnSizingInfo(j=>{var M,R;const _=t.options.columnResizeDirection==="rtl"?-1:1,C=(w-((M=j==null?void 0:j.startOffset)!=null?M:0))*_,S=Math.max(C/((R=j==null?void 0:j.startSize)!=null?R:0),-.999999);return j.columnSizingStart.forEach(T=>{let[L,V]=T;c[L]=Math.round(Math.max(V+V*S,0)*100)/100}),{...j,deltaOffset:C,deltaPercentage:S}}),(t.options.columnResizeMode==="onChange"||b==="end")&&t.setColumnSizing(j=>({...j,...c})))},u=b=>p("move",b),m=b=>{p("end",b),t.setColumnSizingInfo(w=>({...w,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},g=Mu(r),h={moveHandler:b=>u(b.clientX),upHandler:b=>{g==null||g.removeEventListener("mousemove",h.moveHandler),g==null||g.removeEventListener("mouseup",h.upHandler),m(b.clientX)}},x={moveHandler:b=>(b.cancelable&&(b.preventDefault(),b.stopPropagation()),u(b.touches[0].clientX),!1),upHandler:b=>{var w;g==null||g.removeEventListener("touchmove",x.moveHandler),g==null||g.removeEventListener("touchend",x.upHandler),b.cancelable&&(b.preventDefault(),b.stopPropagation()),m((w=b.touches[0])==null?void 0:w.clientX)}},y=Iu()?{passive:!1}:!1;Rr(a)?(g==null||g.addEventListener("touchmove",x.moveHandler,y),g==null||g.addEventListener("touchend",x.upHandler,y)):(g==null||g.addEventListener("mousemove",h.moveHandler,y),g==null||g.addEventListener("mouseup",h.upHandler,y)),t.setColumnSizingInfo(b=>({...b,startOffset:d,startSize:i,deltaOffset:0,deltaPercentage:0,columnSizingStart:l,isResizingColumn:o.id}))}}},createTable:e=>{e.setColumnSizing=t=>e.options.onColumnSizingChange==null?void 0:e.options.onColumnSizingChange(t),e.setColumnSizingInfo=t=>e.options.onColumnSizingInfoChange==null?void 0:e.options.onColumnSizingInfoChange(t),e.resetColumnSizing=t=>{var r;e.setColumnSizing(t?{}:(r=e.initialState.columnSizing)!=null?r:{})},e.resetHeaderSizeInfo=t=>{var r;e.setColumnSizingInfo(t?Sr():(r=e.initialState.columnSizingInfo)!=null?r:Sr())},e.getTotalSize=()=>{var t,r;return(t=(r=e.getHeaderGroups()[0])==null?void 0:r.headers.reduce((o,s)=>o+s.getSize(),0))!=null?t:0},e.getLeftTotalSize=()=>{var t,r;return(t=(r=e.getLeftHeaderGroups()[0])==null?void 0:r.headers.reduce((o,s)=>o+s.getSize(),0))!=null?t:0},e.getCenterTotalSize=()=>{var t,r;return(t=(r=e.getCenterHeaderGroups()[0])==null?void 0:r.headers.reduce((o,s)=>o+s.getSize(),0))!=null?t:0},e.getRightTotalSize=()=>{var t,r;return(t=(r=e.getRightHeaderGroups()[0])==null?void 0:r.headers.reduce((o,s)=>o+s.getSize(),0))!=null?t:0}}};let or=null;function Iu(){if(typeof or=="boolean")return or;let e=!1;try{const t={get passive(){return e=!0,!1}},r=()=>{};window.addEventListener("test",r,t),window.removeEventListener("test",r)}catch{e=!1}return or=e,or}function Rr(e){return e.type==="touchstart"}const Lu={getInitialState:e=>({columnVisibility:{},...e}),getDefaultOptions:e=>({onColumnVisibilityChange:Oe("columnVisibility",e)}),createColumn:(e,t)=>{e.toggleVisibility=r=>{e.getCanHide()&&t.setColumnVisibility(o=>({...o,[e.id]:r??!e.getIsVisible()}))},e.getIsVisible=()=>{var r,o;const s=e.columns;return(r=s.length?s.some(a=>a.getIsVisible()):(o=t.getState().columnVisibility)==null?void 0:o[e.id])!=null?r:!0},e.getCanHide=()=>{var r,o;return((r=e.columnDef.enableHiding)!=null?r:!0)&&((o=t.options.enableHiding)!=null?o:!0)},e.getToggleVisibilityHandler=()=>r=>{e.toggleVisibility==null||e.toggleVisibility(r.target.checked)}},createRow:(e,t)=>{e._getAllVisibleCells=oe(()=>[e.getAllCells(),t.getState().columnVisibility],r=>r.filter(o=>o.column.getIsVisible()),se(t.options,"debugRows","_getAllVisibleCells")),e.getVisibleCells=oe(()=>[e.getLeftVisibleCells(),e.getCenterVisibleCells(),e.getRightVisibleCells()],(r,o,s)=>[...r,...o,...s],se(t.options,"debugRows","getVisibleCells"))},createTable:e=>{const t=(r,o)=>oe(()=>[o(),o().filter(s=>s.getIsVisible()).map(s=>s.id).join("_")],s=>s.filter(a=>a.getIsVisible==null?void 0:a.getIsVisible()),se(e.options,"debugColumns",r));e.getVisibleFlatColumns=t("getVisibleFlatColumns",()=>e.getAllFlatColumns()),e.getVisibleLeafColumns=t("getVisibleLeafColumns",()=>e.getAllLeafColumns()),e.getLeftVisibleLeafColumns=t("getLeftVisibleLeafColumns",()=>e.getLeftLeafColumns()),e.getRightVisibleLeafColumns=t("getRightVisibleLeafColumns",()=>e.getRightLeafColumns()),e.getCenterVisibleLeafColumns=t("getCenterVisibleLeafColumns",()=>e.getCenterLeafColumns()),e.setColumnVisibility=r=>e.options.onColumnVisibilityChange==null?void 0:e.options.onColumnVisibilityChange(r),e.resetColumnVisibility=r=>{var o;e.setColumnVisibility(r?{}:(o=e.initialState.columnVisibility)!=null?o:{})},e.toggleAllColumnsVisible=r=>{var o;r=(o=r)!=null?o:!e.getIsAllColumnsVisible(),e.setColumnVisibility(e.getAllLeafColumns().reduce((s,a)=>({...s,[a.id]:r||!(a.getCanHide!=null&&a.getCanHide())}),{}))},e.getIsAllColumnsVisible=()=>!e.getAllLeafColumns().some(r=>!(r.getIsVisible!=null&&r.getIsVisible())),e.getIsSomeColumnsVisible=()=>e.getAllLeafColumns().some(r=>r.getIsVisible==null?void 0:r.getIsVisible()),e.getToggleAllColumnsVisibilityHandler=()=>r=>{var o;e.toggleAllColumnsVisible((o=r.target)==null?void 0:o.checked)}}};function zt(e,t){return t?t==="center"?e.getCenterVisibleLeafColumns():t==="left"?e.getLeftVisibleLeafColumns():e.getRightVisibleLeafColumns():e.getVisibleLeafColumns()}const Tu={createTable:e=>{e._getGlobalFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,"__global__"),e.getGlobalFacetedRowModel=()=>e.options.manualFiltering||!e._getGlobalFacetedRowModel?e.getPreFilteredRowModel():e._getGlobalFacetedRowModel(),e._getGlobalFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,"__global__"),e.getGlobalFacetedUniqueValues=()=>e._getGlobalFacetedUniqueValues?e._getGlobalFacetedUniqueValues():new Map,e._getGlobalFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,"__global__"),e.getGlobalFacetedMinMaxValues=()=>{if(e._getGlobalFacetedMinMaxValues)return e._getGlobalFacetedMinMaxValues()}}},Eu={getInitialState:e=>({globalFilter:void 0,...e}),getDefaultOptions:e=>({onGlobalFilterChange:Oe("globalFilter",e),globalFilterFn:"auto",getColumnCanGlobalFilter:t=>{var r;const o=(r=e.getCoreRowModel().flatRows[0])==null||(r=r._getAllCellsByColumnId()[t.id])==null?void 0:r.getValue();return typeof o=="string"||typeof o=="number"}}),createColumn:(e,t)=>{e.getCanGlobalFilter=()=>{var r,o,s,a;return((r=e.columnDef.enableGlobalFilter)!=null?r:!0)&&((o=t.options.enableGlobalFilter)!=null?o:!0)&&((s=t.options.enableFilters)!=null?s:!0)&&((a=t.options.getColumnCanGlobalFilter==null?void 0:t.options.getColumnCanGlobalFilter(e))!=null?a:!0)&&!!e.accessorFn}},createTable:e=>{e.getGlobalAutoFilterFn=()=>rt.includesString,e.getGlobalFilterFn=()=>{var t,r;const{globalFilterFn:o}=e.options;return vr(o)?o:o==="auto"?e.getGlobalAutoFilterFn():(t=(r=e.options.filterFns)==null?void 0:r[o])!=null?t:rt[o]},e.setGlobalFilter=t=>{e.options.onGlobalFilterChange==null||e.options.onGlobalFilterChange(t)},e.resetGlobalFilter=t=>{e.setGlobalFilter(t?void 0:e.initialState.globalFilter)}}},Du={getInitialState:e=>({expanded:{},...e}),getDefaultOptions:e=>({onExpandedChange:Oe("expanded",e),paginateExpandedRows:!0}),createTable:e=>{let t=!1,r=!1;e._autoResetExpanded=()=>{var o,s;if(!t){e._queue(()=>{t=!0});return}if((o=(s=e.options.autoResetAll)!=null?s:e.options.autoResetExpanded)!=null?o:!e.options.manualExpanding){if(r)return;r=!0,e._queue(()=>{e.resetExpanded(),r=!1})}},e.setExpanded=o=>e.options.onExpandedChange==null?void 0:e.options.onExpandedChange(o),e.toggleAllRowsExpanded=o=>{o??!e.getIsAllRowsExpanded()?e.setExpanded(!0):e.setExpanded({})},e.resetExpanded=o=>{var s,a;e.setExpanded(o?{}:(s=(a=e.initialState)==null?void 0:a.expanded)!=null?s:{})},e.getCanSomeRowsExpand=()=>e.getPrePaginationRowModel().flatRows.some(o=>o.getCanExpand()),e.getToggleAllRowsExpandedHandler=()=>o=>{o.persist==null||o.persist(),e.toggleAllRowsExpanded()},e.getIsSomeRowsExpanded=()=>{const o=e.getState().expanded;return o===!0||Object.values(o).some(Boolean)},e.getIsAllRowsExpanded=()=>{const o=e.getState().expanded;return typeof o=="boolean"?o===!0:!(!Object.keys(o).length||e.getRowModel().flatRows.some(s=>!s.getIsExpanded()))},e.getExpandedDepth=()=>{let o=0;return(e.getState().expanded===!0?Object.keys(e.getRowModel().rowsById):Object.keys(e.getState().expanded)).forEach(a=>{const i=a.split(".");o=Math.max(o,i.length)}),o},e.getPreExpandedRowModel=()=>e.getSortedRowModel(),e.getExpandedRowModel=()=>(!e._getExpandedRowModel&&e.options.getExpandedRowModel&&(e._getExpandedRowModel=e.options.getExpandedRowModel(e)),e.options.manualExpanding||!e._getExpandedRowModel?e.getPreExpandedRowModel():e._getExpandedRowModel())},createRow:(e,t)=>{e.toggleExpanded=r=>{t.setExpanded(o=>{var s;const a=o===!0?!0:!!(o!=null&&o[e.id]);let i={};if(o===!0?Object.keys(t.getRowModel().rowsById).forEach(l=>{i[l]=!0}):i=o,r=(s=r)!=null?s:!a,!a&&r)return{...i,[e.id]:!0};if(a&&!r){const{[e.id]:l,...d}=i;return d}return o})},e.getIsExpanded=()=>{var r;const o=t.getState().expanded;return!!((r=t.options.getIsRowExpanded==null?void 0:t.options.getIsRowExpanded(e))!=null?r:o===!0||o!=null&&o[e.id])},e.getCanExpand=()=>{var r,o,s;return(r=t.options.getRowCanExpand==null?void 0:t.options.getRowCanExpand(e))!=null?r:((o=t.options.enableExpanding)!=null?o:!0)&&!!((s=e.subRows)!=null&&s.length)},e.getIsAllParentsExpanded=()=>{let r=!0,o=e;for(;r&&o.parentId;)o=t.getRow(o.parentId,!0),r=o.getIsExpanded();return r},e.getToggleExpandedHandler=()=>{const r=e.getCanExpand();return()=>{r&&e.toggleExpanded()}}}},zr=0,$r=10,_r=()=>({pageIndex:zr,pageSize:$r}),Au={getInitialState:e=>({...e,pagination:{..._r(),...e==null?void 0:e.pagination}}),getDefaultOptions:e=>({onPaginationChange:Oe("pagination",e)}),createTable:e=>{let t=!1,r=!1;e._autoResetPageIndex=()=>{var o,s;if(!t){e._queue(()=>{t=!0});return}if((o=(s=e.options.autoResetAll)!=null?s:e.options.autoResetPageIndex)!=null?o:!e.options.manualPagination){if(r)return;r=!0,e._queue(()=>{e.resetPageIndex(),r=!1})}},e.setPagination=o=>{const s=a=>dt(o,a);return e.options.onPaginationChange==null?void 0:e.options.onPaginationChange(s)},e.resetPagination=o=>{var s;e.setPagination(o?_r():(s=e.initialState.pagination)!=null?s:_r())},e.setPageIndex=o=>{e.setPagination(s=>{let a=dt(o,s.pageIndex);const i=typeof e.options.pageCount>"u"||e.options.pageCount===-1?Number.MAX_SAFE_INTEGER:e.options.pageCount-1;return a=Math.max(0,Math.min(a,i)),{...s,pageIndex:a}})},e.resetPageIndex=o=>{var s,a;e.setPageIndex(o?zr:(s=(a=e.initialState)==null||(a=a.pagination)==null?void 0:a.pageIndex)!=null?s:zr)},e.resetPageSize=o=>{var s,a;e.setPageSize(o?$r:(s=(a=e.initialState)==null||(a=a.pagination)==null?void 0:a.pageSize)!=null?s:$r)},e.setPageSize=o=>{e.setPagination(s=>{const a=Math.max(1,dt(o,s.pageSize)),i=s.pageSize*s.pageIndex,l=Math.floor(i/a);return{...s,pageIndex:l,pageSize:a}})},e.setPageCount=o=>e.setPagination(s=>{var a;let i=dt(o,(a=e.options.pageCount)!=null?a:-1);return typeof i=="number"&&(i=Math.max(-1,i)),{...s,pageCount:i}}),e.getPageOptions=oe(()=>[e.getPageCount()],o=>{let s=[];return o&&o>0&&(s=[...new Array(o)].fill(null).map((a,i)=>i)),s},se(e.options,"debugTable","getPageOptions")),e.getCanPreviousPage=()=>e.getState().pagination.pageIndex>0,e.getCanNextPage=()=>{const{pageIndex:o}=e.getState().pagination,s=e.getPageCount();return s===-1?!0:s===0?!1:o<s-1},e.previousPage=()=>e.setPageIndex(o=>o-1),e.nextPage=()=>e.setPageIndex(o=>o+1),e.firstPage=()=>e.setPageIndex(0),e.lastPage=()=>e.setPageIndex(e.getPageCount()-1),e.getPrePaginationRowModel=()=>e.getExpandedRowModel(),e.getPaginationRowModel=()=>(!e._getPaginationRowModel&&e.options.getPaginationRowModel&&(e._getPaginationRowModel=e.options.getPaginationRowModel(e)),e.options.manualPagination||!e._getPaginationRowModel?e.getPrePaginationRowModel():e._getPaginationRowModel()),e.getPageCount=()=>{var o;return(o=e.options.pageCount)!=null?o:Math.ceil(e.getRowCount()/e.getState().pagination.pageSize)},e.getRowCount=()=>{var o;return(o=e.options.rowCount)!=null?o:e.getPrePaginationRowModel().rows.length}}},Mr=()=>({top:[],bottom:[]}),Fu={getInitialState:e=>({rowPinning:Mr(),...e}),getDefaultOptions:e=>({onRowPinningChange:Oe("rowPinning",e)}),createRow:(e,t)=>{e.pin=(r,o,s)=>{const a=o?e.getLeafRows().map(d=>{let{id:c}=d;return c}):[],i=s?e.getParentRows().map(d=>{let{id:c}=d;return c}):[],l=new Set([...i,e.id,...a]);t.setRowPinning(d=>{var c,p;if(r==="bottom"){var u,m;return{top:((u=d==null?void 0:d.top)!=null?u:[]).filter(x=>!(l!=null&&l.has(x))),bottom:[...((m=d==null?void 0:d.bottom)!=null?m:[]).filter(x=>!(l!=null&&l.has(x))),...Array.from(l)]}}if(r==="top"){var g,h;return{top:[...((g=d==null?void 0:d.top)!=null?g:[]).filter(x=>!(l!=null&&l.has(x))),...Array.from(l)],bottom:((h=d==null?void 0:d.bottom)!=null?h:[]).filter(x=>!(l!=null&&l.has(x)))}}return{top:((c=d==null?void 0:d.top)!=null?c:[]).filter(x=>!(l!=null&&l.has(x))),bottom:((p=d==null?void 0:d.bottom)!=null?p:[]).filter(x=>!(l!=null&&l.has(x)))}})},e.getCanPin=()=>{var r;const{enableRowPinning:o,enablePinning:s}=t.options;return typeof o=="function"?o(e):(r=o??s)!=null?r:!0},e.getIsPinned=()=>{const r=[e.id],{top:o,bottom:s}=t.getState().rowPinning,a=r.some(l=>o==null?void 0:o.includes(l)),i=r.some(l=>s==null?void 0:s.includes(l));return a?"top":i?"bottom":!1},e.getPinnedIndex=()=>{var r,o;const s=e.getIsPinned();if(!s)return-1;const a=(r=s==="top"?t.getTopRows():t.getBottomRows())==null?void 0:r.map(i=>{let{id:l}=i;return l});return(o=a==null?void 0:a.indexOf(e.id))!=null?o:-1}},createTable:e=>{e.setRowPinning=t=>e.options.onRowPinningChange==null?void 0:e.options.onRowPinningChange(t),e.resetRowPinning=t=>{var r,o;return e.setRowPinning(t?Mr():(r=(o=e.initialState)==null?void 0:o.rowPinning)!=null?r:Mr())},e.getIsSomeRowsPinned=t=>{var r;const o=e.getState().rowPinning;if(!t){var s,a;return!!((s=o.top)!=null&&s.length||(a=o.bottom)!=null&&a.length)}return!!((r=o[t])!=null&&r.length)},e._getPinnedRows=(t,r,o)=>{var s;return((s=e.options.keepPinnedRows)==null||s?(r??[]).map(i=>{const l=e.getRow(i,!0);return l.getIsAllParentsExpanded()?l:null}):(r??[]).map(i=>t.find(l=>l.id===i))).filter(Boolean).map(i=>({...i,position:o}))},e.getTopRows=oe(()=>[e.getRowModel().rows,e.getState().rowPinning.top],(t,r)=>e._getPinnedRows(t,r,"top"),se(e.options,"debugRows","getTopRows")),e.getBottomRows=oe(()=>[e.getRowModel().rows,e.getState().rowPinning.bottom],(t,r)=>e._getPinnedRows(t,r,"bottom"),se(e.options,"debugRows","getBottomRows")),e.getCenterRows=oe(()=>[e.getRowModel().rows,e.getState().rowPinning.top,e.getState().rowPinning.bottom],(t,r,o)=>{const s=new Set([...r??[],...o??[]]);return t.filter(a=>!s.has(a.id))},se(e.options,"debugRows","getCenterRows"))}},Vu={getInitialState:e=>({rowSelection:{},...e}),getDefaultOptions:e=>({onRowSelectionChange:Oe("rowSelection",e),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:e=>{e.setRowSelection=t=>e.options.onRowSelectionChange==null?void 0:e.options.onRowSelectionChange(t),e.resetRowSelection=t=>{var r;return e.setRowSelection(t?{}:(r=e.initialState.rowSelection)!=null?r:{})},e.toggleAllRowsSelected=t=>{e.setRowSelection(r=>{t=typeof t<"u"?t:!e.getIsAllRowsSelected();const o={...r},s=e.getPreGroupedRowModel().flatRows;return t?s.forEach(a=>{a.getCanSelect()&&(o[a.id]=!0)}):s.forEach(a=>{delete o[a.id]}),o})},e.toggleAllPageRowsSelected=t=>e.setRowSelection(r=>{const o=typeof t<"u"?t:!e.getIsAllPageRowsSelected(),s={...r};return e.getRowModel().rows.forEach(a=>{Br(s,a.id,o,!0,e)}),s}),e.getPreSelectedRowModel=()=>e.getCoreRowModel(),e.getSelectedRowModel=oe(()=>[e.getState().rowSelection,e.getCoreRowModel()],(t,r)=>Object.keys(t).length?Pr(e,r):{rows:[],flatRows:[],rowsById:{}},se(e.options,"debugTable","getSelectedRowModel")),e.getFilteredSelectedRowModel=oe(()=>[e.getState().rowSelection,e.getFilteredRowModel()],(t,r)=>Object.keys(t).length?Pr(e,r):{rows:[],flatRows:[],rowsById:{}},se(e.options,"debugTable","getFilteredSelectedRowModel")),e.getGroupedSelectedRowModel=oe(()=>[e.getState().rowSelection,e.getSortedRowModel()],(t,r)=>Object.keys(t).length?Pr(e,r):{rows:[],flatRows:[],rowsById:{}},se(e.options,"debugTable","getGroupedSelectedRowModel")),e.getIsAllRowsSelected=()=>{const t=e.getFilteredRowModel().flatRows,{rowSelection:r}=e.getState();let o=!!(t.length&&Object.keys(r).length);return o&&t.some(s=>s.getCanSelect()&&!r[s.id])&&(o=!1),o},e.getIsAllPageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows.filter(s=>s.getCanSelect()),{rowSelection:r}=e.getState();let o=!!t.length;return o&&t.some(s=>!r[s.id])&&(o=!1),o},e.getIsSomeRowsSelected=()=>{var t;const r=Object.keys((t=e.getState().rowSelection)!=null?t:{}).length;return r>0&&r<e.getFilteredRowModel().flatRows.length},e.getIsSomePageRowsSelected=()=>{const t=e.getPaginationRowModel().flatRows;return e.getIsAllPageRowsSelected()?!1:t.filter(r=>r.getCanSelect()).some(r=>r.getIsSelected()||r.getIsSomeSelected())},e.getToggleAllRowsSelectedHandler=()=>t=>{e.toggleAllRowsSelected(t.target.checked)},e.getToggleAllPageRowsSelectedHandler=()=>t=>{e.toggleAllPageRowsSelected(t.target.checked)}},createRow:(e,t)=>{e.toggleSelected=(r,o)=>{const s=e.getIsSelected();t.setRowSelection(a=>{var i;if(r=typeof r<"u"?r:!s,e.getCanSelect()&&s===r)return a;const l={...a};return Br(l,e.id,r,(i=o==null?void 0:o.selectChildren)!=null?i:!0,t),l})},e.getIsSelected=()=>{const{rowSelection:r}=t.getState();return _n(e,r)},e.getIsSomeSelected=()=>{const{rowSelection:r}=t.getState();return Or(e,r)==="some"},e.getIsAllSubRowsSelected=()=>{const{rowSelection:r}=t.getState();return Or(e,r)==="all"},e.getCanSelect=()=>{var r;return typeof t.options.enableRowSelection=="function"?t.options.enableRowSelection(e):(r=t.options.enableRowSelection)!=null?r:!0},e.getCanSelectSubRows=()=>{var r;return typeof t.options.enableSubRowSelection=="function"?t.options.enableSubRowSelection(e):(r=t.options.enableSubRowSelection)!=null?r:!0},e.getCanMultiSelect=()=>{var r;return typeof t.options.enableMultiRowSelection=="function"?t.options.enableMultiRowSelection(e):(r=t.options.enableMultiRowSelection)!=null?r:!0},e.getToggleSelectedHandler=()=>{const r=e.getCanSelect();return o=>{var s;r&&e.toggleSelected((s=o.target)==null?void 0:s.checked)}}}},Br=(e,t,r,o,s)=>{var a;const i=s.getRow(t,!0);r?(i.getCanMultiSelect()||Object.keys(e).forEach(l=>delete e[l]),i.getCanSelect()&&(e[t]=!0)):delete e[t],o&&(a=i.subRows)!=null&&a.length&&i.getCanSelectSubRows()&&i.subRows.forEach(l=>Br(e,l.id,r,o,s))};function Pr(e,t){const r=e.getState().rowSelection,o=[],s={},a=function(i,l){return i.map(d=>{var c;const p=_n(d,r);if(p&&(o.push(d),s[d.id]=d),(c=d.subRows)!=null&&c.length&&(d={...d,subRows:a(d.subRows)}),p)return d}).filter(Boolean)};return{rows:a(t.rows),flatRows:o,rowsById:s}}function _n(e,t){var r;return(r=t[e.id])!=null?r:!1}function Or(e,t,r){var o;if(!((o=e.subRows)!=null&&o.length))return!1;let s=!0,a=!1;return e.subRows.forEach(i=>{if(!(a&&!s)&&(i.getCanSelect()&&(_n(i,t)?a=!0:s=!1),i.subRows&&i.subRows.length)){const l=Or(i,t);l==="all"?a=!0:(l==="some"&&(a=!0),s=!1)}}),s?"all":a?"some":!1}const Hr=/([0-9]+)/gm,zu=(e,t,r)=>Oa(ut(e.getValue(r)).toLowerCase(),ut(t.getValue(r)).toLowerCase()),$u=(e,t,r)=>Oa(ut(e.getValue(r)),ut(t.getValue(r))),Bu=(e,t,r)=>Mn(ut(e.getValue(r)).toLowerCase(),ut(t.getValue(r)).toLowerCase()),Ou=(e,t,r)=>Mn(ut(e.getValue(r)),ut(t.getValue(r))),Hu=(e,t,r)=>{const o=e.getValue(r),s=t.getValue(r);return o>s?1:o<s?-1:0},Gu=(e,t,r)=>Mn(e.getValue(r),t.getValue(r));function Mn(e,t){return e===t?0:e>t?1:-1}function ut(e){return typeof e=="number"?isNaN(e)||e===1/0||e===-1/0?"":String(e):typeof e=="string"?e:""}function Oa(e,t){const r=e.split(Hr).filter(Boolean),o=t.split(Hr).filter(Boolean);for(;r.length&&o.length;){const s=r.shift(),a=o.shift(),i=parseInt(s,10),l=parseInt(a,10),d=[i,l].sort();if(isNaN(d[0])){if(s>a)return 1;if(a>s)return-1;continue}if(isNaN(d[1]))return isNaN(i)?-1:1;if(i>l)return 1;if(l>i)return-1}return r.length-o.length}const Tt={alphanumeric:zu,alphanumericCaseSensitive:$u,text:Bu,textCaseSensitive:Ou,datetime:Hu,basic:Gu},qu={getInitialState:e=>({sorting:[],...e}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:e=>({onSortingChange:Oe("sorting",e),isMultiSortEvent:t=>t.shiftKey}),createColumn:(e,t)=>{e.getAutoSortingFn=()=>{const r=t.getFilteredRowModel().flatRows.slice(10);let o=!1;for(const s of r){const a=s==null?void 0:s.getValue(e.id);if(Object.prototype.toString.call(a)==="[object Date]")return Tt.datetime;if(typeof a=="string"&&(o=!0,a.split(Hr).length>1))return Tt.alphanumeric}return o?Tt.text:Tt.basic},e.getAutoSortDir=()=>{const r=t.getFilteredRowModel().flatRows[0];return typeof(r==null?void 0:r.getValue(e.id))=="string"?"asc":"desc"},e.getSortingFn=()=>{var r,o;if(!e)throw new Error;return vr(e.columnDef.sortingFn)?e.columnDef.sortingFn:e.columnDef.sortingFn==="auto"?e.getAutoSortingFn():(r=(o=t.options.sortingFns)==null?void 0:o[e.columnDef.sortingFn])!=null?r:Tt[e.columnDef.sortingFn]},e.toggleSorting=(r,o)=>{const s=e.getNextSortingOrder(),a=typeof r<"u"&&r!==null;t.setSorting(i=>{const l=i==null?void 0:i.find(g=>g.id===e.id),d=i==null?void 0:i.findIndex(g=>g.id===e.id);let c=[],p,u=a?r:s==="desc";if(i!=null&&i.length&&e.getCanMultiSort()&&o?l?p="toggle":p="add":i!=null&&i.length&&d!==i.length-1?p="replace":l?p="toggle":p="replace",p==="toggle"&&(a||s||(p="remove")),p==="add"){var m;c=[...i,{id:e.id,desc:u}],c.splice(0,c.length-((m=t.options.maxMultiSortColCount)!=null?m:Number.MAX_SAFE_INTEGER))}else p==="toggle"?c=i.map(g=>g.id===e.id?{...g,desc:u}:g):p==="remove"?c=i.filter(g=>g.id!==e.id):c=[{id:e.id,desc:u}];return c})},e.getFirstSortDir=()=>{var r,o;return((r=(o=e.columnDef.sortDescFirst)!=null?o:t.options.sortDescFirst)!=null?r:e.getAutoSortDir()==="desc")?"desc":"asc"},e.getNextSortingOrder=r=>{var o,s;const a=e.getFirstSortDir(),i=e.getIsSorted();return i?i!==a&&((o=t.options.enableSortingRemoval)==null||o)&&(!(r&&(s=t.options.enableMultiRemove)!=null)||s)?!1:i==="desc"?"asc":"desc":a},e.getCanSort=()=>{var r,o;return((r=e.columnDef.enableSorting)!=null?r:!0)&&((o=t.options.enableSorting)!=null?o:!0)&&!!e.accessorFn},e.getCanMultiSort=()=>{var r,o;return(r=(o=e.columnDef.enableMultiSort)!=null?o:t.options.enableMultiSort)!=null?r:!!e.accessorFn},e.getIsSorted=()=>{var r;const o=(r=t.getState().sorting)==null?void 0:r.find(s=>s.id===e.id);return o?o.desc?"desc":"asc":!1},e.getSortIndex=()=>{var r,o;return(r=(o=t.getState().sorting)==null?void 0:o.findIndex(s=>s.id===e.id))!=null?r:-1},e.clearSorting=()=>{t.setSorting(r=>r!=null&&r.length?r.filter(o=>o.id!==e.id):[])},e.getToggleSortingHandler=()=>{const r=e.getCanSort();return o=>{r&&(o.persist==null||o.persist(),e.toggleSorting==null||e.toggleSorting(void 0,e.getCanMultiSort()?t.options.isMultiSortEvent==null?void 0:t.options.isMultiSortEvent(o):!1))}}},createTable:e=>{e.setSorting=t=>e.options.onSortingChange==null?void 0:e.options.onSortingChange(t),e.resetSorting=t=>{var r,o;e.setSorting(t?[]:(r=(o=e.initialState)==null?void 0:o.sorting)!=null?r:[])},e.getPreSortedRowModel=()=>e.getGroupedRowModel(),e.getSortedRowModel=()=>(!e._getSortedRowModel&&e.options.getSortedRowModel&&(e._getSortedRowModel=e.options.getSortedRowModel(e)),e.options.manualSorting||!e._getSortedRowModel?e.getPreSortedRowModel():e._getSortedRowModel())}},Wu=[fu,Lu,Ru,_u,gu,pu,Tu,Eu,qu,Cu,Du,Au,Fu,Vu,Pu];function Uu(e){var t,r;process.env.NODE_ENV!=="production"&&(e.debugAll||e.debugTable)&&console.info("Creating Table Instance...");const o=[...Wu,...(t=e._features)!=null?t:[]];let s={_features:o};const a=s._features.reduce((m,g)=>Object.assign(m,g.getDefaultOptions==null?void 0:g.getDefaultOptions(s)),{}),i=m=>s.options.mergeOptions?s.options.mergeOptions(a,m):{...a,...m};let d={...{},...(r=e.initialState)!=null?r:{}};s._features.forEach(m=>{var g;d=(g=m.getInitialState==null?void 0:m.getInitialState(d))!=null?g:d});const c=[];let p=!1;const u={_features:o,options:{...a,...e},initialState:d,_queue:m=>{c.push(m),p||(p=!0,Promise.resolve().then(()=>{for(;c.length;)c.shift()();p=!1}).catch(g=>setTimeout(()=>{throw g})))},reset:()=>{s.setState(s.initialState)},setOptions:m=>{const g=dt(m,s.options);s.options=i(g)},getState:()=>s.options.state,setState:m=>{s.options.onStateChange==null||s.options.onStateChange(m)},_getRowId:(m,g,h)=>{var x;return(x=s.options.getRowId==null?void 0:s.options.getRowId(m,g,h))!=null?x:`${h?[h.id,g].join("."):g}`},getCoreRowModel:()=>(s._getCoreRowModel||(s._getCoreRowModel=s.options.getCoreRowModel(s)),s._getCoreRowModel()),getRowModel:()=>s.getPaginationRowModel(),getRow:(m,g)=>{let h=(g?s.getPrePaginationRowModel():s.getRowModel()).rowsById[m];if(!h&&(h=s.getCoreRowModel().rowsById[m],!h))throw process.env.NODE_ENV!=="production"?new Error(`getRow could not find row with ID: ${m}`):new Error;return h},_getDefaultColumnDef:oe(()=>[s.options.defaultColumn],m=>{var g;return m=(g=m)!=null?g:{},{header:h=>{const x=h.header.column.columnDef;return x.accessorKey?x.accessorKey:x.accessorFn?x.id:null},cell:h=>{var x,y;return(x=(y=h.renderValue())==null||y.toString==null?void 0:y.toString())!=null?x:null},...s._features.reduce((h,x)=>Object.assign(h,x.getDefaultColumnDef==null?void 0:x.getDefaultColumnDef()),{}),...m}},se(e,"debugColumns","_getDefaultColumnDef")),_getColumnDefs:()=>s.options.columns,getAllColumns:oe(()=>[s._getColumnDefs()],m=>{const g=function(h,x,y){return y===void 0&&(y=0),h.map(b=>{const w=mu(s,b,y,x),j=b;return w.columns=j.columns?g(j.columns,w,y+1):[],w})};return g(m)},se(e,"debugColumns","getAllColumns")),getAllFlatColumns:oe(()=>[s.getAllColumns()],m=>m.flatMap(g=>g.getFlatColumns()),se(e,"debugColumns","getAllFlatColumns")),_getAllFlatColumnsById:oe(()=>[s.getAllFlatColumns()],m=>m.reduce((g,h)=>(g[h.id]=h,g),{}),se(e,"debugColumns","getAllFlatColumnsById")),getAllLeafColumns:oe(()=>[s.getAllColumns(),s._getOrderColumnsFn()],(m,g)=>{let h=m.flatMap(x=>x.getLeafColumns());return g(h)},se(e,"debugColumns","getAllLeafColumns")),getColumn:m=>{const g=s._getAllFlatColumnsById()[m];return process.env.NODE_ENV!=="production"&&!g&&console.error(`[Table] Column with id '${m}' does not exist.`),g}};Object.assign(s,u);for(let m=0;m<s._features.length;m++){const g=s._features[m];g==null||g.createTable==null||g.createTable(s)}return s}function Ku(){return e=>oe(()=>[e.options.data],t=>{const r={rows:[],flatRows:[],rowsById:{}},o=function(s,a,i){a===void 0&&(a=0);const l=[];for(let c=0;c<s.length;c++){const p=Sn(e,e._getRowId(s[c],c,i),s[c],c,a,void 0,i==null?void 0:i.id);if(r.flatRows.push(p),r.rowsById[p.id]=p,l.push(p),e.options.getSubRows){var d;p.originalSubRows=e.options.getSubRows(s[c],c),(d=p.originalSubRows)!=null&&d.length&&(p.subRows=o(p.originalSubRows,a+1,p))}}return l};return r.rows=o(t),r},se(e.options,"debugTable","getRowModel",()=>e._autoResetPageIndex()))}function Xu(e){const t=[],r=o=>{var s;t.push(o),(s=o.subRows)!=null&&s.length&&o.getIsExpanded()&&o.subRows.forEach(r)};return e.rows.forEach(r),{rows:t,flatRows:e.flatRows,rowsById:e.rowsById}}function Yu(e,t,r){return r.options.filterFromLeafRows?Zu(e,t,r):Ju(e,t,r)}function Zu(e,t,r){var o;const s=[],a={},i=(o=r.options.maxLeafRowFilterDepth)!=null?o:100,l=function(d,c){c===void 0&&(c=0);const p=[];for(let m=0;m<d.length;m++){var u;let g=d[m];const h=Sn(r,g.id,g.original,g.index,g.depth,void 0,g.parentId);if(h.columnFilters=g.columnFilters,(u=g.subRows)!=null&&u.length&&c<i){if(h.subRows=l(g.subRows,c+1),g=h,t(g)&&!h.subRows.length){p.push(g),a[g.id]=g,s.push(g);continue}if(t(g)||h.subRows.length){p.push(g),a[g.id]=g,s.push(g);continue}}else g=h,t(g)&&(p.push(g),a[g.id]=g,s.push(g))}return p};return{rows:l(e),flatRows:s,rowsById:a}}function Ju(e,t,r){var o;const s=[],a={},i=(o=r.options.maxLeafRowFilterDepth)!=null?o:100,l=function(d,c){c===void 0&&(c=0);const p=[];for(let m=0;m<d.length;m++){let g=d[m];if(t(g)){var u;if((u=g.subRows)!=null&&u.length&&c<i){const x=Sn(r,g.id,g.original,g.index,g.depth,void 0,g.parentId);x.subRows=l(g.subRows,c+1),g=x}p.push(g),s.push(g),a[g.id]=g}}return p};return{rows:l(e),flatRows:s,rowsById:a}}function Qu(){return e=>oe(()=>[e.getPreFilteredRowModel(),e.getState().columnFilters,e.getState().globalFilter],(t,r,o)=>{if(!t.rows.length||!(r!=null&&r.length)&&!o){for(let m=0;m<t.flatRows.length;m++)t.flatRows[m].columnFilters={},t.flatRows[m].columnFiltersMeta={};return t}const s=[],a=[];(r??[]).forEach(m=>{var g;const h=e.getColumn(m.id);if(!h)return;const x=h.getFilterFn();if(!x){process.env.NODE_ENV!=="production"&&console.warn(`Could not find a valid 'column.filterFn' for column with the ID: ${h.id}.`);return}s.push({id:m.id,filterFn:x,resolvedValue:(g=x.resolveFilterValue==null?void 0:x.resolveFilterValue(m.value))!=null?g:m.value})});const i=(r??[]).map(m=>m.id),l=e.getGlobalFilterFn(),d=e.getAllLeafColumns().filter(m=>m.getCanGlobalFilter());o&&l&&d.length&&(i.push("__global__"),d.forEach(m=>{var g;a.push({id:m.id,filterFn:l,resolvedValue:(g=l.resolveFilterValue==null?void 0:l.resolveFilterValue(o))!=null?g:o})}));let c,p;for(let m=0;m<t.flatRows.length;m++){const g=t.flatRows[m];if(g.columnFilters={},s.length)for(let h=0;h<s.length;h++){c=s[h];const x=c.id;g.columnFilters[x]=c.filterFn(g,x,c.resolvedValue,y=>{g.columnFiltersMeta[x]=y})}if(a.length){for(let h=0;h<a.length;h++){p=a[h];const x=p.id;if(p.filterFn(g,x,p.resolvedValue,y=>{g.columnFiltersMeta[x]=y})){g.columnFilters.__global__=!0;break}}g.columnFilters.__global__!==!0&&(g.columnFilters.__global__=!1)}}const u=m=>{for(let g=0;g<i.length;g++)if(m.columnFilters[i[g]]===!1)return!1;return!0};return Yu(t.rows,u,e)},se(e.options,"debugTable","getFilteredRowModel",()=>e._autoResetPageIndex()))}function em(e){return t=>oe(()=>[t.getState().pagination,t.getPrePaginationRowModel(),t.options.paginateExpandedRows?void 0:t.getState().expanded],(r,o)=>{if(!o.rows.length)return o;const{pageSize:s,pageIndex:a}=r;let{rows:i,flatRows:l,rowsById:d}=o;const c=s*a,p=c+s;i=i.slice(c,p);let u;t.options.paginateExpandedRows?u={rows:i,flatRows:l,rowsById:d}:u=Xu({rows:i,flatRows:l,rowsById:d}),u.flatRows=[];const m=g=>{u.flatRows.push(g),g.subRows.length&&g.subRows.forEach(m)};return u.rows.forEach(m),u},se(t.options,"debugTable","getPaginationRowModel"))}function tm(){return e=>oe(()=>[e.getState().sorting,e.getPreSortedRowModel()],(t,r)=>{if(!r.rows.length||!(t!=null&&t.length))return r;const o=e.getState().sorting,s=[],a=o.filter(d=>{var c;return(c=e.getColumn(d.id))==null?void 0:c.getCanSort()}),i={};a.forEach(d=>{const c=e.getColumn(d.id);c&&(i[d.id]={sortUndefined:c.columnDef.sortUndefined,invertSorting:c.columnDef.invertSorting,sortingFn:c.getSortingFn()})});const l=d=>{const c=d.map(p=>({...p}));return c.sort((p,u)=>{for(let g=0;g<a.length;g+=1){var m;const h=a[g],x=i[h.id],y=x.sortUndefined,b=(m=h==null?void 0:h.desc)!=null?m:!1;let w=0;if(y){const j=p.getValue(h.id),M=u.getValue(h.id),R=j===void 0,_=M===void 0;if(R||_){if(y==="first")return R?-1:1;if(y==="last")return R?1:-1;w=R&&_?0:R?y:-y}}if(w===0&&(w=x.sortingFn(p,u,h.id)),w!==0)return b&&(w*=-1),x.invertSorting&&(w*=-1),w}return p.index-u.index}),c.forEach(p=>{var u;s.push(p),(u=p.subRows)!=null&&u.length&&(p.subRows=l(p.subRows))}),c};return{rows:l(r.rows),flatRows:s,rowsById:r.rowsById}},se(e.options,"debugTable","getSortedRowModel",()=>e._autoResetPageIndex()))}/**
24
+ color: hsl(${Math.max(0,Math.min(120-120*h,120))}deg 100% 31%);`,t==null?void 0:t.key)}return n}}function me(r,e,t,s){return{debug:()=>{var n;return(n=r==null?void 0:r.debugAll)!=null?n:r[e]},key:process.env.NODE_ENV==="development"&&t,onChange:s}}function Y0(r,e,t,s){const n=()=>{var o;return(o=i.getValue())!=null?o:r.options.renderFallbackValue},i={id:`${e.id}_${t.id}`,row:e,column:t,getValue:()=>e.getValue(s),renderValue:n,getContext:ge(()=>[r,t,e,i],(o,a,c,l)=>({table:o,column:a,row:c,cell:l,getValue:l.getValue,renderValue:l.renderValue}),me(r.options,"debugCells","cell.getContext"))};return r._features.forEach(o=>{o.createCell==null||o.createCell(i,t,e,r)},{}),i}function q0(r,e,t,s){var n,i;const a={...r._getDefaultColumnDef(),...e},c=a.accessorKey;let l=(n=(i=a.id)!=null?i:c?typeof String.prototype.replaceAll=="function"?c.replaceAll(".","_"):c.replace(/\./g,"_"):void 0)!=null?n:typeof a.header=="string"?a.header:void 0,d;if(a.accessorFn?d=a.accessorFn:c&&(c.includes(".")?d=h=>{let g=h;for(const p of c.split(".")){var m;g=(m=g)==null?void 0:m[p],process.env.NODE_ENV!=="production"&&g===void 0&&console.warn(`"${p}" in deeply nested key "${c}" returned undefined.`)}return g}:d=h=>h[a.accessorKey]),!l)throw process.env.NODE_ENV!=="production"?new Error(a.accessorFn?"Columns require an id when using an accessorFn":"Columns require an id when using a non-string header"):new Error;let u={id:`${String(l)}`,accessorFn:d,parent:s,depth:t,columnDef:a,columns:[],getFlatColumns:ge(()=>[!0],()=>{var h;return[u,...(h=u.columns)==null?void 0:h.flatMap(g=>g.getFlatColumns())]},me(r.options,"debugColumns","column.getFlatColumns")),getLeafColumns:ge(()=>[r._getOrderColumnsFn()],h=>{var g;if((g=u.columns)!=null&&g.length){let m=u.columns.flatMap(p=>p.getLeafColumns());return h(m)}return[u]},me(r.options,"debugColumns","column.getLeafColumns"))};for(const h of r._features)h.createColumn==null||h.createColumn(u,r);return u}const ut="debugHeaders";function Fa(r,e,t){var s;let i={id:(s=t.id)!=null?s:e.id,column:e,index:t.index,isPlaceholder:!!t.isPlaceholder,placeholderId:t.placeholderId,depth:t.depth,subHeaders:[],colSpan:0,rowSpan:0,headerGroup:null,getLeafHeaders:()=>{const o=[],a=c=>{c.subHeaders&&c.subHeaders.length&&c.subHeaders.map(a),o.push(c)};return a(i),o},getContext:()=>({table:r,header:i,column:e})};return r._features.forEach(o=>{o.createHeader==null||o.createHeader(i,r)}),i}const X0={createTable:r=>{r.getHeaderGroups=ge(()=>[r.getAllColumns(),r.getVisibleLeafColumns(),r.getState().columnPinning.left,r.getState().columnPinning.right],(e,t,s,n)=>{var i,o;const a=(i=s==null?void 0:s.map(u=>t.find(h=>h.id===u)).filter(Boolean))!=null?i:[],c=(o=n==null?void 0:n.map(u=>t.find(h=>h.id===u)).filter(Boolean))!=null?o:[],l=t.filter(u=>!(s!=null&&s.includes(u.id))&&!(n!=null&&n.includes(u.id)));return zr(e,[...a,...l,...c],r)},me(r.options,ut,"getHeaderGroups")),r.getCenterHeaderGroups=ge(()=>[r.getAllColumns(),r.getVisibleLeafColumns(),r.getState().columnPinning.left,r.getState().columnPinning.right],(e,t,s,n)=>(t=t.filter(i=>!(s!=null&&s.includes(i.id))&&!(n!=null&&n.includes(i.id))),zr(e,t,r,"center")),me(r.options,ut,"getCenterHeaderGroups")),r.getLeftHeaderGroups=ge(()=>[r.getAllColumns(),r.getVisibleLeafColumns(),r.getState().columnPinning.left],(e,t,s)=>{var n;const i=(n=s==null?void 0:s.map(o=>t.find(a=>a.id===o)).filter(Boolean))!=null?n:[];return zr(e,i,r,"left")},me(r.options,ut,"getLeftHeaderGroups")),r.getRightHeaderGroups=ge(()=>[r.getAllColumns(),r.getVisibleLeafColumns(),r.getState().columnPinning.right],(e,t,s)=>{var n;const i=(n=s==null?void 0:s.map(o=>t.find(a=>a.id===o)).filter(Boolean))!=null?n:[];return zr(e,i,r,"right")},me(r.options,ut,"getRightHeaderGroups")),r.getFooterGroups=ge(()=>[r.getHeaderGroups()],e=>[...e].reverse(),me(r.options,ut,"getFooterGroups")),r.getLeftFooterGroups=ge(()=>[r.getLeftHeaderGroups()],e=>[...e].reverse(),me(r.options,ut,"getLeftFooterGroups")),r.getCenterFooterGroups=ge(()=>[r.getCenterHeaderGroups()],e=>[...e].reverse(),me(r.options,ut,"getCenterFooterGroups")),r.getRightFooterGroups=ge(()=>[r.getRightHeaderGroups()],e=>[...e].reverse(),me(r.options,ut,"getRightFooterGroups")),r.getFlatHeaders=ge(()=>[r.getHeaderGroups()],e=>e.map(t=>t.headers).flat(),me(r.options,ut,"getFlatHeaders")),r.getLeftFlatHeaders=ge(()=>[r.getLeftHeaderGroups()],e=>e.map(t=>t.headers).flat(),me(r.options,ut,"getLeftFlatHeaders")),r.getCenterFlatHeaders=ge(()=>[r.getCenterHeaderGroups()],e=>e.map(t=>t.headers).flat(),me(r.options,ut,"getCenterFlatHeaders")),r.getRightFlatHeaders=ge(()=>[r.getRightHeaderGroups()],e=>e.map(t=>t.headers).flat(),me(r.options,ut,"getRightFlatHeaders")),r.getCenterLeafHeaders=ge(()=>[r.getCenterFlatHeaders()],e=>e.filter(t=>{var s;return!((s=t.subHeaders)!=null&&s.length)}),me(r.options,ut,"getCenterLeafHeaders")),r.getLeftLeafHeaders=ge(()=>[r.getLeftFlatHeaders()],e=>e.filter(t=>{var s;return!((s=t.subHeaders)!=null&&s.length)}),me(r.options,ut,"getLeftLeafHeaders")),r.getRightLeafHeaders=ge(()=>[r.getRightFlatHeaders()],e=>e.filter(t=>{var s;return!((s=t.subHeaders)!=null&&s.length)}),me(r.options,ut,"getRightLeafHeaders")),r.getLeafHeaders=ge(()=>[r.getLeftHeaderGroups(),r.getCenterHeaderGroups(),r.getRightHeaderGroups()],(e,t,s)=>{var n,i,o,a,c,l;return[...(n=(i=e[0])==null?void 0:i.headers)!=null?n:[],...(o=(a=t[0])==null?void 0:a.headers)!=null?o:[],...(c=(l=s[0])==null?void 0:l.headers)!=null?c:[]].map(d=>d.getLeafHeaders()).flat()},me(r.options,ut,"getLeafHeaders"))}};function zr(r,e,t,s){var n,i;let o=0;const a=function(h,g){g===void 0&&(g=1),o=Math.max(o,g),h.filter(m=>m.getIsVisible()).forEach(m=>{var p;(p=m.columns)!=null&&p.length&&a(m.columns,g+1)},0)};a(r);let c=[];const l=(h,g)=>{const m={depth:g,id:[s,`${g}`].filter(Boolean).join("_"),headers:[]},p=[];h.forEach(x=>{const v=[...p].reverse()[0],y=x.column.depth===m.depth;let b,T=!1;if(y&&x.column.parent?b=x.column.parent:(b=x.column,T=!0),v&&(v==null?void 0:v.column)===b)v.subHeaders.push(x);else{const R=Fa(t,b,{id:[s,g,b.id,x==null?void 0:x.id].filter(Boolean).join("_"),isPlaceholder:T,placeholderId:T?`${p.filter(_=>_.column===b).length}`:void 0,depth:g,index:p.length});R.subHeaders.push(x),p.push(R)}m.headers.push(x),x.headerGroup=m}),c.push(m),g>0&&l(p,g-1)},d=e.map((h,g)=>Fa(t,h,{depth:o,index:g}));l(d,o-1),c.reverse();const u=h=>h.filter(m=>m.column.getIsVisible()).map(m=>{let p=0,x=0,v=[0];m.subHeaders&&m.subHeaders.length?(v=[],u(m.subHeaders).forEach(b=>{let{colSpan:T,rowSpan:R}=b;p+=T,v.push(R)})):p=1;const y=Math.min(...v);return x=x+y,m.colSpan=p,m.rowSpan=x,{colSpan:p,rowSpan:x}});return u((n=(i=c[0])==null?void 0:i.headers)!=null?n:[]),c}const Vo=(r,e,t,s,n,i,o)=>{let a={id:e,index:s,original:t,depth:n,parentId:o,_valuesCache:{},_uniqueValuesCache:{},getValue:c=>{if(a._valuesCache.hasOwnProperty(c))return a._valuesCache[c];const l=r.getColumn(c);if(l!=null&&l.accessorFn)return a._valuesCache[c]=l.accessorFn(a.original,s),a._valuesCache[c]},getUniqueValues:c=>{if(a._uniqueValuesCache.hasOwnProperty(c))return a._uniqueValuesCache[c];const l=r.getColumn(c);if(l!=null&&l.accessorFn)return l.columnDef.getUniqueValues?(a._uniqueValuesCache[c]=l.columnDef.getUniqueValues(a.original,s),a._uniqueValuesCache[c]):(a._uniqueValuesCache[c]=[a.getValue(c)],a._uniqueValuesCache[c])},renderValue:c=>{var l;return(l=a.getValue(c))!=null?l:r.options.renderFallbackValue},subRows:[],getLeafRows:()=>W0(a.subRows,c=>c.subRows),getParentRow:()=>a.parentId?r.getRow(a.parentId,!0):void 0,getParentRows:()=>{let c=[],l=a;for(;;){const d=l.getParentRow();if(!d)break;c.push(d),l=d}return c.reverse()},getAllCells:ge(()=>[r.getAllLeafColumns()],c=>c.map(l=>Y0(r,a,l,l.id)),me(r.options,"debugRows","getAllCells")),_getAllCellsByColumnId:ge(()=>[a.getAllCells()],c=>c.reduce((l,d)=>(l[d.column.id]=d,l),{}),me(r.options,"debugRows","getAllCellsByColumnId"))};for(let c=0;c<r._features.length;c++){const l=r._features[c];l==null||l.createRow==null||l.createRow(a,r)}return a},Q0={createColumn:(r,e)=>{r._getFacetedRowModel=e.options.getFacetedRowModel&&e.options.getFacetedRowModel(e,r.id),r.getFacetedRowModel=()=>r._getFacetedRowModel?r._getFacetedRowModel():e.getPreFilteredRowModel(),r._getFacetedUniqueValues=e.options.getFacetedUniqueValues&&e.options.getFacetedUniqueValues(e,r.id),r.getFacetedUniqueValues=()=>r._getFacetedUniqueValues?r._getFacetedUniqueValues():new Map,r._getFacetedMinMaxValues=e.options.getFacetedMinMaxValues&&e.options.getFacetedMinMaxValues(e,r.id),r.getFacetedMinMaxValues=()=>{if(r._getFacetedMinMaxValues)return r._getFacetedMinMaxValues()}}},Bu=(r,e,t)=>{var s,n;const i=t==null||(s=t.toString())==null?void 0:s.toLowerCase();return!!(!((n=r.getValue(e))==null||(n=n.toString())==null||(n=n.toLowerCase())==null)&&n.includes(i))};Bu.autoRemove=r=>Wt(r);const $u=(r,e,t)=>{var s;return!!(!((s=r.getValue(e))==null||(s=s.toString())==null)&&s.includes(t))};$u.autoRemove=r=>Wt(r);const Uu=(r,e,t)=>{var s;return((s=r.getValue(e))==null||(s=s.toString())==null?void 0:s.toLowerCase())===(t==null?void 0:t.toLowerCase())};Uu.autoRemove=r=>Wt(r);const Gu=(r,e,t)=>{var s;return(s=r.getValue(e))==null?void 0:s.includes(t)};Gu.autoRemove=r=>Wt(r);const Vu=(r,e,t)=>!t.some(s=>{var n;return!((n=r.getValue(e))!=null&&n.includes(s))});Vu.autoRemove=r=>Wt(r)||!(r!=null&&r.length);const Hu=(r,e,t)=>t.some(s=>{var n;return(n=r.getValue(e))==null?void 0:n.includes(s)});Hu.autoRemove=r=>Wt(r)||!(r!=null&&r.length);const Ku=(r,e,t)=>r.getValue(e)===t;Ku.autoRemove=r=>Wt(r);const zu=(r,e,t)=>r.getValue(e)==t;zu.autoRemove=r=>Wt(r);const Ho=(r,e,t)=>{let[s,n]=t;const i=r.getValue(e);return i>=s&&i<=n};Ho.resolveFilterValue=r=>{let[e,t]=r,s=typeof e!="number"?parseFloat(e):e,n=typeof t!="number"?parseFloat(t):t,i=e===null||Number.isNaN(s)?-1/0:s,o=t===null||Number.isNaN(n)?1/0:n;if(i>o){const a=i;i=o,o=a}return[i,o]};Ho.autoRemove=r=>Wt(r)||Wt(r[0])&&Wt(r[1]);const cs={includesString:Bu,includesStringSensitive:$u,equalsString:Uu,arrIncludes:Gu,arrIncludesAll:Vu,arrIncludesSome:Hu,equals:Ku,weakEquals:zu,inNumberRange:Ho};function Wt(r){return r==null||r===""}const Z0={getDefaultColumnDef:()=>({filterFn:"auto"}),getInitialState:r=>({columnFilters:[],...r}),getDefaultOptions:r=>({onColumnFiltersChange:Nt("columnFilters",r),filterFromLeafRows:!1,maxLeafRowFilterDepth:100}),createColumn:(r,e)=>{r.getAutoFilterFn=()=>{const t=e.getCoreRowModel().flatRows[0],s=t==null?void 0:t.getValue(r.id);return typeof s=="string"?cs.includesString:typeof s=="number"?cs.inNumberRange:typeof s=="boolean"||s!==null&&typeof s=="object"?cs.equals:Array.isArray(s)?cs.arrIncludes:cs.weakEquals},r.getFilterFn=()=>{var t,s;return Vn(r.columnDef.filterFn)?r.columnDef.filterFn:r.columnDef.filterFn==="auto"?r.getAutoFilterFn():(t=(s=e.options.filterFns)==null?void 0:s[r.columnDef.filterFn])!=null?t:cs[r.columnDef.filterFn]},r.getCanFilter=()=>{var t,s,n;return((t=r.columnDef.enableColumnFilter)!=null?t:!0)&&((s=e.options.enableColumnFilters)!=null?s:!0)&&((n=e.options.enableFilters)!=null?n:!0)&&!!r.accessorFn},r.getIsFiltered=()=>r.getFilterIndex()>-1,r.getFilterValue=()=>{var t;return(t=e.getState().columnFilters)==null||(t=t.find(s=>s.id===r.id))==null?void 0:t.value},r.getFilterIndex=()=>{var t,s;return(t=(s=e.getState().columnFilters)==null?void 0:s.findIndex(n=>n.id===r.id))!=null?t:-1},r.setFilterValue=t=>{e.setColumnFilters(s=>{const n=r.getFilterFn(),i=s==null?void 0:s.find(d=>d.id===r.id),o=ys(t,i?i.value:void 0);if(Oa(n,o,r)){var a;return(a=s==null?void 0:s.filter(d=>d.id!==r.id))!=null?a:[]}const c={id:r.id,value:o};if(i){var l;return(l=s==null?void 0:s.map(d=>d.id===r.id?c:d))!=null?l:[]}return s!=null&&s.length?[...s,c]:[c]})}},createRow:(r,e)=>{r.columnFilters={},r.columnFiltersMeta={}},createTable:r=>{r.setColumnFilters=e=>{const t=r.getAllLeafColumns(),s=n=>{var i;return(i=ys(e,n))==null?void 0:i.filter(o=>{const a=t.find(c=>c.id===o.id);if(a){const c=a.getFilterFn();if(Oa(c,o.value,a))return!1}return!0})};r.options.onColumnFiltersChange==null||r.options.onColumnFiltersChange(s)},r.resetColumnFilters=e=>{var t,s;r.setColumnFilters(e?[]:(t=(s=r.initialState)==null?void 0:s.columnFilters)!=null?t:[])},r.getPreFilteredRowModel=()=>r.getCoreRowModel(),r.getFilteredRowModel=()=>(!r._getFilteredRowModel&&r.options.getFilteredRowModel&&(r._getFilteredRowModel=r.options.getFilteredRowModel(r)),r.options.manualFiltering||!r._getFilteredRowModel?r.getPreFilteredRowModel():r._getFilteredRowModel())}};function Oa(r,e,t){return(r&&r.autoRemove?r.autoRemove(e,t):!1)||typeof e>"u"||typeof e=="string"&&!e}const J0=(r,e,t)=>t.reduce((s,n)=>{const i=n.getValue(r);return s+(typeof i=="number"?i:0)},0),ex=(r,e,t)=>{let s;return t.forEach(n=>{const i=n.getValue(r);i!=null&&(s>i||s===void 0&&i>=i)&&(s=i)}),s},tx=(r,e,t)=>{let s;return t.forEach(n=>{const i=n.getValue(r);i!=null&&(s<i||s===void 0&&i>=i)&&(s=i)}),s},sx=(r,e,t)=>{let s,n;return t.forEach(i=>{const o=i.getValue(r);o!=null&&(s===void 0?o>=o&&(s=n=o):(s>o&&(s=o),n<o&&(n=o)))}),[s,n]},rx=(r,e)=>{let t=0,s=0;if(e.forEach(n=>{let i=n.getValue(r);i!=null&&(i=+i)>=i&&(++t,s+=i)}),t)return s/t},nx=(r,e)=>{if(!e.length)return;const t=e.map(i=>i.getValue(r));if(!z0(t))return;if(t.length===1)return t[0];const s=Math.floor(t.length/2),n=t.sort((i,o)=>i-o);return t.length%2!==0?n[s]:(n[s-1]+n[s])/2},ix=(r,e)=>Array.from(new Set(e.map(t=>t.getValue(r))).values()),ox=(r,e)=>new Set(e.map(t=>t.getValue(r))).size,ax=(r,e)=>e.length,Zn={sum:J0,min:ex,max:tx,extent:sx,mean:rx,median:nx,unique:ix,uniqueCount:ox,count:ax},lx={getDefaultColumnDef:()=>({aggregatedCell:r=>{var e,t;return(e=(t=r.getValue())==null||t.toString==null?void 0:t.toString())!=null?e:null},aggregationFn:"auto"}),getInitialState:r=>({grouping:[],...r}),getDefaultOptions:r=>({onGroupingChange:Nt("grouping",r),groupedColumnMode:"reorder"}),createColumn:(r,e)=>{r.toggleGrouping=()=>{e.setGrouping(t=>t!=null&&t.includes(r.id)?t.filter(s=>s!==r.id):[...t??[],r.id])},r.getCanGroup=()=>{var t,s;return((t=r.columnDef.enableGrouping)!=null?t:!0)&&((s=e.options.enableGrouping)!=null?s:!0)&&(!!r.accessorFn||!!r.columnDef.getGroupingValue)},r.getIsGrouped=()=>{var t;return(t=e.getState().grouping)==null?void 0:t.includes(r.id)},r.getGroupedIndex=()=>{var t;return(t=e.getState().grouping)==null?void 0:t.indexOf(r.id)},r.getToggleGroupingHandler=()=>{const t=r.getCanGroup();return()=>{t&&r.toggleGrouping()}},r.getAutoAggregationFn=()=>{const t=e.getCoreRowModel().flatRows[0],s=t==null?void 0:t.getValue(r.id);if(typeof s=="number")return Zn.sum;if(Object.prototype.toString.call(s)==="[object Date]")return Zn.extent},r.getAggregationFn=()=>{var t,s;if(!r)throw new Error;return Vn(r.columnDef.aggregationFn)?r.columnDef.aggregationFn:r.columnDef.aggregationFn==="auto"?r.getAutoAggregationFn():(t=(s=e.options.aggregationFns)==null?void 0:s[r.columnDef.aggregationFn])!=null?t:Zn[r.columnDef.aggregationFn]}},createTable:r=>{r.setGrouping=e=>r.options.onGroupingChange==null?void 0:r.options.onGroupingChange(e),r.resetGrouping=e=>{var t,s;r.setGrouping(e?[]:(t=(s=r.initialState)==null?void 0:s.grouping)!=null?t:[])},r.getPreGroupedRowModel=()=>r.getFilteredRowModel(),r.getGroupedRowModel=()=>(!r._getGroupedRowModel&&r.options.getGroupedRowModel&&(r._getGroupedRowModel=r.options.getGroupedRowModel(r)),r.options.manualGrouping||!r._getGroupedRowModel?r.getPreGroupedRowModel():r._getGroupedRowModel())},createRow:(r,e)=>{r.getIsGrouped=()=>!!r.groupingColumnId,r.getGroupingValue=t=>{if(r._groupingValuesCache.hasOwnProperty(t))return r._groupingValuesCache[t];const s=e.getColumn(t);return s!=null&&s.columnDef.getGroupingValue?(r._groupingValuesCache[t]=s.columnDef.getGroupingValue(r.original),r._groupingValuesCache[t]):r.getValue(t)},r._groupingValuesCache={}},createCell:(r,e,t,s)=>{r.getIsGrouped=()=>e.getIsGrouped()&&e.id===t.groupingColumnId,r.getIsPlaceholder=()=>!r.getIsGrouped()&&e.getIsGrouped(),r.getIsAggregated=()=>{var n;return!r.getIsGrouped()&&!r.getIsPlaceholder()&&!!((n=t.subRows)!=null&&n.length)}}};function cx(r,e,t){if(!(e!=null&&e.length)||!t)return r;const s=r.filter(i=>!e.includes(i.id));return t==="remove"?s:[...e.map(i=>r.find(o=>o.id===i)).filter(Boolean),...s]}const dx={getInitialState:r=>({columnOrder:[],...r}),getDefaultOptions:r=>({onColumnOrderChange:Nt("columnOrder",r)}),createColumn:(r,e)=>{r.getIndex=ge(t=>[br(e,t)],t=>t.findIndex(s=>s.id===r.id),me(e.options,"debugColumns","getIndex")),r.getIsFirstColumn=t=>{var s;return((s=br(e,t)[0])==null?void 0:s.id)===r.id},r.getIsLastColumn=t=>{var s;const n=br(e,t);return((s=n[n.length-1])==null?void 0:s.id)===r.id}},createTable:r=>{r.setColumnOrder=e=>r.options.onColumnOrderChange==null?void 0:r.options.onColumnOrderChange(e),r.resetColumnOrder=e=>{var t;r.setColumnOrder(e?[]:(t=r.initialState.columnOrder)!=null?t:[])},r._getOrderColumnsFn=ge(()=>[r.getState().columnOrder,r.getState().grouping,r.options.groupedColumnMode],(e,t,s)=>n=>{let i=[];if(!(e!=null&&e.length))i=n;else{const o=[...e],a=[...n];for(;a.length&&o.length;){const c=o.shift(),l=a.findIndex(d=>d.id===c);l>-1&&i.push(a.splice(l,1)[0])}i=[...i,...a]}return cx(i,t,s)},me(r.options,"debugTable","_getOrderColumnsFn"))}},Jn=()=>({left:[],right:[]}),ux={getInitialState:r=>({columnPinning:Jn(),...r}),getDefaultOptions:r=>({onColumnPinningChange:Nt("columnPinning",r)}),createColumn:(r,e)=>{r.pin=t=>{const s=r.getLeafColumns().map(n=>n.id).filter(Boolean);e.setColumnPinning(n=>{var i,o;if(t==="right"){var a,c;return{left:((a=n==null?void 0:n.left)!=null?a:[]).filter(u=>!(s!=null&&s.includes(u))),right:[...((c=n==null?void 0:n.right)!=null?c:[]).filter(u=>!(s!=null&&s.includes(u))),...s]}}if(t==="left"){var l,d;return{left:[...((l=n==null?void 0:n.left)!=null?l:[]).filter(u=>!(s!=null&&s.includes(u))),...s],right:((d=n==null?void 0:n.right)!=null?d:[]).filter(u=>!(s!=null&&s.includes(u)))}}return{left:((i=n==null?void 0:n.left)!=null?i:[]).filter(u=>!(s!=null&&s.includes(u))),right:((o=n==null?void 0:n.right)!=null?o:[]).filter(u=>!(s!=null&&s.includes(u)))}})},r.getCanPin=()=>r.getLeafColumns().some(s=>{var n,i,o;return((n=s.columnDef.enablePinning)!=null?n:!0)&&((i=(o=e.options.enableColumnPinning)!=null?o:e.options.enablePinning)!=null?i:!0)}),r.getIsPinned=()=>{const t=r.getLeafColumns().map(a=>a.id),{left:s,right:n}=e.getState().columnPinning,i=t.some(a=>s==null?void 0:s.includes(a)),o=t.some(a=>n==null?void 0:n.includes(a));return i?"left":o?"right":!1},r.getPinnedIndex=()=>{var t,s;const n=r.getIsPinned();return n?(t=(s=e.getState().columnPinning)==null||(s=s[n])==null?void 0:s.indexOf(r.id))!=null?t:-1:0}},createRow:(r,e)=>{r.getCenterVisibleCells=ge(()=>[r._getAllVisibleCells(),e.getState().columnPinning.left,e.getState().columnPinning.right],(t,s,n)=>{const i=[...s??[],...n??[]];return t.filter(o=>!i.includes(o.column.id))},me(e.options,"debugRows","getCenterVisibleCells")),r.getLeftVisibleCells=ge(()=>[r._getAllVisibleCells(),e.getState().columnPinning.left],(t,s)=>(s??[]).map(i=>t.find(o=>o.column.id===i)).filter(Boolean).map(i=>({...i,position:"left"})),me(e.options,"debugRows","getLeftVisibleCells")),r.getRightVisibleCells=ge(()=>[r._getAllVisibleCells(),e.getState().columnPinning.right],(t,s)=>(s??[]).map(i=>t.find(o=>o.column.id===i)).filter(Boolean).map(i=>({...i,position:"right"})),me(e.options,"debugRows","getRightVisibleCells"))},createTable:r=>{r.setColumnPinning=e=>r.options.onColumnPinningChange==null?void 0:r.options.onColumnPinningChange(e),r.resetColumnPinning=e=>{var t,s;return r.setColumnPinning(e?Jn():(t=(s=r.initialState)==null?void 0:s.columnPinning)!=null?t:Jn())},r.getIsSomeColumnsPinned=e=>{var t;const s=r.getState().columnPinning;if(!e){var n,i;return!!((n=s.left)!=null&&n.length||(i=s.right)!=null&&i.length)}return!!((t=s[e])!=null&&t.length)},r.getLeftLeafColumns=ge(()=>[r.getAllLeafColumns(),r.getState().columnPinning.left],(e,t)=>(t??[]).map(s=>e.find(n=>n.id===s)).filter(Boolean),me(r.options,"debugColumns","getLeftLeafColumns")),r.getRightLeafColumns=ge(()=>[r.getAllLeafColumns(),r.getState().columnPinning.right],(e,t)=>(t??[]).map(s=>e.find(n=>n.id===s)).filter(Boolean),me(r.options,"debugColumns","getRightLeafColumns")),r.getCenterLeafColumns=ge(()=>[r.getAllLeafColumns(),r.getState().columnPinning.left,r.getState().columnPinning.right],(e,t,s)=>{const n=[...t??[],...s??[]];return e.filter(i=>!n.includes(i.id))},me(r.options,"debugColumns","getCenterLeafColumns"))}};function fx(r){return r||(typeof document<"u"?document:null)}const Wr={size:150,minSize:20,maxSize:Number.MAX_SAFE_INTEGER},ei=()=>({startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,isResizingColumn:!1,columnSizingStart:[]}),hx={getDefaultColumnDef:()=>Wr,getInitialState:r=>({columnSizing:{},columnSizingInfo:ei(),...r}),getDefaultOptions:r=>({columnResizeMode:"onEnd",columnResizeDirection:"ltr",onColumnSizingChange:Nt("columnSizing",r),onColumnSizingInfoChange:Nt("columnSizingInfo",r)}),createColumn:(r,e)=>{r.getSize=()=>{var t,s,n;const i=e.getState().columnSizing[r.id];return Math.min(Math.max((t=r.columnDef.minSize)!=null?t:Wr.minSize,(s=i??r.columnDef.size)!=null?s:Wr.size),(n=r.columnDef.maxSize)!=null?n:Wr.maxSize)},r.getStart=ge(t=>[t,br(e,t),e.getState().columnSizing],(t,s)=>s.slice(0,r.getIndex(t)).reduce((n,i)=>n+i.getSize(),0),me(e.options,"debugColumns","getStart")),r.getAfter=ge(t=>[t,br(e,t),e.getState().columnSizing],(t,s)=>s.slice(r.getIndex(t)+1).reduce((n,i)=>n+i.getSize(),0),me(e.options,"debugColumns","getAfter")),r.resetSize=()=>{e.setColumnSizing(t=>{let{[r.id]:s,...n}=t;return n})},r.getCanResize=()=>{var t,s;return((t=r.columnDef.enableResizing)!=null?t:!0)&&((s=e.options.enableColumnResizing)!=null?s:!0)},r.getIsResizing=()=>e.getState().columnSizingInfo.isResizingColumn===r.id},createHeader:(r,e)=>{r.getSize=()=>{let t=0;const s=n=>{if(n.subHeaders.length)n.subHeaders.forEach(s);else{var i;t+=(i=n.column.getSize())!=null?i:0}};return s(r),t},r.getStart=()=>{if(r.index>0){const t=r.headerGroup.headers[r.index-1];return t.getStart()+t.getSize()}return 0},r.getResizeHandler=t=>{const s=e.getColumn(r.column.id),n=s==null?void 0:s.getCanResize();return i=>{if(!s||!n||(i.persist==null||i.persist(),ti(i)&&i.touches&&i.touches.length>1))return;const o=r.getSize(),a=r?r.getLeafHeaders().map(v=>[v.column.id,v.column.getSize()]):[[s.id,s.getSize()]],c=ti(i)?Math.round(i.touches[0].clientX):i.clientX,l={},d=(v,y)=>{typeof y=="number"&&(e.setColumnSizingInfo(b=>{var T,R;const _=e.options.columnResizeDirection==="rtl"?-1:1,w=(y-((T=b==null?void 0:b.startOffset)!=null?T:0))*_,A=Math.max(w/((R=b==null?void 0:b.startSize)!=null?R:0),-.999999);return b.columnSizingStart.forEach(C=>{let[L,P]=C;l[L]=Math.round(Math.max(P+P*A,0)*100)/100}),{...b,deltaOffset:w,deltaPercentage:A}}),(e.options.columnResizeMode==="onChange"||v==="end")&&e.setColumnSizing(b=>({...b,...l})))},u=v=>d("move",v),h=v=>{d("end",v),e.setColumnSizingInfo(y=>({...y,isResizingColumn:!1,startOffset:null,startSize:null,deltaOffset:null,deltaPercentage:null,columnSizingStart:[]}))},g=fx(t),m={moveHandler:v=>u(v.clientX),upHandler:v=>{g==null||g.removeEventListener("mousemove",m.moveHandler),g==null||g.removeEventListener("mouseup",m.upHandler),h(v.clientX)}},p={moveHandler:v=>(v.cancelable&&(v.preventDefault(),v.stopPropagation()),u(v.touches[0].clientX),!1),upHandler:v=>{var y;g==null||g.removeEventListener("touchmove",p.moveHandler),g==null||g.removeEventListener("touchend",p.upHandler),v.cancelable&&(v.preventDefault(),v.stopPropagation()),h((y=v.touches[0])==null?void 0:y.clientX)}},x=gx()?{passive:!1}:!1;ti(i)?(g==null||g.addEventListener("touchmove",p.moveHandler,x),g==null||g.addEventListener("touchend",p.upHandler,x)):(g==null||g.addEventListener("mousemove",m.moveHandler,x),g==null||g.addEventListener("mouseup",m.upHandler,x)),e.setColumnSizingInfo(v=>({...v,startOffset:c,startSize:o,deltaOffset:0,deltaPercentage:0,columnSizingStart:a,isResizingColumn:s.id}))}}},createTable:r=>{r.setColumnSizing=e=>r.options.onColumnSizingChange==null?void 0:r.options.onColumnSizingChange(e),r.setColumnSizingInfo=e=>r.options.onColumnSizingInfoChange==null?void 0:r.options.onColumnSizingInfoChange(e),r.resetColumnSizing=e=>{var t;r.setColumnSizing(e?{}:(t=r.initialState.columnSizing)!=null?t:{})},r.resetHeaderSizeInfo=e=>{var t;r.setColumnSizingInfo(e?ei():(t=r.initialState.columnSizingInfo)!=null?t:ei())},r.getTotalSize=()=>{var e,t;return(e=(t=r.getHeaderGroups()[0])==null?void 0:t.headers.reduce((s,n)=>s+n.getSize(),0))!=null?e:0},r.getLeftTotalSize=()=>{var e,t;return(e=(t=r.getLeftHeaderGroups()[0])==null?void 0:t.headers.reduce((s,n)=>s+n.getSize(),0))!=null?e:0},r.getCenterTotalSize=()=>{var e,t;return(e=(t=r.getCenterHeaderGroups()[0])==null?void 0:t.headers.reduce((s,n)=>s+n.getSize(),0))!=null?e:0},r.getRightTotalSize=()=>{var e,t;return(e=(t=r.getRightHeaderGroups()[0])==null?void 0:t.headers.reduce((s,n)=>s+n.getSize(),0))!=null?e:0}}};let Yr=null;function gx(){if(typeof Yr=="boolean")return Yr;let r=!1;try{const e={get passive(){return r=!0,!1}},t=()=>{};window.addEventListener("test",t,e),window.removeEventListener("test",t)}catch{r=!1}return Yr=r,Yr}function ti(r){return r.type==="touchstart"}const mx={getInitialState:r=>({columnVisibility:{},...r}),getDefaultOptions:r=>({onColumnVisibilityChange:Nt("columnVisibility",r)}),createColumn:(r,e)=>{r.toggleVisibility=t=>{r.getCanHide()&&e.setColumnVisibility(s=>({...s,[r.id]:t??!r.getIsVisible()}))},r.getIsVisible=()=>{var t,s;const n=r.columns;return(t=n.length?n.some(i=>i.getIsVisible()):(s=e.getState().columnVisibility)==null?void 0:s[r.id])!=null?t:!0},r.getCanHide=()=>{var t,s;return((t=r.columnDef.enableHiding)!=null?t:!0)&&((s=e.options.enableHiding)!=null?s:!0)},r.getToggleVisibilityHandler=()=>t=>{r.toggleVisibility==null||r.toggleVisibility(t.target.checked)}},createRow:(r,e)=>{r._getAllVisibleCells=ge(()=>[r.getAllCells(),e.getState().columnVisibility],t=>t.filter(s=>s.column.getIsVisible()),me(e.options,"debugRows","_getAllVisibleCells")),r.getVisibleCells=ge(()=>[r.getLeftVisibleCells(),r.getCenterVisibleCells(),r.getRightVisibleCells()],(t,s,n)=>[...t,...s,...n],me(e.options,"debugRows","getVisibleCells"))},createTable:r=>{const e=(t,s)=>ge(()=>[s(),s().filter(n=>n.getIsVisible()).map(n=>n.id).join("_")],n=>n.filter(i=>i.getIsVisible==null?void 0:i.getIsVisible()),me(r.options,"debugColumns",t));r.getVisibleFlatColumns=e("getVisibleFlatColumns",()=>r.getAllFlatColumns()),r.getVisibleLeafColumns=e("getVisibleLeafColumns",()=>r.getAllLeafColumns()),r.getLeftVisibleLeafColumns=e("getLeftVisibleLeafColumns",()=>r.getLeftLeafColumns()),r.getRightVisibleLeafColumns=e("getRightVisibleLeafColumns",()=>r.getRightLeafColumns()),r.getCenterVisibleLeafColumns=e("getCenterVisibleLeafColumns",()=>r.getCenterLeafColumns()),r.setColumnVisibility=t=>r.options.onColumnVisibilityChange==null?void 0:r.options.onColumnVisibilityChange(t),r.resetColumnVisibility=t=>{var s;r.setColumnVisibility(t?{}:(s=r.initialState.columnVisibility)!=null?s:{})},r.toggleAllColumnsVisible=t=>{var s;t=(s=t)!=null?s:!r.getIsAllColumnsVisible(),r.setColumnVisibility(r.getAllLeafColumns().reduce((n,i)=>({...n,[i.id]:t||!(i.getCanHide!=null&&i.getCanHide())}),{}))},r.getIsAllColumnsVisible=()=>!r.getAllLeafColumns().some(t=>!(t.getIsVisible!=null&&t.getIsVisible())),r.getIsSomeColumnsVisible=()=>r.getAllLeafColumns().some(t=>t.getIsVisible==null?void 0:t.getIsVisible()),r.getToggleAllColumnsVisibilityHandler=()=>t=>{var s;r.toggleAllColumnsVisible((s=t.target)==null?void 0:s.checked)}}};function br(r,e){return e?e==="center"?r.getCenterVisibleLeafColumns():e==="left"?r.getLeftVisibleLeafColumns():r.getRightVisibleLeafColumns():r.getVisibleLeafColumns()}const px={createTable:r=>{r._getGlobalFacetedRowModel=r.options.getFacetedRowModel&&r.options.getFacetedRowModel(r,"__global__"),r.getGlobalFacetedRowModel=()=>r.options.manualFiltering||!r._getGlobalFacetedRowModel?r.getPreFilteredRowModel():r._getGlobalFacetedRowModel(),r._getGlobalFacetedUniqueValues=r.options.getFacetedUniqueValues&&r.options.getFacetedUniqueValues(r,"__global__"),r.getGlobalFacetedUniqueValues=()=>r._getGlobalFacetedUniqueValues?r._getGlobalFacetedUniqueValues():new Map,r._getGlobalFacetedMinMaxValues=r.options.getFacetedMinMaxValues&&r.options.getFacetedMinMaxValues(r,"__global__"),r.getGlobalFacetedMinMaxValues=()=>{if(r._getGlobalFacetedMinMaxValues)return r._getGlobalFacetedMinMaxValues()}}},xx={getInitialState:r=>({globalFilter:void 0,...r}),getDefaultOptions:r=>({onGlobalFilterChange:Nt("globalFilter",r),globalFilterFn:"auto",getColumnCanGlobalFilter:e=>{var t;const s=(t=r.getCoreRowModel().flatRows[0])==null||(t=t._getAllCellsByColumnId()[e.id])==null?void 0:t.getValue();return typeof s=="string"||typeof s=="number"}}),createColumn:(r,e)=>{r.getCanGlobalFilter=()=>{var t,s,n,i;return((t=r.columnDef.enableGlobalFilter)!=null?t:!0)&&((s=e.options.enableGlobalFilter)!=null?s:!0)&&((n=e.options.enableFilters)!=null?n:!0)&&((i=e.options.getColumnCanGlobalFilter==null?void 0:e.options.getColumnCanGlobalFilter(r))!=null?i:!0)&&!!r.accessorFn}},createTable:r=>{r.getGlobalAutoFilterFn=()=>cs.includesString,r.getGlobalFilterFn=()=>{var e,t;const{globalFilterFn:s}=r.options;return Vn(s)?s:s==="auto"?r.getGlobalAutoFilterFn():(e=(t=r.options.filterFns)==null?void 0:t[s])!=null?e:cs[s]},r.setGlobalFilter=e=>{r.options.onGlobalFilterChange==null||r.options.onGlobalFilterChange(e)},r.resetGlobalFilter=e=>{r.setGlobalFilter(e?void 0:r.initialState.globalFilter)}}},vx={getInitialState:r=>({expanded:{},...r}),getDefaultOptions:r=>({onExpandedChange:Nt("expanded",r),paginateExpandedRows:!0}),createTable:r=>{let e=!1,t=!1;r._autoResetExpanded=()=>{var s,n;if(!e){r._queue(()=>{e=!0});return}if((s=(n=r.options.autoResetAll)!=null?n:r.options.autoResetExpanded)!=null?s:!r.options.manualExpanding){if(t)return;t=!0,r._queue(()=>{r.resetExpanded(),t=!1})}},r.setExpanded=s=>r.options.onExpandedChange==null?void 0:r.options.onExpandedChange(s),r.toggleAllRowsExpanded=s=>{s??!r.getIsAllRowsExpanded()?r.setExpanded(!0):r.setExpanded({})},r.resetExpanded=s=>{var n,i;r.setExpanded(s?{}:(n=(i=r.initialState)==null?void 0:i.expanded)!=null?n:{})},r.getCanSomeRowsExpand=()=>r.getPrePaginationRowModel().flatRows.some(s=>s.getCanExpand()),r.getToggleAllRowsExpandedHandler=()=>s=>{s.persist==null||s.persist(),r.toggleAllRowsExpanded()},r.getIsSomeRowsExpanded=()=>{const s=r.getState().expanded;return s===!0||Object.values(s).some(Boolean)},r.getIsAllRowsExpanded=()=>{const s=r.getState().expanded;return typeof s=="boolean"?s===!0:!(!Object.keys(s).length||r.getRowModel().flatRows.some(n=>!n.getIsExpanded()))},r.getExpandedDepth=()=>{let s=0;return(r.getState().expanded===!0?Object.keys(r.getRowModel().rowsById):Object.keys(r.getState().expanded)).forEach(i=>{const o=i.split(".");s=Math.max(s,o.length)}),s},r.getPreExpandedRowModel=()=>r.getSortedRowModel(),r.getExpandedRowModel=()=>(!r._getExpandedRowModel&&r.options.getExpandedRowModel&&(r._getExpandedRowModel=r.options.getExpandedRowModel(r)),r.options.manualExpanding||!r._getExpandedRowModel?r.getPreExpandedRowModel():r._getExpandedRowModel())},createRow:(r,e)=>{r.toggleExpanded=t=>{e.setExpanded(s=>{var n;const i=s===!0?!0:!!(s!=null&&s[r.id]);let o={};if(s===!0?Object.keys(e.getRowModel().rowsById).forEach(a=>{o[a]=!0}):o=s,t=(n=t)!=null?n:!i,!i&&t)return{...o,[r.id]:!0};if(i&&!t){const{[r.id]:a,...c}=o;return c}return s})},r.getIsExpanded=()=>{var t;const s=e.getState().expanded;return!!((t=e.options.getIsRowExpanded==null?void 0:e.options.getIsRowExpanded(r))!=null?t:s===!0||s!=null&&s[r.id])},r.getCanExpand=()=>{var t,s,n;return(t=e.options.getRowCanExpand==null?void 0:e.options.getRowCanExpand(r))!=null?t:((s=e.options.enableExpanding)!=null?s:!0)&&!!((n=r.subRows)!=null&&n.length)},r.getIsAllParentsExpanded=()=>{let t=!0,s=r;for(;t&&s.parentId;)s=e.getRow(s.parentId,!0),t=s.getIsExpanded();return t},r.getToggleExpandedHandler=()=>{const t=r.getCanExpand();return()=>{t&&r.toggleExpanded()}}}},Oi=0,ji=10,si=()=>({pageIndex:Oi,pageSize:ji}),yx={getInitialState:r=>({...r,pagination:{...si(),...r==null?void 0:r.pagination}}),getDefaultOptions:r=>({onPaginationChange:Nt("pagination",r)}),createTable:r=>{let e=!1,t=!1;r._autoResetPageIndex=()=>{var s,n;if(!e){r._queue(()=>{e=!0});return}if((s=(n=r.options.autoResetAll)!=null?n:r.options.autoResetPageIndex)!=null?s:!r.options.manualPagination){if(t)return;t=!0,r._queue(()=>{r.resetPageIndex(),t=!1})}},r.setPagination=s=>{const n=i=>ys(s,i);return r.options.onPaginationChange==null?void 0:r.options.onPaginationChange(n)},r.resetPagination=s=>{var n;r.setPagination(s?si():(n=r.initialState.pagination)!=null?n:si())},r.setPageIndex=s=>{r.setPagination(n=>{let i=ys(s,n.pageIndex);const o=typeof r.options.pageCount>"u"||r.options.pageCount===-1?Number.MAX_SAFE_INTEGER:r.options.pageCount-1;return i=Math.max(0,Math.min(i,o)),{...n,pageIndex:i}})},r.resetPageIndex=s=>{var n,i;r.setPageIndex(s?Oi:(n=(i=r.initialState)==null||(i=i.pagination)==null?void 0:i.pageIndex)!=null?n:Oi)},r.resetPageSize=s=>{var n,i;r.setPageSize(s?ji:(n=(i=r.initialState)==null||(i=i.pagination)==null?void 0:i.pageSize)!=null?n:ji)},r.setPageSize=s=>{r.setPagination(n=>{const i=Math.max(1,ys(s,n.pageSize)),o=n.pageSize*n.pageIndex,a=Math.floor(o/i);return{...n,pageIndex:a,pageSize:i}})},r.setPageCount=s=>r.setPagination(n=>{var i;let o=ys(s,(i=r.options.pageCount)!=null?i:-1);return typeof o=="number"&&(o=Math.max(-1,o)),{...n,pageCount:o}}),r.getPageOptions=ge(()=>[r.getPageCount()],s=>{let n=[];return s&&s>0&&(n=[...new Array(s)].fill(null).map((i,o)=>o)),n},me(r.options,"debugTable","getPageOptions")),r.getCanPreviousPage=()=>r.getState().pagination.pageIndex>0,r.getCanNextPage=()=>{const{pageIndex:s}=r.getState().pagination,n=r.getPageCount();return n===-1?!0:n===0?!1:s<n-1},r.previousPage=()=>r.setPageIndex(s=>s-1),r.nextPage=()=>r.setPageIndex(s=>s+1),r.firstPage=()=>r.setPageIndex(0),r.lastPage=()=>r.setPageIndex(r.getPageCount()-1),r.getPrePaginationRowModel=()=>r.getExpandedRowModel(),r.getPaginationRowModel=()=>(!r._getPaginationRowModel&&r.options.getPaginationRowModel&&(r._getPaginationRowModel=r.options.getPaginationRowModel(r)),r.options.manualPagination||!r._getPaginationRowModel?r.getPrePaginationRowModel():r._getPaginationRowModel()),r.getPageCount=()=>{var s;return(s=r.options.pageCount)!=null?s:Math.ceil(r.getRowCount()/r.getState().pagination.pageSize)},r.getRowCount=()=>{var s;return(s=r.options.rowCount)!=null?s:r.getPrePaginationRowModel().rows.length}}},ri=()=>({top:[],bottom:[]}),bx={getInitialState:r=>({rowPinning:ri(),...r}),getDefaultOptions:r=>({onRowPinningChange:Nt("rowPinning",r)}),createRow:(r,e)=>{r.pin=(t,s,n)=>{const i=s?r.getLeafRows().map(c=>{let{id:l}=c;return l}):[],o=n?r.getParentRows().map(c=>{let{id:l}=c;return l}):[],a=new Set([...o,r.id,...i]);e.setRowPinning(c=>{var l,d;if(t==="bottom"){var u,h;return{top:((u=c==null?void 0:c.top)!=null?u:[]).filter(p=>!(a!=null&&a.has(p))),bottom:[...((h=c==null?void 0:c.bottom)!=null?h:[]).filter(p=>!(a!=null&&a.has(p))),...Array.from(a)]}}if(t==="top"){var g,m;return{top:[...((g=c==null?void 0:c.top)!=null?g:[]).filter(p=>!(a!=null&&a.has(p))),...Array.from(a)],bottom:((m=c==null?void 0:c.bottom)!=null?m:[]).filter(p=>!(a!=null&&a.has(p)))}}return{top:((l=c==null?void 0:c.top)!=null?l:[]).filter(p=>!(a!=null&&a.has(p))),bottom:((d=c==null?void 0:c.bottom)!=null?d:[]).filter(p=>!(a!=null&&a.has(p)))}})},r.getCanPin=()=>{var t;const{enableRowPinning:s,enablePinning:n}=e.options;return typeof s=="function"?s(r):(t=s??n)!=null?t:!0},r.getIsPinned=()=>{const t=[r.id],{top:s,bottom:n}=e.getState().rowPinning,i=t.some(a=>s==null?void 0:s.includes(a)),o=t.some(a=>n==null?void 0:n.includes(a));return i?"top":o?"bottom":!1},r.getPinnedIndex=()=>{var t,s;const n=r.getIsPinned();if(!n)return-1;const i=(t=n==="top"?e.getTopRows():e.getBottomRows())==null?void 0:t.map(o=>{let{id:a}=o;return a});return(s=i==null?void 0:i.indexOf(r.id))!=null?s:-1}},createTable:r=>{r.setRowPinning=e=>r.options.onRowPinningChange==null?void 0:r.options.onRowPinningChange(e),r.resetRowPinning=e=>{var t,s;return r.setRowPinning(e?ri():(t=(s=r.initialState)==null?void 0:s.rowPinning)!=null?t:ri())},r.getIsSomeRowsPinned=e=>{var t;const s=r.getState().rowPinning;if(!e){var n,i;return!!((n=s.top)!=null&&n.length||(i=s.bottom)!=null&&i.length)}return!!((t=s[e])!=null&&t.length)},r._getPinnedRows=(e,t,s)=>{var n;return((n=r.options.keepPinnedRows)==null||n?(t??[]).map(o=>{const a=r.getRow(o,!0);return a.getIsAllParentsExpanded()?a:null}):(t??[]).map(o=>e.find(a=>a.id===o))).filter(Boolean).map(o=>({...o,position:s}))},r.getTopRows=ge(()=>[r.getRowModel().rows,r.getState().rowPinning.top],(e,t)=>r._getPinnedRows(e,t,"top"),me(r.options,"debugRows","getTopRows")),r.getBottomRows=ge(()=>[r.getRowModel().rows,r.getState().rowPinning.bottom],(e,t)=>r._getPinnedRows(e,t,"bottom"),me(r.options,"debugRows","getBottomRows")),r.getCenterRows=ge(()=>[r.getRowModel().rows,r.getState().rowPinning.top,r.getState().rowPinning.bottom],(e,t,s)=>{const n=new Set([...t??[],...s??[]]);return e.filter(i=>!n.has(i.id))},me(r.options,"debugRows","getCenterRows"))}},Sx={getInitialState:r=>({rowSelection:{},...r}),getDefaultOptions:r=>({onRowSelectionChange:Nt("rowSelection",r),enableRowSelection:!0,enableMultiRowSelection:!0,enableSubRowSelection:!0}),createTable:r=>{r.setRowSelection=e=>r.options.onRowSelectionChange==null?void 0:r.options.onRowSelectionChange(e),r.resetRowSelection=e=>{var t;return r.setRowSelection(e?{}:(t=r.initialState.rowSelection)!=null?t:{})},r.toggleAllRowsSelected=e=>{r.setRowSelection(t=>{e=typeof e<"u"?e:!r.getIsAllRowsSelected();const s={...t},n=r.getPreGroupedRowModel().flatRows;return e?n.forEach(i=>{i.getCanSelect()&&(s[i.id]=!0)}):n.forEach(i=>{delete s[i.id]}),s})},r.toggleAllPageRowsSelected=e=>r.setRowSelection(t=>{const s=typeof e<"u"?e:!r.getIsAllPageRowsSelected(),n={...t};return r.getRowModel().rows.forEach(i=>{Bi(n,i.id,s,!0,r)}),n}),r.getPreSelectedRowModel=()=>r.getCoreRowModel(),r.getSelectedRowModel=ge(()=>[r.getState().rowSelection,r.getCoreRowModel()],(e,t)=>Object.keys(e).length?ni(r,t):{rows:[],flatRows:[],rowsById:{}},me(r.options,"debugTable","getSelectedRowModel")),r.getFilteredSelectedRowModel=ge(()=>[r.getState().rowSelection,r.getFilteredRowModel()],(e,t)=>Object.keys(e).length?ni(r,t):{rows:[],flatRows:[],rowsById:{}},me(r.options,"debugTable","getFilteredSelectedRowModel")),r.getGroupedSelectedRowModel=ge(()=>[r.getState().rowSelection,r.getSortedRowModel()],(e,t)=>Object.keys(e).length?ni(r,t):{rows:[],flatRows:[],rowsById:{}},me(r.options,"debugTable","getGroupedSelectedRowModel")),r.getIsAllRowsSelected=()=>{const e=r.getFilteredRowModel().flatRows,{rowSelection:t}=r.getState();let s=!!(e.length&&Object.keys(t).length);return s&&e.some(n=>n.getCanSelect()&&!t[n.id])&&(s=!1),s},r.getIsAllPageRowsSelected=()=>{const e=r.getPaginationRowModel().flatRows.filter(n=>n.getCanSelect()),{rowSelection:t}=r.getState();let s=!!e.length;return s&&e.some(n=>!t[n.id])&&(s=!1),s},r.getIsSomeRowsSelected=()=>{var e;const t=Object.keys((e=r.getState().rowSelection)!=null?e:{}).length;return t>0&&t<r.getFilteredRowModel().flatRows.length},r.getIsSomePageRowsSelected=()=>{const e=r.getPaginationRowModel().flatRows;return r.getIsAllPageRowsSelected()?!1:e.filter(t=>t.getCanSelect()).some(t=>t.getIsSelected()||t.getIsSomeSelected())},r.getToggleAllRowsSelectedHandler=()=>e=>{r.toggleAllRowsSelected(e.target.checked)},r.getToggleAllPageRowsSelectedHandler=()=>e=>{r.toggleAllPageRowsSelected(e.target.checked)}},createRow:(r,e)=>{r.toggleSelected=(t,s)=>{const n=r.getIsSelected();e.setRowSelection(i=>{var o;if(t=typeof t<"u"?t:!n,r.getCanSelect()&&n===t)return i;const a={...i};return Bi(a,r.id,t,(o=s==null?void 0:s.selectChildren)!=null?o:!0,e),a})},r.getIsSelected=()=>{const{rowSelection:t}=e.getState();return Ko(r,t)},r.getIsSomeSelected=()=>{const{rowSelection:t}=e.getState();return $i(r,t)==="some"},r.getIsAllSubRowsSelected=()=>{const{rowSelection:t}=e.getState();return $i(r,t)==="all"},r.getCanSelect=()=>{var t;return typeof e.options.enableRowSelection=="function"?e.options.enableRowSelection(r):(t=e.options.enableRowSelection)!=null?t:!0},r.getCanSelectSubRows=()=>{var t;return typeof e.options.enableSubRowSelection=="function"?e.options.enableSubRowSelection(r):(t=e.options.enableSubRowSelection)!=null?t:!0},r.getCanMultiSelect=()=>{var t;return typeof e.options.enableMultiRowSelection=="function"?e.options.enableMultiRowSelection(r):(t=e.options.enableMultiRowSelection)!=null?t:!0},r.getToggleSelectedHandler=()=>{const t=r.getCanSelect();return s=>{var n;t&&r.toggleSelected((n=s.target)==null?void 0:n.checked)}}}},Bi=(r,e,t,s,n)=>{var i;const o=n.getRow(e,!0);t?(o.getCanMultiSelect()||Object.keys(r).forEach(a=>delete r[a]),o.getCanSelect()&&(r[e]=!0)):delete r[e],s&&(i=o.subRows)!=null&&i.length&&o.getCanSelectSubRows()&&o.subRows.forEach(a=>Bi(r,a.id,t,s,n))};function ni(r,e){const t=r.getState().rowSelection,s=[],n={},i=function(o,a){return o.map(c=>{var l;const d=Ko(c,t);if(d&&(s.push(c),n[c.id]=c),(l=c.subRows)!=null&&l.length&&(c={...c,subRows:i(c.subRows)}),d)return c}).filter(Boolean)};return{rows:i(e.rows),flatRows:s,rowsById:n}}function Ko(r,e){var t;return(t=e[r.id])!=null?t:!1}function $i(r,e,t){var s;if(!((s=r.subRows)!=null&&s.length))return!1;let n=!0,i=!1;return r.subRows.forEach(o=>{if(!(i&&!n)&&(o.getCanSelect()&&(Ko(o,e)?i=!0:n=!1),o.subRows&&o.subRows.length)){const a=$i(o,e);a==="all"?i=!0:(a==="some"&&(i=!0),n=!1)}}),n?"all":i?"some":!1}const Ui=/([0-9]+)/gm,Ex=(r,e,t)=>Wu(Ss(r.getValue(t)).toLowerCase(),Ss(e.getValue(t)).toLowerCase()),Tx=(r,e,t)=>Wu(Ss(r.getValue(t)),Ss(e.getValue(t))),wx=(r,e,t)=>zo(Ss(r.getValue(t)).toLowerCase(),Ss(e.getValue(t)).toLowerCase()),Rx=(r,e,t)=>zo(Ss(r.getValue(t)),Ss(e.getValue(t))),Ax=(r,e,t)=>{const s=r.getValue(t),n=e.getValue(t);return s>n?1:s<n?-1:0},Ix=(r,e,t)=>zo(r.getValue(t),e.getValue(t));function zo(r,e){return r===e?0:r>e?1:-1}function Ss(r){return typeof r=="number"?isNaN(r)||r===1/0||r===-1/0?"":String(r):typeof r=="string"?r:""}function Wu(r,e){const t=r.split(Ui).filter(Boolean),s=e.split(Ui).filter(Boolean);for(;t.length&&s.length;){const n=t.shift(),i=s.shift(),o=parseInt(n,10),a=parseInt(i,10),c=[o,a].sort();if(isNaN(c[0])){if(n>i)return 1;if(i>n)return-1;continue}if(isNaN(c[1]))return isNaN(o)?-1:1;if(o>a)return 1;if(a>o)return-1}return t.length-s.length}const fr={alphanumeric:Ex,alphanumericCaseSensitive:Tx,text:wx,textCaseSensitive:Rx,datetime:Ax,basic:Ix},Lx={getInitialState:r=>({sorting:[],...r}),getDefaultColumnDef:()=>({sortingFn:"auto",sortUndefined:1}),getDefaultOptions:r=>({onSortingChange:Nt("sorting",r),isMultiSortEvent:e=>e.shiftKey}),createColumn:(r,e)=>{r.getAutoSortingFn=()=>{const t=e.getFilteredRowModel().flatRows.slice(10);let s=!1;for(const n of t){const i=n==null?void 0:n.getValue(r.id);if(Object.prototype.toString.call(i)==="[object Date]")return fr.datetime;if(typeof i=="string"&&(s=!0,i.split(Ui).length>1))return fr.alphanumeric}return s?fr.text:fr.basic},r.getAutoSortDir=()=>{const t=e.getFilteredRowModel().flatRows[0];return typeof(t==null?void 0:t.getValue(r.id))=="string"?"asc":"desc"},r.getSortingFn=()=>{var t,s;if(!r)throw new Error;return Vn(r.columnDef.sortingFn)?r.columnDef.sortingFn:r.columnDef.sortingFn==="auto"?r.getAutoSortingFn():(t=(s=e.options.sortingFns)==null?void 0:s[r.columnDef.sortingFn])!=null?t:fr[r.columnDef.sortingFn]},r.toggleSorting=(t,s)=>{const n=r.getNextSortingOrder(),i=typeof t<"u"&&t!==null;e.setSorting(o=>{const a=o==null?void 0:o.find(g=>g.id===r.id),c=o==null?void 0:o.findIndex(g=>g.id===r.id);let l=[],d,u=i?t:n==="desc";if(o!=null&&o.length&&r.getCanMultiSort()&&s?a?d="toggle":d="add":o!=null&&o.length&&c!==o.length-1?d="replace":a?d="toggle":d="replace",d==="toggle"&&(i||n||(d="remove")),d==="add"){var h;l=[...o,{id:r.id,desc:u}],l.splice(0,l.length-((h=e.options.maxMultiSortColCount)!=null?h:Number.MAX_SAFE_INTEGER))}else d==="toggle"?l=o.map(g=>g.id===r.id?{...g,desc:u}:g):d==="remove"?l=o.filter(g=>g.id!==r.id):l=[{id:r.id,desc:u}];return l})},r.getFirstSortDir=()=>{var t,s;return((t=(s=r.columnDef.sortDescFirst)!=null?s:e.options.sortDescFirst)!=null?t:r.getAutoSortDir()==="desc")?"desc":"asc"},r.getNextSortingOrder=t=>{var s,n;const i=r.getFirstSortDir(),o=r.getIsSorted();return o?o!==i&&((s=e.options.enableSortingRemoval)==null||s)&&(!(t&&(n=e.options.enableMultiRemove)!=null)||n)?!1:o==="desc"?"asc":"desc":i},r.getCanSort=()=>{var t,s;return((t=r.columnDef.enableSorting)!=null?t:!0)&&((s=e.options.enableSorting)!=null?s:!0)&&!!r.accessorFn},r.getCanMultiSort=()=>{var t,s;return(t=(s=r.columnDef.enableMultiSort)!=null?s:e.options.enableMultiSort)!=null?t:!!r.accessorFn},r.getIsSorted=()=>{var t;const s=(t=e.getState().sorting)==null?void 0:t.find(n=>n.id===r.id);return s?s.desc?"desc":"asc":!1},r.getSortIndex=()=>{var t,s;return(t=(s=e.getState().sorting)==null?void 0:s.findIndex(n=>n.id===r.id))!=null?t:-1},r.clearSorting=()=>{e.setSorting(t=>t!=null&&t.length?t.filter(s=>s.id!==r.id):[])},r.getToggleSortingHandler=()=>{const t=r.getCanSort();return s=>{t&&(s.persist==null||s.persist(),r.toggleSorting==null||r.toggleSorting(void 0,r.getCanMultiSort()?e.options.isMultiSortEvent==null?void 0:e.options.isMultiSortEvent(s):!1))}}},createTable:r=>{r.setSorting=e=>r.options.onSortingChange==null?void 0:r.options.onSortingChange(e),r.resetSorting=e=>{var t,s;r.setSorting(e?[]:(t=(s=r.initialState)==null?void 0:s.sorting)!=null?t:[])},r.getPreSortedRowModel=()=>r.getGroupedRowModel(),r.getSortedRowModel=()=>(!r._getSortedRowModel&&r.options.getSortedRowModel&&(r._getSortedRowModel=r.options.getSortedRowModel(r)),r.options.manualSorting||!r._getSortedRowModel?r.getPreSortedRowModel():r._getSortedRowModel())}},Cx=[X0,mx,dx,ux,Q0,Z0,px,xx,Lx,lx,vx,yx,bx,Sx,hx];function _x(r){var e,t;process.env.NODE_ENV!=="production"&&(r.debugAll||r.debugTable)&&console.info("Creating Table Instance...");const s=[...Cx,...(e=r._features)!=null?e:[]];let n={_features:s};const i=n._features.reduce((h,g)=>Object.assign(h,g.getDefaultOptions==null?void 0:g.getDefaultOptions(n)),{}),o=h=>n.options.mergeOptions?n.options.mergeOptions(i,h):{...i,...h};let c={...{},...(t=r.initialState)!=null?t:{}};n._features.forEach(h=>{var g;c=(g=h.getInitialState==null?void 0:h.getInitialState(c))!=null?g:c});const l=[];let d=!1;const u={_features:s,options:{...i,...r},initialState:c,_queue:h=>{l.push(h),d||(d=!0,Promise.resolve().then(()=>{for(;l.length;)l.shift()();d=!1}).catch(g=>setTimeout(()=>{throw g})))},reset:()=>{n.setState(n.initialState)},setOptions:h=>{const g=ys(h,n.options);n.options=o(g)},getState:()=>n.options.state,setState:h=>{n.options.onStateChange==null||n.options.onStateChange(h)},_getRowId:(h,g,m)=>{var p;return(p=n.options.getRowId==null?void 0:n.options.getRowId(h,g,m))!=null?p:`${m?[m.id,g].join("."):g}`},getCoreRowModel:()=>(n._getCoreRowModel||(n._getCoreRowModel=n.options.getCoreRowModel(n)),n._getCoreRowModel()),getRowModel:()=>n.getPaginationRowModel(),getRow:(h,g)=>{let m=(g?n.getPrePaginationRowModel():n.getRowModel()).rowsById[h];if(!m&&(m=n.getCoreRowModel().rowsById[h],!m))throw process.env.NODE_ENV!=="production"?new Error(`getRow could not find row with ID: ${h}`):new Error;return m},_getDefaultColumnDef:ge(()=>[n.options.defaultColumn],h=>{var g;return h=(g=h)!=null?g:{},{header:m=>{const p=m.header.column.columnDef;return p.accessorKey?p.accessorKey:p.accessorFn?p.id:null},cell:m=>{var p,x;return(p=(x=m.renderValue())==null||x.toString==null?void 0:x.toString())!=null?p:null},...n._features.reduce((m,p)=>Object.assign(m,p.getDefaultColumnDef==null?void 0:p.getDefaultColumnDef()),{}),...h}},me(r,"debugColumns","_getDefaultColumnDef")),_getColumnDefs:()=>n.options.columns,getAllColumns:ge(()=>[n._getColumnDefs()],h=>{const g=function(m,p,x){return x===void 0&&(x=0),m.map(v=>{const y=q0(n,v,x,p),b=v;return y.columns=b.columns?g(b.columns,y,x+1):[],y})};return g(h)},me(r,"debugColumns","getAllColumns")),getAllFlatColumns:ge(()=>[n.getAllColumns()],h=>h.flatMap(g=>g.getFlatColumns()),me(r,"debugColumns","getAllFlatColumns")),_getAllFlatColumnsById:ge(()=>[n.getAllFlatColumns()],h=>h.reduce((g,m)=>(g[m.id]=m,g),{}),me(r,"debugColumns","getAllFlatColumnsById")),getAllLeafColumns:ge(()=>[n.getAllColumns(),n._getOrderColumnsFn()],(h,g)=>{let m=h.flatMap(p=>p.getLeafColumns());return g(m)},me(r,"debugColumns","getAllLeafColumns")),getColumn:h=>{const g=n._getAllFlatColumnsById()[h];return process.env.NODE_ENV!=="production"&&!g&&console.error(`[Table] Column with id '${h}' does not exist.`),g}};Object.assign(n,u);for(let h=0;h<n._features.length;h++){const g=n._features[h];g==null||g.createTable==null||g.createTable(n)}return n}function kx(){return r=>ge(()=>[r.options.data],e=>{const t={rows:[],flatRows:[],rowsById:{}},s=function(n,i,o){i===void 0&&(i=0);const a=[];for(let l=0;l<n.length;l++){const d=Vo(r,r._getRowId(n[l],l,o),n[l],l,i,void 0,o==null?void 0:o.id);if(t.flatRows.push(d),t.rowsById[d.id]=d,a.push(d),r.options.getSubRows){var c;d.originalSubRows=r.options.getSubRows(n[l],l),(c=d.originalSubRows)!=null&&c.length&&(d.subRows=s(d.originalSubRows,i+1,d))}}return a};return t.rows=s(e),t},me(r.options,"debugTable","getRowModel",()=>r._autoResetPageIndex()))}function Dx(r){const e=[],t=s=>{var n;e.push(s),(n=s.subRows)!=null&&n.length&&s.getIsExpanded()&&s.subRows.forEach(t)};return r.rows.forEach(t),{rows:e,flatRows:r.flatRows,rowsById:r.rowsById}}function Px(r,e,t){return t.options.filterFromLeafRows?Nx(r,e,t):Mx(r,e,t)}function Nx(r,e,t){var s;const n=[],i={},o=(s=t.options.maxLeafRowFilterDepth)!=null?s:100,a=function(c,l){l===void 0&&(l=0);const d=[];for(let h=0;h<c.length;h++){var u;let g=c[h];const m=Vo(t,g.id,g.original,g.index,g.depth,void 0,g.parentId);if(m.columnFilters=g.columnFilters,(u=g.subRows)!=null&&u.length&&l<o){if(m.subRows=a(g.subRows,l+1),g=m,e(g)&&!m.subRows.length){d.push(g),i[g.id]=g,n.push(g);continue}if(e(g)||m.subRows.length){d.push(g),i[g.id]=g,n.push(g);continue}}else g=m,e(g)&&(d.push(g),i[g.id]=g,n.push(g))}return d};return{rows:a(r),flatRows:n,rowsById:i}}function Mx(r,e,t){var s;const n=[],i={},o=(s=t.options.maxLeafRowFilterDepth)!=null?s:100,a=function(c,l){l===void 0&&(l=0);const d=[];for(let h=0;h<c.length;h++){let g=c[h];if(e(g)){var u;if((u=g.subRows)!=null&&u.length&&l<o){const p=Vo(t,g.id,g.original,g.index,g.depth,void 0,g.parentId);p.subRows=a(g.subRows,l+1),g=p}d.push(g),n.push(g),i[g.id]=g}}return d};return{rows:a(r),flatRows:n,rowsById:i}}function Fx(){return r=>ge(()=>[r.getPreFilteredRowModel(),r.getState().columnFilters,r.getState().globalFilter],(e,t,s)=>{if(!e.rows.length||!(t!=null&&t.length)&&!s){for(let h=0;h<e.flatRows.length;h++)e.flatRows[h].columnFilters={},e.flatRows[h].columnFiltersMeta={};return e}const n=[],i=[];(t??[]).forEach(h=>{var g;const m=r.getColumn(h.id);if(!m)return;const p=m.getFilterFn();if(!p){process.env.NODE_ENV!=="production"&&console.warn(`Could not find a valid 'column.filterFn' for column with the ID: ${m.id}.`);return}n.push({id:h.id,filterFn:p,resolvedValue:(g=p.resolveFilterValue==null?void 0:p.resolveFilterValue(h.value))!=null?g:h.value})});const o=(t??[]).map(h=>h.id),a=r.getGlobalFilterFn(),c=r.getAllLeafColumns().filter(h=>h.getCanGlobalFilter());s&&a&&c.length&&(o.push("__global__"),c.forEach(h=>{var g;i.push({id:h.id,filterFn:a,resolvedValue:(g=a.resolveFilterValue==null?void 0:a.resolveFilterValue(s))!=null?g:s})}));let l,d;for(let h=0;h<e.flatRows.length;h++){const g=e.flatRows[h];if(g.columnFilters={},n.length)for(let m=0;m<n.length;m++){l=n[m];const p=l.id;g.columnFilters[p]=l.filterFn(g,p,l.resolvedValue,x=>{g.columnFiltersMeta[p]=x})}if(i.length){for(let m=0;m<i.length;m++){d=i[m];const p=d.id;if(d.filterFn(g,p,d.resolvedValue,x=>{g.columnFiltersMeta[p]=x})){g.columnFilters.__global__=!0;break}}g.columnFilters.__global__!==!0&&(g.columnFilters.__global__=!1)}}const u=h=>{for(let g=0;g<o.length;g++)if(h.columnFilters[o[g]]===!1)return!1;return!0};return Px(e.rows,u,r)},me(r.options,"debugTable","getFilteredRowModel",()=>r._autoResetPageIndex()))}function Ox(r){return e=>ge(()=>[e.getState().pagination,e.getPrePaginationRowModel(),e.options.paginateExpandedRows?void 0:e.getState().expanded],(t,s)=>{if(!s.rows.length)return s;const{pageSize:n,pageIndex:i}=t;let{rows:o,flatRows:a,rowsById:c}=s;const l=n*i,d=l+n;o=o.slice(l,d);let u;e.options.paginateExpandedRows?u={rows:o,flatRows:a,rowsById:c}:u=Dx({rows:o,flatRows:a,rowsById:c}),u.flatRows=[];const h=g=>{u.flatRows.push(g),g.subRows.length&&g.subRows.forEach(h)};return u.rows.forEach(h),u},me(e.options,"debugTable","getPaginationRowModel"))}function jx(){return r=>ge(()=>[r.getState().sorting,r.getPreSortedRowModel()],(e,t)=>{if(!t.rows.length||!(e!=null&&e.length))return t;const s=r.getState().sorting,n=[],i=s.filter(c=>{var l;return(l=r.getColumn(c.id))==null?void 0:l.getCanSort()}),o={};i.forEach(c=>{const l=r.getColumn(c.id);l&&(o[c.id]={sortUndefined:l.columnDef.sortUndefined,invertSorting:l.columnDef.invertSorting,sortingFn:l.getSortingFn()})});const a=c=>{const l=c.map(d=>({...d}));return l.sort((d,u)=>{for(let g=0;g<i.length;g+=1){var h;const m=i[g],p=o[m.id],x=p.sortUndefined,v=(h=m==null?void 0:m.desc)!=null?h:!1;let y=0;if(x){const b=d.getValue(m.id),T=u.getValue(m.id),R=b===void 0,_=T===void 0;if(R||_){if(x==="first")return R?-1:1;if(x==="last")return R?1:-1;y=R&&_?0:R?x:-x}}if(y===0&&(y=p.sortingFn(d,u,m.id)),y!==0)return v&&(y*=-1),p.invertSorting&&(y*=-1),y}return d.index-u.index}),l.forEach(d=>{var u;n.push(d),(u=d.subRows)!=null&&u.length&&(d.subRows=a(d.subRows))}),l};return{rows:a(t.rows),flatRows:n,rowsById:t.rowsById}},me(r.options,"debugTable","getSortedRowModel",()=>r._autoResetPageIndex()))}/**
25
25
  * react-table
26
26
  *
27
27
  * Copyright (c) TanStack
@@ -30,9 +30,54 @@
30
30
  * LICENSE.md file in the root directory of this source tree.
31
31
  *
32
32
  * @license MIT
33
- */function Yn(e,t){return e?rm(e)?f.createElement(e,t):e:null}function rm(e){return nm(e)||typeof e=="function"||om(e)}function nm(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function om(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function sm(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[r]=f.useState(()=>({current:Uu(t)})),[o,s]=f.useState(()=>r.current.initialState);return r.current.setOptions(a=>({...a,...e,state:{...o,...e.state},onStateChange:i=>{s(i),e.onStateChange==null||e.onStateChange(i)}})),r.current}function am({columns:e,data:t,searchKey:r,searchPlaceholder:o,pageSize:s=10}){var y,b;const a=ce(),i=o??a.dataTable_searchPlaceholder,[l,d]=f.useState([]),[c,p]=f.useState([]),[u,m]=f.useState({}),[g,h]=f.useState({}),x=sm({data:t,columns:e,onSortingChange:d,onColumnFiltersChange:p,getCoreRowModel:Ku(),getPaginationRowModel:em(),getSortedRowModel:tm(),getFilteredRowModel:Qu(),onColumnVisibilityChange:m,onRowSelectionChange:h,state:{sorting:l,columnFilters:c,columnVisibility:u,rowSelection:g},initialState:{pagination:{pageSize:s}}});return n.jsxs("div",{className:"space-y-4",children:[r&&n.jsx("div",{className:"flex items-center gap-2",children:n.jsx(mt,{placeholder:i,value:((y=x.getColumn(r))==null?void 0:y.getFilterValue())??"",onChange:w=>{var j;return(j=x.getColumn(r))==null?void 0:j.setFilterValue(w.target.value)},className:"max-w-sm"})}),n.jsx("div",{className:"rounded-md border",children:n.jsxs(on,{children:[n.jsx(sn,{children:x.getHeaderGroups().map(w=>n.jsx(At,{children:w.headers.map(j=>n.jsx(ln,{children:j.isPlaceholder?null:Yn(j.column.columnDef.header,j.getContext())},j.id))},w.id))}),n.jsx(an,{children:(b=x.getRowModel().rows)!=null&&b.length?x.getRowModel().rows.map(w=>n.jsx(At,{"data-state":w.getIsSelected()&&"selected",children:w.getVisibleCells().map(j=>n.jsx(ir,{children:Yn(j.column.columnDef.cell,j.getContext())},j.id))},w.id)):n.jsx(At,{children:n.jsx(ir,{colSpan:e.length,className:"h-24 text-center",children:a.dataTable_noResults})})})]})}),n.jsxs("div",{className:"flex items-center justify-between px-2",children:[n.jsx("div",{className:"text-sm text-muted-foreground",children:ze(a.dataTable_pageOf,{page:x.getState().pagination.pageIndex+1,total:x.getPageCount()})}),n.jsxs("div",{className:"flex items-center space-x-2",children:[n.jsxs(ke,{variant:"outline",size:"sm",onClick:()=>x.previousPage(),disabled:!x.getCanPreviousPage(),children:[n.jsx(P.ChevronLeft,{className:"h-4 w-4"}),a.dataTable_previous]}),n.jsxs(ke,{variant:"outline",size:"sm",onClick:()=>x.nextPage(),disabled:!x.getCanNextPage(),children:[a.dataTable_next,n.jsx(P.ChevronRight,{className:"h-4 w-4"})]})]})]})]})}function im({column:e,title:t,className:r}){return e.getCanSort()?n.jsxs(ke,{variant:"ghost",size:"sm",className:v("-ml-3 h-8",r),onClick:()=>e.toggleSorting(e.getIsSorted()==="asc"),children:[t,n.jsx(P.ArrowUpDown,{className:"ml-2 h-4 w-4"})]}):n.jsx("div",{className:v(r),children:t})}const lm=new Set(["abstract","as","async","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","let","new","null","of","package","private","protected","public","return","set","static","super","switch","this","throw","true","try","type","typeof","undefined","var","void","while","with","yield"]),cm=new Set(["display","flex","grid","none","block","inline","relative","absolute","fixed","sticky","hidden","visible","auto","inherit","initial","unset","important","solid","dashed","dotted","transparent","center","left","right","top","bottom","normal","bold","italic","nowrap","wrap"]);function dm(e,t){const r=e.split(`
34
- `),o=t==="css"||t==="scss"||t==="less",s=t==="html"||t==="xml"||t==="svg",a=t==="json",i=t==="bash"||t==="sh"||t==="shell"||t==="zsh";return r.map(l=>{const d=[];let c=0;const p=l.length*4;let u=0;for(;c<l.length&&u++<p;){if(!o&&!a&&l[c]==="/"&&l[c+1]==="/"){d.push({type:"comment",value:l.slice(c)}),c=l.length;continue}if(i&&l[c]==="#"){d.push({type:"comment",value:l.slice(c)}),c=l.length;continue}if(l[c]==="/"&&l[c+1]==="*"){const m=l.indexOf("*/",c+2);m!==-1?(d.push({type:"comment",value:l.slice(c,m+2)}),c=m+2):(d.push({type:"comment",value:l.slice(c)}),c=l.length);continue}if(l[c]==="`"){let m=c+1;for(;m<l.length&&l[m]!=="`";)l[m]==="\\"&&m++,m++;d.push({type:"string",value:l.slice(c,m+1)}),c=m+1;continue}if(l[c]==='"'||l[c]==="'"){const m=l[c];let g=c+1;for(;g<l.length&&l[g]!==m;)l[g]==="\\"&&g++,g++;d.push({type:"string",value:l.slice(c,g+1)}),c=g+1;continue}if(/[0-9]/.test(l[c])&&(c===0||/[\s,\(\[:=+\-*/<>!&|^~?{]/.test(l[c-1]))){let m=c;for(;m<l.length&&/[0-9a-fA-FxXoObB._eE+\-n]/.test(l[m]);)m++;d.push({type:"number",value:l.slice(c,m)}),c=m;continue}if(l[c]==="<"&&/[a-zA-Z\/!]/.test(l[c+1]||"")||l[c]==="/"&&l[c+1]===">"){if(l[c]==="/"&&l[c+1]===">"){d.push({type:"punctuation",value:"/>"}),c+=2;continue}const m=l[c+1]==="/";let g=m?c+2:c+1;for(;g<l.length&&/[a-zA-Z0-9.\-_]/.test(l[g]);)g++;d.push({type:"punctuation",value:l[c]+(m?"/":"")});const h=l.slice(m?c+2:c+1,g);h&&d.push({type:"tag",value:h}),c=g;continue}if(l[c]===">"){d.push({type:"punctuation",value:">"}),c++;continue}if(/[a-zA-Z_$@]/.test(l[c])){let m=c;for(;m<l.length&&/[a-zA-Z0-9_$@\-]/.test(l[m]);)m++;m===c&&m++;const g=l.slice(c,m);if(o&&cm.has(g))d.push({type:"keyword",value:g});else if(s||o){const h=l.slice(m).trimStart();h[0]==="="||h[0]===":"?d.push({type:"attr",value:g}):d.push({type:"plain",value:g})}else lm.has(g)?d.push({type:"keyword",value:g}):!a&&l[m]==="("?d.push({type:"function",value:g}):!a&&/^[A-Z]/.test(g)?d.push({type:"tag",value:g}):d.push({type:"plain",value:g});c=m;continue}if(/[=+\-*/%<>!&|^~?:]/.test(l[c])){let m=c;for(;m<l.length&&/[=+\-*/%<>!&|^~?:]/.test(l[m]);)m++;d.push({type:"operator",value:l.slice(c,m)}),c=m;continue}if(/[{}()\[\],;.]/.test(l[c])){d.push({type:"punctuation",value:l[c]}),c++;continue}if(/\s/.test(l[c])){let m=c;for(;m<l.length&&/\s/.test(l[m]);)m++;d.push({type:"plain",value:l.slice(c,m)}),c=m;continue}d.push({type:"plain",value:l[c]}),c++}return d})}const um={comment:"var(--cb-comment, #6a9955)",string:"var(--cb-string, #ce9178)",keyword:"var(--cb-keyword, #569cd6)",number:"var(--cb-number, #b5cea8)",function:"var(--cb-function, #dcdcaa)",tag:"var(--cb-tag, #4ec9b0)",attr:"var(--cb-attr, #9cdcfe)",punctuation:"var(--cb-punctuation, #d4d4d4)",operator:"var(--cb-operator, #d4d4d4)",plain:"var(--cb-plain, #d4d4d4)"};function mm({code:e,language:t="tsx",showLineNumbers:r=!1,showCopy:o=!0,className:s}){const a=ce(),[i,l]=f.useState(!1),d=e.trim(),c=f.useMemo(()=>{try{return dm(d,t)}catch{return d.split(`
35
- `).map(u=>[{type:"plain",value:u}])}},[d,t]),p=async()=>{try{await navigator.clipboard.writeText(d),l(!0),setTimeout(()=>l(!1),2e3)}catch{}};return n.jsxs("div",{className:v("relative group",s),children:[o&&n.jsx("button",{type:"button",onClick:p,className:"absolute top-3 right-3 z-10 p-1.5 rounded-md bg-white/10 backdrop-blur text-white/60 hover:text-white opacity-0 group-hover:opacity-100 transition-opacity text-xs","aria-label":a.common_copyCode,children:i?n.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"20 6 9 17 4 12"})}):n.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{width:"14",height:"14",x:"8",y:"8",rx:"2"}),n.jsx("path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"})]})}),n.jsx("pre",{className:"overflow-x-auto rounded-lg p-4 text-[13px] leading-relaxed font-mono",style:{background:"var(--cb-bg, #1e1e2e)",color:"var(--cb-plain, #d4d4d4)"},children:c.map((u,m)=>n.jsxs("div",{children:[r&&n.jsx("span",{className:"inline-block w-8 select-none text-right mr-4 opacity-40",style:{color:"var(--cb-plain, #d4d4d4)"},children:m+1}),u.map((g,h)=>n.jsx("span",{style:{color:um[g.type]},children:g.value},h))]},m))})]})}const Ha=Le("font-bold tracking-tight",{variants:{level:{1:"text-2xl lg:text-3xl",2:"text-xl lg:text-2xl",3:"text-lg lg:text-xl",4:"text-base lg:text-lg",5:"text-sm lg:text-base",6:"text-xs lg:text-sm"}},defaultVariants:{level:2}});function fm({className:e,level:t=2,as:r,children:o,...s}){const a=r||`h${t}`;return n.jsx(a,{className:v(Ha({level:t}),e),...s,children:o})}const Ga=Le("",{variants:{size:{xs:"text-xs",sm:"text-sm",base:"text-base",lg:"text-lg",xl:"text-xl"},weight:{normal:"font-normal",medium:"font-medium",semibold:"font-semibold",bold:"font-bold"},variant:{default:"text-foreground",muted:"text-muted-foreground",primary:"text-primary",destructive:"text-destructive",success:"text-green-600 dark:text-green-400"},leading:{tight:"leading-tight",normal:"leading-normal",relaxed:"leading-relaxed"}},defaultVariants:{size:"base",weight:"normal",variant:"default",leading:"normal"}});function gm({className:e,size:t,weight:r,variant:o,leading:s,as:a="p",children:i,...l}){return n.jsx(a,{className:v(Ga({size:t,weight:r,variant:o,leading:s}),e),...l,children:i})}function pm({className:e,...t}){return n.jsx("code",{className:v("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm",e),...t})}function hm({className:e,...t}){return n.jsx("blockquote",{className:v("border-l-4 border-primary pl-4 italic text-muted-foreground",e),...t})}function xm({className:e,...t}){return n.jsx("p",{className:v("text-xl text-muted-foreground",e),...t})}function vm({className:e,...t}){return n.jsx("p",{className:v("text-sm text-muted-foreground",e),...t})}const qa=f.forwardRef(({className:e,children:t,...r},o)=>n.jsx("div",{ref:o,className:v("w-full h-full min-h-[300px]",e),...r,children:n.jsx(Wr.ResponsiveContainer,{width:"100%",height:"100%",children:t})}));qa.displayName="ChartContainer";const bm=Wr.Tooltip,wm=Wr.Legend,Wa=f.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:v("flex flex-col space-y-4",e),...t}));Wa.displayName="Timeline";const Ua=f.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:v("relative flex gap-4 pb-4 last:pb-0",e),...t}));Ua.displayName="TimelineItem";const Ka=f.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:v("relative z-10 flex h-8 w-8 shrink-0 items-center justify-center rounded-full border bg-background text-primary shadow-sm",e),...t}));Ka.displayName="TimelineIcon";const Xa=f.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:v("absolute left-4 top-8 -bottom-4 w-px bg-border",e),...t}));Xa.displayName="TimelineConnector";const Ya=f.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,className:v("flex-1 space-y-1 pt-1",e),...t}));Ya.displayName="TimelineContent";const Za=f.forwardRef(({className:e,children:t,...r},o)=>n.jsx("div",{ref:o,className:v("grid min-h-screen w-full lg:grid-cols-[280px_1fr]",e),...r,children:t}));Za.displayName="AppShell";const Ja=f.forwardRef(({className:e,children:t,...r},o)=>n.jsx("div",{ref:o,className:v("hidden border-r bg-muted/40 lg:block dark:bg-muted/10",e),...r,children:n.jsx("div",{className:"flex h-full max-h-screen flex-col gap-2",children:t})}));Ja.displayName="Sidebar";const Qa=f.forwardRef(({className:e,children:t,...r},o)=>n.jsx("header",{ref:o,className:v("flex h-14 items-center gap-4 border-b bg-background px-6 lg:h-[60px]",e),...r,children:t}));Qa.displayName="Header";const ei=f.forwardRef(({className:e,children:t,...r},o)=>n.jsx("main",{ref:o,className:v("flex flex-1 flex-col gap-4 p-4 lg:gap-6 lg:p-6",e),...r,children:t}));ei.displayName="Main";function ym({title:e,value:t,description:r,trend:o,trendLabel:s,icon:a,className:i,...l}){return n.jsxs(en,{className:v("overflow-hidden",i),...l,children:[n.jsxs(tn,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[n.jsx(rn,{className:"text-sm font-medium text-muted-foreground",children:e}),a&&n.jsx("div",{className:"text-muted-foreground",children:a})]}),n.jsxs(nn,{children:[n.jsx("div",{className:"text-2xl font-bold",children:t}),(r||o!==void 0)&&n.jsxs("div",{className:"text-xs flex items-center gap-1 mt-1 text-muted-foreground",children:[o!==void 0&&n.jsxs("span",{className:v("flex items-center font-medium",o>0?"text-green-500":o<0?"text-red-500":"text-muted-foreground"),children:[o>0?n.jsx(P.TrendingUp,{className:"mr-1 h-3 w-3"}):o<0?n.jsx(P.TrendingDown,{className:"mr-1 h-3 w-3"}):n.jsx(P.Minus,{className:"mr-1 h-3 w-3"}),o>0?"+":"",o,"%"]}),s&&n.jsx("span",{children:s}),r&&!o&&n.jsx("span",{children:r})]})]})]})}const ti=f.forwardRef(({className:e,label:t,value:r,...o},s)=>{const[a,i]=f.useState(!1),l=()=>{navigator.clipboard.writeText(r),i(!0),setTimeout(()=>i(!1),2e3)};return n.jsxs("div",{className:"space-y-2",children:[t&&n.jsx(mr,{children:t}),n.jsxs("div",{className:"flex gap-2 relative",children:[n.jsx(mt,{ref:s,value:r,readOnly:!0,className:v("pr-10 font-mono text-sm",e),...o}),n.jsx(ke,{size:"icon",variant:"outline",className:"shrink-0",onClick:l,children:a?n.jsx(P.Check,{className:"h-4 w-4 text-green-500"}):n.jsx(P.Copy,{className:"h-4 w-4"})})]})]})});ti.displayName="CopyInput";const ri=f.forwardRef(({className:e,data:t,...r},o)=>n.jsx("pre",{ref:o,className:v("rounded-lg border bg-muted p-4 overflow-auto text-xs font-mono text-muted-foreground",e),...r,children:JSON.stringify(t,null,2)}));ri.displayName="JsonViewer";const jm=Le("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{status:{neutral:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",success:"border-transparent bg-green-500/15 text-green-700 dark:text-green-400 hover:bg-green-500/25",warning:"border-transparent bg-yellow-500/15 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/25",error:"border-transparent bg-red-500/15 text-red-700 dark:text-red-400 hover:bg-red-500/25",info:"border-transparent bg-blue-500/15 text-blue-700 dark:text-blue-400 hover:bg-blue-500/25"}},defaultVariants:{status:"neutral"}});function Nm({className:e,status:t,dot:r=!0,children:o,...s}){return n.jsxs("div",{className:v(jm({status:t}),e),...s,children:[r&&n.jsx("span",{className:v("mr-1.5 h-2 w-2 rounded-full",{"bg-current":!0})}),o]})}const br=f.forwardRef(({src:e,data:t,stream:r,color:o,progressColor:s,progress:a=0,height:i=80,barCount:l=100,barWidth:d=3,barGap:c=1,barRadius:p=2,mirrored:u=!1,onSeek:m,className:g,...h},x)=>{const y=f.useRef(null),[b,w]=f.useState([]),[j,M]=f.useState(!1),R=f.useRef(0),_=ce(),[C,S]=f.useState({width:0,height:0}),[T,L]=f.useState(null);f.useEffect(()=>{var z;const $=(z=y.current)==null?void 0:z.parentElement;if(!$)return;const k=new ResizeObserver(A=>{for(const E of A){const{width:N,height:W}=E.contentRect;S({width:N,height:W})}});return k.observe($),()=>k.disconnect()},[]),f.useEffect(()=>{if(!e||r)return;M(!0);const $=new AudioContext;let k=!1;return fetch(e).then(z=>z.arrayBuffer()).then(z=>$.decodeAudioData(z)).then(z=>{if(k)return;const A=z.getChannelData(0),E=Math.floor(A.length/l),N=[];for(let q=0;q<l;q++){let G=0;for(let Z=0;Z<E;Z++)G+=Math.abs(A[q*E+Z]);N.push(G/E)}const W=Math.max(...N,.01);w(N.map(q=>q/W)),M(!1)}).catch(()=>{k||(L(_.audioWaveform_error),M(!1))}),()=>{k=!0,$.close()}},[e,l]),f.useEffect(()=>{if(t){const $=Math.max(...t,.01);w(t.map(k=>k/$))}},[t]),f.useEffect(()=>{if(!r)return;const $=new AudioContext,k=$.createMediaStreamSource(r),z=$.createAnalyser();z.fftSize=256,k.connect(z);const A=new Uint8Array(z.frequencyBinCount),E=()=>{z.getByteFrequencyData(A);const N=Math.floor(A.length/l),W=[];for(let q=0;q<l;q++)W.push(A[q*N]/255);w(W),R.current=requestAnimationFrame(E)};return R.current=requestAnimationFrame(E),()=>{cancelAnimationFrame(R.current),k.disconnect(),$.close()}},[r,l]),f.useEffect(()=>{const $=y.current;if(!$||b.length===0)return;const k=$.getContext("2d");if(!k)return;const z=window.devicePixelRatio||1,A=$.getBoundingClientRect();$.width=A.width*z,$.height=A.height*z,k.scale(z,z),k.clearRect(0,0,A.width,A.height);const E=getComputedStyle($),N=o||E.getPropertyValue("--muted-foreground").trim()||"#888",W=s||E.getPropertyValue("--primary").trim()||"#7c3aed",q=d+c,G=Math.max(0,(A.width-b.length*q)/2);for(let Z=0;Z<b.length;Z++){const I=Math.max(2,b[Z]*(u?A.height/2:A.height*.9)),F=G+Z*q,U=Z/b.length<=a;if(k.fillStyle=U?W:N,u){const ee=A.height/2-I;Ir(k,F,ee,d,I,p),k.fill(),Ir(k,F,A.height/2,d,I,p),k.fill()}else{const ee=A.height-I;Ir(k,F,ee,d,I,p),k.fill()}}},[b,a,o,s,d,c,p,u,i,C]);const V=$=>{if(!m||!y.current)return;const k=y.current.getBoundingClientRect(),z=($.clientX-k.left)/k.width;m(Math.max(0,Math.min(1,z)))},O=$=>{if(!m)return;const k=$.shiftKey?.1:.02;$.key==="ArrowRight"?($.preventDefault(),m(Math.min(1,a+k))):$.key==="ArrowLeft"&&($.preventDefault(),m(Math.max(0,a-k)))};return n.jsxs("div",{ref:x,className:v("relative w-full",g),role:"img","aria-label":_.audioWaveform_label,...h,children:[j&&!r&&n.jsx("div",{className:"absolute inset-0 flex items-center gap-[2px] justify-center",style:{height:i},children:Array.from({length:Math.min(l,30)}).map(($,k)=>n.jsx("div",{className:"bg-muted animate-pulse rounded-full",style:{width:d,height:`${20+Math.random()*60}%`,animationDelay:`${k*50}ms`}},k))}),n.jsx("canvas",{ref:y,style:{width:"100%",height:i},className:v(m&&"cursor-pointer"),onClick:V,onKeyDown:O,tabIndex:m?0:void 0,role:m?"slider":void 0,"aria-valuemin":m?0:void 0,"aria-valuemax":m?100:void 0,"aria-valuenow":m?Math.round(a*100):void 0}),T&&n.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-sm text-muted-foreground",children:T})]})});br.displayName="AudioWaveform";function Ir(e,t,r,o,s,a){e.beginPath(),e.moveTo(t+a,r),e.lineTo(t+o-a,r),e.quadraticCurveTo(t+o,r,t+o,r+a),e.lineTo(t+o,r+s-a),e.quadraticCurveTo(t+o,r+s,t+o-a,r+s),e.lineTo(t+a,r+s),e.quadraticCurveTo(t,r+s,t,r+s-a),e.lineTo(t,r+a),e.quadraticCurveTo(t,r,t+a,r),e.closePath()}const ni=Le("flex items-center gap-3 rounded-lg text-card-foreground",{variants:{variant:{default:"border bg-card p-3 shadow-sm",ghost:"bg-transparent p-3",minimal:"bg-transparent p-1 gap-2"},size:{sm:"p-2 gap-2",default:"",lg:"p-4 gap-4"}},defaultVariants:{variant:"default",size:"default"}}),km={sm:"h-3.5 w-3.5",default:"h-4 w-4",lg:"h-5 w-5"},wr=f.forwardRef(({src:e,title:t,artist:r,albumArt:o,showWaveform:s=!1,showVolume:a=!0,defaultVolume:i=1,autoPlay:l=!1,loop:d=!1,preload:c="metadata",variant:p,size:u="default",onPlay:m,onPause:g,onEnded:h,onTimeUpdate:x,className:y},b)=>{const w=f.useRef(null),j=f.useRef(null),M=f.useRef(!1),[R,_]=f.useState(!1),[C,S]=f.useState(0),[T,L]=f.useState(0),[V,O]=f.useState(0),[$,k]=f.useState(i),[z,A]=f.useState(!1),[E,N]=f.useState(!0),[W,q]=f.useState(null),G=ce(),Z=km[u??"default"];f.useEffect(()=>{const H=w.current;if(!H)return;const ne=()=>{L(H.duration),N(!1)},me=()=>N(!0),ve=()=>N(!1),fe=()=>{M.current||(S(H.currentTime),x==null||x(H.currentTime)),H.buffered.length>0&&O(H.buffered.end(H.buffered.length-1))},Re=()=>{_(!0),m==null||m()},ue=()=>{_(!1),g==null||g()},Fe=()=>{_(!1),h==null||h()},He=()=>{_(!1),N(!1),q(G.audioPlayer_error)};return H.addEventListener("loadedmetadata",ne),H.addEventListener("waiting",me),H.addEventListener("canplay",ve),H.addEventListener("timeupdate",fe),H.addEventListener("play",Re),H.addEventListener("pause",ue),H.addEventListener("ended",Fe),H.addEventListener("error",He),()=>{H.removeEventListener("loadedmetadata",ne),H.removeEventListener("waiting",me),H.removeEventListener("canplay",ve),H.removeEventListener("timeupdate",fe),H.removeEventListener("play",Re),H.removeEventListener("pause",ue),H.removeEventListener("ended",Fe),H.removeEventListener("error",He)}},[m,g,h,x,G.audioPlayer_error]),f.useEffect(()=>{const H=w.current;H&&(H.volume=z?0:$)},[$,z]),f.useEffect(()=>{q(null),S(0),L(0),O(0),N(!0)},[e]);const I=()=>{const H=w.current;H&&(R?H.pause():H.play())},F=f.useCallback(H=>{const ne=w.current;!ne||!T||(ne.currentTime=H*T,S(ne.currentTime))},[T]),U=H=>{if(!j.current)return;const ne=j.current.getBoundingClientRect();F((H.clientX-ne.left)/ne.width)},ee=H=>{var ne,me;M.current=!0,(me=(ne=H.target).setPointerCapture)==null||me.call(ne,H.pointerId)};f.useEffect(()=>{const H=j.current;if(!H)return;const ne=ve=>{if(!M.current||!j.current)return;const fe=j.current.getBoundingClientRect(),Re=Math.max(0,Math.min(1,(ve.clientX-fe.left)/fe.width));F(Re)},me=()=>{M.current=!1};return H.addEventListener("pointermove",ne),H.addEventListener("pointerup",me),H.addEventListener("lostpointercapture",me),()=>{H.removeEventListener("pointermove",ne),H.removeEventListener("pointerup",me),H.removeEventListener("lostpointercapture",me)}},[F]);const X=H=>{if(!w.current||!T)return;const ne=H.shiftKey?10:5;H.key==="ArrowLeft"?(H.preventDefault(),w.current.currentTime=Math.max(0,C-ne)):H.key==="ArrowRight"&&(H.preventDefault(),w.current.currentTime=Math.min(T,C+ne))},Y=H=>{H.key==="ArrowUp"||H.key==="+"?(H.preventDefault(),k(ne=>Math.min(1,ne+.1)),A(!1)):(H.key==="ArrowDown"||H.key==="-")&&(H.preventDefault(),k(ne=>Math.max(0,ne-.1)))},ae=()=>A(H=>!H),te=z||$===0?P.VolumeX:$<.5?P.Volume1:P.Volume2,ie=T?C/T:0,K=T?V/T:0;return n.jsxs("div",{ref:b,className:v(ni({variant:p,size:u}),y),children:[n.jsx("audio",{ref:w,src:e,autoPlay:l,loop:d,preload:c}),W&&n.jsx("div",{className:"flex-1 text-sm text-destructive",children:W}),!W&&n.jsxs(n.Fragment,{children:[o&&n.jsx("img",{src:o,alt:"",className:v("rounded object-cover shrink-0",u==="sm"?"h-8 w-8":u==="lg"?"h-14 w-14":"h-10 w-10")}),n.jsx("button",{type:"button",onClick:I,className:"shrink-0 flex items-center justify-center rounded-full bg-primary text-primary-foreground hover:bg-primary/90 active:scale-95 transition-all h-8 w-8 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","aria-label":R?G.audioPlayer_pause:G.audioPlayer_play,children:E&&R?n.jsx(P.Loader2,{className:v(Z,"animate-spin")}):R?n.jsx(P.Pause,{className:Z}):n.jsx(P.Play,{className:v(Z,"ml-0.5")})}),n.jsxs("div",{className:"flex-1 min-w-0 space-y-1",children:[(t||r)&&n.jsxs("div",{className:"flex items-center gap-2 text-xs leading-tight",children:[t&&n.jsx("span",{className:"font-medium truncate",children:t}),r&&n.jsx("span",{className:"text-muted-foreground truncate",children:r})]}),s?n.jsx(br,{src:e,progress:ie,height:u==="sm"?24:u==="lg"?40:32,barCount:60,onSeek:F}):n.jsxs("div",{ref:j,className:"relative h-1.5 bg-muted rounded-full cursor-pointer group",onClick:U,onPointerDown:ee,onKeyDown:X,role:"slider","aria-label":G.audioPlayer_seek,"aria-valuemin":0,"aria-valuemax":Math.round(T),"aria-valuenow":Math.round(C),"aria-valuetext":Ke(C),tabIndex:0,children:[n.jsx("div",{className:"absolute inset-y-0 left-0 bg-muted-foreground/30 rounded-full",style:{width:`${K*100}%`}}),n.jsx("div",{className:"absolute inset-y-0 left-0 bg-primary rounded-full transition-[width] duration-75",style:{width:`${ie*100}%`}}),n.jsx("div",{className:"absolute top-1/2 -translate-y-1/2 h-3 w-3 rounded-full bg-primary shadow opacity-0 group-hover:opacity-100 transition-opacity",style:{left:`${ie*100}%`,transform:"translate(-50%, -50%)"}})]}),n.jsxs("div",{className:"flex items-center justify-between text-[10px] text-muted-foreground tabular-nums",children:[n.jsx("span",{children:Ke(C)}),n.jsx("span",{children:Ke(T)})]})]}),a&&n.jsxs("div",{className:"shrink-0 flex items-center gap-1.5 group/volume [&:focus-within>input]:opacity-100",onKeyDown:Y,children:[n.jsx("button",{type:"button",onClick:ae,className:"p-1 rounded hover:bg-accent active:scale-95 transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":z?G.audioPlayer_unmute:G.audioPlayer_mute,children:n.jsx(te,{className:Z})}),n.jsx("input",{type:"range",min:0,max:1,step:.01,value:z?0:$,onChange:H=>{k(Number(H.target.value)),A(!1)},className:"w-16 h-1 accent-primary cursor-pointer opacity-0 group-hover/volume:opacity-100 focus:opacity-100 transition-opacity","aria-label":G.audioPlayer_volume})]})]})]})});wr.displayName="AudioPlayer";const oi=Le("space-y-3 rounded-lg border bg-card text-card-foreground shadow-sm",{variants:{size:{sm:"p-3",default:"p-4",lg:"p-5"}},defaultVariants:{size:"default"}}),si=f.forwardRef(({mimeType:e="audio/webm",maxDuration:t,showWaveform:r=!0,size:o,onRecordingComplete:s,onRecordingStart:a,onError:i,className:l},d)=>{const[c,p]=f.useState("idle"),[u,m]=f.useState(0),[g,h]=f.useState(null),[x,y]=f.useState(null),[b,w]=f.useState(null),j=f.useRef(null),M=f.useRef([]),R=f.useRef(null),_=f.useRef(null),C=f.useRef(null),S=ce(),T=f.useCallback(()=>{R.current&&(clearInterval(R.current),R.current=null),_.current&&(_.current.getTracks().forEach(E=>E.stop()),_.current=null,y(null)),C.current&&(URL.revokeObjectURL(C.current),C.current=null)},[]);f.useEffect(()=>T,[T]);const L=()=>{R.current=setInterval(()=>{m(E=>{const N=E+1;return t&&N>=t&&$(),N})},1e3)},V=()=>{R.current&&(clearInterval(R.current),R.current=null)},O=async()=>{w(null);try{const E=await navigator.mediaDevices.getUserMedia({audio:!0});y(E),_.current=E,m(0),g&&(URL.revokeObjectURL(g),h(null),C.current=null);const N=MediaRecorder.isTypeSupported(e)?e:"",W=new MediaRecorder(E,N?{mimeType:N}:void 0);W.ondataavailable=q=>{q.data.size>0&&M.current.push(q.data)},W.onstop=()=>{const q=new Blob(M.current,{type:N||"audio/webm"}),G=URL.createObjectURL(q);h(G),C.current=G,s==null||s(q),E.getTracks().forEach(Z=>Z.stop()),y(null),_.current=null},W.onerror=()=>{w(S.audioRecorder_error),T(),p("idle")},j.current=W,M.current=[],W.start(100),p("recording"),L(),a==null||a()}catch(E){const N=E instanceof Error?E:new Error(String(E));N.name==="NotAllowedError"||N.name==="PermissionDeniedError"?w(S.audioRecorder_permissionDenied):w(S.audioRecorder_error),i==null||i(N)}},$=()=>{j.current&&j.current.state!=="inactive"&&j.current.stop(),V(),p("stopped")},k=()=>{j.current&&j.current.state==="recording"&&(j.current.pause(),V(),p("paused"))},z=()=>{j.current&&j.current.state==="paused"&&(j.current.resume(),L(),p("recording"))},A=()=>{T(),m(0),h(null),C.current=null,w(null),p("idle")};return n.jsxs("div",{ref:d,className:v(oi({size:o}),l),children:[b&&n.jsxs("div",{className:"flex items-center gap-2 text-sm text-destructive",children:[n.jsx(P.AlertCircle,{className:"h-4 w-4 shrink-0"}),n.jsx("span",{children:b}),n.jsx("button",{type:"button",onClick:A,className:"ml-auto text-muted-foreground hover:text-foreground transition-colors",children:n.jsx(P.RotateCcw,{className:"h-4 w-4"})})]}),!b&&c==="stopped"&&g?n.jsxs("div",{className:"space-y-3",children:[n.jsx(wr,{src:g,size:"sm"}),n.jsxs("button",{type:"button",onClick:A,className:"flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[n.jsx(P.RotateCcw,{className:"h-4 w-4"}),S.audioRecorder_reRecord]})]}):b?null:n.jsxs(n.Fragment,{children:[r&&x&&c==="recording"&&n.jsx(br,{stream:x,height:48,barCount:50,className:"rounded"}),n.jsxs("div",{className:"flex items-center justify-center gap-4",children:[c==="idle"&&n.jsxs("button",{type:"button",onClick:O,className:"flex items-center gap-2 px-4 py-2 rounded-full bg-destructive text-destructive-foreground hover:bg-destructive/90 active:scale-95 transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","aria-label":S.audioRecorder_startRecording,children:[n.jsx(P.Mic,{className:"h-4 w-4"}),n.jsx("span",{className:"text-sm",children:S.audioRecorder_startRecording})]}),(c==="recording"||c==="paused")&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"text-sm font-mono tabular-nums text-muted-foreground min-w-[60px] text-center","aria-live":"off",children:[c==="recording"&&n.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-destructive animate-pulse mr-2"}),Ke(u)]}),c==="recording"?n.jsx("button",{type:"button",onClick:k,className:"p-2 rounded-full hover:bg-accent active:scale-95 transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":S.audioRecorder_pauseRecording,children:n.jsx(P.Pause,{className:"h-5 w-5"})}):n.jsx("button",{type:"button",onClick:z,className:"p-2 rounded-full hover:bg-accent active:scale-95 transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":S.audioRecorder_resumeRecording,children:n.jsx(P.Play,{className:"h-5 w-5"})}),n.jsx("button",{type:"button",onClick:$,className:"p-2 rounded-full bg-destructive text-destructive-foreground hover:bg-destructive/90 active:scale-95 transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","aria-label":S.audioRecorder_stopRecording,children:n.jsx(P.Square,{className:"h-5 w-5"})})]})]}),t&&(c==="recording"||c==="paused")&&n.jsx("div",{className:"w-full bg-muted rounded-full h-1",children:n.jsx("div",{className:"bg-destructive rounded-full h-1 transition-[width] duration-1000",style:{width:`${Math.min(100,u/t*100)}%`}})})]})]})});si.displayName="AudioRecorder";const Gr=Le("rounded-lg border bg-card text-card-foreground shadow-sm overflow-hidden",{variants:{variant:{default:"",compact:"[&_.ap-controls]:gap-2 [&_.ap-controls]:py-1"}},defaultVariants:{variant:"default"}}),ai=f.forwardRef(({tracks:e,showWaveform:t=!1,defaultRepeatMode:r="none",defaultShuffle:o=!1,autoPlay:s=!1,variant:a,onTrackChange:i,onPlayStateChange:l,className:d},c)=>{const[p,u]=f.useState(0),[m,g]=f.useState(r),[h,x]=f.useState(o),[y,b]=f.useState([]),[w,j]=f.useState(new Map),[M,R]=f.useState(null),_=f.useRef(null),C=ce();f.useEffect(()=>{if(h){const N=Array.from({length:e.length},(q,G)=>G);for(let q=N.length-1;q>0;q--){const G=Math.floor(Math.random()*(q+1));[N[q],N[G]]=[N[G],N[q]]}b(N);const W=new Map;N.forEach((q,G)=>W.set(q,G)),j(W)}},[h,e.length]);const S=f.useCallback((N,W=1)=>{if(h){const Z=(w.get(N)??-1)+W;return Z>=0&&Z<y.length?y[Z]:m==="all"?W===1?y[0]:y[y.length-1]:null}const q=N+W;return q>=0&&q<e.length?q:m==="all"?W===1?0:e.length-1:null},[h,y,w,e.length,m]),T=N=>{u(N),i==null||i(e[N],N)},L=()=>{if(m==="one")return;const N=S(p,1);N!==null&&T(N)},V=()=>{const N=S(p,-1);N!==null&&T(N)},O=()=>{const N=S(p,1);N!==null&&T(N)},$=()=>{g(N=>N==="none"?"all":N==="all"?"one":"none")},k=m==="none"?C.audioPlaylist_repeatOff:m==="all"?C.audioPlaylist_repeatAll:C.audioPlaylist_repeatOne,z=N=>{N.key==="ArrowDown"?(N.preventDefault(),R(W=>{const q=W===null?0:Math.min(W+1,e.length-1);return A(q),q})):N.key==="ArrowUp"?(N.preventDefault(),R(W=>{const q=W===null?e.length-1:Math.max(W-1,0);return A(q),q})):N.key==="Enter"||N.key===" "?(N.preventDefault(),M!==null&&T(M)):N.key==="Home"?(N.preventDefault(),R(0),A(0)):N.key==="End"&&(N.preventDefault(),R(e.length-1),A(e.length-1))},A=N=>{const W=_.current;if(!W)return;const q=W.children[N];q==null||q.scrollIntoView({block:"nearest"})},E=e[p];return E?n.jsxs("div",{ref:c,className:v(Gr({variant:a}),d),children:[n.jsxs("div",{className:"p-3 border-b space-y-2",children:[n.jsxs("div",{className:"ap-controls flex items-center justify-center gap-3",children:[n.jsx("button",{type:"button",onClick:()=>x(N=>!N),className:v("p-1.5 rounded hover:bg-accent active:scale-95 transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",h&&"text-primary"),"aria-label":C.audioPlaylist_shuffle,"aria-pressed":h,children:n.jsx(P.Shuffle,{className:"h-4 w-4"})}),n.jsx("button",{type:"button",onClick:V,className:"p-1.5 rounded hover:bg-accent active:scale-95 transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":C.audioPlaylist_previousTrack,children:n.jsx(P.SkipBack,{className:"h-4 w-4"})}),n.jsx("button",{type:"button",onClick:O,className:"p-1.5 rounded hover:bg-accent active:scale-95 transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":C.audioPlaylist_nextTrack,children:n.jsx(P.SkipForward,{className:"h-4 w-4"})}),n.jsx("button",{type:"button",onClick:$,className:v("p-1.5 rounded hover:bg-accent active:scale-95 transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",m!=="none"&&"text-primary"),"aria-label":k,children:m==="one"?n.jsx(P.Repeat1,{className:"h-4 w-4"}):n.jsx(P.Repeat,{className:"h-4 w-4"})})]}),n.jsx(wr,{src:E.src,title:E.title,artist:E.artist,albumArt:E.albumArt,showWaveform:t,autoPlay:s||p>0,loop:m==="one",onEnded:L,onPlay:()=>l==null?void 0:l(!0),onPause:()=>l==null?void 0:l(!1),size:"sm",variant:"ghost",className:"border-0 shadow-none p-0"},E.id)]}),n.jsx(fr,{className:"max-h-64",children:n.jsx("div",{ref:_,role:"listbox","aria-label":C.audioPlaylist_shuffle,tabIndex:0,onKeyDown:z,onBlur:()=>R(null),className:"divide-y focus-visible:outline-none",children:e.map((N,W)=>n.jsxs("button",{type:"button",role:"option","aria-selected":W===p,onClick:()=>T(W),className:v("w-full flex items-center gap-3 px-3 py-2 text-left hover:bg-accent/50 transition-colors",W===p&&"bg-accent",M===W&&"ring-2 ring-inset ring-ring"),children:[N.albumArt?n.jsx("img",{src:N.albumArt,alt:"",className:"h-8 w-8 rounded object-cover shrink-0"}):n.jsx("div",{className:"h-8 w-8 rounded bg-muted flex items-center justify-center shrink-0",children:W===p?n.jsx(P.Volume2,{className:"h-4 w-4 text-primary"}):n.jsx(P.Music,{className:"h-4 w-4 text-muted-foreground"})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:v("text-sm font-medium truncate",W===p&&"text-primary"),children:N.title}),N.artist&&n.jsx("p",{className:"text-xs text-muted-foreground truncate",children:N.artist})]}),N.duration!==void 0&&n.jsx("span",{className:"text-xs text-muted-foreground tabular-nums shrink-0",children:Ke(N.duration)})]},N.id))})}),e.length>1&&n.jsx("div",{className:"px-3 py-1.5 border-t text-xs text-muted-foreground text-center",children:ze(C.audioPlaylist_trackOf,{current:String(p+1),total:String(e.length)})})]}):n.jsx("div",{ref:c,className:v(Gr({variant:a}),"p-8",d),children:n.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 text-muted-foreground",children:[n.jsx(P.Music,{className:"h-8 w-8"}),n.jsx("p",{className:"text-sm",children:C.audioPlaylist_empty})]})})});ai.displayName="AudioPlaylist";const ii=Le("relative group rounded-lg overflow-hidden bg-card dark:bg-black text-card-foreground",{variants:{size:{sm:"[&_button]:p-0.5 [&_.vp-icon]:h-4 [&_.vp-icon]:w-4 [&_.vp-time]:text-[10px]",default:"",lg:"[&_button]:p-1.5 [&_.vp-icon]:h-6 [&_.vp-icon]:w-6 [&_.vp-time]:text-sm"}},defaultVariants:{size:"default"}}),Xt=f.forwardRef(({src:e,poster:t,showControls:r=!0,controlsTimeout:o=3e3,enablePiP:s=!0,enableFullscreen:a=!0,enablePlaybackRate:i=!0,playbackRates:l=[.5,.75,1,1.25,1.5,2],tracks:d,aspectRatio:c="16/9",autoPlay:p=!1,loop:u=!1,muted:m=!1,preload:g="metadata",size:h,onPlay:x,onPause:y,onEnded:b,onTimeUpdate:w,onFullscreenChange:j,className:M},R)=>{const _=f.useRef(null),C=f.useRef(null),S=f.useRef(null),T=f.useRef(null),L=f.useRef(!1),[V,O]=f.useState(!1),[$,k]=f.useState(0),[z,A]=f.useState(0),[E,N]=f.useState(0),[W,q]=f.useState(1),[G,Z]=f.useState(m),[I,F]=f.useState(!1),[U,ee]=f.useState(!0),[X,Y]=f.useState(!1),[ae,te]=f.useState(!1),[ie,K]=f.useState(1),[H,ne]=f.useState(-1),[me,ve]=f.useState(!0),[fe,Re]=f.useState(null),ue=ce(),Fe=f.useMemo(()=>D=>{C.current=D,typeof R=="function"?R(D):R&&(R.current=D)},[R]),He=typeof document<"u"&&"pictureInPictureEnabled"in document;f.useEffect(()=>{if(d){const D=d.findIndex(re=>re.default);D>=0&&ne(D)}},[d]),f.useEffect(()=>{const D=C.current;if(!D)return;const re=()=>{A(D.duration),ve(!1)},we=()=>ve(!0),Pe=()=>ve(!1),et=()=>{L.current||(k(D.currentTime),w==null||w(D.currentTime)),D.buffered.length>0&&N(D.buffered.end(D.buffered.length-1))},ft=()=>{O(!0),x==null||x()},it=()=>{O(!1),y==null||y()},lt=()=>{O(!1),b==null||b()},le=()=>{O(!1),ve(!1),Re(ue.videoPlayer_error)};return D.addEventListener("loadedmetadata",re),D.addEventListener("waiting",we),D.addEventListener("canplay",Pe),D.addEventListener("timeupdate",et),D.addEventListener("play",ft),D.addEventListener("pause",it),D.addEventListener("ended",lt),D.addEventListener("error",le),()=>{D.removeEventListener("loadedmetadata",re),D.removeEventListener("waiting",we),D.removeEventListener("canplay",Pe),D.removeEventListener("timeupdate",et),D.removeEventListener("play",ft),D.removeEventListener("pause",it),D.removeEventListener("ended",lt),D.removeEventListener("error",le)}},[x,y,b,w,ue.videoPlayer_error]),f.useEffect(()=>{const D=C.current;D&&(D.volume=G?0:W)},[W,G]),f.useEffect(()=>{Re(null),k(0),A(0),N(0),ve(!0)},[e]),f.useEffect(()=>{const D=()=>{const re=!!document.fullscreenElement;F(re),j==null||j(re)};return document.addEventListener("fullscreenchange",D),()=>document.removeEventListener("fullscreenchange",D)},[j]),f.useEffect(()=>{const D=C.current;if(D)for(let re=0;re<D.textTracks.length;re++)D.textTracks[re].mode=re===H?"showing":"hidden"},[H]),f.useEffect(()=>{if(!X&&!ae)return;const D=()=>{Y(!1),te(!1)},re=setTimeout(()=>{document.addEventListener("click",D,{once:!0})},0);return()=>{clearTimeout(re),document.removeEventListener("click",D)}},[X,ae]);const Ne=f.useCallback(()=>{ee(!0),T.current&&clearTimeout(T.current),V&&(T.current=setTimeout(()=>ee(!1),o))},[V,o]),Te=()=>{const D=C.current;D&&(V?D.pause():D.play())},nt=f.useCallback(D=>{const re=C.current;!re||!z||(re.currentTime=D*z,k(re.currentTime))},[z]),jt=D=>{if(!S.current)return;const re=S.current.getBoundingClientRect();nt((D.clientX-re.left)/re.width)},ot=D=>{var re,we;L.current=!0,(we=(re=D.target).setPointerCapture)==null||we.call(re,D.pointerId)};f.useEffect(()=>{const D=S.current;if(!D)return;const re=Pe=>{if(!L.current||!S.current)return;const et=S.current.getBoundingClientRect();nt(Math.max(0,Math.min(1,(Pe.clientX-et.left)/et.width)))},we=()=>{L.current=!1};return D.addEventListener("pointermove",re),D.addEventListener("pointerup",we),D.addEventListener("lostpointercapture",we),()=>{D.removeEventListener("pointermove",re),D.removeEventListener("pointerup",we),D.removeEventListener("lostpointercapture",we)}},[nt]);const st=()=>{var D,re;_.current&&(document.fullscreenElement?document.exitFullscreen():(re=(D=_.current).requestFullscreen)==null||re.call(D))},Nt=async()=>{const D=C.current;if(D)try{document.pictureInPictureElement?await document.exitPictureInPicture():await D.requestPictureInPicture()}catch{}},Ze=()=>Z(D=>!D),Ee=D=>{const re=C.current;re&&(re.playbackRate=D),K(D),Y(!1)},Qe=D=>{ne(D),te(!1)},Ge=D=>{const re=C.current;if(re){switch(D.key){case" ":case"k":D.preventDefault(),Te();break;case"f":D.preventDefault(),st();break;case"m":D.preventDefault(),Ze();break;case"ArrowLeft":D.preventDefault(),re.currentTime=Math.max(0,re.currentTime-5);break;case"ArrowRight":D.preventDefault(),re.currentTime=Math.min(z,re.currentTime+5);break;case"ArrowUp":D.preventDefault(),q(we=>Math.min(1,we+.1)),Z(!1);break;case"ArrowDown":D.preventDefault(),q(we=>Math.max(0,we-.1));break;case"c":D.preventDefault(),d&&d.length>0&&ne(we=>we>=0?-1:0);break}Ne()}},at=G||W===0?P.VolumeX:W<.5?P.Volume1:P.Volume2,kt=z?$/z:0,Ct=z?E/z:0;return n.jsxs("div",{ref:_,className:v(ii({size:h}),M),style:{aspectRatio:c},onMouseMove:Ne,onMouseLeave:()=>V&&ee(!1),onKeyDown:Ge,tabIndex:0,role:"application","aria-label":ue.videoPlayer_label,children:[n.jsx("video",{ref:Fe,src:e,poster:t,autoPlay:p,loop:u,muted:m,preload:g,className:"w-full h-full object-contain",onClick:Te,onDoubleClick:st,children:d==null?void 0:d.map((D,re)=>n.jsx("track",{src:D.src,kind:D.kind,srcLang:D.srcLang,label:D.label,default:D.default},re))}),fe&&n.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2 bg-card/90 dark:bg-black/90 z-30",children:[n.jsx(P.AlertCircle,{className:"h-10 w-10 text-destructive"}),n.jsx("p",{className:"text-sm text-destructive font-medium",children:fe})]}),me&&!fe&&V&&n.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-20 pointer-events-none",children:n.jsx(P.Loader2,{className:"h-10 w-10 text-primary animate-spin"})}),!V&&!fe&&r&&n.jsx("button",{type:"button",onClick:Te,className:"absolute inset-0 flex items-center justify-center z-10","aria-label":ue.videoPlayer_play,children:n.jsx("div",{className:"h-16 w-16 rounded-full bg-background/60 dark:bg-black/50 flex items-center justify-center backdrop-blur-sm hover:bg-background/80 dark:hover:bg-black/70 transition-colors",children:n.jsx(P.Play,{className:"h-8 w-8 text-foreground dark:text-white ml-1"})})}),r&&!fe&&n.jsxs("div",{className:v("absolute bottom-0 left-0 right-0 z-20 bg-gradient-to-t from-background/80 dark:from-black/80 to-transparent pt-8 pb-2 px-3 transition-opacity duration-200",U||!V?"opacity-100":"opacity-0 pointer-events-none"),children:[n.jsxs("div",{ref:S,className:"relative h-1 bg-foreground/20 dark:bg-white/20 rounded-full cursor-pointer mb-2 group/seek",onClick:jt,onPointerDown:ot,role:"slider","aria-label":ue.videoPlayer_seek,"aria-valuemin":0,"aria-valuemax":Math.round(z),"aria-valuenow":Math.round($),"aria-valuetext":Ke($),tabIndex:0,children:[n.jsx("div",{className:"absolute inset-y-0 left-0 bg-muted-foreground/30 rounded-full",style:{width:`${Ct*100}%`}}),n.jsx("div",{className:"absolute inset-y-0 left-0 bg-primary rounded-full",style:{width:`${kt*100}%`}}),n.jsx("div",{className:"absolute top-1/2 h-3 w-3 rounded-full bg-primary shadow opacity-0 group-hover/seek:opacity-100 transition-opacity",style:{left:`${kt*100}%`,transform:"translate(-50%, -50%)"}})]}),n.jsxs("div",{className:"flex items-center gap-2 text-foreground dark:text-white",children:[n.jsx("button",{type:"button",onClick:Te,className:"p-1 hover:bg-foreground/10 dark:hover:bg-white/10 rounded transition-colors","aria-label":V?ue.videoPlayer_pause:ue.videoPlayer_play,children:V?n.jsx(P.Pause,{className:"vp-icon h-5 w-5"}):n.jsx(P.Play,{className:"vp-icon h-5 w-5"})}),n.jsxs("span",{className:"vp-time text-xs tabular-nums",children:[Ke($)," / ",Ke(z)]}),n.jsx("div",{className:"flex-1"}),n.jsxs("div",{className:"flex items-center gap-1 group/vol",children:[n.jsx("button",{type:"button",onClick:Ze,className:"p-1 hover:bg-foreground/10 dark:hover:bg-white/10 rounded transition-colors","aria-label":G?ue.videoPlayer_unmute:ue.videoPlayer_mute,children:n.jsx(at,{className:"vp-icon h-5 w-5"})}),n.jsx("input",{type:"range",min:0,max:1,step:.01,value:G?0:W,onChange:D=>{q(Number(D.target.value)),Z(!1)},className:"w-16 h-1 accent-primary cursor-pointer opacity-0 group-hover/vol:opacity-100 focus:opacity-100 transition-opacity","aria-label":ue.videoPlayer_volume})]}),i&&n.jsxs("div",{className:"relative",children:[n.jsxs("button",{type:"button",onClick:D=>{D.stopPropagation(),Y(re=>!re),te(!1)},className:"px-1.5 py-0.5 text-xs hover:bg-foreground/10 dark:hover:bg-white/10 rounded transition-colors","aria-label":ue.videoPlayer_playbackSpeed,children:[ie,"x"]}),X&&n.jsx("div",{className:"absolute bottom-full right-0 mb-1 bg-popover text-popover-foreground rounded-md border shadow-md py-1 min-w-[60px]",onClick:D=>D.stopPropagation(),children:l.map(D=>n.jsxs("button",{type:"button",onClick:()=>Ee(D),className:v("block w-full px-3 py-1 text-xs text-left hover:bg-accent transition-colors",D===ie&&"text-primary"),children:[D,"x"]},D))})]}),d&&d.length>0&&n.jsxs("div",{className:"relative",children:[n.jsx("button",{type:"button",onClick:D=>{D.stopPropagation(),te(re=>!re),Y(!1)},className:v("p-1 hover:bg-foreground/10 dark:hover:bg-white/10 rounded transition-colors",H>=0&&"text-primary"),"aria-label":ue.videoPlayer_subtitles,children:n.jsx(P.Subtitles,{className:"vp-icon h-5 w-5"})}),ae&&n.jsxs("div",{className:"absolute bottom-full right-0 mb-1 bg-popover text-popover-foreground rounded-md border shadow-md py-1 min-w-[120px]",onClick:D=>D.stopPropagation(),children:[n.jsx("button",{type:"button",onClick:()=>Qe(-1),className:v("block w-full px-3 py-1 text-xs text-left hover:bg-accent transition-colors",H===-1&&"text-primary"),children:ue.videoPlayer_subtitlesOff}),d.map((D,re)=>n.jsx("button",{type:"button",onClick:()=>Qe(re),className:v("block w-full px-3 py-1 text-xs text-left hover:bg-accent transition-colors",re===H&&"text-primary"),children:D.label},re))]})]}),s&&He&&n.jsx("button",{type:"button",onClick:Nt,className:"p-1 hover:bg-foreground/10 dark:hover:bg-white/10 rounded transition-colors","aria-label":ue.videoPlayer_pictureInPicture,children:n.jsx(P.PictureInPicture2,{className:"vp-icon h-5 w-5"})}),a&&n.jsx("button",{type:"button",onClick:st,className:"p-1 hover:bg-foreground/10 dark:hover:bg-white/10 rounded transition-colors","aria-label":I?ue.videoPlayer_exitFullscreen:ue.videoPlayer_fullscreen,children:I?n.jsx(P.Minimize,{className:"vp-icon h-5 w-5"}):n.jsx(P.Maximize,{className:"vp-icon h-5 w-5"})})]})]})]})});Xt.displayName="VideoPlayer";const li=f.forwardRef(({source:e="camera",videoConstraints:t,audioConstraints:r=!0,mimeType:o="video/webm",maxDuration:s,showTimer:a=!0,mirrored:i,onRecordingComplete:l,onRecordingStart:d,onError:c,className:p},u)=>{const[m,g]=f.useState("idle"),[h,x]=f.useState(0),[y,b]=f.useState(null),[w,j]=f.useState(null),[M,R]=f.useState(null),_=f.useRef(null),C=f.useRef(null),S=f.useRef([]),T=f.useRef(null),L=f.useRef(null),V=f.useRef(null),O=ce(),$=i!==void 0?i:e==="camera",k=f.useCallback(()=>{T.current&&(clearInterval(T.current),T.current=null),L.current&&(L.current.getTracks().forEach(I=>I.stop()),L.current=null,j(null)),V.current&&(URL.revokeObjectURL(V.current),V.current=null)},[]);f.useEffect(()=>k,[k]);const z=()=>{T.current=setInterval(()=>{x(I=>{const F=I+1;return s&&F>=s&&W(),F})},1e3)},A=()=>{T.current&&(clearInterval(T.current),T.current=null)},E=async()=>{R(null);try{let I;e==="screen"?I=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!!r}):I=await navigator.mediaDevices.getUserMedia({video:t||!0,audio:r}),I.getVideoTracks().forEach(F=>{F.addEventListener("ended",()=>{k(),g("idle")})}),j(I),L.current=I,g("preview"),_.current&&(_.current.srcObject=I)}catch(I){const F=I instanceof Error?I:new Error(String(I));F.name==="NotAllowedError"||F.name==="PermissionDeniedError"?R(O.videoRecorder_permissionDenied):R(O.videoRecorder_error),c==null||c(F)}};f.useEffect(()=>{_.current&&w&&(m==="preview"||m==="recording"||m==="paused")&&(_.current.srcObject=w)},[w,m]);const N=()=>{if(!w)return;S.current=[],x(0),y&&(URL.revokeObjectURL(y),b(null),V.current=null);const I=MediaRecorder.isTypeSupported(o)?o:"",F=new MediaRecorder(w,I?{mimeType:I}:void 0);F.ondataavailable=U=>{U.data.size>0&&S.current.push(U.data)},F.onstop=()=>{const U=new Blob(S.current,{type:I||"video/webm"}),ee=URL.createObjectURL(U);b(ee),V.current=ee,l==null||l(U),w.getTracks().forEach(X=>X.stop()),j(null),L.current=null},F.onerror=()=>{R(O.videoRecorder_error),k(),g("idle")},C.current=F,F.start(100),g("recording"),z(),d==null||d()},W=()=>{C.current&&C.current.state!=="inactive"&&C.current.stop(),A(),g("stopped")},q=()=>{C.current&&C.current.state==="recording"&&(C.current.pause(),A(),g("paused"))},G=()=>{C.current&&C.current.state==="paused"&&(C.current.resume(),z(),g("recording"))},Z=()=>{k(),x(0),b(null),V.current=null,R(null),g("idle")};return n.jsxs("div",{ref:u,className:v("space-y-3 rounded-lg border bg-card text-card-foreground shadow-sm overflow-hidden",p),children:[M&&n.jsxs("div",{className:"flex items-center gap-2 p-4 text-sm text-destructive",children:[n.jsx(P.AlertCircle,{className:"h-4 w-4 shrink-0"}),n.jsx("span",{children:M}),n.jsx("button",{type:"button",onClick:Z,className:"ml-auto text-muted-foreground hover:text-foreground transition-colors",children:n.jsx(P.RotateCcw,{className:"h-4 w-4"})})]}),!M&&m==="stopped"&&y?n.jsxs("div",{className:"space-y-3",children:[n.jsx(Xt,{src:y,aspectRatio:"16/9"}),n.jsx("div",{className:"px-4 pb-3",children:n.jsxs("button",{type:"button",onClick:Z,className:"flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[n.jsx(P.RotateCcw,{className:"h-4 w-4"}),O.videoRecorder_reRecord]})})]}):!M&&m==="idle"?n.jsx("div",{className:"flex items-center justify-center gap-3 p-8",children:n.jsx("button",{type:"button",onClick:E,className:"flex items-center gap-2 px-4 py-2 rounded-lg bg-primary text-primary-foreground hover:bg-primary/90 active:scale-95 transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e==="screen"?n.jsxs(n.Fragment,{children:[n.jsx(P.Monitor,{className:"h-4 w-4"}),n.jsx("span",{className:"text-sm",children:O.videoRecorder_shareScreen})]}):n.jsxs(n.Fragment,{children:[n.jsx(P.Camera,{className:"h-4 w-4"}),n.jsx("span",{className:"text-sm",children:O.videoRecorder_startCamera})]})})}):M?null:n.jsxs("div",{className:"relative",children:[n.jsx("video",{ref:_,autoPlay:!0,muted:!0,playsInline:!0,className:v("w-full",$&&"scale-x-[-1]"),style:{aspectRatio:"16/9"},"aria-label":e==="camera"?O.videoRecorder_cameraPreview:O.videoRecorder_screenPreview}),a&&(m==="recording"||m==="paused")&&n.jsxs("div",{className:"absolute top-3 left-3 flex items-center gap-2 px-2 py-1 rounded bg-background/60 dark:bg-black/60 text-foreground dark:text-white text-sm tabular-nums backdrop-blur-sm",children:[m==="recording"&&n.jsx("span",{className:"h-2 w-2 rounded-full bg-destructive animate-pulse"}),Ke(h)]}),n.jsxs("div",{className:"absolute bottom-3 left-1/2 -translate-x-1/2 flex items-center gap-3",children:[m==="preview"&&n.jsx("button",{type:"button",onClick:N,className:"h-12 w-12 rounded-full bg-destructive hover:bg-destructive/90 flex items-center justify-center transition-colors border-4 border-background/80 dark:border-white/80 active:scale-95 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":O.videoRecorder_startRecording,children:n.jsx(P.Circle,{className:"h-5 w-5 text-destructive-foreground fill-destructive-foreground"})}),m==="recording"&&n.jsxs(n.Fragment,{children:[n.jsx("button",{type:"button",onClick:q,className:"p-2 rounded-full bg-background/50 dark:bg-black/50 hover:bg-background/70 dark:hover:bg-black/70 text-foreground dark:text-white transition-colors backdrop-blur-sm active:scale-95","aria-label":O.videoRecorder_pauseRecording,children:n.jsx(P.Pause,{className:"h-5 w-5"})}),n.jsx("button",{type:"button",onClick:W,className:"h-12 w-12 rounded-full bg-destructive hover:bg-destructive/90 flex items-center justify-center transition-colors border-4 border-background/80 dark:border-white/80 active:scale-95","aria-label":O.videoRecorder_stopRecording,children:n.jsx(P.Square,{className:"h-5 w-5 text-destructive-foreground fill-destructive-foreground"})})]}),m==="paused"&&n.jsxs(n.Fragment,{children:[n.jsx("button",{type:"button",onClick:G,className:"p-2 rounded-full bg-background/50 dark:bg-black/50 hover:bg-background/70 dark:hover:bg-black/70 text-foreground dark:text-white transition-colors backdrop-blur-sm active:scale-95","aria-label":O.videoRecorder_resumeRecording,children:n.jsx(P.Play,{className:"h-5 w-5"})}),n.jsx("button",{type:"button",onClick:W,className:"h-12 w-12 rounded-full bg-destructive hover:bg-destructive/90 flex items-center justify-center transition-colors border-4 border-background/80 dark:border-white/80 active:scale-95","aria-label":O.videoRecorder_stopRecording,children:n.jsx(P.Square,{className:"h-5 w-5 text-destructive-foreground fill-destructive-foreground"})})]})]}),s&&(m==="recording"||m==="paused")&&n.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-1 bg-foreground/20 dark:bg-white/20",children:n.jsx("div",{className:"h-full bg-destructive transition-[width] duration-1000",style:{width:`${Math.min(100,h/s*100)}%`}})})]})]})});li.displayName="VideoRecorder";const Pn=f.forwardRef(({src:e,poster:t,title:r,duration:o,clickAction:s="inline",aspectRatio:a="16/9",showDuration:i=!0,showPlayButton:l=!0,onPlay:d,className:c,...p},u)=>{const[m,g]=f.useState(!1),[h,x]=f.useState(null),y=ce();f.useEffect(()=>{if(t||!e)return;const R=document.createElement("video");R.crossOrigin="anonymous",R.preload="metadata",R.muted=!0;const _=()=>{try{const S=document.createElement("canvas");S.width=R.videoWidth,S.height=R.videoHeight;const T=S.getContext("2d");T&&(T.drawImage(R,0,0),x(S.toDataURL("image/jpeg",.7)))}catch{}R.remove()};R.addEventListener("seeked",_,{once:!0});const C=()=>{R.currentTime=Math.min(1,R.duration*.1)};return R.addEventListener("loadedmetadata",C,{once:!0}),R.src=e,()=>{R.removeEventListener("seeked",_),R.removeEventListener("loadedmetadata",C),R.src="",R.remove()}},[e,t]);const b=()=>{s==="inline"?(g(!0),d==null||d()):s==="none"&&(d==null||d())},w=R=>{(R.key==="Enter"||R.key===" ")&&(R.preventDefault(),b())},j=t||h,M=r?ze(y.videoThumbnail_play,{title:r}):y.videoPlayer_play;return m&&s==="inline"?n.jsx("div",{ref:u,className:v("rounded-lg overflow-hidden bg-card dark:bg-black",c),style:{aspectRatio:a},...p,children:n.jsx(Xt,{src:e,autoPlay:!0,aspectRatio:a})}):n.jsxs("div",{ref:u,className:v("relative rounded-lg overflow-hidden bg-muted cursor-pointer group",c),style:{aspectRatio:a},onClick:b,onKeyDown:w,role:"button",tabIndex:0,"aria-label":M,...p,children:[j?n.jsx("img",{src:j,alt:r||"",className:"w-full h-full object-cover",draggable:!1}):n.jsx("div",{className:"w-full h-full bg-muted flex items-center justify-center",children:n.jsx(P.Play,{className:"h-8 w-8 text-muted-foreground"})}),l&&n.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:n.jsx("div",{className:"h-12 w-12 rounded-full bg-background/60 dark:bg-black/50 flex items-center justify-center backdrop-blur-sm group-hover:bg-background/80 dark:group-hover:bg-black/70 group-hover:scale-110 transition-all",children:n.jsx(P.Play,{className:"h-6 w-6 text-foreground dark:text-white ml-0.5"})})}),i&&o!==void 0&&n.jsx("span",{className:"absolute bottom-2 right-2 px-1.5 py-0.5 rounded bg-card/80 dark:bg-black/70 text-card-foreground dark:text-white text-xs tabular-nums backdrop-blur-sm",children:Ke(o)}),r&&n.jsx("div",{className:"absolute bottom-0 left-0 right-0 bg-gradient-to-t from-background/60 dark:from-black/60 to-transparent p-2 pt-6",children:n.jsx("p",{className:"text-foreground dark:text-white text-sm font-medium truncate",children:r})})]})});Pn.displayName="VideoThumbnail";const ci=f.forwardRef(({videos:e,columns:t=3,gap:r=4,aspectRatio:o="16/9",clickAction:s="lightbox",onVideoSelect:a,className:i,...l},d)=>{const[c,p]=f.useState(null),[u,m]=f.useState(null),g=f.useRef(null),h=f.useRef(null),x=ce(),y=f.useCallback(()=>{if(typeof t=="number")return t;if(typeof window>"u")return t.sm??3;const L=window.innerWidth;return t.xl&&L>=1280?t.xl:t.lg&&L>=1024?t.lg:t.md&&L>=768?t.md:t.sm??3},[t]),[b,w]=f.useState(typeof t=="number"?t:3);f.useEffect(()=>{const L=()=>w(y());return L(),window.addEventListener("resize",L),()=>window.removeEventListener("resize",L)},[y]);const j=(L,V)=>{a==null||a(L,V),s==="lightbox"&&(g.current=document.activeElement instanceof HTMLElement?document.activeElement:null,p(V))},M=()=>{var L;p(null),(L=g.current)==null||L.focus()},R=f.useCallback(()=>{c!==null&&p(c>0?c-1:e.length-1)},[c,e.length]),_=f.useCallback(()=>{c!==null&&p(c<e.length-1?c+1:0)},[c,e.length]);f.useEffect(()=>{var O;if(c===null)return;const L=document.body.style.overflow;document.body.style.overflow="hidden",(O=h.current)==null||O.focus();const V=$=>{switch($.key){case"Escape":$.preventDefault(),M();break;case"ArrowLeft":$.preventDefault(),R();break;case"ArrowRight":$.preventDefault(),_();break}if($.key==="Tab"&&h.current){const k=h.current.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(k.length===0)return;const z=k[0],A=k[k.length-1];$.shiftKey?document.activeElement===z&&($.preventDefault(),A.focus()):document.activeElement===A&&($.preventDefault(),z.focus())}};return document.addEventListener("keydown",V),()=>{document.removeEventListener("keydown",V),document.body.style.overflow=L}},[c,R,_]);const C=L=>{m(L.touches[0].clientX)},S=L=>{var $;if(u===null)return;const V=u-L.changedTouches[0].clientX,O=Math.max(30,Math.min(80,((($=h.current)==null?void 0:$.offsetWidth)??300)*.1));Math.abs(V)>O&&(V>0?_():R()),m(null)},T={gridTemplateColumns:`repeat(${b}, minmax(0, 1fr))`};return n.jsxs(n.Fragment,{children:[n.jsx("div",{ref:d,className:v("grid",i),style:{...T,gap:`${r*4}px`},role:"list","aria-label":x.videoGallery_label,...l,children:e.map((L,V)=>n.jsx(Pn,{src:L.src,poster:L.poster,title:L.title,duration:L.duration,aspectRatio:o,clickAction:"none",onPlay:()=>j(L,V),role:"listitem"},L.id))}),s==="lightbox"&&c!==null&&e[c]&&qr.createPortal(n.jsxs("div",{ref:h,className:"fixed inset-0 z-50 flex items-center justify-center bg-background/95 dark:bg-black/95",onClick:L=>{L.target===L.currentTarget&&M()},onTouchStart:C,onTouchEnd:S,role:"dialog","aria-modal":"true","aria-label":x.videoGallery_label,tabIndex:-1,children:[n.jsx("button",{type:"button",onClick:M,className:"absolute top-4 right-4 z-10 p-2 rounded-full bg-foreground/10 hover:bg-foreground/20 text-foreground transition-colors","aria-label":x.common_close,children:n.jsx(P.X,{className:"h-5 w-5"})}),e.length>1&&n.jsxs(n.Fragment,{children:[n.jsx("button",{type:"button",onClick:R,className:"absolute left-4 top-1/2 -translate-y-1/2 z-10 p-2 rounded-full bg-foreground/10 hover:bg-foreground/20 text-foreground transition-colors","aria-label":x.common_previous,children:n.jsx(P.ChevronLeft,{className:"h-6 w-6"})}),n.jsx("button",{type:"button",onClick:_,className:"absolute right-4 top-1/2 -translate-y-1/2 z-10 p-2 rounded-full bg-foreground/10 hover:bg-foreground/20 text-foreground transition-colors","aria-label":x.common_next,children:n.jsx(P.ChevronRight,{className:"h-6 w-6"})})]}),n.jsxs("div",{className:"w-full max-w-4xl px-4",children:[n.jsx(Xt,{src:e[c].src,poster:e[c].poster,autoPlay:!0,aspectRatio:o},e[c].id),e[c].title&&n.jsx("p",{className:"text-foreground text-sm mt-3 text-center",children:e[c].title})]}),n.jsxs("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 text-muted-foreground text-sm tabular-nums",children:[c+1," / ",e.length]})]}),document.body)]})});ci.displayName="VideoGallery";const Cm={contain:"object-contain",cover:"object-cover",fill:"object-fill",none:"object-none","scale-down":"object-scale-down"},di=f.forwardRef(({src:e,alt:t,fallbackSrc:r,placeholder:o,showSkeleton:s=!0,lazy:a=!0,rootMargin:i="200px",aspectRatio:l,zoomOnHover:d=!1,zoomScale:c=1.5,zoomOnClick:p=!1,fit:u="cover",className:m,style:g,onLoad:h,onError:x,...y},b)=>{const[w,j]=f.useState("loading"),[M,R]=f.useState(!a),[_,C]=f.useState(e),[S,T]=f.useState(!1),L=f.useRef(null),V=ce();f.useEffect(()=>{C(e),j("loading")},[e]),f.useEffect(()=>{if(!a||!L.current)return;const E=new IntersectionObserver(([N])=>{N.isIntersecting&&(R(!0),E.disconnect())},{rootMargin:i});return E.observe(L.current),()=>E.disconnect()},[a,i]);const O=E=>{j("loaded"),h==null||h(E)},$=E=>{r&&_!==r?C(r):j("error"),x==null||x(E)},k=()=>{p&&T(E=>!E)},z=E=>{p&&(E.key==="Enter"||E.key===" ")&&(E.preventDefault(),T(N=>!N))},A=l!==void 0?{aspectRatio:typeof l=="number"?`${l}`:l}:{};return n.jsxs("div",{ref:L,className:v("group relative overflow-hidden inline-block",p&&"cursor-zoom-in focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",m),style:{...A,...g},onClick:k,onKeyDown:z,tabIndex:p?0:void 0,role:p?"button":void 0,"aria-label":p?V.image_zoomIn:void 0,children:[M&&_?n.jsx("img",{ref:b,src:_,alt:t??"",className:v("w-full h-full transition-transform duration-300",Cm[u],d&&"hover:scale-[var(--zoom-scale)]",S&&"scale-[var(--zoom-scale)]",w==="loading"&&"opacity-0"),style:{"--zoom-scale":c},onLoad:O,onError:$,...y}):null,w==="loading"&&M&&n.jsx("div",{className:"absolute inset-0",children:o||s&&n.jsx("div",{className:"w-full h-full animate-pulse bg-muted rounded-md"})}),w==="error"&&n.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2 bg-muted rounded-md",children:[n.jsx(P.ImageOff,{className:"h-6 w-6 text-muted-foreground"}),n.jsx("span",{className:"text-xs text-muted-foreground",children:V.image_failedToLoad})]}),p&&w==="loaded"&&!S&&n.jsx("div",{className:"absolute bottom-2 right-2 p-1.5 rounded-full bg-background/60 dark:bg-black/50 text-foreground dark:text-white opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none backdrop-blur-sm",children:n.jsx(P.ZoomIn,{className:"h-4 w-4"})})]})});di.displayName="NUIImage";function ui({images:e,open:t,defaultIndex:r=0,onClose:o,onIndexChange:s,enableZoom:a=!0,enableKeyboard:i=!0,enableDownload:l=!1,showCounter:d=!0,showThumbnails:c=!1,className:p,children:u}){const[m,g]=f.useState(!1),[h,x]=f.useState(r),[y,b]=f.useState(!1),[w,j]=f.useState(!0),[M,R]=f.useState(null),_=f.useRef(null),C=f.useRef(null),S=ce(),T=t!==void 0?t:m,L=G=>{_.current=document.activeElement instanceof HTMLElement?document.activeElement:null,G!==void 0&&x(G),j(!0),g(!0)},V=()=>{var G;g(!1),b(!1),o==null||o(),(G=_.current)==null||G.focus()},O=f.useCallback(G=>{x(G),b(!1),j(!0),s==null||s(G)},[s]),$=f.useCallback(()=>{O(h>0?h-1:e.length-1)},[h,e.length,O]),k=f.useCallback(()=>{O(h<e.length-1?h+1:0)},[h,e.length,O]);f.useEffect(()=>{if(!T||!i)return;const G=Z=>{switch(Z.key){case"Escape":Z.preventDefault(),V();break;case"ArrowLeft":Z.preventDefault(),$();break;case"ArrowRight":Z.preventDefault(),k();break}};return document.addEventListener("keydown",G),()=>document.removeEventListener("keydown",G)},[T,i,$,k]),f.useEffect(()=>{var I;if(!T)return;const G=document.body.style.overflow;document.body.style.overflow="hidden",(I=C.current)==null||I.focus();const Z=F=>{if(F.key!=="Tab"||!C.current)return;const U=C.current.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(U.length===0)return;const ee=U[0],X=U[U.length-1];F.shiftKey?document.activeElement===ee&&(F.preventDefault(),X.focus()):document.activeElement===X&&(F.preventDefault(),ee.focus())};return document.addEventListener("keydown",Z),()=>{document.body.style.overflow=G,document.removeEventListener("keydown",Z)}},[T]);const z=G=>{G.target===C.current&&V()},A=G=>{R(G.touches[0].clientX)},E=G=>{var F;if(M===null)return;const Z=M-G.changedTouches[0].clientX,I=Math.max(30,Math.min(80,(((F=C.current)==null?void 0:F.offsetWidth)??300)*.1));Math.abs(Z)>I&&(Z>0?k():$()),R(null)},N=()=>{a&&b(G=>!G)},W=()=>{const G=e[h];if(!G)return;const Z=document.createElement("a");Z.href=G.src,Z.download=G.alt||"image",Z.click()};if(!T)return u?n.jsx("div",{onClick:()=>L(r),className:"cursor-pointer",children:u}):null;const q=e[h];return q?qr.createPortal(n.jsxs("div",{ref:C,className:v("fixed inset-0 z-50 flex flex-col items-center justify-center bg-background/95 dark:bg-black/95",p),onClick:z,onTouchStart:A,onTouchEnd:E,role:"dialog","aria-modal":"true","aria-label":S.lightbox_label,tabIndex:-1,children:[n.jsxs("div",{className:"absolute top-4 left-0 right-0 z-10 flex items-center justify-between px-4",children:[d&&e.length>1&&n.jsx("div",{className:"text-muted-foreground text-sm tabular-nums","aria-live":"polite",children:ze(S.lightbox_imageOf,{current:String(h+1),total:String(e.length)})}),!d&&n.jsx("div",{}),n.jsxs("div",{className:"flex items-center gap-2",children:[l&&n.jsx("button",{type:"button",onClick:W,className:"p-2 rounded-full bg-foreground/10 hover:bg-foreground/20 text-foreground transition-colors","aria-label":S.lightbox_download,children:n.jsx(P.Download,{className:"h-5 w-5"})}),a&&n.jsx("button",{type:"button",onClick:()=>b(G=>!G),className:"p-2 rounded-full bg-foreground/10 hover:bg-foreground/20 text-foreground transition-colors","aria-label":y?S.lightbox_zoomOut:S.lightbox_zoomIn,children:y?n.jsx(P.ZoomOut,{className:"h-5 w-5"}):n.jsx(P.ZoomIn,{className:"h-5 w-5"})}),n.jsx("button",{type:"button",onClick:V,className:"p-2 rounded-full bg-foreground/10 hover:bg-foreground/20 text-foreground transition-colors","aria-label":S.common_close,children:n.jsx(P.X,{className:"h-5 w-5"})})]})]}),e.length>1&&n.jsxs(n.Fragment,{children:[n.jsx("button",{type:"button",onClick:$,className:"absolute left-4 top-1/2 -translate-y-1/2 z-10 p-2 rounded-full bg-foreground/10 hover:bg-foreground/20 text-foreground transition-colors","aria-label":S.common_previous,children:n.jsx(P.ChevronLeft,{className:"h-6 w-6"})}),n.jsx("button",{type:"button",onClick:k,className:"absolute right-4 top-1/2 -translate-y-1/2 z-10 p-2 rounded-full bg-foreground/10 hover:bg-foreground/20 text-foreground transition-colors","aria-label":S.common_next,children:n.jsx(P.ChevronRight,{className:"h-6 w-6"})})]}),n.jsxs("div",{className:v("flex-1 flex items-center justify-center w-full",y?"overflow-auto cursor-zoom-out":"cursor-zoom-in"),onDoubleClick:N,children:[w&&n.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:n.jsx(P.Loader2,{className:"h-8 w-8 text-primary animate-spin"})}),n.jsx("img",{src:q.src,alt:q.alt||"",className:v("transition-all duration-200 select-none",y?"max-w-none max-h-none":"max-h-[85vh] max-w-[90vw] object-contain",w&&"opacity-0"),style:y?{transform:"scale(2)"}:void 0,draggable:!1,onLoad:()=>j(!1)},q.src)]}),(q.title||q.description)&&n.jsxs("div",{className:"absolute bottom-16 left-1/2 -translate-x-1/2 text-center text-foreground max-w-lg px-4",children:[q.title&&n.jsx("p",{className:"text-sm font-medium",children:q.title}),q.description&&n.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:q.description})]}),c&&e.length>1&&n.jsx("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2 max-w-[90vw] overflow-x-auto px-4 py-2",children:e.map((G,Z)=>n.jsx("button",{type:"button",onClick:()=>O(Z),className:v("shrink-0 w-12 h-12 rounded overflow-hidden border-2 transition-all",Z===h?"border-primary":"border-transparent opacity-60 hover:opacity-100"),children:n.jsx("img",{src:G.src,alt:"",className:"w-full h-full object-cover"})},Z))})]}),document.body):null}ui.displayName="Lightbox";const mi=f.forwardRef(({src:e,aspectRatio:t,minSize:r=50,maxSize:o,initialCrop:s,outputFormat:a="image/png",outputQuality:i=.92,onCropComplete:l,onCropChange:d,onError:c,showGrid:p=!0,circular:u=!1,className:m},g)=>{const h=f.useRef(null),x=f.useRef(null),[y,b]=f.useState(!1),[w,j]=f.useState({width:0,height:0}),[M,R]=f.useState(s||{x:.15,y:.15,width:.7,height:.7}),[_,C]=f.useState(null),[S,T]=f.useState(null),[L,V]=f.useState({x:0,y:0}),[O,$]=f.useState({x:0,y:0,width:0,height:0}),k=f.useRef(null),z=ce();f.useEffect(()=>{s&&R(s)},[s]);const A=()=>{x.current&&(j({width:x.current.naturalWidth,height:x.current.naturalHeight}),b(!0))},E=f.useCallback(I=>{let{x:F,y:U,width:ee,height:X}=I;const Y=r/(w.width||1),ae=r/(w.height||1);if(ee=Math.max(Y,ee),X=Math.max(ae,X),o&&(ee=Math.min(o/(w.width||1),ee),X=Math.min(o/(w.height||1),X)),ee=Math.min(1,ee),X=Math.min(1,X),t){const te=(w.width||1)/(w.height||1),ie=t/te;ee/X>ie?ee=X*ie:X=ee/ie}return F=Math.max(0,Math.min(1-ee,F)),U=Math.max(0,Math.min(1-X,U)),{x:F,y:U,width:ee,height:X}},[w,r,o,t]);f.useEffect(()=>{if(!_)return;const I=U=>{U.preventDefault();const ee=h.current;if(!ee)return;const X=ee.getBoundingClientRect(),Y=(U.clientX-L.x)/X.width,ae=(U.clientY-L.y)/X.height;let te;if(_==="move")te=E({...O,x:O.x+Y,y:O.y+ae});else{switch(te={...O},S){case"se":te.width=O.width+Y,te.height=O.height+ae;break;case"sw":te.x=O.x+Y,te.width=O.width-Y,te.height=O.height+ae;break;case"ne":te.y=O.y+ae,te.width=O.width+Y,te.height=O.height-ae;break;case"nw":te.x=O.x+Y,te.y=O.y+ae,te.width=O.width-Y,te.height=O.height-ae;break;case"n":te.y=O.y+ae,te.height=O.height-ae;break;case"s":te.height=O.height+ae;break;case"w":te.x=O.x+Y,te.width=O.width-Y;break;case"e":te.width=O.width+Y;break}te=E(te)}R(te),d==null||d(te)},F=()=>{if(C(null),T(null),k.current){try{k.current.target.releasePointerCapture(k.current.pointerId)}catch{}k.current=null}};return document.addEventListener("pointermove",I),document.addEventListener("pointerup",F),()=>{document.removeEventListener("pointermove",I),document.removeEventListener("pointerup",F)}},[_,L,O,S,E,d]);const N=(I,F,U)=>{I.preventDefault(),I.stopPropagation();const ee=I.currentTarget;try{ee.setPointerCapture(I.pointerId),k.current={target:ee,pointerId:I.pointerId}}catch{}C(F),T(U||null),V({x:I.clientX,y:I.clientY}),$({...M})},W=I=>{const F=I.shiftKey?.05:.01;let U={...M};if(I.shiftKey&&!I.altKey)switch(I.key){case"ArrowLeft":U.width-=F;break;case"ArrowRight":U.width+=F;break;case"ArrowUp":U.height-=F;break;case"ArrowDown":U.height+=F;break;default:return}else switch(I.key){case"ArrowLeft":U.x-=F;break;case"ArrowRight":U.x+=F;break;case"ArrowUp":U.y-=F;break;case"ArrowDown":U.y+=F;break;case"Enter":q();return;default:return}I.preventDefault(),U=E(U),R(U),d==null||d(U)},q=()=>{const I=x.current;if(!I||!l)return;const F=document.createElement("canvas"),U=M.x*I.naturalWidth,ee=M.y*I.naturalHeight,X=M.width*I.naturalWidth,Y=M.height*I.naturalHeight;F.width=X,F.height=Y;const ae=F.getContext("2d");if(!ae)return;u&&(ae.beginPath(),ae.arc(X/2,Y/2,Math.min(X,Y)/2,0,Math.PI*2),ae.closePath(),ae.clip()),ae.drawImage(I,U,ee,X,Y,0,0,X,Y);const te=F.toDataURL(a,i);F.toBlob(ie=>{ie?l(ie,te):c==null||c(new Error(z.imageCropper_cropFailed))},a,i)},G=()=>{const F=E(s||{x:.15,y:.15,width:.7,height:.7});R(F),d==null||d(F)},Z=[{handle:"nw",pos:"top-0 left-0 -translate-x-1/2 -translate-y-1/2",cursor:"cursor-[nw-resize]"},{handle:"ne",pos:"top-0 right-0 translate-x-1/2 -translate-y-1/2",cursor:"cursor-[ne-resize]"},{handle:"sw",pos:"bottom-0 left-0 -translate-x-1/2 translate-y-1/2",cursor:"cursor-[sw-resize]"},{handle:"se",pos:"bottom-0 right-0 translate-x-1/2 translate-y-1/2",cursor:"cursor-[se-resize]"},{handle:"n",pos:"top-0 left-1/2 -translate-x-1/2 -translate-y-1/2",cursor:"cursor-[n-resize]"},{handle:"s",pos:"bottom-0 left-1/2 -translate-x-1/2 translate-y-1/2",cursor:"cursor-[s-resize]"},{handle:"w",pos:"top-1/2 left-0 -translate-x-1/2 -translate-y-1/2",cursor:"cursor-[w-resize]"},{handle:"e",pos:"top-1/2 right-0 translate-x-1/2 -translate-y-1/2",cursor:"cursor-[e-resize]"}];return n.jsxs("div",{ref:g,className:v("space-y-3",m),children:[n.jsxs("div",{ref:h,className:"relative overflow-hidden rounded-lg select-none",role:"application","aria-label":z.imageCropper_label,tabIndex:0,onKeyDown:W,children:[n.jsx("img",{ref:x,src:e,alt:"",className:"block w-full",onLoad:A,crossOrigin:"anonymous",draggable:!1}),y&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"absolute inset-0 bg-black/50 pointer-events-none"}),n.jsxs("div",{className:v("absolute border-2 border-white shadow-lg cursor-move",u&&"rounded-full"),style:{left:`${M.x*100}%`,top:`${M.y*100}%`,width:`${M.width*100}%`,height:`${M.height*100}%`},onPointerDown:I=>N(I,"move"),children:[n.jsx("div",{className:v("absolute inset-0 overflow-hidden",u&&"rounded-full"),children:n.jsx("img",{src:e,alt:"",className:"block",style:{position:"absolute",left:`-${M.x/M.width*100}%`,top:`-${M.y/M.height*100}%`,width:`${1/M.width*100}%`,height:`${1/M.height*100}%`},draggable:!1})}),p&&!u&&n.jsxs("div",{className:"absolute inset-0 pointer-events-none",children:[n.jsx("div",{className:"absolute left-1/3 top-0 bottom-0 w-px bg-white/40"}),n.jsx("div",{className:"absolute left-2/3 top-0 bottom-0 w-px bg-white/40"}),n.jsx("div",{className:"absolute top-1/3 left-0 right-0 h-px bg-white/40"}),n.jsx("div",{className:"absolute top-2/3 left-0 right-0 h-px bg-white/40"})]}),!u&&Z.map(({handle:I,pos:F,cursor:U})=>n.jsx("div",{className:v("absolute w-3 h-3 bg-white rounded-full border border-border shadow z-10",F,U),onPointerDown:ee=>N(ee,"resize",I)},I))]})]})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("button",{type:"button",onClick:q,className:"flex items-center gap-2 px-3 py-1.5 rounded-md bg-primary text-primary-foreground text-sm hover:bg-primary/90 transition-colors",children:[n.jsx(P.Crop,{className:"h-4 w-4"}),z.imageCropper_crop]}),n.jsxs("button",{type:"button",onClick:G,className:"flex items-center gap-2 px-3 py-1.5 rounded-md border text-sm hover:bg-accent transition-colors",children:[n.jsx(P.RotateCcw,{className:"h-4 w-4"}),z.imageCropper_reset]})]})]})});mi.displayName="ImageCropper";const fi=f.forwardRef(({beforeSrc:e,afterSrc:t,beforeAlt:r="",afterAlt:o="",initialPosition:s=50,orientation:a="horizontal",showLabels:i=!0,beforeLabel:l,afterLabel:d,handleSize:c=4,onPositionChange:p,className:u,...m},g)=>{const[h,x]=f.useState(Math.max(0,Math.min(100,s))),[y,b]=f.useState(!1),w=f.useRef(null),[j,M]=f.useState({width:0,height:0}),R=f.useRef(null),_=ce(),C=a==="horizontal",S=l??_.imageCompare_before,T=d??_.imageCompare_after;f.useEffect(()=>{const k=w.current;if(!k)return;const z=new ResizeObserver(A=>{for(const E of A){const{width:N,height:W}=E.contentRect;M({width:N,height:W})}});return z.observe(k),M({width:k.offsetWidth,height:k.offsetHeight}),()=>z.disconnect()},[]);const L=f.useCallback((k,z)=>{const A=w.current;if(!A)return;const E=A.getBoundingClientRect();let N;C?N=(k-E.left)/E.width*100:N=(z-E.top)/E.height*100,N=Math.max(0,Math.min(100,N)),x(N),p==null||p(N)},[C,p]);f.useEffect(()=>{if(!y)return;const k=E=>{E.preventDefault(),L(E.clientX,E.clientY)},z=()=>{if(R.current){const{element:E,pointerId:N}=R.current;E.releasePointerCapture(N),R.current=null}b(!1)},A=()=>{if(R.current){const{element:E,pointerId:N}=R.current;E.releasePointerCapture(N),R.current=null}b(!1)};return document.addEventListener("pointermove",k),document.addEventListener("pointerup",z),window.addEventListener("blur",A),()=>{document.removeEventListener("pointermove",k),document.removeEventListener("pointerup",z),window.removeEventListener("blur",A)}},[y,L]);const V=k=>{k.preventDefault();const z=k.currentTarget;z.setPointerCapture(k.pointerId),R.current={element:z,pointerId:k.pointerId},b(!0)},O=k=>{const z=k.shiftKey?10:1;let A=h;if(C&&k.key==="ArrowLeft"||!C&&k.key==="ArrowUp")A=Math.max(0,h-z);else if(C&&k.key==="ArrowRight"||!C&&k.key==="ArrowDown")A=Math.min(100,h+z);else return;k.preventDefault(),x(A),p==null||p(A)},$=()=>{const k=s;x(k),p==null||p(k)};return n.jsxs("div",{ref:k=>{w.current=k,typeof g=="function"?g(k):g&&(g.current=k)},className:v("relative select-none overflow-hidden rounded-lg",u),...m,children:[n.jsx("img",{src:t,alt:o,className:"block w-full h-full object-cover",draggable:!1}),n.jsx("div",{className:"absolute inset-0 overflow-hidden",style:C?{width:`${h}%`}:{height:`${h}%`},children:n.jsx("img",{src:e,alt:r,className:v("block object-cover",C?"h-full":"w-full"),style:C?{width:`${j.width}px`,maxWidth:"none",height:"100%"}:{height:`${j.height}px`,maxHeight:"none",width:"100%"},draggable:!1})}),n.jsxs("div",{className:v("absolute z-10",C?"top-0 bottom-0 cursor-[ew-resize]":"left-0 right-0 cursor-[ns-resize]"),style:C?{left:`${h}%`,width:c,transform:"translateX(-50%)"}:{top:`${h}%`,height:c,transform:"translateY(-50%)"},onPointerDown:V,onDoubleClick:$,onKeyDown:O,role:"slider","aria-label":_.imageCompare_slider,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(h),"aria-orientation":C?"horizontal":"vertical",tabIndex:0,children:[n.jsx("div",{className:v("bg-primary shadow-lg",C?"w-0.5 h-full mx-auto":"h-0.5 w-full my-auto")}),n.jsx("div",{className:v("absolute flex items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg","left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-8"),children:n.jsx(P.GripVertical,{className:v("h-4 w-4",!C&&"rotate-90")})})]}),i&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"absolute top-3 left-3 px-2 py-1 rounded bg-card/80 dark:bg-black/60 text-card-foreground dark:text-white text-xs font-medium pointer-events-none backdrop-blur-sm",children:S}),n.jsx("span",{className:"absolute top-3 right-3 px-2 py-1 rounded bg-card/80 dark:bg-black/60 text-card-foreground dark:text-white text-xs font-medium pointer-events-none backdrop-blur-sm",children:T})]})]})});fi.displayName="ImageCompare";function Sm({className:e}){const{setTheme:t}=gr(),r=ce();return n.jsxs(ws,{children:[n.jsx(ys,{asChild:!0,children:n.jsxs(ke,{variant:"outline",size:"icon",className:e,children:[n.jsx(P.Sun,{className:"h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),n.jsx(P.Moon,{className:"absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),n.jsx("span",{className:"sr-only",children:r.modeToggle_toggleTheme})]})}),n.jsxs(xn,{align:"end",children:[n.jsxs(Ft,{onClick:()=>t("light"),children:[n.jsx(P.Sun,{className:"mr-2 h-4 w-4"}),r.modeToggle_light]}),n.jsxs(Ft,{onClick:()=>t("dark"),children:[n.jsx(P.Moon,{className:"mr-2 h-4 w-4"}),r.modeToggle_dark]}),n.jsxs(Ft,{onClick:()=>t("system"),children:[n.jsx(P.Monitor,{className:"mr-2 h-4 w-4"}),r.modeToggle_system]})]})]})}const Rm=[{value:"light",icon:P.Sun,key:"modeToggle_light"},{value:"dark",icon:P.Moon,key:"modeToggle_dark"},{value:"system",icon:P.Monitor,key:"modeToggle_system"}];function _m({className:e}){const{theme:t,setTheme:r,themes:o}=gr(),s=ce();return n.jsx("div",{className:v("inline-flex items-center rounded-lg border border-border bg-muted/50 p-0.5 gap-0.5",e),role:"radiogroup","aria-label":s.modeToggle_colorTheme,children:Rm.filter(a=>o.includes(a.value)).map(({value:a,icon:i,key:l})=>{const d=s[l];return n.jsxs("button",{role:"radio","aria-checked":t===a,"aria-label":d,onClick:()=>r(a),className:v("inline-flex items-center justify-center rounded-md px-2.5 py-1.5 text-sm font-medium transition-all","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t===a?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground hover:bg-background/50"),children:[n.jsx(i,{className:"h-4 w-4"}),n.jsx("span",{className:"sr-only",children:d})]},a)})})}const gi=f.forwardRef(({className:e,variant:t="received",children:r,...o},s)=>n.jsx("div",{ref:s,className:v("group flex gap-2 max-w-[85%]",t==="sent"?"ml-auto flex-row-reverse":"mr-auto",e),"data-variant":t,...o,children:r}));gi.displayName="ChatBubble";const pi=f.forwardRef(({className:e,src:t,fallback:r,...o},s)=>n.jsx("div",{ref:s,className:v("flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-muted text-xs font-medium text-muted-foreground overflow-hidden",e),...o,children:t?n.jsx("img",{src:t,alt:r??"avatar",className:"h-full w-full object-cover"}):n.jsx("span",{children:r??"?"})}));pi.displayName="ChatBubbleAvatar";const Mm={sending:n.jsxs("svg",{className:"h-3 w-3 text-muted-foreground",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("path",{d:"M12 6v6l4 2"})]}),sent:n.jsx("svg",{className:"h-3 w-3 text-muted-foreground",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M20 6 9 17l-5-5"})}),delivered:n.jsxs("svg",{className:"h-3 w-3 text-muted-foreground",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6 7 17l-5-5"}),n.jsx("path",{d:"m22 10-9.5 9.5-2-2"})]}),read:n.jsxs("svg",{className:"h-3 w-3 text-primary",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6 7 17l-5-5"}),n.jsx("path",{d:"m22 10-9.5 9.5-2-2"})]}),error:n.jsxs("svg",{className:"h-3 w-3 text-destructive",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("path",{d:"m15 9-6 6"}),n.jsx("path",{d:"m9 9 6 6"})]})},hi=f.forwardRef(({className:e,variant:t="received",isLoading:r,status:o,children:s,...a},i)=>n.jsx("div",{ref:i,className:v("rounded-2xl px-4 py-2.5 text-sm leading-relaxed",t==="sent"?"bg-primary text-primary-foreground rounded-br-md":"bg-muted text-foreground rounded-bl-md",e),...a,children:r?n.jsxs("div",{className:"flex items-center gap-1 py-1",children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-current animate-bounce [animation-delay:0ms]"}),n.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-current animate-bounce [animation-delay:150ms]"}),n.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-current animate-bounce [animation-delay:300ms]"})]}):n.jsxs(n.Fragment,{children:[s,o&&n.jsx("div",{className:"flex justify-end mt-1",children:Mm[o]})]})}));hi.displayName="ChatBubbleMessage";const xi=f.forwardRef(({className:e,...t},r)=>n.jsx("span",{ref:r,className:v("text-[10px] text-muted-foreground mt-1 px-1",e),...t}));xi.displayName="ChatBubbleTimestamp";const vi=f.forwardRef(({visibility:e="hover",className:t,children:r,...o},s)=>n.jsx("div",{ref:s,className:v("flex items-center gap-0.5 mt-0.5",e==="hover"&&"opacity-0 group-hover:opacity-100 transition-opacity",t),...o,children:r}));vi.displayName="ChatBubbleActions";const bi=f.forwardRef(({onSend:e,placeholder:t,disabled:r,isLoading:o,showAttach:s,onAttach:a,acceptFiles:i="*",onStop:l,value:d,onChange:c,headerSlot:p,footerSlot:u,maxLength:m,className:g},h)=>{const x=ce(),y=f.useRef(null),b=f.useRef(null),[w,j]=f.useState(""),M=d!==void 0,R=M?d:w,_=k=>{M?c==null||c(k):j(k)},C=()=>{const k=y.current;k&&(k.style.height="auto",k.style.height=Math.min(k.scrollHeight,160)+"px")},S=()=>{const k=R.trim();!k||r||o||(e==null||e(k),_(""),y.current&&(y.current.style.height="auto"))},T=k=>{k.key==="Enter"&&!k.shiftKey&&(k.preventDefault(),S())},L=()=>{var k;(k=b.current)==null||k.click()},V=k=>{k.target.files&&k.target.files.length>0&&(a==null||a(k.target.files)),k.target.value=""},O=R.length,$=m?O>m:!1;return n.jsxs("div",{ref:h,className:v("rounded-xl border border-border bg-background",g),children:[p&&n.jsx("div",{className:"px-3 pt-2 pb-1 border-b border-border/40",children:p}),n.jsxs("div",{className:"flex items-end gap-2 p-2",children:[s&&n.jsxs(n.Fragment,{children:[n.jsx("button",{type:"button",onClick:L,className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors","aria-label":x.chatInput_attachFile,disabled:r,children:n.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"})})}),n.jsx("input",{ref:b,type:"file",multiple:!0,accept:i,onChange:V,className:"hidden","aria-hidden":"true"})]}),n.jsx("textarea",{ref:y,value:R,onChange:k=>{_(k.target.value),C()},onKeyDown:T,placeholder:t??x.chatInput_placeholder,disabled:r||o,rows:1,className:"flex-1 resize-none bg-transparent text-sm outline-none placeholder:text-muted-foreground min-h-[36px] py-2 px-2 max-h-40"}),o&&l?n.jsx("button",{type:"button",onClick:l,className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-destructive/10 text-destructive hover:bg-destructive/20 transition-colors","aria-label":x.chatInput_stopGenerating,children:n.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:n.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"})})}):n.jsx("button",{type:"button",onClick:S,disabled:r||o||!R.trim()||$,className:v("flex h-9 w-9 shrink-0 items-center justify-center rounded-lg transition-colors",R.trim()&&!r&&!o&&!$?"bg-primary text-primary-foreground hover:bg-primary/90":"bg-muted text-muted-foreground cursor-not-allowed"),"aria-label":x.chatInput_sendMessage,children:o?n.jsx("svg",{className:"animate-spin",xmlns:"http://www.w3.org/2000/svg",width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:n.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}):n.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"m5 12 7-7 7 7"}),n.jsx("path",{d:"M12 19V5"})]})})]}),(u||m)&&n.jsxs("div",{className:"px-3 pb-2 pt-0.5 flex items-center gap-2",children:[n.jsx("div",{className:"flex-1",children:u}),m&&n.jsxs("span",{className:v("text-[10px] tabular-nums shrink-0",$?"text-destructive font-medium":"text-muted-foreground"),children:[O,"/",m]})]})]})});bi.displayName="ChatInput";const wi=f.forwardRef(({className:e,children:t,...r},o)=>n.jsx("div",{ref:o,className:v("flex flex-col h-full",e),...r,children:t}));wi.displayName="ChatContainer";const yi=f.forwardRef(({className:e,children:t,autoScroll:r=!0,...o},s)=>{const a=f.useRef(null),i=f.Children.count(t);return f.useEffect(()=>{r&&a.current&&a.current.scrollIntoView({behavior:"smooth"})},[i,r]),n.jsx(fr,{className:"flex-1",orientation:"vertical",children:n.jsxs("div",{ref:s,className:v("flex flex-col gap-4 p-4",e),...o,children:[t,n.jsx("div",{ref:a})]})})});yi.displayName="ChatList";const ji=f.forwardRef(({className:e,variant:t="dots",text:r,...o},s)=>{const a=ce(),i=r??a.aiLoading_thinking;return t==="text"?n.jsxs("div",{ref:s,className:v("flex items-center gap-1.5 text-sm text-muted-foreground",e),...o,children:[n.jsx("svg",{className:"animate-spin h-4 w-4",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:n.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),n.jsxs("span",{className:"animate-pulse",children:[i,"…"]})]}):n.jsxs("div",{ref:s,className:v("flex items-center gap-1",e),...o,children:[n.jsx("span",{className:"h-2 w-2 rounded-full bg-muted-foreground/60 animate-bounce [animation-delay:0ms]"}),n.jsx("span",{className:"h-2 w-2 rounded-full bg-muted-foreground/60 animate-bounce [animation-delay:150ms]"}),n.jsx("span",{className:"h-2 w-2 rounded-full bg-muted-foreground/60 animate-bounce [animation-delay:300ms]"})]})});ji.displayName="AILoading";function ht(e){const t=[],r=/(`[^`]+`)|(\~\~[^~]+\~\~)|(\*\*[^*]+\*\*)|(\*[^*]+\*)|(!\[[^\]]*\]\([^)]+\))|(\[[^\]]+\]\([^)]+\))/g;let o=0,s;for(;(s=r.exec(e))!==null;){s.index>o&&t.push(e.slice(o,s.index));const a=s[0];if(a.startsWith("`"))t.push(n.jsx("code",{className:"px-1 py-0.5 rounded bg-muted text-sm font-mono",children:a.slice(1,-1)},s.index));else if(a.startsWith("~~"))t.push(n.jsx("del",{className:"text-muted-foreground",children:a.slice(2,-2)},s.index));else if(a.startsWith("**"))t.push(n.jsx("strong",{children:a.slice(2,-2)},s.index));else if(a.startsWith("*"))t.push(n.jsx("em",{children:a.slice(1,-1)},s.index));else if(a.startsWith("![")){const i=a.indexOf("]"),l=a.slice(2,i),d=a.slice(i+2,-1);t.push(n.jsx("img",{src:d,alt:l,className:"max-w-full rounded-lg my-2 inline-block",loading:"lazy"},s.index))}else if(a.startsWith("[")){const i=a.indexOf("]"),l=a.slice(1,i),d=a.slice(i+2,-1);t.push(n.jsx("a",{href:d,target:"_blank",rel:"noopener noreferrer",className:"text-primary underline underline-offset-2 hover:text-primary/80",children:l},s.index))}o=s.index+a.length}return o<e.length&&t.push(e.slice(o)),t}function Pm(e){const t=e.split(`
36
- `),r=[];let o=0,s=0;for(;o<t.length;){const a=t[o];if(a.trimStart().startsWith("```")){const l=a.trimStart().slice(3).trim(),d=[];for(o++;o<t.length&&!t[o].trimStart().startsWith("```");)d.push(t[o]),o++;o++,r.push(n.jsx("pre",{className:"overflow-x-auto rounded-lg p-4 text-[13px] leading-relaxed font-mono my-3",style:{background:"var(--cb-bg, #1e1e2e)",color:"var(--cb-plain, #d4d4d4)"},children:n.jsx("code",{"data-language":l||void 0,children:d.join(`
37
- `)})},s++));continue}const i=a.match(/^(#{1,6})\s+(.*)/);if(i){const l=i[1].length,d=i[2],c=`h${l}`,p={1:"text-2xl font-bold mt-6 mb-3",2:"text-xl font-semibold mt-5 mb-2",3:"text-lg font-semibold mt-4 mb-2",4:"text-base font-semibold mt-3 mb-1",5:"text-sm font-semibold mt-2 mb-1",6:"text-sm font-medium mt-2 mb-1"};r.push(n.jsx(c,{className:p[l],children:ht(d)},s++)),o++;continue}if(/^[\s]*[-*]\s/.test(a)){const l=[];for(;o<t.length&&/^[\s]*[-*]\s/.test(t[o]);)l.push(n.jsx("li",{children:ht(t[o].replace(/^[\s]*[-*]\s/,""))},s++)),o++;r.push(n.jsx("ul",{className:"list-disc pl-5 space-y-1 my-2 text-sm",children:l},s++));continue}if(/^\s*\d+\.\s/.test(a)){const l=[];for(;o<t.length&&/^\s*\d+\.\s/.test(t[o]);)l.push(n.jsx("li",{children:ht(t[o].replace(/^\s*\d+\.\s/,""))},s++)),o++;r.push(n.jsx("ol",{className:"list-decimal pl-5 space-y-1 my-2 text-sm",children:l},s++));continue}if(a.startsWith(">")){const l=[];for(;o<t.length&&t[o].startsWith(">");)l.push(t[o].replace(/^>\s?/,"")),o++;r.push(n.jsx("blockquote",{className:"border-l-4 border-primary/40 pl-4 italic text-muted-foreground my-3 text-sm",children:ht(l.join(" "))},s++));continue}if(a.includes("|")&&o+1<t.length&&/^\s*\|?[\s\-:|]+\|/.test(t[o+1])){const l=[];for(;o<t.length&&t[o].includes("|");)l.push(t[o]),o++;if(l.length>=2){const d=u=>u.split("|").map(m=>m.trim()).filter((m,g,h)=>g>0&&g<h.length),c=d(l[0]),p=l.slice(2).map(d);r.push(n.jsx("div",{className:"overflow-x-auto my-3",children:n.jsxs("table",{className:"w-full text-sm border-collapse",children:[n.jsx("thead",{children:n.jsx("tr",{className:"border-b border-border",children:c.map((u,m)=>n.jsx("th",{className:"px-3 py-2 text-left font-semibold text-foreground",children:ht(u)},m))})}),n.jsx("tbody",{children:p.map((u,m)=>n.jsx("tr",{className:"border-b border-border/50",children:u.map((g,h)=>n.jsx("td",{className:"px-3 py-2 text-muted-foreground",children:ht(g)},h))},m))})]})},s++));continue}}if(/^[-*_]{3,}\s*$/.test(a)){r.push(n.jsx("hr",{className:"my-4 border-border"},s++)),o++;continue}if(a.trim()===""){o++;continue}r.push(n.jsx("p",{className:"text-sm leading-relaxed my-2",children:ht(a)},s++)),o++}return r}const Ni=f.forwardRef(({content:e,streaming:t,className:r,...o},s)=>{const a=t?e:e.trim(),i=f.useMemo(()=>{try{return Pm(a)}catch{return[f.createElement("p",{className:"text-sm"},a)]}},[a]);return n.jsx("div",{ref:s,className:v("markdown-renderer",r),...o,children:i})});Ni.displayName="MarkdownRenderer";const ki=f.forwardRef(({suggestions:e,onSelect:t,columns:r=2,className:o,...s},a)=>{const i={1:"grid-cols-1",2:"grid-cols-1 sm:grid-cols-2",3:"grid-cols-1 sm:grid-cols-2 lg:grid-cols-3",4:"grid-cols-1 sm:grid-cols-2 lg:grid-cols-4"};return n.jsx("div",{ref:a,className:v("grid gap-3",i[r],o),...s,children:e.map((l,d)=>n.jsxs("button",{type:"button",onClick:()=>t==null?void 0:t(l.prompt),className:v("flex flex-col items-start gap-1 rounded-xl border border-border p-4","bg-card text-left transition-colors hover:bg-muted/60 hover:border-primary/30","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"),children:[n.jsx("span",{className:"text-sm font-medium text-foreground",children:l.title}),l.description&&n.jsx("span",{className:"text-xs text-muted-foreground line-clamp-2",children:l.description})]},d))})});ki.displayName="PromptSuggestions";const Ci=f.forwardRef(({models:e,value:t,onChange:r,placeholder:o,compact:s,className:a,...i},l)=>{const d=ce(),[c,p]=f.useState(!1),[u,m]=f.useState(""),g=f.useRef(null),h=f.useRef(null),x=e.find(w=>w.id===t),y=f.useMemo(()=>{if(!u)return e;const w=u.toLowerCase();return e.filter(j=>{var M;return j.name.toLowerCase().includes(w)||((M=j.provider)==null?void 0:M.toLowerCase().includes(w))||j.id.toLowerCase().includes(w)})},[e,u]);f.useEffect(()=>{c&&(m(""),setTimeout(()=>{var w;return(w=h.current)==null?void 0:w.focus()},0))},[c]),f.useEffect(()=>{if(!c)return;const w=j=>{g.current&&!g.current.contains(j.target)&&p(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[c]);const b=w=>{w.key==="Escape"&&p(!1)};return n.jsxs("div",{ref:g,className:v("relative",a),...i,children:[n.jsxs("button",{ref:l,type:"button",onClick:()=>p(w=>!w),className:v("flex items-center gap-2 rounded-lg border border-border bg-background px-3 py-1.5 text-sm transition-colors hover:bg-muted","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",!x&&"text-muted-foreground"),children:[x?n.jsxs(n.Fragment,{children:[x.icon&&n.jsx("span",{className:"text-base shrink-0",children:x.icon}),n.jsx("span",{className:"font-medium truncate",children:x.name}),!s&&x.provider&&n.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",x.provider,")"]})]}):n.jsx("span",{children:o??d.modelSelector_placeholder}),n.jsx("svg",{className:v("h-3.5 w-3.5 ml-auto shrink-0 text-muted-foreground transition-transform",c&&"rotate-180"),xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),c&&n.jsxs("div",{className:"absolute z-50 mt-1 w-full min-w-[260px] rounded-xl border border-border bg-popover shadow-lg animate-in fade-in-0 zoom-in-95",onKeyDown:b,children:[n.jsx("div",{className:"p-2 border-b border-border",children:n.jsx("input",{ref:h,value:u,onChange:w=>m(w.target.value),placeholder:d.modelSelector_searchPlaceholder,className:"w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground px-2 py-1"})}),n.jsxs("div",{className:"max-h-[280px] overflow-auto p-1",children:[y.length===0&&n.jsx("div",{className:"px-3 py-6 text-center text-sm text-muted-foreground",children:d.modelSelector_noResults}),y.map(w=>n.jsxs("button",{type:"button",disabled:w.disabled,onClick:()=>{r==null||r(w.id),p(!1)},className:v("flex w-full items-start gap-3 rounded-lg px-3 py-2.5 text-left text-sm transition-colors","hover:bg-muted focus-visible:outline-none focus-visible:bg-muted",w.id===t&&"bg-primary/10",w.disabled&&"opacity-50 cursor-not-allowed"),children:[w.icon&&n.jsx("span",{className:"text-lg shrink-0 mt-0.5",children:w.icon}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"font-medium truncate",children:w.name}),w.id===t&&n.jsx("svg",{className:"h-4 w-4 text-primary shrink-0",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M20 6 9 17l-5-5"})})]}),w.provider&&n.jsx("span",{className:"text-xs text-muted-foreground",children:w.provider}),w.description&&n.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:w.description}),w.badges&&w.badges.length>0&&n.jsx("div",{className:"flex flex-wrap gap-1 mt-1.5",children:w.badges.map(j=>n.jsx("span",{className:"inline-flex items-center rounded-full border border-border px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground",children:j},j))})]})]},w.id))]})]})]})});Ci.displayName="ModelSelector";const Si=f.forwardRef(({modes:e,value:t,onChange:r,size:o="default",className:s,...a},i)=>n.jsx("div",{ref:i,className:v("inline-flex items-center gap-1 rounded-lg bg-muted/50 p-1",s),role:"radiogroup",...a,children:e.map(l=>{const d=l.id===t;return n.jsxs("button",{type:"button",role:"radio","aria-checked":d,onClick:()=>r==null?void 0:r(l.id),title:l.description,className:v("rounded-md transition-all text-sm font-medium whitespace-nowrap","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",o==="sm"?"px-2.5 py-1 text-xs":"px-3 py-1.5",d?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[l.icon&&n.jsx("span",{className:"mr-1",children:l.icon}),l.label]},l.id)})}));Si.displayName="ChatModeSelector";const Ri=f.forwardRef(({question:e,options:t,onSelect:r,selected:o,allowFreeText:s,onFreeTextSubmit:a,columns:i=1,className:l,...d},c)=>{const p=ce(),[u,m]=f.useState(""),g=!!o,h=()=>{const x=u.trim();x&&(a==null||a(x),m(""))};return n.jsxs("div",{ref:c,className:v("rounded-2xl bg-muted text-foreground rounded-bl-md px-4 py-3 max-w-[85%]",l),...d,children:[n.jsx("p",{className:"text-sm leading-relaxed mb-3",children:e}),n.jsx("div",{className:v("grid gap-2",i===2?"grid-cols-1 sm:grid-cols-2":"grid-cols-1"),children:t.map(x=>{const y=x.id===o;return n.jsxs("button",{type:"button",disabled:g,onClick:()=>r==null?void 0:r(x.id,x.label),className:v("flex items-center gap-2 rounded-xl border px-3 py-2 text-left text-sm transition-all","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",y?"border-primary bg-primary/10 text-primary font-medium":g?"border-border/50 text-muted-foreground opacity-50 cursor-default":"border-border bg-background hover:border-primary/40 hover:bg-primary/5 cursor-pointer"),children:[y&&n.jsx("svg",{className:"h-4 w-4 shrink-0 text-primary",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M20 6 9 17l-5-5"})}),!y&&n.jsx("span",{className:v("h-4 w-4 shrink-0 rounded-full border-2",g?"border-border/50":"border-border")}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("span",{className:"block truncate",children:x.label}),x.description&&n.jsx("span",{className:"block text-xs text-muted-foreground mt-0.5 line-clamp-1",children:x.description})]})]},x.id)})}),s&&!g&&n.jsxs("div",{className:"flex gap-2 mt-2",children:[n.jsx("input",{type:"text",value:u,onChange:x=>m(x.target.value),onKeyDown:x=>{x.key==="Enter"&&h()},placeholder:p.followUp_freeTextPlaceholder,className:"flex-1 bg-background rounded-lg border border-border px-3 py-1.5 text-sm outline-none placeholder:text-muted-foreground focus:border-primary/40"}),n.jsx("button",{type:"button",onClick:h,disabled:!u.trim(),className:v("rounded-lg px-3 py-1.5 text-sm font-medium transition-colors",u.trim()?"bg-primary text-primary-foreground hover:bg-primary/90":"bg-muted text-muted-foreground cursor-not-allowed"),children:p.followUp_send})]})]})});Ri.displayName="ChatFollowUp";const _i=f.forwardRef(({id:e,question:t,options:r,onSelect:o,selectedId:s,disabled:a=!1,allowFreeText:i=!1,onFreeTextSubmit:l,columns:d=1,freeTextValue:c,className:p,...u},m)=>{const[g,h]=f.useState(""),[x,y]=f.useState(null),[b,w]=f.useState(null),j=Array.isArray(r)?r:[],M=t??"",R=s??x,_=c??b,C=a||R!=null&&R!==""||_!=null&&_!=="",S=f.useCallback((L,V)=>{C||(y(L),o==null||o(L,V))},[C,o]),T=f.useCallback(()=>{const L=(g??"").trim();!L||C||(w(L),l==null||l(L),h(""))},[g,C,l]);return n.jsxs("div",{ref:m,"data-question-id":e,className:v("rounded-xl border border-border/60 overflow-hidden","bg-card shadow-sm","animate-in fade-in-0 slide-in-from-bottom-2 duration-300",p),...u,children:[n.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-3 border-b border-border/40 bg-muted/30",children:[n.jsx("div",{className:"flex-shrink-0 flex items-center justify-center w-7 h-7 rounded-lg bg-primary/15 text-primary",children:n.jsx(P.HelpCircle,{className:"w-4 h-4"})}),n.jsx("p",{className:"text-sm font-medium text-foreground leading-snug",children:M})]}),n.jsxs("div",{className:"p-3 space-y-3",children:[j.length>0&&n.jsx("div",{className:v("grid gap-2",d===2?"grid-cols-1 sm:grid-cols-2":"grid-cols-1"),children:j.map((L,V)=>{if(!L)return null;const O=L.id||`opt-${V}`,$=L.label||O,k=R===L.id;return n.jsxs("button",{type:"button",disabled:C,onClick:()=>S(L.id,$),className:v("group relative flex items-center gap-3 w-full p-3 rounded-lg border text-left","transition-all duration-200 ease-out","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1",k?"border-primary bg-primary/8 ring-1 ring-primary/20":C?"border-border/40 text-muted-foreground/60 cursor-not-allowed":"border-border/60 bg-background hover:border-primary/40 hover:bg-accent/50 cursor-pointer active:scale-[0.98]"),children:[n.jsx("div",{className:v("flex-shrink-0 flex items-center justify-center w-5 h-5 rounded-full border-2 transition-all duration-200",k?"border-primary bg-primary scale-110":C?"border-muted-foreground/30":"border-muted-foreground/40 group-hover:border-primary/60"),children:k&&n.jsx(P.Check,{className:"w-3 h-3 text-primary-foreground animate-in zoom-in-50 duration-200"})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("span",{className:v("block text-sm font-medium leading-tight",k?"text-primary":"text-foreground"),children:$}),L.description&&n.jsx("span",{className:"block text-xs text-muted-foreground mt-0.5 line-clamp-2",children:L.description})]})]},O)})}),_&&n.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-primary/8 border border-primary/20",children:[n.jsx(P.Check,{className:"w-4 h-4 text-primary flex-shrink-0"}),n.jsx("span",{className:"text-sm font-medium text-primary truncate",children:_})]}),i&&!C&&n.jsxs("div",{className:"flex gap-2 pt-2 border-t border-border/30",children:[n.jsx("input",{type:"text",value:g,onChange:L=>h(L.target.value),onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),T())},placeholder:"Или напишите свой ответ...",className:v("flex-1 rounded-lg border border-border/60 bg-background px-3 py-2 text-sm","placeholder:text-muted-foreground/60","outline-none focus:border-primary/50 focus:ring-1 focus:ring-primary/20","transition-colors")}),n.jsx("button",{type:"button",onClick:T,disabled:!(g??"").trim(),className:v("flex-shrink-0 flex items-center justify-center w-9 h-9 rounded-lg transition-all duration-150",(g??"").trim()?"bg-primary text-primary-foreground hover:bg-primary/90 cursor-pointer active:scale-95":"bg-muted text-muted-foreground/50 cursor-not-allowed"),children:n.jsx(P.Send,{className:"w-4 h-4"})})]})]})]})});_i.displayName="ChatQuestion";const Zn={success:{Icon:P.CheckCircle2,border:"border-emerald-500/30",bg:"bg-emerald-500/5",iconBox:"bg-emerald-500/15 text-emerald-600 dark:text-emerald-400",title:"text-emerald-900 dark:text-emerald-100",btn:"bg-emerald-600 hover:bg-emerald-700 text-white"},info:{Icon:P.Info,border:"border-blue-500/30",bg:"bg-blue-500/5",iconBox:"bg-blue-500/15 text-blue-600 dark:text-blue-400",title:"text-blue-900 dark:text-blue-100",btn:"bg-blue-600 hover:bg-blue-700 text-white"},warning:{Icon:P.AlertTriangle,border:"border-amber-500/30",bg:"bg-amber-500/5",iconBox:"bg-amber-500/15 text-amber-600 dark:text-amber-400",title:"text-amber-900 dark:text-amber-100",btn:"bg-amber-600 hover:bg-amber-700 text-white"},result:{Icon:P.Sparkles,border:"border-violet-500/30",bg:"bg-gradient-to-br from-violet-500/8 to-emerald-500/5",iconBox:"bg-violet-500/15 text-violet-600 dark:text-violet-400",title:"text-violet-900 dark:text-violet-100",btn:"bg-violet-600 hover:bg-violet-700 text-white"}},Mi=f.forwardRef(({type:e="info",title:t,description:r,icon:o,action:s,dismissible:a=!1,onDismiss:i,className:l,...d},c)=>{const[p,u]=f.useState(!1),[m,g]=f.useState(!1),h=Zn[e]??Zn.info,x=o??h.Icon,y=f.useCallback(()=>{u(!0),i==null||i()},[i]),b=f.useCallback(()=>{m||!(s!=null&&s.onClick)||(g(!0),s.onClick(),setTimeout(()=>g(!1),1e3))},[s,m]);return p?null:n.jsx("div",{ref:c,className:v("rounded-xl border overflow-hidden shadow-sm","animate-in fade-in-0 slide-in-from-bottom-2 duration-300",h.border,h.bg,l),...d,children:n.jsxs("div",{className:"flex items-start gap-3 p-4",children:[n.jsx("div",{className:v("flex-shrink-0 flex items-center justify-center w-9 h-9 rounded-lg",h.iconBox),children:n.jsx(x,{className:"w-5 h-5"})}),n.jsxs("div",{className:"flex-1 min-w-0 pt-0.5",children:[t&&n.jsx("h4",{className:v("text-sm font-semibold leading-tight",h.title),children:t}),r&&n.jsx("p",{className:"text-sm text-muted-foreground mt-1 leading-relaxed",children:r})]}),s&&s.label&&n.jsxs("button",{type:"button",disabled:m,onClick:b,className:v("flex-shrink-0 inline-flex items-center gap-1.5 px-3.5 py-1.5 rounded-lg","text-sm font-medium whitespace-nowrap","transition-all duration-150","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","active:scale-95",m?"opacity-60 cursor-wait":"cursor-pointer",h.btn),children:[s.label,n.jsx(P.ArrowRight,{className:"w-3.5 h-3.5"})]}),a&&n.jsx("button",{type:"button",onClick:y,className:"flex-shrink-0 p-1 rounded-md hover:bg-foreground/10 text-muted-foreground hover:text-foreground transition-colors","aria-label":"Dismiss",children:n.jsx(P.X,{className:"w-4 h-4"})})]})})});Mi.displayName="ChatActionCard";const Jn={task:{Icon:P.CheckSquare,color:"text-blue-600 dark:text-blue-400 bg-blue-500/12"},project:{Icon:P.FolderKanban,color:"text-purple-600 dark:text-purple-400 bg-purple-500/12"},file:{Icon:P.FileText,color:"text-orange-600 dark:text-orange-400 bg-orange-500/12"},custom:{Icon:P.FileText,color:"text-primary bg-primary/12"}},Pi=f.forwardRef(({type:e="task",title:t,id:r,status:o,properties:s,icon:a,onNavigate:i,className:l,...d},c)=>{const p=Jn[e]??Jn.custom,u=a??p.Icon,m=typeof i=="function",g=s&&typeof s=="object"?s:null,h=f.useCallback(()=>{i==null||i()},[i]),x=f.useCallback(y=>{m&&(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),i==null||i())},[m,i]);return n.jsxs("div",{ref:c,role:m?"button":void 0,tabIndex:m?0:void 0,onClick:m?h:void 0,onKeyDown:m?x:void 0,className:v("rounded-xl border border-border/60 bg-card overflow-hidden shadow-sm","animate-in fade-in-0 slide-in-from-bottom-2 duration-300",m&&"cursor-pointer hover:border-primary/40 hover:shadow-md transition-all active:scale-[0.99]",l),...d,children:[n.jsxs("div",{className:"flex items-start gap-3 p-4",children:[n.jsx("div",{className:v("flex-shrink-0 flex items-center justify-center w-9 h-9 rounded-lg",p.color),children:n.jsx(u,{className:"w-5 h-5"})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("h4",{className:"text-sm font-semibold text-foreground truncate",children:t??"Untitled"}),r&&n.jsx("span",{className:"inline-flex px-1.5 py-0.5 rounded bg-muted text-[11px] font-mono text-muted-foreground leading-none",children:r})]}),o&&n.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:o})]}),m&&n.jsx(P.ExternalLink,{className:"flex-shrink-0 w-4 h-4 text-muted-foreground/50 mt-0.5"})]}),g&&Object.keys(g).length>0&&n.jsx("div",{className:"px-4 pb-4",children:n.jsx("div",{className:"rounded-lg bg-muted/40 divide-y divide-border/30",children:Object.entries(g).map(([y,b])=>n.jsxs("div",{className:"flex items-baseline justify-between gap-4 px-3 py-2 text-xs",children:[n.jsx("span",{className:"text-muted-foreground font-medium whitespace-nowrap",children:y}),n.jsx("span",{className:"text-foreground text-right break-words",children:String(b??"")})]},y))})})]})});Pi.displayName="ChatEntityPreview";const Ii=f.forwardRef(({title:e,description:t,icon:r,linkLabel:o,onNavigate:s,metadata:a,variant:i="success",className:l,...d},c)=>{const p=r??(i==="highlight"?P.Sparkles:P.CheckCircle2),u=a&&typeof a=="object"?a:null,m=typeof s=="function",g=i==="success";return n.jsx("div",{ref:c,className:v("rounded-xl border overflow-hidden shadow-sm","animate-in fade-in-0 slide-in-from-bottom-3 duration-300",g?"border-emerald-500/30 bg-gradient-to-br from-emerald-500/8 via-emerald-500/4 to-transparent":"border-violet-500/30 bg-gradient-to-br from-violet-500/8 via-violet-500/4 to-transparent",l),...d,children:n.jsxs("div",{className:"p-4 space-y-3",children:[n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx("div",{className:v("flex-shrink-0 flex items-center justify-center w-10 h-10 rounded-xl",g?"bg-emerald-500/15 text-emerald-600 dark:text-emerald-400":"bg-violet-500/15 text-violet-600 dark:text-violet-400"),children:n.jsx(p,{className:"w-5 h-5"})}),n.jsxs("div",{className:"flex-1 min-w-0 pt-0.5",children:[e&&n.jsx("h4",{className:v("text-sm font-semibold leading-tight",g?"text-emerald-900 dark:text-emerald-100":"text-violet-900 dark:text-violet-100"),children:e}),t&&n.jsx("p",{className:"text-sm text-muted-foreground mt-1 leading-relaxed",children:t})]}),m&&n.jsxs("button",{type:"button",onClick:s,className:v("flex-shrink-0 inline-flex items-center gap-1.5 px-4 py-2 rounded-lg","text-sm font-medium whitespace-nowrap","transition-all duration-150","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","active:scale-95 cursor-pointer",g?"bg-emerald-600 hover:bg-emerald-700 text-white":"bg-violet-600 hover:bg-violet-700 text-white"),children:[o??"Перейти",n.jsx(P.ArrowRight,{className:"w-4 h-4"})]})]}),u&&Object.keys(u).length>0&&n.jsx("div",{className:"rounded-lg bg-background/60 border border-border/30 divide-y divide-border/20",children:Object.entries(u).map(([h,x])=>n.jsxs("div",{className:"flex items-baseline justify-between gap-4 px-3 py-2 text-xs",children:[n.jsx("span",{className:"text-muted-foreground font-medium whitespace-nowrap",children:h}),n.jsx("span",{className:"text-foreground text-right break-words",children:String(x??"")})]},h))})]})})});Ii.displayName="ChatResultCard";const Im={copy:{path:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2 M9 2h6a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1H9a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1z"},retry:{path:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8 M3 3v5h5"},edit:{path:"M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"},like:{path:"M7 10v12 M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2h0a3.13 3.13 0 0 1 3 3.88Z"},dislike:{path:"M17 14V2 M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22h0a3.13 3.13 0 0 1-3-3.88Z"},share:{path:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8 M16 6l-4-4-4 4 M12 2v13"}},Li=f.forwardRef(({actions:e=["copy"],content:t,likeState:r,onCopy:o,onRetry:s,onEdit:a,onLike:i,onDislike:l,onShare:d,visibility:c="hover",className:p,...u},m)=>{const g=ce(),[h,x]=f.useState(!1),y={copy:g.messageActions_copy,retry:g.messageActions_retry,edit:g.messageActions_edit,like:g.messageActions_like,dislike:g.messageActions_dislike,share:g.messageActions_share},w={copy:async()=>{if(t)try{await navigator.clipboard.writeText(t),x(!0),setTimeout(()=>x(!1),2e3)}catch{}o==null||o()},retry:s,edit:a,like:i,dislike:l,share:d};return n.jsx("div",{ref:m,className:v("flex items-center gap-0.5",c==="hover"&&"opacity-0 group-hover:opacity-100 transition-opacity",p),...u,children:e.map(j=>{const M=j==="copy"&&h,C=j==="like"&&r==="liked"||j==="dislike"&&r==="disliked";return n.jsx("button",{type:"button",onClick:w[j],"aria-label":y[j],title:M?g.messageActions_copied:y[j],className:v("inline-flex items-center justify-center h-7 w-7 rounded-md transition-colors","text-muted-foreground hover:text-foreground hover:bg-muted","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",C&&"text-primary",M&&"text-green-500"),children:M?n.jsx("svg",{className:"h-3.5 w-3.5",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M20 6 9 17l-5-5"})}):n.jsx("svg",{className:"h-3.5 w-3.5",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:C?"currentColor":"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:Im[j].path})})},j)})})});Li.displayName="MessageActions";const Ti=f.forwardRef(({text:e,speed:t=2,onComplete:r,cursor:o=!0,immediate:s=!1,className:a,...i},l)=>{const[d,c]=f.useState(s?e:""),[p,u]=f.useState(s),m=f.useRef(e),g=f.useRef(),h=f.useRef(s?e.length:0);return f.useEffect(()=>{if(e!==m.current){if(m.current=e,s){c(e),u(!0),h.current=e.length;return}e.startsWith(d)||(h.current=0,c("")),u(!1)}},[e,s,d]),f.useEffect(()=>{if(s||p)return;const x=()=>{const y=Math.min(h.current+t,e.length);h.current=y,c(e.slice(0,y)),y>=e.length?(u(!0),r==null||r()):g.current=requestAnimationFrame(x)};return g.current=requestAnimationFrame(x),()=>{g.current&&cancelAnimationFrame(g.current)}},[e,t,s,p,r]),n.jsxs("span",{ref:l,className:v("whitespace-pre-wrap",a),...i,children:[d,o&&!p&&n.jsx("span",{className:"inline-block w-[2px] h-[1em] bg-foreground ml-px align-text-bottom animate-pulse"})]})});Ti.displayName="StreamingText";const Ei=f.forwardRef(({content:e,isThinking:t,duration:r,defaultOpen:o=!1,title:s,className:a,...i},l)=>{const d=ce(),[c,p]=f.useState(o||t===!0),[u,m]=f.useState(r??0),g=f.useRef(Date.now());f.useEffect(()=>{t&&p(!0)},[t]),f.useEffect(()=>{if(!t)return;g.current=Date.now();const y=setInterval(()=>{m(Math.floor((Date.now()-g.current)/1e3))},1e3);return()=>clearInterval(y)},[t]);const h=t?u:r??u,x=y=>y<60?`${y}s`:`${Math.floor(y/60)}m ${y%60}s`;return n.jsxs("div",{ref:l,className:v("rounded-xl border border-border/60 overflow-hidden my-2",t&&"border-primary/30",a),...i,children:[n.jsxs("button",{type:"button",onClick:()=>p(y=>!y),className:v("flex items-center gap-2 w-full px-3 py-2 text-sm transition-colors","hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",t&&"bg-primary/5"),children:[n.jsxs("svg",{className:v("h-4 w-4 shrink-0 text-muted-foreground",t&&"text-primary animate-pulse"),xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"}),n.jsx("path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"}),n.jsx("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),n.jsx("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),n.jsx("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),n.jsx("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),n.jsx("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),n.jsx("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),n.jsx("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]}),n.jsx("span",{className:v("font-medium",t&&"text-primary animate-pulse"),children:t?d.reasoning_thinking:s??d.reasoning_title}),h>0&&n.jsx("span",{className:"text-xs text-muted-foreground",children:t?`${x(h)}...`:ze(d.reasoning_thoughtFor,{duration:x(h)})}),n.jsx("svg",{className:v("h-3.5 w-3.5 ml-auto shrink-0 text-muted-foreground transition-transform duration-200",c&&"rotate-180"),xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),c&&n.jsx("div",{className:"border-t border-border/40 px-4 py-3 bg-muted/20",children:n.jsx("div",{className:"border-l-2 border-primary/20 pl-3",children:n.jsxs("p",{className:"text-xs text-muted-foreground leading-relaxed whitespace-pre-wrap",children:[e,t&&n.jsx("span",{className:"inline-block w-[2px] h-[1em] bg-muted-foreground ml-px align-text-bottom animate-pulse"})]})})})]})});Ei.displayName="ReasoningBlock";const Di=f.forwardRef(({name:e,args:t,result:r,status:o,error:s,defaultOpen:a=!1,className:i,...l},d)=>{const c=ce(),[p,u]=f.useState(a),m={running:n.jsx("svg",{className:"h-3.5 w-3.5 animate-spin text-primary",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:n.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),success:n.jsx("svg",{className:"h-3.5 w-3.5 text-green-500",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M20 6 9 17l-5-5"})}),error:n.jsxs("svg",{className:"h-3.5 w-3.5 text-destructive",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6 6 18"}),n.jsx("path",{d:"m6 6 12 12"})]})},g={running:ze(c.toolCall_calling,{name:e}),success:e,error:ze(c.toolCall_failed,{name:e})};return n.jsxs("div",{ref:d,className:v("rounded-xl border overflow-hidden my-1",o==="error"?"border-destructive/30":"border-border/60",i),...l,children:[n.jsxs("button",{type:"button",onClick:()=>u(h=>!h),className:v("flex items-center gap-2 w-full px-3 py-2 text-sm transition-colors","hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:[n.jsx("svg",{className:"h-4 w-4 shrink-0 text-muted-foreground",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),m[o],n.jsx("span",{className:v("font-medium font-mono text-xs",o==="running"&&"text-primary",o==="error"&&"text-destructive"),children:g[o]}),n.jsx("svg",{className:v("h-3.5 w-3.5 ml-auto shrink-0 text-muted-foreground transition-transform duration-200",p&&"rotate-180"),xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),p&&n.jsxs("div",{className:"border-t border-border/40 text-xs",children:[t&&Object.keys(t).length>0&&n.jsxs("div",{className:"px-3 py-2 bg-muted/20",children:[n.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground mb-1 font-semibold",children:c.toolCall_arguments}),n.jsx("pre",{className:"overflow-x-auto font-mono text-foreground/80 whitespace-pre-wrap",children:JSON.stringify(t,null,2)})]}),r&&n.jsxs("div",{className:v("px-3 py-2",t&&"border-t border-border/30"),children:[n.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground mb-1 font-semibold",children:c.toolCall_result}),n.jsx("pre",{className:"overflow-x-auto font-mono text-foreground/80 whitespace-pre-wrap",children:r})]}),s&&n.jsxs("div",{className:v("px-3 py-2 bg-destructive/5",t&&"border-t border-border/30"),children:[n.jsx("div",{className:"text-[10px] uppercase tracking-wider text-destructive mb-1 font-semibold",children:c.toolCall_error}),n.jsx("pre",{className:"overflow-x-auto font-mono text-destructive whitespace-pre-wrap",children:s})]})]})]})});Di.displayName="ChatToolCall";function Lm(e,t){const r=new Date,o=new Date(r.getFullYear(),r.getMonth(),r.getDate()),s=new Date(o.getTime()-864e5),a=new Date(o.getTime()-7*864e5),i=[{label:t[0],items:[]},{label:t[1],items:[]},{label:t[2],items:[]},{label:t[3],items:[]}],l=[...e].sort((d,c)=>c.updatedAt.getTime()-d.updatedAt.getTime());for(const d of l){const c=d.updatedAt;c>=o?i[0].items.push(d):c>=s?i[1].items.push(d):c>=a?i[2].items.push(d):i[3].items.push(d)}return i.filter(d=>d.items.length>0)}const Ai=f.forwardRef(({conversations:e,activeId:t,onSelect:r,onNew:o,onDelete:s,onRename:a,showSearch:i=!0,className:l,...d},c)=>{const p=ce(),[u,m]=f.useState(""),[g,h]=f.useState(null),[x,y]=f.useState(""),b=f.useRef(null),w=f.useMemo(()=>{if(!u)return e;const C=u.toLowerCase();return e.filter(S=>{var T;return S.title.toLowerCase().includes(C)||((T=S.lastMessage)==null?void 0:T.toLowerCase().includes(C))})},[e,u]),j=[p.conversationList_today,p.conversationList_yesterday,p.conversationList_previous7Days,p.conversationList_older],M=f.useMemo(()=>Lm(w,j),[w,j]),R=C=>{h(C.id),y(C.title),setTimeout(()=>{var S;return(S=b.current)==null?void 0:S.focus()},0)},_=()=>{g&&x.trim()&&(a==null||a(g,x.trim())),h(null)};return n.jsxs("div",{ref:c,className:v("flex flex-col h-full",l),...d,children:[o&&n.jsx("div",{className:"p-3 border-b border-border shrink-0",children:n.jsxs("button",{type:"button",onClick:o,className:v("flex items-center justify-center gap-2 w-full rounded-lg border border-border px-3 py-2 text-sm font-medium","transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:[n.jsxs("svg",{className:"h-4 w-4",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M5 12h14"}),n.jsx("path",{d:"M12 5v14"})]}),p.conversationList_newChat]})}),i&&n.jsx("div",{className:"px-3 pt-3 pb-2 shrink-0",children:n.jsxs("div",{className:"relative",children:[n.jsxs("svg",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"11",cy:"11",r:"8"}),n.jsx("path",{d:"m21 21-4.3-4.3"})]}),n.jsx("input",{value:u,onChange:C=>m(C.target.value),placeholder:p.conversationList_searchPlaceholder,className:"w-full bg-muted/50 rounded-lg pl-8 pr-3 py-1.5 text-sm outline-none placeholder:text-muted-foreground focus:bg-muted"})]})}),n.jsxs("div",{className:"flex-1 overflow-auto px-2 py-1",children:[M.length===0&&n.jsx("div",{className:"px-3 py-8 text-center text-sm text-muted-foreground",children:u?p.conversationList_noResults:p.conversationList_empty}),M.map(C=>n.jsxs("div",{className:"mb-3",children:[n.jsx("div",{className:"px-2 py-1.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:C.label}),C.items.map(S=>{const T=S.id===t,L=S.id===g;return n.jsxs("div",{className:v("group flex items-center gap-2 rounded-lg px-2 py-2 cursor-pointer transition-colors",T?"bg-primary/10":"hover:bg-muted"),onClick:()=>!L&&(r==null?void 0:r(S.id)),children:[n.jsx("svg",{className:"h-4 w-4 shrink-0 text-muted-foreground",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z"})}),n.jsx("div",{className:"flex-1 min-w-0",children:L?n.jsx("input",{ref:b,value:x,onChange:V=>y(V.target.value),onBlur:_,onKeyDown:V=>{V.key==="Enter"&&_(),V.key==="Escape"&&h(null)},className:"w-full bg-background border border-border rounded px-1 py-0.5 text-sm outline-none",onClick:V=>V.stopPropagation()}):n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"text-sm truncate font-medium",children:S.title}),S.lastMessage&&n.jsx("div",{className:"text-xs text-muted-foreground truncate",children:S.lastMessage})]})}),!L&&n.jsxs("div",{className:"flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity shrink-0",children:[a&&n.jsx("button",{type:"button",onClick:V=>{V.stopPropagation(),R(S)},className:"h-6 w-6 flex items-center justify-center rounded text-muted-foreground hover:text-foreground hover:bg-muted","aria-label":p.conversationList_rename,children:n.jsx("svg",{className:"h-3 w-3",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"})})}),s&&n.jsx("button",{type:"button",onClick:V=>{V.stopPropagation(),s(S.id)},className:"h-6 w-6 flex items-center justify-center rounded text-muted-foreground hover:text-destructive hover:bg-destructive/10","aria-label":p.conversationList_delete,children:n.jsxs("svg",{className:"h-3 w-3",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 6h18"}),n.jsx("path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"}),n.jsx("path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"})]})})]})]},S.id)})]},C.label))]})]})});Ai.displayName="ConversationList";const Tm={online:"bg-green-500",offline:"bg-muted-foreground/40",typing:"bg-primary animate-pulse"},Fi=f.forwardRef(({title:e,model:t,modelIcon:r,status:o,onClear:s,onSettings:a,onBack:i,children:l,className:d,...c},p)=>{const u=ce(),m={online:u.chatHeader_online,offline:u.chatHeader_offline,typing:u.chatHeader_typing};return n.jsxs("div",{ref:p,className:v("flex items-center gap-3 px-4 h-14 border-b border-border shrink-0 bg-background",d),...c,children:[i&&n.jsx("button",{type:"button",onClick:i,className:"h-8 w-8 flex items-center justify-center rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors -ml-1 shrink-0","aria-label":u.chatHeader_back,children:n.jsx("svg",{className:"h-4 w-4",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m15 18-6-6 6-6"})})}),r&&n.jsx("span",{className:"text-xl shrink-0",children:r}),n.jsxs("div",{className:"flex-1 min-w-0",children:[e&&n.jsx("div",{className:"text-sm font-semibold truncate",children:e}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[t&&n.jsx("span",{className:"text-xs text-muted-foreground truncate",children:t}),o&&n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx("span",{className:v("h-1.5 w-1.5 rounded-full shrink-0",Tm[o])}),n.jsx("span",{className:"text-[10px] text-muted-foreground",children:m[o]})]})]})]}),l,n.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[s&&n.jsx("button",{type:"button",onClick:s,className:"h-8 w-8 flex items-center justify-center rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors","aria-label":u.chatHeader_clearConversation,title:u.chatHeader_clearConversation,children:n.jsxs("svg",{className:"h-4 w-4",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 6h18"}),n.jsx("path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"}),n.jsx("path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"})]})}),a&&n.jsx("button",{type:"button",onClick:a,className:"h-8 w-8 flex items-center justify-center rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors","aria-label":u.chatHeader_settings,title:u.chatHeader_settings,children:n.jsxs("svg",{className:"h-4 w-4",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),n.jsx("circle",{cx:"12",cy:"12",r:"3"})]})})]})]})});Fi.displayName="ChatHeader";const In=f.forwardRef(({citation:e,className:t,...r},o)=>{const[s,a]=f.useState(!1);return n.jsxs("span",{className:"relative inline-block",children:[n.jsx("button",{ref:o,type:"button",onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),onFocus:()=>a(!0),onBlur:()=>a(!1),onClick:()=>window.open(e.url,"_blank","noopener"),className:v("inline-flex items-center justify-center h-4 min-w-[16px] px-1 rounded text-[10px] font-medium","bg-primary/15 text-primary hover:bg-primary/25 transition-colors cursor-pointer","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","align-super",t),"aria-label":`Source ${e.index}: ${e.title}`,...r,children:e.index}),s&&n.jsxs("div",{className:"absolute z-50 bottom-full left-1/2 -translate-x-1/2 mb-2 w-64 rounded-lg border border-border bg-popover shadow-lg p-3 text-left animate-in fade-in-0 zoom-in-95",children:[n.jsxs("div",{className:"flex items-start gap-2",children:[e.favicon&&n.jsx("img",{src:e.favicon,alt:"",className:"h-4 w-4 mt-0.5 shrink-0 rounded"}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-sm font-medium text-foreground truncate",children:e.title}),n.jsx("div",{className:"text-[10px] text-muted-foreground truncate",children:e.url}),e.snippet&&n.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:e.snippet})]})]}),n.jsx("div",{className:"absolute top-full left-1/2 -translate-x-1/2 border-4 border-transparent border-t-border"})]})]})});In.displayName="CitationBadge";const Vi=f.forwardRef(({citations:e,variant:t="footer",className:r,...o},s)=>{const a=ce();return t==="inline"?n.jsx("span",{ref:s,className:v("inline",r),...o,children:e.map(i=>n.jsx(In,{citation:i},i.index))}):n.jsxs("div",{ref:s,className:v("border-t border-border/50 pt-3 mt-3 space-y-2",r),...o,children:[n.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-semibold mb-2",children:a.sourceCitation_sources}),e.map(i=>n.jsxs("a",{href:i.url,target:"_blank",rel:"noopener noreferrer",className:v("flex items-start gap-2.5 rounded-lg border border-border/60 p-2.5 transition-colors","hover:bg-muted/50 hover:border-primary/30"),children:[n.jsx("span",{className:"flex items-center justify-center h-5 w-5 rounded bg-primary/15 text-primary text-[10px] font-semibold shrink-0 mt-0.5",children:i.index}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[i.favicon&&n.jsx("img",{src:i.favicon,alt:"",className:"h-3.5 w-3.5 rounded shrink-0"}),n.jsx("span",{className:"text-sm font-medium text-foreground truncate",children:i.title})]}),n.jsx("span",{className:"text-[10px] text-muted-foreground truncate block",children:i.url}),i.snippet&&n.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:i.snippet})]})]},i.index))]})});Vi.displayName="SourceCitation";function Qn(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function eo(e){return e.startsWith("image/")}function to(e){return e.startsWith("image/")?"🖼️":e.startsWith("video/")?"🎬":e.startsWith("audio/")?"🎵":e.includes("pdf")?"📄":e.includes("zip")||e.includes("rar")||e.includes("tar")?"📦":e.includes("json")||e.includes("xml")||e.includes("csv")?"📊":e.includes("text")||e.includes("javascript")||e.includes("typescript")?"📝":"📎"}const zi=f.forwardRef(({files:e,onRemove:t,variant:r="compact",className:o,...s},a)=>{const i=ce();return e.length===0?null:r==="grid"?n.jsx("div",{ref:a,className:v("grid grid-cols-2 gap-2",o),...s,children:e.map((l,d)=>n.jsxs("div",{className:"group relative rounded-xl border border-border overflow-hidden bg-muted/30",children:[eo(l.type)&&(l.thumbnail||l.url)?n.jsx("div",{className:"aspect-square",children:n.jsx("img",{src:l.thumbnail||l.url,alt:l.name,className:"h-full w-full object-cover"})}):n.jsx("div",{className:"aspect-square flex items-center justify-center text-3xl bg-muted/50",children:to(l.type)}),n.jsxs("div",{className:"px-2 py-1.5 border-t border-border/40",children:[n.jsx("div",{className:"text-xs font-medium truncate",children:l.name}),n.jsx("div",{className:"text-[10px] text-muted-foreground",children:Qn(l.size)})]}),t&&n.jsx("button",{type:"button",onClick:()=>t(d),className:"absolute top-1.5 right-1.5 h-5 w-5 rounded-full bg-background/80 backdrop-blur flex items-center justify-center text-muted-foreground hover:text-destructive transition-colors opacity-0 group-hover:opacity-100","aria-label":ze(i.filePreview_remove,{name:l.name}),children:n.jsxs("svg",{className:"h-3 w-3",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6 6 18"}),n.jsx("path",{d:"m6 6 12 12"})]})})]},l.id??d))}):n.jsx("div",{ref:a,className:v("flex gap-2 overflow-x-auto pb-1",o),...s,children:e.map((l,d)=>n.jsxs("div",{className:"group relative flex items-center gap-2 rounded-lg border border-border bg-muted/30 px-2.5 py-1.5 shrink-0 max-w-[200px]",children:[eo(l.type)&&(l.thumbnail||l.url)?n.jsx("img",{src:l.thumbnail||l.url,alt:l.name,className:"h-8 w-8 rounded object-cover shrink-0"}):n.jsx("span",{className:"text-lg shrink-0",children:to(l.type)}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-xs font-medium truncate",children:l.name}),n.jsx("div",{className:"text-[10px] text-muted-foreground",children:Qn(l.size)})]}),t&&n.jsx("button",{type:"button",onClick:()=>t(d),className:"h-5 w-5 rounded-full flex items-center justify-center text-muted-foreground hover:text-destructive transition-colors shrink-0 opacity-0 group-hover:opacity-100","aria-label":ze(i.filePreview_remove,{name:l.name}),children:n.jsxs("svg",{className:"h-3 w-3",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6 6 18"}),n.jsx("path",{d:"m6 6 12 12"})]})})]},l.id??d))})});zi.displayName="FilePreview";const Em={sending:n.jsxs("svg",{className:"h-3 w-3 text-muted-foreground",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("path",{d:"M12 6v6l4 2"})]}),sent:n.jsx("svg",{className:"h-3 w-3 text-muted-foreground",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M20 6 9 17l-5-5"})}),delivered:n.jsxs("svg",{className:"h-3 w-3 text-muted-foreground",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6 7 17l-5-5"}),n.jsx("path",{d:"m22 10-9.5 9.5-2-2"})]}),read:n.jsxs("svg",{className:"h-3 w-3 text-primary",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6 7 17l-5-5"}),n.jsx("path",{d:"m22 10-9.5 9.5-2-2"})]}),error:n.jsxs("svg",{className:"h-3 w-3 text-destructive",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("path",{d:"m15 9-6 6"}),n.jsx("path",{d:"m9 9 6 6"})]})},$i=f.forwardRef(({variant:e="received",avatar:t,avatarFallback:r,content:o,timestamp:s,isLoading:a,status:i,actions:l,textContent:d,likeState:c,onCopy:p,onRetry:u,onEdit:m,onLike:g,onDislike:h,onShare:x,followUp:y,onFollowUpSelect:b,onFollowUpFreeText:w,reasoning:j,toolCalls:M,citations:R,className:_,...C},S)=>{const T=ce(),L=e==="sent",[V,O]=f.useState(!1),$=async()=>{if(d)try{await navigator.clipboard.writeText(d),O(!0),setTimeout(()=>O(!1),2e3)}catch{}p==null||p()};return n.jsxs("div",{ref:S,className:v("group flex gap-2 max-w-[85%]",L?"ml-auto flex-row-reverse":"mr-auto",_),...C,children:[(t||r)&&n.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-muted text-xs font-medium text-muted-foreground overflow-hidden",children:t?n.jsx("img",{src:t,alt:r??"avatar",className:"h-full w-full object-cover"}):n.jsx("span",{children:r??"?"})}),n.jsxs("div",{className:"flex flex-col gap-1 min-w-0",children:[j&&n.jsx("div",{className:v("rounded-xl border border-border/60 overflow-hidden",j.isThinking&&"border-primary/30"),children:n.jsx(Dm,{...j})}),M==null?void 0:M.map((k,z)=>n.jsx(Am,{...k},z)),n.jsxs("div",{className:v("rounded-2xl px-4 py-2.5 text-sm leading-relaxed",L?"bg-primary text-primary-foreground rounded-br-md":"bg-muted text-foreground rounded-bl-md"),children:[a?n.jsxs("div",{className:"flex items-center gap-1 py-1",children:[n.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-current animate-bounce [animation-delay:0ms]"}),n.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-current animate-bounce [animation-delay:150ms]"}),n.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-current animate-bounce [animation-delay:300ms]"})]}):o,R&&R.length>0&&n.jsxs("div",{className:"border-t border-border/30 pt-2 mt-2 space-y-1.5",children:[n.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-semibold",children:T.sourceCitation_sources}),R.map(k=>n.jsxs("a",{href:k.url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors",children:[n.jsx("span",{className:"h-4 min-w-[16px] px-0.5 rounded bg-primary/15 text-primary text-[10px] font-semibold flex items-center justify-center",children:k.index}),n.jsx("span",{className:"truncate",children:k.title})]},k.index))]})]}),y&&n.jsxs("div",{className:"rounded-2xl bg-muted text-foreground rounded-bl-md px-4 py-3",children:[n.jsx("p",{className:"text-sm leading-relaxed mb-2.5",children:y.question}),n.jsx("div",{className:"grid gap-1.5",children:y.options.map(k=>{const z=k.id===y.selected,A=!!y.selected;return n.jsxs("button",{type:"button",disabled:A,onClick:()=>b==null?void 0:b(k.id,k.label),className:v("flex items-center gap-2 rounded-xl border px-3 py-2 text-left text-sm transition-all",z?"border-primary bg-primary/10 text-primary font-medium":A?"border-border/50 text-muted-foreground opacity-50 cursor-default":"border-border bg-background hover:border-primary/40 hover:bg-primary/5 cursor-pointer"),children:[z?n.jsx("svg",{className:"h-4 w-4 shrink-0 text-primary",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M20 6 9 17l-5-5"})}):n.jsx("span",{className:v("h-4 w-4 shrink-0 rounded-full border-2",A?"border-border/50":"border-border")}),n.jsx("span",{className:"truncate",children:k.label})]},k.id)})})]}),(s||i)&&n.jsxs("div",{className:v("flex items-center gap-1 px-1",L&&"flex-row-reverse"),children:[s&&n.jsx("span",{className:"text-[10px] text-muted-foreground",children:s}),i&&Em[i]]}),l&&l.length>0&&!a&&n.jsx("div",{className:"flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:l.map(k=>{const z=k==="copy"&&V,A={copy:$,retry:u,edit:m,like:g,dislike:h,share:x},E=k==="like"&&c==="liked"||k==="dislike"&&c==="disliked",N={copy:T.messageActions_copy,retry:T.messageActions_retry,edit:T.messageActions_edit,like:T.messageActions_like,dislike:T.messageActions_dislike,share:T.messageActions_share};return n.jsx("button",{type:"button",onClick:A[k],title:z?T.messageActions_copied:N[k],className:v("h-7 w-7 rounded-md flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",E&&"text-primary",z&&"text-green-500"),children:z?n.jsx("svg",{className:"h-3.5 w-3.5",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M20 6 9 17l-5-5"})}):k==="copy"?n.jsxs("svg",{className:"h-3.5 w-3.5",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),n.jsx("path",{d:"M9 2h6a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1H9a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1z"})]}):k==="retry"?n.jsxs("svg",{className:"h-3.5 w-3.5",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),n.jsx("path",{d:"M3 3v5h5"})]}):k==="like"?n.jsx("svg",{className:"h-3.5 w-3.5",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:E?"currentColor":"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M7 10v12 M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2h0a3.13 3.13 0 0 1 3 3.88Z"})}):k==="dislike"?n.jsx("svg",{className:"h-3.5 w-3.5",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:E?"currentColor":"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M17 14V2 M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22h0a3.13 3.13 0 0 1-3-3.88Z"})}):k==="edit"?n.jsx("svg",{className:"h-3.5 w-3.5",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"})}):n.jsxs("svg",{className:"h-3.5 w-3.5",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"}),n.jsx("path",{d:"M16 6l-4-4-4 4"}),n.jsx("path",{d:"M12 2v13"})]})},k)})})]})]})});$i.displayName="ChatMessage";function Dm({content:e,isThinking:t,duration:r}){const o=ce(),[s,a]=f.useState(t===!0),[i,l]=f.useState(r??0);f.useEffect(()=>{t&&a(!0)},[t]),f.useEffect(()=>{if(!t)return;const c=Date.now(),p=setInterval(()=>l(Math.floor((Date.now()-c)/1e3)),1e3);return()=>clearInterval(p)},[t]);const d=t?i:r??i;return n.jsxs(n.Fragment,{children:[n.jsxs("button",{type:"button",onClick:()=>a(c=>!c),className:"flex items-center gap-2 w-full px-3 py-2 text-sm hover:bg-muted/50",children:[n.jsxs("svg",{className:v("h-4 w-4 shrink-0 text-muted-foreground",t&&"text-primary animate-pulse"),xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"}),n.jsx("path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"})]}),n.jsx("span",{className:v("font-medium",t&&"text-primary animate-pulse"),children:t?o.reasoning_thinking:o.reasoning_title}),d>0&&n.jsx("span",{className:"text-xs text-muted-foreground",children:t?`${d}s...`:ze(o.reasoning_thoughtFor,{duration:`${d}s`})}),n.jsx("svg",{className:v("h-3.5 w-3.5 ml-auto text-muted-foreground transition-transform",s&&"rotate-180"),xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),s&&n.jsx("div",{className:"border-t border-border/40 px-4 py-3 bg-muted/20",children:n.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed whitespace-pre-wrap border-l-2 border-primary/20 pl-3",children:e})})]})}function Am({name:e,args:t,result:r,status:o,error:s}){const a=ce(),[i,l]=f.useState(!1);return n.jsxs("div",{className:v("rounded-xl border overflow-hidden",o==="error"?"border-destructive/30":"border-border/60"),children:[n.jsxs("button",{type:"button",onClick:()=>l(d=>!d),className:"flex items-center gap-2 w-full px-3 py-2 text-sm hover:bg-muted/50",children:[n.jsx("svg",{className:"h-4 w-4 shrink-0 text-muted-foreground",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),o==="running"?n.jsx("svg",{className:"h-3.5 w-3.5 animate-spin text-primary",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:n.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}):o==="success"?n.jsx("svg",{className:"h-3.5 w-3.5 text-green-500",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M20 6 9 17l-5-5"})}):n.jsxs("svg",{className:"h-3.5 w-3.5 text-destructive",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 6 6 18"}),n.jsx("path",{d:"m6 6 12 12"})]}),n.jsx("span",{className:"font-medium font-mono text-xs",children:o==="running"?ze(a.toolCall_calling,{name:e}):e}),n.jsx("svg",{className:v("h-3.5 w-3.5 ml-auto text-muted-foreground transition-transform",i&&"rotate-180"),xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m6 9 6 6 6-6"})})]}),i&&n.jsxs("div",{className:"border-t border-border/40 text-xs",children:[t&&Object.keys(t).length>0&&n.jsxs("div",{className:"px-3 py-2 bg-muted/20",children:[n.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground mb-1 font-semibold",children:a.toolCall_arguments}),n.jsx("pre",{className:"overflow-x-auto font-mono whitespace-pre-wrap",children:JSON.stringify(t,null,2)})]}),r&&n.jsxs("div",{className:"px-3 py-2 border-t border-border/30",children:[n.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground mb-1 font-semibold",children:a.toolCall_result}),n.jsx("pre",{className:"overflow-x-auto font-mono whitespace-pre-wrap",children:r})]}),s&&n.jsxs("div",{className:"px-3 py-2 bg-destructive/5 border-t border-border/30",children:[n.jsx("div",{className:"text-[10px] uppercase tracking-wider text-destructive mb-1 font-semibold",children:a.toolCall_error}),n.jsx("pre",{className:"overflow-x-auto font-mono text-destructive whitespace-pre-wrap",children:s})]})]})]})}exports.AILoading=ji;exports.Accordion=jc;exports.AccordionContent=cs;exports.AccordionItem=is;exports.AccordionTrigger=ls;exports.Alert=Fs;exports.AlertDescription=zs;exports.AlertDialog=Dc;exports.AlertDialogAction=Ws;exports.AlertDialogCancel=Us;exports.AlertDialogContent=Bs;exports.AlertDialogDescription=qs;exports.AlertDialogFooter=Hs;exports.AlertDialogHeader=Os;exports.AlertDialogOverlay=bn;exports.AlertDialogPortal=$s;exports.AlertDialogTitle=Gs;exports.AlertDialogTrigger=Ac;exports.AlertTitle=Vs;exports.AppShell=Za;exports.AspectRatio=vc;exports.AudioPlayer=wr;exports.AudioPlaylist=ai;exports.AudioRecorder=si;exports.AudioWaveform=br;exports.Avatar=Co;exports.AvatarFallback=Ro;exports.AvatarImage=So;exports.Badge=Xr;exports.Blockquote=hm;exports.Box=Wo;exports.Breadcrumb=Ys;exports.BreadcrumbEllipsis=ra;exports.BreadcrumbItem=Js;exports.BreadcrumbLink=Qs;exports.BreadcrumbList=Zs;exports.BreadcrumbPage=ea;exports.BreadcrumbSeparator=ta;exports.Button=ke;exports.Calendar=Qr;exports.Card=en;exports.CardContent=nn;exports.CardDescription=es;exports.CardFooter=ts;exports.CardHeader=tn;exports.CardTitle=rn;exports.Carousel=Ma;exports.CarouselContent=Pa;exports.CarouselItem=Ia;exports.CarouselNext=Ta;exports.CarouselPrevious=La;exports.ChartContainer=qa;exports.ChartLegend=wm;exports.ChartTooltip=bm;exports.ChatActionCard=Mi;exports.ChatBubble=gi;exports.ChatBubbleActions=vi;exports.ChatBubbleAvatar=pi;exports.ChatBubbleMessage=hi;exports.ChatBubbleTimestamp=xi;exports.ChatContainer=wi;exports.ChatEntityPreview=Pi;exports.ChatFollowUp=Ri;exports.ChatHeader=Fi;exports.ChatInput=bi;exports.ChatList=yi;exports.ChatMessage=$i;exports.ChatModeSelector=Si;exports.ChatQuestion=_i;exports.ChatResultCard=Ii;exports.ChatToolCall=Di;exports.Checkbox=_o;exports.CitationBadge=In;exports.Code=pm;exports.CodeBlock=mm;exports.Collapsible=bc;exports.CollapsibleContent=Jo;exports.CollapsibleTrigger=wc;exports.ColorPicker=hc;exports.Combobox=dc;exports.Command=vn;exports.CommandDialog=Tc;exports.CommandEmpty=Ls;exports.CommandGroup=Ts;exports.CommandInput=Ps;exports.CommandItem=Ds;exports.CommandList=Is;exports.CommandSeparator=Es;exports.CommandShortcut=As;exports.Container=Zo;exports.ContextMenu=yd;exports.ContextMenuCheckboxItem=ba;exports.ContextMenuContent=xa;exports.ContextMenuGroup=Nd;exports.ContextMenuItem=va;exports.ContextMenuLabel=ya;exports.ContextMenuPortal=kd;exports.ContextMenuRadioGroup=Sd;exports.ContextMenuRadioItem=wa;exports.ContextMenuSeparator=ja;exports.ContextMenuShortcut=Na;exports.ContextMenuSub=Cd;exports.ContextMenuSubContent=ha;exports.ContextMenuSubTrigger=pa;exports.ContextMenuTrigger=jd;exports.ConversationList=Ai;exports.CopyInput=ti;exports.DataTable=am;exports.DataTableColumnHeader=im;exports.DatePicker=ac;exports.Dialog=ds;exports.DialogClose=kc;exports.DialogContent=dn;exports.DialogDescription=ps;exports.DialogFooter=fs;exports.DialogHeader=ms;exports.DialogOverlay=cn;exports.DialogPortal=us;exports.DialogTitle=gs;exports.DialogTrigger=Nc;exports.Drawer=hs;exports.DrawerClose=vs;exports.DrawerContent=mn;exports.DrawerDescription=hn;exports.DrawerFooter=gn;exports.DrawerHeader=fn;exports.DrawerTitle=pn;exports.DrawerTrigger=xs;exports.DropdownMenu=ws;exports.DropdownMenuCheckboxItem=ks;exports.DropdownMenuContent=xn;exports.DropdownMenuGroup=Sc;exports.DropdownMenuItem=Ft;exports.DropdownMenuLabel=Ss;exports.DropdownMenuPortal=Rc;exports.DropdownMenuRadioGroup=Mc;exports.DropdownMenuRadioItem=Cs;exports.DropdownMenuSeparator=Rs;exports.DropdownMenuShortcut=_s;exports.DropdownMenuSub=_c;exports.DropdownMenuSubContent=Ns;exports.DropdownMenuSubTrigger=js;exports.DropdownMenuTrigger=ys;exports.EmptyState=xd;exports.FilePreview=zi;exports.FileUpload=fc;exports.Flex=Uo;exports.Grid=Yo;exports.HStack=Xo;exports.Header=Qa;exports.Heading=fm;exports.HoverCard=Rd;exports.HoverCardContent=ka;exports.HoverCardTrigger=_d;exports.Image=di;exports.ImageCompare=fi;exports.ImageCropper=mi;exports.Input=mt;exports.JsonViewer=ri;exports.Label=mr;exports.Lead=xm;exports.Lightbox=ui;exports.Main=ei;exports.MarkdownRenderer=Ni;exports.MessageActions=Li;exports.MetricCard=ym;exports.ModeToggle=Sm;exports.ModeToggleGroup=_m;exports.ModelSelector=Ci;exports.MultiSelect=uc;exports.Muted=vm;exports.NUIProvider=qo;exports.NavigationMenu=ca;exports.NavigationMenuContent=fa;exports.NavigationMenuIndicator=ga;exports.NavigationMenuItem=bd;exports.NavigationMenuLink=wd;exports.NavigationMenuList=da;exports.NavigationMenuTrigger=ma;exports.NavigationMenuViewport=wn;exports.NumberInput=lc;exports.OTPInput=mc;exports.Pagination=na;exports.PaginationContent=oa;exports.PaginationEllipsis=la;exports.PaginationItem=sa;exports.PaginationLink=pr;exports.PaginationNext=ia;exports.PaginationPrevious=aa;exports.Popover=Pt;exports.PopoverContent=yt;exports.PopoverTrigger=It;exports.Progress=Ks;exports.PromptSuggestions=ki;exports.RadioGroup=Do;exports.RadioGroupItem=Ao;exports.ReasoningBlock=Ei;exports.ScrollArea=fr;exports.ScrollBar=lr;exports.Select=tc;exports.SelectContent=Io;exports.SelectGroup=rc;exports.SelectItem=To;exports.SelectLabel=Lo;exports.SelectScrollDownButton=Zr;exports.SelectScrollUpButton=Yr;exports.SelectSeparator=Eo;exports.SelectTrigger=Po;exports.SelectValue=nc;exports.Separator=ko;exports.Sheet=hs;exports.SheetClose=vs;exports.SheetContent=mn;exports.SheetDescription=hn;exports.SheetFooter=gn;exports.SheetHeader=fn;exports.SheetOverlay=un;exports.SheetPortal=bs;exports.SheetTitle=pn;exports.SheetTrigger=xs;exports.Sidebar=Ja;exports.Skeleton=Fc;exports.Slider=Fo;exports.SourceCitation=Vi;exports.StatusBadge=Nm;exports.Stepper=vd;exports.StreamingText=Ti;exports.Switch=Mo;exports.Table=on;exports.TableBody=an;exports.TableCaption=ns;exports.TableCell=ir;exports.TableFooter=rs;exports.TableHead=ln;exports.TableHeader=sn;exports.TableRow=At;exports.Tabs=yc;exports.TabsContent=as;exports.TabsList=os;exports.TabsTrigger=ss;exports.TagInput=cc;exports.Text=gm;exports.Textarea=jo;exports.ThemeProvider=pd;exports.TimePicker=ic;exports.Timeline=Wa;exports.TimelineConnector=Xa;exports.TimelineContent=Ya;exports.TimelineIcon=Ka;exports.TimelineItem=Ua;exports.Toaster=hd;exports.Toggle=Vo;exports.ToggleGroup=zo;exports.ToggleGroupItem=Bo;exports.Tooltip=Ic;exports.TooltipContent=Ms;exports.TooltipProvider=Pc;exports.TooltipTrigger=Lc;exports.TranslateProvider=qo;exports.VStack=Ko;exports.VideoGallery=ci;exports.VideoPlayer=Xt;exports.VideoRecorder=li;exports.VideoThumbnail=Pn;exports.audioPlayerVariants=ni;exports.audioPlaylistVariants=Gr;exports.audioRecorderVariants=oi;exports.badgeVariants=No;exports.buttonVariants=Ut;exports.cardVariants=Qo;exports.cn=v;exports.en=Ot;exports.formatTime=Ke;exports.headingVariants=Ha;exports.inputVariants=yo;exports.navigationMenuTriggerStyle=ua;exports.ru=Oo;exports.textVariants=Ga;exports.toast=ed;exports.toggleVariants=Jr;exports.tpl=ze;exports.useLocale=sc;exports.useNUILocale=ce;exports.useTheme=gr;exports.useTranslate=ce;exports.videoPlayerVariants=ii;
33
+ */function ja(r,e){return r?Bx(r)?E.createElement(r,e):r:null}function Bx(r){return $x(r)||typeof r=="function"||Ux(r)}function $x(r){return typeof r=="function"&&(()=>{const e=Object.getPrototypeOf(r);return e.prototype&&e.prototype.isReactComponent})()}function Ux(r){return typeof r=="object"&&typeof r.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(r.$$typeof.description)}function Gx(r){const e={state:{},onStateChange:()=>{},renderFallbackValue:null,...r},[t]=E.useState(()=>({current:_x(e)})),[s,n]=E.useState(()=>t.current.initialState);return t.current.setOptions(i=>({...i,...r,state:{...s,...r.state},onStateChange:o=>{n(o),r.onStateChange==null||r.onStateChange(o)}})),t.current}function Vx({columns:r,data:e,searchKey:t,searchPlaceholder:s,pageSize:n=10}){var x,v;const i=ye(),o=s??i.dataTable_searchPlaceholder,[a,c]=E.useState([]),[l,d]=E.useState([]),[u,h]=E.useState({}),[g,m]=E.useState({}),p=Gx({data:e,columns:r,onSortingChange:c,onColumnFiltersChange:d,getCoreRowModel:kx(),getPaginationRowModel:Ox(),getSortedRowModel:jx(),getFilteredRowModel:Fx(),onColumnVisibilityChange:h,onRowSelectionChange:m,state:{sorting:a,columnFilters:l,columnVisibility:u,rowSelection:g},initialState:{pagination:{pageSize:n}}});return f.jsxs("div",{className:"space-y-4",children:[t&&f.jsx("div",{className:"flex items-center gap-2",children:f.jsx(ws,{placeholder:o,value:((x=p.getColumn(t))==null?void 0:x.getFilterValue())??"",onChange:y=>{var b;return(b=p.getColumn(t))==null?void 0:b.setFilterValue(y.target.value)},className:"max-w-sm"})}),f.jsx("div",{className:"rounded-md border",children:f.jsxs(Eo,{children:[f.jsx(To,{children:p.getHeaderGroups().map(y=>f.jsx(xr,{children:y.headers.map(b=>f.jsx(Ro,{children:b.isPlaceholder?null:ja(b.column.columnDef.header,b.getContext())},b.id))},y.id))}),f.jsx(wo,{children:(v=p.getRowModel().rows)!=null&&v.length?p.getRowModel().rows.map(y=>f.jsx(xr,{"data-state":y.getIsSelected()&&"selected",children:y.getVisibleCells().map(b=>f.jsx(Sn,{children:ja(b.column.columnDef.cell,b.getContext())},b.id))},y.id)):f.jsx(xr,{children:f.jsx(Sn,{colSpan:r.length,className:"h-24 text-center",children:i.dataTable_noResults})})})]})}),f.jsxs("div",{className:"flex items-center justify-between px-2",children:[f.jsx("div",{className:"text-sm text-muted-foreground",children:bt(i.dataTable_pageOf,{page:p.getState().pagination.pageIndex+1,total:p.getPageCount()})}),f.jsxs("div",{className:"flex items-center space-x-2",children:[f.jsxs(Ze,{variant:"outline",size:"sm",onClick:()=>p.previousPage(),disabled:!p.getCanPreviousPage(),children:[f.jsx(W.ChevronLeft,{className:"h-4 w-4"}),i.dataTable_previous]}),f.jsxs(Ze,{variant:"outline",size:"sm",onClick:()=>p.nextPage(),disabled:!p.getCanNextPage(),children:[i.dataTable_next,f.jsx(W.ChevronRight,{className:"h-4 w-4"})]})]})]})]})}function Hx({column:r,title:e,className:t}){return r.getCanSort()?f.jsxs(Ze,{variant:"ghost",size:"sm",className:I("-ml-3 h-8",t),onClick:()=>r.toggleSorting(r.getIsSorted()==="asc"),children:[e,f.jsx(W.ArrowUpDown,{className:"ml-2 h-4 w-4"})]}):f.jsx("div",{className:I(t),children:e})}const Kx=new Set(["abstract","as","async","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","let","new","null","of","package","private","protected","public","return","set","static","super","switch","this","throw","true","try","type","typeof","undefined","var","void","while","with","yield"]),zx=new Set(["display","flex","grid","none","block","inline","relative","absolute","fixed","sticky","hidden","visible","auto","inherit","initial","unset","important","solid","dashed","dotted","transparent","center","left","right","top","bottom","normal","bold","italic","nowrap","wrap"]);function Wx(r,e){const t=r.split(`
34
+ `),s=e==="css"||e==="scss"||e==="less",n=e==="html"||e==="xml"||e==="svg",i=e==="json",o=e==="bash"||e==="sh"||e==="shell"||e==="zsh";return t.map(a=>{const c=[];let l=0;const d=a.length*4;let u=0;for(;l<a.length&&u++<d;){if(!s&&!i&&a[l]==="/"&&a[l+1]==="/"){c.push({type:"comment",value:a.slice(l)}),l=a.length;continue}if(o&&a[l]==="#"){c.push({type:"comment",value:a.slice(l)}),l=a.length;continue}if(a[l]==="/"&&a[l+1]==="*"){const h=a.indexOf("*/",l+2);h!==-1?(c.push({type:"comment",value:a.slice(l,h+2)}),l=h+2):(c.push({type:"comment",value:a.slice(l)}),l=a.length);continue}if(a[l]==="`"){let h=l+1;for(;h<a.length&&a[h]!=="`";)a[h]==="\\"&&h++,h++;c.push({type:"string",value:a.slice(l,h+1)}),l=h+1;continue}if(a[l]==='"'||a[l]==="'"){const h=a[l];let g=l+1;for(;g<a.length&&a[g]!==h;)a[g]==="\\"&&g++,g++;c.push({type:"string",value:a.slice(l,g+1)}),l=g+1;continue}if(/[0-9]/.test(a[l])&&(l===0||/[\s,\(\[:=+\-*/<>!&|^~?{]/.test(a[l-1]))){let h=l;for(;h<a.length&&/[0-9a-fA-FxXoObB._eE+\-n]/.test(a[h]);)h++;c.push({type:"number",value:a.slice(l,h)}),l=h;continue}if(a[l]==="<"&&/[a-zA-Z\/!]/.test(a[l+1]||"")||a[l]==="/"&&a[l+1]===">"){if(a[l]==="/"&&a[l+1]===">"){c.push({type:"punctuation",value:"/>"}),l+=2;continue}const h=a[l+1]==="/";let g=h?l+2:l+1;for(;g<a.length&&/[a-zA-Z0-9.\-_]/.test(a[g]);)g++;c.push({type:"punctuation",value:a[l]+(h?"/":"")});const m=a.slice(h?l+2:l+1,g);m&&c.push({type:"tag",value:m}),l=g;continue}if(a[l]===">"){c.push({type:"punctuation",value:">"}),l++;continue}if(/[a-zA-Z_$@]/.test(a[l])){let h=l;for(;h<a.length&&/[a-zA-Z0-9_$@\-]/.test(a[h]);)h++;h===l&&h++;const g=a.slice(l,h);if(s&&zx.has(g))c.push({type:"keyword",value:g});else if(n||s){const m=a.slice(h).trimStart();m[0]==="="||m[0]===":"?c.push({type:"attr",value:g}):c.push({type:"plain",value:g})}else Kx.has(g)?c.push({type:"keyword",value:g}):!i&&a[h]==="("?c.push({type:"function",value:g}):!i&&/^[A-Z]/.test(g)?c.push({type:"tag",value:g}):c.push({type:"plain",value:g});l=h;continue}if(/[=+\-*/%<>!&|^~?:]/.test(a[l])){let h=l;for(;h<a.length&&/[=+\-*/%<>!&|^~?:]/.test(a[h]);)h++;c.push({type:"operator",value:a.slice(l,h)}),l=h;continue}if(/[{}()\[\],;.]/.test(a[l])){c.push({type:"punctuation",value:a[l]}),l++;continue}if(/\s/.test(a[l])){let h=l;for(;h<a.length&&/\s/.test(a[h]);)h++;c.push({type:"plain",value:a.slice(l,h)}),l=h;continue}c.push({type:"plain",value:a[l]}),l++}return c})}const Yx={comment:"var(--cb-comment, #6a9955)",string:"var(--cb-string, #ce9178)",keyword:"var(--cb-keyword, #569cd6)",number:"var(--cb-number, #b5cea8)",function:"var(--cb-function, #dcdcaa)",tag:"var(--cb-tag, #4ec9b0)",attr:"var(--cb-attr, #9cdcfe)",punctuation:"var(--cb-punctuation, #d4d4d4)",operator:"var(--cb-operator, #d4d4d4)",plain:"var(--cb-plain, #d4d4d4)"};function qx({code:r,language:e="tsx",showLineNumbers:t=!1,showCopy:s=!0,className:n}){const i=ye(),[o,a]=E.useState(!1),c=r.trim(),l=E.useMemo(()=>{try{return Wx(c,e)}catch{return c.split(`
35
+ `).map(u=>[{type:"plain",value:u}])}},[c,e]),d=async()=>{try{await navigator.clipboard.writeText(c),a(!0),setTimeout(()=>a(!1),2e3)}catch{}};return f.jsxs("div",{className:I("relative group",n),children:[s&&f.jsx("button",{type:"button",onClick:d,className:"absolute top-3 right-3 z-10 p-1.5 rounded-md bg-white/10 backdrop-blur text-white/60 hover:text-white opacity-0 group-hover:opacity-100 transition-opacity text-xs","aria-label":i.common_copyCode,children:o?f.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("polyline",{points:"20 6 9 17 4 12"})}):f.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("rect",{width:"14",height:"14",x:"8",y:"8",rx:"2"}),f.jsx("path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"})]})}),f.jsx("pre",{className:"overflow-x-auto rounded-lg p-4 text-[13px] leading-relaxed font-mono",style:{background:"var(--cb-bg, #1e1e2e)",color:"var(--cb-plain, #d4d4d4)"},children:l.map((u,h)=>f.jsxs("div",{children:[t&&f.jsx("span",{className:"inline-block w-8 select-none text-right mr-4 opacity-40",style:{color:"var(--cb-plain, #d4d4d4)"},children:h+1}),u.map((g,m)=>f.jsx("span",{style:{color:Yx[g.type]},children:g.value},m))]},h))})]})}const Yu=ft("font-bold tracking-tight",{variants:{level:{1:"text-2xl lg:text-3xl",2:"text-xl lg:text-2xl",3:"text-lg lg:text-xl",4:"text-base lg:text-lg",5:"text-sm lg:text-base",6:"text-xs lg:text-sm"}},defaultVariants:{level:2}});function Xx({className:r,level:e=2,as:t,children:s,...n}){const i=t||`h${e}`;return f.jsx(i,{className:I(Yu({level:e}),r),...n,children:s})}const qu=ft("",{variants:{size:{xs:"text-xs",sm:"text-sm",base:"text-base",lg:"text-lg",xl:"text-xl"},weight:{normal:"font-normal",medium:"font-medium",semibold:"font-semibold",bold:"font-bold"},variant:{default:"text-foreground",muted:"text-muted-foreground",primary:"text-primary",destructive:"text-destructive",success:"text-green-600 dark:text-green-400"},leading:{tight:"leading-tight",normal:"leading-normal",relaxed:"leading-relaxed"}},defaultVariants:{size:"base",weight:"normal",variant:"default",leading:"normal"}});function Qx({className:r,size:e,weight:t,variant:s,leading:n,as:i="p",children:o,...a}){return f.jsx(i,{className:I(qu({size:e,weight:t,variant:s,leading:n}),r),...a,children:o})}function Zx({className:r,...e}){return f.jsx("code",{className:I("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm",r),...e})}function Jx({className:r,...e}){return f.jsx("blockquote",{className:I("border-l-4 border-primary pl-4 italic text-muted-foreground",r),...e})}function ev({className:r,...e}){return f.jsx("p",{className:I("text-xl text-muted-foreground",r),...e})}function tv({className:r,...e}){return f.jsx("p",{className:I("text-sm text-muted-foreground",r),...e})}const Xu=E.forwardRef(({className:r,children:e,...t},s)=>f.jsx("div",{ref:s,className:I("w-full h-full min-h-[300px]",r),...t,children:f.jsx(co.ResponsiveContainer,{width:"100%",height:"100%",children:e})}));Xu.displayName="ChartContainer";const sv=co.Tooltip,rv=co.Legend,Qu=E.forwardRef(({className:r,...e},t)=>f.jsx("div",{ref:t,className:I("flex flex-col space-y-4",r),...e}));Qu.displayName="Timeline";const Zu=E.forwardRef(({className:r,...e},t)=>f.jsx("div",{ref:t,className:I("relative flex gap-4 pb-4 last:pb-0",r),...e}));Zu.displayName="TimelineItem";const Ju=E.forwardRef(({className:r,...e},t)=>f.jsx("div",{ref:t,className:I("relative z-10 flex h-8 w-8 shrink-0 items-center justify-center rounded-full border bg-background text-primary shadow-sm",r),...e}));Ju.displayName="TimelineIcon";const ef=E.forwardRef(({className:r,...e},t)=>f.jsx("div",{ref:t,className:I("absolute left-4 top-8 -bottom-4 w-px bg-border",r),...e}));ef.displayName="TimelineConnector";const tf=E.forwardRef(({className:r,...e},t)=>f.jsx("div",{ref:t,className:I("flex-1 space-y-1 pt-1",r),...e}));tf.displayName="TimelineContent";const sf=E.forwardRef(({className:r,children:e,...t},s)=>f.jsx("div",{ref:s,className:I("grid min-h-screen w-full lg:grid-cols-[280px_1fr]",r),...t,children:e}));sf.displayName="AppShell";const rf=E.forwardRef(({className:r,children:e,...t},s)=>f.jsx("div",{ref:s,className:I("hidden border-r bg-muted/40 lg:block dark:bg-muted/10",r),...t,children:f.jsx("div",{className:"flex h-full max-h-screen flex-col gap-2",children:e})}));rf.displayName="Sidebar";const nf=E.forwardRef(({className:r,children:e,...t},s)=>f.jsx("header",{ref:s,className:I("flex h-14 items-center gap-4 border-b bg-background px-6 lg:h-[60px]",r),...t,children:e}));nf.displayName="Header";const of=E.forwardRef(({className:r,children:e,...t},s)=>f.jsx("main",{ref:s,className:I("flex flex-1 flex-col gap-4 p-4 lg:gap-6 lg:p-6",r),...t,children:e}));of.displayName="Main";function nv({title:r,value:e,description:t,trend:s,trendLabel:n,icon:i,className:o,...a}){return f.jsxs(vo,{className:I("overflow-hidden",o),...a,children:[f.jsxs(yo,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[f.jsx(bo,{className:"text-sm font-medium text-muted-foreground",children:r}),i&&f.jsx("div",{className:"text-muted-foreground",children:i})]}),f.jsxs(So,{children:[f.jsx("div",{className:"text-2xl font-bold",children:e}),(t||s!==void 0)&&f.jsxs("div",{className:"text-xs flex items-center gap-1 mt-1 text-muted-foreground",children:[s!==void 0&&f.jsxs("span",{className:I("flex items-center font-medium",s>0?"text-green-500":s<0?"text-red-500":"text-muted-foreground"),children:[s>0?f.jsx(W.TrendingUp,{className:"mr-1 h-3 w-3"}):s<0?f.jsx(W.TrendingDown,{className:"mr-1 h-3 w-3"}):f.jsx(W.Minus,{className:"mr-1 h-3 w-3"}),s>0?"+":"",s,"%"]}),n&&f.jsx("span",{children:n}),t&&!s&&f.jsx("span",{children:t})]})]})]})}const af=E.forwardRef(({className:r,label:e,value:t,...s},n)=>{const[i,o]=E.useState(!1),a=()=>{navigator.clipboard.writeText(t),o(!0),setTimeout(()=>o(!1),2e3)};return f.jsxs("div",{className:"space-y-2",children:[e&&f.jsx(On,{children:e}),f.jsxs("div",{className:"flex gap-2 relative",children:[f.jsx(ws,{ref:n,value:t,readOnly:!0,className:I("pr-10 font-mono text-sm",r),...s}),f.jsx(Ze,{size:"icon",variant:"outline",className:"shrink-0",onClick:a,children:i?f.jsx(W.Check,{className:"h-4 w-4 text-green-500"}):f.jsx(W.Copy,{className:"h-4 w-4"})})]})]})});af.displayName="CopyInput";const lf=E.forwardRef(({className:r,data:e,...t},s)=>f.jsx("pre",{ref:s,className:I("rounded-lg border bg-muted p-4 overflow-auto text-xs font-mono text-muted-foreground",r),...t,children:JSON.stringify(e,null,2)}));lf.displayName="JsonViewer";const iv=ft("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{status:{neutral:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",success:"border-transparent bg-green-500/15 text-green-700 dark:text-green-400 hover:bg-green-500/25",warning:"border-transparent bg-yellow-500/15 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/25",error:"border-transparent bg-red-500/15 text-red-700 dark:text-red-400 hover:bg-red-500/25",info:"border-transparent bg-blue-500/15 text-blue-700 dark:text-blue-400 hover:bg-blue-500/25"}},defaultVariants:{status:"neutral"}});function ov({className:r,status:e,dot:t=!0,children:s,...n}){return f.jsxs("div",{className:I(iv({status:e}),r),...n,children:[t&&f.jsx("span",{className:I("mr-1.5 h-2 w-2 rounded-full",{"bg-current":!0})}),s]})}const Hn=E.forwardRef(({src:r,data:e,stream:t,color:s,progressColor:n,progress:i=0,height:o=80,barCount:a=100,barWidth:c=3,barGap:l=1,barRadius:d=2,mirrored:u=!1,onSeek:h,className:g,...m},p)=>{const x=E.useRef(null),[v,y]=E.useState([]),[b,T]=E.useState(!1),R=E.useRef(0),_=ye(),[w,A]=E.useState({width:0,height:0}),[C,L]=E.useState(null);E.useEffect(()=>{var $;const j=($=x.current)==null?void 0:$.parentElement;if(!j)return;const D=new ResizeObserver(N=>{for(const F of N){const{width:k,height:z}=F.contentRect;A({width:k,height:z})}});return D.observe(j),()=>D.disconnect()},[]),E.useEffect(()=>{if(!r||t)return;T(!0);const j=new AudioContext;let D=!1;return fetch(r).then($=>$.arrayBuffer()).then($=>j.decodeAudioData($)).then($=>{if(D)return;const N=$.getChannelData(0),F=Math.floor(N.length/a),k=[];for(let Y=0;Y<a;Y++){let U=0;for(let K=0;K<F;K++)U+=Math.abs(N[Y*F+K]);k.push(U/F)}const z=Math.max(...k,.01);y(k.map(Y=>Y/z)),T(!1)}).catch(()=>{D||(L(_.audioWaveform_error),T(!1))}),()=>{D=!0,j.close()}},[r,a]),E.useEffect(()=>{if(e){const j=Math.max(...e,.01);y(e.map(D=>D/j))}},[e]),E.useEffect(()=>{if(!t)return;const j=new AudioContext,D=j.createMediaStreamSource(t),$=j.createAnalyser();$.fftSize=256,D.connect($);const N=new Uint8Array($.frequencyBinCount),F=()=>{$.getByteFrequencyData(N);const k=Math.floor(N.length/a),z=[];for(let Y=0;Y<a;Y++)z.push(N[Y*k]/255);y(z),R.current=requestAnimationFrame(F)};return R.current=requestAnimationFrame(F),()=>{cancelAnimationFrame(R.current),D.disconnect(),j.close()}},[t,a]),E.useEffect(()=>{const j=x.current;if(!j||v.length===0)return;const D=j.getContext("2d");if(!D)return;const $=window.devicePixelRatio||1,N=j.getBoundingClientRect();j.width=N.width*$,j.height=N.height*$,D.scale($,$),D.clearRect(0,0,N.width,N.height);const F=getComputedStyle(j),k=F.getPropertyValue("--muted-foreground").trim(),z=F.getPropertyValue("--primary").trim(),Y=s||(k?`hsl(${k})`:"#888"),U=n||(z?`hsl(${z})`:"#7c3aed"),K=c+l,G=Math.max(0,(N.width-v.length*K)/2);for(let H=0;H<v.length;H++){const q=Math.max(2,v[H]*(u?N.height/2:N.height*.9)),J=G+H*K,ee=H/v.length<=i;if(D.fillStyle=ee?U:Y,u){const te=N.height/2-q;ii(D,J,te,c,q,d),D.fill(),ii(D,J,N.height/2,c,q,d),D.fill()}else{const te=N.height-q;ii(D,J,te,c,q,d),D.fill()}}},[v,i,s,n,c,l,d,u,o,w]);const P=j=>{if(!h||!x.current)return;const D=x.current.getBoundingClientRect(),$=(j.clientX-D.left)/D.width;h(Math.max(0,Math.min(1,$)))},M=j=>{if(!h)return;const D=j.shiftKey?.1:.02;j.key==="ArrowRight"?(j.preventDefault(),h(Math.min(1,i+D))):j.key==="ArrowLeft"&&(j.preventDefault(),h(Math.max(0,i-D)))};return f.jsxs("div",{ref:p,className:I("relative w-full",g),role:"img","aria-label":_.audioWaveform_label,...m,children:[b&&!t&&f.jsx("div",{className:"absolute inset-0 flex items-center gap-[2px] justify-center",style:{height:o},children:Array.from({length:Math.min(a,30)}).map((j,D)=>f.jsx("div",{className:"bg-muted animate-pulse rounded-full",style:{width:c,height:`${20+Math.random()*60}%`,animationDelay:`${D*50}ms`}},D))}),f.jsx("canvas",{ref:x,style:{width:"100%",height:o},className:I(h&&"cursor-pointer"),onClick:P,onKeyDown:M,tabIndex:h?0:void 0,role:h?"slider":void 0,"aria-valuemin":h?0:void 0,"aria-valuemax":h?100:void 0,"aria-valuenow":h?Math.round(i*100):void 0}),C&&f.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-sm text-muted-foreground",children:C})]})});Hn.displayName="AudioWaveform";function ii(r,e,t,s,n,i){r.beginPath(),r.moveTo(e+i,t),r.lineTo(e+s-i,t),r.quadraticCurveTo(e+s,t,e+s,t+i),r.lineTo(e+s,t+n-i),r.quadraticCurveTo(e+s,t+n,e+s-i,t+n),r.lineTo(e+i,t+n),r.quadraticCurveTo(e,t+n,e,t+n-i),r.lineTo(e,t+i),r.quadraticCurveTo(e,t,e+i,t),r.closePath()}const cf=ft("flex items-center gap-3 rounded-lg text-card-foreground",{variants:{variant:{default:"border bg-card p-3 shadow-sm",ghost:"bg-transparent p-3",minimal:"bg-transparent p-1 gap-2"},size:{sm:"p-2 gap-2",default:"",lg:"p-4 gap-4"}},defaultVariants:{variant:"default",size:"default"}}),av={sm:"h-3.5 w-3.5",default:"h-4 w-4",lg:"h-5 w-5"},Kn=E.forwardRef(({src:r,title:e,artist:t,albumArt:s,showWaveform:n=!1,showVolume:i=!0,defaultVolume:o=1,autoPlay:a=!1,loop:c=!1,preload:l="metadata",variant:d,size:u="default",onPlay:h,onPause:g,onEnded:m,onTimeUpdate:p,className:x},v)=>{const y=E.useRef(null),b=E.useRef(null),T=E.useRef(!1),[R,_]=E.useState(!1),[w,A]=E.useState(0),[C,L]=E.useState(0),[P,M]=E.useState(0),[j,D]=E.useState(o),[$,N]=E.useState(!1),[F,k]=E.useState(!0),[z,Y]=E.useState(null),U=ye(),K=av[u??"default"];E.useEffect(()=>{const Z=y.current;if(!Z)return;const fe=()=>{L(Z.duration),k(!1)},Re=()=>k(!0),he=()=>k(!1),be=()=>{T.current||(A(Z.currentTime),p==null||p(Z.currentTime)),Z.buffered.length>0&&M(Z.buffered.end(Z.buffered.length-1))},Ae=()=>{_(!0),h==null||h()},Ie=()=>{_(!1),g==null||g()},Me=()=>{_(!1),m==null||m()},$e=()=>{_(!1),k(!1),Y(U.audioPlayer_error)};return Z.addEventListener("loadedmetadata",fe),Z.addEventListener("waiting",Re),Z.addEventListener("canplay",he),Z.addEventListener("timeupdate",be),Z.addEventListener("play",Ae),Z.addEventListener("pause",Ie),Z.addEventListener("ended",Me),Z.addEventListener("error",$e),()=>{Z.removeEventListener("loadedmetadata",fe),Z.removeEventListener("waiting",Re),Z.removeEventListener("canplay",he),Z.removeEventListener("timeupdate",be),Z.removeEventListener("play",Ae),Z.removeEventListener("pause",Ie),Z.removeEventListener("ended",Me),Z.removeEventListener("error",$e)}},[h,g,m,p,U.audioPlayer_error]),E.useEffect(()=>{const Z=y.current;Z&&(Z.volume=$?0:j)},[j,$]),E.useEffect(()=>{Y(null),A(0),L(0),M(0),k(!0)},[r]);const G=()=>{const Z=y.current;Z&&(R?Z.pause():Z.play())},H=E.useCallback(Z=>{const fe=y.current;!fe||!C||(fe.currentTime=Z*C,A(fe.currentTime))},[C]),q=Z=>{if(!b.current)return;const fe=b.current.getBoundingClientRect();H((Z.clientX-fe.left)/fe.width)},J=Z=>{var fe,Re;T.current=!0,(Re=(fe=Z.target).setPointerCapture)==null||Re.call(fe,Z.pointerId)};E.useEffect(()=>{const Z=b.current;if(!Z)return;const fe=he=>{if(!T.current||!b.current)return;const be=b.current.getBoundingClientRect(),Ae=Math.max(0,Math.min(1,(he.clientX-be.left)/be.width));H(Ae)},Re=()=>{T.current=!1};return Z.addEventListener("pointermove",fe),Z.addEventListener("pointerup",Re),Z.addEventListener("lostpointercapture",Re),()=>{Z.removeEventListener("pointermove",fe),Z.removeEventListener("pointerup",Re),Z.removeEventListener("lostpointercapture",Re)}},[H]);const ee=Z=>{if(!y.current||!C)return;const fe=Z.shiftKey?10:5;Z.key==="ArrowLeft"?(Z.preventDefault(),y.current.currentTime=Math.max(0,w-fe)):Z.key==="ArrowRight"&&(Z.preventDefault(),y.current.currentTime=Math.min(C,w+fe))},te=Z=>{Z.key==="ArrowUp"||Z.key==="+"?(Z.preventDefault(),D(fe=>Math.min(1,fe+.1)),N(!1)):(Z.key==="ArrowDown"||Z.key==="-")&&(Z.preventDefault(),D(fe=>Math.max(0,fe-.1)))},de=()=>N(Z=>!Z),ie=$||j===0?W.VolumeX:j<.5?W.Volume1:W.Volume2,ue=C?w/C:0,re=C?P/C:0;return f.jsxs("div",{ref:v,className:I(cf({variant:d,size:u}),x),children:[f.jsx("audio",{ref:y,src:r,autoPlay:a,loop:c,preload:l}),z&&f.jsx("div",{className:"flex-1 text-sm text-destructive",children:z}),!z&&f.jsxs(f.Fragment,{children:[s&&f.jsx("img",{src:s,alt:"",className:I("rounded object-cover shrink-0",u==="sm"?"h-8 w-8":u==="lg"?"h-14 w-14":"h-10 w-10")}),f.jsx("button",{type:"button",onClick:G,className:"shrink-0 flex items-center justify-center rounded-full bg-primary text-primary-foreground hover:bg-primary/90 active:scale-95 transition-all h-8 w-8 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","aria-label":R?U.audioPlayer_pause:U.audioPlayer_play,children:F&&R?f.jsx(W.Loader2,{className:I(K,"animate-spin")}):R?f.jsx(W.Pause,{className:K}):f.jsx(W.Play,{className:I(K,"ml-0.5")})}),f.jsxs("div",{className:"flex-1 min-w-0 space-y-1",children:[(e||t)&&f.jsxs("div",{className:"flex items-center gap-2 text-xs leading-tight",children:[e&&f.jsx("span",{className:"font-medium truncate",children:e}),t&&f.jsx("span",{className:"text-muted-foreground truncate",children:t})]}),n?f.jsx(Hn,{src:r,progress:ue,height:u==="sm"?24:u==="lg"?40:32,barCount:60,onSeek:H}):f.jsxs("div",{ref:b,className:"relative h-1.5 bg-muted rounded-full cursor-pointer group",onClick:q,onPointerDown:J,onKeyDown:ee,role:"slider","aria-label":U.audioPlayer_seek,"aria-valuemin":0,"aria-valuemax":Math.round(C),"aria-valuenow":Math.round(w),"aria-valuetext":Dt(w),tabIndex:0,children:[f.jsx("div",{className:"absolute inset-y-0 left-0 bg-muted-foreground/30 rounded-full",style:{width:`${re*100}%`}}),f.jsx("div",{className:"absolute inset-y-0 left-0 bg-primary rounded-full transition-[width] duration-75",style:{width:`${ue*100}%`}}),f.jsx("div",{className:"absolute top-1/2 -translate-y-1/2 h-3 w-3 rounded-full bg-primary shadow opacity-0 group-hover:opacity-100 transition-opacity",style:{left:`${ue*100}%`,transform:"translate(-50%, -50%)"}})]}),f.jsxs("div",{className:"flex items-center justify-between text-[10px] text-muted-foreground tabular-nums",children:[f.jsx("span",{children:Dt(w)}),f.jsx("span",{children:Dt(C)})]})]}),i&&f.jsxs("div",{className:"shrink-0 flex items-center gap-1.5 group/volume [&:focus-within>input]:opacity-100",onKeyDown:te,children:[f.jsx("button",{type:"button",onClick:de,className:"p-1 rounded hover:bg-accent active:scale-95 transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":$?U.audioPlayer_unmute:U.audioPlayer_mute,children:f.jsx(ie,{className:K})}),f.jsx("input",{type:"range",min:0,max:1,step:.01,value:$?0:j,onChange:Z=>{D(Number(Z.target.value)),N(!1)},className:"w-16 h-1 accent-primary cursor-pointer","aria-label":U.audioPlayer_volume})]})]})]})});Kn.displayName="AudioPlayer";const df=ft("space-y-3 rounded-lg border bg-card text-card-foreground shadow-sm",{variants:{size:{sm:"p-3",default:"p-4",lg:"p-5"}},defaultVariants:{size:"default"}}),uf=E.forwardRef(({mimeType:r="audio/webm",maxDuration:e,showWaveform:t=!0,size:s,onRecordingComplete:n,onRecordingStart:i,onError:o,className:a},c)=>{const[l,d]=E.useState("idle"),[u,h]=E.useState(0),[g,m]=E.useState(null),[p,x]=E.useState(null),[v,y]=E.useState(null),b=E.useRef(null),T=E.useRef([]),R=E.useRef(null),_=E.useRef(null),w=E.useRef(null),A=ye(),C=E.useCallback(()=>{R.current&&(clearInterval(R.current),R.current=null),_.current&&(_.current.getTracks().forEach(F=>F.stop()),_.current=null,x(null)),w.current&&(URL.revokeObjectURL(w.current),w.current=null)},[]);E.useEffect(()=>C,[C]);const L=()=>{R.current=setInterval(()=>{h(F=>{const k=F+1;return e&&k>=e&&j(),k})},1e3)},P=()=>{R.current&&(clearInterval(R.current),R.current=null)},M=async()=>{y(null);try{const F=await navigator.mediaDevices.getUserMedia({audio:!0});x(F),_.current=F,h(0),g&&(URL.revokeObjectURL(g),m(null),w.current=null);const k=MediaRecorder.isTypeSupported(r)?r:"",z=new MediaRecorder(F,k?{mimeType:k}:void 0);z.ondataavailable=Y=>{Y.data.size>0&&T.current.push(Y.data)},z.onstop=()=>{const Y=new Blob(T.current,{type:k||"audio/webm"}),U=URL.createObjectURL(Y);m(U),w.current=U,n==null||n(Y),F.getTracks().forEach(K=>K.stop()),x(null),_.current=null},z.onerror=()=>{y(A.audioRecorder_error),C(),d("idle")},b.current=z,T.current=[],z.start(100),d("recording"),L(),i==null||i()}catch(F){const k=F instanceof Error?F:new Error(String(F));k.name==="NotAllowedError"||k.name==="PermissionDeniedError"?y(A.audioRecorder_permissionDenied):y(A.audioRecorder_error),o==null||o(k)}},j=()=>{b.current&&b.current.state!=="inactive"&&b.current.stop(),P(),d("stopped")},D=()=>{b.current&&b.current.state==="recording"&&(b.current.pause(),P(),d("paused"))},$=()=>{b.current&&b.current.state==="paused"&&(b.current.resume(),L(),d("recording"))},N=()=>{C(),h(0),m(null),w.current=null,y(null),d("idle")};return f.jsxs("div",{ref:c,className:I(df({size:s}),a),children:[v&&f.jsxs("div",{className:"flex items-center gap-2 text-sm text-destructive",children:[f.jsx(W.AlertCircle,{className:"h-4 w-4 shrink-0"}),f.jsx("span",{children:v}),f.jsx("button",{type:"button",onClick:N,className:"ml-auto text-muted-foreground hover:text-foreground transition-colors",children:f.jsx(W.RotateCcw,{className:"h-4 w-4"})})]}),!v&&l==="stopped"&&g?f.jsxs("div",{className:"space-y-3",children:[f.jsx(Kn,{src:g,size:"sm"}),f.jsxs("button",{type:"button",onClick:N,className:"flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[f.jsx(W.RotateCcw,{className:"h-4 w-4"}),A.audioRecorder_reRecord]})]}):v?null:f.jsxs(f.Fragment,{children:[t&&p&&l==="recording"&&f.jsx(Hn,{stream:p,height:48,barCount:50,className:"rounded"}),f.jsxs("div",{className:"flex items-center justify-center gap-4",children:[l==="idle"&&f.jsxs("button",{type:"button",onClick:M,className:"flex items-center gap-2 px-4 py-2 rounded-full bg-destructive text-destructive-foreground hover:bg-destructive/90 active:scale-95 transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","aria-label":A.audioRecorder_startRecording,children:[f.jsx(W.Mic,{className:"h-4 w-4"}),f.jsx("span",{className:"text-sm",children:A.audioRecorder_startRecording})]}),(l==="recording"||l==="paused")&&f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"text-sm font-mono tabular-nums text-muted-foreground min-w-[60px] text-center","aria-live":"off",children:[l==="recording"&&f.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-destructive animate-pulse mr-2"}),Dt(u)]}),l==="recording"?f.jsx("button",{type:"button",onClick:D,className:"p-2 rounded-full hover:bg-accent active:scale-95 transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":A.audioRecorder_pauseRecording,children:f.jsx(W.Pause,{className:"h-5 w-5"})}):f.jsx("button",{type:"button",onClick:$,className:"p-2 rounded-full hover:bg-accent active:scale-95 transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":A.audioRecorder_resumeRecording,children:f.jsx(W.Play,{className:"h-5 w-5"})}),f.jsx("button",{type:"button",onClick:j,className:"p-2 rounded-full bg-destructive text-destructive-foreground hover:bg-destructive/90 active:scale-95 transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","aria-label":A.audioRecorder_stopRecording,children:f.jsx(W.Square,{className:"h-5 w-5"})})]})]}),e&&(l==="recording"||l==="paused")&&f.jsx("div",{className:"w-full bg-muted rounded-full h-1",children:f.jsx("div",{className:"bg-destructive rounded-full h-1 transition-[width] duration-1000",style:{width:`${Math.min(100,u/e*100)}%`}})})]})]})});uf.displayName="AudioRecorder";const Gi=ft("rounded-lg border bg-card text-card-foreground shadow-sm overflow-hidden",{variants:{variant:{default:"",compact:"[&_.ap-controls]:gap-2 [&_.ap-controls]:py-1"}},defaultVariants:{variant:"default"}}),ff=E.forwardRef(({tracks:r,showWaveform:e=!1,defaultRepeatMode:t="none",defaultShuffle:s=!1,autoPlay:n=!1,variant:i,onTrackChange:o,onPlayStateChange:a,className:c},l)=>{const[d,u]=E.useState(0),[h,g]=E.useState(t),[m,p]=E.useState(s),[x,v]=E.useState([]),[y,b]=E.useState(new Map),[T,R]=E.useState(null),_=E.useRef(null),w=ye();E.useEffect(()=>{if(m){const k=Array.from({length:r.length},(Y,U)=>U);for(let Y=k.length-1;Y>0;Y--){const U=Math.floor(Math.random()*(Y+1));[k[Y],k[U]]=[k[U],k[Y]]}v(k);const z=new Map;k.forEach((Y,U)=>z.set(Y,U)),b(z)}},[m,r.length]);const A=E.useCallback((k,z=1)=>{if(m){const K=(y.get(k)??-1)+z;return K>=0&&K<x.length?x[K]:h==="all"?z===1?x[0]:x[x.length-1]:null}const Y=k+z;return Y>=0&&Y<r.length?Y:h==="all"?z===1?0:r.length-1:null},[m,x,y,r.length,h]),C=k=>{u(k),o==null||o(r[k],k)},L=()=>{if(h==="one")return;const k=A(d,1);k!==null&&C(k)},P=()=>{const k=A(d,-1);k!==null&&C(k)},M=()=>{const k=A(d,1);k!==null&&C(k)},j=()=>{g(k=>k==="none"?"all":k==="all"?"one":"none")},D=h==="none"?w.audioPlaylist_repeatOff:h==="all"?w.audioPlaylist_repeatAll:w.audioPlaylist_repeatOne,$=k=>{k.key==="ArrowDown"?(k.preventDefault(),R(z=>{const Y=z===null?0:Math.min(z+1,r.length-1);return N(Y),Y})):k.key==="ArrowUp"?(k.preventDefault(),R(z=>{const Y=z===null?r.length-1:Math.max(z-1,0);return N(Y),Y})):k.key==="Enter"||k.key===" "?(k.preventDefault(),T!==null&&C(T)):k.key==="Home"?(k.preventDefault(),R(0),N(0)):k.key==="End"&&(k.preventDefault(),R(r.length-1),N(r.length-1))},N=k=>{const z=_.current;if(!z)return;const Y=z.children[k];Y==null||Y.scrollIntoView({block:"nearest"})},F=r[d];return F?f.jsxs("div",{ref:l,className:I(Gi({variant:i}),c),children:[f.jsxs("div",{className:"p-3 border-b space-y-2",children:[f.jsxs("div",{className:"ap-controls flex items-center justify-center gap-3",children:[f.jsx("button",{type:"button",onClick:()=>p(k=>!k),className:I("p-1.5 rounded hover:bg-accent active:scale-95 transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",m&&"text-primary"),"aria-label":w.audioPlaylist_shuffle,"aria-pressed":m,children:f.jsx(W.Shuffle,{className:"h-4 w-4"})}),f.jsx("button",{type:"button",onClick:P,className:"p-1.5 rounded hover:bg-accent active:scale-95 transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":w.audioPlaylist_previousTrack,children:f.jsx(W.SkipBack,{className:"h-4 w-4"})}),f.jsx("button",{type:"button",onClick:M,className:"p-1.5 rounded hover:bg-accent active:scale-95 transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":w.audioPlaylist_nextTrack,children:f.jsx(W.SkipForward,{className:"h-4 w-4"})}),f.jsx("button",{type:"button",onClick:j,className:I("p-1.5 rounded hover:bg-accent active:scale-95 transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",h!=="none"&&"text-primary"),"aria-label":D,children:h==="one"?f.jsx(W.Repeat1,{className:"h-4 w-4"}):f.jsx(W.Repeat,{className:"h-4 w-4"})})]}),f.jsx(Kn,{src:F.src,title:F.title,artist:F.artist,albumArt:F.albumArt,showWaveform:e,autoPlay:n||d>0,loop:h==="one",onEnded:L,onPlay:()=>a==null?void 0:a(!0),onPause:()=>a==null?void 0:a(!1),size:"sm",variant:"ghost",className:"border-0 shadow-none p-0"},F.id)]}),f.jsx(jn,{className:"max-h-64",children:f.jsx("div",{ref:_,role:"listbox","aria-label":w.audioPlaylist_shuffle,tabIndex:0,onKeyDown:$,onBlur:()=>R(null),className:"divide-y focus-visible:outline-none",children:r.map((k,z)=>f.jsxs("button",{type:"button",role:"option","aria-selected":z===d,onClick:()=>C(z),className:I("w-full flex items-center gap-3 px-3 py-2 text-left hover:bg-accent/50 transition-colors",z===d&&"bg-accent",T===z&&"ring-2 ring-inset ring-ring"),children:[k.albumArt?f.jsx("img",{src:k.albumArt,alt:"",className:"h-8 w-8 rounded object-cover shrink-0"}):f.jsx("div",{className:"h-8 w-8 rounded bg-muted flex items-center justify-center shrink-0",children:z===d?f.jsx(W.Volume2,{className:"h-4 w-4 text-primary"}):f.jsx(W.Music,{className:"h-4 w-4 text-muted-foreground"})}),f.jsxs("div",{className:"flex-1 min-w-0",children:[f.jsx("p",{className:I("text-sm font-medium truncate",z===d&&"text-primary"),children:k.title}),k.artist&&f.jsx("p",{className:"text-xs text-muted-foreground truncate",children:k.artist})]}),k.duration!==void 0&&f.jsx("span",{className:"text-xs text-muted-foreground tabular-nums shrink-0",children:Dt(k.duration)})]},k.id))})}),r.length>1&&f.jsx("div",{className:"px-3 py-1.5 border-t text-xs text-muted-foreground text-center",children:bt(w.audioPlaylist_trackOf,{current:String(d+1),total:String(r.length)})})]}):f.jsx("div",{ref:l,className:I(Gi({variant:i}),"p-8",c),children:f.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 text-muted-foreground",children:[f.jsx(W.Music,{className:"h-8 w-8"}),f.jsx("p",{className:"text-sm",children:w.audioPlaylist_empty})]})})});ff.displayName="AudioPlaylist";const ne=Number.isFinite||function(r){return typeof r=="number"&&isFinite(r)},lv=Number.isSafeInteger||function(r){return typeof r=="number"&&Math.abs(r)<=cv},cv=Number.MAX_SAFE_INTEGER||9007199254740991;let ce=function(r){return r.NETWORK_ERROR="networkError",r.MEDIA_ERROR="mediaError",r.KEY_SYSTEM_ERROR="keySystemError",r.MUX_ERROR="muxError",r.OTHER_ERROR="otherError",r}({}),B=function(r){return r.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",r.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",r.KEY_SYSTEM_NO_SESSION="keySystemNoSession",r.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",r.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",r.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",r.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",r.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",r.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",r.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",r.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",r.MANIFEST_LOAD_ERROR="manifestLoadError",r.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",r.MANIFEST_PARSING_ERROR="manifestParsingError",r.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",r.LEVEL_EMPTY_ERROR="levelEmptyError",r.LEVEL_LOAD_ERROR="levelLoadError",r.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",r.LEVEL_PARSING_ERROR="levelParsingError",r.LEVEL_SWITCH_ERROR="levelSwitchError",r.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",r.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",r.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",r.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",r.FRAG_LOAD_ERROR="fragLoadError",r.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",r.FRAG_DECRYPT_ERROR="fragDecryptError",r.FRAG_PARSING_ERROR="fragParsingError",r.FRAG_GAP="fragGap",r.REMUX_ALLOC_ERROR="remuxAllocError",r.KEY_LOAD_ERROR="keyLoadError",r.KEY_LOAD_TIMEOUT="keyLoadTimeOut",r.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",r.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",r.BUFFER_APPEND_ERROR="bufferAppendError",r.BUFFER_APPENDING_ERROR="bufferAppendingError",r.BUFFER_STALLED_ERROR="bufferStalledError",r.BUFFER_FULL_ERROR="bufferFullError",r.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",r.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",r.ASSET_LIST_LOAD_ERROR="assetListLoadError",r.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",r.ASSET_LIST_PARSING_ERROR="assetListParsingError",r.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",r.INTERNAL_EXCEPTION="internalException",r.INTERNAL_ABORTED="aborted",r.ATTACH_MEDIA_ERROR="attachMediaError",r.UNKNOWN="unknown",r}({}),S=function(r){return r.MEDIA_ATTACHING="hlsMediaAttaching",r.MEDIA_ATTACHED="hlsMediaAttached",r.MEDIA_DETACHING="hlsMediaDetaching",r.MEDIA_DETACHED="hlsMediaDetached",r.MEDIA_ENDED="hlsMediaEnded",r.STALL_RESOLVED="hlsStallResolved",r.BUFFER_RESET="hlsBufferReset",r.BUFFER_CODECS="hlsBufferCodecs",r.BUFFER_CREATED="hlsBufferCreated",r.BUFFER_APPENDING="hlsBufferAppending",r.BUFFER_APPENDED="hlsBufferAppended",r.BUFFER_EOS="hlsBufferEos",r.BUFFERED_TO_END="hlsBufferedToEnd",r.BUFFER_FLUSHING="hlsBufferFlushing",r.BUFFER_FLUSHED="hlsBufferFlushed",r.MANIFEST_LOADING="hlsManifestLoading",r.MANIFEST_LOADED="hlsManifestLoaded",r.MANIFEST_PARSED="hlsManifestParsed",r.LEVEL_SWITCHING="hlsLevelSwitching",r.LEVEL_SWITCHED="hlsLevelSwitched",r.LEVEL_LOADING="hlsLevelLoading",r.LEVEL_LOADED="hlsLevelLoaded",r.LEVEL_UPDATED="hlsLevelUpdated",r.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",r.LEVELS_UPDATED="hlsLevelsUpdated",r.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",r.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",r.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",r.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",r.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",r.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",r.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",r.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",r.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",r.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",r.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",r.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",r.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",r.CUES_PARSED="hlsCuesParsed",r.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",r.INIT_PTS_FOUND="hlsInitPtsFound",r.FRAG_LOADING="hlsFragLoading",r.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",r.FRAG_LOADED="hlsFragLoaded",r.FRAG_DECRYPTED="hlsFragDecrypted",r.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",r.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",r.FRAG_PARSING_METADATA="hlsFragParsingMetadata",r.FRAG_PARSED="hlsFragParsed",r.FRAG_BUFFERED="hlsFragBuffered",r.FRAG_CHANGED="hlsFragChanged",r.FPS_DROP="hlsFpsDrop",r.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",r.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",r.ERROR="hlsError",r.DESTROYING="hlsDestroying",r.KEY_LOADING="hlsKeyLoading",r.KEY_LOADED="hlsKeyLoaded",r.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",r.BACK_BUFFER_REACHED="hlsBackBufferReached",r.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",r.ASSET_LIST_LOADING="hlsAssetListLoading",r.ASSET_LIST_LOADED="hlsAssetListLoaded",r.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",r.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",r.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",r.INTERSTITIAL_STARTED="hlsInterstitialStarted",r.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",r.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",r.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",r.INTERSTITIAL_ENDED="hlsInterstitialEnded",r.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",r.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",r.EVENT_CUE_ENTER="hlsEventCueEnter",r}({});var Te={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},oe={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class Ks{constructor(e,t=0,s=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_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class dv{constructor(e,t,s,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_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Ks(e),this.fast_=new Ks(t),this.defaultTTFB_=n,this.ttfb_=new Ks(e)}update(e,t){const{slow_:s,fast_:n,ttfb_:i}=this;s.halfLife!==e&&(this.slow_=new Ks(e,s.getEstimate(),s.getTotalWeight())),n.halfLife!==t&&(this.fast_=new Ks(t,n.getEstimate(),n.getTotalWeight())),i.halfLife!==e&&(this.ttfb_=new Ks(e,i.getEstimate(),i.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const s=8*t,n=e/1e3,i=s/n;this.fast_.sample(n,i),this.slow_.sample(n,i)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,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 uv(r,e,t){return(e=hv(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function De(){return De=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(r[s]=t[s])}return r},De.apply(null,arguments)}function Ba(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(r);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(r,n).enumerable})),t.push.apply(t,s)}return t}function _e(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Ba(Object(t),!0).forEach(function(s){uv(r,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Ba(Object(t)).forEach(function(s){Object.defineProperty(r,s,Object.getOwnPropertyDescriptor(t,s))})}return r}function fv(r,e){if(typeof r!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var s=t.call(r,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function hv(r){var e=fv(r,"string");return typeof e=="symbol"?e:e+""}class Ut{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 s=`[${e}]:`;this.trace=xs,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}}const xs=function(){},gv={trace:xs,debug:xs,log:xs,warn:xs,info:xs,error:xs};function Vi(){return De({},gv)}function mv(r,e){const t=self.console[r];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${r}] >`):xs}function $a(r,e,t){return e[r]?e[r].bind(e):mv(r,t)}const Hi=Vi();function pv(r,e,t){const s=Vi();if(typeof console=="object"&&r===!0||typeof r=="object"){const n=["debug","log","info","warn","error"];n.forEach(i=>{s[i]=$a(i,r,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return Vi()}n.forEach(i=>{Hi[i]=$a(i,r)})}else De(Hi,s);return s}const ke=Hi;function Es(r=!0){return typeof self>"u"?void 0:(r||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function xv(r){return typeof self<"u"&&r===self.ManagedMediaSource}function hf(r,e){const t=Object.keys(r),s=Object.keys(e),n=t.length,i=s.length;return!n||!i||n===i&&!t.some(o=>s.indexOf(o)===-1)}function Pt(r,e=!1){if(typeof TextDecoder<"u"){const l=new TextDecoder("utf-8").decode(r);if(e){const d=l.indexOf("\0");return d!==-1?l.substring(0,d):l}return l.replace(/\0/g,"")}const t=r.length;let s,n,i,o="",a=0;for(;a<t;){if(s=r[a++],s===0&&e)return o;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(s);break;case 12:case 13:n=r[a++],o+=String.fromCharCode((s&31)<<6|n&63);break;case 14:n=r[a++],i=r[a++],o+=String.fromCharCode((s&15)<<12|(n&63)<<6|(i&63)<<0);break}}return o}function ct(r){let e="";for(let t=0;t<r.length;t++){let s=r[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function gf(r){return Uint8Array.from(r.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function vv(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var oi={exports:{}},Ua;function yv(){return Ua||(Ua=1,function(r,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,n=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,o=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(c,l,d){if(d=d||{},c=c.trim(),l=l.trim(),!l){if(!d.alwaysNormalize)return c;var u=a.parseURL(c);if(!u)throw new Error("Error trying to parse base URL.");return u.path=a.normalizePath(u.path),a.buildURLFromParts(u)}var h=a.parseURL(l);if(!h)throw new Error("Error trying to parse relative URL.");if(h.scheme)return d.alwaysNormalize?(h.path=a.normalizePath(h.path),a.buildURLFromParts(h)):l;var g=a.parseURL(c);if(!g)throw new Error("Error trying to parse base URL.");if(!g.netLoc&&g.path&&g.path[0]!=="/"){var m=n.exec(g.path);g.netLoc=m[1],g.path=m[2]}g.netLoc&&!g.path&&(g.path="/");var p={scheme:g.scheme,netLoc:h.netLoc,path:null,params:h.params,query:h.query,fragment:h.fragment};if(!h.netLoc&&(p.netLoc=g.netLoc,h.path[0]!=="/"))if(!h.path)p.path=g.path,h.params||(p.params=g.params,h.query||(p.query=g.query));else{var x=g.path,v=x.substring(0,x.lastIndexOf("/")+1)+h.path;p.path=a.normalizePath(v)}return p.path===null&&(p.path=d.alwaysNormalize?a.normalizePath(h.path):h.path),a.buildURLFromParts(p)},parseURL:function(c){var l=s.exec(c);return l?{scheme:l[1]||"",netLoc:l[2]||"",path:l[3]||"",params:l[4]||"",query:l[5]||"",fragment:l[6]||""}:null},normalizePath:function(c){for(c=c.split("").reverse().join("").replace(i,"");c.length!==(c=c.replace(o,"")).length;);return c.split("").reverse().join("")},buildURLFromParts:function(c){return c.scheme+c.netLoc+c.path+c.params+c.query+c.fragment}};r.exports=a})()}(oi)),oi.exports}var Wo=yv();class Yo{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var Pe={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class mf{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,Sv(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let n;s.length===1?n=(t==null?void 0:t.byteRangeEndOffset)||0:n=parseInt(s[1]),this._byteRange=[n,parseInt(s[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={[Pe.AUDIO]:null,[Pe.VIDEO]:null,[Pe.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 Yo),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Wo.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[Pe.AUDIO]=null,e[Pe.VIDEO]=null,e[Pe.AUDIOVIDEO]=null}}function qe(r){return r.sn!=="initSegment"}class ai extends mf{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(ne(e)&&ne(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 s=Object.keys(t);if(s.length===1){const n=this._decryptdata=t[s[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=ne(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 s=Object.keys(this.levelkeys),n=s.length;if(n>1||n===1&&(t=this.levelkeys[s[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(!ne(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return qe(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 s;const n=t[e];n&&!((s=this._decryptdata)!=null&&s.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,s,n,i,o=!1){const{elementaryStreams:a}=this,c=a[e];if(!c){a[e]={startPTS:t,endPTS:s,startDTS:n,endDTS:i,partial:o};return}c.startPTS=Math.min(c.startPTS,t),c.endPTS=Math.max(c.endPTS,s),c.startDTS=Math.min(c.startDTS,n),c.endDTS=Math.max(c.endDTS,i)}}class bv extends mf{constructor(e,t,s,n,i){super(s),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 o=e.enumeratedString("BYTERANGE");o&&this.setByteRange(o,i),i&&(this.fragOffset=i.fragOffset+i.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function pf(r,e){const t=Object.getPrototypeOf(r);if(t){const s=Object.getOwnPropertyDescriptor(t,e);return s||pf(t,e)}}function Sv(r,e){const t=pf(r,e);t&&(t.enumerable=!0,Object.defineProperty(r,e,t))}const Ga=Math.pow(2,32)-1,Ev=[].push,xf={video:1,audio:2,id3:3,text:4};function st(r){return String.fromCharCode.apply(null,r)}function vf(r,e){const t=r[e]<<8|r[e+1];return t<0?65536+t:t}function pe(r,e){const t=yf(r,e);return t<0?4294967296+t:t}function Va(r,e){let t=pe(r,e);return t*=Math.pow(2,32),t+=pe(r,e+4),t}function yf(r,e){return r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3]}function Tv(r){const e=r.byteLength;for(let t=0;t<e;){const s=pe(r,t);if(s>8&&r[t+4]===109&&r[t+5]===111&&r[t+6]===111&&r[t+7]===102)return!0;t=s>1?t+s:e}return!1}function Ee(r,e){const t=[];if(!e.length)return t;const s=r.byteLength;for(let n=0;n<s;){const i=pe(r,n),o=st(r.subarray(n+4,n+8)),a=i>1?n+i:s;if(o===e[0])if(e.length===1)t.push(r.subarray(n+8,a));else{const c=Ee(r.subarray(n+8,a),e.slice(1));c.length&&Ev.apply(t,c)}n=a}return t}function wv(r){const e=[],t=r[0];let s=8;const n=pe(r,s);s+=4;let i=0,o=0;t===0?(i=pe(r,s),o=pe(r,s+4),s+=8):(i=Va(r,s),o=Va(r,s+8),s+=16),s+=2;let a=r.length+o;const c=vf(r,s);s+=2;for(let l=0;l<c;l++){let d=s;const u=pe(r,d);d+=4;const h=u&2147483647;if((u&2147483648)>>>31===1)return ke.warn("SIDX has hierarchical references (not supported)"),null;const m=pe(r,d);d+=4,e.push({referenceSize:h,subsegmentDuration:m,info:{duration:m/n,start:a,end:a+h-1}}),a+=h,d+=4,s=d}return{earliestPresentationTime:i,timescale:n,version:t,referencesCount:c,references:e}}function bf(r){const e=[],t=Ee(r,["moov","trak"]);for(let n=0;n<t.length;n++){const i=t[n],o=Ee(i,["tkhd"])[0];if(o){let a=o[0];const c=pe(o,a===0?12:20),l=Ee(i,["mdia","mdhd"])[0];if(l){a=l[0];const d=pe(l,a===0?12:20),u=Ee(i,["mdia","hdlr"])[0];if(u){const h=st(u.subarray(8,12)),g={soun:Pe.AUDIO,vide:Pe.VIDEO}[h],m=Ee(i,["mdia","minf","stbl","stsd"])[0],p=Rv(m);g?(e[c]={timescale:d,type:g,stsd:p},e[g]=_e({timescale:d,id:c},p)):e[c]={timescale:d,type:h,stsd:p}}}}}return Ee(r,["moov","mvex","trex"]).forEach(n=>{const i=pe(n,4),o=e[i];o&&(o.default={duration:pe(n,12),flags:pe(n,20)})}),e}function Rv(r){const e=r.subarray(8),t=e.subarray(86),s=st(e.subarray(4,8));let n=s,i;const o=s==="enca"||s==="encv";if(o){const l=Ee(e,[s])[0].subarray(s==="enca"?28:78);Ee(l,["sinf"]).forEach(u=>{const h=Ee(u,["schm"])[0];if(h){const g=st(h.subarray(4,8));if(g==="cbcs"||g==="cenc"){const m=Ee(u,["frma"])[0];m&&(n=st(m))}}})}const a=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const c=Ee(t,["avcC"])[0];c&&c.length>3&&(n+="."+Xr(c[1])+Xr(c[2])+Xr(c[3]),i=qr(a==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const c=Ee(e,[s])[0],l=Ee(c.subarray(28),["esds"])[0];if(l&&l.length>7){let d=4;if(l[d++]!==3)break;d=li(l,d),d+=2;const u=l[d++];if(u&128&&(d+=2),u&64&&(d+=l[d++]),l[d++]!==4)break;d=li(l,d);const h=l[d++];if(h===64)n+="."+Xr(h);else break;if(d+=12,l[d++]!==5)break;d=li(l,d);const g=l[d++];let m=(g&248)>>3;m===31&&(m+=1+((g&7)<<3)+((l[d]&224)>>5)),n+="."+m}break}case"hvc1":case"hev1":{const c=Ee(t,["hvcC"])[0];if(c&&c.length>12){const l=c[1],d=["","A","B","C"][l>>6],u=l&31,h=pe(c,2),g=(l&32)>>5?"H":"L",m=c[12],p=c.subarray(6,12);n+="."+d+u,n+="."+Av(h).toString(16).toUpperCase(),n+="."+g+m;let x="";for(let v=p.length;v--;){const y=p[v];(y||x)&&(x="."+y.toString(16).toUpperCase()+x)}n+=x}i=qr(a=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{n=qr(n,t)||n;break}case"vp09":{const c=Ee(t,["vpcC"])[0];if(c&&c.length>6){const l=c[4],d=c[5],u=c[6]>>4&15;n+="."+Zt(l)+"."+Zt(d)+"."+Zt(u)}break}case"av01":{const c=Ee(t,["av1C"])[0];if(c&&c.length>2){const l=c[1]>>>5,d=c[1]&31,u=c[2]>>>7?"H":"M",h=(c[2]&64)>>6,g=(c[2]&32)>>5,m=l===2&&h?g?12:10:h?10:8,p=(c[2]&16)>>4,x=(c[2]&8)>>3,v=(c[2]&4)>>2,y=c[2]&3;n+="."+l+"."+Zt(d)+u+"."+Zt(m)+"."+p+"."+x+v+y+"."+Zt(1)+"."+Zt(1)+"."+Zt(1)+"."+0,i=qr("dav1",t)}break}}return{codec:n,encrypted:o,supplemental:i}}function qr(r,e){const t=Ee(e,["dvvC"]),s=t.length?t[0]:Ee(e,["dvcC"])[0];if(s){const n=s[2]>>1&127,i=s[2]<<5&32|s[3]>>3&31;return r+"."+Zt(n)+"."+Zt(i)}}function Av(r){let e=0;for(let t=0;t<32;t++)e|=(r>>t&1)<<31-t;return e>>>0}function li(r,e){const t=e+5;for(;r[e++]&128&&e<t;);return e}function Xr(r){return("0"+r.toString(16).toUpperCase()).slice(-2)}function Zt(r){return(r<10?"0":"")+r}function Iv(r,e){if(!r||!e)return;const t=e.keyId;t&&e.isCommonEncryption&&Sf(r,(s,n)=>{const i=s.subarray(8,24);i.some(o=>o!==0)||(ke.log(`[eme] Patching keyId in 'enc${n?"a":"v"}>sinf>>tenc' box: ${ct(i)} -> ${ct(t)}`),s.set(t,8))})}function Lv(r){const e=[];return Sf(r,t=>e.push(t.subarray(8,24))),e}function Sf(r,e){Ee(r,["moov","trak"]).forEach(s=>{const n=Ee(s,["mdia","minf","stbl","stsd"])[0];if(!n)return;const i=n.subarray(8);let o=Ee(i,["enca"]);const a=o.length>0;a||(o=Ee(i,["encv"])),o.forEach(c=>{const l=a?c.subarray(28):c.subarray(78);Ee(l,["sinf"]).forEach(u=>{const h=Ef(u);h&&e(h,a)})})})}function Ef(r){const e=Ee(r,["schm"])[0];if(e){const t=st(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const s=Ee(r,["schi","tenc"])[0];if(s)return s}}}function Cv(r,e,t){const s={},n=Ee(r,["moof","traf"]);for(let i=0;i<n.length;i++){const o=n[i],a=Ee(o,["tfhd"])[0],c=pe(a,4),l=e[c];if(!l)continue;s[c]||(s[c]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const d=s[c],u=Ee(o,["tfdt"])[0];if(u){const b=u[0];let T=pe(u,4);b===1&&(T===Ga?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(T*=Ga+1,T+=pe(u,8))),ne(T)&&(!ne(d.start)||T<d.start)&&(d.start=T)}const h=l.default,g=pe(a,0)|(h==null?void 0:h.flags);let m=(h==null?void 0:h.duration)||0;g&8&&(g&2?m=pe(a,12):m=pe(a,8));const p=Ee(o,["trun"]);let x=d.start||0,v=0,y=m;for(let b=0;b<p.length;b++){const T=p[b],R=pe(T,4),_=d.sampleCount;d.sampleCount+=R;const w=T[3]&1,A=T[3]&4,C=T[2]&1,L=T[2]&2,P=T[2]&4,M=T[2]&8;let j=8,D=R;for(w&&(j+=4),A&&R&&(!(T[j+1]&1)&&d.keyFrameIndex===void 0&&(d.keyFrameIndex=_),j+=4,C?(y=pe(T,j),j+=4):y=m,L&&(j+=4),M&&(j+=4),x+=y,v+=y,D--);D--;)C?(y=pe(T,j),j+=4):y=m,L&&(j+=4),P&&(T[j+1]&1||d.keyFrameIndex===void 0&&(d.keyFrameIndex=d.sampleCount-(D+1),d.keyFrameStart=x),j+=4),M&&(j+=4),x+=y,v+=y;!v&&m&&(v+=m*R)}d.duration+=v}if(!Object.keys(s).some(i=>s[i].duration)){let i=1/0,o=0;const a=Ee(r,["sidx"]);for(let c=0;c<a.length;c++){const l=wv(a[c]);if(l!=null&&l.references){i=Math.min(i,l.earliestPresentationTime/l.timescale);const d=l.references.reduce((u,h)=>u+h.info.duration||0,0);o=Math.max(o,d+l.earliestPresentationTime/l.timescale)}}o&&ne(o)&&Object.keys(s).forEach(c=>{s[c].duration||(s[c].duration=o*s[c].timescale-s[c].start)})}return s}function _v(r){const e={valid:null,remainder:null},t=Ee(r,["moof"]);if(t.length<2)return e.remainder=r,e;const s=t[t.length-1];return e.valid=r.slice(0,s.byteOffset-8),e.remainder=r.slice(s.byteOffset-8),e}function $t(r,e){const t=new Uint8Array(r.length+e.length);return t.set(r),t.set(e,r.length),t}function Ha(r,e){const t=[],s=e.samples,n=e.timescale,i=e.id;let o=!1;return Ee(s,["moof"]).map(c=>{const l=c.byteOffset-8;Ee(c,["traf"]).map(u=>{const h=Ee(u,["tfdt"]).map(g=>{const m=g[0];let p=pe(g,4);return m===1&&(p*=Math.pow(2,32),p+=pe(g,8)),p/n})[0];return h!==void 0&&(r=h),Ee(u,["tfhd"]).map(g=>{const m=pe(g,4),p=pe(g,0)&16777215,x=(p&1)!==0,v=(p&2)!==0,y=(p&8)!==0;let b=0;const T=(p&16)!==0;let R=0;const _=(p&32)!==0;let w=8;m===i&&(x&&(w+=8),v&&(w+=4),y&&(b=pe(g,w),w+=4),T&&(R=pe(g,w),w+=4),_&&(w+=4),e.type==="video"&&(o=zn(e.codec)),Ee(u,["trun"]).map(A=>{const C=A[0],L=pe(A,0)&16777215,P=(L&1)!==0;let M=0;const j=(L&4)!==0,D=(L&256)!==0;let $=0;const N=(L&512)!==0;let F=0;const k=(L&1024)!==0,z=(L&2048)!==0;let Y=0;const U=pe(A,4);let K=8;P&&(M=pe(A,K),K+=4),j&&(K+=4);let G=M+l;for(let H=0;H<U;H++){if(D?($=pe(A,K),K+=4):$=b,N?(F=pe(A,K),K+=4):F=R,k&&(K+=4),z&&(C===0?Y=pe(A,K):Y=yf(A,K),K+=4),e.type===Pe.VIDEO){let q=0;for(;q<F;){const J=pe(s,G);if(G+=4,kv(o,s[G])){const ee=s.subarray(G,G+J);qo(ee,o?2:1,r+Y/n,t)}G+=J,q+=J+4}}r+=$/n}}))})})}),t}function zn(r){if(!r)return!1;const e=r.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function kv(r,e){if(r){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function qo(r,e,t,s){const n=Tf(r);let i=0;i+=e;let o=0,a=0,c=0;for(;i<n.length;){o=0;do{if(i>=n.length)break;c=n[i++],o+=c}while(c===255);a=0;do{if(i>=n.length)break;c=n[i++],a+=c}while(c===255);const l=n.length-i;let d=i;if(a<l)i+=a;else if(a>l){ke.error(`Malformed SEI payload. ${a} is too small, only ${l} bytes left to parse.`);break}if(o===4){if(n[d++]===181){const h=vf(n,d);if(d+=2,h===49){const g=pe(n,d);if(d+=4,g===1195456820){const m=n[d++];if(m===3){const p=n[d++],x=31&p,v=64&p,y=v?2+x*3:0,b=new Uint8Array(y);if(v){b[0]=p;for(let T=1;T<y;T++)b[T]=n[d++]}s.push({type:m,payloadType:o,pts:t,bytes:b})}}}}}else if(o===5&&a>16){const u=[];for(let m=0;m<16;m++){const p=n[d++].toString(16);u.push(p.length==1?"0"+p:p),(m===3||m===5||m===7||m===9)&&u.push("-")}const h=a-16,g=new Uint8Array(h);for(let m=0;m<h;m++)g[m]=n[d++];s.push({payloadType:o,pts:t,uuid:u.join(""),userData:Pt(g),userDataBytes:g})}}}function Tf(r){const e=r.byteLength,t=[];let s=1;for(;s<e-2;)r[s]===0&&r[s+1]===0&&r[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return r;const n=e-t.length,i=new Uint8Array(n);let o=0;for(s=0;s<n;o++,s++)o===t[0]&&(o++,t.shift()),i[s]=r[o];return i}function Dv(r){const e=r[0];let t="",s="",n=0,i=0,o=0,a=0,c=0,l=0;if(e===0){for(;st(r.subarray(l,l+1))!=="\0";)t+=st(r.subarray(l,l+1)),l+=1;for(t+=st(r.subarray(l,l+1)),l+=1;st(r.subarray(l,l+1))!=="\0";)s+=st(r.subarray(l,l+1)),l+=1;s+=st(r.subarray(l,l+1)),l+=1,n=pe(r,12),i=pe(r,16),a=pe(r,20),c=pe(r,24),l=28}else if(e===1){l+=4,n=pe(r,l),l+=4;const u=pe(r,l);l+=4;const h=pe(r,l);for(l+=4,o=2**32*u+h,lv(o)||(o=Number.MAX_SAFE_INTEGER,ke.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),a=pe(r,l),l+=4,c=pe(r,l),l+=4;st(r.subarray(l,l+1))!=="\0";)t+=st(r.subarray(l,l+1)),l+=1;for(t+=st(r.subarray(l,l+1)),l+=1;st(r.subarray(l,l+1))!=="\0";)s+=st(r.subarray(l,l+1)),l+=1;s+=st(r.subarray(l,l+1)),l+=1}const d=r.subarray(l,r.byteLength);return{schemeIdUri:t,value:s,timeScale:n,presentationTime:o,presentationTimeDelta:i,eventDuration:a,id:c,payload:d}}function Pv(r,...e){const t=e.length;let s=8,n=t;for(;n--;)s+=e[n].byteLength;const i=new Uint8Array(s);for(i[0]=s>>24&255,i[1]=s>>16&255,i[2]=s>>8&255,i[3]=s&255,i.set(r,4),n=0,s=8;n<t;n++)i.set(e[n],s),s+=e[n].byteLength;return i}function Nv(r,e,t){if(r.byteLength!==16)throw new RangeError("Invalid system id");let s,n;s=0,n=new Uint8Array;let i;s>0?(i=new Uint8Array(4),e.length>0&&new DataView(i.buffer).setUint32(0,e.length,!1)):i=new Uint8Array;const o=new Uint8Array(4);return t.byteLength>0&&new DataView(o.buffer).setUint32(0,t.byteLength,!1),Pv([112,115,115,104],new Uint8Array([s,0,0,0]),r,i,n,o,t)}function Mv(r){const e=[];if(r instanceof ArrayBuffer){const t=r.byteLength;let s=0;for(;s+32<t;){const n=new DataView(r,s),i=Fv(n);e.push(i),s+=i.size}}return e}function Fv(r){const e=r.getUint32(0),t=r.byteOffset,s=r.byteLength;if(s<e)return{offset:t,size:s};if(r.getUint32(4)!==1886614376)return{offset:t,size:e};const i=r.getUint32(8)>>>24;if(i!==0&&i!==1)return{offset:t,size:e};const o=r.buffer,a=ct(new Uint8Array(o,t+12,16));let c=null,l=null,d=0;if(i===0)d=28;else{const h=r.getUint32(28);if(!h||s<32+h*16)return{offset:t,size:e};c=[];for(let g=0;g<h;g++)c.push(new Uint8Array(o,t+32+g*16,16));d=32+h*16}if(!d)return{offset:t,size:e};const u=r.getUint32(d);return e-32<u?{offset:t,size:e}:(l=new Uint8Array(o,t+d+4,u),{version:i,systemId:a,kids:c,data:l,offset:t,size:e})}const wf=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),sr={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 Xo(r,e){const t=sr[e];return!!t&&!!t[r.slice(0,4)]}function _r(r,e,t=!0){return!r.split(",").some(s=>!Qo(s,e,t))}function Qo(r,e,t=!0){var s;const n=Es(t);return(s=n==null?void 0:n.isTypeSupported(kr(r,e)))!=null?s:!1}function kr(r,e){return`${e}/mp4;codecs=${r}`}function Ka(r){if(r){const e=r.substring(0,4);return sr.video[e]}return 2}function wn(r){const e=wf();return r.split(",").reduce((t,s)=>{const i=e&&zn(s)?9:sr.video[s];return i?(i*2+t)/(t?3:2):(sr.audio[s]+t)/(t?2:1)},0)}const ci={};function Ov(r,e=!0){if(ci[r])return ci[r];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[r];for(let n=0;n<t.length;n++){var s;if(Qo(t[n],"audio",e))return ci[r]=t[n],t[n];if(t[n]==="mp3"&&(s=Es(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return r}const jv=/flac|opus|mp4a\.40\.34/i;function Rn(r,e=!0){return r.replace(jv,t=>Ov(t.toLowerCase(),e))}function Bv(r,e){const t=[];if(r){const s=r.split(",");for(let n=0;n<s.length;n++)Xo(s[n],"video")||t.push(s[n])}return e&&t.push(e),t.join(",")}function fn(r,e){if(r&&(r.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(r)!==-1)&&(za(r,"audio")||za(r,"video")))return r;if(e){const t=e.split(",");if(t.length>1){if(r){for(let s=t.length;s--;)if(t[s].substring(0,4)===r.substring(0,4))return t[s]}return t[0]}}return e||r}function za(r,e){return Xo(r,e)&&Qo(r,e)}function $v(r){const e=r.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}function Uv(r){if(r.startsWith("av01.")){const e=r.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return r}function Wa(r){const e=Es(r)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Ki(r){return r.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Gv={supported:!0,powerEfficient:!0,smooth:!0},Vv={supported:!1,smooth:!1,powerEfficient:!1},Rf={supported:!0,configurations:[],decodingInfoResults:[Gv]};function Af(r,e){return{supported:!1,configurations:e,decodingInfoResults:[Vv],error:r}}function Hv(r,e,t,s,n,i){const o=r.videoCodec,a=r.audioCodec?r.audioGroups:null,c=i==null?void 0:i.audioCodec,l=i==null?void 0:i.channels,d=l?parseInt(l):c?1/0:2;let u=null;if(a!=null&&a.length)try{a.length===1&&a[0]?u=e.groups[a[0]].channels:u=a.reduce((h,g)=>{if(g){const m=e.groups[g];if(!m)throw new Error(`Audio track group ${g} not found`);Object.keys(m.channels).forEach(p=>{h[p]=(h[p]||0)+m.channels[p]})}return h},{2:0})}catch{return!0}return o!==void 0&&(o.split(",").some(h=>zn(h))||r.width>1920&&r.height>1088||r.height>1920&&r.width>1088||r.frameRate>Math.max(s,30)||r.videoRange!=="SDR"&&r.videoRange!==t||r.bitrate>Math.max(n,8e6))||!!u&&ne(d)&&Object.keys(u).some(h=>parseInt(h)>d)}function If(r,e,t,s={}){const n=r.videoCodec;if(!n&&!r.audioCodec||!t)return Promise.resolve(Rf);const i=[],o=Kv(r),a=o.length,c=zv(r,e,a>0),l=c.length;for(let d=a||1*l||1;d--;){const u={type:"media-source"};if(a&&(u.video=o[d%a]),l){u.audio=c[d%l];const h=u.audio.bitrate;u.video&&h&&(u.video.bitrate-=h)}i.push(u)}if(n){const d=navigator.userAgent;if(n.split(",").some(u=>zn(u))&&wf())return Promise.resolve(Af(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${d})`),i))}return Promise.all(i.map(d=>{const u=Yv(d);return s[u]||(s[u]=t.decodingInfo(d))})).then(d=>({supported:!d.some(u=>!u.supported),configurations:i,decodingInfoResults:d})).catch(d=>({supported:!1,configurations:i,decodingInfoResults:[],error:d}))}function Kv(r){var e;const t=(e=r.videoCodec)==null?void 0:e.split(","),s=Lf(r),n=r.width||640,i=r.height||480,o=r.frameRate||30,a=r.videoRange.toLowerCase();return t?t.map(c=>{const l={contentType:kr(Uv(c),"video"),width:n,height:i,bitrate:s,framerate:o};return a!=="sdr"&&(l.transferFunction=a),l}):[]}function zv(r,e,t){var s;const n=(s=r.audioCodec)==null?void 0:s.split(","),i=Lf(r);return n&&r.audioGroups?r.audioGroups.reduce((o,a)=>{var c;const l=a?(c=e.groups[a])==null?void 0:c.tracks:null;return l?l.reduce((d,u)=>{if(u.groupId===a){const h=parseFloat(u.channels||"");n.forEach(g=>{const m={contentType:kr(g,"audio"),bitrate:t?Wv(g,i):i};h&&(m.channels=""+h),d.push(m)})}return d},o):o},[]):[]}function Wv(r,e){if(e<=1)return 1;let t=128e3;return r==="ec-3"?t=768e3:r==="ac-3"&&(t=64e4),Math.min(e/2,t)}function Lf(r){return Math.ceil(Math.max(r.bitrate*.9,r.averageBitrate)/1e3)*1e3||1}function Yv(r){let e="";const{audio:t,video:s}=r;if(s){const n=Ki(s.contentType);e+=`${n}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(t){const n=Ki(t.contentType);e+=`${s?"_":""}${n}_c${t.channels}`}return e}const zi=["NONE","TYPE-0","TYPE-1",null];function qv(r){return zi.indexOf(r)>-1}const An=["SDR","PQ","HLG"];function Xv(r){return!!r&&An.indexOf(r)>-1}var hn={No:"",Yes:"YES",v2:"v2"};function Ya(r){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=r,n=s<e/2;return e&&n?t?hn.v2:hn.Yes:hn.No}class qa{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}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}}class Dr{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(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.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 Xa(this._audioGroups,e)}hasSubtitleGroup(e){return Xa(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.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 Xa(r,e){return!e||!r?!1:r.indexOf(e)!==-1}function Qv(){if(typeof matchMedia=="function"){const r=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(r.media!==e.media)return r.matches===!0}return!1}function Zv(r,e){let t=!1,s=[];if(r&&(t=r!=="SDR",s=[r]),e){s=e.allowedVideoRanges||An.slice(0);const n=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:n&&Qv(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}const Jv=r=>{const e=new WeakSet;return(t,s)=>{if(r&&(s=r(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},Ne=(r,e)=>JSON.stringify(r,Jv(e));function ey(r,e,t,s,n){const i=Object.keys(r),o=s==null?void 0:s.channels,a=s==null?void 0:s.audioCodec,c=n==null?void 0:n.videoCodec,l=o&&parseInt(o)===2;let d=!1,u=!1,h=1/0,g=1/0,m=1/0,p=1/0,x=0,v=[];const{preferHDR:y,allowedVideoRanges:b}=Zv(e,n);for(let A=i.length;A--;){const C=r[i[A]];d||(d=C.channels[2]>0),h=Math.min(h,C.minHeight),g=Math.min(g,C.minFramerate),m=Math.min(m,C.minBitrate),b.filter(P=>C.videoRanges[P]>0).length>0&&(u=!0)}h=ne(h)?h:0,g=ne(g)?g:0;const T=Math.max(1080,h),R=Math.max(30,g);m=ne(m)?m:t,t=Math.max(m,t),u||(e=void 0);const _=i.length>1;return{codecSet:i.reduce((A,C)=>{const L=r[C];if(C===A)return A;if(v=u?b.filter(P=>L.videoRanges[P]>0):[],_){if(L.minBitrate>t)return Xt(C,`min bitrate of ${L.minBitrate} > current estimate of ${t}`),A;if(!L.hasDefaultAudio)return Xt(C,"no renditions with default or auto-select sound found"),A;if(a&&C.indexOf(a.substring(0,4))%5!==0)return Xt(C,`audio codec preference "${a}" not found`),A;if(o&&!l){if(!L.channels[o])return Xt(C,`no renditions with ${o} channel sound found (channels options: ${Object.keys(L.channels)})`),A}else if((!a||l)&&d&&L.channels[2]===0)return Xt(C,"no renditions with stereo sound found"),A;if(L.minHeight>T)return Xt(C,`min resolution of ${L.minHeight} > maximum of ${T}`),A;if(L.minFramerate>R)return Xt(C,`min framerate of ${L.minFramerate} > maximum of ${R}`),A;if(!v.some(P=>L.videoRanges[P]>0))return Xt(C,`no variants with VIDEO-RANGE of ${Ne(v)} found`),A;if(c&&C.indexOf(c.substring(0,4))%5!==0)return Xt(C,`video codec preference "${c}" not found`),A;if(L.maxScore<x)return Xt(C,`max score of ${L.maxScore} < selected max of ${x}`),A}return A&&(wn(C)>=wn(A)||L.fragmentError>r[A].fragmentError)?A:(p=L.minIndex,x=L.maxScore,C)},void 0),videoRanges:v,preferHDR:y,minFramerate:g,minBitrate:m,minIndex:p}}function Xt(r,e){ke.log(`[abr] start candidates with "${r}" ignored because ${e}`)}function Cf(r){return r.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const n=t.channels||"2";return s.channels[n]=(s.channels[n]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function ty(r,e,t,s){return r.slice(t,s+1).reduce((n,i,o)=>{if(!i.codecSet)return n;const a=i.audioGroups;let c=n[i.codecSet];c||(n[i.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:o,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!a,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,i.bitrate);const l=Math.min(i.height,i.width);return c.minHeight=Math.min(c.minHeight,l),c.minFramerate=Math.min(c.minFramerate,i.frameRate),c.minIndex=Math.min(c.minIndex,o),c.maxScore=Math.max(c.maxScore,i.score),c.fragmentError+=i.fragmentError,c.videoRanges[i.videoRange]=(c.videoRanges[i.videoRange]||0)+1,a&&a.forEach(d=>{if(!d)return;const u=e.groups[d];u&&(c.hasDefaultAudio=c.hasDefaultAudio||e.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(u.channels).forEach(h=>{c.channels[h]=(c.channels[h]||0)+u.channels[h]}))}),n},{})}function Qa(r){if(!r)return r;const{lang:e,assocLang:t,characteristics:s,channels:n,audioCodec:i}=r;return{lang:e,assocLang:t,characteristics:s,channels:n,audioCodec:i}}function es(r,e,t){if("attrs"in r){const s=e.indexOf(r);if(s!==-1)return s}for(let s=0;s<e.length;s++){const n=e[s];if(Ns(r,n,t))return s}return-1}function Ns(r,e,t){const{groupId:s,name:n,lang:i,assocLang:o,default:a}=r,c=r.forced;return(s===void 0||e.groupId===s)&&(n===void 0||e.name===n)&&(i===void 0||sy(i,e.lang))&&(i===void 0||e.assocLang===o)&&(a===void 0||e.default===a)&&(c===void 0||e.forced===c)&&(!("characteristics"in r)||ry(r.characteristics||"",e.characteristics))&&(t===void 0||t(r,e))}function sy(r,e="--"){return r.length===e.length?r===e:r.startsWith(e)||e.startsWith(r)}function ry(r,e=""){const t=r.split(","),s=e.split(",");return t.length===s.length&&!t.some(n=>s.indexOf(n)===-1)}function Ds(r,e){const{audioCodec:t,channels:s}=r;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function ny(r,e,t,s,n){const i=e[s],a=e.reduce((h,g,m)=>{const p=g.uri;return(h[p]||(h[p]=[])).push(m),h},{})[i.uri];a.length>1&&(s=Math.max.apply(Math,a));const c=i.videoRange,l=i.frameRate,d=i.codecSet.substring(0,4),u=Za(e,s,h=>{if(h.videoRange!==c||h.frameRate!==l||h.codecSet.substring(0,4)!==d)return!1;const g=h.audioGroups,m=t.filter(p=>!g||g.indexOf(p.groupId)!==-1);return es(r,m,n)>-1});return u>-1?u:Za(e,s,h=>{const g=h.audioGroups,m=t.filter(p=>!g||g.indexOf(p.groupId)!==-1);return es(r,m,n)>-1})}function Za(r,e,t){for(let s=e;s>-1;s--)if(t(r[s]))return s;for(let s=e+1;s<r.length;s++)if(t(r[s]))return s;return-1}function In(r,e){var t;return!!r&&r!==((t=e.loadLevelObj)==null?void 0:t.uri)}class iy extends Ut{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 s;const{fragCurrent:n,partCurrent:i,hls:o}=this,{autoLevelEnabled:a,media:c}=o;if(!n||!c)return;const l=performance.now(),d=i?i.stats:n.stats,u=i?i.duration:n.duration,h=l-d.loading.start,g=o.minAutoLevel,m=n.level,p=this._nextAutoLevel;if(d.aborted||d.loaded&&d.loaded===d.total||m<=g){this.clearTimer(),this._nextAutoLevel=-1;return}if(!a)return;const x=p>-1&&p!==m,v=!!t||x;if(!v&&(c.paused||!c.playbackRate||!c.readyState))return;const y=o.mainForwardBufferInfo;if(!v&&y===null)return;const b=this.bwEstimator.getEstimateTTFB(),T=Math.abs(c.playbackRate);if(h<=Math.max(b,1e3*(u/(T*2))))return;const R=y?y.len/T:0,_=d.loading.first?d.loading.first-d.loading.start:-1,w=d.loaded&&_>-1,A=this.getBwEstimate(),C=o.levels,L=C[m],P=Math.max(d.loaded,Math.round(u*(n.bitrate||L.averageBitrate)/8));let M=w?h-_:h;M<1&&w&&(M=Math.min(h,d.loaded*8/A));const j=w?d.loaded*1e3/M:0,D=b/1e3,$=j?(P-d.loaded)/j:P*8/A+D;if($<=R)return;const N=j?j*8:A,F=((s=(t==null?void 0:t.details)||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,k=this.hls.config.abrBandWidthUpFactor;let z=Number.POSITIVE_INFINITY,Y;for(Y=m-1;Y>g;Y--){const H=C[Y].maxBitrate,q=!C[Y].details||F;if(z=this.getTimeToLoadFrag(D,N,u*H,q),z<Math.min(R,u+D))break}if(z>=$||z>u*10)return;w?this.bwEstimator.sample(h-Math.min(b,_),d.loaded):this.bwEstimator.sampleTTFB(h);const U=C[Y].maxBitrate;this.getBwEstimate()*k>U&&this.resetEstimator(U);const K=this.findBestLevel(U,g,Y,0,R,1,1);K>-1&&(Y=K),this.warn(`Fragment ${n.sn}${i?" part "+i.index:""} of level ${m} is loading too slowly;
36
+ Fragment duration: ${n.duration.toFixed(3)}
37
+ Time to underbuffer: ${R.toFixed(3)} s
38
+ Estimated load time for current fragment: ${$.toFixed(3)} s
39
+ Estimated load time for down switch fragment: ${z.toFixed(3)} s
40
+ TTFB estimate: ${_|0} ms
41
+ Current BW estimate: ${ne(A)?A|0:"Unknown"} bps
42
+ New BW estimate: ${this.getBwEstimate()|0} bps
43
+ Switching to level ${Y} @ ${U|0} bps`),o.nextLoadLevel=o.nextAutoLevel=Y,this.clearTimer();const G=()=>{if(this.clearTimer(),this.fragCurrent===n&&this.hls.loadLevel===Y&&Y>0){const H=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${Y>0?"and switching down":""}
44
+ Fragment duration: ${n.duration.toFixed(3)} s
45
+ Time to underbuffer: ${H.toFixed(3)} s`),n.abortRequests(),this.fragCurrent=this.partCurrent=null,Y>g){let q=this.findBestLevel(this.hls.levels[g].bitrate,g,Y,0,H,1,1);q===-1&&(q=g),this.hls.nextLoadLevel=this.hls.nextAutoLevel=q,this.resetEstimator(this.hls.levels[q].bitrate)}}};x||$>z*2?G():this.timer=self.setInterval(G,z*1e3),o.trigger(S.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:i,stats:d})},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 dv(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.FRAG_LOADING,this.onFragLoading,this),e.on(S.FRAG_LOADED,this.onFragLoaded,this),e.on(S.FRAG_BUFFERED,this.onFragBuffered,this),e.on(S.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(S.LEVEL_LOADED,this.onLevelLoaded,this),e.on(S.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(S.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(S.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.FRAG_LOADING,this.onFragLoading,this),e.off(S.FRAG_LOADED,this.onFragLoaded,this),e.off(S.FRAG_BUFFERED,this.onFragBuffered,this),e.off(S.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(S.LEVEL_LOADED,this.onLevelLoaded,this),e.off(S.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(S.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(S.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 s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var n;this.fragCurrent=s,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 B.BUFFER_ADD_CODEC_ERROR:case B.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case B.FRAG_LOAD_TIMEOUT:{const s=t.frag,{fragCurrent:n,partCurrent:i}=this;if(s&&n&&s.sn===n.sn&&s.level===n.level){const o=performance.now(),a=i?i.stats:s.stats,c=o-a.loading.start,l=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&l>-1){const u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(u,l),a.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(e,t,s,n){const i=e+s/t,o=n?e+this.lastLevelLoadSec:0;return i+o}onLevelLoaded(e,t){const s=this.hls.config,{loading:n}=t.stats,i=n.end-n.first;ne(i)&&(this.lastLevelLoadSec=i/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){const n=s?s.stats:t.stats;if(t.type===oe.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 i=s?s.duration:t.duration,o=this.hls.levels[t.level],a=(o.loaded?o.loaded.bytes:0)+n.loaded,c=(o.loaded?o.loaded.duration:0)+i;o.loaded={bytes:a,duration:c},o.realBitrate=Math.round(8*a/c)}if(t.bitrateTest){const i={stats:n,frag:t,part:s,id:t.type};this.onFragBuffered(S.FRAG_BUFFERED,i),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:n}=t,i=n!=null&&n.stats.loaded?n.stats:s.stats;if(i.aborted||this.ignoreFragment(s))return;const o=i.parsing.end-i.loading.start-Math.min(i.loading.first-i.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,i.loaded),i.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=o/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==oe.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,i=this.findBestLevel(s,t,e,0,n,1,1);if(i>-1)return i;const o=this.hls.firstLevel,a=Math.min(Math.max(o,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${o} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),n=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!n||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const i=s&&n?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const o=this.hls.levels;if(o.length>Math.max(e,i)&&o[e].loadError<=o[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:n,config:i,minAutoLevel:o}=s,a=t?t.duration:e?e.duration:0,c=this.getBwEstimate(),l=this.getStarvationDelay();let d=i.abrBandWidthFactor,u=i.abrBandWidthUpFactor;if(l){const x=this.findBestLevel(c,o,n,l,0,d,u);if(x>=0)return this.rebufferNotice=-1,x}let h=a?Math.min(a,i.maxStarvationDelay):i.maxStarvationDelay;if(!l){const x=this.bitrateTestDelay;x&&(h=(a?Math.min(a,i.maxLoadingDelay):i.maxLoadingDelay)-x,this.info(`bitrate test took ${Math.round(1e3*x)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),d=u=1)}const g=this.findBestLevel(c,o,n,l,h,d,u);if(this.rebufferNotice!==g&&(this.rebufferNotice=g,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${g}`)),g>-1)return g;const m=s.levels[o],p=s.loadLevelObj;return p&&(m==null?void 0:m.bitrate)<p.bitrate?o:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,n=e.mainForwardBufferInfo;return(n?n.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,n,i,o,a){var c;const l=n+i,d=this.lastLoadedFragLevel,u=d===-1?this.hls.firstLevel:d,{fragCurrent:h,partCurrent:g}=this,{levels:m,allAudioTracks:p,loadLevel:x,config:v}=this.hls;if(m.length===1)return 0;const y=m[u],b=!!((c=this.hls.latestLevelDetails)!=null&&c.live),T=x===-1||d===-1;let R,_="SDR",w=(y==null?void 0:y.frameRate)||0;const{audioPreference:A,videoPreference:C}=v,L=this.audioTracksByGroup||(this.audioTracksByGroup=Cf(p));let P=-1;if(T){if(this.firstSelection!==-1)return this.firstSelection;const N=this.codecTiers||(this.codecTiers=ty(m,L,t,s)),F=ey(N,_,e,A,C),{codecSet:k,videoRanges:z,minFramerate:Y,minBitrate:U,minIndex:K,preferHDR:G}=F;P=K,R=k,_=G?z[z.length-1]:z[0],w=Y,e=Math.max(e,U),this.log(`picked start tier ${Ne(F)}`)}else R=y==null?void 0:y.codecSet,_=y==null?void 0:y.videoRange;const M=g?g.duration:h?h.duration:0,j=this.bwEstimator.getEstimateTTFB()/1e3,D=[];for(let N=s;N>=t;N--){var $;const F=m[N],k=N>u;if(!F)continue;if(v.useMediaCapabilities&&!F.supportedResult&&!F.supportedPromise){const q=navigator.mediaCapabilities;typeof(q==null?void 0:q.decodingInfo)=="function"&&Hv(F,L,_,w,e,A)?(F.supportedPromise=If(F,L,q,this.supportedCache),F.supportedPromise.then(J=>{if(!this.hls)return;F.supportedResult=J;const ee=this.hls.levels,te=ee.indexOf(F);J.error?this.warn(`MediaCapabilities decodingInfo error: "${J.error}" for level ${te} ${Ne(J)}`):J.supported?J.decodingInfoResults.some(de=>de.smooth===!1||de.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${te} not smooth or powerEfficient: ${Ne(J)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${te} ${Ne(J)}`),te>-1&&ee.length>1&&(this.log(`Removing unsupported level ${te}`),this.hls.removeLevel(te),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(J=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${J}`)})):F.supportedResult=Rf}if((R&&F.codecSet!==R||_&&F.videoRange!==_||k&&w>F.frameRate||!k&&w>0&&w<F.frameRate||($=F.supportedResult)!=null&&($=$.decodingInfoResults)!=null&&$.some(q=>q.smooth===!1))&&(!T||N!==P)){D.push(N);continue}const z=F.details,Y=(g?z==null?void 0:z.partTarget:z==null?void 0:z.averagetargetduration)||M;let U;k?U=a*e:U=o*e;const K=M&&n>=M*2&&i===0?F.averageBitrate:F.maxBitrate,G=this.getTimeToLoadFrag(j,U,K*Y,z===void 0);if(U>=K&&(N===d||F.loadError===0&&F.fragmentError===0)&&(G<=j||!ne(G)||b&&!this.bitrateTestDelay||G<l)){const q=this.forcedAutoLevel;return N!==x&&(q===-1||q!==x)&&(D.length&&this.trace(`Skipped level(s) ${D.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${m[D[0]].codecs}" ${m[D[0]].videoRange}; not compatible with "${R}" ${_}`),this.info(`switch candidate:${u}->${N} adjustedbw(${Math.round(U)})-bitrate=${Math.round(U-K)} ttfb:${j.toFixed(1)} avgDuration:${Y.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${G.toFixed(1)} firstSelection:${T} codecSet:${F.codecSet} videoRange:${F.videoRange} hls.loadLevel:${x}`)),T&&(this.firstSelection=N),N}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}}const _f={search:function(r,e){let t=0,s=r.length-1,n=null,i=null;for(;t<=s;){n=(t+s)/2|0,i=r[n];const o=e(i);if(o>0)t=n+1;else if(o<0)s=n-1;else return i}return null}};function oy(r,e,t){if(e===null||!Array.isArray(r)||!r.length||!ne(e))return null;const s=r[0].programDateTime;if(e<(s||0))return null;const n=r[r.length-1].endProgramDateTime;if(e>=(n||0))return null;for(let i=0;i<r.length;++i){const o=r[i];if(ly(e,t,o))return o}return null}function Os(r,e,t=0,s=0,n=.005){let i=null;if(r){i=e[1+r.sn-e[0].sn]||null;const a=r.endDTS-t;a>0&&a<15e-7&&(t+=15e-7),i&&r.level!==i.level&&i.end<=r.end&&(i=e[2+r.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(i=e[0]);if(i&&((!r||r.level===i.level)&&Ja(t,s,i)===0||ay(i,r,Math.min(n,s))))return i;const o=_f.search(e,Ja.bind(null,t,s));return o&&(o!==r||!i)?o:i}function ay(r,e,t){if(e&&e.start===0&&e.level<r.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((n,i)=>(i[0]==="INF"&&(n+=parseFloat(i[1])),n),t);return r.start<=s}return!1}function Ja(r=0,e=0,t){if(t.start<=r&&t.start+t.duration>r)return 0;const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=r?1:t.start-s>r&&t.start?-1:0}function ly(r,e,t){const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>r}function kf(r,e,t){if(r&&r.startCC<=e&&r.endCC>=e){let s=r.fragments;const{fragmentHint:n}=r;n&&(s=s.concat(n));let i;return _f.search(s,o=>o.cc<e?1:o.cc>e?-1:(i=o,o.end<=t?1:o.start>t?-1:0)),i||null}return null}function Ln(r){switch(r.details){case B.FRAG_LOAD_TIMEOUT:case B.KEY_LOAD_TIMEOUT:case B.LEVEL_LOAD_TIMEOUT:case B.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Df(r){return r.details.startsWith("key")}function Pf(r){return Df(r)&&!!r.frag&&!r.frag.decryptdata}function el(r,e){const t=Ln(e);return r.default[`${t?"timeout":"error"}Retry`]}function Zo(r,e){const t=r.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*r.retryDelayMs,r.maxRetryDelayMs)}function tl(r){return _e(_e({},r),{errorRetry:null,timeoutRetry:null})}function Cn(r,e,t,s){if(!r)return!1;const n=s==null?void 0:s.code,i=e<r.maxNumRetry&&(cy(n)||!!t);return r.shouldRetry?r.shouldRetry(r,e,t,s,i):i}function cy(r){return Wi(r)||!!r&&(r<400||r>499)}function Wi(r){return r===0&&navigator.onLine===!1}var lt={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Ct={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class dy extends Ut{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(S.ERROR,this.onError,this),e.on(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(S.ERROR,this.onError,this),e.off(S.ERROR,this.onErrorOut,this),e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===oe.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,s=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||s===-1?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if((s=e.details)!=null&&s.hasKey(t))return!0;const n=e.audioGroups;if(n)return this.hls.allAudioTracks.filter(o=>n.indexOf(o.groupId)>=0).some(o=>{var a;return(a=o.details)==null?void 0:a.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const n=this.hls,i=t.context;switch(t.details){case B.FRAG_LOAD_ERROR:case B.FRAG_LOAD_TIMEOUT:case B.KEY_LOAD_ERROR:case B.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case B.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=Zs();return}case B.FRAG_GAP:case B.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=lt.SendAlternateToPenaltyBox;return}case B.LEVEL_EMPTY_ERROR:case B.LEVEL_PARSING_ERROR:{var o;const c=t.parent===oe.MAIN?t.level:n.loadLevel;t.details===B.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(o=o.levelDetails)!=null&&o.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case B.LEVEL_LOAD_ERROR:case B.LEVEL_LOAD_TIMEOUT:typeof(i==null?void 0:i.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.level));return;case B.AUDIO_TRACK_LOAD_ERROR:case B.AUDIO_TRACK_LOAD_TIMEOUT:case B.SUBTITLE_LOAD_ERROR:case B.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const c=n.loadLevelObj;if(c&&(i.type===Te.AUDIO_TRACK&&c.hasAudioGroup(i.groupId)||i.type===Te.SUBTITLE_TRACK&&c.hasSubtitleGroup(i.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=lt.SendAlternateToPenaltyBox,t.errorAction.flags=Ct.MoveAllAlternatesMatchingHost;return}}return;case B.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:lt.SendAlternateToPenaltyBox,flags:Ct.MoveAllAlternatesMatchingHDCP};return;case B.KEY_SYSTEM_SESSION_UPDATE_FAILED:case B.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case B.KEY_SYSTEM_NO_SESSION:t.errorAction={action:lt.SendAlternateToPenaltyBox,flags:Ct.MoveAllAlternatesMatchingKey};return;case B.BUFFER_ADD_CODEC_ERROR:case B.REMUX_ALLOC_ERROR:case B.BUFFER_APPEND_ERROR:if(!t.errorAction){var a;t.errorAction=this.getLevelSwitchAction(t,(a=t.level)!=null?a:n.loadLevel)}return;case B.INTERNAL_EXCEPTION:case B.BUFFER_APPENDING_ERROR:case B.BUFFER_FULL_ERROR:case B.LEVEL_SWITCH_ERROR:case B.BUFFER_STALLED_ERROR:case B.BUFFER_SEEK_OVER_HOLE:case B.BUFFER_NUDGE_ON_STALL:t.errorAction=Zs();return}t.type===ce.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Zs())}getPlaylistRetryOrSwitchAction(e,t){const s=this.hls,n=el(s.config.playlistLoadPolicy,e),i=this.playlistError++;if(Cn(n,i,Ln(e),e.response))return{action:lt.RetryRequest,flags:Ct.None,retryConfig:n,retryCount:i};const a=this.getLevelSwitchAction(e,t);return n&&(a.retryConfig=n,a.retryCount=i),a}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),n=t.levels[s],{fragLoadPolicy:i,keyLoadPolicy:o}=t.config,a=el(Df(e)?o:i,e),c=t.levels.reduce((d,u)=>d+u.fragmentError,0);if(n&&(e.details!==B.FRAG_GAP&&n.fragmentError++,!Pf(e)&&Cn(a,c,Ln(e),e.response)))return{action:lt.RetryRequest,flags:Ct.None,retryConfig:a,retryCount:c};const l=this.getLevelSwitchAction(e,s);return a&&(l.retryConfig=a,l.retryCount=c),l}getLevelSwitchAction(e,t){const s=this.hls;t==null&&(t=s.loadLevel);const n=this.hls.levels[t];if(n){var i,o;const l=e.details;n.loadError++,l===B.BUFFER_APPEND_ERROR&&n.fragmentError++;let d=-1;const{levels:u,loadLevel:h,minAutoLevel:g,maxAutoLevel:m}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);const p=(i=e.frag)==null?void 0:i.type,v=(p===oe.AUDIO&&l===B.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===B.BUFFER_ADD_CODEC_ERROR||l===B.BUFFER_APPEND_ERROR))&&u.some(({audioCodec:_})=>n.audioCodec!==_),b=e.sourceBufferName==="video"&&(l===B.BUFFER_ADD_CODEC_ERROR||l===B.BUFFER_APPEND_ERROR)&&u.some(({codecSet:_,audioCodec:w})=>n.codecSet!==_&&n.audioCodec===w),{type:T,groupId:R}=(o=e.context)!=null?o:{};for(let _=u.length;_--;){const w=(_+h)%u.length;if(w!==h&&w>=g&&w<=m&&u[w].loadError===0){var a,c;const A=u[w];if(l===B.FRAG_GAP&&p===oe.MAIN&&e.frag){const C=u[w].details;if(C){const L=Os(e.frag,C.fragments,e.frag.start);if(L!=null&&L.gap)continue}}else{if(T===Te.AUDIO_TRACK&&A.hasAudioGroup(R)||T===Te.SUBTITLE_TRACK&&A.hasSubtitleGroup(R))continue;if(p===oe.AUDIO&&(a=n.audioGroups)!=null&&a.some(C=>A.hasAudioGroup(C))||p===oe.SUBTITLE&&(c=n.subtitleGroups)!=null&&c.some(C=>A.hasSubtitleGroup(C))||v&&n.audioCodec===A.audioCodec||b&&n.codecSet===A.codecSet||!v&&n.codecSet!==A.codecSet)continue}d=w;break}}if(d>-1&&s.loadLevel!==d)return e.levelRetry=!0,this.playlistError=0,{action:lt.SendAlternateToPenaltyBox,flags:Ct.None,nextAutoLevel:d}}return{action:lt.SendAlternateToPenaltyBox,flags:Ct.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case lt.DoNothing:break;case lt.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==B.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,s=e.errorAction;if(!s)return;const{flags:n}=s,i=s.nextAutoLevel;switch(n){case Ct.None:this.switchLevel(e,i);break;case Ct.MoveAllAlternatesMatchingHDCP:{const c=this.getVariantLevelIndex(e.frag),l=t.levels[c],d=l==null?void 0:l.attrs["HDCP-LEVEL"];if(s.hdcpLevel=d,d==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(d){t.maxHdcpLevel=zi[zi.indexOf(d)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Ct.MoveAllAlternatesMatchingKey:{const c=e.decryptdata;if(c){const l=this.hls.levels,d=l.length;for(let h=d;h--;)if(this.variantHasKey(l[h],c)){var o,a;this.log(`Banned key found in level ${h} (${l[h].bitrate}bps) or audio group "${(o=l[h].audioGroups)==null?void 0:o.join(",")}" (${(a=e.frag)==null?void 0:a.type} fragment) ${ct(c.keyId||[])}`),l[h].fragmentError++,l[h].loadError++,this.log(`Removing level ${h} with key error (${e.error})`),this.hls.removeLevel(h)}const u=e.frag;if(this.hls.levels.length<d)s.resolved=!0;else if(u&&u.type!==oe.MAIN){const h=u.decryptdata;h&&!c.matches(h)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(e,i)}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===B.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const s=Ki(e.mimeType),n=this.hls.levels;for(let i=n.length;i--;)n[i][`${e.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${i} for ${e.details} ("${s}" not supported)`),this.hls.removeLevel(i))}}}function Zs(r){const e={action:lt.DoNothing,flags:Ct.None};return r&&(e.resolved=!0),e}var rt={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class uy{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(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.BUFFER_APPENDED,this.onBufferAppended,this),e.on(S.FRAG_BUFFERED,this.onFragBuffered,this),e.on(S.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.BUFFER_APPENDED,this.onBufferAppended,this),e.off(S.FRAG_BUFFERED,this.onFragBuffered,this),e.off(S.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let n=s.length;n--;){const i=s[n];if(!i)break;if(i.start<=e&&e<=i.end&&i.loaded)return i}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:n}=this,i=Object.keys(n);for(let o=i.length;o--;){const a=n[i[o]];if((a==null?void 0:a.body.type)===t&&(!s||a.buffered)){const c=a.body;if(c.start<=e&&e<=c.end)return c}}return null}detectEvictedFragments(e,t,s,n,i){this.timeRanges&&(this.timeRanges[e]=t);const o=(n==null?void 0:n.fragment.sn)||-1;Object.keys(this.fragments).forEach(a=>{const c=this.fragments[a];if(!c||o>=c.body.sn)return;if(!c.buffered&&(!c.loaded||i)){c.body.type===s&&this.removeFragment(c.body);return}const l=c.range[e];if(l){if(l.time.length===0){this.removeFragment(c.body);return}l.time.some(d=>{const u=!this.isTimeBuffered(d.startPTS,d.endPTS,t);return u&&this.removeFragment(c.body),u})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const s=e.frag,n=zs(s),i=this.fragments[n];if(!i||i.buffered&&s.gap)return;const o=!s.relurl;Object.keys(t).forEach(a=>{const c=s.elementaryStreams[a];if(!c)return;const l=t[a],d=o||c.partial===!0;i.range[a]=this.getBufferedTimes(s,e.part,d,l)}),i.loaded=null,Object.keys(i.range).length?(this.bufferedEnd(i,s),Qr(i)||this.removeParts(s.sn-1,s.type)):this.removeFragment(i.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=sl(s,n=>n.fragment.sn>=e))}fragBuffered(e,t){const s=zs(e);let n=this.fragments[s];!n&&t&&(n=this.fragments[s]={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,s,n){const i={time:[],partial:s},o=e.start,a=e.end,c=e.minEndPTS||a,l=e.maxStartPTS||o;for(let d=0;d<n.length;d++){const u=n.start(d)-this.bufferPadding,h=n.end(d)+this.bufferPadding;if(l>=u&&c<=h){i.time.push({startPTS:Math.max(o,n.start(d)),endPTS:Math.min(a,n.end(d))});break}else if(o<h&&a>u){const g=Math.max(o,n.start(d)),m=Math.min(a,n.end(d));m>g&&(i.partial=!0,i.time.push({startPTS:g,endPTS:m}))}else if(a<=u)break}return i}getPartialFragment(e){let t=null,s,n,i,o=0;const{bufferPadding:a,fragments:c}=this;return Object.keys(c).forEach(l=>{const d=c[l];d&&Qr(d)&&(n=d.body.start-a,i=d.body.end+a,e>=n&&e<=i&&(s=Math.min(e-n,i-e),o<=s&&(t=d.body,o=s)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||Qr(t))}getState(e){const t=zs(e),s=this.fragments[t];return s?s.buffered?Qr(s)?rt.PARTIAL:rt.OK:rt.APPENDING:rt.NOT_LOADED}isTimeBuffered(e,t,s){let n,i;for(let o=0;o<s.length;o++){if(n=s.start(o)-this.bufferPadding,i=s.end(o)+this.bufferPadding,e>=n&&t<=i)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 s=t.frag,n=t.part?null:t,i=zs(s);this.fragments[i]={body:s,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:n,timeRanges:i,type:o}=t;if(s.sn==="initSegment")return;const a=s.type;if(n){let l=this.activePartLists[a];l||(this.activePartLists[a]=l=[]),l.push(n)}this.timeRanges=i;const c=i[o];this.detectEvictedFragments(o,c,a,n)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=zs(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let n=s.length;n--;){const i=t[s[n]];if((i==null?void 0:i.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,s,n,i){n&&!this.hasGaps||Object.keys(this.fragments).forEach(o=>{const a=this.fragments[o];if(!a)return;const c=a.body;c.type!==s||n&&!c.gap||c.start<t&&c.end>e&&(a.buffered||i)&&this.removeFragment(c)})}removeFragment(e){const t=zs(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const n=e.sn;this.activePartLists[e.type]=sl(s,i=>i.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(s=>s.clearElementaryStreamInfo())}}function Qr(r){var e,t,s;return r.buffered&&!!(r.body.gap||(e=r.range.video)!=null&&e.partial||(t=r.range.audio)!=null&&t.partial||(s=r.range.audiovideo)!=null&&s.partial)}function zs(r){return`${r.type}_${r.level}_${r.sn}`}function sl(r,e){return r.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}var Ts={cbc:0,ctr:1};class fy{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case Ts.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Ts.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 hy(r){const e=r.byteLength,t=e&&new DataView(r.buffer).getUint8(e-1);return t?r.slice(0,e-t):r}class gy{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),s=new Uint32Array(4);for(let n=0;n<4;n++)s[n]=t.getUint32(n*4);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,n=s[0],i=s[1],o=s[2],a=s[3],c=this.invSubMix,l=c[0],d=c[1],u=c[2],h=c[3],g=new Uint32Array(256);let m=0,p=0,x=0;for(x=0;x<256;x++)x<128?g[x]=x<<1:g[x]=x<<1^283;for(x=0;x<256;x++){let v=p^p<<1^p<<2^p<<3^p<<4;v=v>>>8^v&255^99,e[m]=v,t[v]=m;const y=g[m],b=g[y],T=g[b];let R=g[v]*257^v*16843008;n[m]=R<<24|R>>>8,i[m]=R<<16|R>>>16,o[m]=R<<8|R>>>24,a[m]=R,R=T*16843009^b*65537^y*257^m*16843008,l[v]=R<<24|R>>>8,d[v]=R<<16|R>>>16,u[v]=R<<8|R>>>24,h[v]=R,m?(m=y^g[g[g[T^y]]],p^=g[g[p]]):m=p=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,n=0;for(;n<t.length&&s;)s=t[n]===this.key[n],n++;if(s)return;this.key=t;const i=this.keySize=t.length;if(i!==4&&i!==6&&i!==8)throw new Error("Invalid aes key size="+i);const o=this.ksRows=(i+6+1)*4;let a,c;const l=this.keySchedule=new Uint32Array(o),d=this.invKeySchedule=new Uint32Array(o),u=this.sBox,h=this.rcon,g=this.invSubMix,m=g[0],p=g[1],x=g[2],v=g[3];let y,b;for(a=0;a<o;a++){if(a<i){y=l[a]=t[a];continue}b=y,a%i===0?(b=b<<8|b>>>24,b=u[b>>>24]<<24|u[b>>>16&255]<<16|u[b>>>8&255]<<8|u[b&255],b^=h[a/i|0]<<24):i>6&&a%i===4&&(b=u[b>>>24]<<24|u[b>>>16&255]<<16|u[b>>>8&255]<<8|u[b&255]),l[a]=y=(l[a-i]^b)>>>0}for(c=0;c<o;c++)a=o-c,c&3?b=l[a]:b=l[a-4],c<4||a<=4?d[c]=b:d[c]=m[u[b>>>24]]^p[u[b>>>16&255]]^x[u[b>>>8&255]]^v[u[b&255]],d[c]=d[c]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){const n=this.keySize+6,i=this.invKeySchedule,o=this.invSBox,a=this.invSubMix,c=a[0],l=a[1],d=a[2],u=a[3],h=this.uint8ArrayToUint32Array_(s);let g=h[0],m=h[1],p=h[2],x=h[3];const v=new Int32Array(e),y=new Int32Array(v.length);let b,T,R,_,w,A,C,L,P,M,j,D,$,N;const F=this.networkToHostOrderSwap;for(;t<v.length;){for(P=F(v[t]),M=F(v[t+1]),j=F(v[t+2]),D=F(v[t+3]),w=P^i[0],A=D^i[1],C=j^i[2],L=M^i[3],$=4,N=1;N<n;N++)b=c[w>>>24]^l[A>>16&255]^d[C>>8&255]^u[L&255]^i[$],T=c[A>>>24]^l[C>>16&255]^d[L>>8&255]^u[w&255]^i[$+1],R=c[C>>>24]^l[L>>16&255]^d[w>>8&255]^u[A&255]^i[$+2],_=c[L>>>24]^l[w>>16&255]^d[A>>8&255]^u[C&255]^i[$+3],w=b,A=T,C=R,L=_,$=$+4;b=o[w>>>24]<<24^o[A>>16&255]<<16^o[C>>8&255]<<8^o[L&255]^i[$],T=o[A>>>24]<<24^o[C>>16&255]<<16^o[L>>8&255]<<8^o[w&255]^i[$+1],R=o[C>>>24]<<24^o[L>>16&255]<<16^o[w>>8&255]<<8^o[A&255]^i[$+2],_=o[L>>>24]<<24^o[w>>16&255]<<16^o[A>>8&255]<<8^o[C&255]^i[$+3],y[t]=F(b^g),y[t+1]=F(_^m),y[t+2]=F(R^p),y[t+3]=F(T^x),g=P,m=M,p=j,x=D,t=t+4}return y.buffer}}class my{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=py(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function py(r){switch(r){case Ts.cbc:return"AES-CBC";case Ts.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${r}`)}}const xy=16;class Jo{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 s=self.crypto;s&&(this.subtle=s.subtle||s.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 s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?hy(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,n){return this.useSoftware?new Promise((i,o)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,s,n);const c=this.flush();c?i(c.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,n)}softwareDecrypt(e,t,s,n){const{currentIV:i,currentResult:o,remainderData:a}=this;if(n!==Ts.cbc||t.byteLength!==16)return ke.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=$t(a,e),this.remainderData=null);const c=this.getValidChunk(e);if(!c.length)return null;i&&(s=i);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new gy),l.expandKey(t);const d=o;return this.currentResult=l.decrypt(c.buffer,0,s),this.currentIV=c.slice(-16).buffer,d||null}webCryptoDecrypt(e,t,s,n){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,n));this.key=t,this.fastAesKey=new my(this.subtle,t,n)}return this.fastAesKey.expandKey().then(i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new fy(this.subtle,new Uint8Array(s),n).decrypt(e.buffer,i)):Promise.reject(new Error("web crypto not initialized"))).catch(i=>(ke.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(e,t,s,n)))}onWebCryptoError(e,t,s,n){const i=this.enableSoftwareAES;if(i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,n);const o=this.flush();if(o)return o.buffer}throw new Error("WebCrypto"+(i?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%xy;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(ke.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const rl=Math.pow(2,17);class vy{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 s=e.url;if(!s)return Promise.reject(new ds({type:ce.NETWORK_ERROR,details:B.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();const n=this.config,i=n.fLoader,o=n.loader;return new Promise((a,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(m=>m[0]==="GAP")){c(il(e));return}else e.gap=!1;const l=this.loader=i?new i(n):new o(n),d=nl(e);e.loader=l;const u=tl(n.fragLoadPolicy.default),h={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:rl};e.stats=l.stats;const g={onSuccess:(m,p,x,v)=>{this.resetLoader(e,l);let y=m.data;x.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(y.slice(0,16)),y=y.slice(16)),a({frag:e,part:null,payload:y,networkDetails:v})},onError:(m,p,x,v)=>{this.resetLoader(e,l),c(new ds({type:ce.NETWORK_ERROR,details:B.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:_e({url:s,data:void 0},m),error:new Error(`HTTP Error ${m.code} ${m.text}`),networkDetails:x,stats:v}))},onAbort:(m,p,x)=>{this.resetLoader(e,l),c(new ds({type:ce.NETWORK_ERROR,details:B.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:x,stats:m}))},onTimeout:(m,p,x)=>{this.resetLoader(e,l),c(new ds({type:ce.NETWORK_ERROR,details:B.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:x,stats:m}))}};t&&(g.onProgress=(m,p,x,v)=>t({frag:e,part:null,payload:x,networkDetails:v})),l.load(d,h,g)})}loadPart(e,t,s){this.abort();const n=this.config,i=n.fLoader,o=n.loader;return new Promise((a,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c(il(e,t));return}const l=this.loader=i?new i(n):new o(n),d=nl(e,t);e.loader=l;const u=tl(n.fragLoadPolicy.default),h={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:rl};t.stats=l.stats,l.load(d,h,{onSuccess:(g,m,p,x)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const v={frag:e,part:t,payload:g.data,networkDetails:x};s(v),a(v)},onError:(g,m,p,x)=>{this.resetLoader(e,l),c(new ds({type:ce.NETWORK_ERROR,details:B.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:_e({url:d.url,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:p,stats:x}))},onAbort:(g,m,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),c(new ds({type:ce.NETWORK_ERROR,details:B.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:g}))},onTimeout:(g,m,p)=>{this.resetLoader(e,l),c(new ds({type:ce.NETWORK_ERROR,details:B.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:p,stats:g}))}})})}updateStatsFromPart(e,t){const s=e.stats,n=t.stats,i=n.total;if(s.loaded+=n.loaded,i){const c=Math.round(e.duration/t.duration),l=Math.min(Math.round(s.loaded/i),c),u=(c-l)*Math.round(s.loaded/l);s.total=s.loaded+u}else s.total=Math.max(s.loaded,s.total);const o=s.loading,a=n.loading;o.start?o.first+=a.first-a.start:(o.start=a.start,o.first=a.first),o.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function nl(r,e=null){const t=e||r,s={frag:r,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},n=t.byteRangeStartOffset,i=t.byteRangeEndOffset;if(ne(n)&&ne(i)){var o;let a=n,c=i;if(r.sn==="initSegment"&&yy((o=r.decryptdata)==null?void 0:o.method)){const l=i-n;l%16&&(c=i+(16-l%16)),n!==0&&(s.resetIV=!0,a=n-16)}s.rangeStart=a,s.rangeEnd=c}return s}function il(r,e){const t=new Error(`GAP ${r.gap?"tag":"attribute"} found`),s={type:ce.MEDIA_ERROR,details:B.FRAG_GAP,fatal:!1,frag:r,error:t,networkDetails:null};return e&&(s.part=e),(e||r).stats.aborted=!0,new ds(s)}function yy(r){return r==="AES-128"||r==="AES-256"}class ds extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Nf extends Ut{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(){}}class ea{constructor(e,t,s,n=0,i=-1,o=!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=Zr(),this.buffering={audio:Zr(),video:Zr(),audiovideo:Zr()},this.level=e,this.sn=t,this.id=s,this.size=n,this.part=i,this.partial=o}}function Zr(){return{start:0,executeStart:0,executeEnd:0,end:0}}const ol={length:0,start:()=>0,end:()=>0};class ve{static isBuffered(e,t){if(e){const s=ve.getBuffered(e);for(let n=s.length;n--;)if(t>=s.start(n)&&t<=s.end(n))return!0}return!1}static bufferedRanges(e){if(e){const t=ve.getBuffered(e);return ve.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){const n=ve.bufferedRanges(e);if(n.length)return ve.bufferedInfo(n,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((d,u)=>d.start-u.start||u.end-d.end);let n=-1,i=[];if(s)for(let d=0;d<e.length;d++){t>=e[d].start&&t<=e[d].end&&(n=d);const u=i.length;if(u){const h=i[u-1].end;e[d].start-h<s?e[d].end>h&&(i[u-1].end=e[d].end):i.push(e[d])}else i.push(e[d])}else i=e;let o=0,a,c=t,l=t;for(let d=0;d<i.length;d++){const u=i[d].start,h=i[d].end;if(n===-1&&t>=u&&t<=h&&(n=d),t+s>=u&&t<h)c=u,l=h,o=l-t;else if(t+s<u){a=u;break}}return{len:o,start:c||0,end:l||0,nextStart:a,buffered:e,bufferedIndex:n}}static getBuffered(e){try{return e.buffered||ol}catch(t){return ke.log("failed to get media.buffered",t),ol}}}const Mf=/\{\$([a-zA-Z0-9-_]+)\}/g;function al(r){return Mf.test(r)}function Yi(r,e){if(r.variableList!==null||r.hasVariableRefs){const t=r.variableList;return e.replace(Mf,s=>{const n=s.substring(2,s.length-1),i=t==null?void 0:t[n];return i===void 0?(r.playlistParsingError||(r.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${n}"`)),s):i})}return e}function ll(r,e,t){let s=r.variableList;s||(r.variableList=s={});let n,i;if("QUERYPARAM"in e){n=e.QUERYPARAM;try{const o=new self.URL(t).searchParams;if(o.has(n))i=o.get(n);else throw new Error(`"${n}" does not match any query parameter in URI: "${t}"`)}catch(o){r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${o.message}`))}}else n=e.NAME,i=e.VALUE;n in s?r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${n}"`)):s[n]=i||""}function by(r,e,t){const s=e.IMPORT;if(t&&s in t){let n=r.variableList;n||(r.variableList=n={}),n[s]=t[s]}else r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const Sy=/^(\d+)x(\d+)$/,cl=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Ve{constructor(e,t){typeof e=="string"&&(e=Ve.parseAttrList(e,t)),De(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const s=new Uint8Array(t.length/2);for(let n=0;n<t.length/2;n++)s[n]=parseInt(t.slice(n*2,n*2+2),16);return s}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((n,i)=>(n[i.toLowerCase()]=!0,n),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=Sy.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const n={},i='"';for(cl.lastIndex=0;(s=cl.exec(e))!==null;){const o=s[1].trim();let a=s[2];const c=a.indexOf(i)===0&&a.lastIndexOf(i)===a.length-1;let l=!1;if(c)a=a.slice(1,-1);else switch(o){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(t&&(c||l))a=Yi(t,a);else if(!l&&!c)switch(o){case"CLOSED-CAPTIONS":if(a==="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(`${e}: attribute ${o} is missing quotes`)}n[o]=a}return n}}const Ey="com.apple.hls.interstitial";function Ty(r){return r!=="ID"&&r!=="CLASS"&&r!=="CUE"&&r!=="START-DATE"&&r!=="DURATION"&&r!=="END-DATE"&&r!=="END-ON-NEXT"}function wy(r){return r==="SCTE35-OUT"||r==="SCTE35-IN"||r==="SCTE35-CMD"}class Ff{constructor(e,t,s=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==null?void 0:t.tagAnchor)||null,this.tagOrder=(n=t==null?void 0:t.tagOrder)!=null?n:s,t){const i=t.attr;for(const o in i)if(Object.prototype.hasOwnProperty.call(e,o)&&e[o]!==i[o]){ke.warn(`DATERANGE tag attribute: "${o}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=o;break}e=De(new Ve({}),i,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 i=(t==null?void 0:t.endDate)||new Date(this.attr["END-DATE"]);ne(i.getTime())&&(this._endDate=i)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(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(ne(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===Ey}get isValid(){return!!this.id&&!this._badValueForSameId&&ne(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const Ry=10;class Ay{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,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>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 s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return this.fragments.length?ne(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Ry}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 s=e.length;s--;)if(e[s].index>t)return e[s].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 _n(r,e){return r.length===e.length?!r.some((t,s)=>t!==e[s]):!1}function dl(r,e){return!r&&!e?!0:!r||!e?!1:_n(r,e)}function Js(r){return r==="AES-128"||r==="AES-256"||r==="AES-256-CTR"}function ta(r){switch(r){case"AES-128":case"AES-256":return Ts.cbc;case"AES-256-CTR":return Ts.ctr;default:throw new Error(`invalid full segment method ${r}`)}}function sa(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}function qi(r){return Uint8Array.from(unescape(encodeURIComponent(r)),e=>e.charCodeAt(0))}function Iy(r){const e=qi(r).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Of(r){const e=function(s,n,i){const o=s[n];s[n]=s[i],s[i]=o};e(r,0,3),e(r,1,2),e(r,4,5),e(r,6,7)}function jf(r){const e=r.split(":");let t=null;if(e[0]==="data"&&e.length===2){const s=e[1].split(";"),n=s[s.length-1].split(",");if(n.length===2){const i=n[0]==="base64",o=n[1];i?(s.splice(-1,1),t=sa(o)):t=Iy(o)}}return t}const kn=typeof self<"u"?self:void 0;var He={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},dt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function gn(r){switch(r){case dt.FAIRPLAY:return He.FAIRPLAY;case dt.PLAYREADY:return He.PLAYREADY;case dt.WIDEVINE:return He.WIDEVINE;case dt.CLEARKEY:return He.CLEARKEY}}function di(r){switch(r){case He.FAIRPLAY:return dt.FAIRPLAY;case He.PLAYREADY:return dt.PLAYREADY;case He.WIDEVINE:return dt.WIDEVINE;case He.CLEARKEY:return dt.CLEARKEY}}function pr(r){const{drmSystems:e,widevineLicenseUrl:t}=r,s=e?[He.FAIRPLAY,He.WIDEVINE,He.PLAYREADY,He.CLEARKEY].filter(n=>!!e[n]):[];return!s[He.WIDEVINE]&&t&&s.push(He.WIDEVINE),s}const Bf=function(r){return kn!=null&&(r=kn.navigator)!=null&&r.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function Ly(r,e,t,s){let n;switch(r){case He.FAIRPLAY:n=["cenc","sinf"];break;case He.WIDEVINE:case He.PLAYREADY:n=["cenc"];break;case He.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${r}`)}return Cy(n,e,t,s)}function Cy(r,e,t,s){return[{initDataTypes:r,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(i=>({contentType:`audio/mp4; codecs=${i}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(i=>({contentType:`video/mp4; codecs=${i}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function _y(r){var e;return!!r&&(r.sessionType==="persistent-license"||!!((e=r.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function $f(r){const e=new Uint16Array(r.buffer,r.byteOffset,r.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),s=t.substring(t.indexOf("<"),t.length),o=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(o){const a=o.childNodes[0]?o.childNodes[0].nodeValue:o.getAttribute("VALUE");if(a){const c=sa(a).subarray(0,16);return Of(c),c}}return null}let Ws={};class bs{static clearKeyUriToKeyIdMap(){Ws={}}static setKeyIdForUri(e,t){Ws[e]=t}static addKeyIdForUri(e){const t=Object.keys(Ws).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),Ws[e]=s,s}constructor(e,t,s,n=[1],i=null,o){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=n,this.iv=i,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Js(e),o!=null&&o.startsWith("0x")&&(this.keyId=new Uint8Array(gf(o)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&_n(e.keyFormatVersions,this.keyFormatVersions)&&dl(e.iv,this.iv)&&dl(e.keyId,this.keyId)}isSupported(){if(this.method){if(Js(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case dt.FAIRPLAY:case dt.WIDEVINE:case dt.PLAYREADY:case dt.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(Js(this.method)){let i=this.iv;return i||(typeof e!="number"&&(ke.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),i=Dy(e)),new bs(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.keyId){const i=Ws[this.uri];if(i&&!_n(this.keyId,i)&&bs.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=jf(this.uri);if(s)switch(this.keyFormat){case dt.WIDEVINE:if(this.pssh=s,!this.keyId){const i=Mv(s.buffer);if(i.length){var n;const o=i[0];this.keyId=(n=o.kids)!=null&&n.length?o.kids[0]:null}}this.keyId||(this.keyId=ul(t));break;case dt.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Nv(i,null,s),this.keyId=$f(s);break}default:{let i=s.subarray(0,16);if(i.length!==16){const o=new Uint8Array(16);o.set(i,16-i.length),i=o}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i;i=ky(t),i||(i=ul(t),i||(i=Ws[this.uri])),i&&(this.keyId=i,bs.setKeyIdForUri(this.uri,i))}return this}}function ky(r){const e=r==null?void 0:r[dt.WIDEVINE];return e?e.keyId:null}function ul(r){const e=r==null?void 0:r[dt.PLAYREADY];if(e){const t=jf(e.uri);if(t)return $f(t)}return null}function Dy(r){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=r>>8*(15-t)&255;return e}const fl=/#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,hl=/#EXT-X-MEDIA:(.*)/g,Py=/^#EXT(?:INF|-X-TARGETDURATION):/m,ui=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Ny=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class ts{static findGroup(e,t){for(let s=0;s<e.length;s++){const n=e[s];if(n.id===t)return n}}static resolve(e,t){return Wo.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Py.test(e)}static parseMasterPlaylist(e,t){const s=al(e),n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},i=[];if(fl.lastIndex=0,!e.startsWith("#EXTM3U"))return n.playlistParsingError=new Error("no EXTM3U delimiter"),n;let o;for(;(o=fl.exec(e))!=null;)if(o[1]){var a;const l=new Ve(o[1],n),d=Yi(n,o[2]),u={attrs:l,bitrate:l.decimalInteger("BANDWIDTH")||l.decimalInteger("AVERAGE-BANDWIDTH"),name:l.NAME,url:ts.resolve(d,t)},h=l.decimalResolution("RESOLUTION");h&&(u.width=h.width,u.height=h.height),pl(l.CODECS,u);const g=l["SUPPLEMENTAL-CODECS"];g&&(u.supplemental={},pl(g,u.supplemental)),(a=u.unknownCodecs)!=null&&a.length||i.push(u),n.levels.push(u)}else if(o[3]){const l=o[3],d=o[4];switch(l){case"SESSION-DATA":{const u=new Ve(d,n),h=u["DATA-ID"];h&&(n.sessionData===null&&(n.sessionData={}),n.sessionData[h]=u);break}case"SESSION-KEY":{const u=gl(d,t,n);u.encrypted&&u.isSupported()?(n.sessionKeys===null&&(n.sessionKeys=[]),n.sessionKeys.push(u)):ke.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${d}"`);break}case"DEFINE":{{const u=new Ve(d,n);ll(n,u,t)}break}case"CONTENT-STEERING":{const u=new Ve(d,n);n.contentSteering={uri:ts.resolve(u["SERVER-URI"],t),pathwayId:u["PATHWAY-ID"]||"."};break}case"START":{n.startTimeOffset=ml(d);break}}}const c=i.length>0&&i.length<n.levels.length;return n.levels=c?i:n.levels,n.levels.length===0&&(n.playlistParsingError=new Error("no levels found in manifest")),n}static parseMasterPlaylistMedia(e,t,s){let n;const i={},o=s.levels,a={AUDIO:o.map(l=>({id:l.attrs.AUDIO,audioCodec:l.audioCodec})),SUBTITLES:o.map(l=>({id:l.attrs.SUBTITLES,textCodec:l.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(hl.lastIndex=0;(n=hl.exec(e))!==null;){const l=new Ve(n[1],s),d=l.TYPE;if(d){const u=a[d],h=i[d]||[];i[d]=h;const g=l.LANGUAGE,m=l["ASSOC-LANGUAGE"],p=l.CHANNELS,x=l.CHARACTERISTICS,v=l["INSTREAM-ID"],y={attrs:l,bitrate:0,id:c++,groupId:l["GROUP-ID"]||"",name:l.NAME||g||"",type:d,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:g,url:l.URI?ts.resolve(l.URI,t):""};if(m&&(y.assocLang=m),p&&(y.channels=p),x&&(y.characteristics=x),v&&(y.instreamId=v),u!=null&&u.length){const b=ts.findGroup(u,y.groupId)||u[0];xl(y,b,"audioCodec"),xl(y,b,"textCodec")}h.push(y)}}return i}static parseLevelPlaylist(e,t,s,n,i,o){var a;const c={url:t},l=new Ay(t),d=l.fragments,u=[];let h=null,g=0,m=0,p=0,x=0,v=0,y=null,b=new ai(n,c),T,R,_,w=-1,A=!1,C=null,L;if(ui.lastIndex=0,l.m3u8=e,l.hasVariableRefs=al(e),((a=ui.exec(e))==null?void 0:a[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(T=ui.exec(e))!==null;){A&&(A=!1,b=new ai(n,c),b.playlistOffset=p,b.setStart(p),b.sn=g,b.cc=x,v&&(b.bitrate=v),b.level=s,h&&(b.initSegment=h,h.rawProgramDateTime&&(b.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null),C&&(b.setByteRange(C),C=null)));const D=T[1];if(D){b.duration=parseFloat(D);const $=(" "+T[2]).slice(1);b.title=$||null,b.tagList.push($?["INF",D,$]:["INF",D])}else if(T[3]){if(ne(b.duration)){b.playlistOffset=p,b.setStart(p),_&&yl(b,_,l),b.sn=g,b.level=s,b.cc=x,d.push(b);const $=(" "+T[3]).slice(1);b.relurl=Yi(l,$),Xi(b,y,u),y=b,p+=b.duration,g++,m=0,A=!0}}else{if(T=T[0].match(Ny),!T){ke.warn("No matches on slow regex match for level playlist!");continue}for(R=1;R<T.length&&T[R]===void 0;R++);const $=(" "+T[R]).slice(1),N=(" "+T[R+1]).slice(1),F=T[R+2]?(" "+T[R+2]).slice(1):null;switch($){case"BYTERANGE":y?b.setByteRange(N,y):b.setByteRange(N);break;case"PROGRAM-DATE-TIME":b.rawProgramDateTime=N,b.tagList.push(["PROGRAM-DATE-TIME",N]),w===-1&&(w=d.length);break;case"PLAYLIST-TYPE":l.type&&as(l,$,T),l.type=N.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?as(l,$,T):d.length>0&&bl(l,$,T),g=l.startSN=parseInt(N);break;case"SKIP":{l.skippedSegments&&as(l,$,T);const k=new Ve(N,l),z=k.decimalInteger("SKIPPED-SEGMENTS");if(ne(z)){l.skippedSegments+=z;for(let U=z;U--;)d.push(null);g+=z}const Y=k.enumeratedString("RECENTLY-REMOVED-DATERANGES");Y&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(Y.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&&as(l,$,T),l.targetduration=Math.max(parseInt(N),1);break;case"VERSION":l.version!==null&&as(l,$,T),l.version=parseInt(N);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||as(l,$,T),l.live=!1;break;case"#":(N||F)&&b.tagList.push(F?[N,F]:[N]);break;case"DISCONTINUITY":x++,b.tagList.push(["DIS"]);break;case"GAP":b.gap=!0,b.tagList.push([$]);break;case"BITRATE":b.tagList.push([$,N]),v=parseInt(N)*1e3,ne(v)?b.bitrate=v:v=0;break;case"DATERANGE":{const k=new Ve(N,l),z=new Ff(k,l.dateRanges[k.ID],l.dateRangeTagCount);l.dateRangeTagCount++,z.isValid||l.skippedSegments?l.dateRanges[z.id]=z:ke.warn(`Ignoring invalid DATERANGE tag: "${N}"`),b.tagList.push(["EXT-X-DATERANGE",N]);break}case"DEFINE":{{const k=new Ve(N,l);"IMPORT"in k?by(l,k,o):ll(l,k,t)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0?as(l,$,T):d.length>0&&bl(l,$,T),l.startCC=x=parseInt(N);break;case"KEY":{const k=gl(N,t,l);if(k.isSupported()){if(k.method==="NONE"){_=void 0;break}_||(_={});const z=_[k.keyFormat];z!=null&&z.matches(k)||(z&&(_=De({},_)),_[k.keyFormat]=k)}else ke.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${N}"`);break}case"START":l.startTimeOffset=ml(N);break;case"MAP":{const k=new Ve(N,l);if(b.duration){const z=new ai(n,c);vl(z,k,s,_),h=z,b.initSegment=h,h.rawProgramDateTime&&!b.rawProgramDateTime&&(b.rawProgramDateTime=h.rawProgramDateTime)}else{const z=b.byteRangeEndOffset;if(z){const Y=b.byteRangeStartOffset;C=`${z-Y}@${Y}`}else C=null;vl(b,k,s,_),h=b,A=!0}h.cc=x;break}case"SERVER-CONTROL":{L&&as(l,$,T),L=new Ve(N),l.canBlockReload=L.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=L.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&L.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=L.optionalFloat("PART-HOLD-BACK",0),l.holdBack=L.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&as(l,$,T);const k=new Ve(N);l.partTarget=k.decimalFloatingPoint("PART-TARGET");break}case"PART":{let k=l.partList;k||(k=l.partList=[]);const z=m>0?k[k.length-1]:void 0,Y=m++,U=new Ve(N,l),K=new bv(U,b,c,Y,z);k.push(K),b.duration+=K.duration;break}case"PRELOAD-HINT":{const k=new Ve(N,l);l.preloadHint=k;break}case"RENDITION-REPORT":{const k=new Ve(N,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(k);break}default:ke.warn(`line parsed but not handled: ${T}`);break}}}y&&!y.relurl?(d.pop(),p-=y.duration,l.partList&&(l.fragmentHint=y)):l.partList&&(Xi(b,y,u),b.cc=x,l.fragmentHint=b,_&&yl(b,_,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const P=d.length,M=d[0],j=d[P-1];if(p+=l.skippedSegments*l.targetduration,p>0&&P&&j){l.averagetargetduration=p/P;const D=j.sn;l.endSN=D!=="initSegment"?D:0,l.live||(j.endList=!0),w>0&&(Fy(d,w),M&&u.unshift(M))}return l.fragmentHint&&(p+=l.fragmentHint.duration),l.totalduration=p,u.length&&l.dateRangeTagCount&&M&&Uf(u,l),l.endCC=x,l}}function Uf(r,e){let t=r.length;if(!t)if(e.hasProgramDateTime){const a=e.fragments[e.fragments.length-1];r.push(a),t++}else return;const s=r[t-1],n=e.live?1/0:e.totalduration,i=Object.keys(e.dateRanges);for(let a=i.length;a--;){const c=e.dateRanges[i[a]],l=c.startDate.getTime();c.tagAnchor=s.ref;for(let d=t;d--;){var o;if(((o=r[d])==null?void 0:o.sn)<e.startSN)break;const u=My(e,l,r,d,n);if(u!==-1){c.tagAnchor=e.fragments[u].ref;break}}}}function My(r,e,t,s,n){const i=t[s];if(i){const a=i.programDateTime;if(e>=a||s===0){var o;const c=(((o=t[s+1])==null?void 0:o.start)||n)-i.start;if(e<=a+c*1e3){const l=t[s].sn-r.startSN;if(l<0)return-1;const d=r.fragments;if(d.length>t.length){const h=(t[s+1]||d[d.length-1]).sn-r.startSN;for(let g=h;g>l;g--){const m=d[g].programDateTime;if(e>=m&&e<m+d[g].duration*1e3)return g}}return l}}}return-1}function gl(r,e,t){var s,n;const i=new Ve(r,t),o=(s=i.METHOD)!=null?s:"",a=i.URI,c=i.hexadecimalInteger("IV"),l=i.KEYFORMATVERSIONS,d=(n=i.KEYFORMAT)!=null?n:"identity";a&&i.IV&&!c&&ke.error(`Invalid IV: ${i.IV}`);const u=a?ts.resolve(a,e):"",h=(l||"1").split("/").map(Number).filter(Number.isFinite);return new bs(o,u,d,h,c,i.KEYID)}function ml(r){const t=new Ve(r).decimalFloatingPoint("TIME-OFFSET");return ne(t)?t:null}function pl(r,e){let t=(r||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const n=t.filter(i=>Xo(i,s));n.length&&(e[`${s}Codec`]=n.map(i=>i.split("/")[0]).join(","),t=t.filter(i=>n.indexOf(i)===-1))}),e.unknownCodecs=t}function xl(r,e,t){const s=e[t];s&&(r[t]=s)}function Fy(r,e){let t=r[e];for(let s=e;s--;){const n=r[s];if(!n)return;n.programDateTime=t.programDateTime-n.duration*1e3,t=n}}function Xi(r,e,t){r.rawProgramDateTime?t.push(r):e!=null&&e.programDateTime&&(r.programDateTime=e.endProgramDateTime)}function vl(r,e,t,s){r.relurl=e.URI,e.BYTERANGE&&r.setByteRange(e.BYTERANGE),r.level=t,r.sn="initSegment",s&&(r.levelkeys=s),r.initSegment=null}function yl(r,e,t){r.levelkeys=e;const{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(n=>e[n].isCommonEncryption)&&s.push(r)}function as(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function bl(r,e,t){r.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function fi(r,e){const t=e.startPTS;if(ne(t)){let s=0,n;e.sn>r.sn?(s=t-r.start,n=r):(s=r.start-t,n=e),n.duration!==s&&n.setDuration(s)}else e.sn>r.sn?r.cc===e.cc&&r.minEndPTS?e.setStart(r.start+(r.minEndPTS-r.start)):e.setStart(r.start+r.duration):e.setStart(Math.max(r.start-e.duration,0))}function Gf(r,e,t,s,n,i,o){s-t<=0&&(o.warn("Fragment should have a positive duration",e),s=t+e.duration,i=n+e.duration);let c=t,l=s;const d=e.startPTS,u=e.endPTS;if(ne(d)){const v=Math.abs(d-t);r&&v>r.totalduration?o.warn(`media timestamps and playlist times differ by ${v}s for level ${e.level} ${r.url}`):ne(e.deltaPTS)?e.deltaPTS=Math.max(v,e.deltaPTS):e.deltaPTS=v,c=Math.max(t,d),t=Math.min(t,d),n=e.startDTS!==void 0?Math.min(n,e.startDTS):n,l=Math.min(s,u),s=Math.max(s,u),i=e.endDTS!==void 0?Math.max(i,e.endDTS):i}const h=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=c,e.startDTS=n,e.endPTS=s,e.minEndPTS=l,e.endDTS=i;const g=e.sn;if(!r||g<r.startSN||g>r.endSN)return 0;let m;const p=g-r.startSN,x=r.fragments;for(x[p]=e,m=p;m>0;m--)fi(x[m],x[m-1]);for(m=p;m<x.length-1;m++)fi(x[m],x[m+1]);return r.fragmentHint&&fi(x[x.length-1],r.fragmentHint),r.PTSKnown=r.alignedSliding=!0,h}function Oy(r,e,t){if(r===e)return;let s=null;const n=r.fragments;for(let d=n.length-1;d>=0;d--){const u=n[d].initSegment;if(u){s=u;break}}r.fragmentHint&&delete r.fragmentHint.endPTS;let i;$y(r,e,(d,u,h,g)=>{if((!e.startCC||e.skippedSegments)&&u.cc!==d.cc){const m=d.cc-u.cc;for(let p=h;p<g.length;p++)g[p].cc+=m;e.endCC=g[g.length-1].cc}ne(d.startPTS)&&ne(d.endPTS)&&(u.setStart(u.startPTS=d.startPTS),u.startDTS=d.startDTS,u.maxStartPTS=d.maxStartPTS,u.endPTS=d.endPTS,u.endDTS=d.endDTS,u.minEndPTS=d.minEndPTS,u.setDuration(d.endPTS-d.startPTS),u.duration&&(i=u),e.PTSKnown=e.alignedSliding=!0),d.hasStreams&&(u.elementaryStreams=d.elementaryStreams),u.loader=d.loader,d.hasStats&&(u.stats=d.stats),d.initSegment&&(u.initSegment=d.initSegment,s=d.initSegment)});const o=e.fragments,a=e.fragmentHint?o.concat(e.fragmentHint):o;if(s&&a.forEach(d=>{var u;d&&(!d.initSegment||d.initSegment.relurl===((u=s)==null?void 0:u.relurl))&&(d.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=o.some(d=>!d),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let d=e.skippedSegments;d--;)o.shift();e.startSN=o[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=jy(r.dateRanges,e,t));const d=r.fragments.filter(u=>u.rawProgramDateTime);if(r.hasProgramDateTime&&!e.hasProgramDateTime)for(let u=1;u<a.length;u++)a[u].programDateTime===null&&Xi(a[u],a[u-1],d);Uf(d,e)}e.endCC=o[o.length-1].cc}if(!e.startCC){var c;const d=Kf(r,e.startSN-1);e.startCC=(c=d==null?void 0:d.cc)!=null?c:o[0].cc}By(r.partList,e.partList,(d,u)=>{u.elementaryStreams=d.elementaryStreams,u.stats=d.stats}),i?Gf(e,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,t):Vf(r,e),o.length&&(e.totalduration=e.edge-o[0].start),e.driftStartTime=r.driftStartTime,e.driftStart=r.driftStart;const l=e.advancedDateTime;if(e.advanced&&l){const d=e.edge;e.driftStart||(e.driftStartTime=l,e.driftStart=d),e.driftEndTime=l,e.driftEnd=d}else e.driftEndTime=r.driftEndTime,e.driftEnd=r.driftEnd,e.advancedDateTime=r.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=r.requestScheduled)}function jy(r,e,t){const{dateRanges:s,recentlyRemovedDateranges:n}=e,i=De({},r);n&&n.forEach(c=>{delete i[c]});const a=Object.keys(i).length;return a?(Object.keys(s).forEach(c=>{const l=i[c],d=new Ff(s[c].attr,l);d.isValid?(i[c]=d,l||(d.tagOrder+=a)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Ne(s[c].attr)}"`)}),i):s}function By(r,e,t){if(r&&e){let s=0;for(let n=0,i=r.length;n<=i;n++){const o=r[n],a=e[n+s];o&&a&&o.index===a.index&&o.fragment.sn===a.fragment.sn?t(o,a):s--}}}function $y(r,e,t){const s=e.skippedSegments,n=Math.max(r.startSN,e.startSN)-e.startSN,i=(r.fragmentHint?1:0)+(s?e.endSN:Math.min(r.endSN,e.endSN))-e.startSN,o=e.startSN-r.startSN,a=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,c=r.fragmentHint?r.fragments.concat(r.fragmentHint):r.fragments;for(let l=n;l<=i;l++){const d=c[o+l];let u=a[l];if(s&&!u&&d&&(u=e.fragments[l]=d),d&&u){t(d,u,l,a);const h=d.relurl,g=u.relurl;if(h&&Uy(h,g)){e.playlistParsingError=Sl(`media sequence mismatch ${u.sn}:`,r,e,d,u);return}else if(d.cc!==u.cc){e.playlistParsingError=Sl(`discontinuity sequence mismatch (${d.cc}!=${u.cc})`,r,e,d,u);return}}}}function Sl(r,e,t,s,n){return new Error(`${r} ${n.url}
46
+ Playlist starting @${e.startSN}
47
+ ${e.m3u8}
48
+
49
+ Playlist starting @${t.startSN}
50
+ ${t.m3u8}`)}function Vf(r,e,t=!0){const s=e.startSN+e.skippedSegments-r.startSN,n=r.fragments,i=s>=0;let o=0;if(i&&s<n.length)o=n[s].start;else if(i&&e.startSN===r.endSN+1)o=r.fragmentEnd;else if(i&&t)o=r.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)o=r.fragmentStart;else return;Qi(e,o)}function Qi(r,e){if(e){const t=r.fragments;for(let s=r.skippedSegments;s<t.length;s++)t[s].addStart(e);r.fragmentHint&&r.fragmentHint.addStart(e)}}function Hf(r,e=1/0){let t=1e3*r.targetduration;if(r.updated){const s=r.fragments;if(s.length&&t*4>e){const i=s[s.length-1].duration*1e3;i<t&&(t=i)}}else t/=2;return Math.round(t)}function Kf(r,e,t){if(!r)return null;let s=r.fragments[e-r.startSN];return s||(s=r.fragmentHint,s&&s.sn===e)?s:e<r.startSN&&t&&t.sn===e?t:null}function El(r,e,t){return r?zf(r.partList,e,t):null}function zf(r,e,t){if(r)for(let s=r.length;s--;){const n=r[s];if(n.index===t&&n.fragment.sn===e)return n}return null}function Wf(r){r.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(n=>{n.level=t,n.initSegment&&(n.initSegment.level=t)})})}function Uy(r,e){return r!==e&&e?Tl(r)!==Tl(e):!1}function Tl(r){return r.replace(/\?[^?]*$/,"")}function Sr(r,e){for(let s=0,n=r.length;s<n;s++){var t;if(((t=r[s])==null?void 0:t.cc)===e)return r[s]}return null}function Gy(r,e){return!!(r&&e.startCC<r.endCC&&e.endCC>r.startCC)}function wl(r,e){const t=r.start+e;r.startPTS=t,r.setStart(t),r.endPTS=t+r.duration}function Yf(r,e){const t=e.fragments;for(let s=0,n=t.length;s<n;s++)wl(t[s],r);e.fragmentHint&&wl(e.fragmentHint,r),e.alignedSliding=!0}function Vy(r,e){r&&(qf(e,r),e.alignedSliding||Dn(e,r),!e.alignedSliding&&!e.skippedSegments&&Vf(r,e,!1))}function qf(r,e){if(!Gy(e,r))return;const t=Math.min(e.endCC,r.endCC),s=Sr(e.fragments,t),n=Sr(r.fragments,t);if(!s||!n)return;ke.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const i=s.start-n.start;Yf(i,r)}function Dn(r,e){if(!r.hasProgramDateTime||!e.hasProgramDateTime)return;const t=r.fragments,s=e.fragments;if(!t.length||!s.length)return;let n,i;const o=Math.min(e.endCC,r.endCC);e.startCC<o&&r.startCC<o&&(n=Sr(s,o),i=Sr(t,o)),(!n||!i)&&(n=s[Math.floor(s.length/2)],i=Sr(t,n.cc)||t[Math.floor(t.length/2)]);const a=n.programDateTime,c=i.programDateTime;if(!a||!c)return;const l=(c-a)/1e3-(i.start-n.start);Yf(l,r)}function ht(r,e,t){yt(r,e,t),r.addEventListener(e,t)}function yt(r,e,t){r.removeEventListener(e,t)}const Hy={toString:function(r){let e="";const t=r.length;for(let s=0;s<t;s++)e+=`[${r.start(s).toFixed(3)}-${r.end(s).toFixed(3)}]`;return e}},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"};class ra extends Nf{constructor(e,t,s,n,i){super(n,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=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:o,fragCurrent:a,media:c,mediaBuffer:l,state:d}=this,u=c?c.currentTime:0,h=ve.bufferInfo(l||c,u,o.maxBufferHole),g=!h.len;if(this.log(`Media seeking to ${ne(u)?u.toFixed(3):u}, state: ${d}, ${g?"out of":"in"} buffer`),this.state===X.ENDED)this.resetLoadingState();else if(a){const m=o.maxFragLookUpTolerance,p=a.start-m,x=a.start+a.duration+m;if(g||x<h.start||p>h.end){const v=u>x;(u<p||v)&&(v&&a.loader&&(this.log(`Cancelling fragment load for seek (sn: ${a.sn})`),a.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(c){this.fragmentTracker.removeFragmentsInRange(u,1/0,this.playlistType,!0);const m=this.lastCurrentTime;if(u>m&&(this.lastCurrentTime=u),!this.loadingParts){const p=Math.max(h.end,u),x=this.shouldLoadParts(this.getLevelDetails(),p);x&&(this.log(`LL-Part loading ON after seeking to ${u.toFixed(2)} with buffer @${p.toFixed(2)}`),this.loadingParts=x)}}this.hls.hasEnoughToStart||(this.log(`Setting ${g?"startPosition":"nextLoadPosition"} to ${u} for seek without enough to start`),this.nextLoadPosition=u,g&&(this.startPosition=u)),g&&this.state===X.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=i,this.hls=e,this.fragmentLoader=new vy(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Jo(e.config)}registerListeners(){const{hls:e}=this;e.on(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(S.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(S.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 s=e.end||0,n=this.config.timelineOffset||0;if(s<=n)return!1;const i=e.buffered;this.config.maxBufferHole&&i&&i.length>1&&(e=ve.bufferedInfo(i,e.start,0));const o=e.nextStart;if(o&&o>n&&o<t.edge||this.media.currentTime<e.start)return!1;const c=t.partList;if(c!=null&&c.length){const d=c[c.length-1];return ve.isBuffered(this.media,d.start+d.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 s=this.media=this.mediaBuffer=t.media;ht(s,"seeking",this.onMediaSeeking),ht(s,"ended",this.onMediaEnded);const n=this.config;this.levels&&n.autoStartLoad&&this.state===X.STOPPED&&this.startLoad(n.startPosition)}onMediaDetaching(e,t){const s=!!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),yt(n,"seeking",this.onMediaSeeking),yt(n,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){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,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){const n=i=>{const o=i.frag;if(this.fragContextChanged(o)){this.warn(`${o.type} sn: ${o.sn}${i.part?" part: "+i.part.index:""} of ${this.fragInfo(o,!1,i.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(o);return}o.stats.chunkCount++,this._handleFragmentLoadProgress(i)};this._doFragLoad(e,t,s,n).then(i=>{if(!i)return;const o=this.state,a=i.frag;if(this.fragContextChanged(a)){(o===X.FRAG_LOADING||!this.fragCurrent&&o===X.PARSING)&&(this.fragmentTracker.removeFragment(a),this.state=X.IDLE);return}"payload"in i&&(this.log(`Loaded ${a.type} sn: ${a.sn} of ${this.playlistLabel()} ${a.level}`),this.hls.trigger(S.FRAG_LOADED,i)),this._handleFragmentLoadComplete(i)}).catch(i=>{this.state===X.STOPPED||this.state===X.ERROR||(this.warn(`Frag error: ${(i==null?void 0:i.message)||i}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===rt.APPENDING){const i=e.type,o=this.getFwdBufferInfo(this.mediaBuffer,i),a=Math.max(e.duration,o?o.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?e.sn-c.sn:0)===1||this.reduceMaxBufferLength(a,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===rt.PARTIAL&&s.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==null?void 0:t.live)&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:s};this.hls.trigger(S.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{const n=s==null?void 0:s.frag;if(!n||this.fragContextChanged(n)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{const{hls:n}=this,{frag:i,payload:o}=s,a=i.decryptdata;if(o&&o.byteLength>0&&a!=null&&a.key&&a.iv&&Js(a.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(o),a.key.buffer,a.iv.buffer,ta(a.method)).catch(l=>{throw n.trigger(S.ERROR,{type:ce.MEDIA_ERROR,details:B.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:i}),l}).then(l=>{const d=self.performance.now();return n.trigger(S.FRAG_DECRYPTED,{frag:i,payload:l,stats:{tstart:c,tdecrypt:d}}),s.payload=l,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===X.STOPPED||this.state===X.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state!==X.STOPPED&&(this.state=X.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,n;const i=e.tracks;if(i&&!t.encrypted&&((s=i.audio)!=null&&s.encrypted||(n=i.video)!=null&&n.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const o=this.media,a=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${o?"attached mediaKeys: "+o.mediaKeys:"detached"})`);return this.warn(a.message),!o||o.mediaKeys?!1:(this.hls.trigger(S.ERROR,{type:ce.KEY_SYSTEM_ERROR,details:B.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 s=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:${s?Hy.toString(ve.getBuffered(s)):"(detached)"})`),qe(e)){var n;if(e.type!==oe.SUBTITLE){const o=e.elementaryStreams;if(!Object.keys(o).some(a=>!!o[a])){this.state=X.IDLE;return}}const i=(n=this.levels)==null?void 0:n[e.level];i!=null&&i.fragmentError&&(this.log(`Resetting level fragment error count of ${i.fragmentError} on frag buffered`),i.fragmentError=0)}this.state=X.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:n,partsLoaded:i}=e,o=!i||i.length===0||i.some(c=>!c),a=new ea(s.level,s.sn,s.stats.chunkCount+1,0,n?n.index:-1,!o);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,n){var i;this.fragCurrent=e;const o=t.details;if(!this.levels||!o)throw new Error(`frag load aborted, missing level${o?"":" detail"}s`);let a=null;if(e.encrypted&&!((i=e.decryptdata)!=null&&i.key)){if(this.log(`Loading key for ${e.sn} of [${o.startSN}-${o.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(S.KEY_LOADED,h),this.state===X.KEY_LOADING&&(this.state=X.IDLE),h}),this.hls.trigger(S.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,o.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));const c=this.fragPrevious;if(qe(e)&&(!c||e.sn!==c.sn)){const h=this.shouldLoadParts(t.details,e.end);h!==this.loadingParts&&(this.log(`LL-Part loading ${h?"ON":"OFF"} loading sn ${c==null?void 0:c.sn}->${e.sn}`),this.loadingParts=h)}if(s=Math.max(e.start,s||0),this.loadingParts&&qe(e)){const h=o.partList;if(h&&n){s>o.fragmentEnd&&o.fragmentHint&&(e=o.fragmentHint);const g=this.getNextPart(h,e,s);if(g>-1){const m=h[g];e=this.fragCurrent=m.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${m.index} (${g}/${h.length-1}) of ${this.fragInfo(e,!1,m)}) cc: ${e.cc} [${o.startSN}-${o.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=m.start+m.duration,this.state=X.FRAG_LOADING;let p;return a?p=a.then(x=>!x||this.fragContextChanged(x.frag)?null:this.doFragPartsLoad(e,m,t,n)).catch(x=>this.handleFragLoadError(x)):p=this.doFragPartsLoad(e,m,t,n).catch(x=>this.handleFragLoadError(x)),this.hls.trigger(S.FRAG_LOADING,{frag:e,part:m,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):p}else if(!e.url||this.loadedEndOfParts(h,s))return Promise.resolve(null)}}if(qe(e)&&this.loadingParts){var l;this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(l=o.partList)==null?void 0:l.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} ${"["+o.startSN+"-"+o.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),ne(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=X.FRAG_LOADING;const d=this.config.progressive&&e.type!==oe.SUBTITLE;let u;return d&&a?u=a.then(h=>!h||this.fragContextChanged(h.frag)?null:this.fragmentLoader.load(e,n)).catch(h=>this.handleFragLoadError(h)):u=Promise.all([this.fragmentLoader.load(e,d?n:void 0),a]).then(([h])=>(!d&&n&&n(h),h)).catch(h=>this.handleFragLoadError(h)),this.hls.trigger(S.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(e,t,s,n){return new Promise((i,o)=>{var a;const c=[],l=(a=s.details)==null?void 0:a.partList,d=u=>{this.fragmentLoader.loadPart(e,u,n).then(h=>{c[u.index]=h;const g=h.part;this.hls.trigger(S.FRAG_LOADED,h);const m=El(s.details,e.sn,u.index+1)||zf(l,e.sn,u.index+1);if(m)d(m);else return i({frag:e,part:g,partsLoaded:c})}).catch(o)};d(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===B.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===ce.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(S.ERROR,t)}else this.hls.trigger(S.ERROR,{type:ce.OTHER_ERROR,details:B.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:s,part:n,level:i}=t,o=self.performance.now();s.stats.parsing.end=o,n&&(n.stats.parsing.end=o);const a=this.getLevelDetails(),l=a&&s.sn>a.endSN||this.shouldLoadParts(a,s.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=l),this.updateLevelTiming(s,n,i,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;const i=e.partList[0];if(i.fragment.type===oe.SUBTITLE)return!1;const o=i.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=o){var n;if((this.hls.hasEnoughToStart?((n=this.media)==null?void 0:n.currentTime)||this.lastCurrentTime:this.getLoadPosition())>i.start-i.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:n,sn:i,part:o}=e;if(!(t!=null&&t[n]))return this.warn(`Levels object was unset while buffering fragment ${i} of ${this.playlistLabel()} ${n}. The current chunk will not be buffered.`),null;const a=t[n],c=a.details,l=o>-1?El(c,i,o):null,d=l?l.fragment:Kf(c,i,s);return d?(s&&s!==d&&(d.stats=s.stats),{frag:d,part:l,level:a}):null}bufferFragmentData(e,t,s,n,i){if(this.state!==X.PARSING)return;const{data1:o,data2:a}=e;let c=o;if(a&&(c=$t(o,a)),!c.length)return;const l=this.initPTS[t.cc],d=l?-l.baseTime/l.timescale:void 0,u={type:e.type,frag:t,part:s,chunkMeta:n,offset:d,parent:t.type,data:c};if(this.hls.trigger(S.BUFFER_APPENDING,u),e.dropped&&e.independent&&!s){if(i)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!ve.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,n=ve.bufferInfo(t,s,0),i=e.duration,o=Math.min(this.config.maxFragLookUpTolerance*2,i*.25),a=Math.max(Math.min(e.start-o,n.end-o),s+o);e.start-a>o&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var s;const n=this.getLoadPosition();if(!ne(n))return null;const o=this.lastCurrentTime>n||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,o)}getFwdBufferInfoAtPos(e,t,s,n){const i=ve.bufferInfo(e,t,n);if(i.len===0&&i.nextStart!==void 0){const o=this.fragmentTracker.getBufferedFrag(t,s);if(o&&(i.nextStart<=o.end||o.gap)){const a=Math.max(Math.min(i.nextStart,o.end)-t,n);return ve.bufferInfo(e,t,a)}}return i}getMaxBufferLength(e){const{config:t}=this;let s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,n=Math.max(Math.min(e-t,s.maxBufferLength),t),i=Math.max(e-t*3,s.maxMaxBufferLength/2,n);return i>=n?(s.maxMaxBufferLength=i,this.warn(`Reduce max buffer length to ${i}s`),!0):!1}getAppendedFrag(e,t=oe.MAIN){const s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,n=s.length;if(!n)return null;const{config:i}=this,o=s[0].start,a=i.lowLatencyMode&&!!t.partList;let c=null;if(t.live){const u=i.initialLiveManifestSize;if(n<u)return this.warn(`Not enough fragments to start playback (have: ${n}, need: ${u})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<o){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),c=this.getInitialLiveFragment(t);const h=this.hls.startPosition,g=this.hls.liveSyncPosition,m=c?(h!==-1&&h>=o?h:g)||c.start:e;this.log(`Setting startPosition to ${m} to match start frag at live edge. mainStart: ${h} liveSyncPosition: ${g} frag.start: ${(l=c)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=m}}else e<=o&&(c=s[0]);if(!c){const u=this.loadingParts?t.partEnd:t.fragmentEnd;c=this.getFragmentAtPosition(e,u,t)}let d=this.filterReplacedPrimary(c,t);if(!d&&c){const u=c.sn-t.startSN;d=this.filterReplacedPrimary(s[u+1]||null,t)}return this.mapToInitFragWhenRequired(d)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===rt.OK||s===rt.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,n,i){let o=null;if(e.gap&&(o=this.getNextFragment(this.nextLoadPosition,t),o&&!o.gap&&s.nextStart)){const a=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,n,0);if(a!==null&&s.len+a.len>=i){const c=o.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,o}get primaryPrefetch(){if(Rl(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(Rl(this.config)&&e.type!==oe.SUBTITLE){const s=this.hls.interstitialsManager,n=s==null?void 0:s.bufferingItem;if(n){const o=n.event;if(o){if(o.appendInPlace||Math.abs(e.start-n.start)>1||n.start===0)return null}else if(e.end<=n.start&&(t==null?void 0:t.live)===!1||e.start>n.end&&n.nextEvent&&(n.nextEvent.appendInPlace||e.start-n.end>1))return null}const i=s==null?void 0:s.playerQueue;if(i)for(let o=i.length;o--;){const a=i[o].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,s){let n=-1,i=!1,o=!0;for(let a=0,c=e.length;a<c;a++){const l=e[a];if(o=o&&!l.independent,n>-1&&s<l.start)break;const d=l.loaded;d?n=-1:(i||(l.independent||o)&&l.fragment===t)&&(l.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${l.start}`),n=a),i=d}return n}loadedEndOfParts(e,t){let s;for(let n=e.length;n--;){if(s=e[n],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let n=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),n=oy(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!n){const i=s.sn+1;if(i>=e.startSN&&i<=e.endSN){const o=t[i-e.startSN];s.cc===o.cc&&(n=o,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=kf(e,s.cc,s.end),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const i=this.hls.liveSyncPosition;i!==null&&(n=this.getFragmentAtPosition(i,this.bitrateTest?e.fragmentEnd:e.edge,e))}return n}getFragmentAtPosition(e,t,s){const{config:n}=this;let{fragPrevious:i}=this,{fragments:o,endSN:a}=s;const{fragmentHint:c}=s,{maxFragLookUpTolerance:l}=n,d=s.partList,u=!!(this.loadingParts&&d!=null&&d.length&&c);u&&!this.bitrateTest&&d[d.length-1].fragment.sn===c.sn&&(o=o.concat(c),a=c.sn);let h;if(e<t){var g;const p=e<this.lastCurrentTime||e>t-l||(g=this.media)!=null&&g.paused||!this.startFragRequested?0:l;h=Os(i,o,e,p)}else h=o[o.length-1];if(h){const m=h.sn-s.startSN,p=this.fragmentTracker.getState(h);if((p===rt.OK||p===rt.PARTIAL&&h.gap)&&(i=h),i&&h.sn===i.sn&&(!u||d[0].fragment.sn>h.sn||!s.live)&&h.level===i.level){const v=o[m+1];h.sn<a&&this.fragmentTracker.getState(v)!==rt.OK?h=v:h=null}}return h}alignPlaylists(e,t,s){const n=e.fragments.length;if(!n)return this.warn("No fragments in live playlist"),0;const i=e.fragmentStart,o=!t,a=e.alignedSliding&&ne(i);if(o||!a&&!i){Vy(s,e);const c=e.fragmentStart;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${n}`),c}return i}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);const n=this.timelineOffset;if(s===-1){const i=this.startTimeOffset!==null,o=i?this.startTimeOffset:e.startTimeOffset;o!==null&&ne(o)?(s=t+o,o<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${o} found in ${i?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+n}this.nextLoadPosition=s+n}getLoadPosition(){var e;const{media:t}=this;let s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&qe(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 s;if(t.chunkMeta&&!t.frag){const v=this.getCurrentContext(t.chunkMeta);v&&(t.frag=v.frag)}const n=t.frag;if(!n||n.type!==e||!this.levels)return;if(this.fragContextChanged(n)){var i;this.warn(`Frag load error must match current frag to retry ${n.url} > ${(i=this.fragCurrent)==null?void 0:i.url}`);return}const o=t.details===B.FRAG_GAP;o&&this.fragmentTracker.fragBuffered(n,!0);const a=t.errorAction;if(!a){this.state=X.ERROR;return}const{action:c,flags:l,retryCount:d=0,retryConfig:u}=a,h=!!u,g=h&&c===lt.RetryRequest,m=h&&!a.resolved&&l===Ct.MoveAllAlternatesMatchingHost,p=(s=this.hls.latestLevelDetails)==null?void 0:s.live;if(!g&&m&&qe(n)&&!n.endList&&p&&!Pf(t))this.resetFragmentErrors(e),this.treatAsGap(n),a.resolved=!0;else if((g||m)&&d<u.maxNumRetry){var x;const v=Wi((x=t.response)==null?void 0:x.code),y=Zo(u,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+y,this.state=X.FRAG_LOADING_WAITING_RETRY,a.resolved=!0,v){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 ${d+1}/${u.maxNumRetry} in ${y}ms`)}else if(u)if(this.resetFragmentErrors(e),d<u.maxNumRetry)!o&&c!==lt.RemoveAlternatePermanently&&(a.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${d})`);return}else c===lt.SendAlternateToPenaltyBox?this.state=X.WAITING_LEVEL:this.state=X.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!Wi(0))&&(s&&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,s=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,s),i=n&&n.len>.5;i&&this.reduceMaxBufferLength(n.len,(t==null?void 0:t.duration)||10);const o=!i;return o&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),o}return!1}resetFragmentErrors(e){e===oe.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==X.STOPPED&&(this.state=X.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const n=ve.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,s),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,s,n){const i=s.details;if(!i){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((c,l)=>{const d=e.elementaryStreams[l];if(d){const u=d.endPTS-d.startPTS;if(u<=0)return this.warn(`Could not parse fragment ${e.sn} ${l} duration reliably (${u})`),c||!1;const h=n?0:Gf(i,e,d.startPTS,d.endPTS,d.startDTS,d.endDTS,this);return this.hls.trigger(S.LEVEL_PTS_UPDATED,{details:i,level:s,drift:h,type:l,frag:e,start:d.startPTS,end:d.endPTS}),!0}return c},!1)){var a;const c=((a=this.transmuxer)==null?void 0:a.error)===null;if((s.fragmentError===0||c&&(s.fragmentError<2||e.endList))&&this.treatAsGap(e,s),c){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(S.ERROR,{type:ce.MEDIA_ERROR,details:B.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.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(S.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===oe.MAIN?"level":"track"}fragInfo(e,t=!0,s){var n,i;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${((n=t&&!s?e.startPTS:(s||e).start)!=null?n:NaN).toFixed(3)}-${((i=t&&!s?e.endPTS:(s||e).end)!=null?i:NaN).toFixed(3)}]${s&&e.type==="main"?"INDEPENDENT="+(s.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 Rl(r){return!!r.interstitialsController&&r.enableInterstitialPlayback!==!1}class Xf{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;if(e.length)e.length===1?s=e[0]:s=Ky(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function Ky(r,e){const t=new Uint8Array(e);let s=0;for(let n=0;n<r.length;n++){const i=r[n];t.set(i,s),s+=i.length}return t}var hi={exports:{}},Al;function zy(){return Al||(Al=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function n(c,l,d){this.fn=c,this.context=l,this.once=d||!1}function i(c,l,d,u,h){if(typeof d!="function")throw new TypeError("The listener must be a function");var g=new n(d,u||c,h),m=t?t+l:l;return c._events[m]?c._events[m].fn?c._events[m]=[c._events[m],g]:c._events[m].push(g):(c._events[m]=g,c._eventsCount++),c}function o(c,l){--c._eventsCount===0?c._events=new s:delete c._events[l]}function a(){this._events=new s,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],d,u;if(this._eventsCount===0)return l;for(u in d=this._events)e.call(d,u)&&l.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(d)):l},a.prototype.listeners=function(l){var d=t?t+l:l,u=this._events[d];if(!u)return[];if(u.fn)return[u.fn];for(var h=0,g=u.length,m=new Array(g);h<g;h++)m[h]=u[h].fn;return m},a.prototype.listenerCount=function(l){var d=t?t+l:l,u=this._events[d];return u?u.fn?1:u.length:0},a.prototype.emit=function(l,d,u,h,g,m){var p=t?t+l:l;if(!this._events[p])return!1;var x=this._events[p],v=arguments.length,y,b;if(x.fn){switch(x.once&&this.removeListener(l,x.fn,void 0,!0),v){case 1:return x.fn.call(x.context),!0;case 2:return x.fn.call(x.context,d),!0;case 3:return x.fn.call(x.context,d,u),!0;case 4:return x.fn.call(x.context,d,u,h),!0;case 5:return x.fn.call(x.context,d,u,h,g),!0;case 6:return x.fn.call(x.context,d,u,h,g,m),!0}for(b=1,y=new Array(v-1);b<v;b++)y[b-1]=arguments[b];x.fn.apply(x.context,y)}else{var T=x.length,R;for(b=0;b<T;b++)switch(x[b].once&&this.removeListener(l,x[b].fn,void 0,!0),v){case 1:x[b].fn.call(x[b].context);break;case 2:x[b].fn.call(x[b].context,d);break;case 3:x[b].fn.call(x[b].context,d,u);break;case 4:x[b].fn.call(x[b].context,d,u,h);break;default:if(!y)for(R=1,y=new Array(v-1);R<v;R++)y[R-1]=arguments[R];x[b].fn.apply(x[b].context,y)}}return!0},a.prototype.on=function(l,d,u){return i(this,l,d,u,!1)},a.prototype.once=function(l,d,u){return i(this,l,d,u,!0)},a.prototype.removeListener=function(l,d,u,h){var g=t?t+l:l;if(!this._events[g])return this;if(!d)return o(this,g),this;var m=this._events[g];if(m.fn)m.fn===d&&(!h||m.once)&&(!u||m.context===u)&&o(this,g);else{for(var p=0,x=[],v=m.length;p<v;p++)(m[p].fn!==d||h&&!m[p].once||u&&m[p].context!==u)&&x.push(m[p]);x.length?this._events[g]=x.length===1?x[0]:x:o(this,g)}return this},a.prototype.removeAllListeners=function(l){var d;return l?(d=t?t+l:l,this._events[d]&&o(this,d)):(this._events=new s,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=t,a.EventEmitter=a,r.exports=a}(hi)),hi.exports}var Wy=zy(),na=vv(Wy);const Pr="1.6.15",rr={};function Yy(){return typeof __HLS_WORKER_BUNDLE__=="function"}function qy(){const r=rr[Pr];if(r)return r.clientCount++,r;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),n={worker:new self.Worker(t),objectURL:t,clientCount:1};return rr[Pr]=n,n}function Xy(r){const e=rr[r];if(e)return e.clientCount++,e;const t=new self.URL(r,self.location.href).href,n={worker:new self.Worker(t),scriptURL:t,clientCount:1};return rr[r]=n,n}function Qy(r){const e=rr[r||Pr];if(e&&e.clientCount--===1){const{worker:s,objectURL:n}=e;delete rr[r||Pr],n&&self.URL.revokeObjectURL(n),s.terminate()}}function Qf(r,e){return e+10<=r.length&&r[e]===51&&r[e+1]===68&&r[e+2]===73&&r[e+3]<255&&r[e+4]<255&&r[e+6]<128&&r[e+7]<128&&r[e+8]<128&&r[e+9]<128}function ia(r,e){return e+10<=r.length&&r[e]===73&&r[e+1]===68&&r[e+2]===51&&r[e+3]<255&&r[e+4]<255&&r[e+6]<128&&r[e+7]<128&&r[e+8]<128&&r[e+9]<128}function Wn(r,e){let t=0;return t=(r[e]&127)<<21,t|=(r[e+1]&127)<<14,t|=(r[e+2]&127)<<7,t|=r[e+3]&127,t}function Nr(r,e){const t=e;let s=0;for(;ia(r,e);){s+=10;const n=Wn(r,e+6);s+=n,Qf(r,e+10)&&(s+=10),e+=s}if(s>0)return r.subarray(t,t+s)}function Zy(r,e,t,s){const n=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],i=e[t+2],o=i>>2&15;if(o>12){const g=new Error(`invalid ADTS sampling index:${o}`);r.emit(S.ERROR,S.ERROR,{type:ce.MEDIA_ERROR,details:B.FRAG_PARSING_ERROR,fatal:!0,error:g,reason:g.message});return}const a=(i>>6&3)+1,c=e[t+3]>>6&3|(i&1)<<2,l="mp4a.40."+a,d=n[o];let u=o;(a===5||a===29)&&(u-=3);const h=[a<<3|(u&14)>>1,(u&1)<<7|c<<3];return ke.log(`manifest codec:${s}, parsed codec:${l}, channels:${c}, rate:${d} (ADTS object type:${a} sampling index:${o})`),{config:h,samplerate:d,channelCount:c,codec:l,parsedCodec:l,manifestCodec:s}}function Zf(r,e){return r[e]===255&&(r[e+1]&246)===240}function Jf(r,e){return r[e+1]&1?7:9}function oa(r,e){return(r[e+3]&3)<<11|r[e+4]<<3|(r[e+5]&224)>>>5}function Jy(r,e){return e+5<r.length}function Pn(r,e){return e+1<r.length&&Zf(r,e)}function eb(r,e){return Jy(r,e)&&Zf(r,e)&&oa(r,e)<=r.length-e}function tb(r,e){if(Pn(r,e)){const t=Jf(r,e);if(e+t>=r.length)return!1;const s=oa(r,e);if(s<=t)return!1;const n=e+s;return n===r.length||Pn(r,n)}return!1}function eh(r,e,t,s,n){if(!r.samplerate){const i=Zy(e,t,s,n);if(!i)return;De(r,i)}}function th(r){return 1024*9e4/r}function sb(r,e){const t=Jf(r,e);if(e+t<=r.length){const s=oa(r,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function sh(r,e,t,s,n){const i=th(r.samplerate),o=s+n*i,a=sb(e,t);let c;if(a){const{frameLength:u,headerLength:h}=a,g=h+u,m=Math.max(0,t+g-e.length);m?(c=new Uint8Array(g-h),c.set(e.subarray(t+h,e.length),0)):c=e.subarray(t+h,t+g);const p={unit:c,pts:o};return m||r.samples.push(p),{sample:p,length:g,missing:m}}const l=e.length-t;return c=new Uint8Array(l),c.set(e.subarray(t,e.length),0),{sample:{unit:c,pts:o},length:l,missing:-1}}function rb(r,e){return ia(r,e)&&Wn(r,e+6)+10<=r.length-e}function nb(r){return r instanceof ArrayBuffer?r:r.byteOffset==0&&r.byteLength==r.buffer.byteLength?r.buffer:new Uint8Array(r).buffer}function gi(r,e=0,t=1/0){return ib(r,e,t,Uint8Array)}function ib(r,e,t,s){const n=ob(r);let i=1;"BYTES_PER_ELEMENT"in s&&(i=s.BYTES_PER_ELEMENT);const o=ab(r)?r.byteOffset:0,a=(o+r.byteLength)/i,c=(o+e)/i,l=Math.floor(Math.max(0,Math.min(c,a))),d=Math.floor(Math.min(l+Math.max(t,0),a));return new s(n,l,d-l)}function ob(r){return r instanceof ArrayBuffer?r:r.buffer}function ab(r){return r&&r.buffer instanceof ArrayBuffer&&r.byteLength!==void 0&&r.byteOffset!==void 0}function lb(r){const e={key:r.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(r.size<2)return;if(r.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const s=r.data.subarray(1).indexOf(0);if(s===-1)return;const n=Pt(gi(r.data,1,s)),i=r.data[2+s],o=r.data.subarray(3+s).indexOf(0);if(o===-1)return;const a=Pt(gi(r.data,3+s,o));let c;return n==="-->"?c=Pt(gi(r.data,4+s+o)):c=nb(r.data.subarray(4+s+o)),e.mimeType=n,e.pictureType=i,e.description=a,e.data=c,e}function cb(r){if(r.size<2)return;const e=Pt(r.data,!0),t=new Uint8Array(r.data.subarray(e.length+1));return{key:r.type,info:e,data:t.buffer}}function db(r){if(r.size<2)return;if(r.type==="TXXX"){let t=1;const s=Pt(r.data.subarray(t),!0);t+=s.length+1;const n=Pt(r.data.subarray(t));return{key:r.type,info:s,data:n}}const e=Pt(r.data.subarray(1));return{key:r.type,info:"",data:e}}function ub(r){if(r.type==="WXXX"){if(r.size<2)return;let t=1;const s=Pt(r.data.subarray(t),!0);t+=s.length+1;const n=Pt(r.data.subarray(t));return{key:r.type,info:s,data:n}}const e=Pt(r.data);return{key:r.type,info:"",data:e}}function fb(r){return r.type==="PRIV"?cb(r):r.type[0]==="W"?ub(r):r.type==="APIC"?lb(r):db(r)}function hb(r){const e=String.fromCharCode(r[0],r[1],r[2],r[3]),t=Wn(r,4),s=10;return{type:e,size:t,data:r.subarray(s,s+t)}}const Jr=10,gb=10;function rh(r){let e=0;const t=[];for(;ia(r,e);){const s=Wn(r,e+6);r[e+5]>>6&1&&(e+=Jr),e+=Jr;const n=e+s;for(;e+gb<n;){const i=hb(r.subarray(e)),o=fb(i);o&&t.push(o),e+=i.size+Jr}Qf(r,e)&&(e+=Jr)}return t}function nh(r){return r&&r.key==="PRIV"&&r.info==="com.apple.streaming.transportStreamTimestamp"}function mb(r){if(r.data.byteLength===8){const e=new Uint8Array(r.data),t=e[3]&1;let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function aa(r){const e=rh(r);for(let t=0;t<e.length;t++){const s=e[t];if(nh(s))return mb(s)}}let kt=function(r){return r.audioId3="org.id3",r.dateRange="com.apple.quicktime.HLS",r.emsg="https://aomedia.org/emsg/ID3",r.misbklv="urn:misb:KLV:bin:1910.1",r}({});function Jt(r="",e=9e4){return{type:r,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class la{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,s,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,s){}demux(e,t){this.cachedData&&(e=$t(this.cachedData,e),this.cachedData=null);let s=Nr(e,0),n=s?s.length:0,i;const o=this._audioTrack,a=this._id3Track,c=s?aa(s):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&ne(c))&&(this.basePTS=pb(c,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:kt.audioId3,duration:Number.POSITIVE_INFINITY});n<l;){if(this.canParse(e,n)){const d=this.appendFrame(o,e,n);d?(this.frameIndex++,this.lastPTS=d.sample.pts,n+=d.length,i=n):n=l}else rb(e,n)?(s=Nr(e,n),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:kt.audioId3,duration:Number.POSITIVE_INFINITY}),n+=s.length,i=n):n++;if(n===l&&i!==l){const d=e.slice(i);this.cachedData?this.cachedData=$t(this.cachedData,d):this.cachedData=d}}return{audioTrack:o,videoTrack:Jt(),id3Track:a,textTrack:Jt()}}demuxSampleAes(e,t,s){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:Jt(),id3Track:this._id3Track,textTrack:Jt()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const pb=(r,e,t)=>{if(ne(r))return r*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s};let en=null;const xb=[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],vb=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],yb=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],bb=[0,1,1,4];function ih(r,e,t,s,n){if(t+24>e.length)return;const i=oh(e,t);if(i&&t+i.frameLength<=e.length){const o=i.samplesPerFrame*9e4/i.sampleRate,a=s+n*o,c={unit:e.subarray(t,t+i.frameLength),pts:a,dts:a};return r.config=[],r.channelCount=i.channelCount,r.samplerate=i.sampleRate,r.samples.push(c),{sample:c,length:i.frameLength,missing:0}}}function oh(r,e){const t=r[e+1]>>3&3,s=r[e+1]>>1&3,n=r[e+2]>>4&15,i=r[e+2]>>2&3;if(t!==1&&n!==0&&n!==15&&i!==3){const o=r[e+2]>>1&1,a=r[e+3]>>6,c=t===3?3-s:s===3?3:4,l=xb[c*14+n-1]*1e3,u=vb[(t===3?0:t===2?1:2)*3+i],h=a===3?1:2,g=yb[t][s],m=bb[s],p=g*8*m,x=Math.floor(g*l/u+o)*m;if(en===null){const b=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);en=b?parseInt(b[1]):0}return!!en&&en<=87&&s===2&&l>=224e3&&a===0&&(r[e+3]=r[e+3]|128),{sampleRate:u,channelCount:h,frameLength:x,samplesPerFrame:p}}}function ca(r,e){return r[e]===255&&(r[e+1]&224)===224&&(r[e+1]&6)!==0}function ah(r,e){return e+1<r.length&&ca(r,e)}function Sb(r,e){return ca(r,e)&&4<=r.length-e}function lh(r,e){if(e+1<r.length&&ca(r,e)){const s=oh(r,e);let n=4;s!=null&&s.frameLength&&(n=s.frameLength);const i=e+n;return i===r.length||ah(r,i)}return!1}class Eb extends la{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,n){super.resetInitSegment(e,t,s,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 s=Nr(e,0);let n=(s==null?void 0:s.length)||0;if(lh(e,n))return!1;for(let i=e.length;n<i;n++)if(tb(e,n))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return eb(e,t)}appendFrame(e,t,s){eh(e,this.observer,t,s,e.manifestCodec);const n=sh(e,t,s,this.basePTS,this.frameIndex);if(n&&n.missing===0)return n}}const ch=(r,e)=>{let t=0,s=5;e+=s;const n=new Uint32Array(1),i=new Uint32Array(1),o=new Uint8Array(1);for(;s>0;){o[0]=r[e];const a=Math.min(s,8),c=8-a;i[0]=4278190080>>>24+c<<c,n[0]=(o[0]&i[0])>>c,t=t?t<<a|n[0]:n[0],e+=1,s-=a}return t};class Tb extends la{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,n){super.resetInitSegment(e,t,s,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,s){const n=dh(e,t,s,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=Nr(e,0);if(!t)return!1;const s=t.length;return e[s]===11&&e[s+1]===119&&aa(t)!==void 0&&ch(e,s)<16}}function dh(r,e,t,s,n){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const i=e[t+4]>>6;if(i>=3)return-1;const a=[48e3,44100,32e3][i],c=e[t+4]&63,d=[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][c*3+i]*2;if(t+d>e.length)return-1;const u=e[t+6]>>5;let h=0;u===2?h+=2:(u&1&&u!==1&&(h+=2),u&4&&(h+=2));const g=(e[t+6]<<8|e[t+7])>>12-h&1,p=[2,1,2,3,3,4,4,5][u]+g,x=e[t+5]>>3,v=e[t+5]&7,y=new Uint8Array([i<<6|x<<1|v>>2,(v&3)<<6|u<<3|g<<2|c>>4,c<<4&224]),b=1536/a*9e4,T=s+n*b,R=e.subarray(t,t+d);return r.config=y,r.channelCount=p,r.samplerate=a,r.samples.push({unit:R,pts:T}),d}class wb extends la{resetInitSegment(e,t,s,n){super.resetInitSegment(e,t,s,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=Nr(e,0);let s=(t==null?void 0:t.length)||0;if(t&&e[s]===11&&e[s+1]===119&&aa(t)!==void 0&&ch(e,s)<=16)return!1;for(let n=e.length;s<n;s++)if(lh(e,s))return ke.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return Sb(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return ih(e,t,s,this.basePTS,this.frameIndex)}}const Rb=/\/emsg[-/]ID3/i;class Ab{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,s,n){const i=this.videoTrack=Jt("video",1),o=this.audioTrack=Jt("audio",1),a=this.txtTrack=Jt("text",1);if(this.id3Track=Jt("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const c=bf(e);if(c.video){const{id:l,timescale:d,codec:u,supplemental:h}=c.video;i.id=l,i.timescale=a.timescale=d,i.codec=u,i.supplemental=h}if(c.audio){const{id:l,timescale:d,codec:u}=c.audio;o.id=l,o.timescale=d,o.codec=u}a.id=xf.text,i.sampleDuration=0,i.duration=o.duration=n}resetContiguity(){this.remainderData=null}static probe(e){return Tv(e)}demux(e,t){this.timeOffset=t;let s=e;const n=this.videoTrack,i=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=$t(this.remainderData,e));const a=_v(s);this.remainderData=a.remainder,n.samples=a.valid||new Uint8Array}else n.samples=s;const o=this.extractID3Track(n,t);return i.samples=Ha(t,n),{videoTrack:n,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(t,this.timeOffset);return s.samples=Ha(e,t),{videoTrack:t,audioTrack:Jt(),id3Track:n,textTrack:Jt()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const n=Ee(e.samples,["emsg"]);n&&n.forEach(i=>{const o=Dv(i);if(Rb.test(o.schemeIdUri)){const a=Il(o,t);let c=o.eventDuration===4294967295?Number.POSITIVE_INFINITY:o.eventDuration/o.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const l=o.payload;s.samples.push({data:l,len:l.byteLength,dts:a,pts:a,type:kt.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&o.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const a=Il(o,t);s.samples.push({data:o.payload,len:o.payload.byteLength,dts:a,pts:a,type:kt.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(e,t,s){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 Il(r,e){return ne(r.presentationTime)?r.presentationTime/r.timeScale:e+r.presentationTimeDelta/r.timeScale}class Ib{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Jo(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Ts.cbc)}decryptAacSample(e,t,s){const n=e[t].unit;if(n.length<=16)return;const i=n.subarray(16,n.length-n.length%16),o=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(o).then(a=>{const c=new Uint8Array(a);n.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t);let n=0;for(let i=32;i<e.length-16;i+=160,n+=16)s.set(e.subarray(i,i+16),n);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let n=0;for(let i=32;i<e.length-16;i+=160,n+=16)e.set(s.subarray(n,n+16),i);return e}decryptAvcSample(e,t,s,n,i){const o=Tf(i.data),a=this.getAvcEncryptedData(o);this.decryptBuffer(a.buffer).then(c=>{i.data=this.getAvcDecryptedUnit(o,c),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,n)}).catch(n)}decryptAvcSamples(e,t,s,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){n();return}const i=e[t].units;for(;!(s>=i.length);s++){const o=i[s];if(!(o.data.length<=48||o.type!==1&&o.type!==5)&&(this.decryptAvcSample(e,t,s,n,o),!this.decrypter.isSync()))return}}}}class uh{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,n;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){const i=s.units;n=i[i.length-1]}return n}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const s=t.samples,n=s.length;if(n){const i=s[n-1];e.pts=i.pts,e.dts=i.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){const n=t.byteLength;let i=e.naluState||0;const o=i,a=[];let c=0,l,d,u,h=-1,g=0;for(i===-1&&(h=0,g=this.getNALuType(t,0),i=0,c=1);c<n;){if(l=t[c++],!i){i=l?0:1;continue}if(i===1){i=l?0:2;continue}if(!l)i=3;else if(l===1){if(d=c-i-1,h>=0){const m={data:t.subarray(h,d),type:g};a.push(m)}else{const m=this.getLastNalUnit(e.samples);m&&(o&&c<=4-o&&m.state&&(m.data=m.data.subarray(0,m.data.byteLength-o)),d>0&&(m.data=$t(m.data,t.subarray(0,d)),m.state=0))}c<n?(u=this.getNALuType(t,c),h=c,g=u,i=0):i=-1}else i=0}if(h>=0&&i>=0){const m={data:t.subarray(h,n),type:g,state:i};a.push(m)}if(a.length===0){const m=this.getLastNalUnit(e.samples);m&&(m.data=$t(m.data,t))}return e.naluState=i,a}}class Er{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,s=e.byteLength-t,n=new Uint8Array(4),i=Math.min(4,t);if(i===0)throw new Error("no bytes available");n.set(e.subarray(s,s+i)),this.word=new DataView(n.buffer).getUint32(0),this.bitsAvailable=i*8,this.bytesAvailable-=i}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 s=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?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class Lb extends uh{parsePES(e,t,s,n){const i=this.parseNALu(e,s.data,n);let o=this.VideoSample,a,c=!1;s.data=null,o&&i.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),i.forEach(l=>{var d,u;switch(l.type){case 1:{let p=!1;a=!0;const x=l.data;if(c&&x.length>4){const v=this.readSliceType(x);(v===2||v===4||v===7||v===9)&&(p=!0)}if(p){var h;(h=o)!=null&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),o.frame=!0,o.key=p;break}case 5:a=!0,(d=o)!=null&&d.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),o.key=!0,o.frame=!0;break;case 6:{a=!0,qo(l.data,1,s.pts,t.samples);break}case 7:{var g,m;a=!0,c=!0;const p=l.data,x=this.readSPS(p);if(!e.sps||e.width!==x.width||e.height!==x.height||((g=e.pixelRatio)==null?void 0:g[0])!==x.pixelRatio[0]||((m=e.pixelRatio)==null?void 0:m[1])!==x.pixelRatio[1]){e.width=x.width,e.height=x.height,e.pixelRatio=x.pixelRatio,e.sps=[p];const v=p.subarray(1,4);let y="avc1.";for(let b=0;b<3;b++){let T=v[b].toString(16);T.length<2&&(T="0"+T),y+=T}e.codec=y}break}case 8:a=!0,e.pps=[l.data];break;case 9:a=!0,e.audFound=!0,(u=o)!=null&&u.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:a=!0;break;default:a=!1;break}o&&a&&o.units.push(l)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Er(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,n=8,i;for(let o=0;o<e;o++)n!==0&&(i=t.readEG(),n=(s+i+256)%256),s=n===0?s:n}readSPS(e){const t=new Er(e);let s=0,n=0,i=0,o=0,a,c,l;const d=t.readUByte.bind(t),u=t.readBits.bind(t),h=t.readUEG.bind(t),g=t.readBoolean.bind(t),m=t.skipBits.bind(t),p=t.skipEG.bind(t),x=t.skipUEG.bind(t),v=this.skipScalingList.bind(this);d();const y=d();if(u(5),m(3),d(),x(),y===100||y===110||y===122||y===244||y===44||y===83||y===86||y===118||y===128){const A=h();if(A===3&&m(1),x(),x(),m(1),g())for(c=A!==3?8:12,l=0;l<c;l++)g()&&(l<6?v(16,t):v(64,t))}x();const b=h();if(b===0)h();else if(b===1)for(m(1),p(),p(),a=h(),l=0;l<a;l++)p();x(),m(1);const T=h(),R=h(),_=u(1);_===0&&m(1),m(1),g()&&(s=h(),n=h(),i=h(),o=h());let w=[1,1];if(g()&&g())switch(d()){case 1:w=[1,1];break;case 2:w=[12,11];break;case 3:w=[10,11];break;case 4:w=[16,11];break;case 5:w=[40,33];break;case 6:w=[24,11];break;case 7:w=[20,11];break;case 8:w=[32,11];break;case 9:w=[80,33];break;case 10:w=[18,11];break;case 11:w=[15,11];break;case 12:w=[64,33];break;case 13:w=[160,99];break;case 14:w=[4,3];break;case 15:w=[3,2];break;case 16:w=[2,1];break;case 255:{w=[d()<<8|d(),d()<<8|d()];break}}return{width:Math.ceil((T+1)*16-s*2-n*2),height:(2-_)*(R+1)*16-(_?2:4)*(i+o),pixelRatio:w}}}class Cb extends uh{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,n){const i=this.parseNALu(e,s.data,n);let o=this.VideoSample,a,c=!1;s.data=null,o&&i.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),i.forEach(l=>{var d,u;switch(l.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),o.frame=!0,a=!0;break;case 16:case 17:case 18:case 21:if(a=!0,c){var h;(h=o)!=null&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),o.key=!0,o.frame=!0;break;case 19:case 20:a=!0,(d=o)!=null&&d.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),o.key=!0,o.frame=!0;break;case 39:a=!0,qo(l.data,2,s.pts,t.samples);break;case 32:a=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=De(e.params,this.readVPS(l.data)),this.initVPS=l.data),e.vps=[l.data];break;case 33:if(a=!0,c=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],l.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const g=this.readSPS(l.data);e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.codec=g.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const m in g.params)e.params[m]=g.params[m]}this.pushParameterSet(e.sps,l.data,e.vps),o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),o.key=!0;break;case 34:if(a=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const g=this.readPPS(l.data);for(const m in g)e.params[m]=g[m]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:a=!0,e.audFound=!0,(u=o)!=null&&u.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:a=!1;break}o&&a&&o.units.push(l)}),n&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let n=0;n<e.byteLength;n++)n>=2&&e[n]===3&&e[n-1]===0&&e[n-2]===0||(t[s]=e[n],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Er(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const s=t.readBits(3),n=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:n}}readSPS(e){const t=new Er(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const n=t.readBits(2),i=t.readBoolean(),o=t.readBits(5),a=t.readUByte(),c=t.readUByte(),l=t.readUByte(),d=t.readUByte(),u=t.readUByte(),h=t.readUByte(),g=t.readUByte(),m=t.readUByte(),p=t.readUByte(),x=t.readUByte(),v=t.readUByte(),y=[],b=[];for(let he=0;he<s;he++)y.push(t.readBoolean()),b.push(t.readBoolean());if(s>0)for(let he=s;he<8;he++)t.readBits(2);for(let he=0;he<s;he++)y[he]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),b[he]&&t.readUByte();t.readUEG();const T=t.readUEG();T==3&&t.skipBits(1);const R=t.readUEG(),_=t.readUEG(),w=t.readBoolean();let A=0,C=0,L=0,P=0;w&&(A+=t.readUEG(),C+=t.readUEG(),L+=t.readUEG(),P+=t.readUEG());const M=t.readUEG(),j=t.readUEG(),D=t.readUEG(),$=t.readBoolean();for(let he=$?0:s;he<=s;he++)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 be=0;be<4;be++)for(let Ae=0;Ae<(be===3?2:6);Ae++)if(!t.readBoolean())t.readUEG();else{const Me=Math.min(64,1<<4+(be<<1));be>1&&t.readEG();for(let $e=0;$e<Me;$e++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const k=t.readUEG();let z=0;for(let he=0;he<k;he++){let be=!1;if(he!==0&&(be=t.readBoolean()),be){he===k&&t.readUEG(),t.readBoolean(),t.readUEG();let Ae=0;for(let Ie=0;Ie<=z;Ie++){const Me=t.readBoolean();let $e=!1;Me||($e=t.readBoolean()),(Me||$e)&&Ae++}z=Ae}else{const Ae=t.readUEG(),Ie=t.readUEG();z=Ae+Ie;for(let Me=0;Me<Ae;Me++)t.readUEG(),t.readBoolean();for(let Me=0;Me<Ie;Me++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const he=t.readUEG();for(let be=0;be<he;be++){for(let Ae=0;Ae<D+4;Ae++)t.readBits(1);t.readBits(1)}}let U=0,K=1,G=1,H=!0,q=1,J=0;t.readBoolean(),t.readBoolean();let ee=!1;if(t.readBoolean()){if(t.readBoolean()){const Le=t.readUByte(),at=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Ge=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];Le>0&&Le<16?(K=at[Le-1],G=Ge[Le-1]):Le===255&&(K=t.readBits(16),G=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(),ee=t.readBoolean(),ee&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(q=t.readBits(32),J=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const Ge=t.readBoolean(),Mt=t.readBoolean();let Je=!1;(Ge||Mt)&&(Je=t.readBoolean(),Je&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),Je&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Tt=0;Tt<=s;Tt++){H=t.readBoolean();const Ft=H||t.readBoolean();let wt=!1;Ft?t.readEG():wt=t.readBoolean();const we=wt?1:t.readUEG()+1;if(Ge)for(let mt=0;mt<we;mt++)t.readUEG(),t.readUEG(),Je&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(Mt)for(let mt=0;mt<we;mt++)t.readUEG(),t.readUEG(),Je&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),U=t.readUEG())}let de=R,ie=_;if(w){let he=1,be=1;T===1?he=be=2:T==2&&(he=2),de=R-he*C-he*A,ie=_-be*P-be*L}const ue=n?["A","B","C"][n]:"",re=a<<24|c<<16|l<<8|d;let Z=0;for(let he=0;he<32;he++)Z=(Z|(re>>he&1)<<31-he)>>>0;let fe=Z.toString(16);return o===1&&fe==="2"&&(fe="6"),{codecString:`hvc1.${ue}${o}.${fe}.${i?"H":"L"}${v}.B0`,params:{general_tier_flag:i,general_profile_idc:o,general_profile_space:n,general_profile_compatibility_flags:[a,c,l,d],general_constraint_indicator_flags:[u,h,g,m,p,x],general_level_idc:v,bit_depth:M+8,bit_depth_luma_minus8:M,bit_depth_chroma_minus8:j,min_spatial_segmentation_idc:U,chroma_format_idc:T,frame_rate:{fixed:H,fps:J/q}},width:de,height:ie,pixelRatio:[K,G]}}readPPS(e){const t=new Er(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 n=t.readBoolean(),i=t.readBoolean();let o=1;return i&&n?o=0:i?o=3:n&&(o=2),{parallelismType:o}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const it=188;class vs{constructor(e,t,s,n){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.logger=n,this.videoParser=null}static probe(e,t){const s=vs.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){const t=e.length;let s=Math.min(it*5,t-it)+1,n=0;for(;n<s;){let i=!1,o=-1,a=0;for(let c=n;c<t;c+=it)if(e[c]===71&&(t-c===it||e[c+it]===71)){if(a++,o===-1&&(o=c,o!==0&&(s=Math.min(o+it*99,e.length-it)+1)),i||(i=Zi(e,c)===0),i&&a>1&&(o===0&&a>2||c+it>s))return o}else{if(a)return-1;break}n++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:xf[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=vs.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=vs.createTrack("audio",n),this._id3Track=vs.createTrack("id3"),this._txtTrack=vs.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,n=!1){s||(this.sampleAes=null);let i;const o=this._videoTrack,a=this._audioTrack,c=this._id3Track,l=this._txtTrack;let d=o.pid,u=o.pesData,h=a.pid,g=c.pid,m=a.pesData,p=c.pesData,x=null,v=this.pmtParsed,y=this._pmtId,b=e.length;if(this.remainderData&&(e=$t(this.remainderData,e),b=e.length,this.remainderData=null),b<it&&!n)return this.remainderData=e,{audioTrack:a,videoTrack:o,id3Track:c,textTrack:l};const T=Math.max(0,vs.syncOffset(e));b-=(b-T)%it,b<e.byteLength&&!n&&(this.remainderData=new Uint8Array(e.buffer,b,e.buffer.byteLength-b));let R=0;for(let w=T;w<b;w+=it)if(e[w]===71){const A=!!(e[w+1]&64),C=Zi(e,w),L=(e[w+3]&48)>>4;let P;if(L>1){if(P=w+5+e[w+4],P===w+it)continue}else P=w+4;switch(C){case d:A&&(u&&(i=Ys(u,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,l,i,!1)),u={data:[],size:0}),u&&(u.data.push(e.subarray(P,w+it)),u.size+=w+it-P);break;case h:if(A){if(m&&(i=Ys(m,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,i);break;case"mp3":this.parseMPEGPES(a,i);break;case"ac3":this.parseAC3PES(a,i);break}m={data:[],size:0}}m&&(m.data.push(e.subarray(P,w+it)),m.size+=w+it-P);break;case g:A&&(p&&(i=Ys(p,this.logger))&&this.parseID3PES(c,i),p={data:[],size:0}),p&&(p.data.push(e.subarray(P,w+it)),p.size+=w+it-P);break;case 0:A&&(P+=e[P]+1),y=this._pmtId=_b(e,P);break;case y:{A&&(P+=e[P]+1);const M=kb(e,P,this.typeSupported,s,this.observer,this.logger);d=M.videoPid,d>0&&(o.pid=d,o.segmentCodec=M.segmentVideoCodec),h=M.audioPid,h>0&&(a.pid=h,a.segmentCodec=M.segmentAudioCodec),g=M.id3Pid,g>0&&(c.pid=g),x!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${w} after unknown PID '${x}'. Backtracking to sync byte @${T} to parse all TS packets.`),x=null,w=T-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:x=C;break}}else R++;R>0&&Ji(this.observer,new Error(`Found ${R} TS packet/s that do not start with 0x47`),void 0,this.logger),o.pesData=u,a.pesData=m,c.pesData=p;const _={audioTrack:a,videoTrack:o,id3Track:c,textTrack:l};return n&&this.extractRemainingSamples(_),_}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:s,id3Track:n,textTrack:i}=e,o=s.pesData,a=t.pesData,c=n.pesData;let l;if(o&&(l=Ys(o,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,i,l,!0),s.pesData=null)):s.pesData=o,a&&(l=Ys(a,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l);break}t.pesData=null}else a!=null&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;c&&(l=Ys(c,this.logger))?(this.parseID3PES(n,l),n.pesData=null):n.pesData=c}demuxSampleAes(e,t,s){const n=this.demux(e,s,!0,!this.config.progressive),i=this.sampleAes=new Ib(this.observer,this.config,t);return this.decrypt(n,i)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new Lb:e==="hevc"&&(this.videoParser=new Cb))}decrypt(e,t){return new Promise(s=>{const{audioTrack:n,videoTrack:i}=e;n.samples&&n.segmentCodec==="aac"?t.decryptAacSamples(n.samples,0,()=>{i.samples?t.decryptAvcSamples(i.samples,0,0,()=>{s(e)}):s(e)}):i.samples&&t.decryptAvcSamples(i.samples,0,0,()=>{s(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let s=0;const n=this.aacOverFlow;let i=t.data;if(n){this.aacOverFlow=null;const u=n.missing,h=n.sample.unit.byteLength;if(u===-1)i=$t(n.sample.unit,i);else{const g=h-u;n.sample.unit.set(i.subarray(0,u),g),e.samples.push(n.sample),s=n.missing}}let o,a;for(o=s,a=i.length;o<a-1&&!Pn(i,o);o++);if(o!==s){let u;const h=o<a-1;if(h?u=`AAC PES did not start with ADTS header,offset:${o}`:u="No ADTS header found in AAC PES",Ji(this.observer,new Error(u),h,this.logger),!h)return}eh(e,this.observer,i,o,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(n){const u=th(e.samplerate);c=n.sample.pts+u}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let l=0,d;for(;o<a;)if(d=sh(e,i,o,c,l),o+=d.length,d.missing){this.aacOverFlow=d;break}else for(l++;o<a-1&&!Pn(i,o);o++);}parseMPEGPES(e,t){const s=t.data,n=s.length;let i=0,o=0;const a=t.pts;if(a===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;o<n;)if(ah(s,o)){const c=ih(e,s,o,a,i);if(c)o+=c.length,i++;else break}else o++}parseAC3PES(e,t){{const s=t.data,n=t.pts;if(n===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const i=s.length;let o=0,a=0,c;for(;a<i&&(c=dh(e,s,a,n,o++))>0;)a+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=De({},t,{type:this._videoTrack?kt.emsg:kt.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function Zi(r,e){return((r[e+1]&31)<<8)+r[e+2]}function _b(r,e){return(r[e+10]&31)<<8|r[e+11]}function kb(r,e,t,s,n,i){const o={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=(r[e+1]&15)<<8|r[e+2],c=e+3+a-4,l=(r[e+10]&15)<<8|r[e+11];for(e+=12+l;e<c;){const d=Zi(r,e),u=(r[e+3]&15)<<8|r[e+4];switch(r[e]){case 207:if(!s){mi("ADTS AAC",i);break}case 15:o.audioPid===-1&&(o.audioPid=d);break;case 21:o.id3Pid===-1&&(o.id3Pid=d);break;case 219:if(!s){mi("H.264",i);break}case 27:o.videoPid===-1&&(o.videoPid=d);break;case 3:case 4:!t.mpeg&&!t.mp3?i.log("MPEG audio found, not supported in this browser"):o.audioPid===-1&&(o.audioPid=d,o.segmentAudioCodec="mp3");break;case 193:if(!s){mi("AC-3",i);break}case 129:t.ac3?o.audioPid===-1&&(o.audioPid=d,o.segmentAudioCodec="ac3"):i.log("AC-3 audio found, not supported in this browser");break;case 6:if(o.audioPid===-1&&u>0){let h=e+5,g=u;for(;g>2;){switch(r[h]){case 106:t.ac3!==!0?i.log("AC-3 audio found, not supported in this browser for now"):(o.audioPid=d,o.segmentAudioCodec="ac3");break}const p=r[h+1]+2;h+=p,g-=p}}break;case 194:case 135:return Ji(n,new Error("Unsupported EC-3 in M2TS found"),void 0,i),o;case 36:o.videoPid===-1&&(o.videoPid=d,o.segmentVideoCodec="hevc",i.log("HEVC in M2TS found"));break}e+=u+5}return o}function Ji(r,e,t,s){s.warn(`parsing error: ${e.message}`),r.emit(S.ERROR,S.ERROR,{type:ce.MEDIA_ERROR,details:B.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function mi(r,e){e.log(`${r} with AES-128-CBC encryption found in unencrypted stream`)}function Ys(r,e){let t=0,s,n,i,o,a;const c=r.data;if(!r||r.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=$t(c[0],c[1]),c.splice(1,1);if(s=c[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(n=(s[4]<<8)+s[5],n&&n>r.size-6)return null;const d=s[7];d&192&&(o=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,d&64?(a=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,o-a>60*9e4&&(e.warn(`${Math.round((o-a)/9e4)}s delta between PTS and DTS, align them`),o=a)):a=o),i=s[8];let u=i+9;if(r.size<=u)return null;r.size-=u;const h=new Uint8Array(r.size);for(let g=0,m=c.length;g<m;g++){s=c[g];let p=s.byteLength;if(u)if(u>p){u-=p;continue}else s=s.subarray(u),p-=u,u=0;h.set(s,t),t+=p}return n&&(n-=i+3),{data:h,pts:o,dts:a,len:n}}return null}class Db{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}}}const ms=Math.pow(2,32)-1;class O{static init(){O.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in O.types)O.types.hasOwnProperty(e)&&(O.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=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]);O.HDLR_TYPES={video:t,audio:s};const n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),i=new Uint8Array([0,0,0,0,0,0,0,0]);O.STTS=O.STSC=O.STCO=i,O.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),O.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),O.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),O.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const o=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);O.FTYP=O.box(O.types.ftyp,o,c,o,a),O.DINF=O.box(O.types.dinf,O.box(O.types.dref,n))}static box(e,...t){let s=8,n=t.length;const i=n;for(;n--;)s+=t[n].byteLength;const o=new Uint8Array(s);for(o[0]=s>>24&255,o[1]=s>>16&255,o[2]=s>>8&255,o[3]=s&255,o.set(e,4),n=0,s=8;n<i;n++)o.set(t[n],s),s+=t[n].byteLength;return o}static hdlr(e){return O.box(O.types.hdlr,O.HDLR_TYPES[e])}static mdat(e){return O.box(O.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(ms+1)),n=Math.floor(t%(ms+1));return O.box(O.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,n>>24,n>>16&255,n>>8&255,n&255,85,196,0,0]))}static mdia(e){return O.box(O.types.mdia,O.mdhd(e.timescale||0,e.duration||0),O.hdlr(e.type),O.minf(e))}static mfhd(e){return O.box(O.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?O.box(O.types.minf,O.box(O.types.smhd,O.SMHD),O.DINF,O.stbl(e)):O.box(O.types.minf,O.box(O.types.vmhd,O.VMHD),O.DINF,O.stbl(e))}static moof(e,t,s){return O.box(O.types.moof,O.mfhd(e),O.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=O.trak(e[t]);return O.box.apply(null,[O.types.moov,O.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(O.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=O.trex(e[t]);return O.box.apply(null,[O.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(ms+1)),n=Math.floor(t%(ms+1)),i=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,n>>24,n>>16&255,n>>8&255,n&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 O.box(O.types.mvhd,i)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let n,i;for(n=0;n<t.length;n++)i=t[n].flags,s[n+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return O.box(O.types.sdtp,s)}static stbl(e){return O.box(O.types.stbl,O.stsd(e),O.box(O.types.stts,O.STTS),O.box(O.types.stsc,O.STSC),O.box(O.types.stsz,O.STSZ),O.box(O.types.stco,O.STCO))}static avc1(e){let t=[],s=[],n,i,o;for(n=0;n<e.sps.length;n++)i=e.sps[n],o=i.byteLength,t.push(o>>>8&255),t.push(o&255),t=t.concat(Array.prototype.slice.call(i));for(n=0;n<e.pps.length;n++)i=e.pps[n],o=i.byteLength,s.push(o>>>8&255),s.push(o&255),s=s.concat(Array.prototype.slice.call(i));const a=O.box(O.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),c=e.width,l=e.height,d=e.pixelRatio[0],u=e.pixelRatio[1];return O.box(O.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,c>>8&255,c&255,l>>8&255,l&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]),a,O.box(O.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),O.box(O.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,u>>24,u>>16&255,u>>8&255,u&255])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return O.box(O.types.mp4a,O.audioStsd(e),O.box(O.types.esds,O.esds(e)))}static mp3(e){return O.box(O.types[".mp3"],O.audioStsd(e))}static ac3(e){return O.box(O.types["ac-3"],O.audioStsd(e),O.box(O.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return O.box(O.types.stsd,O.STSD,O.mp4a(e));if(t==="ac3"&&e.config)return O.box(O.types.stsd,O.STSD,O.ac3(e));if(t==="mp3"&&e.codec==="mp3")return O.box(O.types.stsd,O.STSD,O.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return O.box(O.types.stsd,O.STSD,O.avc1(e));if(t==="hevc"&&e.vps)return O.box(O.types.stsd,O.STSD,O.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,s=(e.duration||0)*(e.timescale||0),n=e.width||0,i=e.height||0,o=Math.floor(s/(ms+1)),a=Math.floor(s%(ms+1));return O.box(O.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,o>>24,o>>16&255,o>>8&255,o&255,a>>24,a>>16&255,a>>8&255,a&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,n>>8&255,n&255,0,0,i>>8&255,i&255,0,0]))}static traf(e,t){const s=O.sdtp(e),n=e.id,i=Math.floor(t/(ms+1)),o=Math.floor(t%(ms+1));return O.box(O.types.traf,O.box(O.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255])),O.box(O.types.tfdt,new Uint8Array([1,0,0,0,i>>24,i>>16&255,i>>8&255,i&255,o>>24,o>>16&255,o>>8&255,o&255])),O.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,O.box(O.types.trak,O.tkhd(e),O.mdia(e))}static trex(e){const t=e.id;return O.box(O.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const s=e.samples||[],n=s.length,i=12+16*n,o=new Uint8Array(i);let a,c,l,d,u,h;for(t+=8+i,o.set([e.type==="video"?1:0,0,15,1,n>>>24&255,n>>>16&255,n>>>8&255,n&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),a=0;a<n;a++)c=s[a],l=c.duration,d=c.size,u=c.flags,h=c.cts,o.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,d>>>24&255,d>>>16&255,d>>>8&255,d&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,h>>>24&255,h>>>16&255,h>>>8&255,h&255],12+16*a);return O.box(O.types.trun,o)}static initSegment(e){O.types||O.init();const t=O.moov(e);return $t(O.FTYP,t)}static hvc1(e){const t=e.params,s=[e.vps,e.sps,e.pps],n=4,i=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),n-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]);let o=i.length;for(let m=0;m<s.length;m+=1){o+=3;for(let p=0;p<s[m].length;p+=1)o+=2+s[m][p].length}const a=new Uint8Array(o);a.set(i,0),o=i.length;const c=s.length-1;for(let m=0;m<s.length;m+=1){a.set(new Uint8Array([32+m|(m===c?128:0),0,s[m].length]),o),o+=3;for(let p=0;p<s[m].length;p+=1)a.set(new Uint8Array([s[m][p].length>>8,s[m][p].length&255]),o),o+=2,a.set(s[m][p],o),o+=s[m][p].length}const l=O.box(O.types.hvcC,a),d=e.width,u=e.height,h=e.pixelRatio[0],g=e.pixelRatio[1];return O.box(O.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,d>>8&255,d&255,u>>8&255,u&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,O.box(O.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),O.box(O.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,g>>24,g>>16&255,g>>8&255,g&255])))}}O.types=void 0;O.HDLR_TYPES=void 0;O.STTS=void 0;O.STSC=void 0;O.STCO=void 0;O.STSZ=void 0;O.VMHD=void 0;O.SMHD=void 0;O.STSD=void 0;O.FTYP=void 0;O.DINF=void 0;const fh=9e4;function da(r,e,t=1,s=!1){const n=r*e*t;return s?Math.round(n):n}function Pb(r,e,t=1,s=!1){return da(r,e,1/t,s)}function hr(r,e=!1){return da(r,1e3,1/fh,e)}function Nb(r,e=1){return da(r,fh,1/e)}function Ll(r){const{baseTime:e,timescale:t,trackId:s}=r;return`${e/t} (${e}/${t}) trackId: ${s}`}const Mb=10*1e3,Fb=1024,Ob=1152,jb=1536;let qs=null,pi=null;function Cl(r,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:r?2:1,isNonSync:r?0:1}}}class mn extends Ut{constructor(e,t,s,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=s,this.ISGenerated=!1,qs===null){const o=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);qs=o?parseInt(o[1]):0}if(pi===null){const i=navigator.userAgent.match(/Safari\/(\d+)/i);pi=i?parseInt(i[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&&Ll(t)} > ${e&&Ll(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 s=e[0].pts,n=e.reduce((i,o)=>{let a=o.pts,c=a-i;return c<-4294967296&&(t=!0,a=_t(a,s),c=a-i),c>0?i:a},s);return t&&this.debug("PTS rollover detected"),n}remux(e,t,s,n,i,o,a,c){let l,d,u,h,g,m,p=i,x=i;const v=e.pid>-1,y=t.pid>-1,b=t.samples.length,T=e.samples.length>0,R=a&&b>0||b>1;if((!v||T)&&(!y||R)||this.ISGenerated||a){if(this.ISGenerated){var w,A,C,L;const D=this.videoTrackConfig;(D&&(t.width!==D.width||t.height!==D.height||((w=t.pixelRatio)==null?void 0:w[0])!==((A=D.pixelRatio)==null?void 0:A[0])||((C=t.pixelRatio)==null?void 0:C[1])!==((L=D.pixelRatio)==null?void 0:L[1]))||!D&&R||this.nextAudioTs===null&&T)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,i,o));const P=this.isVideoContiguous;let M=-1,j;if(R&&(M=Bb(t.samples),!P&&this.config.forceKeyFrameOnDiscontinuity))if(m=!0,M>0){this.warn(`Dropped ${M} out of ${b} video samples due to a missing keyframe`);const D=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(M),t.dropped+=M,x+=(t.samples[0].pts-D)/t.inputTimeScale,j=x}else M===-1&&(this.warn(`No keyframe found out of ${b} video samples`),m=!1);if(this.ISGenerated){if(T&&R){const D=this.getVideoStartPts(t.samples),N=(_t(e.samples[0].pts,D)-D)/t.inputTimeScale;p+=Math.max(0,N),x+=Math.max(0,-N)}if(T){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(e,t,i,o)),d=this.remuxAudio(e,p,this.isAudioContiguous,o,y||R||c===oe.AUDIO?x:void 0),R){const D=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(e,t,i,o)),l=this.remuxVideo(t,x,P,D)}}else R&&(l=this.remuxVideo(t,x,P,0));l&&(l.firstKeyFrame=M,l.independent=M!==-1,l.firstKeyFramePTS=j)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(g=hh(s,i,this._initPTS,this._initDTS)),n.samples.length&&(h=gh(n,i,this._initPTS))),{audio:d,video:l,initSegment:u,independent:m,text:h,id3:g}}computeInitPts(e,t,s,n){const i=Math.round(s*t);let o=_t(e,i);if(o<i+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(i-o)/t} ${n}`);o<i+t;)o+=8589934592;return o-i}generateIS(e,t,s,n){const i=e.samples,o=t.samples,a=this.typeSupported,c={},l=this._initPTS;let d=!l||n,u="audio/mp4",h,g,m,p=-1;if(d&&(h=g=1/0),e.config&&i.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(u="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}c.audio={id:"audio",container:u,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&a.mpeg?new Uint8Array(0):O.initSegment([e]),metadata:{channelCount:e.channelCount}},d&&(p=e.id,m=e.inputTimeScale,!l||m!==l.timescale?h=g=this.computeInitPts(i[0].pts,m,s,"audio"):d=!1)}if(t.sps&&t.pps&&o.length){if(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:O.initSegment([t]),metadata:{width:t.width,height:t.height}},d)if(p=t.id,m=t.inputTimeScale,!l||m!==l.timescale){const x=this.getVideoStartPts(o),v=_t(o[0].dts,x),y=this.computeInitPts(v,m,s,"video"),b=this.computeInitPts(x,m,s,"video");g=Math.min(g,y),h=Math.min(h,b)}else d=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(c).length)return this.ISGenerated=!0,d?(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${s} ${h/m} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${h/m} (${h}/${m}) trackId: ${p}`),this._initPTS={baseTime:h,timescale:m,trackId:p},this._initDTS={baseTime:g,timescale:m,trackId:p}):h=m=void 0,{tracks:c,initPTS:h,timescale:m,trackId:p}}remuxVideo(e,t,s,n){const i=e.inputTimeScale,o=e.samples,a=[],c=o.length,l=this._initPTS,d=l.baseTime*i/l.timescale;let u=this.nextVideoTs,h=8,g=this.videoSampleDuration,m,p,x=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,y=!1;if(!s||u===null){const U=d+t*i,K=o[0].pts-_t(o[0].dts,o[0].pts);qs&&u!==null&&Math.abs(U-K-(u+d))<15e3?s=!0:u=U-K-d}const b=u+d;for(let U=0;U<c;U++){const K=o[U];K.pts=_t(K.pts,b),K.dts=_t(K.dts,b),K.dts<o[U>0?U-1:U].dts&&(y=!0)}y&&o.sort(function(U,K){const G=U.dts-K.dts,H=U.pts-K.pts;return G||H}),m=o[0].dts,p=o[o.length-1].dts;const T=p-m,R=T?Math.round(T/(c-1)):g||e.inputTimeScale/30;if(s){const U=m-b,K=U>R,G=U<-1;if((K||G)&&(K?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${hr(U,!0)} ms (${U}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${hr(-U,!0)} ms (${U}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!G||b>=o[0].pts||qs)){m=b;const H=o[0].pts-U;if(K)o[0].dts=m,o[0].pts=H;else{let q=!0;for(let J=0;J<o.length&&!(o[J].dts>H&&q);J++){const ee=o[J].pts;if(o[J].dts-=U,o[J].pts-=U,J<o.length-1){const te=o[J+1].pts,de=o[J].pts,ie=te<=de,ue=te<=ee;q=ie==ue}}}this.log(`Video: Initial PTS/DTS adjusted: ${hr(H,!0)}/${hr(m,!0)}, delta: ${hr(U,!0)} ms`)}}m=Math.max(0,m);let _=0,w=0,A=m;for(let U=0;U<c;U++){const K=o[U],G=K.units,H=G.length;let q=0;for(let J=0;J<H;J++)q+=G[J].data.length;w+=q,_+=H,K.length=q,K.dts<A?(K.dts=A,A+=R/4|0||1):A=K.dts,x=Math.min(K.pts,x),v=Math.max(K.pts,v)}p=o[c-1].dts;const C=w+4*_+8;let L;try{L=new Uint8Array(C)}catch(U){this.observer.emit(S.ERROR,S.ERROR,{type:ce.MUX_ERROR,details:B.REMUX_ALLOC_ERROR,fatal:!1,error:U,bytes:C,reason:`fail allocating video mdat ${C}`});return}const P=new DataView(L.buffer);P.setUint32(0,C),L.set(O.types.mdat,4);let M=!1,j=Number.POSITIVE_INFINITY,D=Number.POSITIVE_INFINITY,$=Number.NEGATIVE_INFINITY,N=Number.NEGATIVE_INFINITY;for(let U=0;U<c;U++){const K=o[U],G=K.units;let H=0;for(let ee=0,te=G.length;ee<te;ee++){const de=G[ee],ie=de.data,ue=de.data.byteLength;P.setUint32(h,ue),h+=4,L.set(ie,h),h+=ue,H+=4+ue}let q;if(U<c-1)g=o[U+1].dts-K.dts,q=o[U+1].pts-K.pts;else{const ee=this.config,te=U>0?K.dts-o[U-1].dts:R;if(q=U>0?K.pts-o[U-1].pts:R,ee.stretchShortVideoTrack&&this.nextAudioTs!==null){const de=Math.floor(ee.maxBufferHole*i),ie=(n?x+n*i:this.nextAudioTs+d)-K.pts;ie>de?(g=ie-te,g<0?g=te:M=!0,this.log(`It is approximately ${ie/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=te}else g=te}const J=Math.round(K.pts-K.dts);j=Math.min(j,g),$=Math.max($,g),D=Math.min(D,q),N=Math.max(N,q),a.push(Cl(K.key,g,H,J))}if(a.length){if(qs){if(qs<70){const U=a[0].flags;U.dependsOn=2,U.isNonSync=0}}else if(pi&&N-D<$-j&&R/$<.025&&a[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let U=m;for(let K=0,G=a.length;K<G;K++){const H=U+a[K].duration,q=U+a[K].cts;if(K<G-1){const J=H+a[K+1].cts;a[K].duration=J-q}else a[K].duration=K?a[K-1].duration:R;a[K].cts=0,U=H}}}g=M||!g?R:g;const F=p+g;this.nextVideoTs=u=F-d,this.videoSampleDuration=g,this.isVideoContiguous=!0;const Y={data1:O.moof(e.sequenceNumber++,m,De(e,{samples:a})),data2:L,startPTS:(x-d)/i,endPTS:(v+g-d)/i,startDTS:(m-d)/i,endDTS:u/i,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 Ob;case"ac3":return jb;default:return Fb}}remuxAudio(e,t,s,n,i){const o=e.inputTimeScale,a=e.samplerate?e.samplerate:o,c=o/a,l=this.getSamplesPerFrame(e),d=l*c,u=this._initPTS,h=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,g=[],m=i!==void 0;let p=e.samples,x=h?0:8,v=this.nextAudioTs||-1;const y=u.baseTime*o/u.timescale,b=y+t*o;if(this.isAudioContiguous=s=s||p.length&&v>0&&(n&&Math.abs(b-(v+y))<9e3||Math.abs(_t(p[0].pts,b)-(v+y))<20*d),p.forEach(function(N){N.pts=_t(N.pts,b)}),!s||v<0){const N=p.length;if(p=p.filter(F=>F.pts>=0),N!==p.length&&this.warn(`Removed ${p.length-N} of ${N} samples (initPTS ${y} / ${o})`),!p.length)return;i===0?v=0:n&&!m?v=Math.max(0,b-y):v=p[0].pts-y}if(e.segmentCodec==="aac"){const N=this.config.maxAudioFramesDrift;for(let F=0,k=v+y;F<p.length;F++){const z=p[F],Y=z.pts,U=Y-k,K=Math.abs(1e3*U/o);if(U<=-N*d&&m)F===0&&(this.warn(`Audio frame @ ${(Y/o).toFixed(3)}s overlaps marker by ${Math.round(1e3*U/o)} ms.`),this.nextAudioTs=v=Y-y,k=Y);else if(U>=N*d&&K<Mb&&m){let G=Math.round(U/d);for(k=Y-G*d;k<0&&G&&d;)G--,k+=d;F===0&&(this.nextAudioTs=v=k-y),this.warn(`Injecting ${G} audio frames @ ${((k-y)/o).toFixed(3)}s due to ${Math.round(1e3*U/o)} ms gap.`);for(let H=0;H<G;H++){let q=Db.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);q||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),q=z.unit.subarray()),p.splice(F,0,{unit:q,pts:k}),k+=d,F++}}z.pts=k,k+=d}}let T=null,R=null,_,w=0,A=p.length;for(;A--;)w+=p[A].unit.byteLength;for(let N=0,F=p.length;N<F;N++){const k=p[N],z=k.unit;let Y=k.pts;if(R!==null){const K=g[N-1];K.duration=Math.round((Y-R)/c)}else if(s&&e.segmentCodec==="aac"&&(Y=v+y),T=Y,w>0){w+=x;try{_=new Uint8Array(w)}catch(K){this.observer.emit(S.ERROR,S.ERROR,{type:ce.MUX_ERROR,details:B.REMUX_ALLOC_ERROR,fatal:!1,error:K,bytes:w,reason:`fail allocating audio mdat ${w}`});return}h||(new DataView(_.buffer).setUint32(0,w),_.set(O.types.mdat,4))}else return;_.set(z,x);const U=z.byteLength;x+=U,g.push(Cl(!0,l,U,0)),R=Y}const C=g.length;if(!C)return;const L=g[g.length-1];v=R-y,this.nextAudioTs=v+c*L.duration;const P=h?new Uint8Array(0):O.moof(e.sequenceNumber++,T/c,De({},e,{samples:g}));e.samples=[];const M=(T-y)/o,j=this.nextAudioTs/o,$={data1:P,data2:_,startPTS:M,endPTS:j,startDTS:M,endDTS:j,type:"audio",hasAudio:!0,hasVideo:!1,nb:C};return this.isAudioContiguous=!0,$}}function _t(r,e){let t;if(e===null)return r;for(e<r?t=-8589934592:t=8589934592;Math.abs(r-e)>4294967296;)r+=t;return r}function Bb(r){for(let e=0;e<r.length;e++)if(r[e].key)return e;return-1}function hh(r,e,t,s){const n=r.samples.length;if(!n)return;const i=r.inputTimeScale;for(let a=0;a<n;a++){const c=r.samples[a];c.pts=_t(c.pts-t.baseTime*i/t.timescale,e*i)/i,c.dts=_t(c.dts-s.baseTime*i/s.timescale,e*i)/i}const o=r.samples;return r.samples=[],{samples:o}}function gh(r,e,t){const s=r.samples.length;if(!s)return;const n=r.inputTimeScale;for(let o=0;o<s;o++){const a=r.samples[o];a.pts=_t(a.pts-t.baseTime*n/t.timescale,e*n)/n}r.samples.sort((o,a)=>o.pts-a.pts);const i=r.samples;return r.samples=[],{samples:i}}class $b extends Ut{constructor(e,t,s,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,s,n){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,n),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:n}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:i,video:o}=this.initData=bf(e);if(t)Iv(e,t);else{const c=i||o;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}i&&(s=_l(i,Pe.AUDIO,this)),o&&(n=_l(o,Pe.VIDEO,this));const a={};i&&o?a.audiovideo={container:"video/mp4",codec:s+","+n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:i?a.audio={container:"audio/mp4",codec:s,encrypted:i.encrypted,initSegment:e,id:"audio"}:o?a.video={container:"video/mp4",codec:n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(e,t,s,n,i,o){var a,c;let{initPTS:l,lastEndTime:d}=this;const u={audio:void 0,video:void 0,text:n,id3:s,initSegment:void 0};ne(d)||(d=this.lastEndTime=i||0);const h=t.samples;if(!h.length)return u;const g={initPTS:void 0,timescale:void 0,trackId:void 0};let m=this.initData;if((a=m)!=null&&a.length||(this.generateInitSegment(h),m=this.initData),!((c=m)!=null&&c.length))return this.warn("Failed to generate initSegment."),u;this.emitInitSegment&&(g.tracks=this.initTracks,this.emitInitSegment=!1);const p=Cv(h,m,this),x=m.audio?p[m.audio.id]:null,v=m.video?p[m.video.id]:null,y=tn(v,1/0),b=tn(x,1/0),T=tn(v,0,!0),R=tn(x,0,!0);let _=i,w=0;const A=x&&(!v||!l&&b<y||l&&l.trackId===m.audio.id),C=A?x:v;if(C){const k=C.timescale,z=C.start-i*k,Y=A?m.audio.id:m.video.id;_=C.start/k,w=A?R-b:T-y,(o||!l)&&(Ub(l,_,i,w)||k!==l.timescale)&&(l&&this.warn(`Timestamps at playlist time: ${o?"":"~"}${i} ${z/k} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${_-i} (${z}/${k}) trackId: ${Y}`),l=null,g.initPTS=z,g.timescale=k,g.trackId=Y)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${i}`);l?(g.initPTS=l.baseTime,g.timescale=l.timescale,g.trackId=l.trackId):((!g.timescale||g.trackId===void 0||g.initPTS===void 0)&&(this.warn("Could not set initPTS"),g.initPTS=_,g.timescale=1,g.trackId=-1),this.initPTS=l={baseTime:g.initPTS,timescale:g.timescale,trackId:g.trackId});const L=_-l.baseTime/l.timescale,P=L+w;w>0?this.lastEndTime=P:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const M=!!m.audio,j=!!m.video;let D="";M&&(D+="audio"),j&&(D+="video");const $=(m.audio?m.audio.encrypted:!1)||(m.video?m.video.encrypted:!1),N={data1:h,startPTS:L,startDTS:L,endPTS:P,endDTS:P,type:D,hasAudio:M,hasVideo:j,nb:1,dropped:0,encrypted:$};u.audio=M&&!j?N:void 0,u.video=j?N:void 0;const F=v==null?void 0:v.sampleCount;if(F){const k=v.keyFrameIndex,z=k!==-1;N.nb=F,N.dropped=k===0||this.isVideoContiguous?0:z?k:F,N.independent=z,N.firstKeyFrame=k,z&&v.keyFrameStart&&(N.firstKeyFramePTS=(v.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(u.independent=z),this.isVideoContiguous||(this.isVideoContiguous=z),N.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${k}/${F} dropped: ${N.dropped} start: ${N.firstKeyFramePTS||"NA"}`)}return u.initSegment=g,u.id3=hh(s,i,l,l),n.samples.length&&(u.text=gh(n,i,l)),u}}function tn(r,e,t=!1){return(r==null?void 0:r.start)!==void 0?(r.start+(t?r.duration:0))/r.timescale:e}function Ub(r,e,t,s){if(r===null)return!0;const n=Math.max(s,1),i=e-r.baseTime/r.timescale;return Math.abs(i-t)>n}function _l(r,e,t){const s=r.codec;return s&&s.length>4?s:e===Pe.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?Rn(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}let us;try{us=self.performance.now.bind(self.performance)}catch{us=Date.now}const pn=[{demux:Ab,remux:$b},{demux:vs,remux:mn},{demux:Eb,remux:mn},{demux:wb,remux:mn}];pn.splice(2,0,{demux:Tb,remux:mn});class kl{constructor(e,t,s,n,i,o){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=s,this.id=i,this.logger=o}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,n){const i=s.transmuxing;i.executeStart=us();let o=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:c}=this;n&&(this.currentTransmuxState=n);const{contiguous:l,discontinuity:d,trackSwitch:u,accurateTimeOffset:h,timeOffset:g,initSegmentChange:m}=n||a,{audioCodec:p,videoCodec:x,defaultInitPts:v,duration:y,initSegmentData:b}=c,T=Gb(o,t);if(T&&Js(T.method)){const A=this.getDecrypter(),C=ta(T.method);if(A.isSync()){let L=A.softwareDecrypt(o,T.key.buffer,T.iv.buffer,C);if(s.part>-1){const M=A.flush();L=M&&M.buffer}if(!L)return i.executeEnd=us(),xi(s);o=new Uint8Array(L)}else return this.asyncResult=!0,this.decryptionPromise=A.webCryptoDecrypt(o,T.key.buffer,T.iv.buffer,C).then(L=>{const P=this.push(L,null,s);return this.decryptionPromise=null,P}),this.decryptionPromise}const R=this.needsProbing(d,u);if(R){const A=this.configureTransmuxer(o);if(A)return this.logger.warn(`[transmuxer] ${A.message}`),this.observer.emit(S.ERROR,S.ERROR,{type:ce.MEDIA_ERROR,details:B.FRAG_PARSING_ERROR,fatal:!1,error:A,reason:A.message}),i.executeEnd=us(),xi(s)}(d||u||m||R)&&this.resetInitSegment(b,p,x,y,t),(d||m||R)&&this.resetInitialTimestamp(v),l||this.resetContiguity();const _=this.transmux(o,T,g,h,s);this.asyncResult=Mr(_);const w=this.currentTransmuxState;return w.contiguous=!0,w.discontinuity=!1,w.trackSwitch=!1,i.executeEnd=us(),_}flush(e){const t=e.transmuxing;t.executeStart=us();const{decrypter:s,currentTransmuxState:n,decryptionPromise:i}=this;if(i)return this.asyncResult=!0,i.then(()=>this.flush(e));const o=[],{timeOffset:a}=n;if(s){const u=s.flush();u&&o.push(this.push(u.buffer,null,e))}const{demuxer:c,remuxer:l}=this;if(!c||!l){t.executeEnd=us();const u=[xi(e)];return this.asyncResult?Promise.resolve(u):u}const d=c.flush(a);return Mr(d)?(this.asyncResult=!0,d.then(u=>(this.flushRemux(o,u,e),o))):(this.flushRemux(o,d,e),this.asyncResult?Promise.resolve(o):o)}flushRemux(e,t,s){const{audioTrack:n,videoTrack:i,id3Track:o,textTrack:a}=t,{accurateTimeOffset:c,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===oe.MAIN?"level":"track"} ${s.level}`);const d=this.remuxer.remux(n,i,o,a,l,c,!0,this.id);e.push({remuxResult:d,chunkMeta:s}),s.transmuxing.executeEnd=us()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,n,i){const{demuxer:o,remuxer:a}=this;!o||!a||(o.resetInitSegment(e,t,s,n),a.resetInitSegment(e,t,s,i))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,n,i){let o;return t&&t.method==="SAMPLE-AES"?o=this.transmuxSampleAes(e,t,s,n,i):o=this.transmuxUnencrypted(e,s,n,i),o}transmuxUnencrypted(e,t,s,n){const{audioTrack:i,videoTrack:o,id3Track:a,textTrack:c}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(i,o,a,c,t,s,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,s,n,i){return this.demuxer.demuxSampleAes(e,t,s).then(o=>({remuxResult:this.remuxer.remux(o.audioTrack,o.videoTrack,o.id3Track,o.textTrack,s,n,!1,this.id),chunkMeta:i}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:n}=this;let i;for(let u=0,h=pn.length;u<h;u++){var o;if((o=pn[u].demux)!=null&&o.probe(e,this.logger)){i=pn[u];break}}if(!i)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,c=this.remuxer,l=i.remux,d=i.demux;(!c||!(c instanceof l))&&(this.remuxer=new l(s,t,n,this.logger)),(!a||!(a instanceof d))&&(this.demuxer=new d(s,t,n,this.logger),this.probe=d.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Jo(this.config)),e}}function Gb(r,e){let t=null;return r.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const xi=r=>({remuxResult:{},chunkMeta:r});function Mr(r){return"then"in r&&r.then instanceof Function}class Vb{constructor(e,t,s,n,i){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=n,this.defaultInitPts=i||null}}class Hb{constructor(e,t,s,n,i,o){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=s,this.trackSwitch=n,this.timeOffset=i,this.initSegmentChange=o}}let Dl=0;class mh{constructor(e,t,s,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Dl++,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=c=>{const l=c.data,d=this.hls;if(!(!d||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var u;const h=(u=this.workerContext)==null?void 0:u.objectURL;h&&self.URL.revokeObjectURL(h);break}case"transmuxComplete":{this.handleTransmuxComplete(l.data);break}case"flush":{this.onFlush(l.data);break}case"workerLog":{d.logger[l.data.logType]&&d.logger[l.data.logType](l.data.message);break}default:{l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,d.trigger(l.event,l.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const l=new Error(`${c.message} (${c.filename}:${c.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(S.ERROR,{type:ce.OTHER_ERROR,details:B.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};const i=e.config;this.hls=e,this.id=t,this.useWorker=!!i.enableWorker,this.onTransmuxComplete=s,this.onFlush=n;const o=(c,l)=>{l=l||{},l.frag=this.frag||void 0,c===S.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(c,l)};this.observer=new na,this.observer.on(S.FRAG_DECRYPTED,o),this.observer.on(S.ERROR,o);const a=Wa(i.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(i.workerPath||Yy()){try{i.workerPath?(c.log(`loading Web Worker ${i.workerPath} for "${t}"`),this.workerContext=Xy(i.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=qy());const{worker:d}=this.workerContext;d.addEventListener("message",this.onWorkerMessage),d.addEventListener("error",this.onWorkerError),d.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:Ne(i)})}catch(d){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,d),this.terminateWorker(),this.error=null,this.transmuxer=new kl(this.observer,a,i,"",t,e.logger)}return}}this.transmuxer=new kl(this.observer,a,i,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Dl++;const t=this.hls.config,s=Wa(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:Ne(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),Qy(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,s,n,i,o,a,c,l,d){var u,h;l.transmuxing.start=self.performance.now();const{instanceNo:g,transmuxer:m}=this,p=o?o.start:i.start,x=i.decryptdata,v=this.frag,y=!(v&&i.cc===v.cc),b=!(v&&l.level===v.level),T=v?l.sn-v.sn:-1,R=this.part?l.part-this.part.index:-1,_=T===0&&l.id>1&&l.id===(v==null?void 0:v.stats.chunkCount),w=!b&&(T===1||T===0&&(R===1||_&&R<=0)),A=self.performance.now();(b||T||i.stats.parsing.start===0)&&(i.stats.parsing.start=A),o&&(R||!w)&&(o.stats.parsing.start=A);const C=!(v&&((u=i.initSegment)==null?void 0:u.url)===((h=v.initSegment)==null?void 0:h.url)),L=new Hb(y,w,c,b,p,C);if(!w||y||C){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===oe.MAIN?"level":"track"}: ${l.level} id: ${l.id}
51
+ discontinuity: ${y}
52
+ trackSwitch: ${b}
53
+ contiguous: ${w}
54
+ accurateTimeOffset: ${c}
55
+ timeOffset: ${p}
56
+ initSegmentChange: ${C}`);const P=new Vb(s,n,t,a,d);this.configureTransmuxer(P)}if(this.frag=i,this.part=o,this.workerContext)this.workerContext.worker.postMessage({instanceNo:g,cmd:"demux",data:e,decryptdata:x,chunkMeta:l,state:L},e instanceof ArrayBuffer?[e]:[]);else if(m){const P=m.push(e,x,l,L);Mr(P)?P.then(M=>{this.handleTransmuxComplete(M)}).catch(M=>{this.transmuxerError(M,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(P)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const n=s.flush(e);Mr(n)?n.then(i=>{this.handleFlushResult(i,e)}).catch(i=>{this.transmuxerError(i,e,"transmuxer-interface flush error")}):this.handleFlushResult(n,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(S.ERROR,{type:ce.MEDIA_ERROR,details:B.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const Pl=100;class Kb extends ra{constructor(e,t,s){super(e,t,s,"audio-stream-controller",oe.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(S.LEVEL_LOADED,this.onLevelLoaded,this),e.on(S.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(S.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(S.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(S.BUFFER_RESET,this.onBufferReset,this),e.on(S.BUFFER_CREATED,this.onBufferCreated,this),e.on(S.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(S.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(S.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(S.FRAG_LOADING,this.onFragLoading,this),e.on(S.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(S.LEVEL_LOADED,this.onLevelLoaded,this),e.off(S.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(S.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(S.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(S.BUFFER_RESET,this.onBufferReset,this),e.off(S.BUFFER_CREATED,this.onBufferCreated,this),e.off(S.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(S.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(S.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(S.FRAG_LOADING,this.onFragLoading,this),e.off(S.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:s,initPTS:n,timescale:i,trackId:o}){if(s===oe.MAIN){const a=t.cc,c=this.fragCurrent;if(this.initPTS[a]={baseTime:n,timescale:i,trackId:o},this.log(`InitPTS for cc: ${a} found from main: ${n/i} (${n}/${i}) trackId: ${o}`),this.mainAnchor=t,this.state===X.WAITING_INIT_PTS){const l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==a)&&this.syncWithAnchor(t,l==null?void 0:l.frag)}else!this.hls.hasEnoughToStart&&c&&c.cc!==a?(c.abortRequests(),this.syncWithAnchor(t,c)):this.state===X.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;const n=((s=this.mainFragLoading)==null?void 0:s.frag)||null;if(t&&(n==null?void 0:n.cc)===t.cc)return;const i=(n||e).cc,o=this.getLevelDetails(),a=this.getLoadPosition(),c=kf(o,i,a);c&&(this.log(`Syncing with main frag at ${c.start} cc ${c.cc}`),this.startFragRequested=!1,this.nextLoadPosition=c.start,this.resetLoadingState(),this.state===X.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=X.STOPPED;return}const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(Pl),s>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,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,s=e==null?void 0:e[t],n=s==null?void 0:s.details;if(n&&!this.waitForLive(s)){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:s,cache:n,complete:i}=e,o=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=X.FRAG_LOADING;const a=n.flush().buffer,c={frag:t,part:s,payload:a,networkDetails:null};this._handleFragmentLoadProgress(c),i&&super._handleFragmentLoadComplete(c)}else o&&o.cc!==e.frag.cc&&this.syncWithAnchor(o,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:s,media:n,trackId:i}=this,o=t.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!o.startFragPrefetch)||!(s!=null&&s[i]))return;const a=s[i],c=a.details;if(!c||this.waitForLive(a)||this.waitForCdnTuneIn(c)){this.state=X.WAITING_TRACK,this.startFragRequested=!1;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,Pe.AUDIO,oe.AUDIO));const d=this.getFwdBufferInfo(l,oe.AUDIO);if(d===null)return;if(!this.switchingTrack&&this._streamEnded(d,c)){t.trigger(S.BUFFER_EOS,{type:"audio"}),this.state=X.ENDED;return}const u=d.len,h=t.maxBufferLength,g=c.fragments,m=g[0].start,p=this.getLoadPosition(),x=this.flushing?p:d.end;if(this.switchingTrack&&n){const b=p;c.PTSKnown&&b<m&&(d.end>m||d.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=m+.05)}if(u>=h&&!this.switchingTrack&&x<g[g.length-1].start)return;let v=this.getNextFragment(x,c);if(v&&this.isLoopLoading(v,x)&&(v=this.getNextFragmentLoopLoading(v,c,d,oe.MAIN,h)),!v){this.bufferFlushed=!0;return}let y=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&qe(v)&&!v.endList&&(!c.live||!this.loadingParts&&x<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===rt.OK&&(this.mainFragLoading=y=null),y&&qe(y))){if(v.start>y.end){const T=this.fragmentTracker.getFragAtPos(x,oe.MAIN);T&&T.end>y.end&&(y=T,this.mainFragLoading={frag:T,targetBufferTime:null})}if(v.start>y.end)return}this.loadFragment(v,a,x)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new Dr(s))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:n}=this;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==X.STOPPED&&(this.setInterval(Pl),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 s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(S.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:n}=this,{details:i,id:o,groupId:a,track:c}=t;if(!n){this.warn(`Audio tracks reset while loading track ${o} "${c.name}" of "${a}"`);return}const l=this.mainDetails;if(!l||i.endCC>l.endCC||l.expired){this.cachedTrackLoadedData=t,this.state!==X.STOPPED&&(this.state=X.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${o} "${c.name}" of "${a}" loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:""},duration:${i.totalduration}`);const d=n[o];let u=0;if(i.live||(s=d.details)!=null&&s.live){if(this.checkLiveUpdate(i),i.deltaUpdateFailed)return;if(d.details){var h;u=this.alignPlaylists(i,d.details,(h=this.levelLastLoaded)==null?void 0:h.details)}i.alignedSliding||(qf(i,l),i.alignedSliding||Dn(i,l),u=i.fragmentStart)}d.details=i,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(l,u),this.hls.trigger(S.AUDIO_TRACK_UPDATED,{details:i,id:o,groupId:t.groupId}),this.state===X.WAITING_TRACK&&!this.waitForCdnTuneIn(i)&&(this.state=X.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:n,payload:i}=e,{config:o,trackId:a,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const l=c[a];if(!l){this.warn("Audio track is undefined on fragment load progress");return}const d=l.details;if(!d){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const u=o.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let h=this.transmuxer;h||(h=this.transmuxer=new mh(this.hls,oe.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const g=this.initPTS[s.cc],m=(t=s.initSegment)==null?void 0:t.data;if(g!==void 0){const x=n?n.index:-1,v=x!==-1,y=new ea(s.level,s.sn,s.stats.chunkCount,i.byteLength,x,v);h.push(i,m,u,"",s,n,d.totalduration,!1,y,g)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${d.startSN} ,${d.endSN}],track ${a}`);const{cache:p}=this.waitingData=this.waitingData||{frag:s,part:n,cache:new Xf,complete:!1};p.push(new Uint8Array(i)),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 s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===oe.MAIN&&qe(t.frag)&&(this.mainFragLoading=t,this.state===X.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:n}=t;if(s.type!==oe.AUDIO){!this.audioOnly&&s.type===oe.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${n?" p: "+n.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(qe(s)){this.fragPrevious=s;const i=this.switchingTrack;i&&(this.bufferedTrack=i,this.switchingTrack=null,this.hls.trigger(S.AUDIO_TRACK_SWITCHED,_e({},i)))}this.fragBufferedComplete(s,n),this.media&&this.tick()}onError(e,t){var s;if(t.fatal){this.state=X.ERROR;return}switch(t.details){case B.FRAG_GAP:case B.FRAG_PARSING_ERROR:case B.FRAG_DECRYPT_ERROR:case B.FRAG_LOAD_ERROR:case B.FRAG_LOAD_TIMEOUT:case B.KEY_LOAD_ERROR:case B.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(oe.AUDIO,t);break;case B.AUDIO_TRACK_LOAD_ERROR:case B.AUDIO_TRACK_LOAD_TIMEOUT:case B.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===X.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===Te.AUDIO_TRACK&&(this.state=X.IDLE);break;case B.BUFFER_ADD_CODEC_ERROR:case B.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case B.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case B.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==Pe.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==Pe.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===X.ENDED&&(this.state=X.IDLE);const s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,oe.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:n}=this,{remuxResult:i,chunkMeta:o}=e,a=this.getCurrentContext(o);if(!a){this.resetWhenMissingContext(o);return}const{frag:c,part:l,level:d}=a,{details:u}=d,{audio:h,text:g,id3:m,initSegment:p}=i;if(this.fragContextChanged(c)||!u){this.fragmentTracker.removeFragment(c);return}if(this.state=X.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){const x=c.initSegment||c;if(this.unhandledEncryptionError(p,c))return;this._bufferInitSegment(d,p.tracks,x,o),n.trigger(S.FRAG_PARSING_INIT_SEGMENT,{frag:x,id:s,tracks:p.tracks})}if(h){const{startPTS:x,endPTS:v,startDTS:y,endDTS:b}=h;l&&(l.elementaryStreams[Pe.AUDIO]={startPTS:x,endPTS:v,startDTS:y,endDTS:b}),c.setElementaryStreamInfo(Pe.AUDIO,x,v,y,b),this.bufferFragmentData(h,c,l,o)}if(m!=null&&(t=m.samples)!=null&&t.length){const x=De({id:s,frag:c,details:u},m);n.trigger(S.FRAG_PARSING_METADATA,x)}if(g){const x=De({id:s,frag:c,details:u},g);n.trigger(S.FRAG_PARSING_USERDATA,x)}}_bufferInitSegment(e,t,s,n){if(this.state!==X.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const i=t.audio;i.id=oe.AUDIO;const o=e.audioCodec;this.log(`Init audio buffer, container:${i.container}, codecs[level/parsed]=[${o}/${i.codec}]`),o&&o.split(",").length===1&&(i.levelCodec=o),this.hls.trigger(S.BUFFER_CODECS,t);const a=i.initSegment;if(a!=null&&a.byteLength){const c={type:"audio",frag:s,part:null,chunkMeta:n,parent:s.type,data:a};this.hls.trigger(S.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(e,t,s){const n=this.fragmentTracker.getState(e);if(this.switchingTrack||n===rt.NOT_LOADED||n===rt.PARTIAL){var i;if(!qe(e))this._loadInitSegment(e,t);else if((i=t.details)!=null&&i.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=X.WAITING_INIT_PTS;const o=this.mainDetails;o&&o.fragmentStart!==t.details.fragmentStart&&Dn(t.details,o)}else super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:s,assocLang:n,characteristics:i,audioCodec:o,channels:a}=this.bufferedTrack;Ns({name:t,lang:s,assocLang:n,characteristics:i,audioCodec:o,channels:a},e,Ds)||(In(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(S.AUDIO_TRACK_SWITCHED,_e({},e))}}class ua extends Ut{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,s){const n=t==null?void 0:t.renditionReports;if(n){let i=-1;for(let o=0;o<n.length;o++){const a=n[o];let c;try{c=new self.URL(a.URI,t.url).href}catch(l){this.warn(`Could not construct new URL for Rendition Report: ${l}`),c=a.URI||""}if(c===e){i=o;break}else c===e.substring(0,c.length)&&(i=o)}if(i!==-1){const o=n[i],a=parseInt(o["LAST-MSN"])||t.lastPartSn;let c=parseInt(o["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const d=Math.min(t.age-t.partTarget,t.targetduration);c>=0&&d>t.partTarget&&(c+=1)}const l=s&&Ya(s);return new qa(a,c>=0?c:void 0,l)}}}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(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){const{details:n,stats:i}=t,o=self.performance.now(),a=i.loading.first?Math.max(0,o-i.loading.first):0;n.advancedDateTime=Date.now()-a;const c=this.hls.config.timelineOffset;if(c!==n.appliedTimelineOffset){const d=Math.max(c||0,0);n.appliedTimelineOffset=d,n.fragments.forEach(u=>{u.setStart(u.playlistOffset+d)})}if(n.live||s!=null&&s.live){const d="levelInfo"in t?t.levelInfo:t.track;if(n.reloaded(s),s&&n.fragments.length>0){Oy(s,n,this);const y=n.playlistParsingError;if(y){this.warn(y);const b=this.hls;if(!b.config.ignorePlaylistParsingErrors){var l;const{networkDetails:T}=t;b.trigger(S.ERROR,{type:ce.NETWORK_ERROR,details:B.LEVEL_PARSING_ERROR,fatal:!1,url:n.url,error:y,reason:y.message,level:t.level||void 0,parent:(l=n.fragments[0])==null?void 0:l.type,networkDetails:T,stats:i});return}n.playlistParsingError=null}}n.requestScheduled===-1&&(n.requestScheduled=i.loading.start);const u=this.hls.mainForwardBufferInfo,h=u?u.end-u.len:0,g=(n.edge-h)*1e3,m=Hf(n,g);if(n.requestScheduled+m<o?n.requestScheduled=o:n.requestScheduled+=m,this.log(`live playlist ${e} ${n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:n.updated?"UPDATED":"MISSED"}`),!this.canLoad||!n.live)return;let p,x,v;if(n.canBlockReload&&n.endSN&&n.advanced){const y=this.hls.config.lowLatencyMode,b=n.lastPartSn,T=n.endSN,R=n.lastPartIndex,_=R!==-1,w=b===T;_?w?(x=T+1,v=y?0:R):(x=b,v=y?R+1:n.maxPartIndex):x=T+1;const A=n.age,C=A+n.ageHeader;let L=Math.min(C-n.partTarget,n.targetduration*1.5);if(L>0){if(C>n.targetduration*3)this.log(`Playlist last advanced ${A.toFixed(2)}s ago. Omitting segment and part directives.`),x=void 0,v=void 0;else if(s!=null&&s.tuneInGoal&&C-n.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${L} with playlist age: ${n.age}`),L=0;else{const P=Math.floor(L/n.targetduration);if(x+=P,v!==void 0){const M=Math.round(L%n.targetduration/n.partTarget);v+=M}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${A.toFixed(2)}s goal: ${L} skip sn ${P} to part ${v}`)}n.tuneInGoal=L}if(p=this.getDeliveryDirectives(n,t.deliveryDirectives,x,v),y||!w){n.requestScheduled=o,this.loadingPlaylist(d,p);return}}else(n.canBlockReload||n.canSkipUntil)&&(p=this.getDeliveryDirectives(n,t.deliveryDirectives,x,v));p&&x!==void 0&&n.canBlockReload&&(n.requestScheduled=i.loading.first+Math.max(m-a*2,m/2)),this.scheduleLoading(d,p,n)}else this.clearTimer()}scheduleLoading(e,t,s){const n=s||e.details;if(!n){this.loadingPlaylist(e,t);return}const i=self.performance.now(),o=n.requestScheduled;if(i>=o){this.loadingPlaylist(e,t);return}const a=o-i;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),a)}getDeliveryDirectives(e,t,s,n){let i=Ya(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,n=t.part,i=hn.No),new qa(s,n,i)}checkRetry(e){const t=e.details,s=Ln(e),n=e.errorAction,{action:i,retryCount:o=0,retryConfig:a}=n||{},c=!!n&&!!a&&(i===lt.RetryRequest||!n.resolved&&i===lt.SendAlternateToPenaltyBox);if(c){var l;if(o>=a.maxNumRetry)return!1;if(s&&(l=e.context)!=null&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const d=Zo(a,o);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),d),this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${t}" in ${d}ms`)}e.levelRetry=!0,n.resolved=!0}return c}}function ph(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(!Fr(r[t].attrs,e[t].attrs))return!1;return!0}function Fr(r,e,t){const s=r["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(n=>r[n]!==e[n])}function eo(r,e){return e.label.toLowerCase()===r.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(r.lang||"").toLowerCase())}class zb extends ua{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(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.MANIFEST_PARSED,this.onManifestParsed,this),e.on(S.LEVEL_LOADING,this.onLevelLoading,this),e.on(S.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(S.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(S.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.MANIFEST_PARSED,this.onManifestParsed,this),e.off(S.LEVEL_LOADING,this.onLevelLoading,this),e.off(S.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(S.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(S.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:s,groupId:n,details:i}=t,o=this.tracksInGroup[s];if(!o||o.groupId!==n){this.warn(`Audio track with id:${s} and group:${n} not found in active group ${o==null?void 0:o.groupId}`);return}const a=o.details;o.details=t.details,this.log(`Audio track ${s} "${o.name}" lang:${o.lang} group:${n} loaded [${i.startSN}-${i.endSN}]`),s===this.trackId&&this.playlistLoaded(s,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 s=t.audioGroups||null,n=this.groupIds;let i=this.currentTrack;if(!s||(n==null?void 0:n.length)!==(s==null?void 0:s.length)||s!=null&&s.some(a=>(n==null?void 0:n.indexOf(a))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(h=>!s||s.indexOf(h.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(h=>h.default)&&(this.selectDefaultTrack=!1),a.forEach((h,g)=>{h.id=g});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const c=this.hls.config.audioPreference;if(!i&&c){const h=es(c,a,Ds);if(h>-1)i=a[h];else{const g=es(c,this.tracks);i=this.tracks[g]}}let l=this.findTrackId(i);l===-1&&i&&(l=this.findTrackId(null));const d={audioTracks:a};this.log(`Updating audio tracks, ${a.length} track(s) found in group(s): ${s==null?void 0:s.join(",")}`),this.hls.trigger(S.AUDIO_TRACKS_UPDATED,d);const u=this.trackId;if(l!==-1&&u===-1)this.setAudioTrack(l);else if(a.length&&u===-1){var o;const h=new Error(`No audio track selected for current audio group-ID(s): ${(o=this.groupIds)==null?void 0:o.join(",")} track count: ${a.length}`);this.warn(h.message),this.hls.trigger(S.ERROR,{type:ce.MEDIA_ERROR,details:B.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:h})}}}onError(e,t){t.fatal||!t.context||t.context.type===Te.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 s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const n=this.currentTrack;if(n&&Ns(e,n,Ds))return n;const i=es(e,this.tracksInGroup,Ds);if(i>-1){const o=this.tracksInGroup[i];return this.setAudioTrack(i),o}else if(n){let o=t.loadLevel;o===-1&&(o=t.firstAutoLevel);const a=ny(e,t.levels,s,o,Ds);if(a===-1)return null;t.nextLoadLevel=a}if(e.channels||e.audioCodec){const o=es(e,s);if(o>-1)return s[o]}}}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 s=this.currentTrack,n=t[e],i=n.details&&!n.details.live;if(e===this.trackId&&n===s&&i||(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(S.AUDIO_TRACK_SWITCHING,_e({},n)),i))return;const o=this.switchParams(n.url,s==null?void 0:s.details,n.details);this.loadPlaylist(o)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const n=t[s];if(!(this.selectDefaultTrack&&!n.default)&&(!e||Ns(e,n,Ds)))return s}if(e){const{name:s,lang:n,assocLang:i,characteristics:o,audioCodec:a,channels:c}=e;for(let l=0;l<t.length;l++){const d=t[l];if(Ns({name:s,lang:n,assocLang:i,characteristics:o,audioCodec:a,channels:c},d,Ds))return l}for(let l=0;l<t.length;l++){const d=t[l];if(Fr(e.attrs,d.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){const d=t[l];if(Fr(e.attrs,d.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&In(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,n=e.groupId,i=this.getUrlWithDirectives(e.url,t),o=e.details,a=o==null?void 0:o.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${a&&o.live?" age "+a.toFixed(1)+(o.type&&" "+o.type||""):""} ${i}`),this.hls.trigger(S.AUDIO_TRACK_LOADING,{url:i,id:s,groupId:n,deliveryDirectives:t||null,track:e})}}class Wb{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;const n=this.queues[t];n.push(e),n.length===1&&!s&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const s=(t=e[0])==null?void 0:t.label;(s==="async-blocker"||s==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const n=t[0];try{n.execute()}catch(i){var s;if(n.onError(i),this.queues===null||this.tracks===null)return;const o=(s=this.tracks[e])==null?void 0:s.buffer;o!=null&&o.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>":`
57
+ ${this.list("video")}
58
+ ${this.list("audio")}
59
+ ${this.list("audiovideo")}}`}list(e){var t,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=(t=this.tracks)==null?void 0:t[e],n=s==null?void 0:s.buffer;return n?`SourceBuffer${n.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}}const Nl=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,xh="HlsJsTrackRemovedError";class Yb extends Error{constructor(e){super(e),this.name=xh}}class qb extends Ut{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=s=>{var n;this.hls&&((n=this.mediaSource)==null?void 0:n.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{const{media:n,mediaSource:i}=this;s&&this.log("Media source opened"),!(!n||!i)&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(S.MEDIA_ATTACHED,{media:n,mediaSource:i}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:s,_objectUrl:n}=this;s!==n&&this.error(`Media element src was set while attaching MediaSource (${n} > ${s})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=xv(Es(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(S.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.MANIFEST_PARSED,this.onManifestParsed,this),e.on(S.BUFFER_RESET,this.onBufferReset,this),e.on(S.BUFFER_APPENDING,this.onBufferAppending,this),e.on(S.BUFFER_CODECS,this.onBufferCodecs,this),e.on(S.BUFFER_EOS,this.onBufferEos,this),e.on(S.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(S.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(S.FRAG_PARSED,this.onFragParsed,this),e.on(S.FRAG_CHANGED,this.onFragChanged,this),e.on(S.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(S.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.MANIFEST_PARSED,this.onManifestParsed,this),e.off(S.BUFFER_RESET,this.onBufferReset,this),e.off(S.BUFFER_APPENDING,this.onBufferAppending,this),e.off(S.BUFFER_CODECS,this.onBufferCodecs,this),e.off(S.BUFFER_EOS,this.onBufferEos,this),e.off(S.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(S.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(S.FRAG_PARSED,this.onFragParsed,this),e.off(S.FRAG_CHANGED,this.onFragChanged,this),e.off(S.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const s={};if(this.operationQueue){const i=this.isUpdating();i||this.operationQueue.removeBlockers();const o=this.isQueued();(i||o)&&this.warn(`Transfering MediaSource with${o?" operations in queue":""}${i?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const n=this.transferData;return!this.sourceBufferCount&&n&&n.mediaSource===t?De(s,n.tracks):this.sourceBuffers.forEach(i=>{const[o]=i;o&&(s[o]=De({},this.tracks[o]),this.removeBuffer(o)),i[0]=i[1]=null}),{media:e,mediaSource:t,tracks:s}}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 s;let n=2;(t.audio&&!t.video||!t.altAudio)&&(n=1),this.bufferCodecEventsTotal=n,this.log(`${n} bufferCodec event(s) expected.`),(s=this.transferData)!=null&&s.mediaSource&&this.sourceBufferCount&&n&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media;this.transferData=this.overrides=void 0;const n=Es(this.appendSource);if(n){const i=!!t.mediaSource;(i||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const o=this.mediaSource=t.mediaSource||new n;if(this.assignMediaSource(o),i)this._objectUrl=s.src,this.attachTransferred();else{const a=this._objectUrl=self.URL.createObjectURL(o);if(this.appendSource)try{s.removeAttribute("src");const c=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||c&&o instanceof c,Ml(s),Xb(s,a),s.load()}catch{s.src=a}else s.src=a}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,s;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(s=e.constructor)==null?void 0:s.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 s=this.tracks,n=t.tracks,i=n?Object.keys(n):null,o=i?i.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(n&&i&&o){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
60
+ required tracks: ${Ne(s,(c,l)=>c==="initSegment"?void 0:l)};
61
+ transfer tracks: ${Ne(n,(c,l)=>c==="initSegment"?void 0:l)}}`),!hf(n,s)){t.mediaSource=null,t.tracks=void 0;const c=e.currentTime,l=this.details,d=Math.max(c,(l==null?void 0:l.fragments[0].start)||0);if(d-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${d}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(n)}"->"${Object.keys(s)}") start time: ${d} currentTime: ${c}`),this.onMediaDetaching(S.MEDIA_DETACHING,{}),this.onMediaAttaching(S.MEDIA_ATTACHING,t),e.currentTime=d;return}this.transferData=void 0,i.forEach(c=>{const l=c,d=n[l];if(d){const u=d.buffer;if(u){const h=this.fragmentTracker,g=d.id;if(h.hasFragments(g)||h.hasParts(g)){const x=ve.getBuffered(u);h.detectEvictedFragments(l,x,g,null,!0)}const m=vi(l),p=[l,u];this.sourceBuffers[m]=p,u.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,d)}}}),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 s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:n,mediaSource:i,_objectUrl:o}=this;if(i){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([a])=>{a&&this.removeBuffer(a)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const a=i.readyState==="open";try{const c=i.sourceBuffers;for(let l=c.length;l--;)a&&c[l].abort(),i.removeSourceBuffer(c[l]);a&&i.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}i.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("sourceended",this._onMediaSourceEnded),i.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(i.removeEventListener("startstreaming",this._onStartStreaming),i.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(n.removeEventListener("emptied",this._onMediaEmptied),s||(o&&self.URL.revokeObjectURL(o),this.mediaSrc===o?(n.removeAttribute("src"),this.appendSource&&Ml(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(S.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var n;(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(i){this.warn(`onBufferReset ${e}`,i)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[vi(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Wb(this.tracks)}onBufferCodecs(e,t){var s;const n=this.tracks,i=Object.keys(t);this.log(`BUFFER_CODECS: "${i}" (current SB count ${this.sourceBufferCount})`);const o="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),a=!o&&this.sourceBufferCount&&this.media&&i.some(c=>!n[c]);if(o||a){this.warn(`Unsupported transition between "${Object.keys(n)}" and "${i}" SourceBuffers`);return}i.forEach(c=>{var l,d;const u=t[c],{id:h,codec:g,levelCodec:m,container:p,metadata:x,supplemental:v}=u;let y=n[c];const b=(l=this.transferData)==null||(l=l.tracks)==null?void 0:l[c],T=b!=null&&b.buffer?b:y,R=(T==null?void 0:T.pendingCodec)||(T==null?void 0:T.codec),_=T==null?void 0:T.levelCodec;y||(y=n[c]={buffer:void 0,listeners:[],codec:g,supplemental:v,container:p,levelCodec:m,metadata:x,id:h});const w=fn(R,_),A=w==null?void 0:w.replace(Nl,"$1");let C=fn(g,m);const L=(d=C)==null?void 0:d.replace(Nl,"$1");C&&w&&A!==L&&(c.slice(0,5)==="audio"&&(C=Rn(C,this.appendSource)),this.log(`switching codec ${R} to ${C}`),C!==(y.pendingCodec||y.codec)&&(y.pendingCodec=C),y.container=p,this.appendChangeType(c,p,C))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.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 s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){const n=`${t};codecs=${s}`,i={label:`change-type=${n}`,execute:()=>{const o=this.tracks[e];if(o){const a=o.buffer;a!=null&&a.changeType&&(this.log(`changing ${e} sourceBuffer type to ${n}`),a.changeType(n),o.codec=s,o.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn(`Failed to change ${e} SourceBuffer type`,o)}};this.append(i,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,n=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,oe.MAIN))==null?void 0:t.gap)===!0)return;const o={label:"block-audio",execute:()=>{var a;const c=this.tracks.video;(this.lastVideoAppendEnd>n||c!=null&&c.buffer&&ve.isBuffered(c.buffer,n)||((a=this.fragmentTracker.getAppendedFrag(n,oe.MAIN))==null?void 0:a.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn("Error executing block-audio operation",a)}};this.blockedAudioAppend={op:o,frag:e},this.append(o,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:s}=this,{data:n,type:i,parent:o,frag:a,part:c,chunkMeta:l,offset:d}=t,u=l.buffering[i],{sn:h,cc:g}=a,m=self.performance.now();u.start=m;const p=a.stats.buffering,x=c?c.stats.buffering:null;p.start===0&&(p.start=m),x&&x.start===0&&(x.start=m);const v=s.audio;let y=!1;i==="audio"&&(v==null?void 0:v.container)==="audio/mpeg"&&(y=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const b=s.video,T=b==null?void 0:b.buffer;if(T&&h!=="initSegment"){const w=c||a,A=this.blockedAudioAppend;if(i==="audio"&&o!=="main"&&!this.blockedAudioAppend&&!(b.ending||b.ended)){const L=w.start+w.duration*.05,P=T.buffered,M=this.currentOp("video");!P.length&&!M?this.blockAudio(w):!M&&!ve.isBuffered(T,L)&&this.lastVideoAppendEnd<L&&this.blockAudio(w)}else if(i==="video"){const C=w.end;if(A){const L=A.frag.start;(C>L||C<this.lastVideoAppendEnd||ve.isBuffered(T,L))&&this.unblockAudio()}this.lastVideoAppendEnd=C}}const R=(c||a).start,_={label:`append-${i}`,execute:()=>{var w;u.executeStart=self.performance.now();const A=(w=this.tracks[i])==null?void 0:w.buffer;A&&(y?this.updateTimestampOffset(A,R,.1,i,h,g):d!==void 0&&ne(d)&&this.updateTimestampOffset(A,d,1e-6,i,h,g)),this.appendExecutor(n,i)},onStart:()=>{},onComplete:()=>{const w=self.performance.now();u.executeEnd=u.end=w,p.first===0&&(p.first=w),x&&x.first===0&&(x.first=w);const A={};this.sourceBuffers.forEach(([C,L])=>{C&&(A[C]=ve.getBuffered(L))}),this.appendErrors[i]=0,i==="audio"||i==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(S.BUFFER_APPENDED,{type:i,frag:a,part:c,chunkMeta:l,parent:a.type,timeRanges:A})},onError:w=>{var A;const C={type:ce.MEDIA_ERROR,parent:a.type,details:B.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:a,part:c,chunkMeta:l,error:w,err:w,fatal:!1},L=(A=this.media)==null?void 0:A.error;if(w.code===DOMException.QUOTA_EXCEEDED_ERR||w.name=="QuotaExceededError"||"quota"in w)C.details=B.BUFFER_FULL_ERROR;else if(w.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!L)C.errorAction=Zs(!0);else if(w.name===xh&&this.sourceBufferCount===0)C.errorAction=Zs(!0);else{const P=++this.appendErrors[i];this.warn(`Failed ${P}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${i}" sourceBuffer (${L||"no media error"})`),(P>=this.hls.config.appendErrorMaxRetry||L)&&(C.fatal=!0)}this.hls.trigger(S.ERROR,C)}};this.log(`queuing "${i}" append sn: ${h}${c?" p: "+c.index:""} of ${a.type===oe.MAIN?"level":"track"} ${a.level} cc: ${g}`),this.append(_,i,this.isPending(this.tracks[i]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(S.BUFFER_FLUSHED,{type:e})},onError:n=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,n)}}}onBufferFlushing(e,t){const{type:s,startOffset:n,endOffset:i}=t;s?this.append(this.getFlushOp(s,n,i),s):this.sourceBuffers.forEach(([o])=>{o&&this.append(this.getFlushOp(o,n,i),o)})}onFragParsed(e,t){const{frag:s,part:n}=t,i=[],o=n?n.elementaryStreams:s.elementaryStreams;o[Pe.AUDIOVIDEO]?i.push("audiovideo"):(o[Pe.AUDIO]&&i.push("audio"),o[Pe.VIDEO]&&i.push("video"));const a=()=>{const c=self.performance.now();s.stats.buffering.end=c,n&&(n.stats.buffering.end=c);const l=n?n.stats:s.stats;this.hls.trigger(S.FRAG_BUFFERED,{frag:s,part:n,stats:l,id:s.type})};i.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(a,i).catch(c=>{this.warn(`Fragment buffered callback ${c}`),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 s;this.sourceBuffers.forEach(([o])=>{if(o){const a=this.tracks[o];(!t.type||t.type===o)&&(a.ending=!0,a.ended||(a.ended=!0,this.log(`${o} buffer reached EOS`)))}});const n=((s=this.overrides)==null?void 0:s.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([o])=>{var a;return o&&!((a=this.tracks[o])!=null&&a.ended)})?n?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:o}=this;if(!o||o.readyState!=="open"){o&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${o.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),o.endOfStream(),this.hls.trigger(S.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(S.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===B.BUFFER_APPEND_ERROR&&t.frag){var s;const n=(s=t.errorAction)==null?void 0:s.nextAutoLevel;ne(n)&&n!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||t===null||!this.sourceBufferCount)return;const n=e.config,i=s.currentTime,o=t.levelTargetDuration,a=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(ne(a)&&a>=0){const l=Math.max(a,o),d=Math.floor(i/o)*o-l;this.flushBackBuffer(i,o,d)}const c=n.frontBufferFlushThreshold;if(ne(c)&&c>0){const l=Math.max(n.maxBufferLength,c),d=Math.max(l,o),u=Math.floor(i/o)*o+d;this.flushFrontBuffer(i,o,u)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([n,i])=>{if(i){const a=ve.getBuffered(i);if(a.length>0&&s>a.start(0)){var o;this.hls.trigger(S.BACK_BUFFER_REACHED,{bufferEnd:s});const c=this.tracks[n];if((o=this.details)!=null&&o.live)this.hls.trigger(S.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(c!=null&&c.ended){this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(S.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:n})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([n,i])=>{if(i){const o=ve.getBuffered(i),a=o.length;if(a<2)return;const c=o.start(a-1),l=o.end(a-1);if(s>c||e>=c&&e<=l)return;this.hls.trigger(S.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:n})}})}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||(s==null?void 0:s.readyState)!=="open")return null;const n=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const l=Math.max(0,t.fragmentStart),d=Math.max(l,n);return{duration:1/0,start:l,end:d}}return{duration:1/0}}const i=(e=this.overrides)==null?void 0:e.duration;if(i)return ne(i)?{duration:i}:null;const o=this.media.duration,a=ne(s.duration)?s.duration:0;return n>a&&n>o||!ne(o)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:s}){const n=this.mediaSource;!this.media||!n||n.readyState!=="open"||(n.duration!==e&&(ne(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),n.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${n.duration}. Setting seekable range to ${t}-${s}.`),n.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${Ne(s)}`),this.tracksReady){var n;const i=(n=this.transferData)==null?void 0:n.tracks;i&&Object.keys(i).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,s])=>{if(t){const n=this.tracks[t];e[t]={buffer:s,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}}),this.hls.trigger(S.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(S.ERROR,{type:ce.MEDIA_ERROR,details:B.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const i in e){const o=i,a=e[o];if(this.isPending(a)){const c=this.getTrackCodec(a,o),l=`${a.container};codecs=${c}`;a.codec=c,this.log(`creating sourceBuffer(${l})${this.currentOp(o)?" Queued":""} ${Ne(a)}`);try{const d=s.addSourceBuffer(l),u=vi(o),h=[o,d];t[u]=h,a.buffer=d}catch(d){var n;this.error(`error while trying to add sourceBuffer: ${d.message}`),this.shiftAndExecuteNext(o),(n=this.operationQueue)==null||n.removeBlockers(),delete this.tracks[o],this.hls.trigger(S.ERROR,{type:ce.MEDIA_ERROR,details:B.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:d,sourceBufferName:o,mimeType:l,parent:a.id});return}this.trackSourceBuffer(o,a)}}this.bufferCreated()}getTrackCodec(e,t){const s=e.supplemental;let n=e.codec;s&&(t==="video"||t==="audiovideo")&&_r(s,"video")&&(n=Bv(n,s));const i=fn(n,e.levelCodec);return i?t.slice(0,5)==="audio"?Rn(i,this.appendSource):i:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const n=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,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",(i,o)=>{const a=o.removedRanges;a!=null&&a.length&&this.hls.trigger(S.BUFFER_FLUSHED,{type:i})})}get mediaSrc(){var e,t;const s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s==null?void 0:s.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 s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;const n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(s=this.mediaSource)==null?void 0:s.readyState}`);this.error(`${n}`,t),this.hls.trigger(S.ERROR,{type:ce.MEDIA_ERROR,details:B.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});const i=this.currentOp(e);i&&i.onError(n)}updateTimestampOffset(e,t,s,n,i,o){const a=t-e.timestampOffset;Math.abs(a)>=s&&(this.log(`Updating ${n} SourceBuffer timestampOffset to ${t} (sn: ${i} cc: ${o})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:n,mediaSource:i}=this,o=this.tracks[e],a=o==null?void 0:o.buffer;if(!n||!i||!a){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const c=ne(n.duration)?n.duration:1/0,l=ne(i.duration)?i.duration:1/0,d=Math.max(0,t),u=Math.min(s,c,l);u>d&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${d},${u}] from the ${e} SourceBuffer`),a.remove(d,u)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],n=s==null?void 0:s.buffer;if(!n)throw new Yb(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.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:s}=this,n=t.map(o=>this.appendBlocker(o));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(o=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;const n=(s=this.tracks[t])==null?void 0:s.buffer;!n||n.updating||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}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,s){const n=this.tracks[e];if(!n)return;const i=n.buffer;if(!i)return;const o=s.bind(this,e);n.listeners.push({event:t,listener:o}),i.addEventListener(t,o)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach(n=>{s.removeEventListener(n.event,n.listener)}),t.listeners.length=0)}}function Ml(r){const e=r.querySelectorAll("source");[].slice.call(e).forEach(t=>{r.removeChild(t)})}function Xb(r,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,r.appendChild(t)}function vi(r){return r==="audio"?1:0}class fa{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(S.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(S.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(S.MANIFEST_PARSED,this.onManifestParsed,this),e.on(S.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(S.BUFFER_CODECS,this.onBufferCodecs,this),e.on(S.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(S.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(S.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(S.MANIFEST_PARSED,this.onManifestParsed,this),e.off(S.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(S.BUFFER_CODECS,this.onBufferCodecs,this),e.off(S.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&ne(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const s=t.filter((n,i)=>this.isLevelAllowed(n)&&i<=e);return this.clientRect=null,fa.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(!(e!=null&&e.length))return-1;const n=(a,c)=>c?a.width!==c.width||a.height!==c.height:!0;let i=e.length-1;const o=Math.max(t,s);for(let a=0;a<e.length;a+=1){const c=e[a];if((c.width>=o||c.height>=o)&&n(c,e[a+1])){i=a;break}}return i}}const Qb={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},xt=Qb,Zb={HLS:"h"},Jb=Zb;class ss{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof ss?s:new ss(s))),this.value=e,this.params=t}}const eS="Dict";function tS(r){return Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":typeof r=="object"?JSON.stringify(r):String(r)}function sS(r,e,t,s){return new Error(`failed to ${r} "${tS(e)}" as ${t}`,{cause:s})}function rs(r,e,t){return sS("serialize",r,e,t)}class vh{constructor(e){this.description=e}}const Fl="Bare Item",rS="Boolean";function nS(r){if(typeof r!="boolean")throw rs(r,rS);return r?"?1":"?0"}function iS(r){return btoa(String.fromCharCode(...r))}const oS="Byte Sequence";function aS(r){if(ArrayBuffer.isView(r)===!1)throw rs(r,oS);return`:${iS(r)}:`}const lS="Integer";function cS(r){return r<-999999999999999||999999999999999<r}function yh(r){if(cS(r))throw rs(r,lS);return r.toString()}function dS(r){return`@${yh(r.getTime()/1e3)}`}function bh(r,e){if(r<0)return-bh(-r,e);const t=Math.pow(10,e);if(Math.abs(r*t%1-.5)<Number.EPSILON){const n=Math.floor(r*t);return(n%2===0?n:n+1)/t}else return Math.round(r*t)/t}const uS="Decimal";function fS(r){const e=bh(r,3);if(Math.floor(Math.abs(e)).toString().length>12)throw rs(r,uS);const t=e.toString();return t.includes(".")?t:`${t}.0`}const hS="String",gS=/[\x00-\x1f\x7f]+/;function mS(r){if(gS.test(r))throw rs(r,hS);return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function pS(r){return r.description||r.toString().slice(7,-1)}const xS="Token";function Ol(r){const e=pS(r);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw rs(e,xS);return e}function to(r){switch(typeof r){case"number":if(!ne(r))throw rs(r,Fl);return Number.isInteger(r)?yh(r):fS(r);case"string":return mS(r);case"symbol":return Ol(r);case"boolean":return nS(r);case"object":if(r instanceof Date)return dS(r);if(r instanceof Uint8Array)return aS(r);if(r instanceof vh)return Ol(r);default:throw rs(r,Fl)}}const vS="Key";function so(r){if(/^[a-z*][a-z0-9\-_.*]*$/.test(r)===!1)throw rs(r,vS);return r}function ha(r){return r==null?"":Object.entries(r).map(([e,t])=>t===!0?`;${so(e)}`:`;${so(e)}=${to(t)}`).join("")}function Sh(r){return r instanceof ss?`${to(r.value)}${ha(r.params)}`:to(r)}function yS(r){return`(${r.value.map(Sh).join(" ")})${ha(r.params)}`}function bS(r,e={whitespace:!0}){if(typeof r!="object"||r==null)throw rs(r,eS);const t=r instanceof Map?r.entries():Object.entries(r),s=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([n,i])=>{i instanceof ss||(i=new ss(i));let o=so(n);return i.value===!0?o+=ha(i.params):(o+="=",Array.isArray(i.value)?o+=yS(i):o+=Sh(i)),o}).join(`,${s}`)}function Eh(r,e){return bS(r,e)}const Qt="CMCD-Object",ze="CMCD-Request",Cs="CMCD-Session",ps="CMCD-Status",SS={br:Qt,ab:Qt,d:Qt,ot:Qt,tb:Qt,tpb:Qt,lb:Qt,tab:Qt,lab:Qt,url:Qt,pb:ze,bl:ze,tbl:ze,dl:ze,ltc:ze,mtp:ze,nor:ze,nrr:ze,rc:ze,sn:ze,sta:ze,su:ze,ttfb:ze,ttfbb:ze,ttlb:ze,cmsdd:ze,cmsds:ze,smrt:ze,df:ze,cs:ze,ts:ze,cid:Cs,pr:Cs,sf:Cs,sid:Cs,st:Cs,v:Cs,msd:Cs,bs:ps,bsd:ps,cdn:ps,rtp:ps,bg:ps,pt:ps,ec:ps,e:ps},ES={REQUEST:ze};function TS(r){return Object.keys(r).reduce((e,t)=>{var s;return(s=r[t])===null||s===void 0||s.forEach(n=>e[n]=t),e},{})}function wS(r,e){const t={};if(!r)return t;const s=Object.keys(r),n=e?TS(e):{};return s.reduce((i,o)=>{var a;const c=SS[o]||n[o]||ES.REQUEST,l=(a=i[c])!==null&&a!==void 0?a:i[c]={};return l[o]=r[o],i},t)}function RS(r){return["ot","sf","st","e","sta"].includes(r)}function AS(r){return typeof r=="number"?ne(r):r!=null&&r!==""&&r!==!1}const Th="event";function IS(r,e){const t=new URL(r),s=new URL(e);if(t.origin!==s.origin)return r;const n=t.pathname.split("/").slice(1),i=s.pathname.split("/").slice(1,-1);for(;n[0]===i[0];)n.shift(),i.shift();for(;i.length;)i.shift(),n.unshift("..");return n.join("/")+t.search+t.hash}const xn=r=>Math.round(r),ro=(r,e)=>Array.isArray(r)?r.map(t=>ro(t,e)):r instanceof ss&&typeof r.value=="string"?new ss(ro(r.value,e),r.params):(e.baseUrl&&(r=IS(r,e.baseUrl)),e.version===1?encodeURIComponent(r):r),sn=r=>xn(r/100)*100,LS=(r,e)=>{let t=r;return e.version>=2&&(r instanceof ss&&typeof r.value=="string"?t=new ss([r]):typeof r=="string"&&(t=[r])),ro(t,e)},CS={br:xn,d:xn,bl:sn,dl:sn,mtp:sn,nor:LS,rtp:sn,tb:xn},wh="request",Rh="response",ga=["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"],_S=["e"],kS=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Yn(r){return kS.test(r)}function DS(r){return ga.includes(r)||_S.includes(r)||Yn(r)}const Ah=["d","dl","nor","ot","rtp","su"];function PS(r){return ga.includes(r)||Ah.includes(r)||Yn(r)}const NS=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function MS(r){return ga.includes(r)||Ah.includes(r)||NS.includes(r)||Yn(r)}const FS=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function OS(r){return FS.includes(r)||Yn(r)}const jS={[Rh]:MS,[Th]:DS,[wh]:PS};function Ih(r,e={}){const t={};if(r==null||typeof r!="object")return t;const s=e.version||r.v||1,n=e.reportingMode||wh,i=s===1?OS:jS[n];let o=Object.keys(r).filter(i);const a=e.filter;typeof a=="function"&&(o=o.filter(a));const c=n===Rh||n===Th;c&&!o.includes("ts")&&o.push("ts"),s>1&&!o.includes("v")&&o.push("v");const l=De({},CS,e.formatters),d={version:s,reportingMode:n,baseUrl:e.baseUrl};return o.sort().forEach(u=>{let h=r[u];const g=l[u];if(typeof g=="function"&&(h=g(h,d)),u==="v"){if(s===1)return;h=s}u=="pr"&&h===1||(c&&u==="ts"&&!ne(h)&&(h=Date.now()),AS(h)&&(RS(u)&&typeof h=="string"&&(h=new vh(h)),t[u]=h))}),t}function BS(r,e={}){const t={};if(!r)return t;const s=Ih(r,e),n=wS(s,e==null?void 0:e.customHeaderMap);return Object.entries(n).reduce((i,[o,a])=>{const c=Eh(a,{whitespace:!1});return c&&(i[o]=c),i},t)}function $S(r,e,t){return De(r,BS(e,t))}const US="CMCD";function GS(r,e={}){return r?Eh(Ih(r,e),{whitespace:!1}):""}function VS(r,e={}){if(!r)return"";const t=GS(r,e);return encodeURIComponent(t)}function HS(r,e={}){if(!r)return"";const t=VS(r,e);return`${US}=${t}`}const jl=/CMCD=[^&#]+/;function KS(r,e,t){const s=HS(e,t);if(!s)return r;if(jl.test(r))return r.replace(jl,s);const n=r.includes("?")?"&":"?";return`${r}${n}${s}`}class zS{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:xt.MANIFEST,su:!this.initialized})}catch(i){this.hls.logger.warn("Could not generate manifest CMCD data.",i)}},this.applyFragmentData=n=>{try{const{frag:i,part:o}=n,a=this.hls.levels[i.level],c=this.getObjectType(i),l={d:(o||i).duration*1e3,ot:c};(c===xt.VIDEO||c===xt.AUDIO||c==xt.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(c)/1e3,l.bl=this.getBufferLength(c));const d=o?this.getNextPart(o):this.getNextFrag(i);d!=null&&d.url&&d.url!==i.url&&(l.nor=d.url),this.apply(n,l)}catch(i){this.hls.logger.warn("Could not generate segment CMCD data.",i)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(S.MEDIA_DETACHED,this.onMediaDetached,this),e.on(S.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(S.MEDIA_DETACHED,this.onMediaDetached,this),e.off(S.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 s,n;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(n=t.tracks.video)==null?void 0:n.buffer}createData(){var e;return{v:1,sf:Jb.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){De(t,this.createData());const s=t.ot===xt.INIT||t.ot===xt.VIDEO||t.ot===xt.MUXED;this.starved&&s&&(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((o,a)=>(n.includes(a)&&(o[a]=t[a]),o),{}));const i={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),$S(e.headers,t,i)):e.url=KS(e.url,t,i)}getNextFrag(e){var t;const s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){const n=e.sn-s.startSN;return s.fragments[n+1]}}getNextPart(e){var t;const{index:s,fragment:n}=e,i=(t=this.hls.levels[n.level])==null||(t=t.details)==null?void 0:t.partList;if(i){const{sn:o}=n;for(let a=i.length-1;a>=0;a--){const c=i[a];if(c.index===s&&c.fragment.sn===o)return i[a+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return xt.TIMED_TEXT;if(e.sn==="initSegment")return xt.INIT;if(t==="audio")return xt.AUDIO;if(t==="main")return this.hls.audioTracks.length?xt.VIDEO:xt.MUXED}getTopBandwidth(e){let t=0,s;const n=this.hls;if(e===xt.AUDIO)s=n.audioTracks;else{const i=n.maxAutoLevel,o=i>-1?i+1:n.levels.length;s=n.levels.slice(0,o)}return s.forEach(i=>{i.bitrate>t&&(t=i.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,s=e===xt.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:ve.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(i){this.loader=void 0,this.loader=new s(i)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(i,o,a){t(i),this.loader.load(i,o,a)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(i){this.loader=void 0,this.loader=new s(i)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(i,o,a){t(i),this.loader.load(i,o,a)}}}}const WS=3e5;class YS extends Ut{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(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(S.MANIFEST_PARSED,this.onManifestParsed,this),e.on(S.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(S.MANIFEST_PARSED,this.onManifestParsed,this),e.off(S.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(s=>s!==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:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if((s==null?void 0:s.action)===lt.SendAlternateToPenaltyBox&&s.flags===Ct.MoveAllAlternatesMatchingHost){const n=this.levels;let i=this._pathwayPriority,o=this.pathwayId;if(t.context){const{groupId:a,pathwayId:c,type:l}=t.context;a&&n?o=this.getPathwayForGroupId(a,l,o):c&&(o=c)}o in this.penalizedPathways||(this.penalizedPathways[o]=performance.now()),!i&&n&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),s.resolved=this.pathwayId!==o),t.details===B.BUFFER_APPEND_ERROR&&!t.fatal?s.resolved=!0:s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${o} levels: ${n&&n.length} priorities: ${Ne(i)} penalized: ${Ne(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}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 s=this.penalizedPathways,n=performance.now();Object.keys(s).forEach(i=>{n-s[i]>WS&&delete s[i]});for(let i=0;i<e.length;i++){const o=e[i];if(o in s)continue;if(o===this.pathwayId)return;const a=this.hls.nextLoadLevel,c=this.hls.levels[a];if(t=this.getLevelsForPathway(o),t.length>0){this.log(`Setting Pathway to "${o}"`),this.pathwayId=o,Wf(t),this.hls.trigger(S.LEVELS_UPDATED,{levels:t});const l=this.hls.levels[a];c&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(e,t,s){const n=this.getLevelsForPathway(s).concat(this.levels||[]);for(let i=0;i<n.length;i++)if(t===Te.AUDIO_TRACK&&n[i].hasAudioGroup(e)||t===Te.SUBTITLE_TRACK&&n[i].hasSubtitleGroup(e))return n[i].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},n={};e.forEach(i=>{const{ID:o,"BASE-ID":a,"URI-REPLACEMENT":c}=i;if(t.some(d=>d.pathwayId===o))return;const l=this.getLevelsForPathway(a).map(d=>{const u=new Ve(d.attrs);u["PATHWAY-ID"]=o;const h=u.AUDIO&&`${u.AUDIO}_clone_${o}`,g=u.SUBTITLES&&`${u.SUBTITLES}_clone_${o}`;h&&(s[u.AUDIO]=h,u.AUDIO=h),g&&(n[u.SUBTITLES]=g,u.SUBTITLES=g);const m=Lh(d.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),p=new Dr({attrs:u,audioCodec:d.audioCodec,bitrate:d.bitrate,height:d.height,name:d.name,url:m,videoCodec:d.videoCodec,width:d.width});if(d.audioGroups)for(let x=1;x<d.audioGroups.length;x++)p.addGroupId("audio",`${d.audioGroups[x]}_clone_${o}`);if(d.subtitleGroups)for(let x=1;x<d.subtitleGroups.length;x++)p.addGroupId("text",`${d.subtitleGroups[x]}_clone_${o}`);return p});t.push(...l),Bl(this.audioTracks,s,c,o),Bl(this.subtitleTracks,n,c,o)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(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 d=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;n.searchParams.set("_HLS_pathway",this.pathwayId),n.searchParams.set("_HLS_throughput",""+d)}const i={responseType:"json",url:n.href},o=t.steeringManifestLoadPolicy.default,a=o.errorRetry||o.timeoutRetry||{},c={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(d,u,h,g)=>{this.log(`Loaded steering manifest: "${n}"`);const m=d.data;if((m==null?void 0:m.VERSION)!==1){this.log(`Steering VERSION ${m.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=m.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":x,"PATHWAY-PRIORITY":v}=m;if(p)try{this.uri=new self.URL(p,n).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||h.url),x&&this.clonePathways(x);const y={steeringManifest:m,url:n.toString()};this.hls.trigger(S.STEERING_MANIFEST_LOADED,y),v&&this.updatePathwayPriority(v)},onError:(d,u,h,g)=>{if(this.log(`Error loading steering manifest: ${d.code} ${d.text} (${u.url})`),this.stopLoad(),d.code===410){this.enabled=!1,this.log(`Steering manifest ${u.url} no longer available`);return}let m=this.timeToLoad*1e3;if(d.code===429){const p=this.loader;if(typeof(p==null?void 0:p.getResponseHeader)=="function"){const x=p.getResponseHeader("Retry-After");x&&(m=parseFloat(x)*1e3)}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,m)},onTimeout:(d,u,h)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(i,c,l)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const n=(s=this.hls)==null?void 0:s.media;if(n&&!n.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function Bl(r,e,t,s){r&&Object.keys(e).forEach(n=>{const i=r.filter(o=>o.groupId===n).map(o=>{const a=De({},o);return a.details=void 0,a.attrs=new Ve(a.attrs),a.url=a.attrs.URI=Lh(o.url,o.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),a.groupId=a.attrs["GROUP-ID"]=e[n],a.attrs["PATHWAY-ID"]=s,a});r.push(...i)})}function Lh(r,e,t,s){const{HOST:n,PARAMS:i,[t]:o}=s;let a;e&&(a=o==null?void 0:o[e],a&&(r=a));const c=new self.URL(r);return n&&!a&&(c.host=n),i&&Object.keys(i).sort().forEach(l=>{l&&c.searchParams.set(l,i[l])}),c.href}class er extends Ut{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=er.CDMCleanupPromise?[er.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:s,initData:n}=t,i=`"${t.type}" event: init data type: "${s}"`;if(this.debug(i),n!==null){if(!this.keyFormatPromise){let o=Object.keys(this.keySystemAccessPromises);o.length||(o=pr(this.config));const a=o.map(di).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(a)}this.keyFormatPromise.then(o=>{const a=gn(o);if(s!=="sinf"||a!==He.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${s}" for selected key-system ${a}`);return}let c;try{const g=st(new Uint8Array(n)),m=sa(JSON.parse(g).sinf),p=Ef(m);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(p.subarray(8,24))}catch(g){this.warn(`${i} Failed to parse sinf: ${g}`);return}const l=ct(c),{keyIdToKeySessionPromise:d,mediaKeySessions:u}=this;let h=d[l];for(let g=0;g<u.length;g++){const m=u[g],p=m.decryptdata;if(!p.keyId)continue;const x=ct(p.keyId);if(_n(c,p.keyId)||p.uri.replace(/-/g,"").indexOf(l)!==-1){if(h=d[x],!h)continue;if(p.pssh)break;delete d[x],p.pssh=new Uint8Array(n),p.keyId=c,h=d[l]=h.then(()=>this.generateRequestWithPreferredKeySession(m,s,n,"encrypted-event-key-match")),h.catch(v=>this.handleError(v));break}}h||this.handleError(new Error(`Key ID ${l} not encountered in playlist. Key-system sessions ${u.length}.`))}).catch(o=>this.handleError(o))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(S.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(S.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(S.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(S.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(S.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(S.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(S.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(S.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(S.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(S.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:s}=this.config,n=t==null?void 0:t[e];if(n)return n.licenseUrl;if(e===He.WIDEVINE&&s)return s}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,s=t==null?void 0:t[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,s=(o,a,c)=>!!o&&c.indexOf(o)===a,n=t.map(o=>o.audioCodec).filter(s),i=t.map(o=>o.videoCodec).filter(s);return n.length+i.length===0&&i.push("avc1.42e01e"),new Promise((o,a)=>{const c=l=>{const d=l.shift();this.getMediaKeysPromise(d,n,i).then(u=>o({keySystem:d,mediaKeys:u})).catch(u=>{l.length?c(l):u instanceof Lt?a(u):a(new Lt({type:ce.KEY_SYSTEM_ERROR,details:B.KEY_SYSTEM_NO_ACCESS,error:u,fatal:!0},u.message))})};c(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let n=`Configured requestMediaKeySystemAccess is not a function ${s}`;return Bf===null&&self.location.protocol==="http:"&&(n=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(n))}return s(e,t)}getMediaKeysPromise(e,t,s){var n;const i=Ly(e,t,s,this.config.drmSystemOptions||{});let o=this.keySystemAccessPromises[e],a=(n=o)==null?void 0:n.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${Ne(i)}`),a=this.requestMediaKeySystemAccess(e,i);const c=o=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),a.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const d=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const u=c.mediaKeys=l.createMediaKeys().then(h=>(this.log(`Media-keys created for "${e}"`),c.hasMediaKeys=!0,d.then(g=>g?this.setMediaKeysServerCertificate(h,e,g):h)));return u.catch(h=>{this.error(`Failed to create media-keys for "${e}"}: ${h}`)}),u})}return a.then(()=>o.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${ct(e.keyId||[])} keyUri: ${e.uri}`);const n=s.createSession(),i={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(i),i}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),n=rn(t),i="cenc";this.keyIdToKeySessionPromise[n]=this.generateRequestWithPreferredKeySession(s,i,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${ct(e.decryptdata.keyId||[])}
62
+ } (data length: ${t.byteLength})`),s.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>di(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return new Promise((t,s)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:n})=>{const i=di(n);i?t(i):s(new Error(`Unable to find format for key-system "${n}"`))}).catch(s)})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=pr(this.config),s=e.map(gn).filter(n=>!!n&&t.indexOf(n)!==-1);return this.selectKeySystem(s)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){const n=qS(e,t[s]);if(n)return n}}loadKey(e){const t=e.keyInfo.decryptdata,s=rn(t),n=this.bannedKeyIds[s];if(n||this.getKeyStatus(t)==="internal-error"){const a=$l(n||"internal-error",t);return this.handleError(a,e.frag),Promise.reject(a)}const i=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${i}`);const o=this.keyIdToKeySessionPromise[s];if(!o){const a=this.getKeySystemForKeyPromise(t).then(({keySystem:c,mediaKeys:l})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${i}`),this.attemptSetMediaKeys(c,l).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:c,mediaKeys:l,decryptdata:t}))))).then(c=>{const l="cenc",d=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,l,d,"playlist-key")});return a.catch(c=>this.handleError(c,e.frag)),this.keyIdToKeySessionPromise[s]=a,a}return o.catch(a=>{if(a instanceof Lt){const c=_e({},a.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);const l=new Lt(c,a.message);this.handleError(l,e.frag)}}),o}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Lt){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${ct(s.keyId||[])})`:""}`),this.hls.trigger(S.ERROR,e.data)}else this.error(e.message),this.hls.trigger(S.ERROR,{type:ce.KEY_SYSTEM_ERROR,details:B.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=rn(e),s=this.keyIdToKeySessionPromise[t];if(!s){const n=gn(e.keyFormat),i=n?[n]:pr(this.config);return this.attemptKeySystemAccess(i)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=pr(this.config)),e.length===0)throw new Lt({type:ce.KEY_SYSTEM_ERROR,details:B.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Ne({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const n=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(t):new Promise((i,o)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return o(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(i).catch(o)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(n),n.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(n),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(i=>s.indexOf(i)===-1)})}generateRequestWithPreferredKeySession(e,t,s,n){var i;const o=(i=this.config.drmSystems)==null||(i=i[e.keySystem])==null?void 0:i.generateRequest;if(o)try{const m=o.call(this.hls,t,s,e);if(!m)throw new Error("Invalid response from configured generateRequest filter");t=m.initDataType,s=m.initData?m.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(m){if(this.warn(m.message),this.hls&&this.hls.config.debug)throw m}if(s===null)return this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(e);const a=rn(e.decryptdata),c=e.decryptdata.uri;this.log(`Generating key-session request for "${n}" keyId: ${a} URI: ${c} (init data type: ${t} length: ${s.byteLength})`);const l=new na,d=e._onmessage=m=>{const p=e.mediaKeysSession;if(!p){l.emit("error",new Error("invalid state"));return}const{messageType:x,message:v}=m;this.log(`"${x}" message event for session "${p.sessionId}" message size: ${v.byteLength}`),x==="license-request"||x==="license-renewal"?this.renewLicense(e,v).catch(y=>{l.eventNames().length?l.emit("error",y):this.handleError(y)}):x==="license-release"?e.keySystem===He.FAIRPLAY&&this.updateKeySession(e,qi("acknowledged")).then(()=>this.removeSession(e)).catch(y=>this.handleError(y)):this.warn(`unhandled media key message type "${x}"`)},u=(m,p)=>{p.keyStatus=m;let x;m.startsWith("usable")?l.emit("resolved"):m==="internal-error"||m==="output-restricted"||m==="output-downscaled"?x=$l(m,p.decryptdata):m==="expired"?x=new Error(`key expired (keyId: ${a})`):m==="released"?x=new Error("key released"):m==="status-pending"||this.warn(`unhandled key status change "${m}" (keyId: ${a})`),x&&(l.eventNames().length?l.emit("error",x):this.handleError(x))},h=e._onkeystatuseschange=m=>{if(!e.mediaKeysSession){l.emit("error",new Error("invalid state"));return}const x=this.getKeyStatuses(e);if(!Object.keys(x).some(T=>x[T]!=="status-pending"))return;if(x[a]==="expired"){this.log(`Expired key ${Ne(x)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let y=x[a];if(y)u(y,e);else{var b;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(b=e.keyStatusTimeouts)[a]||(b[a]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const R=this.getKeyStatus(e.decryptdata);if(R&&R!=="status-pending")return this.log(`No status for keyId ${a} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${R} from other session.`),u(R,e);this.log(`key status for ${a} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),y="internal-error",u(y,e)},1e3)),this.log(`No status for keyId ${a} (${Ne(x)}).`)}};ht(e.mediaKeysSession,"message",d),ht(e.mediaKeysSession,"keystatuseschange",h);const g=new Promise((m,p)=>{l.on("error",p),l.on("resolved",m)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${a} URI: ${c}`)}).catch(m=>{throw new Lt({type:ce.KEY_SYSTEM_ERROR,details:B.KEY_SYSTEM_NO_SESSION,error:m,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${m}`)}).then(()=>g).catch(m=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw m}))).then(()=>(l.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((s,n)=>{if(typeof n=="string"&&typeof s=="object"){const a=n;n=s,s=a}const i="buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);if(e.keySystem===He.PLAYREADY&&i.length===16){const a=ct(i);t[a]=s,Of(i)}const o=ct(i);s==="internal-error"&&(this.bannedKeyIds[o]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${o} key-session "${e.mediaKeysSession.sessionId}"`),t[o]=s}),t}fetchServerCertificate(e){const t=this.config,s=t.loader,n=new s(t),i=this.getServerCertificateUrl(e);return i?(this.log(`Fetching server certificate for "${e}"`),new Promise((o,a)=>{const c={responseType:"arraybuffer",url:i},l=t.certLoadPolicy.default,d={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(h,g,m,p)=>{o(h.data)},onError:(h,g,m,p)=>{a(new Lt({type:ce.KEY_SYSTEM_ERROR,details:B.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:_e({url:c.url,data:void 0},h)},`"${e}" certificate request failed (${i}). Status: ${h.code} (${h.text})`))},onTimeout:(h,g,m)=>{a(new Lt({type:ce.KEY_SYSTEM_ERROR,details:B.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${i})`))},onAbort:(h,g,m)=>{a(new Error("aborted"))}};n.load(c,d,u)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((n,i)=>{e.setServerCertificate(s).then(o=>{this.log(`setServerCertificate ${o?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),n(e)}).catch(o=>{i(new Lt({type:ce.KEY_SYSTEM_ERROR,details:B.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:o,fatal:!0},o.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(n=>{throw new Lt({type:ce.KEY_SYSTEM_ERROR,details:B.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:n,fatal:!1},n.message)}))}unpackPlayReadyKeyMessage(e,t){const s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const n=new DOMParser().parseFromString(s,"application/xml"),i=n.querySelectorAll("HttpHeader");if(i.length>0){let d;for(let u=0,h=i.length;u<h;u++){var o,a;d=i[u];const g=(o=d.querySelector("name"))==null?void 0:o.textContent,m=(a=d.querySelector("value"))==null?void 0:a.textContent;g&&m&&e.setRequestHeader(g,m)}}const c=n.querySelector("Challenge"),l=c==null?void 0:c.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return qi(atob(l))}setupLicenseXHR(e,t,s,n){const i=this.config.licenseXhrSetup;return i?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return i.call(this.hls,e,t,s,n)}).catch(o=>{if(!s.decryptdata)throw o;return e.open("POST",t,!0),i.call(this.hls,e,t,s,n)}).then(o=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:o||n})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise((n,i)=>{const o=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${o}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return i(new Error("invalid state"));if(a.readyState===4)if(a.status===200){this._requestLicenseFailureCount=0;let c=a.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const l=this.config.licenseResponseCallback;if(l)try{c=l.call(this.hls,a,o,e)}catch(d){this.error(d)}n(c)}else{const c=s.errorRetry,l=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)i(new Lt({type:ce.KEY_SYSTEM_ERROR,details:B.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:a,response:{url:o,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${o}). Status: ${a.status} (${a.statusText})`));else{const d=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${d} attempts left`),this.requestLicense(e,t).then(n,i)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,o,e,t).then(({xhr:c,licenseChallenge:l})=>{e.keySystem==He.PLAYREADY&&(l=this.unpackPlayReadyKeyMessage(c,l)),c.send(l)}).catch(i)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,ht(s,"encrypted",this.onMediaEncrypted),ht(s,"waitingforkey",this.onWaitingForKey);const n=this.mediaResolved;n?n():this.mediaKeys=s.mediaKeys}onMediaDetached(){const e=this.media;e&&(yt(e,"encrypted",this.onMediaEncrypted),yt(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const s=this.media,n=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,bs.clearKeyUriToKeyIdMap();const i=n.length;er.CDMCleanupPromise=Promise.all(n.map(o=>this.removeSession(o)).concat((s==null||(e=s.setMediaKeys(null))==null?void 0:e.catch(o=>{this.log(`Could not clear media keys: ${o}`),this.hls&&this.hls.trigger(S.ERROR,{type:ce.OTHER_ERROR,details:B.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${o}`)})}))||Promise.resolve())).catch(o=>{this.log(`Could not close sessions and clear media keys: ${o}`),this.hls&&this.hls.trigger(S.ERROR,{type:ce.OTHER_ERROR,details:B.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${o}`)})}).then(()=>{i&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const s=t.reduce((n,i)=>(n.indexOf(i.keyFormat)===-1&&n.push(i.keyFormat),n),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s,decryptdata:n}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${ct((n==null?void 0:n.keyId)||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(e);i>-1&&this.mediaKeySessions.splice(i,1);const{keyStatusTimeouts:o}=e;o&&Object.keys(o).forEach(l=>self.clearTimeout(o[l]));const{drmSystemOptions:a}=this.config;return(_y(a)?new Promise((l,d)=>{self.setTimeout(()=>d(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(l).catch(d)}):Promise.resolve()).catch(l=>{this.log(`Could not remove session: ${l}`),this.hls&&this.hls.trigger(S.ERROR,{type:ce.OTHER_ERROR,details:B.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${l}`)})}).then(()=>t.close()).catch(l=>{this.log(`Could not close session: ${l}`),this.hls&&this.hls.trigger(S.ERROR,{type:ce.OTHER_ERROR,details:B.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${l}`)})})}return Promise.resolve()}}er.CDMCleanupPromise=void 0;function rn(r){if(!r)throw new Error("Could not read keyId of undefined decryptdata");if(r.keyId===null)throw new Error("keyId is null");return ct(r.keyId)}function qS(r,e){if(r.keyId&&e.mediaKeysSession.keyStatuses.has(r.keyId))return e.mediaKeysSession.keyStatuses.get(r.keyId);if(r.matches(e.decryptdata))return e.keyStatus}class Lt 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 $l(r,e){const t=r==="output-restricted",s=t?B.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:B.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Lt({type:ce.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${r}"`)}class XS{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(S.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(S.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(S.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(S.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.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),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const n=performance.now();if(t){if(this.lastTime){const i=n-this.lastTime,o=s-this.lastDroppedFrames,a=t-this.lastDecodedFrames,c=1e3*o/i,l=this.hls;if(l.trigger(S.FPS_DROP,{currentDropped:o,currentDecoded:a,totalDroppedFrames:s}),c>0&&o>l.config.fpsDroppedMonitoringThreshold*a){let d=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+d),d>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=d)&&(d=d-1,l.trigger(S.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:l.currentLevel}),l.autoLevelCapping=d,this.streamController.nextLevelSwitch())}}this.lastTime=n,this.lastDroppedFrames=s,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 Ch(r,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=r,e.dispatchEvent(t)}function _h(r,e){const t=r.mode;if(t==="disabled"&&(r.mode="hidden"),r.cues&&!r.cues.getCueById(e.id))try{if(r.addCue(e),!r.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){ke.debug(`[texttrack-utils]: ${s}`);try{const n=new self.TextTrackCue(e.startTime,e.endTime,e.text);n.id=e.id,r.addCue(n)}catch(n){ke.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${n}`)}}t==="disabled"&&(r.mode=t)}function Qs(r,e){const t=r.mode;if(t==="disabled"&&(r.mode="hidden"),r.cues)for(let s=r.cues.length;s--;)e&&r.cues[s].removeEventListener("enter",e),r.removeCue(r.cues[s]);t==="disabled"&&(r.mode=t)}function no(r,e,t,s){const n=r.mode;if(n==="disabled"&&(r.mode="hidden"),r.cues&&r.cues.length>0){const i=ZS(r.cues,e,t);for(let o=0;o<i.length;o++)(!s||s(i[o]))&&r.removeCue(i[o])}n==="disabled"&&(r.mode=n)}function QS(r,e){if(e<=r[0].startTime)return 0;const t=r.length-1;if(e>r[t].endTime)return-1;let s=0,n=t,i;for(;s<=n;)if(i=Math.floor((n+s)/2),e<r[i].startTime)n=i-1;else if(e>r[i].startTime&&s<t)s=i+1;else return i;return r[s].startTime-e<e-r[n].startTime?s:n}function ZS(r,e,t){const s=[],n=QS(r,e);if(n>-1)for(let i=n,o=r.length;i<o;i++){const a=r[i];if(a.startTime>=e&&a.endTime<=t)s.push(a);else if(a.startTime>t)return s}return s}function vn(r){const e=[];for(let t=0;t<r.length;t++){const s=r[t];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&e.push(r[t])}return e}class JS extends ua{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 s=vn(this.media.textTracks);for(let i=0;i<s.length;i++)if(s[i].mode==="hidden")t=s[i];else if(s[i].mode==="showing"){t=s[i];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(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.MANIFEST_PARSED,this.onManifestParsed,this),e.on(S.LEVEL_LOADING,this.onLevelLoading,this),e.on(S.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(S.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(S.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.MANIFEST_PARSED,this.onManifestParsed,this),e.off(S.LEVEL_LOADING,this.onLevelLoading,this),e.off(S.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(S.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(S.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 s=this.media;if(!s)return;const n=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,n)return;vn(s.textTracks).forEach(o=>{Qs(o)})}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:s,groupId:n,details:i}=t,o=this.tracksInGroup[s];if(!o||o.groupId!==n){this.warn(`Subtitle track with id:${s} and group:${n} not found in active group ${o==null?void 0:o.groupId}`);return}const a=o.details;o.details=t.details,this.log(`Subtitle track ${s} "${o.name}" lang:${o.lang} group:${n} loaded [${i.startSN}-${i.endSN}]`),s===this.trackId&&this.playlistLoaded(s,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 s=t.subtitleGroups||null,n=this.groupIds;let i=this.currentTrack;if(!s||(n==null?void 0:n.length)!==(s==null?void 0:s.length)||s!=null&&s.some(o=>(n==null?void 0:n.indexOf(o))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(d=>!s||s.indexOf(d.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(d=>d.default)&&(this.selectDefaultTrack=!1),o.forEach((d,u)=>{d.id=u});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const a=this.hls.config.subtitlePreference;if(!i&&a){this.selectDefaultTrack=!1;const d=es(a,o);if(d>-1)i=o[d];else{const u=es(a,this.tracks);i=this.tracks[u]}}let c=this.findTrackId(i);c===-1&&i&&(c=this.findTrackId(null));const l={subtitleTracks:o};this.log(`Updating subtitle tracks, ${o.length} track(s) found in "${s==null?void 0:s.join(",")}" group-id`),this.hls.trigger(S.SUBTITLE_TRACKS_UPDATED,l),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let n=0;n<t.length;n++){const i=t[n];if(!(s&&!i.default||!s&&!e)&&(!e||Ns(i,e)))return n}if(e){for(let n=0;n<t.length;n++){const i=t[n];if(Fr(e.attrs,i.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return n}for(let n=0;n<t.length;n++){const i=t[n];if(Fr(e.attrs,i.attrs,["LANGUAGE"]))return n}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const n=t[s];if(eo(n,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===Te.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 s=this.currentTrack;if(s&&Ns(e,s))return s;const n=es(e,this.tracksInGroup);if(n>-1){const i=this.tracksInGroup[n];return this.setSubtitleTrack(n),i}else{if(s)return null;{const i=es(e,t);if(i>-1)return t[i]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,n=e.groupId,i=this.getUrlWithDirectives(e.url,t),o=e.details,a=o==null?void 0:o.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${a&&o.live?" age "+a.toFixed(1)+(o.type&&" "+o.type||""):""} ${i}`),this.hls.trigger(S.SUBTITLE_TRACK_LOADING,{url:i,id:s,groupId:n,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=vn(e.textTracks),s=this.currentTrack;let n;if(s&&(n=t.filter(i=>eo(s,i))[0],n||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(i=>{i.mode!=="disabled"&&i!==n&&(i.mode="disabled")}),n){const i=this.subtitleDisplay?"showing":"hidden";n.mode!==i&&(n.mode=i)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!ne(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,n=t[e]||null;if(this.trackId=e,this.currentTrack=n,this.toggleTrackModes(),!n){this.hls.trigger(S.SUBTITLE_TRACK_SWITCH,{id:e});return}const i=!!n.details&&!n.details.live;if(e===this.trackId&&n===s&&i)return;this.log(`Switching to subtitle-track ${e}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));const{id:o,groupId:a="",name:c,type:l,url:d}=n;this.hls.trigger(S.SUBTITLE_TRACK_SWITCH,{id:o,groupId:a,name:c,type:l,url:d});const u=this.switchParams(n.url,s==null?void 0:s.details,n.details);this.loadPlaylist(u)}}function eE(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const i=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(n=="x"?i:i&3|8).toString(16)})}}}function Tr(r){let e=5381,t=r.length;for(;t;)e=e*33^r.charCodeAt(--t);return(e>>>0).toString()}const tr=.025;let Nn=function(r){return r[r.Point=0]="Point",r[r.Range=1]="Range",r}({});function tE(r,e,t){return`${r.identifier}-${t+1}-${Tr(e)}`}class sE{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 s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}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 yi(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,s=yi(t,e);return t-s<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=ne(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 yi(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)<tr))}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"?Nn.Range:Nn.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 rE(this)}}function yi(r,e){return r-e.start<e.duration/2&&!(Math.abs(r-(e.start+e.duration))<tr)?e.start:e.start+e.duration}function kh(r,e,t){const s=new self.URL(r,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function bi(r,e){for(;(t=r.assetList[++e])!=null&&t.error;)var t;return e}function rE(r){return`["${r.identifier}" ${r.cue.pre?"<pre>":r.cue.post?"<post>":""}${r.timelineStart.toFixed(2)}-${r.resumeTime.toFixed(2)}]`}function Xs(r){const e=r.timelineStart,t=r.duration||0;return`["${r.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class nE{constructor(e,t,s,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(S.PLAYOUT_LIMIT_REACHED,{})};const i=this.hls=new e(t);this.interstitial=s,this.assetItem=n;const o=()=>{this.hasDetails=!0};i.once(S.LEVEL_LOADED,o),i.once(S.AUDIO_TRACK_LOADED,o),i.once(S.SUBTITLE_TRACK_LOADED,o),i.on(S.MEDIA_ATTACHING,(a,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&i.on(S.BUFFER_APPENDED,()=>{const d=this.bufferedEnd;this.reachedPlayout(d)&&(this._bufferedEosTime=d,i.trigger(S.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=kh(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 s=Math.min(this._bufferedEosTime||1/0,this.duration),n=this.timelineOffset,i=ve.bufferInfo(e,n,0);return this.getAssetTime(i.end)>=s-.02}reachedPlayout(e){const s=this.interstitial.playoutLimit;return this.startOffset+e>=s}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=ve.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 s=t-this.startOffset;if(s>0&&s<e)return s}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 s=e-t;if(Math.abs(s)>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,s=this.duration;return Math.min(Math.max(0,e-t),s)}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=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var n;(n=this.hls)==null||n.on(e,t)}once(e,t,s){var n;(n=this.hls)==null||n.once(e,t)}off(e,t,s){var n;(n=this.hls)==null||n.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${Xs(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Ul=.033;class iE extends Ut{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((s,n)=>e<=n.startOffset&&t>n.startOffset?(delete n.error,s+1):s,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 s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const n=this.items;if(n)for(n[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(i=n[s])!=null&&i.event;){var i;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let n=0;n<s.length;n++){let i=s[n];if(t&&t!=="primary"&&(i=i[t]),e===i.start||e>i.start&&e<i.end)return n}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let n=e;n<=t&&s[n];n++){const i=s[n].event;if(i!=null&&i.restrictions.jump&&!i.appendInPlace)return n}return-1}findEventIndex(e){const t=this.items;if(t)for(let n=t.length;n--;){var s;if(((s=t[n].event)==null?void 0:s.identifier)===e)return n}return-1}findAssetIndex(e,t){const s=e.assetList,n=s.length;if(n>1)for(let i=0;i<n;i++){const o=s[i];if(!o.error){const a=o.timelineStart;if(t===a||t>a&&(t<a+(o.duration||0)||i===n-1))return i}}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 s=t.assetList,n=s[s.length-1];if(n)return n.identifier}return null}parseInterstitialDateRanges(e,t){const s=e.main.details,{dateRanges:n}=s,i=this.events,o=this.parseDateRanges(n,{url:s.url},t),a=Object.keys(n),c=i?i.filter(l=>!a.includes(l.identifier)):[];o.length&&o.sort((l,d)=>{const u=l.cue.pre,h=l.cue.post,g=d.cue.pre,m=d.cue.post;if(u&&!g)return-1;if(g&&!u||h&&!m)return 1;if(m&&!h)return-1;if(!u&&!g&&!h&&!m){const p=l.startTime,x=d.startTime;if(p!==x)return p-x}return l.dateRange.tagOrder-d.dateRange.tagOrder}),this.events=o,c.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,c)}updateSchedule(e,t=[],s=!1){const n=this.events||[];if(n.length||t.length||this.length<2){const i=this.items,o=this.parseSchedule(n,e);(s||t.length||(i==null?void 0:i.length)!==o.length||o.some((c,l)=>Math.abs(c.playout.start-i[l].playout.start)>.005||Math.abs(c.playout.end-i[l].playout.end)>.005))&&(this.items=o,this.onScheduleUpdate(t,i))}}parseDateRanges(e,t,s){const n=[],i=Object.keys(e);for(let o=0;o<i.length;o++){const a=i[o],c=e[a];if(c.isInterstitial){let l=this.eventMap[a];l?l.setDateRange(c):(l=new sE(c,t),this.eventMap[a]=l,s===!1&&(l.appendInPlace=s)),n.push(l)}}return n}parseSchedule(e,t){const s=[],n=t.main.details,i=n.live?1/0:n.edge;let o=0;if(e=e.filter(c=>!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,l=0;if(e.forEach((d,u)=>{const h=d.cue.pre,g=d.cue.post,m=e[u-1]||null,p=d.appendInPlace,x=g?i:d.startOffset,v=d.duration,y=d.timelineOccupancy===Nn.Range?v:0,b=d.resumptionOffset,T=(m==null?void 0:m.startTime)===x,R=x+d.cumulativeDuration;let _=p?R+v:x+b;if(h||!g&&x<=0){const A=l;l+=y,d.timelineStart=R;const C=o;o+=v,s.push({event:d,start:R,end:_,playout:{start:C,end:o},integrated:{start:A,end:l}})}else if(x<=i){if(!T){const L=x-c;if(L>Ul){const P=c,M=l;l+=L;const j=o;o+=L;const D={previousEvent:e[u-1]||null,nextEvent:d,start:P,end:P+L,playout:{start:j,end:o},integrated:{start:M,end:l}};s.push(D)}else L>0&&m&&(m.cumulativeDuration+=L,s[s.length-1].end=x)}g&&(_=R),d.timelineStart=R;const A=l;l+=y;const C=o;o+=v,s.push({event:d,start:R,end:_,playout:{start:C,end:o},integrated:{start:A,end:l}})}else return;const w=d.resumeTime;g||w>i?c=i:c=w}),c<i){var a;const d=c,u=l,h=i-c;l+=h;const g=o;o+=h,s.push({previousEvent:((a=s[s.length-1])==null?void 0:a.event)||null,nextEvent:null,start:c,end:d+h,playout:{start:g,end:o},integrated:{start:u,end:l}})}this.setDurations(i,o,l)}else s.push({previousEvent:null,nextEvent:null,start:0,end:i,playout:{start:0,end:i},integrated:{start:0,end:i}}),this.setDurations(i,i,i);return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,n=s.live?1/0:s.edge;let i=0,o=-1;e.forEach((a,c)=>{const l=a.cue.pre,d=a.cue.post,u=l?0:d?n:a.startTime;this.updateAssetDurations(a),o===u?a.cumulativeDuration=i:(i=0,o=u),!d&&a.snapOptions.in&&(a.resumeAnchor=Os(null,s.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(a,t)||(a.appendInPlace=!1)),!a.appendInPlace&&c+1<e.length&&e[c+1].startTime-e[c].resumeTime<Ul&&(e[c+1].appendInPlace=!1,e[c+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`));const g=ne(a.resumeOffset)?a.resumeOffset:a.duration;i+=g})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,n=e.startTime+e.resumptionOffset;return Math.abs(s-n)>tr?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${n}`),!1):!Object.keys(t).some(o=>{const a=t[o].details,c=a.edge;if(s>=c)return this.log(`"${e.identifier}" resumption ${s} past ${o} playlist end ${c}`),!1;const l=Os(null,a.fragments,s);if(!l)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${o} playlist (${a.fragStart}-${a.fragmentEnd})`),!0;const d=o==="audio"?.175:0;return Math.abs(l.start-s)<tr+d||Math.abs(l.end-s)<tr+d?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${o} fragment bounds (${l.start}-${l.end} sn: ${l.sn} cc: ${l.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,n=!1,i=!1;for(let o=0;o<e.assetList.length;o++){const a=e.assetList[o],c=t+s;a.startOffset=s,a.timelineStart=c,n||(n=a.duration===null),i||(i=!!a.error);const l=a.error?0:a.duration||0;s+=l}n&&!i?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function Ht(r){return`[${r.event?'"'+r.event.identifier+'"':"primary"}: ${r.start.toFixed(2)}-${r.end.toFixed(2)}]`}class oE{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let n;try{n=kh(s,this.hls.sessionId,e.baseUrl)}catch(h){const g=this.assignAssetListError(e,B.ASSET_LIST_LOAD_ERROR,h,s);this.hls.trigger(S.ERROR,g);return}t&&n.protocol!=="data:"&&n.searchParams.set("_HLS_start_offset",""+t);const i=this.hls.config,o=i.loader,a=new o(i),c={responseType:"json",url:n.href},l=i.interstitialAssetListLoadPolicy.default,d={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(h,g,m,p)=>{const x=h.data,v=x==null?void 0:x.ASSETS;if(!Array.isArray(v)){const y=this.assignAssetListError(e,B.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),m.url,g,p);this.hls.trigger(S.ERROR,y);return}e.assetListResponse=x,this.hls.trigger(S.ASSET_LIST_LOADED,{event:e,assetListResponse:x,networkDetails:p})},onError:(h,g,m,p)=>{const x=this.assignAssetListError(e,B.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${h.code} ${h.text} (${g.url})`),g.url,p,m);this.hls.trigger(S.ERROR,x)},onTimeout:(h,g,m)=>{const p=this.assignAssetListError(e,B.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${g.url})`),g.url,h,m);this.hls.trigger(S.ERROR,p)}};return a.load(c,d,u),this.hls.trigger(S.ASSET_LIST_LOADING,{event:e}),a}assignAssetListError(e,t,s,n,i,o){return e.error=s,{type:ce.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:n,error:s,networkDetails:o,stats:i}}}function Gl(r){var e;r==null||(e=r.play())==null||e.catch(()=>{})}function nn(r,e){return`[${r}] Advancing timeline position to ${e}`}class aE extends Ut{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 s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;const n=s-this.timelinePos;if(Math.abs(n)<1/7056e5)return;const o=n<=-.01;this.timelinePos=s,this.bufferedPos=s;const a=this.playingItem;if(!a){this.checkBuffer();return}if(o&&this.schedule.resetErrorsInRange(s,s-n)&&this.updateSchedule(!0),this.checkBuffer(),o&&s<a.start||s>=a.end){var c;const g=this.findItemIndex(a);let m=this.schedule.findItemIndexAtTime(s);if(m===-1&&(m=g+(o?-1:1),this.log(`seeked ${o?"back ":""}to position not covered by schedule ${s} (resolving from ${g} to ${m})`)),!this.isInterstitial(a)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!o&&m>g){const p=this.schedule.findJumpRestrictedIndex(g+1,m);if(p>g){this.setSchedulePosition(p);return}}this.setSchedulePosition(m);return}const l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(a)){const g=a.event.assetList[0];g&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,g))}return}const d=l.timelineStart,u=l.duration||0;if(o&&s<d||s>=d+u){var h;(h=a.event)!=null&&h.appendInPlace&&(this.clearAssetPlayers(a.event,a),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,l)}},this.onTimeupdate=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;const n=this.playingItem;if(!n||this.playingLastItem)return;if(s>=n.end){this.timelinePos=n.end;const a=this.findItemIndex(n);this.setSchedulePosition(a+1)}const i=this.playingAsset;if(!i)return;const o=i.timelineStart+(i.duration||0);s>=o&&this.setScheduleToAssetAtTime(s,i)},this.onScheduleUpdate=(s,n)=>{const i=this.schedule;if(!i)return;const o=this.playingItem,a=i.events||[],c=i.items||[],l=i.durations,d=s.map(p=>p.identifier),u=!!(a.length||d.length);(u||n)&&this.log(`INTERSTITIALS_UPDATED (${a.length}): ${a}
63
+ Schedule: ${c.map(p=>Ht(p))} pos: ${this.timelinePos}`),d.length&&this.log(`Removed events ${d}`);let h=null,g=null;o&&(h=this.updateItem(o,this.timelinePos),this.itemsMatch(o,h)?this.playingItem=h:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const m=this.bufferingItem;if(m&&(g=this.updateItem(m,this.bufferedPos),this.itemsMatch(m,g)?this.bufferingItem=g:m.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(m.event,null))),s.forEach(p=>{p.assetList.forEach(x=>{this.clearAssetPlayer(x.identifier,null)})}),this.playerQueue.forEach(p=>{if(p.interstitial.appendInPlace){const x=p.assetItem.timelineStart,v=p.timelineOffset-x;if(v)try{p.timelineOffset=x}catch(y){Math.abs(v)>tr&&this.warn(`${y} ("${p.assetId}" ${p.timelineOffset}->${x})`)}}}),u||n){if(this.hls.trigger(S.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:c.slice(0),durations:l,removedIds:d}),this.isInterstitial(o)&&d.includes(o.event.identifier)){this.warn(`Interstitial "${o.event.identifier}" removed while playing`),this.primaryFallback(o.event);return}o&&this.trimInPlace(h,o),m&&g!==h&&this.trimInPlace(g,m),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new oE(e),this.schedule=new iE(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(S.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(S.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(S.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(S.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(S.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(S.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(S.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(S.BUFFER_APPENDED,this.onBufferAppended,this),e.on(S.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(S.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(S.MEDIA_ENDED,this.onMediaEnded,this),e.on(S.ERROR,this.onError,this),e.on(S.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(S.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(S.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(S.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(S.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(S.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(S.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(S.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(S.BUFFER_CODECS,this.onBufferCodecs,this),e.off(S.BUFFER_APPENDED,this.onBufferAppended,this),e.off(S.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(S.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(S.MEDIA_ENDED,this.onMediaEnded,this),e.off(S.ERROR,this.onError,this),e.off(S.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){yt(e,"play",this.onPlay),yt(e,"pause",this.onPause),yt(e,"seeking",this.onSeeking),yt(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;ht(s,"seeking",this.onSeeking),ht(s,"timeupdate",this.onTimeupdate),ht(s,"play",this.onPlay),ht(s,"pause",this.onPause)}onMediaAttached(e,t){const s=this.effectivePlayingItem,n=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!n){this.clearScheduleState();const i=this.findItemIndex(s);this.setSchedulePosition(i)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const s=!!t.transferMedia,n=this.media;if(this.media=null,!s&&(n&&this.removeMediaListeners(n),this.detachedData)){const i=this.getBufferingPlayer();i&&(this.log(`Removing schedule state for detachedData and ${i}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,i.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,s=u=>u&&e.getAssetPlayer(u.identifier),n=(u,h,g,m,p)=>{if(u){let x=u[h].start;const v=u.event;if(v){if(h==="playout"||v.timelineOccupancy!==Nn.Point){const y=s(g);(y==null?void 0:y.interstitial)===v&&(x+=y.assetItem.startOffset+y[p])}}else{const y=m==="bufferedPos"?o():e[m];x+=y-u.start}return x}return 0},i=(u,h)=>{var g;if(u!==0&&h!=="primary"&&(g=e.schedule)!=null&&g.length){var m;const p=e.schedule.findItemIndexAtTime(u),x=(m=e.schedule.items)==null?void 0:m[p];if(x){const v=x[h].start-x.start;return u+v}}return u},o=()=>{const u=e.bufferedPos;return u===Number.MAX_VALUE?a("primary"):Math.max(u,0)},a=u=>{var h,g;return(h=e.primaryDetails)!=null&&h.live?e.primaryDetails.edge:((g=e.schedule)==null?void 0:g.durations[u])||0},c=(u,h)=>{var g,m;const p=e.effectivePlayingItem;if(p!=null&&(g=p.event)!=null&&g.restrictions.skip||!e.schedule)return;e.log(`seek to ${u} "${h}"`);const x=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(u,h),y=(m=e.schedule.items)==null?void 0:m[v],b=e.getBufferingPlayer(),T=b==null?void 0:b.interstitial,R=T==null?void 0:T.appendInPlace,_=x&&e.itemsMatch(x,y);if(x&&(R||_)){const w=s(e.playingAsset),A=(w==null?void 0:w.media)||e.primaryMedia;if(A){const C=h==="primary"?A.currentTime:n(x,h,e.playingAsset,"timelinePos","currentTime"),L=u-C,P=(R?C:A.currentTime)+L;if(P>=0&&(!w||R||P<=w.duration)){A.currentTime=P;return}}}if(y){let w=u;if(h!=="primary"){const C=y[h].start,L=u-C;w=y.start+L}const A=!e.isInterstitial(y);if((!e.isInterstitial(x)||x.event.appendInPlace)&&(A||y.event.appendInPlace)){const C=e.media||(R?b==null?void 0:b.media:null);C&&(C.currentTime=w)}else if(x){const C=e.findItemIndex(x);if(v>C){const P=e.schedule.findJumpRestrictedIndex(C+1,v);if(P>C){e.setSchedulePosition(P);return}}let L=0;if(A)e.timelinePos=w,e.checkBuffer();else{const P=y.event.assetList,M=u-(y[h]||y).start;for(let j=P.length;j--;){const D=P[j];if(D.duration&&M>=D.startOffset&&M<D.startOffset+D.duration){L=j;break}}}e.setSchedulePosition(v,L)}}},l=()=>{const u=e.effectivePlayingItem;if(e.isInterstitial(u))return u;const h=t();return e.isInterstitial(h)?h:null},d={get bufferedEnd(){const u=t(),h=e.bufferingItem;if(h&&h===u){var g;return n(h,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-h.playout.start||((g=e.bufferingAsset)==null?void 0:g.startOffset)||0}return 0},get currentTime(){const u=l(),h=e.effectivePlayingItem;return h&&h===u?n(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(u){const h=l(),g=e.effectivePlayingItem;g&&g===h&&c(u+g.playout.start,"playout")},get duration(){const u=l();return u?u.playout.end-u.playout.start:0},get assetPlayers(){var u;const h=(u=l())==null?void 0:u.event.assetList;return h?h.map(g=>e.getAssetPlayer(g.identifier)):[]},get playingIndex(){var u;const h=(u=l())==null?void 0:u.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};return this.manager={get events(){var u;return((u=e.schedule)==null||(u=u.events)==null?void 0:u.slice(0))||[]},get schedule(){var u;return((u=e.schedule)==null||(u=u.items)==null?void 0:u.slice(0))||[]},get interstitialPlayer(){return l()?d:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const u=t();return e.findItemIndex(u)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const u=e.effectivePlayingItem;return e.findItemIndex(u)},primary:{get bufferedEnd(){return o()},get currentTime(){const u=e.timelinePos;return u>0?u:0},set currentTime(u){c(u,"primary")},get duration(){return a("primary")},get seekableStart(){var u;return((u=e.primaryDetails)==null?void 0:u.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(u){c(u,"integrated")},get duration(){return a("integrated")},get seekableStart(){var u;return i(((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0,"integrated")}},skip:()=>{const u=e.effectivePlayingItem,h=u==null?void 0:u.event;if(h&&!h.restrictions.skip){const g=e.findItemIndex(u);if(h.appendInPlace){const m=u.playout.start+u.event.duration;c(m+.001,"playout")}else e.advanceAfterAssetEnded(h,g,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,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let n=this.media;!n&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(n=this.primaryMedia);const i=(t=n)==null?void 0:t.currentTime;if(!(i===void 0||!ne(i)))return i}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,n=e.media;if(s&&n===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&n){this.detachedData={media:n};return}const i=e.transferMedia();this.log(`transfer MediaSource from ${e} ${Ne(i)}`),this.detachedData=i}else t&&n&&(this.shouldPlay||(this.shouldPlay=!n.paused))}transferMediaTo(e,t){var s,n;if(e.media===t)return;let i=null;const o=this.hls,a=e!==o,c=a&&e.interstitial.appendInPlace,l=(s=this.detachedData)==null?void 0:s.mediaSource;let d;if(o.media)c&&(i=o.transferMedia(),this.detachedData=i),d="Primary";else if(l){const m=this.getBufferingPlayer();m?(i=m.transferMedia(),d=`${m}`):d="detached MediaSource"}else d="detached media";if(!i){if(l)i=this.detachedData,this.log(`using detachedData: MediaSource ${Ne(i)}`);else if(!this.detachedData||o.media===t){const m=this.playerQueue;m.length>1&&m.forEach(p=>{if(a&&p.interstitial.appendInPlace!==c){const x=p.interstitial;this.clearInterstitial(p.interstitial,null),x.appendInPlace=!1,x.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${x}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const u=i&&"mediaSource"in i&&((n=i.mediaSource)==null?void 0:n.readyState)!=="closed",h=u&&i?i:t;this.log(`${u?"transfering MediaSource":"attaching media"} to ${a?e:"Primary"} from ${d} (media.currentTime: ${t.currentTime})`);const g=this.schedule;if(h===i&&g){const m=a&&e.assetId===g.assetIdAtEnd;h.overrides={duration:g.duration,endOfStream:!a||m,cueRemoval:!a}}e.attachMedia(h)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e==null?void 0:e.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const s=this.timelinePos,n=this.effectivePlayingItem;if(s===-1){const i=this.hls.startPosition;if(this.log(nn("checkStart",i)),this.timelinePos=i,t.length&&t[0].cue.pre){const o=e.findEventIndex(t[0].identifier);this.setSchedulePosition(o)}else if(i>=0||!this.primaryLive){const o=this.timelinePos=i>0?i:0,a=e.findItemIndexAtTime(o);this.setSchedulePosition(a)}}else if(n&&!this.playingItem){const i=e.findItemIndex(n);this.setSchedulePosition(i)}}advanceAssetBuffering(e,t){const s=e.event,n=s.findAssetIndex(t),i=bi(s,n);if(!s.isAssetPastPlayoutLimit(i))this.bufferedToEvent(e,i);else if(this.schedule){var o;const a=(o=this.schedule.items)==null?void 0:o[this.findItemIndex(e)+1];a&&this.bufferedToItem(a)}}advanceAfterAssetEnded(e,t,s){const n=bi(e,s);if(e.isAssetPastPlayoutLimit(n)){if(this.schedule){const i=this.schedule.items;if(i){const o=t+1,a=i.length;if(o>=a){this.setSchedulePosition(-1);return}const c=e.resumeTime;this.timelinePos<c&&(this.log(nn("advanceAfterAssetEnded",c)),this.timelinePos=c,e.appendInPlace&&this.advanceInPlace(c),this.checkBuffer(this.bufferedPos<c)),this.setSchedulePosition(o)}}}else{if(e.appendInPlace){const i=e.assetList[n];i&&this.advanceInPlace(i.timelineStart)}this.setSchedulePosition(t,n)}}setScheduleToAssetAtTime(e,t){const s=this.schedule;if(!s)return;const n=t.parentIdentifier,i=s.getEvent(n);if(i){const o=s.findEventIndex(n),a=s.findAssetIndex(i,e);this.advanceAfterAssetEnded(i,o,a-1)}}setSchedulePosition(e,t){var s;const n=(s=this.schedule)==null?void 0:s.items;if(!n||this.playbackDisabled)return;const i=e>=0?n[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${i&&Ht(i)}) pos: ${this.timelinePos}`);const o=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(o)){const d=o.event,u=this.playingAsset,h=u==null?void 0:u.identifier,g=h?this.getAssetPlayer(h):null;if(g&&h&&(!this.eventItemsMatch(o,i)||t!==void 0&&h!==d.assetList[t].identifier)){var c;const m=d.findAssetIndex(u);if(this.log(`INTERSTITIAL_ASSET_ENDED ${m+1}/${d.assetList.length} ${Xs(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(S.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:m,event:d,schedule:n.slice(0),scheduleIndex:e,player:g}),o!==this.playingItem){this.itemsMatch(o,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(d,this.findItemIndex(this.playingItem),m);return}this.retreiveMediaSource(h,i),g.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&g.detachMedia()}if(!this.eventItemsMatch(o,i)&&(this.endedItem=o,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${d} ${Ht(o)}`),d.hasPlayed=!0,this.hls.trigger(S.INTERSTITIAL_ENDED,{event:d,schedule:n.slice(0),scheduleIndex:e}),d.cue.once)){var l;this.updateSchedule();const m=(l=this.schedule)==null?void 0:l.items;if(i&&m){const p=this.findItemIndex(i);this.advanceSchedule(p,m,t,o,a)}return}}this.advanceSchedule(e,n,t,o,a)}advanceSchedule(e,t,s,n,i){const o=this.schedule;if(!o)return;const a=t[e]||null,c=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(d=>{const u=d.interstitial,h=o.findEventIndex(u.identifier);(h<e||h>e+1)&&this.clearInterstitial(u,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const d=a.event;if(s===void 0){s=o.findAssetIndex(d,this.timelinePos);const m=bi(d,s-1);if(d.isAssetPastPlayoutLimit(m)||d.appendInPlace&&this.timelinePos===a.end){this.advanceAfterAssetEnded(d,e,s);return}s=m}const u=this.waitingItem;this.assetsBuffered(a,c)||this.setBufferingItem(a);let h=this.preloadAssets(d,s);if(this.eventItemsMatch(a,u||n)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${Ht(a)} ${d.appendInPlace?"append in place":""}`),this.hls.trigger(S.INTERSTITIAL_STARTED,{event:d,schedule:t.slice(0),scheduleIndex:e})),!d.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${d}`);return}if(d.assetListLoader&&(d.assetListLoader.destroy(),d.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${d}`);return}this.waitingItem=this.endedItem=null,this.playingItem=a;const g=d.assetList[s];if(!g){this.advanceAfterAssetEnded(d,e,s||0);return}if(h||(h=this.getAssetPlayer(g.identifier)),h===null||h.destroyed){const m=d.assetList.length;this.warn(`asset ${s+1}/${m} player destroyed ${d}`),h=this.createAssetPlayer(d,g,s),h.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&d.appendInPlace&&this.isAssetBuffered(g))return;this.startAssetPlayer(h,s,t,e,c),this.shouldPlay&&Gl(h.media)}else a?(this.resumePrimary(a,e,n),this.shouldPlay&&Gl(this.hls.media)):i&&this.isInterstitial(n)&&(this.endedItem=null,this.playingItem=n,n.event.appendInPlace||this.attachPrimary(o.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,s){var n,i;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Ht(e)}`),!((n=this.detachedData)!=null&&n.mediaSource)){let a=this.timelinePos;(a<e.start||a>=e.end)&&(a=this.getPrimaryResumption(e,t),this.log(nn("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)}if(!s)return;const o=(i=this.schedule)==null?void 0:i.items;o&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Ht(e)}`),this.hls.trigger(S.INTERSTITIALS_PRIMARY_RESUMED,{schedule:o.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const s=e.start;if(this.primaryLive){const n=this.primaryDetails;if(t===0)return this.hls.startPosition;if(n&&(s<n.fragmentStart||s>n.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:ve.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const n=this.primaryMedia;if(!n)return;const i=this.hls;i.media?this.checkBuffer():(this.transferMediaTo(i,n),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(nn("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){var s;const n=this.hls;!n.loadingEnabled||!n.media||Math.abs((((s=n.mainForwardBufferInfo)==null?void 0:s.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(S.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(S.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const s=this.hls.levels[t.level];if(!s.details)return;const n=_e(_e({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=n,this.schedule.parseInterstitialDateRanges(n,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=_e(_e({},this.altSelection),{},{audio:s});return}const i=_e(_e({},n),{},{audio:s});this.mediaSelection=i}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=_e(_e({},this.altSelection),{},{subtitles:s});return}const i=_e(_e({},n),{},{subtitles:s});this.mediaSelection=i}onAudioTrackSwitching(e,t){const s=Qa(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setAudioOption(t)||n.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=Qa(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setSubtitleOption(t)||t.id!==-1&&n.setSubtitleOption(s)))}onBufferCodecs(e,t){const s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){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 i=t[n];if(i.cue.post){var s;const o=this.schedule.findEventIndex(i.identifier),a=(s=this.schedule.items)==null?void 0:s[o];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 s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){var s;const n=(s=this.schedule)==null?void 0:s.items;if(e&&n){const i=this.findItemIndex(e,t);return n[i]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((i,o)=>{e.event.isAssetPastPlayoutLimit(o)&&this.clearAssetPlayer(i.identifier,null)});const s=e.end+.25,n=ve.bufferInfo(this.primaryMedia,s,0);(n.end>s||(n.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${Ht(e)} (was ${Ht(t)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}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 s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const s=this.mediaSelection;s&&((t=this.schedule)==null||t.updateSchedule(s,[],e))}checkBuffer(e){var t;const s=(t=this.schedule)==null?void 0:t.items;if(!s)return;const n=ve.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=n.len<1),this.updateBufferedPos(n.end,s,e)}updateBufferedPos(e,t,s){const n=this.schedule,i=this.bufferingItem;if(this.bufferedPos>e||!n)return;if(t.length===1&&this.itemsMatch(t[0],i)){this.bufferedPos=e;return}const o=this.playingItem,a=this.findItemIndex(o);let c=n.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const d=this.findItemIndex(i),u=Math.min(d+1,t.length-1),h=t[u];if((c===-1&&i&&e>=i.end||(l=h.event)!=null&&l.appendInPlace&&e+.01>=h.start)&&(c=u),this.isInterstitial(i)){const g=i.event;if(u-a>1&&g.appendInPlace===!1||g.assetList.length===0&&g.assetListLoader)return}if(this.bufferedPos=e,c>d&&c>a)this.bufferedToItem(h);else{const g=this.primaryDetails;this.primaryLive&&g&&e>g.edge-g.targetduration&&h.start<g.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(h)&&this.preloadAssets(h.event,0)}}else s&&o&&!this.itemsMatch(o,i)&&(c===a?this.bufferedToItem(o):c===a+1&&this.bufferedToItem(t[c]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(n=>{const i=this.getAssetPlayer(n.identifier);return!(i!=null&&i.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){const{items:n,events:i}=s;if(!n||!i)return t;const o=this.isInterstitial(e),a=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const c=a?a.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Ht(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(o){const l=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((d,u)=>{const h=this.getAssetPlayer(d.identifier);h&&(u===l&&h.loadSource(),h.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(l=>l.pauseBuffering());this.hls.trigger(S.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:i.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==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),s=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(s)}bufferedToEvent(e,t){const s=e.event,n=s.assetList.length===0&&!s.assetListLoader,i=s.cue.once;if(n||!i){const o=this.preloadAssets(s,t);if(o!=null&&o.interstitial.appendInPlace){const a=this.primaryMedia;a&&this.bufferAssetPlayer(o,a)}}}preloadAssets(e,t){const s=e.assetUrl,n=e.assetList.length,i=n===0&&!e.assetListLoader,o=e.cue.once;if(i){const c=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(c+.25)}let l,d=0;if(!this.playingItem&&this.primaryLive&&(d=this.hls.startPosition,d===-1&&(d=this.hls.liveSyncPosition||0)),d&&!(e.cue.pre||e.cue.post)){const h=d-c;h>0&&(l=Math.round(h*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:n} ${e}${l?` live-start: ${d} start-offset: ${l}`:""}`),s)return this.createAsset(e,0,0,c,e.duration,s);const u=this.assetListLoader.loadAssetList(e,l);u&&(e.assetListLoader=u)}else if(!o&&n){for(let l=t;l<n;l++){const d=e.assetList[l],u=this.getAssetPlayerQueueIndex(d.identifier);(u===-1||this.playerQueue[u].destroyed)&&!d.error&&this.createAssetPlayer(e,d,l)}const c=e.assetList[t];if(c){const l=this.getAssetPlayer(c.identifier);return l&&l.loadSource(),l}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(n=>{this.hls.trigger(S.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:n})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;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 s=0;s<e.length;s++)if(e[s].media===t)return e[s]}return null}createAsset(e,t,s,n,i,o){const a={parentIdentifier:e.identifier,identifier:tE(e,o,t),duration:i,startOffset:s,timelineStart:n,uri:o};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,s){const n=this.hls,i=n.userConfig;let o=i.videoPreference;const a=n.loadLevelObj||n.levels[n.currentLevel];(o||a)&&(o=De({},o),a.videoCodec&&(o.videoCodec=a.videoCodec),a.videoRange&&(o.allowedVideoRanges=[a.videoRange]));const c=n.audioTracks[n.audioTrack],l=n.subtitleTracks[n.subtitleTrack];let d=0;if(this.primaryLive||e.appendInPlace){const T=this.timelinePos-t.timelineStart;if(T>1){const R=t.duration;R&&T<R&&(d=T)}}const u=t.identifier,h=_e(_e({},i),{},{maxMaxBufferLength:Math.min(180,n.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:d,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:o,audioPreference:c||i.audioPreference,subtitlePreference:l||i.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(h.timelineOffset=t.timelineStart));const g=h.cmcd;g!=null&&g.sessionId&&g.contentId&&(h.cmcd=De({},g,{contentId:Tr(t.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${e} and asset ${u}`);const m=new nE(this.HlsPlayerClass,h,e,t);this.playerQueue.push(m),e.assetList[s]=t;let p=!0;const x=T=>{if(T.live){var R;const A=new Error(`Interstitials MUST be VOD assets ${e}`),C={fatal:!0,type:ce.OTHER_ERROR,details:B.INTERSTITIAL_ASSET_ITEM_ERROR,error:A},L=((R=this.schedule)==null?void 0:R.findEventIndex(e.identifier))||-1;this.handleAssetItemError(C,e,L,s,A.message);return}const _=T.edge-T.fragmentStart,w=t.duration;(p||w===null||_>w)&&(p=!1,this.log(`Interstitial asset "${u}" duration change ${w} > ${_}`),t.duration=_,this.updateSchedule())};m.on(S.LEVEL_UPDATED,(T,{details:R})=>x(R)),m.on(S.LEVEL_PTS_UPDATED,(T,{details:R})=>x(R)),m.on(S.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const v=(T,R)=>{const _=this.getAssetPlayer(u);if(_&&R.tracks){_.off(S.BUFFER_CODECS,v),_.tracks=R.tracks;const w=this.primaryMedia;this.bufferingAsset===_.assetItem&&w&&!_.media&&this.bufferAssetPlayer(_,w)}};m.on(S.BUFFER_CODECS,v);const y=()=>{var T;const R=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${R}`),!R||!this.schedule)return;const _=this.schedule.findEventIndex(e.identifier),w=(T=this.schedule.items)==null?void 0:T[_];this.isInterstitial(w)&&this.advanceAssetBuffering(w,t)};m.on(S.BUFFERED_TO_END,y);const b=T=>()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;this.shouldPlay=!0;const _=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,_,T)};return m.once(S.MEDIA_ENDED,b(s)),m.once(S.PLAYOUT_LIMIT_REACHED,b(1/0)),m.on(S.ERROR,(T,R)=>{if(!this.schedule)return;const _=this.getAssetPlayer(u);if(R.details===B.BUFFER_STALLED_ERROR){if(_!=null&&_.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(R,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${R.error} ${e}`)}),m.on(S.DESTROYING,()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;const R=new Error(`Asset player destroyed unexpectedly ${u}`),_={fatal:!0,type:ce.OTHER_ERROR,details:B.INTERSTITIAL_ASSET_ITEM_ERROR,error:R};this.handleAssetItemError(_,e,this.schedule.findEventIndex(e.identifier),s,R.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Xs(t)}`),this.hls.trigger(S.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:m}),m}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(s!==-1){const n=this.playerQueue[s];this.log(`clear ${n} toSegment: ${t&&Ht(t)}`),this.transferMediaFromPlayer(n,t),this.playerQueue.splice(s,1),n.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,n,i){const{interstitial:o,assetItem:a,assetId:c}=e,l=o.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=a,(!d||d.identifier!==c)&&(d&&(this.clearAssetPlayer(d.identifier,s[n]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${Xs(a)}`),this.hls.trigger(S.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:o,schedule:s.slice(0),scheduleIndex:n,player:e})),this.bufferAssetPlayer(e,i)}bufferAssetPlayer(e,t){var s,n;if(!this.schedule)return;const{interstitial:i,assetItem:o}=e,a=this.schedule.findEventIndex(i.identifier),c=(s=this.schedule.items)==null?void 0:s[a];if(!c)return;e.loadSource(),this.setBufferingItem(c),this.bufferingAsset=o;const l=this.getBufferingPlayer();if(l===e)return;const d=i.appendInPlace;if(d&&(l==null?void 0:l.interstitial.appendInPlace)===!1)return;const u=(l==null?void 0:l.tracks)||((n=this.detachedData)==null?void 0:n.tracks)||this.requiredTracks;if(d&&o!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(u&&!hf(u,e.tracks)){const h=new Error(`Asset ${Xs(o)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(u)}')`),g={fatal:!0,type:ce.OTHER_ERROR,details:B.INTERSTITIAL_ASSET_ITEM_ERROR,error:h},m=i.findAssetIndex(o);this.handleAssetItemError(g,i,a,m,h.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,s=this.primaryMedia;if(!t||!s)return;const n=s.currentTime,i=t.findAssetIndex(e,n),o=e.assetList[i];if(o){const a=this.getAssetPlayer(o.identifier);if(a){const c=a.currentTime||n-o.timelineStart,l=a.duration-c;if(this.warn(`Stalled at ${c} of ${c+l} in ${a} ${e} (media.currentTime: ${n})`),c&&(l/s.playbackRate<.5||a.bufferedInPlaceToEnd(s))&&a.hls){const d=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,d,i)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,s,n,i){if(e.details===B.BUFFER_STALLED_ERROR)return;const o=t.assetList[n]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${o&&Xs(o)} ${e.error}`),!this.schedule)return;const a=(o==null?void 0:o.identifier)||"",c=this.getAssetPlayerQueueIndex(a),l=this.playerQueue[c]||null,d=this.schedule.items,u=De({},e,{fatal:!1,errorAction:Zs(!0),asset:o,assetListIndex:n,event:t,schedule:d,scheduleIndex:s,player:l});if(this.hls.trigger(S.INTERSTITIAL_ASSET_ERROR,u),!e.fatal)return;const h=this.playingAsset,g=this.bufferingAsset,m=new Error(i);if(o&&(this.clearAssetPlayer(a,null),o.error=m),!t.assetList.some(p=>!p.error))t.error=m;else for(let p=n;p<t.assetList.length;p++)this.resetAssetPlayer(t.assetList[p].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):h&&h.identifier===a?this.advanceAfterAssetEnded(t,s,n):g&&g.identifier===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,g)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem;let n=this.timelinePos;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${n} playing: ${Ht(s)} error: ${e.error}`),n===-1&&(n=this.hls.startPosition);const o=this.updateItem(s,n);this.itemsMatch(s,o)&&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 i=this.schedule.findItemIndexAtTime(n);this.setSchedulePosition(i)}onAssetListLoaded(e,t){var s,n;const i=t.event,o=i.identifier,a=t.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(o)))return;const c=i.timelineStart,l=i.duration;let d=0;a.forEach((p,x)=>{const v=parseFloat(p.DURATION);this.createAsset(i,x,d,c+d,v,p.URI),d+=v}),i.duration=d,this.log(`Loaded asset-list with duration: ${d} (was: ${l}) ${i}`);const u=this.waitingItem,h=(u==null?void 0:u.event.identifier)===o;this.updateSchedule();const g=(n=this.bufferingItem)==null?void 0:n.event;if(h){var m;const p=this.schedule.findEventIndex(o),x=(m=this.schedule.items)==null?void 0:m[p];if(x){if(!this.playingItem&&this.timelinePos>x.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==p){i.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${i}`),this.log(i.error.message),this.updateSchedule(!0),this.primaryFallback(i);return}this.setBufferingItem(x)}this.setSchedulePosition(p)}else if((g==null?void 0:g.identifier)===o){const p=i.assetList[0];if(p){const x=this.getAssetPlayer(p.identifier);if(g.appendInPlace){const v=this.primaryMedia;x&&v&&this.bufferAssetPlayer(x,v)}else x&&x.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case B.ASSET_LIST_PARSING_ERROR:case B.ASSET_LIST_LOAD_ERROR:case B.ASSET_LIST_LOAD_TIMEOUT:{const s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case B.BUFFER_STALLED_ERROR:{const s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const Vl=500;class lE extends ra{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",oe.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(S.LEVEL_LOADED,this.onLevelLoaded,this),e.on(S.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(S.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(S.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(S.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(S.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(S.LEVEL_LOADED,this.onLevelLoaded,this),e.off(S.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(S.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(S.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(S.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(S.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=X.IDLE,this.setInterval(Vl),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:s,success:n}=t;if(this.fragContextChanged(s)||(qe(s)&&(this.fragPrevious=s),this.state=X.IDLE),!n)return;const i=this.tracksBuffered[this.currentTrackId];if(!i)return;let o;const a=s.start;for(let l=0;l<i.length;l++)if(a>=i[l].start&&a<=i[l].end){o=i[l];break}const c=s.start+s.duration;o?o.end=c:(o={start:a,end:c},i.push(o)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:s,endOffset:n}=t;if(s===0&&n!==Number.POSITIVE_INFINITY){const i=n-1;if(i<=0)return;t.endOffsetSubtitles=Math.max(0,i),this.tracksBuffered.forEach(o=>{for(let a=0;a<o.length;){if(o[a].end<=i){o.shift();continue}else if(o[a].start<i)o[a].start=i;else break;a++}}),this.fragmentTracker.removeFragmentsInRange(s,i,oe.SUBTITLE)}}onError(e,t){const s=t.frag;(s==null?void 0:s.type)===oe.SUBTITLE&&(t.details===B.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==X.STOPPED&&(this.state=X.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&ph(this.levels,t)){this.levels=t.map(s=>new Dr(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const n=new Dr(s);return this.tracksBuffered[n.id]=[],n}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,oe.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,!((s=this.levels)!=null&&s.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(Vl)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:n,levels:i}=this,{details:o,id:a}=t;if(!i){this.warn(`Subtitle tracks were reset while loading level ${a}`);return}const c=i[a];if(a>=i.length||!c)return;this.log(`Subtitle track ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""},duration:${o.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(o.live||(s=c.details)!=null&&s.live){if(o.deltaUpdateFailed)return;const u=this.mainDetails;if(!u){this.startFragRequested=!1;return}const h=u.fragments[0];if(!c.details)o.hasProgramDateTime&&u.hasProgramDateTime?(Dn(o,u),l=o.fragmentStart):h&&(l=h.start,Qi(o,l));else{var d;l=this.alignPlaylists(o,c.details,(d=this.levelLastLoaded)==null?void 0:d.details),l===0&&h&&(l=h.start,Qi(o,l))}u&&!this.startFragRequested&&this.setStartPosition(u,l)}c.details=o,this.levelLastLoaded=c,a===n&&(this.hls.trigger(S.SUBTITLE_TRACK_UPDATED,{details:o,id:a,groupId:t.groupId}),this.tick(),o.live&&!this.fragCurrent&&this.media&&this.state===X.IDLE&&(Os(null,o.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,n=t.decryptdata,i=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&n!=null&&n.key&&n.iv&&Js(n.method)){const o=performance.now();this.decrypter.decrypt(new Uint8Array(s),n.key.buffer,n.iv.buffer,ta(n.method)).catch(a=>{throw i.trigger(S.ERROR,{type:ce.MEDIA_ERROR,details:B.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:t}),a}).then(a=>{const c=performance.now();i.trigger(S.FRAG_DECRYPTED,{frag:t,payload:a,stats:{tstart:o,tdecrypt:c}})}).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,s=t==null?void 0:t[e];if(!s||!t.length||!s.details||this.waitForLive(s))return;const{config:n}=this,i=this.getLoadPosition(),o=ve.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],i,n.maxBufferHole),{end:a,len:c}=o,l=s.details,d=this.hls.maxBufferLength+l.levelTargetDuration;if(c>d)return;const u=l.fragments,h=u.length,g=l.edge;let m=null;const p=this.fragPrevious;if(a<g){const y=n.maxFragLookUpTolerance,b=a>g-y?0:y;m=Os(p,u,Math.max(u[0].start,a),b),!m&&p&&p.start<u[0].start&&(m=u[0])}else m=u[h-1];if(m=this.filterReplacedPrimary(m,s.details),!m)return;const x=m.sn-l.startSN,v=u[x-1];if(v&&v.cc===m.cc&&this.fragmentTracker.getState(v)===rt.NOT_LOADED&&(m=v),this.fragmentTracker.getState(m)===rt.NOT_LOADED){const y=this.mapToInitFragWhenRequired(m);y&&this.loadFragment(y,s,a)}}}loadFragment(e,t,s){qe(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new cE(this.tracksBuffered[this.currentTrackId]||[])}}class cE{constructor(e){this.buffered=void 0;const t=(s,n,i)=>{if(n=n>>>0,n>i-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${i})`);return e[n][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}}const dE={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},Dh=r=>String.fromCharCode(dE[r]||r),Kt=15,ls=100,uE={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},fE={17:2,18:4,21:6,22:8,23:10,19:13,20:15},hE={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},gE={25:2,26:4,29:6,30:8,31:10,27:13,28:15},mE=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class pE{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;ke.log(`${this.time} [${e}] ${s}`)}}}const _s=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class Ph{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 s=0;s<t.length;s++){const n=t[s];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}}class xE{constructor(){this.uchar=" ",this.penState=new Ph}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class vE{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Ph,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<ls;t++)this.chars.push(new xE);this.logger=e}equals(e){for(let t=0;t<ls;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<ls;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<ls;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>ls&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=ls)}moveCursor(e){const t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].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=Dh(e);if(this.pos>=ls){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<ls;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 s=0;s<ls;s++){const n=this.chars[s].uchar;n!==" "&&(t=!1),e.push(n)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class Si{constructor(e){this.rows=[],this.currRow=Kt-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Kt;t++)this.rows.push(new vE(e));this.logger=e}reset(){for(let e=0;e<Kt;e++)this.rows[e].clear();this.currRow=Kt-1}equals(e){let t=!0;for(let s=0;s<Kt;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<Kt;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<Kt;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 = "+Ne(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<Kt;a++)this.rows[a].clear();const i=this.currRow+1-this.nrRollUpRows,o=this.lastOutputScreen;if(o){const a=o.rows[i].cueStartTime,c=this.logger.time;if(a!==null&&c!==null&&a<c)for(let l=0;l<this.nrRollUpRows;l++)this.rows[t-this.nrRollUpRows+l+1].copy(o.rows[i+l])}}this.currRow=t;const s=this.rows[this.currRow];if(e.indent!==null){const i=e.indent,o=Math.max(i-1,0);s.setCursor(e.indent),e.color=s.chars[o].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 = "+Ne(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 s="",n=-1;for(let i=0;i<Kt;i++){const o=this.rows[i].getTextString();o&&(n=i+1,e?t.push("Row "+n+": '"+o+"'"):t.push(o.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(`
64
+ `)),s}getTextAndFormat(){return this.rows}}class Hl{constructor(e,t,s){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 Si(s),this.nonDisplayedMemory=new Si(s),this.lastOutputScreen=new Si(s),this.currRollUpRow=this.displayedMemory.rows[Kt-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Kt-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 s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);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};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const s=Math.floor(e/2)-16,n=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=n[s]}this.logger.log(2,"MIDROW: "+Ne(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))}}class Kl{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=bE(),this.logger=void 0;const n=this.logger=new pE;this.channels=[null,new Hl(e,t,n),new Hl(e+1,s,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 s=0;s<t.length;s+=2){const n=t[s]&127,i=t[s+1]&127;let o=!1,a=null;if(n===0&&i===0)continue;this.logger.log(3,()=>"["+_s([t[s],t[s+1]])+"] -> ("+_s([n,i])+")");const c=this.cmdHistory;if(n>=16&&n<=31){if(yE(n,i,c)){on(null,null,c),this.logger.log(3,()=>"Repeated command ("+_s([n,i])+") is dropped");continue}on(n,i,this.cmdHistory),o=this.parseCmd(n,i),o||(o=this.parseMidrow(n,i)),o||(o=this.parsePAC(n,i)),o||(o=this.parseBackgroundAttributes(n,i))}else on(null,null,c);if(!o&&(a=this.parseChars(n,i),a)){const d=this.currentChannel;d&&d>0?this.channels[d].insertChars(a):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!o&&!a&&this.logger.log(2,()=>"Couldn't parse cleaned data "+_s([n,i])+" orig: "+_s([t[s],t[s+1]]))}}parseCmd(e,t){const s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=33&&t<=35;if(!(s||n))return!1;const i=e===20||e===21||e===23?1:2,o=this.channels[i];return e===20||e===21||e===28||e===29?t===32?o.ccRCL():t===33?o.ccBS():t===34?o.ccAOF():t===35?o.ccAON():t===36?o.ccDER():t===37?o.ccRU(2):t===38?o.ccRU(3):t===39?o.ccRU(4):t===40?o.ccFON():t===41?o.ccRDC():t===42?o.ccTR():t===43?o.ccRTD():t===44?o.ccEDM():t===45?o.ccCR():t===46?o.ccENM():t===47&&o.ccEOC():o.ccTO(t-32),this.currentChannel=i,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const n=this.channels[s];return n?(n.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+_s([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s;const n=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,i=(e===16||e===24)&&t>=64&&t<=95;if(!(n||i))return!1;const o=e<=23?1:2;t>=64&&t<=95?s=o===1?uE[e]:hE[e]:s=o===1?fE[e]:gE[e];const a=this.channels[o];return a?(a.setPAC(this.interpretPAC(s,t)),this.currentChannel=o,!0):!1}interpretPAC(e,t){let s;const n={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,n.underline=(s&1)===1,s<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(n.italics=!0,n.color="white"):n.indent=Math.floor((s-16)/2)*4,n}parseChars(e,t){let s,n=null,i=null;if(e>=25?(s=2,i=e-8):(s=1,i=e),i>=17&&i<=19){let o;i===17?o=t+80:i===18?o=t+112:o=t+144,this.logger.log(2,()=>"Special char '"+Dh(o)+"' in channel "+s),n=[o]}else e>=32&&e<=127&&(n=t===0?[e]:[e,t]);return n&&this.logger.log(3,()=>"Char codes = "+_s(n).join(",")),n}parseBackgroundAttributes(e,t){const s=(e===16||e===24)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=45&&t<=47;if(!(s||n))return!1;let i;const o={};e===16||e===24?(i=Math.floor((t-32)/2),o.background=mE[i],t%2===1&&(o.background=o.background+"_semi")):t===45?o.background="transparent":(o.foreground="black",t===47&&(o.underline=!0));const a=e<=23?1:2;return this.channels[a].setBkgData(o),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}on(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function on(r,e,t){t.a=r,t.b=e}function yE(r,e,t){return t.a===r&&t.b===e}function bE(){return{a:null,b:null}}var ma=function(){if(kn!=null&&kn.VTTCue)return self.VTTCue;const r=["","lr","rl"],e=["start","middle","end","left","right"];function t(a,c){if(typeof c!="string"||!Array.isArray(a))return!1;const l=c.toLowerCase();return~a.indexOf(l)?l:!1}function s(a){return t(r,a)}function n(a){return t(e,a)}function i(a,...c){let l=1;for(;l<arguments.length;l++){const d=arguments[l];for(const u in d)a[u]=d[u]}return a}function o(a,c,l){const d=this,u={enumerable:!0};d.hasBeenReset=!1;let h="",g=!1,m=a,p=c,x=l,v=null,y="",b=!0,T="auto",R="start",_=50,w="middle",A=50,C="middle";Object.defineProperty(d,"id",i({},u,{get:function(){return h},set:function(L){h=""+L}})),Object.defineProperty(d,"pauseOnExit",i({},u,{get:function(){return g},set:function(L){g=!!L}})),Object.defineProperty(d,"startTime",i({},u,{get:function(){return m},set:function(L){if(typeof L!="number")throw new TypeError("Start time must be set to a number.");m=L,this.hasBeenReset=!0}})),Object.defineProperty(d,"endTime",i({},u,{get:function(){return p},set:function(L){if(typeof L!="number")throw new TypeError("End time must be set to a number.");p=L,this.hasBeenReset=!0}})),Object.defineProperty(d,"text",i({},u,{get:function(){return x},set:function(L){x=""+L,this.hasBeenReset=!0}})),Object.defineProperty(d,"region",i({},u,{get:function(){return v},set:function(L){v=L,this.hasBeenReset=!0}})),Object.defineProperty(d,"vertical",i({},u,{get:function(){return y},set:function(L){const P=s(L);if(P===!1)throw new SyntaxError("An invalid or illegal string was specified.");y=P,this.hasBeenReset=!0}})),Object.defineProperty(d,"snapToLines",i({},u,{get:function(){return b},set:function(L){b=!!L,this.hasBeenReset=!0}})),Object.defineProperty(d,"line",i({},u,{get:function(){return T},set:function(L){if(typeof L!="number"&&L!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");T=L,this.hasBeenReset=!0}})),Object.defineProperty(d,"lineAlign",i({},u,{get:function(){return R},set:function(L){const P=n(L);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");R=P,this.hasBeenReset=!0}})),Object.defineProperty(d,"position",i({},u,{get:function(){return _},set:function(L){if(L<0||L>100)throw new Error("Position must be between 0 and 100.");_=L,this.hasBeenReset=!0}})),Object.defineProperty(d,"positionAlign",i({},u,{get:function(){return w},set:function(L){const P=n(L);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");w=P,this.hasBeenReset=!0}})),Object.defineProperty(d,"size",i({},u,{get:function(){return A},set:function(L){if(L<0||L>100)throw new Error("Size must be between 0 and 100.");A=L,this.hasBeenReset=!0}})),Object.defineProperty(d,"align",i({},u,{get:function(){return C},set:function(L){const P=n(L);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");C=P,this.hasBeenReset=!0}})),d.displayState=void 0}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o}();class SE{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Nh(r){function e(s,n,i,o){return(s|0)*3600+(n|0)*60+(i|0)+parseFloat(o||0)}const t=r.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class EE{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let n=0;n<s.length;++n)if(t===s[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 s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function Mh(r,e,t,s){const n=s?r.split(s):[r];for(const i in n){if(typeof n[i]!="string")continue;const o=n[i].split(t);if(o.length!==2)continue;const a=o[0],c=o[1];e(a,c)}}const io=new ma(0,0,""),an=io.align==="middle"?"middle":"center";function TE(r,e,t){const s=r;function n(){const a=Nh(r);if(a===null)throw new Error("Malformed timestamp: "+s);return r=r.replace(/^[^\sa-zA-Z-]+/,""),a}function i(a,c){const l=new EE;Mh(a,function(h,g){let m;switch(h){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===g){l.set(h,t[p].region);break}break;case"vertical":l.alt(h,g,["rl","lr"]);break;case"line":m=g.split(","),l.integer(h,m[0]),l.percent(h,m[0])&&l.set("snapToLines",!1),l.alt(h,m[0],["auto"]),m.length===2&&l.alt("lineAlign",m[1],["start",an,"end"]);break;case"position":m=g.split(","),l.percent(h,m[0]),m.length===2&&l.alt("positionAlign",m[1],["start",an,"end","line-left","line-right","auto"]);break;case"size":l.percent(h,g);break;case"align":l.alt(h,g,["start",an,"end","left","right"]);break}},/:/,/\s/),c.region=l.get("region",null),c.vertical=l.get("vertical","");let d=l.get("line","auto");d==="auto"&&io.line===-1&&(d=-1),c.line=d,c.lineAlign=l.get("lineAlign","start"),c.snapToLines=l.get("snapToLines",!0),c.size=l.get("size",100),c.align=l.get("align",an);let u=l.get("position","auto");u==="auto"&&io.position===50&&(u=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=u}function o(){r=r.replace(/^\s+/,"")}if(o(),e.startTime=n(),o(),r.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);r=r.slice(3),o(),e.endTime=n(),o(),i(r,e)}function Fh(r){return r.replace(/<br(?: \/)?>/gi,`
65
+ `)}class wE{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new SE,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 s(){let i=t.buffer,o=0;for(i=Fh(i);o<i.length&&i[o]!=="\r"&&i[o]!==`
66
+ `;)++o;const a=i.slice(0,o);return i[o]==="\r"&&++o,i[o]===`
67
+ `&&++o,t.buffer=i.slice(o),a}function n(i){Mh(i,function(o,a){},/:/)}try{let i="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;i=s();const a=i.match(/^()?WEBVTT([ \t].*)?$/);if(!(a!=null&&a[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let o=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(o?o=!1:i=s(),t.state){case"HEADER":/:/.test(i)?n(i):i||(t.state="ID");continue;case"NOTE":i||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(i)){t.state="NOTE";break}if(!i)continue;if(t.cue=new ma(0,0,""),t.state="CUE",i.indexOf("-->")===-1){t.cue.id=i;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{TE(i,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const a=i.indexOf("-->")!==-1;if(!i||a&&(o=!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+=`
68
+ `),t.cue.text+=i}continue;case"BADCUE":i||(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+=`
69
+
70
+ `,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}}const RE=/\r\n|\n\r|\n|\r/g,Ei=function(e,t,s=0){return e.slice(s,s+t.length)===t},AE=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),n=parseInt(e.slice(-9,-7)),i=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!ne(t)||!ne(s)||!ne(n)||!ne(i))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=60*1e3*n,t+=60*60*1e3*i,t};function pa(r,e,t){return Tr(r.toString())+Tr(e.toString())+Tr(t)}const IE=function(e,t,s){let n=e[t],i=e[n.prevCC];if(!i||!i.new&&n.new){e.ccOffset=e.presentationOffset=n.start,n.new=!1;return}for(;(o=i)!=null&&o.new;){var o;e.ccOffset+=n.start-i.start,n.new=!1,n=i,i=e[n.prevCC]}e.presentationOffset=s};function LE(r,e,t,s,n,i,o){const a=new wE,c=Pt(new Uint8Array(r)).trim().replace(RE,`
71
+ `).split(`
72
+ `),l=[],d=e?Nb(e.baseTime,e.timescale):0;let u="00:00.000",h=0,g=0,m,p=!0;a.oncue=function(x){const v=t[s];let y=t.ccOffset;const b=(h-d)/9e4;if(v!=null&&v.new&&(g!==void 0?y=t.ccOffset=v.start:IE(t,s,b)),b){if(!e){m=new Error("Missing initPTS for VTT MPEGTS");return}y=b-t.presentationOffset}const T=x.endTime-x.startTime,R=_t((x.startTime+y-g)*9e4,n*9e4)/9e4;x.startTime=Math.max(R,0),x.endTime=Math.max(R+T,0);const _=x.text.trim();x.text=decodeURIComponent(encodeURIComponent(_)),x.id||(x.id=pa(x.startTime,x.endTime,_)),x.endTime>0&&l.push(x)},a.onparsingerror=function(x){m=x},a.onflush=function(){if(m){o(m);return}i(l)},c.forEach(x=>{if(p)if(Ei(x,"X-TIMESTAMP-MAP=")){p=!1,x.slice(16).split(",").forEach(v=>{Ei(v,"LOCAL:")?u=v.slice(6):Ei(v,"MPEGTS:")&&(h=parseInt(v.slice(7)))});try{g=AE(u)/1e3}catch(v){m=v}return}else x===""&&(p=!1);a.parse(x+`
73
+ `)}),a.flush()}const Ti="stpp.ttml.im1t",Oh=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,jh=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,CE={left:"start",center:"center",right:"end",start:"start",end:"end"};function zl(r,e,t,s){const n=Ee(new Uint8Array(r),["mdat"]);if(n.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const i=n.map(a=>Pt(a)),o=Pb(e.baseTime,1,e.timescale);try{i.forEach(a=>t(_E(a,o)))}catch(a){s(a)}}function _E(r,e){const n=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("tt")[0];if(!n)throw new Error("Invalid ttml");const i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},o=Object.keys(i).reduce((u,h)=>(u[h]=n.getAttribute(`ttp:${h}`)||i[h],u),{}),a=n.getAttribute("xml:space")!=="preserve",c=Wl(wi(n,"styling","style")),l=Wl(wi(n,"layout","region")),d=wi(n,"body","[begin]");return[].map.call(d,u=>{const h=Bh(u,a);if(!h||!u.hasAttribute("begin"))return null;const g=Ai(u.getAttribute("begin"),o),m=Ai(u.getAttribute("dur"),o);let p=Ai(u.getAttribute("end"),o);if(g===null)throw Yl(u);if(p===null){if(m===null)throw Yl(u);p=g+m}const x=new ma(g-e,p-e,h);x.id=pa(x.startTime,x.endTime,x.text);const v=l[u.getAttribute("region")],y=c[u.getAttribute("style")],b=kE(v,y,c),{textAlign:T}=b;if(T){const R=CE[T];R&&(x.lineAlign=R),x.align=T}return De(x,b),x}).filter(u=>u!==null)}function wi(r,e,t){const s=r.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function Wl(r){return r.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function Bh(r,e){return[].slice.call(r.childNodes).reduce((t,s,n)=>{var i;return s.nodeName==="br"&&n?t+`
74
+ `:(i=s.childNodes)!=null&&i.length?Bh(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function kE(r,e,t){const s="http://www.w3.org/ns/ttml#styling";let n=null;const i=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],o=r!=null&&r.hasAttribute("style")?r.getAttribute("style"):null;return o&&t.hasOwnProperty(o)&&(n=t[o]),i.reduce((a,c)=>{const l=Ri(e,s,c)||Ri(r,s,c)||Ri(n,s,c);return l&&(a[c]=l),a},{})}function Ri(r,e,t){return r&&r.hasAttributeNS(e,t)?r.getAttributeNS(e,t):null}function Yl(r){return new Error(`Could not parse ttml timestamp ${r}`)}function Ai(r,e){if(!r)return null;let t=Nh(r);return t===null&&(Oh.test(r)?t=DE(r,e):jh.test(r)&&(t=PE(r,e))),t}function DE(r,e){const t=Oh.exec(r),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function PE(r,e){const t=jh.exec(r),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s*1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}class ln{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,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class NE{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=Xl(),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(S.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(S.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(S.FRAG_LOADING,this.onFragLoading,this),e.on(S.FRAG_LOADED,this.onFragLoaded,this),e.on(S.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(S.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(S.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(S.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(S.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(S.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(S.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(S.FRAG_LOADING,this.onFragLoading,this),e.off(S.FRAG_LOADED,this.onFragLoaded,this),e.off(S.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(S.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(S.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(S.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(S.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new ln(this,"textTrack1"),t=new ln(this,"textTrack2"),s=new ln(this,"textTrack3"),n=new ln(this,"textTrack4");this.cea608Parser1=new Kl(1,e,t),this.cea608Parser2=new Kl(3,s,n)}addCues(e,t,s,n,i){let o=!1;for(let a=i.length;a--;){const c=i[a],l=ME(c[0],c[1],t,s);if(l>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],s),o=!0,l/(s-t)>.5))return}if(o||i.push([t,s]),this.config.renderTextTracksNatively){const a=this.captionsTracks[e];this.Cues.newCue(a,t,s,n)}else{const a=this.Cues.newCue(null,t,s,n);this.hls.trigger(S.CUES_PARSED,{type:"captions",cues:a,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:n,timescale:i,trackId:o}){const{unparsedVttFrags:a}=this;s===oe.MAIN&&(this.initPTS[t.cc]={baseTime:n,timescale:i,trackId:o}),a.length&&(this.unparsedVttFrags=[],a.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded(S.FRAG_LOADED,c):this.hls.trigger(S.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:c.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:s}=this;if(s)for(let n=0;n<s.textTracks.length;n++){const i=s.textTracks[n];if(ql(i,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return i}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:n}=this,{label:i,languageCode:o}=t[e],a=this.getExistingTrack(i,o);if(a)s[e]=a,Qs(s[e]),Ch(s[e],n);else{const c=this.createTextTrack("captions",i,o);c&&(c[e]=!0,s[e]=c)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s=t.label,n={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=n,this.hls.trigger(S.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[n]})}createTextTrack(e,t,s){const n=this.media;if(n)return n.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const s=!!t.transferMedia;if(this.media=null,s)return;const{captionsTracks:n}=this;Object.keys(n).forEach(i=>{Qs(n[i]),delete n[i]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Xl(),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 s=0;s<t.length;s++)Qs(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],n=s.some(i=>i.textCodec===Ti);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(ph(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const o=this.media,a=o?vn(o.textTracks):null;if(this.tracks.forEach((c,l)=>{let d;if(a){let u=null;for(let h=0;h<a.length;h++)if(a[h]&&ql(a[h],c)){u=a[h],a[h]=null;break}u&&(d=u)}if(d)Qs(d);else{const u=$h(c);d=this.createTextTrack(u,c.name,c.lang),d&&(d.mode="disabled")}d&&this.textTracks.push(d)}),a!=null&&a.length){const c=a.filter(l=>l!==null).map(l=>l.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const o=this.tracks.map(a=>({label:a.name,kind:a.type.toLowerCase(),default:a.default,subtitleTrack:a}));this.hls.trigger(S.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:o})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{const n=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!n)return;const i=`textTrack${n[1]}`,o=this.captionsProperties[i];o&&(o.label=s.name,s.lang&&(o.languageCode=s.lang),o.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===oe.MAIN){var s,n;const{cea608Parser1:i,cea608Parser2:o,lastSn:a}=this,{cc:c,sn:l}=t.frag,d=(s=(n=t.part)==null?void 0:n.index)!=null?s:-1;i&&o&&(l!==a+1||l===a&&d!==this.lastPartIndex+1||c!==this.lastCc)&&(i.reset(),o.reset()),this.lastCc=c,this.lastSn=l,this.lastPartIndex=d}}onFragLoaded(e,t){const{frag:s,payload:n}=t;if(s.type===oe.SUBTITLE)if(n.byteLength){const i=s.decryptdata,o="stats"in t;if(i==null||!i.encrypted||o){const a=this.tracks[s.level],c=this.vttCCs;c[s.cc]||(c[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),a&&a.textCodec===Ti?this._parseIMSC1(s,n):this._parseVTTs(t)}}else this.hls.trigger(S.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;zl(t,this.initPTS[e.cc],n=>{this._appendCues(n,e.level),s.trigger(S.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},n=>{s.logger.log(`Failed to parse IMSC1: ${n}`),s.trigger(S.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:n})})}_parseVTTs(e){var t;const{frag:s,payload:n}=e,{initPTS:i,unparsedVttFrags:o}=this,a=i.length-1;if(!i[s.cc]&&a===-1){o.push(e);return}const c=this.hls,l=(t=s.initSegment)!=null&&t.data?$t(s.initSegment.data,new Uint8Array(n)).buffer:n;LE(l,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,d=>{this._appendCues(d,s.level),c.trigger(S.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},d=>{const u=d.message==="Missing initPTS for VTT MPEGTS";u?o.push(e):this._fallbackToIMSC1(s,n),c.logger.log(`Failed to parse VTT cue: ${d}`),!(u&&a>s.cc)&&c.trigger(S.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:d})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||zl(t,this.initPTS[e.cc],()=>{s.textCodec=Ti,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const n=this.textTracks[t];if(!n||n.mode==="disabled")return;e.forEach(i=>_h(n,i))}else{const n=this.tracks[t];if(!n)return;const i=n.default?"default":"subtitles"+t;s.trigger(S.CUES_PARSED,{type:"subtitles",cues:e,track:i})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===oe.SUBTITLE&&this.onFragLoaded(S.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:n}=t;if(!(s.type===oe.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let i=0;i<n.length;i++){const o=n[i].bytes;if(o){this.cea608Parser1||this.initCea608Parsers();const a=this.extractCea608Data(o);this.cea608Parser1.addData(n[i].pts,a[0]),this.cea608Parser2.addData(n[i].pts,a[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:n,type:i}){const{media:o}=this;if(!(!o||o.currentTime<s)){if(!i||i==="video"){const{captionsTracks:a}=this;Object.keys(a).forEach(c=>no(a[c],t,s))}if(this.config.renderTextTracksNatively&&t===0&&n!==void 0){const{textTracks:a}=this;Object.keys(a).forEach(c=>no(a[c],t,n))}}}extractCea608Data(e){const t=[[],[]],s=e[0]&31;let n=2;for(let i=0;i<s;i++){const o=e[n++],a=127&e[n++],c=127&e[n++];if(a===0&&c===0)continue;if((4&o)!==0){const d=3&o;(d===0||d===1)&&(t[d].push(a),t[d].push(c))}}return t}}function $h(r){return r.characteristics&&/transcribes-spoken-dialog/gi.test(r.characteristics)&&/describes-music-and-sound/gi.test(r.characteristics)?"captions":"subtitles"}function ql(r,e){return!!r&&r.kind===$h(e)&&eo(e,r)}function ME(r,e,t,s){return Math.min(e,s)-Math.max(r,t)}function Xl(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const FE=/\s/,OE={newCue(r,e,t,s){const n=[];let i,o,a,c,l;const d=self.VTTCue||self.TextTrackCue;for(let h=0;h<s.rows.length;h++)if(i=s.rows[h],a=!0,c=0,l="",!i.isEmpty()){var u;for(let p=0;p<i.chars.length;p++)FE.test(i.chars[p].uchar)&&a?c++:(l+=i.chars[p].uchar,a=!1);i.cueStartTime=e,e===t&&(t+=1e-4),c>=16?c--:c++;const g=Fh(l.trim()),m=pa(e,t,g);r!=null&&(u=r.cues)!=null&&u.getCueById(m)||(o=new d(e,t,g),o.id=m,o.line=h+1,o.align="left",o.position=10+Math.min(80,Math.floor(c*8/32)*10),n.push(o))}return r&&n.length&&(n.sort((h,g)=>h.line==="auto"||g.line==="auto"?0:h.line>8&&g.line>8?g.line-h.line:h.line-g.line),n.forEach(h=>_h(r,h))),n}};function jE(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const BE=/(\d+)-(\d+)\/(\d+)/;class Ql{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||VE,this.controller=new self.AbortController,this.stats=new Yo}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,s){const n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();const i=$E(e,this.controller.signal),o=e.responseType==="arraybuffer",a=o?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,i),self.clearTimeout(this.requestTimeout),t.timeout=c&&ne(c)?c:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},t.timeout),(Mr(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(u=>{var h;this.response=this.loader=u;const g=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},l-(g-n.loading.start)),!u.ok){const{status:p,statusText:x}=u;throw new HE(x||"fetch, bad network response",p,u)}n.loading.first=g,n.total=GE(u.headers)||n.total;const m=(h=this.callbacks)==null?void 0:h.onProgress;return m&&ne(t.highWaterMark)?this.loadProgressively(u,n,e,t.highWaterMark,m):o?u.arrayBuffer():e.responseType==="json"?u.json():u.text()}).then(u=>{var h,g;const m=this.response;if(!m)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const p=u[a];p&&(n.loaded=n.total=p);const x={url:m.url,data:u,code:m.status},v=(h=this.callbacks)==null?void 0:h.onProgress;v&&!ne(t.highWaterMark)&&v(n,e,u,m),(g=this.callbacks)==null||g.onSuccess(x,n,e,m)}).catch(u=>{var h;if(self.clearTimeout(this.requestTimeout),n.aborted)return;const g=u&&u.code||0,m=u?u.message:null;(h=this.callbacks)==null||h.onError({code:g,text:m},e,u?u.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,s,n=0,i){const o=new Xf,a=e.body.getReader(),c=()=>a.read().then(l=>{if(l.done)return o.dataLength&&i(t,s,o.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const d=l.value,u=d.length;return t.loaded+=u,u<n||o.dataLength?(o.push(d),o.dataLength>=n&&i(t,s,o.flush().buffer,e)):i(t,s,d.buffer,e),c()}).catch(()=>Promise.reject());return c()}}function $E(r,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(De({},r.headers))};return r.rangeEnd&&t.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),t}function UE(r){const e=BE.exec(r);if(e)return parseInt(e[2])-parseInt(e[1])+1}function GE(r){const e=r.get("Content-Range");if(e){const s=UE(e);if(ne(s))return s}const t=r.get("Content-Length");if(t)return parseInt(t)}function VE(r,e){return new self.Request(r.url,e)}class HE extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const KE=/^age:\s*[\d.]+\s*$/im;class Uh{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 Yo,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,s){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=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;const i=this.xhrSetup;i?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return i(s,t.url)}).catch(o=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),i(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(o=>{var a;(a=this.callbacks)==null||a.onError({code:s.status,text:o.message},t,s,n)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const n=t.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:o}=s.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),s.timeout=i&&ne(i)?i:o,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const n=t.readyState,i=this.config;if(!s.aborted&&n>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),n===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const l=t.status,d=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){const m=d??t.response;if(m!=null){var o,a;s.loading.end=Math.max(self.performance.now(),s.loading.first);const p=t.responseType==="arraybuffer"?m.byteLength:m.length;s.loaded=s.total=p,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);const x=(o=this.callbacks)==null?void 0:o.onProgress;x&&x(s,e,m,t);const v={url:t.responseURL,data:m,code:l};(a=this.callbacks)==null||a.onSuccess(v,s,e,t);return}}const u=i.loadPolicy.errorRetry,h=s.retry,g={url:e.url,data:void 0,code:l};if(Cn(u,h,!1,g))this.retry(u);else{var c;ke.error(`${l} while loading ${e.url}`),(c=this.callbacks)==null||c.onError({code:l,text:t.statusText},e,t,s)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Cn(e,t,!0))this.retry(e);else{var s;ke.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);const n=this.callbacks;n&&(this.abortInternal(),n.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=Zo(e,s.retry),s.retry++,ke.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${s.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&&KE.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const zE={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},WE=_e(_e({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:Uh,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:iy,bufferController:qb,capLevelController:fa,errorController:dy,fpsController:XS,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:Bf,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:zE},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},YE()),{},{subtitleStreamController:lE,subtitleTrackController:JS,timelineController:NE,audioStreamController:Kb,audioTrackController:zb,emeController:er,cmcdController:zS,contentSteeringController:YS,interstitialsController:aE});function YE(){return{cueHandler:OE,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 qE(r,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=oo(r),n=["manifest","level","frag"],i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return n.forEach(o=>{const a=`${o==="level"?"playlist":o}LoadPolicy`,c=e[a]===void 0,l=[];i.forEach(d=>{const u=`${o}Loading${d}`,h=e[u];if(h!==void 0&&c){l.push(u);const g=s[a].default;switch(e[a]={default:g},d){case"TimeOut":g.maxLoadTimeMs=h,g.maxTimeToFirstByteMs=h;break;case"MaxRetry":g.errorRetry.maxNumRetry=h,g.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":g.errorRetry.retryDelayMs=h,g.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":g.errorRetry.maxRetryDelayMs=h,g.timeoutRetry.maxRetryDelayMs=h;break}}}),l.length&&t.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${Ne(e[a])}`)}),_e(_e({},s),e)}function oo(r){return r&&typeof r=="object"?Array.isArray(r)?r.map(oo):Object.keys(r).reduce((e,t)=>(e[t]=oo(r[t]),e),{}):r}function XE(r,e){const t=r.loader;t!==Ql&&t!==Uh?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),r.progressive=!1):jE()&&(r.loader=Ql,r.progressive=!0,r.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const yn=2,QE=.1,ZE=.05,JE=100;class eT extends Nf{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 s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(S.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(S.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(S.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(JE),this.mediaSource=t.mediaSource;const s=this.media=t.media;ht(s,"playing",this.onMediaPlaying),ht(s,"waiting",this.onMediaWaiting),ht(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(yt(s,"playing",this.onMediaPlaying),yt(s,"waiting",this.onMediaWaiting),yt(s,"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 s,n;const i=(s=this.hls)==null?void 0:s.config;if(!i)return;const o=this.media;if(!o)return;const{seeking:a}=o,c=this.seeking&&!a,l=!this.seeking&&a,d=o.paused&&!a||o.ended||o.playbackRate===0;if(this.seeking=a,e!==t){t&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,i.nudgeOnVideoHole&&!d&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(l||c){c&&this.stallResolved(e);return}if(d){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&o.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(S.MEDIA_ENDED,{stalled:!1}));return}if(!ve.getBuffered(o).length){this.nudgeRetry=0;return}const u=ve.bufferInfo(o,e,0),h=u.nextStart||0,g=this.fragmentTracker;if(a&&g&&this.hls){const _=Zl(this.hls.inFlightFragments,e),w=u.len>yn,A=!h||_||h-e>yn&&!g.getPartialFragment(e);if(w||A)return;this.moved=!1}const m=(n=this.hls)==null?void 0:n.latestLevelDetails;if(!this.moved&&this.stalled!==null&&g){if(!(u.len>0)&&!h)return;const w=Math.max(h,u.start||0)-e,C=!!(m!=null&&m.live)?m.targetduration*2:yn,L=cn(e,g);if(w>0&&(w<=C||L)){o.paused||this._trySkipBufferHole(L);return}}const p=i.detectStallWithCurrentTimeMs,x=self.performance.now(),v=this.waiting;let y=this.stalled;if(y===null)if(v>0&&x-v<p)y=this.stalled=v;else{this.stalled=x;return}const b=x-y;if(!a&&(b>=p||v)&&this.hls){var T;if(((T=this.mediaSource)==null?void 0:T.readyState)==="ended"&&!(m!=null&&m.live)&&Math.abs(e-((m==null?void 0:m.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(S.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(u),!this.media||!this.hls)return}const R=ve.bufferInfo(o,e,i.maxBufferHole);this._tryFixBufferStall(R,b,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(S.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const n=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&n&&n.length>1&&e>n.end(0)){const i=ve.bufferedInfo(ve.timeRangesToArray(this.buffered.audio),e,0);if(i.len>1&&t>=i.start){const o=ve.timeRangesToArray(n),a=ve.bufferedInfo(o,t,0).bufferedIndex;if(a>-1&&a<o.length-1){const c=ve.bufferedInfo(o,e,0).bufferedIndex,l=o[a].end,d=o[a+1].start;if((c===-1||c>a)&&d-l<1&&e-l<2){const u=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${d} buffered index: ${c}`);this.warn(u.message),this.media.currentTime+=1e-6;let h=cn(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);const g=ve.bufferInfo(this.media,e,0);this.hls.trigger(S.ERROR,{type:ce.MEDIA_ERROR,details:B.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:h,buffer:g.len,bufferInfo:g})}}}}}_tryFixBufferStall(e,t,s){var n,i;const{fragmentTracker:o,media:a}=this,c=(n=this.hls)==null?void 0:n.config;if(!a||!o||!c)return;const l=(i=this.hls)==null?void 0:i.latestLevelDetails,d=cn(s,o);if((d||l!=null&&l.live&&s<l.fragmentStart)&&(this._trySkipBufferHole(d)||!this.media))return;const u=e.buffered,h=this.adjacentTraversal(e,s);(u&&u.length>1&&e.len>c.maxBufferHole||e.nextStart&&(e.nextStart-s<c.maxBufferHole||h))&&(t>c.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,n=e.nextStart;if(s&&n){const i=s.getFragAtPos(t,oe.MAIN),o=s.getFragAtPos(n,oe.MAIN);if(i&&o)return o.sn-i.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:n,stalled:i}=this;if(!n&&i!==null&&s&&t){this.stallReported=!0;const o=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${Ne(e)})`);this.warn(o.message),t.trigger(S.ERROR,{type:ce.MEDIA_ERROR,details:B.BUFFER_STALLED_ERROR,fatal:!1,error:o,buffer:e.len,bufferInfo:e,stalled:{start:i}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:s,media:n}=this,i=(t=this.hls)==null?void 0:t.config;if(!n||!s||!i)return 0;const o=n.currentTime,a=ve.bufferInfo(n,o,0),c=o<a.start?a.start:a.nextStart;if(c&&this.hls){const d=a.len<=i.maxBufferHole,u=a.len>0&&a.len<1&&n.readyState<3,h=c-o;if(h>0&&(d||u)){if(h>i.maxBufferHole){let m=!1;if(o===0){const p=s.getAppendedFrag(0,oe.MAIN);p&&c<p.end&&(m=!0)}if(!m&&e){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||Zl(this.hls.inFlightFragments,c))return 0;let x=!1,v=e.end;for(;v<c;){const y=cn(v,s);if(y)v+=y.duration;else{x=!0;break}}if(x)return 0}}const g=Math.max(c+ZE,o+QE);if(this.warn(`skipping hole, adjusting currentTime from ${o} to ${g}`),this.moved=!0,n.currentTime=g,!(e!=null&&e.gap)){const m=new Error(`fragment loaded with buffer holes, seeking from ${o} to ${g}`),p={type:ce.MEDIA_ERROR,details:B.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:m,reason:m.message,buffer:a.len,bufferInfo:a};e&&("fragment"in e?p.part=e:p.frag=e),this.hls.trigger(S.ERROR,p)}return g}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:n}=this,i=t==null?void 0:t.config;if(!s||!i)return 0;const o=s.currentTime;if(this.nudgeRetry++,n<i.nudgeMaxRetry){const a=o+(n+1)*i.nudgeOffset,c=new Error(`Nudging 'currentTime' from ${o} to ${a}`);this.warn(c.message),s.currentTime=a,t.trigger(S.ERROR,{type:ce.MEDIA_ERROR,details:B.BUFFER_NUDGE_ON_STALL,error:c,fatal:!1,buffer:e.len,bufferInfo:e})}else{const a=new Error(`Playhead still not moving while enough data buffered @${o} after ${i.nudgeMaxRetry} nudges`);this.error(a.message),t.trigger(S.ERROR,{type:ce.MEDIA_ERROR,details:B.BUFFER_STALLED_ERROR,error:a,fatal:!0,buffer:e.len,bufferInfo:e})}}}function Zl(r,e){const t=Jl(r.main);if(t&&t.start<=e)return t;const s=Jl(r.audio);return s&&s.start<=e?s:null}function Jl(r){if(!r)return null;switch(r.state){case X.IDLE:case X.STOPPED:case X.ENDED:case X.ERROR:return null}return r.frag}function cn(r,e){return e.getAppendedFrag(r,oe.MAIN)||e.getPartialFragment(r)}const tT=.25;function ao(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Ii(r,e,t,s,n){let i=new r(e,t,"");try{i.value=s,n&&(i.type=n)}catch{i=new r(e,t,Ne(n?_e({type:n},s):s))}return i}const dn=(()=>{const r=ao();try{r&&new r(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class sT{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(S.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(S.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(S.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(S.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(S.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(S.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(S.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(S.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(S.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var s;this.media=t.media,((s=t.overrides)==null?void 0:s.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&&Qs(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 s=e[t];if(s.kind==="metadata"&&s.label==="id3")return Ch(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:n}=this.hls.config;if(!s&&!n)return;const{samples:i}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=ao();if(o)for(let a=0;a<i.length;a++){const c=i[a].type;if(c===kt.emsg&&!s||!n)continue;const l=rh(i[a].data),d=i[a].pts;let u=d+i[a].duration;u>dn&&(u=dn),u-d<=0&&(u=d+tT);for(let g=0;g<l.length;g++){const m=l[g];if(!nh(m)){this.updateId3CueEnds(d,c);const p=Ii(o,d,u,m,c);p&&this.id3Track.addCue(p)}}}}updateId3CueEnds(e,t){var s;const n=(s=this.id3Track)==null?void 0:s.cues;if(n)for(let i=n.length;i--;){const o=n[i];o.type===t&&o.startTime<e&&o.endTime===dn&&(o.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:n}){const{id3Track:i,hls:o}=this;if(!o)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:c}}=o;if(i&&(a||c)){let l;n==="audio"?l=d=>d.type===kt.audioId3&&c:n==="video"?l=d=>d.type===kt.emsg&&a:l=d=>d.type===kt.audioId3&&c||d.type===kt.emsg&&a,no(i,t,s,l)}}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:s,timelineOffset:n,enableDateRangeMetadataCues:i,interstitialsController:o}=this.hls.config;if(!i)return;const a=ao();if(s&&n&&!o){const{fragmentStart:p,fragmentEnd:x}=e;let v=this.assetCue;v?(v.startTime=p,v.endTime=x):a&&(v=this.assetCue=Ii(a,p,x,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(v),v.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:l}=e,d=Object.keys(l);let u=this.dateRangeCuesAppended;if(c&&t){var h;if((h=c.cues)!=null&&h.length){const p=Object.keys(u).filter(x=>!d.includes(x));for(let x=p.length;x--;){var g;const v=p[x],y=(g=u[v])==null?void 0:g.cues;delete u[v],y&&Object.keys(y).forEach(b=>{const T=y[b];if(T){T.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(T)}catch{}}})}}else u=this.dateRangeCuesAppended={}}const m=e.fragments[e.fragments.length-1];if(!(d.length===0||!ne(m==null?void 0:m.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<d.length;p++){const x=d[p],v=l[x],y=v.startTime,b=u[x],T=(b==null?void 0:b.cues)||{};let R=(b==null?void 0:b.durationKnown)||!1,_=dn;const{duration:w,endDate:A}=v;if(A&&w!==null)_=y+w,R=!0;else if(v.endOnNext&&!R){const L=d.reduce((P,M)=>{if(M!==v.id){const j=l[M];if(j.class===v.class&&j.startDate>v.startDate&&(!P||v.startDate<P.startDate))return j}return P},null);L&&(_=L.startTime,R=!0)}const C=Object.keys(v.attr);for(let L=0;L<C.length;L++){const P=C[L];if(!Ty(P))continue;const M=T[P];if(M)R&&!(b!=null&&b.durationKnown)?M.endTime=_:Math.abs(M.startTime-y)>.01&&(M.startTime=y,M.endTime=_);else if(a){let j=v.attr[P];wy(P)&&(j=gf(j));const $=Ii(a,y,_,{key:P,data:j},kt.dateRange);$&&($.id=x,this.id3Track.addCue($),T[P]=$,o&&(P==="X-ASSET-LIST"||P==="X-ASSET-URL")&&$.addEventListener("enter",this.onEventCueEnter))}}u[x]={cues:T,dateRange:v,durationKnown:R}}}}}class rT{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,s=this.levelDetails;if(!t||!s)return;this.currentTime=t.currentTime;const n=this.computeLatency();if(n===null)return;this._latency=n;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:o}=this.config;if(!i||o===1||!s.live)return;const a=this.targetLatency;if(a===null)return;const c=n-a,l=Math.min(this.maxLatency,a+s.targetduration);if(c<l&&c>.05&&this.forwardBufferLength>1){const u=Math.min(2,Math.max(1,o)),h=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,g=Math.min(u,Math.max(1,h));this.changeMediaPlaybackRate(t,g)}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:s,targetduration:n}=e,{liveSyncDuration:i,liveSyncDurationCount:o,lowLatencyMode:a}=this.config,c=this.hls.userConfig;let l=a&&s||t;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||l===0)&&(l=i!==void 0?i:o*n);const d=n;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,d)}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 s=this.levelDetails;if(s===null)return null;const n=s.edge,i=e-t-this.edgeStalled,o=n-s.totalduration,a=n-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(o,i),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 s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(S.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(S.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 s;t.details===B.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,n;e.playbackRate!==t&&((s=this.hls)==null||s.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}}class nT extends ua{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(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(S.LEVEL_LOADED,this.onLevelLoaded,this),e.on(S.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(S.FRAG_BUFFERED,this.onFragBuffered,this),e.on(S.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(S.LEVEL_LOADED,this.onLevelLoaded,this),e.off(S.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(S.FRAG_BUFFERED,this.onFragBuffered,this),e.off(S.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.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 s=this.hls.config.preferManagedMediaSource,n=[],i={},o={};let a=!1,c=!1,l=!1;t.levels.forEach(d=>{const u=d.attrs;let{audioCodec:h,videoCodec:g}=d;h&&(d.audioCodec=h=Rn(h,s)||void 0),g&&(g=d.videoCodec=$v(g));const{width:m,height:p,unknownCodecs:x}=d,v=(x==null?void 0:x.length)||0;if(a||(a=!!(m&&p)),c||(c=!!g),l||(l=!!h),v||h&&!this.isAudioSupported(h)||g&&!this.isVideoSupported(g)){this.log(`Some or all CODECS not supported "${u.CODECS}"`);return}const{CODECS:y,"FRAME-RATE":b,"HDCP-LEVEL":T,"PATHWAY-ID":R,RESOLUTION:_,"VIDEO-RANGE":w}=u,C=`${`${R||"."}-`}${d.bitrate}-${_}-${b}-${y}-${w}-${T}`;if(i[C])if(i[C].uri!==d.url&&!d.attrs["PATHWAY-ID"]){const L=o[C]+=1;d.attrs["PATHWAY-ID"]=new Array(L+1).join(".");const P=this.createLevel(d);i[C]=P,n.push(P)}else i[C].addGroupId("audio",u.AUDIO),i[C].addGroupId("text",u.SUBTITLES);else{const L=this.createLevel(d);i[C]=L,o[C]=1,n.push(L)}}),this.filterAndSortMediaOptions(n,t,a,c,l)}createLevel(e){const t=new Dr(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const n=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(n.message),t.supportedResult=Af(n,[])}return t}isAudioSupported(e){return _r(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return _r(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,n,i){var o;let a=[],c=[],l=e;const d=((o=t.stats)==null?void 0:o.parsing)||{};if((s||n)&&i&&(l=l.filter(({videoCodec:y,videoRange:b,width:T,height:R})=>(!!y||!!(T&&R))&&Xv(b))),l.length===0){Promise.resolve().then(()=>{if(this.hls){let y="no level with compatible codecs found in manifest",b=y;t.levels.length&&(b=`one or more CODECS in variant not supported: ${Ne(t.levels.map(R=>R.attrs.CODECS).filter((R,_,w)=>w.indexOf(R)===_))}`,this.warn(b),y+=` (${b})`);const T=new Error(y);this.hls.trigger(S.ERROR,{type:ce.MEDIA_ERROR,details:B.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:T,reason:b})}}),d.end=performance.now();return}t.audioTracks&&(a=t.audioTracks.filter(y=>!y.audioCodec||this.isAudioSupported(y.audioCodec)),ec(a)),t.subtitles&&(c=t.subtitles,ec(c));const u=l.slice(0);l.sort((y,b)=>{if(y.attrs["HDCP-LEVEL"]!==b.attrs["HDCP-LEVEL"])return(y.attrs["HDCP-LEVEL"]||"")>(b.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&y.height!==b.height)return y.height-b.height;if(y.frameRate!==b.frameRate)return y.frameRate-b.frameRate;if(y.videoRange!==b.videoRange)return An.indexOf(y.videoRange)-An.indexOf(b.videoRange);if(y.videoCodec!==b.videoCodec){const T=Ka(y.videoCodec),R=Ka(b.videoCodec);if(T!==R)return R-T}if(y.uri===b.uri&&y.codecSet!==b.codecSet){const T=wn(y.codecSet),R=wn(b.codecSet);if(T!==R)return R-T}return y.averageBitrate!==b.averageBitrate?y.averageBitrate-b.averageBitrate:0});let h=u[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==u.length)){for(let y=0;y<u.length;y++)if(u[y].pathwayId===l[0].pathwayId){h=u[y];break}}this._levels=l;for(let y=0;y<l.length;y++)if(l[y]===h){var g;this._firstLevel=y;const b=h.bitrate,T=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${b}`),((g=this.hls.userConfig)==null?void 0:g.abrEwmaDefaultEstimate)===void 0){const R=Math.min(b,this.hls.config.abrEwmaDefaultEstimateMax);R>T&&T===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=R)}break}const m=i&&!n,p=this.hls.config,x=!!(p.audioStreamController&&p.audioTrackController),v={levels:l,audioTracks:a,subtitleTracks:c,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:i,video:n,altAudio:x&&!m&&a.some(y=>!!y.url)};d.end=performance.now(),this.hls.trigger(S.MANIFEST_PARSED,v)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const d=new Error("invalid level idx"),u=e<0;if(this.hls.trigger(S.ERROR,{type:ce.OTHER_ERROR,details:B.LEVEL_SWITCH_ERROR,level:e,fatal:u,error:d,reason:d.message}),u)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,n=this.currentLevel,i=n?n.attrs["PATHWAY-ID"]:void 0,o=t[e],a=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,s===e&&n&&i===a)return;this.log(`Switching to level ${e} (${o.height?o.height+"p ":""}${o.videoRange?o.videoRange+" ":""}${o.codecSet?o.codecSet+" ":""}@${o.bitrate})${a?" with Pathway "+a:""} from level ${s}${i?" with Pathway "+i:""}`);const c={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(S.LEVEL_SWITCHING,c);const l=o.details;if(!l||l.live){const d=this.switchParams(o.uri,n==null?void 0:n.details,l);this.loadPlaylist(d)}}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(),s=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=s}}onError(e,t){t.fatal||!t.context||t.context.type===Te.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===oe.MAIN){const s=t.elementaryStreams;if(!Object.keys(s).some(i=>!!s[i]))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 s;const{level:n,details:i}=t,o=t.levelInfo;if(!o){var a;this.warn(`Invalid level index ${n}`),(a=t.deliveryDirectives)!=null&&a.skip&&(i.deltaUpdateFailed=!0);return}if(o===this.currentLevel||t.withoutMultiVariant){o.fragmentError===0&&(o.loadError=0);let c=o.details;c===t.details&&c.advanced&&(c=void 0),this.playlistLoaded(n,t,c)}else(s=t.deliveryDirectives)!=null&&s.skip&&(i.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=this.getUrlWithDirectives(e.uri,t),n=this.currentLevelIndex,i=e.attrs["PATHWAY-ID"],o=e.details,a=o==null?void 0:o.age;this.log(`Loading level index ${n}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${i?" Pathway "+i:""}${a&&o.live?" age "+a.toFixed(1)+(o.type&&" "+o.type||""):""} ${s}`),this.hls.trigger(S.LEVEL_LOADING,{url:s,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 s=this._levels.filter((i,o)=>o!==e?!0:(this.steering&&this.steering.removeLevel(i),i===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,i.details&&i.details.fragments.forEach(a=>a.level=-1)),!1));Wf(s),this._levels=s,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=s.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(S.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(S.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function ec(r){const e={};r.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function Gh(){return self.SourceBuffer||self.WebKitSourceBuffer}function Vh(){if(!Es())return!1;const e=Gh();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function iT(){if(!Vh())return!1;const r=Es();return typeof(r==null?void 0:r.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>r.isTypeSupported(kr(e,"video")))||["mp4a.40.2","fLaC"].some(e=>r.isTypeSupported(kr(e,"audio"))))}function oT(){var r;const e=Gh();return typeof(e==null||(r=e.prototype)==null?void 0:r.changeType)=="function"}const aT=100;class lT extends ra{constructor(e,t,s){super(e,t,s,"stream-controller",oe.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,i=n?n.currentTime:null;if(i===null||!ne(i)||(this.log(`Media seeked to ${i.toFixed(3)}`),!this.getBufferedFrag(i)))return;const o=this.getFwdBufferInfoAtPos(n,i,oe.MAIN,0);if(o===null||o.len===0){this.warn(`Main forward buffer length at ${i} on "seeked" event ${o?o.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(S.MANIFEST_PARSED,this.onManifestParsed,this),e.on(S.LEVEL_LOADING,this.onLevelLoading,this),e.on(S.LEVEL_LOADED,this.onLevelLoaded,this),e.on(S.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(S.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(S.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(S.BUFFER_CREATED,this.onBufferCreated,this),e.on(S.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(S.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(S.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(S.MANIFEST_PARSED,this.onManifestParsed,this),e.off(S.LEVEL_LOADED,this.onLevelLoaded,this),e.off(S.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(S.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(S.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(S.BUFFER_CREATED,this.onBufferCreated,this),e.off(S.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(S.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(S.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:s,hls:n}=this;if(this.stopLoad(),this.setInterval(aT),this.level=-1,!this.startFragRequested){let i=n.startLevel;i===-1&&(n.config.testBandwidth&&this.levels.length>1?(i=0,this.bitrateTest=!0):i=n.firstAutoLevel),n.nextLoadLevel=i,this.level=n.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),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,s=e==null?void 0:e[t],n=s==null?void 0:s.details;if(n&&(!n.live||this.levelLastLoaded===s&&!this.waitForLive(s))){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:s,media:n}=this;if(t===null||!n&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const i=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[i]))return;const o=s[i],a=this.getMainFwdBufferInfo();if(a===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(a,c)){const p={};this.altAudio===2&&(p.type="video"),this.hls.trigger(S.BUFFER_EOS,p),this.state=X.ENDED;return}if(!this.buffering)return;e.loadLevel!==i&&e.manualLevel===-1&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=e.nextLoadLevel=i;const l=o.details;if(!l||this.state===X.WAITING_LEVEL||this.waitForLive(o)){this.level=i,this.state=X.WAITING_LEVEL,this.startFragRequested=!1;return}const d=a.len,u=this.getMaxBufferLength(o.maxBitrate);if(d>=u)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:a.end;let g=this.getNextFragment(h,l);if(this.couldBacktrack&&!this.fragPrevious&&g&&qe(g)&&this.fragmentTracker.getState(g)!==rt.OK){var m;const x=((m=this.backtrackFragment)!=null?m:g).sn-l.startSN,v=l.fragments[x-1];v&&g.cc===v.cc&&(g=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,h)){if(!g.gap){const x=this.audioOnly&&!this.altAudio?Pe.AUDIO:Pe.VIDEO,v=(x===Pe.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,x,oe.MAIN)}g=this.getNextFragmentLoopLoading(g,l,a,oe.MAIN,u)}g&&(g.initSegment&&!g.initSegment.data&&!this.bitrateTest&&(g=g.initSegment),this.loadFragment(g,o,h))}loadFragment(e,t,s){const n=this.fragmentTracker.getState(e);n===rt.NOT_LOADED||n===rt.PARTIAL?qe(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,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,oe.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let s;const n=this.getAppendedFrag(t.currentTime);n&&n.start>1&&this.flushMainBuffer(0,n.start-1);const i=this.getLevelDetails();if(i!=null&&i.live){const a=this.getMainFwdBufferInfo();if(!a||a.len<i.targetduration*2)return}if(!t.paused&&e){const a=this.hls.nextLoadLevel,c=e[a],l=this.fragLastKbps;l&&this.fragCurrent?s=this.fragCurrent.duration*c.maxBitrate/(1e3*l)+1:s=0}else s=0;const o=this.getBufferedFrag(t.currentTime+s);if(o){const a=this.followingBufferedFrag(o);if(a){this.abortCurrentFrag();const c=a.maxStartPTS?a.maxStartPTS:a.start,l=a.duration,d=Math.max(o.end,c+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(d,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 s=t.media;ht(s,"playing",this.onMediaPlaying),ht(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(yt(s,"playing",this.onMediaPlaying),yt(s,"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(S.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 s=!1,n=!1;for(let i=0;i<t.levels.length;i++){const o=t.levels[i].audioCodec;o&&(s=s||o.indexOf("mp4a.40.2")!==-1,n=n||o.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&n&&!oT(),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:s}=this;if(!s||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 s;const{levels:n,startFragRequested:i}=this,o=t.level,a=t.details,c=a.totalduration;if(!n){this.warn(`Levels were reset while loading level ${o}`);return}this.log(`Level ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${c}`);const l=t.levelInfo,d=this.fragCurrent;d&&(this.state===X.FRAG_LOADING||this.state===X.FRAG_LOADING_WAITING_RETRY)&&d.level!==t.level&&d.loader&&this.abortCurrentFrag();let u=0;if(a.live||(s=l.details)!=null&&s.live){var h;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;u=this.alignPlaylists(a,l.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(l.details=a,this.levelLastLoaded=l,i||this.setStartPosition(a,u),this.hls.trigger(S.LEVEL_UPDATED,{details:a,level:o}),this.state===X.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=X.IDLE}i&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const n=this.hls.liveSyncPosition,i=this.getLoadPosition(),o=e.fragmentStart,a=e.edge,c=i>=o-t.maxFragLookUpTolerance&&i<=a;if(n!==null&&s.duration>n&&(i<n||!c)){const d=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!c&&s.readyState<4||i<a-d)&&(this._hasEnoughToStart||(this.nextLoadPosition=n),s.readyState))if(this.warn(`Playback: ${i.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${n.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var l;const u=ve.bufferInfo(s,n,0);if(!((l=u.buffered)!=null&&l.length)){s.currentTime=n;return}if(u.start<=i){s.currentTime=n;return}const{nextStart:g}=ve.bufferedInfo(u.buffered,i,0);g&&(s.currentTime=g)}else s.currentTime=n}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:n,payload:i}=e,{levels:o}=this;if(!o){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const a=o[s.level];if(!a){this.warn(`Level ${s.level} not found on progress`);return}const c=a.details;if(!c){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}const l=a.videoCodec,d=c.PTSKnown||!c.live,u=(t=s.initSegment)==null?void 0:t.data,h=this._getAudioCodec(a),g=this.transmuxer=this.transmuxer||new mh(this.hls,oe.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=n?n.index:-1,p=m!==-1,x=new ea(s.level,s.sn,s.stats.chunkCount,i.byteLength,m,p),v=this.initPTS[s.cc];g.push(i,u,h,l,s,n,c.totalduration,d,x,v)}onAudioTrackSwitching(e,t){const s=this.hls,n=this.altAudio!==0;if(In(t.url,s))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 o=this.fragCurrent;o&&(this.log("Switching to main audio track, cancel main fragment load"),o.abortRequests(),this.fragmentTracker.removeFragment(o)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(n){this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once(S.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(S.AUDIO_TRACK_SWITCHED,t)}),s.trigger(S.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(S.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=In(t.url,this.hls);if(s){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=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let n,i,o=!1;for(const a in s){const c=s[a];if(c.id==="main"){if(i=a,n=c,a==="video"){const l=s[a];l&&(this.videoBuffer=l.buffer)}}else o=!0}o&&n?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=n.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:n}=t,i=s.type===oe.MAIN;if(i){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${n?" p: "+n.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===X.PARSED&&(this.state=X.IDLE);return}const a=n?n.stats:s.stats;this.fragLastKbps=Math.round(8*a.total/(a.buffering.end-a.loading.first)),qe(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,n)}const o=this.media;o&&(!this._hasEnoughToStart&&ve.getBuffered(o).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),i&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=X.ERROR;return}switch(t.details){case B.FRAG_GAP:case B.FRAG_PARSING_ERROR:case B.FRAG_DECRYPT_ERROR:case B.FRAG_LOAD_ERROR:case B.FRAG_LOAD_TIMEOUT:case B.KEY_LOAD_ERROR:case B.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(oe.MAIN,t);break;case B.LEVEL_LOAD_ERROR:case B.LEVEL_LOAD_TIMEOUT:case B.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===X.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===Te.LEVEL&&(this.state=X.IDLE);break;case B.BUFFER_ADD_CODEC_ERROR:case B.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case B.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 B.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!==Pe.AUDIO||!this.altAudio){const s=(t===Pe.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,oe.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 s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}const n=this.timelineOffset;n&&s&&(s+=n);const i=this.getLevelDetails(),o=ve.getBuffered(e),a=o.length?o.start(0):0,c=a-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||c>0&&(c<l||this.loadingParts&&c<2*((i==null?void 0:i.partTarget)||0)))&&(this.log(`adjusting start position by ${c} to match buffer start`),s+=c,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${a}`),e.currentTime=s)}}_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(s=>{const{hls:n}=this,i=s==null?void 0:s.frag;if(!i||this.fragContextChanged(i))return;t.fragmentError=0,this.state=X.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const o=i.stats;o.parsing.start=o.parsing.end=o.buffering.start=o.buffering.end=self.performance.now(),n.trigger(S.FRAG_LOADED,s),i.bitrateTest=!1}).catch(s=>{this.state===X.STOPPED||this.state===X.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:n,chunkMeta:i}=e,o=this.getCurrentContext(i);if(!o){this.resetWhenMissingContext(i);return}const{frag:a,part:c,level:l}=o,{video:d,text:u,id3:h,initSegment:g}=n,{details:m}=l,p=this.altAudio?void 0:n.audio;if(this.fragContextChanged(a)){this.fragmentTracker.removeFragment(a);return}if(this.state=X.PARSING,g){const x=g.tracks;if(x){const T=a.initSegment||a;if(this.unhandledEncryptionError(g,a))return;this._bufferInitSegment(l,x,T,i),s.trigger(S.FRAG_PARSING_INIT_SEGMENT,{frag:T,id:t,tracks:x})}const v=g.initPTS,y=g.timescale,b=this.initPTS[a.cc];if(ne(v)&&(!b||b.baseTime!==v||b.timescale!==y)){const T=g.trackId;this.initPTS[a.cc]={baseTime:v,timescale:y,trackId:T},s.trigger(S.INIT_PTS_FOUND,{frag:a,id:t,initPTS:v,timescale:y,trackId:T})}}if(d&&m){p&&d.type==="audiovideo"&&this.logMuxedErr(a);const x=m.fragments[a.sn-1-m.startSN],v=a.sn===m.startSN,y=!x||a.cc>x.cc;if(n.independent!==!1){const{startPTS:b,endPTS:T,startDTS:R,endDTS:_}=d;if(c)c.elementaryStreams[d.type]={startPTS:b,endPTS:T,startDTS:R,endDTS:_};else if(d.firstKeyFrame&&d.independent&&i.id===1&&!y&&(this.couldBacktrack=!0),d.dropped&&d.independent){const w=this.getMainFwdBufferInfo(),A=(w?w.end:this.getLoadPosition())+this.config.maxBufferHole,C=d.firstKeyFramePTS?d.firstKeyFramePTS:b;if(!v&&A<C-this.config.maxBufferHole&&!y){this.backtrack(a);return}else y&&(a.gap=!0);a.setElementaryStreamInfo(d.type,a.start,T,a.start,_,!0)}else v&&b-(m.appliedTimelineOffset||0)>yn&&(a.gap=!0);a.setElementaryStreamInfo(d.type,b,T,R,_),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(d,a,c,i,v||y)}else if(v||y)a.gap=!0;else{this.backtrack(a);return}}if(p){const{startPTS:x,endPTS:v,startDTS:y,endDTS:b}=p;c&&(c.elementaryStreams[Pe.AUDIO]={startPTS:x,endPTS:v,startDTS:y,endDTS:b}),a.setElementaryStreamInfo(Pe.AUDIO,x,v,y,b),this.bufferFragmentData(p,a,c,i)}if(m&&h!=null&&h.samples.length){const x={id:t,frag:a,details:m,samples:h.samples};s.trigger(S.FRAG_PARSING_METADATA,x)}if(m&&u){const x={id:t,frag:a,details:m,samples:u.samples};s.trigger(S.FRAG_PARSING_USERDATA,x)}}logMuxedErr(e){this.warn(`${qe(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,n){if(this.state!==X.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:i,video:o,audiovideo:a}=t;if(i){const l=e.audioCodec;let d=fn(i.codec,l);d==="mp4a"&&(d="mp4a.40.5");const u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){d&&(d.indexOf("mp4a.40.5")!==-1?d="mp4a.40.2":d="mp4a.40.5");const h=i.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&u.indexOf("firefox")===-1&&(d="mp4a.40.5")}d&&d.indexOf("mp4a.40.5")!==-1&&u.indexOf("android")!==-1&&i.container!=="audio/mpeg"&&(d="mp4a.40.2",this.log(`Android: force audio codec to ${d}`)),l&&l!==d&&this.log(`Swapping manifest audio codec "${l}" for "${d}"`),i.levelCodec=d,i.id=oe.MAIN,this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${d||""}/${l||""}/${i.codec}]`),delete t.audiovideo}if(o){o.levelCodec=e.videoCodec,o.id=oe.MAIN;const l=o.codec;if((l==null?void 0:l.length)===4)switch(l){case"hvc1":case"hev1":o.codec="hvc1.1.6.L120.90";break;case"av01":o.codec="av01.0.04M.08";break;case"avc1":o.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${o.container}, codecs[level/parsed]=[${e.videoCodec||""}/${l}]${o.codec!==l?" parsed-corrected="+o.codec:""}${o.supplemental?" supplemental="+o.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 c=Object.keys(t);if(c.length){if(this.hls.trigger(S.BUFFER_CODECS,t),!this.hls)return;c.forEach(l=>{const u=t[l].initSegment;u!=null&&u.byteLength&&this.hls.trigger(S.BUFFER_APPENDING,{type:l,data:u,frag:s,part:null,chunkMeta:n,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,oe.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=e==null?void 0:e[t];return s?this.getMaxBufferLength(s.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 s=e.currentTime;if(ve.isBuffered(e,s)?t=this.getAppendedFrag(s):ve.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const n=this.fragPlaying,i=t.level;(!n||t.sn!==n.sn||n.level!==i)&&(this.fragPlaying=t,this.hls.trigger(S.FRAG_CHANGED,{frag:t}),(!n||n.level!==i)&&this.hls.trigger(S.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return ne(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(ne(t)){const s=this.getLevelDetails(),n=this.currentFrag||(s?Os(null,s.fragments,t):null);if(n){const i=n.programDateTime;if(i!==null){const o=i+(t-n.start)*1e3;return new Date(o)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class cT extends Ut{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyIdToKeyInfo){const n=this.keyIdToKeyInfo[s].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=B.KEY_LOAD_ERROR,s,n,i){return new ds({type:ce.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:i,error:s,networkDetails:n})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let n=0,i=t.length;n<i;n++){const o=t[n];if(e.cc<=o.cc&&(!qe(e)||!qe(o)||e.sn<o.sn)||!s&&n==i-1)return this.emeController.selectKeySystemFormat(o).then(a=>{if(!this.emeController)return;o.setKeyFormat(a);const c=gn(a);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const n=pr(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 s,n;t&&e.setKeyFormat(t);const i=e.decryptdata;if(!i){const l=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,B.KEY_LOAD_ERROR,l))}const o=i.uri;if(!o)return Promise.reject(this.createKeyLoadError(e,B.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${o}"`)));const a=Li(i);let c=this.keyIdToKeyInfo[a];if((s=c)!=null&&s.decryptdata.key)return i.key=c.decryptdata.key,Promise.resolve({frag:e,keyInfo:c});if(this.emeController&&(n=c)!=null&&n.keyLoadPromise)switch(this.emeController.getKeyStatus(c.decryptdata)){case"usable":case"usable-in-future":return c.keyLoadPromise.then(d=>{const{keyInfo:u}=d;return i.key=u.decryptdata.key,{frag:e,keyInfo:u}})}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${i.keyId?" keyId: "+ct(i.keyId):""} URI: ${i.uri} from ${e.type} ${e.level}`),c=this.keyIdToKeyInfo[a]={decryptdata:i,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},i.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return i.keyFormat==="identity"?this.loadKeyHTTP(c,e):this.loadKeyEME(c,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(c,e);default:return Promise.reject(this.createKeyLoadError(e,B.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var n;if(!e.decryptdata.keyId&&(n=t.initSegment)!=null&&n.data){const o=Lv(t.initSegment.data);if(o.length){let a=o[0];a.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${ct(a)}`),bs.setKeyIdForUri(e.decryptdata.uri,a)):(a=bs.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${ct(a)}`)),e.decryptdata.keyId=a}}if(!e.decryptdata.keyId&&!qe(t))return Promise.resolve(s);const i=this.emeController.loadKey(s);return(e.keyLoadPromise=i.then(o=>(e.mediaKeySessionContext=o,s))).catch(o=>{throw e.keyLoadPromise=null,"data"in o&&(o.data.frag=t),o})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,n=s.loader,i=new n(s);return t.keyLoader=e.loader=i,e.keyLoadPromise=new Promise((o,a)=>{const c={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=s.keyLoadPolicy.default,d={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(h,g,m,p)=>{const{frag:x,keyInfo:v}=m,y=Li(v.decryptdata);if(!x.decryptdata||v!==this.keyIdToKeyInfo[y])return a(this.createKeyLoadError(x,B.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));v.decryptdata.key=x.decryptdata.key=new Uint8Array(h.data),x.keyLoader=null,v.loader=null,o({frag:x,keyInfo:v})},onError:(h,g,m,p)=>{this.resetLoader(g),a(this.createKeyLoadError(t,B.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),m,_e({url:c.url,data:void 0},h)))},onTimeout:(h,g,m)=>{this.resetLoader(g),a(this.createKeyLoadError(t,B.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m))},onAbort:(h,g,m)=>{this.resetLoader(g),a(this.createKeyLoadError(t,B.INTERNAL_ABORTED,new Error("key loading aborted"),m))}};i.load(c,d,u)})}resetLoader(e){const{frag:t,keyInfo:s,url:n}=e,i=s.loader;t.keyLoader===i&&(t.keyLoader=null,s.loader=null);const o=Li(s.decryptdata)||n;delete this.keyIdToKeyInfo[o],i&&i.destroy()}}function Li(r){if(r.keyFormat!==dt.FAIRPLAY){const e=r.keyId;if(e)return ct(e)}return r.uri}function tc(r){const{type:e}=r;switch(e){case Te.AUDIO_TRACK:return oe.AUDIO;case Te.SUBTITLE_TRACK:return oe.SUBTITLE;default:return oe.MAIN}}function Ci(r,e){let t=r.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class dT{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(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.LEVEL_LOADING,this.onLevelLoading,this),e.on(S.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(S.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(S.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.LEVEL_LOADING,this.onLevelLoading,this),e.off(S.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(S.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(S.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,n=t.loader,i=s||n,o=new i(t);return this.loaders[e.type]=o,o}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:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Te.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:n,pathwayId:i,url:o,deliveryDirectives:a,levelInfo:c}=t;this.load({id:s,level:n,pathwayId:i,responseType:"text",type:Te.LEVEL,url:o,deliveryDirectives:a,levelOrTrack:c})}onAudioTrackLoading(e,t){const{id:s,groupId:n,url:i,deliveryDirectives:o,track:a}=t;this.load({id:s,groupId:n,level:null,responseType:"text",type:Te.AUDIO_TRACK,url:i,deliveryDirectives:o,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:s,groupId:n,url:i,deliveryDirectives:o,track:a}=t;this.load({id:s,groupId:n,level:null,responseType:"text",type:Te.SUBTITLE_TRACK,url:i,deliveryDirectives:o,levelOrTrack:a})}onLevelsUpdated(e,t){const s=this.loaders[Te.LEVEL];if(s){const n=s.context;n&&!t.levels.some(i=>i===n.levelOrTrack)&&(s.abort(),delete this.loaders[Te.LEVEL])}}load(e){var t;const s=this.hls.config;let n=this.getInternalLoader(e);if(n){const l=this.hls.logger,d=n.context;if(d&&d.levelOrTrack===e.levelOrTrack&&(d.url===e.url||d.deliveryDirectives&&!e.deliveryDirectives)){d.url===e.url?l.log(`[playlist-loader]: ignore ${e.url} ongoing request`):l.log(`[playlist-loader]: ignore ${e.url} in favor of ${d.url}`);return}l.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}let i;if(e.type===Te.MANIFEST?i=s.manifestLoadPolicy.default:i=De({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),ne((t=e.deliveryDirectives)==null?void 0:t.part)){let l;if(e.type===Te.LEVEL&&e.level!==null?l=this.hls.levels[e.level].details:e.type===Te.AUDIO_TRACK&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===Te.SUBTITLE_TRACK&&e.id!==null&&(l=this.hls.subtitleTracks[e.id].details),l){const d=l.partTarget,u=l.targetduration;if(d&&u){const h=Math.max(d*3,u*.8)*1e3;i=De({},i,{maxTimeToFirstByteMs:Math.min(h,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(h,i.maxTimeToFirstByteMs)})}}}const o=i.errorRetry||i.timeoutRetry||{},a={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(l,d,u,h)=>{const g=this.getInternalLoader(u);this.resetInternalLoader(u.type);const m=l.data;d.parsing.start=performance.now(),ts.isMediaPlaylist(m)||u.type!==Te.MANIFEST?this.handleTrackOrLevelPlaylist(l,d,u,h||null,g):this.handleMasterPlaylist(l,d,u,h)},onError:(l,d,u,h)=>{this.handleNetworkError(d,u,!1,l,h)},onTimeout:(l,d,u)=>{this.handleNetworkError(d,u,!0,void 0,l)}};n.load(e,a,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,n){const i=this.hls,o=e.data,a=Ci(e,s),c=ts.parseMasterPlaylist(o,a);if(c.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,c.playlistParsingError,n,t);return}const{contentSteering:l,levels:d,sessionData:u,sessionKeys:h,startTimeOffset:g,variableList:m}=c;this.variableList=m,d.forEach(y=>{const{unknownCodecs:b}=y;if(b){const{preferManagedMediaSource:T}=this.hls.config;let{audioCodec:R,videoCodec:_}=y;for(let w=b.length;w--;){const A=b[w];_r(A,"audio",T)?(y.audioCodec=R=R?`${R},${A}`:A,sr.audio[R.substring(0,4)]=2,b.splice(w,1)):_r(A,"video",T)&&(y.videoCodec=_=_?`${_},${A}`:A,sr.video[_.substring(0,4)]=2,b.splice(w,1))}}});const{AUDIO:p=[],SUBTITLES:x,"CLOSED-CAPTIONS":v}=ts.parseMasterPlaylistMedia(o,a,c);p.length&&!p.some(b=>!b.url)&&d[0].audioCodec&&!d[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Ve({}),bitrate:0,url:""})),i.trigger(S.MANIFEST_LOADED,{levels:d,audioTracks:p,subtitles:x,captions:v,contentSteering:l,url:a,stats:t,networkDetails:n,sessionData:u,sessionKeys:h,startTimeOffset:g,variableList:m})}handleTrackOrLevelPlaylist(e,t,s,n,i){const o=this.hls,{id:a,level:c,type:l}=s,d=Ci(e,s),u=ne(c)?c:ne(a)?a:0,h=tc(s),g=ts.parseLevelPlaylist(e.data,d,u,h,0,this.variableList);if(l===Te.MANIFEST){const m={attrs:new Ve({}),bitrate:0,details:g,name:"",url:d};g.requestScheduled=t.loading.start+Hf(g,0),o.trigger(S.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:d,stats:t,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=g,this.handlePlaylistLoaded(g,e,t,s,n,i)}handleManifestParsingError(e,t,s,n,i){this.hls.trigger(S.ERROR,{type:ce.NETWORK_ERROR,details:B.MANIFEST_PARSING_ERROR,fatal:t.type===Te.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:n,stats:i})}handleNetworkError(e,t,s=!1,n,i){let o=`A network ${s?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${e.type}`;e.type===Te.LEVEL?o+=`: ${e.level} id: ${e.id}`:(e.type===Te.AUDIO_TRACK||e.type===Te.SUBTITLE_TRACK)&&(o+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(o);this.hls.logger.warn(`[playlist-loader]: ${o}`);let c=B.UNKNOWN,l=!1;const d=this.getInternalLoader(e);switch(e.type){case Te.MANIFEST:c=s?B.MANIFEST_LOAD_TIMEOUT:B.MANIFEST_LOAD_ERROR,l=!0;break;case Te.LEVEL:c=s?B.LEVEL_LOAD_TIMEOUT:B.LEVEL_LOAD_ERROR,l=!1;break;case Te.AUDIO_TRACK:c=s?B.AUDIO_TRACK_LOAD_TIMEOUT:B.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case Te.SUBTITLE_TRACK:c=s?B.SUBTITLE_TRACK_LOAD_TIMEOUT:B.SUBTITLE_LOAD_ERROR,l=!1;break}d&&this.resetInternalLoader(e.type);const u={type:ce.NETWORK_ERROR,details:c,fatal:l,url:e.url,loader:d,context:e,error:a,networkDetails:t,stats:i};if(n){const h=(t==null?void 0:t.url)||e.url;u.response=_e({url:h,data:void 0},n)}this.hls.trigger(S.ERROR,u)}handlePlaylistLoaded(e,t,s,n,i,o){const a=this.hls,{type:c,level:l,levelOrTrack:d,id:u,groupId:h,deliveryDirectives:g}=n,m=Ci(t,n),p=tc(n);let x=typeof n.level=="number"&&p===oe.MAIN?l:void 0;const v=e.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${e.url}`),!a.config.ignorePlaylistParsingErrors){a.trigger(S.ERROR,{type:ce.NETWORK_ERROR,details:B.LEVEL_PARSING_ERROR,fatal:!1,url:m,error:v,reason:v.message,response:t,context:n,level:x,parent:p,networkDetails:i,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){const y=e.playlistParsingError=new Error("No Segments found in Playlist");a.trigger(S.ERROR,{type:ce.NETWORK_ERROR,details:B.LEVEL_EMPTY_ERROR,fatal:!1,url:m,error:y,reason:y.message,response:t,context:n,level:x,parent:p,networkDetails:i,stats:s});return}switch(e.live&&o&&(o.getCacheAge&&(e.ageHeader=o.getCacheAge()||0),(!o.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case Te.MANIFEST:case Te.LEVEL:if(x){if(!d)x=0;else if(d!==a.levels[x]){const y=a.levels.indexOf(d);y>-1&&(x=y)}}a.trigger(S.LEVEL_LOADED,{details:e,levelInfo:d||a.levels[0],level:x||0,id:u||0,stats:s,networkDetails:i,deliveryDirectives:g,withoutMultiVariant:c===Te.MANIFEST});break;case Te.AUDIO_TRACK:a.trigger(S.AUDIO_TRACK_LOADED,{details:e,track:d,id:u||0,groupId:h||"",stats:s,networkDetails:i,deliveryDirectives:g});break;case Te.SUBTITLE_TRACK:a.trigger(S.SUBTITLE_TRACK_LOADED,{details:e,track:d,id:u||0,groupId:h||"",stats:s,networkDetails:i,deliveryDirectives:g});break}}}class Bt{static get version(){return Pr}static isMSESupported(){return Vh()}static isSupported(){return iT()}static getMediaSource(){return Es()}static get Events(){return S}static get MetadataSchema(){return kt}static get ErrorTypes(){return ce}static get ErrorDetails(){return B}static get DefaultConfig(){return Bt.defaultConfig?Bt.defaultConfig:WE}static set DefaultConfig(e){Bt.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new na,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=pv(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=qE(Bt.DefaultConfig,e,t);this.userConfig=e,s.progressive&&XE(s,t);const{abrController:n,bufferController:i,capLevelController:o,errorController:a,fpsController:c}=s,l=new a(this),d=this.abrController=new n(this),u=new uy(this),h=s.interstitialsController,g=h?this.interstitialsController=new h(this,Bt):null,m=this.bufferController=new i(this,u),p=this.capLevelController=new o(this),x=new c(this),v=new dT(this),y=s.contentSteeringController,b=y?new y(this):null,T=this.levelController=new nT(this,b),R=new sT(this),_=new cT(this.config,this.logger),w=this.streamController=new lT(this,u,_),A=this.gapController=new eT(this,u);p.setStreamController(w),x.setStreamController(w);const C=[v,T,w];g&&C.splice(1,0,g),b&&C.splice(1,0,b),this.networkControllers=C;const L=[d,m,A,p,x,R,u];this.audioTrackController=this.createController(s.audioTrackController,C);const P=s.audioStreamController;P&&C.push(this.audioStreamController=new P(this,u,_)),this.subtitleTrackController=this.createController(s.subtitleTrackController,C);const M=s.subtitleStreamController;M&&C.push(this.subtititleStreamController=new M(this,u,_)),this.createController(s.timelineController,L),_.emeController=this.emeController=this.createController(s.emeController,L),this.cmcdController=this.createController(s.cmcdController,L),this.latencyController=this.createController(rT,L),this.coreComponents=L,C.push(l);const j=l.onErrorOut;typeof j=="function"&&this.on(S.ERROR,j,l),this.on(S.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,n){this._emitter.off(e,t,s,n)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const n=e===S.ERROR;this.trigger(S.ERROR,{type:ce.OTHER_ERROR,details:B.INTERNAL_EXCEPTION,fatal:n,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(S.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const i=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(S.ERROR,{type:ce.OTHER_ERROR,details:B.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 t="media"in e,s=t?e.media:e,n=t?e:{media:s};this._media=s,this.trigger(S.MEDIA_ATTACHING,n)}detachMedia(){this.logger.log("detachMedia"),this.trigger(S.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(S.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,s=this._url,n=this._url=Wo.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${n}`),t&&s&&(s!==n||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(S.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[oe.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[oe.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[oe.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=eE()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){qv(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const s=e.length;for(let n=0;n<s;n++)if(e[n].maxBitrate>=t)return n;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let n;if(t===-1&&e!=null&&e.length?n=e.length-1:n=t,s)for(let i=n;i--;){const o=e[i].attrs["HDCP-LEVEL"];if(o&&o<=s)return i}return n}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){const s=Cf(t);return If(e,s,navigator.mediaCapabilities)}}Bt.defaultConfig=void 0;const Hh=ft("relative group rounded-lg overflow-hidden bg-card dark:bg-black text-card-foreground",{variants:{size:{sm:"[&_button]:p-0.5 [&_.vp-icon]:h-4 [&_.vp-icon]:w-4 [&_.vp-time]:text-[10px]",default:"",lg:"[&_button]:p-1.5 [&_.vp-icon]:h-6 [&_.vp-icon]:w-6 [&_.vp-time]:text-sm"}},defaultVariants:{size:"default"}});function sc(r){return r.includes(".m3u8")||r.includes("m3u8?")}const $r=E.forwardRef(({src:r,poster:e,showControls:t=!0,controlsTimeout:s=3e3,enablePiP:n=!0,enableFullscreen:i=!0,enablePlaybackRate:o=!0,playbackRates:a=[.5,.75,1,1.25,1.5,2],tracks:c,chapters:l,aspectRatio:d="16/9",autoPlay:u=!1,loop:h=!1,muted:g=!1,preload:m="metadata",size:p,onPlay:x,onPause:v,onEnded:y,onTimeUpdate:b,onFullscreenChange:T,className:R},_)=>{const w=E.useRef(null),A=E.useRef(null),C=E.useRef(null),L=E.useRef(null),P=E.useRef(!1),M=E.useRef(null),j=E.useRef(null),[D,$]=E.useState(!1),[N,F]=E.useState(0),[k,z]=E.useState(0),[Y,U]=E.useState(0),[K,G]=E.useState(1),[H,q]=E.useState(g),[J,ee]=E.useState(!1),[te,de]=E.useState(!0),[ie,ue]=E.useState(!1),[re,Z]=E.useState(!1),[fe,Re]=E.useState(!1),[he,be]=E.useState(1),[Ae,Ie]=E.useState(-1),[Me,$e]=E.useState(!0),[Le,at]=E.useState(null),[Ge,Mt]=E.useState(!1),[Je,Tt]=E.useState(null),[Ft,wt]=E.useState(null),we=ye(),mt=E.useMemo(()=>V=>{A.current=V,typeof _=="function"?_(V):_&&(_.current=V)},[_]),Ot=typeof document<"u"&&"pictureInPictureEnabled"in document,Xe=E.useMemo(()=>l?[...l].sort((V,se)=>V.time-se.time):[],[l]),Rs=E.useMemo(()=>{if(Xe.length===0)return null;let V=Xe[0];for(const se of Xe)if(se.time<=N)V=se;else break;return V},[Xe,N]),$s=E.useCallback(V=>{if(Xe.length===0)return null;let se=Xe[0];for(const Ce of Xe)if(Ce.time<=V)se=Ce;else break;return se},[Xe]);E.useEffect(()=>{var se,Ce;const V=A.current;if(V){if(at(null),F(0),z(0),U(0),$e(!0),Mt(!1),sc(r))if(Bt.isSupported()){(se=M.current)==null||se.destroy();const Qe=new Bt({startLevel:-1});M.current=Qe,Qe.loadSource(r),Qe.attachMedia(V),Qe.on(Bt.Events.MANIFEST_PARSED,()=>{u&&V.play().catch(()=>{})}),Qe.on(Bt.Events.LEVEL_LOADED,(jt,Vt)=>{Mt(!!Vt.details.live)}),Qe.on(Bt.Events.ERROR,(jt,Vt)=>{Vt.fatal&&($e(!1),at(we.videoPlayer_error))})}else V.canPlayType("application/vnd.apple.mpegurl")&&(V.src=r,Mt(!1));else(Ce=M.current)==null||Ce.destroy(),M.current=null,V.src=r;return()=>{var Qe;(Qe=M.current)==null||Qe.destroy(),M.current=null}}},[r]),E.useEffect(()=>{if(c){const V=c.findIndex(se=>se.default);V>=0&&Ie(V)}},[c]),E.useEffect(()=>{const V=A.current;if(!V)return;const se=()=>{const Ur=V.duration;z(isFinite(Ur)?Ur:0),$e(!1),(!isFinite(Ur)||Ur===0)&&Mt(!0)},Ce=()=>$e(!0),Qe=()=>$e(!1),jt=()=>{P.current||(F(V.currentTime),b==null||b(V.currentTime)),V.buffered.length>0&&U(V.buffered.end(V.buffered.length-1))},Vt=()=>{$(!0),x==null||x()},Vs=()=>{$(!1),v==null||v()},ya=()=>{$(!1),y==null||y()},ba=()=>{$(!1),$e(!1),at(we.videoPlayer_error)};return V.addEventListener("loadedmetadata",se),V.addEventListener("waiting",Ce),V.addEventListener("canplay",Qe),V.addEventListener("timeupdate",jt),V.addEventListener("play",Vt),V.addEventListener("pause",Vs),V.addEventListener("ended",ya),V.addEventListener("error",ba),()=>{V.removeEventListener("loadedmetadata",se),V.removeEventListener("waiting",Ce),V.removeEventListener("canplay",Qe),V.removeEventListener("timeupdate",jt),V.removeEventListener("play",Vt),V.removeEventListener("pause",Vs),V.removeEventListener("ended",ya),V.removeEventListener("error",ba)}},[x,v,y,b,we.videoPlayer_error]),E.useEffect(()=>{const V=A.current;V&&(V.volume=H?0:K)},[K,H]),E.useEffect(()=>{const V=()=>{const se=!!document.fullscreenElement;ee(se),T==null||T(se)};return document.addEventListener("fullscreenchange",V),()=>document.removeEventListener("fullscreenchange",V)},[T]),E.useEffect(()=>{const V=A.current;if(V)for(let se=0;se<V.textTracks.length;se++)V.textTracks[se].mode=se===Ae?"showing":"hidden"},[Ae]),E.useEffect(()=>{if(!ie&&!re&&!fe)return;const V=()=>{ue(!1),Z(!1),Re(!1)},se=setTimeout(()=>{document.addEventListener("click",V,{once:!0})},0);return()=>{clearTimeout(se),document.removeEventListener("click",V)}},[ie,re,fe]);const fs=E.useCallback(()=>{de(!0),L.current&&clearTimeout(L.current),D&&(L.current=setTimeout(()=>de(!1),s))},[D,s]),As=()=>{const V=A.current;V&&(D?V.pause():V.play())},ns=E.useCallback(V=>{const se=A.current;!se||!k||Ge||(se.currentTime=V*k,F(se.currentTime))},[k,Ge]),Rt=V=>{if(!C.current||Ge)return;const se=C.current.getBoundingClientRect();ns((V.clientX-se.left)/se.width)},cr=V=>{var se,Ce;Ge||(P.current=!0,(Ce=(se=V.target).setPointerCapture)==null||Ce.call(se,V.pointerId))},Us=V=>{if(!C.current||!k||Ge)return;const se=C.current.getBoundingClientRect(),Ce=Math.max(0,Math.min(1,(V.clientX-se.left)/se.width));wt({x:V.clientX-se.left,time:Ce*k})},Is=()=>{wt(null)};E.useEffect(()=>{const V=C.current;if(!V)return;const se=Qe=>{if(!P.current||!C.current||Ge)return;const jt=C.current.getBoundingClientRect();ns(Math.max(0,Math.min(1,(Qe.clientX-jt.left)/jt.width)))},Ce=()=>{P.current=!1};return V.addEventListener("pointermove",se),V.addEventListener("pointerup",Ce),V.addEventListener("lostpointercapture",Ce),()=>{V.removeEventListener("pointermove",se),V.removeEventListener("pointerup",Ce),V.removeEventListener("lostpointercapture",Ce)}},[ns,Ge]);const Yt=()=>{var V,se;w.current&&(document.fullscreenElement?document.exitFullscreen():(se=(V=w.current).requestFullscreen)==null||se.call(V))},xe=async()=>{const V=A.current;if(V)try{document.pictureInPictureElement?await document.exitPictureInPicture():await V.requestPictureInPicture()}catch{}},Ue=()=>q(V=>!V),Ye=V=>{const se=A.current;se&&(se.playbackRate=V),be(V),ue(!1)},nt=V=>{Ie(V),Z(!1)},Gt=E.useCallback(V=>{const se=A.current;!se||Ge||(se.currentTime=Math.max(0,Math.min(se.duration||0,se.currentTime+V)),F(se.currentTime))},[Ge]),et=V=>{const se=w.current;if(!se)return;const Ce=se.getBoundingClientRect(),Qe=(V.clientX-Ce.left)/Ce.width;Qe<.3?(Gt(-10),Tt({side:"left",key:Date.now()})):Qe>.7?(Gt(10),Tt({side:"right",key:Date.now()})):Yt()},pt=V=>{if(V.changedTouches.length!==1)return;const se=V.changedTouches[0],Ce=w.current;if(!Ce)return;const Qe=Ce.getBoundingClientRect(),jt=(se.clientX-Qe.left)/Qe.width,Vt=Date.now(),Vs=j.current;Vs&&Vt-Vs.time<300&&Math.abs(jt-Vs.relX)<.35?(j.current=null,jt<.3?(Gt(-10),Tt({side:"left",key:Vt})):jt>.7?(Gt(10),Tt({side:"right",key:Vt})):Yt()):j.current={time:Vt,relX:jt}};E.useEffect(()=>{if(!Je)return;const V=setTimeout(()=>Tt(null),600);return()=>clearTimeout(V)},[Je]);const Gs=V=>{const se=A.current;se&&(se.currentTime=V.time,F(V.time),Re(!1),fs())},At=V=>{if(A.current){switch(V.key){case" ":case"k":V.preventDefault(),As();break;case"f":V.preventDefault(),Yt();break;case"m":V.preventDefault(),Ue();break;case"ArrowLeft":V.preventDefault(),Gt(-5);break;case"ArrowRight":V.preventDefault(),Gt(5);break;case"ArrowUp":V.preventDefault(),G(Ce=>Math.min(1,Ce+.1)),q(!1);break;case"ArrowDown":V.preventDefault(),G(Ce=>Math.max(0,Ce-.1));break;case"c":V.preventDefault(),c&&c.length>0&&Ie(Ce=>Ce>=0?-1:0);break}fs()}},It=H||K===0?W.VolumeX:K<.5?W.Volume1:W.Volume2,dr=k?N/k:0,is=k?Y/k:0,hs=Ft?$s(Ft.time):null;return f.jsxs("div",{ref:w,className:I(Hh({size:p}),R),style:{aspectRatio:d},onMouseMove:fs,onMouseLeave:()=>D&&de(!1),onKeyDown:At,tabIndex:0,role:"application","aria-label":we.videoPlayer_label,children:[f.jsx("video",{ref:mt,poster:e,autoPlay:u,loop:h,muted:g,preload:sc(r)?void 0:m,className:"w-full h-full object-contain",children:c==null?void 0:c.map((V,se)=>f.jsx("track",{src:V.src,kind:V.kind,srcLang:V.srcLang,label:V.label,default:V.default},se))}),f.jsx("div",{className:"absolute inset-0 z-[5]",onClick:As,onDoubleClick:et,onTouchEnd:pt}),Je&&f.jsx("div",{className:I("absolute top-0 bottom-0 z-20 flex items-center justify-center pointer-events-none animate-[vp-skip-fade_0.6s_ease-out_forwards]",Je.side==="left"?"left-0 w-[30%] rounded-r-[50%]":"right-0 w-[30%] rounded-l-[50%]"),style:{background:"radial-gradient(circle at center, rgba(255,255,255,0.2) 0%, transparent 70%)"},children:f.jsxs("div",{className:"flex flex-col items-center gap-1 text-white drop-shadow-lg pointer-events-none select-none",children:[Je.side==="left"?f.jsx(W.ChevronsLeft,{className:"h-8 w-8"}):f.jsx(W.ChevronsRight,{className:"h-8 w-8"}),f.jsx("span",{className:"text-sm font-medium",children:"10s"})]})},Je.key),Le&&f.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2 bg-card/90 dark:bg-black/90 z-30",children:[f.jsx(W.AlertCircle,{className:"h-10 w-10 text-destructive"}),f.jsx("p",{className:"text-sm text-destructive font-medium",children:Le})]}),Me&&!Le&&D&&f.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-20 pointer-events-none",children:f.jsx(W.Loader2,{className:"h-10 w-10 text-primary animate-spin"})}),!D&&!Le&&t&&f.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10 pointer-events-none",children:f.jsx("div",{className:"h-16 w-16 rounded-full bg-background/60 dark:bg-black/50 flex items-center justify-center backdrop-blur-sm",children:f.jsx(W.Play,{className:"h-8 w-8 text-foreground dark:text-white ml-1"})})}),Ge&&!Le&&f.jsxs("div",{className:"absolute top-3 left-3 z-20 flex items-center gap-1 bg-red-600 text-white text-xs font-bold px-2 py-0.5 rounded pointer-events-none",children:[f.jsx(W.Radio,{className:"h-3 w-3"}),we.videoPlayer_live]}),t&&!Le&&f.jsxs("div",{className:I("absolute bottom-0 left-0 right-0 z-20 bg-gradient-to-t from-background/80 dark:from-black/80 to-transparent pt-6 pb-2 px-3 transition-opacity duration-200",te||!D?"opacity-100":"opacity-0 pointer-events-none"),children:[Rs&&Xe.length>0&&f.jsx("div",{className:"text-xs text-foreground/80 dark:text-white/80 mb-1 truncate",children:Rs.title}),!Ge&&f.jsxs("div",{ref:C,className:"relative h-1 bg-foreground/20 dark:bg-white/20 rounded-full cursor-pointer mb-2 group/seek hover:h-1.5 transition-[height]",onClick:Rt,onPointerDown:cr,onMouseMove:Us,onMouseLeave:Is,role:"slider","aria-label":we.videoPlayer_seek,"aria-valuemin":0,"aria-valuemax":Math.round(k),"aria-valuenow":Math.round(N),"aria-valuetext":Dt(N),tabIndex:0,children:[f.jsx("div",{className:"absolute inset-y-0 left-0 bg-muted-foreground/30 rounded-full",style:{width:`${is*100}%`}}),f.jsx("div",{className:"absolute inset-y-0 left-0 bg-primary rounded-full",style:{width:`${dr*100}%`}}),Xe.length>0&&k>0&&Xe.map((V,se)=>f.jsx("div",{className:"absolute top-1/2 -translate-y-1/2 w-0.5 h-full bg-foreground/60 dark:bg-white/60 rounded-full z-[1]",style:{left:`${V.time/k*100}%`}},se)),f.jsx("div",{className:"absolute top-1/2 h-3 w-3 rounded-full bg-primary shadow opacity-0 group-hover/seek:opacity-100 transition-opacity z-[2]",style:{left:`${dr*100}%`,transform:"translate(-50%, -50%)"}}),Ft&&k>0&&f.jsxs("div",{className:"absolute bottom-full mb-2 -translate-x-1/2 bg-popover text-popover-foreground border rounded px-2 py-1 text-xs whitespace-nowrap shadow-md pointer-events-none z-30",style:{left:Ft.x},children:[(hs==null?void 0:hs.thumbnail)&&f.jsx("img",{src:hs.thumbnail,alt:hs.title,className:"w-24 h-14 object-cover rounded mb-1"}),f.jsx("div",{className:"font-medium tabular-nums",children:Dt(Ft.time)}),hs&&f.jsx("div",{className:"text-muted-foreground text-[10px]",children:hs.title})]})]}),f.jsxs("div",{className:"flex items-center gap-1.5 text-foreground dark:text-white flex-wrap",children:[f.jsx("button",{type:"button",onClick:As,className:"p-1 hover:bg-foreground/10 dark:hover:bg-white/10 rounded transition-colors shrink-0","aria-label":D?we.videoPlayer_pause:we.videoPlayer_play,children:D?f.jsx(W.Pause,{className:"vp-icon h-5 w-5"}):f.jsx(W.Play,{className:"vp-icon h-5 w-5"})}),Ge?f.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[f.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-500 animate-pulse shrink-0"}),f.jsx("span",{className:"vp-time font-bold text-red-500",children:we.videoPlayer_live})]}):f.jsxs("span",{className:"vp-time text-xs tabular-nums shrink-0",children:[Dt(N)," / ",Dt(k)]}),f.jsx("div",{className:"flex-1 min-w-0"}),Xe.length>0&&f.jsxs("div",{className:"relative shrink-0",children:[f.jsx("button",{type:"button",onClick:V=>{V.stopPropagation(),Re(se=>!se),ue(!1),Z(!1)},className:"px-1.5 py-0.5 text-xs hover:bg-foreground/10 dark:hover:bg-white/10 rounded transition-colors","aria-label":we.videoPlayer_chapter,children:we.videoPlayer_chapter}),fe&&f.jsx("div",{className:"absolute bottom-full right-0 mb-1 bg-popover text-popover-foreground rounded-md border shadow-md py-1 min-w-[180px] max-h-[240px] overflow-y-auto z-30",onClick:V=>V.stopPropagation(),children:Xe.map((V,se)=>{const Ce=Rs===V;return f.jsxs("button",{type:"button",onClick:()=>Gs(V),className:I("flex items-center gap-2 w-full px-3 py-1.5 text-xs text-left hover:bg-accent transition-colors",Ce&&"text-primary"),children:[V.thumbnail&&f.jsx("img",{src:V.thumbnail,alt:V.title,className:"w-10 h-6 object-cover rounded shrink-0"}),f.jsx("span",{className:"tabular-nums text-muted-foreground shrink-0 w-10",children:Dt(V.time)}),f.jsx("span",{className:"truncate",children:V.title})]},se)})})]}),f.jsxs("div",{className:"flex items-center gap-1 group/vol shrink-0",children:[f.jsx("button",{type:"button",onClick:Ue,className:"p-1 hover:bg-foreground/10 dark:hover:bg-white/10 rounded transition-colors","aria-label":H?we.videoPlayer_unmute:we.videoPlayer_mute,children:f.jsx(It,{className:"vp-icon h-5 w-5"})}),f.jsx("input",{type:"range",min:0,max:1,step:.01,value:H?0:K,onChange:V=>{G(Number(V.target.value)),q(!1)},className:"w-14 h-1 accent-primary cursor-pointer hidden sm:block","aria-label":we.videoPlayer_volume})]}),o&&!Ge&&f.jsxs("div",{className:"relative shrink-0",children:[f.jsxs("button",{type:"button",onClick:V=>{V.stopPropagation(),ue(se=>!se),Z(!1),Re(!1)},className:"px-1.5 py-0.5 text-xs hover:bg-foreground/10 dark:hover:bg-white/10 rounded transition-colors","aria-label":we.videoPlayer_playbackSpeed,children:[he,"x"]}),ie&&f.jsx("div",{className:"absolute bottom-full right-0 mb-1 bg-popover text-popover-foreground rounded-md border shadow-md py-1 min-w-[60px] z-30",onClick:V=>V.stopPropagation(),children:a.map(V=>f.jsxs("button",{type:"button",onClick:()=>Ye(V),className:I("block w-full px-3 py-1 text-xs text-left hover:bg-accent transition-colors",V===he&&"text-primary"),children:[V,"x"]},V))})]}),c&&c.length>0&&f.jsxs("div",{className:"relative shrink-0",children:[f.jsx("button",{type:"button",onClick:V=>{V.stopPropagation(),Z(se=>!se),ue(!1),Re(!1)},className:I("p-1 hover:bg-foreground/10 dark:hover:bg-white/10 rounded transition-colors",Ae>=0&&"text-primary"),"aria-label":we.videoPlayer_subtitles,children:f.jsx(W.Subtitles,{className:"vp-icon h-5 w-5"})}),re&&f.jsxs("div",{className:"absolute bottom-full right-0 mb-1 bg-popover text-popover-foreground rounded-md border shadow-md py-1 min-w-[120px] z-30",onClick:V=>V.stopPropagation(),children:[f.jsx("button",{type:"button",onClick:()=>nt(-1),className:I("block w-full px-3 py-1 text-xs text-left hover:bg-accent transition-colors",Ae===-1&&"text-primary"),children:we.videoPlayer_subtitlesOff}),c.map((V,se)=>f.jsx("button",{type:"button",onClick:()=>nt(se),className:I("block w-full px-3 py-1 text-xs text-left hover:bg-accent transition-colors",se===Ae&&"text-primary"),children:V.label},se))]})]}),n&&Ot&&f.jsx("button",{type:"button",onClick:xe,className:"p-1 hover:bg-foreground/10 dark:hover:bg-white/10 rounded transition-colors shrink-0 hidden sm:flex","aria-label":we.videoPlayer_pictureInPicture,children:f.jsx(W.PictureInPicture2,{className:"vp-icon h-5 w-5"})}),i&&f.jsx("button",{type:"button",onClick:Yt,className:"p-1 hover:bg-foreground/10 dark:hover:bg-white/10 rounded transition-colors shrink-0","aria-label":J?we.videoPlayer_exitFullscreen:we.videoPlayer_fullscreen,children:J?f.jsx(W.Minimize,{className:"vp-icon h-5 w-5"}):f.jsx(W.Maximize,{className:"vp-icon h-5 w-5"})})]})]}),f.jsx("style",{children:`
75
+ @keyframes vp-skip-fade {
76
+ 0% { opacity: 0; }
77
+ 30% { opacity: 1; }
78
+ 100% { opacity: 0; }
79
+ }
80
+ `})]})});$r.displayName="VideoPlayer";const Kh=E.forwardRef(({source:r="camera",videoConstraints:e,audioConstraints:t=!0,mimeType:s="video/webm",maxDuration:n,showTimer:i=!0,mirrored:o,onRecordingComplete:a,onRecordingStart:c,onError:l,className:d},u)=>{const[h,g]=E.useState("idle"),[m,p]=E.useState(0),[x,v]=E.useState(null),[y,b]=E.useState(null),[T,R]=E.useState(null),_=E.useRef(null),w=E.useRef(null),A=E.useRef([]),C=E.useRef(null),L=E.useRef(null),P=E.useRef(null),M=ye(),j=o!==void 0?o:r==="camera",D=E.useCallback(()=>{C.current&&(clearInterval(C.current),C.current=null),L.current&&(L.current.getTracks().forEach(G=>G.stop()),L.current=null,b(null)),P.current&&(URL.revokeObjectURL(P.current),P.current=null)},[]);E.useEffect(()=>D,[D]);const $=()=>{C.current=setInterval(()=>{p(G=>{const H=G+1;return n&&H>=n&&z(),H})},1e3)},N=()=>{C.current&&(clearInterval(C.current),C.current=null)},F=async()=>{R(null);try{let G;r==="screen"?G=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!!t}):G=await navigator.mediaDevices.getUserMedia({video:e||!0,audio:t}),G.getVideoTracks().forEach(H=>{H.addEventListener("ended",()=>{D(),g("idle")})}),b(G),L.current=G,g("preview"),_.current&&(_.current.srcObject=G)}catch(G){const H=G instanceof Error?G:new Error(String(G));H.name==="NotAllowedError"||H.name==="PermissionDeniedError"?R(M.videoRecorder_permissionDenied):R(M.videoRecorder_error),l==null||l(H)}};E.useEffect(()=>{_.current&&y&&(h==="preview"||h==="recording"||h==="paused")&&(_.current.srcObject=y)},[y,h]);const k=()=>{if(!y)return;A.current=[],p(0),x&&(URL.revokeObjectURL(x),v(null),P.current=null);const G=MediaRecorder.isTypeSupported(s)?s:"",H=new MediaRecorder(y,G?{mimeType:G}:void 0);H.ondataavailable=q=>{q.data.size>0&&A.current.push(q.data)},H.onstop=()=>{const q=new Blob(A.current,{type:G||"video/webm"}),J=URL.createObjectURL(q);v(J),P.current=J,a==null||a(q),y.getTracks().forEach(ee=>ee.stop()),b(null),L.current=null},H.onerror=()=>{R(M.videoRecorder_error),D(),g("idle")},w.current=H,H.start(100),g("recording"),$(),c==null||c()},z=()=>{w.current&&w.current.state!=="inactive"&&w.current.stop(),N(),g("stopped")},Y=()=>{w.current&&w.current.state==="recording"&&(w.current.pause(),N(),g("paused"))},U=()=>{w.current&&w.current.state==="paused"&&(w.current.resume(),$(),g("recording"))},K=()=>{D(),p(0),v(null),P.current=null,R(null),g("idle")};return f.jsxs("div",{ref:u,className:I("space-y-3 rounded-lg border bg-card text-card-foreground shadow-sm overflow-hidden",d),children:[T&&f.jsxs("div",{className:"flex items-center gap-2 p-4 text-sm text-destructive",children:[f.jsx(W.AlertCircle,{className:"h-4 w-4 shrink-0"}),f.jsx("span",{children:T}),f.jsx("button",{type:"button",onClick:K,className:"ml-auto text-muted-foreground hover:text-foreground transition-colors",children:f.jsx(W.RotateCcw,{className:"h-4 w-4"})})]}),!T&&h==="stopped"&&x?f.jsxs("div",{className:"space-y-3",children:[f.jsx($r,{src:x,aspectRatio:"16/9"}),f.jsx("div",{className:"px-4 pb-3",children:f.jsxs("button",{type:"button",onClick:K,className:"flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[f.jsx(W.RotateCcw,{className:"h-4 w-4"}),M.videoRecorder_reRecord]})})]}):!T&&h==="idle"?f.jsx("div",{className:"flex items-center justify-center gap-3 p-8",children:f.jsx("button",{type:"button",onClick:F,className:"flex items-center gap-2 px-4 py-2 rounded-lg bg-primary text-primary-foreground hover:bg-primary/90 active:scale-95 transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:r==="screen"?f.jsxs(f.Fragment,{children:[f.jsx(W.Monitor,{className:"h-4 w-4"}),f.jsx("span",{className:"text-sm",children:M.videoRecorder_shareScreen})]}):f.jsxs(f.Fragment,{children:[f.jsx(W.Camera,{className:"h-4 w-4"}),f.jsx("span",{className:"text-sm",children:M.videoRecorder_startCamera})]})})}):T?null:f.jsxs("div",{className:"relative",children:[f.jsx("video",{ref:_,autoPlay:!0,muted:!0,playsInline:!0,className:I("w-full",j&&"scale-x-[-1]"),style:{aspectRatio:"16/9"},"aria-label":r==="camera"?M.videoRecorder_cameraPreview:M.videoRecorder_screenPreview}),i&&(h==="recording"||h==="paused")&&f.jsxs("div",{className:"absolute top-3 left-3 flex items-center gap-2 px-2 py-1 rounded bg-background/60 dark:bg-black/60 text-foreground dark:text-white text-sm tabular-nums backdrop-blur-sm",children:[h==="recording"&&f.jsx("span",{className:"h-2 w-2 rounded-full bg-destructive animate-pulse"}),Dt(m)]}),f.jsxs("div",{className:"absolute bottom-3 left-1/2 -translate-x-1/2 flex items-center gap-3",children:[h==="preview"&&f.jsx("button",{type:"button",onClick:k,className:"h-12 w-12 rounded-full bg-destructive hover:bg-destructive/90 flex items-center justify-center transition-colors border-4 border-background/80 dark:border-white/80 active:scale-95 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":M.videoRecorder_startRecording,children:f.jsx(W.Circle,{className:"h-5 w-5 text-destructive-foreground fill-destructive-foreground"})}),h==="recording"&&f.jsxs(f.Fragment,{children:[f.jsx("button",{type:"button",onClick:Y,className:"p-2 rounded-full bg-background/50 dark:bg-black/50 hover:bg-background/70 dark:hover:bg-black/70 text-foreground dark:text-white transition-colors backdrop-blur-sm active:scale-95","aria-label":M.videoRecorder_pauseRecording,children:f.jsx(W.Pause,{className:"h-5 w-5"})}),f.jsx("button",{type:"button",onClick:z,className:"h-12 w-12 rounded-full bg-destructive hover:bg-destructive/90 flex items-center justify-center transition-colors border-4 border-background/80 dark:border-white/80 active:scale-95","aria-label":M.videoRecorder_stopRecording,children:f.jsx(W.Square,{className:"h-5 w-5 text-destructive-foreground fill-destructive-foreground"})})]}),h==="paused"&&f.jsxs(f.Fragment,{children:[f.jsx("button",{type:"button",onClick:U,className:"p-2 rounded-full bg-background/50 dark:bg-black/50 hover:bg-background/70 dark:hover:bg-black/70 text-foreground dark:text-white transition-colors backdrop-blur-sm active:scale-95","aria-label":M.videoRecorder_resumeRecording,children:f.jsx(W.Play,{className:"h-5 w-5"})}),f.jsx("button",{type:"button",onClick:z,className:"h-12 w-12 rounded-full bg-destructive hover:bg-destructive/90 flex items-center justify-center transition-colors border-4 border-background/80 dark:border-white/80 active:scale-95","aria-label":M.videoRecorder_stopRecording,children:f.jsx(W.Square,{className:"h-5 w-5 text-destructive-foreground fill-destructive-foreground"})})]})]}),n&&(h==="recording"||h==="paused")&&f.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-1 bg-foreground/20 dark:bg-white/20",children:f.jsx("div",{className:"h-full bg-destructive transition-[width] duration-1000",style:{width:`${Math.min(100,m/n*100)}%`}})})]})]})});Kh.displayName="VideoRecorder";const xa=E.forwardRef(({src:r,poster:e,title:t,duration:s,clickAction:n="inline",aspectRatio:i="16/9",showDuration:o=!0,showPlayButton:a=!0,onPlay:c,className:l,...d},u)=>{const[h,g]=E.useState(!1),[m,p]=E.useState(null),x=ye();E.useEffect(()=>{if(e||!r)return;const R=document.createElement("video");R.crossOrigin="anonymous",R.preload="metadata",R.muted=!0;const _=()=>{try{const A=document.createElement("canvas");A.width=R.videoWidth,A.height=R.videoHeight;const C=A.getContext("2d");C&&(C.drawImage(R,0,0),p(A.toDataURL("image/jpeg",.7)))}catch{}R.remove()};R.addEventListener("seeked",_,{once:!0});const w=()=>{R.currentTime=Math.min(1,R.duration*.1)};return R.addEventListener("loadedmetadata",w,{once:!0}),R.src=r,()=>{R.removeEventListener("seeked",_),R.removeEventListener("loadedmetadata",w),R.src="",R.remove()}},[r,e]);const v=()=>{n==="inline"?(g(!0),c==null||c()):n==="none"&&(c==null||c())},y=R=>{(R.key==="Enter"||R.key===" ")&&(R.preventDefault(),v())},b=e||m,T=t?bt(x.videoThumbnail_play,{title:t}):x.videoPlayer_play;return h&&n==="inline"?f.jsx("div",{ref:u,className:I("rounded-lg overflow-hidden bg-card dark:bg-black",l),style:{aspectRatio:i},...d,children:f.jsx($r,{src:r,autoPlay:!0,aspectRatio:i})}):f.jsxs("div",{ref:u,className:I("relative rounded-lg overflow-hidden bg-muted cursor-pointer group",l),style:{aspectRatio:i},onClick:v,onKeyDown:y,role:"button",tabIndex:0,"aria-label":T,...d,children:[b?f.jsx("img",{src:b,alt:t||"",className:"w-full h-full object-cover",draggable:!1}):f.jsx("div",{className:"w-full h-full bg-muted flex items-center justify-center",children:f.jsx(W.Play,{className:"h-8 w-8 text-muted-foreground"})}),a&&f.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:f.jsx("div",{className:"h-12 w-12 rounded-full bg-background/60 dark:bg-black/50 flex items-center justify-center backdrop-blur-sm group-hover:bg-background/80 dark:group-hover:bg-black/70 group-hover:scale-110 transition-all",children:f.jsx(W.Play,{className:"h-6 w-6 text-foreground dark:text-white ml-0.5"})})}),o&&s!==void 0&&f.jsx("span",{className:"absolute bottom-2 right-2 px-1.5 py-0.5 rounded bg-card/80 dark:bg-black/70 text-card-foreground dark:text-white text-xs tabular-nums backdrop-blur-sm",children:Dt(s)}),t&&f.jsx("div",{className:"absolute bottom-0 left-0 right-0 bg-gradient-to-t from-background/60 dark:from-black/60 to-transparent p-2 pt-6",children:f.jsx("p",{className:"text-foreground dark:text-white text-sm font-medium truncate",children:t})})]})});xa.displayName="VideoThumbnail";const zh=E.forwardRef(({videos:r,columns:e=3,gap:t=4,aspectRatio:s="16/9",clickAction:n="lightbox",onVideoSelect:i,className:o,...a},c)=>{const[l,d]=E.useState(null),[u,h]=E.useState(null),g=E.useRef(null),m=E.useRef(null),p=ye(),x=E.useCallback(()=>{if(typeof e=="number")return e;if(typeof window>"u")return e.sm??3;const L=window.innerWidth;return e.xl&&L>=1280?e.xl:e.lg&&L>=1024?e.lg:e.md&&L>=768?e.md:e.sm??3},[e]),[v,y]=E.useState(typeof e=="number"?e:3);E.useEffect(()=>{const L=()=>y(x());return L(),window.addEventListener("resize",L),()=>window.removeEventListener("resize",L)},[x]);const b=(L,P)=>{i==null||i(L,P),n==="lightbox"&&(g.current=document.activeElement instanceof HTMLElement?document.activeElement:null,d(P))},T=()=>{var L;d(null),(L=g.current)==null||L.focus()},R=E.useCallback(()=>{l!==null&&d(l>0?l-1:r.length-1)},[l,r.length]),_=E.useCallback(()=>{l!==null&&d(l<r.length-1?l+1:0)},[l,r.length]);E.useEffect(()=>{var M;if(l===null)return;const L=document.body.style.overflow;document.body.style.overflow="hidden",(M=m.current)==null||M.focus();const P=j=>{switch(j.key){case"Escape":j.preventDefault(),T();break;case"ArrowLeft":j.preventDefault(),R();break;case"ArrowRight":j.preventDefault(),_();break}if(j.key==="Tab"&&m.current){const D=m.current.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(D.length===0)return;const $=D[0],N=D[D.length-1];j.shiftKey?document.activeElement===$&&(j.preventDefault(),N.focus()):document.activeElement===N&&(j.preventDefault(),$.focus())}};return document.addEventListener("keydown",P),()=>{document.removeEventListener("keydown",P),document.body.style.overflow=L}},[l,R,_]);const w=L=>{h(L.touches[0].clientX)},A=L=>{var j;if(u===null)return;const P=u-L.changedTouches[0].clientX,M=Math.max(30,Math.min(80,(((j=m.current)==null?void 0:j.offsetWidth)??300)*.1));Math.abs(P)>M&&(P>0?_():R()),h(null)},C={gridTemplateColumns:`repeat(${v}, minmax(0, 1fr))`};return f.jsxs(f.Fragment,{children:[f.jsx("div",{ref:c,className:I("grid",o),style:{...C,gap:`${t*4}px`},role:"list","aria-label":p.videoGallery_label,...a,children:r.map((L,P)=>f.jsx(xa,{src:L.src,poster:L.poster,title:L.title,duration:L.duration,aspectRatio:s,clickAction:"none",onPlay:()=>b(L,P),role:"listitem"},L.id))}),n==="lightbox"&&l!==null&&r[l]&&lo.createPortal(f.jsxs("div",{ref:m,className:"fixed inset-0 z-50 flex items-center justify-center bg-background/95 dark:bg-black/95",onClick:L=>{L.target===L.currentTarget&&T()},onTouchStart:w,onTouchEnd:A,role:"dialog","aria-modal":"true","aria-label":p.videoGallery_label,tabIndex:-1,children:[f.jsx("button",{type:"button",onClick:T,className:"absolute top-4 right-4 z-10 p-2 rounded-full bg-foreground/10 hover:bg-foreground/20 text-foreground transition-colors","aria-label":p.common_close,children:f.jsx(W.X,{className:"h-5 w-5"})}),r.length>1&&f.jsxs(f.Fragment,{children:[f.jsx("button",{type:"button",onClick:R,className:"absolute left-4 top-1/2 -translate-y-1/2 z-10 p-2 rounded-full bg-foreground/10 hover:bg-foreground/20 text-foreground transition-colors","aria-label":p.common_previous,children:f.jsx(W.ChevronLeft,{className:"h-6 w-6"})}),f.jsx("button",{type:"button",onClick:_,className:"absolute right-4 top-1/2 -translate-y-1/2 z-10 p-2 rounded-full bg-foreground/10 hover:bg-foreground/20 text-foreground transition-colors","aria-label":p.common_next,children:f.jsx(W.ChevronRight,{className:"h-6 w-6"})})]}),f.jsxs("div",{className:"w-full max-w-4xl px-4",children:[f.jsx($r,{src:r[l].src,poster:r[l].poster,autoPlay:!0,aspectRatio:s},r[l].id),r[l].title&&f.jsx("p",{className:"text-foreground text-sm mt-3 text-center",children:r[l].title})]}),f.jsxs("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 text-muted-foreground text-sm tabular-nums",children:[l+1," / ",r.length]})]}),document.body)]})});zh.displayName="VideoGallery";const uT={contain:"object-contain",cover:"object-cover",fill:"object-fill",none:"object-none","scale-down":"object-scale-down"},Wh=E.forwardRef(({src:r,alt:e,fallbackSrc:t,placeholder:s,showSkeleton:n=!0,lazy:i=!0,rootMargin:o="200px",aspectRatio:a,zoomOnHover:c=!1,zoomScale:l=1.5,zoomOnClick:d=!1,fit:u="cover",className:h,style:g,onLoad:m,onError:p,...x},v)=>{const[y,b]=E.useState("loading"),[T,R]=E.useState(!i),[_,w]=E.useState(r),[A,C]=E.useState(!1),L=E.useRef(null),P=ye();E.useEffect(()=>{w(r),b("loading")},[r]),E.useEffect(()=>{if(!i||!L.current)return;const F=new IntersectionObserver(([k])=>{k.isIntersecting&&(R(!0),F.disconnect())},{rootMargin:o});return F.observe(L.current),()=>F.disconnect()},[i,o]);const M=F=>{b("loaded"),m==null||m(F)},j=F=>{t&&_!==t?w(t):b("error"),p==null||p(F)},D=()=>{d&&C(F=>!F)},$=F=>{d&&(F.key==="Enter"||F.key===" ")&&(F.preventDefault(),C(k=>!k))},N=a!==void 0?{aspectRatio:typeof a=="number"?`${a}`:a}:{};return f.jsxs("div",{ref:L,className:I("group relative overflow-hidden inline-block",d&&"cursor-zoom-in focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",h),style:{...N,...g},onClick:D,onKeyDown:$,tabIndex:d?0:void 0,role:d?"button":void 0,"aria-label":d?P.image_zoomIn:void 0,children:[T&&_?f.jsx("img",{ref:v,src:_,alt:e??"",className:I("w-full h-full transition-transform duration-300",uT[u],c&&"hover:scale-[var(--zoom-scale)]",A&&"scale-[var(--zoom-scale)]",y==="loading"&&"opacity-0"),style:{"--zoom-scale":l},onLoad:M,onError:j,...x}):null,y==="loading"&&T&&f.jsx("div",{className:"absolute inset-0",children:s||n&&f.jsx("div",{className:"w-full h-full animate-pulse bg-muted rounded-md"})}),y==="error"&&f.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2 bg-muted rounded-md",children:[f.jsx(W.ImageOff,{className:"h-6 w-6 text-muted-foreground"}),f.jsx("span",{className:"text-xs text-muted-foreground",children:P.image_failedToLoad})]}),d&&y==="loaded"&&!A&&f.jsx("div",{className:"absolute bottom-2 right-2 p-1.5 rounded-full bg-background/60 dark:bg-black/50 text-foreground dark:text-white opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none backdrop-blur-sm",children:f.jsx(W.ZoomIn,{className:"h-4 w-4"})})]})});Wh.displayName="NUIImage";function Yh({images:r,open:e,defaultIndex:t=0,onClose:s,onIndexChange:n,enableZoom:i=!0,enableKeyboard:o=!0,enableDownload:a=!1,showCounter:c=!0,showThumbnails:l=!1,className:d,children:u}){const[h,g]=E.useState(!1),[m,p]=E.useState(t),[x,v]=E.useState(!1),[y,b]=E.useState(!0),[T,R]=E.useState(null),_=E.useRef(null),w=E.useRef(null),A=ye(),C=e!==void 0?e:h,L=U=>{_.current=document.activeElement instanceof HTMLElement?document.activeElement:null,U!==void 0&&p(U),b(!0),g(!0)},P=()=>{var U;g(!1),v(!1),s==null||s(),(U=_.current)==null||U.focus()},M=E.useCallback(U=>{p(U),v(!1),b(!0),n==null||n(U)},[n]),j=E.useCallback(()=>{M(m>0?m-1:r.length-1)},[m,r.length,M]),D=E.useCallback(()=>{M(m<r.length-1?m+1:0)},[m,r.length,M]);E.useEffect(()=>{if(!C||!o)return;const U=K=>{switch(K.key){case"Escape":K.preventDefault(),P();break;case"ArrowLeft":K.preventDefault(),j();break;case"ArrowRight":K.preventDefault(),D();break}};return document.addEventListener("keydown",U),()=>document.removeEventListener("keydown",U)},[C,o,j,D]),E.useEffect(()=>{var G;if(!C)return;const U=document.body.style.overflow;document.body.style.overflow="hidden",(G=w.current)==null||G.focus();const K=H=>{if(H.key!=="Tab"||!w.current)return;const q=w.current.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(q.length===0)return;const J=q[0],ee=q[q.length-1];H.shiftKey?document.activeElement===J&&(H.preventDefault(),ee.focus()):document.activeElement===ee&&(H.preventDefault(),J.focus())};return document.addEventListener("keydown",K),()=>{document.body.style.overflow=U,document.removeEventListener("keydown",K)}},[C]);const $=U=>{U.target===w.current&&P()},N=U=>{R(U.touches[0].clientX)},F=U=>{var H;if(T===null)return;const K=T-U.changedTouches[0].clientX,G=Math.max(30,Math.min(80,(((H=w.current)==null?void 0:H.offsetWidth)??300)*.1));Math.abs(K)>G&&(K>0?D():j()),R(null)},k=()=>{i&&v(U=>!U)},z=()=>{const U=r[m];if(!U)return;const K=document.createElement("a");K.href=U.src,K.download=U.alt||"image",K.click()};if(!C)return u?f.jsx("div",{onClick:()=>L(t),className:"cursor-pointer",children:u}):null;const Y=r[m];return Y?lo.createPortal(f.jsxs("div",{ref:w,className:I("fixed inset-0 z-50 flex flex-col items-center justify-center bg-background/95 dark:bg-black/95",d),onClick:$,onTouchStart:N,onTouchEnd:F,role:"dialog","aria-modal":"true","aria-label":A.lightbox_label,tabIndex:-1,children:[f.jsxs("div",{className:"absolute top-4 left-0 right-0 z-10 flex items-center justify-between px-4",children:[c&&r.length>1&&f.jsx("div",{className:"text-muted-foreground text-sm tabular-nums","aria-live":"polite",children:bt(A.lightbox_imageOf,{current:String(m+1),total:String(r.length)})}),!c&&f.jsx("div",{}),f.jsxs("div",{className:"flex items-center gap-2",children:[a&&f.jsx("button",{type:"button",onClick:z,className:"p-2 rounded-full bg-foreground/10 hover:bg-foreground/20 text-foreground transition-colors","aria-label":A.lightbox_download,children:f.jsx(W.Download,{className:"h-5 w-5"})}),i&&f.jsx("button",{type:"button",onClick:()=>v(U=>!U),className:"p-2 rounded-full bg-foreground/10 hover:bg-foreground/20 text-foreground transition-colors","aria-label":x?A.lightbox_zoomOut:A.lightbox_zoomIn,children:x?f.jsx(W.ZoomOut,{className:"h-5 w-5"}):f.jsx(W.ZoomIn,{className:"h-5 w-5"})}),f.jsx("button",{type:"button",onClick:P,className:"p-2 rounded-full bg-foreground/10 hover:bg-foreground/20 text-foreground transition-colors","aria-label":A.common_close,children:f.jsx(W.X,{className:"h-5 w-5"})})]})]}),r.length>1&&f.jsxs(f.Fragment,{children:[f.jsx("button",{type:"button",onClick:j,className:"absolute left-4 top-1/2 -translate-y-1/2 z-10 p-2 rounded-full bg-foreground/10 hover:bg-foreground/20 text-foreground transition-colors","aria-label":A.common_previous,children:f.jsx(W.ChevronLeft,{className:"h-6 w-6"})}),f.jsx("button",{type:"button",onClick:D,className:"absolute right-4 top-1/2 -translate-y-1/2 z-10 p-2 rounded-full bg-foreground/10 hover:bg-foreground/20 text-foreground transition-colors","aria-label":A.common_next,children:f.jsx(W.ChevronRight,{className:"h-6 w-6"})})]}),f.jsxs("div",{className:I("flex-1 flex items-center justify-center w-full",x?"overflow-auto cursor-zoom-out":"cursor-zoom-in"),onDoubleClick:k,children:[y&&f.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:f.jsx(W.Loader2,{className:"h-8 w-8 text-primary animate-spin"})}),f.jsx("img",{src:Y.src,alt:Y.alt||"",className:I("transition-all duration-200 select-none",x?"max-w-none max-h-none":"max-h-[85vh] max-w-[90vw] object-contain",y&&"opacity-0"),style:x?{transform:"scale(2)"}:void 0,draggable:!1,onLoad:()=>b(!1)},Y.src)]}),(Y.title||Y.description)&&f.jsxs("div",{className:"absolute bottom-16 left-1/2 -translate-x-1/2 text-center text-foreground max-w-lg px-4",children:[Y.title&&f.jsx("p",{className:"text-sm font-medium",children:Y.title}),Y.description&&f.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Y.description})]}),l&&r.length>1&&f.jsx("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2 max-w-[90vw] overflow-x-auto px-4 py-2",children:r.map((U,K)=>f.jsx("button",{type:"button",onClick:()=>M(K),className:I("shrink-0 w-12 h-12 rounded overflow-hidden border-2 transition-all",K===m?"border-primary":"border-transparent opacity-60 hover:opacity-100"),children:f.jsx("img",{src:U.src,alt:"",className:"w-full h-full object-cover"})},K))})]}),document.body):null}Yh.displayName="Lightbox";const qh=E.forwardRef(({src:r,aspectRatio:e,minSize:t=50,maxSize:s,initialCrop:n,outputFormat:i="image/png",outputQuality:o=.92,onCropComplete:a,onCropChange:c,onError:l,showGrid:d=!0,circular:u=!1,className:h},g)=>{const m=E.useRef(null),p=E.useRef(null),[x,v]=E.useState(!1),[y,b]=E.useState({width:0,height:0}),[T,R]=E.useState(n||{x:.15,y:.15,width:.7,height:.7}),[_,w]=E.useState(null),[A,C]=E.useState(null),[L,P]=E.useState({x:0,y:0}),[M,j]=E.useState({x:0,y:0,width:0,height:0}),D=E.useRef(null),$=ye();E.useEffect(()=>{n&&R(n)},[n]);const N=()=>{p.current&&(b({width:p.current.naturalWidth,height:p.current.naturalHeight}),v(!0))},F=E.useCallback(G=>{let{x:H,y:q,width:J,height:ee}=G;const te=t/(y.width||1),de=t/(y.height||1);if(J=Math.max(te,J),ee=Math.max(de,ee),s&&(J=Math.min(s/(y.width||1),J),ee=Math.min(s/(y.height||1),ee)),J=Math.min(1,J),ee=Math.min(1,ee),e){const ie=(y.width||1)/(y.height||1),ue=e/ie;J/ee>ue?J=ee*ue:ee=J/ue}return H=Math.max(0,Math.min(1-J,H)),q=Math.max(0,Math.min(1-ee,q)),{x:H,y:q,width:J,height:ee}},[y,t,s,e]);E.useEffect(()=>{if(!_)return;const G=q=>{q.preventDefault();const J=m.current;if(!J)return;const ee=J.getBoundingClientRect(),te=(q.clientX-L.x)/ee.width,de=(q.clientY-L.y)/ee.height;let ie;if(_==="move")ie=F({...M,x:M.x+te,y:M.y+de});else{switch(ie={...M},A){case"se":ie.width=M.width+te,ie.height=M.height+de;break;case"sw":ie.x=M.x+te,ie.width=M.width-te,ie.height=M.height+de;break;case"ne":ie.y=M.y+de,ie.width=M.width+te,ie.height=M.height-de;break;case"nw":ie.x=M.x+te,ie.y=M.y+de,ie.width=M.width-te,ie.height=M.height-de;break;case"n":ie.y=M.y+de,ie.height=M.height-de;break;case"s":ie.height=M.height+de;break;case"w":ie.x=M.x+te,ie.width=M.width-te;break;case"e":ie.width=M.width+te;break}ie=F(ie)}R(ie),c==null||c(ie)},H=()=>{if(w(null),C(null),D.current){try{D.current.target.releasePointerCapture(D.current.pointerId)}catch{}D.current=null}};return document.addEventListener("pointermove",G),document.addEventListener("pointerup",H),()=>{document.removeEventListener("pointermove",G),document.removeEventListener("pointerup",H)}},[_,L,M,A,F,c]);const k=(G,H,q)=>{G.preventDefault(),G.stopPropagation();const J=G.currentTarget;try{J.setPointerCapture(G.pointerId),D.current={target:J,pointerId:G.pointerId}}catch{}w(H),C(q||null),P({x:G.clientX,y:G.clientY}),j({...T})},z=G=>{const H=G.shiftKey?.05:.01;let q={...T};if(G.shiftKey&&!G.altKey)switch(G.key){case"ArrowLeft":q.width-=H;break;case"ArrowRight":q.width+=H;break;case"ArrowUp":q.height-=H;break;case"ArrowDown":q.height+=H;break;default:return}else switch(G.key){case"ArrowLeft":q.x-=H;break;case"ArrowRight":q.x+=H;break;case"ArrowUp":q.y-=H;break;case"ArrowDown":q.y+=H;break;case"Enter":Y();return;default:return}G.preventDefault(),q=F(q),R(q),c==null||c(q)},Y=()=>{const G=p.current;if(!G||!a)return;const H=document.createElement("canvas"),q=T.x*G.naturalWidth,J=T.y*G.naturalHeight,ee=T.width*G.naturalWidth,te=T.height*G.naturalHeight;H.width=ee,H.height=te;const de=H.getContext("2d");if(!de)return;u&&(de.beginPath(),de.arc(ee/2,te/2,Math.min(ee,te)/2,0,Math.PI*2),de.closePath(),de.clip()),de.drawImage(G,q,J,ee,te,0,0,ee,te);const ie=H.toDataURL(i,o);H.toBlob(ue=>{ue?a(ue,ie):l==null||l(new Error($.imageCropper_cropFailed))},i,o)},U=()=>{const H=F(n||{x:.15,y:.15,width:.7,height:.7});R(H),c==null||c(H)},K=[{handle:"nw",pos:"top-0 left-0 -translate-x-1/2 -translate-y-1/2",cursor:"cursor-[nw-resize]"},{handle:"ne",pos:"top-0 right-0 translate-x-1/2 -translate-y-1/2",cursor:"cursor-[ne-resize]"},{handle:"sw",pos:"bottom-0 left-0 -translate-x-1/2 translate-y-1/2",cursor:"cursor-[sw-resize]"},{handle:"se",pos:"bottom-0 right-0 translate-x-1/2 translate-y-1/2",cursor:"cursor-[se-resize]"},{handle:"n",pos:"top-0 left-1/2 -translate-x-1/2 -translate-y-1/2",cursor:"cursor-[n-resize]"},{handle:"s",pos:"bottom-0 left-1/2 -translate-x-1/2 translate-y-1/2",cursor:"cursor-[s-resize]"},{handle:"w",pos:"top-1/2 left-0 -translate-x-1/2 -translate-y-1/2",cursor:"cursor-[w-resize]"},{handle:"e",pos:"top-1/2 right-0 translate-x-1/2 -translate-y-1/2",cursor:"cursor-[e-resize]"}];return f.jsxs("div",{ref:g,className:I("space-y-3",h),children:[f.jsxs("div",{ref:m,className:"relative overflow-hidden rounded-lg select-none",style:{touchAction:"none"},role:"application","aria-label":$.imageCropper_label,tabIndex:0,onKeyDown:z,children:[f.jsx("img",{ref:p,src:r,alt:"",className:"block w-full",onLoad:N,crossOrigin:"anonymous",draggable:!1}),x&&f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"absolute inset-0 bg-black/50 pointer-events-none"}),f.jsxs("div",{className:I("absolute border-2 border-white shadow-lg cursor-move",u&&"rounded-full"),style:{left:`${T.x*100}%`,top:`${T.y*100}%`,width:`${T.width*100}%`,height:`${T.height*100}%`},onPointerDown:G=>k(G,"move"),children:[f.jsx("div",{className:I("absolute inset-0 overflow-hidden",u&&"rounded-full"),children:f.jsx("img",{src:r,alt:"",className:"block max-w-none",crossOrigin:"anonymous",style:{position:"absolute",left:`-${T.x/T.width*100}%`,top:`-${T.y/T.height*100}%`,width:`${1/T.width*100}%`,height:`${1/T.height*100}%`},draggable:!1})}),d&&!u&&f.jsxs("div",{className:"absolute inset-0 pointer-events-none",children:[f.jsx("div",{className:"absolute left-1/3 top-0 bottom-0 w-px bg-white/40"}),f.jsx("div",{className:"absolute left-2/3 top-0 bottom-0 w-px bg-white/40"}),f.jsx("div",{className:"absolute top-1/3 left-0 right-0 h-px bg-white/40"}),f.jsx("div",{className:"absolute top-2/3 left-0 right-0 h-px bg-white/40"})]}),!u&&K.map(({handle:G,pos:H,cursor:q})=>f.jsx("div",{className:I("absolute w-3 h-3 bg-white rounded-full border border-border shadow z-10",H,q),onPointerDown:J=>k(J,"resize",G)},G))]})]})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("button",{type:"button",onClick:Y,className:"flex items-center gap-2 px-3 py-1.5 rounded-md bg-primary text-primary-foreground text-sm hover:bg-primary/90 transition-colors",children:[f.jsx(W.Crop,{className:"h-4 w-4"}),$.imageCropper_crop]}),f.jsxs("button",{type:"button",onClick:U,className:"flex items-center gap-2 px-3 py-1.5 rounded-md border text-sm hover:bg-accent transition-colors",children:[f.jsx(W.RotateCcw,{className:"h-4 w-4"}),$.imageCropper_reset]})]})]})});qh.displayName="ImageCropper";const Xh=E.forwardRef(({beforeSrc:r,afterSrc:e,beforeAlt:t="",afterAlt:s="",initialPosition:n=50,orientation:i="horizontal",showLabels:o=!0,beforeLabel:a,afterLabel:c,handleSize:l=4,onPositionChange:d,className:u,...h},g)=>{const[m,p]=E.useState(Math.max(0,Math.min(100,n))),[x,v]=E.useState(!1),y=E.useRef(null),[b,T]=E.useState({width:0,height:0}),R=E.useRef(null),_=ye(),w=i==="horizontal",A=a??_.imageCompare_before,C=c??_.imageCompare_after;E.useEffect(()=>{const D=y.current;if(!D)return;const $=new ResizeObserver(N=>{for(const F of N){const{width:k,height:z}=F.contentRect;T({width:k,height:z})}});return $.observe(D),T({width:D.offsetWidth,height:D.offsetHeight}),()=>$.disconnect()},[]);const L=E.useCallback((D,$)=>{const N=y.current;if(!N)return;const F=N.getBoundingClientRect();let k;w?k=(D-F.left)/F.width*100:k=($-F.top)/F.height*100,k=Math.max(0,Math.min(100,k)),p(k),d==null||d(k)},[w,d]);E.useEffect(()=>{if(!x)return;const D=F=>{F.preventDefault(),L(F.clientX,F.clientY)},$=()=>{if(R.current){const{element:F,pointerId:k}=R.current;F.releasePointerCapture(k),R.current=null}v(!1)},N=()=>{if(R.current){const{element:F,pointerId:k}=R.current;F.releasePointerCapture(k),R.current=null}v(!1)};return document.addEventListener("pointermove",D),document.addEventListener("pointerup",$),window.addEventListener("blur",N),()=>{document.removeEventListener("pointermove",D),document.removeEventListener("pointerup",$),window.removeEventListener("blur",N)}},[x,L]);const P=D=>{D.preventDefault();const $=D.currentTarget;$.setPointerCapture(D.pointerId),R.current={element:$,pointerId:D.pointerId},v(!0)},M=D=>{const $=D.shiftKey?10:1;let N=m;if(w&&D.key==="ArrowLeft"||!w&&D.key==="ArrowUp")N=Math.max(0,m-$);else if(w&&D.key==="ArrowRight"||!w&&D.key==="ArrowDown")N=Math.min(100,m+$);else return;D.preventDefault(),p(N),d==null||d(N)},j=()=>{const D=n;p(D),d==null||d(D)};return f.jsxs("div",{ref:D=>{y.current=D,typeof g=="function"?g(D):g&&(g.current=D)},className:I("relative select-none overflow-hidden rounded-lg",u),...h,children:[f.jsx("img",{src:e,alt:s,className:"block w-full h-full object-cover",draggable:!1}),f.jsx("div",{className:"absolute inset-0 overflow-hidden",style:w?{width:`${m}%`}:{height:`${m}%`},children:f.jsx("img",{src:r,alt:t,className:I("block object-cover",w?"h-full":"w-full"),style:w?{width:`${b.width}px`,maxWidth:"none",height:"100%"}:{height:`${b.height}px`,maxHeight:"none",width:"100%"},draggable:!1})}),f.jsxs("div",{className:I("absolute z-10",w?"top-0 bottom-0 cursor-[ew-resize]":"left-0 right-0 cursor-[ns-resize]"),style:w?{left:`${m}%`,width:l,transform:"translateX(-50%)"}:{top:`${m}%`,height:l,transform:"translateY(-50%)"},onPointerDown:P,onDoubleClick:j,onKeyDown:M,role:"slider","aria-label":_.imageCompare_slider,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(m),"aria-orientation":w?"horizontal":"vertical",tabIndex:0,children:[f.jsx("div",{className:I("bg-primary shadow-lg",w?"w-0.5 h-full mx-auto":"h-0.5 w-full my-auto")}),f.jsx("div",{className:I("absolute flex items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg","left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-8"),children:f.jsx(W.GripVertical,{className:I("h-4 w-4",!w&&"rotate-90")})})]}),o&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"absolute top-3 left-3 px-2 py-1 rounded bg-card/80 dark:bg-black/60 text-card-foreground dark:text-white text-xs font-medium pointer-events-none backdrop-blur-sm",children:A}),f.jsx("span",{className:"absolute top-3 right-3 px-2 py-1 rounded bg-card/80 dark:bg-black/60 text-card-foreground dark:text-white text-xs font-medium pointer-events-none backdrop-blur-sm",children:C})]})]})});Xh.displayName="ImageCompare";function fT({className:r}){const{setTheme:e}=Bn(),t=ye();return f.jsxs(Rd,{children:[f.jsx(Ad,{asChild:!0,children:f.jsxs(Ze,{variant:"outline",size:"icon",className:r,children:[f.jsx(W.Sun,{className:"h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),f.jsx(W.Moon,{className:"absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),f.jsx("span",{className:"sr-only",children:t.modeToggle_toggleTheme})]})}),f.jsxs(No,{align:"end",children:[f.jsxs(vr,{onClick:()=>e("light"),children:[f.jsx(W.Sun,{className:"mr-2 h-4 w-4"}),t.modeToggle_light]}),f.jsxs(vr,{onClick:()=>e("dark"),children:[f.jsx(W.Moon,{className:"mr-2 h-4 w-4"}),t.modeToggle_dark]}),f.jsxs(vr,{onClick:()=>e("system"),children:[f.jsx(W.Monitor,{className:"mr-2 h-4 w-4"}),t.modeToggle_system]})]})]})}const hT=[{value:"light",icon:W.Sun,key:"modeToggle_light"},{value:"dark",icon:W.Moon,key:"modeToggle_dark"},{value:"system",icon:W.Monitor,key:"modeToggle_system"}];function gT({className:r}){const{theme:e,setTheme:t,themes:s}=Bn(),n=ye();return f.jsx("div",{className:I("inline-flex items-center rounded-lg border border-border bg-muted/50 p-0.5 gap-0.5",r),role:"radiogroup","aria-label":n.modeToggle_colorTheme,children:hT.filter(i=>s.includes(i.value)).map(({value:i,icon:o,key:a})=>{const c=n[a];return f.jsxs("button",{role:"radio","aria-checked":e===i,"aria-label":c,onClick:()=>t(i),className:I("inline-flex items-center justify-center rounded-md px-2.5 py-1.5 text-sm font-medium transition-all","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e===i?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground hover:bg-background/50"),children:[f.jsx(o,{className:"h-4 w-4"}),f.jsx("span",{className:"sr-only",children:c})]},i)})})}const Qh=E.forwardRef(({className:r,variant:e="received",children:t,...s},n)=>f.jsx("div",{ref:n,className:I("group flex gap-2 max-w-[85%]",e==="sent"?"ml-auto flex-row-reverse":"mr-auto",r),"data-variant":e,...s,children:t}));Qh.displayName="ChatBubble";const Zh=E.forwardRef(({className:r,src:e,fallback:t,...s},n)=>f.jsx("div",{ref:n,className:I("flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-muted text-xs font-medium text-muted-foreground overflow-hidden",r),...s,children:e?f.jsx("img",{src:e,alt:t??"avatar",className:"h-full w-full object-cover"}):f.jsx("span",{children:t??"?"})}));Zh.displayName="ChatBubbleAvatar";const mT={sending:f.jsxs("svg",{className:"h-3 w-3 text-muted-foreground",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("circle",{cx:"12",cy:"12",r:"10"}),f.jsx("path",{d:"M12 6v6l4 2"})]}),sent:f.jsx("svg",{className:"h-3 w-3 text-muted-foreground",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:"M20 6 9 17l-5-5"})}),delivered:f.jsxs("svg",{className:"h-3 w-3 text-muted-foreground",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"M18 6 7 17l-5-5"}),f.jsx("path",{d:"m22 10-9.5 9.5-2-2"})]}),read:f.jsxs("svg",{className:"h-3 w-3 text-primary",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"M18 6 7 17l-5-5"}),f.jsx("path",{d:"m22 10-9.5 9.5-2-2"})]}),error:f.jsxs("svg",{className:"h-3 w-3 text-destructive",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("circle",{cx:"12",cy:"12",r:"10"}),f.jsx("path",{d:"m15 9-6 6"}),f.jsx("path",{d:"m9 9 6 6"})]})},Jh=E.forwardRef(({className:r,variant:e="received",isLoading:t,status:s,children:n,...i},o)=>f.jsx("div",{ref:o,className:I("rounded-2xl px-4 py-2.5 text-sm leading-relaxed",e==="sent"?"bg-primary text-primary-foreground rounded-br-md":"bg-muted text-foreground rounded-bl-md",r),...i,children:t?f.jsxs("div",{className:"flex items-center gap-1 py-1",children:[f.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-current animate-bounce [animation-delay:0ms]"}),f.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-current animate-bounce [animation-delay:150ms]"}),f.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-current animate-bounce [animation-delay:300ms]"})]}):f.jsxs(f.Fragment,{children:[n,s&&f.jsx("div",{className:"flex justify-end mt-1",children:mT[s]})]})}));Jh.displayName="ChatBubbleMessage";const eg=E.forwardRef(({className:r,...e},t)=>f.jsx("span",{ref:t,className:I("text-[10px] text-muted-foreground mt-1 px-1",r),...e}));eg.displayName="ChatBubbleTimestamp";const tg=E.forwardRef(({visibility:r="hover",className:e,children:t,...s},n)=>f.jsx("div",{ref:n,className:I("flex items-center gap-0.5 mt-0.5",r==="hover"&&"opacity-0 group-hover:opacity-100 transition-opacity",e),...s,children:t}));tg.displayName="ChatBubbleActions";const sg=E.forwardRef(({onSend:r,placeholder:e,disabled:t,isLoading:s,showAttach:n,onAttach:i,acceptFiles:o="*",onStop:a,value:c,onChange:l,headerSlot:d,footerSlot:u,maxLength:h,className:g},m)=>{const p=ye(),x=E.useRef(null),v=E.useRef(null),[y,b]=E.useState(""),T=c!==void 0,R=T?c:y,_=D=>{T?l==null||l(D):b(D)},w=()=>{const D=x.current;D&&(D.style.height="auto",D.style.height=Math.min(D.scrollHeight,160)+"px")},A=()=>{const D=R.trim();!D||t||s||(r==null||r(D),_(""),x.current&&(x.current.style.height="auto"))},C=D=>{D.key==="Enter"&&!D.shiftKey&&(D.preventDefault(),A())},L=()=>{var D;(D=v.current)==null||D.click()},P=D=>{D.target.files&&D.target.files.length>0&&(i==null||i(D.target.files)),D.target.value=""},M=R.length,j=h?M>h:!1;return f.jsxs("div",{ref:m,className:I("rounded-xl border border-border bg-background",g),children:[d&&f.jsx("div",{className:"px-3 pt-2 pb-1 border-b border-border/40",children:d}),f.jsxs("div",{className:"flex items-end gap-2 p-2",children:[n&&f.jsxs(f.Fragment,{children:[f.jsx("button",{type:"button",onClick:L,className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors","aria-label":p.chatInput_attachFile,disabled:t,children:f.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"})})}),f.jsx("input",{ref:v,type:"file",multiple:!0,accept:o,onChange:P,className:"hidden","aria-hidden":"true"})]}),f.jsx("textarea",{ref:x,value:R,onChange:D=>{_(D.target.value),w()},onKeyDown:C,placeholder:e??p.chatInput_placeholder,disabled:t||s,rows:1,className:"flex-1 resize-none bg-transparent text-sm outline-none placeholder:text-muted-foreground min-h-[36px] py-2 px-2 max-h-40"}),s&&a?f.jsx("button",{type:"button",onClick:a,className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-destructive/10 text-destructive hover:bg-destructive/20 transition-colors","aria-label":p.chatInput_stopGenerating,children:f.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:f.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"})})}):f.jsx("button",{type:"button",onClick:A,disabled:t||s||!R.trim()||j,className:I("flex h-9 w-9 shrink-0 items-center justify-center rounded-lg transition-colors",R.trim()&&!t&&!s&&!j?"bg-primary text-primary-foreground hover:bg-primary/90":"bg-muted text-muted-foreground cursor-not-allowed"),"aria-label":p.chatInput_sendMessage,children:s?f.jsx("svg",{className:"animate-spin",xmlns:"http://www.w3.org/2000/svg",width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:f.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}):f.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"m5 12 7-7 7 7"}),f.jsx("path",{d:"M12 19V5"})]})})]}),(u||h)&&f.jsxs("div",{className:"px-3 pb-2 pt-0.5 flex items-center gap-2",children:[f.jsx("div",{className:"flex-1",children:u}),h&&f.jsxs("span",{className:I("text-[10px] tabular-nums shrink-0",j?"text-destructive font-medium":"text-muted-foreground"),children:[M,"/",h]})]})]})});sg.displayName="ChatInput";const rg=E.forwardRef(({className:r,children:e,...t},s)=>f.jsx("div",{ref:s,className:I("flex flex-col h-full",r),...t,children:e}));rg.displayName="ChatContainer";const ng=E.forwardRef(({className:r,children:e,autoScroll:t=!0,...s},n)=>{const i=E.useRef(null),o=E.Children.count(e);return E.useEffect(()=>{t&&i.current&&i.current.scrollIntoView({behavior:"smooth"})},[o,t]),f.jsx(jn,{className:"flex-1",orientation:"vertical",children:f.jsxs("div",{ref:n,className:I("flex flex-col gap-4 p-4",r),...s,children:[e,f.jsx("div",{ref:i})]})})});ng.displayName="ChatList";const ig=E.forwardRef(({className:r,variant:e="dots",text:t,...s},n)=>{const i=ye(),o=t??i.aiLoading_thinking;return e==="text"?f.jsxs("div",{ref:n,className:I("flex items-center gap-1.5 text-sm text-muted-foreground",r),...s,children:[f.jsx("svg",{className:"animate-spin h-4 w-4",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:f.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),f.jsxs("span",{className:"animate-pulse",children:[o,"…"]})]}):f.jsxs("div",{ref:n,className:I("flex items-center gap-1",r),...s,children:[f.jsx("span",{className:"h-2 w-2 rounded-full bg-muted-foreground/60 animate-bounce [animation-delay:0ms]"}),f.jsx("span",{className:"h-2 w-2 rounded-full bg-muted-foreground/60 animate-bounce [animation-delay:150ms]"}),f.jsx("span",{className:"h-2 w-2 rounded-full bg-muted-foreground/60 animate-bounce [animation-delay:300ms]"})]})});ig.displayName="AILoading";function ks(r){const e=[],t=/(`[^`]+`)|(\~\~[^~]+\~\~)|(\*\*[^*]+\*\*)|(\*[^*]+\*)|(!\[[^\]]*\]\([^)]+\))|(\[[^\]]+\]\([^)]+\))/g;let s=0,n;for(;(n=t.exec(r))!==null;){n.index>s&&e.push(r.slice(s,n.index));const i=n[0];if(i.startsWith("`"))e.push(f.jsx("code",{className:"px-1 py-0.5 rounded bg-muted text-sm font-mono",children:i.slice(1,-1)},n.index));else if(i.startsWith("~~"))e.push(f.jsx("del",{className:"text-muted-foreground",children:i.slice(2,-2)},n.index));else if(i.startsWith("**"))e.push(f.jsx("strong",{children:i.slice(2,-2)},n.index));else if(i.startsWith("*"))e.push(f.jsx("em",{children:i.slice(1,-1)},n.index));else if(i.startsWith("![")){const o=i.indexOf("]"),a=i.slice(2,o),c=i.slice(o+2,-1);e.push(f.jsx("img",{src:c,alt:a,className:"max-w-full rounded-lg my-2 inline-block",loading:"lazy"},n.index))}else if(i.startsWith("[")){const o=i.indexOf("]"),a=i.slice(1,o),c=i.slice(o+2,-1);e.push(f.jsx("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"text-primary underline underline-offset-2 hover:text-primary/80",children:a},n.index))}s=n.index+i.length}return s<r.length&&e.push(r.slice(s)),e}function pT(r){const e=r.split(`
81
+ `),t=[];let s=0,n=0;for(;s<e.length;){const i=e[s];if(i.trimStart().startsWith("```")){const a=i.trimStart().slice(3).trim(),c=[];for(s++;s<e.length&&!e[s].trimStart().startsWith("```");)c.push(e[s]),s++;s++,t.push(f.jsx("pre",{className:"overflow-x-auto rounded-lg p-4 text-[13px] leading-relaxed font-mono my-3",style:{background:"var(--cb-bg, #1e1e2e)",color:"var(--cb-plain, #d4d4d4)"},children:f.jsx("code",{"data-language":a||void 0,children:c.join(`
82
+ `)})},n++));continue}const o=i.match(/^(#{1,6})\s+(.*)/);if(o){const a=o[1].length,c=o[2],l=`h${a}`,d={1:"text-2xl font-bold mt-6 mb-3",2:"text-xl font-semibold mt-5 mb-2",3:"text-lg font-semibold mt-4 mb-2",4:"text-base font-semibold mt-3 mb-1",5:"text-sm font-semibold mt-2 mb-1",6:"text-sm font-medium mt-2 mb-1"};t.push(f.jsx(l,{className:d[a],children:ks(c)},n++)),s++;continue}if(/^[\s]*[-*]\s/.test(i)){const a=[];for(;s<e.length&&/^[\s]*[-*]\s/.test(e[s]);)a.push(f.jsx("li",{children:ks(e[s].replace(/^[\s]*[-*]\s/,""))},n++)),s++;t.push(f.jsx("ul",{className:"list-disc pl-5 space-y-1 my-2 text-sm",children:a},n++));continue}if(/^\s*\d+\.\s/.test(i)){const a=[];for(;s<e.length&&/^\s*\d+\.\s/.test(e[s]);)a.push(f.jsx("li",{children:ks(e[s].replace(/^\s*\d+\.\s/,""))},n++)),s++;t.push(f.jsx("ol",{className:"list-decimal pl-5 space-y-1 my-2 text-sm",children:a},n++));continue}if(i.startsWith(">")){const a=[];for(;s<e.length&&e[s].startsWith(">");)a.push(e[s].replace(/^>\s?/,"")),s++;t.push(f.jsx("blockquote",{className:"border-l-4 border-primary/40 pl-4 italic text-muted-foreground my-3 text-sm",children:ks(a.join(" "))},n++));continue}if(i.includes("|")&&s+1<e.length&&/^\s*\|?[\s\-:|]+\|/.test(e[s+1])){const a=[];for(;s<e.length&&e[s].includes("|");)a.push(e[s]),s++;if(a.length>=2){const c=u=>u.split("|").map(h=>h.trim()).filter((h,g,m)=>g>0&&g<m.length),l=c(a[0]),d=a.slice(2).map(c);t.push(f.jsx("div",{className:"overflow-x-auto my-3",children:f.jsxs("table",{className:"w-full text-sm border-collapse",children:[f.jsx("thead",{children:f.jsx("tr",{className:"border-b border-border",children:l.map((u,h)=>f.jsx("th",{className:"px-3 py-2 text-left font-semibold text-foreground",children:ks(u)},h))})}),f.jsx("tbody",{children:d.map((u,h)=>f.jsx("tr",{className:"border-b border-border/50",children:u.map((g,m)=>f.jsx("td",{className:"px-3 py-2 text-muted-foreground",children:ks(g)},m))},h))})]})},n++));continue}}if(/^[-*_]{3,}\s*$/.test(i)){t.push(f.jsx("hr",{className:"my-4 border-border"},n++)),s++;continue}if(i.trim()===""){s++;continue}t.push(f.jsx("p",{className:"text-sm leading-relaxed my-2",children:ks(i)},n++)),s++}return t}const og=E.forwardRef(({content:r,streaming:e,className:t,...s},n)=>{const i=e?r:r.trim(),o=E.useMemo(()=>{try{return pT(i)}catch{return[E.createElement("p",{className:"text-sm"},i)]}},[i]);return f.jsx("div",{ref:n,className:I("markdown-renderer",t),...s,children:o})});og.displayName="MarkdownRenderer";const ag=E.forwardRef(({suggestions:r,onSelect:e,columns:t=2,className:s,...n},i)=>{const o={1:"grid-cols-1",2:"grid-cols-1 sm:grid-cols-2",3:"grid-cols-1 sm:grid-cols-2 lg:grid-cols-3",4:"grid-cols-1 sm:grid-cols-2 lg:grid-cols-4"};return f.jsx("div",{ref:i,className:I("grid gap-3",o[t],s),...n,children:r.map((a,c)=>f.jsxs("button",{type:"button",onClick:()=>e==null?void 0:e(a.prompt),className:I("flex flex-col items-start gap-1 rounded-xl border border-border p-4","bg-card text-left transition-colors hover:bg-muted/60 hover:border-primary/30","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"),children:[f.jsx("span",{className:"text-sm font-medium text-foreground",children:a.title}),a.description&&f.jsx("span",{className:"text-xs text-muted-foreground line-clamp-2",children:a.description})]},c))})});ag.displayName="PromptSuggestions";const lg=E.forwardRef(({models:r,value:e,onChange:t,placeholder:s,compact:n,className:i,...o},a)=>{const c=ye(),[l,d]=E.useState(!1),[u,h]=E.useState(""),g=E.useRef(null),m=E.useRef(null),p=r.find(y=>y.id===e),x=E.useMemo(()=>{if(!u)return r;const y=u.toLowerCase();return r.filter(b=>{var T;return b.name.toLowerCase().includes(y)||((T=b.provider)==null?void 0:T.toLowerCase().includes(y))||b.id.toLowerCase().includes(y)})},[r,u]);E.useEffect(()=>{l&&(h(""),setTimeout(()=>{var y;return(y=m.current)==null?void 0:y.focus()},0))},[l]),E.useEffect(()=>{if(!l)return;const y=b=>{g.current&&!g.current.contains(b.target)&&d(!1)};return document.addEventListener("mousedown",y),()=>document.removeEventListener("mousedown",y)},[l]);const v=y=>{y.key==="Escape"&&d(!1)};return f.jsxs("div",{ref:g,className:I("relative",i),...o,children:[f.jsxs("button",{ref:a,type:"button",onClick:()=>d(y=>!y),className:I("flex items-center gap-2 rounded-lg border border-border bg-background px-3 py-1.5 text-sm transition-colors hover:bg-muted","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",!p&&"text-muted-foreground"),children:[p?f.jsxs(f.Fragment,{children:[p.icon&&f.jsx("span",{className:"text-base shrink-0",children:p.icon}),f.jsx("span",{className:"font-medium truncate",children:p.name}),!n&&p.provider&&f.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",p.provider,")"]})]}):f.jsx("span",{children:s??c.modelSelector_placeholder}),f.jsx("svg",{className:I("h-3.5 w-3.5 ml-auto shrink-0 text-muted-foreground transition-transform",l&&"rotate-180"),xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:"m6 9 6 6 6-6"})})]}),l&&f.jsxs("div",{className:"absolute z-50 mt-1 w-full min-w-[260px] rounded-xl border border-border bg-popover shadow-lg animate-in fade-in-0 zoom-in-95",onKeyDown:v,children:[f.jsx("div",{className:"p-2 border-b border-border",children:f.jsx("input",{ref:m,value:u,onChange:y=>h(y.target.value),placeholder:c.modelSelector_searchPlaceholder,className:"w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground px-2 py-1"})}),f.jsxs("div",{className:"max-h-[280px] overflow-auto p-1",children:[x.length===0&&f.jsx("div",{className:"px-3 py-6 text-center text-sm text-muted-foreground",children:c.modelSelector_noResults}),x.map(y=>f.jsxs("button",{type:"button",disabled:y.disabled,onClick:()=>{t==null||t(y.id),d(!1)},className:I("flex w-full items-start gap-3 rounded-lg px-3 py-2.5 text-left text-sm transition-colors","hover:bg-muted focus-visible:outline-none focus-visible:bg-muted",y.id===e&&"bg-primary/10",y.disabled&&"opacity-50 cursor-not-allowed"),children:[y.icon&&f.jsx("span",{className:"text-lg shrink-0 mt-0.5",children:y.icon}),f.jsxs("div",{className:"flex-1 min-w-0",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("span",{className:"font-medium truncate",children:y.name}),y.id===e&&f.jsx("svg",{className:"h-4 w-4 text-primary shrink-0",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:"M20 6 9 17l-5-5"})})]}),y.provider&&f.jsx("span",{className:"text-xs text-muted-foreground",children:y.provider}),y.description&&f.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:y.description}),y.badges&&y.badges.length>0&&f.jsx("div",{className:"flex flex-wrap gap-1 mt-1.5",children:y.badges.map(b=>f.jsx("span",{className:"inline-flex items-center rounded-full border border-border px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground",children:b},b))})]})]},y.id))]})]})]})});lg.displayName="ModelSelector";const cg=E.forwardRef(({modes:r,value:e,onChange:t,size:s="default",className:n,...i},o)=>f.jsx("div",{ref:o,className:I("inline-flex items-center gap-1 rounded-lg bg-muted/50 p-1",n),role:"radiogroup",...i,children:r.map(a=>{const c=a.id===e;return f.jsxs("button",{type:"button",role:"radio","aria-checked":c,onClick:()=>t==null?void 0:t(a.id),title:a.description,className:I("rounded-md transition-all text-sm font-medium whitespace-nowrap","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",s==="sm"?"px-2.5 py-1 text-xs":"px-3 py-1.5",c?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[a.icon&&f.jsx("span",{className:"mr-1",children:a.icon}),a.label]},a.id)})}));cg.displayName="ChatModeSelector";const dg=E.forwardRef(({question:r,options:e,onSelect:t,selected:s,allowFreeText:n,onFreeTextSubmit:i,columns:o=1,className:a,...c},l)=>{const d=ye(),[u,h]=E.useState(""),g=!!s,m=()=>{const p=u.trim();p&&(i==null||i(p),h(""))};return f.jsxs("div",{ref:l,className:I("rounded-2xl bg-muted text-foreground rounded-bl-md px-4 py-3 max-w-[85%]",a),...c,children:[f.jsx("p",{className:"text-sm leading-relaxed mb-3",children:r}),f.jsx("div",{className:I("grid gap-2",o===2?"grid-cols-1 sm:grid-cols-2":"grid-cols-1"),children:e.map(p=>{const x=p.id===s;return f.jsxs("button",{type:"button",disabled:g,onClick:()=>t==null?void 0:t(p.id,p.label),className:I("flex items-center gap-2 rounded-xl border px-3 py-2 text-left text-sm transition-all","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",x?"border-primary bg-primary/10 text-primary font-medium":g?"border-border/50 text-muted-foreground opacity-50 cursor-default":"border-border bg-background hover:border-primary/40 hover:bg-primary/5 cursor-pointer"),children:[x&&f.jsx("svg",{className:"h-4 w-4 shrink-0 text-primary",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:"M20 6 9 17l-5-5"})}),!x&&f.jsx("span",{className:I("h-4 w-4 shrink-0 rounded-full border-2",g?"border-border/50":"border-border")}),f.jsxs("div",{className:"min-w-0",children:[f.jsx("span",{className:"block truncate",children:p.label}),p.description&&f.jsx("span",{className:"block text-xs text-muted-foreground mt-0.5 line-clamp-1",children:p.description})]})]},p.id)})}),n&&!g&&f.jsxs("div",{className:"flex gap-2 mt-2",children:[f.jsx("input",{type:"text",value:u,onChange:p=>h(p.target.value),onKeyDown:p=>{p.key==="Enter"&&m()},placeholder:d.followUp_freeTextPlaceholder,className:"flex-1 bg-background rounded-lg border border-border px-3 py-1.5 text-sm outline-none placeholder:text-muted-foreground focus:border-primary/40"}),f.jsx("button",{type:"button",onClick:m,disabled:!u.trim(),className:I("rounded-lg px-3 py-1.5 text-sm font-medium transition-colors",u.trim()?"bg-primary text-primary-foreground hover:bg-primary/90":"bg-muted text-muted-foreground cursor-not-allowed"),children:d.followUp_send})]})]})});dg.displayName="ChatFollowUp";const ug=E.forwardRef(({id:r,question:e,options:t,onSelect:s,selectedId:n,disabled:i=!1,allowFreeText:o=!1,onFreeTextSubmit:a,columns:c=1,freeTextValue:l,className:d,...u},h)=>{const[g,m]=E.useState(""),[p,x]=E.useState(null),[v,y]=E.useState(null),b=Array.isArray(t)?t:[],T=e??"",R=n??p,_=l??v,w=i||R!=null&&R!==""||_!=null&&_!=="",A=E.useCallback((L,P)=>{w||(x(L),s==null||s(L,P))},[w,s]),C=E.useCallback(()=>{const L=(g??"").trim();!L||w||(y(L),a==null||a(L),m(""))},[g,w,a]);return f.jsxs("div",{ref:h,"data-question-id":r,className:I("rounded-xl border border-border/60 overflow-hidden","bg-card shadow-sm","animate-in fade-in-0 slide-in-from-bottom-2 duration-300",d),...u,children:[f.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-3 border-b border-border/40 bg-muted/30",children:[f.jsx("div",{className:"flex-shrink-0 flex items-center justify-center w-7 h-7 rounded-lg bg-primary/15 text-primary",children:f.jsx(W.HelpCircle,{className:"w-4 h-4"})}),f.jsx("p",{className:"text-sm font-medium text-foreground leading-snug",children:T})]}),f.jsxs("div",{className:"p-3 space-y-3",children:[b.length>0&&f.jsx("div",{className:I("grid gap-2",c===2?"grid-cols-1 sm:grid-cols-2":"grid-cols-1"),children:b.map((L,P)=>{if(!L)return null;const M=L.id||`opt-${P}`,j=L.label||M,D=R===L.id;return f.jsxs("button",{type:"button",disabled:w,onClick:()=>A(L.id,j),className:I("group relative flex items-center gap-3 w-full p-3 rounded-lg border text-left","transition-all duration-200 ease-out","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1",D?"border-primary bg-primary/8 ring-1 ring-primary/20":w?"border-border/40 text-muted-foreground/60 cursor-not-allowed":"border-border/60 bg-background hover:border-primary/40 hover:bg-accent/50 cursor-pointer active:scale-[0.98]"),children:[f.jsx("div",{className:I("flex-shrink-0 flex items-center justify-center w-5 h-5 rounded-full border-2 transition-all duration-200",D?"border-primary bg-primary scale-110":w?"border-muted-foreground/30":"border-muted-foreground/40 group-hover:border-primary/60"),children:D&&f.jsx(W.Check,{className:"w-3 h-3 text-primary-foreground animate-in zoom-in-50 duration-200"})}),f.jsxs("div",{className:"flex-1 min-w-0",children:[f.jsx("span",{className:I("block text-sm font-medium leading-tight",D?"text-primary":"text-foreground"),children:j}),L.description&&f.jsx("span",{className:"block text-xs text-muted-foreground mt-0.5 line-clamp-2",children:L.description})]})]},M)})}),_&&f.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-primary/8 border border-primary/20",children:[f.jsx(W.Check,{className:"w-4 h-4 text-primary flex-shrink-0"}),f.jsx("span",{className:"text-sm font-medium text-primary truncate",children:_})]}),o&&!w&&f.jsxs("div",{className:"flex gap-2 pt-2 border-t border-border/30",children:[f.jsx("input",{type:"text",value:g,onChange:L=>m(L.target.value),onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),C())},placeholder:"Или напишите свой ответ...",className:I("flex-1 rounded-lg border border-border/60 bg-background px-3 py-2 text-sm","placeholder:text-muted-foreground/60","outline-none focus:border-primary/50 focus:ring-1 focus:ring-primary/20","transition-colors")}),f.jsx("button",{type:"button",onClick:C,disabled:!(g??"").trim(),className:I("flex-shrink-0 flex items-center justify-center w-9 h-9 rounded-lg transition-all duration-150",(g??"").trim()?"bg-primary text-primary-foreground hover:bg-primary/90 cursor-pointer active:scale-95":"bg-muted text-muted-foreground/50 cursor-not-allowed"),children:f.jsx(W.Send,{className:"w-4 h-4"})})]})]})]})});ug.displayName="ChatQuestion";const rc={success:{Icon:W.CheckCircle2,border:"border-emerald-500/30",bg:"bg-emerald-500/5",iconBox:"bg-emerald-500/15 text-emerald-600 dark:text-emerald-400",title:"text-emerald-900 dark:text-emerald-100",btn:"bg-emerald-600 hover:bg-emerald-700 text-white"},info:{Icon:W.Info,border:"border-blue-500/30",bg:"bg-blue-500/5",iconBox:"bg-blue-500/15 text-blue-600 dark:text-blue-400",title:"text-blue-900 dark:text-blue-100",btn:"bg-blue-600 hover:bg-blue-700 text-white"},warning:{Icon:W.AlertTriangle,border:"border-amber-500/30",bg:"bg-amber-500/5",iconBox:"bg-amber-500/15 text-amber-600 dark:text-amber-400",title:"text-amber-900 dark:text-amber-100",btn:"bg-amber-600 hover:bg-amber-700 text-white"},result:{Icon:W.Sparkles,border:"border-violet-500/30",bg:"bg-gradient-to-br from-violet-500/8 to-emerald-500/5",iconBox:"bg-violet-500/15 text-violet-600 dark:text-violet-400",title:"text-violet-900 dark:text-violet-100",btn:"bg-violet-600 hover:bg-violet-700 text-white"}},fg=E.forwardRef(({type:r="info",title:e,description:t,icon:s,action:n,dismissible:i=!1,onDismiss:o,className:a,...c},l)=>{const[d,u]=E.useState(!1),[h,g]=E.useState(!1),m=rc[r]??rc.info,p=s??m.Icon,x=E.useCallback(()=>{u(!0),o==null||o()},[o]),v=E.useCallback(()=>{h||!(n!=null&&n.onClick)||(g(!0),n.onClick(),setTimeout(()=>g(!1),1e3))},[n,h]);return d?null:f.jsx("div",{ref:l,className:I("rounded-xl border overflow-hidden shadow-sm","animate-in fade-in-0 slide-in-from-bottom-2 duration-300",m.border,m.bg,a),...c,children:f.jsxs("div",{className:"flex items-start gap-3 p-4",children:[f.jsx("div",{className:I("flex-shrink-0 flex items-center justify-center w-9 h-9 rounded-lg",m.iconBox),children:f.jsx(p,{className:"w-5 h-5"})}),f.jsxs("div",{className:"flex-1 min-w-0 pt-0.5",children:[e&&f.jsx("h4",{className:I("text-sm font-semibold leading-tight",m.title),children:e}),t&&f.jsx("p",{className:"text-sm text-muted-foreground mt-1 leading-relaxed",children:t})]}),n&&n.label&&f.jsxs("button",{type:"button",disabled:h,onClick:v,className:I("flex-shrink-0 inline-flex items-center gap-1.5 px-3.5 py-1.5 rounded-lg","text-sm font-medium whitespace-nowrap","transition-all duration-150","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","active:scale-95",h?"opacity-60 cursor-wait":"cursor-pointer",m.btn),children:[n.label,f.jsx(W.ArrowRight,{className:"w-3.5 h-3.5"})]}),i&&f.jsx("button",{type:"button",onClick:x,className:"flex-shrink-0 p-1 rounded-md hover:bg-foreground/10 text-muted-foreground hover:text-foreground transition-colors","aria-label":"Dismiss",children:f.jsx(W.X,{className:"w-4 h-4"})})]})})});fg.displayName="ChatActionCard";const nc={task:{Icon:W.CheckSquare,color:"text-blue-600 dark:text-blue-400 bg-blue-500/12"},project:{Icon:W.FolderKanban,color:"text-purple-600 dark:text-purple-400 bg-purple-500/12"},file:{Icon:W.FileText,color:"text-orange-600 dark:text-orange-400 bg-orange-500/12"},custom:{Icon:W.FileText,color:"text-primary bg-primary/12"}},hg=E.forwardRef(({type:r="task",title:e,id:t,status:s,properties:n,icon:i,onNavigate:o,className:a,...c},l)=>{const d=nc[r]??nc.custom,u=i??d.Icon,h=typeof o=="function",g=n&&typeof n=="object"?n:null,m=E.useCallback(()=>{o==null||o()},[o]),p=E.useCallback(x=>{h&&(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),o==null||o())},[h,o]);return f.jsxs("div",{ref:l,role:h?"button":void 0,tabIndex:h?0:void 0,onClick:h?m:void 0,onKeyDown:h?p:void 0,className:I("rounded-xl border border-border/60 bg-card overflow-hidden shadow-sm","animate-in fade-in-0 slide-in-from-bottom-2 duration-300",h&&"cursor-pointer hover:border-primary/40 hover:shadow-md transition-all active:scale-[0.99]",a),...c,children:[f.jsxs("div",{className:"flex items-start gap-3 p-4",children:[f.jsx("div",{className:I("flex-shrink-0 flex items-center justify-center w-9 h-9 rounded-lg",d.color),children:f.jsx(u,{className:"w-5 h-5"})}),f.jsxs("div",{className:"flex-1 min-w-0",children:[f.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[f.jsx("h4",{className:"text-sm font-semibold text-foreground truncate",children:e??"Untitled"}),t&&f.jsx("span",{className:"inline-flex px-1.5 py-0.5 rounded bg-muted text-[11px] font-mono text-muted-foreground leading-none",children:t})]}),s&&f.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:s})]}),h&&f.jsx(W.ExternalLink,{className:"flex-shrink-0 w-4 h-4 text-muted-foreground/50 mt-0.5"})]}),g&&Object.keys(g).length>0&&f.jsx("div",{className:"px-4 pb-4",children:f.jsx("div",{className:"rounded-lg bg-muted/40 divide-y divide-border/30",children:Object.entries(g).map(([x,v])=>f.jsxs("div",{className:"flex items-baseline justify-between gap-4 px-3 py-2 text-xs",children:[f.jsx("span",{className:"text-muted-foreground font-medium whitespace-nowrap",children:x}),f.jsx("span",{className:"text-foreground text-right break-words",children:String(v??"")})]},x))})})]})});hg.displayName="ChatEntityPreview";const gg=E.forwardRef(({title:r,description:e,icon:t,linkLabel:s,onNavigate:n,metadata:i,variant:o="success",className:a,...c},l)=>{const d=t??(o==="highlight"?W.Sparkles:W.CheckCircle2),u=i&&typeof i=="object"?i:null,h=typeof n=="function",g=o==="success";return f.jsx("div",{ref:l,className:I("rounded-xl border overflow-hidden shadow-sm","animate-in fade-in-0 slide-in-from-bottom-3 duration-300",g?"border-emerald-500/30 bg-gradient-to-br from-emerald-500/8 via-emerald-500/4 to-transparent":"border-violet-500/30 bg-gradient-to-br from-violet-500/8 via-violet-500/4 to-transparent",a),...c,children:f.jsxs("div",{className:"p-4 space-y-3",children:[f.jsxs("div",{className:"flex items-start gap-3",children:[f.jsx("div",{className:I("flex-shrink-0 flex items-center justify-center w-10 h-10 rounded-xl",g?"bg-emerald-500/15 text-emerald-600 dark:text-emerald-400":"bg-violet-500/15 text-violet-600 dark:text-violet-400"),children:f.jsx(d,{className:"w-5 h-5"})}),f.jsxs("div",{className:"flex-1 min-w-0 pt-0.5",children:[r&&f.jsx("h4",{className:I("text-sm font-semibold leading-tight",g?"text-emerald-900 dark:text-emerald-100":"text-violet-900 dark:text-violet-100"),children:r}),e&&f.jsx("p",{className:"text-sm text-muted-foreground mt-1 leading-relaxed",children:e})]}),h&&f.jsxs("button",{type:"button",onClick:n,className:I("flex-shrink-0 inline-flex items-center gap-1.5 px-4 py-2 rounded-lg","text-sm font-medium whitespace-nowrap","transition-all duration-150","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","active:scale-95 cursor-pointer",g?"bg-emerald-600 hover:bg-emerald-700 text-white":"bg-violet-600 hover:bg-violet-700 text-white"),children:[s??"Перейти",f.jsx(W.ArrowRight,{className:"w-4 h-4"})]})]}),u&&Object.keys(u).length>0&&f.jsx("div",{className:"rounded-lg bg-background/60 border border-border/30 divide-y divide-border/20",children:Object.entries(u).map(([m,p])=>f.jsxs("div",{className:"flex items-baseline justify-between gap-4 px-3 py-2 text-xs",children:[f.jsx("span",{className:"text-muted-foreground font-medium whitespace-nowrap",children:m}),f.jsx("span",{className:"text-foreground text-right break-words",children:String(p??"")})]},m))})]})})});gg.displayName="ChatResultCard";const xT={copy:{path:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2 M9 2h6a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1H9a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1z"},retry:{path:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8 M3 3v5h5"},edit:{path:"M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"},like:{path:"M7 10v12 M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2h0a3.13 3.13 0 0 1 3 3.88Z"},dislike:{path:"M17 14V2 M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22h0a3.13 3.13 0 0 1-3-3.88Z"},share:{path:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8 M16 6l-4-4-4 4 M12 2v13"}},mg=E.forwardRef(({actions:r=["copy"],content:e,likeState:t,onCopy:s,onRetry:n,onEdit:i,onLike:o,onDislike:a,onShare:c,visibility:l="hover",className:d,...u},h)=>{const g=ye(),[m,p]=E.useState(!1),x={copy:g.messageActions_copy,retry:g.messageActions_retry,edit:g.messageActions_edit,like:g.messageActions_like,dislike:g.messageActions_dislike,share:g.messageActions_share},y={copy:async()=>{if(e)try{await navigator.clipboard.writeText(e),p(!0),setTimeout(()=>p(!1),2e3)}catch{}s==null||s()},retry:n,edit:i,like:o,dislike:a,share:c};return f.jsx("div",{ref:h,className:I("flex items-center gap-0.5",l==="hover"&&"opacity-0 group-hover:opacity-100 transition-opacity",d),...u,children:r.map(b=>{const T=b==="copy"&&m,w=b==="like"&&t==="liked"||b==="dislike"&&t==="disliked";return f.jsx("button",{type:"button",onClick:y[b],"aria-label":x[b],title:T?g.messageActions_copied:x[b],className:I("inline-flex items-center justify-center h-7 w-7 rounded-md transition-colors","text-muted-foreground hover:text-foreground hover:bg-muted","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",w&&"text-primary",T&&"text-green-500"),children:T?f.jsx("svg",{className:"h-3.5 w-3.5",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:"M20 6 9 17l-5-5"})}):f.jsx("svg",{className:"h-3.5 w-3.5",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:w?"currentColor":"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:xT[b].path})})},b)})})});mg.displayName="MessageActions";const pg=E.forwardRef(({text:r,speed:e=2,onComplete:t,cursor:s=!0,immediate:n=!1,className:i,...o},a)=>{const[c,l]=E.useState(n?r:""),[d,u]=E.useState(n),h=E.useRef(r),g=E.useRef(),m=E.useRef(n?r.length:0);return E.useEffect(()=>{if(r!==h.current){if(h.current=r,n){l(r),u(!0),m.current=r.length;return}r.startsWith(c)||(m.current=0,l("")),u(!1)}},[r,n,c]),E.useEffect(()=>{if(n||d)return;const p=()=>{const x=Math.min(m.current+e,r.length);m.current=x,l(r.slice(0,x)),x>=r.length?(u(!0),t==null||t()):g.current=requestAnimationFrame(p)};return g.current=requestAnimationFrame(p),()=>{g.current&&cancelAnimationFrame(g.current)}},[r,e,n,d,t]),f.jsxs("span",{ref:a,className:I("whitespace-pre-wrap",i),...o,children:[c,s&&!d&&f.jsx("span",{className:"inline-block w-[2px] h-[1em] bg-foreground ml-px align-text-bottom animate-pulse"})]})});pg.displayName="StreamingText";const xg=E.forwardRef(({content:r,isThinking:e,duration:t,defaultOpen:s=!1,title:n,className:i,...o},a)=>{const c=ye(),[l,d]=E.useState(s||e===!0),[u,h]=E.useState(t??0),g=E.useRef(Date.now());E.useEffect(()=>{e&&d(!0)},[e]),E.useEffect(()=>{if(!e)return;g.current=Date.now();const x=setInterval(()=>{h(Math.floor((Date.now()-g.current)/1e3))},1e3);return()=>clearInterval(x)},[e]);const m=e?u:t??u,p=x=>x<60?`${x}s`:`${Math.floor(x/60)}m ${x%60}s`;return f.jsxs("div",{ref:a,className:I("rounded-xl border border-border/60 overflow-hidden my-2",e&&"border-primary/30",i),...o,children:[f.jsxs("button",{type:"button",onClick:()=>d(x=>!x),className:I("flex items-center gap-2 w-full px-3 py-2 text-sm transition-colors","hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",e&&"bg-primary/5"),children:[f.jsxs("svg",{className:I("h-4 w-4 shrink-0 text-muted-foreground",e&&"text-primary animate-pulse"),xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"}),f.jsx("path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"}),f.jsx("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),f.jsx("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),f.jsx("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),f.jsx("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),f.jsx("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),f.jsx("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),f.jsx("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]}),f.jsx("span",{className:I("font-medium",e&&"text-primary animate-pulse"),children:e?c.reasoning_thinking:n??c.reasoning_title}),m>0&&f.jsx("span",{className:"text-xs text-muted-foreground",children:e?`${p(m)}...`:bt(c.reasoning_thoughtFor,{duration:p(m)})}),f.jsx("svg",{className:I("h-3.5 w-3.5 ml-auto shrink-0 text-muted-foreground transition-transform duration-200",l&&"rotate-180"),xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:"m6 9 6 6 6-6"})})]}),l&&f.jsx("div",{className:"border-t border-border/40 px-4 py-3 bg-muted/20",children:f.jsx("div",{className:"border-l-2 border-primary/20 pl-3",children:f.jsxs("p",{className:"text-xs text-muted-foreground leading-relaxed whitespace-pre-wrap",children:[r,e&&f.jsx("span",{className:"inline-block w-[2px] h-[1em] bg-muted-foreground ml-px align-text-bottom animate-pulse"})]})})})]})});xg.displayName="ReasoningBlock";const vg=E.forwardRef(({name:r,args:e,result:t,status:s,error:n,defaultOpen:i=!1,className:o,...a},c)=>{const l=ye(),[d,u]=E.useState(i),h={running:f.jsx("svg",{className:"h-3.5 w-3.5 animate-spin text-primary",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:f.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}),success:f.jsx("svg",{className:"h-3.5 w-3.5 text-green-500",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:"M20 6 9 17l-5-5"})}),error:f.jsxs("svg",{className:"h-3.5 w-3.5 text-destructive",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"M18 6 6 18"}),f.jsx("path",{d:"m6 6 12 12"})]})},g={running:bt(l.toolCall_calling,{name:r}),success:r,error:bt(l.toolCall_failed,{name:r})};return f.jsxs("div",{ref:c,className:I("rounded-xl border overflow-hidden my-1",s==="error"?"border-destructive/30":"border-border/60",o),...a,children:[f.jsxs("button",{type:"button",onClick:()=>u(m=>!m),className:I("flex items-center gap-2 w-full px-3 py-2 text-sm transition-colors","hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:[f.jsx("svg",{className:"h-4 w-4 shrink-0 text-muted-foreground",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),h[s],f.jsx("span",{className:I("font-medium font-mono text-xs",s==="running"&&"text-primary",s==="error"&&"text-destructive"),children:g[s]}),f.jsx("svg",{className:I("h-3.5 w-3.5 ml-auto shrink-0 text-muted-foreground transition-transform duration-200",d&&"rotate-180"),xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:"m6 9 6 6 6-6"})})]}),d&&f.jsxs("div",{className:"border-t border-border/40 text-xs",children:[e&&Object.keys(e).length>0&&f.jsxs("div",{className:"px-3 py-2 bg-muted/20",children:[f.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground mb-1 font-semibold",children:l.toolCall_arguments}),f.jsx("pre",{className:"overflow-x-auto font-mono text-foreground/80 whitespace-pre-wrap",children:JSON.stringify(e,null,2)})]}),t&&f.jsxs("div",{className:I("px-3 py-2",e&&"border-t border-border/30"),children:[f.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground mb-1 font-semibold",children:l.toolCall_result}),f.jsx("pre",{className:"overflow-x-auto font-mono text-foreground/80 whitespace-pre-wrap",children:t})]}),n&&f.jsxs("div",{className:I("px-3 py-2 bg-destructive/5",e&&"border-t border-border/30"),children:[f.jsx("div",{className:"text-[10px] uppercase tracking-wider text-destructive mb-1 font-semibold",children:l.toolCall_error}),f.jsx("pre",{className:"overflow-x-auto font-mono text-destructive whitespace-pre-wrap",children:n})]})]})]})});vg.displayName="ChatToolCall";function vT(r,e){const t=new Date,s=new Date(t.getFullYear(),t.getMonth(),t.getDate()),n=new Date(s.getTime()-864e5),i=new Date(s.getTime()-7*864e5),o=[{label:e[0],items:[]},{label:e[1],items:[]},{label:e[2],items:[]},{label:e[3],items:[]}],a=[...r].sort((c,l)=>l.updatedAt.getTime()-c.updatedAt.getTime());for(const c of a){const l=c.updatedAt;l>=s?o[0].items.push(c):l>=n?o[1].items.push(c):l>=i?o[2].items.push(c):o[3].items.push(c)}return o.filter(c=>c.items.length>0)}const yg=E.forwardRef(({conversations:r,activeId:e,onSelect:t,onNew:s,onDelete:n,onRename:i,showSearch:o=!0,className:a,...c},l)=>{const d=ye(),[u,h]=E.useState(""),[g,m]=E.useState(null),[p,x]=E.useState(""),v=E.useRef(null),y=E.useMemo(()=>{if(!u)return r;const w=u.toLowerCase();return r.filter(A=>{var C;return A.title.toLowerCase().includes(w)||((C=A.lastMessage)==null?void 0:C.toLowerCase().includes(w))})},[r,u]),b=[d.conversationList_today,d.conversationList_yesterday,d.conversationList_previous7Days,d.conversationList_older],T=E.useMemo(()=>vT(y,b),[y,b]),R=w=>{m(w.id),x(w.title),setTimeout(()=>{var A;return(A=v.current)==null?void 0:A.focus()},0)},_=()=>{g&&p.trim()&&(i==null||i(g,p.trim())),m(null)};return f.jsxs("div",{ref:l,className:I("flex flex-col h-full",a),...c,children:[s&&f.jsx("div",{className:"p-3 border-b border-border shrink-0",children:f.jsxs("button",{type:"button",onClick:s,className:I("flex items-center justify-center gap-2 w-full rounded-lg border border-border px-3 py-2 text-sm font-medium","transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:[f.jsxs("svg",{className:"h-4 w-4",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"M5 12h14"}),f.jsx("path",{d:"M12 5v14"})]}),d.conversationList_newChat]})}),o&&f.jsx("div",{className:"px-3 pt-3 pb-2 shrink-0",children:f.jsxs("div",{className:"relative",children:[f.jsxs("svg",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("circle",{cx:"11",cy:"11",r:"8"}),f.jsx("path",{d:"m21 21-4.3-4.3"})]}),f.jsx("input",{value:u,onChange:w=>h(w.target.value),placeholder:d.conversationList_searchPlaceholder,className:"w-full bg-muted/50 rounded-lg pl-8 pr-3 py-1.5 text-sm outline-none placeholder:text-muted-foreground focus:bg-muted"})]})}),f.jsxs("div",{className:"flex-1 overflow-auto px-2 py-1",children:[T.length===0&&f.jsx("div",{className:"px-3 py-8 text-center text-sm text-muted-foreground",children:u?d.conversationList_noResults:d.conversationList_empty}),T.map(w=>f.jsxs("div",{className:"mb-3",children:[f.jsx("div",{className:"px-2 py-1.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:w.label}),w.items.map(A=>{const C=A.id===e,L=A.id===g;return f.jsxs("div",{className:I("group flex items-center gap-2 rounded-lg px-2 py-2 cursor-pointer transition-colors",C?"bg-primary/10":"hover:bg-muted"),onClick:()=>!L&&(t==null?void 0:t(A.id)),children:[f.jsx("svg",{className:"h-4 w-4 shrink-0 text-muted-foreground",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z"})}),f.jsx("div",{className:"flex-1 min-w-0",children:L?f.jsx("input",{ref:v,value:p,onChange:P=>x(P.target.value),onBlur:_,onKeyDown:P=>{P.key==="Enter"&&_(),P.key==="Escape"&&m(null)},className:"w-full bg-background border border-border rounded px-1 py-0.5 text-sm outline-none",onClick:P=>P.stopPropagation()}):f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"text-sm truncate font-medium",children:A.title}),A.lastMessage&&f.jsx("div",{className:"text-xs text-muted-foreground truncate",children:A.lastMessage})]})}),!L&&f.jsxs("div",{className:"flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity shrink-0",children:[i&&f.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),R(A)},className:"h-6 w-6 flex items-center justify-center rounded text-muted-foreground hover:text-foreground hover:bg-muted","aria-label":d.conversationList_rename,children:f.jsx("svg",{className:"h-3 w-3",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:"M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"})})}),n&&f.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),n(A.id)},className:"h-6 w-6 flex items-center justify-center rounded text-muted-foreground hover:text-destructive hover:bg-destructive/10","aria-label":d.conversationList_delete,children:f.jsxs("svg",{className:"h-3 w-3",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"M3 6h18"}),f.jsx("path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"}),f.jsx("path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"})]})})]})]},A.id)})]},w.label))]})]})});yg.displayName="ConversationList";const yT={online:"bg-green-500",offline:"bg-muted-foreground/40",typing:"bg-primary animate-pulse"},bg=E.forwardRef(({title:r,model:e,modelIcon:t,status:s,onClear:n,onSettings:i,onBack:o,children:a,className:c,...l},d)=>{const u=ye(),h={online:u.chatHeader_online,offline:u.chatHeader_offline,typing:u.chatHeader_typing};return f.jsxs("div",{ref:d,className:I("flex items-center gap-3 px-4 h-14 border-b border-border shrink-0 bg-background",c),...l,children:[o&&f.jsx("button",{type:"button",onClick:o,className:"h-8 w-8 flex items-center justify-center rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors -ml-1 shrink-0","aria-label":u.chatHeader_back,children:f.jsx("svg",{className:"h-4 w-4",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:"m15 18-6-6 6-6"})})}),t&&f.jsx("span",{className:"text-xl shrink-0",children:t}),f.jsxs("div",{className:"flex-1 min-w-0",children:[r&&f.jsx("div",{className:"text-sm font-semibold truncate",children:r}),f.jsxs("div",{className:"flex items-center gap-1.5",children:[e&&f.jsx("span",{className:"text-xs text-muted-foreground truncate",children:e}),s&&f.jsxs("span",{className:"flex items-center gap-1",children:[f.jsx("span",{className:I("h-1.5 w-1.5 rounded-full shrink-0",yT[s])}),f.jsx("span",{className:"text-[10px] text-muted-foreground",children:h[s]})]})]})]}),a,f.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[n&&f.jsx("button",{type:"button",onClick:n,className:"h-8 w-8 flex items-center justify-center rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors","aria-label":u.chatHeader_clearConversation,title:u.chatHeader_clearConversation,children:f.jsxs("svg",{className:"h-4 w-4",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"M3 6h18"}),f.jsx("path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"}),f.jsx("path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"})]})}),i&&f.jsx("button",{type:"button",onClick:i,className:"h-8 w-8 flex items-center justify-center rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors","aria-label":u.chatHeader_settings,title:u.chatHeader_settings,children:f.jsxs("svg",{className:"h-4 w-4",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),f.jsx("circle",{cx:"12",cy:"12",r:"3"})]})})]})]})});bg.displayName="ChatHeader";const va=E.forwardRef(({citation:r,className:e,...t},s)=>{const[n,i]=E.useState(!1);return f.jsxs("span",{className:"relative inline-block",children:[f.jsx("button",{ref:s,type:"button",onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),onFocus:()=>i(!0),onBlur:()=>i(!1),onClick:()=>window.open(r.url,"_blank","noopener"),className:I("inline-flex items-center justify-center h-4 min-w-[16px] px-1 rounded text-[10px] font-medium","bg-primary/15 text-primary hover:bg-primary/25 transition-colors cursor-pointer","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","align-super",e),"aria-label":`Source ${r.index}: ${r.title}`,...t,children:r.index}),n&&f.jsxs("div",{className:"absolute z-50 bottom-full left-1/2 -translate-x-1/2 mb-2 w-64 rounded-lg border border-border bg-popover shadow-lg p-3 text-left animate-in fade-in-0 zoom-in-95",children:[f.jsxs("div",{className:"flex items-start gap-2",children:[r.favicon&&f.jsx("img",{src:r.favicon,alt:"",className:"h-4 w-4 mt-0.5 shrink-0 rounded"}),f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:"text-sm font-medium text-foreground truncate",children:r.title}),f.jsx("div",{className:"text-[10px] text-muted-foreground truncate",children:r.url}),r.snippet&&f.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:r.snippet})]})]}),f.jsx("div",{className:"absolute top-full left-1/2 -translate-x-1/2 border-4 border-transparent border-t-border"})]})]})});va.displayName="CitationBadge";const Sg=E.forwardRef(({citations:r,variant:e="footer",className:t,...s},n)=>{const i=ye();return e==="inline"?f.jsx("span",{ref:n,className:I("inline",t),...s,children:r.map(o=>f.jsx(va,{citation:o},o.index))}):f.jsxs("div",{ref:n,className:I("border-t border-border/50 pt-3 mt-3 space-y-2",t),...s,children:[f.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-semibold mb-2",children:i.sourceCitation_sources}),r.map(o=>f.jsxs("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:I("flex items-start gap-2.5 rounded-lg border border-border/60 p-2.5 transition-colors","hover:bg-muted/50 hover:border-primary/30"),children:[f.jsx("span",{className:"flex items-center justify-center h-5 w-5 rounded bg-primary/15 text-primary text-[10px] font-semibold shrink-0 mt-0.5",children:o.index}),f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsxs("div",{className:"flex items-center gap-1.5",children:[o.favicon&&f.jsx("img",{src:o.favicon,alt:"",className:"h-3.5 w-3.5 rounded shrink-0"}),f.jsx("span",{className:"text-sm font-medium text-foreground truncate",children:o.title})]}),f.jsx("span",{className:"text-[10px] text-muted-foreground truncate block",children:o.url}),o.snippet&&f.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:o.snippet})]})]},o.index))]})});Sg.displayName="SourceCitation";function ic(r){return r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(1)} KB`:`${(r/(1024*1024)).toFixed(1)} MB`}function oc(r){return r.startsWith("image/")}function ac(r){return r.startsWith("image/")?"🖼️":r.startsWith("video/")?"🎬":r.startsWith("audio/")?"🎵":r.includes("pdf")?"📄":r.includes("zip")||r.includes("rar")||r.includes("tar")?"📦":r.includes("json")||r.includes("xml")||r.includes("csv")?"📊":r.includes("text")||r.includes("javascript")||r.includes("typescript")?"📝":"📎"}const Eg=E.forwardRef(({files:r,onRemove:e,variant:t="compact",className:s,...n},i)=>{const o=ye();return r.length===0?null:t==="grid"?f.jsx("div",{ref:i,className:I("grid grid-cols-2 gap-2",s),...n,children:r.map((a,c)=>f.jsxs("div",{className:"group relative rounded-xl border border-border overflow-hidden bg-muted/30",children:[oc(a.type)&&(a.thumbnail||a.url)?f.jsx("div",{className:"aspect-square",children:f.jsx("img",{src:a.thumbnail||a.url,alt:a.name,className:"h-full w-full object-cover"})}):f.jsx("div",{className:"aspect-square flex items-center justify-center text-3xl bg-muted/50",children:ac(a.type)}),f.jsxs("div",{className:"px-2 py-1.5 border-t border-border/40",children:[f.jsx("div",{className:"text-xs font-medium truncate",children:a.name}),f.jsx("div",{className:"text-[10px] text-muted-foreground",children:ic(a.size)})]}),e&&f.jsx("button",{type:"button",onClick:()=>e(c),className:"absolute top-1.5 right-1.5 h-5 w-5 rounded-full bg-background/80 backdrop-blur flex items-center justify-center text-muted-foreground hover:text-destructive transition-colors opacity-0 group-hover:opacity-100","aria-label":bt(o.filePreview_remove,{name:a.name}),children:f.jsxs("svg",{className:"h-3 w-3",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"M18 6 6 18"}),f.jsx("path",{d:"m6 6 12 12"})]})})]},a.id??c))}):f.jsx("div",{ref:i,className:I("flex gap-2 overflow-x-auto pb-1",s),...n,children:r.map((a,c)=>f.jsxs("div",{className:"group relative flex items-center gap-2 rounded-lg border border-border bg-muted/30 px-2.5 py-1.5 shrink-0 max-w-[200px]",children:[oc(a.type)&&(a.thumbnail||a.url)?f.jsx("img",{src:a.thumbnail||a.url,alt:a.name,className:"h-8 w-8 rounded object-cover shrink-0"}):f.jsx("span",{className:"text-lg shrink-0",children:ac(a.type)}),f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:"text-xs font-medium truncate",children:a.name}),f.jsx("div",{className:"text-[10px] text-muted-foreground",children:ic(a.size)})]}),e&&f.jsx("button",{type:"button",onClick:()=>e(c),className:"h-5 w-5 rounded-full flex items-center justify-center text-muted-foreground hover:text-destructive transition-colors shrink-0 opacity-0 group-hover:opacity-100","aria-label":bt(o.filePreview_remove,{name:a.name}),children:f.jsxs("svg",{className:"h-3 w-3",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"M18 6 6 18"}),f.jsx("path",{d:"m6 6 12 12"})]})})]},a.id??c))})});Eg.displayName="FilePreview";const bT={sending:f.jsxs("svg",{className:"h-3 w-3 text-muted-foreground",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("circle",{cx:"12",cy:"12",r:"10"}),f.jsx("path",{d:"M12 6v6l4 2"})]}),sent:f.jsx("svg",{className:"h-3 w-3 text-muted-foreground",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:"M20 6 9 17l-5-5"})}),delivered:f.jsxs("svg",{className:"h-3 w-3 text-muted-foreground",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"M18 6 7 17l-5-5"}),f.jsx("path",{d:"m22 10-9.5 9.5-2-2"})]}),read:f.jsxs("svg",{className:"h-3 w-3 text-primary",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"M18 6 7 17l-5-5"}),f.jsx("path",{d:"m22 10-9.5 9.5-2-2"})]}),error:f.jsxs("svg",{className:"h-3 w-3 text-destructive",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("circle",{cx:"12",cy:"12",r:"10"}),f.jsx("path",{d:"m15 9-6 6"}),f.jsx("path",{d:"m9 9 6 6"})]})},Tg=E.forwardRef(({variant:r="received",avatar:e,avatarFallback:t,content:s,timestamp:n,isLoading:i,status:o,actions:a,textContent:c,likeState:l,onCopy:d,onRetry:u,onEdit:h,onLike:g,onDislike:m,onShare:p,followUp:x,onFollowUpSelect:v,onFollowUpFreeText:y,reasoning:b,toolCalls:T,citations:R,className:_,...w},A)=>{const C=ye(),L=r==="sent",[P,M]=E.useState(!1),j=async()=>{if(c)try{await navigator.clipboard.writeText(c),M(!0),setTimeout(()=>M(!1),2e3)}catch{}d==null||d()};return f.jsxs("div",{ref:A,className:I("group flex gap-2 max-w-[85%]",L?"ml-auto flex-row-reverse":"mr-auto",_),...w,children:[(e||t)&&f.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-muted text-xs font-medium text-muted-foreground overflow-hidden",children:e?f.jsx("img",{src:e,alt:t??"avatar",className:"h-full w-full object-cover"}):f.jsx("span",{children:t??"?"})}),f.jsxs("div",{className:"flex flex-col gap-1 min-w-0",children:[b&&f.jsx("div",{className:I("rounded-xl border border-border/60 overflow-hidden",b.isThinking&&"border-primary/30"),children:f.jsx(ST,{...b})}),T==null?void 0:T.map((D,$)=>f.jsx(ET,{...D},$)),f.jsxs("div",{className:I("rounded-2xl px-4 py-2.5 text-sm leading-relaxed",L?"bg-primary text-primary-foreground rounded-br-md":"bg-muted text-foreground rounded-bl-md"),children:[i?f.jsxs("div",{className:"flex items-center gap-1 py-1",children:[f.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-current animate-bounce [animation-delay:0ms]"}),f.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-current animate-bounce [animation-delay:150ms]"}),f.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-current animate-bounce [animation-delay:300ms]"})]}):s,R&&R.length>0&&f.jsxs("div",{className:"border-t border-border/30 pt-2 mt-2 space-y-1.5",children:[f.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-semibold",children:C.sourceCitation_sources}),R.map(D=>f.jsxs("a",{href:D.url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors",children:[f.jsx("span",{className:"h-4 min-w-[16px] px-0.5 rounded bg-primary/15 text-primary text-[10px] font-semibold flex items-center justify-center",children:D.index}),f.jsx("span",{className:"truncate",children:D.title})]},D.index))]})]}),x&&f.jsxs("div",{className:"rounded-2xl bg-muted text-foreground rounded-bl-md px-4 py-3",children:[f.jsx("p",{className:"text-sm leading-relaxed mb-2.5",children:x.question}),f.jsx("div",{className:"grid gap-1.5",children:x.options.map(D=>{const $=D.id===x.selected,N=!!x.selected;return f.jsxs("button",{type:"button",disabled:N,onClick:()=>v==null?void 0:v(D.id,D.label),className:I("flex items-center gap-2 rounded-xl border px-3 py-2 text-left text-sm transition-all",$?"border-primary bg-primary/10 text-primary font-medium":N?"border-border/50 text-muted-foreground opacity-50 cursor-default":"border-border bg-background hover:border-primary/40 hover:bg-primary/5 cursor-pointer"),children:[$?f.jsx("svg",{className:"h-4 w-4 shrink-0 text-primary",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:"M20 6 9 17l-5-5"})}):f.jsx("span",{className:I("h-4 w-4 shrink-0 rounded-full border-2",N?"border-border/50":"border-border")}),f.jsx("span",{className:"truncate",children:D.label})]},D.id)})})]}),(n||o)&&f.jsxs("div",{className:I("flex items-center gap-1 px-1",L&&"flex-row-reverse"),children:[n&&f.jsx("span",{className:"text-[10px] text-muted-foreground",children:n}),o&&bT[o]]}),a&&a.length>0&&!i&&f.jsx("div",{className:"flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:a.map(D=>{const $=D==="copy"&&P,N={copy:j,retry:u,edit:h,like:g,dislike:m,share:p},F=D==="like"&&l==="liked"||D==="dislike"&&l==="disliked",k={copy:C.messageActions_copy,retry:C.messageActions_retry,edit:C.messageActions_edit,like:C.messageActions_like,dislike:C.messageActions_dislike,share:C.messageActions_share};return f.jsx("button",{type:"button",onClick:N[D],title:$?C.messageActions_copied:k[D],className:I("h-7 w-7 rounded-md flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",F&&"text-primary",$&&"text-green-500"),children:$?f.jsx("svg",{className:"h-3.5 w-3.5",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:"M20 6 9 17l-5-5"})}):D==="copy"?f.jsxs("svg",{className:"h-3.5 w-3.5",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),f.jsx("path",{d:"M9 2h6a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1H9a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1z"})]}):D==="retry"?f.jsxs("svg",{className:"h-3.5 w-3.5",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),f.jsx("path",{d:"M3 3v5h5"})]}):D==="like"?f.jsx("svg",{className:"h-3.5 w-3.5",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:F?"currentColor":"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:"M7 10v12 M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2h0a3.13 3.13 0 0 1 3 3.88Z"})}):D==="dislike"?f.jsx("svg",{className:"h-3.5 w-3.5",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:F?"currentColor":"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:"M17 14V2 M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22h0a3.13 3.13 0 0 1-3-3.88Z"})}):D==="edit"?f.jsx("svg",{className:"h-3.5 w-3.5",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:"M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"})}):f.jsxs("svg",{className:"h-3.5 w-3.5",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"}),f.jsx("path",{d:"M16 6l-4-4-4 4"}),f.jsx("path",{d:"M12 2v13"})]})},D)})})]})]})});Tg.displayName="ChatMessage";function ST({content:r,isThinking:e,duration:t}){const s=ye(),[n,i]=E.useState(e===!0),[o,a]=E.useState(t??0);E.useEffect(()=>{e&&i(!0)},[e]),E.useEffect(()=>{if(!e)return;const l=Date.now(),d=setInterval(()=>a(Math.floor((Date.now()-l)/1e3)),1e3);return()=>clearInterval(d)},[e]);const c=e?o:t??o;return f.jsxs(f.Fragment,{children:[f.jsxs("button",{type:"button",onClick:()=>i(l=>!l),className:"flex items-center gap-2 w-full px-3 py-2 text-sm hover:bg-muted/50",children:[f.jsxs("svg",{className:I("h-4 w-4 shrink-0 text-muted-foreground",e&&"text-primary animate-pulse"),xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"}),f.jsx("path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"})]}),f.jsx("span",{className:I("font-medium",e&&"text-primary animate-pulse"),children:e?s.reasoning_thinking:s.reasoning_title}),c>0&&f.jsx("span",{className:"text-xs text-muted-foreground",children:e?`${c}s...`:bt(s.reasoning_thoughtFor,{duration:`${c}s`})}),f.jsx("svg",{className:I("h-3.5 w-3.5 ml-auto text-muted-foreground transition-transform",n&&"rotate-180"),xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:"m6 9 6 6 6-6"})})]}),n&&f.jsx("div",{className:"border-t border-border/40 px-4 py-3 bg-muted/20",children:f.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed whitespace-pre-wrap border-l-2 border-primary/20 pl-3",children:r})})]})}function ET({name:r,args:e,result:t,status:s,error:n}){const i=ye(),[o,a]=E.useState(!1);return f.jsxs("div",{className:I("rounded-xl border overflow-hidden",s==="error"?"border-destructive/30":"border-border/60"),children:[f.jsxs("button",{type:"button",onClick:()=>a(c=>!c),className:"flex items-center gap-2 w-full px-3 py-2 text-sm hover:bg-muted/50",children:[f.jsx("svg",{className:"h-4 w-4 shrink-0 text-muted-foreground",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),s==="running"?f.jsx("svg",{className:"h-3.5 w-3.5 animate-spin text-primary",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:f.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}):s==="success"?f.jsx("svg",{className:"h-3.5 w-3.5 text-green-500",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:"M20 6 9 17l-5-5"})}):f.jsxs("svg",{className:"h-3.5 w-3.5 text-destructive",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"M18 6 6 18"}),f.jsx("path",{d:"m6 6 12 12"})]}),f.jsx("span",{className:"font-medium font-mono text-xs",children:s==="running"?bt(i.toolCall_calling,{name:r}):r}),f.jsx("svg",{className:I("h-3.5 w-3.5 ml-auto text-muted-foreground transition-transform",o&&"rotate-180"),xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:f.jsx("path",{d:"m6 9 6 6 6-6"})})]}),o&&f.jsxs("div",{className:"border-t border-border/40 text-xs",children:[e&&Object.keys(e).length>0&&f.jsxs("div",{className:"px-3 py-2 bg-muted/20",children:[f.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground mb-1 font-semibold",children:i.toolCall_arguments}),f.jsx("pre",{className:"overflow-x-auto font-mono whitespace-pre-wrap",children:JSON.stringify(e,null,2)})]}),t&&f.jsxs("div",{className:"px-3 py-2 border-t border-border/30",children:[f.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground mb-1 font-semibold",children:i.toolCall_result}),f.jsx("pre",{className:"overflow-x-auto font-mono whitespace-pre-wrap",children:t})]}),n&&f.jsxs("div",{className:"px-3 py-2 bg-destructive/5 border-t border-border/30",children:[f.jsx("div",{className:"text-[10px] uppercase tracking-wider text-destructive mb-1 font-semibold",children:i.toolCall_error}),f.jsx("pre",{className:"overflow-x-auto font-mono text-destructive whitespace-pre-wrap",children:n})]})]})]})}exports.AILoading=ig;exports.Accordion=ip;exports.AccordionContent=gd;exports.AccordionItem=fd;exports.AccordionTrigger=hd;exports.Alert=Gd;exports.AlertDescription=Hd;exports.AlertDialog=vp;exports.AlertDialogAction=Qd;exports.AlertDialogCancel=Zd;exports.AlertDialogContent=zd;exports.AlertDialogDescription=Xd;exports.AlertDialogFooter=Yd;exports.AlertDialogHeader=Wd;exports.AlertDialogOverlay=Fo;exports.AlertDialogPortal=Kd;exports.AlertDialogTitle=qd;exports.AlertDialogTrigger=yp;exports.AlertTitle=Vd;exports.AppShell=sf;exports.AspectRatio=tp;exports.AudioPlayer=Kn;exports.AudioPlaylist=ff;exports.AudioRecorder=uf;exports.AudioWaveform=Hn;exports.Avatar=_c;exports.AvatarFallback=Dc;exports.AvatarImage=kc;exports.Badge=ho;exports.Blockquote=Jx;exports.Box=Qc;exports.Breadcrumb=tu;exports.BreadcrumbEllipsis=au;exports.BreadcrumbItem=ru;exports.BreadcrumbLink=nu;exports.BreadcrumbList=su;exports.BreadcrumbPage=iu;exports.BreadcrumbSeparator=ou;exports.Button=Ze;exports.Calendar=xo;exports.Card=vo;exports.CardContent=So;exports.CardDescription=id;exports.CardFooter=od;exports.CardHeader=yo;exports.CardTitle=bo;exports.Carousel=Nu;exports.CarouselContent=Mu;exports.CarouselItem=Fu;exports.CarouselNext=ju;exports.CarouselPrevious=Ou;exports.ChartContainer=Xu;exports.ChartLegend=rv;exports.ChartTooltip=sv;exports.ChatActionCard=fg;exports.ChatBubble=Qh;exports.ChatBubbleActions=tg;exports.ChatBubbleAvatar=Zh;exports.ChatBubbleMessage=Jh;exports.ChatBubbleTimestamp=eg;exports.ChatContainer=rg;exports.ChatEntityPreview=hg;exports.ChatFollowUp=dg;exports.ChatHeader=bg;exports.ChatInput=sg;exports.ChatList=ng;exports.ChatMessage=Tg;exports.ChatModeSelector=cg;exports.ChatQuestion=ug;exports.ChatResultCard=gg;exports.ChatToolCall=vg;exports.Checkbox=Pc;exports.CitationBadge=va;exports.Code=Zx;exports.CodeBlock=qx;exports.Collapsible=sp;exports.CollapsibleContent=rd;exports.CollapsibleTrigger=rp;exports.ColorPicker=Jm;exports.Combobox=Wm;exports.Command=Mo;exports.CommandDialog=pp;exports.CommandEmpty=Od;exports.CommandGroup=jd;exports.CommandInput=Md;exports.CommandItem=$d;exports.CommandList=Fd;exports.CommandSeparator=Bd;exports.CommandShortcut=Ud;exports.Container=sd;exports.ContextMenu=n0;exports.ContextMenuCheckboxItem=wu;exports.ContextMenuContent=Eu;exports.ContextMenuGroup=o0;exports.ContextMenuItem=Tu;exports.ContextMenuLabel=Au;exports.ContextMenuPortal=a0;exports.ContextMenuRadioGroup=c0;exports.ContextMenuRadioItem=Ru;exports.ContextMenuSeparator=Iu;exports.ContextMenuShortcut=Lu;exports.ContextMenuSub=l0;exports.ContextMenuSubContent=Su;exports.ContextMenuSubTrigger=bu;exports.ContextMenuTrigger=i0;exports.ConversationList=yg;exports.CopyInput=af;exports.DataTable=Vx;exports.DataTableColumnHeader=Hx;exports.DatePicker=Vm;exports.Dialog=md;exports.DialogClose=ap;exports.DialogContent=Io;exports.DialogDescription=bd;exports.DialogFooter=vd;exports.DialogHeader=xd;exports.DialogOverlay=Ao;exports.DialogPortal=pd;exports.DialogTitle=yd;exports.DialogTrigger=op;exports.Drawer=Sd;exports.DrawerClose=Td;exports.DrawerContent=Co;exports.DrawerDescription=Po;exports.DrawerFooter=ko;exports.DrawerHeader=_o;exports.DrawerTitle=Do;exports.DrawerTrigger=Ed;exports.DropdownMenu=Rd;exports.DropdownMenuCheckboxItem=Cd;exports.DropdownMenuContent=No;exports.DropdownMenuGroup=cp;exports.DropdownMenuItem=vr;exports.DropdownMenuLabel=kd;exports.DropdownMenuPortal=dp;exports.DropdownMenuRadioGroup=fp;exports.DropdownMenuRadioItem=_d;exports.DropdownMenuSeparator=Dd;exports.DropdownMenuShortcut=Pd;exports.DropdownMenuSub=up;exports.DropdownMenuSubContent=Ld;exports.DropdownMenuSubTrigger=Id;exports.DropdownMenuTrigger=Ad;exports.EmptyState=e0;exports.FilePreview=Eg;exports.FileUpload=Xm;exports.Flex=Zc;exports.Grid=td;exports.HStack=ed;exports.Header=nf;exports.Heading=Xx;exports.HoverCard=d0;exports.HoverCardContent=Cu;exports.HoverCardTrigger=u0;exports.Image=Wh;exports.ImageCompare=Xh;exports.ImageCropper=qh;exports.Input=ws;exports.JsonViewer=lf;exports.Label=On;exports.Lead=ev;exports.Lightbox=Yh;exports.Main=of;exports.MarkdownRenderer=og;exports.MessageActions=mg;exports.MetricCard=nv;exports.ModeToggle=fT;exports.ModeToggleGroup=gT;exports.ModelSelector=lg;exports.MultiSelect=Ym;exports.Muted=tv;exports.NUIProvider=Xc;exports.NavigationMenu=gu;exports.NavigationMenuContent=vu;exports.NavigationMenuIndicator=yu;exports.NavigationMenuItem=s0;exports.NavigationMenuLink=r0;exports.NavigationMenuList=mu;exports.NavigationMenuTrigger=xu;exports.NavigationMenuViewport=Oo;exports.NumberInput=Km;exports.OTPInput=qm;exports.Pagination=lu;exports.PaginationContent=cu;exports.PaginationEllipsis=hu;exports.PaginationItem=du;exports.PaginationLink=$n;exports.PaginationNext=fu;exports.PaginationPrevious=uu;exports.Popover=ar;exports.PopoverContent=Bs;exports.PopoverTrigger=lr;exports.Progress=Jd;exports.PromptSuggestions=ag;exports.RadioGroup=$c;exports.RadioGroupItem=Uc;exports.ReasoningBlock=xg;exports.ScrollArea=jn;exports.ScrollBar=En;exports.Select=jm;exports.SelectContent=Fc;exports.SelectGroup=Bm;exports.SelectItem=jc;exports.SelectLabel=Oc;exports.SelectScrollDownButton=mo;exports.SelectScrollUpButton=go;exports.SelectSeparator=Bc;exports.SelectTrigger=Mc;exports.SelectValue=$m;exports.Separator=Cc;exports.Sheet=Sd;exports.SheetClose=Td;exports.SheetContent=Co;exports.SheetDescription=Po;exports.SheetFooter=ko;exports.SheetHeader=_o;exports.SheetOverlay=Lo;exports.SheetPortal=wd;exports.SheetTitle=Do;exports.SheetTrigger=Ed;exports.Sidebar=rf;exports.Skeleton=bp;exports.Slider=Gc;exports.SourceCitation=Sg;exports.StatusBadge=ov;exports.Stepper=t0;exports.StreamingText=pg;exports.Switch=Nc;exports.Table=Eo;exports.TableBody=wo;exports.TableCaption=ld;exports.TableCell=Sn;exports.TableFooter=ad;exports.TableHead=Ro;exports.TableHeader=To;exports.TableRow=xr;exports.Tabs=np;exports.TabsContent=ud;exports.TabsList=cd;exports.TabsTrigger=dd;exports.TagInput=zm;exports.Text=Qx;exports.Textarea=Ic;exports.ThemeProvider=Zp;exports.TimePicker=Hm;exports.Timeline=Qu;exports.TimelineConnector=ef;exports.TimelineContent=tf;exports.TimelineIcon=Ju;exports.TimelineItem=Zu;exports.Toaster=Jp;exports.Toggle=Vc;exports.ToggleGroup=Hc;exports.ToggleGroupItem=zc;exports.Tooltip=gp;exports.TooltipContent=Nd;exports.TooltipProvider=hp;exports.TooltipTrigger=mp;exports.TranslateProvider=Xc;exports.VStack=Jc;exports.VideoGallery=zh;exports.VideoPlayer=$r;exports.VideoRecorder=Kh;exports.VideoThumbnail=xa;exports.audioPlayerVariants=cf;exports.audioPlaylistVariants=Gi;exports.audioRecorderVariants=df;exports.badgeVariants=Lc;exports.buttonVariants=jr;exports.cardVariants=nd;exports.cn=I;exports.en=Ar;exports.formatTime=Dt;exports.headingVariants=Yu;exports.inputVariants=Ac;exports.navigationMenuTriggerStyle=pu;exports.ru=Wc;exports.textVariants=qu;exports.toast=Op;exports.toggleVariants=po;exports.tpl=bt;exports.useLocale=Gm;exports.useNUILocale=ye;exports.useTheme=Bn;exports.useTranslate=ye;exports.videoPlayerVariants=Hh;
38
83
  //# sourceMappingURL=index.cjs.js.map